Dough Git

commit

aaa

commit
682690b818ec96a95ace350bbaed4a0533387d52
author
Clove Twilight <[email protected]>
date
2026-07-21 16:53

diff --git a/.dev.vars.example b/.dev.vars.example
index e9ea8d6..f704f90 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -43,6 +43,18 @@ ADMIN_PASSWORD=
 # 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/apidata.ts b/src/apidata.ts
index 8c21f4b..dcfe519 100644
--- a/src/apidata.ts
+++ b/src/apidata.ts
@@ -78,15 +78,23 @@ export const GROUPS: GroupDef[] = [
     ],
   },
   {
-    id: "plural-auth", name: "Plural — accounts & auth", blurb: "Login, signup, and the current user.",
+    id: "plural-auth", name: "Plural — accounts & auth", blurb: "Login, signup, password reset, and the current user.",
     endpoints: [
       { m: "POST", path: "/plural/login", auth: "public",
         desc: "Log in with your username and password (plus a Turnstile captcha token). Returns an access token to use on protected endpoints.",
         example: 'POST body: { "username": "admin", "password": "…", "turnstile_token": "…" }  →  { "access_token": "…", "token_type": "bearer", "success": true }' },
       { m: "POST", path: "/plural/signup", auth: "public",
-        desc: "Create a non-admin account. Body { username, password (≥10 chars), display_name?, turnstile_token }." },
+        desc: "Create a non-admin account. Body { username, password (≥10 chars), email, display_name?, turnstile_token }. Email is required and must be unique — it is the only self-service password-recovery route." },
       { m: "GET", path: "/plural/users/check-username?username=", auth: "public",
         desc: "Check username availability. Returns { username, exists, available }." },
+      { m: "POST", path: "/plural/forgot-password", auth: "public",
+        desc: "Request a password-reset link. Body { email, turnstile_token }. Always returns the same message whether or not the address matches an account, so it cannot be used to enumerate users. Rate limited to one request per IP per minute.",
+        example: 'POST body: { "email": "[email protected]", "turnstile_token": "…" }  →  { "success": true, "message": "If an account exists for that email address, a reset link is on its way." }' },
+      { m: "GET", path: "/plural/reset-password/check?token=", auth: "public",
+        desc: "Check whether a reset token is still usable before rendering the form. Returns { valid }." },
+      { m: "POST", path: "/plural/reset-password", auth: "public",
+        desc: "Set a new password using a token from the reset email. Body { token, new_password (≥10 chars), turnstile_token }. Tokens last 15 minutes, are single-use, and requesting a new one revokes the previous.",
+        example: 'POST body: { "token": "…", "new_password": "…", "turnstile_token": "…" }  →  { "success": true, "message": "Your password has been reset. …" }' },
       { m: "GET", path: "/plural/user_info", auth: "auth",
         desc: "The current authenticated user (no password hash)." },
       { m: "GET", path: "/plural/auth/is_admin", auth: "auth", desc: "{ isAdmin } for the current user." },
diff --git a/src/system/app.ts b/src/system/app.ts
index 556467d..8de71dd 100644
--- a/src/system/app.ts
+++ b/src/system/app.ts
@@ -27,6 +27,7 @@ import { corsOrigins, isLocalhostOrigin } from "./config";
 import { initializeAdminUser } from "./services/users";
 
 import { authRoutes } from "./routes/auth";
+import { passwordResetRoutes } from "./routes/password_reset";
 import { systemRoutes } from "./routes/system";
 import { membersRoutes } from "./routes/members";
 import { frontingRoutes } from "./routes/fronting";
@@ -57,6 +58,7 @@ async function ensureSeeded(): Promise<void> {
 
 const pluralApp = new Hono<Env>();
 pluralApp.route("/", authRoutes);
+pluralApp.route("/", passwordResetRoutes);
 pluralApp.route("/", systemRoutes);
 pluralApp.route("/", membersRoutes);
 pluralApp.route("/", frontingRoutes);
diff --git a/src/system/config.ts b/src/system/config.ts
index 1d33f37..d521d43 100644
--- a/src/system/config.ts
+++ b/src/system/config.ts
@@ -57,10 +57,50 @@ 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;
+}
+
 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(/\/+$/, "");
+}
+
+// ---------------------------------------------------------------------------
+// Email (Resend)
+// ---------------------------------------------------------------------------
+
+export function resendApiKey(): string | undefined {
+  return rt().env.RESEND_API_KEY;
+}
+
+/** 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(/\/+$/, "");
+}
+
+export function emailFrom(): string {
+  return rt().env.EMAIL_FROM ?? "Doughmination System <[email protected]>";
+}
+
+/** Base URL of the password-reset page. The token is appended as ?token=. */
+export function passwordResetUrl(): string {
+  const configured = rt().env.PASSWORD_RESET_URL;
+  if (configured) return configured.replace(/\/+$/, "");
+  return `${frontendUrl()}/user/reset-password`;
+}
+
+/** How long a password-reset token stays valid. */
+export const PASSWORD_RESET_TTL_MINUTES = 15;
+
 /** Any localhost origin, on any port and either scheme — local dev servers
  *  (Vite :5173, Next :3000, wrangler :8787, …) are always allowed. */
 export function isLocalhostOrigin(origin: string): boolean {
diff --git a/src/system/models.ts b/src/system/models.ts
index 8b3bfbd..6e4c67d 100644
--- a/src/system/models.ts
+++ b/src/system/models.ts
@@ -16,11 +16,22 @@ import { z } from "zod";
 // USER MODELS
 // ============================================================================
 
+/** Emails are stored lowercased and trimmed so uniqueness checks are stable. */
+export const EmailSchema = z
+  .string()
+  .trim()
+  .toLowerCase()
+  .email("Must be a valid email address")
+  .max(254, "Email address is too long");
+
 export const UserSchema = z.object({
   id: z.string(),
   username: z.string(),
   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(),
   is_admin: z.boolean().default(false),
   is_owner: z.boolean().default(false),
   is_pet: z.boolean().default(false),
@@ -31,6 +42,7 @@ export type User = z.infer<typeof UserSchema>;
 export const UserCreateSchema = z.object({
   username: z.string(),
   password: z.string(),
+  email: EmailSchema.nullable().optional(),
   display_name: z.string().nullable().optional(),
   is_admin: z.boolean().default(false),
   is_pet: z.boolean().default(false),
@@ -41,6 +53,7 @@ export const UserResponseSchema = z.object({
   id: z.string(),
   username: z.string(),
   display_name: z.string().nullable().optional(),
+  email: z.string().nullable().optional(),
   is_admin: z.boolean().default(false),
   is_owner: z.boolean().default(false),
   is_pet: z.boolean().default(false),
@@ -53,6 +66,8 @@ export const UserUpdateSchema = z.object({
   current_password: z.string().nullable().optional(),
   new_password: z.string().nullable().optional(),
   avatar_url: z.string().nullable().optional(),
+  /** Owner-only. Rejected with 403 for anyone else — see services/users.ts. */
+  email: EmailSchema.nullable().optional(),
   is_admin: z.boolean().nullable().optional(),
   is_pet: z.boolean().nullable().optional(),
 });
@@ -65,6 +80,19 @@ export const LoginRequestSchema = z.object({
 });
 export type LoginRequest = z.infer<typeof LoginRequestSchema>;
 
+export const ForgotPasswordRequestSchema = z.object({
+  email: EmailSchema,
+  turnstile_token: z.string().min(1, "Security verification is required"),
+});
+export type ForgotPasswordRequest = z.infer<typeof ForgotPasswordRequestSchema>;
+
+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. */
 export function toUserResponse(user: User): UserResponse {
   const { password_hash: _drop, ...rest } = user;
diff --git a/src/system/routes/auth.ts b/src/system/routes/auth.ts
index 92269b7..c950867 100644
--- a/src/system/routes/auth.ts
+++ b/src/system/routes/auth.ts
@@ -8,7 +8,7 @@ import { Hono } from "hono";
 import type { Context } from "hono";
 
 import type { Env } from "../hono";
-import { UserResponseSchema, LoginRequestSchema } from "../models";
+import { UserResponseSchema, LoginRequestSchema, EmailSchema } from "../models";
 import type { User } from "../models";
 import { verifyUser, createUser, getUsers } from "../services/users";
 import { createAccessToken, verifyTurnstileToken } from "../security";
@@ -22,6 +22,7 @@ function toUserResponseJson(user: User) {
     id: user.id,
     username: user.username,
     display_name: user.display_name,
+    email: user.email ?? null,
     is_admin: user.is_admin,
     is_owner: user.is_owner,
     is_pet: user.is_pet,
@@ -86,6 +87,15 @@ authRoutes.post("/signup", async (c) => {
   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));
@@ -96,10 +106,13 @@ authRoutes.post("/signup", async (c) => {
   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, display_name: displayName, is_admin: false, is_pet: false },
+      { username, password, email, display_name: displayName, is_admin: false, is_pet: false },
       null,
     );
     return c.json({
diff --git a/src/system/routes/password_reset.ts b/src/system/routes/password_reset.ts
new file mode 100644
index 0000000..b7f89ea
--- /dev/null
+++ b/src/system/routes/password_reset.ts
@@ -0,0 +1,162 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * Password reset:
+ *
+ *   POST /v2/plural/forgot-password        request a reset link
+ *   GET  /v2/plural/reset-password/check   is this token still usable?
+ *   POST /v2/plural/reset-password         set a new password with a token
+ *
+ * Anti-enumeration: /forgot-password returns the same body whether or not the
+ * address maps to an account, whether or not that account has an email, and
+ * whether or not Resend actually accepted the message. The only distinguishing
+ * responses are validation (400) and rate limit (429), neither of which depends
+ * on account existence.
+ */
+
+import { Hono } from "hono";
+import type { Context } from "hono";
+
+import type { Env } from "../hono";
+import { ForgotPasswordRequestSchema, ResetPasswordRequestSchema } from "../models";
+import { PASSWORD_RESET_TTL_MINUTES, passwordResetUrl } from "../config";
+import { getUserByEmail, getUserById, setPassword } from "../services/users";
+import {
+  consumeResetToken,
+  createResetToken,
+  peekResetToken,
+  revokeResetTokensForUser,
+} from "../services/password_reset";
+import { passwordResetTemplate, sendEmail } from "../services/email";
+import { verifyTurnstileToken } from "../security";
+import { HttpError } from "../errors";
+import { rt } from "../runtime";
+
+export const passwordResetRoutes = new Hono<Env>();
+
+/** Same opaque answer for every outcome — see the module comment. */
+const GENERIC_FORGOT_RESPONSE = {
+  success: true,
+  message: "If an account exists for that email address, a reset link is on its way.",
+};
+
+const RL_PREFIX = "pwreset_rl:";
+/** Minimum seconds between reset requests from one IP. */
+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(ip: string | undefined): Promise<boolean> {
+  if (!ip) return true;
+  const key = RL_PREFIX + ip;
+  const last = await rt().store.get<number>(key, 0);
+  const now = Date.now();
+  if (last && now - last < RATE_LIMIT_SECONDS * 1000) return false;
+  await rt().store.put(key, now);
+  return true;
+}
+
+function firstIssueMessage(issues: Array<{ message: string }>, fallback: string): string {
+  return issues[0]?.message ?? fallback;
+}
+
+// ---------------------------------------------------------------------------
+// POST /forgot-password
+// ---------------------------------------------------------------------------
+
+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(clientIp(c)))) {
+    throw new HttpError(429, "Too many reset requests. Please wait a minute and try again.");
+  }
+
+  const user = await getUserByEmail(parsed.data.email);
+
+  // No account, or an account with no email on file: stop here, but return the
+  // same body as the success path so the caller learns nothing.
+  if (!user || !user.email) {
+    console.info("Password reset requested for an address with no matching account");
+    return c.json(GENERIC_FORGOT_RESPONSE);
+  }
+
+  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) {
+    // Don't surface the failure — a "send failed" response would confirm the
+    // address exists. Log it; wrangler tail will show it.
+    console.error(`Failed to send password reset email for user ${user.id}`);
+  }
+
+  return c.json(GENERIC_FORGOT_RESPONSE);
+});
+
+// ---------------------------------------------------------------------------
+// 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.",
+  });
+});
diff --git a/src/system/services/email.ts b/src/system/services/email.ts
new file mode 100644
index 0000000..0fb4e1a
--- /dev/null
+++ b/src/system/services/email.ts
@@ -0,0 +1,154 @@
+/**
+ * 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, "&amp;")
+    .replace(/</g, "&lt;")
+    .replace(/>/g, "&gt;")
+    .replace(/"/g, "&quot;")
+    .replace(/'/g, "&#39;");
+}
+
+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 };
+}
diff --git a/src/system/services/password_reset.ts b/src/system/services/password_reset.ts
new file mode 100644
index 0000000..1189638
--- /dev/null
+++ b/src/system/services/password_reset.ts
@@ -0,0 +1,143 @@
+/**
+ * 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 62a3f55..3f05b66 100644
--- a/src/system/services/users.ts
+++ b/src/system/services/users.ts
@@ -11,7 +11,7 @@
  */
 
 import type { User, UserCreate, UserUpdate } from "../models";
-import { adminUsername, adminPassword, adminDisplayName } from "../config";
+import { adminUsername, adminPassword, adminDisplayName, adminEmail } from "../config";
 import { hashPassword, verifyPassword, isSupportedHash } from "../security";
 import { rt } from "../runtime";
 
@@ -36,6 +36,13 @@ export async function getUsers(): Promise<User[]> {
       userDict.is_owner = true;
       userDict.is_admin = true;
       userDict.is_pet = true;
+      // The owner account predates the email field. Backfill it from
+      // ADMIN_EMAIL so password recovery works without a manual edit; an
+      // address already set by hand always wins.
+      if (!userDict.email) {
+        const seeded = adminEmail();
+        if (seeded) userDict.email = seeded;
+      }
     }
     return userDict as unknown as User;
   });
