From ebdbab241b030c8b7a2ba42562ce1eb9a6e021c2 Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Sat, 21 Nov 2026 17:28:56 -0600 Subject: [PATCH] Offer opt-in unified decisions in Node middleware --- .changeset/unified-middleware-decisions.md | 6 + packages/express/README.md | 5 +- packages/nextjs/src/middleware.ts | 6 +- .../nextjs/src/with-bot-protection.test.ts | 26 +++ packages/webdecoy/README.md | 11 +- packages/webdecoy/src/client.ts | 13 +- packages/webdecoy/src/index.ts | 1 + packages/webdecoy/src/sdk.ts | 67 +++++--- packages/webdecoy/src/types.ts | 26 ++- .../webdecoy/src/unified-decision.test.ts | 160 ++++++++++++++++++ 10 files changed, 287 insertions(+), 34 deletions(-) create mode 100644 .changeset/unified-middleware-decisions.md create mode 100644 packages/webdecoy/src/unified-decision.test.ts diff --git a/.changeset/unified-middleware-decisions.md b/.changeset/unified-middleware-decisions.md new file mode 100644 index 0000000..2b19aa4 --- /dev/null +++ b/.changeset/unified-middleware-decisions.md @@ -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. diff --git a/packages/express/README.md b/packages/express/README.md index 9896375..979d0d3 100644 --- a/packages/express/README.md +++ b/packages/express/README.md @@ -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; diff --git a/packages/nextjs/src/middleware.ts b/packages/nextjs/src/middleware.ts index 5d72cb8..5ee232d 100644 --- a/packages/nextjs/src/middleware.ts +++ b/packages/nextjs/src/middleware.ts @@ -263,8 +263,8 @@ export function withWebDecoy( 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; } @@ -295,7 +295,7 @@ export function withBotProtection any>( 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'; diff --git a/packages/nextjs/src/with-bot-protection.test.ts b/packages/nextjs/src/with-bot-protection.test.ts index d05fc82..926dd19 100644 --- a/packages/nextjs/src/with-bot-protection.test.ts +++ b/packages/nextjs/src/with-bot-protection.test.ts @@ -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'); + }); +}); diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index cc1e031..1e72a63 100644 --- a/packages/webdecoy/README.md +++ b/packages/webdecoy/README.md @@ -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) @@ -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 diff --git a/packages/webdecoy/src/client.ts b/packages/webdecoy/src/client.ts index 08d0ce7..222e94d 100644 --- a/packages/webdecoy/src/client.ts +++ b/packages/webdecoy/src/client.ts @@ -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 { diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index 4de9607..71a134b 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -28,6 +28,7 @@ export { WebDecoy } from './sdk'; export type { WebDecoyConfig, + DecisionMode, TLSInfo, RequestMetadata, LocalAnalysis, diff --git a/packages/webdecoy/src/sdk.ts b/packages/webdecoy/src/sdk.ts index eebbaf5..0604ad5 100644 --- a/packages/webdecoy/src/sdk.ts +++ b/packages/webdecoy/src/sdk.ts @@ -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'; @@ -28,7 +28,6 @@ import { WebDecoyConfig, RequestMetadata, ProtectOptions, - SDKDetectionRequest, SDKDetectionResponse, SSRFCanary, SSRFCanaryOptions, @@ -47,9 +46,10 @@ export class WebDecoy { private client: WebDecoyClient | null; private config: Omit< Required, - '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; @@ -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, @@ -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. @@ -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 @@ -514,7 +519,8 @@ export class WebDecoy { private async decide( metadata: RequestMetadata, - options: ProtectOptions = {} + options: ProtectOptions, + span: Span, ): Promise { // 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. @@ -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); } @@ -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', @@ -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: { @@ -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 @@ -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 @@ -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', { @@ -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' @@ -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 ?? [], @@ -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), @@ -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, diff --git a/packages/webdecoy/src/types.ts b/packages/webdecoy/src/types.ts index 0144a97..c60e938 100644 --- a/packages/webdecoy/src/types.ts +++ b/packages/webdecoy/src/types.ts @@ -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 */ @@ -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; @@ -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 } */ @@ -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. */ @@ -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'; @@ -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 */ diff --git a/packages/webdecoy/src/unified-decision.test.ts b/packages/webdecoy/src/unified-decision.test.ts new file mode 100644 index 0000000..b46d460 --- /dev/null +++ b/packages/webdecoy/src/unified-decision.test.ts @@ -0,0 +1,160 @@ +import { createFetchGuard } from './fetch-guard'; +import { tripwire } from './rules'; +import { WebDecoy } from './sdk'; +import type { RequestMetadata, SDKDetectionResponse, WebDecoyConfig } from './types'; + +const options = { + apiKey: 'sk_test_decision_fixture', + apiUrl: 'https://ingest.example', + rules: [], + countAIReferrals: false, + logger: { debug() {}, info() {}, warn() {}, error() {} }, +} satisfies WebDecoyConfig; + +const bot: RequestMetadata = { + method: 'GET', + path: '/products', + ip: '192.0.2.9', + user_agent: 'python-requests/2.31.0', + headers: { 'user-agent': 'python-requests/2.31.0' }, + timestamp: 1, +}; + +const browser: RequestMetadata = { + ...bot, + user_agent: 'Mozilla/5.0 Firefox/140.0', + headers: { + 'user-agent': 'Mozilla/5.0 Firefox/140.0', + accept: 'text/html', + 'accept-language': 'en', + 'accept-encoding': 'gzip', + }, +}; + +function unified(decision: SDKDetectionResponse['decision']): SDKDetectionResponse { + const fields = { + allow: { unified_score: 10, confidence: 20, threat_level: 'MINIMAL' }, + challenge: { unified_score: 55, confidence: 50, threat_level: 'MEDIUM' }, + block: { unified_score: 70, confidence: 70, threat_level: 'HIGH' }, + } as const; + return { + ...fields[decision], + decision_mode: 'unified_v1', + decision, + bot_detected: decision !== 'allow', + detection_id: 'detection-from-ingest', + rule_enforced: false, + }; +} + +function serve(body: unknown, status = 200) { + return jest.spyOn(globalThis, 'fetch').mockImplementation(async () => + new Response(JSON.stringify(body), { status }), + ); +} + +afterEach(() => jest.restoreAllMocks()); + +it('uses the opted-in verdict and exposes the synchronous score on the returned decision', async () => { + const fetch = serve(unified('block')); + const sdk = new WebDecoy({ ...options, decisionMode: 'unified_v1' }); + const result = await sdk.protect(bot); + expect(result.conclusion).toBe('DENY'); + expect(result.detection).toMatchObject({ decision_mode: 'unified_v1', unified_score: 70, confidence: 70 }); + expect(fetch).toHaveBeenCalledTimes(1); + const wire = JSON.parse(fetch.mock.calls[0][1]?.body as string); + expect(wire.decision_mode).toBe('unified_v1'); + expect(wire.request_metadata).not.toHaveProperty('tls_info'); +}); + +it('omits the negotiation field and keeps the legacy confidence minimum by default', async () => { + const { decision_mode, unified_score, ...legacy } = unified('block'); + expect(decision_mode).toBe('unified_v1'); + expect(unified_score).toBe(70); + const fetch = serve(legacy); + const result = await new WebDecoy(options).protect(bot); + expect(result.conclusion).toBe('ALLOW'); + expect(JSON.parse(fetch.mock.calls[0][1]?.body as string)).not.toHaveProperty('decision_mode'); +}); + +it('keeps an explicitly configured confidence minimum and the per-request override', async () => { + serve(unified('challenge')); + const sdk = new WebDecoy({ ...options, decisionMode: 'unified_v1', threatScoreThreshold: 60 }); + expect((await sdk.protect(bot)).conclusion).toBe('ALLOW'); + expect((await sdk.protect(bot, { threshold: 50 })).conclusion).toBe('CHALLENGE'); +}); + +it('runs the local gate in unified mode and traces excluded requests without transmitting them', async () => { + const fetch = serve(unified('allow')); + const setAttribute = jest.fn(); + const tracer = { startSpan: () => ({ setAttribute, end() {} }) }; + const sdk = new WebDecoy({ ...options, decisionMode: 'unified_v1', tracer }); + expect((await sdk.protect(browser)).conclusion).toBe('ALLOW'); + expect(fetch).not.toHaveBeenCalled(); + expect(setAttribute).toHaveBeenCalledWith('webdecoy.cloud.admission', 'local_gate'); + expect(setAttribute).toHaveBeenCalledWith('webdecoy.cloud.gate_datacenter_ip', false); + expect(setAttribute).toHaveBeenCalledWith('webdecoy.cloud.gate_missing_sec_ch_ua', true); +}); + +it('does not reuse a cloud block when the next request takes a different path', async () => { + const fetch = serve(unified('allow')); + fetch.mockResolvedValueOnce(new Response(JSON.stringify(unified('block')), { status: 200 })); + const sdk = new WebDecoy({ ...options, decisionMode: 'unified_v1' }); + expect((await sdk.protect(bot)).conclusion).toBe('DENY'); + expect((await sdk.protect({ ...bot, path: '/help' })).conclusion).toBe('ALLOW'); + expect(fetch).toHaveBeenCalledTimes(2); +}); + +it('never asks the cloud for a verdict when a local rule already denied', async () => { + const fetch = serve(unified('allow')); + const sdk = new WebDecoy({ ...options, decisionMode: 'unified_v1', rules: [tripwire({ paths: ['/local-rule-fixture'] })] }); + try { + const result = await sdk.protect({ ...bot, path: '/local-rule-fixture' }); + expect(result.conclusion).toBe('DENY'); + expect(result.detection.rule_enforced).toBe(true); + expect(fetch).not.toHaveBeenCalled(); + } finally { + await sdk.destroy(); + } +}); + +it.each([ + ['unavailable', { error: 'unavailable' }, 503], + ['legacy response', { ...unified('block'), decision_mode: undefined }, 200], + ['missing unified score', { ...unified('block'), unified_score: undefined }, 200], + ['unknown action', { ...unified('block'), decision: 'unexpected' }, 200], +])('serves the request and reports an ERROR for %s', async (_name, body, status) => { + const fetch = serve(body, status); + const sdk = new WebDecoy({ ...options, decisionMode: 'unified_v1' }); + const decision = await sdk.protect(bot); + expect(decision.conclusion).toBe('ERROR'); + expect(decision.allowed).toBe(true); + if (status === 503) { + expect((await sdk.protect(bot)).conclusion).toBe('ERROR'); + expect(fetch).toHaveBeenCalledTimes(1); + } +}); + +it('preserves the installation trigger and sends the opted-in mode', async () => { + const fetch = serve(unified('block')); + const sdk = new WebDecoy({ ...options, decisionMode: 'unified_v1' }); + const result = await sdk.protect({ ...bot, user_agent: 'WebDecoy-Test/1.0' }); + expect(result.conclusion).toBe('DENY'); + expect(JSON.parse(fetch.mock.calls[0][1]?.body as string)).toMatchObject({ + decision_mode: 'unified_v1', + local_analysis: { flags: ['test_trigger'] }, + }); +}); + +it.each([['monitor', undefined], ['enforce', 403]] as const)( + 'fetch guard applies the unified decision in %s mode', + async (mode, status) => { + serve(unified('block')); + const guard = createFetchGuard({ ...options, mode, decisionMode: 'unified_v1' }); + const { decision, response } = await guard.check(new Request('https://shop.example/products', { + headers: { 'user-agent': bot.user_agent! }, + })); + expect(decision.conclusion).toBe('DENY'); + expect(response?.status).toBe(status); + }, +);