commit
Move the plural API into the site at /api/plural
The tracker API now runs inside this Worker on D1 and R2, with an OpenAPI spec at /api/openapi.json. PluralKit is no longer called: data comes from a one-time pk;export upload at /admin/members. On first run the site copies users, sessions, tags, statuses, pride, relationships and mental state from the old api Worker through the HUB binding, which also carries live-update broadcasts to /v2/ws. Adds member create, edit and delete, system edit, switch history and switch delete, and serves copied avatars and banners from R2. Co-Authored-By: Sandrone <[email protected]>
diff --git a/bun.lock b/bun.lock
index 02d2d3b..f30d988 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,9 +5,12 @@
"": {
"name": "doughmination-system",
"dependencies": {
+ "@hono/zod-openapi": "^1.6.3",
"doughmination-api": "^1.6.0",
+ "hono": "^4.13.18",
"iconsax": "^0.1.1",
"simple-icons": "npm:@icons-pack/svelte-simple-icons@^7.2.0",
+ "zod": "^4.6.7",
},
"devDependencies": {
"@cloudflare/workers-types": "^5.20261029.1",
@@ -23,6 +26,8 @@
},
},
"packages": {
+ "@asteasolutions/zod-to-openapi": ["@asteasolutions/[email protected]", "", { "dependencies": { "openapi3-ts": "^4.6.0" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-pLMeRgRYS7/vZIgAAkOe2P6+XGTifR1MT9pqDoxZ11EmcJJ+DPmdPqLN8ZZF4U8R9KHCCQCS9c2wtuE8wSrfkw=="],
+
"@cloudflare/kv-asset-handler": ["@cloudflare/[email protected]", "", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="],
"@cloudflare/unenv-preset": ["@cloudflare/[email protected]", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ=="],
@@ -95,6 +100,10 @@
"@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="],
+ "@hono/zod-openapi": ["@hono/[email protected]", "", { "dependencies": { "@asteasolutions/zod-to-openapi": "^9.1.0", "@hono/zod-validator": "^0.9.1", "openapi3-ts": "^4.5.0" }, "peerDependencies": { "hono": ">=4.10.0", "zod": "^4.0.0" } }, "sha512-VYR82Y60plu8g3pN60OUXMVKpmxh3R04Qs++3DY9vtwZ9/sA/BRY0PcRIR+Z37/3itWtM7pYwT9bKiH9JhqV6Q=="],
+
+ "@hono/zod-validator": ["@hono/[email protected]", "", { "peerDependencies": { "hono": ">=4.11.2", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-iiv6w0qrIc0arfvCtUqBWsvl4fXjzaTcQcCJTTtCnkawF9HHGE+KjEl0ox3gQJ6rKZEgE3mLExlQCF72M+mNuw=="],
+
"@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
"@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="],
@@ -257,6 +266,8 @@
"fsevents": ["[email protected]", "", { "os": "darwin", "hasInstallScript": true }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
+ "hono": ["[email protected]", "", {}, "sha512-H9q/E1XizaWstJxUW881dmLxEj+t/TrGGnyxINkm4+sK0qUwsMtFdo2BWI9Vs3cIS19MU6b6iCijoUoEf4f3DA=="],
+
"iconsax": ["[email protected]", "", { "bin": { "iconsax": "bin/iconsax.js" } }, "sha512-/HXomG+SuhytKH/Yw4ZdunDGyWP02Osuk/pjony1k9CCMOsg7dUpnomu7HZUOHNu0yK0b3phErjH2IgUTJFjPA=="],
"is-reference": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.6" } }, "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw=="],
@@ -301,6 +312,8 @@
"obug": ["[email protected]", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="],
+ "openapi3-ts": ["[email protected]", "", { "dependencies": { "yaml": "^2.9.1" } }, "sha512-gyyil3DweqhXiEhTqtAs9wwRLfWHmetwhI4kmM5Rn0d6gtmK863Ki7qqbQnp9+Wwlqoe3B1LFWj7kMp5ctE4rQ=="],
+
"path-to-regexp": ["[email protected]", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="],
"pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
@@ -357,12 +370,16 @@
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],
+ "yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="],
+
"youch": ["[email protected]", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="],
"youch-core": ["[email protected]", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="],
"zimmerframe": ["[email protected]", "", {}, "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA=="],
+ "zod": ["[email protected]", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="],
+
"@cspotcode/source-map-support/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="],
"svelte/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
diff --git a/migrations/0001_initial.sql b/migrations/0001_initial.sql
new file mode 100644
index 0000000..2acb7dc
--- /dev/null
+++ b/migrations/0001_initial.sql
@@ -0,0 +1,62 @@
+-- migrations/0001_initial.sql
+-- 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.
+
+-- JSON blobs carried over from the old Durable Object store:
+-- users, member_tags, member_status, member_pride, member_relationships,
+-- mental_state, and short-lived oidc_state / app_code / sso_session entries
+CREATE TABLE kv (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+);
+
+CREATE TABLE systems (
+ id TEXT PRIMARY KEY,
+ uuid TEXT NOT NULL UNIQUE,
+ name TEXT,
+ description TEXT,
+ tag TEXT,
+ pronouns TEXT,
+ avatar_url TEXT,
+ banner TEXT,
+ color TEXT,
+ timezone TEXT,
+ created TEXT NOT NULL,
+ privacy TEXT NOT NULL DEFAULT '{}'
+);
+
+CREATE TABLE members (
+ id TEXT PRIMARY KEY,
+ uuid TEXT NOT NULL UNIQUE,
+ system_id TEXT NOT NULL REFERENCES systems(id),
+ name TEXT NOT NULL,
+ display_name TEXT,
+ color TEXT,
+ birthday TEXT,
+ pronouns TEXT,
+ avatar_url TEXT,
+ webhook_avatar_url TEXT,
+ banner TEXT,
+ description TEXT,
+ created TEXT NOT NULL,
+ -- Kept for the future proxy bot: [{ "prefix": "c:", "suffix": null }]
+ proxy_tags TEXT NOT NULL DEFAULT '[]',
+ keep_proxy INTEGER NOT NULL DEFAULT 0,
+ autoproxy_enabled INTEGER,
+ message_count INTEGER NOT NULL DEFAULT 0,
+ last_message_timestamp TEXT,
+ privacy TEXT NOT NULL DEFAULT '{}'
+);
+
+CREATE INDEX members_system ON members (system_id);
+
+CREATE TABLE switches (
+ id TEXT PRIMARY KEY,
+ system_id TEXT NOT NULL REFERENCES systems(id),
+ timestamp TEXT NOT NULL,
+ -- JSON array of member ids, in front order
+ members TEXT NOT NULL
+);
+
+CREATE INDEX switches_system_time ON switches (system_id, timestamp DESC);
diff --git a/package.json b/package.json
index 0e27f84..8a75760 100644
--- a/package.json
+++ b/package.json
@@ -16,9 +16,12 @@
"#lib/*": "./src/lib/*"
},
"dependencies": {
+ "@hono/zod-openapi": "^1.6.3",
"doughmination-api": "^1.6.0",
+ "hono": "^4.13.18",
"iconsax": "^0.1.1",
- "simple-icons": "npm:@icons-pack/svelte-simple-icons@^7.2.0"
+ "simple-icons": "npm:@icons-pack/svelte-simple-icons@^7.2.0",
+ "zod": "^4.6.7"
},
"devDependencies": {
"@cloudflare/workers-types": "^5.20261029.1",
diff --git a/src/app.d.ts b/src/app.d.ts
index e7e60ee..91a5cc8 100644
--- a/src/app.d.ts
+++ b/src/app.d.ts
@@ -4,6 +4,8 @@
* See LICENCE.md in the project root for full licence information.
*/
+import type { PluralEnv } from "#lib/server/plural/types.ts";
+
declare global {
namespace App {
interface Error {
@@ -17,8 +19,8 @@ declare global {
}
}
- // Bindings; none yet beyond the static assets
- interface Env {
+ // Static assets plus the plural API's bindings, vars and secrets
+ interface Env extends PluralEnv {
ASSETS: Fetcher;
}
}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 8f2aaee..761657b 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -5,6 +5,7 @@
*/
import { DoughminationClient } from "doughmination-api/server";
+import { siteUrl } from "./index.ts";
const TOKEN_KEY = "token";
@@ -27,13 +28,25 @@ export function writeToken(token: string | null) {
}
}
+// The API lives on this site, at /api
+export function apiBase(origin: string): string {
+ return `${origin}/api`;
+}
+
+// Live updates come from the shared hub on the api Worker
+export const socketUrl = "wss://doughmination.uk/v2/ws";
+
/** A client for load functions: SvelteKit's fetch, no token */
-export function publicClient(fetcher: typeof fetch): DoughminationClient {
- return new DoughminationClient({ fetch: fetcher });
+export function publicClient(fetcher: typeof fetch, origin: string): DoughminationClient {
+ return new DoughminationClient({
+ fetch: fetcher,
+ baseUrl: apiBase(origin),
+ });
}
/** The browser's client: every request carries the current token */
export const client = new DoughminationClient({
+ baseUrl: apiBase(typeof location === "undefined" ? siteUrl : location.origin),
token: () => readToken(),
});
diff --git a/src/lib/live.svelte.ts b/src/lib/live.svelte.ts
index 5ee7a40..20dc7c6 100644
--- a/src/lib/live.svelte.ts
+++ b/src/lib/live.svelte.ts
@@ -5,7 +5,7 @@
*/
import { invalidate } from "$app/navigation";
-import { client } from "./api.ts";
+import { socketUrl } from "./api.ts";
// The API's socket: fronters and mental state changes, and admin "reload everyone"
const PING_MS = 30_000;
@@ -23,7 +23,7 @@ class Live {
connect() {
if (this.socket || typeof WebSocket === "undefined") return;
- const socket = new WebSocket(client.socketUrl);
+ const socket = new WebSocket(socketUrl);
this.socket = socket;
this.status = this.attempts > 0 ? "reconnecting" : "connecting";
diff --git a/src/lib/server/plural/app.ts b/src/lib/server/plural/app.ts
new file mode 100644
index 0000000..6e3a5d9
--- /dev/null
+++ b/src/lib/server/plural/app.ts
@@ -0,0 +1,113 @@
+/* src/lib/server/plural/app.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 { OpenAPIHono } from "@hono/zod-openapi";
+import { cors } from "hono/cors";
+
+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";
+import { membersRoutes } from "./routes/members";
+import { memberStatusRoutes } from "./routes/member_status";
+import { relationshipsRoutes } from "./routes/relationships";
+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
+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;
+ console.error(`Admin seed failed: ${String(err)}`);
+ }
+}
+
+const plural = new OpenAPIHono<Env>();
+plural.route("/", authRoutes);
+plural.route("/", systemRoutes);
+plural.route("/", membersRoutes);
+plural.route("/", memberStatusRoutes);
+plural.route("/", relationshipsRoutes);
+plural.route("/", frontingRoutes);
+plural.route("/", usersRoutes);
+plural.route("/", metricsRoutes);
+plural.route("/", adminRoutes);
+plural.route("/", botRoutes);
+
+export const app = new OpenAPIHono<Env>().basePath("/api");
+
+app.use(
+ "*",
+ cors({
+ origin: (origin) => (isLocalhostOrigin(origin) || corsOrigins().includes(origin) ? origin : ""),
+ credentials: true,
+ allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
+ }),
+);
+
+app.use("*", async (_c, next) => {
+ await ensureSeeded();
+ await next();
+});
+
+app.onError((err, c) => {
+ if (err instanceof HttpError) {
+ for (const [name, value] of Object.entries(err.headers ?? {})) c.header(name, value);
+ return c.json({ detail: err.message }, err.statusCode as never);
+ }
+ console.error("Unhandled error:", err);
+ return c.json({ detail: "Internal server error" }, 500);
+});
+
+app.route("/plural", plural);
+
+app.openAPIRegistry.registerComponent("securitySchemes", "bearerAuth", {
+ type: "http",
+ scheme: "bearer",
+ bearerFormat: "JWT",
+ 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: {
+ title: "Doughmination System API",
+ version: "3.0.0",
+ description:
+ "The plural system behind doughmination.co.uk. Live updates (fronters_update, mental_state_update, force_refresh) " +
+ "arrive on the WebSocket at wss://doughmination.uk/v2/ws.",
+ },
+ servers: [
+ {
+ url: "https://doughmination.co.uk",
+ },
+ ],
+});
+
+app.notFound((c) => c.json({ detail: "Unknown route." }, 404));
diff --git a/src/lib/server/plural/config.ts b/src/lib/server/plural/config.ts
new file mode 100644
index 0000000..618c49b
--- /dev/null
+++ b/src/lib/server/plural/config.ts
@@ -0,0 +1,101 @@
+/* src/lib/server/plural/config.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 { rt } from "./runtime";
+
+export const JWT_ALGORITHM = "HS256" as const;
+
+// 24 hours
+export const ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24;
+
+// How long an in-flight authorization request (state + PKCE verifier) stays valid
+export const OIDC_STATE_TTL_MINUTES = 10;
+
+export function jwtSecret(): string {
+ const secret = rt().env.JWT_SECRET;
+ // Never sign with a guessable default in production
+ if (!secret) throw new Error("JWT_SECRET is not set");
+ return secret;
+}
+
+export function adminUsername(): string {
+ return rt().env.ADMIN_USERNAME ?? "admin";
+}
+
+export function adminDisplayName(): string {
+ return rt().env.ADMIN_DISPLAY_NAME ?? "Administrator";
+}
+
+// Backfilled onto the owner account on read when it has no email yet
+export function adminEmail(): string | undefined {
+ const value = rt().env.ADMIN_EMAIL?.trim().toLowerCase();
+ return value || undefined;
+}
+
+export function frontendUrl(): string {
+ return (rt().env.FRONTEND_URL ?? "https://doughmination.co.uk").replace(/\/+$/, "");
+}
+
+// ---- Doughmination SSO (OpenID Connect), the only login method ----
+
+export function ssoIssuer(): string {
+ return (rt().env.SSO_ISSUER ?? "").replace(/\/+$/, "");
+}
+
+export function ssoClientId(): string | undefined {
+ return rt().env.SSO_CLIENT_ID;
+}
+
+export function ssoClientSecret(): string | undefined {
+ return rt().env.SSO_CLIENT_SECRET;
+}
+
+export function ssoRedirectUri(): string {
+ return rt().env.SSO_REDIRECT_URI ?? `${frontendUrl()}/api/plural/auth/sso/callback`;
+}
+
+export function ssoScopes(): string {
+ return rt().env.SSO_SCOPES ?? "openid profile email offline_access";
+}
+
+// The token is appended in the URL fragment so it never hits a server log
+export function ssoPostLoginUrl(): string {
+ const configured = rt().env.SSO_POST_LOGIN_URL;
+ if (configured) return configured.replace(/\/+$/, "");
+ return `${frontendUrl()}/user/login/callback`;
+}
+
+export function ssoLoginErrorUrl(): string {
+ return `${frontendUrl()}/user/login`;
+}
+
+export function ssoPostLogoutRedirectUri(): string {
+ return rt().env.SSO_POST_LOGOUT_REDIRECT_URI ?? `${frontendUrl()}/`;
+}
+
+// ---- CORS ----
+
+// Local dev servers on any port are always allowed
+export function isLocalhostOrigin(origin: string): boolean {
+ return /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(origin);
+}
+
+export function corsOrigins(): string[] {
+ const defaults = [
+ "https://doughmination.uk",
+ "https://doughmination.co.uk",
+ "https://doughmination.gay",
+ "https://vibecoded.doughmination.gay",
+ "https://www.doughmination.gay",
+ "https://is.doughmination.gay",
+ "https://c.stupid.cat",
+ ];
+ const extra = (rt().env.CORS_ORIGINS ?? "")
+ .split(",")
+ .map((origin) => origin.trim())
+ .filter(Boolean);
+ return [...new Set([...defaults, ...extra])];
+}
diff --git a/src/lib/server/plural/datetime.ts b/src/lib/server/plural/datetime.ts
new file mode 100644
index 0000000..144fb15
--- /dev/null
+++ b/src/lib/server/plural/datetime.ts
@@ -0,0 +1,46 @@
+/* src/lib/server/plural/datetime.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.
+ */
+
+/** Parse an ISO-8601 timestamp, tolerating excess fractional-second digits
+ * and missing offsets (naive input is treated as UTC). Ported verbatim. */
+
+const TIMESTAMP_PATTERN = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d+)?([+-]\d{2}:\d{2})?$/;
+
+export function parseTimestamp(timestampStr: string): Date {
+ let s = timestampStr;
+ const hadExplicitTz = /[zZ]$|[+-]\d{2}:\d{2}$/.test(s);
+
+ if (s.endsWith("Z") || s.endsWith("z")) {
+ s = `${s.slice(0, -1)}+00:00`;
+ }
+
+ const match = s.match(TIMESTAMP_PATTERN);
+ if (match) {
+ const [, base, frac, tz] = match;
+ const fracPart = frac ? frac.slice(0, 4) : "";
+ s = `${base}${fracPart}${tz ?? ""}`;
+ }
+
+ const dt = new Date(s);
+ if (Number.isNaN(dt.getTime())) {
+ throw new Error(`Could not parse timestamp: ${timestampStr}`);
+ }
+
+ if (!hadExplicitTz) {
+ return new Date(
+ Date.UTC(
+ dt.getFullYear(),
+ dt.getMonth(),
+ dt.getDate(),
+ dt.getHours(),
+ dt.getMinutes(),
+ dt.getSeconds(),
+ dt.getMilliseconds(),
+ ),
+ );
+ }
+ return dt;
+}
diff --git a/src/lib/server/plural/errors.ts b/src/lib/server/plural/errors.ts
new file mode 100644
index 0000000..de7bfcd
--- /dev/null
+++ b/src/lib/server/plural/errors.ts
@@ -0,0 +1,22 @@
+/* src/lib/server/plural/errors.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.
+ */
+
+/**
+ * Lightweight HTTP error, thrown anywhere in the system API and translated
+ * into a JSON `{ detail }` response by the Hono error handler (see app.ts).
+ * Mirrors the old Express HttpError so ported handlers read identically.
+ */
+export class HttpError extends Error {
+ public readonly statusCode: number;
+ public readonly headers?: Record<string, string>;
+
+ constructor(statusCode: number, detail: string, headers?: Record<string, string>) {
+ super(detail);
+ this.name = "HttpError";
+ this.statusCode = statusCode;
+ this.headers = headers;
+ }
+}
diff --git a/src/lib/server/plural/hono.ts b/src/lib/server/plural/hono.ts
new file mode 100644
index 0000000..b030a4e
--- /dev/null
+++ b/src/lib/server/plural/hono.ts
@@ -0,0 +1,16 @@
+/* src/lib/server/plural/hono.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 type { Hono } from "hono";
+import type { User } from "./models";
+
+/** Variables carried on the Hono context (set by auth middleware). */
+export type Variables = {
+ user?: User;
+};
+
+export type Env = { Variables: Variables };
+export type App = Hono<Env>;
diff --git a/src/lib/server/plural/middleware/auth.ts b/src/lib/server/plural/middleware/auth.ts
new file mode 100644
index 0000000..1e5e2b1
--- /dev/null
+++ b/src/lib/server/plural/middleware/auth.ts
@@ -0,0 +1,118 @@
+/* src/lib/server/plural/middleware/auth.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.
+ */
+
+/**
+ * Auth middleware, ported from the Express dependencies. On success the
+ * resolved user is attached with `c.set("user", user)` (the Hono analogue
+ * of `req.user`). Failures throw HttpError, translated by app.onError.
+ */
+
+import type { Context, Next } from "hono";
+import type { Env } from "../hono";
+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 {
+ const header = c.req.header("Authorization");
+ if (!header) return undefined;
+ const parts = header.split(" ");
+ const [scheme, token] = parts;
+ if (parts.length !== 2 || scheme?.toLowerCase() !== "bearer") return undefined;
+ return token;
+}
+
+async function resolveCurrentUser(c: Context<Env>): Promise<User> {
+ const token = extractBearer(c);
+ if (!token) {
+ throw new HttpError(401, "Not authenticated", { "WWW-Authenticate": "Bearer" });
+ }
+
+ const payload = await decodeAccessToken(token);
+ const username = payload.sub;
+ if (!username || typeof username !== "string") {
+ throw new HttpError(401, "Invalid token", { "WWW-Authenticate": "Bearer" });
+ }
+
+ // Every token belongs to an SSO-backed session: logging out, the session
+ // expiring, or the SSO no longer vouching for the account all end it here.
+ // Tokens from before sessions existed carry no sid and must sign in again.
+ const session = typeof payload.sid === "string" ? await currentSsoSession(payload.sid) : null;
+ if (!session || session.username.toLowerCase() !== username.toLowerCase()) {
+ throw new HttpError(401, "Session ended. Please sign in again.", { "WWW-Authenticate": "Bearer" });
+ }
+
+ const user = await getUserByUsername(username);
+ if (!user) {
+ throw new HttpError(401, "User not found", { "WWW-Authenticate": "Bearer" });
+ }
+ return user;
+}
+
+/** Require an authenticated user. */
+export async function requireAuth(c: Context<Env>, next: Next): Promise<void> {
+ c.set("user", await resolveCurrentUser(c));
+ await next();
+}
+
+/** Attach user if authenticated, otherwise leave undefined. Never rejects. */
+export async function optionalAuth(c: Context<Env>, next: Next): Promise<void> {
+ try {
+ c.set("user", await resolveCurrentUser(c));
+ } catch {
+ // ignore
+ }
+ await next();
+}
+
+export async function requireAdmin(c: Context<Env>, next: Next): Promise<void> {
+ const user = c.get("user") as User | undefined;
+ if (!user?.is_admin) throw new HttpError(403, "Admin privileges required");
+ await next();
+}
+
+export async function requireOwner(c: Context<Env>, next: Next): Promise<void> {
+ const user = c.get("user") as User | undefined;
+ if (!user?.is_owner) throw new HttpError(403, "Owner privileges required");
+ await next();
+}
+
+export async function requirePet(c: Context<Env>, next: Next): Promise<void> {
+ const user = c.get("user") as User | undefined;
+ 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
new file mode 100644
index 0000000..4ccf383
--- /dev/null
+++ b/src/lib/server/plural/models.ts
@@ -0,0 +1,123 @@
+/* src/lib/server/plural/models.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.
+ */
+
+/**
+ * zod models + types. Field names stay snake_case to match the existing
+ * data blobs and the frontend wire format. Consolidated from the old
+ * models/user.ts + models/index.ts.
+ */
+
+import { z } from "zod";
+
+// ============================================================================
+// USER MODELS
+// ============================================================================
+
+/** Emails are stored lowercased and trimmed so uniqueness checks are stable. */
+export const EmailSchema = z
+ .string()
+ .trim()
+ .toLowerCase()
+ .email("Must be a valid email address")
+ .max(254, "Email address is too long");
+
+export const UserSchema = z.object({
+ id: z.string(),
+ username: z.string(),
+ /**
+ * The OIDC subject (`sub`) this account is linked to. The field keeps its
+ * original name so stored records load unchanged: accounts linked before the
+ * move to the Doughmination SSO hold a PocketID subject here.
+ * Optional so the owner seed and pre-link accounts still load.
+ */
+ pocket_id: z.string().nullable().optional(),
+ /**
+ * Issuer that `pocket_id` belongs to. Null/absent = linked before the SSO
+ * move (or never linked), which is what lets the first SSO sign-in adopt the
+ * account by username exactly once.
+ */
+ sso_issuer: z.string().nullable().optional(),
+ /**
+ * Legacy PBKDF2 hash from the retired password login. Kept optional purely
+ * so old stored records still parse; it is never read or written any more.
+ */
+ password_hash: z.string().nullable().optional(),
+ display_name: z.string().nullable().optional(),
+ /** Email address, populated from the SSO `email` claim when available. */
+ email: z.string().nullable().optional(),
+ /** ISO timestamp of account creation. Absent on legacy accounts. */
+ created_at: z.string().nullable().optional(),
+ is_admin: z.boolean().default(false),
+ is_owner: z.boolean().default(false),
+ is_pet: z.boolean().default(false),
+ avatar_url: z.string().nullable().optional(),
+});
+export type User = z.infer<typeof UserSchema>;
+
+export const UserCreateSchema = z.object({
+ username: z.string(),
+ /** Set when an admin pre-provisions an account before its first SSO login
+ * (the SSO subject id); normally the link is established automatically. */
+ pocket_id: z.string().nullable().optional(),
+ email: EmailSchema.nullable().optional(),
+ display_name: z.string().nullable().optional(),
+ is_admin: z.boolean().default(false),
+ is_pet: z.boolean().default(false),
+});
+export type UserCreate = z.infer<typeof UserCreateSchema>;
+
+export const UserResponseSchema = z.object({
+ id: z.string(),
+ username: z.string(),
+ display_name: z.string().nullable().optional(),
+ email: z.string().nullable().optional(),
+ created_at: z.string().nullable().optional(),
+ is_admin: z.boolean().default(false),
+ is_owner: z.boolean().default(false),
+ is_pet: z.boolean().default(false),
+ avatar_url: z.string().nullable().optional(),
+});
+export type UserResponse = z.infer<typeof UserResponseSchema>;
+
+export const UserUpdateSchema = z.object({
+ display_name: z.string().nullable().optional(),
+ avatar_url: z.string().nullable().optional(),
+ /**
+ * Profile email. Changeable by the account's own user or by an admin/owner.
+ * There is no confirmation step any more — identity is proven by the SSO,
+ * so this field is purely informational/contact metadata.
+ */
+ email: EmailSchema.nullable().optional(),
+ is_admin: z.boolean().nullable().optional(),
+ is_pet: z.boolean().nullable().optional(),
+});
+export type UserUpdate = z.infer<typeof UserUpdateSchema>;
+
+/** Strip internal-only fields for public-facing responses. */
+export function toUserResponse(user: User): UserResponse {
+ const { password_hash: _pw, pocket_id: _sub, sso_issuer: _iss, ...rest } = user;
+ return rest;
+}
+
+// ============================================================================
+// SYSTEM / MENTAL STATE
+// ============================================================================
+
+export const MentalStateSchema = z.object({
+ level: z.string(),
+ updated_at: z.coerce.date().default(() => new Date()),
+ notes: z.string().nullable().optional(),
+});
+export type MentalState = z.infer<typeof MentalStateSchema>;
+
+// ============================================================================
+// BOT MODELS
+// ============================================================================
+
+export const MultiSwitchRequestSchema = z.object({
+ member_ids: z.array(z.string()),
+});
+export type MultiSwitchRequest = z.infer<typeof MultiSwitchRequestSchema>;
diff --git a/src/lib/server/plural/openapi.ts b/src/lib/server/plural/openapi.ts
new file mode 100644
index 0000000..bb6278b
--- /dev/null
+++ b/src/lib/server/plural/openapi.ts
@@ -0,0 +1,72 @@
+/* src/lib/server/plural/openapi.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 { OpenAPIHono, type z } from "@hono/zod-openapi";
+
+import type { Env } from "./hono";
+import { ErrorSchema } from "./schemas";
+
+const errorBody = {
+ content: {
+ "application/json": {
+ schema: ErrorSchema,
+ },
+ },
+};
+
+export const errorResponses = {
+ 400: { ...errorBody, description: "Bad request" },
+ 401: { ...errorBody, description: "Not signed in, or the token is invalid" },
+ 403: { ...errorBody, description: "Signed in, but missing the required role" },
+ 404: { ...errorBody, description: "Not found" },
+ 422: { ...errorBody, description: "The body or query failed validation" },
+} as const;
+
+// A 200 JSON response plus the shared error responses
+export function ok<T extends z.ZodType>(schema: T, description = "OK") {
+ return {
+ 200: {
+ content: {
+ "application/json": {
+ schema,
+ },
+ },
+ description,
+ },
+ ...errorResponses,
+ };
+}
+
+export function jsonBody<T extends z.ZodType>(schema: T) {
+ return {
+ body: {
+ required: true,
+ content: {
+ "application/json": {
+ schema,
+ },
+ },
+ },
+ };
+}
+
+export const signedIn = [{ bearerAuth: [] }];
+export const botAuth = [{ botAuth: [] }];
+
+function issuesText(issues: ReadonlyArray<{ path: PropertyKey[]; message: string }>): string {
+ return issues
+ .map((issue) => (issue.path.length ? `${issue.path.map(String).join(".")}: ${issue.message}` : issue.message))
+ .join("; ");
+}
+
+// Every route group uses this, so validation failures all come back as 422 { detail }
+export function router() {
+ return new OpenAPIHono<Env>({
+ defaultHook: (result, c) => {
+ if (!result.success) return c.json({ detail: issuesText(result.error.issues) }, 422);
+ },
+ });
+}
diff --git a/src/lib/server/plural/routes/admin.ts b/src/lib/server/plural/routes/admin.ts
new file mode 100644
index 0000000..00fbcb8
--- /dev/null
+++ b/src/lib/server/plural/routes/admin.ts
@@ -0,0 +1,127 @@
+/* src/lib/server/plural/routes/admin.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, 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 { rt } from "../runtime";
+
+export const adminRoutes = router();
+
+adminRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/admin/refresh",
+ tags: ["Admin"],
+ summary: "Reload every open page (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ await broadcastFrontendUpdate("force_refresh", { message: "Admin initiated refresh" });
+ return c.json({ success: true, message: "Refresh broadcast sent" }, 200);
+ },
+);
+
+adminRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/admin/import/pluralkit",
+ tags: ["Admin"],
+ summary: "Import a PluralKit export file (owner). Images are copied into this site's storage",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ request: {
+ query: z.object({
+ replace: z
+ .enum(["true", "false"])
+ .default("false")
+ .openapi({ description: "Overwrite an already-imported system, members and switch history" }),
+ copy_media: z.enum(["true", "false"]).default("true"),
+ }),
+ ...jsonBody(z.looseObject({}).openapi({ description: "The JSON file from pk;export, unchanged" })),
+ },
+ responses: ok(
+ z.object({
+ system: z.string(),
+ members: z.number(),
+ switches: z.number(),
+ media_copied: z.number(),
+ media_failed: z.array(z.string()),
+ }),
+ ),
+ }),
+ async (c) => {
+ const query = c.req.valid("query");
+ const report = await importPluralKitExport(c.req.valid("json"), {
+ replace: query.replace === "true",
+ copyMedia: query.copy_media === "true",
+ });
+ return c.json(report, 200);
+ },
+);
+
+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({
+ method: "get",
+ path: "/media/{key}",
+ tags: ["Media"],
+ summary: "A stored avatar or banner",
+ request: {
+ params: z.object({
+ key: z
+ .string()
+ .regex(/^[a-z0-9_-]+$/)
+ .openapi({ example: "member-abcdef-avatar_url" }),
+ }),
+ },
+ responses: {
+ 200: {
+ description: "The image",
+ content: {
+ "image/*": {
+ schema: z.string().openapi({ format: "binary" }),
+ },
+ },
+ },
+ },
+ }),
+ async (c) => {
+ const { key } = c.req.valid("param");
+ const object = await rt().env.MEDIA.get(key);
+ if (!object) return c.json({ detail: "Not found" }, 404) as never;
+
+ const headers = new Headers();
+ object.writeHttpMetadata(headers);
+ headers.set("ETag", object.httpEtag);
+ headers.set("Cache-Control", "public, max-age=86400");
+ return new Response(object.body, { headers }) as never;
+ },
+);
diff --git a/src/lib/server/plural/routes/auth.ts b/src/lib/server/plural/routes/auth.ts
new file mode 100644
index 0000000..221e08d
--- /dev/null
+++ b/src/lib/server/plural/routes/auth.ts
@@ -0,0 +1,260 @@
+/* src/lib/server/plural/routes/auth.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.
+ */
+
+// Doughmination SSO (OpenID Connect) is the only login.
+// Native apps start with ?app=<S256 challenge>, get a one-time code back on
+// gay.doughmination.plural://auth, and swap it at /auth/app/token with their verifier.
+// /auth/pocketid/* stay as aliases because the published client still builds those URLs.
+
+import { createRoute, z } from "@hono/zod-openapi";
+import type { Context } from "hono";
+
+import type { Env } from "../hono";
+import { router, ok, jsonBody, signedIn } from "../openapi";
+import { UserSchema } from "../schemas";
+import { toUserResponse, type User } from "../models";
+import { findOrCreateFromSso } from "../services/users";
+import { beginLogin, completeLogin, endSessionUrl, isAppLogin, revokeRefreshToken } from "../services/oidc";
+import { APP_CODE, PKCE_CHALLENGE, PKCE_VERIFIER, saveAppCode, takeAppCode } from "../services/app_codes";
+import { createSsoSession, endSsoSession } from "../services/sso_sessions";
+import { ssoPostLoginUrl, ssoLoginErrorUrl, ACCESS_TOKEN_EXPIRE_MINUTES } from "../config";
+import { createAccessToken, decodeAccessToken } from "../security";
+import { requireAuth } from "../middleware/auth";
+import { HttpError } from "../errors";
+
+export const authRoutes = router();
+
+// Where an app-started login lands; the Plural Android app handles this scheme
+const APP_REDIRECT = "gay.doughmination.plural://auth";
+
+// Only a path starting with a single "/" — never "//host", "/\host" or a full URL
+function safeReturnPath(raw: string | undefined): string {
+ if (!raw) return "/";
+ if (!raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return "/";
+ return raw;
+}
+
+function loginError(c: Context<Env>, message: string, app = false) {
+ const url = new URL(app ? APP_REDIRECT : ssoLoginErrorUrl());
+ url.searchParams.set("error", message);
+ return c.redirect(url.toString(), 302);
+}
+
+async function login(c: Context<Env>) {
+ const from = safeReturnPath(c.req.query("from"));
+ const app = c.req.query("app");
+ if (app !== undefined && !PKCE_CHALLENGE.test(app)) {
+ throw new HttpError(400, "'app' must be an S256 PKCE challenge.");
+ }
+ return c.redirect(await beginLogin(from, app), 302);
+}
+
+async function callback(c: Context<Env>) {
+ const code = c.req.query("code");
+ const state = c.req.query("state");
+ // Errors go back to whoever started the login: the app or the website
+ const app = await isAppLogin(state);
+
+ const errorParam = c.req.query("error");
+ if (errorParam === "access_denied") {
+ return loginError(c, "Your SSO account isn't allowed to use this site.", app);
+ }
+ if (errorParam) return loginError(c, errorParam, app);
+ if (!code || !state) return loginError(c, "missing_code", app);
+
+ let result;
+ try {
+ result = await completeLogin(code, state, c.req.query("iss"));
+ } catch (err) {
+ return loginError(c, err instanceof Error ? err.message : "Login failed. Please try again.", app);
+ }
+
+ const { identity, tokens, from, appChallenge } = result;
+
+ let user: User;
+ try {
+ user = await findOrCreateFromSso({
+ sub: identity.sub,
+ issuer: identity.issuer,
+ username: identity.preferredUsername,
+ email: identity.email,
+ displayName: identity.displayName,
+ });
+ } catch (err) {
+ return loginError(c, err instanceof Error ? err.message : "Could not sign you in.", app);
+ }
+
+ const expiresAt = Date.now() + ACCESS_TOKEN_EXPIRE_MINUTES * 60 * 1000;
+ const sid = await createSsoSession(user, tokens, expiresAt);
+
+ const token = await createAccessToken({
+ sub: user.username,
+ id: user.id,
+ sid,
+ display_name: user.display_name,
+ admin: user.is_admin,
+ owner: user.is_owner,
+ pet: user.is_pet,
+ avatar_url: user.avatar_url ?? null,
+ });
+
+ // An app gets a one-time code, never the token: any app can claim a custom scheme
+ if (appChallenge) {
+ const appCode = await saveAppCode(token, appChallenge);
+ return c.redirect(`${APP_REDIRECT}?code=${encodeURIComponent(appCode)}`, 302);
+ }
+
+ // The fragment never reaches a server log or the Referer header
+ const dest = new URL(ssoPostLoginUrl());
+ dest.hash = `token=${encodeURIComponent(token)}&from=${encodeURIComponent(from)}`;
+ return c.redirect(dest.toString(), 302);
+}
+
+const redirect = {
+ 302: {
+ description: "Redirect",
+ },
+};
+
+const LoginQuery = z.object({
+ from: z.string().optional().openapi({ description: "Site path to return to after signing in" }),
+ app: z.string().optional().openapi({ description: "S256 PKCE challenge, for native apps only" }),
+});
+
+for (const path of ["/auth/sso/login", "/auth/pocketid/login"]) {
+ authRoutes.openapi(
+ createRoute({
+ method: "get",
+ path,
+ tags: ["Auth"],
+ summary: "Start an SSO sign-in",
+ request: {
+ query: LoginQuery,
+ },
+ responses: redirect,
+ }),
+ login as never,
+ );
+}
+
+for (const path of ["/auth/sso/callback", "/auth/pocketid/callback"]) {
+ authRoutes.openapi(
+ createRoute({
+ method: "get",
+ path,
+ tags: ["Auth"],
+ summary: "Where the SSO sends the browser back",
+ responses: redirect,
+ }),
+ callback as never,
+ );
+}
+
+authRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/auth/app/token",
+ tags: ["Auth"],
+ summary: "A native app swaps its one-time code and PKCE verifier for a token",
+ request: jsonBody(
+ z.object({
+ code: z.string().regex(APP_CODE),
+ verifier: z.string().regex(PKCE_VERIFIER),
+ }),
+ ),
+ responses: ok(
+ z.object({
+ access_token: z.string(),
+ token_type: z.literal("bearer"),
+ }),
+ ),
+ }),
+ async (c) => {
+ const { code, verifier } = c.req.valid("json");
+ const token = await takeAppCode(code, verifier);
+ c.header("Cache-Control", "no-store");
+ if (!token) throw new HttpError(400, "That sign-in code is invalid or has expired. Please sign in again.");
+ return c.json({ access_token: token, token_type: "bearer" as const }, 200);
+ },
+);
+
+// Accepts an expired token, so a stale tab can still sign out cleanly
+authRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/auth/logout",
+ tags: ["Auth"],
+ summary: "End the session here, and get the SSO's logout URL",
+ security: signedIn,
+ responses: ok(
+ z.object({
+ ok: z.boolean(),
+ end_session_url: z.string().nullable(),
+ }),
+ ),
+ }),
+ async (c) => {
+ const header = c.req.header("Authorization") ?? "";
+ const token = header.toLowerCase().startsWith("bearer ") ? header.slice(7).trim() : "";
+
+ let sid: string | null = null;
+ if (token) {
+ try {
+ const payload = await decodeAccessToken(token, { allowExpired: true });
+ sid = typeof payload.sid === "string" ? payload.sid : null;
+ } catch {
+ // Unverifiable token: nothing of ours to end
+ }
+ }
+
+ const session = sid ? await endSsoSession(sid) : null;
+ if (session?.refreshToken) {
+ await revokeRefreshToken(session.refreshToken).catch((err) =>
+ console.warn(`SSO refresh token revocation failed: ${String(err)}`),
+ );
+ }
+
+ let endSession: string | null = null;
+ try {
+ endSession = await endSessionUrl(session?.idToken ?? null);
+ } catch {
+ // SSO unreachable; the local session is gone regardless
+ }
+ return c.json({ ok: true, end_session_url: endSession }, 200);
+ },
+);
+
+authRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/user_info",
+ tags: ["Auth"],
+ summary: "The signed-in account",
+ security: signedIn,
+ middleware: [requireAuth] as const,
+ responses: ok(UserSchema),
+ }),
+ (c) => c.json(toUserResponse(c.get("user") as User), 200),
+);
+
+for (const [path, key, role] of [
+ ["/auth/is_admin", "isAdmin", "is_admin"],
+ ["/auth/is_pet", "isPet", "is_pet"],
+ ["/auth/is_owner", "isOwner", "is_owner"],
+] as const) {
+ authRoutes.openapi(
+ createRoute({
+ method: "get",
+ path,
+ tags: ["Auth"],
+ summary: `Whether the signed-in account has ${role}`,
+ security: signedIn,
+ middleware: [requireAuth] as const,
+ responses: ok(z.record(z.string(), z.boolean())),
+ }),
+ (c) => c.json({ [key]: Boolean(c.get("user")?.[role]) }, 200),
+ );
+}
diff --git a/src/lib/server/plural/routes/bot.ts b/src/lib/server/plural/routes/bot.ts
new file mode 100644
index 0000000..076ecf9
--- /dev/null
+++ b/src/lib/server/plural/routes/bot.ts
@@ -0,0 +1,141 @@
+/* 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
new file mode 100644
index 0000000..8503f1b
--- /dev/null
+++ b/src/lib/server/plural/routes/fronting.ts
@@ -0,0 +1,158 @@
+/* src/lib/server/plural/routes/fronting.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, signedIn } from "../openapi";
+import { FrontersSchema, MessageSchema, SwitchSchema } from "../schemas";
+import { deleteSwitch, getFronters, getMembers, getSwitches, setFront } from "../services/system";
+import { enrichMembersWithTags } from "../services/tags";
+import { enrichMembersWithStatus } from "../services/status";
+import { requireAuth, requireAdmin } from "../middleware/auth";
+import { broadcastFrontingUpdate } from "../ws";
+import { HttpError } from "../errors";
+import type { JsonObject } from "../types";
+
+export const frontingRoutes = router();
+
+type Fronters = z.infer<typeof FrontersSchema>;
+
+async function enrichedFronters(): Promise<Fronters> {
+ const fronters = await getFronters();
+ const withTags = await enrichMembersWithTags(fronters.members as JsonObject[]);
+ return { ...fronters, members: await enrichMembersWithStatus(withTags) } as Fronters;
+}
+
+// Switch, then tell every connected page. Shared with the bot routes
+export async function switchAndBroadcast(memberIds: string[]): Promise<Fronters> {
+ await setFront(memberIds);
+ const fronters = await enrichedFronters();
+ await broadcastFrontingUpdate(fronters);
+ return fronters;
+}
+
+frontingRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/fronters",
+ tags: ["Fronting"],
+ summary: "Who is fronting now",
+ responses: ok(FrontersSchema),
+ }),
+ async (c) => c.json(await enrichedFronters(), 200),
+);
+
+frontingRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/switches",
+ tags: ["Fronting"],
+ summary: "Switch history, newest first",
+ request: {
+ query: z.object({
+ limit: z.coerce.number().int().min(1).max(1000).default(100),
+ before: z.string().optional().openapi({ description: "Only switches before this ISO timestamp, for paging" }),
+ }),
+ },
+ responses: ok(z.array(SwitchSchema)),
+ }),
+ async (c) => {
+ const { limit, before } = c.req.valid("query");
+ return c.json((await getSwitches(limit, before)) as z.infer<typeof SwitchSchema>[], 200);
+ },
+);
+
+frontingRoutes.openapi(
+ createRoute({
+ method: "delete",
+ path: "/switches/{id}",
+ tags: ["Fronting"],
+ summary: "Delete a mistaken switch (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: {
+ params: z.object({ id: z.string() }),
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const { id } = c.req.valid("param");
+ if (!(await deleteSwitch(id))) throw new HttpError(404, "Switch not found");
+ await broadcastFrontingUpdate(await enrichedFronters());
+ return c.json({ status: "success", message: "Switch deleted" }, 200);
+ },
+);
+
+frontingRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/switch",
+ tags: ["Fronting"],
+ summary: "Set the front. An empty list means switch-out",
+ security: signedIn,
+ middleware: [requireAuth] as const,
+ request: jsonBody(z.object({ members: z.array(z.string()).default([]) })),
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ await switchAndBroadcast(c.req.valid("json").members);
+ return c.json({ status: "success", message: "Front updated successfully" }, 200);
+ },
+);
+
+frontingRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/switch_front",
+ tags: ["Fronting"],
+ summary: "Switch to a single member",
+ security: signedIn,
+ middleware: [requireAuth] as const,
+ request: jsonBody(z.object({ member_id: z.string().min(1, "member_id is required") })),
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const fronters = await switchAndBroadcast([c.req.valid("json").member_id]);
+ return c.json({ success: true, message: "Front updated", data: fronters }, 200);
+ },
+);
+
+frontingRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/multi_switch",
+ tags: ["Fronting"],
+ summary: "Switch to several members, echoing their names back",
+ security: signedIn,
+ middleware: [requireAuth] as const,
+ request: jsonBody(z.object({ member_ids: z.array(z.string()).default([]) })),
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const memberIds = c.req.valid("json").member_ids;
+ await switchAndBroadcast(memberIds);
+
+ const byId = new Map((await getMembers()).map((member) => [member.id, member]));
+ const fronters = memberIds
+ .map((id) => byId.get(id))
+ .filter((member): member is JsonObject => Boolean(member))
+ .map((member) => ({
+ id: member.id,
+ name: member.name,
+ display_name: member.display_name ?? member.name,
+ }));
+
+ return c.json(
+ {
+ status: "success",
+ message: "Fronters updated successfully",
+ fronters,
+ count: fronters.length,
+ },
+ 200,
+ );
+ },
+);
diff --git a/src/lib/server/plural/routes/member_status.ts b/src/lib/server/plural/routes/member_status.ts
new file mode 100644
index 0000000..a433a09
--- /dev/null
+++ b/src/lib/server/plural/routes/member_status.ts
@@ -0,0 +1,86 @@
+/* src/lib/server/plural/routes/member_status.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, signedIn } from "../openapi";
+import { IdentifierParam, MemberStatusSchema } from "../schemas";
+import { getMemberStatus, setMemberStatus, clearMemberStatus } from "../services/status";
+import { requireAuth, requireAdmin } from "../middleware/auth";
+
+export const memberStatusRoutes = router();
+
+const StatusResponse = z.object({
+ success: z.boolean(),
+ member_identifier: z.string().optional(),
+ message: z.string().optional(),
+ status: MemberStatusSchema.nullable().optional(),
+});
+
+memberStatusRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/members/{member_identifier}/status",
+ tags: ["Status"],
+ summary: "A member's status note",
+ request: {
+ params: IdentifierParam,
+ },
+ responses: ok(StatusResponse),
+ }),
+ async (c) => {
+ const identifier = c.req.valid("param").member_identifier;
+ return c.json({ success: true, member_identifier: identifier, status: await getMemberStatus(identifier) }, 200);
+ },
+);
+
+memberStatusRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/members/{member_identifier}/status",
+ tags: ["Status"],
+ summary: "Set a member's status note (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: {
+ params: IdentifierParam,
+ ...jsonBody(
+ z.object({
+ text: z.string().min(1, "Status text is required").max(100, "Status text must be 100 characters or less"),
+ emoji: z.string().nullable().optional(),
+ }),
+ ),
+ },
+ responses: ok(StatusResponse),
+ }),
+ async (c) => {
+ const identifier = c.req.valid("param").member_identifier;
+ const { text, emoji } = c.req.valid("json");
+ const status = await setMemberStatus(identifier, text, emoji ?? null);
+ return c.json({ success: true, message: `Status updated for ${identifier}`, status }, 200);
+ },
+);
+
+memberStatusRoutes.openapi(
+ createRoute({
+ method: "delete",
+ path: "/members/{member_identifier}/status",
+ tags: ["Status"],
+ summary: "Clear a member's status note (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: {
+ params: IdentifierParam,
+ },
+ responses: ok(StatusResponse),
+ }),
+ async (c) => {
+ const identifier = c.req.valid("param").member_identifier;
+ return (await clearMemberStatus(identifier))
+ ? c.json({ success: true, message: `Status cleared for ${identifier}` }, 200)
+ : c.json({ success: false, message: `No status found for ${identifier}` }, 200);
+ },
+);
diff --git a/src/lib/server/plural/routes/members.ts b/src/lib/server/plural/routes/members.ts
new file mode 100644
index 0000000..3dbae2c
--- /dev/null
+++ b/src/lib/server/plural/routes/members.ts
@@ -0,0 +1,277 @@
+/* src/lib/server/plural/routes/members.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, signedIn } from "../openapi";
+import {
+ IdentifierParam,
+ MemberCreateSchema,
+ MemberSchema,
+ MemberUpdateSchema,
+ MessageSchema,
+} from "../schemas";
+import { createMember, deleteMember, findMember, getMembers, updateMember } from "../services/system";
+import { getMemberTags, updateMemberTags, addMemberTag, removeMemberTag, enrichMembersWithTags } from "../services/tags";
+import { enrichMembersWithStatus } from "../services/status";
+import { getMemberPride, addMemberPride, removeMemberPride, enrichMembersWithPride } from "../services/pride";
+import { requireAuth, requireAdmin, requireOwner } from "../middleware/auth";
+import { HttpError } from "../errors";
+import type { JsonObject } from "../types";
+
+export const membersRoutes = router();
+
+type Member = z.infer<typeof MemberSchema>;
+
+async function enrichFully(members: JsonObject[]): Promise<Member[]> {
+ const withTags = await enrichMembersWithTags(members);
+ const withStatus = await enrichMembersWithStatus(withTags);
+ return (await enrichMembersWithPride(withStatus)) as Member[];
+}
+
+async function enrichOne(member: JsonObject): Promise<Member> {
+ const [enriched] = await enrichFully([member]);
+ return enriched as Member;
+}
+
+// ---- Members ----
+
+membersRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/members",
+ tags: ["Members"],
+ summary: "Every member, with tags, status and pride",
+ responses: ok(z.array(MemberSchema)),
+ }),
+ async (c) => c.json(await enrichFully(await getMembers()), 200),
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/member/{member_identifier}",
+ tags: ["Members"],
+ summary: "One member by id or name",
+ request: {
+ params: IdentifierParam,
+ },
+ responses: ok(MemberSchema),
+ }),
+ async (c) => {
+ const member = await findMember(c.req.valid("param").member_identifier);
+ if (!member) throw new HttpError(404, "Member not found");
+ return c.json(await enrichOne(member), 200);
+ },
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/members",
+ tags: ["Members"],
+ summary: "Create a member (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: jsonBody(MemberCreateSchema),
+ responses: ok(MemberSchema, "The new member"),
+ }),
+ async (c) => c.json(await enrichOne(await createMember(c.req.valid("json"))), 200),
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "patch",
+ path: "/members/{member_identifier}",
+ tags: ["Members"],
+ summary: "Edit a member (admin). Send only the fields to change; null clears one",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: {
+ params: IdentifierParam,
+ ...jsonBody(MemberUpdateSchema),
+ },
+ responses: ok(MemberSchema, "The updated member"),
+ }),
+ async (c) => {
+ const member = await updateMember(c.req.valid("param").member_identifier, c.req.valid("json"));
+ return c.json(await enrichOne(member), 200);
+ },
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "delete",
+ path: "/members/{member_identifier}",
+ tags: ["Members"],
+ summary: "Delete a member (owner). Their past switches are kept",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ request: {
+ params: IdentifierParam,
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const identifier = c.req.valid("param").member_identifier;
+ if (!(await deleteMember(identifier))) throw new HttpError(404, "Member not found");
+ return c.json({ status: "success", message: `Deleted ${identifier}` }, 200);
+ },
+);
+
+// ---- Member tags ----
+
+membersRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/member-tags",
+ tags: ["Tags"],
+ summary: "Every member's tags (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ responses: ok(
+ z.object({
+ status: z.string(),
+ member_tags: z.record(z.string(), z.array(z.string())),
+ }),
+ ),
+ }),
+ async (c) => c.json({ status: "success", member_tags: await getMemberTags() }, 200),
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/member-tags/{member_identifier}",
+ tags: ["Tags"],
+ summary: "Replace a member's tags (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: {
+ params: IdentifierParam,
+ ...jsonBody(z.array(z.string())),
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const identifier = c.req.valid("param").member_identifier;
+ const tags = c.req.valid("json");
+ await updateMemberTags(identifier, tags);
+ return c.json({ status: "success", message: `Updated tags for ${identifier}`, tags }, 200);
+ },
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/member-tags/{member_identifier}/add",
+ tags: ["Tags"],
+ summary: "Add one tag to a member (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: {
+ params: IdentifierParam,
+ ...jsonBody(z.object({ tag: z.string().min(1) })),
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const identifier = c.req.valid("param").member_identifier;
+ const { tag } = c.req.valid("json");
+ const added = await addMemberTag(identifier, tag);
+ return added
+ ? c.json({ status: "success", message: `Added tag '${tag}' to ${identifier}` }, 200)
+ : c.json({ status: "info", message: `Tag '${tag}' already exists for ${identifier}` }, 200);
+ },
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "delete",
+ path: "/member-tags/{member_identifier}/{tag}",
+ tags: ["Tags"],
+ summary: "Remove one tag from a member (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: {
+ params: IdentifierParam.extend({ tag: z.string() }),
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const { member_identifier: identifier, tag } = c.req.valid("param");
+ if (!(await removeMemberTag(identifier, tag))) {
+ throw new HttpError(404, `Tag '${tag}' not found for ${identifier}`);
+ }
+ return c.json({ status: "success", message: `Removed tag '${tag}' from ${identifier}` }, 200);
+ },
+);
+
+// ---- Member pride identities ----
+
+membersRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/member-pride",
+ tags: ["Pride"],
+ summary: "Every member's pride identities (owner)",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ responses: ok(
+ z.object({
+ status: z.string(),
+ member_pride: z.record(z.string(), z.array(z.string())),
+ }),
+ ),
+ }),
+ async (c) => c.json({ status: "success", member_pride: await getMemberPride() }, 200),
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/member-pride/{member_identifier}/add",
+ tags: ["Pride"],
+ summary: "Add a pride identity to a member (owner)",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ request: {
+ params: IdentifierParam,
+ ...jsonBody(z.object({ identity: z.string().min(1) })),
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const identifier = c.req.valid("param").member_identifier;
+ const { identity } = c.req.valid("json");
+ const added = await addMemberPride(identifier, identity);
+ return added
+ ? c.json({ status: "success", message: `Added pride '${identity}' to ${identifier}` }, 200)
+ : c.json({ status: "info", message: `Pride '${identity}' already set for ${identifier}` }, 200);
+ },
+);
+
+membersRoutes.openapi(
+ createRoute({
+ method: "delete",
+ path: "/member-pride/{member_identifier}/{identity}",
+ tags: ["Pride"],
+ summary: "Remove a pride identity from a member (owner)",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ request: {
+ params: IdentifierParam.extend({ identity: z.string() }),
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const { member_identifier: identifier, identity } = c.req.valid("param");
+ if (!(await removeMemberPride(identifier, identity))) {
+ throw new HttpError(404, `Pride '${identity}' not found for ${identifier}`);
+ }
+ return c.json({ status: "success", message: `Removed pride '${identity}' from ${identifier}` }, 200);
+ },
+);
diff --git a/src/lib/server/plural/routes/metrics.ts b/src/lib/server/plural/routes/metrics.ts
new file mode 100644
index 0000000..abf5a0d
--- /dev/null
+++ b/src/lib/server/plural/routes/metrics.ts
@@ -0,0 +1,51 @@
+/* src/lib/server/plural/routes/metrics.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 } from "../openapi";
+import { FrontingTimeSchema, SwitchFrequencySchema } from "../schemas";
+import { getFrontingTimeMetrics, getSwitchFrequencyMetrics } from "../services/metrics";
+
+export const metricsRoutes = router();
+
+const DaysQuery = z.object({
+ days: z.coerce.number().min(1).max(365).default(30),
+});
+
+metricsRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/metrics/fronting-time",
+ tags: ["Metrics"],
+ summary: "Time each member spent fronting",
+ request: {
+ query: DaysQuery,
+ },
+ responses: ok(FrontingTimeSchema),
+ }),
+ async (c) => {
+ const metrics = await getFrontingTimeMetrics(c.req.valid("query").days);
+ return c.json(metrics as z.infer<typeof FrontingTimeSchema>, 200);
+ },
+);
+
+metricsRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/metrics/switch-frequency",
+ tags: ["Metrics"],
+ summary: "How often the system switched",
+ request: {
+ query: DaysQuery,
+ },
+ responses: ok(SwitchFrequencySchema),
+ }),
+ async (c) => {
+ const metrics = await getSwitchFrequencyMetrics(c.req.valid("query").days);
+ return c.json(metrics as z.infer<typeof SwitchFrequencySchema>, 200);
+ },
+);
diff --git a/src/lib/server/plural/routes/relationships.ts b/src/lib/server/plural/routes/relationships.ts
new file mode 100644
index 0000000..4c1d20b
--- /dev/null
+++ b/src/lib/server/plural/routes/relationships.ts
@@ -0,0 +1,87 @@
+/* src/lib/server/plural/routes/relationships.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, signedIn } from "../openapi";
+import { MessageSchema, RelationshipSchema } from "../schemas";
+import { getRelationships, addRelationship, removeRelationship } from "../services/relationships";
+import { requireAuth, requireOwner } from "../middleware/auth";
+import { HttpError } from "../errors";
+
+export const relationshipsRoutes = router();
+
+relationshipsRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/relationships",
+ tags: ["Relationships"],
+ summary: "The whole relationship map",
+ responses: ok(
+ z.object({
+ status: z.string(),
+ relationships: z.array(RelationshipSchema),
+ }),
+ ),
+ }),
+ async (c) => c.json({ status: "success", relationships: await getRelationships() }, 200),
+);
+
+relationshipsRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/relationships",
+ tags: ["Relationships"],
+ summary: "Link two members (owner)",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ request: jsonBody(
+ z.object({
+ memberA: z.string().min(1),
+ memberB: z.string().min(1),
+ type: z.string().min(1).optional().openapi({ description: "Defaults to 'partner'. 'crush' is one-way, A to B" }),
+ since: z.string().nullable().optional(),
+ }),
+ ),
+ responses: ok(
+ z.object({
+ status: z.string(),
+ relationship: RelationshipSchema,
+ }),
+ ),
+ }),
+ async (c) => {
+ const body = c.req.valid("json");
+ if (body.memberA === body.memberB) {
+ throw new HttpError(422, "A member cannot be in a relationship with themselves");
+ }
+ try {
+ return c.json({ status: "success", relationship: await addRelationship(body) }, 200);
+ } catch (err) {
+ throw new HttpError(400, err instanceof Error ? err.message : String(err));
+ }
+ },
+);
+
+relationshipsRoutes.openapi(
+ createRoute({
+ method: "delete",
+ path: "/relationships/{id}",
+ tags: ["Relationships"],
+ summary: "Remove a link (owner)",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ request: {
+ params: z.object({ id: z.string() }),
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const { id } = c.req.valid("param");
+ if (!(await removeRelationship(id))) throw new HttpError(404, `Relationship '${id}' not found`);
+ return c.json({ status: "success", message: `Removed relationship ${id}` }, 200);
+ },
+);
diff --git a/src/lib/server/plural/routes/system.ts b/src/lib/server/plural/routes/system.ts
new file mode 100644
index 0000000..fbca8bd
--- /dev/null
+++ b/src/lib/server/plural/routes/system.ts
@@ -0,0 +1,96 @@
+/* src/lib/server/plural/routes/system.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, signedIn } from "../openapi";
+import { MentalStateWireSchema, MessageSchema, SystemSchema, SystemUpdateSchema } from "../schemas";
+import { getSystem, updateSystem } from "../services/system";
+import { getMentalState, saveMentalState } from "../services/mental_state";
+import { requireAuth, requireAdmin, requireOwner } from "../middleware/auth";
+import { broadcastMentalStateUpdate } from "../ws";
+import { HttpError } from "../errors";
+
+export const systemRoutes = router();
+
+function mentalStateJson(state: Awaited<ReturnType<typeof getMentalState>>) {
+ return {
+ level: state.level,
+ updated_at: state.updated_at.toISOString(),
+ notes: state.notes ?? null,
+ };
+}
+
+systemRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/system",
+ tags: ["System"],
+ summary: "The system, with its current mental state",
+ responses: ok(SystemSchema),
+ }),
+ async (c) => {
+ const system = await getSystem();
+ return c.json({ ...system, mental_state: mentalStateJson(await getMentalState()) } as z.infer<typeof SystemSchema>, 200);
+ },
+);
+
+systemRoutes.openapi(
+ createRoute({
+ method: "patch",
+ path: "/system",
+ tags: ["System"],
+ summary: "Edit the system (owner)",
+ security: signedIn,
+ middleware: [requireAuth, requireOwner] as const,
+ request: jsonBody(SystemUpdateSchema),
+ responses: ok(SystemSchema),
+ }),
+ async (c) => {
+ const system = await updateSystem(c.req.valid("json"));
+ return c.json(system as z.infer<typeof SystemSchema>, 200);
+ },
+);
+
+systemRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/mental-state",
+ tags: ["System"],
+ summary: "Current mental state",
+ responses: ok(MentalStateWireSchema),
+ }),
+ async (c) => c.json(mentalStateJson(await getMentalState()), 200),
+);
+
+systemRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/mental-state",
+ tags: ["System"],
+ summary: "Set the mental state (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: jsonBody(
+ z.object({
+ level: z.string().min(1),
+ notes: z.string().nullable().optional(),
+ }),
+ ),
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const body = c.req.valid("json");
+ const state = {
+ level: body.level,
+ updated_at: new Date(),
+ notes: body.notes ?? null,
+ };
+ if (!(await saveMentalState(state))) throw new HttpError(500, "Failed to save mental state");
+ await broadcastMentalStateUpdate(mentalStateJson(state));
+ return c.json({ success: true, message: "Mental state updated" }, 200);
+ },
+);
diff --git a/src/lib/server/plural/routes/users.ts b/src/lib/server/plural/routes/users.ts
new file mode 100644
index 0000000..4a95987
--- /dev/null
+++ b/src/lib/server/plural/routes/users.ts
@@ -0,0 +1,117 @@
+/* src/lib/server/plural/routes/users.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, signedIn } from "../openapi";
+import { MessageSchema, UserCreateBody, UserSchema, UserUpdateBody } from "../schemas";
+import { toUserResponse } from "../models";
+import type { User } from "../models";
+import { getUsers, createUser, updateUser, deleteUser } from "../services/users";
+import { requireAuth, requireAdmin } from "../middleware/auth";
+import { HttpError } from "../errors";
+
+export const usersRoutes = router();
+
+const UserIdParam = z.object({ user_id: z.string() });
+
+function errorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+usersRoutes.openapi(
+ createRoute({
+ method: "get",
+ path: "/users",
+ tags: ["Users"],
+ summary: "Every site account (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ responses: ok(z.array(UserSchema)),
+ }),
+ async (c) => c.json((await getUsers()).map(toUserResponse), 200),
+);
+
+usersRoutes.openapi(
+ createRoute({
+ method: "post",
+ path: "/users",
+ tags: ["Users"],
+ summary: "Pre-provision an account (admin). It links on the person's first SSO sign-in",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: jsonBody(UserCreateBody),
+ responses: ok(UserSchema),
+ }),
+ async (c) => {
+ try {
+ return c.json(toUserResponse(await createUser(c.req.valid("json"), c.get("user") ?? null)), 200);
+ } catch (err) {
+ throw new HttpError(400, errorMessage(err));
+ }
+ },
+);
+
+usersRoutes.openapi(
+ createRoute({
+ method: "put",
+ path: "/users/{user_id}",
+ tags: ["Users"],
+ summary: "Edit an account. Your own, or anyone's as an admin",
+ security: signedIn,
+ middleware: [requireAuth] as const,
+ request: {
+ params: UserIdParam,
+ ...jsonBody(UserUpdateBody),
+ },
+ responses: ok(UserSchema),
+ }),
+ async (c) => {
+ const { user_id: userId } = c.req.valid("param");
+ const currentUser = c.get("user") as User;
+ if (!currentUser.is_admin && currentUser.id !== userId) {
+ throw new HttpError(403, "Not authorized to update this user");
+ }
+
+ let updated: User | null;
+ try {
+ updated = await updateUser(userId, c.req.valid("json"), currentUser);
+ } catch (err) {
+ throw new HttpError(400, errorMessage(err));
+ }
+ if (!updated) throw new HttpError(404, "User not found");
+ return c.json(toUserResponse(updated), 200);
+ },
+);
+
+usersRoutes.openapi(
+ createRoute({
+ method: "delete",
+ path: "/users/{user_id}",
+ tags: ["Users"],
+ summary: "Delete an account (admin)",
+ security: signedIn,
+ middleware: [requireAuth, requireAdmin] as const,
+ request: {
+ params: UserIdParam,
+ },
+ responses: ok(MessageSchema),
+ }),
+ async (c) => {
+ const { user_id: userId } = c.req.valid("param");
+ const currentUser = c.get("user") as User;
+ if (userId === currentUser.id) throw new HttpError(400, "Cannot delete your own account");
+
+ let deleted: boolean;
+ try {
+ deleted = await deleteUser(userId, currentUser);
+ } catch (err) {
+ throw new HttpError(403, errorMessage(err));
+ }
+ if (!deleted) throw new HttpError(404, "User not found");
+ return c.json({ message: "User deleted successfully" }, 200);
+ },
+);
diff --git a/src/lib/server/plural/runtime.ts b/src/lib/server/plural/runtime.ts
new file mode 100644
index 0000000..3761651
--- /dev/null
+++ b/src/lib/server/plural/runtime.ts
@@ -0,0 +1,89 @@
+/* src/lib/server/plural/runtime.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 type { PluralEnv } from "./types";
+
+// JSON blob store over the D1 `kv` table, the same shape the old DO store had
+export interface Store {
+ get<T>(key: string, fallback: T): Promise<T>;
+ put(key: string, value: unknown): Promise<void>;
+ delete(key: string): Promise<void>;
+ // Read and delete in one statement, so a one-time value can only be used once
+ take<T>(key: string): Promise<T | null>;
+ // Replace only if the stored value is still `expected`. False when another request won
+ swap(key: string, expected: unknown, next: unknown): Promise<boolean>;
+}
+
+export interface PluralRuntime {
+ env: PluralEnv;
+ db: D1Database;
+ store: Store;
+ broadcast(data: unknown): Promise<void>;
+}
+
+function d1Store(db: D1Database): Store {
+ return {
+ async get<T>(key: string, fallback: T): Promise<T> {
+ const row = await db
+ .prepare("SELECT value FROM kv WHERE key = ?")
+ .bind(key)
+ .first<{ value: string }>();
+ return row ? (JSON.parse(row.value) as T) : fallback;
+ },
+
+ async put(key: string, value: unknown): Promise<void> {
+ await db
+ .prepare("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
+ .bind(key, JSON.stringify(value))
+ .run();
+ },
+
+ async delete(key: string): Promise<void> {
+ await db.prepare("DELETE FROM kv WHERE key = ?").bind(key).run();
+ },
+
+ async take<T>(key: string): Promise<T | null> {
+ const row = await db
+ .prepare("DELETE FROM kv WHERE key = ? RETURNING value")
+ .bind(key)
+ .first<{ value: string }>();
+ return row ? (JSON.parse(row.value) as T) : null;
+ },
+
+ async swap(key: string, expected: unknown, next: unknown): Promise<boolean> {
+ const result = await db
+ .prepare("UPDATE kv SET value = ? WHERE key = ? AND value = ?")
+ .bind(JSON.stringify(next), key, JSON.stringify(expected))
+ .run();
+ return result.meta.changes === 1;
+ },
+ };
+}
+
+let current: PluralRuntime | null = null;
+
+// Env is fixed for the life of an isolate, so building this once per isolate is safe
+export function setRuntime(env: PluralEnv): void {
+ if (current?.env === env) return;
+ current = {
+ env,
+ db: env.DB,
+ store: d1Store(env.DB),
+ broadcast: async (data) => {
+ try {
+ await env.HUB.broadcast(data);
+ } catch (err) {
+ // A dropped live update must never fail the write that caused it
+ console.error(`Realtime broadcast failed: ${String(err)}`);
+ }
+ },
+ };
+}
+
+export function rt(): PluralRuntime {
+ if (!current) throw new Error("plural runtime not initialised");
+ return current;
+}
diff --git a/src/lib/server/plural/schemas.ts b/src/lib/server/plural/schemas.ts
new file mode 100644
index 0000000..164d163
--- /dev/null
+++ b/src/lib/server/plural/schemas.ts
@@ -0,0 +1,243 @@
+/* src/lib/server/plural/schemas.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 { z } from "@hono/zod-openapi";
+
+import { EmailSchema } from "./models";
+
+// ---- Shared ----
+
+export const ErrorSchema = z
+ .object({
+ detail: z.union([z.string(), z.array(z.unknown())]),
+ })
+ .openapi("Error");
+
+export const MessageSchema = z
+ .looseObject({
+ status: z.string().optional(),
+ success: z.boolean().optional(),
+ message: z.string().optional(),
+ })
+ .openapi("Message");
+
+export const IdentifierParam = z.object({
+ member_identifier: z.string().openapi({
+ param: {
+ name: "member_identifier",
+ in: "path",
+ },
+ description: "Member id, or member name (case-insensitive)",
+ example: "abcdef",
+ }),
+});
+
+const Hex = z
+ .string()
+ .regex(/^[0-9a-fA-F]{6}$/, "Must be a 6-digit hex colour without '#'")
+ .nullable();
+
+const Url = z.url().max(2048).nullable();
+
+// ---- Members ----
+
+export const ProxyTagSchema = z
+ .object({
+ prefix: z.string().max(100).nullable(),
+ suffix: z.string().max(100).nullable(),
+ })
+ .openapi("ProxyTag");
+
+export const MemberStatusSchema = z
+ .object({
+ text: z.string(),
+ emoji: z.string().nullable(),
+ updated_at: z.string(),
+ })
+ .openapi("MemberStatus");
+
+export const MemberSchema = z
+ .looseObject({
+ id: z.string().openapi({ example: "abcdef" }),
+ uuid: z.string(),
+ system: z.string(),
+ name: z.string(),
+ display_name: z.string().nullable(),
+ color: z.string().nullable(),
+ birthday: z.string().nullable().openapi({ description: "YYYY-MM-DD. Year 0004 means the year is hidden" }),
+ pronouns: z.string().nullable(),
+ avatar_url: z.string().nullable(),
+ webhook_avatar_url: z.string().nullable(),
+ banner: z.string().nullable(),
+ description: z.string().nullable(),
+ created: z.string(),
+ proxy_tags: z.array(ProxyTagSchema),
+ keep_proxy: z.boolean(),
+ autoproxy_enabled: z.boolean().nullable(),
+ message_count: z.number(),
+ last_message_timestamp: z.string().nullable(),
+ privacy: z.record(z.string(), z.unknown()),
+ is_special: z.boolean().optional(),
+ original_name: z.string().optional(),
+ tags: z.array(z.string()).optional(),
+ status: MemberStatusSchema.nullable().optional(),
+ pride: z.array(z.string()).optional(),
+ })
+ .openapi("Member");
+
+const memberFields = {
+ name: z.string().trim().min(1).max(100),
+ display_name: z.string().max(100).nullable(),
+ color: Hex,
+ birthday: z
+ .string()
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD")
+ .nullable(),
+ pronouns: z.string().max(100).nullable(),
+ avatar_url: Url,
+ webhook_avatar_url: Url,
+ banner: Url,
+ description: z.string().max(1000).nullable(),
+ proxy_tags: z.array(ProxyTagSchema).max(100),
+ keep_proxy: z.boolean(),
+ autoproxy_enabled: z.boolean().nullable(),
+ privacy: z.record(z.string(), z.enum(["public", "private"])),
+};
+
+export const MemberCreateSchema = z
+ .object(memberFields)
+ .partial()
+ .required({ name: true })
+ .openapi("MemberCreate");
+
+export const MemberUpdateSchema = z.object(memberFields).partial().openapi("MemberUpdate");
+
+// ---- System ----
+
+export const MentalStateWireSchema = z
+ .object({
+ level: z.string(),
+ updated_at: z.string(),
+ notes: z.string().nullable().optional(),
+ })
+ .openapi("MentalState");
+
+export const SystemSchema = z
+ .looseObject({
+ id: z.string(),
+ uuid: z.string(),
+ name: z.string().nullable(),
+ description: z.string().nullable(),
+ tag: z.string().nullable(),
+ pronouns: z.string().nullable(),
+ avatar_url: z.string().nullable(),
+ banner: z.string().nullable(),
+ color: z.string().nullable(),
+ timezone: z.string().nullable(),
+ created: z.string(),
+ privacy: z.record(z.string(), z.unknown()),
+ mental_state: MentalStateWireSchema.optional(),
+ })
+ .openapi("System");
+
+export const SystemUpdateSchema = z
+ .object({
+ name: z.string().max(100).nullable(),
+ description: z.string().max(1000).nullable(),
+ tag: z.string().max(79).nullable(),
+ pronouns: z.string().max(100).nullable(),
+ avatar_url: Url,
+ banner: Url,
+ color: Hex,
+ timezone: z.string().max(64).nullable(),
+ privacy: z.record(z.string(), z.enum(["public", "private"])),
+ })
+ .partial()
+ .openapi("SystemUpdate");
+
+// ---- Switches ----
+
+export const SwitchSchema = z
+ .object({
+ id: z.string(),
+ timestamp: z.string(),
+ members: z.array(z.string()),
+ })
+ .openapi("Switch");
+
+export const FrontersSchema = z
+ .object({
+ id: z.string().nullable(),
+ timestamp: z.string().nullable(),
+ members: z.array(MemberSchema),
+ })
+ .openapi("Fronters");
+
+// ---- Relationships ----
+
+export const RelationshipSchema = z
+ .object({
+ id: z.string(),
+ members: z.tuple([z.string(), z.string()]),
+ type: z.string(),
+ since: z.string().nullable(),
+ })
+ .openapi("Relationship");
+
+// ---- Users ----
+
+export const UserSchema = z
+ .object({
+ id: z.string(),
+ username: z.string(),
+ display_name: z.string().nullable().optional(),
+ email: z.string().nullable().optional(),
+ created_at: z.string().nullable().optional(),
+ is_admin: z.boolean(),
+ is_owner: z.boolean(),
+ is_pet: z.boolean(),
+ avatar_url: z.string().nullable().optional(),
+ })
+ .openapi("User");
+
+export const UserCreateBody = z
+ .object({
+ username: z.string().min(1),
+ pocket_id: z.string().nullable().optional(),
+ email: EmailSchema.nullable().optional(),
+ display_name: z.string().nullable().optional(),
+ is_admin: z.boolean().default(false),
+ is_pet: z.boolean().default(false),
+ })
+ .openapi("UserCreate");
+
+export const UserUpdateBody = z
+ .object({
+ display_name: z.string().nullable().optional(),
+ avatar_url: z.string().nullable().optional(),
+ email: EmailSchema.nullable().optional(),
+ is_admin: z.boolean().nullable().optional(),
+ is_pet: z.boolean().nullable().optional(),
+ })
+ .openapi("UserUpdate");
+
+// ---- Metrics ----
+
+export const FrontingTimeSchema = z
+ .looseObject({
+ total_time: z.number(),
+ members: z.record(z.string(), z.unknown()),
+ timeframes: z.record(z.string(), z.record(z.string(), z.number())),
+ })
+ .openapi("FrontingTimeMetrics");
+
+export const SwitchFrequencySchema = z
+ .object({
+ total_switches: z.number(),
+ avg_switches_per_day: z.number(),
+ timeframes: z.record(z.string(), z.number()),
+ })
+ .openapi("SwitchFrequencyMetrics");
diff --git a/src/lib/server/plural/security.ts b/src/lib/server/plural/security.ts
new file mode 100644
index 0000000..aa24caa
--- /dev/null
+++ b/src/lib/server/plural/security.ts
@@ -0,0 +1,137 @@
+/* src/lib/server/plural/security.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.
+ */
+
+/**
+ * Security utilities, rewritten for the Workers runtime (Web Crypto only —
+ * no `bcrypt`, `jsonwebtoken`, or `axios`).
+ *
+ * - JWT: HS256 signed/verified with SubtleCrypto HMAC. This is the token the
+ * API issues to the browser AFTER a successful SSO (OIDC) login, so every
+ * existing bearer-auth route keeps working unchanged. It carries the id of
+ * the SSO-backed session it belongs to (see services/sso_sessions.ts).
+ * - OIDC helpers: cryptographically random state/PKCE-verifier generation and
+ * the S256 code-challenge digest.
+ *
+ * Local password hashing has been removed — login is SSO-only.
+ */
+
+import { ACCESS_TOKEN_EXPIRE_MINUTES, jwtSecret } from "./config";
+import { HttpError } from "./errors";
+
+const enc = new TextEncoder();
+const dec = new TextDecoder();
+
+// ---------------------------------------------------------------------------
+// base64url helpers
+// ---------------------------------------------------------------------------
+
+function bytesToB64url(bytes: Uint8Array): string {
+ let bin = "";
+ for (const b of bytes) bin += String.fromCharCode(b);
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+function b64urlToBytes(s: string): Uint8Array<ArrayBuffer> {
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=");
+ const bin = atob(b64);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+ return out;
+}
+
+function b64urlJson(obj: unknown): string {
+ return bytesToB64url(enc.encode(JSON.stringify(obj)));
+}
+
+/** Constant-time byte comparison. */
+function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
+ if (a.length !== b.length) return false;
+ let diff = 0;
+ for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;
+ return diff === 0;
+}
+
+/** Constant-time string comparison, tolerant of differing lengths. */
+export function constantTimeStringEqual(a: string, b: string): boolean {
+ return timingSafeEqual(enc.encode(a), enc.encode(b));
+}
+
+// ---------------------------------------------------------------------------
+// OIDC / PKCE helpers
+// ---------------------------------------------------------------------------
+
+/** A URL-safe, cryptographically random token — used for OIDC `state` and the
+ * PKCE code verifier. `bytes` is the amount of entropy, not the string length. */
+export function randomUrlToken(bytes = 32): string {
+ return bytesToB64url(crypto.getRandomValues(new Uint8Array(bytes)));
+}
+
+/** The PKCE S256 code challenge: base64url( SHA-256( verifier ) ). */
+export async function sha256Base64Url(input: string): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", enc.encode(input));
+ return bytesToB64url(new Uint8Array(digest));
+}
+
+// ---------------------------------------------------------------------------
+// JWT (HS256)
+// ---------------------------------------------------------------------------
+
+async function hmacKey(): Promise<CryptoKey> {
+ return crypto.subtle.importKey(
+ "raw",
+ enc.encode(jwtSecret()),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign", "verify"],
+ );
+}
+
+export async function createAccessToken(data: Record<string, unknown>): Promise<string> {
+ const now = Math.floor(Date.now() / 1000);
+ const payload = {
+ ...data,
+ iat: now,
+ exp: now + ACCESS_TOKEN_EXPIRE_MINUTES * 60,
+ };
+ const header = { alg: "HS256", typ: "JWT" };
+ const signingInput = `${b64urlJson(header)}.${b64urlJson(payload)}`;
+ const key = await hmacKey();
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(signingInput)));
+ return `${signingInput}.${bytesToB64url(sig)}`;
+}
+
+export interface JwtPayload {
+ sub?: string;
+ [k: string]: unknown;
+}
+
+/** `allowExpired` is only for logout, where a stale token should still end its session. */
+export async function decodeAccessToken(
+ token: string,
+ opts: { allowExpired?: boolean } = {},
+): Promise<JwtPayload> {
+ try {
+ const parts = token.split(".");
+ if (parts.length !== 3) throw new Error("malformed");
+ const [h, p, s] = parts as [string, string, string];
+ const key = await hmacKey();
+ const valid = await crypto.subtle.verify(
+ "HMAC",
+ key,
+ b64urlToBytes(s),
+ enc.encode(`${h}.${p}`),
+ );
+ if (!valid) throw new Error("bad signature");
+
+ const payload = JSON.parse(dec.decode(b64urlToBytes(p))) as JwtPayload & { exp?: number };
+ if (!opts.allowExpired && typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1000)) {
+ throw new Error("expired");
+ }
+ return payload;
+ } catch {
+ throw new HttpError(401, "Invalid or expired token", { "WWW-Authenticate": "Bearer" });
+ }
+}
diff --git a/src/lib/server/plural/services/app_codes.ts b/src/lib/server/plural/services/app_codes.ts
new file mode 100644
index 0000000..975be84
--- /dev/null
+++ b/src/lib/server/plural/services/app_codes.ts
@@ -0,0 +1,68 @@
+/* src/lib/server/plural/services/app_codes.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.
+ */
+
+/**
+ * One-time sign-in codes for native apps.
+ *
+ * A browser can be handed its JWT in a URL fragment, but an app's redirect URI
+ * (a custom scheme) can be claimed by any other app on the phone. So an
+ * app-started login ends with a short-lived, single-use code instead, and the
+ * app swaps it at POST /v2/plural/auth/app/token together with the PKCE
+ * verifier only it holds. Anyone else who catches the redirect gets a useless
+ * code: without the verifier it can't be redeemed, and once redeemed (or after
+ * a minute) it's gone.
+ */
+
+import { rt } from "../runtime";
+import { constantTimeStringEqual, randomUrlToken, sha256Base64Url } from "../security";
+
+/** How long an app has to redeem its code. */
+export const APP_CODE_TTL_SECONDS = 60;
+
+/** An S256 PKCE challenge: base64url of a SHA-256 digest, 43 characters. */
+export const PKCE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
+
+/** A code from saveAppCode: 32 random bytes, base64url. */
+export const APP_CODE = /^[A-Za-z0-9_-]{43}$/;
+
+/** RFC 7636 verifier: 43–128 unreserved characters. */
+export const PKCE_VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
+
+interface StoredAppCode {
+ token: string;
+ challenge: string;
+ expiresAt: number;
+}
+
+function codeKey(code: string): string {
+ return `app_code:${code}`;
+}
+
+/** Park a freshly minted JWT behind a one-time code bound to the app's challenge. */
+export async function saveAppCode(token: string, challenge: string): Promise<string> {
+ const code = randomUrlToken(32);
+ await rt().store.put(codeKey(code), {
+ token,
+ challenge,
+ expiresAt: Date.now() + APP_CODE_TTL_SECONDS * 1000,
+ } satisfies StoredAppCode);
+ return code;
+}
+
+/**
+ * The JWT for a code, exactly once. The code is consumed on the first attempt,
+ * right or wrong, so a guessed verifier can't be retried. Null when the code is
+ * unknown, already used, expired, or the verifier doesn't match.
+ */
+export async function takeAppCode(code: string, verifier: string): Promise<string | null> {
+ const key = codeKey(code);
+ const stored = await rt().store.take<StoredAppCode>(key);
+ if (!stored) return null;
+
+ if (Date.now() > stored.expiresAt) return null;
+ const challenge = await sha256Base64Url(verifier);
+ return constantTimeStringEqual(challenge, stored.challenge) ? stored.token : null;
+}
diff --git a/src/lib/server/plural/services/importer.ts b/src/lib/server/plural/services/importer.ts
new file mode 100644
index 0000000..d22944c
--- /dev/null
+++ b/src/lib/server/plural/services/importer.ts
@@ -0,0 +1,220 @@
+/* src/lib/server/plural/services/importer.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 { rt } from "../runtime";
+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;
+
+// D1 caps how much one batch may carry, so big switch histories go in slices
+const BATCH_SIZE = 200;
+
+export interface ImportReport {
+ system: string;
+ members: number;
+ switches: number;
+ media_copied: number;
+ media_failed: string[];
+}
+
+function text(value: unknown): string | null {
+ return typeof value === "string" && value !== "" ? value : null;
+}
+
+export function mediaUrl(key: string): string {
+ return `${frontendUrl()}/api/plural/media/${key}`;
+}
+
+// Copy one image into R2. Returns the new URL, or null when the source is gone or not an image
+async function copyMedia(source: string, key: string): Promise<string | null> {
+ if (source.startsWith(mediaUrl(""))) return source;
+
+ try {
+ const response = await fetch(source);
+ const type = response.headers.get("Content-Type") ?? "";
+ if (!response.ok || !type.startsWith("image/")) return null;
+
+ const body = await response.arrayBuffer();
+ if (body.byteLength > MAX_MEDIA_BYTES) return null;
+
+ await rt().env.MEDIA.put(key, body, { httpMetadata: { contentType: type } });
+ return mediaUrl(key);
+ } catch {
+ return null;
+ }
+}
+
+async function copyAllMedia(owner: JsonObject, prefix: string, report: ImportReport): Promise<void> {
+ for (const field of MEDIA_FIELDS) {
+ const source = text(owner[field]);
+ if (!source) continue;
+
+ const copied = await copyMedia(source, `${prefix}-${field}`);
+ if (copied) {
+ owner[field] = copied;
+ report.media_copied += 1;
+ } else {
+ // Keep the old URL so nothing disappears; it can be re-uploaded by hand
+ report.media_failed.push(`${prefix}.${field}`);
+ }
+ }
+}
+
+async function runBatches(statements: D1PreparedStatement[]): Promise<void> {
+ for (let start = 0; start < statements.length; start += BATCH_SIZE) {
+ await rt().db.batch(statements.slice(start, start + BATCH_SIZE));
+ }
+}
+
+// A PluralKit export file (pk;export). `replace` must be set to overwrite an existing system
+export async function importPluralKitExport(
+ data: JsonObject,
+ options: { replace: boolean; copyMedia: boolean },
+): Promise<ImportReport> {
+ const systemHid = text(data.id);
+ if (!systemHid || !Array.isArray(data.members) || !Array.isArray(data.switches)) {
+ throw new HttpError(422, "That doesn't look like a PluralKit export (needs id, members and switches)");
+ }
+
+ const existing = await rt().db.prepare("SELECT id FROM systems LIMIT 1").first<{ id: string }>();
+ if (existing && !options.replace) {
+ throw new HttpError(409, "A system is already imported. Send replace=true to overwrite it.");
+ }
+
+ const report: ImportReport = {
+ system: systemHid,
+ members: 0,
+ switches: 0,
+ media_copied: 0,
+ media_failed: [],
+ };
+
+ const members = data.members as JsonObject[];
+ if (options.copyMedia) {
+ await copyAllMedia(data, "system", report);
+ for (const member of members) await copyAllMedia(member, `member-${member.id}`, report);
+ }
+
+ const db = rt().db;
+ const statements: D1PreparedStatement[] = [
+ db.prepare("DELETE FROM switches"),
+ db.prepare("DELETE FROM members"),
+ db.prepare("DELETE FROM systems"),
+ db
+ .prepare(
+ `INSERT INTO systems (id, uuid, name, description, tag, pronouns, avatar_url, banner, color, timezone, created, privacy)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .bind(
+ systemHid,
+ text(data.uuid) ?? crypto.randomUUID(),
+ text(data.name),
+ text(data.description),
+ text(data.tag),
+ text(data.pronouns),
+ text(data.avatar_url),
+ text(data.banner),
+ text(data.color),
+ text(data.config?.timezone) ?? text(data.timezone),
+ text(data.created) ?? new Date().toISOString(),
+ JSON.stringify(data.privacy ?? {}),
+ ),
+ ];
+
+ for (const member of members) {
+ const id = text(member.id);
+ const name = text(member.name);
+ if (!id || !name) continue;
+
+ statements.push(
+ db
+ .prepare(
+ `INSERT INTO members (id, uuid, system_id, name, display_name, color, birthday, pronouns, avatar_url,
+ webhook_avatar_url, banner, description, created, proxy_tags, keep_proxy, autoproxy_enabled,
+ message_count, last_message_timestamp, privacy)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .bind(
+ id,
+ text(member.uuid) ?? crypto.randomUUID(),
+ systemHid,
+ name,
+ text(member.display_name),
+ text(member.color),
+ text(member.birthday),
+ text(member.pronouns),
+ text(member.avatar_url),
+ text(member.webhook_avatar_url),
+ text(member.banner),
+ text(member.description),
+ text(member.created) ?? new Date().toISOString(),
+ JSON.stringify(Array.isArray(member.proxy_tags) ? member.proxy_tags : []),
+ member.keep_proxy ? 1 : 0,
+ member.autoproxy_enabled == null ? null : member.autoproxy_enabled ? 1 : 0,
+ Number(member.message_count) || 0,
+ text(member.last_message_timestamp),
+ JSON.stringify(member.privacy ?? {}),
+ ),
+ );
+ report.members += 1;
+ }
+
+ for (const entry of data.switches as JsonObject[]) {
+ const timestamp = text(entry.timestamp);
+ if (!timestamp || !Array.isArray(entry.members)) continue;
+
+ statements.push(
+ db
+ .prepare("INSERT INTO switches (id, system_id, timestamp, members) VALUES (?, ?, ?, ?)")
+ .bind(text(entry.id) ?? crypto.randomUUID(), systemHid, timestamp, JSON.stringify(entry.members.map(String))),
+ );
+ report.switches += 1;
+ }
+
+ // shortcut: batches commit one slice at a time, so a failure part-way leaves a partial import. Re-run with replace=true
+ 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
new file mode 100644
index 0000000..86be6c0
--- /dev/null
+++ b/src/lib/server/plural/services/keys.ts
@@ -0,0 +1,25 @@
+/* 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/services/mental_state.ts b/src/lib/server/plural/services/mental_state.ts
new file mode 100644
index 0000000..f9bfee4
--- /dev/null
+++ b/src/lib/server/plural/services/mental_state.ts
@@ -0,0 +1,60 @@
+/* src/lib/server/plural/services/mental_state.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 type { MentalState } from "../models";
+import { parseTimestamp } from "../datetime";
+import { rt } from "../runtime";
+
+const KEY = "mental_state";
+
+interface StoredMentalState {
+ level: string;
+ updated_at: string;
+ notes?: string | null;
+}
+
+function defaultState(): MentalState {
+ return { level: "safe", updated_at: new Date(), notes: null };
+}
+
+export async function getMentalState(): Promise<MentalState> {
+ try {
+ const stateData = await rt().store.get<StoredMentalState | null>(KEY, null);
+ if (!stateData) return defaultState();
+ return {
+ level: stateData.level,
+ updated_at: parseTimestamp(stateData.updated_at),
+ notes: stateData.notes ?? null,
+ };
+ } catch (err) {
+ console.error(`Error loading mental state: ${String(err)}`);
+ return defaultState();
+ }
+}
+
+export async function saveMentalState(state: MentalState): Promise<boolean> {
+ try {
+ const stateData: StoredMentalState = {
+ level: state.level,
+ updated_at: state.updated_at.toISOString(),
+ notes: state.notes ?? null,
+ };
+ await rt().store.put(KEY, stateData);
+ return true;
+ } catch (err) {
+ console.error(`Error saving mental state: ${String(err)}`);
+ return false;
+ }
+}
+
+export async function updateMentalState(
+ level: string,
+ notes?: string | null,
+): Promise<MentalState> {
+ const state: MentalState = { level, updated_at: new Date(), notes: notes ?? null };
+ await saveMentalState(state);
+ return state;
+}
diff --git a/src/lib/server/plural/services/metrics.ts b/src/lib/server/plural/services/metrics.ts
new file mode 100644
index 0000000..108cbde
--- /dev/null
+++ b/src/lib/server/plural/services/metrics.ts
@@ -0,0 +1,223 @@
+/* src/lib/server/plural/services/metrics.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.
+ */
+
+/** Fronting-time and switch-frequency metrics. Logic ported verbatim. */
+
+import { getSwitches, getMembers } from "./system";
+import { parseTimestamp } from "../datetime";
+import type { JsonObject } from "../types";
+
+interface MemberDetail {
+ name: string;
+ display_name: string;
+ avatar_url: string | null;
+}
+
+interface FrontingTimeTotals {
+ total_seconds: number;
+ "24h": number;
+ "48h": number;
+ "5d": number;
+ "7d": number;
+ "30d": number;
+}
+
+const TIMEFRAME_KEYS = ["24h", "48h", "5d", "7d", "30d"] as const;
+
+function emptyFrontingMetrics(): JsonObject {
+ return {
+ total_time: 0,
+ members: {},
+ timeframes: { "24h": {}, "48h": {}, "5d": {}, "7d": {}, "30d": {} },
+ };
+}
+
+export async function getFrontingTimeMetrics(days = 30): Promise<JsonObject> {
+ try {
+ const switches = await getSwitches(1000);
+
+ const now = new Date();
+ const cutoffTime = new Date(now.getTime() - days * 24 * 3600 * 1000);
+
+ const memberDetails: Record<string, MemberDetail> = {};
+ try {
+ const members = await getMembers();
+ for (const member of members) {
+ memberDetails[member.id] = {
+ name: member.name,
+ display_name: member.display_name ?? member.name,
+ avatar_url: member.avatar_url ?? null,
+ };
+ }
+ } catch (err) {
+ console.error(`Error fetching member details: ${String(err)}`);
+ }
+
+ const filteredSwitches: JsonObject[] = [];
+ for (const switchObj of switches) {
+ try {
+ const timestamp = parseTimestamp(switchObj.timestamp);
+ if (timestamp >= cutoffTime) {
+ filteredSwitches.push({ ...switchObj, _parsed_timestamp: timestamp });
+ }
+ } catch (err) {
+ console.error(`Error parsing timestamp: ${String(err)}`);
+ }
+ }
+
+ filteredSwitches.sort(
+ (a, b) => (a._parsed_timestamp as Date).getTime() - (b._parsed_timestamp as Date).getTime(),
+ );
+
+ if (filteredSwitches.length === 0) return emptyFrontingMetrics();
+
+ const currentMembers = filteredSwitches[filteredSwitches.length - 1]!.members;
+ filteredSwitches.push({
+ timestamp: now.toISOString(),
+ members: currentMembers,
+ _parsed_timestamp: now,
+ });
+
+ const frontingTimes: Record<string, FrontingTimeTotals> = {};
+ let totalTimeSeconds = 0;
+
+ for (let i = 1; i < filteredSwitches.length; i++) {
+ const prevSwitch = filteredSwitches[i - 1]!;
+ const currSwitch = filteredSwitches[i]!;
+
+ try {
+ const prevTime: Date = prevSwitch._parsed_timestamp;
+ const currTime: Date = currSwitch._parsed_timestamp;
+ const durationSeconds = (currTime.getTime() - prevTime.getTime()) / 1000;
+ totalTimeSeconds += durationSeconds;
+
+ for (const memberId of prevSwitch.members as string[]) {
+ const totals = (frontingTimes[memberId] ??= {
+ total_seconds: 0,
+ "24h": 0,
+ "48h": 0,
+ "5d": 0,
+ "7d": 0,
+ "30d": 0,
+ });
+
+ totals.total_seconds += durationSeconds;
+
+ const timeAgo = (now.getTime() - prevTime.getTime()) / 1000;
+ if (timeAgo <= 24 * 3600) totals["24h"] += durationSeconds;
+ if (timeAgo <= 48 * 3600) totals["48h"] += durationSeconds;
+ if (timeAgo <= 5 * 24 * 3600) totals["5d"] += durationSeconds;
+ if (timeAgo <= 7 * 24 * 3600) totals["7d"] += durationSeconds;
+ if (timeAgo <= 30 * 24 * 3600) totals["30d"] += durationSeconds;
+ }
+ } catch (err) {
+ console.error(`Error processing switch: ${String(err)}`);
+ }
+ }
+
+ const result: JsonObject = {
+ total_time: totalTimeSeconds,
+ members: {},
+ timeframes: { "24h": {}, "48h": {}, "5d": {}, "7d": {}, "30d": {} },
+ };
+
+ for (const [memberId, times] of Object.entries(frontingTimes)) {
+ let name = memberId;
+ let displayName = memberId;
+ let avatarUrl: string | null = null;
+
+ const details = memberDetails[memberId];
+ if (details) {
+ name = details.name;
+ displayName = details.display_name;
+ avatarUrl = details.avatar_url;
+ }
+
+ const totalPercent = totalTimeSeconds > 0 ? (times.total_seconds / totalTimeSeconds) * 100 : 0;
+
+ result.members[memberId] = {
+ id: memberId,
+ name,
+ display_name: displayName,
+ avatar_url: avatarUrl,
+ total_seconds: times.total_seconds,
+ total_percent: totalPercent,
+ "24h": times["24h"],
+ "48h": times["48h"],
+ "5d": times["5d"],
+ "7d": times["7d"],
+ "30d": times["30d"],
+ };
+
+ for (const tf of TIMEFRAME_KEYS) {
+ result.timeframes[tf][memberId] = times[tf];
+ }
+ }
+
+ return result;
+ } catch (err) {
+ console.error(`Error in getFrontingTimeMetrics: ${String(err)}`);
+ return emptyFrontingMetrics();
+ }
+}
+
+export async function getSwitchFrequencyMetrics(days = 30): Promise<JsonObject> {
+ try {
+ const switches = await getSwitches(1000);
+
+ const now = new Date();
+ const cutoffTime = new Date(now.getTime() - days * 24 * 3600 * 1000);
+
+ const filteredSwitches: JsonObject[] = [];
+ for (const switchObj of switches) {
+ try {
+ const timestamp = parseTimestamp(switchObj.timestamp);
+ if (timestamp >= cutoffTime) {
+ filteredSwitches.push({ ...switchObj, _parsed_timestamp: timestamp });
+ }
+ } catch (err) {
+ console.error(`Error parsing timestamp in switch_frequency: ${String(err)}`);
+ }
+ }
+
+ const totalSwitches = filteredSwitches.length;
+ const timeframes: Record<"24h" | "48h" | "5d" | "7d" | "30d", number> = {
+ "24h": 0,
+ "48h": 0,
+ "5d": 0,
+ "7d": 0,
+ "30d": totalSwitches,
+ };
+
+ for (const switchObj of filteredSwitches) {
+ try {
+ const timestamp: Date = switchObj._parsed_timestamp;
+ const timeAgo = (now.getTime() - timestamp.getTime()) / 1000;
+ if (timeAgo <= 24 * 3600) timeframes["24h"] += 1;
+ if (timeAgo <= 48 * 3600) timeframes["48h"] += 1;
+ if (timeAgo <= 5 * 24 * 3600) timeframes["5d"] += 1;
+ if (timeAgo <= 7 * 24 * 3600) timeframes["7d"] += 1;
+ } catch (err) {
+ console.error(`Error calculating timeframes: ${String(err)}`);
+ }
+ }
+
+ const avgSwitchesPerDay = days > 0 ? totalSwitches / days : 0;
+
+ return {
+ total_switches: totalSwitches,
+ avg_switches_per_day: avgSwitchesPerDay,
+ timeframes,
+ };
+ } catch (err) {
+ console.error(`Error in getSwitchFrequencyMetrics: ${String(err)}`);
+ return {
+ total_switches: 0,
+ avg_switches_per_day: 0,
+ timeframes: { "24h": 0, "48h": 0, "5d": 0, "7d": 0, "30d": 0 },
+ };
+ }
+}
diff --git a/src/lib/server/plural/services/oidc.ts b/src/lib/server/plural/services/oidc.ts
new file mode 100644
index 0000000..6a0724f
--- /dev/null
+++ b/src/lib/server/plural/services/oidc.ts
@@ -0,0 +1,338 @@
+/* src/lib/server/plural/services/oidc.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.
+ */
+
+/**
+ * Doughmination SSO / OpenID Connect client.
+ *
+ * The API is a confidential OIDC client running Authorization Code + PKCE:
+ *
+ * 1. /auth/sso/login — mint a `state` + PKCE verifier, stash them in the DO
+ * store, and 302 the browser to the SSO's authorization endpoint.
+ * 2. The SSO authenticates the user and redirects back with `?code&state&iss`.
+ * 3. /auth/sso/callback — validate `state` and `iss`, exchange the code for
+ * tokens over a direct TLS call to the token endpoint, then read the
+ * identity claims from the userinfo endpoint.
+ *
+ * Because the code exchange and userinfo call are server-to-server over TLS
+ * with a client secret, their responses are trusted directly — we do not need
+ * to separately verify the id_token's signature.
+ *
+ * The refresh token from step 3 is kept with the API session (see
+ * sso_sessions.ts) and used to re-check the account with the SSO.
+ */
+
+import {
+ ssoIssuer,
+ ssoClientId,
+ ssoClientSecret,
+ ssoRedirectUri,
+ ssoScopes,
+ ssoPostLogoutRedirectUri,
+ OIDC_STATE_TTL_MINUTES,
+} from "../config";
+import { randomUrlToken, sha256Base64Url } from "../security";
+import { HttpError } from "../errors";
+import { rt } from "../runtime";
+
+/** The subset of the OIDC discovery document we use. */
+interface OidcDiscovery {
+ issuer: string;
+ authorization_endpoint: string;
+ token_endpoint: string;
+ userinfo_endpoint: string;
+ end_session_endpoint?: string;
+ revocation_endpoint?: string;
+}
+
+/** Identity claims we care about, normalized from the userinfo response. */
+export interface OidcIdentity {
+ /** Stable subject identifier — the primary key we link accounts on. */
+ sub: string;
+ /** The issuer that vouched for `sub`. */
+ issuer: string;
+ /** preferred_username claim; the account username we match/create on. */
+ preferredUsername: string;
+ email: string | null;
+ displayName: string | null;
+}
+
+/** Tokens kept with the API session. */
+export interface SsoTokens {
+ refreshToken: string | null;
+ idToken: string | null;
+}
+
+/** Cached discovery document (the DO is a singleton, so module scope persists
+ * across requests in the same isolate). Re-fetched after the TTL. */
+let discoveryCache: { issuer: string; doc: OidcDiscovery; fetchedAt: number } | null = null;
+const DISCOVERY_TTL_MS = 60 * 60 * 1000; // 1 hour
+
+function assertConfigured(): void {
+ if (!ssoIssuer()) throw new HttpError(500, "SSO is not configured (SSO_ISSUER)");
+ if (!ssoClientId()) throw new HttpError(500, "SSO is not configured (SSO_CLIENT_ID)");
+ if (!ssoClientSecret()) throw new HttpError(500, "SSO is not configured (SSO_CLIENT_SECRET)");
+}
+
+/** Fetch (and cache) the issuer's OpenID configuration. */
+export async function discover(): Promise<OidcDiscovery> {
+ const issuer = ssoIssuer();
+ const now = Date.now();
+ if (
+ discoveryCache &&
+ discoveryCache.issuer === issuer &&
+ now - discoveryCache.fetchedAt < DISCOVERY_TTL_MS
+ ) {
+ return discoveryCache.doc;
+ }
+
+ const url = `${issuer}/.well-known/openid-configuration`;
+ let res: Response;
+ try {
+ res = await fetch(url, { headers: { Accept: "application/json" } });
+ } catch (err) {
+ throw new HttpError(502, `Could not reach the SSO: ${String(err)}`);
+ }
+ if (!res.ok) {
+ throw new HttpError(502, `SSO discovery failed (${res.status})`);
+ }
+ const doc = (await res.json()) as OidcDiscovery;
+ if (!doc.authorization_endpoint || !doc.token_endpoint || !doc.userinfo_endpoint) {
+ throw new HttpError(502, "SSO discovery document is missing required endpoints");
+ }
+ if (doc.issuer !== issuer) {
+ throw new HttpError(502, `SSO issuer mismatch: configured ${issuer}, discovered ${doc.issuer}`);
+ }
+ discoveryCache = { issuer, doc, fetchedAt: now };
+ return doc;
+}
+
+interface StoredState {
+ verifier: string;
+ from: string;
+ createdAt: number;
+ /** Set when a native app started this login: the app's own S256 PKCE challenge. */
+ appChallenge?: string;
+}
+
+function stateKey(state: string): string {
+ return `oidc_state:${state}`;
+}
+
+/**
+ * Build the authorization redirect URL and persist the matching PKCE verifier.
+ * `from` is the app path to return the user to after login. `appChallenge` is
+ * set when a native app started the login (see routes/auth.ts).
+ */
+export async function beginLogin(from: string, appChallenge?: string): Promise<string> {
+ assertConfigured();
+ const doc = await discover();
+
+ const state = randomUrlToken(32);
+ const verifier = randomUrlToken(64);
+ const challenge = await sha256Base64Url(verifier);
+
+ await rt().store.put(stateKey(state), {
+ verifier,
+ from: from || "/",
+ createdAt: Date.now(),
+ ...(appChallenge ? { appChallenge } : {}),
+ } satisfies StoredState);
+
+ const authUrl = new URL(doc.authorization_endpoint);
+ authUrl.searchParams.set("response_type", "code");
+ authUrl.searchParams.set("client_id", ssoClientId() as string);
+ authUrl.searchParams.set("redirect_uri", ssoRedirectUri());
+ authUrl.searchParams.set("scope", ssoScopes());
+ authUrl.searchParams.set("state", state);
+ authUrl.searchParams.set("code_challenge", challenge);
+ authUrl.searchParams.set("code_challenge_method", "S256");
+ return authUrl.toString();
+}
+
+export interface CallbackResult {
+ identity: OidcIdentity;
+ tokens: SsoTokens;
+ /** The original app path to return the user to. */
+ from: string;
+ /** The native app's PKCE challenge, when an app started this login. */
+ appChallenge?: string;
+}
+
+/**
+ * Whether a pending login was started by a native app, without consuming it.
+ * Lets a callback that fails before the code exchange (the SSO refusing the
+ * account, say) still send the person back to the app rather than the website.
+ */
+export async function isAppLogin(state: string | undefined): Promise<boolean> {
+ if (!state) return false;
+ const stored = await rt().store.get<StoredState | null>(stateKey(state), null);
+ return Boolean(stored?.appChallenge);
+}
+
+/** Thrown when the SSO definitively refuses a grant (as opposed to being unreachable). */
+export class GrantRejectedError extends Error {}
+
+async function tokenRequest(params: Record<string, string>): Promise<Record<string, unknown>> {
+ const doc = await discover();
+ const body = new URLSearchParams({
+ ...params,
+ client_id: ssoClientId() as string,
+ client_secret: ssoClientSecret() as string,
+ });
+
+ let res: Response;
+ try {
+ res = await fetch(doc.token_endpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
+ body,
+ });
+ } catch (err) {
+ throw new HttpError(502, `SSO token request failed: ${String(err)}`);
+ }
+
+ if (!res.ok) {
+ const detail = await res.text().catch(() => "");
+ let error = "";
+ try {
+ error = String((JSON.parse(detail) as { error?: string }).error ?? "");
+ } catch {
+ // not JSON
+ }
+ if (error === "invalid_grant") throw new GrantRejectedError(detail);
+ throw new HttpError(res.status === 401 ? 502 : 401, `The SSO rejected the request (${res.status}). ${detail}`.trim());
+ }
+ return (await res.json()) as Record<string, unknown>;
+}
+
+/**
+ * Complete the flow: validate state, exchange the code, and read identity
+ * claims. Consumes the stored state (single use).
+ */
+export async function completeLogin(code: string, state: string, iss: string | undefined): Promise<CallbackResult> {
+ assertConfigured();
+
+ const key = stateKey(state);
+ const stored = await rt().store.take<StoredState>(key);
+ // Consume immediately so a replayed callback can't reuse it.
+
+ if (!stored) {
+ throw new HttpError(400, "Login session expired or invalid. Please try again.");
+ }
+ if (Date.now() - stored.createdAt > OIDC_STATE_TTL_MINUTES * 60 * 1000) {
+ throw new HttpError(400, "Login session expired. Please try again.");
+ }
+
+ const doc = await discover();
+ // RFC 9207: when the SSO names itself on the callback it must be the one we
+ // sent the user to, so a response from a different provider can't be mixed in.
+ if (iss !== undefined && iss !== doc.issuer) {
+ throw new HttpError(400, "Login response came from an unexpected issuer.");
+ }
+
+ // ---- Exchange the authorization code for tokens (direct TLS) -----------
+ let tokens: Record<string, unknown>;
+ try {
+ tokens = await tokenRequest({
+ grant_type: "authorization_code",
+ code,
+ redirect_uri: ssoRedirectUri(),
+ code_verifier: stored.verifier,
+ });
+ } catch (err) {
+ if (err instanceof GrantRejectedError) {
+ throw new HttpError(401, "The SSO rejected the login. Please try again.");
+ }
+ throw err;
+ }
+
+ const accessToken = typeof tokens.access_token === "string" ? tokens.access_token : "";
+ if (!accessToken) {
+ throw new HttpError(502, "The SSO did not return an access token");
+ }
+
+ // ---- Read identity claims from the userinfo endpoint -------------------
+ let infoRes: Response;
+ try {
+ infoRes = await fetch(doc.userinfo_endpoint, {
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
+ });
+ } catch (err) {
+ throw new HttpError(502, `SSO userinfo request failed: ${String(err)}`);
+ }
+ if (!infoRes.ok) {
+ throw new HttpError(502, `SSO userinfo request failed (${infoRes.status})`);
+ }
+
+ const claims = (await infoRes.json()) as Record<string, unknown>;
+ const sub = typeof claims.sub === "string" ? claims.sub : "";
+ if (!sub) throw new HttpError(502, "The SSO did not return a subject identifier");
+
+ const preferredUsername =
+ (typeof claims.preferred_username === "string" && claims.preferred_username) ||
+ (typeof claims.nickname === "string" && claims.nickname) ||
+ (typeof claims.name === "string" && claims.name) ||
+ // Last resort: a deterministic username derived from the subject.
+ `user_${sub.slice(0, 12)}`;
+
+ const email = typeof claims.email === "string" ? claims.email : null;
+ const displayName =
+ (typeof claims.name === "string" && claims.name) ||
+ (typeof claims.preferred_username === "string" && claims.preferred_username) ||
+ null;
+
+ return {
+ identity: { sub, issuer: doc.issuer, preferredUsername, email, displayName },
+ tokens: {
+ refreshToken: typeof tokens.refresh_token === "string" ? tokens.refresh_token : null,
+ idToken: typeof tokens.id_token === "string" ? tokens.id_token : null,
+ },
+ from: stored.from || "/",
+ ...(stored.appChallenge ? { appChallenge: stored.appChallenge } : {}),
+ };
+}
+
+/**
+ * Ask the SSO whether it still vouches for a session. Throws
+ * GrantRejectedError when it doesn't (account disabled, removed from this
+ * app's allowed groups, signed out everywhere); any other error means the SSO
+ * couldn't be asked.
+ */
+export async function refreshTokens(refreshToken: string): Promise<SsoTokens> {
+ const tokens = await tokenRequest({ grant_type: "refresh_token", refresh_token: refreshToken });
+ return {
+ refreshToken: typeof tokens.refresh_token === "string" ? tokens.refresh_token : null,
+ idToken: typeof tokens.id_token === "string" ? tokens.id_token : null,
+ };
+}
+
+/** Best-effort RFC 7009 revocation of a session's refresh token. */
+export async function revokeRefreshToken(refreshToken: string): Promise<void> {
+ const doc = await discover();
+ if (!doc.revocation_endpoint) return;
+ await fetch(doc.revocation_endpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ token: refreshToken,
+ token_type_hint: "refresh_token",
+ client_id: ssoClientId() as string,
+ client_secret: ssoClientSecret() as string,
+ }),
+ });
+}
+
+/** Where to send the browser so the SSO session ends too. */
+export async function endSessionUrl(idToken: string | null): Promise<string | null> {
+ const doc = await discover();
+ if (!doc.end_session_endpoint) return null;
+ const url = new URL(doc.end_session_endpoint);
+ url.searchParams.set("post_logout_redirect_uri", ssoPostLogoutRedirectUri());
+ url.searchParams.set("client_id", ssoClientId() as string);
+ // With the id_token as proof, the SSO signs out without asking again.
+ if (idToken) url.searchParams.set("id_token_hint", idToken);
+ return url.toString();
+}
diff --git a/src/lib/server/plural/services/pride.ts b/src/lib/server/plural/services/pride.ts
new file mode 100644
index 0000000..17b55ad
--- /dev/null
+++ b/src/lib/server/plural/services/pride.ts
@@ -0,0 +1,82 @@
+/* src/lib/server/plural/services/pride.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 type { JsonObject } from "../types";
+import { rt } from "../runtime";
+
+type MemberPrideMap = Record<string, string[]>;
+
+const KEY = "member_pride";
+
+const DEFAULT_MEMBER_PRIDE: MemberPrideMap = {};
+
+export async function getMemberPride(): Promise<MemberPrideMap> {
+ const stored = await rt().store.get<MemberPrideMap | null>(KEY, null);
+ if (!stored) {
+ await saveMemberPride(DEFAULT_MEMBER_PRIDE);
+ return { ...DEFAULT_MEMBER_PRIDE };
+ }
+ return stored;
+}
+
+export async function saveMemberPride(memberPride: MemberPrideMap): Promise<void> {
+ await rt().store.put(KEY, memberPride);
+}
+
+export async function getMemberPrideById(
+ memberId: string,
+ memberName: string,
+): Promise<string[]> {
+ const memberPride = await getMemberPride();
+ return memberPride[memberName] ?? memberPride[memberId] ?? [];
+}
+
+export async function updateMemberPride(
+ memberIdentifier: string,
+ identities: string[],
+): Promise<boolean> {
+ const memberPride = await getMemberPride();
+ memberPride[memberIdentifier] = identities;
+ await saveMemberPride(memberPride);
+ return true;
+}
+
+export async function addMemberPride(
+ memberIdentifier: string,
+ identity: string,
+): Promise<boolean> {
+ const memberPride = await getMemberPride();
+ const list = (memberPride[memberIdentifier] ??= []);
+ if (!list.includes(identity)) {
+ list.push(identity);
+ await saveMemberPride(memberPride);
+ return true;
+ }
+ return false;
+}
+
+export async function removeMemberPride(
+ memberIdentifier: string,
+ identity: string,
+): Promise<boolean> {
+ const memberPride = await getMemberPride();
+ const identities = memberPride[memberIdentifier];
+ if (identities && identities.includes(identity)) {
+ memberPride[memberIdentifier] = identities.filter((one) => one !== identity);
+ await saveMemberPride(memberPride);
+ return true;
+ }
+ return false;
+}
+
+export async function enrichMembersWithPride(members: JsonObject[]): Promise<JsonObject[]> {
+ const enriched: JsonObject[] = [];
+ for (const member of members) {
+ const pride = await getMemberPrideById(member.id ?? "", member.name ?? "");
+ enriched.push({ ...member, pride });
+ }
+ return enriched;
+}
diff --git a/src/lib/server/plural/services/relationships.ts b/src/lib/server/plural/services/relationships.ts
new file mode 100644
index 0000000..2dfef2c
--- /dev/null
+++ b/src/lib/server/plural/services/relationships.ts
@@ -0,0 +1,70 @@
+/* src/lib/server/plural/services/relationships.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 { rt } from "../runtime";
+
+export interface Relationship {
+ id: string;
+ members: [string, string];
+ type: string;
+ since: string | null;
+}
+
+export interface RelationshipInput {
+ memberA: string;
+ memberB: string;
+ type?: string;
+ since?: string | null;
+}
+
+const KEY = "member_relationships";
+
+const DEFAULT_RELATIONSHIPS: Relationship[] = [];
+
+export async function getRelationships(): Promise<Relationship[]> {
+ const stored = await rt().store.get<Relationship[] | null>(KEY, null);
+ if (!stored) {
+ await saveRelationships(DEFAULT_RELATIONSHIPS);
+ return [...DEFAULT_RELATIONSHIPS];
+ }
+ return stored;
+}
+
+export async function saveRelationships(relationships: Relationship[]): Promise<void> {
+ await rt().store.put(KEY, relationships);
+}
+
+export async function addRelationship(input: RelationshipInput): Promise<Relationship> {
+ const relationships = await getRelationships();
+
+ const alreadyLinked = relationships.some(
+ (edge) =>
+ (edge.members[0] === input.memberA && edge.members[1] === input.memberB) ||
+ (edge.members[0] === input.memberB && edge.members[1] === input.memberA),
+ );
+ if (alreadyLinked) {
+ throw new Error("These members are already linked");
+ }
+
+ const relationship: Relationship = {
+ id: crypto.randomUUID(),
+ members: [input.memberA, input.memberB],
+ type: input.type ?? "partner",
+ since: input.since ?? null,
+ };
+
+ relationships.push(relationship);
+ await saveRelationships(relationships);
+ return relationship;
+}
+
+export async function removeRelationship(id: string): Promise<boolean> {
+ const relationships = await getRelationships();
+ const next = relationships.filter((edge) => edge.id !== id);
+ if (next.length === relationships.length) return false;
+ await saveRelationships(next);
+ return true;
+}
diff --git a/src/lib/server/plural/services/sso_sessions.ts b/src/lib/server/plural/services/sso_sessions.ts
new file mode 100644
index 0000000..b90ec07
--- /dev/null
+++ b/src/lib/server/plural/services/sso_sessions.ts
@@ -0,0 +1,154 @@
+/* src/lib/server/plural/services/sso_sessions.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.
+ */
+
+/**
+ * SSO-backed sessions.
+ *
+ * The JWT the API hands the frontend is stateless, so on its own an account
+ * disabled on the SSO would keep working here until the token expired. Each
+ * JWT therefore carries a session id (`sid`) that points at one of these
+ * records, which holds the SSO refresh token from the login:
+ *
+ * - every authenticated request looks the session up, so logout (or the
+ * session expiring) ends the JWT immediately;
+ * - every RECHECK_AFTER_MS the refresh token is spent at the SSO. The SSO
+ * refuses it once the account is disabled, taken out of this app's
+ * allowed groups, or signed out everywhere — and the session ends.
+ *
+ * The SSO rotates refresh tokens and treats replays as theft, so a D1
+ * compare-and-swap makes sure only one request spends each token.
+ */
+
+import { randomUrlToken } from "../security";
+import { rt } from "../runtime";
+import { GrantRejectedError, refreshTokens, type SsoTokens } from "./oidc";
+
+const RECHECK_AFTER_MS = 10 * 60 * 1000;
+/** How long sessions survive while the SSO can't be reached. */
+const OUTAGE_GRACE_MS = 60 * 60 * 1000;
+/** Minimum gap between retries while the SSO is unreachable. */
+const RETRY_AFTER_MS = 60 * 1000;
+
+const INDEX_KEY = "sso_sessions_index";
+
+export interface SsoSession {
+ sid: string;
+ userId: string;
+ username: string;
+ refreshToken: string | null;
+ idToken: string | null;
+ createdAt: number;
+ verifiedAt: number;
+ checkedAt: number;
+ expiresAt: number;
+}
+
+interface IndexEntry {
+ sid: string;
+ expiresAt: number;
+}
+
+function sessionKey(sid: string): string {
+ return `sso_session:${sid}`;
+}
+
+/** Drops index entries (and their sessions) that have expired. */
+async function pruneExpired(index: IndexEntry[]): Promise<IndexEntry[]> {
+ const now = Date.now();
+ const live: IndexEntry[] = [];
+ for (const entry of index) {
+ if (entry.expiresAt > now) live.push(entry);
+ else await rt().store.delete(sessionKey(entry.sid));
+ }
+ return live;
+}
+
+export async function createSsoSession(
+ user: { id: string; username: string },
+ tokens: SsoTokens,
+ expiresAt: number,
+): Promise<string> {
+ const sid = randomUrlToken(24);
+ const now = Date.now();
+ const session: SsoSession = {
+ sid,
+ userId: user.id,
+ username: user.username,
+ refreshToken: tokens.refreshToken,
+ idToken: tokens.idToken,
+ createdAt: now,
+ verifiedAt: now,
+ checkedAt: now,
+ expiresAt,
+ };
+ await rt().store.put(sessionKey(sid), session);
+
+ const index = await pruneExpired(await rt().store.get<IndexEntry[]>(INDEX_KEY, []));
+ index.push({ sid, expiresAt });
+ await rt().store.put(INDEX_KEY, index);
+ return sid;
+}
+
+async function readSession(sid: string): Promise<SsoSession | null> {
+ const session = await rt().store.get<SsoSession | null>(sessionKey(sid), null);
+ if (!session) return null;
+ if (session.expiresAt <= Date.now()) {
+ await rt().store.delete(sessionKey(sid));
+ return null;
+ }
+ return session;
+}
+
+async function revalidate(session: SsoSession): Promise<SsoSession | null> {
+ const now = Date.now();
+ if (now - session.verifiedAt < RECHECK_AFTER_MS || !session.refreshToken) return session;
+
+ const overdue = now - session.verifiedAt > RECHECK_AFTER_MS + OUTAGE_GRACE_MS;
+ if (now - session.checkedAt < RETRY_AFTER_MS) {
+ if (!overdue) return session;
+ await rt().store.delete(sessionKey(session.sid));
+ return null;
+ }
+
+ // Claim the re-check. Only one request, in any isolate, wins the swap and spends the token
+ const claimed = { ...session, checkedAt: now };
+ const won = await rt().store.swap(sessionKey(session.sid), session, claimed);
+ if (!won) return overdue ? null : session;
+
+ try {
+ const fresh = await refreshTokens(session.refreshToken);
+ const at = Date.now();
+ const updated: SsoSession = {
+ ...session,
+ refreshToken: fresh.refreshToken ?? session.refreshToken,
+ idToken: fresh.idToken ?? session.idToken,
+ verifiedAt: at,
+ checkedAt: at,
+ };
+ await rt().store.put(sessionKey(session.sid), updated);
+ return updated;
+ } catch (err) {
+ if (err instanceof GrantRejectedError || overdue) {
+ await rt().store.delete(sessionKey(session.sid));
+ return null;
+ }
+ console.warn(`Could not reach the SSO to re-check a session: ${String(err)}`);
+ return claimed;
+ }
+}
+
+/** The live session for `sid`, re-checked with the SSO when due. */
+export async function currentSsoSession(sid: string): Promise<SsoSession | null> {
+ const session = await readSession(sid);
+ return session ? revalidate(session) : null;
+}
+
+/** Ends a session here and returns it, so the caller can end it at the SSO too. */
+export async function endSsoSession(sid: string): Promise<SsoSession | null> {
+ const session = await readSession(sid);
+ await rt().store.delete(sessionKey(sid));
+ return session;
+}
diff --git a/src/lib/server/plural/services/status.ts b/src/lib/server/plural/services/status.ts
new file mode 100644
index 0000000..00261b5
--- /dev/null
+++ b/src/lib/server/plural/services/status.ts
@@ -0,0 +1,72 @@
+/* src/lib/server/plural/services/status.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 type { JsonObject } from "../types";
+import { rt } from "../runtime";
+
+interface MemberStatus {
+ text: string;
+ emoji: string | null;
+ updated_at: string;
+}
+
+type StatusMap = Record<string, MemberStatus>;
+
+const KEY = "member_status";
+
+export async function getAllStatuses(): Promise<StatusMap> {
+ return rt().store.get<StatusMap>(KEY, {});
+}
+
+export async function saveAllStatuses(statuses: StatusMap): Promise<void> {
+ await rt().store.put(KEY, statuses);
+}
+
+export async function getMemberStatus(memberIdentifier: string): Promise<MemberStatus | null> {
+ const statuses = await getAllStatuses();
+ return statuses[memberIdentifier] ?? null;
+}
+
+export async function setMemberStatus(
+ memberIdentifier: string,
+ statusText: string,
+ emoji?: string | null,
+): Promise<MemberStatus> {
+ const statuses = await getAllStatuses();
+ const statusObj: MemberStatus = {
+ text: statusText,
+ emoji: emoji ?? null,
+ updated_at: new Date().toISOString(),
+ };
+ statuses[memberIdentifier] = statusObj;
+ await saveAllStatuses(statuses);
+ return statusObj;
+}
+
+export async function clearMemberStatus(memberIdentifier: string): Promise<boolean> {
+ const statuses = await getAllStatuses();
+ if (memberIdentifier in statuses) {
+ delete statuses[memberIdentifier];
+ await saveAllStatuses(statuses);
+ return true;
+ }
+ return false;
+}
+
+export async function enrichMemberWithStatus(member: JsonObject): Promise<JsonObject> {
+ const memberId = member.id;
+ const memberName = member.name;
+
+ let status: MemberStatus | null = null;
+ if (memberId) status = await getMemberStatus(String(memberId));
+ if (!status && memberName) status = await getMemberStatus(memberName);
+
+ return { ...member, status };
+}
+
+export async function enrichMembersWithStatus(members: JsonObject[]): Promise<JsonObject[]> {
+ return Promise.all(members.map((member) => enrichMemberWithStatus(member)));
+}
diff --git a/src/lib/server/plural/services/system.ts b/src/lib/server/plural/services/system.ts
new file mode 100644
index 0000000..07ac581
--- /dev/null
+++ b/src/lib/server/plural/services/system.ts
@@ -0,0 +1,279 @@
+/* src/lib/server/plural/services/system.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 { rt } from "../runtime";
+import { HttpError } from "../errors";
+import type { JsonObject } from "../types";
+
+// Shown instead of the stored name for a few placeholder members
+const SPECIAL_DISPLAY_NAMES: Record<string, string> = {
+ answer: "Answer Machine",
+ system: "Unsure",
+ sleeping: "I am sleeping",
+};
+
+// Columns a caller may write, and how each is stored
+const MEMBER_TEXT_FIELDS = [
+ "name",
+ "display_name",
+ "color",
+ "birthday",
+ "pronouns",
+ "avatar_url",
+ "webhook_avatar_url",
+ "banner",
+ "description",
+] as const;
+
+const SYSTEM_TEXT_FIELDS = [
+ "name",
+ "description",
+ "tag",
+ "pronouns",
+ "avatar_url",
+ "banner",
+ "color",
+ "timezone",
+] as const;
+
+type Row = Record<string, unknown>;
+
+function parseJson<T>(raw: unknown, fallback: T): T {
+ if (typeof raw !== "string") return fallback;
+ try {
+ return JSON.parse(raw) as T;
+ } catch {
+ return fallback;
+ }
+}
+
+function systemFromRow(row: Row): JsonObject {
+ return {
+ ...row,
+ privacy: parseJson(row.privacy, {}),
+ };
+}
+
+function memberFromRow(row: Row): JsonObject {
+ const member: JsonObject = {
+ ...row,
+ system: row.system_id,
+ proxy_tags: parseJson(row.proxy_tags, []),
+ keep_proxy: row.keep_proxy === 1,
+ autoproxy_enabled: row.autoproxy_enabled === null ? null : row.autoproxy_enabled === 1,
+ privacy: parseJson(row.privacy, {}),
+ };
+ delete member.system_id;
+
+ const name = String(member.name);
+ if (name in SPECIAL_DISPLAY_NAMES) {
+ member.display_name = SPECIAL_DISPLAY_NAMES[name];
+ member.is_special = true;
+ member.original_name = name;
+ }
+ return member;
+}
+
+// A 6-letter id in PluralKit's style, so imported and new ids look alike
+function newShortId(): string {
+ const letters = "abcdefghijklmnopqrstuvwxyz";
+ const bytes = crypto.getRandomValues(new Uint8Array(6));
+ return Array.from(bytes, (byte) => letters[byte % letters.length]).join("");
+}
+
+// ---- System ----
+
+async function systemRow(): Promise<Row> {
+ const row = await rt().db.prepare("SELECT * FROM systems LIMIT 1").first<Row>();
+ if (!row) throw new HttpError(404, "No system yet. Import one first.");
+ return row;
+}
+
+export async function systemId(): Promise<string> {
+ return String((await systemRow()).id);
+}
+
+export async function getSystem(): Promise<JsonObject> {
+ return systemFromRow(await systemRow());
+}
+
+export async function updateSystem(patch: JsonObject): Promise<JsonObject> {
+ const row = await systemRow();
+ const sets: string[] = [];
+ const values: unknown[] = [];
+
+ for (const field of SYSTEM_TEXT_FIELDS) {
+ if (field in patch) {
+ sets.push(`${field} = ?`);
+ values.push(patch[field] ?? null);
+ }
+ }
+ if ("privacy" in patch) {
+ sets.push("privacy = ?");
+ values.push(JSON.stringify(patch.privacy ?? {}));
+ }
+
+ if (sets.length > 0) {
+ await rt()
+ .db.prepare(`UPDATE systems SET ${sets.join(", ")} WHERE id = ?`)
+ .bind(...values, row.id)
+ .run();
+ }
+ return getSystem();
+}
+
+// ---- Members ----
+
+export async function getMembers(): Promise<JsonObject[]> {
+ const { results } = await rt().db.prepare("SELECT * FROM members ORDER BY name COLLATE NOCASE").all<Row>();
+ return results.map(memberFromRow);
+}
+
+// By id, or by name (case-insensitive), as the old routes accepted
+export async function findMember(identifier: string): Promise<JsonObject | null> {
+ const row = await rt()
+ .db.prepare("SELECT * FROM members WHERE id = ? OR lower(name) = lower(?) LIMIT 1")
+ .bind(identifier, identifier)
+ .first<Row>();
+ return row ? memberFromRow(row) : null;
+}
+
+function memberColumns(input: JsonObject): { names: string[]; values: unknown[] } {
+ const names: string[] = [];
+ const values: unknown[] = [];
+
+ for (const field of MEMBER_TEXT_FIELDS) {
+ if (field in input) {
+ names.push(field);
+ values.push(input[field] ?? null);
+ }
+ }
+ if ("proxy_tags" in input) {
+ names.push("proxy_tags");
+ values.push(JSON.stringify(input.proxy_tags ?? []));
+ }
+ if ("keep_proxy" in input) {
+ names.push("keep_proxy");
+ values.push(input.keep_proxy ? 1 : 0);
+ }
+ if ("autoproxy_enabled" in input) {
+ names.push("autoproxy_enabled");
+ values.push(input.autoproxy_enabled == null ? null : input.autoproxy_enabled ? 1 : 0);
+ }
+ if ("privacy" in input) {
+ names.push("privacy");
+ values.push(JSON.stringify(input.privacy ?? {}));
+ }
+ return { names, values };
+}
+
+async function assertNameFree(name: string, exceptId?: string): Promise<void> {
+ const clash = await findMember(name);
+ if (clash && clash.id !== exceptId && String(clash.original_name ?? clash.name).toLowerCase() === name.toLowerCase()) {
+ throw new HttpError(409, `A member named '${name}' already exists`);
+ }
+}
+
+export async function createMember(input: JsonObject): Promise<JsonObject> {
+ const system = await systemId();
+ await assertNameFree(String(input.name));
+
+ let id = newShortId();
+ while (await findMember(id)) id = newShortId();
+
+ const { names, values } = memberColumns(input);
+ const columns = ["id", "uuid", "system_id", "created", ...names];
+ const placeholders = columns.map(() => "?").join(", ");
+
+ await rt()
+ .db.prepare(`INSERT INTO members (${columns.join(", ")}) VALUES (${placeholders})`)
+ .bind(id, crypto.randomUUID(), system, new Date().toISOString(), ...values)
+ .run();
+
+ return (await findMember(id)) as JsonObject;
+}
+
+export async function updateMember(identifier: string, patch: JsonObject): Promise<JsonObject> {
+ const member = await findMember(identifier);
+ if (!member) throw new HttpError(404, "Member not found");
+ if (typeof patch.name === "string") await assertNameFree(patch.name, member.id);
+
+ const { names, values } = memberColumns(patch);
+ if (names.length > 0) {
+ const sets = names.map((name) => `${name} = ?`).join(", ");
+ await rt()
+ .db.prepare(`UPDATE members SET ${sets} WHERE id = ?`)
+ .bind(...values, member.id)
+ .run();
+ }
+ return (await findMember(member.id)) as JsonObject;
+}
+
+// Past switches keep the id, so fronting history still adds up
+export async function deleteMember(identifier: string): Promise<boolean> {
+ const member = await findMember(identifier);
+ if (!member) return false;
+ await rt().db.prepare("DELETE FROM members WHERE id = ?").bind(member.id).run();
+ return true;
+}
+
+// ---- Switches and fronters ----
+
+function switchFromRow(row: Row): JsonObject {
+ return {
+ id: row.id,
+ timestamp: row.timestamp,
+ members: parseJson<string[]>(row.members, []),
+ };
+}
+
+// Newest first, as PluralKit returned them
+export async function getSwitches(limit = 1000, before?: string): Promise<JsonObject[]> {
+ const statement = before
+ ? rt().db.prepare("SELECT * FROM switches WHERE timestamp < ? ORDER BY timestamp DESC LIMIT ?").bind(before, limit)
+ : rt().db.prepare("SELECT * FROM switches ORDER BY timestamp DESC LIMIT ?").bind(limit);
+ const { results } = await statement.all<Row>();
+ return results.map(switchFromRow);
+}
+
+export async function getFronters(): Promise<JsonObject> {
+ const [latest] = await getSwitches(1);
+ if (!latest) return { id: null, timestamp: null, members: [] };
+
+ const members = await getMembers();
+ const byId = new Map(members.map((member) => [member.id, member]));
+ return {
+ ...latest,
+ members: (latest.members as string[])
+ .map((id) => byId.get(id))
+ .filter((member): member is JsonObject => Boolean(member)),
+ };
+}
+
+export async function setFront(memberIds: string[]): Promise<JsonObject> {
+ const unique = [...new Set(memberIds.map(String))];
+ if (unique.length !== memberIds.length) throw new HttpError(400, "Duplicate member IDs in switch");
+
+ const known = new Set((await getMembers()).map((member) => member.id));
+ const unknown = unique.filter((id) => !known.has(id));
+ if (unknown.length > 0) throw new HttpError(400, `Invalid member IDs: ${unknown.join(", ")}`);
+
+ const entry = {
+ id: crypto.randomUUID(),
+ timestamp: new Date().toISOString(),
+ members: unique,
+ };
+ await rt()
+ .db.prepare("INSERT INTO switches (id, system_id, timestamp, members) VALUES (?, ?, ?, ?)")
+ .bind(entry.id, await systemId(), entry.timestamp, JSON.stringify(entry.members))
+ .run();
+ return entry;
+}
+
+export async function deleteSwitch(id: string): Promise<boolean> {
+ const result = await rt().db.prepare("DELETE FROM switches WHERE id = ?").bind(id).run();
+ return result.meta.changes === 1;
+}
diff --git a/src/lib/server/plural/services/tags.ts b/src/lib/server/plural/services/tags.ts
new file mode 100644
index 0000000..7f0b690
--- /dev/null
+++ b/src/lib/server/plural/services/tags.ts
@@ -0,0 +1,69 @@
+/* src/lib/server/plural/services/tags.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 type { JsonObject } from "../types";
+import { rt } from "../runtime";
+
+type MemberTagsMap = Record<string, string[]>;
+
+const KEY = "member_tags";
+const DEFAULT_MEMBER_TAGS: MemberTagsMap = { C1: ["Host"] };
+
+export async function getMemberTags(): Promise<MemberTagsMap> {
+ const stored = await rt().store.get<MemberTagsMap | null>(KEY, null);
+ if (!stored) {
+ await saveMemberTags(DEFAULT_MEMBER_TAGS);
+ return { ...DEFAULT_MEMBER_TAGS };
+ }
+ return stored;
+}
+
+export async function saveMemberTags(memberTags: MemberTagsMap): Promise<void> {
+ await rt().store.put(KEY, memberTags);
+}
+
+export async function getMemberTagsById(memberId: string, memberName: string): Promise<string[]> {
+ const memberTags = await getMemberTags();
+ return memberTags[memberName] ?? memberTags[memberId] ?? [];
+}
+
+export async function updateMemberTags(memberIdentifier: string, tags: string[]): Promise<boolean> {
+ const memberTags = await getMemberTags();
+ memberTags[memberIdentifier] = tags;
+ await saveMemberTags(memberTags);
+ return true;
+}
+
+export async function addMemberTag(memberIdentifier: string, tag: string): Promise<boolean> {
+ const memberTags = await getMemberTags();
+ const list = (memberTags[memberIdentifier] ??= []);
+ if (!list.includes(tag)) {
+ list.push(tag);
+ await saveMemberTags(memberTags);
+ return true;
+ }
+ return false;
+}
+
+export async function removeMemberTag(memberIdentifier: string, tag: string): Promise<boolean> {
+ const memberTags = await getMemberTags();
+ const tags = memberTags[memberIdentifier];
+ if (tags && tags.includes(tag)) {
+ memberTags[memberIdentifier] = tags.filter((t) => t !== tag);
+ await saveMemberTags(memberTags);
+ return true;
+ }
+ return false;
+}
+
+export async function enrichMembersWithTags(members: JsonObject[]): Promise<JsonObject[]> {
+ const enriched: JsonObject[] = [];
+ for (const member of members) {
+ const tags = await getMemberTagsById(member.id ?? "", member.name ?? "");
+ enriched.push({ ...member, tags });
+ }
+ return enriched;
+}
diff --git a/src/lib/server/plural/services/users.ts b/src/lib/server/plural/services/users.ts
new file mode 100644
index 0000000..e6561e8
--- /dev/null
+++ b/src/lib/server/plural/services/users.ts
@@ -0,0 +1,367 @@
+/* src/lib/server/plural/services/users.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.
+ */
+
+/**
+ * User management service.
+ *
+ * Authentication is the Doughmination SSO (OIDC) only — there are no passwords
+ * here. Each account is linked to an SSO subject (`pocket_id` + `sso_issuer`);
+ * on first login we match an existing, not-yet-linked account by username and
+ * fill in the link, or provision a new non-admin account. Roles (admin/owner/pet), avatars and the owner
+ * protections are unchanged. Storage is the DO blob store (key "users").
+ */
+
+import type { User, UserCreate, UserUpdate } from "../models";
+import { adminUsername, adminDisplayName, adminEmail } from "../config";
+import { rt } from "../runtime";
+
+const USERS_KEY = "users";
+
+export function getOwnerUsername(): string {
+ return adminUsername();
+}
+
+export function isOwnerUsername(username: string): boolean {
+ return username.toLowerCase() === getOwnerUsername().toLowerCase();
+}
+
+export async function getUsers(): Promise<User[]> {
+ const usersData = await rt().store.get<Array<Record<string, unknown>>>(USERS_KEY, []);
+
+ return usersData.map((userDict) => {
+ if (!("is_owner" in userDict)) userDict.is_owner = false;
+ if (!("is_pet" in userDict)) userDict.is_pet = false;
+
+ if (isOwnerUsername(String(userDict.username ?? ""))) {
+ userDict.is_owner = true;
+ userDict.is_admin = true;
+ userDict.is_pet = true;
+ // The owner account predates the email field. Backfill it from
+ // ADMIN_EMAIL so contact metadata is present; an address already set by
+ // hand always wins.
+ if (!userDict.email) {
+ const seeded = adminEmail();
+ if (seeded) userDict.email = seeded;
+ }
+ }
+ return userDict as unknown as User;
+ });
+}
+
+export async function saveUsers(users: User[]): Promise<void> {
+ for (const user of users) {
+ if (isOwnerUsername(user.username)) {
+ user.is_owner = true;
+ user.is_admin = true;
+ user.is_pet = true;
+ if (!user.email) {
+ const seeded = adminEmail();
+ if (seeded) user.email = seeded;
+ }
+ }
+ }
+ await rt().store.put(USERS_KEY, users);
+}
+
+export async function getUserByUsername(username: string): Promise<User | null> {
+ const users = await getUsers();
+ return users.find((u) => u.username.toLowerCase() === username.toLowerCase()) ?? null;
+}
+
+export async function getUserById(userId: string): Promise<User | null> {
+ const users = await getUsers();
+ return users.find((u) => u.id === userId) ?? null;
+}
+
+export async function getUserBySub(sub: string, issuer: string): Promise<User | null> {
+ if (!sub) return null;
+ const users = await getUsers();
+ return users.find((u) => u.pocket_id === sub && u.sso_issuer === issuer) ?? null;
+}
+
+export function normalizeEmail(email: string): string {
+ return email.trim().toLowerCase();
+}
+
+export async function getUserByEmail(email: string): Promise<User | null> {
+ const target = normalizeEmail(email);
+ if (!target) return null;
+ const users = await getUsers();
+ return users.find((u) => u.email && normalizeEmail(u.email) === target) ?? null;
+}
+
+/** Throw if `email` is already used by a different account. */
+async function assertEmailAvailable(email: string, exceptUserId?: string): Promise<void> {
+ const target = normalizeEmail(email);
+ const users = await getUsers();
+ const clash = users.find(
+ (u) => u.id !== exceptUserId && u.email && normalizeEmail(u.email) === target,
+ );
+ if (clash) throw new Error("Email address is already in use");
+}
+
+export async function createUser(
+ userCreate: UserCreate,
+ requestingUser?: User | null,
+): Promise<User> {
+ const users = await getUsers();
+
+ if (await getUserByUsername(userCreate.username)) {
+ throw new Error(`Username '${userCreate.username}' already exists`);
+ }
+
+ if (isOwnerUsername(userCreate.username) && requestingUser != null) {
+ throw new Error(
+ "Cannot create user with owner username. Owner account must be created via initial setup.",
+ );
+ }
+
+ let isOwner: boolean;
+ let isAdmin: boolean;
+ let isPet: boolean;
+
+ if (isOwnerUsername(userCreate.username)) {
+ isOwner = true;
+ isAdmin = true;
+ isPet = false;
+ } else {
+ isOwner = false;
+ isAdmin = userCreate.is_admin;
+ isPet = userCreate.is_pet;
+ }
+
+ const email = userCreate.email ? normalizeEmail(userCreate.email) : null;
+ if (email) await assertEmailAvailable(email);
+
+ const newUser: User = {
+ id: crypto.randomUUID(),
+ username: userCreate.username,
+ pocket_id: userCreate.pocket_id ?? null,
+ display_name: userCreate.display_name ?? null,
+ email,
+ created_at: new Date().toISOString(),
+ is_admin: isAdmin,
+ is_owner: isOwner,
+ is_pet: isPet,
+ avatar_url: null,
+ };
+
+ users.push(newUser);
+ await saveUsers(users);
+ return newUser;
+}
+
+/**
+ * Resolve an SSO login to a local account.
+ *
+ * Match order:
+ * 1. the account already linked to this subject on this issuer;
+ * 2. an account pre-provisioned with this subject but no issuer yet;
+ * 3. by username (case-insensitive), but ONLY an account that isn't linked
+ * to this issuer yet — the owner seed, admin-provisioned accounts, and
+ * accounts from the PocketID days. Each such account is adopted once.
+ *
+ * An account already linked to a *different* subject on this issuer is never
+ * taken over by username, so a reused or renamed SSO username can't inherit
+ * someone else's account (including the owner's). Unknown users are
+ * auto-provisioned as non-admins.
+ */
+export async function findOrCreateFromSso(claims: {
+ sub: string;
+ issuer: string;
+ username: string;
+ email?: string | null;
+ displayName?: string | null;
+}): Promise<User> {
+ const users = await getUsers();
+ const sameName = (u: User) => u.username.toLowerCase() === claims.username.toLowerCase();
+
+ const linked = users.find((u) => u.pocket_id === claims.sub && u.sso_issuer === claims.issuer);
+ const preLinked = users.find((u) => u.pocket_id === claims.sub && !u.sso_issuer);
+ const byName = users.find((u) => sameName(u) && u.sso_issuer !== claims.issuer);
+ const existing = linked ?? preLinked ?? byName;
+
+ if (!existing && users.some(sameName)) {
+ throw new Error(
+ `The username '${claims.username}' here is linked to a different SSO account. Ask the owner to sort it out.`,
+ );
+ }
+
+ if (existing) {
+ const index = users.findIndex((u) => u.id === existing.id);
+ let changed = false;
+
+ if (existing.pocket_id !== claims.sub || existing.sso_issuer !== claims.issuer) {
+ console.info(`Linking account '${existing.username}' to ${claims.issuer} subject ${claims.sub}`);
+ existing.pocket_id = claims.sub;
+ existing.sso_issuer = claims.issuer;
+ changed = true;
+ }
+ // Backfill contact/profile metadata from the provider if we don't have it.
+ if (!existing.email && claims.email) {
+ existing.email = normalizeEmail(claims.email);
+ changed = true;
+ }
+ if (!existing.display_name && claims.displayName) {
+ existing.display_name = claims.displayName;
+ changed = true;
+ }
+
+ if (changed) {
+ users[index] = existing;
+ await saveUsers(users);
+ }
+ return existing;
+ }
+
+ // First-time login for an unknown SSO user → provision a plain account.
+ const created = await createUser({
+ username: claims.username,
+ pocket_id: claims.sub,
+ email: claims.email ?? null,
+ display_name: claims.displayName ?? null,
+ is_admin: false,
+ is_pet: false,
+ });
+ return linkIssuer(created.id, claims.issuer);
+}
+
+async function linkIssuer(userId: string, issuer: string): Promise<User> {
+ const users = await getUsers();
+ const index = users.findIndex((u) => u.id === userId);
+ const linked: User = { ...users[index]!, sso_issuer: issuer };
+ users[index] = linked;
+ await saveUsers(users);
+ return linked;
+}
+
+export async function updateUser(
+ userId: string,
+ userUpdate: UserUpdate,
+ requestingUser?: User | null,
+): Promise<User | null> {
+ const users = await getUsers();
+
+ const index = users.findIndex((u) => u.id === userId);
+ const user = users[index];
+ if (!user) return null;
+
+ if (user.is_owner && userUpdate.is_admin === false) {
+ throw new Error("Cannot remove admin privileges from owner");
+ }
+
+ if (requestingUser && user.is_admin && requestingUser.id !== user.id) {
+ if (!requestingUser.is_owner) {
+ throw new Error("Only the owner can modify admin accounts");
+ }
+ }
+
+ // Role assignment (admin/pet) is the owner's job — plain admins can edit
+ // profiles but not grant or revoke roles.
+ const wantsAdminChange = userUpdate.is_admin != null && userUpdate.is_admin !== user.is_admin;
+ const wantsPetChange = userUpdate.is_pet != null && userUpdate.is_pet !== user.is_pet;
+ if ((wantsAdminChange || wantsPetChange) && !requestingUser?.is_owner) {
+ throw new Error("Only the owner can change user roles");
+ }
+
+ // ---- Email (contact metadata only) ------------------------------------
+ // Editable by the account's own user or by an admin/owner. Identity is
+ // proven by the SSO, so there is no confirmation step.
+ let email = user.email ?? null;
+ if (userUpdate.email !== undefined) {
+ const requestedEmail = userUpdate.email ? normalizeEmail(userUpdate.email) : null;
+ const isSelf = requestingUser?.id === user.id;
+ const isAdminActing = !!requestingUser?.is_admin;
+
+ if (requestedEmail !== email) {
+ if (!isSelf && !isAdminActing) {
+ throw new Error("You can only change your own email address");
+ }
+ if (requestedEmail) await assertEmailAvailable(requestedEmail, user.id);
+ email = requestedEmail;
+ }
+ }
+
+ const newIsOwner = isOwnerUsername(user.username);
+ const newIsAdmin = newIsOwner ? true : userUpdate.is_admin ?? user.is_admin;
+ const newIsPet = userUpdate.is_pet ?? user.is_pet;
+
+ const updatedUser: User = {
+ id: user.id,
+ username: user.username,
+ pocket_id: user.pocket_id ?? null,
+ sso_issuer: user.sso_issuer ?? null,
+ // `undefined` = field omitted, keep current value; explicit `null` clears it.
+ display_name: userUpdate.display_name !== undefined ? userUpdate.display_name : user.display_name,
+ email,
+ created_at: user.created_at ?? null,
+ is_admin: newIsAdmin,
+ is_owner: newIsOwner,
+ is_pet: newIsPet,
+ avatar_url: userUpdate.avatar_url !== undefined ? userUpdate.avatar_url : user.avatar_url ?? null,
+ };
+
+ users[index] = updatedUser;
+ await saveUsers(users);
+ return updatedUser;
+}
+
+export async function deleteUser(userId: string, requestingUser?: User | null): Promise<boolean> {
+ const users = await getUsers();
+
+ const userToDelete = users.find((u) => u.id === userId);
+ if (!userToDelete) return false;
+
+ if (userToDelete.is_owner) {
+ throw new Error("Cannot delete the owner account");
+ }
+
+ if (requestingUser && userToDelete.is_admin && !requestingUser.is_owner) {
+ throw new Error("Only the owner can delete admin accounts");
+ }
+
+ const remaining = users.filter((u) => u.id !== userId);
+ if (remaining.length < users.length) {
+ await saveUsers(remaining);
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Seed the owner account from ADMIN_* env vars if no users exist yet.
+ *
+ * The account has no password — it becomes usable the first time the owner
+ * signs in through the SSO with a matching `preferred_username`, at which
+ * point its SSO link is filled in automatically (see findOrCreateFromSso).
+ * Runs lazily on first request.
+ */
+export async function initializeAdminUser(): Promise<void> {
+ const users = await getUsers();
+ if (users.length > 0) return;
+
+ const username = adminUsername();
+ const displayName = adminDisplayName();
+
+ try {
+ const newUser: User = {
+ id: crypto.randomUUID(),
+ username,
+ pocket_id: null,
+ display_name: displayName,
+ email: adminEmail() ?? null,
+ created_at: new Date().toISOString(),
+ is_admin: true,
+ is_owner: true,
+ is_pet: false,
+ avatar_url: null,
+ };
+ await saveUsers([newUser]);
+ console.info(`Seeded owner user: ${username}`);
+ } catch (err) {
+ console.error(`Error creating owner user: ${String(err)}`);
+ }
+}
diff --git a/src/lib/server/plural/types.ts b/src/lib/server/plural/types.ts
new file mode 100644
index 0000000..95947b7
--- /dev/null
+++ b/src/lib/server/plural/types.ts
@@ -0,0 +1,40 @@
+/* src/lib/server/plural/types.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.
+ */
+
+// 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 {
+ DB: D1Database;
+ MEDIA: R2Bucket;
+ HUB: Fetcher & HubRpc;
+
+ // Secrets
+ JWT_SECRET?: string;
+ SSO_CLIENT_ID?: string;
+ SSO_CLIENT_SECRET?: string;
+ DOUGH_BOT_TOKEN?: string;
+
+ // Vars
+ SSO_ISSUER?: string;
+ SSO_REDIRECT_URI?: string;
+ SSO_SCOPES?: string;
+ SSO_POST_LOGIN_URL?: string;
+ SSO_POST_LOGOUT_REDIRECT_URI?: string;
+ ADMIN_USERNAME?: string;
+ ADMIN_DISPLAY_NAME?: string;
+ ADMIN_EMAIL?: string;
+ FRONTEND_URL?: string;
+ CORS_ORIGINS?: string;
+}
+
+// Member, system and switch objects travel as loose JSON, as they did from PluralKit
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type JsonObject = Record<string, any>;
diff --git a/src/lib/server/plural/ws.ts b/src/lib/server/plural/ws.ts
new file mode 100644
index 0000000..5cf0841
--- /dev/null
+++ b/src/lib/server/plural/ws.ts
@@ -0,0 +1,29 @@
+/* src/lib/server/plural/ws.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.
+ */
+
+// Live events go out on the api Worker's /v2/ws hub, which every site already listens to
+import { rt } from "./runtime";
+
+export function broadcastFrontingUpdate(frontersData: unknown): Promise<void> {
+ return rt().broadcast({
+ type: "fronters_update",
+ data: frontersData,
+ });
+}
+
+export function broadcastMentalStateUpdate(stateData: unknown): Promise<void> {
+ return rt().broadcast({
+ type: "mental_state_update",
+ data: stateData,
+ });
+}
+
+export function broadcastFrontendUpdate(updateType: string, data: unknown): Promise<void> {
+ return rt().broadcast({
+ type: updateType,
+ data,
+ });
+}
diff --git a/src/routes/+page.ts b/src/routes/+page.ts
index f46d234..127c3a6 100644
--- a/src/routes/+page.ts
+++ b/src/routes/+page.ts
@@ -8,9 +8,9 @@ import type { PageLoad } from "./$types";
import { publicClient } from "#lib/api.ts";
// Rendered on the server for search engines and link previews, then kept live by the socket
-export const load: PageLoad = async ({ fetch, depends }) => {
+export const load: PageLoad = async ({ fetch, depends, url }) => {
depends("api:public");
- const api = publicClient(fetch);
+ const api = publicClient(fetch, url.origin);
const [members, fronters, system] = await Promise.all([
api.getMembers().catch(() => []),
diff --git a/src/routes/[member_id]/+page.ts b/src/routes/[member_id]/+page.ts
index 1161a33..2659c44 100644
--- a/src/routes/[member_id]/+page.ts
+++ b/src/routes/[member_id]/+page.ts
@@ -10,9 +10,9 @@ import type { PageLoad } from "./$types";
import { publicClient } from "#lib/api.ts";
// Server-rendered so Discord embeds and live data stay current with no rebuild
-export const load: PageLoad = async ({ fetch, params, depends }) => {
+export const load: PageLoad = async ({ fetch, params, depends, url }) => {
depends("api:public");
- const api = publicClient(fetch);
+ const api = publicClient(fetch, url.origin);
const id = params.member_id;
const [member, status, members, relationships] = await Promise.all([
diff --git a/src/routes/admin/dash/+page.svelte b/src/routes/admin/dash/+page.svelte
index b1bc450..f6901dd 100644
--- a/src/routes/admin/dash/+page.svelte
+++ b/src/routes/admin/dash/+page.svelte
@@ -12,6 +12,12 @@
import Message from "#lib/components/Message.svelte";
const PAGES = [
+ {
+ href: "/admin/members",
+ label: "Member manager",
+ icon: "profile-2user",
+ desc: "Create and edit members, import data",
+ },
{
href: "/admin/switch",
label: "Switch manager",
@@ -115,10 +121,10 @@
<p>{page.desc}</p>
</a>
{/each}
- <a class="tile" href="https://doughmination.uk/docs" target="_blank" rel="noopener noreferrer">
+ <a class="tile" href="/api/openapi.json" target="_blank" rel="noopener noreferrer">
<span class="tile-icon"><iconsax-icon name="driver" type="bulk" size="22"></iconsax-icon></span>
<h3>API endpoints</h3>
- <p>View API reference</p>
+ <p>OpenAPI spec for this site</p>
</a>
</div>
</div>
diff --git a/src/routes/admin/members/+page.svelte b/src/routes/admin/members/+page.svelte
new file mode 100644
index 0000000..6f42f1b
--- /dev/null
+++ b/src/routes/admin/members/+page.svelte
@@ -0,0 +1,340 @@
+<!-- src/routes/admin/members/+page.svelte
+ 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.
+-->
+
+<script lang="ts">
+ import { onMount } from "svelte";
+ import type { PluralMember, PluralProxyTag } from "doughmination-api/server";
+ import { avatarFallback, errorText, fallbackAvatar, memberName, sortMembers, type Message as MessageType } from "#lib";
+ import { authFetch, client } from "#lib/api.ts";
+ import { auth } from "#lib/auth.svelte.ts";
+ import Protected from "#lib/components/Protected.svelte";
+ import PageHead from "#lib/components/PageHead.svelte";
+ import Message from "#lib/components/Message.svelte";
+
+ // Text fields, in form order. Empty input is saved as null
+ const FIELDS = [
+ {
+ key: "name",
+ label: "Name",
+ placeholder: "Used in links and switching",
+ },
+ {
+ key: "display_name",
+ label: "Display name",
+ placeholder: "Shown on the site",
+ },
+ {
+ key: "pronouns",
+ label: "Pronouns",
+ placeholder: "fae/faer",
+ },
+ {
+ key: "color",
+ label: "Colour",
+ placeholder: "ff99cc (no #)",
+ },
+ {
+ key: "birthday",
+ label: "Birthday",
+ placeholder: "YYYY-MM-DD, year 0004 hides it",
+ },
+ {
+ key: "avatar_url",
+ label: "Avatar URL",
+ placeholder: "https://…",
+ },
+ {
+ key: "banner",
+ label: "Banner URL",
+ placeholder: "https://…",
+ },
+ ] as const;
+
+ type FieldKey = (typeof FIELDS)[number]["key"];
+
+ let members = $state<PluralMember[]>([]);
+ let chosenId = $state<string | null>(null);
+ let form = $state<Record<FieldKey | "description" | "proxy_tags", string>>(emptyForm());
+ let loading = $state(true);
+ let saving = $state(false);
+ let message = $state<MessageType>(null);
+
+ let importFile = $state<FileList | null>(null);
+ let replaceExisting = $state(false);
+
+ const chosen = $derived(members.find((member) => member.id === chosenId) ?? null);
+
+ function emptyForm() {
+ return {
+ name: "",
+ display_name: "",
+ pronouns: "",
+ color: "",
+ birthday: "",
+ avatar_url: "",
+ banner: "",
+ description: "",
+ proxy_tags: "",
+ };
+ }
+
+ // One tag per line, written like PluralKit: "c:text" or "[text]"
+ function tagsToText(tags: PluralProxyTag[] | undefined): string {
+ return (tags ?? []).map((tag) => `${tag.prefix ?? ""}text${tag.suffix ?? ""}`).join("\n");
+ }
+
+ function textToTags(text: string): PluralProxyTag[] {
+ return text
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line.includes("text"))
+ .map((line) => {
+ const at = line.indexOf("text");
+ return {
+ prefix: line.slice(0, at) || null,
+ suffix: line.slice(at + 4) || null,
+ };
+ });
+ }
+
+ function pick(member: PluralMember | null) {
+ chosenId = member?.id ?? null;
+ message = null;
+ if (!member) {
+ form = emptyForm();
+ return;
+ }
+ form = {
+ name: member.original_name ?? member.name ?? "",
+ display_name: member.is_special ? "" : (member.display_name ?? ""),
+ pronouns: member.pronouns ?? "",
+ color: member.color ?? "",
+ birthday: member.birthday ?? "",
+ avatar_url: member.avatar_url ?? "",
+ banner: member.banner ?? "",
+ description: member.description ?? "",
+ proxy_tags: tagsToText(member.proxy_tags),
+ };
+ }
+
+ function body() {
+ const result: Record<string, unknown> = {
+ description: form.description.trim() || null,
+ proxy_tags: textToTags(form.proxy_tags),
+ };
+ for (const field of FIELDS) result[field.key] = form[field.key].trim() || null;
+ return result;
+ }
+
+ async function reload() {
+ members = sortMembers(await client.getMembers());
+ }
+
+ onMount(() => {
+ void reload()
+ .catch((err) => {
+ message = {
+ type: "error",
+ content: errorText(err, "Failed to load members"),
+ };
+ })
+ .finally(() => (loading = false));
+ });
+
+ async function run(action: () => Promise<string>, fallback: string) {
+ saving = true;
+ message = null;
+ try {
+ message = {
+ type: "success",
+ content: await action(),
+ };
+ } catch (err) {
+ message = {
+ type: "error",
+ content: errorText(err, fallback),
+ };
+ } finally {
+ saving = false;
+ }
+ }
+
+ function save(event: SubmitEvent) {
+ event.preventDefault();
+ if (!form.name.trim()) return;
+
+ void run(async () => {
+ const path = chosenId ? `/plural/members/${encodeURIComponent(chosenId)}` : "/plural/members";
+ const saved = await authFetch<PluralMember>(path, {
+ method: chosenId ? "PATCH" : "POST",
+ body: JSON.stringify(body()),
+ }, "Failed to save member");
+ await reload();
+ pick(members.find((member) => member.id === saved.id) ?? null);
+ return chosenId ? "Member saved!" : "Member created!";
+ }, "Failed to save member");
+ }
+
+ function remove() {
+ if (!chosen || !confirm(`Delete ${memberName(chosen)}? Their past switches stay in the history.`)) return;
+
+ void run(async () => {
+ await authFetch(`/plural/members/${encodeURIComponent(chosen.id)}`, { method: "DELETE" }, "Failed to delete member");
+ pick(null);
+ await reload();
+ return "Member deleted";
+ }, "Failed to delete member");
+ }
+
+ function importExport(event: SubmitEvent) {
+ event.preventDefault();
+ const file = importFile?.[0];
+ if (!file) return;
+
+ void run(async () => {
+ const query = `replace=${replaceExisting}`;
+ const report = await authFetch<{
+ members: number;
+ switches: number;
+ media_copied: number;
+ media_failed: string[];
+ }>(`/plural/admin/import/pluralkit?${query}`, {
+ method: "POST",
+ body: await file.text(),
+ }, "Import failed");
+ await reload();
+ const failed = report.media_failed.length ? `, ${report.media_failed.length} image(s) kept their old URL` : "";
+ 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>
+ <title>Member manager · Doughmination System</title>
+</svelte:head>
+
+<Protected admin>
+ <div class="page">
+ <PageHead
+ eyebrow="Admin"
+ title="Member manager"
+ subtitle="Create, edit and remove members"
+ back={{
+ href: "/admin/dash",
+ label: "Back to dashboard",
+ }}
+ />
+
+ <Message {message} />
+
+ {#if loading}
+ <p class="muted">Loading…</p>
+ {:else}
+ <div class="two-col">
+ <form class="panel stack" onsubmit={save}>
+ <h2>{chosen ? `Editing ${memberName(chosen)}` : "New member"}</h2>
+
+ {#each FIELDS as field (field.key)}
+ <label class="field">
+ <span>{field.label}</span>
+ <input type="text" bind:value={form[field.key]} placeholder={field.placeholder} required={field.key === "name"} />
+ </label>
+ {/each}
+
+ <label class="field">
+ <span>Description</span>
+ <textarea bind:value={form.description} maxlength="1000" rows="4"></textarea>
+ </label>
+
+ <label class="field">
+ <span>Proxy tags</span>
+ <textarea bind:value={form.proxy_tags} rows="2" placeholder={"c:text\n[text]"}></textarea>
+ <small class="muted">One per line. "text" marks where the message goes</small>
+ </label>
+
+ <div class="buttons">
+ <button type="submit" class="primary" disabled={saving || !form.name.trim()}>
+ {saving ? "Saving..." : chosen ? "Save member" : "Create member"}
+ </button>
+ {#if chosen}
+ <button type="button" disabled={saving} onclick={() => pick(null)}>New member</button>
+ {#if auth.isOwner}
+ <button type="button" class="danger" disabled={saving} onclick={remove}>Delete</button>
+ {/if}
+ {/if}
+ </div>
+ </form>
+
+ <section class="panel">
+ <h2>Members</h2>
+ <p class="muted small">{members.length} member(s)</p>
+ <div class="pick-list">
+ {#each members as member (member.id)}
+ <button type="button" class="pick" class:selected={member.id === chosenId} onclick={() => pick(member)}>
+ <img class="member-avatar avatar-sm" src={member.avatar_url || fallbackAvatar} alt="" onerror={avatarFallback} />
+ <span class="grow">
+ <p>{memberName(member)}</p>
+ <p class="muted small">{member.id}{member.pronouns ? ` · ${member.pronouns}` : ""}</p>
+ </span>
+ </button>
+ {:else}
+ <p class="muted">No members yet. Import a PluralKit export below.</p>
+ {/each}
+ </div>
+ </section>
+ </div>
+
+ {#if auth.isOwner}
+ <section class="panel stack import">
+ <h2>Import</h2>
+
+ <form class="stack" onsubmit={importExport}>
+ <label class="field">
+ <span>PluralKit export file (from pk;export)</span>
+ <input type="file" accept="application/json,.json" bind:files={importFile} />
+ </label>
+ <label class="check">
+ <input type="checkbox" bind:checked={replaceExisting} />
+ Replace the system already here, with its members and switch history
+ </label>
+ <div class="buttons">
+ <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}
+ </div>
+</Protected>
+
+<style>
+ h2,
+ p {
+ margin: 0;
+ }
+
+ h2 {
+ font-size: 1.05rem;
+ }
+
+ .import {
+ margin-top: 1.25rem;
+ }
+</style>
diff --git a/src/routes/api/[...path]/+server.ts b/src/routes/api/[...path]/+server.ts
new file mode 100644
index 0000000..dab1c39
--- /dev/null
+++ b/src/routes/api/[...path]/+server.ts
@@ -0,0 +1,18 @@
+/* src/routes/api/[...path]/+server.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 { env } from "cloudflare:workers";
+
+import type { RequestHandler } from "./$types";
+import { app } from "#lib/server/plural/app.ts";
+import { setRuntime } from "#lib/server/plural/runtime.ts";
+import type { PluralEnv } from "#lib/server/plural/types.ts";
+
+// Every method under /api goes to the Hono app
+export const fallback: RequestHandler = async ({ request }) => {
+ setRuntime(env as unknown as PluralEnv);
+ return app.fetch(request);
+};
diff --git a/src/routes/relationships/+page.ts b/src/routes/relationships/+page.ts
index 37d0874..01699ff 100644
--- a/src/routes/relationships/+page.ts
+++ b/src/routes/relationships/+page.ts
@@ -7,9 +7,9 @@
import type { PageLoad } from "./$types";
import { publicClient } from "#lib/api.ts";
-export const load: PageLoad = async ({ fetch, depends }) => {
+export const load: PageLoad = async ({ fetch, depends, url }) => {
depends("api:public");
- const api = publicClient(fetch);
+ const api = publicClient(fetch, url.origin);
const [members, relationships] = await Promise.all([
api.getMembers().catch(() => []),
diff --git a/vite.config.ts b/vite.config.ts
index 8e0c1a8..e91a684 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -16,6 +16,11 @@ export default defineConfig({
runes: ({ filename }) => (filename.split(/[/\\]/).includes("node_modules") ? undefined : true),
},
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
+ csrf: {
+ trustedOrigins: ["*"],
+ },
}),
],
// iconsax fetches its icon data relative to its own file, which pre-bundling breaks
diff --git a/wrangler.jsonc b/wrangler.jsonc
index a10d602..1c6122c 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -1,16 +1,57 @@
+// wrangler.jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "doughmination-system",
"main": ".svelte-kit/cloudflare/_worker.js",
+ "account_id": "f87ee4b9600f437b8da1104d077418c3",
"compatibility_date": "2026-10-01",
"compatibility_flags": [
"nodejs_compat",
- // Makes fetch() in server code go over the public internet — needed so
- // member pages can call the Doughmination/PluralKit API while rendering.
+ // fetch() in server code goes over the public internet (SSO, media import)
"global_fetch_strictly_public"
],
"assets": {
"binding": "ASSETS",
"directory": ".svelte-kit/cloudflare"
+ },
+ "observability": {
+ "enabled": true
+ },
+ "d1_databases": [
+ {
+ "binding": "DB",
+ "database_name": "doughmination-system",
+ "database_id": "447ff8ba-f1c1-4447-82b2-71dac05fae8b",
+ "migrations_dir": "migrations"
+ }
+ ],
+ "r2_buckets": [
+ {
+ "binding": "MEDIA",
+ "bucket_name": "doughmination-system-media"
+ }
+ ],
+ // The api Worker's realtime hub (/v2/ws). RPC only, never public
+ "services": [
+ {
+ "binding": "HUB",
+ "service": "api",
+ "entrypoint": "Hub"
+ }
+ ],
+ "vars": {
+ "ADMIN_USERNAME": "clove",
+ "ADMIN_DISPLAY_NAME": "Administrator",
+ "ADMIN_EMAIL": "[email protected]",
+ "FRONTEND_URL": "https://doughmination.co.uk",
+ "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_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/"
}
}