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
50 changes: 50 additions & 0 deletions packages/client/src/collectors/form.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { getFormAnalyzer } from './form';

function attachTextarea(id: string): HTMLTextAreaElement {
const textarea = document.createElement('textarea');
textarea.id = id;
document.body.append(textarea);
return textarea;
}

function paste(target: HTMLElement): void {
target.dispatchEvent(new Event('paste', { bubbles: true }));
}

afterEach(() => {
document.body.replaceChildren();
getFormAnalyzer().textareaStats.clear();
});

it('records a first paste in a textarea before any key events', () => {
const analyzer = getFormAnalyzer();
const textarea = attachTextarea('message');
paste(textarea);
textarea.value = 'Sample text pasted into the form';

expect(analyzer.analyze().textareaKeyboard).toEqual({
message: expect.objectContaining({
keyCount: 0,
pasteCount: 1,
contentLength: textarea.value.length,
noKeyboardEvents: true,
}),
});
});

it('shares textarea stats across typing and repeated paste events', () => {
const analyzer = getFormAnalyzer();
const textarea = attachTextarea('notes');
textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'a', bubbles: true }));
paste(textarea);
paste(textarea);

const input = document.createElement('input');
input.name = 'unrelated';
document.body.append(input);
paste(input);

expect(analyzer.analyze().textareaKeyboard).toEqual({
notes: expect.objectContaining({ keyCount: 1, pasteCount: 2 }),
});
});
56 changes: 28 additions & 28 deletions packages/client/src/collectors/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,10 @@ export class FormAnalyzer {
document.addEventListener(eventType, (e: Event) => this._recordInteraction(e), { passive: true });
});

// Track textarea keyboard patterns (spam detection)
// Track textarea key and paste events.
document.addEventListener('keydown', (e: KeyboardEvent) => this._recordTextareaKey(e), { passive: true });
document.addEventListener('keyup', (e: KeyboardEvent) => this._recordTextareaKey(e), { passive: true });
document.addEventListener('paste', (e: ClipboardEvent) => this.recordPaste(e), { passive: true });

// Track form submissions
document.addEventListener('submit', (e: SubmitEvent) => this._recordSubmit(e), { capture: true });
Expand Down Expand Up @@ -94,23 +95,7 @@ export class FormAnalyzer {
const target = e.target as (HTMLTextAreaElement & Element) | null;
if (target?.tagName !== 'TEXTAREA') return;

const textareaId = target.id || target.name || 'unnamed';
if (!this.textareaStats.has(textareaId)) {
this.textareaStats.set(textareaId, {
keydowns: [],
keyups: [],
intervals: [],
lastKeyTime: null,
inputWithoutKey: 0,
pasteCount: 0,
dwellTimes: [],
rollovers: 0,
activeKeyCount: 0,
pendingKeydowns: []
});
}

const stats = this.textareaStats.get(textareaId) as TextareaStats;
const stats = this.getTextareaStats(target);
const now = performance.now();

// Modifier keys excluded from dwell/rollover tracking
Expand Down Expand Up @@ -246,15 +231,15 @@ export class FormAnalyzer {
};
});

