@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.
- package/package.json +12 -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 +37 -0
- package/src/index.ts +87 -1
- 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/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/outbound-account-payloads.test.ts +137 -0
- package/src/lib/outbound.ts +91 -0
- package/src/lib/provider-credentials.ts +19 -5
- package/src/lib/webhook-catalog-sync.test.ts +24 -0
- package/src/lib/webhook-signing.ts +18 -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/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,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
|
+
}
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
|
|
2
|
+
import type { AnalyticsProvider } from "@hogsend/core";
|
|
3
|
+
import type { JourneyRegistry } from "@hogsend/core/registry";
|
|
4
|
+
import type { Database } from "@hogsend/db";
|
|
5
|
+
import { getJourneyRegistrySingleton } from "../journeys/registry-singleton.js";
|
|
6
|
+
import type { AccountUnlinkedFacts } from "./account-link-events.js";
|
|
7
|
+
import { buildDedupeKey } from "./account-link-events.js";
|
|
8
|
+
import type { LinkAccountResult } from "./account-links.js";
|
|
9
|
+
import { getAnalytics } from "./analytics-singleton.js";
|
|
10
|
+
import { createLogger, type Logger } from "./logger.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* THE JOURNEY PLANE for account links (PRD 08 T5).
|
|
14
|
+
*
|
|
15
|
+
* ## TWO PLANES. NEITHER MAY BE COLLAPSED INTO THE OTHER.
|
|
16
|
+
*
|
|
17
|
+
* Every call to a function here sits BESIDE a call to the outbound spine
|
|
18
|
+
* (`emitOutbound` / `emitAccountUnlinked` / `noteUnlinked`), and the two look
|
|
19
|
+
* redundant precisely because they carry the same fact. They are not:
|
|
20
|
+
*
|
|
21
|
+
* - the OUTBOUND plane (`lib/outbound.ts`) writes a `webhook_deliveries` row
|
|
22
|
+
* and ships full current state to the CUSTOMER'S subscriber. It is emitted
|
|
23
|
+
* from the intent layer ONLY (DECISIONS §8), and the ingest path never
|
|
24
|
+
* emits.
|
|
25
|
+
* - the JOURNEY plane (this file → `ingestEvent`) writes a `user_events` row
|
|
26
|
+
* and pushes to Hatchet so `defineJourney({ trigger: { event:
|
|
27
|
+
* "account.linked" } })` fires INSIDE Hogsend. It reaches no subscriber.
|
|
28
|
+
*
|
|
29
|
+
* Delete either one and the other silently keeps working, so nothing fails
|
|
30
|
+
* loudly: an outbound-only build leaves every account-link journey dead, and an
|
|
31
|
+
* ingest-only build leaves every customer mirror stale. **Do not "simplify" the
|
|
32
|
+
* pair into one call**, and do not make `ingestEvent` emit or `emitOutbound`
|
|
33
|
+
* ingest — the `group.*` precedent (`routes/groups/index.ts`) is that the
|
|
34
|
+
* intent layer emits and the ingest path does not, and that boundary is what
|
|
35
|
+
* keeps a re-ingest from fanning a second delivery out to every subscriber.
|
|
36
|
+
*
|
|
37
|
+
* ## SCALARS ONLY in `eventProperties` (DECISIONS §8)
|
|
38
|
+
*
|
|
39
|
+
* Journeys branch on `eventProperties`; `contactProperties` never reach the
|
|
40
|
+
* Hatchet payload, and `ingestEvent` itself FILTERS the push payload down to
|
|
41
|
+
* `string | number | boolean | null` (`ingestion.ts` step 3). So a nested
|
|
42
|
+
* object or an array added here does not fail — it is silently dropped between
|
|
43
|
+
* `user_events` and the journey, and a `where` clause referencing it never
|
|
44
|
+
* matches. Same correction as `cold-connect/index.ts:45-49`. Every property
|
|
45
|
+
* built below is a literal scalar, and
|
|
46
|
+
* `apps/api/src/__tests__/accounts-journey-trigger.test.ts` iterates the stored
|
|
47
|
+
* row asserting `typeof`, so a future field of the wrong shape fails there.
|
|
48
|
+
*
|
|
49
|
+
* ## IDENTITY: the provenance pin, never the bare canonical key
|
|
50
|
+
*
|
|
51
|
+
* `owner.userId` is `contactKey()` (`external_id ?? anonymous_id ?? id`), so
|
|
52
|
+
* for a cold Steam link — the case this feature creates MOST of — it is an
|
|
53
|
+
* ANONYMOUS id. Passing that alone as `event.userId` would have `findByKey`
|
|
54
|
+
* read it as kind `external` and mint a row with `external_id = <anonId>`,
|
|
55
|
+
* which then trips `collidesWithIdentified` and locks the visitor out of their
|
|
56
|
+
* own feed: strictly worse than the ghost row it would avoid. So every state
|
|
57
|
+
* event also carries `contactId: owner.contactId`, the ENGINE-INTERNAL
|
|
58
|
+
* provenance pin, which resolves the exact row by uuid (and follows a merge
|
|
59
|
+
* alias to the survivor) and can never mint. The `userId` is still supplied
|
|
60
|
+
* because the resolver requires at least one value key, but the pin wins the
|
|
61
|
+
* branch (`contacts.ts` step −1).
|
|
62
|
+
*
|
|
63
|
+
* ## Replay safety — none to reach for, deliberately
|
|
64
|
+
*
|
|
65
|
+
* These calls run in ROUTE-HANDLER runtime (the hosted callback, the data
|
|
66
|
+
* plane) or in post-commit library code (the merge fold), never inside a
|
|
67
|
+
* Hatchet durable task, so nothing here enters any journey's replay journal.
|
|
68
|
+
* The idempotency is the `user_events.idempotency_key` unique index, fed the
|
|
69
|
+
* SAME `al:<provider>:<uid>:v<version>` string the outbound `dedupeKey` uses —
|
|
70
|
+
* so a retried callback routes at most one enrollment. A journey that REACTS
|
|
71
|
+
* to `account.linked` is an ordinary event-triggered journey and obeys every
|
|
72
|
+
* existing replay law unchanged.
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
// The engine singletons, the `lib/account-link-emit.ts` idiom: the
|
|
76
|
+
// `lib/contacts.ts` call site is reached from library code with no request
|
|
77
|
+
// container to read a registry/analytics/logger off. A caller that DOES have
|
|
78
|
+
// one passes it.
|
|
79
|
+
const fallbackLogger = createLogger(process.env.LOG_LEVEL);
|
|
80
|
+
|
|
81
|
+
/** The container's handles, when the caller has a container. */
|
|
82
|
+
export interface AccountLinkIngestHandles {
|
|
83
|
+
registry?: JourneyRegistry;
|
|
84
|
+
hatchet?: HatchetClient;
|
|
85
|
+
logger?: Logger;
|
|
86
|
+
analytics?: AnalyticsProvider;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The two {@link LinkAccountResult} arms that actually bound something. */
|
|
90
|
+
type LinkedFacts = Extract<
|
|
91
|
+
LinkAccountResult,
|
|
92
|
+
{ status: "linked" } | { status: "relinked" }
|
|
93
|
+
>;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The subject a failed link can be attributed to, or `null` for none.
|
|
97
|
+
*
|
|
98
|
+
* `contactId` is the SEALED, server-minted id from a state that verified —
|
|
99
|
+
* unforgeable. `anonymousId` is the COLD path's browser-supplied value, which
|
|
100
|
+
* is why that arm is both `collidesWithIdentified`-screened and refused
|
|
101
|
+
* creation below.
|
|
102
|
+
*/
|
|
103
|
+
export type LinkFailedSubject =
|
|
104
|
+
| { contactId: string; anonymousId?: undefined }
|
|
105
|
+
| { anonymousId: string; contactId?: undefined }
|
|
106
|
+
| null;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* `account.linked` onto the journey plane, beside the outbound emit.
|
|
110
|
+
*
|
|
111
|
+
* Fire-and-forget with an attributed catch, exactly like
|
|
112
|
+
* `emitAccountUnlinked`: a Hatchet hiccup or an uninitialized registry must
|
|
113
|
+
* never fail a link the player already completed. Returns `void` so there is
|
|
114
|
+
* deliberately nothing for a caller to await and therefore nothing for a
|
|
115
|
+
* caller to accidentally fail on.
|
|
116
|
+
*/
|
|
117
|
+
export function ingestAccountLinked(
|
|
118
|
+
db: Database,
|
|
119
|
+
facts: LinkedFacts,
|
|
120
|
+
handles: AccountLinkIngestHandles = {},
|
|
121
|
+
): void {
|
|
122
|
+
const { provider, providerUserId } = facts.row;
|
|
123
|
+
run(
|
|
124
|
+
db,
|
|
125
|
+
handles,
|
|
126
|
+
{
|
|
127
|
+
event: "account.linked",
|
|
128
|
+
// `LinkOwner.userId` is TYPED nullable, so fall back to the row uuid —
|
|
129
|
+
// which `findByKey` resolves to the same contact by id. The value key
|
|
130
|
+
// only has to exist (the resolver requires one); the pin below is what
|
|
131
|
+
// actually decides the row.
|
|
132
|
+
userId: facts.owner.userId ?? facts.owner.contactId,
|
|
133
|
+
contactId: facts.owner.contactId,
|
|
134
|
+
// The CONTACT's email, threaded so `JourneyUser.email` is populated:
|
|
135
|
+
// without it `ingestEvent` pushes `userEmail: ""` and the documented
|
|
136
|
+
// recipe — `sendEmail({ to: user.email })` in an `account.linked`
|
|
137
|
+
// journey — sends to an empty string. Every sibling re-ingest in the
|
|
138
|
+
// engine supplies it (contacts.ts merge fold, bucket-emit,
|
|
139
|
+
// tracking-events); this one did not.
|
|
140
|
+
...(facts.owner.email ? { userEmail: facts.owner.email } : {}),
|
|
141
|
+
eventProperties: {
|
|
142
|
+
state: "linked",
|
|
143
|
+
provider,
|
|
144
|
+
providerUserId,
|
|
145
|
+
username: facts.row.username,
|
|
146
|
+
method: facts.row.method,
|
|
147
|
+
relink: facts.relink,
|
|
148
|
+
version: facts.version,
|
|
149
|
+
},
|
|
150
|
+
source: "account_link",
|
|
151
|
+
idempotencyKey: buildDedupeKey(provider, providerUserId, facts.version),
|
|
152
|
+
},
|
|
153
|
+
{ provider, providerUserId, version: facts.version },
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* `account.unlinked` onto the journey plane, beside the outbound emit.
|
|
159
|
+
*
|
|
160
|
+
* Keyed on the facts' OWN pair — a `replacedSingleton` is a DIFFERENT pair
|
|
161
|
+
* with its own version sequence, and a key built from the arriving pair would
|
|
162
|
+
* collide with the `account.linked` idempotency key and silently drop this
|
|
163
|
+
* enrollment.
|
|
164
|
+
*/
|
|
165
|
+
export function ingestAccountUnlinked(
|
|
166
|
+
db: Database,
|
|
167
|
+
facts: AccountUnlinkedFacts,
|
|
168
|
+
handles: AccountLinkIngestHandles = {},
|
|
169
|
+
): void {
|
|
170
|
+
run(
|
|
171
|
+
db,
|
|
172
|
+
handles,
|
|
173
|
+
{
|
|
174
|
+
event: "account.unlinked",
|
|
175
|
+
// Nullable by type only — see {@link ingestAccountLinked}.
|
|
176
|
+
userId: facts.owner.userId ?? facts.owner.contactId,
|
|
177
|
+
contactId: facts.owner.contactId,
|
|
178
|
+
// See {@link ingestAccountLinked} — a journey reacting to an unlink
|
|
179
|
+
// needs a recipient too.
|
|
180
|
+
...(facts.owner.email ? { userEmail: facts.owner.email } : {}),
|
|
181
|
+
eventProperties: {
|
|
182
|
+
state: "unlinked",
|
|
183
|
+
provider: facts.provider,
|
|
184
|
+
providerUserId: facts.providerUserId,
|
|
185
|
+
reason: facts.reason,
|
|
186
|
+
version: facts.version,
|
|
187
|
+
},
|
|
188
|
+
source: "account_link",
|
|
189
|
+
idempotencyKey: buildDedupeKey(
|
|
190
|
+
facts.provider,
|
|
191
|
+
facts.providerUserId,
|
|
192
|
+
facts.version,
|
|
193
|
+
),
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
provider: facts.provider,
|
|
197
|
+
providerUserId: facts.providerUserId,
|
|
198
|
+
version: facts.version,
|
|
199
|
+
},
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* `account.link_failed` onto the journey plane, beside the outbound emit.
|
|
205
|
+
*
|
|
206
|
+
* NO `idempotencyKey`, mirroring the missing `dedupeKey`: the event carries no
|
|
207
|
+
* version, and two genuine failures in a row are two genuine facts.
|
|
208
|
+
*
|
|
209
|
+
* `allowCreate: false` is MANDATORY here (DECISIONS §8) and is what
|
|
210
|
+
* STRUCTURALLY enforces "a failed link never mints a contact" — rather than
|
|
211
|
+
* relying on the caller happening to pass no identity. On the cold arm the key
|
|
212
|
+
* is an `anonymous_id` typed into an unauthenticated URL, so a creating
|
|
213
|
+
* resolve would mint a CRM row for a link that never happened, on a value the
|
|
214
|
+
* visitor chose.
|
|
215
|
+
*
|
|
216
|
+
* A `null` subject is a no-op, not an error: a state that did not verify
|
|
217
|
+
* carries nothing to attribute a failure to, and `resolveContactNoCreate`
|
|
218
|
+
* would throw anyway (D8 — it needs `userId` or `anonymousId`).
|
|
219
|
+
*/
|
|
220
|
+
export function ingestAccountLinkFailed(
|
|
221
|
+
db: Database,
|
|
222
|
+
args: {
|
|
223
|
+
provider: string;
|
|
224
|
+
reason: "denied" | "vetoed" | "exchange_failed" | "state_invalid";
|
|
225
|
+
subject: LinkFailedSubject;
|
|
226
|
+
},
|
|
227
|
+
handles: AccountLinkIngestHandles = {},
|
|
228
|
+
): void {
|
|
229
|
+
const { subject } = args;
|
|
230
|
+
if (!subject) return;
|
|
231
|
+
const eventProperties = {
|
|
232
|
+
provider: args.provider,
|
|
233
|
+
reason: args.reason,
|
|
234
|
+
};
|
|
235
|
+
const context = { provider: args.provider, providerUserId: null };
|
|
236
|
+
if (subject.contactId !== undefined) {
|
|
237
|
+
run(
|
|
238
|
+
db,
|
|
239
|
+
handles,
|
|
240
|
+
{
|
|
241
|
+
event: "account.link_failed",
|
|
242
|
+
// The uuid doubles as the value key: `findByKey` resolves a
|
|
243
|
+
// uuid-shaped `external` key straight to that row. Supplied because
|
|
244
|
+
// the resolver requires at least one value key; the pin beside it wins
|
|
245
|
+
// the branch either way.
|
|
246
|
+
userId: subject.contactId,
|
|
247
|
+
contactId: subject.contactId,
|
|
248
|
+
eventProperties,
|
|
249
|
+
source: "account_link",
|
|
250
|
+
},
|
|
251
|
+
context,
|
|
252
|
+
{ allowCreate: false },
|
|
253
|
+
);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
run(
|
|
257
|
+
db,
|
|
258
|
+
handles,
|
|
259
|
+
{
|
|
260
|
+
event: "account.link_failed",
|
|
261
|
+
anonymousId: subject.anonymousId,
|
|
262
|
+
eventProperties,
|
|
263
|
+
source: "account_link",
|
|
264
|
+
},
|
|
265
|
+
context,
|
|
266
|
+
{ allowCreate: false, screenAnonymousId: subject.anonymousId },
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** What `ingestEvent` is handed, narrowed to the fields these three build. */
|
|
271
|
+
interface AccountLinkIngestEvent {
|
|
272
|
+
event: "account.linked" | "account.unlinked" | "account.link_failed";
|
|
273
|
+
userId?: string;
|
|
274
|
+
userEmail?: string;
|
|
275
|
+
anonymousId?: string;
|
|
276
|
+
contactId?: string;
|
|
277
|
+
eventProperties: Record<string, string | number | boolean | null>;
|
|
278
|
+
source: string;
|
|
279
|
+
idempotencyKey?: string;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The one place `ingestEvent` is reached from, so the fire-and-forget contract,
|
|
284
|
+
* the singleton fallbacks and the failure log cannot drift across the three
|
|
285
|
+
* builders above.
|
|
286
|
+
*
|
|
287
|
+
* ## `./ingestion.js` and `./contacts.js` are reached by DYNAMIC import
|
|
288
|
+
*
|
|
289
|
+
* `lib/contacts.ts` imports THIS module (the merge fold's post-commit
|
|
290
|
+
* `account.unlinked`) and `lib/ingestion.ts` imports `lib/contacts.ts`, so a
|
|
291
|
+
* static import here is a module cycle. It is also the
|
|
292
|
+
* `lib/account-link-emit.ts` hazard verbatim: `src/testing.ts` re-exports from
|
|
293
|
+
* `lib/contacts.ts`, and `ingestion.ts` reaches `lib/hatchet.js`, whose import
|
|
294
|
+
* runs `HatchetClient.init(...)` and throws `Invalid token format` where no
|
|
295
|
+
* real token exists. Resolving inside the async body keeps that barrel clean;
|
|
296
|
+
* the ESM module cache makes every call after the first free.
|
|
297
|
+
*/
|
|
298
|
+
function run(
|
|
299
|
+
db: Database,
|
|
300
|
+
handles: AccountLinkIngestHandles,
|
|
301
|
+
event: AccountLinkIngestEvent,
|
|
302
|
+
context: {
|
|
303
|
+
provider: string;
|
|
304
|
+
providerUserId: string | null;
|
|
305
|
+
version?: string;
|
|
306
|
+
},
|
|
307
|
+
opts: { allowCreate?: boolean; screenAnonymousId?: string } = {},
|
|
308
|
+
): void {
|
|
309
|
+
const logger = handles.logger ?? fallbackLogger;
|
|
310
|
+
void ingestOne(db, handles, event, opts, logger).catch((error: unknown) => {
|
|
311
|
+
// ATTRIBUTED, and `error` not `warn`: the journey plane going quiet is
|
|
312
|
+
// invisible from the outbound plane (which kept working), so an operator
|
|
313
|
+
// needs to know WHICH fact failed to route.
|
|
314
|
+
logger.error("account link journey re-ingest failed", {
|
|
315
|
+
event: event.event,
|
|
316
|
+
provider: context.provider,
|
|
317
|
+
providerUserId: context.providerUserId,
|
|
318
|
+
version: context.version ?? null,
|
|
319
|
+
error: error instanceof Error ? error.message : String(error),
|
|
320
|
+
});
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function ingestOne(
|
|
325
|
+
db: Database,
|
|
326
|
+
handles: AccountLinkIngestHandles,
|
|
327
|
+
event: AccountLinkIngestEvent,
|
|
328
|
+
opts: { allowCreate?: boolean; screenAnonymousId?: string },
|
|
329
|
+
logger: Logger,
|
|
330
|
+
): Promise<void> {
|
|
331
|
+
if (opts.screenAnonymousId !== undefined) {
|
|
332
|
+
// The cold arm's key arrives on an unauthenticated URL. `allowCreate:
|
|
333
|
+
// false` already stops it MINTING, but it would still file a
|
|
334
|
+
// `user_events` row under the canonical key of whatever identified
|
|
335
|
+
// contact the value names — injecting a fake `account.link_failed` into a
|
|
336
|
+
// victim's timeline for any journey to trigger on. This is the same guard
|
|
337
|
+
// the engine already applies at its other token-less anon-id-accepting
|
|
338
|
+
// surfaces (`feed/recipient.ts`, `tracking/arrive.ts`, and the cold leg of
|
|
339
|
+
// the account-link callback itself).
|
|
340
|
+
const { collidesWithIdentified } = await import("./contacts.js");
|
|
341
|
+
if (await collidesWithIdentified(db, opts.screenAnonymousId)) {
|
|
342
|
+
logger.warn(
|
|
343
|
+
"account.link_failed re-ingest skipped: the cold anonymous id names " +
|
|
344
|
+
"an identified contact",
|
|
345
|
+
{ event: event.event },
|
|
346
|
+
);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
const { ingestEvent } = await import("./ingestion.js");
|
|
351
|
+
// Only reach for the singleton when the caller had none to give: importing
|
|
352
|
+
// `./hatchet.js` is what runs `HatchetClient.init`.
|
|
353
|
+
const hatchet = handles.hatchet ?? (await import("./hatchet.js")).hatchet;
|
|
354
|
+
const analytics = handles.analytics ?? getAnalytics();
|
|
355
|
+
await ingestEvent({
|
|
356
|
+
db,
|
|
357
|
+
registry: handles.registry ?? getJourneyRegistrySingleton(),
|
|
358
|
+
hatchet,
|
|
359
|
+
logger,
|
|
360
|
+
event,
|
|
361
|
+
...(analytics ? { analytics } : {}),
|
|
362
|
+
...(opts.allowCreate === false ? { allowCreate: false } : {}),
|
|
363
|
+
});
|
|
364
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import {
|
|
4
|
+
type AccountLinkNonceRedis,
|
|
5
|
+
burnAccountLinkNonce,
|
|
6
|
+
NONCE_BURN_TTL_SECONDS,
|
|
7
|
+
} from "./account-link-nonce.js";
|
|
8
|
+
|
|
9
|
+
/** Real `SET NX EX` semantics, plus a record of the exact arguments. */
|
|
10
|
+
function fakeRedis(opts: { throws?: boolean } = {}): AccountLinkNonceRedis & {
|
|
11
|
+
claimed: Map<string, { ttl: number }>;
|
|
12
|
+
} {
|
|
13
|
+
const claimed = new Map<string, { ttl: number }>();
|
|
14
|
+
return {
|
|
15
|
+
claimed,
|
|
16
|
+
async set(key, _value, _ex, ttlSeconds, _nx) {
|
|
17
|
+
if (opts.throws) throw new Error("connection lost");
|
|
18
|
+
if (claimed.has(key)) return null;
|
|
19
|
+
claimed.set(key, { ttl: ttlSeconds });
|
|
20
|
+
return "OK";
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
test("burns a nonce exactly once", async () => {
|
|
26
|
+
const redis = fakeRedis();
|
|
27
|
+
assert.equal(await burnAccountLinkNonce("n-1", redis), true);
|
|
28
|
+
assert.equal(await burnAccountLinkNonce("n-1", redis), false);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("the marker key and TTL mirror the connector burn byte-for-byte in shape", async () => {
|
|
32
|
+
const redis = fakeRedis();
|
|
33
|
+
await burnAccountLinkNonce("n-2", redis);
|
|
34
|
+
assert.deepEqual(
|
|
35
|
+
[...redis.claimed.entries()],
|
|
36
|
+
[["account_link:state:used:n-2", { ttl: NONCE_BURN_TTL_SECONDS }]],
|
|
37
|
+
);
|
|
38
|
+
assert.equal(NONCE_BURN_TTL_SECONDS, 900);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("a null redis REFUSES the burn (fail closed, unlike the connector route)", async () => {
|
|
42
|
+
// The connector callback degrades to TTL-only validity here. This one must
|
|
43
|
+
// not: a replayed account-link callback can MOVE a link (DECISIONS §6.1).
|
|
44
|
+
assert.equal(await burnAccountLinkNonce("n-3", null), false);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("a throwing redis REFUSES the burn", async () => {
|
|
48
|
+
assert.equal(
|
|
49
|
+
await burnAccountLinkNonce("n-4", fakeRedis({ throws: true })),
|
|
50
|
+
false,
|
|
51
|
+
);
|
|
52
|
+
});
|