app.ts

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