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
2 changes: 1 addition & 1 deletion packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ Mount the endpoints with your adapter (`webdecoyCaptcha` in Express, `webdecoyCa

When the browser provides usable scroll samples, `/verify` and `/score` return an `observations` entry with the ID `large-scroll-step-v1`. It summarizes the sample count and largest step in CSS pixels for diagnostics.

Pass `onScoringComparison` to the server adapter, `Captcha`, or `DetectionEngine` to receive the current and candidate scores and recommendations on the server. Both scores use your configured category weights. The `noisy-or-decisive-v1` candidate uses noisy-OR aggregation and applies FCaptcha's decisive score floor to explicit WebDriver declarations and known driver injection signals in enabled categories. Verification and token issuance continue to use the current policy.
Pass `onScoringComparison` to the server adapter, `Captcha`, or `DetectionEngine` to receive the current and candidate scores and recommendations on the server. Both scores use your configured category weights. The `noisy-or-floors-v1` candidate uses noisy-OR aggregation and applies a decisive score floor to explicit WebDriver declarations and known driver injection signals in enabled categories. It also applies a corroboration floor when measured interaction and known driver findings agree. Verification and token issuance use the current policy.

```ts
import express from 'express';
Expand Down
2 changes: 1 addition & 1 deletion packages/webdecoy/src/captcha/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ describe('captcha HTTP endpoints', () => {
expect(res?.status).toBe(200);
const decision = res!.body as { score: number; recommendation: string };
expect(onScoringComparison.mock.calls).toEqual([[{
policy: 'noisy-or-decisive-v1',
policy: 'noisy-or-floors-v1',
current: { score: decision.score, recommendation: decision.recommendation },
candidate: { score: expect.any(Number), recommendation: 'allow' },
}]]);
Expand Down
13 changes: 8 additions & 5 deletions packages/webdecoy/src/detection/detectors/behavioral.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
/** Core behavioral detection: mouse data sufficiency, velocity, timing. */

import type { Detection, Signals } from '../types';
import { addCorroboratingDetection } from './corroborating-detection';
import { classifyKeyboardInput } from './keyboard-input';
import { hasHumanMovementMarkers, isTouchModality } from './pointer-evidence';

export function detectBehavioral(signals: Signals, widgetInteraction = true): Detection[] {
export function detectBehavioral(
signals: Signals, widgetInteraction = true, corroborating?: Detection[],
): Detection[] {
const detections: Detection[] = [];
const b = signals.behavioral ?? {};
const t = signals.temporal ?? {};
Expand All @@ -17,7 +20,7 @@ export function detectBehavioral(signals: Signals, widgetInteraction = true): De
const humanMovement = hasHumanMovementMarkers(b);

if (keyboard === 'short-key-holds' && !isTouchUser) {
detections.push({
addCorroboratingDetection(detections, corroborating, {
category: 'behavioral',
score: 0.8,
confidence: 0.9,
Expand All @@ -41,7 +44,7 @@ export function detectBehavioral(signals: Signals, widgetInteraction = true): De

const velVar = b.velocityVariance ?? 1;
if (velVar < 0.02 && trajectory > 50 && !humanMovement) {
detections.push({
addCorroboratingDetection(detections, corroborating, {
category: 'behavioral',
score: 0.6,
confidence: 0.6,
Expand Down Expand Up @@ -105,7 +108,7 @@ export function detectBehavioral(signals: Signals, widgetInteraction = true): De

const straight = b.straightLineRatio ?? 0;
if (straight > 0.8 && trajectory > 100) {
detections.push({
addCorroboratingDetection(detections, corroborating, {
category: 'behavioral',
score: 0.5,
confidence: 0.5,
Expand All @@ -115,7 +118,7 @@ export function detectBehavioral(signals: Signals, widgetInteraction = true): De

const dirChanges = b.directionChanges ?? 10;
if (totalPoints > 50 && dirChanges < 3) {
detections.push({
addCorroboratingDetection(detections, corroborating, {
category: 'behavioral',
score: 0.4,
confidence: 0.4,
Expand Down
16 changes: 15 additions & 1 deletion packages/webdecoy/src/detection/detectors/cdp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,23 @@
import type { Detection, Signals } from '../types';

const HIGH_CONFIDENCE_SIGNALS = ['chromedriver_cdc', 'puppeteer_eval', 'cdp_script_injection'];
// Driver artifacts emitted by the browser collector. Other CDP findings still contribute to the base score.
const CORROBORATING_DRIVER_SIGNALS = new Set([
...HIGH_CONFIDENCE_SIGNALS,
'selenium_evaluate',
'selenium_driver_evaluate',
'selenium_unwrapped',
'selenium_driver_unwrapped',
'selenium_direct',
'firefox_driver',
'firefox_driver_unwrapped',
]);

export function hasDriverInjection(signals: readonly string[]): boolean {
return signals.some((signal) => HIGH_CONFIDENCE_SIGNALS.includes(signal));
}

export function detectCDP(signals: Signals): Detection[] {
export function detectCDP(signals: Signals, corroborating?: Detection[]): Detection[] {
const detections: Detection[] = [];
const cdp = signals.environmental?.cdp ?? {};

Expand Down Expand Up @@ -40,5 +51,8 @@ export function detectCDP(signals: Signals): Detection[] {
});
}

if (corroborating && signalList.every((signal) => CORROBORATING_DRIVER_SIGNALS.has(signal))) {
corroborating.push(...detections);
}
return detections;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Detection } from '../types';

/** Record an ordinary detection and make it available to the optional policy comparison. */
export function addCorroboratingDetection(
detections: Detection[],
corroborating: Detection[] | undefined,
detection: Detection,
): void {
detections.push(detection);
corroborating?.push(detection);
}
11 changes: 7 additions & 4 deletions packages/webdecoy/src/detection/detectors/vision-ai.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
/** Vision-AI agent detection: missing natural mouse behavior + PoW timing. */

import type { Detection, Signals } from '../types';
import { addCorroboratingDetection } from './corroborating-detection';
import { classifyKeyboardInput } from './keyboard-input';
import { hasHumanMovementMarkers, isTouchModality } from './pointer-evidence';

export function detectVisionAI(signals: Signals, widgetInteraction = true): Detection[] {
export function detectVisionAI(
signals: Signals, widgetInteraction = true, corroborating?: Detection[],
): Detection[] {
const detections: Detection[] = [];
const b = signals.behavioral ?? {};
const t = signals.temporal ?? {};
Expand Down Expand Up @@ -59,7 +62,7 @@ export function detectVisionAI(signals: Signals, widgetInteraction = true): Dete

const microTremor = b.microTremorScore ?? 0.5;
if (usesMouse && totalPoints >= 5 && microTremor < 0.15) {
detections.push({
addCorroboratingDetection(detections, corroborating, {
category: 'vision_ai',
score: 0.7,
confidence: 0.6,
Expand All @@ -74,7 +77,7 @@ export function detectVisionAI(signals: Signals, widgetInteraction = true): Dete
(b.approachDirectness ?? 0) > 0.95 &&
!hasHumanMovementMarkers(b)
) {
detections.push({
addCorroboratingDetection(detections, corroborating, {
category: 'vision_ai',
score: 0.5,
confidence: 0.5,
Expand All @@ -84,7 +87,7 @@ export function detectVisionAI(signals: Signals, widgetInteraction = true): Dete

const exploration = b.explorationRatio ?? 0.3;
if (widgetInteraction && exploration < 0.05 && trajectory > 50) {
detections.push({
addCorroboratingDetection(detections, corroborating, {
category: 'vision_ai',
score: 0.4,
confidence: 0.4,
Expand Down
32 changes: 30 additions & 2 deletions packages/webdecoy/src/detection/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ describe('scoring comparison', () => {
observations: [{ id: 'large-scroll-step-v1', mode: 'observe', status: 'detected', samples: 3, maxStep: 680 }],
});
expect(onScoringComparison.mock.calls).toEqual([[{
policy: 'noisy-or-decisive-v1',
policy: 'noisy-or-floors-v1',
current: { score: expect.closeTo(0.295, 10), recommendation: 'allow' },
candidate: { score: expect.closeTo(0.336875, 10), recommendation: 'challenge' },
}]]);
Expand All @@ -302,7 +302,35 @@ describe('scoring comparison', () => {

expect(verdict).toEqual({ ...current, timestamp: verdict.timestamp });
expect(onScoringComparison.mock.calls).toEqual([[{
policy: 'noisy-or-decisive-v1',
policy: 'noisy-or-floors-v1',
current: { score: current.score, recommendation: current.recommendation },
candidate: {
score: expect.closeTo(candidate.score, 10),
recommendation: candidate.recommendation,
},
}]]);
});
});

describe('corroboration floor', () => {
it.each(scoringPolicyFixtures.corroborationFloorCases)('compares independent evidence for $name', ({
signals, weights, candidate,
}) => {
const onScoringComparison = jest.fn();
const options = { weights: weights ?? { vision_ai: 0.15, behavioral: 0.18, cdp: 0.12 } };
const context = {
ip: '203.0.113.9',
siteKey: 'test',
userAgent: UA_CHROME_MAC,
headers: GOOD_HEADERS,
pow: { provided: true, valid: true, serverElapsed: 3000 },
};
const current = new DetectionEngine(options).score(signals, context);
const verdict = new DetectionEngine({ ...options, onScoringComparison }).score(signals, context);

expect(verdict).toEqual({ ...current, timestamp: verdict.timestamp });
expect(onScoringComparison.mock.calls).toEqual([[{
policy: 'noisy-or-floors-v1',
current: { score: current.score, recommendation: current.recommendation },
candidate: {
score: expect.closeTo(candidate.score, 10),
Expand Down
19 changes: 11 additions & 8 deletions packages/webdecoy/src/detection/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
type RateLimiter,
} from './stores';
import {
applyCorroborationScoreFloor,
applyDecisiveScoreFloor,
calculateCategoryScores,
calculateFinalScore,
Expand Down Expand Up @@ -45,7 +46,7 @@ import {
} from './detectors';

export interface ScoringComparison {
policy: 'noisy-or-decisive-v1';
policy: 'noisy-or-floors-v1';
current: { score: number; recommendation: Recommendation };
candidate: { score: number; recommendation: Recommendation };
}
Expand Down Expand Up @@ -87,6 +88,8 @@ export class DetectionEngine {
const { ip, siteKey, userAgent } = context;
const headers = context.headers ?? {};
const detections: Detection[] = [];
const onScoringComparison = this.onScoringComparison;
const corroborating: Detection[] | undefined = onScoringComparison ? [] : undefined;

// Orchestrator-supplied detections (e.g. signals-tampering check).
if (context.extraDetections) detections.push(...context.extraDetections);
Expand Down Expand Up @@ -135,11 +138,11 @@ export class DetectionEngine {
// --- Behavioral / environmental detectors ---------------------------------
const widgetInteraction = context.widgetInteraction !== false;
detections.push(
...detectVisionAI(signals, widgetInteraction),
...detectVisionAI(signals, widgetInteraction, corroborating),
...detectHeadless(signals, userAgent),
...detectAutomation(signals),
...detectCDP(signals),
...detectBehavioral(signals, widgetInteraction),
...detectCDP(signals, corroborating),
...detectBehavioral(signals, widgetInteraction, corroborating),
...detectTouchAuthenticity(signals, userAgent),
...detectSensorEntropy(signals, userAgent),
...detectTouchKinematics(signals),
Expand Down Expand Up @@ -182,15 +185,15 @@ export class DetectionEngine {
const recommendation = recommend(score);
const scrollObservation = observeScrollJump(signals.behavioral);

const onScoringComparison = this.onScoringComparison;
if (onScoringComparison) {
if (onScoringComparison && corroborating) {
const candidateScores = calculateNoisyOrCategoryScores(detections, this.weights);
const candidateScore = applyDecisiveScoreFloor(
const decisiveScore = applyDecisiveScoreFloor(
calculateFinalScore(candidateScores, this.weights), signals.environmental, this.weights,
);
const candidateScore = applyCorroborationScoreFloor(decisiveScore, corroborating, this.weights);
try {
const pending = onScoringComparison({
policy: 'noisy-or-decisive-v1',
policy: 'noisy-or-floors-v1',
current: { score, recommendation },
candidate: { score: candidateScore, recommendation: recommend(candidateScore) },
});
Expand Down
79 changes: 79 additions & 0 deletions packages/webdecoy/src/detection/fixtures/scoring-policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -252,5 +252,84 @@
"weights": { "headless": 1.1, "cdp": 0 },
"candidate": { "score": 0.99275, "recommendation": "block" }
}
],
"corroborationFloorCases": [
{
"name": "measured movement with an independent driver finding",
"signals": {
"behavioral": { "totalPoints": 80, "trajectoryLength": 350, "approachPoints": 12, "microTremorScore": 0.1, "overshootCorrections": 1 },
"environmental": { "cdp": { "detected": true, "signals": ["selenium_evaluate"] } }
},
"candidate": { "score": 0.6, "recommendation": "block" },
"referenceFloor": 0.6
},
{
"name": "a weak movement finding with an independent driver finding",
"signals": {
"behavioral": { "totalPoints": 80, "trajectoryLength": 350, "approachPoints": 12, "approachDirectness": 0.97, "overshootCorrections": 1 },
"environmental": { "cdp": { "detected": true, "signals": ["selenium_evaluate"] } }
},
"candidate": { "score": 0.0879, "recommendation": "allow" },
"referenceFloor": 0
},
{
"name": "two categories reacting to the same movement trace",
"signals": {
"behavioral": { "totalPoints": 80, "trajectoryLength": 350, "approachPoints": 12, "microTremorScore": 0.1, "overshootCorrections": 1, "velocityVariance": 0.01, "straightLineRatio": 0.9 }
},
"candidate": { "score": 0.1566, "recommendation": "allow" },
"referenceFloor": 0.6
},
{
"name": "missing interaction data with a driver finding",
"signals": { "environmental": { "cdp": { "detected": true, "signals": ["selenium_evaluate"] } } },
"candidate": { "score": 0.31449, "recommendation": "challenge" },
"referenceFloor": 0.6
},
{
"name": "measured movement with a DevTools console observation",
"signals": {
"behavioral": { "totalPoints": 80, "trajectoryLength": 350, "approachPoints": 12, "microTremorScore": 0.1, "overshootCorrections": 1 },
"environmental": { "cdpRuntime": { "consoleAttached": true } }
},
"candidate": { "score": 0.063, "recommendation": "allow" },
"referenceFloor": 0
},
{
"name": "measured movement with a mixed CDP finding",
"signals": {
"behavioral": { "totalPoints": 80, "trajectoryLength": 350, "approachPoints": 12, "microTremorScore": 0.1, "overshootCorrections": 1 },
"environmental": { "cdp": { "detected": true, "signals": ["selenium_evaluate", "webdriver_getter_modified"] } }
},
"candidate": { "score": 0.1446, "recommendation": "allow" },
"referenceFloor": 0.6
},
{
"name": "ordinary keyboard use with a driver finding",
"signals": {
"behavioral": { "keyEvents": 6, "keyHoldSamples": 3, "keyHoldAvg": 80 },
"environmental": { "cdp": { "detected": true, "signals": ["selenium_evaluate"] } }
},
"candidate": { "score": 0.0504, "recommendation": "allow" },
"referenceFloor": 0
},
{
"name": "a corroborating driver category disabled by custom weights",
"signals": {
"behavioral": { "totalPoints": 80, "trajectoryLength": 350, "approachPoints": 12, "microTremorScore": 0.1, "overshootCorrections": 1 },
"environmental": { "cdp": { "detected": true, "signals": ["selenium_evaluate"] } }
},
"weights": { "vision_ai": 0.15, "behavioral": 0.18, "cdp": 0 },
"candidate": { "score": 0.063, "recommendation": "allow" }
},
{
"name": "the decisive floor also applies",
"signals": {
"behavioral": { "totalPoints": 80, "trajectoryLength": 350, "approachPoints": 12, "microTremorScore": 0.1, "overshootCorrections": 1 },
"environmental": { "cdp": { "detected": true, "signals": ["chromedriver_cdc"] } }
},
"candidate": { "score": 0.9, "recommendation": "block" },
"referenceFloor": 0.6
}
]
}
14 changes: 14 additions & 0 deletions packages/webdecoy/src/detection/scoring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ export function applyDecisiveScoreFloor(
return declaresWebDriver || hasInjectedDriver ? Math.max(0.9, score) : score;
}

/** Require agreement between measured interaction and a separate driver finding. */
export function applyCorroborationScoreFloor(
score: number,
detections: Detection[],
weights: Record<string, number>,
): number {
if (score >= 0.6 || detections.length < 2) return score;

const support = calculateNoisyOrCategoryScores(detections, weights);
const agrees = (category: string) => (weights[category] ?? 0) > 0 &&
(support[category] ?? 0) >= 0.4 - 1e-9;
return agrees('cdp') && (agrees('vision_ai') || agrees('behavioral')) ? 0.6 : score;
}

/**
* Aggregate detections into per-category scores. Each category's score is the
* confidence-weighted mean of its detections' scores, capped at 1.0. Categories
Expand Down
12 changes: 12 additions & 0 deletions scripts/check-captcha-score-parity.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,15 @@ for (const { name, environmental, referenceFloor } of fixtures.decisiveFloorCase
assert.equal(floor, referenceFloor, name + ' (FCaptcha decisive floor)');
console.log(name + ' — FCaptcha decisive floor ' + floor);
}

for (const { name, signals, referenceFloor } of fixtures.corroborationFloorCases) {
if (referenceFloor === undefined) continue;
const detections = [
...reference.detectVisionAI(signals),
...reference.detectBehavioral(signals),
...reference.detectCDP(signals),
];
const floor = reference.applyCorroborationFloor(0, detections);
assert.equal(floor, referenceFloor, name + ' (FCaptcha corroboration floor)');
console.log(name + ' — FCaptcha corroboration floor ' + floor);
}
Loading