app.ts

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