@hogsend/engine 0.64.0 → 0.66.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 (77) 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/battlenet.ts +84 -0
  7. package/src/account-links/epic.ts +87 -0
  8. package/src/account-links/index.ts +15 -0
  9. package/src/account-links/riot.ts +82 -0
  10. package/src/account-links/steam.test.ts +243 -0
  11. package/src/account-links/steam.ts +48 -0
  12. package/src/account-links/twitch.test.ts +157 -0
  13. package/src/account-links/twitch.ts +99 -0
  14. package/src/account-links/xbox.ts +92 -0
  15. package/src/app.ts +9 -1
  16. package/src/container.account-links.env.test.ts +65 -0
  17. package/src/container.account-links.halfenv.test.ts +48 -0
  18. package/src/container.account-links.test.ts +185 -0
  19. package/src/container.ts +120 -0
  20. package/src/env.ts +53 -0
  21. package/src/index.ts +93 -1
  22. package/src/lib/account-link-emit.ts +126 -0
  23. package/src/lib/account-link-events.ts +180 -0
  24. package/src/lib/account-link-hooks.test.ts +158 -0
  25. package/src/lib/account-link-hooks.ts +73 -0
  26. package/src/lib/account-link-ingest.ts +364 -0
  27. package/src/lib/account-link-nonce.test.ts +52 -0
  28. package/src/lib/account-link-nonce.ts +57 -0
  29. package/src/lib/account-link-origins.test.ts +72 -0
  30. package/src/lib/account-link-origins.ts +87 -0
  31. package/src/lib/account-link-pkce.test.ts +91 -0
  32. package/src/lib/account-link-pkce.ts +106 -0
  33. package/src/lib/account-link-provider-registry.test.ts +52 -0
  34. package/src/lib/account-link-provider-registry.ts +61 -0
  35. package/src/lib/account-link-throttle.test.ts +178 -0
  36. package/src/lib/account-link-throttle.ts +130 -0
  37. package/src/lib/account-link-url.ts +85 -0
  38. package/src/lib/account-links-emit.test.ts +525 -0
  39. package/src/lib/account-links-env.test.ts +40 -0
  40. package/src/lib/account-links-from-env.test.ts +187 -0
  41. package/src/lib/account-links-from-env.ts +190 -0
  42. package/src/lib/account-links.ts +1300 -0
  43. package/src/lib/app-secret.ts +34 -0
  44. package/src/lib/connector-actions.test.ts +13 -4
  45. package/src/lib/connector-state.account-link.test.ts +114 -0
  46. package/src/lib/connector-state.ts +48 -3
  47. package/src/lib/contacts.ts +342 -6
  48. package/src/lib/outbound-account-payloads.test.ts +137 -0
  49. package/src/lib/outbound.ts +91 -0
  50. package/src/lib/provider-credentials.ts +19 -5
  51. package/src/lib/snippet.ts +76 -0
  52. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  53. package/src/lib/webhook-signing.ts +18 -1
  54. package/src/routes/accounts/callback.ts +597 -0
  55. package/src/routes/accounts/emit.ts +231 -0
  56. package/src/routes/accounts/import-links.ts +210 -0
  57. package/src/routes/accounts/index.ts +75 -0
  58. package/src/routes/accounts/lookup.ts +177 -0
  59. package/src/routes/accounts/me.ts +215 -0
  60. package/src/routes/accounts/mint.ts +279 -0
  61. package/src/routes/accounts/pages.ts +62 -0
  62. package/src/routes/accounts/resolve.ts +61 -0
  63. package/src/routes/accounts/serialize.ts +96 -0
  64. package/src/routes/accounts/shared.ts +107 -0
  65. package/src/routes/accounts/start.ts +229 -0
  66. package/src/routes/accounts/unlink.ts +98 -0
  67. package/src/routes/admin/agent.ts +2 -0
  68. package/src/routes/admin/api-keys.ts +7 -0
  69. package/src/routes/admin/contacts.ts +38 -2
  70. package/src/routes/connectors/index.ts +17 -0
  71. package/src/routes/contacts/index.ts +8 -0
  72. package/src/routes/index.ts +81 -0
  73. package/src/routes/snippet.test.ts +70 -0
  74. package/src/routes/snippet.ts +58 -0
  75. package/src/testing-barrel.test.ts +74 -0
  76. package/src/testing.ts +17 -0
  77. package/src/workflows/import-contacts.ts +6 -0
@@ -9,6 +9,7 @@ import {
9
9
  emailSends,
10
10
  groupMemberships,
11
11
  journeyStates,
12
+ linkedAccounts,
12
13
  userEvents,
13
14
  } from "@hogsend/db";