// Check for textareas with content but no keyboard events (DOM manipulation)
// Report textarea content length alongside observed input events.
const textareas = document.querySelectorAll('textarea');
textareas.forEach((ta: HTMLTextAreaElement) => {
const id = ta.id || ta.name || 'unnamed';
const contentLength = (ta.value || '').length;

if (contentLength > 0) {
if (!textareaAnalysis[id]) {
// Textarea has content but we never saw any keyboard events - DOM manipulation!
// This field has content and no recorded input events.
textareaAnalysis[id] = {
keyCount: 0,
avgKeyInterval: 0,
Expand Down Expand Up @@ -290,15 +275,32 @@ export class FormAnalyzer {
};
}

// Track paste events on textareas
private getTextareaStats(target: HTMLTextAreaElement): TextareaStats {
const id = target.id || target.name || 'unnamed';
const existing = this.textareaStats.get(id);
if (existing) return existing;

const stats: TextareaStats = {
keydowns: [],
keyups: [],
intervals: [],
lastKeyTime: null,
inputWithoutKey: 0,
pasteCount: 0,
dwellTimes: [],
rollovers: 0,
activeKeyCount: 0,
pendingKeydowns: []
};
this.textareaStats.set(id, stats);
return stats;
}

recordPaste(e: ClipboardEvent): void {
const target = e.target as (HTMLTextAreaElement & Element) | null;
const target = e.target as HTMLTextAreaElement | null;
if (target?.tagName !== 'TEXTAREA') return;

const textareaId = target.id || target.name || 'unnamed';
if (this.textareaStats.has(textareaId)) {
(this.textareaStats.get(textareaId) as TextareaStats).pasteCount++;
}
this.getTextareaStats(target).pasteCount++;
}
}

Expand All @@ -307,8 +309,6 @@ let globalFormAnalyzer: FormAnalyzer | null = null;
export function getFormAnalyzer(): FormAnalyzer {
if (!globalFormAnalyzer) {
globalFormAnalyzer = new FormAnalyzer();
// Also track paste events
document.addEventListener('paste', (e: ClipboardEvent) => (globalFormAnalyzer as FormAnalyzer).recordPaste(e), { passive: true });
}
return globalFormAnalyzer;
}
Expand Down
12 changes: 8 additions & 4 deletions packages/webdecoy/src/detection/detectors/form.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
/** Form-interaction analysis: credential stuffing & spam patterns. */

import type { Detection, FormAnalysisSignals } from '../types';
import type { BehavioralSignals, Detection, FormAnalysisSignals } from '../types';
import { analyzeKeystrokeCadence } from './keystroke';

export function analyzeFormInteraction(formAnalysis?: FormAnalysisSignals): Detection[] {
export function analyzeFormInteraction(
formAnalysis?: FormAnalysisSignals,
behavioral?: BehavioralSignals,
): Detection[] {
if (!formAnalysis) return [];

const detections: Detection[] = [];
Expand Down Expand Up @@ -66,14 +69,15 @@ export function analyzeFormInteraction(formAnalysis?: FormAnalysisSignals): Dete

const textareaData = formAnalysis.textareaKeyboard;
if (textareaData) {
const hasPointerOrTouch = (behavioral?.totalPoints ?? 0) >= 5 || (behavioral?.touchEvents ?? 0) > 0;
for (const [fieldId, stats] of Object.entries(textareaData)) {
const keyCount = stats.keyCount ?? 0;
const pasteCount = stats.pasteCount ?? 0;
const avgKeyInterval = stats.avgKeyInterval ?? 0;
const keyIntervalVariance = stats.keyIntervalVariance ?? 0;
const keydownUpRatio = stats.keydownUpRatio ?? 1;

if (pasteCount > 0 && keyCount < 5) {
if (pasteCount > 0 && keyCount < 5 && !hasPointerOrTouch) {
detections.push({
category: 'bot',
score: 0.6,
Expand Down Expand Up @@ -109,7 +113,7 @@ export function analyzeFormInteraction(formAnalysis?: FormAnalysisSignals): Dete
});
}

if (stats.noKeyboardEvents && (stats.contentLength ?? 0) > 0) {
if (stats.noKeyboardEvents && keyCount === 0 && pasteCount === 0 && (stats.contentLength ?? 0) > 0) {
detections.push({
category: 'bot',
score: 0.75,
Expand Down
36 changes: 36 additions & 0 deletions packages/webdecoy/src/detection/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,42 @@ describe('form interaction', () => {
expect(hasReasonIncluding(v, 'no user interaction events')).toBe(true);
});

it.each([
{ name: 'mouse movement', behavioral: HUMAN_BEHAVIOR },
{ name: 'touch input', behavioral: { touchEvents: 1 } },
])('keeps a recorded textarea paste neutral with $name', ({ behavioral }) => {
const verdict = score({
behavioral,
formAnalysis: { textareaKeyboard: {
message: { keyCount: 0, pasteCount: 1, contentLength: 40, noKeyboardEvents: true },
} },
});

expect(hasReasonIncluding(verdict, 'DOM manipulation')).toBe(false);
expect(hasReasonIncluding(verdict, 'filled mostly by paste')).toBe(false);
});

it('keeps the paste-heavy finding for sessions with no pointer or touch evidence', () => {
const verdict = score({
formAnalysis: { textareaKeyboard: {
message: { keyCount: 0, pasteCount: 3, contentLength: 40, noKeyboardEvents: true },
} },
});

expect(hasReasonIncluding(verdict, 'filled mostly by paste')).toBe(true);
expect(hasReasonIncluding(verdict, 'DOM manipulation')).toBe(false);
});

it('continues to report textarea content with no recorded typing or paste', () => {
const verdict = score({
formAnalysis: { textareaKeyboard: {
message: { keyCount: 0, contentLength: 40, noKeyboardEvents: true },
} },
});

expect(hasReasonIncluding(verdict, 'DOM manipulation')).toBe(true);
});

it('detects impossibly fast textarea typing', () => {
const v = score({
formAnalysis: {
Expand Down
2 changes: 1 addition & 1 deletion packages/webdecoy/src/detection/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export class DetectionEngine {

// --- Form interaction + advanced fingerprints -----------------------------
if (signals.formAnalysis) {
detections.push(...analyzeFormInteraction(signals.formAnalysis));
detections.push(...analyzeFormInteraction(signals.formAnalysis, signals.behavioral));
}
detections.push(...analyzeAdvancedSignals(signals));

Expand Down
Loading