@didit-protocol/sdk-web 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,27 +1,35 @@
1
1
  /**
2
- * Didit SDK for Web v0.5.1
2
+ * Didit SDK for Web v0.6.0
3
3
  * (c) 2026 Didit
4
4
  * @license MIT
5
5
  */
6
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:
7
+ * What the navigator alone says about automation.
12
8
  *
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
9
+ * The score is the strongest flag found, not a count: one conclusive signal is not diluted because
10
+ * the other checks came back clean. Only what a browser never shows to a person (a driver's
11
+ * `navigator.webdriver`, a headless or automation user agent) weighs 0.8 or more.
15
12
  */
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;
13
+ function detectBotFromNavigator(signals) {
14
+ const flags = [];
15
+ const userAgent = signals.userAgent;
16
+ let score = 0;
17
+ if (typeof navigator !== "undefined" && navigator.webdriver) {
18
+ flags.push("webdriver");
19
+ score = 0.9;
20
+ }
21
+ if (/HeadlessChrome|PhantomJS|Selenium|puppeteer|playwright/i.test(userAgent)) {
22
+ flags.push("headless-ua");
23
+ score = 0.9;
24
+ }
25
+ if (signals.uaDataMobile === false && /Android|iPhone|iPad/i.test(userAgent)) {
26
+ flags.push("ua-mobile-mismatch");
27
+ score = score || 0.3;
28
+ }
29
+ return { score, flags };
30
+ }
31
+
20
32
  const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
21
- let memoryPersistentId = null;
22
- let cachedPayload = null;
23
- let pendingPayload = null;
24
- let cachedPayloadPromise = null;
25
33
  function bytesToBase64Url(bytes) {
26
34
  let output = "";
27
35
  let i = 0;
@@ -45,12 +53,40 @@ function bytesToBase64Url(bytes) {
45
53
  }
46
54
  return output;
47
55
  }
56
+ function toBytes(input) {
57
+ if (typeof input === "string") {
58
+ return new TextEncoder().encode(input);
59
+ }
60
+ return input;
61
+ }
62
+ async function sha256Bytes(input) {
63
+ if (typeof crypto === "undefined" || !crypto.subtle) {
64
+ throw new Error("WebCrypto SubtleCrypto is not available");
65
+ }
66
+ const bytes = toBytes(input);
67
+ // crypto.subtle.digest needs a BufferSource; copy into a fresh ArrayBuffer-backed view
68
+ // so we are not handing over a SharedArrayBuffer-typed slice. The view itself is passed, not
69
+ // its buffer: a bare ArrayBuffer made in another realm (a test runner's sandbox on Node 20) is
70
+ // refused as "not an ArrayBuffer", and the hash would be left out; a view is accepted everywhere.
71
+ const view = new Uint8Array(bytes.byteLength);
72
+ view.set(bytes);
73
+ const digest = await crypto.subtle.digest("SHA-256", view);
74
+ return new Uint8Array(digest);
75
+ }
76
+ // SHA-256 truncated to the leading 128 bits, base64url-encoded (22 chars).
77
+ // Used as the composite fingerprint hash. 128 bits keeps the birthday boundary
78
+ // at 2^64 — collision-safe at any conceivable session volume.
79
+ async function sha256_128(input) {
80
+ const bytes = await sha256Bytes(input);
81
+ return bytesToBase64Url(bytes.slice(0, 16));
82
+ }
48
83
  function randomBytes(length) {
49
84
  if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
50
85
  const buffer = new Uint8Array(length);
51
86
  crypto.getRandomValues(buffer);
52
87
  return buffer;
53
88
  }
89
+ // Math.random fallback — only reached in environments without WebCrypto.
54
90
  const fallback = new Uint8Array(length);
55
91
  for (let i = 0; i < length; i++) {
56
92
  fallback[i] = Math.floor(Math.random() * 256);
@@ -60,27 +96,13 @@ function randomBytes(length) {
60
96
  function randomBase64Url(byteLength) {
61
97
  return bytesToBase64Url(randomBytes(byteLength));
62
98
  }
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");
68
- }
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);
81
- }
82
- return (hash >>> 0).toString(16).padStart(8, "0");
83
- }
99
+
100
+ /**
101
+ * Which fields the composite hash reads. It travels inside `signals`, the part of the payload
102
+ * Didit stores, so a stored hash can be told apart from one of an earlier version. A change to
103
+ * `canonicalNavigator` or to the full canonical form changes every device's hash once: raise it.
104
+ */
105
+ const COMPOSITE_HASH_VERSION = 4;
84
106
  function stableStringify(value) {
85
107
  if (value === null || value === undefined)
86
108
  return JSON.stringify(value ?? null);
@@ -93,200 +115,391 @@ function stableStringify(value) {
93
115
  }
94
116
  return JSON.stringify(value);
95
117
  }
