@didit-protocol/sdk-web 0.5.3 → 0.7.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.3
2
+ * Didit SDK for Web v0.7.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
  });
@@ -791,9 +1045,10 @@ const CSS_CLASSES = {
791
1045
  loading: "didit-loading",
792
1046
  confirmOverlay: "didit-confirm-overlay",
793
1047
  confirmBox: "didit-confirm-box",
794
- embedded: "didit-embedded"
1048
+ embedded: "didit-embedded",
1049
+ curtain: "didit-modal-curtain"
795
1050
  };
796
- const SDK_VERSION = "0.5.3";
1051
+ const SDK_VERSION = "0.7.0";
797
1052
  /**
798
1053
  * The permissions the verification iframe gets, in a modal and embedded:
799
1054
  * camera and microphone for capture, clipboard-write for the flow's copy
@@ -819,6 +1074,13 @@ const PRESENTATION_QUERY_PARAMS = {
819
1074
  presentation: "sdk_presentation",
820
1075
  closeButton: "sdk_close_button"
821
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";
822
1084
  /**
823
1085
  * Posted by the hosted flow when it lays itself out for the modal, with
824
1086
  * `data: { contentHeight, colorScheme?, dir?, kind? }` (`kind` is `handoff` or `step`, `step` when missing). The modal then grows to the
@@ -945,15 +1207,21 @@ const CAMERA_SWITCH_OPTIONS = ["showDocumentCameraSwitchButton", "showLivenessCa
945
1207
  * `showDocumentCameraSwitchButton` -> `document_camera_switch=true|false`,
946
1208
  * `showLivenessCameraSwitchButton` -> `liveness_camera_switch=true|false`.
947
1209
  * How the SDK presents the flow is always added: `sdk_presentation=modal|embedded`
948
- * 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`.
949
1212
  * Each parameter is set (not appended) so the configuration wins over a value
950
1213
  * already on the URL; existing query parameters and the hash are kept. A
951
1214
  * value of the wrong shape is ignored with a warning rather than forwarded,
952
1215
  * and a URL the browser cannot parse is returned as it came (the modal
953
1216
  * reports it when it loads).
954
1217
  */
