1import { createHash } from "node:crypto";2import { mkdirSync, rmSync, writeFileSync } from "node:fs";3import { join } from "node:path";4import type { Context, Hono } from "hono";5import { isSafePath } from "../bucket/repo.ts";6import { applyHidden, openMirror } from "../mirror/store.ts";7import { supportText } from "../pages/docs.ts";8import { html } from "../pages/html.ts";9import { hiddenPaths, ignoredNames, setting } from "../server/db.ts";10import { type AdminContext, adminPage, formField, notice, textFields } from "./console.ts";11import { allRepos, saveSettings } from "./store.ts";121314const FIELDS: [key: string, label: string, max: number][] = [15 ["site_name", "site name", 100],16 ["tagline", "tagline", 300],17 ["branding", "branding text", 100],18 ["handle", "handle", 39],19 ["bio", "bio", 2000],20 ["location", "location", 100],21 ["link", "link", 500],22 ["building_since", "building since", 100],23 ["support_page", "support page (Markdown)", 4000],24];25const TEXTAREAS = new Set(["bio", "support_page"]);26const PROFILE_FIELDS = new Set(["handle", "bio", "location", "link", "building_since"]);27const HANDLE = /^[A-Za-z0-9._-]+$/;28const HTTP_URL = /^https?:\/\/[^\s]+$/i;2930const MAX_SIGNATURE = 60 * 1024;31const OWN_SIGNATURE = /^signature-[0-9a-f]{16}\.(png|jpg|webp)$/;32const MAX_IGNORED = 50;33const MAX_IGNORED_NAME = 255;343536373839function imageType(bytes: Uint8Array): "png" | "jpg" | "webp" | null {40 const starts = (sig: number[], at = 0) => sig.every((byte, i) => bytes[at + i] === byte);41 if (starts([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "png";42 if (starts([0xff, 0xd8, 0xff])) return "jpg";43 if (starts([0x52, 0x49, 0x46, 0x46]) && starts([0x57, 0x45, 0x42, 0x50], 8)) return "webp";44 return null;45}464748export function registerSite(app: Hono, ctx: AdminContext): void {49 const assets = join(ctx.dataDir, "assets");50 app.get("/admin/site", (c) => c.html(sitePage(c, ctx, "")));5152 app.post("/admin/site", async (c) => {53 const fields = await textFields(c);54 const section = fields.section;55 if (section && section !== "profile" && section !== "site")56 return c.text("Unknown section.", 400);57 const refuse = (error: string) => c.html(sitePage(c, ctx, error, fields), 400);58 const values: Record<string, string> = {};59 for (const [key, label, max] of FIELDS) {60 if (section && PROFILE_FIELDS.has(key) !== (section === "profile")) continue;61 values[key] = (fields[key] ?? "").trim();62 if (values[key].length > max) return refuse(`The ${label} is over ${max} characters.`);63 }64 if (values.handle && !HANDLE.test(values.handle)) {65 return refuse("A handle is letters, digits, '.', '_' and '-'.");66 }67 68 if (section !== "profile") values.support_off = fields.support === "1" ? "" : "1";69 const ignored = [70 ...new Set(71 (fields.ignored ?? "")72 .split(/\r?\n/)73 .map((name) => name.trim())74 .filter(Boolean),75 ),76 ];77 if (ignored.length > MAX_IGNORED) return refuse(`Up to ${MAX_IGNORED} ignored names.`);78 const bad = ignored.find(79 (name) => name.length > MAX_IGNORED_NAME || name.includes("/") || !isSafePath(name),80 );81 if (bad !== undefined) return refuse(`"${bad}" is not a file or folder name.`);82 const previousIgnored = ignoredNames(ctx.kepr);83 if (section !== "profile") values.ignored = ignored.join("\n");84 if (values.link && !HTTP_URL.test(values.link)) {85 return refuse("The link must be an http or https address.");86 }87 const upload = (await c.req.parseBody()).signature;88 const previous = setting(ctx.kepr, "signature");89 if (90 section === "site" &&91 ((upload instanceof File && upload.size > 0) || fields.remove_signature === "1")92 )93 return refuse("Edit your signature in profile settings.");94 if (upload instanceof File && upload.size > MAX_SIGNATURE) {95 return refuse("The signature must be under 60 KB.");96 }97 if (upload instanceof File && upload.size > 0) {98 const bytes = new Uint8Array(await upload.arrayBuffer());99 const type = imageType(bytes);100 if (!type) return refuse("The signature must be a PNG, JPEG or WebP image.");101 102 const hash = createHash("sha256").update(bytes).digest("hex").slice(0, 16);103 values.signature = `signature-${hash}.${type}`;104 mkdirSync(assets, { recursive: true });105 writeFileSync(join(assets, values.signature), bytes);106 } else if (fields.remove_signature === "1") {107 values.signature = "";108 }109 saveSettings(ctx.kepr, values);110 111 if (112 previous &&113 OWN_SIGNATURE.test(previous) &&114 values.signature !== undefined &&115 previous !== values.signature116 ) {117 rmSync(join(assets, previous), { force: true });118 }119 if (values.ignored !== undefined && values.ignored !== previousIgnored.join("\n")) {120 for (const { name } of allRepos(ctx.kepr)) {121 applyHidden(openMirror(ctx.mirrorDir, name), hiddenPaths(ctx.kepr, name));122 }123 }124 return c.redirect(`/admin/site?${section === "profile" ? "section=profile&" : ""}saved=1`, 303);125 });126}127128function sitePage(129 c: Context,130 ctx: AdminContext,131 error: string,132 fields?: Record<string, string>,133): string {134 const profile = (fields?.section ?? c.req.query("section")) === "profile";135 136 const value = (key: string) =>137 fields138 ? (fields[key] ?? "")139 : key === "support_page"140 ? supportText(ctx.kepr)141 : (setting(ctx.kepr, key) ?? "");142 const input = ([key, label, max]: (typeof FIELDS)[number]) =>143 html`<label class="issues-label" for="${key}">${label}</label>144${145 TEXTAREAS.has(key)146 ? html`<textarea class="issues-textarea" id="${key}" name="${key}" rows="${key === "bio" ? 4 : 12}"147maxlength="${max}">${value(key)}</textarea>`148 : html`<input class="issues-input" id="${key}" name="${key}" maxlength="${max}"149value="${value(key)}">`150}`;151 const body = html`${notice(error)}152<p class="admin-intro">${profile ? "Your public profile brings your work together. A handle gives it an address beginning with @." : "The name and words visitors see across your site."}</p>153${profile && setting(ctx.kepr, "handle") && html`<p><a href="/@${setting(ctx.kepr, "handle")}">view profile ↗</a></p>`}154<form class="issues-form" method="post" action="/admin/site" enctype="multipart/form-data">155${formField(c)}156<input type="hidden" name="section" value="${profile ? "profile" : "site"}">157${FIELDS.filter(([key]) => PROFILE_FIELDS.has(key) === profile).map(input)}158${159 !profile &&160 html`161<label class="issues-label"><input type="checkbox" name="support" value="1"${162 (fields ? fields.support === "1" : !setting(ctx.kepr, "support_off")) && " checked"163 }>164show the support page</label>165<label class="issues-label" for="ignored">ignored in every repo</label>166<p class="admin-intro">One file or folder name per line, such as .agent or AGENTS.md: hidden at167any depth in every repo, from pages and tarballs. Applied after any sync under way.</p>168<textarea class="issues-textarea mono" id="ignored" name="ignored" rows="4">${169 fields ? (fields.ignored ?? "") : ignoredNames(ctx.kepr).join("\n")170 }</textarea>`171}172<button class="issues-submit" type="submit">save ${profile ? "profile" : "site"}</button>173</form>`;174 return adminPage(c, ctx, profile ? "profile" : "site", body);175}