app.ts

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