Dough Git

commit

Finish migrating

commit
c222cdaccb6b5eb3089ad950285e18e9197756a9
author
Clove Twilight <[email protected]>
date
2026-09-26 19:44

diff --git a/lib/attachments.ts b/lib/attachments.ts
index aa9f167..f09cfa5 100644
--- a/lib/attachments.ts
+++ b/lib/attachments.ts
@@ -1,4 +1,7 @@
-import { kv } from "./kv";
+import { db } from "./db";
+
+// D1 caps a row at 2 MB; stay well under it.
+const CHUNK_BYTES = 1_000_000;
 import type { StoredAttachment } from "./store";
 
 export async function saveAttachment(
@@ -12,7 +15,15 @@ export async function saveAttachment(
   const cid = normalizeContentId(contentId);
   const name = filename || "attachment";
   const type = contentType || "application/octet-stream";
-  await kv().put(`att:${id}`, bytes);
+  const inserts = [];
+  for (let idx = 0, off = 0; off < bytes.length || idx === 0; idx++, off += CHUNK_BYTES) {
+    inserts.push(
+      db()
+        .prepare("INSERT INTO attachment_chunks (attachment_id, idx, data) VALUES (?, ?, ?)")
+        .bind(id, idx, bytes.subarray(off, off + CHUNK_BYTES)),
+    );
+  }
+  await db().batch(inserts);
   return { id, filename: name, contentType: type, size: bytes.length, contentId: cid };
 }
 
@@ -35,13 +46,24 @@ export function normalizeContentId(raw: unknown): string | null {
 
 export async function readAttachment(attachmentId: string): Promise<Uint8Array | null> {
   if (!attachmentId) return null;
-  const buf = await kv().get(`att:${attachmentId}`, "arrayBuffer");
-  return buf ? new Uint8Array(buf) : null;
+  const { results } = await db()
+    .prepare("SELECT data FROM attachment_chunks WHERE attachment_id = ? ORDER BY idx")
+    .bind(attachmentId)
+    .all<{ data: ArrayBuffer | number[] }>();
+  if (results.length === 0) return null;
+  const parts = results.map((r) => new Uint8Array(r.data));
+  const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+  let off = 0;
+  for (const p of parts) {
+    out.set(p, off);
+    off += p.length;
+  }
+  return out;
 }
 
 export async function deleteAttachment(attachmentId: string): Promise<void> {
   if (!attachmentId) return;
-  await kv().delete(`att:${attachmentId}`);
+  await db().prepare("DELETE FROM attachment_chunks WHERE attachment_id = ?").bind(attachmentId).run();
 }
 
 export async function toResendAttachment(
diff --git a/lib/auth.ts b/lib/auth.ts
index a721fa2..cdd69c3 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -1,7 +1,7 @@
-import { kv } from "./kv";
+import { db } from "./db";
 import { GrantRejected, refreshSession, type Pending, type TokenSet } from "./oidc";
 
-// Sessions live in KV so they can be ended from the server side, and each one
+// Sessions live in D1 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.
@@ -24,20 +24,24 @@ interface Session {
 
 const now = () => Math.floor(Date.now() / 1000);
 
-function sessionKey(token: string): string {
-  return `session:${token}`;
+async function deleteSession(token: string): Promise<void> {
+  await db().prepare("DELETE FROM sessions WHERE token = ?").bind(token).run();
 }
 
 async function readSession(token: string): Promise<Session | null> {
-  const raw = await kv().get(sessionKey(token));
-  if (!raw) return null;
+  const row = await db()
+    .prepare("SELECT data FROM sessions WHERE token = ? AND expires_at > ?")
+    .bind(token, now())
+    .first<{ data: string }>();
+  if (!row) return null;
+  const raw = row.data;
   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));
+  await deleteSession(token);
   return null;
 }
 
@@ -45,15 +49,31 @@ 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));
+    await deleteSession(token);
     return;
   }
-  await kv().put(sessionKey(token), JSON.stringify(session), { expirationTtl: remaining });
+  await db()
+    .prepare(
+      "INSERT INTO sessions (token, data, expires_at) VALUES (?, ?, ?) " +
+        "ON CONFLICT (token) DO UPDATE SET data = excluded.data, expires_at = excluded.expires_at",
+    )
+    .bind(token, JSON.stringify(session), now() + remaining)
+    .run();
+}
+
+// D1 has no TTLs, so expired rows are swept whenever someone signs in.
+async function sweepExpired(): Promise<void> {
+  const ts = now();
+  await db().batch([
+    db().prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(ts),
+    db().prepare("DELETE FROM pending_logins WHERE expires_at <= ?").bind(ts),
+  ]);
 }
 
 export async function createSession(tokens: TokenSet): Promise<string> {
   const token = crypto.randomUUID();
   const ts = now();
+  await sweepExpired();
   await writeSession(token, {
     username: tokens.username,
     sub: tokens.sub,
@@ -76,7 +96,7 @@ async function revalidate(token: string, session: Session): Promise<Session | nu
   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));
+    await deleteSession(token);
     return null;
   }
 
