commit
Final tweaks
diff --git a/package-lock.json b/package-lock.json
index eb73c3e..9cc07a1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -19,6 +19,7 @@
"@sveltejs/vite-plugin-svelte": "7.3.1",
"@tsconfig/svelte": "5.0.8",
"@types/node": "26.6.5",
+ "standardwebhooks": "1.1.1",
"svelte": "5.57.2",
"svelte-check": "4.7.6",
"typescript": "6.0.3",
diff --git a/package.json b/package.json
index c1f2db0..4b2f200 100644
--- a/package.json
+++ b/package.json
@@ -27,6 +27,7 @@
"@sveltejs/vite-plugin-svelte": "7.3.1",
"@tsconfig/svelte": "5.0.8",
"@types/node": "26.6.5",
+ "standardwebhooks": "1.1.1",
"svelte": "5.57.2",
"svelte-check": "4.7.6",
"typescript": "6.0.3",
diff --git a/src/worker/routes/webhook.ts b/src/worker/routes/webhook.ts
index a5eefa3..eb8b4bb 100644
--- a/src/worker/routes/webhook.ts
+++ b/src/worker/routes/webhook.ts
@@ -1,7 +1,7 @@
import { Hono } from "hono";
import type { AppEnv } from "../middleware";
import { syncDomains } from "../services/domains";
-import { receiveEmail } from "../services/inbound";
+import { receiveBounce, receiveEmail } from "../services/inbound";
import { resend } from "../services/resend";
export const webhook = new Hono<AppEnv>().post("/inbound", async (c) => {
@@ -25,8 +25,23 @@ export const webhook = new Hono<AppEnv>().post("/inbound", async (c) => {
// Subscribe the webhook to domain.* too and new domains appear on their own.
if (event.type.startsWith("domain.")) return c.json({ ok: true, ...(await syncDomains(c.env)) });
+ // Errors propagate as a 500 so Resend retries; both handlers are idempotent.
+ if (event.type === "email.bounced") {
+ const { data } = event;
+ return c.json({
+ ok: true,
+ ...(await receiveBounce(c.env, {
+ emailId: data.email_id,
+ to: data.to,
+ subject: data.subject,
+ bouncedAt: event.created_at,
+ type: data.bounce.type,
+ subType: data.bounce.subType,
+ message: data.bounce.message,
+ })),
+ });
+ }
if (event.type !== "email.received") return c.json({ ok: true, ignored: event.type });
- // Errors propagate as a 500 so Resend retries; receiveEmail is idempotent.
return c.json({ ok: true, ...(await receiveEmail(c.env, event.data.email_id)) });
});
diff --git a/src/worker/services/inbound.ts b/src/worker/services/inbound.ts
index 1a93d05..62c0888 100644
--- a/src/worker/services/inbound.ts
+++ b/src/worker/services/inbound.ts
@@ -114,3 +114,78 @@ export async function receiveEmail(env: Env, emailId: string): Promise<{ stored:
}
return { stored };
}
+
+export interface Bounce {
+ /** Resend's id for the email that bounced, stored as resend_id on our Sent copy. */
+ emailId: string;
+ to: string[];
+ subject: string;
+ bouncedAt: string;
+ type: string;
+ subType: string;
+ message: string;
+}
+
+/**
+ * Puts a delivery-failure notice into the sender's inbox, in the same
+ * conversation as the message that bounced. Bounces for mail this inbox
+ * didn't send (the old proxy, say) are ignored. Safe to run again: the
+ * notice's resend_id is derived from the bounced email's, so a retry is a no-op.
+ */
+export async function receiveBounce(env: Env, bounce: Bounce): Promise<{ stored: number }> {
+ const sent = await env.DB.prepare(
+ "SELECT id, owner, thread_id, mailbox, from_addr, subject FROM messages WHERE resend_id = ? AND folder = 'sent'",
+ )
+ .bind(bounce.emailId)
+ .first<{ id: string; owner: string; thread_id: string; mailbox: string; from_addr: string; subject: string }>();
+ if (!sent) return { stored: 0 };
+
+ const domain = sent.mailbox.slice(sent.mailbox.lastIndexOf("@") + 1);
+ const sentAt = Date.parse(bounce.bouncedAt) || Date.now();
+ const kind = [bounce.type, bounce.subType].filter(Boolean).join(" / ");
+ const text = [
+ "Your message couldn't be delivered.",
+ "",
+ `To: ${bounce.to.join(", ")}`,
+ `Subject: ${sent.subject}`,
+ ...(kind ? [`Bounce: ${kind}`] : []),
+ "",
+ bounce.message || "The receiving server gave no reason.",
+ ].join("\n");
+
+ const id = crypto.randomUUID();
+ const [inserted] = await env.DB.batch([
+ insertMessageStatement(env, sent.thread_id, {
+ id,
+ owner: sent.owner,
+ folder: "inbox",
+ mailbox: sent.mailbox,
+ resend_id: `bounce:${bounce.emailId}`,
+ message_id: null,
+ in_reply_to: null,
+ refs: null,
+ from_addr: `Mail Delivery <mailer-daemon@${domain}>`,
+ to_addrs: JSON.stringify([sent.from_addr]),
+ cc_addrs: "[]",
+ subject: `Undelivered: ${sent.subject || bounce.subject || "(no subject)"}`,
+ html: null,
+ text,
+ sent_at: sentAt,
+ read: false,
+ }),
+ env.DB.prepare("UPDATE threads SET last_at = MAX(last_at, ?) WHERE id = ?").bind(sentAt, sent.thread_id),
+ ]);
+ if (!inserted?.meta.changes) return { stored: 0 };
+
+ try {
+ await notifyUser(env, sent.owner, {
+ title: "Message not delivered",
+ body: `${sent.subject || "(no subject)"} to ${bounce.to.join(", ")}`,
+ url: `/inbox/${sent.thread_id}`,
+ tag: id,
+ });
+ } catch (err) {
+ console.error("Push notification failed", err);
+ }
+ return { stored: 1 };
+}
diff --git a/test/bounce.test.ts b/test/bounce.test.ts
new file mode 100644
index 0000000..37c1848
--- /dev/null
+++ b/test/bounce.test.ts
@@ -0,0 +1,122 @@
+import { env, exports } from "cloudflare:workers";
+import { Webhook } from "standardwebhooks";
+import { beforeAll, describe, expect, it } from "vitest";
+import type { Thread } from "../src/shared/types";
+import { insertMessage, resolveThread } from "../src/worker/services/messages";
+
+const ORIGIN = "https://mail.test";
+const SENT_RESEND_ID = "5f2b1c3e-0000-4000-8000-000000000001";
+let token: string;
+let threadId: string;
+
+/** Delivers `event` the way Resend does: signed with the webhook secret. */
+function webhook(event: unknown) {
+ const id = `msg_${crypto.randomUUID()}`;
+ const now = new Date();
+ const body = JSON.stringify(event);
+ const signature = new Webhook(env.RESEND_WEBHOOK_SECRET).sign(id, now, body);
+ return exports.default.fetch(
+ new Request(`${ORIGIN}/webhook/inbound`, {
+ method: "POST",
+ headers: {
+ "svix-id": id,
+ "svix-timestamp": String(Math.floor(now.getTime() / 1000)),
+ "svix-signature": signature,
+ "content-type": "application/json",
+ },
+ body,
+ }),
+ );
+}
+
+const bounced = (emailId: string) => ({
+ type: "email.bounced",
+ created_at: new Date().toISOString(),
+ data: {
+ created_at: new Date().toISOString(),
+ email_id: emailId,
+ message_id: "<[email protected]>",
+ from: "[email protected]",
+ to: ["[email protected]"],
+ subject: "Hello there",
+ bounce: { type: "Permanent", subType: "General", message: "550 5.1.1 User unknown" },
+ },
+});
+
+beforeAll(async () => {
+ const now = Date.now();
+ await env.DB.prepare("INSERT INTO users (username, sub, is_admin, created_at, last_login_at) VALUES ('clove', 'sub-clove', 0, ?, ?)")
+ .bind(now, now)
+ .run();
+ token = crypto.randomUUID();
+ const ts = Math.floor(now / 1000);
+ await env.DB.prepare("INSERT INTO sessions (token, data, expires_at) VALUES (?, ?, ?)")
+ .bind(
+ token,
+ JSON.stringify({ username: "clove", sub: "sub-clove", refreshToken: null, idToken: null, createdAt: ts, verifiedAt: ts, checkedAt: ts }),
+ ts + 3600,
+ )
+ .run();
+
+ threadId = await resolveThread(env, "clove", {
+ inReplyTo: null,
+ refs: null,
+ subject: "Hello there",
+ counterpart: "[email protected]",
+ sentAt: now,
+ });
+ await insertMessage(env, threadId, {
+ id: crypto.randomUUID(),
+ owner: "clove",
+ folder: "sent",
+ mailbox: "[email protected]",
+ resend_id: SENT_RESEND_ID,
+ message_id: "<[email protected]>",
+ in_reply_to: null,
+ refs: null,
+ from_addr: "[email protected]",
+ to_addrs: JSON.stringify(["[email protected]"]),
+ cc_addrs: "[]",
+ subject: "Hello there",
+ html: null,
+ text: "hi",
+ sent_at: now,
+ read: true,
+ });
+});
+
+describe("email.bounced", () => {
+ it("puts an unread notice in the inbox, in the same conversation", async () => {
+ const res = await webhook(bounced(SENT_RESEND_ID));
+ expect(await res.json()).toEqual({ ok: true, stored: 1 });
+
+ const thread = (await (
+ await exports.default.fetch(new Request(`${ORIGIN}/api/threads/${threadId}`, { headers: { cookie: `session=${token}` } }))
+ ).json()) as Thread;
+ expect(thread.messages).toHaveLength(2);
+ const notice = thread.messages[1]!;
+ expect(notice).toMatchObject({
+ folder: "inbox",
+ read: false,
+ from: "Mail Delivery <[email protected]>",
+ subject: "Undelivered: Hello there",
+ });
+ expect(notice.text).toContain("550 5.1.1 User unknown");
+ expect(notice.text).toContain("[email protected]");
+ });
+
+ it("doesn't add a second notice when Resend retries", async () => {
+ expect(await (await webhook(bounced(SENT_RESEND_ID))).json()).toEqual({ ok: true, stored: 0 });
+ });
+
+ it("ignores bounces for mail this inbox didn't send", async () => {
+ expect(await (await webhook(bounced("not-ours"))).json()).toEqual({ ok: true, stored: 0 });
+ });
+
+ it("rejects unsigned events", async () => {
+ const res = await exports.default.fetch(
+ new Request(`${ORIGIN}/webhook/inbound`, { method: "POST", body: JSON.stringify(bounced(SENT_RESEND_ID)) }),
+ );
+ expect(res.status).toBe(401);
+ });
+});
diff --git a/test/review-fixes.test.ts b/test/review-fixes.test.ts
new file mode 100644
index 0000000..04a129b
--- /dev/null
+++ b/test/review-fixes.test.ts
@@ -0,0 +1,77 @@
+import { env, exports } from "cloudflare:workers";
+import { describe, expect, it } from "vitest";
+import { splitList } from "../src/web/lib/format";
+import { insertAttachmentStatement } from "../src/worker/services/attachments";
+import { AccountConflict, recordLogin } from "../src/worker/services/directory";
+
+const ORIGIN = "https://mail.test";
+
+async function session(username: string, sub: string): Promise<string> {
+ const token = crypto.randomUUID();
+ 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)
+ .run();
+ return token;
+}
+
+const me = (token: string) =>
+ exports.default.fetch(new Request(`${ORIGIN}/api/me`, { headers: { cookie: `session=${token}` } }));
+
+describe("sessions are tied to the SSO account, not just the username", () => {
+ it("rejects a session whose sub no longer owns the username", async () => {
+ await recordLogin(env, { username: "sam", sub: "sub-new", refreshToken: null, idToken: "x" });
+ expect((await me(await session("sam", "sub-new"))).status).toBe(200);
+ // A session left over from the previous holder of the name.
+ expect((await me(await session("sam", "sub-old"))).status).toBe(401);
+ });
+
+ it("refuses a sign-in that would take over another account's username", async () => {
+ await expect(
+ recordLogin(env, { username: "sam", sub: "sub-someone-else", refreshToken: null, idToken: "x" }),
+ ).rejects.toBeInstanceOf(AccountConflict);
+ // The same account signing in again is fine.
+ await recordLogin(env, { username: "sam", sub: "sub-new", refreshToken: null, idToken: "x" });
+ });
+});
+
+describe("attachment inserts batched after a message", () => {
+ it("insert nothing when the message doesn't exist", async () => {
+ const res = await insertAttachmentStatement(env, {
+ id: crypto.randomUUID(),
+ owner: "sam",
+ messageId: crypto.randomUUID(),
+ r2Key: "inbox/x",
+ filename: "a.txt",
+ contentType: "text/plain",
+ size: 1,
+ contentId: null,
+ }).run();
+ expect(res.meta.changes).toBe(0);
+ });
+
+ it("still store unclaimed uploads", async () => {
+ const res = await insertAttachmentStatement(env, {
+ id: crypto.randomUUID(),
+ owner: "sam",
+ messageId: null,
+ r2Key: "inbox/uploads/y",
+ filename: "b.txt",
+ contentType: "text/plain",
+ size: 1,
+ contentId: null,
+ }).run();
+ expect(res.meta.changes).toBe(1);
+ });
+});
+
+describe("splitList", () => {
+ it("splits on , ; and newlines but not inside quotes", () => {
+ expect(splitList('"Doe, Jane" <[email protected]>, [email protected];\n [email protected],,')).toEqual([
+ '"Doe, Jane" <[email protected]>',
+ "[email protected]",
+ "[email protected]",
+ ]);
+ });
+});