Dough Git

commit

aaa

commit
0edcec7d7129b424d283d92f7e7d559191fab438
author
Clove Twilight <[email protected]>
date
2026-09-16 12:52

diff --git a/.dev.vars.example b/.dev.vars.example
index f51f51d..0bc54fb 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -27,7 +27,7 @@ DISCORD_USER_TOKEN3=
 # PluralKit system token (Authorization header for api.pluralkit.me).
 SYSTEM_TOKEN=
 
-# HMAC secret used to sign the JWT the API issues after a PocketID login.
+# HMAC secret used to sign the JWT the API issues after an SSO login.
 # REQUIRED in production — set to a long random string, e.g.
 # `openssl rand -base64 48`.
 JWT_SECRET=
@@ -35,22 +35,27 @@ JWT_SECRET=
 # Cloudflare Turnstile secret (public guestbook captcha).
 TURNSTILE_SECRET=
 
-# ---- PocketID (OpenID Connect) — the ONLY login method ---------------------
-# OIDC client credentials issued by your PocketID instance. The non-secret
-# bits (POCKETID_ISSUER / REDIRECT_URI / SCOPES / POST_LOGIN_URL) live in
-# wrangler.jsonc vars. In production set these two as secrets:
-#   wrangler secret put POCKETID_CLIENT_ID
-#   wrangler secret put POCKETID_CLIENT_SECRET
-POCKETID_CLIENT_ID=
-POCKETID_CLIENT_SECRET=
+# ---- Doughmination SSO (OpenID Connect) — the ONLY login method -------------
+# In the SSO admin (/admin/clients) add a *confidential* application with:
+#   Redirect URI:             https://doughmination.uk/v2/plural/auth/sso/callback
+#   Post-logout redirect URI: https://doughmination.co.uk/
+# The non-secret bits (SSO_ISSUER / REDIRECT_URI / SCOPES / POST_LOGIN_URL /
+# POST_LOGOUT_REDIRECT_URI) live in wrangler.jsonc vars. In production:
+#   wrangler secret put SSO_CLIENT_ID
+#   wrangler secret put SSO_CLIENT_SECRET
+SSO_CLIENT_ID=
+SSO_CLIENT_SECRET=
 # OPTIONAL local overrides (otherwise inherited from wrangler.jsonc vars):
-# POCKETID_ISSUER=https://doughmination.xyz
-# POCKETID_REDIRECT_URI=http://localhost:8787/v2/plural/auth/pocketid/callback
-# POCKETID_POST_LOGIN_URL=http://localhost:3000/user/login/callback
+# SSO_ISSUER=http://localhost:8787
+# SSO_REDIRECT_URI=http://localhost:8789/v2/plural/auth/sso/callback
+# SSO_POST_LOGIN_URL=http://localhost:3000/user/login/callback
+# SSO_POST_LOGOUT_REDIRECT_URI=http://localhost:3000/
 
 # The initial owner account (ADMIN_USERNAME / ADMIN_DISPLAY_NAME in
 # wrangler.jsonc) is seeded on first request with no password. It becomes
-# usable the first time that username signs in through PocketID.
+# usable the first time that username signs in through the SSO. Accounts that
+# were linked to PocketID are taken over the same way, once: the first SSO
+# sign-in with a matching username re-links them to the SSO.
 
 # MANUAL bot token for /v2/plural/bot/* — nothing is generated any more.
 # Give this exact value to the Discord bot as DOUGH_API_TOKEN.
diff --git a/src/system/config.ts b/src/system/config.ts
index 50a1bbe..43b9a11 100644
--- a/src/system/config.ts
+++ b/src/system/config.ts
@@ -54,57 +54,68 @@ export function adminDisplayName(): string {
 }
 
 // ---------------------------------------------------------------------------
-// PocketID (OpenID Connect) — the ONLY login method.
+// Doughmination SSO (OpenID Connect) — the ONLY login method.
 //
 // The API is a confidential OIDC client: it runs the Authorization Code +
