import type { Database } from "bun:sqlite"; import { join } from "node:path"; import { Hono } from "hono"; import { bodyLimit } from "hono/body-limit"; import { secureHeaders } from "hono/secure-headers"; import { isSafePath } from "../bucket/repo.ts"; import { registerFileRoutes } from "../pages/files.ts"; import { registerRepoPage } from "../pages/repo.ts"; import { registerSavePage } from "../pages/save.ts"; import { registerTarballRoutes } from "../tarball/archive.ts"; import type { Config } from "./config.ts"; const MAX_BODY_BYTES = 64 * 1024; const PUBLIC_DIR = join(import.meta.dir, "../../public"); // §18 allows Bunny Fonts: its stylesheet and the font files it points at. const FONTS = "https://fonts.bunny.net"; /** The Hono app with §25's headers and body cap, and every route built so far. */ export function createApp(config: Config, kepr: Database): Hono { const app = new Hono(); // §25 allows images from the presigned host, which is the bucket endpoint's origin. const imgSrc = config.bucket.kind === "s3" ? ["'self'", new URL(config.bucket.endpoint).origin] : ["'self'"]; app.use( secureHeaders({ contentSecurityPolicy: { defaultSrc: ["'self'"], scriptSrc: ["'self'"], styleSrc: ["'self'", FONTS], fontSrc: [FONTS], imgSrc, objectSrc: ["'none'"], baseUri: ["'none'"], formAction: ["'self'"], frameAncestors: ["'none'"], }, xFrameOptions: "DENY", }), ); app.use( bodyLimit({ maxSize: MAX_BODY_BYTES, onError: (c) => c.text("Request body too large", 413) }), ); app.get("/static/:path{.+}", async (c) => { const path = c.req.param("path"); const file = Bun.file(join(PUBLIC_DIR, path)); if (!isSafePath(path) || !(await file.exists())) return c.notFound(); c.header("Cache-Control", "public, max-age=3600"); return c.body(await file.bytes(), 200, { "Content-Type": file.type }); }); const ctx = { domain: config.domain, kepr, mirrorDir: join(config.dataDir, "mirror") }; registerRepoPage(app, ctx); registerFileRoutes(app, ctx); registerSavePage(app, ctx); registerTarballRoutes(app, ctx, join(config.dataDir, "tarballs")); return app; }