@hogsend/engine 0.64.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 (68) hide show
  1. package/package.json +12 -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 +37 -0
  16. package/src/index.ts +87 -1
  17. package/src/lib/account-link-emit.ts +126 -0
  18. package/src/lib/account-link-events.ts +180 -0
  19. package/src/lib/account-link-hooks.test.ts +158 -0
  20. package/src/lib/account-link-hooks.ts +73 -0
  21. package/src/lib/account-link-ingest.ts +364 -0
  22. package/src/lib/account-link-nonce.test.ts +52 -0
  23. package/src/lib/account-link-nonce.ts +57 -0
  24. package/src/lib/account-link-origins.test.ts +72 -0
  25. package/src/lib/account-link-origins.ts +87 -0
  26. package/src/lib/account-link-pkce.test.ts +91 -0
  27. package/src/lib/account-link-pkce.ts +106 -0
  28. package/src/lib/account-link-provider-registry.test.ts +52 -0
  29. package/src/lib/account-link-provider-registry.ts +61 -0
  30. package/src/lib/account-link-throttle.test.ts +178 -0
  31. package/src/lib/account-link-throttle.ts +130 -0
  32. package/src/lib/account-link-url.ts +85 -0
  33. package/src/lib/account-links-emit.test.ts +525 -0
  34. package/src/lib/account-links-env.test.ts +40 -0
  35. package/src/lib/account-links-from-env.test.ts +187 -0
  36. package/src/lib/account-links-from-env.ts +126 -0
  37. package/src/lib/account-links.ts +1300 -0
  38. package/src/lib/app-secret.ts +34 -0
  39. package/src/lib/connector-actions.test.ts +13 -4
  40. package/src/lib/connector-state.account-link.test.ts +114 -0
  41. package/src/lib/connector-state.ts +48 -3
  42. package/src/lib/contacts.ts +320 -6
  43. package/src/lib/outbound-account-payloads.test.ts +137 -0
  44. package/src/lib/outbound.ts +91 -0
  45. package/src/lib/provider-credentials.ts +19 -5
  46. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  47. package/src/lib/webhook-signing.ts +18 -1
  48. package/src/routes/accounts/callback.ts +597 -0
  49. package/src/routes/accounts/emit.ts +231 -0
  50. package/src/routes/accounts/import-links.ts +210 -0
  51. package/src/routes/accounts/index.ts +75 -0
  52. package/src/routes/accounts/lookup.ts +177 -0
  53. package/src/routes/accounts/me.ts +215 -0
  54. package/src/routes/accounts/mint.ts +279 -0
  55. package/src/routes/accounts/pages.ts +62 -0
  56. package/src/routes/accounts/resolve.ts +61 -0
  57. package/src/routes/accounts/serialize.ts +96 -0
  58. package/src/routes/accounts/shared.ts +107 -0
  59. package/src/routes/accounts/start.ts +229 -0
  60. package/src/routes/accounts/unlink.ts +98 -0
  61. package/src/routes/admin/agent.ts +2 -0
  62. package/src/routes/admin/api-keys.ts +7 -0
  63. package/src/routes/admin/contacts.ts +38 -2
  64. package/src/routes/connectors/index.ts +17 -0
  65. package/src/routes/contacts/index.ts +8 -0
  66. package/src/routes/index.ts +75 -0
  67. package/src/testing-barrel.test.ts +74 -0
  68. package/src/testing.ts +17 -0
