@touchque/device-risk 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1580 @@
1
+ 'use strict';
2
+
3
+ // src/fingerprint.ts
4
+ var STORAGE_KEY = "tq_device_id";
5
+ var ID_VERSION = "tq2";
6
+ function randomId() {
7
+ const bytes = new Uint8Array(16);
8
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(bytes);
9
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
10
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
11
+ }
12
+ function readOrCreateDeviceId() {
13
+ try {
14
+ const existing = window.localStorage.getItem(STORAGE_KEY);
15
+ if (existing && /^tq2_[0-9a-f]{32}$/.test(existing)) return existing;
16
+ const created = `${ID_VERSION}_${randomId()}`;
17
+ window.localStorage.setItem(STORAGE_KEY, created);
18
+ return created;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+ function webglRenderer() {
24
+ try {
25
+ const canvas = document.createElement("canvas");
26
+ const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
27
+ if (!gl) return null;
28
+ const ext = gl.getExtension("WEBGL_debug_renderer_info");
29
+ if (!ext) return gl.getParameter(gl.RENDERER);
30
+ return `${gl.getParameter(ext.UNMASKED_VENDOR_WEBGL)}|${gl.getParameter(ext.UNMASKED_RENDERER_WEBGL)}`;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+ function canvasSignature() {
36
+ try {
37
+ const canvas = document.createElement("canvas");
38
+ canvas.width = 240;
39
+ canvas.height = 60;
40
+ const ctx = canvas.getContext("2d");
41
+ if (!ctx) return null;
42
+ ctx.textBaseline = "alphabetic";
43
+ ctx.fillStyle = "#f60";
44
+ ctx.fillRect(125, 1, 62, 20);
45
+ ctx.fillStyle = "#069";
46
+ ctx.font = "14px 'Arial'";
47
+ ctx.fillText("TouchQue device \u{1F512} \xE7\u011F\u0131\xF6\u015F\xFC", 2, 15);
48
+ ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
49
+ ctx.font = "18px serif";
50
+ ctx.fillText("TouchQue device \u{1F512} \xE7\u011F\u0131\xF6\u015F\xFC", 4, 40);
51
+ ctx.globalCompositeOperation = "multiply";
52
+ ctx.fillStyle = "rgb(255,0,255)";
53
+ ctx.beginPath();
54
+ ctx.arc(50, 30, 20, 0, Math.PI * 2, true);
55
+ ctx.fill();
56
+ return canvas.toDataURL();
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+ async function audioSignature() {
62
+ try {
63
+ const Ctx = window;
64
+ const Offline = Ctx.OfflineAudioContext || Ctx.webkitOfflineAudioContext;
65
+ if (!Offline) return null;
66
+ const context = new Offline(1, 5e3, 44100);
67
+ const oscillator = context.createOscillator();
68
+ oscillator.type = "triangle";
69
+ oscillator.frequency.value = 1e4;
70
+ const compressor = context.createDynamicsCompressor();
71
+ oscillator.connect(compressor);
72
+ compressor.connect(context.destination);
73
+ oscillator.start(0);
74
+ const buffer = await Promise.race([
75
+ context.startRendering(),
76
+ new Promise((resolve) => setTimeout(() => resolve(null), 1500))
77
+ ]);
78
+ if (!buffer) return null;
79
+ const data = buffer.getChannelData(0);
80
+ let sum = 0;
81
+ for (let i = 4500; i < 5e3; i++) sum += Math.abs(data[i]);
82
+ return sum.toFixed(6);
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+ var FONT_PROBES = [
88
+ "Arial",
89
+ "Helvetica",
90
+ "Times New Roman",
91
+ "Courier New",
92
+ "Verdana",
93
+ "Georgia",
94
+ "Palatino",
95
+ "Garamond",
96
+ "Comic Sans MS",
97
+ "Trebuchet MS",
98
+ "Impact",
99
+ "Tahoma",
100
+ "Segoe UI",
101
+ "Calibri",
102
+ "Cambria",
103
+ "Consolas",
104
+ "Menlo",
105
+ "Monaco",
106
+ "Roboto",
107
+ "Ubuntu",
108
+ "Noto Sans",
109
+ "Lucida Grande",
110
+ "Helvetica Neue",
111
+ "SF Pro Text",
112
+ "Apple Color Emoji"
113
+ ];
114
+ function installedFonts() {
115
+ try {
116
+ const span = document.createElement("span");
117
+ span.style.cssText = "position:absolute;left:-9999px;top:-9999px;font-size:72px;visibility:hidden";
118
+ span.textContent = "mmmmmmmmmmlliWWW";
119
+ document.body.appendChild(span);
120
+ const measure = (family) => {
121
+ span.style.fontFamily = family;
122
+ return `${span.offsetWidth}x${span.offsetHeight}`;
123
+ };
124
+ const baselines = ["monospace", "sans-serif", "serif"].map(measure);
125
+ const found = [];
126
+ for (const font of FONT_PROBES) {
127
+ const differs = ["monospace", "sans-serif", "serif"].some((base, i) => measure(`'${font}',${base}`) !== baselines[i]);
128
+ if (differs) found.push(font);
129
+ }
130
+ document.body.removeChild(span);
131
+ return found;
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+ function cyrb53Hex(input, seed) {
137
+ let h1 = 3735928559 ^ seed, h2 = 1103547991 ^ seed;
138
+ for (let i = 0; i < input.length; i++) {
139
+ const ch = input.charCodeAt(i);
140
+ h1 = Math.imul(h1 ^ ch, 2654435761);
141
+ h2 = Math.imul(h2 ^ ch, 1597334677);
142
+ }
143
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
144
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
145
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, "0");
146
+ }
147
+ async function digestHex(input) {
148
+ try {
149
+ if (typeof crypto !== "undefined" && crypto.subtle) {
150
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
151
+ return { hex: Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join(""), weak: false };
152
+ }
153
+ } catch {
154
+ }
155
+ return { hex: [1, 2, 3, 4, 5].map((seed) => cyrb53Hex(input, seed)).join("").slice(0, 64), weak: true };
156
+ }
157
+
158
+ // src/browserKey.ts
159
+ var DB_NAME = "touchque";
160
+ var STORE_NAME = "keys";
161
+ var KEY_NAME = "browser-key-v1";
162
+ function browserProofMessage(aud, iat, nonce) {
163
+ return `touchque-browser:v1
164
+ ${aud}
165
+ ${iat}
166
+ ${nonce}`;
167
+ }
168
+ function deviceSealMessage(aud, iat, nonce, digest) {
169
+ return `touchque-device:v1
170
+ ${aud}
171
+ ${iat}
172
+ ${nonce}
173
+ ${digest}`;
174
+ }
175
+ function browserKeyThumbprintInput(jwk) {
176
+ return JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y });
177
+ }
178
+ async function browserKeyThumbprint(jwk, subtle = globalThis.crypto.subtle) {
179
+ const digest = await subtle.digest("SHA-256", utf8(browserKeyThumbprintInput(jwk)));
180
+ return base64url(new Uint8Array(digest));
181
+ }
182
+ function utf8(s) {
183
+ return new TextEncoder().encode(s);
184
+ }
185
+ function base64url(bytes) {
186
+ let bin = "";
187
+ for (let i = 0; i < bytes.length; i += 1) bin += String.fromCharCode(bytes[i]);
188
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
189
+ }
190
+ function isKeyPair(v) {
191
+ const p = v;
192
+ return !!p && typeof p === "object" && !!p.privateKey && p.privateKey.type === "private" && !!p.publicKey && p.publicKey.type === "public";
193
+ }
194
+ function indexedDbStore(idb) {
195
+ const open = () => new Promise((resolve, reject) => {
196
+ const req = idb.open(DB_NAME, 1);
197
+ req.onupgradeneeded = () => {
198
+ if (!req.result.objectStoreNames.contains(STORE_NAME)) req.result.createObjectStore(STORE_NAME);
199
+ };
200
+ let failed = false;
201
+ req.onsuccess = () => {
202
+ if (failed) req.result.close();
203
+ else resolve(req.result);
204
+ };
205
+ req.onerror = () => {
206
+ failed = true;
207
+ reject(req.error);
208
+ };
209
+ req.onblocked = () => {
210
+ failed = true;
211
+ reject(new Error("IndexedDB open blocked"));
212
+ };
213
+ });
214
+ async function run(mode, fn) {
215
+ const db = await open();
216
+ try {
217
+ return await new Promise((resolve, reject) => {
218
+ const tx = db.transaction(STORE_NAME, mode);
219
+ let value;
220
+ fn(tx.objectStore(STORE_NAME), (v) => {
221
+ value = v;
222
+ });
223
+ tx.oncomplete = () => resolve(value);
224
+ tx.onerror = () => reject(tx.error);
225
+ tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
226
+ });
227
+ } finally {
228
+ db.close();
229
+ }
230
+ }
231
+ return {
232
+ load: () => run("readonly", (store, report) => {
233
+ const req = store.get(KEY_NAME);
234
+ req.onsuccess = () => report(isKeyPair(req.result) ? req.result : void 0);
235
+ }),
236
+ // Read and write in one readwrite transaction: they are serialized across
237
+ // tabs, so two tabs making a key at once end up with the same one.
238
+ save: (pair) => run("readwrite", (store, report) => {
239
+ const req = store.get(KEY_NAME);
240
+ req.onsuccess = () => {
241
+ if (isKeyPair(req.result)) return report(req.result);
242
+ store.put({ privateKey: pair.privateKey, publicKey: pair.publicKey }, KEY_NAME);
243
+ report(pair);
244
+ };
245
+ }),
246
+ remove: () => run("readwrite", (store, report) => {
247
+ store.delete(KEY_NAME);
248
+ report(void 0);
249
+ })
250
+ };
251
+ }
252
+ function within(work, ms) {
253
+ return new Promise((resolve) => {
254
+ const timer = setTimeout(() => resolve(null), ms);
255
+ work().then(
256
+ (value) => {
257
+ clearTimeout(timer);
258
+ resolve(value);
259
+ },
260
+ () => {
261
+ clearTimeout(timer);
262
+ resolve(null);
263
+ }
264
+ );
265
+ });
266
+ }
267
+ var HINTS_TIMEOUT_MS = 300;
268
+ var HINT_MAX_BRANDS = 8;
269
+ var HINT_MAX_CHARS = 64;
270
+ var MAX_HEADER_CHARS = 2048;
271
+ var hintString = (v) => typeof v === "string" ? v.trim().slice(0, HINT_MAX_CHARS) : "";
272
+ function reduceHints(values, mobileFallback) {
273
+ if (!values || typeof values !== "object") return null;
274
+ const v = values;
275
+ const list = Array.isArray(v.fullVersionList) ? v.fullVersionList : [];
276
+ const fullVersionList = [];
277
+ for (const entry of list) {
278
+ if (fullVersionList.length >= HINT_MAX_BRANDS) break;
279
+ const e = entry && typeof entry === "object" ? entry : {};
280
+ const brand = hintString(e.brand);
281
+ if (brand) fullVersionList.push({ brand, version: hintString(e.version) });
282
+ }
283
+ return {
284
+ platform: hintString(v.platform),
285
+ platformVersion: hintString(v.platformVersion),
286
+ fullVersionList,
287
+ mobile: (typeof v.mobile === "boolean" ? v.mobile : mobileFallback) === true,
288
+ model: hintString(v.model)
289
+ };
290
+ }
291
+ function defaultUserAgentData() {
292
+ try {
293
+ const uad = typeof navigator !== "undefined" ? navigator.userAgentData : void 0;
294
+ return uad && typeof uad.getHighEntropyValues === "function" ? uad : null;
295
+ } catch {
296
+ return null;
297
+ }
298
+ }
299
+ function defaultStore() {
300
+ try {
301
+ return typeof indexedDB !== "undefined" && indexedDB ? indexedDbStore(indexedDB) : null;
302
+ } catch {
303
+ return null;
304
+ }
305
+ }
306
+ function createBrowserKey(options = {}) {
307
+ let storeMemo;
308
+ const store = () => {
309
+ if (storeMemo === void 0) storeMemo = options.store !== void 0 ? options.store : defaultStore();
310
+ return storeMemo;
311
+ };
312
+ const cryptoImpl = () => {
313
+ try {
314
+ const c = options.crypto ?? globalThis.crypto;
315
+ return c && c.subtle && typeof c.getRandomValues === "function" ? c : null;
316
+ } catch {
317
+ return null;
318
+ }
319
+ };
320
+ const audience = () => {
321
+ let aud = options.origin;
322
+ if (aud === void 0) {
323
+ try {
324
+ aud = typeof location !== "undefined" ? location.origin : void 0;
325
+ } catch {
326
+ aud = void 0;
327
+ }
328
+ }
329
+ return typeof aud === "string" && aud !== "" && aud !== "null" ? aud : null;
330
+ };
331
+ let current2;
332
+ const keys = (c, s) => {
333
+ if (!current2) {
334
+ const loading = (async () => {
335
+ let pair = await s.load();
336
+ if (!isKeyPair(pair)) {
337
+ const made = await c.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
338
+ pair = await s.save(made);
339
+ if (!isKeyPair(pair)) throw new Error("browser key not stored");
340
+ }
341
+ const pub = await c.subtle.exportKey("jwk", pair.publicKey);
342
+ if (pub.kty !== "EC" || pub.crv !== "P-256" || typeof pub.x !== "string" || typeof pub.y !== "string") {
343
+ throw new Error("browser key is not P-256");
344
+ }
345
+ return { pair, jwk: { kty: "EC", crv: "P-256", x: pub.x, y: pub.y } };
346
+ })();
347
+ current2 = loading;
348
+ loading.catch(() => {
349
+ if (current2 === loading) current2 = void 0;
350
+ });
351
+ }
352
+ return current2;
353
+ };
354
+ let hintsMemo;
355
+ const hints = () => {
356
+ if (!hintsMemo) {
357
+ hintsMemo = (async () => {
358
+ try {
359
+ const uad = options.userAgentData !== void 0 ? options.userAgentData : defaultUserAgentData();
360
+ if (!uad || typeof uad.getHighEntropyValues !== "function") return null;
361
+ const values = await uad.getHighEntropyValues(["platformVersion", "fullVersionList", "model"]);
362
+ return reduceHints(values, uad.mobile);
363
+ } catch {
364
+ return null;
365
+ }
366
+ })();
367
+ }
368
+ return hintsMemo;
369
+ };
370
+ const timeoutMs = options.timeoutMs ?? 2e3;
371
+ return {
372
+ proof: () => within(async () => {
373
+ const c = cryptoImpl();
374
+ const s = store();
375
+ const aud = audience();
376
+ if (!c || !s || !aud) return null;
377
+ const { pair, jwk } = await keys(c, s);
378
+ const iat = Math.floor((options.now ?? Date.now)() / 1e3);
379
+ const nonce = base64url(c.getRandomValues(new Uint8Array(16)));
380
+ const sig = new Uint8Array(await c.subtle.sign(
381
+ { name: "ECDSA", hash: "SHA-256" },
382
+ pair.privateKey,
383
+ utf8(browserProofMessage(aud, iat, nonce))
384
+ ));
385
+ if (sig.length !== 64) return null;
386
+ const proof = { v: 1, jwk, aud, iat, nonce, sig: base64url(sig) };
387
+ const h = await within(hints, HINTS_TIMEOUT_MS);
388
+ if (h) {
389
+ const withHints = base64url(utf8(JSON.stringify({ ...proof, hints: h })));
390
+ if (withHints.length <= MAX_HEADER_CHARS) return withHints;
391
+ }
392
+ return base64url(utf8(JSON.stringify(proof)));
393
+ }, timeoutMs),
394
+ sealDevice: (digest) => within(async () => {
395
+ const c = cryptoImpl();
396
+ const s = store();
397
+ const aud = audience();
398
+ if (!c || !s || !aud || !/^[A-Za-z0-9_-]{43}$/.test(digest)) return null;
399
+ const { pair, jwk } = await keys(c, s);
400
+ const iat = Math.floor((options.now ?? Date.now)() / 1e3);
401
+ const nonce = base64url(c.getRandomValues(new Uint8Array(16)));
402
+ const sig = new Uint8Array(await c.subtle.sign(
403
+ { name: "ECDSA", hash: "SHA-256" },
404
+ pair.privateKey,
405
+ utf8(deviceSealMessage(aud, iat, nonce, digest))
406
+ ));
407
+ if (sig.length !== 64) return null;
408
+ return { jwk, aud, iat, nonce, sig: base64url(sig) };
409
+ }, timeoutMs),
410
+ thumbprint: () => within(async () => {
411
+ const c = cryptoImpl();
412
+ const s = store();
413
+ if (!c || !s) return null;
414
+ if (!current2) {
415
+ const stored = await s.load();
416
+ if (!isKeyPair(stored)) return null;
417
+ }
418
+ const { jwk } = await keys(c, s);
419
+ return browserKeyThumbprint(jwk, c.subtle);
420
+ }, timeoutMs),
421
+ async forget() {
422
+ current2 = void 0;
423
+ await within(async () => {
424
+ await store()?.remove();
425
+ return null;
426
+ }, timeoutMs);
427
+ }
428
+ };
429
+ }
430
+ var browserKey = createBrowserKey();
431
+
432
+ // src/log.ts
433
+ var current = null;
434
+ function setTouchqueLogger(logger) {
435
+ current = logger;
436
+ }
437
+ function logWarn(message) {
438
+ try {
439
+ current?.warn(message);
440
+ } catch {
441
+ }
442
+ }
443
+ function errorText(err) {
444
+ return err instanceof Error ? err.message : typeof err === "string" ? err : "unknown error";
445
+ }
446
+
447
+ // src/reportKey.ts
448
+ var REPORT_KEY = {
449
+ kid: "9d8a2f55",
450
+ jwk: { kty: "EC", crv: "P-256", x: "QXrbInfJL8yPadD1kbcSDFajSop7_-DoK7oTbEO5sGU", y: "LqIO9D9uliBoFiR1kLk_1hT3eKvoFQqqkhydzFAkM5Y" }
451
+ };
452
+
453
+ // src/envelope.ts
454
+ var PREFIX = "tqe1";
455
+ var INFO = new TextEncoder().encode("touchque-device-report:v1");
456
+ function b64url(bytes) {
457
+ let bin = "";
458
+ for (let i = 0; i < bytes.length; i += 1) bin += String.fromCharCode(bytes[i]);
459
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
460
+ }
461
+ async function sealReport(json, key = REPORT_KEY, subtle = globalThis.crypto?.subtle) {
462
+ if (!subtle || !key) return null;
463
+ try {
464
+ const peer = await subtle.importKey("jwk", { ...key.jwk, ext: true }, { name: "ECDH", namedCurve: "P-256" }, false, []);
465
+ const mine = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
466
+ const epk = new Uint8Array(await subtle.exportKey("raw", mine.publicKey));
467
+ const shared = await subtle.deriveBits({ name: "ECDH", public: peer }, mine.privateKey, 256);
468
+ const hkdf = await subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
469
+ const aes = await subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: epk, info: INFO }, hkdf, { name: "AES-GCM", length: 256 }, false, ["encrypt"]);
470
+ const iv = new Uint8Array(12);
471
+ globalThis.crypto.getRandomValues(iv);
472
+ const ct = new Uint8Array(await subtle.encrypt(
473
+ { name: "AES-GCM", iv, additionalData: new TextEncoder().encode(`${PREFIX}.${key.kid}`) },
474
+ aes,
475
+ new TextEncoder().encode(json)
476
+ ));
477
+ return [PREFIX, key.kid, b64url(epk), b64url(iv), b64url(ct)].join(".");
478
+ } catch {
479
+ return null;
480
+ }
481
+ }
482
+
483
+ // src/deviceRisk.ts
484
+ var DEVICE_RISK_PURPOSES = ["sign_in", "sign_up", "password_reset", "approval"];
485
+ var DEVICE_RISK_FIELD = "deviceRisk";
486
+ var DEVICE_RISK_HEADER = "X-Touchque-Device";
487
+ var MAX_ENCODED = 6144;
488
+ function base64url2(bytes) {
489
+ let bin = "";
490
+ for (let i = 0; i < bytes.length; i += 1) bin += String.fromCharCode(bytes[i]);
491
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
492
+ }
493
+ function encodeJson(value) {
494
+ return base64url2(new TextEncoder().encode(JSON.stringify(value)));
495
+ }
496
+ function randomNonce() {
497
+ const bytes = new Uint8Array(16);
498
+ try {
499
+ crypto.getRandomValues(bytes);
500
+ } catch {
501
+ for (let i = 0; i < 16; i += 1) bytes[i] = Math.floor(Math.random() * 256);
502
+ }
503
+ return base64url2(bytes);
504
+ }
505
+ var short = (v, n) => typeof v === "string" ? v.slice(0, n) : "";
506
+ var hex16 = async (input) => input === null ? null : (await digestHex(input)).hex.slice(0, 16);
507
+ function within2(work, ms, fallback) {
508
+ return new Promise((resolve) => {
509
+ const timer = setTimeout(() => resolve(fallback), ms);
510
+ work.then((v) => {
511
+ clearTimeout(timer);
512
+ resolve(v);
513
+ }, () => {
514
+ clearTimeout(timer);
515
+ resolve(fallback);
516
+ });
517
+ });
518
+ }
519
+ function osFamily(ua, platform) {
520
+ if (/CrOS/.test(ua)) return "ChromeOS";
521
+ if (/Android/i.test(ua)) return "Android";
522
+ if (/iPhone|iPad|iPod/.test(ua) || /Macintosh/.test(ua) && /Mobile\//.test(ua)) return "iOS";
523
+ if (/Windows/.test(ua) || /^Win/.test(platform)) return "Windows";
524
+ if (/Mac OS X|Macintosh/.test(ua) || /^Mac/.test(platform)) return "macOS";
525
+ if (/Linux|X11/.test(ua) || /Linux/.test(platform)) return "Linux";
526
+ return "Other";
527
+ }
528
+ function browserFamily(ua) {
529
+ const v = (re) => {
530
+ const m = re.exec(ua);
531
+ return m ? Number(m[1]) || 0 : 0;
532
+ };
533
+ if (/Edg(e|A|iOS)?\//.test(ua)) return { br: "Edge", bv: v(/Edg(?:e|A|iOS)?\/(\d+)/) };
534
+ if (/OPR\/|Opera/.test(ua)) return { br: "Opera", bv: v(/OPR\/(\d+)/) };
535
+ if (/SamsungBrowser\//.test(ua)) return { br: "Samsung", bv: v(/SamsungBrowser\/(\d+)/) };
536
+ if (/Firefox\/|FxiOS\//.test(ua)) return { br: "Firefox", bv: v(/(?:Firefox|FxiOS)\/(\d+)/) };
537
+ if (/Chrome\/|CriOS\//.test(ua)) return { br: "Chrome", bv: v(/(?:Chrome|CriOS)\/(\d+)/) };
538
+ if (/Safari\//.test(ua) && /Version\//.test(ua)) return { br: "Safari", bv: v(/Version\/(\d+)/) };
539
+ return { br: "Other", bv: 0 };
540
+ }
541
+ function mathDigestInput() {
542
+ const M = Math;
543
+ return [
544
+ M.acos(0.12312423423423424),
545
+ M.acosh(1e308),
546
+ M.asinh(1),
547
+ M.atanh(0.5),
548
+ M.expm1(1),
549
+ M.sinh(1),
550
+ M.cosh(1),
551
+ M.tan(-1e300),
552
+ M.log1p(10),
553
+ M.cbrt(Math.PI),
554
+ M.exp(1) ** 10
555
+ ].map(String).join(",");
556
+ }
557
+ function webglLimits() {
558
+ try {
559
+ const gl = document.createElement("canvas").getContext("webgl");
560
+ if (!gl) return null;
561
+ const keys = [
562
+ gl.MAX_TEXTURE_SIZE,
563
+ gl.MAX_RENDERBUFFER_SIZE,
564
+ gl.MAX_VERTEX_ATTRIBS,
565
+ gl.MAX_VERTEX_UNIFORM_VECTORS,
566
+ gl.MAX_FRAGMENT_UNIFORM_VECTORS,
567
+ gl.MAX_VARYING_VECTORS,
568
+ gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS,
569
+ gl.MAX_VIEWPORT_DIMS,
570
+ gl.ALIASED_LINE_WIDTH_RANGE,
571
+ gl.ALIASED_POINT_SIZE_RANGE
572
+ ];
573
+ const values = keys.map((k) => {
574
+ const v = gl.getParameter(k);
575
+ return v && typeof v === "object" ? Array.from(v).join("x") : String(v);
576
+ });
577
+ const ext = (gl.getSupportedExtensions() || []).slice().sort().join(",");
578
+ return `${values.join("|")}#${ext}`;
579
+ } catch {
580
+ return null;
581
+ }
582
+ }
583
+ async function collectTraits(win) {
584
+ const nav = win.navigator;
585
+ const ua = nav.userAgent || "";
586
+ const platform = short(nav.platform, 32);
587
+ const { br, bv } = browserFamily(ua);
588
+ let tz = "";
589
+ try {
590
+ tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
591
+ } catch {
592
+ }
593
+ const w = win.screen?.width || 0;
594
+ const h = win.screen?.height || 0;
595
+ const canvasRaw = canvasSignature();
596
+ const gpuRaw = webglRenderer();
597
+ const fonts = installedFonts();
598
+ const traits = {
599
+ os: osFamily(ua, platform),
600
+ br,
601
+ bv,
602
+ pf: platform,
603
+ tz: short(tz, 64),
604
+ tzo: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
605
+ lang: (Array.isArray(nav.languages) && nav.languages.length ? nav.languages : [nav.language || ""]).slice(0, 3).map((l) => short(l, 16)),
606
+ scr: `${Math.max(w, h)}x${Math.min(w, h)}`,
607
+ cd: win.screen?.colorDepth || 0,
608
+ dpr: Math.round((win.devicePixelRatio || 1) * 100) / 100,
609
+ hc: nav.hardwareConcurrency || 0,
610
+ dm: typeof nav.deviceMemory === "number" ? nav.deviceMemory : null,
611
+ tp: nav.maxTouchPoints || 0,
612
+ gpu: gpuRaw ? gpuRaw.slice(0, 128) : null,
613
+ cv: await hex16(canvasRaw),
614
+ au: null,
615
+ fn: fonts ? await hex16(fonts.join(",")) : null,
616
+ mt: await hex16(mathDigestInput()),
617
+ wg: await hex16(webglLimits())
618
+ };
619
+ return { traits, canvasRaw, gpuRaw, fonts };
620
+ }
621
+ var NATIVE = /\{\s*\[native code\]\s*\}\s*$/;
622
+ var WATCHED = [
623
+ ["nav_user_agent", () => Navigator.prototype, "userAgent", "get"],
624
+ ["nav_platform", () => Navigator.prototype, "platform", "get"],
625
+ ["nav_languages", () => Navigator.prototype, "languages", "get"],
626
+ ["nav_cores", () => Navigator.prototype, "hardwareConcurrency", "get"],
627
+ ["nav_webdriver", () => Navigator.prototype, "webdriver", "get"],
628
+ ["nav_touch", () => Navigator.prototype, "maxTouchPoints", "get"],
629
+ ["screen_width", () => Screen.prototype, "width", "get"],
630
+ ["screen_height", () => Screen.prototype, "height", "get"],
631
+ ["canvas_data_url", () => HTMLCanvasElement.prototype, "toDataURL", "value"],
632
+ ["canvas_context", () => HTMLCanvasElement.prototype, "getContext", "value"],
633
+ ["canvas_image_data", () => typeof CanvasRenderingContext2D !== "undefined" ? CanvasRenderingContext2D.prototype : void 0, "getImageData", "value"],
634
+ ["webgl_parameter", () => typeof WebGLRenderingContext !== "undefined" ? WebGLRenderingContext.prototype : void 0, "getParameter", "value"],
635
+ ["tz_resolved", () => Intl.DateTimeFormat.prototype, "resolvedOptions", "value"],
636
+ ["tz_offset", () => Date.prototype, "getTimezoneOffset", "value"],
637
+ ["audio_channel", () => typeof AudioBuffer !== "undefined" ? AudioBuffer.prototype : void 0, "getChannelData", "value"]
638
+ ];
639
+ var OWN_ON_INSTANCE = [
640
+ ["nav_own_property", () => navigator, "userAgent"],
641
+ ["nav_own_property", () => navigator, "platform"],
642
+ ["nav_own_property", () => navigator, "webdriver"],
643
+ ["nav_own_property", () => navigator, "hardwareConcurrency"],
644
+ ["nav_own_property", () => navigator, "languages"],
645
+ ["screen_own_property", () => screen, "width"]
646
+ ];
647
+ function isNative(fn) {
648
+ try {
649
+ if (typeof fn !== "function") return true;
650
+ if (!NATIVE.test(Function.prototype.toString.call(fn))) return false;
651
+ return !Object.prototype.hasOwnProperty.call(fn, "prototype");
652
+ } catch {
653
+ return false;
654
+ }
655
+ }
656
+ function tamperFindings(win, native = isNative) {
657
+ const out = /* @__PURE__ */ new Set();
658
+ if (!native(Function.prototype.toString)) out.add("fn_to_string");
659
+ for (const [code, target, prop, kind] of WATCHED) {
660
+ try {
661
+ const proto = target();
662
+ if (!proto) continue;
663
+ const d = Object.getOwnPropertyDescriptor(proto, prop);
664
+ if (!d) continue;
665
+ if (!native(kind === "get" ? d.get : d.value)) out.add(code);
666
+ } catch {
667
+ }
668
+ }
669
+ for (const [code, target, prop] of OWN_ON_INSTANCE) {
670
+ try {
671
+ const obj = target();
672
+ if (obj && Object.prototype.hasOwnProperty.call(obj, prop)) out.add(code);
673
+ } catch {
674
+ }
675
+ }
676
+ const nav = win.navigator;
677
+ const ua = nav.userAgent || "";
678
+ const os = osFamily(ua, "");
679
+ const pf = nav.platform || "";
680
+ try {
681
+ const pfOs = /^Win/.test(pf) ? "Windows" : /^Mac/.test(pf) ? "macOS" : /^(iPhone|iPad|iPod)/.test(pf) ? "iOS" : /Linux|Android/.test(pf) ? "Linux" : "";
682
+ const uaOs = os === "Android" || os === "ChromeOS" ? "Linux" : os;
683
+ if (pfOs && uaOs !== "Other" && pfOs !== uaOs && !(uaOs === "iOS" && pfOs === "macOS") && !(uaOs === "macOS" && pfOs === "iOS")) out.add("ua_platform_mismatch");
684
+ } catch {
685
+ }
686
+ try {
687
+ const chPf = nav.userAgentData?.platform;
688
+ if (chPf) {
689
+ const map = { Windows: "Windows", macOS: "macOS", Linux: "Linux", Android: "Android", "Chrome OS": "ChromeOS", ChromeOS: "ChromeOS", iOS: "iOS" };
690
+ if (map[chPf] && os !== "Other" && map[chPf] !== os) out.add("uach_platform_mismatch");
691
+ }
692
+ } catch {
693
+ }
694
+ try {
695
+ const gecko = typeof win.mozInnerScreenX === "number";
696
+ const { br } = browserFamily(ua);
697
+ if (br === "Firefox" && !/FxiOS/.test(ua) && !gecko) out.add("ua_engine_mismatch");
698
+ if ((br === "Chrome" || br === "Edge" || br === "Opera") && !/CriOS|EdgiOS|OPT\//.test(ua) && gecko) out.add("ua_engine_mismatch");
699
+ } catch {
700
+ }
701
+ try {
702
+ const langs = nav.languages;
703
+ if (Array.isArray(langs) && langs.length && nav.language && langs[0] !== nav.language) out.add("language_mismatch");
704
+ } catch {
705
+ }
706
+ try {
707
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
708
+ if (tz) {
709
+ const now = /* @__PURE__ */ new Date();
710
+ const there = new Date(now.toLocaleString("en-US", { timeZone: tz }));
711
+ const utc = new Date(now.toLocaleString("en-US", { timeZone: "UTC" }));
712
+ const zoneOffset = Math.round((utc.getTime() - there.getTime()) / 6e4);
713
+ if (Math.abs(zoneOffset - now.getTimezoneOffset()) > 1) out.add("timezone_mismatch");
714
+ }
715
+ } catch {
716
+ }
717
+ try {
718
+ const hc = nav.hardwareConcurrency;
719
+ if (typeof hc === "number" && (hc < 1 || hc > 256 || !Number.isInteger(hc))) out.add("impossible_cores");
720
+ } catch {
721
+ }
722
+ return [...out].sort();
723
+ }
724
+ function jsEngine() {
725
+ try {
726
+ const nothing = null;
727
+ return nothing.x === void 0 ? null : null;
728
+ } catch (e) {
729
+ const m = String(e?.message || "");
730
+ if (/Cannot read propert/.test(m)) return "v8";
731
+ if (/is not an object/.test(m)) return "jsc";
732
+ if (/has no properties|can't access property/.test(m)) return "gecko";
733
+ return null;
734
+ }
735
+ }
736
+ var DESKTOP_GPU = /NVIDIA|GeForce|Quadro|Radeon|Intel\(R\)|Intel Iris|Intel UHD|Intel HD|Direct3D|D3D11|Apple M\d|Metal Renderer/i;
737
+ var PHONE_GPU = /Mali-|PowerVR|Xclipse|Immortalis|Adreno/i;
738
+ function consistencyFindings(win, t, fonts, engine = jsEngine()) {
739
+ const out = /* @__PURE__ */ new Set();
740
+ if (engine) {
741
+ const want = t.os === "iOS" || t.br === "Safari" ? "jsc" : t.br === "Firefox" ? "gecko" : ["Chrome", "Edge", "Opera", "Samsung"].includes(t.br) ? "v8" : null;
742
+ if (want && engine !== want) out.add("ua_engine_mismatch");
743
+ }
744
+ const gpu = t.gpu || "";
745
+ if (gpu) {
746
+ if (t.os === "iOS" && !/Apple GPU/i.test(gpu)) out.add("gpu_os_mismatch");
747
+ if (t.os === "Android" && DESKTOP_GPU.test(gpu)) out.add("gpu_os_mismatch");
748
+ if (t.os === "Windows" && /Apple GPU|Apple M\d|Mali-|PowerVR|Xclipse|Immortalis/i.test(gpu)) out.add("gpu_os_mismatch");
749
+ if (t.os === "macOS" && (/Direct3D|D3D11/i.test(gpu) || PHONE_GPU.test(gpu) && !/Apple/i.test(gpu))) out.add("gpu_os_mismatch");
750
+ }
751
+ if (fonts) {
752
+ const has = (f) => fonts.includes(f);
753
+ if ((t.os === "macOS" || t.os === "iOS" || t.os === "Android") && has("Segoe UI")) out.add("fonts_os_mismatch");
754
+ if ((t.os === "Windows" || t.os === "Android") && has("Apple Color Emoji") && has("Menlo")) out.add("fonts_os_mismatch");
755
+ }
756
+ if (t.os === "iOS" && /^Mac/.test(t.pf || "")) out.add("ua_platform_mismatch");
757
+ if (t.os === "iOS" || t.os === "Android") {
758
+ let finePointerOnly = false;
759
+ try {
760
+ finePointerOnly = !!win.matchMedia && win.matchMedia("(any-pointer: fine)").matches && !win.matchMedia("(any-pointer: coarse)").matches;
761
+ } catch {
762
+ }
763
+ if (t.tp === 0 || finePointerOnly) out.add("mobile_desktop_mismatch");
764
+ const long = Number(String(t.scr || "").split("x")[0]) || 0;
765
+ if (t.os === "iOS" && !/^iPad/.test(t.pf || "") && (long > 1e3 || t.dpr && t.dpr < 2)) out.add("mobile_desktop_mismatch");
766
+ }
767
+ return [...out].sort();
768
+ }
769
+ function vmFindings(win, gpu) {
770
+ const out = /* @__PURE__ */ new Set();
771
+ const nav = win.navigator;
772
+ if (gpu && /SwiftShader|llvmpipe|softpipe|Software Rasterizer|Microsoft Basic Render|Mesa OffScreen/i.test(gpu)) out.add("soft_gpu");
773
+ if (gpu && /VMware|VirtualBox|Parallels|QXL|Red Hat|virgl|Hyper-V|Citrix|bochs|UTM|Apple Paravirtual/i.test(gpu)) out.add("vm_gpu");
774
+ if (gpu && /Android Emulator|Emulator OpenGL|Genymotion|BlueStacks|\bNox\b|LDPlayer|MuMu/i.test(gpu)) out.add("emulator");
775
+ try {
776
+ if (/HeadlessChrome|PhantomJS|SlimerJS/.test(nav.userAgent || "")) out.add("headless");
777
+ } catch {
778
+ }
779
+ try {
780
+ if ((nav.userAgentData?.brands || []).some((b) => /Headless/i.test(b.brand))) out.add("headless");
781
+ } catch {
782
+ }
783
+ try {
784
+ if (nav.webdriver === true) out.add("webdriver");
785
+ } catch {
786
+ }
787
+ try {
788
+ if (win.outerWidth === 0 && win.outerHeight === 0) out.add("zero_window");
789
+ } catch {
790
+ }
791
+ try {
792
+ if (nav.hardwareConcurrency === 1) out.add("one_core");
793
+ } catch {
794
+ }
795
+ try {
796
+ const scr = win.screen;
797
+ const desktop = !(nav.maxTouchPoints > 0);
798
+ if (desktop && scr && scr.width === 800 && scr.height === 600 && win.outerHeight === win.innerHeight && win.outerWidth === win.innerWidth) out.add("headless_window");
799
+ } catch {
800
+ }
801
+ return [...out].sort();
802
+ }
803
+ function automationFindings(win) {
804
+ const out = /* @__PURE__ */ new Set();
805
+ const w = win;
806
+ const doc = win.document;
807
+ const has = (o, k) => {
808
+ try {
809
+ return k in o;
810
+ } catch {
811
+ return false;
812
+ }
813
+ };
814
+ try {
815
+ for (const k of Object.getOwnPropertyNames(win)) if (/^cdc_[A-Za-z0-9]{10,}/.test(k) || /^\$?wdc_/.test(k)) out.add("selenium");
816
+ for (const k of Object.keys(win.document)) if (/^\$?cdc_|^\$wdc_/.test(k)) out.add("selenium");
817
+ } catch {
818
+ }
819
+ for (const k of [
820
+ "__selenium_unwrapped",
821
+ "__selenium_evaluate",
822
+ "__webdriver_evaluate",
823
+ "__driver_evaluate",
824
+ "__webdriver_unwrapped",
825
+ "__driver_unwrapped",
826
+ "__fxdriver_evaluate",
827
+ "__fxdriver_unwrapped",
828
+ "__webdriver_script_fn",
829
+ "__webdriver_script_func",
830
+ "_Selenium_IDE_Recorder",
831
+ "callSelenium",
832
+ "_selenium",
833
+ "__webdriverFunc"
834
+ ]) {
835
+ if (has(w, k) || has(doc, k)) out.add("selenium");
836
+ }
837
+ try {
838
+ if (win.document.documentElement?.getAttribute("webdriver") !== null) out.add("selenium");
839
+ } catch {
840
+ }
841
+ for (const k of ["__playwright__binding__", "__pwInitScripts", "__playwright_evaluation_script__", "__playwright"]) if (has(w, k)) out.add("playwright");
842
+ for (const k of ["callPhantom", "_phantom"]) if (has(w, k)) out.add("phantomjs");
843
+ if (has(w, "__nightmare")) out.add("nightmare");
844
+ try {
845
+ if (/HeadlessChrome/.test(win.navigator.userAgent || "")) out.add("headless_chrome");
846
+ } catch {
847
+ }
848
+ try {
849
+ let read = false;
850
+ const probe = new Error("");
851
+ Object.defineProperty(probe, "stack", { configurable: true, get() {
852
+ read = true;
853
+ return "";
854
+ } });
855
+ win.console?.debug?.(probe);
856
+ if (read) out.add("cdp");
857
+ } catch {
858
+ }
859
+ return [...out].sort();
860
+ }
861
+ async function privateWindow(win) {
862
+ const nav = win.navigator;
863
+ const ua = nav.userAgent || "";
864
+ const { br } = browserFamily(ua);
865
+ try {
866
+ if (br === "Firefox" && win.isSecureContext && !("serviceWorker" in nav)) return "firefox_no_sw";
867
+ if (br === "Safari" && nav.storage && typeof nav.storage.getDirectory === "function") {
868
+ try {
869
+ await nav.storage.getDirectory();
870
+ } catch (err) {
871
+ if (String(err?.message || "").includes("unknown transient reason")) return "safari_opfs";
872
+ }
873
+ return null;
874
+ }
875
+ if ((br === "Chrome" || br === "Edge" || br === "Opera" || br === "Samsung") && nav.storage?.estimate) {
876
+ const { quota } = await nav.storage.estimate();
877
+ const heap = win.performance?.memory?.jsHeapSizeLimit || 1073741824;
878
+ if (typeof quota === "number" && quota > 0 && quota < heap * 2) return "chromium_quota";
879
+ }
880
+ } catch {
881
+ }
882
+ return null;
883
+ }
884
+ function storageFindings(win) {
885
+ const out = { ls: false, idb: false, cookie: false };
886
+ try {
887
+ const k = "__tq_dr";
888
+ win.localStorage.setItem(k, "1");
889
+ win.localStorage.removeItem(k);
890
+ out.ls = true;
891
+ } catch {
892
+ }
893
+ try {
894
+ out.idb = typeof win.indexedDB !== "undefined" && !!win.indexedDB;
895
+ } catch {
896
+ }
897
+ try {
898
+ out.cookie = win.navigator.cookieEnabled === true;
899
+ } catch {
900
+ }
901
+ return out;
902
+ }
903
+ function pageOrigin(win) {
904
+ try {
905
+ const o = win.location.origin;
906
+ return o && o !== "null" ? o : "";
907
+ } catch {
908
+ return "";
909
+ }
910
+ }
911
+ async function buildDeviceRiskReport(options, win = window) {
912
+ const started = Date.now();
913
+ const timeoutMs = options.timeoutMs ?? 1500;
914
+ const purpose = DEVICE_RISK_PURPOSES.includes(options.purpose) ? options.purpose : "sign_in";
915
+ const { traits, canvasRaw, gpuRaw, fonts } = await collectTraits(win);
916
+ const [audio, priv] = await Promise.all([
917
+ within2(audioSignature(), timeoutMs, null),
918
+ within2(privateWindow(win), timeoutMs, null)
919
+ ]);
920
+ traits.au = await hex16(audio);
921
+ let cvNoise = false;
922
+ try {
923
+ const again = canvasSignature();
924
+ cvNoise = !!canvasRaw && !!again && again !== canvasRaw;
925
+ } catch {
926
+ }
927
+ const nav = win.navigator;
928
+ const body = {
929
+ v: 1,
930
+ p: purpose,
931
+ aud: pageOrigin(win),
932
+ iat: Math.floor(Date.now() / 1e3),
933
+ nonce: randomNonce(),
934
+ sid: readOrCreateDeviceId(),
935
+ t: traits,
936
+ s: {
937
+ tamper: [.../* @__PURE__ */ new Set([...tamperFindings(win), ...consistencyFindings(win, traits, fonts)])].sort(),
938
+ vm: vmFindings(win, gpuRaw),
939
+ auto: automationFindings(win),
940
+ priv,
941
+ brave: typeof nav.brave === "object" && nav.brave !== null,
942
+ cvNoise,
943
+ storage: storageFindings(win)
944
+ },
945
+ ms: Date.now() - started
946
+ };
947
+ const text = JSON.stringify(body);
948
+ const report = { v: 1, body: text };
949
+ const key = options.browserKey === void 0 ? browserKey : options.browserKey;
950
+ if (key && typeof key.sealDevice === "function") {
951
+ try {
952
+ const digest = await digestHex(text);
953
+ if (!digest.weak) {
954
+ const bytes = new Uint8Array(digest.hex.match(/../g).map((b) => parseInt(b, 16)));
955
+ const seal = await key.sealDevice(base64url2(bytes));
956
+ if (seal) report.seal = seal;
957
+ }
958
+ } catch {
959
+ }
960
+ }
961
+ return report;
962
+ }
963
+ var SITE_KEY = /^tqpk_[A-Za-z0-9_-]{32}$/;
964
+ var DEFAULT_API = "https://api.touchque.com";
965
+ function createDeviceRisk(win) {
966
+ const target = () => win ?? window;
967
+ const api = {
968
+ report: (options) => buildDeviceRiskReport(options, target()),
969
+ async identify(options) {
970
+ if (!options || typeof options.siteKey !== "string" || !SITE_KEY.test(options.siteKey)) {
971
+ throw new Error("deviceRisk.identify: siteKey must be your workspace's Device risk site key (tqpk_\u2026)");
972
+ }
973
+ const base = (options.apiBaseUrl || DEFAULT_API).replace(/\/+$/, "");
974
+ if (!/^https?:\/\/[^/]/i.test(base)) throw new Error("deviceRisk.identify: apiBaseUrl must be an absolute URL, e.g. https://api.touchque.com");
975
+ const doFetch = options.fetch ?? (typeof fetch !== "undefined" ? fetch : void 0);
976
+ if (!doFetch) throw new Error("deviceRisk.identify: no `fetch` available, pass `fetch` in the options.");
977
+ try {
978
+ const report = await api.collect(options);
979
+ const res = await doFetch.call(globalThis, `${base}/device-risk/identify`, {
980
+ method: "POST",
981
+ headers: { "Content-Type": "text/plain" },
982
+ body: JSON.stringify({ siteKey: options.siteKey, report, ...options.pageView && { view: true } }),
983
+ // Only to the page's own origin (a first-party /_tq/ proxy): Touchque's HttpOnly
984
+ // first-party cookie goes there and back. To api.touchque.com it sends no cookie.
985
+ credentials: "same-origin"
986
+ });
987
+ const out = await res.json().catch(() => null);
988
+ if (!res.ok || !out || typeof out.visitorId !== "string" || typeof out.requestId !== "string") {
989
+ logWarn(`Touchque deviceRisk.identify: ${out?.code || res.status}`);
990
+ return null;
991
+ }
992
+ return { visitorId: out.visitorId, requestId: out.requestId, confidence: typeof out.confidence === "number" ? out.confidence : 0 };
993
+ } catch (err) {
994
+ logWarn(`Touchque deviceRisk.identify: Touchque could not be reached (${errorText(err)})`);
995
+ return null;
996
+ }
997
+ },
998
+ async collect(options) {
999
+ try {
1000
+ const report = await buildDeviceRiskReport(options, target());
1001
+ let plain = report;
1002
+ let encoded = encodeJson(plain);
1003
+ if (encoded.length > MAX_ENCODED) {
1004
+ const body = JSON.parse(report.body);
1005
+ body.t.gpu = body.t.gpu ? body.t.gpu.slice(0, 48) : null;
1006
+ plain = { v: 1, body: JSON.stringify(body) };
1007
+ encoded = encodeJson(plain);
1008
+ }
1009
+ if (options.encrypt === false) return encoded;
1010
+ return await sealReport(JSON.stringify(plain)) || encoded;
1011
+ } catch {
1012
+ return encodeJson({ v: 1, body: JSON.stringify({ v: 1, p: options.purpose, error: true }) });
1013
+ }
1014
+ }
1015
+ };
1016
+ return api;
1017
+ }
1018
+ var deviceRisk = createDeviceRisk();
1019
+
1020
+ // src/pointerSummary.ts
1021
+ var JUMP_WINDOW_MS = 500;
1022
+ var JUMP_PX = 30;
1023
+ var STROKE_GAP_MS = 150;
1024
+ var LONG_PX = 300;
1025
+ var LONG_SAMPLES = 10;
1026
+ var TAP_PX = 10;
1027
+ var AXIS = Math.tan(3 * Math.PI / 180);
1028
+ var KEEP = 64;
1029
+ var MAX_SAMPLES = 2e3;
1030
+ function lineFit(samples) {
1031
+ if (samples.length < 2) return { length: 0, deviation: 0, dx: 0, dy: 0 };
1032
+ const a = samples[0];
1033
+ const b = samples[samples.length - 1];
1034
+ const dx = b.x - a.x;
1035
+ const dy = b.y - a.y;
1036
+ const chord = Math.hypot(dx, dy);
1037
+ let length = 0;
1038
+ let deviation = 0;
1039
+ for (let i = 1; i < samples.length; i += 1) {
1040
+ const s = samples[i];
1041
+ length += Math.hypot(s.x - samples[i - 1].x, s.y - samples[i - 1].y);
1042
+ const d = chord > 0 ? Math.abs(dy * (s.x - a.x) - dx * (s.y - a.y)) / chord : Math.hypot(s.x - a.x, s.y - a.y);
1043
+ if (d > deviation) deviation = d;
1044
+ }
1045
+ return { length, deviation, dx, dy };
1046
+ }
1047
+ var nearAxis = (dx, dy) => Math.min(Math.abs(dx), Math.abs(dy)) <= AXIS * Math.max(Math.abs(dx), Math.abs(dy));
1048
+ var round1 = (n) => n === null ? null : Math.round(n * 10) / 10;
1049
+ var smaller = (a, b) => a === null ? b : Math.min(a, b);
1050
+ var larger = (a, b) => a === null ? b : Math.max(a, b);
1051
+ function clockIsCoarse(perf) {
1052
+ try {
1053
+ if (!perf) return true;
1054
+ const a = perf.now();
1055
+ let b = a;
1056
+ for (let i = 0; i < 1e5 && b === a; i += 1) b = perf.now();
1057
+ return b === a || b - a >= 5;
1058
+ } catch {
1059
+ return true;
1060
+ }
1061
+ }
1062
+ function startPointerSummary(root = document, deps = {}) {
1063
+ const doc = root instanceof Document ? root : root.ownerDocument;
1064
+ const trusted = deps.trusted ?? ((e) => e.isTrusted);
1065
+ const perf = doc.defaultView?.performance;
1066
+ const coarse = clockIsCoarse(perf);
1067
+ let mv = 0;
1068
+ let tm = 0;
1069
+ let p = 0;
1070
+ let pt = 0;
1071
+ let ls = 0;
1072
+ let lsd = null;
1073
+ let t = 0;
1074
+ let th = null;
1075
+ let sw = 0;
1076
+ let swd = null;
1077
+ let stroke = [];
1078
+ const moves = [];
1079
+ let lastDown = -Infinity;
1080
+ const jumped = [];
1081
+ let finger = null;
1082
+ const longStroke = (samples) => {
1083
+ if (samples.length < LONG_SAMPLES) return null;
1084
+ const f = lineFit(samples);
1085
+ return f.length >= LONG_PX && !nearAxis(f.dx, f.dy) ? f.deviation : null;
1086
+ };
1087
+ const endStroke = () => {
1088
+ const d = longStroke(stroke);
1089
+ if (d !== null) {
1090
+ ls += 1;
1091
+ lsd = smaller(lsd, d);
1092
+ }
1093
+ stroke = [];
1094
+ };
1095
+ const isPointer = (e) => trusted(e) && (e.pointerType === "mouse" || e.pointerType === "pen");
1096
+ const onMove = (e) => {
1097
+ if (!isPointer(e)) return;
1098
+ const coalesced = typeof e.getCoalescedEvents === "function" ? e.getCoalescedEvents() : [];
1099
+ for (const c of coalesced.length ? coalesced : [e]) {
1100
+ const s = { x: c.clientX, y: c.clientY, t: c.timeStamp };
1101
+ const last = stroke[stroke.length - 1];
1102
+ if (last && s.t - last.t > STROKE_GAP_MS || stroke.length >= MAX_SAMPLES) endStroke();
1103
+ stroke.push(s);
1104
+ moves.push(s);
1105
+ if (moves.length > KEEP) moves.shift();
1106
+ mv += 1;
1107
+ }
1108
+ };
1109
+ const onDown = (e) => {
1110
+ if (!isPointer(e) || e.button !== 0) return;
1111
+ endStroke();
1112
+ p += 1;
1113
+ const at = e.timeStamp;
1114
+ const from = Math.max(at - JUMP_WINDOW_MS, lastDown);
1115
+ const recent = moves.filter((m) => m.t > from);
1116
+ let before = null;
1117
+ for (let i = moves.length - 1; i >= 0; i -= 1) if (moves[i].t <= from) {
1118
+ before = moves[i];
1119
+ break;
1120
+ }
1121
+ lastDown = at;
1122
+ moves.push({ x: e.clientX, y: e.clientY, t: at });
1123
+ if (moves.length > KEEP) moves.shift();
1124
+ if (recent.length <= 1 && (!before || Math.hypot(e.clientX - before.x, e.clientY - before.y) >= JUMP_PX)) {
1125
+ pt += 1;
1126
+ jumped.push({ id: e.pointerId, down: at, up: null });
1127
+ if (jumped.length > KEEP) jumped.shift();
1128
+ }
1129
+ };
1130
+ const onUp = (e) => {
1131
+ if (!isPointer(e)) return;
1132
+ for (let i = jumped.length - 1; i >= 0; i -= 1) {
1133
+ if (jumped[i].id === e.pointerId && jumped[i].up === null) {
1134
+ jumped[i].up = e.timeStamp;
1135
+ break;
1136
+ }
1137
+ }
1138
+ };
1139
+ const onTouchStart = (e) => {
1140
+ if (!trusted(e)) return;
1141
+ const c = e.changedTouches[0];
1142
+ finger = e.touches.length === 1 && c ? { id: c.identifier, start: e.timeStamp, samples: [{ x: c.clientX, y: c.clientY, t: e.timeStamp }], far: 0 } : null;
1143
+ };
1144
+ const track = (e) => {
1145
+ if (!finger) return null;
1146
+ const c = Array.from(e.changedTouches).find((x) => x.identifier === finger.id);
1147
+ if (!c) return null;
1148
+ const first = finger.samples[0];
1149
+ if (finger.samples.length < MAX_SAMPLES) finger.samples.push({ x: c.clientX, y: c.clientY, t: e.timeStamp });
1150
+ finger.far = Math.max(finger.far, Math.hypot(c.clientX - first.x, c.clientY - first.y));
1151
+ return finger;
1152
+ };
1153
+ const onTouchMove = (e) => {
1154
+ if (!trusted(e)) return;
1155
+ tm += 1;
1156
+ track(e);
1157
+ };
1158
+ const onTouchEnd = (e) => {
1159
+ if (!trusted(e)) return;
1160
+ const done = track(e);
1161
+ if (!done) return;
1162
+ finger = null;
1163
+ if (done.far < TAP_PX) {
1164
+ t += 1;
1165
+ th = larger(th, e.timeStamp - done.start);
1166
+ return;
1167
+ }
1168
+ if (done.samples.length >= LONG_SAMPLES) {
1169
+ const f = lineFit(done.samples);
1170
+ if (f.length >= LONG_PX) {
1171
+ sw += 1;
1172
+ swd = smaller(swd, f.deviation);
1173
+ }
1174
+ }
1175
+ };
1176
+ const onTouchCancel = () => {
1177
+ finger = null;
1178
+ };
1179
+ const opts = { capture: true, passive: true };
1180
+ const listeners = [
1181
+ ["pointermove", onMove],
1182
+ ["pointerdown", onDown],
1183
+ ["pointerup", onUp],
1184
+ ["touchstart", onTouchStart],
1185
+ ["touchmove", onTouchMove],
1186
+ ["touchend", onTouchEnd],
1187
+ ["touchcancel", onTouchCancel]
1188
+ ];
1189
+ for (const [type, fn] of listeners) root.addEventListener(type, fn, opts);
1190
+ const summary = () => {
1191
+ const now = perf ? perf.now() : 0;
1192
+ let pth = null;
1193
+ for (const j of jumped) pth = larger(pth, (j.up ?? now) - j.down);
1194
+ const current2 = longStroke(stroke);
1195
+ return {
1196
+ v: 1,
1197
+ p,
1198
+ pt,
1199
+ pth: coarse ? null : round1(pth),
1200
+ ls: ls + (current2 === null ? 0 : 1),
1201
+ lsd: round1(current2 === null ? lsd : smaller(lsd, current2)),
1202
+ t,
1203
+ th: coarse ? null : round1(th),
1204
+ sw,
1205
+ swd: round1(swd),
1206
+ mv,
1207
+ tm
1208
+ };
1209
+ };
1210
+ return {
1211
+ summary,
1212
+ encode: () => encodePointerSummary(summary()),
1213
+ stop() {
1214
+ for (const [type, fn] of listeners) root.removeEventListener(type, fn, opts);
1215
+ }
1216
+ };
1217
+ }
1218
+ var DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1219
+ var NONE = 4095;
1220
+ var one = (n) => DIGITS[Math.max(0, Math.min(63, Math.floor(n)))];
1221
+ var two = (n) => {
1222
+ const v = n === null ? NONE : Math.max(0, Math.min(NONE - 1, Math.round(n)));
1223
+ return DIGITS[v >> 6] + DIGITS[v & 63];
1224
+ };
1225
+ function encodePointerSummary(s) {
1226
+ const pt = s.pt >= s.p ? one(s.p) : one(Math.min(s.pt, 62));
1227
+ return `1${one(s.p)}${pt}${two(s.pth)}${one(s.ls)}${two(s.lsd === null ? null : s.lsd * 10)}${one(s.t)}${two(s.th)}${one(s.sw)}${two(s.swd === null ? null : s.swd * 10)}${two(s.mv)}${two(s.tm)}`;
1228
+ }
1229
+
1230
+ // src/inputSummary.ts
1231
+ var BURST_GAP_MS = 1500;
1232
+ var LONG_GAP_MS = 1500;
1233
+ var LONG_GAP_MAX_MS = 2e4;
1234
+ var KEY_NEAR_MS = 150;
1235
+ var CENTER_PX = 1;
1236
+ var MIN_TARGET_PX = 8;
1237
+ var KEEP2 = 200;
1238
+ function clockIsCoarse2(perf) {
1239
+ try {
1240
+ if (!perf) return true;
1241
+ const a = perf.now();
1242
+ let b = a;
1243
+ for (let i = 0; i < 1e5 && b === a; i += 1) b = perf.now();
1244
+ return b === a || b - a >= 5;
1245
+ } catch {
1246
+ return true;
1247
+ }
1248
+ }
1249
+ var mean = (xs) => xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : null;
1250
+ function stddev(xs) {
1251
+ const m = mean(xs);
1252
+ if (m === null) return null;
1253
+ return Math.sqrt(xs.reduce((s, x) => s + (x - m) ** 2, 0) / xs.length);
1254
+ }
1255
+ function median(xs) {
1256
+ if (!xs.length) return null;
1257
+ const s = [...xs].sort((a, b) => a - b);
1258
+ const mid = s.length >> 1;
1259
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
1260
+ }
1261
+ function startInputSummary(root = document, deps = {}) {
1262
+ const doc = root instanceof Document ? root : root.ownerDocument;
1263
+ const trusted = deps.trusted ?? ((e) => e.isTrusted);
1264
+ const perf = doc.defaultView?.performance;
1265
+ const coarse = clockIsCoarse2(perf);
1266
+ let kd = 0;
1267
+ let nk = 0;
1268
+ let pa = 0;
1269
+ let cp = 0;
1270
+ let cc = 0;
1271
+ let lastKey = -Infinity;
1272
+ let lastAction = -Infinity;
1273
+ const intervals = [];
1274
+ const holds = [];
1275
+ const down = /* @__PURE__ */ new Map();
1276
+ const actions = [];
1277
+ const action = (at) => {
1278
+ actions.push(at);
1279
+ if (actions.length > KEEP2) actions.shift();
1280
+ lastAction = at;
1281
+ };
1282
+ const onKeyDown = (e) => {
1283
+ if (!trusted(e) || e.repeat || typeof e.key !== "string" || e.key.length !== 1) return;
1284
+ const at = e.timeStamp;
1285
+ kd += 1;
1286
+ if (at - lastKey < BURST_GAP_MS) {
1287
+ intervals.push(at - lastKey);
1288
+ if (intervals.length > KEEP2) intervals.shift();
1289
+ } else if (at - lastAction >= BURST_GAP_MS || lastAction === -Infinity) {
1290
+ action(at);
1291
+ }
1292
+ lastKey = at;
1293
+ down.set(e.code || e.key, at);
1294
+ };
1295
+ const onKeyUp = (e) => {
1296
+ if (!trusted(e)) return;
1297
+ const k = e.code || e.key;
1298
+ const at = down.get(k);
1299
+ if (at === void 0) return;
1300
+ down.delete(k);
1301
+ holds.push(e.timeStamp - at);
1302
+ if (holds.length > KEEP2) holds.shift();
1303
+ };
1304
+ const onInput = (e) => {
1305
+ if (!trusted(e)) return;
1306
+ const ie = e;
1307
+ const type = typeof ie.inputType === "string" ? ie.inputType : "";
1308
+ if (type === "insertFromPaste" || type === "insertFromDrop") {
1309
+ pa += 1;
1310
+ return;
1311
+ }
1312
+ if (type !== "insertText" || ie.isComposing) return;
1313
+ const at = e.timeStamp;
1314
+ if (at - lastKey > KEY_NEAR_MS) {
1315
+ nk += 1;
1316
+ if (at - lastAction >= BURST_GAP_MS) action(at);
1317
+ }
1318
+ };
1319
+ const onPaste = (e) => {
1320
+ if (trusted(e) && !(e.target instanceof Element && e.target.closest("input,textarea,[contenteditable]"))) pa += 1;
1321
+ };
1322
+ const onDown = (e) => {
1323
+ if (!trusted(e) || e.button !== 0) return;
1324
+ action(e.timeStamp);
1325
+ if (e.pointerType !== "mouse" && e.pointerType !== "pen") return;
1326
+ const el = e.target instanceof Element ? e.target : null;
1327
+ if (!el) return;
1328
+ try {
1329
+ const r = el.getBoundingClientRect();
1330
+ if (r.width < MIN_TARGET_PX || r.height < MIN_TARGET_PX) return;
1331
+ cp += 1;
1332
+ if (Math.abs(e.clientX - (r.left + r.width / 2)) <= CENTER_PX && Math.abs(e.clientY - (r.top + r.height / 2)) <= CENTER_PX) cc += 1;
1333
+ } catch {
1334
+ }
1335
+ };
1336
+ const opts = { capture: true, passive: true };
1337
+ const listeners = [
1338
+ ["keydown", onKeyDown],
1339
+ ["keyup", onKeyUp],
1340
+ ["input", onInput],
1341
+ ["paste", onPaste],
1342
+ ["pointerdown", onDown]
1343
+ ];
1344
+ for (const [type, fn] of listeners) root.addEventListener(type, fn, opts);
1345
+ const summary = () => {
1346
+ const gaps = [];
1347
+ for (let i = 1; i < actions.length; i += 1) gaps.push(actions[i] - actions[i - 1]);
1348
+ const lg = gaps.filter((g) => g >= LONG_GAP_MS && g <= LONG_GAP_MAX_MS).length;
1349
+ const r = (n) => n === null ? null : Math.round(n);
1350
+ return {
1351
+ v: 1,
1352
+ kd,
1353
+ nk,
1354
+ pa,
1355
+ kn: intervals.length,
1356
+ km: coarse ? null : r(mean(intervals)),
1357
+ ks: coarse ? null : r(stddev(intervals)),
1358
+ hm: coarse ? null : r(mean(holds)),
1359
+ cp,
1360
+ cc,
1361
+ ac: actions.length,
1362
+ lg,
1363
+ gm: coarse ? null : r(median(gaps))
1364
+ };
1365
+ };
1366
+ return {
1367
+ summary,
1368
+ encode: () => encodeInputSummary(summary()),
1369
+ stop() {
1370
+ for (const [type, fn] of listeners) root.removeEventListener(type, fn, opts);
1371
+ }
1372
+ };
1373
+ }
1374
+ var DIGITS2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1375
+ var NONE2 = 4095;
1376
+ var one2 = (n) => DIGITS2[Math.max(0, Math.min(63, Math.floor(n)))];
1377
+ var two2 = (n) => {
1378
+ const v = n === null ? NONE2 : Math.max(0, Math.min(NONE2 - 1, Math.round(n)));
1379
+ return DIGITS2[v >> 6] + DIGITS2[v & 63];
1380
+ };
1381
+ function encodeInputSummary(s) {
1382
+ const cp = Math.min(s.cp, 63);
1383
+ const ac = Math.min(s.ac, 63);
1384
+ return `1${one2(s.kd)}${one2(s.nk)}${one2(s.pa)}${one2(s.kn)}${two2(s.km)}${two2(s.ks)}${two2(s.hm)}${one2(cp)}${one2(Math.min(s.cc, cp))}${one2(ac)}${one2(Math.min(s.lg, ac))}${two2(s.gm === null ? null : s.gm / 100)}`;
1385
+ }
1386
+
1387
+ // src/deviceRiskTag.ts
1388
+ var REQUEST_ID_FIELD = "touchque_request_id";
1389
+ var FORM_PURPOSE_ATTRIBUTE = "data-touchque-purpose";
1390
+ var DEVICE_EVENT = "touchque:device";
1391
+ var REFRESH_AFTER_MS = 10 * 60 * 1e3;
1392
+ var AFTER_SUBMIT_MS = 1e3;
1393
+ var DEVICE_TAG_VERSION = "3.0.0";
1394
+ var isPurpose = (v) => DEVICE_RISK_PURPOSES.includes(v);
1395
+ function installDeviceRiskTag(options, deps = {}) {
1396
+ const win = deps.win ?? window;
1397
+ const doc = win.document;
1398
+ const now = deps.now ?? (() => Date.now());
1399
+ const risk = deps.deviceRisk ?? createDeviceRisk(win);
1400
+ const pagePurpose = isPurpose(options.purpose) ? options.purpose : "sign_in";
1401
+ const slots = /* @__PURE__ */ new Map();
1402
+ const roots = /* @__PURE__ */ new Set([doc]);
1403
+ let stopped = false;
1404
+ let pointer = null;
1405
+ try {
1406
+ pointer = deps.pointer !== void 0 ? deps.pointer : options.pointer === false ? null : startPointerSummary(doc);
1407
+ } catch {
1408
+ }
1409
+ let input = null;
1410
+ try {
1411
+ input = !pointer ? null : deps.input !== void 0 ? deps.input : startInputSummary(doc);
1412
+ } catch {
1413
+ }
1414
+ const valueOf = (purpose) => {
1415
+ const id = slots.get(purpose)?.current?.requestId;
1416
+ if (!id) return null;
1417
+ let out = id;
1418
+ try {
1419
+ if (pointer) out = `${id}.${pointer.encode()}`;
1420
+ } catch {
1421
+ return id;
1422
+ }
1423
+ try {
1424
+ if (pointer && input) out = `${out}.${input.encode()}`;
1425
+ } catch {
1426
+ }
1427
+ return out;
1428
+ };
1429
+ const slot = (purpose) => {
1430
+ let s = slots.get(purpose);
1431
+ if (!s) {
1432
+ s = { current: null, at: 0, pending: null, timer: null, stale: false };
1433
+ slots.set(purpose, s);
1434
+ }
1435
+ return s;
1436
+ };
1437
+ const purposeOf = (form) => {
1438
+ const own = form.getAttribute(FORM_PURPOSE_ATTRIBUTE);
1439
+ return isPurpose(own) ? own : pagePurpose;
1440
+ };
1441
+ const formsIn = (root) => {
1442
+ const out = [];
1443
+ if (root.tagName === "FORM") out.push(root);
1444
+ if (typeof root.querySelectorAll === "function") out.push(...Array.from(root.querySelectorAll("form")));
1445
+ return out;
1446
+ };
1447
+ const fieldOf = (form) => {
1448
+ const existing = Array.from(form.querySelectorAll("input")).find((i) => i.name === REQUEST_ID_FIELD);
1449
+ if (existing) return existing;
1450
+ const input2 = doc.createElement("input");
1451
+ input2.type = "hidden";
1452
+ input2.name = REQUEST_ID_FIELD;
1453
+ form.appendChild(input2);
1454
+ return input2;
1455
+ };
1456
+ const fill = (purpose) => {
1457
+ const value = slots.get(purpose)?.current?.requestId ?? "";
1458
+ for (const root of roots) for (const form of formsIn(root)) if (purposeOf(form) === purpose) fieldOf(form).value = value;
1459
+ };
1460
+ const schedule = (purpose) => {
1461
+ const s = slot(purpose);
1462
+ if (s.timer) clearTimeout(s.timer);
1463
+ s.stale = false;
1464
+ s.timer = setTimeout(() => {
1465
+ s.timer = null;
1466
+ if (doc.visibilityState === "hidden") s.stale = true;
1467
+ else void identifyFor(purpose);
1468
+ }, REFRESH_AFTER_MS);
1469
+ };
1470
+ const identifyFor = (purpose) => {
1471
+ const s = slot(purpose);
1472
+ if (s.pending) return s.pending;
1473
+ if (stopped) return Promise.resolve(s.current);
1474
+ s.pending = risk.identify({ siteKey: options.siteKey, purpose, apiBaseUrl: options.apiBaseUrl, pageView: true }).catch((err) => {
1475
+ logWarn(`Touchque device.js: ${errorText(err)}`);
1476
+ return null;
1477
+ }).then((id) => {
1478
+ s.pending = null;
1479
+ if (stopped) return id;
1480
+ s.current = id;
1481
+ s.at = now();
1482
+ fill(purpose);
1483
+ if (id) schedule(purpose);
1484
+ try {
1485
+ doc.dispatchEvent(new CustomEvent(DEVICE_EVENT, { detail: { purpose, requestId: id?.requestId ?? null, visitorId: id?.visitorId ?? null, confidence: id?.confidence ?? null } }));
1486
+ } catch {
1487
+ }
1488
+ return id;
1489
+ });
1490
+ return s.pending;
1491
+ };
1492
+ const scan = (root) => {
1493
+ for (const form of formsIn(root)) {
1494
+ const purpose = purposeOf(form);
1495
+ const field = fieldOf(form);
1496
+ const s = slots.get(purpose);
1497
+ if (s?.current) field.value = s.current.requestId;
1498
+ else void identifyFor(purpose);
1499
+ }
1500
+ };
1501
+ const freshen = () => {
1502
+ for (const [purpose, s] of slots) {
1503
+ if (s.stale || s.at && now() - s.at >= REFRESH_AFTER_MS) void identifyFor(purpose);
1504
+ }
1505
+ };
1506
+ const onVisible = () => {
1507
+ if (doc.visibilityState !== "hidden") freshen();
1508
+ };
1509
+ const onSubmit = (e) => {
1510
+ const form = e.target;
1511
+ if (!form || form.tagName !== "FORM") return;
1512
+ const purpose = purposeOf(form);
1513
+ const value = valueOf(purpose);
1514
+ if (value) fieldOf(form).value = value;
1515
+ setTimeout(() => {
1516
+ if (!stopped) void identifyFor(purpose);
1517
+ }, AFTER_SUBMIT_MS);
1518
+ };
1519
+ const Observer = win.MutationObserver;
1520
+ const observer = typeof Observer === "function" ? new Observer((records) => {
1521
+ for (const r of records) for (const node of Array.from(r.addedNodes)) if (node.nodeType === 1) scan(node);
1522
+ }) : null;
1523
+ const ready = identifyFor(pagePurpose);
1524
+ try {
1525
+ observer?.observe(doc.documentElement, { childList: true, subtree: true });
1526
+ doc.addEventListener("submit", onSubmit, true);
1527
+ doc.addEventListener("visibilitychange", onVisible);
1528
+ doc.addEventListener("focusin", freshen);
1529
+ scan(doc);
1530
+ if (doc.readyState === "loading") doc.addEventListener("DOMContentLoaded", () => scan(doc), { once: true });
1531
+ } catch {
1532
+ }
1533
+ return {
1534
+ ready,
1535
+ get requestId() {
1536
+ return slots.get(pagePurpose)?.current?.requestId ?? null;
1537
+ },
1538
+ get visitorId() {
1539
+ return slots.get(pagePurpose)?.current?.visitorId ?? null;
1540
+ },
1541
+ value: (purpose) => valueOf(isPurpose(purpose) ? purpose : pagePurpose),
1542
+ refresh: (purpose) => identifyFor(isPurpose(purpose) ? purpose : pagePurpose),
1543
+ attach(root) {
1544
+ roots.add(root);
1545
+ scan(root);
1546
+ },
1547
+ stop() {
1548
+ stopped = true;
1549
+ observer?.disconnect();
1550
+ doc.removeEventListener("submit", onSubmit, true);
1551
+ doc.removeEventListener("visibilitychange", onVisible);
1552
+ doc.removeEventListener("focusin", freshen);
1553
+ for (const s of slots.values()) if (s.timer) clearTimeout(s.timer);
1554
+ pointer?.stop();
1555
+ input?.stop();
1556
+ },
1557
+ version: DEVICE_TAG_VERSION
1558
+ };
1559
+ }
1560
+
1561
+ exports.DEVICE_EVENT = DEVICE_EVENT;
1562
+ exports.DEVICE_RISK_FIELD = DEVICE_RISK_FIELD;
1563
+ exports.DEVICE_RISK_HEADER = DEVICE_RISK_HEADER;
1564
+ exports.DEVICE_RISK_PURPOSES = DEVICE_RISK_PURPOSES;
1565
+ exports.DEVICE_TAG_VERSION = DEVICE_TAG_VERSION;
1566
+ exports.FORM_PURPOSE_ATTRIBUTE = FORM_PURPOSE_ATTRIBUTE;
1567
+ exports.REPORT_KEY = REPORT_KEY;
1568
+ exports.REQUEST_ID_FIELD = REQUEST_ID_FIELD;
1569
+ exports.buildDeviceRiskReport = buildDeviceRiskReport;
1570
+ exports.consistencyFindings = consistencyFindings;
1571
+ exports.createDeviceRisk = createDeviceRisk;
1572
+ exports.deviceRisk = deviceRisk;
1573
+ exports.encodeInputSummary = encodeInputSummary;
1574
+ exports.encodePointerSummary = encodePointerSummary;
1575
+ exports.installDeviceRiskTag = installDeviceRiskTag;
1576
+ exports.jsEngine = jsEngine;
1577
+ exports.sealReport = sealReport;
1578
+ exports.setTouchqueLogger = setTouchqueLogger;
1579
+ exports.startInputSummary = startInputSummary;
1580
+ exports.startPointerSummary = startPointerSummary;