14
15
  import {
@@ -25,6 +26,19 @@ import {
25
26
  type SQL,
26
27
  sql,
27
28
  } from "drizzle-orm";
29
+ // The account-link store (PRD 03) is the ONE module allowed to write a
30
+ // `linked_accounts` VERSION — this file only consumes its tx-scoped helpers
31
+ // (the merge fold, the delete leg) plus one version-free contact_id repoint
32
+ // inside `foldLinkedAccounts`. No import cycle: account-links.ts never imports
33
+ // this module.
34
+ import { emitAccountUnlinked } from "./account-link-emit.js";
35
+ import { ingestAccountUnlinked } from "./account-link-ingest.js";
36
+ import {
37
+ type ContactUnlinkFact,
38
+ type LinkOwner,
39
+ unlinkAccountInTx,
40
+ unlinkAccountsForContactInTx,
41
+ } from "./account-links.js";
28
42
  import { createLogger } from "./logger.js";
29
43
 
30
44
  /** Module logger (the house lib idiom — see connector-actions.ts:28). Used only
@@ -140,6 +154,7 @@ export async function collidesWithIdentified(
140
154
  // would fail OPEN there. Keep both legs (PRD 07 re-spec).
141
155
  const rows = await db
142
156
  .select({
157
+ id: contacts.id,
143
158
  externalId: contacts.externalId,
144
159
  email: contacts.email,
145
160
  anonymousId: contacts.anonymousId,
@@ -151,6 +166,19 @@ export async function collidesWithIdentified(
151
166
  eq(contacts.externalId, value),
152
167
  eq(contacts.email, value),
153
168
  eq(contacts.anonymousId, value),
169
+ // THE UUID LEG. A contact holding neither an `external_id` nor an
170
+ // `anonymous_id` — an email-only CRM row, which is the ordinary
171
+ // shape for an imported contact — is keyed on its ROW UUID, and
172
+ // that key LEAVES THE SYSTEM (Hatchet payloads, `hs_t` tokens,
173
+ // webhook payloads), so it is guessable in a way a browser-local
174
+ // anon id is not. Without this leg every caller of this guard is
175
+ // fail-OPEN for exactly those contacts: an unauthenticated surface
176
+ // that accepts an `anonymous_id` will happily file events under a
177
+ // real person's canonical key. `keysAnotherContact` below has
178
+ // carried this leg, and this comment, since PRD 07; this one did
179
+ // not, and the account-link cold `link_failed` screen inherited the
180
+ // hole (verified by reproduction, not inference).
181
+ ...(UUID_REGEX.test(value) ? [eq(contacts.id, value)] : []),
154
182
  ),
155
183
  isNull(contacts.deletedAt),
156
184
  ),
@@ -162,6 +190,9 @@ export async function collidesWithIdentified(
162
190
  // The supplied value is this contact's `email` AND that email is its
163
191
  // canonical key (no external_id) → identified rows are keyed on it. Reject.
164
192
  if (row.email === value && !row.externalId) return true;
193
+ // The supplied value IS this contact's canonical key by uuid fallback
194
+ // (neither string key set) → its history is keyed on it. Reject.
195
+ if (row.id === value && !row.externalId && !row.anonymousId) return true;
165
196
  }
166
197
  return false;
167
198
  }
@@ -1048,6 +1079,48 @@ interface ResolveContactOptions {
1048
1079
  source?: string;
1049
1080
  /** Timestamp paired with {@link source}; defaults to now() at create time. */
1050
1081
  sourcedAt?: Date;
1082
+ /**
1083
+ * JOURNEY-PLANE opt-out for the merge fold's `account.unlinked` re-ingest
1084
+ * (PRD 08 T5). Default `true`: an organic resolve (a live `/v1/events`
1085
+ * ingest that happens to fold two contacts) SHOULD enrol journeys on the
1086
+ * `account.unlinked` a merge produced, exactly as a direct unlink would.
1087
+ *
1088
+ * A BULK importer sets `false`. A CSV import is a statement about the PAST,
1089
+ * and one job can merge many rows whose losers each held a live linked
1090
+ * account — so left on, a single import would fan out one journey enrolment
1091
+ * per such row (the same amplification class the `/v1/accounts/import`
1092
+ * route gates with its own `enrollJourneys`). This suppresses ONLY the
1093
+ * journey plane; the outbound `account.unlinked` webhook still fires, so the
1094
+ * customer's mirror converges whether or not a journey ran.
1095
+ */
1096
+ enrollJourneys?: boolean;
1097
+ }
1098
+
1099
+ /**
1100
+ * One `linked_accounts` soft-unlink the merge fold performed (PRD 04 T2): the
1101
+ * loser's live singleton link lost the arbitration to the survivor's. PRD 08
1102
+ * emits one `account.unlinked` per entry AFTER the resolve transaction
1103
+ * commits; nothing is emitted here (DECISIONS §8). `version` is that pair's
1104
+ * OWN next version, a STRING end to end (DECISIONS §5.1).
1105
+ */
1106
+ export interface MergedLinkUnlink {
1107
+ provider: string;
1108
+ providerUserId: string;
1109
+ version: string;
1110
+ /** The loser contact that held the soft-unlinked row. */
1111
+ contactId: string;
1112
+ reason: "relinked";
1113
+ /**
1114
+ * The owner facts the store read INSIDE the fold's transaction (DECISIONS
1115
+ * §15.5). PRD 08's payload carries `userId` (`contactKey()`) and `email`,
1116
+ * and neither lives on `linked_accounts` — without carrying them here the
1117
+ * post-commit emit would either ship two nulls or bolt a second contacts
1118
+ * read on after the lock released, which is no longer the state that
1119
+ * committed. `unlinkAccountInTx`'s `unlinked` arm returns it
1120
+ * (`account-links.ts:260`) and the fold only narrows to that arm, so the
1121
+ * fold copies it straight across — no extra query.
1122
+ */
1123
+ owner: LinkOwner;
1051
1124
  }
