diff --git a/packages/webdecoy/src/captcha/captcha.test.ts b/packages/webdecoy/src/captcha/captcha.test.ts index 608a1ad..b23230b 100644 --- a/packages/webdecoy/src/captcha/captcha.test.ts +++ b/packages/webdecoy/src/captcha/captcha.test.ts @@ -268,9 +268,7 @@ describe('Captcha end-to-end', () => { expect(result.detections.some((d) => d.reason.includes('No PoW solution'))).toBe(true); }); - it('does not block on "no PoW" alone — pushes to challenge, not block', async () => { - // A single maxed category cannot cross the 0.5 success threshold; missing - // PoW on an otherwise-clean request yields a "challenge" recommendation. + it('requires verified proof of work before issuing a token', async () => { const captcha = new Captcha({ secret: SECRET }); const result = await captcha.verify({ siteKey: 'site', @@ -279,7 +277,9 @@ describe('Captcha end-to-end', () => { headers: { 'user-agent': 'curl/8.0' }, signals: {}, }); - expect(result.recommendation).not.toBe('allow'); + expect(result.success).toBe(false); + expect(result.token).toBeNull(); + expect(result.recommendation).toBe('challenge'); expect(result.detections.some((d) => d.reason.includes('No PoW solution'))).toBe(true); }); diff --git a/packages/webdecoy/src/captcha/http.test.ts b/packages/webdecoy/src/captcha/http.test.ts index 83c6acf..d40599c 100644 --- a/packages/webdecoy/src/captcha/http.test.ts +++ b/packages/webdecoy/src/captcha/http.test.ts @@ -106,18 +106,47 @@ describe('captcha HTTP endpoints', () => { expect((tRes!.body as { valid: boolean }).valid).toBe(true); }); - it('scores in invisible mode on POST /__webdecoy/score', async () => { - const { handle } = createCaptchaEndpoints({ secret: 's' }); - const res = await handle( - req({ - method: 'POST', - pathname: '/__webdecoy/score', - headers: HEADERS, - body: { siteKey: 'site', action: 'login', signals: { behavioral: HUMAN, environmental: ENV } }, - }), - ); - expect(res?.status).toBe(200); - expect((res!.body as { action: string }).action).toBe('login'); + it.each(['verify', 'score'])('applies route-specific interaction checks on /%s', async (route) => { + const { captcha, handle } = createCaptchaEndpoints({ secret: 's' }); + const ip = '73.15.22.100'; + const now = Date.now(); + const clock = jest.spyOn(Date, 'now').mockReturnValue(now); + try { + const challenge = await captcha.issueChallenge('site', ip, 2); + clock.mockReturnValue(now + 90_000); + const res = await handle( + req({ + method: 'POST', + pathname: '/__webdecoy/' + route, + ip, + headers: HEADERS, + body: { + siteKey: 'site', + action: 'login', + powSolution: solve(challenge), + signals: { + behavioral: { ...HUMAN, interactionDuration: 90_000 }, + environmental: ENV, + meta: { challengeNonce: challenge.nonce, invisible: true }, + }, + }, + }), + ); + + expect(res?.status).toBe(200); + expect(res?.body).toMatchObject({ success: true, token: expect.any(String) }); + if (route === 'verify') { + expect(res?.body).toMatchObject({ + detections: expect.arrayContaining([ + expect.objectContaining({ reason: 'Unusually long interaction time' }), + ]), + }); + } else { + expect(res?.body).toMatchObject({ action: 'login', score: 0 }); + } + } finally { + clock.mockRestore(); + } }); it('400s a token verify with no token', async () => { diff --git a/packages/webdecoy/src/captcha/service.ts b/packages/webdecoy/src/captcha/service.ts index 8573b99..cce3504 100644 --- a/packages/webdecoy/src/captcha/service.ts +++ b/packages/webdecoy/src/captcha/service.ts @@ -84,6 +84,10 @@ export class Captcha { * signals, and issues a session token on success. Mirrors `runVerification`. */ async verify(input: VerifyInput): Promise { + return this.verifySubmission(input, true); + } + + private async verifySubmission(input: VerifyInput, widgetInteraction: boolean): Promise { const { siteKey, ip, userAgent } = input; const headers = input.headers ?? {}; let signals: Signals = input.signals ?? {}; @@ -136,19 +140,25 @@ export class Captcha { headers, ja3Hash: input.ja3Hash ?? null, trustedJA4Headers: this.trustedJA4Headers, + widgetInteraction, pow, extraDetections, }); - // 5. Issue a token on success. - const token = verdict.success ? await this.tokens.issue(ip, siteKey, verdict.score) : null; + // 5. Token issuance requires both a verified proof and a passing score. + const proofVerified = pow.valid === true; + const success = proofVerified && verdict.success; + const token = success ? await this.tokens.issue(ip, siteKey, verdict.score) : null; + const recommendation = !proofVerified && verdict.recommendation === 'allow' + ? 'challenge' + : verdict.recommendation; - return { ...verdict, token }; + return { ...verdict, success, recommendation, token }; } /** Invisible-mode scoring — same pipeline, returns a compact result + action. */ async score(input: VerifyInput & { action?: string }): Promise { - const result = await this.verify(input); + const result = await this.verifySubmission(input, false); return { success: result.success, score: result.score, diff --git a/packages/webdecoy/src/captcha/types.ts b/packages/webdecoy/src/captcha/types.ts index 3599589..baa66dd 100644 --- a/packages/webdecoy/src/captcha/types.ts +++ b/packages/webdecoy/src/captcha/types.ts @@ -78,12 +78,15 @@ export interface VerifyInput { /** A verdict plus an issued token (present only on success). */ export interface VerifyResult extends Verdict { + /** True when the proof verified and the score passed. */ + success: boolean; /** base64url session token, or null when the request did not pass. */ token: string | null; } /** Invisible-mode (`score`) result. */ export interface ScoreResult { + /** True when the proof verified and the score passed. */ success: boolean; score: number; token: string | null; diff --git a/packages/webdecoy/src/detection/detectors/behavioral.ts b/packages/webdecoy/src/detection/detectors/behavioral.ts index 9d12ff1..63afea4 100644 --- a/packages/webdecoy/src/detection/detectors/behavioral.ts +++ b/packages/webdecoy/src/detection/detectors/behavioral.ts @@ -2,7 +2,7 @@ import type { Detection, Signals } from '../types'; -export function detectBehavioral(signals: Signals): Detection[] { +export function detectBehavioral(signals: Signals, widgetInteraction = true): Detection[] { const detections: Detection[] = []; const b = signals.behavioral ?? {}; const t = signals.temporal ?? {}; @@ -42,7 +42,7 @@ export function detectBehavioral(signals: Signals): Detection[] { } const overshoots = b.overshootCorrections ?? 0; - if (overshoots === 0 && trajectory > 200) { + if (widgetInteraction && overshoots === 0 && trajectory > 200) { detections.push({ category: 'behavioral', score: 0.4, @@ -59,7 +59,7 @@ export function detectBehavioral(signals: Signals): Detection[] { confidence: 0.7, reason: 'Interaction completed too quickly', }); - } else if (interactionTime > 60000) { + } else if (widgetInteraction && interactionTime > 60000) { detections.push({ category: 'captcha_farm', score: 0.3, diff --git a/packages/webdecoy/src/detection/detectors/vision-ai.ts b/packages/webdecoy/src/detection/detectors/vision-ai.ts index adb0a8f..e6d8962 100644 --- a/packages/webdecoy/src/detection/detectors/vision-ai.ts +++ b/packages/webdecoy/src/detection/detectors/vision-ai.ts @@ -2,7 +2,7 @@ import type { Detection, Signals } from '../types'; -export function detectVisionAI(signals: Signals): Detection[] { +export function detectVisionAI(signals: Signals, widgetInteraction = true): Detection[] { const detections: Detection[] = []; const b = signals.behavioral ?? {}; const t = signals.temporal ?? {}; @@ -25,7 +25,7 @@ export function detectVisionAI(signals: Signals): Detection[] { }); } - if (approachPts === 0 && !isTouchUser && !isKeyboardUser) { + if (widgetInteraction && approachPts === 0 && !isTouchUser && !isKeyboardUser) { detections.push({ category: 'vision_ai', score: 0.7, @@ -66,7 +66,7 @@ export function detectVisionAI(signals: Signals): Detection[] { }); } - if ((b.approachDirectness ?? 0) > 0.95) { + if (widgetInteraction && (b.approachDirectness ?? 0) > 0.95) { detections.push({ category: 'vision_ai', score: 0.5, @@ -76,7 +76,7 @@ export function detectVisionAI(signals: Signals): Detection[] { } const precision = b.clickPrecision ?? 10; - if (precision > 0 && precision < 2) { + if (widgetInteraction && precision > 0 && precision < 2) { detections.push({ category: 'vision_ai', score: 0.4, @@ -86,7 +86,7 @@ export function detectVisionAI(signals: Signals): Detection[] { } const exploration = b.explorationRatio ?? 0.3; - if (exploration < 0.05 && trajectory > 50) { + if (widgetInteraction && exploration < 0.05 && trajectory > 50) { detections.push({ category: 'vision_ai', score: 0.4, diff --git a/packages/webdecoy/src/detection/engine.test.ts b/packages/webdecoy/src/detection/engine.test.ts index 7503f11..4dad904 100644 --- a/packages/webdecoy/src/detection/engine.test.ts +++ b/packages/webdecoy/src/detection/engine.test.ts @@ -22,6 +22,7 @@ interface ScoreOpts { ip?: string; headers?: Record; ja3Hash?: string; + widgetInteraction?: boolean; } function score(signals: Signals, opts: ScoreOpts = {}): Verdict { @@ -33,6 +34,7 @@ function score(signals: Signals, opts: ScoreOpts = {}): Verdict { userAgent: ua, headers: { 'user-agent': ua, ...(opts.headers ?? {}) }, ja3Hash: opts.ja3Hash, + widgetInteraction: opts.widgetInteraction, }; return engine.score(signals, context); } @@ -188,6 +190,40 @@ describe('behavioral signals', () => { }); }); +describe('widget and invisible interaction modes', () => { + it('uses widget-only checks only for widget interaction and keeps shared checks', () => { + const signals: Signals = { + behavioral: { + ...HUMAN_BEHAVIOR, + approachPoints: 0, + approachDirectness: 0.98, + clickPrecision: 1, + explorationRatio: 0.01, + overshootCorrections: 0, + interactionDuration: 90_000, + velocityVariance: 0.01, + }, + }; + const widgetOnly = [ + 'No approach trajectory to target', + 'Mouse path to target is unnaturally direct', + 'Click precision is unnaturally accurate', + 'No exploratory mouse movement before click', + 'No overshoot corrections on long trajectory', + 'Unusually long interaction time', + ]; + const widget = score(signals); + const invisible = score(signals, { widgetInteraction: false }); + + for (const reason of widgetOnly) { + expect(hasReasonIncluding(widget, reason)).toBe(true); + expect(hasReasonIncluding(invisible, reason)).toBe(false); + } + expect(hasReasonIncluding(widget, 'Mouse velocity too consistent')).toBe(true); + expect(hasReasonIncluding(invisible, 'Mouse velocity too consistent')).toBe(true); + }); +}); + describe('vision AI detection', () => { it('detects impossibly fast PoW', () => { const v = score({ temporal: { pow: { duration: 10, iterations: 100000 } } }); diff --git a/packages/webdecoy/src/detection/engine.ts b/packages/webdecoy/src/detection/engine.ts index 2357a5b..331f292 100644 --- a/packages/webdecoy/src/detection/engine.ts +++ b/packages/webdecoy/src/detection/engine.ts @@ -116,12 +116,13 @@ export class DetectionEngine { } // --- Behavioral / environmental detectors --------------------------------- + const widgetInteraction = context.widgetInteraction !== false; detections.push( - ...detectVisionAI(signals), + ...detectVisionAI(signals, widgetInteraction), ...detectHeadless(signals, userAgent), ...detectAutomation(signals), ...detectCDP(signals), - ...detectBehavioral(signals), + ...detectBehavioral(signals, widgetInteraction), ...detectTouchAuthenticity(signals, userAgent), ...detectSensorEntropy(signals, userAgent), ...detectTouchKinematics(signals), diff --git a/packages/webdecoy/src/detection/types.ts b/packages/webdecoy/src/detection/types.ts index 44e81b0..8724b3c 100644 --- a/packages/webdecoy/src/detection/types.ts +++ b/packages/webdecoy/src/detection/types.ts @@ -280,6 +280,8 @@ export interface DetectionContext { * change the score. */ trustedJA4Headers?: string[]; + /** Whether the server requested a widget click. Defaults to true. */ + widgetInteraction?: boolean; /** Proof-of-work verification outcome (supplied by the PoW subsystem). */ pow?: PoWOutcome; /**