@anonympins/fingerprint 0.5.2 → 0.5.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/package.json +1 -1
  3. package/src/js/fingerprint.client.js +1271 -1191
  4. package/src/js/fingerprint.js +202 -108
  5. package/src/js/fingerprint.utils.js +213 -213
  6. package/src/js/library.js +24 -8
  7. package/src/js/mongodb-store.js +165 -79
  8. package/src/js/pow.solver.inline.js +500 -14
  9. package/src/js/pow.solver.js +323 -14
  10. package/src/js/problem-manager.js +1 -1
  11. package/src/js/redis-store.js +114 -42
  12. package/src/js/tests/dns-circuit-breaker.test.js +55 -0
  13. package/src/js/tests/fingerprint.client.init.test.js +143 -143
  14. package/src/js/tests/fingerprint.client.test.js +128 -128
  15. package/src/js/tests/fingerprint.test.js +32 -2
  16. package/src/js/tests/ip-reputation.test.js +1 -1
  17. package/src/js/tests/pow.solver.test.js +5 -2
  18. package/src/js/tests/usefulWorkSolver.test.js +162 -0
  19. package/src/php/Challenge/ChallengeUtils.php +21 -8
  20. package/src/php/FingerprintClient.php +22 -5
  21. package/src/php/FingerprintEngine.php +232 -56
  22. package/src/php/Optimization/Optimization.php +23 -16
  23. package/src/php/Optimization/OptimizationOperators.php +27 -0
  24. package/src/php/ProblemManager.php +1 -1
  25. package/src/php/Store/MongoDbStore.php +184 -104
  26. package/src/php/Store/RedisStore.php +91 -11
  27. package/src/php/Tests/ChallengeUtilsTest.php +285 -285
  28. package/src/php/Tests/DnsCircuitBreakerTest.php +106 -0
  29. package/src/php/Tests/IpReputationTest.php +1 -1
  30. package/src/php/Tests/PowTest.php +1 -1
  31. package/src/php/Tests/RequestUtilsTest.php +29 -0
  32. package/src/php/Tests/TLSClientHelloParserTest.php +177 -117
  33. package/src/php/Utils/BigInt.php +202 -202
  34. package/src/php/Utils/RequestUtils.php +74 -21
  35. package/src/php/Utils/TLSClientHelloParser.php +212 -116
