@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,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
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { getRedisIfConnected } from "./redis.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The single-use nonce burn for the hosted account-link callback.
|
|
5
|
+
*
|
|
6
|
+
* Shape-identical to the connector callback's burn
|
|
7
|
+
* (`routes/connectors/index.ts:136-146`), down to the 900s TTL and the
|
|
8
|
+
* `"OK"`-comparison on the `SET NX` result: the signed state is otherwise
|
|
9
|
+
* TTL-replayable, so a captured callback URL works until `exp` unless the first
|
|
10
|
+
* use burns the per-mint nonce.
|
|
11
|
+
*
|
|
12
|
+
* ONE DELIBERATE DIVERGENCE, and it must stay: when Redis is absent the
|
|
13
|
+
* connector callback degrades to TTL-only validity ("we never block a callback
|
|
14
|
+
* on a cache miss"), and this one REFUSES. DECISIONS §6.8 says fail closed, and
|
|
15
|
+
* the threat differs — a replayed connector install re-captures a guild id,
|
|
16
|
+
* whereas a replayed account-link callback can MOVE a platform account between
|
|
17
|
+
* contacts (DECISIONS §6.1). It is a named function rather than four inline
|
|
18
|
+
* lines so the null-Redis arm is directly testable; a guard whose fail-closed
|
|
19
|
+
* branch no test can reach is a guard nobody will notice losing.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export interface AccountLinkNonceRedis {
|
|
23
|
+
set(
|
|
24
|
+
key: string,
|
|
25
|
+
value: string,
|
|
26
|
+
ex: "EX",
|
|
27
|
+
ttlSeconds: number,
|
|
28
|
+
nx: "NX",
|
|
29
|
+
): Promise<string | null>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Matches `connector:state:used:<nonce>`'s window so the marker outlives any valid state. */
|
|
33
|
+
export const NONCE_BURN_TTL_SECONDS = 900;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Claim a nonce. TRUE exactly once per nonce; FALSE on a replay, on a missing
|
|
37
|
+
* Redis, and on any Redis fault.
|
|
38
|
+
*/
|
|
39
|
+
export async function burnAccountLinkNonce(
|
|
40
|
+
nonce: string,
|
|
41
|
+
redis?: AccountLinkNonceRedis | null,
|
|
42
|
+
): Promise<boolean> {
|
|
43
|
+
const client = redis === undefined ? (getRedisIfConnected() ?? null) : redis;
|
|
44
|
+
if (!client) return false;
|
|
45
|
+
try {
|
|
46
|
+
const claimed = await client.set(
|
|
47
|
+
`account_link:state:used:${nonce}`,
|
|
48
|
+
"1",
|
|
49
|
+
"EX",
|
|
50
|
+
NONCE_BURN_TTL_SECONDS,
|
|
51
|
+
"NX",
|
|
52
|
+
);
|
|
53
|
+
return claimed === "OK";
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { parseAllowedOrigins } from "./account-link-origins.js";
|
|
4
|
+
|
|
5
|
+
test("parses a csv of origins", () => {
|
|
6
|
+
assert.deepEqual(
|
|
7
|
+
parseAllowedOrigins(
|
|
8
|
+
"https://play.example.com, https://www.example.com ,http://localhost:3000",
|
|
9
|
+
),
|
|
10
|
+
[
|
|
11
|
+
"https://play.example.com",
|
|
12
|
+
"https://www.example.com",
|
|
13
|
+
"http://localhost:3000",
|
|
14
|
+
],
|
|
15
|
+
);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test("throws on a path", () => {
|
|
19
|
+
assert.throws(
|
|
20
|
+
() => parseAllowedOrigins("https://x.example.com/cb"),
|
|
21
|
+
/not an absolute origin/,
|
|
22
|
+
);
|
|
23
|
+
assert.throws(
|
|
24
|
+
() => parseAllowedOrigins(["https://x.example.com/cb"]),
|
|
25
|
+
/not an absolute origin/,
|
|
26
|
+
);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("throws on a bare *", () => {
|
|
30
|
+
assert.throws(() => parseAllowedOrigins("*"), /not an absolute origin/);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("throws on a wildcard host", () => {
|
|
34
|
+
assert.throws(
|
|
35
|
+
() => parseAllowedOrigins("https://*.example.com"),
|
|
36
|
+
/not an absolute origin/,
|
|
37
|
+
);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("throws naming the offending entry", () => {
|
|
41
|
+
assert.throws(
|
|
42
|
+
() =>
|
|
43
|
+
parseAllowedOrigins("https://good.example.com,https://bad.example.com/x"),
|
|
44
|
+
/"https:\/\/bad\.example\.com\/x"/,
|
|
45
|
+
);
|
|
46
|
+
// The source label rides along so the operator knows which knob to fix.
|
|
47
|
+
assert.throws(
|
|
48
|
+
() => parseAllowedOrigins(["*"], "accountLinks.allowedOrigins"),
|
|
49
|
+
/accountLinks\.allowedOrigins/,
|
|
50
|
+
);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("returns an empty array for undefined and for an empty string", () => {
|
|
54
|
+
assert.deepEqual(parseAllowedOrigins(undefined), []);
|
|
55
|
+
assert.deepEqual(parseAllowedOrigins(""), []);
|
|
56
|
+
assert.deepEqual(parseAllowedOrigins([]), []);
|
|
57
|
+
// Empty csv slots are dropped, not treated as malformed entries.
|
|
58
|
+
assert.deepEqual(parseAllowedOrigins(",https://a.example.com,,"), [
|
|
59
|
+
"https://a.example.com",
|
|
60
|
+
]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("dedupes", () => {
|
|
64
|
+
assert.deepEqual(
|
|
65
|
+
parseAllowedOrigins([
|
|
66
|
+
"https://a.example.com",
|
|
67
|
+
"https://b.example.com",
|
|
68
|
+
"https://a.example.com",
|
|
69
|
+
]),
|
|
70
|
+
["https://a.example.com", "https://b.example.com"],
|
|
71
|
+
);
|
|
72
|
+
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse the ONE origin allowlist governing `returnTo` (PRD 07) and the
|
|
3
|
+
* `postMessage` targetOrigin (PRD 10). THROWS on a malformed entry rather than
|
|
4
|
+
* dropping it: an allowlist is a security control, and a silently shortened one
|
|
5
|
+
* produces a link button that spins to a timeout while the link has already
|
|
6
|
+
* committed server-side — the single most likely first-run misconfiguration
|
|
7
|
+
* (PRD 13). Precedent: FX_RATES is parsed outside the env schema for exactly
|
|
8
|
+
* this reason (env.ts, lib/fx.ts).
|
|
9
|
+
*
|
|
10
|
+
* Accepts the csv env var (`ACCOUNT_LINK_ALLOWED_ORIGINS`) as a string, or the
|
|
11
|
+
* consumer option (`accountLinks.allowedOrigins`) as an array — the container
|
|
12
|
+
* concatenates env-first and parses both as ONE list, so the same rule applies
|
|
13
|
+
* to each. Entries are trimmed, empties dropped, and each remaining entry must
|
|
14
|
+
* be a parseable ABSOLUTE origin that round-trips (`new URL(e).origin === e`):
|
|
15
|
+
* a path suffix, a bare `*`, or a wildcard host all throw naming the entry.
|
|
16
|
+
* Returns the deduped list, order preserved.
|
|
17
|
+
*
|
|
18
|
+
* `source` names where the offending entry came from in the throw message;
|
|
19
|
+
* the container's single merged call keeps the default naming both.
|
|
20
|
+
*/
|
|
21
|
+
export function parseAllowedOrigins(
|
|
22
|
+
entries: string | string[] | undefined,
|
|
23
|
+
source = "ACCOUNT_LINK_ALLOWED_ORIGINS / accountLinks.allowedOrigins",
|
|
24
|
+
): string[] {
|
|
25
|
+
if (entries === undefined) return [];
|
|
26
|
+
const raw = typeof entries === "string" ? entries.split(",") : entries;
|
|
27
|
+
const origins: string[] = [];
|
|
28
|
+
for (const entry of raw) {
|
|
29
|
+
const trimmed = entry.trim();
|
|
30
|
+
if (trimmed === "") continue;
|
|
31
|
+
let origin: string | undefined;
|
|
32
|
+
// Explicit, BEFORE the URL parse: `*` is not a forbidden host code point
|
|
33
|
+
// in the WHATWG URL Standard, so `new URL("https://*.example.com")`
|
|
34
|
+
// parses and its origin round-trips — the round-trip check alone would
|
|
35
|
+
// wave a wildcard host (or a bare "*", on some runtimes) straight into a
|
|
36
|
+
// postMessage targetOrigin. An allowlist entry is one literal origin.
|
|
37
|
+
if (trimmed.includes("*")) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`allowed origin "${trimmed}" (from ${source}) is not an absolute ` +
|
|
40
|
+
"origin — wildcards are never allowed. Each entry must be one " +
|
|
41
|
+
'literal origin, e.g. "https://play.example.com"',
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
origin = new URL(trimmed).origin;
|
|
46
|
+
} catch {
|
|
47
|
+
// fall through to the throw below with origin undefined
|
|
48
|
+
}
|
|
49
|
+
if (origin !== trimmed) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`allowed origin "${trimmed}" (from ${source}) is not an absolute ` +
|
|
52
|
+
"origin. Each entry must be scheme + host [+ port] exactly — e.g. " +
|
|
53
|
+
'"https://play.example.com" — with no path, no trailing slash, and ' +
|
|
54
|
+
'never a wildcard or "*". A malformed allowlist entry is a security ' +
|
|
55
|
+
"control failure, so it stops boot rather than being dropped",
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
if (!origins.includes(origin)) origins.push(origin);
|
|
59
|
+
}
|
|
60
|
+
return origins;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Is this `returnTo` allowed to be a redirect target?
|
|
65
|
+
*
|
|
66
|
+
* The ONE rule, applied at BOTH ends of the flow: `/start` checks it before it
|
|
67
|
+
* mints a state, and `/callback` re-checks it before it redirects, because the
|
|
68
|
+
* allowlist can be edited while a signed state is in flight and the signature
|
|
69
|
+
* proves only that WE minted the value, never that it is still permitted.
|
|
70
|
+
*
|
|
71
|
+
* Fail-closed by construction: an empty allowlist allows nothing (the container
|
|
72
|
+
* warns once at boot when providers are registered with no origins), an
|
|
73
|
+
* unparseable `returnTo` is refused, and the comparison is on the parsed
|
|
74
|
+
* `origin` — never a `startsWith`, which `https://play.example.com.evil.test`
|
|
75
|
+
* walks straight through.
|
|
76
|
+
*/
|
|
77
|
+
export function isAllowedReturnTo(
|
|
78
|
+
returnTo: string,
|
|
79
|
+
allowedOrigins: readonly string[],
|
|
80
|
+
): boolean {
|
|
81
|
+
if (allowedOrigins.length === 0) return false;
|
|
82
|
+
try {
|
|
83
|
+
return allowedOrigins.includes(new URL(returnTo).origin);
|
|
84
|
+
} catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|