From 50e4cb187ca928c2652817164cfbe5b2fe3787b2 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Mon, 23 Nov 2026 16:27:07 +1100 Subject: [PATCH 1/6] feat(guard): feed of new API emails, pause older teams for phishing or scams (with evidence), ignore suppressed-address bounces --- .../src/app/api/admin/guard/emails/route.ts | 16 +++ .../src/app/api/admin/guard/route.api.test.ts | 32 ++++- apps/web/src/server/service/guard-service.ts | 131 +++++++++++++++++- .../server/service/guard-service.unit.test.ts | 127 ++++++++++++++++- .../web/src/server/service/ses-hook-parser.ts | 21 ++- .../service/ses-hook-parser.unit.test.ts | 21 ++- apps/web/src/types/aws-types.ts | 2 +- 7 files changed, 331 insertions(+), 19 deletions(-) create mode 100644 apps/web/src/app/api/admin/guard/emails/route.ts diff --git a/apps/web/src/app/api/admin/guard/emails/route.ts b/apps/web/src/app/api/admin/guard/emails/route.ts new file mode 100644 index 000000000..fbcb1d473 --- /dev/null +++ b/apps/web/src/app/api/admin/guard/emails/route.ts @@ -0,0 +1,16 @@ +import { adminApiRoute } from "~/server/admin-api"; +import { listNewEmails, newEmailsQuery } from "~/server/service/guard-service"; + +export const dynamic = "force-dynamic"; + +/** + * GET /api/admin/guard/emails?cursor=&limit=<1-200> + * New API and SMTP emails across all teams, oldest first. Pass `nextCursor` + * back to continue; without a cursor it starts 10 minutes ago. + */ +export const GET = adminApiRoute(async ({ req }) => { + const url = new URL(req.url); + return listNewEmails( + newEmailsQuery.parse(Object.fromEntries(url.searchParams)), + ); +}); diff --git a/apps/web/src/app/api/admin/guard/route.api.test.ts b/apps/web/src/app/api/admin/guard/route.api.test.ts index c1c754b7a..4b27395ea 100644 --- a/apps/web/src/app/api/admin/guard/route.api.test.ts +++ b/apps/web/src/app/api/admin/guard/route.api.test.ts @@ -4,6 +4,7 @@ const { mockEnv, mocks } = vi.hoisted(() => ({ mockEnv: { ADMIN_API_TOKEN: undefined as string | undefined }, mocks: { listApplications: vi.fn(), + listNewEmails: vi.fn(), listActiveCampaigns: vi.fn(), markGuardSeen: vi.fn(), guardReviewCampaign: vi.fn(), @@ -31,6 +32,7 @@ vi.mock("~/server/service/campaign-service", () => ({ import { GET as getApplications } from "~/app/api/admin/guard/applications/route"; import { GET as getCampaigns } from "~/app/api/admin/guard/campaigns/route"; +import { GET as getNewEmails } from "~/app/api/admin/guard/emails/route"; import { POST as postReview } from "~/app/api/admin/guard/campaigns/[id]/review/route"; import { GET as getTeams } from "~/app/api/admin/guard/teams/route"; import { GET as getEmails } from "~/app/api/admin/guard/teams/[id]/emails/route"; @@ -93,6 +95,26 @@ describe("Guard admin API", () => { ); }); + it("lists new emails from a cursor, and rejects a bad one", async () => { + const ok = await getNewEmails( + get( + "/api/admin/guard/emails?cursor=2026-11-23T10%3A00%3A00.000Z%7Ce9&limit=50", + ), + ctx(), + ); + expect(ok.status).toBe(200); + expect(mocks.listNewEmails).toHaveBeenCalledWith({ + cursor: "2026-11-23T10:00:00.000Z|e9", + limit: 50, + }); + + const bad = await getNewEmails( + get("/api/admin/guard/emails?cursor=nope"), + ctx(), + ); + expect(bad.status).toBe(400); + }); + it("lists new teams for 14 days by default", async () => { await getTeams(get("/api/admin/guard/teams"), ctx()); expect(mocks.listWatchedTeams).toHaveBeenCalledWith({ @@ -102,7 +124,10 @@ describe("Guard admin API", () => { }); it("pages campaigns", async () => { - await getCampaigns(get("/api/admin/guard/campaigns?limit=10&cursor=c9"), ctx()); + await getCampaigns( + get("/api/admin/guard/campaigns?limit=10&cursor=c9"), + ctx(), + ); expect(mocks.markGuardSeen).toHaveBeenCalled(); expect(mocks.listActiveCampaigns).toHaveBeenCalledWith({ limit: 10, @@ -141,7 +166,10 @@ describe("Guard admin API", () => { new GuardForbiddenError("first 14 days"), ); const response = await postAction( - post("/api/admin/guard/teams/7/actions", { action: "PAUSE", reason: "x" }), + post("/api/admin/guard/teams/7/actions", { + action: "PAUSE", + reason: "x", + }), ctx({ id: "7" }), ); expect(response.status).toBe(403); diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 33f8ceee9..4d02c0178 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -8,12 +8,14 @@ import { logger } from "~/server/logger/log"; import IORedis from "ioredis"; import { redisKey } from "~/server/redis"; import { TeamService } from "~/server/service/team-service"; +import { emailTeam } from "~/server/service/team-email"; /** * What the Guard (our separate review service) can read and do, through the * internal admin API. It reads applications, campaigns, new teams and their * emails; it can approve or stop a campaign, log an alert, and pause a team. - * It can never block or resume a team, or delete anything. + * It can never block or resume a team, or delete anything. It pauses older + * teams only for phishing or scams, naming the emails that show it. * * New teams' campaigns wait for the Guard's check before sending, but only * while the Guard is running (it checks in by listing campaigns), and only @@ -233,7 +235,8 @@ export async function listActiveCampaigns( select: { id: true }, }); const pageIds = rows.slice(0, query.limit).map((row) => row.id); - const nextCursor = rows.length > query.limit ? (pageIds.at(-1) ?? null) : null; + const nextCursor = + rows.length > query.limit ? (pageIds.at(-1) ?? null) : null; if (pageIds.length === 0) return { items: [], nextCursor }; const campaigns = await db.campaign.findMany({ @@ -419,8 +422,34 @@ export const teamActionBody = z.object({ action: z.enum(["ALERT", "PAUSE"]), reason: z.string().trim().min(1).max(2_000), details: z.record(z.unknown()).optional(), + /** Needed to pause a team past its first 14 days. */ + abuse: z.enum(["phishing", "scam"]).optional(), + /** The team's emails that show the abuse. Needed with `abuse`. */ + emailIds: z.array(z.string().min(1)).min(1).max(20).optional(), }); +const ABUSE_LABEL = { + phishing: + "phishing (pretending to be another company to get people's details)", + scam: "a scam", +} as const; + +/** The email a team gets when the Guard pauses it for phishing or a scam. */ +export function abusePauseEmail(input: { + teamName: string; + abuse: keyof typeof ABUSE_LABEL; + subjects: string[]; +}) { + const subjects = input.subjects + .slice(0, 3) + .map((subject) => `- "${subject.slice(0, 150)}"`) + .join("\n"); + return { + subject: "useSend: we paused sending on your account", + text: `Hi ${input.teamName} team,\n\nWe paused sending on your useSend account because emails sent from it look like ${ABUSE_LABEL[input.abuse]}, for example:\n${subjects}\n\nIf you didn't send these, one of your API keys has probably leaked, often from a hacked website. Delete that key in useSend, create a new one, and check the site that used it.\n\nReply to this email and we'll turn sending back on once it's sorted. While sending is paused, new emails fail instead of going out.\n\nuseSend`, + }; +} + /** * ALERT only logs. PAUSE stops the team's sending and its campaigns, like an * admin pause, for new teams only; an admin @@ -432,7 +461,7 @@ export async function recordTeamAction( ) { const team = await db.team.findUnique({ where: { id: teamId }, - select: { id: true, createdAt: true }, + select: { id: true, name: true, createdAt: true }, }); if (!team) throw new GuardNotFoundError("Team not found"); @@ -455,7 +484,24 @@ export async function recordTeamAction( return { ok: true, changed: false }; } - assertGuardMayAct(team); + // New teams can be paused for anything clear; older teams only for + // phishing or scams, with the emails that show it. + let evidence: Array<{ subject: string }> = []; + if (body.abuse) { + const ids = [...new Set(body.emailIds ?? [])]; + if (ids.length === 0) { + throw new GuardForbiddenError("Name the emails that show it (emailIds)"); + } + evidence = await db.email.findMany({ + where: { id: { in: ids }, teamId }, + select: { subject: true }, + }); + if (evidence.length !== ids.length) { + throw new GuardForbiddenError("Some of those emails aren't this team's"); + } + } else { + assertGuardMayAct(team); + } const changed = await db.$transaction(async (tx) => { await tx.$queryRaw`SELECT id FROM "Team" WHERE id = ${teamId} FOR UPDATE`; @@ -487,6 +533,83 @@ export async function recordTeamAction( // The cache expires within 2 minutes anyway. logger.error({ err: error, teamId }, "[Guard]: Cache refresh failed"); } + if (body.abuse) { + // Tell them, so they can find a leaked key. emailTeam never throws. + const message = abusePauseEmail({ + teamName: team.name, + abuse: body.abuse, + subjects: [...new Set(evidence.map((email) => email.subject))], + }); + await emailTeam(teamId, message.subject, message.text); + } } return { ok: true, changed }; } + +// --- New emails (API and SMTP, not campaigns) --- + +export const newEmailsQuery = z.object({ + /** From `nextCursor`; without it, starts from the last 10 minutes. */ + cursor: z + .string() + .regex(/^\d{4}-\d\d-\d\dT[\d:.]+Z\|[\w-]+$/) + .optional(), + limit: z.coerce.number().int().min(1).max(200).default(100), +}); + +/** + * Emails sent through the API or SMTP since the cursor, oldest first, across + * all teams, for the Guard's content check. Campaign emails are checked + * through their campaign instead. Recipients are reduced to their domains. + */ +export async function listNewEmails(query: z.infer) { + const [afterIso, afterId] = query.cursor?.split("|") ?? []; + const after = afterIso + ? new Date(afterIso) + : new Date(Date.now() - 10 * 60_000); + const rows = await db.email.findMany({ + where: { + campaignId: null, + OR: [ + { createdAt: { gt: after } }, + ...(afterId ? [{ createdAt: after, id: { gt: afterId } }] : []), + ], + }, + orderBy: [{ createdAt: "asc" }, { id: "asc" }], + take: query.limit, + select: { + id: true, + createdAt: true, + from: true, + to: true, + replyTo: true, + subject: true, + text: true, + html: true, + team: { + select: { + id: true, + name: true, + createdAt: true, + isBlocked: true, + sendingPausedAt: true, + }, + }, + }, + }); + const last = rows.at(-1); + return { + items: rows.map(({ to, text, html, team, ...email }) => ({ + ...email, + toDomains: [ + ...new Set(to.map((address) => address.split("@")[1] ?? "")), + ].filter(Boolean), + text: truncate(text, EMAIL_TEXT_MAX), + html: truncate(html, EMAIL_TEXT_MAX), + team: { ...team, isNew: isNewTeam(team) }, + })), + nextCursor: last + ? `${last.createdAt.toISOString()}|${last.id}` + : (query.cursor ?? `${after.toISOString()}|`), + }; +} diff --git a/apps/web/src/server/service/guard-service.unit.test.ts b/apps/web/src/server/service/guard-service.unit.test.ts index 4a3f744c7..cc6a69e6c 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -31,6 +31,8 @@ vi.mock("~/server/logger/log", () => ({ vi.mock("~/server/service/team-service", () => ({ TeamService: { refreshTeamCache: mockRefreshTeamCache }, })); +const { mockEmailTeam } = vi.hoisted(() => ({ mockEmailTeam: vi.fn() })); +vi.mock("~/server/service/team-email", () => ({ emailTeam: mockEmailTeam })); import { GuardForbiddenError, @@ -40,6 +42,7 @@ import { markGuardSeen, isReviewHeld, listActiveCampaigns, + listNewEmails, recordTeamAction, reviewHoldFor, sampleTeamEmails, @@ -148,9 +151,9 @@ describe("campaignContentHash", () => { }; const hash = campaignContentHash(base); expect(campaignContentHash({ ...base })).toBe(hash); - expect( - campaignContentHash({ ...base, replyTo: ["other@y.com"] }), - ).not.toBe(hash); + expect(campaignContentHash({ ...base, replyTo: ["other@y.com"] })).not.toBe( + hash, + ); expect(campaignContentHash({ ...base, subject: "Hey" })).not.toBe(hash); expect(campaignContentHash({ ...base, html: "

2

" })).not.toBe(hash); expect(campaignContentHash({ ...base, content: '{"doc":1}' })).not.toBe( @@ -308,6 +311,70 @@ describe("recordTeamAction", () => { expect(mockDb.team.updateMany).not.toHaveBeenCalled(); }); + describe("an older team", () => { + beforeEach(() => { + mockDb.team.findUnique.mockResolvedValue({ + id: 7, + name: "Motionstack", + createdAt: new Date(Date.now() - 365 * DAY), + }); + mockDb.team.updateMany.mockResolvedValue({ count: 1 }); + mockDb.campaign.updateMany.mockResolvedValue({ count: 0 }); + }); + + it("is paused for phishing, with the emails that show it, and told why", async () => { + mockDb.email.findMany.mockResolvedValue([ + { subject: "Your E-ZPass Invoice Notification" }, + { subject: "Your E-ZPass Invoice Notification" }, + ]); + + const result = await recordTeamAction(7, { + action: "PAUSE", + reason: "E-ZPass phishing", + abuse: "phishing", + emailIds: ["e1", "e2"], + }); + + expect(result.changed).toBe(true); + expect(mockDb.email.findMany).toHaveBeenCalledWith({ + where: { id: { in: ["e1", "e2"] }, teamId: 7 }, + select: { subject: true }, + }); + expect(mockEmailTeam).toHaveBeenCalledTimes(1); + const [, subject, text] = mockEmailTeam.mock.calls[0]!; + expect(subject).toContain("paused"); + expect(text).toContain("Your E-ZPass Invoice Notification"); + expect(text).toContain("API keys has probably leaked"); + // The AI's own wording never reaches the customer. + expect(text).not.toContain("E-ZPass phishing"); + }); + + it("isn't paused for anything else", async () => { + await expect( + recordTeamAction(7, { action: "PAUSE", reason: "spammy" }), + ).rejects.toBeInstanceOf(GuardForbiddenError); + expect(mockDb.team.updateMany).not.toHaveBeenCalled(); + }); + + it("isn't paused without evidence, or with another team's emails", async () => { + await expect( + recordTeamAction(7, { action: "PAUSE", reason: "x", abuse: "scam" }), + ).rejects.toThrow("emailIds"); + + mockDb.email.findMany.mockResolvedValue([{ subject: "a" }]); + await expect( + recordTeamAction(7, { + action: "PAUSE", + reason: "x", + abuse: "scam", + emailIds: ["mine", "someone-elses"], + }), + ).rejects.toThrow("aren't this team's"); + expect(mockDb.team.updateMany).not.toHaveBeenCalled(); + expect(mockEmailTeam).not.toHaveBeenCalled(); + }); + }); + it("says when the team doesn't exist", async () => { mockDb.team.findUnique.mockResolvedValue(null); await expect( @@ -341,3 +408,57 @@ describe("sampleTeamEmails", () => { expect(items[0]?.html).toBe("

Hi there

"); }); }); + +describe("listNewEmails", () => { + const row = (id: string, at: string) => ({ + id, + createdAt: new Date(at), + from: "a@acme.com", + to: ["x@gmail.com", "y@gmail.com"], + replyTo: [], + subject: "Hi", + text: "t", + html: null, + team: { + id: 7, + name: "Acme", + createdAt: new Date(Date.now() - DAY), + isBlocked: false, + sendingPausedAt: null, + }, + }); + + it("pages through API emails with a cursor that never skips a tie", async () => { + mockDb.email.findMany.mockResolvedValue([ + row("e1", "2026-11-23T10:00:00.000Z"), + row("e2", "2026-11-23T10:00:01.000Z"), + ]); + + const page = await listNewEmails({ + cursor: "2026-11-23T09:59:59.000Z|e0", + limit: 2, + }); + + const query = mockDb.email.findMany.mock.calls[0]![0]; + expect(query.where).toEqual({ + campaignId: null, + OR: [ + { createdAt: { gt: new Date("2026-11-23T09:59:59.000Z") } }, + { createdAt: new Date("2026-11-23T09:59:59.000Z"), id: { gt: "e0" } }, + ], + }); + expect(page.nextCursor).toBe("2026-11-23T10:00:01.000Z|e2"); + expect(page.items[0]).toMatchObject({ toDomains: ["gmail.com"] }); + expect(page.items[0]).not.toHaveProperty("to"); + expect(page.items[0]!.team.isNew).toBe(true); + }); + + it("keeps the cursor when nothing is new", async () => { + mockDb.email.findMany.mockResolvedValue([]); + const page = await listNewEmails({ + cursor: "2026-11-23T10:00:00.000Z|e9", + limit: 100, + }); + expect(page.nextCursor).toBe("2026-11-23T10:00:00.000Z|e9"); + }); +}); diff --git a/apps/web/src/server/service/ses-hook-parser.ts b/apps/web/src/server/service/ses-hook-parser.ts index 263daded9..290a4bfeb 100644 --- a/apps/web/src/server/service/ses-hook-parser.ts +++ b/apps/web/src/server/service/ses-hook-parser.ts @@ -136,6 +136,13 @@ export async function parseSesHook(data: SesEvent) { const isHardBounced = mailStatus === EmailStatus.BOUNCED && (mailData as SesBounce).bounceType === "Permanent"; + // SES never tried to deliver to an address on our account's suppression + // list, and AWS doesn't count it toward the bounce rate. Neither do we: a + // team re-sending to one address shouldn't look like a bad list. + const countsAsHardBounce = + isHardBounced && + String((mailData as SesBounce).bounceSubType ?? "").trim() !== + "OnAccountSuppressionList"; // Fix: Only add the actual bounced/complained recipients to suppression list // Add emails to suppression list for hard bounces and complaints @@ -210,7 +217,7 @@ export async function parseSesHook(data: SesEvent) { // SES can deliver the same hard bounce or complaint more than once. Count // each only once per email: the sending rules and dashboards rely on it. - const outcome = isHardBounced + const outcome = countsAsHardBounce ? ("hardBounced" as const) : mailStatus === EmailStatus.COMPLAINED ? ("complained" as const) @@ -259,24 +266,24 @@ export async function parseSesHook(data: SesEvent) { bounced: updateField === "bounced" ? 1 : 0, complained: updateField === "complained" ? 1 : 0, sent: updateField === "sent" ? 1 : 0, - hardBounced: isHardBounced ? 1 : 0, + hardBounced: countsAsHardBounce ? 1 : 0, }, update: { [updateField]: { increment: 1, }, - ...(isHardBounced ? { hardBounced: { increment: 1 } } : {}), + ...(countsAsHardBounce ? { hardBounced: { increment: 1 } } : {}), }, }), ]; if ( - isHardBounced || + countsAsHardBounce || updateField === "complained" || updateField === "delivered" ) { logger.info("Updating cumulated metrics"); - const cumulatedField = isHardBounced ? "hardBounced" : updateField; + const cumulatedField = countsAsHardBounce ? "hardBounced" : updateField; usageWrites.push( db.cumulatedMetrics.upsert({ where: { @@ -327,7 +334,7 @@ export async function parseSesHook(data: SesEvent) { await updateCampaignAnalytics( email.campaignId, mailStatus, - isHardBounced, + countsAsHardBounce, ); } } @@ -340,7 +347,7 @@ export async function parseSesHook(data: SesEvent) { await checkSendingHealth({ teamId: email.teamId, campaignId: email.campaignId, - spamTrap: isHardBounced && isSpamTrapBounce(data.bounce), + spamTrap: countsAsHardBounce && isSpamTrapBounce(data.bounce), }); } catch (error) { // Never fail event processing because of the rules. diff --git a/apps/web/src/server/service/ses-hook-parser.unit.test.ts b/apps/web/src/server/service/ses-hook-parser.unit.test.ts index 1784a4b10..de865b1cc 100644 --- a/apps/web/src/server/service/ses-hook-parser.unit.test.ts +++ b/apps/web/src/server/service/ses-hook-parser.unit.test.ts @@ -215,13 +215,16 @@ describe("parseSesHook sending rules", () => { mockClaimOutcome.mockResolvedValue("claimed"); }); - function bounceEvent(diagnosticCode: string): SesEvent { + function bounceEvent( + diagnosticCode: string, + bounceSubType = "General", + ): SesEvent { const event = buildEvent("Open"); delete event.open; event.eventType = "Bounce"; event.bounce = { bounceType: "Permanent", - bounceSubType: "General", + bounceSubType, bouncedRecipients: [ { emailAddress: "recipient@example.com", diagnosticCode }, ], @@ -266,6 +269,20 @@ describe("parseSesHook sending rules", () => { ); }); + it("doesn't count a send to an address on the SES suppression list, like AWS", async () => { + await parseSesHook( + bounceEvent("Amazon SES did not send", "OnAccountSuppressionList"), + ); + + expect(mockClaimOutcome).not.toHaveBeenCalled(); + expect(mockCheckSendingHealth).not.toHaveBeenCalled(); + const usage = mockDb.dailyEmailUsage.upsert.mock.calls[0]?.[0]; + expect(usage.create.hardBounced).toBe(0); + expect(usage.update).not.toHaveProperty("hardBounced"); + // Still a bounce on the dashboard, just not a hard one. + expect(usage.update.bounced).toEqual({ increment: 1 }); + }); + it("counts a repeated hard bounce only once", async () => { mockClaimOutcome.mockResolvedValue("duplicate"); diff --git a/apps/web/src/types/aws-types.ts b/apps/web/src/types/aws-types.ts index fc574c11c..46dda7d6e 100644 --- a/apps/web/src/types/aws-types.ts +++ b/apps/web/src/types/aws-types.ts @@ -35,7 +35,7 @@ export interface SesBounce { | "General" | "NoEmail" | "Suppressed" - | "OnAccountSuppressionList " + | "OnAccountSuppressionList" | "MailboxFull" | "MessageTooLarge" | "ContentRejected" From a6bd4845781fd5537c1de1e70cbfe419fc89468c Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Mon, 23 Nov 2026 16:30:45 +1100 Subject: [PATCH 2/6] fix(guard): email feed cursor narrows by date first so it always uses the createdAt index --- apps/web/src/server/service/guard-service.ts | 8 ++++---- apps/web/src/server/service/guard-service.unit.test.ts | 7 +++---- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 4d02c0178..295da7756 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -570,10 +570,10 @@ export async function listNewEmails(query: z.infer) { const rows = await db.email.findMany({ where: { campaignId: null, - OR: [ - { createdAt: { gt: after } }, - ...(afterId ? [{ createdAt: after, id: { gt: afterId } }] : []), - ], + // A date range first, so the createdAt index does the work; then skip + // what the last page already returned at that same instant. + createdAt: { gte: after }, + ...(afterId ? { NOT: { createdAt: after, id: { lte: afterId } } } : {}), }, orderBy: [{ createdAt: "asc" }, { id: "asc" }], take: query.limit, diff --git a/apps/web/src/server/service/guard-service.unit.test.ts b/apps/web/src/server/service/guard-service.unit.test.ts index cc6a69e6c..05a8cc0b6 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -440,12 +440,11 @@ describe("listNewEmails", () => { }); const query = mockDb.email.findMany.mock.calls[0]![0]; + const at = new Date("2026-11-23T09:59:59.000Z"); expect(query.where).toEqual({ campaignId: null, - OR: [ - { createdAt: { gt: new Date("2026-11-23T09:59:59.000Z") } }, - { createdAt: new Date("2026-11-23T09:59:59.000Z"), id: { gt: "e0" } }, - ], + createdAt: { gte: at }, + NOT: { createdAt: at, id: { lte: "e0" } }, }); expect(page.nextCursor).toBe("2026-11-23T10:00:01.000Z|e2"); expect(page.items[0]).toMatchObject({ toDomains: ["gmail.com"] }); From 2aa5080bf698b004bf1aceaafff09ce17e1a9ad6 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Mon, 23 Nov 2026 16:32:12 +1100 Subject: [PATCH 3/6] fix(guard): accept the date-only starting cursor; clean quoted subjects in the pause email --- apps/web/src/server/service/guard-service.ts | 14 +++++++-- .../server/service/guard-service.unit.test.ts | 29 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 295da7756..ba71158d9 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -440,9 +440,19 @@ export function abusePauseEmail(input: { abuse: keyof typeof ABUSE_LABEL; subjects: string[]; }) { + // Their own subjects, but cleaned: one line, no links or domains, short. const subjects = input.subjects + .map((subject) => + subject + .replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi, "") + .replace(/\b(?:[a-z0-9-]+\.)+[a-z]{2,24}\b(?:\/\S*)?/gi, "") + .replace(/\s+/g, " ") + .trim() + .slice(0, 100), + ) + .filter(Boolean) .slice(0, 3) - .map((subject) => `- "${subject.slice(0, 150)}"`) + .map((subject) => `- "${subject}"`) .join("\n"); return { subject: "useSend: we paused sending on your account", @@ -552,7 +562,7 @@ export const newEmailsQuery = z.object({ /** From `nextCursor`; without it, starts from the last 10 minutes. */ cursor: z .string() - .regex(/^\d{4}-\d\d-\d\dT[\d:.]+Z\|[\w-]+$/) + .regex(/^\d{4}-\d\d-\d\dT[\d:.]+Z\|[\w-]*$/) .optional(), limit: z.coerce.number().int().min(1).max(200).default(100), }); diff --git a/apps/web/src/server/service/guard-service.unit.test.ts b/apps/web/src/server/service/guard-service.unit.test.ts index 05a8cc0b6..0dc265036 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -43,6 +43,8 @@ import { isReviewHeld, listActiveCampaigns, listNewEmails, + newEmailsQuery, + abusePauseEmail, recordTeamAction, reviewHoldFor, sampleTeamEmails, @@ -452,6 +454,18 @@ describe("listNewEmails", () => { expect(page.items[0]!.team.isNew).toBe(true); }); + it("starts with a date-only cursor that it accepts back", async () => { + mockDb.email.findMany.mockResolvedValue([]); + const first = await listNewEmails({ limit: 100 }); + expect(first.nextCursor).toMatch(/\|$/); + expect(newEmailsQuery.parse({ cursor: first.nextCursor }).cursor).toBe( + first.nextCursor, + ); + await listNewEmails({ cursor: first.nextCursor, limit: 100 }); + const query = mockDb.email.findMany.mock.calls[1]![0]; + expect(query.where).not.toHaveProperty("NOT"); + }); + it("keeps the cursor when nothing is new", async () => { mockDb.email.findMany.mockResolvedValue([]); const page = await listNewEmails({ @@ -461,3 +475,18 @@ describe("listNewEmails", () => { expect(page.nextCursor).toBe("2026-11-23T10:00:00.000Z|e9"); }); }); + +describe("abusePauseEmail", () => { + it("quotes subjects on one line, without links", () => { + const { text } = abusePauseEmail({ + teamName: "Acme", + abuse: "phishing", + subjects: [ + "Pay now\nat https://evil.example/x or evil.example today", + "", + ], + }); + expect(text).toContain('- "Pay now at or today"'); + expect(text).not.toContain("evil"); + }); +}); From da73f51e8c7ad6c938ba5e7fc6bc43f6fef1da3c Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Mon, 23 Nov 2026 16:34:08 +1100 Subject: [PATCH 4/6] feat(guard): every Guard pause posts to Discord --- apps/web/src/server/service/guard-service.ts | 22 +++++++++++++++++++ .../server/service/guard-service.unit.test.ts | 13 +++++++++++ 2 files changed, 35 insertions(+) diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index ba71158d9..27d25af92 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -9,6 +9,7 @@ import IORedis from "ioredis"; import { redisKey } from "~/server/redis"; import { TeamService } from "~/server/service/team-service"; import { emailTeam } from "~/server/service/team-email"; +import { sendToDiscord } from "~/server/service/notification-service"; /** * What the Guard (our separate review service) can read and do, through the @@ -543,6 +544,12 @@ export async function recordTeamAction( // The cache expires within 2 minutes anyway. logger.error({ err: error, teamId }, "[Guard]: Cache refresh failed"); } + // Always tell the founder, whatever the agent posts itself. + try { + await sendToDiscord(guardPauseNotice(team, body, evidence.length)); + } catch (error) { + logger.error({ err: error, teamId }, "[Guard]: Discord notice failed"); + } if (body.abuse) { // Tell them, so they can find a leaked key. emailTeam never throws. const message = abusePauseEmail({ @@ -556,6 +563,21 @@ export async function recordTeamAction( return { ok: true, changed }; } +/** The Discord message for every Guard pause. */ +export function guardPauseNotice( + team: { id: number; name: string; createdAt: Date }, + body: z.infer, + evidenceCount: number, +) { + const age = isNewTeam(team) + ? "new team" + : `customer since ${team.createdAt.toISOString().slice(0, 10)}`; + const why = body.abuse + ? `${body.abuse} (${evidenceCount} email${evidenceCount === 1 ? "" : "s"} as evidence). The team has been emailed.` + : "clear abuse."; + return `🛑 **Guard paused ${team.name}** (#${team.id}, ${age}) for ${why}\n${body.reason.slice(0, 600)}\nResume on the admin teams page if it's wrong: ${env.NEXTAUTH_URL}/admin/teams`; +} + // --- New emails (API and SMTP, not campaigns) --- export const newEmailsQuery = z.object({ diff --git a/apps/web/src/server/service/guard-service.unit.test.ts b/apps/web/src/server/service/guard-service.unit.test.ts index 0dc265036..6468032c2 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -33,6 +33,12 @@ vi.mock("~/server/service/team-service", () => ({ })); const { mockEmailTeam } = vi.hoisted(() => ({ mockEmailTeam: vi.fn() })); vi.mock("~/server/service/team-email", () => ({ emailTeam: mockEmailTeam })); +const { mockSendToDiscord } = vi.hoisted(() => ({ + mockSendToDiscord: vi.fn(), +})); +vi.mock("~/server/service/notification-service", () => ({ + sendToDiscord: mockSendToDiscord, +})); import { GuardForbiddenError, @@ -289,6 +295,8 @@ describe("recordTeamAction", () => { data: { status: "PAUSED" }, }); expect(mockRefreshTeamCache).toHaveBeenCalledWith(7); + // Every Guard pause reaches Discord, even without abuse evidence. + expect(mockSendToDiscord).toHaveBeenCalledTimes(1); }); it("does nothing more for a team that's already paused or blocked", async () => { @@ -299,6 +307,7 @@ describe("recordTeamAction", () => { expect(result.changed).toBe(false); expect(mockDb.teamAction.create).not.toHaveBeenCalled(); expect(mockRefreshTeamCache).not.toHaveBeenCalled(); + expect(mockSendToDiscord).not.toHaveBeenCalled(); }); it("won't pause a team past its first 14 days", async () => { @@ -342,6 +351,10 @@ describe("recordTeamAction", () => { where: { id: { in: ["e1", "e2"] }, teamId: 7 }, select: { subject: true }, }); + expect(mockSendToDiscord).toHaveBeenCalledTimes(1); + expect(mockSendToDiscord.mock.calls[0]![0]).toMatch( + /Guard paused Motionstack.*#7.*customer since.*phishing \(2 emails/s, + ); expect(mockEmailTeam).toHaveBeenCalledTimes(1); const [, subject, text] = mockEmailTeam.mock.calls[0]!; expect(subject).toContain("paused"); From 3acc06eb5154a8a3233f734bb7d4d9bb61633820 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Mon, 23 Nov 2026 16:44:37 +1100 Subject: [PATCH 5/6] feat(guard): pause any team for a clear break of the terms, not just phishing; customer email names the rule --- apps/web/src/server/service/guard-service.ts | 34 ++++++++++++--- .../server/service/guard-service.unit.test.ts | 42 +++++++++++++++++++ 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 27d25af92..421d40e22 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -16,7 +16,8 @@ import { sendToDiscord } from "~/server/service/notification-service"; * internal admin API. It reads applications, campaigns, new teams and their * emails; it can approve or stop a campaign, log an alert, and pause a team. * It can never block or resume a team, or delete anything. It pauses older - * teams only for phishing or scams, naming the emails that show it. + * teams only for a clear break of the terms (phishing, scams, cold outreach, + * gambling and the other banned kinds), naming the emails that show it. * * New teams' campaigns wait for the Guard's check before sending, but only * while the Guard is running (it checks in by listing campaigns), and only @@ -423,8 +424,18 @@ export const teamActionBody = z.object({ action: z.enum(["ALERT", "PAUSE"]), reason: z.string().trim().min(1).max(2_000), details: z.record(z.unknown()).optional(), - /** Needed to pause a team past its first 14 days. */ - abuse: z.enum(["phishing", "scam"]).optional(), + /** The rule broken. Needed to pause a team past its first 14 days. */ + abuse: z + .enum([ + "phishing", + "scam", + "cold_outreach", + "gambling", + "adult", + "money_scheme", + "pharma", + ]) + .optional(), /** The team's emails that show the abuse. Needed with `abuse`. */ emailIds: z.array(z.string().min(1)).min(1).max(20).optional(), }); @@ -433,8 +444,17 @@ const ABUSE_LABEL = { phishing: "phishing (pretending to be another company to get people's details)", scam: "a scam", + cold_outreach: + "cold outreach (emails to people who never signed up to hear from you)", + gambling: "gambling or betting", + adult: "adult content", + money_scheme: "crypto, trading, MLM or make-money schemes", + pharma: "pharmaceuticals or supplements with medical claims", } as const; +/** Kinds that usually mean someone else used the account. */ +const LIKELY_LEAKED = new Set(["phishing", "scam"]); + /** The email a team gets when the Guard pauses it for phishing or a scam. */ export function abusePauseEmail(input: { teamName: string; @@ -457,7 +477,11 @@ export function abusePauseEmail(input: { .join("\n"); return { subject: "useSend: we paused sending on your account", - text: `Hi ${input.teamName} team,\n\nWe paused sending on your useSend account because emails sent from it look like ${ABUSE_LABEL[input.abuse]}, for example:\n${subjects}\n\nIf you didn't send these, one of your API keys has probably leaked, often from a hacked website. Delete that key in useSend, create a new one, and check the site that used it.\n\nReply to this email and we'll turn sending back on once it's sorted. While sending is paused, new emails fail instead of going out.\n\nuseSend`, + text: `Hi ${input.teamName} team,\n\nWe paused sending on your useSend account because emails sent from it look like ${ABUSE_LABEL[input.abuse]}, which our terms don't allow, for example:\n${subjects}\n\n${ + LIKELY_LEAKED.has(input.abuse) + ? "If you didn't send these, one of your API keys has probably leaked, often from a hacked website. Delete that key in useSend, create a new one, and check the site that used it.\n\nReply to this email and we'll turn sending back on once it's sorted." + : "If we got this wrong, reply to this email and tell us who these emails go to and how they signed up; we'll take another look." + } While sending is paused, new emails fail instead of going out.\n\nuseSend`, }; } @@ -573,7 +597,7 @@ export function guardPauseNotice( ? "new team" : `customer since ${team.createdAt.toISOString().slice(0, 10)}`; const why = body.abuse - ? `${body.abuse} (${evidenceCount} email${evidenceCount === 1 ? "" : "s"} as evidence). The team has been emailed.` + ? `${body.abuse.replace("_", " ")} (${evidenceCount} email${evidenceCount === 1 ? "" : "s"} as evidence). The team has been emailed.` : "clear abuse."; return `🛑 **Guard paused ${team.name}** (#${team.id}, ${age}) for ${why}\n${body.reason.slice(0, 600)}\nResume on the admin teams page if it's wrong: ${env.NEXTAUTH_URL}/admin/teams`; } diff --git a/apps/web/src/server/service/guard-service.unit.test.ts b/apps/web/src/server/service/guard-service.unit.test.ts index 6468032c2..6c4143ebf 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -51,6 +51,7 @@ import { listNewEmails, newEmailsQuery, abusePauseEmail, + teamActionBody, recordTeamAction, reviewHoldFor, sampleTeamEmails, @@ -489,6 +490,47 @@ describe("listNewEmails", () => { }); }); +describe("abusePauseEmail for other terms", () => { + it("names the rule, and asks how people signed up instead of blaming a leak", () => { + const { text } = abusePauseEmail({ + teamName: "Acme", + abuse: "cold_outreach", + subjects: ["Quick question about your business"], + }); + expect(text).toContain("cold outreach"); + expect(text).toContain("which our terms don't allow"); + expect(text).toContain("how they signed up"); + expect(text).not.toContain("leaked"); + }); + + it("accepts every banned kind in a pause request", () => { + for (const abuse of [ + "cold_outreach", + "gambling", + "adult", + "money_scheme", + "pharma", + ]) { + expect( + teamActionBody.parse({ + action: "PAUSE", + reason: "x", + abuse, + emailIds: ["e1"], + }).abuse, + ).toBe(abuse); + } + expect(() => + teamActionBody.parse({ + action: "PAUSE", + reason: "x", + abuse: "spam", + emailIds: ["e1"], + }), + ).toThrow(); + }); +}); + describe("abusePauseEmail", () => { it("quotes subjects on one line, without links", () => { const { text } = abusePauseEmail({ From af264b54b923d53c7a43cf8e303ca878445914a2 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Mon, 23 Nov 2026 16:46:08 +1100 Subject: [PATCH 6/6] fix(guard): emailTeam never throws; reject impossible cursor dates; feed skips rows that could still commit behind it; count repeated suppression-list bounces once --- apps/web/src/server/service/guard-service.ts | 9 ++++- .../server/service/guard-service.unit.test.ts | 16 ++++++++- .../web/src/server/service/ses-hook-parser.ts | 10 +++--- .../service/ses-hook-parser.unit.test.ts | 13 ++++++- .../src/server/service/ses-outcome-claims.ts | 6 +++- apps/web/src/server/service/team-email.ts | 16 +++++++-- .../server/service/team-email.unit.test.ts | 36 +++++++++++++++++++ 7 files changed, 96 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/server/service/team-email.unit.test.ts diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 421d40e22..e4faf6057 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -604,11 +604,16 @@ export function guardPauseNotice( // --- New emails (API and SMTP, not campaigns) --- +const COMMIT_SETTLE_MS = 30_000; + export const newEmailsQuery = z.object({ /** From `nextCursor`; without it, starts from the last 10 minutes. */ cursor: z .string() .regex(/^\d{4}-\d\d-\d\dT[\d:.]+Z\|[\w-]*$/) + .refine((cursor) => !Number.isNaN(Date.parse(cursor.split("|")[0]!)), { + message: "Invalid cursor timestamp", + }) .optional(), limit: z.coerce.number().int().min(1).max(200).default(100), }); @@ -628,7 +633,9 @@ export async function listNewEmails(query: z.infer) { campaignId: null, // A date range first, so the createdAt index does the work; then skip // what the last page already returned at that same instant. - createdAt: { gte: after }, + // Only rows at least 30s old: an insert can get its timestamp before + // it commits, so newer rows could still appear behind the cursor. + createdAt: { gte: after, lt: new Date(Date.now() - COMMIT_SETTLE_MS) }, ...(afterId ? { NOT: { createdAt: after, id: { lte: afterId } } } : {}), }, orderBy: [{ createdAt: "asc" }, { id: "asc" }], diff --git a/apps/web/src/server/service/guard-service.unit.test.ts b/apps/web/src/server/service/guard-service.unit.test.ts index 6c4143ebf..d5f2e4788 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -459,7 +459,7 @@ describe("listNewEmails", () => { const at = new Date("2026-11-23T09:59:59.000Z"); expect(query.where).toEqual({ campaignId: null, - createdAt: { gte: at }, + createdAt: { gte: at, lt: expect.any(Date) }, NOT: { createdAt: at, id: { lte: "e0" } }, }); expect(page.nextCursor).toBe("2026-11-23T10:00:01.000Z|e2"); @@ -480,6 +480,20 @@ describe("listNewEmails", () => { expect(query.where).not.toHaveProperty("NOT"); }); + it("only reads rows old enough that nothing can still commit behind them", async () => { + mockDb.email.findMany.mockResolvedValue([]); + const before = Date.now(); + await listNewEmails({ limit: 100 }); + const { lt } = mockDb.email.findMany.mock.calls[0]![0].where.createdAt; + expect(before - lt.getTime()).toBeGreaterThanOrEqual(29_000); + }); + + it("rejects an impossible cursor date", () => { + expect(() => + newEmailsQuery.parse({ cursor: "2026-99-99T99:99:99Z|e9" }), + ).toThrow(); + }); + it("keeps the cursor when nothing is new", async () => { mockDb.email.findMany.mockResolvedValue([]); const page = await listNewEmails({ diff --git a/apps/web/src/server/service/ses-hook-parser.ts b/apps/web/src/server/service/ses-hook-parser.ts index 290a4bfeb..35cffcde0 100644 --- a/apps/web/src/server/service/ses-hook-parser.ts +++ b/apps/web/src/server/service/ses-hook-parser.ts @@ -219,9 +219,11 @@ export async function parseSesHook(data: SesEvent) { // each only once per email: the sending rules and dashboards rely on it. const outcome = countsAsHardBounce ? ("hardBounced" as const) - : mailStatus === EmailStatus.COMPLAINED - ? ("complained" as const) - : null; + : isHardBounced + ? ("suppressedBounce" as const) + : mailStatus === EmailStatus.COMPLAINED + ? ("complained" as const) + : null; const claim = outcome ? await claimOutcome(email.id, outcome) : null; // "unavailable" (Redis failed) still updates the dashboards, as before; // only a confirmed duplicate is skipped. @@ -342,7 +344,7 @@ export async function parseSesHook(data: SesEvent) { // Check the sending rules once per new hard bounce or complaint, after the // counters above include it. A repeat of the same event doesn't re-run them. - if (outcome && claim === "claimed") { + if (outcome && outcome !== "suppressedBounce" && claim === "claimed") { try { await checkSendingHealth({ teamId: email.teamId, diff --git a/apps/web/src/server/service/ses-hook-parser.unit.test.ts b/apps/web/src/server/service/ses-hook-parser.unit.test.ts index de865b1cc..a8237cef5 100644 --- a/apps/web/src/server/service/ses-hook-parser.unit.test.ts +++ b/apps/web/src/server/service/ses-hook-parser.unit.test.ts @@ -274,7 +274,7 @@ describe("parseSesHook sending rules", () => { bounceEvent("Amazon SES did not send", "OnAccountSuppressionList"), ); - expect(mockClaimOutcome).not.toHaveBeenCalled(); + expect(mockClaimOutcome).toHaveBeenCalledWith(email.id, "suppressedBounce"); expect(mockCheckSendingHealth).not.toHaveBeenCalled(); const usage = mockDb.dailyEmailUsage.upsert.mock.calls[0]?.[0]; expect(usage.create.hardBounced).toBe(0); @@ -283,6 +283,17 @@ describe("parseSesHook sending rules", () => { expect(usage.update.bounced).toEqual({ increment: 1 }); }); + it("counts a repeated suppression-list bounce only once", async () => { + mockClaimOutcome.mockResolvedValue("duplicate"); + + await parseSesHook( + bounceEvent("Amazon SES did not send", "OnAccountSuppressionList"), + ); + + expect(mockDb.dailyEmailUsage.upsert).not.toHaveBeenCalled(); + expect(mockCheckSendingHealth).not.toHaveBeenCalled(); + }); + it("counts a repeated hard bounce only once", async () => { mockClaimOutcome.mockResolvedValue("duplicate"); diff --git a/apps/web/src/server/service/ses-outcome-claims.ts b/apps/web/src/server/service/ses-outcome-claims.ts index ace8fbe12..12950082b 100644 --- a/apps/web/src/server/service/ses-outcome-claims.ts +++ b/apps/web/src/server/service/ses-outcome-claims.ts @@ -7,7 +7,11 @@ import { getRedis, redisKey } from "~/server/redis"; const OUTCOME_CLAIM_SECONDS = 14 * 24 * 60 * 60; -export type Outcome = "hardBounced" | "complained"; +/** + * "suppressedBounce" is a bounce to an address on our SES suppression list: + * claimed so a repeat isn't counted twice, but it isn't a hard bounce. + */ +export type Outcome = "hardBounced" | "complained" | "suppressedBounce"; export type OutcomeClaim = "claimed" | "duplicate" | "unavailable"; diff --git a/apps/web/src/server/service/team-email.ts b/apps/web/src/server/service/team-email.ts index 6e871df54..788eb34de 100644 --- a/apps/web/src/server/service/team-email.ts +++ b/apps/web/src/server/service/team-email.ts @@ -8,7 +8,16 @@ import { TeamService } from "~/server/service/team-service"; * hey@usesend.com. Failures are logged, never thrown. */ export async function emailTeam(teamId: number, subject: string, text: string) { - const teamUsers = await TeamService.getTeamUsers(teamId); + let teamUsers: Awaited>; + try { + teamUsers = await TeamService.getTeamUsers(teamId); + } catch (error) { + logger.error( + { err: error, teamId }, + "[TeamEmail]: Couldn't find the team's members", + ); + return; + } const recipients = teamUsers .map((teamUser) => teamUser.user?.email) .filter((email): email is string => Boolean(email)); @@ -20,7 +29,10 @@ export async function emailTeam(teamId: number, subject: string, text: string) { ); results.forEach((result) => { if (result.status === "rejected") { - logger.error({ err: result.reason, teamId }, "[TeamEmail]: Team email failed"); + logger.error( + { err: result.reason, teamId }, + "[TeamEmail]: Team email failed", + ); } }); } diff --git a/apps/web/src/server/service/team-email.unit.test.ts b/apps/web/src/server/service/team-email.unit.test.ts new file mode 100644 index 000000000..cf28b973e --- /dev/null +++ b/apps/web/src/server/service/team-email.unit.test.ts @@ -0,0 +1,36 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { mockGetTeamUsers, mockSendMail, mockLogger } = vi.hoisted(() => ({ + mockGetTeamUsers: vi.fn(), + mockSendMail: vi.fn(), + mockLogger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); + +vi.mock("~/server/logger/log", () => ({ logger: mockLogger })); +vi.mock("~/server/mailer", () => ({ sendMail: mockSendMail })); +vi.mock("~/server/service/team-service", () => ({ + TeamService: { getTeamUsers: mockGetTeamUsers }, +})); + +import { emailTeam } from "~/server/service/team-email"; + +beforeEach(() => vi.clearAllMocks()); + +describe("emailTeam", () => { + it("emails every member", async () => { + mockGetTeamUsers.mockResolvedValue([ + { user: { email: "a@acme.com" } }, + { user: { email: "b@acme.com" } }, + { user: null }, + ]); + await emailTeam(7, "Subject", "Body"); + expect(mockSendMail).toHaveBeenCalledTimes(2); + }); + + it("never throws, even if the members can't be read", async () => { + mockGetTeamUsers.mockRejectedValue(new Error("db down")); + await expect(emailTeam(7, "Subject", "Body")).resolves.toBeUndefined(); + expect(mockSendMail).not.toHaveBeenCalled(); + expect(mockLogger.error).toHaveBeenCalled(); + }); +});