@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,34 @@
1
+ /**
2
+ * Lazy access to `env.BETTER_AUTH_SECRET`, the engine's one master secret
3
+ * (AES-256-GCM key material for sealed link tokens and stored provider
4
+ * credentials).
5
+ *
6
+ * WHY THIS MODULE EXISTS: `../env.js` calls `createEnv` at MODULE SCOPE, so a
7
+ * static `import { env }` anywhere makes that file's whole import graph
8
+ * unloadable without a full, valid environment. `lib/account-links.ts` and
9
+ * `lib/provider-credentials.ts` are both reachable from `src/testing.ts` — the
10
+ * `@hogsend/engine/testing` entry point, which `@hogsend/testing` imports from
11
+ * a consumer app that has NO environment at all (the scaffold's packed-consumer
12
+ * smoke runs it under plain `tsx` with every var stripped). A static env import
13
+ * on that path turns "import a journey test helper" into "Invalid environment
14
+ * variables".
15
+ *
16
+ * Neither module reads the secret at module scope — only inside functions that
17
+ * are already `async` — so resolving it lazily costs nothing and validates
18
+ * EXACTLY the same contract: this loads the real `env.js`, it does not re-read
19
+ * or re-validate `process.env` itself. In a running API/worker `env.js` is
20
+ * already in the module cache (the container imports it at boot, so a bad
21
+ * environment still fails fast at startup); here the `await` just hands back
22
+ * the cached module.
23
+ *
24
+ * The promise is memoised, so the module is loaded — and, on a bad
25
+ * environment, throws — exactly once.
26
+ */
27
+
28
+ let secret: Promise<string> | undefined;
29
+
30
+ /** The validated `BETTER_AUTH_SECRET`, loading `env.js` on first use. */
31
+ export function getAppSecret(): Promise<string> {
32
+ secret ??= import("../env.js").then((m) => m.env.BETTER_AUTH_SECRET);
33
+ return secret;
34
+ }
@@ -23,10 +23,19 @@ import {
23
23
  ContactSourceRegistry,
24
24
  setContactSourceRegistry,
25
25
  } from "../sources/registry.js";
26
- import {
27
- checkActionAudience,
28
- sendConnectorAction,
29
- } from "./connector-actions.js";
26
+
27
+ // connector-actions' import chain reaches env.ts (validates required env vars
28
+ // at import time — via contacts.ts → the account-link store, PRD 04) — stub
29
+ // the required vars BEFORE the dynamic import, exactly as bucket-emit.test.ts
30
+ // does. Nothing is ever contacted: the boundary/registry seams intercept
31
+ // everything, and the DATABASE_URL points at a port nothing listens on.
32
+ process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
33
+ process.env.BETTER_AUTH_SECRET ??= "test-secret";
34
+ process.env.HATCHET_CLIENT_TOKEN ??=
35
+ "eyJhbGciOiJFUzI1NiIsImtpZCI6InRlc3QifQ.eyJhdWQiOiJsb2NhbGhvc3QiLCJleHAiOjQ5MzMyNDA5ODMsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyIsImlhdCI6MTc3OTY0MDk4MywiaXNzIjoibG9jYWxob3N0Iiwic2VydmVyX3VybCI6ImxvY2FsaG9zdCIsInN1YiI6InRlc3QtdGVuYW50LWlkIiwidG9rZW5faWQiOiJ0ZXN0LXRva2VuLWlkIn0.test";
36
+ const { checkActionAudience, sendConnectorAction } = await import(
37
+ "./connector-actions.js"
38
+ );
30
39
 
