@webdecoy/node 0.21.2 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,11 @@
1
+ import {
2
+ WebDecoy,
3
+ injectHoneytokenLink,
4
+ isInjectableHtml,
5
+ siteHoneytoken,
6
+ tripwire
7
+ } from "./chunk-FL7FXNYV.mjs";
8
+
1
9
  // src/client-ip.ts
2
10
  var IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
3
11
  function ipv4ToBytes(ip) {
@@ -1358,11 +1366,223 @@ function createClearanceGate(options = {}) {
1358
1366
  };
1359
1367
  }
1360
1368
 
1369
+ // src/adapter-core.ts
1370
+ function shouldSkipPath(path, patterns) {
1371
+ if (!patterns || patterns.length === 0) return false;
1372
+ return patterns.some(
1373
+ (pattern) => typeof pattern === "string" ? path === pattern || path.startsWith(pattern) : pattern.test(path)
1374
+ );
1375
+ }
1376
+ function ruleBlockResponse(decision) {
1377
+ const rr2 = decision.ruleResult;
1378
+ if (decision.allowed || !rr2) return null;
1379
+ if (rr2.action === "THROTTLE") {
1380
+ const retryAfter = Number(rr2.metadata?.retryAfter ?? 60);
1381
+ return {
1382
+ status: 429,
1383
+ headers: { "Retry-After": String(retryAfter) },
1384
+ body: {
1385
+ error: "Too Many Requests",
1386
+ message: rr2.reason || "Rate limit exceeded",
1387
+ retry_after: retryAfter
1388
+ }
1389
+ };
1390
+ }
1391
+ if (rr2.action === "DENY") {
1392
+ return {
1393
+ status: 403,
1394
+ headers: {},
1395
+ body: {
1396
+ error: "Forbidden",
1397
+ message: rr2.reason || "Access denied by rule",
1398
+ rule: rr2.rule
1399
+ }
1400
+ };
1401
+ }
1402
+ return null;
1403
+ }
1404
+ function armSiteHoneytoken(sdk, options) {
1405
+ let token = null;
1406
+ void deriveAndArm(sdk, options).then((t) => {
1407
+ token = t;
1408
+ });
1409
+ return () => token;
1410
+ }
1411
+ async function deriveAndArm(sdk, options) {
1412
+ const enabled = (options.enabled ?? true) && Boolean(options.apiKey);
1413
+ if (!enabled) return null;
1414
+ try {
1415
+ const token = await siteHoneytoken({ secret: options.apiKey });
1416
+ sdk.addRule(tripwire({ paths: token.activePaths, includeDefaults: false }));
1417
+ return token;
1418
+ } catch (error) {
1419
+ options.onError?.(error);
1420
+ return null;
1421
+ }
1422
+ }
1423
+
1424
+ // src/fetch-guard.ts
1425
+ function defaultBlocked(_request, decision) {
1426
+ const block = ruleBlockResponse(decision) ?? {
1427
+ status: 403,
1428
+ headers: {},
1429
+ body: { error: "Forbidden", message: "Access denied by Web Decoy protection" }
1430
+ };
1431
+ return new Response(JSON.stringify({ ...block.body, detection_id: decision.id }), {
1432
+ status: block.status,
1433
+ headers: { "content-type": "application/json", ...block.headers }
1434
+ });
1435
+ }
1436
+ function headerRecord(headers) {
1437
+ const out = {};
1438
+ headers.forEach((value, key) => {
1439
+ out[key.toLowerCase()] = value;
1440
+ });
1441
+ return out;
1442
+ }
1443
+ function createFetchGuard(options = {}) {
1444
+ const sdk = new WebDecoy(options);
1445
+ const mode = options.mode ?? "monitor";
1446
+ const onBlocked = options.onBlocked ?? defaultBlocked;
1447
+ const getToken = armSiteHoneytoken(sdk, {
1448
+ apiKey: options.apiKey,
1449
+ enabled: options.honeytoken
1450
+ });
1451
+ function resolveIP(request, peer) {
1452
+ if (options.getIP) return options.getIP(request);
1453
+ return resolveClientIp({
1454
+ headers: request.headers,
1455
+ peer,
1456
+ trustProxy: options.trustProxy ?? 1
1457
+ }) ?? normalizeIp(peer) ?? "127.0.0.1";
1458
+ }
1459
+ return {
1460
+ sdk,
1461
+ skips(pathname) {
1462
+ return shouldSkipPath(pathname, options.skipPaths);
1463
+ },
1464
+ async check(request, peer) {
1465
+ const url = new URL(request.url);
1466
+ const metadata = {
1467
+ method: request.method,
1468
+ path: url.pathname,
1469
+ ip: resolveIP(request, peer),
1470
+ user_agent: request.headers.get("user-agent") ?? void 0,
1471
+ headers: headerRecord(request.headers),
1472
+ query: url.search ? url.search.slice(1) : void 0,
1473
+ timestamp: Date.now()
1474
+ };
1475
+ const decision = await sdk.protect(metadata, {
1476
+ threshold: options.threshold,
1477
+ skipLocalAnalysis: options.skipLocalAnalysis,
1478
+ metadata: options.metadata
1479
+ });
1480
+ if (decision.allowed || mode !== "enforce") return { decision };
1481
+ return { decision, response: await onBlocked(request, decision) };
1482
+ },
1483
+ async decorate(response) {
1484
+ const current = getToken();
1485
+ if (!current) return response;
1486
+ if (!isInjectableHtml(response.headers.get("content-type"))) return response;
1487
+ if (response.bodyUsed) return response;
1488
+ try {
1489
+ const html = await response.text();
1490
+ const injected = injectHoneytokenLink(html, current.linkHtml);
1491
+ if (injected === html) return new Response(html, response);
1492
+ const headers = new Headers(response.headers);
1493
+ headers.delete("content-length");
1494
+ return new Response(injected, {
1495
+ status: response.status,
1496
+ statusText: response.statusText,
1497
+ headers
1498
+ });
1499
+ } catch {
1500
+ return response;
1501
+ }
1502
+ }
1503
+ };
1504
+ }
1505
+
1506
+ // src/detect-and-gate.ts
1507
+ var DECISION_HEADER = "x-webdecoy-decision";
1508
+ var DETECTION_ID_HEADER = "x-webdecoy-detection-id";
1509
+ var WOULD_BLOCK_HEADER = "x-webdecoy-would-block";
1510
+ var warnedBadKey = false;
1511
+ function createDetectAndGate(options = {}) {
1512
+ const gate = createClearanceGate(options);
1513
+ const trustProxy = options.trustProxy ?? 1;
1514
+ let guard = null;
1515
+ let guardKey = "";
1516
+ let failedKey = "";
1517
+ function guardFor(apiKey) {
1518
+ if (guard && guardKey === apiKey) return guard;
1519
+ if (failedKey === apiKey) return null;
1520
+ try {
1521
+ guard = createFetchGuard({ ...options, apiKey, trustProxy, honeytoken: false, mode: options.mode ?? "monitor" });
1522
+ guardKey = apiKey;
1523
+ return guard;
1524
+ } catch (error) {
1525
+ failedKey = apiKey;
1526
+ if (!warnedBadKey) {
1527
+ warnedBadKey = true;
1528
+ console.warn(
1529
+ `[WebDecoy] detection is off: ${error instanceof Error ? error.message : "the API key was rejected"}`
1530
+ );
1531
+ }
1532
+ return null;
1533
+ }
1534
+ }
1535
+ async function detect(request, apiKey) {
1536
+ try {
1537
+ const g = guardFor(apiKey);
1538
+ if (!g) return null;
1539
+ if (shouldSkipPath(new URL(request.url).pathname, options.skipPaths)) return null;
1540
+ return await g.check(request);
1541
+ } catch {
1542
+ return null;
1543
+ }
1544
+ }
1545
+ async function runGate(request, context) {
1546
+ try {
1547
+ return await gate(request, context);
1548
+ } catch {
1549
+ return { action: "continue", headers: null, verdict: null };
1550
+ }
1551
+ }
1552
+ return async (request, context) => {
1553
+ const apiKey = (options.apiKey ?? fromEnv("WEBDECOY_API_KEY")).trim();
1554
+ if (!apiKey) return { outcome: await runGate(request, context), decision: null };
1555
+ const [guarded, gated] = await Promise.all([detect(request, apiKey), runGate(request, context)]);
1556
+ if (!guarded) return { outcome: gated, decision: null };
1557
+ const { decision, response } = guarded;
1558
+ if (response) return { outcome: { action: "respond", response }, decision };
1559
+ if (gated.action === "respond") return { outcome: gated, decision };
1560
+ try {
1561
+ const headers = gated.headers ? new Headers(gated.headers) : tt(request);
1562
+ headers.delete(DECISION_HEADER);
1563
+ headers.delete(DETECTION_ID_HEADER);
1564
+ headers.delete(WOULD_BLOCK_HEADER);
1565
+ headers.set(DECISION_HEADER, decision.detection?.decision ?? "");
1566
+ headers.set(DETECTION_ID_HEADER, decision.detection?.detection_id ?? "");
1567
+ headers.set(WOULD_BLOCK_HEADER, String(!decision.allowed));
1568
+ return { outcome: { action: "continue", headers, verdict: gated.verdict }, decision };
1569
+ } catch {
1570
+ return { outcome: gated, decision };
1571
+ }
1572
+ };
1573
+ }
1574
+
1361
1575
  export {
1362
1576
  normalizeIp,
1363
1577
  ipInCidr,
1364
1578
  resolveClientIp,
1365
1579
  ne,
1366
1580
  resolveGateEnv,
1367
- createClearanceGate
1581
+ createClearanceGate,
1582
+ shouldSkipPath,
1583
+ ruleBlockResponse,
1584
+ armSiteHoneytoken,
1585
+ deriveAndArm,
1586
+ createFetchGuard,
1587
+ createDetectAndGate
1368
1588
  };