-// PKCE flow against a PocketID instance, then mints its own JWT (see
-// security.ts) so every existing `requireAuth` route keeps working unchanged.
+// PKCE flow against the SSO (auth-server), then mints its own JWT (see
+// security.ts) so every existing `requireAuth` route keeps working. Each JWT
+// is tied to an SSO session that is re-checked every few minutes, so accounts
+// disabled on the SSO stop working here too (see services/sso_sessions.ts).
 // ---------------------------------------------------------------------------
 
-/** PocketID issuer origin, e.g. https://doughmination.xyz. No trailing slash.
+/** SSO issuer origin, e.g. https://auth.doughmination.gay. No trailing slash.
  *  `${issuer}/.well-known/openid-configuration` must resolve. */
-export function pocketIdIssuer(): string {
-  return (rt().env.POCKETID_ISSUER ?? "").replace(/\/+$/, "");
+export function ssoIssuer(): string {
+  return (rt().env.SSO_ISSUER ?? "").replace(/\/+$/, "");
 }
 
-/** OIDC client id issued by PocketID for this application. */
-export function pocketIdClientId(): string | undefined {
-  return rt().env.POCKETID_CLIENT_ID;
+/** OIDC client id of this API's application on the SSO. */
+export function ssoClientId(): string | undefined {
+  return rt().env.SSO_CLIENT_ID;
 }
 
-/** OIDC client secret. Set via `wrangler secret put POCKETID_CLIENT_SECRET`. */
-export function pocketIdClientSecret(): string | undefined {
-  return rt().env.POCKETID_CLIENT_SECRET;
+/** OIDC client secret. Set via `wrangler secret put SSO_CLIENT_SECRET`. */
+export function ssoClientSecret(): string | undefined {
+  return rt().env.SSO_CLIENT_SECRET;
 }
 
-/** The redirect URI registered with PocketID. Must point back at the API's
- *  callback route. Defaults to `${baseUrl}/v2/plural/auth/pocketid/callback`. */
-export function pocketIdRedirectUri(): string {
-  const configured = rt().env.POCKETID_REDIRECT_URI;
+/** The redirect URI registered on the SSO. Must point back at the API's
+ *  callback route. Defaults to `${baseUrl}/v2/plural/auth/sso/callback`. */
+export function ssoRedirectUri(): string {
+  const configured = rt().env.SSO_REDIRECT_URI;
   if (configured) return configured;
-  return `${baseUrl()}/v2/plural/auth/pocketid/callback`;
+  return `${baseUrl()}/v2/plural/auth/sso/callback`;
 }
 
-/** Space-separated OIDC scopes. `openid` is mandatory; `profile` gives us
- *  preferred_username + name, `email` gives the address. */
-export function pocketIdScopes(): string {
-  return rt().env.POCKETID_SCOPES ?? "openid profile email";
+/** Space-separated OIDC scopes. `openid` is mandatory; `profile` gives
+ *  preferred_username + name, `email` the address, and `offline_access` the
+ *  refresh token sessions are re-checked with. */
+export function ssoScopes(): string {
+  return rt().env.SSO_SCOPES ?? "openid profile email offline_access";
 }
 
 /** Where the callback sends the browser once a JWT has been minted. The token
  *  is appended in the URL fragment (`#token=…`) so it never hits a server log.
- *  Defaults to the frontend's PocketID landing page. */
-export function pocketIdPostLoginUrl(): string {
-  const configured = rt().env.POCKETID_POST_LOGIN_URL;
+ *  Defaults to the frontend's login landing page. */
+export function ssoPostLoginUrl(): string {
+  const configured = rt().env.SSO_POST_LOGIN_URL;
   if (configured) return configured.replace(/\/+$/, "");
   return `${frontendUrl()}/user/login/callback`;
 }
 
 /** Where the browser is sent when login fails or is cancelled. */
-export function pocketIdLoginErrorUrl(): string {
+export function ssoLoginErrorUrl(): string {
   return `${frontendUrl()}/user/login`;
 }
 
+/** Where the SSO returns the browser after signing out. Must be registered as
+ *  a post-logout redirect URI on the SSO application. */
+export function ssoPostLogoutRedirectUri(): string {
+  const configured = rt().env.SSO_POST_LOGOUT_REDIRECT_URI;
+  if (configured) return configured;
+  return `${frontendUrl()}/`;
+}
+
 /** How long an in-flight authorization request (state + PKCE verifier) stays
  *  valid between /login and /callback. */
 export const OIDC_STATE_TTL_MINUTES = 10;
diff --git a/src/system/middleware/auth.ts b/src/system/middleware/auth.ts
index d0432fd..53522fa 100644
--- a/src/system/middleware/auth.ts
+++ b/src/system/middleware/auth.ts
@@ -15,6 +15,7 @@ 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, verifyBatteryKey } from "../services/keys";
 import type { User } from "../models";
 
@@ -38,6 +39,14 @@ async function resolveCurrentUser(c: Context<Env>): Promise<User> {
     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" });
diff --git a/src/system/models.ts b/src/system/models.ts
index b8e7b4d..40a1ef8 100644
--- a/src/system/models.ts
+++ b/src/system/models.ts
@@ -28,18 +28,25 @@ export const UserSchema = z.object({
   id: z.string(),
   username: z.string(),
   /**
-   * The PocketID subject identifier (OIDC `sub`) this account is linked to.
-   * Set on first PocketID login and used as the primary match key thereafter.
+   * 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 PocketID `email` claim when available. */
+  /** 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(),
@@ -52,8 +59,8 @@ 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 PocketID
-   *  login; normally the link is established automatically on login. */
+  /** 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(),
@@ -80,7 +87,7 @@ export const UserUpdateSchema = z.object({
   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 PocketID,
+   * 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(),
@@ -91,7 +98,7 @@ 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, ...rest } = user;
+  const { password_hash: _pw, pocket_id: _sub, sso_issuer: _iss, ...rest } = user;
   return rest;
 }
 
diff --git a/src/system/routes/auth.ts b/src/system/routes/auth.ts
index 67474bf..34bbe88 100644
--- a/src/system/routes/auth.ts
+++ b/src/system/routes/auth.ts
@@ -5,27 +5,38 @@
  */
 
 /**
- * Authentication — PocketID (OpenID Connect) only.
+ * Authentication — Doughmination SSO (OpenID Connect) only.
  *
- *   GET /auth/pocketid/login     — redirect to PocketID to start the flow.
- *   GET /auth/pocketid/callback  — PocketID redirects back here; we exchange
- *                                  the code, link/create the account, mint a
- *                                  JWT and hand the browser back to the frontend
- *                                  with the token in the URL fragment.
+ *   GET  /auth/sso/login     — redirect to the SSO to start the flow.
+ *   GET  /auth/sso/callback  — the SSO redirects back here; we exchange the
+ *                              code, link/create the account, open an SSO-backed
+ *                              session, mint a JWT and hand the browser back to
+ *                              the frontend with the token in the URL fragment.
+ *   POST /auth/logout        — end the session here and at the SSO.
+ *
+ * /auth/pocketid/login and /auth/pocketid/callback remain as aliases: the
+ * published @doughmination/react-api client still builds the old login URL.
  *
  * Everything downstream (the /user_info + /auth/is_* checks and every
- * requireAuth route) keeps using the same HS256 bearer token as before.
+ * requireAuth route) keeps using the same HS256 bearer token as before; it
+ * now also carries the session id that requireAuth checks.
  */
 
-import { Hono } from "hono";
+import { Hono, type Context } from "hono";
 
 import type { Env } from "../hono";
 import { UserResponseSchema } from "../models";
 import type { User } from "../models";
-import { findOrCreateFromPocketId } from "../services/users";
-import { beginLogin, completeLogin } from "../services/oidc";
-import { pocketIdPostLoginUrl, pocketIdLoginErrorUrl } from "../config";
-import { createAccessToken } from "../security";
+import { findOrCreateFromSso } from "../services/users";
+import {
+  beginLogin,
+  completeLogin,
+  endSessionUrl,
+  revokeRefreshToken,
+} from "../services/oidc";
+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";
 
 export const authRoutes = new Hono<Env>();
@@ -45,71 +56,68 @@ function toUserResponseJson(user: User) {
 }
 
 /** A same-origin-ish app path, defended against open-redirect abuse: only a
- *  path beginning with a single "/" is accepted, never "//host" or a full URL. */
+ *  path beginning with a single "/" is accepted, never "//host", "/\host" or a
+ *  full URL. */
 function safeReturnPath(raw: string | undefined): string {
   if (!raw) return "/";
-  if (!raw.startsWith("/") || raw.startsWith("//")) return "/";
+  if (!raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return "/";
   return raw;
 }
 
-/** Start the PocketID login: 302 to the provider's authorization endpoint. */
-authRoutes.get("/auth/pocketid/login", async (c) => {
+function loginError(c: Context<Env>, message: string) {
+  const url = new URL(ssoLoginErrorUrl());
+  url.searchParams.set("error", message);
+  return c.redirect(url.toString(), 302);
+}
+
+/** Start the SSO login: 302 to the provider's authorization endpoint. */
+async function login(c: Context<Env>) {
   const from = safeReturnPath(c.req.query("from"));
   const authUrl = await beginLogin(from);
   return c.redirect(authUrl, 302);
-});
+}
 
-/** PocketID redirects the browser back here after the user authenticates. */
-authRoutes.get("/auth/pocketid/callback", async (c) => {
+/** The SSO redirects the browser back here after the user authenticates. */
+async function callback(c: Context<Env>) {
   const errorParam = c.req.query("error");
-  if (errorParam) {
-    const url = new URL(pocketIdLoginErrorUrl());
-    url.searchParams.set("error", errorParam);
-    return c.redirect(url.toString(), 302);
+  if (errorParam === "access_denied") {
+    return loginError(c, "Your SSO account isn't allowed to use this site.");
   }
+  if (errorParam) return loginError(c, errorParam);
 
   const code = c.req.query("code");
   const state = c.req.query("state");
-  if (!code || !state) {
-    const url = new URL(pocketIdLoginErrorUrl());
-    url.searchParams.set("error", "missing_code");
-    return c.redirect(url.toString(), 302);
-  }
+  if (!code || !state) return loginError(c, "missing_code");
 
   let result;
   try {
-    result = await completeLogin(code, state);
+    result = await completeLogin(code, state, c.req.query("iss"));
   } catch (err) {
-    const url = new URL(pocketIdLoginErrorUrl());
-    url.searchParams.set(
-      "error",
-      err instanceof Error ? err.message : "Login failed. Please try again.",
-    );
-    return c.redirect(url.toString(), 302);
+    return loginError(c, err instanceof Error ? err.message : "Login failed. Please try again.");
   }
 
-  const { identity, from } = result;
+  const { identity, tokens, from } = result;
 
   let user: User;
   try {
-    user = await findOrCreateFromPocketId({
+    user = await findOrCreateFromSso({
       sub: identity.sub,
+      issuer: identity.issuer,
       username: identity.preferredUsername,
       email: identity.email,
       displayName: identity.displayName,
     });
   } catch (err) {
-    const url = new URL(pocketIdLoginErrorUrl());
-    url.searchParams.set(
-      "error",
-      err instanceof Error ? err.message : "Could not sign you in.",
-    );
-    return c.redirect(url.toString(), 302);
+    return loginError(c, err instanceof Error ? err.message : "Could not sign you in.");
   }
 
+  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,
@@ -119,9 +127,49 @@ authRoutes.get("/auth/pocketid/callback", async (c) => {
 
   // Token goes in the fragment so it never lands in a server access log or the
   // Referer header; the frontend callback page reads it from location.hash.
-  const dest = new URL(pocketIdPostLoginUrl());
+  const dest = new URL(ssoPostLoginUrl());
   dest.hash = `token=${encodeURIComponent(token)}&from=${encodeURIComponent(from)}`;
   return c.redirect(dest.toString(), 302);
+}
+
+authRoutes.get("/auth/sso/login", login);
+authRoutes.get("/auth/sso/callback", callback);
+authRoutes.get("/auth/pocketid/login", login);
+authRoutes.get("/auth/pocketid/callback", callback);
+
+/**
+ * End the caller's session. Accepts an expired or already-revoked token so a
+ * stale tab can still sign out cleanly; returns the SSO URL the browser should
+ * visit to end the SSO session as well.
+ */
+authRoutes.post("/auth/logout", 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 });
 });
 
 authRoutes.get("/user_info", requireAuth, (c) => c.json(toUserResponseJson(c.get("user") as User)));
diff --git a/src/system/routes/users.ts b/src/system/routes/users.ts
index 7069b67..2da5fb2 100644
--- a/src/system/routes/users.ts
+++ b/src/system/routes/users.ts
@@ -36,7 +36,7 @@ usersRoutes.post("/users", requireAuth, requireAdmin, async (c) => {
 
   try {
     // Admin-provisioned account. It becomes usable once the person signs in
-    // through PocketID with a matching username (the link is filled in then),
+    // through the SSO with a matching username (the link is filled in then),
     // or immediately if `pocket_id` was supplied.
     const newUser = await createUser(parsed.data, c.get("user") ?? null);
     return c.json(toUserResponse(newUser));
diff --git a/src/system/security.ts b/src/system/security.ts
index 4c3fa94..1ccb2c2 100644
--- a/src/system/security.ts
+++ b/src/system/security.ts
@@ -9,13 +9,14 @@
  * 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 PocketID (OIDC) login, so
- *    every existing bearer-auth route keeps working unchanged.
+ *    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.
  *  - Turnstile: verified with `fetch` (still used by the public guestbook).
  *
- * Local password hashing has been removed — login is PocketID-only.
+ * Local password hashing has been removed — login is SSO-only.
  */
 
 import { ACCESS_TOKEN_EXPIRE_MINUTES, jwtSecret, turnstileSecret } from "./config";
@@ -108,7 +109,11 @@ export interface JwtPayload {
   [k: string]: unknown;
 }
 
-export async function decodeAccessToken(token: string): Promise<JwtPayload> {
+/** `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");
@@ -123,7 +128,7 @@ export async function decodeAccessToken(token: string): Promise<JwtPayload> {
     if (!valid) throw new Error("bad signature");
 
     const payload = JSON.parse(dec.decode(b64urlToBytes(p))) as JwtPayload & { exp?: number };
-    if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1000)) {
+    if (!opts.allowExpired && typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1000)) {
       throw new Error("expired");
     }
     return payload;
diff --git a/src/system/services/oidc.ts b/src/system/services/oidc.ts
index 603d90c..482b3ae 100644
--- a/src/system/services/oidc.ts
+++ b/src/system/services/oidc.ts
@@ -5,28 +5,32 @@
  */
 
 /**
- * PocketID / OpenID Connect client.
+ * Doughmination SSO / OpenID Connect client.
  *
  * The API is a confidential OIDC client running Authorization Code + PKCE:
  *
- *   1. /auth/pocketid/login  — mint a `state` + PKCE verifier, stash them in
- *      the DO store, and 302 the browser to PocketID's authorization endpoint.
- *   2. PocketID authenticates the user and redirects back with `?code&state`.
- *   3. /auth/pocketid/callback — validate `state`, exchange the code for tokens
- *      over a direct TLS call to the token endpoint, then read the identity
- *      claims from the userinfo endpoint.
+ *   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 RS256 signature.
+ * 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 {
-  pocketIdIssuer,
-  pocketIdClientId,
-  pocketIdClientSecret,
-  pocketIdRedirectUri,
-  pocketIdScopes,
+  ssoIssuer,
+  ssoClientId,
+  ssoClientSecret,
+  ssoRedirectUri,
+  ssoScopes,
+  ssoPostLogoutRedirectUri,
   OIDC_STATE_TTL_MINUTES,
 } from "../config";
 import { randomUrlToken, sha256Base64Url } from "../security";
@@ -35,38 +39,46 @@ 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 (!pocketIdIssuer()) throw new HttpError(500, "PocketID is not configured (POCKETID_ISSUER)");
-  if (!pocketIdClientId()) throw new HttpError(500, "PocketID is not configured (POCKETID_CLIENT_ID)");
-  if (!pocketIdClientSecret()) {
-    throw new HttpError(500, "PocketID is not configured (POCKETID_CLIENT_SECRET)");
-  }
+  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 = pocketIdIssuer();
+  const issuer = ssoIssuer();
   const now = Date.now();
   if (
     discoveryCache &&
@@ -81,14 +93,17 @@ export async function discover(): Promise<OidcDiscovery> {
   try {
     res = await fetch(url, { headers: { Accept: "application/json" } });
   } catch (err) {
-    throw new HttpError(502, `Could not reach PocketID: ${String(err)}`);
+    throw new HttpError(502, `Could not reach the SSO: ${String(err)}`);
   }
   if (!res.ok) {
-    throw new HttpError(502, `PocketID discovery failed (${res.status})`);
+    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, "PocketID discovery document is missing required endpoints");
+    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;
@@ -124,9 +139,9 @@ export async function beginLogin(from: string): Promise<string> {
 
   const authUrl = new URL(doc.authorization_endpoint);
   authUrl.searchParams.set("response_type", "code");
-  authUrl.searchParams.set("client_id", pocketIdClientId() as string);
-  authUrl.searchParams.set("redirect_uri", pocketIdRedirectUri());
-  authUrl.searchParams.set("scope", pocketIdScopes());
+  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");
@@ -135,15 +150,52 @@ export async function beginLogin(from: string): Promise<string> {
 
 export interface CallbackResult {
   identity: OidcIdentity;
+  tokens: SsoTokens;
   /** The original app path to return the user to. */
   from: string;
 }
 
+/** 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): Promise<CallbackResult> {
+export async function completeLogin(code: string, state: string, iss: string | undefined): Promise<CallbackResult> {
   assertConfigured();
 
   const key = stateKey(state);
@@ -159,56 +211,49 @@ export async function completeLogin(code: string, state: string): Promise<Callba
   }
 
   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) -----------
-  const body = new URLSearchParams({
-    grant_type: "authorization_code",
-    code,
-    redirect_uri: pocketIdRedirectUri(),
-    client_id: pocketIdClientId() as string,
-    client_secret: pocketIdClientSecret() as string,
-    code_verifier: stored.verifier,
-  });
-
-  let tokenRes: Response;
+  let tokens: Record<string, unknown>;
   try {
-    tokenRes = await fetch(doc.token_endpoint, {
-      method: "POST",
-      headers: {
-        "Content-Type": "application/x-www-form-urlencoded",
-        Accept: "application/json",
-      },
-      body,
+    tokens = await tokenRequest({
+      grant_type: "authorization_code",
+      code,
+      redirect_uri: ssoRedirectUri(),
+      code_verifier: stored.verifier,
     });
   } catch (err) {
-    throw new HttpError(502, `PocketID token exchange failed: ${String(err)}`);
-  }
-  if (!tokenRes.ok) {
-    const detail = await tokenRes.text().catch(() => "");
-    throw new HttpError(401, `PocketID rejected the login (${tokenRes.status}). ${detail}`.trim());
+    if (err instanceof GrantRejectedError) {
+      throw new HttpError(401, "The SSO rejected the login. Please try again.");
+    }
+    throw err;
   }
 
-  const tokens = (await tokenRes.json()) as { access_token?: string };
-  if (!tokens.access_token) {
-    throw new HttpError(502, "PocketID did not return an access token");
+  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 ${tokens.access_token}`, Accept: "application/json" },
+      headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
     });
   } catch (err) {
-    throw new HttpError(502, `PocketID userinfo request failed: ${String(err)}`);
+    throw new HttpError(502, `SSO userinfo request failed: ${String(err)}`);
   }
   if (!infoRes.ok) {
-    throw new HttpError(502, `PocketID userinfo request failed (${infoRes.status})`);
+    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, "PocketID did not return a subject identifier");
+  if (!sub) throw new HttpError(502, "The SSO did not return a subject identifier");
 
   const preferredUsername =
     (typeof claims.preferred_username === "string" && claims.preferred_username) ||
@@ -224,7 +269,53 @@ export async function completeLogin(code: string, state: string): Promise<Callba
     null;
 
   return {
-    identity: { sub, preferredUsername, email, displayName },
+    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 || "/",
   };
 }
+
+/**
+ * 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/system/services/sso_sessions.ts b/src/system/services/sso_sessions.ts
new file mode 100644
index 0000000..82267c9
--- /dev/null
+++ b/src/system/services/sso_sessions.ts
@@ -0,0 +1,162 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 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 DO is a single instance, so an in-memory map is enough to make
+ * concurrent requests on one session share a single refresh; the SSO rotates
+ * refresh tokens and treats replays outside a short grace period as theft.
+ */
+
+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;
+}
+
+const inflight = new Map<string, Promise<SsoSession | null>>();
+
+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;
+  }
+
+  const pending = inflight.get(session.sid);
+  if (pending) return pending;
+
+  const task = (async (): Promise<SsoSession | null> => {
+    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)}`);
+      const updated = { ...session, checkedAt: Date.now() };
+      await rt().store.put(sessionKey(session.sid), updated);
+      return updated;
+    }
+  })().finally(() => inflight.delete(session.sid));
+
+  inflight.set(session.sid, task);
+  return task;
+}
+
+/** 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/system/services/users.ts b/src/system/services/users.ts
index 4f59817..8d27324 100644
--- a/src/system/services/users.ts
+++ b/src/system/services/users.ts
@@ -7,10 +7,10 @@
 /**
  * User management service.
  *
- * Authentication is PocketID (OIDC) only — there are no passwords here. Each
- * account is linked to a PocketID subject (`pocket_id`); on first login we
- * match an existing account by username and backfill the link, or provision a
- * new non-admin account. Roles (admin/owner/pet), avatars and the owner
+ * 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").
  */
 
@@ -76,10 +76,10 @@ export async function getUserById(userId: string): Promise<User | null> {
   return users.find((u) => u.id === userId) ?? null;
 }
 
-export async function getUserBySub(sub: string): Promise<User | 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 && u.pocket_id === sub) ?? null;
+  return users.find((u) => u.pocket_id === sub && u.sso_issuer === issuer) ?? null;
 }
 
 export function normalizeEmail(email: string): string {
@@ -155,30 +155,49 @@ export async function createUser(
 }
 
 /**
- * Resolve a PocketID login to a local account.
+ * Resolve an SSO login to a local account.
  *
- * Match order: by the stable `pocket_id` subject first, then by username
- * (case-insensitive) so a pre-existing/owner account adopts its PocketID link
- * on first login. Unknown users are auto-provisioned as non-admins.
+ * 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 findOrCreateFromPocketId(claims: {
+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;
 
-  const bySub = users.find((u) => u.pocket_id && u.pocket_id === claims.sub);
-  const byName = users.find((u) => u.username.toLowerCase() === claims.username.toLowerCase());
-  const existing = bySub ?? 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) {
+    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.
@@ -198,8 +217,8 @@ export async function findOrCreateFromPocketId(claims: {
     return existing;
   }
 
-  // First-time login for an unknown PocketID user → provision a plain account.
-  return createUser({
+  // 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,
@@ -207,6 +226,15 @@ export async function findOrCreateFromPocketId(claims: {
     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);
+  users[index] = { ...users[index], sso_issuer: issuer };
+  await saveUsers(users);
+  return users[index];
 }
 
 export async function updateUser(
@@ -241,7 +269,7 @@ export async function updateUser(
 
   // ---- Email (contact metadata only) ------------------------------------
   // Editable by the account's own user or by an admin/owner. Identity is
-  // proven by PocketID, so there is no confirmation step.
+  // 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;
@@ -265,6 +293,7 @@ export async function updateUser(
     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,
@@ -306,9 +335,9 @@ export async function deleteUser(userId: string, requestingUser?: User | null):
  * 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 PocketID with a matching `preferred_username`, at which
- * point its `pocket_id` link is filled in automatically (see
- * findOrCreateFromPocketId). Runs lazily on first request.
+ * 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();
diff --git a/src/system/types.ts b/src/system/types.ts
index 9703278..c6fc8de 100644
--- a/src/system/types.ts
+++ b/src/system/types.ts
@@ -28,7 +28,7 @@ export interface SystemEnv {
   CACHE_TTL?: string;
 
   // ---- Auth --------------------------------------------------------------
-  /** HMAC secret for signing the JWT the API issues after a PocketID login.
+  /** HMAC secret for signing the JWT the API issues after an SSO login.
    *  REQUIRED in production. */
   JWT_SECRET?: string;
   /** Cloudflare Turnstile secret (public guestbook captcha). */
@@ -36,21 +36,23 @@ export interface SystemEnv {
   /** Back-compat alias for the original (typo'd) env name. */
   TURNSILE_SECRET?: string;
 
-  // ---- PocketID (OIDC) — the only login method ---------------------------
-  /** Issuer origin, e.g. https://doughmination.xyz (no trailing slash). */
-  POCKETID_ISSUER?: string;
-  /** OIDC client id for this application. */
-  POCKETID_CLIENT_ID?: string;
-  /** OIDC client secret — set with `wrangler secret put POCKETID_CLIENT_SECRET`. */
-  POCKETID_CLIENT_SECRET?: string;
+  // ---- Doughmination SSO (OIDC) — the only login method -----------------
+  /** Issuer origin, e.g. https://auth.doughmination.gay (no trailing slash). */
+  SSO_ISSUER?: string;
+  /** OIDC client id of this API's application on the SSO. */
+  SSO_CLIENT_ID?: string;
+  /** OIDC client secret — set with `wrangler secret put SSO_CLIENT_SECRET`. */
+  SSO_CLIENT_SECRET?: string;
   /** Registered redirect URI. Defaults to
-   *  `${BASE_URL}/v2/plural/auth/pocketid/callback`. */
-  POCKETID_REDIRECT_URI?: string;
-  /** Space-separated scopes. Defaults to "openid profile email". */
-  POCKETID_SCOPES?: string;
+   *  `${BASE_URL}/v2/plural/auth/sso/callback`. */
+  SSO_REDIRECT_URI?: string;
+  /** Space-separated scopes. Defaults to "openid profile email offline_access". */
+  SSO_SCOPES?: string;
   /** Frontend page the callback hands the minted JWT to (in the URL fragment).
    *  Defaults to `${FRONTEND_URL}/user/login/callback`. */
-  POCKETID_POST_LOGIN_URL?: string;
+  SSO_POST_LOGIN_URL?: string;
+  /** Where the SSO sends the browser after logout. Defaults to `${FRONTEND_URL}/`. */
+  SSO_POST_LOGOUT_REDIRECT_URI?: string;
 
   // ---- Initial owner seed (only used when no users exist yet) ------------
   ADMIN_USERNAME?: string;
diff --git a/wrangler.jsonc b/wrangler.jsonc
index 9d47cf0..cfd19d4 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -78,11 +78,13 @@
 		"COUNTER_SITE_IDS": "is.doughmination.gay",
 		"FRONTEND_URL": "https://doughmination.co.uk",
 
-		// ---- PocketID (SSO) -----
-		"POCKETID_ISSUER": "https://sso.doughmination.gay",
-		"POCKETID_REDIRECT_URI": "https://doughmination.uk/v2/plural/auth/pocketid/callback",
-		"POCKETID_SCOPES": "openid profile email",
-		"POCKETID_POST_LOGIN_URL": "https://doughmination.co.uk/user/login/callback",
+		// ---- Doughmination SSO (auth-server) -----
+		// Secrets: wrangler secret put SSO_CLIENT_ID / SSO_CLIENT_SECRET
+		"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/",
 
 	}
 }