app.ts

7.6 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 } 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(imgSrc: (string | (() => string))[] = ["'self'"]) {49	return secureHeaders({50		contentSecurityPolicy: {51			defaultSrc: ["'self'"],52			scriptSrc: ["'self'"],53			styleSrc: ["'self'"],54			fontSrc: ["'self'"],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	syncer?: Syncer,76): Hono {77	const app = new Hono();78	// §25 allows images from the presigned host, which is the bucket endpoint's origin; uploaded79	// videos come from there too.80	const imgSrc = [81		"'self'",82		() => (config.bucket.kind === "s3" ? new URL(config.bucket.endpoint).origin : ""),83	];84	app.use("*", async (c, next) => {85		await next();86		const path = c.req.path;87		if (c.res.headers.get("Content-Type")?.startsWith("text/html")) {88			c.header("Speculation-Rules", '"/speculation.json"');89		}90		if (/^\/(admin(?:\/|$)|sign-in$|connect$)/.test(path))91			c.header("Referrer-Policy", "same-origin");92		if (/^\/[^/]+\/raw\/.+/.test(path) || path.startsWith("/static/assets/")) {93			const policy = c.res.headers.get("Content-Security-Policy");94			c.header("Content-Security-Policy", policy ? `${policy}; sandbox` : "sandbox");95		}96	});97	app.use(securityHeaders(imgSrc));98	// A renamed repo's old pages, which now 404, move to its new name (June, 2026-10-01). Koh's99	// routes keep their 404, so a machine follows the bucket's rename marker instead.100	app.use("*", async (c, next) => {101		await next();102		if (c.req.method !== "GET" || c.res.status !== 404) return;103		const [, first = "", second, ...rest] = c.req.path.split("/");104		const to = second !== "koh" && renamedTo(kepr, first);105		if (!to) return;106		const query = new URL(c.req.url).search;107		const path = ["", to, ...(second === undefined ? [] : [second, ...rest])].join("/");108		c.res = c.redirect(`${path}${query}`, 301);109	});110	const limit = (maxSize: number) =>111		bodyLimit({112			maxSize,113			onError: (c) =>114				// An oversized redemption is one more failed redemption — but only where the route115				// exists: without write keys it is an unknown path and answers as one.116				c.req.path === "/api/connect" && connectKeys(config)117					? noCode(c)118					: c.text("Request body too large", 413),119		});120	const [small, large] = [limit(MAX_BODY_BYTES), limit(MAX_MEDIA_BYTES)];121	app.use((c, next) => (MEDIA_UPLOAD.test(c.req.path) ? large : small)(c, next));122	// `/static/assets/` is the operator's uploads in `data/assets/` (§19), such as the signature.123	const assetsDir = join(config.dataDir, "assets");124	app.get("/static/:path{.+}", async (c, next) => {125		const path = c.req.param("path");126		if (!isSafePath(path)) return c.notFound();127		// A repo's uploads have their own route: as private as the repo (§20), and Range for video.128		if (path.startsWith("assets/media/")) return next();129		const file = Bun.file(130			path.startsWith("assets/") ? join(assetsDir, path.slice(7)) : join(PUBLIC_DIR, path),131		);132		if (!(await file.exists())) return c.notFound();133		// A versioned URL names one build's file, and a font file never changes under its name, so134		// neither needs asking again.135		const versioned = c.req.query("v") !== undefined || path.startsWith("fonts/");136		c.header(137			"Cache-Control",138			versioned ? "public, max-age=31536000, immutable" : "public, max-age=3600",139		);140		return c.body(await file.bytes(), 200, { "Content-Type": file.type });141	});142	const mirrorDir = join(config.dataDir, "mirror");143	// A getter, so a domain saved in the console reaches every page and check at once.144	const ctx = {145		get domain() {146			return config.domain;147		},148		kepr,149		mirrorDir,150	};151	// Before every other route, so the admin guard runs ahead of each `/admin` handler.152	registerLogin(app, ctx, config);153	registerConnect(app, config, ctx);154	// Not a spread of `ctx`, which would copy the domain once instead of keeping the getter.155	const admin = {156		get domain() {157			return config.domain;158		},159		kepr,160		mirrorDir,161		config,162		configPath,163		dataDir: config.dataDir,164		sync: { bucket, kepr, mirrorDir },165		syncer: syncer ?? localSyncer({ bucket, kepr, mirrorDir }),166	};167	registerStatus(app, admin);168	registerRepos(app, admin);169	registerIssues(app, admin);170	registerDownloads(app, admin);171	registerStorage(app, admin);172	registerSite(app, admin);173	registerBucket(app, admin);174	registerNotifications(app, admin);175	registerEmail(app, admin);176	registerBackups(app, admin);177	registerAccount(app, admin);178	registerRepoText(app, admin);179	registerHousekeeping(app, ctx);180	registerFrontPages(app, ctx);181	registerDocsPages(app, ctx);182	registerProfilePage(app, ctx);183	registerKepr2Routes(app, ctx);184	registerRepoPage(app, ctx);185	registerFileRoutes(app, ctx);186	registerSavePage(app, ctx);187	registerKohRemote(app, ctx);188	registerArchivesPage(app, ctx);189	registerReleasesPage(app, ctx);190	registerIssuePages(app, ctx);191	registerTarballRoutes(app, ctx, bucket);192	registerReleaseRoutes(app, ctx, bucket);193	return app;194}