@anonympins/fingerprint 0.7.0 → 0.7.2

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 (66) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1 -1
  3. package/composer.json +8 -1
  4. package/package.json +1 -1
  5. package/public/fingerprint-wordpress.zip +0 -0
  6. package/src/js/build-client.js +8 -10
  7. package/src/js/fingerprint.builder.js +37 -38
  8. package/src/js/fingerprint.client.js +1531 -1463
  9. package/src/js/fingerprint.client.obfuscated.js +1 -0
  10. package/src/js/fingerprint.js +190 -16
  11. package/src/js/fingerprint.utils.js +213 -213
  12. package/src/js/library.js +340 -376
  13. package/src/js/mongodb-store.js +1 -1
  14. package/src/js/optimization.worker.js +27 -27
  15. package/src/js/pow.solver.inline.js +154 -56
  16. package/src/js/pow.solver.js +180 -92
  17. package/src/js/pow.worker.js +48 -48
  18. package/src/js/redis-store.js +1 -1
  19. package/src/js/tests/fingerprint.client.init.test.js +146 -143
  20. package/src/js/tests/fingerprint.test.js +124 -10
  21. package/src/js/tests/ip-reputation.test.js +1 -0
  22. package/src/js/upow-model-task.js +14 -15
  23. package/src/php/AutoTuner.php +34 -34
  24. package/src/php/Challenge/ChallengeUtils.php +57 -11
  25. package/src/php/Config/SecurityProfiles.php +20 -0
  26. package/src/php/DirectFingerprint.php +190 -145
  27. package/src/php/FingerprintBuilder.php +29 -30
  28. package/src/php/FingerprintClient.php +147 -148
  29. package/src/php/FingerprintEngine.php +44 -17
  30. package/src/php/Ja3AnomalyDetector.php +33 -32
  31. package/src/php/Optimization/FunctionRegistry.php +7 -7
  32. package/src/php/Optimization/Optimization.php +24 -24
  33. package/src/php/Optimization/OptimizationOperators.php +26 -25
  34. package/src/php/Optimization/ProblemInitializers.php +52 -52
  35. package/src/php/ProblemManager.php +31 -34
  36. package/src/php/RequestContext.php +8 -1
  37. package/src/php/Store/IStore.php +7 -8
  38. package/src/php/Store/InMemoryStore.php +66 -66
  39. package/src/php/Store/MongoDbStore.php +5 -5
  40. package/src/php/Store/RedisStore.php +5 -5
  41. package/src/php/Store/StoreManager.php +35 -35
  42. package/src/php/Tests/ChallengeUtilsTest.php +453 -453
  43. package/src/php/Tests/DnsCircuitBreakerTest.php +105 -105
  44. package/src/php/Tests/FingerprintEngineTest.php +38 -0
  45. package/src/php/Tests/IpReputationTest.php +10 -0
  46. package/src/php/Tests/MaliciousPatternsTest.php +103 -103
  47. package/src/php/Tests/MetricsTest.php +97 -97
  48. package/src/php/Tests/ProblemManagerTest.php +376 -376
  49. package/src/php/Tests/QuicFingerprintTest.php +53 -53
  50. package/src/php/Tests/RequestUtilsTest.php +471 -471
  51. package/src/php/Tests/TLSClientHelloParserTest.php +177 -177
  52. package/src/php/Tests/config/ed25519_key.json +3 -3
  53. package/src/php/Utils/BlockList.php +99 -99
  54. package/src/php/Utils/Env.php +49 -49
  55. package/src/php/Utils/MaliciousPatterns.php +74 -74
  56. package/src/php/Utils/MetricsManager.php +209 -209
  57. package/src/php/Utils/RequestUtils.php +129 -7
  58. package/src/php/Utils/TLSClientHelloParser.php +369 -369
  59. package/src/php/WordPress/WpDbStore.php +155 -0
  60. package/src/php/WordPress/fingerprint-wordpress.php +554 -0
  61. package/src/php/WordPress/languages/fingerprint-wordpress-de_DE.mo +0 -0
  62. package/src/php/WordPress/languages/fingerprint-wordpress-de_DE.po +262 -0
  63. package/src/php/WordPress/languages/fingerprint-wordpress-fr_FR.mo +0 -0
  64. package/src/php/WordPress/languages/fingerprint-wordpress-fr_FR.po +268 -0
  65. package/src/php/WordPress/package.php +218 -0
  66. package/src/php/bin/auto-tune.php +118 -118