@@ -1,3 +1,5 @@
1
+ import { Z as WebDecoyConfig, G as ProtectOptions, r as Decision, W as WebDecoy } from './sdk-B8M-WYTc.mjs';
2
+
1
3
  /**
2
4
  * Resolving the client IP address behind a proxy.
3
5
  *
@@ -165,4 +167,147 @@ declare function resolveGateEnv(options?: ClearanceGateOptions): GateEnv | null;
165
167
  */
166
168
  declare function createClearanceGate(options?: ClearanceGateOptions): (request: Request, context?: ClearanceContext) => Promise<GateOutcome>;
167
169
 
168
- export { BUILD as B, type ClearanceContext as C, type GateEnv as G, type HeaderSource as H, type ResolveClientIpOptions as R, type TrustedProxies as T, type ClearanceGateOptions as a, type GateOutcome as b, createClearanceGate as c, resolveGateEnv as d, ipInCidr as i, normalizeIp as n, resolveClientIp as r };
170
+ /**
171
+ * One adapter, for every runtime that speaks `Request` and `Response`.
172
+ *
173
+ * WHY THIS EXISTS
174
+ *
175
+ * Express, Fastify and Next.js each grew their own copy of the same middleware:
176
+ * skip-path matching, monitor-versus-enforce, honeytoken arming, the 429 with a
177
+ * `Retry-After`, fail-open error handling. Three copies of a decision tree is
178
+ * three places for the branch that matters to be subtly different — and it
179
+ * already had been, which is how the leftmost-`X-Forwarded-For` bug survived in
180
+ * two adapters after the WordPress plugin fixed it.
181
+ *
182
+ * It is also the answer to "which framework do you support?". Hono, Bun, Deno,
183
+ * Astro, Nitro, SvelteKit and Remix all hand you a WHATWG `Request` and want a
184
+ * `Response` back. Written once here, each of those is a translation layer thin
185
+ * enough not to need a package — see the README recipe — and `@webdecoy/hono` is
186
+ * the one that does, because Hono has a middleware contract worth fitting.
187
+ *
188
+ * No `node:` imports: this is the code path that has to run on Workers.
189
+ */
190
+
191
+ interface FetchGuardOptions extends WebDecoyConfig, ProtectOptions {
192
+ /**
193
+ * Whether a blocking verdict actually blocks. Defaults to `'monitor'`.
194
+ *
195
+ * Nobody adopts a defence by having it break their site on the first install.
196
+ * Watch what it would have done, then switch.
197
+ */
198
+ mode?: 'monitor' | 'enforce';
199
+ /** Paths to skip entirely — health checks, static assets. */
200
+ skipPaths?: (string | RegExp)[];
201
+ /**
202
+ * How much of the `X-Forwarded-For` chain to believe. Defaults to `1` trusted
203
+ * hop: a fetch handler has no socket to fall back on, so there is no
204
+ * believe-nothing default available. See `resolveClientIp`.
205
+ */
206
+ trustProxy?: TrustedProxies;
207
+ /** Override IP resolution entirely. */
208
+ getIP?: (request: Request) => string;
209
+ /**
210
+ * Inject a hidden honeytoken link into HTML responses, and arm the tripwire it
211
+ * points at. Defaults to on when an `apiKey` is present.
212
+ */
213
+ honeytoken?: boolean;
214
+ /** Build the blocking response. Defaults to 403, or 429 for a throttle. */
215
+ onBlocked?: (request: Request, decision: Decision) => Response | Promise<Response>;
216
+ }
217
+ interface GuardOutcome {
218
+ /** What the SDK concluded. Always present, in both modes. */
219
+ decision: Decision;
220
+ /**
221
+ * The response to return instead of calling the handler, or undefined to
222
+ * carry on. Undefined in monitor mode even when the decision is a denial.
223
+ */
224
+ response?: Response;
225
+ }
226
+ interface FetchGuard {
227
+ /** Evaluate one request. */
228
+ check(request: Request, peer?: string): Promise<GuardOutcome>;
229
+ /**
230
+ * Rewrite an HTML response to carry the honeytoken link. Returns the response
231
+ * unchanged when there is no token yet, or the body is not injectable HTML.
232
+ */
233
+ decorate(response: Response): Promise<Response>;
234
+ /** Whether this path is skipped. */
235
+ skips(pathname: string): boolean;
236
+ /** The underlying SDK, for `detectBot()` and friends. */
237
+ sdk: WebDecoy;
238
+ }
239
+ /**
240
+ * A guard over WHATWG `Request`/`Response`.
241
+ *
242
+ * ```ts
243
+ * const guard = createFetchGuard({ rules: [tripwire()] });
244
+ *
245
+ * export default {
246
+ * async fetch(request) {
247
+ * const { response } = await guard.check(request);
248
+ * if (response) return response;
249
+ * return guard.decorate(await handle(request));
250
+ * },
251
+ * };
252
+ * ```
253
+ */
254
+ declare function createFetchGuard(options?: FetchGuardOptions): FetchGuard;
255
+
256
+ /**
257
+ * Detection and the clearance gate, in one middleware.
258
+ *
259
+ * A site on Vercel has one middleware file. Detection (what is this client,
260
+ * report it) and the clearance gate (does this protected page need a token)
261
+ * used to be two separate middlewares with two sets of credentials, so a site
262
+ * had to pick one or hand-write a chain. This runs both, for one request, and
263
+ * returns one outcome:
264
+ *
265
+ * - Detection runs when an API key is configured (`apiKey`, else
266
+ * `WEBDECOY_API_KEY`). It reports the reserved test trigger
267
+ * (`curl -A "WebDecoy-Test/1.0"`), tripwire hits and clients that look like
268
+ * bots, including every agent the bot registry names.
269
+ * - The gate runs when the site's identity is configured (`siteKey`,
270
+ * `scannerId`, `sensorKey`, else the WEBDECOY_* variables), exactly as
271
+ * `createClearanceGate()` does on its own.
272
+ *
273
+ * Without an API key this is the gate alone, unchanged. Without either, every
274
+ * request passes. Nothing here throws: a failure in detection or the gate lets
275
+ * the request through.
276
+ *
277
+ * Both halves resolve the client IP the same way and see the same path, so a
278
+ * request the gate refuses (or would refuse, in monitor mode) and the
279
+ * detection reported for it describe the same client.
280
+ */
281
+
282
+ interface DetectAndGateOptions extends ClearanceGateOptions, Omit<FetchGuardOptions, 'getIP' | 'honeytoken' | 'trustProxy'> {
283
+ /**
284
+ * The WebDecoy API key. `WEBDECOY_API_KEY` by default. A secret: set it in the
285
+ * platform's environment, never in code. Without one, no detection runs and
286
+ * this is the clearance gate alone.
287
+ */
288
+ apiKey?: string;
289
+ /**
290
+ * What a blocking detection verdict does. Defaults to `'monitor'`: the
291
+ * request is served and the verdict rides on the request headers
292
+ * (`x-webdecoy-decision`, `x-webdecoy-detection-id`, `x-webdecoy-would-block`).
293
+ * `'enforce'` answers a blocked request with 403 (or 429 for a rate limit).
294
+ *
295
+ * This is detection's mode only. Whether the clearance gate monitors or
296
+ * enforces is set per site in WebDecoy.
297
+ */
298
+ mode?: 'monitor' | 'enforce';
299
+ }
300
+ /** Detection's verdict on a request, when detection ran. */
301
+ interface DetectAndGateOutcome {
302
+ /** What to do with the request. Same shape as the gate's outcome. */
303
+ outcome: GateOutcome;
304
+ /** The detection decision, or null when detection did not run or failed. */
305
+ decision: Decision | null;
306
+ }
307
+ /**
308
+ * Detection then the clearance gate, bound to one site: call it with each
309
+ * request. Options default to the environment.
310
+ */
311
+ declare function createDetectAndGate(options?: DetectAndGateOptions): (request: Request, context?: ClearanceContext) => Promise<DetectAndGateOutcome>;
312
+
313
+ export { BUILD as B, type ClearanceContext as C, type DetectAndGateOptions as D, type FetchGuard as F, type GateEnv as G, type HeaderSource as H, type ResolveClientIpOptions as R, type TrustedProxies as T, type ClearanceGateOptions as a, type DetectAndGateOutcome as b, type FetchGuardOptions as c, type GateOutcome as d, type GuardOutcome as e, createClearanceGate as f, createDetectAndGate as g, createFetchGuard as h, ipInCidr as i, resolveGateEnv as j, normalizeIp as n, resolveClientIp as r };
@@ -1,3 +1,5 @@
1
+ import { Z as WebDecoyConfig, G as ProtectOptions, r as Decision, W as WebDecoy } from './sdk-B8M-WYTc.js';
2
+
1
3
  /**
2
4
  * Resolving the client IP address behind a proxy.
3
5
  *
@@ -165,4 +167,147 @@ declare function resolveGateEnv(options?: ClearanceGateOptions): GateEnv | null;
165
167
  */
