@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,376 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import type {
4
+ EmailAttachment,
5
+ EmailEvent,
6
+ EmailProvider,
7
+ EmailProviderCapabilities,
8
+ SendEmailOptions,
9
+ } from "@hogsend/core";
10
+ import { MAX_ATTACHMENT_BYTES } from "@hogsend/core";
11
+ import { EmailAction, type TemplateRegistry } from "@hogsend/email";
12
+
13
+ // The engine's env contract is validated at module scope (lib/hatchet.ts pulls
14
+ // env.ts in through lib/tracked.ts), so these must be in place BEFORE the
15
+ // dynamic imports below. Nothing here reaches the network: the db is a fake,
16
+ // the provider is a fake, and Hatchet is only constructed, never called.
17
+ process.env.NODE_ENV ??= "test";
18
+ process.env.LOG_LEVEL ??= "error";
19
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
20
+ process.env.BETTER_AUTH_SECRET ??=
21
+ "test-secret-for-node-test-minimum-32-characters-long";
22
+ // A structurally-valid but inert Hatchet token (the same fixture apps/api's
23
+ // vitest config uses). The client is constructed at import; it never dials.
24
+ process.env.HATCHET_CLIENT_TOKEN ??=
25
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
26
+
27
+ const { sendTrackedEmail } = await import("./tracked.js");
28
+ const { AttachmentsUnsupportedError } = await import("./attachments.js");
29
+ const { prepareTrackedHtml } = await import("./tracking.js");
30
+ const { sendEmail, setEmailService } = await import("./email.js");
31
+
32
+ const TEMPLATE = "welcome" as never;
33
+ const EMAIL_SEND_ID = "es_00000000-0000-4000-8000-000000000001";
34
+ const BASE_URL = "https://api.example.com";
35
+
36
+ /**
37
+ * The registry the mailer renders through. `EmailAction` is imported rather
38
+ * than a hand-written component so the element is built by the SAME React copy
39
+ * `renderToHtml` renders with (the engine itself has no `react` dependency —
40
+ * it is the consumer's peer). The absolute href gives `rewriteLinks` a real
41
+ * anchor to rewrite, which the tracking-survival test asserts on.
42
+ */
43
+ const registry = {
44
+ welcome: {
45
+ component: () =>
46
+ EmailAction({
47
+ href: "https://example.com/welcome",
48
+ event: "welcome.clicked",
49
+ children: "Get started",
50
+ }),
51
+ defaultSubject: "Welcome",
52
+ },
53
+ } as unknown as TemplateRegistry;
54
+
55
+ /**
56
+ * A minimal chainable fake `db` (mirrors tracked-idempotency-header.test.ts).
57
+ * Records EVERY `insert(...).values(...)` payload: the `email_sends` row is the
58
+ * first insert; when the real `prepareTrackedHtml` runs, the `tracked_links`
59
+ * bulk insert (an ARRAY payload) lands after it.
60
+ */
61
+ function makeFakeDb() {
62
+ const inserted: unknown[] = [];
63
+ const chain = (result: unknown[]): Record<string, unknown> => {
64
+ const self: Record<string, unknown> = {
65
+ from: () => self,
66
+ leftJoin: () => self,
67
+ where: () => self,
68
+ orderBy: () => self,
69
+ limit: () => Promise.resolve(result),
70
+ // A drizzle query builder IS thenable: `await db.select().from(t).where(c)`
71
+ // with no terminal call is exactly the shape emitOutbound uses, so the
72
+ // fake has to be thenable to model it.
73
+ // biome-ignore lint/suspicious/noThenProperty: modelling a drizzle builder
74
+ then: (resolve: (rows: unknown[]) => void) => resolve(result),
75
+ };
76
+ return self;
77
+ };
78
+ const returning = () => Promise.resolve([{ id: EMAIL_SEND_ID }]);
79
+ const db = {
80
+ select: () => chain([]),
81
+ insert: () => ({
82
+ values: (values: unknown) => {
83
+ inserted.push(values);
84
+ return {
85
+ onConflictDoNothing: () => ({ returning }),
86
+ returning,
87
+ };
88
+ },
89
+ }),
90
+ update: () => ({
91
+ set: () => ({ where: () => Promise.resolve() }),
92
+ }),
93
+ };
94
+ return { db: db as never, inserted };
95
+ }
96
+
97
+ /**
98
+ * A fake provider that only records what it was handed. `capabilities` decides
99
+ * whether attachments may travel — NEVER the id — so every test states it
100
+ * explicitly. Default models a capable transport; pass `capabilities: {}` for
101
+ * one that never declared `attachments` (absence is not consent).
102
+ */
103
+ function makeFakeProvider(
104
+ over: { id?: string; capabilities?: EmailProviderCapabilities } = {},
105
+ ) {
106
+ const id = over.id ?? "hogsend";
107
+ const capabilities =
108
+ "capabilities" in over ? over.capabilities : { attachments: true };
109
+ const sends: SendEmailOptions[] = [];
110
+ const provider = {
111
+ meta: { id, name: "Fake" },
112
+ capabilities,
113
+ send: async (options: SendEmailOptions) => {
114
+ sends.push(options);
115
+ return { id: "msg_fake_1" };
116
+ },
117
+ sendBatch: async () => ({ results: [] }),
118
+ verifyWebhook: (): EmailEvent => {
119
+ throw new Error("not used");
120
+ },
121
+ parseWebhook: (): EmailEvent => {
122
+ throw new Error("not used");
123
+ },
124
+ } as unknown as EmailProvider;
125
+ return { provider, sends };
126
+ }
127
+
128
+ function baseOptions(over: Record<string, unknown> = {}) {
129
+ return {
130
+ templateKey: TEMPLATE,
131
+ props: {} as never,
132
+ from: "Hogsend <noreply@example.com>",
133
+ to: "user@example.com",
134
+ // Skips suppression / control group / frequency cap / journey suppress, all
135
+ // of which would need far more DB shape than this fake carries and none of
136
+ // which this suite is about.
137
+ skipPreferenceCheck: true,
138
+ ...over,
139
+ };
140
+ }
141
+
142
+ const PDF_SENTINEL = "%PDF-1.4 SENTINEL-BYTES-NEVER-STORED";
143
+
144
+ function pdfAttachment(): EmailAttachment {
145
+ return {
146
+ filename: "invoice.pdf",
147
+ contentType: "application/pdf",
148
+ content: new TextEncoder().encode(PDF_SENTINEL),
149
+ };
150
+ }
151
+
152
+ test("a send with no attachments hands the provider options with NO attachments key", async () => {
153
+ // The no-regression assertion for every existing send: not `attachments:
154
+ // undefined`, the key simply is not there — the wire is byte-identical to
155
+ // before this feature existed. The row grows no metadata either.
156
+ const { db, inserted } = makeFakeDb();
157
+ const { provider, sends } = makeFakeProvider();
158
+
159
+ await sendTrackedEmail({ db, provider, registry, options: baseOptions() });
160
+
161
+ assert.equal(sends.length, 1);
162
+ assert.equal("attachments" in (sends[0] ?? {}), false);
163
+ assert.equal(
164
+ "metadata" in ((inserted[0] ?? {}) as Record<string, unknown>),
165
+ false,
166
+ );
167
+ });
168
+
169
+ test("attachments pass through to a provider that declares the capability", async () => {
170
+ const { db } = makeFakeDb();
171
+ const { provider, sends } = makeFakeProvider({
172
+ capabilities: { attachments: true },
173
+ });
174
+ const attachment = pdfAttachment();
175
+
176
+ await sendTrackedEmail({
177
+ db,
178
+ provider,
179
+ registry,
180
+ options: baseOptions({ attachments: [attachment] }),
181
+ });
182
+
183
+ assert.equal(sends.length, 1);
184
+ assert.deepEqual(sends[0]?.attachments, [attachment]);
185
+ });
186
+
187
+ test("tracking still applies with attachments present: links rewritten, pixel injected, files alongside", async () => {
188
+ // THE locked ordering decision of PRD 17 task 6: tracking is applied FIRST
189
+ // and the attachments ride alongside the TRACKED html on the same provider
190
+ // call. An attachment must never cause tracking to be skipped — this runs
191
+ // the REAL prepareTrackedHtml (rewriteLinks + injectOpenPixel), not a stub.
192
+ const { db } = makeFakeDb();
193
+ const { provider, sends } = makeFakeProvider({
194
+ capabilities: { attachments: true },
195
+ });
196
+ const attachment = pdfAttachment();
197
+
198
+ await sendTrackedEmail({
199
+ db,
200
+ provider,
201
+ registry,
202
+ prepareTrackedHtml,
203
+ options: baseOptions({
204
+ baseUrl: BASE_URL,
205
+ attachments: [attachment],
206
+ }),
207
+ });
208
+
209
+ assert.equal(sends.length, 1);
210
+ const html = sends[0]?.html ?? "";
211
+ // The template's absolute link was rewritten to the first-party redirect…
212
+ assert.match(html, new RegExp(`${BASE_URL}/v1/t/c/`));
213
+ assert.doesNotMatch(html, /https:\/\/example\.com\/welcome/);
214
+ // …the open pixel was injected for THIS send…
215
+ assert.match(html, new RegExp(`${BASE_URL}/v1/t/o/${EMAIL_SEND_ID}`));
216
+ // …and the attachments travelled on the SAME wire call as the tracked html.
217
+ assert.deepEqual(sends[0]?.attachments, [attachment]);
218
+ });
219
+
220
+ test("a provider without capabilities.attachments throws, naming the provider — BEFORE send and BEFORE any row", async () => {
221
+ // Absence is not consent: a receipt delivered without its invoice looks
222
+ // `sent` from every dashboard, so the engine must refuse loudly instead.
223
+ // The fail-before-work assertions are the point — a throw AFTER the provider
224
+ // call (or after the row insert) would record a send that must not exist.
225
+ const { db, inserted } = makeFakeDb();
226
+ const { provider, sends } = makeFakeProvider({
227
+ id: "resend",
228
+ capabilities: {},
229
+ });
230
+
231
+ await assert.rejects(
232
+ sendTrackedEmail({
233
+ db,
234
+ provider,
235
+ registry,
236
+ options: baseOptions({ attachments: [pdfAttachment()] }),
237
+ }),
238
+ (error: unknown) => {
239
+ assert.ok(error instanceof AttachmentsUnsupportedError);
240
+ assert.match(error.message, /"resend"/);
241
+ assert.match(error.message, /capabilities\.attachments/);
242
+ return true;
243
+ },
244
+ );
245
+
246
+ assert.equal(sends.length, 0);
247
+ assert.equal(inserted.length, 0);
248
+ });
249
+
250
+ test("a CR/LF filename throws InvalidAttachmentError before the provider is called", async () => {
251
+ const { db, inserted } = makeFakeDb();
252
+ const { provider, sends } = makeFakeProvider({
253
+ capabilities: { attachments: true },
254
+ });
255
+
256
+ await assert.rejects(
257
+ sendTrackedEmail({
258
+ db,
259
+ provider,
260
+ registry,
261
+ options: baseOptions({
262
+ attachments: [
263
+ { filename: "invoice\r\n.pdf", content: new Uint8Array([1]) },
264
+ ],
265
+ }),
266
+ }),
267
+ (error: unknown) => {
268
+ assert.equal((error as Error).name, "InvalidAttachmentError");
269
+ assert.match((error as Error).message, /CR, LF or NUL/);
270
+ return true;
271
+ },
272
+ );
273
+
274
+ assert.equal(sends.length, 0);
275
+ assert.equal(inserted.length, 0);
276
+ });
277
+
278
+ test("an over-cap attachment throws before the provider is called", async () => {
279
+ const { db } = makeFakeDb();
280
+ const { provider, sends } = makeFakeProvider({
281
+ capabilities: { attachments: true },
282
+ });
283
+
284
+ await assert.rejects(
285
+ sendTrackedEmail({
286
+ db,
287
+ provider,
288
+ registry,
289
+ options: baseOptions({
290
+ attachments: [
291
+ {
292
+ filename: "huge.bin",
293
+ content: new Uint8Array(MAX_ATTACHMENT_BYTES + 1),
294
+ },
295
+ ],
296
+ }),
297
+ }),
298
+ (error: unknown) => {
299
+ assert.equal((error as Error).name, "InvalidAttachmentError");
300
+ return true;
301
+ },
302
+ );
303
+
304
+ assert.equal(sends.length, 0);
305
+ });
306
+
307
+ test("email_sends records filename/size/contentType — and NEVER the content bytes", async () => {
308
+ // Storing customer invoices indefinitely is a data-protection decision
309
+ // nobody has made, so the absence of the bytes is asserted DELIBERATELY:
310
+ // deepEqual pins the metadata to EXACTLY the three descriptive fields, and
311
+ // the sentinel scan proves the payload text appears nowhere in the row. The
312
+ // `{ base64 }` attachment additionally pins `sizeBytes` to the DECODED
313
+ // length ("abcd" → 3 raw bytes), the same number the size cap enforces.
314
+ const { db, inserted } = makeFakeDb();
315
+ const { provider } = makeFakeProvider({
316
+ capabilities: { attachments: true },
317
+ });
318
+
319
+ await sendTrackedEmail({
320
+ db,
321
+ provider,
322
+ registry,
323
+ options: baseOptions({
324
+ attachments: [
325
+ pdfAttachment(),
326
+ { filename: "export.csv", content: { base64: "abcd" } },
327
+ ],
328
+ }),
329
+ });
330
+
331
+ const row = (inserted[0] ?? {}) as Record<string, unknown>;
332
+ const metadata = row.metadata as Record<string, unknown>;
333
+ assert.deepEqual(metadata.attachments, [
334
+ {
335
+ filename: "invoice.pdf",
336
+ sizeBytes: PDF_SENTINEL.length,
337
+ contentType: "application/pdf",
338
+ },
339
+ { filename: "export.csv", sizeBytes: 3 },
340
+ ]);
341
+ // Belt and braces on the absence: no `content` key on any entry, and the
342
+ // sentinel text is nowhere in the serialized row.
343
+ for (const entry of metadata.attachments as Record<string, unknown>[]) {
344
+ assert.equal("content" in entry, false);
345
+ }
346
+ assert.equal(JSON.stringify(row).includes("SENTINEL"), false);
347
+ });
348
+
349
+ test("the sendEmail journey helper forwards attachments to the email service", async () => {
350
+ // The authoring surface of task 5: `sendEmail({ ..., attachments })` must
351
+ // hand the files to `service.send` exactly like every other option. No
352
+ // journey boundary here — a plain forwarding check at the service seam.
353
+ const received: Array<Record<string, unknown>> = [];
354
+ setEmailService({
355
+ send: async (options: unknown) => {
356
+ received.push(options as Record<string, unknown>);
357
+ return {
358
+ emailSendId: EMAIL_SEND_ID,
359
+ messageId: "msg_fake_1",
360
+ resendId: "msg_fake_1",
361
+ status: "sent",
362
+ };
363
+ },
364
+ } as never);
365
+ const attachment = pdfAttachment();
366
+
367
+ await sendEmail({
368
+ to: "user@example.com",
369
+ userId: "user_1",
370
+ template: TEMPLATE,
371
+ attachments: [attachment],
372
+ });
373
+
374
+ assert.equal(received.length, 1);
375
+ assert.deepEqual(received[0]?.attachments, [attachment]);
376
+ });