app.ts

8.9 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 { localSyncer, type Syncer } from "../bucket/sync.ts";21import { registerIssuePages } from "../issues/pages.ts";22import { registerKohRemote } from "../mirror/remote.ts";23import { registerArchivesPage } from "../pages/archives.ts";24import { registerDocsPages } from "../pages/docs.ts";25import { registerFileRoutes } from "../pages/files.ts";26import { registerFrontPages } from "../pages/front.ts";27import { registerHousekeeping } from "../pages/housekeeping.ts";28import { registerKepr2Routes } from "../pages/kepr2.ts";29import { registerProfilePage } from "../pages/profile.ts";30import { registerReleasesPage } from "../pages/releases.ts";31import { registerRepoPage } from "../pages/repo.ts";32import { registerSavePage } from "../pages/save.ts";33import { registerReleaseRoutes } from "../releases/routes.ts";34import { registerTarballRoutes } from "../tarball/archive.ts";35import { CONFIG_FILE, type Config } from "./config.ts";36import { connectKeys, noCode, registerConnect } from "./connect.ts";37import { publicRepo, renamedTo, setting } from "./db.ts";38import { registerLogin } from "./login.ts";3940const MAX_BODY_BYTES = 64 * 1024;41// §25's cap, except for the operator's picture and video uploads, which only a session reaches,42// and an issue or reply with its attachments (§23: four files of up to 8 MB).43const MAX_MEDIA_BYTES = 64 * 1024 * 1024;44const MAX_ISSUE_BYTES = 34 * 1024 * 1024;45const MEDIA_UPLOAD = /^\/admin\/repos\/[^/]+\/media$/;46const ISSUE_POST = /^\/[^/]+\/issues\/(new|[0-9]{1,9})$/;47export const PUBLIC_DIR = join(import.meta.dir, "../../public");48// §18 allows Bunny Fonts: its stylesheet and the font files it points at.4950/** §25's headers: the CSP, with no inline scripts, and no framing. */51export function securityHeaders(52	imgSrc: (string | (() => string))[] = ["'self'"],53	scriptSrc: (string | (() => string))[] = ["'self'"],54) {55	return secureHeaders({56		contentSecurityPolicy: {57			defaultSrc: ["'self'"],58			scriptSrc,59			// Umami's script reports to the origin it loads from.60			connectSrc: scriptSrc,61			styleSrc: ["'self'"],62			fontSrc: ["'self'"],63			imgSrc,64			mediaSrc: imgSrc,65			objectSrc: ["'none'"],66			baseUri: ["'none'"],67			formAction: ["'self'"],68			frameAncestors: ["'none'"],69		},70		xFrameOptions: "DENY",71	});72}7374/**75 * The Hono app with §25's headers and body cap, and every route built so far. The console's Bucket76 * section changes `config.bucket` and `bucket` in place, so everything here reads them per request.77 */78export function createApp(79	config: Config,80	kepr: Database,81	bucket: Bucket = openBucket(config.bucket),82	configPath = CONFIG_FILE,83	syncer?: Syncer,84): Hono {85	const app = new Hono();86	// §25 allows images from the presigned host, which is the bucket endpoint's origin; uploaded87	// videos come from there too. `blob:` is an issue attachment's preview, made by the page itself.88	const imgSrc = [89		"'self'",90		() => (config.bucket.kind === "s3" ? new URL(config.bucket.endpoint).origin : ""),91		"blob:",92	];93	app.use("*", async (c, next) => {94		await next();95		const path = c.req.path;96		if (c.res.headers.get("Content-Type")?.startsWith("text/html")) {97			c.header("Speculation-Rules", '"/speculation.json"');98		}99		if (/^\/(admin(?:\/|$)|sign-in$|connect$)/.test(path))100			c.header("Referrer-Policy", "same-origin");101		if (102			/^\/[^/]+\/(raw|issues\/[0-9]+\/files)\/.+/.test(path) ||103			path.startsWith("/static/assets/")104		) {105			const policy = c.res.headers.get("Content-Security-Policy");106			c.header("Content-Security-Policy", policy ? `${policy}; sandbox` : "sandbox");107		}108	});109	// The operator's Umami script, when set (June, 2026-10-04).110	const scriptSrc = [111		"'self'",112		() => {113			const src = setting(kepr, "umami_src");114			return src ? new URL(src).origin : "";115		},116	];117	app.use(securityHeaders(imgSrc, scriptSrc));118	// A renamed repo's old pages, which now 404, move to its new name (June, 2026-10-01). Koh's119	// routes keep their 404, so a machine follows the bucket's rename marker instead.120	app.use("*", async (c, next) => {121		await next();122		if (c.req.method !== "GET" || c.res.status !== 404) return;123		const [, first = "", second, ...rest] = c.req.path.split("/");124		const to = second !== "koh" && renamedTo(kepr, first);125		if (!to || !publicRepo(kepr, to)) return;126		const query = new URL(c.req.url).search;127		const path = ["", to, ...(second === undefined ? [] : [second, ...rest])].join("/");128		c.res = c.redirect(`${path}${query}`, 301);129	});130	const limit = (maxSize: number) =>131		bodyLimit({132			maxSize,133			onError: (c) =>134				// An oversized redemption is one more failed redemption — but only where the route135				// exists: on a folder bucket it is an unknown path and answers as one.136				c.req.path === "/api/connect" && connectKeys(config)137					? noCode(c)138					: c.text("Request body too large", 413),139		});140	const [small, issue, large] = [MAX_BODY_BYTES, MAX_ISSUE_BYTES, MAX_MEDIA_BYTES].map(limit);141	app.use((c, next) => {142		const path = c.req.path;143		return (MEDIA_UPLOAD.test(path) ? large : ISSUE_POST.test(path) ? issue : small)(c, next);144	});145	// `/static/assets/` is the operator's uploads in `data/assets/` (§19), such as the signature.146	const assetsDir = join(config.dataDir, "assets");147	app.get("/static/:path{.+}", async (c, next) => {148		const path = c.req.param("path");149		if (!isSafePath(path)) return c.notFound();150		// A repo's uploads have their own route: as private as the repo (§20), and Range for video.151		if (path.startsWith("assets/media/")) return next();152		const file = Bun.file(153			path.startsWith("assets/") ? join(assetsDir, path.slice(7)) : join(PUBLIC_DIR, path),154		);155		if (!(await file.exists())) return c.notFound();156		// Size and mtime are a strong validator; the path keeps two files with the same stamp apart.157		const stamp = `${file.size.toString(16)}-${file.lastModified.toString(36)}`;158		const etag = `"${Bun.hash(path).toString(16)}-${stamp}"`;159		// A versioned URL names one build's file, and a font file never changes under its name, so160		// neither needs asking again.161		const versioned = c.req.query("v") !== undefined || path.startsWith("fonts/");162		c.header(163			"Cache-Control",164			versioned ? "public, max-age=31536000, immutable" : "public, max-age=3600",165		);166		c.header("ETag", etag);167		const asked = c.req.header("If-None-Match");168		// Matching first answers without reading the file, which is the whole point of the tag.169		if (asked?.split(",").some((it) => it.trim() === etag) || asked === "*")170			return c.body(null, 304);171		return c.body(await file.bytes(), 200, { "Content-Type": file.type });172	});173	const mirrorDir = join(config.dataDir, "mirror");174	// A getter, so a domain saved in the console reaches every page and check at once.175	const ctx = {176		get domain() {177			return config.domain;178		},179		kepr,180		mirrorDir,181	};182	// Before every other route, so the admin guard runs ahead of each `/admin` handler.183	registerLogin(app, ctx, config);184	registerConnect(app, config, ctx);185	// Not a spread of `ctx`, which would copy the domain once instead of keeping the getter.186	const admin = {187		get domain() {188			return config.domain;189		},190		kepr,191		mirrorDir,192		config,193		configPath,194		dataDir: config.dataDir,195		sync: { bucket, kepr, mirrorDir },196		syncer: syncer ?? localSyncer({ bucket, kepr, mirrorDir }),197	};198	registerStatus(app, admin);199	registerRepos(app, admin);200	registerIssues(app, admin);201	registerDownloads(app, admin);202	registerStorage(app, admin);203	registerSite(app, admin);204	registerBucket(app, admin);205	registerNotifications(app, admin);206	registerEmail(app, admin);207	registerBackups(app, admin);208	registerAccount(app, admin);209	registerRepoText(app, admin);210	registerHousekeeping(app, ctx);211	registerFrontPages(app, ctx);212	registerDocsPages(app, ctx);213	registerProfilePage(app, ctx);214	registerKepr2Routes(app, ctx);215	registerRepoPage(app, ctx);216	registerFileRoutes(app, ctx);217	registerSavePage(app, ctx);218	registerKohRemote(app, ctx);219	registerArchivesPage(app, ctx);220	registerReleasesPage(app, ctx);221	registerIssuePages(app, ctx, config);222	registerTarballRoutes(app, ctx, bucket);223	registerReleaseRoutes(app, ctx, bucket);224	return app;225}