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
1 change: 1 addition & 0 deletions packages/express/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@
threshold: config.threshold,
skipLocalAnalysis: config.skipLocalAnalysis,
metadata: config.metadata,
violationReporting: { mode },
});

// Honeytoken injection.
Expand Down Expand Up @@ -284,13 +285,13 @@
return intercepting;
};

(res as any).write = function (chunk: any, ...rest: any[]): boolean {

Check warning on line 288 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

Check warning on line 288 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

Check warning on line 288 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

Check warning on line 288 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type

Check warning on line 288 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type

Check warning on line 288 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type
if (!shouldIntercept()) return originalWrite(chunk, ...rest);
if (chunk) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
return true;
};

(res as any).end = function (chunk: any, ...rest: any[]): any {

Check warning on line 294 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

Check warning on line 294 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

Check warning on line 294 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

Check warning on line 294 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

Check warning on line 294 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type

Check warning on line 294 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type

Check warning on line 294 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type

Check warning on line 294 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type
try {
if (!shouldIntercept()) return originalEnd(chunk, ...rest);
if (chunk && typeof chunk !== 'function') {
Expand Down Expand Up @@ -325,8 +326,8 @@
// name in every adapter, which `webdecoy` cannot.
req.webdecoy = result.detection;
req.webdecoyDecision = result;
(req as any).webdecoyEdge = result.edge;

Check warning on line 329 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

Check warning on line 329 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type
(req as any).webdecoyWouldBlock = !result.allowed;

Check warning on line 330 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type
return next();
}

Expand Down Expand Up @@ -354,7 +355,7 @@
// req.webdecoyEdge.isScript instead of string-matching x-wd-class, and
// `present: false` tells it the edge was never in front of this request —
// which is no information, not a clean bill of health.
(req as any).webdecoyEdge = result.edge;

Check warning on line 358 in packages/express/src/middleware.ts

View workflow job for this annotation

GitHub Actions / Build (20)

Unexpected any. Specify a different type
return next();
} else {
// Block the request
Expand Down
1 change: 1 addition & 0 deletions packages/fastify/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
35 changes: 35 additions & 0 deletions packages/nextjs/src/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NextRequest } from 'next/server';
import { tripwire } from '@webdecoy/node';
import { withWebDecoy } from './middleware';
import { getEdgeVerdict } from './edge-verdict';

Expand Down Expand Up @@ -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<void, [Promise<void>]>();
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();
}
});
});
7 changes: 5 additions & 2 deletions packages/nextjs/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/

import { NextRequest, NextResponse } from 'next/server';
import type { NextFetchEvent } from 'next/server';
import {
WebDecoy,
WebDecoyConfig,
Expand Down Expand Up @@ -153,7 +154,7 @@
*/
export function withWebDecoy(
config: WebDecoyConfig & WebDecoyMiddlewareOptions
): (req: NextRequest) => Promise<NextResponse> {
): (req: NextRequest, event?: Pick<NextFetchEvent, 'waitUntil'>) => Promise<NextResponse> {
const sdk = new WebDecoy(config);

const getIP = config.getIP || ((req: NextRequest) => resolveIP(req, config.trustProxy));
Expand All @@ -162,7 +163,7 @@
const onError = config.onError || defaultOnError;
const skipPaths = config.skipPaths;

return async (req: NextRequest): Promise<NextResponse> => {
return async (req, event): Promise<NextResponse> => {
try {
const pathname = req.nextUrl.pathname;

Expand Down Expand Up @@ -194,6 +195,7 @@
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
Expand Down Expand Up @@ -290,7 +292,7 @@
* });
* ```
*/
export function withBotProtection<T extends (...args: any[]) => any>(

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

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type

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

View workflow job for this annotation

GitHub Actions / Build (22)

Unexpected any. Specify a different type
handler: T,
config: WebDecoyConfig & WithBotProtectionOptions
): T {
Expand Down Expand Up @@ -329,6 +331,7 @@
threshold,
skipLocalAnalysis: config.skipLocalAnalysis,
metadata: config.metadata,
violationReporting: { mode },
});

if (!result.allowed && mode === 'enforce') {
Expand Down
6 changes: 6 additions & 0 deletions packages/webdecoy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 11 additions & 2 deletions packages/webdecoy/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,14 +347,23 @@ export class WebDecoyClient {
* Send violation events to the ingest service
*/
async sendViolations(events: ViolationEvent[]): Promise<void> {
await this.sendViolationBatch(events);
}

/** Acknowledgment from ingest for one batch. Transport failures resolve false. */
async sendViolationBatch(events: ViolationEvent[]): Promise<boolean> {
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;
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/webdecoy/src/fetch-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
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 @@ -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.
Expand Down
39 changes: 32 additions & 7 deletions packages/webdecoy/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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,
Expand All @@ -42,6 +43,9 @@ import { hmacSha256Hex, randomHex, timingSafeEqualStr } from './webcrypto';
import { createOffensiveToolchainEvidence } from './offensive-toolchain';
import type { OffensiveToolchainEvidenceInput } from './offensive-toolchain';

type ConfiguredViolationReporter = Pick<ViolationReporter, 'report' | 'flush' | 'destroy'> &
Partial<Pick<ViolationReporter, 'getDeliveryStats'>>;

export class WebDecoy {
private client: WebDecoyClient | null;
private config: Omit<
Expand All @@ -53,7 +57,7 @@ export class WebDecoy {
};
private ruleEngine: RuleEngine | null;
private referralCounter: AIReferralCounter | null = null;
private violationReporter: { report(violations: ViolationEvent[]): void; flush(): Promise<void>; destroy(): Promise<void> } | null = null;
private violationReporter: ConfiguredViolationReporter | null = null;
private ipEnrichmentClient: IPEnrichmentClient | null = null;
private _hasFilterRules = false;
private _hasAgentRules = false;
Expand Down Expand Up @@ -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');
Expand All @@ -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;
}
Expand Down Expand Up @@ -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 —
Expand Down Expand Up @@ -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<void>; destroy(): Promise<void> }): 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.)
*/
Expand Down
6 changes: 6 additions & 0 deletions packages/webdecoy/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,4 +396,10 @@ export interface ProtectOptions {

/** Additional metadata to include in the detection */
metadata?: Record<string, any>;

/** How the caller handles local violations and keeps a background report alive. */
violationReporting?: {
mode: 'monitor' | 'enforce';
waitUntil?: (delivery: Promise<void>) => void;
};
}
Loading