@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
@@ -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
  }
@@ -1050,6 +1081,33 @@ interface ResolveContactOptions {
1050
1081
  sourcedAt?: Date;
1051
1082
  }
1052
1083
 
1084
+ /**
1085
+ * One `linked_accounts` soft-unlink the merge fold performed (PRD 04 T2): the
1086
+ * loser's live singleton link lost the arbitration to the survivor's. PRD 08
1087
+ * emits one `account.unlinked` per entry AFTER the resolve transaction
1088
+ * commits; nothing is emitted here (DECISIONS §8). `version` is that pair's
1089
+ * OWN next version, a STRING end to end (DECISIONS §5.1).
1090
+ */
1091
+ export interface MergedLinkUnlink {
1092
+ provider: string;
1093
+ providerUserId: string;
1094
+ version: string;
1095
+ /** The loser contact that held the soft-unlinked row. */
1096
+ contactId: string;
1097
+ reason: "relinked";
1098
+ /**
1099
+ * The owner facts the store read INSIDE the fold's transaction (DECISIONS
1100
+ * §15.5). PRD 08's payload carries `userId` (`contactKey()`) and `email`,
1101
+ * and neither lives on `linked_accounts` — without carrying them here the
1102
+ * post-commit emit would either ship two nulls or bolt a second contacts
1103
+ * read on after the lock released, which is no longer the state that
1104
+ * committed. `unlinkAccountInTx`'s `unlinked` arm returns it
1105
+ * (`account-links.ts:260`) and the fold only narrows to that arm, so the
1106
+ * fold copies it straight across — no extra query.
1107
+ */
1108
+ owner: LinkOwner;
1109
+ }
1110
+
1053
1111
  /**
1054
1112
  * The shared implementation's result. Identical to
1055
1113
  * {@link resolveOrCreateContact}'s (documented there) EXCEPT that `id` is
@@ -1065,6 +1123,9 @@ interface ResolveContactSharedResult {
1065
1123
  merged: boolean;
1066
1124
  mergedKeys?: string[];
1067
1125
  mergedIdentifiedKeys?: string[];
1126
+ /** PRD 04: link soft-unlinks a collide-MERGE performed (see
1127
+ * {@link MergedLinkUnlink}). Absent when the resolve unlinked nothing. */
1128
+ linkUnlinks?: MergedLinkUnlink[];
1068
1129
  }
1069
1130
 
