app.ts

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