Dough Git

commit

Add more stuff

commit
7598e98ae9c63c1f7ff7e518829e4dad1912b92a
author
Clove Twilight <[email protected]>
date
2026-11-04 18:32

diff --git a/.dev.vars.example b/.dev.vars.example
index 0bc54fb..e76d4eb 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -65,6 +65,11 @@ DOUGH_BOT_TOKEN=
 # `X-Battery-Key` header to POST /v2/battery.
 BATTERY_API_KEYS=
 
+# MANUAL guestbook moderation key(s), comma-separated. The website's server
+# sends it as `X-Guestbook-Key` to /v2/guestbook/admin/*. Give the same value
+# to the website as GUESTBOOK_ADMIN_KEY. e.g. `openssl rand -base64 48`.
+GUESTBOOK_ADMIN_KEYS=
+
 # ---- contribapi (/v2/contribapi) — merged git contribution heatmaps --------
 # Codeberg/Forgejo needs no token for the public heatmap endpoint.
 CODEBERG_USERNAME=
diff --git a/src/apidata.ts b/src/apidata.ts
index d364783..313ef7d 100644
--- a/src/apidata.ts
+++ b/src/apidata.ts
@@ -6,7 +6,7 @@
  * change — nothing else needs editing.
  * ===================================================================== */
 
