app.ts

7.2 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 { registerAccount } from "../admin/account.ts";7import { registerBackups } from "../admin/backups.ts";8import { registerBucket } from "../admin/bucket.ts";9import { registerStatus } from "../admin/console.ts";10import { registerDownloads } from "../admin/downloads.ts";11import { registerEmail } from "../admin/email.ts";12import { registerIssues } from "../admin/issues.ts";13import { registerNotifications } from "../admin/notifications.ts";14import { registerRepos } from "../admin/repos.ts";15import { registerSite } from "../admin/site.ts";16import { registerStorage } from "../admin/storage.ts";17import { registerRepoText } from "../admin/text.ts";18import { type Bucket, openBucket } from "../bucket/reader.ts";19import { isSafePath } from "../bucket/repo.ts";20import { registerIssuePages } from "../issues/pages.ts";21import { registerKohRemote } from "../mirror/remote.ts";22import { registerArchivesPage } from "../pages/archives.ts";23import { registerDocsPages } from "../pages/docs.ts";24import { registerFileRoutes } from "../pages/files.ts";25import { registerFrontPages } from "../pages/front.ts";26import { registerHousekeeping } from "../pages/housekeeping.ts";27import { registerKepr2Routes } from "../pages/kepr2.ts";28import { registerProfilePage } from "../pages/profile.ts";29import { registerReleasesPage } from "../pages/releases.ts";30import { registerRepoPage } from "../pages/repo.ts";31import { registerSavePage } from "../pages/save.ts";32import { registerReleaseRoutes } from "../releases/routes.ts";33import { registerTarballRoutes } from "../tarball/archive.ts";34import { CONFIG_FILE, type Config } from "./config.ts";35import { connectKeys, noCode, registerConnect } from "./connect.ts";36import { renamedTo } from "./db.ts";37import { registerLogin } from "./login.ts";3839const MAX_BODY_BYTES = 64 * 1024;40// §25's cap, except for the operator's picture and video uploads, which only a session reaches.41const MAX_MEDIA_BYTES = 64 * 1024 * 1024;42const MEDIA_UPLOAD = /^\/admin\/repos\/[^/]+\/media$/;43export const PUBLIC_DIR = join(import.meta.dir, "../../public");44// §18 allows Bunny Fonts: its stylesheet and the font files it points at.45const FONTS = "https://fonts.bunny.net";4647/** §25's headers: the CSP, with no inline scripts, and no framing. */48export function securityHeaders(imgSrc: (string | (() => string))[] = ["'self'"]) {49	return secureHeaders({50		contentSecurityPolicy: {51			defaultSrc: ["'self'"],52			scriptSrc: ["'self'"],53			styleSrc: ["'self'", FONTS],54			fontSrc: [FONTS],55			imgSrc,56			mediaSrc: imgSrc,57			objectSrc: ["'none'"],58			baseUri: ["'none'"],59			formAction: ["'self'"],60			frameAncestors: ["'none'"],61		},62		xFrameOptions: "DENY",63	});64}6566/**67 * The Hono app with §25's headers and body cap, and every route built so far. The console's Bucket68 * section changes `config.bucket` and `bucket` in place, so everything here reads them per request.69 */70export function createApp(71	config: Config,72	kepr: Database,73	bucket: Bucket = openBucket(config.bucket),74	configPath = CONFIG_FILE,75): Hono {76	const app = new Hono();77	// §25 allows images from the presigned host, which is the bucket endpoint's origin; uploaded78	// videos come from there too.79	const imgSrc = [80		"'self'",81		() => (config.bucket.kind === "s3" ? new URL(config.bucket.endpoint).origin : ""),82	];83	app.use("*", async (c, next) => {84		await next();85		const path = c.req.path;86		if (/^\/(admin(?:\/|$)|sign-in$|connect$)/.test(path))87			c.header("Referrer-Policy", "same-origin");88		if (/^\/[^/]+\/raw\/.+/.test(path) || path.startsWith("/static/assets/")) {89			const policy = c.res.headers.get("Content-Security-Policy");90			c.header("Content-Security-Policy", policy ? `${policy}; sandbox` : "sandbox");91		}92	});93	app.use(securityHeaders(imgSrc));94	// A renamed repo's old pages, which now 404, move to its new name (June, 2026-10-01). Koh's95	// routes keep their 404, so a machine follows the bucket's rename marker instead.96	app.use("*", async (c, next) => {97		await next();98		if (c.req.method !== "GET" || c.res.status !== 404) return;99		const [, first = "", second, ...rest] = c.req.path.split("/");100		const to = second !== "koh" && renamedTo(kepr, first);101		if (!to) return;102		const query = new URL(c.req.url).search;103		const path = ["", to, ...(second === undefined ? [] : [second, ...rest])].join("/");104		c.res = c.redirect(`${path}${query}`, 301);105	});106	const limit = (maxSize: number) =>107		bodyLimit({108			maxSize,109			onError: (c) =>110				// An oversized redemption is one more failed redemption — but only where the route111				// exists: without write keys it is an unknown path and answers as one.112				c.req.path === "/api/connect" && connectKeys(config)113					? noCode(c)114					: c.text("Request body too large", 413),115		});116	const [small, large] = [limit(MAX_BODY_BYTES), limit(MAX_MEDIA_BYTES)];117	app.use((c, next) => (MEDIA_UPLOAD.test(c.req.path) ? large : small)(c, next));118	// `/static/assets/` is the operator's uploads in `data/assets/` (§19), such as the signature.119	const assetsDir = join(config.dataDir, "assets");120	app.get("/static/:path{.+}", async (c, next) => {121		const path = c.req.param("path");122		if (!isSafePath(path)) return c.notFound();123		// A repo's uploads have their own route: as private as the repo (§20), and Range for video.124		if (path.startsWith("assets/media/")) return next();125		const file = Bun.file(126			path.startsWith("assets/") ? join(assetsDir, path.slice(7)) : join(PUBLIC_DIR, path),127		);128		if (!(await file.exists())) return c.notFound();129		c.header("Cache-Control", "public, max-age=3600");130		return c.body(await file.bytes(), 200, { "Content-Type": file.type });131	});132	const mirrorDir = join(config.dataDir, "mirror");133	// A getter, so a domain saved in the console reaches every page and check at once.134	const ctx = {135		get domain() {136			return config.domain;137		},138		kepr,139		mirrorDir,140	};141	// Before every other route, so the admin guard runs ahead of each `/admin` handler.142	registerLogin(app, ctx, config);143	registerConnect(app, config, ctx);144	// Not a spread of `ctx`, which would copy the domain once instead of keeping the getter.145	const admin = {146		get domain() {147			return config.domain;148		},149		kepr,150		mirrorDir,151		config,152		configPath,153		dataDir: config.dataDir,154		sync: { bucket, kepr, mirrorDir },155	};156	registerStatus(app, admin);157	registerRepos(app, admin);158	registerIssues(app, admin);159	registerDownloads(app, admin);160	registerStorage(app, admin);161	registerSite(app, admin);162	registerBucket(app, admin);163	registerNotifications(app, admin);164	registerEmail(app, admin);165	registerBackups(app, admin);166	registerAccount(app, admin);167	registerRepoText(app, admin);168	registerHousekeeping(app, ctx);169	registerFrontPages(app, ctx);170	registerDocsPages(app, ctx);171	registerProfilePage(app, ctx);172	registerKepr2Routes(app, ctx);173	registerRepoPage(app, ctx);174	registerFileRoutes(app, ctx);175	registerSavePage(app, ctx);176	registerKohRemote(app, ctx);177	registerArchivesPage(app, ctx);178	registerReleasesPage(app, ctx);179	registerIssuePages(app, ctx);180	registerTarballRoutes(app, ctx, bucket);181	registerReleaseRoutes(app, ctx, bucket);182	return app;183}