Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): sync signup and account deletion contacts with resend (#969)
Gener6f24c48ada3a
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d973e2979..157267435 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -511,6 +511,9 @@ importers:remark-gfm:specifier: ^4.0.1version: 4.0.1+ resend:+ specifier: 6.17.2+ version: 6.17.2shadcn:specifier: ^4.21.4version: 4.21.4@@ -3376,6 +3379,9 @@ packages:'@speed-highlight/[email protected]':resolution: {integrity: sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==}+ '@stablelib/[email protected]':+ resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}+'@standard-schema/[email protected]':resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}@@ -6011,6 +6017,9 @@ packages:resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}+ resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==}+resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}@@ -7956,6 +7965,9 @@ packages:resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-0WdnFQYUrPGGTFu1uOqD2s7omwua8xaeYGdO6rb88oD5yJ/4pPHDA4sdWqfD8wQVfCny563n/HQS7zTFft+f/g==}+resolution: {integrity: sha512-UUlyE2KlxmvwMGq060onF/VWU3zD6dVW31FwokQ5v26jWd35fbs2MoTFzh+jXnPwAyV2MULMKXcBInGOl5TO6Q==}@@ -8319,6 +8331,15 @@ packages:resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==}+ resolution: {integrity: sha512-hbaXEORFIFfT2Bh03NsA/akTTTKkD1hiuJ88ke64c5dWVV6DyoLxzFve3OiZqVOQ+JKLJ5uVkPR6hlUslpJFoA==}+ engines: {node: '>=20'}+ peerDependencies:+ '@react-email/render': '*'+ peerDependenciesMeta:+ '@react-email/render':+ optional: true+resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}engines: {node: '>=4'}@@ -8651,6 +8672,9 @@ packages:resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}+ resolution: {integrity: sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==}+resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}engines: {node: '>= 0.8'}@@ -12554,6 +12578,8 @@ snapshots:'@speed-highlight/[email protected]': {}+ '@stablelib/[email protected]': {}+'@standard-schema/[email protected]': {}'@streamdown/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])':@@ -15351,6 +15377,8 @@ snapshots:+ [email protected]: {}+optional: true@@ -17838,6 +17866,8 @@ snapshots:+ [email protected]: {}+@@ -18421,6 +18451,11 @@ snapshots:+ dependencies:+ postal-mime: 2.7.4+ standardwebhooks: 1.0.0+@@ -18937,6 +18972,11 @@ snapshots:+ dependencies:+ '@stablelib/base64': 1.0.1+ fast-sha256: 1.3.0+diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.exampleindex 47c85a2d0..f093f765d 100644--- a/src/web/.dev.vars.example+++ b/src/web/.dev.vars.example@@ -8,6 +8,7 @@# Session signing secret (generate with: openssl rand -base64 32)BETTER_AUTH_SECRET=+RESEND_API_KEY=BETTER_AUTH_URL=http://localhost:3000# Encryption key for credentials and device tokens (generate with: openssl rand -base64 32)diff --git a/src/web/package.json b/src/web/package.jsonindex 6bd430255..778d6315b 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -124,6 +124,7 @@"rehype-slug": "^6.0.0","remark-breaks": "^4.0.0","remark-gfm": "^4.0.1",+ "resend": "6.17.2","shadcn": "^4.21.4","shiki": "^4.5.0","sonner": "^2.0.8",diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex 9abcd2965..e7076c15d 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -4,6 +4,7 @@ interface RuntimeEnv {STRIPE_PORTAL_CONFIGURATION_ID?: stringSTRIPE_RETURN_ORIGIN?: stringGA4_API_SECRET?: string+ RESEND_API_KEY?: stringENCRYPTION_KEY: stringAPP_REVIEW_EMAIL?: stringAPP_REVIEW_OTP?: stringdiff --git a/src/web/src/lib/account-deletion/execution.test.ts b/src/web/src/lib/account-deletion/execution.test.tsindex 7b9ebe0fa..94ecb10bf 100644--- a/src/web/src/lib/account-deletion/execution.test.ts+++ b/src/web/src/lib/account-deletion/execution.test.ts@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({revokeProvider: vi.fn(),invalidateMany: vi.fn(),warn: vi.fn(),+ unsubscribe: vi.fn(),}))vi.mock("@alook/shared", () => ({@@ -30,6 +31,7 @@ vi.mock("@alook/shared", () => ({},}))vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))+vi.mock("@/lib/resend-contacts", () => ({ unsubscribeResendContact: mocks.unsubscribe }))vi.mock("@/lib/cache", () => ({cacheKeys: { machineToken: (token: string) => `mt:${token.slice(0, 20)}` },invalidateMany: mocks.invalidateMany,@@ -87,6 +89,7 @@ describe("account deletion execution", () => {mocks.broadcastUser,mocks.revokeProvider,mocks.invalidateMany,+ mocks.unsubscribe,]) effect.mockResolvedValue(undefined)})@@ -114,6 +117,8 @@ describe("account deletion execution", () => {"mt:al_final_token",])expect(waitUntil).toHaveBeenCalledOnce()+ expect(mocks.unsubscribe).toHaveBeenCalledWith(expect.anything(), final.identity.email)+ expect(mocks.unsubscribe.mock.invocationCallOrder[0]).toBeGreaterThan(mocks.deleteRows.mock.invocationCallOrder[0])})it("invalidates the initial machine tokens when another request already removed the user", async () => {@@ -129,6 +134,7 @@ describe("account deletion execution", () => {expect(mocks.invalidateMany).toHaveBeenCalledWith(["mt:al_initial_token"])expect(mocks.deleteRows).not.toHaveBeenCalled()+ expect(mocks.unsubscribe).not.toHaveBeenCalled()})it("does not run the D1 batch after synchronous storage cleanup fails", async () => {@@ -143,6 +149,7 @@ describe("account deletion execution", () => {)).resolves.toEqual({ kind: "failed" })expect(mocks.getSnapshot).toHaveBeenCalledTimes(2)expect(mocks.deleteRows).not.toHaveBeenCalled()+ expect(mocks.unsubscribe).not.toHaveBeenCalled()})it("treats an ambiguous D1 error as success only when a new primary no longer finds the user", async () => {@@ -157,6 +164,9 @@ describe("account deletion execution", () => {"user-1",)).resolves.toEqual({ kind: "deleted" })+ expect(mocks.unsubscribe).toHaveBeenCalledOnce()+ mocks.unsubscribe.mockClear()+mocks.getUser.mockResolvedValue({ id: "user-1" })await expect(executeAccountDeletion({} as never,@@ -164,6 +174,7 @@ describe("account deletion execution", () => {{ waitUntil: vi.fn() },"user-1",)).resolves.toEqual({ kind: "failed" })+ expect(mocks.unsubscribe).not.toHaveBeenCalled()})it("keeps committed deletion successful when post-commit effects reject", async () => {@@ -258,6 +269,7 @@ describe("account deletion execution", () => {expect(mocks.deleteStorage).not.toHaveBeenCalled()expect(mocks.deleteRows).not.toHaveBeenCalled()expect(mocks.invalidateMany).not.toHaveBeenCalled()+ expect(mocks.unsubscribe).not.toHaveBeenCalled()})it("keeps a committed deletion successful when machine-token invalidation fails", async () => {@@ -288,6 +300,7 @@ describe("account deletion execution", () => {{ waitUntil: vi.fn() },"user-1",)).resolves.toEqual({ kind: "failed" })+ expect(mocks.unsubscribe).not.toHaveBeenCalled()})it("keeps a committed deletion successful when waitUntil is unavailable", async () => {@@ -302,4 +315,51 @@ describe("account deletion execution", () => {)).resolves.toEqual({ kind: "deleted" })expect(mocks.warn).toHaveBeenCalledWith("account_deletion_wait_until_unavailable")})++ it("owns pending unsubscribe in the original single background group after confirmed deletion", async () => {+ mocks.getSnapshot.mockResolvedValue(snapshot("current"))+ mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })+ let finish: (() => void) | undefined+ mocks.unsubscribe.mockReturnValueOnce(new Promise<void>((resolve) => { finish = resolve }))+ const owner = { waitUntil: vi.fn(function (this: unknown, _promise: Promise<unknown>) { expect(this).toBe(owner) }) }+ const env = { RESEND_API_KEY: "mock-key" }+ await expect(executeAccountDeletion({} as never, env as never, owner, "user-1"))+ .resolves.toEqual({ kind: "deleted" })+ expect(owner.waitUntil).toHaveBeenCalledOnce()+ expect(mocks.unsubscribe).toHaveBeenCalledWith(env, "[email protected]")+ finish?.()+ await owner.waitUntil.mock.calls[0]?.[0]+ })++ it("keeps committed deletion successful when the contact effect rejects", async () => {+ mocks.getSnapshot.mockResolvedValue(snapshot("current"))+ mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })+ mocks.unsubscribe.mockRejectedValueOnce(new Error("contact provider unavailable"))+ const waitUntil = vi.fn()+ await expect(executeAccountDeletion({} as never, {} as never, { waitUntil }, "user-1"))+ .resolves.toEqual({ kind: "deleted" })+ await expect(waitUntil.mock.calls[0]?.[0]).resolves.toBeUndefined()+ expect(mocks.warn).toHaveBeenCalledWith("account_deletion_post_commit_effects_failed", { failures: 1 })+ })++ it("does not invent an unsubscribe for an initially missing account", async () => {+ mocks.getSnapshot.mockResolvedValueOnce(null)+ const waitUntil = vi.fn()+ await expect(executeAccountDeletion({} as never, {} as never, { waitUntil }, "user-1"))+ .resolves.toEqual({ kind: "missing" })+ expect(mocks.unsubscribe).not.toHaveBeenCalled()+ expect(waitUntil).not.toHaveBeenCalled()+ })++ it("unsubscribes when a no-op delete batch is confirmed absent on a fresh primary", async () => {+ mocks.getSnapshot.mockResolvedValue(snapshot("current"))+ mocks.deleteRows.mockResolvedValue({ deleted: false, readStateRevisions: [] })+ mocks.getUser.mockResolvedValueOnce(null)+ const waitUntil = vi.fn()+ await expect(executeAccountDeletion({} as never, {} as never, { waitUntil }, "user-1"))+ .resolves.toEqual({ kind: "deleted" })+ expect(mocks.unsubscribe).toHaveBeenCalledOnce()+ expect(mocks.unsubscribe.mock.invocationCallOrder[0]).toBeGreaterThan(mocks.getUser.mock.invocationCallOrder[0])+ expect(waitUntil).toHaveBeenCalledOnce()+ })})diff --git a/src/web/src/lib/account-deletion/execution.ts b/src/web/src/lib/account-deletion/execution.tsindex 8d578707d..c3d72490a 100644--- a/src/web/src/lib/account-deletion/execution.ts+++ b/src/web/src/lib/account-deletion/execution.ts@@ -7,6 +7,7 @@ import { fanOutToUsers, broadcastToUserSafe } from "@/lib/community/fanout"import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"import { deleteAccountStorage } from "./storage"import { revokeProviderAccount } from "./provider-revocation"+import { unsubscribeResendContact } from "@/lib/resend-contacts"const log = createLogger({ service: "account-deletion" })@@ -26,6 +27,7 @@ function scheduleAfterCommit(readStateRevisions: Array<{ userId: string; revision: number }>,): void {const work = Promise.allSettled([+ unsubscribeResendContact(env, snapshot.identity.email),forceCloseCommunityMachinesByDoNames(env, snapshot.machineDoNames),...snapshot.botBindings.map((binding) => pushBotEventToMachine(env, binding.machineId, {type: "bot:removed",diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex 33042ce54..c7d2201fd 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -8,6 +8,8 @@ const authLogMocks = vi.hoisted(() => ({warn: vi.fn(),error: vi.fn(),}))+const contactMocks = vi.hoisted(() => ({ signup: vi.fn(async () => {}) }))+vi.mock("./resend-contacts", () => ({ syncResendSignupContact: contactMocks.signup }))const cloudflareMocks = vi.hoisted(() => {const waitUntil = vi.fn<(promise: Promise<unknown>) => void>()return {@@ -245,6 +247,16 @@ describe("getAuth lifecycle", () => {expect(second).not.toBe(first)})++ it("rebuilds when optional contact configuration changes", async () => {+ const { getAuth } = await loadAuthModule()+ const absent = getAuth(makeEnv() as never)+ const configured = getAuth(makeEnv({ RESEND_API_KEY: "mock-key-a" }) as never)+ const changed = getAuth(makeEnv({ RESEND_API_KEY: "mock-key-b" }) as never)+ expect(configured).not.toBe(absent)+ expect(changed).not.toBe(configured)+ expect(getAuth(makeEnv({ RESEND_API_KEY: "mock-key-b" }) as never)).toBe(changed)+ })})// Fetches the OTP-plugin `sendVerificationOTP` callback for a given env@@ -765,7 +777,10 @@ describe("createAuth device authorization plugin", () => {})describe("createAuth databaseHooks — user.create.after", () => {- beforeEach(() => vi.clearAllMocks())+ beforeEach(() => {+ vi.clearAllMocks()+ contactMocks.signup.mockReset().mockResolvedValue(undefined)+ })function makeCtx(url: string) {const cookies: Record<string, { value: string; opts: unknown }> = {}@@ -829,6 +844,63 @@ describe("createAuth databaseHooks — user.create.after", () => {const afterHook = opts.databaseHooks!.user!.create!.after!await expect(afterHook({ id: "u5" }, null)).resolves.toBeUndefined()})++ it("skips contact dispatch with no Key while preserving the signup cookie", async () => {+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv() as never) as { __options: AuthOptions }).__options+ const ctx = makeCtx("http://localhost:3000/api/auth/sign-in/email-otp")+ await opts.databaseHooks!.user!.create!.after!({ email: "[email protected]", name: "QA" }, ctx)+ expect(contactMocks.signup).not.toHaveBeenCalled()+ expect(cloudflareMocks.waitUntil).not.toHaveBeenCalled()+ expect(ctx.setCookie).toHaveBeenCalledWith("is_new_signup", "email", expect.anything())+ })++ it("owns pending signup sync in the current Worker invocation without waiting for provider completion", async () => {+ let finish: (() => void) | undefined+ const pending = new Promise<void>((resolve) => { finish = resolve })+ contactMocks.signup.mockReturnValueOnce(pending)+ const createAuth = await loadCreateAuth()+ const env = makeEnv({ RESEND_API_KEY: "mock-key" })+ const opts = (createAuth(env as never) as { __options: AuthOptions }).__options+ const ctx = makeCtx("http://localhost:3000/api/auth/callback/google")+ const user = { email: "[email protected]", name: "QA" }+ await opts.databaseHooks!.user!.create!.after!(user, ctx)+ expect(contactMocks.signup).toHaveBeenCalledWith(env, user)+ expect(cloudflareMocks.waitUntil).toHaveBeenCalledWith(pending)+ expect(ctx.setCookie).toHaveBeenCalledWith("is_new_signup", "google", expect.anything())+ finish?.()+ await pending+ })++ it("resolves the current background owner separately for each created user", async () => {+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv({ RESEND_API_KEY: "mock-key" }) as never) as { __options: AuthOptions }).__options+ const firstOwner = { waitUntil: vi.fn(function (this: unknown) { expect(this).toBe(firstOwner) }) }+ const secondOwner = { waitUntil: vi.fn(function (this: unknown) { expect(this).toBe(secondOwner) }) }+ cloudflareMocks.getCloudflareContext.mockReturnValueOnce({ ctx: firstOwner }).mockReturnValueOnce({ ctx: secondOwner })+ const after = opts.databaseHooks!.user!.create!.after!+ await after({ email: "[email protected]", name: "One" }, null)+ await after({ email: "[email protected]", name: "Two" }, null)+ expect(firstOwner.waitUntil).toHaveBeenCalledOnce()+ expect(secondOwner.waitUntil).toHaveBeenCalledOnce()+ })++ it("awaits a captured signup operation if Worker scheduling is unavailable", async () => {+ cloudflareMocks.getCloudflareContext.mockImplementationOnce(() => { throw new Error("no Worker context") })+ let finish: (() => void) | undefined+ contactMocks.signup.mockReturnValueOnce(new Promise<void>((resolve) => { finish = resolve }))+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv({ RESEND_API_KEY: "mock-key" }) as never) as { __options: AuthOptions }).__options+ let settled = false+ const work = opts.databaseHooks!.user!.create!.after!({ email: "[email protected]", name: "QA" }, null)+ .then(() => { settled = true })+ await Promise.resolve()+ expect(settled).toBe(false)+ expect(cloudflareMocks.waitUntil).not.toHaveBeenCalled()+ finish?.()+ await work+ expect(settled).toBe(true)+ })})describe("createAuth databaseHooks — session.create.after", () => {@@ -836,7 +908,7 @@ describe("createAuth databaseHooks — session.create.after", () => {it("sets is_sign_in cookie with method=apple for an Apple callback", async () => {const createAuth = await loadCreateAuth()- const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as {+ const opts = (createAuth(makeEnv({ NODE_ENV: "production", RESEND_API_KEY: "mock-key" }) as never) as {__options: AuthOptions}).__optionsconst afterHook = opts.databaseHooks!.session!.create!.after!@@ -848,6 +920,8 @@ describe("createAuth databaseHooks — session.create.after", () => {await afterHook({ id: "session-apple", userId: "u-apple" }, ctx)+ expect(contactMocks.signup).not.toHaveBeenCalled()+expect(ctx.setCookie).toHaveBeenCalledWith("is_sign_in","apple",@@ -862,6 +936,16 @@ describe("createAuth databaseHooks — user.create.before", () => {selectResponses = []})+ it("rejects a bot-domain signup before any contact work", async () => {+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv({ RESEND_API_KEY: "mock-key" }) as never) as { __options: AuthOptions }).__options+ const { COMMUNITY_BOT_EMAIL_DOMAIN } = await import("@alook/shared")+ await expect(opts.databaseHooks!.user!.create!.before!({ email: `bot@${COMMUNITY_BOT_EMAIL_DOMAIN}`, name: "Bot" }))+ .resolves.toBe(false)+ expect(contactMocks.signup).not.toHaveBeenCalled()+ expect(cloudflareMocks.waitUntil).not.toHaveBeenCalled()+ })+it("coalesces empty name to email prefix", async () => {const createAuth = await loadCreateAuth()const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__optionsdiff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex c06df3694..bb1b9b6b3 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -23,6 +23,7 @@ import {} from "@/lib/apple-auth"import { appleOauthHardeningPlugin } from "@/lib/apple-oauth-hardening"import { getOtpSubject, renderOtpEmail, type OtpType } from "./email-templates"+import { syncResendSignupContact } from "./resend-contacts"const log = createLogger({ service: "auth" })@@ -248,6 +249,14 @@ export function createAuth(env: Env) {return { data: { ...user, id, name, discriminator } }},after: async (user, ctx) => {+ if (env.RESEND_API_KEY) {+ const contactSync = syncResendSignupContact(env, user)+ try {+ getCloudflareContext().ctx.waitUntil(contactSync)+ } catch {+ await contactSync+ }+ }if (!ctx) returnconst path = ctx.request?.url ? new URL(ctx.request.url).pathname : ""let method = "unknown"@@ -426,6 +435,7 @@ function authConfiguration(env: Env): readonly (string | undefined)[] {env.DEV_AUTH_OTP,env.AUTH_OTP_RATE_LIMIT_MAX,env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,+ env.RESEND_API_KEY,]}diff --git a/src/web/src/lib/resend-contacts.test.ts b/src/web/src/lib/resend-contacts.test.tsnew file mode 100644index 000000000..db3d5baf2--- /dev/null+++ b/src/web/src/lib/resend-contacts.test.ts@@ -0,0 +1,173 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"++const logs = vi.hoisted(() => ({ warn: vi.fn() }))+vi.mock("@alook/shared", () => ({ createLogger: () => logs }))++import { syncResendSignupContact, unsubscribeResendContact } from "./resend-contacts"++const fetchMock = vi.fn<typeof fetch>()+const env = { RESEND_API_KEY: "mock-contact-key" } as Env+const user = { email: "[email protected]", name: "QA Display Name" }+const segmentId = "6701946e-a7e2-442b-8fa5-aba379a81248"+const privateError = `${user.email} ${user.name} ${env.RESEND_API_KEY}`++function response(body: unknown, status = 200): Response {+ return Response.json(body, { status })+}++function existingContact(unsubscribed = false): Response {+ return response({ id: "contact-1", email: user.email, unsubscribed, object: "contact" })+}++function providerError(status: number, name = "application_error"): Response {+ return response({ name, message: privateError, statusCode: status }, status)+}++function requestAt(index: number) {+ const [url, options] = fetchMock.mock.calls[index]+ return {+ url,+ method: options?.method,+ body: typeof options?.body === "string" ? JSON.parse(options.body) : undefined,+ }+}++describe("Resend contact lifecycle with the official SDK", () => {+ beforeEach(() => {+ fetchMock.mockReset()+ logs.warn.mockReset()+ vi.stubGlobal("fetch", fetchMock)+ vi.stubEnv("NODE_ENV", "development")+ vi.spyOn(console, "error")+ })+ afterEach(() => {+ expect(console.error).not.toHaveBeenCalled()+ for (const value of [user.email, user.name, env.RESEND_API_KEY]) {+ expect(JSON.stringify(logs.warn.mock.calls)).not.toContain(value)+ }+ vi.unstubAllGlobals()+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+ })++ it.each([undefined, ""])("skips all SDK network work without a Key (%s)", async (key) => {+ const noKey = { RESEND_API_KEY: key } as Env+ await syncResendSignupContact(noKey, user)+ await unsubscribeResendContact(noKey, user.email)+ expect(fetchMock).not.toHaveBeenCalled()+ expect(logs.warn).not.toHaveBeenCalled()+ })++ it("creates a definitely missing contact with the exact segment and no subscription reset", async () => {+ fetchMock.mockResolvedValueOnce(providerError(404, "not_found"))+ .mockResolvedValueOnce(response({ id: "new-contact", object: "contact" }))++ await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()++ expect(fetchMock).toHaveBeenCalledTimes(2)+ expect(requestAt(0)).toEqual({+ url: `https://api.resend.com/contacts/${user.email}`, method: "GET", body: undefined,+ })+ expect(requestAt(1)).toEqual({+ url: "https://api.resend.com/contacts", method: "POST",+ body: { email: user.email, first_name: user.name, segments: [{ id: segmentId }] },+ })+ expect(logs.warn).not.toHaveBeenCalled()+ })++ it.each([false, true])("keeps existing subscription state (%s) while updating and joining New Signups", async (unsubscribed) => {+ fetchMock.mockResolvedValueOnce(existingContact(unsubscribed))+ .mockResolvedValueOnce(response({ id: "contact-1", object: "contact" }))+ .mockResolvedValueOnce(response({ id: segmentId }))++ await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()++ expect(fetchMock).toHaveBeenCalledTimes(3)+ expect(requestAt(1)).toEqual({+ url: "https://api.resend.com/contacts/contact-1", method: "PATCH",+ body: { first_name: user.name },+ })+ expect(requestAt(2)).toEqual({+ url: `https://api.resend.com/contacts/contact-1/segments/${segmentId}`,+ method: "POST", body: undefined,+ })+ expect(logs.warn).not.toHaveBeenCalled()+ })++ it.each([[429, "rate_limit_exceeded"], [404, "validation_error"]])(+ "does not create after an uncertain lookup error (%i %s)", async (status, name) => {+ fetchMock.mockResolvedValueOnce(providerError(status, name))+ await syncResendSignupContact(env, user)+ expect(fetchMock).toHaveBeenCalledOnce()+ expect(logs.warn).toHaveBeenCalledWith("resend_contact_sync_failed", {+ action: "signup", stage: "lookup", errorCategory: "provider_error", statusCode: status,+ })+ expect(JSON.stringify(logs.warn.mock.calls)).not.toContain(privateError)+ },+ )++ it.each(["create", "update", "segment"] as const)("contains a %s response error and stops dependent calls", async (stage) => {+ fetchMock.mockResolvedValueOnce(stage === "create" ? providerError(404, "not_found") : existingContact(true))+ if (stage === "segment") fetchMock.mockResolvedValueOnce(response({ id: "contact-1" }))+ fetchMock.mockResolvedValueOnce(providerError(500))++ await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()++ expect(fetchMock).toHaveBeenCalledTimes(stage === "segment" ? 3 : 2)+ expect(logs.warn).toHaveBeenCalledWith("resend_contact_sync_failed", {+ action: "signup", stage, errorCategory: "provider_error", statusCode: 500,+ })+ expect(JSON.stringify(logs.warn.mock.calls)).not.toContain(privateError)+ })++ it("contains a rejected SDK request without logging its raw error", async () => {+ fetchMock.mockRejectedValueOnce(new Error(privateError))+ await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()+ expect(fetchMock).toHaveBeenCalledOnce()+ expect(logs.warn).toHaveBeenCalledWith("resend_contact_sync_failed", {+ action: "signup", stage: "lookup", errorCategory: "provider_error",+ })+ expect(JSON.stringify(logs.warn.mock.calls)).not.toContain(privateError)+ })++ it("retains the deleted account's contact with a global unsubscribe only", async () => {+ fetchMock.mockResolvedValueOnce(response({ id: "contact-1", object: "contact" }))+ await expect(unsubscribeResendContact(env, user.email)).resolves.toBeUndefined()+ expect(fetchMock).toHaveBeenCalledOnce()+ expect(requestAt(0)).toEqual({+ url: `https://api.resend.com/contacts/${user.email}`, method: "PATCH",+ body: { unsubscribed: true },+ })+ expect(logs.warn).not.toHaveBeenCalled()+ })++ it.each([404, 429, 500])("contains an unsubscribe response failure (%i) without creating/removing a contact", async (status) => {+ fetchMock.mockResolvedValueOnce(providerError(status, status === 404 ? "not_found" : "application_error"))+ await expect(unsubscribeResendContact(env, user.email)).resolves.toBeUndefined()+ expect(fetchMock).toHaveBeenCalledOnce()+ expect(logs.warn).toHaveBeenCalledWith("resend_contact_sync_failed", {+ action: "account-deletion", stage: "update", errorCategory: "provider_error", statusCode: status,+ })+ expect(JSON.stringify(logs.warn.mock.calls)).not.toContain(privateError)+ })++ it("contains a malformed successful SDK response as a sanitized exception", async () => {+ fetchMock.mockResolvedValueOnce(response(null))+ await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()+ expect(fetchMock).toHaveBeenCalledOnce()+ expect(logs.warn).toHaveBeenCalledWith("resend_contact_sync_failed", {+ action: "signup", stage: "update", errorCategory: "exception",+ })+ })++ it("contains SDK constructor exceptions in both operations without raw console logs", async () => {+ const invalidEnv = { RESEND_API_KEY: "mock\ninvalid" } as Env+ await expect(syncResendSignupContact(invalidEnv, user)).resolves.toBeUndefined()+ await expect(unsubscribeResendContact(invalidEnv, user.email)).resolves.toBeUndefined()+ expect(fetchMock).not.toHaveBeenCalled()+ expect(logs.warn.mock.calls).toEqual([+ ["resend_contact_sync_failed", { action: "signup", stage: "lookup", errorCategory: "exception" }],+ ["resend_contact_sync_failed", { action: "account-deletion", stage: "update", errorCategory: "exception" }],+ ])+ })+})diff --git a/src/web/src/lib/resend-contacts.ts b/src/web/src/lib/resend-contacts.tsnew file mode 100644index 000000000..1b762c431--- /dev/null+++ b/src/web/src/lib/resend-contacts.ts@@ -0,0 +1,79 @@+import { createLogger } from "@alook/shared"+import { Resend } from "resend"++const log = createLogger({ service: "resend-contacts" })+const NEW_SIGNUPS_SEGMENT_ID = "6701946e-a7e2-442b-8fa5-aba379a81248"++type ContactAction = "signup" | "account-deletion"+type ContactStage = "lookup" | "create" | "update" | "segment"++function logProviderFailure(+ action: ContactAction,+ stage: ContactStage,+ statusCode: number | null,+): void {+ log.warn("resend_contact_sync_failed", {+ action,+ stage,+ errorCategory: "provider_error",+ ...(Number.isInteger(statusCode) && statusCode !== null && statusCode >= 100 && statusCode <= 599+ ? { statusCode }+ : {}),+ })+}++export async function syncResendSignupContact(+ env: Env,+ user: { email: string; name: string },+): Promise<void> {+ if (!env.RESEND_API_KEY) return+ let stage: ContactStage = "lookup"+ try {+ const resend = new Resend(env.RESEND_API_KEY)+ const contact = await resend.contacts.get({ email: user.email })+ if (contact.error) {+ if (contact.error.name !== "not_found" || contact.error.statusCode !== 404) {+ logProviderFailure("signup", stage, contact.error.statusCode)+ return+ }+ stage = "create"+ const created = await resend.contacts.create({+ email: user.email,+ firstName: user.name,+ segments: [{ id: NEW_SIGNUPS_SEGMENT_ID }],+ })+ if (created.error) logProviderFailure("signup", stage, created.error.statusCode)+ return+ }++ stage = "update"+ const updated = await resend.contacts.update({ id: contact.data.id, firstName: user.name })+ if (updated.error) {+ logProviderFailure("signup", stage, updated.error.statusCode)+ return+ }+ stage = "segment"+ const added = await resend.contacts.segments.add({+ contactId: contact.data.id,+ segmentId: NEW_SIGNUPS_SEGMENT_ID,+ })+ if (added.error) logProviderFailure("signup", stage, added.error.statusCode)+ } catch {+ log.warn("resend_contact_sync_failed", { action: "signup", stage, errorCategory: "exception" })+ }+}++export async function unsubscribeResendContact(env: Env, email: string): Promise<void> {+ if (!env.RESEND_API_KEY) return+ try {+ const resend = new Resend(env.RESEND_API_KEY)+ const updated = await resend.contacts.update({ email, unsubscribed: true })+ if (updated.error) logProviderFailure("account-deletion", "update", updated.error.statusCode)+ } catch {+ log.warn("resend_contact_sync_failed", {+ action: "account-deletion",+ stage: "update",+ errorCategory: "exception",+ })+ }+}diff --git a/src/web/test-runtime/resend-contacts.runtime.test.ts b/src/web/test-runtime/resend-contacts.runtime.test.tsnew file mode 100644index 000000000..84a579886--- /dev/null+++ b/src/web/test-runtime/resend-contacts.runtime.test.ts@@ -0,0 +1,69 @@+/// <reference types="@cloudflare/vitest-plugin/types" />++import { createExecutionContext, waitOnExecutionContext } from "cloudflare:test"+import { afterEach, describe, expect, it, vi } from "vitest"+import { syncResendSignupContact, unsubscribeResendContact } from "../src/lib/resend-contacts"++const env = { RESEND_API_KEY: "mock-runtime-key" } as Env+const user = { email: "[email protected]", name: "Runtime QA" }+const segmentId = "6701946e-a7e2-442b-8fa5-aba379a81248"++afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe("official Resend SDK in workerd", () => {+ it("loads the SDK and creates a contact within the original execution context", async () => {+ const fetchMock = vi.fn<typeof fetch>()+ .mockResolvedValueOnce(Response.json({ name: "not_found", statusCode: 404, message: "Missing contact" }, { status: 404 }))+ .mockResolvedValueOnce(Response.json({ id: "runtime-contact", object: "contact" }))+ vi.stubGlobal("fetch", fetchMock)+ const context = createExecutionContext()+ context.waitUntil(syncResendSignupContact(env, user))+ const response = new Response("created")+ expect(await response.text()).toBe("created")+ await waitOnExecutionContext(context)++ expect(fetchMock).toHaveBeenCalledTimes(2)+ expect(fetchMock.mock.calls[1]?.[0]).toBe("https://api.resend.com/contacts")+ expect(JSON.parse(fetchMock.mock.calls[1]?.[1]?.body as string)).toEqual({+ email: user.email, first_name: user.name, segments: [{ id: segmentId }],+ })+ })++ it("contains unsubscribe provider failure without leaking its body or email through console", async () => {+ const privateError = `${user.email} ${user.name} ${env.RESEND_API_KEY}`+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(Response.json({+ name: "rate_limit_exceeded", statusCode: 429, message: privateError,+ }, { status: 429 }))+ vi.stubGlobal("fetch", fetchMock)+ const log = vi.spyOn(console, "log")+ const error = vi.spyOn(console, "error")+ const context = createExecutionContext()+ context.waitUntil(unsubscribeResendContact(env, user.email))+ await expect(waitOnExecutionContext(context)).resolves.toBeUndefined()+ expect(fetchMock).toHaveBeenCalledOnce()+ expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("PATCH")+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toEqual({ unsubscribed: true })+ expect(error).not.toHaveBeenCalled()+ const entry = JSON.parse(log.mock.calls[0]?.[0] as string)+ expect(entry).toMatchObject({+ service: "resend-contacts", msg: "resend_contact_sync_failed", action: "account-deletion",+ stage: "update", errorCategory: "provider_error", statusCode: 429,+ })+ for (const value of [user.email, user.name, env.RESEND_API_KEY]) {+ expect(JSON.stringify(log.mock.calls)).not.toContain(value)+ }+ })++ it("skips both operations with the optional binding absent", async () => {+ const fetchMock = vi.fn<typeof fetch>()+ vi.stubGlobal("fetch", fetchMock)+ const context = createExecutionContext()+ context.waitUntil(syncResendSignupContact({} as Env, user))+ context.waitUntil(unsubscribeResendContact({} as Env, user.email))+ await waitOnExecutionContext(context)+ expect(fetchMock).not.toHaveBeenCalled()+ })+})