Dough Git

commit

More changes

commit
5cc2f9589d33dad9a0f10ed110d9d32bb525bd82
author
Clove Twilight <[email protected]>
date
2026-10-24 07:47

diff --git a/README.md b/README.md
index e93315a..1e5f6a6 100644
--- a/README.md
+++ b/README.md
@@ -72,6 +72,6 @@ Then:
 | | |
 |---|---|
 | `npm run dev` | Vite + the Worker in workerd, with hot reload |
-| `npm run typecheck` | Worker (`tsc`) and app (`svelte-check`) |
+| `npm run typecheck` | Worker and tests (`tsc`), and the app (`svelte-check`) |
 | `npm test` | vitest inside workerd |
 | `npm run types` | regenerate `worker-configuration.d.ts` after changing `wrangler.jsonc` |
diff --git a/package.json b/package.json
index a99aea4..c1f2db0 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
     "preview": "npm run build && vite preview",
     "deploy": "npm run build && wrangler deploy",
     "types": "wrangler types src/worker/worker-configuration.d.ts --env-file .dev.vars.example",
-    "typecheck": "tsc -p src/worker && svelte-check --tsconfig src/web/tsconfig.json",
+    "typecheck": "tsc -p src/worker && tsc -p test && svelte-check --tsconfig src/web/tsconfig.json",
     "test": "vitest run",
     "db:migrate:local": "wrangler d1 migrations apply DB --local",
     "db:migrate:remote": "wrangler d1 migrations apply DB --remote"
diff --git a/src/web/components/EmailFrame.svelte b/src/web/components/EmailFrame.svelte
index 57bd51f..73dd3be 100644
--- a/src/web/components/EmailFrame.svelte
+++ b/src/web/components/EmailFrame.svelte
@@ -49,7 +49,7 @@
     const remote = showRemote ? " https:" : "";
     const csp =
       `default-src 'none'; img-src 'self' data:${remote}; style-src 'unsafe-inline'${remote}; ` +
-      `font-src data:${remote}; media-src 'none'; form-action 'none'`;
+      `font-src data:${remote}; media-src 'none'; form-action 'none'; base-uri 'none'`;
     return (
       `<!doctype html><html><head><meta charset="utf-8">` +
       `<meta http-equiv="Content-Security-Policy" content="${csp}">` +
diff --git a/src/web/components/ThreadList.svelte b/src/web/components/ThreadList.svelte
index 8b986a8..c998201 100644
--- a/src/web/components/ThreadList.svelte
+++ b/src/web/components/ThreadList.svelte
@@ -16,36 +16,39 @@
   let cursor = $state<string | null>(null);
   let loading = $state(false);
   let error = $state("");
+  /** Bumped on every reload; a response from an older one is dropped. */
+  let generation = 0;
 
   $effect(() => {
     // Reload when the folder, mailbox filter or session.version changes.
     const key = [folder, router.mailbox, session.version] as const;
-    let stale = false;
+    const gen = ++generation;
     loading = true;
     error = "";
     api
       .threads(key[0], key[1])
       .then((page) => {
-        if (stale) return;
+        if (gen !== generation) return;
         items = page.items;
         cursor = page.nextCursor;
       })
-      .catch((e: Error) => !stale && (error = e.message))
-      .finally(() => !stale && (loading = false));
-    return () => (stale = true);
+      .catch((e: Error) => gen === generation && (error = e.message))
+      .finally(() => gen === generation && (loading = false));
   });
 
   async function more() {
     if (!cursor) return;
+    const gen = generation;
     loading = true;
     try {
       const page = await api.threads(folder, router.mailbox, cursor);
+      if (gen !== generation) return;
       items = [...items, ...page.items];
       cursor = page.nextCursor;
     } catch (e) {
-      error = (e as Error).message;
+      if (gen === generation) error = (e as Error).message;
     } finally {
-      loading = false;
+      if (gen === generation) loading = false;
     }
   }
 
diff --git a/src/web/components/ThreadView.svelte b/src/web/components/ThreadView.svelte
index c7ed07b..dad042c 100644
--- a/src/web/components/ThreadView.svelte
+++ b/src/web/components/ThreadView.svelte
@@ -32,10 +32,16 @@
     confirming = null;
     api
       .thread(threadId)
-      .then(async (t) => {
+      .then((t) => {
         if (stale) return;
         thread = t;
-        if (t.messages.some((m) => !m.read)) changed((await api.markThread(threadId, true)).unread);
+        // Failing to mark it read shouldn't hide a thread that loaded fine.
+        if (t.messages.some((m) => !m.read)) {
+          api.markThread(threadId, true).then(
+            (r) => changed(r.unread),
+            (e: Error) => console.warn("Could not mark thread read", e),
+          );
+        }
       })
       .catch((e: Error) => !stale && (error = e.message));
     return () => (stale = true);
diff --git a/src/web/lib/format.ts b/src/web/lib/format.ts
index 51865d2..42c5701 100644
--- a/src/web/lib/format.ts
+++ b/src/web/lib/format.ts
@@ -22,9 +22,7 @@ export function displayName(addr: string): string {
   return name || addr.replace(/[<>]/g, "");
 }
 
+/** Splits on , ; and newlines, except inside quotes: "Doe, Jane" <[email protected]> stays whole. */
 export function splitList(raw: string): string[] {
-  return raw
-    .split(/[,;\n]/)
-    .map((s) => s.trim())
-    .filter(Boolean);
+  return (raw.match(/(?:"[^"]*"?|[^,;\n"])+/g) ?? []).map((s) => s.trim()).filter(Boolean);
 }
diff --git a/src/web/pages/Admin.svelte b/src/web/pages/Admin.svelte
index 7acaf68..ad10eb3 100644
--- a/src/web/pages/Admin.svelte
+++ b/src/web/pages/Admin.svelte
@@ -42,14 +42,21 @@
     return d.resend.sending ? "receiving + sending" : "receiving only; sending off in Resend";
   }
 
