Dough Git

commit

email service

commit
86a1db1e5a03e79007ba70a16280ef479f99da83
author
Clove Twilight <[email protected]>
date
2026-07-21 17:20

diff --git a/src/apidata.ts b/src/apidata.ts
index dcfe519..98ff332 100644
--- a/src/apidata.ts
+++ b/src/apidata.ts
@@ -84,12 +84,24 @@ export const GROUPS: GroupDef[] = [
         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), email, display_name?, turnstile_token }. Email is required and must be unique — it is the only self-service password-recovery route." },
+        desc: "Create a non-admin account. Body { username, password (≥10 chars), email, display_name?, turnstile_token }. Email is required and unique. The account starts UNCONFIRMED: login is refused until the emailed link is used, and unconfirmed accounts are deleted after 24 hours. The response includes a short-lived correction_token — hold onto it, it's the only way to fix a mistyped address without a password.",
+        example: 'POST body: { "username": "clove", "password": "…", "email": "[email protected]", "turnstile_token": "…" }  →  { "success": true, "email_sent": true, "correction_token": "…", "user": { … } }' },
+      { m: "POST", path: "/plural/verify-email", auth: "public",
+        desc: "Confirm an address using the token from the email. Body { token }. Single use, valid 24 hours. Also applies a pending email change." },
+      { m: "POST", path: "/plural/resend-verification", auth: "public",
+        desc: "Send the confirmation link again. Body { turnstile_token } plus either { correction_token } or { username, password }. Rate limited to one per IP per minute." },
+      { m: "POST", path: "/plural/correct-email", auth: "public",
+        desc: "Fix a mistyped address before confirmation, without a password. Body { correction_token, email, turnstile_token }. The correction token is issued only to the client that signed up, lasts 2 hours, and stops working once the account is confirmed — it is what stops anyone repointing an unconfirmed account at their own inbox." },
       { m: "GET", path: "/plural/users/check-username?username=", auth: "public",
         desc: "Check username availability. Returns { username, exists, available }." },
+      { m: "GET", path: "/plural/users/check-email?email=", auth: "public",
+        desc: "Check email availability. Returns { email, exists, available }. Rate limited to 20 lookups per IP per minute." },
       { 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." }' },
+        desc: "Request a password-reset link by USERNAME. Body { username, turnstile_token }. The link is emailed to the address on file for that account; the response reports a masked hint so the user knows which inbox to check. Returns 404 for an unknown username and 409 if the account has no email on file. Rate limited to one request per IP per minute.",
+        example: 'POST body: { "username": "clove", "turnstile_token": "…" }  →  { "success": true, "message": "Reset link sent. The link expires in 15 minutes.", "sent_to": "a•••@d•••.win" }' },
+      { m: "POST", path: "/plural/forgot-username", auth: "public",
+        desc: "Recover a forgotten username by EMAIL. Body { email, turnstile_token }. The username is emailed to that address rather than returned, so knowing an address isn't enough to learn the username on it. Returns 404 if the address isn't registered. Rate limited to one request per IP per minute.",
+        example: 'POST body: { "email": "[email protected]", "turnstile_token": "…" }  →  { "success": true, "message": "We\'ve sent your username to that address.", "sent_to": "y•••@e•••.com" }' },
       { 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",
@@ -154,9 +166,9 @@ export const GROUPS: GroupDef[] = [
     endpoints: [
       { m: "GET", path: "/plural/users", auth: "admin", desc: "List all users (no password hashes)." },
       { m: "POST", path: "/plural/users", auth: "admin",
-        desc: "Create a user. Body { username, password, display_name?, is_admin?, is_pet? }." },
+        desc: "Create a user. Body { username, password, email?, display_name?, is_admin?, is_pet? }. Accounts created here are pre-confirmed — the address is being assigned deliberately — so they can log in immediately and are never touched by the unconfirmed-account sweep." },
       { m: "PUT", path: "/plural/users/:user_id", auth: "auth",
-        desc: "Update a user (admin, or the user themselves). Body may include display_name, current_password + new_password, avatar_url (an EXTERNAL image URL — uploads were removed), is_admin, is_pet." },
+        desc: "Update a user (admin, or the user themselves). Body may include display_name, current_password + new_password, avatar_url (an EXTERNAL image URL — uploads were removed), is_admin, is_pet, email. EMAIL RULES: a user may change their own address but must supply current_password, and the new address is held in pending_email until confirmed (the old one keeps working, and gets an alert). The owner may set anyone's address outright. A plain admin may NOT change someone else's." },
       { m: "DELETE", path: "/plural/users/:user_id", auth: "admin",
         desc: "Delete a user. Cannot delete yourself or the owner." },
     ],
