app.ts

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