@hogsend/engine 0.64.0 → 0.66.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 (77) 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/battlenet.ts +84 -0
  7. package/src/account-links/epic.ts +87 -0
  8. package/src/account-links/index.ts +15 -0
  9. package/src/account-links/riot.ts +82 -0
  10. package/src/account-links/steam.test.ts +243 -0
  11. package/src/account-links/steam.ts +48 -0
  12. package/src/account-links/twitch.test.ts +157 -0
  13. package/src/account-links/twitch.ts +99 -0
  14. package/src/account-links/xbox.ts +92 -0
  15. package/src/app.ts +9 -1
  16. package/src/container.account-links.env.test.ts +65 -0
  17. package/src/container.account-links.halfenv.test.ts +48 -0
  18. package/src/container.account-links.test.ts +185 -0
  19. package/src/container.ts +120 -0
  20. package/src/env.ts +53 -0
  21. package/src/index.ts +93 -1
  22. package/src/lib/account-link-emit.ts +126 -0
  23. package/src/lib/account-link-events.ts +180 -0
  24. package/src/lib/account-link-hooks.test.ts +158 -0
  25. package/src/lib/account-link-hooks.ts +73 -0
  26. package/src/lib/account-link-ingest.ts +364 -0
  27. package/src/lib/account-link-nonce.test.ts +52 -0
  28. package/src/lib/account-link-nonce.ts +57 -0
  29. package/src/lib/account-link-origins.test.ts +72 -0
  30. package/src/lib/account-link-origins.ts +87 -0
  31. package/src/lib/account-link-pkce.test.ts +91 -0
  32. package/src/lib/account-link-pkce.ts +106 -0
  33. package/src/lib/account-link-provider-registry.test.ts +52 -0
  34. package/src/lib/account-link-provider-registry.ts +61 -0
  35. package/src/lib/account-link-throttle.test.ts +178 -0
  36. package/src/lib/account-link-throttle.ts +130 -0
  37. package/src/lib/account-link-url.ts +85 -0
  38. package/src/lib/account-links-emit.test.ts +525 -0
  39. package/src/lib/account-links-env.test.ts +40 -0
  40. package/src/lib/account-links-from-env.test.ts +187 -0
  41. package/src/lib/account-links-from-env.ts +190 -0
  42. package/src/lib/account-links.ts +1300 -0
  43. package/src/lib/app-secret.ts +34 -0
  44. package/src/lib/connector-actions.test.ts +13 -4
  45. package/src/lib/connector-state.account-link.test.ts +114 -0
  46. package/src/lib/connector-state.ts +48 -3
  47. package/src/lib/contacts.ts +342 -6
  48. package/src/lib/outbound-account-payloads.test.ts +137 -0
  49. package/src/lib/outbound.ts +91 -0
  50. package/src/lib/provider-credentials.ts +19 -5
  51. package/src/lib/snippet.ts +76 -0
  52. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  53. package/src/lib/webhook-signing.ts +18 -1
  54. package/src/routes/accounts/callback.ts +597 -0
  55. package/src/routes/accounts/emit.ts +231 -0
  56. package/src/routes/accounts/import-links.ts +210 -0
  57. package/src/routes/accounts/index.ts +75 -0
  58. package/src/routes/accounts/lookup.ts +177 -0
  59. package/src/routes/accounts/me.ts +215 -0
  60. package/src/routes/accounts/mint.ts +279 -0
  61. package/src/routes/accounts/pages.ts +62 -0
  62. package/src/routes/accounts/resolve.ts +61 -0
  63. package/src/routes/accounts/serialize.ts +96 -0
  64. package/src/routes/accounts/shared.ts +107 -0
  65. package/src/routes/accounts/start.ts +229 -0
  66. package/src/routes/accounts/unlink.ts +98 -0
  67. package/src/routes/admin/agent.ts +2 -0
  68. package/src/routes/admin/api-keys.ts +7 -0
  69. package/src/routes/admin/contacts.ts +38 -2
  70. package/src/routes/connectors/index.ts +17 -0
  71. package/src/routes/contacts/index.ts +8 -0
  72. package/src/routes/index.ts +81 -0
  73. package/src/routes/snippet.test.ts +70 -0
  74. package/src/routes/snippet.ts +58 -0
  75. package/src/testing-barrel.test.ts +74 -0
  76. package/src/testing.ts +17 -0
  77. package/src/workflows/import-contacts.ts +6 -0
