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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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)`.
Expand Down
45 changes: 45 additions & 0 deletions packages/webdecoy/src/captcha/captcha.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
3 changes: 3 additions & 0 deletions packages/webdecoy/src/captcha/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export interface CaptchaOptions {
secret?: string;
/** Override per-category detection weights. */
weights?: Record<string, number>;
/** 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'];
/**
Expand Down Expand Up @@ -67,6 +69,7 @@ export class Captcha {

this.engine = new DetectionEngine({
weights: options.weights,
scoringPolicy: options.scoringPolicy,
requirePoW: true,
fingerprintStore,
rateLimiter,
Expand Down
45 changes: 45 additions & 0 deletions packages/webdecoy/src/detection/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
62 changes: 51 additions & 11 deletions packages/webdecoy/src/detection/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 };
Expand All @@ -54,6 +63,12 @@ export interface ScoringComparison {
export interface DetectionEngineOptions {
/** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */
weights?: Record<string, number>;
/**
* 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
Expand All @@ -70,13 +85,22 @@ export interface DetectionEngineOptions {

export class DetectionEngine {
private readonly weights: Record<string, number>;
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();
Expand All @@ -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);
Expand Down Expand Up @@ -180,29 +205,44 @@ 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 {
// An application observer must not interrupt CAPTCHA verification.
}
}

const categoryScores = useCandidate ? candidateCategoryScores! : currentCategoryScores;
const score = useCandidate ? candidateScore! : currentScore;
const recommendation = useCandidate ? candidateRecommendation! : currentRecommendation;

return {
success: score < 0.5,
score,
Expand Down
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, ScoringComparison } from './engine';
export type { DetectionEngineOptions, DetectionScoringPolicy, ScoringComparison } from './engine';

export {
calculateCategoryScores,
Expand Down
4 changes: 2 additions & 2 deletions packages/webdecoy/src/detection/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions packages/webdecoy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ export {

export type {
DetectionEngineOptions,
DetectionScoringPolicy,
ScoringComparison,
Detection,
ScrollJumpObservation,
Expand Down
28 changes: 19 additions & 9 deletions scripts/check-captcha-captured-parity.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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
);
Expand Down
Loading