Dough Git

commit

Updates

commit
b86fa325e407436d8a72aa074eea2b64dd3c5562
author
Clove Twilight <[email protected]>
date
2026-09-16 12:34

diff --git a/.dev.vars.example b/.dev.vars.example
index b72d53a..78cd9c6 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -6,7 +6,7 @@ OIDC_ISSUER=
 OIDC_CLIENT_ID=
 OIDC_CLIENT_SECRET=
 OIDC_REDIRECT_URI=
-OIDC_SCOPE=openid profile email
+OIDC_SCOPE=openid profile email offline_access
 OIDC_POST_LOGOUT_REDIRECT_URI=
 VAPID_PUBLIC_KEY=
 VAPID_PRIVATE_KEY=
diff --git a/lib/auth.ts b/lib/auth.ts
index 5511de1..a721fa2 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -1,26 +1,147 @@
 import { kv } from "./kv";
-import type { Pending } from "./oidc";
+import { GrantRejected, refreshSession, type Pending, type TokenSet } from "./oidc";
 
-const SESSION_TTL_S = 60 * 60 * 24 * 7;
+// Sessions live in KV so they can be ended from the server side, and each one
+// keeps the SSO's refresh token so it can be re-checked: an account that's
+// disabled or taken out of this app's allowed groups on the SSO is signed out
+// here within RECHECK_AFTER_S.
+export const SESSION_TTL_S = 60 * 60 * 24 * 30;
+const RECHECK_AFTER_S = 60 * 10;
+const OUTAGE_GRACE_S = 60 * 60;
+const RETRY_AFTER_S = 60;
+const UNCHECKED_TTL_S = 60 * 60 * 24;
 const PENDING_TTL_S = 60 * 10;
 
