@hogsend/engine 0.64.0 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/package.json +12 -12
  2. package/src/account-links/__fixtures__/fake-fetch.test.ts +57 -0
  3. package/src/account-links/__fixtures__/fake-fetch.ts +114 -0
  4. package/src/account-links/__fixtures__/steam.json +21 -0
  5. package/src/account-links/__fixtures__/twitch.json +22 -0
  6. package/src/account-links/index.ts +8 -0
  7. package/src/account-links/steam.test.ts +243 -0
  8. package/src/account-links/steam.ts +48 -0
  9. package/src/account-links/twitch.test.ts +157 -0
  10. package/src/account-links/twitch.ts +99 -0
  11. package/src/container.account-links.env.test.ts +65 -0
  12. package/src/container.account-links.halfenv.test.ts +48 -0
  13. package/src/container.account-links.test.ts +185 -0
  14. package/src/container.ts +120 -0
  15. package/src/env.ts +37 -0
  16. package/src/index.ts +87 -1
  17. package/src/lib/account-link-emit.ts +126 -0
  18. package/src/lib/account-link-events.ts +180 -0
  19. package/src/lib/account-link-hooks.test.ts +158 -0
  20. package/src/lib/account-link-hooks.ts +73 -0
  21. package/src/lib/account-link-ingest.ts +364 -0
  22. package/src/lib/account-link-nonce.test.ts +52 -0
  23. package/src/lib/account-link-nonce.ts +57 -0
  24. package/src/lib/account-link-origins.test.ts +72 -0
  25. package/src/lib/account-link-origins.ts +87 -0
  26. package/src/lib/account-link-pkce.test.ts +91 -0
  27. package/src/lib/account-link-pkce.ts +106 -0
  28. package/src/lib/account-link-provider-registry.test.ts +52 -0
  29. package/src/lib/account-link-provider-registry.ts +61 -0
  30. package/src/lib/account-link-throttle.test.ts +178 -0
  31. package/src/lib/account-link-throttle.ts +130 -0
  32. package/src/lib/account-link-url.ts +85 -0
  33. package/src/lib/account-links-emit.test.ts +525 -0
  34. package/src/lib/account-links-env.test.ts +40 -0
  35. package/src/lib/account-links-from-env.test.ts +187 -0
  36. package/src/lib/account-links-from-env.ts +126 -0
  37. package/src/lib/account-links.ts +1300 -0
  38. package/src/lib/app-secret.ts +34 -0
  39. package/src/lib/connector-actions.test.ts +13 -4
  40. package/src/lib/connector-state.account-link.test.ts +114 -0
  41. package/src/lib/connector-state.ts +48 -3
  42. package/src/lib/contacts.ts +320 -6
  43. package/src/lib/outbound-account-payloads.test.ts +137 -0
  44. package/src/lib/outbound.ts +91 -0
  45. package/src/lib/provider-credentials.ts +19 -5
  46. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  47. package/src/lib/webhook-signing.ts +18 -1
  48. package/src/routes/accounts/callback.ts +597 -0
  49. package/src/routes/accounts/emit.ts +231 -0
  50. package/src/routes/accounts/import-links.ts +210 -0
  51. package/src/routes/accounts/index.ts +75 -0
  52. package/src/routes/accounts/lookup.ts +177 -0
  53. package/src/routes/accounts/me.ts +215 -0
  54. package/src/routes/accounts/mint.ts +279 -0
  55. package/src/routes/accounts/pages.ts +62 -0
  56. package/src/routes/accounts/resolve.ts +61 -0
  57. package/src/routes/accounts/serialize.ts +96 -0
  58. package/src/routes/accounts/shared.ts +107 -0
  59. package/src/routes/accounts/start.ts +229 -0
  60. package/src/routes/accounts/unlink.ts +98 -0
  61. package/src/routes/admin/agent.ts +2 -0
  62. package/src/routes/admin/api-keys.ts +7 -0
  63. package/src/routes/admin/contacts.ts +38 -2
  64. package/src/routes/connectors/index.ts +17 -0
  65. package/src/routes/contacts/index.ts +8 -0
  66. package/src/routes/index.ts +75 -0
  67. package/src/testing-barrel.test.ts +74 -0
  68. package/src/testing.ts +17 -0
