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: 2 additions & 0 deletions packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,8 @@ 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.

```ts
import express from 'express';
import { webdecoyCaptcha } from '@webdecoy/express';
Expand Down
15 changes: 13 additions & 2 deletions packages/webdecoy/src/captcha/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,13 @@ describe('captcha HTTP endpoints', () => {
expect((tRes!.body as { valid: boolean }).valid).toBe(true);
});

it.each(['verify', 'score'])('applies route-specific interaction checks on /%s', async (route) => {
it.each([
{ route: 'verify', fail: () => { throw new Error('observer failed'); } },
{ route: 'score', fail: () => Promise.reject(new Error('observer failed')) },
])('applies route-specific interaction checks on /$route even when the observer fails', async ({ route, fail }) => {
const signalStore = new MemoryClientSignalStore();
const { captcha, handle } = createCaptchaEndpoints({ secret: 's', signalStore });
const onScoringComparison = jest.fn(fail);
const { captcha, handle } = createCaptchaEndpoints({ secret: 's', signalStore, onScoringComparison });
const ip = '73.15.22.100';
const now = Date.now();
const clock = jest.spyOn(Date, 'now').mockReturnValue(now);
Expand Down Expand Up @@ -143,6 +147,13 @@ 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',
current: { score: decision.score, recommendation: decision.recommendation },
candidate: { score: expect.any(Number), recommendation: 'allow' },
}]]);
expect(res?.body).not.toHaveProperty('scoringComparison');
expect(res?.body).toMatchObject({
success: true,
token: expect.any(String),
Expand Down
5 changes: 4 additions & 1 deletion packages/webdecoy/src/captcha/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
*/

import { sha256Hex } from '../webcrypto';
import { DetectionEngine } from '../detection/engine';
import { DetectionEngine, type DetectionEngineOptions } from '../detection/engine';
import type { Detection, PoWOutcome, Signals } from '../detection/types';
import {
InMemoryFingerprintStore,
Expand All @@ -33,6 +33,8 @@ export interface CaptchaOptions {
secret?: string;
/** Override per-category detection weights. */
weights?: Record<string, number>;
/** Receive score and recommendation comparisons on the server without affecting verification. */
onScoringComparison?: DetectionEngineOptions['onScoringComparison'];
/**
* Trusted reverse-proxy header names carrying a JA4 fingerprint, matched
* against the lower-cased request header keys (e.g. `['x-ja4']`).
Expand Down Expand Up @@ -68,6 +70,7 @@ export class Captcha {
requirePoW: true,
fingerprintStore,
rateLimiter,
onScoringComparison: options.onScoringComparison,
});
this.pow = new PoWManager({ secret, store: options.challengeStore, rateLimiter });
this.tokens = new TokenManager({ secret, store: options.tokenStore });
Expand Down
7 changes: 5 additions & 2 deletions packages/webdecoy/src/detection/detectors/cdp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import type { Detection, Signals } from '../types';

const HIGH_CONFIDENCE_SIGNALS = ['chromedriver_cdc', 'puppeteer_eval', 'cdp_script_injection'];

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

export function detectCDP(signals: Signals): Detection[] {
const detections: Detection[] = [];
const cdp = signals.environmental?.cdp ?? {};
Expand All @@ -12,9 +16,8 @@ export function detectCDP(signals: Signals): Detection[] {

const signalList = cdp.signals ?? [];
const signalCount = signalList.length;
const hasHighConf = signalList.some((s) => HIGH_CONFIDENCE_SIGNALS.includes(s));

if (hasHighConf) {
if (hasDriverInjection(signalList)) {
detections.push({
category: 'cdp',
score: 0.9,
Expand Down
65 changes: 64 additions & 1 deletion packages/webdecoy/src/detection/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import { DetectionEngine } from './engine';
import fontPlatformFixtures from './fixtures/font-platform.json';
import inputModalityFixtures from './fixtures/input-modality.json';
import scoringPolicyFixtures from './fixtures/scoring-policy.json';
import type { DetectionContext, Signals, Verdict } from './types';

const UA_CHROME_WIN = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0';
Expand Down Expand Up @@ -253,6 +254,64 @@ describe('observe-only scroll diagnostics', () => {
});
});

describe('scoring comparison', () => {
it('uses custom weights for both scores and preserves the current verdict when they disagree', () => {
const onScoringComparison = jest.fn();
const weights = { vision_ai: 0.5 };
const observations = scoringPolicyFixtures.cases.find(({ name }) => name === 'two observations in one category')!;
const context = {
ip: '203.0.113.9',
siteKey: 'test',
userAgent: UA_CHROME_MAC,
headers: GOOD_HEADERS,
pow: { provided: true, valid: true, serverElapsed: 3000 },
extraDetections: observations.detections,
};
const baseline = new DetectionEngine({ weights }).score({ behavioral: HUMAN_BEHAVIOR }, context);
const verdict = new DetectionEngine({ weights, onScoringComparison }).score({
behavioral: { ...HUMAN_BEHAVIOR, scrollMorphology: { samples: 3, maxStep: 680 } },
}, context);

expect(verdict).toEqual({
...baseline,
timestamp: verdict.timestamp,
observations: [{ id: 'large-scroll-step-v1', mode: 'observe', status: 'detected', samples: 3, maxStep: 680 }],
});
expect(onScoringComparison.mock.calls).toEqual([[{
policy: 'noisy-or-decisive-v1',
current: { score: expect.closeTo(0.295, 10), recommendation: 'allow' },
candidate: { score: expect.closeTo(0.336875, 10), recommendation: 'challenge' },
}]]);
});

it.each(scoringPolicyFixtures.decisiveFloorCases)('computes the candidate score for $name', ({
environmental, weights, candidate,
}) => {
const onScoringComparison = jest.fn();
const options = { weights: weights ?? { headless: 0.15, cdp: 0.12 } };
const signals = { behavioral: HUMAN_BEHAVIOR, environmental };
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-decisive-v1',
current: { score: current.score, recommendation: current.recommendation },
candidate: {
score: expect.closeTo(candidate.score, 10),
recommendation: candidate.recommendation,
},
}]]);
});
});

describe('vision AI detection', () => {
it('detects impossibly fast PoW', () => {
const v = score({ temporal: { pow: { duration: 10, iterations: 100000 } } });
Expand Down Expand Up @@ -564,7 +623,8 @@ describe('PoW outcome', () => {

describe('input modality controls from FCaptcha ' + inputModalityFixtures.reference.version, () => {
it.each(inputModalityFixtures.cases)('$name', ({ behavioral, reasons }) => {
const engine = new DetectionEngine();
const onScoringComparison = jest.fn();
const engine = new DetectionEngine({ onScoringComparison });
const verdict = engine.score({ behavioral }, {
ip: '203.0.113.9',
siteKey: 'test',
Expand All @@ -578,6 +638,9 @@ describe('input modality controls from FCaptcha ' + inputModalityFixtures.refere
.sort();
expect(inputReasons).toEqual([...reasons].sort());
expect(verdict.recommendation).toBe('allow');
expect(onScoringComparison).toHaveBeenCalledWith(expect.objectContaining({
candidate: { score: expect.any(Number), recommendation: 'allow' },
}));
});
});

Expand Down
41 changes: 38 additions & 3 deletions packages/webdecoy/src/detection/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* supplies a {@link PoWOutcome} and the engine emits the matching detections.
*/

import type { Detection, DetectionContext, Signals, Verdict } from './types';
import type { Detection, DetectionContext, Recommendation, Signals, Verdict } from './types';
import { DEFAULT_WEIGHTS } from './weights';
import { observeScrollJump } from './scroll-observation';
import { isDatacenterIP } from './ip';
Expand All @@ -17,7 +17,13 @@ import {
type FingerprintStore,
type RateLimiter,
} from './stores';
import { calculateCategoryScores, calculateFinalScore, recommend } from './scoring';
import {
applyDecisiveScoreFloor,
calculateCategoryScores,
calculateFinalScore,
calculateNoisyOrCategoryScores,
recommend,
} from './scoring';
import {
detectVisionAI,
detectHeadless,
Expand All @@ -38,6 +44,12 @@ import {
analyzeAdvancedSignals,
} from './detectors';

export interface ScoringComparison {
policy: 'noisy-or-decisive-v1';
current: { score: number; recommendation: Recommendation };
candidate: { score: number; recommendation: Recommendation };
}

export interface DetectionEngineOptions {
/** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */
weights?: Record<string, number>;
Expand All @@ -51,19 +63,23 @@ export interface DetectionEngineOptions {
fingerprintStore?: FingerprintStore;
/** Rate limiter for rate-abuse detection (defaults to in-memory). */
rateLimiter?: RateLimiter;
/** Receive a server-side comparison of the two aggregation methods using the same weights. */
onScoringComparison?: (comparison: ScoringComparison) => void | Promise<void>;
}

export class DetectionEngine {
private readonly weights: Record<string, number>;
private readonly requirePoW: boolean;
private readonly fingerprintStore: FingerprintStore;
private readonly rateLimiter: RateLimiter;
private readonly onScoringComparison: DetectionEngineOptions['onScoringComparison'];

constructor(options: DetectionEngineOptions = {}) {
this.weights = options.weights ?? DEFAULT_WEIGHTS;
this.requirePoW = options.requirePoW ?? true;
this.fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter();
this.onScoringComparison = options.onScoringComparison;
}

/** Score `signals` for the given request context and return a verdict. */
Expand Down Expand Up @@ -163,12 +179,31 @@ export class DetectionEngine {
// --- Aggregate -------------------------------------------------------------
const categoryScores = calculateCategoryScores(detections, this.weights);
const score = calculateFinalScore(categoryScores, this.weights);
const recommendation = recommend(score);
const scrollObservation = observeScrollJump(signals.behavioral);

const onScoringComparison = this.onScoringComparison;
if (onScoringComparison) {
const candidateScores = calculateNoisyOrCategoryScores(detections, this.weights);
const candidateScore = applyDecisiveScoreFloor(
calculateFinalScore(candidateScores, this.weights), signals.environmental, this.weights,
);
try {
const pending = onScoringComparison({
policy: 'noisy-or-decisive-v1',
current: { score, recommendation },
candidate: { score: candidateScore, recommendation: recommend(candidateScore) },
});
void pending?.catch(() => {});
} catch {
// An application observer must not interrupt CAPTCHA verification.
}
}

return {
success: score < 0.5,
score,
recommendation: recommend(score),
recommendation,
categoryScores,
detections,
...(scrollObservation ? { observations: [scrollObservation] } : {}),
Expand Down
54 changes: 54 additions & 0 deletions packages/webdecoy/src/detection/fixtures/scoring-policy.json
Original file line number Diff line number Diff line change
Expand Up @@ -198,5 +198,59 @@
"success": true
}
}
],
"decisiveFloorCases": [
{
"name": "an explicit WebDriver declaration",
"environmental": { "webdriver": true, "automationFlags": { "webdriver": true } },
"candidate": { "score": 0.9, "recommendation": "block" },
"referenceFloor": 0.9
},
{
"name": "an older aggregate WebDriver flag",
"environmental": { "webdriver": true },
"candidate": { "score": 0.135375, "recommendation": "allow" },
"referenceFloor": 0.9
},
{
"name": "an indirect WebDriver hint with a false explicit flag",
"environmental": { "webdriver": true, "automationFlags": { "webdriver": false } },
"candidate": { "score": 0.135375, "recommendation": "allow" },
"referenceFloor": 0.9
},
{
"name": "a known injected driver marker",
"environmental": { "cdp": { "detected": true, "signals": ["chromedriver_cdc"] } },
"candidate": { "score": 0.9, "recommendation": "block" },
"referenceFloor": 0.9
},
{
"name": "a generic CDP finding",
"environmental": { "cdp": { "detected": true, "signals": ["selenium_evaluate"] } },
"candidate": { "score": 0.0504, "recommendation": "allow" },
"referenceFloor": 0
},
{
"name": "a DevTools console observation",
"environmental": { "cdpRuntime": { "consoleAttached": true } },
"candidate": { "score": 0, "recommendation": "allow" },
"referenceFloor": 0
},
{
"name": "decisive findings in disabled categories",
"environmental": {
"webdriver": true,
"automationFlags": { "webdriver": true },
"cdp": { "detected": true, "signals": ["chromedriver_cdc"] }
},
"weights": { "headless": 0, "cdp": 0 },
"candidate": { "score": 0, "recommendation": "allow" }
},
{
"name": "a weighted score above the floor",
"environmental": { "webdriver": true, "automationFlags": { "webdriver": true } },
"weights": { "headless": 1.1, "cdp": 0 },
"candidate": { "score": 0.99275, "recommendation": "block" }
}
]
}
2 changes: 1 addition & 1 deletion packages/webdecoy/src/detection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/

export { DetectionEngine } from './engine';
export type { DetectionEngineOptions } from './engine';
export type { DetectionEngineOptions, ScoringComparison } from './engine';

export {
calculateCategoryScores,
Expand Down
32 changes: 31 additions & 1 deletion packages/webdecoy/src/detection/scoring.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import fixtures from './fixtures/scoring-policy.json';
import { calculateCategoryScores, calculateFinalScore, recommend } from './scoring';
import {
calculateCategoryScores,
calculateFinalScore,
calculateNoisyOrCategoryScores,
recommend,
} from './scoring';
import { DEFAULT_WEIGHTS } from './weights';

describe('embedded CAPTCHA score policy', () => {
Expand All @@ -11,3 +16,28 @@ describe('embedded CAPTCHA score policy', () => {
expect(score < 0.5).toBe(embedded.success);
});
});

describe('noisy-OR score aggregation', () => {
it.each(fixtures.cases.filter(({ name }) => [
'ordinary input with no findings',
'one weak behavior finding',
'one stronger observation',
'two observations in one category',
'debug context contributes without corroborating',
].includes(name)))('matches the reference aggregation for $name', ({ detections, reference }) => {
const categories = calculateNoisyOrCategoryScores(detections, DEFAULT_WEIGHTS);
expect(calculateFinalScore(categories, DEFAULT_WEIGHTS)).toBeCloseTo(reference.score, 10);
});

it('bounds categories when evidence is oversized or invalid', () => {
const detections = [
{ category: 'oversized', reason: 'fixture', score: 2, confidence: 1 },
{ category: 'invalid', reason: 'fixture', score: NaN, confidence: 1 },
{ category: 'invalid', reason: 'fixture', score: 0.8, confidence: Infinity },
{ category: 'invalid', reason: 'fixture', score: -1, confidence: -1 },
{ category: 'ignored', reason: 'fixture', score: 1, confidence: 1 },
];
expect(calculateNoisyOrCategoryScores(detections, { oversized: 1, invalid: 1, empty: 1 }))
.toEqual({ oversized: 1, invalid: 0, empty: 0 });
});
});
Loading
Loading