31
40
  test("a scoped connector override requires registration validation before capture", async () => {
32
41
  let captures = 0;
@@ -0,0 +1,114 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import {
4
+ type ConnectorStateIntent,
5
+ signConnectorState,
6
+ verifyConnectorState,
7
+ } from "./connector-state.js";
8
+
9
+ /**
10
+ * PRD 07 T1 — the `account_link` purpose on the ONE state token format.
11
+ *
12
+ * There is deliberately no second token: `BETTER_AUTH_SECRET` signs every state
13
+ * in the process, so a second format would be a second thing to keep hardened.
14
+ * What IS new is `providerId`, which is why the cross-surface tests below (and
15
+ * `apps/api/src/__tests__/connectors-oauth-state-purpose.test.ts`) exist.
16
+ */
17
+
18
+ const SECRET = "test-secret-for-account-link-state-minimum-32-characters";
19
+
20
+ const WARM: ConnectorStateIntent = {
21
+ purpose: "account_link",
22
+ providerId: "steam",
23
+ contactId: "11111111-2222-3333-4444-555555555555",
24
+ returnTo: "https://play.example.com/settings",
25
+ nonce: "nonce-warm",
26
+ };
27
+
28
+ const COLD: ConnectorStateIntent = {
29
+ purpose: "account_link",
30
+ providerId: "twitch",
31
+ anonymousId: "anon-abc",
32
+ nonce: "nonce-cold",
33
+ };
34
+
35
+ test("signs and verifies an account_link intent round-trip", () => {
36
+ for (const intent of [WARM, COLD]) {
37
+ const result = verifyConnectorState(
38
+ signConnectorState(intent, SECRET, 900),
39
+ SECRET,
40
+ );
41
+ assert.equal(result.valid, true);
42
+ assert.deepEqual(result.intent, intent);
43
+ // The connector surface's binding field is absent, not empty-string.
44
+ assert.equal(result.intent?.connectorId, undefined);
45
+ }
46
+ });
47
+
48
+ test("a tampered payload fails with bad_signature", () => {
49
+ const token = signConnectorState(WARM, SECRET, 900);
50
+ const [payloadB64, sig] = token.split(".");
51
+ assert.ok(payloadB64 && sig);
52
+ const payload = JSON.parse(
53
+ Buffer.from(payloadB64, "base64url").toString("utf8"),
54
+ ) as Record<string, unknown>;
55
+ // The exact attack the signature exists to stop: re-point the sealed
56
+ // contact at someone else's row and keep the old signature.
57
+ payload.contactId = "99999999-9999-9999-9999-999999999999";
58
+ const forged = `${Buffer.from(JSON.stringify(payload)).toString("base64url")}.${sig}`;
59
+
60
+ const result = verifyConnectorState(forged, SECRET);
61
+ assert.equal(result.valid, false);
62
+ assert.equal(result.reason, "bad_signature");
63
+ assert.equal(result.intent, undefined);
64
+ });
65
+
66
+ test("an expired account_link state fails with expired", () => {
67
+ const token = signConnectorState(WARM, SECRET, -1);
68
+ const result = verifyConnectorState(token, SECRET);
69
+ assert.equal(result.valid, false);
70
+ assert.equal(result.reason, "expired");
71
+ assert.equal(result.intent, undefined);
72
+ });
73
+
74
+ test("the existing install/member_link round-trips are unchanged", () => {
75
+ const install: ConnectorStateIntent = {
76
+ purpose: "install",
77
+ connectorId: "discord",
78
+ nonce: "nonce-install",
79
+ };
80
+ const memberLink: ConnectorStateIntent = {
81
+ purpose: "member_link",
82
+ connectorId: "discord",
83
+ contactId: "contact-123",
84
+ email: "alice@example.com",
85
+ nonce: "nonce-member",
86
+ };
87
+
88
+ for (const intent of [install, memberLink]) {
89
+ const result = verifyConnectorState(
90
+ signConnectorState(intent, SECRET, 600),
91
+ SECRET,
92
+ );
93
+ assert.equal(result.valid, true);
94
+ assert.deepEqual(result.intent, intent);
95
+ // Neither connector purpose ever carries the account-link fields.
96
+ assert.equal(result.intent?.providerId, undefined);
97
+ assert.equal(result.intent?.anonymousId, undefined);
98
+ assert.equal(result.intent?.returnTo, undefined);
99
+ }
100
+ });
101
+
102
+ test("an account_link state carries no connectorId, so the connector callback's own check rejects it", () => {
103
+ // `routes/connectors/index.ts` compares `intent.connectorId !== id`, and
104
+ // `undefined !== "steam"` is true. This pins the INCIDENTAL half of the
105
+ // defence; the EXPLICIT purpose allowlist is pinned separately in
106
+ // `apps/api/src/__tests__/connectors-oauth-state-purpose.test.ts` so the two
107
+ // guards are never aliased onto one test.
108
+ const result = verifyConnectorState(
109
+ signConnectorState(WARM, SECRET, 900),
110
+ SECRET,
111
+ );
112
+ assert.equal(result.valid, true);
113
+ assert.notEqual(result.intent?.connectorId, "steam");
114
+ });
@@ -13,6 +13,14 @@ import { safeEqual } from "../webhook-sources/verify.js";
13
13
  * link was issued for, so the callback attaches the platform identity to THAT
14
14
  * contact (never to whatever email the platform happens to report — the
15
15
  * grafting/account-takeover vector).
16
+ * - `purpose: "account_link"` — binds ONE account-link attempt
17
+ * (`/v1/accounts/:provider/start` → `/callback`, PRD 07) to the provider it
18
+ * was minted for (`providerId`) and to the contact side it may attach to:
19
+ * either a sealed `contactId` (the WARM binding, authoritative — the
20
+ * provider-reported email is NEVER a resolution key) or an `anonymousId`
21
+ * (the COLD binding, which may attach only to an anonymous-only contact,
22
+ * DECISIONS §6.10). It also carries the already-allowlist-checked
23
+ * `returnTo`, re-checked at redirect time.
16
24
  *
17
25
  * The token is `base64url(JSON(payload)).base64url(HMAC-SHA256(payloadB64))`,
18
26
  * signed with the engine's `BETTER_AUTH_SECRET`. The same hardened constant-time
@@ -25,12 +33,49 @@ import { safeEqual } from "../webhook-sources/verify.js";
25
33
  * it, but the same token works until expiry. The mint TTL is the replay window.
26
34
  */
27
35
  export interface ConnectorStateIntent {
28
- purpose: "install" | "member_link";
29
- connectorId: string;
30
- /** Member-link only — the bound contact id (authoritative resolution key). */
36
+ purpose: "install" | "member_link" | "account_link";
37
+ /**
38
+ * Connector flows only (`install` / `member_link`). OPTIONAL now that
39
+ * `account_link` exists — an account-link state binds `providerId` instead.
40
+ */
41
+ connectorId?: string;
42
+ /**
43
+ * `account_link` only — the `AccountLinkProvider` `meta.id` this state was
44
+ * minted for.
45
+ *
46
+ * A NEW field, deliberately NOT a reuse of {@link connectorId}: one secret
47
+ * signs every state in the process, so a state minted for one surface is
48
+ * signature-valid on the other, and a future connector id colliding with an
49
+ * account-link provider id (both `"discord"`, say) would make the two
50
+ * indistinguishable. Two fields cannot be confused. The connector callback's
51
+ * `intent.connectorId !== id` check already rejects an account-link state
52
+ * incidentally (`undefined !== id`), and it also states the rule explicitly
53
+ * with a purpose allowlist.
54
+ */
55
+ providerId?: string;
56
+ /**
57
+ * `member_link`, and `account_link`'s WARM binding — the bound contact id.
58
+ * AUTHORITATIVE: the callback attaches to THIS contact and never to whatever
59
+ * email the platform reports (DECISIONS §6.3).
60
+ */
31
61
  contactId?: string;
32
62
  /** Member-link only — the bound contact email (authoritative resolution key). */
33
63
  email?: string;
64
+ /**
65
+ * `account_link` COLD binding only — the browser anonymous key the link
66
+ * attaches to. It is browser-readable by design, so a cold link may attach
67
+ * ONLY to an anonymous-only contact and may never displace a live owner
68
+ * (DECISIONS §6.10). Exactly one of {@link contactId} / `anonymousId` is set
69
+ * on an account-link state.
70
+ */
71
+ anonymousId?: string;
72
+ /**
73
+ * `account_link` only — where to send the player after a completed link.
74
+ * Allowlist-checked at MINT time AND re-checked at redirect time, because
75
+ * the allowlist can change between the two (and a signed state outlives a
76
+ * config edit).
77
+ */
78
+ returnTo?: string;
34
79
  /**
35
80
  * High-entropy per-mint value so two states are never byte-identical AND so
36
81
  * the callback can burn it for single-use replay protection (see header).