app.ts

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