@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,187 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { hours } from "@hogsend/core";
4
+ import { accountLinksFromEnv } from "./account-links-from-env.js";
5
+
6
+ // `accountLinksFromEnv` is pure — it reads only the fields below off the env
7
+ // OBJECT it is handed, so the suite builds plain literals instead of stubbing
8
+ // process.env (env.ts itself is imported as a TYPE only; nothing here trips
9
+ // its import-time validation).
10
+ type EngineEnv = Parameters<typeof accountLinksFromEnv>[0];
11
+
12
+ function makeEnv(overrides: Partial<EngineEnv> = {}): EngineEnv {
13
+ return {
14
+ API_PUBLIC_URL: "https://api.example.com",
15
+ // The schema defaults this to 900, so the parsed env ALWAYS carries it —
16
+ // included here so every case proves the gate ignores it.
17
+ ACCOUNT_LINK_STATE_TTL_SECONDS: 900,
18
+ ...overrides,
19
+ } as EngineEnv;
20
+ }
21
+
22
+ const OPTED_IN = { consumerOptedIn: true };
23
+
24
+ function ids(
25
+ env: EngineEnv,
26
+ options?: { consumerOptedIn?: boolean },
27
+ ): string[] {
28
+ return accountLinksFromEnv(env, options).providers.map((p) => p.meta.id);
29
+ }
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // The intent gate
33
+ // ---------------------------------------------------------------------------
34
+
35
+ test("builds NO providers from a truly empty env", () => {
36
+ // The inert-when-unconfigured posture: no ACCOUNT_LINK_* var, no
37
+ // STEAM_WEB_API_KEY, no consumer option ⇒ nothing registers, so a bare
38
+ // deploy exposes no /v1/accounts/* provider and warns about nothing.
39
+ const result = accountLinksFromEnv(makeEnv());
40
+ assert.deepEqual(result.providers, []);
41
+ assert.deepEqual(result.warnings, []);
42
+ });
43
+
44
+ test("ACCOUNT_LINK_STATE_TTL_SECONDS alone is NOT intent", () => {
45
+ // The var carries `.default(900)`, so it is ALWAYS truthy on the parsed
46
+ // env. If it ever joined the intent check the gate would be vacuously true
47
+ // on every deploy — the exact bug the gate exists to remove. An explicit
48
+ // non-default value must not count either: setting a TTL tunes a flow, it
49
+ // does not ask for one.
50
+ const result = accountLinksFromEnv(
51
+ makeEnv({ ACCOUNT_LINK_STATE_TTL_SECONDS: 1234 }),
52
+ );
53
+ assert.deepEqual(result.providers, []);
54
+ assert.deepEqual(result.warnings, []);
55
+ });
56
+
57
+ test("builds steam from ACCOUNT_LINK_ALLOWED_ORIGINS alone", () => {
58
+ // Env intent with no credential at all — an allowlist only exists for the
59
+ // account-link flow, so setting it is asking for the feature.
60
+ const result = accountLinksFromEnv(
61
+ makeEnv({ ACCOUNT_LINK_ALLOWED_ORIGINS: "https://play.example.com" }),
62
+ );
63
+ assert.deepEqual(
64
+ result.providers.map((p) => p.meta.id),
65
+ ["steam"],
66
+ );
67
+ assert.deepEqual(result.warnings, []);
68
+ });
69
+
70
+ test("builds steam when the consumer passes an accountLinks option", () => {
71
+ // Code intent: the container passes `consumerOptedIn` when ANY
72
+ // `accountLinks` option was given to createHogsendClient — even `{}`.
73
+ const result = accountLinksFromEnv(makeEnv(), OPTED_IN);
74
+ assert.deepEqual(
75
+ result.providers.map((p) => p.meta.id),
76
+ ["steam"],
77
+ );
78
+ assert.deepEqual(result.warnings, []);
79
+ });
80
+
81
+ test("builds steam and ONLY steam from an otherwise empty env, once opted in", () => {
82
+ // The zero-CREDENTIAL proof (steam needs no app registration, no client
83
+ // id, no secret) — intent shown, nothing else configured.
84
+ const result = accountLinksFromEnv(makeEnv(), OPTED_IN);
85
+ assert.deepEqual(
86
+ result.providers.map((p) => p.meta.id),
87
+ ["steam"],
88
+ );
89
+ assert.deepEqual(result.warnings, []);
90
+ });
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Twitch
94
+ // ---------------------------------------------------------------------------
95
+
96
+ test("builds twitch when both vars are set", () => {
97
+ const result = accountLinksFromEnv(
98
+ makeEnv({
99
+ ACCOUNT_LINK_TWITCH_CLIENT_ID: "cid",
100
+ ACCOUNT_LINK_TWITCH_CLIENT_SECRET: "csecret",
101
+ }),
102
+ );
103
+ assert.deepEqual(
104
+ result.providers.map((p) => p.meta.id),
105
+ ["steam", "twitch"],
106
+ );
107
+ assert.deepEqual(result.warnings, []);
108
+ });
109
+
110
+ test("omits twitch and warns naming ACCOUNT_LINK_TWITCH_CLIENT_SECRET when only the id is set", () => {
111
+ const result = accountLinksFromEnv(
112
+ makeEnv({ ACCOUNT_LINK_TWITCH_CLIENT_ID: "cid" }),
113
+ );
114
+ assert.deepEqual(
115
+ result.providers.map((p) => p.meta.id),
116
+ ["steam"],
117
+ );
118
+ assert.equal(result.warnings.length, 1);
119
+ assert.match(
120
+ result.warnings[0] ?? "",
121
+ /ACCOUNT_LINK_TWITCH_CLIENT_SECRET is unset/,
122
+ );
123
+ });
124
+
125
+ test("omits twitch and warns naming ACCOUNT_LINK_TWITCH_CLIENT_ID when only the secret is set", () => {
126
+ const result = accountLinksFromEnv(
127
+ makeEnv({ ACCOUNT_LINK_TWITCH_CLIENT_SECRET: "csecret" }),
128
+ );
129
+ assert.deepEqual(
130
+ result.providers.map((p) => p.meta.id),
131
+ ["steam"],
132
+ );
133
+ assert.equal(result.warnings.length, 1);
134
+ assert.match(
135
+ result.warnings[0] ?? "",
136
+ /ACCOUNT_LINK_TWITCH_CLIENT_ID is unset/,
137
+ );
138
+ });
139
+
140
+ // ---------------------------------------------------------------------------
141
+ // Steam widen-not-enable
142
+ // ---------------------------------------------------------------------------
143
+
144
+ test("registers steam with no web api key and omits the sync capability", () => {
145
+ const result = accountLinksFromEnv(makeEnv(), OPTED_IN);
146
+ const steam = result.providers.find((p) => p.meta.id === "steam");
147
+ // The widen-not-enable proof: the provider EXISTS without the key…
148
+ assert.ok(steam, "steam must register with no STEAM_WEB_API_KEY");
149
+ // …and only the sync capability is missing.
150
+ assert.equal(steam.sync, undefined);
151
+ });
152
+
153
+ test("attaches the steam sync capability when STEAM_WEB_API_KEY is set", () => {
154
+ // The key is itself env intent, so no opt-in is needed alongside it.
155
+ const result = accountLinksFromEnv(makeEnv({ STEAM_WEB_API_KEY: "wak" }));
156
+ const steam = result.providers.find((p) => p.meta.id === "steam");
157
+ assert.ok(steam);
158
+ assert.equal(typeof steam.sync?.read, "function");
159
+ assert.deepEqual(steam.sync?.every, hours(24));
160
+ });
161
+
162
+ test("passes API_PUBLIC_URL, trailing slash stripped, as the Steam realm", async () => {
163
+ const result = accountLinksFromEnv(
164
+ makeEnv({ API_PUBLIC_URL: "https://api.example.com/" }),
165
+ OPTED_IN,
166
+ );
167
+ const steam = result.providers.find((p) => p.meta.id === "steam");
168
+ assert.ok(steam);
169
+ const url = new URL(
170
+ await steam.authorizeUrl({
171
+ state: "s",
172
+ redirectUri: "https://api.example.com/v1/accounts/steam/callback",
173
+ }),
174
+ );
175
+ assert.equal(url.searchParams.get("openid.realm"), "https://api.example.com");
176
+ });
177
+
178
+ test("builds no discord provider under any env", () => {
179
+ const fullyConfigured = makeEnv({
180
+ ACCOUNT_LINK_TWITCH_CLIENT_ID: "cid",
181
+ ACCOUNT_LINK_TWITCH_CLIENT_SECRET: "csecret",
182
+ STEAM_WEB_API_KEY: "wak",
183
+ });
184
+ for (const env of [makeEnv(), fullyConfigured]) {
185
+ assert.equal(ids(env, OPTED_IN).includes("discord"), false);
186
+ }
187
+ });
@@ -0,0 +1,190 @@
1
+ import type { AccountLinkProvider } from "@hogsend/core";
2
+ import { battlenetAccountLink } from "../account-links/battlenet.js";
3
+ import { epicAccountLink } from "../account-links/epic.js";
4
+ import { riotAccountLink } from "../account-links/riot.js";
5
+ import { steamAccountLink } from "../account-links/steam.js";
6
+ import { twitchAccountLink } from "../account-links/twitch.js";
7
+ import { xboxAccountLink } from "../account-links/xbox.js";
8
+ import type { env as envSchema } from "../env.js";
9
+
10
+ export interface AccountLinkEnvResult {
11
+ providers: AccountLinkProvider[];
12
+ /** One line per partially-configured provider. The container logs each ONCE. */
13
+ warnings: string[];
14
+ }
15
+
16
+ export interface AccountLinksFromEnvOptions {
17
+ /**
18
+ * True when the consumer passed ANY `accountLinks` option to
19
+ * `createHogsendClient` — even `accountLinks: {}`. Code-side intent: an
20
+ * operator who mentioned the feature gets the presets.
21
+ */
22
+ consumerOptedIn?: boolean;
23
+ }
24
+
25
+ /**
26
+ * The env vars whose PRESENCE signals the operator wants account linking.
27
+ * `ACCOUNT_LINK_STATE_TTL_SECONDS` is deliberately NOT here: it carries
28
+ * `.default(900)` in the schema, so the parsed value is ALWAYS truthy and
29
+ * counting it would make the intent gate vacuously true — exactly the
30
+ * register-on-every-deploy bug this gate removes. (If it ever must count,
31
+ * read the raw `process.env` key to distinguish set from defaulted.)
32
+ */
33
+ function hasEnvIntent(env: typeof envSchema): boolean {
34
+ return Boolean(
35
+ env.ACCOUNT_LINK_TWITCH_CLIENT_ID ||
36
+ env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET ||
37
+ env.STEAM_WEB_API_KEY ||
38
+ env.ACCOUNT_LINK_BATTLENET_CLIENT_ID ||
39
+ env.ACCOUNT_LINK_BATTLENET_CLIENT_SECRET ||
40
+ env.ACCOUNT_LINK_EPIC_CLIENT_ID ||
41
+ env.ACCOUNT_LINK_EPIC_CLIENT_SECRET ||
42
+ env.ACCOUNT_LINK_XBOX_CLIENT_ID ||
43
+ env.ACCOUNT_LINK_XBOX_CLIENT_SECRET ||
44
+ env.ACCOUNT_LINK_RIOT_CLIENT_ID ||
45
+ env.ACCOUNT_LINK_RIOT_CLIENT_SECRET ||
46
+ env.ACCOUNT_LINK_ALLOWED_ORIGINS,
47
+ );
48
+ }
49
+
50
+ /**
51
+ * Build the env-enabled account-link provider presets. Structural mirror of
52
+ * `emailProvidersFromEnv` (`lib/email-providers-from-env.ts`), with two
53
+ * deliberate divergences:
54
+ *
55
+ * 1. **Static imports.** No `loadOptionalPlugin`, no runtime-assembled
56
+ * specifier, because the six built-in providers are IN-PACKAGE config over
57
+ * the `@hogsend/core` presets, not opt-in plugin packages (DECISIONS §3.1).
58
+ * No top-level `await`, so `createHogsendClient` stays synchronous.
59
+ * 2. **It returns warnings rather than calling `console.warn`.** The email
60
+ * preset builder warns straight to `console.warn` because it runs before a
61
+ * logger exists; here the container already has `logger`, so the strings
62
+ * come back and the container logs them through the real logger. That keeps
63
+ * this function pure and unit-testable with no console spy.
64
+ *
65
+ * Rules:
66
+ * - **Presets register only when the operator shows INTENT** in account links,
67
+ * preserving this repo's inert-when-unconfigured posture: a deploy that
68
+ * never asked for account linking gets no public `/v1/accounts/*` surface
69
+ * and no boot warning. Intent is EITHER env-side ({@link hasEnvIntent}: any
70
+ * `ACCOUNT_LINK_*` var, `STEAM_WEB_API_KEY`, or
71
+ * `ACCOUNT_LINK_ALLOWED_ORIGINS` set) OR code-side
72
+ * ({@link AccountLinksFromEnvOptions.consumerOptedIn}: any `accountLinks`
73
+ * option passed, even `{}`). No intent ⇒ empty result.
74
+ * - **Steam stays credential-free** and registers on ANY intent. "Sign in
75
+ * through Steam" is OpenID 2.0: the relying party presents no credential of
76
+ * any kind — no app registration, no client id, no secret. The whole
77
+ * security model is the server-side `check_authentication` round-trip,
78
+ * unauthenticated by design. `STEAM_WEB_API_KEY` is OPTIONAL and WIDENS the
79
+ * provider (persona/avatar pull + the playtime sync) rather than enabling
80
+ * it — the preset branches on it, so it is passed straight through, not
81
+ * re-derived here. The only genuine requirement is the realm:
82
+ * `API_PUBLIC_URL` (already required by the engine env), trailing slash
83
+ * stripped — Steam rejects the assertion under a wrong realm. Steam
84
+ * contributes no warning and cannot be half-configured.
85
+ * - OAuth providers (Twitch, Battle.net, Epic, Xbox, Riot) are registered iff
86
+ * BOTH `ACCOUNT_LINK_<ID>_CLIENT_ID` and `_CLIENT_SECRET` are set. Exactly
87
+ * one set ⇒ no registration (absent from the registry, not
88
+ * present-but-disabled) plus a warning naming the MISSING var.
89
+ * - Discord is the only excluded platform: it already ships via
90
+ * `plugin-discord`, and a second writer on `contacts.discordId` would drift.
91
+ *
92
+ * These presets come FIRST in the container's merge — a consumer-supplied
93
+ * provider of the same id wins (last-writer-wins on the registry).
94
+ */
95
+ export function accountLinksFromEnv(
96
+ env: typeof envSchema,
97
+ options: AccountLinksFromEnvOptions = {},
98
+ ): AccountLinkEnvResult {
99
+ const providers: AccountLinkProvider[] = [];
100
+ const warnings: string[] = [];
101
+
102
+ if (!hasEnvIntent(env) && options.consumerOptedIn !== true) {
103
+ return { providers, warnings };
104
+ }
105
+
106
+ providers.push(
107
+ steamAccountLink({
108
+ // Same normalization the SMS webhook route applies: the one
109
+ // operator-controlled degree of freedom is a trailing slash.
110
+ realm: env.API_PUBLIC_URL.replace(/\/+$/, ""),
111
+ ...(env.STEAM_WEB_API_KEY ? { webApiKey: env.STEAM_WEB_API_KEY } : {}),
112
+ }),
113
+ );
114
+
115
+ const oauthPresets: Array<{
116
+ id: string;
117
+ clientId: string | undefined;
118
+ clientSecret: string | undefined;
119
+ idVar: string;
120
+ secretVar: string;
121
+ factory: (cfg: {
122
+ clientId: string;
123
+ clientSecret: string;
124
+ }) => AccountLinkProvider;
125
+ portal: string;
126
+ }> = [
127
+ {
128
+ id: "twitch",
129
+ clientId: env.ACCOUNT_LINK_TWITCH_CLIENT_ID,
130
+ clientSecret: env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET,
131
+ idVar: "ACCOUNT_LINK_TWITCH_CLIENT_ID",
132
+ secretVar: "ACCOUNT_LINK_TWITCH_CLIENT_SECRET",
133
+ factory: twitchAccountLink,
134
+ portal: "https://dev.twitch.tv/console/apps",
135
+ },
136
+ {
137
+ id: "battlenet",
138
+ clientId: env.ACCOUNT_LINK_BATTLENET_CLIENT_ID,
139
+ clientSecret: env.ACCOUNT_LINK_BATTLENET_CLIENT_SECRET,
140
+ idVar: "ACCOUNT_LINK_BATTLENET_CLIENT_ID",
141
+ secretVar: "ACCOUNT_LINK_BATTLENET_CLIENT_SECRET",
142
+ factory: battlenetAccountLink,
143
+ portal: "https://develop.battle.net/access",
144
+ },
145
+ {
146
+ id: "epic",
147
+ clientId: env.ACCOUNT_LINK_EPIC_CLIENT_ID,
148
+ clientSecret: env.ACCOUNT_LINK_EPIC_CLIENT_SECRET,
149
+ idVar: "ACCOUNT_LINK_EPIC_CLIENT_ID",
150
+ secretVar: "ACCOUNT_LINK_EPIC_CLIENT_SECRET",
151
+ factory: epicAccountLink,
152
+ portal: "https://dev.epicgames.com/portal",
153
+ },
154
+ {
155
+ id: "xbox",
156
+ clientId: env.ACCOUNT_LINK_XBOX_CLIENT_ID,
157
+ clientSecret: env.ACCOUNT_LINK_XBOX_CLIENT_SECRET,
158
+ idVar: "ACCOUNT_LINK_XBOX_CLIENT_ID",
159
+ secretVar: "ACCOUNT_LINK_XBOX_CLIENT_SECRET",
160
+ factory: xboxAccountLink,
161
+ portal: "https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps",
162
+ },
163
+ {
164
+ id: "riot",
165
+ clientId: env.ACCOUNT_LINK_RIOT_CLIENT_ID,
166
+ clientSecret: env.ACCOUNT_LINK_RIOT_CLIENT_SECRET,
167
+ idVar: "ACCOUNT_LINK_RIOT_CLIENT_ID",
168
+ secretVar: "ACCOUNT_LINK_RIOT_CLIENT_SECRET",
169
+ factory: riotAccountLink,
170
+ portal: "https://developer.riotgames.com",
171
+ },
172
+ ];
173
+
174
+ for (const p of oauthPresets) {
175
+ if (p.clientId && p.clientSecret) {
176
+ providers.push(
177
+ p.factory({ clientId: p.clientId, clientSecret: p.clientSecret }),
178
+ );
179
+ } else if (p.clientId || p.clientSecret) {
180
+ const missing = p.clientId ? p.secretVar : p.idVar;
181
+ warnings.push(
182
+ `${p.id} account linking is half-configured: ${missing} is unset, ` +
183
+ `so the ${p.id} provider is NOT registered. Set both ${p.idVar} ` +
184
+ `and ${p.secretVar} (from ${p.portal}), or unset both`,
185
+ );
186
+ }
187
+ }
188
+
189
+ return { providers, warnings };
190
+ }