app.ts

8.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 { 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.42const MAX_MEDIA_BYTES = 64 * 1024 * 1024;43const MEDIA_UPLOAD = /^\/admin\/repos\/[^/]+\/media$/;44export const PUBLIC_DIR = join(import.meta.dir, "../../public");45// §18 allows Bunny Fonts: its stylesheet and the font files it points at.4647/** §25's headers: the CSP, with no inline scripts, and no framing. */48export function securityHeaders(49	imgSrc: (string | (() => string))[] = ["'self'"],50	scriptSrc: (string | (() => string))[] = ["'self'"],51) {52	return secureHeaders({53		contentSecurityPolicy: {54			defaultSrc: ["'self'"],55			scriptSrc,56			// Umami's script reports to the origin it loads from.57			connectSrc: scriptSrc,58			styleSrc: ["'self'"],59			fontSrc: ["'self'"],60			imgSrc,61			mediaSrc: imgSrc,62			objectSrc: ["'none'"],63			baseUri: ["'none'"],64			formAction: ["'self'"],65			frameAncestors: ["'none'"],66		},67		xFrameOptions: "DENY",68	});69}7071/**72 * The Hono app with §25's headers and body cap, and every route built so far. The console's Bucket73 * section changes `config.bucket` and `bucket` in place, so everything here reads them per request.74 */75export function createApp(76	config: Config,77	kepr: Database,78	bucket: Bucket = openBucket(config.bucket),79	configPath = CONFIG_FILE,80	syncer?: Syncer,81): Hono {82	const app = new Hono();83	// §25 allows images from the presigned host, which is the bucket endpoint's origin; uploaded84	// videos come from there too.85	const imgSrc = [86		"'self'",87		() => (config.bucket.kind === "s3" ? new URL(config.bucket.endpoint).origin : ""),88	];89	app.use("*", async (c, next) => {90		await next();91		const path = c.req.path;92		if (c.res.headers.get("Content-Type")?.startsWith("text/html")) {93			c.header("Speculation-Rules", '"/speculation.json"');94		}95		if (/^\/(admin(?:\/|$)|sign-in$|connect$)/.test(path))96			c.header("Referrer-Policy", "same-origin");97		if (/^\/[^/]+\/raw\/.+/.test(path) || path.startsWith("/static/assets/")) {98			const policy = c.res.headers.get("Content-Security-Policy");99			c.header("Content-Security-Policy", policy ? `${policy}; sandbox` : "sandbox");100		}101	});102	// The operator's Umami script, when set (June, 2026-10-04).103	const scriptSrc = [104		"'self'",105		() => {106			const src = setting(kepr, "umami_src");107			return src ? new URL(src).origin : "";108		},109	];110	app.use(securityHeaders(imgSrc, scriptSrc));111	// A renamed repo's old pages, which now 404, move to its new name (June, 2026-10-01). Koh's112	// routes keep their 404, so a machine follows the bucket's rename marker instead.113	app.use("*", async (c, next) => {114		await next();115		if (c.req.method !== "GET" || c.res.status !== 404) return;116		const [, first = "", second, ...rest] = c.req.path.split("/");117		const to = second !== "koh" && renamedTo(kepr, first);118		if (!to) return;119		const query = new URL(c.req.url).search;120		const path = ["", to, ...(second === undefined ? [] : [second, ...rest])].join("/");121		c.res = c.redirect(`${path}${query}`, 301);122	});123	const limit = (maxSize: number) =>124		bodyLimit({125			maxSize,126			onError: (c) =>127				// An oversized redemption is one more failed redemption — but only where the route128				// exists: without write keys it is an unknown path and answers as one.129				c.req.path === "/api/connect" && connectKeys(config)130					? noCode(c)131					: c.text("Request body too large", 413),132		});133	const [small, large] = [limit(MAX_BODY_BYTES), limit(MAX_MEDIA_BYTES)];134	app.use((c, next) => (MEDIA_UPLOAD.test(c.req.path) ? large : small)(c, next));135	// `/static/assets/` is the operator's uploads in `data/assets/` (§19), such as the signature.136	const assetsDir = join(config.dataDir, "assets");137	app.get("/static/:path{.+}", async (c, next) => {138		const path = c.req.param("path");139		if (!isSafePath(path)) return c.notFound();140		// A repo's uploads have their own route: as private as the repo (§20), and Range for video.141		if (path.startsWith("assets/media/")) return next();142		const file = Bun.file(143			path.startsWith("assets/") ? join(assetsDir, path.slice(7)) : join(PUBLIC_DIR, path),144		);145		if (!(await file.exists())) return c.notFound();146		// A versioned URL names one build's file, and a font file never changes under its name, so147		// neither needs asking again.148		const versioned = c.req.query("v") !== undefined || path.startsWith("fonts/");149		c.header(150			"Cache-Control",151			versioned ? "public, max-age=31536000, immutable" : "public, max-age=3600",152		);153		return c.body(await file.bytes(), 200, { "Content-Type": file.type });154	});155	const mirrorDir = join(config.dataDir, "mirror");156	// A getter, so a domain saved in the console reaches every page and check at once.157	const ctx = {158		get domain() {159			return config.domain;160		},161		kepr,162		mirrorDir,163	};164	// Before every other route, so the admin guard runs ahead of each `/admin` handler.165	registerLogin(app, ctx, config);166	registerConnect(app, config, ctx);167	// Not a spread of `ctx`, which would copy the domain once instead of keeping the getter.168	const admin = {169		get domain() {170			return config.domain;171		},172		kepr,173		mirrorDir,174		config,175		configPath,176		dataDir: config.dataDir,177		sync: { bucket, kepr, mirrorDir },178		syncer: syncer ?? localSyncer({ bucket, kepr, mirrorDir }),179	};180	registerStatus(app, admin);181	registerRepos(app, admin);182	registerIssues(app, admin);183	registerDownloads(app, admin);184	registerStorage(app, admin);185	registerSite(app, admin);186	registerBucket(app, admin);187	registerNotifications(app, admin);188	registerEmail(app, admin);189	registerBackups(app, admin);190	registerAccount(app, admin);191	registerRepoText(app, admin);192	registerHousekeeping(app, ctx);193	registerFrontPages(app, ctx);194	registerDocsPages(app, ctx);195	registerProfilePage(app, ctx);196	registerKepr2Routes(app, ctx);197	registerRepoPage(app, ctx);198	registerFileRoutes(app, ctx);199	registerSavePage(app, ctx);200	registerKohRemote(app, ctx);201	registerArchivesPage(app, ctx);202	registerReleasesPage(app, ctx);203	registerIssuePages(app, ctx);204	registerTarballRoutes(app, ctx, bucket);205	registerReleaseRoutes(app, ctx, bucket);206	return app;207}