@anonympins/fingerprint 0.4.2 → 0.4.4

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,636 +1,832 @@
1
- import {cyrb53 as jsCyrb53, FingerprintBuilder} from './fingerprint.builder.js';
2
- import {solveChallenge} from './pow.solver.js';
3
-
4
- // Variable pour stocker la fonction de hachage active.
5
- // Par défaut, c'est l'implémentation JavaScript.
6
- let activeCyrb53 = jsCyrb53;
7
-
8
- const ClientLibrary = {
9
- // Cache pour éviter de recalculer les constantes (Hardware, etc.)
10
- _cachedBuilder: null,
11
- /**
12
- * @private
13
- * Dispatches a custom event from the window object.
14
- * @param {string} eventName - The name of the event.
15
- * @param {object} [detail={}] - The data to include in the event's detail property.
16
- */
17
- _dispatchEvent(eventName, detail = {}) {
18
- if (typeof window === 'undefined' || typeof CustomEvent === 'undefined') return;
19
- const event = new CustomEvent(`fingerprint:${eventName}`, { detail });
20
- window.dispatchEvent(event);
21
- },
22
-
23
- /**
24
- * Wrapper interne pour la fonction de hachage.
25
- * @private
26
- */
27
- _hasher: (str, seed) => activeCyrb53(str, seed),
28
-
29
- /**
30
- * Génère l'empreinte de l'appareil actuel.
31
- */
32
- getDeviceFingerprint() {
33
- if (typeof window === "undefined") {
34
- console.error("getDeviceFingerprint can only be called on the client-side.");
35
- return "";
36
- }
37
-
38
- if (!this._cachedBuilder) {
39
- const nav = window.navigator;
40
- const screen = window.screen;
41
-
42
- this._cachedBuilder = new FingerprintBuilder();
43
-
44
- // 1. Hardware (Très stable) : Cœurs, RAM, GPU (si dispo via canvas), Touch
45
- this._cachedBuilder.add(
46
- "hw", // Utilise maintenant le hasher actif
47
- `${nav.hardwareConcurrency}_${nav.deviceMemory}_${nav.maxTouchPoints}`,
48
- );
49
-
50
- // 2. Geo/Locale (Stable sauf voyage/VPN) : Timezone, Langue
51
- this._cachedBuilder.add(
52
- "geo",
53
- `${Intl.DateTimeFormat().resolvedOptions().timeZone}_${nav.language}_${new Date().getTimezoneOffset()}`,
54
- );
55
-
56
- // 3. Screen (Stable sauf changement moniteur/zoom) : Dimensions, ColorDepth
57
- this._cachedBuilder.add(
58
- "scr",
59
- `${screen.width}x${screen.height}_${screen.colorDepth}`,
60
- );
61
-
62
- // 4. Platform (Stable) : OS, Engine
63
- this._cachedBuilder.add("os", nav.platform);
64
-
65
- // 5. Graphics (WebGL Vendor/Renderer) - Invariant matériel fort
66
- try {
67
- const canvas = document.createElement("canvas");
68
- const gl =
69
- canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
70
- if (gl) {
71
- const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
72
- if (debugInfo) {
73
- const vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
74
- const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
75
- this._cachedBuilder.add("gpu", `${vendor}_${renderer}`);
76
- }
77
- }
78
- } catch (e) {
79
- }
80
-
81
- // 6. Canvas Fingerprinting (Rendering quirks)
82
- try {
83
- const canvas = document.createElement("canvas");
84
- const ctx = canvas.getContext("2d");
85
- if (ctx) {
86
- canvas.width = 200;
87
- canvas.height = 50;
88
- ctx.textBaseline = "alphabetic";
89
- ctx.font = "14px 'Arial'";
90
- ctx.fillStyle = "#f60";
91
- ctx.fillRect(125, 1, 62, 20);
92
- ctx.fillStyle = "#069";
93
- ctx.fillText("fingerprint", 2, 15);
94
- ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
95
- ctx.fillText("fingerprint", 4, 17);
96
- this._cachedBuilder.add("cvs", canvas.toDataURL());
97
- }
98
- } catch (e) {
99
- }
100
-
101
- // 7. Détection des artefacts du Chrome DevTools Protocol (CDP)
102
- // Ces variables sont souvent injectées par les outils d'automatisation.
103
- const cdpFootprints = [
104
- 'cdc_adoQpoasnfa76pfcZLmcfl_Array',
105
- 'cdc_adoQpoasnfa76pfcZLmcfl_Promise',
106
- 'cdc_adoQpoasnfa76pfcZLmcfl_Symbol',
107
- '$cdc_asdjflasutopfhvcZLmcfl_',
108
- '_selenium',
109
- '_driver'
110
- ];
111
- if (cdpFootprints.some(fp => window[fp])) {
112
- this._cachedBuilder.add("cdp", "true");
113
- }
114
-
115
- // 7. Bot Detection (Indication cachée)
116
- if (nav.webdriver) this._cachedBuilder.add("bot", "true");
117
- }
118
-
119
- return this._cachedBuilder.toString();
120
- },
121
-
122
- /**
123
- * Génère une signature de requête incluant le contexte.
124
- * @param {object} payload
125
- */
126
- /**
127
- * Génère une signature de requête incluant le contexte.
128
- * @param {object} payload
129
- */
130
- generateRequestSignature(payload = {}) {
131
- const deviceFp = this.getDeviceFingerprint();
132
- const sortedPayload = Object.keys(payload)
133
- .sort()
134
- .map((k) => `${k}=${payload[k]}`)
135
- .join("&");
136
- const payloadHash = this._hasher(sortedPayload);
137
- return `${deviceFp}|req:${payloadHash}`;
138
- },
139
-
140
- /**
141
- * Génère une signature HMAC-SHA256 en utilisant l'API Web Crypto.
142
- * @param {object} payload - Les données à signer.
143
- * @param {string} secret - La clé secrète partagée.
144
- * @returns {Promise<string>} La signature hexadécimale.
145
- */
146
- async generateClientSideSignature(payload, secret) {
147
- const sortedPayload = Object.keys(payload).sort().map((k) => `${k}=${payload[k]}`).join("&");
148
- const encoder = new TextEncoder();
149
- const key = await window.crypto.subtle.importKey("raw", encoder.encode(secret), {
150
- name: "HMAC",
151
- hash: "SHA-256"
152
- }, false, ["sign"]);
153
- const signatureBuffer = await window.crypto.subtle.sign("HMAC", key, encoder.encode(sortedPayload));
154
- const hashArray = Array.from(new Uint8Array(signatureBuffer));
155
- return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
156
- },
157
-
158
- /**
159
- * @internal
160
- * Resets the cached fingerprint builder. Used for testing purposes.
161
- */
162
- _resetCache() {
163
- // Réinitialise le hasher à l'implémentation JS par défaut.
164
- activeCyrb53 = jsCyrb53;
165
- this._cachedBuilder = null;
166
- },
167
-
168
- /**
169
- * Démarre le suivi des mouvements de la souris pour calculer l'entropie.
170
- * À appeler une fois sur la page.
171
- */
172
- startMouseEntropyTracker() {
173
- // Utiliser un drapeau pour éviter d'attacher l'écouteur plusieurs fois
174
- if (this._mouseTrackerAttached) return;
175
- this._mouseTrackerAttached = true;
176
-
177
- document.addEventListener('mousemove', (e) => {
178
- // NOUVEAU: Capturer une série de points {x, y, t}
179
- if (mouseMovementsHistory.length >= MOUSE_HISTORY_MAX) {
180
- // Garder la taille de l'historique constante pour éviter une consommation mémoire excessive.
181
- mouseMovementsHistory.shift();
182
- }
183
- mouseMovementsHistory.push({
184
- x: e.clientX,
185
- y: e.clientY,
186
- t: performance.now()
187
- });
188
- }, {passive: true});
189
- },
190
-
191
- /**
192
- * Démarre le suivi de la dynamique de frappe pour calculer la latence.
193
- * À appeler une fois sur la page.
194
- */
195
- startKeystrokeDynamicsTracker() {
196
- // S'assurer de ne pas attacher l'écouteur plusieurs fois
197
- if (keystrokeTimestamps.length > 0) return;
198
-
199
- document.addEventListener('keydown', () => {
200
- const now = performance.now();
201
- if (keystrokeTimestamps.length > 0) {
202
- const lastTimestamp = keystrokeTimestamps[keystrokeTimestamps.length - 1];
203
- const latency = now - lastTimestamp;
204
- // On ignore les latences irréalistes (trop longues ou trop courtes)
205
- if (latency > 10 && latency < 2000) { // Augmenté à 2s
206
- if (keystrokeLatencies.length >= KEYSTROKE_HISTORY_MAX) {
207
- keystrokeLatencies.shift(); // Garder la taille de l'historique
208
- }
209
- keystrokeLatencies.push(latency);
210
- }
211
- }
212
- keystrokeTimestamps.push(now);
213
- }, {passive: true});
214
- },
215
-
216
- /**
217
- * Starts tracking click events to analyze position variance.
218
- * @private
219
- */
220
- startClickTracker() {
221
- if (this._clickTrackerAttached) return;
222
- this._clickTrackerAttached = true;
223
-
224
- document.addEventListener('click', (e) => {
225
- if (clicksHistory.length >= CLICKS_HISTORY_MAX) {
226
- clicksHistory.shift();
227
- }
228
- // Generate a simple identifier for the target element
229
- const target = e.target;
230
- const targetId = target.id || target.name || target.tagName;
231
-
232
- clicksHistory.push({
233
- x: e.clientX,
234
- y: e.clientY,
235
- t: performance.now(),
236
- targetId: this._hasher(targetId) // Hash the ID to keep it short and consistent
237
- });
238
- }, { passive: true });
239
- },
240
- /**
241
- * Initialise ou réinitialise les honeypots côté client pour une détection immédiate.
242
- * Les anciens écouteurs sont supprimés avant d'en ajouter de nouveaux.
243
- * @param {string[]} honeypotFieldNames - Noms des champs de formulaire cachés.
244
- */
245
- initializeHoneypots(honeypotFieldNames) {
246
- // 1. Nettoyer les anciens écouteurs
247
- activeHoneypotListeners.forEach((listener, field) => {
248
- field.removeEventListener('input', listener);
249
- });
250
- activeHoneypotListeners.clear();
251
-
252
- // 2. Ajouter les nouveaux écouteurs
253
- honeypotFieldNames.forEach(fieldName => {
254
- const field = document.querySelector(`[name="${fieldName}"]`);
255
- if (field) {
256
- // On utilise une fonction nommée (ou une référence) pour pouvoir la supprimer plus tard.
257
- // L'option { once: true } est excellente, mais pour une réinitialisation complète,
258
- // il est plus propre de gérer le nettoyage nous-mêmes.
259
- const listener = () => {
260
- this.onHoneypotTrigger();
261
- // Se supprime lui-même après exécution, comme { once: true }
262
- field.removeEventListener('input', listener);
263
- };
264
- field.addEventListener('input', listener);
265
- activeHoneypotListeners.set(field, listener); // On stocke la référence
266
- }
267
- });
268
- },
269
-
270
- /**
271
- * Récupère les métriques comportementales collectées.
272
- * À appeler avant d'envoyer une requête sensible.
273
- * @returns {ClientBehaviorMetrics}
274
- */
275
- getClientBehaviorMetrics() {
276
- // Add history length as a behavioral signal.
277
- metrics.historyLength = window.history.length;
278
-
279
- // Ajoute un timestamp au moment de la collecte pour la détection de rejeu.
280
- metrics.clicksHistory = clicksHistory;
281
- metrics.clientTimestamp = Date.now();
282
-
283
- // NOUVEAU: Inclure l'historique des mouvements de la souris pour une analyse côté serveur.
284
- metrics.mouseMovementsHistory = mouseMovementsHistory;
285
-
286
- // Calcule la latence moyenne des frappes
287
- if (keystrokeLatencies.length > 0) {
288
- const sum = keystrokeLatencies.reduce((a, b) => a + b, 0);
289
- metrics.keystrokeLatency = sum / keystrokeLatencies.length;
290
- } else {
291
- metrics.keystrokeLatency = 0;
292
- }
293
- return metrics;
294
- },
295
-
296
- /**
297
- * Enrichit une requête fetch avec les en-têtes de fingerprinting et de comportement.
298
- * @param {RequestInfo} resource
299
- * @param {RequestInit} [options]
300
- * @returns {Promise<Response>}
301
- */
302
- async protectedFetch(resource, options = {}) {
303
- const fp = this.getDeviceFingerprint();
304
- const behavior = this.getClientBehaviorMetrics();
305
-
306
- const headers = new Headers(options.headers || {});
307
- headers.set('X-Device-Fingerprint', fp);
308
- headers.set('X-Behavior-Metrics', JSON.stringify(behavior));
309
-
310
- options.headers = headers;
311
- return fetch(resource, options);
312
- },
313
-
314
- // --- Système d'interception de Fetch robuste et anti-conflit ---
315
-
316
- _isFetchPatched: false,
317
- _interceptorChain: [],
318
- // On stocke la fonction fetch originale et on la lie à son contexte (window)
319
- // pour éviter les erreurs "Illegal invocation" si une autre lib la modifie.
320
- _originalFetch: (typeof window !== 'undefined') ? window.fetch.bind(window) : null,
321
-
322
- /**
323
- * Adds an interceptor function to the `fetch` chain.
324
- * Chaque intercepteur reçoit `resource`, `options`, et une fonction `next`.
325
- * Il DOIT appeler `next(resource, options)` pour continuer la chaîne.
326
- * @param {function(RequestInfo, RequestInit, function): Promise<Response>} interceptor
327
- */
328
- addFetchInterceptor(interceptor) {
329
- if (!this._isFetchPatched) {
330
- this.patchGlobalFetch();
331
- }
332
- this._interceptorChain.push(interceptor);
333
- },
334
-
335
- patchGlobalFetch() {
336
- if (this._isFetchPatched || !this._originalFetch) return;
337
-
338
- this._isFetchPatched = true;
339
- window.fetch = (resource, options) => {
340
- // Le "dispatcher" qui exécute la chaîne.
341
- const dispatch = (index, res, opts) => {
342
- if (index >= this._interceptorChain.length) {
343
- // Fin de la chaîne, on appelle le fetch original.
344
- return this._originalFetch(res, opts);
345
- }
346
- const nextInterceptor = this._interceptorChain[index];
347
- // Appelle l'intercepteur actuel en lui passant la fonction pour appeler le suivant.
348
- return nextInterceptor(res, opts, (nextRes, nextOpts) => dispatch(index + 1, nextRes, nextOpts));
349
- };
350
- return dispatch(0, resource, options || {});
351
- };
352
- },
353
-
354
- /**
355
- * La fonction qui est appelée lorsqu'un honeypot est déclenché.
356
- * @private
357
- */
358
- onHoneypotTrigger() {
359
- metrics.honeypotInteraction = true;
360
- // Émettre un événement pour que l'application puisse réagir.
361
- this._dispatchEvent('honeypotTriggered');
362
- },
363
-
364
- /**
365
- * Initialise l'intercepteur de fingerprinting.
366
- * Il s'ajoute à la chaîne d'interception sans écraser les autres.
367
- * @param {string[]} [targetDomains] - Optionnel. Liste de domaines à protéger.
368
- * Si non fourni, protège les requêtes de même origine.
369
- */
370
- initializeFetch(targetDomains = []) {
371
- const fingerprintInterceptor = (resource, options, next) => {
372
- const requestUrl = (resource instanceof Request) ? resource.url : String(resource);
373
- let shouldProtect = false;
374
-
375
- try {
376
- const url = new URL(requestUrl, window.location.origin);
377
- // Protéger si la liste de domaines est vide ET que la requête est de même origine,
378
- // OU si le domaine de la requête est dans la liste fournie.
379
- shouldProtect = (targetDomains.length === 0 && url.origin === window.location.origin) ||
380
- (targetDomains.length > 0 && targetDomains.includes(url.hostname));
381
- } catch (e) {
382
- // Si l'URL est relative (ex: '/api/data'), new URL() ne lèvera pas d'erreur.
383
- // Ce bloc est une sécurité pour les cas l'URL serait malformée.
384
- // On protège par défaut si aucune liste de domaines n'est spécifiée.
385
- shouldProtect = targetDomains.length === 0;
386
- }
387
-
388
- if (shouldProtect) {
389
- const fp = this.getDeviceFingerprint();
390
- const behavior = this.getClientBehaviorMetrics();
391
- const headers = new Headers(options.headers || {});
392
- headers.set('X-Device-Fingerprint', fp);
393
- headers.set('X-Behavior-Metrics', JSON.stringify(behavior));
394
- options.headers = headers;
395
- }
396
-
397
- // Passe la main à l'intercepteur suivant dans la chaîne.
398
- return next(resource, options);
399
- };
400
-
401
- this.addFetchInterceptor(fingerprintInterceptor);
402
- }, // <-- VIRGULE AJOUTÉE ICI
403
-
404
- /**
405
- * Injects visually hidden "honeypot" links into the DOM to trap bots.
406
- * @param {string[]} urls - An array of trap URLs to inject.
407
- * @private
408
- */
409
- injectTrapLinks(urls) {
410
- if (!urls || urls.length === 0 || typeof document === 'undefined') {
411
- return;
412
- }
413
-
414
- const trapContainer = document.createElement('div');
415
- trapContainer.setAttribute('aria-hidden', 'true');
416
- trapContainer.style.position = 'absolute';
417
- trapContainer.style.left = '-9999px';
418
- trapContainer.style.top = '-9999px';
419
-
420
- urls.forEach(url => {
421
- const link = document.createElement('a');
422
- link.href = url;
423
- link.tabIndex = -1; // Make it unfocusable
424
- link.textContent = 'config'; // Some plausible text
425
- trapContainer.appendChild(link);
426
- });
427
-
428
- document.body.appendChild(trapContainer);
429
- },
430
- /**
431
- * Intercepte une réponse de challenge JSON, le résout, et réessaie la requête.
432
- * @param {Response} response - La réponse initiale (potentiellement 429).
433
- * @param {RequestInfo} resource - La ressource de la requête originale.
434
- * @param {RequestInit} options - Les options de la requête originale.
435
- * @returns {Promise<Response>} - La réponse de la requête réessayée.
436
- * @private
437
- */
438
- async solveChallengeAndRetry(response, resource, options) {
439
- if (response.status !== 404 || !response.headers.get('content-type')?.includes('application/json') || response.bodyUsed) {
440
- return response;
441
- }
442
-
443
- try {
444
- const challengeData = await response.json();
445
- if (!challengeData.challenge || !challengeData.challenge.type) {
446
- return response; // Pas un challenge JSON valide
447
- }
448
-
449
- console.log(`[Fingerprint] Received a '${challengeData.challenge.type}' challenge. Solving...`);
450
- this._dispatchEvent('challengeReceived', { challenge: challengeData.challenge });
451
-
452
- // L'empreinte de l'appareil qui résout le challenge est cruciale.
453
- const solverFp = this.getDeviceFingerprint();
454
- const solutionWrapper = await solveChallenge(challengeData.challenge, solverFp);
455
- console.log('[Fingerprint] Challenge solved. Retrying original request.');
456
-
457
- this._dispatchEvent('challengeSolved', { solution: solutionWrapper.rawSolution });
458
- // Ajouter la solution aux paramètres de la requête pour le nouvel essai
459
- const url = new URL((resource instanceof Request) ? resource.url : String(resource), window.location.origin);
460
- // La logique de formatage est maintenant cachée dans la classe ChallengeSolution.
461
- solutionWrapper.applyToUrl(url);
462
-
463
- // On ajoute l'empreinte du solveur à la requête de réessai.
464
- url.searchParams.set('pow_fp', solverFp);
465
-
466
- // On utilise la chaîne d'intercepteurs pour la requête réessayée,
467
- // ce qui garantit que le fetch original est appelé avec le bon contexte.
468
- // Cela évite de réintroduire l'erreur "Illegal invocation".
469
- return window.fetch(url.toString(), options);
470
- } catch (e) {
471
- console.error('[Fingerprint] Failed to solve or retry challenge:', e);
472
- return response; // Retourne la réponse 429 originale en cas d'échec
473
- }
474
- }, // <-- VIRGULE AJOUTÉE ICI
475
-
476
- /**
477
- * Initialise toutes les protections côté client en une seule fois.
478
- * Tente également de charger le module WASM si `wasmPath` est fourni.
479
- * C'est la méthode d'initialisation recommandée.
480
- * @param {ClientConfig} [config={}] - L'objet de configuration.
481
- */
482
- initializeClient(config = {}) {
483
- const {
484
- mouse = true,
485
- keystrokes = true,
486
- clicks = true, // Add new option
487
- honeypots = [],
488
- trapUrls = [], // Nouveau paramètre pour les URL pièges
489
- wasmPath, // Nouveau paramètre
490
- fetch: fetchConfig = {}
491
- } = config;
492
-
493
- // Tentative de chargement du WASM si le chemin est fourni
494
- if (wasmPath) {
495
- this.initializeWasm(wasmPath);
496
- }
497
-
498
- if (mouse) {
499
- this.startMouseEntropyTracker();
500
- }
501
- if (keystrokes) {
502
- this.startKeystrokeDynamicsTracker();
503
- }
504
- if (clicks) {
505
- this.startClickTracker();
506
- }
507
- if (honeypots.length > 0) {
508
- this.initializeHoneypots(honeypots);
509
- }
510
-
511
- // Injection dynamique des liens pièges au démarrage
512
- if (trapUrls.length > 0) {
513
- this.injectTrapLinks(trapUrls);
514
- }
515
- // On active l'interception si `fetch` est configuré, même avec un objet vide.
516
- if (config.fetch) {
517
- this.initializeFetch(fetchConfig.targetDomains);
518
-
519
- // Ajoute l'intercepteur pour la résolution de challenge
520
- if (fetchConfig.handleChallenges !== false) {
521
- this.addFetchInterceptor(async (resource, options, next) => {
522
- const originalResponse = await next(resource, options);
523
- // On clone la réponse pour que la lecture du corps par solveChallengeAndRetry ne la consomme pas pour l'appelant original.
524
- return this.solveChallengeAndRetry(originalResponse.clone(), resource, options);
525
- });
526
- }
527
- }
528
- },
529
-
530
- /**
531
- * Tente de charger et d'initialiser le module WebAssembly pour un hachage plus rapide.
532
- * Si le chargement échoue, il se rabat silencieusement sur l'implémentation JS.
533
- * @param {string} wasmPath - Le chemin vers le script de chargement du module WASM (ex: '/fp.js').
534
- */
535
- async initializeWasm(wasmPath) {
536
- try {
537
- // 1. Injecter le script qui charge le module WASM
538
- const script = document.createElement('script');
539
- script.src = wasmPath;
540
- await new Promise((resolve, reject) => {
541
- script.onload = resolve;
542
- script.onerror = reject;
543
- document.head.appendChild(script);
544
- });
545
-
546
- // 2. Attendre que la fonction globale `createFingerprintModule` soit disponible
547
- if (typeof window.createFingerprintModule !== 'function') {
548
- throw new Error('WASM loader script did not expose createFingerprintModule.');
549
- }
550
-
551
- // 3. Initialiser le module
552
- const wasmModule = await window.createFingerprintModule();
553
- if (typeof wasmModule._hash_string !== 'function') {
554
- throw new Error('WASM module did not export _hash_string.');
555
- }
556
- window.wasmModule = wasmModule;
557
- ClientLibrary.wasmModule = wasmModule;
558
-
559
- // 4. Remplacer la fonction de hachage par la version WASM
560
- activeCyrb53 = (str) => {
561
- // La fonction C++ attend un pointeur, Emscripten gère la conversion
562
- return wasmModule._hash_string(str);
563
- };
564
-
565
- console.log('[Fingerprint] WASM module loaded successfully. Using fast hashing.');
566
- // NOUVEAU: Ajoute un indicateur à l'empreinte pour que le serveur sache que le WASM est actif.
567
- if (this._cachedBuilder) {
568
- this._cachedBuilder.addRaw('wasm', 'true');
569
- }
570
- } catch (error) {
571
- console.warn('[Fingerprint] WASM module failed to load. Falling back to JS implementation. Error:', error);
572
- }
573
- }
574
- };
575
-
576
- /**
577
- * @typedef {object} ClientBehaviorMetrics
578
- * @property {number} mouseEntropy - Entropie des mouvements de la souris.
579
- * @property {Array<{x: number, y: number, t: number}>} mouseMovementsHistory - Historique des points de la souris.
580
- * @property {number} keystrokeLatency - Latence moyenne entre les frappes.
581
- * @property {boolean} honeypotInteraction - Vrai si un honeypot a été touché.
582
- * @property {Array<{x: number, y: number, t: number, targetId: string}>} clicksHistory - Historique des clics.
583
- * @property {number} historyLength - La longueur de l'historique de session du navigateur (`window.history.length`).
584
- * @property {number} clientTimestamp - Timestamp (Date.now()) de la collecte des métriques.
585
- * @property {string[]} [trapUrls] - URLs pièges à injecter dynamiquement.
586
- */
587
- /** @type {ClientBehaviorMetrics} */
588
- const metrics = {
589
- mouseEntropy: 0, // Conservé pour la compatibilité, mais l'analyse se fait maintenant sur l'historique
590
- mouseMovementsHistory: [],
591
- clicksHistory: [],
592
- keystrokeLatency: 0,
593
- honeypotInteraction: false,
594
- historyLength: 0,
595
- clientTimestamp: 0,
596
- };
597
-
598
- let lastMousePos = { x: 0, y: 0 };
599
- let mouseMovementsHistory = []; // NOUVEAU: Historique des points de la souris
600
- const MOUSE_HISTORY_MAX = 100; // Limite le nombre de points stockés
601
- let clicksHistory = [];
602
- const CLICKS_HISTORY_MAX = 50;
603
- let activeHoneypotListeners = new Map(); // Garde une trace des écouteurs actifs
604
- let keystrokeTimestamps = [];
605
- let keystrokeLatencies = []; // NOUVEAU: Tableau dédié pour les latences
606
- const KEYSTROKE_HISTORY_MAX = 20; // On garde l'historique des 20 dernières frappes
607
-
608
-
609
-
610
- // Exporter les fonctions individuellement pour la compatibilité ascendante
611
- export const getDeviceFingerprint = ClientLibrary.getDeviceFingerprint.bind(ClientLibrary);
612
- export const generateRequestSignature = ClientLibrary.generateRequestSignature.bind(ClientLibrary);
613
- export const generateClientSideSignature = ClientLibrary.generateClientSideSignature.bind(ClientLibrary);
614
- export const _resetCache = ClientLibrary._resetCache.bind(ClientLibrary);
615
- export const startMouseEntropyTracker = ClientLibrary.startMouseEntropyTracker.bind(ClientLibrary);
616
- export const startKeystrokeDynamicsTracker = ClientLibrary.startKeystrokeDynamicsTracker.bind(ClientLibrary);
617
- export const startClickTracker = ClientLibrary.startClickTracker.bind(ClientLibrary);
618
- export const initializeHoneypots = ClientLibrary.initializeHoneypots.bind(ClientLibrary);
619
- export const getClientBehaviorMetrics = ClientLibrary.getClientBehaviorMetrics.bind(ClientLibrary);
620
- export const protectedFetch = ClientLibrary.protectedFetch.bind(ClientLibrary);
621
- export const addFetchInterceptor = ClientLibrary.addFetchInterceptor.bind(ClientLibrary);
622
- export const patchGlobalFetch = ClientLibrary.patchGlobalFetch.bind(ClientLibrary);
623
- export const initializeFetch = ClientLibrary.initializeFetch.bind(ClientLibrary);
624
- export const initializeClient = ClientLibrary.initializeClient.bind(ClientLibrary);
625
- export const initializeWasm = ClientLibrary.initializeWasm.bind(ClientLibrary);
626
- export const injectTrapLinks = ClientLibrary.injectTrapLinks.bind(ClientLibrary);
627
- export const solveChallengeAndRetry = ClientLibrary.solveChallengeAndRetry.bind(ClientLibrary);
628
-
629
- // Export the internal object for testing purposes
630
- export default ClientLibrary;
631
-
632
- // --- Global Export for Browser ---
633
- // Attach the library to the window object to make it accessible from inline scripts.
634
- if (typeof window !== 'undefined') {
635
- window.ClientLibrary = ClientLibrary;
1
+ import {cyrb53 as jsCyrb53, FingerprintBuilder} from './fingerprint.builder.js';
2
+ import {solveChallenge} from './pow.solver.js';
3
+
4
+ // Variable pour stocker la fonction de hachage active.
5
+ // Par défaut, c'est l'implémentation JavaScript.
6
+ let activeCyrb53 = jsCyrb53;
7
+
8
+ const DB_NAME = 'wasm-cache-db';
9
+ const DB_VERSION = 1;
10
+ const STORE_NAME = 'wasm-modules';
11
+
12
+ function getCachedWasm(url) {
13
+ return new Promise((resolve) => {
14
+ if (typeof indexedDB === 'undefined') return resolve(null);
15
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
16
+ request.onupgradeneeded = (e) => {
17
+ const db = e.target.result;
18
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
19
+ db.createObjectStore(STORE_NAME);
20
+ }
21
+ };
22
+ request.onsuccess = (e) => {
23
+ const db = e.target.result;
24
+ try {
25
+ const transaction = db.transaction(STORE_NAME, 'readonly');
26
+ const store = transaction.objectStore(STORE_NAME);
27
+ const getReq = store.get(url);
28
+ getReq.onsuccess = () => resolve(getReq.result);
29
+ getReq.onerror = () => resolve(null);
30
+ } catch (err) {
31
+ resolve(null);
32
+ }
33
+ };
34
+ request.onerror = () => resolve(null);
35
+ });
36
+ }
37
+
38
+ function cacheWasm(url, data) {
39
+ return new Promise((resolve) => {
40
+ if (typeof indexedDB === 'undefined') return resolve(false);
41
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
42
+ request.onupgradeneeded = (e) => {
43
+ const db = e.target.result;
44
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
45
+ db.createObjectStore(STORE_NAME);
46
+ }
47
+ };
48
+ request.onsuccess = (e) => {
49
+ const db = e.target.result;
50
+ try {
51
+ const transaction = db.transaction(STORE_NAME, 'readwrite');
52
+ const store = transaction.objectStore(STORE_NAME);
53
+ store.put(data, url);
54
+ transaction.oncomplete = () => resolve(true);
55
+ transaction.onerror = () => resolve(false);
56
+ } catch (err) {
57
+ resolve(false);
58
+ }
59
+ };
60
+ request.onerror = () => resolve(false);
61
+ });
62
+ }
63
+
64
+ const ClientLibrary = {
65
+ // Cache pour éviter de recalculer les constantes (Hardware, etc.)
66
+ _cachedBuilder: null,
67
+ /**
68
+ * @private
69
+ * Dispatches a custom event from the window object.
70
+ * @param {string} eventName - The name of the event.
71
+ * @param {object} [detail={}] - The data to include in the event's detail property.
72
+ */
73
+ _dispatchEvent(eventName, detail = {}) {
74
+ if (typeof window === 'undefined' || typeof CustomEvent === 'undefined') return;
75
+ const event = new CustomEvent(`fingerprint:${eventName}`, { detail });
76
+ window.dispatchEvent(event);
77
+ },
78
+
79
+ /**
80
+ * Wrapper interne pour la fonction de hachage.
81
+ * @private
82
+ */
83
+ _hasher: (str, seed) => activeCyrb53(str, seed),
84
+
85
+ /**
86
+ * Génère l'empreinte de l'appareil actuel.
87
+ */
88
+ getDeviceFingerprint() {
89
+ if (typeof window === "undefined") {
90
+ console.error("getDeviceFingerprint can only be called on the client-side.");
91
+ return "";
92
+ }
93
+
94
+ if (!this._cachedBuilder) {
95
+ const nav = window.navigator;
96
+ const screen = window.screen;
97
+
98
+ this._cachedBuilder = new FingerprintBuilder();
99
+
100
+ // 1. Hardware (Très stable) : Cœurs, RAM, GPU (si dispo via canvas), Touch
101
+ this._cachedBuilder.add(
102
+ "hw", // Utilise maintenant le hasher actif
103
+ `${nav.hardwareConcurrency}_${nav.deviceMemory}_${nav.maxTouchPoints}`,
104
+ );
105
+
106
+ // 2. Geo/Locale (Stable sauf voyage/VPN) : Timezone, Langue
107
+ this._cachedBuilder.add(
108
+ "geo",
109
+ `${Intl.DateTimeFormat().resolvedOptions().timeZone}_${nav.language}_${new Date().getTimezoneOffset()}`,
110
+ );
111
+
112
+ // 3. Screen (Stable sauf changement moniteur/zoom) : Dimensions, ColorDepth
113
+ this._cachedBuilder.add(
114
+ "scr",
115
+ `${screen.width}x${screen.height}_${screen.colorDepth}`,
116
+ );
117
+
118
+ // 4. Platform (Stable) : OS, Engine
119
+ this._cachedBuilder.add("os", nav.platform);
120
+
121
+ // 5. Graphics (WebGL Vendor/Renderer) - Invariant matériel fort
122
+ try {
123
+ const canvas = document.createElement("canvas");
124
+ const gl =
125
+ canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
126
+ if (gl) {
127
+ const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
128
+ if (debugInfo) {
129
+ const vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
130
+ const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
131
+ this._cachedBuilder.add("gpu", `${vendor}_${renderer}`);
132
+ }
133
+ }
134
+ } catch (e) {
135
+ }
136
+
137
+ // 6. Canvas Fingerprinting (Rendering quirks)
138
+ try {
139
+ const canvas = document.createElement("canvas");
140
+ const ctx = canvas.getContext("2d");
141
+ if (ctx) {
142
+ canvas.width = 200;
143
+ canvas.height = 50;
144
+ ctx.textBaseline = "alphabetic";
145
+ ctx.font = "14px 'Arial'";
146
+ ctx.fillStyle = "#f60";
147
+ ctx.fillRect(125, 1, 62, 20);
148
+ ctx.fillStyle = "#069";
149
+ ctx.fillText("fingerprint", 2, 15);
150
+ ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
151
+ ctx.fillText("fingerprint", 4, 17);
152
+ this._cachedBuilder.add("cvs", canvas.toDataURL());
153
+ }
154
+ } catch (e) {
155
+ }
156
+
157
+ // 7. Détection des artefacts du Chrome DevTools Protocol (CDP)
158
+ // Ces variables sont souvent injectées par les outils d'automatisation.
159
+ const cdpFootprints = [
160
+ 'cdc_adoQpoasnfa76pfcZLmcfl_Array',
161
+ 'cdc_adoQpoasnfa76pfcZLmcfl_Promise',
162
+ 'cdc_adoQpoasnfa76pfcZLmcfl_Symbol',
163
+ '$cdc_asdjflasutopfhvcZLmcfl_',
164
+ '_selenium',
165
+ '_driver'
166
+ ];
167
+ if (cdpFootprints.some(fp => window[fp])) {
168
+ this._cachedBuilder.add("cdp", "true");
169
+ }
170
+
171
+ // 7. Bot Detection (Indication cachée)
172
+ if (nav.webdriver) this._cachedBuilder.add("bot", "true");
173
+ }
174
+
175
+ return this._cachedBuilder.toString();
176
+ },
177
+
178
+ /**
179
+ * Génère une signature de requête incluant le contexte.
180
+ * @param {object} payload
181
+ */
182
+ /**
183
+ * Génère une signature de requête incluant le contexte.
184
+ * @param {object} payload
185
+ */
186
+ generateRequestSignature(payload = {}) {
187
+ const deviceFp = this.getDeviceFingerprint();
188
+ const sortedPayload = Object.keys(payload)
189
+ .sort()
190
+ .map((k) => `${k}=${payload[k]}`)
191
+ .join("&");
192
+ const payloadHash = this._hasher(sortedPayload);
193
+ return `${deviceFp}|req:${payloadHash}`;
194
+ },
195
+
196
+ /**
197
+ * Génère une signature HMAC-SHA256 en utilisant l'API Web Crypto.
198
+ * @param {object} payload - Les données à signer.
199
+ * @param {string} secret - La clé secrète partagée.
200
+ * @returns {Promise<string>} La signature hexadécimale.
201
+ */
202
+ async generateClientSideSignature(payload, secret) {
203
+ const sortedPayload = Object.keys(payload).sort().map((k) => `${k}=${payload[k]}`).join("&");
204
+ const encoder = new TextEncoder();
205
+ const key = await window.crypto.subtle.importKey("raw", encoder.encode(secret), {
206
+ name: "HMAC",
207
+ hash: "SHA-256"
208
+ }, false, ["sign"]);
209
+ const signatureBuffer = await window.crypto.subtle.sign("HMAC", key, encoder.encode(sortedPayload));
210
+ const hashArray = Array.from(new Uint8Array(signatureBuffer));
211
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
212
+ },
213
+
214
+ /**
215
+ * @internal
216
+ * Resets the cached fingerprint builder. Used for testing purposes.
217
+ */
218
+ _resetCache() {
219
+ // Réinitialise le hasher à l'implémentation JS par défaut.
220
+ activeCyrb53 = jsCyrb53;
221
+ this._cachedBuilder = null;
222
+ },
223
+
224
+ /**
225
+ * Injecte des éléments interactifs fantômes invisibles pour piéger les bots (focus/hover).
226
+ */
227
+ injectPhantomTraps() {
228
+ if (typeof document === 'undefined') return;
229
+
230
+ // Création d'un élément interactif fantôme
231
+ const phantom = document.createElement('a');
232
+ phantom.href = '#';
233
+ // Nom trompeur pour attirer les analyseurs automatiques de liens / formulaires
234
+ phantom.id = 'sys-session-recovery';
235
+ phantom.tabIndex = 0; // Dans le flux naturel de tabulation
236
+ phantom.setAttribute('aria-hidden', 'true'); // Masqué pour les screen readers légitimes
237
+
238
+ // Style invisible mais interactif (1px x 1px, presque transparent)
239
+ phantom.style.position = 'fixed';
240
+ phantom.style.top = '1px';
241
+ phantom.style.left = '1px';
242
+ phantom.style.width = '1px';
243
+ phantom.style.height = '1px';
244
+ phantom.style.opacity = '0.001';
245
+ phantom.style.zIndex = '99999';
246
+ phantom.style.overflow = 'hidden';
247
+ phantom.style.pointerEvents = 'auto';
248
+
249
+ const triggerTrap = () => {
250
+ this.onHoneypotTrigger();
251
+ };
252
+
253
+ phantom.addEventListener('focus', triggerTrap, { passive: true });
254
+ phantom.addEventListener('mouseover', triggerTrap, { passive: true });
255
+
256
+ document.body.appendChild(phantom);
257
+ },
258
+
259
+ /**
260
+ * Démarre le suivi des événements tactiles sur mobile/tablette.
261
+ */
262
+ startTouchEventTracker() {
263
+ if (this._touchTrackerAttached) return;
264
+ this._touchTrackerAttached = true;
265
+
266
+ const handleTouch = (e) => {
267
+ if (touchMovementsHistory.length >= TOUCH_HISTORY_MAX) {
268
+ touchMovementsHistory.shift();
269
+ }
270
+ const touch = e.touches[0] || e.changedTouches[0];
271
+ if (!touch) return;
272
+
273
+ const radiusX = touch.radiusX || 0;
274
+ const radiusY = touch.radiusY || 0;
275
+ const radius = (radiusX + radiusY) / 2;
276
+ const force = touch.force || touch.webkitForce || 0;
277
+
278
+ touchMovementsHistory.push({
279
+ x: touch.clientX,
280
+ y: touch.clientY,
281
+ t: performance.now(),
282
+ p: force,
283
+ r: radius,
284
+ num: e.touches.length
285
+ });
286
+ };
287
+
288
+ document.addEventListener('touchstart', handleTouch, { passive: true });
289
+ document.addEventListener('touchmove', handleTouch, { passive: true });
290
+ document.addEventListener('touchend', handleTouch, { passive: true });
291
+ },
292
+
293
+ /**
294
+ * Démarre le suivi des mouvements de la souris pour calculer l'entropie.
295
+ * À appeler une fois sur la page.
296
+ */
297
+ startMouseEntropyTracker() {
298
+ // Utiliser un drapeau pour éviter d'attacher l'écouteur plusieurs fois
299
+ if (this._mouseTrackerAttached) return;
300
+ this._mouseTrackerAttached = true;
301
+
302
+ document.addEventListener('mousemove', (e) => {
303
+ // NOUVEAU: Capturer une série de points {x, y, t}
304
+ if (mouseMovementsHistory.length >= MOUSE_HISTORY_MAX) {
305
+ // Garder la taille de l'historique constante pour éviter une consommation mémoire excessive.
306
+ mouseMovementsHistory.shift();
307
+ }
308
+ mouseMovementsHistory.push({
309
+ x: e.clientX,
310
+ y: e.clientY,
311
+ t: performance.now()
312
+ });
313
+ }, {passive: true});
314
+ },
315
+
316
+ /**
317
+ * Démarre le suivi de la dynamique de frappe pour calculer la latence.
318
+ * À appeler une fois sur la page.
319
+ */
320
+ startKeystrokeDynamicsTracker() {
321
+ // S'assurer de ne pas attacher l'écouteur plusieurs fois
322
+ if (keystrokeTimestamps.length > 0) return;
323
+
324
+ document.addEventListener('keydown', () => {
325
+ const now = performance.now();
326
+ if (keystrokeTimestamps.length > 0) {
327
+ const lastTimestamp = keystrokeTimestamps[keystrokeTimestamps.length - 1];
328
+ const latency = now - lastTimestamp;
329
+ // On ignore les latences irréalistes (trop longues ou trop courtes)
330
+ if (latency > 10 && latency < 2000) { // Augmenté à 2s
331
+ if (keystrokeLatencies.length >= KEYSTROKE_HISTORY_MAX) {
332
+ keystrokeLatencies.shift(); // Garder la taille de l'historique
333
+ }
334
+ keystrokeLatencies.push(latency);
335
+ }
336
+ }
337
+ keystrokeTimestamps.push(now);
338
+ }, {passive: true});
339
+ },
340
+
341
+ /**
342
+ * Starts tracking click events to analyze position variance.
343
+ * @private
344
+ */
345
+ startClickTracker() {
346
+ if (this._clickTrackerAttached) return;
347
+ this._clickTrackerAttached = true;
348
+
349
+ document.addEventListener('click', (e) => {
350
+ if (clicksHistory.length >= CLICKS_HISTORY_MAX) {
351
+ clicksHistory.shift();
352
+ }
353
+ // Generate a simple identifier for the target element
354
+ const target = e.target;
355
+ const targetId = target.id || target.name || target.tagName;
356
+
357
+ clicksHistory.push({
358
+ x: e.clientX,
359
+ y: e.clientY,
360
+ t: performance.now(),
361
+ targetId: this._hasher(targetId) // Hash the ID to keep it short and consistent
362
+ });
363
+ }, { passive: true });
364
+ },
365
+ /**
366
+ * Initialise ou réinitialise les honeypots côté client pour une détection immédiate.
367
+ * Les anciens écouteurs sont supprimés avant d'en ajouter de nouveaux.
368
+ * @param {string[]} honeypotFieldNames - Noms des champs de formulaire cachés.
369
+ */
370
+ initializeHoneypots(honeypotFieldNames) {
371
+ // 1. Nettoyer les anciens écouteurs
372
+ activeHoneypotListeners.forEach((listener, field) => {
373
+ field.removeEventListener('input', listener);
374
+ });
375
+ activeHoneypotListeners.clear();
376
+
377
+ // 2. Ajouter les nouveaux écouteurs
378
+ honeypotFieldNames.forEach(fieldName => {
379
+ const field = document.querySelector(`[name="${fieldName}"]`);
380
+ if (field) {
381
+ // On utilise une fonction nommée (ou une référence) pour pouvoir la supprimer plus tard.
382
+ // L'option { once: true } est excellente, mais pour une réinitialisation complète,
383
+ // il est plus propre de gérer le nettoyage nous-mêmes.
384
+ const listener = () => {
385
+ this.onHoneypotTrigger();
386
+ // Se supprime lui-même après exécution, comme { once: true }
387
+ field.removeEventListener('input', listener);
388
+ };
389
+ field.addEventListener('input', listener);
390
+ activeHoneypotListeners.set(field, listener); // On stocke la référence
391
+ }
392
+ });
393
+ },
394
+
395
+ /**
396
+ * Récupère les métriques comportementales collectées.
397
+ * À appeler avant d'envoyer une requête sensible.
398
+ * @returns {ClientBehaviorMetrics}
399
+ */
400
+ getClientBehaviorMetrics() {
401
+ // Add history length as a behavioral signal.
402
+ metrics.historyLength = window.history.length;
403
+
404
+ // Ajoute un timestamp au moment de la collecte pour la détection de rejeu.
405
+ metrics.clicksHistory = clicksHistory;
406
+ metrics.clientTimestamp = Date.now();
407
+
408
+ metrics.touchMovementsHistory = touchMovementsHistory;
409
+ // NOUVEAU: Inclure l'historique des mouvements de la souris pour une analyse côté serveur.
410
+ metrics.mouseMovementsHistory = mouseMovementsHistory;
411
+
412
+ // Calcule la latence moyenne des frappes
413
+ if (keystrokeLatencies.length > 0) {
414
+ const sum = keystrokeLatencies.reduce((a, b) => a + b, 0);
415
+ metrics.keystrokeLatency = sum / keystrokeLatencies.length;
416
+ } else {
417
+ metrics.keystrokeLatency = 0;
418
+ }
419
+ return metrics;
420
+ },
421
+
422
+ /**
423
+ * Enrichit une requête fetch avec les en-têtes de fingerprinting et de comportement.
424
+ * @param {RequestInfo} resource
425
+ * @param {RequestInit} [options]
426
+ * @returns {Promise<Response>}
427
+ */
428
+ async protectedFetch(resource, options = {}) {
429
+ const fp = this.getDeviceFingerprint();
430
+ const behavior = this.getClientBehaviorMetrics();
431
+
432
+ const headers = new Headers(options.headers || {});
433
+ headers.set('X-Device-Fingerprint', fp);
434
+ headers.set('X-Behavior-Metrics', JSON.stringify(behavior));
435
+
436
+ options.headers = headers;
437
+ return fetch(resource, options);
438
+ },
439
+
440
+ // --- Système d'interception de Fetch robuste et anti-conflit ---
441
+
442
+ _isFetchPatched: false,
443
+ _interceptorChain: [],
444
+ // On stocke la fonction fetch originale et on la lie à son contexte (window)
445
+ // pour éviter les erreurs "Illegal invocation" si une autre lib la modifie.
446
+ _originalFetch: (typeof window !== 'undefined') ? window.fetch.bind(window) : null,
447
+
448
+ /**
449
+ * Adds an interceptor function to the `fetch` chain.
450
+ * Chaque intercepteur reçoit `resource`, `options`, et une fonction `next`.
451
+ * Il DOIT appeler `next(resource, options)` pour continuer la chaîne.
452
+ * @param {function(RequestInfo, RequestInit, function): Promise<Response>} interceptor
453
+ */
454
+ addFetchInterceptor(interceptor) {
455
+ if (!this._isFetchPatched) {
456
+ this.patchGlobalFetch();
457
+ }
458
+ this._interceptorChain.push(interceptor);
459
+ },
460
+
461
+ patchGlobalFetch() {
462
+ if (this._isFetchPatched || !this._originalFetch) return;
463
+
464
+ this._isFetchPatched = true;
465
+ window.fetch = (resource, options) => {
466
+ // Le "dispatcher" qui exécute la chaîne.
467
+ const dispatch = (index, res, opts) => {
468
+ if (index >= this._interceptorChain.length) {
469
+ // Fin de la chaîne, on appelle le fetch original.
470
+ return this._originalFetch(res, opts);
471
+ }
472
+ const nextInterceptor = this._interceptorChain[index];
473
+ // Appelle l'intercepteur actuel en lui passant la fonction pour appeler le suivant.
474
+ return nextInterceptor(res, opts, (nextRes, nextOpts) => dispatch(index + 1, nextRes, nextOpts));
475
+ };
476
+ return dispatch(0, resource, options || {});
477
+ };
478
+ },
479
+
480
+ /**
481
+ * La fonction qui est appelée lorsqu'un honeypot est déclenché.
482
+ * @private
483
+ */
484
+ onHoneypotTrigger() {
485
+ metrics.honeypotInteraction = true;
486
+ // Émettre un événement pour que l'application puisse réagir.
487
+ this._dispatchEvent('honeypotTriggered');
488
+ },
489
+
490
+ /**
491
+ * Initialise l'intercepteur de fingerprinting.
492
+ * Il s'ajoute à la chaîne d'interception sans écraser les autres.
493
+ * @param {string[]} [targetDomains] - Optionnel. Liste de domaines à protéger.
494
+ * Si non fourni, protège les requêtes de même origine.
495
+ */
496
+ initializeFetch(targetDomains = []) {
497
+ const fingerprintInterceptor = (resource, options, next) => {
498
+ const requestUrl = (resource instanceof Request) ? resource.url : String(resource);
499
+ let shouldProtect = false;
500
+
501
+ try {
502
+ const url = new URL(requestUrl, window.location.origin);
503
+ // Protéger si la liste de domaines est vide ET que la requête est de même origine,
504
+ // OU si le domaine de la requête est dans la liste fournie.
505
+ shouldProtect = (targetDomains.length === 0 && url.origin === window.location.origin) ||
506
+ (targetDomains.length > 0 && targetDomains.includes(url.hostname));
507
+ } catch (e) {
508
+ // Si l'URL est relative (ex: '/api/data'), new URL() ne lèvera pas d'erreur.
509
+ // Ce bloc est une sécurité pour les cas où l'URL serait malformée.
510
+ // On protège par défaut si aucune liste de domaines n'est spécifiée.
511
+ shouldProtect = targetDomains.length === 0;
512
+ }
513
+
514
+ if (shouldProtect) {
515
+ const fp = this.getDeviceFingerprint();
516
+ const behavior = this.getClientBehaviorMetrics();
517
+ const headers = new Headers(options.headers || {});
518
+ headers.set('X-Device-Fingerprint', fp);
519
+ headers.set('X-Behavior-Metrics', JSON.stringify(behavior));
520
+ options.headers = headers;
521
+ }
522
+
523
+ // Passe la main à l'intercepteur suivant dans la chaîne.
524
+ return next(resource, options);
525
+ };
526
+
527
+ this.addFetchInterceptor(fingerprintInterceptor);
528
+ }, // <-- VIRGULE AJOUTÉE ICI
529
+
530
+ /**
531
+ * Injects visually hidden "honeypot" links into the DOM to trap bots.
532
+ * @param {string[]} urls - An array of trap URLs to inject.
533
+ * @private
534
+ */
535
+ injectTrapLinks(urls) {
536
+ if (!urls || urls.length === 0 || typeof document === 'undefined') {
537
+ return;
538
+ }
539
+
540
+ const trapContainer = document.createElement('div');
541
+ trapContainer.setAttribute('aria-hidden', 'true');
542
+ trapContainer.style.position = 'absolute';
543
+ trapContainer.style.left = '-9999px';
544
+ trapContainer.style.top = '-9999px';
545
+ trapContainer.style.transform = 'scale(0)';
546
+ trapContainer.style.pointerEvents = 'none';
547
+
548
+ urls.forEach((url,i) => {
549
+ const link = document.createElement('a');
550
+ link.href = url;
551
+ link.rel = 'nofollow';
552
+ link.tabIndex = -1; // Make it unfocusable
553
+ link.innerHTML = `<span>&gt; ${i+1}</span>`; // SEO-insignificant content
554
+ trapContainer.appendChild(link);
555
+ });
556
+
557
+ document.body.appendChild(trapContainer);
558
+ },
559
+ /**
560
+ * Intercepte une réponse de challenge JSON, le résout, et réessaie la requête.
561
+ * @param {Response} response - La réponse initiale (potentiellement 429).
562
+ * @param {RequestInfo} resource - La ressource de la requête originale.
563
+ * @param {RequestInit} options - Les options de la requête originale.
564
+ * @returns {Promise<Response>} - La réponse de la requête réessayée.
565
+ * @private
566
+ */
567
+ async solveChallengeAndRetry(response, resource, options) {
568
+ if (response.status !== 404 || !response.headers.get('content-type')?.includes('application/json') || response.bodyUsed) {
569
+ return response;
570
+ }
571
+
572
+ try {
573
+ const challengeData = await response.json();
574
+ if (!challengeData.challenge || !challengeData.challenge.type) {
575
+ return response; // Pas un challenge JSON valide
576
+ }
577
+
578
+ console.log(`[Fingerprint] Received a '${challengeData.challenge.type}' challenge. Solving...`);
579
+ this._dispatchEvent('challengeReceived', { challenge: challengeData.challenge });
580
+
581
+ // L'empreinte de l'appareil qui résout le challenge est cruciale.
582
+ const solverFp = this.getDeviceFingerprint();
583
+ const solutionWrapper = await solveChallenge(challengeData.challenge, solverFp);
584
+ console.log('[Fingerprint] Challenge solved. Retrying original request.');
585
+
586
+ this._dispatchEvent('challengeSolved', { solution: solutionWrapper.rawSolution });
587
+ // Ajouter la solution aux paramètres de la requête pour le nouvel essai
588
+ const url = new URL((resource instanceof Request) ? resource.url : String(resource), window.location.origin);
589
+ // La logique de formatage est maintenant cachée dans la classe ChallengeSolution.
590
+ solutionWrapper.applyToUrl(url);
591
+
592
+ // On ajoute l'empreinte du solveur à la requête de réessai.
593
+ url.searchParams.set('pow_fp', solverFp);
594
+
595
+ // On utilise la chaîne d'intercepteurs pour la requête réessayée,
596
+ // ce qui garantit que le fetch original est appelé avec le bon contexte.
597
+ // Cela évite de réintroduire l'erreur "Illegal invocation".
598
+ return window.fetch(url.toString(), options);
599
+ } catch (e) {
600
+ console.error('[Fingerprint] Failed to solve or retry challenge:', e);
601
+ return response; // Retourne la réponse 429 originale en cas d'échec
602
+ }
603
+ }, // <-- VIRGULE AJOUTÉE ICI
604
+
605
+ /**
606
+ * Initialise toutes les protections côté client en une seule fois.
607
+ * Tente également de charger le module WASM si `wasmPath` est fourni.
608
+ * C'est la méthode d'initialisation recommandée.
609
+ * @param {ClientConfig} [config={}] - L'objet de configuration.
610
+ */
611
+ initializeClient(config = {}) {
612
+ const {
613
+ mouse = true,
614
+ keystrokes = true,
615
+ clicks = true, // Add new option
616
+ touches = true, // Nouveau paramètre tactiles
617
+ phantomTraps = true, // NOUVEAU
618
+ honeypots = [],
619
+ trapUrls = [], // Nouveau paramètre pour les URL pièges
620
+ wasmPath, // Nouveau paramètre
621
+ fetch: fetchConfig = {}
622
+ } = config;
623
+
624
+ // Tentative de chargement du WASM si le chemin est fourni
625
+ if (wasmPath) {
626
+ this.initializeWasm(wasmPath);
627
+ }
628
+
629
+ if (mouse) {
630
+ this.startMouseEntropyTracker();
631
+ }
632
+ if (keystrokes) {
633
+ this.startKeystrokeDynamicsTracker();
634
+ }
635
+ if (clicks) {
636
+ this.startClickTracker();
637
+ }
638
+ if (touches) {
639
+ this.startTouchEventTracker();
640
+ }
641
+ if (phantomTraps) {
642
+ this.injectPhantomTraps();
643
+ }
644
+ if (honeypots.length > 0) {
645
+ this.initializeHoneypots(honeypots);
646
+ }
647
+
648
+ // Injection dynamique des liens pièges au démarrage
649
+ if (trapUrls.length > 0) {
650
+ this.injectTrapLinks(trapUrls);
651
+ }
652
+ // On active l'interception si `fetch` est configuré, même avec un objet vide.
653
+ if (config.fetch) {
654
+ this.initializeFetch(fetchConfig.targetDomains);
655
+
656
+ // Ajoute l'intercepteur pour la résolution de challenge
657
+ if (fetchConfig.handleChallenges !== false) {
658
+ this.addFetchInterceptor(async (resource, options, next) => {
659
+ const originalResponse = await next(resource, options);
660
+ // On clone la réponse pour que la lecture du corps par solveChallengeAndRetry ne la consomme pas pour l'appelant original.
661
+ return this.solveChallengeAndRetry(originalResponse.clone(), resource, options);
662
+ });
663
+ }
664
+ }
665
+ },
666
+
667
+ /**
668
+ * Tente de charger et d'initialiser le module WebAssembly pour un hachage plus rapide.
669
+ * Si le chargement échoue, il se rabat silencieusement sur l'implémentation JS.
670
+ * @param {string} wasmPath - Le chemin vers le script de chargement du module WASM (ex: '/fp.js').
671
+ */
672
+ async initializeWasm(wasmPath) {
673
+ try {
674
+ // 1. Injecter le script qui charge le module WASM
675
+ const script = document.createElement('script');
676
+ script.src = wasmPath;
677
+ await new Promise((resolve, reject) => {
678
+ script.onload = resolve;
679
+ script.onerror = reject;
680
+ document.head.appendChild(script);
681
+ });
682
+
683
+ // 2. Attendre que la fonction globale `createFingerprintModule` soit disponible
684
+ if (typeof window.createFingerprintModule !== 'function') {
685
+ throw new Error('WASM loader script did not expose createFingerprintModule.');
686
+ }
687
+
688
+ // 3. Initialiser le module
689
+ const wasmUrl = wasmPath.replace(/\.js$/, '.wasm');
690
+ const wasmModule = await window.createFingerprintModule({
691
+ instantiateWasm: (imports, successCallback) => {
692
+ (async () => {
693
+ try {
694
+ const cached = await getCachedWasm(wasmUrl);
695
+ if (cached) {
696
+ let instance;
697
+ if (cached instanceof WebAssembly.Module) {
698
+ instance = await WebAssembly.instantiate(cached, imports);
699
+ } else {
700
+ const result = await WebAssembly.instantiate(cached, imports);
701
+ instance = result.instance;
702
+ }
703
+ successCallback(instance, cached);
704
+ return;
705
+ }
706
+
707
+ const response = await fetch(wasmUrl);
708
+ const arrayBuffer = await response.arrayBuffer();
709
+
710
+ let cachedData = arrayBuffer;
711
+ let isModuleCached = false;
712
+ try {
713
+ const compiledModule = await WebAssembly.compile(arrayBuffer);
714
+ const success = await cacheWasm(wasmUrl, compiledModule);
715
+ if (success) {
716
+ cachedData = compiledModule;
717
+ isModuleCached = true;
718
+ }
719
+ } catch (e) {
720
+ // Fallback if browser doesn't allow structured cloning of Compiled Modules
721
+ }
722
+
723
+ if (!isModuleCached) {
724
+ await cacheWasm(wasmUrl, arrayBuffer);
725
+ }
726
+
727
+ let instance;
728
+ if (cachedData instanceof WebAssembly.Module) {
729
+ instance = await WebAssembly.instantiate(cachedData, imports);
730
+ } else {
731
+ const result = await WebAssembly.instantiate(arrayBuffer, imports);
732
+ instance = result.instance;
733
+ }
734
+ successCallback(instance, cachedData);
735
+ } catch (err) {
736
+ console.warn('[Fingerprint] Custom WASM instantiation failed, falling back to default Emscripten loader:', err);
737
+ successCallback(null);
738
+ }
739
+ })();
740
+ return {}; // Async instantiation indicator for Emscripten
741
+ }
742
+ });
743
+ if (typeof wasmModule._hash_string !== 'function') {
744
+ throw new Error('WASM module did not export _hash_string.');
745
+ }
746
+ window.wasmModule = wasmModule;
747
+ ClientLibrary.wasmModule = wasmModule;
748
+
749
+ // 4. Remplacer la fonction de hachage par la version WASM
750
+ activeCyrb53 = (str) => {
751
+ // La fonction C++ attend un pointeur, Emscripten gère la conversion
752
+ return wasmModule._hash_string(str);
753
+ };
754
+
755
+ console.log('[Fingerprint] WASM module loaded successfully. Using fast hashing.');
756
+ // NOUVEAU: Ajoute un indicateur à l'empreinte pour que le serveur sache que le WASM est actif.
757
+ if (this._cachedBuilder) {
758
+ this._cachedBuilder.addRaw('wasm', 'true');
759
+ }
760
+ } catch (error) {
761
+ console.warn('[Fingerprint] WASM module failed to load. Falling back to JS implementation. Error:', error);
762
+ }
763
+ }
764
+ };
765
+
766
+ /**
767
+ * @typedef {object} ClientBehaviorMetrics
768
+ * @property {number} mouseEntropy - Entropie des mouvements de la souris.
769
+ * @property {Array<{x: number, y: number, t: number}>} mouseMovementsHistory - Historique des points de la souris.
770
+ * @property {number} keystrokeLatency - Latence moyenne entre les frappes.
771
+ * @property {boolean} honeypotInteraction - Vrai si un honeypot a été touché.
772
+ * @property {Array<{x: number, y: number, t: number, targetId: string}>} clicksHistory - Historique des clics.
773
+ * @property {Array<{x: number, y: number, t: number, p: number, r: number, num: number}>} touchMovementsHistory - Historique des glissements tactiles.
774
+ * @property {number} historyLength - La longueur de l'historique de session du navigateur (`window.history.length`).
775
+ * @property {number} clientTimestamp - Timestamp (Date.now()) de la collecte des métriques.
776
+ * @property {string[]} [trapUrls] - URLs pièges à injecter dynamiquement.
777
+ */
778
+ /** @type {ClientBehaviorMetrics} */
779
+ const metrics = {
780
+ mouseEntropy: 0, // Conservé pour la compatibilité, mais l'analyse se fait maintenant sur l'historique
781
+ mouseMovementsHistory: [],
782
+ touchMovementsHistory: [],
783
+ clicksHistory: [],
784
+ keystrokeLatency: 0,
785
+ honeypotInteraction: false,
786
+ historyLength: 0,
787
+ clientTimestamp: 0,
788
+ };
789
+
790
+ let lastMousePos = { x: 0, y: 0 };
791
+ let mouseMovementsHistory = []; // NOUVEAU: Historique des points de la souris
792
+ let touchMovementsHistory = []; // NOUVEAU: Historique des gestes tactiles
793
+ const TOUCH_HISTORY_MAX = 100;
794
+ const MOUSE_HISTORY_MAX = 100; // Limite le nombre de points stockés
795
+ let clicksHistory = [];
796
+ const CLICKS_HISTORY_MAX = 50;
797
+ let activeHoneypotListeners = new Map(); // Garde une trace des écouteurs actifs
798
+ let keystrokeTimestamps = [];
799
+ let keystrokeLatencies = []; // NOUVEAU: Tableau dédié pour les latences
800
+ const KEYSTROKE_HISTORY_MAX = 20; // On garde l'historique des 20 dernières frappes
801
+
802
+
803
+
804
+ // Exporter les fonctions individuellement pour la compatibilité ascendante
805
+ export const getDeviceFingerprint = ClientLibrary.getDeviceFingerprint.bind(ClientLibrary);
806
+ export const generateRequestSignature = ClientLibrary.generateRequestSignature.bind(ClientLibrary);
807
+ export const generateClientSideSignature = ClientLibrary.generateClientSideSignature.bind(ClientLibrary);
808
+ export const _resetCache = ClientLibrary._resetCache.bind(ClientLibrary);
809
+ export const startMouseEntropyTracker = ClientLibrary.startMouseEntropyTracker.bind(ClientLibrary);
810
+ export const startKeystrokeDynamicsTracker = ClientLibrary.startKeystrokeDynamicsTracker.bind(ClientLibrary);
811
+ export const startClickTracker = ClientLibrary.startClickTracker.bind(ClientLibrary);
812
+ export const startTouchEventTracker = ClientLibrary.startTouchEventTracker.bind(ClientLibrary);
813
+ export const initializeHoneypots = ClientLibrary.initializeHoneypots.bind(ClientLibrary);
814
+ export const getClientBehaviorMetrics = ClientLibrary.getClientBehaviorMetrics.bind(ClientLibrary);
815
+ export const protectedFetch = ClientLibrary.protectedFetch.bind(ClientLibrary);
816
+ export const addFetchInterceptor = ClientLibrary.addFetchInterceptor.bind(ClientLibrary);
817
+ export const patchGlobalFetch = ClientLibrary.patchGlobalFetch.bind(ClientLibrary);
818
+ export const initializeFetch = ClientLibrary.initializeFetch.bind(ClientLibrary);
819
+ export const initializeClient = ClientLibrary.initializeClient.bind(ClientLibrary);
820
+ export const initializeWasm = ClientLibrary.initializeWasm.bind(ClientLibrary);
821
+ export const injectTrapLinks = ClientLibrary.injectTrapLinks.bind(ClientLibrary);
822
+ export const injectPhantomTraps = ClientLibrary.injectPhantomTraps.bind(ClientLibrary);
823
+ export const solveChallengeAndRetry = ClientLibrary.solveChallengeAndRetry.bind(ClientLibrary);
824
+
825
+ // Export the internal object for testing purposes
826
+ export default ClientLibrary;
827
+
828
+ // --- Global Export for Browser ---
829
+ // Attach the library to the window object to make it accessible from inline scripts.
830
+ if (typeof window !== 'undefined') {
831
+ window.ClientLibrary = ClientLibrary;
636
832
  }