app.ts

8.4 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 { 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) 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		// A versioned URL names one build's file, and a font file never changes under its name, so157		// neither needs asking again.158		const versioned = c.req.query("v") !== undefined || path.startsWith("fonts/");159		c.header(160			"Cache-Control",161			versioned ? "public, max-age=31536000, immutable" : "public, max-age=3600",162		);163		return c.body(await file.bytes(), 200, { "Content-Type": file.type });164	});165	const mirrorDir = join(config.dataDir, "mirror");166	// A getter, so a domain saved in the console reaches every page and check at once.167	const ctx = {168		get domain() {169			return config.domain;170		},171		kepr,172		mirrorDir,173	};174	// Before every other route, so the admin guard runs ahead of each `/admin` handler.175	registerLogin(app, ctx, config);176	registerConnect(app, config, ctx);177	// Not a spread of `ctx`, which would copy the domain once instead of keeping the getter.178	const admin = {179		get domain() {180			return config.domain;181		},182		kepr,183		mirrorDir,184		config,185		configPath,186		dataDir: config.dataDir,187		sync: { bucket, kepr, mirrorDir },188		syncer: syncer ?? localSyncer({ bucket, kepr, mirrorDir }),189	};190	registerStatus(app, admin);191	registerRepos(app, admin);192	registerIssues(app, admin);193	registerDownloads(app, admin);194	registerStorage(app, admin);195	registerSite(app, admin);196	registerBucket(app, admin);197	registerNotifications(app, admin);198	registerEmail(app, admin);199	registerBackups(app, admin);200	registerAccount(app, admin);201	registerRepoText(app, admin);202	registerHousekeeping(app, ctx);203	registerFrontPages(app, ctx);204	registerDocsPages(app, ctx);205	registerProfilePage(app, ctx);206	registerKepr2Routes(app, ctx);207	registerRepoPage(app, ctx);208	registerFileRoutes(app, ctx);209	registerSavePage(app, ctx);210	registerKohRemote(app, ctx);211	registerArchivesPage(app, ctx);212	registerReleasesPage(app, ctx);213	registerIssuePages(app, ctx, config);214	registerTarballRoutes(app, ctx, bucket);215	registerReleaseRoutes(app, ctx, bucket);216	return app;217}