@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.
- package/package.json +12 -12
- package/src/account-links/__fixtures__/fake-fetch.test.ts +57 -0
- package/src/account-links/__fixtures__/fake-fetch.ts +114 -0
- package/src/account-links/__fixtures__/steam.json +21 -0
- package/src/account-links/__fixtures__/twitch.json +22 -0
- package/src/account-links/index.ts +8 -0
- package/src/account-links/steam.test.ts +243 -0
- package/src/account-links/steam.ts +48 -0
- package/src/account-links/twitch.test.ts +157 -0
- package/src/account-links/twitch.ts +99 -0
- package/src/container.account-links.env.test.ts +65 -0
- package/src/container.account-links.halfenv.test.ts +48 -0
- package/src/container.account-links.test.ts +185 -0
- package/src/container.ts +120 -0
- package/src/env.ts +37 -0
- package/src/index.ts +87 -1
- package/src/lib/account-link-emit.ts +126 -0
- package/src/lib/account-link-events.ts +180 -0
- package/src/lib/account-link-hooks.test.ts +158 -0
- package/src/lib/account-link-hooks.ts +73 -0
- package/src/lib/account-link-ingest.ts +364 -0
- package/src/lib/account-link-nonce.test.ts +52 -0
- package/src/lib/account-link-nonce.ts +57 -0
- package/src/lib/account-link-origins.test.ts +72 -0
- package/src/lib/account-link-origins.ts +87 -0
- package/src/lib/account-link-pkce.test.ts +91 -0
- package/src/lib/account-link-pkce.ts +106 -0
- package/src/lib/account-link-provider-registry.test.ts +52 -0
- package/src/lib/account-link-provider-registry.ts +61 -0
- package/src/lib/account-link-throttle.test.ts +178 -0
- package/src/lib/account-link-throttle.ts +130 -0
- package/src/lib/account-link-url.ts +85 -0
- package/src/lib/account-links-emit.test.ts +525 -0
- package/src/lib/account-links-env.test.ts +40 -0
- package/src/lib/account-links-from-env.test.ts +187 -0
- package/src/lib/account-links-from-env.ts +126 -0
- package/src/lib/account-links.ts +1300 -0
- package/src/lib/app-secret.ts +34 -0
- package/src/lib/connector-actions.test.ts +13 -4
- package/src/lib/connector-state.account-link.test.ts +114 -0
- package/src/lib/connector-state.ts +48 -3
- package/src/lib/contacts.ts +320 -6
- package/src/lib/outbound-account-payloads.test.ts +137 -0
- package/src/lib/outbound.ts +91 -0
- package/src/lib/provider-credentials.ts +19 -5
- package/src/lib/webhook-catalog-sync.test.ts +24 -0
- package/src/lib/webhook-signing.ts +18 -1
- package/src/routes/accounts/callback.ts +597 -0
- package/src/routes/accounts/emit.ts +231 -0
- package/src/routes/accounts/import-links.ts +210 -0
- package/src/routes/accounts/index.ts +75 -0
- package/src/routes/accounts/lookup.ts +177 -0
- package/src/routes/accounts/me.ts +215 -0
- package/src/routes/accounts/mint.ts +279 -0
- package/src/routes/accounts/pages.ts +62 -0
- package/src/routes/accounts/resolve.ts +61 -0
- package/src/routes/accounts/serialize.ts +96 -0
- package/src/routes/accounts/shared.ts +107 -0
- package/src/routes/accounts/start.ts +229 -0
- package/src/routes/accounts/unlink.ts +98 -0
- package/src/routes/admin/agent.ts +2 -0
- package/src/routes/admin/api-keys.ts +7 -0
- package/src/routes/admin/contacts.ts +38 -2
- package/src/routes/connectors/index.ts +17 -0
- package/src/routes/contacts/index.ts +8 -0
- package/src/routes/index.ts +75 -0
- package/src/testing-barrel.test.ts +74 -0
- package/src/testing.ts +17 -0
package/src/lib/contacts.ts
CHANGED
|
@@ -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
|
-
|
|
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,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
|
+
});
|