app.ts

5.5 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; uploaded44	// videos come from there too.45	const imgSrc =46		config.bucket.kind === "s3" ? ["'self'", new URL(config.bucket.endpoint).origin] : ["'self'"];47	app.use("*", async (c, next) => {48		await next();49		const path = c.req.path;50		if (/^\/(admin(?:\/|$)|sign-in$|connect$)/.test(path))51			c.header("Referrer-Policy", "same-origin");52		if (/^\/[^/]+\/raw\/.+/.test(path) || path.startsWith("/static/assets/")) {53			const policy = c.res.headers.get("Content-Security-Policy");54			c.header("Content-Security-Policy", policy ? `${policy}; sandbox` : "sandbox");55		}56	});57	app.use(58		secureHeaders({59			contentSecurityPolicy: {60				defaultSrc: ["'self'"],61				scriptSrc: ["'self'"],62				styleSrc: ["'self'", FONTS],63				fontSrc: [FONTS],64				imgSrc,65				mediaSrc: imgSrc,66				objectSrc: ["'none'"],67				baseUri: ["'none'"],68				formAction: ["'self'"],69				frameAncestors: ["'none'"],70			},71			xFrameOptions: "DENY",72		}),73	);74	const limit = (maxSize: number) =>75		bodyLimit({76			maxSize,77			onError: (c) =>78				// An oversized redemption is one more failed redemption — but only where the route79				// exists: without write keys it is an unknown path and answers as one.80				c.req.path === "/api/connect" && connectKeys(config)81					? noCode(c)82					: c.text("Request body too large", 413),83		});84	const [small, large] = [limit(MAX_BODY_BYTES), limit(MAX_MEDIA_BYTES)];85	app.use((c, next) => (MEDIA_UPLOAD.test(c.req.path) ? large : small)(c, next));86	// `/static/assets/` is the operator's uploads in `data/assets/` (§19), such as the signature.87	const assetsDir = join(config.dataDir, "assets");88	app.get("/static/:path{.+}", async (c, next) => {89		const path = c.req.param("path");90		if (!isSafePath(path)) return c.notFound();91		// A repo's uploads have their own route: as private as the repo (§20), and Range for video.92		if (path.startsWith("assets/media/")) return next();93		const file = Bun.file(94			path.startsWith("assets/") ? join(assetsDir, path.slice(7)) : join(PUBLIC_DIR, path),95		);96		if (!(await file.exists())) return c.notFound();97		c.header("Cache-Control", "public, max-age=3600");98		return c.body(await file.bytes(), 200, { "Content-Type": file.type });99	});100	const ctx = { domain: config.domain, kepr, mirrorDir: join(config.dataDir, "mirror") };101	const bucket = openBucket(config.bucket);102	// Before every other route, so the admin guard runs ahead of each `/admin` handler.103	registerLogin(app, ctx, config.adminPasswordHash);104	registerConnect(app, config, ctx);105	const admin = {106		...ctx,107		canConnect: connectKeys(config) !== null,108		dataDir: config.dataDir,109		sync: { bucket, kepr, mirrorDir: ctx.mirrorDir, tarballDir: join(config.dataDir, "tarballs") },110	};111	registerStatus(app, admin);112	registerRepos(app, admin);113	registerIssues(app, admin);114	registerReleases(app, admin);115	registerSite(app, admin);116	registerRepoText(app, admin);117	registerHousekeeping(app, ctx);118	registerFrontPages(app, ctx);119	registerDocsPages(app, ctx);120	registerProfilePage(app, ctx);121	registerKepr2Routes(app, ctx);122	registerRepoPage(app, ctx);123	registerFileRoutes(app, ctx);124	registerSavePage(app, ctx);125	registerKohRemote(app, ctx);126	registerArchivesPage(app, ctx);127	registerReleasesPage(app, ctx);128	registerIssuePages(app, ctx);129	registerTarballRoutes(app, ctx, join(config.dataDir, "tarballs"));130	registerReleaseRoutes(app, ctx, bucket);131	return app;132}