@anonympins/fingerprint 0.7.1 → 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.
@@ -1,100 +1,100 @@
1
- <?php
2
-
3
- declare(strict_types=1);
4
-
5
- namespace Anonympins\Fingerprint\Utils;
6
-
7
- /**
8
- * Implémentation PHP d'une liste de blocage IP/CIDR, similaire à Node.js `net.BlockList`.
9
- */
10
- class BlockList
11
- {
12
- /**
13
- * @var array<string> Liste des IPs ou CIDR à bloquer.
14
- */
15
- private array $entries = [];
16
-
17
- /**
18
- * Ajoute une adresse IP ou une plage CIDR à la liste.
19
- * @param string $entry Une adresse IP (ex: '192.168.1.1') ou une plage CIDR (ex: '192.168.1.0/24').
20
- * @return void
21
- */
22
- public function add(string $entry): void
23
- {
24
- $this->entries[] = $entry;
25
- }
26
-
27
- /**
28
- * Vérifie si une adresse IP est présente dans la liste de blocage.
29
- * @param string $ip L'adresse IP à vérifier.
30
- * @return bool True si l'IP est bloquée, false sinon.
31
- */
32
- public function check(string $ip): bool
33
- {
34
- foreach ($this->entries as $entry) {
35
- if (str_contains($entry, '/')) {
36
- // C'est une plage CIDR
37
- if ($this->ipInCidr($ip, $entry)) {
38
- return true;
39
- }
40
- } else {
41
- // C'est une IP directe
42
- if ($ip === $entry) {
43
- return true;
44
- }
45
- }
46
- }
47
- return false;
48
- }
49
-
50
- /**
51
- * Vérifie si une adresse IP se trouve dans une plage CIDR donnée.
52
- * @param string $ip L'adresse IP à vérifier.
53
- * @param string $cidr La plage CIDR (ex: '192.168.1.0/24').
54
- * @return bool True si l'IP est dans la plage, false sinon.
55
- */
56
- private function ipInCidr(string $ip, string $cidr): bool
57
- {
58
- [$network, $mask] = explode('/', $cidr);
59
- $mask = (int)$mask;
60
-
61
- if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
62
- // IPv6
63
- $ipBinary = inet_pton($ip);
64
- $networkBinary = inet_pton($network);
65
-
66
- if ($ipBinary === false || $networkBinary === false) {
67
- return false;
68
- }
69
-
70
- $ipHex = bin2hex($ipBinary);
71
- $networkHex = bin2hex($networkBinary);
72
-
73
- $numBytes = (int)ceil($mask / 8);
74
- $compareLength = $numBytes * 2;
75
-
76
- if (substr($ipHex, 0, $compareLength) !== substr($networkHex, 0, $compareLength)) {
77
- return false;
78
- }
79
-
80
- if ($mask % 8 !== 0) {
81
- $bitMask = (0xFF << (8 - ($mask % 8))) & 0xFF;
82
- $ipByte = hexdec(substr($ipHex, $numBytes * 2 - 2, 2));
83
- $networkByte = hexdec(substr($networkHex, $numBytes * 2 - 2, 2));
84
- return ($ipByte & $bitMask) === ($networkByte & $bitMask);
85
- }
86
-
87
- return true;
88
-
89
- } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
90
- // IPv4
91
- $ipLong = ip2long($ip);
92
- $networkLong = ip2long($network);
93
- $wildcard = pow(2, (32 - $mask)) - 1;
94
- $netmask = ~$wildcard;
95
- return (($ipLong & $netmask) === ($networkLong & $netmask));
96
- }
97
-
98
- return false;
99
- }
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint\Utils;
6
+
7
+ /**
8
+ * Implémentation PHP d'une liste de blocage IP/CIDR, similaire à Node.js `net.BlockList`.
9
+ */
10
+ class BlockList
11
+ {
12
+ /**
13
+ * @var array<string> Liste des IPs ou CIDR à bloquer.
14
+ */
15
+ private array $entries = [];
16
+
17
+ /**
18
+ * Ajoute une adresse IP ou une plage CIDR à la liste.
19
+ * @param string $entry Une adresse IP (ex: '192.168.1.1') ou une plage CIDR (ex: '192.168.1.0/24').
20
+ * @return void
21
+ */
22
+ public function add(string $entry): void
23
+ {
24
+ $this->entries[] = $entry;
25
+ }
26
+
27
+ /**
28
+ * Vérifie si une adresse IP est présente dans la liste de blocage.
29
+ * @param string $ip L'adresse IP à vérifier.
30
+ * @return bool True si l'IP est bloquée, false sinon.
31
+ */
32
+ public function check(string $ip): bool
33
+ {
34
+ foreach ($this->entries as $entry) {
35
+ if (str_contains($entry, '/')) {
36
+ // C'est une plage CIDR
37
+ if ($this->ipInCidr($ip, $entry)) {
38
+ return true;
39
+ }
40
+ } else {
41
+ // C'est une IP directe
42
+ if ($ip === $entry) {
43
+ return true;
44
+ }
45
+ }
46
+ }
47
+ return false;
48
+ }
49
+
50
+ /**
51
+ * Vérifie si une adresse IP se trouve dans une plage CIDR donnée.
52
+ * @param string $ip L'adresse IP à vérifier.
53
+ * @param string $cidr La plage CIDR (ex: '192.168.1.0/24').
54
+ * @return bool True si l'IP est dans la plage, false sinon.
55
+ */
56
+ private function ipInCidr(string $ip, string $cidr): bool
57
+ {
58
+ // Handle IPv4-mapped IPv6 addresses by converting them to IPv4
59
+ if (str_starts_with(strtolower($ip), '::ffff:') && filter_var(substr($ip, 7), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
60
+ $ip = substr($ip, 7);
61
+ }
62
+
63
+ [$network, $mask] = explode('/', $cidr, 2);
64
+ $mask = (int)$mask;
65
+
66
+ // Now, both $ip and $network should be in the same family for a valid comparison
67
+ if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
68
+ if ($mask < 0 || $mask > 32) { return false; }
69
+ $ipLong = ip2long($ip);
70
+ $networkLong = ip2long($network);
71
+ if ($ipLong === false || $networkLong === false) return false;
72
+ $netmask = -1 << (32 - $mask);
73
+ return ($ipLong & $netmask) === ($networkLong & $netmask);
74
+ } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
75
+ // IPv6 vs IPv6 CIDR
76
+ if ($mask < 0 || $mask > 128) { return false; }
77
+ $ipBinary = inet_pton($ip);
78
+ $networkBinary = inet_pton($network);
79
+ if ($ipBinary === false || $networkBinary === false) return false;
80
+
81
+ $bytesToCompare = (int)floor($mask / 8);
82
+ if (strncmp($ipBinary, $networkBinary, $bytesToCompare) !== 0) {
83
+ return false;
84
+ }
85
+
86
+ $bitsToCompare = $mask % 8;
87
+ if ($bitsToCompare > 0) {
88
+ $byteIndex = $bytesToCompare;
89
+ $bitmask = (0xFF << (8 - $bitsToCompare)) & 0xFF;
90
+ if ((ord($ipBinary[$byteIndex]) & $bitmask) !== (ord($networkBinary[$byteIndex]) & $bitmask)) {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ return true;
96
+ }
97
+
98
+ return false;
99
+ }
100
100
  }
@@ -2,10 +2,12 @@
2
2
  /**
3
3
  * Plugin Name: Fingerprint Anti-Bot & Proof-of-Work
4
4
  * Plugin URI: https://github.com/anonympins/fingerprint
5
- * Description: Protection bot haute performance pour WordPress avec Proof-of-Work client et détection d'anomalies.
6
- * Version: 0.7.1
5
+ * Description: High-performance client-side anti-bot protection and Proof-of-Work challenge verification for WordPress.
6
+ * Version: 0.7.2
7
7
  * Author: Anonympins
8
8
  * License: MIT
9
+ * Text Domain: fingerprint-wordpress
10
+ * Domain Path: /languages
9
11
  */
10
12
 
11
13
  declare(strict_types=1);
@@ -13,6 +15,7 @@ declare(strict_types=1);
13
15
  use Anonympins\Fingerprint\DirectFingerprint;
14
16
  use Anonympins\Fingerprint\Store\StoreManager;
15
17
  use Anonympins\Fingerprint\Config\SecurityProfiles;
18
+ use Anonympins\Fingerprint\Utils\MetricsManager;
16
19
  use Anonympins\Fingerprint\WordPress\WpDbStore;
17
20
 
18
21
  if (!defined('ABSPATH')) {
@@ -55,7 +58,7 @@ $foreignEnvHoneypotFields = [
55
58
  ];
56
59
 
57
60
  // =============================================================================
58
- // CONFIGURATION RAPIDE DES PROFILS DE SÉCURITÉ PAR CONTEXTE
61
+ // CONFIGURATION PAR DÉFAUT DES PROFILS DE SÉCURITÉ PAR CONTEXTE
59
62
  // =============================================================================
60
63
  $fingerprintSecurityProfiles = [
61
64
  'api' => [
@@ -96,6 +99,26 @@ $fingerprintSecurityProfiles = [
96
99
  ],
97
100
  ];
98
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
+
99
122
  // 1. Autoloader PSR-4 pour le moteur Fingerprint
100
123
  if (!class_exists(DirectFingerprint::class)) {
101
124
  $composerPaths = [
@@ -174,15 +197,14 @@ add_action('fingerprint_prune_expired_entries', function () {
174
197
  add_action('admin_notices', function () {
175
198
  if (!is_ssl()) {
176
199
  echo '<div class="notice notice-warning is-dismissible">';
177
- echo '<p><strong>[Fingerprint Anti-Bot Security Warning]</strong> : Votre site fonctionne actuellement sous le protocole non chiffré <code>HTTP</code>. ';
178
- echo 'Dans ce mode, l\'API native <em>Web Cryptography</em> (<code>crypto.subtle</code>) des navigateurs est désactivée par mesure de sécurité par les navigateurs modernes, ';
179
- echo 'forçant l\'exécution d\'un simulacre/fallback purement JavaScript plus lent et vulnérable aux attaques par interception (MitM). ';
180
- echo 'Il est fortement recommandé de déployer un certificat TLS/SSL et de forcer <code>HTTPS</code> pour garantir l\'intégrité des calculs PoW et la protection des cookies d\'identité.</p>';
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>';
181
203
  echo '</div>';
182
204
  }
183
205
  });
184
206
 
185
- // 5. Interception de sécurité au plus tôt du cycle de vie WordPress
207
+ // 6. Interception de sécurité au plus tôt du cycle de vie WordPress
186
208
  add_action('plugins_loaded', function () use ($fingerprintSecurityProfiles) {
187
209
  // Ignore WP-CLI et les exécutions internes de cron
188
210
  if ((defined('WP_CLI') && WP_CLI) || (defined('DOING_CRON') && DOING_CRON)) {
@@ -197,8 +219,11 @@ add_action('plugins_loaded', function () use ($fingerprintSecurityProfiles) {
197
219
  $isRestApi = defined('REST_REQUEST') && REST_REQUEST;
198
220
  $isAdmin = is_admin() || str_contains($requestUri, 'wp-login.php');
199
221
 
222
+ // Fusion avec les options enregistrées via l'admin WP
223
+ $effectiveProfiles = fingerprint_get_effective_profiles($fingerprintSecurityProfiles);
224
+
200
225
  // Possibilité de filtrer la configuration via functions.php ou un thème
201
- $configs = apply_filters('fingerprint_security_profiles', $fingerprintSecurityProfiles);
226
+ $configs = apply_filters('fingerprint_security_profiles', $effectiveProfiles);
202
227
 
203
228
  // Sélection adaptative du profil selon la cible de la requête
204
229
  if ($isRestApi || str_starts_with($requestUri, '/wp-json/')) {
@@ -214,4 +239,316 @@ add_action('plugins_loaded', function () use ($fingerprintSecurityProfiles) {
214
239
 
215
240
  // Inspecte la requête : bloque ou envoie le challenge si nécessaire et stoppe le script
216
241
  $guard->protect();
217
- }, 0);
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
+ }