@anonympins/fingerprint 0.3.2 → 0.3.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 (51) hide show
  1. package/CHANGELOG.md +193 -0
  2. package/README.md +1080 -834
  3. package/composer.json +39 -0
  4. package/index.js +5 -0
  5. package/package.json +31 -23
  6. package/phpunit.xml +21 -0
  7. package/public/fp.js +2 -0
  8. package/src/js/build-client.js +69 -0
  9. package/{fingerprint.builder.js → src/js/fingerprint.builder.js} +168 -175
  10. package/{fingerprint.client.js → src/js/fingerprint.client.js} +634 -538
  11. package/src/js/fingerprint.client.obfuscated.js +1 -0
  12. package/{fingerprint.js → src/js/fingerprint.js} +3733 -3294
  13. package/{library.js → src/js/library.js} +1729 -1729
  14. package/{problem-manager.js → src/js/problem-manager.js} +539 -522
  15. package/src/php/AutoTuner.php +155 -0
  16. package/src/php/Challenge/ChallengeUtils.php +306 -0
  17. package/src/php/Config/SecurityProfiles.php +267 -0
  18. package/src/php/DirectFingerprint.php +81 -0
  19. package/src/php/FingerprintBuilder.php +186 -0
  20. package/src/php/FingerprintClient.php +132 -0
  21. package/src/php/FingerprintEngine.php +863 -0
  22. package/src/php/Optimization/FunctionRegistry.php +63 -0
  23. package/src/php/Optimization/Optimization.php +256 -0
  24. package/src/php/Optimization/OptimizationOperators.php +305 -0
  25. package/src/php/Optimization/ProblemInitializers.php +53 -0
  26. package/src/php/ProblemManager.php +255 -0
  27. package/src/php/RequestContext.php +91 -0
  28. package/src/php/Store/IStore.php +42 -0
  29. package/src/php/Store/InMemoryStore.php +67 -0
  30. package/src/php/Store/StoreManager.php +36 -0
  31. package/src/php/Tests/ChallengeUtilsTest.php +82 -0
  32. package/src/php/Tests/FingerprintBuilderTest.php +58 -0
  33. package/src/php/Tests/FingerprintEngineTest.php +300 -0
  34. package/src/php/Tests/IpReputationTest.php +157 -0
  35. package/src/php/Tests/PowTest.php +40 -0
  36. package/src/php/Tests/ProblemManagerTest.php +295 -0
  37. package/src/php/Tests/RequestUtilsTest.php +81 -0
  38. package/src/php/Tests/problems.config.json +9 -0
  39. package/src/php/Utils/BigInt.php +145 -0
  40. package/src/php/Utils/BlockList.php +100 -0
  41. package/src/php/Utils/Logger.php +30 -0
  42. package/src/php/Utils/MaliciousPatterns.php +59 -0
  43. package/src/php/Utils/RequestUtils.php +962 -0
  44. package/fingerprint.client.obfuscated.js +0 -1
  45. /package/{mongodb-store.js → src/js/mongodb-store.js} +0 -0
  46. /package/{optimization.worker.js → src/js/optimization.worker.js} +0 -0
  47. /package/{pow.solver.inline.js → src/js/pow.solver.inline.js} +0 -0
  48. /package/{pow.solver.js → src/js/pow.solver.js} +0 -0
  49. /package/{pow.worker.js → src/js/pow.worker.js} +0 -0
  50. /package/{redis-store.js → src/js/redis-store.js} +0 -0
  51. /package/{sql-store.js → src/js/sql-store.js} +0 -0