@@ -0,0 +1,525 @@
1
+ import assert from "node:assert/strict";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import test from "node:test";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ // `account-link-events.ts` is deliberately RUNTIME-import-free (its only
7
+ // imports are `import type`), so no env stub is needed here — importing it
8
+ // must never drag `env.ts` (which validates at import time) into a test.
9
+ const {
10
+ buildAccountLinkedPayload,
11
+ buildAccountUnlinkedPayload,
12
+ buildDedupeKey,
13
+ buildLinkFailedPayload,
14
+ } = await import("./account-link-events.js");
15
+
16
+ const AT = new Date("2026-08-14T12:00:00.000Z");
17
+
18
+ test("buildDedupeKey escapes nothing and is a pure template", () => {
19
+ assert.equal(
20
+ buildDedupeKey("steam", "76561198000000000", "3"),
21
+ "al:steam:76561198000000000:v3",
22
+ );
23
+
24
+ // A REGRESSION PIN. Someone will one day be tempted to URL-encode or
25
+ // normalize these segments; the moment they do, the key for a version
26
+ // emitted before the change no longer matches the key emitted after it, and
27
+ // the `(endpointId, dedupeKey)` dedupe silently stops deduping. Every
28
+ // segment must survive VERBATIM.
29
+ assert.equal(
30
+ buildDedupeKey("twitch:beta", "user id/with?chars&+%", "9007199254740995"),
31
+ "al:twitch:beta:user id/with?chars&+%:v9007199254740995",
32
+ );
33
+
34
+ // `version` is a STRING in and a STRING out — never parsed, never Number()'d
35
+ // (DECISIONS §5.1). An odd value above 2^53 is the only one that can catch a
36
+ // round-trip through float64.
37
+ assert.equal(
38
+ buildDedupeKey("steam", "u", "9007199254740995"),
39
+ "al:steam:u:v9007199254740995",
40
+ );
41
+ });
42
+
43
+ test("buildAccountLinkedPayload carries owner.userId and owner.email, not the provider email", () => {
44
+ const payload = buildAccountLinkedPayload(
45
+ {
46
+ status: "linked",
47
+ relink: false,
48
+ version: "7",
49
+ owner: {
50
+ contactId: "contact-1",
51
+ userId: "player-42",
52
+ email: "player@contact.example",
53
+ },
54
+ row: {
55
+ id: "row-1",
56
+ contactId: "contact-1",
57
+ provider: "steam",
58
+ providerUserId: "76561198000000000",
59
+ username: "gaben",
60
+ // The provider-reported address. It is a display property at most
61
+ // (DECISIONS §6.3/§6.4) and must NEVER surface in a field named
62
+ // `email` next to `contactId` — that is exactly how a downstream
63
+ // system ends up resolving on it.
64
+ verifiedEmail: "provider-reported@steam.example",
65
+ avatarUrl: null,
66
+ method: "oauth",
67
+ singleton: true,
68
+ version: "7",
69
+ linkedAt: AT,
70
+ unlinkedAt: null,
71
+ unlinkReason: null,
72
+ tokensRevokedAt: null,
73
+ hasTokens: false,
74
+ },
75
+ },
76
+ AT,
77
+ );
78
+
79
+ assert.equal(payload.userId, "player-42");
80
+ assert.equal(payload.email, "player@contact.example");
81
+ assert.notEqual(payload.email, "provider-reported@steam.example");
82
+ assert.deepEqual(payload, {
83
+ state: "linked",
84
+ provider: "steam",
85
+ providerUserId: "76561198000000000",
86
+ contactId: "contact-1",
87
+ userId: "player-42",
88
+ email: "player@contact.example",
89
+ username: "gaben",
90
+ method: "oauth",
91
+ relink: false,
92
+ version: "7",
93
+ at: "2026-08-14T12:00:00.000Z",
94
+ });
95
+ });
96
+
97
+ test("buildAccountLinkedPayload keeps an above-2^53 version as an exact string", () => {
98
+ const payload = buildAccountLinkedPayload(
99
+ {
100
+ status: "relinked",
101
+ relink: true,
102
+ version: "9007199254740995",
103
+ owner: { contactId: "c", userId: null, email: null },
104
+ previous: {
105
+ contactId: "old",
106
+ version: "9007199254740994",
107
+ owner: { contactId: "old", userId: null, email: null },
108
+ },
109
+ row: {
110
+ id: "row",
111
+ contactId: "c",
112
+ provider: "twitch",
113
+ providerUserId: "u",
114
+ username: null,
115
+ verifiedEmail: null,
116
+ avatarUrl: null,
117
+ method: "oauth",
118
+ singleton: false,
119
+ version: "9007199254740995",
120
+ linkedAt: AT,
121
+ unlinkedAt: null,
122
+ unlinkReason: null,
123
+ tokensRevokedAt: null,
124
+ hasTokens: false,
125
+ },
126
+ },
127
+ AT,
128
+ );
129
+
130
+ assert.equal(payload.relink, true);
131
+ assert.equal(JSON.parse(JSON.stringify(payload)).version, "9007199254740995");
132
+ });
133
+
134
+ test("buildAccountUnlinkedPayload reads the contact key and email off the owner block", () => {
135
+ const payload = buildAccountUnlinkedPayload(
136
+ {
137
+ provider: "steam",
138
+ providerUserId: "76561198000000001",
139
+ version: "4",
140
+ reason: "relinked",
141
+ owner: {
142
+ contactId: "loser-contact",
143
+ userId: "anon-abc",
144
+ email: null,
145
+ },
146
+ },
147
+ AT,
148
+ );
149
+
150
+ assert.deepEqual(payload, {
151
+ state: "unlinked",
152
+ provider: "steam",
153
+ providerUserId: "76561198000000001",
154
+ // The OWNER block is the single source — never a second contacts lookup
155
+ // at emit time (DECISIONS §15.5).
156
+ contactId: "loser-contact",
157
+ userId: "anon-abc",
158
+ email: null,
159
+ reason: "relinked",
160
+ version: "4",
161
+ at: "2026-08-14T12:00:00.000Z",
162
+ });
163
+ });
164
+
165
+ test("buildLinkFailedPayload carries no version and no state", () => {
166
+ const payload = buildLinkFailedPayload(
167
+ { provider: "steam", reason: "state_invalid", contactId: null },
168
+ AT,
169
+ );
170
+
171
+ assert.deepEqual(payload, {
172
+ provider: "steam",
173
+ reason: "state_invalid",
174
+ contactId: null,
175
+ at: "2026-08-14T12:00:00.000Z",
176
+ });
177
+ assert.equal("version" in payload, false);
178
+ assert.equal("state" in payload, false);
179
+ });
180
+
181
+ const STORE_SOURCE = readFileSync(
182
+ fileURLToPath(new URL("./account-links.ts", import.meta.url)),
183
+ "utf8",
184
+ );
185
+
186
+ /**
187
+ * Every symbol that reaches the outbound spine. Naming ONE of these is what
188
+ * the first version of this guard did, and a second emit surface
189
+ * (`emitAccountUnlinked`) walked straight past it.
190
+ */
191
+ const EMIT_SYMBOLS = ["emitOutbound", "emitAccountUnlinked"];
192
+
193
+ /**
194
+ * The store's permitted RUNTIME imports (`import type` is erased, so it cannot
195
+ * carry a call). Anything else — including a THIRD emit helper nobody has
196
+ * written yet, under any name — trips the guard, because emitting requires
197
+ * importing something that can emit.
198
+ *
199
+ * KNOWN LIMIT, stated rather than papered over: this guard reads LITERAL
200
+ * import specifiers and LITERAL symbol names. A store emit routed through both
201
+ * a renamed re-export AND a computed `import(someVariable)` would evade it —
202
+ * source scanning has no fixed point, so the regexes are deliberately not
203
+ * widened. Every single-step variant is caught; if you ever see a non-literal
204
+ * `import(...)` in `lib/account-links.ts`, treat it as the bypass it is rather
205
+ * than as this guard's silence.
206
+ */
207
+ const ALLOWED_RUNTIME_IMPORTS = [
208
+ "@hogsend/core",
209
+ "@hogsend/db",
210
+ "drizzle-orm",
211
+ // NOT "../env.js": that file validates at import time, and this module is
212
+ // reachable from the `@hogsend/engine/testing` barrel. `./app-secret.js`
213
+ // is the lazy accessor that keeps the barrel importable with no
214
+ // environment — see `src/testing-barrel.test.ts`, which fails if the
215
+ // static form comes back.
216
+ "./app-secret.js",
217
+ "./provider-credentials.js",
218
+ ];
219
+
220
+ /** STATIC runtime (non-`import type`) module specifiers. */
221
+ function staticImports(source: string): string[] {
222
+ const specifiers = new Set<string>();
223
+ for (const m of source.matchAll(
224
+ /^import\s+(?!type\s)(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/gm,
225
+ )) {
226
+ if (m[1]) specifiers.add(m[1]);
227
+ }
228
+ return [...specifiers];
229
+ }
230
+
231
+ /** DYNAMIC `import("…")` module specifiers. */
232
+ function dynamicImports(source: string): string[] {
233
+ const specifiers = new Set<string>();
234
+ for (const m of source.matchAll(/\bimport\s*\(\s*["']([^"']+)["']/g)) {
235
+ if (m[1]) specifiers.add(m[1]);
236
+ }
237
+ return [...specifiers];
238
+ }
239
+
240
+ /** Runtime (non-`import type`) module specifiers, static and dynamic. */
241
+ function runtimeImports(source: string): string[] {
242
+ return [...new Set([...staticImports(source), ...dynamicImports(source)])];
243
+ }
244
+
245
+ test("the store module reaches no emit surface", () => {
246
+ // DECISIONS §15.7: ONE OWNER PER EMIT SITE, and `lib/account-links.ts` is
247
+ // not one of them — it returns facts, its callers emit.
248
+ //
249
+ // This assertion is a SOURCE read rather than a behavioural test on purpose.
250
+ // A store emit PLUS a route emit for the same mutation share the
251
+ // `al:<provider>:<uid>:v<version>` key, so `emitOutbound`'s
252
+ // `onConflictDoNothing({ target: [endpointId, dedupeKey] })` would silently
253
+ // swallow the duplicate: no other test in this repo could fail. The
254
+ // duplicate would just hide which layer owns the fact.
255
+ const hits = STORE_SOURCE.split("\n")
256
+ .map((line, i) => [i + 1, line] as const)
257
+ .filter(([, line]) => EMIT_SYMBOLS.some((symbol) => line.includes(symbol)));
258
+
259
+ assert.deepEqual(
260
+ hits,
261
+ [],
262
+ "lib/account-links.ts must import NEITHER the outbound spine " +
263
+ "(`emitOutbound`) NOR the account-link fan-out helper " +
264
+ `(\`emitAccountUnlinked\`, ./account-link-emit.js); found: ${JSON.stringify(hits)}`,
265
+ );
266
+ });
267
+
268
+ const EMIT_HELPER_SOURCE = readFileSync(
269
+ fileURLToPath(new URL("./account-link-emit.ts", import.meta.url)),
270
+ "utf8",
271
+ );
272
+
273
+ test("the emit helper reaches the spine only by DYNAMIC import", () => {
274
+ // `lib/contacts.ts` imports `account-link-emit.ts`, and `src/testing.ts`
275
+ // re-exports `softDeleteContact` from `lib/contacts.ts`. A STATIC
276
+ // `./hatchet.js` or `./outbound.js` here (outbound →
277
+ // `workflows/deliver-webhook.js` → `lib/hatchet.js`) therefore runs
278
+ // `HatchetClient.init(...)` the instant anything touches the
279
+ // `@hogsend/engine/testing` barrel, which is documented side-effect-free.
280
+ //
281
+ // This is a SOURCE read because NOTHING ELSE CAN CATCH IT. Restoring the
282
+ // static form leaves every gate green — including this package's own suite —
283
+ // because every test environment hands `HATCHET_CLIENT_TOKEN` a well-formed
284
+ // dummy JWT; the throw only appears where the token is malformed or absent,
285
+ // which no gate reproduces. Without this line a simplify pass that dislikes
286
+ // dynamic imports in a loop re-breaks the barrel silently.
287
+ const forbidden = ["./hatchet.js", "./outbound.js"];
288
+ const statics = staticImports(EMIT_HELPER_SOURCE);
289
+ assert.deepEqual(
290
+ statics.filter((s) => forbidden.includes(s)),
291
+ [],
292
+ "lib/account-link-emit.ts must import ./hatchet.js and ./outbound.js " +
293
+ "DYNAMICALLY (inside the fire-and-forget body), never statically: a " +
294
+ "static import runs HatchetClient.init when the side-effect-free " +
295
+ "`@hogsend/engine/testing` barrel is loaded, which throws " +
296
+ `"Invalid token format" without a real token. Found: ${JSON.stringify(statics)}`,
297
+ );
298
+
299
+ // And they ARE still reached — a guard that passed because the emit stopped
300
+ // emitting would be worthless.
301
+ const dynamics = dynamicImports(EMIT_HELPER_SOURCE);
302
+ for (const specifier of forbidden) {
303
+ assert.ok(
304
+ dynamics.includes(specifier),
305
+ `lib/account-link-emit.ts no longer dynamically imports ${specifier}`,
306
+ );
307
+ }
308
+ });
309
+
310
+ test("the store module imports nothing new at runtime", () => {
311
+ // The symbol scan above only catches emit surfaces we already know the name
312
+ // of. This one catches the NEXT one: a store that emits has to import
313
+ // something that emits, so pinning the runtime import list makes any such
314
+ // edge fail here first, whatever it gets called.
315
+ assert.deepEqual(
316
+ runtimeImports(STORE_SOURCE).sort(),
317
+ [...ALLOWED_RUNTIME_IMPORTS].sort(),
318
+ "lib/account-links.ts changed its runtime imports. If the new import " +
319
+ "cannot emit (re-read DECISIONS §15.7 — the store returns facts, its " +
320
+ "callers emit), add it to ALLOWED_RUNTIME_IMPORTS.",
321
+ );
322
+ });
323
+
324
+ const INGEST_HELPER_SOURCE = readFileSync(
325
+ fileURLToPath(new URL("./account-link-ingest.ts", import.meta.url)),
326
+ "utf8",
327
+ );
328
+
329
+ test("the two planes stay two planes", () => {
330
+ // PRD 08 T5. `lib/account-link-ingest.ts` (journey plane) and
331
+ // `lib/account-link-emit.ts` (outbound plane) are called SIDE BY SIDE at
332
+ // every account-link site, which is exactly how someone later "simplifies"
333
+ // one into the other. Nothing else can catch that: collapsing the emit into
334
+ // the ingest still writes a delivery row, and collapsing the ingest into the
335
+ // emit still routes a journey — until the two fan out to the wrong audience.
336
+ // DECISIONS §8 (the `group.*` rule): the intent layer emits, and the ingest
337
+ // path never does.
338
+ const ingestHits = INGEST_HELPER_SOURCE.split("\n")
339
+ .map((line, i) => [i + 1, line] as const)
340
+ .filter(
341
+ ([, line]) =>
342
+ !line.trimStart().startsWith("*") &&
343
+ !line.trimStart().startsWith("//") &&
344
+ EMIT_SYMBOLS.some((symbol) => line.includes(symbol)),
345
+ );
346
+ assert.deepEqual(
347
+ ingestHits,
348
+ [],
349
+ "lib/account-link-ingest.ts must reach NO emit surface — the ingest path " +
350
+ `never emits (DECISIONS §8); found: ${JSON.stringify(ingestHits)}`,
351
+ );
352
+
353
+ const emitHits = EMIT_HELPER_SOURCE.split("\n")
354
+ .map((line, i) => [i + 1, line] as const)
355
+ .filter(
356
+ ([, line]) =>
357
+ !line.trimStart().startsWith("*") &&
358
+ !line.trimStart().startsWith("//") &&
359
+ ["ingestEvent", "ingestAccountUnlinked"].some((s) => line.includes(s)),
360
+ );
361
+ assert.deepEqual(
362
+ emitHits,
363
+ [],
364
+ "lib/account-link-emit.ts must reach NO ingest surface — the two planes " +
365
+ `are called side by side, never nested; found: ${JSON.stringify(emitHits)}`,
366
+ );
367
+ });
368
+
369
+ test("the ingest helper reaches ingestion only by DYNAMIC import", () => {
370
+ // Same hazard as the emit helper's guard above, one layer along:
371
+ // `lib/contacts.ts` now imports THIS module (the merge fold's post-commit
372
+ // `account.unlinked`), and `src/testing.ts` re-exports from
373
+ // `lib/contacts.ts`. `./ingestion.js` reaches `lib/hatchet.js`, whose import
374
+ // runs `HatchetClient.init(...)` — so a static import here throws
375
+ // "Invalid token format" the instant the documented side-effect-free
376
+ // `@hogsend/engine/testing` barrel is loaded. It is ALSO a module cycle
377
+ // (`ingestion.ts` imports `contacts.ts` imports this). A SOURCE read because
378
+ // every gate stays green without it: the test environments all hand
379
+ // `HATCHET_CLIENT_TOKEN` a well-formed dummy JWT.
380
+ const forbidden = ["./ingestion.js", "./contacts.js", "./hatchet.js"];
381
+ const statics = staticImports(INGEST_HELPER_SOURCE);
382
+ assert.deepEqual(
383
+ statics.filter((s) => forbidden.includes(s)),
384
+ [],
385
+ "lib/account-link-ingest.ts must import ./ingestion.js, ./contacts.js " +
386
+ "and ./hatchet.js DYNAMICALLY (inside the fire-and-forget body), never " +
387
+ `statically. Found: ${JSON.stringify(statics)}`,
388
+ );
389
+
390
+ // And they ARE still reached — a guard that passed because the re-ingest
391
+ // stopped ingesting would be worthless.
392
+ const dynamics = dynamicImports(INGEST_HELPER_SOURCE);
393
+ for (const specifier of forbidden) {
394
+ assert.ok(
395
+ dynamics.includes(specifier),
396
+ `lib/account-link-ingest.ts no longer dynamically imports ${specifier}`,
397
+ );
398
+ }
399
+ });
400
+
401
+ test("every account-link emit site also reaches the journey plane", () => {
402
+ // THE PAIRING GUARD (PRD 08 T5). The two planes are called side by side, and
403
+ // the failure mode this catches is the one nothing else can: a NEW emit site
404
+ // that ships to the customer's subscriber and never routes a journey. Both
405
+ // planes fail SILENTLY when absent — an outbound-only site leaves every
406
+ // account-link journey dead for that path, and nothing throws, nothing logs,
407
+ // and every existing test stays green. The "two planes stay two planes"
408
+ // guard above only stops the two being NESTED; it cannot see a site that
409
+ // forgot one.
410
+ //
411
+ // Enumerated from source rather than pinned as a literal list, so a new file
412
+ // is judged by what it DOES, not by whether someone remembered to list it.
413
+ const SRC = fileURLToPath(new URL("..", import.meta.url)).replace(/\/$/, "");
414
+ // A FILESYSTEM walk, not `git ls-files`. Enumerating from the git index
415
+ // means a brand-new, not-yet-added emit file is INVISIBLE — and a new file
416
+ // is precisely the shape this guard exists to catch. (Verified: an untracked
417
+ // emit site with no re-ingest passed, and only failed after `git add -N`.)
418
+ const walk = (dir: string): string[] =>
419
+ readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
420
+ const full = `${dir}/${entry.name}`;
421
+ if (entry.isDirectory()) return walk(full);
422
+ if (!entry.name.endsWith(".ts") || entry.name.endsWith(".test.ts")) {
423
+ return [];
424
+ }
425
+ return [full.slice(SRC.length + 1)];
426
+ });
427
+ const files = walk(SRC);
428
+
429
+ // The machinery, not a site: these DECLARE the surfaces (the outbound spine
430
+ // itself, the event catalog, the payload builders) and the two account-link
431
+ // helper modules DEFINE them.
432
+ const MACHINERY = [
433
+ "lib/outbound.ts",
434
+ "lib/webhook-signing.ts",
435
+ "lib/account-link-events.ts",
436
+ "lib/account-link-emit.ts",
437
+ "lib/account-link-ingest.ts",
438
+ ];
439
+
440
+ // The deliberate one-plane emits, COUNTED per file with the reason. Both are
441
+ // erasure legs: the contact is deleted in the SAME transaction as the
442
+ // unlink, so there is no subject left to enroll. Filing a fresh `user_events`
443
+ // row and starting a journey for a just-erased person contradicts the
444
+ // erasure, and the only keys available are a soft-deleted row (which ingest
445
+ // drops as provenance-lost) or a value key that would MINT — resurrecting the
446
+ // row just erased. They still EMIT, because the customer's mirror must
447
+ // converge.
448
+ //
449
+ // A COUNT, not a filename, because `lib/contacts.ts` holds a PAIRED site (the
450
+ // merge fold) alongside its erasure leg — exempting the whole file would
451
+ // blind the guard to the merge fold losing its journey plane.
452
+ //
453
+ // Raising a number here is a real decision. An unpaired emit is invisible in
454
+ // production; write down why, or call the chokepoints instead.
455
+ const ERASURE_ONLY: Record<string, number> = {
456
+ // `softDeleteContact` — the deletion leg.
457
+ "lib/contacts.ts": 1,
458
+ // The admin erasure route, which runs its own transaction.
459
+ "routes/admin/contacts.ts": 1,
460
+ };
461
+
462
+ // COUNTED PER EVENT KIND, not per file. A whole-file total is defeated by a
463
+ // count-preserving RELOCATION: deleting the `ingestAccountUnlinked` from
464
+ // `noteUnlinked` and adding a second `ingestAccountLinked` to `noteLinked`
465
+ // holds `routes/accounts/emit.ts` at 2 emits / 2 re-ingests while
466
+ // `account.unlinked` reaches no journey at all. (Verified — the whole-file
467
+ // form passed that mutation.) Pairing each KIND with its own re-ingest makes
468
+ // the two halves un-swappable.
469
+ const count = (src: string, re: RegExp) => (src.match(re) ?? []).length;
470
+ const unbalanced: string[] = [];
471
+ let totalEmits = 0;
472
+ for (const file of files) {
473
+ if (MACHINERY.includes(file)) continue;
474
+ const code = readFileSync(`${SRC}/${file}`, "utf8")
475
+ .split("\n")
476
+ .filter((line) => {
477
+ const t = line.trimStart();
478
+ return !t.startsWith("*") && !t.startsWith("//") && !t.startsWith("/*");
479
+ })
480
+ .join("\n");
481
+
482
+ // Whitespace-permissive: an 80-col wrap can split `event:` from its
483
+ // literal, and a strict single-space match would score that as zero emits.
484
+ const emitted = (kind: string) =>
485
+ count(code, new RegExp(`event:\\s*"account\\.${kind}"`, "g"));
486
+ // Calls only — the trailing `(` keeps a bare `import { … }` from counting.
487
+ const ingested = (fn: string) =>
488
+ count(code, new RegExp(`\\bingestAccount${fn}\\(`, "g"));
489
+
490
+ const kinds: Array<[string, number, number]> = [
491
+ ["account.linked", emitted("linked"), ingested("Linked")],
492
+ [
493
+ "account.unlinked",
494
+ emitted("unlinked") +
495
+ count(code, /emitAccountUnlinked\(/g) -
496
+ (ERASURE_ONLY[file] ?? 0),
497
+ ingested("Unlinked"),
498
+ ],
499
+ ["account.link_failed", emitted("link_failed"), ingested("LinkFailed")],
500
+ ];
501
+ for (const [kind, emits, ingests] of kinds) {
502
+ totalEmits += emits;
503
+ if (emits !== ingests) {
504
+ unbalanced.push(
505
+ `${file} [${kind}]: ${emits} emit(s), ${ingests} re-ingest(s)`,
506
+ );
507
+ }
508
+ }
509
+ }
510
+
511
+ assert.ok(
512
+ totalEmits > 0,
513
+ "found NO account-link emit sites — this guard just went vacuous",
514
+ );
515
+ assert.deepEqual(
516
+ unbalanced,
517
+ [],
518
+ "every account.* emit must be PAIRED with a journey-plane re-ingest in " +
519
+ "the same file. A one-plane site is a SILENT hole: outbound-only " +
520
+ "leaves journeys dead, ingest-only leaves the customer's mirror " +
521
+ "stale, and neither fails loudly. Call the chokepoints in " +
522
+ "routes/accounts/emit.ts, or — if the site genuinely has no subject " +
523
+ "to enroll — add it to ERASURE_ONLY with the reason.",
524
+ );
525
+ });
@@ -0,0 +1,40 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ // env.ts validates at IMPORT time (t3-env parses process.env once), so the
5
+ // required vars are stubbed BEFORE the dynamic import below — the
6
+ // email-provider-boot.test.ts idiom. No ACCOUNT_LINK_* / STEAM_WEB_API_KEY var
7
+ // is set, which is exactly the case under test: an entirely-unset account-link
8
+ // block must leave validation green and the TTL on its default.
9
+ process.env.NODE_ENV ??= "test";
10
+ process.env.LOG_LEVEL ??= "error";
11
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
12
+ process.env.BETTER_AUTH_SECRET ??=
13
+ "test-secret-for-node-test-minimum-32-characters-long";
14
+ process.env.HATCHET_CLIENT_TOKEN ??=
15
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
16
+ for (const name of [
17
+ "ACCOUNT_LINK_TWITCH_CLIENT_ID",
18
+ "ACCOUNT_LINK_TWITCH_CLIENT_SECRET",
19
+ "STEAM_WEB_API_KEY",
20
+ "ACCOUNT_LINK_ALLOWED_ORIGINS",
21
+ "ACCOUNT_LINK_STATE_TTL_SECONDS",
22
+ ]) {
23
+ delete process.env[name];
24
+ }
25
+
26
+ const { env } = await import("../env.js");
27
+
28
+ test("ACCOUNT_LINK_STATE_TTL_SECONDS defaults to 900", () => {
29
+ assert.equal(env.ACCOUNT_LINK_STATE_TTL_SECONDS, 900);
30
+ });
31
+
32
+ test("an unset ACCOUNT_LINK_* block leaves env validation green", () => {
33
+ // The import above already proved validation passed (a failure throws at
34
+ // module load). Pin the unset optionals to undefined so a future .default()
35
+ // or .min(1) requirement on them is a deliberate change, not drift.
36
+ assert.equal(env.ACCOUNT_LINK_TWITCH_CLIENT_ID, undefined);
37
+ assert.equal(env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET, undefined);
38
+ assert.equal(env.STEAM_WEB_API_KEY, undefined);
39
+ assert.equal(env.ACCOUNT_LINK_ALLOWED_ORIGINS, undefined);
40
+ });