From da6903b2c3f498ad1fe511f35c347d1f9d6e9f68 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Tue, 24 Nov 2026 10:37:40 +1100 Subject: [PATCH 1/3] feat(guard): give the Guard each new team's application volume/list source and last-day recipient count --- apps/web/src/server/service/guard-service.ts | 32 +++++++++- .../server/service/guard-service.unit.test.ts | 62 ++++++++++++++++++- 2 files changed, 92 insertions(+), 2 deletions(-) diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 3c7d8601..6b127831 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -375,7 +375,12 @@ export async function listWatchedTeams(query: z.infer) { select: { email: true, waitlistApplication: { - select: { website: true, description: true }, + select: { + website: true, + description: true, + emailVolume: true, + listSource: true, + }, }, }, }, @@ -404,6 +409,23 @@ export async function listWatchedTeams(query: z.infer) { }); const usageByTeam = new Map(usage.map((row) => [row.teamId, row._sum])); + // API email in the last day, and to how many different people: one message + // blasted to thousands of strangers only shows up as a pattern. Counts + // only; no addresses leave the database. + const lastDayRows = await db.$queryRaw< + Array<{ teamId: number; emails: number; recipients: number }> + >` + SELECT e."teamId" AS "teamId", + COUNT(DISTINCT e.id)::int AS emails, + COUNT(DISTINCT lower(r.address))::int AS recipients + FROM "Email" e + CROSS JOIN LATERAL unnest(e."to") AS r(address) + WHERE e."teamId" = ANY(${page.map((team) => team.id)}) + AND e."createdAt" > ${new Date(Date.now() - DAY_MS)} + AND e."campaignId" IS NULL + GROUP BY e."teamId"`; + const lastDayByTeam = new Map(lastDayRows.map((row) => [row.teamId, row])); + return { items: page.map(({ teamUsers, ...team }) => { const sums = usageByTeam.get(team.id); @@ -414,7 +436,15 @@ export async function listWatchedTeams(query: z.infer) { email: user.email, website: user.waitlistApplication?.website ?? null, description: user.waitlistApplication?.description ?? null, + // What they said they'd send, so the Guard can compare it with + // what they actually send. + emailVolume: user.waitlistApplication?.emailVolume ?? null, + listSource: user.waitlistApplication?.listSource ?? null, })), + lastDay: { + emails: lastDayByTeam.get(team.id)?.emails ?? 0, + recipients: lastDayByTeam.get(team.id)?.recipients ?? 0, + }, usage: { sent: sums?.sent ?? 0, delivered: sums?.delivered ?? 0, 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 cea26cf2..d95dec69 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -6,7 +6,8 @@ const { mockEnv, mockDb, mockRefreshTeamCache, mockRedis } = vi.hoisted(() => ({ mockDb: { $transaction: vi.fn(), $queryRaw: vi.fn(), - team: { findUnique: vi.fn(), updateMany: vi.fn() }, + team: { findUnique: vi.fn(), updateMany: vi.fn(), findMany: vi.fn() }, + dailyEmailUsage: { groupBy: vi.fn() }, campaign: { findMany: vi.fn(), updateMany: vi.fn() }, teamAction: { create: vi.fn() }, email: { findMany: vi.fn() }, @@ -52,6 +53,7 @@ import { isReviewHeld, listActiveCampaigns, listNewEmails, + listWatchedTeams, newEmailsQuery, abusePauseEmail, teamActionBody, @@ -428,6 +430,64 @@ describe("recordTeamAction", () => { }); }); +describe("listWatchedTeams", () => { + it("includes what each member applied with, to compare with their sending", async () => { + mockDb.team.findMany.mockResolvedValue([ + { + id: 453, + name: "New team", + createdAt: new Date(), + domains: [], + teamUsers: [ + { + role: "ADMIN", + user: { + email: "owner@example.com", + waitlistApplication: { + website: "https://example.com", + description: "A weekly digest", + emailVolume: "Close to zero for now", + listSource: "Signup form with double opt-in", + }, + }, + }, + ], + }, + ]); + mockDb.dailyEmailUsage.groupBy.mockResolvedValue([ + { + teamId: 453, + _sum: { + sent: 2952, + delivered: 2933, + bounced: 17, + hardBounced: 17, + complained: 2, + }, + }, + ]); + + mockDb.$queryRaw.mockResolvedValueOnce([ + { teamId: 453, emails: 2952, recipients: 2946 }, + ]); + + const { items } = await listWatchedTeams({ days: 14, limit: 100 }); + + expect(items[0]!.members).toEqual([ + { + role: "ADMIN", + email: "owner@example.com", + website: "https://example.com", + description: "A weekly digest", + emailVolume: "Close to zero for now", + listSource: "Signup form with double opt-in", + }, + ]); + expect(items[0]!.usage.sent).toBe(2952); + expect(items[0]!.lastDay).toEqual({ emails: 2952, recipients: 2946 }); + }); +}); + describe("sampleTeamEmails", () => { it("returns content but only the recipients' domains", async () => { mockDb.email.findMany.mockResolvedValue([ From 715f1233f391d6834ae1cee808db9f92d222c5c6 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Tue, 24 Nov 2026 10:40:02 +1100 Subject: [PATCH 2/3] feat(guard): per-message recipient counts for the last 2 hours instead of a team-wide day --- apps/web/src/server/service/guard-service.ts | 43 +++++++++++++------ .../server/service/guard-service.unit.test.ts | 17 +++++++- 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 6b127831..142855aa 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -352,6 +352,10 @@ export const watchQuery = z.object({ }); /** Teams created in the last `days`, with their sending numbers, paged. */ +/** The window and size of each team's `recentMessages`. */ +const RECENT_MESSAGES_MS = 2 * 60 * 60 * 1000; +const RECENT_MESSAGES_MAX = 5; + export async function listWatchedTeams(query: z.infer) { const since = new Date(Date.now() - query.days * DAY_MS); const teams = await db.team.findMany({ @@ -409,22 +413,36 @@ export async function listWatchedTeams(query: z.infer) { }); const usageByTeam = new Map(usage.map((row) => [row.teamId, row._sum])); - // API email in the last day, and to how many different people: one message - // blasted to thousands of strangers only shows up as a pattern. Counts - // only; no addresses leave the database. - const lastDayRows = await db.$queryRaw< - Array<{ teamId: number; emails: number; recipients: number }> + // Each recent API message (sender + subject pattern) and how many different + // people it went to: one message blasted to thousands of strangers only + // shows up as a pattern. Scoped to the last 2 hours so it describes a + // burst, not the whole day. Counts only; no addresses leave the database. + const recentRows = await db.$queryRaw< + Array<{ + teamId: number; + from: string; + subject: string; + emails: number; + recipients: number; + }> >` - SELECT e."teamId" AS "teamId", + SELECT e."teamId" AS "teamId", e."from" AS "from", + regexp_replace(e.subject, '[0-9]+', '#', 'g') AS subject, COUNT(DISTINCT e.id)::int AS emails, COUNT(DISTINCT lower(r.address))::int AS recipients FROM "Email" e CROSS JOIN LATERAL unnest(e."to") AS r(address) WHERE e."teamId" = ANY(${page.map((team) => team.id)}) - AND e."createdAt" > ${new Date(Date.now() - DAY_MS)} + AND e."createdAt" > ${new Date(Date.now() - RECENT_MESSAGES_MS)} AND e."campaignId" IS NULL - GROUP BY e."teamId"`; - const lastDayByTeam = new Map(lastDayRows.map((row) => [row.teamId, row])); + GROUP BY 1, 2, 3 + ORDER BY emails DESC`; + const recentByTeam = new Map(); + for (const row of recentRows) { + const rows = recentByTeam.get(row.teamId) ?? []; + if (rows.length < RECENT_MESSAGES_MAX) rows.push(row); + recentByTeam.set(row.teamId, rows); + } return { items: page.map(({ teamUsers, ...team }) => { @@ -441,10 +459,9 @@ export async function listWatchedTeams(query: z.infer) { emailVolume: user.waitlistApplication?.emailVolume ?? null, listSource: user.waitlistApplication?.listSource ?? null, })), - lastDay: { - emails: lastDayByTeam.get(team.id)?.emails ?? 0, - recipients: lastDayByTeam.get(team.id)?.recipients ?? 0, - }, + recentMessages: (recentByTeam.get(team.id) ?? []).map( + ({ teamId: _teamId, ...message }) => message, + ), usage: { sent: sums?.sent ?? 0, delivered: sums?.delivered ?? 0, 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 d95dec69..adea88ae 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -468,7 +468,13 @@ describe("listWatchedTeams", () => { ]); mockDb.$queryRaw.mockResolvedValueOnce([ - { teamId: 453, emails: 2952, recipients: 2946 }, + { + teamId: 453, + from: "info@example.com", + subject: "Successful registration", + emails: 1932, + recipients: 1930, + }, ]); const { items } = await listWatchedTeams({ days: 14, limit: 100 }); @@ -484,7 +490,14 @@ describe("listWatchedTeams", () => { }, ]); expect(items[0]!.usage.sent).toBe(2952); - expect(items[0]!.lastDay).toEqual({ emails: 2952, recipients: 2946 }); + expect(items[0]!.recentMessages).toEqual([ + { + from: "info@example.com", + subject: "Successful registration", + emails: 1932, + recipients: 1930, + }, + ]); }); }); From d0dfd37371057fc55972f00f9acd765c1e4621de Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Tue, 24 Nov 2026 10:54:21 +1100 Subject: [PATCH 3/3] fix(guard): count cc and bcc recipients in recentMessages --- apps/web/src/server/service/guard-service.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 142855aa..0e5e8184 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -416,7 +416,9 @@ export async function listWatchedTeams(query: z.infer) { // Each recent API message (sender + subject pattern) and how many different // people it went to: one message blasted to thousands of strangers only // shows up as a pattern. Scoped to the last 2 hours so it describes a - // burst, not the whole day. Counts only; no addresses leave the database. + // burst, not the whole day. Recipients include cc and bcc. Every attempt + // counts (even suppressed or failed): trying to blast a list is the signal. + // Counts only; no addresses leave the database. const recentRows = await db.$queryRaw< Array<{ teamId: number; @@ -431,7 +433,9 @@ export async function listWatchedTeams(query: z.infer) { COUNT(DISTINCT e.id)::int AS emails, COUNT(DISTINCT lower(r.address))::int AS recipients FROM "Email" e - CROSS JOIN LATERAL unnest(e."to") AS r(address) + CROSS JOIN LATERAL unnest( + e."to" || coalesce(e.cc, '{}') || coalesce(e.bcc, '{}') + ) AS r(address) WHERE e."teamId" = ANY(${page.map((team) => team.id)}) AND e."createdAt" > ${new Date(Date.now() - RECENT_MESSAGES_MS)} AND e."campaignId" IS NULL