app.ts

2.3 KB · raw

1import type { Database } from "bun:sqlite";2import { join } from "node:path";3import { Hono } from "hono";4import { bodyLimit } from "hono/body-limit";5import { secureHeaders } from "hono/secure-headers";6import { isSafePath } from "../bucket/repo.ts";7import { registerArchivesPage } from "../pages/archives.ts";8import { registerFileRoutes } from "../pages/files.ts";9import { registerReleasesPage } from "../pages/releases.ts";10import { registerRepoPage } from "../pages/repo.ts";11import { registerSavePage } from "../pages/save.ts";12import { registerTarballRoutes } from "../tarball/archive.ts";13import type { Config } from "./config.ts";1415const MAX_BODY_BYTES = 64 * 1024;16const PUBLIC_DIR = join(import.meta.dir, "../../public");17// §18 allows Bunny Fonts: its stylesheet and the font files it points at.18const FONTS = "https://fonts.bunny.net";1920/** The Hono app with §25's headers and body cap, and every route built so far. */21export function createApp(config: Config, kepr: Database): Hono {22	const app = new Hono();23	// §25 allows images from the presigned host, which is the bucket endpoint's origin.24	const imgSrc =25		config.bucket.kind === "s3" ? ["'self'", new URL(config.bucket.endpoint).origin] : ["'self'"];26	app.use(27		secureHeaders({28			contentSecurityPolicy: {29				defaultSrc: ["'self'"],30				scriptSrc: ["'self'"],31				styleSrc: ["'self'", FONTS],32				fontSrc: [FONTS],33				imgSrc,34				objectSrc: ["'none'"],35				baseUri: ["'none'"],36				formAction: ["'self'"],37				frameAncestors: ["'none'"],38			},39			xFrameOptions: "DENY",40		}),41	);42	app.use(43		bodyLimit({ maxSize: MAX_BODY_BYTES, onError: (c) => c.text("Request body too large", 413) }),44	);45	app.get("/static/:path{.+}", async (c) => {46		const path = c.req.param("path");47		const file = Bun.file(join(PUBLIC_DIR, path));48		if (!isSafePath(path) || !(await file.exists())) return c.notFound();49		c.header("Cache-Control", "public, max-age=3600");50		return c.body(await file.bytes(), 200, { "Content-Type": file.type });51	});52	const ctx = { domain: config.domain, kepr, mirrorDir: join(config.dataDir, "mirror") };53	registerRepoPage(app, ctx);54	registerFileRoutes(app, ctx);55	registerSavePage(app, ctx);56	registerArchivesPage(app, ctx);57	registerReleasesPage(app, ctx);58	registerTarballRoutes(app, ctx, join(config.dataDir, "tarballs"));59	return app;60}