diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b0465d2..193ee0c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,4 +97,4 @@ jobs: node-version: '22' - name: Replay scanner report transport - run: node --test tests/ScannerReportTest.cjs + run: node --test tests/ScannerReportTest.cjs tests/HandoffObservationTest.cjs diff --git a/includes/class-webdecoy-browser-report.php b/includes/class-webdecoy-browser-report.php index 2f03d9f..1eeaf08 100644 --- a/includes/class-webdecoy-browser-report.php +++ b/includes/class-webdecoy-browser-report.php @@ -113,9 +113,107 @@ public static function build(array $detection, string $user_agent): array if ($fp) { $report['fp'] = $fp; } + $input_evidence = self::input_evidence($detection['input_evidence'] ?? null); + if ($input_evidence) { + $report['input_evidence'] = $input_evidence; + } return $report; } + /** Whether a caller supplied a structurally valid bounded action sample. */ + public static function has_action_windows(array $detection): bool + { + return self::input_evidence($detection['input_evidence'] ?? null) !== []; + } + + /** Whether the relay should forward without local logging or enforcement. */ + public static function is_handoff_observation(array $detection): bool + { + return ($detection['s'] ?? null) === 0 + && ($detection['f'] ?? null) === [] + && self::has_action_windows($detection); + } + + /** @return array>> */ + private static function input_evidence($value): array + { + if (!is_array($value) || !is_array($value['behavioral'] ?? null)) { + return []; + } + $sample = $value['behavioral']['actionWindows'] ?? null; + if (!is_array($sample) + || ($sample['version'] ?? null) !== 1 + || ($sample['quantumMs'] ?? null) !== 250 + || ($sample['maxWindows'] ?? null) !== 48 + || !is_bool($sample['truncated'] ?? null) + || !is_array($sample['windows'] ?? null) + || count($sample['windows']) > 48) { + return []; + } + + $kinds = ['click', 'key', 'scroll', 'touch']; + $families = ['pointer_path', 'pointer_provenance', 'typing_cadence', 'scroll_behavior', 'touch_provenance']; + $windows = []; + foreach ($sample['windows'] as $window) { + if (!is_array($window) + || !is_int($window['t'] ?? null) || $window['t'] < 0 || $window['t'] > 65535 + || !in_array($window['kind'] ?? null, $kinds, true) + || !is_int($window['events'] ?? null) || $window['events'] < 0 || $window['events'] > 255) { + return []; + } + $human = self::evidence_families($window['humanEvidenceFamilies'] ?? null, $families); + $agent = self::evidence_families($window['agentEvidenceFamilies'] ?? null, $families); + if ($human === null || $agent === null) { + return []; + } + $windows[] = [ + 't' => $window['t'], + 'kind' => $window['kind'], + 'events' => $window['events'], + 'humanEvidenceFamilies' => $human, + 'agentEvidenceFamilies' => $agent, + ]; + } + if ($windows === []) { + return []; + } + + $bounded = [ + 'version' => 1, + 'quantumMs' => 250, + 'maxWindows' => 48, + 'truncated' => $sample['truncated'], + 'windows' => $windows, + ]; + while (strlen((string) wp_json_encode($bounded)) > 8192 && $bounded['windows'] !== []) { + array_pop($bounded['windows']); + $bounded['truncated'] = true; + } + if ($bounded['windows'] === []) { + return []; + } + return ['behavioral' => ['actionWindows' => $bounded]]; + } + + /** @return array|null */ + private static function evidence_families($values, array $allowlist): ?array + { + if (!is_array($values) || count($values) > 4) { + return null; + } + $result = []; + foreach ($values as $value) { + if (!is_string($value) || !in_array($value, $allowlist, true)) { + return null; + } + if (!in_array($value, $result, true)) { + $result[] = $value; + } + } + sort($result); + return $result; + } + /** @return array */ private static function bounded_numbers(array $data, array $limits): array { diff --git a/public/js/webdecoy-scanner.js b/public/js/webdecoy-scanner.js index 1e1716f..c5a1999 100644 --- a/public/js/webdecoy-scanner.js +++ b/public/js/webdecoy-scanner.js @@ -20,6 +20,156 @@ return; } + // A bounded, content-free interaction summary. The hosted ingest service + // independently closes these windows into an observe-only actor timeline. + function createActionWindowCollector(doc, win, clock) { + var VERSION = 1, QUANTUM_MS = 250, MAX_WINDOWS = 48, MAX_BYTES = 8192; + var started = clock(), windows = [], listeners = [], stopped = false, truncated = false; + var pointerMoves = [], keysDown = {}, lastScroll = null, pointerX = null, pointerY = null; + var excludedKeys = { Shift: true, Control: true, Alt: true, Meta: true, + CapsLock: true, NumLock: true, ScrollLock: true }; + function listen(name, fn) { doc.addEventListener(name, fn, true); listeners.push([name, fn]); } + function family(list, value) { if (list.indexOf(value) === -1 && list.length < 4) list.push(value); } + function action(kind, now, mergeWithin) { + var item = windows.length ? windows[windows.length - 1] : null; + if (mergeWithin > 0 && item && item.kind === kind && now - item.lastAt <= mergeWithin) { + item.lastAt = now; + return item; + } + if (windows.length >= MAX_WINDOWS) { truncated = true; return null; } + item = { t: Math.min(65535, Math.max(0, Math.floor((now - started) / QUANTUM_MS))), + kind: kind, events: 0, firstAt: now, lastAt: now, holds: [], + humanEvidenceFamilies: [], agentEvidenceFamilies: [] }; + windows.push(item); + return item; + } + listen('pointermove', function(e) { + var now = clock(), coalesced = 1, zeroMovement = false; + if (e.pointerType !== 'touch' && typeof e.getCoalescedEvents === 'function') { + try { var values = e.getCoalescedEvents(); coalesced = values && values.length ? values.length : 1; } + catch (_err) { coalesced = 1; } + } + if (e.pointerType !== 'touch' && pointerX !== null && + (e.clientX !== pointerX || e.clientY !== pointerY) && + (Number(e.movementX) || 0) === 0 && (Number(e.movementY) || 0) === 0) zeroMovement = true; + pointerMoves.push({ at: now, coalesced: coalesced, zeroMovement: zeroMovement }); + if (pointerMoves.length > 16) pointerMoves.shift(); + pointerX = Number(e.clientX) || 0; pointerY = Number(e.clientY) || 0; + }); + listen('pointerdown', function(e) { + var now = clock(), x = Number(e.clientX) || 0, y = Number(e.clientY) || 0; + var teleport = pointerX !== null && Math.hypot(x - pointerX, y - pointerY) > 150; + var item = action('click', now, 0); + if (!item) return; + item.events = 1; + var recent = pointerMoves.filter(function(move) { return now >= move.at && now - move.at <= 1000; }); + if (recent.length >= 3 && recent[recent.length - 1].at - recent[0].at >= 32 && + recent.some(function(move) { return move.coalesced > 1; }) && + !recent.some(function(move) { return move.zeroMovement; })) family(item.humanEvidenceFamilies, 'pointer_path'); + var last = recent.length ? recent[recent.length - 1] : null; + if (teleport || (last && now - last.at <= 50 && last.coalesced <= 1 && last.zeroMovement)) { + family(item.agentEvidenceFamilies, 'pointer_provenance'); + } + pointerMoves = []; pointerX = x; pointerY = y; + }); + listen('keydown', function(e) { + var now = clock(); + if (e.repeat || excludedKeys[e.key]) return; + var id = e.code || e.key; + if (!id) return; + var item = action('key', now, 1000); + if (!item) return; + item.events = Math.min(255, item.events + 1); + keysDown[id] = { at: now, item: item }; + }); + listen('keyup', function(e) { + var id = e.code || e.key, press = keysDown[id]; + if (!press) return; + delete keysDown[id]; + var hold = clock() - press.at; + if (hold > 0 && hold < 2000 && press.item.holds.length < 16) press.item.holds.push(hold); + }); + listen('scroll', function() { + var now = clock(), x = Number(win.scrollX) || 0, y = Number(win.scrollY) || 0; + var item = action('scroll', now, 250); + if (!item) return; + item.events = Math.min(255, item.events + 1); + var step = lastScroll ? Math.abs(x - lastScroll.x) + Math.abs(y - lastScroll.y) : 0; + item.maxStep = Math.max(item.maxStep || 0, step); + lastScroll = { x: x, y: y }; + }); + ['touchstart', 'touchmove', 'touchend'].forEach(function(name) { + listen(name, function(e) { + var touches = e.touches && e.touches.length ? e.touches : e.changedTouches; + if (!touches || !touches.length) return; + var now = clock(), touch = touches[0], item = action('touch', now, e.type === 'touchstart' ? 0 : 750); + if (!item) return; + item.events = Math.min(255, item.events + 1); + var force = typeof touch.force === 'number' ? touch.force : 0; + var radius = Math.max(typeof touch.radiusX === 'number' ? touch.radiusX : 0, + typeof touch.radiusY === 'number' ? touch.radiusY : 0); + item.forceMin = Math.min(item.forceMin === undefined ? force : item.forceMin, force); + item.forceMax = Math.max(item.forceMax === undefined ? force : item.forceMax, force); + item.radiusMin = Math.min(item.radiusMin === undefined ? radius : item.radiusMin, radius); + item.radiusMax = Math.max(item.radiusMax === undefined ? radius : item.radiusMax, radius); + item.multiTouch = item.multiTouch || Boolean(e.touches && e.touches.length > 1); + }); + }); + function boundedSnapshot() { + var closed = windows.map(function(item) { + if (item.kind === 'key' && item.holds.length >= 3) { + var plausible = item.holds.filter(function(hold) { return hold >= 20 && hold <= 500; }); + var range = Math.max.apply(null, item.holds) - Math.min.apply(null, item.holds); + if (plausible.length >= 2 && range >= 5) family(item.humanEvidenceFamilies, 'typing_cadence'); + if (item.holds.every(function(hold) { return hold <= 5; })) family(item.agentEvidenceFamilies, 'typing_cadence'); + } + if (item.kind === 'scroll') { + if (item.events >= 3 && item.lastAt - item.firstAt >= 32) family(item.humanEvidenceFamilies, 'scroll_behavior'); + else if (item.events === 1 && (item.maxStep || 0) >= 300) family(item.agentEvidenceFamilies, 'scroll_behavior'); + } + if (item.kind === 'touch' && item.events >= 3 && + (item.multiTouch || item.forceMax - item.forceMin > 0.05 || item.radiusMax - item.radiusMin > 1)) { + family(item.humanEvidenceFamilies, 'touch_provenance'); + } + return { t: item.t, kind: item.kind, events: item.events, + humanEvidenceFamilies: item.humanEvidenceFamilies.slice().sort(), + agentEvidenceFamilies: item.agentEvidenceFamilies.slice().sort() }; + }); + var value = { version: VERSION, quantumMs: QUANTUM_MS, maxWindows: MAX_WINDOWS, + truncated: truncated, windows: closed }; + while (JSON.stringify(value).length > MAX_BYTES && value.windows.length) { + value.windows.pop(); value.truncated = true; + } + return value; + } + return { + snapshot: boundedSnapshot, + stop: function() { + if (!stopped) listeners.forEach(function(item) { doc.removeEventListener(item[0], item[1], true); }); + stopped = true; pointerMoves = []; keysDown = {}; + } + }; + } + + var actionWindowCollector = null; + var handoffObservationSent = false; + + function collectActionEvidence() { + return actionWindowCollector ? { behavioral: { actionWindows: actionWindowCollector.snapshot() } } : null; + } + + function hasPotentialHandoff(actionWindows) { + var previous = 'unknown'; + return actionWindows.windows.some(function(window) { + var human = window.humanEvidenceFamilies.length > 0; + var agent = window.agentEvidenceFamilies.length > 0; + var actor = human === agent ? 'unknown' : (human ? 'human' : 'agent'); + var changed = previous !== 'unknown' && actor !== 'unknown' && previous !== actor; + previous = actor; + return changed; + }); + } + /** * Detects if browser is running under webdriver protocol */ @@ -1187,6 +1337,10 @@ } var clientScore = calculateScore(signals); + var inputEvidence = collectActionEvidence(); + if (inputEvidence && hasPotentialHandoff(inputEvidence.behavioral.actionWindows)) { + handoffObservationSent = true; + } submitScannerReport({ v: 1, @@ -1199,7 +1353,8 @@ ai: signals.aiBot || '', hp: signals.honeypotTriggered ? 'filled' : '', timing: signals.apiTiming ? signals.apiTiming.timing : null, - behavior: signals.behavioral ? signals.behavioral.metrics : null + behavior: signals.behavioral ? signals.behavioral.metrics : null, + input_evidence: inputEvidence }); } catch (error) { // Silently fail @@ -1287,6 +1442,26 @@ function init() { // Start behavioral tracking immediately initBehavioralTracking(); + actionWindowCollector = createActionWindowCollector(document, window, function() { return performance.now(); }); + + window.addEventListener('pagehide', function(event) { + var evidence = collectActionEvidence(); + if (!handoffObservationSent && evidence && hasPotentialHandoff(evidence.behavioral.actionWindows)) { + handoffObservationSent = true; + submitScannerReport({ + v: 1, + s: 0, + f: [], + url: window.location.href, + ref: document.referrer, + ts: Date.now(), + input_evidence: evidence + }); + } + if (!event.persisted && actionWindowCollector) { + actionWindowCollector.stop(); + } + }); if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', sendDetection); diff --git a/tests/BrowserReportTest.php b/tests/BrowserReportTest.php index 0e66741..5a8a5c8 100644 --- a/tests/BrowserReportTest.php +++ b/tests/BrowserReportTest.php @@ -5,6 +5,12 @@ if (!defined('ABSPATH')) { define('ABSPATH', '/tmp/'); } +if (!function_exists('wp_json_encode')) { + function wp_json_encode($value) + { + return json_encode($value); + } +} require_once dirname(__DIR__) . '/includes/class-webdecoy-browser-report.php'; TestRunner::test('the AJAX relay builds a separate browser report from aggregate observations', function () { @@ -60,3 +66,71 @@ TestRunner::assertTrue(!array_key_exists('behavior', $report)); TestRunner::assertTrue(!array_key_exists('fp', $report)); }); + +TestRunner::test('browser reports preserve only bounded content-free action windows', function () { + $windows = [ + [ + 't' => 1, + 'kind' => 'key', + 'events' => 3, + 'humanEvidenceFamilies' => ['typing_cadence'], + 'agentEvidenceFamilies' => [], + 'key' => 'PRIVATE_FIXTURE', + ], + [ + 't' => 9, + 'kind' => 'key', + 'events' => 3, + 'humanEvidenceFamilies' => [], + 'agentEvidenceFamilies' => ['typing_cadence'], + 'value' => 'PRIVATE_FIXTURE', + ], + ]; + $report = WebDecoy_Browser_Report::build([ + 's' => 0, + 'f' => [], + 'input_evidence' => ['behavioral' => ['actionWindows' => [ + 'version' => 1, + 'quantumMs' => 250, + 'maxWindows' => 48, + 'truncated' => false, + 'windows' => $windows, + ]]], + ], ''); + + TestRunner::assertTrue(WebDecoy_Browser_Report::has_action_windows([ + 'input_evidence' => $report['input_evidence'], + ])); + TestRunner::assertTrue(WebDecoy_Browser_Report::is_handoff_observation([ + 's' => 0, + 'f' => [], + 'input_evidence' => $report['input_evidence'], + ])); + TestRunner::assertTrue(!WebDecoy_Browser_Report::is_handoff_observation([ + 's' => 20, + 'f' => [], + 'input_evidence' => $report['input_evidence'], + ])); + TestRunner::assertSame('typing_cadence', $report['input_evidence']['behavioral']['actionWindows']['windows'][0]['humanEvidenceFamilies'][0]); + TestRunner::assertTrue(strpos(json_encode($report), 'PRIVATE_FIXTURE') === false); +}); + +TestRunner::test('browser reports reject malformed or unbounded action windows', function () { + $invalid = ['behavioral' => ['actionWindows' => [ + 'version' => 1, + 'quantumMs' => 250, + 'maxWindows' => 48, + 'truncated' => false, + 'windows' => [[ + 't' => 0, + 'kind' => 'key', + 'events' => 3, + 'humanEvidenceFamilies' => ['unrecognized'], + 'agentEvidenceFamilies' => [], + ]], + ]]]; + $report = WebDecoy_Browser_Report::build(['s' => 0, 'f' => [], 'input_evidence' => $invalid], ''); + + TestRunner::assertTrue(!isset($report['input_evidence'])); + TestRunner::assertTrue(!WebDecoy_Browser_Report::has_action_windows(['input_evidence' => $invalid])); +}); diff --git a/tests/HandoffObservationTest.cjs b/tests/HandoffObservationTest.cjs new file mode 100644 index 0000000..a55a905 --- /dev/null +++ b/tests/HandoffObservationTest.cjs @@ -0,0 +1,79 @@ +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 start = scanner.indexOf('function createActionWindowCollector'); +const end = scanner.indexOf('\n\n var actionWindowCollector', start); +assert.ok(start > 0 && end > start, 'collector source is present'); +const createCollector = vm.runInNewContext('(' + scanner.slice(start, end) + ')', { Math, Number, Boolean, JSON }); + +function harness() { + let now = 0; + const listeners = new Map(); + const document = { + addEventListener(name, fn) { + if (!listeners.has(name)) listeners.set(name, []); + listeners.get(name).push(fn); + }, + removeEventListener(name, fn) { + listeners.set(name, (listeners.get(name) || []).filter((value) => value !== fn)); + } + }; + const window = { scrollX: 0, scrollY: 0 }; + const collector = createCollector(document, window, () => now); + function emit(name, values = {}) { + for (const fn of listeners.get(name) || []) fn({ type: name, ...values }); + } + function type(holds) { + holds.forEach((hold, index) => { + const code = 'Key' + String.fromCharCode(65 + index); + emit('keydown', { key: code, code, repeat: false }); + now += hold; + emit('keyup', { key: code, code }); + now += 10; + }); + } + return { collector, emit, type, advance(value) { now += value; }, listeners }; +} + +test('records a bounded human to agent typing transition without content', () => { + const value = harness(); + value.type([35, 55, 75]); + value.advance(1100); + value.type([1, 1, 1]); + const sample = value.collector.snapshot(); + + assert.equal(sample.version, 1); + assert.equal(sample.quantumMs, 250); + assert.equal(Array.from(sample.windows[0].humanEvidenceFamilies).join(','), 'typing_cadence'); + assert.equal(Array.from(sample.windows[1].agentEvidenceFamilies).join(','), 'typing_cadence'); + assert.doesNotMatch(JSON.stringify(sample), /KeyA|KeyB|KeyC|value|selector|clientX|clientY/); +}); + +test('ambiguous activity contains no actor evidence and cannot claim a handoff', () => { + const value = harness(); + value.emit('pointerdown', { pointerType: 'mouse', clientX: 10, clientY: 10 }); + const window = value.collector.snapshot().windows[0]; + + assert.equal(window.humanEvidenceFamilies.length, 0); + assert.equal(window.agentEvidenceFamilies.length, 0); + assert.equal(scanner.includes('e.isTrusted'), false); +}); + +test('caps the sample and removes every listener', () => { + const value = harness(); + for (let index = 0; index < 60; index++) { + value.emit('pointerdown', { pointerType: 'mouse', clientX: index, clientY: index }); + value.advance(300); + } + const sample = value.collector.snapshot(); + assert.equal(sample.windows.length, 48); + assert.equal(sample.truncated, true); + assert.ok(JSON.stringify(sample).length <= 8192); + + value.collector.stop(); + assert.ok([...value.listeners.values()].every((items) => items.length === 0)); +}); diff --git a/webdecoy.php b/webdecoy.php index 3393d7a..8c786cd 100644 --- a/webdecoy.php +++ b/webdecoy.php @@ -2936,14 +2936,19 @@ public function ajax_client_detection(): void return; } - // Log detection locally - $this->log_client_detection($detection, $ip); + $score = intval($detection['s'] ?? 0); + $handoff_observation = WebDecoy_Browser_Report::is_handoff_observation($detection); + + // Observation-only handoff samples are validated by hosted ingest. Do + // not let an unauthenticated browser turn one into a local row or block. + if (!$handoff_observation) { + $this->log_client_detection($detection, $ip); + } // Check if should block based on score and action setting - $score = intval($detection['s'] ?? 0); $action = $this->options['block_action'] ?? 'block'; - if ($score >= $this->options['min_score_to_block'] && $action === 'block') { + if (!$handoff_observation && $score >= $this->options['min_score_to_block'] && $action === 'block') { // Only block if action is set to 'block' $flags = implode(', ', $detection['f'] ?? []); $this->enforce_block($ip, "Client detection (score: {$score}): {$flags}");