1052
1125
 
1053
1126
  /**
@@ -1065,6 +1138,9 @@ interface ResolveContactSharedResult {
1065
1138
  merged: boolean;
1066
1139
  mergedKeys?: string[];
1067
1140
  mergedIdentifiedKeys?: string[];
1141
+ /** PRD 04: link soft-unlinks a collide-MERGE performed (see
1142
+ * {@link MergedLinkUnlink}). Absent when the resolve unlinked nothing. */
1143
+ linkUnlinks?: MergedLinkUnlink[];
1068
1144
  }
1069
1145
 
1070
1146
  /**
@@ -1200,7 +1276,7 @@ async function resolveContactShared(
1200
1276
  const patch = contactProperties ?? {};
1201
1277
  const hasPatch = Object.keys(patch).length > 0;
1202
1278
 
1203
- return db.transaction(async (tx) => {
1279
+ const committed = await db.transaction(async (tx) => {
1204
1280
  // (−1) ENGINE-INTERNAL PROVENANCE PIN. A uuid-shaped `contactId` from a
1205
1281
  // trusted internal re-emit pins resolution to that exact row (no value-key
1206
1282
  // probe, no mint), so a contact's own canonical key round-tripping back as a
@@ -1380,7 +1456,7 @@ async function resolveContactShared(
1380
1456
  if (clamped) {
1381
1457
  throw new PublishableAnonymousMergeError();
1382
1458
  }
1383
- const { id, resolvedKey, mergedKeys, mergedIdentifiedKeys } =
1459
+ const { id, resolvedKey, mergedKeys, mergedIdentifiedKeys, linkUnlinks } =
1384
1460
  await mergeContacts(tx, candidates, {
1385
1461
  userId,
1386
1462
  email,
@@ -1399,8 +1475,59 @@ async function resolveContactShared(
1399
1475
  merged: true,
1400
1476
  mergedKeys,
1401
1477
  mergedIdentifiedKeys,
1478
+ linkUnlinks,
1402
1479
  };
1403
1480
  });
1481
+
1482
+ // One widening step: the callback's inferred return is a UNION of per-arm
1483
+ // object literals and only the merge arm declares `linkUnlinks`, so the
1484
+ // field is unreadable off the raw union. This is the declared result type
1485
+ // the old `return db.transaction(...)` was checked against — no cast, no
1486
+ // behaviour change.
1487
+ const resolved: ResolveContactSharedResult = committed;
1488
+
1489
+ // THE MERGE'S `account.unlinked` EMIT (PRD 08 T3), and the reason this
1490
+ // function `await`s its own transaction instead of returning it.
1491
+ //
1492
+ // `foldLinkedAccounts` produced these facts INSIDE the transaction above, so
1493
+ // it cannot emit them itself: a merge that rolled back after the fold must
1494
+ // never have announced an unlink that never happened. Here we are strictly
1495
+ // past the COMMIT — the transaction promise has resolved, so a rollback took
1496
+ // the `throw` path and never reached this line. This is the commit/intent
1497
+ // layer DECISIONS §8 names, and it is ONE owner for every call site of
1498
+ // `resolveOrCreateContact` / `resolveContactNoCreate`.
1499
+ //
1500
+ // Only the singleton-COLLISION soft-unlinks are here. The repoint that moves
1501
+ // the loser's surviving links to the survivor is deliberately silent — see
1502
+ // the note on step 4 of `foldLinkedAccounts`.
1503
+ if (resolved.linkUnlinks && resolved.linkUnlinks.length > 0) {
1504
+ emitAccountUnlinked(db, resolved.linkUnlinks);
1505
+ // THE JOURNEY PLANE, beside the outbound one (PRD 08 T5). TWO DIFFERENT
1506
+ // PLANES: `emitAccountUnlinked` writes a `webhook_deliveries` row for the
1507
+ // CUSTOMER'S subscriber; this writes `user_events` + pushes to Hatchet so
1508
+ // a journey can trigger on `account.unlinked`. Neither may be collapsed
1509
+ // into the other — see the header of `lib/account-link-ingest.ts`.
1510
+ //
1511
+ // Yes, this re-enters `ingestEvent`, which is what called this resolver.
1512
+ // It is bounded at one hop and cannot loop: `fact.owner.contactId` is the
1513
+ // LOSER row (soft-deleted by the merge just above), so the re-ingest takes
1514
+ // the provenance-pin branch, which follows the merge alias to the SURVIVOR
1515
+ // and returns without probing value keys — so it can neither merge again
1516
+ // nor produce a second `linkUnlinks`. It is also fire-and-forget and
1517
+ // strictly post-commit, so it cannot slow or fail the resolve.
1518
+ //
1519
+ // A BULK importer opts OUT here (`enrollJourneys: false`): one job can fold
1520
+ // many rows, and left on it would fan out one enrolment per merged row that
1521
+ // dropped a live link. The outbound `emitAccountUnlinked` above is
1522
+ // deliberately NOT gated — the customer's mirror converges regardless.
1523
+ if (opts.enrollJourneys !== false) {
1524
+ for (const fact of resolved.linkUnlinks) {
1525
+ ingestAccountUnlinked(db, fact);
1526
+ }
1527
+ }
1528
+ }
1529
+
1530
+ return resolved;
1404
1531
  }
1405
1532
 
1406
1533
  /**
@@ -1446,6 +1573,13 @@ export async function resolveOrCreateContact(
1446
1573
  * `identity.merge.residual_twin` for observability. Never aliased.
1447
1574
  */