@@ -0,0 +1,1300 @@
1
+ import type {
2
+ AccountLinkHooks,
3
+ AfterLinkContext,
4
+ AfterUnlinkContext,
5
+ LinkedIdentity,
6
+ LinkTokens,
7
+ } from "@hogsend/core";
8
+ import { ACCOUNT_LINK_HOOK_TIMEOUT_MS } from "@hogsend/core";
9
+ import { contacts, type Database, linkedAccounts } from "@hogsend/db";
10
+ import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
11
+ import { getAppSecret } from "./app-secret.js";
12
+ import type { Logger } from "./logger.js";
13
+ import { sealJson, unsealJson } from "./provider-credentials.js";
14
+
15
+ /**
16
+ * The account-link store: the ONE place a `linked_accounts` row is ever
17
+ * written (PRD 03). It computes the monotonic per-pair version under a
18
+ * Postgres advisory lock, enforces the live-owner rule (DECISIONS §6.1/§6.2),
19
+ * performs a relink as a two-version soft-unlink-then-insert (DECISIONS §5),
20
+ * enforces `multiple: false` through the `singleton` column, seals tokens with
21
+ * the engine's AES-256-GCM construction, and invokes `afterLink`/`afterUnlink`
22
+ * post-commit.
23
+ *
24
+ * House style follows {@link file://./groups.ts}: single-object-in /
25
+ * result-object-out, `db` injected, typed error classes.
26
+ *
27
+ * THIS MODULE IS THE SOLE INVOKER of `afterLink` and `afterUnlink`
28
+ * (DECISIONS §15.4). Routes, hosted pages and SDK paths pass
29
+ * `hooks: container.accountLinkHooks` in and call nothing themselves — the
30
+ * original stack specified the invocation in both places, which would have
31
+ * fired every customer hook twice per link, forever, and the at-least-once
32
+ * documentation would have hidden it.
33
+ *
34
+ * `beforeLink` is NEVER invoked here. It is the pre-write veto and PRD 07's
35
+ * callback owns it (DECISIONS §9): moving it into the store would run it after
36
+ * the transaction opened, holding the pair advisory lock across a customer's
37
+ * network call. The store ACCEPTS an already-vetoed decision via
38
+ * `LinkAccountInput.vetoed` and must never re-run the hook.
39
+ */
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // Errors
43
+ // ---------------------------------------------------------------------------
44
+
45
+ /**
46
+ * Thrown after {@link MAX_VERSION_RACE_RETRIES} attempts all failed on a
47
+ * retryable condition (the version-index 23505, a 40P01/40001, or a stale lock
48
+ * set). Never carries token material. The caller sees this instead of a
49
+ * silently duplicated version — a duplicate version is a permanent, invisible
50
+ * wrong answer in the consumer's `incoming.version > stored.version` guard.
51
+ */
52
+ export class AccountLinkVersionRaceError extends Error {
53
+ constructor(
54
+ public readonly provider: string,
55
+ public readonly providerUserId: string,
56
+ ) {
57
+ super(
58
+ `account link mutation for (${provider}, ${providerUserId}) still ` +
59
+ `conflicting after ${MAX_VERSION_RACE_RETRIES} attempts`,
60
+ );
61
+ this.name = "AccountLinkVersionRaceError";
62
+ }
63
+ }
64
+
65
+ /**
66
+ * INTERNAL control-flow error, treated as retryable by the mutation retry
67
+ * (T5): the singleton pre-read's pair set went stale between the pre-read and
68
+ * the lock, so the transaction found a singleton row whose pair lock it does
69
+ * NOT hold. The correct response is to abort and re-run the whole mutation
70
+ * from the pre-read — grabbing a lock mid-transaction is the staged
71
+ * acquisition that deadlocks two mirror-image swaps (each already holds what
72
+ * the other wants; Postgres kills one with 40P01).
73
+ */
74
+ export class AccountLinkLockSetChangedError extends Error {
75
+ constructor(provider: string, providerUserId: string) {
76
+ super(
77
+ `account link singleton pre-read went stale for (${provider}, ` +
78
+ `${providerUserId}) — retrying from the pre-read`,
79
+ );
80
+ this.name = "AccountLinkLockSetChangedError";
81
+ }
82
+ }
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // Types (PRD 03 T1)
86
+ // ---------------------------------------------------------------------------
87
+
88
+ type Tx = Parameters<Parameters<Database["transaction"]>[0]>[0];
89
+
90
+ export type LinkMutationStatus =
91
+ | "linked"
92
+ | "relinked"
93
+ | "unchanged"
94
+ | "rejected";
95
+
96
+ export interface LinkedAccountRecord {
97
+ id: string;
98
+ contactId: string;
99
+ provider: string;
100
+ providerUserId: string;
101
+ username: string | null;
102
+ verifiedEmail: string | null;
103
+ avatarUrl: string | null;
104
+ method: "oauth" | "import";
105
+ singleton: boolean;
106
+ /** bigint. STRING at every boundary — never a JS number (DECISIONS §5.1). */
107
+ version: string;
108
+ linkedAt: Date;
109
+ unlinkedAt: Date | null;
110
+ unlinkReason: string | null;
111
+ tokensRevokedAt: Date | null;
112
+ /** Always redacted to a boolean. The blob NEVER leaves this module. */
113
+ hasTokens: boolean;
114
+ }
115
+
116
+ /**
117
+ * The contact facts every downstream plane needs, read by a join to `contacts`
118
+ * INSIDE the mutation's transaction (DECISIONS §15.5). PRD 08's payloads carry
119
+ * `userId` and `email`; PRD 01's hook contexts carry the same two. Neither
120
+ * lives on `linked_accounts`, and neither may be looked up at emit time — a
121
+ * second read after the lock released is no longer the state that was
122
+ * committed.
123
+ */
124
+ export interface LinkOwner {
125
+ contactId: string;
126
+ /**
127
+ * `contactKey()` = `external_id ?? anonymous_id ?? id`, contacts.ts:863-865.
128
+ * ONE definition across PULL, PUSH and IN-PROCESS, so a consumer can join on
129
+ * it. NOT raw `externalId`.
130
+ */
131
+ userId: string | null;
132
+ /** The CONTACT's email. Never `linked_accounts.verified_email`. */
133
+ email: string | null;
134
+ }
135
+
136
+ export interface LinkAccountInput {
137
+ db: Database;
138
+ provider: string;
139
+ identity: LinkedIdentity;
140
+ /**
141
+ * ALREADY RESOLVED by the caller. The store never resolves, never mints, and
142
+ * never accepts an `anonymousId`: the cold-path resolve is PRD 07's
143
+ * (DECISIONS §6.10) and `resolveOrCreateContact` takes its own contact-key
144
+ * advisory locks, which cannot be nested inside the pair lock.
145
+ */
146
+ contactId: string;
147
+ method: "oauth" | "import";
148
+ /** From the provider definition; the CALLER resolves the default (`true`). */
149
+ multiple: boolean;
150
+ /** Only consulted when `multiple === false`. */
151
+ onConflict: "replace" | "reject";
152
+ /** From `capabilities.tokens`. False ⇒ tokens are dropped, not stored. */
153
+ storeTokens: boolean;
154
+ /**
155
+ * TRUE only from a completed hosted callback (DECISIONS §6.1). The import
156
+ * path (§6.2) passes FALSE and is therefore structurally insert-only: it
157
+ * cannot graft a link off its current owner no matter what it sends.
158
+ */
159
+ allowDisplaceLiveOwner: boolean;
160
+ /**
161
+ * PRD 07 already ran `beforeLink` and it REFUSED. The store must not re-run
162
+ * the hook; it just records the refusal.
163
+ */
164
+ vetoed?: boolean;
165
+ /**
166
+ * Override the INSERTed row's `linked_at`. The import path (PRD 09 T5) uses
167
+ * it to preserve the customer's historical timestamp; every other caller
168
+ * omits it and takes the column default (`now()`).
169
+ *
170
+ * It touches ONLY the insert. A same-owner refresh must not rewrite the
171
+ * timestamp of a link that already exists, and no unlink path reads it.
172
+ */
173
+ linkedAt?: Date;
174
+ hooks?: AccountLinkHooks;
175
+ logger?: Logger;
176
+ }
177
+
178
+ /**
179
+ * A soft-unlinked row this mutation displaced, with the facts PRD 08 needs to
180
+ * emit its `account.unlinked` without re-reading the database.
181
+ */
182
+ export interface DisplacedLink {
183
+ contactId: string;
184
+ provider: string;
185
+ providerUserId: string;
186
+ /** That pair's OWN next version (string, DECISIONS §5.1). */
187
+ version: string;
188
+ owner: LinkOwner;
189
+ }
190
+
191
+ export type LinkAccountResult =
192
+ | {
193
+ status: "linked";
194
+ row: LinkedAccountRecord;
195
+ relink: false;
196
+ version: string;
197
+ owner: LinkOwner;
198
+ /**
199
+ * Present when a `multiple: false` / `onConflict: "replace"` mutation
200
+ * soft-unlinked the contact's OTHER pair to make room. That row's facts
201
+ * are carried here (its pair, its own next version, its owner) because
202
+ * the store returns the full facts each mutation produced (DECISIONS §8)
203
+ * and the write is otherwise invisible to the caller.
204
+ */
205
+ replacedSingleton?: DisplacedLink;
206
+ }
207
+ | {
208
+ status: "relinked";
209
+ row: LinkedAccountRecord;
210
+ relink: true;
211
+ version: string;
212
+ owner: LinkOwner;
213
+ previous: { contactId: string; version: string; owner: LinkOwner };
214
+ replacedSingleton?: DisplacedLink;
215
+ }
216
+ | {
217
+ status: "unchanged";
218
+ row: LinkedAccountRecord;
219
+ version: string;
220
+ owner: LinkOwner;
221
+ }
222
+ | {
223
+ status: "rejected";
224
+ reason: "live_owner_conflict" | "singleton_conflict" | "vetoed";
225
+ currentOwnerContactId?: string;
226
+ };
227
+
228
+ export interface UnlinkAccountInput {
229
+ db: Database;
230
+ provider: string;
231
+ providerUserId: string;
232
+ reason: "player" | "api" | "relinked";
233
+ /**
234
+ * Guard: only unlink when this contact is the live owner. Omit for admin.
235
+ *
236
+ * REQUIRED on both player-facing revokes (PRD 09's `/accounts/me/revoke` and
237
+ * PRD 11's manage page). It is evaluated INSIDE the pair lock, after the
238
+ * live-owner probe, which is the whole point: a caller that reads the row,
239
+ * compares in application code, then unlinks by pair has a window in which a
240
+ * hosted callback relinks the pair, and contact A's revoke then destroys
241
+ * contact B's just-proven link. This is the same read-then-write hazard
242
+ * PRD 09 forbids for the import path.
243
+ */
244
+ expectContactId?: string;
245
+ /** Best-effort provider-side token revoke, run post-commit. */
246
+ revoke?: (tokens: LinkTokens) => Promise<void>;
247
+ hooks?: AccountLinkHooks;
248
+ logger?: Logger;
249
+ }
250
+
251
+ export type UnlinkAccountResult =
252
+ | {
253
+ status: "unlinked";
254
+ row: LinkedAccountRecord;
255
+ version: string;
256
+ owner: LinkOwner;
257
+ }
258
+ | { status: "not_found" }
259
+ | { status: "rejected"; reason: "not_owner"; currentOwnerContactId: string };
260
+
261
+ /**
262
+ * `unlinkAccountInTx`'s result. A union rather than the bare
263
+ * `{ version, owner }`: the acceptance criteria require the `expectContactId`
264
+ * guard to REJECT (mutating nothing) on both entry points, and the merge
265
+ * caller must be able to see "the row you meant is already gone" without a
266
+ * throw unwinding its whole transaction.
267
+ */
268
+ export type UnlinkAccountInTxResult =
269
+ | { status: "unlinked"; version: string; owner: LinkOwner }
270
+ | { status: "not_found" }
271
+ | { status: "rejected"; reason: "not_owner"; currentOwnerContactId: string };
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // The advisory lock (PRD 03 T2)
275
+ // ---------------------------------------------------------------------------
276
+
277
+ /**
278
+ * Serialize every mutation for ONE platform account. `hashtext` folds the
279
+ * string into the int4 the single-arg `pg_advisory_xact_lock` overload takes;
280
+ * the lock is TRANSACTION-scoped, so it releases on COMMIT or ROLLBACK with no
281
+ * unlock call and no leak on a thrown error. Same idiom as
282
+ * `lib/blueprint-lock.ts:20` and `lib/contacts.ts:1223`.
283
+ *
284
+ * The key is `al:<provider>:<providerUserId>`. The `al:` prefix keeps it from
285
+ * colliding with the `bp-graph:` and `<kind>:<value>` namespaces already in
286
+ * use; `hashtext` collisions across namespaces are possible in principle and
287
+ * cost only a spurious wait, never a correctness bug.
288
+ */
289
+ export function pairLockKey(provider: string, providerUserId: string): string {
290
+ return `al:${provider}:${providerUserId}`;
291
+ }
292
+
293
+ /**
294
+ * Exported for the lock-order unit test only; production callers are the
295
+ * mutations in this module.
296
+ */
297
+ export async function lockPairs(tx: Tx, keys: string[]): Promise<void> {
298
+ // SORTED, deduped: when a `multiple:false` replace has to touch TWO pairs,
299
+ // two mirror-image concurrent replaces taking them in opposite orders is a
300
+ // textbook deadlock. A total order removes the cycle.
301
+ for (const key of [...new Set(keys)].sort()) {
302
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${key}))`);
303
+ }
304
+ }
305
+
306
+ // ---------------------------------------------------------------------------
307
+ // Internals
308
+ // ---------------------------------------------------------------------------
309
+
310
+ /**
311
+ * `COALESCE(MAX(version), 0) + 1` across ALL rows for the pair, live and
312
+ * unlinked (DECISIONS §5.1). Computed INSIDE the pair lock, in SQL — the
313
+ * increment never happens in JS, and the value crosses out of Postgres as a
314
+ * string which `BigInt()` carries losslessly into the drizzle
315
+ * `mode: "bigint"` column. Never `Number()`, never `parseInt`.
316
+ */
317
+ async function nextVersion(
318
+ tx: Tx,
319
+ provider: string,
320
+ providerUserId: string,
321
+ ): Promise<bigint> {
322
+ const rows = (await tx.execute(sql`
323
+ SELECT COALESCE(MAX(version), 0) + 1 AS next
324
+ FROM linked_accounts
325
+ WHERE provider = ${provider} AND provider_user_id = ${providerUserId}
326
+ `)) as unknown as Array<{ next: string | bigint }>;
327
+ const next = rows[0]?.next;
328
+ if (next === undefined) {
329
+ throw new Error("nextVersion: aggregate returned no row");
330
+ }
331
+ return BigInt(next);
332
+ }
333
+
334
+ /**
335
+ * The owner read, INSIDE the locked transaction (DECISIONS §15.5). `userId`
336
+ * is `contactKey()` (`external_id ?? anonymous_id ?? id`,
337
+ * `lib/contacts.ts:863-865`), NEVER raw `externalId`; `email` is the
338
+ * CONTACT's own address, never the provider-reported `verifiedEmail`
339
+ * (DECISIONS §6.3/§6.4 — wiring the provider email in here is the grafting
340
+ * vector).
341
+ */
342
+ async function readOwner(tx: Tx, contactId: string): Promise<LinkOwner> {
343
+ const [c] = await tx
344
+ .select({
345
+ id: contacts.id,
346
+ externalId: contacts.externalId,
347
+ anonymousId: contacts.anonymousId,
348
+ email: contacts.email,
349
+ })
350
+ .from(contacts)
351
+ .where(eq(contacts.id, contactId))
352
+ .limit(1);
353
+ if (!c) return { contactId, userId: null, email: null };
354
+ return {
355
+ contactId,
356
+ userId: c.externalId ?? c.anonymousId ?? c.id,
357
+ email: c.email ?? null,
358
+ };
359
+ }
360
+
361
+ type LinkedAccountRow = typeof linkedAccounts.$inferSelect;
362
+
363
+ /**
364
+ * The ONE projection from a row to the public shape. This is where `tokens`
365
+ * collapses to `hasTokens` — the sealed blob never leaves this module, and
366
+ * nothing else in the engine may select `linkedAccounts.tokens` except the
367
+ * property-sync path (PRD 14).
368
+ */
369
+ function toLinkedAccountRecord(row: LinkedAccountRow): LinkedAccountRecord {
370
+ return {
371
+ id: row.id,
372
+ contactId: row.contactId,
373
+ provider: row.provider,
374
+ providerUserId: row.providerUserId,
375
+ username: row.username,
376
+ verifiedEmail: row.verifiedEmail,
377
+ avatarUrl: row.avatarUrl,
378
+ method: row.method,
379
+ singleton: row.singleton,
380
+ // Drizzle's `mode: "bigint"` yields a JS BigInt — String() is lossless.
381
+ // NEVER Number()/parseInt: bigint exceeds Number.MAX_SAFE_INTEGER and a
382
+ // rounded version breaks the consumer's monotonic guard invisibly.
383
+ version: String(row.version),
384
+ linkedAt: row.linkedAt,
385
+ unlinkedAt: row.unlinkedAt,
386
+ unlinkReason: row.unlinkReason,
387
+ tokensRevokedAt: row.tokensRevokedAt,
388
+ hasTokens: row.tokens !== null,
389
+ };
390
+ }
391
+
392
+ /** Seal a token grant. AES-256-GCM via `lib/provider-credentials.ts` — ONE
393
+ * construction in the engine, one place a secret rotation is handled.
394
+ *
395
+ * Async only because the secret is fetched lazily (see `lib/app-secret.ts`);
396
+ * the crypto itself is synchronous, and both call sites are already inside the
397
+ * link transaction's async body. */
398
+ async function sealTokens(tokens: LinkTokens): Promise<string> {
399
+ return sealJson(tokens, await getAppSecret());
400
+ }
401
+
402
+ // ---------------------------------------------------------------------------
403
+ // Retry (PRD 03 T5)
404
+ // ---------------------------------------------------------------------------
405
+
406
+ export const MAX_VERSION_RACE_RETRIES = 3;
407
+
408
+ /**
409
+ * Walk `err.cause` for the postgres error. Drizzle wraps the driver error, so
410
+ * `code`/`constraint_name` live on the CAUSE, not the top-level error —
411
+ * string-matching the message is not acceptable. Depth-bounded against
412
+ * pathological cause cycles.
413
+ */
414
+ function findPgError(
415
+ err: unknown,
416
+ ): { code: string; constraint?: string } | null {
417
+ let cur: unknown = err;
418
+ for (let depth = 0; depth < 10 && cur; depth++) {
419
+ if (typeof cur === "object" && cur !== null) {
420
+ const c = cur as {
421
+ code?: unknown;
422
+ constraint_name?: unknown;
423
+ constraint?: unknown;
424
+ cause?: unknown;
425
+ };
426
+ if (typeof c.code === "string") {
427
+ const constraint =
428
+ typeof c.constraint_name === "string"
429
+ ? c.constraint_name
430
+ : typeof c.constraint === "string"
431
+ ? c.constraint
432
+ : undefined;
433
+ return { code: c.code, constraint };
434
+ }
435
+ cur = c.cause;
436
+ } else {
437
+ break;
438
+ }
439
+ }
440
+ return null;
441
+ }
442
+
443
+ /**
444
+ * The RETRYABLE set is exactly three things (PRD 03 T5):
445
+ *
446
+ * 1. 23505 on `linked_accounts_provider_uid_version_idx` — the lost-race
447
+ * backstop fired; another transaction burned the version we read.
448
+ * 2. 40P01 (deadlock detected) / 40001 (serialization failure) — Postgres
449
+ * already rolled the transaction back and chose us as the victim.
450
+ * Transient by definition; surfacing one is a 500 on a player's callback
451
+ * for no reason.
452
+ * 3. `AccountLinkLockSetChangedError` — the pre-read's pair set went stale;
453
+ * re-running from the pre-read locks the right set.
454
+ *
455
+ * Any OTHER 23505 (the live index, the singleton index) is NOT retryable: it
456
+ * means a policy branch was wrong or a concurrent mutation legitimately won,
457
+ * and retrying would loop.
458
+ */
459
+ function isRetryable(err: unknown): boolean {
460
+ if (err instanceof AccountLinkLockSetChangedError) return true;
461
+ const pg = findPgError(err);
462
+ if (!pg) return false;
463
+ if (pg.code === "40P01" || pg.code === "40001") return true;
464
+ return (
465
+ pg.code === "23505" &&
466
+ pg.constraint === "linked_accounts_provider_uid_version_idx"
467
+ );
468
+ }
469
+
470
+ async function withVersionRaceRetry<T>(
471
+ opts: { provider: string; providerUserId: string; logger?: Logger },
472
+ run: () => Promise<T>,
473
+ ): Promise<T> {
474
+ for (let attempt = 1; attempt <= MAX_VERSION_RACE_RETRIES; attempt++) {
475
+ try {
476
+ return await run();
477
+ } catch (err) {
478
+ if (!isRetryable(err)) throw err;
479
+ opts.logger?.warn("accountLink mutation retrying", {
480
+ provider: opts.provider,
481
+ providerUserId: opts.providerUserId,
482
+ attempt,
483
+ error: err instanceof Error ? err.message : String(err),
484
+ });
485
+ if (attempt === MAX_VERSION_RACE_RETRIES) {
486
+ // Never write a duplicate version, never fall back to a version
487
+ // computed outside the lock.
488
+ throw new AccountLinkVersionRaceError(
489
+ opts.provider,
490
+ opts.providerUserId,
491
+ );
492
+ }
493
+ }
494
+ }
495
+ // Unreachable: the loop either returns or throws.
496
+ throw new AccountLinkVersionRaceError(opts.provider, opts.providerUserId);
497
+ }
498
+
499
+ // ---------------------------------------------------------------------------
500
+ // Post-commit hooks (PRD 03 T6)
501
+ // ---------------------------------------------------------------------------
502
+
503
+ /**
504
+ * Invoke one after-hook post-commit: bounded by
505
+ * {@link ACCOUNT_LINK_HOOK_TIMEOUT_MS}, FAIL-OPEN. A throw or a timeout is
506
+ * logged and never changes the returned result — the write already committed,
507
+ * and reporting failure would make the caller retry a completed mutation.
508
+ * Posture precedent: cold-connect's `afterBind`
509
+ * (`cold-connect/index.ts:222-233`).
510
+ */
511
+ async function invokeAfterHook(
512
+ name: "afterLink" | "afterUnlink",
513
+ fn: (() => Promise<void> | void) | undefined,
514
+ logger: Logger | undefined,
515
+ meta: { provider: string; providerUserId: string },
516
+ ): Promise<void> {
517
+ if (!fn) return;
518
+ let timer: NodeJS.Timeout | undefined;
519
+ try {
520
+ await Promise.race([
521
+ Promise.resolve(fn()),
522
+ new Promise<never>((_, reject) => {
523
+ timer = setTimeout(
524
+ () =>
525
+ reject(
526
+ new Error(`${name} exceeded ${ACCOUNT_LINK_HOOK_TIMEOUT_MS}ms`),
527
+ ),
528
+ ACCOUNT_LINK_HOOK_TIMEOUT_MS,
529
+ );
530
+ }),
531
+ ]);
532
+ } catch (err) {
533
+ logger?.warn(`accountLink ${name} threw`, {
534
+ provider: meta.provider,
535
+ providerUserId: meta.providerUserId,
536
+ error: err instanceof Error ? err.message : String(err),
537
+ });
538
+ } finally {
539
+ if (timer) clearTimeout(timer);
540
+ }
541
+ }
542
+
543
+ // ---------------------------------------------------------------------------
544
+ // linkAccount (PRD 03 T3 + T4)
545
+ // ---------------------------------------------------------------------------
546
+
547
+ /** What the transaction hands back for post-commit hook invocation. */
548
+ type LinkTxOutcome =
549
+ | { kind: "unchanged"; row: LinkedAccountRow; owner: LinkOwner }
550
+ | {
551
+ kind: "rejected";
552
+ reason: "live_owner_conflict" | "singleton_conflict";
553
+ currentOwnerContactId?: string;
554
+ }
555
+ | {
556
+ kind: "written";
557
+ row: LinkedAccountRow;
558
+ owner: LinkOwner;
559
+ previous: { contactId: string; version: string; owner: LinkOwner } | null;
560
+ replacedSingleton: DisplacedLink | null;
561
+ };
562
+
563
+ export async function linkAccount(
564
+ input: LinkAccountInput,
565
+ ): Promise<LinkAccountResult> {
566
+ // PRD 07 ran `beforeLink` and it REFUSED — record the refusal, run nothing.
567
+ // The store never re-runs the veto (DECISIONS §9).
568
+ if (input.vetoed) return { status: "rejected", reason: "vetoed" };
569
+
570
+ const { db, provider, identity } = input;
571
+ const providerUserId = identity.providerUserId;
572
+ const targetKey = pairLockKey(provider, providerUserId);
573
+
574
+ const outcome = await withVersionRaceRetry(
575
+ { provider, providerUserId, logger: input.logger },
576
+ async (): Promise<LinkTxOutcome> => {
577
+ // Step 0, OUTSIDE the transaction: the singleton pre-read. It exists so
578
+ // the FULL SET of pairs the transaction will touch is known before it
579
+ // takes its first lock. It is a HINT, not a decision: the row may change
580
+ // between the pre-read and the lock, so T4 re-verifies it inside the
581
+ // lock. Skipped entirely for `multiple: true` (never a second pair).
582
+ let preReadKeys: string[] = [];
583
+ if (!input.multiple) {
584
+ const [pre] = await db
585
+ .select({
586
+ provider: linkedAccounts.provider,
587
+ providerUserId: linkedAccounts.providerUserId,
588
+ })
589
+ .from(linkedAccounts)
590
+ .where(
591
+ and(
592
+ eq(linkedAccounts.contactId, input.contactId),
593
+ eq(linkedAccounts.provider, provider),
594
+ isNull(linkedAccounts.unlinkedAt),
595
+ eq(linkedAccounts.singleton, true),
596
+ ),
597
+ )
598
+ .limit(1);
599
+ if (pre) preReadKeys = [pairLockKey(pre.provider, pre.providerUserId)];
600
+ }
601
+
602
+ return db.transaction(async (tx) => {
603
+ // (1) EVERY pair lock this transaction might need, sorted + deduped,
604
+ // as the FIRST statement. Acquiring a second lock later, once the
605
+ // probe has revealed which pair to displace, is a textbook deadlock:
606
+ // two mirror-image swaps each already hold the other's second target.
607
+ const lockedKeys = [targetKey, ...preReadKeys];
608
+ await lockPairs(tx, lockedKeys);
609
+ const lockedSet = new Set(lockedKeys);
610
+
611
+ // (2) The live-owner probe.
612
+ const [live] = await tx
613
+ .select()
614
+ .from(linkedAccounts)
615
+ .where(
616
+ and(
617
+ eq(linkedAccounts.provider, provider),
618
+ eq(linkedAccounts.providerUserId, providerUserId),
619
+ isNull(linkedAccounts.unlinkedAt),
620
+ ),
621
+ )
622
+ .limit(1);
623
+
624
+ // Same-owner refresh: display fields (and tokens when supplied), NO
625
+ // version bump, NO emission. A display refresh is not a state
626
+ // transition and must not consume a version the consumer would then
627
+ // see as a gap (there is deliberately no `account.updated` event).
628
+ if (live && live.contactId === input.contactId) {
629
+ const set: Partial<typeof linkedAccounts.$inferInsert> = {
630
+ username: identity.username ?? null,
631
+ verifiedEmail: identity.verifiedEmail ?? null,
632
+ avatarUrl: identity.avatarUrl ?? null,
633
+ updatedAt: new Date(),
634
+ };
635
+ if (input.storeTokens && identity.tokens) {
636
+ set.tokens = await sealTokens(identity.tokens);
637
+ }
638
+ const [updated] = await tx
639
+ .update(linkedAccounts)
640
+ .set(set)
641
+ .where(eq(linkedAccounts.id, live.id))
642
+ .returning();
643
+ if (!updated) throw new Error("refresh update returned no row");
644
+ const owner = await readOwner(tx, input.contactId);
645
+ return { kind: "unchanged", row: updated, owner };
646
+ }
647
+
648
+ // Different-owner + no displacement right: only a completed hosted
649
+ // callback may MOVE a link (DECISIONS §6.1); the import path is
650
+ // structurally insert-only (§6.2).
651
+ if (live && !input.allowDisplaceLiveOwner) {
652
+ return {
653
+ kind: "rejected",
654
+ reason: "live_owner_conflict",
655
+ currentOwnerContactId: live.contactId,
656
+ };
657
+ }
658
+
659
+ // (T4) `multiple: false`: RE-VERIFY the pre-read under the lock. The
660
+ // `singleton` COLUMN is the enforcement, not this code path: the
661
+ // partial unique index `linked_accounts_contact_provider_singleton_idx`
662
+ // is what makes a bug here a 23505 instead of a silent second link.
663
+ let replacedSingleton: DisplacedLink | null = null;
664
+ if (!input.multiple) {
665
+ const [own] = await tx
666
+ .select()
667
+ .from(linkedAccounts)
668
+ .where(
669
+ and(
670
+ eq(linkedAccounts.contactId, input.contactId),
671
+ eq(linkedAccounts.provider, provider),
672
+ isNull(linkedAccounts.unlinkedAt),
673
+ eq(linkedAccounts.singleton, true),
674
+ ),
675
+ )
676
+ .limit(1);
677
+ if (own) {
678
+ if (input.onConflict === "reject") {
679
+ return { kind: "rejected", reason: "singleton_conflict" };
680
+ }
681
+ const ownKey = pairLockKey(own.provider, own.providerUserId);
682
+ if (!lockedSet.has(ownKey)) {
683
+ // The pre-read missed this pair (it changed under us). Its lock
684
+ // is NOT held — do NOT acquire one here; abort and let the
685
+ // bounded retry re-run from the pre-read.
686
+ throw new AccountLinkLockSetChangedError(
687
+ provider,
688
+ providerUserId,
689
+ );
690
+ }
691
+ // That row is a DIFFERENT pair with its OWN version sequence, and
692
+ // its lock is already held (the pre-read put it in the first
693
+ // statement's sorted set).
694
+ const ownNext = await nextVersion(
695
+ tx,
696
+ own.provider,
697
+ own.providerUserId,
698
+ );
699
+ const now = new Date();
700
+ await tx
701
+ .update(linkedAccounts)
702
+ .set({
703
+ unlinkedAt: now,
704
+ unlinkReason: "relinked",
705
+ version: ownNext,
706
+ updatedAt: now,
707
+ })
708
+ .where(eq(linkedAccounts.id, own.id));
709
+ replacedSingleton = {
710
+ contactId: own.contactId,
711
+ provider: own.provider,
712
+ providerUserId: own.providerUserId,
713
+ version: String(ownNext),
714
+ owner: await readOwner(tx, own.contactId),
715
+ };
716
+ }
717
+ }
718
+
719
+ // Relink: TWO statements, TWO versions. The displaced row's bump to
720
+ // N+1 (below the new row's N+2) is what makes the consumer's
721
+ // `incoming.version > stored.version` guard discard a LATE
722
+ // `account.unlinked`: N+1 is not greater than N+2. Emitting the
723
+ // unlink at the old row's ORIGINAL version would let the late unlink
724
+ // win and permanently record the wrong owner. Load-bearing ordering.
725
+ let previous: {
726
+ contactId: string;
727
+ version: string;
728
+ owner: LinkOwner;
729
+ } | null = null;
730
+ if (live) {
731
+ const displacedVersion = await nextVersion(
732
+ tx,
733
+ provider,
734
+ providerUserId,
735
+ );
736
+ const now = new Date();
737
+ await tx
738
+ .update(linkedAccounts)
739
+ .set({
740
+ unlinkedAt: now,
741
+ unlinkReason: "relinked",
742
+ version: displacedVersion,
743
+ updatedAt: now,
744
+ })
745
+ .where(eq(linkedAccounts.id, live.id));
746
+ previous = {
747
+ contactId: live.contactId,
748
+ version: String(displacedVersion),
749
+ owner: await readOwner(tx, live.contactId),
750
+ };
751
+ }
752
+
753
+ // (3) The version for the new row — inside the lock, in SQL. On a
754
+ // relink the MAX now includes the displaced row's fresh N+1, so this
755
+ // yields N+2.
756
+ const version = await nextVersion(tx, provider, providerUserId);
757
+ const [inserted] = await tx
758
+ .insert(linkedAccounts)
759
+ .values({
760
+ contactId: input.contactId,
761
+ provider,
762
+ providerUserId,
763
+ username: identity.username ?? null,
764
+ verifiedEmail: identity.verifiedEmail ?? null,
765
+ avatarUrl: identity.avatarUrl ?? null,
766
+ // No token declaration ⇒ tokens are DROPPED, not stored, even if
767
+ // the identity carried them.
768
+ tokens:
769
+ input.storeTokens && identity.tokens
770
+ ? await sealTokens(identity.tokens)
771
+ : null,
772
+ method: input.method,
773
+ singleton: !input.multiple,
774
+ version,
775
+ ...(input.linkedAt ? { linkedAt: input.linkedAt } : {}),
776
+ })
777
+ .returning();
778
+ if (!inserted) throw new Error("link insert returned no row");
779
+
780
+ // (6) The owner read, still inside the transaction (DECISIONS §15.5).
781
+ const owner = await readOwner(tx, input.contactId);
782
+ return {
783
+ kind: "written",
784
+ row: inserted,
785
+ owner,
786
+ previous,
787
+ replacedSingleton,
788
+ };
789
+ });
790
+ },
791
+ );
792
+
793
+ if (outcome.kind === "rejected") {
794
+ return {
795
+ status: "rejected",
796
+ reason: outcome.reason,
797
+ ...(outcome.currentOwnerContactId
798
+ ? { currentOwnerContactId: outcome.currentOwnerContactId }
799
+ : {}),
800
+ };
801
+ }
802
+
803
+ if (outcome.kind === "unchanged") {
804
+ // No hooks, no emission: nothing transitioned.
805
+ const record = toLinkedAccountRecord(outcome.row);
806
+ return {
807
+ status: "unchanged",
808
+ row: record,
809
+ version: record.version,
810
+ owner: outcome.owner,
811
+ };
812
+ }
813
+
814
+ const record = toLinkedAccountRecord(outcome.row);
815
+ const at = record.linkedAt.toISOString();
816
+ const hookMeta = { provider, providerUserId };
817
+
818
+ // Post-commit, AFTER db.transaction() resolved — never inside it, or a hook
819
+ // that reads the pull plane sees a snapshot that may still roll back.
820
+ // `afterUnlink` for displaced rows FIRST, then `afterLink` for the new row,
821
+ // mirroring the outbound event order (DECISIONS §5).
822
+ //
823
+ // `beforeLink` is DELIBERATELY not invoked anywhere in this module — it is
824
+ // PRD 07's pre-write veto. Moving it here would run it after the
825
+ // transaction opened, holding the pair lock across a customer's network
826
+ // call.
827
+ if (outcome.replacedSingleton) {
828
+ const r = outcome.replacedSingleton;
829
+ const ctx: AfterUnlinkContext = {
830
+ provider: r.provider,
831
+ providerUserId: r.providerUserId,
832
+ contactId: r.contactId,
833
+ userId: r.owner.userId,
834
+ email: r.owner.email,
835
+ reason: "relinked",
836
+ version: r.version,
837
+ at,
838
+ };
839
+ await invokeAfterHook(
840
+ "afterUnlink",
841
+ input.hooks?.afterUnlink && (() => input.hooks?.afterUnlink?.(ctx)),
842
+ input.logger,
843
+ { provider: r.provider, providerUserId: r.providerUserId },
844
+ );
845
+ }
846
+ if (outcome.previous) {
847
+ const p = outcome.previous;
848
+ const ctx: AfterUnlinkContext = {
849
+ provider,
850
+ providerUserId,
851
+ contactId: p.contactId,
852
+ userId: p.owner.userId,
853
+ email: p.owner.email,
854
+ reason: "relinked",
855
+ version: p.version,
856
+ at,
857
+ };
858
+ await invokeAfterHook(
859
+ "afterUnlink",
860
+ input.hooks?.afterUnlink && (() => input.hooks?.afterUnlink?.(ctx)),
861
+ input.logger,
862
+ hookMeta,
863
+ );
864
+ }
865
+ {
866
+ const ctx: AfterLinkContext = {
867
+ provider,
868
+ identity,
869
+ contactId: input.contactId,
870
+ userId: outcome.owner.userId,
871
+ email: outcome.owner.email,
872
+ method: input.method,
873
+ relink: outcome.previous !== null,
874
+ version: record.version,
875
+ at,
876
+ ...(outcome.previous
877
+ ? { currentOwnerContactId: outcome.previous.contactId }
878
+ : {}),
879
+ };
880
+ await invokeAfterHook(
881
+ "afterLink",
882
+ input.hooks?.afterLink && (() => input.hooks?.afterLink?.(ctx)),
883
+ input.logger,
884
+ hookMeta,
885
+ );
886
+ }
887
+
888
+ if (outcome.previous) {
889
+ return {
890
+ status: "relinked",
891
+ row: record,
892
+ relink: true,
893
+ version: record.version,
894
+ owner: outcome.owner,
895
+ previous: outcome.previous,
896
+ ...(outcome.replacedSingleton
897
+ ? { replacedSingleton: outcome.replacedSingleton }
898
+ : {}),
899
+ };
900
+ }
901
+ return {
902
+ status: "linked",
903
+ row: record,
904
+ relink: false,
905
+ version: record.version,
906
+ owner: outcome.owner,
907
+ ...(outcome.replacedSingleton
908
+ ? { replacedSingleton: outcome.replacedSingleton }
909
+ : {}),
910
+ };
911
+ }
912
+
913
+ // ---------------------------------------------------------------------------
914
+ // unlinkAccount (public) + unlinkAccountInTx (PRD 03 T3b)
915
+ // ---------------------------------------------------------------------------
916
+
917
+ /**
918
+ * The soft-unlink core, run inside SOME transaction under the pair lock:
919
+ * probe → `expectContactId` guard (INSIDE the lock, after the probe — the
920
+ * whole point of the guard) → version bump → soft-unlink UPDATE → owner read.
921
+ */
922
+ async function unlinkCore(
923
+ tx: Tx,
924
+ opts: {
925
+ provider: string;
926
+ providerUserId: string;
927
+ reason: "player" | "api" | "relinked";
928
+ expectContactId?: string;
929
+ /** When set, the live row must BE this row or the unlink is `not_found`. */
930
+ expectRowId?: string;
931
+ },
932
+ ): Promise<
933
+ | { status: "unlinked"; row: LinkedAccountRow; owner: LinkOwner }
934
+ | { status: "not_found" }
935
+ | { status: "rejected"; reason: "not_owner"; currentOwnerContactId: string }
936
+ > {
937
+ await lockPairs(tx, [pairLockKey(opts.provider, opts.providerUserId)]);
938
+
939
+ const [live] = await tx
940
+ .select()
941
+ .from(linkedAccounts)
942
+ .where(
943
+ and(
944
+ eq(linkedAccounts.provider, opts.provider),
945
+ eq(linkedAccounts.providerUserId, opts.providerUserId),
946
+ isNull(linkedAccounts.unlinkedAt),
947
+ ),
948
+ )
949
+ .limit(1);
950
+
951
+ if (!live) return { status: "not_found" };
952
+ if (opts.expectRowId && live.id !== opts.expectRowId) {
953
+ return { status: "not_found" };
954
+ }
955
+ // Evaluated INSIDE the pair lock, after the live-owner probe: a caller that
956
+ // compares in application code has a window in which a hosted callback
957
+ // relinks the pair, and contact A's revoke then destroys contact B's
958
+ // just-proven link.
959
+ if (opts.expectContactId && live.contactId !== opts.expectContactId) {
960
+ return {
961
+ status: "rejected",
962
+ reason: "not_owner",
963
+ currentOwnerContactId: live.contactId,
964
+ };
965
+ }
966
+
967
+ const version = await nextVersion(tx, opts.provider, opts.providerUserId);
968
+ const now = new Date();
969
+ const [updated] = await tx
970
+ .update(linkedAccounts)
971
+ .set({
972
+ unlinkedAt: now,
973
+ unlinkReason: opts.reason,
974
+ version,
975
+ updatedAt: now,
976
+ })
977
+ .where(eq(linkedAccounts.id, live.id))
978
+ .returning();
979
+ if (!updated) throw new Error("unlink update returned no row");
980
+
981
+ const owner = await readOwner(tx, live.contactId);
982
+ return { status: "unlinked", row: updated, owner };
983
+ }
984
+
985
+ export async function unlinkAccount(
986
+ input: UnlinkAccountInput,
987
+ ): Promise<UnlinkAccountResult> {
988
+ const outcome = await withVersionRaceRetry(
989
+ {
990
+ provider: input.provider,
991
+ providerUserId: input.providerUserId,
992
+ logger: input.logger,
993
+ },
994
+ () =>
995
+ input.db.transaction((tx) =>
996
+ unlinkCore(tx, {
997
+ provider: input.provider,
998
+ providerUserId: input.providerUserId,
999
+ reason: input.reason,
1000
+ expectContactId: input.expectContactId,
1001
+ }),
1002
+ ),
1003
+ );
1004
+
1005
+ if (outcome.status !== "unlinked") return outcome;
1006
+
1007
+ const record = toLinkedAccountRecord(outcome.row);
1008
+
1009
+ // Best-effort provider-side token revoke, post-commit (DECISIONS §10). The
1010
+ // sealed blob is unsealed here and handed to the caller's `revoke` wire —
1011
+ // never logged, never returned.
1012
+ if (input.revoke && outcome.row.tokens) {
1013
+ try {
1014
+ const tokens = unsealJson(
1015
+ outcome.row.tokens,
1016
+ await getAppSecret(),
1017
+ `account-link:${input.provider}`,
1018
+ ) as LinkTokens;
1019
+ await input.revoke(tokens);
1020
+ } catch (err) {
1021
+ input.logger?.warn("accountLink token revoke failed", {
1022
+ provider: input.provider,
1023
+ providerUserId: input.providerUserId,
1024
+ error: err instanceof Error ? err.message : String(err),
1025
+ });
1026
+ }
1027
+ }
1028
+
1029
+ const at = (outcome.row.unlinkedAt ?? new Date()).toISOString();
1030
+ const ctx: AfterUnlinkContext = {
1031
+ provider: input.provider,
1032
+ providerUserId: input.providerUserId,
1033
+ contactId: outcome.row.contactId,
1034
+ userId: outcome.owner.userId,
1035
+ email: outcome.owner.email,
1036
+ reason: input.reason,
1037
+ version: record.version,
1038
+ at,
1039
+ };
1040
+ await invokeAfterHook(
1041
+ "afterUnlink",
1042
+ input.hooks?.afterUnlink && (() => input.hooks?.afterUnlink?.(ctx)),
1043
+ input.logger,
1044
+ { provider: input.provider, providerUserId: input.providerUserId },
1045
+ );
1046
+
1047
+ return {
1048
+ status: "unlinked",
1049
+ row: record,
1050
+ version: record.version,
1051
+ owner: outcome.owner,
1052
+ };
1053
+ }
1054
+
1055
+ /**
1056
+ * Transaction-scoped unlink, for a caller that ALREADY holds a transaction.
1057
+ * Its ONLY caller outside this module is PRD 04's contact merge, which holds
1058
+ * contact-key advisory locks and therefore cannot call the public
1059
+ * `unlinkAccount`: on a different connection it blocks forever on the merge's
1060
+ * row locks, and on the same connection it nests (DECISIONS §7).
1061
+ *
1062
+ * Takes the pair lock RE-ENTRANTLY (advisory xact locks are re-entrant within
1063
+ * one transaction), bumps the version with the same
1064
+ * `COALESCE(MAX(version), 0) + 1`, soft-unlinks. It does NOTHING else: no
1065
+ * transaction of its own, no hooks, no outbound events, no token revoke. Its
1066
+ * lifecycle is the caller's, so a caller rollback erases it.
1067
+ *
1068
+ * The public `unlinkAccount` is a thin wrapper opening the transaction and
1069
+ * adding the hook/revoke posture around the same core.
1070
+ */
1071
+ export async function unlinkAccountInTx(
1072
+ tx: Tx,
1073
+ opts: {
1074
+ rowId: string;
1075
+ provider: string;
1076
+ providerUserId: string;
1077
+ reason: "player" | "api" | "relinked";
1078
+ /** Same guard as the public entry point, evaluated under the pair lock. */
1079
+ expectContactId?: string;
1080
+ },
1081
+ ): Promise<UnlinkAccountInTxResult> {
1082
+ const outcome = await unlinkCore(tx, {
1083
+ provider: opts.provider,
1084
+ providerUserId: opts.providerUserId,
1085
+ reason: opts.reason,
1086
+ expectContactId: opts.expectContactId,
1087
+ expectRowId: opts.rowId,
1088
+ });
1089
+ if (outcome.status !== "unlinked") return outcome;
1090
+ return {
1091
+ status: "unlinked",
1092
+ version: String(outcome.row.version),
1093
+ owner: outcome.owner,
1094
+ };
1095
+ }
1096
+
1097
+ /**
1098
+ * One unlink the contact-deletion leg performed (PRD 04 T5). The facts PRD 08
1099
+ * needs to emit `account.unlinked` post-commit without re-reading the
1100
+ * database. `version` is a STRING end to end (DECISIONS §5.1).
1101
+ */
1102
+ export interface ContactUnlinkFact {
1103
+ provider: string;
1104
+ providerUserId: string;
1105
+ version: string;
1106
+ contactId: string;
1107
+ owner: LinkOwner;
1108
+ reason: "api";
1109
+ }
1110
+
1111
+ /**
1112
+ * Soft-unlink EVERY live link a contact holds, inside the caller's transaction.
1113
+ * The caller is contact deletion: `softDeleteContact` and the admin delete
1114
+ * route. Nothing in this repo hard-deletes a contact, so without this a live
1115
+ * link outlives its owner forever — the pair stays owned by a dead contact, and
1116
+ * under `onConflict: "reject"` an erased player can NEVER relink their own
1117
+ * platform account (DECISIONS §15.3). Each row gets its own pair's next version
1118
+ * under that pair's advisory lock, exactly like the merge leg, so a consumer's
1119
+ * monotonic guard accepts the unlink.
1120
+ *
1121
+ * The token blob is HARD-deleted on the unlinked rows unconditionally: a
1122
+ * sealed grant belonging to a deleted person is retained secret material with
1123
+ * no owner to revoke it. When `erase` is set (the admin delete route, which
1124
+ * also deletes identity aliases), the personal display fields
1125
+ * (`verified_email`, `username`, `avatar_url`) are nulled on EVERY row for the
1126
+ * contact, live and historical — the version sequence survives erasure so the
1127
+ * pair stays monotonic; the personal data does not.
1128
+ *
1129
+ * ALL pair locks are taken sorted+deduped BEFORE the first mutation (the same
1130
+ * deadlock rule as `linkAccount`'s two-pair replace: a delete can touch many
1131
+ * pairs at once). Idempotent by construction: a second call finds no live rows
1132
+ * and returns an empty array. Opens no transaction, invokes no hook, emits
1133
+ * nothing — its lifecycle is the caller's.
1134
+ */
1135
+ export async function unlinkAccountsForContactInTx(
1136
+ tx: Tx,
1137
+ contactId: string,
1138
+ opts: { reason: "api"; erase?: boolean },
1139
+ ): Promise<ContactUnlinkFact[]> {
1140
+ const liveRows = await tx
1141
+ .select({
1142
+ id: linkedAccounts.id,
1143
+ provider: linkedAccounts.provider,
1144
+ providerUserId: linkedAccounts.providerUserId,
1145
+ })
1146
+ .from(linkedAccounts)
1147
+ .where(
1148
+ and(
1149
+ eq(linkedAccounts.contactId, contactId),
1150
+ isNull(linkedAccounts.unlinkedAt),
1151
+ ),
1152
+ );
1153
+
1154
+ await lockPairs(
1155
+ tx,
1156
+ liveRows.map((r) => pairLockKey(r.provider, r.providerUserId)),
1157
+ );
1158
+
1159
+ const facts: ContactUnlinkFact[] = [];
1160
+ const unlinkedIds: string[] = [];
1161
+ for (const row of liveRows) {
1162
+ const outcome = await unlinkCore(tx, {
1163
+ provider: row.provider,
1164
+ providerUserId: row.providerUserId,
1165
+ reason: opts.reason,
1166
+ // A pair that mutated between the read above and the lock (unlinked,
1167
+ // or relinked to a NEW row) is legitimately not ours anymore — skip it
1168
+ // rather than unlink someone else's just-proven link.
1169
+ expectRowId: row.id,
1170
+ expectContactId: contactId,
1171
+ });
1172
+ if (outcome.status !== "unlinked") continue;
1173
+ unlinkedIds.push(outcome.row.id);
1174
+ facts.push({
1175
+ provider: row.provider,
1176
+ providerUserId: row.providerUserId,
1177
+ // BigInt → String is lossless; never Number()/parseInt (DECISIONS §5.1).
1178
+ version: String(outcome.row.version),
1179
+ contactId,
1180
+ owner: outcome.owner,
1181
+ reason: opts.reason,
1182
+ });
1183
+ }
1184
+
1185
+ if (unlinkedIds.length > 0) {
1186
+ await tx
1187
+ .update(linkedAccounts)
1188
+ .set({ tokens: null, updatedAt: new Date() })
1189
+ .where(inArray(linkedAccounts.id, unlinkedIds));
1190
+ }
1191
+
1192
+ if (opts.erase) {
1193
+ await tx
1194
+ .update(linkedAccounts)
1195
+ .set({
1196
+ tokens: null,
1197
+ verifiedEmail: null,
1198
+ username: null,
1199
+ avatarUrl: null,
1200
+ updatedAt: new Date(),
1201
+ })
1202
+ .where(eq(linkedAccounts.contactId, contactId));
1203
+ }
1204
+
1205
+ return facts;
1206
+ }
1207
+
1208
+ // ---------------------------------------------------------------------------
1209
+ // Read helpers (PRD 09's routes call these; they never hand-roll a query)
1210
+ // ---------------------------------------------------------------------------
1211
+
1212
+ export async function getLiveLink(opts: {
1213
+ db: Database;
1214
+ provider: string;
1215
+ providerUserId: string;
1216
+ }): Promise<LinkedAccountRecord | null> {
1217
+ const [row] = await opts.db
1218
+ .select()
1219
+ .from(linkedAccounts)
1220
+ .where(
1221
+ and(
1222
+ eq(linkedAccounts.provider, opts.provider),
1223
+ eq(linkedAccounts.providerUserId, opts.providerUserId),
1224
+ isNull(linkedAccounts.unlinkedAt),
1225
+ ),
1226
+ )
1227
+ .limit(1);
1228
+ return row ? toLinkedAccountRecord(row) : null;
1229
+ }
1230
+
1231
+ export async function listLiveLinksForContact(opts: {
1232
+ db: Database;
1233
+ contactId: string;
1234
+ }): Promise<LinkedAccountRecord[]> {
1235
+ const rows = await opts.db
1236
+ .select()
1237
+ .from(linkedAccounts)
1238
+ .where(
1239
+ and(
1240
+ eq(linkedAccounts.contactId, opts.contactId),
1241
+ isNull(linkedAccounts.unlinkedAt),
1242
+ ),
1243
+ )
1244
+ .orderBy(linkedAccounts.provider, linkedAccounts.providerUserId);
1245
+ return rows.map(toLinkedAccountRecord);
1246
+ }
1247
+
1248
+ /**
1249
+ * The pull plane's list read (PRD 09 T3): live links filtered by contact
1250
+ * and/or provider, NEWEST FIRST, paginated. Strongly consistent by
1251
+ * construction — it reads the live row, never a cached mirror (DECISIONS
1252
+ * §3.2).
1253
+ *
1254
+ * At least one of `contactId` / `provider` is always supplied by the route
1255
+ * (the no-filter request is a 400 there, not a full-table scan here), but this
1256
+ * function does not enforce that: it is a read helper, and a caller that wants
1257
+ * every live link is asking a legitimate question with a bounded `limit`.
1258
+ */
1259
+ export async function listLiveLinks(opts: {
1260
+ db: Database;
1261
+ contactId?: string;
1262
+ provider?: string;
1263
+ limit?: number;
1264
+ offset?: number;
1265
+ }): Promise<LinkedAccountRecord[]> {
1266
+ const rows = await opts.db
1267
+ .select()
1268
+ .from(linkedAccounts)
1269
+ .where(
1270
+ and(
1271
+ isNull(linkedAccounts.unlinkedAt),
1272
+ ...(opts.contactId
1273
+ ? [eq(linkedAccounts.contactId, opts.contactId)]
1274
+ : []),
1275
+ ...(opts.provider ? [eq(linkedAccounts.provider, opts.provider)] : []),
1276
+ ),
1277
+ )
1278
+ .orderBy(desc(linkedAccounts.linkedAt), desc(linkedAccounts.id))
1279
+ .limit(opts.limit ?? 50)
1280
+ .offset(opts.offset ?? 0);
1281
+ return rows.map(toLinkedAccountRecord);
1282
+ }
1283
+
1284
+ export async function listLinkHistory(opts: {
1285
+ db: Database;
1286
+ provider: string;
1287
+ providerUserId: string;
1288
+ }): Promise<LinkedAccountRecord[]> {
1289
+ const rows = await opts.db
1290
+ .select()
1291
+ .from(linkedAccounts)
1292
+ .where(
1293
+ and(
1294
+ eq(linkedAccounts.provider, opts.provider),
1295
+ eq(linkedAccounts.providerUserId, opts.providerUserId),
1296
+ ),
1297
+ )
1298
+ .orderBy(desc(linkedAccounts.version));
1299
+ return rows.map(toLinkedAccountRecord);
1300
+ }