@didit-protocol/sdk-web 0.4.0 → 0.5.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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Didit SDK for Web v0.4.0
2
+ * Didit SDK for Web v0.5.1
3
3
  * (c) 2026 Didit
4
4
  * @license MIT
5
5
  */
@@ -9,197 +9,1008 @@
9
9
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.DiditSDK = {}));
10
10
  })(this, (function (exports) { 'use strict';
11
11
 
12
- const DEFAULT_CONFIG = {
13
- zIndex: 9999,
14
- showCloseButton: true,
15
- showExitConfirmation: true,
16
- loggingEnabled: false};
17
- const CSS_CLASSES = {
18
- overlay: "didit-modal-overlay",
19
- container: "didit-modal-container",
20
- iframe: "didit-verification-iframe",
21
- closeButton: "didit-close-button",
22
- loading: "didit-loading",
23
- confirmOverlay: "didit-confirm-overlay",
24
- confirmBox: "didit-confirm-box",
25
- embedded: "didit-embedded"
26
- };
27
- const SDK_VERSION = "0.4.0";
28
- /** The verification-URL query parameter each camera option is forwarded as. */
29
- const CAMERA_QUERY_PARAMS = {
30
- defaultDocumentCamera: "document_camera",
31
- defaultLivenessCamera: "liveness_camera",
32
- showDocumentCameraSwitchButton: "document_camera_switch",
33
- showLivenessCameraSwitchButton: "liveness_camera_switch"
34
- };
35
- const CAMERA_LENSES = ["front", "back"];
36
- const languages = [
37
- "ar",
38
- "bg",
39
- "bn",
40
- "ca",
41
- "cnr",
42
- "cs",
43
- "da",
44
- "de",
45
- "el",
46
- "en",
47
- "es",
48
- "et",
49
- "fa",
50
- "fi",
51
- "fr",
52
- "he",
53
- "hi",
54
- "hr",
55
- "hu",
56
- "hy",
57
- "id",
58
- "it",
59
- "ja",
60
- "ka",
61
- "ko",
62
- "lt",
63
- "lv",
64
- "mk",
65
- "mn",
66
- "ms",
67
- "nl",
68
- "no",
69
- "pl",
70
- "pt-BR",
71
- "pt",
72
- "ro",
73
- "ru",
74
- "sk",
75
- "sl",
76
- "so",
77
- "sr",
78
- "sv",
79
- "th",
80
- "tr",
81
- "uk",
82
- "uz",
83
- "vi",
84
- "zh-CN",
85
- "zh-TW",
86
- "zh",
87
- ];
88
-
89
- class SDKLogger {
90
- static get isEnabled() {
91
- return this._enabled;
92
- }
93
- static set isEnabled(value) {
94
- this._enabled = value;
12
+ /**
13
+ * Minimal self-contained port of the didit-fp-v2 device fingerprint used by the
14
+ * Didit verification frontend. It collects stable browser signals, hashes them
15
+ * with WebCrypto SHA-256 and persists a random device id in localStorage with a
16
+ * cookie fallback. The payload shape matches the didit-fp-v2 schema so the Didit
17
+ * backend middleware parses it identically to the verification flow:
18
+ *
19
+ * - headers: X-Didit-PID (persistent id) and X-Didit-FP-Hash (composite hash)
20
+ * - body: a top-level `fingerprint_v2` field carrying the full payload
21
+ */
22
+ const PERSISTENT_ID_STORAGE_KEY = "didit-pid-v1";
23
+ const PERSISTENT_ID_COOKIE_NAME = "didit_pid";
24
+ const PERSISTENT_ID_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365 * 2;
25
+ const PERSISTENT_ID_BYTE_LENGTH = 16;
26
+ const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
27
+ let memoryPersistentId = null;
28
+ let cachedPayload = null;
29
+ let pendingPayload = null;
30
+ let cachedPayloadPromise = null;
31
+ function bytesToBase64Url(bytes) {
32
+ let output = "";
33
+ let i = 0;
34
+ for (; i + 2 < bytes.length; i += 3) {
35
+ const triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
36
+ output += BASE64URL_ALPHABET[(triplet >> 18) & 0x3f];
37
+ output += BASE64URL_ALPHABET[(triplet >> 12) & 0x3f];
38
+ output += BASE64URL_ALPHABET[(triplet >> 6) & 0x3f];
39
+ output += BASE64URL_ALPHABET[triplet & 0x3f];
95
40
  }
96
- static log(...args) {
97
- if (this._enabled) {
98
- console.log("[DiditSDK]", ...args);
41
+ if (i < bytes.length) {
42
+ const remaining = bytes.length - i;
43
+ const a = bytes[i];
44
+ const b = remaining > 1 ? bytes[i + 1] : 0;
45
+ const triplet = (a << 16) | (b << 8);
46
+ output += BASE64URL_ALPHABET[(triplet >> 18) & 0x3f];
47
+ output += BASE64URL_ALPHABET[(triplet >> 12) & 0x3f];
48
+ if (remaining > 1) {
49
+ output += BASE64URL_ALPHABET[(triplet >> 6) & 0x3f];
99
50
  }
100
51
  }
101
- static warn(...args) {
102
- if (this._enabled) {
103
- console.warn("[DiditSDK]", ...args);
104
- }
52
+ return output;
53
+ }
54
+ function randomBytes(length) {
55
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
56
+ const buffer = new Uint8Array(length);
57
+ crypto.getRandomValues(buffer);
58
+ return buffer;
105
59
  }
106
- static error(...args) {
107
- if (this._enabled) {
108
- console.error("[DiditSDK]", ...args);
109
- }
60
+ const fallback = new Uint8Array(length);
61
+ for (let i = 0; i < length; i++) {
62
+ fallback[i] = Math.floor(Math.random() * 256);
110
63
  }
64
+ return fallback;
111
65
  }
112
- SDKLogger._enabled = false;
113
- function generateModalId() {
114
- return `didit-modal-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
66
+ function randomBase64Url(byteLength) {
67
+ return bytesToBase64Url(randomBytes(byteLength));
115
68
  }
116
- function isAllowedOrigin(origin, url) {
117
- try {
118
- const originURL = new URL(origin);
119
- const urlURL = new URL(url);
120
- return originURL.hostname.endsWith(".didit.me") || originURL.hostname === urlURL.hostname;
69
+ // SHA-256 truncated to the leading 128 bits, base64url-encoded (22 chars).
70
+ // Same construction as the didit-fp-v2 composite hash in the verification frontend.
71
+ async function sha256_128(input) {
72
+ if (typeof crypto === "undefined" || !crypto.subtle) {
73
+ throw new Error("WebCrypto SubtleCrypto is not available");
121
74
  }
122
- catch {
123
- return false;
75
+ const bytes = new TextEncoder().encode(input);
76
+ const view = new Uint8Array(bytes.byteLength);
77
+ view.set(bytes);
78
+ const digest = await crypto.subtle.digest("SHA-256", view.buffer);
79
+ return bytesToBase64Url(new Uint8Array(digest).slice(0, 16));
80
+ }
81
+ // FNV-1a 32-bit fallback hash, only used when WebCrypto is unavailable.
82
+ function fnv1a32(value) {
83
+ let hash = 0x811c9dc5;
84
+ for (let i = 0; i < value.length; i++) {
85
+ hash ^= value.charCodeAt(i);
86
+ hash = Math.imul(hash, 0x01000193);
124
87
  }
88
+ return (hash >>> 0).toString(16).padStart(8, "0");
125
89
  }
126
- function createVerificationError(type, customMessage) {
127
- const messages = {
128
- sessionExpired: "Your verification session has expired.",
129
- networkError: "A network error occurred. Please try again.",
130
- cameraAccessDenied: "Camera access is required for verification.",
131
- unknown: customMessage || "An unknown error occurred."
132
- };
133
- return {
134
- type,
135
- message: customMessage || messages[type]
136
- };
90
+ function stableStringify(value) {
91
+ if (value === null || value === undefined)
92
+ return JSON.stringify(value ?? null);
93
+ if (Array.isArray(value))
94
+ return `[${value.map((v) => stableStringify(v)).join(",")}]`;
95
+ if (typeof value === "object") {
96
+ const keys = Object.keys(value).sort();
97
+ const parts = keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`);
98
+ return `{${parts.join(",")}}`;
99
+ }
100
+ return JSON.stringify(value);
137
101
  }
138
- function isCameraLens(value) {
139
- return CAMERA_LENSES.includes(value);
102
+ function isValidPersistentId(value) {
103
+ return typeof value === "string" && /^[A-Za-z0-9_-]{20,32}$/.test(value);
140
104
  }
141
- const CAMERA_LENS_OPTIONS = ["defaultDocumentCamera", "defaultLivenessCamera"];
142
- const CAMERA_SWITCH_OPTIONS = ["showDocumentCameraSwitchButton", "showLivenessCameraSwitchButton"];
143
- /**
144
- * The URL the verification iframe loads: the integrator's URL with the
145
- * configuration options the hosted page reads from its query string.
146
- *
147
- * The camera options (the same four the native SDKs expose) become query
148
- * parameters: `defaultDocumentCamera` -> `document_camera=<lens>`,
149
- * `defaultLivenessCamera` -> `liveness_camera=<lens>`,
150
- * `showDocumentCameraSwitchButton` -> `document_camera_switch=true|false`,
151
- * `showLivenessCameraSwitchButton` -> `liveness_camera_switch=true|false`.
152
- * Each parameter is set (not appended) so the configuration wins over a value
153
- * already on the URL; existing query parameters and the hash are kept. A
154
- * value of the wrong shape is ignored with a warning rather than forwarded,
155
- * and a URL the browser cannot parse is returned as it came (the modal
156
- * reports it when it loads).
157
- */
158
- function buildVerificationUrl(url, configuration) {
159
- if (!configuration)
160
- return url;
161
- const params = [];
162
- for (const option of CAMERA_LENS_OPTIONS) {
163
- const value = configuration[option];
164
- if (value === undefined)
165
- continue;
166
- if (!isCameraLens(value)) {
167
- SDKLogger.warn(`Ignoring ${option}: expected "front" or "back", got`, value);
168
- continue;
169
- }
170
- params.push([CAMERA_QUERY_PARAMS[option], value]);
171
- }
172
- for (const option of CAMERA_SWITCH_OPTIONS) {
173
- const value = configuration[option];
174
- if (value === undefined)
175
- continue;
176
- if (typeof value !== "boolean") {
177
- SDKLogger.warn(`Ignoring ${option}: expected a boolean, got`, value);
178
- continue;
179
- }
180
- params.push([CAMERA_QUERY_PARAMS[option], value ? "true" : "false"]);
181
- }
182
- if (params.length === 0)
183
- return url;
105
+ function readLocalStorageId() {
184
106
  try {
185
- const parsed = new URL(url);
186
- params.forEach(([name, value]) => parsed.searchParams.set(name, value));
187
- return parsed.toString();
107
+ if (typeof localStorage === "undefined")
108
+ return null;
109
+ const value = localStorage.getItem(PERSISTENT_ID_STORAGE_KEY);
110
+ return isValidPersistentId(value) ? value : null;
188
111
  }
189
112
  catch {
190
- return url;
113
+ return null;
191
114
  }
192
115
  }
193
- function detectLanguageFromUrl(url) {
116
+ function writeLocalStorageId(id) {
194
117
  try {
195
- const { pathname } = new URL(url);
196
- const firstSegment = pathname.split("/").filter(Boolean)[0];
197
- if (firstSegment && languages.includes(firstSegment)) {
198
- return firstSegment;
199
- }
118
+ if (typeof localStorage === "undefined")
119
+ return;
120
+ localStorage.setItem(PERSISTENT_ID_STORAGE_KEY, id);
200
121
  }
201
122
  catch {
202
- // we get it from the browser
123
+ // Storage may be blocked (private mode, storage policies); cookie layer still applies.
124
+ }
125
+ }
126
+ function readCookieId() {
127
+ try {
128
+ if (typeof document === "undefined" || !document.cookie)
129
+ return null;
130
+ const prefix = `${PERSISTENT_ID_COOKIE_NAME}=`;
131
+ for (const part of document.cookie.split(";")) {
132
+ const trimmed = part.trim();
133
+ if (trimmed.startsWith(prefix)) {
134
+ const value = decodeURIComponent(trimmed.substring(prefix.length));
135
+ return isValidPersistentId(value) ? value : null;
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ }
144
+ function writeCookieId(id) {
145
+ try {
146
+ if (typeof document === "undefined")
147
+ return;
148
+ const isSecure = typeof location !== "undefined" && location.protocol === "https:";
149
+ const attributes = [
150
+ `${PERSISTENT_ID_COOKIE_NAME}=${encodeURIComponent(id)}`,
151
+ "Path=/",
152
+ `Max-Age=${PERSISTENT_ID_COOKIE_MAX_AGE_SECONDS}`,
153
+ "SameSite=Lax"
154
+ ];
155
+ if (isSecure)
156
+ attributes.push("Secure");
157
+ document.cookie = attributes.join("; ");
158
+ }
159
+ catch {
160
+ // Cookies may be blocked; localStorage layer still applies.
161
+ }
162
+ }
163
+ function loadOrCreatePersistentId() {
164
+ const fromLocalStorage = readLocalStorageId();
165
+ const fromCookie = readCookieId();
166
+ let id;
167
+ let sources;
168
+ let wasCreated = false;
169
+ if (fromLocalStorage) {
170
+ id = fromLocalStorage;
171
+ sources = fromCookie === fromLocalStorage ? ["localStorage", "cookie"] : ["localStorage"];
172
+ }
173
+ else if (fromCookie) {
174
+ id = fromCookie;
175
+ sources = ["cookie"];
176
+ }
177
+ else if (memoryPersistentId && isValidPersistentId(memoryPersistentId)) {
178
+ id = memoryPersistentId;
179
+ sources = ["memory"];
180
+ }
181
+ else {
182
+ id = randomBase64Url(PERSISTENT_ID_BYTE_LENGTH);
183
+ sources = ["fresh"];
184
+ wasCreated = true;
185
+ }
186
+ memoryPersistentId = id;
187
+ // Self-heal any layer that was missing or mismatched.
188
+ if (fromLocalStorage !== id)
189
+ writeLocalStorageId(id);
190
+ if (fromCookie !== id)
191
+ writeCookieId(id);
192
+ return { id, sources, wasCreated };
193
+ }
194
+ function collectNavigatorSignals() {
195
+ const nav = typeof navigator !== "undefined" ? navigator : null;
196
+ const scr = typeof screen !== "undefined" ? screen : null;
197
+ let timeZone = null;
198
+ try {
199
+ timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
200
+ }
201
+ catch {
202
+ timeZone = null;
203
+ }
204
+ const uaData = nav
205
+ ? nav
206
+ .userAgentData
207
+ : undefined;
208
+ return {
209
+ userAgent: nav?.userAgent ?? "",
210
+ platform: nav?.platform ?? null,
211
+ language: nav?.language ?? "",
212
+ languages: nav?.languages ? [...nav.languages] : [],
213
+ hardwareConcurrency: typeof nav?.hardwareConcurrency === "number" ? nav.hardwareConcurrency : null,
214
+ deviceMemory: (() => {
215
+ const memory = nav ? nav.deviceMemory : undefined;
216
+ return typeof memory === "number" ? memory : null;
217
+ })(),
218
+ maxTouchPoints: typeof nav?.maxTouchPoints === "number" ? nav.maxTouchPoints : null,
219
+ devicePixelRatio: typeof window !== "undefined" && typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : null,
220
+ screenWidth: typeof scr?.width === "number" ? scr.width : null,
221
+ screenHeight: typeof scr?.height === "number" ? scr.height : null,
222
+ colorDepth: typeof scr?.colorDepth === "number" ? scr.colorDepth : null,
223
+ timeZone,
224
+ uaDataPlatform: uaData?.platform ?? null,
225
+ uaDataMobile: typeof uaData?.mobile === "boolean" ? uaData.mobile : null,
226
+ uaDataBrands: uaData?.brands ? uaData.brands.map((entry) => `${entry.brand} ${entry.version}`) : []
227
+ };
228
+ }
229
+ function detectWebViewKind(userAgent) {
230
+ if (/;\s?wv\)/.test(userAgent) || /\bVersion\/[\d.]+\s+Chrome\/[\d.]+\s+Mobile\b/.test(userAgent)) {
231
+ return "android-webview";
232
+ }
233
+ if (/FBAN|FBAV|Instagram|Line\/|MicroMessenger|Snapchat|musical_ly|BytedanceWebview/i.test(userAgent)) {
234
+ return "in-app-browser";
235
+ }
236
+ if (/iPhone|iPad|iPod/.test(userAgent) && !/Safari\//.test(userAgent) && !/CriOS|FxiOS|EdgiOS/.test(userAgent)) {
237
+ return "ios-webview";
238
+ }
239
+ return "browser";
240
+ }
241
+ function detectBot(signals) {
242
+ const flags = [];
243
+ const userAgent = signals.navigator.userAgent;
244
+ if (typeof navigator !== "undefined" && navigator.webdriver) {
245
+ flags.push("webdriver");
246
+ }
247
+ if (/HeadlessChrome|PhantomJS|Selenium|puppeteer|playwright/i.test(userAgent)) {
248
+ flags.push("headless-ua");
249
+ }
250
+ if (signals.navigator.uaDataMobile === false && /Android|iPhone|iPad/i.test(userAgent)) {
251
+ flags.push("ua-mobile-mismatch");
252
+ }
253
+ return { score: Math.min(1, flags.length / 4), flags };
254
+ }
255
+ function canonicalizeSignals(signals) {
256
+ // Only drift-resistant fields, serialized with stable key order so the same
257
+ // device always produces the same composite hash.
258
+ const stable = {
259
+ platform: signals.platform,
260
+ navigator: {
261
+ ua: signals.navigator.userAgent,
262
+ platform: signals.navigator.platform,
263
+ lang: signals.navigator.language.split("-")[0],
264
+ languages: [...signals.navigator.languages].sort(),
265
+ concurrency: signals.navigator.hardwareConcurrency,
266
+ memory: signals.navigator.deviceMemory,
267
+ maxTouch: signals.navigator.maxTouchPoints,
268
+ dpr: signals.navigator.devicePixelRatio,
269
+ screen: [signals.navigator.screenWidth, signals.navigator.screenHeight],
270
+ colorDepth: signals.navigator.colorDepth,
271
+ timeZone: signals.navigator.timeZone,
272
+ uaDataPlatform: signals.navigator.uaDataPlatform,
273
+ uaDataBrands: signals.navigator.uaDataBrands
274
+ },
275
+ webview: signals.webview.kind
276
+ };
277
+ return stableStringify(stable);
278
+ }
279
+ async function computeCompositeHash(canonical) {
280
+ try {
281
+ return await sha256_128(canonical);
282
+ }
283
+ catch {
284
+ // Environments without WebCrypto (very old browsers) fall back to a stable FNV-1a pair.
285
+ return `fnv-${fnv1a32(canonical)}${fnv1a32(`${canonical}:fallback`)}`;
286
+ }
287
+ }
288
+ async function buildPayload() {
289
+ const persistent = loadOrCreatePersistentId();
290
+ const navigatorSignals = collectNavigatorSignals();
291
+ const signals = {
292
+ platform: "web",
293
+ navigator: navigatorSignals,
294
+ webview: { kind: detectWebViewKind(navigatorSignals.userAgent) }
295
+ };
296
+ const payload = {
297
+ version: 2,
298
+ schema: "didit-fp-v2",
299
+ platform: "web",
300
+ collectedAt: new Date().toISOString(),
301
+ persistentId: persistent.id,
302
+ persistentIdSources: persistent.sources,
303
+ persistentIdWasCreated: persistent.wasCreated,
304
+ signals,
305
+ bot: detectBot(signals),
306
+ compositeHash: ""
307
+ };
308
+ // Keep all synchronously collected context available during the native hash.
309
+ // An empty hash is omitted from headers, never replaced with a different identity.
310
+ pendingPayload = payload;
311
+ return { ...payload, compositeHash: await computeCompositeHash(canonicalizeSignals(signals)) };
312
+ }
313
+ function isBrowserEnvironment() {
314
+ return typeof window !== "undefined" && typeof navigator !== "undefined" && typeof document !== "undefined";
315
+ }
316
+ /**
317
+ * Collects the device fingerprint. Resolves to null outside a browser
318
+ * environment (SSR, Node, workers) so callers degrade to a fingerprint-less
319
+ * request instead of sending junk signals. Never intended to throw into the
320
+ * submit path: callers still guard with .catch(() => null).
321
+ */
322
+ async function getDeviceFingerprintPayload() {
323
+ if (!isBrowserEnvironment())
324
+ return null;
325
+ if (cachedPayload)
326
+ return cachedPayload;
327
+ if (!cachedPayloadPromise) {
328
+ cachedPayloadPromise = buildPayload().then((payload) => {
329
+ cachedPayload = payload;
330
+ return payload;
331
+ }, (error) => {
332
+ // Do not cache failures; a later call may succeed.
333
+ cachedPayloadPromise = null;
334
+ throw error;
335
+ });
336
+ }
337
+ return cachedPayloadPromise;
338
+ }
339
+ /** Internal exit snapshot: never waits for WebCrypto or changes the cached payload. */
340
+ function getAvailableDeviceFingerprintPayload() {
341
+ return cachedPayload ?? pendingPayload;
342
+ }
343
+ function buildFingerprintHeaders(payload) {
344
+ if (!payload)
345
+ return {};
346
+ const headers = { "X-Didit-FP-V2": "1" };
347
+ if (payload.persistentId)
348
+ headers["X-Didit-PID"] = payload.persistentId;
349
+ if (payload.compositeHash)
350
+ headers["X-Didit-FP-Hash"] = payload.compositeHash;
351
+ if (payload.signals.webview.kind)
352
+ headers["X-Didit-FP-Webview"] = payload.signals.webview.kind;
353
+ if (payload.bot.score)
354
+ headers["X-Didit-FP-Bot-Score"] = payload.bot.score.toFixed(2);
355
+ return headers;
356
+ }
357
+
358
+ const DEFAULT_EVENTS_BASE_URL = "https://verification.didit.me";
359
+ const BATCH_PATH = "/v1/events/batch/";
360
+ const MAX_BATCH_EVENTS = 500;
361
+ const MAX_RETRY_DELAY_MS = 60000;
362
+ // Browsers cap the bodies of every keepalive request a page has in flight at
363
+ // 64 KiB together; the allowance covers the envelope and the fingerprint.
364
+ const KEEPALIVE_BUDGET_BYTES = 64 * 1024;
365
+ // The server's backpressure contract (monitoring_event_schemas.py): these are
366
+ // never dropped, and the low-value ones go first when the queue is full.
367
+ const NEVER_DROPPED = /^(security|payment|dispute|responsible_gambling)\.|^gameplay\.(bet_placed|bet_settled|p2p_settlement)$/;
368
+ const LOW_VALUE = /^session\.(page_view|sdk_heartbeat|sdk_loaded|device_seen|bot_signal_observed)$|^bonus\.promotion_viewed$|^affiliate\.referral_clicked$/;
369
+ const PRIORITY_NEVER_DROPPED = 2;
370
+ /**
371
+ * Typed error for events Didit refused or the SDK had to drop. Thrown by
372
+ * submitEvent for a missing token or event, otherwise delivered to the
373
+ * configured onError and in the flush results.
374
+ */
375
+ class DiditEventError extends Error {
376
+ constructor(type, message, options) {
377
+ super(message);
378
+ this.name = "DiditEventError";
379
+ this.type = type;
380
+ this.status = options?.status;
381
+ this.eventIds = options?.eventIds ?? [];
382
+ this.errors = options?.errors;
383
+ }
384
+ }
385
+ const DEFAULT_SETTINGS = {
386
+ baseUrl: DEFAULT_EVENTS_BASE_URL,
387
+ batchSize: 25,
388
+ flushIntervalMs: 5000,
389
+ maxQueueSize: 1000
390
+ };
391
+ let settings = { ...DEFAULT_SETTINGS };
392
+ let queue = [];
393
+ let timer;
394
+ let failures = 0;
395
+ let flushing = 0;
396
+ let chain = Promise.resolve();
397
+ let listening = false;
398
+ let exiting = false;
399
+ let keepaliveBytes = 0;
400
+ function isRecord(value) {
401
+ return value !== null && typeof value === "object" && !Array.isArray(value);
402
+ }
403
+ function compact$1(record) {
404
+ return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));
405
+ }
406
+ function browserTimeZone() {
407
+ try {
408
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
409
+ }
410
+ catch {
411
+ return undefined;
412
+ }
413
+ }
414
+ function newEventId() {
415
+ // randomUUID only exists in secure contexts; plain-http pages get 128 random bits instead.
416
+ return typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
417
+ ? crypto.randomUUID()
418
+ : randomBase64Url(16);
419
+ }
420
+ /** Maps the SDK-friendly camelCase event onto the snake_case wire contract of /v1/events/. */
421
+ function buildEventRequestBody(event, eventId) {
422
+ const { session, transactionContext, subject, occurredAt } = event;
423
+ return compact$1({
424
+ event_id: eventId,
425
+ event_category: event.category,
426
+ action_type: event.actionType,
427
+ occurred_at: occurredAt instanceof Date ? occurredAt.toISOString() : occurredAt ?? new Date().toISOString(),
428
+ time_zone: event.timeZone ?? browserTimeZone(),
429
+ subject: subject &&
430
+ compact$1({ full_name: subject.fullName, email: subject.email, phone: subject.phone, country: subject.country }),
431
+ business: event.business,
432
+ session: session &&
433
+ compact$1({
434
+ session_id: session.sessionId,
435
+ sequence: session.sequence,
436
+ page_url: session.pageUrl,
437
+ referrer: session.referrer
438
+ }),
439
+ transaction_context: transactionContext &&
440
+ compact$1({
441
+ amount: transactionContext.amount,
442
+ currency: transactionContext.currency,
443
+ direction: transactionContext.direction,
444
+ payment_reference_id: transactionContext.paymentReferenceId
445
+ }),
446
+ payload: event.payload,
447
+ custom_values: event.customValues
448
+ });
449
+ }
450
+ function report(error) {
451
+ try {
452
+ settings.onError?.(error);
453
+ }
454
+ catch {
455
+ // An integrator callback must never break delivery of the other events.
456
+ }
457
+ }
458
+ function waiting() {
459
+ return queue.filter((entry) => !entry.sending);
460
+ }
461
+ function schedule(delayMs) {
462
+ if (timer !== undefined)
463
+ return;
464
+ timer = setTimeout(() => {
465
+ timer = undefined;
466
+ flush().catch(() => undefined);
467
+ }, delayMs);
468
+ }
469
+ function clearTimer() {
470
+ if (timer !== undefined)
471
+ clearTimeout(timer);
472
+ timer = undefined;
473
+ }
474
+ function scheduleWaiting() {
475
+ if (flushing || !waiting().length)
476
+ return;
477
+ schedule(failures ? Math.min(Math.max(1000, settings.flushIntervalMs) * 2 ** failures, MAX_RETRY_DELAY_MS) : settings.flushIntervalMs);
478
+ }
479
+ function enqueue(entry) {
480
+ let victim;
481
+ if (queue.length >= settings.maxQueueSize) {
482
+ // The oldest waiting event of the lowest priority goes, or the new one when it ranks lower still.
483
+ for (const queued of waiting()) {
484
+ if (!victim || queued.priority < victim.priority)
485
+ victim = queued;
486
+ }
487
+ if (!victim || entry.priority < victim.priority)
488
+ victim = entry;
489
+ if (victim.priority === PRIORITY_NEVER_DROPPED)
490
+ victim = undefined;
491
+ }
492
+ if (victim && victim !== entry)
493
+ queue.splice(queue.indexOf(victim), 1);
494
+ if (victim !== entry)
495
+ queue.push(entry);
496
+ if (victim) {
497
+ report(new DiditEventError("dropped", "The event queue is full, so the event was dropped before it was sent.", {
498
+ eventIds: [victim.id]
499
+ }));
500
+ }
501
+ }
502
+ /** The next waiting events that share a token and endpoint, oldest first, within an optional byte budget. */
503
+ function nextBatch(budgetBytes = Infinity, envelopeBytes = 0) {
504
+ const batch = [];
505
+ let bytes = envelopeBytes;
506
+ for (const entry of queue) {
507
+ if (batch.length === settings.batchSize)
508
+ break;
509
+ if (entry.sending || bytes + entry.bytes + (batch.length ? 1 : 0) > budgetBytes)
510
+ continue;
511
+ if (batch.length && (entry.token !== batch[0].token || entry.url !== batch[0].url))
512
+ continue;
513
+ bytes += entry.bytes + (batch.length ? 1 : 0);
514
+ batch.push(entry);
515
+ }
516
+ return batch;
517
+ }
518
+ function readDetail(body) {
519
+ return isRecord(body) && typeof body.detail === "string" ? body.detail : undefined;
520
+ }
521
+ /** Classifies a refused batch: every event in it shares the outcome. */
522
+ function classifyEventError(status, body, eventIds) {
523
+ const detail = readDetail(body);
524
+ const code = isRecord(body) && typeof body.code === "string" ? body.code : "";
525
+ let type = "validation";
526
+ if (code === "event_monitoring_disabled") {
527
+ type = "monitoring_disabled";
528
+ }
529
+ else if (status === 401 || status === 403) {
530
+ type = /expired/i.test(`${detail} ${code}`) ? "expired_token" : "invalid_token";
531
+ }
532
+ return new DiditEventError(type, detail ?? `Didit refused the events with status ${status}.`, {
533
+ status,
534
+ eventIds,
535
+ errors: type === "validation" && isRecord(body) ? body : undefined
536
+ });
537
+ }
538
+ function isTransient(status) {
539
+ return status === 408 || status === 429 || status >= 500;
540
+ }
541
+ async function readJson(response) {
542
+ try {
543
+ return await response.json();
544
+ }
545
+ catch {
546
+ return null;
547
+ }
548
+ }
549
+ function byteLength(json) {
550
+ return encodeURIComponent(json).replace(/%[\dA-F]{2}/g, "-").length;
551
+ }
552
+ function batchBody(batch, fingerprint) {
553
+ const fingerprintJson = fingerprint ? `,"fingerprint_v2":${JSON.stringify(fingerprint)}` : "";
554
+ return `{"events":[${batch.map((entry) => entry.json).join(",")}]${fingerprintJson}}`;
555
+ }
556
+ /**
557
+ * Sends one batch and settles its events. Returns false when the batch has to
558
+ * be retried (network error, timeout, rate limit, 5xx, unreadable answer): the
559
+ * events stay queued with the same ids, so a batch the server already stored
560
+ * comes back as "replayed" instead of being stored twice.
561
+ */
562
+ async function send(batch, result, fingerprint, keepalive = false) {
563
+ const bodyJson = batchBody(batch, fingerprint);
564
+ const reservedBytes = keepalive ? byteLength(bodyJson) : 0;
565
+ const settled = new Set();
566
+ const errors = [];
567
+ const reject = (entry, error) => {
568
+ result.results.push({ eventId: entry.id, outcome: "rejected", error });
569
+ result.rejectedCount++;
570
+ settled.add(entry);
571
+ };
572
+ for (const entry of batch)
573
+ entry.sending = true;
574
+ keepaliveBytes += reservedBytes;
575
+ try {
576
+ const response = await fetch(batch[0].url, {
577
+ method: "POST",
578
+ redirect: "error",
579
+ keepalive,
580
+ headers: {
581
+ "Content-Type": "application/json",
582
+ "X-Monitoring-Token": batch[0].token,
583
+ ...buildFingerprintHeaders(fingerprint)
584
+ },
585
+ body: bodyJson
586
+ });
587
+ const body = await readJson(response);
588
+ if (isTransient(response.status) || !isRecord(body))
589
+ return false;
590
+ if (!response.ok) {
591
+ const error = classifyEventError(response.status, body, batch.map((entry) => entry.id));
592
+ for (const entry of batch)
593
+ reject(entry, error);
594
+ errors.push(error);
595
+ return true;
596
+ }
597
+ const answers = isRecord(body) && Array.isArray(body.results) ? body.results : [];
598
+ batch.forEach((entry, index) => {
599
+ const matches = answers.filter((item) => isRecord(item) && item.index === index);
600
+ const answer = matches[0];
601
+ if (matches.length !== 1 || !isRecord(answer))
602
+ return;
603
+ if (answer.outcome === "accepted" || answer.outcome === "replayed") {
604
+ if (typeof answer.event_uuid !== "string" || !answer.event_uuid)
605
+ return;
606
+ const eventResult = { eventId: entry.id, outcome: answer.outcome, eventUuid: answer.event_uuid };
607
+ if (typeof answer.status === "string")
608
+ eventResult.status = answer.status;
609
+ if (typeof answer.score === "number" || answer.score === null)
610
+ eventResult.score = answer.score;
611
+ result.results.push(eventResult);
612
+ result[answer.outcome === "accepted" ? "acceptedCount" : "replayedCount"]++;
613
+ settled.add(entry);
614
+ }
615
+ else if (answer.outcome === "rejected" && isRecord(answer.errors)) {
616
+ const error = new DiditEventError("validation", "Didit rejected the event; see errors for the details.", {
617
+ status: response.status,
618
+ eventIds: [entry.id],
619
+ errors: answer.errors
620
+ });
621
+ reject(entry, error);
622
+ errors.push(error);
623
+ }
624
+ });
625
+ // An answer that does not cover every event is retried like a network error.
626
+ return settled.size === batch.length;
627
+ }
628
+ catch {
629
+ return false;
630
+ }
631
+ finally {
632
+ keepaliveBytes -= reservedBytes;
633
+ queue = queue.filter((entry) => !settled.has(entry));
634
+ for (const entry of batch)
635
+ entry.sending = false;
636
+ failures = settled.size === batch.length ? 0 : failures + 1;
637
+ if (keepalive)
638
+ scheduleWaiting();
639
+ errors.forEach(report);
640
+ }
641
+ }
642
+ function emptyResult() {
643
+ return { acceptedCount: 0, replayedCount: 0, rejectedCount: 0, pendingCount: 0, results: [] };
644
+ }
645
+ async function drain() {
646
+ const result = emptyResult();
647
+ const fingerprint = await getDeviceFingerprintPayload().catch(() => null);
648
+ clearTimer();
649
+ let batch;
650
+ while ((batch = nextBatch()).length) {
651
+ if (!(await send(batch, result, fingerprint)))
652
+ break;
653
+ }
654
+ result.pendingCount = queue.length;
655
+ return result;
656
+ }
657
+ /**
658
+ * Sends what is still waiting while the page is being hidden or unloaded.
659
+ *
660
+ * sendBeacon cannot carry the X-Monitoring-Token header the events lane reads
661
+ * the credential from, so this uses fetch with keepalive, the same browser
662
+ * mechanism (the request outlives the page, within a 64 KiB budget) with
663
+ * headers. The batches go out in parallel: there is no time left to wait for
664
+ * one answer before sending the next.
665
+ */
666
+ async function drainOnExit() {
667
+ if (exiting)
668
+ return;
669
+ exiting = true;
670
+ clearTimer();
671
+ try {
672
+ // Start fetch inside the lifecycle handler. Awaiting even an in-progress
673
+ // hash can leave the request unissued when this document is discarded.
674
+ const fingerprint = getAvailableDeviceFingerprintPayload();
675
+ const envelopeBytes = byteLength(batchBody([], fingerprint));
676
+ let batch;
677
+ while ((batch = nextBatch(KEEPALIVE_BUDGET_BYTES - keepaliveBytes, envelopeBytes)).length) {
678
+ send(batch, emptyResult(), fingerprint, true).catch(() => undefined);
679
+ }
680
+ }
681
+ finally {
682
+ exiting = false;
683
+ // What did not fit goes out on the normal timer if the page comes back.
684
+ scheduleWaiting();
685
+ }
686
+ }
687
+ function sendOnExit() {
688
+ drainOnExit().catch(() => undefined);
689
+ }
690
+ function onVisibilityChange() {
691
+ if (document.visibilityState === "hidden")
692
+ sendOnExit();
693
+ }
694
+ function listen() {
695
+ if (listening || typeof window === "undefined" || typeof document === "undefined")
696
+ return;
697
+ listening = true;
698
+ window.addEventListener("pagehide", sendOnExit);
699
+ document.addEventListener("visibilitychange", onVisibilityChange);
700
+ }
701
+ /**
702
+ * Tunes the event queue. Call it once, before or after the first submitEvent;
703
+ * fields you leave out keep their current value.
704
+ */
705
+ function configureEvents(configuration) {
706
+ const next = { ...settings, ...compact$1({ ...configuration }) };
707
+ next.baseUrl = next.baseUrl.replace(/\/+$/, "");
708
+ next.batchSize = Math.min(Math.max(1, Math.floor(next.batchSize)), MAX_BATCH_EVENTS);
709
+ next.flushIntervalMs = Math.max(0, next.flushIntervalMs);
710
+ next.maxQueueSize = Math.max(1, Math.floor(next.maxQueueSize));
711
+ settings = next;
712
+ }
713
+ /**
714
+ * Queues an end-user event for Didit's event monitoring and returns its id.
715
+ *
716
+ * Events are sent in batches to POST /v1/events/batch/ with the
717
+ * X-Monitoring-Token header: as soon as `batchSize` events are waiting, after
718
+ * `flushIntervalMs`, and when the page is hidden or closed. The device
719
+ * fingerprint is attached to every batch. Each event keeps the token it was
720
+ * submitted with, so events from before and after a sign-in never mix people.
721
+ *
722
+ * @throws {DiditEventError} "invalid_token" without a monitoringToken,
723
+ * "validation" without an event category and action type, "network" when the
724
+ * environment has no fetch.
725
+ */
726
+ function submitEvent(options) {
727
+ const token = options?.monitoringToken;
728
+ const event = options?.event;
729
+ if (!token || typeof token !== "string") {
730
+ throw new DiditEventError("invalid_token", "monitoringToken is required.");
731
+ }
732
+ if (!isRecord(event) || !event.category || typeof event.actionType !== "string" || !event.actionType.trim()) {
733
+ throw new DiditEventError("validation", "event.category and event.actionType are required.");
734
+ }
735
+ if (event.occurredAt instanceof Date && Number.isNaN(event.occurredAt.getTime())) {
736
+ throw new DiditEventError("validation", "event.occurredAt must be a valid date.");
737
+ }
738
+ if (typeof fetch !== "function") {
739
+ throw new DiditEventError("network", "fetch is not available in this environment.");
740
+ }
741
+ const eventId = event.eventId || newEventId();
742
+ const json = JSON.stringify(buildEventRequestBody(event, eventId));
743
+ const kind = `${event.category}.${event.actionType}`;
744
+ enqueue({
745
+ id: eventId,
746
+ json,
747
+ // UTF-8 length; JSON.stringify never leaves a lone surrogate for encodeURIComponent to reject.
748
+ bytes: byteLength(json),
749
+ token,
750
+ url: `${(options.baseUrl ?? settings.baseUrl).replace(/\/+$/, "")}${BATCH_PATH}`,
751
+ priority: NEVER_DROPPED.test(kind) ? PRIORITY_NEVER_DROPPED : LOW_VALUE.test(kind) ? 0 : 1,
752
+ sending: false
753
+ });
754
+ listen();
755
+ // Collect synchronous context now; exits can use it while the hash is pending.
756
+ getDeviceFingerprintPayload().catch(() => null);
757
+ if (!flushing && !failures && waiting().length >= settings.batchSize) {
758
+ flush().catch(() => undefined);
759
+ }
760
+ else {
761
+ scheduleWaiting();
762
+ }
763
+ return eventId;
764
+ }
765
+ /**
766
+ * Sends every waiting event now. Resolves with what Didit did with each event
767
+ * once the queue is empty, or with `pendingCount` above zero when the network
768
+ * failed (those events are retried automatically). Never rejects.
769
+ */
770
+ function flush() {
771
+ flushing++;
772
+ const run = chain
773
+ .then(drain)
774
+ .catch(() => ({ ...emptyResult(), pendingCount: queue.length }))
775
+ .finally(() => {
776
+ flushing--;
777
+ scheduleWaiting();
778
+ });
779
+ chain = run;
780
+ return run;
781
+ }
782
+
783
+ const DEFAULT_CONFIG = {
784
+ zIndex: 9999,
785
+ showCloseButton: true,
786
+ showExitConfirmation: true,
787
+ loggingEnabled: false};
788
+ const CSS_CLASSES = {
789
+ overlay: "didit-modal-overlay",
790
+ container: "didit-modal-container",
791
+ iframe: "didit-verification-iframe",
792
+ closeButton: "didit-close-button",
793
+ closeIcon: "didit-close-icon",
794
+ closeIconLegacy: "didit-close-icon-legacy",
795
+ flowSized: "didit-flow-sized",
796
+ loading: "didit-loading",
797
+ confirmOverlay: "didit-confirm-overlay",
798
+ confirmBox: "didit-confirm-box",
799
+ embedded: "didit-embedded"
800
+ };
801
+ const SDK_VERSION = "0.5.1";
802
+ /**
803
+ * The permissions the verification iframe gets, in a modal and embedded:
804
+ * camera and microphone for capture, clipboard-write for the flow's copy
805
+ * buttons, and digital-credentials-get so the flow can ask a digital ID wallet
806
+ * (Google Wallet) through the W3C Digital Credentials API from inside the iframe.
807
+ */
808
+ const IFRAME_ALLOW = "camera; microphone; fullscreen; autoplay; encrypted-media; geolocation; clipboard-write; digital-credentials-get";
809
+ /** The verification-URL query parameter each camera option is forwarded as. */
810
+ const CAMERA_QUERY_PARAMS = {
811
+ defaultDocumentCamera: "document_camera",
812
+ defaultLivenessCamera: "liveness_camera",
813
+ showDocumentCameraSwitchButton: "document_camera_switch",
814
+ showLivenessCameraSwitchButton: "liveness_camera_switch"
815
+ };
816
+ const CAMERA_LENSES = ["front", "back"];
817
+ /**
818
+ * The verification-URL query parameters that tell the hosted flow how the SDK
819
+ * presents it: `sdk_presentation=modal|embedded` and, in a modal,
820
+ * `sdk_close_button=true|false` (whether the SDK draws its close button over
821
+ * the flow's top bar).
822
+ */
823
+ const PRESENTATION_QUERY_PARAMS = {
824
+ presentation: "sdk_presentation",
825
+ closeButton: "sdk_close_button"
826
+ };
827
+ /**
828
+ * Posted by the hosted flow when it lays itself out for the modal, with
829
+ * `data: { contentHeight, colorScheme?, dir? }`. The modal then grows to the
830
+ * handoff card on a computer and follows the content height in a narrow
831
+ * window. Handled by the modal and never delivered to `onEvent`.
832
+ */
833
+ const LAYOUT_MESSAGE_TYPE = "didit:layout";
834
+ /** Languages the hosted flow lays out right to left. */
835
+ const RTL_LANGUAGES = ["ar", "fa", "he"];
836
+ const languages = [
837
+ "ar",
838
+ "bg",
839
+ "bn",
840
+ "ca",
841
+ "cnr",
842
+ "cs",
843
+ "da",
844
+ "de",
845
+ "el",
846
+ "en",
847
+ "es",
848
+ "et",
849
+ "fa",
850
+ "fi",
851
+ "fr",
852
+ "he",
853
+ "hi",
854
+ "hr",
855
+ "hu",
856
+ "hy",
857
+ "id",
858
+ "it",
859
+ "ja",
860
+ "ka",
861
+ "ko",
862
+ "lt",
863
+ "lv",
864
+ "mk",
865
+ "mn",
866
+ "ms",
867
+ "nl",
868
+ "no",
869
+ "pl",
870
+ "pt-BR",
871
+ "pt",
872
+ "ro",
873
+ "ru",
874
+ "sk",
875
+ "sl",
876
+ "so",
877
+ "sr",
878
+ "sv",
879
+ "th",
880
+ "tr",
881
+ "uk",
882
+ "uz",
883
+ "vi",
884
+ "zh-CN",
885
+ "zh-TW",
886
+ "zh",
887
+ ];
888
+
889
+ class SDKLogger {
890
+ static get isEnabled() {
891
+ return this._enabled;
892
+ }
893
+ static set isEnabled(value) {
894
+ this._enabled = value;
895
+ }
896
+ static log(...args) {
897
+ if (this._enabled) {
898
+ console.log("[DiditSDK]", ...args);
899
+ }
900
+ }
901
+ static warn(...args) {
902
+ if (this._enabled) {
903
+ console.warn("[DiditSDK]", ...args);
904
+ }
905
+ }
906
+ static error(...args) {
907
+ if (this._enabled) {
908
+ console.error("[DiditSDK]", ...args);
909
+ }
910
+ }
911
+ }
912
+ SDKLogger._enabled = false;
913
+ function generateModalId() {
914
+ return `didit-modal-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
915
+ }
916
+ function isAllowedOrigin(origin, url) {
917
+ try {
918
+ const originURL = new URL(origin);
919
+ const urlURL = new URL(url);
920
+ return originURL.hostname.endsWith(".didit.me") || originURL.hostname === urlURL.hostname;
921
+ }
922
+ catch {
923
+ return false;
924
+ }
925
+ }
926
+ function createVerificationError(type, customMessage) {
927
+ const messages = {
928
+ sessionExpired: "Your verification session has expired.",
929
+ networkError: "A network error occurred. Please try again.",
930
+ cameraAccessDenied: "Camera access is required for verification.",
931
+ unknown: customMessage || "An unknown error occurred."
932
+ };
933
+ return {
934
+ type,
935
+ message: customMessage || messages[type]
936
+ };
937
+ }
938
+ function isCameraLens(value) {
939
+ return CAMERA_LENSES.includes(value);
940
+ }
941
+ const CAMERA_LENS_OPTIONS = ["defaultDocumentCamera", "defaultLivenessCamera"];
942
+ const CAMERA_SWITCH_OPTIONS = ["showDocumentCameraSwitchButton", "showLivenessCameraSwitchButton"];
943
+ /**
944
+ * The URL the verification iframe loads: the integrator's URL with the
945
+ * configuration options the hosted page reads from its query string.
946
+ *
947
+ * The camera options (the same four the native SDKs expose) become query
948
+ * parameters: `defaultDocumentCamera` -> `document_camera=<lens>`,
949
+ * `defaultLivenessCamera` -> `liveness_camera=<lens>`,
950
+ * `showDocumentCameraSwitchButton` -> `document_camera_switch=true|false`,
951
+ * `showLivenessCameraSwitchButton` -> `liveness_camera_switch=true|false`.
952
+ * How the SDK presents the flow is always added: `sdk_presentation=modal|embedded`
953
+ * and, in a modal, `sdk_close_button=true|false`.
954
+ * Each parameter is set (not appended) so the configuration wins over a value
955
+ * already on the URL; existing query parameters and the hash are kept. A
956
+ * value of the wrong shape is ignored with a warning rather than forwarded,
957
+ * and a URL the browser cannot parse is returned as it came (the modal
958
+ * reports it when it loads).
959
+ */
960
+ function buildVerificationUrl(url, configuration = {}) {
961
+ const params = presentationParams(configuration);
962
+ for (const option of CAMERA_LENS_OPTIONS) {
963
+ const value = configuration[option];
964
+ if (value === undefined)
965
+ continue;
966
+ if (!isCameraLens(value)) {
967
+ SDKLogger.warn(`Ignoring ${option}: expected "front" or "back", got`, value);
968
+ continue;
969
+ }
970
+ params.push([CAMERA_QUERY_PARAMS[option], value]);
971
+ }
972
+ for (const option of CAMERA_SWITCH_OPTIONS) {
973
+ const value = configuration[option];
974
+ if (value === undefined)
975
+ continue;
976
+ if (typeof value !== "boolean") {
977
+ SDKLogger.warn(`Ignoring ${option}: expected a boolean, got`, value);
978
+ continue;
979
+ }
980
+ params.push([CAMERA_QUERY_PARAMS[option], value ? "true" : "false"]);
981
+ }
982
+ try {
983
+ const parsed = new URL(url);
984
+ params.forEach(([name, value]) => parsed.searchParams.set(name, value));
985
+ return parsed.toString();
986
+ }
987
+ catch {
988
+ return url;
989
+ }
990
+ }
991
+ function presentationParams(configuration) {
992
+ if (configuration.embedded) {
993
+ return [[PRESENTATION_QUERY_PARAMS.presentation, "embedded"]];
994
+ }
995
+ const closeButton = configuration.showCloseButton ?? DEFAULT_CONFIG.showCloseButton;
996
+ return [
997
+ [PRESENTATION_QUERY_PARAMS.presentation, "modal"],
998
+ [PRESENTATION_QUERY_PARAMS.closeButton, closeButton ? "true" : "false"]
999
+ ];
1000
+ }
1001
+ function isRtlLanguage(language) {
1002
+ return RTL_LANGUAGES.includes(language.split("-")[0]);
1003
+ }
1004
+ function detectLanguageFromUrl(url) {
1005
+ try {
1006
+ const { pathname } = new URL(url);
1007
+ const firstSegment = pathname.split("/").filter(Boolean)[0];
1008
+ if (firstSegment && languages.includes(firstSegment)) {
1009
+ return firstSegment;
1010
+ }
1011
+ }
1012
+ catch {
1013
+ // we get it from the browser
203
1014
  }
204
1015
  const browserLang = navigator.language;
205
1016
  if (languages.includes(browserLang))
@@ -661,8 +1472,11 @@
661
1472
  this.iframe = null;
662
1473
  this.loadingEl = null;
663
1474
  this.confirmOverlay = null;
1475
+ this.confirmationTrigger = null;
664
1476
  this.boundHandleMessage = null;
665
1477
  this.boundHandleKeydown = null;
1478
+ this.boundHandleFocusChange = null;
1479
+ this.confirmationFocusTimeout = null;
666
1480
  this.embedded = false;
667
1481
  this.embeddedContainer = null;
668
1482
  this.language = "en";
@@ -822,6 +1636,7 @@
822
1636
  transform: scale(0.95);
823
1637
  transition: transform 0.15s ease-out;
824
1638
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
1639
+ outline: none;
825
1640
  }
826
1641
 
827
1642
  .${CSS_CLASSES.confirmOverlay}.active .${CSS_CLASSES.confirmBox} {
@@ -849,7 +1664,7 @@
849
1664
  gap: 1rem;
850
1665
  }
851
1666
 
852
- .didit-confirm-actions button {
1667
+ .didit-confirm-actions [data-action="continue"] {
853
1668
  background: #2563eb;
854
1669
  color: #fff;
855
1670
  border: none;
@@ -861,11 +1676,16 @@
861
1676
  transition: background 0.15s ease;
862
1677
  }
863
1678
 
864
- .didit-confirm-actions button:hover {
1679
+ .didit-confirm-actions [data-action="continue"]:hover {
865
1680
  background: #1d4ed8;
866
1681
  }
867
1682
 
868
- .didit-confirm-actions span {
1683
+ .didit-confirm-actions [data-action="exit"] {
1684
+ background: transparent;
1685
+ border: none;
1686
+ font-family: inherit;
1687
+ font-weight: inherit;
1688
+ line-height: inherit;
869
1689
  color: #666;
870
1690
  font-size: 0.875rem;
871
1691
  cursor: pointer;
@@ -873,10 +1693,15 @@
873
1693
  transition: color 0.15s ease;
874
1694
  }
875
1695
 
876
- .didit-confirm-actions span:hover {
1696
+ .didit-confirm-actions [data-action="exit"]:hover {
877
1697
  color: #1a1a2e;
878
1698
  }
879
1699
 
1700
+ .didit-confirm-actions button:focus-visible {
1701
+ outline: 2px solid #2567ff;
1702
+ outline-offset: 2px;
1703
+ }
1704
+
880
1705
  @media (max-width: 540px) {
881
1706
  .${CSS_CLASSES.overlay} {
882
1707
  padding: 0;
@@ -885,673 +1710,601 @@
885
1710
  .${CSS_CLASSES.container} {
886
1711
  max-width: 100%;
887
1712
  max-height: 100vh;
888
- max-height: 100dvh;
889
- border-radius: 0;
890
- }
891
-
892
- .${CSS_CLASSES.iframe} {
893
- height: 100vh;
894
- height: 100dvh;
895
- max-height: none;
896
- }
897
- }
898
-
899
- .${CSS_CLASSES.embedded} {
900
- position: relative;
901
- width: 100%;
902
- height: 100%;
903
- }
904
-
905
- .${CSS_CLASSES.embedded} .${CSS_CLASSES.iframe} {
906
- width: 100%;
907
- height: 100%;
908
- max-height: none;
909
- }
910
-
911
- .${CSS_CLASSES.embedded} .${CSS_CLASSES.loading} {
912
- border-radius: 0;
913
- }
914
- `;
915
- document.head.appendChild(styles);
916
- }
917
- createDOM() {
918
- this.injectStyles();
919
- if (this.embedded && this.embeddedContainer) {
920
- this.createEmbeddedDOM();
921
- return;
922
- }
923
- const t = getTranslations(this.language);
924
- this.overlay = document.createElement("div");
925
- this.overlay.id = this.modalId;
926
- this.overlay.className = CSS_CLASSES.overlay;
927
- this.overlay.setAttribute("role", "dialog");
928
- this.overlay.setAttribute("aria-modal", "true");
929
- this.overlay.setAttribute("aria-label", t.ariaLabelModal);
930
- this.container = document.createElement("div");
931
- this.container.className = CSS_CLASSES.container;
932
- this.loadingEl = document.createElement("div");
933
- this.loadingEl.className = CSS_CLASSES.loading;
934
- this.loadingEl.innerHTML = `
935
- <svg viewBox="0 0 24 24">
936
- <circle cx="12" cy="12" r="10" />
937
- <path d="M12 2a10 10 0 0 1 10 10" />
938
- </svg>
939
- `;
940
- if (this.config.showCloseButton) {
941
- const closeBtn = document.createElement("button");
942
- closeBtn.className = CSS_CLASSES.closeButton;
943
- closeBtn.setAttribute("aria-label", t.ariaLabelClose);
944
- closeBtn.innerHTML = `
945
- <svg width="14" height="14" viewBox="0 0 14 14">
946
- <line x1="1" y1="1" x2="13" y2="13" />
947
- <line x1="13" y1="1" x2="1" y2="13" />
948
- </svg>
949
- `;
950
- closeBtn.addEventListener("click", () => this.handleCloseRequest());
951
- this.container.appendChild(closeBtn);
952
- }
953
- this.iframe = document.createElement("iframe");
954
- this.iframe.className = CSS_CLASSES.iframe;
955
- this.iframe.setAttribute("allow", "camera; microphone; fullscreen; autoplay; encrypted-media; geolocation");
956
- this.iframe.setAttribute("title", t.ariaLabelModal);
957
- this.iframe.addEventListener("load", () => this.handleIframeLoad());
958
- this.confirmOverlay = document.createElement("div");
959
- this.confirmOverlay.className = CSS_CLASSES.confirmOverlay;
960
- this.confirmOverlay.innerHTML = `
961
- <div class="${CSS_CLASSES.confirmBox}">
962
- <h3>${t.exitTitle}</h3>
963
- <p>${t.exitMessage}</p>
964
- <div class="didit-confirm-actions">
965
- <button type="button" data-action="continue">${t.continueButton}</button>
966
- <span data-action="exit">${t.exitButton}</span>
967
- </div>
968
- </div>
969
- `;
970
- this.confirmOverlay.querySelector('[data-action="continue"]')?.addEventListener("click", () => {
971
- this.hideConfirmation();
972
- });
973
- this.confirmOverlay.querySelector('[data-action="exit"]')?.addEventListener("click", () => {
974
- this.confirmExit();
975
- });
976
- this.container.appendChild(this.loadingEl);
977
- this.container.appendChild(this.iframe);
978
- this.container.appendChild(this.confirmOverlay);
979
- this.overlay.appendChild(this.container);
980
- this.overlay.addEventListener("click", (e) => {
981
- if (e.target === this.overlay) {
982
- this.handleCloseRequest();
983
- }
984
- });
985
- this.containerElement.appendChild(this.overlay);
986
- }
987
- createEmbeddedDOM() {
988
- if (!this.embeddedContainer)
989
- return;
990
- this.container = document.createElement("div");
991
- this.container.id = this.modalId;
992
- this.container.className = CSS_CLASSES.embedded;
993
- this.loadingEl = document.createElement("div");
994
- this.loadingEl.className = CSS_CLASSES.loading;
995
- this.loadingEl.innerHTML = `
996
- <svg viewBox="0 0 24 24">
997
- <circle cx="12" cy="12" r="10" />
998
- <path d="M12 2a10 10 0 0 1 10 10" />
999
- </svg>
1000
- `;
1001
- this.iframe = document.createElement("iframe");
1002
- this.iframe.className = CSS_CLASSES.iframe;
1003
- this.iframe.setAttribute("allow", "camera; microphone; fullscreen; autoplay; encrypted-media; geolocation");
1004
- this.iframe.setAttribute("title", getTranslations(this.language).ariaLabelModal);
1005
- this.iframe.addEventListener("load", () => this.handleIframeLoad());
1006
- this.container.appendChild(this.loadingEl);
1007
- this.container.appendChild(this.iframe);
1008
- this.embeddedContainer.appendChild(this.container);
1009
- }
1010
- setupEventListeners() {
1011
- // Idempotent: open() calls this every time it presents the modal, but a
1012
- // modal that was already open (or re-opened without an intervening
1013
- // close()) must not accumulate duplicate listeners.
1014
- if (this.boundHandleMessage || this.boundHandleKeydown) {
1015
- return;
1016
- }
1017
- this.boundHandleMessage = this.handleMessage.bind(this);
1018
- window.addEventListener("message", this.boundHandleMessage);
1019
- this.boundHandleKeydown = this.handleKeydown.bind(this);
1020
- document.addEventListener("keydown", this.boundHandleKeydown);
1021
- }
1022
- removeEventListeners() {
1023
- if (this.boundHandleMessage) {
1024
- window.removeEventListener("message", this.boundHandleMessage);
1025
- this.boundHandleMessage = null;
1026
- }
1027
- if (this.boundHandleKeydown) {
1028
- document.removeEventListener("keydown", this.boundHandleKeydown);
1029
- this.boundHandleKeydown = null;
1030
- }
1031
- }
1032
- pushToTop() {
1033
- const modals = VerificationModal.openModals;
1034
- const existingIndex = modals.indexOf(this);
1035
- if (existingIndex !== -1) {
1036
- modals.splice(existingIndex, 1);
1037
- }
1038
- modals.push(this);
1039
- }
1040
- removeFromStack() {
1041
- const modals = VerificationModal.openModals;
1042
- const existingIndex = modals.indexOf(this);
1043
- if (existingIndex !== -1) {
1044
- modals.splice(existingIndex, 1);
1045
- }
1046
- }
1047
- isTopmost() {
1048
- const modals = VerificationModal.openModals;
1049
- return modals.length > 0 && modals[modals.length - 1] === this;
1050
- }
1051
- handleMessage(event) {
1052
- if (!this.iframe?.src)
1053
- return;
1054
- if (!isAllowedOrigin(event.origin, this.iframe.src)) {
1055
- return SDKLogger.warn("Received postMessage from unallowed origin:", event.origin);
1056
- }
1057
- // Scope every message to this modal's own iframe. Without this check, a
1058
- // second VerificationModal open at the same time (e.g. a transaction
1059
- // action modal stacked over the verification modal) would also react to
1060
- // postMessages meant for the other iframe.
1061
- if (!this.iframe || event.source !== this.iframe.contentWindow) {
1062
- return;
1063
- }
1064
- SDKLogger.log("Received postMessage:", event.data);
1065
- let messageData;
1066
- try {
1067
- if (typeof event.data === "string") {
1068
- messageData = JSON.parse(event.data);
1069
- }
1070
- else {
1071
- messageData = event.data;
1072
- }
1073
- }
1074
- catch {
1075
- SDKLogger.warn("Failed to parse postMessage:", event.data);
1076
- return;
1077
- }
1078
- if (messageData.type === "didit:close_request") {
1079
- this.handleCloseRequest();
1080
- return;
1081
- }
1082
- this.callbacks.onMessage(messageData);
1083
- }
1084
- handleKeydown(event) {
1085
- if (!this.state.isOpen)
1086
- return;
1087
- // When multiple modals are open at once, only the topmost one should
1088
- // react to a keypress aimed at it (e.g. Escape closing a stacked
1089
- // transaction action modal must not also trigger the exit confirmation
1090
- // of the verification modal underneath it).
1091
- if (!this.isTopmost())
1092
- return;
1093
- if (event.key === "Escape") {
1094
- event.preventDefault();
1095
- if (this.state.showConfirmation) {
1096
- this.hideConfirmation();
1097
- }
1098
- else {
1099
- this.handleCloseRequest();
1100
- }
1101
- }
1102
- }
1103
- handleIframeLoad() {
1104
- if (this.iframe?.src && this.iframe.src !== "about:blank") {
1105
- this.state.isLoading = false;
1106
- this.loadingEl?.classList.add("hidden");
1107
- this.callbacks.onIframeLoad();
1108
- }
1109
- }
1110
- handleCloseRequest() {
1111
- if (this.config.showExitConfirmation) {
1112
- this.showConfirmation();
1113
- }
1114
- else {
1115
- this.callbacks.onCloseConfirmed();
1116
- }
1117
- }
1118
- showConfirmation() {
1119
- this.state.showConfirmation = true;
1120
- this.confirmOverlay?.classList.add("active");
1121
- this.callbacks.onClose();
1122
- }
1123
- hideConfirmation() {
1124
- this.state.showConfirmation = false;
1125
- this.confirmOverlay?.classList.remove("active");
1126
- }
1127
- confirmExit() {
1128
- this.hideConfirmation();
1129
- this.callbacks.onCloseConfirmed();
1713
+ max-height: 100dvh;
1714
+ border-radius: 0;
1130
1715
  }
1131
- open(verificationUrl) {
1132
- // Whether this modal already held its scroll lock before this call. Re-opening
1133
- // an already-open instance must not re-capture previousBodyOverflow, or it
1134
- // would record this modal's own "hidden" lock and close() could never restore
1135
- // the real pre-lock value.
1136
- const wasAlreadyOpen = this.state.isOpen;
1137
- this.language = detectLanguageFromUrl(verificationUrl);
1138
- if (!this.overlay && !this.container) {
1139
- this.createDOM();
1140
- }
1141
- // Re-attach listeners every open() (idempotent) since close() now tears
1142
- // them down; this lets the same instance be re-opened without a
1143
- // destroy()/re-create cycle.
1144
- this.setupEventListeners();
1145
- SDKLogger.log("Opening with URL:", verificationUrl);
1146
- this.state.isLoading = true;
1147
- this.state.showConfirmation = false;
1148
- this.loadingEl?.classList.remove("hidden");
1149
- this.confirmOverlay?.classList.remove("active");
1150
- if (this.iframe) {
1151
- this.iframe.src = verificationUrl;
1152
- }
1153
- this.state.isOpen = true;
1154
- this.pushToTop();
1155
- if (this.embedded) {
1156
- return;
1157
- }
1158
- this.overlay?.classList.add("active");
1159
- // Capture whatever overflow value is currently in effect (which may
1160
- // already be "hidden" because another modal is open) so close() can
1161
- // restore exactly that value instead of clobbering a scroll lock owned
1162
- // by a concurrently open modal. Skip the capture on a re-open: the value
1163
- // in effect is this modal's own lock, and previousBodyOverflow already
1164
- // holds the correct pre-lock value.
1165
- if (!wasAlreadyOpen) {
1166
- this.previousBodyOverflow = document.body.style.overflow;
1167
- }
1168
- document.body.style.overflow = "hidden";
1716
+
1717
+ .${CSS_CLASSES.iframe} {
1718
+ height: 100vh;
1719
+ height: 100dvh;
1720
+ max-height: none;
1169
1721
  }
1170
- close() {
1171
- SDKLogger.log("Closing");
1172
- this.state.isOpen = false;
1173
- this.state.isLoading = true;
1174
- this.state.showConfirmation = false;
1175
- this.removeFromStack();
1176
- this.removeEventListeners();
1177
- if (this.iframe) {
1178
- this.iframe.src = "about:blank";
1179
- }
1180
- if (this.embedded) {
1181
- return;
1182
- }
1183
- this.overlay?.classList.remove("active");
1184
- document.body.style.overflow = this.previousBodyOverflow ?? "";
1185
- this.previousBodyOverflow = null;
1722
+ }
1723
+
1724
+ /*
1725
+ * Once the hosted flow reports its layout (didit:layout), the modal
1726
+ * grows to the handoff card on a computer (960 x 660, at most 90% of
1727
+ * the window) and follows the flow's content height in a narrow
1728
+ * window. Colours are the design system tokens named beside them.
1729
+ */
1730
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1731
+ --didit-ground: #ffffff; /* site-ground */
1732
+ --didit-heading: #1a1a1a; /* c-heading */
1733
+ --didit-accent: #2567ff; /* c-accent */
1734
+ --didit-hover: rgba(120, 120, 128, 0.08); /* c-hover */
1735
+ --didit-close-fill: rgba(0, 0, 0, 0.06);
1736
+ --didit-drop: rgba(17, 24, 39, 0.35);
1737
+ --didit-ring: rgba(0, 0, 0, 0.06);
1738
+ max-width: 500px;
1739
+ background: var(--didit-ground);
1740
+ box-shadow: 0 30px 80px -24px var(--didit-drop), 0 0 0 1px var(--didit-ring);
1741
+ }
1742
+
1743
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized}[data-didit-theme="dark"] {
1744
+ --didit-ground: #0b0b0d;
1745
+ --didit-heading: #f5f5f7;
1746
+ --didit-accent: #4d8bff;
1747
+ --didit-hover: rgba(255, 255, 255, 0.06);
1748
+ --didit-close-fill: rgba(255, 255, 255, 0.06);
1749
+ --didit-drop: rgba(0, 0, 0, 0.55); /* c-shadow-pop, dark */
1750
+ --didit-ring: rgba(255, 255, 255, 0.08); /* c-shadow-pop, dark */
1751
+ }
1752
+
1753
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1754
+ height: var(--didit-flow-height);
1755
+ max-height: 90vh;
1756
+ max-height: 90dvh;
1757
+ }
1758
+
1759
+ .${CSS_CLASSES.closeIcon} {
1760
+ display: none;
1761
+ }
1762
+
1763
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton} {
1764
+ top: 8px;
1765
+ right: 8px;
1766
+ width: 44px;
1767
+ height: 44px;
1768
+ display: flex;
1769
+ align-items: center;
1770
+ justify-content: center;
1771
+ border-radius: 50%;
1772
+ background: var(--didit-close-fill);
1773
+ color: var(--didit-heading);
1774
+ }
1775
+
1776
+ .${CSS_CLASSES.flowSized}[data-didit-dir="rtl"] .${CSS_CLASSES.closeButton} {
1777
+ right: auto;
1778
+ left: 8px;
1779
+ }
1780
+
1781
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:hover,
1782
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:focus {
1783
+ background: var(--didit-close-fill);
1784
+ opacity: 1;
1785
+ }
1786
+
1787
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:hover {
1788
+ background-image: linear-gradient(var(--didit-hover), var(--didit-hover));
1789
+ }
1790
+
1791
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:focus-visible {
1792
+ outline: 2px solid var(--didit-accent);
1793
+ outline-offset: 2px;
1794
+ }
1795
+
1796
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeIconLegacy} {
1797
+ display: none;
1798
+ }
1799
+
1800
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton} .${CSS_CLASSES.closeIcon} {
1801
+ display: block;
1802
+ stroke: currentColor;
1803
+ stroke-width: 1.75;
1804
+ stroke-linejoin: round;
1805
+ }
1806
+
1807
+ /*
1808
+ * The exit confirmation is sized in rem, so with a large text size it
1809
+ * can be taller than a short flow: it scrolls inside the modal instead
1810
+ * of being clipped, and its width and actions follow a larger text size.
1811
+ * It never grows wider than the modal: a long word wraps instead.
1812
+ */
1813
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.confirmOverlay} {
1814
+ padding: 1rem;
1815
+ overflow-y: auto;
1816
+ }
1817
+
1818
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.confirmBox} {
1819
+ min-width: 0;
1820
+ max-width: max(300px, 18.75rem);
1821
+ margin: auto;
1822
+ overflow-wrap: anywhere;
1823
+ /* Focusing the dialog scrolls it into view start-aligned; this keeps
1824
+ * the overlay's top padding visible so the title is never clipped. */
1825
+ scroll-margin-top: 1rem;
1826
+ }
1827
+
1828
+ .${CSS_CLASSES.flowSized} .didit-confirm-actions {
1829
+ flex-wrap: wrap;
1830
+ }
1831
+
1832
+ @media (min-width: 1024px) {
1833
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1834
+ width: 90vw;
1835
+ max-width: 960px;
1186
1836
  }
1187
- destroy() {
1188
- SDKLogger.log("Destroying");
1189
- this.close();
1190
- this.removeEventListeners();
1191
- if (this.embedded && this.container && this.container.parentNode) {
1192
- this.container.parentNode.removeChild(this.container);
1193
- }
1194
- else if (this.overlay && this.overlay.parentNode) {
1195
- this.overlay.parentNode.removeChild(this.overlay);
1196
- }
1197
- this.overlay = null;
1198
- this.container = null;
1199
- this.iframe = null;
1200
- this.loadingEl = null;
1201
- this.confirmOverlay = null;
1837
+
1838
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1839
+ height: 660px;
1202
1840
  }
1203
- isOpen() {
1204
- return this.state.isOpen;
1841
+ }
1842
+
1843
+ @media (max-width: 540px) {
1844
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1845
+ max-width: 100%;
1846
+ box-shadow: none;
1205
1847
  }
1206
- isLoading() {
1207
- return this.state.isLoading;
1848
+
1849
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1850
+ height: 100vh;
1851
+ height: 100dvh;
1852
+ max-height: none;
1208
1853
  }
1209
- }
1210
- /**
1211
- * Every currently-open modal, oldest first. Used so a single Escape
1212
- * keypress (or other document-level shortcut) only acts on the topmost
1213
- * modal when multiple VerificationModal instances are open at once (e.g.
1214
- * a transaction action modal stacked over the verification modal).
1215
- */
1216
- VerificationModal.openModals = [];
1854
+ }
1217
1855
 
