app.ts

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