@anonympins/fingerprint 0.6.6 → 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,1448 +1,1464 @@
1
- import {cyrb53 as jsCyrb53, FingerprintBuilder} from './fingerprint.builder.js';
2
- import {solveChallenge} from './pow.solver.js';
3
-
4
- function secureRandom() {
5
- if (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) {
6
- const array = new Uint32Array(1);
7
- (window.crypto || window.msCrypto).getRandomValues(array);
8
- return array[0] / 0x100000000;
9
- }
10
- return Math.random();
11
- }
12
-
13
- // Variable pour stocker la fonction de hachage active.
14
- // Par défaut, c'est l'implémentation JavaScript.
15
- let activeCyrb53 = jsCyrb53;
16
- let derivedKey = null;
17
-
18
- async function negotiateSessionKey() {
19
- if (typeof window === 'undefined' || !window.crypto || !window.crypto.subtle) return;
20
- try {
21
- const keyPair = await window.crypto.subtle.generateKey(
22
- { name: "ECDH", namedCurve: "P-256" },
23
- false,
24
- ["deriveKey"]
25
- );
26
- const clientPubKeyBuffer = await window.crypto.subtle.exportKey("raw", keyPair.publicKey);
27
- const clientPubKeyHex = Array.from(new Uint8Array(clientPubKeyBuffer))
28
- .map(b => b.toString(16).padStart(2, '0'))
29
- .join('');
30
-
31
- const response = await fetch(window.location.pathname + '?fp_handshake=1', {
32
- method: 'POST',
33
- headers: {
34
- 'Content-Type': 'application/json',
35
- 'x-client-ephemeral-key': clientPubKeyHex
36
- },
37
- body: JSON.stringify({ fp: ClientLibrary.getDeviceFingerprint() })
38
- });
39
-
40
- const serverPubKeyHex = response.headers.get('x-server-ephemeral-key');
41
- if (serverPubKeyHex) {
42
- const serverPubKeyBuffer = new Uint8Array(
43
- serverPubKeyHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))
44
- );
45
- const serverPubKey = await window.crypto.subtle.importKey(
46
- "raw",
47
- serverPubKeyBuffer,
48
- { name: "ECDH", namedCurve: "P-256" },
49
- true,
50
- []
51
- );
52
- derivedKey = await window.crypto.subtle.deriveKey(
53
- { name: "ECDH", public: serverPubKey },
54
- keyPair.privateKey,
55
- { name: "HMAC", hash: "SHA-256", length: 256 },
56
- true,
57
- ["sign"]
58
- );
59
- console.log('[Fingerprint] Cryptographic session negotiated successfully.');
60
- }
61
- } catch (e) {
62
- console.warn('[Fingerprint] Cryptographic session negotiation failed:', e);
63
- }
64
- }
65
-
66
- async function signMetrics(metricsObj) {
67
- if (!derivedKey) return metricsObj;
68
- try {
69
- const copy = JSON.parse(JSON.stringify(metricsObj));
70
- delete copy.signature;
71
- const dataToSign = new TextEncoder().encode(JSON.stringify(copy));
72
- const signatureBuffer = await window.crypto.subtle.sign(
73
- "HMAC",
74
- derivedKey,
75
- dataToSign
76
- );
77
- copy.signature = Array.from(new Uint8Array(signatureBuffer))
78
- .map(b => b.toString(16).padStart(2, '0'))
79
- .join('');
80
- return copy;
81
- } catch (e) {
82
- return metricsObj;
83
- }
84
- }
85
-
86
- const DB_NAME = 'wasm-cache-db';
87
- const DB_VERSION = 1;
88
- const STORE_NAME = 'wasm-modules';
89
-
90
- const genRandStr = (len = 8) => {
91
- return Array.from({ length: len }, () => String.fromCharCode(97 + Math.floor(secureRandom() * 26))).join('');
92
- };
93
-
94
- function getCachedWasm(url) {
95
- return new Promise((resolve) => {
96
- if (typeof indexedDB === 'undefined') return resolve(null);
97
- const request = indexedDB.open(DB_NAME, DB_VERSION);
98
- request.onupgradeneeded = (e) => {
99
- const db = e.target.result;
100
- if (!db.objectStoreNames.contains(STORE_NAME)) {
101
- db.createObjectStore(STORE_NAME);
102
- }
103
- };
104
- request.onsuccess = (e) => {
105
- const db = e.target.result;
106
- try {
107
- const transaction = db.transaction(STORE_NAME, 'readonly');
108
- const store = transaction.objectStore(STORE_NAME);
109
- const getReq = store.get(url);
110
- getReq.onsuccess = () => resolve(getReq.result);
111
- getReq.onerror = () => resolve(null);
112
- } catch (err) {
113
- resolve(null);
114
- }
115
- };
116
- request.onerror = () => resolve(null);
117
- });
118
- }
119
-
120
- function cacheWasm(url, data) {
121
- return new Promise((resolve) => {
122
- if (typeof indexedDB === 'undefined') return resolve(false);
123
- const request = indexedDB.open(DB_NAME, DB_VERSION);
124
- request.onupgradeneeded = (e) => {
125
- const db = e.target.result;
126
- if (!db.objectStoreNames.contains(STORE_NAME)) {
127
- db.createObjectStore(STORE_NAME);
128
- }
129
- };
130
- request.onsuccess = (e) => {
131
- const db = e.target.result;
132
- try {
133
- const transaction = db.transaction(STORE_NAME, 'readwrite');
134
- const store = transaction.objectStore(STORE_NAME);
135
- store.put(data, url);
136
- transaction.oncomplete = () => resolve(true);
137
- transaction.onerror = () => resolve(false);
138
- } catch (err) {
139
- resolve(false);
140
- }
141
- };
142
- request.onerror = () => resolve(false);
143
- });
144
- }
145
-
146
- const ClientLibrary = {
147
- // Cache pour éviter de recalculer les constantes (Hardware, etc.)
148
- _cachedBuilder: null,
149
- /**
150
- * @private
151
- * Dispatches a custom event from the window object.
152
- * @param {string} eventName - The name of the event.
153
- * @param {object} [detail={}] - The data to include in the event's detail property.
154
- */
155
- _dispatchEvent(eventName, detail = {}) {
156
- if (typeof window === 'undefined' || typeof CustomEvent === 'undefined') return;
157
- const event = new CustomEvent(`fingerprint:${eventName}`, { detail });
158
- window.dispatchEvent(event);
159
- },
160
-
161
- /**
162
- * Wrapper interne pour la fonction de hachage.
163
- * @private
164
- */
165
- _hasher: (str, seed) => activeCyrb53(str, seed),
166
-
167
- /**
168
- * Génère une preuve de connaissance à divulgation nulle (ZKP) de Schnorr pour l'empreinte de l'appareil.
169
- * Rend le tout stable et compatible avec les vérifications JS, PHP et Python.
170
- * @param {string} fingerprint - L'empreinte de l'appareil.
171
- * @returns {Promise<string>} La preuve sous format "y:t:s" en hexadécimal.
172
- */
173
- async generateZkpProof(fingerprint) {
174
- const ZKP_P = 115792089237316195423570985008687907853269984665640564039457584007908834671663n;
175
- const ZKP_G = 2n;
176
- const cryptoObj = window.crypto || window.msCrypto;
177
-
178
- const sha256Hex = async (str) => {
179
- const encoder = new TextEncoder();
180
- const data = encoder.encode(str);
181
- const hashBuffer = await cryptoObj.subtle.digest('SHA-256', data);
182
- const hashArray = Array.from(new Uint8Array(hashBuffer));
183
- return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
184
- };
185
-
186
- const modPow = (base, exponent, modulus) => {
187
- if (modulus === 1n) return 0n;
188
- let result = 1n;
189
- base = base % modulus;
190
- while (exponent > 0n) {
191
- if (exponent % 2n === 1n) {
192
- result = (result * base) % modulus;
193
- }
194
- exponent = exponent >> 1n;
195
- base = (base * base) % modulus;
196
- }
197
- return result;
198
- };
199
-
200
- const xHex = await sha256Hex(fingerprint);
201
- const x = BigInt('0x' + xHex) % ZKP_P;
202
- const y = modPow(ZKP_G, x, ZKP_P);
203
- const randomBytes = new Uint8Array(32);
204
- cryptoObj.getRandomValues(randomBytes);
205
- let vHex = Array.from(randomBytes).map(b => b.toString(16).padStart(2, '0')).join('');
206
- let v = BigInt('0x' + vHex) % (ZKP_P - 1n);
207
- if (v === 0n) v = 1n;
208
- const t = modPow(ZKP_G, v, ZKP_P);
209
- const cStr = ZKP_G.toString() + y.toString() + t.toString();
210
- const cHex = await sha256Hex(cStr);
211
- const c = BigInt('0x' + cHex) % ZKP_P;
212
- const s = (v + c * x) % (ZKP_P - 1n);
213
-
214
- return `${y.toString(16)}:${t.toString(16)}:${s.toString(16)}`;
215
- },
216
-
217
- /**
218
- * Génère l'empreinte de l'appareil actuel.
219
- */
220
- getDeviceFingerprint() {
221
- if (typeof window === "undefined") {
222
- console.error("getDeviceFingerprint can only be called on the client-side.");
223
- return "";
224
- }
225
-
226
- if (!this._cachedBuilder) {
227
- const nav = window.navigator;
228
- const screen = window.screen;
229
-
230
- this._cachedBuilder = new FingerprintBuilder();
231
-
232
- // 1. Hardware (Très stable) : Cœurs, RAM, GPU (si dispo via canvas), Touch
233
- this._cachedBuilder.add(
234
- "hw", // Utilise maintenant le hasher actif
235
- `${nav.hardwareConcurrency}_${nav.deviceMemory}_${nav.maxTouchPoints}`,
236
- );
237
-
238
- // 2. Geo/Locale (Stable sauf voyage/VPN) : Timezone, Langue
239
- this._cachedBuilder.add(
240
- "geo",
241
- `${Intl.DateTimeFormat().resolvedOptions().timeZone}_${nav.language}_${new Date().getTimezoneOffset()}`,
242
- );
243
-
244
- // 3. Screen (Stable sauf changement moniteur/zoom) : Dimensions, ColorDepth
245
- this._cachedBuilder.add(
246
- "scr",
247
- `${screen.width}x${screen.height}_${screen.colorDepth}`,
248
- );
249
-
250
- // 4. Platform (Stable) : OS, Engine
251
- this._cachedBuilder.add("os", nav.platform);
252
-
253
- // 5. Graphics (WebGL Vendor/Renderer) - Invariant matériel fort
254
- try {
255
- const canvas = document.createElement("canvas");
256
- const gl =
257
- canvas.getContext("webgl2") ||
258
- canvas.getContext("webgl") ||
259
- canvas.getContext("experimental-webgl");
260
- if (gl) {
261
- const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
262
- if (debugInfo) {
263
- const vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
264
- const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
265
- this._cachedBuilder.add("gpu", `${vendor}_${renderer}`);
266
- }
267
- }
268
- } catch (e) {
269
- }
270
-
271
- // 6. Canvas Fingerprinting (Rendering quirks)
272
- try {
273
- const canvas = document.createElement("canvas");
274
- const ctx = canvas.getContext("2d");
275
- if (ctx) {
276
- canvas.width = 200;
277
- canvas.height = 50;
278
- ctx.textBaseline = "alphabetic";
279
- ctx.font = "14px 'Arial'";
280
- ctx.fillStyle = "#f60";
281
- ctx.fillRect(125, 1, 62, 20);
282
- ctx.fillStyle = "#069";
283
- ctx.fillText("fingerprint", 2, 15);
284
- ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
285
- ctx.fillText("fingerprint", 4, 17);
286
- this._cachedBuilder.add("cvs", canvas.toDataURL());
287
- }
288
- } catch (e) {
289
- }
290
-
291
- // 7. Détection des artefacts du Chrome DevTools Protocol (CDP)
292
- // Ces variables sont souvent injectées par les outils d'automatisation.
293
- const cdpFootprints = [
294
- 'cdc_adoQpoasnfa76pfcZLmcfl_Array',
295
- 'cdc_adoQpoasnfa76pfcZLmcfl_Promise',
296
- 'cdc_adoQpoasnfa76pfcZLmcfl_Symbol',
297
- '$cdc_asdjflasutopfhvcZLmcfl_',
298
- '_selenium',
299
- '_driver'
300
- ];
301
- if (cdpFootprints.some(fp => window[fp])) {
302
- this._cachedBuilder.add("cdp", "true");
303
- }
304
-
305
- // 7. Bot Detection (Indication cachée)
306
- if (nav.webdriver) this._cachedBuilder.add("bot", "true");
307
- }
308
-
309
- return this._cachedBuilder.toString();
310
- },
311
-
312
- /**
313
- * Génère une signature de requête incluant le contexte.
314
- * @param {object} payload
315
- */
316
- /**
317
- * Génère une signature de requête incluant le contexte.
318
- * @param {object} payload
319
- */
320
- generateRequestSignature(payload = {}) {
321
- const deviceFp = this.getDeviceFingerprint();
322
- const sortedPayload = Object.keys(payload)
323
- .sort()
324
- .map((k) => `${k}=${payload[k]}`)
325
- .join("&");
326
- const payloadHash = this._hasher(sortedPayload);
327
- return `${deviceFp}|req:${payloadHash}`;
328
- },
329
-
330
- /**
331
- * Génère une signature HMAC-SHA256 en utilisant l'API Web Crypto.
332
- * @param {object} payload - Les données à signer.
333
- * @param {string} secret - La clé secrète partagée.
334
- * @returns {Promise<string>} La signature hexadécimale.
335
- */
336
- async generateClientSideSignature(payload, secret) {
337
- const sortedPayload = Object.keys(payload).sort().map((k) => `${k}=${payload[k]}`).join("&");
338
- const encoder = new TextEncoder();
339
- const key = await window.crypto.subtle.importKey("raw", encoder.encode(secret), {
340
- name: "HMAC",
341
- hash: "SHA-256"
342
- }, false, ["sign"]);
343
- const signatureBuffer = await window.crypto.subtle.sign("HMAC", key, encoder.encode(sortedPayload));
344
- const hashArray = Array.from(new Uint8Array(signatureBuffer));
345
- return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
346
- },
347
-
348
- /**
349
- * @internal
350
- * Resets the cached fingerprint builder. Used for testing purposes.
351
- */
352
- _resetCache() {
353
- // Réinitialise le hasher à l'implémentation JS par défaut.
354
- activeCyrb53 = jsCyrb53;
355
- this._cachedBuilder = null;
356
- },
357
-
358
- /**
359
- * Injecte des éléments interactifs fantômes invisibles pour piéger les bots (focus/hover).
360
- */
361
- injectPhantomTraps() {
362
- if (typeof document === 'undefined') return;
363
-
364
- // Création d'un élément interactif fantôme
365
- const phantom = document.createElement('a');
366
- phantom.href = '#';
367
- // Nom trompeur aléatoire pour attirer les analyseurs automatiques de liens / formulaires
368
- const phantomNames = ['sys-session-recovery', 'auth-token-refresh', 'debug-console-login', 'admin-portal-access', 'security-bypass-bypass', 'recovery-key-session', 'api-key-test', 'client-secrets-access'];
369
- phantom.id = phantomNames[Math.floor(secureRandom() * phantomNames.length)] + '-' + genRandStr(6);
370
- phantom.className = genRandStr(8);
371
- phantom.tabIndex = 0; // Dans le flux naturel de tabulation
372
- phantom.setAttribute('aria-hidden', 'true'); // Masqué pour les screen readers légitimes
373
-
374
- // Style invisible mais interactif (1px x 1px, presque transparent)
375
- phantom.style.position = 'fixed';
376
- phantom.style.top = '1px';
377
- phantom.style.left = '1px';
378
- phantom.style.width = '1px';
379
- phantom.style.height = '1px';
380
- phantom.style.opacity = '0.001';
381
- phantom.style.zIndex = '99999';
382
- phantom.style.overflow = 'hidden';
383
- phantom.style.pointerEvents = 'auto';
384
-
385
- const triggerTrap = () => {
386
- this.onHoneypotTrigger();
387
- };
388
-
389
- phantom.addEventListener('focus', triggerTrap, { passive: true });
390
- phantom.addEventListener('mouseover', triggerTrap, { passive: true });
391
-
392
- // Imbrication polymorphique du piège fantôme dans le corps du document
393
- const nestingOptions = [
394
- () => document.body.appendChild(phantom),
395
- () => {
396
- const wrapper = document.createElement(secureRandom() > 0.5 ? 'span' : 'div');
397
- wrapper.className = genRandStr(8);
398
- wrapper.style.position = 'absolute';
399
- wrapper.style.width = '0';
400
- wrapper.style.height = '0';
401
- wrapper.style.overflow = 'hidden';
402
- wrapper.appendChild(phantom);
403
- document.body.appendChild(wrapper);
404
- }
405
- ];
406
- nestingOptions[Math.floor(secureRandom() * nestingOptions.length)]();
407
- },
408
-
409
- /**
410
- * Démarre le suivi des événements tactiles sur mobile/tablette.
411
- */
412
- startTouchEventTracker() {
413
- if (this._touchTrackerAttached) return;
414
- this._touchTrackerAttached = true;
415
-
416
- const handleTouch = (e) => {
417
- if (touchMovementsHistory.length >= TOUCH_HISTORY_MAX) {
418
- touchMovementsHistory.shift();
419
- }
420
- const touch = e.touches[0] || e.changedTouches[0];
421
- if (!touch) return;
422
-
423
- const radiusX = touch.radiusX || 0;
424
- const radiusY = touch.radiusY || 0;
425
- const radius = (radiusX + radiusY) / 2;
426
- const force = touch.force || touch.webkitForce || 0;
427
-
428
- touchMovementsHistory.push({
429
- x: touch.clientX,
430
- y: touch.clientY,
431
- t: performance.now(),
432
- p: force,
433
- r: radius,
434
- num: e.touches.length
435
- });
436
- };
437
-
438
- document.addEventListener('touchstart', handleTouch, { passive: true });
439
- document.addEventListener('touchmove', handleTouch, { passive: true });
440
- document.addEventListener('touchend', handleTouch, { passive: true });
441
- },
442
-
443
- /**
444
- * Démarre le suivi de la régularité d'affichage (V-Sync/rAF) pour détecter les framebuffers logiciels sans V-Sync.
445
- */
446
- startRenderingTracker() {
447
- if (this._renderingTrackerAttached) return;
448
- this._renderingTrackerAttached = true;
449
-
450
- if (typeof window === 'undefined' || !window.requestAnimationFrame) return;
451
-
452
- const rAfTimestamps = [];
453
- let lastTime = performance.now();
454
- const maxSamples = 15;
455
-
456
- const checkOffscreenAnom = () => {
457
- try {
458
- if ('OffscreenCanvas' in window && HTMLCanvasElement.prototype.transferControlToOffscreen) {
459
- const nativeToString = Function.prototype.toString.call(HTMLCanvasElement.prototype.transferControlToOffscreen);
460
- return !nativeToString.includes('[native code]');
461
- }
462
- } catch (e) {}
463
- return false;
464
- };
465
-
466
- const loop = (time) => {
467
- const delta = time - lastTime;
468
- lastTime = time;
469
- if (rAfTimestamps.length < maxSamples) {
470
- if (rAfTimestamps.length > 0) { // Skip first delta
471
- rAfTimestamps.push(delta);
472
- }
473
- window.requestAnimationFrame(loop);
474
- } else {
475
- const avg = rAfTimestamps.reduce((a, b) => a + b, 0) / rAfTimestamps.length;
476
- const sqDiffs = rAfTimestamps.map(v => Math.pow(v - avg, 2));
477
- const avgSqDiff = sqDiffs.reduce((a, b) => a + b, 0) / sqDiffs.length;
478
-
479
- metrics.rendering = {
480
- fps: Math.round((1000 / avg) * 100) / 100,
481
- jitter: Math.round(Math.sqrt(avgSqDiff) * 100) / 100,
482
- offscreenAnom: checkOffscreenAnom()
483
- };
484
- }
485
- };
486
- window.requestAnimationFrame(loop);
487
- },
488
-
489
- /**
490
- * Initialise l'espace Proof-of-Space persistant dans l'IndexedDB locale.
491
- */
492
- async initializeSpace(seed, sizeMb) {
493
- return new Promise((resolve, reject) => {
494
- const request = indexedDB.open('pospace-db', 1);
495
- request.onupgradeneeded = (e) => {
496
- const db = e.target.result;
497
- if (!db.objectStoreNames.contains('blocks')) {
498
- db.createObjectStore('blocks');
499
- }
500
- };
501
- request.onsuccess = async (e) => {
502
- const db = e.target.result;
503
- const tx = db.transaction('blocks', 'readwrite');
504
- const store = tx.objectStore('blocks');
505
-
506
- const maxBlocks = sizeMb * 1024;
507
- const countReq = store.count();
508
- countReq.onsuccess = async () => {
509
- if (countReq.result < maxBlocks) {
510
- for (let i = 0; i < maxBlocks; i++) {
511
- const block = new Uint8Array(1024);
512
- let h = 5381;
513
- for (let j = 0; j < seed.length; j++) {
514
- h = (h << 5) + h + seed.charCodeAt(j);
515
- }
516
- h = (h << 5) + h + i;
517
- for (let k = 0; k < 1024; k++) {
518
- h = Math.imul(h ^ k, 1597334677);
519
- block[k] = h & 0xff;
520
- }
521
- store.put(block, i);
522
- }
523
- }
524
- resolve();
525
- };
526
- };
527
- request.onerror = () => reject(new Error("Failed to open pospace database"));
528
- });
529
- },
530
-
531
- /**
532
- * Lit un bloc spécifique de l'IndexedDB locale sous format hexadécimal.
533
- */
534
- async readSpaceBlock(blockIdx) {
535
- return new Promise((resolve, reject) => {
536
- const request = indexedDB.open('pospace-db', 1);
537
- request.onsuccess = (e) => {
538
- const db = e.target.result;
539
- const tx = db.transaction('blocks', 'readonly');
540
- const store = tx.objectStore('blocks');
541
- const getReq = store.get(blockIdx);
542
- getReq.onsuccess = () => {
543
- const block = getReq.result;
544
- if (block) {
545
- const hex = Array.from(block).map(b => b.toString(16).padStart(2, '0')).join('');
546
- resolve(hex);
547
- } else {
548
- reject(new Error("Block not found"));
549
- }
550
- };
551
- getReq.onerror = () => reject(getReq.error);
552
- };
553
- request.onerror = () => reject(new Error("Failed to open pospace database"));
554
- });
555
- },
556
-
557
- /**
558
- * Résout le Proof-of-Space en combinant optionnellement le bloc du pair.
559
- */
560
- async solveSpaceChallenge(seed, queries, nonce, clientSecret, peerBlock = '') {
561
- const blocks = [];
562
- for (const idx of queries) {
563
- const blockHex = await this.readSpaceBlock(idx);
564
- blocks.push(blockHex);
565
- }
566
- let finalPayload = blocks.join('') + peerBlock + nonce + ":" + clientSecret;
567
- const encoder = new TextEncoder();
568
- const data = encoder.encode(finalPayload);
569
- const hashBuffer = await window.crypto.subtle.digest('SHA-256', data);
570
- const hashArray = Array.from(new Uint8Array(hashBuffer));
571
- return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
572
- },
573
-
574
- /**
575
- * Démarre le suivi des mouvements de la souris pour calculer l'entropie.
576
- * À appeler une fois sur la page.
577
- */
578
- startMouseEntropyTracker() {
579
- // Utiliser un drapeau pour éviter d'attacher l'écouteur plusieurs fois
580
- if (this._mouseTrackerAttached) return;
581
- this._mouseTrackerAttached = true;
582
-
583
- document.addEventListener('mousemove', (e) => {
584
- // NOUVEAU: Capturer une série de points {x, y, t}
585
- if (mouseMovementsHistory.length >= MOUSE_HISTORY_MAX) {
586
- // Garder la taille de l'historique constante pour éviter une consommation mémoire excessive.
587
- mouseMovementsHistory.shift();
588
- }
589
- mouseMovementsHistory.push({
590
- x: e.clientX,
591
- y: e.clientY,
592
- t: performance.now()
593
- });
594
- }, {passive: true});
595
- },
596
-
597
- /**
598
- * Démarre le suivi de la dynamique de frappe pour calculer le dwell time et le flight time (digraphie/trigraphie).
599
- * À appeler une fois sur la page.
600
- */
601
- startKeystrokeDynamicsTracker() {
602
- // S'assurer de ne pas attacher l'écouteur plusieurs fois
603
- if (this._keystrokeTrackerAttached) return;
604
- this._keystrokeTrackerAttached = true;
605
-
606
- const activeKeys = new Map();
607
- let lastKeyDownTime = 0;
608
- let lastKeyName = '';
609
-
610
- document.addEventListener('keydown', (e) => {
611
- const now = performance.now();
612
- const key = e.key;
613
- const code = e.code;
614
- if (!key && !code) return;
615
-
616
- const keyIdentifier = code || key;
617
-
618
- // Prevent key repeat triggering multiple events
619
- if (activeKeys.has(keyIdentifier)) return;
620
- activeKeys.set(keyIdentifier, now);
621
-
622
- if (keystrokeTimestamps.length > 0) {
623
- const lastTimestamp = keystrokeTimestamps[keystrokeTimestamps.length - 1];
624
- const latency = now - lastTimestamp;
625
- if (latency > 10 && latency < 2000) {
626
- if (keystrokeLatencies.length >= KEYSTROKE_HISTORY_MAX) {
627
- keystrokeLatencies.shift();
628
- }
629
- keystrokeLatencies.push(latency);
630
- }
631
- }
632
- keystrokeTimestamps.push(now);
633
-
634
- // Flight Time (KeyDown to KeyDown)
635
- if (lastKeyDownTime > 0) {
636
- const flightTime = now - lastKeyDownTime;
637
- if (flightTime > 10 && flightTime < 2000) {
638
- if (keystrokeFlightTimes.length >= KEYSTROKE_HISTORY_MAX) {
639
- keystrokeFlightTimes.shift();
640
- }
641
- const digraph = lastKeyName ? this._hasher(lastKeyName + "_" + keyIdentifier).toString() : "unknown";
642
- keystrokeFlightTimes.push({ digraph, time: flightTime });
643
- }
644
- }
645
- lastKeyDownTime = now;
646
- lastKeyName = keyIdentifier;
647
- }, {passive: true});
648
-
649
- document.addEventListener('keyup', (e) => {
650
- const now = performance.now();
651
- const key = e.key;
652
- const code = e.code;
653
- if (!key && !code) return;
654
-
655
- const keyIdentifier = code || key;
656
-
657
- if (activeKeys.has(keyIdentifier)) {
658
- const pressTime = activeKeys.get(keyIdentifier);
659
- const dwellTime = now - pressTime;
660
- activeKeys.delete(keyIdentifier);
661
-
662
- if (dwellTime > 5 && dwellTime < 1000) {
663
- if (keystrokeDwellTimes.length >= KEYSTROKE_HISTORY_MAX) {
664
- keystrokeDwellTimes.shift();
665
- }
666
- keystrokeDwellTimes.push(dwellTime);
667
- }
668
- }
669
- }, {passive: true});
670
- },
671
-
672
- /**
673
- * Starts tracking click events to analyze position variance.
674
- * @private
675
- */
676
- startClickTracker() {
677
- if (this._clickTrackerAttached) return;
678
- this._clickTrackerAttached = true;
679
-
680
- document.addEventListener('click', (e) => {
681
- if (clicksHistory.length >= CLICKS_HISTORY_MAX) {
682
- clicksHistory.shift();
683
- }
684
- // Generate a simple identifier for the target element
685
- const target = e.target;
686
- const targetId = target.id || target.name || target.tagName;
687
-
688
- clicksHistory.push({
689
- x: e.clientX,
690
- y: e.clientY,
691
- t: performance.now(),
692
- targetId: this._hasher(targetId) // Hash the ID to keep it short and consistent
693
- });
694
- }, { passive: true });
695
- },
696
- /**
697
- * Initialise ou réinitialise les honeypots côté client pour une détection immédiate.
698
- * Les anciens écouteurs sont supprimés avant d'en ajouter de nouveaux.
699
- * @param {string[]} honeypotFieldNames - Noms des champs de formulaire cachés.
700
- */
701
- initializeHoneypots(honeypotFieldNames) {
702
- // 1. Nettoyer les anciens écouteurs
703
- activeHoneypotListeners.forEach((listener, field) => {
704
- field.removeEventListener('input', listener);
705
- });
706
- activeHoneypotListeners.clear();
707
-
708
- // 2. Ajouter les nouveaux écouteurs sur le DOM classique
709
- honeypotFieldNames.forEach(fieldName => {
710
- const field = document.querySelector(`[name="${fieldName}"]`);
711
- if (field) {
712
- const listener = () => {
713
- this.onHoneypotTrigger();
714
- field.removeEventListener('input', listener);
715
- };
716
- field.addEventListener('input', listener);
717
- activeHoneypotListeners.set(field, listener); // On stocke la référence
718
- }
719
- });
720
-
721
- // 3. Générer des champs d'input pièges masqués dans un Shadow DOM fermé
722
- if (typeof document !== 'undefined' && honeypotFieldNames.length > 0) {
723
- const host = document.createElement('div');
724
- host.setAttribute('aria-hidden', 'true');
725
- host.style.position = 'absolute';
726
- host.style.width = '0';
727
- host.style.height = '0';
728
- host.style.overflow = 'hidden';
729
-
730
- const shadow = host.attachShadow({ mode: 'closed' });
731
-
732
- // Aléatisation des classes, variables CSS et balises de structure
733
- const wrapperClass = genRandStr(10);
734
- const posStateVar = `--${genRandStr(8)}`;
735
- const offValVar = `--${genRandStr(8)}`;
736
- const visStateVar = `--${genRandStr(8)}`;
737
- const scaleValVar = `--${genRandStr(8)}`;
738
-
739
- const style = document.createElement('style');
740
- style.textContent = `
741
- :host {
742
- ${posStateVar}: absolute;
743
- ${offValVar}: -9999px;
744
- ${visStateVar}: hidden;
745
- ${scaleValVar}: 0;
746
- }
747
- .${wrapperClass} {
748
- position: var(${posStateVar});
749
- left: var(${offValVar});
750
- top: var(${offValVar});
751
- visibility: var(${visStateVar});
752
- transform: scale(var(${scaleValVar}));
753
- }
754
- `;
755
- shadow.appendChild(style);
756
-
757
- const wrapperTags = ['div', 'section', 'p', 'span', 'form', 'main'];
758
- const selectedWrapperTag = wrapperTags[Math.floor(secureRandom() * wrapperTags.length)];
759
- const wrapper = document.createElement(selectedWrapperTag);
760
- wrapper.className = wrapperClass;
761
-
762
- honeypotFieldNames.forEach(fieldName => {
763
- const label = document.createElement('label');
764
- label.textContent = fieldName;
765
- const input = document.createElement('input');
766
- input.type = 'text';
767
- input.name = fieldName;
768
- input.tabIndex = -1;
769
- input.className = genRandStr(6);
770
- input.id = genRandStr(8);
771
- input.autocomplete = 'off';
772
-
773
- const trigger = () => {
774
- this.onHoneypotTrigger();
775
- };
776
-
777
- input.addEventListener('input', trigger, { passive: true });
778
- input.addEventListener('change', trigger, { passive: true });
779
- input.addEventListener('focus', trigger, { passive: true });
780
-
781
- // Imbrication polymorphique du label et de l'input
782
- const nestingType = Math.floor(secureRandom() * 3);
783
- if (nestingType === 1) {
784
- label.appendChild(input);
785
- wrapper.appendChild(label);
786
- } else if (nestingType === 2) {
787
- const innerContainer = document.createElement(secureRandom() > 0.5 ? 'span' : 'div');
788
- innerContainer.className = genRandStr(5);
789
- innerContainer.appendChild(label);
790
- innerContainer.appendChild(input);
791
- wrapper.appendChild(innerContainer);
792
- } else {
793
- wrapper.appendChild(label);
794
- wrapper.appendChild(input);
795
- }
796
- });
797
-
798
- shadow.appendChild(wrapper);
799
- document.body.appendChild(host);
800
- }
801
- },
802
- /**
803
- * Sollicite silencieusement l'attestation matérielle FIDO2 (WebAuthn)
804
- * pour ancrer l'identité physique de l'appareil via TPM / Secure Enclave.
805
- * @returns {Promise<object|null>}
806
- */
807
- async getWebAuthnAnchor() {
808
- if (typeof window === 'undefined' || !window.PublicKeyCredential) return null;
809
- try {
810
- const isPlatformAvailable = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
811
- if (!isPlatformAvailable) return null;
812
-
813
- const storedCredIdBase64 = localStorage.getItem('fp_webauthn_cred_id');
814
- const challenge = new Uint8Array([109, 101, 116, 114, 105, 99, 115, 95, 97, 110, 99, 104, 111, 114, 95, 115, 101, 99, 117, 114, 101]); // Static stable challenge
815
-
816
- if (storedCredIdBase64) {
817
- // Tentative d'assertion silencieuse (Authentification)
818
- const credentialId = Uint8Array.from(atob(storedCredIdBase64), c => c.charCodeAt(0));
819
- const assertion = await navigator.credentials.get({
820
- publicKey: {
821
- challenge,
822
- allowCredentials: [{
823
- id: credentialId,
824
- type: 'public-key'
825
- }],
826
- userVerification: 'discouraged',
827
- timeout: 1000
828
- }
829
- });
830
- if (assertion) {
831
- return {
832
- type: 'assertion',
833
- credentialId: storedCredIdBase64,
834
- signature: btoa(String.fromCharCode(...new Uint8Array(assertion.response.signature))),
835
- authenticatorData: btoa(String.fromCharCode(...new Uint8Array(assertion.response.authenticatorData))),
836
- clientDataJSON: btoa(String.fromCharCode(...new Uint8Array(assertion.response.clientDataJSON)))
837
- };
838
- }
839
- } else {
840
- // Création silencieuse (Enregistrement initial)
841
- const options = {
842
- publicKey: {
843
- challenge,
844
- rp: { name: window.location.hostname, id: window.location.hostname },
845
- user: {
846
- id: new Uint8Array([102, 112, 105, 100]),
847
- name: 'silent-device-anchor',
848
- displayName: 'Hardware Device Anchor'
849
- },
850
- pubKeyCredParams: [
851
- { type: 'public-key', alg: -7 }, // ES256 (P-256) - Secure Enclave / TPM / Android Keystore
852
- { type: 'public-key', alg: -257 } // RS256 - Windows Hello TPM
853
- ],
854
- authenticatorSelection: {
855
- authenticatorAttachment: 'platform',
856
- userVerification: 'discouraged',
857
- residentKey: 'preferred'
858
- },
859
- timeout: 1500,
860
- attestation: 'indirect'
861
- }
862
- };
863
- const credential = await navigator.credentials.create(options);
864
- if (credential) {
865
- const credIdBase64 = btoa(String.fromCharCode(...new Uint8Array(credential.rawId)));
866
- localStorage.setItem('fp_webauthn_cred_id', credIdBase64);
867
- const publicKeyDer = credential.response.getPublicKey ? credential.response.getPublicKey() : null;
868
- return {
869
- type: 'registration',
870
- credentialId: credIdBase64,
871
- publicKey: publicKeyDer ? btoa(String.fromCharCode(...new Uint8Array(publicKeyDer))) : null,
872
- attestationObject: btoa(String.fromCharCode(...new Uint8Array(credential.response.getAttestationObject()))),
873
- clientDataJSON: btoa(String.fromCharCode(...new Uint8Array(credential.response.clientDataJSON)))
874
- };
875
- }
876
- }
877
- } catch (e) {
878
- // Ignore et bypass silencieusement pour garder l'invisibilité en cas de non-support
879
- console.log('[WebAuthn-Anchor] Silent attestation bypassed:', e.message);
880
- }
881
- return null;
882
- },
883
-
884
- /**
885
- * Récupère les métriques comportementales collectées.
886
- * À appeler avant d'envoyer une requête sensible.
887
- * @returns {ClientBehaviorMetrics}
888
- */
889
- getClientBehaviorMetrics() {
890
- // Add history length as a behavioral signal.
891
- metrics.historyLength = window.history.length;
892
-
893
- // Ajoute un timestamp au moment de la collecte pour la détection de rejeu.
894
- metrics.clicksHistory = clicksHistory;
895
- metrics.clientTimestamp = Date.now();
896
-
897
- metrics.touchMovementsHistory = touchMovementsHistory;
898
- // NOUVEAU: Inclure l'historique des mouvements de la souris pour une analyse côté serveur.
899
- metrics.mouseMovementsHistory = mouseMovementsHistory;
900
-
901
- // NOUVEAU: Keystroke dynamics metrics (dwell and flight times)
902
- metrics.keystrokeDwellTimes = keystrokeDwellTimes;
903
- metrics.keystrokeFlightTimes = keystrokeFlightTimes;
904
-
905
- // Calcule la latence moyenne des frappes
906
- if (keystrokeLatencies.length > 0) {
907
- const sum = keystrokeLatencies.reduce((a, b) => a + b, 0);
908
- metrics.keystrokeLatency = sum / keystrokeLatencies.length;
909
- } else {
910
- metrics.keystrokeLatency = 0;
911
- }
912
- return metrics;
913
- },
914
-
915
- /**
916
- * Enrichit une requête fetch avec les en-têtes de fingerprinting et de comportement.
917
- * @param {RequestInfo} resource
918
- * @param {RequestInit} [options]
919
- * @returns {Promise<Response>}
920
- */
921
- async protectedFetch(resource, options = {}) {
922
- const fp = this.getDeviceFingerprint();
923
- const rawBehavior = this.getClientBehaviorMetrics();
924
- const zkpProof = await this.generateZkpProof(fp); // Generate ZKP proof
925
- const behavior = await signMetrics(rawBehavior);
926
-
927
- const headers = new Headers(options.headers || {});
928
- headers.set('X-ZKP-Proof', zkpProof); // Add ZKP proof to headers
929
- headers.set('X-Device-Fingerprint', fp);
930
- headers.set('X-Behavior-Metrics', JSON.stringify(behavior));
931
-
932
- options.headers = headers;
933
- return fetch(resource, options);
934
- },
935
-
936
- // --- Système d'interception de Fetch robuste et anti-conflit ---
937
-
938
- _isFetchPatched: false,
939
- _interceptorChain: [],
940
- // On stocke la fonction fetch originale et on la lie à son contexte (window)
941
- // pour éviter les erreurs "Illegal invocation" si une autre lib la modifie.
942
- _originalFetch: (typeof window !== 'undefined') ? window.fetch.bind(window) : null,
943
-
944
- /**
945
- * Adds an interceptor function to the `fetch` chain.
946
- * Chaque intercepteur reçoit `resource`, `options`, et une fonction `next`.
947
- * Il DOIT appeler `next(resource, options)` pour continuer la chaîne.
948
- * @param {function(RequestInfo, RequestInit, function): Promise<Response>} interceptor
949
- */
950
- addFetchInterceptor(interceptor) {
951
- if (!this._isFetchPatched) {
952
- this.patchGlobalFetch();
953
- }
954
- this._interceptorChain.push(interceptor);
955
- },
956
-
957
- patchGlobalFetch() {
958
- if (this._isFetchPatched || !this._originalFetch) return;
959
-
960
- this._isFetchPatched = true;
961
- window.fetch = (resource, options) => {
962
- // Le "dispatcher" qui exécute la chaîne.
963
- const dispatch = (index, res, opts) => {
964
- if (index >= this._interceptorChain.length) {
965
- // Fin de la chaîne, on appelle le fetch original.
966
- return this._originalFetch(res, opts);
967
- }
968
- const nextInterceptor = this._interceptorChain[index];
969
- // Appelle l'intercepteur actuel en lui passant la fonction pour appeler le suivant.
970
- return nextInterceptor(res, opts, (nextRes, nextOpts) => dispatch(index + 1, nextRes, nextOpts));
971
- };
972
- return dispatch(0, resource, options || {});
973
- };
974
- },
975
-
976
- /**
977
- * La fonction qui est appelée lorsqu'un honeypot est déclenché.
978
- * @private
979
- */
980
- onHoneypotTrigger() {
981
- metrics.honeypotInteraction = true;
982
- // Émettre un événement pour que l'application puisse réagir.
983
- this._dispatchEvent('honeypotTriggered');
984
- },
985
-
986
- /**
987
- * Initialise l'intercepteur de fingerprinting.
988
- * Il s'ajoute à la chaîne d'interception sans écraser les autres.
989
- * @param {string[]} [targetDomains] - Optionnel. Liste de domaines à protéger.
990
- * Si non fourni, protège les requêtes de même origine.
991
- */
992
- initializeFetch(targetDomains = []) {
993
- const fingerprintInterceptor = async (resource, options, next) => {
994
- const requestUrl = (resource instanceof Request) ? resource.url : String(resource);
995
- let shouldProtect = false;
996
-
997
- try {
998
- const url = new URL(requestUrl, window.location.origin);
999
- // Protéger si la liste de domaines est vide ET que la requête est de même origine,
1000
- // OU si le domaine de la requête est dans la liste fournie.
1001
- shouldProtect = (targetDomains.length === 0 && url.origin === window.location.origin) ||
1002
- (targetDomains.length > 0 && targetDomains.includes(url.hostname));
1003
- } catch (e) {
1004
- // Si l'URL est relative (ex: '/api/data'), new URL() ne lèvera pas d'erreur.
1005
- // Ce bloc est une sécurité pour les cas où l'URL serait malformée.
1006
- // On protège par défaut si aucune liste de domaines n'est spécifiée.
1007
- shouldProtect = targetDomains.length === 0;
1008
- }
1009
-
1010
- if (shouldProtect) {
1011
- const fp = this.getDeviceFingerprint();
1012
- const rawBehavior = this.getClientBehaviorMetrics();
1013
- const behavior = await signMetrics(rawBehavior);
1014
- const headers = new Headers(options.headers || {});
1015
- headers.set('X-Device-Fingerprint', fp);
1016
- headers.set('X-Behavior-Metrics', JSON.stringify(behavior));
1017
- options.headers = headers;
1018
- }
1019
-
1020
- // Passe la main à l'intercepteur suivant dans la chaîne.
1021
- return next(resource, options);
1022
- };
1023
-
1024
- this.addFetchInterceptor(fingerprintInterceptor);
1025
- }, // <-- VIRGULE AJOUTÉE ICI
1026
-
1027
- /**
1028
- * Injects visually hidden "honeypot" links into the DOM to trap bots.
1029
- * @param {string[]} urls - An array of trap URLs to inject.
1030
- * @private
1031
- */
1032
- injectTrapLinks(urls) {
1033
- if (!urls || urls.length === 0 || typeof document === 'undefined') {
1034
- return;
1035
- }
1036
-
1037
- const host = document.createElement('div');
1038
- host.setAttribute('aria-hidden', 'true');
1039
- host.style.position = 'absolute';
1040
- host.style.width = '0';
1041
- host.style.height = '0';
1042
- host.style.overflow = 'hidden';
1043
-
1044
- const shadow = host.attachShadow({ mode: 'closed' });
1045
-
1046
- // Aléatisation des classes, variables CSS et balises de structure
1047
- const wrapperClass = genRandStr(10);
1048
- const layoutPosVar = `--${genRandStr(8)}`;
1049
- const offsetValVar = `--${genRandStr(8)}`;
1050
- const visibilityStateVar = `--${genRandStr(8)}`;
1051
- const scaleFactorVar = `--${genRandStr(8)}`;
1052
- const ptrEventsVar = `--${genRandStr(8)}`;
1053
- const linkColorClass = genRandStr(6);
1054
-
1055
- const style = document.createElement('style');
1056
- style.textContent = `
1057
- :host {
1058
- ${layoutPosVar}: absolute;
1059
- ${offsetValVar}: -9999px;
1060
- ${visibilityStateVar}: hidden;
1061
- ${scaleFactorVar}: 0;
1062
- ${ptrEventsVar}: none;
1063
- }
1064
- .${wrapperClass} {
1065
- position: var(${layoutPosVar});
1066
- left: var(${offsetValVar});
1067
- top: var(${offsetValVar});
1068
- visibility: var(${visibilityStateVar});
1069
- transform: scale(var(${scaleFactorVar}));
1070
- pointer-events: var(${ptrEventsVar});
1071
- }
1072
- .${linkColorClass} {
1073
- color: transparent;
1074
- text-decoration: none;
1075
- }
1076
- `;
1077
- shadow.appendChild(style);
1078
-
1079
- const wrapperTags = ['div', 'section', 'p', 'span', 'nav', 'aside'];
1080
- const selectedWrapperTag = wrapperTags[Math.floor(secureRandom() * wrapperTags.length)];
1081
- const wrapper = document.createElement(selectedWrapperTag);
1082
- wrapper.className = wrapperClass;
1083
-
1084
- urls.forEach((url, i) => {
1085
- const link = document.createElement('a');
1086
- link.href = url;
1087
- link.rel = 'nofollow';
1088
- link.tabIndex = -1;
1089
- link.className = linkColorClass;
1090
- link.id = genRandStr(8);
1091
-
1092
- // Structure interne polymorphique du lien
1093
- const contentNestingType = Math.floor(secureRandom() * 3);
1094
- if (contentNestingType === 1) {
1095
- const span = document.createElement('span');
1096
- span.className = genRandStr(5);
1097
- span.innerHTML = `&gt; ${i + 1}`;
1098
- link.appendChild(span);
1099
- } else if (contentNestingType === 2) {
1100
- const b = document.createElement('b');
1101
- b.className = genRandStr(5);
1102
- b.innerHTML = `&gt; ${i + 1}`;
1103
- link.appendChild(b);
1104
- } else {
1105
- link.innerHTML = `<span>&gt; ${i + 1}</span>`;
1106
- }
1107
-
1108
- const trigger = () => {
1109
- this.onHoneypotTrigger();
1110
- };
1111
- link.addEventListener('click', trigger, { passive: true });
1112
- link.addEventListener('focus', trigger, { passive: true });
1113
- link.addEventListener('mouseover', trigger, { passive: true });
1114
-
1115
- // Imbrication du lien de manière polymorphique
1116
- if (secureRandom() > 0.5) {
1117
- const itemContainer = document.createElement('span');
1118
- itemContainer.className = genRandStr(5);
1119
- itemContainer.appendChild(link);
1120
- wrapper.appendChild(itemContainer);
1121
- } else {
1122
- wrapper.appendChild(link);
1123
- }
1124
- });
1125
-
1126
- shadow.appendChild(wrapper);
1127
- document.body.appendChild(host);
1128
- },
1129
- /**
1130
- * Intercepte une réponse de challenge JSON, le résout, et réessaie la requête.
1131
- * @param {Response} response - La réponse initiale (potentiellement 429).
1132
- * @param {RequestInfo} resource - La ressource de la requête originale.
1133
- * @param {RequestInit} options - Les options de la requête originale.
1134
- * @returns {Promise<Response>} - La réponse de la requête réessayée.
1135
- * @private
1136
- */
1137
- async solveChallengeAndRetry(response, resource, options) {
1138
- if (response.status !== 404 || !response.headers.get('content-type')?.includes('application/json') || response.bodyUsed) {
1139
- return response;
1140
- }
1141
-
1142
- try {
1143
- const challengeData = await response.json();
1144
- if (!challengeData.challenge || !challengeData.challenge.type) {
1145
- return response; // Pas un challenge JSON valide
1146
- }
1147
-
1148
- console.log(`[Fingerprint] Received a '${challengeData.challenge.type}' challenge. Solving...`);
1149
- this._dispatchEvent('challengeReceived', { challenge: challengeData.challenge });
1150
-
1151
- // L'empreinte de l'appareil qui résout le challenge est cruciale.
1152
- const solverFp = this.getDeviceFingerprint();
1153
- const solutionWrapper = await solveChallenge(challengeData.challenge, solverFp);
1154
- console.log('[Fingerprint] Challenge solved. Retrying original request.');
1155
-
1156
- this._dispatchEvent('challengeSolved', { solution: solutionWrapper.rawSolution });
1157
- // Ajouter la solution aux paramètres de la requête pour le nouvel essai
1158
- const url = new URL((resource instanceof Request) ? resource.url : String(resource), window.location.origin);
1159
- // La logique de formatage est maintenant cachée dans la classe ChallengeSolution.
1160
- solutionWrapper.applyToUrl(url);
1161
-
1162
- // On ajoute l'empreinte du solveur à la requête de réessai.
1163
- url.searchParams.set('pow_fp', solverFp);
1164
-
1165
- // On utilise la chaîne d'intercepteurs pour la requête réessayée,
1166
- // ce qui garantit que le fetch original est appelé avec le bon contexte.
1167
- // Cela évite de réintroduire l'erreur "Illegal invocation".
1168
- return window.fetch(url.toString(), options);
1169
- } catch (e) {
1170
- console.error('[Fingerprint] Failed to solve or retry challenge:', e);
1171
- return response; // Retourne la réponse 429 originale en cas d'échec
1172
- }
1173
- }, // <-- VIRGULE AJOUTÉE ICI
1174
-
1175
- /**
1176
- * Initialise toutes les protections côté client en une seule fois.
1177
- * Tente également de charger le module WASM si `wasmPath` est fourni.
1178
- * C'est la méthode d'initialisation recommandée.
1179
- * @param {ClientConfig} [config={}] - L'objet de configuration.
1180
- */
1181
- initializeClient(config = {}) {
1182
- const {
1183
- mouse = true,
1184
- keystrokes = true,
1185
- clicks = true, // Add new option
1186
- touches = true, // Nouveau paramètre tactiles
1187
- rendering = true,
1188
- phantomTraps = true, // NOUVEAU
1189
- honeypots = [],
1190
- trapUrls = [], // Nouveau paramètre pour les URL pièges
1191
- wasmPath, // Nouveau paramètre
1192
- fetch: fetchConfig = {}
1193
- } = config;
1194
-
1195
- negotiateSessionKey();
1196
- // Tentative de chargement du WASM si le chemin est fourni
1197
- if (wasmPath) {
1198
- this.initializeWasm(wasmPath);
1199
- }
1200
-
1201
- if (mouse) {
1202
- this.startMouseEntropyTracker();
1203
- }
1204
- if (keystrokes) {
1205
- this.startKeystrokeDynamicsTracker();
1206
- }
1207
- if (clicks) {
1208
- this.startClickTracker();
1209
- }
1210
- if (touches) {
1211
- this.startTouchEventTracker();
1212
- }
1213
- if (rendering) {
1214
- this.startRenderingTracker();
1215
- }
1216
- if (phantomTraps) {
1217
- this.injectPhantomTraps();
1218
- }
1219
- if (honeypots.length > 0) {
1220
- this.initializeHoneypots(honeypots);
1221
- }
1222
-
1223
- // Injection dynamique des liens pièges au démarrage
1224
- if (trapUrls.length > 0) {
1225
- this.injectTrapLinks(trapUrls);
1226
- }
1227
- // On active l'interception si `fetch` est configuré, même avec un objet vide.
1228
- if (config.fetch) {
1229
- this.initializeFetch(fetchConfig.targetDomains);
1230
-
1231
- // Ajoute l'intercepteur pour la résolution de challenge
1232
- if (fetchConfig.handleChallenges !== false) {
1233
- this.addFetchInterceptor(async (resource, options, next) => {
1234
- const originalResponse = await next(resource, options);
1235
- // On clone la réponse pour que la lecture du corps par solveChallengeAndRetry ne la consomme pas pour l'appelant original.
1236
- return this.solveChallengeAndRetry(originalResponse.clone(), resource, options);
1237
- });
1238
- }
1239
- }
1240
- },
1241
-
1242
- /**
1243
- * Tente de charger et d'initialiser le module WebAssembly pour un hachage plus rapide.
1244
- * Si le chargement échoue, il se rabat silencieusement sur l'implémentation JS.
1245
- * @param {string} wasmPath - Le chemin vers le script de chargement du module WASM (ex: '/fp.js').
1246
- */
1247
- async initializeWasm(wasmPath) {
1248
- try {
1249
- // Direct standalone polymorphic WebAssembly loading
1250
- if (wasmPath.endsWith('.wasm')) {
1251
- const response = await fetch(wasmPath);
1252
- const arrayBuffer = await response.arrayBuffer();
1253
- const module = await WebAssembly.compile(arrayBuffer);
1254
- const instance = await WebAssembly.instantiate(module, {});
1255
- const exports = instance.exports;
1256
- const memory = exports.memory;
1257
- activeCyrb53 = (str) => {
1258
- const encoder = new TextEncoder();
1259
- const bytes = encoder.encode(str);
1260
- const view = new Uint8Array(memory.buffer, 0, bytes.length);
1261
- view.set(bytes);
1262
- return exports.hash(0, bytes.length);
1263
- };
1264
- console.log('[Fingerprint] Standalone polymorphic WASM loaded successfully. Using fast dynamic hashing.');
1265
- if (this._cachedBuilder) {
1266
- this._cachedBuilder.addRaw('wasm', 'true');
1267
- }
1268
- return;
1269
- }
1270
- // 1. Injecter le script qui charge le module WASM
1271
- const script = document.createElement('script');
1272
- script.src = wasmPath;
1273
- await new Promise((resolve, reject) => {
1274
- script.onload = resolve;
1275
- script.onerror = reject;
1276
- document.head.appendChild(script);
1277
- });
1278
-
1279
- // 2. Attendre que la fonction globale `createFingerprintModule` soit disponible
1280
- if (typeof window.createFingerprintModule !== 'function') {
1281
- throw new Error('WASM loader script did not expose createFingerprintModule.');
1282
- }
1283
-
1284
- // 3. Initialiser le module
1285
- const wasmUrl = wasmPath.replace(/\.js$/, '.wasm');
1286
- const wasmModule = await window.createFingerprintModule({
1287
- instantiateWasm: (imports, successCallback) => {
1288
- (async () => {
1289
- try {
1290
- const cached = await getCachedWasm(wasmUrl);
1291
- if (cached) {
1292
- let instance;
1293
- if (cached instanceof WebAssembly.Module) {
1294
- instance = await WebAssembly.instantiate(cached, imports);
1295
- } else {
1296
- const result = await WebAssembly.instantiate(cached, imports);
1297
- instance = result.instance;
1298
- }
1299
- successCallback(instance, cached);
1300
- return;
1301
- }
1302
-
1303
- const response = await fetch(wasmUrl);
1304
- const arrayBuffer = await response.arrayBuffer();
1305
-
1306
- let cachedData = arrayBuffer;
1307
- let isModuleCached = false;
1308
- try {
1309
- const compiledModule = await WebAssembly.compile(arrayBuffer);
1310
- const success = await cacheWasm(wasmUrl, compiledModule);
1311
- if (success) {
1312
- cachedData = compiledModule;
1313
- isModuleCached = true;
1314
- }
1315
- } catch (e) {
1316
- // Fallback if browser doesn't allow structured cloning of Compiled Modules
1317
- }
1318
-
1319
- if (!isModuleCached) {
1320
- await cacheWasm(wasmUrl, arrayBuffer);
1321
- }
1322
-
1323
- let instance;
1324
- if (cachedData instanceof WebAssembly.Module) {
1325
- instance = await WebAssembly.instantiate(cachedData, imports);
1326
- } else {
1327
- const result = await WebAssembly.instantiate(arrayBuffer, imports);
1328
- instance = result.instance;
1329
- }
1330
- successCallback(instance, cachedData);
1331
- } catch (err) {
1332
- console.warn('[Fingerprint] Custom WASM instantiation failed, falling back to default Emscripten loader:', err);
1333
- successCallback(null);
1334
- }
1335
- })();
1336
- return {}; // Async instantiation indicator for Emscripten
1337
- }
1338
- });
1339
- if (typeof wasmModule._hash_string !== 'function') {
1340
- throw new Error('WASM module did not export _hash_string.');
1341
- }
1342
- window.wasmModule = wasmModule;
1343
- ClientLibrary.wasmModule = wasmModule;
1344
-
1345
- // Pooling de mémoire statique : pré-allocation d'un buffer réutilisable de 4 Ko
1346
- // Évite d'allouer/libérer de la mémoire sur le tas Emscripten lors des frappes clavier/mouvements souris rapides
1347
- const staticBufferSize = 4096;
1348
- const staticBufferPtr = wasmModule._malloc(staticBufferSize);
1349
- const encoder = new TextEncoder();
1350
-
1351
- // 4. Remplacer la fonction de hachage par la version WASM optimisée via le buffer statique
1352
- activeCyrb53 = (str) => {
1353
- const bytes = encoder.encode(str);
1354
- if (bytes.length < staticBufferSize) {
1355
- wasmModule.HEAPU8.set(bytes, staticBufferPtr);
1356
- wasmModule.HEAPU8[staticBufferPtr + bytes.length] = 0; // null-terminator
1357
- return wasmModule._hash_string(staticBufferPtr);
1358
- }
1359
- // Fallback dynamique sécurisé si la chaîne dépasse la taille du buffer statique
1360
- return wasmModule._hash_string(str);
1361
- };
1362
-
1363
- console.log('[Fingerprint] WASM module loaded successfully. Using fast hashing.');
1364
- // NOUVEAU: Ajoute un indicateur à l'empreinte pour que le serveur sache que le WASM est actif.
1365
- if (this._cachedBuilder) {
1366
- this._cachedBuilder.addRaw('wasm', 'true');
1367
- }
1368
- } catch (error) {
1369
- console.warn('[Fingerprint] WASM module failed to load. Falling back to JS implementation. Error:', error);
1370
- }
1371
- }
1372
- };
1373
-
1374
- /**
1375
- * @typedef {object} ClientBehaviorMetrics
1376
- * @property {number} mouseEntropy - Entropie des mouvements de la souris.
1377
- * @property {Array<{x: number, y: number, t: number}>} mouseMovementsHistory - Historique des points de la souris.
1378
- * @property {number} keystrokeLatency - Latence moyenne entre les frappes.
1379
- * @property {boolean} honeypotInteraction - Vrai si un honeypot a été touché.
1380
- * @property {Array<{x: number, y: number, t: number, targetId: string}>} clicksHistory - Historique des clics.
1381
- * @property {Array<{x: number, y: number, t: number, p: number, r: number, num: number}>} touchMovementsHistory - Historique des glissements tactiles.
1382
- * @property {number} historyLength - La longueur de l'historique de session du navigateur (`window.history.length`).
1383
- * @property {number} clientTimestamp - Timestamp (Date.now()) de la collecte des métriques.
1384
- * @property {string[]} [trapUrls] - URLs pièges à injecter dynamiquement.
1385
- */
1386
- /** @type {ClientBehaviorMetrics} */
1387
- const metrics = {
1388
- mouseEntropy: 0, // Conservé pour la compatibilité, mais l'analyse se fait maintenant sur l'historique
1389
- mouseMovementsHistory: [],
1390
- touchMovementsHistory: [],
1391
- clicksHistory: [],
1392
- keystrokeLatency: 0,
1393
- honeypotInteraction: false,
1394
- historyLength: 0,
1395
- clientTimestamp: 0,
1396
- rendering: { fps: 0, jitter: 0, offscreenAnom: false },
1397
- };
1398
-
1399
- let lastMousePos = { x: 0, y: 0 };
1400
- let mouseMovementsHistory = []; // NOUVEAU: Historique des points de la souris
1401
- let touchMovementsHistory = []; // NOUVEAU: Historique des gestes tactiles
1402
- const TOUCH_HISTORY_MAX = 100;
1403
- const MOUSE_HISTORY_MAX = 100; // Limite le nombre de points stockés
1404
- let clicksHistory = [];
1405
- const CLICKS_HISTORY_MAX = 50;
1406
- let activeHoneypotListeners = new Map(); // Garde une trace des écouteurs actifs
1407
- let keystrokeTimestamps = [];
1408
- let keystrokeLatencies = []; // NOUVEAU: Tableau dédié pour les latences
1409
- let keystrokeDwellTimes = [];
1410
- let keystrokeFlightTimes = [];
1411
- const KEYSTROKE_HISTORY_MAX = 20; // On garde l'historique des 20 dernières frappes
1412
-
1413
-
1414
-
1415
- // Exporter les fonctions individuellement pour la compatibilité ascendante
1416
- export const getDeviceFingerprint = ClientLibrary.getDeviceFingerprint.bind(ClientLibrary);
1417
- export const generateRequestSignature = ClientLibrary.generateRequestSignature.bind(ClientLibrary);
1418
- export const generateClientSideSignature = ClientLibrary.generateClientSideSignature.bind(ClientLibrary);
1419
- export const _resetCache = ClientLibrary._resetCache.bind(ClientLibrary);
1420
- export const startMouseEntropyTracker = ClientLibrary.startMouseEntropyTracker.bind(ClientLibrary);
1421
- export const startKeystrokeDynamicsTracker = ClientLibrary.startKeystrokeDynamicsTracker.bind(ClientLibrary);
1422
- export const startClickTracker = ClientLibrary.startClickTracker.bind(ClientLibrary);
1423
- export const startTouchEventTracker = ClientLibrary.startTouchEventTracker.bind(ClientLibrary);
1424
- export const startRenderingTracker = ClientLibrary.startRenderingTracker.bind(ClientLibrary);
1425
- export const initializeHoneypots = ClientLibrary.initializeHoneypots.bind(ClientLibrary);
1426
- export const getClientBehaviorMetrics = ClientLibrary.getClientBehaviorMetrics.bind(ClientLibrary);
1427
- export const protectedFetch = ClientLibrary.protectedFetch.bind(ClientLibrary);
1428
- export const addFetchInterceptor = ClientLibrary.addFetchInterceptor.bind(ClientLibrary);
1429
- export const patchGlobalFetch = ClientLibrary.patchGlobalFetch.bind(ClientLibrary);
1430
- export const initializeFetch = ClientLibrary.initializeFetch.bind(ClientLibrary);
1431
- export const initializeClient = ClientLibrary.initializeClient.bind(ClientLibrary);
1432
- export const initializeWasm = ClientLibrary.initializeWasm.bind(ClientLibrary);
1433
- export const injectTrapLinks = ClientLibrary.injectTrapLinks.bind(ClientLibrary);
1434
- export const injectPhantomTraps = ClientLibrary.injectPhantomTraps.bind(ClientLibrary);
1435
- export const solveChallengeAndRetry = ClientLibrary.solveChallengeAndRetry.bind(ClientLibrary);
1436
- export const generateZkpProof = ClientLibrary.generateZkpProof.bind(ClientLibrary);
1437
- export const initializeSpace = ClientLibrary.initializeSpace.bind(ClientLibrary);
1438
- export const readSpaceBlock = ClientLibrary.readSpaceBlock.bind(ClientLibrary);
1439
- export const solveSpaceChallenge = ClientLibrary.solveSpaceChallenge.bind(ClientLibrary);
1440
-
1441
- // Export the internal object for testing purposes
1442
- export default ClientLibrary;
1443
-
1444
- // --- Global Export for Browser ---
1445
- // Attach the library to the window object to make it accessible from inline scripts.
1446
- if (typeof window !== 'undefined') {
1447
- window.ClientLibrary = ClientLibrary;
1
+ import {cyrb53 as jsCyrb53, FingerprintBuilder} from './fingerprint.builder.js';
2
+ import {solveChallenge} from './pow.solver.js';
3
+
4
+ function secureRandom() {
5
+ if (typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.getRandomValues) {
6
+ const array = new Uint32Array(1);
7
+ globalThis.crypto.getRandomValues(array);
8
+ return array[0] / 0xffffffff;
9
+ }
10
+ return Math.random();
11
+ }
12
+
13
+ // Variable pour stocker la fonction de hachage active.
14
+ // Par défaut, c'est l'implémentation JavaScript.
15
+ let activeCyrb53 = jsCyrb53;
16
+ let derivedKey = null;
17
+
18
+ async function negotiateSessionKey() {
19
+ if (typeof window === 'undefined' || !window.crypto || !window.crypto.subtle) return;
20
+ try {
21
+ const keyPair = await window.crypto.subtle.generateKey(
22
+ { name: "ECDH", namedCurve: "P-256" },
23
+ false,
24
+ ["deriveKey"]
25
+ );
26
+ const clientPubKeyBuffer = await window.crypto.subtle.exportKey("raw", keyPair.publicKey);
27
+ const clientPubKeyHex = Array.from(new Uint8Array(clientPubKeyBuffer))
28
+ .map(b => b.toString(16).padStart(2, '0'))
29
+ .join('');
30
+
31
+ const response = await fetch(window.location.pathname + '?fp_handshake=1', {
32
+ method: 'POST',
33
+ headers: {
34
+ 'Content-Type': 'application/json',
35
+ 'x-client-ephemeral-key': clientPubKeyHex
36
+ },
37
+ body: JSON.stringify({ fp: ClientLibrary.getDeviceFingerprint() })
38
+ });
39
+
40
+ const serverPubKeyHex = response.headers.get('x-server-ephemeral-key');
41
+ if (serverPubKeyHex) {
42
+ const serverPubKeyBuffer = new Uint8Array(
43
+ serverPubKeyHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))
44
+ );
45
+ const serverPubKey = await window.crypto.subtle.importKey(
46
+ "raw",
47
+ serverPubKeyBuffer,
48
+ { name: "ECDH", namedCurve: "P-256" },
49
+ true,
50
+ []
51
+ );
52
+ derivedKey = await window.crypto.subtle.deriveKey(
53
+ { name: "ECDH", public: serverPubKey },
54
+ keyPair.privateKey,
55
+ { name: "HMAC", hash: "SHA-256", length: 256 },
56
+ true,
57
+ ["sign"]
58
+ );
59
+ console.log('[Fingerprint] Cryptographic session negotiated successfully.');
60
+ }
61
+ } catch (e) {
62
+ console.warn('[Fingerprint] Cryptographic session negotiation failed:', e);
63
+ }
64
+ }
65
+
66
+ async function signMetrics(metricsObj) {
67
+ if (!derivedKey) return metricsObj;
68
+ try {
69
+ const copy = JSON.parse(JSON.stringify(metricsObj));
70
+ delete copy.signature;
71
+ const dataToSign = new TextEncoder().encode(JSON.stringify(copy));
72
+ const signatureBuffer = await window.crypto.subtle.sign(
73
+ "HMAC",
74
+ derivedKey,
75
+ dataToSign
76
+ );
77
+ copy.signature = Array.from(new Uint8Array(signatureBuffer))
78
+ .map(b => b.toString(16).padStart(2, '0'))
79
+ .join('');
80
+ return copy;
81
+ } catch (e) {
82
+ return metricsObj;
83
+ }
84
+ }
85
+
86
+ const DB_NAME = 'wasm-cache-db';
87
+ const DB_VERSION = 1;
88
+ const STORE_NAME = 'wasm-modules';
89
+
90
+ const genRandStr = (len = 8) => {
91
+ return Array.from({ length: len }, () => String.fromCharCode(97 + Math.floor(secureRandom() * 26))).join('');
92
+ };
93
+
94
+ function getCachedWasm(url) {
95
+ return new Promise((resolve) => {
96
+ if (typeof indexedDB === 'undefined') return resolve(null);
97
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
98
+ request.onupgradeneeded = (e) => {
99
+ const db = e.target.result;
100
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
101
+ db.createObjectStore(STORE_NAME);
102
+ }
103
+ };
104
+ request.onsuccess = (e) => {
105
+ const db = e.target.result;
106
+ try {
107
+ const transaction = db.transaction(STORE_NAME, 'readonly');
108
+ const store = transaction.objectStore(STORE_NAME);
109
+ const getReq = store.get(url);
110
+ getReq.onsuccess = () => resolve(getReq.result);
111
+ getReq.onerror = () => resolve(null);
112
+ } catch (err) {
113
+ resolve(null);
114
+ }
115
+ };
116
+ request.onerror = () => resolve(null);
117
+ });
118
+ }
119
+
120
+ function cacheWasm(url, data) {
121
+ return new Promise((resolve) => {
122
+ if (typeof indexedDB === 'undefined') return resolve(false);
123
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
124
+ request.onupgradeneeded = (e) => {
125
+ const db = e.target.result;
126
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
127
+ db.createObjectStore(STORE_NAME);
128
+ }
129
+ };
130
+ request.onsuccess = (e) => {
131
+ const db = e.target.result;
132
+ try {
133
+ const transaction = db.transaction(STORE_NAME, 'readwrite');
134
+ const store = transaction.objectStore(STORE_NAME);
135
+ store.put(data, url);
136
+ transaction.oncomplete = () => resolve(true);
137
+ transaction.onerror = () => resolve(false);
138
+ } catch (err) {
139
+ resolve(false);
140
+ }
141
+ };
142
+ request.onerror = () => resolve(false);
143
+ });
144
+ }
145
+
146
+ const ClientLibrary = {
147
+ // Cache pour éviter de recalculer les constantes (Hardware, etc.)
148
+ _cachedBuilder: null,
149
+ /**
150
+ * @private
151
+ * Dispatches a custom event from the window object.
152
+ * @param {string} eventName - The name of the event.
153
+ * @param {object} [detail={}] - The data to include in the event's detail property.
154
+ */
155
+ _dispatchEvent(eventName, detail = {}) {
156
+ if (typeof window === 'undefined' || typeof CustomEvent === 'undefined') return;
157
+ const event = new CustomEvent(`fingerprint:${eventName}`, { detail });
158
+ window.dispatchEvent(event);
159
+ },
160
+
161
+ /**
162
+ * Wrapper interne pour la fonction de hachage.
163
+ * @private
164
+ */
165
+ _hasher: (str, seed) => activeCyrb53(str, seed),
166
+
167
+ /**
168
+ * Génère une preuve de connaissance à divulgation nulle (ZKP) de Schnorr pour l'empreinte de l'appareil.
169
+ * Rend le tout stable et compatible avec les vérifications JS, PHP et Python.
170
+ * @param {string} fingerprint - L'empreinte de l'appareil.
171
+ * @returns {Promise<string>} La preuve sous format "y:t:s" en hexadécimal.
172
+ */
173
+ async generateZkpProof(fingerprint) {
174
+ const ZKP_P = 115792089237316195423570985008687907853269984665640564039457584007908834671663n;
175
+ const ZKP_G = 2n;
176
+ const cryptoObj = window.crypto || window.msCrypto;
177
+
178
+ const sha256Hex = async (str) => {
179
+ const encoder = new TextEncoder();
180
+ const data = encoder.encode(str);
181
+ const hashBuffer = await cryptoObj.subtle.digest('SHA-256', data);
182
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
183
+ return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
184
+ };
185
+
186
+ const modPow = (base, exponent, modulus) => {
187
+ if (modulus === 1n) return 0n;
188
+ let result = 1n;
189
+ base = base % modulus;
190
+ while (exponent > 0n) {
191
+ if (exponent % 2n === 1n) {
192
+ result = (result * base) % modulus;
193
+ }
194
+ exponent = exponent >> 1n;
195
+ base = (base * base) % modulus;
196
+ }
197
+ return result;
198
+ };
199
+
200
+ const xHex = await sha256Hex(fingerprint);
201
+ const x = BigInt('0x' + xHex) % ZKP_P;
202
+ const y = modPow(ZKP_G, x, ZKP_P);
203
+ const randomBytes = new Uint8Array(32);
204
+ cryptoObj.getRandomValues(randomBytes);
205
+ let vHex = Array.from(randomBytes).map(b => b.toString(16).padStart(2, '0')).join('');
206
+ let v = BigInt('0x' + vHex) % (ZKP_P - 1n);
207
+ if (v === 0n) v = 1n;
208
+ const t = modPow(ZKP_G, v, ZKP_P);
209
+ const cStr = ZKP_G.toString() + y.toString() + t.toString();
210
+ const cHex = await sha256Hex(cStr);
211
+ const c = BigInt('0x' + cHex) % ZKP_P;
212
+ const s = (v + c * x) % (ZKP_P - 1n);
213
+
214
+ return `${y.toString(16)}:${t.toString(16)}:${s.toString(16)}`;
215
+ },
216
+
217
+ /**
218
+ * Génère l'empreinte de l'appareil actuel.
219
+ */
220
+ getDeviceFingerprint() {
221
+ if (typeof window === "undefined") {
222
+ console.error("getDeviceFingerprint can only be called on the client-side.");
223
+ return "";
224
+ }
225
+
226
+ if (!this._cachedBuilder) {
227
+ const nav = window.navigator;
228
+ const screen = window.screen;
229
+
230
+ this._cachedBuilder = new FingerprintBuilder();
231
+
232
+ // 1. Hardware (Très stable) : Cœurs, RAM, GPU (si dispo via canvas), Touch
233
+ this._cachedBuilder.add(
234
+ "hw", // Utilise maintenant le hasher actif
235
+ `${nav.hardwareConcurrency}_${nav.deviceMemory}_${nav.maxTouchPoints}`,
236
+ );
237
+
238
+ // 2. Geo/Locale (Stable sauf voyage/VPN) : Timezone, Langue
239
+ this._cachedBuilder.add(
240
+ "geo",
241
+ `${Intl.DateTimeFormat().resolvedOptions().timeZone}_${nav.language}_${new Date().getTimezoneOffset()}`,
242
+ );
243
+
244
+ // 3. Screen (Stable sauf changement moniteur/zoom) : Dimensions, ColorDepth
245
+ this._cachedBuilder.add(
246
+ "scr",
247
+ `${screen.width}x${screen.height}_${screen.colorDepth}`,
248
+ );
249
+
250
+ // 4. Platform (Stable) : OS, Engine
251
+ this._cachedBuilder.add("os", nav.platform);
252
+
253
+ // 5. Graphics (WebGL Vendor/Renderer) - Invariant matériel fort
254
+ try {
255
+ const canvas = document.createElement("canvas");
256
+ const gl =
257
+ canvas.getContext("webgl2") ||
258
+ canvas.getContext("webgl") ||
259
+ canvas.getContext("experimental-webgl");
260
+ if (gl) {
261
+ const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
262
+ if (debugInfo) {
263
+ const vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
264
+ const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
265
+ this._cachedBuilder.add("gpu", `${vendor}_${renderer}`);
266
+ }
267
+ }
268
+ } catch (e) {
269
+ }
270
+
271
+ // 6. Canvas Fingerprinting (Rendering quirks)
272
+ try {
273
+ const canvas = document.createElement("canvas");
274
+ const ctx = canvas.getContext("2d");
275
+ if (ctx) {
276
+ canvas.width = 200;
277
+ canvas.height = 50;
278
+ ctx.textBaseline = "alphabetic";
279
+ ctx.font = "14px 'Arial'";
280
+ ctx.fillStyle = "#f60";
281
+ ctx.fillRect(125, 1, 62, 20);
282
+ ctx.fillStyle = "#069";
283
+ ctx.fillText("fingerprint", 2, 15);
284
+ ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
285
+ ctx.fillText("fingerprint", 4, 17);
286
+ this._cachedBuilder.add("cvs", canvas.toDataURL());
287
+ }
288
+ } catch (e) {
289
+ }
290
+
291
+ // 7. Détection des artefacts du Chrome DevTools Protocol (CDP)
292
+ // Ces variables sont souvent injectées par les outils d'automatisation.
293
+ const cdpFootprints = [
294
+ 'cdc_adoQpoasnfa76pfcZLmcfl_Array',
295
+ 'cdc_adoQpoasnfa76pfcZLmcfl_Promise',
296
+ 'cdc_adoQpoasnfa76pfcZLmcfl_Symbol',
297
+ '$cdc_asdjflasutopfhvcZLmcfl_',
298
+ '_selenium',
299
+ '_driver'
300
+ ];
301
+ if (cdpFootprints.some(fp => window[fp])) {
302
+ this._cachedBuilder.add("cdp", "true");
303
+ }
304
+
305
+ // 7. Bot Detection (Indication cachée)
306
+ if (nav.webdriver) this._cachedBuilder.add("bot", "true");
307
+ }
308
+
309
+ return this._cachedBuilder.toString();
310
+ },
311
+
312
+ /**
313
+ * Génère une signature de requête incluant le contexte.
314
+ * @param {object} payload
315
+ */
316
+ /**
317
+ * Génère une signature de requête incluant le contexte.
318
+ * @param {object} payload
319
+ */
320
+ generateRequestSignature(payload = {}) {
321
+ const deviceFp = this.getDeviceFingerprint();
322
+ const sortedPayload = Object.keys(payload)
323
+ .sort()
324
+ .map((k) => `${k}=${payload[k]}`)
325
+ .join("&");
326
+ const payloadHash = this._hasher(sortedPayload);
327
+ return `${deviceFp}|req:${payloadHash}`;
328
+ },
329
+
330
+ /**
331
+ * Génère une signature HMAC-SHA256 en utilisant l'API Web Crypto.
332
+ * @param {object} payload - Les données à signer.
333
+ * @param {string} secret - La clé secrète partagée.
334
+ * @returns {Promise<string>} La signature hexadécimale.
335
+ */
336
+ async generateClientSideSignature(payload, secret) {
337
+ const sortedPayload = Object.keys(payload).sort().map((k) => `${k}=${payload[k]}`).join("&");
338
+ const encoder = new TextEncoder();
339
+ const key = await window.crypto.subtle.importKey("raw", encoder.encode(secret), {
340
+ name: "HMAC",
341
+ hash: "SHA-256"
342
+ }, false, ["sign"]);
343
+ const signatureBuffer = await window.crypto.subtle.sign("HMAC", key, encoder.encode(sortedPayload));
344
+ const hashArray = Array.from(new Uint8Array(signatureBuffer));
345
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
346
+ },
347
+
348
+ /**
349
+ * @internal
350
+ * Resets the cached fingerprint builder. Used for testing purposes.
351
+ */
352
+ _resetCache() {
353
+ // Réinitialise le hasher à l'implémentation JS par défaut.
354
+ activeCyrb53 = jsCyrb53;
355
+ this._cachedBuilder = null;
356
+ },
357
+
358
+ /**
359
+ * Injecte des éléments interactifs fantômes invisibles pour piéger les bots (focus/hover).
360
+ */
361
+ injectPhantomTraps() {
362
+ if (typeof document === 'undefined') return;
363
+
364
+ // Création d'un élément interactif fantôme
365
+ const phantom = document.createElement('a');
366
+ phantom.href = '#';
367
+ // Nom trompeur aléatoire pour attirer les analyseurs automatiques de liens / formulaires
368
+ const phantomNames = ['sys-session-recovery', 'auth-token-refresh', 'debug-console-login', 'admin-portal-access', 'security-bypass-bypass', 'recovery-key-session', 'api-key-test', 'client-secrets-access'];
369
+ phantom.id = phantomNames[Math.floor(secureRandom() * phantomNames.length)] + '-' + genRandStr(6);
370
+ phantom.className = genRandStr(8);
371
+ phantom.tabIndex = 0; // Dans le flux naturel de tabulation
372
+ phantom.setAttribute('aria-hidden', 'true'); // Masqué pour les screen readers légitimes
373
+
374
+ // Style invisible mais interactif (1px x 1px, presque transparent)
375
+ phantom.style.position = 'fixed';
376
+ phantom.style.top = '1px';
377
+ phantom.style.left = '1px';
378
+ phantom.style.width = '1px';
379
+ phantom.style.height = '1px';
380
+ phantom.style.opacity = '0.001';
381
+ phantom.style.zIndex = '99999';
382
+ phantom.style.overflow = 'hidden';
383
+ phantom.style.pointerEvents = 'auto';
384
+
385
+ const triggerTrap = () => {
386
+ this.onHoneypotTrigger();
387
+ };
388
+
389
+ phantom.addEventListener('focus', triggerTrap, { passive: true });
390
+ phantom.addEventListener('mouseover', triggerTrap, { passive: true });
391
+
392
+ // Imbrication polymorphique du piège fantôme dans le corps du document
393
+ const nestingOptions = [
394
+ () => document.body.appendChild(phantom),
395
+ () => {
396
+ const wrapper = document.createElement(secureRandom() > 0.5 ? 'span' : 'div');
397
+ wrapper.className = genRandStr(8);
398
+ wrapper.style.position = 'absolute';
399
+ wrapper.style.width = '0';
400
+ wrapper.style.height = '0';
401
+ wrapper.style.overflow = 'hidden';
402
+ wrapper.appendChild(phantom);
403
+ document.body.appendChild(wrapper);
404
+ }
405
+ ];
406
+ nestingOptions[Math.floor(secureRandom() * nestingOptions.length)]();
407
+ },
408
+
409
+ /**
410
+ * Démarre le suivi des événements tactiles sur mobile/tablette.
411
+ */
412
+ startTouchEventTracker() {
413
+ if (this._touchTrackerAttached) return;
414
+ this._touchTrackerAttached = true;
415
+
416
+ const handleTouch = (e) => {
417
+ if (touchMovementsHistory.length >= TOUCH_HISTORY_MAX) {
418
+ touchMovementsHistory.shift();
419
+ }
420
+ const touch = e.touches[0] || e.changedTouches[0];
421
+ if (!touch) return;
422
+
423
+ const radiusX = touch.radiusX || 0;
424
+ const radiusY = touch.radiusY || 0;
425
+ const radius = (radiusX + radiusY) / 2;
426
+ const force = touch.force || touch.webkitForce || 0;
427
+
428
+ touchMovementsHistory.push({
429
+ x: touch.clientX,
430
+ y: touch.clientY,
431
+ t: performance.now(),
432
+ p: force,
433
+ r: radius,
434
+ num: e.touches.length
435
+ });
436
+ };
437
+
438
+ document.addEventListener('touchstart', handleTouch, { passive: true });
439
+ document.addEventListener('touchmove', handleTouch, { passive: true });
440
+ document.addEventListener('touchend', handleTouch, { passive: true });
441
+ },
442
+
443
+ /**
444
+ * Démarre le suivi de la régularité d'affichage (V-Sync/rAF) pour détecter les framebuffers logiciels sans V-Sync.
445
+ */
446
+ startRenderingTracker() {
447
+ if (this._renderingTrackerAttached) return;
448
+ this._renderingTrackerAttached = true;
449
+
450
+ if (typeof window === 'undefined' || !window.requestAnimationFrame) return;
451
+
452
+ const rAfTimestamps = [];
453
+ let lastTime = performance.now();
454
+ const maxSamples = 15;
455
+
456
+ const checkOffscreenAnom = () => {
457
+ try {
458
+ if ('OffscreenCanvas' in window && HTMLCanvasElement.prototype.transferControlToOffscreen) {
459
+ const nativeToString = Function.prototype.toString.call(HTMLCanvasElement.prototype.transferControlToOffscreen);
460
+ return !nativeToString.includes('[native code]');
461
+ }
462
+ } catch (e) {}
463
+ return false;
464
+ };
465
+
466
+ const loop = (time) => {
467
+ const delta = time - lastTime;
468
+ lastTime = time;
469
+ if (rAfTimestamps.length < maxSamples) {
470
+ if (rAfTimestamps.length > 0) { // Skip first delta
471
+ rAfTimestamps.push(delta);
472
+ }
473
+ window.requestAnimationFrame(loop);
474
+ } else {
475
+ const avg = rAfTimestamps.reduce((a, b) => a + b, 0) / rAfTimestamps.length;
476
+ const sqDiffs = rAfTimestamps.map(v => Math.pow(v - avg, 2));
477
+ const avgSqDiff = sqDiffs.reduce((a, b) => a + b, 0) / sqDiffs.length;
478
+
479
+ metrics.rendering = {
480
+ fps: Math.round((1000 / avg) * 100) / 100,
481
+ jitter: Math.round(Math.sqrt(avgSqDiff) * 100) / 100,
482
+ offscreenAnom: checkOffscreenAnom()
483
+ };
484
+ }
485
+ };
486
+ window.requestAnimationFrame(loop);
487
+ },
488
+
489
+ /**
490
+ * Initialise l'espace Proof-of-Space persistant dans l'IndexedDB locale.
491
+ */
492
+ async initializeSpace(seed, sizeMb) {
493
+ return new Promise((resolve, reject) => {
494
+ const request = indexedDB.open('pospace-db', 1);
495
+ request.onupgradeneeded = (e) => {
496
+ const db = e.target.result;
497
+ if (!db.objectStoreNames.contains('blocks')) {
498
+ db.createObjectStore('blocks');
499
+ }
500
+ };
501
+ request.onsuccess = async (e) => {
502
+ const db = e.target.result;
503
+ const tx = db.transaction('blocks', 'readwrite');
504
+ const store = tx.objectStore('blocks');
505
+
506
+ const maxBlocks = sizeMb * 1024;
507
+ const countReq = store.count();
508
+ countReq.onsuccess = async () => {
509
+ if (countReq.result < maxBlocks) {
510
+ for (let i = 0; i < maxBlocks; i++) {
511
+ const block = new Uint8Array(1024);
512
+ let h = 5381;
513
+ for (let j = 0; j < seed.length; j++) {
514
+ h = (h << 5) + h + seed.charCodeAt(j);
515
+ }
516
+ h = (h << 5) + h + i;
517
+ for (let k = 0; k < 1024; k++) {
518
+ h = Math.imul(h ^ k, 1597334677);
519
+ block[k] = h & 0xff;
520
+ }
521
+ store.put(block, i);
522
+ }
523
+ }
524
+ resolve();
525
+ };
526
+ };
527
+ request.onerror = () => reject(new Error("Failed to open pospace database"));
528
+ });
529
+ },
530
+
531
+ /**
532
+ * Lit un bloc spécifique de l'IndexedDB locale sous format hexadécimal.
533
+ */
534
+ async readSpaceBlock(blockIdx) {
535
+ return new Promise((resolve, reject) => {
536
+ const request = indexedDB.open('pospace-db', 1);
537
+ request.onsuccess = (e) => {
538
+ const db = e.target.result;
539
+ const tx = db.transaction('blocks', 'readonly');
540
+ const store = tx.objectStore('blocks');
541
+ const getReq = store.get(blockIdx);
542
+ getReq.onsuccess = () => {
543
+ const block = getReq.result;
544
+ if (block) {
545
+ const hex = Array.from(block).map(b => b.toString(16).padStart(2, '0')).join('');
546
+ resolve(hex);
547
+ } else {
548
+ reject(new Error("Block not found"));
549
+ }
550
+ };
551
+ getReq.onerror = () => reject(getReq.error);
552
+ };
553
+ request.onerror = () => reject(new Error("Failed to open pospace database"));
554
+ });
555
+ },
556
+
557
+ /**
558
+ * Résout le Proof-of-Space en combinant optionnellement le bloc du pair.
559
+ */
560
+ async solveSpaceChallenge(seed, queries, nonce, clientSecret, peerBlock = '') {
561
+ const blocks = [];
562
+ for (const idx of queries) {
563
+ const blockHex = await this.readSpaceBlock(idx);
564
+ blocks.push(blockHex);
565
+ }
566
+ let finalPayload = blocks.join('') + peerBlock + nonce + ":" + clientSecret;
567
+ const encoder = new TextEncoder();
568
+ const data = encoder.encode(finalPayload);
569
+ const hashBuffer = await window.crypto.subtle.digest('SHA-256', data);
570
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
571
+ return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
572
+ },
573
+
574
+ /**
575
+ * Démarre le suivi des mouvements de la souris pour calculer l'entropie.
576
+ * À appeler une fois sur la page.
577
+ */
578
+ startMouseEntropyTracker() {
579
+ // Utiliser un drapeau pour éviter d'attacher l'écouteur plusieurs fois
580
+ if (this._mouseTrackerAttached) return;
581
+ this._mouseTrackerAttached = true;
582
+
583
+ document.addEventListener('mousemove', (e) => {
584
+ // NOUVEAU: Capturer une série de points {x, y, t}
585
+ if (mouseMovementsHistory.length >= MOUSE_HISTORY_MAX) {
586
+ // Garder la taille de l'historique constante pour éviter une consommation mémoire excessive.
587
+ mouseMovementsHistory.shift();
588
+ }
589
+ mouseMovementsHistory.push({
590
+ x: e.clientX,
591
+ y: e.clientY,
592
+ t: performance.now()
593
+ });
594
+ }, {passive: true});
595
+ },
596
+
597
+ /**
598
+ * Démarre le suivi de la dynamique de frappe pour calculer le dwell time et le flight time (digraphie/trigraphie).
599
+ * À appeler une fois sur la page.
600
+ */
601
+ startKeystrokeDynamicsTracker() {
602
+ // S'assurer de ne pas attacher l'écouteur plusieurs fois
603
+ if (this._keystrokeTrackerAttached) return;
604
+ this._keystrokeTrackerAttached = true;
605
+
606
+ const activeKeys = new Map();
607
+ let lastKeyDownTime = 0;
608
+ let lastKeyName = '';
609
+
610
+ document.addEventListener('keydown', (e) => {
611
+ const now = performance.now();
612
+ const key = e.key;
613
+ const code = e.code;
614
+ if (!key && !code) return;
615
+
616
+ const keyIdentifier = code || key;
617
+
618
+ // Prevent key repeat triggering multiple events
619
+ if (activeKeys.has(keyIdentifier)) return;
620
+ activeKeys.set(keyIdentifier, now);
621
+
622
+ if (keystrokeTimestamps.length > 0) {
623
+ const lastTimestamp = keystrokeTimestamps[keystrokeTimestamps.length - 1];
624
+ const latency = now - lastTimestamp;
625
+ if (latency > 10 && latency < 2000) {
626
+ if (keystrokeLatencies.length >= KEYSTROKE_HISTORY_MAX) {
627
+ keystrokeLatencies.shift();
628
+ }
629
+ keystrokeLatencies.push(latency);
630
+ }
631
+ }
632
+ keystrokeTimestamps.push(now);
633
+
634
+ // Flight Time (KeyDown to KeyDown)
635
+ if (lastKeyDownTime > 0) {
636
+ const flightTime = now - lastKeyDownTime;
637
+ if (flightTime > 10 && flightTime < 2000) {
638
+ if (keystrokeFlightTimes.length >= KEYSTROKE_HISTORY_MAX) {
639
+ keystrokeFlightTimes.shift();
640
+ }
641
+ const digraph = lastKeyName ? this._hasher(lastKeyName + "_" + keyIdentifier).toString() : "unknown";
642
+ keystrokeFlightTimes.push({ digraph, time: flightTime });
643
+ }
644
+ }
645
+ lastKeyDownTime = now;
646
+ lastKeyName = keyIdentifier;
647
+ }, {passive: true});
648
+
649
+ document.addEventListener('keyup', (e) => {
650
+ const now = performance.now();
651
+ const key = e.key;
652
+ const code = e.code;
653
+ if (!key && !code) return;
654
+
655
+ const keyIdentifier = code || key;
656
+
657
+ if (activeKeys.has(keyIdentifier)) {
658
+ const pressTime = activeKeys.get(keyIdentifier);
659
+ const dwellTime = now - pressTime;
660
+ activeKeys.delete(keyIdentifier);
661
+
662
+ if (dwellTime > 5 && dwellTime < 1000) {
663
+ if (keystrokeDwellTimes.length >= KEYSTROKE_HISTORY_MAX) {
664
+ keystrokeDwellTimes.shift();
665
+ }
666
+ keystrokeDwellTimes.push(dwellTime);
667
+ }
668
+ }
669
+ }, {passive: true});
670
+ },
671
+
672
+ /**
673
+ * Starts tracking click events to analyze position variance.
674
+ * @private
675
+ */
676
+ startClickTracker() {
677
+ if (this._clickTrackerAttached) return;
678
+ this._clickTrackerAttached = true;
679
+
680
+ document.addEventListener('click', (e) => {
681
+ if (clicksHistory.length >= CLICKS_HISTORY_MAX) {
682
+ clicksHistory.shift();
683
+ }
684
+ // Generate a simple identifier for the target element
685
+ const target = e.target;
686
+ const targetId = target.id || target.name || target.tagName;
687
+
688
+ clicksHistory.push({
689
+ x: e.clientX,
690
+ y: e.clientY,
691
+ t: performance.now(),
692
+ targetId: this._hasher(targetId) // Hash the ID to keep it short and consistent
693
+ });
694
+ }, { passive: true });
695
+ },
696
+ /**
697
+ * Initialise ou réinitialise les honeypots côté client pour une détection immédiate.
698
+ * Les anciens écouteurs sont supprimés avant d'en ajouter de nouveaux.
699
+ * @param {string[]} honeypotFieldNames - Noms des champs de formulaire cachés.
700
+ */
701
+ initializeHoneypots(honeypotFieldNames) {
702
+ // 1. Nettoyer les anciens écouteurs
703
+ activeHoneypotListeners.forEach((listener, field) => {
704
+ field.removeEventListener('input', listener);
705
+ });
706
+ activeHoneypotListeners.clear();
707
+
708
+ // 2. Ajouter les nouveaux écouteurs sur le DOM classique
709
+ honeypotFieldNames.forEach(fieldName => {
710
+ const field = document.querySelector(`[name="${fieldName}"]`);
711
+ if (field) {
712
+ const listener = () => {
713
+ this.onHoneypotTrigger();
714
+ field.removeEventListener('input', listener);
715
+ };
716
+ field.addEventListener('input', listener);
717
+ activeHoneypotListeners.set(field, listener); // On stocke la référence
718
+ }
719
+ });
720
+
721
+ // 3. Générer des champs d'input pièges masqués dans un Shadow DOM fermé
722
+ if (typeof document !== 'undefined' && honeypotFieldNames.length > 0) {
723
+ const host = document.createElement('div');
724
+ host.setAttribute('aria-hidden', 'true');
725
+ host.style.position = 'absolute';
726
+ host.style.width = '0';
727
+ host.style.height = '0';
728
+ host.style.overflow = 'hidden';
729
+
730
+ const shadow = host.attachShadow({ mode: 'closed' });
731
+
732
+ // Aléatisation des classes, variables CSS et balises de structure
733
+ const wrapperClass = genRandStr(10);
734
+ const posStateVar = `--${genRandStr(8)}`;
735
+ const offValVar = `--${genRandStr(8)}`;
736
+ const visStateVar = `--${genRandStr(8)}`;
737
+ const scaleValVar = `--${genRandStr(8)}`;
738
+
739
+ const style = document.createElement('style');
740
+ style.textContent = `
741
+ :host {
742
+ ${posStateVar}: absolute;
743
+ ${offValVar}: -9999px;
744
+ ${visStateVar}: hidden;
745
+ ${scaleValVar}: 0;
746
+ }
747
+ .${wrapperClass} {
748
+ position: var(${posStateVar});
749
+ left: var(${offValVar});
750
+ top: var(${offValVar});
751
+ visibility: var(${visStateVar});
752
+ transform: scale(var(${scaleValVar}));
753
+ }
754
+ `;
755
+ shadow.appendChild(style);
756
+
757
+ const wrapperTags = ['div', 'section', 'p', 'span', 'form', 'main'];
758
+ const selectedWrapperTag = wrapperTags[Math.floor(secureRandom() * wrapperTags.length)];
759
+ const wrapper = document.createElement(selectedWrapperTag);
760
+ wrapper.className = wrapperClass;
761
+
762
+ honeypotFieldNames.forEach(fieldName => {
763
+ const label = document.createElement('label');
764
+ label.textContent = fieldName;
765
+ const input = document.createElement('input');
766
+ input.type = 'text';
767
+ input.name = fieldName;
768
+ input.tabIndex = -1;
769
+ input.className = genRandStr(6);
770
+ input.id = genRandStr(8);
771
+ input.autocomplete = 'off';
772
+
773
+ const trigger = () => {
774
+ this.onHoneypotTrigger();
775
+ };
776
+
777
+ input.addEventListener('input', trigger, { passive: true });
778
+ input.addEventListener('change', trigger, { passive: true });
779
+ input.addEventListener('focus', trigger, { passive: true });
780
+
781
+ // Imbrication polymorphique du label et de l'input
782
+ const nestingType = Math.floor(secureRandom() * 3);
783
+ if (nestingType === 1) {
784
+ label.appendChild(input);
785
+ wrapper.appendChild(label);
786
+ } else if (nestingType === 2) {
787
+ const innerContainer = document.createElement(secureRandom() > 0.5 ? 'span' : 'div');
788
+ innerContainer.className = genRandStr(5);
789
+ innerContainer.appendChild(label);
790
+ innerContainer.appendChild(input);
791
+ wrapper.appendChild(innerContainer);
792
+ } else {
793
+ wrapper.appendChild(label);
794
+ wrapper.appendChild(input);
795
+ }
796
+ });
797
+
798
+ shadow.appendChild(wrapper);
799
+ document.body.appendChild(host);
800
+ }
801
+ },
802
+ /**
803
+ * Sollicite silencieusement l'attestation matérielle FIDO2 (WebAuthn)
804
+ * pour ancrer l'identité physique de l'appareil via TPM / Secure Enclave.
805
+ * @returns {Promise<object|null>}
806
+ */
807
+ async getWebAuthnAnchor() {
808
+ if (typeof window === 'undefined' || !window.PublicKeyCredential) return null;
809
+ try {
810
+ const isPlatformAvailable = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
811
+ if (!isPlatformAvailable) return null;
812
+
813
+ const storedCredIdBase64 = localStorage.getItem('fp_webauthn_cred_id');
814
+ const challenge = new Uint8Array([109, 101, 116, 114, 105, 99, 115, 95, 97, 110, 99, 104, 111, 114, 95, 115, 101, 99, 117, 114, 101]); // Static stable challenge
815
+
816
+ if (storedCredIdBase64) {
817
+ // Tentative d'assertion silencieuse (Authentification)
818
+ const credentialId = Uint8Array.from(atob(storedCredIdBase64), c => c.charCodeAt(0));
819
+ const assertion = await navigator.credentials.get({
820
+ publicKey: {
821
+ challenge,
822
+ allowCredentials: [{
823
+ id: credentialId,
824
+ type: 'public-key'
825
+ }],
826
+ userVerification: 'discouraged',
827
+ timeout: 1000
828
+ }
829
+ });
830
+ if (assertion) {
831
+ return {
832
+ type: 'assertion',
833
+ credentialId: storedCredIdBase64,
834
+ signature: btoa(String.fromCharCode(...new Uint8Array(assertion.response.signature))),
835
+ authenticatorData: btoa(String.fromCharCode(...new Uint8Array(assertion.response.authenticatorData))),
836
+ clientDataJSON: btoa(String.fromCharCode(...new Uint8Array(assertion.response.clientDataJSON)))
837
+ };
838
+ }
839
+ } else {
840
+ // Création silencieuse (Enregistrement initial)
841
+ const options = {
842
+ publicKey: {
843
+ challenge,
844
+ rp: { name: window.location.hostname, id: window.location.hostname },
845
+ user: {
846
+ id: new Uint8Array([102, 112, 105, 100]),
847
+ name: 'silent-device-anchor',
848
+ displayName: 'Hardware Device Anchor'
849
+ },
850
+ pubKeyCredParams: [
851
+ { type: 'public-key', alg: -7 }, // ES256 (P-256) - Secure Enclave / TPM / Android Keystore
852
+ { type: 'public-key', alg: -257 } // RS256 - Windows Hello TPM
853
+ ],
854
+ authenticatorSelection: {
855
+ authenticatorAttachment: 'platform',
856
+ userVerification: 'discouraged',
857
+ residentKey: 'preferred'
858
+ },
859
+ timeout: 1500,
860
+ attestation: 'indirect'
861
+ }
862
+ };
863
+ const credential = await navigator.credentials.create(options);
864
+ if (credential) {
865
+ const credIdBase64 = btoa(String.fromCharCode(...new Uint8Array(credential.rawId)));
866
+ localStorage.setItem('fp_webauthn_cred_id', credIdBase64);
867
+ const publicKeyDer = credential.response.getPublicKey ? credential.response.getPublicKey() : null;
868
+ return {
869
+ type: 'registration',
870
+ credentialId: credIdBase64,
871
+ publicKey: publicKeyDer ? btoa(String.fromCharCode(...new Uint8Array(publicKeyDer))) : null,
872
+ attestationObject: btoa(String.fromCharCode(...new Uint8Array(credential.response.getAttestationObject()))),
873
+ clientDataJSON: btoa(String.fromCharCode(...new Uint8Array(credential.response.clientDataJSON)))
874
+ };
875
+ }
876
+ }
877
+ } catch (e) {
878
+ // Ignore et bypass silencieusement pour garder l'invisibilité en cas de non-support
879
+ console.log('[WebAuthn-Anchor] Silent attestation bypassed:', e.message);
880
+ }
881
+ return null;
882
+ },
883
+
884
+ /**
885
+ * Récupère les métriques comportementales collectées.
886
+ * À appeler avant d'envoyer une requête sensible.
887
+ * @returns {ClientBehaviorMetrics}
888
+ */
889
+ getClientBehaviorMetrics() {
890
+ // Add history length as a behavioral signal.
891
+ metrics.historyLength = window.history.length;
892
+
893
+ // Ajoute un timestamp au moment de la collecte pour la détection de rejeu.
894
+ metrics.clicksHistory = clicksHistory;
895
+ metrics.clientTimestamp = Date.now();
896
+
897
+ metrics.touchMovementsHistory = touchMovementsHistory;
898
+ // NOUVEAU: Inclure l'historique des mouvements de la souris pour une analyse côté serveur.
899
+ metrics.mouseMovementsHistory = mouseMovementsHistory;
900
+
901
+ // NOUVEAU: Keystroke dynamics metrics (dwell and flight times)
902
+ metrics.keystrokeDwellTimes = keystrokeDwellTimes;
903
+ metrics.keystrokeFlightTimes = keystrokeFlightTimes;
904
+
905
+ // Calcule la latence moyenne des frappes
906
+ if (keystrokeLatencies.length > 0) {
907
+ const sum = keystrokeLatencies.reduce((a, b) => a + b, 0);
908
+ metrics.keystrokeLatency = sum / keystrokeLatencies.length;
909
+ } else {
910
+ metrics.keystrokeLatency = 0;
911
+ }
912
+ return metrics;
913
+ },
914
+
915
+ /**
916
+ * Enrichit une requête fetch avec les en-têtes de fingerprinting et de comportement.
917
+ * @param {RequestInfo} resource
918
+ * @param {RequestInit} [options]
919
+ * @returns {Promise<Response>}
920
+ */
921
+ async protectedFetch(resource, options = {}) {
922
+ const fp = this.getDeviceFingerprint();
923
+ const rawBehavior = this.getClientBehaviorMetrics();
924
+ const zkpProof = await this.generateZkpProof(fp); // Generate ZKP proof
925
+ const behavior = await signMetrics(rawBehavior);
926
+
927
+ const headers = new Headers(options.headers || {});
928
+ headers.set('X-ZKP-Proof', zkpProof); // Add ZKP proof to headers
929
+ headers.set('X-Device-Fingerprint', fp);
930
+ headers.set('X-Behavior-Metrics', JSON.stringify(behavior));
931
+
932
+ options.headers = headers;
933
+ return fetch(resource, options);
934
+ },
935
+
936
+ // --- Système d'interception de Fetch robuste et anti-conflit ---
937
+
938
+ _isFetchPatched: false,
939
+ _interceptorChain: [],
940
+ // On stocke la fonction fetch originale et on la lie à son contexte (window)
941
+ // pour éviter les erreurs "Illegal invocation" si une autre lib la modifie.
942
+ _originalFetch: (typeof window !== 'undefined') ? window.fetch.bind(window) : null,
943
+
944
+ /**
945
+ * Adds an interceptor function to the `fetch` chain.
946
+ * Chaque intercepteur reçoit `resource`, `options`, et une fonction `next`.
947
+ * Il DOIT appeler `next(resource, options)` pour continuer la chaîne.
948
+ * @param {function(RequestInfo, RequestInit, function): Promise<Response>} interceptor
949
+ */
950
+ addFetchInterceptor(interceptor) {
951
+ if (!this._isFetchPatched) {
952
+ this.patchGlobalFetch();
953
+ }
954
+ this._interceptorChain.push(interceptor);
955
+ },
956
+
957
+ patchGlobalFetch() {
958
+ if (this._isFetchPatched || !this._originalFetch) return;
959
+
960
+ this._isFetchPatched = true;
961
+ window.fetch = (resource, options) => {
962
+ // Le "dispatcher" qui exécute la chaîne.
963
+ const dispatch = (index, res, opts) => {
964
+ if (index >= this._interceptorChain.length) {
965
+ // Fin de la chaîne, on appelle le fetch original.
966
+ return this._originalFetch(res, opts);
967
+ }
968
+ const nextInterceptor = this._interceptorChain[index];
969
+ // Appelle l'intercepteur actuel en lui passant la fonction pour appeler le suivant.
970
+ return nextInterceptor(res, opts, (nextRes, nextOpts) => dispatch(index + 1, nextRes, nextOpts));
971
+ };
972
+ return dispatch(0, resource, options || {});
973
+ };
974
+ },
975
+
976
+ /**
977
+ * La fonction qui est appelée lorsqu'un honeypot est déclenché.
978
+ * @private
979
+ */
980
+ onHoneypotTrigger() {
981
+ metrics.honeypotInteraction = true;
982
+ // Émettre un événement pour que l'application puisse réagir.
983
+ this._dispatchEvent('honeypotTriggered');
984
+ },
985
+
986
+ /**
987
+ * Initialise l'intercepteur de fingerprinting.
988
+ * Il s'ajoute à la chaîne d'interception sans écraser les autres.
989
+ * @param {string[]} [targetDomains] - Optionnel. Liste de domaines à protéger.
990
+ * Si non fourni, protège les requêtes de même origine.
991
+ */
992
+ initializeFetch(targetDomains = []) {
993
+ const fingerprintInterceptor = async (resource, options, next) => {
994
+ const requestUrl = (resource instanceof Request) ? resource.url : String(resource);
995
+ let shouldProtect = false;
996
+
997
+ try {
998
+ const url = new URL(requestUrl, window.location.origin);
999
+ // Protéger si la liste de domaines est vide ET que la requête est de même origine,
1000
+ // OU si le domaine de la requête est dans la liste fournie.
1001
+ shouldProtect = (targetDomains.length === 0 && url.origin === window.location.origin) ||
1002
+ (targetDomains.length > 0 && targetDomains.includes(url.hostname));
1003
+ } catch (e) {
1004
+ // Si l'URL est relative (ex: '/api/data'), new URL() ne lèvera pas d'erreur.
1005
+ // Ce bloc est une sécurité pour les cas où l'URL serait malformée.
1006
+ // On protège par défaut si aucune liste de domaines n'est spécifiée.
1007
+ shouldProtect = targetDomains.length === 0;
1008
+ }
1009
+
1010
+ if (shouldProtect) {
1011
+ const fp = this.getDeviceFingerprint();
1012
+ const rawBehavior = this.getClientBehaviorMetrics();
1013
+ const behavior = await signMetrics(rawBehavior);
1014
+ const headers = new Headers(options.headers || {});
1015
+ headers.set('X-Device-Fingerprint', fp);
1016
+ headers.set('X-Behavior-Metrics', JSON.stringify(behavior));
1017
+ options.headers = headers;
1018
+ }
1019
+
1020
+ // Passe la main à l'intercepteur suivant dans la chaîne.
1021
+ return next(resource, options);
1022
+ };
1023
+
1024
+ this.addFetchInterceptor(fingerprintInterceptor);
1025
+ }, // <-- VIRGULE AJOUTÉE ICI
1026
+
1027
+ /**
1028
+ * Injects visually hidden "honeypot" links into the DOM to trap bots.
1029
+ * @param {string[]} urls - An array of trap URLs to inject.
1030
+ * @private
1031
+ */
1032
+ injectTrapLinks(urls) {
1033
+ if (!urls || urls.length === 0 || typeof document === 'undefined') {
1034
+ return;
1035
+ }
1036
+
1037
+ const host = document.createElement('div');
1038
+ host.setAttribute('aria-hidden', 'true');
1039
+ host.style.position = 'absolute';
1040
+ host.style.width = '0';
1041
+ host.style.height = '0';
1042
+ host.style.overflow = 'hidden';
1043
+
1044
+ const shadow = host.attachShadow({ mode: 'closed' });
1045
+
1046
+ // Aléatisation des classes, variables CSS et balises de structure
1047
+ const wrapperClass = genRandStr(10);
1048
+ const layoutPosVar = `--${genRandStr(8)}`;
1049
+ const offsetValVar = `--${genRandStr(8)}`;
1050
+ const visibilityStateVar = `--${genRandStr(8)}`;
1051
+ const scaleFactorVar = `--${genRandStr(8)}`;
1052
+ const ptrEventsVar = `--${genRandStr(8)}`;
1053
+ const linkColorClass = genRandStr(6);
1054
+
1055
+ const style = document.createElement('style');
1056
+ style.textContent = `
1057
+ :host {
1058
+ ${layoutPosVar}: absolute;
1059
+ ${offsetValVar}: -9999px;
1060
+ ${visibilityStateVar}: hidden;
1061
+ ${scaleFactorVar}: 0;
1062
+ ${ptrEventsVar}: none;
1063
+ }
1064
+ .${wrapperClass} {
1065
+ position: var(${layoutPosVar});
1066
+ left: var(${offsetValVar});
1067
+ top: var(${offsetValVar});
1068
+ visibility: var(${visibilityStateVar});
1069
+ transform: scale(var(${scaleFactorVar}));
1070
+ pointer-events: var(${ptrEventsVar});
1071
+ }
1072
+ .${linkColorClass} {
1073
+ color: transparent;
1074
+ text-decoration: none;
1075
+ }
1076
+ `;
1077
+ shadow.appendChild(style);
1078
+
1079
+ const wrapperTags = ['div', 'section', 'p', 'span', 'nav', 'aside'];
1080
+ const selectedWrapperTag = wrapperTags[Math.floor(secureRandom() * wrapperTags.length)];
1081
+ const wrapper = document.createElement(selectedWrapperTag);
1082
+ wrapper.className = wrapperClass;
1083
+
1084
+ urls.forEach((url, i) => {
1085
+ const link = document.createElement('a');
1086
+ link.href = url;
1087
+ link.rel = 'nofollow';
1088
+ link.tabIndex = -1;
1089
+ link.className = linkColorClass;
1090
+ link.id = genRandStr(8);
1091
+
1092
+ // Structure interne polymorphique du lien
1093
+ const contentNestingType = Math.floor(secureRandom() * 3);
1094
+ if (contentNestingType === 1) {
1095
+ const span = document.createElement('span');
1096
+ span.className = genRandStr(5);
1097
+ span.innerHTML = `&gt; ${i + 1}`;
1098
+ link.appendChild(span);
1099
+ } else if (contentNestingType === 2) {
1100
+ const b = document.createElement('b');
1101
+ b.className = genRandStr(5);
1102
+ b.innerHTML = `&gt; ${i + 1}`;
1103
+ link.appendChild(b);
1104
+ } else {
1105
+ link.innerHTML = `<span>&gt; ${i + 1}</span>`;
1106
+ }
1107
+
1108
+ const trigger = () => {
1109
+ this.onHoneypotTrigger();
1110
+ };
1111
+ link.addEventListener('click', trigger, { passive: true });
1112
+ link.addEventListener('focus', trigger, { passive: true });
1113
+ link.addEventListener('mouseover', trigger, { passive: true });
1114
+
1115
+ // Imbrication du lien de manière polymorphique
1116
+ if (secureRandom() > 0.5) {
1117
+ const itemContainer = document.createElement('span');
1118
+ itemContainer.className = genRandStr(5);
1119
+ itemContainer.appendChild(link);
1120
+ wrapper.appendChild(itemContainer);
1121
+ } else {
1122
+ wrapper.appendChild(link);
1123
+ }
1124
+ });
1125
+
1126
+ shadow.appendChild(wrapper);
1127
+ document.body.appendChild(host);
1128
+ },
1129
+ /**
1130
+ * Intercepte une réponse de challenge JSON, le résout, et réessaie la requête.
1131
+ * @param {Response} response - La réponse initiale (potentiellement 429).
1132
+ * @param {RequestInfo} resource - La ressource de la requête originale.
1133
+ * @param {RequestInit} options - Les options de la requête originale.
1134
+ * @returns {Promise<Response>} - La réponse de la requête réessayée.
1135
+ * @private
1136
+ */
1137
+ async solveChallengeAndRetry(response, resource, options) {
1138
+ if (response.status !== 404 || !response.headers.get('content-type')?.includes('application/json') || response.bodyUsed) {
1139
+ return response;
1140
+ }
1141
+
1142
+ try {
1143
+ const challengeData = await response.json();
1144
+ if (!challengeData.challenge || !challengeData.challenge.type) {
1145
+ return response; // Pas un challenge JSON valide
1146
+ }
1147
+
1148
+ console.log(`[Fingerprint] Received a '${challengeData.challenge.type}' challenge. Solving...`);
1149
+ this._dispatchEvent('challengeReceived', { challenge: challengeData.challenge });
1150
+
1151
+ // L'empreinte de l'appareil qui résout le challenge est cruciale.
1152
+ const solverFp = this.getDeviceFingerprint();
1153
+ const solutionWrapper = await solveChallenge(challengeData.challenge, solverFp);
1154
+ console.log('[Fingerprint] Challenge solved. Retrying original request.');
1155
+
1156
+ this._dispatchEvent('challengeSolved', { solution: solutionWrapper.rawSolution });
1157
+ // Ajouter la solution aux paramètres de la requête pour le nouvel essai
1158
+ const url = new URL((resource instanceof Request) ? resource.url : String(resource), window.location.origin);
1159
+ // La logique de formatage est maintenant cachée dans la classe ChallengeSolution.
1160
+ solutionWrapper.applyToUrl(url);
1161
+
1162
+ // On ajoute l'empreinte du solveur à la requête de réessai.
1163
+ url.searchParams.set('pow_fp', solverFp);
1164
+
1165
+ // On utilise la chaîne d'intercepteurs pour la requête réessayée,
1166
+ // ce qui garantit que le fetch original est appelé avec le bon contexte.
1167
+ // Cela évite de réintroduire l'erreur "Illegal invocation".
1168
+ return window.fetch(url.toString(), options);
1169
+ } catch (e) {
1170
+ console.error('[Fingerprint] Failed to solve or retry challenge:', e);
1171
+ return response; // Retourne la réponse 429 originale en cas d'échec
1172
+ }
1173
+ }, // <-- VIRGULE AJOUTÉE ICI
1174
+
1175
+ /**
1176
+ * Initialise toutes les protections côté client en une seule fois.
1177
+ * Tente également de charger le module WASM si `wasmPath` est fourni.
1178
+ * C'est la méthode d'initialisation recommandée.
1179
+ * @param {ClientConfig} [config={}] - L'objet de configuration.
1180
+ */
1181
+ initializeClient(config = {}) {
1182
+ const {
1183
+ mouse = true,
1184
+ keystrokes = true,
1185
+ clicks = true, // Add new option
1186
+ touches = true, // Nouveau paramètre tactiles
1187
+ rendering = true,
1188
+ phantomTraps = true, // NOUVEAU
1189
+ honeypots = [],
1190
+ trapUrls = [], // Nouveau paramètre pour les URL pièges
1191
+ wasmPath, // Nouveau paramètre
1192
+ workerPath, // NOUVEAU
1193
+ fetch: fetchConfig = {}
1194
+ } = config;
1195
+
1196
+ negotiateSessionKey();
1197
+ // Tentative de chargement du WASM si le chemin est fourni
1198
+ if (wasmPath) {
1199
+ this.initializeWasm(wasmPath);
1200
+ }
1201
+
1202
+ if (mouse) {
1203
+ this.startMouseEntropyTracker();
1204
+ }
1205
+ if (workerPath) {
1206
+ this.workerPath = workerPath;
1207
+ }
1208
+ if (keystrokes) {
1209
+ this.startKeystrokeDynamicsTracker();
1210
+ }
1211
+ if (clicks) {
1212
+ this.startClickTracker();
1213
+ }
1214
+ if (touches) {
1215
+ this.startTouchEventTracker();
1216
+ }
1217
+ if (rendering) {
1218
+ this.startRenderingTracker();
1219
+ }
1220
+ if (phantomTraps) {
1221
+ this.injectPhantomTraps();
1222
+ }
1223
+ if (honeypots.length > 0) {
1224
+ this.initializeHoneypots(honeypots);
1225
+ }
1226
+
1227
+ // Injection dynamique des liens pièges au démarrage
1228
+ if (trapUrls.length > 0) {
1229
+ this.injectTrapLinks(trapUrls);
1230
+ }
1231
+ // On active l'interception si `fetch` est configuré, même avec un objet vide.
1232
+ if (config.fetch) {
1233
+ this.initializeFetch(fetchConfig.targetDomains);
1234
+
1235
+ // Ajoute l'intercepteur pour la résolution de challenge
1236
+ if (fetchConfig.handleChallenges !== false) {
1237
+ this.addFetchInterceptor(async (resource, options, next) => {
1238
+ const originalResponse = await next(resource, options);
1239
+ // On clone la réponse pour que la lecture du corps par solveChallengeAndRetry ne la consomme pas pour l'appelant original.
1240
+ return this.solveChallengeAndRetry(originalResponse.clone(), resource, options);
1241
+ });
1242
+ }
1243
+ }
1244
+ },
1245
+
1246
+ /**
1247
+ * Tente de charger et d'initialiser le module WebAssembly pour un hachage plus rapide.
1248
+ * Si le chargement échoue, il se rabat silencieusement sur l'implémentation JS.
1249
+ * @param {string} wasmPath - Le chemin vers le script de chargement du module WASM (ex: '/fp.js').
1250
+ */
1251
+ async initializeWasm(wasmPath) {
1252
+ try {
1253
+ // Direct standalone polymorphic WebAssembly loading
1254
+ if (wasmPath.endsWith('.wasm')) {
1255
+ let instance;
1256
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
1257
+ try {
1258
+ const response = await fetch(wasmPath);
1259
+ const result = await WebAssembly.instantiateStreaming(response, {});
1260
+ instance = result.instance;
1261
+ } catch (streamingError) {
1262
+ console.warn('[Fingerprint] WebAssembly.instantiateStreaming failed, falling back to compile:', streamingError);
1263
+ }
1264
+ }
1265
+ if (!instance) {
1266
+ const response = await fetch(wasmPath);
1267
+ const arrayBuffer = await response.arrayBuffer();
1268
+ const module = await WebAssembly.compile(arrayBuffer);
1269
+ instance = await WebAssembly.instantiate(module, {});
1270
+ }
1271
+ const exports = instance.exports;
1272
+ const memory = exports.memory;
1273
+ activeCyrb53 = (str) => {
1274
+ const encoder = new TextEncoder();
1275
+ const bytes = encoder.encode(str);
1276
+ const view = new Uint8Array(memory.buffer, 0, bytes.length);
1277
+ view.set(bytes);
1278
+ return exports.hash(0, bytes.length);
1279
+ };
1280
+ console.log('[Fingerprint] Standalone polymorphic WASM loaded successfully. Using fast dynamic hashing.');
1281
+ if (this._cachedBuilder) {
1282
+ this._cachedBuilder.addRaw('wasm', 'true');
1283
+ }
1284
+ return;
1285
+ }
1286
+ // 1. Injecter le script qui charge le module WASM
1287
+ const script = document.createElement('script');
1288
+ script.src = wasmPath;
1289
+ await new Promise((resolve, reject) => {
1290
+ script.onload = resolve;
1291
+ script.onerror = reject;
1292
+ document.head.appendChild(script);
1293
+ });
1294
+
1295
+ // 2. Attendre que la fonction globale `createFingerprintModule` soit disponible
1296
+ if (typeof window.createFingerprintModule !== 'function') {
1297
+ throw new Error('WASM loader script did not expose createFingerprintModule.');
1298
+ }
1299
+
1300
+ // 3. Initialiser le module
1301
+ const wasmUrl = wasmPath.replace(/\.js$/, '.wasm');
1302
+ const wasmModule = await window.createFingerprintModule({
1303
+ instantiateWasm: (imports, successCallback) => {
1304
+ (async () => {
1305
+ try {
1306
+ const cached = await getCachedWasm(wasmUrl);
1307
+ if (cached) {
1308
+ let instance;
1309
+ if (cached instanceof WebAssembly.Module) {
1310
+ instance = await WebAssembly.instantiate(cached, imports);
1311
+ } else {
1312
+ const result = await WebAssembly.instantiate(cached, imports);
1313
+ instance = result.instance;
1314
+ }
1315
+ successCallback(instance, cached);
1316
+ return;
1317
+ }
1318
+
1319
+ const response = await fetch(wasmUrl);
1320
+ const arrayBuffer = await response.arrayBuffer();
1321
+
1322
+ let cachedData = arrayBuffer;
1323
+ let isModuleCached = false;
1324
+ try {
1325
+ const compiledModule = await WebAssembly.compile(arrayBuffer);
1326
+ const success = await cacheWasm(wasmUrl, compiledModule);
1327
+ if (success) {
1328
+ cachedData = compiledModule;
1329
+ isModuleCached = true;
1330
+ }
1331
+ } catch (e) {
1332
+ // Fallback if browser doesn't allow structured cloning of Compiled Modules
1333
+ }
1334
+
1335
+ if (!isModuleCached) {
1336
+ await cacheWasm(wasmUrl, arrayBuffer);
1337
+ }
1338
+
1339
+ let instance;
1340
+ if (cachedData instanceof WebAssembly.Module) {
1341
+ instance = await WebAssembly.instantiate(cachedData, imports);
1342
+ } else {
1343
+ const result = await WebAssembly.instantiate(arrayBuffer, imports);
1344
+ instance = result.instance;
1345
+ }
1346
+ successCallback(instance, cachedData);
1347
+ } catch (err) {
1348
+ console.warn('[Fingerprint] Custom WASM instantiation failed, falling back to default Emscripten loader:', err);
1349
+ successCallback(null);
1350
+ }
1351
+ })();
1352
+ return {}; // Async instantiation indicator for Emscripten
1353
+ }
1354
+ });
1355
+ if (typeof wasmModule._hash_string !== 'function') {
1356
+ throw new Error('WASM module did not export _hash_string.');
1357
+ }
1358
+ window.wasmModule = wasmModule;
1359
+ ClientLibrary.wasmModule = wasmModule;
1360
+
1361
+ // Pooling de mémoire statique : pré-allocation d'un buffer réutilisable de 4 Ko
1362
+ // Évite d'allouer/libérer de la mémoire sur le tas Emscripten lors des frappes clavier/mouvements souris rapides
1363
+ const staticBufferSize = 4096;
1364
+ const staticBufferPtr = wasmModule._malloc(staticBufferSize);
1365
+ const encoder = new TextEncoder();
1366
+
1367
+ // 4. Remplacer la fonction de hachage par la version WASM optimisée via le buffer statique
1368
+ activeCyrb53 = (str) => {
1369
+ const bytes = encoder.encode(str);
1370
+ if (bytes.length < staticBufferSize) {
1371
+ wasmModule.HEAPU8.set(bytes, staticBufferPtr);
1372
+ wasmModule.HEAPU8[staticBufferPtr + bytes.length] = 0; // null-terminator
1373
+ return wasmModule._hash_string(staticBufferPtr);
1374
+ }
1375
+ // Fallback dynamique sécurisé si la chaîne dépasse la taille du buffer statique
1376
+ return wasmModule._hash_string(str);
1377
+ };
1378
+
1379
+ console.log('[Fingerprint] WASM module loaded successfully. Using fast hashing.');
1380
+ // NOUVEAU: Ajoute un indicateur à l'empreinte pour que le serveur sache que le WASM est actif.
1381
+ if (this._cachedBuilder) {
1382
+ this._cachedBuilder.addRaw('wasm', 'true');
1383
+ }
1384
+ } catch (error) {
1385
+ console.warn('[Fingerprint] WASM module failed to load. Falling back to JS implementation. Error:', error);
1386
+ }
1387
+ }
1388
+ };
1389
+
1390
+ /**
1391
+ * @typedef {object} ClientBehaviorMetrics
1392
+ * @property {number} mouseEntropy - Entropie des mouvements de la souris.
1393
+ * @property {Array<{x: number, y: number, t: number}>} mouseMovementsHistory - Historique des points de la souris.
1394
+ * @property {number} keystrokeLatency - Latence moyenne entre les frappes.
1395
+ * @property {boolean} honeypotInteraction - Vrai si un honeypot a été touché.
1396
+ * @property {Array<{x: number, y: number, t: number, targetId: string}>} clicksHistory - Historique des clics.
1397
+ * @property {Array<{x: number, y: number, t: number, p: number, r: number, num: number}>} touchMovementsHistory - Historique des glissements tactiles.
1398
+ * @property {number} historyLength - La longueur de l'historique de session du navigateur (`window.history.length`).
1399
+ * @property {number} clientTimestamp - Timestamp (Date.now()) de la collecte des métriques.
1400
+ * @property {string[]} [trapUrls] - URLs pièges à injecter dynamiquement.
1401
+ */
1402
+ /** @type {ClientBehaviorMetrics} */
1403
+ const metrics = {
1404
+ mouseEntropy: 0, // Conservé pour la compatibilité, mais l'analyse se fait maintenant sur l'historique
1405
+ mouseMovementsHistory: [],
1406
+ touchMovementsHistory: [],
1407
+ clicksHistory: [],
1408
+ keystrokeLatency: 0,
1409
+ honeypotInteraction: false,
1410
+ historyLength: 0,
1411
+ clientTimestamp: 0,
1412
+ rendering: { fps: 0, jitter: 0, offscreenAnom: false },
1413
+ };
1414
+
1415
+ let lastMousePos = { x: 0, y: 0 };
1416
+ let mouseMovementsHistory = []; // NOUVEAU: Historique des points de la souris
1417
+ let touchMovementsHistory = []; // NOUVEAU: Historique des gestes tactiles
1418
+ const TOUCH_HISTORY_MAX = 100;
1419
+ const MOUSE_HISTORY_MAX = 100; // Limite le nombre de points stockés
1420
+ let clicksHistory = [];
1421
+ const CLICKS_HISTORY_MAX = 50;
1422
+ let activeHoneypotListeners = new Map(); // Garde une trace des écouteurs actifs
1423
+ let keystrokeTimestamps = [];
1424
+ let keystrokeLatencies = []; // NOUVEAU: Tableau dédié pour les latences
1425
+ let keystrokeDwellTimes = [];
1426
+ let keystrokeFlightTimes = [];
1427
+ const KEYSTROKE_HISTORY_MAX = 20; // On garde l'historique des 20 dernières frappes
1428
+
1429
+
1430
+
1431
+ // Exporter les fonctions individuellement pour la compatibilité ascendante
1432
+ export const getDeviceFingerprint = ClientLibrary.getDeviceFingerprint.bind(ClientLibrary);
1433
+ export const generateRequestSignature = ClientLibrary.generateRequestSignature.bind(ClientLibrary);
1434
+ export const generateClientSideSignature = ClientLibrary.generateClientSideSignature.bind(ClientLibrary);
1435
+ export const _resetCache = ClientLibrary._resetCache.bind(ClientLibrary);
1436
+ export const startMouseEntropyTracker = ClientLibrary.startMouseEntropyTracker.bind(ClientLibrary);
1437
+ export const startKeystrokeDynamicsTracker = ClientLibrary.startKeystrokeDynamicsTracker.bind(ClientLibrary);
1438
+ export const startClickTracker = ClientLibrary.startClickTracker.bind(ClientLibrary);
1439
+ export const startTouchEventTracker = ClientLibrary.startTouchEventTracker.bind(ClientLibrary);
1440
+ export const startRenderingTracker = ClientLibrary.startRenderingTracker.bind(ClientLibrary);
1441
+ export const initializeHoneypots = ClientLibrary.initializeHoneypots.bind(ClientLibrary);
1442
+ export const getClientBehaviorMetrics = ClientLibrary.getClientBehaviorMetrics.bind(ClientLibrary);
1443
+ export const protectedFetch = ClientLibrary.protectedFetch.bind(ClientLibrary);
1444
+ export const addFetchInterceptor = ClientLibrary.addFetchInterceptor.bind(ClientLibrary);
1445
+ export const patchGlobalFetch = ClientLibrary.patchGlobalFetch.bind(ClientLibrary);
1446
+ export const initializeFetch = ClientLibrary.initializeFetch.bind(ClientLibrary);
1447
+ export const initializeClient = ClientLibrary.initializeClient.bind(ClientLibrary);
1448
+ export const initializeWasm = ClientLibrary.initializeWasm.bind(ClientLibrary);
1449
+ export const injectTrapLinks = ClientLibrary.injectTrapLinks.bind(ClientLibrary);
1450
+ export const injectPhantomTraps = ClientLibrary.injectPhantomTraps.bind(ClientLibrary);
1451
+ export const solveChallengeAndRetry = ClientLibrary.solveChallengeAndRetry.bind(ClientLibrary);
1452
+ export const generateZkpProof = ClientLibrary.generateZkpProof.bind(ClientLibrary);
1453
+ export const initializeSpace = ClientLibrary.initializeSpace.bind(ClientLibrary);
1454
+ export const readSpaceBlock = ClientLibrary.readSpaceBlock.bind(ClientLibrary);
1455
+ export const solveSpaceChallenge = ClientLibrary.solveSpaceChallenge.bind(ClientLibrary);
1456
+
1457
+ // Export the internal object for testing purposes
1458
+ export default ClientLibrary;
1459
+
1460
+ // --- Global Export for Browser ---
1461
+ // Attach the library to the window object to make it accessible from inline scripts.
1462
+ if (typeof window !== 'undefined') {
1463
+ window.ClientLibrary = ClientLibrary;
1448
1464
  }