@hogsend/engine 0.63.0 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/package.json +13 -12
  2. package/src/account-links/__fixtures__/fake-fetch.test.ts +57 -0
  3. package/src/account-links/__fixtures__/fake-fetch.ts +114 -0
  4. package/src/account-links/__fixtures__/steam.json +21 -0
  5. package/src/account-links/__fixtures__/twitch.json +22 -0
  6. package/src/account-links/index.ts +8 -0
  7. package/src/account-links/steam.test.ts +243 -0
  8. package/src/account-links/steam.ts +48 -0
  9. package/src/account-links/twitch.test.ts +157 -0
  10. package/src/account-links/twitch.ts +99 -0
  11. package/src/container.account-links.env.test.ts +65 -0
  12. package/src/container.account-links.halfenv.test.ts +48 -0
  13. package/src/container.account-links.test.ts +185 -0
  14. package/src/container.ts +120 -0
  15. package/src/env.ts +60 -0
  16. package/src/index.ts +104 -1
  17. package/src/journeys/journey-boundary.ts +8 -0
  18. package/src/lib/account-link-emit.ts +126 -0
  19. package/src/lib/account-link-events.ts +180 -0
  20. package/src/lib/account-link-hooks.test.ts +158 -0
  21. package/src/lib/account-link-hooks.ts +73 -0
  22. package/src/lib/account-link-ingest.ts +364 -0
  23. package/src/lib/account-link-nonce.test.ts +52 -0
  24. package/src/lib/account-link-nonce.ts +57 -0
  25. package/src/lib/account-link-origins.test.ts +72 -0
  26. package/src/lib/account-link-origins.ts +87 -0
  27. package/src/lib/account-link-pkce.test.ts +91 -0
  28. package/src/lib/account-link-pkce.ts +106 -0
  29. package/src/lib/account-link-provider-registry.test.ts +52 -0
  30. package/src/lib/account-link-provider-registry.ts +61 -0
  31. package/src/lib/account-link-throttle.test.ts +178 -0
  32. package/src/lib/account-link-throttle.ts +130 -0
  33. package/src/lib/account-link-url.ts +85 -0
  34. package/src/lib/account-links-emit.test.ts +525 -0
  35. package/src/lib/account-links-env.test.ts +40 -0
  36. package/src/lib/account-links-from-env.test.ts +187 -0
  37. package/src/lib/account-links-from-env.ts +126 -0
  38. package/src/lib/account-links.ts +1300 -0
  39. package/src/lib/app-secret.ts +34 -0
  40. package/src/lib/attachments.ts +81 -0
  41. package/src/lib/connector-actions.test.ts +13 -4
  42. package/src/lib/connector-state.account-link.test.ts +114 -0
  43. package/src/lib/connector-state.ts +48 -3
  44. package/src/lib/contacts.ts +320 -6
  45. package/src/lib/domain-status.return-path.test.ts +68 -0
  46. package/src/lib/domain-status.ts +19 -0
  47. package/src/lib/email-provider-boot.hogsend.test.ts +48 -0
  48. package/src/lib/email-provider-boot.test.ts +33 -0
  49. package/src/lib/email-providers-from-env.hogsend.test.ts +110 -0
  50. package/src/lib/email-providers-from-env.test.ts +52 -0
  51. package/src/lib/email-providers-from-env.ts +67 -0
  52. package/src/lib/email-service-types.ts +11 -0
  53. package/src/lib/email.ts +17 -0
  54. package/src/lib/mailer-bounce-idempotency.test.ts +469 -0
  55. package/src/lib/mailer-rejected.test.ts +229 -0
  56. package/src/lib/mailer-replied.test.ts +379 -0
  57. package/src/lib/mailer.ts +359 -24
  58. package/src/lib/outbound-account-payloads.test.ts +137 -0
  59. package/src/lib/outbound.ts +126 -0
  60. package/src/lib/provider-credentials.ts +19 -5
  61. package/src/lib/sending-domain-guidance.test.ts +99 -0
  62. package/src/lib/sending-domain-guidance.ts +84 -0
  63. package/src/lib/tracked-attachments.test.ts +376 -0
  64. package/src/lib/tracked-idempotency-header.test.ts +437 -0
  65. package/src/lib/tracked.ts +116 -4
  66. package/src/lib/tracking-event-names.ts +9 -0
  67. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  68. package/src/lib/webhook-signing.ts +25 -1
  69. package/src/routes/accounts/callback.ts +597 -0
  70. package/src/routes/accounts/emit.ts +231 -0
  71. package/src/routes/accounts/import-links.ts +210 -0
  72. package/src/routes/accounts/index.ts +75 -0
  73. package/src/routes/accounts/lookup.ts +177 -0
  74. package/src/routes/accounts/me.ts +215 -0
  75. package/src/routes/accounts/mint.ts +279 -0
  76. package/src/routes/accounts/pages.ts +62 -0
  77. package/src/routes/accounts/resolve.ts +61 -0
  78. package/src/routes/accounts/serialize.ts +96 -0
  79. package/src/routes/accounts/shared.ts +107 -0
  80. package/src/routes/accounts/start.ts +229 -0
  81. package/src/routes/accounts/unlink.ts +98 -0
  82. package/src/routes/admin/agent.ts +2 -0
  83. package/src/routes/admin/api-keys.ts +7 -0
  84. package/src/routes/admin/contacts.ts +38 -2
  85. package/src/routes/admin/domain-conflict.test.ts +188 -0
  86. package/src/routes/admin/domain-return-path.test.ts +274 -0
  87. package/src/routes/admin/domain.ts +214 -1
  88. package/src/routes/connectors/index.ts +17 -0
  89. package/src/routes/contacts/index.ts +8 -0
  90. package/src/routes/index.ts +75 -0
  91. package/src/testing-barrel.test.ts +74 -0
  92. package/src/testing.ts +17 -0
