Dough Git

commit

Add auth

commit
c07e108ada60997a83e673c8c7d98d0794fa38c1
author
Clove Twilight <[email protected]>
date
2026-09-21 20:25

diff --git a/.dev.vars.example b/.dev.vars.example
index 755a217..f82447b 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -15,4 +15,8 @@ KEY_ENCRYPTION_KEY=
 SETUP_TOKEN=
 
 # "open" enables /register. Overrides the value in wrangler.jsonc.
-# REGISTRATION=closed
\ No newline at end of file
+# REGISTRATION=closed
+
+# Resend API key. Leave empty locally and emails are printed to the terminal
+# instead of being sent.
+RESEND_API_KEY=
diff --git a/migrations/0003_email_verifications.sql b/migrations/0003_email_verifications.sql
new file mode 100644
index 0000000..5c6ba93
--- /dev/null
+++ b/migrations/0003_email_verifications.sql
@@ -0,0 +1,15 @@
+-- migrations/0003_email_verifications.sql
+-- Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+-- Licensed under the DASL-1.2 Licence.
+
+-- Links sent to prove an email address. `email` is the address the link was
+-- sent to, so a link for an old address can't verify a new one.
+CREATE TABLE email_verifications (
+  token_hash TEXT PRIMARY KEY,
+  user_id    TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+  email      TEXT NOT NULL,
+  created_at INTEGER NOT NULL,
+  expires_at INTEGER NOT NULL
+);
+
+CREATE INDEX email_verifications_user ON email_verifications (user_id);
diff --git a/src/data/cleanup.ts b/src/data/cleanup.ts
index bc6aca9..8342952 100644
--- a/src/data/cleanup.ts
+++ b/src/data/cleanup.ts
@@ -17,6 +17,7 @@ export async function sweepExpired(env: Env): Promise<void> {
     env.DB.prepare("DELETE FROM pending_logins WHERE expires_at <= ?").bind(ts),
     env.DB.prepare("DELETE FROM webauthn_challenges WHERE expires_at <= ?").bind(ts),
     env.DB.prepare("DELETE FROM login_links WHERE expires_at <= ?").bind(ts),
+    env.DB.prepare("DELETE FROM email_verifications WHERE expires_at <= ?").bind(ts),
     env.DB.prepare("DELETE FROM auth_codes WHERE expires_at <= ?").bind(ts),
     // Revoked or used refresh tokens are kept until they expire anyway, so reuse
     // of an old token can still be recognised and its family shut down.
diff --git a/src/data/verifications.ts b/src/data/verifications.ts
new file mode 100644
index 0000000..5a819d1
--- /dev/null
+++ b/src/data/verifications.ts
@@ -0,0 +1,77 @@
+/* src/data/verifications.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { TTL, issuer, now, siteName, type Env } from "../env";
+import { randomToken, sha256Hex } from "../lib/crypto";
+import { sendMail } from "../lib/mail";
+import { attempt } from "../lib/ratelimit";
+
+export type SendResult = "sent" | "rate_limited" | "failed";
+
+/**
+ * Emails a verification link for `email`. Rate limited per account, so neither
+ * sign-ups nor profile edits can be used to flood someone's inbox.
+ */
+export async function sendVerificationEmail(env: Env, userId: string, email: string): Promise<SendResult> {
+  if (!(await attempt(env, `verify-mail:${userId}`, 5, 60 * 60))) return "rate_limited";
+
+  const token = randomToken(32);
+  const ts = now();
+  await env.DB.batch([
+    // Only the newest link for an account stays valid.
+    env.DB.prepare("DELETE FROM email_verifications WHERE user_id = ?").bind(userId),
+    env.DB.prepare(
+      "INSERT INTO email_verifications (token_hash, user_id, email, created_at, expires_at) VALUES (?, ?, ?, ?, ?)",
+    ).bind(await sha256Hex(token), userId, email, ts, ts + TTL.emailVerification),
+  ]);
+
+  // Only our own site name and URL go into the body, never user input, so
+  // nothing here needs HTML escaping.
+  const url = `${issuer(env)}/verify-email/${token}`;
+  const site = siteName(env);
+  const sent = await sendMail(env, {
+    to: email,
+    subject: `Verify your email for ${site}`,
+    text:
+      `Open this link to verify your email address for ${site}:\n\n${url}\n\n` +
+      `It works for 24 hours. If you didn't ask for this, you can ignore this email.`,
+    html:
+      `<p>Open this link to verify your email address for ${site}:</p>` +
+      `<p><a href="${url}">Verify my email</a></p>` +
+      `<p>It works for 24 hours. If you didn't ask for this, you can ignore this email.</p>`,
+  });
+  return sent ? "sent" : "failed";
+}
+
+/** The address a link would verify, without using it (the confirmation page). */
+export async function peekEmailVerification(env: Env, token: string): Promise<string | null> {
+  const row = await env.DB.prepare(
+    "SELECT email FROM email_verifications WHERE token_hash = ? AND expires_at > ?",
+  )
+    .bind(await sha256Hex(token), now())
+    .first<{ email: string }>();
+  return row?.email ?? null;
+}
+
+/**
+ * Uses a link up. Only verifies if the account still has the address the link
+ * was sent to. Returns the user id on success.
+ */
+export async function consumeEmailVerification(env: Env, token: string): Promise<string | null> {
+  const row = await env.DB.prepare(
+    "DELETE FROM email_verifications WHERE token_hash = ? RETURNING user_id, email, expires_at",
+  )
+    .bind(await sha256Hex(token))
+    .first<{ user_id: string; email: string; expires_at: number }>();
+  if (!row || row.expires_at <= now()) return null;
+
+  const result = await env.DB.prepare(
+    "UPDATE users SET email_verified = 1, updated_at = ? WHERE id = ? AND email = ?",
+  )
+    .bind(now(), row.user_id, row.email)
+    .run();
+  return result.meta.changes === 1 ? row.user_id : null;
+}
diff --git a/src/env.ts b/src/env.ts
index 54e8851..d68f0cb 100644
--- a/src/env.ts
+++ b/src/env.ts
@@ -13,6 +13,8 @@ export interface Env {
   KEY_ENCRYPTION_KEY: string;
   SETUP_TOKEN?: string;
   REGISTRATION?: string;
+  RESEND_API_KEY?: string;
+  MAIL_FROM: string;
 }
 
 export interface SessionInfo {
@@ -54,6 +56,8 @@ export const TTL = {
   accessToken: 60 * 60,
   idToken: 60 * 60,
   refreshToken: 60 * 60 * 24 * 30,
+  /** Email verification links. */
+  emailVerification: 60 * 60 * 24,
   /** A used refresh token is honoured again for this long (racing app instances). */
   refreshReuseGrace: 60,
   /** Changing sign-in methods or using /admin needs a sign-in this recent. */
diff --git a/src/lib/mail.ts b/src/lib/mail.ts
new file mode 100644
index 0000000..38dc588
--- /dev/null
+++ b/src/lib/mail.ts
@@ -0,0 +1,55 @@
+/* src/lib/mail.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { isSecure, type Env } from "../env";
+
+export interface Mail {
+  to: string;
+  subject: string;
+  text: string;
+  html: string;
+}
+
+/**
+ * Sends through Resend's HTTP API (Workers can't use SMTP libraries). Without an
+ * API key on a local http issuer, the mail is printed instead so links can be
+ * clicked from the terminal.
+ */
+export async function sendMail(env: Env, mail: Mail): Promise<boolean> {
+  if (!env.RESEND_API_KEY) {
+    if (isSecure(env)) {
+      console.error("[mail] RESEND_API_KEY isn't set");
+      return false;
+    }
+    console.log(`[mail] to ${mail.to}: ${mail.subject}\n${mail.text}`);
+    return true;
+  }
+
+  try {
+    const res = await fetch("https://api.resend.com/emails", {
+      method: "POST",
+      headers: {
+        Authorization: `Bearer ${env.RESEND_API_KEY}`,
+        "Content-Type": "application/json",
+      },
+      body: JSON.stringify({
+        from: env.MAIL_FROM,
+        to: [mail.to],
+        subject: mail.subject,
+        text: mail.text,
+        html: mail.html,
+      }),
+    });
+    if (!res.ok) {
+      console.error("[mail] resend refused", res.status, await res.text());
+      return false;
+    }
+    return true;
+  } catch (err) {
+    console.error("[mail] resend unreachable", err);
+    return false;
+  }
+}
diff --git a/src/main.ts b/src/main.ts
index 63115e6..47bfb98 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -14,6 +14,7 @@ import { setup } from "./routes/setup";
 import { account } from "./routes/account";
 import { admin } from "./routes/admin";
 import { register } from "./routes/register";
+import { verify } from "./routes/verify";
 
 const app = new Hono<AppEnv>();
 
@@ -68,6 +69,7 @@ app.get("/", (c) => c.redirect(c.get("user") ? "/account" : "/login"));
 app.route("/", oidc);
 app.route("/", login);
 app.route("/", register);
+app.route("/", verify);
 app.route("/", setup);
 app.route("/", account);
 app.route("/", admin);
diff --git a/src/oidc/endpoints.tsx b/src/oidc/endpoints.tsx
index d5a6739..c98f46e 100644
--- a/src/oidc/endpoints.tsx
+++ b/src/oidc/endpoints.tsx
@@ -204,6 +204,37 @@ async function authorize(c: AppContext) {
     );
   }
 
+  // Apps may trust the email claim, so every account needs a verified address.
+  if (!user.email_verified) {
+    if (prompts.includes("none")) return fail("interaction_required", "The user hasn't verified their email address.");
+    return render(
+      c,
+      { title: "Verify your email", narrow: true, status: 403 },
+      <div class="card">
+        <h1>Verify your email first</h1>
+        <p class="muted">
+          {user.email ? (
+            <>
+              We sent a link to <strong>{user.email}</strong>. Open it, then come back here.
+            </>
+          ) : (
+            <>Add an email address on your account page and verify it to use {client.name}.</>
+          )}
+        </p>
+        <p>
+          <a class="btn primary wide" href={`/authorize?${new URLSearchParams(params)}`}>
+            I've verified it, continue
+          </a>
+        </p>
+        <p>
+          <a class="btn wide" href="/account">
+            Your account (resend the link)
+          </a>
+        </p>
+      </div>,
+    );
+  }
+
   const code = randomToken(32);
   await c.env.DB.prepare(
     `INSERT INTO auth_codes (code_hash, client_id, user_id, redirect_uri, scope, nonce, code_challenge, auth_time, amr, expires_at)
diff --git a/src/routes/account.tsx b/src/routes/account.tsx
index 9416b8c..31d3d22 100644
--- a/src/routes/account.tsx
+++ b/src/routes/account.tsx
@@ -35,6 +35,7 @@ import {
   updateProfile,
   type UserRow,
 } from "../data/users";
+import { sendVerificationEmail } from "../data/verifications";
 import { render } from "../views/layout";
 import { Csrf, ErrorNote, Field, Flash, Section, date, describeAgent, relative } from "../views/ui";
 
@@ -106,6 +107,13 @@ async function accountPage(c: AppContext, opts: { error?: string; status?: 400 }
             </button>
           </div>
         </form>
+        {user.email && !user.email_verified && (
+          <form method="post" action="/account/email/verify" class="inline-edit">
+            <Csrf token={csrf} />
+            <small class="muted">{user.email} isn't verified yet.</small>
+            <button type="submit" class="small">Resend verification email</button>
+          </form>
+        )}
       </Section>
 
       <Section title="Passkeys" description="The quickest and safest way to sign in: your device unlocks with a fingerprint, face or PIN.">
@@ -250,11 +258,23 @@ account.post("/account/profile", async (c) => {
   const problem = emailProblem(update.email) ?? pictureProblem(update.picture);
   if (problem) return accountPage(c, { error: problem, status: 400 });
 
-  await updateProfile(c.env, await me(c), update);
+  const user = await me(c);
+  await updateProfile(c.env, user, update);
   await audit(c, "account.profile");
+  if (update.email && update.email !== user.email) {
+    const sent = await sendVerificationEmail(c.env, user.id, update.email);
+    return c.redirect(`/account?m=${sent === "sent" ? "verify-sent" : "verify-failed"}`);
+  }
   return c.redirect("/account?m=profile-saved");
 });
 
+account.post("/account/email/verify", async (c) => {
+  const user = await me(c);
+  if (!user.email || user.email_verified) return c.redirect("/account");
+  const sent = await sendVerificationEmail(c.env, user.id, user.email);
+  return c.redirect(`/account?m=${sent === "sent" ? "verify-sent" : "verify-failed"}`);
+});
+
 // --- passkeys --------------------------------------------------------------------
 
 account.post("/account/passkeys/options", async (c) => {
diff --git a/src/routes/register.tsx b/src/routes/register.tsx
index d99430e..1a45eca 100644
--- a/src/routes/register.tsx
+++ b/src/routes/register.tsx
@@ -11,10 +11,11 @@ import { audit } from "../lib/audit";
 import { clientIp, form, safeReturn } from "../lib/http";
 import { PASSWORD_MAX, PASSWORD_MIN, hashPassword, passwordProblem } from "../lib/password";
 import { attempt } from "../lib/ratelimit";
-import { cleanText, normaliseUsername, usernameProblem } from "../lib/validate";
+import { cleanText, emailProblem, normaliseUsername, usernameProblem } from "../lib/validate";
 import { isReserved } from "../data/reserved";
 import { startSession } from "../data/sessions";
 import { countUsers, createUser } from "../data/users";
+import { sendVerificationEmail } from "../data/verifications";
 import { render } from "../views/layout";
 import { ErrorNote, Field } from "../views/ui";
 
@@ -49,6 +50,7 @@ interface RegisterValues {
     returnTo: string;
     username?: string;
     name?: string;
+    email?: string;
 }
 
 function registerPage(c: AppContext, values: RegisterValues, error?: string) {
@@ -72,6 +74,16 @@ function registerPage(c: AppContext, values: RegisterValues, error?: string) {
                     hint="Lowercase letters, digits, dots, dashes or underscores. You can't change it later."
                 />
                 <Field label="Display name" name="name" value={values.name} autocomplete="name" maxlength={100} />
+                <Field
+                    label="Email"
+                    name="email"
+                    type="email"
+                    value={values.email}
+                    required
+                    autocomplete="email"
+                    maxlength={254}
+                    hint="We'll send a link to verify it."
+                />
                 <Field
                     label="Password"
                     name="password"
@@ -116,26 +128,31 @@ register.post("/register", async (c) => {
     const returnTo = safeReturn(body.return);
     const username = normaliseUsername(body.username);
     const password = (body.password ?? "").slice(0, PASSWORD_MAX);
+    const email = cleanText(body.email, 254);
     // Never echo the password back into the form.
-    const values = { returnTo, username, name: body.name ?? "" };
+    const values = { returnTo, username, name: body.name ?? "", email: email ?? "" };
 
     const problem =
         usernameProblem(username) ??
         ((await isReserved(c.env, username)) ? UNAVAILABLE : null) ??
+        (email === null ? "Enter your email address." : emailProblem(email)) ??
         passwordProblem(password, username) ??
         (password !== body.confirm ? "The passwords don't match." : null);
-    if (problem) return registerPage(c, values, problem);
+    if (problem || email === null) return registerPage(c, values, problem ?? "Enter your email address.");
 
     const result = await createUser(c.env, {
         username,
         name: cleanText(body.name, 100),
-        email: null,
+        email,
         emailVerified: false,
         passwordHash: await hashPassword(password),
     });
     if (!result.ok) return registerPage(c, values, UNAVAILABLE);
 
+    const sent = await sendVerificationEmail(c.env, result.id, email);
     await startSession(c, result.id, ["pwd"]);
     await audit(c, "register", { actor: result.id, target: username });
-    return c.redirect(returnTo === "/account" ? "/account?m=welcome" : returnTo);
+    // From an app: back to /authorize, which asks them to verify before continuing.
+    if (returnTo !== "/account") return c.redirect(returnTo);
+    return c.redirect(`/account?m=${sent === "sent" ? "welcome-verify" : "verify-failed"}`);
 });
\ No newline at end of file
diff --git a/src/routes/verify.tsx b/src/routes/verify.tsx
new file mode 100644
index 0000000..2123f88
--- /dev/null
+++ b/src/routes/verify.tsx
@@ -0,0 +1,81 @@
+/* src/routes/verify.tsx
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { Hono } from "hono";
+import { Check, Login } from "pixelarticons/react";
+import type { AppContext, AppEnv } from "../env";
+import { audit } from "../lib/audit";
+import { clientIp } from "../lib/http";
+import { attempt } from "../lib/ratelimit";
+import { consumeEmailVerification, peekEmailVerification } from "../data/verifications";
+import { render } from "../views/layout";
+
+export const verify = new Hono<AppEnv>();
+
+function unusable(c: AppContext) {
+  return render(
+    c,
+    { title: "Link expired", narrow: true, status: 410 },
+    <div class="card">
+      <h1>This link can't be used</h1>
+      <p class="muted">
+        It has expired, was already used, or a newer one was sent. You can send a new one from your account page.
+      </p>
+      <p>
+        <a class="btn primary" href="/account">
+          Your account
+        </a>
+      </p>
+    </div>,
+  );
+}
+
+// Mail scanners follow GETs, so verifying takes a deliberate POST.
+verify.get("/verify-email/:token", async (c) => {
+  const email = await peekEmailVerification(c.env, c.req.param("token"));
+  if (!email) return unusable(c);
+  return render(
+    c,
+    { title: "Verify your email", narrow: true },
+    <div class="card">
+      <h1>Verify your email</h1>
+      <p class="muted">
+        Confirm that <strong>{email}</strong> is yours.
+      </p>
+      <form method="post" action={`/verify-email/${c.req.param("token")}`}>
+        <button type="submit" class="primary wide">
+          <Check class="icon" aria-hidden="true" />
+          Verify
+        </button>
+      </form>
+    </div>,
+  );
+});
+
+verify.post("/verify-email/:token", async (c) => {
+  if (!(await attempt(c.env, `verify-ip:${clientIp(c)}`, 30, 15 * 60))) {
+    return c.text("Too many attempts. Wait a few minutes and try again.", 429);
+  }
+  const userId = await consumeEmailVerification(c.env, c.req.param("token"));
+  if (!userId) return unusable(c);
+
+  await audit(c, "account.email_verified", { actor: userId, target: userId });
+  if (c.get("user")?.id === userId) return c.redirect("/account?m=email-verified");
+  return render(
+    c,
+    { title: "Email verified", narrow: true },
+    <div class="card">
+      <h1>Email verified</h1>
+      <p class="muted">Thanks! You can close this tab, or sign in.</p>
+      <p>
+        <a class="btn primary" href="/login">
+          <Login class="icon" aria-hidden="true" />
+          Sign in
+        </a>
+      </p>
+    </div>,
+  );
+});
diff --git a/src/types/pixelarticons-react.ts b/src/types/pixelarticons-react.ts
index 7d7ed13..0b5da53 100644
--- a/src/types/pixelarticons-react.ts
+++ b/src/types/pixelarticons-react.ts
@@ -14,6 +14,7 @@ type Icon = (props: Record<string, unknown>) => any;
 
 export declare const AppWindows: Icon;
 export declare const ArrowLeft: Icon;
+export declare const Check: Icon;
 export declare const Key: Icon;
 export declare const Link: Icon;
 export declare const Login: Icon;
diff --git a/src/views/ui.tsx b/src/views/ui.tsx
index 1563c09..aff10f7 100644
--- a/src/views/ui.tsx
+++ b/src/views/ui.tsx
@@ -12,6 +12,10 @@ const MESSAGES: Record<string, string> = {
   "signed-out": "You're signed out.",
   "setup-done": "Your admin account is ready. Add a passkey or password below so you can sign in again.",
   "link-welcome": "You're signed in. Add a passkey (or a password) now so you can sign in next time.",
+  "welcome-verify": "Welcome! We've emailed you a link to verify your address. Add a passkey below while you wait.",
+  "verify-sent": "Verification email sent. Check your inbox (and spam).",
+  "verify-failed": "We couldn't send a verification email right now. Try again later.",
+  "email-verified": "Email verified.",
   "profile-saved": "Profile saved.",
   "passkey-added": "Passkey added.",
   "passkey-renamed": "Passkey renamed.",
diff --git a/wrangler.jsonc b/wrangler.jsonc
index 67b5a57..bf7dd11 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -44,9 +44,12 @@
 		// relying party, so it must never change once passkeys are registered.
 		"ISSUER": "https://auth.doughmination.gay",
 		"SITE_NAME": "Doughmination SSO",
-		"REGISTRATION": "open"
+		"REGISTRATION": "open",
+		// Sender for verification emails. The domain must be verified in Resend.
+		"MAIL_FROM": "Doughmination SSO <[email protected]>"
 	}
 	// Secrets (wrangler secret put <NAME>):
 	//   KEY_ENCRYPTION_KEY  encrypts signing keys + TOTP secrets at rest
 	//   SETUP_TOKEN         unlocks /setup while there are no users yet
+	//   RESEND_API_KEY      sends verification emails (optional locally: they're logged instead)
 }
\ No newline at end of file