diff --git a/src/index.ts b/src/index.ts
index 6b41d7a..97fff74 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -444,6 +444,14 @@ 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 8de71dd..522e79b 100644
--- a/src/system/app.ts
+++ b/src/system/app.ts
@@ -28,6 +28,7 @@ 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 { frontingRoutes } from "./routes/fronting";
@@ -59,6 +60,7 @@ 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("/", frontingRoutes);
diff --git a/src/system/config.ts b/src/system/config.ts
index d521d43..9d6311c 100644
--- a/src/system/config.ts
+++ b/src/system/config.ts
@@ -98,9 +98,19 @@ export function passwordResetUrl(): string {
   return `${frontendUrl()}/user/reset-password`;
 }
 
+/** 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`;
+}
+
 /** How long a password-reset token stays valid. */
 export const PASSWORD_RESET_TTL_MINUTES = 15;
 
+/** Unconfirmed signups are deleted once they are older than this. */
+export const UNVERIFIED_ACCOUNT_TTL_HOURS = 24;
+
 /** 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/do.ts b/src/system/do.ts
index ed69ffe..f0320c0 100644
--- a/src/system/do.ts
+++ b/src/system/do.ts
@@ -31,6 +31,8 @@ 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) {}
@@ -53,6 +55,8 @@ 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
@@ -94,6 +98,18 @@ 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 6e4c67d..e498063 100644
--- a/src/system/models.ts
+++ b/src/system/models.ts
@@ -32,6 +32,23 @@ export const UserSchema = z.object({
   /** 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.
+   */
+  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. */
+  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),
@@ -54,6 +71,9 @@ 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),
   is_pet: z.boolean().default(false),
@@ -66,7 +86,12 @@ 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. */
+  /**
+   * 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.
+   */
   email: EmailSchema.nullable().optional(),
   is_admin: z.boolean().nullable().optional(),
   is_pet: z.boolean().nullable().optional(),
