Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions admin/partials/settings-page.php
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,7 @@
<div id="tab-scanner-tab" class="webdecoy-tab-content">
<h2><?php esc_html_e('Client-Side Bot Scanner', 'webdecoy'); ?></h2>
<p class="description"><?php esc_html_e('The bot scanner runs in visitors\' browsers to detect automation tools, headless browsers, and other bot indicators.', 'webdecoy'); ?></p>
<p class="description"><?php esc_html_e('Full-page cache hits can bypass PHP detection and crawler counts. Cached pages can still report browser signals when the scanner loads and the same-origin WordPress AJAX endpoint is reachable. Use the cache bypass setting for supported plugins or an edge sensor to see requests served upstream.', 'webdecoy'); ?></p>

<table class="form-table">
<tr>
Expand Down
105 changes: 71 additions & 34 deletions public/js/webdecoy-scanner.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

/**
Expand Down
82 changes: 82 additions & 0 deletions tests/ScannerReportTest.cjs
Original file line number Diff line number Diff line change
@@ -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]);
});
40 changes: 33 additions & 7 deletions webdecoy.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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
Expand All @@ -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;
}

Expand Down
Loading