1070
1131
  /**
@@ -1200,7 +1261,7 @@ async function resolveContactShared(
1200
1261
  const patch = contactProperties ?? {};
1201
1262
  const hasPatch = Object.keys(patch).length > 0;
1202
1263
 
1203
- return db.transaction(async (tx) => {
1264
+ const committed = await db.transaction(async (tx) => {
1204
1265
  // (−1) ENGINE-INTERNAL PROVENANCE PIN. A uuid-shaped `contactId` from a
1205
1266
  // trusted internal re-emit pins resolution to that exact row (no value-key
1206
1267
  // probe, no mint), so a contact's own canonical key round-tripping back as a
@@ -1380,7 +1441,7 @@ async function resolveContactShared(
1380
1441
  if (clamped) {
1381
1442
  throw new PublishableAnonymousMergeError();
1382
1443
  }
1383
- const { id, resolvedKey, mergedKeys, mergedIdentifiedKeys } =
1444
+ const { id, resolvedKey, mergedKeys, mergedIdentifiedKeys, linkUnlinks } =
1384
1445
  await mergeContacts(tx, candidates, {
1385
1446
  userId,
1386
1447
  email,
@@ -1399,8 +1460,52 @@ async function resolveContactShared(
1399
1460
  merged: true,
1400
1461
  mergedKeys,
1401
1462
  mergedIdentifiedKeys,
1463
+ linkUnlinks,
1402
1464
  };
1403
1465
  });
1466
+
1467
+ // One widening step: the callback's inferred return is a UNION of per-arm
1468
+ // object literals and only the merge arm declares `linkUnlinks`, so the
1469
+ // field is unreadable off the raw union. This is the declared result type
1470
+ // the old `return db.transaction(...)` was checked against — no cast, no
1471
+ // behaviour change.
1472
+ const resolved: ResolveContactSharedResult = committed;
1473
+
1474
+ // THE MERGE'S `account.unlinked` EMIT (PRD 08 T3), and the reason this
1475
+ // function `await`s its own transaction instead of returning it.
1476
+ //
1477
+ // `foldLinkedAccounts` produced these facts INSIDE the transaction above, so
1478
+ // it cannot emit them itself: a merge that rolled back after the fold must
1479
+ // never have announced an unlink that never happened. Here we are strictly
1480
+ // past the COMMIT — the transaction promise has resolved, so a rollback took
1481
+ // the `throw` path and never reached this line. This is the commit/intent
1482
+ // layer DECISIONS §8 names, and it is ONE owner for every call site of
1483
+ // `resolveOrCreateContact` / `resolveContactNoCreate`.
1484
+ //
1485
+ // Only the singleton-COLLISION soft-unlinks are here. The repoint that moves
1486
+ // the loser's surviving links to the survivor is deliberately silent — see
1487
+ // the note on step 4 of `foldLinkedAccounts`.
1488
+ if (resolved.linkUnlinks && resolved.linkUnlinks.length > 0) {
1489
+ emitAccountUnlinked(db, resolved.linkUnlinks);
1490
+ // THE JOURNEY PLANE, beside the outbound one (PRD 08 T5). TWO DIFFERENT
1491
+ // PLANES: `emitAccountUnlinked` writes a `webhook_deliveries` row for the
1492
+ // CUSTOMER'S subscriber; this writes `user_events` + pushes to Hatchet so
1493
+ // a journey can trigger on `account.unlinked`. Neither may be collapsed
1494
+ // into the other — see the header of `lib/account-link-ingest.ts`.
1495
+ //
1496
+ // Yes, this re-enters `ingestEvent`, which is what called this resolver.
1497
+ // It is bounded at one hop and cannot loop: `fact.owner.contactId` is the
1498
+ // LOSER row (soft-deleted by the merge just above), so the re-ingest takes
1499
+ // the provenance-pin branch, which follows the merge alias to the SURVIVOR
1500
+ // and returns without probing value keys — so it can neither merge again
1501
+ // nor produce a second `linkUnlinks`. It is also fire-and-forget and
1502
+ // strictly post-commit, so it cannot slow or fail the resolve.
1503
+ for (const fact of resolved.linkUnlinks) {
1504
+ ingestAccountUnlinked(db, fact);
1505
+ }
1506
+ }
1507
+
1508
+ return resolved;
1404
1509
  }
1405
1510
 
1406
1511
  /**
@@ -1446,6 +1551,13 @@ export async function resolveOrCreateContact(
1446
1551
  * `identity.merge.residual_twin` for observability. Never aliased.
1447
1552
  */
1448
1553
  mergedIdentifiedKeys?: string[];
