@hogsend/engine 0.64.0 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/package.json +12 -12
  2. package/src/account-links/__fixtures__/fake-fetch.test.ts +57 -0
  3. package/src/account-links/__fixtures__/fake-fetch.ts +114 -0
  4. package/src/account-links/__fixtures__/steam.json +21 -0
  5. package/src/account-links/__fixtures__/twitch.json +22 -0
  6. package/src/account-links/index.ts +8 -0
  7. package/src/account-links/steam.test.ts +243 -0
  8. package/src/account-links/steam.ts +48 -0
  9. package/src/account-links/twitch.test.ts +157 -0
  10. package/src/account-links/twitch.ts +99 -0
  11. package/src/container.account-links.env.test.ts +65 -0
  12. package/src/container.account-links.halfenv.test.ts +48 -0
  13. package/src/container.account-links.test.ts +185 -0
  14. package/src/container.ts +120 -0
  15. package/src/env.ts +37 -0
  16. package/src/index.ts +87 -1
  17. package/src/lib/account-link-emit.ts +126 -0
  18. package/src/lib/account-link-events.ts +180 -0
  19. package/src/lib/account-link-hooks.test.ts +158 -0
  20. package/src/lib/account-link-hooks.ts +73 -0
  21. package/src/lib/account-link-ingest.ts +364 -0
  22. package/src/lib/account-link-nonce.test.ts +52 -0
  23. package/src/lib/account-link-nonce.ts +57 -0
  24. package/src/lib/account-link-origins.test.ts +72 -0
  25. package/src/lib/account-link-origins.ts +87 -0
  26. package/src/lib/account-link-pkce.test.ts +91 -0
  27. package/src/lib/account-link-pkce.ts +106 -0
  28. package/src/lib/account-link-provider-registry.test.ts +52 -0
  29. package/src/lib/account-link-provider-registry.ts +61 -0
  30. package/src/lib/account-link-throttle.test.ts +178 -0
  31. package/src/lib/account-link-throttle.ts +130 -0
  32. package/src/lib/account-link-url.ts +85 -0
  33. package/src/lib/account-links-emit.test.ts +525 -0
  34. package/src/lib/account-links-env.test.ts +40 -0
  35. package/src/lib/account-links-from-env.test.ts +187 -0
  36. package/src/lib/account-links-from-env.ts +126 -0
  37. package/src/lib/account-links.ts +1300 -0
  38. package/src/lib/app-secret.ts +34 -0
  39. package/src/lib/connector-actions.test.ts +13 -4
  40. package/src/lib/connector-state.account-link.test.ts +114 -0
  41. package/src/lib/connector-state.ts +48 -3
  42. package/src/lib/contacts.ts +320 -6
  43. package/src/lib/outbound-account-payloads.test.ts +137 -0
  44. package/src/lib/outbound.ts +91 -0
  45. package/src/lib/provider-credentials.ts +19 -5
  46. package/src/lib/webhook-catalog-sync.test.ts +24 -0
  47. package/src/lib/webhook-signing.ts +18 -1
  48. package/src/routes/accounts/callback.ts +597 -0
  49. package/src/routes/accounts/emit.ts +231 -0
  50. package/src/routes/accounts/import-links.ts +210 -0
  51. package/src/routes/accounts/index.ts +75 -0
  52. package/src/routes/accounts/lookup.ts +177 -0
  53. package/src/routes/accounts/me.ts +215 -0
  54. package/src/routes/accounts/mint.ts +279 -0
  55. package/src/routes/accounts/pages.ts +62 -0
  56. package/src/routes/accounts/resolve.ts +61 -0
  57. package/src/routes/accounts/serialize.ts +96 -0
  58. package/src/routes/accounts/shared.ts +107 -0
  59. package/src/routes/accounts/start.ts +229 -0
  60. package/src/routes/accounts/unlink.ts +98 -0
  61. package/src/routes/admin/agent.ts +2 -0
  62. package/src/routes/admin/api-keys.ts +7 -0
  63. package/src/routes/admin/contacts.ts +38 -2
  64. package/src/routes/connectors/index.ts +17 -0
  65. package/src/routes/contacts/index.ts +8 -0
  66. package/src/routes/index.ts +75 -0
  67. package/src/testing-barrel.test.ts +74 -0
  68. package/src/testing.ts +17 -0
@@ -4,6 +4,7 @@ import type { HogsendClient } from "../container.js";
4
4
  import { requireApiKey, requireScope } from "../middleware/api-key.js";
5
5
  import { requirePublishableOrIngest } from "../middleware/publishable-key.js";
6
6
  import { createRateLimit } from "../middleware/rate-limit.js";
7
+ import { createAccountsRouter } from "./accounts/index.js";
7
8
  import { adminRouter } from "./admin/index.js";
8
9
  import { campaignsRouter } from "./campaigns/index.js";
9
10
  import { registerConnectorRoutes } from "./connectors/index.js";