@@ -0,0 +1,469 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import type { EmailEvent, EmailProvider } from "@hogsend/core";
4
+ import type { Database } from "@hogsend/db";
5
+ import { emailPreferences, emailSends, webhookDeliveries } from "@hogsend/db";
6
+ import type { TemplateRegistry } from "@hogsend/email";
7
+ import type { SQL } from "drizzle-orm";
8
+ import { PgDialect } from "drizzle-orm/pg-core";
9
+
10
+ // mailer's import chain reaches env.ts (validates required env vars at import
11
+ // time) and lib/hatchet.ts (parses HATCHET_CLIENT_TOKEN as a JWT at import
12
+ // time) — stub both BEFORE the dynamic import. Nothing is ever contacted: the
13
+ // db is a fake and the provider is never called on this path.
14
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
15
+ process.env.BETTER_AUTH_SECRET ??= "test-secret";
16
+ process.env.HATCHET_CLIENT_TOKEN ??=
17
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
18
+ const { createTrackedMailer } = await import("./mailer.js");
19
+
20
+ /**
21
+ * BOUNCE IDEMPOTENCY.
22
+ *
23
+ * SNS is at-least-once, and the control plane deliberately re-drives a
24
+ * `pending` event row after 60s so a bounce is never LOST — which means the
25
+ * SAME bounce can reach this instance more than once. Two things must survive
26
+ * that, and neither is cosmetic:
27
+ *
28
+ * 1. **the suppression counter.** `bounceThreshold` defaults to 3, so THREE
29
+ * redeliveries of ONE bounce would permanently suppress a perfectly
30
+ * deliverable address — silently, with nothing the customer can undo;
31
+ * 2. **the outbound `email.bounced` emit.** A redelivery double-fires the
32
+ * customer's webhook destination and fires a journey waiting on
33
+ * `email.bounced` twice.
34
+ *
35
+ * Asserted against a db fake that EVALUATES the statement's WHERE clause
36
+ * against modelled row state (rendered through drizzle's own pg dialect)
37
+ * rather than assuming a guard exists. That is the point: a fake that simply
38
+ * refused the second write would pass whether or not the engine actually
39
+ * guards, which is the vacuous-green trap this repo has been bitten by. Delete
40
+ * the guard and these tests go red.
41
+ */
42
+
43
+ const dialect = new PgDialect();
44
+
45
+ /** `bounced_at` → `bouncedAt`. */
46
+ function camel(column: string): string {
47
+ return column.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
48
+ }
49
+
50
+ /**
51
+ * Evaluate a rendered WHERE against a modelled row. Supports EXACTLY the three
52
+ * predicate shapes this path emits and THROWS on anything else — an unknown
53
+ * shape must fail loudly rather than silently evaluate to "matched".
54
+ */
55
+ function matches(row: Record<string, unknown>, condition: unknown): boolean {
56
+ const { sql: text, params } = dialect.sqlToQuery(condition as SQL);
57
+ const terms = text.replace(/^\(/, "").replace(/\)$/, "").split(" and ");
58
+ return terms.every((raw) => {
59
+ const term = raw.trim();
60
+ let m = /^"[a-z_]+"\."([a-z_]+)" = \$(\d+)$/.exec(term);
61
+ if (m) return row[camel(m[1] as string)] === params[Number(m[2]) - 1];
62
+ m = /^"[a-z_]+"\."([a-z_]+)" is null$/.exec(term);
63
+ if (m) return row[camel(m[1] as string)] == null;
64
+ m = /^"[a-z_]+"\."([a-z_]+)" is distinct from \$(\d+)$/.exec(term);
65
+ if (m) return row[camel(m[1] as string)] !== params[Number(m[2]) - 1];
66
+ throw new Error(`fake db: unsupported predicate \`${term}\``);
67
+ });
68
+ }
69
+
70
+ interface FakeSend {
71
+ id: string;
72
+ messageId: string;
73
+ toEmail: string;
74
+ status: string;
75
+ sentAt: Date | null;
76
+ deliveredAt: Date | null;
77
+ openedAt: Date | null;
78
+ clickedAt: Date | null;
79
+ bouncedAt: Date | null;
80
+ bounceType: string | null;
81
+ bounceReason: string | null;
82
+ }
83
+
84
+ function send(messageId: string, overrides: Partial<FakeSend> = {}): FakeSend {
85
+ return {
86
+ id: `send-${messageId}`,
87
+ messageId,
88
+ toEmail: "recipient@example.com",
89
+ status: "sent",
90
+ sentAt: new Date(),
91
+ deliveredAt: null,
92
+ openedAt: null,
93
+ clickedAt: null,
94
+ bouncedAt: null,
95
+ bounceType: null,
96
+ bounceReason: null,
97
+ ...overrides,
98
+ };
99
+ }
100
+
101
+ interface RecordedUpdate {
102
+ values: Record<string, unknown>;
103
+ /** How many modelled rows the statement's WHERE actually matched. */
104
+ matched: number;
105
+ }
106
+
107
+ interface FakeDb {
108
+ db: Database;
109
+ sends: FakeSend[];
110
+ sendUpdates: RecordedUpdate[];
111
+ preferenceUpdates: RecordedUpdate[];
112
+ /** Advanced by 1 per issued `bounce_count + 1` statement. */
113
+ bounceCount: () => number;
114
+ outbound: () => { eventType: string }[];
115
+ warnings: { message: string; meta?: unknown }[];
116
+ }
117
+
118
+ /** A resolved promise that also answers `.returning()`, like drizzle's builder. */
119
+ function settled<T>(
120
+ rows: T[],
121
+ ): Promise<T[]> & { returning: () => Promise<T[]> } {
122
+ const promise = Promise.resolve(rows) as Promise<T[]> & {
123
+ returning: () => Promise<T[]>;
124
+ };
125
+ promise.returning = () => Promise.resolve(rows);
126
+ return promise;
127
+ }
128
+
129
+ function fakeDb(rows: FakeSend[]): FakeDb {
130
+ const sendUpdates: RecordedUpdate[] = [];
131
+ const preferenceUpdates: RecordedUpdate[] = [];
132
+ const deliveries: { eventType: string }[] = [];
133
+ const warnings: { message: string; meta?: unknown }[] = [];
134
+ let bounceCount = 0;
135
+
136
+ const db = {
137
+ update(table: unknown) {
138
+ return {
139
+ set(values: Record<string, unknown>) {
140
+ return {
141
+ where(condition: unknown) {
142
+ if (table === emailSends) {
143
+ const hit = rows.filter((row) =>
144
+ matches(row as unknown as Record<string, unknown>, condition),
145
+ );
146
+ for (const row of hit) {
147
+ for (const [key, value] of Object.entries(values)) {
148
+ // Drizzle `sql` expressions (the counter increments) are
149
+ // modelled separately; plain values write through.
150
+ if (
151
+ value &&
152
+ typeof value === "object" &&
153
+ "queryChunks" in value
154
+ ) {
155
+ continue;
156
+ }
157
+ (row as unknown as Record<string, unknown>)[key] = value;
158
+ }
159
+ }
160
+ sendUpdates.push({ values, matched: hit.length });
161
+ return settled(hit.map((row) => ({ id: row.id })));
162
+ }
163
+ if (table === emailPreferences) {
164
+ preferenceUpdates.push({ values, matched: 1 });
165
+ if ("bounceCount" in values) bounceCount += 1;
166
+ return settled([{ id: "pref-1" }]);
167
+ }
168
+ return settled<{ id: string }>([]);
169
+ },
170
+ };
171
+ },
172
+ };
173
+ },
174
+ select() {
175
+ return {
176
+ from() {
177
+ return {
178
+ // `resolveEmailSendContextByMessageId` joins to `journey_states`;
179
+ // `emitOutbound`'s endpoint select does not. The join tells the two
180
+ // reads apart, so one fake serves both.
181
+ leftJoin: () => ({
182
+ where: (condition: unknown) => ({
183
+ limit: () =>
184
+ Promise.resolve(
185
+ rows
186
+ .filter((row) =>
187
+ matches(
188
+ row as unknown as Record<string, unknown>,
189
+ condition,
190
+ ),
191
+ )
192
+ .map((row) => ({
193
+ emailSendId: row.id,
194
+ toEmail: row.toEmail,
195
+ templateKey: "onboarding-day-1",
196
+ sendContactId: null,
197
+ userId: null,
198
+ userEmail: null,
199
+ enrollmentContactId: null,
200
+ sendUserId: null,
201
+ sendUserEmail: null,
202
+ })),
203
+ ),
204
+ }),
205
+ }),
206
+ // One subscribed endpoint, so the spine has somewhere to deliver.
207
+ where: () => Promise.resolve([{ id: "endpoint-1" }]),
208
+ };
209
+ },
210
+ };
211
+ },
212
+ insert(table: unknown) {
213
+ return {
214
+ values(values: unknown) {
215
+ if (table === webhookDeliveries) {
216
+ deliveries.push(...(values as { eventType: string }[]));
217
+ }
218
+ return {
219
+ onConflictDoNothing: () => ({
220
+ returning: () => Promise.resolve([]),
221
+ }),
222
+ returning: () => Promise.resolve([]),
223
+ };
224
+ },
225
+ };
226
+ },
227
+ };
228
+
229
+ return {
230
+ db: db as unknown as Database,
231
+ sends: rows,
232
+ sendUpdates,
233
+ preferenceUpdates,
234
+ bounceCount: () => bounceCount,
235
+ outbound: () => deliveries,
236
+ warnings,
237
+ };
238
+ }
239
+
240
+ /** Never called on the webhook path — present only to satisfy the contract. */
241
+ const provider = {
242
+ meta: { id: "test", name: "Test" },
243
+ capabilities: { nativeTracking: false },
244
+ send: async () => ({ id: "unused" }),
245
+ } as unknown as EmailProvider;
246
+
247
+ function mailer(fake: FakeDb) {
248
+ return createTrackedMailer(
249
+ {
250
+ defaultFrom: "test@example.com",
251
+ templates: {} as TemplateRegistry,
252
+ db: fake.db,
253
+ logger: {
254
+ debug: () => {},
255
+ info: () => {},
256
+ warn: (message: string, meta?: unknown) => {
257
+ fake.warnings.push({ message, meta });
258
+ },
259
+ error: () => {},
260
+ } as never,
261
+ },
262
+ { provider },
263
+ );
264
+ }
265
+
266
+ function bounced(
267
+ messageId: string,
268
+ bounce: { class?: string; reason?: string } = { class: "permanent" },
269
+ ): EmailEvent {
270
+ return {
271
+ type: "email.bounced",
272
+ messageId,
273
+ recipients: ["recipient@example.com"],
274
+ occurredAt: "2026-08-12T10:00:00.000Z",
275
+ bounce: bounce as EmailEvent["bounce"],
276
+ raw: {},
277
+ };
278
+ }
279
+
280
+ /** The outbound emit is fire-and-forget — let its continuation land. */
281
+ async function drain(): Promise<void> {
282
+ for (let i = 0; i < 20; i += 1) {
283
+ await new Promise((resolve) => setImmediate(resolve));
284
+ }
285
+ }
286
+
287
+ function bouncedEmits(fake: FakeDb): number {
288
+ return fake.outbound().filter((row) => row.eventType === "email.bounced")
289
+ .length;
290
+ }
291
+
292
+ test("THE test: the same bounce delivered three times counts ONCE", async () => {
293
+ // The headline claim. With `bounceThreshold` at 3, an ungated counter turns
294
+ // three redeliveries of ONE bounce into a permanent suppression of an address
295
+ // that never did anything wrong.
296
+ const fake = fakeDb([send("msg-1")]);
297
+ const service = mailer(fake);
298
+
299
+ await service.handleWebhook(bounced("msg-1"));
300
+ await drain();
301
+ assert.equal(fake.bounceCount(), 1, "the first delivery must count");
302
+ assert.equal(bouncedEmits(fake), 1, "the first delivery must emit");
303
+
304
+ await service.handleWebhook(bounced("msg-1"));
305
+ await drain();
306
+ assert.equal(fake.bounceCount(), 1, "a redelivery must NOT count again");
307
+ assert.equal(bouncedEmits(fake), 1, "a redelivery must NOT emit again");
308
+
309
+ await service.handleWebhook(bounced("msg-1"));
310
+ await drain();
311
+ assert.equal(fake.bounceCount(), 1, "still exactly one after a third");
312
+ assert.equal(bouncedEmits(fake), 1, "still exactly one emit after a third");
313
+
314
+ // Nothing was suppressed: one count is two short of the threshold.
315
+ assert.equal(fake.preferenceUpdates.length, 1);
316
+ });
317
+
318
+ test("the first delivery still records the bounce facts on the send", async () => {
319
+ // The guard must not cost the row its state. This is the control for the test
320
+ // above: if the claim wrote nothing at all, "counted once" would be vacuous.
321
+ const fake = fakeDb([send("msg-1")]);
322
+ await mailer(fake).handleWebhook(
323
+ bounced("msg-1", { class: "permanent", reason: "550 5.1.1 unknown" }),
324
+ );
325
+
326
+ const row = fake.sends[0] as FakeSend;
327
+ assert.equal(row.status, "bounced");
328
+ assert.ok(row.bouncedAt instanceof Date);
329
+ assert.equal(row.bounceType, "permanent");
330
+ assert.equal(row.bounceReason, "550 5.1.1 unknown");
331
+ });
332
+
333
+ test("a SECOND, DISTINCT bounce for the same address still counts", async () => {
334
+ // Do not over-dedupe. Two sends to the same address that both bounce are two
335
+ // bounces, and suppression exists precisely so the second one moves the
336
+ // counter. Dedupe is scoped to (send, bounce), never to the address.
337
+ const fake = fakeDb([send("msg-1"), send("msg-2")]);
338
+ const service = mailer(fake);
339
+
340
+ await service.handleWebhook(bounced("msg-1"));
341
+ await service.handleWebhook(bounced("msg-2"));
342
+ await drain();
343
+
344
+ assert.equal(fake.bounceCount(), 2);
345
+ assert.equal(bouncedEmits(fake), 2);
346
+ });
347
+
348
+ test("a permanent bounce AFTER a transient one on the same send counts", async () => {
349
+ // The escalation the guard deliberately admits. A soft bounce recorded first
350
+ // must not shield the hard bounce that follows it — that would silently
351
+ // disable suppression for exactly the addresses that need it.
352
+ const fake = fakeDb([send("msg-1")]);
353
+ const service = mailer(fake);
354
+
355
+ await service.handleWebhook(bounced("msg-1", { class: "transient" }));
356
+ await drain();
357
+ assert.equal(fake.bounceCount(), 0, "a transient bounce never counts");
358
+
359
+ await service.handleWebhook(bounced("msg-1", { class: "permanent" }));
360
+ await drain();
361
+ assert.equal(fake.bounceCount(), 1, "the permanent escalation DOES count");
362
+
363
+ // ...and the permanent one is itself idempotent from there on.
364
+ await service.handleWebhook(bounced("msg-1", { class: "permanent" }));
365
+ await drain();
366
+ assert.equal(fake.bounceCount(), 1);
367
+ });
368
+
369
+ test("a transient bounce still auto-suppresses NOTHING, however often it arrives", async () => {
370
+ const fake = fakeDb([send("msg-1")]);
371
+ const service = mailer(fake);
372
+
373
+ await service.handleWebhook(bounced("msg-1", { class: "transient" }));
374
+ await service.handleWebhook(bounced("msg-1", { class: "transient" }));
375
+ await drain();
376
+
377
+ assert.deepEqual(fake.preferenceUpdates, []);
378
+ assert.equal(fake.bounceCount(), 0);
379
+ // The redelivered transient does not re-emit either.
380
+ assert.equal(bouncedEmits(fake), 1);
381
+ assert.equal((fake.sends[0] as FakeSend).bounceType, "transient");
382
+ });
383
+
384
+ test("a bounce for a send we never recorded STILL counts", async () => {
385
+ // The deliberate edge (requirement 4). `sendRaw` writes no `email_sends` row
386
+ // at all, and a webhook can outrun the send row's commit — so "no matching
387
+ // row" is a REAL bounce we have no send-scoped state to dedupe against.
388
+ // Silently dropping it would disable suppression for those addresses
389
+ // entirely, which is the worse failure, so the count is preserved (today's
390
+ // behaviour) and the un-dedupable path is logged instead of hidden.
391
+ const fake = fakeDb([]);
392
+ const service = mailer(fake);
393
+
394
+ await service.handleWebhook(bounced("msg-unknown"));
395
+ await drain();
396
+
397
+ assert.equal(fake.bounceCount(), 1);
398
+ assert.ok(
399
+ fake.warnings.some((entry) => /unrecorded send/.test(entry.message)),
400
+ "the un-dedupable path must be logged, not silent",
401
+ );
402
+
403
+ // The residual, pinned deliberately rather than left to be discovered: with
404
+ // no send row there is nothing to claim, so a redelivery counts again. The
405
+ // emit does NOT double-fire — it resolves its context from the same missing
406
+ // row and no-ops.
407
+ await service.handleWebhook(bounced("msg-unknown"));
408
+ await drain();
409
+ assert.equal(fake.bounceCount(), 2);
410
+ assert.equal(bouncedEmits(fake), 0);
411
+ });
412
+
413
+ test("opened and clicked are NOT gated — every hit still writes", async () => {
414
+ // The per-hit behaviour of open/click is deliberate and documented in the
415
+ // dispatch branch. The bounce guard must not leak onto it.
416
+ const fake = fakeDb([send("msg-1")]);
417
+ const service = mailer(fake);
418
+
419
+ await service.handleWebhook({
420
+ type: "email.opened",
421
+ messageId: "msg-1",
422
+ recipients: ["recipient@example.com"],
423
+ occurredAt: "2026-08-12T10:00:00.000Z",
424
+ raw: {},
425
+ });
426
+ await service.handleWebhook({
427
+ type: "email.opened",
428
+ messageId: "msg-1",
429
+ recipients: ["recipient@example.com"],
430
+ occurredAt: "2026-08-12T10:00:01.000Z",
431
+ raw: {},
432
+ });
433
+ await service.handleWebhook({
434
+ type: "email.clicked",
435
+ messageId: "msg-1",
436
+ recipients: ["recipient@example.com"],
437
+ occurredAt: "2026-08-12T10:00:02.000Z",
438
+ raw: {},
439
+ });
440
+ await drain();
441
+
442
+ // Three statements, and every one of them MATCHED a row: an accidental
443
+ // `WHERE openedAt IS NULL` here would leave the second open matching nothing.
444
+ assert.equal(fake.sendUpdates.length, 3);
445
+ for (const update of fake.sendUpdates) {
446
+ assert.equal(update.matched, 1);
447
+ }
448
+ });
449
+
450
+ test("a delivered webhook is untouched by the bounce guard", async () => {
451
+ const fake = fakeDb([send("msg-1")]);
452
+ const service = mailer(fake);
453
+
454
+ await service.handleWebhook({
455
+ type: "email.delivered",
456
+ messageId: "msg-1",
457
+ recipients: ["recipient@example.com"],
458
+ occurredAt: "2026-08-12T10:00:00.000Z",
459
+ raw: {},
460
+ });
461
+ await drain();
462
+
463
+ assert.equal((fake.sends[0] as FakeSend).status, "delivered");
464
+ assert.deepEqual(fake.preferenceUpdates, []);
465
+ assert.equal(
466
+ fake.outbound().filter((row) => row.eventType === "email.delivered").length,
467
+ 1,
468
+ );
469
+ });
@@ -0,0 +1,229 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import type { EmailEvent, EmailProvider } from "@hogsend/core";
4
+ import type { Database } from "@hogsend/db";
5
+ import { emailPreferences, emailSends } from "@hogsend/db";
6
+ import type { TemplateRegistry } from "@hogsend/email";
7
+
8
+ // mailer's import chain reaches env.ts (validates required env vars at import
9
+ // time) and lib/hatchet.ts (parses HATCHET_CLIENT_TOKEN as a JWT at import
10
+ // time) — stub both BEFORE the dynamic import. Nothing is ever contacted: the
11
+ // db is a recorder and the provider is never called on this path.
12
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
13
+ process.env.BETTER_AUTH_SECRET ??= "test-secret";
14
+ process.env.HATCHET_CLIENT_TOKEN ??=
15
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
16
+ const { createTrackedMailer } = await import("./mailer.js");
17
+
18
+ /**
19
+ * `email.rejected` handling (PRD 18).
20
+ *
21
+ * SES accepted the message, returned a message id, and then threw it away
22
+ * because it detected a virus. Two things have to be true of that, and the
23
+ * second one is the reason this file exists:
24
+ *
25
+ * 1. the send reaches a TERMINAL status — no further event is coming, so a row
26
+ * left at `sent` stays non-terminal permanently;
27
+ * 2. **NOTHING is suppressed.** The recipient's address is fine; our content
28
+ * was the problem. Folding a reject onto the bounce path would let one bad
29
+ * attachment permanently block a deliverable address, silently, with the
30
+ * customer discovering it months later.
31
+ *
32
+ * Asserted at the DB seam with a recording fake, so the assertion is about the
33
+ * statements the mailer actually issues rather than about a mock's call count.
34
+ * The reject deliberately NAMES a recipient (the normalizer sends
35
+ * `mail.destination`, because a reject is message-scoped): a no-suppression
36
+ * test over an empty recipient list would pass whatever the code did.
37
+ */
38
+
39
+ interface RecordedUpdate {
40
+ table: unknown;
41
+ values: Record<string, unknown>;
42
+ }
43
+
44
+ /**
45
+ * A resolved statement that also answers `.returning()`, like drizzle's
46
+ * builder. The bounce leg claims its send with a guarded `UPDATE ... RETURNING`
47
+ * (see `claimBounce`), so the recorder has to model the row it matched: one
48
+ * row = "a real send that had not bounced yet", which is what every bounce
49
+ * control below assumes.
50
+ */
51
+ function settled(): Promise<{ id: string }[]> & {
52
+ returning: () => Promise<{ id: string }[]>;
53
+ } {
54
+ const rows = [{ id: "send-row-uuid" }];
55
+ const promise = Promise.resolve(rows) as Promise<{ id: string }[]> & {
56
+ returning: () => Promise<{ id: string }[]>;
57
+ };
58
+ promise.returning = () => Promise.resolve(rows);
59
+ return promise;
60
+ }
61
+
62
+ function recordingDb(): { db: Database; updates: RecordedUpdate[] } {
63
+ const updates: RecordedUpdate[] = [];
64
+ const db = {
65
+ update(table: unknown) {
66
+ return {
67
+ set(values: Record<string, unknown>) {
68
+ updates.push({ table, values });
69
+ return { where: () => settled() };
70
+ },
71
+ };
72
+ },
73
+ };
74
+ return { db: db as unknown as Database, updates };
75
+ }
76
+
77
+ /** Never called on the webhook path — present only to satisfy the contract. */
78
+ const provider = {
79
+ meta: { id: "test", name: "Test" },
80
+ capabilities: { nativeTracking: false },
81
+ send: async () => ({ id: "unused" }),
82
+ } as unknown as EmailProvider;
83
+
84
+ function mailer(db: Database) {
85
+ return createTrackedMailer(
86
+ {
87
+ defaultFrom: "test@example.com",
88
+ templates: {} as TemplateRegistry,
89
+ db,
90
+ },
91
+ { provider },
92
+ );
93
+ }
94
+
95
+ function rejected(overrides: Partial<EmailEvent> = {}): EmailEvent {
96
+ return {
97
+ type: "email.rejected",
98
+ messageId: "0100018f-ses-rejected-id",
99
+ recipients: ["good-address@example.com"],
100
+ occurredAt: new Date().toISOString(),
101
+ reject: { reason: "Bad content" },
102
+ raw: {},
103
+ ...overrides,
104
+ };
105
+ }
106
+
107
+ test("email.rejected marks the send TERMINAL", async () => {
108
+ const { db, updates } = recordingDb();
109
+ const result = await mailer(db).handleWebhook(rejected());
110
+
111
+ assert.equal(result.type, "email.rejected");
112
+
113
+ const sendUpdates = updates.filter((row) => row.table === emailSends);
114
+ assert.equal(sendUpdates.length, 1);
115
+ // `failed` is the terminal status this schema already has for "did not reach
116
+ // the recipient and nothing further is coming". It is NOT `bounced`: that
117
+ // status carries a bounce classification the engine suppresses on.
118
+ assert.equal(sendUpdates[0]?.values.status, "failed");
119
+ });
120
+
121
+ test("email.rejected records no bounce facts on the send row", async () => {
122
+ const { db, updates } = recordingDb();
123
+ await mailer(db).handleWebhook(rejected());
124
+
125
+ const values = updates.find((row) => row.table === emailSends)?.values ?? {};
126
+ assert.equal("bouncedAt" in values, false);
127
+ assert.equal("bounceType" in values, false);
128
+ assert.equal("bounceReason" in values, false);
129
+ // A reject never arrived, so it must not read as a delivery either.
130
+ assert.equal("deliveredAt" in values, false);
131
+ });
132
+
133
+ test("email.rejected SUPPRESSES NOTHING, even naming a recipient", async () => {
134
+ // THE assertion of this PRD. `email_preferences` is the only table
135
+ // suppression and the bounce counter live in, so ZERO writes to it is the
136
+ // whole claim: no `bounceCount` increment, no `suppressed` flag, nothing to
137
+ // undo later.
138
+ const { db, updates } = recordingDb();
139
+ await mailer(db).handleWebhook(rejected());
140
+
141
+ const preferenceUpdates = updates.filter(
142
+ (row) => row.table === emailPreferences,
143
+ );
144
+ assert.deepEqual(preferenceUpdates, []);
145
+ });
146
+
147
+ test("a reject carrying a bounce block STILL suppresses nothing", async () => {
148
+ // Defence in depth. The plugin already strips `bounce` off a reject, so this
149
+ // is what happens if a future provider (or a hand-built event) does not: the
150
+ // engine branches on the TYPE, never on the presence of the block.
151
+ const { db, updates } = recordingDb();
152
+ await mailer(db).handleWebhook(
153
+ rejected({ bounce: { class: "permanent", code: "Permanent/General" } }),
154
+ );
155
+
156
+ assert.deepEqual(
157
+ updates.filter((row) => row.table === emailPreferences),
158
+ [],
159
+ );
160
+ });
161
+
162
+ test("a permanent bounce DOES suppress — the mutation check's control", async () => {
163
+ // The counterweight. Without this, "no preference writes" could pass because
164
+ // the recording db never sees preference writes at all, and the
165
+ // no-suppression test above would be vacuous.
166
+ const { db, updates } = recordingDb();
167
+ await mailer(db).handleWebhook({
168
+ type: "email.bounced",
169
+ messageId: "0100018f-ses-bounced-id",
170
+ recipients: ["good-address@example.com"],
171
+ occurredAt: new Date().toISOString(),
172
+ bounce: { class: "permanent", code: "Permanent/General" },
173
+ raw: {},
174
+ });
175
+
176
+ const preferenceUpdates = updates.filter(
177
+ (row) => row.table === emailPreferences,
178
+ );
179
+ assert.equal(preferenceUpdates.length, 1);
180
+ assert.ok("bounceCount" in (preferenceUpdates[0]?.values ?? {}));
181
+ });
182
+
183
+ test("a consumer handler for email.rejected is invoked with the reason", async () => {
184
+ // How a journey learns the send is never arriving: the neutral type gets a
185
+ // `WebhookHandlerMap` slot for free, and the reason rides verbatim.
186
+ const { db } = recordingDb();
187
+ const seen: EmailEvent[] = [];
188
+ const service = createTrackedMailer(
189
+ {
190
+ defaultFrom: "test@example.com",
191
+ templates: {} as TemplateRegistry,
192
+ db,
193
+ webhookHandlers: {
194
+ "email.rejected": (event) => {
195
+ seen.push(event);
196
+ },
197
+ },
198
+ },
199
+ { provider },
200
+ );
201
+
202
+ const result = await service.handleWebhook(rejected());
203
+
204
+ assert.equal(result.handled, true);
205
+ assert.equal(seen.length, 1);
206
+ assert.deepEqual(seen[0]?.reject, { reason: "Bad content" });
207
+ });
208
+
209
+ test("a provider that never emits email.rejected behaves exactly as today", async () => {
210
+ // The back-compat line: adding a union member must not change any existing
211
+ // branch. A delivery still writes `delivered` + `deliveredAt` and touches no
212
+ // preference row.
213
+ const { db, updates } = recordingDb();
214
+ await mailer(db).handleWebhook({
215
+ type: "email.delivered",
216
+ messageId: "0100018f-ses-delivered-id",
217
+ recipients: ["good-address@example.com"],
218
+ occurredAt: new Date().toISOString(),
219
+ raw: {},
220
+ });
221
+
222
+ const values = updates.find((row) => row.table === emailSends)?.values ?? {};
223
+ assert.equal(values.status, "delivered");
224
+ assert.ok(values.deliveredAt instanceof Date);
225
+ assert.deepEqual(
226
+ updates.filter((row) => row.table === emailPreferences),
227
+ [],
228
+ );
229
+ });