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
8 changes: 4 additions & 4 deletions packages/webdecoy/src/captcha/captcha.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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);
});

Expand Down
53 changes: 41 additions & 12 deletions packages/webdecoy/src/captcha/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
18 changes: 14 additions & 4 deletions packages/webdecoy/src/captcha/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ export class Captcha {
* signals, and issues a session token on success. Mirrors `runVerification`.
*/
async verify(input: VerifyInput): Promise<VerifyResult> {
return this.verifySubmission(input, true);
}

private async verifySubmission(input: VerifyInput, widgetInteraction: boolean): Promise<VerifyResult> {
const { siteKey, ip, userAgent } = input;
const headers = input.headers ?? {};
let signals: Signals = input.signals ?? {};
Expand Down Expand Up @@ -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<ScoreResult> {
const result = await this.verify(input);
const result = await this.verifySubmission(input, false);
return {
success: result.success,
score: result.score,
Expand Down
3 changes: 3 additions & 0 deletions packages/webdecoy/src/captcha/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions packages/webdecoy/src/detection/detectors/behavioral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? {};
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
10 changes: 5 additions & 5 deletions packages/webdecoy/src/detection/detectors/vision-ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? {};
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
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 @@ -22,6 +22,7 @@ interface ScoreOpts {
ip?: string;
headers?: Record<string, string>;
ja3Hash?: string;
widgetInteraction?: boolean;
}

function score(signals: Signals, opts: ScoreOpts = {}): Verdict {
Expand All @@ -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);
}
Expand Down Expand Up @@ -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 } } });
Expand Down
5 changes: 3 additions & 2 deletions packages/webdecoy/src/detection/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
2 changes: 2 additions & 0 deletions packages/webdecoy/src/detection/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
/**
Expand Down
Loading