1448
1575
  mergedIdentifiedKeys?: string[];
1576
+ /**
1577
+ * PRD 04: the `linked_accounts` soft-unlinks a collide-MERGE performed
1578
+ * (loser's live singleton link lost the arbitration — see
1579
+ * {@link MergedLinkUnlink}). PRD 08 emits one `account.unlinked` per entry
1580
+ * post-commit. Absent when the resolve unlinked nothing.
1581
+ */
1582
+ linkUnlinks?: MergedLinkUnlink[];
1449
1583
  }> {
1450
1584
  // PRD 06: this entry point is create-on-miss BY CONTRACT — honouring a
1451
1585
  // refuse-on-miss policy here would make the refusal arm reachable and force
@@ -1501,6 +1635,8 @@ export async function resolveContactNoCreate(
1501
1635
  merged: boolean;
1502
1636
  mergedKeys?: string[];
1503
1637
  mergedIdentifiedKeys?: string[];
1638
+ /** As {@link resolveOrCreateContact} (PRD 04). */
1639
+ linkUnlinks?: MergedLinkUnlink[];
1504
1640
  }> {
1505
1641
  // Mirror the shared body's normalization so the precondition reads the same
1506
1642
  // keys resolution will (a whitespace-only `userId` is not a supplied key).
@@ -1570,6 +1706,9 @@ async function fillInLink(
1570
1706
  resolvedKey: string;
1571
1707
  mergedKeys?: string[];
1572
1708
  mergedIdentifiedKeys?: string[];
1709
+ /** Shape parity with {@link mergeContacts} (PRD 04); a fill-in-link never
1710
+ * touches `linked_accounts`, so this arm never sets it. */
1711
+ linkUnlinks?: MergedLinkUnlink[];
1573
1712
  }> {
1574
1713
  const set: Record<string, unknown> = {
1575
1714
  lastSeenAt: new Date(),
@@ -1781,6 +1920,7 @@ async function mergeContacts(
1781
1920
  resolvedKey: string;
1782
1921
  mergedKeys?: string[];
1783
1922
  mergedIdentifiedKeys?: string[];
1923
+ linkUnlinks?: MergedLinkUnlink[];
1784
1924
  }> {
1785
1925
  const { survivor, losers } = pickSurvivor(candidates);
1786
1926
  const survivorKey = contactKey(survivor);
@@ -1791,6 +1931,9 @@ async function mergeContacts(
1791
1931
  // merge on the safe path — it is recorded as the twin residual, NEVER aliased.
1792
1932
  const safeLoserKeys: string[] = [];
1793
1933
  const identifiedLoserKeys: string[] = [];
1934
+ // PRD 04: every `linked_accounts` soft-unlink the fold performs, returned so
1935
+ // PRD 08 can emit `account.unlinked` post-commit. Never emitted in here.
1936
+ const linkMutations: MergedLinkUnlink[] = [];
1794
1937
 
1795
1938
  for (const loser of losers) {
1796
1939
  // The id is the last-resort key for a loser that has neither external nor
@@ -1935,6 +2078,13 @@ async function mergeContacts(
1935
2078
  // when BOTH already belong to the same group, so fold-then-rewrite.
1936
2079
  await foldGroupMemberships(tx, survivor.id, loser.id);
1937
2080
 
2081
+ // (vi-d) linked_accounts FOLD — the same stranding failure as (vi-c), with
2082
+ // an extra wrinkle: the singleton partial-unique index forbids a blind
2083
+ // repoint. See foldLinkedAccounts.
2084
+ linkMutations.push(
2085
+ ...(await foldLinkedAccounts(tx, survivor.id, loser.id)),
2086
+ );
2087
+
1938
2088
  // (ix) RECORD aliases for each loser key → survivor.
1939
2089
  await recordMergeAliases(tx, survivor.id, loser);
1940
2090
  }
@@ -2122,6 +2272,7 @@ async function mergeContacts(
2122
2272
  mergedKeys: safeLoserKeys.length > 0 ? safeLoserKeys : undefined,
2123
2273
  mergedIdentifiedKeys:
2124
2274
  identifiedLoserKeys.length > 0 ? identifiedLoserKeys : undefined,
2275
+ linkUnlinks: linkMutations.length > 0 ? linkMutations : undefined,
2125
2276
  };
2126
2277
  }
2127
2278
 
@@ -2392,6 +2543,125 @@ async function foldGroupMemberships(
2392
2543
  .where(eq(groupMemberships.contactId, loserId));
2393
2544
  }
2394
2545
 
2546
+ /**
2547
+ * linked_accounts FOLD (vi-d, PRD 04 T2).
2548
+ * `linked_accounts_contact_provider_singleton_idx` is a PARTIAL unique index
2549
+ * on (contact_id, provider) WHERE unlinked_at IS NULL AND singleton, so a
2550
+ * blind repoint raises 23505 whenever survivor and loser both hold a live
2551
+ * singleton link for the same provider. Resolution: the survivor's row stays
2552
+ * (the survivor is what `pickSurvivor` considers primary, consistent with
2553
+ * every other fold), the loser's is SOFT-unlinked with reason "relinked"
2554
+ * through the store's versioning helper (never raw SQL — an unlink whose
2555
+ * version does not advance is discarded forever by the consumer's monotonic
2556
+ * guard, DECISIONS §5.3), and everything else repoints.
2557
+ *
2558
+ * `multiple: true` links (singleton = false) and already-unlinked history rows
2559
+ * need no arbitration: they are outside the partial index, so they just move.
2560
+ *
2561
+ * Known lock-order hazard, stated rather than hidden (PRD 04): the merge
2562
+ * transaction already holds contact-key advisory locks (taken at the top of
2563
+ * the resolve tx) and only NOW takes pair locks; the store takes pair locks
2564
+ * and then touches `linked_accounts` rows belonging to contacts. The two
2565
+ * never take the SAME two advisory locks in opposite orders, so there is no
2566
+ * advisory-lock cycle, but a ROW-lock cycle between a merge and a concurrent
2567
+ * link on the same rows is possible in principle — Postgres detects it and
2568
+ * aborts one side with 40P01, which surfaces as a failed resolve/link the
2569
+ * caller retries. Mitigation, not elimination: this fold runs as LATE as
2570
+ * possible in the merge (immediately before `recordMergeAliases`) so the
2571
+ * window is a few statements wide. Do not attempt a global lock ordering
2572
+ * across the two subsystems.
2573
+ */
2574
+ async function foldLinkedAccounts(
2575
+ tx: Tx,
2576
+ survivorId: string,
2577
+ loserId: string,
2578
+ ): Promise<MergedLinkUnlink[]> {
2579
+ const facts: MergedLinkUnlink[] = [];
2580
+
2581
+ // 1. The survivor's occupied singleton providers.
2582
+ const survivorSingletons = await tx
2583
+ .select({ provider: linkedAccounts.provider })
2584
+ .from(linkedAccounts)
2585
+ .where(
2586
+ and(
2587
+ eq(linkedAccounts.contactId, survivorId),
2588
+ isNull(linkedAccounts.unlinkedAt),
2589
+ eq(linkedAccounts.singleton, true),
2590
+ ),
2591
+ );
2592
+ const occupied = survivorSingletons.map((r) => r.provider);
2593
+
2594
+ if (occupied.length > 0) {
2595
+ // 2. The collisions: the loser's live singleton rows for those providers.
2596
+ const collisions = await tx
2597
+ .select({
2598
+ id: linkedAccounts.id,
2599
+ provider: linkedAccounts.provider,
2600
+ providerUserId: linkedAccounts.providerUserId,
2601
+ })
2602
+ .from(linkedAccounts)
2603
+ .where(
2604
+ and(
2605
+ eq(linkedAccounts.contactId, loserId),
2606
+ isNull(linkedAccounts.unlinkedAt),
2607
+ eq(linkedAccounts.singleton, true),
2608
+ inArray(linkedAccounts.provider, occupied),
2609
+ ),
2610
+ );
2611
+
2612
+ // 3. Soft-unlink each collision at that pair's OWN next version, through
2613
+ // the store (PRD 03's tx-scoped entry point — `contacts.ts` never writes
2614
+ // a version).
2615
+ for (const row of collisions) {
2616
+ const outcome = await unlinkAccountInTx(tx, {
2617
+ rowId: row.id,
2618
+ provider: row.provider,
2619
+ providerUserId: row.providerUserId,
2620
+ reason: "relinked",
2621
+ });
2622
+ // The store's result is a UNION, not a bare success: a `not_found`
2623
+ // means the row went stale between our read and the pair lock
2624
+ // (unlinked/relinked by a concurrent commit) — nothing was mutated, so
2625
+ // recording a fact here would make PRD 08 emit a phantom
2626
+ // `account.unlinked`. Skip it; step 4 still repoints whatever remains.
2627
+ if (outcome.status !== "unlinked") continue;
2628
+ facts.push({
2629
+ provider: row.provider,
2630
+ providerUserId: row.providerUserId,
2631
+ version: outcome.version,
2632
+ contactId: loserId,
2633
+ reason: "relinked",
2634
+ // The `unlinked` arm the narrowing above just proved (the join to
2635
+ // `contacts` the store did under the pair lock). Copied, never
2636
+ // re-read: PRD 08's payload needs `userId`/`email`, and a second
2637
+ // lookup at emit time is no longer the state that committed.
2638
+ owner: outcome.owner,
2639
+ });
2640
+ }
2641
+ }
2642
+
2643
+ // 4. Repoint EVERYTHING remaining — live, historical, and the rows step 3
2644
+ // just unlinked (an unlinked row is outside every partial index, so it
2645
+ // moves without conflict; leaving it behind would strand history on the
2646
+ // soft-deleted loser). A version-free ownership repoint, not a state
2647
+ // transition: version/linked_at/method/tokens are preserved.
2648
+ //
2649
+ // DELIBERATELY NOT AN EMIT POINT (PRD 08). A reader looking for the
2650
+ // `account.unlinked` that step 3 produces will look here too: moving a link
2651
+ // to the merge's survivor is not a new identity fact, it allocates no
2652
+ // version, and emitting from here would double-report every merge. Step 3's
2653
+ // soft-unlink is the different thing that IS emitted — it really did end a
2654
+ // link, at its own new version — and even that emit does not happen here:
2655
+ // this whole function runs INSIDE the merge transaction, so the emit lives
2656
+ // post-commit in `resolveContactShared` (DECISIONS §8, commit/intent layer).
2657
+ await tx
2658
+ .update(linkedAccounts)
2659
+ .set({ contactId: survivorId, updatedAt: new Date() })
2660
+ .where(eq(linkedAccounts.contactId, loserId));
2661
+
2662
+ return facts;
2663
+ }
2664
+
2395
2665
  /**
2396
2666
  * email_preferences FOLD (risk 6 — suppression/unsubscribe must NEVER be lost).
2397
2667
  * For each of the loser's pref rows, fold it into whatever currently sits at
@@ -2571,6 +2841,15 @@ async function adoptOrphanHistory(
2571
2841
  await foldEmailPreferences(tx, [fromKey], ownKey, row.id, undefined, {
2572
2842
  stampOnly: true,
2573
2843
  });
2844
+
2845
+ // linked_accounts is deliberately ABSENT here, and that is not an omission.
2846
+ // This function stamps rows that sat under a text key with NO owner
2847
+ // (`WHERE user_id = :fromKey AND contact_id IS NULL`). `linked_accounts` has
2848
+ // no `user_id` column and its `contact_id` is NOT NULL: a link row can only
2849
+ // be created from a callback where the contact is already bound (DECISIONS
2850
+ // §7), so an orphan link row is unrepresentable. The merge path DOES carry
2851
+ // links — see foldLinkedAccounts. Do not "fix" this by adding a statement;
2852
+ // add a test instead if you doubt it.
2574
2853
  }
2575
2854
 
2576
2855
  /** RECORD a contact_aliases row per loser key → survivor (reason 'merge'). */
@@ -2808,6 +3087,8 @@ export async function upsertContact(opts: {
2808
3087
  mergedKeys?: string[];
2809
3088
  /** §5.3 MF-2: already-identified loser keys (twin residual); never aliased. */
2810
3089
  mergedIdentifiedKeys?: string[];
3090
+ /** As {@link resolveOrCreateContact} (PRD 04). */
3091
+ linkUnlinks?: MergedLinkUnlink[];
2811
3092
  }> {
2812
3093
  return resolveOrCreateContact({
2813
3094
  db: opts.db,
@@ -2879,6 +3160,13 @@ export async function softDeleteContact(opts: {
2879
3160
  id?: string;
2880
3161
  externalId?: string | null;
2881
3162
  email?: string | null;
3163
+ /**
3164
+ * PRD 04 T5 (DECISIONS §15.3): one fact per live `linked_accounts` row this
3165
+ * delete soft-unlinked (token blobs hard-deleted alongside). PRD 08 emits
3166
+ * one `account.unlinked` per entry post-commit so mirrors converge. Absent
3167
+ * when the deleted contact(s) held no live links.
3168
+ */
3169
+ linkUnlinks?: ContactUnlinkFact[];
2882
3170
  }> {
2883
3171
  const { db } = opts;
2884
3172
  const email = opts.email ? normalizeEmail(opts.email) : undefined;
@@ -2919,6 +3207,22 @@ export async function softDeleteContact(opts: {
2919
3207
  }
2920
3208
  if (targetIds.size === 0) return undefined;
2921
3209
 
3210
+ // PRD 04 T5 (DECISIONS §15.3): soft-unlink every live link the target(s)
3211
+ // hold, in this SAME transaction, each at its own pair's next version
3212
+ // through the store's tx-scoped helper — a live row outliving its owner
3213
+ // locks the `(provider, provider_user_id)` pair forever, so an erased
3214
+ // player could never relink their own account under onConflict "reject".
3215
+ // Tokens are hard-deleted alongside. Idempotent by construction: a target
3216
+ // with no live links contributes nothing.
3217
+ const linkUnlinks: ContactUnlinkFact[] = [];
3218
+ for (const targetId of targetIds) {
3219
+ linkUnlinks.push(
3220
+ ...(await unlinkAccountsForContactInTx(tx, targetId, {
3221
+ reason: "api",
3222
+ })),
3223
+ );
3224
+ }
3225
+
2922
3226
  const updated = await tx
2923
3227
  .update(contacts)
2924
3228
  .set({ deletedAt: new Date(), updatedAt: new Date() })
@@ -2935,16 +3239,48 @@ export async function softDeleteContact(opts: {
2935
3239
  for (const deleted of updated) {
2936
3240
  await deleteIdentityAliasesForContact(tx, deleted.id);
2937
3241
  }
2938
- return updated[0];
3242
+ return updated[0] ? { row: updated[0], linkUnlinks } : undefined;
2939
3243
  });
2940
3244
 
2941
3245
  if (!row) return { deleted: false };
2942
3246
 
3247
+ // THE CONTACT-DELETION `account.unlinked` EMIT (PRD 08 T3, DECISIONS §15.3),
3248
+ // one per live link, `reason: "api"`. Post-commit: the transaction above has
3249
+ // resolved, so a rollback never reaches this line.
3250
+ //
3251
+ // It lives HERE rather than at the callers because `softDeleteContact` has
3252
+ // THREE of them — `routes/contacts/index.ts`'s DELETE, the agent tool's
3253
+ // `delete_contact` arm, and any consumer-built deletion flow — and each one
3254
+ // that forgot would leave a customer's mirror recording a deleted player as
3255
+ // still linked, forever. The facts stay on the return value as well; that is
3256
+ // the reporting channel (and what the delete-leg tests assert), not a second
3257
+ // emit point. The admin erasure route runs its OWN transaction and therefore
3258
+ // owns its own post-commit emit (`routes/admin/contacts.ts`).
3259
+ emitAccountUnlinked(db, row.linkUnlinks);
3260
+
3261
+ // NO journey-plane re-ingest here, deliberately (PRD 08 T5). Every other
3262
+ // `account.unlinked` site gets one; this one must not, for two independent
3263
+ // reasons:
3264
+ //
3265
+ // 1. The subject was just ERASED. Filing a fresh `user_events` row for a
3266
+ // contact that was soft-deleted microseconds ago — and enrolling them in
3267
+ // a journey that would then try to reach them — is the opposite of what
3268
+ // a deletion means.
3269
+ // 2. There is no safe key anyway. The pin (`fact.owner.contactId`) resolves
3270
+ // to a soft-deleted row with no merge alias to follow, so the re-ingest
3271
+ // would be dropped as provenance-lost; and the only alternative,
3272
+ // `owner.userId`, is a value key that `resolveOrCreateContact` would
3273
+ // MINT a fresh contact for — RESURRECTING the row the caller just
3274
+ // erased.
3275
+ //
3276
+ // The customer's mirror still converges: that is what the emit above is for.
3277
+
2943
3278
  return {
2944
3279
  deleted: true,
2945
- id: row.id,
2946
- externalId: row.externalId,
2947
- email: row.email,
3280
+ id: row.row.id,
3281
+ externalId: row.row.externalId,
3282
+ email: row.row.email,
3283
+ linkUnlinks: row.linkUnlinks.length > 0 ? row.linkUnlinks : undefined,
2948
3284
  };
2949
3285
  }
2950
3286
 
@@ -0,0 +1,137 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import type { OutboundPayloads } from "./outbound.js";
4
+
5
+ /**
6
+ * The `account.*` outbound payload shapes (PRD 08 T2).
7
+ *
8
+ * The load-bearing assertion here is not the field list — it is that `version`
9
+ * crosses the wire as a decimal STRING. `linked_accounts.version` is a Postgres
10
+ * `bigint` (DECISIONS §5.1) and the whole consistency contract is a consumer's
11
+ * `incoming.version > stored.version` guard, so a version that has been through
12
+ * a JS `number` at ANY point in the producer is silently wrong above
13
+ * `Number.MAX_SAFE_INTEGER` and breaks the guard in exactly the case it exists
14
+ * for. A type-only test cannot see a `Number(row.version)` in a serializer, so
15
+ * the last two cases are runtime assertions on a BUILT payload.
16
+ */
17
+
18
+ /** The store's row shape, narrowed to what a payload build reads. */
19
+ interface FakeLinkRow {
20
+ provider: string;
21
+ providerUserId: string;
22
+ contactId: string;
23
+ version: bigint;
24
+ }
25
+
26
+ /** Stand-in for the T3 builder: the serialization under test is `String()`. */
27
+ function buildLinkedPayload(
28
+ row: FakeLinkRow,
29
+ ): OutboundPayloads["account.linked"] {
30
+ return {
31
+ state: "linked",
32
+ provider: row.provider,
33
+ providerUserId: row.providerUserId,
34
+ contactId: row.contactId,
35
+ userId: "usr_1",
36
+ email: "player@example.com",
37
+ username: "player",
38
+ method: "oauth",
39
+ relink: false,
40
+ version: String(row.version),
41
+ at: "2026-08-14T00:00:00.000Z",
42
+ };
43
+ }
44
+
45
+ test("an account.linked payload type-checks with every documented field", () => {
46
+ const linked: OutboundPayloads["account.linked"] = {
47
+ state: "linked",
48
+ provider: "steam",
49
+ providerUserId: "76561198000000000",
50
+ contactId: "ct_1",
51
+ userId: "usr_1",
52
+ email: "player@example.com",
53
+ username: "player",
54
+ method: "oauth",
55
+ relink: true,
56
+ version: "3",
57
+ at: "2026-08-14T00:00:00.000Z",
58
+ };
59
+ const unlinked: OutboundPayloads["account.unlinked"] = {
60
+ state: "unlinked",
61
+ provider: "steam",
62
+ providerUserId: "76561198000000000",
63
+ contactId: "ct_1",
64
+ userId: null,
65
+ email: null,
66
+ reason: "relinked",
67
+ version: "2",
68
+ at: "2026-08-14T00:00:00.000Z",
69
+ };
70
+ const failed: OutboundPayloads["account.link_failed"] = {
71
+ provider: "steam",
72
+ reason: "state_invalid",
73
+ contactId: null,
74
+ at: "2026-08-14T00:00:00.000Z",
75
+ };
76
+
77
+ assert.deepEqual(Object.keys(linked).sort(), [
78
+ "at",
79
+ "contactId",
80
+ "email",
81
+ "method",
82
+ "provider",
83
+ "providerUserId",
84
+ "relink",
85
+ "state",
86
+ "userId",
87
+ "username",
88
+ "version",
89
+ ]);
90
+ assert.deepEqual(Object.keys(unlinked).sort(), [
91
+ "at",
92
+ "contactId",
93
+ "email",
94
+ "provider",
95
+ "providerUserId",
96
+ "reason",
97
+ "state",
98
+ "userId",
99
+ "version",
100
+ ]);
101
+ // `account.link_failed` carries NO version and NO state: nothing mutated.
102
+ assert.deepEqual(Object.keys(failed).sort(), [
103
+ "at",
104
+ "contactId",
105
+ "provider",
106
+ "reason",
107
+ ]);
108
+ });
109
+
110
+ test("version serializes as a string, not a number", () => {
111
+ const payload = buildLinkedPayload({
112
+ provider: "steam",
113
+ providerUserId: "76561198000000000",
114
+ contactId: "ct_1",
115
+ version: 7n,
116
+ });
117
+ assert.equal(typeof payload.version, "string");
118
+ assert.equal(payload.version, "7");
119
+ });
120
+
121
+ test("a version above Number.MAX_SAFE_INTEGER round-trips through the payload without loss", () => {
122
+ // ODD and above 2^53: every EVEN integer below 2^54 is exactly representable
123
+ // in float64, so an assertion on an even value passes whether or not the code
124
+ // rounds (DECISIONS §5.1). 9007199254740993 rounds to ...992 through a JS
125
+ // number, so this assertion is non-vacuous.
126
+ const payload = buildLinkedPayload({
127
+ provider: "steam",
128
+ providerUserId: "76561198000000000",
129
+ contactId: "ct_1",
130
+ version: 9007199254740993n,
131
+ });
132
+ const roundTripped = JSON.parse(
133
+ JSON.stringify(payload),
134
+ ) as OutboundPayloads["account.linked"];
135
+ assert.equal(roundTripped.version, "9007199254740993");
136
+ assert.notEqual(String(Number(payload.version)), payload.version);
137
+ });