-export async function createSession(username: string): Promise<string> {
+interface Session {
+  username: string;
+  sub: string;
+  refreshToken: string | null;
+  idToken: string | null;
+  createdAt: number;
+  verifiedAt: number;
+  checkedAt: number;
+}
+
+const now = () => Math.floor(Date.now() / 1000);
+
+function sessionKey(token: string): string {
+  return `session:${token}`;
+}
+
+async function readSession(token: string): Promise<Session | null> {
+  const raw = await kv().get(sessionKey(token));
+  if (!raw) return null;
+  try {
+    const session = JSON.parse(raw) as Session;
+    if (typeof session?.username === "string" && typeof session.verifiedAt === "number") return session;
+  } catch {
+    // Sessions from before the SSO move were a bare username; they sign in again.
+  }
+  await kv().delete(sessionKey(token));
+  return null;
+}
+
+async function writeSession(token: string, session: Session): Promise<void> {
+  const lifetime = session.refreshToken ? SESSION_TTL_S : UNCHECKED_TTL_S;
+  const remaining = session.createdAt + lifetime - now();
+  if (remaining < 60) {
+    await kv().delete(sessionKey(token));
+    return;
+  }
+  await kv().put(sessionKey(token), JSON.stringify(session), { expirationTtl: remaining });
+}
+
+export async function createSession(tokens: TokenSet): Promise<string> {
   const token = crypto.randomUUID();
-  await kv().put(`session:${token}`, username, { expirationTtl: SESSION_TTL_S });
+  const ts = now();
+  await writeSession(token, {
+    username: tokens.username,
+    sub: tokens.sub,
+    refreshToken: tokens.refreshToken,
+    idToken: tokens.idToken,
+    createdAt: ts,
+    verifiedAt: ts,
+    checkedAt: ts,
+  });
   return token;
 }
 
+const inflight = new Map<string, Promise<Session | null>>();
+
+async function revalidate(token: string, session: Session): Promise<Session | null> {
+  const ts = now();
+  if (ts - session.verifiedAt < RECHECK_AFTER_S || !session.refreshToken) return session;
+
+  const overdue = ts - session.verifiedAt > RECHECK_AFTER_S + OUTAGE_GRACE_S;
+  if (ts - session.checkedAt < RETRY_AFTER_S) {
+    // A recent attempt couldn't reach the SSO; don't retry on every request.
+    if (!overdue) return session;
+    await kv().delete(sessionKey(token));
+    return null;
+  }
+
+  // Requests handled by this isolate share one refresh. Other isolates may
+  // still race it; the SSO honours a just-used refresh token for a short grace
+  // period so that doesn't read as token theft.
+  const pending = inflight.get(token);
+  if (pending) return pending;
+
+  const task = (async (): Promise<Session | null> => {
+    try {
+      const fresh = await refreshSession(session.refreshToken!);
+      if (fresh.sub && fresh.sub !== session.sub) {
+        await kv().delete(sessionKey(token));
+        return null;
+      }
+      const at = now();
+      const updated: Session = {
+        ...session,
+        refreshToken: fresh.refreshToken ?? session.refreshToken,
+        idToken: fresh.idToken ?? session.idToken,
+        verifiedAt: at,
+        checkedAt: at,
+      };
+      await writeSession(token, updated);
+      return updated;
+    } catch (err) {
+      if (err instanceof GrantRejected) {
+        await kv().delete(sessionKey(token));
+        return null;
+      }
+      console.warn("could not reach the SSO to re-check a session", err);
+      if (overdue) {
+        await kv().delete(sessionKey(token));
+        return null;
+      }
+      const updated = { ...session, checkedAt: now() };
+      await writeSession(token, updated);
+      return updated;
+    }
+  })().finally(() => inflight.delete(token));
+
+  inflight.set(token, task);
+  return task;
+}
+
 export async function isValidSession(token: string | undefined): Promise<boolean> {
   return (await sessionUser(token)) !== null;
 }
 
 export async function sessionUser(token: string | undefined): Promise<string | null> {
   if (!token) return null;
-  return (await kv().get(`session:${token}`)) ?? null;
+  const session = await readSession(token);
+  if (!session) return null;
+  return (await revalidate(token, session))?.username ?? null;
 }
 
-export async function destroySession(token: string | undefined): Promise<void> {
-  if (token) await kv().delete(`session:${token}`);
+/** Deletes the session and hands back what's needed to end it at the SSO too. */
+export async function destroySession(
+  token: string | undefined,
+): Promise<{ refreshToken: string | null; idToken: string | null } | null> {
+  if (!token) return null;
+  const session = await readSession(token);
+  await kv().delete(sessionKey(token));
+  return session ? { refreshToken: session.refreshToken, idToken: session.idToken } : null;
 }
 
 export async function savePending(p: Pending): Promise<string> {
diff --git a/lib/oidc.ts b/lib/oidc.ts
index 6e9ecd9..c84a209 100644
--- a/lib/oidc.ts
+++ b/lib/oidc.ts
@@ -1,11 +1,13 @@
-import { createRemoteJWKSet, jwtVerify } from "jose";
+import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";
 
 const OIDC = {
   issuer: (process.env.OIDC_ISSUER || "").replace(/\/+$/, ""),
   clientId: process.env.OIDC_CLIENT_ID || "",
   clientSecret: process.env.OIDC_CLIENT_SECRET || "",
   redirectUri: process.env.OIDC_REDIRECT_URI || "",
-  scope: process.env.OIDC_SCOPE || "openid profile email",
+  // offline_access is what gets a refresh token, which sessions use to keep
+  // checking that the SSO still vouches for the account.
+  scope: process.env.OIDC_SCOPE || "openid profile email offline_access",
   postLogoutRedirectUri: process.env.OIDC_POST_LOGOUT_REDIRECT_URI || "",
 };
 
@@ -15,6 +17,7 @@ interface Discovery {
   token_endpoint: string;
   jwks_uri: string;
   end_session_endpoint?: string;
+  revocation_endpoint?: string;
 }
 
 let discovery: Discovery | null = null;
@@ -29,8 +32,12 @@ async function getDiscovery(): Promise<Discovery> {
     throw new Error(`OIDC discovery failed (${res.status}) at ${url}`);
   }
 
-  discovery = (await res.json()) as Discovery;
-  jwks = createRemoteJWKSet(new URL(discovery.jwks_uri));
+  const doc = (await res.json()) as Discovery;
+  if (doc.issuer !== OIDC.issuer) {
+    throw new Error(`OIDC issuer mismatch: configured ${OIDC.issuer}, discovered ${doc.issuer}`);
+  }
+  discovery = doc;
+  jwks = createRemoteJWKSet(new URL(doc.jwks_uri));
   return discovery;
 }
 
@@ -84,6 +91,12 @@ function pickUsername(claims: Record<string, unknown>): string {
   return sanitizeUsername(String(raw));
 }
 
+/** Same-site paths only: "/x" yes; "//host", "/\host" and absolute URLs no. */
+export function safeReturnTo(raw: string | undefined, fallback = "/inbox"): string {
+  if (!raw || !raw.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return fallback;
+  return raw;
+}
+
 export interface Pending {
   state: string;
   nonce: string;
@@ -111,56 +124,120 @@ export async function buildAuthUrl(returnTo: string): Promise<{ url: string; pen
 
   return {
     url: url.toString(),
-    pending: { state, nonce, codeVerifier, returnTo: returnTo.startsWith("/") ? returnTo : "/inbox" },
+    pending: { state, nonce, codeVerifier, returnTo: safeReturnTo(returnTo) },
   };
 }
 
-export async function completeLogin(
-  code: string,
-  pending: Pending,
-): Promise<{ username: string; sub: string }> {
-  const d = await getDiscovery();
+/** RFC 9207: when the SSO names itself on the callback, it must be the one we asked. */
+export function issuerMatches(iss: string | undefined): boolean {
+  return iss === undefined || iss === OIDC.issuer;
+}
 
-  const body = new URLSearchParams({
-    grant_type: "authorization_code",
-    code,
-    redirect_uri: OIDC.redirectUri,
-    client_id: OIDC.clientId,
-    client_secret: OIDC.clientSecret,
-    code_verifier: pending.codeVerifier,
-  });
+export interface TokenSet {
+  username: string;
+  sub: string;
+  refreshToken: string | null;
+  idToken: string;
+}
+
+export class GrantRejected extends Error {}
 
-  const tokenRes = await fetch(d.token_endpoint, {
+async function tokenRequest(params: Record<string, string>): Promise<{ id_token?: string; refresh_token?: string }> {
+  const d = await getDiscovery();
+  const res = await fetch(d.token_endpoint, {
     method: "POST",
     headers: { "Content-Type": "application/x-www-form-urlencoded" },
-    body,
+    body: new URLSearchParams({
+      ...params,
+      client_id: OIDC.clientId,
+      client_secret: OIDC.clientSecret,
+    }),
   });
 
-  if (!tokenRes.ok) {
-    const text = await tokenRes.text();
-    throw new Error(`token exchange failed (${tokenRes.status}): ${text}`);
+  if (!res.ok) {
+    const text = await res.text();
+    let error = "";
+    try {
+      error = (JSON.parse(text) as { error?: string }).error ?? "";
+    } catch {
+      // not JSON
+    }
+    // invalid_grant is the SSO's definitive "no"; anything else might be transient.
+    if (error === "invalid_grant") throw new GrantRejected(text);
+    throw new Error(`token request failed (${res.status}): ${text}`);
   }
+  return (await res.json()) as { id_token?: string; refresh_token?: string };
+}
 
-  const tokens = (await tokenRes.json()) as { id_token?: string };
-  if (!tokens.id_token) throw new Error("no id_token returned");
-
-  const { payload } = await jwtVerify(tokens.id_token, jwks!, {
+async function verifyIdToken(idToken: string): Promise<JWTPayload> {
+  const d = await getDiscovery();
+  const { payload } = await jwtVerify(idToken, jwks!, {
     issuer: d.issuer,
     audience: OIDC.clientId,
   });
+  return payload;
+}
+
+export async function completeLogin(code: string, pending: Pending): Promise<TokenSet> {
+  const tokens = await tokenRequest({
+    grant_type: "authorization_code",
+    code,
+    redirect_uri: OIDC.redirectUri,
+    code_verifier: pending.codeVerifier,
+  });
+  if (!tokens.id_token) throw new Error("no id_token returned");
 
+  const payload = await verifyIdToken(tokens.id_token);
   if (payload.nonce !== pending.nonce) throw new Error("nonce mismatch");
 
   const username = pickUsername(payload as Record<string, unknown>);
   if (!username) throw new Error("no usable username in token");
 
-  return { username, sub: String(payload.sub || "") };
+  return {
+    username,
+    sub: String(payload.sub || ""),
+    refreshToken: tokens.refresh_token ?? null,
+    idToken: tokens.id_token,
+  };
+}
+
+/**
+ * Asks the SSO whether it still vouches for a session. Throws GrantRejected
+ * when it doesn't (account disabled, removed from the app's allowed groups,
+ * signed out everywhere); other errors mean it couldn't be asked.
+ */
+export async function refreshSession(refreshToken: string): Promise<{ sub: string; refreshToken: string | null; idToken: string | null }> {
+  const tokens = await tokenRequest({ grant_type: "refresh_token", refresh_token: refreshToken });
+  const payload = tokens.id_token ? await verifyIdToken(tokens.id_token) : null;
+  return {
+    sub: payload ? String(payload.sub || "") : "",
+    refreshToken: tokens.refresh_token ?? null,
+    idToken: tokens.id_token ?? null,
+  };
+}
+
+export async function revokeRefreshToken(refreshToken: string): Promise<void> {
+  const d = await getDiscovery();
+  if (!d.revocation_endpoint) return;
+  await fetch(d.revocation_endpoint, {
+    method: "POST",
+    headers: { "Content-Type": "application/x-www-form-urlencoded" },
+    body: new URLSearchParams({
+      token: refreshToken,
+      token_type_hint: "refresh_token",
+      client_id: OIDC.clientId,
+      client_secret: OIDC.clientSecret,
+    }),
+  });
 }
 
-export function endSessionUrl(): string | null {
+/** Where to send the browser so the SSO session ends too. */
+export function endSessionUrl(idToken: string | null): string | null {
   if (!discovery?.end_session_endpoint || !OIDC.postLogoutRedirectUri) return null;
   const url = new URL(discovery.end_session_endpoint);
   url.searchParams.set("post_logout_redirect_uri", OIDC.postLogoutRedirectUri);
   url.searchParams.set("client_id", OIDC.clientId);
+  // With the id_token as proof, the SSO signs out without asking again.
+  if (idToken) url.searchParams.set("id_token_hint", idToken);
   return url.toString();
 }
diff --git a/public/app.js b/public/app.js
index 602a2c9..f59ed68 100644
--- a/public/app.js
+++ b/public/app.js
@@ -732,8 +732,10 @@ backBtn.addEventListener("click", () => {
 });
 
 document.getElementById("logoutBtn").addEventListener("click", async () => {
-  await fetch("/api/logout", { method: "POST" });
-  window.location.href = "/login";
+  const res = await fetch("/api/logout", { method: "POST" });
+  const data = await res.json().catch(() => ({}));
+  // Ending the SSO session too, when the server says how.
+  window.location.href = data.endSession || "/login";
 });
 
 document.getElementById("cancelBtn").addEventListener("click", () => {
diff --git a/public/login.html b/public/login.html
index ead2683..58d812d 100644
--- a/public/login.html
+++ b/public/login.html
@@ -27,7 +27,7 @@
 <body class="login-body">
   <div class="compose login-card">
     <h2>Sign in</h2>
-    <p>Use your passkey to sign in to the inbox.</p>
+    <p>Use your Doughmination SSO account to sign in to the inbox.</p>
 
     <div class="actions">
       <a href="/auth/login" class="btn-accent">๐Ÿ”‘ Sign in with SSO</a>
diff --git a/public/login.js b/public/login.js
deleted file mode 100644
index fe9cde8..0000000
--- a/public/login.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* mailbox/public/login.js
- * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
- * Licensed under the DASL-1.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-const form = document.getElementById("loginForm");
-const errorEl = document.getElementById("loginError");
-
-form.addEventListener("submit", async (ev) => {
-  ev.preventDefault();
-  errorEl.classList.add("hidden");
-
-  const formData = new FormData(form);
-
-  const res = await fetch("/api/login", {
-    method: "POST",
-    headers: { "Content-Type": "application/json" },
-    body: JSON.stringify({
-      username: formData.get("username"),
-      password: formData.get("password"),
-      // Turnstile injects this hidden field into the widget's container div
-      // once a challenge is solved.
-      turnstileToken: formData.get("cf-turnstile-response"),
-      // Honeypot โ€” should always be empty for a real visitor.
-      website: formData.get("website"),
-    }),
-  });
-
-  if (!res.ok) {
-    const err = await res.json().catch(() => ({}));
-    errorEl.textContent = err.error ?? "Sign in failed.";
-    errorEl.classList.remove("hidden");
-    // Turnstile tokens are single-use โ€” get a fresh one for the next attempt.
-    if (window.turnstile) window.turnstile.reset();
-    return;
-  }
-
-  window.location.href = "/";
-});
\ No newline at end of file
diff --git a/public/settings.js b/public/settings.js
index 3595cce..c53db7b 100644
--- a/public/settings.js
+++ b/public/settings.js
@@ -292,8 +292,10 @@ assignForm.addEventListener("submit", (ev) => {
 });
 
 document.getElementById("logoutBtn").addEventListener("click", async () => {
-  await fetch("/api/logout", { method: "POST" });
-  window.location.href = "/login";
+  const res = await fetch("/api/logout", { method: "POST" });
+  const data = await res.json().catch(() => ({}));
+  // Ending the SSO session too, when the server says how.
+  window.location.href = data.endSession || "/login";
 });
 
 // --- Web Push ---
diff --git a/server.ts b/server.ts
index 16d2fcd..6a59117 100644
--- a/server.ts
+++ b/server.ts
@@ -24,6 +24,7 @@ import {
   persistInboundAttachments,
 } from "./lib/attachments";
 import {
+  SESSION_TTL_S,
   createSession,
   sessionUser,
   destroySession,
@@ -35,6 +36,8 @@ import {
   buildAuthUrl,
   completeLogin,
   endSessionUrl,
+  issuerMatches,
+  revokeRefreshToken,
 } from "./lib/oidc";
 import {
   isAdmin,
@@ -190,7 +193,7 @@ const app = new Hono<{ Variables: { user: string } }>();
 const PUBLIC_PATHS = new Set([
   "/login",
   "/login.html",
-  "/login.js",
+  "/sfx.js",
   "/style.css",
   "/favicon.ico",
   "/apple-touch-icon.png",
@@ -200,6 +203,22 @@ const PUBLIC_PATHS = new Set([
   "/manifest.webmanifest",
 ]);
 
+// Session cookies are SameSite=Lax, which still lets sibling subdomains (same
+// site) send them. State-changing requests must come from this origin.
+app.use("/*", async (c, next) => {
+  const method = c.req.method;
+  if (method === "GET" || method === "HEAD" || method === "OPTIONS" || c.req.path === "/webhook/inbound") {
+    return next();
+  }
+  const origin = c.req.header("origin");
+  const site = c.req.header("sec-fetch-site");
+  const self = new URL(c.req.url).origin;
+  if (origin ? origin !== self : site !== undefined && site !== "same-origin" && site !== "none") {
+    return c.json({ error: "Cross-site request refused" }, 403);
+  }
+  return next();
+});
+
 app.use("/*", async (c, next) => {
   const path = c.req.path;
   if (path === "/webhook/inbound" || PUBLIC_PATHS.has(path)) {
@@ -242,7 +261,11 @@ app.get("/auth/callback", async (c) => {
   const code = c.req.query("code");
   const stateParam = c.req.query("state");
   const err = c.req.query("error");
+  if (err === "access_denied") {
+    return c.text("Your SSO account isn't allowed to use the inbox. Ask an SSO admin to add you to its allowed groups.", 403);
+  }
   if (err) return c.text(`Login failed: ${err}`, 401);
+  if (!issuerMatches(c.req.query("iss"))) return c.text("Login failed: unexpected issuer.", 401);
 
   const pending = await takePending(getCookie(c, "login"));
   deleteCookie(c, "login", { path: "/" });
@@ -252,15 +275,15 @@ app.get("/auth/callback", async (c) => {
   }
 
   try {
-    const { username } = await completeLogin(code, pending);
-    await ensureUser(username);
-    const token = await createSession(username);
+    const tokens = await completeLogin(code, pending);
+    await ensureUser(tokens.username);
+    const token = await createSession(tokens);
     setCookie(c, "session", token, {
       httpOnly: true,
       sameSite: "Lax",
       secure: cookieSecure(),
       path: "/",
-      maxAge: 60 * 60 * 24 * 7,
+      maxAge: SESSION_TTL_S,
     });
     return c.redirect(pending.returnTo);
   } catch (e) {
@@ -276,9 +299,15 @@ app.get("/drafts", (c) => sendAsset(c.req.raw, "/index.html"));
 app.get("/settings", (c) => sendAsset(c.req.raw, "/settings.html"));
 
 app.post("/api/logout", async (c) => {
-  await destroySession(getCookie(c, "session"));
+  const ended = await destroySession(getCookie(c, "session"));
   deleteCookie(c, "session", { path: "/" });
-  return c.json({ ok: true, endSession: endSessionUrl() });
+  if (ended?.refreshToken) {
+    c.executionCtx.waitUntil(
+      revokeRefreshToken(ended.refreshToken).catch((err) => console.warn("refresh token revocation failed", err)),
+    );
+  }
+  // The client navigates here so the SSO session ends as well.
+  return c.json({ ok: true, endSession: endSessionUrl(ended?.idToken ?? null) });
 });
 
 app.get("/api/me", (c) => {
@@ -723,7 +752,7 @@ app.post("/api/owners/unassign", async (c) => {
 
 // Remove a user: permanently delete all their stored mail (attachments too),
 // then drop their reservations and admin rights. They can sign in again via
-// PocketID and are recreated as an ordinary user owning just username@domain.
+// the SSO and are recreated as an ordinary user owning just username@domain.
 app.post("/api/owners/delete-user", async (c) => {
   const actor = c.get("user");
   if (!isAdmin(actor)) return c.json({ error: "Forbidden" }, 403);
diff --git a/wrangler.jsonc b/wrangler.jsonc
index d3a189d..30f8110 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -21,10 +21,10 @@
 		}
 	],
 	"vars": {
-		"OIDC_SCOPE": "openid profile email",
+		"OIDC_SCOPE": "openid profile email offline_access",
 		"VAPID_SUBJECT": "mailto:[email protected]",
 		"COOKIE_SECURE": "true",
-		"OIDC_ISSUER": "https://sso.doughmination.gay",
+		"OIDC_ISSUER": "https://auth.doughmination.gay",
 		"OIDC_CLIENT_ID": "cc067f21-88ca-4927-ac7b-26d21968d2e1",
 		"OIDC_REDIRECT_URI": "https://mail.doughmination.gay/auth/callback",
 		"OIDC_POST_LOGOUT_REDIRECT_URI": "https://mail.doughmination.gay",