@joryio/web-sdk 1.3.3 → 1.4.0-beta.1
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/CHANGELOG.md +16 -0
- package/README.md +12 -2
- package/dist/core/click-identity.d.ts +7 -0
- package/dist/core/click-identity.d.ts.map +1 -0
- package/dist/core/config.d.ts +8 -2
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/identity.d.ts +1 -1
- package/dist/core/identity.d.ts.map +1 -1
- package/dist/core/inapp.d.ts +4 -1
- package/dist/core/inapp.d.ts.map +1 -1
- package/dist/core/network.d.ts +26 -1
- package/dist/core/network.d.ts.map +1 -1
- package/dist/core/push.d.ts +6 -0
- package/dist/core/push.d.ts.map +1 -1
- package/dist/core/reset-to.d.ts +7 -0
- package/dist/core/reset-to.d.ts.map +1 -0
- package/dist/core/sdk.d.ts +11 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/index.d.mts +42 -4
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/joryio-sw.js +1 -1
- package/dist/joryio.cjs.js +404 -33
- package/dist/joryio.min.js +2 -2
- package/dist/joryio.min.js.map +1 -1
- package/dist/joryio.mjs +404 -33
- package/dist/joryio.umd.js +404 -33
- package/package.json +5 -1
- package/src/core/click-identity.ts +67 -0
- package/src/core/config.ts +47 -2
- package/src/core/identity.ts +4 -3
- package/src/core/inapp.ts +49 -20
- package/src/core/network.ts +205 -6
- package/src/core/push.ts +54 -0
- package/src/core/reset-to.ts +59 -0
- package/src/core/sdk.ts +219 -2
- package/src/index.ts +2 -0
- package/src/snippet/loader.js +5 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joryio/web-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0-beta.1",
|
|
4
4
|
"description": "Joryio Web Tracking SDK - Lightweight analytics and event tracking",
|
|
5
5
|
"main": "dist/joryio.cjs.js",
|
|
6
6
|
"module": "dist/joryio.mjs",
|
|
@@ -88,5 +88,9 @@
|
|
|
88
88
|
"/node_modules/",
|
|
89
89
|
"/dist/"
|
|
90
90
|
]
|
|
91
|
+
},
|
|
92
|
+
"overrides": {
|
|
93
|
+
"minimatch@9.0.3": "9.0.9",
|
|
94
|
+
"serialize-javascript": "^7.1.4"
|
|
91
95
|
}
|
|
92
96
|
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Click-link identity (Joryio BACKLOG D407).
|
|
3
|
+
*
|
|
4
|
+
* A tracked link in a Joryio message lands with `jr_t` - an opaque,
|
|
5
|
+
* authenticated token naming the recipient (no personal data in it). The
|
|
6
|
+
* SDK removes it from the address bar at once (so it is never bookmarked,
|
|
7
|
+
* shared or recorded as a landing page), and - only when tracking is allowed
|
|
8
|
+
* and nobody is identified on this browser - sends it to
|
|
9
|
+
* POST /v1/identify-link with the anonymous id, so this visit is the
|
|
10
|
+
* recipient's. `jr_cid` / `jr_jid` / utm_* stay in the URL as before.
|
|
11
|
+
*
|
|
12
|
+
* Wire contract, identical in every Joryio SDK (the backend's
|
|
13
|
+
* sdk-click-identity-parity.spec.ts): param `jr_t`, path `/v1/identify-link`,
|
|
14
|
+
* body keys `token` and `anonymousId`, public method `identifyFromLink`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const CLICK_IDENTITY_PARAM = 'jr_t';
|
|
18
|
+
export const CLICK_IDENTITY_PATH = '/v1/identify-link';
|
|
19
|
+
/** Base64url, sane length: anything else is not ours and is never sent. */
|
|
20
|
+
export const CLICK_IDENTITY_TOKEN_RE = /^[A-Za-z0-9_-]{16,512}$/;
|
|
21
|
+
|
|
22
|
+
/** The `jr_t` value of a URL (absolute, or relative to the page), or null. */
|
|
23
|
+
export function readClickIdentityToken(url: string | null | undefined): string | null {
|
|
24
|
+
if (typeof url !== 'string' || !url.includes(`${CLICK_IDENTITY_PARAM}=`)) return null;
|
|
25
|
+
try {
|
|
26
|
+
const base = typeof window !== 'undefined' && window.location ? window.location.href : 'https://x.invalid/';
|
|
27
|
+
const value = new URL(url, base).searchParams.get(CLICK_IDENTITY_PARAM);
|
|
28
|
+
return value && CLICK_IDENTITY_TOKEN_RE.test(value) ? value : null;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** `url` without `jr_t` (every other parameter and the fragment kept), or null when it had none. */
|
|
35
|
+
export function withoutClickIdentityToken(url: string): string | null {
|
|
36
|
+
try {
|
|
37
|
+
const parsed = new URL(url);
|
|
38
|
+
if (!parsed.searchParams.has(CLICK_IDENTITY_PARAM)) return null;
|
|
39
|
+
parsed.searchParams.delete(CLICK_IDENTITY_PARAM);
|
|
40
|
+
return parsed.toString();
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Read `jr_t` from the current page and remove it from the address bar
|
|
48
|
+
* (history.replaceState, keeping the history entry's state). Always strips,
|
|
49
|
+
* whatever consent says: URL hygiene is not collection. Returns the token
|
|
50
|
+
* (valid shape only) or null.
|
|
51
|
+
*/
|
|
52
|
+
export function consumeClickIdentityTokenFromLocation(): string | null {
|
|
53
|
+
if (typeof window === 'undefined' || !window.location) return null;
|
|
54
|
+
const href = window.location.href;
|
|
55
|
+
const token = readClickIdentityToken(href);
|
|
56
|
+
const stripped = withoutClickIdentityToken(href);
|
|
57
|
+
if (stripped) {
|
|
58
|
+
try {
|
|
59
|
+
if (window.history && typeof window.history.replaceState === 'function') {
|
|
60
|
+
window.history.replaceState(window.history.state, '', stripped);
|
|
61
|
+
}
|
|
62
|
+
} catch {
|
|
63
|
+
// A sandboxed frame may refuse; the token is still only used once.
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return token;
|
|
67
|
+
}
|
package/src/core/config.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* SDK Configuration Types and Defaults
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
export const SDK_VERSION = '1.
|
|
5
|
+
export const SDK_VERSION = '1.4.0'; // keep in sync with package.json — the backend serves this in X-SDK-Version headers
|
|
6
6
|
export const DEFAULT_API_ENDPOINT = 'https://api-eu1.joryio.com/api';
|
|
7
7
|
|
|
8
8
|
/**
|
|
@@ -148,6 +148,26 @@ export interface InitConfig {
|
|
|
148
148
|
// In-App Messaging
|
|
149
149
|
inApp?: InAppOptions;
|
|
150
150
|
|
|
151
|
+
/**
|
|
152
|
+
* Does this site use Joryio web push? Decides whether the SDK reports the
|
|
153
|
+
* `push_permission` profile attribute on page load.
|
|
154
|
+
*
|
|
155
|
+
* - `true`: reported on page load (only when it changed since the server
|
|
156
|
+
* last acknowledged it), so a segment can find visitors who have not
|
|
157
|
+
* been asked yet (`not_determined`).
|
|
158
|
+
* - unset (default): reported only once this browser has used Joryio web
|
|
159
|
+
* push - `push.subscribe()` was called or `push.prepare()` succeeded,
|
|
160
|
+
* here or on an earlier page view, or the browser was registered for
|
|
161
|
+
* push by an earlier SDK version.
|
|
162
|
+
* - `false`: never reported on page load. A `push.subscribe()` call (or a
|
|
163
|
+
* successful `push.prepare()`) on the page still reports its outcome.
|
|
164
|
+
*
|
|
165
|
+
* A site that does not use web push sends nothing about it: the attribute
|
|
166
|
+
* used to be written for every new visitor, one request each and, for an
|
|
167
|
+
* anonymous visitor the SDK sends nothing else for, a profile of its own.
|
|
168
|
+
*/
|
|
169
|
+
webPush?: boolean;
|
|
170
|
+
|
|
151
171
|
// Storage
|
|
152
172
|
persistQueue?: boolean;
|
|
153
173
|
|
|
@@ -181,6 +201,22 @@ export interface InitConfig {
|
|
|
181
201
|
enableSdkAuthentication?: boolean;
|
|
182
202
|
sdkAuthenticationToken?: string;
|
|
183
203
|
|
|
204
|
+
/**
|
|
205
|
+
* Storefront identity token (store plugins, D383): a token JORYIO minted
|
|
206
|
+
* for a signed-in store customer's browser, bound to one anonymous id (its
|
|
207
|
+
* `vid`). Attached as `X-Joryio-Auth` to ANONYMOUS requests only, and only
|
|
208
|
+
* while that anonymous id is this SDK's. Independent of
|
|
209
|
+
* `enableSdkAuthentication`. Not for sites with their own backend: those
|
|
210
|
+
* use SDK authentication.
|
|
211
|
+
*/
|
|
212
|
+
storefrontIdentityToken?: string;
|
|
213
|
+
/**
|
|
214
|
+
* Called for a fresh storefront identity token when the one held is about
|
|
215
|
+
* to expire or the API refused it as expired. Resolve the new token, or
|
|
216
|
+
* null for none.
|
|
217
|
+
*/
|
|
218
|
+
storefrontIdentityTokenProvider?: () => string | null | undefined | Promise<string | null | undefined>;
|
|
219
|
+
|
|
184
220
|
// Debugging
|
|
185
221
|
/** Log everything (`logLevel: 'debug'`) - unless `logLevel` is set too, which then wins. */
|
|
186
222
|
enableDebug?: boolean;
|
|
@@ -194,14 +230,18 @@ export interface InitConfig {
|
|
|
194
230
|
plugins?: Array<Plugin>;
|
|
195
231
|
}
|
|
196
232
|
|
|
197
|
-
export interface ResolvedConfig extends Required<Omit<InitConfig, 'userId' | 'plugins' | 'inApp' | 'sdkAuthenticationToken' | 'trackingConsent'>> {
|
|
233
|
+
export interface ResolvedConfig extends Required<Omit<InitConfig, 'userId' | 'plugins' | 'inApp' | 'sdkAuthenticationToken' | 'trackingConsent' | 'webPush' | 'storefrontIdentityToken' | 'storefrontIdentityTokenProvider'>> {
|
|
198
234
|
userId?: string;
|
|
235
|
+
/** Undefined = not set by the app (see InitConfig.webPush). */
|
|
236
|
+
webPush?: boolean;
|
|
199
237
|
/** Undefined = not set by the app (see InitConfig.trackingConsent). */
|
|
200
238
|
trackingConsent?: 'granted' | 'denied' | 'pending';
|
|
201
239
|
plugins: Array<Plugin>;
|
|
202
240
|
inApp: Required<InAppOptions>;
|
|
203
241
|
// Optional — absent until the host app supplies a token.
|
|
204
242
|
sdkAuthenticationToken?: string;
|
|
243
|
+
storefrontIdentityToken?: string;
|
|
244
|
+
storefrontIdentityTokenProvider?: InitConfig['storefrontIdentityTokenProvider'];
|
|
205
245
|
/** Whether the logger prints at all: `enableDebug` or an explicit `logLevel`. */
|
|
206
246
|
loggingEnabled: boolean;
|
|
207
247
|
}
|
|
@@ -339,6 +379,8 @@ export function resolveConfig(config: InitConfig): ResolvedConfig {
|
|
|
339
379
|
trackPageProperties: config.trackPageProperties !== false,
|
|
340
380
|
trackDeviceProperties: config.trackDeviceProperties !== false,
|
|
341
381
|
inApp: inAppOptions,
|
|
382
|
+
// Tri-state on purpose: unset ("decide from this browser") is not `false`.
|
|
383
|
+
webPush: config.webPush === true ? true : config.webPush === false ? false : undefined,
|
|
342
384
|
persistQueue: config.persistQueue !== false,
|
|
343
385
|
// 0 is a real value ("no immediate retries"), so not `||`.
|
|
344
386
|
maxRetries:
|
|
@@ -356,6 +398,9 @@ export function resolveConfig(config: InitConfig): ResolvedConfig {
|
|
|
356
398
|
: undefined,
|
|
357
399
|
enableSdkAuthentication: config.enableSdkAuthentication === true,
|
|
358
400
|
sdkAuthenticationToken: config.sdkAuthenticationToken,
|
|
401
|
+
storefrontIdentityToken: typeof config.storefrontIdentityToken === 'string' && config.storefrontIdentityToken ? config.storefrontIdentityToken : undefined,
|
|
402
|
+
storefrontIdentityTokenProvider:
|
|
403
|
+
typeof config.storefrontIdentityTokenProvider === 'function' ? config.storefrontIdentityTokenProvider : undefined,
|
|
359
404
|
enableDebug: config.enableDebug || false,
|
|
360
405
|
// `enableDebug: true` alone means debug; an explicit `logLevel` wins (rule 58).
|
|
361
406
|
logLevel: config.logLevel || (config.enableDebug ? 'debug' : 'error'),
|
package/src/core/identity.ts
CHANGED
|
@@ -85,14 +85,15 @@ export class IdentityManager {
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
/**
|
|
88
|
-
* Reset identity (logout)
|
|
88
|
+
* Reset identity (logout). `anonymousId`: the id to adopt instead of a new
|
|
89
|
+
* random one (resetTo, already validated by the caller).
|
|
89
90
|
*/
|
|
90
|
-
reset(): void {
|
|
91
|
+
reset(anonymousId?: string): void {
|
|
91
92
|
this.logger.debug(`Resetting identity (was: ${this.userId || 'anonymous'})`);
|
|
92
93
|
|
|
93
94
|
this.userId = null;
|
|
94
95
|
this.attributes = {};
|
|
95
|
-
this.anonymousId = generateUUID();
|
|
96
|
+
this.anonymousId = anonymousId || generateUUID();
|
|
96
97
|
|
|
97
98
|
this.storage.remove(USER_ID_KEY);
|
|
98
99
|
this.storage.remove(USER_ATTRIBUTES_KEY);
|
package/src/core/inapp.ts
CHANGED
|
@@ -18,8 +18,13 @@ import { SdkAuthFailureInfo } from './network';
|
|
|
18
18
|
*/
|
|
19
19
|
export interface InAppAuthProvider {
|
|
20
20
|
/** `subjectUserId`: whose request it is - a logged-out user's carries that user's own token. */
|
|
21
|
-
|
|
21
|
+
/** `anonymousId`: the visitor the request names (D383: a storefront token goes only with its own visitor). */
|
|
22
|
+
getSdkAuthHeaders(subjectUserId?: string | null, anonymousId?: string | null): Record<string, string>;
|
|
22
23
|
isSdkAuthError(status: number, data: any): boolean;
|
|
24
|
+
/** D383: a 401 `storefront_identity_error` (optional so test stubs need not have it). */
|
|
25
|
+
isStorefrontIdentityError?(status: number, data: any): boolean;
|
|
26
|
+
/** D383: refresh (expired) or drop the storefront token, so the NEXT call carries a good one or none. */
|
|
27
|
+
handleStorefrontIdentityError?(data: any): Promise<boolean>;
|
|
23
28
|
refreshSdkAuthToken(info: SdkAuthFailureInfo): Promise<string | undefined>;
|
|
24
29
|
/** The signed-in user; the host's auth handler is only asked about THEIR requests (contract item 39). */
|
|
25
30
|
getCurrentUserId?(): string | null;
|
|
@@ -84,6 +89,13 @@ export interface InAppCampaign {
|
|
|
84
89
|
* IN_APP_REQUIRE_DELIVERY_TOKEN is switched on.
|
|
85
90
|
*/
|
|
86
91
|
deliveryToken?: string;
|
|
92
|
+
/**
|
|
93
|
+
* Joryio-signed proof that THIS form was served to THIS visitor (present
|
|
94
|
+
* only when the message carries a form). Sent back as-is on the form
|
|
95
|
+
* submit; the server reads campaign, variant and form from it. Opaque, and
|
|
96
|
+
* it lives 24 hours - every sync brings a fresh one.
|
|
97
|
+
*/
|
|
98
|
+
formToken?: string;
|
|
87
99
|
/** 'journey' when queued by a canvas node; absent for campaign in-apps. */
|
|
88
100
|
source?: string;
|
|
89
101
|
/**
|
|
@@ -975,6 +987,12 @@ export class InAppMessagingManager {
|
|
|
975
987
|
} catch {
|
|
976
988
|
return;
|
|
977
989
|
}
|
|
990
|
+
// D383: a refused storefront identity token - refreshed or dropped, so
|
|
991
|
+
// the next sync / track carries a good one or none (no inline retry here).
|
|
992
|
+
if (this.auth.isStorefrontIdentityError?.(response.status, data)) {
|
|
993
|
+
await this.auth.handleStorefrontIdentityError?.(data).catch(() => false);
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
978
996
|
if (!this.auth.isSdkAuthError(response.status, data)) {
|
|
979
997
|
return;
|
|
980
998
|
}
|
|
@@ -1023,7 +1041,7 @@ export class InAppMessagingManager {
|
|
|
1023
1041
|
headers: {
|
|
1024
1042
|
'Content-Type': 'application/json',
|
|
1025
1043
|
'X-SDK-Key': this.sdkKey,
|
|
1026
|
-
...(this.auth?.getSdkAuthHeaders(subjectUser) || {}),
|
|
1044
|
+
...(this.auth?.getSdkAuthHeaders(subjectUser, subjectUser ? null : this.identity.getAnonymousId()) || {}),
|
|
1027
1045
|
},
|
|
1028
1046
|
body: JSON.stringify({
|
|
1029
1047
|
...this.subject(),
|
|
@@ -1217,7 +1235,7 @@ export class InAppMessagingManager {
|
|
|
1217
1235
|
headers: {
|
|
1218
1236
|
'Content-Type': 'application/json',
|
|
1219
1237
|
'X-SDK-Key': this.sdkKey,
|
|
1220
|
-
...(this.auth?.getSdkAuthHeaders(this.identity.getUserId()) || {}),
|
|
1238
|
+
...(this.auth?.getSdkAuthHeaders(this.identity.getUserId(), this.identity.getUserId() ? null : this.identity.getAnonymousId()) || {}),
|
|
1221
1239
|
},
|
|
1222
1240
|
body: JSON.stringify({
|
|
1223
1241
|
...this.subject(),
|
|
@@ -2400,22 +2418,33 @@ export class InAppMessagingManager {
|
|
|
2400
2418
|
const timeoutId = setTimeout(() => controller.abort(), this.runtime.requestTimeoutMs);
|
|
2401
2419
|
const subjectUser = this.identity.getUserId();
|
|
2402
2420
|
try {
|
|
2403
|
-
const
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2421
|
+
const send = () =>
|
|
2422
|
+
fetch(`${this.apiEndpoint}/v1/in-app/form-submit`, {
|
|
2423
|
+
method: 'POST',
|
|
2424
|
+
headers: {
|
|
2425
|
+
'Content-Type': 'application/json',
|
|
2426
|
+
'X-SDK-Key': this.sdkKey,
|
|
2427
|
+
...(this.auth?.getSdkAuthHeaders(subjectUser, subjectUser ? null : this.identity.getAnonymousId()) || {}),
|
|
2428
|
+
},
|
|
2429
|
+
body: JSON.stringify({
|
|
2430
|
+
campaignId,
|
|
2431
|
+
variantId: (message?.campaign as any)?.variantId,
|
|
2432
|
+
userId: this.identity.getUserId() || undefined,
|
|
2433
|
+
anonymousId: this.identity.getAnonymousId(),
|
|
2434
|
+
...(message?.campaign?.formToken ? { formToken: message.campaign.formToken } : {}),
|
|
2435
|
+
values,
|
|
2436
|
+
}),
|
|
2437
|
+
signal: controller.signal,
|
|
2438
|
+
});
|
|
2439
|
+
let response = await send();
|
|
2440
|
+
// D383: a person's form is not lost to a refused storefront token - it
|
|
2441
|
+
// is refreshed (expired) or dropped, and the form is sent once more.
|
|
2442
|
+
if (response.status === 401 && this.auth?.isStorefrontIdentityError) {
|
|
2443
|
+
const data = await response.clone().json().catch(() => null);
|
|
2444
|
+
if (this.auth.isStorefrontIdentityError(401, data) && (await this.auth.handleStorefrontIdentityError?.(data).catch(() => false))) {
|
|
2445
|
+
response = await send();
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2419
2448
|
await this.maybeHandleSdkAuthError(response, `${this.apiEndpoint}/v1/in-app/form-submit`, subjectUser);
|
|
2420
2449
|
const json = await response.json().catch(() => null);
|
|
2421
2450
|
if (!json || typeof json !== 'object') return { ok: false, message: 'Something went wrong. Please try again.' };
|
|
@@ -2502,7 +2531,7 @@ export class InAppMessagingManager {
|
|
|
2502
2531
|
headers: {
|
|
2503
2532
|
'Content-Type': 'application/json',
|
|
2504
2533
|
'X-SDK-Key': this.sdkKey,
|
|
2505
|
-
...(this.auth?.getSdkAuthHeaders(subjectUser) || {}),
|
|
2534
|
+
...(this.auth?.getSdkAuthHeaders(subjectUser, subjectUser ? null : data.anonymousId ?? null) || {}),
|
|
2506
2535
|
},
|
|
2507
2536
|
body: JSON.stringify(data),
|
|
2508
2537
|
signal: controller.signal,
|
package/src/core/network.ts
CHANGED
|
@@ -274,6 +274,48 @@ export type SdkAuthFailureCallback = (
|
|
|
274
274
|
info: SdkAuthFailureInfo,
|
|
275
275
|
) => void | string | Promise<void | string>;
|
|
276
276
|
|
|
277
|
+
/** The issuer of a storefront identity token (Joryio-signed, D383). Wire value - same as the backend's. */
|
|
278
|
+
export const STOREFRONT_IDENTITY_ISSUER = 'joryio-storefront';
|
|
279
|
+
/** The 401 `error` the API answers for a refused storefront identity token. */
|
|
280
|
+
export const STOREFRONT_IDENTITY_ERROR = 'storefront_identity_error';
|
|
281
|
+
/** A storefront token this close to its expiry is not attached; a fresh one is asked for. */
|
|
282
|
+
const STOREFRONT_TOKEN_MIN_LIFE_MS = 30_000;
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Supplies a fresh storefront identity token (the WordPress plugin's
|
|
286
|
+
* storefront script asks the store for a new customer proof and exchanges
|
|
287
|
+
* it). Resolve null when there is none - the visitor is then anonymous.
|
|
288
|
+
*/
|
|
289
|
+
export type StorefrontIdentityTokenProvider = () => string | null | undefined | Promise<string | null | undefined>;
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The storefront token's claims the SDK reads - WITHOUT verifying it (the API
|
|
293
|
+
* does): its issuer, the visitor id it is bound to, and its expiry.
|
|
294
|
+
*/
|
|
295
|
+
export function storefrontTokenClaims(token: string | undefined): { vid: string; exp: number } | null {
|
|
296
|
+
const c = jwtClaims(token);
|
|
297
|
+
if (!c || c.iss !== STOREFRONT_IDENTITY_ISSUER) return null;
|
|
298
|
+
if (typeof c.vid !== 'string' || !c.vid || typeof c.exp !== 'number') return null;
|
|
299
|
+
return { vid: c.vid, exp: c.exp };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** The anonymous id a request body names (null: none, or an identified request). */
|
|
303
|
+
export function anonymousIdOfBody(body: any): string | null {
|
|
304
|
+
if (!body || typeof body !== 'object') return null;
|
|
305
|
+
if (identifiedUserOf(body)) return null;
|
|
306
|
+
const ids = new Set<string>();
|
|
307
|
+
const add = (v: unknown) => {
|
|
308
|
+
if (typeof v === 'string' && v) ids.add(v);
|
|
309
|
+
};
|
|
310
|
+
add(body.anonymousId);
|
|
311
|
+
if (body.identify) add(body.identify.anonymousId);
|
|
312
|
+
for (const list of [body.events, body.impressions]) {
|
|
313
|
+
if (Array.isArray(list)) list.forEach((e: any) => e && add(e.anonymousId));
|
|
314
|
+
}
|
|
315
|
+
// Two visitors in one body: no single visitor to vouch for.
|
|
316
|
+
return ids.size === 1 ? (ids.values().next().value as string) : null;
|
|
317
|
+
}
|
|
318
|
+
|
|
277
319
|
export interface CircuitBreakerConfig {
|
|
278
320
|
/** Number of consecutive failures before opening the circuit. Default: 5 */
|
|
279
321
|
failureThreshold: number;
|
|
@@ -327,6 +369,19 @@ export class NetworkClient {
|
|
|
327
369
|
/** Current user id, kept in sync so failure info can carry it. */
|
|
328
370
|
private currentUserId: string | null = null;
|
|
329
371
|
|
|
372
|
+
/**
|
|
373
|
+
* Storefront identity token (D383): Joryio-signed, bound to ONE visitor id
|
|
374
|
+
* (its `vid` claim). Attached to an ANONYMOUS request only, and only when
|
|
375
|
+
* the request's visitor is that `vid` and the visitor id this SDK uses now
|
|
376
|
+
* - never to an identified request, never after reset() changed the
|
|
377
|
+
* visitor. Independent of `enableSdkAuthentication`.
|
|
378
|
+
*/
|
|
379
|
+
private storefrontToken: string | undefined;
|
|
380
|
+
private storefrontTokenProvider: StorefrontIdentityTokenProvider | null = null;
|
|
381
|
+
private storefrontRefresh: Promise<string | undefined> | null = null;
|
|
382
|
+
/** The SDK's current anonymous id (a getter: identity owns it). */
|
|
383
|
+
private anonymousIdSource: (() => string | null) | null = null;
|
|
384
|
+
|
|
330
385
|
/**
|
|
331
386
|
* Set by a 402 `SDK_INGESTION_SUSPENDED`: the workspace's ingestion is
|
|
332
387
|
* paused, so every further request this page makes would be refused the same
|
|
@@ -346,6 +401,108 @@ export class NetworkClient {
|
|
|
346
401
|
|
|
347
402
|
// --- SDK Authentication wiring ---------------------------------------
|
|
348
403
|
|
|
404
|
+
// --- Storefront identity token (D383) -------------------------------
|
|
405
|
+
|
|
406
|
+
/** Where the network client reads the SDK's current anonymous id. */
|
|
407
|
+
setAnonymousIdSource(source: (() => string | null) | null): void {
|
|
408
|
+
this.anonymousIdSource = source;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Set / replace the storefront identity token (undefined or '' forgets it). */
|
|
412
|
+
setStorefrontIdentityToken(token: string | null | undefined): void {
|
|
413
|
+
const next = typeof token === 'string' && token ? token : undefined;
|
|
414
|
+
if (next && !storefrontTokenClaims(next)) {
|
|
415
|
+
this.logger.warn('setStorefrontIdentityToken: not a storefront identity token - ignored');
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
this.storefrontToken = next;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Register the provider asked for a fresh storefront token (expired, or refused as expired). */
|
|
422
|
+
setStorefrontIdentityTokenProvider(provider: StorefrontIdentityTokenProvider | null): void {
|
|
423
|
+
this.storefrontTokenProvider = provider;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** reset() / wipeData(): the next visitor is not the store customer. */
|
|
427
|
+
clearStorefrontIdentityToken(): void {
|
|
428
|
+
this.storefrontToken = undefined;
|
|
429
|
+
this.storefrontRefresh = null;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** True if a parsed response body is a `storefront_identity_error`. */
|
|
433
|
+
isStorefrontIdentityError(status: number, data: any): boolean {
|
|
434
|
+
return status === 401 && !!data && typeof data === 'object' && data.error === STOREFRONT_IDENTITY_ERROR;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* The storefront token a request may carry, or undefined. `bodyAnonymousId`:
|
|
439
|
+
* the visitor the body names (anonymousIdOfBody); undefined when the caller
|
|
440
|
+
* has no body to read (it is then the current visitor).
|
|
441
|
+
*/
|
|
442
|
+
private storefrontTokenFor(subjectUserId: string | null | undefined, bodyAnonymousId?: string | null): string | undefined {
|
|
443
|
+
const token = this.storefrontToken;
|
|
444
|
+
if (!token) return undefined;
|
|
445
|
+
const user = subjectUserId === undefined ? this.currentUserId : subjectUserId;
|
|
446
|
+
if (user) return undefined; // identified: the customer's own SDK Authentication, never this
|
|
447
|
+
const claims = storefrontTokenClaims(token);
|
|
448
|
+
const current = this.anonymousIdSource ? this.anonymousIdSource() : null;
|
|
449
|
+
if (!claims || !current || claims.vid !== current) return undefined;
|
|
450
|
+
if (bodyAnonymousId === null) return undefined;
|
|
451
|
+
if (bodyAnonymousId !== undefined && bodyAnonymousId !== claims.vid) return undefined;
|
|
452
|
+
if (claims.exp * 1000 - Date.now() < STOREFRONT_TOKEN_MIN_LIFE_MS) {
|
|
453
|
+
// About to expire: not sent (the API would refuse it); a fresh one is asked for.
|
|
454
|
+
void this.refreshStorefrontToken();
|
|
455
|
+
return undefined;
|
|
456
|
+
}
|
|
457
|
+
return token;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Ask the provider for a fresh token (one request at a time). Resolves the
|
|
462
|
+
* new token when it differs from the one held, else undefined.
|
|
463
|
+
*/
|
|
464
|
+
refreshStorefrontToken(): Promise<string | undefined> {
|
|
465
|
+
if (!this.storefrontTokenProvider) return Promise.resolve(undefined);
|
|
466
|
+
if (this.storefrontRefresh) return this.storefrontRefresh;
|
|
467
|
+
const previous = this.storefrontToken;
|
|
468
|
+
const provider = this.storefrontTokenProvider;
|
|
469
|
+
this.storefrontRefresh = (async () => {
|
|
470
|
+
try {
|
|
471
|
+
const fresh = await Promise.resolve(provider());
|
|
472
|
+
if (typeof fresh === 'string' && fresh && storefrontTokenClaims(fresh)) {
|
|
473
|
+
this.storefrontToken = fresh;
|
|
474
|
+
return fresh !== previous ? fresh : undefined;
|
|
475
|
+
}
|
|
476
|
+
} catch (err) {
|
|
477
|
+
this.logger.warn('The storefront identity token provider failed:', err);
|
|
478
|
+
}
|
|
479
|
+
return undefined;
|
|
480
|
+
})().finally(() => {
|
|
481
|
+
this.storefrontRefresh = null;
|
|
482
|
+
});
|
|
483
|
+
return this.storefrontRefresh;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* A 401 `storefront_identity_error`: `expired` asks the provider for a
|
|
488
|
+
* fresh token; anything else (invalid, vid_mismatch, revoked) drops the
|
|
489
|
+
* token - the visitor carries on as an ordinary anonymous visitor.
|
|
490
|
+
* Resolves true when the request should be retried once.
|
|
491
|
+
*/
|
|
492
|
+
async handleStorefrontIdentityError(data: any): Promise<boolean> {
|
|
493
|
+
const reason = data && typeof data === 'object' ? data.reason : undefined;
|
|
494
|
+
this.logger.warn(`Storefront identity token refused (${reason || 'invalid'})`);
|
|
495
|
+
if (reason === 'expired') {
|
|
496
|
+
const before = this.storefrontToken;
|
|
497
|
+
const fresh = await this.refreshStorefrontToken();
|
|
498
|
+
if (fresh) return true;
|
|
499
|
+
if (this.storefrontToken === before) this.storefrontToken = undefined;
|
|
500
|
+
return true;
|
|
501
|
+
}
|
|
502
|
+
this.storefrontToken = undefined;
|
|
503
|
+
return true;
|
|
504
|
+
}
|
|
505
|
+
|
|
349
506
|
/** Enable/disable SDK authentication (attach + refresh the auth JWT). */
|
|
350
507
|
setSdkAuthenticationEnabled(enabled: boolean): void {
|
|
351
508
|
this.sdkAuthEnabled = enabled;
|
|
@@ -647,8 +804,8 @@ export class NetworkClient {
|
|
|
647
804
|
* `subjectUserId`: the user the request is about - a logged-out user's
|
|
648
805
|
* request carries THAT user's retired token, never the next user's.
|
|
649
806
|
*/
|
|
650
|
-
getSdkAuthHeaders(subjectUserId?: string | null): Record<string, string> {
|
|
651
|
-
const token = this.sdkAuthTokenFor(subjectUserId);
|
|
807
|
+
getSdkAuthHeaders(subjectUserId?: string | null, anonymousId?: string | null): Record<string, string> {
|
|
808
|
+
const token = this.sdkAuthTokenFor(subjectUserId) ?? this.storefrontTokenFor(subjectUserId, anonymousId);
|
|
652
809
|
return token ? { [SDK_AUTH_HEADER]: token } : {};
|
|
653
810
|
}
|
|
654
811
|
|
|
@@ -743,6 +900,8 @@ export class NetworkClient {
|
|
|
743
900
|
}
|
|
744
901
|
const forCurrentUser =
|
|
745
902
|
request.subjectUserId === undefined || (request.subjectUserId || null) === this.currentUserId;
|
|
903
|
+
// The visitor the body names (D383: a storefront token goes only with its own visitor).
|
|
904
|
+
const bodyAnonymousId = request.body ? anonymousIdOfBody(request.body) : undefined;
|
|
746
905
|
|
|
747
906
|
let lastError: Error | null = null;
|
|
748
907
|
let lastStatus = 0;
|
|
@@ -752,12 +911,21 @@ export class NetworkClient {
|
|
|
752
911
|
// SDK-auth refresh is a distinct ONE-SHOT retry, kept out of the
|
|
753
912
|
// backoff loop below so it can never loop or consume a backoff attempt.
|
|
754
913
|
let sdkAuthRefreshAttempted = false;
|
|
914
|
+
let storefrontRetryAttempted = false;
|
|
755
915
|
|
|
756
916
|
while (attempt <= this.retryConfig.maxRetries) {
|
|
757
917
|
try {
|
|
758
918
|
this.logger.debug(`Request attempt ${attempt + 1}/${this.retryConfig.maxRetries + 1}: ${method} ${url}`);
|
|
759
919
|
|
|
760
|
-
let { response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId);
|
|
920
|
+
let { response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId);
|
|
921
|
+
|
|
922
|
+
// --- Storefront identity token refused (D383): refresh or drop, retry once ---
|
|
923
|
+
if (!storefrontRetryAttempted && this.isStorefrontIdentityError(response.status, responseData)) {
|
|
924
|
+
storefrontRetryAttempted = true;
|
|
925
|
+
if (await this.handleStorefrontIdentityError(responseData)) {
|
|
926
|
+
({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId));
|
|
927
|
+
}
|
|
928
|
+
}
|
|
761
929
|
|
|
762
930
|
// --- SDK authentication: one-shot refresh + retry (out-of-band) ---
|
|
763
931
|
// On a 401 sdk_authentication_error, fire the host callback to obtain a
|
|
@@ -778,7 +946,7 @@ export class NetworkClient {
|
|
|
778
946
|
});
|
|
779
947
|
if (fresh) {
|
|
780
948
|
this.logger.debug('SDK authentication token refreshed – retrying request once');
|
|
781
|
-
({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId));
|
|
949
|
+
({ response, responseData } = await this.performFetch(url, method, headers, body, request.subjectUserId, bodyAnonymousId));
|
|
782
950
|
}
|
|
783
951
|
}
|
|
784
952
|
|
|
@@ -919,6 +1087,7 @@ export class NetworkClient {
|
|
|
919
1087
|
callerHeaders: Record<string, string>,
|
|
920
1088
|
body: string | undefined,
|
|
921
1089
|
subjectUserId?: string | null,
|
|
1090
|
+
bodyAnonymousId?: string | null,
|
|
922
1091
|
): Promise<{ response: Response; responseData: any }> {
|
|
923
1092
|
const controller = new AbortController();
|
|
924
1093
|
const timeoutId = setTimeout(() => controller.abort(), this.retryConfig.timeoutMs || 10_000);
|
|
@@ -929,7 +1098,8 @@ export class NetworkClient {
|
|
|
929
1098
|
...callerHeaders,
|
|
930
1099
|
};
|
|
931
1100
|
// Attach the SDK-auth JWT last so the managed token is authoritative.
|
|
932
|
-
|
|
1101
|
+
// An anonymous request may carry the storefront identity token instead (D383).
|
|
1102
|
+
const authToken = this.sdkAuthTokenFor(subjectUserId) ?? this.storefrontTokenFor(subjectUserId, bodyAnonymousId);
|
|
933
1103
|
if (authToken) {
|
|
934
1104
|
headers[SDK_AUTH_HEADER] = authToken;
|
|
935
1105
|
}
|
|
@@ -1089,7 +1259,8 @@ export class NetworkClient {
|
|
|
1089
1259
|
'Content-Type': 'application/json',
|
|
1090
1260
|
'X-SDK-Key': this.sdkKey,
|
|
1091
1261
|
};
|
|
1092
|
-
const
|
|
1262
|
+
const subject = identifiedUserOf(body);
|
|
1263
|
+
const authToken = this.sdkAuthTokenFor(subject) ?? this.storefrontTokenFor(subject, anonymousIdOfBody(body));
|
|
1093
1264
|
if (authToken) {
|
|
1094
1265
|
headers[SDK_AUTH_HEADER] = authToken;
|
|
1095
1266
|
}
|
|
@@ -1147,6 +1318,34 @@ export class NetworkClient {
|
|
|
1147
1318
|
});
|
|
1148
1319
|
}
|
|
1149
1320
|
|
|
1321
|
+
/**
|
|
1322
|
+
* Click-link identity (D407): hand a tracked link's `jr_t` to the server,
|
|
1323
|
+
* which attaches this anonymous visitor to the message's recipient when
|
|
1324
|
+
* the token verifies. Anonymous by construction (no subject user); the
|
|
1325
|
+
* answer is only `{ success, status: 'ok' | 'ignored' }`.
|
|
1326
|
+
*/
|
|
1327
|
+
async sendIdentifyLink(apiEndpoint: string, payload: { token: string; anonymousId: string }): Promise<NetworkResponse> {
|
|
1328
|
+
return this.request({
|
|
1329
|
+
url: `${apiEndpoint}/v1/identify-link`,
|
|
1330
|
+
method: 'POST',
|
|
1331
|
+
body: { token: payload.token, anonymousId: payload.anonymousId },
|
|
1332
|
+
subjectUserId: null,
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/**
|
|
1337
|
+
* A signed-in store customer's token (D383) is held for THIS visitor
|
|
1338
|
+
* (expiring or not - the customer is signed in either way). A provider
|
|
1339
|
+
* alone does not count: stores register one for guests too.
|
|
1340
|
+
*/
|
|
1341
|
+
hasStorefrontIdentity(): boolean {
|
|
1342
|
+
const token = this.storefrontToken;
|
|
1343
|
+
if (!token) return false;
|
|
1344
|
+
const claims = storefrontTokenClaims(token);
|
|
1345
|
+
const current = this.anonymousIdSource ? this.anonymousIdSource() : null;
|
|
1346
|
+
return !!claims && !!current && claims.vid === current;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1150
1349
|
/**
|
|
1151
1350
|
* Add a labelled alias (`aliasLabel` / `aliasName`) to this visitor.
|
|
1152
1351
|
*
|