app.ts

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