app.ts

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