166
168
  declare function createClearanceGate(options?: ClearanceGateOptions): (request: Request, context?: ClearanceContext) => Promise<GateOutcome>;
167
169
 
168
- export { BUILD as B, type ClearanceContext as C, type GateEnv as G, type HeaderSource as H, type ResolveClientIpOptions as R, type TrustedProxies as T, type ClearanceGateOptions as a, type GateOutcome as b, createClearanceGate as c, resolveGateEnv as d, ipInCidr as i, normalizeIp as n, resolveClientIp as r };
170
+ /**
171
+ * One adapter, for every runtime that speaks `Request` and `Response`.
172
+ *
173
+ * WHY THIS EXISTS
174
+ *
175
+ * Express, Fastify and Next.js each grew their own copy of the same middleware:
176
+ * skip-path matching, monitor-versus-enforce, honeytoken arming, the 429 with a
177
+ * `Retry-After`, fail-open error handling. Three copies of a decision tree is
178
+ * three places for the branch that matters to be subtly different — and it
179
+ * already had been, which is how the leftmost-`X-Forwarded-For` bug survived in
180
+ * two adapters after the WordPress plugin fixed it.
181
+ *
182
+ * It is also the answer to "which framework do you support?". Hono, Bun, Deno,
183
+ * Astro, Nitro, SvelteKit and Remix all hand you a WHATWG `Request` and want a
184
+ * `Response` back. Written once here, each of those is a translation layer thin
185
+ * enough not to need a package — see the README recipe — and `@webdecoy/hono` is
186
+ * the one that does, because Hono has a middleware contract worth fitting.
187
+ *
188
+ * No `node:` imports: this is the code path that has to run on Workers.
189
+ */
190
+
191
+ interface FetchGuardOptions extends WebDecoyConfig, ProtectOptions {
192
+ /**
193
+ * Whether a blocking verdict actually blocks. Defaults to `'monitor'`.
194
+ *
195
+ * Nobody adopts a defence by having it break their site on the first install.
196
+ * Watch what it would have done, then switch.
197
+ */
198
+ mode?: 'monitor' | 'enforce';
199
+ /** Paths to skip entirely — health checks, static assets. */
200
+ skipPaths?: (string | RegExp)[];
201
+ /**
202
+ * How much of the `X-Forwarded-For` chain to believe. Defaults to `1` trusted
203
+ * hop: a fetch handler has no socket to fall back on, so there is no
204
+ * believe-nothing default available. See `resolveClientIp`.
205
+ */
206
+ trustProxy?: TrustedProxies;
207
+ /** Override IP resolution entirely. */
208
+ getIP?: (request: Request) => string;
209
+ /**
210
+ * Inject a hidden honeytoken link into HTML responses, and arm the tripwire it
211
+ * points at. Defaults to on when an `apiKey` is present.
212
+ */
213
+ honeytoken?: boolean;
214
+ /** Build the blocking response. Defaults to 403, or 429 for a throttle. */
215
+ onBlocked?: (request: Request, decision: Decision) => Response | Promise<Response>;
216
+ }
217
+ interface GuardOutcome {
218
+ /** What the SDK concluded. Always present, in both modes. */
219
+ decision: Decision;
220
+ /**
221
+ * The response to return instead of calling the handler, or undefined to
222
+ * carry on. Undefined in monitor mode even when the decision is a denial.
223
+ */
224
+ response?: Response;
225
+ }
226
+ interface FetchGuard {
227
+ /** Evaluate one request. */
228
+ check(request: Request, peer?: string): Promise<GuardOutcome>;
229
+ /**
230
+ * Rewrite an HTML response to carry the honeytoken link. Returns the response
231
+ * unchanged when there is no token yet, or the body is not injectable HTML.
232
+ */
233
+ decorate(response: Response): Promise<Response>;
234
+ /** Whether this path is skipped. */
235
+ skips(pathname: string): boolean;
236
+ /** The underlying SDK, for `detectBot()` and friends. */
237
+ sdk: WebDecoy;
238
+ }
239
+ /**
240
+ * A guard over WHATWG `Request`/`Response`.
241
+ *
242
+ * ```ts
243
+ * const guard = createFetchGuard({ rules: [tripwire()] });
244
+ *
245
+ * export default {
246
+ * async fetch(request) {
247
+ * const { response } = await guard.check(request);
248
+ * if (response) return response;
249
+ * return guard.decorate(await handle(request));
250
+ * },
251
+ * };
252
+ * ```
253
+ */
254
+ declare function createFetchGuard(options?: FetchGuardOptions): FetchGuard;
255
+
256
+ /**
257
+ * Detection and the clearance gate, in one middleware.
258
+ *
259
+ * A site on Vercel has one middleware file. Detection (what is this client,
260
+ * report it) and the clearance gate (does this protected page need a token)
261
+ * used to be two separate middlewares with two sets of credentials, so a site
262
+ * had to pick one or hand-write a chain. This runs both, for one request, and
263
+ * returns one outcome:
264
+ *
265
+ * - Detection runs when an API key is configured (`apiKey`, else
266
+ * `WEBDECOY_API_KEY`). It reports the reserved test trigger
267
+ * (`curl -A "WebDecoy-Test/1.0"`), tripwire hits and clients that look like
268
+ * bots, including every agent the bot registry names.
269
+ * - The gate runs when the site's identity is configured (`siteKey`,
270
+ * `scannerId`, `sensorKey`, else the WEBDECOY_* variables), exactly as
271
+ * `createClearanceGate()` does on its own.
272
+ *
273
+ * Without an API key this is the gate alone, unchanged. Without either, every
274
+ * request passes. Nothing here throws: a failure in detection or the gate lets
275
+ * the request through.
276
+ *
277
+ * Both halves resolve the client IP the same way and see the same path, so a
278
+ * request the gate refuses (or would refuse, in monitor mode) and the
279
+ * detection reported for it describe the same client.
280
+ */
281
+
282
+ interface DetectAndGateOptions extends ClearanceGateOptions, Omit<FetchGuardOptions, 'getIP' | 'honeytoken' | 'trustProxy'> {
283
+ /**
284
+ * The WebDecoy API key. `WEBDECOY_API_KEY` by default. A secret: set it in the
285
+ * platform's environment, never in code. Without one, no detection runs and
286
+ * this is the clearance gate alone.
287
+ */
288
+ apiKey?: string;
289
+ /**
290
+ * What a blocking detection verdict does. Defaults to `'monitor'`: the
291
+ * request is served and the verdict rides on the request headers
292
+ * (`x-webdecoy-decision`, `x-webdecoy-detection-id`, `x-webdecoy-would-block`).
293
+ * `'enforce'` answers a blocked request with 403 (or 429 for a rate limit).
294
+ *
295
+ * This is detection's mode only. Whether the clearance gate monitors or
296
+ * enforces is set per site in WebDecoy.
297
+ */
298
+ mode?: 'monitor' | 'enforce';
299
+ }
300
+ /** Detection's verdict on a request, when detection ran. */
301
+ interface DetectAndGateOutcome {
302
+ /** What to do with the request. Same shape as the gate's outcome. */
303
+ outcome: GateOutcome;
304
+ /** The detection decision, or null when detection did not run or failed. */
305
+ decision: Decision | null;
306
+ }
307
+ /**
308
+ * Detection then the clearance gate, bound to one site: call it with each
309
+ * request. Options default to the environment.
310
+ */
311
+ declare function createDetectAndGate(options?: DetectAndGateOptions): (request: Request, context?: ClearanceContext) => Promise<DetectAndGateOutcome>;
312
+
313
+ export { BUILD as B, type ClearanceContext as C, type DetectAndGateOptions as D, type FetchGuard as F, type GateEnv as G, type HeaderSource as H, type ResolveClientIpOptions as R, type TrustedProxies as T, type ClearanceGateOptions as a, type DetectAndGateOutcome as b, type FetchGuardOptions as c, type GateOutcome as d, type GuardOutcome as e, createClearanceGate as f, createDetectAndGate as g, createFetchGuard as h, ipInCidr as i, resolveGateEnv as j, normalizeIp as n, resolveClientIp as r };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,6 @@
1
- import { R as Rule, a as RuleContext, b as RuleResult, c as RuleEngineResult, d as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, e as BotAgent, f as BotCategory, A as AgentCategory, g as RateLimitStore, h as RateLimitConsume, i as RateLimitOutcome, W as WebDecoy, P as ProtectResult, D as Decision, j as WebDecoyConfig, k as ProtectOptions, l as AgentVerifierOptions, m as AgentRequestInput, n as AgentVerdict, S as SignedAgentDirectory } from './sdk-FCU-Ce-1.mjs';
2
- export { o as AgentStatus, p as BOT_CATEGORIES, q as BOT_REGISTRY, r as BotVerdict, C as Characteristic, s as Conclusion, t as DEFAULT_CHARACTERISTICS, u as DecisionCache, v as DecisionCacheOptions, w as DecisionInit, E as EDGE_CLASS_HEADER, x as EDGE_CLEARANCE_HEADER, y as EdgeClass, z as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, G as LogFields, H as Logger, M as MemoryRateLimitStore, J as RequestMetadata, K as RuleOutcome, N as RuleState, O as SDKDetectionRequest, Q as SDKDetectionResponse, U as Span, V as SyncRateLimitStore, X as TLSInfo, Y as Tracer, Z as ViolationEvent, _ as classifyUserAgent, $ as consoleLogger, a0 as deriveKey, a1 as fromPino, a2 as matchUserAgent, a3 as newDecisionId, a4 as readEdgeVerdict, a5 as silentLogger } from './sdk-FCU-Ce-1.mjs';
3
- import { T as TrustedProxies } from './index-GXXXr_mb.mjs';
4
- export { B as CLEARANCE_GATE_BUILD, C as ClearanceContext, a as ClearanceGateOptions, G as GateEnv, b as GateOutcome, H as HeaderSource, R as ResolveClientIpOptions, c as createClearanceGate, i as ipInCidr, n as normalizeIp, r as resolveClientIp, d as resolveGateEnv } from './index-GXXXr_mb.mjs';
1
+ import { R as Rule, a as RuleContext, b as RuleResult, c as RuleEngineResult, d as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, e as BotAgent, f as BotCategory, A as AgentCategory, g as RateLimitStore, h as RateLimitConsume, i as RateLimitOutcome, W as WebDecoy, P as ProtectResult, j as AgentVerifierOptions, k as AgentRequestInput, l as AgentVerdict, S as SignedAgentDirectory } from './sdk-B8M-WYTc.mjs';
2
+ export { m as AgentStatus, n as BOT_CATEGORIES, o as BOT_REGISTRY, p as BotVerdict, C as Characteristic, q as Conclusion, D as DEFAULT_CHARACTERISTICS, r as Decision, s as DecisionCache, t as DecisionCacheOptions, u as DecisionInit, E as EDGE_CLASS_HEADER, v as EDGE_CLEARANCE_HEADER, w as EdgeClass, x as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, y as LogFields, z as Logger, M as MemoryRateLimitStore, G as ProtectOptions, H as RequestMetadata, J as RuleOutcome, K as RuleState, N as SDKDetectionRequest, O as SDKDetectionResponse, Q as Span, U as SyncRateLimitStore, V as TLSInfo, X as Tracer, Y as ViolationEvent, Z as WebDecoyConfig, _ as classifyUserAgent, $ as consoleLogger, a0 as deriveKey, a1 as fromPino, a2 as matchUserAgent, a3 as newDecisionId, a4 as readEdgeVerdict, a5 as silentLogger } from './sdk-B8M-WYTc.mjs';
3
+ export { B as CLEARANCE_GATE_BUILD, C as ClearanceContext, a as ClearanceGateOptions, D as DetectAndGateOptions, b as DetectAndGateOutcome, F as FetchGuard, c as FetchGuardOptions, G as GateEnv, d as GateOutcome, e as GuardOutcome, H as HeaderSource, R as ResolveClientIpOptions, T as TrustedProxies, f as createClearanceGate, g as createDetectAndGate, h as createFetchGuard, i as ipInCidr, n as normalizeIp, r as resolveClientIp, j as resolveGateEnv } from './detect-and-gate-BES1jZ8P.mjs';
5
4
 
