app.ts

4.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 { registerStatus } from "../admin/console.ts";7import { registerIssues } from "../admin/issues.ts";8import { registerReleases } from "../admin/releases.ts";9import { registerRepos } from "../admin/repos.ts";10import { registerSite } from "../admin/site.ts";11import { openBucket } from "../bucket/reader.ts";12import { isSafePath } from "../bucket/repo.ts";13import { registerIssuePages } from "../issues/pages.ts";14import { registerKohRemote } from "../mirror/remote.ts";15import { registerArchivesPage } from "../pages/archives.ts";16import { registerDocsPages } from "../pages/docs.ts";17import { registerFileRoutes } from "../pages/files.ts";18import { registerFrontPages } from "../pages/front.ts";19import { registerHousekeeping } from "../pages/housekeeping.ts";20import { registerKepr2Routes } from "../pages/kepr2.ts";21import { registerProfilePage } from "../pages/profile.ts";22import { registerReleasesPage } from "../pages/releases.ts";23import { registerRepoPage } from "../pages/repo.ts";24import { registerSavePage } from "../pages/save.ts";25import { registerReleaseRoutes } from "../releases/routes.ts";26import { registerTarballRoutes } from "../tarball/archive.ts";27import type { Config } from "./config.ts";28import { connectKeys, noCode, registerConnect } from "./connect.ts";29import { registerLogin } from "./login.ts";3031const MAX_BODY_BYTES = 64 * 1024;32const PUBLIC_DIR = join(import.meta.dir, "../../public");33// §18 allows Bunny Fonts: its stylesheet and the font files it points at.34const FONTS = "https://fonts.bunny.net";3536/** The Hono app with §25's headers and body cap, and every route built so far. */37export function createApp(config: Config, kepr: Database): Hono {38	const app = new Hono();39	// §25 allows images from the presigned host, which is the bucket endpoint's origin.40	const imgSrc =41		config.bucket.kind === "s3" ? ["'self'", new URL(config.bucket.endpoint).origin] : ["'self'"];42	app.use("*", async (c, next) => {43		await next();44		const path = c.req.path;45		if (/^\/[^/]+\/raw\/.+/.test(path) || path.startsWith("/static/assets/")) {46			const policy = c.res.headers.get("Content-Security-Policy");47			c.header("Content-Security-Policy", policy ? `${policy}; sandbox` : "sandbox");48		}49	});50	app.use(51		secureHeaders({52			contentSecurityPolicy: {53				defaultSrc: ["'self'"],54				scriptSrc: ["'self'"],55				styleSrc: ["'self'", FONTS],56				fontSrc: [FONTS],57				imgSrc,58				objectSrc: ["'none'"],59				baseUri: ["'none'"],60				formAction: ["'self'"],61				frameAncestors: ["'none'"],62			},63			xFrameOptions: "DENY",64		}),65	);66	app.use(67		bodyLimit({68			maxSize: MAX_BODY_BYTES,69			onError: (c) =>70				// An oversized redemption is one more failed redemption — but only where the route71				// exists: without write keys it is an unknown path and answers as one.72				c.req.path === "/api/connect" && connectKeys(config)73					? noCode(c)74					: c.text("Request body too large", 413),75		}),76	);77	// `/static/assets/` is the operator's uploads in `data/assets/` (§19), such as the signature.78	const assetsDir = join(config.dataDir, "assets");79	app.get("/static/:path{.+}", async (c) => {80		const path = c.req.param("path");81		if (!isSafePath(path)) return c.notFound();82		const file = Bun.file(83			path.startsWith("assets/") ? join(assetsDir, path.slice(7)) : join(PUBLIC_DIR, path),84		);85		if (!(await file.exists())) return c.notFound();86		c.header("Cache-Control", "public, max-age=3600");87		return c.body(await file.bytes(), 200, { "Content-Type": file.type });88	});89	const ctx = { domain: config.domain, kepr, mirrorDir: join(config.dataDir, "mirror") };90	const bucket = openBucket(config.bucket);91	// Before every other route, so the admin guard runs ahead of each `/admin` handler.92	registerLogin(app, ctx, config.adminPasswordHash);93	registerConnect(app, config, ctx);94	const admin = {95		...ctx,96		canConnect: connectKeys(config) !== null,97		dataDir: config.dataDir,98		sync: { bucket, kepr, mirrorDir: ctx.mirrorDir, tarballDir: join(config.dataDir, "tarballs") },99	};100	registerStatus(app, admin);101	registerRepos(app, admin);102	registerIssues(app, admin);103	registerReleases(app, admin);104	registerSite(app, admin);105	registerHousekeeping(app, ctx);106	registerFrontPages(app, ctx);107	registerDocsPages(app, ctx);108	registerProfilePage(app, ctx);109	registerKepr2Routes(app, ctx);110	registerRepoPage(app, ctx);111	registerFileRoutes(app, ctx);112	registerSavePage(app, ctx);113	registerKohRemote(app, ctx);114	registerArchivesPage(app, ctx);115	registerReleasesPage(app, ctx);116	registerIssuePages(app, ctx);117	registerTarballRoutes(app, ctx, join(config.dataDir, "tarballs"));118	registerReleaseRoutes(app, ctx, bucket);119	return app;120}