@@ -80,12 +105,51 @@ export const LoginRequestSchema = z.object({
 });
 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({
-  email: EmailSchema,
+  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"),
diff --git a/src/system/routes/auth.ts b/src/system/routes/auth.ts
index c950867..e9bb05b 100644
--- a/src/system/routes/auth.ts
+++ b/src/system/routes/auth.ts
@@ -10,10 +10,14 @@ import type { Context } from "hono";
 import type { Env } from "../hono";
 import { UserResponseSchema, LoginRequestSchema, EmailSchema } from "../models";
 import type { User } from "../models";
-import { verifyUser, createUser, getUsers } from "../services/users";
+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 { requireAuth } from "../middleware/auth";
 import { HttpError } from "../errors";
+import { rt } from "../runtime";
 
 export const authRoutes = new Hono<Env>();
 
@@ -23,6 +27,9 @@ 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,
     is_pet: user.is_pet,
@@ -62,6 +69,18 @@ authRoutes.post("/login", async (c) => {
     throw new HttpError(401, "Invalid credentials", { "WWW-Authenticate": "Bearer" });
   }
 
+  // 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 token = await createAccessToken({
     sub: user.username,
     id: user.id,
@@ -114,10 +133,25 @@ authRoutes.post("/signup", async (c) => {
     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: "Account created successfully",
+      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) {
@@ -137,6 +171,40 @@ authRoutes.get("/users/check-username", async (c) => {
   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 });
+});
+
 authRoutes.get("/user_info", requireAuth, (c) => c.json(toUserResponseJson(c.get("user") as User)));
 
 authRoutes.get("/auth/is_admin", requireAuth, (c) =>
diff --git a/src/system/routes/email_verification.ts b/src/system/routes/email_verification.ts
new file mode 100644
index 0000000..95f1806
--- /dev/null
+++ b/src/system/routes/email_verification.ts
@@ -0,0 +1,234 @@
+/**
+ * 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
index b7f89ea..c4c4db5 100644
--- a/src/system/routes/password_reset.ts
+++ b/src/system/routes/password_reset.ts
@@ -5,47 +5,54 @@
  */
 
 /**
- * Password reset:
+ * Account recovery:
  *
- *   POST /v2/plural/forgot-password        request a reset link
+ *   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
  *
- * 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.
+ * 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, ResetPasswordRequestSchema } from "../models";
-import { PASSWORD_RESET_TTL_MINUTES, passwordResetUrl } from "../config";
-import { getUserByEmail, getUserById, setPassword } from "../services/users";
+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 } from "../services/email";
+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>();
 
-/** 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. */
+/** 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 {
@@ -53,9 +60,9 @@ function clientIp(c: Context): string | undefined {
 }
 
 /** Per-IP throttle. True = allowed (and recorded). Blank IP is never limited. */
-async function checkAndRecordRateLimit(ip: string | undefined): Promise<boolean> {
+async function checkAndRecordRateLimit(prefix: string, ip: string | undefined): Promise<boolean> {
   if (!ip) return true;
-  const key = RL_PREFIX + ip;
+  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;
@@ -67,8 +74,31 @@ function firstIssueMessage(issues: Array<{ message: string }>, fallback: 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
+// POST /forgot-password  — by username
 // ---------------------------------------------------------------------------
 
 passwordResetRoutes.post("/forgot-password", async (c) => {
@@ -80,17 +110,23 @@ passwordResetRoutes.post("/forgot-password", async (c) => {
   const ok = await verifyTurnstileToken(parsed.data.turnstile_token, clientIp(c));
   if (!ok) throw new HttpError(400, "Security verification failed");
 
-  if (!(await checkAndRecordRateLimit(clientIp(c)))) {
+  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 getUserByEmail(parsed.data.email);
+  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.",
+    );
+  }
 
-  // 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);
+  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);
@@ -104,12 +140,64 @@ passwordResetRoutes.post("/forgot-password", async (c) => {
 
   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}`);
+    throw new HttpError(
+      502,
+      "We couldn't send the reset email just now. Please try again in a few minutes.",
+    );
   }
 
-  return c.json(GENERIC_FORGOT_RESPONSE);
+  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),
+  });
 });
 
 // ---------------------------------------------------------------------------
@@ -158,5 +246,6 @@ passwordResetRoutes.post("/reset-password", async (c) => {
   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 6c211c2..f3094f8 100644
--- a/src/system/routes/users.ts
+++ b/src/system/routes/users.ts
@@ -14,7 +14,10 @@ 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 } from "../services/users";
+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 { requireAuth, requireAdmin } from "../middleware/auth";
 import { HttpError } from "../errors";
 
@@ -35,7 +38,9 @@ usersRoutes.post("/users", requireAuth, requireAdmin, async (c) => {
   if (!parsed.success) return c.json({ detail: validationDetail(parsed.error.issues) }, 422);
 
   try {
-    const newUser = await createUser(parsed.data, c.get("user") ?? null);
+    // 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 });
     return c.json(toUserResponse(newUser));
   } catch (err) {
     throw new HttpError(400, String(err instanceof Error ? err.message : err));
@@ -53,10 +58,57 @@ 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");
-    return c.json(toUserResponse(updated));
+
+    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.",
+          }
+        : {}),
+    });
   } catch (err) {
     if (err instanceof HttpError) throw err;
     throw new HttpError(400, String(err instanceof Error ? err.message : err));
diff --git a/src/system/services/email.ts b/src/system/services/email.ts
index 0fb4e1a..9540d2d 100644
--- a/src/system/services/email.ts
+++ b/src/system/services/email.ts
@@ -152,3 +152,191 @@ export function passwordResetTemplate({ displayName, resetUrl, ttlMinutes }: Pas
 
   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
new file mode 100644
index 0000000..98105bb
--- /dev/null
+++ b/src/system/services/email_verification.ts
@@ -0,0 +1,214 @@
+/**
+ * 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/users.ts b/src/system/services/users.ts
index 3f05b66..7596174 100644
--- a/src/system/services/users.ts
+++ b/src/system/services/users.ts
@@ -78,6 +78,18 @@ export function normalizeEmail(email: string): string {
   return email.trim().toLowerCase();
 }
 
+/**
+ * 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 async function getUserByEmail(email: string): Promise<User | null> {
   const target = normalizeEmail(email);
   if (!target) return null;
@@ -85,17 +97,38 @@ export async function getUserByEmail(email: string): Promise<User | null> {
   return users.find((u) => u.email && normalizeEmail(u.email) === target) ?? null;
 }
 
-/** Throw if `email` belongs to a different account. */
+/**
+ * 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.
+ */
 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");
-  }
+  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)),
+  );
+  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();
 
@@ -126,12 +159,19 @@ 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),
     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,
@@ -173,19 +213,59 @@ 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.
+  // ---- 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.
   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 isChange = requestedEmail !== email;
-    if (isChange) {
-      if (!requestingUser?.is_owner) {
-        throw new Error("Only the owner can change email addresses");
+    const isSelf = requestingUser?.id === user.id;
+    const isOwnerActing = !!requestingUser?.is_owner;
+
+    if (requestedEmail !== email) {
+      if (!isSelf && !isOwnerActing) {
+        throw new Error("You can only change your own email address");
       }
+
       if (requestedEmail) await assertEmailAvailable(requestedEmail, user.id);
-      email = requestedEmail;
+
+      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;
+      }
     }
   }
 
@@ -208,12 +288,21 @@ export async function updateUser(
     // `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;
@@ -241,6 +330,100 @@ 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.
  *
diff --git a/src/system/types.ts b/src/system/types.ts
index 3979169..86afd80 100644
--- a/src/system/types.ts
+++ b/src/system/types.ts
@@ -60,6 +60,9 @@ export interface SystemEnv {
   /** 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. */
diff --git a/wrangler.jsonc b/wrangler.jsonc
index 464d397..ad41b01 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -92,6 +92,7 @@
 		// 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",
 
 		// Hypixel API policy: the keyed /v2/minecraft/hypixel endpoint only
 		// serves our OWN accounts, never arbitrary players (no proxying the