@@ -1,144 +1,144 @@
1
- import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
2
- import {JSDOM} from 'jsdom';
3
- import ClientLibrary from '../fingerprint.client.js';
4
-
5
- // --- Setup JSDOM Environment ---
6
- // Vitest peut être configuré pour le faire automatiquement, mais le faire manuellement
7
- // ici rend le test explicite et portable.
8
- const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
9
- url: 'http://localhost',
10
- });
11
-
12
- // In recent Node.js versions, some global properties like 'navigator', 'performance',
13
- // and 'screen' are read-only. To ensure our JSDOM environment works correctly across
14
- // all versions, we use Object.defineProperty to make these properties writable.
15
- Object.defineProperty(global, 'window', { value: dom.window, writable: true });
16
- Object.defineProperty(global, 'document', { value: dom.window.document, writable: true });
17
- Object.defineProperty(global, 'navigator', { value: dom.window.navigator, writable: true });
18
- Object.defineProperty(global, 'screen', { value: dom.window.screen, writable: true });
19
- Object.defineProperty(global, 'performance', { value: dom.window.performance, writable: true });
20
-
21
- global.fetch = vi.fn(); // Mock global fetch
22
- global.Headers = dom.window.Headers;
23
- global.Request = dom.window.Request;
24
- global.URL = dom.window.URL;
25
- global.TextEncoder = dom.window.TextEncoder;
26
-
27
-
28
- describe('ClientLibrary.initializeClient', () => {
29
-
30
- // On utilise des espions (spies) pour vérifier si les méthodes internes sont appelées.
31
- let startMouseSpy, startKeystrokeSpy, startClickSpy, startTouchSpy, startRenderingSpy, initWasmSpy, initHoneypotsSpy, injectTrapsSpy, initFetchSpy, injectPhantomTrapsSpy;
32
-
33
- beforeEach(() => {
34
- // Réinitialiser l'état du client avant chaque test
35
- ClientLibrary._resetCache();
36
-
37
- // Créer les espions sur les méthodes internes
38
- startMouseSpy = vi.spyOn(ClientLibrary, 'startMouseEntropyTracker');
39
- startKeystrokeSpy = vi.spyOn(ClientLibrary, 'startKeystrokeDynamicsTracker');
40
- startClickSpy = vi.spyOn(ClientLibrary, 'startClickTracker');
41
- startTouchSpy = vi.spyOn(ClientLibrary, 'startTouchEventTracker');
42
- startRenderingSpy = vi.spyOn(ClientLibrary, 'startRenderingTracker');
43
- initWasmSpy = vi.spyOn(ClientLibrary, 'initializeWasm').mockResolvedValue(undefined);
44
- initHoneypotsSpy = vi.spyOn(ClientLibrary, 'initializeHoneypots');
45
- injectTrapsSpy = vi.spyOn(ClientLibrary, 'injectTrapLinks');
46
- initFetchSpy = vi.spyOn(ClientLibrary, 'initializeFetch');
47
- injectPhantomTrapsSpy = vi.spyOn(ClientLibrary, 'injectPhantomTraps');
48
- });
49
-
50
- afterEach(() => {
51
- // Restaurer les espions après chaque test pour ne pas affecter les autres tests
52
- vi.restoreAllMocks();
53
- });
54
-
55
- it('should enable all trackers by default', () => {
56
- ClientLibrary.initializeClient();
57
-
58
- expect(startMouseSpy).toHaveBeenCalled();
59
- expect(startKeystrokeSpy).toHaveBeenCalled();
60
- expect(startClickSpy).toHaveBeenCalled();
61
- expect(startTouchSpy).toHaveBeenCalled();
62
- expect(startRenderingSpy).toHaveBeenCalled();
63
- expect(injectPhantomTrapsSpy).toHaveBeenCalled();
64
- });
65
-
66
- it('should disable trackers when configured', () => {
67
- ClientLibrary.initializeClient({ mouse: false, keystrokes: false, clicks: false, touches: false, rendering: false });
68
-
69
- expect(startMouseSpy).not.toHaveBeenCalled();
70
- expect(startKeystrokeSpy).not.toHaveBeenCalled();
71
- expect(startClickSpy).not.toHaveBeenCalled();
72
- expect(startTouchSpy).not.toHaveBeenCalled();
73
- expect(startRenderingSpy).not.toHaveBeenCalled();
74
- });
75
-
76
- it('should initialize WASM if wasmPath is configured', () => {
77
- ClientLibrary.initializeClient({ wasmPath: '/fp.js' });
78
-
79
- expect(initWasmSpy).toHaveBeenCalledWith('/fp.js');
80
- });
81
-
82
- it('should disable phantom traps when configured', () => {
83
- ClientLibrary.initializeClient({ phantomTraps: false });
84
-
85
- expect(injectPhantomTrapsSpy).not.toHaveBeenCalled();
86
- });
87
-
88
- it('should initialize honeypots with the provided field names', () => {
89
- const honeypotFields = ['email_confirm', 'user_nickname'];
90
- ClientLibrary.initializeClient({ honeypots: honeypotFields });
91
-
92
- expect(initHoneypotsSpy).toHaveBeenCalledWith(honeypotFields);
93
- });
94
-
95
- it('should not initialize honeypots if the array is empty', () => {
96
- ClientLibrary.initializeClient({ honeypots: [] });
97
-
98
- expect(initHoneypotsSpy).not.toHaveBeenCalled();
99
- });
100
-
101
- it('should inject trap URLs when provided', () => {
102
- const urls = ['/trap1?sig=123', '/trap2?sig=456'];
103
- ClientLibrary.initializeClient({ trapUrls: urls });
104
-
105
- expect(injectTrapsSpy).toHaveBeenCalledWith(urls);
106
- });
107
-
108
- it('should not inject trap URLs if the array is empty', () => {
109
- ClientLibrary.initializeClient({ trapUrls: [] });
110
-
111
- expect(injectTrapsSpy).not.toHaveBeenCalled();
112
- });
113
-
114
- it('should initialize fetch interception when fetch config is present', () => {
115
- const targetDomains = ['api.example.com'];
116
- ClientLibrary.initializeClient({ fetch: { targetDomains } });
117
-
118
- expect(initFetchSpy).toHaveBeenCalledWith(targetDomains);
119
- });
120
-
121
- it('should not initialize fetch interception if fetch config is absent', () => {
122
- ClientLibrary.initializeClient(); // No fetch config
123
-
124
- expect(initFetchSpy).not.toHaveBeenCalled();
125
- });
126
-
127
- it('should call all initializers correctly when a full config is provided', () => {
128
- const config = {
129
- mouse: true,
130
- keystrokes: true,
131
- honeypots: ['field1'],
132
- trapUrls: ['/trap1'],
133
- fetch: { targetDomains: ['api.com'] }
134
- };
135
- ClientLibrary.initializeClient(config);
136
-
137
- expect(startMouseSpy).toHaveBeenCalled();
138
- expect(startKeystrokeSpy).toHaveBeenCalled();
139
- expect(initHoneypotsSpy).toHaveBeenCalledWith(config.honeypots);
140
- expect(injectTrapsSpy).toHaveBeenCalledWith(config.trapUrls);
141
- expect(initFetchSpy).toHaveBeenCalledWith(config.fetch.targetDomains);
142
- });
143
-
1
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
2
+ import {JSDOM} from 'jsdom';
3
+ import ClientLibrary from '../fingerprint.client.js';
4
+
5
+ // --- Setup JSDOM Environment ---
6
+ // Vitest peut être configuré pour le faire automatiquement, mais le faire manuellement
7
+ // ici rend le test explicite et portable.
8
+ const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
9
+ url: 'http://localhost',
10
+ });
11
+
12
+ // In recent Node.js versions, some global properties like 'navigator', 'performance',
13
+ // and 'screen' are read-only. To ensure our JSDOM environment works correctly across
14
+ // all versions, we use Object.defineProperty to make these properties writable.
15
+ Object.defineProperty(global, 'window', { value: dom.window, writable: true });
16
+ Object.defineProperty(global, 'document', { value: dom.window.document, writable: true });
17
+ Object.defineProperty(global, 'navigator', { value: dom.window.navigator, writable: true });
18
+ Object.defineProperty(global, 'screen', { value: dom.window.screen, writable: true });
19
+ Object.defineProperty(global, 'performance', { value: dom.window.performance, writable: true });
20
+
21
+ global.fetch = vi.fn(); // Mock global fetch
22
+ global.Headers = dom.window.Headers;
23
+ global.Request = dom.window.Request;
24
+ global.URL = dom.window.URL;
25
+ global.TextEncoder = dom.window.TextEncoder;
26
+
27
+
28
+ describe('ClientLibrary.initializeClient', () => {
29
+
30
+ // On utilise des espions (spies) pour vérifier si les méthodes internes sont appelées.
31
+ let startMouseSpy, startKeystrokeSpy, startClickSpy, startTouchSpy, startRenderingSpy, initWasmSpy, initHoneypotsSpy, injectTrapsSpy, initFetchSpy, injectPhantomTrapsSpy;
32
+
33
+ beforeEach(() => {
34
+ // Réinitialiser l'état du client avant chaque test
35
+ ClientLibrary._resetCache();
36
+
37
+ // Créer les espions sur les méthodes internes
38
+ startMouseSpy = vi.spyOn(ClientLibrary, 'startMouseEntropyTracker');
39
+ startKeystrokeSpy = vi.spyOn(ClientLibrary, 'startKeystrokeDynamicsTracker');
40
+ startClickSpy = vi.spyOn(ClientLibrary, 'startClickTracker');
41
+ startTouchSpy = vi.spyOn(ClientLibrary, 'startTouchEventTracker');
42
+ startRenderingSpy = vi.spyOn(ClientLibrary, 'startRenderingTracker');
43
+ initWasmSpy = vi.spyOn(ClientLibrary, 'initializeWasm').mockResolvedValue(undefined);
44
+ initHoneypotsSpy = vi.spyOn(ClientLibrary, 'initializeHoneypots');
45
+ injectTrapsSpy = vi.spyOn(ClientLibrary, 'injectTrapLinks');
46
+ initFetchSpy = vi.spyOn(ClientLibrary, 'initializeFetch');
47
+ injectPhantomTrapsSpy = vi.spyOn(ClientLibrary, 'injectPhantomTraps');
48
+ });
49
+
50
+ afterEach(() => {
51
+ // Restaurer les espions après chaque test pour ne pas affecter les autres tests
52
+ vi.restoreAllMocks();
53
+ });
54
+
55
+ it('should enable all trackers by default', () => {
56
+ ClientLibrary.initializeClient();
57
+
58
+ expect(startMouseSpy).toHaveBeenCalled();
59
+ expect(startKeystrokeSpy).toHaveBeenCalled();
60
+ expect(startClickSpy).toHaveBeenCalled();
61
+ expect(startTouchSpy).toHaveBeenCalled();
62
+ expect(startRenderingSpy).toHaveBeenCalled();
63
+ expect(injectPhantomTrapsSpy).toHaveBeenCalled();
64
+ });
65
+
66
+ it('should disable trackers when configured', () => {
67
+ ClientLibrary.initializeClient({ mouse: false, keystrokes: false, clicks: false, touches: false, rendering: false });
68
+
69
+ expect(startMouseSpy).not.toHaveBeenCalled();
70
+ expect(startKeystrokeSpy).not.toHaveBeenCalled();
71
+ expect(startClickSpy).not.toHaveBeenCalled();
72
+ expect(startTouchSpy).not.toHaveBeenCalled();
73
+ expect(startRenderingSpy).not.toHaveBeenCalled();
74
+ });
75
+
76
+ it('should initialize WASM if wasmPath is configured', () => {
77
+ ClientLibrary.initializeClient({ wasmPath: '/fp.js' });
78
+
79
+ expect(initWasmSpy).toHaveBeenCalledWith('/fp.js');
80
+ });
81
+
82
+ it('should disable phantom traps when configured', () => {
83
+ ClientLibrary.initializeClient({ phantomTraps: false });
84
+
85
+ expect(injectPhantomTrapsSpy).not.toHaveBeenCalled();
86
+ });
87
+
88
+ it('should initialize honeypots with the provided field names', () => {
89
+ const honeypotFields = ['email_confirm', 'user_nickname'];
90
+ ClientLibrary.initializeClient({ honeypots: honeypotFields });
91
+
92
+ expect(initHoneypotsSpy).toHaveBeenCalledWith(honeypotFields);
93
+ });
94
+
95
+ it('should not initialize honeypots if the array is empty', () => {
96
+ ClientLibrary.initializeClient({ honeypots: [] });
97
+
98
+ expect(initHoneypotsSpy).not.toHaveBeenCalled();
99
+ });
100
+
101
+ it('should inject trap URLs when provided', () => {
102
+ const urls = ['/trap1?sig=123', '/trap2?sig=456'];
103
+ ClientLibrary.initializeClient({ trapUrls: urls });
104
+
105
+ expect(injectTrapsSpy).toHaveBeenCalledWith(urls);
106
+ });
107
+
108
+ it('should not inject trap URLs if the array is empty', () => {
109
+ ClientLibrary.initializeClient({ trapUrls: [] });
110
+
111
+ expect(injectTrapsSpy).not.toHaveBeenCalled();
112
+ });
113
+
114
+ it('should initialize fetch interception when fetch config is present', () => {
115
+ const targetDomains = ['api.example.com'];
116
+ ClientLibrary.initializeClient({ fetch: { targetDomains } });
117
+
118
+ expect(initFetchSpy).toHaveBeenCalledWith(targetDomains);
119
+ });
120
+
121
+ it('should not initialize fetch interception if fetch config is absent', () => {
122
+ ClientLibrary.initializeClient(); // No fetch config
123
+
124
+ expect(initFetchSpy).not.toHaveBeenCalled();
125
+ });
126
+
127
+ it('should call all initializers correctly when a full config is provided', () => {
128
+ const config = {
129
+ mouse: true,
130
+ keystrokes: true,
131
+ honeypots: ['field1'],
132
+ trapUrls: ['/trap1'],
133
+ fetch: { targetDomains: ['api.com'] }
134
+ };
135
+ ClientLibrary.initializeClient(config);
136
+
137
+ expect(startMouseSpy).toHaveBeenCalled();
138
+ expect(startKeystrokeSpy).toHaveBeenCalled();
139
+ expect(initHoneypotsSpy).toHaveBeenCalledWith(config.honeypots);
140
+ expect(injectTrapsSpy).toHaveBeenCalledWith(config.trapUrls);
141
+ expect(initFetchSpy).toHaveBeenCalledWith(config.fetch.targetDomains);
142
+ });
143
+
144
144
  });
