From 9967777dc0db76e61d0f1e39c02cede3f291458b Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Sat, 21 Nov 2026 21:08:36 -0600 Subject: [PATCH] Recover WordPress scanner reports on cached pages --- .github/workflows/ci.yml | 7 +++ README.md | 13 ++++ admin/partials/settings-page.php | 1 + public/js/webdecoy-scanner.js | 105 +++++++++++++++++++++---------- tests/ScannerReportTest.cjs | 82 ++++++++++++++++++++++++ webdecoy.php | 40 +++++++++--- 6 files changed, 207 insertions(+), 41 deletions(-) create mode 100644 tests/ScannerReportTest.cjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 67283da..b0465d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,3 +91,10 @@ jobs: # were not committed with it, fails here. - name: Run tests run: php tests/run.php + + - uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Replay scanner report transport + run: node --test tests/ScannerReportTest.cjs diff --git a/README.md b/README.md index 5dd8e65..c849839 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,19 @@ Three rapid synthetic failed orders. The fourth checkout attempt refused. Separa 3. Upload the ZIP file and click **Install Now** 4. Activate the plugin +## Coverage on cached pages + +A cache can answer the page request before WebDecoy's PHP detection or crawler +counter runs. Supported WordPress caches expose an opt-in for known AI and search +crawlers on **WebDecoy → AI Traffic**. Use a WebDecoy edge sensor when an upstream +cache serves requests before WordPress. + +Cached pages can still report browser signals if the scanner script loads and +the site's same-origin `wp-admin/admin-ajax.php` accepts POST requests. If +WordPress rejects an expired scanner nonce, the scanner fetches a current one +and retries the report once. Keep this AJAX endpoint out of cache and purge +cached HTML after upgrading so it loads the updated scanner. + ## Development ### Prerequisites diff --git a/admin/partials/settings-page.php b/admin/partials/settings-page.php index e9d0d0e..a379467 100644 --- a/admin/partials/settings-page.php +++ b/admin/partials/settings-page.php @@ -926,6 +926,7 @@

+

