Skip to content
Closed
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
5 changes: 5 additions & 0 deletions includes/class-webdecoy-browser-report.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
exit;
}

require_once __DIR__ . '/class-webdecoy-input-timing.php';

final class WebDecoy_Browser_Report
{
private const FLAGS = [
Expand Down Expand Up @@ -113,6 +115,9 @@ public static function build(array $detection, string $user_agent): array
if ($fp) {
$report['fp'] = $fp;
}
if (array_key_exists('input_evidence', $detection)) {
$report['input_evidence'] = WebDecoy_Input_Timing::normalize($detection['input_evidence']);
}
return $report;
}

Expand Down
89 changes: 89 additions & 0 deletions includes/class-webdecoy-input-timing.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

/** Bounded descriptive input timing; never contributes to enforcement. */

if (!defined('ABSPATH')) {
exit;
}
final class WebDecoy_Input_Timing
{
private static function object($v): array
{
return is_array($v) ? $v : [];
}
private static function number($v): bool
{
return (is_int($v) || is_float($v)) && is_finite((float) $v);
}
private static function numbers(array $raw, array $limits): array
{
$out = [];
foreach ($limits as $key => $max) {
$n = $raw[$key] ?? null;
if (self::number($n) && $n >= 0 && $n <= $max) {
$out[$key] = $n;
}
}
return $out;
}
public static function normalize($value): array
{
$raw = self::object($value);
$b = self::object($raw['behavioral'] ?? null);
$forensics = self::object($b['inputForensics'] ?? null);
$timing = self::object($forensics['keyTiming'] ?? null);
$form = self::object($raw['formAnalysis'] ?? null);
$out = self::numbers($b, ['totalPoints' => 1000000, 'touchEvents' => 200]);
if (is_bool($b['pointerHasNonMouseType'] ?? null)) {
$out['pointerHasNonMouseType'] = $b['pointerHasNonMouseType'];
}
$t = self::numbers($timing, ['version' => 1, 'keydowns' => 200]);
foreach (['intervals','holds'] as $key) {
$t[$key] = self::numbers(self::object($timing[$key] ?? null), ['samples' => 200,'mean' => 2000,'variance' => 4000000,'min' => 2000,'max' => 2000]);
}
$out['inputForensics'] = ['keyTiming' => $t];
return ['behavioral' => $out, 'formAnalysis' => ['typing' => self::numbers(self::object($form['typing'] ?? null), ['inputEvents' => 201,'pasteEvents' => 200,'pasteInputs' => 200,'inputsWithoutKeys' => 200,'inputsWithoutInputType' => 200])]];
}
private static function count($v, int $min, int $max): bool
{
return self::number($v) && floor($v) == $v && $v >= $min && $v <= $max;
}
private static function summary(array $s, int $max): bool
{
foreach (['samples','mean','variance','min','max'] as $key) {
if (!self::number($s[$key] ?? null)) {
return false;
}
}
return self::count($s['samples'], 20, $max) && $s['min'] >= 20 && $s['max'] <= 2000 && $s['min'] < $s['max']
&& $s['mean'] > $s['min'] && $s['mean'] < $s['max'] && $s['variance'] > 0
&& $s['variance'] <= (($s['max'] - $s['min']) ** 2) / 4;
}
public static function observe($value): array
{
$s = self::normalize($value);
$b = $s['behavioral'];
$t = $b['inputForensics']['keyTiming'];
$f = $s['formAnalysis']['typing'];
$result = ['id' => 'regular-input-timing-v1','mode' => 'observe','status' => 'unknown'];
if (
($t['version'] ?? null) != 1 || !self::count($t['keydowns'] ?? null, 21, 200)
|| !self::count($b['totalPoints'] ?? null, 1, 1000000) || ($b['pointerHasNonMouseType'] ?? null) !== false
|| !isset($f['inputEvents']) || $f['inputEvents'] != $t['keydowns']
) {
return $result;
}
foreach ([$b['touchEvents'] ?? null,$f['pasteEvents'] ?? null,$f['pasteInputs'] ?? null,$f['inputsWithoutKeys'] ?? null,$f['inputsWithoutInputType'] ?? null] as $n) {
if (!self::number($n) || $n != 0) {
return $result;
}
}
$a = $t['intervals'];
$h = $t['holds'];
if (!self::summary($a, 199) || !self::summary($h, 200) || $a['samples'] != $t['keydowns'] - 1 || $h['samples'] != $t['keydowns']) {
return $result;
}
$result['status'] = $a['variance'] < ($a['mean'] * 0.08) ** 2 && $h['variance'] < ($h['mean'] * 0.08) ** 2 ? 'detected' : 'clear';
return $result;
}
}
72 changes: 72 additions & 0 deletions public/js/webdecoy-scanner.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,74 @@

(function() {
'use strict';
// BEGIN bounded input timing collector (keep copies identical across browser surfaces).
function createInputTimingCollector(doc, clock) {
var keys = 0, inputs = 0, mouse = 0, touch = 0, nonMouse = false;
var invalid = false, target = null, down = null, previous = null, awaitingInput = false;
var intervals = [], holds = [], listeners = [], stopped = false;
function eligible(node) {
if (!node || !/^(INPUT|TEXTAREA)$/.test(node.tagName)) return false;
if (node.tagName === 'INPUT' && !/^(text|search)$/.test(node.type || 'text')) return false;
var autocomplete = node.getAttribute('autocomplete');
return (!autocomplete || autocomplete === 'off') && !node.disabled && !node.readOnly;
}
function listen(name, fn) { doc.addEventListener(name, fn, true); listeners.push([name, fn]); }
function reset(node) {
keys = 0; inputs = 0; invalid = false; down = previous = null;
awaitingInput = false; intervals = []; holds = []; target = node;
}
listen('keydown', function(e) {
if (!eligible(e.target)) { reset(null); return; }
if (target !== e.target || (keys > 0 && previous === null)) reset(e.target);
if (keys >= 200) { invalid = true; return; }
var now = clock();
if (e.isComposing || e.repeat || e.ctrlKey || e.altKey || e.metaKey || down !== null) invalid = true;
if (previous !== null) intervals.push(now - previous);
previous = down = now; awaitingInput = true; keys++;
});
listen('keyup', function(e) {
if (target !== e.target || down === null || keys > 200) return;
if (holds.length < 200) holds.push(clock() - down);
down = null;
});
listen('input', function(e) {
if (!eligible(e.target)) return;
if (target !== e.target) reset(e.target);
if (inputs < 201) inputs++;
if (!awaitingInput || e.isComposing || e.inputType !== 'insertText') invalid = true;
awaitingInput = false;
});
listen('paste', function(e) { if (eligible(e.target)) { if (target !== e.target) reset(e.target); invalid = true; } });
listen('compositionstart', function(e) { if (eligible(e.target)) { if (target !== e.target) reset(e.target); invalid = true; } });
listen('focusout', function(e) {
if (target === e.target) {
if (down !== null || awaitingInput || inputs !== keys) invalid = true;
down = previous = null;
}
});
listen('mousemove', function() { mouse = Math.min(mouse + 1, 1000000); });
listen('touchstart', function() { touch = Math.min(touch + 1, 200); });
listen('pointerdown', function(e) { if (e.pointerType !== 'mouse') nonMouse = true; });
function summary(values) {
if (!values.length) return { samples: 0, mean: 0, variance: 0, min: 0, max: 0 };
var mean = values.reduce(function(a, b) { return a + b; }, 0) / values.length;
return { samples: values.length, mean: mean,
variance: values.reduce(function(a, b) { return a + (b - mean) * (b - mean); }, 0) / values.length,
min: Math.min.apply(null, values), max: Math.max.apply(null, values) };
}
return {
snapshot: function() {
return { behavioral: { totalPoints: mouse, touchEvents: touch, pointerHasNonMouseType: nonMouse,
inputForensics: { keyTiming: { version: invalid ? 0 : 1, keydowns: keys,
intervals: summary(intervals), holds: summary(holds) } } },
formAnalysis: { typing: { inputEvents: inputs, pasteEvents: 0, pasteInputs: 0,
inputsWithoutKeys: 0, inputsWithoutInputType: 0 } } };
},
stop: function() { if (!stopped) listeners.forEach(function(item) { doc.removeEventListener(item[0], item[1], true); }); stopped = true; }
};
}
// END bounded input timing collector.


// Configuration injected by WordPress (via wp_localize_script)
if (typeof webdecoyScanner === 'undefined') {
Expand Down Expand Up @@ -1199,6 +1267,7 @@
ai: signals.aiBot || '',
hp: signals.honeypotTriggered ? 'filled' : '',
timing: signals.apiTiming ? signals.apiTiming.timing : null,
input_evidence: inputTimingCollector ? inputTimingCollector.snapshot() : undefined,
behavior: signals.behavioral ? signals.behavioral.metrics : null
});
} catch (error) {
Expand Down Expand Up @@ -1284,7 +1353,10 @@
/**
* Initialize
*/
var inputTimingCollector = null;
function init() {
inputTimingCollector = createInputTimingCollector(document, function() { return performance.now(); });
window.addEventListener('pagehide', function(e) { if (!e.persisted) inputTimingCollector.stop(); });
// Start behavioral tracking immediately
initBehavioralTracking();

Expand Down
50 changes: 50 additions & 0 deletions tests/InputTimingCollectorTest.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const paths = [path.join(__dirname,'../public/js/webdecoy-scanner.js')];
function source(file) {
const s=fs.readFileSync(file,'utf8');
return s.slice(s.indexOf(' // BEGIN bounded input timing'),s.indexOf(' // END bounded input timing'));
}
function setup(file) {
let time=0; const listeners=new Map();
const doc={addEventListener:(n,f)=>listeners.set(n,f),removeEventListener:(n)=>listeners.delete(n)};
const create=vm.runInNewContext(source(file)+'\ncreateInputTimingCollector');
const collector=create(doc,()=>time);
const field=(type='text',auto=null)=>({tagName:'INPUT',type,getAttribute:()=>auto,get value(){throw Error('read value');},get name(){throw Error('read name');}});
const input=field();
const emit=(name,event={})=>listeners.get(name)?.({target:input,...event});
const type=(i,event={})=>{time+=100+(i%2);emit('keydown',event);emit('input',{...event,inputType:'insertText'});time+=60+(i%3);emit('keyup',event);};
return {collector,field,input,emit,type,listeners};
}
test('browser surfaces use identical bounded collectors',()=>{for(const p of paths) assert.equal(source(p),source(paths[0]));});
for(const file of paths) {
test(file+': dynamic ordinary inputs yield summaries without reading content',()=>{
const h=setup(file);h.emit('mousemove');for(let i=0;i<32;i++)h.type(i);
const s=h.collector.snapshot(),t=s.behavioral.inputForensics.keyTiming;
assert.equal(t.version,1);assert.equal(t.keydowns,32);assert.equal(t.intervals.samples,31);assert.equal(t.holds.samples,32);
assert.equal(s.formAnalysis.typing.inputEvents,32);assert.ok(JSON.stringify(s).length<1024);
assert.equal(s.behavioral.totalPoints,1);
h.emit('focusout'); assert.equal(h.collector.snapshot().behavioral.inputForensics.keyTiming.version,1);
h.type(1); assert.equal(h.collector.snapshot().behavioral.inputForensics.keyTiming.keydowns,1);
});
test(file+': sensitive inputs are excluded, mixed/editing input is unknown',()=>{
for(const [type,auto] of [['password',null],['email',null],['tel',null],['text','cc-number'],['text','one-time-code']]) {
const h=setup(file);h.type(1,{target:h.field(type,auto)});assert.equal(h.collector.snapshot().behavioral.inputForensics.keyTiming.keydowns,0);
}
for(const event of ['paste','compositionstart']) {
const h=setup(file);h.type(1);h.emit(event);assert.equal(h.collector.snapshot().behavioral.inputForensics.keyTiming.version,0);
}
const h=setup(file);h.emit('input',{inputType:'insertReplacementText'});assert.equal(h.collector.snapshot().behavioral.inputForensics.keyTiming.version,0);
});
test(file+': modality, sample cap and listener cleanup',()=>{
const h=setup(file);h.emit('touchstart');h.emit('pointerdown',{pointerType:'pen'});
for(let i=0;i<250;i++)h.type(i);
const s=h.collector.snapshot(),t=s.behavioral.inputForensics.keyTiming;
assert.equal(t.version,0);assert.equal(t.keydowns,200);assert.ok(t.holds.samples<=200);assert.ok(t.intervals.samples<=199);
assert.equal(s.behavioral.touchEvents,1);assert.equal(s.behavioral.pointerHasNonMouseType,true);
h.collector.stop();h.collector.stop();assert.equal(h.listeners.size,0);
});
}
20 changes: 20 additions & 0 deletions tests/InputTimingTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php
require_once dirname(__DIR__) . '/includes/class-webdecoy-input-timing.php';
require_once dirname(__DIR__) . '/includes/class-webdecoy-browser-report.php';
TestRunner::test('input timing matches shared fixtures without changing forwarded score or flags', function () {
$fixtures = json_decode(file_get_contents(__DIR__.'/fixtures/input-timing.json'),true);
foreach ($fixtures['cases'] as $case) {
$observation=WebDecoy_Input_Timing::observe($case['signals']);
TestRunner::assertSame($case['status'],$observation['status'],$case['name']);
TestRunner::assertSame('observe',$observation['mode']);
$report=WebDecoy_Browser_Report::build(['s'=>12,'f'=>['webdriver'],'input_evidence'=>$case['signals']], '');
TestRunner::assertSame(12,$report['s']); TestRunner::assertSame(['webdriver'],$report['f']);
TestRunner::assertSame($case['status'],WebDecoy_Input_Timing::observe($report['input_evidence'])['status']);
}
});
TestRunner::test('input evidence drops arbitrary text, verdicts and invalid numeric values',function(){
$raw=['status'=>'detected','value'=>'PRIVATE','behavioral'=>['totalPoints'=>'PRIVATE','touchEvents'=>true]];
$report=WebDecoy_Browser_Report::build(['input_evidence'=>$raw], '');
TestRunner::assertSame(false,strpos(json_encode($report),'PRIVATE'));
TestRunner::assertSame('unknown',WebDecoy_Input_Timing::observe($report['input_evidence'])['status']);
});
3 changes: 3 additions & 0 deletions tests/ScannerReportTest.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,6 @@ test('keeps beacon delivery when fetch has no keepalive support', async () => {
await send();
assert.deepEqual(requests.map(body => body.get('action')), [report]);
});

// The scanner report CI entry point also exercises the shipped timing collector.
require('./InputTimingCollectorTest.cjs');
Loading
Loading