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
6 changes: 6 additions & 0 deletions .changeset/unified-middleware-decisions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@webdecoy/node': minor
'@webdecoy/nextjs': minor
---

Add opt-in unified cloud decisions and trace the local admission gate while preserving the legacy default.
5 changes: 4 additions & 1 deletion packages/express/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,10 @@ interface WebDecoyMiddlewareOptions {
// 'monitor' (default) records and serves; 'enforce' blocks.
mode?: 'monitor' | 'enforce';

// Threat score above which a request counts as blocked (default: 80)
// Opt in to the synchronous unified ingest verdict.
decisionMode?: 'legacy' | 'unified_v1';

// Minimum confidence to act on the verdict (default: 80 in legacy mode).
threatScoreThreshold?: number;
// Per-request override of the same threshold
threshold?: number;
Expand Down
6 changes: 3 additions & 3 deletions packages/nextjs/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,8 @@

export interface WithBotProtectionOptions extends WebDecoyMiddlewareOptions {
/**
* Block threshold (0-100). Requests with scores above this are blocked.
* Default: 80
* Minimum confidence (0–100) required to act on a cloud verdict.
* Defaults to 80 in legacy mode. Unified mode uses ingest's confidence gates.
*/
blockThreshold?: number;
}
Expand All @@ -290,12 +290,12 @@
* });
* ```
*/
export function withBotProtection<T extends (...args: any[]) => any>(

Check warning on line 293 in packages/nextjs/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type

Check warning on line 293 in packages/nextjs/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type
handler: T,
config: WebDecoyConfig & WithBotProtectionOptions
): T {
const sdk = new WebDecoy(config);
const threshold = config.blockThreshold ?? 80;
const threshold = config.blockThreshold ?? (config.decisionMode === 'unified_v1' ? undefined : 80);
// Monitor by default, like withWebDecoy and every other adapter: a wrapper
// that says nothing about mode must never refuse a request.
const mode = config.mode ?? 'monitor';
Expand Down
26 changes: 26 additions & 0 deletions packages/nextjs/src/with-bot-protection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,29 @@ describe('withBotProtection honours mode', () => {
expect(res.statusCode).toBe(403);
});
});

describe('withBotProtection unified cloud decisions', () => {
afterEach(() => jest.restoreAllMocks());

it.each([
['monitor', 200],
['enforce', 403],
] as const)('uses the ingest decision in %s mode', async (mode, status) => {
const fetch = jest.spyOn(globalThis, 'fetch').mockImplementation(async () =>
new Response(JSON.stringify({
decision_mode: 'unified_v1', unified_score: 70, decision: 'block',
confidence: 70, threat_level: 'HIGH', bot_detected: true,
detection_id: 'fixture', rule_enforced: false,
})),
);
const handler = jest.fn((_req, res) => res.status(200).json({ ok: true }));
const res = pagesRes();
await withBotProtection(handler, {
apiKey: 'sk_test_decision_fixture', decisionMode: 'unified_v1', mode,
rules: [], countAIReferrals: false,
})(pagesReq(), res);
expect(res.statusCode).toBe(status);
expect(handler).toHaveBeenCalledTimes(mode === 'monitor' ? 1 : 0);
expect(JSON.parse(fetch.mock.calls[0][1]?.body as string).decision_mode).toBe('unified_v1');
});
});
11 changes: 10 additions & 1 deletion packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,8 @@ const wd = new WebDecoy({
apiKey: process.env.WEBDECOY_API_KEY, // optional; without it, local rules only
rules: [tripwire()], // optional; default [tripwire()], [] to opt out
apiUrl: 'https://in.webdecoy.com', // optional (default shown)
threatScoreThreshold: 80, // optional, 0-100 (default 80)
decisionMode: 'legacy', // use 'unified_v1' to opt in
threatScoreThreshold: 80, // optional minimum confidence, default 80 in legacy mode
timeout: 5000, // optional, ms (default 5000)
enableTLSFingerprinting: true, // optional (default true)
tlsRejectUnauthorized: true, // optional (default true)
Expand All @@ -277,6 +278,14 @@ Also accepted: `characteristics` (what identifies the same caller for rate limit

`protect()` also takes per-request options: `threshold`, `skipLocalAnalysis` and `metadata`.

### Unified cloud decisions

Set `decisionMode: 'unified_v1'` on `WebDecoy`, `createFetchGuard()`, or the Express, Fastify, Hono, and Next.js adapters. Adapter monitor mode exposes the verdict on `webdecoyDecision` while serving the request. `decision.detection.unified_score` is the score at request time. Later enrichment can update the detection in the dashboard.

Ingest applies its own confidence gates. An explicit `threshold`, `threatScoreThreshold`, or Next.js Pages `blockThreshold` can add a minimum confidence. Cloud-eligible requests each get their own unified verdict, including repeats from the same caller. During a cloud outage or an invalid response, the request proceeds with an `ERROR` decision.

Local rules decide first. The cloud gate forwards requests with a local bot signal, TLS material, or an explicit `skipLocalAnalysis` bypass. A datacenter IP or a missing Sec-CH-UA alone stays local. With `tracer` configured, count `webdecoy.cloud.admission` by `webdecoy.cloud.decision_mode`. The `local_gate` outcome includes two booleans for the datacenter and missing Sec-CH-UA observations. `cloud` records requests handed to the client and `backoff` records calls skipped during an outage. These attributes contain only bounded outcomes and booleans.

Without an API key no request leaves your server. With one, a request goes to WebDecoy only when local analysis flags it as needing verification (or carries TLS details); that call is awaited, bounded by `timeout`, and fails open on error.

## Client IP behind a proxy
Expand Down
13 changes: 12 additions & 1 deletion packages/webdecoy/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,18 @@ export class WebDecoyClient {
throw new Error(`API request failed: HTTP ${response.status}`);
}

return response.data as SDKDetectionResponse;
const detection = response.data;
if (request.decision_mode === 'unified_v1' && (
detection?.decision_mode !== 'unified_v1' ||
!(typeof detection.unified_score === 'number' && Number.isInteger(detection.unified_score) &&
detection.unified_score >= 0 && detection.unified_score <= 100) ||
!(Number.isInteger(detection.confidence) && detection.confidence >= 0 && detection.confidence <= 100) ||
!['allow', 'challenge', 'block'].includes(detection.decision) ||
typeof detection.detection_id !== 'string' || !detection.detection_id
)) {
throw new Error('WebDecoy did not return a valid unified decision');
}
return detection as SDKDetectionResponse;
}

async createSSRFCanary(options: SSRFCanaryOptions): Promise<SSRFCanary> {
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 @@ -28,6 +28,7 @@ export { WebDecoy } from './sdk';

export type {
WebDecoyConfig,
DecisionMode,
TLSInfo,
RequestMetadata,
LocalAnalysis,
Expand Down
67 changes: 44 additions & 23 deletions packages/webdecoy/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import type { AgentRequestInput, AgentVerdict } from './agent/types';
import { readEdgeVerdict } from './edge';
import { resolveLogger } from './logger';
import { startSpan, setAttribute, recordError, endSpan } from './tracing';
import type { Tracer } from './tracing';
import type { Span, Tracer } from './tracing';
import type { Logger } from './logger';
import { Decision, newDecisionId } from './decision';
import type { Conclusion } from './decision';
Expand All @@ -28,7 +28,6 @@ import {
WebDecoyConfig,
RequestMetadata,
ProtectOptions,
SDKDetectionRequest,
SDKDetectionResponse,
SSRFCanary,
SSRFCanaryOptions,
Expand All @@ -47,9 +46,10 @@ export class WebDecoy {
private client: WebDecoyClient | null;
private config: Omit<
Required<WebDecoyConfig>,
'apiKey' | 'rules' | 'webBotAuth' | 'characteristics' | 'decisionCache' | 'logger' | 'tracer'
'apiKey' | 'rules' | 'webBotAuth' | 'characteristics' | 'decisionCache' | 'logger' | 'tracer' | 'threatScoreThreshold'
> & {
apiKey?: string;
threatScoreThreshold?: number;
};
private ruleEngine: RuleEngine | null;
private referralCounter: AIReferralCounter | null = null;
Expand Down Expand Up @@ -84,7 +84,8 @@ export class WebDecoy {
apiKey: config.apiKey,
apiUrl: config.apiUrl || 'https://in.webdecoy.com',
enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
threatScoreThreshold: config.threatScoreThreshold ?? 80,
decisionMode: config.decisionMode ?? 'legacy',
threatScoreThreshold: config.threatScoreThreshold,
timeout: config.timeout ?? 5000,
debug: config.debug ?? false,
tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true,
Expand All @@ -110,8 +111,11 @@ export class WebDecoy {

this.webBotAuthOptions = config.webBotAuth;
this.characteristics = config.characteristics ?? DEFAULT_CHARACTERISTICS;
this.decisionCache =
config.decisionCache === false ? null : new DecisionCache(config.decisionCache ?? {});
// Unified admission scores this request's path and headers. An earlier
// verdict for the same characteristic key cannot stand in for it.
this.decisionCache = config.decisionCache === false || this.config.decisionMode === 'unified_v1'
? null
: new DecisionCache(config.decisionCache ?? {});

// Rules. When none are configured, tripwires are switched on rather than
// leaving the SDK with nothing to detect.
Expand Down Expand Up @@ -478,7 +482,8 @@ export class WebDecoy {

const span = startSpan(this.tracer, 'webdecoy.protect');
try {
const decision = (await this.decide(metadata, options)).withEdge(edge);
setAttribute(span, 'webdecoy.cloud.decision_mode', this.config.decisionMode);
const decision = (await this.decide(metadata, options, span)).withEdge(edge);

// Attributes chosen so a trace answers the questions an operator actually
// asks: what did we decide, which rule decided it, and did this request
Expand Down Expand Up @@ -514,7 +519,8 @@ export class WebDecoy {

private async decide(
metadata: RequestMetadata,
options: ProtectOptions = {}
options: ProtectOptions,
span: Span,
): Promise<Decision> {
// Declared out here so the catch below can stamp the same id and key onto
// an ERROR decision. An error is still a decision about a caller.
Expand All @@ -538,6 +544,7 @@ export class WebDecoy {
// and it must never fire the customer's rules — ingest marks the row
// is_test and keeps it out of stats, billing, and enforcement.
if (isTestTriggerUserAgent(metadata.user_agent)) {
setAttribute(span, 'webdecoy.cloud.admission', 'test_trigger');
return this.reportTestTrigger(metadata, id);
}

Expand All @@ -559,6 +566,7 @@ export class WebDecoy {
// a rate limiter has to see every request to advance its window, and a
// cached tripwire hit would stop the violation being reported.
if (ruleResult && ruleResult.action !== 'ALLOW') {
setAttribute(span, 'webdecoy.cloud.admission', 'local_rule');
const throttled = ruleResult.action === 'THROTTLE';
return new Decision({
conclusion: 'DENY',
Expand All @@ -581,6 +589,7 @@ export class WebDecoy {

// No API client — local rules are all there is, and they allowed.
if (!this.client) {
setAttribute(span, 'webdecoy.cloud.admission', 'no_api_key');
return new Decision({
conclusion: 'ALLOW',
detection: {
Expand All @@ -603,7 +612,10 @@ export class WebDecoy {
// at the top of the method so the rules still run: the limiter has to see
// every request, and a tripwire hit still has to be reported.
const cached = this.decisionCache?.get(key);
if (cached) return cached.asCached();
if (cached) {
setAttribute(span, 'webdecoy.cloud.admission', 'cached');
return cached.asCached();
}

// Perform local analysis (unless explicitly skipped)
const localAnalysis = options.skipLocalAnalysis
Expand All @@ -619,18 +631,15 @@ export class WebDecoy {

this.log.debug('Local analysis', { ...localAnalysis });

// Build detection request
const detectionRequest: SDKDetectionRequest = {
request_metadata: metadata,
local_analysis: localAnalysis,
};

// Send to server if verification is needed or TLS fingerprinting is enabled
const shouldCallServer =
localAnalysis.needs_verification ||
(this.config.enableTLSFingerprinting && metadata.tls_info);

if (!shouldCallServer) {
setAttribute(span, 'webdecoy.cloud.admission', 'local_gate');
setAttribute(span, 'webdecoy.cloud.gate_datacenter_ip', localAnalysis.datacenter_ip);
setAttribute(span, 'webdecoy.cloud.gate_missing_sec_ch_ua', localAnalysis.missing_sec_ch_ua);
// No local bot signal and nothing to fingerprint: a legitimate
// request. Allow it locally and never touch the server — only bot
// traffic reaches ingest. (A datacenter/VPN IP or a missing Sec-CH-UA
Expand All @@ -654,11 +663,18 @@ export class WebDecoy {
});
}

// Call the detection API
const detection = await this.client.detect(detectionRequest);
const unified = this.config.decisionMode === 'unified_v1';
setAttribute(span, 'webdecoy.cloud.admission', 'cloud');
const detection = await this.client.detect({
request_metadata: metadata,
local_analysis: localAnalysis,
...(unified && { decision_mode: 'unified_v1' }),
});

// Determine if request should be allowed
const threshold = options.threshold ?? this.config.threatScoreThreshold;
// Unified admission already includes confidence gates. An explicitly
// configured client minimum can still make the local policy stricter
// about when to act on a cloud verdict.
const threshold = options.threshold ?? this.config.threatScoreThreshold ?? (unified ? 0 : 80);
const allowed = detection.decision === 'allow' || detection.confidence < threshold;

this.log.debug('Server detection', {
Expand All @@ -667,9 +683,8 @@ export class WebDecoy {
allowed,
});

// A server verdict of "challenge" is the one case that can route to the
// captcha, and it only counts when the score cleared the threshold —
// below it, the request is allowed and there is nothing to challenge.
// Only a server challenge can route to CAPTCHA. The configured
// confidence minimum can suppress both challenges and denials.
const conclusion: Conclusion = allowed
? 'ALLOW'
: detection.decision === 'challenge'
Expand All @@ -678,7 +693,9 @@ export class WebDecoy {

const decision = new Decision({
conclusion,
reason: allowed ? undefined : `Threat score ${detection.confidence} (threshold ${threshold})`,
reason: allowed ? undefined : unified
? `Unified verdict ${detection.decision} (score ${detection.unified_score}, confidence ${detection.confidence})`
: `Threat score ${detection.confidence} (threshold ${threshold})`,
detection,
id,
results: ruleResult?.results ?? [],
Expand All @@ -699,6 +716,9 @@ export class WebDecoy {
// While the client is paused after an outage, every request lands here.
// The failure that started the pause was already logged as an error;
// logging each paused request too would flood the operator's logs.
if (error instanceof WebDecoyUnavailableError) {
setAttribute(span, 'webdecoy.cloud.admission', 'backoff');
}
const log = error instanceof WebDecoyUnavailableError ? this.log.debug.bind(this.log) : this.log.error.bind(this.log);
log('Protection error', {
error: error instanceof Error ? error.message : String(error),
Expand Down Expand Up @@ -760,6 +780,7 @@ export class WebDecoy {
try {
const detection = await this.client.detect({
request_metadata: metadata,
...(this.config.decisionMode === 'unified_v1' && { decision_mode: 'unified_v1' }),
local_analysis: {
suspicious_headers: false,
missing_sec_ch_ua: false,
Expand Down
26 changes: 21 additions & 5 deletions packages/webdecoy/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import type { Tracer } from './tracing';

export type { ProtectResult, Conclusion, RuleState, RuleOutcome } from './decision';

export type DecisionMode = 'legacy' | 'unified_v1';

/**
* Configuration options for the Web Decoy SDK
*/
Expand All @@ -38,9 +40,15 @@ export interface WebDecoyConfig {
enableTLSFingerprinting?: boolean;

/**
* Threat score threshold for blocking (0-100)
* Requests with scores above this will be blocked
* @default 80
* Cloud decision policy. Legacy is the default. Opt in to unified_v1 to
* use the ingest verdict based on the same synchronous score as its row.
*/
decisionMode?: DecisionMode;

/**
* Minimum cloud confidence (0–100) required to act on a block or challenge.
* Defaults to 80 in legacy mode. Unified mode uses ingest's confidence
* gates unless a minimum is explicitly set.
*/
threatScoreThreshold?: number;

Expand Down Expand Up @@ -106,7 +114,7 @@ export interface WebDecoyConfig {
/**
* Reuse of decisions that cost a network round trip. `false` disables it.
*
* Only server-derived DENY and CHALLENGE verdicts are cached — never ALLOW,
* Used in legacy mode. Only server-derived DENY and CHALLENGE verdicts are cached — never ALLOW,
* and never a rule outcome, because a rate limiter has to see every request.
* @default { ttl: 60_000, max: 10_000 }
*/
Expand Down Expand Up @@ -306,6 +314,8 @@ export interface LocalAnalysis {
export interface SDKDetectionRequest {
request_metadata: RequestMetadata;
local_analysis: LocalAnalysis;
/** Sent only when a caller explicitly requests unified admission. */
decision_mode?: 'unified_v1';
/** Privacy-bounded model-plane tool orchestration; never raw arguments or results. */
offensive_toolchain?: OffensiveToolchainObservation;
/** Reviewed framework identity evidence produced by an SDK helper. */
Expand Down Expand Up @@ -346,6 +356,12 @@ export interface FrameworkEvidenceObservation {
* Detection response from the ingest service
*/
export interface SDKDetectionResponse {
/** Present for a verdict produced by the unified policy. */
decision_mode?: 'unified_v1';

/** Synchronous ingest score (0–100), before asynchronous enrichment. */
unified_score?: number;

/** Decision: "allow", "block", or "challenge" */
decision: 'allow' | 'block' | 'challenge';

Expand All @@ -372,7 +388,7 @@ export interface SDKDetectionResponse {
* Options for the protect() method
*/
export interface ProtectOptions {
/** Custom threat score threshold for this request */
/** Minimum cloud confidence required to act on this request */
threshold?: number;

/** Skip local analysis and only use server-side detection */
Expand Down
Loading
Loading