6
5
  /**
7
6
  * The reserved test trigger.
@@ -1305,92 +1304,6 @@ declare function armSiteHoneytoken(sdk: WebDecoy, options: HoneytokenArmingOptio
1305
1304
  */
1306
1305
  declare function deriveAndArm(sdk: WebDecoy, options: HoneytokenArmingOptions): Promise<SiteHoneytoken | null>;
1307
1306
 
1308
- /**
1309
- * One adapter, for every runtime that speaks `Request` and `Response`.
1310
- *
1311
- * WHY THIS EXISTS
1312
- *
1313
- * Express, Fastify and Next.js each grew their own copy of the same middleware:
1314
- * skip-path matching, monitor-versus-enforce, honeytoken arming, the 429 with a
1315
- * `Retry-After`, fail-open error handling. Three copies of a decision tree is
1316
- * three places for the branch that matters to be subtly different — and it
1317
- * already had been, which is how the leftmost-`X-Forwarded-For` bug survived in
1318
- * two adapters after the WordPress plugin fixed it.
1319
- *
1320
- * It is also the answer to "which framework do you support?". Hono, Bun, Deno,
1321
- * Astro, Nitro, SvelteKit and Remix all hand you a WHATWG `Request` and want a
1322
- * `Response` back. Written once here, each of those is a translation layer thin
1323
- * enough not to need a package — see the README recipe — and `@webdecoy/hono` is
1324
- * the one that does, because Hono has a middleware contract worth fitting.
1325
- *
1326
- * No `node:` imports: this is the code path that has to run on Workers.
1327
- */
1328
-
1329
- interface FetchGuardOptions extends WebDecoyConfig, ProtectOptions {
1330
- /**
1331
- * Whether a blocking verdict actually blocks. Defaults to `'monitor'`.
1332
- *
1333
- * Nobody adopts a defence by having it break their site on the first install.
1334
- * Watch what it would have done, then switch.
1335
- */
1336
- mode?: 'monitor' | 'enforce';
1337
- /** Paths to skip entirely — health checks, static assets. */
1338
- skipPaths?: (string | RegExp)[];
1339
- /**
1340
- * How much of the `X-Forwarded-For` chain to believe. Defaults to `1` trusted
1341
- * hop: a fetch handler has no socket to fall back on, so there is no
1342
- * believe-nothing default available. See `resolveClientIp`.
1343
- */
1344
- trustProxy?: TrustedProxies;
1345
- /** Override IP resolution entirely. */
1346
- getIP?: (request: Request) => string;
1347
- /**
1348
- * Inject a hidden honeytoken link into HTML responses, and arm the tripwire it
1349
- * points at. Defaults to on when an `apiKey` is present.
1350
- */
1351
- honeytoken?: boolean;
1352
- /** Build the blocking response. Defaults to 403, or 429 for a throttle. */
1353
- onBlocked?: (request: Request, decision: Decision) => Response | Promise<Response>;
1354
- }
1355
- interface GuardOutcome {
1356
- /** What the SDK concluded. Always present, in both modes. */
1357
- decision: Decision;
1358
- /**
1359
- * The response to return instead of calling the handler, or undefined to
1360
- * carry on. Undefined in monitor mode even when the decision is a denial.
1361
- */
1362
- response?: Response;
1363
- }
1364
- interface FetchGuard {
1365
- /** Evaluate one request. */
1366
- check(request: Request, peer?: string): Promise<GuardOutcome>;
1367
- /**
1368
- * Rewrite an HTML response to carry the honeytoken link. Returns the response
1369
- * unchanged when there is no token yet, or the body is not injectable HTML.
1370
- */
1371
- decorate(response: Response): Promise<Response>;
1372
- /** Whether this path is skipped. */
1373
- skips(pathname: string): boolean;
1374
- /** The underlying SDK, for `detectBot()` and friends. */
1375
- sdk: WebDecoy;
1376
- }
1377
- /**
1378
- * A guard over WHATWG `Request`/`Response`.
1379
- *
1380
- * ```ts
1381
- * const guard = createFetchGuard({ rules: [tripwire()] });
1382
- *
1383
- * export default {
1384
- * async fetch(request) {
1385
- * const { response } = await guard.check(request);
1386
- * if (response) return response;
1387
- * return guard.decorate(await handle(request));
1388
- * },
1389
- * };
1390
- * ```
1391
- */
1392
- declare function createFetchGuard(options?: FetchGuardOptions): FetchGuard;
1393
-
1394
1307
  /**
1395
1308
  * AgentVerifier — the public entry point for local Web Bot Auth verification.
1396
1309
  *
@@ -1787,4 +1700,4 @@ declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
1787
1700
  };
1788
1701
  type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
1789
1702
 
1790
- export { ATTACK_SIGNATURE_IDS, AgentCategory, AgentRequestInput, AgentVerdict, AgentVerifier, AgentVerifierOptions, type AttackSignatureConfig, AttackSignatureRule, type BehavioralSignals, type BlockResponse, BotAgent, BotCategory, BotPolicy, type BotPolicyOptions, BotRule, BotRuleConfig, CLIENT_SESSION_COOKIE, CLIENT_SESSION_HEADER, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, type ClientSignalConfig, ClientSignalRule, type ClientSignalStore, type ClientVerdict, DEFAULT_SIGNED_AGENT_DIRECTORIES, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, Decision, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, type EnvironmentalSignals, type FetchGuard, type FetchGuardOptions, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, type GuardOutcome, HONEYTOKEN_BASE_PATH, type Honeytoken, type HoneytokenArmingOptions, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectOptions, ProtectResult, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type Signals, SignedAgentDirectory, type SiteHoneytoken, type SiteHoneytokenOptions, type StoredChallenge, TEST_TRIGGER_UA_PREFIX, TEST_TRIGGER_USER_AGENT, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, TripwireConfig, TripwireRule, TrustedProxies, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, WebDecoyConfig, armSiteHoneytoken, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, createFetchGuard, deriveAndArm, filter, honeytoken, injectHoneytokenLink, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, parseUserAgent, rateLimit, readClientSession, recommend, resolveSecret, ruleBlockResponse, shouldSkipPath, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };
1703
+ export { ATTACK_SIGNATURE_IDS, AgentCategory, AgentRequestInput, AgentVerdict, AgentVerifier, AgentVerifierOptions, type AttackSignatureConfig, AttackSignatureRule, type BehavioralSignals, type BlockResponse, BotAgent, BotCategory, BotPolicy, type BotPolicyOptions, BotRule, BotRuleConfig, CLIENT_SESSION_COOKIE, CLIENT_SESSION_HEADER, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, type ClientSignalConfig, ClientSignalRule, type ClientSignalStore, type ClientVerdict, DEFAULT_SIGNED_AGENT_DIRECTORIES, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, type EnvironmentalSignals, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, HONEYTOKEN_BASE_PATH, type Honeytoken, type HoneytokenArmingOptions, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectResult, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type Signals, SignedAgentDirectory, type SiteHoneytoken, type SiteHoneytokenOptions, type StoredChallenge, TEST_TRIGGER_UA_PREFIX, TEST_TRIGGER_USER_AGENT, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, TripwireConfig, TripwireRule, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, armSiteHoneytoken, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, deriveAndArm, filter, honeytoken, injectHoneytokenLink, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, parseUserAgent, rateLimit, readClientSession, recommend, resolveSecret, ruleBlockResponse, shouldSkipPath, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };