From a1df5e1566bd5454739df38b4e87b2866ed0b25e Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Sun, 22 Nov 2026 20:59:52 -0600 Subject: [PATCH] Record first textarea paste in CAPTCHA scoring --- packages/client/src/collectors/form.test.ts | 50 +++++++++++++++++ packages/client/src/collectors/form.ts | 56 +++++++++---------- .../webdecoy/src/detection/detectors/form.ts | 12 ++-- .../webdecoy/src/detection/engine.test.ts | 36 ++++++++++++ packages/webdecoy/src/detection/engine.ts | 2 +- 5 files changed, 123 insertions(+), 33 deletions(-) create mode 100644 packages/client/src/collectors/form.test.ts diff --git a/packages/client/src/collectors/form.test.ts b/packages/client/src/collectors/form.test.ts new file mode 100644 index 0000000..f7bc8ef --- /dev/null +++ b/packages/client/src/collectors/form.test.ts @@ -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 }), + }); +}); diff --git a/packages/client/src/collectors/form.ts b/packages/client/src/collectors/form.ts index ca3b9d8..9ba044a 100644 --- a/packages/client/src/collectors/form.ts +++ b/packages/client/src/collectors/form.ts @@ -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 }); @@ -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 @@ -246,7 +231,7 @@ 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'; @@ -254,7 +239,7 @@ export class FormAnalyzer { 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, @@ -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++; } } @@ -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; } diff --git a/packages/webdecoy/src/detection/detectors/form.ts b/packages/webdecoy/src/detection/detectors/form.ts index cacc8c0..64bdd21 100644 --- a/packages/webdecoy/src/detection/detectors/form.ts +++ b/packages/webdecoy/src/detection/detectors/form.ts @@ -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[] = []; @@ -66,6 +69,7 @@ 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; @@ -73,7 +77,7 @@ export function analyzeFormInteraction(formAnalysis?: FormAnalysisSignals): Dete 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, @@ -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, diff --git a/packages/webdecoy/src/detection/engine.test.ts b/packages/webdecoy/src/detection/engine.test.ts index c1ae066..a102df3 100644 --- a/packages/webdecoy/src/detection/engine.test.ts +++ b/packages/webdecoy/src/detection/engine.test.ts @@ -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: { diff --git a/packages/webdecoy/src/detection/engine.ts b/packages/webdecoy/src/detection/engine.ts index 7438283..ac9d192 100644 --- a/packages/webdecoy/src/detection/engine.ts +++ b/packages/webdecoy/src/detection/engine.ts @@ -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));