@@ -47,6 +54,11 @@ 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;
+      }
     }
   }
   await rt().store.put(USERS_KEY, users);
@@ -62,6 +74,25 @@ 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 getUserByEmail(email: string): Promise<User | null> {
+  const target = normalizeEmail(email);
+  if (!target) return null;
+  const users = await getUsers();
+  return users.find((u) => u.email && normalizeEmail(u.email) === target) ?? null;
+}
+
+/** Throw if `email` belongs to a different account. */
+async function assertEmailAvailable(email: string, exceptUserId?: string): Promise<void> {
+  const existing = await getUserByEmail(email);
+  if (existing && existing.id !== exceptUserId) {
+    throw new Error("Email address is already in use");
+  }
+}
+
 export async function createUser(
   userCreate: UserCreate,
   requestingUser?: User | null,
@@ -92,11 +123,15 @@ export async function createUser(
     isPet = userCreate.is_pet;
   }
 
+  const email = userCreate.email ? normalizeEmail(userCreate.email) : null;
+  if (email) await assertEmailAvailable(email);
+
   const newUser: User = {
     id: crypto.randomUUID(),
     username: userCreate.username,
     password_hash: await hashPassword(userCreate.password),
     display_name: userCreate.display_name ?? null,
+    email,
     is_admin: isAdmin,
     is_owner: isOwner,
     is_pet: isPet,
@@ -138,6 +173,22 @@ export async function updateUser(
     throw new Error("Only the owner can change user roles");
   }
 
+  // Email is owner-managed only. Users cannot change their own address, and
+  // plain admins cannot change anyone's — that's deliberate, because email is
+  // the account-recovery factor.
+  let email = user.email ?? null;
+  if (userUpdate.email !== undefined) {
+    const requestedEmail = userUpdate.email ? normalizeEmail(userUpdate.email) : null;
+    const isChange = requestedEmail !== email;
+    if (isChange) {
+      if (!requestingUser?.is_owner) {
+        throw new Error("Only the owner can change email addresses");
+      }
+      if (requestedEmail) await assertEmailAvailable(requestedEmail, user.id);
+      email = requestedEmail;
+    }
+  }
+
   let passwordHash = user.password_hash;
   if (userUpdate.current_password && userUpdate.new_password) {
     if (!(await verifyPassword(userUpdate.current_password, user.password_hash))) {
@@ -156,6 +207,7 @@ export async function updateUser(
     password_hash: passwordHash,
     // `undefined` = field omitted, keep current value; explicit `null` clears it.
     display_name: userUpdate.display_name !== undefined ? userUpdate.display_name : user.display_name,
+    email,
     is_admin: newIsAdmin,
     is_owner: newIsOwner,
     is_pet: newIsPet,
@@ -189,6 +241,23 @@ export async function deleteUser(userId: string, requestingUser?: User | null):
   return false;
 }
 
+/**
+ * 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))) {
@@ -222,6 +291,7 @@ export async function initializeAdminUser(): Promise<void> {
         username,
         password_hash: passwordOrHash,
         display_name: displayName,
+        email: adminEmail() ?? null,
         is_admin: true,
         is_owner: true,
         is_pet: false,
@@ -232,6 +302,7 @@ export async function initializeAdminUser(): Promise<void> {
       await createUser({
         username,
         password: passwordOrHash,
+        email: adminEmail() ?? null,
         display_name: displayName,
         is_admin: true,
         is_pet: false,
diff --git a/src/system/types.ts b/src/system/types.ts
index bc57292..3979169 100644
--- a/src/system/types.ts
+++ b/src/system/types.ts
@@ -39,6 +39,9 @@ export interface SystemEnv {
   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. */
+  ADMIN_EMAIL?: string;
 
   // ---- Manual API keys (replaces generate-on-first-run) ------------------
   /** Static bearer token the Discord bot uses for /api/bot/*. */
@@ -46,9 +49,23 @@ 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;
+
   // ---- Misc --------------------------------------------------------------
   /** Public base URL, used in a few absolute links. */
   BASE_URL?: string;
+  /** Public URL of the frontend, used to build user-facing links. */
+  FRONTEND_URL?: string;
   /** Comma-separated extra CORS origins (added to the built-in defaults). */
   CORS_ORIGINS?: string;
 }
diff --git a/wrangler.jsonc b/wrangler.jsonc
index af69b13..464d397 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -76,9 +76,23 @@
 		"CACHE_TTL": "30",
 		"ADMIN_USERNAME": "clove",
 		"ADMIN_DISPLAY_NAME": "Administrator",
+		// Owner's recovery 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.
+		"FRONTEND_URL": "https://doughmination.co.uk",
+		"PASSWORD_RESET_URL": "https://doughmination.co.uk/user/reset-password",
+
 		// Hypixel API policy: the keyed /v2/minecraft/hypixel endpoint only
 		// serves our OWN accounts, never arbitrary players (no proxying the
 		// Public API to third parties). Add every owned UUID here, comma-