@webdecoy/node 0.16.0 → 0.18.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.
- package/dist/{chunk-YBRI6SNF.mjs → chunk-MHCY2FDT.mjs} +172 -11
- package/dist/index.d.mts +8 -3
- package/dist/index.d.ts +8 -3
- package/dist/index.js +182 -18
- package/dist/index.mjs +4 -1
- package/dist/{sdk-C14NYPw_.d.mts → sdk-BTqYTW4I.d.mts} +39 -0
- package/dist/{sdk-C14NYPw_.d.ts → sdk-BTqYTW4I.d.ts} +39 -0
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +172 -11
- package/dist/testing.mjs +1 -1
- package/package.json +1 -1
|
@@ -2085,16 +2085,16 @@ function componentValue(req, c) {
|
|
|
2085
2085
|
case "@query":
|
|
2086
2086
|
return req.url.search === "" ? "?" : req.url.search;
|
|
2087
2087
|
case "signature-agent": {
|
|
2088
|
-
const
|
|
2089
|
-
if (
|
|
2090
|
-
if (c.keyParam !== void 0) return dictMemberValue(
|
|
2091
|
-
return
|
|
2088
|
+
const header2 = req.headers.get("signature-agent");
|
|
2089
|
+
if (header2 === null) throw new Error("signature-agent covered but absent");
|
|
2090
|
+
if (c.keyParam !== void 0) return dictMemberValue(header2, c.keyParam);
|
|
2091
|
+
return header2.trim().replace(/\s+/g, " ");
|
|
2092
2092
|
}
|
|
2093
2093
|
default: {
|
|
2094
2094
|
if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
|
|
2095
|
-
const
|
|
2096
|
-
if (
|
|
2097
|
-
return
|
|
2095
|
+
const header2 = req.headers.get(name);
|
|
2096
|
+
if (header2 === null) throw new Error(`covered header ${name} absent`);
|
|
2097
|
+
return header2.trim().replace(/\s+/g, " ");
|
|
2098
2098
|
}
|
|
2099
2099
|
}
|
|
2100
2100
|
}
|
|
@@ -2107,8 +2107,8 @@ function canonicalAuthority(url) {
|
|
|
2107
2107
|
}
|
|
2108
2108
|
return `${host}:${port}`;
|
|
2109
2109
|
}
|
|
2110
|
-
function dictMemberValue(
|
|
2111
|
-
const dict = parseDictionary(
|
|
2110
|
+
function dictMemberValue(header2, key) {
|
|
2111
|
+
const dict = parseDictionary(header2);
|
|
2112
2112
|
const found = dict.find((d) => d.key === key);
|
|
2113
2113
|
if (!found) throw new Error(`signature-agent has no member ${key}`);
|
|
2114
2114
|
return found.raw;
|
|
@@ -2552,6 +2552,23 @@ var WebDecoyClient = class {
|
|
|
2552
2552
|
}
|
|
2553
2553
|
}
|
|
2554
2554
|
}
|
|
2555
|
+
/**
|
|
2556
|
+
* Send AI referral counts. Resolves true when the batch needs no retry:
|
|
2557
|
+
* accepted, or refused for a reason a retry cannot fix (a 4xx). Only a
|
|
2558
|
+
* server error or a network failure resolves false, so the caller retries
|
|
2559
|
+
* the same batch id.
|
|
2560
|
+
*/
|
|
2561
|
+
async sendAIReferrals(batch) {
|
|
2562
|
+
try {
|
|
2563
|
+
const response = await this.request("POST", "/api/v1/sdk/ai-referrals", batch);
|
|
2564
|
+
return response.status < 500;
|
|
2565
|
+
} catch (error) {
|
|
2566
|
+
if (this.config.debug) {
|
|
2567
|
+
console.error("[WebDecoy] Failed to send AI referrals:", error);
|
|
2568
|
+
}
|
|
2569
|
+
return false;
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2555
2572
|
/**
|
|
2556
2573
|
* Get IP enrichment data from the ingest service
|
|
2557
2574
|
*/
|
|
@@ -2666,7 +2683,7 @@ function hasSuspiciousHeaders(metadata) {
|
|
|
2666
2683
|
const headers = metadata.headers || {};
|
|
2667
2684
|
const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent));
|
|
2668
2685
|
const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter(
|
|
2669
|
-
(
|
|
2686
|
+
(header2) => !headers[header2] && !headers[header2.toLowerCase()]
|
|
2670
2687
|
);
|
|
2671
2688
|
return hasBotUA || missingCommonHeaders.length > 0;
|
|
2672
2689
|
}
|
|
@@ -2778,6 +2795,143 @@ var ViolationReporter = class {
|
|
|
2778
2795
|
}
|
|
2779
2796
|
};
|
|
2780
2797
|
|
|
2798
|
+
// src/referrals/llm-platforms.generated.ts
|
|
2799
|
+
var LLM_PLATFORMS = {
|
|
2800
|
+
"chat.deepseek.com": "DeepSeek",
|
|
2801
|
+
"chat.openai.com": "ChatGPT",
|
|
2802
|
+
"chatgpt.com": "ChatGPT",
|
|
2803
|
+
"claude.ai": "Claude",
|
|
2804
|
+
"copilot.microsoft.com": "Copilot",
|
|
2805
|
+
"deepseek.com": "DeepSeek",
|
|
2806
|
+
"gemini.google.com": "Gemini",
|
|
2807
|
+
"grok.com": "Grok",
|
|
2808
|
+
"kagi.com": "Kagi",
|
|
2809
|
+
"meta.ai": "Meta AI",
|
|
2810
|
+
"perplexity.ai": "Perplexity",
|
|
2811
|
+
"phind.com": "Phind",
|
|
2812
|
+
"www.deepseek.com": "DeepSeek",
|
|
2813
|
+
"www.grok.com": "Grok",
|
|
2814
|
+
"www.kagi.com": "Kagi",
|
|
2815
|
+
"www.meta.ai": "Meta AI",
|
|
2816
|
+
"www.perplexity.ai": "Perplexity",
|
|
2817
|
+
"www.phind.com": "Phind",
|
|
2818
|
+
"www.you.com": "You.com",
|
|
2819
|
+
"you.com": "You.com"
|
|
2820
|
+
};
|
|
2821
|
+
|
|
2822
|
+
// src/referrals/llm-referral.ts
|
|
2823
|
+
var TAG_KEYS = ["utm_source", "ref", "utm_medium"];
|
|
2824
|
+
function classifyReferral(referer, pageUrl) {
|
|
2825
|
+
const ref = (referer ?? "").trim();
|
|
2826
|
+
if (ref) {
|
|
2827
|
+
try {
|
|
2828
|
+
return LLM_PLATFORMS[new URL(ref).hostname.toLowerCase()] ?? "";
|
|
2829
|
+
} catch {
|
|
2830
|
+
return "";
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
let url;
|
|
2834
|
+
try {
|
|
2835
|
+
url = new URL(pageUrl);
|
|
2836
|
+
} catch {
|
|
2837
|
+
return "";
|
|
2838
|
+
}
|
|
2839
|
+
for (const key of TAG_KEYS) {
|
|
2840
|
+
for (const value of url.searchParams.getAll(key)) {
|
|
2841
|
+
const platform = platformForTag(value);
|
|
2842
|
+
if (platform) return platform;
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
return "";
|
|
2846
|
+
}
|
|
2847
|
+
var squash = (s) => s.replace(/[ \-_.]/g, "");
|
|
2848
|
+
function platformForTag(raw) {
|
|
2849
|
+
let value = raw.trim().toLowerCase();
|
|
2850
|
+
if (!value) return "";
|
|
2851
|
+
try {
|
|
2852
|
+
const host = new URL(value).hostname;
|
|
2853
|
+
if (host) value = host.toLowerCase();
|
|
2854
|
+
} catch {
|
|
2855
|
+
}
|
|
2856
|
+
value = value.replace(/\.$/, "");
|
|
2857
|
+
if (LLM_PLATFORMS[value]) return LLM_PLATFORMS[value];
|
|
2858
|
+
const normalized = squash(value);
|
|
2859
|
+
for (const [domain, name] of Object.entries(LLM_PLATFORMS)) {
|
|
2860
|
+
if (normalized === squash(name.toLowerCase()) || normalized === domain.replace(/^www\./, "").replace(/\./g, "")) {
|
|
2861
|
+
return name;
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
return "";
|
|
2865
|
+
}
|
|
2866
|
+
|
|
2867
|
+
// src/referrals/referral-counter.ts
|
|
2868
|
+
var MAX_PATH = 500;
|
|
2869
|
+
var MAX_ENTRIES = 500;
|
|
2870
|
+
var header = (headers, name) => {
|
|
2871
|
+
const v = headers[name] ?? headers[name.toLowerCase()];
|
|
2872
|
+
if (v !== void 0) return v;
|
|
2873
|
+
for (const [k, value] of Object.entries(headers)) if (k.toLowerCase() === name) return value;
|
|
2874
|
+
return "";
|
|
2875
|
+
};
|
|
2876
|
+
var AIReferralCounter = class {
|
|
2877
|
+
constructor(sender, config = {}) {
|
|
2878
|
+
this.sender = sender;
|
|
2879
|
+
this.counts = /* @__PURE__ */ new Map();
|
|
2880
|
+
/** A batch that failed to send, retried under the same id so it counts once. */
|
|
2881
|
+
this.pending = null;
|
|
2882
|
+
this.flushing = false;
|
|
2883
|
+
this.timer = setInterval(() => void this.flush(), config.flushInterval ?? 6e4);
|
|
2884
|
+
this.timer.unref?.();
|
|
2885
|
+
}
|
|
2886
|
+
/** Count the request if it is a page visit an AI product sent. Never throws. */
|
|
2887
|
+
observe(metadata) {
|
|
2888
|
+
try {
|
|
2889
|
+
if ((metadata.method ?? "").toUpperCase() !== "GET") return;
|
|
2890
|
+
const headers = metadata.headers ?? {};
|
|
2891
|
+
if (header(headers, "sec-fetch-mode") !== "navigate") return;
|
|
2892
|
+
const dest = header(headers, "sec-fetch-dest");
|
|
2893
|
+
if (dest && dest !== "document") return;
|
|
2894
|
+
const path = (metadata.path || "/").split("?")[0] || "/";
|
|
2895
|
+
const query = metadata.query ? `?${metadata.query}` : "";
|
|
2896
|
+
const platform = classifyReferral(header(headers, "referer"), `https://site.invalid${path}${query}`);
|
|
2897
|
+
if (!platform) return;
|
|
2898
|
+
const landing = path.length > MAX_PATH ? path.slice(0, MAX_PATH) : path;
|
|
2899
|
+
const key = `${platform}
|
|
2900
|
+
${landing}`;
|
|
2901
|
+
const entry = this.counts.get(key);
|
|
2902
|
+
if (entry) {
|
|
2903
|
+
entry.count++;
|
|
2904
|
+
} else {
|
|
2905
|
+
this.counts.set(key, { platform, path: landing, count: 1 });
|
|
2906
|
+
if (this.counts.size >= MAX_ENTRIES) void this.flush();
|
|
2907
|
+
}
|
|
2908
|
+
} catch {
|
|
2909
|
+
}
|
|
2910
|
+
}
|
|
2911
|
+
/** Send what has been counted. Never rejects. */
|
|
2912
|
+
async flush() {
|
|
2913
|
+
if (this.flushing) return;
|
|
2914
|
+
this.flushing = true;
|
|
2915
|
+
try {
|
|
2916
|
+
if (!this.pending && this.counts.size > 0) {
|
|
2917
|
+
this.pending = { report_id: crypto.randomUUID(), source: "sdk", referrals: [...this.counts.values()] };
|
|
2918
|
+
this.counts = /* @__PURE__ */ new Map();
|
|
2919
|
+
}
|
|
2920
|
+
if (this.pending && await this.sender.sendAIReferrals(this.pending)) {
|
|
2921
|
+
this.pending = null;
|
|
2922
|
+
}
|
|
2923
|
+
} catch {
|
|
2924
|
+
} finally {
|
|
2925
|
+
this.flushing = false;
|
|
2926
|
+
}
|
|
2927
|
+
}
|
|
2928
|
+
/** Stop the timer and send what is left. */
|
|
2929
|
+
async destroy() {
|
|
2930
|
+
clearInterval(this.timer);
|
|
2931
|
+
await this.flush();
|
|
2932
|
+
}
|
|
2933
|
+
};
|
|
2934
|
+
|
|
2781
2935
|
// src/ip-enrichment.ts
|
|
2782
2936
|
var IPEnrichmentClient = class {
|
|
2783
2937
|
constructor(client, ttlMs = 36e5) {
|
|
@@ -2866,6 +3020,7 @@ function endSpan(span) {
|
|
|
2866
3020
|
// src/sdk.ts
|
|
2867
3021
|
var WebDecoy = class {
|
|
2868
3022
|
constructor(config) {
|
|
3023
|
+
this.referralCounter = null;
|
|
2869
3024
|
this.violationReporter = null;
|
|
2870
3025
|
this.ipEnrichmentClient = null;
|
|
2871
3026
|
this._hasFilterRules = false;
|
|
@@ -2887,7 +3042,8 @@ var WebDecoy = class {
|
|
|
2887
3042
|
threatScoreThreshold: config.threatScoreThreshold ?? 80,
|
|
2888
3043
|
timeout: config.timeout ?? 5e3,
|
|
2889
3044
|
debug: config.debug ?? false,
|
|
2890
|
-
tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
|
|
3045
|
+
tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true,
|
|
3046
|
+
countAIReferrals: config.countAIReferrals ?? true
|
|
2891
3047
|
};
|
|
2892
3048
|
this.log = resolveLogger(config.logger, this.config.debug);
|
|
2893
3049
|
this.tracer = config.tracer;
|
|
@@ -2921,6 +3077,9 @@ var WebDecoy = class {
|
|
|
2921
3077
|
if (this.client && this._hasFilterRules) {
|
|
2922
3078
|
this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
|
|
2923
3079
|
}
|
|
3080
|
+
if (this.client && this.config.countAIReferrals !== false) {
|
|
3081
|
+
this.referralCounter = new AIReferralCounter(this.client);
|
|
3082
|
+
}
|
|
2924
3083
|
if (this.client && this.ruleEngine) {
|
|
2925
3084
|
const reporter = new ViolationReporter(this.client, {
|
|
2926
3085
|
debug: this.config.debug
|
|
@@ -3092,6 +3251,7 @@ var WebDecoy = class {
|
|
|
3092
3251
|
*/
|
|
3093
3252
|
async protect(metadata, options = {}) {
|
|
3094
3253
|
const edge = readEdgeVerdict(metadata.headers);
|
|
3254
|
+
this.referralCounter?.observe(metadata);
|
|
3095
3255
|
const span = startSpan(this.tracer, "webdecoy.protect");
|
|
3096
3256
|
try {
|
|
3097
3257
|
const decision = (await this.decide(metadata, options)).withEdge(edge);
|
|
@@ -3353,6 +3513,7 @@ var WebDecoy = class {
|
|
|
3353
3513
|
if (this.violationReporter) {
|
|
3354
3514
|
await this.violationReporter.destroy();
|
|
3355
3515
|
}
|
|
3516
|
+
await this.referralCounter?.destroy();
|
|
3356
3517
|
}
|
|
3357
3518
|
};
|
|
3358
3519
|
function agentInputFromMetadata(metadata) {
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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-
|
|
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-
|
|
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-BTqYTW4I.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-BTqYTW4I.mjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* The reserved test trigger.
|
|
@@ -67,11 +67,16 @@ declare function isTestTriggerUserAgent(userAgent: string | undefined): boolean;
|
|
|
67
67
|
* - `'cloudflare'` — use `CF-Connecting-IP`. Only meaningful if the origin is
|
|
68
68
|
* unreachable except through Cloudflare, since the header is otherwise just
|
|
69
69
|
* another thing a client can send.
|
|
70
|
+
* - `'railway'` — the app runs on Railway with nothing else in front. Railway's
|
|
71
|
+
* edge replaces any `X-Forwarded-For` the client sent with exactly
|
|
72
|
+
* `<client>, <edge>`, so the client is two entries from the right. The
|
|
73
|
+
* common guess of `1` names Railway's edge for every visitor. With a CDN in
|
|
74
|
+
* front of Railway, configure for the CDN instead (`'cloudflare'`).
|
|
70
75
|
* - `string[]` — CIDRs (or bare addresses) of the proxies you run. The chain is
|
|
71
76
|
* walked right to left and the first address that isn't one of yours is the
|
|
72
77
|
* client. Use this when the depth varies.
|
|
73
78
|
*/
|
|
74
|
-
type TrustedProxies = false | number | 'cloudflare' | string[];
|
|
79
|
+
type TrustedProxies = false | number | 'cloudflare' | 'railway' | string[];
|
|
75
80
|
/** Headers as either a Node-style bag or a WHATWG `Headers`. */
|
|
76
81
|
type HeaderSource = Record<string, string | string[] | undefined> | {
|
|
77
82
|
get(name: string): string | null;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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-
|
|
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-
|
|
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-BTqYTW4I.js';
|
|
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-BTqYTW4I.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* The reserved test trigger.
|
|
@@ -67,11 +67,16 @@ declare function isTestTriggerUserAgent(userAgent: string | undefined): boolean;
|
|
|
67
67
|
* - `'cloudflare'` — use `CF-Connecting-IP`. Only meaningful if the origin is
|
|
68
68
|
* unreachable except through Cloudflare, since the header is otherwise just
|
|
69
69
|
* another thing a client can send.
|
|
70
|
+
* - `'railway'` — the app runs on Railway with nothing else in front. Railway's
|
|
71
|
+
* edge replaces any `X-Forwarded-For` the client sent with exactly
|
|
72
|
+
* `<client>, <edge>`, so the client is two entries from the right. The
|
|
73
|
+
* common guess of `1` names Railway's edge for every visitor. With a CDN in
|
|
74
|
+
* front of Railway, configure for the CDN instead (`'cloudflare'`).
|
|
70
75
|
* - `string[]` — CIDRs (or bare addresses) of the proxies you run. The chain is
|
|
71
76
|
* walked right to left and the first address that isn't one of yours is the
|
|
72
77
|
* client. Use this when the depth varies.
|
|
73
78
|
*/
|
|
74
|
-
type TrustedProxies = false | number | 'cloudflare' | string[];
|
|
79
|
+
type TrustedProxies = false | number | 'cloudflare' | 'railway' | string[];
|
|
75
80
|
/** Headers as either a Node-style bag or a WHATWG `Headers`. */
|
|
76
81
|
type HeaderSource = Record<string, string | string[] | undefined> | {
|
|
77
82
|
get(name: string): string | null;
|
package/dist/index.js
CHANGED
|
@@ -204,6 +204,23 @@ var WebDecoyClient = class {
|
|
|
204
204
|
}
|
|
205
205
|
}
|
|
206
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* Send AI referral counts. Resolves true when the batch needs no retry:
|
|
209
|
+
* accepted, or refused for a reason a retry cannot fix (a 4xx). Only a
|
|
210
|
+
* server error or a network failure resolves false, so the caller retries
|
|
211
|
+
* the same batch id.
|
|
212
|
+
*/
|
|
213
|
+
async sendAIReferrals(batch) {
|
|
214
|
+
try {
|
|
215
|
+
const response = await this.request("POST", "/api/v1/sdk/ai-referrals", batch);
|
|
216
|
+
return response.status < 500;
|
|
217
|
+
} catch (error) {
|
|
218
|
+
if (this.config.debug) {
|
|
219
|
+
console.error("[WebDecoy] Failed to send AI referrals:", error);
|
|
220
|
+
}
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
207
224
|
/**
|
|
208
225
|
* Get IP enrichment data from the ingest service
|
|
209
226
|
*/
|
|
@@ -318,7 +335,7 @@ function hasSuspiciousHeaders(metadata) {
|
|
|
318
335
|
const headers = metadata.headers || {};
|
|
319
336
|
const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent));
|
|
320
337
|
const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter(
|
|
321
|
-
(
|
|
338
|
+
(header2) => !headers[header2] && !headers[header2.toLowerCase()]
|
|
322
339
|
);
|
|
323
340
|
return hasBotUA || missingCommonHeaders.length > 0;
|
|
324
341
|
}
|
|
@@ -2057,6 +2074,143 @@ var ViolationReporter = class {
|
|
|
2057
2074
|
}
|
|
2058
2075
|
};
|
|
2059
2076
|
|
|
2077
|
+
// src/referrals/llm-platforms.generated.ts
|
|
2078
|
+
var LLM_PLATFORMS = {
|
|
2079
|
+
"chat.deepseek.com": "DeepSeek",
|
|
2080
|
+
"chat.openai.com": "ChatGPT",
|
|
2081
|
+
"chatgpt.com": "ChatGPT",
|
|
2082
|
+
"claude.ai": "Claude",
|
|
2083
|
+
"copilot.microsoft.com": "Copilot",
|
|
2084
|
+
"deepseek.com": "DeepSeek",
|
|
2085
|
+
"gemini.google.com": "Gemini",
|
|
2086
|
+
"grok.com": "Grok",
|
|
2087
|
+
"kagi.com": "Kagi",
|
|
2088
|
+
"meta.ai": "Meta AI",
|
|
2089
|
+
"perplexity.ai": "Perplexity",
|
|
2090
|
+
"phind.com": "Phind",
|
|
2091
|
+
"www.deepseek.com": "DeepSeek",
|
|
2092
|
+
"www.grok.com": "Grok",
|
|
2093
|
+
"www.kagi.com": "Kagi",
|
|
2094
|
+
"www.meta.ai": "Meta AI",
|
|
2095
|
+
"www.perplexity.ai": "Perplexity",
|
|
2096
|
+
"www.phind.com": "Phind",
|
|
2097
|
+
"www.you.com": "You.com",
|
|
2098
|
+
"you.com": "You.com"
|
|
2099
|
+
};
|
|
2100
|
+
|
|
2101
|
+
// src/referrals/llm-referral.ts
|
|
2102
|
+
var TAG_KEYS = ["utm_source", "ref", "utm_medium"];
|
|
2103
|
+
function classifyReferral(referer, pageUrl) {
|
|
2104
|
+
const ref = (referer ?? "").trim();
|
|
2105
|
+
if (ref) {
|
|
2106
|
+
try {
|
|
2107
|
+
return LLM_PLATFORMS[new URL(ref).hostname.toLowerCase()] ?? "";
|
|
2108
|
+
} catch {
|
|
2109
|
+
return "";
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
let url;
|
|
2113
|
+
try {
|
|
2114
|
+
url = new URL(pageUrl);
|
|
2115
|
+
} catch {
|
|
2116
|
+
return "";
|
|
2117
|
+
}
|
|
2118
|
+
for (const key of TAG_KEYS) {
|
|
2119
|
+
for (const value of url.searchParams.getAll(key)) {
|
|
2120
|
+
const platform = platformForTag(value);
|
|
2121
|
+
if (platform) return platform;
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
return "";
|
|
2125
|
+
}
|
|
2126
|
+
var squash = (s) => s.replace(/[ \-_.]/g, "");
|
|
2127
|
+
function platformForTag(raw) {
|
|
2128
|
+
let value = raw.trim().toLowerCase();
|
|
2129
|
+
if (!value) return "";
|
|
2130
|
+
try {
|
|
2131
|
+
const host = new URL(value).hostname;
|
|
2132
|
+
if (host) value = host.toLowerCase();
|
|
2133
|
+
} catch {
|
|
2134
|
+
}
|
|
2135
|
+
value = value.replace(/\.$/, "");
|
|
2136
|
+
if (LLM_PLATFORMS[value]) return LLM_PLATFORMS[value];
|
|
2137
|
+
const normalized = squash(value);
|
|
2138
|
+
for (const [domain, name] of Object.entries(LLM_PLATFORMS)) {
|
|
2139
|
+
if (normalized === squash(name.toLowerCase()) || normalized === domain.replace(/^www\./, "").replace(/\./g, "")) {
|
|
2140
|
+
return name;
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
return "";
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
// src/referrals/referral-counter.ts
|
|
2147
|
+
var MAX_PATH = 500;
|
|
2148
|
+
var MAX_ENTRIES = 500;
|
|
2149
|
+
var header = (headers, name) => {
|
|
2150
|
+
const v = headers[name] ?? headers[name.toLowerCase()];
|
|
2151
|
+
if (v !== void 0) return v;
|
|
2152
|
+
for (const [k, value] of Object.entries(headers)) if (k.toLowerCase() === name) return value;
|
|
2153
|
+
return "";
|
|
2154
|
+
};
|
|
2155
|
+
var AIReferralCounter = class {
|
|
2156
|
+
constructor(sender, config = {}) {
|
|
2157
|
+
this.sender = sender;
|
|
2158
|
+
this.counts = /* @__PURE__ */ new Map();
|
|
2159
|
+
/** A batch that failed to send, retried under the same id so it counts once. */
|
|
2160
|
+
this.pending = null;
|
|
2161
|
+
this.flushing = false;
|
|
2162
|
+
this.timer = setInterval(() => void this.flush(), config.flushInterval ?? 6e4);
|
|
2163
|
+
this.timer.unref?.();
|
|
2164
|
+
}
|
|
2165
|
+
/** Count the request if it is a page visit an AI product sent. Never throws. */
|
|
2166
|
+
observe(metadata) {
|
|
2167
|
+
try {
|
|
2168
|
+
if ((metadata.method ?? "").toUpperCase() !== "GET") return;
|
|
2169
|
+
const headers = metadata.headers ?? {};
|
|
2170
|
+
if (header(headers, "sec-fetch-mode") !== "navigate") return;
|
|
2171
|
+
const dest = header(headers, "sec-fetch-dest");
|
|
2172
|
+
if (dest && dest !== "document") return;
|
|
2173
|
+
const path = (metadata.path || "/").split("?")[0] || "/";
|
|
2174
|
+
const query = metadata.query ? `?${metadata.query}` : "";
|
|
2175
|
+
const platform = classifyReferral(header(headers, "referer"), `https://site.invalid${path}${query}`);
|
|
2176
|
+
if (!platform) return;
|
|
2177
|
+
const landing = path.length > MAX_PATH ? path.slice(0, MAX_PATH) : path;
|
|
2178
|
+
const key = `${platform}
|
|
2179
|
+
${landing}`;
|
|
2180
|
+
const entry = this.counts.get(key);
|
|
2181
|
+
if (entry) {
|
|
2182
|
+
entry.count++;
|
|
2183
|
+
} else {
|
|
2184
|
+
this.counts.set(key, { platform, path: landing, count: 1 });
|
|
2185
|
+
if (this.counts.size >= MAX_ENTRIES) void this.flush();
|
|
2186
|
+
}
|
|
2187
|
+
} catch {
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
/** Send what has been counted. Never rejects. */
|
|
2191
|
+
async flush() {
|
|
2192
|
+
if (this.flushing) return;
|
|
2193
|
+
this.flushing = true;
|
|
2194
|
+
try {
|
|
2195
|
+
if (!this.pending && this.counts.size > 0) {
|
|
2196
|
+
this.pending = { report_id: crypto.randomUUID(), source: "sdk", referrals: [...this.counts.values()] };
|
|
2197
|
+
this.counts = /* @__PURE__ */ new Map();
|
|
2198
|
+
}
|
|
2199
|
+
if (this.pending && await this.sender.sendAIReferrals(this.pending)) {
|
|
2200
|
+
this.pending = null;
|
|
2201
|
+
}
|
|
2202
|
+
} catch {
|
|
2203
|
+
} finally {
|
|
2204
|
+
this.flushing = false;
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
/** Stop the timer and send what is left. */
|
|
2208
|
+
async destroy() {
|
|
2209
|
+
clearInterval(this.timer);
|
|
2210
|
+
await this.flush();
|
|
2211
|
+
}
|
|
2212
|
+
};
|
|
2213
|
+
|
|
2060
2214
|
// src/ip-enrichment.ts
|
|
2061
2215
|
var IPEnrichmentClient = class {
|
|
2062
2216
|
constructor(client, ttlMs = 36e5) {
|
|
@@ -2565,16 +2719,16 @@ function componentValue(req, c) {
|
|
|
2565
2719
|
case "@query":
|
|
2566
2720
|
return req.url.search === "" ? "?" : req.url.search;
|
|
2567
2721
|
case "signature-agent": {
|
|
2568
|
-
const
|
|
2569
|
-
if (
|
|
2570
|
-
if (c.keyParam !== void 0) return dictMemberValue(
|
|
2571
|
-
return
|
|
2722
|
+
const header2 = req.headers.get("signature-agent");
|
|
2723
|
+
if (header2 === null) throw new Error("signature-agent covered but absent");
|
|
2724
|
+
if (c.keyParam !== void 0) return dictMemberValue(header2, c.keyParam);
|
|
2725
|
+
return header2.trim().replace(/\s+/g, " ");
|
|
2572
2726
|
}
|
|
2573
2727
|
default: {
|
|
2574
2728
|
if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
|
|
2575
|
-
const
|
|
2576
|
-
if (
|
|
2577
|
-
return
|
|
2729
|
+
const header2 = req.headers.get(name);
|
|
2730
|
+
if (header2 === null) throw new Error(`covered header ${name} absent`);
|
|
2731
|
+
return header2.trim().replace(/\s+/g, " ");
|
|
2578
2732
|
}
|
|
2579
2733
|
}
|
|
2580
2734
|
}
|
|
@@ -2587,8 +2741,8 @@ function canonicalAuthority(url) {
|
|
|
2587
2741
|
}
|
|
2588
2742
|
return `${host}:${port}`;
|
|
2589
2743
|
}
|
|
2590
|
-
function dictMemberValue(
|
|
2591
|
-
const dict = parseDictionary(
|
|
2744
|
+
function dictMemberValue(header2, key) {
|
|
2745
|
+
const dict = parseDictionary(header2);
|
|
2592
2746
|
const found = dict.find((d) => d.key === key);
|
|
2593
2747
|
if (!found) throw new Error(`signature-agent has no member ${key}`);
|
|
2594
2748
|
return found.raw;
|
|
@@ -2970,6 +3124,7 @@ function isTestTriggerUserAgent(userAgent) {
|
|
|
2970
3124
|
// src/sdk.ts
|
|
2971
3125
|
var WebDecoy = class {
|
|
2972
3126
|
constructor(config) {
|
|
3127
|
+
this.referralCounter = null;
|
|
2973
3128
|
this.violationReporter = null;
|
|
2974
3129
|
this.ipEnrichmentClient = null;
|
|
2975
3130
|
this._hasFilterRules = false;
|
|
@@ -2991,7 +3146,8 @@ var WebDecoy = class {
|
|
|
2991
3146
|
threatScoreThreshold: config.threatScoreThreshold ?? 80,
|
|
2992
3147
|
timeout: config.timeout ?? 5e3,
|
|
2993
3148
|
debug: config.debug ?? false,
|
|
2994
|
-
tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
|
|
3149
|
+
tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true,
|
|
3150
|
+
countAIReferrals: config.countAIReferrals ?? true
|
|
2995
3151
|
};
|
|
2996
3152
|
this.log = resolveLogger(config.logger, this.config.debug);
|
|
2997
3153
|
this.tracer = config.tracer;
|
|
@@ -3025,6 +3181,9 @@ var WebDecoy = class {
|
|
|
3025
3181
|
if (this.client && this._hasFilterRules) {
|
|
3026
3182
|
this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
|
|
3027
3183
|
}
|
|
3184
|
+
if (this.client && this.config.countAIReferrals !== false) {
|
|
3185
|
+
this.referralCounter = new AIReferralCounter(this.client);
|
|
3186
|
+
}
|
|
3028
3187
|
if (this.client && this.ruleEngine) {
|
|
3029
3188
|
const reporter = new ViolationReporter(this.client, {
|
|
3030
3189
|
debug: this.config.debug
|
|
@@ -3196,6 +3355,7 @@ var WebDecoy = class {
|
|
|
3196
3355
|
*/
|
|
3197
3356
|
async protect(metadata, options = {}) {
|
|
3198
3357
|
const edge = readEdgeVerdict(metadata.headers);
|
|
3358
|
+
this.referralCounter?.observe(metadata);
|
|
3199
3359
|
const span = startSpan(this.tracer, "webdecoy.protect");
|
|
3200
3360
|
try {
|
|
3201
3361
|
const decision = (await this.decide(metadata, options)).withEdge(edge);
|
|
@@ -3457,6 +3617,7 @@ var WebDecoy = class {
|
|
|
3457
3617
|
if (this.violationReporter) {
|
|
3458
3618
|
await this.violationReporter.destroy();
|
|
3459
3619
|
}
|
|
3620
|
+
await this.referralCounter?.destroy();
|
|
3460
3621
|
}
|
|
3461
3622
|
};
|
|
3462
3623
|
function agentInputFromMetadata(metadata) {
|
|
@@ -3605,6 +3766,9 @@ function resolveClientIp(options) {
|
|
|
3605
3766
|
if (trustProxy === "cloudflare") {
|
|
3606
3767
|
return normalizeIp(readHeader(headers, "cf-connecting-ip")) ?? peer;
|
|
3607
3768
|
}
|
|
3769
|
+
if (trustProxy === "railway") {
|
|
3770
|
+
return resolveClientIp({ headers, peer: options.peer, trustProxy: 2 });
|
|
3771
|
+
}
|
|
3608
3772
|
const chain = forwardedChain(headers);
|
|
3609
3773
|
const singleHeaderFallback = () => normalizeIp(readHeader(headers, "x-real-ip")) ?? normalizeIp(readHeader(headers, "x-vercel-forwarded-for")?.split(",").pop()) ?? void 0;
|
|
3610
3774
|
if (typeof trustProxy === "number") {
|
|
@@ -3666,8 +3830,8 @@ function readClientSession(headers) {
|
|
|
3666
3830
|
}
|
|
3667
3831
|
}
|
|
3668
3832
|
}
|
|
3669
|
-
const
|
|
3670
|
-
return
|
|
3833
|
+
const header2 = headers[CLIENT_SESSION_HEADER];
|
|
3834
|
+
return header2 || void 0;
|
|
3671
3835
|
}
|
|
3672
3836
|
var ClientSignalRule = class {
|
|
3673
3837
|
constructor(config) {
|
|
@@ -4717,8 +4881,8 @@ function analyzeHeaders(headers) {
|
|
|
4717
4881
|
headersLower[key.toLowerCase()] = value;
|
|
4718
4882
|
}
|
|
4719
4883
|
let missingCount = 0;
|
|
4720
|
-
for (const
|
|
4721
|
-
if (!(
|
|
4884
|
+
for (const header2 of EXPECTED_BROWSER_HEADERS) {
|
|
4885
|
+
if (!(header2 in headersLower)) missingCount++;
|
|
4722
4886
|
}
|
|
4723
4887
|
if (missingCount > 1) {
|
|
4724
4888
|
detections.push({
|
|
@@ -4728,13 +4892,13 @@ function analyzeHeaders(headers) {
|
|
|
4728
4892
|
reason: `Missing ${missingCount} expected browser headers`
|
|
4729
4893
|
});
|
|
4730
4894
|
}
|
|
4731
|
-
for (const
|
|
4732
|
-
if (SUSPICIOUS_HEADERS.has(
|
|
4895
|
+
for (const header2 of Object.keys(headersLower)) {
|
|
4896
|
+
if (SUSPICIOUS_HEADERS.has(header2)) {
|
|
4733
4897
|
detections.push({
|
|
4734
4898
|
category: "bot",
|
|
4735
4899
|
score: 0.3,
|
|
4736
4900
|
confidence: 0.4,
|
|
4737
|
-
reason: `Suspicious header present: ${
|
|
4901
|
+
reason: `Suspicious header present: ${header2}`
|
|
4738
4902
|
});
|
|
4739
4903
|
}
|
|
4740
4904
|
}
|
package/dist/index.mjs
CHANGED
|
@@ -54,7 +54,7 @@ import {
|
|
|
54
54
|
tripwire,
|
|
55
55
|
upstashRateLimitStore,
|
|
56
56
|
webBotAuth
|
|
57
|
-
} from "./chunk-
|
|
57
|
+
} from "./chunk-MHCY2FDT.mjs";
|
|
58
58
|
|
|
59
59
|
// src/client-ip.ts
|
|
60
60
|
var IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
|
@@ -183,6 +183,9 @@ function resolveClientIp(options) {
|
|
|
183
183
|
if (trustProxy === "cloudflare") {
|
|
184
184
|
return normalizeIp(readHeader(headers, "cf-connecting-ip")) ?? peer;
|
|
185
185
|
}
|
|
186
|
+
if (trustProxy === "railway") {
|
|
187
|
+
return resolveClientIp({ headers, peer: options.peer, trustProxy: 2 });
|
|
188
|
+
}
|
|
186
189
|
const chain = forwardedChain(headers);
|
|
187
190
|
const singleHeaderFallback = () => normalizeIp(readHeader(headers, "x-real-ip")) ?? normalizeIp(readHeader(headers, "x-vercel-forwarded-for")?.split(",").pop()) ?? void 0;
|
|
188
191
|
if (typeof trustProxy === "number") {
|
|
@@ -633,6 +633,15 @@ interface WebDecoyConfig {
|
|
|
633
633
|
* @default false
|
|
634
634
|
*/
|
|
635
635
|
debug?: boolean;
|
|
636
|
+
/**
|
|
637
|
+
* Count visits AI products send to this application (ChatGPT, Claude,
|
|
638
|
+
* Perplexity and others), for the AI Traffic page. Aggregate counts only:
|
|
639
|
+
* the AI platform, the landing path and a number, sent about once a
|
|
640
|
+
* minute. Nothing about a visitor is kept or sent. Needs an API key scoped
|
|
641
|
+
* to one site.
|
|
642
|
+
* @default true when an apiKey is set
|
|
643
|
+
*/
|
|
644
|
+
countAIReferrals?: boolean;
|
|
636
645
|
/**
|
|
637
646
|
* Whether to reject unauthorized TLS certificates
|
|
638
647
|
* Set to false for development/testing with self-signed certificates
|
|
@@ -1222,6 +1231,28 @@ interface RuleEngineResult {
|
|
|
1222
1231
|
results: RuleOutcome[];
|
|
1223
1232
|
}
|
|
1224
1233
|
|
|
1234
|
+
/**
|
|
1235
|
+
* Counts visits AI products send to this application, and reports the totals.
|
|
1236
|
+
*
|
|
1237
|
+
* Aggregate counts only: an AI platform, a landing path and a number, sent
|
|
1238
|
+
* about once a minute. Nothing about a visitor (no IP, user agent, cookie,
|
|
1239
|
+
* query string or full referrer) is kept or sent. Only a browser loading a
|
|
1240
|
+
* page counts: a GET whose fetch metadata says it is a document navigation.
|
|
1241
|
+
* Subresources, API calls and clients that send no fetch metadata are not
|
|
1242
|
+
* visits and are never counted.
|
|
1243
|
+
*/
|
|
1244
|
+
|
|
1245
|
+
interface AIReferralEntry {
|
|
1246
|
+
platform: string;
|
|
1247
|
+
path: string;
|
|
1248
|
+
count: number;
|
|
1249
|
+
}
|
|
1250
|
+
interface AIReferralBatch {
|
|
1251
|
+
report_id: string;
|
|
1252
|
+
source: 'sdk';
|
|
1253
|
+
referrals: AIReferralEntry[];
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1225
1256
|
/**
|
|
1226
1257
|
* Web Decoy API Client
|
|
1227
1258
|
* Handles communication with the ingest service.
|
|
@@ -1257,6 +1288,13 @@ declare class WebDecoyClient {
|
|
|
1257
1288
|
* Send violation events to the ingest service
|
|
1258
1289
|
*/
|
|
1259
1290
|
sendViolations(events: ViolationEvent[]): Promise<void>;
|
|
1291
|
+
/**
|
|
1292
|
+
* Send AI referral counts. Resolves true when the batch needs no retry:
|
|
1293
|
+
* accepted, or refused for a reason a retry cannot fix (a 4xx). Only a
|
|
1294
|
+
* server error or a network failure resolves false, so the caller retries
|
|
1295
|
+
* the same batch id.
|
|
1296
|
+
*/
|
|
1297
|
+
sendAIReferrals(batch: AIReferralBatch): Promise<boolean>;
|
|
1260
1298
|
/**
|
|
1261
1299
|
* Get IP enrichment data from the ingest service
|
|
1262
1300
|
*/
|
|
@@ -1271,6 +1309,7 @@ declare class WebDecoy {
|
|
|
1271
1309
|
private client;
|
|
1272
1310
|
private config;
|
|
1273
1311
|
private ruleEngine;
|
|
1312
|
+
private referralCounter;
|
|
1274
1313
|
private violationReporter;
|
|
1275
1314
|
private ipEnrichmentClient;
|
|
1276
1315
|
private _hasFilterRules;
|
|
@@ -633,6 +633,15 @@ interface WebDecoyConfig {
|
|
|
633
633
|
* @default false
|
|
634
634
|
*/
|
|
635
635
|
debug?: boolean;
|
|
636
|
+
/**
|
|
637
|
+
* Count visits AI products send to this application (ChatGPT, Claude,
|
|
638
|
+
* Perplexity and others), for the AI Traffic page. Aggregate counts only:
|
|
639
|
+
* the AI platform, the landing path and a number, sent about once a
|
|
640
|
+
* minute. Nothing about a visitor is kept or sent. Needs an API key scoped
|
|
641
|
+
* to one site.
|
|
642
|
+
* @default true when an apiKey is set
|
|
643
|
+
*/
|
|
644
|
+
countAIReferrals?: boolean;
|
|
636
645
|
/**
|
|
637
646
|
* Whether to reject unauthorized TLS certificates
|
|
638
647
|
* Set to false for development/testing with self-signed certificates
|
|
@@ -1222,6 +1231,28 @@ interface RuleEngineResult {
|
|
|
1222
1231
|
results: RuleOutcome[];
|
|
1223
1232
|
}
|
|
1224
1233
|
|
|
1234
|
+
/**
|
|
1235
|
+
* Counts visits AI products send to this application, and reports the totals.
|
|
1236
|
+
*
|
|
1237
|
+
* Aggregate counts only: an AI platform, a landing path and a number, sent
|
|
1238
|
+
* about once a minute. Nothing about a visitor (no IP, user agent, cookie,
|
|
1239
|
+
* query string or full referrer) is kept or sent. Only a browser loading a
|
|
1240
|
+
* page counts: a GET whose fetch metadata says it is a document navigation.
|
|
1241
|
+
* Subresources, API calls and clients that send no fetch metadata are not
|
|
1242
|
+
* visits and are never counted.
|
|
1243
|
+
*/
|
|
1244
|
+
|
|
1245
|
+
interface AIReferralEntry {
|
|
1246
|
+
platform: string;
|
|
1247
|
+
path: string;
|
|
1248
|
+
count: number;
|
|
1249
|
+
}
|
|
1250
|
+
interface AIReferralBatch {
|
|
1251
|
+
report_id: string;
|
|
1252
|
+
source: 'sdk';
|
|
1253
|
+
referrals: AIReferralEntry[];
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1225
1256
|
/**
|
|
1226
1257
|
* Web Decoy API Client
|
|
1227
1258
|
* Handles communication with the ingest service.
|
|
@@ -1257,6 +1288,13 @@ declare class WebDecoyClient {
|
|
|
1257
1288
|
* Send violation events to the ingest service
|
|
1258
1289
|
*/
|
|
1259
1290
|
sendViolations(events: ViolationEvent[]): Promise<void>;
|
|
1291
|
+
/**
|
|
1292
|
+
* Send AI referral counts. Resolves true when the batch needs no retry:
|
|
1293
|
+
* accepted, or refused for a reason a retry cannot fix (a 4xx). Only a
|
|
1294
|
+
* server error or a network failure resolves false, so the caller retries
|
|
1295
|
+
* the same batch id.
|
|
1296
|
+
*/
|
|
1297
|
+
sendAIReferrals(batch: AIReferralBatch): Promise<boolean>;
|
|
1260
1298
|
/**
|
|
1261
1299
|
* Get IP enrichment data from the ingest service
|
|
1262
1300
|
*/
|
|
@@ -1271,6 +1309,7 @@ declare class WebDecoy {
|
|
|
1271
1309
|
private client;
|
|
1272
1310
|
private config;
|
|
1273
1311
|
private ruleEngine;
|
|
1312
|
+
private referralCounter;
|
|
1274
1313
|
private violationReporter;
|
|
1275
1314
|
private ipEnrichmentClient;
|
|
1276
1315
|
private _hasFilterRules;
|
package/dist/testing.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-
|
|
1
|
+
import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-BTqYTW4I.mjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Testing utilities, for the application's test suite rather than ours.
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-
|
|
1
|
+
import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-BTqYTW4I.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Testing utilities, for the application's test suite rather than ours.
|
package/dist/testing.js
CHANGED
|
@@ -134,6 +134,23 @@ var WebDecoyClient = class {
|
|
|
134
134
|
}
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* Send AI referral counts. Resolves true when the batch needs no retry:
|
|
139
|
+
* accepted, or refused for a reason a retry cannot fix (a 4xx). Only a
|
|
140
|
+
* server error or a network failure resolves false, so the caller retries
|
|
141
|
+
* the same batch id.
|
|
142
|
+
*/
|
|
143
|
+
async sendAIReferrals(batch) {
|
|
144
|
+
try {
|
|
145
|
+
const response = await this.request("POST", "/api/v1/sdk/ai-referrals", batch);
|
|
146
|
+
return response.status < 500;
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (this.config.debug) {
|
|
149
|
+
console.error("[WebDecoy] Failed to send AI referrals:", error);
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
137
154
|
/**
|
|
138
155
|
* Get IP enrichment data from the ingest service
|
|
139
156
|
*/
|
|
@@ -248,7 +265,7 @@ function hasSuspiciousHeaders(metadata) {
|
|
|
248
265
|
const headers = metadata.headers || {};
|
|
249
266
|
const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent));
|
|
250
267
|
const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter(
|
|
251
|
-
(
|
|
268
|
+
(header2) => !headers[header2] && !headers[header2.toLowerCase()]
|
|
252
269
|
);
|
|
253
270
|
return hasBotUA || missingCommonHeaders.length > 0;
|
|
254
271
|
}
|
|
@@ -812,6 +829,143 @@ var ViolationReporter = class {
|
|
|
812
829
|
}
|
|
813
830
|
};
|
|
814
831
|
|
|
832
|
+
// src/referrals/llm-platforms.generated.ts
|
|
833
|
+
var LLM_PLATFORMS = {
|
|
834
|
+
"chat.deepseek.com": "DeepSeek",
|
|
835
|
+
"chat.openai.com": "ChatGPT",
|
|
836
|
+
"chatgpt.com": "ChatGPT",
|
|
837
|
+
"claude.ai": "Claude",
|
|
838
|
+
"copilot.microsoft.com": "Copilot",
|
|
839
|
+
"deepseek.com": "DeepSeek",
|
|
840
|
+
"gemini.google.com": "Gemini",
|
|
841
|
+
"grok.com": "Grok",
|
|
842
|
+
"kagi.com": "Kagi",
|
|
843
|
+
"meta.ai": "Meta AI",
|
|
844
|
+
"perplexity.ai": "Perplexity",
|
|
845
|
+
"phind.com": "Phind",
|
|
846
|
+
"www.deepseek.com": "DeepSeek",
|
|
847
|
+
"www.grok.com": "Grok",
|
|
848
|
+
"www.kagi.com": "Kagi",
|
|
849
|
+
"www.meta.ai": "Meta AI",
|
|
850
|
+
"www.perplexity.ai": "Perplexity",
|
|
851
|
+
"www.phind.com": "Phind",
|
|
852
|
+
"www.you.com": "You.com",
|
|
853
|
+
"you.com": "You.com"
|
|
854
|
+
};
|
|
855
|
+
|
|
856
|
+
// src/referrals/llm-referral.ts
|
|
857
|
+
var TAG_KEYS = ["utm_source", "ref", "utm_medium"];
|
|
858
|
+
function classifyReferral(referer, pageUrl) {
|
|
859
|
+
const ref = (referer ?? "").trim();
|
|
860
|
+
if (ref) {
|
|
861
|
+
try {
|
|
862
|
+
return LLM_PLATFORMS[new URL(ref).hostname.toLowerCase()] ?? "";
|
|
863
|
+
} catch {
|
|
864
|
+
return "";
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
let url;
|
|
868
|
+
try {
|
|
869
|
+
url = new URL(pageUrl);
|
|
870
|
+
} catch {
|
|
871
|
+
return "";
|
|
872
|
+
}
|
|
873
|
+
for (const key of TAG_KEYS) {
|
|
874
|
+
for (const value of url.searchParams.getAll(key)) {
|
|
875
|
+
const platform = platformForTag(value);
|
|
876
|
+
if (platform) return platform;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
return "";
|
|
880
|
+
}
|
|
881
|
+
var squash = (s) => s.replace(/[ \-_.]/g, "");
|
|
882
|
+
function platformForTag(raw) {
|
|
883
|
+
let value = raw.trim().toLowerCase();
|
|
884
|
+
if (!value) return "";
|
|
885
|
+
try {
|
|
886
|
+
const host = new URL(value).hostname;
|
|
887
|
+
if (host) value = host.toLowerCase();
|
|
888
|
+
} catch {
|
|
889
|
+
}
|
|
890
|
+
value = value.replace(/\.$/, "");
|
|
891
|
+
if (LLM_PLATFORMS[value]) return LLM_PLATFORMS[value];
|
|
892
|
+
const normalized = squash(value);
|
|
893
|
+
for (const [domain, name] of Object.entries(LLM_PLATFORMS)) {
|
|
894
|
+
if (normalized === squash(name.toLowerCase()) || normalized === domain.replace(/^www\./, "").replace(/\./g, "")) {
|
|
895
|
+
return name;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
return "";
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// src/referrals/referral-counter.ts
|
|
902
|
+
var MAX_PATH = 500;
|
|
903
|
+
var MAX_ENTRIES = 500;
|
|
904
|
+
var header = (headers, name) => {
|
|
905
|
+
const v = headers[name] ?? headers[name.toLowerCase()];
|
|
906
|
+
if (v !== void 0) return v;
|
|
907
|
+
for (const [k, value] of Object.entries(headers)) if (k.toLowerCase() === name) return value;
|
|
908
|
+
return "";
|
|
909
|
+
};
|
|
910
|
+
var AIReferralCounter = class {
|
|
911
|
+
constructor(sender, config = {}) {
|
|
912
|
+
this.sender = sender;
|
|
913
|
+
this.counts = /* @__PURE__ */ new Map();
|
|
914
|
+
/** A batch that failed to send, retried under the same id so it counts once. */
|
|
915
|
+
this.pending = null;
|
|
916
|
+
this.flushing = false;
|
|
917
|
+
this.timer = setInterval(() => void this.flush(), config.flushInterval ?? 6e4);
|
|
918
|
+
this.timer.unref?.();
|
|
919
|
+
}
|
|
920
|
+
/** Count the request if it is a page visit an AI product sent. Never throws. */
|
|
921
|
+
observe(metadata) {
|
|
922
|
+
try {
|
|
923
|
+
if ((metadata.method ?? "").toUpperCase() !== "GET") return;
|
|
924
|
+
const headers = metadata.headers ?? {};
|
|
925
|
+
if (header(headers, "sec-fetch-mode") !== "navigate") return;
|
|
926
|
+
const dest = header(headers, "sec-fetch-dest");
|
|
927
|
+
if (dest && dest !== "document") return;
|
|
928
|
+
const path = (metadata.path || "/").split("?")[0] || "/";
|
|
929
|
+
const query = metadata.query ? `?${metadata.query}` : "";
|
|
930
|
+
const platform = classifyReferral(header(headers, "referer"), `https://site.invalid${path}${query}`);
|
|
931
|
+
if (!platform) return;
|
|
932
|
+
const landing = path.length > MAX_PATH ? path.slice(0, MAX_PATH) : path;
|
|
933
|
+
const key = `${platform}
|
|
934
|
+
${landing}`;
|
|
935
|
+
const entry = this.counts.get(key);
|
|
936
|
+
if (entry) {
|
|
937
|
+
entry.count++;
|
|
938
|
+
} else {
|
|
939
|
+
this.counts.set(key, { platform, path: landing, count: 1 });
|
|
940
|
+
if (this.counts.size >= MAX_ENTRIES) void this.flush();
|
|
941
|
+
}
|
|
942
|
+
} catch {
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
/** Send what has been counted. Never rejects. */
|
|
946
|
+
async flush() {
|
|
947
|
+
if (this.flushing) return;
|
|
948
|
+
this.flushing = true;
|
|
949
|
+
try {
|
|
950
|
+
if (!this.pending && this.counts.size > 0) {
|
|
951
|
+
this.pending = { report_id: crypto.randomUUID(), source: "sdk", referrals: [...this.counts.values()] };
|
|
952
|
+
this.counts = /* @__PURE__ */ new Map();
|
|
953
|
+
}
|
|
954
|
+
if (this.pending && await this.sender.sendAIReferrals(this.pending)) {
|
|
955
|
+
this.pending = null;
|
|
956
|
+
}
|
|
957
|
+
} catch {
|
|
958
|
+
} finally {
|
|
959
|
+
this.flushing = false;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
/** Stop the timer and send what is left. */
|
|
963
|
+
async destroy() {
|
|
964
|
+
clearInterval(this.timer);
|
|
965
|
+
await this.flush();
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
|
|
815
969
|
// src/ip-enrichment.ts
|
|
816
970
|
var IPEnrichmentClient = class {
|
|
817
971
|
constructor(client, ttlMs = 36e5) {
|
|
@@ -1320,16 +1474,16 @@ function componentValue(req, c) {
|
|
|
1320
1474
|
case "@query":
|
|
1321
1475
|
return req.url.search === "" ? "?" : req.url.search;
|
|
1322
1476
|
case "signature-agent": {
|
|
1323
|
-
const
|
|
1324
|
-
if (
|
|
1325
|
-
if (c.keyParam !== void 0) return dictMemberValue(
|
|
1326
|
-
return
|
|
1477
|
+
const header2 = req.headers.get("signature-agent");
|
|
1478
|
+
if (header2 === null) throw new Error("signature-agent covered but absent");
|
|
1479
|
+
if (c.keyParam !== void 0) return dictMemberValue(header2, c.keyParam);
|
|
1480
|
+
return header2.trim().replace(/\s+/g, " ");
|
|
1327
1481
|
}
|
|
1328
1482
|
default: {
|
|
1329
1483
|
if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
|
|
1330
|
-
const
|
|
1331
|
-
if (
|
|
1332
|
-
return
|
|
1484
|
+
const header2 = req.headers.get(name);
|
|
1485
|
+
if (header2 === null) throw new Error(`covered header ${name} absent`);
|
|
1486
|
+
return header2.trim().replace(/\s+/g, " ");
|
|
1333
1487
|
}
|
|
1334
1488
|
}
|
|
1335
1489
|
}
|
|
@@ -1342,8 +1496,8 @@ function canonicalAuthority(url) {
|
|
|
1342
1496
|
}
|
|
1343
1497
|
return `${host}:${port}`;
|
|
1344
1498
|
}
|
|
1345
|
-
function dictMemberValue(
|
|
1346
|
-
const dict = parseDictionary(
|
|
1499
|
+
function dictMemberValue(header2, key) {
|
|
1500
|
+
const dict = parseDictionary(header2);
|
|
1347
1501
|
const found = dict.find((d) => d.key === key);
|
|
1348
1502
|
if (!found) throw new Error(`signature-agent has no member ${key}`);
|
|
1349
1503
|
return found.raw;
|
|
@@ -1713,6 +1867,7 @@ function isTestTriggerUserAgent(userAgent) {
|
|
|
1713
1867
|
// src/sdk.ts
|
|
1714
1868
|
var WebDecoy = class {
|
|
1715
1869
|
constructor(config) {
|
|
1870
|
+
this.referralCounter = null;
|
|
1716
1871
|
this.violationReporter = null;
|
|
1717
1872
|
this.ipEnrichmentClient = null;
|
|
1718
1873
|
this._hasFilterRules = false;
|
|
@@ -1734,7 +1889,8 @@ var WebDecoy = class {
|
|
|
1734
1889
|
threatScoreThreshold: config.threatScoreThreshold ?? 80,
|
|
1735
1890
|
timeout: config.timeout ?? 5e3,
|
|
1736
1891
|
debug: config.debug ?? false,
|
|
1737
|
-
tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
|
|
1892
|
+
tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true,
|
|
1893
|
+
countAIReferrals: config.countAIReferrals ?? true
|
|
1738
1894
|
};
|
|
1739
1895
|
this.log = resolveLogger(config.logger, this.config.debug);
|
|
1740
1896
|
this.tracer = config.tracer;
|
|
@@ -1768,6 +1924,9 @@ var WebDecoy = class {
|
|
|
1768
1924
|
if (this.client && this._hasFilterRules) {
|
|
1769
1925
|
this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
|
|
1770
1926
|
}
|
|
1927
|
+
if (this.client && this.config.countAIReferrals !== false) {
|
|
1928
|
+
this.referralCounter = new AIReferralCounter(this.client);
|
|
1929
|
+
}
|
|
1771
1930
|
if (this.client && this.ruleEngine) {
|
|
1772
1931
|
const reporter = new ViolationReporter(this.client, {
|
|
1773
1932
|
debug: this.config.debug
|
|
@@ -1939,6 +2098,7 @@ var WebDecoy = class {
|
|
|
1939
2098
|
*/
|
|
1940
2099
|
async protect(metadata, options = {}) {
|
|
1941
2100
|
const edge = readEdgeVerdict(metadata.headers);
|
|
2101
|
+
this.referralCounter?.observe(metadata);
|
|
1942
2102
|
const span = startSpan(this.tracer, "webdecoy.protect");
|
|
1943
2103
|
try {
|
|
1944
2104
|
const decision = (await this.decide(metadata, options)).withEdge(edge);
|
|
@@ -2200,6 +2360,7 @@ var WebDecoy = class {
|
|
|
2200
2360
|
if (this.violationReporter) {
|
|
2201
2361
|
await this.violationReporter.destroy();
|
|
2202
2362
|
}
|
|
2363
|
+
await this.referralCounter?.destroy();
|
|
2203
2364
|
}
|
|
2204
2365
|
};
|
|
2205
2366
|
function agentInputFromMetadata(metadata) {
|
package/dist/testing.mjs
CHANGED