@@ -1,129 +1,129 @@
1
- /**
2
- * @vitest-environment jsdom
3
- */
4
-
5
- import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
6
- import ClientLibrary from '../fingerprint.client.js';
7
-
8
- describe('ClientLibrary WASM Integration', () => {
9
- beforeEach(() => {
10
- // Réinitialise le cache et les mocks avant chaque test
11
- ClientLibrary._resetCache();
12
- vi.spyOn(console, 'log').mockImplementation(() => {});
13
- vi.spyOn(console, 'warn').mockImplementation(() => {});
14
-
15
- // Supprime les mocks globaux pour éviter les fuites entre les tests
16
- delete window.createFingerprintModule;
17
- });
18
-
19
- afterEach(() => {
20
- vi.restoreAllMocks();
21
- });
22
-
23
- it('should successfully load WASM module and switch hasher', async () => {
24
- // 1. Simuler un module WASM fonctionnel
25
- const mockWasmModule = {
26
- _hash_string: vi.fn((str) => 99999), // Un mock qui retourne une valeur distincte
27
- };
28
-
29
- // 2. Simuler le chargement du script et l'initialisation du module
30
- // On attache les fonctions de simulation à `window` car c'est ce que le code cherche
31
- window.createFingerprintModule = vi.fn().mockResolvedValue(mockWasmModule);
32
-
33
- // On simule l'injection du script en appelant directement `onload`
34
- vi.spyOn(document.head, 'appendChild').mockImplementation((script) => {
35
- // Simule le chargement réussi du script
36
- script.onload();
37
- return script;
38
- });
39
-
40
- // 3. Appeler la fonction d'initialisation
41
- await ClientLibrary.initializeWasm('/fake/path/to/fp.js');
42
-
43
- // 4. Vérifier que le hasher a été remplacé
44
- const wasmHash = ClientLibrary._hasher("test");
45
- expect(wasmHash).toBe(99999);
46
- expect(mockWasmModule._hash_string).toHaveBeenCalledWith("test");
47
- expect(console.log).toHaveBeenCalledWith(expect.stringContaining('WASM module loaded successfully'));
48
- });
49
-
50
- it('should gracefully fall back to JS hasher if WASM module fails to load', async () => {
51
- // 1. Simuler un échec de chargement du script
52
- vi.spyOn(document.head, 'appendChild').mockImplementation((script) => {
53
- script.onerror(new Error('Script loading failed'));
54
- return script;
55
- });
56
-
57
- // 2. Appeler la fonction d'initialisation
58
- await ClientLibrary.initializeWasm('/fake/path/to/fp.js');
59
-
60
- // 3. Vérifier que le hasher est toujours l'implémentation JS
61
- const jsHash = ClientLibrary._hasher("test");
62
- const originalJsHash = (await import('../fingerprint.builder.js')).cyrb53("test");
63
-
64
- expect(jsHash).toBe(originalJsHash);
65
- expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('WASM module failed to load'), expect.any(Error));
66
- });
67
-
68
- it('should gracefully fall back if WASM module does not export _hash_string', async () => {
69
- // 1. Simuler un module WASM malformé (sans la fonction attendue)
70
- const mockWasmModule = {};
71
- window.createFingerprintModule = vi.fn().mockResolvedValue(mockWasmModule);
72
-
73
- vi.spyOn(document.head, 'appendChild').mockImplementation((script) => {
74
- script.onload();
75
- return script;
76
- });
77
-
78
- // 2. Appeler la fonction d'initialisation
79
- await ClientLibrary.initializeWasm('/fake/path/to/fp.js');
80
-
81
- // 3. Vérifier le fallback
82
- const jsHash = ClientLibrary._hasher("test");
83
- const originalJsHash = (await import('../fingerprint.builder.js')).cyrb53("test");
84
- expect(jsHash).toBe(originalJsHash);
85
- // L'assertion est maintenant plus précise : elle vérifie le message générique ET le message d'erreur spécifique.
86
- expect(console.warn).toHaveBeenCalledWith(
87
- expect.stringContaining('WASM module failed to load'),
88
- expect.objectContaining({ message: 'WASM module did not export _hash_string.' })
89
- );
90
- });
91
-
92
- it('should successfully load raw WASM and use standalone polymorphic hasher', async () => {
93
- const mockWasmInstance = {
94
- exports: {
95
- memory: { buffer: new ArrayBuffer(65536) },
96
- hash: vi.fn().mockReturnValue(123456)
97
- }
98
- };
99
-
100
- global.WebAssembly = {
101
- compile: vi.fn().mockResolvedValue({}),
102
- instantiate: vi.fn().mockResolvedValue(mockWasmInstance)
103
- };
104
-
105
- global.fetch = vi.fn().mockResolvedValue({
106
- arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(100))
107
- });
108
-
109
- await ClientLibrary.initializeWasm('/fp.wasm');
110
-
111
- const hash = ClientLibrary._hasher("test");
112
- expect(hash).toBe(123456);
113
- expect(mockWasmInstance.exports.hash).toHaveBeenCalledWith(0, 4);
114
- });
115
-
116
- it('should use the default JS hasher if WASM is not configured', async () => {
117
- // Ensure no WASM path is provided in the config
118
- ClientLibrary.initializeClient({});
119
-
120
- // Verify that the active hasher is the original JS implementation
121
- const jsHash = ClientLibrary._hasher("another test string");
122
- const originalJsHash = (await import('../fingerprint.builder.js')).cyrb53("another test string");
123
-
124
- expect(jsHash).toBe(originalJsHash);
125
- // Ensure no WASM-related console logs or warnings were made
126
- expect(console.log).not.toHaveBeenCalledWith(expect.stringContaining('WASM module loaded successfully'));
127
- expect(console.warn).not.toHaveBeenCalledWith(expect.stringContaining('WASM module failed to load'));
128
- });
1
+ /**
2
+ * @vitest-environment jsdom
3
+ */
4
+
5
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
6
+ import ClientLibrary from '../fingerprint.client.js';
7
+
8
+ describe('ClientLibrary WASM Integration', () => {
9
+ beforeEach(() => {
10
+ // Réinitialise le cache et les mocks avant chaque test
11
+ ClientLibrary._resetCache();
12
+ vi.spyOn(console, 'log').mockImplementation(() => {});
13
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
14
+
15
+ // Supprime les mocks globaux pour éviter les fuites entre les tests
16
+ delete window.createFingerprintModule;
17
+ });
18
+
19
+ afterEach(() => {
20
+ vi.restoreAllMocks();
21
+ });
22
+
23
+ it('should successfully load WASM module and switch hasher', async () => {
24
+ // 1. Simuler un module WASM fonctionnel
25
+ const mockWasmModule = {
26
+ _hash_string: vi.fn((str) => 99999), // Un mock qui retourne une valeur distincte
27
+ };
28
+
29
+ // 2. Simuler le chargement du script et l'initialisation du module
30
+ // On attache les fonctions de simulation à `window` car c'est ce que le code cherche
31
+ window.createFingerprintModule = vi.fn().mockResolvedValue(mockWasmModule);
32
+
33
+ // On simule l'injection du script en appelant directement `onload`
34
+ vi.spyOn(document.head, 'appendChild').mockImplementation((script) => {
35
+ // Simule le chargement réussi du script
36
+ script.onload();
37
+ return script;
38
+ });
39
+
40
+ // 3. Appeler la fonction d'initialisation
41
+ await ClientLibrary.initializeWasm('/fake/path/to/fp.js');
42
+
43
+ // 4. Vérifier que le hasher a été remplacé
44
+ const wasmHash = ClientLibrary._hasher("test");
45
+ expect(wasmHash).toBe(99999);
46
+ expect(mockWasmModule._hash_string).toHaveBeenCalledWith("test");
47
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('WASM module loaded successfully'));
48
+ });
49
+
50
+ it('should gracefully fall back to JS hasher if WASM module fails to load', async () => {
51
+ // 1. Simuler un échec de chargement du script
52
+ vi.spyOn(document.head, 'appendChild').mockImplementation((script) => {
53
+ script.onerror(new Error('Script loading failed'));
54
+ return script;
55
+ });
56
+
57
+ // 2. Appeler la fonction d'initialisation
58
+ await ClientLibrary.initializeWasm('/fake/path/to/fp.js');
59
+
60
+ // 3. Vérifier que le hasher est toujours l'implémentation JS
61
+ const jsHash = ClientLibrary._hasher("test");
62
+ const originalJsHash = (await import('../fingerprint.builder.js')).cyrb53("test");
63
+
64
+ expect(jsHash).toBe(originalJsHash);
65
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('WASM module failed to load'), expect.any(Error));
66
+ });
67
+
68
+ it('should gracefully fall back if WASM module does not export _hash_string', async () => {
69
+ // 1. Simuler un module WASM malformé (sans la fonction attendue)
70
+ const mockWasmModule = {};
71
+ window.createFingerprintModule = vi.fn().mockResolvedValue(mockWasmModule);
72
+
73
+ vi.spyOn(document.head, 'appendChild').mockImplementation((script) => {
74
+ script.onload();
75
+ return script;
76
+ });
77
+
78
+ // 2. Appeler la fonction d'initialisation
79
+ await ClientLibrary.initializeWasm('/fake/path/to/fp.js');
80
+
81
+ // 3. Vérifier le fallback
82
+ const jsHash = ClientLibrary._hasher("test");
83
+ const originalJsHash = (await import('../fingerprint.builder.js')).cyrb53("test");
84
+ expect(jsHash).toBe(originalJsHash);
85
+ // L'assertion est maintenant plus précise : elle vérifie le message générique ET le message d'erreur spécifique.
86
+ expect(console.warn).toHaveBeenCalledWith(
87
+ expect.stringContaining('WASM module failed to load'),
88
+ expect.objectContaining({ message: 'WASM module did not export _hash_string.' })
89
+ );
90
+ });
91
+
92
+ it('should successfully load raw WASM and use standalone polymorphic hasher', async () => {
93
+ const mockWasmInstance = {
94
+ exports: {
95
+ memory: { buffer: new ArrayBuffer(65536) },
96
+ hash: vi.fn().mockReturnValue(123456)
97
+ }
98
+ };
99
+
100
+ global.WebAssembly = {
101
+ compile: vi.fn().mockResolvedValue({}),
102
+ instantiate: vi.fn().mockResolvedValue(mockWasmInstance)
103
+ };
104
+
105
+ global.fetch = vi.fn().mockResolvedValue({
106
+ arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(100))
107
+ });
108
+
109
+ await ClientLibrary.initializeWasm('/fp.wasm');
110
+
111
+ const hash = ClientLibrary._hasher("test");
112
+ expect(hash).toBe(123456);
113
+ expect(mockWasmInstance.exports.hash).toHaveBeenCalledWith(0, 4);
114
+ });
115
+
116
+ it('should use the default JS hasher if WASM is not configured', async () => {
117
+ // Ensure no WASM path is provided in the config
118
+ ClientLibrary.initializeClient({});
119
+
120
+ // Verify that the active hasher is the original JS implementation
121
+ const jsHash = ClientLibrary._hasher("another test string");
122
+ const originalJsHash = (await import('../fingerprint.builder.js')).cyrb53("another test string");
123
+
124
+ expect(jsHash).toBe(originalJsHash);
125
+ // Ensure no WASM-related console logs or warnings were made
126
+ expect(console.log).not.toHaveBeenCalledWith(expect.stringContaining('WASM module loaded successfully'));
127
+ expect(console.warn).not.toHaveBeenCalledWith(expect.stringContaining('WASM module failed to load'));
128
+ });
129
129
  });
