@hogsend/engine 0.63.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.
- package/package.json +13 -12
- package/src/account-links/__fixtures__/fake-fetch.test.ts +57 -0
- package/src/account-links/__fixtures__/fake-fetch.ts +114 -0
- package/src/account-links/__fixtures__/steam.json +21 -0
- package/src/account-links/__fixtures__/twitch.json +22 -0
- package/src/account-links/index.ts +8 -0
- package/src/account-links/steam.test.ts +243 -0
- package/src/account-links/steam.ts +48 -0
- package/src/account-links/twitch.test.ts +157 -0
- package/src/account-links/twitch.ts +99 -0
- package/src/container.account-links.env.test.ts +65 -0
- package/src/container.account-links.halfenv.test.ts +48 -0
- package/src/container.account-links.test.ts +185 -0
- package/src/container.ts +120 -0
- package/src/env.ts +60 -0
- package/src/index.ts +104 -1
- package/src/journeys/journey-boundary.ts +8 -0
- package/src/lib/account-link-emit.ts +126 -0
- package/src/lib/account-link-events.ts +180 -0
- package/src/lib/account-link-hooks.test.ts +158 -0
- package/src/lib/account-link-hooks.ts +73 -0
- package/src/lib/account-link-ingest.ts +364 -0
- package/src/lib/account-link-nonce.test.ts +52 -0
- package/src/lib/account-link-nonce.ts +57 -0
- package/src/lib/account-link-origins.test.ts +72 -0
- package/src/lib/account-link-origins.ts +87 -0
- package/src/lib/account-link-pkce.test.ts +91 -0
- package/src/lib/account-link-pkce.ts +106 -0
- package/src/lib/account-link-provider-registry.test.ts +52 -0
- package/src/lib/account-link-provider-registry.ts +61 -0
- package/src/lib/account-link-throttle.test.ts +178 -0
- package/src/lib/account-link-throttle.ts +130 -0
- package/src/lib/account-link-url.ts +85 -0
- package/src/lib/account-links-emit.test.ts +525 -0
- package/src/lib/account-links-env.test.ts +40 -0
- package/src/lib/account-links-from-env.test.ts +187 -0
- package/src/lib/account-links-from-env.ts +126 -0
- package/src/lib/account-links.ts +1300 -0
- package/src/lib/app-secret.ts +34 -0
- package/src/lib/attachments.ts +81 -0
- package/src/lib/connector-actions.test.ts +13 -4
- package/src/lib/connector-state.account-link.test.ts +114 -0
- package/src/lib/connector-state.ts +48 -3
- package/src/lib/contacts.ts +320 -6
- package/src/lib/domain-status.return-path.test.ts +68 -0
- package/src/lib/domain-status.ts +19 -0
- package/src/lib/email-provider-boot.hogsend.test.ts +48 -0
- package/src/lib/email-provider-boot.test.ts +33 -0
- package/src/lib/email-providers-from-env.hogsend.test.ts +110 -0
- package/src/lib/email-providers-from-env.test.ts +52 -0
- package/src/lib/email-providers-from-env.ts +67 -0
- package/src/lib/email-service-types.ts +11 -0
- package/src/lib/email.ts +17 -0
- package/src/lib/mailer-bounce-idempotency.test.ts +469 -0
- package/src/lib/mailer-rejected.test.ts +229 -0
- package/src/lib/mailer-replied.test.ts +379 -0
- package/src/lib/mailer.ts +359 -24
- package/src/lib/outbound-account-payloads.test.ts +137 -0
- package/src/lib/outbound.ts +126 -0
- package/src/lib/provider-credentials.ts +19 -5
- package/src/lib/sending-domain-guidance.test.ts +99 -0
- package/src/lib/sending-domain-guidance.ts +84 -0
- package/src/lib/tracked-attachments.test.ts +376 -0
- package/src/lib/tracked-idempotency-header.test.ts +437 -0
- package/src/lib/tracked.ts +116 -4
- package/src/lib/tracking-event-names.ts +9 -0
- package/src/lib/webhook-catalog-sync.test.ts +24 -0
- package/src/lib/webhook-signing.ts +25 -1
- package/src/routes/accounts/callback.ts +597 -0
- package/src/routes/accounts/emit.ts +231 -0
- package/src/routes/accounts/import-links.ts +210 -0
- package/src/routes/accounts/index.ts +75 -0
- package/src/routes/accounts/lookup.ts +177 -0
- package/src/routes/accounts/me.ts +215 -0
- package/src/routes/accounts/mint.ts +279 -0
- package/src/routes/accounts/pages.ts +62 -0
- package/src/routes/accounts/resolve.ts +61 -0
- package/src/routes/accounts/serialize.ts +96 -0
- package/src/routes/accounts/shared.ts +107 -0
- package/src/routes/accounts/start.ts +229 -0
- package/src/routes/accounts/unlink.ts +98 -0
- package/src/routes/admin/agent.ts +2 -0
- package/src/routes/admin/api-keys.ts +7 -0
- package/src/routes/admin/contacts.ts +38 -2
- package/src/routes/admin/domain-conflict.test.ts +188 -0
- package/src/routes/admin/domain-return-path.test.ts +274 -0
- package/src/routes/admin/domain.ts +214 -1
- package/src/routes/connectors/index.ts +17 -0
- package/src/routes/contacts/index.ts +8 -0
- package/src/routes/index.ts +75 -0
- package/src/testing-barrel.test.ts +74 -0
- package/src/testing.ts +17 -0
|
@@ -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
|
+
}
|