955
- function buildVerificationUrl(url, configuration = {}) {
1218
+ function buildVerificationUrl(url, configuration = {}, storedDeviceId = null) {
956
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]);
957
1225
  for (const option of CAMERA_LENS_OPTIONS) {
958
1226
  const value = configuration[option];
959
1227
  if (value === undefined)
@@ -1459,6 +1727,10 @@ function getTranslations(language) {
1459
1727
  const SIZE_ANIMATION_MS = 300;
1460
1728
  /** How long the modal waits for the first layout before it shows at step size, so it can never hang. */
1461
1729
  const FIRST_LAYOUT_TIMEOUT_MS = 3000;
1730
+ /** A strip is a line or two of text: a taller value is not one, and would push the close button out of reach. */
1731
+ const MAX_TOP_INSET = 160;
1732
+ /** The flow's ground (site-ground in the design system), which a full-screen modal paints the page with. */
1733
+ const FLOW_GROUND = { light: "#ffffff", dark: "#0b0b0d" };
1462
1734
  class VerificationModal {
1463
1735
  constructor(configuration, callbacks) {
1464
1736
  this.state = {
@@ -1481,10 +1753,9 @@ class VerificationModal {
1481
1753
  this.embedded = false;
1482
1754
  this.embeddedContainer = null;
1483
1755
  this.language = "en";
1484
- /** The page's own background colours, kept while a full-screen modal paints over them. */
1485
- this.pageBackground = null;
1486
- /** body.style.overflow value observed right before this modal locked scroll, restored on close(). */
1487
- this.previousBodyOverflow = null;
1756
+ /** The ground below the layout viewport (see showCurtain), while this modal is open. */
1757
+ this.curtain = null;
1758
+ this.boundPlaceCurtain = null;
1488
1759
  this.modalId = generateModalId();
1489
1760
  this.config = {
1490
1761
  zIndex: configuration?.zIndex ?? DEFAULT_CONFIG.zIndex,
@@ -1578,13 +1849,14 @@ class VerificationModal {
1578
1849
  display: flex;
1579
1850
  align-items: center;
1580
1851
  justify-content: center;
1581
- background: #fafafa;
1852
+ /* The flow's ground, so a phone's loader meets the ground below the viewport without a seam. */
1853
+ background: ${FLOW_GROUND.light};
1582
1854
  z-index: 5;
1583
1855
  }
1584
1856
 
1585
1857
  @media (prefers-color-scheme: dark) {
1586
1858
  .${CSS_CLASSES.loading} {
1587
- background: #0b0b0d;
1859
+ background: ${FLOW_GROUND.dark};
1588
1860
  }
1589
1861
  }
1590
1862
 
@@ -1774,6 +2046,40 @@ class VerificationModal {
1774
2046
  }
1775
2047
  }
1776
2048
 
2049
+ /*
2050
+ * The flow's ground right below the layout viewport, in the page itself (see showCurtain):
2051
+ * on a phone, iOS browsers with their toolbars collapsed show a band of the page there,
2052
+ * below every fixed element, the full-screen modal included.
2053
+ */
2054
+ .${CSS_CLASSES.curtain} {
2055
+ display: none;
2056
+ position: absolute;
2057
+ top: 0;
2058
+ left: 0;
2059
+ width: 100vw;
2060
+ height: 100vh;
2061
+ margin: 0;
2062
+ pointer-events: none;
2063
+ /* Under the modal where they meet for a frame while the toolbars move, above the page. */
2064
+ z-index: ${this.config.zIndex - 1};
2065
+ background: ${FLOW_GROUND.light};
2066
+ }
2067
+
2068
+ .${CSS_CLASSES.curtain}[data-didit-theme="dark"] {
2069
+ background: ${FLOW_GROUND.dark};
2070
+ }
2071
+
2072
+ /* The exit confirmation's dimming continues over the ground below the viewport. */
2073
+ .${CSS_CLASSES.curtain}[data-didit-dimmed] {
2074
+ background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5));
2075
+ }
2076
+
2077
+ @media (max-width: 540px) {
2078
+ .${CSS_CLASSES.curtain} {
2079
+ display: block;
2080
+ }
2081
+ }
2082
+
1777
2083
  /*
1778
2084
  * The hosted flow's layout message (didit:layout) brings the modal's size
1779
2085
  * (see above), theme and direction. Colours are the design system tokens
@@ -1806,7 +2112,7 @@ class VerificationModal {
1806
2112
  }
1807
2113
 
1808
2114
  .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton} {
1809
- top: 8px;
2115
+ top: calc(8px + var(--didit-top-inset, 0px));
1810
2116
  right: 8px;
1811
2117
  width: 44px;
1812
2118
  height: 44px;
@@ -2107,11 +2413,12 @@ class VerificationModal {
2107
2413
  /**
2108
2414
  * Reads a didit:layout message's data. Without a positive contentHeight the
2109
2415
  * message is ignored; a missing or unknown colorScheme follows the device,
2110
- * and a missing or unknown dir follows the verification URL's language.
2416
+ * a missing or unknown dir follows the verification URL's language, and the
2417
+ * close button keeps its place without a plausible topInset.
2111
2418
  */
2112
2419
  readFlowLayout(data) {
2113
2420
  const fields = typeof data === "object" && data !== null ? data : {};
2114
- const { contentHeight, colorScheme, dir, kind } = fields;
2421
+ const { contentHeight, colorScheme, dir, kind, topInset } = fields;
2115
2422
  if (typeof contentHeight !== "number" || !Number.isFinite(contentHeight) || contentHeight <= 0) {
2116
2423
  return null;
2117
2424
  }
@@ -2120,7 +2427,8 @@ class VerificationModal {
2120
2427
  kind: kind === "handoff" ? "handoff" : "step",
2121
2428
  contentHeight: Math.ceil(contentHeight),
2122
2429
  colorScheme: colorScheme === "light" || colorScheme === "dark" ? colorScheme : prefersDark ? "dark" : "light",
2123
- dir: dir === "ltr" || dir === "rtl" ? dir : isRtlLanguage(this.language) ? "rtl" : "ltr"
2430
+ dir: dir === "ltr" || dir === "rtl" ? dir : isRtlLanguage(this.language) ? "rtl" : "ltr",
2431
+ topInset: typeof topInset === "number" && topInset > 0 && topInset <= MAX_TOP_INSET ? Math.ceil(topInset) : 0
2124
2432
  };
2125
2433
  }
2126
2434
  /** Embedded mode keeps filling the integrator's host element, whatever the flow reports. */
@@ -2134,7 +2442,11 @@ class VerificationModal {
2134
2442
  // The height the person sees now, before the reported content height can change it.
2135
2443
  const shownHeight = this.container.offsetHeight;
2136
2444
  this.container.style.setProperty("--didit-content-height", `${layout.contentHeight}px`);
2445
+ // The close button sits under the flow's strip, over its top bar.
2446
+ this.container.style.setProperty("--didit-top-inset", `${layout.topInset}px`);
2137
2447
  this.matchPageBackground(layout.colorScheme);
2448
+ if (this.curtain)
2449
+ this.curtain.dataset.diditTheme = layout.colorScheme;
2138
2450
  this.setModalKind(layout.kind, layout.kind === "handoff" && this.handoffHeight(layout) === shownHeight);
2139
2451
  }
2140
2452
  /** Whether the window is a computer-sized one: a phone is full screen and never waits for a layout. */
@@ -2205,18 +2517,125 @@ class VerificationModal {
2205
2517
  matchPageBackground(colorScheme) {
2206
2518
  if (!window.matchMedia?.("(max-width: 540px)").matches)
2207
2519
  return;
2208
- const root = document.documentElement;
2209
- this.pageBackground ?? (this.pageBackground = { root: root.style.backgroundColor, body: document.body.style.backgroundColor });
2210
- const ground = colorScheme === "dark" ? "#0b0b0d" : "#ffffff";
2211
- root.style.backgroundColor = ground;
2212
- document.body.style.backgroundColor = ground;
2520
+ VerificationModal.pageBackground ?? (VerificationModal.pageBackground = {
2521
+ saved: { root: document.documentElement.style.backgroundColor, body: document.body.style.backgroundColor },
2522
+ grounds: new Map()
2523
+ });
2524
+ VerificationModal.pageBackground.grounds.set(this, colorScheme);
2525
+ VerificationModal.paintPageBackground();
2213
2526
  }
2214
2527
  restorePageBackground() {
2215
- if (!this.pageBackground)
2528
+ const background = VerificationModal.pageBackground;
2529
+ if (!background?.grounds.delete(this))
2530
+ return;
2531
+ if (background.grounds.size > 0) {
2532
+ VerificationModal.paintPageBackground();
2216
2533
  return;
2217
- document.documentElement.style.backgroundColor = this.pageBackground.root;
2218
- document.body.style.backgroundColor = this.pageBackground.body;
2219
- this.pageBackground = null;
2534
+ }
2535
+ VerificationModal.pageBackground = null;
2536
+ document.documentElement.style.backgroundColor = background.saved.root;
2537
+ document.body.style.backgroundColor = background.saved.body;
2538
+ }
2539
+ /** The page shows the ground of the topmost open modal that lends one. */
2540
+ static paintPageBackground() {
2541
+ const background = VerificationModal.pageBackground;
2542
+ if (!background)
2543
+ return;
2544
+ const lender = [...VerificationModal.openModals].reverse().find((modal) => background.grounds.has(modal));
2545
+ const colorScheme = lender ? background.grounds.get(lender) : [...background.grounds.values()].pop();
2546
+ if (!colorScheme)
2547
+ return;
2548
+ document.documentElement.style.backgroundColor = FLOW_GROUND[colorScheme];
2549
+ document.body.style.backgroundColor = FLOW_GROUND[colorScheme];
2550
+ }
2551
+ /**
2552
+ * Stops the page scrolling under the modal. The lock is on the root element: Chrome for iOS keeps
2553
+ * scrolling a page whose body alone is `overflow: hidden` (a swipe over the modal scrolls the page
2554
+ * and toggles the browser's toolbars), and stops only when the root element is. A page that
2555
+ * scrolls its body instead of the window has its body locked too. The first modal to open keeps
2556
+ * the page's own values and the last one to close gives them back.
2557
+ */
2558
+ lockPageScroll() {
2559
+ const lock = VerificationModal.pageScrollLock;
2560
+ if (lock) {
2561
+ lock.holders.add(this);
2562
+ return;
2563
+ }
2564
+ const root = document.documentElement;
2565
+ const body = document.body;
2566
+ // The body's overflow is the viewport's only while the root's is visible; otherwise a body with
2567
+ // an overflow of its own is a scroll container. Locking a body that is not one would clip the page
2568
+ // to the body's box.
2569
+ const clips = (overflow) => overflow !== "" && overflow !== "visible";
2570
+ const bodyScrollsItself = clips(window.getComputedStyle(root).overflowY) && clips(window.getComputedStyle(body).overflowY);
2571
+ VerificationModal.pageScrollLock = {
2572
+ holders: new Set([this]),
2573
+ root: { overflow: root.style.overflow, overscrollBehavior: root.style.overscrollBehavior },
2574
+ body: bodyScrollsItself ? { overflow: body.style.overflow } : null
2575
+ };
2576
+ root.style.overflow = "hidden";
2577
+ root.style.overscrollBehavior = "none";
2578
+ if (bodyScrollsItself)
2579
+ body.style.overflow = "hidden";
2580
+ }
2581
+ unlockPageScroll() {
2582
+ const lock = VerificationModal.pageScrollLock;
2583
+ if (!lock || !lock.holders.delete(this) || lock.holders.size > 0)
2584
+ return;
2585
+ VerificationModal.pageScrollLock = null;
2586
+ const root = document.documentElement;
2587
+ root.style.overflow = lock.root.overflow;
2588
+ root.style.overscrollBehavior = lock.root.overscrollBehavior;
2589
+ if (lock.body)
2590
+ document.body.style.overflow = lock.body.overflow;
2591
+ }
2592
+ /**
2593
+ * On a phone, Chrome for iOS (and the other iOS browsers built on WebKit's web view) shows a band
2594
+ * of the page below the layout viewport while its toolbars are collapsed: the home indicator's
2595
+ * area, and more while the toolbars move. Fixed elements end at the layout viewport, so the
2596
+ * full-screen modal cannot cover it and the host page's own content showed under the flow. The
2597
+ * curtain is part of the page instead: right below the viewport, in the flow's ground, so that band
2598
+ * shows the modal's ground. The page cannot scroll while the modal is open (lockPageScroll), and the
2599
+ * curtain follows the viewport when it resizes. Only phone-sized windows draw it (see the styles).
2600
+ */
2601
+ showCurtain() {
2602
+ if (!this.curtain) {
2603
+ const curtain = document.createElement("div");
2604
+ curtain.className = CSS_CLASSES.curtain;
2605
+ curtain.setAttribute("aria-hidden", "true");
2606
+ document.body.appendChild(curtain);
2607
+ this.curtain = curtain;
2608
+ this.boundPlaceCurtain = () => this.placeCurtain();
2609
+ window.addEventListener("resize", this.boundPlaceCurtain);
2610
+ window.addEventListener("scroll", this.boundPlaceCurtain);
2611
+ window.visualViewport?.addEventListener("resize", this.boundPlaceCurtain);
2612
+ }
2613
+ // The device's theme until the newly loaded flow reports its own (applyFlowLayout).
2614
+ this.curtain.dataset.diditTheme = window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
2615
+ this.placeCurtain();
2616
+ }
2617
+ /** Puts the curtain's top at the bottom of the layout viewport, whatever its containing block is. */
2618
+ placeCurtain() {
2619
+ const curtain = this.curtain;
2620
+ if (!curtain)
2621
+ return;
2622
+ curtain.style.top = "0px";
2623
+ curtain.style.left = "0px";
2624
+ // At 0, 0 the curtain's box starts at its containing block's corner (the page's, or a positioned
2625
+ // body's), in viewport coordinates: the offset that brings its top to the viewport's bottom edge.
2626
+ const origin = curtain.getBoundingClientRect();
2627
+ curtain.style.top = `${window.innerHeight - origin.top}px`;
2628
+ curtain.style.left = `${-origin.left}px`;
2629
+ }
2630
+ removeCurtain() {
2631
+ if (this.boundPlaceCurtain) {
2632
+ window.removeEventListener("resize", this.boundPlaceCurtain);
2633
+ window.removeEventListener("scroll", this.boundPlaceCurtain);
2634
+ window.visualViewport?.removeEventListener("resize", this.boundPlaceCurtain);
2635
+ this.boundPlaceCurtain = null;
2636
+ }
2637
+ this.curtain?.remove();
2638
+ this.curtain = null;
2220
2639
  }
2221
2640
  /** Back to the neutral look until the newly loaded flow reports its theme and direction. */
2222
2641
  resetFlowLayout() {
@@ -2228,6 +2647,7 @@ class VerificationModal {
2228
2647
  delete this.container.dataset.diditDir;
2229
2648
  delete this.container.dataset.diditKind;
2230
2649
  this.container.style.removeProperty("--didit-content-height");
2650
+ this.container.style.removeProperty("--didit-top-inset");
2231
2651
  if (this.firstLayoutTimeout !== null) {
2232
2652
  window.clearTimeout(this.firstLayoutTimeout);
2233
2653
  this.firstLayoutTimeout = null;
@@ -2294,6 +2714,7 @@ class VerificationModal {
2294
2714
  : this.container?.querySelector(`.${CSS_CLASSES.closeButton}`) ?? this.iframe);
2295
2715
  this.state.showConfirmation = true;
2296
2716
  this.confirmOverlay.classList.add("active");
2717
+ this.curtain?.setAttribute("data-didit-dimmed", "");
2297
2718
  if (this.iframe)
2298
2719
  this.iframe.inert = true;
2299
2720
  const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
@@ -2317,6 +2738,7 @@ class VerificationModal {
2317
2738
  return;
2318
2739
  this.state.showConfirmation = false;
2319
2740
  this.confirmOverlay?.classList.remove("active");
2741
+ this.curtain?.removeAttribute("data-didit-dimmed");
2320
2742
  if (this.iframe)
2321
2743
  this.iframe.inert = false;
2322
2744
  const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
@@ -2344,11 +2766,6 @@ class VerificationModal {
2344
2766
  this.callbacks.onCloseConfirmed();
2345
2767
  }
2346
2768
  open(verificationUrl) {
2347
- // Whether this modal already held its scroll lock before this call. Re-opening
2348
- // an already-open instance must not re-capture previousBodyOverflow, or it
2349
- // would record this modal's own "hidden" lock and close() could never restore
2350
- // the real pre-lock value.
2351
- const wasAlreadyOpen = this.state.isOpen;
2352
2769
  this.language = detectLanguageFromUrl(verificationUrl);
2353
2770
  if (!this.overlay && !this.container) {
2354
2771
  this.createDOM();
@@ -2373,16 +2790,10 @@ class VerificationModal {
2373
2790
  return;
2374
2791
  }
2375
2792
  this.overlay?.classList.add("active");
2376
- // Capture whatever overflow value is currently in effect (which may
2377
- // already be "hidden" because another modal is open) so close() can
2378
- // restore exactly that value instead of clobbering a scroll lock owned
2379
- // by a concurrently open modal. Skip the capture on a re-open: the value
2380
- // in effect is this modal's own lock, and previousBodyOverflow already
2381
- // holds the correct pre-lock value.
2382
- if (!wasAlreadyOpen) {
2383
- this.previousBodyOverflow = document.body.style.overflow;
2384
- }
2385
- document.body.style.overflow = "hidden";
2793
+ // Idempotent: a re-open of a modal that is still open keeps its one hold on the lock, so
2794
+ // close() still gives the page back the values it had before any modal opened.
2795
+ this.lockPageScroll();
2796
+ this.showCurtain();
2386
2797
  }
2387
2798
  close() {
2388
2799
  SDKLogger.log("Closing");
@@ -2400,8 +2811,8 @@ class VerificationModal {
2400
2811
  return;
2401
2812
  }
2402
2813
  this.overlay?.classList.remove("active");
2403
- document.body.style.overflow = this.previousBodyOverflow ?? "";
2404
- this.previousBodyOverflow = null;
2814
+ this.removeCurtain();
2815
+ this.unlockPageScroll();
2405
2816
  }
2406
2817
  destroy() {
2407
2818
  SDKLogger.log("Destroying");
@@ -2433,6 +2844,16 @@ class VerificationModal {
2433
2844
  * a transaction action modal stacked over the verification modal).
2434
2845
  */
2435
2846
  VerificationModal.openModals = [];
2847
+ /**
2848
+ * The page's own background colours, kept while full-screen modals lend it their ground, shared by
2849
+ * every open modal: the topmost one's ground shows and the last one to give it back restores them.
2850
+ */
2851
+ VerificationModal.pageBackground = null;
2852
+ /**
2853
+ * The page's scroll styles from before the first open modal locked them, shared by every open
2854
+ * modal: the last one to close gives them back.
2855
+ */
2856
+ VerificationModal.pageScrollLock = null;
2436
2857
 
2437
2858
  const DEFAULT_TRANSACTION_BASE_URL = "https://verification.didit.me";
2438
2859
  const ACTION_POLL_INTERVAL_MS = 1500;
@@ -2752,6 +3173,18 @@ function assertEmbeddedHostExists(configuration) {
2752
3173
  throw new Error(`Embedded container "#${containerId}" was not found in the page.`);
2753
3174
  }
2754
3175
  }
3176
+ /**
3177
+ * The device id this page already keeps for Didit (it has sent events, transactions or sign-ins),
3178
+ * or null. Reading it never creates one, and a browser that refuses the read is not an error.
3179
+ */
3180
+ function storedDeviceId() {
3181
+ try {
3182
+ return getStoredDeviceId();
3183
+ }
3184
+ catch {
3185
+ return null;
3186
+ }
3187
+ }
2755
3188
  class DiditSdk {
2756
3189
  static get shared() {
2757
3190
  if (!DiditSdk._instance) {
@@ -2825,7 +3258,7 @@ class DiditSdk {
2825
3258
  onMessage: (event) => this.handleVerificationEvent(event),
2826
3259
  onIframeLoad: () => this.handleIframeLoad()
2827
3260
  });
2828
- this._url = buildVerificationUrl(url, config);
3261
+ this._url = buildVerificationUrl(url, config, storedDeviceId());
2829
3262
  this.setState("loading");
2830
3263
  this.emitInternalEvent("didit:started", {});
2831
3264
  this._modal?.open(this._url);
@@ -3211,5 +3644,5 @@ class DiditSdk {
3211
3644
  }
3212
3645
  DiditSdk._instance = null;
3213
3646
 
3214
- export { DEFAULT_EVENTS_BASE_URL, DEFAULT_TRANSACTION_BASE_URL, DiditEventError, DiditSdk, DiditTransactionError, SDK_VERSION, buildFingerprintHeaders, configureEvents, DiditSdk as default, flush, getDeviceFingerprintPayload, submitEvent };
3647
+ export { DEFAULT_EVENTS_BASE_URL, DEFAULT_TRANSACTION_BASE_URL, DiditEventError, DiditSdk, DiditTransactionError, SDK_VERSION, buildFingerprintHeaders, configureEvents, DiditSdk as default, flush, getDeviceFingerprintPayload, getStoredDeviceId, setDeviceSignalsProvider, submitEvent };
3215
3648
  //# sourceMappingURL=didit-sdk.esm.js.map