@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
@@ -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";
@@ -16,6 +17,7 @@ import { flagsRouter } from "./flags/index.js";
16
17
  import { groupsRouter } from "./groups/index.js";
17
18
  import { healthRouter } from "./health.js";
18
19
  import { listsRouter } from "./lists/index.js";
20
+ import { createSnippetRouter } from "./snippet.js";
19
21
  import { trackingRouter } from "./tracking/index.js";
20
22
  import { shortLinkRouter } from "./tracking/short.js";
21
23
  import { vanityRouter } from "./tracking/vanity.js";
@@ -148,6 +150,80 @@ export function registerRoutes(
148
150
  // per request), halving the effective per-key budget (decision #16 / risk 15).
149
151
  v1.use("/emails/*", emailRateLimit);
150
152
 
153
+ // ---- Account links (PRD 07's hosted flow + PRD 09's data plane) ----
154
+ //
155
+ // THREE TIERS ON ONE PREFIX, and every path is enumerated EXPLICITLY. There
156
+ // is deliberately NO `/accounts/*` catch-all: a `/<prefix>/*` `use` in Hono
157
+ // also matches the bare `/<prefix>` path AND every literal sibling, so one
158
+ // would 401 the browser-reachable `/accounts/me` + `/accounts/link-url` and
159
+ // the unauthenticated `/accounts/manage` — the same trap documented for
160
+ // `/contacts/*` and `/lists/*` above, which fails CLOSED and silently
161
+ // (DECISIONS §15.1).
162
+ //
163
+ // Tier 1 — browser-reachable literals (publishable OR secret-ingest), each
164
+ // `userToken`-gated INSIDE its handler. Both `/me` entries are enumerated
165
+ // rather than written `/accounts/me/*`: the wildcard trap applies at every
166
+ // depth.
167
+ v1.use("/accounts/me", requirePublishableOrIngest);
168
+ v1.use("/accounts/me/revoke", requirePublishableOrIngest);
169
+ v1.use("/accounts/link-url", requirePublishableOrIngest);
170
+ // Tier 2 — secret-only literals, in the style of `/contacts/find` and
171
+ // `/flags/evaluate` above. `accounts` is an ORTHOGONAL scope
172
+ // (`middleware/api-key.ts:35-40`): an explicit grant or `full-admin`, and no
173
+ // SCOPE_HIERARCHY edit.
174
+ v1.use("/accounts", requireApiKey, requireScope("accounts"));
175
+ v1.use("/accounts/import", requireApiKey, requireScope("accounts"));
176
+ v1.use("/accounts/mint-link", requireApiKey, requireScope("accounts"));
177
+ // `/accounts/manage` (PRD 11) gets NO guard: it is the unauthenticated,
178
+ // token-bearing player page, the same posture as `/v1/email` at :45.
179
+ //
180
+ // Tier 3 — the two-segment param pattern gets ONE BRANCHING guard, never a
181
+ // stacked `requireApiKey, requireScope` pair. This is the most dangerous
182
+ // registration in the file: Hono runs EVERY matching `use`, so this pattern
183
+ // also fires on `/accounts/me/revoke`, `/accounts/:provider/start` and
184
+ // `/accounts/:provider/callback`. Stacking would 401 the entire hosted OAuth
185
+ // flow (PRD 07's routes carry no Authorization header) and 403 the primary
186
+ // player revoke (a pk_ key holds only `["ingest-public"]`). Branch, exactly
187
+ // like the method-branching `/contacts` guard above.
188
+ //
189
+ // `start`, `callback` and `me` are all in `RESERVED_ACCOUNT_LINK_IDS`, so no
190
+ // real provider or providerUserId can reach these branches by accident.
191
+ const accountsScopeGuard = requireScope("accounts");
192
+ v1.use("/accounts/:provider/:providerUserId", async (c, next) => {
193
+ const provider = c.req.param("provider");
194
+ const second = c.req.param("providerUserId");
195
+ // PRD 07's unauthenticated, self-verifying hosted flow. No guard at all.
196
+ //
197
+ // GATED ON METHOD, and that is load-bearing. A `use` matches EVERY method,
198
+ // but the routes this exemption exists for are GET-only. Without the method
199
+ // check, `DELETE /v1/accounts/steam/start` passes no guard here, then finds
200
+ // no matching GET literal, and falls through to the param route's DELETE —
201
+ // the secret-key operator unlink — with no API key at all.
202
+ const method = c.req.method;
203
+ if (method === "GET" && (second === "start" || second === "callback")) {
204
+ return next();
205
+ }
206
+ // The browser-reachable player revoke. Publishable tier; ownership comes
207
+ // from the userToken inside the handler, never from the request. Also
208
+ // method-gated: the literal is POST-only, so a DELETE on this same shape
209
+ // would otherwise reach the operator unlink holding only a `pk_` key.
210
+ if (method === "POST" && provider === "me" && second === "revoke") {
211
+ return requirePublishableOrIngest(c, next);
212
+ }
213
+ // Everything else on this shape is the operator reverse lookup / unlink.
214
+ // `requireApiKey` only runs its `next` on a successful auth, so use a flag
215
+ // to detect a short-circuit and surface its response (the `/contacts`
216
+ // DELETE idiom above).
217
+ let authed = false;
218
+ const res = await requireApiKey(c, async () => {
219
+ authed = true;
220
+ });
221
+ if (!authed) return res;
222
+ return accountsScopeGuard(c, next);
223
+ });
224
+
225
+ v1.route("/accounts", createAccountsRouter());
226
+
151
227
  v1.route("/contacts", contactsRouter);
152
228
  v1.route("/events", eventsRouter);
153
229
  v1.route("/feed", feedRouter);
@@ -169,6 +245,11 @@ export function registerRoutes(
169
245
  // against the GSM-7 segment budget. Unauthenticated like /l.
170
246
  app.route("/", shortLinkRouter);
171
247
 
248
+ // Drop-in browser SDK — root-mounted so the pasted tag is
249
+ // `${API_PUBLIC_URL}/hogsend.js`. Public; 404s when @hogsend/js is not
250
+ // installed next to the engine (best-effort, like the Studio SPA).
251
+ app.route("/", createSnippetRouter());
252
+
172
253
  // Generic connector dispatch (oauth/interactions/ingress) — the static
173
254
  // `connectors/` prefix is registered BEFORE the `:sourceId` webhook catch-all
174
255
  // so it wins path matching. These routes self-authenticate (oauth state +
@@ -0,0 +1,70 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { OpenAPIHono } from "@hono/zod-openapi";
7
+ import { secureHeaders } from "hono/secure-headers";
8
+ import { loadSnippet } from "../lib/snippet.js";
9
+ import {
10
+ createSnippetRouter,
11
+ SNIPPET_CACHE_CONTROL,
12
+ SNIPPET_PATH,
13
+ } from "./snippet.js";
14
+
15
+ // Mirrors app.ts: secureHeaders on everything EXCEPT the snippet path (it
16
+ // would force CORP same-origin after the handler and break the embed).
17
+ function appWith(path: string | null) {
18
+ const app = new OpenAPIHono();
19
+ const secure = secureHeaders();
20
+ app.use("*", (c, next) =>
21
+ c.req.path === SNIPPET_PATH ? next() : secure(c, next),
22
+ );
23
+ app.route("/", createSnippetRouter(loadSnippet(path)));
24
+ return app;
25
+ }
26
+
27
+ function tmpSnippet(body: string) {
28
+ const dir = mkdtempSync(join(tmpdir(), "hs-snippet-"));
29
+ const file = join(dir, "hogsend.js");
30
+ writeFileSync(file, body);
31
+ return file;
32
+ }
33
+
34
+ test("serves the snippet with cache + cross-origin headers", async () => {
35
+ const app = appWith(tmpSnippet("console.log('hi')"));
36
+ const res = await app.request("/hogsend.js");
37
+ assert.equal(res.status, 200);
38
+ assert.equal(await res.text(), "console.log('hi')");
39
+ assert.equal(
40
+ res.headers.get("content-type"),
41
+ "application/javascript; charset=utf-8",
42
+ );
43
+ assert.equal(res.headers.get("cache-control"), SNIPPET_CACHE_CONTROL);
44
+ assert.equal(res.headers.get("cross-origin-resource-policy"), "cross-origin");
45
+ assert.match(res.headers.get("etag") ?? "", /^"[a-f0-9]{32}"$/);
46
+ });
47
+
48
+ test("revalidates to 304 on a matching If-None-Match", async () => {
49
+ const app = appWith(tmpSnippet("x"));
50
+ const first = await app.request("/hogsend.js");
51
+ const etag = first.headers.get("etag") ?? "";
52
+ const res = await app.request("/hogsend.js", {
53
+ headers: { "if-none-match": etag },
54
+ });
55
+ assert.equal(res.status, 304);
56
+ assert.equal(await res.text(), "");
57
+ assert.equal(res.headers.get("etag"), etag);
58
+ });
59
+
60
+ test("etag tracks content", () => {
61
+ const a = loadSnippet(tmpSnippet("a"));
62
+ const b = loadSnippet(tmpSnippet("b"));
63
+ assert.notEqual(a?.etag, b?.etag);
64
+ });
65
+
66
+ test("404s when no asset is installed", async () => {
67
+ const app = appWith(null);
68
+ const res = await app.request("/hogsend.js");
69
+ assert.equal(res.status, 404);
70
+ });
@@ -0,0 +1,58 @@
1
+ import { createRoute, OpenAPIHono } from "@hono/zod-openapi";
2
+ import type { AppEnv } from "../app.js";
3
+ import { type LoadedSnippet, loadSnippet } from "../lib/snippet.js";
4
+
5
+ // The drop-in browser snippet, root-mounted as `/hogsend.js` so the tag a
6
+ // non-bundler site pastes is just `${API_PUBLIC_URL}/hogsend.js`. Public and
7
+ // unauthenticated by construction (it is the SDK itself; the publishable key
8
+ // travels on the tag, not the request). Collides with nothing (`/v1`, `/l`,
9
+ // `/s`, `/studio`, `/docs`, `/api/auth`, `/connectors`, webhooks).
10
+ export const SNIPPET_PATH = "/hogsend.js";
11
+
12
+ const snippetRoute = createRoute({
13
+ method: "get",
14
+ path: SNIPPET_PATH,
15
+ tags: ["SDK"],
16
+ summary: "Drop-in browser SDK script",
17
+ responses: {
18
+ 200: { description: "The @hogsend/js IIFE bundle" },
19
+ 304: { description: "Not modified" },
20
+ 404: { description: "Snippet asset not installed" },
21
+ },
22
+ });
23
+
24
+ /**
25
+ * Cache policy: five minutes fresh, a day stale-while-revalidate, strong ETag.
26
+ * A deploy with a newer `@hogsend/js` is picked up within minutes by every
27
+ * page without a cache-busting URL, and a revalidation is a 304 with no body.
28
+ */
29
+ export const SNIPPET_CACHE_CONTROL =
30
+ "public, max-age=300, stale-while-revalidate=86400";
31
+
32
+ export function createSnippetRouter(
33
+ snippet: LoadedSnippet | null = loadSnippet(),
34
+ ): OpenAPIHono<AppEnv> {
35
+ return new OpenAPIHono<AppEnv>().openapi(snippetRoute, (c) => {
36
+ if (!snippet) {
37
+ return c.json(
38
+ {
39
+ error:
40
+ "hogsend.js is not installed on this engine. Add @hogsend/js as a dependency (or set HOGSEND_JS_PATH).",
41
+ },
42
+ 404,
43
+ );
44
+ }
45
+ // Explicit CORP so a cross-origin <script src> load is allowed (app.ts
46
+ // exempts this path from secureHeaders, which would force same-origin).
47
+ c.header("Cross-Origin-Resource-Policy", "cross-origin");
48
+ c.header("Cache-Control", SNIPPET_CACHE_CONTROL);
49
+ c.header("ETag", snippet.etag);
50
+ c.header("Vary", "Accept-Encoding");
51
+
52
+ if (c.req.header("if-none-match") === snippet.etag) {
53
+ return c.body(null, 304);
54
+ }
55
+ c.header("Content-Type", "application/javascript; charset=utf-8");
56
+ return c.body(snippet.body, 200);
57
+ });
58
+ }
@@ -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,
@@ -140,6 +140,12 @@ export const importContactsTask = hatchet.task({
140
140
  allowMerge: "any",
141
141
  trustedKinds: ["external", "email"],
142
142
  },
143
+ // A backfill is a statement about the PAST. If a row merges into a
144
+ // contact whose loser held a live linked account, the fold emits an
145
+ // `account.unlinked` — do NOT enrol journeys on it once per row
146
+ // (the outbound webhook still fires). Mirrors the
147
+ // `/v1/accounts/import` route's own `enrollJourneys` default-off.
148
+ enrollJourneys: false,
143
149
  }).then(async (result) => {
144
150
  await attachPhone(db, result.id, row.phone);
145
151
  return { index: i + idx, ok: true };