Dough Git

commit

add guestbook

commit
0ec4439c4a56ebcda1063d93383231a8bdfe97ee
author
Clove Twilight <[email protected]>
date
2026-07-14 11:38

diff --git a/src/docs.ts b/src/docs.ts
index 72ba8e9..16b3857 100644
--- a/src/docs.ts
+++ b/src/docs.ts
@@ -396,6 +396,22 @@ var GROUPS = [
         params: [["device", "1–64 chars (required)."]] }
     ]
   },
+  {
+    id: "guestbook", name: "Guestbook", blurb: "Public guestbook. Each entry gets a random UID so it can be deleted individually.",
+    endpoints: [
+      { m: "GET", path: "/guestbook?limit=50&offset=0", auth: "public",
+        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.",
+        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? }." }
+    ]
+  },
   {
     id: "system-data", name: "System-data — visitor logs", blurb: "Visit logging plus an admin-only log viewer.",
     endpoints: [
diff --git a/src/system/app.ts b/src/system/app.ts
index 22482ae..59a9f85 100644
--- a/src/system/app.ts
+++ b/src/system/app.ts
@@ -11,6 +11,7 @@
  *   /v2/plural/*        — auth, system, members, fronting, users, metrics,
  *                         admin, member status, bot, SEO (robots/sitemap)
  *   /v2/devices/*       — device state (battery, etc.)  (misc)
+ *   /v2/guestbook/*     — public guestbook (post/list/delete)  (misc)
  *   /v2/system-data/*   — visitor logging + log viewer (misc)
  *
  * The realtime socket /v2/plural/ws is handled by the DO before the request
@@ -36,6 +37,7 @@ import { memberStatusRoutes } from "./routes/member_status";
 import { botRoutes } from "./routes/bot";
 import { staticRoutes } from "./routes/static";
 import { deviceRoutes } from "./routes/devices";
+import { guestbookRoutes } from "./routes/guestbook";
 import { systemDataRoutes } from "./routes/system_data";
 
 // One-time owner seed per DO lifetime (there is no startup phase on a Worker).
@@ -96,6 +98,7 @@ systemApp.onError((err, c) => {
 
 systemApp.route("/v2/plural", pluralApp);
 systemApp.route("/v2/devices", deviceRoutes);
+systemApp.route("/v2/guestbook", guestbookRoutes);
 systemApp.route("/v2/system-data", systemDataRoutes);
 
 systemApp.notFound((c) => c.json({ detail: "Unknown route." }, 404));
diff --git a/src/system/routes/guestbook.ts b/src/system/routes/guestbook.ts
new file mode 100644
index 0000000..baee73c
--- /dev/null
+++ b/src/system/routes/guestbook.ts
@@ -0,0 +1,146 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * Guestbook. Mounted at /v2/guestbook.
+ *   GET    /v2/guestbook?limit=50&offset=0   (public, newest first)
+ *   POST   /v2/guestbook                     (public; honeypot + Turnstile + rate limit)
+ *   DELETE /v2/guestbook/:id                 (X-Battery-Key required)
+ *   POST   /v2/guestbook/import              (X-Battery-Key required; migration, no captcha)
+ *
+ * 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.
+ */
+
+import { Hono } from "hono";
+import type { Context } from "hono";
+
+import type { Env } from "../hono";
+import { verifyBatteryAccess } from "../middleware/auth";
+import { verifyTurnstileToken } from "../security";
+import { turnstileSecret } from "../config";
+import {
+  LIMITS,
+  RATE_LIMIT_SECONDS,
+  clean,
+  cleanWebsite,
+  readEntries,
+  addEntry,
+  deleteEntry,
+  checkAndRecordRateLimit,
+} from "../services/guestbook";
+
+export const guestbookRoutes = new Hono<Env>();
+
+interface PostBody {
+  name?: unknown;
+  message?: unknown;
+  website?: unknown;
+  url2?: unknown; // honeypot
+  turnstileToken?: unknown;
+  "cf-turnstile-response"?: unknown;
+}
+
+function clientIp(c: Context): string | undefined {
+  return c.req.header("cf-connecting-ip") ?? c.req.header("x-forwarded-for")?.split(",")[0].trim();
+}
+
+// ---- Public read -----------------------------------------------------------
+
+guestbookRoutes.get("/", async (c) => {
+  const entries = await readEntries();
+  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),
+    total: entries.length,
+    limit,
+    offset,
+  });
+});
+
+// ---- Public write (captcha + honeypot + rate limit) ------------------------
+
+guestbookRoutes.post("/", async (c) => {
+  let body: PostBody;
+  try {
+    body = await c.req.json<PostBody>();
+  } catch {
+    return c.json({ error: "Invalid JSON body." }, 400);
+  }
+
+  // Honeypot: real users never fill this hidden field.
+  if (clean(body.url2 ?? "", 100)) {
+    return c.json({ ok: true, skipped: true }); // pretend success
+  }
+
+  // Turnstile — only enforced when a secret is configured.
+  if (turnstileSecret()) {
+    const token = body.turnstileToken ?? body["cf-turnstile-response"];
+    const ok = typeof token === "string" && token
+      ? await verifyTurnstileToken(token, clientIp(c))
+      : false;
+    if (!ok) {
+      return c.json({ error: "Captcha verification failed. Please try again." }, 403);
+    }
+  }
+
+  const name = clean(body.name, LIMITS.name);
+  const message = clean(body.message, LIMITS.message);
+  const website = cleanWebsite(body.website);
+
+  if (!name) return c.json({ error: "Please enter a name." }, 400);
+  if (!message) return c.json({ error: "Please enter a message." }, 400);
+
+  const allowed = await checkAndRecordRateLimit(clientIp(c));
+  if (!allowed) {
+    return c.json(
+      { error: `Slow down a moment — you can post again in ~${RATE_LIMIT_SECONDS}s.` },
+      429,
+    );
+  }
+
+  const entry = await addEntry({ name, message, website });
+  return c.json({ ok: true, entry }, 201);
+});
+
+// ---- Delete by UID (protected) ---------------------------------------------
+
+guestbookRoutes.delete("/:id", verifyBatteryAccess, async (c) => {
+  const id = c.req.param("id");
+  if (!id) {
+    return c.json({ detail: "Missing entry id" }, 400);
+  }
+  const deleted = await deleteEntry(id);
+  if (!deleted) {
+    return c.json({ detail: `No guestbook entry with id '${id}'` }, 404);
+  }
+  return c.json({ success: true, id, deleted: true });
+});
+
+// ---- Migration import (protected; no captcha / no rate limit) --------------
+
+guestbookRoutes.post("/import", verifyBatteryAccess, async (c) => {
+  let body: PostBody;
+  try {
+    body = await c.req.json<PostBody>();
+  } catch {
+    return c.json({ error: "Invalid JSON body." }, 400);
+  }
+
+  const name = clean(body.name, LIMITS.name);
+  const message = clean(body.message, LIMITS.message);
+  const website = cleanWebsite(body.website);
+
+  if (!name) return c.json({ error: "Please enter a name." }, 400);
+  if (!message) return c.json({ error: "Please enter a message." }, 400);
+
+  const entry = await addEntry({ name, message, website });
+  return c.json({ ok: true, entry }, 201);
+});
diff --git a/src/system/services/guestbook.ts b/src/system/services/guestbook.ts
new file mode 100644
index 0000000..fe52828
--- /dev/null
+++ b/src/system/services/guestbook.ts
@@ -0,0 +1,123 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * Guestbook state. Ported from the standalone `guestbook` Worker (Cloudflare
+ * KV) to the SystemState DO blob store. Entries live newest-first in a single
+ * JSON blob under `guestbook_entries`; each entry carries a random UID so it
+ * can be deleted individually.
+ *
+ * Per-IP rate limiting is kept, stored as a timestamp under
+ * `guestbook_rl:<ip>` (compared against RATE_LIMIT_SECONDS on each POST).
+ */
+
+import { rt } from "../runtime";
+
+export interface GuestbookEntry {
+  id: string;
+  name: string;
+  message: string;
+  website: string;
+  ts: number;
+}
+
+/** Fields a caller may submit. */
+export interface GuestbookInput {
+  name: string;
+  message: string;
+  website: string;
+}
+
+const ENTRIES_KEY = "guestbook_entries";
+const RL_PREFIX = "guestbook_rl:";
+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
+
+export const LIMITS = {
+  name: 40,
+  message: 500,
+  website: 200,
+} as const;
+
+// Collapse whitespace, trim, and strip control chars. We do NOT store HTML;
+// consumers render everything as text, so this is just tidy-up.
+export function clean(value: unknown, max: number): string {
+  if (typeof value !== "string") return "";
+  return value
+    .replace(/[\x00-\x1F\x7F]/g, " ")
+    .replace(/\s+/g, " ")
+    .trim()
+    .slice(0, max);
+}
+
+// Accept only http(s) links; otherwise drop it.
+export function cleanWebsite(value: unknown): string {
+  const v = clean(value, LIMITS.website);
+  if (!v) return "";
+  let url = v;
+  if (!/^https?:\/\//i.test(url)) url = "https://" + url;
+  try {
+    const u = new URL(url);
+    if (u.protocol !== "http:" && u.protocol !== "https:") return "";
+    return u.toString().slice(0, LIMITS.website);
+  } catch {
+    return "";
+  }
+}
+
+export async function readEntries(): Promise<GuestbookEntry[]> {
+  return rt().store.get<GuestbookEntry[]>(ENTRIES_KEY, []);
+}
+
+async function saveEntries(entries: GuestbookEntry[]): Promise<void> {
+  await rt().store.put(ENTRIES_KEY, entries);
+}
+
+/**
+ * Insert a new entry (newest first) with a fresh UID and the current time.
+ * Inputs are assumed already cleaned/validated by the caller.
+ */
+export async function addEntry(input: GuestbookInput): Promise<GuestbookEntry> {
+  const entry: GuestbookEntry = {
+    id: crypto.randomUUID(),
+    name: input.name,
+    message: input.message,
+    website: input.website,
+    ts: Date.now(),
+  };
+
+  const entries = await readEntries();
+  entries.unshift(entry);
+  if (entries.length > MAX_ENTRIES) entries.length = MAX_ENTRIES;
+  await saveEntries(entries);
+  return entry;
+}
+
+/** Remove an entry by UID. Returns true if it existed and was deleted. */
+export async function deleteEntry(id: string): Promise<boolean> {
+  const entries = await readEntries();
+  const idx = entries.findIndex((e) => e.id === id);
+  if (idx === -1) return false;
+  entries.splice(idx, 1);
+  await saveEntries(entries);
+  return true;
+}
+
+/**
+ * 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.
+ * A blank IP is never rate-limited.
+ */
+export async function checkAndRecordRateLimit(ip: string | undefined): Promise<boolean> {
+  if (!ip) return true;
+  const key = RL_PREFIX + ip;
+  const last = await rt().store.get<number>(key, 0);
+  const now = Date.now();
+  if (last && now - last < RATE_LIMIT_SECONDS * 1000) return false;
+  await rt().store.put(key, now);
+  return true;
+}