1218
- /**
1219
- * Minimal self-contained port of the didit-fp-v2 device fingerprint used by the
1220
- * Didit verification frontend. It collects stable browser signals, hashes them
1221
- * with WebCrypto SHA-256 and persists a random device id in localStorage with a
1222
- * cookie fallback. The payload shape matches the didit-fp-v2 schema so the Didit
1223
- * backend middleware parses it identically to the verification flow:
1224
- *
1225
- * - headers: X-Didit-PID (persistent id) and X-Didit-FP-Hash (composite hash)
1226
- * - body: a top-level `fingerprint_v2` field carrying the full payload
1227
- */
1228
- const PERSISTENT_ID_STORAGE_KEY = "didit-pid-v1";
1229
- const PERSISTENT_ID_COOKIE_NAME = "didit_pid";
1230
- const PERSISTENT_ID_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365 * 2;
1231
- const PERSISTENT_ID_BYTE_LENGTH = 16;
1232
- const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1233
- let memoryPersistentId = null;
1234
- let cachedPayload = null;
1235
- let cachedPayloadPromise = null;
1236
- function bytesToBase64Url(bytes) {
1237
- let output = "";
1238
- let i = 0;
1239
- for (; i + 2 < bytes.length; i += 3) {
1240
- const triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
1241
- output += BASE64URL_ALPHABET[(triplet >> 18) & 0x3f];
1242
- output += BASE64URL_ALPHABET[(triplet >> 12) & 0x3f];
1243
- output += BASE64URL_ALPHABET[(triplet >> 6) & 0x3f];
1244
- output += BASE64URL_ALPHABET[triplet & 0x3f];
1856
+ .${CSS_CLASSES.embedded} {
1857
+ position: relative;
1858
+ width: 100%;
1859
+ height: 100%;
1860
+ }
1861
+
1862
+ .${CSS_CLASSES.embedded} .${CSS_CLASSES.iframe} {
1863
+ width: 100%;
1864
+ height: 100%;
1865
+ max-height: none;
1866
+ }
1867
+
1868
+ .${CSS_CLASSES.embedded} .${CSS_CLASSES.loading} {
1869
+ border-radius: 0;
1870
+ }
1871
+ `;
1872
+ document.head.appendChild(styles);
1245
1873
  }
1246
- if (i < bytes.length) {
1247
- const remaining = bytes.length - i;
1248
- const a = bytes[i];
1249
- const b = remaining > 1 ? bytes[i + 1] : 0;
1250
- const triplet = (a << 16) | (b << 8);
1251
- output += BASE64URL_ALPHABET[(triplet >> 18) & 0x3f];
1252
- output += BASE64URL_ALPHABET[(triplet >> 12) & 0x3f];
1253
- if (remaining > 1) {
1254
- output += BASE64URL_ALPHABET[(triplet >> 6) & 0x3f];
1874
+ createDOM() {
1875
+ this.injectStyles();
1876
+ if (this.embedded && this.embeddedContainer) {
1877
+ this.createEmbeddedDOM();
1878
+ return;
1255
1879
  }
1880
+ const t = getTranslations(this.language);
1881
+ this.overlay = document.createElement("div");
1882
+ this.overlay.id = this.modalId;
1883
+ this.overlay.className = CSS_CLASSES.overlay;
1884
+ this.overlay.setAttribute("role", "dialog");
1885
+ this.overlay.setAttribute("aria-modal", "true");
1886
+ this.overlay.setAttribute("aria-label", t.ariaLabelModal);
1887
+ this.container = document.createElement("div");
1888
+ this.container.className = CSS_CLASSES.container;
1889
+ this.loadingEl = document.createElement("div");
1890
+ this.loadingEl.className = CSS_CLASSES.loading;
1891
+ this.loadingEl.innerHTML = `
1892
+ <svg viewBox="0 0 24 24">
1893
+ <circle cx="12" cy="12" r="10" />
1894
+ <path d="M12 2a10 10 0 0 1 10 10" />
1895
+ </svg>
1896
+ `;
1897
+ if (this.config.showCloseButton) {
1898
+ const closeBtn = document.createElement("button");
1899
+ closeBtn.className = CSS_CLASSES.closeButton;
1900
+ closeBtn.setAttribute("aria-label", t.ariaLabelClose);
1901
+ closeBtn.innerHTML = `
1902
+ <svg class="${CSS_CLASSES.closeIconLegacy}" width="14" height="14" viewBox="0 0 14 14">
1903
+ <line x1="1" y1="1" x2="13" y2="13" />
1904
+ <line x1="13" y1="1" x2="1" y2="13" />
1905
+ </svg>
1906
+ <svg class="${CSS_CLASSES.closeIcon}" width="18" height="18" viewBox="0 0 24 24" fill="none">
1907
+ <path d="M7 7.03882L17 16.9611" />
1908
+ <path d="M7.03968 17L16.9619 7" />
1909
+ </svg>
1910
+ `;
1911
+ closeBtn.addEventListener("click", () => this.handleCloseRequest(closeBtn));
1912
+ this.container.appendChild(closeBtn);
1913
+ }
1914
+ this.iframe = document.createElement("iframe");
1915
+ this.iframe.className = CSS_CLASSES.iframe;
1916
+ this.iframe.setAttribute("allow", IFRAME_ALLOW);
1917
+ this.iframe.setAttribute("title", t.ariaLabelModal);
1918
+ this.iframe.addEventListener("load", () => this.handleIframeLoad());
1919
+ this.confirmOverlay = document.createElement("div");
1920
+ this.confirmOverlay.className = CSS_CLASSES.confirmOverlay;
1921
+ this.confirmOverlay.innerHTML = `
1922
+ <div class="${CSS_CLASSES.confirmBox}" role="dialog" aria-modal="true" tabindex="-1"
1923
+ aria-labelledby="${this.modalId}-exit-title" aria-describedby="${this.modalId}-exit-message">
1924
+ <h3 id="${this.modalId}-exit-title">${t.exitTitle}</h3>
1925
+ <p id="${this.modalId}-exit-message">${t.exitMessage}</p>
1926
+ <div class="didit-confirm-actions">
1927
+ <button type="button" data-action="continue">${t.continueButton}</button>
1928
+ <button type="button" data-action="exit">${t.exitButton}</button>
1929
+ </div>
1930
+ </div>
1931
+ `;
1932
+ this.confirmOverlay.querySelector('[data-action="continue"]')?.addEventListener("click", () => {
1933
+ this.hideConfirmation();
1934
+ });
1935
+ this.confirmOverlay.querySelector('[data-action="exit"]')?.addEventListener("click", () => {
1936
+ this.confirmExit();
1937
+ });
1938
+ this.container.appendChild(this.loadingEl);
1939
+ this.container.appendChild(this.iframe);
1940
+ this.container.appendChild(this.confirmOverlay);
1941
+ this.overlay.appendChild(this.container);
1942
+ this.overlay.addEventListener("click", (e) => {
1943
+ if (e.target === this.overlay) {
1944
+ this.handleCloseRequest();
1945
+ }
1946
+ });
1947
+ this.containerElement.appendChild(this.overlay);
1256
1948
  }
1257
- return output;
1258
- }
1259
- function randomBytes(length) {
1260
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
1261
- const buffer = new Uint8Array(length);
1262
- crypto.getRandomValues(buffer);
1263
- return buffer;
1264
- }
1265
- const fallback = new Uint8Array(length);
1266
- for (let i = 0; i < length; i++) {
1267
- fallback[i] = Math.floor(Math.random() * 256);
1949
+ createEmbeddedDOM() {
1950
+ if (!this.embeddedContainer)
1951
+ return;
1952
+ this.container = document.createElement("div");
1953
+ this.container.id = this.modalId;
1954
+ this.container.className = CSS_CLASSES.embedded;
1955
+ this.loadingEl = document.createElement("div");
1956
+ this.loadingEl.className = CSS_CLASSES.loading;
1957
+ this.loadingEl.innerHTML = `
1958
+ <svg viewBox="0 0 24 24">
1959
+ <circle cx="12" cy="12" r="10" />
1960
+ <path d="M12 2a10 10 0 0 1 10 10" />
1961
+ </svg>
1962
+ `;
1963
+ this.iframe = document.createElement("iframe");
1964
+ this.iframe.className = CSS_CLASSES.iframe;
1965
+ this.iframe.setAttribute("allow", IFRAME_ALLOW);
1966
+ this.iframe.setAttribute("title", getTranslations(this.language).ariaLabelModal);
1967
+ this.iframe.addEventListener("load", () => this.handleIframeLoad());
1968
+ this.container.appendChild(this.loadingEl);
1969
+ this.container.appendChild(this.iframe);
1970
+ this.embeddedContainer.appendChild(this.container);
1268
1971
  }
1269
- return fallback;
1270
- }
1271
- function randomBase64Url(byteLength) {
1272
- return bytesToBase64Url(randomBytes(byteLength));
1273
- }
1274
- // SHA-256 truncated to the leading 128 bits, base64url-encoded (22 chars).
1275
- // Same construction as the didit-fp-v2 composite hash in the verification frontend.
1276
- async function sha256_128(input) {
1277
- if (typeof crypto === "undefined" || !crypto.subtle) {
1278
- throw new Error("WebCrypto SubtleCrypto is not available");
1972
+ setupEventListeners() {
1973
+ // Idempotent: open() calls this every time it presents the modal, but a
1974
+ // modal that was already open (or re-opened without an intervening
1975
+ // close()) must not accumulate duplicate listeners.
1976
+ if (this.boundHandleMessage || this.boundHandleKeydown) {
1977
+ return;
1978
+ }
1979
+ this.boundHandleMessage = this.handleMessage.bind(this);
1980
+ window.addEventListener("message", this.boundHandleMessage);
1981
+ this.boundHandleKeydown = this.handleKeydown.bind(this);
1982
+ document.addEventListener("keydown", this.boundHandleKeydown);
1983
+ this.boundHandleFocusChange = () => {
1984
+ if (!this.state.showConfirmation || !this.isTopmost())
1985
+ return;
1986
+ // An iframe can take focus without a focusin event in its parent document.
1987
+ // Wait until its focus transition finishes before moving focus back.
1988
+ if (this.confirmationFocusTimeout !== null)
1989
+ window.clearTimeout(this.confirmationFocusTimeout);
1990
+ this.confirmationFocusTimeout = window.setTimeout(() => {
1991
+ this.confirmationFocusTimeout = null;
1992
+ if (this.state.showConfirmation && this.isTopmost() && !this.confirmOverlay?.contains(document.activeElement)) {
1993
+ this.focusConfirmation();
1994
+ }
1995
+ }, 0);
1996
+ };
1997
+ document.addEventListener("focusin", this.boundHandleFocusChange);
1998
+ document.addEventListener("focusout", this.boundHandleFocusChange);
1999
+ window.addEventListener("blur", this.boundHandleFocusChange);
1279
2000
  }
1280
- const bytes = new TextEncoder().encode(input);
1281
- const view = new Uint8Array(bytes.byteLength);
1282
- view.set(bytes);
1283
- const digest = await crypto.subtle.digest("SHA-256", view.buffer);
1284
- return bytesToBase64Url(new Uint8Array(digest).slice(0, 16));
1285
- }
1286
- // FNV-1a 32-bit fallback hash, only used when WebCrypto is unavailable.
1287
- function fnv1a32(value) {
1288
- let hash = 0x811c9dc5;
1289
- for (let i = 0; i < value.length; i++) {
1290
- hash ^= value.charCodeAt(i);
1291
- hash = Math.imul(hash, 0x01000193);
2001
+ removeEventListeners() {
2002
+ if (this.boundHandleMessage) {
2003
+ window.removeEventListener("message", this.boundHandleMessage);
2004
+ this.boundHandleMessage = null;
2005
+ }
2006
+ if (this.boundHandleKeydown) {
2007
+ document.removeEventListener("keydown", this.boundHandleKeydown);
2008
+ this.boundHandleKeydown = null;
2009
+ }
2010
+ if (this.boundHandleFocusChange) {
2011
+ document.removeEventListener("focusin", this.boundHandleFocusChange);
2012
+ document.removeEventListener("focusout", this.boundHandleFocusChange);
2013
+ window.removeEventListener("blur", this.boundHandleFocusChange);
2014
+ this.boundHandleFocusChange = null;
2015
+ }
1292
2016
  }
1293
- return (hash >>> 0).toString(16).padStart(8, "0");
1294
- }
1295
- function stableStringify(value) {
1296
- if (value === null || value === undefined)
1297
- return JSON.stringify(value ?? null);
1298
- if (Array.isArray(value))
1299
- return `[${value.map((v) => stableStringify(v)).join(",")}]`;
1300
- if (typeof value === "object") {
1301
- const keys = Object.keys(value).sort();
1302
- const parts = keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`);
1303
- return `{${parts.join(",")}}`;
2017
+ pushToTop() {
2018
+ const modals = VerificationModal.openModals;
2019
+ const existingIndex = modals.indexOf(this);
2020
+ if (existingIndex !== -1) {
2021
+ modals.splice(existingIndex, 1);
2022
+ }
2023
+ modals.push(this);
1304
2024
  }
1305
- return JSON.stringify(value);
1306
- }
1307
- function isValidPersistentId(value) {
1308
- return typeof value === "string" && /^[A-Za-z0-9_-]{20,32}$/.test(value);
1309
- }
1310
- function readLocalStorageId() {
1311
- try {
1312
- if (typeof localStorage === "undefined")
1313
- return null;
1314
- const value = localStorage.getItem(PERSISTENT_ID_STORAGE_KEY);
1315
- return isValidPersistentId(value) ? value : null;
2025
+ removeFromStack() {
2026
+ const modals = VerificationModal.openModals;
2027
+ const existingIndex = modals.indexOf(this);
2028
+ if (existingIndex !== -1) {
2029
+ modals.splice(existingIndex, 1);
2030
+ }
1316
2031
  }
1317
- catch {
1318
- return null;
2032
+ isTopmost() {
2033
+ const modals = VerificationModal.openModals;
2034
+ return modals.length > 0 && modals[modals.length - 1] === this;
1319
2035
  }
1320
- }
1321
- function writeLocalStorageId(id) {
1322
- try {
1323
- if (typeof localStorage === "undefined")
2036
+ handleMessage(event) {
2037
+ if (!this.iframe?.src)
1324
2038
  return;
1325
- localStorage.setItem(PERSISTENT_ID_STORAGE_KEY, id);
1326
- }
1327
- catch {
1328
- // Storage may be blocked (private mode, storage policies); cookie layer still applies.
1329
- }
1330
- }
1331
- function readCookieId() {
1332
- try {
1333
- if (typeof document === "undefined" || !document.cookie)
1334
- return null;
1335
- const prefix = `${PERSISTENT_ID_COOKIE_NAME}=`;
1336
- for (const part of document.cookie.split(";")) {
1337
- const trimmed = part.trim();
1338
- if (trimmed.startsWith(prefix)) {
1339
- const value = decodeURIComponent(trimmed.substring(prefix.length));
1340
- return isValidPersistentId(value) ? value : null;
2039
+ if (!isAllowedOrigin(event.origin, this.iframe.src)) {
2040
+ return SDKLogger.warn("Received postMessage from unallowed origin:", event.origin);
2041
+ }
2042
+ // Scope every message to this modal's own iframe. Without this check, a
2043
+ // second VerificationModal open at the same time (e.g. a transaction
2044
+ // action modal stacked over the verification modal) would also react to
2045
+ // postMessages meant for the other iframe.
2046
+ if (!this.iframe || event.source !== this.iframe.contentWindow) {
2047
+ return;
2048
+ }
2049
+ SDKLogger.log("Received postMessage:", event.data);
2050
+ let messageData;
2051
+ try {
2052
+ if (typeof event.data === "string") {
2053
+ messageData = JSON.parse(event.data);
2054
+ }
2055
+ else {
2056
+ messageData = event.data;
1341
2057
  }
1342
2058
  }
1343
- return null;
1344
- }
1345
- catch {
1346
- return null;
1347
- }
1348
- }
1349
- function writeCookieId(id) {
1350
- try {
1351
- if (typeof document === "undefined")
2059
+ catch {
2060
+ SDKLogger.warn("Failed to parse postMessage:", event.data);
1352
2061
  return;
1353
- const isSecure = typeof location !== "undefined" && location.protocol === "https:";
1354
- const attributes = [
1355
- `${PERSISTENT_ID_COOKIE_NAME}=${encodeURIComponent(id)}`,
1356
- "Path=/",
1357
- `Max-Age=${PERSISTENT_ID_COOKIE_MAX_AGE_SECONDS}`,
1358
- "SameSite=Lax"
1359
- ];
1360
- if (isSecure)
1361
- attributes.push("Secure");
1362
- document.cookie = attributes.join("; ");
1363
- }
1364
- catch {
1365
- // Cookies may be blocked; localStorage layer still applies.
1366
- }
1367
- }
1368
- function loadOrCreatePersistentId() {
1369
- const fromLocalStorage = readLocalStorageId();
1370
- const fromCookie = readCookieId();
1371
- let id;
1372
- let sources;
1373
- let wasCreated = false;
1374
- if (fromLocalStorage) {
1375
- id = fromLocalStorage;
1376
- sources = fromCookie === fromLocalStorage ? ["localStorage", "cookie"] : ["localStorage"];
2062
+ }
2063
+ if (messageData.type === "didit:close_request") {
2064
+ this.handleCloseRequest();
2065
+ return;
2066
+ }
2067
+ if (messageData.type === LAYOUT_MESSAGE_TYPE) {
2068
+ const layout = this.readFlowLayout(messageData.data);
2069
+ if (layout) {
2070
+ this.applyFlowLayout(layout);
2071
+ }
2072
+ else {
2073
+ SDKLogger.warn("Ignoring a layout message without a positive contentHeight:", messageData.data);
2074
+ }
2075
+ return;
2076
+ }
2077
+ this.callbacks.onMessage(messageData);
1377
2078
  }
1378
- else if (fromCookie) {
1379
- id = fromCookie;
1380
- sources = ["cookie"];
2079
+ /**
2080
+ * Reads a didit:layout message's data. Without a positive contentHeight the
2081
+ * message is ignored; a missing or unknown colorScheme follows the device,
2082
+ * and a missing or unknown dir follows the verification URL's language.
2083
+ */
2084
+ readFlowLayout(data) {
2085
+ const fields = typeof data === "object" && data !== null ? data : {};
2086
+ const { contentHeight, colorScheme, dir } = fields;
2087
+ if (typeof contentHeight !== "number" || !Number.isFinite(contentHeight) || contentHeight <= 0) {
2088
+ return null;
2089
+ }
2090
+ const prefersDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false;
2091
+ return {
2092
+ contentHeight: Math.ceil(contentHeight),
2093
+ colorScheme: colorScheme === "light" || colorScheme === "dark" ? colorScheme : prefersDark ? "dark" : "light",
2094
+ dir: dir === "ltr" || dir === "rtl" ? dir : isRtlLanguage(this.language) ? "rtl" : "ltr"
2095
+ };
1381
2096
  }
1382
- else if (memoryPersistentId && isValidPersistentId(memoryPersistentId)) {
1383
- id = memoryPersistentId;
1384
- sources = ["memory"];
2097
+ /** Embedded mode keeps filling the integrator's host element, whatever the flow reports. */
2098
+ applyFlowLayout(layout) {
2099
+ if (this.embedded || !this.container)
2100
+ return;
2101
+ SDKLogger.log("Flow layout:", layout);
2102
+ this.container.classList.add(CSS_CLASSES.flowSized);
2103
+ this.container.style.setProperty("--didit-flow-height", `${layout.contentHeight}px`);
2104
+ this.container.dataset.diditTheme = layout.colorScheme;
2105
+ this.container.dataset.diditDir = layout.dir;
2106
+ }
2107
+ /** Back to the fixed 500 x 700 modal until the newly loaded flow reports its layout. */
2108
+ resetFlowLayout() {
2109
+ if (this.embedded || !this.container)
2110
+ return;
2111
+ this.container.classList.remove(CSS_CLASSES.flowSized);
2112
+ this.container.style.removeProperty("--didit-flow-height");
2113
+ delete this.container.dataset.diditTheme;
2114
+ delete this.container.dataset.diditDir;
1385
2115
  }
1386
- else {
1387
- id = randomBase64Url(PERSISTENT_ID_BYTE_LENGTH);
1388
- sources = ["fresh"];
1389
- wasCreated = true;
2116
+ handleKeydown(event) {
2117
+ if (!this.state.isOpen)
2118
+ return;
2119
+ // When multiple modals are open at once, only the topmost one should
2120
+ // react to a keypress aimed at it (e.g. Escape closing a stacked
2121
+ // transaction action modal must not also trigger the exit confirmation
2122
+ // of the verification modal underneath it).
2123
+ if (!this.isTopmost())
2124
+ return;
2125
+ if (event.key === "Tab" && this.state.showConfirmation) {
2126
+ const buttons = Array.from(this.confirmOverlay?.querySelectorAll("button") ?? []);
2127
+ if (buttons.length) {
2128
+ event.preventDefault();
2129
+ const current = buttons.findIndex((button) => button === document.activeElement);
2130
+ const next = event.shiftKey
2131
+ ? (current <= 0 ? buttons.length - 1 : current - 1)
2132
+ : (current + 1) % buttons.length;
2133
+ buttons[next].focus();
2134
+ }
2135
+ return;
2136
+ }
2137
+ if (event.key === "Escape") {
2138
+ event.preventDefault();
2139
+ if (this.state.showConfirmation) {
2140
+ this.hideConfirmation();
2141
+ }
2142
+ else {
2143
+ this.handleCloseRequest();
2144
+ }
2145
+ }
1390
2146
  }
1391
- memoryPersistentId = id;
1392
- // Self-heal any layer that was missing or mismatched.
1393
- if (fromLocalStorage !== id)
1394
- writeLocalStorageId(id);
1395
- if (fromCookie !== id)
1396
- writeCookieId(id);
1397
- return { id, sources, wasCreated };
1398
- }
1399
- function collectNavigatorSignals() {
1400
- const nav = typeof navigator !== "undefined" ? navigator : null;
1401
- const scr = typeof screen !== "undefined" ? screen : null;
1402
- let timeZone = null;
1403
- try {
1404
- timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
2147
+ handleIframeLoad() {
2148
+ if (this.iframe?.src && this.iframe.src !== "about:blank") {
2149
+ this.state.isLoading = false;
2150
+ this.loadingEl?.classList.add("hidden");
2151
+ this.callbacks.onIframeLoad();
2152
+ }
1405
2153
  }
1406
- catch {
1407
- timeZone = null;
2154
+ handleCloseRequest(trigger) {
2155
+ if (this.config.showExitConfirmation) {
2156
+ this.showConfirmation(trigger);
2157
+ }
2158
+ else {
2159
+ this.callbacks.onCloseConfirmed();
2160
+ }
1408
2161
  }
1409
- const uaData = nav
1410
- ? nav
1411
- .userAgentData
1412
- : undefined;
1413
- return {
1414
- userAgent: nav?.userAgent ?? "",
1415
- platform: nav?.platform ?? null,
1416
- language: nav?.language ?? "",
1417
- languages: nav?.languages ? [...nav.languages] : [],
1418
- hardwareConcurrency: typeof nav?.hardwareConcurrency === "number" ? nav.hardwareConcurrency : null,
1419
- deviceMemory: (() => {
1420
- const memory = nav ? nav.deviceMemory : undefined;
1421
- return typeof memory === "number" ? memory : null;
1422
- })(),
1423
- maxTouchPoints: typeof nav?.maxTouchPoints === "number" ? nav.maxTouchPoints : null,
1424
- devicePixelRatio: typeof window !== "undefined" && typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : null,
1425
- screenWidth: typeof scr?.width === "number" ? scr.width : null,
1426
- screenHeight: typeof scr?.height === "number" ? scr.height : null,
1427
- colorDepth: typeof scr?.colorDepth === "number" ? scr.colorDepth : null,
1428
- timeZone,
1429
- uaDataPlatform: uaData?.platform ?? null,
1430
- uaDataMobile: typeof uaData?.mobile === "boolean" ? uaData.mobile : null,
1431
- uaDataBrands: uaData?.brands ? uaData.brands.map((entry) => `${entry.brand} ${entry.version}`) : []
1432
- };
1433
- }
1434
- function detectWebViewKind(userAgent) {
1435
- if (/;\s?wv\)/.test(userAgent) || /\bVersion\/[\d.]+\s+Chrome\/[\d.]+\s+Mobile\b/.test(userAgent)) {
1436
- return "android-webview";
2162
+ showConfirmation(trigger) {
2163
+ if (!this.confirmOverlay || this.state.showConfirmation)
2164
+ return;
2165
+ const activeElement = document.activeElement;
2166
+ this.confirmationTrigger = trigger ?? (activeElement instanceof HTMLElement && activeElement !== document.body
2167
+ ? activeElement
2168
+ : this.container?.querySelector(`.${CSS_CLASSES.closeButton}`) ?? this.iframe);
2169
+ this.state.showConfirmation = true;
2170
+ this.confirmOverlay.classList.add("active");
2171
+ if (this.iframe)
2172
+ this.iframe.inert = true;
2173
+ const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
2174
+ if (close)
2175
+ close.inert = true;
2176
+ // A confirmation scrolled at a large text size opens again at its title.
2177
+ this.confirmOverlay.scrollTop = 0;
2178
+ if (this.isTopmost())
2179
+ this.focusConfirmation();
2180
+ this.callbacks.onClose();
1437
2181
  }
1438
- if (/FBAN|FBAV|Instagram|Line\/|MicroMessenger|Snapchat|musical_ly|BytedanceWebview/i.test(userAgent)) {
1439
- return "in-app-browser";
2182
+ focusConfirmation() {
2183
+ this.confirmOverlay?.querySelector(`.${CSS_CLASSES.confirmBox}`)?.focus({ preventScroll: true });
1440
2184
  }
1441
- if (/iPhone|iPad|iPod/.test(userAgent) && !/Safari\//.test(userAgent) && !/CriOS|FxiOS|EdgiOS/.test(userAgent)) {
1442
- return "ios-webview";
2185
+ hideConfirmation(restoreFocus = true) {
2186
+ if (this.confirmationFocusTimeout !== null) {
2187
+ window.clearTimeout(this.confirmationFocusTimeout);
2188
+ this.confirmationFocusTimeout = null;
2189
+ }
2190
+ if (!this.state.showConfirmation)
2191
+ return;
2192
+ this.state.showConfirmation = false;
2193
+ this.confirmOverlay?.classList.remove("active");
2194
+ if (this.iframe)
2195
+ this.iframe.inert = false;
2196
+ const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
2197
+ if (close)
2198
+ close.inert = false;
2199
+ const trigger = this.confirmationTrigger;
2200
+ this.confirmationTrigger = null;
2201
+ if (restoreFocus && this.isTopmost() && trigger?.isConnected) {
2202
+ if (trigger === this.iframe) {
2203
+ // Firefox needs a browser task to reactivate an inert cross-origin frame.
2204
+ this.confirmationFocusTimeout = window.setTimeout(() => {
2205
+ this.confirmationFocusTimeout = null;
2206
+ if (this.state.isOpen && !this.state.showConfirmation && this.isTopmost() && trigger.isConnected) {
2207
+ trigger.focus({ preventScroll: true });
2208
+ }
2209
+ }, 0);
2210
+ }
2211
+ else {
2212
+ trigger.focus({ preventScroll: true });
2213
+ }
2214
+ }
1443
2215
  }
1444
- return "browser";
1445
- }
1446
- function detectBot(signals) {
1447
- const flags = [];
1448
- const userAgent = signals.navigator.userAgent;
1449
- if (typeof navigator !== "undefined" && navigator.webdriver) {
1450
- flags.push("webdriver");
2216
+ confirmExit() {
2217
+ this.hideConfirmation();
2218
+ this.callbacks.onCloseConfirmed();
1451
2219
  }
1452
- if (/HeadlessChrome|PhantomJS|Selenium|puppeteer|playwright/i.test(userAgent)) {
1453
- flags.push("headless-ua");
2220
+ open(verificationUrl) {
2221
+ // Whether this modal already held its scroll lock before this call. Re-opening
2222
+ // an already-open instance must not re-capture previousBodyOverflow, or it
2223
+ // would record this modal's own "hidden" lock and close() could never restore
2224
+ // the real pre-lock value.
2225
+ const wasAlreadyOpen = this.state.isOpen;
2226
+ this.language = detectLanguageFromUrl(verificationUrl);
2227
+ if (!this.overlay && !this.container) {
2228
+ this.createDOM();
2229
+ }
2230
+ // Re-attach listeners every open() (idempotent) since close() now tears
2231
+ // them down; this lets the same instance be re-opened without a
2232
+ // destroy()/re-create cycle.
2233
+ this.setupEventListeners();
2234
+ SDKLogger.log("Opening with URL:", verificationUrl);
2235
+ this.state.isLoading = true;
2236
+ this.hideConfirmation();
2237
+ this.loadingEl?.classList.remove("hidden");
2238
+ this.resetFlowLayout();
2239
+ if (this.iframe) {
2240
+ this.iframe.src = verificationUrl;
2241
+ }
2242
+ this.state.isOpen = true;
2243
+ this.pushToTop();
2244
+ if (this.embedded) {
2245
+ return;
2246
+ }
2247
+ this.overlay?.classList.add("active");
2248
+ // Capture whatever overflow value is currently in effect (which may
2249
+ // already be "hidden" because another modal is open) so close() can
2250
+ // restore exactly that value instead of clobbering a scroll lock owned
2251
+ // by a concurrently open modal. Skip the capture on a re-open: the value
2252
+ // in effect is this modal's own lock, and previousBodyOverflow already
2253
+ // holds the correct pre-lock value.
2254
+ if (!wasAlreadyOpen) {
2255
+ this.previousBodyOverflow = document.body.style.overflow;
2256
+ }
2257
+ document.body.style.overflow = "hidden";
1454
2258
  }
1455
- if (signals.navigator.uaDataMobile === false && /Android|iPhone|iPad/i.test(userAgent)) {
1456
- flags.push("ua-mobile-mismatch");
2259
+ close() {
2260
+ SDKLogger.log("Closing");
2261
+ this.hideConfirmation(false);
2262
+ this.state.isOpen = false;
2263
+ this.state.isLoading = true;
2264
+ this.state.showConfirmation = false;
2265
+ this.removeFromStack();
2266
+ this.removeEventListeners();
2267
+ this.resetFlowLayout();
2268
+ if (this.iframe) {
2269
+ this.iframe.src = "about:blank";
2270
+ }
2271
+ if (this.embedded) {
2272
+ return;
2273
+ }
2274
+ this.overlay?.classList.remove("active");
2275
+ document.body.style.overflow = this.previousBodyOverflow ?? "";
2276
+ this.previousBodyOverflow = null;
1457
2277
  }
1458
- return { score: Math.min(1, flags.length / 4), flags };
1459
- }
1460
- function canonicalizeSignals(signals) {
1461
- // Only drift-resistant fields, serialized with stable key order so the same
1462
- // device always produces the same composite hash.
1463
- const stable = {
1464
- platform: signals.platform,
1465
- navigator: {
1466
- ua: signals.navigator.userAgent,
1467
- platform: signals.navigator.platform,
1468
- lang: signals.navigator.language.split("-")[0],
1469
- languages: [...signals.navigator.languages].sort(),
1470
- concurrency: signals.navigator.hardwareConcurrency,
1471
- memory: signals.navigator.deviceMemory,
1472
- maxTouch: signals.navigator.maxTouchPoints,
1473
- dpr: signals.navigator.devicePixelRatio,
1474
- screen: [signals.navigator.screenWidth, signals.navigator.screenHeight],
1475
- colorDepth: signals.navigator.colorDepth,
1476
- timeZone: signals.navigator.timeZone,
1477
- uaDataPlatform: signals.navigator.uaDataPlatform,
1478
- uaDataBrands: signals.navigator.uaDataBrands
1479
- },
1480
- webview: signals.webview.kind
1481
- };
1482
- return stableStringify(stable);
1483
- }
1484
- async function computeCompositeHash(canonical) {
1485
- try {
1486
- return await sha256_128(canonical);
2278
+ destroy() {
2279
+ SDKLogger.log("Destroying");
2280
+ this.close();
2281
+ this.removeEventListeners();
2282
+ if (this.embedded && this.container && this.container.parentNode) {
2283
+ this.container.parentNode.removeChild(this.container);
2284
+ }
2285
+ else if (this.overlay && this.overlay.parentNode) {
2286
+ this.overlay.parentNode.removeChild(this.overlay);
2287
+ }
2288
+ this.overlay = null;
2289
+ this.container = null;
2290
+ this.iframe = null;
2291
+ this.loadingEl = null;
2292
+ this.confirmOverlay = null;
1487
2293
  }
1488
- catch {
1489
- // Environments without WebCrypto (very old browsers) fall back to a stable FNV-1a pair.
1490
- return `fnv-${fnv1a32(canonical)}${fnv1a32(`${canonical}:fallback`)}`;
2294
+ isOpen() {
2295
+ return this.state.isOpen;
2296
+ }
2297
+ isLoading() {
2298
+ return this.state.isLoading;
1491
2299
  }
1492
- }
1493
- async function buildPayload() {
1494
- const persistent = loadOrCreatePersistentId();
1495
- const navigatorSignals = collectNavigatorSignals();
1496
- const signals = {
1497
- platform: "web",
1498
- navigator: navigatorSignals,
1499
- webview: { kind: detectWebViewKind(navigatorSignals.userAgent) }
1500
- };
1501
- const compositeHash = await computeCompositeHash(canonicalizeSignals(signals));
1502
- return {
1503
- version: 2,
1504
- schema: "didit-fp-v2",
1505
- platform: "web",
1506
- collectedAt: new Date().toISOString(),
1507
- persistentId: persistent.id,
1508
- persistentIdSources: persistent.sources,
1509
- persistentIdWasCreated: persistent.wasCreated,
1510
- signals,
1511
- bot: detectBot(signals),
1512
- compositeHash
1513
- };
1514
- }
1515
- function isBrowserEnvironment() {
1516
- return typeof window !== "undefined" && typeof navigator !== "undefined" && typeof document !== "undefined";
1517
2300
  }
1518
2301
  /**
1519
- * Collects the device fingerprint. Resolves to null outside a browser
1520
- * environment (SSR, Node, workers) so callers degrade to a fingerprint-less
1521
- * request instead of sending junk signals. Never intended to throw into the
1522
- * submit path: callers still guard with .catch(() => null).
2302
+ * Every currently-open modal, oldest first. Used so a single Escape
2303
+ * keypress (or other document-level shortcut) only acts on the topmost
2304
+ * modal when multiple VerificationModal instances are open at once (e.g.
2305
+ * a transaction action modal stacked over the verification modal).
1523
2306
  */
1524
- async function getDeviceFingerprintPayload() {
1525
- if (!isBrowserEnvironment())
1526
- return null;
1527
- if (cachedPayload)
1528
- return cachedPayload;
1529
- if (!cachedPayloadPromise) {
1530
- cachedPayloadPromise = buildPayload().then((payload) => {
1531
- cachedPayload = payload;
1532
- return payload;
1533
- }, (error) => {
1534
- // Do not cache failures; a later call may succeed.
1535
- cachedPayloadPromise = null;
1536
- throw error;
1537
- });
1538
- }
1539
- return cachedPayloadPromise;
1540
- }
1541
- function buildFingerprintHeaders(payload) {
1542
- if (!payload)
1543
- return {};
1544
- const headers = { "X-Didit-FP-V2": "1" };
1545
- if (payload.persistentId)
1546
- headers["X-Didit-PID"] = payload.persistentId;
1547
- if (payload.compositeHash)
1548
- headers["X-Didit-FP-Hash"] = payload.compositeHash;
1549
- if (payload.signals.webview.kind)
1550
- headers["X-Didit-FP-Webview"] = payload.signals.webview.kind;
1551
- if (payload.bot.score)
1552
- headers["X-Didit-FP-Bot-Score"] = payload.bot.score.toFixed(2);
1553
- return headers;
1554
- }
2307
+ VerificationModal.openModals = [];
1555
2308
 
1556
2309
  const DEFAULT_TRANSACTION_BASE_URL = "https://verification.didit.me";
1557
2310
  const ACTION_POLL_INTERVAL_MS = 1500;
@@ -1854,6 +2607,23 @@
1854
2607
  return latest;
1855
2608
  }
1856
2609
 
2610
+ /**
2611
+ * Embedded mode renders inside an element that already exists on the
2612
+ * integrator's page. Without it the modal never shows anything (embedded mode
2613
+ * never activates the overlay), so the launch fails with a message the
2614
+ * integrator can act on instead of silently presenting nothing.
2615
+ */
2616
+ function assertEmbeddedHostExists(configuration) {
2617
+ if (!configuration?.embedded)
2618
+ return;
2619
+ const containerId = configuration.embeddedContainerId;
2620
+ if (!containerId) {
2621
+ throw new Error("Embedded mode requires embeddedContainerId: the id of the element that hosts the verification.");
2622
+ }
2623
+ if (typeof document === "undefined" || !document.getElementById(containerId)) {
2624
+ throw new Error(`Embedded container "#${containerId}" was not found in the page.`);
2625
+ }
2626
+ }
1857
2627
  class DiditSdk {
1858
2628
  static get shared() {
1859
2629
  if (!DiditSdk._instance) {
@@ -1913,17 +2683,20 @@
1913
2683
  this._modal.destroy();
1914
2684
  this._modal = null;
1915
2685
  }
1916
- this._modal = new VerificationModal(config, {
1917
- onClose: () => this.handleModalClose(),
1918
- onCloseConfirmed: () => this.handleModalCloseConfirmed(),
1919
- onMessage: (event) => this.handleVerificationEvent(event),
1920
- onIframeLoad: () => this.handleIframeLoad()
1921
- });
2686
+ // A new launch is not in an error state any more, whatever the last one did.
2687
+ this._errorMessage = undefined;
1922
2688
  try {
1923
2689
  const { url } = options;
1924
2690
  if (!url || typeof url !== "string") {
1925
2691
  throw new Error("Invalid options: url is required");
1926
2692
  }
2693
+ assertEmbeddedHostExists(config);
2694
+ this._modal = new VerificationModal(config, {
2695
+ onClose: () => this.handleModalClose(),
2696
+ onCloseConfirmed: () => this.handleModalCloseConfirmed(),
2697
+ onMessage: (event) => this.handleVerificationEvent(event),
2698
+ onIframeLoad: () => this.handleIframeLoad()
2699
+ });
1927
2700
  this._url = buildVerificationUrl(url, config);
1928
2701
  this.setState("loading");
1929
2702
  this.emitInternalEvent("didit:started", {});
@@ -1996,6 +2769,30 @@
1996
2769
  }
1997
2770
  return result;
1998
2771
  }
2772
+ /**
2773
+ * Queues an end-user event (sign-up, login, failed login, logout, password
2774
+ * reset, MFA, device change...) for Didit's event monitoring, so it appears
2775
+ * in the console tied to the same person as their verifications and
2776
+ * transactions. Returns the event id.
2777
+ *
2778
+ * The request is authenticated with a short-lived monitoring token minted by
2779
+ * your backend for that person (POST /v3/events/sdk-token/) and sent via the
2780
+ * X-Monitoring-Token header; the person always comes from the token. Events
2781
+ * are batched to /v1/events/batch/ with the device fingerprint attached, and
2782
+ * sent when 25 are waiting, every 5 seconds and when the page is hidden or
2783
+ * closed. Tune the queue with `configureEvents` and send right away with
2784
+ * `flush`, both exported by this package.
2785
+ *
2786
+ * @param options monitoringToken, the event and an optional baseUrl
2787
+ * (defaults to https://verification.didit.me).
2788
+ * @returns The event id: yours when you set event.eventId, otherwise a new UUID.
2789
+ * @throws {DiditEventError} "invalid_token" without a monitoringToken,
2790
+ * "validation" without an event category and action type.
2791
+ */
2792
+ submitEvent(options) {
2793
+ SDKLogger.log("Submitting event:", options?.event?.category, options?.event?.actionType);
2794
+ return submitEvent(options);
2795
+ }
1999
2796
  /**
2000
2797
  * Dismisses everything currently on screen in one deterministic call: a
2001
2798
  * pending transaction action modal is treated as an abort (no follow-up
@@ -2016,6 +2813,7 @@
2016
2813
  this._modal?.destroy();
2017
2814
  this._modal = null;
2018
2815
  this.reset();
2816
+ this.setState("idle");
2019
2817
  }
2020
2818
  async runTransactionAction(baseUrl, transactionToken, submitResult, onActionCompleted) {
2021
2819
  const generation = this._actionGeneration;
@@ -2131,6 +2929,7 @@
2131
2929
  const sessionData = this.buildSessionData();
2132
2930
  this._modal?.close();
2133
2931
  this.reset();
2932
+ this.setState("idle");
2134
2933
  const result = {
2135
2934
  type: "cancelled",
2136
2935
  session: sessionData
@@ -2151,6 +2950,11 @@
2151
2950
  }
2152
2951
  handleVerificationEvent(event) {
2153
2952
  SDKLogger.log("Verification event:", event);
2953
+ // Keep the session the flow told us about so a modal the user closes by
2954
+ // hand still reports the session it belongs to in the cancelled result.
2955
+ if (event.data?.sessionId) {
2956
+ this._sessionId = event.data.sessionId;
2957
+ }
2154
2958
  this.onEvent?.(event);
2155
2959
  switch (event.type) {
2156
2960
  case "didit:ready":
@@ -2206,6 +3010,7 @@
2206
3010
  if (this._configuration?.closeModalOnComplete) {
2207
3011
  this._modal?.close();
2208
3012
  this.reset();
3013
+ this.setState("idle");
2209
3014
  }
2210
3015
  const result = {
2211
3016
  type: "completed",
@@ -2218,6 +3023,7 @@
2218
3023
  const sessionData = this.buildSessionData(event.data);
2219
3024
  this._modal?.close();
2220
3025
  this.reset();
3026
+ this.setState("idle");
2221
3027
  const result = {
2222
3028
  type: "cancelled",
2223
3029
  session: sessionData
@@ -2236,10 +3042,14 @@
2236
3042
  else {
2237
3043
  verificationError = createVerificationError("unknown", "An unknown error occurred");
2238
3044
  }
2239
- this._errorMessage = verificationError.message;
2240
- this.setState("error");
2241
3045
  this._modal?.close();
3046
+ this._modal = null;
3047
+ // Clear what the failed launch left behind, then report the error as the
3048
+ // state the SDK is in: reset() alone would leave callers reading "idle"
3049
+ // with no error message right after onStateChange("error").
2242
3050
  this.reset();
3051
+ this._errorMessage = verificationError.message;
3052
+ this.setState("error");
2243
3053
  const result = {
2244
3054
  type: "failed",
2245
3055
  error: verificationError
@@ -2255,7 +3065,6 @@
2255
3065
  }
2256
3066
  }
2257
3067
  reset() {
2258
- this._state = "idle";
2259
3068
  this._sessionId = undefined;
2260
3069
  this._url = undefined;
2261
3070
  this._errorMessage = undefined;
@@ -2274,11 +3083,18 @@
2274
3083
  }
2275
3084
  DiditSdk._instance = null;
2276
3085
 
3086
+ exports.DEFAULT_EVENTS_BASE_URL = DEFAULT_EVENTS_BASE_URL;
2277
3087
  exports.DEFAULT_TRANSACTION_BASE_URL = DEFAULT_TRANSACTION_BASE_URL;
3088
+ exports.DiditEventError = DiditEventError;
2278
3089
  exports.DiditSdk = DiditSdk;
2279
3090
  exports.DiditTransactionError = DiditTransactionError;
2280
3091
  exports.SDK_VERSION = SDK_VERSION;
3092
+ exports.buildFingerprintHeaders = buildFingerprintHeaders;
3093
+ exports.configureEvents = configureEvents;
2281
3094
  exports.default = DiditSdk;
3095
+ exports.flush = flush;
3096
+ exports.getDeviceFingerprintPayload = getDeviceFingerprintPayload;
3097
+ exports.submitEvent = submitEvent;
2282
3098
 
2283
3099
  Object.defineProperty(exports, '__esModule', { value: true });
2284
3100