@@ -31,6 +31,7 @@ const {
31
31
  default_whitelist,
32
32
  stopThresholdAutoTuning,
33
33
  getCompositeDeviceHash,
34
+ sanitizeTrafficData,
34
35
  } = fingerprint;
35
36
  const { store, getRequestPatternScore, getDeviceHash } = __internal;
36
37
  const { getRenderingAnomalyScore } = __internal;
@@ -1083,6 +1084,35 @@ describe('Fingerprint & PoW Security Suite', () => {
1083
1084
  describe('Threshold Auto-Tuning', () => {
1084
1085
  let setIntervalSpy, clearIntervalSpy, consoleLogSpy;
1085
1086
 
1087
+ test('should sanitize traffic data based on stable hardware cluster', async () => {
1088
+ const trafficData = [];
1089
+ // Attacker rotating IPs and deviceIds but having the same hardware fingerprint
1090
+ for (let i = 0; i < 100; i++) {
1091
+ trafficData.push({
1092
+ type: 'trap_triggered',
1093
+ deviceId: `attacker-dev-${i}`,
1094
+ clientIp: `192.168.1.${i}`,
1095
+ fingerprint: 'gpu:spoofed-nvidia-gpu|cvs:spoofed-canvas-data'
1096
+ });
1097
+ }
1098
+
1099
+ // Unique legit users
1100
+ for (let i = 0; i < 10; i++) {
1101
+ trafficData.push({
1102
+ type: 'challenge_solved',
1103
+ deviceId: `legit-dev-${i}`,
1104
+ clientIp: `10.0.0.${i}`,
1105
+ fingerprint: `gpu:legit-gpu-${i}|cvs:legit-canvas-${i}`
1106
+ });
1107
+ }
1108
+
1109
+ const sanitized = sanitizeTrafficData(trafficData);
1110
+ const attackerLogs = sanitized.filter(log => log.deviceId.startsWith('attacker-dev-'));
1111
+
1112
+ // Total 110 logs. 2% limit = Math.max(3, 2) = 3.
1113
+ expect(attackerLogs.length).toBeLessThanOrEqual(3);
1114
+ });
1115
+
1086
1116
  beforeEach(() => {
1087
1117
  setIntervalSpy = vi.spyOn(global, 'setInterval');
1088
1118
  clearIntervalSpy = vi.spyOn(global, 'clearInterval');
@@ -2305,9 +2335,9 @@ describe('Subnet Scoring (Node.js)', () => {
2305
2335
  // The new version handles other prefixes
2306
2336
  expect(getIpSubnet('10.20.30.40', 16)).toBe('10.20.0.0/16');
2307
2337
  // IPv6
2308
- expect(getIpSubnet('2001:db8:abcd:0012:0000:0000:0000:0001', 48)).toBe('2001:db8:abcd:0:0:0:0:0/48');
2338
+ expect(getIpSubnet('2001:db8:abcd:0012:0000:0000:0000:0001', 48)).toBe('2001:0db8:abcd:0000:0000:0000:0000:0000/48');
2309
2339
  // The new version handles other prefixes
2310
- expect(getIpSubnet('2a01:e0a:129:57c0:a1b2:c3d4:e5f6:a7b8', 64)).toBe('2a01:e0a:129:0:0:0:0:0/48');
2340
+ expect(getIpSubnet('2a01:e0a:129:57c0:a1b2:c3d4:e5f6:a7b8', 64)).toBe('2a01:0e0a:0129:0000:0000:0000:0000:0000/48');
2311
2341
  // Invalid IPs
2312
2342
  expect(getIpSubnet('not-an-ip')).toBeNull();
2313
2343
  });
@@ -96,7 +96,7 @@ describe('IP Reputation Local System (Node.js)', () => {
96
96
  expect(ipv4Subnet).toBe('192.168.1.0/24');
97
97
 
98
98
  const ipv6Subnet = __internal.getIpSubnet('2001:db8:abcd:12::1', 24, 48);
99
- expect(ipv6Subnet).toBe('2001:db8:abcd:0:0:0:0:0/48');
99
+ expect(ipv6Subnet).toBe('2001:0db8:abcd:0000:0000:0000:0000:0000/48');
100
100
  });
101
101
 
102
102
  it('should calculate client hints inconsistency score correctly', async () => {
@@ -223,9 +223,12 @@ describe('Proof-of-Work Solvers', () => {
223
223
  const seed = 'test-wasm-seed';
224
224
  const difficulty = 4; // 4 MB
225
225
 
226
- const solution = await solveMemory(seed, difficulty);
226
+ const result = await solveMemory(seed, difficulty);
227
227
 
228
- expect(solution).toBe(777);
228
+ expect(result).toBeInstanceOf(Object);
229
+ expect(result.solution).toBe(777);
230
+ expect(result.merkleRoot).toBeDefined();
231
+ expect(result.proofs).toBeDefined();
229
232
  expect(mockWasmModule._malloc).toHaveBeenCalledTimes(1);
230
233
  expect(mockWasmModule._free).toHaveBeenCalledTimes(1);
231
234
  expect(mockWasmModule._solve_memory_challenge).toHaveBeenCalledWith(1234, difficulty);