app.ts

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