@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
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
@@ -130,6 +130,29 @@ export const env = createEnv({
130
130
  POSTMARK_MESSAGE_STREAM: z.string().min(1).optional(),
131
131
  POSTMARK_WEBHOOK_USER: z.string().min(1).optional(),
132
132
  POSTMARK_WEBHOOK_PASS: z.string().min(1).optional(),
133
+ // --- Hogsend Email (Cloud-only first-party sending; opt-in provider) ---
134
+ // The environment's relay token (`hsrel_…`), minted by Hogsend Cloud at
135
+ // provision time. It is the ONLY credential a tenant instance holds — the
136
+ // AWS credentials never leave the control plane.
137
+ //
138
+ // Its ABSENCE is a mode, not a gap: with no token `@hogsend/plugin-hogsend`
139
+ // is never imported at all, so a self-hosted deploy that will never send
140
+ // through Cloud never touches the package and behaves exactly as before.
141
+ // Present, a preset is built — and like Postmark it NEVER changes the
142
+ // active provider on its own; set EMAIL_PROVIDER=hogsend to activate it.
143
+ HOGSEND_EMAIL_TOKEN: z.string().min(1).optional(),
144
+ // Origin of the Hogsend Cloud control plane the send relay lives on (the
145
+ // provisioner injects its own CLOUD_PUBLIC_URL here). NO default ON
146
+ // PURPOSE: staging and production control planes are different origins, so
147
+ // a guessed default would point a tenant's mail at the wrong one. A token
148
+ // set WITHOUT this is a misconfiguration — the preset warns and skips
149
+ // rather than building a provider aimed at nowhere.
150
+ HOGSEND_EMAIL_RELAY_URL: z.string().url().optional(),
151
+ // HMAC secret the relay signs its status webhooks with. Absent ⇒ the
152
+ // provider FAILS CLOSED: every inbound webhook is rejected before it is
153
+ // parsed, so an unauthenticated status update can never mark a contact
154
+ // bounced. Sending is unaffected; only status updates stop.
155
+ HOGSEND_EMAIL_WEBHOOK_SECRET: z.string().min(1).optional(),
133
156
  // --- Base-currency FX lens (optional; docs/groups.md §Base-currency lens) ---
134
157
  // The operator's reporting currency. UNSET = the lens is OFF everywhere
135
158
  // (zero behavior change): no converted figures, no converted ranking. Set
@@ -207,6 +230,43 @@ export const env = createEnv({
207
230
  .int()
208
231
  .nonnegative()
209
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),
210
270
  // Hatchet connection contract. The @hatchet-dev SDK also reads these straight
211
271
  // from process.env via its own config-loader, so this schema is a presence /
212
272
  // shape check that keeps the contract in one place — the values still flow to
package/src/index.ts CHANGED
@@ -28,7 +28,9 @@ export type {
28
28
  /** @deprecated Use {@link EmailEvent}. Frozen `event.raw` cast target. */
29
29
  LegacyResendWebhookEvent,
30
30
  PostHogService,
31
+ ReturnPathState,
31
32
  SendResult,
33
+ SetReturnPathInput,
32
34
  /** @deprecated Use {@link EmailEvent}. Kept for one minor. */
33
35
  WebhookEvent,
34
36
  WebhookHandlerMap,
@@ -44,10 +46,24 @@ export * from "@hogsend/core";
44
46
  // `SendEmailOptions` is the high-level journey-facing send options from
45
47
  // `./lib/email.js`; the provider-contract `SendEmailOptions` remains available
46
48
  // via `@hogsend/core`.)
47
- 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,
48
60
  bySubject,
61
+ defineAccountLink,
49
62
  defineAnalyticsProvider,
50
63
  defineEmailProvider,
64
+ type LinkedIdentity,
65
+ type LinkTokens,
66
+ RESERVED_ACCOUNT_LINK_IDS,
51
67
  type Subject,
52
68
  WebhookHandshakeSignal,
53
69
  } from "@hogsend/core";
@@ -65,6 +81,15 @@ export {
65
81
  type JournalShape,
66
82
  type SchemaVersion,
67
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";
68
93
  // --- App / container / worker factories ---
69
94
  export {
70
95
  type AppEnv,
@@ -290,6 +315,53 @@ export {
290
315
  getJourneyRegistrySingleton,
291
316
  setJourneyRegistry,
292
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";
293
365
  // --- Studio co-working agent (HITL proposal chokepoint) ---
294
366
  export {
295
367
  InvalidProposalError,
@@ -306,6 +378,13 @@ export {
306
378
  } from "./lib/analytics-identity.js";
307
379
  export { AnalyticsProviderRegistry } from "./lib/analytics-provider-registry.js";
308
380
  export { analyticsProvidersFromEnv } from "./lib/analytics-providers-from-env.js";
381
+ // --- Attachments (engine-side gate + email_sends metadata shape, PRD 17) ---
382
+ export {
383
+ type AttachmentSendMetadata,
384
+ AttachmentsUnsupportedError,
385
+ assertAttachmentsSendable,
386
+ attachmentSendMetadata,
387
+ } from "./lib/attachments.js";
309
388
  // --- Auth ---
310
389
  export {
311
390
  type Auth,
@@ -409,10 +488,13 @@ export {
409
488
  // `ResolvePolicy`/`IdentityKind` (PRD 06): the explicit caller-declared trust
410
489
  // shape both resolver entry points accept via `policy` — the additive
411
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.
412
493
  export {
413
494
  deleteIdentityAliasesForContact,
414
495
  type IdentityKind,
415
496
  identifiedContactFilter,
497
+ type MergedLinkUnlink,
416
498
  type ResolvePolicy,
417
499
  resolveContactNoCreate,
418
500
  resolveOrCreateContact,
@@ -708,6 +790,13 @@ export {
708
790
  SEMANTIC_BURST_DISTINCT_LINKS,
709
791
  SEMANTIC_BURST_WINDOW_MS,
710
792
  } from "./lib/semantic-click.js";
793
+ // --- Sending-subdomain setup guidance (static; one source for all surfaces) ---
794
+ export {
795
+ exampleSendingSubdomain,
796
+ looksLikeRootDomain,
797
+ SENDING_DOMAIN_GUIDANCE,
798
+ type SendingDomainGuidance,
799
+ } from "./lib/sending-domain-guidance.js";
711
800
  // --- SMS ---
712
801
  export {
713
802
  getSmsService,
@@ -770,6 +859,7 @@ export {
770
859
  export {
771
860
  EMAIL_LINK_CLICKED,
772
861
  EMAIL_OPENED,
862
+ EMAIL_REPLIED,
773
863
  LINK_ARRIVED,
774
864
  LINK_CLICKED,
775
865
  SMS_LINK_CLICKED,
@@ -868,6 +958,19 @@ export {
868
958
  } from "./middleware/rate-limit.js";
869
959
  // --- Middleware (consumer-mounted routes, e.g. the @hogsend/mcp hosted route) ---
870
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";
871
974
  // --- Contact sources (Clay/Attio/generic-webhook → cold prospects) ---
872
975
  export {
873
976
  type ColdChannelPosture,
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { EmailAttachment } from "@hogsend/core";
2
3
 
3
4
  /**
4
5
  * The minimal slice of Hatchet's `DurableContext` the boundary needs for its
@@ -25,6 +26,13 @@ export interface JourneyEmailEffect {
25
26
  journeyName?: string;
26
27
  journeyStateId?: string;
27
28
  idempotencyKey?: string;
29
+ /**
30
+ * Neutral attachments (PRD 17), carried so a scoped `services.email`
31
+ * override observes the files a send would carry rather than silently
32
+ * dropping them. Deliberately NOT part of any derived idempotency key —
33
+ * the key stays `kind:anchor:site:template`.
34
+ */
35
+ attachments?: EmailAttachment[];
28
36
  }
29
37
 
30
38
  export interface JourneySmsEffect {
@@ -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
+ }