@@ -148,6 +149,80 @@ export function registerRoutes(
148
149
  // per request), halving the effective per-key budget (decision #16 / risk 15).
149
150
  v1.use("/emails/*", emailRateLimit);
150
151
 
152
+ // ---- Account links (PRD 07's hosted flow + PRD 09's data plane) ----
153
+ //
154
+ // THREE TIERS ON ONE PREFIX, and every path is enumerated EXPLICITLY. There
155
+ // is deliberately NO `/accounts/*` catch-all: a `/<prefix>/*` `use` in Hono
156
+ // also matches the bare `/<prefix>` path AND every literal sibling, so one
157
+ // would 401 the browser-reachable `/accounts/me` + `/accounts/link-url` and
158
+ // the unauthenticated `/accounts/manage` — the same trap documented for
159
+ // `/contacts/*` and `/lists/*` above, which fails CLOSED and silently
160
+ // (DECISIONS §15.1).
161
+ //
162
+ // Tier 1 — browser-reachable literals (publishable OR secret-ingest), each
163
+ // `userToken`-gated INSIDE its handler. Both `/me` entries are enumerated
164
+ // rather than written `/accounts/me/*`: the wildcard trap applies at every
165
+ // depth.
166
+ v1.use("/accounts/me", requirePublishableOrIngest);
167
+ v1.use("/accounts/me/revoke", requirePublishableOrIngest);
168
+ v1.use("/accounts/link-url", requirePublishableOrIngest);
169
+ // Tier 2 — secret-only literals, in the style of `/contacts/find` and
170
+ // `/flags/evaluate` above. `accounts` is an ORTHOGONAL scope
171
+ // (`middleware/api-key.ts:35-40`): an explicit grant or `full-admin`, and no
172
+ // SCOPE_HIERARCHY edit.
173
+ v1.use("/accounts", requireApiKey, requireScope("accounts"));
174
+ v1.use("/accounts/import", requireApiKey, requireScope("accounts"));
175
+ v1.use("/accounts/mint-link", requireApiKey, requireScope("accounts"));
176
+ // `/accounts/manage` (PRD 11) gets NO guard: it is the unauthenticated,
177
+ // token-bearing player page, the same posture as `/v1/email` at :45.
178
+ //
179
+ // Tier 3 — the two-segment param pattern gets ONE BRANCHING guard, never a
180
+ // stacked `requireApiKey, requireScope` pair. This is the most dangerous
181
+ // registration in the file: Hono runs EVERY matching `use`, so this pattern
182
+ // also fires on `/accounts/me/revoke`, `/accounts/:provider/start` and
183
+ // `/accounts/:provider/callback`. Stacking would 401 the entire hosted OAuth
184
+ // flow (PRD 07's routes carry no Authorization header) and 403 the primary
185
+ // player revoke (a pk_ key holds only `["ingest-public"]`). Branch, exactly
186
+ // like the method-branching `/contacts` guard above.
187
+ //
188
+ // `start`, `callback` and `me` are all in `RESERVED_ACCOUNT_LINK_IDS`, so no
189
+ // real provider or providerUserId can reach these branches by accident.
190
+ const accountsScopeGuard = requireScope("accounts");
191
+ v1.use("/accounts/:provider/:providerUserId", async (c, next) => {
192
+ const provider = c.req.param("provider");
193
+ const second = c.req.param("providerUserId");
194
+ // PRD 07's unauthenticated, self-verifying hosted flow. No guard at all.
195
+ //
196
+ // GATED ON METHOD, and that is load-bearing. A `use` matches EVERY method,
197
+ // but the routes this exemption exists for are GET-only. Without the method
198
+ // check, `DELETE /v1/accounts/steam/start` passes no guard here, then finds
199
+ // no matching GET literal, and falls through to the param route's DELETE —
200
+ // the secret-key operator unlink — with no API key at all.
201
+ const method = c.req.method;
202
+ if (method === "GET" && (second === "start" || second === "callback")) {
203
+ return next();
204
+ }
205
+ // The browser-reachable player revoke. Publishable tier; ownership comes
206
+ // from the userToken inside the handler, never from the request. Also
207
+ // method-gated: the literal is POST-only, so a DELETE on this same shape
208
+ // would otherwise reach the operator unlink holding only a `pk_` key.
209
+ if (method === "POST" && provider === "me" && second === "revoke") {
210
+ return requirePublishableOrIngest(c, next);
211
+ }
212
+ // Everything else on this shape is the operator reverse lookup / unlink.
213
+ // `requireApiKey` only runs its `next` on a successful auth, so use a flag
214
+ // to detect a short-circuit and surface its response (the `/contacts`
215
+ // DELETE idiom above).
216
+ let authed = false;
217
+ const res = await requireApiKey(c, async () => {
218
+ authed = true;
219
+ });
220
+ if (!authed) return res;
221
+ return accountsScopeGuard(c, next);
222
+ });
223
+
224
+ v1.route("/accounts", createAccountsRouter());
225
+
151
226
  v1.route("/contacts", contactsRouter);
152
227
  v1.route("/events", eventsRouter);
153
228
  v1.route("/feed", feedRouter);
@@ -0,0 +1,74 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import test from "node:test";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ /**
7
+ * `src/testing.ts` — the `@hogsend/engine/testing` entry point — is documented
8
+ * side-effect-free, and `@hogsend/testing` re-exports from it. Consumers import
9
+ * that package from an app that may have NO environment at all: the scaffold's
10
+ * `[2c] clean packed-consumer runtime import` gate builds a throwaway project
11
+ * whose only dependency is `@hogsend/testing`, writes a two-line file importing
12
+ * `createJourneyTest`, and runs it with plain `tsx` and an empty environment.
13
+ *
14
+ * `src/env.ts` calls `createEnv` at MODULE SCOPE, so ANY static
15
+ * `import { env }` anywhere in the barrel's import graph turns that into
16
+ * "Invalid environment variables" — including one added several modules deep
17
+ * (the barrel exports `softDeleteContact` from `lib/contacts.ts`, which reaches
18
+ * `lib/account-links.ts`, which reaches `lib/provider-credentials.ts`).
19
+ *
20
+ * This has to run in a CHILD PROCESS: `env.ts` caches its validation on first
21
+ * import, and this package's own suite runs with a full environment, so an
22
+ * in-process `await import()` here would pass no matter what. And it strips the
23
+ * environment rather than reading source, so it catches the edge WHEREVER in
24
+ * the graph it reappears — not just in the files we already know about.
25
+ */
26
+
27
+ /** Every var `src/env.ts` declares with no `.default()` / `.optional()`. */
28
+ const REQUIRED_ENGINE_VARS = [
29
+ "DATABASE_URL",
30
+ "BETTER_AUTH_SECRET",
31
+ "HATCHET_CLIENT_TOKEN",
32
+ ];
33
+
34
+ test("the testing barrel imports with no environment", () => {
35
+ // Keep PATH/NODE_OPTIONS etc. so the child can still resolve its TypeScript
36
+ // loader; drop exactly what `env.ts` demands.
37
+ const env = { ...process.env };
38
+ for (const name of REQUIRED_ENGINE_VARS) delete env[name];
39
+
40
+ const barrel = pathToFileURL(
41
+ new URL("./testing.ts", import.meta.url).pathname,
42
+ ).href;
43
+
44
+ let stdout: string;
45
+ try {
46
+ stdout = execFileSync(
47
+ process.execPath,
48
+ [
49
+ ...process.execArgv,
50
+ "--input-type=module",
51
+ "-e",
52
+ `await import(${JSON.stringify(barrel)});\nconsole.log("BARREL_OK");`,
53
+ ],
54
+ { env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },
55
+ );
56
+ } catch (err) {
57
+ const detail =
58
+ err && typeof err === "object" && "stderr" in err
59
+ ? String((err as { stderr: unknown }).stderr)
60
+ : String(err);
61
+ assert.fail(
62
+ "`@hogsend/engine/testing` no longer imports without an environment. " +
63
+ "Something in its graph gained an import-time `env.ts` dependency — " +
64
+ "use `lib/app-secret.ts` (or another lazy accessor) instead of a " +
65
+ `static \`import { env }\`. Do NOT fix this by stubbing env vars in a test config; the scaffold gate runs plain \`tsx\` with none. Child stderr:\n${detail}`,
66
+ );
67
+ }
68
+
69
+ assert.match(
70
+ stdout,
71
+ /BARREL_OK/,
72
+ "child process did not reach the import — the probe itself is broken",
73
+ );
74
+ });
package/src/testing.ts CHANGED
@@ -10,6 +10,23 @@ export {
10
10
  registerRecordLabel,
11
11
  runWithJourneyBoundary,
12
12
  } from "./journeys/journey-boundary.js";
13
+ // The account-link store's internal mechanics. These live HERE and not on the
14
+ // main barrel on purpose: `packages/engine/src/index.ts` is the committed
15
+ // semver boundary, and how the store happens to take advisory locks (or signal
16
+ // a stale pre-read) is not a promise to consumers. Tests need them to assert
17
+ // lock ORDER, which is the property the whole module exists to guarantee.
18
+ export {
19
+ AccountLinkLockSetChangedError,
20
+ lockPairs,
21
+ MAX_VERSION_RACE_RETRIES,
22
+ pairLockKey,
23
+ } from "./lib/account-links.js";
24
+ // PRD 04's guard + delete-leg tests. `ALL_IDENTITY_KINDS` is the resolver's
25
+ // internal full-trust grant (deliberately not public API — the test pinning
26
+ // that IdentityKind is never widened reads it here); `softDeleteContact` is
27
+ // route-internal on the main barrel, and the delete-leg tests assert on its
28
+ // returned `linkUnlinks` facts directly.
29
+ export { ALL_IDENTITY_KINDS, softDeleteContact } from "./lib/contacts.js";
13
30
  export {
14
31
  type EnrollmentPolicyFacts,
15
32
  type EnrollmentPolicyResult,