@@ -0,0 +1,267 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint\Config;
6
+
7
+ /**
8
+ * Définit les profils de sécurité prédéfinis pour la bibliothèque Fingerprint.
9
+ * Ces profils contiennent les poids des scores de suspicion et les seuils de déclenchement.
10
+ */
11
+ class SecurityProfiles
12
+ {
13
+ /**
14
+ * @var array<string, array<string, mixed>>
15
+ */
16
+ public const PROFILES = [
17
+ /**
18
+ * Balanced Profile (Default)
19
+ * A general-purpose configuration suitable for most websites, offering a good mix of security and user experience.
20
+ * It's sensitive enough to catch common bots without being overly aggressive towards legitimate users.
21
+ */
22
+ 'balanced' => [
23
+ 'summary' => 'Balanced Profile (Default)',
24
+ 'description' => 'A general-purpose configuration suitable for most websites, offering a good mix of security and user experience. It\'s sensitive enough to catch common bots without being overly aggressive towards legitimate users.',
25
+ 'weights' => [
26
+ 'historyScore' => 0.3,
27
+ 'rotationScore' => 0.5,
28
+ 'headerAnomalyScore' => 0.1,
29
+ 'requestPatternScore' => 0.6,
30
+ 'inconsistencyScore' => 0.8,
31
+ 'behaviorScore' => 0.7,
32
+ 'honeypotScore' => 1.0,
33
+ 'crossLayerInconsistencyScore' => 0.4,
34
+ 'timeInconsistencyScore' => 0.9,
35
+ 'tlsSpoofingScore' => 0.8,
36
+ 'botScore' => 1.0, // Poids pour le score de bot explicite
37
+ 'cookieDroppingScore' => 0.9, // Pénalité élevée pour la suppression de cookies
38
+ 'threatIntelScore' => 0.4, // Poids pour le renseignement sur les menaces (ex: IP de proxy connu)
39
+ 'clientHintsInconsistencyScore' => 0.7, // Penalizes inconsistency between User-Agent and Client-Hints
40
+ 'clickVarianceScore' => 0.6, // Poids pour la variance des clics
41
+ 'subnetScore' => 0.5, // Pénalise les sous-réseaux IP avec une activité suspecte agrégée
42
+ ],
43
+ 'thresholds' => ['low' => 20, 'medium' => 45, 'high' => 75, 'block' => 95],
44
+ 'patterns' => [
45
+ 'velocityThreshold' => 800,
46
+ 'burstThreshold' => 1500,
47
+ 'scrapeThreshold' => 1000,
48
+ 'historySize' => 10,
49
+ 'minSamples' => 5,
50
+ 'regularityThreshold' => 50,
51
+ 'benfordThreshold' => 0.15,
52
+ 'patternWeight' => 80,
53
+ 'decayFactor' => 0.9,
54
+ 'inactivityReset' => 5000,
55
+ ],
56
+ ],
57
+
58
+ /**
59
+ * Strict Profile
60
+ * An aggressive configuration for sensitive applications (e.g., financial services, admin panels).
61
+ * It uses lower suspicion thresholds and higher penalties for anomalies, prioritizing security over user convenience.
62
+ * All new devices are challenged by default.
63
+ */
64
+ 'strict' => [
65
+ 'summary' => 'Strict Profile',
66
+ 'description' => 'An aggressive configuration for sensitive applications (e.g., financial services, admin panels). It uses lower suspicion thresholds and higher penalties for anomalies, prioritizing security over user convenience. All new devices are challenged by default.',
67
+ 'weights' => [
68
+ 'historyScore' => 0.4,
69
+ 'rotationScore' => 0.6,
70
+ 'headerAnomalyScore' => 0.2,
71
+ 'requestPatternScore' => 0.8,
72
+ 'inconsistencyScore' => 1.0,
73
+ 'behaviorScore' => 0.8,
74
+ 'honeypotScore' => 1.0,
75
+ 'crossLayerInconsistencyScore' => 0.6,
76
+ 'timeInconsistencyScore' => 1.0,
77
+ 'tlsSpoofingScore' => 1.0,
78
+ 'botScore' => 1.0,
79
+ 'cookieDroppingScore' => 1.0, // Pénalité maximale
80
+ 'threatIntelScore' => 0.7, // Poids élevé pour les menaces connues (Tor, etc.)
81
+ 'clientHintsInconsistencyScore' => 0.9, // Very high penalty in strict mode
82
+ 'clickVarianceScore' => 0.7, // High weight for click variance
83
+ 'subnetScore' => 0.7, // Poids plus élevé en mode strict
84
+ ],
85
+ 'thresholds' => ['low' => 10, 'medium' => 35, 'high' => 65, 'block' => 90],
86
+ 'patterns' => [
87
+ 'velocityThreshold' => 1000,
88
+ 'burstThreshold' => 1800,
89
+ 'scrapeThreshold' => 1200,
90
+ 'historySize' => 15,
91
+ 'minSamples' => 4,
92
+ 'regularityThreshold' => 40,
93
+ 'benfordThreshold' => 0.12,
94
+ 'patternWeight' => 90,
95
+ 'decayFactor' => 0.85,
96
+ 'inactivityReset' => 4000,
97
+ ],
98
+ 'challengeNewDevices' => true, // Challenge all new devices
99
+ ],
100
+
101
+ /**
102
+ * API Profile
103
+ * Optimized for protecting API endpoints. This profile is highly sensitive to request patterns (velocity, bursts)
104
+ * and less reliant on browser-specific behavioral metrics. It's designed to quickly identify and throttle scrapers and automated clients.
105
+ */
106
+ 'api' => [
107
+ 'summary' => 'API Profile',
108
+ 'description' => 'Optimized for protecting API endpoints. This profile is highly sensitive to request patterns (velocity, bursts) and less reliant on browser-specific behavioral metrics. It\'s designed to quickly identify and throttle scrapers and automated clients.',
109
+ 'weights' => [
110
+ 'historyScore' => 0.5,
111
+ 'rotationScore' => 0.5,
112
+ 'headerAnomalyScore' => 0.3,
113
+ 'requestPatternScore' => 1.0, // Very high weight for API patterns
114
+ 'inconsistencyScore' => 0.7,
115
+ 'behaviorScore' => 0.2, // Lower weight, as browser behavior is not applicable
116
+ 'honeypotScore' => 1.0,
117
+ 'crossLayerInconsistencyScore' => 0.5,
118
+ 'timeInconsistencyScore' => 0.8,
119
+ 'tlsSpoofingScore' => 0.7,
120
+ 'botScore' => 0.5,
121
+ 'cookieDroppingScore' => 0.8, // Important pour les clients API qui doivent maintenir un état
122
+ 'threatIntelScore' => 0.5, // APIs are often targeted by malicious IPs
123
+ 'clientHintsInconsistencyScore' => 0.6, // Relevant signal for APIs
124
+ 'clickVarianceScore' => 0.3, // Low weight as not applicable to APIs
125
+ 'subnetScore' => 0.8, // Très important pour les API pour détecter les botnets
126
+ ],
127
+ 'thresholds' => ['low' => 25, 'medium' => 50, 'high' => 80, 'block' => 95],
128
+ 'patterns' => [
129
+ 'velocityThreshold' => 200, // APIs are expected to be fast
130
+ 'burstThreshold' => 500,
131
+ 'scrapeThreshold' => 400,
132
+ 'historySize' => 20,
133
+ 'minSamples' => 8,
134
+ 'regularityThreshold' => 20,
135
+ 'benfordThreshold' => 0.18,
136
+ 'patternWeight' => 85,
137
+ 'decayFactor' => 0.9,
138
+ 'inactivityReset' => 10000,
139
+ ],
140
+ // This would be a callable in PHP, but for now, we represent its intent.
141
+ 'isApiRequest' => 'req.path.startsWith("/api/") || req.headers.accept?.includes("application/json")',
142
+ ],
143
+
144
+ /**
145
+ * Blog Profile
146
+ * Tuned for blogs and content-heavy websites. This profile focuses on detecting content scraping and comment spam
147
+ * by placing a high weight on request patterns and honeypot traps, while being more lenient on behavioral metrics
148
+ * typical of readers.
149
+ */
150
+ 'blog' => [
151
+ 'summary' => 'Blog Profile',
152
+ 'description' => 'Tuned for blogs and content-heavy websites. This profile focuses on detecting content scraping and comment spam by placing a high weight on request patterns and honeypot traps, while being more lenient on behavioral metrics typical of readers.',
153
+ 'weights' => [
154
+ 'historyScore' => 0.2,
155
+ 'rotationScore' => 0.3,
156
+ 'headerAnomalyScore' => 0.1,
157
+ 'requestPatternScore' => 0.8, // High weight to detect content scraping
158
+ 'inconsistencyScore' => 0.7,
159
+ 'behaviorScore' => 0.5, // Less emphasis on complex interactions
160
+ 'honeypotScore' => 1.0, // Crucial for comment spam
161
+ 'crossLayerInconsistencyScore' => 0.4,
162
+ 'timeInconsistencyScore' => 0.8,
163
+ 'tlsSpoofingScore' => 0.6,
164
+ 'botScore' => 0.8,
165
+ 'cookieDroppingScore' => 0.7, // Moins critique, mais toujours un signal
166
+ 'threatIntelScore' => 0.3, // Lower priority for a blog
167
+ 'clientHintsInconsistencyScore' => 0.5,
168
+ 'clickVarianceScore' => 0.5, // Moderate weight for click variance
169
+ 'subnetScore' => 0.4, // Utile contre le spam de commentaires coordonné
170
+ ],
171
+ 'thresholds' => ['low' => 25, 'medium' => 55, 'high' => 80, 'block' => 95],
172
+ 'patterns' => [
173
+ 'velocityThreshold' => 1000, // Readers can be fast
174
+ 'burstThreshold' => 2000,
175
+ 'scrapeThreshold' => 800, // Very sensitive to scraping patterns
176
+ 'historySize' => 12,
177
+ 'minSamples' => 5,
178
+ 'regularityThreshold' => 60,
179
+ 'benfordThreshold' => 0.16,
180
+ 'patternWeight' => 85,
181
+ 'decayFactor' => 0.92,
182
+ 'inactivityReset' => 10000,
183
+ ],
184
+ ],
185
+
186
+ /**
187
+ * E-commerce Profile
188
+ * A strict profile tailored for e-commerce sites. It's designed to combat inventory scalping,
189
+ * price scraping, and account takeover attempts by using high weights for request patterns and fingerprint inconsistency.
190
+ * It also challenges all new devices to increase the cost for bots.
191
+ */
192
+ 'ecommerce' => [
193
+ 'summary' => 'E-commerce Profile',
194
+ 'description' => 'A strict profile tailored for e-commerce sites. It\'s designed to combat inventory scalping, price scraping, and account takeover attempts by using high weights for request patterns and fingerprint inconsistency. It also challenges all new devices to increase the cost for bots.',
195
+ 'weights' => [
196
+ 'historyScore' => 0.4,
197
+ 'rotationScore' => 0.6,
198
+ 'headerAnomalyScore' => 0.2,
199
+ 'inconsistencyScore' => 1.0, // Crucial for preventing account takeover
200
+ 'behaviorScore' => 0.8, // Important for checkout/login forms
201
+ 'honeypotScore' => 1.0,
202
+ 'crossLayerInconsistencyScore' => 0.7,
203
+ // NOUVEAU: Ajout des scores manquants pour une configuration complète
204
+ 'requestPatternScore' => 0.9, // Poids unifié pour les patterns, remplace les scores scindés
205
+ 'timeInconsistencyScore' => 0.9,
206
+ 'tlsSpoofingScore' => 0.9,
207
+ 'botScore' => 1.0,
208
+ 'cookieDroppingScore' => 1.0, // Crucial pour la détection de bots e-commerce
209
+ 'threatIntelScore' => 0.8, // Very important for e-commerce (scalping proxies)
210
+ 'clientHintsInconsistencyScore' => 0.9, // Very important for e-commerce
211
+ 'clickVarianceScore' => 0.8, // Very high weight for click variance
212
+ 'subnetScore' => 0.9, // Crucial contre les attaques de scalping distribuées
213
+ ],
214
+ 'thresholds' => ['low' => 15, 'medium' => 40, 'high' => 70, 'block' => 90],
215
+ 'patterns' => [
216
+ 'velocityThreshold' => 500, // Bots are very fast
217
+ 'burstThreshold' => 1000, // Detects rapid retries on the same product/action
218
+ 'scrapeThreshold' => 600,
219
+ 'historySize' => 15,
220
+ 'minSamples' => 6,
221
+ 'regularityThreshold' => 30,
222
+ 'benfordThreshold' => 0.14,
223
+ 'patternWeight' => 95,
224
+ 'decayFactor' => 0.88,
225
+ 'inactivityReset' => 3000,
226
+ ],
227
+ 'challengeNewDevices' => true, // New devices are suspicious in e-commerce
228
+ // This would be a callable in PHP, but for now, we represent its intent.
229
+ 'isApiRequest' => 'req.path.startsWith("/api/cart") || req.path.startsWith("/api/stock") || req.path.startsWith("/api/checkout")',
230
+ ],
231
+ ];
232
+
233
+ /**
234
+ * Crée une configuration de sécurité basée sur un profil nommé, avec des surcharges optionnelles.
235
+ *
236
+ * @param string $profileName Le nom du profil à utiliser ('balanced', 'strict', 'api', etc.).
237
+ * @param array<string, mixed> $overrides Un tableau pour fusionner profondément avec le profil, permettant la personnalisation.
238
+ * @return array<string, mixed> L'objet de configuration de sécurité final.
239
+ */
240
+ public static function createSecurityProfile(string $profileName = 'balanced', array $overrides = []): array
241
+ {
242
+ $baseProfile = self::PROFILES[$profileName] ?? self::PROFILES['balanced'];
243
+ return self::deepMerge($baseProfile, $overrides);
244
+ }
245
+
246
+ /**
247
+ * Fusionne profondément deux tableaux. Les propriétés du tableau `$source` écrasent celles du tableau `$target`.
248
+ *
249
+ * @param array<string, mixed> $target Le tableau cible.
250
+ * @param array<string, mixed> $source Le tableau source.
251
+ * @return array<string, mixed> Le tableau fusionné.
252
+ */
253
+ private static function deepMerge(array $target, array $source): array
254
+ {
255
+ $output = $target;
256
+
257
+ foreach ($source as $key => $value) {
258
+ if (is_array($value) && isset($output[$key]) && is_array($output[$key])) {
259
+ $output[$key] = self::deepMerge($output[$key], $value);
260
+ } else {
261
+ $output[$key] = $value;
262
+ }
263
+ }
264
+
265
+ return $output;
266
+ }
267
+ }
@@ -0,0 +1,81 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint;
6
+
7
+ /**
8
+ * Intégration directe du moteur de fingerprinting pour les applications PHP sans framework PSR.
9
+ * Cette classe interagit directement avec les superglobales PHP et les fonctions de réponse.
10
+ */
11
+ class DirectFingerprint
12
+ {
13
+ private FingerprintEngine $engine;
14
+
15
+ /**
16
+ * @param array $securityConfig La configuration de sécurité pour le moteur.
17
+ */
18
+ public function __construct(array $securityConfig)
19
+ {
20
+ $this->engine = new FingerprintEngine($securityConfig);
21
+ }
22
+
23
+ /**
24
+ * Protège le point d'entrée actuel.
25
+ * Analyse la requête entrante et, si nécessaire, envoie une réponse de challenge/blocage et termine le script.
26
+ * Si la requête est autorisée, la méthode retourne simplement et le reste du script peut s'exécuter.
27
+ *
28
+ * @return array{score: float, vector: array}|null Les données du fingerprint si la requête est autorisée, null sinon.
29
+ */
30
+ public function protect(): ?array
31
+ {
32
+ // 1. Construire le contexte de la requête à partir des superglobales PHP.
33
+ $body = $_POST ?: json_decode(file_get_contents('php://input'), true);
34
+ $headers = function_exists('getallheaders') ? getallheaders() : [];
35
+
36
+ $context = new RequestContext(
37
+ $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1',
38
+ parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '/',
39
+ $headers,
40
+ $_GET,
41
+ $body,
42
+ $_COOKIE,
43
+ $_SERVER['SERVER_PROTOCOL'] ?? '1.1'
44
+ );
45
+
46
+ // 2. Traiter la requête avec le moteur.
47
+ $decision = $this->engine->processRequest($context);
48
+
49
+ // 3. Agir sur la décision.
50
+ if (isset($context->newCookieForResponse)) {
51
+ $cookie = $context->newCookieForResponse;
52
+ setcookie($cookie['name'], $cookie['value'], $cookie['options']);
53
+ }
54
+
55
+ switch ($decision['action']) {
56
+ case 'block':
57
+ case 'challenge':
58
+ http_response_code($decision['status'] ?? 403);
59
+ if (is_array($decision['body'])) {
60
+ header('Content-Type: application/json');
61
+ echo json_encode($decision['body']);
62
+ } else {
63
+ header('Content-Type: text/html; charset=utf-8');
64
+ echo $decision['body'];
65
+ }
66
+ exit(); // Termine le script.
67
+
68
+ case 'redirect':
69
+ if (isset($decision['cookie'])) {
70
+ setcookie($decision['cookie']['name'], $decision['cookie']['value'], $decision['cookie']['options']);
71
+ }
72
+ header('Location: ' . $decision['path'], true, 302);
73
+ exit(); // Termine le script.
74
+
75
+ case 'next':
76
+ default:
77
+ // La requête est autorisée, on retourne les informations du fingerprint.
78
+ return ['score' => $decision['score'], 'vector' => $decision['vector']];
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,186 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint;
6
+
7
+ /**
8
+ * Classe pour construire une empreinte composite (Multi-Hash).
9
+ * Format de sortie : "grp1:hash1|grp2:hash2|grp3:hash3"
10
+ */
11
+ class FingerprintBuilder
12
+ {
13
+ /**
14
+ * @var array<string, string|int>
15
+ */
16
+ private array $components = [];
17
+
18
+ /**
19
+ * Ajoute un composant à l'empreinte.
20
+ * La valeur est hachée pour l'anonymiser et réduire sa taille.
21
+ *
22
+ * @param string $group Le nom du groupe (ex: 'hw', 'screen', 'geo').
23
+ * @param string|int|bool|null $value La valeur brute à hacher.
24
+ * @return self
25
+ */
26
+ public function add(string $group, $value): self
27
+ {
28
+ if ($value === null || $value === '') {
29
+ return $this;
30
+ }
31
+ // On hache la valeur individuellement.
32
+ $this->components[$group] = self::cyrb53((string)$value);
33
+ return $this;
34
+ }
35
+
36
+ /**
37
+ * Ajoute un composant brut sans le hacher.
38
+ * Utile pour les métriques qui doivent être lues telles quelles par le serveur.
39
+ *
40
+ * @param string $group Le nom du groupe.
41
+ * @param string|int|null $value La valeur brute.
42
+ * @return self
43
+ */
44
+ public function addRaw(string $group, $value): self
45
+ {
46
+ if ($value === null) {
47
+ return $this;
48
+ }
49
+ $this->components[$group] = $value;
50
+ return $this;
51
+ }
52
+
53
+ /**
54
+ * Génère la chaîne de l'empreinte finale.
55
+ * Les composants sont triés par clé pour garantir un ordre déterministe.
56
+ *
57
+ * @return string
58
+ */
59
+ public function __toString(): string
60
+ {
61
+ // ksort trie le tableau par clé.
62
+ ksort($this->components);
63
+
64
+ $parts = [];
65
+ foreach ($this->components as $key => $hash) {
66
+ $parts[] = "{$key}:{$hash}";
67
+ }
68
+
69
+ return implode('|', $parts);
70
+ }
71
+
72
+ /**
73
+ * Compare deux empreintes et retourne un score de similarité (de 0 à 1).
74
+ * Utilise une pondération pour donner plus d'importance aux invariants forts (Canvas, GPU, JA3).
75
+ *
76
+ * @param string|null $fpString1 Empreinte A.
77
+ * @param string|null $fpString2 Empreinte B.
78
+ * @return float
79
+ */
80
+ public static function compare(?string $fpString1, ?string $fpString2): float
81
+ {
82
+ if (empty($fpString1) || empty($fpString2)) {
83
+ return 0.0;
84
+ }
85
+
86
+ $parse = function (string $str): array {
87
+ $map = [];
88
+ foreach (explode('|', $str) as $part) {
89
+ $pair = explode(':', $part, 2);
90
+ if (count($pair) === 2 && !empty($pair[0]) && !empty($pair[1])) {
91
+ $map[$pair[0]] = $pair[1];
92
+ }
93
+ }
94
+ return $map;
95
+ };
96
+
97
+ $map1 = $parse($fpString1);
98
+ $map2 = $parse($fpString2);
99
+
100
+ $volatileKeys = [
101
+ 'ch_ua', 'ch_platform', 'ch_mobile', 'ch_model', 'ch_arch', 'ch_bitness',
102
+ 'cookie_keys', 'upgrade', 'network', 'http_ver',
103
+ 'x_forwarded_for', 'x_real_ip', 'cf_connecting_ip'
104
+ ];
105
+
106
+ $weights = [
107
+ 'cvs' => 5.0, 'gpu' => 4.0, 'ja3' => 3.5, 'ja4' => 4.0, 'ja4s' => 4.0, 'ja4h' => 3.8,
108
+ 'h2_settings' => 3.0, 'tcp_fp' => 2.5, 'ua' => 2.0,
109
+ 'client_fp_hash' => 3.0, 'browser' => 1.5, 'os_version' => 1.5,
110
+ 'device_type' => 1.0, 'hw' => 1.5, 'scr' => 1.0, 'os' => 0.8, 'geo' => 0.5,
111
+ ];
112
+
113
+ $weightedMatches = 0.0;
114
+ $totalWeight = 0.0;
115
+
116
+ $allKeys = array_unique(array_merge(array_keys($map1), array_keys($map2)));
117
+
118
+ foreach ($allKeys as $key) {
119
+ // On ignore les clés volatiles pour cette comparaison spécifique.
120
+ if (in_array($key, $volatileKeys, true)) { // @phpstan-ignore-line
121
+ continue;
122
+ }
123
+
124
+ // On ne compare que les clés qui ont un poids défini.
125
+ $weight = $weights[$key] ?? null;
126
+ if ($weight === null) continue;
127
+
128
+ $totalWeight += $weight;
129
+ if (isset($map1[$key]) && isset($map2[$key])) {
130
+ if ($map1[$key] === $map2[$key]) {
131
+ $weightedMatches += $weight;
132
+ }
133
+ }
134
+ }
135
+
136
+ return $totalWeight === 0.0 ? 0.0 : $weightedMatches / $totalWeight;
137
+ }
138
+
139
+ /**
140
+ * Algorithme de hachage cyrb53 (rapide et faible taux de collision).
141
+ * Porté depuis la version JavaScript.
142
+ *
143
+ * @param string $str La chaîne à hacher.
144
+ * @param int $seed Une graine optionnelle.
145
+ * @return string Le hash sous forme de chaîne de caractères.
146
+ */
147
+ public static function cyrb53(string $str, int $seed = 0): string
148
+ {
149
+ $h1 = 0xdeadbeef ^ $seed;
150
+ $h2 = 0x41c6ce57 ^ $seed;
151
+
152
+ for ($i = 0, $l = strlen($str); $i < $l; $i++) {
153
+ $ch = ord($str[$i]);
154
+ $h1 = self::imul($h1 ^ $ch, 2654435761);
155
+ $h2 = self::imul($h2 ^ $ch, 1597334677);
156
+ }
157
+
158
+ $h1 = self::imul($h1 ^ ($h1 >> 16), 2246822507) ^ self::imul($h2 ^ ($h2 >> 13), 3266489909);
159
+ $h2 = self::imul($h2 ^ ($h2 >> 16), 2246822507) ^ self::imul($h1 ^ ($h1 >> 13), 3266489909);
160
+
161
+ // En PHP, les opérations sur les grands nombres peuvent être délicates.
162
+ // On utilise bcmath pour une arithmétique de précision arbitraire, garantissant le même résultat que JS.
163
+ $val_h2 = bcadd(bcmul((string)(2097151 & $h2), '4294967296'), (string)($h1 >= 0 ? $h1 : $h1 + 4294967296));
164
+ return $val_h2;
165
+ }
166
+
167
+ /**
168
+ * Émule la multiplication 32-bit `Math.imul` de JavaScript.
169
+ *
170
+ * @param int $a
171
+ * @param int $b
172
+ * @return int Un entier signé 32-bit.
173
+ */
174
+ private static function imul(int $a, int $b): int
175
+ {
176
+ // Emulation of JavaScript's Math.imul for signed 32-bit integer multiplication.
177
+ // This version correctly handles overflows on 64-bit systems.
178
+ $ah = ($a >> 16) & 0xffff;
179
+ $al = $a & 0xffff;
180
+ $bh = ($b >> 16) & 0xffff;
181
+ $bl = $b & 0xffff;
182
+ $lo = $al * $bl;
183
+ $hi = (($lo >> 16) + ($al * $bh) + ($ah * $bl)) & 0xffff;
184
+ return (($hi << 16) | ($lo & 0xffff)) | 0;
185
+ }
186
+ }
@@ -0,0 +1,132 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint;
6
+ use Anonympins\Fingerprint\Config\SecurityProfiles;
7
+
8
+ /**
9
+ * FingerprintClient - Wrapper PHP pour la bibliothèque de fingerprinting côté client.
10
+ *
11
+ * Cette classe facilite l'intégration de la bibliothèque JavaScript `fingerprint.client.js`
12
+ * dans une application PHP. Elle gère l'injection sécurisée du script et la création
13
+ * de "honeypots" (pièges à bots) dans les formulaires.
14
+ */
15
+ class FingerprintClient
16
+ {
17
+ /**
18
+ * @var string Le chemin vers le fichier de la bibliothèque client JavaScript.
19
+ */
20
+ private string $clientScriptPath;
21
+
22
+ /**
23
+ * @var array La configuration à passer à la fonction `initializeClient` de la bibliothèque JS.
24
+ */
25
+ private array $clientConfig;
26
+
27
+ /**
28
+ * @var string|null Un nonce cryptographique pour la Content Security Policy (CSP).
29
+ */
30
+ private ?string $nonce;
31
+
32
+ /**
33
+ * Constructeur de la classe.
34
+ *
35
+ * @param string $clientScriptPath Le chemin d'accès web au fichier `fingerprint.client.js`.
36
+ * @param array $clientConfig La configuration pour la bibliothèque client (souris, frappes, honeypots, etc.).
37
+ */
38
+ public function __construct(string $clientScriptPath, array $clientConfig = [])
39
+ {
40
+ $this->clientScriptPath = $clientScriptPath;
41
+
42
+ $defaultConfig = [
43
+ 'mouse' => true,
44
+ 'keystrokes' => true,
45
+ 'clicks' => true,
46
+ 'honeypots' => [],
47
+ 'fetch' => [
48
+ 'handleChallenges' => true,
49
+ 'probationaryTtl' => 30000, // 30 seconds
50
+ ],
51
+ 'wasm' => true, // Activer la tentative de chargement du module WASM
52
+ 'wasmPath' => '/fp.js' // Chemin vers le script de chargement WASM
53
+ ];
54
+
55
+ // Utiliser une fusion profonde pour permettre de surcharger des sous-clés
56
+ $this->clientConfig = SecurityProfiles::deepMerge($defaultConfig, $clientConfig);
57
+
58
+ try {
59
+ // Génère un nonce pour CSP si possible, pour une sécurité renforcée.
60
+ $this->nonce = bin2hex(random_bytes(16));
61
+ } catch (\Exception $e) {
62
+ $this->nonce = null;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Génère un champ de formulaire "honeypot" caché.
68
+ * Les bots le rempliront, mais il sera invisible pour les humains.
69
+ *
70
+ * @param string $fieldName Le nom du champ (doit correspondre à la configuration client).
71
+ * @return string Le code HTML du champ honeypot.
72
+ */
73
+ public function generateHoneypotField(string $fieldName): string
74
+ {
75
+ // Ajoute le champ à la configuration pour que le script client le surveille.
76
+ if (!in_array($fieldName, $this->clientConfig['honeypots'])) {
77
+ $this->clientConfig['honeypots'][] = $fieldName;
78
+ }
79
+
80
+ // Styles CSS pour cacher le champ de manière robuste.
81
+ $styles = 'position:absolute; left:-9999px; top:-9999px; opacity:0;';
82
+
83
+ return '<div style="' . $styles . '" aria-hidden="true">'
84
+ . '<label for="' . htmlspecialchars($fieldName) . '">Ne pas remplir ce champ</label>'
85
+ . '<input type="text" id="' . htmlspecialchars($fieldName) . '" name="' . htmlspecialchars($fieldName) . '" tabindex="-1" autocomplete="off">'
86
+ . '</div>';
87
+ }
88
+
89
+ /**
90
+ * Génère le bloc de script complet à inclure dans une page HTML.
91
+ *
92
+ * @return string Le code HTML des balises <script>.
93
+ */
94
+ public function getScriptTag(): string
95
+ {
96
+ $configJson = json_encode($this->clientConfig);
97
+ $nonceAttr = $this->nonce ? ' nonce="' . $this->nonce . '"' : '';
98
+
99
+ // Le script d'initialisation qui sera inclus dans la page.
100
+ $initScript = <<<JS
101
+ document.addEventListener('DOMContentLoaded', function() {
102
+ const config = {$configJson};
103
+ if (window.ClientLibrary) {
104
+ if (config.wasmPath) {
105
+ const wasmScript = document.createElement('script');
106
+ wasmScript.src = config.wasmPath;
107
+ wasmScript.async = true;
108
+ wasmScript.nonce = '{$this->nonce}';
109
+ document.head.appendChild(wasmScript);
110
+ }
111
+
112
+ window.ClientLibrary.initializeClient(config);
113
+ } else {
114
+ console.error('Fingerprint client library not loaded.');
115
+ }
116
+ });
117
+ JS;
118
+
119
+ // On combine le chargement de la bibliothèque et le script d'initialisation.
120
+ return '<script src="' . htmlspecialchars($this->clientScriptPath) . '"' . $nonceAttr . '></script>'
121
+ . '<script' . $nonceAttr . '>' . $initScript . '</script>';
122
+ }
123
+
124
+ /**
125
+ * Retourne le nonce généré pour pouvoir l'utiliser dans les en-têtes CSP.
126
+ * @return string|null
127
+ */
128
+ public function getNonce(): ?string
129
+ {
130
+ return $this->nonce;
131
+ }
132
+ }