@corbado/observe 1.10.1 → 1.11.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/dist/analysis/client.mjs +37 -1595
- package/dist/analysis/default-tracker.mjs +16 -0
- package/dist/analysis/index.mjs +29 -41
- package/dist/analysis/plugins/cookie-storage.mjs +11 -0
- package/dist/analysis/plugins/cross-origin-session.mjs +171 -0
- package/dist/analysis/plugins/probes.mjs +69 -0
- package/dist/analysis/plugins/raw-errors.mjs +8 -0
- package/dist/analysis/probe-lane.mjs +175 -0
- package/dist/analysis/queue.mjs +18 -141
- package/dist/analysis/session-keys.mjs +11 -0
- package/dist/analysis/tracker-core.mjs +1352 -0
- package/dist/analysis/tracker-features.mjs +80 -0
- package/dist/analysis/tracker-functions.mjs +103 -0
- package/dist/analysis/utils/appconfirmation-operation-full.mjs +5 -1
- package/dist/analysis/utils/captcha-operation-full.mjs +5 -1
- package/dist/analysis/utils/email-link-operation-full.mjs +9 -1
- package/dist/analysis/utils/email-otp-operation-full.mjs +5 -1
- package/dist/analysis/utils/form-operation-full.mjs +5 -1
- package/dist/analysis/utils/key-operation-full.mjs +9 -1
- package/dist/analysis/utils/operation-full-provide-identifier-with-cui.mjs +8 -1
- package/dist/analysis/utils/operation-full.mjs +4 -2
- package/dist/analysis/utils/passkey-deletion-operation-full.mjs +5 -1
- package/dist/analysis/utils/passkey-enrollment-operation-full.mjs +5 -1
- package/dist/analysis/utils/passkey-login-operation-full.mjs +5 -1
- package/dist/analysis/utils/password-enrollment-operation-full.mjs +5 -1
- package/dist/analysis/utils/password-login-operation-full.mjs +5 -1
- package/dist/analysis/utils/provide-data-operation-full.mjs +5 -1
- package/dist/analysis/utils/sms-otp-operation-full.mjs +5 -1
- package/dist/analysis/utils/social-operation-login.mjs +5 -1
- package/dist/analysis/utils/sso-operation-login.mjs +5 -1
- package/dist/analysis/utils/totp-operation-full.mjs +5 -1
- package/dist/analysis/utils/trusted-device-operation-full.mjs +9 -1
- package/dist/analysis/version.mjs +1 -1
- package/dist/cdn/script.global.js +4 -4
- package/dist/index.d.mts +1366 -883
- package/dist/index.d.ts +1366 -883
- package/dist/index.js +4 -4
- package/dist/index.mjs +4 -4
- package/package.json +1 -1
|
@@ -0,0 +1,1352 @@
|
|
|
1
|
+
// src/tracker-core.ts
|
|
2
|
+
import { reserveCaptureSeq } from "./low-events/capture-sequence.mjs";
|
|
3
|
+
import { readSourcePath } from "./readers/page.mjs";
|
|
4
|
+
import { readUserAgent } from "./readers/device.mjs";
|
|
5
|
+
import { SharedWindowObserver, getCapturePageId } from "./low-events/shared-window-observer.mjs";
|
|
6
|
+
import {
|
|
7
|
+
AuthEventName
|
|
8
|
+
} from "./types.mjs";
|
|
9
|
+
import { FetchTransport } from "./transports/fetch.mjs";
|
|
10
|
+
import { RequestQueue } from "./queue.mjs";
|
|
11
|
+
import { DeviceCollector } from "./device.mjs";
|
|
12
|
+
import { DeviceInfoManager } from "./device-info-manager.mjs";
|
|
13
|
+
import { LocalStorage, namespacedKey, NamespacedStorage, SessionStorage } from "./storage/index.mjs";
|
|
14
|
+
import { OUTBOX_LOCK_NAME } from "./store/event-store.mjs";
|
|
15
|
+
import { migrateLegacyStorage } from "./storage/migration.mjs";
|
|
16
|
+
import {
|
|
17
|
+
DEFAULT_RELIABILITY_CONFIG,
|
|
18
|
+
resolveFixedDataConfig,
|
|
19
|
+
resolveReliabilityConfig
|
|
20
|
+
} from "./config.mjs";
|
|
21
|
+
import { ConfigManager } from "./config-manager.mjs";
|
|
22
|
+
import { v7 as uuidv7 } from "uuid";
|
|
23
|
+
import { isBlockedUserAgent } from "./utils/blocked-user-agents.mjs";
|
|
24
|
+
import { hasWebLocks, withWebLock } from "./readers/web-lock.mjs";
|
|
25
|
+
import { SDK_NAME, SDK_VERSION } from "./version.mjs";
|
|
26
|
+
import { createLogger } from "./logger.mjs";
|
|
27
|
+
import { PasswordManagerSampler } from "./utils/password-manager-sampler.mjs";
|
|
28
|
+
import {
|
|
29
|
+
SEQ_STORAGE_KEY,
|
|
30
|
+
SESSION_CONTINUITY_KEY,
|
|
31
|
+
SESSION_STORAGE_KEY,
|
|
32
|
+
UUID_RE
|
|
33
|
+
} from "./session-keys.mjs";
|
|
34
|
+
var SDK_INFO = {
|
|
35
|
+
name: SDK_NAME,
|
|
36
|
+
version: SDK_VERSION
|
|
37
|
+
};
|
|
38
|
+
var INTEGRATION_VERSION_PATTERN = /^[0-9A-Za-z.+_-]{1,32}$/;
|
|
39
|
+
function sdkInfo(integrationVersion, logger) {
|
|
40
|
+
if (integrationVersion === void 0) return SDK_INFO;
|
|
41
|
+
if (typeof integrationVersion === "string" && INTEGRATION_VERSION_PATTERN.test(integrationVersion)) {
|
|
42
|
+
return { ...SDK_INFO, integrationVersion };
|
|
43
|
+
}
|
|
44
|
+
logger.debug("Ignoring invalid integrationVersion (expected <= 32 chars of [0-9A-Za-z.+_-])");
|
|
45
|
+
return SDK_INFO;
|
|
46
|
+
}
|
|
47
|
+
var EXPERIMENTS_STORAGE_KEY = "cbo_experiments";
|
|
48
|
+
var DATA_POLICY_STORAGE_KEY = "cbo_data_policy";
|
|
49
|
+
var DATA_POLICY_MAX = 255;
|
|
50
|
+
var EXPERIMENT_KEY_RE = /^[A-Za-z0-9_-]+$/;
|
|
51
|
+
var EXPERIMENT_KEY_MAX = 128;
|
|
52
|
+
var EXPERIMENT_VALUE_MAX = 256;
|
|
53
|
+
var TELEMETRY_MESSAGE_MAX = 1e3;
|
|
54
|
+
var MAX_SELF_TELEMETRY = 50;
|
|
55
|
+
var SEQ_LOCK_NAME = "cbo_seq";
|
|
56
|
+
var SESSION_ACTIVITY_WRITE_INTERVAL_MS = 1e3;
|
|
57
|
+
var CorbadoTrackerCore = class _CorbadoTrackerCore {
|
|
58
|
+
/**
|
|
59
|
+
* @param options - Tracker options; `options.plugins` selects the optional features.
|
|
60
|
+
* @param plugins - Plugins installed before `options.plugins` (used by {@link CorbadoTracker}).
|
|
61
|
+
*/
|
|
62
|
+
constructor(options, plugins = []) {
|
|
63
|
+
this.options = options;
|
|
64
|
+
this.options.debug = options.debug ?? false;
|
|
65
|
+
this.logger = options.logger ?? createLogger({ debug: this.options.debug });
|
|
66
|
+
const installed = plugins.concat(Array.isArray(options.plugins) ? options.plugins : []);
|
|
67
|
+
const localStorage = new LocalStorage(this.logger);
|
|
68
|
+
const sessionStorage = new SessionStorage(this.logger);
|
|
69
|
+
let custom;
|
|
70
|
+
this.eachPlugin(installed, (plugin) => {
|
|
71
|
+
if (plugin.storage) custom = plugin.storage(this.logger) || custom;
|
|
72
|
+
});
|
|
73
|
+
migrateLegacyStorage(options.projectId, localStorage, sessionStorage, custom?.engine, this.logger);
|
|
74
|
+
const namespace = options.projectId;
|
|
75
|
+
const scoped = (engine) => new NamespacedStorage(engine, namespace);
|
|
76
|
+
this.seqLockName = namespacedKey(SEQ_LOCK_NAME, namespace);
|
|
77
|
+
this.sessionStorage = scoped(sessionStorage);
|
|
78
|
+
this.persistentStorage = scoped(localStorage);
|
|
79
|
+
this.storage = scoped(custom?.engine ?? localStorage);
|
|
80
|
+
this.configOverrides = {
|
|
81
|
+
...options.sdkConfig,
|
|
82
|
+
...options.sdkConfig?.retry && { retry: { ...options.sdkConfig.retry } },
|
|
83
|
+
...options.sdkConfig?.flushOnFlowTypeFinished && {
|
|
84
|
+
flushOnFlowTypeFinished: [...options.sdkConfig.flushOnFlowTypeFinished]
|
|
85
|
+
},
|
|
86
|
+
...options.sdkConfig?.sourcePathQueryAllow && {
|
|
87
|
+
sourcePathQueryAllow: [...options.sdkConfig.sourcePathQueryAllow]
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
this.fixedData = resolveFixedDataConfig(options.fixedDataConfig);
|
|
91
|
+
if (this.fixedData) {
|
|
92
|
+
this.configOverrides.pmd = this.fixedData.pmd;
|
|
93
|
+
}
|
|
94
|
+
const completeOverride = Object.keys(DEFAULT_RELIABILITY_CONFIG).every(
|
|
95
|
+
(key) => this.configOverrides[key] !== void 0
|
|
96
|
+
) && Object.keys(DEFAULT_RELIABILITY_CONFIG.retry).every(
|
|
97
|
+
(key) => this.configOverrides.retry?.[key] !== void 0
|
|
98
|
+
);
|
|
99
|
+
if (!completeOverride) {
|
|
100
|
+
this.configManager = new ConfigManager(
|
|
101
|
+
options.apiBaseUrl + (options.apiConfigPath ?? "/v1/observe/config") + "/" + options.projectId,
|
|
102
|
+
this.persistentStorage,
|
|
103
|
+
this.logger
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
const cachedConfig = this.configManager?.initialConfig;
|
|
107
|
+
this.config = resolveReliabilityConfig(cachedConfig, this.configOverrides);
|
|
108
|
+
if (!completeOverride && !cachedConfig && options.flushInterval != null && this.configOverrides.flushIntervalMs === void 0) {
|
|
109
|
+
this.config = { ...this.config, flushIntervalMs: options.flushInterval };
|
|
110
|
+
}
|
|
111
|
+
if (!completeOverride && !cachedConfig && options.deviceInfoCollectorTimeout != null && this.configOverrides.deviceInfoCollectorTimeoutMs === void 0) {
|
|
112
|
+
this.config = { ...this.config, deviceInfoCollectorTimeoutMs: options.deviceInfoCollectorTimeout };
|
|
113
|
+
}
|
|
114
|
+
if (options.apiBaseUrl !== "") {
|
|
115
|
+
if (!/^https?:\/\//.test(options.apiBaseUrl)) {
|
|
116
|
+
this.logger.critical(
|
|
117
|
+
`Invalid apiBaseUrl: URL must start with http:// or https:// (got: "${options.apiBaseUrl}")`
|
|
118
|
+
);
|
|
119
|
+
this.reportTelemetry("error", "invalid apiBaseUrl: missing http(s) scheme");
|
|
120
|
+
}
|
|
121
|
+
if (options.apiBaseUrl.endsWith("/")) {
|
|
122
|
+
this.logger.critical(`Invalid apiBaseUrl: URL must not have a trailing slash (got: "${options.apiBaseUrl}")`);
|
|
123
|
+
this.reportTelemetry("error", "invalid apiBaseUrl: trailing slash");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const url = options.apiBaseUrl + (options.apiEventPath ?? "/v1/observe/events") + "/" + options.projectId;
|
|
127
|
+
this.logger.debug(`Using API endpoint: ${url}`);
|
|
128
|
+
const transport = new FetchTransport({
|
|
129
|
+
logger: this.logger,
|
|
130
|
+
url
|
|
131
|
+
});
|
|
132
|
+
this.eachPlugin(installed, (plugin) => {
|
|
133
|
+
if (plugin.session) this.bridge = plugin.session(this) || this.bridge;
|
|
134
|
+
if (plugin.rawErrors) this.rawErrors = plugin.rawErrors;
|
|
135
|
+
});
|
|
136
|
+
if (options.fixedDataConfig?.crossOriginSession && !this.bridge) {
|
|
137
|
+
this.logger.warn("fixedDataConfig.crossOriginSession is ignored without the crossOriginSession() plugin");
|
|
138
|
+
}
|
|
139
|
+
this.sessionId = this.resolveSession();
|
|
140
|
+
this.queue = new RequestQueue(
|
|
141
|
+
this.logger,
|
|
142
|
+
transport,
|
|
143
|
+
this.sessionId,
|
|
144
|
+
sdkInfo(this.options.integrationVersion, this.logger),
|
|
145
|
+
{
|
|
146
|
+
debug: this.options.debug,
|
|
147
|
+
config: this.config,
|
|
148
|
+
requestConfig: false,
|
|
149
|
+
outboxLockName: namespacedKey(OUTBOX_LOCK_NAME, namespace),
|
|
150
|
+
getDataPolicy: () => this.dataPolicy,
|
|
151
|
+
getCrossOriginSession: (sessionId) => this.bridge?.meta(sessionId),
|
|
152
|
+
fixedData: this.fixedData !== void 0 || typeof __CBO_DATA_PMD__ === "boolean" || typeof __CBO_DATA_PRIVATE_MODE__ === "boolean",
|
|
153
|
+
beforeEventBatchSend: (events) => this.attachUndeliveredDeviceInfo(events),
|
|
154
|
+
// The queue is created before the device info manager; both are only called once it exists.
|
|
155
|
+
standaloneDeviceInfo: {
|
|
156
|
+
has: () => this.deviceInfoManager?.hasStandalone() ?? false,
|
|
157
|
+
take: () => this.deviceInfoManager?.takeStandalone()
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
this.persistentStorage
|
|
161
|
+
);
|
|
162
|
+
this.telemetryReady = true;
|
|
163
|
+
this.logger.setTelemetrySink?.((level, message) => this.reportTelemetry(level, message));
|
|
164
|
+
try {
|
|
165
|
+
this.getWindowObserver();
|
|
166
|
+
} catch (error) {
|
|
167
|
+
this.logger.error("Failed to attach page low-event observer", error);
|
|
168
|
+
}
|
|
169
|
+
if (typeof __CBO_DATA_PMD__ === "boolean" ? __CBO_DATA_PMD__ : this.fixedData?.pmd !== false) {
|
|
170
|
+
try {
|
|
171
|
+
this.passwordManagerSampler = this.isTrackingBlocked() ? void 0 : new PasswordManagerSampler(
|
|
172
|
+
this.logger,
|
|
173
|
+
() => typeof __CBO_DATA_PMD__ === "boolean" ? __CBO_DATA_PMD__ : this.config.pmd,
|
|
174
|
+
this.getWindowObserver()
|
|
175
|
+
);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
this.logger.error("Failed to start password manager detection", error);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const bufferedTelemetry = this.pendingSelfTelemetry;
|
|
181
|
+
this.pendingSelfTelemetry = [];
|
|
182
|
+
for (const item of bufferedTelemetry) {
|
|
183
|
+
this.telemetry(item.level, item.message);
|
|
184
|
+
}
|
|
185
|
+
const deviceInfoCollector = new DeviceCollector(
|
|
186
|
+
this.logger,
|
|
187
|
+
this.storage,
|
|
188
|
+
custom?.source ?? "localstorage",
|
|
189
|
+
this.sessionStorage,
|
|
190
|
+
() => ({
|
|
191
|
+
timing: this.config.deviceInfoTiming
|
|
192
|
+
}),
|
|
193
|
+
// Timing entries carry raw millisecond values, so they go through the public telemetry path
|
|
194
|
+
// rather than reportTelemetry: the latter dedupes by exact message and is capped per load,
|
|
195
|
+
// where ever-changing messages would crowd out real error diagnostics.
|
|
196
|
+
(level, message) => this.telemetry(level, message),
|
|
197
|
+
this.fixedData?.privateMode ?? true
|
|
198
|
+
);
|
|
199
|
+
this.deviceCollector = deviceInfoCollector;
|
|
200
|
+
const deviceInfoDebounceTime = options.deviceInfoDebounceTime ?? 3e4;
|
|
201
|
+
this.deviceInfoManager = new DeviceInfoManager(
|
|
202
|
+
this.logger,
|
|
203
|
+
deviceInfoCollector,
|
|
204
|
+
Math.max(1, deviceInfoDebounceTime),
|
|
205
|
+
deviceInfoDebounceTime,
|
|
206
|
+
{
|
|
207
|
+
timing: () => this.config.deviceInfoTiming,
|
|
208
|
+
emit: (level, message) => this.telemetry(level, message)
|
|
209
|
+
},
|
|
210
|
+
() => this.queue.notifyDeviceInfo()
|
|
211
|
+
);
|
|
212
|
+
this.deviceInfoManager.start();
|
|
213
|
+
this.experiments = this.loadPersistedExperiments();
|
|
214
|
+
if (options.experiments) {
|
|
215
|
+
this.setExperiments(options.experiments);
|
|
216
|
+
}
|
|
217
|
+
this.dataPolicy = this.loadPersistedDataPolicy();
|
|
218
|
+
if (options.dataPolicy !== void 0) {
|
|
219
|
+
this.setDataPolicy(options.dataPolicy);
|
|
220
|
+
}
|
|
221
|
+
this.configManager?.start((config) => this.handleConfig(config));
|
|
222
|
+
this.eachPlugin(installed, (plugin) => {
|
|
223
|
+
if (plugin.setup) plugin.setup(this);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
logger;
|
|
227
|
+
queue;
|
|
228
|
+
sessionId;
|
|
229
|
+
storage;
|
|
230
|
+
sessionStorage;
|
|
231
|
+
/** Dedicated localStorage engine for reliability state (config cache, outbox, continuity session, seq). */
|
|
232
|
+
persistentStorage;
|
|
233
|
+
/** Seq/continuity Web Lock name; project-scoped together with the storage keys it guards. */
|
|
234
|
+
seqLockName;
|
|
235
|
+
/** Current resolved policy. Continuity and persistence stay enabled once activated within a document. */
|
|
236
|
+
config;
|
|
237
|
+
configManager;
|
|
238
|
+
configOverrides;
|
|
239
|
+
/** Resolved `fixedDataConfig`; undefined when not given (server-driven data switches). */
|
|
240
|
+
fixedData;
|
|
241
|
+
deviceInfoManager;
|
|
242
|
+
deviceCollector;
|
|
243
|
+
/**
|
|
244
|
+
* Cached per-tab id stamped onto every event's meta (see {@link EventMeta.tabId}). Resolved
|
|
245
|
+
* lazily from the collector's sessionStorage-backed id; stable for the whole page lifetime.
|
|
246
|
+
*/
|
|
247
|
+
eventTabId;
|
|
248
|
+
seq = 0;
|
|
249
|
+
/**
|
|
250
|
+
* When the continuity record's `lastActiveAt` was last persisted. Throttles that write inside the
|
|
251
|
+
* seq critical section (see {@link SESSION_ACTIVITY_WRITE_INTERVAL_MS}). 0 = not written yet on
|
|
252
|
+
* this load, so the first allocation always persists.
|
|
253
|
+
*/
|
|
254
|
+
lastActivityWriteAt = 0;
|
|
255
|
+
/** Persistent experiment assignments (experiment key → variant), attached to every produced event. */
|
|
256
|
+
experiments = {};
|
|
257
|
+
/**
|
|
258
|
+
* Persistent data policy code, stamped into every batch's `meta.dataPolicy` once set. Never
|
|
259
|
+
* cleared (only overwritten): it survives reloads, session rotation, resetSession and destroy.
|
|
260
|
+
*/
|
|
261
|
+
dataPolicy;
|
|
262
|
+
/** Self-instrumentation state: re-entrancy guard, readiness, per-load dedupe, and pre-queue buffer. */
|
|
263
|
+
telemetryReporting = false;
|
|
264
|
+
telemetryReady = false;
|
|
265
|
+
reportedTelemetryKeys = /* @__PURE__ */ new Set();
|
|
266
|
+
pendingSelfTelemetry = [];
|
|
267
|
+
windowObserver;
|
|
268
|
+
passwordManagerSampler;
|
|
269
|
+
/** Session reconciliation of a plugin (the cross-origin session); undefined when none is installed. */
|
|
270
|
+
bridge;
|
|
271
|
+
/** Raw-error serializer of a plugin; undefined = operation step errors drop `rawError`. */
|
|
272
|
+
rawErrors;
|
|
273
|
+
/** @internal Shared passive page observation and per-operation context registration. */
|
|
274
|
+
getWindowObserver() {
|
|
275
|
+
return this.windowObserver ??= new SharedWindowObserver(
|
|
276
|
+
this.logger,
|
|
277
|
+
(low, sessionId) => this.enqueueLowEvent(low, sessionId),
|
|
278
|
+
() => this.lowEventFlushKeepalive()
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
/** Runs `install` per plugin; a missing or throwing plugin is logged and skipped (never throws). */
|
|
282
|
+
eachPlugin(plugins, install) {
|
|
283
|
+
for (const plugin of plugins) {
|
|
284
|
+
try {
|
|
285
|
+
if (plugin) install(plugin);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
this.logger.error("Failed to install tracker plugin", error);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Whether this tracker is the full {@link CorbadoTracker} (created by {@link init} or its constructor).
|
|
293
|
+
* @internal
|
|
294
|
+
*/
|
|
295
|
+
isFullTracker() {
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
/** Apply init overrides on every refresh; continuity and persistence only activate within a document. */
|
|
299
|
+
handleConfig(config) {
|
|
300
|
+
const next = resolveReliabilityConfig(config, this.configOverrides);
|
|
301
|
+
next.sessionContinuity ||= this.config.sessionContinuity;
|
|
302
|
+
next.durableOutbox ||= this.config.durableOutbox;
|
|
303
|
+
this.config = next;
|
|
304
|
+
this.queue.updateConfig(this.config);
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Returns the logger used by this tracker.
|
|
308
|
+
* @internal
|
|
309
|
+
*/
|
|
310
|
+
getLogger() {
|
|
311
|
+
return this.logger;
|
|
312
|
+
}
|
|
313
|
+
applicationTag() {
|
|
314
|
+
if (this.options.applicationId) {
|
|
315
|
+
return { applicationId: this.options.applicationId.toLowerCase() };
|
|
316
|
+
}
|
|
317
|
+
return {};
|
|
318
|
+
}
|
|
319
|
+
// --- Experiments ---
|
|
320
|
+
/**
|
|
321
|
+
* Register several experiment assignments at once (experiment key → variant). Additive: existing
|
|
322
|
+
* assignments for other keys are kept. See {@link CorbadoTracker.setExperiment}.
|
|
323
|
+
*
|
|
324
|
+
* Never throws: invalid input is ignored with a debug log.
|
|
325
|
+
*/
|
|
326
|
+
setExperiments(assignments) {
|
|
327
|
+
try {
|
|
328
|
+
if (!assignments || typeof assignments !== "object") {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
let changed = false;
|
|
332
|
+
for (const [key, variant] of Object.entries(assignments)) {
|
|
333
|
+
if (!_CorbadoTrackerCore.isValidExperimentKey(key) || !_CorbadoTrackerCore.isValidExperimentVariant(variant)) {
|
|
334
|
+
this.logger.debug(`Ignoring invalid experiment assignment "${String(key)}"`);
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
if (this.experiments[key] !== variant) {
|
|
338
|
+
this.experiments[key] = variant;
|
|
339
|
+
changed = true;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (changed) {
|
|
343
|
+
this.persistExperiments();
|
|
344
|
+
}
|
|
345
|
+
} catch (error) {
|
|
346
|
+
this.logger.error("Failed to set experiments", error);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
/** Returns a copy of the currently active experiment assignments. */
|
|
350
|
+
getExperiments() {
|
|
351
|
+
return { ...this.experiments };
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Returns the currently active public SDK configuration, including live updates.
|
|
355
|
+
*
|
|
356
|
+
* @returns A frozen snapshot, created fresh on every call.
|
|
357
|
+
*/
|
|
358
|
+
/** @internal Project-scoped localStorage used by operation helpers (e.g. email-link continuity). */
|
|
359
|
+
getPersistentStorage() {
|
|
360
|
+
return this.persistentStorage;
|
|
361
|
+
}
|
|
362
|
+
getSdkConfig() {
|
|
363
|
+
return Object.freeze({
|
|
364
|
+
version: this.config.version,
|
|
365
|
+
aap: this.config.aap,
|
|
366
|
+
rawErrors: this.config.rawErrors
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
// --- Data policy ---
|
|
370
|
+
/**
|
|
371
|
+
* Set the data policy code for this tracker (e.g. `setDataPolicy(1)` once the user agreed to
|
|
372
|
+
* extended processing; `setDataPolicy(0)` to return to the project default). Codes are
|
|
373
|
+
* project-scoped non-negative integers (0..255) selecting a policy configured in Corbado; they
|
|
374
|
+
* carry no ordering.
|
|
375
|
+
*
|
|
376
|
+
* The code is persisted (localStorage, project-scoped) and sent as `meta.dataPolicy` on every
|
|
377
|
+
* subsequent batch, across reloads and session rotation. It is never cleared, only overwritten.
|
|
378
|
+
* The server records the latest code it receives for a session (last write wins). Invalid codes
|
|
379
|
+
* are ignored with a debug log; never throws.
|
|
380
|
+
*/
|
|
381
|
+
setDataPolicy(code) {
|
|
382
|
+
try {
|
|
383
|
+
if (!_CorbadoTrackerCore.isValidDataPolicy(code)) {
|
|
384
|
+
this.logger.debug(`Ignoring invalid data policy code "${String(code)}"`);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (this.dataPolicy !== code) {
|
|
388
|
+
this.dataPolicy = code;
|
|
389
|
+
this.persistDataPolicy();
|
|
390
|
+
}
|
|
391
|
+
} catch (error) {
|
|
392
|
+
this.logger.error("Failed to set data policy", error);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
/** Returns the current data policy code, or undefined when none has ever been set. */
|
|
396
|
+
getDataPolicy() {
|
|
397
|
+
return this.dataPolicy;
|
|
398
|
+
}
|
|
399
|
+
static isValidDataPolicy(code) {
|
|
400
|
+
return typeof code === "number" && Number.isInteger(code) && code >= 0 && code <= DATA_POLICY_MAX;
|
|
401
|
+
}
|
|
402
|
+
loadPersistedDataPolicy() {
|
|
403
|
+
try {
|
|
404
|
+
const stored = this.persistentStorage.getItem(DATA_POLICY_STORAGE_KEY);
|
|
405
|
+
return _CorbadoTrackerCore.isValidDataPolicy(stored) ? stored : void 0;
|
|
406
|
+
} catch (error) {
|
|
407
|
+
this.logger.debug("Failed to load persisted data policy", error);
|
|
408
|
+
return void 0;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
persistDataPolicy() {
|
|
412
|
+
try {
|
|
413
|
+
if (this.dataPolicy === void 0) {
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
this.persistentStorage.setItem(DATA_POLICY_STORAGE_KEY, this.dataPolicy);
|
|
417
|
+
} catch (error) {
|
|
418
|
+
this.logger.debug("Failed to persist data policy", error);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
static isValidExperimentKey(key) {
|
|
422
|
+
return typeof key === "string" && key.length > 0 && key.length <= EXPERIMENT_KEY_MAX && EXPERIMENT_KEY_RE.test(key);
|
|
423
|
+
}
|
|
424
|
+
static isValidExperimentVariant(variant) {
|
|
425
|
+
return typeof variant === "string" && variant.length > 0 && variant.length <= EXPERIMENT_VALUE_MAX;
|
|
426
|
+
}
|
|
427
|
+
loadPersistedExperiments() {
|
|
428
|
+
try {
|
|
429
|
+
const stored = this.persistentStorage.getItem(EXPERIMENTS_STORAGE_KEY);
|
|
430
|
+
if (!stored || typeof stored !== "object") {
|
|
431
|
+
return {};
|
|
432
|
+
}
|
|
433
|
+
const cleaned = {};
|
|
434
|
+
for (const [key, variant] of Object.entries(stored)) {
|
|
435
|
+
if (_CorbadoTrackerCore.isValidExperimentKey(key) && _CorbadoTrackerCore.isValidExperimentVariant(variant)) {
|
|
436
|
+
cleaned[key] = variant;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
return cleaned;
|
|
440
|
+
} catch (error) {
|
|
441
|
+
this.logger.debug("Failed to load persisted experiments", error);
|
|
442
|
+
return {};
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
persistExperiments() {
|
|
446
|
+
try {
|
|
447
|
+
this.persistentStorage.setItem(EXPERIMENTS_STORAGE_KEY, this.experiments);
|
|
448
|
+
} catch (error) {
|
|
449
|
+
this.logger.debug("Failed to persist experiments", error);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Resolves the experiments to attach to one event: the persistent assignments with any per-call
|
|
454
|
+
* override merged on top. Returns undefined when there are none (so the field is omitted).
|
|
455
|
+
*/
|
|
456
|
+
resolveExperiments(perCall) {
|
|
457
|
+
const merged = { ...this.experiments };
|
|
458
|
+
if (perCall && typeof perCall === "object") {
|
|
459
|
+
for (const [key, variant] of Object.entries(perCall)) {
|
|
460
|
+
if (_CorbadoTrackerCore.isValidExperimentKey(key) && _CorbadoTrackerCore.isValidExperimentVariant(variant)) {
|
|
461
|
+
merged[key] = variant;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return Object.keys(merged).length > 0 ? merged : void 0;
|
|
466
|
+
}
|
|
467
|
+
isTrackingBlocked() {
|
|
468
|
+
if (typeof navigator === "undefined") {
|
|
469
|
+
return false;
|
|
470
|
+
}
|
|
471
|
+
return isBlockedUserAgent(
|
|
472
|
+
readUserAgent({
|
|
473
|
+
key: "browser-api:sdk.blocked-user-agent",
|
|
474
|
+
title: "User agent check for crawlers and bots",
|
|
475
|
+
accessNote: "navigator.userAgent, matched against a list of crawler and bot patterns",
|
|
476
|
+
group: "Observe SDK state",
|
|
477
|
+
origin: "observe-external",
|
|
478
|
+
fields: [
|
|
479
|
+
{
|
|
480
|
+
path: "result",
|
|
481
|
+
label: "Whether the browser looks like a bot",
|
|
482
|
+
exposure: "computed",
|
|
483
|
+
transform: { note: "matched against the blocked user-agent list; only the boolean is used (tracking off)" }
|
|
484
|
+
}
|
|
485
|
+
]
|
|
486
|
+
})
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Resolve the session of this load: locally ({@link resolveSessionId}), or through the session bridge
|
|
491
|
+
* of a plugin (cross-origin session) when one is installed. Used at boot and by the recovery in
|
|
492
|
+
* `getSessionId`.
|
|
493
|
+
*/
|
|
494
|
+
resolveSession() {
|
|
495
|
+
return this.bridge ? this.bridge.resolve() : this.resolveSessionId();
|
|
496
|
+
}
|
|
497
|
+
resolveSessionId() {
|
|
498
|
+
try {
|
|
499
|
+
if (this.config.sessionContinuity) {
|
|
500
|
+
return this.getContinuitySessionId();
|
|
501
|
+
}
|
|
502
|
+
const now = Date.now();
|
|
503
|
+
const stored = this.readPerTabSession();
|
|
504
|
+
if (stored && now - stored.lastActiveAt < this.perTabInactivityMs(stored)) {
|
|
505
|
+
this.persistPerTabSession(stored.id, now);
|
|
506
|
+
this.seq = 0;
|
|
507
|
+
return stored.id;
|
|
508
|
+
}
|
|
509
|
+
const newSessionId = uuidv7();
|
|
510
|
+
this.persistPerTabSession(newSessionId, now);
|
|
511
|
+
this.seq = 0;
|
|
512
|
+
this.logger.debug("Created session id", newSessionId);
|
|
513
|
+
return newSessionId;
|
|
514
|
+
} catch (error) {
|
|
515
|
+
this.logger.error("Failed to get session id", error);
|
|
516
|
+
this.reportTelemetry("error", "failed to get session id");
|
|
517
|
+
return "";
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Resolve the session id from localStorage so it survives reloads and is shared across tabs of the
|
|
522
|
+
* same browser. Rotates after `config.sessionInactivityMs` of inactivity (server-controlled,
|
|
523
|
+
* evaluated at boot), resetting the seq counter.
|
|
524
|
+
*
|
|
525
|
+
* Inactivity rotation happens at boot only, here and on the per-tab path {@link resolveSessionId}
|
|
526
|
+
* takes without continuity. Boot is chosen on an assumption, not a guarantee: that a load
|
|
527
|
+
* re-announces its flow, so the fresh session id gets a classifiable flow. That holds where a
|
|
528
|
+
* flow is opened per load. Where one is opened once and carried across loads it does not, and a
|
|
529
|
+
* boot rotation splits that flow — such a project needs a window long enough to span the journey.
|
|
530
|
+
* Mid-page the assumption is not even available: nothing re-announces between two tracked events,
|
|
531
|
+
* so rotating there would leave the started flow unfinished in the old session and the remaining
|
|
532
|
+
* events without a flow start in the new one — one gap counted as a drop-off, one completion
|
|
533
|
+
* counted as nothing. `nextSeq` therefore never rotates on inactivity, on either path.
|
|
534
|
+
*/
|
|
535
|
+
getContinuitySessionId() {
|
|
536
|
+
const now = Date.now();
|
|
537
|
+
const existing = this.persistentStorage.getItem(SESSION_CONTINUITY_KEY);
|
|
538
|
+
if (existing?.id && now - existing.lastActiveAt < this.config.sessionInactivityMs) {
|
|
539
|
+
this.persistContinuitySession(existing.id, now);
|
|
540
|
+
this.seq = this.persistentStorage.getItem(SEQ_STORAGE_KEY) ?? 0;
|
|
541
|
+
return existing.id;
|
|
542
|
+
}
|
|
543
|
+
if (!existing?.id) {
|
|
544
|
+
const perTab = this.readPerTabSession();
|
|
545
|
+
if (perTab && now - perTab.lastActiveAt < this.config.sessionInactivityMs) {
|
|
546
|
+
this.persistContinuitySession(perTab.id, now);
|
|
547
|
+
this.persistentStorage.setItem(SEQ_STORAGE_KEY, 0);
|
|
548
|
+
this.seq = 0;
|
|
549
|
+
this.logger.debug("Adopted per-tab session id as continuity session", perTab.id);
|
|
550
|
+
return perTab.id;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const newSessionId = uuidv7();
|
|
554
|
+
this.persistContinuitySession(newSessionId, now);
|
|
555
|
+
this.persistentStorage.setItem(SEQ_STORAGE_KEY, 0);
|
|
556
|
+
this.seq = 0;
|
|
557
|
+
this.logger.debug("Created continuity session id", newSessionId);
|
|
558
|
+
return newSessionId;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Persist the continuity record and remember when, so the throttled refresh in the seq critical
|
|
562
|
+
* section measures from the last write that actually happened — whoever made it.
|
|
563
|
+
*/
|
|
564
|
+
persistContinuitySession(id, now) {
|
|
565
|
+
this.lastActivityWriteAt = now;
|
|
566
|
+
this.persistentStorage.setItem(SESSION_CONTINUITY_KEY, { id, lastActiveAt: now });
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Read the per-tab session record. A bare string is the format that predates dating: it carries no
|
|
570
|
+
* `lastActiveAt`, so its window can only start on the load that reads it. That load rewrites it in
|
|
571
|
+
* the dated shape, so a tab converts once and ages normally from then on, and the case drains as
|
|
572
|
+
* the rollout replaces the bundles that write it.
|
|
573
|
+
*/
|
|
574
|
+
readPerTabSession() {
|
|
575
|
+
const stored = this.sessionStorage.getItem(SESSION_STORAGE_KEY);
|
|
576
|
+
if (!stored) {
|
|
577
|
+
return void 0;
|
|
578
|
+
}
|
|
579
|
+
if (typeof stored === "string") {
|
|
580
|
+
return UUID_RE.test(stored) ? { id: stored, lastActiveAt: Date.now() } : void 0;
|
|
581
|
+
}
|
|
582
|
+
if (typeof stored.lastActiveAt !== "number") {
|
|
583
|
+
return void 0;
|
|
584
|
+
}
|
|
585
|
+
return UUID_RE.test(stored.id) ? stored : void 0;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Persist the per-tab record and remember when, sharing the throttle bookkeeping with the
|
|
589
|
+
* continuity record — a load resolves its session on one path or the other, never both.
|
|
590
|
+
*
|
|
591
|
+
* An explicit timeout override or server config stamps the window. Otherwise carry forward what
|
|
592
|
+
* the tab already knows, so a defaults boot does not replace a previously configured threshold.
|
|
593
|
+
*/
|
|
594
|
+
persistPerTabSession(id, now) {
|
|
595
|
+
this.lastActivityWriteAt = now;
|
|
596
|
+
const inactivityMs = this.configOverrides.sessionInactivityMs !== void 0 || this.config.version ? this.config.sessionInactivityMs : this.readPerTabSession()?.inactivityMs;
|
|
597
|
+
this.sessionStorage.setItem(SESSION_STORAGE_KEY, {
|
|
598
|
+
id,
|
|
599
|
+
lastActiveAt: now,
|
|
600
|
+
...inactivityMs === void 0 ? {} : { inactivityMs }
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
/** Explicit init timeout wins; otherwise retain the window a prior configured load recorded. */
|
|
604
|
+
perTabInactivityMs(stored) {
|
|
605
|
+
return this.configOverrides.sessionInactivityMs !== void 0 ? this.config.sessionInactivityMs : stored.inactivityMs ?? this.config.sessionInactivityMs;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Return the next sequence number. With session continuity the counter is persisted so ordering
|
|
609
|
+
* survives reloads/redirects; the read-increment-write runs under a cross-tab Web Lock
|
|
610
|
+
* ({@link SEQ_LOCK_NAME}) so two tabs sharing the session cannot allocate the same seq (where Web
|
|
611
|
+
* Locks are unavailable or exceed the configured timeout it degrades to the historical best-effort merge).
|
|
612
|
+
* Lock grants are FIFO, so seq order matches `track()` call order within a tab. Tracking also keeps the
|
|
613
|
+
* continuity session's `lastActiveAt` fresh (throttled, see {@link SESSION_ACTIVITY_WRITE_INTERVAL_MS}),
|
|
614
|
+
* so the window the NEXT boot evaluates measures real user
|
|
615
|
+
* inactivity instead of time-since-page-load (a long-lived active tab must not rotate the session
|
|
616
|
+
* on the next reload). It never rotates the session itself: the inactivity window is evaluated at
|
|
617
|
+
* boot only ({@link getContinuitySessionId} documents why). Consequence: while a page is never
|
|
618
|
+
* reloaded — foreground idle, bfcache restore, long-lived SPA tab — a session can outlive
|
|
619
|
+
* `sessionInactivityMs`. That inflates flow durations but keeps flow counts correct, which is the
|
|
620
|
+
* better half of the trade. An empty store while this load already has a session id means
|
|
621
|
+
* persistence is failing (or was cleared); the in-memory id is reused then — never re-minted — so
|
|
622
|
+
* a broken store degrades to one session per page load instead of one session per event.
|
|
623
|
+
*/
|
|
624
|
+
nextSeq() {
|
|
625
|
+
if (!this.config.sessionContinuity) {
|
|
626
|
+
const now = Date.now();
|
|
627
|
+
if (this.sessionId && now - this.lastActivityWriteAt >= SESSION_ACTIVITY_WRITE_INTERVAL_MS) {
|
|
628
|
+
this.persistPerTabSession(this.sessionId, now);
|
|
629
|
+
}
|
|
630
|
+
const current = this.bridge ? this.bridge.claim(this.sessionId, this.seq, now) : this.seq;
|
|
631
|
+
this.seq = current + 1;
|
|
632
|
+
return current;
|
|
633
|
+
}
|
|
634
|
+
const allocate = () => {
|
|
635
|
+
const now = Date.now();
|
|
636
|
+
const storedSession = this.persistentStorage.getItem(SESSION_CONTINUITY_KEY);
|
|
637
|
+
let sessionChanged = false;
|
|
638
|
+
if (!storedSession?.id && this.sessionId) {
|
|
639
|
+
this.persistContinuitySession(this.sessionId, now);
|
|
640
|
+
} else if (!storedSession?.id) {
|
|
641
|
+
const newSessionId = uuidv7();
|
|
642
|
+
this.persistContinuitySession(newSessionId, now);
|
|
643
|
+
this.persistentStorage.setItem(SEQ_STORAGE_KEY, 0);
|
|
644
|
+
this.sessionId = newSessionId;
|
|
645
|
+
this.queue.setSessionId(newSessionId);
|
|
646
|
+
this.seq = 0;
|
|
647
|
+
sessionChanged = true;
|
|
648
|
+
} else {
|
|
649
|
+
if (now - this.lastActivityWriteAt >= SESSION_ACTIVITY_WRITE_INTERVAL_MS) {
|
|
650
|
+
this.persistContinuitySession(storedSession.id, now);
|
|
651
|
+
}
|
|
652
|
+
if (storedSession.id !== this.sessionId) {
|
|
653
|
+
this.sessionId = storedSession.id;
|
|
654
|
+
this.queue.setSessionId(storedSession.id);
|
|
655
|
+
sessionChanged = true;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
const stored = this.persistentStorage.getItem(SEQ_STORAGE_KEY);
|
|
659
|
+
if (sessionChanged) {
|
|
660
|
+
this.seq = typeof stored === "number" ? stored : 0;
|
|
661
|
+
}
|
|
662
|
+
let current = typeof stored === "number" && stored > this.seq ? stored : this.seq;
|
|
663
|
+
if (this.bridge) {
|
|
664
|
+
current = this.bridge.claim(this.sessionId, current, now);
|
|
665
|
+
}
|
|
666
|
+
this.seq = current + 1;
|
|
667
|
+
this.persistentStorage.setItem(SEQ_STORAGE_KEY, this.seq);
|
|
668
|
+
return current;
|
|
669
|
+
};
|
|
670
|
+
const timeoutMs = this.config.seqLockTimeoutMs;
|
|
671
|
+
if (timeoutMs === 0 || !hasWebLocks({
|
|
672
|
+
key: "browser-api:sdk.web-locks",
|
|
673
|
+
title: "Coordination of Observe data across open tabs",
|
|
674
|
+
accessNote: "Web Locks API (navigator.locks) on Observe's own lock names",
|
|
675
|
+
group: "Observe SDK state",
|
|
676
|
+
origin: "observe-internal",
|
|
677
|
+
fields: [
|
|
678
|
+
{
|
|
679
|
+
path: "available",
|
|
680
|
+
label: "Whether the browser supports tab coordination",
|
|
681
|
+
exposure: "enum",
|
|
682
|
+
transform: { values: [true, false] }
|
|
683
|
+
}
|
|
684
|
+
]
|
|
685
|
+
})) {
|
|
686
|
+
return allocate();
|
|
687
|
+
}
|
|
688
|
+
return withWebLock(
|
|
689
|
+
{
|
|
690
|
+
key: "browser-api:sdk.web-locks",
|
|
691
|
+
title: "Coordination of Observe data across open tabs",
|
|
692
|
+
accessNote: "Web Locks API (navigator.locks) on Observe's own lock names",
|
|
693
|
+
group: "Observe SDK state",
|
|
694
|
+
origin: "observe-internal",
|
|
695
|
+
fields: [
|
|
696
|
+
{
|
|
697
|
+
path: "result",
|
|
698
|
+
label: "Coordination between open tabs",
|
|
699
|
+
exposure: "none",
|
|
700
|
+
transform: { note: "own cbo_* lock names; serializes the SDK's storage updates across tabs" }
|
|
701
|
+
}
|
|
702
|
+
]
|
|
703
|
+
},
|
|
704
|
+
this.seqLockName,
|
|
705
|
+
allocate,
|
|
706
|
+
{
|
|
707
|
+
timeoutMs,
|
|
708
|
+
onTimeout: () => {
|
|
709
|
+
this.logger.warn(`Sequence Web Lock acquisition timed out after ${timeoutMs}ms; using fallback`);
|
|
710
|
+
this.reportTelemetry("info", `seq web lock timeout; using fallback, ${timeoutMs}ms`);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
);
|
|
714
|
+
}
|
|
715
|
+
resolveTrackingSourcePath() {
|
|
716
|
+
if (typeof window === "undefined") {
|
|
717
|
+
return void 0;
|
|
718
|
+
}
|
|
719
|
+
return readSourcePath(
|
|
720
|
+
{
|
|
721
|
+
key: "page:location.source-path",
|
|
722
|
+
title: "Page path and allowed query parameters",
|
|
723
|
+
accessNote: "location.pathname and location.search; the query is reduced by the sourcePathQuery policy inside the reader (trackingSourcePath)",
|
|
724
|
+
group: "Page",
|
|
725
|
+
origin: "observe-external",
|
|
726
|
+
fields: [
|
|
727
|
+
{ path: "url.path", label: "Page path", exposure: "raw" },
|
|
728
|
+
{
|
|
729
|
+
path: "url.query",
|
|
730
|
+
label: "Page address parameters (allowed ones only)",
|
|
731
|
+
exposure: "redacted",
|
|
732
|
+
transform: { note: "sourcePathQuery 'allowlist': values of non-allowlisted keys become '*'; 'all': raw" }
|
|
733
|
+
}
|
|
734
|
+
]
|
|
735
|
+
},
|
|
736
|
+
this.config.sourcePathQuery,
|
|
737
|
+
this.config.sourcePathQueryAllow
|
|
738
|
+
);
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Per-tab id for event meta, cached after the first successful resolution: the id is
|
|
742
|
+
* sessionStorage-backed and stable for the whole page lifetime.
|
|
743
|
+
*/
|
|
744
|
+
resolveEventTabId() {
|
|
745
|
+
if (this.eventTabId === void 0) {
|
|
746
|
+
this.eventTabId = this.deviceCollector.getTabId();
|
|
747
|
+
}
|
|
748
|
+
return this.eventTabId;
|
|
749
|
+
}
|
|
750
|
+
/** @internal */
|
|
751
|
+
trackSubflowStarted(subflowType, data, options, eventId) {
|
|
752
|
+
const wrappedData = {
|
|
753
|
+
subflowType,
|
|
754
|
+
...data
|
|
755
|
+
};
|
|
756
|
+
void this.track(
|
|
757
|
+
AuthEventName.SubflowStarted,
|
|
758
|
+
wrappedData,
|
|
759
|
+
options?.userReference,
|
|
760
|
+
void 0,
|
|
761
|
+
void 0,
|
|
762
|
+
options?.explicitTimestamp,
|
|
763
|
+
options?.experiments,
|
|
764
|
+
{
|
|
765
|
+
id: eventId,
|
|
766
|
+
subflowStartEventId: options?.subflowStartEventId,
|
|
767
|
+
sessionId: options?.captureSessionId,
|
|
768
|
+
initiator: options?.initiator
|
|
769
|
+
}
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
/** @internal */
|
|
773
|
+
trackSubflowTrigger(subflowType, data, options) {
|
|
774
|
+
const wrappedData = {
|
|
775
|
+
subflowType,
|
|
776
|
+
...data
|
|
777
|
+
};
|
|
778
|
+
void this.track(
|
|
779
|
+
AuthEventName.SubflowTrigger,
|
|
780
|
+
wrappedData,
|
|
781
|
+
options?.userReference,
|
|
782
|
+
void 0,
|
|
783
|
+
void 0,
|
|
784
|
+
options?.explicitTimestamp,
|
|
785
|
+
options?.experiments,
|
|
786
|
+
{
|
|
787
|
+
subflowStartEventId: options?.subflowStartEventId,
|
|
788
|
+
sessionId: options?.captureSessionId,
|
|
789
|
+
initiator: options?.initiator
|
|
790
|
+
}
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
/** @internal */
|
|
794
|
+
trackSubflowStepStarted(subflowType, stepName, data, options, ignoreAsInteraction) {
|
|
795
|
+
const wrappedData = {
|
|
796
|
+
subflowType,
|
|
797
|
+
stepName,
|
|
798
|
+
stepData: data,
|
|
799
|
+
identifier: options?.identifier,
|
|
800
|
+
ignoreAsInteraction
|
|
801
|
+
};
|
|
802
|
+
void this.track(
|
|
803
|
+
AuthEventName.SubflowStepStarted,
|
|
804
|
+
wrappedData,
|
|
805
|
+
options?.userReference,
|
|
806
|
+
void 0,
|
|
807
|
+
void 0,
|
|
808
|
+
options?.explicitTimestamp,
|
|
809
|
+
options?.experiments,
|
|
810
|
+
{
|
|
811
|
+
subflowStartEventId: options?.subflowStartEventId,
|
|
812
|
+
sessionId: options?.captureSessionId,
|
|
813
|
+
initiator: options?.initiator
|
|
814
|
+
}
|
|
815
|
+
);
|
|
816
|
+
}
|
|
817
|
+
/** @internal */
|
|
818
|
+
trackSubflowStepFinished(subflowType, stepName, data, options) {
|
|
819
|
+
const wrappedData = {
|
|
820
|
+
subflowType,
|
|
821
|
+
stepName,
|
|
822
|
+
stepData: data,
|
|
823
|
+
identifier: options?.identifier
|
|
824
|
+
};
|
|
825
|
+
void this.track(
|
|
826
|
+
AuthEventName.SubflowStepFinished,
|
|
827
|
+
wrappedData,
|
|
828
|
+
options?.userReference,
|
|
829
|
+
void 0,
|
|
830
|
+
void 0,
|
|
831
|
+
options?.explicitTimestamp,
|
|
832
|
+
options?.experiments,
|
|
833
|
+
{
|
|
834
|
+
subflowStartEventId: options?.subflowStartEventId,
|
|
835
|
+
sessionId: options?.captureSessionId,
|
|
836
|
+
initiator: options?.initiator
|
|
837
|
+
}
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
/** @internal */
|
|
841
|
+
trackSubflowStepError(subflowType, stepName, data, options) {
|
|
842
|
+
const wrappedData = {
|
|
843
|
+
subflowType,
|
|
844
|
+
stepName,
|
|
845
|
+
stepData: data,
|
|
846
|
+
identifier: options?.identifier
|
|
847
|
+
};
|
|
848
|
+
void this.track(
|
|
849
|
+
AuthEventName.SubflowStepError,
|
|
850
|
+
wrappedData,
|
|
851
|
+
options?.userReference,
|
|
852
|
+
void 0,
|
|
853
|
+
void 0,
|
|
854
|
+
options?.explicitTimestamp,
|
|
855
|
+
options?.experiments,
|
|
856
|
+
{
|
|
857
|
+
subflowStartEventId: options?.subflowStartEventId,
|
|
858
|
+
sessionId: options?.captureSessionId,
|
|
859
|
+
initiator: options?.initiator
|
|
860
|
+
}
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Error situations:
|
|
865
|
+
* - Blocked user agent (see `isBlockedUserAgent`): skip with a debug log and return
|
|
866
|
+
* - Any error before the event is enqueued (e.g. `JSON.stringify` in debug logging, `queue.enqueue`): log `Failed to process event "<name>" before enqueue`
|
|
867
|
+
*
|
|
868
|
+
* @internal
|
|
869
|
+
*/
|
|
870
|
+
async track(name, data, userReference, tags, contexts, explicitTimestamp, experiments, capture) {
|
|
871
|
+
try {
|
|
872
|
+
if (this.isTrackingBlocked()) {
|
|
873
|
+
this.logger.debug(`Skipping event "${name}" for blocked user agent.`);
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
if (name === AuthEventName.FlowFinished || name === AuthEventName.FlowAutoFinished || name === AuthEventName.FlowReset) {
|
|
877
|
+
this.windowObserver?.flushInputs();
|
|
878
|
+
}
|
|
879
|
+
const timestamp = explicitTimestamp ?? Date.now();
|
|
880
|
+
const capturedId = capture?.id ?? uuidv7();
|
|
881
|
+
const capturedSessionId = capture?.sessionId ?? this.sessionId;
|
|
882
|
+
const nextSeq = this.nextSeq();
|
|
883
|
+
const seq = typeof nextSeq === "number" ? nextSeq : await nextSeq;
|
|
884
|
+
const trackingSourcePath = this.resolveTrackingSourcePath();
|
|
885
|
+
const event = {
|
|
886
|
+
type: "predefined",
|
|
887
|
+
name,
|
|
888
|
+
id: capturedId,
|
|
889
|
+
timestamp,
|
|
890
|
+
seq,
|
|
891
|
+
data,
|
|
892
|
+
user: userReference,
|
|
893
|
+
contexts,
|
|
894
|
+
tags,
|
|
895
|
+
experiments: this.resolveExperiments(experiments),
|
|
896
|
+
meta: {
|
|
897
|
+
captureVersion: 1,
|
|
898
|
+
pageId: getCapturePageId(),
|
|
899
|
+
initiator: capture?.initiator,
|
|
900
|
+
trackingSourcePath: trackingSourcePath ?? "",
|
|
901
|
+
subflowStartEventId: capture?.subflowStartEventId,
|
|
902
|
+
tabId: this.resolveEventTabId()
|
|
903
|
+
}
|
|
904
|
+
};
|
|
905
|
+
const deviceInfo = this.deviceInfoManager.getForEvent();
|
|
906
|
+
if (deviceInfo) {
|
|
907
|
+
event.deviceInfo = deviceInfo;
|
|
908
|
+
}
|
|
909
|
+
this.logger.debug(`Track: ${name}`, JSON.stringify(event, null, 2));
|
|
910
|
+
const passwordManagers = this.passwordManagerSampler?.takeReport(capturedSessionId);
|
|
911
|
+
if (passwordManagers) {
|
|
912
|
+
event.passwordManagers = passwordManagers;
|
|
913
|
+
}
|
|
914
|
+
this.queue.enqueue(event, capturedSessionId);
|
|
915
|
+
} catch (error) {
|
|
916
|
+
this.logger.error(`Failed to process event "${name}" before enqueue`, error);
|
|
917
|
+
this.reportTelemetry("error", `failed to process event "${name}" before enqueue`);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
// --- Typed Tracking Methods ---
|
|
921
|
+
/**
|
|
922
|
+
* Track when an authentication flow (or flow selection screen) becomes visible.
|
|
923
|
+
*
|
|
924
|
+
* @remarks
|
|
925
|
+
* Call this once when the user first enters an auth touchpoint (for example account login,
|
|
926
|
+
* checkout login, or account recovery). If users can choose between multiple flows
|
|
927
|
+
* (such as login vs signup), pass `flowNames` and optionally `defaultFlowName`.
|
|
928
|
+
*
|
|
929
|
+
* The returned handle can attach identity after completion with `await flow.enrich({ userId })`.
|
|
930
|
+
* Enrichment requires a backend supporting explicit event targeting.
|
|
931
|
+
*
|
|
932
|
+
* @param data - Flow metadata, including one flow (`flowName`) or multiple candidates (`flowNames`).
|
|
933
|
+
* @param tags - Optional key-value tags for filtering and segmentation.
|
|
934
|
+
* @param experiments - Optional per-call experiment overrides.
|
|
935
|
+
* @param contexts - Optional structured event context (e.g. technical metadata that is not an
|
|
936
|
+
* analytical dimension). Written to the event's `contexts` field verbatim.
|
|
937
|
+
* @param options - Optional `explicitTimestamp` (epoch ms) when the flow became visible earlier than
|
|
938
|
+
* this call, e.g. because an integration confirms a screen only after it stayed up for a while.
|
|
939
|
+
*
|
|
940
|
+
* @example
|
|
941
|
+
* ```typescript
|
|
942
|
+
* tracker.flowStarted({
|
|
943
|
+
* flowNames: ["login", "signup"],
|
|
944
|
+
* defaultFlowName: "login",
|
|
945
|
+
* touchpoint: "account",
|
|
946
|
+
* });
|
|
947
|
+
* ```
|
|
948
|
+
*/
|
|
949
|
+
flowStarted(data, tags, experiments, contexts, options) {
|
|
950
|
+
try {
|
|
951
|
+
const targetEventId = uuidv7();
|
|
952
|
+
const sessionId = this.sessionId;
|
|
953
|
+
const effectiveTags = { ...this.options.defaultTags, ...this.applicationTag(), ...tags };
|
|
954
|
+
void this.track(
|
|
955
|
+
AuthEventName.FlowStarted,
|
|
956
|
+
data,
|
|
957
|
+
void 0,
|
|
958
|
+
effectiveTags,
|
|
959
|
+
contexts,
|
|
960
|
+
options?.explicitTimestamp,
|
|
961
|
+
experiments,
|
|
962
|
+
{
|
|
963
|
+
id: targetEventId,
|
|
964
|
+
sessionId
|
|
965
|
+
}
|
|
966
|
+
);
|
|
967
|
+
return this.flowHandle(targetEventId, sessionId);
|
|
968
|
+
} catch (error) {
|
|
969
|
+
this.logger.warn("Failed to start flow", error);
|
|
970
|
+
return { enrich: async () => {
|
|
971
|
+
} };
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Track when the user commits to a specific flow.
|
|
976
|
+
*
|
|
977
|
+
* @remarks
|
|
978
|
+
* Use this after presenting alternatives and once you know which path the user takes
|
|
979
|
+
* (for example when identifier checks route to login vs signup).
|
|
980
|
+
*
|
|
981
|
+
* @param data - Selected flow name.
|
|
982
|
+
* @param tags - Optional key-value tags for filtering and segmentation.
|
|
983
|
+
*
|
|
984
|
+
* @example
|
|
985
|
+
* ```typescript
|
|
986
|
+
* tracker.flowDecided({flowName: "signup"});
|
|
987
|
+
* ```
|
|
988
|
+
*/
|
|
989
|
+
flowDecided(data, tags, experiments) {
|
|
990
|
+
void this.track(AuthEventName.FlowDecided, data, void 0, tags, void 0, void 0, experiments);
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Track when a flow successfully completes.
|
|
994
|
+
*
|
|
995
|
+
* @remarks
|
|
996
|
+
* Fire this when the user has finished the target flow end-to-end, such as completed login,
|
|
997
|
+
* signup, or recovery. Record identity with `setUser()` while the flow is active,
|
|
998
|
+
* or enrich it after completion through the handle returned by `flowStarted()` or by this call.
|
|
999
|
+
*
|
|
1000
|
+
* The returned handle targets the flow this event finished, so identity learned only after
|
|
1001
|
+
* completion — for example from a profile request that follows account creation — can be
|
|
1002
|
+
* attached with `await finished.enrich({ userId })` even on a page that never saw the flow start.
|
|
1003
|
+
* Enrichment requires a backend supporting explicit flow-event targeting.
|
|
1004
|
+
*
|
|
1005
|
+
* Legacy identity fields in `data` remain supported but are deprecated.
|
|
1006
|
+
*
|
|
1007
|
+
* @param data - Finished flow name, optional explicit outcome, and deprecated user reference fields.
|
|
1008
|
+
* @param tags - Optional key-value tags for filtering and segmentation.
|
|
1009
|
+
*
|
|
1010
|
+
* @example
|
|
1011
|
+
* ```typescript
|
|
1012
|
+
* const finished = tracker.flowFinished({ flowName: "signup" });
|
|
1013
|
+
* const userId = await hashUserId(createdAccountId);
|
|
1014
|
+
* await finished.enrich({ userId });
|
|
1015
|
+
* ```
|
|
1016
|
+
*/
|
|
1017
|
+
flowFinished(data, tags, experiments) {
|
|
1018
|
+
try {
|
|
1019
|
+
const { userId, identifier, ...dataOut } = data;
|
|
1020
|
+
const userReference = { userId, identifier };
|
|
1021
|
+
const targetEventId = uuidv7();
|
|
1022
|
+
const sessionId = this.sessionId;
|
|
1023
|
+
void this.track(AuthEventName.FlowFinished, dataOut, userReference, tags, void 0, void 0, experiments, {
|
|
1024
|
+
id: targetEventId,
|
|
1025
|
+
sessionId
|
|
1026
|
+
});
|
|
1027
|
+
return this.flowHandle(targetEventId, sessionId);
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
this.logger.warn("Failed to finish flow", error);
|
|
1030
|
+
return { enrich: async () => {
|
|
1031
|
+
} };
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
/** Emits `flow_enriched` against an explicit target, in the session that emitted the target. */
|
|
1035
|
+
flowHandle(targetEventId, sessionId) {
|
|
1036
|
+
return {
|
|
1037
|
+
enrich: async (user) => {
|
|
1038
|
+
try {
|
|
1039
|
+
await this.track(
|
|
1040
|
+
AuthEventName.FlowEnriched,
|
|
1041
|
+
{ targetEventId },
|
|
1042
|
+
{ ...user },
|
|
1043
|
+
void 0,
|
|
1044
|
+
void 0,
|
|
1045
|
+
void 0,
|
|
1046
|
+
void 0,
|
|
1047
|
+
{ sessionId }
|
|
1048
|
+
);
|
|
1049
|
+
} catch (error) {
|
|
1050
|
+
this.logger.warn("Failed to enrich flow", error);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Track when an in-progress flow is reset and restarted.
|
|
1057
|
+
*
|
|
1058
|
+
* @remarks
|
|
1059
|
+
* Use this when users abandon the current path and return to the beginning of the same flow,
|
|
1060
|
+
* for example after switching account/identifier and reopening the first step.
|
|
1061
|
+
*
|
|
1062
|
+
* @param data - Flow name being reset.
|
|
1063
|
+
* @param tags - Optional key-value tags for filtering and segmentation.
|
|
1064
|
+
*
|
|
1065
|
+
* @example
|
|
1066
|
+
* ```typescript
|
|
1067
|
+
* tracker.flowReset({flowName: "login"});
|
|
1068
|
+
* ```
|
|
1069
|
+
*/
|
|
1070
|
+
flowReset(data, tags, experiments) {
|
|
1071
|
+
void this.track(AuthEventName.FlowReset, data, void 0, tags, void 0, void 0, experiments);
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Track when a flow is considered finished because another flow finished it implicitly.
|
|
1075
|
+
*
|
|
1076
|
+
* @remarks
|
|
1077
|
+
* Use this for automatic completions where no separate explicit finish action happens in the
|
|
1078
|
+
* current flow. Set `flowName` to the auto-finished flow and `finishedByFlowName` to the flow
|
|
1079
|
+
* that caused it. Record identity with `setUser()` while the intended flow is still
|
|
1080
|
+
* current, before it is auto-finished.
|
|
1081
|
+
*
|
|
1082
|
+
* Legacy identity fields in `data` remain supported but are deprecated.
|
|
1083
|
+
*
|
|
1084
|
+
* @param data - Auto-finished flow, finishing flow, and deprecated user reference fields.
|
|
1085
|
+
* @param tags - Optional key-value tags for filtering and segmentation.
|
|
1086
|
+
*
|
|
1087
|
+
* @example
|
|
1088
|
+
* ```typescript
|
|
1089
|
+
* tracker.flowAutoFinished({
|
|
1090
|
+
* flowName: "signup",
|
|
1091
|
+
* finishedByFlowName: "login",
|
|
1092
|
+
* });
|
|
1093
|
+
* ```
|
|
1094
|
+
*/
|
|
1095
|
+
flowAutoFinished(data, tags, experiments) {
|
|
1096
|
+
const { userId, identifier, ...dataOut } = data;
|
|
1097
|
+
const userReference = { userId, identifier };
|
|
1098
|
+
void this.track(AuthEventName.FlowAutoFinished, dataOut, userReference, tags, void 0, void 0, experiments);
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Track when you present authentication method choices to the user.
|
|
1102
|
+
*
|
|
1103
|
+
* @remarks
|
|
1104
|
+
* Use this whenever a decision point is shown with a concrete method set, such as
|
|
1105
|
+
* identifier entry options (`d1`) or post-identifier options (`d3`). Set
|
|
1106
|
+
* `explicitDecisionValue` when the options are re-offered after a user action and you want
|
|
1107
|
+
* to capture what triggered that transition.
|
|
1108
|
+
*
|
|
1109
|
+
* @param data - Decision identifier, offered options, and optional transition reason.
|
|
1110
|
+
* @param tags - Optional key-value tags for filtering and segmentation.
|
|
1111
|
+
* @param experiments - Optional per-call experiment assignments.
|
|
1112
|
+
* @param options - Optional explicit event timestamp.
|
|
1113
|
+
*
|
|
1114
|
+
* @example
|
|
1115
|
+
* ```typescript
|
|
1116
|
+
* tracker.authMethodsDecisionStarted({
|
|
1117
|
+
* decisionName: "d3",
|
|
1118
|
+
* options: ["passkey", "social-google", "password", "reset-flow"],
|
|
1119
|
+
* });
|
|
1120
|
+
* ```
|
|
1121
|
+
*/
|
|
1122
|
+
authMethodsDecisionStarted(data, tags, experiments, options) {
|
|
1123
|
+
void this.track(
|
|
1124
|
+
AuthEventName.AuthMethodDecisionStarted,
|
|
1125
|
+
data,
|
|
1126
|
+
void 0,
|
|
1127
|
+
tags,
|
|
1128
|
+
void 0,
|
|
1129
|
+
options?.explicitTimestamp,
|
|
1130
|
+
experiments
|
|
1131
|
+
);
|
|
1132
|
+
}
|
|
1133
|
+
authMethodsDecisionFinished(data, tags, experiments) {
|
|
1134
|
+
void this.track(AuthEventName.AuthMethodDecisionFinished, data, void 0, tags, void 0, void 0, experiments);
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* Enqueue a "low" event (granular DOM/window/visualviewport/PWM signal) for the current session.
|
|
1138
|
+
*
|
|
1139
|
+
* @remarks
|
|
1140
|
+
* Low events are sent in the `lows` array of the events endpoint payload, alongside any
|
|
1141
|
+
* pending typed events. Blocked user agents are skipped silently.
|
|
1142
|
+
*
|
|
1143
|
+
* @internal
|
|
1144
|
+
*/
|
|
1145
|
+
enqueueLowEvent(low, capturedSessionId) {
|
|
1146
|
+
try {
|
|
1147
|
+
if (this.isTrackingBlocked()) {
|
|
1148
|
+
this.logger.debug(`Skipping low event "${low.lowType}" for blocked user agent.`);
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
this.queue.enqueueLow(
|
|
1152
|
+
{
|
|
1153
|
+
...low,
|
|
1154
|
+
captureSeq: low.captureSeq ?? reserveCaptureSeq(),
|
|
1155
|
+
captureVersion: 1,
|
|
1156
|
+
pageId: low.pageId ?? getCapturePageId()
|
|
1157
|
+
},
|
|
1158
|
+
capturedSessionId
|
|
1159
|
+
);
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
this.logger.error(`Failed to process low event "${low.lowType}" before enqueue`, error);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Record a diagnostic telemetry entry (a `level` + free-form `message`) for the current session.
|
|
1166
|
+
*
|
|
1167
|
+
* @remarks
|
|
1168
|
+
* Telemetry is delivered in the `telemetry` array of the events endpoint payload, tied to the same
|
|
1169
|
+
* session, and is never classified as an auth-flow event. By default a telemetry entry piggybacks
|
|
1170
|
+
* the next normal flush (it does not trigger one on its own); this is server-controlled. Collection
|
|
1171
|
+
* can be turned off server-side via the `telemetry` config flag. Blocked user agents are skipped.
|
|
1172
|
+
*
|
|
1173
|
+
* The message is truncated to {@link TELEMETRY_MESSAGE_MAX} characters. Never pass credentials or
|
|
1174
|
+
* PII — telemetry is for diagnostics only. Like all SDK entry points, this never throws.
|
|
1175
|
+
*/
|
|
1176
|
+
telemetry(level, message) {
|
|
1177
|
+
try {
|
|
1178
|
+
if (this.isTrackingBlocked()) {
|
|
1179
|
+
this.logger.debug("Skipping telemetry for blocked user agent.");
|
|
1180
|
+
return;
|
|
1181
|
+
}
|
|
1182
|
+
const text = typeof message === "string" ? message : String(message);
|
|
1183
|
+
if (text.length === 0) {
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
const entry = {
|
|
1187
|
+
id: uuidv7(),
|
|
1188
|
+
level,
|
|
1189
|
+
message: text.length > TELEMETRY_MESSAGE_MAX ? text.slice(0, TELEMETRY_MESSAGE_MAX) : text,
|
|
1190
|
+
ts: Date.now()
|
|
1191
|
+
};
|
|
1192
|
+
this.queue.enqueueTelemetry(entry);
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
this.logger.error("Failed to process telemetry before enqueue", error);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* Queue hook run right before an event batch is sent: a device info snapshot that no event carried
|
|
1199
|
+
* yet (typically the fast snapshot after a burst of events at page load, or the privateMode update)
|
|
1200
|
+
* rides the first event of this page in the batch that has none. Events of other pages (outbox
|
|
1201
|
+
* replays) are never touched. A snapshot no event can carry goes as the batch's request-level device
|
|
1202
|
+
* info instead (queue option `standaloneDeviceInfo`).
|
|
1203
|
+
*
|
|
1204
|
+
* Error situations:
|
|
1205
|
+
* - Any error: log "Failed to attach device info to batch" and send the batch unchanged
|
|
1206
|
+
*/
|
|
1207
|
+
attachUndeliveredDeviceInfo(events) {
|
|
1208
|
+
try {
|
|
1209
|
+
const manager = this.deviceInfoManager;
|
|
1210
|
+
if (!manager?.hasUndelivered()) {
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
const pageId = getCapturePageId();
|
|
1214
|
+
const target = events.find((event) => event.meta?.pageId === pageId && !event.deviceInfo);
|
|
1215
|
+
if (target) {
|
|
1216
|
+
target.deviceInfo = manager.takeUndelivered();
|
|
1217
|
+
}
|
|
1218
|
+
} catch (error) {
|
|
1219
|
+
this.logger.error("Failed to attach device info to batch", error);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* Escalate an internal SDK diagnostic to the telemetry stream (self-instrumentation). This is the
|
|
1224
|
+
* sink behind {@link Logger.reportTelemetry}; chosen internal failure sites route here so faults
|
|
1225
|
+
* that are otherwise only visible with `debug: true` become observable in the field.
|
|
1226
|
+
*
|
|
1227
|
+
* @remarks
|
|
1228
|
+
* Bounded and deduped per load (a persistent fault — blocked storage, a downed endpoint — cannot
|
|
1229
|
+
* flood the stream), re-entrancy-guarded so it can never recurse, and it never throws into the
|
|
1230
|
+
* host. Diagnostics raised before the queue exists (early boot) are buffered and replayed once the
|
|
1231
|
+
* queue is ready. Messages must be stable and low-cardinality (no raw error objects / PII).
|
|
1232
|
+
*/
|
|
1233
|
+
reportTelemetry(level, message) {
|
|
1234
|
+
if (this.telemetryReporting) {
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
this.telemetryReporting = true;
|
|
1238
|
+
try {
|
|
1239
|
+
if (this.reportedTelemetryKeys.has(message) || this.reportedTelemetryKeys.size >= MAX_SELF_TELEMETRY) {
|
|
1240
|
+
return;
|
|
1241
|
+
}
|
|
1242
|
+
this.reportedTelemetryKeys.add(message);
|
|
1243
|
+
if (!this.telemetryReady) {
|
|
1244
|
+
this.pendingSelfTelemetry.push({ level, message });
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
this.telemetry(level, message);
|
|
1248
|
+
} catch {
|
|
1249
|
+
} finally {
|
|
1250
|
+
this.telemetryReporting = false;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Synchronously flush any pending events and low events via beacon. Use during page-unload
|
|
1255
|
+
* style teardown where async flushing is unreliable.
|
|
1256
|
+
*
|
|
1257
|
+
* @param reason What triggered the flush; recorded as `meta.flushReason` on the batch. Defaults
|
|
1258
|
+
* to a direct call by the host app.
|
|
1259
|
+
*
|
|
1260
|
+
* @internal
|
|
1261
|
+
*/
|
|
1262
|
+
flushKeepalive(reason = "manual") {
|
|
1263
|
+
try {
|
|
1264
|
+
this.queue.flushKeepalive(reason);
|
|
1265
|
+
} catch (error) {
|
|
1266
|
+
this.logger.error("Failed to flush queue keepalive", error);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* Keepalive flush requested by a low-event tracker's `pagehide` teardown. Gated by the
|
|
1271
|
+
* server-controlled trigger switch `tlf` (boot-snapshot, default true = historical behavior):
|
|
1272
|
+
* disabling it server-side makes low-event delivery rely solely on the queue's own triggers.
|
|
1273
|
+
*
|
|
1274
|
+
* @internal
|
|
1275
|
+
*/
|
|
1276
|
+
lowEventFlushKeepalive() {
|
|
1277
|
+
if (!this.config.tlf) {
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
this.flushKeepalive("low-event-teardown");
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* Flush any pending events and release all resources (timers, event listeners).
|
|
1284
|
+
*
|
|
1285
|
+
* @remarks
|
|
1286
|
+
* After calling destroy, the tracker must not be used. Operation objects
|
|
1287
|
+
* returned by factory methods (e.g. `passwordLoginFullOperation`) that hold
|
|
1288
|
+
* DOM references must be destroyed separately by the caller.
|
|
1289
|
+
* The final flush is gated by the server-controlled trigger switch `td` (default true);
|
|
1290
|
+
* resources are released either way.
|
|
1291
|
+
*/
|
|
1292
|
+
async destroy() {
|
|
1293
|
+
this.bridge?.stop();
|
|
1294
|
+
this.configManager?.destroy();
|
|
1295
|
+
this.passwordManagerSampler?.destroy();
|
|
1296
|
+
this.windowObserver?.destroy();
|
|
1297
|
+
this.deviceInfoManager.destroy();
|
|
1298
|
+
if (this.config.td) {
|
|
1299
|
+
try {
|
|
1300
|
+
await this.queue.flush("destroy");
|
|
1301
|
+
} catch (error) {
|
|
1302
|
+
this.logger.error("Failed to flush queue during destroy", error);
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
this.queue.destroy();
|
|
1306
|
+
}
|
|
1307
|
+
// Session Management
|
|
1308
|
+
/**
|
|
1309
|
+
* Return the Observe session id this tracker is currently reporting under.
|
|
1310
|
+
*
|
|
1311
|
+
* @remarks
|
|
1312
|
+
* Use this to route a server-side event into the same session the browser reports to: read the id,
|
|
1313
|
+
* pass it to your own backend, and let the backend use it as the `sessionID` of its ingest call.
|
|
1314
|
+
* Reading it here is the supported path — the storage layout behind it is an implementation detail
|
|
1315
|
+
* that has already changed once (per-tab `sessionStorage` to the cross-tab continuity record).
|
|
1316
|
+
*
|
|
1317
|
+
* The value is **not stable for the lifetime of the page**. It changes on
|
|
1318
|
+
* {@link CorbadoTracker.resetSession}, when this tab adopts a continuity session another tab
|
|
1319
|
+
* rotated to, and when a failed bootstrap recovers. Read it at the moment you need it; never cache
|
|
1320
|
+
* it across a request.
|
|
1321
|
+
*
|
|
1322
|
+
* `undefined` means no session id could be established at all — an environment without Web Crypto,
|
|
1323
|
+
* where tracking is not working either. Skip the server-side event instead of sending an empty id:
|
|
1324
|
+
* the ingest API requires a UUID and would reject the batch.
|
|
1325
|
+
*
|
|
1326
|
+
* @returns The current session id, or `undefined` if none could be established.
|
|
1327
|
+
*
|
|
1328
|
+
* @example
|
|
1329
|
+
* ```typescript
|
|
1330
|
+
* const sessionId = tracker.getSessionId();
|
|
1331
|
+
* if (sessionId) {
|
|
1332
|
+
* await fetch("/api/checkout", {
|
|
1333
|
+
* method: "POST",
|
|
1334
|
+
* body: JSON.stringify({ ...payload, observeSessionId: sessionId }),
|
|
1335
|
+
* });
|
|
1336
|
+
* }
|
|
1337
|
+
* ```
|
|
1338
|
+
*/
|
|
1339
|
+
getSessionId() {
|
|
1340
|
+
if (!this.sessionId) {
|
|
1341
|
+
const recovered = this.resolveSession();
|
|
1342
|
+
if (recovered) {
|
|
1343
|
+
this.sessionId = recovered;
|
|
1344
|
+
this.queue.setSessionId(recovered);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
return this.sessionId || void 0;
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
export {
|
|
1351
|
+
CorbadoTrackerCore
|
|
1352
|
+
};
|