app.ts

6.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 { registerEmail } from "../admin/email.ts";11import { registerIssues } from "../admin/issues.ts";12import { registerNotifications } from "../admin/notifications.ts";13import { registerRepos } from "../admin/repos.ts";14import { registerSite } from "../admin/site.ts";15import { registerRepoText } from "../admin/text.ts";16import { type Bucket, openBucket } from "../bucket/reader.ts";17import { isSafePath } from "../bucket/repo.ts";18import { registerIssuePages } from "../issues/pages.ts";19import { registerKohRemote } from "../mirror/remote.ts";20import { registerArchivesPage } from "../pages/archives.ts";21import { registerDocsPages } from "../pages/docs.ts";22import { registerFileRoutes } from "../pages/files.ts";23import { registerFrontPages } from "../pages/front.ts";24import { registerHousekeeping } from "../pages/housekeeping.ts";25import { registerKepr2Routes } from "../pages/kepr2.ts";26import { registerProfilePage } from "../pages/profile.ts";27import { registerReleasesPage } from "../pages/releases.ts";28import { registerRepoPage } from "../pages/repo.ts";29import { registerSavePage } from "../pages/save.ts";30import { registerReleaseRoutes } from "../releases/routes.ts";31import { registerTarballRoutes } from "../tarball/archive.ts";32import { CONFIG_FILE, type Config } from "./config.ts";33import { connectKeys, noCode, registerConnect } from "./connect.ts";34import { registerLogin } from "./login.ts";3536const MAX_BODY_BYTES = 64 * 1024;37// §25's cap, except for the operator's picture and video uploads, which only a session reaches.38const MAX_MEDIA_BYTES = 64 * 1024 * 1024;39const MEDIA_UPLOAD = /^\/admin\/repos\/[^/]+\/media$/;40export const PUBLIC_DIR = join(import.meta.dir, "../../public");41// §18 allows Bunny Fonts: its stylesheet and the font files it points at.42const FONTS = "https://fonts.bunny.net";4344/** §25's headers: the CSP, with no inline scripts, and no framing. */45export function securityHeaders(imgSrc: (string | (() => string))[] = ["'self'"]) {46	return secureHeaders({47		contentSecurityPolicy: {48			defaultSrc: ["'self'"],49			scriptSrc: ["'self'"],50			styleSrc: ["'self'", FONTS],51			fontSrc: [FONTS],52			imgSrc,53			mediaSrc: imgSrc,54			objectSrc: ["'none'"],55			baseUri: ["'none'"],56			formAction: ["'self'"],57			frameAncestors: ["'none'"],58		},59		xFrameOptions: "DENY",60	});61}6263/**64 * The Hono app with §25's headers and body cap, and every route built so far. The console's Bucket65 * section changes `config.bucket` and `bucket` in place, so everything here reads them per request.66 */67export function createApp(68	config: Config,69	kepr: Database,70	bucket: Bucket = openBucket(config.bucket),71	configPath = CONFIG_FILE,72): Hono {73	const app = new Hono();74	// §25 allows images from the presigned host, which is the bucket endpoint's origin; uploaded75	// videos come from there too.76	const imgSrc = [77		"'self'",78		() => (config.bucket.kind === "s3" ? new URL(config.bucket.endpoint).origin : ""),79	];80	app.use("*", async (c, next) => {81		await next();82		const path = c.req.path;83		if (/^\/(admin(?:\/|$)|sign-in$|connect$)/.test(path))84			c.header("Referrer-Policy", "same-origin");85		if (/^\/[^/]+\/raw\/.+/.test(path) || path.startsWith("/static/assets/")) {86			const policy = c.res.headers.get("Content-Security-Policy");87			c.header("Content-Security-Policy", policy ? `${policy}; sandbox` : "sandbox");88		}89	});90	app.use(securityHeaders(imgSrc));91	const limit = (maxSize: number) =>92		bodyLimit({93			maxSize,94			onError: (c) =>95				// An oversized redemption is one more failed redemption — but only where the route96				// exists: without write keys it is an unknown path and answers as one.97				c.req.path === "/api/connect" && connectKeys(config)98					? noCode(c)99					: c.text("Request body too large", 413),100		});101	const [small, large] = [limit(MAX_BODY_BYTES), limit(MAX_MEDIA_BYTES)];102	app.use((c, next) => (MEDIA_UPLOAD.test(c.req.path) ? large : small)(c, next));103	// `/static/assets/` is the operator's uploads in `data/assets/` (§19), such as the signature.104	const assetsDir = join(config.dataDir, "assets");105	app.get("/static/:path{.+}", async (c, next) => {106		const path = c.req.param("path");107		if (!isSafePath(path)) return c.notFound();108		// A repo's uploads have their own route: as private as the repo (§20), and Range for video.109		if (path.startsWith("assets/media/")) return next();110		const file = Bun.file(111			path.startsWith("assets/") ? join(assetsDir, path.slice(7)) : join(PUBLIC_DIR, path),112		);113		if (!(await file.exists())) return c.notFound();114		c.header("Cache-Control", "public, max-age=3600");115		return c.body(await file.bytes(), 200, { "Content-Type": file.type });116	});117	const mirrorDir = join(config.dataDir, "mirror");118	// A getter, so a domain saved in the console reaches every page and check at once.119	const ctx = {120		get domain() {121			return config.domain;122		},123		kepr,124		mirrorDir,125	};126	// Before every other route, so the admin guard runs ahead of each `/admin` handler.127	registerLogin(app, ctx, config);128	registerConnect(app, config, ctx);129	// Not a spread of `ctx`, which would copy the domain once instead of keeping the getter.130	const admin = {131		get domain() {132			return config.domain;133		},134		kepr,135		mirrorDir,136		config,137		configPath,138		dataDir: config.dataDir,139		sync: { bucket, kepr, mirrorDir },140	};141	registerStatus(app, admin);142	registerRepos(app, admin);143	registerIssues(app, admin);144	registerSite(app, admin);145	registerBucket(app, admin);146	registerNotifications(app, admin);147	registerEmail(app, admin);148	registerBackups(app, admin);149	registerAccount(app, admin);150	registerRepoText(app, admin);151	registerHousekeeping(app, ctx);152	registerFrontPages(app, ctx);153	registerDocsPages(app, ctx);154	registerProfilePage(app, ctx);155	registerKepr2Routes(app, ctx);156	registerRepoPage(app, ctx);157	registerFileRoutes(app, ctx);158	registerSavePage(app, ctx);159	registerKohRemote(app, ctx);160	registerArchivesPage(app, ctx);161	registerReleasesPage(app, ctx);162	registerIssuePages(app, ctx);163	registerTarballRoutes(app, ctx, bucket);164	registerReleaseRoutes(app, ctx, bucket);165	return app;166}