@@ -0,0 +1,554 @@
1
+ <?php
2
+ /**
3
+ * Plugin Name: Fingerprint Anti-Bot & Proof-of-Work
4
+ * Plugin URI: https://github.com/anonympins/fingerprint
5
+ * Description: High-performance client-side anti-bot protection and Proof-of-Work challenge verification for WordPress.
6
+ * Version: 0.7.2
7
+ * Author: Anonympins
8
+ * License: MIT
9
+ * Text Domain: fingerprint-wordpress
10
+ * Domain Path: /languages
11
+ */
12
+
13
+ declare(strict_types=1);
14
+
15
+ use Anonympins\Fingerprint\DirectFingerprint;
16
+ use Anonympins\Fingerprint\Store\StoreManager;
17
+ use Anonympins\Fingerprint\Config\SecurityProfiles;
18
+ use Anonympins\Fingerprint\Utils\MetricsManager;
19
+ use Anonympins\Fingerprint\WordPress\WpDbStore;
20
+
21
+ if (!defined('ABSPATH')) {
22
+ exit;
23
+ }
24
+
25
+ // =============================================================================
26
+ // PIÈGES HONEYPOT POUR ENVIRONNEMENTS TIERS (NON-WORDPRESS)
27
+ // Détecte et bloque instantanément les scans de vulnérabilités ciblant
28
+ // Laravel, Symfony, Spring Boot, Django, ASP.NET, phpMyAdmin, Git, Cloud, etc.
29
+ // =============================================================================
30
+ $foreignEnvTrapUrls = [
31
+ // Outils d'administration BDD & scripts de debug
32
+ '/phpmyadmin', '/pma', '/adminer', '/mysql', '/dbadmin', '/phpinfo',
33
+ // Frameworks PHP (Laravel, Symfony) & fichiers d'environnement
34
+ '/.env', '/artisan', '/telescope', '/_profiler', '/config/database.php', '/vendor/',
35
+ // Java / Spring Boot / Actuator
36
+ '/actuator', '/actuator/health', '/actuator/gateway', '/api-docs', '/swagger-ui',
37
+ // Python / Django / Flask
38
+ '/.flask', '/django_admin', '/__pycache__',
39
+ // Node.js & configuration paquets
40
+ '/.npmrc', '/package.json', '/package-lock.json',
41
+ // ASP.NET / IIS / CGI
42
+ '/elmah.axd', '/trace.axd', '/cgi-bin/',
43
+ // DevOps, VCS & Déploiements cloud
44
+ '/.git', '/.svn', '/.aws', '/.kube', '/docker-compose', '/serverless'
45
+ ];
46
+
47
+ $foreignEnvHoneypotFields = [
48
+ // Tokens CSRF et formulaires spécifiques à d'autres frameworks
49
+ '_token', // Laravel
50
+ 'csrfmiddlewaretoken', // Django
51
+ 'authenticity_token', // Ruby on Rails
52
+ 'form_build_id', // Drupal
53
+ 'form_id', // Drupal
54
+ 'j_username', // Java / Spring Security
55
+ 'j_password', // Java / Spring Security
56
+ '__VIEWSTATE', // ASP.NET WebForms
57
+ '__EVENTVALIDATION', // ASP.NET WebForms
58
+ ];
59
+
60
+ // =============================================================================
61
+ // CONFIGURATION PAR DÉFAUT DES PROFILS DE SÉCURITÉ PAR CONTEXTE
62
+ // =============================================================================
63
+ $fingerprintSecurityProfiles = [
64
+ 'api' => [
65
+ 'profile' => 'api',
66
+ 'overrides' => [
67
+ 'verbose' => false,
68
+ 'challengeNewDevices' => false,
69
+ 'honeypot' => [
70
+ 'fields' => $foreignEnvHoneypotFields,
71
+ 'trapUrls' => $foreignEnvTrapUrls,
72
+ 'detectInjections' => true,
73
+ ],
74
+ ],
75
+ ],
76
+ 'admin' => [
77
+ 'profile' => 'strict',
78
+ 'overrides' => [
79
+ 'verbose' => true,
80
+ 'challengeNewDevices' => true,
81
+ 'honeypot' => [
82
+ 'fields' => $foreignEnvHoneypotFields,
83
+ 'trapUrls' => $foreignEnvTrapUrls,
84
+ 'detectInjections' => true,
85
+ ],
86
+ ],
87
+ ],
88
+ 'frontend' => [
89
+ 'profile' => 'blog',
90
+ 'overrides' => [
91
+ 'verbose' => false,
92
+ 'challengeNewDevices' => false,
93
+ 'honeypot' => [
94
+ 'fields' => $foreignEnvHoneypotFields,
95
+ 'trapUrls' => $foreignEnvTrapUrls,
96
+ 'detectInjections' => true,
97
+ ],
98
+ ],
99
+ ],
100
+ ];
101
+
102
+ /**
103
+ * Récupère les configurations fusionnées avec les réglages persistés dans WordPress.
104
+ */
105
+ function fingerprint_get_effective_profiles(array $defaultProfiles): array {
106
+ $saved = get_option('fingerprint_security_options', []);
107
+ if (!is_array($saved) || empty($saved)) {
108
+ return $defaultProfiles;
109
+ }
110
+ return [
111
+ 'frontend' => SecurityProfiles::deepMerge($defaultProfiles['frontend'], $saved['frontend'] ?? []),
112
+ 'admin' => SecurityProfiles::deepMerge($defaultProfiles['admin'], $saved['admin'] ?? []),
113
+ 'api' => SecurityProfiles::deepMerge($defaultProfiles['api'], $saved['api'] ?? []),
114
+ ];
115
+ }
116
+
117
+ // Chargement du domaine de traduction i18n (FR / EN / DE)
118
+ add_action('init', function (): void {
119
+ load_plugin_textdomain('fingerprint-wordpress', false, dirname(plugin_basename(__FILE__)) . '/languages');
120
+ });
121
+
122
+ // 1. Autoloader PSR-4 pour le moteur Fingerprint
123
+ if (!class_exists(DirectFingerprint::class)) {
124
+ $composerPaths = [
125
+ __DIR__ . '/vendor/autoload.php',
126
+ dirname(__DIR__, 2) . '/vendor/autoload.php',
127
+ dirname(__DIR__, 3) . '/vendor/autoload.php',
128
+ (defined('ABSPATH') ? ABSPATH . 'vendor/autoload.php' : ''),
129
+ ];
130
+ foreach ($composerPaths as $cPath) {
131
+ if (!empty($cPath) && file_exists($cPath)) {
132
+ require_once $cPath;
133
+ break;
134
+ }
135
+ }
136
+
137
+ spl_autoload_register(function (string $class): void {
138
+ $prefix = 'Anonympins\\Fingerprint\\';
139
+ $len = strlen($prefix);
140
+ if (strncmp($prefix, $class, $len) !== 0) {
141
+ return;
142
+ }
143
+
144
+ $relativeClass = substr($class, $len);
145
+
146
+ // Classes spécifiques WordPress (ex: WpDbStore)
147
+ if (str_starts_with($relativeClass, 'WordPress\\')) {
148
+ $localClass = substr($relativeClass, strlen('WordPress\\'));
149
+ $localFile = __DIR__ . '/' . str_replace('\\', '/', $localClass) . '.php';
150
+ if (file_exists($localFile)) {
151
+ require_once $localFile;
152
+ return;
153
+ }
154
+ }
155
+
156
+ // Chemins candidats pour le moteur PHP (packagé ou environnement dev)
157
+ $candidateDirs = [
158
+ __DIR__ . '/src/',
159
+ __DIR__ . '/includes/',
160
+ __DIR__ . '/',
161
+ dirname(__DIR__) . '/',
162
+ ];
163
+
164
+ $fileRelative = str_replace('\\', '/', $relativeClass) . '.php';
165
+ foreach ($candidateDirs as $dir) {
166
+ $fullPath = $dir . $fileRelative;
167
+ if (file_exists($fullPath)) {
168
+ require_once $fullPath;
169
+ return;
170
+ }
171
+ }
172
+ });
173
+ }
174
+
175
+ // 2. Activation du plugin : Création de la table de cache SQL
176
+ register_activation_hook(__FILE__, function () {
177
+ $store = new WpDbStore();
178
+ $store->ensureTable();
179
+
180
+ if (!wp_next_scheduled('fingerprint_prune_expired_entries')) {
181
+ wp_schedule_event(time(), 'hourly', 'fingerprint_prune_expired_entries');
182
+ }
183
+ });
184
+
185
+ // 3. Désactivation : Nettoyage du WP-Cron
186
+ register_deactivation_hook(__FILE__, function () {
187
+ wp_clear_scheduled_hook('fingerprint_prune_expired_entries');
188
+ });
189
+
190
+ // 4. Tâche de fond WP-Cron : Purge des clés expirées dans la BDD
191
+ add_action('fingerprint_prune_expired_entries', function () {
192
+ $store = new WpDbStore();
193
+ $store->pruneExpired();
194
+ });
195
+
196
+ // 5. Avertissement Admin si le site n'utilise pas HTTPS (Environnement Non Sécurisé)
197
+ add_action('admin_notices', function () {
198
+ if (!is_ssl()) {
199
+ echo '<div class="notice notice-warning is-dismissible">';
200
+ echo '<p><strong>' . esc_html__('[Fingerprint Anti-Bot Security Warning]', 'fingerprint-wordpress') . '</strong> : ' .
201
+ esc_html__('Your website is currently running on unencrypted HTTP. In this mode, modern web browsers disable the native Web Cryptography API (crypto.subtle) for security reasons, forcing a JavaScript fallback simulation that is slower and vulnerable to Man-in-the-Middle (MitM) attacks. We strongly recommend deploying a TLS/SSL certificate and enforcing HTTPS to ensure the cryptographic integrity of Proof-of-Work computations and identity protection.', 'fingerprint-wordpress') .
202
+ '</p>';
203
+ echo '</div>';
204
+ }
205
+ });
206
+
207
+ // 6. Interception de sécurité au plus tôt du cycle de vie WordPress
208
+ add_action('plugins_loaded', function () use ($fingerprintSecurityProfiles) {
209
+ // Ignore WP-CLI et les exécutions internes de cron
210
+ if ((defined('WP_CLI') && WP_CLI) || (defined('DOING_CRON') && DOING_CRON)) {
211
+ return;
212
+ }
213
+
214
+ // Initialiser le Store persistant basé sur $wpdb
215
+ $store = new WpDbStore();
216
+ StoreManager::configureStore($store);
217
+
218
+ $requestUri = $_SERVER['REQUEST_URI'] ?? '/';
219
+ $isRestApi = defined('REST_REQUEST') && REST_REQUEST;
220
+ $isAdmin = is_admin() || str_contains($requestUri, 'wp-login.php');
221
+
222
+ // Fusion avec les options enregistrées via l'admin WP
223
+ $effectiveProfiles = fingerprint_get_effective_profiles($fingerprintSecurityProfiles);
224
+
225
+ // Possibilité de filtrer la configuration via functions.php ou un thème
226
+ $configs = apply_filters('fingerprint_security_profiles', $effectiveProfiles);
227
+
228
+ // Sélection adaptative du profil selon la cible de la requête
229
+ if ($isRestApi || str_starts_with($requestUri, '/wp-json/')) {
230
+ $contextConfig = $configs['api'] ?? $fingerprintSecurityProfiles['api'];
231
+ } elseif ($isAdmin) {
232
+ $contextConfig = $configs['admin'] ?? $fingerprintSecurityProfiles['admin'];
233
+ } else {
234
+ $contextConfig = $configs['frontend'] ?? $fingerprintSecurityProfiles['frontend'];
235
+ }
236
+
237
+ $securityConfig = SecurityProfiles::createSecurityProfile($contextConfig['profile'], $contextConfig['overrides'] ?? []);
238
+ $guard = new DirectFingerprint($securityConfig);
239
+
240
+ // Inspecte la requête : bloque ou envoie le challenge si nécessaire et stoppe le script
241
+ $guard->protect();
242
+ }, 0);
243
+
244
+ // =============================================================================
245
+ // INTERFACE D'ADMINISTRATION, RÉGLAGES & INSPECTION DES MÉTRIQUES
246
+ // =============================================================================
247
+
248
+ add_action('admin_menu', function () {
249
+ add_options_page(
250
+ __('Fingerprint Anti-Bot', 'fingerprint-wordpress'),
251
+ __('Fingerprint Anti-Bot', 'fingerprint-wordpress'),
252
+ 'manage_options',
253
+ 'fingerprint-settings',
254
+ 'fingerprint_render_admin_page'
255
+ );
256
+ });
257
+
258
+ /**
259
+ * Rendu de la page de réglages et du visualiseur de métriques.
260
+ */
261
+ function fingerprint_render_admin_page(): void {
262
+ if (!current_user_can('manage_options')) {
263
+ wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'fingerprint-wordpress'));
264
+ }
265
+
266
+ global $fingerprintSecurityProfiles, $wpdb;
267
+
268
+ // Sauvegarde des réglages
269
+ if (isset($_POST['fingerprint_save_settings']) && check_admin_referer('fingerprint_settings_nonce', 'fingerprint_nonce')) {
270
+ $saved = get_option('fingerprint_security_options', []);
271
+ if (!is_array($saved)) {
272
+ $saved = [];
273
+ }
274
+
275
+ // Profils sélectionnés
276
+ $saved['frontend']['profile'] = sanitize_text_field($_POST['frontend_profile'] ?? 'blog');
277
+ $saved['admin']['profile'] = sanitize_text_field($_POST['admin_profile'] ?? 'strict');
278
+ $saved['api']['profile'] = sanitize_text_field($_POST['api_profile'] ?? 'api');
279
+
280
+ // Seuils Frontend
281
+ $saved['frontend']['overrides']['thresholds'] = [
282
+ 'low' => max(1, (int)($_POST['frontend_threshold_low'] ?? 20)),
283
+ 'medium' => max(5, (int)($_POST['frontend_threshold_medium'] ?? 45)),
284
+ 'high' => max(10, (int)($_POST['frontend_threshold_high'] ?? 75)),
285
+ 'block' => max(20, (int)($_POST['frontend_threshold_block'] ?? 95)),
286
+ ];
287
+
288
+ // Options booléennes
289
+ $saved['frontend']['overrides']['challengeNewDevices'] = !empty($_POST['frontend_challenge_new']);
290
+ $saved['frontend']['overrides']['verbose'] = !empty($_POST['frontend_verbose']);
291
+ $saved['frontend']['overrides']['honeypot']['detectInjections'] = !empty($_POST['detect_injections']);
292
+
293
+ // Surcharges de l'ensemble des poids de métriques
294
+ foreach ($_POST as $postKey => $postVal) {
295
+ if (str_starts_with($postKey, 'weight_')) {
296
+ $wKey = substr($postKey, 7);
297
+ $val = (float)$postVal;
298
+ $saved['frontend']['overrides']['weights'][$wKey] = max(0.0, min(2.0, $val));
299
+ }
300
+ }
301
+
302
+ update_option('fingerprint_security_options', $saved);
303
+ echo '<div class="notice notice-success is-dismissible"><p><strong>' . esc_html__('Fingerprint settings updated successfully.', 'fingerprint-wordpress') . '</strong></p></div>';
304
+ }
305
+
306
+ // Action pour vider le cache SQL manuellement
307
+ if (isset($_POST['fingerprint_clear_store']) && check_admin_referer('fingerprint_clear_nonce', 'fingerprint_nonce_clear')) {
308
+ $store = new WpDbStore();
309
+ $store->clear();
310
+ echo '<div class="notice notice-info is-dismissible"><p>' . esc_html__('SQL cache table ($wpdb) cleared successfully.', 'fingerprint-wordpress') . '</p></div>';
311
+ }
312
+
313
+ // Récupération des profils effectifs
314
+ $effective = fingerprint_get_effective_profiles($fingerprintSecurityProfiles);
315
+ $frontendConfig = SecurityProfiles::createSecurityProfile($effective['frontend']['profile'], $effective['frontend']['overrides'] ?? []);
316
+
317
+ // Statistiques de la table de cache SQL
318
+ $tableName = $wpdb->prefix . 'fingerprint_store';
319
+ $totalRows = (int)$wpdb->get_var("SELECT COUNT(*) FROM {$tableName}");
320
+ $now = time();
321
+ $expiredRows = (int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$tableName} WHERE expires_at IS NOT NULL AND expires_at < %d", $now));
322
+
323
+ // Métriques Prometheus au format texte
324
+ $prometheusRaw = MetricsManager::getPrometheusMetrics($frontendConfig);
325
+ ?>
326
+ <div class="wrap">
327
+ <h1><span class="dashicons dashicons-shield-alt" style="font-size:32px;vertical-align:middle;margin-right:8px;"></span> Fingerprint Anti-Bot & Proof-of-Work</h1>
328
+ <p class="description"><?php esc_html_e('Client-side behavioral and cryptographic anti-bot protection without third-party CAPTCHA for WordPress.', 'fingerprint-wordpress'); ?></p>
329
+
330
+ <div style="background:#fff;border-left:4px solid #2271b1;padding:12px 18px;margin:18px 0;box-shadow:0 1px 1px rgba(0,0,0,.04);">
331
+ <p style="margin:4px 0;">
332
+ <strong><?php esc_html_e('Official documentation reference:', 'fingerprint-wordpress'); ?></strong>
333
+ <a href="https://github.com/anonympins/fingerprint/blob/main/doc/full_options.md" target="_blank" rel="noopener noreferrer" class="button button-secondary" style="margin-left:8px;">
334
+ <span class="dashicons dashicons-external" style="vertical-align:middle;"></span> <?php esc_html_e('View Full Configuration Options on GitHub', 'fingerprint-wordpress'); ?>
335
+ </a>
336
+ <a href="https://github.com/anonympins/fingerprint" target="_blank" rel="noopener noreferrer" class="button button-secondary" style="margin-left:4px;">
337
+ <span class="dashicons dashicons-admin-plugins" style="vertical-align:middle;"></span> <?php esc_html_e('GitHub Repository', 'fingerprint-wordpress'); ?>
338
+ </a>
339
+ </p>
340
+ </div>
341
+
342
+ <!-- TABLEAU DE BORD STATISTIQUES & ÉTAT -->
343
+ <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(240px, 1fr));gap:16px;margin-bottom:24px;">
344
+ <div style="background:#fff;padding:16px;border-radius:4px;border:1px solid #ccd0d4;">
345
+ <h3 style="margin-top:0;"><?php esc_html_e('HTTPS Status', 'fingerprint-wordpress'); ?></h3>
346
+ <?php if (is_ssl()): ?>
347
+ <p style="color:#007017;font-weight:bold;font-size:16px;">
348
+ <span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e('Active (WebCrypto Subtle available)', 'fingerprint-wordpress'); ?>
349
+ </p>
350
+ <?php else: ?>
351
+ <p style="color:#d63638;font-weight:bold;font-size:16px;">
352
+ <span class="dashicons dashicons-warning"></span> <?php esc_html_e('Insecure (Unencrypted HTTP)', 'fingerprint-wordpress'); ?>
353
+ </p>
354
+ <?php endif; ?>
355
+ </div>
356
+ <div style="background:#fff;padding:16px;border-radius:4px;border:1px solid #ccd0d4;">
357
+ <h3 style="margin-top:0;"><?php esc_html_e('SQL Cache ($wpdb)', 'fingerprint-wordpress'); ?></h3>
358
+ <p style="font-size:22px;margin:0;font-weight:600;"><?php echo esc_html((string)$totalRows); ?> <span style="font-size:14px;color:#646970;font-weight:normal;"><?php esc_html_e('keys in database', 'fingerprint-wordpress'); ?></span></p>
359
+ <small style="color:#8c8f94;"><?php echo sprintf(esc_html__('%d expired keys awaiting cron purge', 'fingerprint-wordpress'), $expiredRows); ?></small>
360
+ </div>
361
+ <div style="background:#fff;padding:16px;border-radius:4px;border:1px solid #ccd0d4;">
362
+ <h3 style="margin-top:0;"><?php esc_html_e('Active Profiles', 'fingerprint-wordpress'); ?></h3>
363
+ <p style="margin:0;">
364
+ <?php esc_html_e('Frontend:', 'fingerprint-wordpress'); ?> <strong><?php echo esc_html($effective['frontend']['profile']); ?></strong><br>
365
+ <?php esc_html_e('Admin:', 'fingerprint-wordpress'); ?> <strong><?php echo esc_html($effective['admin']['profile']); ?></strong><br>
366
+ <?php esc_html_e('REST API:', 'fingerprint-wordpress'); ?> <strong><?php echo esc_html($effective['api']['profile']); ?></strong>
367
+ </p>
368
+ </div>
369
+ </div>
370
+
371
+ <!-- ONGLETS DE NAVIGATION -->
372
+ <h2 class="nav-tab-wrapper">
373
+ <a href="#tab-settings" class="nav-tab nav-tab-active" onclick="fingerprintSwitchTab(event, 'tab-settings')"><?php esc_html_e('Settings & Profiles', 'fingerprint-wordpress'); ?></a>
374
+ <a href="#tab-metrics" class="nav-tab" onclick="fingerprintSwitchTab(event, 'tab-metrics')"><?php esc_html_e('Metrics & Weights View', 'fingerprint-wordpress'); ?></a>
375
+ <a href="#tab-prometheus" class="nav-tab" onclick="fingerprintSwitchTab(event, 'tab-prometheus')"><?php esc_html_e('Prometheus Stream', 'fingerprint-wordpress'); ?></a>
376
+ </h2>
377
+
378
+ <!-- TAB 1 : RÉGLAGES -->
379
+ <div id="tab-settings" class="fingerprint-tab-content" style="background:#fff;padding:20px;border:1px solid #ccd0d4;border-top:none;">
380
+ <form method="post" action="">
381
+ <?php wp_nonce_field('fingerprint_settings_nonce', 'fingerprint_nonce'); ?>
382
+
383
+ <h3><?php esc_html_e('1. Target Security Profiles', 'fingerprint-wordpress'); ?></h3>
384
+ <table class="form-table">
385
+ <tr>
386
+ <th scope="row"><label for="frontend_profile"><?php esc_html_e('Visitors & Frontend', 'fingerprint-wordpress'); ?></label></th>
387
+ <td>
388
+ <select name="frontend_profile" id="frontend_profile">
389
+ <option value="blog" <?php selected($effective['frontend']['profile'], 'blog'); ?>><?php esc_html_e('Blog (Optimal for content, smooth UX)', 'fingerprint-wordpress'); ?></option>
390
+ <option value="balanced" <?php selected($effective['frontend']['profile'], 'balanced'); ?>><?php esc_html_e('Balanced (General purpose)', 'fingerprint-wordpress'); ?></option>
391
+ <option value="strict" <?php selected($effective['frontend']['profile'], 'strict'); ?>><?php esc_html_e('Strict (Maximum protection)', 'fingerprint-wordpress'); ?></option>
392
+ <option value="ecommerce" <?php selected($effective['frontend']['profile'], 'ecommerce'); ?>><?php esc_html_e('E-commerce (Anti-scraping / scalping)', 'fingerprint-wordpress'); ?></option>
393
+ </select>
394
+ <p class="description"><?php esc_html_e('Profile applied to all public pages of the WordPress site.', 'fingerprint-wordpress'); ?></p>
395
+ </td>
396
+ </tr>
397
+ <tr>
398
+ <th scope="row"><label for="admin_profile"><?php esc_html_e('Administration Area (wp-login / wp-admin)', 'fingerprint-wordpress'); ?></label></th>
399
+ <td>
400
+ <select name="admin_profile" id="admin_profile">
401
+ <option value="strict" <?php selected($effective['admin']['profile'], 'strict'); ?>><?php esc_html_e('Strict (Recommended to secure logins)', 'fingerprint-wordpress'); ?></option>
402
+ <option value="balanced" <?php selected($effective['admin']['profile'], 'balanced'); ?>><?php esc_html_e('Balanced', 'fingerprint-wordpress'); ?></option>
403
+ </select>
404
+ </td>
405
+ </tr>
406
+ <tr>
407
+ <th scope="row"><label for="api_profile"><?php esc_html_e('REST API (/wp-json/)', 'fingerprint-wordpress'); ?></label></th>
408
+ <td>
409
+ <select name="api_profile" id="api_profile">
410
+ <option value="api" <?php selected($effective['api']['profile'], 'api'); ?>><?php esc_html_e('API (JSON challenges & machine PoW)', 'fingerprint-wordpress'); ?></option>
411
+ <option value="strict" <?php selected($effective['api']['profile'], 'strict'); ?>><?php esc_html_e('Strict', 'fingerprint-wordpress'); ?></option>
412
+ </select>
413
+ </td>
414
+ </tr>
415
+ </table>
416
+
417
+ <hr>
418
+
419
+ <h3><?php esc_html_e('2. Action Thresholds (Frontend)', 'fingerprint-wordpress'); ?></h3>
420
+ <table class="form-table">
421
+ <tr>
422
+ <th scope="row"><?php esc_html_e('Suspicion Score Thresholds (0 - 100)', 'fingerprint-wordpress'); ?></th>
423
+ <td>
424
+ <label><?php esc_html_e('Low (Initial challenge):', 'fingerprint-wordpress'); ?>
425
+ <input type="number" name="frontend_threshold_low" value="<?php echo esc_attr((string)($frontendConfig['thresholds']['low'] ?? 20)); ?>" min="1" max="50" style="width:80px;">
426
+ </label><br><br>
427
+ <label><?php esc_html_e('Medium (Hardened challenge):', 'fingerprint-wordpress'); ?>
428
+ <input type="number" name="frontend_threshold_medium" value="<?php echo esc_attr((string)($frontendConfig['thresholds']['medium'] ?? 45)); ?>" min="10" max="75" style="width:80px;">
429
+ </label><br><br>
430
+ <label><?php esc_html_e('High (Heavy Proof-of-Work):', 'fingerprint-wordpress'); ?>
431
+ <input type="number" name="frontend_threshold_high" value="<?php echo esc_attr((string)($frontendConfig['thresholds']['high'] ?? 75)); ?>" min="30" max="95" style="width:80px;">
432
+ </label><br><br>
433
+ <label><?php esc_html_e('Block (Immediate 403 Forbidden):', 'fingerprint-wordpress'); ?>
434
+ <input type="number" name="frontend_threshold_block" value="<?php echo esc_attr((string)($frontendConfig['thresholds']['block'] ?? 95)); ?>" min="50" max="100" style="width:80px;">
435
+ </label>
436
+ </td>
437
+ </tr>
438
+ <tr>
439
+ <th scope="row"><?php esc_html_e('Advanced Behaviors', 'fingerprint-wordpress'); ?></th>
440
+ <td>
441
+ <label>
442
+ <input type="checkbox" name="frontend_challenge_new" value="1" <?php checked(!empty($frontendConfig['challengeNewDevices'])); ?>>
443
+ <?php esc_html_e('Automatically challenge unknown new devices (without device_id cookie)', 'fingerprint-wordpress'); ?>
444
+ </label><br>
445
+ <label>
446
+ <input type="checkbox" name="detect_injections" value="1" <?php checked(!empty($frontendConfig['honeypot']['detectInjections'])); ?>>
447
+ <?php esc_html_e('Enable recursive WAF inspection (SQL, NoSQL, Log4j, Traversal in GET/POST)', 'fingerprint-wordpress'); ?>
448
+ </label><br>
449
+ <label>
450
+ <input type="checkbox" name="frontend_verbose" value="1" <?php checked(!empty($frontendConfig['verbose'])); ?>>
451
+ <?php esc_html_e('Verbose mode in PHP logs (Debugging)', 'fingerprint-wordpress'); ?>
452
+ </label>
453
+ </td>
454
+ </tr>
455
+ </table>
456
+
457
+ <?php submit_button(esc_html__('Save Changes', 'fingerprint-wordpress'), 'primary', 'fingerprint_save_settings'); ?>
458
+ </form>
459
+
460
+ <hr>
461
+ <form method="post" action="" style="margin-top:16px;">
462
+ <?php wp_nonce_field('fingerprint_clear_nonce', 'fingerprint_nonce_clear'); ?>
463
+ <p>
464
+ <strong><?php esc_html_e('Store Maintenance:', 'fingerprint-wordpress'); ?></strong>
465
+ <button type="submit" name="fingerprint_clear_store" class="button button-secondary" onclick="return confirm('<?php echo esc_js(__('Purge all stored sessions and nonces?', 'fingerprint-wordpress')); ?>');">
466
+ <?php esc_html_e('Clear SQL cache table ($wpdb)', 'fingerprint-wordpress'); ?>
467
+ </button>
468
+ </p>
469
+ </form>
470
+ </div>
471
+
472
+ <!-- TAB 2 : VUE DÉTAILLÉE DES MÉTRIQUES -->
473
+ <div id="tab-metrics" class="fingerprint-tab-content" style="display:none;background:#fff;padding:20px;border:1px solid #ccd0d4;border-top:none;">
474
+ <h3><?php esc_html_e('Behavioral & Transport Indicator Weights (Active Frontend Profile)', 'fingerprint-wordpress'); ?></h3>
475
+ <p class="description"><?php echo wp_kses_post(__('The final score of each request is computed using the weighted sum: <code>Score = &Sigma; (Metric &times; Weight)</code>.', 'fingerprint-wordpress')); ?></p>
476
+
477
+ <form method="post" action="">
478
+ <?php wp_nonce_field('fingerprint_settings_nonce', 'fingerprint_nonce'); ?>
479
+ <table class="wp-list-table widefat fixed striped">
480
+ <thead>
481
+ <tr>
482
+ <th style="width:280px;"><?php esc_html_e('Indicator / Metric', 'fingerprint-wordpress'); ?></th>
483
+ <th style="width:120px;"><?php esc_html_e('Current Weight', 'fingerprint-wordpress'); ?></th>
484
+ <th><?php esc_html_e('Description & Detection Role', 'fingerprint-wordpress'); ?></th>
485
+ </tr>
486
+ </thead>
487
+ <tbody>
488
+ <?php
489
+ $metricDescriptions = [
490
+ 'honeypotScore' => __('Triggering of invisible trap links, multi-framework honeypots, and injection probes.', 'fingerprint-wordpress'),
491
+ 'headerAnomalyScore' => __('Missing, malformed, or out-of-order HTTP headers inconsistent with legitimate browsers.', 'fingerprint-wordpress'),
492
+ 'tlsSpoofingScore' => __('Discrepancy between User-Agent and TLS cryptographic fingerprints (JA3/JA4, extensions, GREASE).', 'fingerprint-wordpress'),
493
+ 'behaviorScore' => __('Dynamic biometrics: mouse movements, keystroke dynamics, and mobile touch anomalies.', 'fingerprint-wordpress'),
494
+ 'requestPatternScore' => __('Velocity, robotic bursts, request standard deviation, and Benford\'s law statistical analysis.', 'fingerprint-wordpress'),
495
+ 'inconsistencyScore' => __('Alteration or drift in the hardware fingerprint between visits with the same cookie.', 'fingerprint-wordpress'),
496
+ 'subnetScore' => __('Aggregated IP reputation of the network subnet (/24 or /48) and nearby attacker density.', 'fingerprint-wordpress'),
497
+ 'ipReputationScore' => __('Local historical reputation score of the client IP address with temporal decay over time.', 'fingerprint-wordpress'),
498
+ 'renderingAnomalyScore' => __('Display rendering anomalies, V-Sync/FPS cadence, and OffscreenCanvas hooking.', 'fingerprint-wordpress'),
499
+ 'protocolAnomalyScore' => __('Divergence in HTTP/2 and QUIC / HTTP/3 flow control frame settings.', 'fingerprint-wordpress'),
500
+ 'quicAnomalyScore' => __('Anomalies in QUIC transport parameters (flow control windows, max streams, and control frame ordering).', 'fingerprint-wordpress'),
501
+ 'tcpAnomalyScore' => __('Passive TCP/IP stack fingerprinting (SYN packet TTL, window size, MSS, options) vs declared operating system.', 'fingerprint-wordpress'),
502
+ 'historyScore' => __('Suspicious rotation of multiple IP addresses associated with a single hardware identity.', 'fingerprint-wordpress'),
503
+ 'rotationScore' => __('Rapid and abnormal modifications to the application stack.', 'fingerprint-wordpress'),
504
+ 'botScore' => __('Detection of native automation attributes (navigator.webdriver, Chrome CDP).', 'fingerprint-wordpress'),
505
+ 'cookieDroppingScore' => __('Detection of cookie deletion, dropping, or refusal between consecutive requests to bypass device identification.', 'fingerprint-wordpress'),
506
+ 'threatIntelScore' => __('Correlation with known proxy IPs, Tor exit nodes, and federated threat intelligence blacklist.', 'fingerprint-wordpress'),
507
+ 'clientHintsInconsistencyScore' => __('Discrepancies between standard User-Agent and Sec-CH-UA Client Hints headers (browser family, version drift).', 'fingerprint-wordpress'),
508
+ 'clickVarianceScore' => __('Statistical analysis of click coordinate variance; flags unnaturally low pixel variance typical of click bots.', 'fingerprint-wordpress'),
509
+ 'botnetClusterScore' => __('Clustering of volatile client requests sharing identical hardware signatures across distinct IP addresses.', 'fingerprint-wordpress'),
510
+ 'timeInconsistencyScore' => __('Time delta between client timestamp and server reception to detect replay and automated delay attacks.', 'fingerprint-wordpress'),
511
+ 'virtualizationScore' => __('Detection of headless browsers, virtual GPU renderers (SwiftShader, llvmpipe) and emulated display resolutions.', 'fingerprint-wordpress'),
512
+ 'crossLayerInconsistencyScore' => __('Strict contradiction between layers (e.g. declared OS in User-Agent vs network TCP/IP stack OS).', 'fingerprint-wordpress'),
513
+ ];
514
+
515
+ foreach ($frontendConfig['weights'] as $indicator => $weight):
516
+ $desc = $metricDescriptions[$indicator] ?? __('Behavioral suspicion indicator.', 'fingerprint-wordpress');
517
+ ?>
518
+ <tr>
519
+ <td><code><?php echo esc_html($indicator); ?></code></td>
520
+ <td>
521
+ <input type="number" step="0.05" min="0" max="2.0" name="weight_<?php echo esc_attr($indicator); ?>" value="<?php echo esc_attr((string)$weight); ?>" style="width:75px;">
522
+ </td>
523
+ <td><?php echo esc_html($desc); ?></td>
524
+ </tr>
525
+ <?php endforeach; ?>
526
+ </tbody>
527
+ </table>
528
+ <p style="margin-top:16px;">
529
+ <?php submit_button(esc_html__('Update Metric Weights', 'fingerprint-wordpress'), 'primary', 'fingerprint_save_settings', false); ?>
530
+ </p>
531
+ </form>
532
+ </div>
533
+
534
+ <!-- TAB 3 : FLUX PROMETHEUS -->
535
+ <div id="tab-prometheus" class="fingerprint-tab-content" style="display:none;background:#fff;padding:20px;border:1px solid #ccd0d4;border-top:none;">
536
+ <h3><?php esc_html_e('Real-Time Prometheus Metrics', 'fingerprint-wordpress'); ?></h3>
537
+ <p class="description"><?php esc_html_e('Raw text format exported for scraping by Prometheus, Grafana Agent, or Datadog.', 'fingerprint-wordpress'); ?></p>
538
+ <textarea readonly style="width:100%;height:380px;font-family:monospace;background:#f6f7f7;padding:12px;"><?php echo esc_textarea($prometheusRaw); ?></textarea>
539
+ </div>
540
+ </div>
541
+
542
+ <script>
543
+ function fingerprintSwitchTab(evt, tabId) {
544
+ evt.preventDefault();
545
+ const tabs = document.querySelectorAll('.fingerprint-tab-content');
546
+ tabs.forEach(t => t.style.display = 'none');
547
+ const navs = document.querySelectorAll('.nav-tab-wrapper a');
548
+ navs.forEach(n => n.classList.remove('nav-tab-active'));
549
+ document.getElementById(tabId).style.display = 'block';
550
+ evt.currentTarget.classList.add('nav-tab-active');
551
+ }
552
+ </script>
553
+ <?php
554
+ }