-export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "WS";
+export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "WS";
 export type AuthKind = "public" | "auth" | "admin" | "owner" | "pet" | "jwt" | "bot" | "key";
 
 export interface EndpointDef {
@@ -237,13 +237,24 @@ export const GROUPS: GroupDef[] = [
         desc: "List entries, newest first → { entries: [{ id, name, message, website, ts }], total, limit, offset }.",
         params: [["limit", "Optional. 1–200, default 50."], ["offset", "Optional. ≥0, default 0."]] },
       { m: "POST", path: "/guestbook", auth: "public",
-        desc: "Sign the guestbook. Honeypot (url2) + Turnstile (when configured) + per-IP rate limit (60s). Returns { ok, entry } with the new UID.",
+        desc: "Sign the guestbook. Honeypot (url2) + Turnstile (when configured) + per-IP rate limit (60s). Returns 201 { ok, entry } with the new UID, or 202 { ok, pending: true } when the word filter holds it for review.",
         example: 'POST body: { "name": "Clove", "message": "hi!", "website": "https://…", "turnstileToken": "…" }' },
       { m: "DELETE", path: "/guestbook/:id", auth: "key",
         desc: "Delete an entry by its UID. Returns 404 if not found. Send the X-Battery-Key header.",
         params: [["id", "The entry's UID (required)."]] },
       { m: "POST", path: "/guestbook/import", auth: "key",
         desc: "Migration import: insert an entry with a fresh UID, bypassing captcha + rate limit. Send the X-Battery-Key header. Body { name, message, website? }." },
+      { m: "GET", path: "/guestbook/admin/entries?status=pending", auth: "admin",
+        desc: "Moderation list, including held entries and the blocklist terms that flagged them → { entries, total, pending }. Send X-Guestbook-Key or an admin bearer token.",
+        params: [["status", "Optional. pending, approved or all (default)."]] },
+      { m: "PATCH", path: "/guestbook/admin/entries/:id", auth: "admin",
+        desc: "Approve, re-hold or edit an entry. Body { status?: 'approved' | 'pending', name?, message?, website? }." },
+      { m: "DELETE", path: "/guestbook/admin/entries/:id", auth: "admin",
+        desc: "Delete an entry by its UID." },
+      { m: "GET", path: "/guestbook/admin/blocklist", auth: "admin",
+        desc: "The word blocklist → { words }. Matching ignores case, accents, spacing, punctuation, repeated letters and common lookalikes (b@d, 8ad, Cyrillic а)." },
+      { m: "PUT", path: "/guestbook/admin/blocklist", auth: "admin",
+        desc: "Replace the blocklist. Body { words: string[] }. Only affects new posts." },
     ],
   },
   {
diff --git a/src/docs.ts b/src/docs.ts
index 94fe714..3dc13f4 100644
--- a/src/docs.ts
+++ b/src/docs.ts
@@ -141,6 +141,7 @@ export const DOCS_HTML = `<!doctype html>
   .m.GET    { background: rgba(166,227,161,.14); color: var(--get);  border-color: rgba(166,227,161,.35); }
   .m.POST   { background: rgba(249,226,175,.14); color: var(--post); border-color: rgba(249,226,175,.35); }
   .m.PUT    { background: rgba(137,180,250,.16); color: var(--put);  border-color: rgba(137,180,250,.35); }
+  .m.PATCH  { background: rgba(137,180,250,.16); color: var(--put);  border-color: rgba(137,180,250,.35); }
   .m.DELETE { background: rgba(243,139,168,.16); color: var(--del);  border-color: rgba(243,139,168,.35); }
   .m.WS     { background: rgba(203,166,247,.16); color: var(--ws);   border-color: rgba(203,166,247,.35); }
 
diff --git a/src/openapi.ts b/src/openapi.ts
index b7af4e8..dcb67d2 100644
--- a/src/openapi.ts
+++ b/src/openapi.ts
@@ -141,7 +141,7 @@ function buildSpec(): JsonObj {
       if (params.length) op.parameters = params;
       const sec = security(ep.auth);
       if (sec) op.security = sec;
-      if (ep.m === "POST" || ep.m === "PUT") {
+      if (ep.m === "POST" || ep.m === "PUT" || ep.m === "PATCH") {
         op.requestBody = {
           required: false,
           content: { "application/json": { schema: { type: "object" } } },
diff --git a/src/system/middleware/auth.ts b/src/system/middleware/auth.ts
index 53522fa..0468788 100644
--- a/src/system/middleware/auth.ts
+++ b/src/system/middleware/auth.ts
@@ -16,7 +16,7 @@ import { decodeAccessToken } from "../security";
 import { HttpError } from "../errors";
 import { getUserByUsername } from "../services/users";
 import { currentSsoSession } from "../services/sso_sessions";
-import { verifyBotToken, verifyBatteryKey } from "../services/keys";
+import { verifyBotToken, verifyBatteryKey, verifyGuestbookKey } from "../services/keys";
 import type { User } from "../models";
 
 function extractBearer(c: Context<Env>): string | undefined {
@@ -123,3 +123,20 @@ export async function verifyBatteryAccess(c: Context<Env>, next: Next): Promise<
   if (!verifyBatteryKey(key)) throw new HttpError(401, "Invalid battery API key");
   await next();
 }
+
+/**
+ * Guestbook moderation: either the X-Guestbook-Key header (the website's
+ * server, after its own SSO login) or a signed-in admin's bearer token.
+ */
+export async function verifyGuestbookAdmin(c: Context<Env>, next: Next): Promise<void> {
+  const key = c.req.header("X-Guestbook-Key");
+  if (key) {
+    if (!verifyGuestbookKey(key)) throw new HttpError(401, "Invalid guestbook key");
+    await next();
+    return;
+  }
+  const user = await resolveCurrentUser(c);
+  if (!user.is_admin) throw new HttpError(403, "Admin privileges required");
+  c.set("user", user);
+  await next();
+}
diff --git a/src/system/routes/guestbook.ts b/src/system/routes/guestbook.ts
index baee73c..d3731d0 100644
--- a/src/system/routes/guestbook.ts
+++ b/src/system/routes/guestbook.ts
@@ -11,18 +11,27 @@
  *   DELETE /v2/guestbook/:id                 (X-Battery-Key required)
  *   POST   /v2/guestbook/import              (X-Battery-Key required; migration, no captcha)
  *
+ * Moderation (X-Guestbook-Key, or an admin bearer token):
+ *   GET    /v2/guestbook/admin/entries?status=pending|approved|all
+ *   PATCH  /v2/guestbook/admin/entries/:id   { status?, name?, message?, website? }
+ *   DELETE /v2/guestbook/admin/entries/:id
+ *   GET    /v2/guestbook/admin/blocklist     → { words }
+ *   PUT    /v2/guestbook/admin/blocklist     { words: string[] } (replaces the list)
+ *
  * POST body (JSON): { name, message, website?, url2?, turnstileToken? | "cf-turnstile-response"? }
  *   - url2 is a honeypot: if filled we pretend success and drop the entry.
  *   - Turnstile is only enforced when TURNSTILE_SECRET is configured.
  *
  * Each accepted entry is assigned a random UID (entry.id); delete by that UID.
+ * Entries that hit the word blocklist are held as pending and only appear in
+ * the public list once approved.
  */
 
 import { Hono } from "hono";
 import type { Context } from "hono";
 
 import type { Env } from "../hono";
-import { verifyBatteryAccess } from "../middleware/auth";
+import { verifyBatteryAccess, verifyGuestbookAdmin } from "../middleware/auth";
 import { verifyTurnstileToken } from "../security";
 import { turnstileSecret } from "../config";
 import {
@@ -34,6 +43,11 @@ import {
   addEntry,
   deleteEntry,
   checkAndRecordRateLimit,
+  isApproved,
+  publicEntry,
+  updateEntry,
+  readBlocklist,
+  saveBlocklist,
 } from "../services/guestbook";
 
 export const guestbookRoutes = new Hono<Env>();
@@ -54,11 +68,11 @@ function clientIp(c: Context): string | undefined {
 // ---- Public read -----------------------------------------------------------
 
 guestbookRoutes.get("/", async (c) => {
-  const entries = await readEntries();
+  const entries = (await readEntries()).filter(isApproved);
   const limit = Math.min(Math.max(parseInt(c.req.query("limit") || "") || 50, 1), 200);
   const offset = Math.max(parseInt(c.req.query("offset") || "") || 0, 0);
   return c.json({
-    entries: entries.slice(offset, offset + limit),
+    entries: entries.slice(offset, offset + limit).map(publicEntry),
     total: entries.length,
     limit,
     offset,
@@ -107,7 +121,10 @@ guestbookRoutes.post("/", async (c) => {
   }
 
   const entry = await addEntry({ name, message, website });
-  return c.json({ ok: true, entry }, 201);
+  // A held entry is acknowledged without echoing it back or saying which word
+  // tripped the filter.
+  if (!isApproved(entry)) return c.json({ ok: true, pending: true }, 202);
+  return c.json({ ok: true, entry: publicEntry(entry) }, 201);
 });
 
 // ---- Delete by UID (protected) ---------------------------------------------
@@ -144,3 +161,58 @@ guestbookRoutes.post("/import", verifyBatteryAccess, async (c) => {
   const entry = await addEntry({ name, message, website });
   return c.json({ ok: true, entry }, 201);
 });
+
+// ---- Moderation (guestbook key or admin) --------------------------------------
+
+guestbookRoutes.use("/admin/*", verifyGuestbookAdmin);
+
+guestbookRoutes.get("/admin/entries", async (c) => {
+  const status = c.req.query("status") ?? "all";
+  const entries = await readEntries();
+  const filtered =
+    status === "pending"
+      ? entries.filter((e) => !isApproved(e))
+      : status === "approved"
+        ? entries.filter(isApproved)
+        : entries;
+  return c.json({
+    entries: filtered.map((e) => ({ ...e, status: e.status ?? "approved" })),
+    total: filtered.length,
+    pending: entries.filter((e) => !isApproved(e)).length,
+  });
+});
+
+guestbookRoutes.patch("/admin/entries/:id", async (c) => {
+  let body: Record<string, unknown>;
+  try {
+    body = await c.req.json();
+  } catch {
+    return c.json({ error: "Invalid JSON body." }, 400);
+  }
+  const entry = await updateEntry(c.req.param("id"), body);
+  if (!entry) return c.json({ detail: `No guestbook entry with id '${c.req.param("id")}'` }, 404);
+  return c.json({ ok: true, entry: { ...entry, status: entry.status ?? "approved" } });
+});
+
+guestbookRoutes.delete("/admin/entries/:id", async (c) => {
+  const id = c.req.param("id");
+  if (!(await deleteEntry(id))) {
+    return c.json({ detail: `No guestbook entry with id '${id}'` }, 404);
+  }
+  return c.json({ success: true, id, deleted: true });
+});
+
+guestbookRoutes.get("/admin/blocklist", async (c) => {
+  return c.json({ words: await readBlocklist() });
+});
+
+guestbookRoutes.put("/admin/blocklist", async (c) => {
+  let body: { words?: unknown };
+  try {
+    body = await c.req.json();
+  } catch {
+    return c.json({ error: "Invalid JSON body." }, 400);
+  }
+  if (!Array.isArray(body.words)) return c.json({ error: "Expected { words: string[] }." }, 400);
+  return c.json({ ok: true, words: await saveBlocklist(body.words) });
+});
diff --git a/src/system/services/guestbook.ts b/src/system/services/guestbook.ts
index fe52828..873db26 100644
--- a/src/system/services/guestbook.ts
+++ b/src/system/services/guestbook.ts
@@ -12,16 +12,27 @@
  *
  * Per-IP rate limiting is kept, stored as a timestamp under
  * `guestbook_rl:<ip>` (compared against RATE_LIMIT_SECONDS on each POST).
+ *
+ * Moderation: every new entry is checked against a word blocklist (stored
+ * under `guestbook_blocklist`, managed through the admin routes). A hit holds
+ * the entry as "pending" until an admin approves or deletes it; only
+ * "approved" entries are ever served publicly. Entries from before moderation
+ * existed carry no status and count as approved.
  */
 
 import { rt } from "../runtime";
 
+export type GuestbookStatus = "approved" | "pending";
+
 export interface GuestbookEntry {
   id: string;
   name: string;
   message: string;
   website: string;
   ts: number;
+  status?: GuestbookStatus;
+  /** Blocklist terms that held this entry for review (admin-only). */
+  flagged?: string[];
 }
 
 /** Fields a caller may submit. */
@@ -32,7 +43,9 @@ export interface GuestbookInput {
 }
 
 const ENTRIES_KEY = "guestbook_entries";
+const BLOCKLIST_KEY = "guestbook_blocklist";
 const RL_PREFIX = "guestbook_rl:";
+const MAX_BLOCKLIST = 2000;
 const MAX_ENTRIES = 1000; // keep the blob bounded (well under the DO 128KB value cap)
 
 export const RATE_LIMIT_SECONDS = 60; // min seconds between posts from one IP
@@ -69,6 +82,73 @@ export function cleanWebsite(value: unknown): string {
   }
 }
 
+// ---- Blocklist ---------------------------------------------------------------
+
+// Characters people swap in to dodge a filter, mapped back to the letter.
+const LOOKALIKES: Record<string, string> = {
+  "0": "o", "1": "i", "3": "e", "4": "a", "5": "s", "7": "t", "8": "b", "9": "g",
+  "@": "a", "$": "s", "!": "i", "|": "i", "+": "t", "€": "e", "£": "l",
+  "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "у": "y", "х": "x", "і": "i", // Cyrillic
+};
+
+/**
+ * Reduce text to bare letters so "B.a-d", "b a d", "bаd" (Cyrillic а), "b@d"
+ * and "baaad" all become "bad". Applied to both the text and each blocklist
+ * term, so they always compare like for like.
+ */
+export function normalize(text: string): string {
+  return text
+    .normalize("NFKD")
+    .replace(/[̀-ͯ]/g, "") // strip accents left behind by NFKD
+    .toLowerCase()
+    .replace(/./gu, (ch) => LOOKALIKES[ch] ?? ch)
+    .replace(/[^\p{L}]/gu, "")
+    .replace(/(.)\1+/gu, "$1");
+}
+
+export async function readBlocklist(): Promise<string[]> {
+  return rt().store.get<string[]>(BLOCKLIST_KEY, []);
+}
+
+/** Replace the whole blocklist. Returns the cleaned, de-duplicated list. */
+export async function saveBlocklist(words: unknown): Promise<string[]> {
+  const list = Array.isArray(words) ? words : [];
+  const cleaned = [
+    ...new Set(list.map((w) => clean(w, 100).toLowerCase()).filter((w) => normalize(w))),
+  ].slice(0, MAX_BLOCKLIST);
+  await rt().store.put(BLOCKLIST_KEY, cleaned);
+  return cleaned;
+}
+
+/**
+ * Blocklist terms found anywhere in the given fields. Matching runs on the
+ * normalized, space-free text, so it errs towards holding too much (a term
+ * inside an innocent word); that only costs an approval click, while a miss
+ * would publish the message.
+ */
+export async function findBlocked(...fields: string[]): Promise<string[]> {
+  const haystack = normalize(fields.join(" "));
+  if (!haystack) return [];
+  const hits: string[] = [];
+  for (const term of await readBlocklist()) {
+    const needle = normalize(term);
+    if (needle && haystack.includes(needle)) hits.push(term);
+  }
+  return hits;
+}
+
+// ---- Entries -----------------------------------------------------------------
+
+export function isApproved(entry: GuestbookEntry): boolean {
+  return (entry.status ?? "approved") === "approved";
+}
+
+/** An entry as served publicly: no moderation fields. */
+export function publicEntry(entry: GuestbookEntry) {
+  const { id, name, message, website, ts } = entry;
+  return { id, name, message, website, ts };
+}
+
 export async function readEntries(): Promise<GuestbookEntry[]> {
   return rt().store.get<GuestbookEntry[]>(ENTRIES_KEY, []);
 }
@@ -79,15 +159,19 @@ async function saveEntries(entries: GuestbookEntry[]): Promise<void> {
 
 /**
  * Insert a new entry (newest first) with a fresh UID and the current time.
- * Inputs are assumed already cleaned/validated by the caller.
+ * Inputs are assumed already cleaned/validated by the caller. Anything that
+ * hits the blocklist is held as pending.
  */
 export async function addEntry(input: GuestbookInput): Promise<GuestbookEntry> {
+  const flagged = await findBlocked(input.name, input.message, input.website);
   const entry: GuestbookEntry = {
     id: crypto.randomUUID(),
     name: input.name,
     message: input.message,
     website: input.website,
     ts: Date.now(),
+    status: flagged.length ? "pending" : "approved",
+    ...(flagged.length ? { flagged } : {}),
   };
 
   const entries = await readEntries();
@@ -107,6 +191,28 @@ export async function deleteEntry(id: string): Promise<boolean> {
   return true;
 }
 
+/**
+ * Admin edit: change an entry's status and/or text. Fields are cleaned the
+ * same way as a public post. Returns the updated entry, or null if not found.
+ */
+export async function updateEntry(
+  id: string,
+  patch: { status?: unknown; name?: unknown; message?: unknown; website?: unknown },
+): Promise<GuestbookEntry | null> {
+  const entries = await readEntries();
+  const entry = entries.find((e) => e.id === id);
+  if (!entry) return null;
+
+  if (patch.status === "approved" || patch.status === "pending") entry.status = patch.status;
+  if (patch.status === "approved") delete entry.flagged;
+  if (patch.name !== undefined) entry.name = clean(patch.name, LIMITS.name) || entry.name;
+  if (patch.message !== undefined) entry.message = clean(patch.message, LIMITS.message) || entry.message;
+  if (patch.website !== undefined) entry.website = cleanWebsite(patch.website);
+
+  await saveEntries(entries);
+  return entry;
+}
+
 /**
  * Per-IP rate limit. Returns true if the caller is allowed to post now (and
  * records this post's time); false if they posted within RATE_LIMIT_SECONDS.
diff --git a/src/system/services/keys.ts b/src/system/services/keys.ts
index 3236c06..99d771e 100644
--- a/src/system/services/keys.ts
+++ b/src/system/services/keys.ts
@@ -43,3 +43,14 @@ export function verifyBatteryKey(providedKey: string): boolean {
   }
   return valid;
 }
+
+// ---- Guestbook moderation keys ----------------------------------------------
+
+export function verifyGuestbookKey(providedKey: string): boolean {
+  if (!providedKey) return false;
+  let valid = false;
+  for (const key of (rt().env.GUESTBOOK_ADMIN_KEYS ?? "").split(",").map((k) => k.trim())) {
+    if (key && constantTimeStringEqual(key, providedKey)) valid = true;
+  }
+  return valid;
+}
diff --git a/src/system/types.ts b/src/system/types.ts
index c6fc8de..9305949 100644
--- a/src/system/types.ts
+++ b/src/system/types.ts
@@ -66,6 +66,8 @@ export interface SystemEnv {
   DOUGH_BOT_TOKEN?: string;
   /** Comma-separated device battery-report keys (X-Battery-Key header). */
   BATTERY_API_KEYS?: string;
+  /** Comma-separated guestbook moderation keys (X-Guestbook-Key header). */
+  GUESTBOOK_ADMIN_KEYS?: string;
 
   // ---- Misc --------------------------------------------------------------
   /** Public base URL, used in a few absolute links. */
diff --git a/src/types.ts b/src/types.ts
index 02f7730..31fbc8e 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -16,6 +16,7 @@ export interface Env {
   ADMIN_DISPLAY_NAME?: string;
   DOUGH_BOT_TOKEN?: string;
   BATTERY_API_KEYS?: string;
+  GUESTBOOK_ADMIN_KEYS?: string;
   BASE_URL?: string;
   CORS_ORIGINS?: string;