app.ts

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