-  /** Runs a change, then refreshes this page and the user's own addresses. */
+  /**
+   * Runs a change, then refreshes this page and the user's own addresses,
+   * even if the change failed, so a checkbox or dropdown snaps back to what's
+   * really saved. The action's own error is the one shown.
+   */
   async function act(fn: () => Promise<unknown>) {
     error = "";
+    let failure = "";
     try {
       await fn();
-      await Promise.all([load(), loadSession()]);
     } catch (e) {
-      error = (e as Error).message;
+      failure = (e as Error).message;
+    } finally {
+      await Promise.all([load(), loadSession().catch(() => {})]);
+      if (failure) error = failure;
     }
   }
 
diff --git a/src/worker/middleware.ts b/src/worker/middleware.ts
index 6a4974a..b58eb0c 100644
--- a/src/worker/middleware.ts
+++ b/src/worker/middleware.ts
@@ -1,7 +1,7 @@
 import { createMiddleware } from "hono/factory";
 import { getCookie } from "hono/cookie";
 import { getUser } from "./services/directory";
-import { sessionUsername } from "./services/sessions";
+import { sessionIdentity } from "./services/sessions";
 
 export type AppEnv = {
   Bindings: Env;
@@ -25,11 +25,12 @@ export const sameOrigin = createMiddleware<AppEnv>(async (c, next) => {
 });
 
 export const requireUser = createMiddleware<AppEnv>(async (c, next) => {
-  const username = await sessionUsername(c.env, getCookie(c, "session"));
-  // A session outlives an admin deleting the user; the row is the authority.
-  const user = username ? await getUser(c.env, username) : null;
-  if (!user) return c.json({ error: "Unauthorized" }, 401);
-  c.set("user", user);
+  const identity = await sessionIdentity(c.env, getCookie(c, "session"));
+  // A session outlives an admin deleting the user, and the username may since
+  // belong to a different SSO account; the row, matched on sub, is the authority.
+  const user = identity ? await getUser(c.env, identity.username) : null;
+  if (!user || user.sub !== identity?.sub) return c.json({ error: "Unauthorized" }, 401);
+  c.set("user", { username: user.username, isAdmin: user.isAdmin });
   return next();
 });
 
diff --git a/src/worker/services/attachments.ts b/src/worker/services/attachments.ts
index ea51ee7..b2e8839 100644
--- a/src/worker/services/attachments.ts
+++ b/src/worker/services/attachments.ts
@@ -21,10 +21,15 @@ export interface AttachmentRecord {
   contentId: string | null;
 }
 
+/**
+ * Inserts nothing when messageId is set but that message doesn't exist, so
+ * it can be batched after a message insert that may have been a no-op.
+ */
 export function insertAttachmentStatement(env: Env, a: AttachmentRecord): D1PreparedStatement {
   return env.DB.prepare(
     "INSERT INTO attachments (id, owner, message_id, r2_key, filename, content_type, size, content_id, created_at) " +
-      "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING",
+      "SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9 " +
+      "WHERE ?3 IS NULL OR EXISTS (SELECT 1 FROM messages WHERE id = ?3) ON CONFLICT (id) DO NOTHING",
   ).bind(a.id, a.owner, a.messageId, a.r2Key, a.filename, a.contentType, a.size, a.contentId, Date.now());
 }
 
diff --git a/src/worker/services/directory.ts b/src/worker/services/directory.ts
index 190fb01..60c908a 100644
--- a/src/worker/services/directory.ts
+++ b/src/worker/services/directory.ts
@@ -71,27 +71,27 @@ function bootstrapAdmins(env: Env): Set<string> {
 export async function recordLogin(env: Env, tokens: TokenSet): Promise<void> {
   const username = tokens.username.toLowerCase();
   const ts = Date.now();
-  const existing = await env.DB.prepare("SELECT sub FROM users WHERE username = ?")
-    .bind(username)
-    .first<{ sub: string }>();
-
-  if (existing && existing.sub !== tokens.sub) {
-    throw new AccountConflict(`username ${username} already belongs to a different SSO account`);
-  }
-
   const admin = bootstrapAdmins(env).has(username) ? 1 : 0;
-  await env.DB.prepare(
+  // One statement, so two sign-ins racing can't both get past a separate check:
+  // an existing row is only touched when it's the same SSO account.
+  const res = await env.DB.prepare(
     "INSERT INTO users (username, sub, is_admin, created_at, last_login_at) VALUES (?, ?, ?, ?, ?) " +
       "ON CONFLICT (username) DO UPDATE SET last_login_at = excluded.last_login_at, " +
-      "is_admin = MAX(users.is_admin, excluded.is_admin)",
+      "is_admin = MAX(users.is_admin, excluded.is_admin) WHERE users.sub = excluded.sub",
   )
     .bind(username, tokens.sub, admin, ts, ts)
     .run();
+  if (res.meta.changes === 0) {
+    throw new AccountConflict(`username ${username} already belongs to a different SSO account`);
+  }
 }
 
-export async function getUser(env: Env, username: string): Promise<{ username: string; isAdmin: boolean } | null> {
-  const row = await env.DB.prepare("SELECT username, is_admin FROM users WHERE username = ?")
+export async function getUser(
+  env: Env,
+  username: string,
+): Promise<{ username: string; sub: string; isAdmin: boolean } | null> {
+  const row = await env.DB.prepare("SELECT username, sub, is_admin FROM users WHERE username = ?")
     .bind(username.toLowerCase())
-    .first<{ username: string; is_admin: number }>();
-  return row ? { username: row.username, isAdmin: row.is_admin === 1 } : null;
+    .first<{ username: string; sub: string; is_admin: number }>();
+  return row ? { username: row.username, sub: row.sub, isAdmin: row.is_admin === 1 } : null;
 }
diff --git a/src/worker/services/inbound.ts b/src/worker/services/inbound.ts
index 5c406f2..1a93d05 100644
--- a/src/worker/services/inbound.ts
+++ b/src/worker/services/inbound.ts
@@ -1,7 +1,7 @@
 import { bareAddress } from "../lib/address";
 import { cleanContentId, inboundKey, insertAttachmentStatement } from "./attachments";
 import { routeRecipients } from "./directory";
-import { insertMessage, resolveThread } from "./messages";
+import { insertMessageStatement, resolveThread } from "./messages";
 import { notifyUser } from "./push";
 import { resend } from "./resend";
 
@@ -63,42 +63,42 @@ export async function receiveEmail(env: Env, emailId: string): Promise<{ stored:
       sentAt,
     });
     const id = crypto.randomUUID();
-    const inserted = await insertMessage(env, threadId, {
-      id,
-      owner,
-      folder: "inbox",
-      mailbox,
-      resend_id: emailId,
-      message_id: email.message_id || null,
-      in_reply_to: inReplyTo,
-      refs,
-      from_addr: email.from,
-      to_addrs: JSON.stringify(email.to),
-      cc_addrs: JSON.stringify(email.cc ?? []),
-      subject: email.subject || "(no subject)",
-      html: email.html,
-      text: email.text,
-      sent_at: sentAt,
-      read: false,
-    });
-    if (!inserted) continue;
-
-    if (files.length) {
-      await env.DB.batch(
-        files.map((a) =>
-          insertAttachmentStatement(env, {
-            id: crypto.randomUUID(),
-            owner,
-            messageId: id,
-            r2Key: inboundKey(emailId, a.id),
-            filename: a.filename || "attachment",
-            contentType: a.content_type || "application/octet-stream",
-            size: a.size,
-            contentId: cleanContentId(a.content_id),
-          }),
-        ),
-      );
-    }
+    // One batch (one transaction), so a crash can't leave the message stored
+    // without its attachments for a retry to then skip. If this copy already
+    // exists the message insert is a no-op and so are the attachment inserts.
+    const [message] = await env.DB.batch([
+      insertMessageStatement(env, threadId, {
+        id,
+        owner,
+        folder: "inbox",
+        mailbox,
+        resend_id: emailId,
+        message_id: email.message_id || null,
+        in_reply_to: inReplyTo,
+        refs,
+        from_addr: email.from,
+        to_addrs: JSON.stringify(email.to),
+        cc_addrs: JSON.stringify(email.cc ?? []),
+        subject: email.subject || "(no subject)",
+        html: email.html,
+        text: email.text,
+        sent_at: sentAt,
+        read: false,
+      }),
+      ...files.map((a) =>
+        insertAttachmentStatement(env, {
+          id: crypto.randomUUID(),
+          owner,
+          messageId: id,
+          r2Key: inboundKey(emailId, a.id),
+          filename: a.filename || "attachment",
+          contentType: a.content_type || "application/octet-stream",
+          size: a.size,
+          contentId: cleanContentId(a.content_id),
+        }),
+      ),
+    ]);
+    if (!message?.meta.changes) continue;
     stored++;
 
     try {
diff --git a/src/worker/services/messages.ts b/src/worker/services/messages.ts
index 0b7cad4..847ac8c 100644
--- a/src/worker/services/messages.ts
+++ b/src/worker/services/messages.ts
@@ -133,7 +133,12 @@ export async function resolveThread(
 
 /** Returns false when this (resend_id, owner) copy was already stored. */
 export async function insertMessage(env: Env, threadId: string, m: NewMessage): Promise<boolean> {
-  const res = await env.DB.prepare(
+  return (await insertMessageStatement(env, threadId, m).run()).meta.changes > 0;
+}
+
+/** For batching with other writes; a no-op when this (resend_id, owner) copy already exists. */
+export function insertMessageStatement(env: Env, threadId: string, m: NewMessage): D1PreparedStatement {
+  return env.DB.prepare(
     "INSERT INTO messages (id, owner, thread_id, folder, mailbox, resend_id, message_id, in_reply_to, refs, " +
       "from_addr, to_addrs, cc_addrs, subject, snippet, html, text, sent_at, read) " +
       "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (resend_id, owner) DO NOTHING",
@@ -157,9 +162,7 @@ export async function insertMessage(env: Env, threadId: string, m: NewMessage):
       m.text,
       m.sent_at,
       m.read ? 1 : 0,
-    )
-    .run();
-  return res.meta.changes > 0;
+    );
 }
 
 export async function getMessageRow(env: Env, owner: string, id: string): Promise<MessageRow | null> {
diff --git a/src/worker/services/sessions.ts b/src/worker/services/sessions.ts
index 2b06f1b..aa24446 100644
--- a/src/worker/services/sessions.ts
+++ b/src/worker/services/sessions.ts
@@ -138,11 +138,16 @@ async function revalidate(env: Env, token: string, session: Session): Promise<Se
   return task;
 }
 
-export async function sessionUsername(env: Env, token: string | undefined): Promise<string | null> {
+/** Who a session belongs to: the username and the SSO account (sub) behind it. */
+export async function sessionIdentity(
+  env: Env,
+  token: string | undefined,
+): Promise<{ username: string; sub: string } | null> {
   if (!token) return null;
   const session = await readSession(env, token);
   if (!session) return null;
-  return (await revalidate(env, token, session))?.username ?? null;
+  const valid = await revalidate(env, token, session);
+  return valid ? { username: valid.username, sub: valid.sub } : null;
 }
 
 /** Deletes the session and hands back what's needed to end it at the SSO too. */