diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index de22c65..3a39a97 100644 --- a/packages/webdecoy/README.md +++ b/packages/webdecoy/README.md @@ -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'; diff --git a/packages/webdecoy/src/captcha/http.test.ts b/packages/webdecoy/src/captcha/http.test.ts index d0d3305..14429d7 100644 --- a/packages/webdecoy/src/captcha/http.test.ts +++ b/packages/webdecoy/src/captcha/http.test.ts @@ -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); @@ -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), diff --git a/packages/webdecoy/src/captcha/service.ts b/packages/webdecoy/src/captcha/service.ts index bbe6e7a..22c7b24 100644 --- a/packages/webdecoy/src/captcha/service.ts +++ b/packages/webdecoy/src/captcha/service.ts @@ -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, @@ -33,6 +33,8 @@ export interface CaptchaOptions { secret?: string; /** Override per-category detection weights. */ weights?: Record; + /** 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']`). @@ -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 }); diff --git a/packages/webdecoy/src/detection/detectors/cdp.ts b/packages/webdecoy/src/detection/detectors/cdp.ts index cbb97f7..0de2490 100644 --- a/packages/webdecoy/src/detection/detectors/cdp.ts +++ b/packages/webdecoy/src/detection/detectors/cdp.ts @@ -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 ?? {}; @@ -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, diff --git a/packages/webdecoy/src/detection/engine.test.ts b/packages/webdecoy/src/detection/engine.test.ts index bfce32b..d332211 100644 --- a/packages/webdecoy/src/detection/engine.test.ts +++ b/packages/webdecoy/src/detection/engine.test.ts @@ -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'; @@ -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 } } }); @@ -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', @@ -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' }, + })); }); }); diff --git a/packages/webdecoy/src/detection/engine.ts b/packages/webdecoy/src/detection/engine.ts index 7f0d374..c48fa39 100644 --- a/packages/webdecoy/src/detection/engine.ts +++ b/packages/webdecoy/src/detection/engine.ts @@ -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'; @@ -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, @@ -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; @@ -51,6 +63,8 @@ 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; } export class DetectionEngine { @@ -58,12 +72,14 @@ export class DetectionEngine { 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. */ @@ -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] } : {}), diff --git a/packages/webdecoy/src/detection/fixtures/scoring-policy.json b/packages/webdecoy/src/detection/fixtures/scoring-policy.json index 5996118..c9fbe03 100644 --- a/packages/webdecoy/src/detection/fixtures/scoring-policy.json +++ b/packages/webdecoy/src/detection/fixtures/scoring-policy.json @@ -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" } + } ] } diff --git a/packages/webdecoy/src/detection/index.ts b/packages/webdecoy/src/detection/index.ts index 7db14cc..02f5a7a 100644 --- a/packages/webdecoy/src/detection/index.ts +++ b/packages/webdecoy/src/detection/index.ts @@ -8,7 +8,7 @@ */ export { DetectionEngine } from './engine'; -export type { DetectionEngineOptions } from './engine'; +export type { DetectionEngineOptions, ScoringComparison } from './engine'; export { calculateCategoryScores, diff --git a/packages/webdecoy/src/detection/scoring.test.ts b/packages/webdecoy/src/detection/scoring.test.ts index dc2d0e5..53bcdf5 100644 --- a/packages/webdecoy/src/detection/scoring.test.ts +++ b/packages/webdecoy/src/detection/scoring.test.ts @@ -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', () => { @@ -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 }); + }); +}); diff --git a/packages/webdecoy/src/detection/scoring.ts b/packages/webdecoy/src/detection/scoring.ts index fdf4253..8d91926 100644 --- a/packages/webdecoy/src/detection/scoring.ts +++ b/packages/webdecoy/src/detection/scoring.ts @@ -1,6 +1,21 @@ -/** Score aggregation: per-category confidence-weighted means → weighted total. */ +/** Per-category score aggregation and weighted totals. */ -import type { CategoryScores, Detection, Recommendation } from './types'; +import { hasDriverInjection } from './detectors/cdp'; +import type { CategoryScores, Detection, EnvironmentalSignals, Recommendation } from './types'; + +/** Minimum candidate score for an explicit automation declaration or driver injection. */ +export function applyDecisiveScoreFloor( + score: number, + env: EnvironmentalSignals | undefined, + weights: Record, +): number { + // The collector's top-level WebDriver flag includes indirect hints. + const declaresWebDriver = (weights.headless ?? 0) > 0 && + env?.webdriver === true && env.automationFlags?.webdriver === true; + const hasInjectedDriver = (weights.cdp ?? 0) > 0 && + env?.cdp?.detected === true && hasDriverInjection(env.cdp.signals ?? []); + return declaresWebDriver || hasInjectedDriver ? Math.max(0.9, score) : score; +} /** * Aggregate detections into per-category scores. Each category's score is the @@ -35,6 +50,25 @@ export function calculateCategoryScores( return result; } +/** Combine confidence-scaled evidence so adding a finding cannot lower its category score. */ +export function calculateNoisyOrCategoryScores( + detections: Detection[], + weights: Record, +): CategoryScores { + const remaining = new Map(); + for (const { category, score, confidence } of detections) { + if (!Number.isFinite(score) || !Number.isFinite(confidence) || score <= 0 || confidence <= 0) { + continue; + } + const evidence = Math.min(1, score * confidence); + remaining.set(category, (remaining.get(category) ?? 1) * (1 - evidence)); + } + + return Object.fromEntries( + Object.keys(weights).map((category) => [category, 1 - (remaining.get(category) ?? 1)]), + ); +} + /** Combine category scores into the final weighted score (capped at 1.0). */ export function calculateFinalScore( categoryScores: CategoryScores, diff --git a/packages/webdecoy/src/detection/types.ts b/packages/webdecoy/src/detection/types.ts index 3f61d5b..2110a24 100644 --- a/packages/webdecoy/src/detection/types.ts +++ b/packages/webdecoy/src/detection/types.ts @@ -95,6 +95,8 @@ export interface EnvironmentalSignals { [key: string]: unknown; }; automationFlags?: { + /** Explicit browser-declared WebDriver flag from navigator.webdriver. */ + webdriver?: boolean; plugins?: number; languages?: boolean; chrome?: boolean; diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index c3b9f47..93d0975 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -234,6 +234,7 @@ export { export type { DetectionEngineOptions, + ScoringComparison, Detection, ScrollJumpObservation, CategoryScores, diff --git a/scripts/check-captcha-score-parity.cjs b/scripts/check-captcha-score-parity.cjs index 99fff9b..bd5f095 100644 --- a/scripts/check-captcha-score-parity.cjs +++ b/scripts/check-captcha-score-parity.cjs @@ -38,3 +38,12 @@ for (const fixture of fixtures.cases) { assertOutcome(referenceScore, recommendation, fixture.reference, name + ' (FCaptcha)'); console.log(name + ' — Node ' + fixture.embedded.recommendation + ', FCaptcha ' + recommendation); } + +for (const { name, environmental, referenceFloor } of fixtures.decisiveFloorCases) { + if (referenceFloor === undefined) continue; + const signals = { environmental }; + const detections = [...reference.detectHeadless(signals, ''), ...reference.detectCDP(signals)]; + const floor = reference.applyDispositiveFloor(0, detections); + assert.equal(floor, referenceFloor, name + ' (FCaptcha decisive floor)'); + console.log(name + ' — FCaptcha decisive floor ' + floor); +}