commit
Fix audit findings and add bearer sign-in for the Android app
- Split IN-list queries under D1's 100-parameter limit, so emptying a big Bin, the Bin purge, deleting a user and wide inbound mail don't fail halfway. - Treat the SSO sub as the identity: an SSO rename keeps the existing mailbox instead of failing on the sub constraint. - ADMIN_USERS only makes a new account an admin while no admin exists. - Refuse sign-ups as role names (postmaster, abuse, ...). - Key sessions by a SHA-256 of the token; everyone signs in once. - Cap attachments per email at what Resend takes, checked before reading. - Reject oversized uploads before buffering them. - Push endpoints must be https, at most 20 devices per user. - Validate list cursors instead of erroring on NaN. - App sign-in: one-time code + PKCE verifier swapped for a bearer token. Co-Authored-By: Claude Opus 5.5 <[email protected]>
diff --git a/email/README.md b/email/README.md
index a37cd4f..f7ff5c4 100644
--- a/email/README.md
+++ b/email/README.md
@@ -32,6 +32,16 @@ test/ vitest, running inside workerd with local D1 + R2
script, its own CSP, and remote content blocked until you click to load it.
That keeps an email's fonts and styles inside the frame. Attachments are only
ever shown inline when they're plain images.
+- **Sign-in**: the SSO, with sessions in D1 keyed by a hash of the cookie's
+ token. The SSO account (`sub`) is the identity, so someone renamed there keeps
+ their mailbox here. Role names like `postmaster` and `abuse` can't be signed up
+ for; hand them out as aliases. `ADMIN_USERS` makes a new account an admin only
+ while there's no admin yet.
+- **Android app**: signs in through the same flow in a browser tab, started with
+ `/auth/login?app=<PKCE challenge>`. The callback redirects to
+ `gay.doughmination.mail://auth?code=...`, the app swaps that code and its
+ verifier at `POST /auth/app/token` for a session token, and sends it as
+ `Authorization: Bearer`.
## Setup
diff --git a/email/migrations/0006_hashed_sessions.sql b/email/migrations/0006_hashed_sessions.sql
new file mode 100644
index 0000000..8e537bb
--- /dev/null
+++ b/email/migrations/0006_hashed_sessions.sql
@@ -0,0 +1,3 @@
+-- Sessions are now keyed by a SHA-256 of the cookie's token rather than the
+-- token itself. Old rows can't be matched any more, so everyone signs in once.
+DELETE FROM sessions;
diff --git a/email/src/worker/index.ts b/email/src/worker/index.ts
index 390129f..6c64934 100644
--- a/email/src/worker/index.ts
+++ b/email/src/worker/index.ts
@@ -22,8 +22,11 @@ const app = new Hono<AppEnv>()
.get("/api/live", async (c) => {
if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return c.json({ error: "Expected a WebSocket" }, 426);
// Browsers send cookies on cross-site WebSocket handshakes and sameOrigin
- // lets GETs through, so check the origin here.
- if (c.req.header("origin") !== new URL(c.req.url).origin) return c.json({ error: "Cross-site request refused" }, 403);
+ // lets GETs through, so check the origin here. The app's bearer token
+ // isn't ambient, so it has nothing to forge.
+ if (!c.get("bearer") && c.req.header("origin") !== new URL(c.req.url).origin) {
+ return c.json({ error: "Cross-site request refused" }, 403);
+ }
const res = await c.env.LIVE.getByName(c.get("user").username.toLowerCase()).fetch(c.req.raw);
// Re-wrapped: the stub's response has immutable headers, which secureHeaders needs to set.
return new Response(null, { status: res.status, webSocket: res.webSocket });
diff --git a/email/src/worker/lib/chunk.ts b/email/src/worker/lib/chunk.ts
new file mode 100644
index 0000000..9ddc0d5
--- /dev/null
+++ b/email/src/worker/lib/chunk.ts
@@ -0,0 +1,10 @@
+/**
+ * D1 binds at most 100 parameters per statement (local D1 doesn't enforce
+ * it, so tests won't notice), so a query with an IN list takes it in slices.
+ * The default leaves room for the query's other parameters.
+ */
+export function chunks<T>(list: T[], size = 90): T[][] {
+ const out: T[][] = [];
+ for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size));
+ return out;
+}
diff --git a/email/src/worker/middleware.ts b/email/src/worker/middleware.ts
index b58eb0c..dc155d3 100644
--- a/email/src/worker/middleware.ts
+++ b/email/src/worker/middleware.ts
@@ -1,3 +1,4 @@
+import type { Context } from "hono";
import { createMiddleware } from "hono/factory";
import { getCookie } from "hono/cookie";
import { getUser } from "./services/directory";
@@ -5,9 +6,25 @@ import { sessionIdentity } from "./services/sessions";
export type AppEnv = {
Bindings: Env;
- Variables: { user: { username: string; isAdmin: boolean } };
+ Variables: {
+ user: { username: string; isAdmin: boolean };
+ /** Signed in with an Authorization header (the Android app) rather than the cookie. */
+ bearer: boolean;
+ };
};
+/**
+ * The session token a request carries: from `Authorization: Bearer` when
+ * that header is there at all (never falling back to the cookie, so a bad
+ * header can't ride on a browser's ambient session), otherwise the cookie.
+ */
+export function sessionToken(c: Context<AppEnv>): { token: string | undefined; bearer: boolean } {
+ const header = c.req.header("authorization");
+ if (header === undefined) return { token: getCookie(c, "session"), bearer: false };
+ const match = /^Bearer\s+(\S+)$/i.exec(header);
+ return { token: match?.[1], bearer: true };
+}
+
/**
* Session cookies are SameSite=Lax, which still lets sibling subdomains (same
* site) send them. State-changing requests must come from this origin.
@@ -15,6 +32,9 @@ export type AppEnv = {
export const sameOrigin = createMiddleware<AppEnv>(async (c, next) => {
const method = c.req.method;
if (method === "GET" || method === "HEAD" || method === "OPTIONS") return next();
+ // A browser can't add an Authorization header cross-site without a CORS
+ // preflight, which nothing here answers, so these can't be forged.
+ if (c.req.header("authorization") !== undefined) return next();
const origin = c.req.header("origin");
const site = c.req.header("sec-fetch-site");
const self = new URL(c.req.url).origin;
@@ -25,12 +45,14 @@ export const sameOrigin = createMiddleware<AppEnv>(async (c, next) => {
});
export const requireUser = createMiddleware<AppEnv>(async (c, next) => {
- const identity = await sessionIdentity(c.env, getCookie(c, "session"));
+ const { token, bearer } = sessionToken(c);
+ const identity = await sessionIdentity(c.env, token);
// 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 });
+ c.set("bearer", bearer);
return next();
});
diff --git a/email/src/worker/routes/auth.ts b/email/src/worker/routes/auth.ts
index a30d5f3..f73d17a 100644
--- a/email/src/worker/routes/auth.ts
+++ b/email/src/worker/routes/auth.ts
@@ -1,16 +1,40 @@
import { Hono } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
-import type { AppEnv } from "../middleware";
-import { AccountConflict, recordLogin } from "../services/directory";
-import { buildAuthUrl, completeLogin, endSessionUrl, issuerMatches, revokeRefreshToken } from "../services/oidc";
-import { SESSION_TTL_S, createSession, destroySession, savePending, takePending } from "../services/sessions";
+import { zValidator } from "@hono/zod-validator";
+import { z } from "zod";
+import { sessionToken, type AppEnv } from "../middleware";
+import { AccountConflict, ReservedUsername, recordLogin } from "../services/directory";
+import {
+ buildAuthUrl,
+ completeLogin,
+ endSessionUrl,
+ issuerMatches,
+ pkceChallenge,
+ revokeRefreshToken,
+} from "../services/oidc";
+import {
+ SESSION_TTL_S,
+ createSession,
+ destroySession,
+ saveAppCode,
+ savePending,
+ takeAppCode,
+ takePending,
+} from "../services/sessions";
const secure = (env: Env) => env.COOKIE_SECURE !== "false";
+/** Where an app-started login lands; the Android app handles this scheme. */
+const APP_REDIRECT = "gay.doughmination.mail://auth";
+/** An S256 PKCE challenge: 32 bytes, base64url. */
+const CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
+
export const auth = new Hono<AppEnv>()
.get("/login", async (c) => {
try {
- const { url, pending } = await buildAuthUrl(c.env, c.req.query("from") || "/inbox");
+ const app = c.req.query("app");
+ if (app !== undefined && !CHALLENGE.test(app)) return c.text("Bad app login request.", 400);
+ const { url, pending } = await buildAuthUrl(c.env, c.req.query("from") || "/inbox", app);
const id = await savePending(c.env, pending);
setCookie(c, "login", id, { httpOnly: true, sameSite: "Lax", secure: secure(c.env), path: "/", maxAge: 600 });
return c.redirect(url);
@@ -39,8 +63,11 @@ export const auth = new Hono<AppEnv>()
try {
const tokens = await completeLogin(c.env, code, pending);
- await recordLogin(c.env, tokens);
- const token = await createSession(c.env, tokens);
+ const username = await recordLogin(c.env, tokens);
+ const token = await createSession(c.env, { ...tokens, username });
+ if (pending.app) {
+ return c.redirect(`${APP_REDIRECT}?code=${await saveAppCode(c.env, token, pending.app)}`);
+ }
setCookie(c, "session", token, {
httpOnly: true,
sameSite: "Lax",
@@ -50,6 +77,9 @@ export const auth = new Hono<AppEnv>()
});
return c.redirect(pending.returnTo);
} catch (e) {
+ if (e instanceof ReservedUsername) {
+ return c.text("Your SSO username is reserved here. Ask an admin to give you an account.", 403);
+ }
if (e instanceof AccountConflict) {
return c.text("This username already belongs to another account here. Ask an admin to sort it out.", 403);
}
@@ -58,8 +88,19 @@ export const auth = new Hono<AppEnv>()
}
})
+ /** The Android app swaps its one-time code (and PKCE verifier) for a session token. */
+ .post(
+ "/app/token",
+ zValidator("json", z.object({ code: z.uuid(), verifier: z.string().min(43).max(128) })),
+ async (c) => {
+ const { code, verifier } = c.req.valid("json");
+ const token = await takeAppCode(c.env, code, async (challenge) => (await pkceChallenge(verifier)) === challenge);
+ return token ? c.json({ token }) : c.json({ error: "That sign-in has expired. Try again." }, 400);
+ },
+ )
+
.post("/logout", async (c) => {
- const ended = await destroySession(c.env, getCookie(c, "session"));
+ const ended = await destroySession(c.env, sessionToken(c).token);
deleteCookie(c, "session", { path: "/" });
if (ended?.refreshToken) {
c.executionCtx.waitUntil(
diff --git a/email/src/worker/routes/mail.ts b/email/src/worker/routes/mail.ts
index 6520843..4802bc6 100644
--- a/email/src/worker/routes/mail.ts
+++ b/email/src/worker/routes/mail.ts
@@ -38,7 +38,7 @@ const compose = z.object({
const listQuery = z.object({
folder: z.enum(["inbox", "sent", "drafts", "bin", "starred"]).default("inbox"),
mailbox: z.string().max(320).optional(),
- cursor: z.string().max(100).optional(),
+ cursor: z.string().regex(/^\d{1,15}\.[0-9a-f-]{36}$/).optional(),
limit: z.coerce.number().int().min(1).max(100).default(50),
});
@@ -130,6 +130,10 @@ export const mail = new Hono<AppEnv>()
.get("/unread", async (c) => c.json({ unread: await unreadByMailbox(c.env, c.get("user").username) }))
.post("/uploads", async (c) => {
+ // parseBody buffers the whole request, so turn away oversized ones before reading them.
+ if (Number(c.req.header("content-length") ?? 0) > MAX_UPLOAD_BYTES + 64 * 1024) {
+ return c.json({ error: "Attachments can be up to 25 MB each." }, 413);
+ }
const body = await c.req.parseBody();
const file = body["file"];
if (!(file instanceof File)) return c.json({ error: "file is required" }, 400);
@@ -189,13 +193,13 @@ export const mail = new Hono<AppEnv>()
zValidator(
"json",
z.object({
- endpoint: z.url().max(2048),
+ endpoint: z.url({ protocol: /^https$/ }).max(2048),
keys: z.object({ p256dh: z.string().max(200), auth: z.string().max(100) }),
}),
),
async (c) => {
- await addSubscription(c.env, c.get("user").username, c.req.valid("json"));
- return c.json({ ok: true });
+ const added = await addSubscription(c.env, c.get("user").username, c.req.valid("json"));
+ return added ? c.json({ ok: true }) : c.json({ error: "Too many devices have notifications on." }, 400);
},
)
diff --git a/email/src/worker/services/attachments.ts b/email/src/worker/services/attachments.ts
index b2e8839..4b92daa 100644
--- a/email/src/worker/services/attachments.ts
+++ b/email/src/worker/services/attachments.ts
@@ -1,9 +1,12 @@
import type { AttachmentInfo } from "../../shared/types";
+import { chunks } from "../lib/chunk";
// Everything this app writes sits under inbox/, apart from the proxy's
// objects in the same bucket.
const PREFIX = "inbox";
export const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
+// Resend takes 40 MB per email once attachments are base64'd (a third bigger).
+export const MAX_MESSAGE_ATTACHMENT_BYTES = 28 * 1024 * 1024;
const ORPHAN_UPLOAD_TTL_MS = 1000 * 60 * 60 * 24 * 2;
export function inboundKey(resendEmailId: string, resendAttachmentId: string): string {
@@ -157,6 +160,8 @@ export async function getAttachment(env: Env, owner: string, id: string): Promis
: null;
}
+export class AttachmentsTooLarge extends Error {}
+
/** Base64 bodies in the shape Resend's send API wants. */
export async function forResend(
env: Env,
@@ -164,10 +169,12 @@ export async function forResend(
messageId: string,
): Promise<{ filename: string; content: string; contentType: string; contentId?: string }[]> {
const { results } = await env.DB.prepare(
- "SELECT r2_key, filename, content_type, content_id FROM attachments WHERE message_id = ? AND owner = ?",
+ "SELECT r2_key, filename, content_type, content_id, size FROM attachments WHERE message_id = ? AND owner = ?",
)
.bind(messageId, owner)
- .all<{ r2_key: string; filename: string; content_type: string; content_id: string | null }>();
+ .all<{ r2_key: string; filename: string; content_type: string; content_id: string | null; size: number }>();
+ // Checked before anything is read: every file is held in memory, base64'd, at once.
+ if (results.reduce((n, r) => n + r.size, 0) > MAX_MESSAGE_ATTACHMENT_BYTES) throw new AttachmentsTooLarge();
return Promise.all(
results.map(async (r) => {
@@ -187,14 +194,17 @@ export async function forResend(
export async function purgeObjects(env: Env, keys: string[]): Promise<void> {
const unique = [...new Set(keys)];
if (!unique.length) return;
- const { results } = await env.DB.prepare(
- `SELECT DISTINCT r2_key FROM attachments WHERE r2_key IN (${unique.map(() => "?").join(", ")})`,
- )
- .bind(...unique)
- .all<{ r2_key: string }>();
- const stillUsed = new Set(results.map((r) => r.r2_key));
+ const found = await env.DB.batch<{ r2_key: string }>(
+ chunks(unique).map((slice) =>
+ env.DB.prepare(
+ `SELECT DISTINCT r2_key FROM attachments WHERE r2_key IN (${slice.map(() => "?").join(", ")})`,
+ ).bind(...slice),
+ ),
+ );
+ const stillUsed = new Set(found.flatMap((r) => r.results.map((row) => row.r2_key)));
const dead = unique.filter((k) => !stillUsed.has(k));
- if (dead.length) await env.BUCKET.delete(dead);
+ // R2 deletes up to 1000 keys per call.
+ for (const slice of chunks(dead, 1000)) await env.BUCKET.delete(slice);
}
/** Uploads that were never sent or saved into a draft. Run from the cron. */
diff --git a/email/src/worker/services/directory.ts b/email/src/worker/services/directory.ts
index 65aec11..c87ae47 100644
--- a/email/src/worker/services/directory.ts
+++ b/email/src/worker/services/directory.ts
@@ -1,4 +1,5 @@
import { bareAddress } from "../lib/address";
+import { chunks } from "../lib/chunk";
import { addressesOf, buildDirectory, route, type AliasRow, type Directory, type DomainRow } from "../lib/routing";
import type { TokenSet } from "./oidc";
@@ -14,12 +15,14 @@ export async function loadDirectory(env: Env): Promise<Directory> {
async function existingUsers(env: Env, names: string[]): Promise<Set<string>> {
if (!names.length) return new Set();
- const { results } = await env.DB.prepare(
- `SELECT username FROM users WHERE username IN (${names.map(() => "?").join(", ")})`,
- )
- .bind(...names)
- .all<{ username: string }>();
- return new Set(results.map((r) => r.username.toLowerCase()));
+ const found = await env.DB.batch<{ username: string }>(
+ chunks(names).map((slice) =>
+ env.DB.prepare(`SELECT username FROM users WHERE username IN (${slice.map(() => "?").join(", ")})`).bind(
+ ...slice,
+ ),
+ ),
+ );
+ return new Set(found.flatMap((r) => r.results.map((row) => row.username.toLowerCase())));
}
/**
@@ -54,6 +57,30 @@ export async function enabledDomains(env: Env): Promise<string[]> {
}
export class AccountConflict extends Error {}
+export class ReservedUsername extends Error {}
+
+// RFC 2142 role mailboxes and other names mail gets sent to blind. Signing up
+// as one would take its mail on every domain, and let you send as it. Hand
+// them out as aliases instead.
+const RESERVED = new Set([
+ "abuse",
+ "admin",
+ "administrator",
+ "billing",
+ "hostmaster",
+ "info",
+ "mailer-daemon",
+ "marketing",
+ "no-reply",
+ "noc",
+ "noreply",
+ "postmaster",
+ "root",
+ "sales",
+ "security",
+ "support",
+ "webmaster",
+]);
function bootstrapAdmins(env: Env): Set<string> {
return new Set(
@@ -76,27 +103,50 @@ export async function setDisplayName(env: Env, username: string, name: string |
}
/**
- * Records a sign-in. Users in ADMIN_USERS are made admins every time, so the
- * first admin needs no setup and can't lock themselves out from the UI. The
- * SSO's name only fills in a missing display name, so one set in Settings sticks.
+ * Records a sign-in and returns the username it signs in as.
+ *
+ * The SSO account (sub) is the identity, not the name: someone renamed on the
+ * SSO keeps the mailbox and addresses they already have here. A new account
+ * gets the SSO's username, unless it's reserved or already someone else's.
+ *
+ * Users in ADMIN_USERS are re-made admins on every sign-in, so they can't be
+ * locked out from the UI. A *new* account only becomes one while there's no
+ * admin at all; otherwise whoever registered a listed name first on the SSO
+ * (after the real one was deleted, say) would walk in as an admin.
+ *
+ * The SSO's name only fills in a missing display name, so one set in Settings sticks.
*/
-export async function recordLogin(env: Env, tokens: TokenSet): Promise<void> {
- const username = tokens.username.toLowerCase();
+export async function recordLogin(env: Env, tokens: TokenSet): Promise<string> {
const ts = Date.now();
- const admin = bootstrapAdmins(env).has(username) ? 1 : 0;
- // 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 admins = bootstrapAdmins(env);
+
+ const known = await env.DB.prepare("SELECT username FROM users WHERE sub = ?")
+ .bind(tokens.sub)
+ .first<{ username: string }>();
+ if (known) {
+ await env.DB.prepare(
+ "UPDATE users SET last_login_at = ?, is_admin = MAX(is_admin, ?), display_name = COALESCE(display_name, ?) " +
+ "WHERE sub = ?",
+ )
+ .bind(ts, admins.has(known.username.toLowerCase()) ? 1 : 0, tokens.name ?? null, tokens.sub)
+ .run();
+ return known.username;
+ }
+
+ const username = tokens.username.toLowerCase();
+ if (RESERVED.has(username)) throw new ReservedUsername(`${username} is reserved`);
+ // One statement, so two sign-ins racing for a name can't both get it.
const res = await env.DB.prepare(
- "INSERT INTO users (username, sub, is_admin, display_name, 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), " +
- "display_name = COALESCE(users.display_name, excluded.display_name) WHERE users.sub = excluded.sub",
+ "INSERT INTO users (username, sub, is_admin, display_name, created_at, last_login_at) " +
+ "SELECT ?1, ?2, ?3 AND NOT EXISTS (SELECT 1 FROM users WHERE is_admin = 1), ?4, ?5, ?5 WHERE true " +
+ "ON CONFLICT DO NOTHING",
)
- .bind(username, tokens.sub, admin, tokens.name ?? null, ts, ts)
+ .bind(username, tokens.sub, admins.has(username) ? 1 : 0, tokens.name ?? null, ts)
.run();
if (res.meta.changes === 0) {
throw new AccountConflict(`username ${username} already belongs to a different SSO account`);
}
+ return username;
}
export async function getUser(
diff --git a/email/src/worker/services/messages.ts b/email/src/worker/services/messages.ts
index fd97d79..fe79295 100644
--- a/email/src/worker/services/messages.ts
+++ b/email/src/worker/services/messages.ts
@@ -1,5 +1,6 @@
import type { AttachmentInfo, Folder, ListFolder, Message, Page, Thread, ThreadSummary } from "../../shared/types";
import { baseSubject, isReplySubject } from "../lib/address";
+import { chunks } from "../lib/chunk";
import { purgeObjects } from "./attachments";
const FALLBACK_THREAD_WINDOW_MS = 1000 * 60 * 60 * 24 * 30;
@@ -360,12 +361,14 @@ async function deleteWhere(env: Env, where: string, params: (string | number)[])
const threads = [...new Set(deleted.map((d) => d.thread_id))];
if (threads.length) {
- await env.DB.prepare(
- `DELETE FROM threads WHERE id IN (${threads.map(() => "?").join(", ")}) ` +
- "AND NOT EXISTS (SELECT 1 FROM messages WHERE thread_id = threads.id)",
- )
- .bind(...threads)
- .run();
+ await env.DB.batch(
+ chunks(threads).map((ids) =>
+ env.DB.prepare(
+ `DELETE FROM threads WHERE id IN (${ids.map(() => "?").join(", ")}) ` +
+ "AND NOT EXISTS (SELECT 1 FROM messages WHERE thread_id = threads.id)",
+ ).bind(...ids),
+ ),
+ );
}
await purgeObjects(env, keys.map((k) => k.r2_key));
return deleted.length;
diff --git a/email/src/worker/services/oidc.ts b/email/src/worker/services/oidc.ts
index e7db767..e2531df 100644
--- a/email/src/worker/services/oidc.ts
+++ b/email/src/worker/services/oidc.ts
@@ -101,14 +101,25 @@ export function safeReturnTo(raw: string | undefined, fallback = "/inbox"): stri
return raw;
}
+/** S256 PKCE challenge for a verifier, as the app computes it too. */
+export async function pkceChallenge(verifier: string): Promise<string> {
+ return b64url(await sha256(verifier));
+}
+
export interface Pending {
state: string;
nonce: string;
codeVerifier: string;
returnTo: string;
+ /** Set when the Android app started this login: its PKCE challenge. */
+ app?: string;
}
-export async function buildAuthUrl(env: Env, returnTo: string): Promise<{ url: string; pending: Pending }> {
+export async function buildAuthUrl(
+ env: Env,
+ returnTo: string,
+ app?: string,
+): Promise<{ url: string; pending: Pending }> {
const cfg = config(env);
const d = await getDiscovery(cfg);
@@ -129,7 +140,7 @@ export async function buildAuthUrl(env: Env, returnTo: string): Promise<{ url: s
return {
url: url.toString(),
- pending: { state, nonce, codeVerifier, returnTo: safeReturnTo(returnTo) },
+ pending: { state, nonce, codeVerifier, returnTo: safeReturnTo(returnTo), ...(app ? { app } : {}) },
};
}
diff --git a/email/src/worker/services/outbound.ts b/email/src/worker/services/outbound.ts
index 56c111a..fb34f85 100644
--- a/email/src/worker/services/outbound.ts
+++ b/email/src/worker/services/outbound.ts
@@ -1,6 +1,6 @@
import type { ComposeInput } from "../../shared/types";
import { bareAddress, formatAddress, splitAddress } from "../lib/address";
-import { forResend, setMessageAttachments } from "./attachments";
+import { AttachmentsTooLarge, MAX_MESSAGE_ATTACHMENT_BYTES, forResend, setMessageAttachments } from "./attachments";
import { displayName, ownedAddress } from "./directory";
import { ancestry, getMessageRow, insertMessage, resolveThread, snippetOf } from "./messages";
import { resend } from "./resend";
@@ -118,7 +118,12 @@ export async function sendDraft(env: Env, user: string, draftId: string): Promis
if (draft.in_reply_to) headers["In-Reply-To"] = draft.in_reply_to;
if (draft.refs) headers["References"] = draft.refs;
- const attachments = await forResend(env, user, draftId);
+ const attachments = await forResend(env, user, draftId).catch((err: unknown) => {
+ if (!(err instanceof AttachmentsTooLarge)) throw err;
+ throw new ComposeError(
+ `Attachments can be up to ${MAX_MESSAGE_ATTACHMENT_BYTES / 1024 / 1024} MB in total. It's saved in Drafts.`,
+ );
+ });
const { data, error } = await resend(env).emails.send(
{
from: fromHeader,
diff --git a/email/src/worker/services/push.ts b/email/src/worker/services/push.ts
index 1a4827c..761a161 100644
--- a/email/src/worker/services/push.ts
+++ b/email/src/worker/services/push.ts
@@ -15,14 +15,20 @@ export function pushPublicKey(env: Env): string | null {
export type PushPayload = { title: string; body: string; url?: string; tag?: string };
-export async function addSubscription(env: Env, username: string, sub: PushSubscription): Promise<void> {
+// Every new email fans out one request per device, so cap them.
+export const MAX_SUBSCRIPTIONS = 20;
+
+/** Returns false when the user already has MAX_SUBSCRIPTIONS other devices. */
+export async function addSubscription(env: Env, username: string, sub: PushSubscription): Promise<boolean> {
// Re-subscribing a device that was someone else's hands it over.
- await env.DB.prepare(
- "INSERT INTO push_subscriptions (endpoint, username, data) VALUES (?, ?, ?) " +
+ const res = await env.DB.prepare(
+ "INSERT INTO push_subscriptions (endpoint, username, data) SELECT ?1, ?2, ?3 " +
+ "WHERE (SELECT COUNT(*) FROM push_subscriptions WHERE username = ?2 AND endpoint != ?1) < ?4 " +
"ON CONFLICT (endpoint) DO UPDATE SET username = excluded.username, data = excluded.data",
)
- .bind(sub.endpoint, username, JSON.stringify(sub))
+ .bind(sub.endpoint, username, JSON.stringify(sub), MAX_SUBSCRIPTIONS)
.run();
+ return res.meta.changes > 0;
}
export async function removeSubscription(env: Env, username: string, endpoint: string): Promise<void> {
diff --git a/email/src/worker/services/sessions.ts b/email/src/worker/services/sessions.ts
index aa24446..f444230 100644
--- a/email/src/worker/services/sessions.ts
+++ b/email/src/worker/services/sessions.ts
@@ -23,13 +23,22 @@ interface Session {
const now = () => Math.floor(Date.now() / 1000);
+/**
+ * Rows are keyed by a hash of the token, so a leaked copy of the database
+ * (a backup, an export) holds nothing that signs anyone in.
+ */
+export async function sessionKey(token: string): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
async function deleteSession(env: Env, token: string): Promise<void> {
- await env.DB.prepare("DELETE FROM sessions WHERE token = ?").bind(token).run();
+ await env.DB.prepare("DELETE FROM sessions WHERE token = ?").bind(await sessionKey(token)).run();
}
async function readSession(env: Env, token: string): Promise<Session | null> {
const row = await env.DB.prepare("SELECT data FROM sessions WHERE token = ? AND expires_at > ?")
- .bind(token, now())
+ .bind(await sessionKey(token), now())
.first<{ data: string }>();
if (!row) return null;
try {
@@ -53,7 +62,7 @@ async function writeSession(env: Env, token: string, session: Session): Promise<
"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)
+ .bind(await sessionKey(token), JSON.stringify(session), now() + remaining)
.run();
}
@@ -170,10 +179,40 @@ export async function savePending(env: Env, p: Pending): Promise<string> {
}
export async function takePending(env: Env, id: string | undefined): Promise<Pending | null> {
+ const data = await takeRow(env, id);
+ return data && typeof data.state === "string" ? (data as unknown as Pending) : null;
+}
+
+async function takeRow(env: Env, id: string | undefined): Promise<Record<string, unknown> | null> {
if (!id) return null;
const row = await env.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;
+ return JSON.parse(row.data) as Record<string, unknown>;
+}
+
+// The Android app signs in through the same SSO flow in a browser tab. The
+// callback can't hand it a cookie, so it hands over a one-time code instead,
+// which the app swaps for the session token along with the PKCE verifier only
+// it holds. Another app that catches the redirect gets a useless code.
+const APP_CODE_TTL_S = 60;
+
+export async function saveAppCode(env: Env, token: string, challenge: string): Promise<string> {
+ const id = crypto.randomUUID();
+ await env.DB.prepare("INSERT INTO pending_logins (id, data, expires_at) VALUES (?, ?, ?)")
+ .bind(id, JSON.stringify({ appToken: token, challenge }), now() + APP_CODE_TTL_S)
+ .run();
+ return id;
+}
+
+/** The session token for an app code, once; null if it's unknown, used, expired or the challenge doesn't match. */
+export async function takeAppCode(
+ env: Env,
+ code: string,
+ matches: (challenge: string) => Promise<boolean>,
+): Promise<string | null> {
+ const data = await takeRow(env, code);
+ if (typeof data?.appToken !== "string" || typeof data.challenge !== "string") return null;
+ return (await matches(data.challenge)) ? data.appToken : null;
}
diff --git a/email/test/audit-fixes.test.ts b/email/test/audit-fixes.test.ts
new file mode 100644
index 0000000..f3fc8a7
--- /dev/null
+++ b/email/test/audit-fixes.test.ts
@@ -0,0 +1,183 @@
+import { env, exports } from "cloudflare:workers";
+import { describe, expect, it } from "vitest";
+import { chunks } from "../src/worker/lib/chunk";
+import { AttachmentsTooLarge, forResend, insertAttachmentStatement } from "../src/worker/services/attachments";
+import { AccountConflict, ReservedUsername, getUser, recordLogin } from "../src/worker/services/directory";
+import { emptyBin, insertMessage, resolveThread } from "../src/worker/services/messages";
+import { pkceChallenge } from "../src/worker/services/oidc";
+import { createSession, saveAppCode, sessionKey } from "../src/worker/services/sessions";
+
+const ORIGIN = "https://mail.test";
+
+const login = (username: string, sub: string) => recordLogin(env, { username, sub, refreshToken: null, idToken: "x" });
+
+function call(path: string, init: RequestInit = {}) {
+ return exports.default.fetch(new Request(`${ORIGIN}${path}`, init));
+}
+
+async function storeMessage(owner: string, subject: string): Promise<{ id: string; threadId: string }> {
+ const threadId = await resolveThread(env, owner, {
+ inReplyTo: null,
+ refs: null,
+ subject,
+ counterpart: "[email protected]",
+ sentAt: Date.now(),
+ });
+ const id = crypto.randomUUID();
+ await insertMessage(env, threadId, {
+ id,
+ owner,
+ folder: "inbox",
+ mailbox: `${owner}@doughmination.gay`,
+ resend_id: crypto.randomUUID(),
+ message_id: null,
+ in_reply_to: null,
+ refs: null,
+ from_addr: "[email protected]",
+ to_addrs: "[]",
+ cc_addrs: "[]",
+ subject,
+ html: null,
+ text: "hi",
+ sent_at: Date.now(),
+ read: false,
+ });
+ return { id, threadId };
+}
+
+describe("sign-in identity", () => {
+ // Runs first: ADMIN_USERS only makes a new account an admin while there's none.
+ it("makes the bootstrap admin an admin when there's no admin yet", async () => {
+ expect(await login("clove", "sub-clove")).toBe("clove");
+ expect((await getUser(env, "clove"))?.isAdmin).toBe(true);
+ });
+
+ it("doesn't make a later holder of a bootstrap name an admin", async () => {
+ await env.DB.prepare("DELETE FROM users WHERE username = 'clove'").run();
+ await env.DB.prepare(
+ "INSERT INTO users (username, sub, is_admin, created_at, last_login_at) VALUES ('ari', 'sub-ari', 1, 0, 0)",
+ ).run();
+ expect(await login("clove", "sub-impostor")).toBe("clove");
+ expect((await getUser(env, "clove"))?.isAdmin).toBe(false);
+ });
+
+ it("keeps someone renamed on the SSO in their existing mailbox", async () => {
+ await login("rosa", "sub-rosa");
+ expect(await login("rosa-renamed", "sub-rosa")).toBe("rosa");
+ expect(await getUser(env, "rosa-renamed")).toBeNull();
+ });
+
+ it("refuses reserved names and names that are taken", async () => {
+ await expect(login("postmaster", "sub-pm")).rejects.toBeInstanceOf(ReservedUsername);
+ await expect(login("rosa", "sub-not-rosa")).rejects.toBeInstanceOf(AccountConflict);
+ });
+});
+
+describe("sessions", () => {
+ it("are stored under a hash, not the token itself", async () => {
+ const token = await createSession(env, { username: "rosa", sub: "sub-rosa", refreshToken: null, idToken: "x" });
+ const raw = await env.DB.prepare("SELECT 1 FROM sessions WHERE token = ?").bind(token).first();
+ const hashed = await env.DB.prepare("SELECT 1 FROM sessions WHERE token = ?").bind(await sessionKey(token)).first();
+ expect(raw).toBeNull();
+ expect(hashed).not.toBeNull();
+ });
+});
+
+describe("app sign-in", () => {
+ const verifier = "v".repeat(43);
+ const swap = (code: string, v: string) =>
+ call("/auth/app/token", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ code, verifier: v }),
+ });
+
+ it("swaps a code for a token only with the right verifier, and only once", async () => {
+ const token = await createSession(env, { username: "rosa", sub: "sub-rosa", refreshToken: null, idToken: "x" });
+ const challenge = await pkceChallenge(verifier);
+
+ expect((await swap(await saveAppCode(env, token, challenge), "w".repeat(43))).status).toBe(400);
+
+ const code = await saveAppCode(env, token, challenge);
+ const res = await swap(code, verifier);
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as { token: string }).token).toBe(token);
+ expect((await swap(code, verifier)).status).toBe(400);
+ });
+
+ it("signs API calls in with the bearer token, and never falls back to the cookie", async () => {
+ const token = await createSession(env, { username: "rosa", sub: "sub-rosa", refreshToken: null, idToken: "x" });
+ expect((await call("/api/me", { headers: { authorization: `Bearer ${token}` } })).status).toBe(200);
+ const mixed = await call("/api/me", { headers: { authorization: "Bearer nope", cookie: `session=${token}` } });
+ expect(mixed.status).toBe(401);
+ // No Origin header, as from the app: allowed, since a bearer token can't be forged cross-site.
+ const patch = await call("/api/me", {
+ method: "PATCH",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify({ name: "Rosa" }),
+ });
+ expect(patch.status).toBe(200);
+ });
+
+ it("rejects a malformed challenge at the start", async () => {
+ expect((await call("/auth/login?app=short")).status).toBe(400);
+ });
+});
+
+describe("request limits", () => {
+ const authed = async () => ({
+ authorization: `Bearer ${await createSession(env, { username: "rosa", sub: "sub-rosa", refreshToken: null, idToken: "x" })}`,
+ "content-type": "application/json",
+ });
+
+ it("refuses a garbage list cursor instead of failing", async () => {
+ expect((await call("/api/threads?cursor=abc.def", { headers: await authed() })).status).toBe(400);
+ });
+
+ it("only takes https push endpoints, and at most 20 devices", async () => {
+ const headers = await authed();
+ const subscribe = (endpoint: string) =>
+ call("/api/push/subscribe", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ endpoint, keys: { p256dh: "p", auth: "a" } }),
+ });
+ expect((await subscribe("http://push.example/x")).status).toBe(400);
+ for (let i = 0; i < 20; i++) expect((await subscribe(`https://push.example/${i}`)).status).toBe(200);
+ expect((await subscribe("https://push.example/20")).status).toBe(400);
+ // Re-subscribing an existing device still works at the cap.
+ expect((await subscribe("https://push.example/3")).status).toBe(200);
+ });
+
+ it("refuses to send more attachment bytes than Resend takes, before reading any", async () => {
+ const { id } = await storeMessage("rosa", "big");
+ for (const n of [1, 2]) {
+ await insertAttachmentStatement(env, {
+ id: crypto.randomUUID(),
+ owner: "rosa",
+ messageId: id,
+ r2Key: `inbox/missing/${n}`,
+ filename: `${n}.bin`,
+ contentType: "application/octet-stream",
+ size: 20 * 1024 * 1024,
+ contentId: null,
+ }).run();
+ }
+ await expect(forResend(env, "rosa", id)).rejects.toBeInstanceOf(AttachmentsTooLarge);
+ });
+});
+
+describe("bulk deletes", () => {
+ it("splits IN lists under D1's 100-parameter limit", () => {
+ const parts = chunks(Array.from({ length: 250 }, (_, i) => i));
+ expect(parts.map((p) => p.length)).toEqual([90, 90, 70]);
+ });
+
+ it("empties a Bin of more threads than one statement can name", async () => {
+ for (let i = 0; i < 150; i++) await storeMessage("rosa", `subject ${i}`);
+ await env.DB.prepare("UPDATE messages SET trashed_at = 1 WHERE owner = 'rosa'").run();
+ expect(await emptyBin(env, "rosa")).toBeGreaterThanOrEqual(150);
+ const left = await env.DB.prepare("SELECT COUNT(*) AS n FROM threads WHERE owner = 'rosa'").first<{ n: number }>();
+ expect(left?.n).toBe(0);
+ });
+});
diff --git a/email/test/bounce.test.ts b/email/test/bounce.test.ts
index 37c1848..f57e3b1 100644
--- a/email/test/bounce.test.ts
+++ b/email/test/bounce.test.ts
@@ -1,6 +1,7 @@
import { env, exports } from "cloudflare:workers";
import { Webhook } from "standardwebhooks";
import { beforeAll, describe, expect, it } from "vitest";
+import { sessionKey } from "../src/worker/services/sessions";
import type { Thread } from "../src/shared/types";
import { insertMessage, resolveThread } from "../src/worker/services/messages";
@@ -52,7 +53,7 @@ beforeAll(async () => {
const ts = Math.floor(now / 1000);
await env.DB.prepare("INSERT INTO sessions (token, data, expires_at) VALUES (?, ?, ?)")
.bind(
- token,
+ await sessionKey(token),
JSON.stringify({ username: "clove", sub: "sub-clove", refreshToken: null, idToken: null, createdAt: ts, verifiedAt: ts, checkedAt: ts }),
ts + 3600,
)
diff --git a/email/test/live.test.ts b/email/test/live.test.ts
index f9675a2..3e7b4ce 100644
--- a/email/test/live.test.ts
+++ b/email/test/live.test.ts
@@ -1,5 +1,6 @@
import { env, exports } from "cloudflare:workers";
import { beforeAll, describe, expect, it } from "vitest";
+import { sessionKey } from "../src/worker/services/sessions";
import { notifyLive } from "../src/worker/services/live";
const ORIGIN = "https://mail.test";
@@ -15,7 +16,7 @@ beforeAll(async () => {
const ts = Math.floor(now / 1000);
const session = { username: "clove", sub: "sub-clove", refreshToken: null, idToken: null, createdAt: ts, verifiedAt: ts, checkedAt: ts };
await env.DB.prepare("INSERT INTO sessions (token, data, expires_at) VALUES (?, ?, ?)")
- .bind(token, JSON.stringify(session), ts + 3600)
+ .bind(await sessionKey(token), JSON.stringify(session), ts + 3600)
.run();
});
diff --git a/email/test/mailbox.test.ts b/email/test/mailbox.test.ts
index b39c6b5..4a35372 100644
--- a/email/test/mailbox.test.ts
+++ b/email/test/mailbox.test.ts
@@ -1,5 +1,6 @@
import { env, exports } from "cloudflare:workers";
import { beforeAll, describe, expect, it } from "vitest";
+import { sessionKey } from "../src/worker/services/sessions";
import type { Page, Thread, ThreadSummary } from "../src/shared/types";
import { setMessageAttachments } from "../src/worker/services/attachments";
import { formatAddress } from "../src/worker/lib/address";
@@ -17,7 +18,7 @@ async function signIn(username: string, isAdmin = false): Promise<string> {
const ts = Math.floor(now / 1000);
const session = { username, sub: `sub-${username}`, refreshToken: null, idToken: null, createdAt: ts, verifiedAt: ts, checkedAt: ts };
await env.DB.prepare("INSERT INTO sessions (token, data, expires_at) VALUES (?, ?, ?)")
- .bind(token, JSON.stringify(session), ts + 3600)
+ .bind(await sessionKey(token), JSON.stringify(session), ts + 3600)
.run();
return token;
}
diff --git a/email/test/review-fixes.test.ts b/email/test/review-fixes.test.ts
index 04a129b..55c6f4e 100644
--- a/email/test/review-fixes.test.ts
+++ b/email/test/review-fixes.test.ts
@@ -1,5 +1,6 @@
import { env, exports } from "cloudflare:workers";
import { describe, expect, it } from "vitest";
+import { sessionKey } from "../src/worker/services/sessions";
import { splitList } from "../src/web/lib/format";
import { insertAttachmentStatement } from "../src/worker/services/attachments";
import { AccountConflict, recordLogin } from "../src/worker/services/directory";
@@ -11,7 +12,7 @@ async function session(username: string, sub: string): Promise<string> {
const ts = Math.floor(Date.now() / 1000);
const data = { username, sub, refreshToken: null, idToken: null, createdAt: ts, verifiedAt: ts, checkedAt: ts };
await env.DB.prepare("INSERT INTO sessions (token, data, expires_at) VALUES (?, ?, ?)")
- .bind(token, JSON.stringify(data), ts + 3600)
+ .bind(await sessionKey(token), JSON.stringify(data), ts + 3600)
.run();
return token;
}