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
52 changes: 48 additions & 4 deletions packages/client/src/collectors/behavioral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ interface ClickData {
holdDuration?: number;
}

const MAX_PENDING_KEY_HOLDS = 64;
const MAX_KEY_HOLD_SAMPLES = 200;
const MAX_KEY_HOLD_MS = 2_000;
const KEY_HOLD_MODIFIERS = new Set(['Alt', 'CapsLock', 'Control', 'Meta', 'NumLock', 'ScrollLock', 'Shift']);

export class BehavioralCollector {
mousePositions: MousePosition[];
mouseVelocities: VelocitySample[];
Expand All @@ -83,8 +88,12 @@ export class BehavioralCollector {
lastMouseTime: number | null;
lastVelocity: number | null;
eventDeltas: number[];
private readonly pendingKeyHolds?: Map<string, number>;
private keyHoldSamples = 0;
private keyHoldTotalMs = 0;

constructor() {
constructor(options: { collectKeyHolds?: boolean } = {}) {
if (options.collectKeyHolds) this.pendingKeyHolds = new Map();
this.mousePositions = [];
this.mouseVelocities = [];
this.mouseAccelerations = [];
Expand Down Expand Up @@ -166,11 +175,42 @@ export class BehavioralCollector {
}

recordKeyEvent(e: KeyboardEvent): void {
const now = performance.now();
this.keyEvents.push({
type: e.type,
keyLength: e.key ? e.key.length : 0, // Don't store actual keys
t: performance.now()
t: now
});
this.recordKeyHold(e, now);
}

private recordKeyHold(e: KeyboardEvent, now: number): void {
const pending = this.pendingKeyHolds;
const code = e.code;
if (!pending || this.keyHoldSamples >= MAX_KEY_HOLD_SAMPLES || !code || code === 'Unidentified') {
return;
}

const target = e.composedPath?.()[0] ?? e.target;
const excluded = e.isComposing || KEY_HOLD_MODIFIERS.has(e.key)
|| (target instanceof Element && target.matches('textarea, input[type="password"]'));

if (e.type === 'keydown' && !e.repeat) {
// Use the physical code to pair events. Only the count and average leave the browser.
pending.delete(code);
if (!excluded && pending.size < MAX_PENDING_KEY_HOLDS) pending.set(code, now);
} else if (e.type === 'keyup') {
const started = pending.get(code);
pending.delete(code);
if (started === undefined || excluded) return;

const duration = now - started;
if (duration > 0 && duration < MAX_KEY_HOLD_MS) {
this.keyHoldSamples++;
this.keyHoldTotalMs += duration;
if (this.keyHoldSamples === MAX_KEY_HOLD_SAMPLES) pending.clear();
}
}
}

recordTouch(e: TouchEvent): void {
Expand Down Expand Up @@ -223,8 +263,11 @@ export class BehavioralCollector {
const velocities = this.mouseVelocities;
const accelerations = this.mouseAccelerations;

const keyHolds = this.keyHoldSamples > 0
? { keyHoldSamples: this.keyHoldSamples, keyHoldAvg: this.keyHoldTotalMs / this.keyHoldSamples }
: {};
if (positions.length < 10) {
return this._getEmptyAnalysis();
return { ...this._getEmptyAnalysis(), ...keyHolds };
}

// Velocity statistics
Expand Down Expand Up @@ -309,7 +352,8 @@ export class BehavioralCollector {
clickData: this.clickData,
interactionDuration: Date.now() - this.startTime,
...touchAnalysis,
...pointerAnalysis
...pointerAnalysis,
...keyHolds
};
}

Expand Down
88 changes: 88 additions & 0 deletions packages/client/src/collectors/keyboard-holds.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { BehavioralCollector } from './behavioral';

describe('CAPTCHA key-hold summaries', () => {
let clock: jest.SpyInstance<number, []>;
let collector: BehavioralCollector;

beforeEach(() => {
clock = jest.spyOn(performance, 'now');
collector = new BehavioralCollector({ collectKeyHolds: true });
});

afterEach(() => clock.mockRestore());

function record(
target: Element,
type: 'keydown' | 'keyup',
at: number,
init: KeyboardEventInit = { key: 'q', code: 'KeyQ' },
): void {
clock.mockReturnValue(at);
target.addEventListener(
type,
event => collector.recordKeyEvent(event as KeyboardEvent),
{ once: true },
);
target.dispatchEvent(new KeyboardEvent(type, init));
}

it('pairs overlapping keys and reports only the count and average', () => {
const input = document.createElement('input');
const otherKey = { key: 'r', code: 'KeyR' };
record(input, 'keydown', 100);
record(input, 'keydown', 110, otherKey);
record(input, 'keydown', 130, { key: 'q', code: 'KeyQ', repeat: true });
record(input, 'keyup', 160);
record(input, 'keyup', 190, otherKey);

const summary = collector.analyze();
expect(summary).toMatchObject({ keyEvents: 5, keyHoldSamples: 2, keyHoldAvg: 70 });
expect(JSON.stringify(summary)).not.toMatch(/KeyQ|KeyR/);

for (let i = 0; i < 10; i++) {
collector.recordMouseMove(new MouseEvent('mousemove', { clientX: i }));
}
expect(collector.analyze()).toMatchObject({ totalPoints: 10, keyHoldSamples: 2, keyHoldAvg: 70 });
});

it('omits textareas, passwords, modifiers and composition events', () => {
const textarea = document.createElement('textarea');
const password = document.createElement('input');
password.type = 'password';
const button = document.createElement('button');
const modifier = { key: 'Shift', code: 'ShiftLeft' };
const composing = { key: 'q', code: 'KeyQ', isComposing: true };

record(textarea, 'keydown', 100);
record(textarea, 'keyup', 150);
record(password, 'keydown', 200);
record(password, 'keyup', 250);
record(button, 'keydown', 300, modifier);
record(button, 'keyup', 350, modifier);
record(button, 'keydown', 400, composing);
record(button, 'keyup', 450);
record(button, 'keydown', 500);
record(textarea, 'keyup', 550);

expect(collector.analyze()).toMatchObject({ keyEvents: 10 });
expect(collector.analyze()).not.toHaveProperty('keyHoldSamples');
});

it('caps the number of holds in the summary', () => {
const button = document.createElement('button');
for (let i = 0; i < 205; i++) {
record(button, 'keydown', i * 100);
record(button, 'keyup', i * 100 + 65);
}
expect(collector.analyze()).toMatchObject({ keyHoldSamples: 200, keyHoldAvg: 65 });
});

it('keeps the original analysis shape for callers without key holds enabled', () => {
collector = new BehavioralCollector();
const button = document.createElement('button');
record(button, 'keydown', 100);
record(button, 'keyup', 170);
expect(collector.analyze()).toMatchObject({ keyEvents: 2 });
expect(collector.analyze()).not.toHaveProperty('keyHoldSamples');
});
});
2 changes: 1 addition & 1 deletion packages/client/src/invisible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class InvisibleSession {
) as Required<InvisibleOptions>;

this.id = 'webdecoy_inv_' + Math.random().toString(36).slice(2, 11);
this.behavioral = new BehavioralCollector();
this.behavioral = new BehavioralCollector({ collectKeyHolds: true });
this.environmental = new EnvironmentalCollector();
this.temporal = new TemporalCollector();
this.sensor = new SensorCollector();
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class CaptchaWidget {
);

this.id = 'webdecoy_' + Math.random().toString(36).slice(2, 11);
this.behavioral = new BehavioralCollector();
this.behavioral = new BehavioralCollector({ collectKeyHolds: true });
this.environmental = new EnvironmentalCollector();
this.temporal = new TemporalCollector();
this.sensor = new SensorCollector();
Expand Down Expand Up @@ -360,7 +360,7 @@ export class CaptchaWidget {
reset(): void {
this.verified = false;
this.token = null;
this.behavioral = new BehavioralCollector();
this.behavioral = new BehavioralCollector({ collectKeyHolds: true });
this.temporal = new TemporalCollector();
if (this.sensor) this.sensor.detach();
this.sensor = new SensorCollector();
Expand Down
12 changes: 9 additions & 3 deletions packages/webdecoy/src/detection/detectors/keyboard-input.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
import type { Signals } from '../types';

const MIN_KEY_HOLD_SAMPLES = 3;
const MAX_KEY_HOLD_SAMPLES = 200;
const SHORT_KEY_HOLD_MS = 20;
const MAX_KEY_HOLD_MS = 2_000;

type KeyboardModality = 'keyboard-only' | 'short-key-holds';

/** Classify pointerless keyboard input using any dwell times already collected in textareas. */
/** Classify pointerless keyboard input using the browser summary and textarea dwell times. */
export function classifyKeyboardInput(signals: Signals): KeyboardModality | null {
const behavioral = signals.behavioral ?? {};
const keyEvents = behavioral.keyEvents ?? 0;
if (!Number.isFinite(keyEvents) || keyEvents < 2 || (behavioral.totalPoints ?? 0) !== 0) {
return null;
}

let count = 0;
let duration = 0;
const { keyHoldSamples = 0, keyHoldAvg = 0 } = behavioral;
const validSummary = Number.isInteger(keyHoldSamples)
&& keyHoldSamples > 0
&& keyHoldSamples <= Math.min(MAX_KEY_HOLD_SAMPLES, Math.floor(keyEvents / 2))
&& Number.isFinite(keyHoldAvg) && keyHoldAvg > 0 && keyHoldAvg < MAX_KEY_HOLD_MS;
let count = validSummary ? keyHoldSamples : 0;
let duration = count > 0 ? count * keyHoldAvg : 0;
for (const field of Object.values(signals.formAnalysis?.textareaKeyboard ?? {})) {
if (!Array.isArray(field?.dwellTimes)) continue;
for (const dwell of field.dwellTimes) {
Expand Down
30 changes: 30 additions & 0 deletions packages/webdecoy/src/detection/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,36 @@ describe('keyboard-only textarea timing', () => {
});
});

describe('CAPTCHA key-hold summaries', () => {
const keyboard = { keyEvents: 12, totalPoints: 0, interactionDuration: 1500 };

it('uses valid summaries from outside textareas', () => {
const verdict = score({
behavioral: { ...keyboard, keyHoldSamples: 4, keyHoldAvg: 8 },
});
expect(hasReasonIncluding(verdict, 'unusually short key holds')).toBe(true);
});

it('combines the timing sources by sample count', () => {
const verdict = score({
behavioral: { ...keyboard, keyHoldSamples: 4, keyHoldAvg: 80 },
formAnalysis: { textareaKeyboard: { message: { dwellTimes: [5, 8, 7] } } },
});
expect(hasCategory(verdict, 'behavioral')).toBe(false);
expect(hasCategory(verdict, 'vision_ai')).toBe(false);
});

it.each([
{ keyHoldSamples: 7, keyHoldAvg: 8 },
{ keyHoldSamples: 4, keyHoldAvg: 0 },
{ keyHoldSamples: 3.5, keyHoldAvg: 8 },
])('ignores an invalid summary %j', summary => {
const verdict = score({ behavioral: { ...keyboard, ...summary } });
expect(hasCategory(verdict, 'behavioral')).toBe(false);
expect(hasCategory(verdict, 'vision_ai')).toBe(false);
});
});

describe('mobile touch authenticity', () => {
it('flags synthetic force=1 touches on mobile UA', () => {
const v = score(
Expand Down
4 changes: 4 additions & 0 deletions packages/webdecoy/src/detection/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export interface BehavioralSignals {
touchEvents?: number;
pointerHasNonMouseType?: boolean;
keyEvents?: number;
/** Number of completed key holds in the browser's timing summary. */
keyHoldSamples?: number;
/** Average hold duration in milliseconds for those samples. */
keyHoldAvg?: number;
/** Count of recent scroll events and largest CSS pixel step between them. */
scrollMorphology?: { samples?: number; maxStep?: number };
microTremorScore?: number;
Expand Down
Loading