@@ -90,7 +110,7 @@ async function revalidate(token: string, session: Session): Promise<Session | nu
     try {
       const fresh = await refreshSession(session.refreshToken!);
       if (fresh.sub && fresh.sub !== session.sub) {
-        await kv().delete(sessionKey(token));
+        await deleteSession(token);
         return null;
       }
       const at = now();
@@ -105,12 +125,12 @@ async function revalidate(token: string, session: Session): Promise<Session | nu
       return updated;
     } catch (err) {
       if (err instanceof GrantRejected) {
-        await kv().delete(sessionKey(token));
+        await deleteSession(token);
         return null;
       }
       console.warn("could not reach the SSO to re-check a session", err);
       if (overdue) {
-        await kv().delete(sessionKey(token));
+        await deleteSession(token);
         return null;
       }
       const updated = { ...session, checkedAt: now() };
@@ -140,20 +160,25 @@ export async function destroySession(
 ): Promise<{ refreshToken: string | null; idToken: string | null } | null> {
   if (!token) return null;
   const session = await readSession(token);
-  await kv().delete(sessionKey(token));
+  await deleteSession(token);
   return session ? { refreshToken: session.refreshToken, idToken: session.idToken } : null;
 }
 
 export async function savePending(p: Pending): Promise<string> {
   const id = crypto.randomUUID();
-  await kv().put(`pending:${id}`, JSON.stringify(p), { expirationTtl: PENDING_TTL_S });
+  await db()
+    .prepare("INSERT INTO pending_logins (id, data, expires_at) VALUES (?, ?, ?)")
+    .bind(id, JSON.stringify(p), now() + PENDING_TTL_S)
+    .run();
   return id;
 }
 
 export async function takePending(id: string | undefined): Promise<Pending | null> {
   if (!id) return null;
-  const raw = await kv().get(`pending:${id}`, "json");
-  if (!raw) return null;
-  await kv().delete(`pending:${id}`);
-  return raw as Pending;
+  const row = await db()
+    .prepare("DELETE FROM pending_logins WHERE id = ? RETURNING data, expires_at")
+    .bind(id)
+    .first<{ data: string; expires_at: number }>();
+  if (!row || row.expires_at <= now()) return null;
+  return JSON.parse(row.data) as Pending;
 }
diff --git a/lib/db.ts b/lib/db.ts
new file mode 100644
index 0000000..152fb2e
--- /dev/null
+++ b/lib/db.ts
@@ -0,0 +1,31 @@
+export interface Env {
+  email_db: D1Database;
+  ASSETS: Fetcher;
+}
+
+let current: Env | null = null;
+
+export function setEnv(e: Env): void {
+  current = e;
+}
+
+export function env(): Env {
+  if (!current) throw new Error("Worker env not initialised");
+  return current;
+}
+
+export function db(): D1Database {
+  return env().email_db;
+}
+
+export async function getConfig<T>(key: string): Promise<T | null> {
+  const row = await db().prepare("SELECT value FROM config WHERE key = ?").bind(key).first<{ value: string }>();
+  return row ? (JSON.parse(row.value) as T) : null;
+}
+
+export async function putConfig(key: string, value: unknown): Promise<void> {
+  await db()
+    .prepare("INSERT INTO config (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
+    .bind(key, JSON.stringify(value))
+    .run();
+}
diff --git a/lib/kv.ts b/lib/kv.ts
deleted file mode 100644
index 8be8558..0000000
--- a/lib/kv.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-export interface Env {
-  MAILBOX_KV: KVNamespace;
-  ASSETS: Fetcher;
-}
-
-let current: Env | null = null;
-
-export function setEnv(e: Env): void {
-  current = e;
-}
-
-export function env(): Env {
-  if (!current) throw new Error("Worker env not initialised");
-  return current;
-}
-
-export function kv(): KVNamespace {
-  return env().MAILBOX_KV;
-}
-
-export async function hashKey(input: string): Promise<string> {
-  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
-  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
-}
-
-export async function listNames(prefix: string): Promise<string[]> {
-  const out: string[] = [];
-  let cursor: string | undefined;
-  do {
-    const res: KVNamespaceListResult<unknown> = await kv().list({ prefix, cursor, limit: 1000 });
-    for (const k of res.keys) out.push(k.name);
-    cursor = res.list_complete ? undefined : res.cursor;
-  } while (cursor);
-  return out;
-}
diff --git a/lib/owners.ts b/lib/owners.ts
index 146101e..31fee02 100644
--- a/lib/owners.ts
+++ b/lib/owners.ts
@@ -1,4 +1,4 @@
-import { kv } from "./kv";
+import { getConfig, putConfig } from "./db";
 import { bareAddress } from "./settings";
 import ownersSeed from "../owners.json";
 
@@ -38,11 +38,11 @@ function state(): OwnersConfig {
 
 async function save(): Promise<void> {
   const s = state();
-  await kv().put("owners:config", JSON.stringify(s));
+  await putConfig("owners", s);
 }
 
 export async function initOwners(): Promise<void> {
-  const stored = (await kv().get("owners:config", "json")) as Partial<OwnersConfig> | null;
+  const stored = await getConfig<Partial<OwnersConfig>>("owners");
   if (stored) {
     cfg = normalize(stored);
     // The domain always comes from owners.json, so changing it there migrates
@@ -62,7 +62,7 @@ export async function initOwners(): Promise<void> {
     return;
   }
   cfg = loadSeed();
-  await kv().put("owners:config", JSON.stringify(cfg));
+  await putConfig("owners", cfg);
 }
 
 function expand(entry: string): string {
diff --git a/lib/push.ts b/lib/push.ts
index 4f257a4..ec6cc31 100644
--- a/lib/push.ts
+++ b/lib/push.ts
@@ -1,4 +1,4 @@
-import { kv, hashKey, listNames } from "./kv";
+import { db } from "./db";
 import { sendWebPush, type PushSubscription, type VapidKeys } from "./webpush";
 
 function vapid(): VapidKeys {
@@ -28,21 +28,27 @@ function isSubscription(x: unknown): x is PushSubscription {
 
 export async function addSubscription(sub: PushSubscription): Promise<void> {
   if (!isSubscription(sub)) throw new Error("Invalid subscription");
-  await kv().put(`push:${await hashKey(sub.endpoint)}`, JSON.stringify(sub));
+  await db()
+    .prepare(
+      "INSERT INTO push_subscriptions (endpoint, data) VALUES (?, ?) " +
+        "ON CONFLICT (endpoint) DO UPDATE SET data = excluded.data",
+    )
+    .bind(sub.endpoint, JSON.stringify(sub))
+    .run();
 }
 
 export async function removeSubscription(endpoint: string): Promise<void> {
-  await kv().delete(`push:${await hashKey(endpoint)}`);
+  await db().prepare("DELETE FROM push_subscriptions WHERE endpoint = ?").bind(endpoint).run();
 }
 
 export async function listSubscriptions(): Promise<PushSubscription[]> {
-  const names = await listNames("push:");
-  const rows = await Promise.all(names.map((n) => kv().get(n, "json")));
-  return rows.filter(isSubscription);
+  const { results } = await db().prepare("SELECT data FROM push_subscriptions").all<{ data: string }>();
+  return results.map((r) => JSON.parse(r.data) as unknown).filter(isSubscription);
 }
 
 export async function subscriptionCount(): Promise<number> {
-  return (await listNames("push:")).length;
+  const row = await db().prepare("SELECT COUNT(*) AS n FROM push_subscriptions").first<{ n: number }>();
+  return row?.n ?? 0;
 }
 
 export async function sendToAll(payload: PushPayload): Promise<{ sent: number; pruned: number }> {
diff --git a/lib/settings.ts b/lib/settings.ts
index 947f361..55a0e33 100644
--- a/lib/settings.ts
+++ b/lib/settings.ts
@@ -1,4 +1,4 @@
-import { kv } from "./kv";
+import { getConfig, putConfig } from "./db";
 
 export type Settings = {
   fromAddresses: string[];
@@ -61,7 +61,7 @@ function normalize(raw: unknown): Settings {
 }
 
 export async function getSettings(): Promise<Settings> {
-  const raw = await kv().get("settings", "json");
+  const raw = await getConfig<unknown>("settings");
   return raw ? normalize(raw) : seedFromEnv();
 }
 
@@ -69,7 +69,7 @@ async function mutate(fn: (s: Settings) => void): Promise<Settings> {
   const s = await getSettings();
   fn(s);
   const next = normalize(s);
-  await kv().put("settings", JSON.stringify(next));
+  await putConfig("settings", next);
   return next;
 }
 
diff --git a/lib/store.ts b/lib/store.ts
index 88377d6..7a0f467 100644
--- a/lib/store.ts
+++ b/lib/store.ts
@@ -1,4 +1,4 @@
-import { kv, hashKey, listNames } from "./kv";
+import { db } from "./db";
 import { deleteAttachment } from "./attachments";
 
 export type StoredAttachment = {
@@ -27,8 +27,12 @@ export type StoredEmail = {
   references: string | null;
   threadKey: string;
   owner: string;
+  read: boolean;
 };
 
+// Outbound mail and drafts are read from the start; inbound mail starts unread.
+export type NewEmail = Omit<StoredEmail, "read"> & { read?: boolean };
+
 export type DraftInput = {
   to: string[];
   subject: string;
@@ -41,112 +45,164 @@ export type DraftInput = {
   owner: string;
 };
 
-type Rec = StoredEmail & { _seq: string; _inv: string };
+type Row = {
+  id: string;
+  owner: string;
+  folder: Folder;
+  from_addr: string;
+  to_addrs: string;
+  subject: string;
+  html: string | null;
+  text: string | null;
+  received_at: string;
+  attachments: string;
+  direction: StoredEmail["direction"];
+  status: StoredEmail["status"];
+  message_id: string | null;
+  in_reply_to: string | null;
+  refs: string | null;
+  thread_key: string;
+  read: number;
+};
 
-const EPOCH_CAP = 10_000_000_000_000;
+const COLUMNS =
+  "id, owner, folder, from_addr, to_addrs, subject, html, text, received_at, attachments, " +
+  "direction, status, message_id, in_reply_to, refs, thread_key, read";
 
 export function folderOf(email: Pick<StoredEmail, "direction" | "status">): Folder {
   if (email.status === "draft") return "drafts";
   return email.direction === "inbound" ? "inbox" : "sent";
 }
 
-function newOrder(): { seq: string; inv: string } {
-  const ms = Date.now();
-  const rand = crypto.randomUUID().replace(/-/g, "").slice(0, 8);
+function toEmail(row: Row): StoredEmail {
   return {
-    seq: `${String(ms).padStart(13, "0")}-${rand}`,
-    inv: `${String(EPOCH_CAP - ms).padStart(13, "0")}-${rand}`,
+    id: row.id,
+    from: row.from_addr,
+    to: JSON.parse(row.to_addrs) as string[],
+    subject: row.subject,
+    html: row.html,
+    text: row.text,
+    receivedAt: row.received_at,
+    attachments: JSON.parse(row.attachments) as StoredAttachment[],
+    direction: row.direction,
+    status: row.status,
+    messageId: row.message_id,
+    inReplyTo: row.in_reply_to,
+    references: row.refs,
+    threadKey: row.thread_key,
+    owner: row.owner,
+    read: row.read !== 0,
   };
 }
 
-function toEmail(rec: Rec): StoredEmail {
-  const { _seq, _inv, ...rest } = rec;
-  return rest;
+async function readRow(id: string): Promise<Row | null> {
+  return db().prepare(`SELECT ${COLUMNS} FROM emails WHERE id = ?`).bind(id).first<Row>();
 }
 
-async function readRecord(id: string): Promise<Rec | null> {
-  return (await kv().get(`email:${id}`, "json")) as Rec | null;
+async function deleteRows(ids: string[]): Promise<void> {
+  if (ids.length === 0) return;
+  await db().batch(ids.map((id) => db().prepare("DELETE FROM emails WHERE id = ?").bind(id)));
 }
 
-async function writeIndexes(rec: Rec): Promise<void> {
-  const jobs: Promise<unknown>[] = [
-    kv().put(`ix:f:${folderOf(rec)}:${rec._inv}:${rec.id}`, ""),
-    hashKey(rec.threadKey).then((h) => kv().put(`ix:t:${h}:${rec._seq}:${rec.id}`, "")),
-  ];
-  if (rec.messageId) {
-    jobs.push(hashKey(rec.messageId).then((h) => kv().put(`ix:m:${h}`, rec.id)));
-  }
-  await Promise.all(jobs);
+export async function addEmail(input: NewEmail): Promise<StoredEmail> {
+  const email: StoredEmail = { ...input, read: input.read ?? input.direction !== "inbound" };
+  const res = await db()
+    .prepare(
+      `INSERT INTO emails (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ` +
+        "ON CONFLICT (id) DO NOTHING",
+    )
+    .bind(
+      email.id,
+      email.owner,
+      folderOf(email),
+      email.from,
+      JSON.stringify(email.to),
+      email.subject,
+      email.html,
+      email.text,
+      email.receivedAt,
+      JSON.stringify(email.attachments),
+      email.direction,
+      email.status,
+      email.messageId,
+      email.inReplyTo,
+      email.references,
+      email.threadKey,
+      email.read ? 1 : 0,
+    )
+    .run();
+  if (res.meta.changes > 0) return email;
+
+  const existing = await readRow(email.id);
+  return existing ? toEmail(existing) : email;
 }
 
-async function deleteIndexes(rec: Rec): Promise<void> {
-  const jobs: Promise<unknown>[] = [
-    kv().delete(`ix:f:${folderOf(rec)}:${rec._inv}:${rec.id}`),
-    hashKey(rec.threadKey).then((h) => kv().delete(`ix:t:${h}:${rec._seq}:${rec.id}`)),
-  ];
-  if (rec.messageId) {
-    jobs.push(hashKey(rec.messageId).then((h) => kv().delete(`ix:m:${h}`)));
+// Newest first within each folder; with no folder given, folders come back in
+// alphabetical order (drafts, inbox, sent).
+export async function listEmails(folder?: Folder, owner?: string) {
+  const where: string[] = [];
+  const params: string[] = [];
+  if (folder) {
+    where.push("folder = ?");
+    params.push(folder);
+  }
+  if (owner) {
+    where.push("owner = ?");
+    params.push(owner);
   }
-  await Promise.all(jobs);
-}
 
-function idFromKey(name: string): string {
-  return name.slice(name.lastIndexOf(":") + 1);
+  const sql =
+    `SELECT ${COLUMNS} FROM emails` +
+    (where.length ? ` WHERE ${where.join(" AND ")}` : "") +
+    " ORDER BY folder, seq DESC";
+  const { results } = await db()
+    .prepare(sql)
+    .bind(...params)
+    .all<Row>();
+
+  return results.map((row) => {
+    const { html, text, ...meta } = toEmail(row);
+    return meta;
+  });
 }
 
-export async function addEmail(email: StoredEmail): Promise<StoredEmail> {
-  const existing = await readRecord(email.id);
-  if (existing) return toEmail(existing);
-
-  const { seq, inv } = newOrder();
-  const rec: Rec = { ...email, _seq: seq, _inv: inv };
-  await kv().put(`email:${email.id}`, JSON.stringify(rec));
-  await writeIndexes(rec);
-  return email;
+export async function getEmail(id: string): Promise<StoredEmail | null> {
+  const row = await readRow(id);
+  return row ? toEmail(row) : null;
 }
 
-export async function listEmails(folder?: Folder, owner?: string) {
-  const prefixes = folder
-    ? [`ix:f:${folder}:`]
-    : ["ix:f:inbox:", "ix:f:sent:", "ix:f:drafts:"];
-
-  const names: string[] = [];
-  for (const p of prefixes) names.push(...(await listNames(p)));
-  names.sort();
-
-  const key = owner?.toLowerCase() ?? null;
-  const records = await Promise.all(names.map((n) => readRecord(idFromKey(n))));
-
-  const out = [];
-  for (const rec of records) {
-    if (!rec) continue;
-    if (key && rec.owner.toLowerCase() !== key) continue;
-    const { html, text, _seq, _inv, ...meta } = rec;
-    out.push(meta);
-  }
-  return out;
+export async function findByMessageId(messageId: string): Promise<StoredEmail | null> {
+  const row = await db()
+    .prepare(`SELECT ${COLUMNS} FROM emails WHERE message_id = ? ORDER BY seq DESC LIMIT 1`)
+    .bind(messageId)
+    .first<Row>();
+  return row ? toEmail(row) : null;
 }
 
-export async function getEmail(id: string): Promise<StoredEmail | null> {
-  const rec = await readRecord(id);
-  return rec ? toEmail(rec) : null;
+async function rowsInThread(threadKey: string, owner?: string): Promise<Row[]> {
+  const sql = owner
+    ? `SELECT ${COLUMNS} FROM emails WHERE thread_key = ? AND owner = ? ORDER BY received_at`
+    : `SELECT ${COLUMNS} FROM emails WHERE thread_key = ? ORDER BY received_at`;
+  const stmt = owner ? db().prepare(sql).bind(threadKey, owner) : db().prepare(sql).bind(threadKey);
+  return (await stmt.all<Row>()).results;
 }
 
-export async function findByMessageId(messageId: string): Promise<StoredEmail | null> {
-  const id = await kv().get(`ix:m:${await hashKey(messageId)}`);
-  return id ? getEmail(id) : null;
+export async function listByThreadKey(threadKey: string, owner?: string): Promise<StoredEmail[]> {
+  return (await rowsInThread(threadKey, owner)).map(toEmail);
 }
 
-export async function listByThreadKey(threadKey: string, owner?: string): Promise<StoredEmail[]> {
-  const names = await listNames(`ix:t:${await hashKey(threadKey)}:`);
-  const ids = [...new Set(names.map(idFromKey))];
-  const key = owner?.toLowerCase() ?? null;
-  const records = await Promise.all(ids.map(readRecord));
+export async function unreadCount(owner?: string): Promise<number> {
+  const stmt = owner
+    ? db().prepare("SELECT COUNT(*) AS n FROM emails WHERE folder = 'inbox' AND read = 0 AND owner = ?").bind(owner)
+    : db().prepare("SELECT COUNT(*) AS n FROM emails WHERE folder = 'inbox' AND read = 0");
+  return (await stmt.first<{ n: number }>())?.n ?? 0;
+}
 
-  return records
-    .filter((rec): rec is Rec => !!rec && (!key || rec.owner.toLowerCase() === key))
-    .sort((a, b) => a.receivedAt.localeCompare(b.receivedAt))
-    .map(toEmail);
+export async function setRead(ids: string[], read: boolean): Promise<void> {
+  if (ids.length === 0) return;
+  await db().batch(
+    ids.map((id) => db().prepare("UPDATE emails SET read = ? WHERE id = ?").bind(read ? 1 : 0, id)),
+  );
 }
 
 export async function createDraft(input: DraftInput): Promise<StoredEmail> {
@@ -166,67 +222,76 @@ export async function createDraft(input: DraftInput): Promise<StoredEmail> {
     references: input.references ?? null,
     threadKey: input.threadKey ?? `draft::${crypto.randomUUID()}`,
     owner: input.owner,
+    read: true,
   };
   await addEmail(draft);
   return draft;
 }
 
 export async function updateDraft(id: string, input: DraftInput): Promise<StoredEmail | null> {
-  const rec = await readRecord(id);
-  if (!rec || rec.status !== "draft") return null;
+  const row = await readRow(id);
+  if (!row || row.status !== "draft") return null;
+  const current = toEmail(row);
 
   const keep = new Set(input.attachments.map((a) => a.id).filter(Boolean));
   await Promise.all(
-    rec.attachments
+    current.attachments
       .filter((a) => a.id && !keep.has(a.id))
       .map((a) => deleteAttachment(a.id)),
   );
 
-  const updated: Rec = {
-    ...rec,
-    from: input.from ?? rec.from,
+  const updated: StoredEmail = {
+    ...current,
+    from: input.from ?? current.from,
     to: input.to,
     subject: input.subject,
     html: input.html,
     attachments: input.attachments,
     receivedAt: new Date().toISOString(),
   };
-  await kv().put(`email:${id}`, JSON.stringify(updated));
-  return toEmail(updated);
+  await db()
+    .prepare(
+      "UPDATE emails SET from_addr = ?, to_addrs = ?, subject = ?, html = ?, attachments = ?, received_at = ? " +
+        "WHERE id = ?",
+    )
+    .bind(
+      updated.from,
+      JSON.stringify(updated.to),
+      updated.subject,
+      updated.html,
+      JSON.stringify(updated.attachments),
+      updated.receivedAt,
+      id,
+    )
+    .run();
+  return updated;
 }
 
 export async function deleteDraft(id: string): Promise<boolean> {
-  const rec = await readRecord(id);
-  if (!rec || rec.status !== "draft") return false;
-  await deleteIndexes(rec);
-  await kv().delete(`email:${id}`);
-  return true;
+  const res = await db().prepare("DELETE FROM emails WHERE id = ? AND status = 'draft'").bind(id).run();
+  return res.meta.changes > 0;
 }
 
 export async function deleteEmail(id: string): Promise<StoredEmail | null> {
-  const rec = await readRecord(id);
-  if (!rec) return null;
-  await deleteIndexes(rec);
-  await kv().delete(`email:${id}`);
-  return toEmail(rec);
+  const row = await db()
+    .prepare(`DELETE FROM emails WHERE id = ? RETURNING ${COLUMNS}`)
+    .bind(id)
+    .first<Row>();
+  return row ? toEmail(row) : null;
 }
 
 export async function deleteByThreadKey(threadKey: string): Promise<StoredEmail[]> {
-  const names = await listNames(`ix:t:${await hashKey(threadKey)}:`);
-  const ids = [...new Set(names.map(idFromKey))];
-  const records = (await Promise.all(ids.map(readRecord))).filter((rec): rec is Rec => !!rec);
-  if (records.length === 0) return [];
-
-  await Promise.all(
-    records.flatMap((rec) => [deleteIndexes(rec), kv().delete(`email:${rec.id}`)]),
-  );
-  return records.map(toEmail);
+  const rows = await rowsInThread(threadKey);
+  await deleteRows(rows.map((r) => r.id));
+  return rows.map(toEmail);
 }
 
 // Every message (inbox, sent, drafts) belonging to one mailbox user. Used by the
 // admin "delete user" flow, which wipes a user's mail before removing the user.
 export async function deleteByOwner(owner: string): Promise<StoredEmail[]> {
-  const metas = await listEmails(undefined, owner);
-  const removed = await Promise.all(metas.map((m) => deleteEmail(m.id)));
-  return removed.filter((r): r is StoredEmail => r !== null);
+  const { results } = await db()
+    .prepare(`DELETE FROM emails WHERE owner = ? RETURNING ${COLUMNS}`)
+    .bind(owner)
+    .all<Row>();
+  return results.map(toEmail);
 }
diff --git a/migrations/0001_init.sql b/migrations/0001_init.sql
new file mode 100644
index 0000000..98f8244
--- /dev/null
+++ b/migrations/0001_init.sql
@@ -0,0 +1,59 @@
+-- Messages in every folder. `seq` keeps insertion order, which is what the
+-- folder listings sort by (a draft's received_at moves on every save).
+CREATE TABLE emails (
+  seq INTEGER PRIMARY KEY AUTOINCREMENT,
+  id TEXT NOT NULL UNIQUE,
+  owner TEXT NOT NULL COLLATE NOCASE,
+  folder TEXT NOT NULL,
+  from_addr TEXT NOT NULL,
+  to_addrs TEXT NOT NULL,
+  subject TEXT NOT NULL,
+  html TEXT,
+  text TEXT,
+  received_at TEXT NOT NULL,
+  attachments TEXT NOT NULL,
+  direction TEXT NOT NULL,
+  status TEXT NOT NULL,
+  message_id TEXT,
+  in_reply_to TEXT,
+  refs TEXT,
+  thread_key TEXT NOT NULL,
+  read INTEGER NOT NULL DEFAULT 0
+);
+CREATE INDEX emails_folder ON emails (folder, seq);
+CREATE INDEX emails_owner ON emails (owner, folder, seq);
+CREATE INDEX emails_unread ON emails (owner, folder) WHERE read = 0;
+CREATE INDEX emails_thread ON emails (thread_key);
+CREATE INDEX emails_message_id ON emails (message_id) WHERE message_id IS NOT NULL;
+
+-- D1 caps a row at 2 MB, so attachment bytes are split across chunks.
+CREATE TABLE attachment_chunks (
+  attachment_id TEXT NOT NULL,
+  idx INTEGER NOT NULL,
+  data BLOB NOT NULL,
+  PRIMARY KEY (attachment_id, idx)
+);
+
+CREATE TABLE sessions (
+  token TEXT PRIMARY KEY,
+  data TEXT NOT NULL,
+  expires_at INTEGER NOT NULL
+);
+CREATE INDEX sessions_expiry ON sessions (expires_at);
+
+CREATE TABLE pending_logins (
+  id TEXT PRIMARY KEY,
+  data TEXT NOT NULL,
+  expires_at INTEGER NOT NULL
+);
+
+CREATE TABLE push_subscriptions (
+  endpoint TEXT PRIMARY KEY,
+  data TEXT NOT NULL
+);
+
+-- Singleton JSON documents: "settings" and "owners".
+CREATE TABLE config (
+  key TEXT PRIMARY KEY,
+  value TEXT NOT NULL
+);
diff --git a/public/app.js b/public/app.js
index f59ed68..38aa311 100644
--- a/public/app.js
+++ b/public/app.js
@@ -23,6 +23,8 @@ const lightboxImg = document.getElementById("lightboxImg");
 const fromRow = document.getElementById("fromRow");
 const fromSelect = composeForm.from;
 const toastHost = document.getElementById("toastHost");
+const inboxNavBtn = folderNav.querySelector('[data-folder="inbox"]');
+const BASE_TITLE = document.title;
 
 let emails = [];
 let activeId = null;
@@ -192,6 +194,39 @@ async function loadEmails(folder = activeFolder) {
   const res = await fetch(`/api/emails?folder=${encodeURIComponent(folder)}`);
   emails = await res.json();
   renderList();
+  loadUnreadCount();
+}
+
+// The browser tab reads "(3) Inbox" and the Inbox folder button "Inbox (3)"
+// while anything in the inbox is unread.
+function showUnreadCount(count) {
+  document.title = count > 0 ? `(${count}) ${BASE_TITLE}` : BASE_TITLE;
+  inboxNavBtn.textContent = count > 0 ? `Inbox (${count})` : "Inbox";
+}
+
+async function loadUnreadCount() {
+  try {
+    const res = await fetch("/api/emails/unread");
+    if (res.ok) showUnreadCount((await res.json()).count);
+  } catch (_) {
+    /* Keep whatever count is showing; the next poll will try again. */
+  }
+}
+
+async function setThreadRead(id, read) {
+  const res = await fetch(`/api/emails/${id}/thread/read`, {
+    method: "POST",
+    headers: { "Content-Type": "application/json" },
+    body: JSON.stringify({ read }),
+  });
+  if (!res.ok) return;
+  const ids = new Set(currentThread.map((m) => m.id));
+  ids.add(id);
+  for (const e of emails) {
+    if (ids.has(e.id) && e.direction === "inbound") e.read = read;
+  }
+  renderList();
+  showUnreadCount((await res.json()).count);
 }
 
 function renderList() {
@@ -204,7 +239,8 @@ function renderList() {
   listEl.innerHTML = visible
     .map(
       (e) => `
-      <div class="list-item ${e.id === activeId ? "active" : ""}" data-id="${e.id}">
+      <div class="list-item ${e.id === activeId ? "active" : ""} ${e.read === false ? "unread" : ""}" data-id="${e.id}">
+        <span class="unread-dot" aria-label="${e.read === false ? "Unread" : ""}"></span>
         <div class="list-item-main">
           <div class="from">${escapeHtml(activeFolder === "drafts" ? (e.to || []).join(", ") || "(no recipient)" : e.from)}</div>
           <div class="subject">${escapeHtml(e.subject || "(no subject)")}</div>
@@ -284,6 +320,7 @@ async function openEmail(id) {
   const thread = await res.json();
   currentThread = thread;
   const last = thread[thread.length - 1];
+  if (thread.some((m) => m.read === false)) setThreadRead(id, true);
 
   const messagesHtml = thread
     .map(
@@ -310,6 +347,7 @@ async function openEmail(id) {
     <div class="thread-actions">
       <button class="btn-accent" id="replyBtn">Reply</button>
       <button class="btn-ghost" id="forwardBtn">Forward</button>
+      ${thread.some((m) => m.direction === "inbound") ? '<button class="btn-ghost" id="markUnreadBtn">Mark unread</button>' : ""}
       <button class="btn-danger" id="deleteThreadBtn">Delete conversation</button>
     </div>
   `;
@@ -317,6 +355,10 @@ async function openEmail(id) {
   document.getElementById("replyBtn").addEventListener("click", () => openReply(last));
   document.getElementById("forwardBtn").addEventListener("click", () => openForward(last));
   document.getElementById("deleteThreadBtn").addEventListener("click", () => deleteThread(id));
+  document.getElementById("markUnreadBtn")?.addEventListener("click", async () => {
+    await setThreadRead(id, false);
+    closeDetail();
+  });
 
   detailEl.querySelectorAll(".msg-delete").forEach((btn) => {
     btn.addEventListener("click", () => deleteMessage(btn.dataset.id));
diff --git a/public/style.css b/public/style.css
index 90d9ea1..9623a36 100644
--- a/public/style.css
+++ b/public/style.css
@@ -254,6 +254,23 @@ body::after {
   margin-top: 0.15rem;
 }
 
+.unread-dot {
+  flex: 0 0 auto;
+  width: 0.5rem;
+  height: 0.5rem;
+  border-radius: 50%;
+  background: transparent;
+}
+
+.list-item.unread .unread-dot {
+  background: var(--pink);
+}
+
+.list-item.unread .subject {
+  color: var(--text);
+  font-weight: 700;
+}
+
 .list-item .time {
   color: var(--overlay0);
   font-size: 0.75rem;
diff --git a/server.ts b/server.ts
index 6a59117..8369078 100644
--- a/server.ts
+++ b/server.ts
@@ -12,6 +12,8 @@ import {
   deleteEmail,
   deleteByThreadKey,
   deleteByOwner,
+  unreadCount,
+  setRead,
   type Folder,
   type StoredEmail,
   type StoredAttachment,
@@ -62,7 +64,7 @@ import {
   subscriptionCount,
   sendToAll,
 } from "./lib/push";
-import { setEnv, env, type Env } from "./lib/kv";
+import { setEnv, env, type Env } from "./lib/db";
 import type { PushSubscription } from "./lib/webpush";
 
 type UploadedAttachment = { filename: string; contentType: string; content: string };
@@ -398,6 +400,12 @@ app.get("/api/emails", async (c) => {
   return c.json(emails);
 });
 
+// Registered before /api/emails/:id so "unread" isn't taken for an id.
+app.get("/api/emails/unread", async (c) => {
+  const user = c.get("user");
+  return c.json({ count: await unreadCount(isAdmin(user) ? undefined : user) });
+});
+
 app.get("/api/emails/:id/attachments/:attachmentId", async (c) => {
   const email = await getEmail(c.req.param("id"));
   if (!email || !canAccessOwner(c.get("user"), email.owner)) {
@@ -607,6 +615,23 @@ app.get("/api/emails/:id/thread", async (c) => {
   return c.json(thread.map(inlineCidImages));
 });
 
+// Opening a conversation marks all of it read; "Mark unread" flips it back.
+app.post("/api/emails/:id/thread/read", async (c) => {
+  const user = c.get("user");
+  const original = await getEmail(c.req.param("id"));
+  if (!original || !canAccessOwner(user, original.owner)) {
+    return c.json({ error: "Not found" }, 404);
+  }
+  const body = await c.req.json<{ read?: unknown }>().catch(() => ({ read: undefined }));
+  const read = body.read !== false;
+  const thread = await listByThreadKey(original.threadKey, isAdmin(user) ? undefined : user);
+  await setRead(
+    thread.filter((m) => m.direction === "inbound").map((m) => m.id),
+    read,
+  );
+  return c.json({ ok: true, count: await unreadCount(isAdmin(user) ? undefined : user) });
+});
+
 app.post("/api/drafts", async (c) => {
   const body = await c.req.json().catch(() => null);
   if (!body?.subject && !body?.html && !body?.to) {