commit
Move to Doughmination SSO
diff --git a/.dev.vars.example b/.dev.vars.example
index f704f90..6b21d0f 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -27,34 +27,35 @@ DISCORD_USER_TOKEN3=
# PluralKit system token (Authorization header for api.pluralkit.me).
SYSTEM_TOKEN=
-# HMAC secret used to sign JWTs. REQUIRED in production — set to a long random
-# string, e.g. `openssl rand -base64 48`.
+# HMAC secret used to sign the JWT the API issues after a PocketID login.
+# REQUIRED in production — set to a long random string, e.g.
+# `openssl rand -base64 48`.
JWT_SECRET=
-# Cloudflare Turnstile secret (login/signup captcha).
+# Cloudflare Turnstile secret (public guestbook captcha).
TURNSTILE_SECRET=
-# Initial owner account, seeded on first request if no users exist yet.
-# ADMIN_PASSWORD may be a plaintext password OR a precomputed pbkdf2$... hash.
-# (ADMIN_USERNAME / ADMIN_DISPLAY_NAME live in wrangler.jsonc vars.)
-ADMIN_PASSWORD=
+# ---- 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=
+# 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
+
+# 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.
# MANUAL bot token for /v2/plural/bot/* — nothing is generated any more.
# Give this exact value to the Discord bot as DOUGH_API_TOKEN.
DOUGH_BOT_TOKEN=
-# Resend API key — sends password-reset email. Without it, POST
-# /v2/plural/forgot-password still returns its usual opaque success response
-# but no mail goes out (the failure is logged). https://resend.com/api-keys
-# The from address must be on a Resend-verified domain; see EMAIL_FROM in
-# wrangler.jsonc.
-RESEND_API_KEY=
-
-# OPTIONAL — override the Resend API base. Only needed to point at a
-# self-hosted relay, or at a local mock when testing the reset flow.
-# Defaults to https://api.resend.com.
-RESEND_API_BASE=
-
# MANUAL battery-report key(s), comma-separated. Devices send it as the
# `X-Battery-Key` header to POST /v2/battery.
BATTERY_API_KEYS=
diff --git a/src/index.ts b/src/index.ts
index c04c4b0..683d83b 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -444,14 +444,6 @@ export default {
// Cron keepalive — keep the gateway DO connected.
async scheduled(_event: ScheduledController, env: Env, _ctx: ExecutionContext): Promise<void> {
await gatewayStub(env).fetch("https://do/connect");
-
- // Housekeeping inside SystemState: removes signups that never confirmed
- // their address. Failures here must not stop the gateway keepalive above.
- try {
- await systemStub(env).fetch("https://do/internal/maintenance", { method: "POST" });
- } catch (err) {
- console.error(`Maintenance sweep failed: ${String(err)}`);
- }
},
};
diff --git a/src/system/app.ts b/src/system/app.ts
index 2556e52..1ae4c56 100644
--- a/src/system/app.ts
+++ b/src/system/app.ts
@@ -27,8 +27,6 @@ import { corsOrigins, isLocalhostOrigin } from "./config";
import { initializeAdminUser } from "./services/users";
import { authRoutes } from "./routes/auth";
-import { passwordResetRoutes } from "./routes/password_reset";
-import { emailVerificationRoutes } from "./routes/email_verification";
import { systemRoutes } from "./routes/system";
import { membersRoutes } from "./routes/members";
import { relationshipsRoutes } from "./routes/relationships";
@@ -60,8 +58,6 @@ async function ensureSeeded(): Promise<void> {
const pluralApp = new Hono<Env>();
pluralApp.route("/", authRoutes);
-pluralApp.route("/", passwordResetRoutes);
-pluralApp.route("/", emailVerificationRoutes);
pluralApp.route("/", systemRoutes);
pluralApp.route("/", membersRoutes);
pluralApp.route("/", relationshipsRoutes);
diff --git a/src/system/config.ts b/src/system/config.ts
index 9d6311c..0b4ce31 100644
--- a/src/system/config.ts
+++ b/src/system/config.ts
@@ -49,67 +49,81 @@ export function adminUsername(): string {
return rt().env.ADMIN_USERNAME ?? "admin";
}
-export function adminPassword(): string | undefined {
- return rt().env.ADMIN_PASSWORD;
-}
-
export function adminDisplayName(): string {
return rt().env.ADMIN_DISPLAY_NAME ?? "Administrator";
}
-/** Owner's email. Backfilled onto the owner account on read, so an owner
- * created before emails existed still gets one without a manual edit. */
-export function adminEmail(): string | undefined {
- const value = rt().env.ADMIN_EMAIL?.trim().toLowerCase();
- return value || undefined;
-}
+// ---------------------------------------------------------------------------
+// PocketID (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.
+// ---------------------------------------------------------------------------
-export function baseUrl(): string {
- return (rt().env.BASE_URL ?? "https://doughmination.uk").replace(/\/+$/, "");
+/** PocketID issuer origin, e.g. https://doughmination.xyz. No trailing slash.
+ * `${issuer}/.well-known/openid-configuration` must resolve. */
+export function pocketIdIssuer(): string {
+ return (rt().env.POCKETID_ISSUER ?? "").replace(/\/+$/, "");
}
-/** Public URL of the frontend (where reset links land). */
-export function frontendUrl(): string {
- return (rt().env.FRONTEND_URL ?? baseUrl()).replace(/\/+$/, "");
+/** OIDC client id issued by PocketID for this application. */
+export function pocketIdClientId(): string | undefined {
+ return rt().env.POCKETID_CLIENT_ID;
}
-// ---------------------------------------------------------------------------
-// Email (Resend)
-// ---------------------------------------------------------------------------
-
-export function resendApiKey(): string | undefined {
- return rt().env.RESEND_API_KEY;
+/** OIDC client secret. Set via `wrangler secret put POCKETID_CLIENT_SECRET`. */
+export function pocketIdClientSecret(): string | undefined {
+ return rt().env.POCKETID_CLIENT_SECRET;
}
-/** Resend API base. Overridable so a fork can point at a self-hosted relay,
- * and so the flow can be exercised against a local mock in tests. */
-export function resendApiBase(): string {
- return (rt().env.RESEND_API_BASE ?? "https://api.resend.com").replace(/\/+$/, "");
+/** 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;
+ if (configured) return configured;
+ return `${baseUrl()}/v2/plural/auth/pocketid/callback`;
}
-export function emailFrom(): string {
- return rt().env.EMAIL_FROM ?? "Doughmination System <[email protected]>";
+/** 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";
}
-/** Base URL of the password-reset page. The token is appended as ?token=. */
-export function passwordResetUrl(): string {
- const configured = rt().env.PASSWORD_RESET_URL;
+/** 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;
if (configured) return configured.replace(/\/+$/, "");
- return `${frontendUrl()}/user/reset-password`;
+ return `${frontendUrl()}/user/login/callback`;
}
-/** Base URL of the email-confirmation page. Token appended as ?token=. */
-export function verificationUrl(): string {
- const configured = rt().env.EMAIL_VERIFY_URL;
- if (configured) return configured.replace(/\/+$/, "");
- return `${frontendUrl()}/user/verify-email`;
+/** Where the browser is sent when login fails or is cancelled. */
+export function pocketIdLoginErrorUrl(): string {
+ return `${frontendUrl()}/user/login`;
}
-/** How long a password-reset token stays valid. */
-export const PASSWORD_RESET_TTL_MINUTES = 15;
+/** How long an in-flight authorization request (state + PKCE verifier) stays
+ * valid between /login and /callback. */
+export const OIDC_STATE_TTL_MINUTES = 10;
+
+/** Owner's email. Backfilled onto the owner account on read, so an owner
+ * created before emails existed still gets one without a manual edit. */
+export function adminEmail(): string | undefined {
+ const value = rt().env.ADMIN_EMAIL?.trim().toLowerCase();
+ return value || undefined;
+}
-/** Unconfirmed signups are deleted once they are older than this. */
-export const UNVERIFIED_ACCOUNT_TTL_HOURS = 24;
+export function baseUrl(): string {
+ return (rt().env.BASE_URL ?? "https://doughmination.uk").replace(/\/+$/, "");
+}
+
+/** Public URL of the frontend (where reset links land). */
+export function frontendUrl(): string {
+ return (rt().env.FRONTEND_URL ?? baseUrl()).replace(/\/+$/, "");
+}
/** Any localhost origin, on any port and either scheme — local dev servers
* (Vite :5173, Next :3000, wrangler :8787, …) are always allowed. */
diff --git a/src/system/do.ts b/src/system/do.ts
index f0320c0..ed69ffe 100644
--- a/src/system/do.ts
+++ b/src/system/do.ts
@@ -31,8 +31,6 @@ import type { SystemEnv } from "./types";
import type { UnifiedPresence } from "../types";
import { setRuntime, type Store } from "./runtime";
import { systemApp } from "./app";
-import { deleteUnverifiedUsers } from "./services/users";
-import { UNVERIFIED_ACCOUNT_TTL_HOURS } from "./config";
class DoStore implements Store {
constructor(private storage: DurableObjectStorage) {}
@@ -55,8 +53,6 @@ class DoStore implements Store {
const WS_PATH = "/v2/ws";
/** Internal DO-to-DO path GatewayManager relays presence updates to. */
const PRESENCE_RELAY_PATH = "/internal/presence";
-/** Internal cron entrypoint — sweeps unconfirmed signups. */
-const MAINTENANCE_PATH = "/internal/maintenance";
/** Per-socket presence subscription, persisted on the hibernatable socket via
* serializeAttachment so it survives eviction. Presence events are filtered
@@ -98,18 +94,6 @@ export class SystemState implements DurableObject {
return this.handleWsUpgrade();
}
- // Scheduled maintenance, driven by the Worker's cron trigger. Internal
- // only — the public router never forwards this path.
- if (url.pathname === MAINTENANCE_PATH && req.method === "POST") {
- const removed = await deleteUnverifiedUsers(UNVERIFIED_ACCOUNT_TTL_HOURS);
- if (removed.length) {
- console.info(
- `Maintenance: removed ${removed.length} unconfirmed account(s): ${removed.join(", ")}`,
- );
- }
- return Response.json({ removed_unverified: removed.length });
- }
-
// Presence relay from GatewayManager (DO-to-DO, never reaches here via the
// public Worker router).
if (url.pathname === PRESENCE_RELAY_PATH && req.method === "POST") {
diff --git a/src/system/models.ts b/src/system/models.ts
index e498063..b8e7b4d 100644
--- a/src/system/models.ts
+++ b/src/system/models.ts
@@ -27,28 +27,22 @@ export const EmailSchema = z
export const UserSchema = z.object({
id: z.string(),
username: z.string(),
- password_hash: z.string(),
- display_name: z.string().nullable().optional(),
- /** Optional on the schema so pre-existing accounts (created before emails
- * were required) still load. New signups always set it. */
- email: z.string().nullable().optional(),
/**
- * Whether `email` has been proven to belong to this user.
- *
- * MIGRATION SAFETY: accounts created before verification existed have this
- * field absent. Absent is read as TRUE (see services/users.ts) so that
- * legacy accounts are grandfathered — they can still log in, and the
- * unverified-account sweep will never delete them. Only rows that explicitly
- * say `false` are treated as unverified.
+ * The PocketID subject identifier (OIDC `sub`) this account is linked to.
+ * Set on first PocketID login and used as the primary match key thereafter.
+ * Optional so the owner seed and pre-link accounts still load.
+ */
+ pocket_id: 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.
*/
- email_verified: z.boolean().optional(),
- email_verified_at: z.string().nullable().optional(),
- /** ISO timestamp. Absent on legacy accounts; the cleanup sweep requires it,
- * which is a second guard against deleting pre-migration users. */
+ password_hash: z.string().nullable().optional(),
+ display_name: z.string().nullable().optional(),
+ /** Email address, populated from the PocketID `email` claim when available. */
+ email: z.string().nullable().optional(),
+ /** ISO timestamp of account creation. Absent on legacy accounts. */
created_at: z.string().nullable().optional(),
- /** A new address awaiting verification. `email` is not replaced until the
- * user proves they control this one, so a typo can't lock them out. */
- pending_email: z.string().nullable().optional(),
is_admin: z.boolean().default(false),
is_owner: z.boolean().default(false),
is_pet: z.boolean().default(false),
@@ -58,7 +52,9 @@ export type User = z.infer<typeof UserSchema>;
export const UserCreateSchema = z.object({
username: z.string(),
- password: z.string(),
+ /** Set when an admin pre-provisions an account before its first PocketID
+ * login; normally the link is established automatically on login. */
+ pocket_id: z.string().nullable().optional(),
email: EmailSchema.nullable().optional(),
display_name: z.string().nullable().optional(),
is_admin: z.boolean().default(false),
@@ -71,8 +67,6 @@ export const UserResponseSchema = z.object({
username: z.string(),
display_name: z.string().nullable().optional(),
email: z.string().nullable().optional(),
- email_verified: z.boolean().optional(),
- pending_email: z.string().nullable().optional(),
created_at: z.string().nullable().optional(),
is_admin: z.boolean().default(false),
is_owner: z.boolean().default(false),
@@ -83,14 +77,11 @@ export type UserResponse = z.infer<typeof UserResponseSchema>;
export const UserUpdateSchema = z.object({
display_name: z.string().nullable().optional(),
- current_password: z.string().nullable().optional(),
- new_password: z.string().nullable().optional(),
avatar_url: z.string().nullable().optional(),
/**
- * Changeable by the account's own user or by the owner — never by a plain
- * admin acting on someone else. A user changing their OWN address must also
- * send `current_password`, and the new address lands in `pending_email`
- * until verified. The owner sets addresses outright. See services/users.ts.
+ * 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,
+ * so this field is purely informational/contact metadata.
*/
email: EmailSchema.nullable().optional(),
is_admin: z.boolean().nullable().optional(),
@@ -98,68 +89,9 @@ export const UserUpdateSchema = z.object({
});
export type UserUpdate = z.infer<typeof UserUpdateSchema>;
-export const LoginRequestSchema = z.object({
- username: z.string(),
- password: z.string(),
- turnstile_token: z.string(),
-});
-export type LoginRequest = z.infer<typeof LoginRequestSchema>;
-
-/** Password reset is keyed on USERNAME — the link goes to whatever address is
- * on file for that account. Users who've forgotten their username use
- * ForgotUsernameRequest below to get it emailed to them first. */
-export const ForgotPasswordRequestSchema = z.object({
- username: z.string().trim().min(1, "Username is required"),
- turnstile_token: z.string().min(1, "Security verification is required"),
-});
-export type ForgotPasswordRequest = z.infer<typeof ForgotPasswordRequestSchema>;
-
-export const ForgotUsernameRequestSchema = z.object({
- email: EmailSchema,
- turnstile_token: z.string().min(1, "Security verification is required"),
-});
-export type ForgotUsernameRequest = z.infer<typeof ForgotUsernameRequestSchema>;
-
-export const VerifyEmailRequestSchema = z.object({
- token: z.string().min(1, "Verification token is required"),
-});
-export type VerifyEmailRequest = z.infer<typeof VerifyEmailRequestSchema>;
-
-/** Resend a verification email. Either a correction token (held by the tab
- * that just signed up) or username+password identifies the account. */
-export const ResendVerificationRequestSchema = z.object({
- correction_token: z.string().optional(),
- username: z.string().trim().optional(),
- password: z.string().optional(),
- turnstile_token: z.string().min(1, "Security verification is required"),
-});
-export type ResendVerificationRequest = z.infer<typeof ResendVerificationRequestSchema>;
-
-/**
- * Fix a mistyped address before verification, without a password.
- *
- * The correction token is what makes this safe: it is issued only to the
- * client that created the account, is short-lived, and only works while the
- * account is still unverified. Without it, this endpoint would let anyone
- * repoint an unverified account at their own inbox and claim it.
- */
-export const CorrectEmailRequestSchema = z.object({
- correction_token: z.string().min(1, "Correction token is required"),
- email: EmailSchema,
- turnstile_token: z.string().min(1, "Security verification is required"),
-});
-export type CorrectEmailRequest = z.infer<typeof CorrectEmailRequestSchema>;
-
-export const ResetPasswordRequestSchema = z.object({
- token: z.string().min(1, "Reset token is required"),
- new_password: z.string().min(10, "Password must be at least 10 characters long"),
- turnstile_token: z.string().min(1, "Security verification is required"),
-});
-export type ResetPasswordRequest = z.infer<typeof ResetPasswordRequestSchema>;
-
-/** Strip the password hash for public-facing responses. */
+/** Strip internal-only fields for public-facing responses. */
export function toUserResponse(user: User): UserResponse {
- const { password_hash: _drop, ...rest } = user;
+ const { password_hash: _pw, pocket_id: _sub, ...rest } = user;
return rest;
}
diff --git a/src/system/routes/auth.ts b/src/system/routes/auth.ts
index e9bb05b..67474bf 100644
--- a/src/system/routes/auth.ts
+++ b/src/system/routes/auth.ts
@@ -4,20 +4,29 @@
* See LICENCE.md in the project root for full licence information.
*/
+/**
+ * Authentication — PocketID (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.
+ *
+ * Everything downstream (the /user_info + /auth/is_* checks and every
+ * requireAuth route) keeps using the same HS256 bearer token as before.
+ */
+
import { Hono } from "hono";
-import type { Context } from "hono";
import type { Env } from "../hono";
-import { UserResponseSchema, LoginRequestSchema, EmailSchema } from "../models";
+import { UserResponseSchema } from "../models";
import type { User } from "../models";
-import { verifyUser, createUser, getUsers, isEmailVerified } from "../services/users";
-import { createCorrectionToken, CORRECTION_TTL_HOURS } from "../services/email_verification";
-import { sendVerificationEmail } from "./email_verification";
-import { UNVERIFIED_ACCOUNT_TTL_HOURS } from "../config";
-import { createAccessToken, verifyTurnstileToken } from "../security";
+import { findOrCreateFromPocketId } from "../services/users";
+import { beginLogin, completeLogin } from "../services/oidc";
+import { pocketIdPostLoginUrl, pocketIdLoginErrorUrl } from "../config";
+import { createAccessToken } from "../security";
import { requireAuth } from "../middleware/auth";
-import { HttpError } from "../errors";
-import { rt } from "../runtime";
export const authRoutes = new Hono<Env>();
@@ -27,8 +36,6 @@ function toUserResponseJson(user: User) {
username: user.username,
display_name: user.display_name,
email: user.email ?? null,
- email_verified: isEmailVerified(user),
- pending_email: user.pending_email ?? null,
created_at: user.created_at ?? null,
is_admin: user.is_admin,
is_owner: user.is_owner,
@@ -37,48 +44,67 @@ function toUserResponseJson(user: User) {
});
}
-function clientIp(c: Context): string | undefined {
- return c.req.header("cf-connecting-ip") ?? c.req.header("x-forwarded-for")?.split(",")[0].trim();
+/** 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. */
+function safeReturnPath(raw: string | undefined): string {
+ if (!raw) return "/";
+ if (!raw.startsWith("/") || raw.startsWith("//")) return "/";
+ return raw;
}
-/** Unified login: JSON (with Turnstile) or legacy form data. */
-authRoutes.post("/login", async (c) => {
- const contentType = c.req.header("content-type") ?? "";
-
- let username: string | undefined;
- let password: string | undefined;
-
- if (contentType.includes("application/json")) {
- const parsed = LoginRequestSchema.safeParse(await c.req.json().catch(() => ({})));
- if (!parsed.success) throw new HttpError(400, "Invalid request format");
+/** Start the PocketID login: 302 to the provider's authorization endpoint. */
+authRoutes.get("/auth/pocketid/login", async (c) => {
+ const from = safeReturnPath(c.req.query("from"));
+ const authUrl = await beginLogin(from);
+ return c.redirect(authUrl, 302);
+});
- const ok = await verifyTurnstileToken(parsed.data.turnstile_token, clientIp(c));
- if (!ok) throw new HttpError(400, "Security verification failed");
+/** PocketID redirects the browser back here after the user authenticates. */
+authRoutes.get("/auth/pocketid/callback", async (c) => {
+ const errorParam = c.req.query("error");
+ if (errorParam) {
+ const url = new URL(pocketIdLoginErrorUrl());
+ url.searchParams.set("error", errorParam);
+ return c.redirect(url.toString(), 302);
+ }
- username = parsed.data.username;
- password = parsed.data.password;
- } else {
- const body = await c.req.parseBody();
- username = typeof body.username === "string" ? body.username : undefined;
- password = typeof body.password === "string" ? body.password : undefined;
- if (!username || !password) throw new HttpError(400, "Username and password required");
+ 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);
}
- const user = await verifyUser(username, password);
- if (!user) {
- throw new HttpError(401, "Invalid credentials", { "WWW-Authenticate": "Bearer" });
+ let result;
+ try {
+ result = await completeLogin(code, state);
+ } 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);
}
- // Unconfirmed signups cannot log in. The credentials were correct, so it's
- // safe to say why — and the frontend needs to know in order to offer a
- // resend. Legacy accounts predate verification and are treated as confirmed
- // (see isEmailVerified), so this never locks out an existing user.
- if (!isEmailVerified(user)) {
- throw new HttpError(
- 403,
- "Confirm your email address before logging in. Check your inbox for the confirmation link.",
- { "X-Auth-Reason": "email_unverified" },
+ const { identity, from } = result;
+
+ let user: User;
+ try {
+ user = await findOrCreateFromPocketId({
+ sub: identity.sub,
+ 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);
}
const token = await createAccessToken({
@@ -91,118 +117,11 @@ authRoutes.post("/login", async (c) => {
avatar_url: user.avatar_url ?? null,
});
- return c.json({ access_token: token, token_type: "bearer", success: true });
-});
-
-/** Public signup with Turnstile. */
-authRoutes.post("/signup", async (c) => {
- const body = (await c.req.json().catch(() => ({}))) as Record<string, unknown>;
-
- const username = String(body.username ?? "").trim();
- const password = typeof body.password === "string" ? body.password : "";
- const displayName = String(body.display_name ?? "").trim() || null;
- const turnstileToken = typeof body.turnstile_token === "string" ? body.turnstile_token : "";
-
- if (!username) throw new HttpError(400, "Username is required");
- if (!password) throw new HttpError(400, "Password is required");
- if (password.length < 10) throw new HttpError(400, "Password must be at least 10 characters long");
-
- // Email is required at signup — it is the only self-service account
- // recovery route. Existing accounts predate this and are backfilled by hand.
- const emailParsed = EmailSchema.safeParse(body.email ?? "");
- if (!emailParsed.success) {
- throw new HttpError(400, emailParsed.error.issues[0]?.message ?? "A valid email is required");
- }
- const email = emailParsed.data;
-
- if (!turnstileToken) throw new HttpError(400, "Security verification is required");
-
- const ok = await verifyTurnstileToken(turnstileToken, clientIp(c));
- if (!ok) throw new HttpError(400, "Security verification failed");
-
- const users = await getUsers();
- const usernameLower = username.toLowerCase();
- if (users.some((u) => u.username.toLowerCase() === usernameLower)) {
- throw new HttpError(400, "Username already exists");
- }
- if (users.some((u) => u.email && u.email.toLowerCase() === email)) {
- throw new HttpError(400, "Email address is already in use");
- }
-
- try {
- const newUser = await createUser(
- { username, password, email, display_name: displayName, is_admin: false, is_pet: false },
- null,
- { emailVerified: false },
- );
-
- const sent = await sendVerificationEmail(newUser, email, "signup");
-
- // The correction token goes ONLY to the client that just created the
- // account, and is what lets them fix a typo'd address without a password.
- // Treat it like a credential: it is not recoverable once this tab is gone.
- const correctionToken = await createCorrectionToken(newUser.id);
-
- return c.json({
- success: true,
- message: sent
- ? "Account created. Check your inbox to confirm your email address."
- : "Account created, but we couldn't send the confirmation email. Use the resend option.",
- email_sent: sent,
- correction_token: correctionToken,
- correction_expires_in_hours: CORRECTION_TTL_HOURS,
- unverified_deleted_after_hours: UNVERIFIED_ACCOUNT_TTL_HOURS,
- user: toUserResponseJson(newUser),
- });
- } catch (err) {
- if (err instanceof HttpError) throw err;
- throw new HttpError(400, String(err instanceof Error ? err.message : err));
- }
-});
-
-/** Public username availability check. */
-authRoutes.get("/users/check-username", async (c) => {
- const username = c.req.query("username") ?? "";
- if (!username.trim()) throw new HttpError(400, "Username parameter is required");
-
- const users = await getUsers();
- const usernameLower = username.trim().toLowerCase();
- const exists = users.some((u) => u.username.toLowerCase() === usernameLower);
- return c.json({ username, exists, available: !exists });
-});
-
-/**
- * Public email availability check, powering the live signup field.
- *
- * This intentionally reveals whether an address is registered — same trade-off
- * as /forgot-password, accepted so signup can flag duplicates before submit.
- * Rate limited per IP because that disclosure makes it worth probing.
- */
-authRoutes.get("/users/check-email", async (c) => {
- const raw = c.req.query("email") ?? "";
- const parsedEmail = EmailSchema.safeParse(raw);
- if (!parsedEmail.success) {
- throw new HttpError(400, "A valid email parameter is required");
- }
-
- const ip = clientIp(c);
- if (ip) {
- const key = `checkemail_rl:${ip}`;
- const bucket = await rt().store.get<{ count: number; reset: number }>(key, {
- count: 0,
- reset: 0,
- });
- const now = Date.now();
- const window = now > bucket.reset ? { count: 0, reset: now + 60_000 } : bucket;
- if (window.count >= 20) {
- throw new HttpError(429, "Too many lookups. Please wait a minute and try again.");
- }
- await rt().store.put(key, { count: window.count + 1, reset: window.reset });
- }
-
- const users = await getUsers();
- const exists = users.some((u) => u.email && u.email.toLowerCase() === parsedEmail.data);
- return c.json({ email: parsedEmail.data, exists, available: !exists });
+ // 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());
+ dest.hash = `token=${encodeURIComponent(token)}&from=${encodeURIComponent(from)}`;
+ return c.redirect(dest.toString(), 302);
});
authRoutes.get("/user_info", requireAuth, (c) => c.json(toUserResponseJson(c.get("user") as User)));
diff --git a/src/system/routes/email_verification.ts b/src/system/routes/email_verification.ts
deleted file mode 100644
index 95f1806..0000000
--- a/src/system/routes/email_verification.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Email verification:
- *
- * POST /v2/plural/verify-email confirm an address with a token
- * POST /v2/plural/resend-verification send the confirmation link again
- * POST /v2/plural/correct-email fix a typo'd address, no password
- *
- * `correct-email` is the one to be careful with. It deliberately skips the
- * password so someone who mistyped their address at signup isn't locked out of
- * a mailbox they can't read. What makes that safe is the correction token: it
- * is returned only to the client that created the account, expires in a couple
- * of hours, is scoped to that one account, and stops working the moment the
- * account is verified. Without it this endpoint would let anyone repoint any
- * unverified account at their own inbox and claim it.
- */
-
-import { Hono } from "hono";
-import type { Context } from "hono";
-
-import type { Env } from "../hono";
-import {
- CorrectEmailRequestSchema,
- ResendVerificationRequestSchema,
- VerifyEmailRequestSchema,
-} from "../models";
-import type { User } from "../models";
-import { frontendUrl, verificationUrl, UNVERIFIED_ACCOUNT_TTL_HOURS } from "../config";
-import {
- applyEmailVerification,
- correctUnverifiedEmail,
- getUserById,
- getUserByUsername,
- isEmailVerified,
- verifyUser,
-} from "../services/users";
-import {
- CORRECTION_TTL_HOURS,
- VERIFICATION_TTL_HOURS,
- createVerificationToken,
- consumeVerificationToken,
- peekCorrectionToken,
- revokeCorrectionTokensForUser,
-} from "../services/email_verification";
-import { sendEmail, verifyEmailTemplate } from "../services/email";
-import { verifyTurnstileToken } from "../security";
-import { HttpError } from "../errors";
-import { rt } from "../runtime";
-
-export const emailVerificationRoutes = new Hono<Env>();
-
-const RATE_LIMIT_SECONDS = 60;
-
-function clientIp(c: Context): string | undefined {
- return c.req.header("cf-connecting-ip") ?? c.req.header("x-forwarded-for")?.split(",")[0].trim();
-}
-
-async function checkAndRecordRateLimit(prefix: string, ip: string | undefined): Promise<boolean> {
- if (!ip) return true;
- const key = prefix + ip;
- const last = await rt().store.get<number>(key, 0);
- const now = Date.now();
- if (last && now - last < RATE_LIMIT_SECONDS * 1000) return false;
- await rt().store.put(key, now);
- return true;
-}
-
-function firstIssueMessage(issues: Array<{ message: string }>, fallback: string): string {
- return issues[0]?.message ?? fallback;
-}
-
-/**
- * Issue a token for `address` and email the confirmation link.
- * Shared by signup, resend, correction, and self-service email change.
- */
-export async function sendVerificationEmail(
- user: User,
- address: string,
- purpose: "signup" | "change",
-): Promise<boolean> {
- const token = await createVerificationToken(user.id, address, purpose);
- const link = `${verificationUrl()}?token=${encodeURIComponent(token)}`;
-
- const { subject, html, text } = verifyEmailTemplate({
- displayName: user.display_name || user.username,
- verifyUrl: link,
- ttlHours: VERIFICATION_TTL_HOURS,
- isChange: purpose === "change",
- deleteAfterHours: purpose === "signup" ? UNVERIFIED_ACCOUNT_TTL_HOURS : undefined,
- });
-
- return sendEmail({ to: address, subject, html, text });
-}
-
-// ---------------------------------------------------------------------------
-// POST /verify-email
-// ---------------------------------------------------------------------------
-
-emailVerificationRoutes.post("/verify-email", async (c) => {
- const parsed = VerifyEmailRequestSchema.safeParse(await c.req.json().catch(() => ({})));
- if (!parsed.success) {
- throw new HttpError(400, firstIssueMessage(parsed.error.issues, "Invalid request format"));
- }
-
- const claim = await consumeVerificationToken(parsed.data.token);
- if (!claim) {
- throw new HttpError(
- 400,
- "This confirmation link is invalid or has expired. Request a new one from the login page.",
- );
- }
-
- const updated = await applyEmailVerification(claim.userId, claim.email);
- if (!updated) {
- // Either the account is gone (swept as unverified) or the address moved on
- // after this token was issued, which makes the link stale.
- throw new HttpError(
- 400,
- "This confirmation link is no longer valid. Request a new one from the login page.",
- );
- }
-
- // A verified account has no further use for its correction token.
- await revokeCorrectionTokensForUser(updated.id);
-
- console.info(`Email verified for user ${updated.id}`);
- return c.json({
- success: true,
- message: "Email confirmed. You can now log in.",
- username: updated.username,
- });
-});
-
-// ---------------------------------------------------------------------------
-// POST /resend-verification
-// ---------------------------------------------------------------------------
-
-emailVerificationRoutes.post("/resend-verification", async (c) => {
- const parsed = ResendVerificationRequestSchema.safeParse(await c.req.json().catch(() => ({})));
- if (!parsed.success) {
- throw new HttpError(400, firstIssueMessage(parsed.error.issues, "Invalid request format"));
- }
-
- const ok = await verifyTurnstileToken(parsed.data.turnstile_token, clientIp(c));
- if (!ok) throw new HttpError(400, "Security verification failed");
-
- if (!(await checkAndRecordRateLimit("resendverify_rl:", clientIp(c)))) {
- throw new HttpError(429, "Too many requests. Please wait a minute and try again.");
- }
-
- // Identify the account either by the signup tab's correction token, or by
- // credentials — login is blocked while unverified, so a correct password is
- // the only other way to prove which account this is.
- let user: User | null = null;
-
- if (parsed.data.correction_token) {
- const userId = await peekCorrectionToken(parsed.data.correction_token);
- if (userId) user = await getUserById(userId);
- } else if (parsed.data.username && parsed.data.password) {
- user = await verifyUser(parsed.data.username, parsed.data.password);
- } else {
- throw new HttpError(400, "Provide your username and password, or use the link from signup.");
- }
-
- if (!user) throw new HttpError(401, "We couldn't confirm which account that is.");
-
- const address = user.pending_email || user.email;
- if (!address) throw new HttpError(409, "That account has no email address on file.");
-
- if (isEmailVerified(user) && !user.pending_email) {
- return c.json({ success: true, message: "That address is already confirmed.", already: true });
- }
-
- const sent = await sendVerificationEmail(user, address, user.pending_email ? "change" : "signup");
- if (!sent) {
- throw new HttpError(502, "We couldn't send that email just now. Please try again shortly.");
- }
-
- return c.json({ success: true, message: "Confirmation email sent. Check your inbox." });
-});
-
-// ---------------------------------------------------------------------------
-// POST /correct-email
-// ---------------------------------------------------------------------------
-
-emailVerificationRoutes.post("/correct-email", async (c) => {
- const parsed = CorrectEmailRequestSchema.safeParse(await c.req.json().catch(() => ({})));
- if (!parsed.success) {
- throw new HttpError(400, firstIssueMessage(parsed.error.issues, "Invalid request format"));
- }
-
- const ok = await verifyTurnstileToken(parsed.data.turnstile_token, clientIp(c));
- if (!ok) throw new HttpError(400, "Security verification failed");
-
- if (!(await checkAndRecordRateLimit("correctemail_rl:", clientIp(c)))) {
- throw new HttpError(429, "Too many requests. Please wait a minute and try again.");
- }
-
- const userId = await peekCorrectionToken(parsed.data.correction_token);
- if (!userId) {
- throw new HttpError(
- 400,
- "That correction link has expired. Sign up again, or contact @doughmination.",
- );
- }
-
- const user = await getUserById(userId);
- if (!user) throw new HttpError(404, "That account no longer exists.");
-
- let updated: User | null;
- try {
- updated = await correctUnverifiedEmail(user.id, parsed.data.email);
- } catch (err) {
- throw new HttpError(400, String(err instanceof Error ? err.message : err));
- }
- if (!updated) throw new HttpError(404, "That account no longer exists.");
-
- const sent = await sendVerificationEmail(updated, parsed.data.email, "signup");
- if (!sent) {
- throw new HttpError(502, "Address updated, but we couldn't send the confirmation email.");
- }
-
- return c.json({
- success: true,
- message: "Address updated. We've sent a new confirmation email.",
- login_url: `${frontendUrl()}/user/login`,
- correction_expires_in_hours: CORRECTION_TTL_HOURS,
- });
-});
diff --git a/src/system/routes/password_reset.ts b/src/system/routes/password_reset.ts
deleted file mode 100644
index c4c4db5..0000000
--- a/src/system/routes/password_reset.ts
+++ /dev/null
@@ -1,251 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Account recovery:
- *
- * POST /v2/plural/forgot-password username -> reset link, emailed
- * POST /v2/plural/forgot-username email -> username, emailed
- * GET /v2/plural/reset-password/check is this token still usable?
- * POST /v2/plural/reset-password set a new password with a token
- *
- * Password reset is keyed on USERNAME: the link is sent to whatever address is
- * on file for that account, and the response reports a masked hint (a•••@d•••)
- * so the user knows which inbox to open without the full address being printed
- * to anyone who guesses a username.
- *
- * NOTE ON ENUMERATION — deliberate product decision, not an oversight.
- * /forgot-password says so when a username doesn't exist, and /forgot-username
- * says so when an address isn't registered, so users aren't left waiting on
- * mail that was never going to arrive. The trade-off is that both endpoints
- * confirm whether an account exists. The per-IP rate limits below are
- * therefore the primary abuse control on these routes, not a secondary one —
- * do not relax them.
- */
-
-import { Hono } from "hono";
-import type { Context } from "hono";
-
-import type { Env } from "../hono";
-import {
- ForgotPasswordRequestSchema,
- ForgotUsernameRequestSchema,
- ResetPasswordRequestSchema,
-} from "../models";
-import { PASSWORD_RESET_TTL_MINUTES, frontendUrl, passwordResetUrl } from "../config";
-import { getUserByEmail, getUserById, getUserByUsername, setPassword } from "../services/users";
-import {
- consumeResetToken,
- createResetToken,
- peekResetToken,
- revokeResetTokensForUser,
-} from "../services/password_reset";
-import { passwordResetTemplate, sendEmail, usernameReminderTemplate } from "../services/email";
-import { verifyTurnstileToken } from "../security";
-import { HttpError } from "../errors";
-import { rt } from "../runtime";
-
-export const passwordResetRoutes = new Hono<Env>();
-
-/** Minimum seconds between recovery requests from one IP. Because these
- * endpoints confirm account existence (see module comment), this is what
- * keeps bulk probing impractical. */
-const RATE_LIMIT_SECONDS = 60;
-
-function clientIp(c: Context): string | undefined {
- return c.req.header("cf-connecting-ip") ?? c.req.header("x-forwarded-for")?.split(",")[0].trim();
-}
-
-/** Per-IP throttle. True = allowed (and recorded). Blank IP is never limited. */
-async function checkAndRecordRateLimit(prefix: string, ip: string | undefined): Promise<boolean> {
- if (!ip) return true;
- const key = prefix + ip;
- const last = await rt().store.get<number>(key, 0);
- const now = Date.now();
- if (last && now - last < RATE_LIMIT_SECONDS * 1000) return false;
- await rt().store.put(key, now);
- return true;
-}
-
-function firstIssueMessage(issues: Array<{ message: string }>, fallback: string): string {
- return issues[0]?.message ?? fallback;
-}
-
-/**
- * Mask an address for display: `[email protected]` -> `a•••@d•••.win`.
- * Enough to recognise your own inbox, not enough to learn someone else's.
- */
-export function maskEmail(email: string): string {
- const at = email.lastIndexOf("@");
- if (at <= 0) return "•••";
-
- const local = email.slice(0, at);
- const domain = email.slice(at + 1);
-
- const maskedLocal = local.length <= 1 ? "•" : `${local[0]}•••`;
-
- const dot = domain.lastIndexOf(".");
- if (dot <= 0) return `${maskedLocal}@•••`;
-
- const domainName = domain.slice(0, dot);
- const tld = domain.slice(dot); // includes the dot
- const maskedDomain = domainName.length <= 1 ? "•" : `${domainName[0]}•••`;
-
- return `${maskedLocal}@${maskedDomain}${tld}`;
-}
-
-// ---------------------------------------------------------------------------
-// POST /forgot-password — by username
-// ---------------------------------------------------------------------------
-
-passwordResetRoutes.post("/forgot-password", async (c) => {
- const parsed = ForgotPasswordRequestSchema.safeParse(await c.req.json().catch(() => ({})));
- if (!parsed.success) {
- throw new HttpError(400, firstIssueMessage(parsed.error.issues, "Invalid request format"));
- }
-
- const ok = await verifyTurnstileToken(parsed.data.turnstile_token, clientIp(c));
- if (!ok) throw new HttpError(400, "Security verification failed");
-
- if (!(await checkAndRecordRateLimit("pwreset_rl:", clientIp(c)))) {
- throw new HttpError(429, "Too many reset requests. Please wait a minute and try again.");
- }
-
- const user = await getUserByUsername(parsed.data.username);
- if (!user) {
- throw new HttpError(
- 404,
- "No account exists with that username. Check the spelling, or use “forgot username” if you're not sure.",
- );
- }
-
- if (!user.email) {
- throw new HttpError(
- 409,
- "That account has no email address on file, so it can't be reset automatically. Contact @doughmination to recover it.",
- );
- }
-
- const token = await createResetToken(user.id);
- const resetUrl = `${passwordResetUrl()}?token=${encodeURIComponent(token)}`;
-
- const { subject, html, text } = passwordResetTemplate({
- displayName: user.display_name || user.username,
- resetUrl,
- ttlMinutes: PASSWORD_RESET_TTL_MINUTES,
- });
-
- const sent = await sendEmail({ to: user.email, subject, html, text });
- if (!sent) {
- console.error(`Failed to send password reset email for user ${user.id}`);
- throw new HttpError(
- 502,
- "We couldn't send the reset email just now. Please try again in a few minutes.",
- );
- }
-
- return c.json({
- success: true,
- message: "Reset link sent. The link expires in 15 minutes.",
- sent_to: maskEmail(user.email),
- });
-});
-
-// ---------------------------------------------------------------------------
-// POST /forgot-username — by email
-// ---------------------------------------------------------------------------
-
-passwordResetRoutes.post("/forgot-username", async (c) => {
- const parsed = ForgotUsernameRequestSchema.safeParse(await c.req.json().catch(() => ({})));
- if (!parsed.success) {
- throw new HttpError(400, firstIssueMessage(parsed.error.issues, "Invalid request format"));
- }
-
- const ok = await verifyTurnstileToken(parsed.data.turnstile_token, clientIp(c));
- if (!ok) throw new HttpError(400, "Security verification failed");
-
- if (!(await checkAndRecordRateLimit("username_rl:", clientIp(c)))) {
- throw new HttpError(429, "Too many requests. Please wait a minute and try again.");
- }
-
- const user = await getUserByEmail(parsed.data.email);
- if (!user) {
- throw new HttpError(404, "No account is registered with that email address.");
- }
-
- // The username is emailed rather than returned, so that knowing an address
- // isn't enough to learn the username attached to it.
- const { subject, html, text } = usernameReminderTemplate({
- username: user.username,
- displayName: user.display_name || user.username,
- loginUrl: `${frontendUrl()}/user/login`,
- });
-
- const sent = await sendEmail({ to: parsed.data.email, subject, html, text });
- if (!sent) {
- console.error(`Failed to send username reminder for user ${user.id}`);
- throw new HttpError(
- 502,
- "We couldn't send that email just now. Please try again in a few minutes.",
- );
- }
-
- return c.json({
- success: true,
- message: "We've sent your username to that address.",
- sent_to: maskEmail(parsed.data.email),
- });
-});
-
-// ---------------------------------------------------------------------------
-// GET /reset-password/check?token=...
-// ---------------------------------------------------------------------------
-
-/** Lets the frontend show "this link expired" before rendering the form. */
-passwordResetRoutes.get("/reset-password/check", async (c) => {
- const token = c.req.query("token") ?? "";
- if (!token) throw new HttpError(400, "Token parameter is required");
-
- const userId = await peekResetToken(token);
- return c.json({ valid: userId !== null });
-});
-
-// ---------------------------------------------------------------------------
-// POST /reset-password
-// ---------------------------------------------------------------------------
-
-passwordResetRoutes.post("/reset-password", async (c) => {
- const parsed = ResetPasswordRequestSchema.safeParse(await c.req.json().catch(() => ({})));
- if (!parsed.success) {
- throw new HttpError(400, firstIssueMessage(parsed.error.issues, "Invalid request format"));
- }
-
- const ok = await verifyTurnstileToken(parsed.data.turnstile_token, clientIp(c));
- if (!ok) throw new HttpError(400, "Security verification failed");
-
- // Consumed up front, so a token is spent even if the write below fails.
- // Better to make the user request a fresh link than to leave a live token.
- const userId = await consumeResetToken(parsed.data.token);
- if (!userId) {
- throw new HttpError(400, "This reset link is invalid or has expired. Please request a new one.");
- }
-
- const user = await getUserById(userId);
- if (!user) throw new HttpError(400, "This reset link is no longer valid.");
-
- const updated = await setPassword(userId, parsed.data.new_password);
- if (!updated) throw new HttpError(400, "This reset link is no longer valid.");
-
- // Belt and braces — consumeResetToken already removed this one.
- await revokeResetTokensForUser(userId);
-
- console.info(`Password reset completed for user ${userId}`);
- return c.json({
- success: true,
- message: "Your password has been reset. You can now log in with your new password.",
- username: user.username,
- });
-});
diff --git a/src/system/routes/users.ts b/src/system/routes/users.ts
index f3094f8..7069b67 100644
--- a/src/system/routes/users.ts
+++ b/src/system/routes/users.ts
@@ -14,10 +14,7 @@ import { Hono } from "hono";
import type { Env } from "../hono";
import { UserCreateSchema, UserUpdateSchema, toUserResponse } from "../models";
import type { User } from "../models";
-import { getUsers, createUser, updateUser, deleteUser, getUserById } from "../services/users";
-import { sendEmail, emailChangeAlertTemplate } from "../services/email";
-import { sendVerificationEmail } from "./email_verification";
-import { maskEmail } from "./password_reset";
+import { getUsers, createUser, updateUser, deleteUser } from "../services/users";
import { requireAuth, requireAdmin } from "../middleware/auth";
import { HttpError } from "../errors";
@@ -38,9 +35,10 @@ usersRoutes.post("/users", requireAuth, requireAdmin, async (c) => {
if (!parsed.success) return c.json({ detail: validationDetail(parsed.error.issues) }, 422);
try {
- // Owner/admin-created accounts skip confirmation: the address is being
- // assigned deliberately, not self-asserted by a stranger.
- const newUser = await createUser(parsed.data, c.get("user") ?? null, { emailVerified: true });
+ // Admin-provisioned account. It becomes usable once the person signs in
+ // through PocketID 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));
} catch (err) {
throw new HttpError(400, String(err instanceof Error ? err.message : err));
@@ -58,57 +56,10 @@ usersRoutes.put("/users/:user_id", requireAuth, async (c) => {
const parsed = UserUpdateSchema.safeParse(await c.req.json().catch(() => ({})));
if (!parsed.success) return c.json({ detail: validationDetail(parsed.error.issues) }, 422);
- // Captured before the write so we can tell whether this request started a
- // new email change, rather than re-sending on every unrelated profile save.
- const before = await getUserById(userId);
- const previousPending = before?.pending_email ?? null;
-
try {
const updated = await updateUser(userId, parsed.data, currentUser);
if (!updated) throw new HttpError(404, "User not found");
-
- const newPending = updated.pending_email ?? null;
- let emailPending = false;
-
- if (newPending && newPending !== previousPending) {
- emailPending = true;
-
- // Confirmation to the new address — until this is clicked, the account
- // keeps its existing address.
- const sent = await sendVerificationEmail(updated, newPending, "change");
- if (!sent) {
- console.error(`Failed to send change-confirmation for user ${updated.id}`);
- }
-
- // Heads-up to the OLD address, so a takeover attempt is visible to
- // whoever actually owns the account. Best-effort; never blocks.
- if (before?.email) {
- const alert = emailChangeAlertTemplate({
- displayName: updated.display_name || updated.username,
- newEmailMasked: maskEmail(newPending),
- });
- const alerted = await sendEmail({
- to: before.email,
- subject: alert.subject,
- html: alert.html,
- text: alert.text,
- });
- if (!alerted) {
- console.error(`Failed to send change alert to previous address for ${updated.id}`);
- }
- }
- }
-
- return c.json({
- ...toUserResponse(updated),
- email_change_pending: emailPending,
- ...(emailPending
- ? {
- message:
- "Check the new address for a confirmation link. Your current email stays active until then.",
- }
- : {}),
- });
+ return c.json(toUserResponse(updated));
} catch (err) {
if (err instanceof HttpError) throw err;
throw new HttpError(400, String(err instanceof Error ? err.message : err));
diff --git a/src/system/security.ts b/src/system/security.ts
index f0aff1b..4c3fa94 100644
--- a/src/system/security.ts
+++ b/src/system/security.ts
@@ -8,16 +8,19 @@
* Security utilities, rewritten for the Workers runtime (Web Crypto only —
* no `bcrypt`, `jsonwebtoken`, or `axios`).
*
- * - Passwords: PBKDF2-HMAC-SHA-256, stored as `pbkdf2$<iters>$<salt>$<hash>`.
- * Old bcrypt hashes will NOT verify (expected — set passwords fresh).
- * - JWT: HS256 signed/verified with SubtleCrypto HMAC.
- * - Turnstile: verified with `fetch`.
+ * - 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.
+ * - 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.
*/
import { ACCESS_TOKEN_EXPIRE_MINUTES, jwtSecret, turnstileSecret } from "./config";
import { HttpError } from "./errors";
-const PBKDF2_ITERATIONS = 100_000;
const enc = new TextEncoder();
const dec = new TextDecoder();
@@ -57,48 +60,19 @@ export function constantTimeStringEqual(a: string, b: string): boolean {
}
// ---------------------------------------------------------------------------
-// Password hashing (PBKDF2)
+// OIDC / PKCE helpers
// ---------------------------------------------------------------------------
-async function pbkdf2(password: string, salt: Uint8Array, iterations: number): Promise<Uint8Array> {
- const keyMaterial = await crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, [
- "deriveBits",
- ]);
- const bits = await crypto.subtle.deriveBits(
- { name: "PBKDF2", salt, iterations, hash: "SHA-256" },
- keyMaterial,
- 256,
- );
- return new Uint8Array(bits);
-}
-
-export async function hashPassword(password: string): Promise<string> {
- const salt = crypto.getRandomValues(new Uint8Array(16));
- const hash = await pbkdf2(password, salt, PBKDF2_ITERATIONS);
- return `pbkdf2$${PBKDF2_ITERATIONS}$${bytesToB64url(salt)}$${bytesToB64url(hash)}`;
-}
-
-export async function verifyPassword(
- plainPassword: string,
- hashedPassword?: string | null,
-): Promise<boolean> {
- if (!hashedPassword) return false;
- try {
- const [scheme, itersStr, saltStr, hashStr] = hashedPassword.split("$");
- if (scheme !== "pbkdf2") return false;
- const iterations = Number(itersStr);
- const salt = b64urlToBytes(saltStr);
- const expected = b64urlToBytes(hashStr);
- const actual = await pbkdf2(plainPassword, salt, iterations);
- return timingSafeEqual(actual, expected);
- } catch {
- return false;
- }
+/** 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)));
}
-/** True if a stored hash is in a format this module can verify. */
-export function isSupportedHash(hash: string): boolean {
- return hash.startsWith("pbkdf2$");
+/** 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));
}
// ---------------------------------------------------------------------------
diff --git a/src/system/services/email.ts b/src/system/services/email.ts
deleted file mode 100644
index 9540d2d..0000000
--- a/src/system/services/email.ts
+++ /dev/null
@@ -1,342 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Transactional email via Resend.
- *
- * Deliberately dependency-free — the `resend` npm package pulls in Node
- * built-ins that don't exist on Workers, and the REST API is a single POST.
- *
- * Sending never throws into a request handler: callers on the password-reset
- * path must not leak "this address exists" through an error response, so
- * failures are logged and reported as a boolean.
- */
-
-import { emailFrom, resendApiBase, resendApiKey } from "../config";
-
-function resendEndpoint(): string {
- return `${resendApiBase()}/emails`;
-}
-
-export interface SendEmailOptions {
- to: string;
- subject: string;
- html: string;
- text: string;
- /** Optional Resend idempotency key, prevents duplicate sends on retry. */
- idempotencyKey?: string;
-}
-
-interface ResendErrorBody {
- message?: string;
- name?: string;
-}
-
-/**
- * Send one email. Returns true on success, false on any failure.
- * Never throws.
- */
-export async function sendEmail(options: SendEmailOptions): Promise<boolean> {
- const apiKey = resendApiKey();
- if (!apiKey) {
- console.error("RESEND_API_KEY is not set — cannot send email");
- return false;
- }
-
- const headers: Record<string, string> = {
- Authorization: `Bearer ${apiKey}`,
- "Content-Type": "application/json",
- };
- if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
-
- try {
- const resp = await fetch(resendEndpoint(), {
- method: "POST",
- headers,
- body: JSON.stringify({
- from: emailFrom(),
- to: [options.to],
- subject: options.subject,
- html: options.html,
- text: options.text,
- }),
- });
-
- if (!resp.ok) {
- const body = (await resp.json().catch(() => null)) as ResendErrorBody | null;
- // Log the status and Resend's message, never the recipient address.
- console.error(
- `Resend send failed: ${resp.status} ${body?.name ?? ""} ${body?.message ?? ""}`.trim(),
- );
- return false;
- }
- return true;
- } catch (err) {
- console.error(`Resend request threw: ${String(err)}`);
- return false;
- }
-}
-
-// ---------------------------------------------------------------------------
-// Templates
-// ---------------------------------------------------------------------------
-
-function escapeHtml(s: string): string {
- return s
- .replace(/&/g, "&")
- .replace(/</g, "<")
- .replace(/>/g, ">")
- .replace(/"/g, """)
- .replace(/'/g, "'");
-}
-
-export interface PasswordResetEmail {
- displayName: string;
- resetUrl: string;
- ttlMinutes: number;
-}
-
-export function passwordResetTemplate({ displayName, resetUrl, ttlMinutes }: PasswordResetEmail): {
- subject: string;
- html: string;
- text: string;
-} {
- const name = escapeHtml(displayName);
- const url = escapeHtml(resetUrl);
-
- const text = [
- `Hi ${displayName},`,
- "",
- "Someone requested a password reset for your Doughmination System account.",
- "Open the link below to choose a new password:",
- "",
- resetUrl,
- "",
- `This link expires in ${ttlMinutes} minutes and can only be used once.`,
- "",
- "If you did not request this, you can ignore this email — your password",
- "will not change until the link above is used.",
- "",
- "— Doughmination System",
- ].join("\n");
-
- const html = `<!doctype html>
-<html lang="en">
-<body style="margin:0;padding:24px;background:#1c0f14;font-family:ui-sans-serif,system-ui,sans-serif;color:#f5dde6;">
- <div style="max-width:520px;margin:0 auto;background:#2b1620;border:1px solid #3d1f2c;border-radius:12px;padding:28px;">
- <h1 style="margin:0 0 16px;font-size:20px;color:#ff5c8a;">Reset your password</h1>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">Hi ${name},</p>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">
- Someone requested a password reset for your Doughmination System account.
- Use the button below to choose a new password.
- </p>
- <p style="margin:24px 0;text-align:center;">
- <a href="${url}" style="display:inline-block;background:#ff5c8a;color:#1c0f14;text-decoration:none;font-weight:600;padding:12px 28px;border-radius:8px;font-size:15px;">Choose a new password</a>
- </p>
- <p style="margin:0 0 14px;font-size:13px;line-height:1.6;color:#c9a8b9;">
- This link expires in ${ttlMinutes} minutes and can only be used once.
- </p>
- <p style="margin:0 0 14px;font-size:13px;line-height:1.6;color:#c9a8b9;">
- If you did not request this, you can ignore this email — your password will
- not change until the link above is used.
- </p>
- <p style="margin:20px 0 0;font-size:12px;line-height:1.6;color:#9a7489;word-break:break-all;">
- Button not working? Paste this into your browser:<br />${url}
- </p>
- </div>
-</body>
-</html>`;
-
- return { subject: "Reset your Doughmination System password", html, text };
-}
-
-export function verifyEmailTemplate({
- displayName,
- verifyUrl,
- ttlHours,
- isChange,
- deleteAfterHours,
-}: {
- displayName: string;
- verifyUrl: string;
- ttlHours: number;
- /** True when confirming a change of address rather than a new signup. */
- isChange: boolean;
- /** Unverified signups are removed after this long. Omitted for changes,
- * where nothing gets deleted. */
- deleteAfterHours?: number;
-}): { subject: string; html: string; text: string } {
- const safeName = escapeHtml(displayName);
- const safeUrl = escapeHtml(verifyUrl);
-
- const lead = isChange
- ? "Confirm this address to finish moving your Doughmination System account to it."
- : "Confirm your address to finish setting up your Doughmination System account.";
-
- const warning = isChange
- ? "Your account keeps using its current address until you confirm here."
- : deleteAfterHours
- ? `You won't be able to log in until you confirm, and unconfirmed accounts are removed after ${deleteAfterHours} hours.`
- : "You won't be able to log in until you confirm.";
-
- const text = [
- `Hi ${displayName},`,
- "",
- lead,
- "",
- verifyUrl,
- "",
- `This link expires in ${ttlHours} hours.`,
- warning,
- "",
- "If you didn't expect this email, you can ignore it.",
- "",
- "— Doughmination System",
- ].join("\n");
-
- const html = `<!doctype html>
-<html lang="en">
-<body style="margin:0;padding:24px;background:#1c0f14;font-family:ui-sans-serif,system-ui,sans-serif;color:#f5dde6;">
- <div style="max-width:520px;margin:0 auto;background:#2b1620;border:1px solid #3d1f2c;border-radius:12px;padding:28px;">
- <h1 style="margin:0 0 16px;font-size:20px;color:#ff5c8a;">${isChange ? "Confirm your new email" : "Confirm your email"}</h1>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">Hi ${safeName},</p>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">${escapeHtml(lead)}</p>
- <p style="margin:24px 0;text-align:center;">
- <a href="${safeUrl}" style="display:inline-block;background:#ff5c8a;color:#1c0f14;text-decoration:none;font-weight:600;padding:12px 28px;border-radius:8px;font-size:15px;">Confirm email address</a>
- </p>
- <p style="margin:0 0 14px;font-size:13px;line-height:1.6;color:#c9a8b9;">
- This link expires in ${ttlHours} hours. ${escapeHtml(warning)}
- </p>
- <p style="margin:0 0 14px;font-size:13px;line-height:1.6;color:#c9a8b9;">
- If you didn't expect this email, you can ignore it.
- </p>
- <p style="margin:20px 0 0;font-size:12px;line-height:1.6;color:#9a7489;word-break:break-all;">
- Button not working? Paste this into your browser:<br />${safeUrl}
- </p>
- </div>
-</body>
-</html>`;
-
- return {
- subject: isChange
- ? "Confirm your new Doughmination System email"
- : "Confirm your Doughmination System email",
- html,
- text,
- };
-}
-
-/**
- * Sent to the OLD address when an email change is requested, so that a
- * takeover attempt is visible to the real owner of the account.
- */
-export function emailChangeAlertTemplate({
- displayName,
- newEmailMasked,
-}: {
- displayName: string;
- newEmailMasked: string;
-}): { subject: string; html: string; text: string } {
- const safeName = escapeHtml(displayName);
- const safeMasked = escapeHtml(newEmailMasked);
-
- const text = [
- `Hi ${displayName},`,
- "",
- "Someone requested that the email address on your Doughmination System",
- `account be changed to ${newEmailMasked}.`,
- "",
- "The change does not take effect until that new address is confirmed.",
- "This address remains on the account until then.",
- "",
- "If this wasn't you, your password may be compromised. Change it now and",
- "contact @doughmination.",
- "",
- "— Doughmination System",
- ].join("\n");
-
- const html = `<!doctype html>
-<html lang="en">
-<body style="margin:0;padding:24px;background:#1c0f14;font-family:ui-sans-serif,system-ui,sans-serif;color:#f5dde6;">
- <div style="max-width:520px;margin:0 auto;background:#2b1620;border:1px solid #3d1f2c;border-radius:12px;padding:28px;">
- <h1 style="margin:0 0 16px;font-size:20px;color:#d9a441;">Email change requested</h1>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">Hi ${safeName},</p>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">
- Someone requested that the email address on your Doughmination System
- account be changed to <strong>${safeMasked}</strong>.
- </p>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">
- The change does not take effect until that new address is confirmed.
- This address remains on the account until then.
- </p>
- <div style="margin:20px 0;padding:14px;background:#1c0f14;border:1px solid #c22a3e;border-radius:8px;">
- <p style="margin:0;font-size:14px;line-height:1.6;color:#f5dde6;">
- <strong style="color:#c22a3e;">Wasn't you?</strong> Your password may be
- compromised. Change it now and contact @doughmination.
- </p>
- </div>
- </div>
-</body>
-</html>`;
-
- return { subject: "Email change requested on your Doughmination System account", html, text };
-}
-
-export function usernameReminderTemplate({
- username,
- displayName,
- loginUrl,
-}: {
- username: string;
- displayName: string;
- loginUrl: string;
-}): { subject: string; html: string; text: string } {
- const safeName = escapeHtml(displayName);
- const safeUsername = escapeHtml(username);
- const safeLogin = escapeHtml(loginUrl);
-
- const text = [
- `Hi ${displayName},`,
- "",
- "Someone asked us to remind you of the username attached to this",
- "email address on the Doughmination System.",
- "",
- `Your username is: ${username}`,
- "",
- `You can log in at ${loginUrl}`,
- "",
- "If you did not request this, you can ignore this email — nothing about",
- "your account has changed.",
- "",
- "— Doughmination System",
- ].join("\n");
-
- const html = `<!doctype html>
-<html lang="en">
-<body style="margin:0;padding:24px;background:#1c0f14;font-family:ui-sans-serif,system-ui,sans-serif;color:#f5dde6;">
- <div style="max-width:520px;margin:0 auto;background:#2b1620;border:1px solid #3d1f2c;border-radius:12px;padding:28px;">
- <h1 style="margin:0 0 16px;font-size:20px;color:#ff5c8a;">Your username</h1>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">Hi ${safeName},</p>
- <p style="margin:0 0 14px;font-size:15px;line-height:1.6;">
- Someone asked us to remind you of the username attached to this email
- address on the Doughmination System.
- </p>
- <p style="margin:20px 0;padding:14px;background:#1c0f14;border:1px solid #3d1f2c;border-radius:8px;text-align:center;font-size:18px;font-weight:600;color:#ff5c8a;">
- ${safeUsername}
- </p>
- <p style="margin:24px 0;text-align:center;">
- <a href="${safeLogin}" style="display:inline-block;background:#ff5c8a;color:#1c0f14;text-decoration:none;font-weight:600;padding:12px 28px;border-radius:8px;font-size:15px;">Go to login</a>
- </p>
- <p style="margin:0;font-size:13px;line-height:1.6;color:#c9a8b9;">
- If you did not request this, you can ignore this email — nothing about
- your account has changed.
- </p>
- </div>
-</body>
-</html>`;
-
- return { subject: "Your Doughmination System username", html, text };
-}
diff --git a/src/system/services/email_verification.ts b/src/system/services/email_verification.ts
deleted file mode 100644
index 98105bb..0000000
--- a/src/system/services/email_verification.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Email verification and "correction" tokens.
- *
- * Two token kinds live here:
- *
- * - VERIFICATION — emailed to an address to prove the user controls it.
- * Carries the address being proven, so a change that lands in
- * `pending_email` can be applied on confirmation.
- *
- * - CORRECTION — handed to the client that just created an account, so a
- * mistyped address can be fixed without a password. This is the only thing
- * authorising that endpoint, so it is scoped to one account, expires
- * quickly, and is refused once the account is verified.
- *
- * As with password resets, only a SHA-256 digest of each token is persisted;
- * the raw value exists in the email (or the signup response) and nowhere else.
- */
-
-import { rt } from "../runtime";
-
-const VERIFY_KEY = "email_verifications";
-const CORRECTION_KEY = "email_corrections";
-
-/** A verification link should outlive a night's sleep. */
-export const VERIFICATION_TTL_HOURS = 24;
-/** The correction token only needs to survive the signup sitting. */
-export const CORRECTION_TTL_HOURS = 2;
-
-export type VerificationPurpose = "signup" | "change";
-
-interface VerificationRecord {
- user_id: string;
- /** The address this token proves. May differ from the user's current email
- * when it's a pending change. */
- email: string;
- purpose: VerificationPurpose;
- expires_at: number;
- created_at: number;
-}
-
-interface CorrectionRecord {
- user_id: string;
- expires_at: number;
- created_at: number;
-}
-
-const enc = new TextEncoder();
-
-function bytesToHex(bytes: Uint8Array): string {
- let out = "";
- for (const b of bytes) out += b.toString(16).padStart(2, "0");
- return out;
-}
-
-async function digestToken(token: string): Promise<string> {
- const buf = await crypto.subtle.digest("SHA-256", enc.encode(token));
- return bytesToHex(new Uint8Array(buf));
-}
-
-function newToken(): string {
- return bytesToHex(crypto.getRandomValues(new Uint8Array(32)));
-}
-
-function pruneExpired<T extends { expires_at: number }>(
- table: Record<string, T>,
- now: number,
-): Record<string, T> {
- const out: Record<string, T> = {};
- for (const [digest, record] of Object.entries(table)) {
- if (record.expires_at > now) out[digest] = record;
- }
- return out;
-}
-
-// ---------------------------------------------------------------------------
-// Verification tokens
-// ---------------------------------------------------------------------------
-
-/**
- * Issue a verification token for `email`, revoking any earlier one for the
- * same user so an old link can't resurrect a superseded address.
- */
-export async function createVerificationToken(
- userId: string,
- email: string,
- purpose: VerificationPurpose,
-): Promise<string> {
- const now = Date.now();
- const raw = newToken();
- const digest = await digestToken(raw);
-
- const table = pruneExpired(
- await rt().store.get<Record<string, VerificationRecord>>(VERIFY_KEY, {}),
- now,
- );
-
- for (const [existing, record] of Object.entries(table)) {
- if (record.user_id === userId) delete table[existing];
- }
-
- table[digest] = {
- user_id: userId,
- email,
- purpose,
- created_at: now,
- expires_at: now + VERIFICATION_TTL_HOURS * 60 * 60 * 1000,
- };
-
- await rt().store.put(VERIFY_KEY, table);
- return raw;
-}
-
-/** Spend a verification token. Returns its payload, or null if unknown/expired. */
-export async function consumeVerificationToken(
- token: string,
-): Promise<{ userId: string; email: string; purpose: VerificationPurpose } | null> {
- const now = Date.now();
- const digest = await digestToken(token);
- const table = pruneExpired(
- await rt().store.get<Record<string, VerificationRecord>>(VERIFY_KEY, {}),
- now,
- );
-
- const record = table[digest];
- if (!record) {
- await rt().store.put(VERIFY_KEY, table);
- return null;
- }
-
- delete table[digest];
- await rt().store.put(VERIFY_KEY, table);
-
- if (record.expires_at <= now) return null;
- return { userId: record.user_id, email: record.email, purpose: record.purpose };
-}
-
-export async function revokeVerificationTokensForUser(userId: string): Promise<void> {
- const table = pruneExpired(
- await rt().store.get<Record<string, VerificationRecord>>(VERIFY_KEY, {}),
- Date.now(),
- );
- let changed = false;
- for (const [digest, record] of Object.entries(table)) {
- if (record.user_id === userId) {
- delete table[digest];
- changed = true;
- }
- }
- if (changed) await rt().store.put(VERIFY_KEY, table);
-}
-
-// ---------------------------------------------------------------------------
-// Correction tokens
-// ---------------------------------------------------------------------------
-
-/** Issue the token that lets a freshly-signed-up client fix its address. */
-export async function createCorrectionToken(userId: string): Promise<string> {
- const now = Date.now();
- const raw = newToken();
- const digest = await digestToken(raw);
-
- const table = pruneExpired(
- await rt().store.get<Record<string, CorrectionRecord>>(CORRECTION_KEY, {}),
- now,
- );
-
- for (const [existing, record] of Object.entries(table)) {
- if (record.user_id === userId) delete table[existing];
- }
-
- table[digest] = {
- user_id: userId,
- created_at: now,
- expires_at: now + CORRECTION_TTL_HOURS * 60 * 60 * 1000,
- };
-
- await rt().store.put(CORRECTION_KEY, table);
- return raw;
-}
-
-/**
- * Resolve a correction token to its user WITHOUT spending it — correcting an
- * address twice (two typos) has to keep working within the window.
- */
-export async function peekCorrectionToken(token: string): Promise<string | null> {
- const now = Date.now();
- const digest = await digestToken(token);
- const table = await rt().store.get<Record<string, CorrectionRecord>>(CORRECTION_KEY, {});
- const record = table[digest];
- if (!record || record.expires_at <= now) return null;
- return record.user_id;
-}
-
-/** Drop a user's correction token — called once they verify. */
-export async function revokeCorrectionTokensForUser(userId: string): Promise<void> {
- const table = pruneExpired(
- await rt().store.get<Record<string, CorrectionRecord>>(CORRECTION_KEY, {}),
- Date.now(),
- );
- let changed = false;
- for (const [digest, record] of Object.entries(table)) {
- if (record.user_id === userId) {
- delete table[digest];
- changed = true;
- }
- }
- if (changed) await rt().store.put(CORRECTION_KEY, table);
-}
diff --git a/src/system/services/oidc.ts b/src/system/services/oidc.ts
new file mode 100644
index 0000000..603d90c
--- /dev/null
+++ b/src/system/services/oidc.ts
@@ -0,0 +1,230 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * PocketID / 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.
+ *
+ * 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.
+ */
+
+import {
+ pocketIdIssuer,
+ pocketIdClientId,
+ pocketIdClientSecret,
+ pocketIdRedirectUri,
+ pocketIdScopes,
+ 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 {
+ authorization_endpoint: string;
+ token_endpoint: string;
+ userinfo_endpoint: string;
+ end_session_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;
+ /** preferred_username claim; the account username we match/create on. */
+ preferredUsername: string;
+ email: string | null;
+ displayName: 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)");
+ }
+}
+
+/** Fetch (and cache) the issuer's OpenID configuration. */
+export async function discover(): Promise<OidcDiscovery> {
+ const issuer = pocketIdIssuer();
+ 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 PocketID: ${String(err)}`);
+ }
+ if (!res.ok) {
+ throw new HttpError(502, `PocketID 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");
+ }
+ discoveryCache = { issuer, doc, fetchedAt: now };
+ return doc;
+}
+
+interface StoredState {
+ verifier: string;
+ from: string;
+ createdAt: number;
+}
+
+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.
+ */
+export async function beginLogin(from: 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(),
+ } satisfies StoredState);
+
+ 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("state", state);
+ authUrl.searchParams.set("code_challenge", challenge);
+ authUrl.searchParams.set("code_challenge_method", "S256");
+ return authUrl.toString();
+}
+
+export interface CallbackResult {
+ identity: OidcIdentity;
+ /** The original app path to return the user to. */
+ from: string;
+}
+
+/**
+ * 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> {
+ assertConfigured();
+
+ const key = stateKey(state);
+ const stored = await rt().store.get<StoredState | null>(key, null);
+ // Consume immediately so a replayed callback can't reuse it.
+ await rt().store.delete(key);
+
+ 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();
+
+ // ---- 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;
+ try {
+ tokenRes = 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, `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());
+ }
+
+ const tokens = (await tokenRes.json()) as { access_token?: string };
+ if (!tokens.access_token) {
+ throw new HttpError(502, "PocketID 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" },
+ });
+ } catch (err) {
+ throw new HttpError(502, `PocketID userinfo request failed: ${String(err)}`);
+ }
+ if (!infoRes.ok) {
+ throw new HttpError(502, `PocketID 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");
+
+ 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, preferredUsername, email, displayName },
+ from: stored.from || "/",
+ };
+}
diff --git a/src/system/services/password_reset.ts b/src/system/services/password_reset.ts
deleted file mode 100644
index 1189638..0000000
--- a/src/system/services/password_reset.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Password-reset tokens.
- *
- * Policy (see PASSWORD_RESET_TTL_MINUTES in ../config):
- * - valid for 15 minutes
- * - single use — consumed the moment a reset succeeds
- * - one active token per user — issuing a new one revokes the previous
- *
- * The raw token only ever exists in the email. What's persisted is a SHA-256
- * digest of it, so read access to the DO store does not let you take over an
- * account. Lookup is by digest, which is why the store is keyed on it.
- */
-
-import { PASSWORD_RESET_TTL_MINUTES } from "../config";
-import { rt } from "../runtime";
-
-/** digest -> record */
-const RESET_KEY = "password_resets";
-
-interface ResetRecord {
- user_id: string;
- /** epoch ms */
- expires_at: number;
- created_at: number;
-}
-
-type ResetTable = Record<string, ResetRecord>;
-
-const enc = new TextEncoder();
-
-function bytesToHex(bytes: Uint8Array): string {
- let out = "";
- for (const b of bytes) out += b.toString(16).padStart(2, "0");
- return out;
-}
-
-/** SHA-256 hex digest. Tokens are high-entropy random, so a plain digest is
- * sufficient here — no salt/stretching needed as there is nothing to guess. */
-async function digestToken(token: string): Promise<string> {
- const buf = await crypto.subtle.digest("SHA-256", enc.encode(token));
- return bytesToHex(new Uint8Array(buf));
-}
-
-async function readTable(): Promise<ResetTable> {
- return rt().store.get<ResetTable>(RESET_KEY, {});
-}
-
-async function writeTable(table: ResetTable): Promise<void> {
- await rt().store.put(RESET_KEY, table);
-}
-
-/** Drop expired rows. Called on every read path so the table self-cleans. */
-function pruneExpired(table: ResetTable, now: number): ResetTable {
- const out: ResetTable = {};
- for (const [digest, record] of Object.entries(table)) {
- if (record.expires_at > now) out[digest] = record;
- }
- return out;
-}
-
-/**
- * Issue a reset token for a user, revoking any token they already had.
- * Returns the RAW token — the only time it exists in plaintext. Put it in the
- * email and drop it.
- */
-export async function createResetToken(userId: string): Promise<string> {
- const now = Date.now();
- const raw = bytesToHex(crypto.getRandomValues(new Uint8Array(32)));
- const digest = await digestToken(raw);
-
- const table = pruneExpired(await readTable(), now);
-
- // One active token per user: drop any existing rows for them first.
- for (const [existingDigest, record] of Object.entries(table)) {
- if (record.user_id === userId) delete table[existingDigest];
- }
-
- table[digest] = {
- user_id: userId,
- created_at: now,
- expires_at: now + PASSWORD_RESET_TTL_MINUTES * 60 * 1000,
- };
-
- await writeTable(table);
- return raw;
-}
-
-/**
- * Look up a token without consuming it. Returns the user id, or null when the
- * token is unknown or expired. Use for a "is this link still good?" check
- * before showing the form.
- */
-export async function peekResetToken(token: string): Promise<string | null> {
- const now = Date.now();
- const digest = await digestToken(token);
- const table = await readTable();
- const record = table[digest];
- if (!record || record.expires_at <= now) return null;
- return record.user_id;
-}
-
-/**
- * Consume a token. Returns the user id on success, null if unknown or
- * expired. The row is deleted before the caller changes the password, so a
- * token cannot be replayed even if two requests race.
- */
-export async function consumeResetToken(token: string): Promise<string | null> {
- const now = Date.now();
- const digest = await digestToken(token);
- const table = pruneExpired(await readTable(), now);
-
- const record = table[digest];
- if (!record) {
- // Still persist the prune so expired rows don't accumulate.
- await writeTable(table);
- return null;
- }
-
- delete table[digest];
- await writeTable(table);
-
- if (record.expires_at <= now) return null;
- return record.user_id;
-}
-
-/** Revoke every outstanding token for a user (e.g. after a password change). */
-export async function revokeResetTokensForUser(userId: string): Promise<void> {
- const table = pruneExpired(await readTable(), Date.now());
- let changed = false;
- for (const [digest, record] of Object.entries(table)) {
- if (record.user_id === userId) {
- delete table[digest];
- changed = true;
- }
- }
- if (changed) await writeTable(table);
-}
diff --git a/src/system/services/users.ts b/src/system/services/users.ts
index 7596174..4f59817 100644
--- a/src/system/services/users.ts
+++ b/src/system/services/users.ts
@@ -5,14 +5,17 @@
*/
/**
- * User management service. Same semantics/owner-protection as the old
- * backend; storage is the DO blob store (key "users") instead of users.json,
- * and hashing is PBKDF2 via ../security.
+ * 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
+ * protections are unchanged. Storage is the DO blob store (key "users").
*/
import type { User, UserCreate, UserUpdate } from "../models";
-import { adminUsername, adminPassword, adminDisplayName, adminEmail } from "../config";
-import { hashPassword, verifyPassword, isSupportedHash } from "../security";
+import { adminUsername, adminDisplayName, adminEmail } from "../config";
import { rt } from "../runtime";
const USERS_KEY = "users";
@@ -37,8 +40,8 @@ export async function getUsers(): Promise<User[]> {
userDict.is_admin = true;
userDict.is_pet = true;
// The owner account predates the email field. Backfill it from
- // ADMIN_EMAIL so password recovery works without a manual edit; an
- // address already set by hand always wins.
+ // 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;
@@ -54,7 +57,6 @@ export async function saveUsers(users: User[]): Promise<void> {
user.is_owner = true;
user.is_admin = true;
user.is_pet = true;
- // Persist the ADMIN_EMAIL backfill so it survives the env var going away.
if (!user.email) {
const seeded = adminEmail();
if (seeded) user.email = seeded;
@@ -74,20 +76,14 @@ export async function getUserById(userId: string): Promise<User | null> {
return users.find((u) => u.id === userId) ?? null;
}
-export function normalizeEmail(email: string): string {
- return email.trim().toLowerCase();
+export async function getUserBySub(sub: string): Promise<User | null> {
+ if (!sub) return null;
+ const users = await getUsers();
+ return users.find((u) => u.pocket_id && u.pocket_id === sub) ?? null;
}
-/**
- * Whether a user's address counts as verified.
- *
- * MIGRATION SAFETY — the default matters. Accounts created before
- * verification existed have no `email_verified` field, and reading absent as
- * TRUE is what grandfathers them: they keep logging in, and the cleanup sweep
- * never sees them as candidates. Only an explicit `false` means unverified.
- */
-export function isEmailVerified(user: User): boolean {
- return user.email_verified !== false;
+export function normalizeEmail(email: string): string {
+ return email.trim().toLowerCase();
}
export async function getUserByEmail(email: string): Promise<User | null> {
@@ -97,38 +93,19 @@ export async function getUserByEmail(email: string): Promise<User | null> {
return users.find((u) => u.email && normalizeEmail(u.email) === target) ?? null;
}
-/**
- * Throw if `email` is taken. Pending (unverified) changes count as taken too,
- * so two accounts can't both be mid-flight onto the same address and have the
- * second confirmation collide.
- */
+/** 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) ||
- (u.pending_email && normalizeEmail(u.pending_email) === target)),
+ (u) => u.id !== exceptUserId && u.email && normalizeEmail(u.email) === target,
);
if (clash) throw new Error("Email address is already in use");
}
-export interface CreateUserOptions {
- /**
- * Whether the address should be treated as already proven.
- *
- * Public signup passes false — the user must confirm before logging in.
- * Owner-created accounts pass true, since the owner is assigning the
- * address deliberately and shouldn't have to chase a confirmation.
- */
- emailVerified?: boolean;
-}
-
export async function createUser(
userCreate: UserCreate,
requestingUser?: User | null,
- options: CreateUserOptions = {},
): Promise<User> {
const users = await getUsers();
@@ -159,19 +136,13 @@ export async function createUser(
const email = userCreate.email ? normalizeEmail(userCreate.email) : null;
if (email) await assertEmailAvailable(email);
- // The owner is never gated on confirming their own address.
- const emailVerified = isOwner ? true : options.emailVerified ?? true;
-
const newUser: User = {
id: crypto.randomUUID(),
username: userCreate.username,
- password_hash: await hashPassword(userCreate.password),
+ pocket_id: userCreate.pocket_id ?? null,
display_name: userCreate.display_name ?? null,
email,
- email_verified: emailVerified,
- email_verified_at: emailVerified ? new Date().toISOString() : null,
created_at: new Date().toISOString(),
- pending_email: null,
is_admin: isAdmin,
is_owner: isOwner,
is_pet: isPet,
@@ -183,6 +154,61 @@ export async function createUser(
return newUser;
}
+/**
+ * Resolve a PocketID 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.
+ */
+export async function findOrCreateFromPocketId(claims: {
+ sub: string;
+ username: string;
+ email?: string | null;
+ displayName?: string | null;
+}): Promise<User> {
+ const users = await getUsers();
+
+ 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) {
+ const index = users.findIndex((u) => u.id === existing.id);
+ let changed = false;
+
+ if (existing.pocket_id !== claims.sub) {
+ existing.pocket_id = claims.sub;
+ 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 PocketID user → provision a plain account.
+ return createUser({
+ username: claims.username,
+ pocket_id: claims.sub,
+ email: claims.email ?? null,
+ display_name: claims.displayName ?? null,
+ is_admin: false,
+ is_pet: false,
+ });
+}
+
export async function updateUser(
userId: string,
userUpdate: UserUpdate,
@@ -213,68 +239,22 @@ export async function updateUser(
throw new Error("Only the owner can change user roles");
}
- // ---- Email ------------------------------------------------------------
- //
- // Who may change it:
- // - the account's own user (requires current_password)
- // - the owner, for anybody
- // - NOT a plain admin acting on someone else — email is the recovery
- // factor, so letting an admin repoint it would be an account takeover
- // primitive.
- //
- // A self-service change does NOT take effect immediately: the new address
- // goes to `pending_email` and only replaces `email` once confirmed, so a
- // typo can never lock someone out of their own account. The owner setting an
- // address is applied directly and marked verified.
+ // ---- 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.
let email = user.email ?? null;
- let pendingEmail = user.pending_email ?? null;
- let emailVerified = isEmailVerified(user);
- let emailVerifiedAt = user.email_verified_at ?? null;
- /** Set when the caller must be sent a confirmation link for a new address. */
- let pendingEmailToConfirm: string | null = null;
-
if (userUpdate.email !== undefined) {
const requestedEmail = userUpdate.email ? normalizeEmail(userUpdate.email) : null;
const isSelf = requestingUser?.id === user.id;
- const isOwnerActing = !!requestingUser?.is_owner;
+ const isAdminActing = !!requestingUser?.is_admin;
if (requestedEmail !== email) {
- if (!isSelf && !isOwnerActing) {
+ if (!isSelf && !isAdminActing) {
throw new Error("You can only change your own email address");
}
-
if (requestedEmail) await assertEmailAvailable(requestedEmail, user.id);
-
- if (isOwnerActing && !isSelf) {
- // Owner assigning an address on someone's behalf: applied outright.
- email = requestedEmail;
- pendingEmail = null;
- emailVerified = true;
- emailVerifiedAt = new Date().toISOString();
- } else {
- // Changing your own address — prove you're still you first.
- if (!userUpdate.current_password) {
- throw new Error("Enter your current password to change your email address");
- }
- if (!(await verifyPassword(userUpdate.current_password, user.password_hash))) {
- throw new Error("Current password is incorrect");
- }
-
- if (!requestedEmail) throw new Error("Email address cannot be empty");
-
- // Held aside until confirmed; `email` deliberately stays put.
- pendingEmail = requestedEmail;
- pendingEmailToConfirm = requestedEmail;
- }
- }
- }
-
- let passwordHash = user.password_hash;
- if (userUpdate.current_password && userUpdate.new_password) {
- if (!(await verifyPassword(userUpdate.current_password, user.password_hash))) {
- throw new Error("Current password is incorrect");
+ email = requestedEmail;
}
- passwordHash = await hashPassword(userUpdate.new_password);
}
const newIsOwner = isOwnerUsername(user.username);
@@ -284,25 +264,17 @@ export async function updateUser(
const updatedUser: User = {
id: user.id,
username: user.username,
- password_hash: passwordHash,
+ pocket_id: user.pocket_id ?? null,
// `undefined` = field omitted, keep current value; explicit `null` clears it.
display_name: userUpdate.display_name !== undefined ? userUpdate.display_name : user.display_name,
email,
- email_verified: emailVerified,
- email_verified_at: emailVerifiedAt,
created_at: user.created_at ?? null,
- pending_email: pendingEmail,
is_admin: newIsAdmin,
is_owner: newIsOwner,
is_pet: newIsPet,
avatar_url: userUpdate.avatar_url !== undefined ? userUpdate.avatar_url : user.avatar_url ?? null,
};
- // Signals to the route that a confirmation link must go out. Compared
- // against the previous value rather than returned separately, so the
- // function signature stays as it was.
- void pendingEmailToConfirm;
-
users[index] = updatedUser;
await saveUsers(users);
return updatedUser;
@@ -330,167 +302,35 @@ export async function deleteUser(userId: string, requestingUser?: User | null):
return false;
}
-/**
- * Mark an address as proven.
- *
- * `email` is the address the token was issued for. If it matches the user's
- * `pending_email`, the change is applied now; if it matches their current
- * address, this is a signup confirmation. A token for anything else is stale
- * (the address moved on since it was issued) and is refused.
- */
-export async function applyEmailVerification(
- userId: string,
- email: string,
-): Promise<User | null> {
- const users = await getUsers();
- const index = users.findIndex((u) => u.id === userId);
- if (index === -1) return null;
-
- const user = users[index];
- const target = normalizeEmail(email);
- const current = user.email ? normalizeEmail(user.email) : null;
- const pending = user.pending_email ? normalizeEmail(user.pending_email) : null;
-
- if (target !== current && target !== pending) return null;
-
- users[index] = {
- ...user,
- email: target,
- pending_email: null,
- email_verified: true,
- email_verified_at: new Date().toISOString(),
- };
-
- await saveUsers(users);
- return users[index];
-}
-
-/**
- * Replace the address on an account that has not been verified yet, without a
- * password. Callers MUST have already validated a correction token — see
- * services/email_verification.ts. Refuses once the account is verified.
- */
-export async function correctUnverifiedEmail(
- userId: string,
- email: string,
-): Promise<User | null> {
- const users = await getUsers();
- const index = users.findIndex((u) => u.id === userId);
- if (index === -1) return null;
-
- const user = users[index];
- if (isEmailVerified(user)) {
- throw new Error("This account is already verified. Change the address from your profile.");
- }
-
- const target = normalizeEmail(email);
- await assertEmailAvailable(target, user.id);
-
- users[index] = { ...user, email: target, pending_email: null, email_verified: false };
- await saveUsers(users);
- return users[index];
-}
-
-/**
- * Delete accounts that signed up but never confirmed their address.
- *
- * Guards, in order of how badly each would hurt if missed:
- * 1. `email_verified === false` — anything else, including legacy accounts
- * with the field absent, is verified per isEmailVerified() and is skipped.
- * 2. `created_at` must be present and parseable. Legacy rows have no
- * timestamp, so this is a second, independent reason they survive.
- * 3. Never the owner, whatever its state.
- */
-export async function deleteUnverifiedUsers(maxAgeHours: number): Promise<string[]> {
- const users = await getUsers();
- const cutoff = Date.now() - maxAgeHours * 60 * 60 * 1000;
-
- const doomed = users.filter((u) => {
- if (u.is_owner || isOwnerUsername(u.username)) return false;
- if (u.email_verified !== false) return false;
- if (!u.created_at) return false;
-
- const created = Date.parse(u.created_at);
- if (Number.isNaN(created)) return false;
-
- return created < cutoff;
- });
-
- if (doomed.length === 0) return [];
-
- const doomedIds = new Set(doomed.map((u) => u.id));
- await saveUsers(users.filter((u) => !doomedIds.has(u.id)));
-
- return doomed.map((u) => u.username);
-}
-
-/**
- * Overwrite a user's password without knowing the current one.
- *
- * Only for flows that have already proven ownership another way — the
- * password-reset token path. Do NOT expose this to a plain authenticated
- * request; that's what updateUser's current_password check is for.
- */
-export async function setPassword(userId: string, newPassword: string): Promise<boolean> {
- const users = await getUsers();
- const index = users.findIndex((u) => u.id === userId);
- if (index === -1) return false;
-
- users[index] = { ...users[index], password_hash: await hashPassword(newPassword) };
- await saveUsers(users);
- return true;
-}
-
-export async function verifyUser(username: string, password: string): Promise<User | null> {
- const user = await getUserByUsername(username);
- if (user && (await verifyPassword(password, user.password_hash))) {
- return user;
- }
- return null;
-}
-
/**
* Seed the owner account from ADMIN_* env vars if no users exist yet.
- * Runs lazily on first request (there is no startup phase on a Worker).
- * ADMIN_PASSWORD may be a plaintext password or a pre-computed pbkdf2 hash.
+ *
+ * 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.
*/
export async function initializeAdminUser(): Promise<void> {
const users = await getUsers();
if (users.length > 0) return;
const username = adminUsername();
- let passwordOrHash = adminPassword();
const displayName = adminDisplayName();
- if (!passwordOrHash) {
- console.warn("No ADMIN_PASSWORD set. Using default password 'admin'.");
- passwordOrHash = "admin";
- }
-
try {
- if (isSupportedHash(passwordOrHash)) {
- const newUser: User = {
- id: crypto.randomUUID(),
- username,
- password_hash: passwordOrHash,
- display_name: displayName,
- email: adminEmail() ?? null,
- is_admin: true,
- is_owner: true,
- is_pet: false,
- avatar_url: null,
- };
- await saveUsers([...users, newUser]);
- } else {
- await createUser({
- username,
- password: passwordOrHash,
- email: adminEmail() ?? null,
- display_name: displayName,
- is_admin: true,
- is_pet: false,
- });
- }
+ 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/system/types.ts b/src/system/types.ts
index 86afd80..31d7066 100644
--- a/src/system/types.ts
+++ b/src/system/types.ts
@@ -28,19 +28,35 @@ export interface SystemEnv {
CACHE_TTL?: string;
// ---- Auth --------------------------------------------------------------
- /** HMAC secret for signing JWTs. REQUIRED in production. */
+ /** HMAC secret for signing the JWT the API issues after a PocketID login.
+ * REQUIRED in production. */
JWT_SECRET?: string;
- /** Cloudflare Turnstile secret (login/signup captcha). */
+ /** Cloudflare Turnstile secret (public guestbook captcha). */
TURNSTILE_SECRET?: string;
/** 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;
+ /** 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;
+ /** 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;
+
// ---- Initial owner seed (only used when no users exist yet) ------------
ADMIN_USERNAME?: string;
- ADMIN_PASSWORD?: string;
ADMIN_DISPLAY_NAME?: string;
- /** Owner's email address, used for password recovery. Backfilled onto the
- * owner account on read if it doesn't have one yet. */
+ /** Owner's contact email. Backfilled onto the owner account on read if it
+ * doesn't have one yet. */
ADMIN_EMAIL?: string;
// ---- Manual API keys (replaces generate-on-first-run) ------------------
@@ -49,21 +65,6 @@ export interface SystemEnv {
/** Comma-separated device battery-report keys (X-Battery-Key header). */
BATTERY_API_KEYS?: string;
- // ---- Email (Resend) ----------------------------------------------------
- /** Resend API key. Without it, password-reset emails cannot be sent. */
- RESEND_API_KEY?: string;
- /** Override the Resend API base (self-hosted relay / local testing). */
- RESEND_API_BASE?: string;
- /** From address for transactional mail. Must be on a Resend-verified
- * domain. Defaults to [email protected]. */
- EMAIL_FROM?: string;
- /** Where password-reset links point. Defaults to FRONTEND_URL, then to the
- * public site. */
- PASSWORD_RESET_URL?: string;
- /** Where email-confirmation links point. Defaults to
- * FRONTEND_URL + /user/verify-email. */
- EMAIL_VERIFY_URL?: string;
-
// ---- Misc --------------------------------------------------------------
/** Public base URL, used in a few absolute links. */
BASE_URL?: string;
diff --git a/wrangler.jsonc b/wrangler.jsonc
index ad41b01..37a1bf7 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -71,28 +71,32 @@
// ---- Doughmination system API (/v2/plural, /v2/battery, ...) --------
// Non-secret config. Secrets (JWT_SECRET, SYSTEM_TOKEN, TURNSTILE_SECRET,
- // ADMIN_PASSWORD, DOUGH_BOT_TOKEN, BATTERY_API_KEYS) go in .dev.vars for
- // local dev and `wrangler secret put <NAME>` in production.
+ // POCKETID_CLIENT_SECRET, DOUGH_BOT_TOKEN, BATTERY_API_KEYS) go in
+ // .dev.vars for local dev and `wrangler secret put <NAME>` in production.
"CACHE_TTL": "30",
"ADMIN_USERNAME": "clove",
"ADMIN_DISPLAY_NAME": "Administrator",
- // Owner's recovery address. Backfilled onto the owner account on read,
+ // Owner's contact address. Backfilled onto the owner account on read,
// so the pre-existing account gets one without a manual edit. Public
// address, hence a var rather than a secret.
"ADMIN_EMAIL": "[email protected]",
"BASE_URL": "https://doughmination.uk",
"CORS_ORIGINS": "",
- // Transactional email (password reset), sent via Resend. The API key
- // itself is a secret — `wrangler secret put RESEND_API_KEY`.
- // EMAIL_FROM must be on a Resend-verified domain.
- "EMAIL_FROM": "Doughmination System <[email protected]>",
- // Where the reset link in the email points. The frontend lives on
- // doughmination.co.uk; this API is doughmination.uk — so these must
- // NOT inherit BASE_URL.
+ // The frontend lives on doughmination.co.uk; this API is
+ // doughmination.uk — so this must NOT inherit BASE_URL.
"FRONTEND_URL": "https://doughmination.co.uk",
- "PASSWORD_RESET_URL": "https://doughmination.co.uk/user/reset-password",
- "EMAIL_VERIFY_URL": "https://doughmination.co.uk/user/verify-email",
+
+ // ---- PocketID (OIDC) — the only login method -----------------------
+ // POCKETID_CLIENT_ID / POCKETID_CLIENT_SECRET are secrets:
+ // wrangler secret put POCKETID_CLIENT_ID
+ // wrangler secret put POCKETID_CLIENT_SECRET
+ // The issuer must serve /.well-known/openid-configuration. The redirect
+ // URI must be registered in PocketID for this client.
+ "POCKETID_ISSUER": "https://doughmination.xyz",
+ "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",
// Hypixel API policy: the keyed /v2/minecraft/hypixel endpoint only
// serves our OWN accounts, never arbitrary players (no proxying the