From 94871f7b7c969ce51bbcbe8c406dd8a8912e5000 Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Mon, 23 Nov 2026 10:14:02 -0600 Subject: [PATCH] Add opt-in CAPTCHA scoring comparison --- packages/webdecoy/README.md | 2 + packages/webdecoy/src/captcha/http.test.ts | 15 +++++++- packages/webdecoy/src/captcha/service.ts | 5 ++- .../webdecoy/src/detection/engine.test.ts | 38 ++++++++++++++++++- packages/webdecoy/src/detection/engine.ts | 38 +++++++++++++++++-- packages/webdecoy/src/detection/index.ts | 2 +- .../webdecoy/src/detection/scoring.test.ts | 32 +++++++++++++++- packages/webdecoy/src/detection/scoring.ts | 21 +++++++++- packages/webdecoy/src/index.ts | 1 + 9 files changed, 144 insertions(+), 10 deletions(-) diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index de22c65..0818407 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 compare the current score with a candidate that accumulates evidence within each category using noisy-OR. Both scores use your configured category weights. The callback receives the `noisy-or-v1` policy ID, both scores, and their score-based recommendations. 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..f6d8a34 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-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/engine.test.ts b/packages/webdecoy/src/detection/engine.test.ts index bfce32b..649adfd 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,37 @@ 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-v1', + current: { score: expect.closeTo(0.295, 10), recommendation: 'allow' }, + candidate: { score: expect.closeTo(0.336875, 10), recommendation: 'challenge' }, + }]]); + }); +}); + describe('vision AI detection', () => { it('detects impossibly fast PoW', () => { const v = score({ temporal: { pow: { duration: 10, iterations: 100000 } } }); @@ -564,7 +596,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 +611,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..1f6a8bc 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,12 @@ import { type FingerprintStore, type RateLimiter, } from './stores'; -import { calculateCategoryScores, calculateFinalScore, recommend } from './scoring'; +import { + calculateCategoryScores, + calculateFinalScore, + calculateNoisyOrCategoryScores, + recommend, +} from './scoring'; import { detectVisionAI, detectHeadless, @@ -38,6 +43,12 @@ import { analyzeAdvancedSignals, } from './detectors'; +export interface ScoringComparison { + policy: 'noisy-or-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 +62,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 +71,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 +178,29 @@ 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 = calculateFinalScore(candidateScores, this.weights); + try { + const pending = onScoringComparison({ + policy: 'noisy-or-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/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..354d5b8 100644 --- a/packages/webdecoy/src/detection/scoring.ts +++ b/packages/webdecoy/src/detection/scoring.ts @@ -1,4 +1,4 @@ -/** Score aggregation: per-category confidence-weighted means → weighted total. */ +/** Per-category score aggregation and weighted totals. */ import type { CategoryScores, Detection, Recommendation } from './types'; @@ -35,6 +35,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/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,