@@ -0,0 +1,65 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ // The env-var leg of the allowlist merge needs ACCOUNT_LINK_ALLOWED_ORIGINS
5
+ // SET at env-parse time, and t3-env parses process.env exactly once per
6
+ // import — so this case lives in its own file (its own node:test process),
7
+ // exactly the email-provider-boot.hogsend.test.ts split. Env is set BEFORE
8
+ // the container import; see container.account-links.test.ts for the rest of
9
+ // the boot preconditions.
10
+ process.env.NODE_ENV = "test";
11
+ process.env.LOG_LEVEL = "error";
12
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
13
+ process.env.BETTER_AUTH_SECRET ??=
14
+ "test-secret-for-node-test-minimum-32-characters-long";
15
+ process.env.HATCHET_CLIENT_TOKEN ??=
16
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
17
+ process.env.ACCOUNT_LINK_ALLOWED_ORIGINS =
18
+ "https://env-a.example.com, https://env-b.example.com";
19
+ process.env.ACCOUNT_LINK_TWITCH_CLIENT_ID = "env-twitch-client-id";
20
+ process.env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET = "env-twitch-client-secret";
21
+
22
+ const { createHogsendClient } = await import("./container.js");
23
+
24
+ test("parses ACCOUNT_LINK_ALLOWED_ORIGINS and the option into one list, env first", () => {
25
+ const client = createHogsendClient({
26
+ accountLinks: {
27
+ allowedOrigins: [
28
+ "https://option.example.com",
29
+ // Duplicate of an env entry — deduped, first (env) position kept.
30
+ "https://env-a.example.com",
31
+ ],
32
+ },
33
+ });
34
+ assert.deepEqual(client.accountLinkAllowedOrigins, [
35
+ "https://env-a.example.com",
36
+ "https://env-b.example.com",
37
+ "https://option.example.com",
38
+ ]);
39
+ });
40
+
41
+ test("registers twitch + steam from env", () => {
42
+ const client = createHogsendClient();
43
+ // Steam unconditionally, twitch because BOTH ACCOUNT_LINK_TWITCH_* vars are
44
+ // set above. Env-preset order: steam first, then twitch.
45
+ assert.deepEqual(client.accountLinkProviders.ids(), ["steam", "twitch"]);
46
+ assert.equal(client.accountLinkProviders.get("twitch")?.meta.name, "Twitch");
47
+ assert.equal(
48
+ client.accountLinkProviders.get("twitch")?.capabilities?.tokens,
49
+ true,
50
+ );
51
+ });
52
+
53
+ test("a consumer provider of the same id overrides the env preset", () => {
54
+ const consumerTwitch = {
55
+ meta: { id: "twitch", name: "consumer-twitch" },
56
+ authorizeUrl: () => "https://example.com/authorize",
57
+ handleCallback: async () => ({ providerUserId: "u1" }),
58
+ };
59
+ const client = createHogsendClient({
60
+ accountLinks: { providers: [consumerTwitch] },
61
+ });
62
+ // Env presets first, consumer last: same count, consumer object wins.
63
+ assert.deepEqual(client.accountLinkProviders.ids(), ["steam", "twitch"]);
64
+ assert.equal(client.accountLinkProviders.get("twitch"), consumerTwitch);
65
+ });
@@ -0,0 +1,48 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ // The half-configured-twitch boot needs ACCOUNT_LINK_TWITCH_CLIENT_ID set and
5
+ // _CLIENT_SECRET unset at env-parse time, and t3-env parses process.env
6
+ // exactly once per import — so this combination lives in its own file (its own
7
+ // node:test process), the container.account-links.env.test.ts split. Env is
8
+ // set BEFORE the container import; LOG_LEVEL=warn so the warning under test is
9
+ // actually emitted.
10
+ process.env.NODE_ENV = "test";
11
+ process.env.LOG_LEVEL = "warn";
12
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
13
+ process.env.BETTER_AUTH_SECRET ??=
14
+ "test-secret-for-node-test-minimum-32-characters-long";
15
+ process.env.HATCHET_CLIENT_TOKEN ??=
16
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
17
+ process.env.ACCOUNT_LINK_TWITCH_CLIENT_ID = "env-twitch-client-id";
18
+ delete process.env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET;
19
+
20
+ const { createHogsendClient } = await import("./container.js");
21
+
22
+ /** Same boot-capture idiom as container.account-links.test.ts. */
23
+ function captureBoot<T>(fn: () => T): { value: T; out: string } {
24
+ const original = process.stdout.write.bind(process.stdout);
25
+ let out = "";
26
+ process.stdout.write = ((chunk: unknown) => {
27
+ out += String(chunk);
28
+ return true;
29
+ }) as typeof process.stdout.write;
30
+ try {
31
+ return { value: fn(), out };
32
+ } finally {
33
+ process.stdout.write = original;
34
+ }
35
+ }
36
+
37
+ const HALF_CONFIGURED_WARN = "twitch account linking is half-configured";
38
+
39
+ test("warns once, does not throw, on a half-configured twitch", () => {
40
+ // Does not throw — the boot completes…
41
+ const { value: client, out } = captureBoot(() => createHogsendClient());
42
+ // …twitch is ABSENT from the registry (not present-but-disabled), steam
43
+ // still registers…
44
+ assert.deepEqual(client.accountLinkProviders.ids(), ["steam"]);
45
+ // …and the warning fires exactly once, naming the MISSING var.
46
+ assert.equal(out.split(HALF_CONFIGURED_WARN).length - 1, 1);
47
+ assert.match(out, /ACCOUNT_LINK_TWITCH_CLIENT_SECRET is unset/);
48
+ });
@@ -0,0 +1,185 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import type { AccountLinkHooks, AccountLinkProvider } from "@hogsend/core";
4
+
5
+ // Env is set BEFORE the container import — env.ts validates at module scope.
6
+ // LOG_LEVEL=warn so the boot warnings under test are actually emitted. No
7
+ // DATABASE_URL connection is opened (`postgres()` is lazy) and boot side
8
+ // effects are skipped under NODE_ENV=test, so a full createHogsendClient()
9
+ // completes offline. Every ACCOUNT_LINK_* var is UNSET here — the env-set
10
+ // merge case lives in container.account-links.env.test.ts (its own process,
11
+ // because t3-env parses process.env exactly once per import).
12
+ process.env.NODE_ENV = "test";
13
+ process.env.LOG_LEVEL = "warn";
14
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
15
+ process.env.BETTER_AUTH_SECRET ??=
16
+ "test-secret-for-node-test-minimum-32-characters-long";
17
+ process.env.HATCHET_CLIENT_TOKEN ??=
18
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
19
+ for (const name of [
20
+ "ACCOUNT_LINK_TWITCH_CLIENT_ID",
21
+ "ACCOUNT_LINK_TWITCH_CLIENT_SECRET",
22
+ "STEAM_WEB_API_KEY",
23
+ "ACCOUNT_LINK_ALLOWED_ORIGINS",
24
+ ]) {
25
+ delete process.env[name];
26
+ }
27
+
28
+ const { createHogsendClient } = await import("./container.js");
29
+
30
+ function stubProvider(id: string, name = id): AccountLinkProvider {
31
+ return {
32
+ meta: { id, name },
33
+ authorizeUrl: () => `https://example.com/authorize?provider=${id}`,
34
+ handleCallback: async () => ({ providerUserId: `${id}-user` }),
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Boot the container while capturing everything winston writes to stdout
40
+ * (boot-time warns happen inside createHogsendClient, before any test could
41
+ * spy on `client.logger`). Output is swallowed during the boot so the TAP
42
+ * stream stays clean; the winston Console transport writes synchronously.
43
+ */
44
+ function captureBoot<T>(fn: () => T): { value: T; out: string } {
45
+ const original = process.stdout.write.bind(process.stdout);
46
+ let out = "";
47
+ process.stdout.write = ((chunk: unknown) => {
48
+ out += String(chunk);
49
+ return true;
50
+ }) as typeof process.stdout.write;
51
+ try {
52
+ return { value: fn(), out };
53
+ } finally {
54
+ process.stdout.write = original;
55
+ }
56
+ }
57
+
58
+ /** The account-link boot warnings under test, as greppable fragments. */
59
+ const ALLOWLIST_WARN = "no allowed origin is configured";
60
+ const DUP_WARN = "more than once";
61
+
62
+ function countOf(haystack: string, needle: string): number {
63
+ return haystack.split(needle).length - 1;
64
+ }
65
+
66
+ test("exposes an empty registry and {} hooks with no config", () => {
67
+ // The inert-when-unconfigured posture: no ACCOUNT_LINK_* env var (deleted
68
+ // above) and no `accountLinks` option ⇒ no operator intent, so NOTHING
69
+ // registers — not even the credential-free steam preset — and no
70
+ // account-link warning fires on a deploy that never asked for the feature.
71
+ const { value: client, out } = captureBoot(() => createHogsendClient());
72
+ assert.equal(client.accountLinkProviders.count(), 0);
73
+ assert.deepEqual(client.accountLinkHooks, {});
74
+ assert.deepEqual(client.accountLinkAllowedOrigins, []);
75
+ assert.equal(out.includes(ALLOWLIST_WARN), false);
76
+ assert.equal(out.includes(DUP_WARN), false);
77
+ });
78
+
79
+ test("builds steam when the consumer passes an accountLinks option", () => {
80
+ // Code intent: ANY `accountLinks` option — even `{}` — opts the deploy in,
81
+ // and the credential-free steam preset registers.
82
+ const { value: client } = captureBoot(() =>
83
+ createHogsendClient({ accountLinks: {} }),
84
+ );
85
+ assert.deepEqual(client.accountLinkProviders.ids(), ["steam"]);
86
+ });
87
+
88
+ test("registers a consumer-supplied provider", () => {
89
+ const steam = stubProvider("steam");
90
+ const { value: client } = captureBoot(() =>
91
+ createHogsendClient({
92
+ accountLinks: {
93
+ providers: [steam],
94
+ allowedOrigins: ["https://play.example.com"],
95
+ },
96
+ }),
97
+ );
98
+ assert.equal(client.accountLinkProviders.count(), 1);
99
+ assert.equal(client.accountLinkProviders.get("steam"), steam);
100
+ });
101
+
102
+ test("keeps the last of two consumer providers sharing an id, and warns once", () => {
103
+ const first = stubProvider("twitch", "first");
104
+ const second = stubProvider("twitch", "second");
105
+ const { value: client, out } = captureBoot(() =>
106
+ createHogsendClient({
107
+ accountLinks: {
108
+ providers: [first, second],
109
+ allowedOrigins: ["https://play.example.com"],
110
+ },
111
+ }),
112
+ );
113
+ // 2 = the unconditional steam env preset + the (deduped) consumer twitch.
114
+ assert.equal(client.accountLinkProviders.count(), 2);
115
+ assert.equal(client.accountLinkProviders.get("twitch"), second);
116
+ assert.equal(countOf(out, DUP_WARN), 1);
117
+ // The warn names the duplicated id.
118
+ assert.match(out, /"twitch"/);
119
+ });
120
+
121
+ test("a consumer provider of the same id overrides the env preset", () => {
122
+ const steam = stubProvider("steam", "consumer-steam");
123
+ const { value: client } = captureBoot(() =>
124
+ createHogsendClient({
125
+ accountLinks: {
126
+ providers: [steam],
127
+ allowedOrigins: ["https://play.example.com"],
128
+ },
129
+ }),
130
+ );
131
+ // Env presets merge FIRST, consumer last — last-writer-wins on meta.id, so
132
+ // the registry holds the consumer's steam, not the env preset's.
133
+ assert.equal(client.accountLinkProviders.count(), 1);
134
+ assert.equal(client.accountLinkProviders.get("steam"), steam);
135
+ });
136
+
137
+ test("exposes accountLinkHooks verbatim", () => {
138
+ const hooks: AccountLinkHooks = {
139
+ beforeLink: () => ({ allow: false, reason: "test" }),
140
+ afterLink: () => {},
141
+ };
142
+ const { value: client } = captureBoot(() =>
143
+ createHogsendClient({ accountLinks: { hooks } }),
144
+ );
145
+ // Reference equality: held verbatim, not wrapped, not per-hook defaulted.
146
+ assert.equal(client.accountLinkHooks, hooks);
147
+ assert.equal(client.accountLinkHooks.beforeLink, hooks.beforeLink);
148
+ assert.equal(client.accountLinkHooks.afterUnlink, undefined);
149
+ });
150
+
151
+ test("throws at boot on a malformed allowed origin", () => {
152
+ assert.throws(
153
+ () =>
154
+ captureBoot(() =>
155
+ createHogsendClient({
156
+ accountLinks: {
157
+ providers: [stubProvider("steam")],
158
+ allowedOrigins: ["https://x.example.com/cb"],
159
+ },
160
+ }),
161
+ ),
162
+ /"https:\/\/x\.example\.com\/cb"/,
163
+ );
164
+ });
165
+
166
+ test("warns when providers are registered but the allowlist is empty", () => {
167
+ const { value: client, out } = captureBoot(() =>
168
+ createHogsendClient({
169
+ accountLinks: { providers: [stubProvider("steam")] },
170
+ }),
171
+ );
172
+ assert.equal(client.accountLinkProviders.count(), 1);
173
+ assert.deepEqual(client.accountLinkAllowedOrigins, []);
174
+ assert.equal(countOf(out, ALLOWLIST_WARN), 1);
175
+ });
176
+
177
+ test("the empty-allowlist warn fires for an opted-in deploy with no allowlist", () => {
178
+ // A deploy that ASKED for account links (`accountLinks: {}` opts in and
179
+ // registers steam) but configured no allowed origin is a genuine
180
+ // misconfiguration: no returnTo is accepted and postMessage never fires,
181
+ // so it warns once. The bare-boot case above stays silent — nothing
182
+ // registers without intent.
183
+ const { out } = captureBoot(() => createHogsendClient({ accountLinks: {} }));
184
+ assert.equal(countOf(out, ALLOWLIST_WARN), 1);
185
+ });
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,59 @@ export const env = createEnv({
230
230
  .int()
231
231
  .nonnegative()
232
232
  .default(0),
233
+ // --- Account links (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
+ // The six 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
+ // Battle.net: the preset is built only when BOTH id + secret are present
255
+ // (same rule as Twitch). Register at https://develop.battle.net/access.
256
+ ACCOUNT_LINK_BATTLENET_CLIENT_ID: z.string().min(1).optional(),
257
+ ACCOUNT_LINK_BATTLENET_CLIENT_SECRET: z.string().min(1).optional(),
258
+ // Epic Games: the preset is built only when BOTH id + secret are present.
259
+ // Register at https://dev.epicgames.com/portal.
260
+ ACCOUNT_LINK_EPIC_CLIENT_ID: z.string().min(1).optional(),
261
+ ACCOUNT_LINK_EPIC_CLIENT_SECRET: z.string().min(1).optional(),
262
+ // Xbox (Microsoft Entra): the preset is built only when BOTH id + secret
263
+ // are present. Register at https://portal.azure.com.
264
+ ACCOUNT_LINK_XBOX_CLIENT_ID: z.string().min(1).optional(),
265
+ ACCOUNT_LINK_XBOX_CLIENT_SECRET: z.string().min(1).optional(),
266
+ // Riot Games: the preset is built only when BOTH id + secret are present.
267
+ // Register at https://developer.riotgames.com.
268
+ ACCOUNT_LINK_RIOT_CLIENT_ID: z.string().min(1).optional(),
269
+ ACCOUNT_LINK_RIOT_CLIENT_SECRET: z.string().min(1).optional(),
270
+ // CSV of absolute origins ("https://play.example.com,https://example.com")
271
+ // — the ONE allowlist governing both `returnTo` (PRD 07) and the
272
+ // `postMessage` targetOrigin (PRD 10). Unset ⇒ empty list ⇒ no `returnTo`
273
+ // accepted and postMessage never attempted (warned once at boot when
274
+ // providers are registered). A plain string here on purpose: the parse +
275
+ // per-entry validation lives in lib/account-link-origins.ts, OUTSIDE the
276
+ // schema, so a malformed entry THROWS at boot naming the offending entry
277
+ // rather than a generic Zod failure (the FX_RATES stance above). Never "*".
278
+ ACCOUNT_LINK_ALLOWED_ORIGINS: z.string().optional(),
279
+ // State/PKCE token TTL for the hosted link flow. 900s matches the window
280
+ // the connector nonce burn already assumes (routes/connectors/index.ts).
281
+ ACCOUNT_LINK_STATE_TTL_SECONDS: z.coerce
282
+ .number()
283
+ .int()
284
+ .positive()
285
+ .default(900),
233
286
  // Hatchet connection contract. The @hatchet-dev SDK also reads these straight
234
287
  // from process.env via its own config-loader, so this schema is a presence /
235
288
  // 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,
@@ -760,6 +833,11 @@ export type {
760
833
  SmsTrackedSendResult,
761
834
  } from "./lib/sms-service-types.js";
762
835
  export { SMS_CHANNEL_ID } from "./lib/sms-tracked.js";
836
+ export {
837
+ type LoadedSnippet,
838
+ loadSnippet,
839
+ resolveSnippetPath,
840
+ } from "./lib/snippet.js";
763
841
  export { type MountStudioResult, mountStudio } from "./lib/studio.js";
764
842
  // --- In-app survey/rating (sendSurvey — producer sugar over sendFeedItem) ---
765
843
  export { type SendSurveyOptions, sendSurvey } from "./lib/survey.js";
@@ -885,6 +963,20 @@ export {
885
963
  } from "./middleware/rate-limit.js";
886
964
  // --- Middleware (consumer-mounted routes, e.g. the @hogsend/mcp hosted route) ---
887
965
  export { requireAdmin } from "./middleware/require-admin.js";
966
+ // The `/v1/accounts/*` serialization boundary — TWO SHAPES, ONE ROW (PRD 09
967
+ // T2). `serializePublicLinkedAccount` is the ONLY shape `GET /v1/accounts/me`
968
+ // may return: four display keys, no id, no version. Exported so PRD 12's
969
+ // server SDK and PRD 13's embed type against the same declarations the routes
970
+ // answer with, rather than re-declaring them and drifting.
971
+ export {
972
+ linkedAccountSchema,
973
+ publicLinkedAccountSchema,
974
+ type SerializedLinkedAccount,
975
+ type SerializedPublicLinkedAccount,
976
+ serializeLinkedAccount,
977
+ serializePublicLinkedAccount,
978
+ } from "./routes/accounts/serialize.js";
979
+ export { createSnippetRouter } from "./routes/snippet.js";
888
980
  // --- Contact sources (Clay/Attio/generic-webhook → cold prospects) ---
889
981
  export {
890
982
  type ColdChannelPosture,