diff --git a/public/js/webdecoy-scanner.js b/public/js/webdecoy-scanner.js index 5b94fa8..1e1716f 100644 --- a/public/js/webdecoy-scanner.js +++ b/public/js/webdecoy-scanner.js @@ -1188,44 +1188,81 @@ var clientScore = calculateScore(signals); - // Build payload for WordPress AJAX endpoint - var payload = { - action: 'webdecoy_client_detection', - nonce: config.nonce, - detection: { - v: 1, - s: clientScore, - f: flags, - fp: fingerprint, - url: window.location.href, - ref: document.referrer, - ts: Date.now(), - ai: signals.aiBot || '', - hp: signals.honeypotTriggered ? 'filled' : '', - timing: signals.apiTiming ? signals.apiTiming.timing : null, - behavior: signals.behavioral ? signals.behavioral.metrics : null + submitScannerReport({ + v: 1, + s: clientScore, + f: flags, + fp: fingerprint, + url: window.location.href, + ref: document.referrer, + ts: Date.now(), + ai: signals.aiBot || '', + hp: signals.honeypotTriggered ? 'filled' : '', + timing: signals.apiTiming ? signals.apiTiming.timing : null, + behavior: signals.behavioral ? signals.behavioral.metrics : null + }); + } catch (error) { + // Silently fail + } + } + + function submitScannerReport(detection) { + var serialized = JSON.stringify(detection); + function reportBody(nonce) { + return 'action=webdecoy_client_detection&nonce=' + encodeURIComponent(nonce) + + '&detection=' + encodeURIComponent(serialized); + } + + if (typeof window.fetch === 'function' && typeof URL === 'function' && + typeof Request === 'function' && 'keepalive' in Request.prototype) { + var ajax = new URL(config.ajaxUrl, window.location.href); + if (ajax.origin === window.location.origin) { + function post(body) { + return window.fetch(ajax.href, { + method: 'POST', + mode: 'same-origin', + credentials: 'same-origin', + redirect: 'error', + cache: 'no-store', + keepalive: true, + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: body + }); } - }; - // Send to WordPress AJAX endpoint - if (navigator.sendBeacon) { - var formData = new FormData(); - formData.append('action', 'webdecoy_client_detection'); - formData.append('nonce', config.nonce); - formData.append('detection', JSON.stringify(payload.detection)); - navigator.sendBeacon(config.ajaxUrl, formData); - } else { - // Fallback for older browsers - var xhr = new XMLHttpRequest(); - xhr.open('POST', config.ajaxUrl, true); - xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); - var params = 'action=webdecoy_client_detection&nonce=' + encodeURIComponent(config.nonce) + - '&detection=' + encodeURIComponent(JSON.stringify(payload.detection)); - xhr.send(params); + // A nonce rejection is emitted before any report side effects. Retry + // only once, after that explicit response and a successful renewal. + return post(reportBody(config.nonce)).then(function(response) { + if (response.status !== 403) return; + return response.json().then(function(result) { + if (!result || !result.data || result.data.code !== 'invalid_scanner_nonce') return; + return post('action=webdecoy_scanner_nonce').then(function(refresh) { + if (!refresh.ok) return; + return refresh.json().then(function(result) { + var nonce = result && result.success && result.data && result.data.nonce; + if (typeof nonce === 'string' && nonce && nonce !== config.nonce) { + return post(reportBody(nonce)); + } + }); + }); + }); + }).catch(function() {}); } - } catch (error) { - // Silently fail } + + if (navigator.sendBeacon) { + var formData = new FormData(); + formData.append('action', 'webdecoy_client_detection'); + formData.append('nonce', config.nonce); + formData.append('detection', serialized); + navigator.sendBeacon(config.ajaxUrl, formData); + return; + } + + var xhr = new XMLHttpRequest(); + xhr.open('POST', config.ajaxUrl, true); + xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); + xhr.send(reportBody(config.nonce)); } /** diff --git a/tests/ScannerReportTest.cjs b/tests/ScannerReportTest.cjs new file mode 100644 index 0000000..39a2af3 --- /dev/null +++ b/tests/ScannerReportTest.cjs @@ -0,0 +1,82 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const scanner = fs.readFileSync(path.join(__dirname, '../public/js/webdecoy-scanner.js'), 'utf8'); +const init = ' init();\n})();'; +assert.ok(scanner.includes(init)); +const fixture = scanner.replace(init, ' window.submitReport = submitScannerReport;\n})();'); +const origin = 'https://fixture.example'; +const report = 'webdecoy_client_detection'; +const refresh = 'webdecoy_scanner_nonce'; +const expired = { status: 403, json: async () => ({ data: { code: 'invalid_scanner_nonce' } }) }; +const renewed = { ok: true, json: async () => ({ success: true, data: { nonce: 'current' } }) }; + +function start(responses, ajaxUrl = origin + '/wp-admin/admin-ajax.php', requestClass = Request) { + const requests = []; + const window = { + location: { origin, href: origin + '/cached-page/' }, + fetch: async (url, options) => { + assert.equal(url, ajaxUrl); + assert.equal(options.mode, 'same-origin'); + assert.equal(options.redirect, 'error'); + assert.equal(options.keepalive, true); + const body = new URLSearchParams(options.body); + requests.push(body); + const response = responses[requests.length - 1]; + if (response instanceof Error) throw response; + return response; + } + }; + vm.runInNewContext(fixture, { + window, URL, FormData, Request: requestClass, + webdecoyScanner: { enabled: true, ajaxUrl, nonce: 'cached' }, + navigator: { sendBeacon: (url, body) => { + assert.equal(url, ajaxUrl); + requests.push(body); + } } + }); + return { send: () => window.submitReport({ s: 25 }), requests }; +} + +test('reloads the nonce once and retries the original report', async () => { + const { send, requests } = start([expired, renewed, expired]); + await send(); + assert.deepEqual(requests.map(body => body.get('action')), [report, refresh, report]); + assert.deepEqual(requests.map(body => body.get('nonce')), ['cached', null, 'current']); + assert.equal(requests[0].get('detection'), requests[2].get('detection')); +}); + +test('leaves acknowledged, unrelated, rate-limited, and ambiguous failures alone', async () => { + for (const outcome of [ + { status: 200 }, + { status: 403, json: async () => ({ data: { code: 'different_error' } }) }, + { status: 429 }, + new Error('connection closed') + ]) { + const { send, requests } = start([outcome]); + await send(); + assert.deepEqual(requests.map(body => body.get('action')), [report]); + } +}); + +test('requires a successful renewal before retrying', async () => { + const { send, requests } = start([expired, { ok: false, status: 403 }]); + await send(); + assert.deepEqual(requests.map(body => body.get('action')), [report, refresh]); +}); + +test('keeps the existing beacon submission for a separate admin origin', async () => { + const { send, requests } = start([], 'https://admin.fixture.example/wp-admin/admin-ajax.php'); + await send(); + assert.deepEqual(requests.map(body => body.get('action')), [report]); + assert.equal(requests[0].get('nonce'), 'cached'); +}); + +test('keeps beacon delivery when fetch has no keepalive support', async () => { + const { send, requests } = start([], origin + '/wp-admin/admin-ajax.php', function LegacyRequest() {}); + await send(); + assert.deepEqual(requests.map(body => body.get('action')), [report]); +}); diff --git a/webdecoy.php b/webdecoy.php index b6ed922..d7b44f0 100644 --- a/webdecoy.php +++ b/webdecoy.php @@ -948,6 +948,8 @@ private function init_hooks(): void // AJAX handlers for client-side scanner (both logged-in and guests) add_action('wp_ajax_webdecoy_client_detection', [$this, 'ajax_client_detection']); add_action('wp_ajax_nopriv_webdecoy_client_detection', [$this, 'ajax_client_detection']); + add_action('wp_ajax_webdecoy_scanner_nonce', [$this, 'ajax_scanner_nonce']); + add_action('wp_ajax_nopriv_webdecoy_scanner_nonce', [$this, 'ajax_scanner_nonce']); // PoW challenge AJAX handlers add_action('wp_ajax_webdecoy_pow_challenge', [$this, 'ajax_pow_challenge']); @@ -2803,12 +2805,7 @@ public function admin_scripts(string $hook): void */ public function frontend_scripts(): void { - if (!$this->options['scanner_enabled']) { - return; - } - - // Skip for logged-in users if configured - if ($this->options['scanner_exclude_logged_in'] && is_user_logged_in()) { + if (!$this->scanner_enabled_for_visitor()) { return; } @@ -2922,6 +2919,35 @@ public function inject_js_verification_token(): void ]); } + private function scanner_enabled_for_visitor(): bool + { + return !empty($this->options['scanner_enabled']) + && (empty($this->options['scanner_exclude_logged_in']) || !is_user_logged_in()); + } + + /** Return a current scanner nonce to a same-origin browser on a cached page. */ + public function ajax_scanner_nonce(): void + { + $method = isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD'])) : ''; + $ajax = wp_parse_url(admin_url('admin-ajax.php')); + $scheme = strtolower($ajax['scheme'] ?? ''); + $host = strtolower($ajax['host'] ?? ''); + $port = $ajax['port'] ?? null; + $origin = $scheme . '://' . $host; + if ($port !== null && $port !== ($scheme === 'https' ? 443 : 80)) { + $origin .= ':' . $port; + } + + if ($method !== 'POST' || !in_array($scheme, ['http', 'https'], true) || $host === '' + || get_http_origin() !== $origin || !$this->scanner_enabled_for_visitor()) { + wp_send_json_error(['message' => 'Scanner nonce unavailable'], 403); + return; + } + + nocache_headers(); + wp_send_json_success(['nonce' => wp_create_nonce('webdecoy_scanner')]); + } + /** * AJAX: Handle client-side detection * Receives detection from JavaScript scanner and forwards to WebDecoy ingest @@ -2931,7 +2957,7 @@ public function ajax_client_detection(): void // Verify nonce // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce verification handles sanitization if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'webdecoy_scanner')) { - wp_send_json_error(['message' => 'Invalid nonce'], 403); + wp_send_json_error(['message' => 'Invalid nonce', 'code' => 'invalid_scanner_nonce'], 403); return; }