@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,126 @@
1
+ import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
2
+ import type { Database } from "@hogsend/db";
3
+ import {
4
+ type AccountUnlinkedFacts,
5
+ buildAccountUnlinkedPayload,
6
+ buildDedupeKey,
7
+ } from "./account-link-events.js";
8
+ import { createLogger, type Logger } from "./logger.js";
9
+
10
+ // The engine singletons, the `lib/preferences.ts` idiom: the `lib/contacts.ts`
11
+ // emit sites are reached from library code (the merge, the delete leg) that has
12
+ // no request container to read a `hatchet`/`logger` off. A caller that DOES
13
+ // have one passes it (see {@link EmitHandles}).
14
+ const logger = createLogger(process.env.LOG_LEVEL);
15
+
16
+ /**
17
+ * The container's handles, when the caller has a container.
18
+ *
19
+ * `logger` attributes the emit to the caller's request. `hatchet` buys exactly
20
+ * one thing — it spares this module the `./hatchet.js` dynamic import below,
21
+ * which is what runs `HatchetClient.init` — plus satisfying `emitOutbound`'s
22
+ * signature. It does NOT redirect delivery, and claiming otherwise would be
23
+ * false: `emitOutbound` destructures
24
+ * `const { db, logger, event, payload, dedupeKey } = opts`
25
+ * (`outbound.ts:619`) and never reads `opts.hatchet`, and the enqueue runs
26
+ * through the MODULE-LEVEL `deliverWebhookTask` built from the singleton at
27
+ * import time, so `opts.overrides.hatchet` cannot reroute it. Both fields are
28
+ * optional so the container-free `lib/contacts.ts` call sites stay a two-arg
29
+ * call.
30
+ */
31
+ export type EmitHandles = {
32
+ hatchet?: HatchetClient;
33
+ logger?: Logger;
34
+ };
35
+
36
+ /**
37
+ * Fan out one `account.unlinked` per mutation fact (PRD 08 T3).
38
+ *
39
+ * This exists so the emit SHAPE lives once: `MergedLinkUnlink` (the merge's
40
+ * singleton-collision soft-unlink, `reason: "relinked"`) and
41
+ * `ContactUnlinkFact` (the contact-deletion leg, `reason: "api"`) both satisfy
42
+ * {@link AccountUnlinkedFacts} structurally, so both legs share this loop and
43
+ * cannot drift apart on the payload or the dedupe key.
44
+ *
45
+ * ## Call it AFTER the mutation's transaction has RESOLVED, never inside it
46
+ *
47
+ * DECISIONS §8 puts emission at the commit/intent layer. Both callers hand us
48
+ * facts a `db.transaction(...)` already returned: a rolled-back merge or
49
+ * delete must never have announced an unlink that did not happen, and a
50
+ * subscriber that reacts by re-reading the pull plane inside the write's own
51
+ * transaction window would read pre-commit state.
52
+ *
53
+ * ## Fire-and-forget, and it stays that way
54
+ *
55
+ * `emitOutbound` never throws (`outbound.ts:600-608`); the `void … .catch` is
56
+ * the defence-in-depth its own docstring asks every call site for. A webhook
57
+ * problem must never fail a contact merge or a GDPR deletion, so this function
58
+ * returns `void` rather than a promise — there is deliberately nothing for a
59
+ * caller to await and therefore nothing for a caller to accidentally fail on.
60
+ *
61
+ * `version` is threaded through as the decimal STRING the store produced and
62
+ * is never parsed (DECISIONS §5.1). `userId`/`email` come off `fact.owner`,
63
+ * read inside the mutation's transaction, and are never looked up here.
64
+ *
65
+ * ## The spine is reached by DYNAMIC import, on purpose
66
+ *
67
+ * `lib/contacts.ts` imports this module, and `src/testing.ts` re-exports
68
+ * `softDeleteContact` from `lib/contacts.ts`. A STATIC `./hatchet.js` or
69
+ * `./outbound.js` import here (outbound → `workflows/deliver-webhook.js` →
70
+ * `lib/hatchet.js`) would therefore run `HatchetClient.init(...)` the moment
71
+ * anything touched the `@hogsend/engine/testing` barrel, which is documented
72
+ * side-effect-free and is consumed where no real Hatchet token exists — it
73
+ * throws `Invalid token format` before a single test runs. Resolving both
74
+ * inside the fire-and-forget body keeps that barrel clean; the ESM module
75
+ * cache makes every call after the first free, and the emit is already
76
+ * asynchronous so nothing about the timing or the post-commit ordering
77
+ * changes. `account-links-emit.test.ts` pins the absence of the static form —
78
+ * every gate stays green without it, so only that guard catches a regression.
79
+ */
80
+ export function emitAccountUnlinked(
81
+ db: Database,
82
+ facts: readonly AccountUnlinkedFacts[],
83
+ handles: EmitHandles = {},
84
+ ): void {
85
+ const log = handles.logger ?? logger;
86
+ for (const fact of facts) {
87
+ void emitOne(db, fact, handles.hatchet, log).catch((error: unknown) => {
88
+ // ATTRIBUTED, and `error` not `warn`. `emitOutbound` logs its own
89
+ // failures with structure, so the only thing that reaches here is a
90
+ // failure of the dynamic `import(...)` above — and Node's ESM loader
91
+ // CACHES a module evaluation error and re-throws it on every later
92
+ // import, so one `HatchetClient.init` throw disables `account.unlinked`
93
+ // for the life of the process. A bare `logger.warn(err)` made that a
94
+ // repeated context-free `Invalid token format`; an operator needs to
95
+ // know WHICH identity fact was dropped. Never rethrows: the
96
+ // fire-and-forget contract holds.
97
+ log.error("account.unlinked emit failed", {
98
+ event: "account.unlinked",
99
+ provider: fact.provider,
100
+ providerUserId: fact.providerUserId,
101
+ version: fact.version,
102
+ error: error instanceof Error ? error.message : String(error),
103
+ });
104
+ });
105
+ }
106
+ }
107
+
108
+ async function emitOne(
109
+ db: Database,
110
+ fact: AccountUnlinkedFacts,
111
+ hatchetHandle: HatchetClient | undefined,
112
+ log: Logger,
113
+ ): Promise<void> {
114
+ const { emitOutbound } = await import("./outbound.js");
115
+ // Only reach for the singleton when the caller had none to give: importing
116
+ // `./hatchet.js` is what runs `HatchetClient.init`.
117
+ const hatchet = hatchetHandle ?? (await import("./hatchet.js")).hatchet;
118
+ await emitOutbound({
119
+ db,
120
+ hatchet,
121
+ logger: log,
122
+ event: "account.unlinked",
123
+ payload: buildAccountUnlinkedPayload(fact),
124
+ dedupeKey: buildDedupeKey(fact.provider, fact.providerUserId, fact.version),
125
+ });
126
+ }
@@ -0,0 +1,180 @@
1
+ import type { LinkAccountResult, LinkOwner } from "./account-links.js";
2
+ import type { OutboundPayloads } from "./outbound.js";
3
+
4
+ /**
5
+ * The ONE place an `account.*` outbound payload or dedupe key is constructed
6
+ * (PRD 08 T3).
7
+ *
8
+ * Six emit sites across four PRDs build these — the hosted callback (linked +
9
+ * four link_failed reasons), the data-plane import, two data-plane revokes,
10
+ * the manage page, the merge's singleton-collision unlink and the
11
+ * contact-deletion leg. Hand-rolling the shape at each of them is how the
12
+ * `email` field ends up carrying the PROVIDER-reported address at one site and
13
+ * the contact's at another, or how one site emits `v3` while another emits
14
+ * `v3.0`. Everything here is a pure function of the facts a mutation already
15
+ * returned.
16
+ *
17
+ * This module has NO runtime imports on purpose (both imports above are
18
+ * `import type`, fully erased). `outbound.ts` reaches the delivery task, which
19
+ * reaches `env.ts`, which validates at IMPORT time — a payload builder must
20
+ * never drag that into a caller that has no env.
21
+ *
22
+ * ## Replay safety — there is none to reach for, and that is deliberate
23
+ *
24
+ * Linking happens in ROUTE-HANDLER runtime (the hosted callback, the data
25
+ * plane), never inside a Hatchet durable task. So nothing here enters the
26
+ * Hatchet journal, the positional-journal law that governs `ctx.sleep` /
27
+ * `ctx.waitForEvent` / the digest+throttle primitives does not apply, and the
28
+ * tracked mailer's exactly-once machinery (auto-keying off the replay-stable
29
+ * Hatchet run id) is NOT involved and must not be reached for.
30
+ *
31
+ * Idempotency here is DB-level, in three layers: the pair advisory lock plus
32
+ * the `(provider, provider_user_id, version)` unique constraint (DECISIONS
33
+ * §5.6) on the write side, and the `(endpointId, dedupeKey)` partial-unique
34
+ * index on the outbound side — which is what {@link buildDedupeKey} feeds. A
35
+ * journey that REACTS to `account.linked` is an ordinary event-triggered
36
+ * journey and obeys every existing replay law unchanged.
37
+ */
38
+
39
+ /**
40
+ * `al:<provider>:<providerUserId>:v<version>` — DECISIONS §5.5, riding the
41
+ * existing `(endpointId, dedupeKey)` partial-unique index on
42
+ * `webhook_deliveries`.
43
+ *
44
+ * A PURE TEMPLATE. Do NOT add URL-encoding, escaping or normalization: the key
45
+ * only has to be stable and unique per mutation, and the instant its spelling
46
+ * changes, a re-emit of a version minted before the change no longer collides
47
+ * with the row written after it — the dedupe silently stops deduping, which no
48
+ * delivery assertion can see.
49
+ *
50
+ * `version` is a decimal STRING in and a STRING out, never parsed
51
+ * (DECISIONS §5.1: the column is a Postgres `bigint`, so `Number()` loses
52
+ * fidelity past `Number.MAX_SAFE_INTEGER` and breaks the consumer's
53
+ * `incoming.version > stored.version` guard in exactly the case it exists for).
54
+ */
55
+ export function buildDedupeKey(
56
+ provider: string,
57
+ providerUserId: string,
58
+ version: string,
59
+ ): string {
60
+ return `al:${provider}:${providerUserId}:v${version}`;
61
+ }
62
+
63
+ /** The two {@link LinkAccountResult} arms that actually bound something. */
64
+ type LinkedFacts = Extract<
65
+ LinkAccountResult,
66
+ { status: "linked" } | { status: "relinked" }
67
+ >;
68
+
69
+ /**
70
+ * FULL CURRENT STATE for a successful bind (DECISIONS §5.2), built from the
71
+ * facts `linkAccount()` returned and nothing else.
72
+ *
73
+ * `userId` and `email` come off `facts.owner` — the join to `contacts` the
74
+ * store performed INSIDE its advisory-locked transaction (DECISIONS §15.5).
75
+ * Neither field exists on `linked_accounts`, and re-reading them here would be
76
+ * a read after the lock released: no longer the state that was committed.
77
+ * `userId` is `contactKey()` (`external_id ?? anonymous_id ?? id`), the ONE
78
+ * definition shared by the PULL, PUSH and IN-PROCESS planes — never the raw
79
+ * `externalId`.
80
+ *
81
+ * `email` is the CONTACT's address. `row.verifiedEmail` (the
82
+ * provider-reported one) is deliberately never read here: it is a display
83
+ * property at most, and putting it in a field named `email` beside `contactId`
84
+ * is precisely how a downstream system ends up resolving identity on it.
85
+ */
86
+ export function buildAccountLinkedPayload(
87
+ facts: LinkedFacts,
88
+ at: Date = new Date(),
89
+ ): OutboundPayloads["account.linked"] {
90
+ return {
91
+ state: "linked",
92
+ provider: facts.row.provider,
93
+ providerUserId: facts.row.providerUserId,
94
+ contactId: facts.owner.contactId,
95
+ userId: facts.owner.userId,
96
+ email: facts.owner.email,
97
+ username: facts.row.username,
98
+ method: facts.row.method,
99
+ relink: facts.relink,
100
+ version: facts.version,
101
+ at: at.toISOString(),
102
+ };
103
+ }
104
+
105
+ /**
106
+ * The facts every unlink site already has in hand.
107
+ *
108
+ * The merge fold's `MergedLinkUnlink` and the delete leg's `ContactUnlinkFact`
109
+ * satisfy this structurally, so `lib/account-link-emit.ts` fans both out
110
+ * without reshaping either. `UnlinkAccountResult` does NOT: its `unlinked` arm
111
+ * carries `provider`/`providerUserId` on `.row`, not at the top level, so a
112
+ * revoke site (PRD 09, PRD 11) passes those two up from `res.row` alongside
113
+ * `res.version`, `res.owner` and its own `reason`.
114
+ */
115
+ export interface AccountUnlinkedFacts {
116
+ provider: string;
117
+ providerUserId: string;
118
+ /** That pair's OWN next version, a decimal STRING (DECISIONS §5.1). */
119
+ version: string;
120
+ reason: "player" | "api" | "relinked";
121
+ /** Read inside the mutation's transaction — see {@link LinkOwner}. */
122
+ owner: LinkOwner;
123
+ }
124
+
125
+ /**
126
+ * FULL CURRENT STATE for a release (DECISIONS §5.2). Shares the
127
+ * `(provider, providerUserId)` version sequence with `account.linked`, so a
128
+ * consumer's single monotonic guard makes reorder, duplicate and late delivery
129
+ * all no-ops.
130
+ *
131
+ * `contactId`/`userId`/`email` are read off `owner` and nowhere else, for the
132
+ * same reason as {@link buildAccountLinkedPayload}.
133
+ */
134
+ export function buildAccountUnlinkedPayload(
135
+ facts: AccountUnlinkedFacts,
136
+ at: Date = new Date(),
137
+ ): OutboundPayloads["account.unlinked"] {
138
+ return {
139
+ state: "unlinked",
140
+ provider: facts.provider,
141
+ providerUserId: facts.providerUserId,
142
+ contactId: facts.owner.contactId,
143
+ userId: facts.owner.userId,
144
+ email: facts.owner.email,
145
+ reason: facts.reason,
146
+ version: facts.version,
147
+ at: at.toISOString(),
148
+ };
149
+ }
150
+
151
+ /**
152
+ * A link flow ended without binding anything.
153
+ *
154
+ * Carries NO `version` and NO `state`: nothing mutated, so there is nothing
155
+ * for the consumer's `incoming.version > stored.version` guard to compare and
156
+ * no current state to report. It gets NO dedupeKey either (the caller passes
157
+ * none) — two genuine failures in a row are two genuine facts, and suppressing
158
+ * the second would hide a brute-force pattern.
159
+ *
160
+ * `reason` is `AccountLinkCallbackError.reason` verbatim; PRD 01 froze that
161
+ * union as the `account.link_failed` union minus `"vetoed"` (which only the
162
+ * hook path produces), so there is no translation table. `contactId` is null
163
+ * whenever the flow failed before a trustworthy contact was in hand, and this
164
+ * event NEVER mints one (DECISIONS §8).
165
+ */
166
+ export function buildLinkFailedPayload(
167
+ args: {
168
+ provider: string;
169
+ reason: "denied" | "vetoed" | "exchange_failed" | "state_invalid";
170
+ contactId: string | null;
171
+ },
172
+ at: Date = new Date(),
173
+ ): OutboundPayloads["account.link_failed"] {
174
+ return {
175
+ provider: args.provider,
176
+ reason: args.reason,
177
+ contactId: args.contactId,
178
+ at: at.toISOString(),
179
+ };
180
+ }
@@ -0,0 +1,158 @@
1
+ import assert from "node:assert/strict";
2
+ import test, { mock } from "node:test";
3
+ import type { AccountLinkHooks, BeforeLinkContext } from "@hogsend/core";
4
+ import { ACCOUNT_LINK_HOOK_TIMEOUT_MS } from "@hogsend/core";
5
+ import { runBeforeLink } from "./account-link-hooks.js";
6
+
7
+ /**
8
+ * PRD 07 T7. `beforeLink` is the ONE fail-closed hook in the feature: a throw,
9
+ * a timeout and an explicit `{ allow: false }` all collapse to the same veto.
10
+ * DECISIONS §6.7 — a veto hook that fails open is not a veto hook.
11
+ */
12
+
13
+ const WARM_CTX: BeforeLinkContext = {
14
+ provider: "steam",
15
+ identity: { providerUserId: "76561197960435530", username: "player" },
16
+ contactId: "11111111-2222-3333-4444-555555555555",
17
+ userId: "player-1",
18
+ email: "player@example.com",
19
+ };
20
+
21
+ const logger = {
22
+ info() {},
23
+ warn() {},
24
+ error() {},
25
+ debug() {},
26
+ } as unknown as Parameters<typeof runBeforeLink>[0]["logger"];
27
+
28
+ const run = (hooks: AccountLinkHooks, ctx: BeforeLinkContext = WARM_CTX) =>
29
+ runBeforeLink({ hooks, ctx, logger });
30
+
31
+ test("an absent beforeLink allows", async () => {
32
+ assert.deepEqual(await run({}), { allow: true });
33
+ });
34
+
35
+ test("a beforeLink returning void allows", async () => {
36
+ // A side-effect-only hook must not have to remember to return.
37
+ assert.deepEqual(
38
+ await run({
39
+ beforeLink() {
40
+ /* observes only */
41
+ },
42
+ }),
43
+ { allow: true },
44
+ );
45
+ });
46
+
47
+ test("an { allow: true } beforeLink allows", async () => {
48
+ assert.deepEqual(
49
+ await run({
50
+ async beforeLink() {
51
+ return { allow: true };
52
+ },
53
+ }),
54
+ {
55
+ allow: true,
56
+ },
57
+ );
58
+ });
59
+
60
+ test("an { allow: false } beforeLink vetoes", async () => {
61
+ assert.deepEqual(
62
+ await run({
63
+ async beforeLink() {
64
+ return { allow: false, reason: "player is banned" };
65
+ },
66
+ }),
67
+ { allow: false, reason: "vetoed" },
68
+ );
69
+ });
70
+
71
+ test("a throwing beforeLink vetoes", async () => {
72
+ assert.deepEqual(
73
+ await run({
74
+ async beforeLink() {
75
+ throw new Error("consumer DB is down");
76
+ },
77
+ }),
78
+ { allow: false, reason: "vetoed" },
79
+ );
80
+ });
81
+
82
+ test("a synchronous (non-promise) beforeLink is honoured", async () => {
83
+ assert.deepEqual(
84
+ await run({
85
+ beforeLink() {
86
+ return { allow: false };
87
+ },
88
+ }),
89
+ { allow: false, reason: "vetoed" },
90
+ );
91
+ assert.deepEqual(
92
+ await run({
93
+ beforeLink() {
94
+ return { allow: true };
95
+ },
96
+ }),
97
+ { allow: true },
98
+ );
99
+ });
100
+
101
+ test("a synchronously THROWING beforeLink vetoes", async () => {
102
+ // A sync throw escapes before any promise exists, so it must be caught
103
+ // around the CALL, not just on the returned promise.
104
+ assert.deepEqual(
105
+ await run({
106
+ beforeLink() {
107
+ throw new Error("sync boom");
108
+ },
109
+ }),
110
+ { allow: false, reason: "vetoed" },
111
+ );
112
+ });
113
+
114
+ test("a beforeLink that never resolves vetoes at 5s", async () => {
115
+ mock.timers.enable({ apis: ["setTimeout"] });
116
+ try {
117
+ const pending = run({
118
+ beforeLink() {
119
+ return new Promise<never>(() => {
120
+ /* never settles */
121
+ });
122
+ },
123
+ });
124
+ mock.timers.tick(ACCOUNT_LINK_HOOK_TIMEOUT_MS);
125
+ assert.deepEqual(await pending, { allow: false, reason: "vetoed" });
126
+ } finally {
127
+ mock.timers.reset();
128
+ }
129
+ });
130
+
131
+ test("the hook sees the cold context verbatim: contactId null, anonymousId set", async () => {
132
+ const seen: BeforeLinkContext[] = [];
133
+ const coldCtx: BeforeLinkContext = {
134
+ provider: "steam",
135
+ identity: { providerUserId: "76561197960435530" },
136
+ contactId: null,
137
+ anonymousId: "anon-xyz",
138
+ userId: null,
139
+ email: null,
140
+ };
141
+ await run(
142
+ {
143
+ beforeLink(ctx) {
144
+ seen.push(ctx);
145
+ },
146
+ },
147
+ coldCtx,
148
+ );
149
+ assert.equal(seen.length, 1);
150
+ assert.deepEqual(seen[0], coldCtx);
151
+ });
152
+
153
+ test("this module exports runBeforeLink and nothing after-shaped", async () => {
154
+ // DECISIONS §15.4: the store is the SOLE invoker of afterLink/afterUnlink. A
155
+ // second bounded runner living here is exactly how they end up firing twice.
156
+ const module = await import("./account-link-hooks.js");
157
+ assert.deepEqual(Object.keys(module), ["runBeforeLink"]);
158
+ });
@@ -0,0 +1,73 @@
1
+ import type { AccountLinkHooks, BeforeLinkContext } from "@hogsend/core";
2
+ import { ACCOUNT_LINK_HOOK_TIMEOUT_MS } from "@hogsend/core";
3
+ import type { Logger } from "./logger.js";
4
+
5
+ /**
6
+ * The `beforeLink` veto runner — FAIL-CLOSED (DECISIONS §6.7).
7
+ *
8
+ * A throw, a timeout at {@link ACCOUNT_LINK_HOOK_TIMEOUT_MS}, and an explicit
9
+ * `{ allow: false }` all collapse to one outcome: `{ allow: false, reason:
10
+ * "vetoed" }`. A `void`/`undefined` return ALLOWS, per PRD 01's
11
+ * `BeforeLinkResult` — denial is never implicit, so a hook that only observes
12
+ * cannot accidentally veto every link. There is no third outcome and no config
13
+ * flag that turns the veto into a warning.
14
+ *
15
+ * **`runBeforeLink` is the ONLY export of this file, deliberately.**
16
+ * `afterLink` / `afterUnlink` have exactly one invoker — the link store,
17
+ * post-commit (DECISIONS §15.4) — and a second bounded runner living here is
18
+ * precisely how they end up firing twice for every link, invisibly, because
19
+ * they are documented at-least-once and nothing would fail loudly. The veto is
20
+ * genuinely route-owned because it is pre-write and the hosted callback is the
21
+ * only pre-write position. If a bounded fail-OPEN runner is ever wanted
22
+ * elsewhere, it lives in `lib/account-links.ts` beside the commit it follows.
23
+ */
24
+ export async function runBeforeLink(args: {
25
+ hooks: AccountLinkHooks;
26
+ ctx: BeforeLinkContext;
27
+ logger?: Logger;
28
+ }): Promise<{ allow: true } | { allow: false; reason: "vetoed" }> {
29
+ const hook = args.hooks.beforeLink;
30
+ if (!hook) return { allow: true };
31
+
32
+ let timer: NodeJS.Timeout | undefined;
33
+ try {
34
+ const verdict = await Promise.race([
35
+ // `Promise.resolve(...)` inside the try so a SYNCHRONOUS throw — which
36
+ // escapes before any promise exists — is caught by the same handler.
37
+ Promise.resolve(hook(args.ctx)),
38
+ new Promise<never>((_, reject) => {
39
+ timer = setTimeout(
40
+ () =>
41
+ reject(
42
+ new Error(
43
+ `beforeLink exceeded ${ACCOUNT_LINK_HOOK_TIMEOUT_MS}ms`,
44
+ ),
45
+ ),
46
+ ACCOUNT_LINK_HOOK_TIMEOUT_MS,
47
+ );
48
+ }),
49
+ ]);
50
+ if (verdict && verdict.allow === false) {
51
+ args.logger?.warn("accountLink beforeLink vetoed the link", {
52
+ provider: args.ctx.provider,
53
+ contactId: args.ctx.contactId,
54
+ // Operator-facing by contract; a hook must not put a secret here.
55
+ reason: verdict.reason,
56
+ });
57
+ return { allow: false, reason: "vetoed" };
58
+ }
59
+ return { allow: true };
60
+ } catch (err) {
61
+ // A throw and a timeout are the SAME outcome. Fail-closed lives on the
62
+ // failure channel, so neither an exception nor a hung customer service can
63
+ // wave a link through.
64
+ args.logger?.warn("accountLink beforeLink failed — link refused", {
65
+ provider: args.ctx.provider,
66
+ contactId: args.ctx.contactId,
67
+ error: err instanceof Error ? err.message : String(err),
68
+ });
69
+ return { allow: false, reason: "vetoed" };
70
+ } finally {
71
+ if (timer) clearTimeout(timer);
72
+ }
73
+ }