1554
+ /**
1555
+ * PRD 04: the `linked_accounts` soft-unlinks a collide-MERGE performed
1556
+ * (loser's live singleton link lost the arbitration — see
1557
+ * {@link MergedLinkUnlink}). PRD 08 emits one `account.unlinked` per entry
1558
+ * post-commit. Absent when the resolve unlinked nothing.
1559
+ */
1560
+ linkUnlinks?: MergedLinkUnlink[];
1449
1561
  }> {
1450
1562
  // PRD 06: this entry point is create-on-miss BY CONTRACT — honouring a
1451
1563
  // refuse-on-miss policy here would make the refusal arm reachable and force
@@ -1501,6 +1613,8 @@ export async function resolveContactNoCreate(
1501
1613
  merged: boolean;
1502
1614
  mergedKeys?: string[];
1503
1615
  mergedIdentifiedKeys?: string[];
1616
+ /** As {@link resolveOrCreateContact} (PRD 04). */
1617
+ linkUnlinks?: MergedLinkUnlink[];
1504
1618
  }> {
1505
1619
  // Mirror the shared body's normalization so the precondition reads the same
1506
1620
  // keys resolution will (a whitespace-only `userId` is not a supplied key).
@@ -1570,6 +1684,9 @@ async function fillInLink(
1570
1684
  resolvedKey: string;
1571
1685
  mergedKeys?: string[];
1572
1686
  mergedIdentifiedKeys?: string[];
1687
+ /** Shape parity with {@link mergeContacts} (PRD 04); a fill-in-link never
1688
+ * touches `linked_accounts`, so this arm never sets it. */
1689
+ linkUnlinks?: MergedLinkUnlink[];
1573
1690
  }> {
1574
1691
  const set: Record<string, unknown> = {
1575
1692
  lastSeenAt: new Date(),
@@ -1781,6 +1898,7 @@ async function mergeContacts(
1781
1898
  resolvedKey: string;
1782
1899
  mergedKeys?: string[];
1783
1900
  mergedIdentifiedKeys?: string[];
1901
+ linkUnlinks?: MergedLinkUnlink[];
1784
1902
  }> {
1785
1903
  const { survivor, losers } = pickSurvivor(candidates);
1786
1904
  const survivorKey = contactKey(survivor);
@@ -1791,6 +1909,9 @@ async function mergeContacts(
1791
1909
  // merge on the safe path — it is recorded as the twin residual, NEVER aliased.
1792
1910
  const safeLoserKeys: string[] = [];
1793
1911
  const identifiedLoserKeys: string[] = [];
1912
+ // PRD 04: every `linked_accounts` soft-unlink the fold performs, returned so
1913
+ // PRD 08 can emit `account.unlinked` post-commit. Never emitted in here.
1914
+ const linkMutations: MergedLinkUnlink[] = [];
1794
1915
 
1795
1916
  for (const loser of losers) {
1796
1917
  // The id is the last-resort key for a loser that has neither external nor
@@ -1935,6 +2056,13 @@ async function mergeContacts(
1935
2056
  // when BOTH already belong to the same group, so fold-then-rewrite.
1936
2057
  await foldGroupMemberships(tx, survivor.id, loser.id);
1937
2058
 
2059
+ // (vi-d) linked_accounts FOLD — the same stranding failure as (vi-c), with
2060
+ // an extra wrinkle: the singleton partial-unique index forbids a blind
2061
+ // repoint. See foldLinkedAccounts.
2062
+ linkMutations.push(
2063
+ ...(await foldLinkedAccounts(tx, survivor.id, loser.id)),
2064
+ );
2065
+
1938
2066
  // (ix) RECORD aliases for each loser key → survivor.
1939
2067
  await recordMergeAliases(tx, survivor.id, loser);
1940
2068
  }
@@ -2122,6 +2250,7 @@ async function mergeContacts(
2122
2250
  mergedKeys: safeLoserKeys.length > 0 ? safeLoserKeys : undefined,
2123
2251
  mergedIdentifiedKeys:
2124
2252
  identifiedLoserKeys.length > 0 ? identifiedLoserKeys : undefined,
2253
+ linkUnlinks: linkMutations.length > 0 ? linkMutations : undefined,
2125
2254
  };
2126
2255
  }
2127
2256
 
@@ -2392,6 +2521,125 @@ async function foldGroupMemberships(
2392
2521
  .where(eq(groupMemberships.contactId, loserId));
2393
2522
  }
2394
2523
 
2524
+ /**
2525
+ * linked_accounts FOLD (vi-d, PRD 04 T2).
2526
+ * `linked_accounts_contact_provider_singleton_idx` is a PARTIAL unique index
2527
+ * on (contact_id, provider) WHERE unlinked_at IS NULL AND singleton, so a
2528
+ * blind repoint raises 23505 whenever survivor and loser both hold a live
2529
+ * singleton link for the same provider. Resolution: the survivor's row stays
2530
+ * (the survivor is what `pickSurvivor` considers primary, consistent with
2531
+ * every other fold), the loser's is SOFT-unlinked with reason "relinked"
2532
+ * through the store's versioning helper (never raw SQL — an unlink whose
2533
+ * version does not advance is discarded forever by the consumer's monotonic
2534
+ * guard, DECISIONS §5.3), and everything else repoints.
2535
+ *
2536
+ * `multiple: true` links (singleton = false) and already-unlinked history rows
2537
+ * need no arbitration: they are outside the partial index, so they just move.
2538
+ *
2539
+ * Known lock-order hazard, stated rather than hidden (PRD 04): the merge
2540
+ * transaction already holds contact-key advisory locks (taken at the top of
2541
+ * the resolve tx) and only NOW takes pair locks; the store takes pair locks
2542
+ * and then touches `linked_accounts` rows belonging to contacts. The two
2543
+ * never take the SAME two advisory locks in opposite orders, so there is no
2544
+ * advisory-lock cycle, but a ROW-lock cycle between a merge and a concurrent
2545
+ * link on the same rows is possible in principle — Postgres detects it and
2546
+ * aborts one side with 40P01, which surfaces as a failed resolve/link the
2547
+ * caller retries. Mitigation, not elimination: this fold runs as LATE as
2548
+ * possible in the merge (immediately before `recordMergeAliases`) so the
2549
+ * window is a few statements wide. Do not attempt a global lock ordering
2550
+ * across the two subsystems.
2551
+ */
2552
+ async function foldLinkedAccounts(
2553
+ tx: Tx,
2554
+ survivorId: string,
2555
+ loserId: string,
2556
+ ): Promise<MergedLinkUnlink[]> {
2557
+ const facts: MergedLinkUnlink[] = [];
2558
+
2559
+ // 1. The survivor's occupied singleton providers.
2560
+ const survivorSingletons = await tx
2561
+ .select({ provider: linkedAccounts.provider })
2562
+ .from(linkedAccounts)
2563
+ .where(
2564
+ and(
2565
+ eq(linkedAccounts.contactId, survivorId),
2566
+ isNull(linkedAccounts.unlinkedAt),
2567
+ eq(linkedAccounts.singleton, true),
2568
+ ),
2569
+ );
2570
+ const occupied = survivorSingletons.map((r) => r.provider);
2571
+
2572
+ if (occupied.length > 0) {
2573
+ // 2. The collisions: the loser's live singleton rows for those providers.
2574
+ const collisions = await tx
2575
+ .select({
2576
+ id: linkedAccounts.id,
2577
+ provider: linkedAccounts.provider,
2578
+ providerUserId: linkedAccounts.providerUserId,
2579
+ })
2580
+ .from(linkedAccounts)
2581
+ .where(
2582
+ and(
2583
+ eq(linkedAccounts.contactId, loserId),
2584
+ isNull(linkedAccounts.unlinkedAt),
2585
+ eq(linkedAccounts.singleton, true),
2586
+ inArray(linkedAccounts.provider, occupied),
2587
+ ),
2588
+ );
2589
+
2590
+ // 3. Soft-unlink each collision at that pair's OWN next version, through
2591
+ // the store (PRD 03's tx-scoped entry point — `contacts.ts` never writes
2592
+ // a version).
2593
+ for (const row of collisions) {
2594
+ const outcome = await unlinkAccountInTx(tx, {
2595
+ rowId: row.id,
2596
+ provider: row.provider,
2597
+ providerUserId: row.providerUserId,
2598
+ reason: "relinked",
2599
+ });
2600
+ // The store's result is a UNION, not a bare success: a `not_found`
2601
+ // means the row went stale between our read and the pair lock
2602
+ // (unlinked/relinked by a concurrent commit) — nothing was mutated, so
2603
+ // recording a fact here would make PRD 08 emit a phantom
2604
+ // `account.unlinked`. Skip it; step 4 still repoints whatever remains.
2605
+ if (outcome.status !== "unlinked") continue;
2606
+ facts.push({
2607
+ provider: row.provider,
2608
+ providerUserId: row.providerUserId,
2609
+ version: outcome.version,
2610
+ contactId: loserId,
2611
+ reason: "relinked",
2612
+ // The `unlinked` arm the narrowing above just proved (the join to
2613
+ // `contacts` the store did under the pair lock). Copied, never
2614
+ // re-read: PRD 08's payload needs `userId`/`email`, and a second
2615
+ // lookup at emit time is no longer the state that committed.
2616
+ owner: outcome.owner,
2617
+ });
2618
+ }
2619
+ }
2620
+
2621
+ // 4. Repoint EVERYTHING remaining — live, historical, and the rows step 3
2622
+ // just unlinked (an unlinked row is outside every partial index, so it
2623
+ // moves without conflict; leaving it behind would strand history on the
2624
+ // soft-deleted loser). A version-free ownership repoint, not a state
2625
+ // transition: version/linked_at/method/tokens are preserved.
2626
+ //
2627
+ // DELIBERATELY NOT AN EMIT POINT (PRD 08). A reader looking for the
2628
+ // `account.unlinked` that step 3 produces will look here too: moving a link
2629
+ // to the merge's survivor is not a new identity fact, it allocates no
2630
+ // version, and emitting from here would double-report every merge. Step 3's
2631
+ // soft-unlink is the different thing that IS emitted — it really did end a
2632
+ // link, at its own new version — and even that emit does not happen here:
2633
+ // this whole function runs INSIDE the merge transaction, so the emit lives
2634
+ // post-commit in `resolveContactShared` (DECISIONS §8, commit/intent layer).
2635
+ await tx
2636
+ .update(linkedAccounts)
2637
+ .set({ contactId: survivorId, updatedAt: new Date() })
2638
+ .where(eq(linkedAccounts.contactId, loserId));
2639
+
2640
+ return facts;
2641
+ }
2642
+
2395
2643
  /**
2396
2644
  * email_preferences FOLD (risk 6 — suppression/unsubscribe must NEVER be lost).
2397
2645
  * For each of the loser's pref rows, fold it into whatever currently sits at
@@ -2571,6 +2819,15 @@ async function adoptOrphanHistory(
2571
2819
  await foldEmailPreferences(tx, [fromKey], ownKey, row.id, undefined, {
2572
2820
  stampOnly: true,
2573
2821
  });
2822
+
2823
+ // linked_accounts is deliberately ABSENT here, and that is not an omission.
2824
+ // This function stamps rows that sat under a text key with NO owner
2825
+ // (`WHERE user_id = :fromKey AND contact_id IS NULL`). `linked_accounts` has
2826
+ // no `user_id` column and its `contact_id` is NOT NULL: a link row can only
2827
+ // be created from a callback where the contact is already bound (DECISIONS
2828
+ // §7), so an orphan link row is unrepresentable. The merge path DOES carry
2829
+ // links — see foldLinkedAccounts. Do not "fix" this by adding a statement;
2830
+ // add a test instead if you doubt it.
2574
2831
  }
2575
2832
 
2576
2833
  /** RECORD a contact_aliases row per loser key → survivor (reason 'merge'). */
@@ -2808,6 +3065,8 @@ export async function upsertContact(opts: {
2808
3065
  mergedKeys?: string[];
2809
3066
  /** §5.3 MF-2: already-identified loser keys (twin residual); never aliased. */
2810
3067
  mergedIdentifiedKeys?: string[];
3068
+ /** As {@link resolveOrCreateContact} (PRD 04). */
3069
+ linkUnlinks?: MergedLinkUnlink[];
2811
3070
  }> {
2812
3071
  return resolveOrCreateContact({
2813
3072
  db: opts.db,
@@ -2879,6 +3138,13 @@ export async function softDeleteContact(opts: {
2879
3138
  id?: string;
2880
3139
  externalId?: string | null;
2881
3140
  email?: string | null;
3141
+ /**
3142
+ * PRD 04 T5 (DECISIONS §15.3): one fact per live `linked_accounts` row this
3143
+ * delete soft-unlinked (token blobs hard-deleted alongside). PRD 08 emits
3144
+ * one `account.unlinked` per entry post-commit so mirrors converge. Absent
3145
+ * when the deleted contact(s) held no live links.
3146
+ */
3147
+ linkUnlinks?: ContactUnlinkFact[];
2882
3148
  }> {
2883
3149
  const { db } = opts;
2884
3150
  const email = opts.email ? normalizeEmail(opts.email) : undefined;
@@ -2919,6 +3185,22 @@ export async function softDeleteContact(opts: {
2919
3185
  }
2920
3186
  if (targetIds.size === 0) return undefined;
2921
3187
 
3188
+ // PRD 04 T5 (DECISIONS §15.3): soft-unlink every live link the target(s)
3189
+ // hold, in this SAME transaction, each at its own pair's next version
3190
+ // through the store's tx-scoped helper — a live row outliving its owner
3191
+ // locks the `(provider, provider_user_id)` pair forever, so an erased
3192
+ // player could never relink their own account under onConflict "reject".
3193
+ // Tokens are hard-deleted alongside. Idempotent by construction: a target
3194
+ // with no live links contributes nothing.
3195
+ const linkUnlinks: ContactUnlinkFact[] = [];
3196
+ for (const targetId of targetIds) {
3197
+ linkUnlinks.push(
3198
+ ...(await unlinkAccountsForContactInTx(tx, targetId, {
3199
+ reason: "api",
3200
+ })),
3201
+ );
3202
+ }
3203
+
2922
3204
  const updated = await tx
2923
3205
  .update(contacts)
2924
3206
  .set({ deletedAt: new Date(), updatedAt: new Date() })
@@ -2935,16 +3217,48 @@ export async function softDeleteContact(opts: {
2935
3217
  for (const deleted of updated) {
2936
3218
  await deleteIdentityAliasesForContact(tx, deleted.id);
2937
3219
  }
2938
- return updated[0];
3220
+ return updated[0] ? { row: updated[0], linkUnlinks } : undefined;
2939
3221
  });
2940
3222
 
2941
3223
  if (!row) return { deleted: false };
2942
3224
 
3225
+ // THE CONTACT-DELETION `account.unlinked` EMIT (PRD 08 T3, DECISIONS §15.3),
3226
+ // one per live link, `reason: "api"`. Post-commit: the transaction above has
3227
+ // resolved, so a rollback never reaches this line.
3228
+ //
3229
+ // It lives HERE rather than at the callers because `softDeleteContact` has
3230
+ // THREE of them — `routes/contacts/index.ts`'s DELETE, the agent tool's
3231
+ // `delete_contact` arm, and any consumer-built deletion flow — and each one
3232
+ // that forgot would leave a customer's mirror recording a deleted player as
3233
+ // still linked, forever. The facts stay on the return value as well; that is
3234
+ // the reporting channel (and what the delete-leg tests assert), not a second
3235
+ // emit point. The admin erasure route runs its OWN transaction and therefore
3236
+ // owns its own post-commit emit (`routes/admin/contacts.ts`).
3237
+ emitAccountUnlinked(db, row.linkUnlinks);
3238
+
3239
+ // NO journey-plane re-ingest here, deliberately (PRD 08 T5). Every other
3240
+ // `account.unlinked` site gets one; this one must not, for two independent
3241
+ // reasons:
3242
+ //
3243
+ // 1. The subject was just ERASED. Filing a fresh `user_events` row for a
3244
+ // contact that was soft-deleted microseconds ago — and enrolling them in
3245
+ // a journey that would then try to reach them — is the opposite of what
3246
+ // a deletion means.
3247
+ // 2. There is no safe key anyway. The pin (`fact.owner.contactId`) resolves
3248
+ // to a soft-deleted row with no merge alias to follow, so the re-ingest
3249
+ // would be dropped as provenance-lost; and the only alternative,
3250
+ // `owner.userId`, is a value key that `resolveOrCreateContact` would
3251
+ // MINT a fresh contact for — RESURRECTING the row the caller just
3252
+ // erased.
3253
+ //
3254
+ // The customer's mirror still converges: that is what the emit above is for.
3255
+
2943
3256
  return {
2944
3257
  deleted: true,
2945
- id: row.id,
2946
- externalId: row.externalId,
2947
- email: row.email,
3258
+ id: row.row.id,
3259
+ externalId: row.row.externalId,
3260
+ email: row.row.email,
3261
+ linkUnlinks: row.linkUnlinks.length > 0 ? row.linkUnlinks : undefined,
2948
3262
  };
2949
3263
  }
2950
3264
 
@@ -0,0 +1,68 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import type { DomainsCapability, EmailProvider } from "@hogsend/core";
4
+ import { createDomainStatusService } from "./domain-status.js";
5
+
6
+ // `EngineDomainStatus.returnPathSupported` is the discovery bit Studio/CLI key
7
+ // the return-path control off (PRD 20 EARS: when the capability has no
8
+ // `setReturnPath`, the upgrade is reported unavailable — never rendered as a
9
+ // dead control). Held here against the REAL service, since the admin-route
10
+ // tests run on a fake status service.
11
+
12
+ const noopLogger = {
13
+ info() {},
14
+ warn() {},
15
+ error() {},
16
+ debug() {},
17
+ } as never;
18
+
19
+ const STATUS = {
20
+ domain: "acme.test",
21
+ state: "verified",
22
+ records: [],
23
+ providerId: "fake",
24
+ checkedAt: "2026-08-11T00:00:00.000Z",
25
+ } as const;
26
+
27
+ function makeService(domains?: DomainsCapability) {
28
+ const provider = {
29
+ meta: { id: "fake", name: "Fake" },
30
+ ...(domains ? { domains } : {}),
31
+ } as unknown as EmailProvider;
32
+ return createDomainStatusService({
33
+ provider,
34
+ env: { EMAIL_DOMAIN: "acme.test", HOGSEND_TEST_MODE: "false" } as never,
35
+ logger: noopLogger,
36
+ });
37
+ }
38
+
39
+ const baseCapability: DomainsCapability = {
40
+ create: async () => ({ ...STATUS, records: [] }),
41
+ get: async () => ({ ...STATUS, records: [] }),
42
+ records: async () => [],
43
+ };
44
+
45
+ test("returnPathSupported is true when the capability has setReturnPath", async () => {
46
+ const service = makeService({
47
+ ...baseCapability,
48
+ setReturnPath: async () => ({
49
+ enabled: true,
50
+ mailFromDomain: "send.acme.test",
51
+ status: { ...STATUS, records: [] },
52
+ }),
53
+ });
54
+ const status = await service.getStatus();
55
+ assert.equal(status.returnPathSupported, true);
56
+ });
57
+
58
+ test("returnPathSupported is false when domains exists without it", async () => {
59
+ const status = await makeService(baseCapability).getStatus();
60
+ assert.equal(status.supported, true);
61
+ assert.equal(status.returnPathSupported, false);
62
+ });
63
+
64
+ test("returnPathSupported is false when there is no domains capability", async () => {
65
+ const status = await makeService().getStatus();
66
+ assert.equal(status.supported, false);
67
+ assert.equal(status.returnPathSupported, false);
68
+ });
@@ -2,6 +2,10 @@ import type { DomainStatus, EmailProvider } from "@hogsend/core";
2
2
  import type { env as envSchema } from "../env.js";
3
3
  import { hostOfFromAddress } from "./from-address.js";
4
4
  import type { Logger } from "./logger.js";
5
+ import {
6
+ SENDING_DOMAIN_GUIDANCE,
7
+ type SendingDomainGuidance,
8
+ } from "./sending-domain-guidance.js";
5
9
 
6
10
  /**
7
11
  * Per-send test-mode snapshot (PROJECT_SPEC pinned shape).
@@ -36,9 +40,19 @@ export interface EngineDomainStatus {
36
40
  providerId: string;
37
41
  /** `!!provider.domains` — presence of the capability is the gate. */
38
42
  supported: boolean;
43
+ /**
44
+ * Whether `provider.domains.setReturnPath` exists — the branded-return-path
45
+ * upgrade's own gate (PRD 20). Studio/CLI key the toggle off this so a
46
+ * provider without the method gets NO dead control; the POST would 501.
47
+ * Optional in the TYPE only for wire skew (an older engine never sends it,
48
+ * and clients ship separately from engines); this engine always sets it.
49
+ */
50
+ returnPathSupported?: boolean;
39
51
  /** `null` when `!supported || !domain` (the provider is never called then). */
40
52
  status: DomainStatus | null;
41
53
  testMode: TestModeState;
54
+ /** Static setup advice. Same words in Studio and the CLI, one source. */
55
+ guidance: SendingDomainGuidance;
42
56
  }
43
57
 
44
58
  /**
@@ -180,6 +194,8 @@ export function createDomainStatusService(deps: {
180
194
 
181
195
  const providerId = provider.meta?.id ?? "resend";
182
196
  const supported = Boolean(provider.domains);
197
+ const returnPathSupported =
198
+ typeof provider.domains?.setReturnPath === "function";
183
199
  const domain =
184
200
  env.EMAIL_DOMAIN ??
185
201
  hostPartOf(env.EMAIL_FROM) ??
@@ -278,6 +294,7 @@ export function createDomainStatusService(deps: {
278
294
  domain,
279
295
  providerId,
280
296
  supported,
297
+ returnPathSupported,
281
298
  status,
282
299
  testMode: {
283
300
  active: false,
@@ -285,6 +302,8 @@ export function createDomainStatusService(deps: {
285
302
  redirectTo: null,
286
303
  fromOverride: null,
287
304
  },
305
+ // Constant advice — no computation, no cache interaction.
306
+ guidance: SENDING_DOMAIN_GUIDANCE,
288
307
  };
289
308
  cache = { snapshot, fetchedAt: Date.now() };
290
309
  const testMode = computeTestMode();
@@ -0,0 +1,48 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ // The positive half of email-provider-boot.test.ts, in its own process because
5
+ // the two need opposite HOGSEND_EMAIL_TOKEN postures at module load (the guarded
6
+ // dynamic import fires at module scope). Together they are the whole contract:
7
+ // token present ⇒ registered and resolvable; token absent ⇒ boot throws.
8
+ //
9
+ // This is the end-to-end wiring proof for the engine side of PRD 10 — env var →
10
+ // guarded import → preset → EmailProviderRegistry → the ACTIVE provider the
11
+ // tracked mailer sends through. No network: the provider is constructed, never
12
+ // called.
13
+ process.env.NODE_ENV ??= "test";
14
+ process.env.LOG_LEVEL ??= "error";
15
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
16
+ process.env.BETTER_AUTH_SECRET ??=
17
+ "test-secret-for-node-test-minimum-32-characters-long";
18
+ process.env.HATCHET_CLIENT_TOKEN ??=
19
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
20
+ // Exactly what a provisioned Cloud environment gets — and deliberately NO
21
+ // RESEND_API_KEY, which is the point: a Cloud instance sends with no Resend
22
+ // account anywhere in the picture. Deleted (not assumed absent) so a dev shell
23
+ // that happens to export provider credentials cannot flip the getAll()
24
+ // assertion below.
25
+ delete process.env.RESEND_API_KEY;
26
+ delete process.env.POSTMARK_SERVER_TOKEN;
27
+ process.env.HOGSEND_EMAIL_TOKEN = "hsrel_boot_test_token";
28
+ process.env.HOGSEND_EMAIL_RELAY_URL = "https://cloud.example.com";
29
+ process.env.HOGSEND_EMAIL_WEBHOOK_SECRET = "whsec_boot_test";
30
+ process.env.EMAIL_PROVIDER = "hogsend";
31
+
32
+ const { createHogsendClient } = await import("../container.js");
33
+
34
+ test("EMAIL_PROVIDER=hogsend + a relay token → hogsend is the ACTIVE provider", () => {
35
+ const client = createHogsendClient();
36
+
37
+ assert.equal(client.emailProvider.meta?.id, "hogsend");
38
+ assert.ok(
39
+ client.emailProviders.get("hogsend"),
40
+ "the registry must hold the provider the webhook route dispatches by id",
41
+ );
42
+ // No Resend key was set, so nothing else is registered — a Cloud instance
43
+ // boots and sends with no Resend account at all.
44
+ assert.deepEqual(
45
+ client.emailProviders.getAll().map((p) => p.meta?.id),
46
+ ["hogsend"],
47
+ );
48
+ });