From a0287a28c8cff779b159d1914017047a659d96be Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Sun, 22 Nov 2026 10:46:46 -0600 Subject: [PATCH] Report Node rule delivery outcomes and flush Next middleware events --- packages/express/src/middleware.ts | 1 + packages/fastify/src/plugin.ts | 1 + packages/nextjs/README.md | 2 + packages/nextjs/src/middleware.test.ts | 35 +++++ packages/nextjs/src/middleware.ts | 7 +- packages/webdecoy/README.md | 6 + packages/webdecoy/src/client.ts | 13 +- packages/webdecoy/src/fetch-guard.ts | 1 + packages/webdecoy/src/index.ts | 1 + packages/webdecoy/src/sdk.ts | 39 ++++- packages/webdecoy/src/types.ts | 6 + .../webdecoy/src/violation-reporter.test.ts | 143 ++++++++++++++++++ packages/webdecoy/src/violation-reporter.ts | 92 +++++++---- 13 files changed, 308 insertions(+), 39 deletions(-) create mode 100644 packages/webdecoy/src/violation-reporter.test.ts diff --git a/packages/express/src/middleware.ts b/packages/express/src/middleware.ts index abd8e51..14eec98 100644 --- a/packages/express/src/middleware.ts +++ b/packages/express/src/middleware.ts @@ -239,6 +239,7 @@ export function webdecoy( threshold: config.threshold, skipLocalAnalysis: config.skipLocalAnalysis, metadata: config.metadata, + violationReporting: { mode }, }); // Honeytoken injection. diff --git a/packages/fastify/src/plugin.ts b/packages/fastify/src/plugin.ts index 9ab85e2..f5ba03b 100644 --- a/packages/fastify/src/plugin.ts +++ b/packages/fastify/src/plugin.ts @@ -272,6 +272,7 @@ async function webdecoyPluginImpl( threshold: options.threshold, skipLocalAnalysis: options.skipLocalAnalysis, metadata: options.metadata, + violationReporting: { mode }, }); // Monitor mode: record the verdict, change nothing. Checked before the diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md index d0ef598..e3c564b 100644 --- a/packages/nextjs/README.md +++ b/packages/nextjs/README.md @@ -77,6 +77,8 @@ To get a key: sign up at [app.webdecoy.com](https://app.webdecoy.com), add your ### Monitor mode +When Next.js supplies a middleware event, `withWebDecoy` uses its `waitUntil` hook to send rule violations after the request decision. Pass that event through if you wrap the middleware with your own function. + `withWebDecoy` starts in **monitor mode**: it serves every request and passes the verdict to your app as request headers, which route handlers and server components can read: | Request header | Value | diff --git a/packages/nextjs/src/middleware.test.ts b/packages/nextjs/src/middleware.test.ts index ad3af1a..e09f874 100644 --- a/packages/nextjs/src/middleware.test.ts +++ b/packages/nextjs/src/middleware.test.ts @@ -1,4 +1,5 @@ import { NextRequest } from 'next/server'; +import { tripwire } from '@webdecoy/node'; import { withWebDecoy } from './middleware'; import { getEdgeVerdict } from './edge-verdict'; @@ -149,3 +150,37 @@ describe('monitor mode', () => { expect(forwardedToApp(res, 'x-webdecoy-would-block')).toMatch(/^(true|false)$/); }); }); + +describe('Next.js rule violation delivery', () => { + it.each([ + { mode: 'monitor', status: 200, dryRun: true, clearance: undefined }, + { mode: 'enforce', status: 403, dryRun: false, clearance: 'fixture-clearance' }, + ] as const)('flushes $mode reports through the request lifecycle', async ({ mode, status, dryRun, clearance }) => { + const fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 201 })); + const waitUntil = jest.fn]>(); + const middleware = withWebDecoy({ + apiKey: 'sk_test_middleware_delivery', + apiUrl: 'https://ingest.example', + countAIReferrals: false, + mode, + rules: [tripwire({ paths: ['/fixture-path'], includeDefaults: false })], + }); + + try { + const response = await middleware(new NextRequest('https://shop.example/fixture-path', { + headers: { cookie: 'wd_clearance=fixture-clearance' }, + }), { waitUntil }); + expect(response.status).toBe(status); + expect(waitUntil).toHaveBeenCalledTimes(1); + await waitUntil.mock.calls[0][0]; + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, request] = fetchMock.mock.calls[0]; + expect(url).toBe('https://ingest.example/api/v1/sdk/violations/batch'); + const { events } = JSON.parse(String(request?.body)); + expect(events).toEqual([expect.objectContaining({ rule: 'tripwire', action: 'DENY', dryRun })]); + expect(events[0].clearance).toBe(clearance); + } finally { + fetchMock.mockRestore(); + } + }); +}); diff --git a/packages/nextjs/src/middleware.ts b/packages/nextjs/src/middleware.ts index 5ee232d..6ee2362 100644 --- a/packages/nextjs/src/middleware.ts +++ b/packages/nextjs/src/middleware.ts @@ -3,6 +3,7 @@ */ import { NextRequest, NextResponse } from 'next/server'; +import type { NextFetchEvent } from 'next/server'; import { WebDecoy, WebDecoyConfig, @@ -153,7 +154,7 @@ function defaultOnError(req: NextRequest, error: Error): NextResponse | null { */ export function withWebDecoy( config: WebDecoyConfig & WebDecoyMiddlewareOptions -): (req: NextRequest) => Promise { +): (req: NextRequest, event?: Pick) => Promise { const sdk = new WebDecoy(config); const getIP = config.getIP || ((req: NextRequest) => resolveIP(req, config.trustProxy)); @@ -162,7 +163,7 @@ export function withWebDecoy( const onError = config.onError || defaultOnError; const skipPaths = config.skipPaths; - return async (req: NextRequest): Promise => { + return async (req, event): Promise => { try { const pathname = req.nextUrl.pathname; @@ -194,6 +195,7 @@ export function withWebDecoy( threshold: config.threshold, skipLocalAnalysis: config.skipLocalAnalysis, metadata: config.metadata, + violationReporting: { mode, waitUntil: event?.waitUntil?.bind(event) }, }); // Monitor mode: record the verdict, change nothing. Checked before the @@ -329,6 +331,7 @@ export function withBotProtection any>( threshold, skipLocalAnalysis: config.skipLocalAnalysis, metadata: config.metadata, + violationReporting: { mode }, }); if (!result.allowed && mode === 'enforce') { diff --git a/packages/webdecoy/README.md b/packages/webdecoy/README.md index 1e72a63..f011063 100644 --- a/packages/webdecoy/README.md +++ b/packages/webdecoy/README.md @@ -194,6 +194,12 @@ const wd = new WebDecoy({ A tripwire match is evidence, not proof of intent: link prefetchers, preview bots and your own security scanners can request a hidden or scanner-bait path. Use `dryRun: true` on a rule to observe it before enforcing. +### Rule violation delivery + +Local rules decide the request before the SDK reports their events. With an API key, the SDK sends rule violations to ingest in batches. Rate limits and rule dry runs are violation events. Framework adapters mark monitor-mode violations as dry runs and omit tripwire clearance tokens. An enforced tripwire denial can also appear in Detections. + +For a long-lived SDK instance, call `getViolationDeliveryStats()` for counts of events acknowledged by ingest, failed batches, discarded events, and events waiting for an attempt. Call `await sdk.destroy()` during graceful shutdown to finish an in-flight send and attempt the remaining queue. Reporting has a fixed in-memory buffer. When the client pauses after a failure, unattempted events stay buffered. An attempted batch with an uncertain acknowledgment is discarded to avoid replaying its server-side effects. + ## Fetch runtimes (Bun, Deno, Workers, Astro, SvelteKit, Remix) `createFetchGuard()` wraps the SDK for any runtime that hands you a WHATWG `Request`. It is the same implementation `@webdecoy/hono` uses. diff --git a/packages/webdecoy/src/client.ts b/packages/webdecoy/src/client.ts index 222e94d..c1205f2 100644 --- a/packages/webdecoy/src/client.ts +++ b/packages/webdecoy/src/client.ts @@ -347,14 +347,23 @@ export class WebDecoyClient { * Send violation events to the ingest service */ async sendViolations(events: ViolationEvent[]): Promise { + await this.sendViolationBatch(events); + } + + /** Acknowledgment from ingest for one batch. Transport failures resolve false. */ + async sendViolationBatch(events: ViolationEvent[]): Promise { try { - await this.request('POST', '/api/v1/sdk/violations/batch', { events }); + const { status } = await this.request('POST', '/api/v1/sdk/violations/batch', { events }); + if (status >= 200 && status < 300) return true; + if (this.config.debug) { + console.warn(`[WebDecoy] Violation batch returned HTTP ${status}`); + } } catch (error) { if (this.config.debug) { console.error('[WebDecoy] Failed to send violations:', error); } - // Silently fail — violations are best-effort } + return false; } /** diff --git a/packages/webdecoy/src/fetch-guard.ts b/packages/webdecoy/src/fetch-guard.ts index 84476f5..f249e3c 100644 --- a/packages/webdecoy/src/fetch-guard.ts +++ b/packages/webdecoy/src/fetch-guard.ts @@ -173,6 +173,7 @@ export function createFetchGuard(options: FetchGuardOptions = {}): FetchGuard { threshold: options.threshold, skipLocalAnalysis: options.skipLocalAnalysis, metadata: options.metadata, + violationReporting: { mode }, }); // Monitor mode records the verdict and serves the request anyway. The diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index 71a134b..8eaddac 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -117,6 +117,7 @@ export type { BotVerdict, BotAgent, BotCategory } from './bots'; export { consoleLogger, silentLogger, fromPino } from './logger'; export type { Tracer, Span } from './tracing'; export type { Logger, LogFields } from './logger'; +export type { ViolationDeliveryStats } from './violation-reporter'; // Browser signals, joined to the requests that follow them. See client-signals.ts // for why this is not a threat judgement about a client that sends none. diff --git a/packages/webdecoy/src/sdk.ts b/packages/webdecoy/src/sdk.ts index 0604ad5..0f89ad0 100644 --- a/packages/webdecoy/src/sdk.ts +++ b/packages/webdecoy/src/sdk.ts @@ -8,6 +8,7 @@ import { analyzeRequest } from './local-analysis'; import { RuleEngine } from './rules/rule-engine'; import { tripwire } from './rules'; import { ViolationReporter } from './violation-reporter'; +import type { ViolationDeliveryStats } from './violation-reporter'; import { AIReferralCounter } from './referrals/referral-counter'; import { IPEnrichmentClient } from './ip-enrichment'; import { AgentVerifier } from './agent/verifier'; @@ -23,7 +24,7 @@ import { deriveKey, DEFAULT_CHARACTERISTICS } from './characteristics'; import { DecisionCache } from './decision-cache'; import { classifyUserAgent } from './bots'; import { isTestTriggerUserAgent } from './test-trigger'; -import type { Rule, RuleContext, RuleEngineResult, ViolationEvent } from './rules/types'; +import type { Rule, RuleContext, RuleEngineResult } from './rules/types'; import { WebDecoyConfig, RequestMetadata, @@ -42,6 +43,9 @@ import { hmacSha256Hex, randomHex, timingSafeEqualStr } from './webcrypto'; import { createOffensiveToolchainEvidence } from './offensive-toolchain'; import type { OffensiveToolchainEvidenceInput } from './offensive-toolchain'; +type ConfiguredViolationReporter = Pick & + Partial>; + export class WebDecoy { private client: WebDecoyClient | null; private config: Omit< @@ -53,7 +57,7 @@ export class WebDecoy { }; private ruleEngine: RuleEngine | null; private referralCounter: AIReferralCounter | null = null; - private violationReporter: { report(violations: ViolationEvent[]): void; flush(): Promise; destroy(): Promise } | null = null; + private violationReporter: ConfiguredViolationReporter | null = null; private ipEnrichmentClient: IPEnrichmentClient | null = null; private _hasFilterRules = false; private _hasAgentRules = false; @@ -280,7 +284,10 @@ export class WebDecoy { } /** Evaluate rules against a prepared context and report any violations. */ - private runRules(context: RuleContext): RuleEngineResult | null { + private runRules( + context: RuleContext, + reporting?: ProtectOptions['violationReporting'], + ): RuleEngineResult | null { if (!this.ruleEngine) return null; const span = startSpan(this.tracer, 'webdecoy.rules'); @@ -291,8 +298,21 @@ export class WebDecoy { if (result.rule) setAttribute(span, 'webdecoy.rules.deciding', result.rule); endSpan(span); - if (result.violations.length > 0 && this.violationReporter) { - this.violationReporter.report(result.violations); + const reporter = this.violationReporter; + if (reporter && result.violations.length > 0) { + const violations = reporting?.mode === 'monitor' + ? result.violations.map((event) => ({ ...event, dryRun: true, clearance: undefined })) + : result.violations; + reporter.report(violations); + + if (reporting?.waitUntil) { + const delivery = Promise.resolve().then(() => reporter.flush()).catch(() => undefined); + try { + reporting.waitUntil(delivery); + } catch { + // A lifecycle hook failure must not alter the request decision. + } + } } return result; } @@ -559,7 +579,7 @@ export class WebDecoy { key = context.key ?? key; const agentVerdict: AgentVerdict | undefined = context.agent; const ruleResult: RuleEngineResult | null = this.ruleEngine - ? this.runRules(context) + ? this.runRules(context, options.violationReporting) : null; // Rules denied or throttled: decided locally, no API call. Not cached — @@ -832,10 +852,15 @@ export class WebDecoy { * Attach a violation reporter for sending violations to the backend. * Called internally when apiKey is present and rules are configured. */ - setViolationReporter(reporter: { report(violations: ViolationEvent[]): void; flush(): Promise; destroy(): Promise }): void { + setViolationReporter(reporter: ConfiguredViolationReporter): void { this.violationReporter = reporter; } + /** Snapshot of this instance's violation delivery, when reporting is enabled. */ + getViolationDeliveryStats(): ViolationDeliveryStats | undefined { + return this.violationReporter?.getDeliveryStats?.(); + } + /** * Get the API client (for use by violation reporter, enrichment, etc.) */ diff --git a/packages/webdecoy/src/types.ts b/packages/webdecoy/src/types.ts index c60e938..e2567cc 100644 --- a/packages/webdecoy/src/types.ts +++ b/packages/webdecoy/src/types.ts @@ -396,4 +396,10 @@ export interface ProtectOptions { /** Additional metadata to include in the detection */ metadata?: Record; + + /** How the caller handles local violations and keeps a background report alive. */ + violationReporting?: { + mode: 'monitor' | 'enforce'; + waitUntil?: (delivery: Promise) => void; + }; } diff --git a/packages/webdecoy/src/violation-reporter.test.ts b/packages/webdecoy/src/violation-reporter.test.ts new file mode 100644 index 0000000..b9aa00e --- /dev/null +++ b/packages/webdecoy/src/violation-reporter.test.ts @@ -0,0 +1,143 @@ +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { WebDecoyClient } from './client'; +import { WebDecoy } from './sdk'; +import { tripwire } from './rules'; +import type { ViolationEvent } from './rules/types'; +import { ViolationReporter } from './violation-reporter'; + +let apiUrl: string; +let status: number; +let batches: ViolationEvent[][]; +const server = createServer(async (request, response) => { + if (request.method !== 'POST' || request.url !== '/api/v1/sdk/violations/batch') { + response.writeHead(404).end(); + return; + } + request.setEncoding('utf8'); + let body = ''; + for await (const chunk of request) body += chunk; + batches.push(JSON.parse(body).events); + response.writeHead(status).end(); +}); + +beforeAll(async () => { + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +beforeEach(() => { + status = 201; + batches = []; +}); + +afterAll(async () => { + await new Promise((resolve, reject) => { + server.close((error) => error ? reject(error) : resolve()); + server.closeIdleConnections(); + }); +}); + +test('drains a locally decided violation and exposes the ingest acknowledgment', async () => { + const sdk = new WebDecoy({ + apiKey: 'sk_test_delivery_fixture', + apiUrl, + countAIReferrals: false, + rules: [tripwire({ paths: ['/fixture-path'], includeDefaults: false })], + }); + + try { + const decision = await sdk.protect({ + ip: '192.0.2.5', path: '/fixture-path', method: 'GET', headers: {}, timestamp: Date.now(), + }); + expect(decision.deniedBy('tripwire')).toBe(true); + expect(sdk.getViolationDeliveryStats()).toMatchObject({ bufferedEvents: 1, acknowledgedEvents: 0 }); + } finally { + await sdk.destroy(); + } + + expect(batches).toHaveLength(1); + expect(batches[0]).toEqual([expect.objectContaining({ rule: 'tripwire', action: 'DENY', path: '/fixture-path' })]); + expect(sdk.getViolationDeliveryStats()).toEqual({ + acknowledgedEvents: 1, + failedBatches: 0, + droppedEvents: 0, + bufferedEvents: 0, + }); +}); + +test('counts a refused batch once and keeps unattempted events for a later flush', async () => { + const client = new WebDecoyClient({ + apiUrl, apiKey: 'sk_test_delivery_fixture', debug: false, timeout: 1_000, tlsRejectUnauthorized: true, + }); + const reporter = new ViolationReporter(client); + const events: ViolationEvent[] = Array.from({ length: 105 }, (_, index) => ({ + rule: 'rateLimit', action: 'THROTTLE', ip: '192.0.2.5', path: `/fixture/${index}`, + dryRun: false, timestamp: new Date().toISOString(), + })); + + try { + status = 503; + reporter.report(events); + await Promise.all([reporter.flush(), reporter.flush()]); + expect(batches).toEqual([events.slice(0, 100)]); + expect(reporter.getDeliveryStats()).toEqual({ + acknowledgedEvents: 0, + failedBatches: 1, + droppedEvents: 100, + bufferedEvents: 5, + }); + + status = 201; + const clock = jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 2_000); + try { + await reporter.flush(); + } finally { + clock.mockRestore(); + } + expect(batches).toEqual([events.slice(0, 100), events.slice(100)]); + expect(reporter.getDeliveryStats()).toEqual({ + acknowledgedEvents: 5, + failedBatches: 1, + droppedEvents: 100, + bufferedEvents: 0, + }); + } finally { + await reporter.destroy(); + } +}); + +test('a flush scheduled during an active send acknowledges the newly queued event', async () => { + const client = new WebDecoyClient({ + apiUrl, apiKey: 'sk_test_delivery_fixture', debug: false, timeout: 1_000, tlsRejectUnauthorized: true, + }); + const reporter = new ViolationReporter(client); + let finishFirst!: (acknowledged: boolean) => void; + const firstAck = new Promise((resolve) => { finishFirst = resolve; }); + const send = jest.spyOn(client, 'sendViolationBatch') + .mockReturnValueOnce(firstAck) + .mockResolvedValue(true); + const first: ViolationEvent = { + rule: 'rateLimit', action: 'THROTTLE', ip: '192.0.2.5', path: '/first', + dryRun: false, timestamp: new Date().toISOString(), + }; + const second = { ...first, path: '/second' }; + + try { + reporter.report([first]); + const activeFlush = reporter.flush(); + await Promise.resolve(); + expect(send).toHaveBeenCalledTimes(1); + + reporter.report([second]); + const pendingFlush = reporter.flush(); + finishFirst(true); + await Promise.all([activeFlush, pendingFlush]); + + expect(send.mock.calls).toEqual([[[first]], [[second]]]); + expect(reporter.getDeliveryStats()).toMatchObject({ acknowledgedEvents: 2, bufferedEvents: 0 }); + } finally { + finishFirst(true); + await reporter.destroy(); + } +}); diff --git a/packages/webdecoy/src/violation-reporter.ts b/packages/webdecoy/src/violation-reporter.ts index 68a232e..309c070 100644 --- a/packages/webdecoy/src/violation-reporter.ts +++ b/packages/webdecoy/src/violation-reporter.ts @@ -21,13 +21,29 @@ export interface ViolationReporterConfig { */ export const MAX_BUFFERED_VIOLATIONS = 1_000; +/** Delivery counters for this SDK instance. */ +export interface ViolationDeliveryStats { + /** Events in batches acknowledged by ingest. */ + acknowledgedEvents: number; + /** HTTP or transport failures for attempted batches. */ + failedBatches: number; + /** Events discarded after failure, overflow, or shutdown. */ + droppedEvents: number; + /** Events waiting for an attempt. */ + bufferedEvents: number; +} + export class ViolationReporter { private client: WebDecoyClient; private buffer: ViolationEvent[] = []; private flushTimer: ReturnType; private maxBufferSize: number; private debug: boolean; - private flushing = false; + private flushPromise: Promise | undefined; + private queuedFlush: Promise | undefined; + private acknowledgedEvents = 0; + private failedBatches = 0; + private droppedEvents = 0; constructor(client: WebDecoyClient, config: ViolationReporterConfig = {}) { this.client = client; @@ -50,7 +66,9 @@ export class ViolationReporter { report(violations: ViolationEvent[]): void { this.buffer.push(...violations); if (this.buffer.length > MAX_BUFFERED_VIOLATIONS) { - this.buffer.splice(0, this.buffer.length - MAX_BUFFERED_VIOLATIONS); + const overflow = this.buffer.length - MAX_BUFFERED_VIOLATIONS; + this.buffer.splice(0, overflow); + this.droppedEvents += overflow; } if (this.buffer.length >= this.maxBufferSize) { @@ -59,43 +77,61 @@ export class ViolationReporter { } } - /** - * Flush buffered violations to the backend - */ - async flush(): Promise { - // While the client is paused, hold the buffer (capped above) rather than - // drain it into requests that cannot be made. - if (this.flushing || this.buffer.length === 0 || !this.client.isAvailable()) return; - this.flushing = true; - - // Drain the buffer - const events = this.buffer.splice(0, this.buffer.length); + /** Flush the buffer, coalescing requests that arrive during an active send. */ + flush(): Promise { + if (this.queuedFlush) return this.queuedFlush; + if (this.flushPromise) { + if (this.buffer.length === 0 || !this.client.isAvailable()) return this.flushPromise; + this.queuedFlush = this.flushPromise.then(() => { + this.queuedFlush = undefined; + return this.flush(); + }); + return this.queuedFlush; + } + if (this.buffer.length === 0 || !this.client.isAvailable()) return Promise.resolve(); - try { - // Split into batches of 100 (API limit) - for (let i = 0; i < events.length; i += 100) { - const batch = events.slice(i, i + 100); - await this.client.sendViolations(batch); + const size = this.buffer.length; + this.flushPromise = Promise.resolve() + .then(() => this.flushBatches(size)) + .finally(() => { this.flushPromise = undefined; }); + return this.flushPromise; + } + private async flushBatches(remaining: number): Promise { + // Keep unattempted events buffered when an HTTP or transport failure pauses + // the client. Each request respects the ingest limit of 100 events. + while (remaining > 0 && this.buffer.length > 0 && this.client.isAvailable()) { + const batch = this.buffer.splice(0, Math.min(100, remaining)); + remaining -= batch.length; + if (await this.client.sendViolationBatch(batch)) { + this.acknowledgedEvents += batch.length; if (this.debug) { console.log(`[WebDecoy] Flushed ${batch.length} violation events`); } + } else { + // A failed response can follow a successful server write. Replaying + // an attempted batch would duplicate violations and tripwire effects. + this.failedBatches++; + this.droppedEvents += batch.length; } - } catch (error) { - if (this.debug) { - console.error('[WebDecoy] Failed to flush violations:', error); - } - // Violations are dropped on failure — no retry, no user impact - } finally { - this.flushing = false; } } - /** - * Flush remaining events and stop the timer - */ + getDeliveryStats(): ViolationDeliveryStats { + return { + acknowledgedEvents: this.acknowledgedEvents, + failedBatches: this.failedBatches, + droppedEvents: this.droppedEvents, + bufferedEvents: this.buffer.length, + }; + } + + /** Stop the timer and give remaining events one final flush. */ async destroy(): Promise { clearInterval(this.flushTimer); + if (this.flushPromise) await this.flushPromise; await this.flush(); + this.droppedEvents += this.buffer.length; + this.buffer.length = 0; } }