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