diff --git a/CHANGELOG.md b/CHANGELOG.md index 8724434..014b9f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Opt into FCaptcha-aligned noisy-OR scoring and decisive/corroboration floors for embedded CAPTCHA verification and token issuance with `scoringPolicy: 'noisy-or-floors-v1'`. + ## [0.29.0] - 2026-11-23 ### Added diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index 39850d1..22f361b 100644 --- a/packages/webdecoy/README.md +++ b/packages/webdecoy/README.md @@ -318,7 +318,9 @@ 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-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. +The default `weighted-mean-v1` policy preserves the original SDK behavior. Pass `onScoringComparison` to the server adapter, `Captcha`, or `DetectionEngine` to receive that baseline and the `noisy-or-floors-v1` score and recommendation on the server. Both scores use your configured category weights. The noisy-OR policy 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. + +After validating the comparison in your traffic, pass `scoringPolicy: 'noisy-or-floors-v1'` to enforce it for verification and token issuance. The option is available on `DetectionEngine`, `Captcha`, and every CAPTCHA server adapter; unknown policy names throw instead of silently falling back. ```ts import express from 'express'; @@ -338,6 +340,15 @@ app.post('/login', async (req, res) => { }); ``` +To enforce the noisy-OR policy, replace the adapter registration above with: + +```ts +app.use(webdecoyCaptcha({ + secret: process.env.WEBDECOY_SECRET, + scoringPolicy: 'noisy-or-floors-v1', +})); +``` + `WEBDECOY_SECRET` is just the variable name used here; pass the value as `secret`. Generate one with `openssl rand -hex 32`. Challenge and token stores are in memory by default; for serverless or multi-instance deployments, pass shared `challengeStore` and `tokenStore` implementations. To score signals yourself, use `new DetectionEngine(options).score(signals, context)`. diff --git a/packages/webdecoy/src/captcha/captcha.test.ts b/packages/webdecoy/src/captcha/captcha.test.ts index b23230b..bd4144c 100644 --- a/packages/webdecoy/src/captcha/captcha.test.ts +++ b/packages/webdecoy/src/captcha/captcha.test.ts @@ -249,6 +249,51 @@ describe('Captcha end-to-end', () => { expect((await captcha.verifyToken(token!, ip)).reason).toBe('token_already_used'); }); + it('withholds a token when the noisy-OR floors policy blocks explicit automation', async () => { + const current = new Captcha({ secret: SECRET }); + const enforced = new Captcha({ secret: SECRET, scoringPolicy: 'noisy-or-floors-v1' }); + const ip = '73.15.22.100'; + const realNow = Date.now(); + const clock = jest.spyOn(Date, 'now').mockReturnValue(realNow); + + try { + const currentChallenge = await current.issueChallenge('site', ip, 2); + const enforcedChallenge = await enforced.issueChallenge('site', ip, 2); + clock.mockReturnValue(realNow + 3000); + + const submit = (captcha: Captcha, challenge: ChallengeData) => captcha.verify({ + siteKey: 'site', + ip, + userAgent: UA_CHROME_MAC, + headers: GOOD_HEADERS, + signals: { + behavioral: HUMAN_BEHAVIOR, + environmental: { + ...CHROME_MAC_ENV, + webdriver: true, + automationFlags: { ...CHROME_MAC_ENV.automationFlags, webdriver: true }, + }, + meta: { challengeNonce: challenge.nonce }, + }, + powSolution: solve(challenge), + }); + + const currentResult = await submit(current, currentChallenge); + const enforcedResult = await submit(enforced, enforcedChallenge); + + expect(currentResult).toMatchObject({ success: true, recommendation: 'allow' }); + expect(currentResult.token).toEqual(expect.any(String)); + expect(enforcedResult).toMatchObject({ + success: false, + score: 0.9, + recommendation: 'block', + token: null, + }); + } finally { + clock.mockRestore(); + } + }); + it('fails a clear bot (headless + CDP + datacenter, no PoW) and issues no token', async () => { const captcha = new Captcha({ secret: SECRET }); const result = await captcha.verify({ diff --git a/packages/webdecoy/src/captcha/service.ts b/packages/webdecoy/src/captcha/service.ts index 22c7b24..80b16da 100644 --- a/packages/webdecoy/src/captcha/service.ts +++ b/packages/webdecoy/src/captcha/service.ts @@ -33,6 +33,8 @@ export interface CaptchaOptions { secret?: string; /** Override per-category detection weights. */ weights?: Record; + /** Aggregation policy used for scoring, verification, and token issuance. */ + scoringPolicy?: DetectionEngineOptions['scoringPolicy']; /** Receive score and recommendation comparisons on the server without affecting verification. */ onScoringComparison?: DetectionEngineOptions['onScoringComparison']; /** @@ -67,6 +69,7 @@ export class Captcha { this.engine = new DetectionEngine({ weights: options.weights, + scoringPolicy: options.scoringPolicy, requirePoW: true, fingerprintStore, rateLimiter, diff --git a/packages/webdecoy/src/detection/engine.test.ts b/packages/webdecoy/src/detection/engine.test.ts index 3813860..8812004 100644 --- a/packages/webdecoy/src/detection/engine.test.ts +++ b/packages/webdecoy/src/detection/engine.test.ts @@ -310,6 +310,51 @@ describe('scoring comparison', () => { }, }]]); }); + + it('can enforce the candidate policy without changing the default', () => { + const onScoringComparison = jest.fn(); + const context = { + ip: '203.0.113.9', + siteKey: 'test', + userAgent: UA_CHROME_MAC, + headers: GOOD_HEADERS, + pow: { provided: true, valid: true, serverElapsed: 3000 }, + }; + const signals = { + behavioral: HUMAN_BEHAVIOR, + environmental: { + ...CHROME_MAC_ENV, + webdriver: true, + automationFlags: { ...CHROME_MAC_ENV.automationFlags, webdriver: true }, + }, + }; + + const current = new DetectionEngine().score(signals, context); + const explicitCurrent = new DetectionEngine({ scoringPolicy: 'weighted-mean-v1' }).score( + signals, + context, + ); + const enforced = new DetectionEngine({ + scoringPolicy: 'noisy-or-floors-v1', + onScoringComparison, + }).score(signals, context); + + expect(current).toMatchObject({ success: true, recommendation: 'allow' }); + expect(current.score).toBeLessThan(0.5); + expect(explicitCurrent).toEqual({ ...current, timestamp: explicitCurrent.timestamp }); + expect(enforced).toMatchObject({ success: false, score: 0.9, recommendation: 'block' }); + expect(onScoringComparison).toHaveBeenCalledWith({ + policy: 'noisy-or-floors-v1', + current: { score: current.score, recommendation: current.recommendation }, + candidate: { score: enforced.score, recommendation: enforced.recommendation }, + }); + }); + + it('rejects an unknown enforcement policy instead of silently falling back', () => { + expect(() => new DetectionEngine({ scoringPolicy: 'future-policy' as never })).toThrow( + 'Unknown detection scoring policy: future-policy', + ); + }); }); describe('corroboration floor', () => { diff --git a/packages/webdecoy/src/detection/engine.ts b/packages/webdecoy/src/detection/engine.ts index b6d52c2..81458ce 100644 --- a/packages/webdecoy/src/detection/engine.ts +++ b/packages/webdecoy/src/detection/engine.ts @@ -7,7 +7,14 @@ * supplies a {@link PoWOutcome} and the engine emits the matching detections. */ -import type { Detection, DetectionContext, Recommendation, Signals, Verdict } from './types'; +import type { + CategoryScores, + Detection, + DetectionContext, + Recommendation, + Signals, + Verdict, +} from './types'; import { DEFAULT_WEIGHTS } from './weights'; import { observeScrollJump } from './scroll-observation'; import { isDatacenterIP } from './ip'; @@ -45,6 +52,8 @@ import { analyzeAdvancedSignals, } from './detectors'; +export type DetectionScoringPolicy = 'weighted-mean-v1' | 'noisy-or-floors-v1'; + export interface ScoringComparison { policy: 'noisy-or-floors-v1'; current: { score: number; recommendation: Recommendation }; @@ -54,6 +63,12 @@ export interface ScoringComparison { export interface DetectionEngineOptions { /** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */ weights?: Record; + /** + * Aggregation policy used for the returned verdict and CAPTCHA token decision. + * Defaults to `weighted-mean-v1`; opt in to `noisy-or-floors-v1` to enforce + * the FCaptcha-aligned noisy-OR, decisive-floor, and corroboration-floor policy. + */ + scoringPolicy?: DetectionScoringPolicy; /** * When true (default), a request with no PoW outcome emits a hard-fail "No PoW * solution provided" detection — matching the reference server. Set false to @@ -70,13 +85,22 @@ export interface DetectionEngineOptions { export class DetectionEngine { private readonly weights: Record; + private readonly scoringPolicy: DetectionScoringPolicy; private readonly requirePoW: boolean; private readonly fingerprintStore: FingerprintStore; private readonly rateLimiter: RateLimiter; private readonly onScoringComparison: DetectionEngineOptions['onScoringComparison']; constructor(options: DetectionEngineOptions = {}) { + if ( + options.scoringPolicy !== undefined && + options.scoringPolicy !== 'weighted-mean-v1' && + options.scoringPolicy !== 'noisy-or-floors-v1' + ) { + throw new TypeError('Unknown detection scoring policy: ' + String(options.scoringPolicy)); + } this.weights = options.weights ?? DEFAULT_WEIGHTS; + this.scoringPolicy = options.scoringPolicy ?? 'weighted-mean-v1'; this.requirePoW = options.requirePoW ?? true; this.fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore(); this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter(); @@ -89,7 +113,8 @@ export class DetectionEngine { const headers = context.headers ?? {}; const detections: Detection[] = []; const onScoringComparison = this.onScoringComparison; - const corroborating: Detection[] | undefined = onScoringComparison ? [] : undefined; + const useCandidate = this.scoringPolicy === 'noisy-or-floors-v1'; + const corroborating: Detection[] | undefined = onScoringComparison || useCandidate ? [] : undefined; // Orchestrator-supplied detections (e.g. signals-tampering check). if (context.extraDetections) detections.push(...context.extraDetections); @@ -180,22 +205,33 @@ export class DetectionEngine { detections.push(...analyzeAdvancedSignals(signals)); // --- Aggregate ------------------------------------------------------------- - const categoryScores = calculateCategoryScores(detections, this.weights); - const score = calculateFinalScore(categoryScores, this.weights); - const recommendation = recommend(score); + const currentCategoryScores = calculateCategoryScores(detections, this.weights); + const currentScore = calculateFinalScore(currentCategoryScores, this.weights); + const currentRecommendation = recommend(currentScore); const scrollObservation = observeScrollJump(signals.behavioral); - if (onScoringComparison && corroborating) { - const candidateScores = calculateNoisyOrCategoryScores(detections, this.weights); + let candidateCategoryScores: CategoryScores | undefined; + let candidateScore: number | undefined; + let candidateRecommendation: Recommendation | undefined; + if (corroborating) { + candidateCategoryScores = calculateNoisyOrCategoryScores(detections, this.weights); const decisiveScore = applyDecisiveScoreFloor( - calculateFinalScore(candidateScores, this.weights), signals.environmental, this.weights, + calculateFinalScore(candidateCategoryScores, this.weights), signals.environmental, this.weights, ); - const candidateScore = applyCorroborationScoreFloor(decisiveScore, corroborating, this.weights); + candidateScore = applyCorroborationScoreFloor(decisiveScore, corroborating, this.weights); + candidateRecommendation = recommend(candidateScore); + } + + if ( + onScoringComparison && + candidateScore !== undefined && + candidateRecommendation !== undefined + ) { try { const pending = onScoringComparison({ policy: 'noisy-or-floors-v1', - current: { score, recommendation }, - candidate: { score: candidateScore, recommendation: recommend(candidateScore) }, + current: { score: currentScore, recommendation: currentRecommendation }, + candidate: { score: candidateScore, recommendation: candidateRecommendation }, }); void pending?.catch(() => {}); } catch { @@ -203,6 +239,10 @@ export class DetectionEngine { } } + const categoryScores = useCandidate ? candidateCategoryScores! : currentCategoryScores; + const score = useCandidate ? candidateScore! : currentScore; + const recommendation = useCandidate ? candidateRecommendation! : currentRecommendation; + return { success: score < 0.5, score, diff --git a/packages/webdecoy/src/detection/index.ts b/packages/webdecoy/src/detection/index.ts index 02f5a7a..cef5415 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, ScoringComparison } from './engine'; +export type { DetectionEngineOptions, DetectionScoringPolicy, ScoringComparison } from './engine'; export { calculateCategoryScores, diff --git a/packages/webdecoy/src/detection/types.ts b/packages/webdecoy/src/detection/types.ts index 2110a24..5e3f573 100644 --- a/packages/webdecoy/src/detection/types.ts +++ b/packages/webdecoy/src/detection/types.ts @@ -313,9 +313,9 @@ export interface ScrollJumpObservation { /** Final verdict returned by {@link DetectionEngine.score}. */ export interface Verdict { - /** True when the weighted score is below the success threshold (< 0.5). */ + /** True when the selected policy's score is below the success threshold (< 0.5). */ success: boolean; - /** Weighted final score, 0..1. */ + /** Selected policy's final score, 0..1. */ score: number; /** Recommended action. */ recommendation: Recommendation; diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index 93d0975..407f627 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -234,6 +234,7 @@ export { export type { DetectionEngineOptions, + DetectionScoringPolicy, ScoringComparison, Detection, ScrollJumpObservation, diff --git a/scripts/check-captcha-captured-parity.cjs b/scripts/check-captcha-captured-parity.cjs index 5ad60f9..d9c224f 100644 --- a/scripts/check-captcha-captured-parity.cjs +++ b/scripts/check-captcha-captured-parity.cjs @@ -193,25 +193,35 @@ for (const [index, sample] of samples.entries()) { ...sample.headers, }); const userAgent = headers['user-agent']; + const context = { + ip: '192.0.2.' + (index + 1), + siteKey: 'captured-parity-' + index, + userAgent, + headers, + widgetInteraction: sample.capture?.endpoint !== '/api/score', + }; let comparison; const node = new embedded.DetectionEngine({ requirePoW: false, onScoringComparison(value) { comparison = value; }, - }).score(structuredClone(sample.signals), { - ip: '192.0.2.' + (index + 1), - siteKey: 'captured-parity-' + index, - userAgent, - headers, - widgetInteraction: sample.capture?.endpoint !== '/api/score', - }); + }).score(structuredClone(sample.signals), context); + const enforced = new embedded.DetectionEngine({ + requirePoW: false, + scoringPolicy: 'noisy-or-floors-v1', + }).score(structuredClone(sample.signals), context); const fcaptcha = referenceVerdict(sample, headers, userAgent); const expected = manifest.expected[sample.id]; assert.ok(comparison, sample.id + ' emitted a candidate scoring comparison'); assertOutcome(node, expected.node, sample.id + ' (Node current)'); assertOutcome(comparison.candidate, expected.candidate, sample.id + ' (Node candidate)'); + assertOutcome(enforced, expected.candidate, sample.id + ' (Node enforced)'); assertOutcome(fcaptcha, expected.reference, sample.id + ' (FCaptcha)'); + assert.ok( + Math.abs(enforced.score - comparison.candidate.score) < 1e-10, + sample.id + ' enforced score matches the observed candidate' + ); assert.deepEqual( getReasonIds(node.detections, sample.id + ' (Node)'), [...expected.node.reasonIds].sort(), @@ -226,8 +236,8 @@ for (const [index, sample] of samples.entries()) { sample.id + ' — Node ' + node.recommendation + - ', candidate ' + - comparison.candidate.recommendation + + ', enforced ' + + enforced.recommendation + ', FCaptcha ' + fcaptcha.recommendation );