96
- function isValidPersistentId(value) {
97
- return typeof value === "string" && /^[A-Za-z0-9_-]{20,32}$/.test(value);
118
+ /**
119
+ * The user agent without its version numbers: `Chrome/147.0.0.0`, `Version/17.5`,
120
+ * `Build/UP1A.231005.007`, `iPhone OS 17_5_1`, `Android 14`. They change with every browser and
121
+ * system update while the device stays the same; what is left names the browser, the system and,
122
+ * where the browser still gives it, the device model (`SM-S918B`, `2312DRA50G`).
123
+ */
124
+ function userAgentWithoutVersions(userAgent) {
125
+ return userAgent
126
+ .replace(/\/[\w.]+/g, "")
127
+ .replace(/\d+(?:[._]\d+)+/g, "")
128
+ .replace(/\bAndroid \d+/g, "Android");
98
129
  }
99
- function readLocalStorageId() {
100
- try {
101
- if (typeof localStorage === "undefined")
102
- return null;
103
- const value = localStorage.getItem(PERSISTENT_ID_STORAGE_KEY);
104
- return isValidPersistentId(value) ? value : null;
105
- }
106
- catch {
107
- return null;
108
- }
130
+ /**
131
+ * The browser's brand names without their versions. The placeholder brand Chromium adds
132
+ * ("Not_A Brand", "Not;A=Brand", ...) is left out: its spelling changes from one version to the next.
133
+ */
134
+ function brandNames(brands) {
135
+ return brands
136
+ .map(brandName)
137
+ .filter((name) => !isPlaceholderBrand(name))
138
+ .sort();
109
139
  }
110
- function writeLocalStorageId(id) {
111
- try {
112
- if (typeof localStorage === "undefined")
113
- return;
114
- localStorage.setItem(PERSISTENT_ID_STORAGE_KEY, id);
115
- }
116
- catch {
117
- // Storage may be blocked (private mode, storage policies); cookie layer still applies.
118
- }
140
+ /**
141
+ * `Google Chrome:147` is `Google Chrome`. The version follows the last colon, not the first: the
142
+ * placeholder has a colon of its own in two Chromium versions out of eleven (`Not:A-Brand:99`,
143
+ * `Not(A:Brand:8`). Cut at the first one it left `Not` or `Not(A` in the list as a brand of its
144
+ * own, and the hash changed with the browser's next update (version 3 did that).
145
+ */
146
+ function brandName(brand) {
147
+ const colon = brand.lastIndexOf(":");
148
+ return colon < 0 ? brand : brand.slice(0, colon);
149
+ }
150
+ /** "not" with "brand" somewhere after it, in any case. Two searches, so a long name costs its length once. */
151
+ function isPlaceholderBrand(name) {
152
+ const lower = name.toLowerCase();
153
+ const not = lower.indexOf("not");
154
+ return not >= 0 && lower.indexOf("brand", not + 3) >= 0;
155
+ }
156
+ /**
157
+ * The navigator part of the canonical form: what describes the device and its browser and reads
158
+ * the same on every visit. No version numbers (a browser update is not another device) and the
159
+ * screen shorter side first (a phone turned on its side is not another device).
160
+ *
161
+ * The light fingerprint hashes this and the webview kind; the full one adds the graphics, font,
162
+ * math and API families (`canonicalize` in compose.ts). Both go through this one function.
163
+ */
164
+ function canonicalNavigator(navigator) {
165
+ const screen = [navigator.screenWidth, navigator.screenHeight].sort((a, b) => (a ?? 0) - (b ?? 0));
166
+ return {
167
+ ua: userAgentWithoutVersions(navigator.userAgent),
168
+ platform: navigator.platform,
169
+ lang: navigator.language.split("-")[0],
170
+ languages: [...navigator.languages].sort(),
171
+ concurrency: navigator.hardwareConcurrencyQuantized,
172
+ memory: navigator.deviceMemory,
173
+ maxTouch: navigator.maxTouchPoints,
174
+ dpr: navigator.devicePixelRatio,
175
+ screen,
176
+ colorDepth: navigator.colorDepth,
177
+ timeZone: navigator.timeZone,
178
+ uaDataPlatform: navigator.uaDataPlatform,
179
+ uaDataBrands: brandNames(navigator.uaDataBrands),
180
+ };
119
181
  }
120
- function readCookieId() {
182
+ /**
183
+ * The composite hash of a canonical form: SHA-256, first 128 bits, base64url. Empty where the
184
+ * browser has no WebCrypto (a page served without TLS): the hash is then left out, never replaced
185
+ * by a weaker one that would read as another device.
186
+ */
187
+ async function compositeHashOf(canonical) {
121
188
  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;
189
+ return await sha256_128(stableStringify(canonical));
133
190
  }
134
191
  catch {
135
- return null;
192
+ return "";
136
193
  }
137
194
  }
138
- function writeCookieId(id) {
195
+
196
+ /**
197
+ * The device headers a Didit API reads. They carry the identifiers only; the signals themselves
198
+ * travel in the request body (`fingerprint_v2`), which has no size limit a proxy would enforce.
199
+ */
200
+ function payloadToHeaders(payload) {
201
+ if (!payload)
202
+ return {};
203
+ const headers = { "X-Didit-FP-V2": "1" };
204
+ if (payload.persistentId)
205
+ headers["X-Didit-PID"] = payload.persistentId;
206
+ if (payload.compositeHash)
207
+ headers["X-Didit-FP-Hash"] = payload.compositeHash;
208
+ if (payload.legacyCompatibilityHash)
209
+ headers["X-Didit-FP-Legacy"] = payload.legacyCompatibilityHash;
210
+ if (payload.signals?.webview?.kind)
211
+ headers["X-Didit-FP-Webview"] = payload.signals.webview.kind;
212
+ if (payload.bot?.score)
213
+ headers["X-Didit-FP-Bot-Score"] = payload.bot.score.toFixed(2);
214
+ return headers;
215
+ }
216
+
217
+ function safe(read, fallback) {
139
218
  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("; ");
219
+ const value = read();
220
+ return value === undefined ? fallback : value;
152
221
  }
153
222
  catch {
154
- // Cookies may be blocked; localStorage layer still applies.
223
+ return fallback;
155
224
  }
156
225
  }
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 };
226
+ function quantizeConcurrency(value) {
227
+ if (value === null)
228
+ return null;
229
+ if (value <= 1)
230
+ return 1;
231
+ if (value <= 2)
232
+ return 2;
233
+ if (value <= 4)
234
+ return 4;
235
+ if (value <= 6)
236
+ return 6;
237
+ if (value <= 8)
238
+ return 8;
239
+ if (value <= 12)
240
+ return 12;
241
+ if (value <= 16)
242
+ return 16;
243
+ return 20;
244
+ }
245
+ function normalizeUserAgent(ua) {
246
+ // Collapse fine-grained version numbers (147.0.7727.137 → 147) so two installs of the same major version match.
247
+ return ua.replace(/(\d+)(\.\d+)+/g, "$1");
187
248
  }
188
249
  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;
250
+ // Outside a browser there is no navigator: every read below then falls back to its empty value.
251
+ const present = typeof navigator !== "undefined";
252
+ const nav = (present ? navigator : {});
253
+ const userAgent = safe(() => nav.userAgent || "", "");
254
+ const concurrency = safe(() => nav.hardwareConcurrency ?? null, null);
255
+ const connection = safe(() => nav.connection || nav.mozConnection || nav.webkitConnection || null, null);
256
+ const screenObj = present && typeof screen !== "undefined" ? screen : null;
257
+ const uaData = safe(() => nav.userAgentData, undefined);
202
258
  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,
259
+ userAgent,
260
+ userAgentNormalized: normalizeUserAgent(userAgent),
261
+ platform: safe(() => nav.platform || "", ""),
262
+ language: safe(() => nav.language || "", ""),
263
+ languages: safe(() => (nav.languages ? [...nav.languages] : []), []),
264
+ hardwareConcurrency: concurrency,
265
+ hardwareConcurrencyQuantized: quantizeConcurrency(concurrency),
266
+ deviceMemory: safe(() => nav.deviceMemory ?? null, null),
267
+ maxTouchPoints: safe(() => nav.maxTouchPoints ?? null, null),
268
+ devicePixelRatio: safe(() => (present && typeof window !== "undefined" ? (window.devicePixelRatio ?? null) : null), null),
269
+ screenWidth: screenObj?.width ?? null,
270
+ screenHeight: screenObj?.height ?? null,
271
+ availWidth: screenObj?.availWidth ?? null,
272
+ availHeight: screenObj?.availHeight ?? null,
273
+ colorDepth: screenObj?.colorDepth ?? null,
274
+ pixelDepth: screenObj?.pixelDepth ?? null,
275
+ orientation: screenObj && "orientation" in screenObj ? (screenObj.orientation?.type ?? null) : null,
276
+ timeZone: safe(() => (present && typeof Intl !== "undefined" && Intl.DateTimeFormat ? Intl.DateTimeFormat().resolvedOptions().timeZone || "" : ""), ""),
277
+ connectionEffectiveType: connection?.effectiveType ?? null,
278
+ connectionDownlink: connection?.downlink ?? null,
279
+ uaDataMobile: uaData?.mobile ?? null,
218
280
  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}`) : []
281
+ uaDataBrands: uaData?.brands ? uaData.brands.map((b) => `${b.brand}:${b.version}`).sort() : [],
282
+ cookieEnabled: safe(() => nav.cookieEnabled ?? null, null),
283
+ doNotTrack: safe(() => nav.doNotTrack ?? null, null),
221
284
  };
222
285
  }
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";
286
+
287
+ function detectWebViewContext(userAgent) {
288
+ if (!userAgent) {
289
+ return { kind: "browser", hostAppVersion: null, isStandaloneBrowser: true };
290
+ }
291
+ const ua = userAgent;
292
+ const waMatch = ua.match(/WA(?:4[A]|4iOS)\/([\d.]+)/);
293
+ if (waMatch)
294
+ return { kind: "whatsapp", hostAppVersion: waMatch[1], isStandaloneBrowser: false };
295
+ // Google app (iOS/Android) in-app browser. On iOS its WKWebView exposes no
296
+ // navigator.mediaDevices at all, so no capture is ever possible there.
297
+ const gsaMatch = ua.match(/GSA\/([\d.]+)/);
298
+ if (gsaMatch)
299
+ return { kind: "gsa", hostAppVersion: gsaMatch[1], isStandaloneBrowser: false };
300
+ const igMatch = ua.match(/Instagram\s+([\d.]+)/);
301
+ if (igMatch)
302
+ return { kind: "instagram", hostAppVersion: igMatch[1], isStandaloneBrowser: false };
303
+ if (/FBAN|FBAV/.test(ua)) {
304
+ const fbVer = ua.match(/FBAV\/([\d.]+)/);
305
+ return { kind: "facebook", hostAppVersion: fbVer?.[1] ?? null, isStandaloneBrowser: false };
306
+ }
307
+ if (/MessengerLiteForiOS|MessengerForiOS|FB_IAB\/Messenger/.test(ua)) {
308
+ return { kind: "messenger", hostAppVersion: null, isStandaloneBrowser: false };
309
+ }
310
+ const ttMatch = ua.match(/(?:musical_ly|TikTok|trill)_(\d+)/i);
311
+ if (ttMatch)
312
+ return { kind: "tiktok", hostAppVersion: ttMatch[1], isStandaloneBrowser: false };
313
+ const lineMatch = ua.match(/Line\/([\d.]+)/);
314
+ if (lineMatch)
315
+ return { kind: "line", hostAppVersion: lineMatch[1], isStandaloneBrowser: false };
316
+ if (/MicroMessenger/.test(ua)) {
317
+ const wcVer = ua.match(/MicroMessenger\/([\d.]+)/);
318
+ return { kind: "wechat", hostAppVersion: wcVer?.[1] ?? null, isStandaloneBrowser: false };
319
+ }
320
+ if (/Telegram/i.test(ua)) {
321
+ return { kind: "telegram", hostAppVersion: null, isStandaloneBrowser: false };
322
+ }
323
+ if (/Twitter|TwitterAndroid/i.test(ua)) {
324
+ return { kind: "twitter", hostAppVersion: null, isStandaloneBrowser: false };
325
+ }
326
+ if (/LinkedInApp/i.test(ua)) {
327
+ return { kind: "linkedin", hostAppVersion: null, isStandaloneBrowser: false };
328
+ }
329
+ if (/Snapchat/i.test(ua)) {
330
+ return { kind: "snapchat", hostAppVersion: null, isStandaloneBrowser: false };
331
+ }
332
+ if (/\bwv\)|\bWebView\b/i.test(ua)) {
333
+ return { kind: "generic-wv", hostAppVersion: null, isStandaloneBrowser: false };
334
+ }
335
+ return { kind: "browser", hostAppVersion: null, isStandaloneBrowser: true };
336
+ }
337
+
338
+ const STORAGE_KEY = "didit-pid-v1";
339
+ const COOKIE_NAME = "didit_pid";
340
+ const COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365 * 2;
341
+ const PERSISTENT_ID_BYTE_LENGTH = 16;
342
+ let memoryFallback = null;
343
+ function isValidPersistentId(value) {
344
+ return typeof value === "string" && /^[A-Za-z0-9_-]{20,32}$/.test(value);
345
+ }
346
+ const localStorageLayer = {
347
+ source: "localStorage",
348
+ read() {
349
+ try {
350
+ if (typeof localStorage === "undefined")
351
+ return null;
352
+ const value = localStorage.getItem(STORAGE_KEY);
353
+ return isValidPersistentId(value) ? value : null;
354
+ }
355
+ catch {
356
+ // Storage may be blocked (private mode, storage policies): the other layers still apply.
357
+ return null;
358
+ }
359
+ },
360
+ write(id) {
361
+ try {
362
+ if (typeof localStorage === "undefined")
363
+ return false;
364
+ localStorage.setItem(STORAGE_KEY, id);
365
+ return true;
366
+ }
367
+ catch {
368
+ return false;
369
+ }
370
+ },
371
+ };
372
+ const cookieLayer = {
373
+ source: "cookie",
374
+ read() {
375
+ try {
376
+ if (typeof document === "undefined" || !document.cookie)
377
+ return null;
378
+ const prefix = `${COOKIE_NAME}=`;
379
+ for (const part of document.cookie.split(";")) {
380
+ const trimmed = part.trim();
381
+ if (trimmed.startsWith(prefix)) {
382
+ const value = decodeURIComponent(trimmed.substring(prefix.length));
383
+ return isValidPersistentId(value) ? value : null;
384
+ }
385
+ }
386
+ return null;
387
+ }
388
+ catch {
389
+ return null;
390
+ }
391
+ },
392
+ write(id) {
393
+ try {
394
+ if (typeof document === "undefined")
395
+ return false;
396
+ const isSecure = typeof location !== "undefined" && location.protocol === "https:";
397
+ const attributes = [
398
+ `${COOKIE_NAME}=${encodeURIComponent(id)}`,
399
+ "Path=/",
400
+ `Max-Age=${COOKIE_MAX_AGE_SECONDS}`,
401
+ "SameSite=Lax",
402
+ ];
403
+ if (isSecure)
404
+ attributes.push("Secure");
405
+ document.cookie = attributes.join("; ");
406
+ return true;
407
+ }
408
+ catch {
409
+ return false;
410
+ }
411
+ },
412
+ };
413
+ /** The layers every browser answers at once. `storage-layers.ts` adds the ones that have to wait. */
414
+ const SYNC_STORAGE_LAYERS = [localStorageLayer, cookieLayer];
415
+ /** The value most layers agree on; on a tie, the layer listed first. */
416
+ function pickWinner(candidates) {
417
+ const tally = new Map();
418
+ for (const { id, source } of candidates) {
419
+ const existing = tally.get(id);
420
+ if (existing) {
421
+ existing.push(source);
422
+ }
423
+ else {
424
+ tally.set(id, [source]);
425
+ }
229
426
  }
230
- if (/iPhone|iPad|iPod/.test(userAgent) && !/Safari\//.test(userAgent) && !/CriOS|FxiOS|EdgiOS/.test(userAgent)) {
231
- return "ios-webview";
427
+ let winner = candidates[0].id;
428
+ let winnerCount = 0;
429
+ for (const [id, sources] of tally) {
430
+ if (sources.length > winnerCount) {
431
+ winnerCount = sources.length;
432
+ winner = id;
433
+ }
232
434
  }
233
- return "browser";
435
+ return { id: winner, sources: tally.get(winner) || [] };
234
436
  }
235
- function detectBot(signals) {
236
- const flags = [];
237
- const userAgent = signals.navigator.userAgent;
238
- if (typeof navigator !== "undefined" && navigator.webdriver) {
239
- flags.push("webdriver");
437
+ /**
438
+ * From what each layer answered: the id this browser profile is known by (the value most layers
439
+ * agree on, the one kept in memory when storage is blocked, or a new random one), and the layers
440
+ * that did not have it, for the caller to write it back to.
441
+ */
442
+ function choosePersistentId(layers, values, embedderId) {
443
+ const candidates = [];
444
+ values.forEach((value, index) => {
445
+ if (value)
446
+ candidates.push({ id: value, source: layers[index].source });
447
+ });
448
+ // No layer has an id, and the page that embeds this one passed its own: this visit goes by it.
449
+ // It is not written to any layer and not kept in memory: the embedding page is where it lives,
450
+ // and a value another page supplies never becomes this origin's stored id.
451
+ if (!candidates.length && isValidPersistentId(embedderId)) {
452
+ return { result: { id: embedderId, sources: ["embedder"], wasCreated: false }, stale: [] };
240
453
  }
241
- if (/HeadlessChrome|PhantomJS|Selenium|puppeteer|playwright/i.test(userAgent)) {
242
- flags.push("headless-ua");
454
+ if (!candidates.length && memoryFallback && isValidPersistentId(memoryFallback)) {
455
+ candidates.push({ id: memoryFallback, source: "memory" });
243
456
  }
244
- if (signals.navigator.uaDataMobile === false && /Android|iPhone|iPad/i.test(userAgent)) {
245
- flags.push("ua-mobile-mismatch");
457
+ let result;
458
+ if (candidates.length) {
459
+ const winner = pickWinner(candidates);
460
+ result = { id: winner.id, sources: winner.sources, wasCreated: false };
246
461
  }
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);
462
+ else {
463
+ result = { id: randomBase64Url(PERSISTENT_ID_BYTE_LENGTH), sources: ["fresh"], wasCreated: true };
276
464
  }
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`)}`;
465
+ memoryFallback = result.id;
466
+ return { result, stale: layers.filter((_, index) => values[index] !== result.id) };
467
+ }
468
+ /**
469
+ * The stored id from the layers that answer at once (localStorage and a cookie), written back to
470
+ * the one that missed it. `loadOrCreatePersistentIdFromBrowserStorage` (storage-layers.ts) reads
471
+ * the slow layers too.
472
+ */
473
+ function loadOrCreatePersistentId() {
474
+ const layers = SYNC_STORAGE_LAYERS;
475
+ const { result, stale } = choosePersistentId(layers, layers.map((layer) => layer.read()));
476
+ stale.forEach((layer) => layer.write(result.id));
477
+ return result;
478
+ }
479
+ /**
480
+ * The id this page already keeps, or null. It only reads: nothing is created and nothing is
481
+ * written, so asking never adds a cookie or a storage entry to a site that had none.
482
+ */
483
+ function readStoredPersistentId() {
484
+ for (const layer of SYNC_STORAGE_LAYERS) {
485
+ const value = layer.read();
486
+ if (value)
487
+ return value;
280
488
  }
489
+ return null;
281
490
  }
491
+
492
+ let provider = null;
493
+ let cachedPayload = null;
494
+ let pendingPayload = null;
495
+ let cachedPayloadPromise = null;
496
+ /** Raised when the source of the payload changes, so a collection started before it is recognised. */
497
+ let generation = 0;
282
498
  async function buildPayload() {
499
+ // These layers answer at once, so the id is in the payload before anything is awaited.
283
500
  const persistent = loadOrCreatePersistentId();
284
501
  const navigatorSignals = collectNavigatorSignals();
285
- const signals = {
286
- platform: "web",
287
- navigator: navigatorSignals,
288
- webview: { kind: detectWebViewKind(navigatorSignals.userAgent) }
289
- };
502
+ const webview = detectWebViewContext(navigatorSignals.userAgent);
290
503
  const payload = {
291
504
  version: 2,
292
505
  schema: "didit-fp-v2",
@@ -295,14 +508,24 @@ async function buildPayload() {
295
508
  persistentId: persistent.id,
296
509
  persistentIdSources: persistent.sources,
297
510
  persistentIdWasCreated: persistent.wasCreated,
298
- signals,
299
- bot: detectBot(signals),
300
- compositeHash: ""
511
+ signals: {
512
+ platform: "web",
513
+ tier: "lite",
514
+ compositeHashVersion: COMPOSITE_HASH_VERSION,
515
+ navigator: navigatorSignals,
516
+ webview,
517
+ },
518
+ bot: detectBotFromNavigator(navigatorSignals),
519
+ compositeHash: "",
301
520
  };
302
521
  // Keep all synchronously collected context available during the native hash.
303
522
  // An empty hash is omitted from headers, never replaced with a different identity.
304
523
  pendingPayload = payload;
305
- return { ...payload, compositeHash: await computeCompositeHash(canonicalizeSignals(signals)) };
524
+ const compositeHash = await compositeHashOf({
525
+ navigator: canonicalNavigator(navigatorSignals),
526
+ webview: webview.kind,
527
+ });
528
+ return { ...payload, compositeHash };
306
529
  }
307
530
  function isBrowserEnvironment() {
308
531
  return typeof window !== "undefined" && typeof navigator !== "undefined" && typeof document !== "undefined";
@@ -319,10 +542,18 @@ async function getDeviceFingerprintPayload() {
319
542
  if (cachedPayload)
320
543
  return cachedPayload;
321
544
  if (!cachedPayloadPromise) {
322
- cachedPayloadPromise = buildPayload().then((payload) => {
545
+ const started = generation;
546
+ cachedPayloadPromise = (provider ? provider.get() : buildPayload()).then((payload) => {
547
+ // The source changed while this was being collected (`enableDeviceIntelligence()` called
548
+ // with the lite collection still running): its result must not become the cached payload,
549
+ // and whoever waited for it gets the payload of the source that replaced it.
550
+ if (started !== generation)
551
+ return getDeviceFingerprintPayload();
323
552
  cachedPayload = payload;
324
553
  return payload;
325
554
  }, (error) => {
555
+ if (started !== generation)
556
+ return getDeviceFingerprintPayload();
326
557
  // Do not cache failures; a later call may succeed.
327
558
  cachedPayloadPromise = null;
328
559
  throw error;
@@ -332,22 +563,27 @@ async function getDeviceFingerprintPayload() {
332
563
  }
333
564
  /** Internal exit snapshot: never waits for WebCrypto or changes the cached payload. */
334
565
  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;
566
+ return cachedPayload ?? (provider ? provider.peek() : pendingPayload);
350
567
  }
568
+ /**
569
+ * Makes another collector the source of the fingerprint this entry sends (null: back to the lite
570
+ * one). `enableDeviceIntelligence()` of `@didit-protocol/signals/device` calls it; nothing else should.
571
+ */
572
+ function setDeviceSignalsProvider(next) {
573
+ provider = next;
574
+ generation += 1;
575
+ cachedPayload = null;
576
+ pendingPayload = null;
577
+ cachedPayloadPromise = null;
578
+ }
579
+ /** The device headers a Didit API reads from the payload. */
580
+ const buildFingerprintHeaders = payloadToHeaders;
581
+ /**
582
+ * The device id this page already keeps for Didit, or null when it keeps none. It never creates
583
+ * one: `@didit-protocol/sdk-web` hands it to the verification it opens, so a site that sends no
584
+ * events, transactions or sign-ins gets no cookie and no storage entry from being asked.
585
+ */
586
+ const getStoredDeviceId = readStoredPersistentId;
351
587
 
352
588
  const DEFAULT_EVENTS_BASE_URL = "https://verification.didit.me";
353
589
  const BATCH_PATH = "/v1/events/batch/";
@@ -361,6 +597,8 @@ const KEEPALIVE_BUDGET_BYTES = 64 * 1024;
361
597
  const NEVER_DROPPED = /^(security|payment|dispute|responsible_gambling)\.|^gameplay\.(bet_placed|bet_settled|p2p_settlement)$/;
362
598
  const LOW_VALUE = /^session\.(page_view|sdk_heartbeat|sdk_loaded|device_seen|bot_signal_observed)$|^bonus\.promotion_viewed$|^affiliate\.referral_clicked$/;
363
599
  const PRIORITY_NEVER_DROPPED = 2;
600
+ /** What `fetch` accepts as a header value: no control character but the tab, nothing above U+00FF. */
601
+ const HEADER_VALUE = /^[\t\x20-\x7e\x80-\xff]+$/;
364
602
  /**
365
603
  * Typed error for events Didit refused or the SDK had to drop. Thrown by
366
604
  * submitEvent for a missing token or event, otherwise delivered to the
@@ -391,6 +629,16 @@ let chain = Promise.resolve();
391
629
  let listening = false;
392
630
  let exiting = false;
393
631
  let keepaliveBytes = 0;
632
+ /**
633
+ * `value` without the slashes it ends with. A loop, not a regular expression: `/\/+$/` rescans a
634
+ * long run of slashes from every one of them.
635
+ */
636
+ function withoutTrailingSlashes(value) {
637
+ let end = value.length;
638
+ while (end > 0 && value.charCodeAt(end - 1) === 47)
639
+ end -= 1;
640
+ return value.slice(0, end);
641
+ }
394
642
  function isRecord(value) {
395
643
  return value !== null && typeof value === "object" && !Array.isArray(value);
396
644
  }
@@ -698,7 +946,7 @@ function listen() {
698
946
  */
699
947
  function configureEvents(configuration) {
700
948
  const next = { ...settings, ...compact$1({ ...configuration }) };
701
- next.baseUrl = next.baseUrl.replace(/\/+$/, "");
949
+ next.baseUrl = withoutTrailingSlashes(next.baseUrl);
702
950
  next.batchSize = Math.min(Math.max(1, Math.floor(next.batchSize)), MAX_BATCH_EVENTS);
703
951
  next.flushIntervalMs = Math.max(0, next.flushIntervalMs);
704
952
  next.maxQueueSize = Math.max(1, Math.floor(next.maxQueueSize));
@@ -718,11 +966,17 @@ function configureEvents(configuration) {
718
966
  * environment has no fetch.
719
967
  */
720
968
  function submitEvent(options) {
721
- const token = options?.monitoringToken;
969
+ // Without the white space around it, as `fetch` sends a header value.
970
+ const token = typeof options?.monitoringToken === "string" ? options.monitoringToken.trim() : "";
722
971
  const event = options?.event;
723
- if (!token || typeof token !== "string") {
972
+ if (!token) {
724
973
  throw new DiditEventError("invalid_token", "monitoringToken is required.");
725
974
  }
975
+ // A line break or a NUL inside it, or a character above U+00FF, makes `fetch` throw before any
976
+ // request is made. Queued, such an event looked like a network failure and was retried forever.
977
+ if (!HEADER_VALUE.test(token)) {
978
+ throw new DiditEventError("invalid_token", "monitoringToken is not a value a header can carry.");
979
+ }
726
980
  if (!isRecord(event) || !event.category || typeof event.actionType !== "string" || !event.actionType.trim()) {
727
981
  throw new DiditEventError("validation", "event.category and event.actionType are required.");
728
982
  }
@@ -741,7 +995,7 @@ function submitEvent(options) {
741
995
  // UTF-8 length; JSON.stringify never leaves a lone surrogate for encodeURIComponent to reject.
742
996
  bytes: byteLength(json),
743
997
  token,
744
- url: `${(options.baseUrl ?? settings.baseUrl).replace(/\/+$/, "")}${BATCH_PATH}`,
998
+ url: `${withoutTrailingSlashes(options.baseUrl ?? settings.baseUrl)}${BATCH_PATH}`,
745
999
  priority: NEVER_DROPPED.test(kind) ? PRIORITY_NEVER_DROPPED : LOW_VALUE.test(kind) ? 0 : 1,
746
1000
  sending: false
747
1001
  });
@@ -787,12 +1041,14 @@ const CSS_CLASSES = {
787
1041
  closeIcon: "didit-close-icon",
788
1042
  closeIconLegacy: "didit-close-icon-legacy",
789
1043
  flowSized: "didit-flow-sized",
1044
+ sizeAnimated: "didit-size-animated",
790
1045
  loading: "didit-loading",
791
1046
  confirmOverlay: "didit-confirm-overlay",
792
1047
  confirmBox: "didit-confirm-box",
793
- embedded: "didit-embedded"
1048
+ embedded: "didit-embedded",
1049
+ curtain: "didit-modal-curtain"
794
1050
  };
795
- const SDK_VERSION = "0.5.1";
1051
+ const SDK_VERSION = "0.6.0";
796
1052
  /**
797
1053
  * The permissions the verification iframe gets, in a modal and embedded:
798
1054
  * camera and microphone for capture, clipboard-write for the flow's copy
@@ -818,9 +1074,16 @@ const PRESENTATION_QUERY_PARAMS = {
818
1074
  presentation: "sdk_presentation",
819
1075
  closeButton: "sdk_close_button"
820
1076
  };
1077
+ /**
1078
+ * The verification-URL query parameter that carries the device id this page
1079
+ * already keeps for Didit, when it keeps one. A browser gives the flow in the
1080
+ * frame storage of its own, apart from this page's, so without it a
1081
+ * verification and this site's events never share a device id.
1082
+ */
1083
+ const DEVICE_ID_QUERY_PARAM = "sdk_device_id";
821
1084
  /**
822
1085
  * 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
1086
+ * `data: { contentHeight, colorScheme?, dir?, kind? }` (`kind` is `handoff` or `step`, `step` when missing). The modal then grows to the
824
1087
  * handoff card on a computer and follows the content height in a narrow
825
1088
  * window. Handled by the modal and never delivered to `onEvent`.
826
1089
  */
@@ -944,15 +1207,21 @@ const CAMERA_SWITCH_OPTIONS = ["showDocumentCameraSwitchButton", "showLivenessCa
944
1207
  * `showDocumentCameraSwitchButton` -> `document_camera_switch=true|false`,
945
1208
  * `showLivenessCameraSwitchButton` -> `liveness_camera_switch=true|false`.
946
1209
  * How the SDK presents the flow is always added: `sdk_presentation=modal|embedded`
947
- * and, in a modal, `sdk_close_button=true|false`.
1210
+ * and, in a modal, `sdk_close_button=true|false`. `storedDeviceId`, when the
1211
+ * page has one, is added as `sdk_device_id`.
948
1212
  * Each parameter is set (not appended) so the configuration wins over a value
949
1213
  * already on the URL; existing query parameters and the hash are kept. A
950
1214
  * value of the wrong shape is ignored with a warning rather than forwarded,
951
1215
  * and a URL the browser cannot parse is returned as it came (the modal
952
1216
  * reports it when it loads).
953
1217
  */
954
- function buildVerificationUrl(url, configuration = {}) {
1218
+ function buildVerificationUrl(url, configuration = {}, storedDeviceId = null) {
955
1219
  const params = presentationParams(configuration);
1220
+ // The id this page already keeps for Didit (see getStoredDeviceId): the flow in the frame, whose
1221
+ // own storage the browser keeps apart from this page's, can then be told apart as the same
1222
+ // device as this site's events. Absent when the page keeps none; nothing is created for it.
1223
+ if (storedDeviceId)
1224
+ params.push([DEVICE_ID_QUERY_PARAM, storedDeviceId]);
956
1225
  for (const option of CAMERA_LENS_OPTIONS) {
957
1226
  const value = configuration[option];
958
1227
  if (value === undefined)
@@ -1454,6 +1723,12 @@ function getTranslations(language) {
1454
1723
  return translationsMap[language] ?? EN;
1455
1724
  }
1456
1725
 
1726
+ /** The length of the one animation when the flow moves from the handoff card to a step or back. */
1727
+ const SIZE_ANIMATION_MS = 300;
1728
+ /** How long the modal waits for the first layout before it shows at step size, so it can never hang. */
1729
+ const FIRST_LAYOUT_TIMEOUT_MS = 3000;
1730
+ /** The flow's ground (site-ground in the design system), which a full-screen modal paints the page with. */
1731
+ const FLOW_GROUND = { light: "#ffffff", dark: "#0b0b0d" };
1457
1732
  class VerificationModal {
1458
1733
  constructor(configuration, callbacks) {
1459
1734
  this.state = {
@@ -1471,11 +1746,14 @@ class VerificationModal {
1471
1746
  this.boundHandleKeydown = null;
1472
1747
  this.boundHandleFocusChange = null;
1473
1748
  this.confirmationFocusTimeout = null;
1749
+ this.firstLayoutTimeout = null;
1750
+ this.sizeTimeout = null;
1474
1751
  this.embedded = false;
1475
1752
  this.embeddedContainer = null;
1476
1753
  this.language = "en";
1477
- /** body.style.overflow value observed right before this modal locked scroll, restored on close(). */
1478
- this.previousBodyOverflow = null;
1754
+ /** The ground below the layout viewport (see showCurtain), while this modal is open. */
1755
+ this.curtain = null;
1756
+ this.boundPlaceCurtain = null;
1479
1757
  this.modalId = generateModalId();
1480
1758
  this.config = {
1481
1759
  zIndex: configuration?.zIndex ?? DEFAULT_CONFIG.zIndex,
@@ -1518,9 +1796,9 @@ class VerificationModal {
1518
1796
  .${CSS_CLASSES.container} {
1519
1797
  position: relative;
1520
1798
  width: 100%;
1521
- max-width: 500px;
1522
- max-height: 90vh;
1523
- max-height: 90dvh;
1799
+ max-width: 440px;
1800
+ height: min(860px, calc(100vh - 2rem));
1801
+ height: min(860px, calc(100dvh - 2rem));
1524
1802
  border-radius: 16px;
1525
1803
  overflow: hidden;
1526
1804
  background: transparent;
@@ -1532,9 +1810,7 @@ class VerificationModal {
1532
1810
 
1533
1811
  .${CSS_CLASSES.iframe} {
1534
1812
  width: 100%;
1535
- height: 90vh;
1536
- height: 90dvh;
1537
- max-height: 700px;
1813
+ height: 100%;
1538
1814
  border: none;
1539
1815
  display: block;
1540
1816
  }
@@ -1571,10 +1847,17 @@ class VerificationModal {
1571
1847
  display: flex;
1572
1848
  align-items: center;
1573
1849
  justify-content: center;
1574
- background: #fafafa;
1850
+ /* The flow's ground, so a phone's loader meets the ground below the viewport without a seam. */
1851
+ background: ${FLOW_GROUND.light};
1575
1852
  z-index: 5;
1576
1853
  }
1577
1854
 
1855
+ @media (prefers-color-scheme: dark) {
1856
+ .${CSS_CLASSES.loading} {
1857
+ background: ${FLOW_GROUND.dark};
1858
+ }
1859
+ }
1860
+
1578
1861
  .${CSS_CLASSES.loading}.hidden {
1579
1862
  display: none;
1580
1863
  }
@@ -1696,6 +1979,58 @@ class VerificationModal {
1696
1979
  outline-offset: 2px;
1697
1980
  }
1698
1981
 
1982
+ /*
1983
+ * Steps are phone-sized (440 x 860, above). On a computer the handoff card is wider
1984
+ * (board Start-Embedded): 960 x 660 on a window of 1000px or more, never wider than the
1985
+ * window less its margin and never taller than 90% of it. In a narrower window the
1986
+ * page stacks and the height follows its content (--didit-content-height, set from the
1987
+ * flow's layout message). Until the flow reports what it shows, the modal is the handoff
1988
+ * card at its final size with the spinner inside it (the flow stays hidden and lays itself
1989
+ * out for that size): it never opens small and grows. The first change of kind (a step
1990
+ * instead of the handoff, or the person continues on this computer) animates once.
1991
+ */
1992
+ @media (min-width: 541px) {
1993
+ .${CSS_CLASSES.container}[data-didit-kind="handoff"],
1994
+ .${CSS_CLASSES.container}[data-didit-kind="pending"] {
1995
+ max-width: min(960px, calc(100vw - 2rem));
1996
+ height: min(var(--didit-content-height, 660px), calc(100vh * 0.9));
1997
+ height: min(var(--didit-content-height, 660px), calc(100dvh * 0.9));
1998
+ }
1999
+
2000
+ .${CSS_CLASSES.container}.${CSS_CLASSES.sizeAnimated} {
2001
+ transition: max-width 0.25s ease, height 0.25s ease;
2002
+ }
2003
+
2004
+ .${CSS_CLASSES.container}[data-didit-kind="pending"] .${CSS_CLASSES.iframe} {
2005
+ visibility: hidden;
2006
+ }
2007
+ }
2008
+
2009
+ /*
2010
+ * While pending the card already looks like the first screen (ground, radius, shadow and
2011
+ * close button come from the flow-sized rules below, with the device theme); the loader
2012
+ * sits inside it on the card's own ground.
2013
+ */
2014
+ .${CSS_CLASSES.container}[data-didit-kind="pending"] .${CSS_CLASSES.loading} {
2015
+ background: transparent;
2016
+ }
2017
+
2018
+ .${CSS_CLASSES.container}[data-didit-kind="pending"][data-didit-theme="dark"] .${CSS_CLASSES.loading} circle {
2019
+ stroke: rgba(255, 255, 255, 0.16);
2020
+ }
2021
+
2022
+ .${CSS_CLASSES.container}[data-didit-kind="pending"][data-didit-theme="dark"] .${CSS_CLASSES.loading} path {
2023
+ stroke: #f5f5f7;
2024
+ }
2025
+
2026
+ @media (min-width: 1000px) {
2027
+ .${CSS_CLASSES.container}[data-didit-kind="handoff"],
2028
+ .${CSS_CLASSES.container}[data-didit-kind="pending"] {
2029
+ height: min(660px, calc(100vh * 0.9));
2030
+ height: min(660px, calc(100dvh * 0.9));
2031
+ }
2032
+ }
2033
+
1699
2034
  @media (max-width: 540px) {
1700
2035
  .${CSS_CLASSES.overlay} {
1701
2036
  padding: 0;
@@ -1703,23 +2038,50 @@ class VerificationModal {
1703
2038
 
1704
2039
  .${CSS_CLASSES.container} {
1705
2040
  max-width: 100%;
1706
- max-height: 100vh;
1707
- max-height: 100dvh;
2041
+ height: 100vh;
2042
+ height: 100dvh;
1708
2043
  border-radius: 0;
1709
2044
  }
2045
+ }
1710
2046
 
1711
- .${CSS_CLASSES.iframe} {
1712
- height: 100vh;
1713
- height: 100dvh;
1714
- max-height: none;
2047
+ /*
2048
+ * The flow's ground right below the layout viewport, in the page itself (see showCurtain):
2049
+ * on a phone, iOS browsers with their toolbars collapsed show a band of the page there,
2050
+ * below every fixed element, the full-screen modal included.
2051
+ */
2052
+ .${CSS_CLASSES.curtain} {
2053
+ display: none;
2054
+ position: absolute;
2055
+ top: 0;
2056
+ left: 0;
2057
+ width: 100vw;
2058
+ height: 100vh;
2059
+ margin: 0;
2060
+ pointer-events: none;
2061
+ /* Under the modal where they meet for a frame while the toolbars move, above the page. */
2062
+ z-index: ${this.config.zIndex - 1};
2063
+ background: ${FLOW_GROUND.light};
2064
+ }
2065
+
2066
+ .${CSS_CLASSES.curtain}[data-didit-theme="dark"] {
2067
+ background: ${FLOW_GROUND.dark};
2068
+ }
2069
+
2070
+ /* The exit confirmation's dimming continues over the ground below the viewport. */
2071
+ .${CSS_CLASSES.curtain}[data-didit-dimmed] {
2072
+ background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5));
2073
+ }
2074
+
2075
+ @media (max-width: 540px) {
2076
+ .${CSS_CLASSES.curtain} {
2077
+ display: block;
1715
2078
  }
1716
2079
  }
1717
2080
 
1718
2081
  /*
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.
2082
+ * The hosted flow's layout message (didit:layout) brings the modal's size
2083
+ * (see above), theme and direction. Colours are the design system tokens
2084
+ * named beside them.
1723
2085
  */
1724
2086
  .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1725
2087
  --didit-ground: #ffffff; /* site-ground */
@@ -1729,7 +2091,6 @@ class VerificationModal {
1729
2091
  --didit-close-fill: rgba(0, 0, 0, 0.06);
1730
2092
  --didit-drop: rgba(17, 24, 39, 0.35);
1731
2093
  --didit-ring: rgba(0, 0, 0, 0.06);
1732
- max-width: 500px;
1733
2094
  background: var(--didit-ground);
1734
2095
  box-shadow: 0 30px 80px -24px var(--didit-drop), 0 0 0 1px var(--didit-ring);
1735
2096
  }
@@ -1744,12 +2105,6 @@ class VerificationModal {
1744
2105
  --didit-ring: rgba(255, 255, 255, 0.08); /* c-shadow-pop, dark */
1745
2106
  }
1746
2107
 
1747
- .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1748
- height: var(--didit-flow-height);
1749
- max-height: 90vh;
1750
- max-height: 90dvh;
1751
- }
1752
-
1753
2108
  .${CSS_CLASSES.closeIcon} {
1754
2109
  display: none;
1755
2110
  }
@@ -1823,28 +2178,11 @@ class VerificationModal {
1823
2178
  flex-wrap: wrap;
1824
2179
  }
1825
2180
 
1826
- @media (min-width: 1024px) {
1827
- .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1828
- width: 90vw;
1829
- max-width: 960px;
1830
- }
1831
-
1832
- .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1833
- height: 660px;
1834
- }
1835
- }
1836
-
1837
2181
  @media (max-width: 540px) {
1838
2182
  .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1839
2183
  max-width: 100%;
1840
2184
  box-shadow: none;
1841
2185
  }
1842
-
1843
- .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1844
- height: 100vh;
1845
- height: 100dvh;
1846
- max-height: none;
1847
- }
1848
2186
  }
1849
2187
 
1850
2188
  .${CSS_CLASSES.embedded} {
@@ -2077,12 +2415,13 @@ class VerificationModal {
2077
2415
  */
2078
2416
  readFlowLayout(data) {
2079
2417
  const fields = typeof data === "object" && data !== null ? data : {};
2080
- const { contentHeight, colorScheme, dir } = fields;
2418
+ const { contentHeight, colorScheme, dir, kind } = fields;
2081
2419
  if (typeof contentHeight !== "number" || !Number.isFinite(contentHeight) || contentHeight <= 0) {
2082
2420
  return null;
2083
2421
  }
2084
2422
  const prefersDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false;
2085
2423
  return {
2424
+ kind: kind === "handoff" ? "handoff" : "step",
2086
2425
  contentHeight: Math.ceil(contentHeight),
2087
2426
  colorScheme: colorScheme === "light" || colorScheme === "dark" ? colorScheme : prefersDark ? "dark" : "light",
2088
2427
  dir: dir === "ltr" || dir === "rtl" ? dir : isRtlLanguage(this.language) ? "rtl" : "ltr"
@@ -2094,18 +2433,222 @@ class VerificationModal {
2094
2433
  return;
2095
2434
  SDKLogger.log("Flow layout:", layout);
2096
2435
  this.container.classList.add(CSS_CLASSES.flowSized);
2097
- this.container.style.setProperty("--didit-flow-height", `${layout.contentHeight}px`);
2098
2436
  this.container.dataset.diditTheme = layout.colorScheme;
2099
2437
  this.container.dataset.diditDir = layout.dir;
2438
+ // The height the person sees now, before the reported content height can change it.
2439
+ const shownHeight = this.container.offsetHeight;
2440
+ this.container.style.setProperty("--didit-content-height", `${layout.contentHeight}px`);
2441
+ this.matchPageBackground(layout.colorScheme);
2442
+ if (this.curtain)
2443
+ this.curtain.dataset.diditTheme = layout.colorScheme;
2444
+ this.setModalKind(layout.kind, layout.kind === "handoff" && this.handoffHeight(layout) === shownHeight);
2445
+ }
2446
+ /** Whether the window is a computer-sized one: a phone is full screen and never waits for a layout. */
2447
+ isPhoneWindow() {
2448
+ return window.matchMedia?.("(max-width: 540px)").matches ?? false;
2449
+ }
2450
+ /** The height the handoff card takes for a layout, as the size rules above compute it (rounded like offsetHeight). */
2451
+ handoffHeight(layout) {
2452
+ const cap = window.innerHeight * 0.9;
2453
+ return Math.round(Math.min(window.innerWidth >= 1000 ? 660 : layout.contentHeight, cap));
2454
+ }
2455
+ /**
2456
+ * Sets what the modal is sized for. Leaving "pending" shows the modal at its final size with no
2457
+ * transition; any later change animates once.
2458
+ */
2459
+ setModalKind(kind, sizeUnchanged = false) {
2460
+ if (!this.container)
2461
+ return;
2462
+ const previous = this.container.dataset.diditKind;
2463
+ if (previous === kind)
2464
+ return;
2465
+ if (this.firstLayoutTimeout !== null && kind !== "pending") {
2466
+ window.clearTimeout(this.firstLayoutTimeout);
2467
+ this.firstLayoutTimeout = null;
2468
+ }
2469
+ // Every change of kind animates, the pending card included (it is on screen), and only for the
2470
+ // length of the change, so resizing the window never lags behind.
2471
+ // Pending already is the handoff card: a handoff first layout of the same size moves nothing,
2472
+ // while a different reported height (a narrow window) animates the correction once.
2473
+ const staysPut = previous === "pending" && kind === "handoff" && sizeUnchanged;
2474
+ if (previous !== undefined && !staysPut)
2475
+ this.animateSizeOnce();
2476
+ this.container.dataset.diditKind = kind;
2477
+ // The final size is in place before the loader goes; a flow still loading keeps its loader.
2478
+ if (previous === "pending" && !this.state.isLoading)
2479
+ this.loadingEl?.classList.add("hidden");
2100
2480
  }
2101
- /** Back to the fixed 500 x 700 modal until the newly loaded flow reports its layout. */
2481
+ animateSizeOnce() {
2482
+ this.container?.classList.add(CSS_CLASSES.sizeAnimated);
2483
+ if (this.sizeTimeout !== null)
2484
+ window.clearTimeout(this.sizeTimeout);
2485
+ this.sizeTimeout = window.setTimeout(() => {
2486
+ this.sizeTimeout = null;
2487
+ this.container?.classList.remove(CSS_CLASSES.sizeAnimated);
2488
+ }, SIZE_ANIMATION_MS);
2489
+ }
2490
+ /** A flow that reports no layout (an older one) still shows, at step size, after a short wait. */
2491
+ waitForFirstLayout() {
2492
+ if (!this.container)
2493
+ return;
2494
+ // The card looks like the first screen from the first frame, in the device's theme.
2495
+ this.container.classList.add(CSS_CLASSES.flowSized);
2496
+ this.container.dataset.diditTheme = window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
2497
+ this.setModalKind("pending");
2498
+ this.firstLayoutTimeout = window.setTimeout(() => {
2499
+ this.firstLayoutTimeout = null;
2500
+ // A flow that never reported is an older one that paints itself: no card look around it.
2501
+ this.container?.classList.remove(CSS_CLASSES.flowSized);
2502
+ delete this.container?.dataset.diditTheme;
2503
+ this.setModalKind("step");
2504
+ }, FIRST_LAYOUT_TIMEOUT_MS);
2505
+ }
2506
+ /**
2507
+ * On a phone Safari paints the bottom edge of the screen with the page's own background, past
2508
+ * any fixed overlay, and shows it when the keyboard moves the page. A full-screen modal lends
2509
+ * the page its ground colour while it is open, so no strip of the host page shows around it.
2510
+ */
2511
+ matchPageBackground(colorScheme) {
2512
+ if (!window.matchMedia?.("(max-width: 540px)").matches)
2513
+ return;
2514
+ VerificationModal.pageBackground ?? (VerificationModal.pageBackground = {
2515
+ saved: { root: document.documentElement.style.backgroundColor, body: document.body.style.backgroundColor },
2516
+ grounds: new Map()
2517
+ });
2518
+ VerificationModal.pageBackground.grounds.set(this, colorScheme);
2519
+ VerificationModal.paintPageBackground();
2520
+ }
2521
+ restorePageBackground() {
2522
+ const background = VerificationModal.pageBackground;
2523
+ if (!background?.grounds.delete(this))
2524
+ return;
2525
+ if (background.grounds.size > 0) {
2526
+ VerificationModal.paintPageBackground();
2527
+ return;
2528
+ }
2529
+ VerificationModal.pageBackground = null;
2530
+ document.documentElement.style.backgroundColor = background.saved.root;
2531
+ document.body.style.backgroundColor = background.saved.body;
2532
+ }
2533
+ /** The page shows the ground of the topmost open modal that lends one. */
2534
+ static paintPageBackground() {
2535
+ const background = VerificationModal.pageBackground;
2536
+ if (!background)
2537
+ return;
2538
+ const lender = [...VerificationModal.openModals].reverse().find((modal) => background.grounds.has(modal));
2539
+ const colorScheme = lender ? background.grounds.get(lender) : [...background.grounds.values()].pop();
2540
+ if (!colorScheme)
2541
+ return;
2542
+ document.documentElement.style.backgroundColor = FLOW_GROUND[colorScheme];
2543
+ document.body.style.backgroundColor = FLOW_GROUND[colorScheme];
2544
+ }
2545
+ /**
2546
+ * Stops the page scrolling under the modal. The lock is on the root element: Chrome for iOS keeps
2547
+ * scrolling a page whose body alone is `overflow: hidden` (a swipe over the modal scrolls the page
2548
+ * and toggles the browser's toolbars), and stops only when the root element is. A page that
2549
+ * scrolls its body instead of the window has its body locked too. The first modal to open keeps
2550
+ * the page's own values and the last one to close gives them back.
2551
+ */
2552
+ lockPageScroll() {
2553
+ const lock = VerificationModal.pageScrollLock;
2554
+ if (lock) {
2555
+ lock.holders.add(this);
2556
+ return;
2557
+ }
2558
+ const root = document.documentElement;
2559
+ const body = document.body;
2560
+ // The body's overflow is the viewport's only while the root's is visible; otherwise a body with
2561
+ // an overflow of its own is a scroll container. Locking a body that is not one would clip the page
2562
+ // to the body's box.
2563
+ const clips = (overflow) => overflow !== "" && overflow !== "visible";
2564
+ const bodyScrollsItself = clips(window.getComputedStyle(root).overflowY) && clips(window.getComputedStyle(body).overflowY);
2565
+ VerificationModal.pageScrollLock = {
2566
+ holders: new Set([this]),
2567
+ root: { overflow: root.style.overflow, overscrollBehavior: root.style.overscrollBehavior },
2568
+ body: bodyScrollsItself ? { overflow: body.style.overflow } : null
2569
+ };
2570
+ root.style.overflow = "hidden";
2571
+ root.style.overscrollBehavior = "none";
2572
+ if (bodyScrollsItself)
2573
+ body.style.overflow = "hidden";
2574
+ }
2575
+ unlockPageScroll() {
2576
+ const lock = VerificationModal.pageScrollLock;
2577
+ if (!lock || !lock.holders.delete(this) || lock.holders.size > 0)
2578
+ return;
2579
+ VerificationModal.pageScrollLock = null;
2580
+ const root = document.documentElement;
2581
+ root.style.overflow = lock.root.overflow;
2582
+ root.style.overscrollBehavior = lock.root.overscrollBehavior;
2583
+ if (lock.body)
2584
+ document.body.style.overflow = lock.body.overflow;
2585
+ }
2586
+ /**
2587
+ * On a phone, Chrome for iOS (and the other iOS browsers built on WebKit's web view) shows a band
2588
+ * of the page below the layout viewport while its toolbars are collapsed: the home indicator's
2589
+ * area, and more while the toolbars move. Fixed elements end at the layout viewport, so the
2590
+ * full-screen modal cannot cover it and the host page's own content showed under the flow. The
2591
+ * curtain is part of the page instead: right below the viewport, in the flow's ground, so that band
2592
+ * shows the modal's ground. The page cannot scroll while the modal is open (lockPageScroll), and the
2593
+ * curtain follows the viewport when it resizes. Only phone-sized windows draw it (see the styles).
2594
+ */
2595
+ showCurtain() {
2596
+ if (!this.curtain) {
2597
+ const curtain = document.createElement("div");
2598
+ curtain.className = CSS_CLASSES.curtain;
2599
+ curtain.setAttribute("aria-hidden", "true");
2600
+ document.body.appendChild(curtain);
2601
+ this.curtain = curtain;
2602
+ this.boundPlaceCurtain = () => this.placeCurtain();
2603
+ window.addEventListener("resize", this.boundPlaceCurtain);
2604
+ window.addEventListener("scroll", this.boundPlaceCurtain);
2605
+ window.visualViewport?.addEventListener("resize", this.boundPlaceCurtain);
2606
+ }
2607
+ // The device's theme until the newly loaded flow reports its own (applyFlowLayout).
2608
+ this.curtain.dataset.diditTheme = window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
2609
+ this.placeCurtain();
2610
+ }
2611
+ /** Puts the curtain's top at the bottom of the layout viewport, whatever its containing block is. */
2612
+ placeCurtain() {
2613
+ const curtain = this.curtain;
2614
+ if (!curtain)
2615
+ return;
2616
+ curtain.style.top = "0px";
2617
+ curtain.style.left = "0px";
2618
+ // At 0, 0 the curtain's box starts at its containing block's corner (the page's, or a positioned
2619
+ // body's), in viewport coordinates: the offset that brings its top to the viewport's bottom edge.
2620
+ const origin = curtain.getBoundingClientRect();
2621
+ curtain.style.top = `${window.innerHeight - origin.top}px`;
2622
+ curtain.style.left = `${-origin.left}px`;
2623
+ }
2624
+ removeCurtain() {
2625
+ if (this.boundPlaceCurtain) {
2626
+ window.removeEventListener("resize", this.boundPlaceCurtain);
2627
+ window.removeEventListener("scroll", this.boundPlaceCurtain);
2628
+ window.visualViewport?.removeEventListener("resize", this.boundPlaceCurtain);
2629
+ this.boundPlaceCurtain = null;
2630
+ }
2631
+ this.curtain?.remove();
2632
+ this.curtain = null;
2633
+ }
2634
+ /** Back to the neutral look until the newly loaded flow reports its theme and direction. */
2102
2635
  resetFlowLayout() {
2103
2636
  if (this.embedded || !this.container)
2104
2637
  return;
2105
- this.container.classList.remove(CSS_CLASSES.flowSized);
2106
- this.container.style.removeProperty("--didit-flow-height");
2638
+ this.restorePageBackground();
2639
+ this.container.classList.remove(CSS_CLASSES.flowSized, CSS_CLASSES.sizeAnimated);
2107
2640
  delete this.container.dataset.diditTheme;
2108
2641
  delete this.container.dataset.diditDir;
2642
+ delete this.container.dataset.diditKind;
2643
+ this.container.style.removeProperty("--didit-content-height");
2644
+ if (this.firstLayoutTimeout !== null) {
2645
+ window.clearTimeout(this.firstLayoutTimeout);
2646
+ this.firstLayoutTimeout = null;
2647
+ }
2648
+ if (this.sizeTimeout !== null) {
2649
+ window.clearTimeout(this.sizeTimeout);
2650
+ this.sizeTimeout = null;
2651
+ }
2109
2652
  }
2110
2653
  handleKeydown(event) {
2111
2654
  if (!this.state.isOpen)
@@ -2141,7 +2684,9 @@ class VerificationModal {
2141
2684
  handleIframeLoad() {
2142
2685
  if (this.iframe?.src && this.iframe.src !== "about:blank") {
2143
2686
  this.state.isLoading = false;
2144
- this.loadingEl?.classList.add("hidden");
2687
+ // A modal still waiting for its first layout keeps the loader over the hidden flow.
2688
+ if (this.container?.dataset.diditKind !== "pending")
2689
+ this.loadingEl?.classList.add("hidden");
2145
2690
  this.callbacks.onIframeLoad();
2146
2691
  }
2147
2692
  }
@@ -2162,6 +2707,7 @@ class VerificationModal {
2162
2707
  : this.container?.querySelector(`.${CSS_CLASSES.closeButton}`) ?? this.iframe);
2163
2708
  this.state.showConfirmation = true;
2164
2709
  this.confirmOverlay.classList.add("active");
2710
+ this.curtain?.setAttribute("data-didit-dimmed", "");
2165
2711
  if (this.iframe)
2166
2712
  this.iframe.inert = true;
2167
2713
  const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
@@ -2185,6 +2731,7 @@ class VerificationModal {
2185
2731
  return;
2186
2732
  this.state.showConfirmation = false;
2187
2733
  this.confirmOverlay?.classList.remove("active");
2734
+ this.curtain?.removeAttribute("data-didit-dimmed");
2188
2735
  if (this.iframe)
2189
2736
  this.iframe.inert = false;
2190
2737
  const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
@@ -2212,11 +2759,6 @@ class VerificationModal {
2212
2759
  this.callbacks.onCloseConfirmed();
2213
2760
  }
2214
2761
  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
2762
  this.language = detectLanguageFromUrl(verificationUrl);
2221
2763
  if (!this.overlay && !this.container) {
2222
2764
  this.createDOM();
@@ -2230,6 +2772,8 @@ class VerificationModal {
2230
2772
  this.hideConfirmation();
2231
2773
  this.loadingEl?.classList.remove("hidden");
2232
2774
  this.resetFlowLayout();
2775
+ if (!this.embedded && !this.isPhoneWindow())
2776
+ this.waitForFirstLayout();
2233
2777
  if (this.iframe) {
2234
2778
  this.iframe.src = verificationUrl;
2235
2779
  }
@@ -2239,16 +2783,10 @@ class VerificationModal {
2239
2783
  return;
2240
2784
  }
2241
2785
  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";
2786
+ // Idempotent: a re-open of a modal that is still open keeps its one hold on the lock, so
2787
+ // close() still gives the page back the values it had before any modal opened.
2788
+ this.lockPageScroll();
2789
+ this.showCurtain();
2252
2790
  }
2253
2791
  close() {
2254
2792
  SDKLogger.log("Closing");
@@ -2266,8 +2804,8 @@ class VerificationModal {
2266
2804
  return;
2267
2805
  }
2268
2806
  this.overlay?.classList.remove("active");
2269
- document.body.style.overflow = this.previousBodyOverflow ?? "";
2270
- this.previousBodyOverflow = null;
2807
+ this.removeCurtain();
2808
+ this.unlockPageScroll();
2271
2809
  }
2272
2810
  destroy() {
2273
2811
  SDKLogger.log("Destroying");
@@ -2299,6 +2837,16 @@ class VerificationModal {
2299
2837
  * a transaction action modal stacked over the verification modal).
2300
2838
  */
2301
2839
  VerificationModal.openModals = [];
2840
+ /**
2841
+ * The page's own background colours, kept while full-screen modals lend it their ground, shared by
2842
+ * every open modal: the topmost one's ground shows and the last one to give it back restores them.
2843
+ */
2844
+ VerificationModal.pageBackground = null;
2845
+ /**
2846
+ * The page's scroll styles from before the first open modal locked them, shared by every open
2847
+ * modal: the last one to close gives them back.
2848
+ */
2849
+ VerificationModal.pageScrollLock = null;
2302
2850
 
2303
2851
  const DEFAULT_TRANSACTION_BASE_URL = "https://verification.didit.me";
2304
2852
  const ACTION_POLL_INTERVAL_MS = 1500;
@@ -2618,6 +3166,18 @@ function assertEmbeddedHostExists(configuration) {
2618
3166
  throw new Error(`Embedded container "#${containerId}" was not found in the page.`);
2619
3167
  }
2620
3168
  }
3169
+ /**
3170
+ * The device id this page already keeps for Didit (it has sent events, transactions or sign-ins),
3171
+ * or null. Reading it never creates one, and a browser that refuses the read is not an error.
3172
+ */
3173
+ function storedDeviceId() {
3174
+ try {
3175
+ return getStoredDeviceId();
3176
+ }
3177
+ catch {
3178
+ return null;
3179
+ }
3180
+ }
2621
3181
  class DiditSdk {
2622
3182
  static get shared() {
2623
3183
  if (!DiditSdk._instance) {
@@ -2691,7 +3251,7 @@ class DiditSdk {
2691
3251
  onMessage: (event) => this.handleVerificationEvent(event),
2692
3252
  onIframeLoad: () => this.handleIframeLoad()
2693
3253
  });
2694
- this._url = buildVerificationUrl(url, config);
3254
+ this._url = buildVerificationUrl(url, config, storedDeviceId());
2695
3255
  this.setState("loading");
2696
3256
  this.emitInternalEvent("didit:started", {});
2697
3257
  this._modal?.open(this._url);
@@ -3077,5 +3637,5 @@ class DiditSdk {
3077
3637
  }
3078
3638
  DiditSdk._instance = null;
3079
3639
 
3080
- export { DEFAULT_EVENTS_BASE_URL, DEFAULT_TRANSACTION_BASE_URL, DiditEventError, DiditSdk, DiditTransactionError, SDK_VERSION, buildFingerprintHeaders, configureEvents, DiditSdk as default, flush, getDeviceFingerprintPayload, submitEvent };
3640
+ export { DEFAULT_EVENTS_BASE_URL, DEFAULT_TRANSACTION_BASE_URL, DiditEventError, DiditSdk, DiditTransactionError, SDK_VERSION, buildFingerprintHeaders, configureEvents, DiditSdk as default, flush, getDeviceFingerprintPayload, getStoredDeviceId, setDeviceSignalsProvider, submitEvent };
3081
3641
  //# sourceMappingURL=didit-sdk.esm.js.map