@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
@@ -25,7 +25,7 @@ import { Webhook } from "svix";
25
25
  */
26
26
 
27
27
  /**
28
- * The 31-event catalog — the SINGLE source of truth (schema, routes, client,
28
+ * The 35-event catalog — the SINGLE source of truth (schema, routes, client,
29
29
  * CLI all derive from this). The `webhook.test` sentinel is intentionally NOT a
30
30
  * member (it is delivered out-of-band regardless of an endpoint's `eventTypes`).
31
31
  *
@@ -49,6 +49,16 @@ import { Webhook } from "svix";
49
49
  * visitor reported back from the destination (opt-in `hs_ref` +
50
50
  * POST /v1/t/arrive) with identity evidence.
51
51
  *
52
+ * The `account.*` family reports a player's third-party platform account
53
+ * (`defineAccountLink`: Steam, Twitch, …) being bound to or released from a
54
+ * contact. `account.linked` and `account.unlinked` are the two STATE events —
55
+ * each carries the FULL current state including `{ state, version }`, never a
56
+ * delta, so a subscriber upserts on `(provider, providerUserId)` and applies
57
+ * only when `incoming.version > stored.version`. `account.link_failed` reports
58
+ * a flow that ended without mutating anything, so it carries no version and
59
+ * never mints a contact. Like `group.*`, all three are emitted from the
60
+ * intent-layer link/unlink call sites ONLY — never from the ingest path.
61
+ *
52
62
  * `impact.digest` is the weekly facts-only impact rollup (shipped journey
53
63
  * versions/labels + holdout-lift threshold crossings). It is the one
54
64
  * SELF-REFERENTIAL event: the digest cron derives its watermark from its
@@ -74,6 +84,13 @@ export const WEBHOOK_EVENT_TYPES = [
74
84
  "email.action",
75
85
  "email.bounced",
76
86
  "email.complained",
87
+ // A human REPLIED to a message a journey sent (PRD 16). The only email event
88
+ // here that reports a message coming BACK rather than the fate of one going
89
+ // out, and the only one whose payload can be uncorrelated: a reply whose
90
+ // `In-Reply-To` names no send this instance made is still delivered, with
91
+ // `correlated: false` and null send context, because dropping a human's words
92
+ // to keep a payload tidy is the worse failure.
93
+ "email.replied",
77
94
  "sms.sent",
78
95
  "sms.delivered",
79
96
  "sms.failed",
@@ -94,6 +111,13 @@ export const WEBHOOK_EVENT_TYPES = [
94
111
  "group.identified",
95
112
  "group.member_added",
96
113
  "group.member_removed",
114
+ // Third-party platform account links (`defineAccountLink`). Emitted from the
115
+ // intent layer ONLY (the link/unlink call sites), never the ingest path.
116
+ // The two STATE events carry full current state + a monotonic `version`;
117
+ // `account.link_failed` mutated nothing, so it carries neither.
118
+ "account.linked",
119
+ "account.unlinked",
120
+ "account.link_failed",
97
121
  // Weekly impact digest (impact experiments D5). Self-referential: the
98
122
  // cron watermarks off its own delivery rows.
99
123
  "impact.digest",
@@ -0,0 +1,597 @@
1
+ import {
2
+ AccountLinkCallbackError,
3
+ type BeforeLinkContext,
4
+ type LinkedIdentity,
5
+ } from "@hogsend/core";
6
+ import { contacts, type Database } from "@hogsend/db";
7
+ import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
8
+ import { and, eq, isNull } from "drizzle-orm";
9
+ import type { AppEnv } from "../../app.js";
10
+ import { buildLinkFailedPayload } from "../../lib/account-link-events.js";
11
+ import { runBeforeLink } from "../../lib/account-link-hooks.js";
12
+ import { ingestAccountLinkFailed } from "../../lib/account-link-ingest.js";
13
+ import { burnAccountLinkNonce } from "../../lib/account-link-nonce.js";
14
+ import { isAllowedReturnTo } from "../../lib/account-link-origins.js";
15
+ import { takePkceVerifier } from "../../lib/account-link-pkce.js";
16
+ import { checkAccountLinkThrottle } from "../../lib/account-link-throttle.js";
17
+ import { getLiveLink, linkAccount } from "../../lib/account-links.js";
18
+ import { verifyConnectorState } from "../../lib/connector-state.js";
19
+ import {
20
+ collidesWithIdentified,
21
+ PublishableAnonymousMergeError,
22
+ resolveOrCreateContact,
23
+ } from "../../lib/contacts.js";
24
+ import { emitOutbound } from "../../lib/outbound.js";
25
+ import { getRedisIfConnected } from "../../lib/redis.js";
26
+ import { type AccountLinkEmitContext, noteLinked } from "./emit.js";
27
+ import { accountLinkErrorPage, accountLinkSuccessPage } from "./pages.js";
28
+ import {
29
+ accountLinkCallbackRedirectUri,
30
+ accountLinkClientIp,
31
+ } from "./shared.js";
32
+
33
+ /**
34
+ * `GET /v1/accounts/:provider/callback` — the ONE place in the whole feature
35
+ * where a link may MOVE (DECISIONS §6.1). Everything else — the import path,
36
+ * the SDK, the manage page — is structurally unable to displace a live owner,
37
+ * because only this route ever passes `allowDisplaceLiveOwner: true`, and only
38
+ * on the WARM path.
39
+ *
40
+ * The order below mirrors `routes/connectors/index.ts:100-159` step for step,
41
+ * because that dispatcher's hardening is the thing being reused rather than
42
+ * re-derived: verify BEFORE dispatching, reject a cross-surface state, burn the
43
+ * nonce single-use. The two deliberate divergences are commented at their
44
+ * sites: a null Redis REFUSES here (fail closed), and the contact side of the
45
+ * link is decided here rather than by the store.
46
+ */
47
+
48
+ export function registerAccountLinkCallbackRoute(router: OpenAPIHono<AppEnv>) {
49
+ router.openapi(
50
+ createRoute({
51
+ method: "get",
52
+ path: "/{provider}/callback",
53
+ tags: ["Account links"],
54
+ summary: "Complete a hosted account link",
55
+ request: { params: z.object({ provider: z.string() }) },
56
+ responses: {
57
+ 200: { description: "Linked — the hosted success page" },
58
+ 302: { description: "Linked — redirect to the allowlisted returnTo" },
59
+ 400: { description: "Refused — the hosted error page" },
60
+ 404: { description: "Unknown provider" },
61
+ 429: { description: "Throttled" },
62
+ 503: { description: "Redis unavailable (fail closed)" },
63
+ },
64
+ }),
65
+ async (c) => {
66
+ const { provider: providerId } = c.req.valid("param");
67
+ const container = c.get("container");
68
+ const {
69
+ accountLinkProviders,
70
+ accountLinkAllowedOrigins,
71
+ accountLinkHooks,
72
+ analytics,
73
+ db,
74
+ env,
75
+ hatchet,
76
+ logger,
77
+ registry,
78
+ } = container;
79
+
80
+ // (1) Provider.
81
+ const provider = accountLinkProviders.get(providerId);
82
+ if (!provider) return c.json({ error: "unknown_provider" }, 404);
83
+ const fail: AccountLinkEmitContext = {
84
+ providerId,
85
+ db,
86
+ hatchet,
87
+ logger,
88
+ registry,
89
+ ...(analytics ? { analytics } : {}),
90
+ };
91
+ const errorPage = () =>
92
+ c.html(accountLinkErrorPage(provider.meta.name), 400);
93
+
94
+ // (2) Redis, FAIL-CLOSED. See `lib/account-link-nonce.ts` for why this
95
+ // diverges from the connector callback's degrade-to-TTL posture.
96
+ if (!getRedisIfConnected()) {
97
+ logger.error(
98
+ "account link callback refused: redis is not connected — the " +
99
+ "single-use nonce burn cannot run, and a TTL-replayable " +
100
+ "account-link state can MOVE a link. Set REDIS_URL",
101
+ { provider: providerId },
102
+ );
103
+ return c.json({ error: "unavailable" }, 503);
104
+ }
105
+
106
+ // (3) Throttle. This endpoint is public and does real work (a code
107
+ // exchange, a DB write), so it is budgeted before any of it happens.
108
+ const ip = accountLinkClientIp(c);
109
+ const budget = await checkAccountLinkThrottle({
110
+ surface: "callback",
111
+ ip,
112
+ });
113
+ if (!budget.ok) {
114
+ return budget.reason === "rate_limited"
115
+ ? c.json({ error: "rate_limited" }, 429)
116
+ : c.json({ error: "unavailable" }, 503);
117
+ }
118
+
119
+ const url = new URL(c.req.url);
120
+ const query = Object.fromEntries(url.searchParams.entries());
121
+
122
+ // (4) VERIFY BEFORE DISPATCHING. A missing/forged/expired state never
123
+ // reaches the provider: no code is exchanged, no `beforeLink` runs, no
124
+ // contact is touched. This is the same rule (and the same comment) as the
125
+ // connector callback, and it is what makes "never calls handleCallback on
126
+ // a bad state" an assertion rather than a hope.
127
+ const stateToken = query.state ?? "";
128
+ const check = verifyConnectorState(stateToken, env.BETTER_AUTH_SECRET);
129
+ if (!check.valid || !check.intent) {
130
+ logger.warn("account link callback: invalid state", {
131
+ provider: providerId,
132
+ reason: check.reason,
133
+ });
134
+ // `contactId: null` — a state that did not verify carries nothing
135
+ // trustworthy, and a failure NEVER mints a contact (DECISIONS §8).
136
+ noteLinkFailed(fail, "state_invalid", null);
137
+ return errorPage();
138
+ }
139
+ const intent = check.intent;
140
+
141
+ // (5) Purpose. One secret signs every state in the process, so a
142
+ // `member_link` state is signature-valid here too.
143
+ if (intent.purpose !== "account_link") {
144
+ logger.warn("account link callback: wrong state purpose", {
145
+ provider: providerId,
146
+ purpose: intent.purpose,
147
+ });
148
+ noteLinkFailed(fail, "state_invalid", null);
149
+ return errorPage();
150
+ }
151
+
152
+ // (6) Cross-provider replay: a state minted for steam, presented at
153
+ // /twitch/callback, is signature-valid and must still be refused.
154
+ if (intent.providerId !== providerId) {
155
+ logger.warn("account link callback: state provider mismatch", {
156
+ routeProviderId: providerId,
157
+ stateProviderId: intent.providerId,
158
+ });
159
+ noteLinkFailed(fail, "state_invalid", null);
160
+ return errorPage();
161
+ }
162
+
163
+ // (7) SINGLE-USE. The signed state is otherwise replayable until `exp`,
164
+ // and a replayed account-link callback can MOVE a platform account
165
+ // between contacts. A null/faulting Redis is a REJECT here, not a bypass.
166
+ if (!(await burnAccountLinkNonce(intent.nonce))) {
167
+ logger.warn("account link callback: state replay rejected", {
168
+ provider: providerId,
169
+ });
170
+ noteLinkFailed(
171
+ fail,
172
+ "state_invalid",
173
+ intent.contactId ?? null,
174
+ intent.anonymousId,
175
+ );
176
+ return errorPage();
177
+ }
178
+
179
+ // (8) PKCE custody, consumed with GETDEL. A declared-PKCE provider whose
180
+ // verifier is missing cannot prove what the flow claims it proves.
181
+ let codeVerifier: string | undefined;
182
+ if (provider.capabilities?.pkce) {
183
+ const verifier = await takePkceVerifier(intent.nonce);
184
+ if (!verifier) {
185
+ logger.warn(
186
+ "account link callback: no PKCE verifier for this state",
187
+ {
188
+ provider: providerId,
189
+ },
190
+ );
191
+ noteLinkFailed(
192
+ fail,
193
+ "state_invalid",
194
+ intent.contactId ?? null,
195
+ intent.anonymousId,
196
+ );
197
+ return errorPage();
198
+ }
199
+ codeVerifier = verifier;
200
+ }
201
+
202
+ // (9) The proof. The provider maps a denial to
203
+ // `AccountLinkCallbackError{denied}` itself (PRD 01 T3/T4), so this route
204
+ // does NOT sniff for `error=access_denied` or `openid.mode=cancel` — it
205
+ // reads `err.reason` verbatim, which is why that union is deliberately
206
+ // the `link_failed` reasons minus `"vetoed"`.
207
+ //
208
+ // No `fetchImpl` is passed: the presets resolve `fetchImpl ??
209
+ // globalThis.fetch`, and tests inject at the provider instead of through
210
+ // a container-level fetch seam that production would never use.
211
+ let identity: LinkedIdentity;
212
+ try {
213
+ identity = await provider.handleCallback({
214
+ query,
215
+ redirectUri: accountLinkCallbackRedirectUri({
216
+ apiPublicUrl: env.API_PUBLIC_URL,
217
+ providerId,
218
+ state: stateToken,
219
+ query,
220
+ }),
221
+ ...(codeVerifier ? { codeVerifier } : {}),
222
+ });
223
+ } catch (err) {
224
+ const reason =
225
+ err instanceof AccountLinkCallbackError
226
+ ? err.reason
227
+ : "exchange_failed";
228
+ // The MESSAGE only. An OAuth error body can carry a token, so a
229
+ // provider must never interpolate one into its message and this must
230
+ // never log a body.
231
+ logger.warn("account link callback: provider refused", {
232
+ provider: providerId,
233
+ reason,
234
+ error: err instanceof Error ? err.message : "unknown error",
235
+ });
236
+ noteLinkFailed(
237
+ fail,
238
+ reason,
239
+ intent.contactId ?? null,
240
+ intent.anonymousId,
241
+ );
242
+ return errorPage();
243
+ }
244
+
245
+ // Who owns this platform account RIGHT NOW — read once, for the hook's
246
+ // `currentOwnerContactId` so a customer rule can refuse a takeover. It is
247
+ // a hint, not a decision: the store re-reads it inside the pair lock.
248
+ const liveOwner = await getLiveLink({
249
+ db,
250
+ provider: providerId,
251
+ providerUserId: identity.providerUserId,
252
+ });
253
+
254
+ // (10) THE VETO, pre-write and fail-closed. On the COLD path
255
+ // `ctx.contactId` is null and `anonymousId` is the key: no contact has
256
+ // been resolved yet, deliberately, so a veto cannot leave a ghost contact
257
+ // behind. `identity.tokens` exists only as a local from here on and is
258
+ // handed to the store ONLY after this allows — LOAD-BEARING: hoisting a
259
+ // token seal above this hook would persist grant material for a link the
260
+ // customer refused.
261
+ const warm = intent.contactId !== undefined;
262
+ let contactFacts: { userId: string | null; email: string | null } = {
263
+ userId: null,
264
+ email: null,
265
+ };
266
+ if (warm) {
267
+ const facts = await readContactFacts(db, intent.contactId as string);
268
+ if (!facts) {
269
+ // The sealed contact is gone (or soft-deleted) since the mint. A
270
+ // state TTL is 15 minutes and a contact deletion unlinks everything
271
+ // it owned (DECISIONS §15.3), so re-attaching here would resurrect a
272
+ // link on a dead row — and `linked_accounts.contact_id` is a NOT NULL
273
+ // FK, so the alternative is an unhandled 500 on a player's callback.
274
+ logger.warn(
275
+ "account link callback: the sealed contact no longer exists",
276
+ { provider: providerId },
277
+ );
278
+ noteLinkFailed(fail, "state_invalid", null);
279
+ return errorPage();
280
+ }
281
+ contactFacts = facts;
282
+ }
283
+ const beforeCtx: BeforeLinkContext = {
284
+ provider: providerId,
285
+ identity,
286
+ contactId: warm ? (intent.contactId as string) : null,
287
+ ...(warm ? {} : { anonymousId: intent.anonymousId }),
288
+ userId: contactFacts.userId,
289
+ email: contactFacts.email,
290
+ // WARM only. On the cold path `intent.contactId` is undefined, so
291
+ // `liveOwner.contactId !== intent.contactId` is true for EVERY live
292
+ // owner — including the visitor's own contact. A consumer shipping the
293
+ // documented takeover guard (`ctx.currentOwnerContactId ? refuse`)
294
+ // would then veto a player re-linking an account they already own: link
295
+ // cold, click Link again, get "we couldn't link your account" plus an
296
+ // account.link_failed{vetoed} for a link they hold.
297
+ //
298
+ // Cold deliberately has no resolved contact at hook time (veto before
299
+ // mint), so "a DIFFERENT owner" is unknowable here — and does not need
300
+ // to be: cold passes `allowDisplaceLiveOwner: false`, so the store
301
+ // itself refuses a real cold takeover with `live_owner_conflict`.
302
+ ...(warm && liveOwner && liveOwner.contactId !== intent.contactId
303
+ ? { currentOwnerContactId: liveOwner.contactId }
304
+ : {}),
305
+ };
306
+ const verdict = await runBeforeLink({
307
+ hooks: accountLinkHooks,
308
+ ctx: beforeCtx,
309
+ logger,
310
+ });
311
+ if (!verdict.allow) {
312
+ // Return BEFORE the store call. Nothing is sealed, nothing is written,
313
+ // and on the cold path no contact was ever resolved.
314
+ noteLinkFailed(
315
+ fail,
316
+ "vetoed",
317
+ warm ? (intent.contactId ?? null) : null,
318
+ warm ? undefined : intent.anonymousId,
319
+ );
320
+ return errorPage();
321
+ }
322
+
323
+ // (11) The contact side. WARM: the sealed id, used as is — the
324
+ // provider-reported email is NEVER a resolution key (DECISIONS §6.3), it
325
+ // rides `identity` into the store as a display property only.
326
+ //
327
+ // COLD: resolved HERE, strictly AFTER the veto and strictly BEFORE
328
+ // `linkAccount` opens its pair-lock transaction —
329
+ // `resolveOrCreateContact` takes its OWN contact-key advisory locks
330
+ // (`lib/contacts.ts`), so calling it inside the pair lock reintroduces the
331
+ // exact deadlock `unlinkAccountInTx` exists to avoid.
332
+ let contactId: string;
333
+ if (warm) {
334
+ contactId = intent.contactId as string;
335
+ } else {
336
+ const anonymousId = intent.anonymousId;
337
+ if (!anonymousId) {
338
+ // An account_link state always carries exactly one binding; a state
339
+ // with neither is malformed regardless of its signature.
340
+ logger.warn("account link callback: state carries no binding", {
341
+ provider: providerId,
342
+ });
343
+ noteLinkFailed(fail, "state_invalid", null);
344
+ return errorPage();
345
+ }
346
+ try {
347
+ // The `allowMerge: "anonymous-only"` clamp below stops a cold link
348
+ // ATTACHING to an identified victim. It does NOT stop a cold link
349
+ // MINTING a doppelganger, and that is the actual takeover:
350
+ //
351
+ // victim: external_id = "user_42", anonymous_id NULL
352
+ // attacker: /start?anonymous_id=user_42, then proves THEIR steam
353
+ //
354
+ // No candidate matches (the victim's key lives in `external_id`), so
355
+ // the clamp is never consulted and a NEW contact is inserted with
356
+ // `anonymous_id = "user_42"`. Canonical key is
357
+ // `external_id ?? anonymous_id ?? id`, so that row's `userId` IS the
358
+ // victim's player id — and `afterLink` hands the publisher
359
+ // `{ userId: "user_42", providerUserId: <attacker's steamid> }`. The
360
+ // documented "grant the reward" integration then entitles the
361
+ // attacker's Steam account as the victim. Same shape with the
362
+ // victim's email when they carry no external_id.
363
+ //
364
+ // `collidesWithIdentified` is the guard the engine already ships for
365
+ // the other token-less anon-id-accepting surfaces (feed/recipient.ts,
366
+ // tracking/arrive.ts): it sees what the anonymous-only clamp cannot —
367
+ // the value being a live contact's external_id or email, or a merged
368
+ // loser's stale non-anonymous alias.
369
+ if (await collidesWithIdentified(db, anonymousId)) {
370
+ throw new PublishableAnonymousMergeError();
371
+ }
372
+ const resolved = await resolveOrCreateContact({
373
+ db,
374
+ anonymousId,
375
+ // ALL THREE fields are spelled out because ALL THREE are required
376
+ // and the DEFAULT is catastrophic here: no policy means
377
+ // `allowMerge: "any"` with `trustedKinds: ALL_IDENTITY_KINDS`,
378
+ // which FILLS IN a link onto whatever contact already owns that
379
+ // anon alias — INCLUDING AN IDENTIFIED VICTIM'S. `anonymous_id`
380
+ // arrives on an unauthenticated URL and is browser-readable by
381
+ // design, so on the cold path the proof is of the PLATFORM
382
+ // account, never of the contact (DECISIONS §6.10).
383
+ policy: {
384
+ // Minting here is legitimate and is NOT the ghost-contact case
385
+ // `resolveContactNoCreate` exists for: a proven platform-account
386
+ // link is an identity ASSERTION, not an observation. Cold Steam
387
+ // is the sharp case — Steam yields no email ever, so the
388
+ // resulting contact is anon-keyed until the player identifies,
389
+ // at which point `adoptOrphanHistory` stamps their anon-keyed
390
+ // history (the `linked_accounts` row itself needs nothing from
391
+ // that path: `contact_id` is NOT NULL there, so it is a proven
392
+ // no-op, and PRD 04's merge leg repoints the row). The clamp
393
+ // that keeps this honest is `allowMerge`, not a refusal to
394
+ // create.
395
+ create: "on-miss",
396
+ allowMerge: "anonymous-only",
397
+ trustedKinds: ["anonymous"],
398
+ },
399
+ });
400
+ contactId = resolved.id;
401
+ } catch (err) {
402
+ if (err instanceof PublishableAnonymousMergeError) {
403
+ // A HARD REFUSAL. Not a fallback, not a retry with a fresh key,
404
+ // not "mint a new contact instead": the only way to get here is an
405
+ // `anonymous_id` naming a contact a cold flow may not touch.
406
+ logger.warn(
407
+ "account link callback: cold anonymous_id names a contact a " +
408
+ "cold link may not attach to — refused",
409
+ { provider: providerId },
410
+ );
411
+ noteLinkFailed(fail, "state_invalid", null);
412
+ return errorPage();
413
+ }
414
+ throw err;
415
+ }
416
+ }
417
+
418
+ // (12) The write. PRD 03's frozen `LinkAccountInput`, field for field.
419
+ // `multiple` / `onConflict` / `storeTokens` come from the provider
420
+ // definition with the CALLER applying the defaults, and
421
+ // `allowDisplaceLiveOwner` is TRUE only on the WARM path — a cold link
422
+ // may never take a platform account off its current owner, because the
423
+ // contact side of a cold link is an anon id typed into an
424
+ // unauthenticated URL.
425
+ //
426
+ // `hooks` is the container's, and passing it in is how the consumer's
427
+ // post-commit hook runs BEFORE the success page renders: the STORE
428
+ // invokes it, post-commit, inside this await. This route invokes no
429
+ // post-commit hook itself (DECISIONS §15.4) — a second invoker would
430
+ // fire every customer hook twice, and because the hooks are documented
431
+ // at-least-once nothing would fail loudly. That is also why
432
+ // `grep -rn "after" this directory finds no hook call: it is a
433
+ // reviewable invariant, not a convention.
434
+ const result = await linkAccount({
435
+ db,
436
+ provider: providerId,
437
+ identity,
438
+ contactId,
439
+ method: "oauth",
440
+ multiple: provider.multiple ?? true,
441
+ onConflict: provider.onConflict ?? "replace",
442
+ storeTokens: provider.capabilities?.tokens === true,
443
+ allowDisplaceLiveOwner: warm,
444
+ hooks: accountLinkHooks,
445
+ logger,
446
+ });
447
+
448
+ if (result.status === "rejected") {
449
+ logger.warn("account link callback: store refused the link", {
450
+ provider: providerId,
451
+ reason: result.reason,
452
+ });
453
+ return errorPage();
454
+ }
455
+
456
+ // (13) `account.linked` is emitted from HERE, the intent layer, off the
457
+ // facts the store returned (including its `owner` block). The store never
458
+ // emits — the `lib/groups.ts` precedent, DECISIONS §8/§15.7.
459
+ //
460
+ // `unchanged` is deliberately NOT an emit: the same contact re-proving
461
+ // the same platform account is a display refresh, not a state
462
+ // transition. It consumed no version, so an emit here would announce a
463
+ // change that did not happen and (with no new version) would be deduped
464
+ // against the previous one anyway.
465
+ if (result.status !== "unchanged") noteLinked(fail, result);
466
+
467
+ // (14) Land the player. `returnTo` is re-checked against the allowlist AT
468
+ // REDIRECT TIME: the state proves we minted the value, not that it is
469
+ // still permitted, and the allowlist can have been edited while the
470
+ // player was on the provider's consent screen.
471
+ if (intent.returnTo) {
472
+ if (isAllowedReturnTo(intent.returnTo, accountLinkAllowedOrigins)) {
473
+ return c.redirect(intent.returnTo, 302);
474
+ }
475
+ logger.warn(
476
+ "account link callback: sealed return_to is no longer allowed — " +
477
+ "falling back to the hosted success page",
478
+ { provider: providerId },
479
+ );
480
+ }
481
+ return c.html(accountLinkSuccessPage(provider.meta.name), 200);
482
+ },
483
+ );
484
+ }
485
+
486
+ /**
487
+ * The contact's own facts for the pre-write hook context. `userId` is
488
+ * `contactKey()` (`external_id ?? anonymous_id ?? id`) — the SAME definition
489
+ * the outbound payloads and the SDK use, never raw `externalId` — and `email`
490
+ * is the CONTACT's address, never the provider-reported one.
491
+ *
492
+ * Read here rather than handed over by the store because `beforeLink` runs
493
+ * strictly BEFORE the store opens its transaction. The post-commit hook gets
494
+ * these from the store's own in-transaction join instead (DECISIONS §15.5),
495
+ * which is why only this one read exists here.
496
+ */
497
+ async function readContactFacts(
498
+ db: Database,
499
+ contactId: string,
500
+ ): Promise<{ userId: string | null; email: string | null } | null> {
501
+ const [row] = await db
502
+ .select({
503
+ id: contacts.id,
504
+ externalId: contacts.externalId,
505
+ anonymousId: contacts.anonymousId,
506
+ email: contacts.email,
507
+ })
508
+ .from(contacts)
509
+ .where(and(eq(contacts.id, contactId), isNull(contacts.deletedAt)))
510
+ .limit(1);
511
+ // NULL means "no live contact", which the caller turns into a refusal — not
512
+ // a silent link onto a row that is gone.
513
+ if (!row) return null;
514
+ return {
515
+ userId: row.externalId ?? row.anonymousId ?? row.id,
516
+ email: row.email ?? null,
517
+ };
518
+ }
519
+
520
+ /**
521
+ * THE `account.link_failed` SITE.
522
+ *
523
+ * One function rather than four inline blocks so every rejection path answers
524
+ * with the same shape and there is exactly one place the emit lives. The two
525
+ * invariants that are PRD 07's:
526
+ *
527
+ * - `contactId` is the SEALED id when the state verified, and `null` when it
528
+ * did not — a state that failed verification carries nothing trustworthy.
529
+ * - it NEVER mints a contact (DECISIONS §8). Nothing here resolves anything.
530
+ *
531
+ * NO `dedupeKey`, deliberately (DECISIONS §8): the event carries no version,
532
+ * so there is no monotonic value to key on, and two genuine failures in a row
533
+ * are two genuine facts — suppressing the second would hide a brute-force
534
+ * pattern. A NULL key is never blocked by the `(endpointId, dedupeKey)` index
535
+ * because Postgres treats multiple NULLs as distinct.
536
+ *
537
+ * `reason` is `AccountLinkCallbackError.reason` verbatim plus `"vetoed"`; PRD
538
+ * 01 froze that union as this one minus `"vetoed"` (which only the hook path
539
+ * produces), which is why no translation table exists anywhere on this path.
540
+ */
541
+ function noteLinkFailed(
542
+ fail: AccountLinkEmitContext,
543
+ reason: "denied" | "vetoed" | "exchange_failed" | "state_invalid",
544
+ contactId: string | null,
545
+ coldAnonymousId?: string,
546
+ ): void {
547
+ fail.logger.info("account link failed", {
548
+ provider: fail.providerId,
549
+ reason,
550
+ contactId,
551
+ });
552
+
553
+ // THE JOURNEY PLANE, beside the outbound one (PRD 08 T5). TWO DIFFERENT
554
+ // PLANES: this writes `user_events` + pushes to Hatchet so a journey can
555
+ // trigger on `account.link_failed`; the `emitOutbound` below writes a
556
+ // `webhook_deliveries` row for the CUSTOMER'S subscriber. Neither may be
557
+ // collapsed into the other — see the header of `lib/account-link-ingest.ts`.
558
+ //
559
+ // The SUBJECT is not the payload's `contactId` field by accident: warm uses
560
+ // the sealed (server-minted, unforgeable) id, and cold uses the state's
561
+ // `anonymous_id`, which the payload deliberately does NOT carry. A failure
562
+ // with neither — a state that did not verify, a sealed contact that is gone
563
+ // — reaches the journey plane not at all: there is nothing trustworthy to
564
+ // attribute it to, and inventing one is how a failed link mints a contact.
565
+ ingestAccountLinkFailed(
566
+ fail.db,
567
+ {
568
+ provider: fail.providerId,
569
+ reason,
570
+ subject: contactId
571
+ ? { contactId }
572
+ : coldAnonymousId
573
+ ? { anonymousId: coldAnonymousId }
574
+ : null,
575
+ },
576
+ {
577
+ hatchet: fail.hatchet,
578
+ logger: fail.logger,
579
+ ...(fail.registry ? { registry: fail.registry } : {}),
580
+ ...(fail.analytics ? { analytics: fail.analytics } : {}),
581
+ },
582
+ );
583
+ // `void … .catch` per the `emitOutbound` contract: it never throws, and the
584
+ // catch is the defence-in-depth its docstring asks every call site for. An
585
+ // emit must never fail the callback.
586
+ void emitOutbound({
587
+ db: fail.db,
588
+ hatchet: fail.hatchet,
589
+ logger: fail.logger,
590
+ event: "account.link_failed",
591
+ payload: buildLinkFailedPayload({
592
+ provider: fail.providerId,
593
+ reason,
594
+ contactId,
595
+ }),
596
+ }).catch(fail.logger.warn);
597
+ }