app.ts

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