Dough Git

commit

Drop the bot routes and the old api import; SSO callback on this host

commit
f95b078ed3f8a3d4609e2869fa125fdd20af6297
author
Clove Twilight <[email protected]>
date
2026-11-14 23:38
The SSO redirect is now https://doughmination.co.uk/api/plural/auth/sso/callback.
Removes the /bot/* routes and the DOUGH_BOT_TOKEN check, and the one-time
copy from the old api Worker (automatic first-run import, the admin route
and its button). Only the pk;export import remains.

Co-Authored-By: Sandrone <[email protected]>

diff --git a/src/lib/server/plural/app.ts b/src/lib/server/plural/app.ts
index 6e3a5d9..1bdf4a1 100644
--- a/src/lib/server/plural/app.ts
+++ b/src/lib/server/plural/app.ts
@@ -11,8 +11,6 @@ import type { Env } from "./hono";
 import { HttpError } from "./errors";
 import { corsOrigins, isLocalhostOrigin } from "./config";
 import { initializeAdminUser } from "./services/users";
-import { importLegacyStore } from "./services/importer";
-import { rt } from "./runtime";
 
 import { authRoutes } from "./routes/auth";
 import { systemRoutes } from "./routes/system";
@@ -23,18 +21,13 @@ import { frontingRoutes } from "./routes/fronting";
 import { usersRoutes } from "./routes/users";
 import { metricsRoutes } from "./routes/metrics";
 import { adminRoutes } from "./routes/admin";
-import { botRoutes } from "./routes/bot";
 
-// First run on an empty database: copy users and sessions from the old api Worker,
-// so people stay signed in. Otherwise seed the owner. Once per isolate
+// Seed the owner account once per isolate
 let seeded = false;
 async function ensureSeeded(): Promise<void> {
   if (seeded) return;
   seeded = true;
   try {
-    if ((await rt().store.get<unknown[]>("users", [])).length === 0) {
-      await importLegacyStore().catch((err) => console.warn(`Legacy import skipped: ${String(err)}`));
-    }
     await initializeAdminUser();
   } catch (err) {
     seeded = false;
@@ -52,7 +45,6 @@ plural.route("/", frontingRoutes);
 plural.route("/", usersRoutes);
 plural.route("/", metricsRoutes);
 plural.route("/", adminRoutes);
-plural.route("/", botRoutes);
 
 export const app = new OpenAPIHono<Env>().basePath("/api");
 
@@ -88,12 +80,6 @@ app.openAPIRegistry.registerComponent("securitySchemes", "bearerAuth", {
   description: "The token from an SSO sign-in (24 hours). Some routes also need the admin, owner or pet role",
 });
 
-app.openAPIRegistry.registerComponent("securitySchemes", "botAuth", {
-  type: "http",
-  scheme: "bearer",
-  description: "The DOUGH_BOT_TOKEN secret, sent with a 'User-Agent: CloveShortcuts/<version>' header",
-});
-
 app.doc31("/openapi.json", {
   openapi: "3.1.0",
   info: {
diff --git a/src/lib/server/plural/config.ts b/src/lib/server/plural/config.ts
index 618c49b..2305071 100644
--- a/src/lib/server/plural/config.ts
+++ b/src/lib/server/plural/config.ts
@@ -85,7 +85,6 @@ export function isLocalhostOrigin(origin: string): boolean {
 
 export function corsOrigins(): string[] {
   const defaults = [
-    "https://doughmination.uk",
     "https://doughmination.co.uk",
     "https://doughmination.gay",
     "https://vibecoded.doughmination.gay",
diff --git a/src/lib/server/plural/middleware/auth.ts b/src/lib/server/plural/middleware/auth.ts
index 1e5e2b1..ca5311b 100644
--- a/src/lib/server/plural/middleware/auth.ts
+++ b/src/lib/server/plural/middleware/auth.ts
@@ -16,7 +16,6 @@ import { decodeAccessToken } from "../security";
 import { HttpError } from "../errors";
 import { getUserByUsername } from "../services/users";
 import { currentSsoSession } from "../services/sso_sessions";
-import { verifyBotToken } from "../services/keys";
 import type { User } from "../models";
 
 function extractBearer(c: Context<Env>): string | undefined {
@@ -88,31 +87,3 @@ export async function requirePet(c: Context<Env>, next: Next): Promise<void> {
   if (!user?.is_pet) throw new HttpError(403, "Pet privileges required");
   await next();
 }
-
-/**
- * Verify Discord bot access: `Authorization: Bearer <DOUGH_BOT_TOKEN>` plus a
- * `User-Agent: CloveShortcuts/<version>` header.
- */
-export async function verifyBotAccess(c: Context<Env>, next: Next): Promise<void> {
-  const userAgent = c.req.header("User-Agent");
-  const authorization = c.req.header("Authorization");
-
-  if (!userAgent || !userAgent.startsWith("CloveShortcuts/")) {
-    throw new HttpError(403, "Invalid User-Agent. Expected 'CloveShortcuts/<version>'");
-  }
-  if (!authorization) {
-    throw new HttpError(401, "Missing Authorization header", { "WWW-Authenticate": "Bearer" });
-  }
-
-  const [scheme, token = ""] = authorization.split(" ");
-  if (authorization.split(" ").length !== 2 || scheme?.toLowerCase() !== "bearer") {
-    throw new HttpError(401, "Invalid Authorization header format. Expected 'Bearer <token>'", {
-      "WWW-Authenticate": "Bearer",
-    });
-  }
-
-  if (!verifyBotToken(token)) {
-    throw new HttpError(401, "Invalid bot access token", { "WWW-Authenticate": "Bearer" });
-  }
-  await next();
-}
diff --git a/src/lib/server/plural/models.ts b/src/lib/server/plural/models.ts
index 4ccf383..264d8bf 100644
--- a/src/lib/server/plural/models.ts
+++ b/src/lib/server/plural/models.ts
@@ -114,7 +114,7 @@ export const MentalStateSchema = z.object({
 export type MentalState = z.infer<typeof MentalStateSchema>;
 
 // ============================================================================
-// BOT MODELS
+// SWITCH MODELS
 // ============================================================================
 
 export const MultiSwitchRequestSchema = z.object({
diff --git a/src/lib/server/plural/openapi.ts b/src/lib/server/plural/openapi.ts
index bb6278b..dfe6f96 100644
--- a/src/lib/server/plural/openapi.ts
+++ b/src/lib/server/plural/openapi.ts
@@ -54,7 +54,6 @@ export function jsonBody<T extends z.ZodType>(schema: T) {
 }
 
 export const signedIn = [{ bearerAuth: [] }];
-export const botAuth = [{ botAuth: [] }];
 
 function issuesText(issues: ReadonlyArray<{ path: PropertyKey[]; message: string }>): string {
   return issues
diff --git a/src/lib/server/plural/routes/admin.ts b/src/lib/server/plural/routes/admin.ts
index 00fbcb8..06a8df2 100644
--- a/src/lib/server/plural/routes/admin.ts
+++ b/src/lib/server/plural/routes/admin.ts
@@ -10,7 +10,7 @@ import { router, ok, jsonBody, signedIn } from "../openapi";
 import { MessageSchema } from "../schemas";
 import { requireAuth, requireAdmin, requireOwner } from "../middleware/auth";
 import { broadcastFrontendUpdate } from "../ws";
-import { importLegacyStore, importPluralKitExport } from "../services/importer";
+import { importPluralKitExport } from "../services/importer";
 import { rt } from "../runtime";
 
 export const adminRoutes = router();
@@ -69,24 +69,6 @@ adminRoutes.openapi(
   },
 );
 
-adminRoutes.openapi(
-  createRoute({
-    method: "post",
-    path: "/admin/import/legacy",
-    tags: ["Admin"],
-    summary: "Copy users, tags, status, pride, relationships, mental state and sessions from the old api Worker (owner)",
-    security: signedIn,
-    middleware: [requireAuth, requireOwner] as const,
-    responses: ok(
-      z.object({
-        imported: z.array(z.string()),
-        skipped: z.array(z.string()),
-      }),
-    ),
-  }),
-  async (c) => c.json(await importLegacyStore(), 200),
-);
-
 // Images copied in by the importer. Public, like the PluralKit CDN was
 adminRoutes.openapi(
   createRoute({
diff --git a/src/lib/server/plural/routes/bot.ts b/src/lib/server/plural/routes/bot.ts
deleted file mode 100644
index 076ecf9..0000000
--- a/src/lib/server/plural/routes/bot.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-/* src/lib/server/plural/routes/bot.ts
- * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
- * Licensed under the DASL-1.2 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { createRoute, z } from "@hono/zod-openapi";
-
-import { router, ok, jsonBody, botAuth, signedIn } from "../openapi";
-import { FrontersSchema, MemberSchema, MessageSchema, SystemSchema } from "../schemas";
-import { getSystem, getMembers } from "../services/system";
-import { enrichMembersWithTags } from "../services/tags";
-import { enrichMembersWithStatus } from "../services/status";
-import { requireAuth, requireOwner, verifyBotAccess } from "../middleware/auth";
-import { HttpError } from "../errors";
-import { switchAndBroadcast } from "./fronting";
-import { getFronters } from "../services/system";
-
-export const botRoutes = router();
-
-const TOKEN_MANAGED_MSG =
-  "Bot token is set manually via the DOUGH_BOT_TOKEN secret; rotate it with `wrangler secret put DOUGH_BOT_TOKEN`.";
-
-function wrapped<T extends z.ZodType>(schema: T) {
-  return z.object({
-    success: z.boolean(),
-    data: schema,
-  });
-}
-
-botRoutes.openapi(
-  createRoute({
-    method: "get",
-    path: "/bot/health",
-    tags: ["Bot"],
-    summary: "Check the bot token works",
-    security: botAuth,
-    middleware: [verifyBotAccess] as const,
-    responses: ok(MessageSchema),
-  }),
-  (c) => c.json({ status: "ok", message: "Bot API is operational", authenticated: true }, 200),
-);
-
-botRoutes.openapi(
-  createRoute({
-    method: "post",
-    path: "/bot/token/regenerate",
-    tags: ["Bot"],
-    summary: "Retired. Always 410",
-    security: signedIn,
-    middleware: [requireAuth, requireOwner] as const,
-    responses: ok(MessageSchema),
-  }),
-  () => {
-    throw new HttpError(410, TOKEN_MANAGED_MSG);
-  },
-);
-
-botRoutes.openapi(
-  createRoute({
-    method: "post",
-    path: "/bot/token/regenerate-self",
-    tags: ["Bot"],
-    summary: "Retired. Always 410",
-    security: botAuth,
-    middleware: [verifyBotAccess] as const,
-    responses: ok(MessageSchema),
-  }),
-  () => {
-    throw new HttpError(410, TOKEN_MANAGED_MSG);
-  },
-);
-
-botRoutes.openapi(
-  createRoute({
-    method: "get",
-    path: "/bot/system/info",
-    tags: ["Bot"],
-    summary: "The system",
-    security: botAuth,
-    middleware: [verifyBotAccess] as const,
-    responses: ok(wrapped(SystemSchema)),
-  }),
-  async (c) => c.json({ success: true, data: (await getSystem()) as z.infer<typeof SystemSchema> }, 200),
-);
-
-botRoutes.openapi(
-  createRoute({
-    method: "get",
-    path: "/bot/members",
-    tags: ["Bot"],
-    summary: "Every member, with tags and status",
-    security: botAuth,
-    middleware: [verifyBotAccess] as const,
-    responses: ok(wrapped(z.array(MemberSchema))),
-  }),
-  async (c) => {
-    const withTags = await enrichMembersWithTags(await getMembers());
-    const members = (await enrichMembersWithStatus(withTags)) as z.infer<typeof MemberSchema>[];
-    return c.json({ success: true, data: members }, 200);
-  },
-);
-
-botRoutes.openapi(
-  createRoute({
-    method: "get",
-    path: "/bot/fronters",
-    tags: ["Bot"],
-    summary: "Who is fronting now",
-    security: botAuth,
-    middleware: [verifyBotAccess] as const,
-    responses: ok(wrapped(FrontersSchema)),
-  }),
-  async (c) => c.json({ success: true, data: (await getFronters()) as z.infer<typeof FrontersSchema> }, 200),
-);
-
-botRoutes.openapi(
-  createRoute({
-    method: "post",
-    path: "/bot/switch",
-    tags: ["Bot"],
-    summary: "Set the front",
-    security: botAuth,
-    middleware: [verifyBotAccess] as const,
-    request: jsonBody(z.object({ member_ids: z.array(z.string()) })),
-    responses: ok(MessageSchema),
-  }),
-  async (c) => {
-    const memberIds = c.req.valid("json").member_ids;
-    const fronters = await switchAndBroadcast(memberIds);
-    return c.json(
-      {
-        status: "success",
-        message: "Fronters updated successfully",
-        fronters: fronters.members,
-        count: memberIds.length,
-      },
-      200,
-    );
-  },
-);
diff --git a/src/lib/server/plural/routes/fronting.ts b/src/lib/server/plural/routes/fronting.ts
index 8503f1b..a3ac5b2 100644
--- a/src/lib/server/plural/routes/fronting.ts
+++ b/src/lib/server/plural/routes/fronting.ts
@@ -26,7 +26,7 @@ async function enrichedFronters(): Promise<Fronters> {
   return { ...fronters, members: await enrichMembersWithStatus(withTags) } as Fronters;
 }
 
-// Switch, then tell every connected page. Shared with the bot routes
+// Switch, then tell every connected page
 export async function switchAndBroadcast(memberIds: string[]): Promise<Fronters> {
   await setFront(memberIds);
   const fronters = await enrichedFronters();
diff --git a/src/lib/server/plural/services/importer.ts b/src/lib/server/plural/services/importer.ts
index d22944c..cbf0ad1 100644
--- a/src/lib/server/plural/services/importer.ts
+++ b/src/lib/server/plural/services/importer.ts
@@ -9,18 +9,6 @@ import { HttpError } from "../errors";
 import { frontendUrl } from "../config";
 import type { JsonObject } from "../types";
 
-// Legacy DO keys that belong to the plural system. Guestbook, devices and counters stay in the api Worker
-const LEGACY_KEYS = new Set([
-  "users",
-  "member_tags",
-  "member_status",
-  "member_pride",
-  "member_relationships",
-  "mental_state",
-  "sso_sessions_index",
-]);
-const LEGACY_PREFIXES = ["sso_session:"];
-
 const MEDIA_FIELDS = ["avatar_url", "webhook_avatar_url", "banner"] as const;
 const MAX_MEDIA_BYTES = 10 * 1024 * 1024;
 
@@ -193,28 +181,3 @@ export async function importPluralKitExport(
   await runBatches(statements);
   return report;
 }
-
-// Pull the plural keys out of the api Worker's old SystemState store
-export async function importLegacyStore(): Promise<{ imported: string[]; skipped: string[] }> {
-  const dump = await rt().env.HUB.exportLegacy();
-  const imported: string[] = [];
-  const skipped: string[] = [];
-  const statements: D1PreparedStatement[] = [];
-
-  for (const [key, value] of Object.entries(dump)) {
-    const wanted = LEGACY_KEYS.has(key) || LEGACY_PREFIXES.some((prefix) => key.startsWith(prefix));
-    if (!wanted) {
-      skipped.push(key);
-      continue;
-    }
-    statements.push(
-      rt()
-        .db.prepare("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
-        .bind(key, JSON.stringify(value)),
-    );
-    imported.push(key);
-  }
-
-  await runBatches(statements);
-  return { imported, skipped };
-}
diff --git a/src/lib/server/plural/services/keys.ts b/src/lib/server/plural/services/keys.ts
deleted file mode 100644
index 86be6c0..0000000
--- a/src/lib/server/plural/services/keys.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/* src/lib/server/plural/services/keys.ts
- * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
- * Licensed under the DASL-1.2 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Manual API-key verification (bot token).
- *
- * These keys are now set MANUALLY as secrets/vars — nothing is generated on
- * first run and there is no longer a regenerate flow. Verification is a
- * constant-time comparison against the configured value(s).
- *   - Bot token:  DOUGH_BOT_TOKEN
- */
-
-import { rt } from "../runtime";
-import { constantTimeStringEqual } from "../security";
-
-// ---- Bot token ------------------------------------------------------------
-
-export function verifyBotToken(providedToken: string): boolean {
-  const configured = rt().env.DOUGH_BOT_TOKEN;
-  if (!configured || !providedToken) return false;
-  return constantTimeStringEqual(configured, providedToken);
-}
diff --git a/src/lib/server/plural/types.ts b/src/lib/server/plural/types.ts
index 95947b7..6333df0 100644
--- a/src/lib/server/plural/types.ts
+++ b/src/lib/server/plural/types.ts
@@ -7,8 +7,6 @@
 // The api Worker's `Hub` entrypoint, reached over the HUB service binding
 export interface HubRpc {
   broadcast(data: unknown): Promise<void>;
-  // Every key in the old SystemState DO store, for the one-time import
-  exportLegacy(): Promise<Record<string, unknown>>;
 }
 
 export interface PluralEnv {
@@ -20,7 +18,6 @@ export interface PluralEnv {
   JWT_SECRET?: string;
   SSO_CLIENT_ID?: string;
   SSO_CLIENT_SECRET?: string;
-  DOUGH_BOT_TOKEN?: string;
 
   // Vars
   SSO_ISSUER?: string;
diff --git a/src/routes/admin/members/+page.svelte b/src/routes/admin/members/+page.svelte
index 6f42f1b..4726d45 100644
--- a/src/routes/admin/members/+page.svelte
+++ b/src/routes/admin/members/+page.svelte
@@ -210,16 +210,6 @@
       return `Imported ${report.members} members and ${report.switches} switches, copied ${report.media_copied} image(s)${failed}`;
     }, "Import failed");
   }
-
-  function importLegacy() {
-    if (!confirm("Copy users, tags, statuses, pride, relationships, mental state and sessions from the old API? Existing values here are overwritten.")) return;
-
-    void run(async () => {
-      const report = await authFetch<{ imported: string[] }>("/plural/admin/import/legacy", { method: "POST" }, "Legacy import failed");
-      await auth.refresh();
-      return `Copied ${report.imported.length} item(s) from the old API`;
-    }, "Legacy import failed");
-  }
 </script>
 
 <svelte:head>
@@ -314,10 +304,6 @@
               <button type="submit" class="primary" disabled={saving || !importFile?.length}>Import export</button>
             </div>
           </form>
-
-          <div class="buttons">
-            <button type="button" disabled={saving} onclick={importLegacy}>Copy data from the old API</button>
-          </div>
         </section>
       {/if}
     {/if}
diff --git a/vite.config.ts b/vite.config.ts
index e91a684..25d4b72 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -17,7 +17,7 @@ export default defineConfig({
       },
       adapter: adapter(),
       // /api is bearer-token only (no cookies) and the site has no form actions, so the origin check guards nothing
-      // and would block body-less calls from the app, CloveShortcuts and the doughmination.uk proxy
+      // and would block body-less calls from the app and other sites
       csrf: {
         trustedOrigins: ["*"],
       },
diff --git a/wrangler.jsonc b/wrangler.jsonc
index 1c6122c..d974b16 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -47,9 +47,8 @@
     "CORS_ORIGINS": "",
 
     // Doughmination SSO. Secrets: SSO_CLIENT_ID, SSO_CLIENT_SECRET, JWT_SECRET
-    // The redirect stays on doughmination.uk, which forwards /v2/plural/* here
     "SSO_ISSUER": "https://auth.doughmination.gay",
-    "SSO_REDIRECT_URI": "https://doughmination.uk/v2/plural/auth/sso/callback",
+    "SSO_REDIRECT_URI": "https://doughmination.co.uk/api/plural/auth/sso/callback",
     "SSO_SCOPES": "openid profile email offline_access",
     "SSO_POST_LOGIN_URL": "https://doughmination.co.uk/user/login/callback",
     "SSO_POST_LOGOUT_REDIRECT_URI": "https://doughmination.co.uk/"