@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
package/src/container.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
2
2
  import type {
3
+ AccountLinkHooks,
4
+ AccountLinkProvider,
3
5
  AnalyticsEventMirrorConfig,
4
6
  AnalyticsProvider,
5
7
  ConversionDestination,
@@ -64,6 +66,9 @@ import type { DefinedJourney } from "./journeys/define-journey.js";
64
66
  import { getJourneySourceLocations } from "./journeys/journey-source-locations-singleton.js";
65
67
  import { getJourneySources } from "./journeys/journey-sources-singleton.js";
66
68
  import { buildJourneyRegistry } from "./journeys/registry.js";
69
+ import { parseAllowedOrigins } from "./lib/account-link-origins.js";
70
+ import { AccountLinkProviderRegistry } from "./lib/account-link-provider-registry.js";
71
+ import { accountLinksFromEnv } from "./lib/account-links-from-env.js";
67
72
  import {
68
73
  isAnalyticsProvider,
69
74
  wrapLegacyAnalyticsService,
@@ -210,6 +215,27 @@ export interface HogsendClient {
210
215
  * Undefined when no SMS provider is configured.
211
216
  */
212
217
  smsProvider?: SmsProvider;
218
+ /**
219
+ * The container-held registry of account-link providers (Steam, Twitch, or
220
+ * consumer-authored via `defineAccountLink`), keyed by `meta.id`. The
221
+ * `/v1/accounts/:provider/*` routes resolve providers out of this and 404 an
222
+ * unknown id. Unlike email/SMS/analytics there is NO single active provider:
223
+ * the player picks one per link, so there is no `accountLinkProvider` field,
224
+ * no `ACCOUNT_LINK_PROVIDER` env, and no "not registered" boot throw — the
225
+ * missing symmetry is deliberate. Empty when none configured (an
226
+ * unconfigured provider is ABSENT, never present-but-disabled).
227
+ */
228
+ accountLinkProviders: AccountLinkProviderRegistry;
229
+ /**
230
+ * The consumer's account-link hooks, held VERBATIM — no wrapping, no
231
+ * per-hook defaulting. The container only holds them: `beforeLink` is
232
+ * invoked by the hosted callback (PRD 07) and `afterLink`/`afterUnlink` by
233
+ * the link store (PRD 03), and by nothing else (DECISIONS §15.4). `{}` when
234
+ * none supplied.
235
+ */
236
+ accountLinkHooks: AccountLinkHooks;
237
+ /** Parsed + validated ACCOUNT_LINK_ALLOWED_ORIGINS. Empty array = none permitted. */
238
+ accountLinkAllowedOrigins: string[];
213
239
  /**
214
240
  * The container-held registry of enrichment providers, keyed by `meta.id` —
215
241
  * the enrichment sibling of {@link smsProviders}. Empty when no enrichment
@@ -460,6 +486,26 @@ export interface HogsendClientOptions {
460
486
  linkTracking?: boolean;
461
487
  linkHost?: string;
462
488
  };
489
+ /**
490
+ * Account linking (Steam, Twitch, or your own `defineAccountLink` provider).
491
+ * The engine owns the stateful flow (state tokens, the link store,
492
+ * versioning, hooks, outbound events); a provider is only the two proof
493
+ * wires (authorize URL + callback → proven identity).
494
+ */
495
+ accountLinks?: {
496
+ /** Register MANY providers. Merged AFTER env presets, so a same-id provider wins. */
497
+ providers?: AccountLinkProvider[];
498
+ /** In-process hooks. beforeLink is fail-closed; afterLink/afterUnlink fail-open (DECISIONS §9). */
499
+ hooks?: AccountLinkHooks;
500
+ /**
501
+ * Extra allowed origins, concatenated AFTER ACCOUNT_LINK_ALLOWED_ORIGINS and
502
+ * parsed by the same rule. A malformed entry THROWS at boot. This is the ONE
503
+ * allowlist: PRD 07 checks `returnTo` against it, PRD 10 uses it as the
504
+ * `postMessage` targetOrigin set, and PRD 10 validates its `resultRedirect`
505
+ * against it. PRD 10 CONSUMES this field and does not redeclare it.
506
+ */
507
+ allowedOrigins?: string[];
508
+ };
463
509
  /**
464
510
  * Enrichment (Refinement) is a first-class provider kind mirroring
465
511
  * {@link email}/{@link sms}. The engine owns the cohesive refinement
@@ -905,6 +951,77 @@ export function createHogsendClient(
905
951
  ]);
906
952
  const smsConfigured = smsProviders.count() > 0;
907
953
 
954
+ // Account-link providers (Steam / Twitch / consumer-authored). NO active-
955
+ // provider resolution here, on purpose: unlike email/SMS/analytics there is
956
+ // no single active account-link provider — the player picks one per link and
957
+ // the route resolves by the `:provider` path param — so there is no
958
+ // ACCOUNT_LINK_PROVIDER env and no "not registered" boot throw. Do not "fix"
959
+ // the missing symmetry. Duplicate ids inside ONE providers array are almost
960
+ // certainly an authoring mistake, so warn (last-writer-wins, like every
961
+ // other registry merge).
962
+ const consumerAccountLinkProviders = opts.accountLinks?.providers ?? [];
963
+ {
964
+ const seenAccountLinkIds = new Set<string>();
965
+ for (const provider of consumerAccountLinkProviders) {
966
+ const id = provider.meta?.id;
967
+ if (!id) continue; // the registry ctor below throws the real TypeError
968
+ if (seenAccountLinkIds.has(id)) {
969
+ logger.warn(
970
+ `accountLinks.providers contains "${id}" more than once — the last one wins (last-writer-wins on meta.id)`,
971
+ );
972
+ }
973
+ seenAccountLinkIds.add(id);
974
+ }
975
+ }
976
+ // Env presets FIRST, consumer last (last-writer-wins on meta.id) — the same
977
+ // merge order and reason as the email registry. The env builder returns its
978
+ // warnings rather than console.warn-ing, so they go through the real logger.
979
+ // Presets register only on operator INTENT (any ACCOUNT_LINK_* / steam env
980
+ // var, or ANY `accountLinks` option — even `{}`), keeping a deploy that
981
+ // never asked for account linking fully inert.
982
+ const accountLinkEnv = accountLinksFromEnv(env, {
983
+ consumerOptedIn: opts.accountLinks !== undefined,
984
+ });
985
+ for (const warning of accountLinkEnv.warnings) logger.warn(warning);
986
+ const accountLinkProviders = new AccountLinkProviderRegistry([
987
+ ...accountLinkEnv.providers,
988
+ ...consumerAccountLinkProviders,
989
+ ]);
990
+ const accountLinkAllowedOrigins = parseAllowedOrigins([
991
+ ...(env.ACCOUNT_LINK_ALLOWED_ORIGINS?.split(",") ?? []),
992
+ ...(opts.accountLinks?.allowedOrigins ?? []),
993
+ ]);
994
+ const accountLinkHooks: AccountLinkHooks = opts.accountLinks?.hooks ?? {};
995
+ if (
996
+ accountLinkProviders.count() > 0 &&
997
+ accountLinkAllowedOrigins.length === 0
998
+ ) {
999
+ // Providers with an empty allowlist is a legal boot (the hosted pages
1000
+ // still work) but a silently degraded one: no `returnTo` is accepted and
1001
+ // `postMessage` never fires, so the embed button spins to a timeout while
1002
+ // the link commits server-side. Say so ONCE at boot, where it is
1003
+ // diagnosable, rather than after a player closes the popup.
1004
+ logger.warn(
1005
+ "account link providers are registered but no allowed origin is configured — no returnTo will be accepted and no postMessage will be sent. Set ACCOUNT_LINK_ALLOWED_ORIGINS (or accountLinks.allowedOrigins)",
1006
+ );
1007
+ }
1008
+ // Gate on the RAW `process.env.REDIS_URL`, for the same reason the
1009
+ // better-auth secondary-storage wiring below does: `env.REDIS_URL` carries a
1010
+ // localhost default and is never empty, and the engine's Redis singleton is
1011
+ // only ever CONSTRUCTED when the raw var is set — so this is exactly the
1012
+ // condition under which `getRedisIfConnected()` is null at request time.
1013
+ if (accountLinkProviders.count() > 0 && !process.env.REDIS_URL) {
1014
+ // The hosted flow is FAIL-CLOSED on Redis (DECISIONS §6.8): PKCE custody
1015
+ // and the callback's single-use nonce burn both live there, so
1016
+ // `/v1/accounts/:provider/start` and `/callback` answer 503 without it.
1017
+ // That is a deliberate divergence from the connector callback, which
1018
+ // degrades to TTL-only validity — so say it ONCE at boot rather than
1019
+ // letting an operator discover it as a 503 on a player's link.
1020
+ logger.warn(
1021
+ "account link providers are registered but redis is not connected — the hosted flow fails closed and /v1/accounts/:provider/start and /callback will answer 503. Set REDIS_URL",
1022
+ );
1023
+ }
1024
+
908
1025
  // CRM sync providers (§Phase 4). No env presets yet — CRM credentials are
909
1026
  // per-deployment enough that construction stays consumer-side; the single
910
1027
  // `provider` merges LAST (wins an id collision with `providers`).
@@ -1650,6 +1767,9 @@ export function createHogsendClient(
1650
1767
  smsService,
1651
1768
  smsProviders,
1652
1769
  smsProvider,
1770
+ accountLinkProviders,
1771
+ accountLinkHooks,
1772
+ accountLinkAllowedOrigins,
1653
1773
  enrichmentProviders,
1654
1774
  enrichmentProvider,
1655
1775
  crmProviders,
package/src/env.ts CHANGED
@@ -230,6 +230,43 @@ export const env = createEnv({
230
230
  .int()
231
231
  .nonnegative()
232
232
  .default(0),
233
+ // --- Account links (Steam / Twitch, opt-in) ---
234
+ // Declared here (PRD 05); READ by the env presets (PRD 06). Convention:
235
+ // ACCOUNT_LINK_<PROVIDER_ID>_CLIENT_ID / _CLIENT_SECRET for OAuth pairs.
236
+ // Only the two built-ins get declared vars — this schema is STATIC, so a
237
+ // consumer-authored provider configures in CODE via the closure it passes
238
+ // to `accountLinks.providers`, never via a dynamically-named env key.
239
+ //
240
+ // Twitch: the preset is built only when BOTH id + secret are present —
241
+ // unconfigured means ABSENT from the registry, not present-but-disabled
242
+ // (the emailProvidersFromEnv rule). The client id is also sent as the
243
+ // `Client-Id` header on Helix calls.
244
+ ACCOUNT_LINK_TWITCH_CLIENT_ID: z.string().min(1).optional(),
245
+ ACCOUNT_LINK_TWITCH_CLIENT_SECRET: z.string().min(1).optional(),
246
+ // Steam Web API key — OPTIONAL, and deliberately NOT gating the provider:
247
+ // "Sign in through Steam" is OpenID 2.0, so the relying party presents no
248
+ // credential and the steam provider registers WITHOUT this key. Setting it
249
+ // only adds the profile pull (persona, avatar) and the PRD 14 playtime
250
+ // sync. Named after the key every Steam integration in the world already
251
+ // uses; an ACCOUNT_LINK_STEAM_CLIENT_SECRET name would be a lie (Steam has
252
+ // no OAuth client pair at all).
253
+ STEAM_WEB_API_KEY: z.string().min(1).optional(),
254
+ // CSV of absolute origins ("https://play.example.com,https://example.com")
255
+ // — the ONE allowlist governing both `returnTo` (PRD 07) and the
256
+ // `postMessage` targetOrigin (PRD 10). Unset ⇒ empty list ⇒ no `returnTo`
257
+ // accepted and postMessage never attempted (warned once at boot when
258
+ // providers are registered). A plain string here on purpose: the parse +
259
+ // per-entry validation lives in lib/account-link-origins.ts, OUTSIDE the
260
+ // schema, so a malformed entry THROWS at boot naming the offending entry
261
+ // rather than a generic Zod failure (the FX_RATES stance above). Never "*".
262
+ ACCOUNT_LINK_ALLOWED_ORIGINS: z.string().optional(),
263
+ // State/PKCE token TTL for the hosted link flow. 900s matches the window
264
+ // the connector nonce burn already assumes (routes/connectors/index.ts).
265
+ ACCOUNT_LINK_STATE_TTL_SECONDS: z.coerce
266
+ .number()
267
+ .int()
268
+ .positive()
269
+ .default(900),
233
270
  // Hatchet connection contract. The @hatchet-dev SDK also reads these straight
234
271
  // from process.env via its own config-loader, so this schema is a presence /
235
272
  // shape check that keeps the contract in one place — the values still flow to
package/src/index.ts CHANGED
@@ -46,10 +46,24 @@ export * from "@hogsend/core";
46
46
  // `SendEmailOptions` is the high-level journey-facing send options from
47
47
  // `./lib/email.js`; the provider-contract `SendEmailOptions` remains available
48
48
  // via `@hogsend/core`.)
49
- export {
49
+ // --- Account links: provider contract (canonical origin: @hogsend/core) ---
50
+ // Already covered by the `export * from "@hogsend/core"` above — re-named here
51
+ // for discoverability, mirroring the email/analytics contract re-exports.
52
+ export {
53
+ ACCOUNT_LINK_HOOK_TIMEOUT_MS,
54
+ ACCOUNT_LINK_ID_RE,
55
+ AccountLinkCallbackError,
56
+ type AccountLinkCapabilities,
57
+ type AccountLinkHooks,
58
+ type AccountLinkMeta,
59
+ type AccountLinkProvider,
50
60
  bySubject,
61
+ defineAccountLink,
51
62
  defineAnalyticsProvider,
52
63
  defineEmailProvider,
64
+ type LinkedIdentity,
65
+ type LinkTokens,
66
+ RESERVED_ACCOUNT_LINK_IDS,
53
67
  type Subject,
54
68
  WebhookHandshakeSignal,
55
69
  } from "@hogsend/core";
@@ -67,6 +81,15 @@ export {
67
81
  type JournalShape,
68
82
  type SchemaVersion,
69
83
  } from "@hogsend/db";
84
+ // The two built-in account-link providers — config over the @hogsend/core
85
+ // presets (DECISIONS §3.1), exported so a consumer can construct one directly
86
+ // with code-supplied config and pass it via `accountLinks.providers`.
87
+ export {
88
+ type SteamAccountLinkConfig,
89
+ steamAccountLink,
90
+ type TwitchAccountLinkConfig,
91
+ twitchAccountLink,
92
+ } from "./account-links/index.js";
70
93
  // --- App / container / worker factories ---
71
94
  export {
72
95
  type AppEnv,
@@ -292,6 +315,53 @@ export {
292
315
  getJourneyRegistrySingleton,
293
316
  setJourneyRegistry,
294
317
  } from "./journeys/registry-singleton.js";
318
+ // The one origin allowlist parser (PRD 07 `returnTo`, PRD 10 `postMessage`) —
319
+ // fail-loud at boot; the container calls it, exported for consumers/tests.
320
+ export {
321
+ isAllowedReturnTo,
322
+ parseAllowedOrigins,
323
+ } from "./lib/account-link-origins.js";
324
+ // The container-held provider registry (`client.accountLinkProviders`).
325
+ export { AccountLinkProviderRegistry } from "./lib/account-link-provider-registry.js";
326
+ // The server-side WARM minter. Returns an ENGINE-origin `/start` URL — never a
327
+ // provider authorize URL (DECISIONS §15.2). PRD 09's `POST
328
+ // /v1/accounts/link-url` returns exactly this value and PRD 13's embed derives
329
+ // its `postMessage` expectedOrigin from it.
330
+ export {
331
+ AccountLinkReturnToError,
332
+ type MintAccountLinkUrlArgs,
333
+ mintAccountLinkUrl,
334
+ } from "./lib/account-link-url.js";
335
+ // --- Account links (the link store — the ONE writer of `linked_accounts`) ---
336
+ //
337
+ // Deliberately NARROW. This barrel is the committed semver boundary for
338
+ // `@hogsend/engine`, so anything exported here is a promise we keep or
339
+ // major-bump. `lockPairs`, `pairLockKey`, `MAX_VERSION_RACE_RETRIES` and
340
+ // `AccountLinkLockSetChangedError` are the store's internal mechanics — how we
341
+ // happen to take advisory locks and signal a stale pre-read today — and the PRD
342
+ // documents the last of those as an INTERNAL retry signal. They stay module-
343
+ // private (still importable within the engine, and the tests import the module
344
+ // directly) so a change to the locking strategy is not a breaking change.
345
+ export {
346
+ AccountLinkVersionRaceError,
347
+ type ContactUnlinkFact,
348
+ type DisplacedLink,
349
+ getLiveLink,
350
+ type LinkAccountInput,
351
+ type LinkAccountResult,
352
+ type LinkedAccountRecord,
353
+ type LinkMutationStatus,
354
+ type LinkOwner,
355
+ linkAccount,
356
+ listLinkHistory,
357
+ listLiveLinksForContact,
358
+ type UnlinkAccountInput,
359
+ type UnlinkAccountInTxResult,
360
+ type UnlinkAccountResult,
361
+ unlinkAccount,
362
+ unlinkAccountInTx,
363
+ unlinkAccountsForContactInTx,
364
+ } from "./lib/account-links.js";
295
365
  // --- Studio co-working agent (HITL proposal chokepoint) ---
296
366
  export {
297
367
  InvalidProposalError,
@@ -418,10 +488,13 @@ export {
418
488
  // `ResolvePolicy`/`IdentityKind` (PRD 06): the explicit caller-declared trust
419
489
  // shape both resolver entry points accept via `policy` — the additive
420
490
  // replacement for the deprecated `restrictToAnonymous`/`allowCreate` booleans.
491
+ // `MergedLinkUnlink` (PRD 04): the link soft-unlink facts a collide-MERGE
492
+ // reports on the resolve result (`linkUnlinks`), for post-commit emission.
421
493
  export {
422
494
  deleteIdentityAliasesForContact,
423
495
  type IdentityKind,
424
496
  identifiedContactFilter,
497
+ type MergedLinkUnlink,
425
498
  type ResolvePolicy,
426
499
  resolveContactNoCreate,
427
500
  resolveOrCreateContact,
@@ -885,6 +958,19 @@ export {
885
958
  } from "./middleware/rate-limit.js";
886
959
  // --- Middleware (consumer-mounted routes, e.g. the @hogsend/mcp hosted route) ---
887
960
  export { requireAdmin } from "./middleware/require-admin.js";
961
+ // The `/v1/accounts/*` serialization boundary — TWO SHAPES, ONE ROW (PRD 09
962
+ // T2). `serializePublicLinkedAccount` is the ONLY shape `GET /v1/accounts/me`
963
+ // may return: four display keys, no id, no version. Exported so PRD 12's
964
+ // server SDK and PRD 13's embed type against the same declarations the routes
965
+ // answer with, rather than re-declaring them and drifting.
966
+ export {
967
+ linkedAccountSchema,
968
+ publicLinkedAccountSchema,
969
+ type SerializedLinkedAccount,
970
+ type SerializedPublicLinkedAccount,
971
+ serializeLinkedAccount,
972
+ serializePublicLinkedAccount,
973
+ } from "./routes/accounts/serialize.js";
888
974
  // --- Contact sources (Clay/Attio/generic-webhook → cold prospects) ---
889
975
  export {
890
976
  type ColdChannelPosture,
@@ -0,0 +1,126 @@
1
+ import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
2
+ import type { Database } from "@hogsend/db";
3
+ import {
4
+ type AccountUnlinkedFacts,
5
+ buildAccountUnlinkedPayload,
6
+ buildDedupeKey,
7
+ } from "./account-link-events.js";
8
+ import { createLogger, type Logger } from "./logger.js";
9
+
10
+ // The engine singletons, the `lib/preferences.ts` idiom: the `lib/contacts.ts`
11
+ // emit sites are reached from library code (the merge, the delete leg) that has
12
+ // no request container to read a `hatchet`/`logger` off. A caller that DOES
13
+ // have one passes it (see {@link EmitHandles}).
14
+ const logger = createLogger(process.env.LOG_LEVEL);
15
+
16
+ /**
17
+ * The container's handles, when the caller has a container.
18
+ *
19
+ * `logger` attributes the emit to the caller's request. `hatchet` buys exactly
20
+ * one thing — it spares this module the `./hatchet.js` dynamic import below,
21
+ * which is what runs `HatchetClient.init` — plus satisfying `emitOutbound`'s
22
+ * signature. It does NOT redirect delivery, and claiming otherwise would be
23
+ * false: `emitOutbound` destructures
24
+ * `const { db, logger, event, payload, dedupeKey } = opts`
25
+ * (`outbound.ts:619`) and never reads `opts.hatchet`, and the enqueue runs
26
+ * through the MODULE-LEVEL `deliverWebhookTask` built from the singleton at
27
+ * import time, so `opts.overrides.hatchet` cannot reroute it. Both fields are
28
+ * optional so the container-free `lib/contacts.ts` call sites stay a two-arg
29
+ * call.
30
+ */
31
+ export type EmitHandles = {
32
+ hatchet?: HatchetClient;
33
+ logger?: Logger;
34
+ };
35
+
36
+ /**
37
+ * Fan out one `account.unlinked` per mutation fact (PRD 08 T3).
38
+ *
39
+ * This exists so the emit SHAPE lives once: `MergedLinkUnlink` (the merge's
40
+ * singleton-collision soft-unlink, `reason: "relinked"`) and
41
+ * `ContactUnlinkFact` (the contact-deletion leg, `reason: "api"`) both satisfy
42
+ * {@link AccountUnlinkedFacts} structurally, so both legs share this loop and
43
+ * cannot drift apart on the payload or the dedupe key.
44
+ *
45
+ * ## Call it AFTER the mutation's transaction has RESOLVED, never inside it
46
+ *
47
+ * DECISIONS §8 puts emission at the commit/intent layer. Both callers hand us
48
+ * facts a `db.transaction(...)` already returned: a rolled-back merge or
49
+ * delete must never have announced an unlink that did not happen, and a
50
+ * subscriber that reacts by re-reading the pull plane inside the write's own
51
+ * transaction window would read pre-commit state.
52
+ *
53
+ * ## Fire-and-forget, and it stays that way
54
+ *
55
+ * `emitOutbound` never throws (`outbound.ts:600-608`); the `void … .catch` is
56
+ * the defence-in-depth its own docstring asks every call site for. A webhook
57
+ * problem must never fail a contact merge or a GDPR deletion, so this function
58
+ * returns `void` rather than a promise — there is deliberately nothing for a
59
+ * caller to await and therefore nothing for a caller to accidentally fail on.
60
+ *
61
+ * `version` is threaded through as the decimal STRING the store produced and
62
+ * is never parsed (DECISIONS §5.1). `userId`/`email` come off `fact.owner`,
63
+ * read inside the mutation's transaction, and are never looked up here.
64
+ *
65
+ * ## The spine is reached by DYNAMIC import, on purpose
66
+ *
67
+ * `lib/contacts.ts` imports this module, and `src/testing.ts` re-exports
68
+ * `softDeleteContact` from `lib/contacts.ts`. A STATIC `./hatchet.js` or
69
+ * `./outbound.js` import here (outbound → `workflows/deliver-webhook.js` →
70
+ * `lib/hatchet.js`) would therefore run `HatchetClient.init(...)` the moment
71
+ * anything touched the `@hogsend/engine/testing` barrel, which is documented
72
+ * side-effect-free and is consumed where no real Hatchet token exists — it
73
+ * throws `Invalid token format` before a single test runs. Resolving both
74
+ * inside the fire-and-forget body keeps that barrel clean; the ESM module
75
+ * cache makes every call after the first free, and the emit is already
76
+ * asynchronous so nothing about the timing or the post-commit ordering
77
+ * changes. `account-links-emit.test.ts` pins the absence of the static form —
78
+ * every gate stays green without it, so only that guard catches a regression.
79
+ */
80
+ export function emitAccountUnlinked(
81
+ db: Database,
82
+ facts: readonly AccountUnlinkedFacts[],
83
+ handles: EmitHandles = {},
84
+ ): void {
85
+ const log = handles.logger ?? logger;
86
+ for (const fact of facts) {
87
+ void emitOne(db, fact, handles.hatchet, log).catch((error: unknown) => {
88
+ // ATTRIBUTED, and `error` not `warn`. `emitOutbound` logs its own
89
+ // failures with structure, so the only thing that reaches here is a
90
+ // failure of the dynamic `import(...)` above — and Node's ESM loader
91
+ // CACHES a module evaluation error and re-throws it on every later
92
+ // import, so one `HatchetClient.init` throw disables `account.unlinked`
93
+ // for the life of the process. A bare `logger.warn(err)` made that a
94
+ // repeated context-free `Invalid token format`; an operator needs to
95
+ // know WHICH identity fact was dropped. Never rethrows: the
96
+ // fire-and-forget contract holds.
97
+ log.error("account.unlinked emit failed", {
98
+ event: "account.unlinked",
99
+ provider: fact.provider,
100
+ providerUserId: fact.providerUserId,
101
+ version: fact.version,
102
+ error: error instanceof Error ? error.message : String(error),
103
+ });
104
+ });
105
+ }
106
+ }
107
+
108
+ async function emitOne(
109
+ db: Database,
110
+ fact: AccountUnlinkedFacts,
111
+ hatchetHandle: HatchetClient | undefined,
112
+ log: Logger,
113
+ ): Promise<void> {
114
+ const { emitOutbound } = await import("./outbound.js");
115
+ // Only reach for the singleton when the caller had none to give: importing
116
+ // `./hatchet.js` is what runs `HatchetClient.init`.
117
+ const hatchet = hatchetHandle ?? (await import("./hatchet.js")).hatchet;
118
+ await emitOutbound({
119
+ db,
120
+ hatchet,
121
+ logger: log,
122
+ event: "account.unlinked",
123
+ payload: buildAccountUnlinkedPayload(fact),
124
+ dedupeKey: buildDedupeKey(fact.provider, fact.providerUserId, fact.version),
125
+ });
126
+ }
@@ -0,0 +1,180 @@
1
+ import type { LinkAccountResult, LinkOwner } from "./account-links.js";
2
+ import type { OutboundPayloads } from "./outbound.js";
3
+
4
+ /**
5
+ * The ONE place an `account.*` outbound payload or dedupe key is constructed
6
+ * (PRD 08 T3).
7
+ *
8
+ * Six emit sites across four PRDs build these — the hosted callback (linked +
9
+ * four link_failed reasons), the data-plane import, two data-plane revokes,
10
+ * the manage page, the merge's singleton-collision unlink and the
11
+ * contact-deletion leg. Hand-rolling the shape at each of them is how the
12
+ * `email` field ends up carrying the PROVIDER-reported address at one site and
13
+ * the contact's at another, or how one site emits `v3` while another emits
14
+ * `v3.0`. Everything here is a pure function of the facts a mutation already
15
+ * returned.
16
+ *
17
+ * This module has NO runtime imports on purpose (both imports above are
18
+ * `import type`, fully erased). `outbound.ts` reaches the delivery task, which
19
+ * reaches `env.ts`, which validates at IMPORT time — a payload builder must
20
+ * never drag that into a caller that has no env.
21
+ *
22
+ * ## Replay safety — there is none to reach for, and that is deliberate
23
+ *
24
+ * Linking happens in ROUTE-HANDLER runtime (the hosted callback, the data
25
+ * plane), never inside a Hatchet durable task. So nothing here enters the
26
+ * Hatchet journal, the positional-journal law that governs `ctx.sleep` /
27
+ * `ctx.waitForEvent` / the digest+throttle primitives does not apply, and the
28
+ * tracked mailer's exactly-once machinery (auto-keying off the replay-stable
29
+ * Hatchet run id) is NOT involved and must not be reached for.
30
+ *
31
+ * Idempotency here is DB-level, in three layers: the pair advisory lock plus
32
+ * the `(provider, provider_user_id, version)` unique constraint (DECISIONS
33
+ * §5.6) on the write side, and the `(endpointId, dedupeKey)` partial-unique
34
+ * index on the outbound side — which is what {@link buildDedupeKey} feeds. A
35
+ * journey that REACTS to `account.linked` is an ordinary event-triggered
36
+ * journey and obeys every existing replay law unchanged.
37
+ */
38
+
39
+ /**
40
+ * `al:<provider>:<providerUserId>:v<version>` — DECISIONS §5.5, riding the
41
+ * existing `(endpointId, dedupeKey)` partial-unique index on
42
+ * `webhook_deliveries`.
43
+ *
44
+ * A PURE TEMPLATE. Do NOT add URL-encoding, escaping or normalization: the key
45
+ * only has to be stable and unique per mutation, and the instant its spelling
46
+ * changes, a re-emit of a version minted before the change no longer collides
47
+ * with the row written after it — the dedupe silently stops deduping, which no
48
+ * delivery assertion can see.
49
+ *
50
+ * `version` is a decimal STRING in and a STRING out, never parsed
51
+ * (DECISIONS §5.1: the column is a Postgres `bigint`, so `Number()` loses
52
+ * fidelity past `Number.MAX_SAFE_INTEGER` and breaks the consumer's
53
+ * `incoming.version > stored.version` guard in exactly the case it exists for).
54
+ */
55
+ export function buildDedupeKey(
56
+ provider: string,
57
+ providerUserId: string,
58
+ version: string,
59
+ ): string {
60
+ return `al:${provider}:${providerUserId}:v${version}`;
61
+ }
62
+
63
+ /** The two {@link LinkAccountResult} arms that actually bound something. */
64
+ type LinkedFacts = Extract<
65
+ LinkAccountResult,
66
+ { status: "linked" } | { status: "relinked" }
67
+ >;
68
+
69
+ /**
70
+ * FULL CURRENT STATE for a successful bind (DECISIONS §5.2), built from the
71
+ * facts `linkAccount()` returned and nothing else.
72
+ *
73
+ * `userId` and `email` come off `facts.owner` — the join to `contacts` the
74
+ * store performed INSIDE its advisory-locked transaction (DECISIONS §15.5).
75
+ * Neither field exists on `linked_accounts`, and re-reading them here would be
76
+ * a read after the lock released: no longer the state that was committed.
77
+ * `userId` is `contactKey()` (`external_id ?? anonymous_id ?? id`), the ONE
78
+ * definition shared by the PULL, PUSH and IN-PROCESS planes — never the raw
79
+ * `externalId`.
80
+ *
81
+ * `email` is the CONTACT's address. `row.verifiedEmail` (the
82
+ * provider-reported one) is deliberately never read here: it is a display
83
+ * property at most, and putting it in a field named `email` beside `contactId`
84
+ * is precisely how a downstream system ends up resolving identity on it.
85
+ */
86
+ export function buildAccountLinkedPayload(
87
+ facts: LinkedFacts,
88
+ at: Date = new Date(),
89
+ ): OutboundPayloads["account.linked"] {
90
+ return {
91
+ state: "linked",
92
+ provider: facts.row.provider,
93
+ providerUserId: facts.row.providerUserId,
94
+ contactId: facts.owner.contactId,
95
+ userId: facts.owner.userId,
96
+ email: facts.owner.email,
97
+ username: facts.row.username,
98
+ method: facts.row.method,
99
+ relink: facts.relink,
100
+ version: facts.version,
101
+ at: at.toISOString(),
102
+ };
103
+ }
104
+
105
+ /**
106
+ * The facts every unlink site already has in hand.
107
+ *
108
+ * The merge fold's `MergedLinkUnlink` and the delete leg's `ContactUnlinkFact`
109
+ * satisfy this structurally, so `lib/account-link-emit.ts` fans both out
110
+ * without reshaping either. `UnlinkAccountResult` does NOT: its `unlinked` arm
111
+ * carries `provider`/`providerUserId` on `.row`, not at the top level, so a
112
+ * revoke site (PRD 09, PRD 11) passes those two up from `res.row` alongside
113
+ * `res.version`, `res.owner` and its own `reason`.
114
+ */
115
+ export interface AccountUnlinkedFacts {
116
+ provider: string;
117
+ providerUserId: string;
118
+ /** That pair's OWN next version, a decimal STRING (DECISIONS §5.1). */
119
+ version: string;
120
+ reason: "player" | "api" | "relinked";
121
+ /** Read inside the mutation's transaction — see {@link LinkOwner}. */
122
+ owner: LinkOwner;
123
+ }
124
+
125
+ /**
126
+ * FULL CURRENT STATE for a release (DECISIONS §5.2). Shares the
127
+ * `(provider, providerUserId)` version sequence with `account.linked`, so a
128
+ * consumer's single monotonic guard makes reorder, duplicate and late delivery
129
+ * all no-ops.
130
+ *
131
+ * `contactId`/`userId`/`email` are read off `owner` and nowhere else, for the
132
+ * same reason as {@link buildAccountLinkedPayload}.
133
+ */
134
+ export function buildAccountUnlinkedPayload(
135
+ facts: AccountUnlinkedFacts,
136
+ at: Date = new Date(),
137
+ ): OutboundPayloads["account.unlinked"] {
138
+ return {
139
+ state: "unlinked",
140
+ provider: facts.provider,
141
+ providerUserId: facts.providerUserId,
142
+ contactId: facts.owner.contactId,
143
+ userId: facts.owner.userId,
144
+ email: facts.owner.email,
145
+ reason: facts.reason,
146
+ version: facts.version,
147
+ at: at.toISOString(),
148
+ };
149
+ }
150
+
151
+ /**
152
+ * A link flow ended without binding anything.
153
+ *
154
+ * Carries NO `version` and NO `state`: nothing mutated, so there is nothing
155
+ * for the consumer's `incoming.version > stored.version` guard to compare and
156
+ * no current state to report. It gets NO dedupeKey either (the caller passes
157
+ * none) — two genuine failures in a row are two genuine facts, and suppressing
158
+ * the second would hide a brute-force pattern.
159
+ *
160
+ * `reason` is `AccountLinkCallbackError.reason` verbatim; PRD 01 froze that
161
+ * union as the `account.link_failed` union minus `"vetoed"` (which only the
162
+ * hook path produces), so there is no translation table. `contactId` is null
163
+ * whenever the flow failed before a trustworthy contact was in hand, and this
164
+ * event NEVER mints one (DECISIONS §8).
165
+ */
166
+ export function buildLinkFailedPayload(
167
+ args: {
168
+ provider: string;
169
+ reason: "denied" | "vetoed" | "exchange_failed" | "state_invalid";
170
+ contactId: string | null;
171
+ },
172
+ at: Date = new Date(),
173
+ ): OutboundPayloads["account.link_failed"] {
174
+ return {
175
+ provider: args.provider,
176
+ reason: args.reason,
177
+ contactId: args.contactId,
178
+ at: at.toISOString(),
179
+ };
180
+ }