@kya-os/agentshield-nextjs 0.3.2 → 0.3.5
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/README.md +21 -369
- package/index.js +9 -0
- package/package.json +6 -141
- package/EDGE_RUNTIME_WASM_SETUP.md +0 -348
- package/bin/setup-edge-wasm.js +0 -525
- package/dist/.tsbuildinfo +0 -1
- package/dist/api-client.d.mts +0 -196
- package/dist/api-client.d.ts +0 -196
- package/dist/api-client.js +0 -200
- package/dist/api-client.js.map +0 -1
- package/dist/api-client.mjs +0 -196
- package/dist/api-client.mjs.map +0 -1
- package/dist/api-middleware.d.mts +0 -140
- package/dist/api-middleware.d.ts +0 -140
- package/dist/api-middleware.js +0 -511
- package/dist/api-middleware.js.map +0 -1
- package/dist/api-middleware.mjs +0 -508
- package/dist/api-middleware.mjs.map +0 -1
- package/dist/create-middleware.d.mts +0 -17
- package/dist/create-middleware.d.ts +0 -17
- package/dist/create-middleware.js +0 -1381
- package/dist/create-middleware.js.map +0 -1
- package/dist/create-middleware.mjs +0 -1358
- package/dist/create-middleware.mjs.map +0 -1
- package/dist/edge/index.d.mts +0 -110
- package/dist/edge/index.d.ts +0 -110
- package/dist/edge/index.js +0 -277
- package/dist/edge/index.js.map +0 -1
- package/dist/edge/index.mjs +0 -275
- package/dist/edge/index.mjs.map +0 -1
- package/dist/edge-detector-wrapper.d.mts +0 -34
- package/dist/edge-detector-wrapper.d.ts +0 -34
- package/dist/edge-detector-wrapper.js +0 -596
- package/dist/edge-detector-wrapper.js.map +0 -1
- package/dist/edge-detector-wrapper.mjs +0 -574
- package/dist/edge-detector-wrapper.mjs.map +0 -1
- package/dist/edge-runtime-loader.d.mts +0 -50
- package/dist/edge-runtime-loader.d.ts +0 -50
- package/dist/edge-runtime-loader.js +0 -204
- package/dist/edge-runtime-loader.js.map +0 -1
- package/dist/edge-runtime-loader.mjs +0 -201
- package/dist/edge-runtime-loader.mjs.map +0 -1
- package/dist/edge-wasm-middleware.d.mts +0 -68
- package/dist/edge-wasm-middleware.d.ts +0 -68
- package/dist/edge-wasm-middleware.js +0 -318
- package/dist/edge-wasm-middleware.js.map +0 -1
- package/dist/edge-wasm-middleware.mjs +0 -315
- package/dist/edge-wasm-middleware.mjs.map +0 -1
- package/dist/enhanced-middleware.d.mts +0 -153
- package/dist/enhanced-middleware.d.ts +0 -153
- package/dist/enhanced-middleware.js +0 -1082
- package/dist/enhanced-middleware.js.map +0 -1
- package/dist/enhanced-middleware.mjs +0 -1080
- package/dist/enhanced-middleware.mjs.map +0 -1
- package/dist/index.d.mts +0 -24
- package/dist/index.d.ts +0 -24
- package/dist/index.js +0 -2717
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -2662
- package/dist/index.mjs.map +0 -1
- package/dist/middleware.d.mts +0 -21
- package/dist/middleware.d.ts +0 -21
- package/dist/middleware.js +0 -1362
- package/dist/middleware.js.map +0 -1
- package/dist/middleware.mjs +0 -1339
- package/dist/middleware.mjs.map +0 -1
- package/dist/nodejs-wasm-loader.d.mts +0 -25
- package/dist/nodejs-wasm-loader.d.ts +0 -25
- package/dist/nodejs-wasm-loader.js +0 -78
- package/dist/nodejs-wasm-loader.js.map +0 -1
- package/dist/nodejs-wasm-loader.mjs +0 -68
- package/dist/nodejs-wasm-loader.mjs.map +0 -1
- package/dist/policy.d.mts +0 -162
- package/dist/policy.d.ts +0 -162
- package/dist/policy.js +0 -189
- package/dist/policy.js.map +0 -1
- package/dist/policy.mjs +0 -165
- package/dist/policy.mjs.map +0 -1
- package/dist/session-tracker.d.mts +0 -55
- package/dist/session-tracker.d.ts +0 -55
- package/dist/session-tracker.js +0 -170
- package/dist/session-tracker.js.map +0 -1
- package/dist/session-tracker.mjs +0 -167
- package/dist/session-tracker.mjs.map +0 -1
- package/dist/signature-verifier.d.mts +0 -33
- package/dist/signature-verifier.d.ts +0 -33
- package/dist/signature-verifier.js +0 -386
- package/dist/signature-verifier.js.map +0 -1
- package/dist/signature-verifier.mjs +0 -362
- package/dist/signature-verifier.mjs.map +0 -1
- package/dist/types-DVmy9NE3.d.mts +0 -105
- package/dist/types-DVmy9NE3.d.ts +0 -105
- package/dist/wasm-middleware.d.mts +0 -63
- package/dist/wasm-middleware.d.ts +0 -63
- package/dist/wasm-middleware.js +0 -98
- package/dist/wasm-middleware.js.map +0 -1
- package/dist/wasm-middleware.mjs +0 -95
- package/dist/wasm-middleware.mjs.map +0 -1
- package/dist/wasm-setup.d.mts +0 -46
- package/dist/wasm-setup.d.ts +0 -46
- package/dist/wasm-setup.js +0 -157
- package/dist/wasm-setup.js.map +0 -1
- package/dist/wasm-setup.mjs +0 -148
- package/dist/wasm-setup.mjs.map +0 -1
- package/templates/middleware-wasm-100.ts +0 -151
- package/wasm/agentshield_wasm.d.ts +0 -479
- package/wasm/agentshield_wasm.js +0 -1536
- package/wasm/agentshield_wasm_bg.wasm +0 -0
- package/wasm/package.json +0 -30
- package/wasm.d.ts +0 -21
package/dist/middleware.mjs
DELETED
|
@@ -1,1339 +0,0 @@
|
|
|
1
|
-
import { loadRulesSync, evaluateEnforcement, shouldEnforce, mapVerificationMethod } from '@kya-os/agentshield-shared';
|
|
2
|
-
import { NextResponse } from 'next/server';
|
|
3
|
-
import * as ed25519 from '@noble/ed25519';
|
|
4
|
-
import { sha512 } from '@noble/hashes/sha2.js';
|
|
5
|
-
|
|
6
|
-
var __defProp = Object.defineProperty;
|
|
7
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
8
|
-
var __esm = (fn, res) => function __init() {
|
|
9
|
-
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
-
};
|
|
11
|
-
var __export = (target, all) => {
|
|
12
|
-
for (var name in all)
|
|
13
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
-
};
|
|
15
|
-
|
|
16
|
-
// src/wasm-loader.ts
|
|
17
|
-
function setWasmBaseUrl(url) {
|
|
18
|
-
baseUrl = url;
|
|
19
|
-
}
|
|
20
|
-
function getWasmUrl() {
|
|
21
|
-
if (baseUrl) {
|
|
22
|
-
try {
|
|
23
|
-
const url = new URL(baseUrl);
|
|
24
|
-
return `${url.origin}${WASM_PATH}`;
|
|
25
|
-
} catch {
|
|
26
|
-
return WASM_PATH;
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
return WASM_PATH;
|
|
30
|
-
}
|
|
31
|
-
async function initWasm() {
|
|
32
|
-
if (wasmExports) return true;
|
|
33
|
-
if (initPromise) {
|
|
34
|
-
await initPromise;
|
|
35
|
-
return !!wasmExports;
|
|
36
|
-
}
|
|
37
|
-
initPromise = (async () => {
|
|
38
|
-
try {
|
|
39
|
-
const controller = new AbortController();
|
|
40
|
-
const timeout = setTimeout(() => controller.abort(), 3e3);
|
|
41
|
-
try {
|
|
42
|
-
const wasmUrl = getWasmUrl();
|
|
43
|
-
if (typeof WebAssembly.instantiateStreaming === "function") {
|
|
44
|
-
try {
|
|
45
|
-
const response2 = await fetch(wasmUrl, { signal: controller.signal });
|
|
46
|
-
clearTimeout(timeout);
|
|
47
|
-
if (!response2.ok) {
|
|
48
|
-
throw new Error(`Failed to fetch WASM: ${response2.status}`);
|
|
49
|
-
}
|
|
50
|
-
const streamResponse = response2.clone();
|
|
51
|
-
const { instance } = await WebAssembly.instantiateStreaming(streamResponse, {
|
|
52
|
-
wbg: {
|
|
53
|
-
__wbg_log_1d3ae13c3d5e6b8e: (ptr, len) => {
|
|
54
|
-
if (process.env.NODE_ENV !== "production") {
|
|
55
|
-
console.debug("WASM:", ptr, len);
|
|
56
|
-
}
|
|
57
|
-
},
|
|
58
|
-
__wbindgen_throw: (ptr, len) => {
|
|
59
|
-
throw new Error(`WASM Error at ${ptr}, length ${len}`);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
});
|
|
63
|
-
wasmInstance = instance;
|
|
64
|
-
wasmExports = instance.exports;
|
|
65
|
-
if (process.env.NODE_ENV !== "production") {
|
|
66
|
-
console.debug("[AgentShield] \u2705 WASM module initialized with streaming");
|
|
67
|
-
}
|
|
68
|
-
return;
|
|
69
|
-
} catch (streamError) {
|
|
70
|
-
if (!controller.signal.aborted) {
|
|
71
|
-
if (process.env.NODE_ENV !== "production") {
|
|
72
|
-
console.debug(
|
|
73
|
-
"[AgentShield] Streaming compilation failed, falling back to standard compilation"
|
|
74
|
-
);
|
|
75
|
-
}
|
|
76
|
-
} else {
|
|
77
|
-
throw streamError;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
const response = await fetch(wasmUrl, { signal: controller.signal });
|
|
82
|
-
clearTimeout(timeout);
|
|
83
|
-
if (!response.ok) {
|
|
84
|
-
throw new Error(`Failed to fetch WASM: ${response.status}`);
|
|
85
|
-
}
|
|
86
|
-
const wasmArrayBuffer = await response.arrayBuffer();
|
|
87
|
-
const compiledModule = await WebAssembly.compile(wasmArrayBuffer);
|
|
88
|
-
const imports = {
|
|
89
|
-
wbg: {
|
|
90
|
-
__wbg_log_1d3ae13c3d5e6b8e: (ptr, len) => {
|
|
91
|
-
if (process.env.NODE_ENV !== "production") {
|
|
92
|
-
console.debug("WASM:", ptr, len);
|
|
93
|
-
}
|
|
94
|
-
},
|
|
95
|
-
__wbindgen_throw: (ptr, len) => {
|
|
96
|
-
throw new Error(`WASM Error at ${ptr}, length ${len}`);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
wasmInstance = await WebAssembly.instantiate(compiledModule, imports);
|
|
101
|
-
wasmExports = wasmInstance.exports;
|
|
102
|
-
if (process.env.NODE_ENV !== "production") {
|
|
103
|
-
console.debug("[AgentShield] \u2705 WASM module initialized via fallback");
|
|
104
|
-
}
|
|
105
|
-
} catch (fetchError) {
|
|
106
|
-
const error = fetchError;
|
|
107
|
-
if (error.name === "AbortError") {
|
|
108
|
-
console.warn(
|
|
109
|
-
"[AgentShield] WASM fetch timed out after 3 seconds - using pattern detection"
|
|
110
|
-
);
|
|
111
|
-
} else {
|
|
112
|
-
console.warn(
|
|
113
|
-
"[AgentShield] Failed to fetch WASM file:",
|
|
114
|
-
error.message || "Unknown error"
|
|
115
|
-
);
|
|
116
|
-
}
|
|
117
|
-
wasmExports = null;
|
|
118
|
-
}
|
|
119
|
-
} catch (error) {
|
|
120
|
-
console.error("[AgentShield] Failed to initialize WASM:", error);
|
|
121
|
-
wasmExports = null;
|
|
122
|
-
}
|
|
123
|
-
})();
|
|
124
|
-
await initPromise;
|
|
125
|
-
return !!wasmExports;
|
|
126
|
-
}
|
|
127
|
-
async function detectAgentWithWasm(_userAgent, _headers, _ipAddress) {
|
|
128
|
-
return null;
|
|
129
|
-
}
|
|
130
|
-
async function getWasmVersion() {
|
|
131
|
-
const initialized = await initWasm();
|
|
132
|
-
if (!initialized || !wasmExports) {
|
|
133
|
-
return null;
|
|
134
|
-
}
|
|
135
|
-
if (typeof wasmExports.version === "function") {
|
|
136
|
-
return wasmExports.version();
|
|
137
|
-
}
|
|
138
|
-
return "unknown";
|
|
139
|
-
}
|
|
140
|
-
async function isWasmAvailable() {
|
|
141
|
-
try {
|
|
142
|
-
const initialized = await initWasm();
|
|
143
|
-
if (!initialized) return false;
|
|
144
|
-
const version = await getWasmVersion();
|
|
145
|
-
return version !== null;
|
|
146
|
-
} catch {
|
|
147
|
-
return false;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
var wasmInstance, wasmExports, initPromise, WASM_PATH, baseUrl;
|
|
151
|
-
var init_wasm_loader = __esm({
|
|
152
|
-
"src/wasm-loader.ts"() {
|
|
153
|
-
wasmInstance = null;
|
|
154
|
-
wasmExports = null;
|
|
155
|
-
initPromise = null;
|
|
156
|
-
WASM_PATH = "/wasm/agentshield_wasm_bg.wasm";
|
|
157
|
-
baseUrl = null;
|
|
158
|
-
}
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
// src/edge-detector-with-wasm.ts
|
|
162
|
-
var edge_detector_with_wasm_exports = {};
|
|
163
|
-
__export(edge_detector_with_wasm_exports, {
|
|
164
|
-
EdgeAgentDetectorWithWasm: () => EdgeAgentDetectorWithWasm,
|
|
165
|
-
EdgeAgentDetectorWrapperWithWasm: () => EdgeAgentDetectorWrapperWithWasm
|
|
166
|
-
});
|
|
167
|
-
var rules2, EdgeAgentDetectorWithWasm, EdgeAgentDetectorWrapperWithWasm;
|
|
168
|
-
var init_edge_detector_with_wasm = __esm({
|
|
169
|
-
"src/edge-detector-with-wasm.ts"() {
|
|
170
|
-
init_wasm_loader();
|
|
171
|
-
rules2 = loadRulesSync();
|
|
172
|
-
EdgeAgentDetectorWithWasm = class {
|
|
173
|
-
constructor(enableWasm = true) {
|
|
174
|
-
this.enableWasm = enableWasm;
|
|
175
|
-
this.rules = rules2;
|
|
176
|
-
}
|
|
177
|
-
wasmEnabled = false;
|
|
178
|
-
initPromise = null;
|
|
179
|
-
baseUrl = null;
|
|
180
|
-
rules;
|
|
181
|
-
/**
|
|
182
|
-
* Set the base URL for WASM loading in Edge Runtime
|
|
183
|
-
*/
|
|
184
|
-
setBaseUrl(url) {
|
|
185
|
-
this.baseUrl = url;
|
|
186
|
-
setWasmBaseUrl(url);
|
|
187
|
-
}
|
|
188
|
-
/**
|
|
189
|
-
* Initialize the detector (including WASM if enabled)
|
|
190
|
-
*/
|
|
191
|
-
async init() {
|
|
192
|
-
if (!this.enableWasm) {
|
|
193
|
-
this.wasmEnabled = false;
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
if (this.initPromise) {
|
|
197
|
-
await this.initPromise;
|
|
198
|
-
return;
|
|
199
|
-
}
|
|
200
|
-
this.initPromise = (async () => {
|
|
201
|
-
try {
|
|
202
|
-
const wasmAvailable = await isWasmAvailable();
|
|
203
|
-
if (wasmAvailable) {
|
|
204
|
-
if (this.baseUrl) {
|
|
205
|
-
setWasmBaseUrl(this.baseUrl);
|
|
206
|
-
}
|
|
207
|
-
await initWasm();
|
|
208
|
-
this.wasmEnabled = true;
|
|
209
|
-
} else {
|
|
210
|
-
this.wasmEnabled = false;
|
|
211
|
-
}
|
|
212
|
-
} catch (error) {
|
|
213
|
-
console.error("[AgentShield] Failed to initialize WASM:", error);
|
|
214
|
-
this.wasmEnabled = false;
|
|
215
|
-
}
|
|
216
|
-
})();
|
|
217
|
-
await this.initPromise;
|
|
218
|
-
}
|
|
219
|
-
/**
|
|
220
|
-
* Pattern-based detection (fallback)
|
|
221
|
-
*/
|
|
222
|
-
async patternDetection(input) {
|
|
223
|
-
const reasons = [];
|
|
224
|
-
let detectedAgent;
|
|
225
|
-
let verificationMethod;
|
|
226
|
-
let confidence = 0;
|
|
227
|
-
const headers = input.headers || {};
|
|
228
|
-
const normalizedHeaders = {};
|
|
229
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
230
|
-
normalizedHeaders[key.toLowerCase()] = value;
|
|
231
|
-
}
|
|
232
|
-
const signaturePresent = !!(normalizedHeaders["signature"] || normalizedHeaders["signature-input"]);
|
|
233
|
-
const signatureAgent = normalizedHeaders["signature-agent"];
|
|
234
|
-
const isChatGPT = (() => {
|
|
235
|
-
try {
|
|
236
|
-
const url = new URL(signatureAgent?.replace(/^"|"$/g, "") || "");
|
|
237
|
-
return url.hostname === "chatgpt.com" || url.hostname.endsWith(".chatgpt.com");
|
|
238
|
-
} catch {
|
|
239
|
-
return false;
|
|
240
|
-
}
|
|
241
|
-
})();
|
|
242
|
-
if (isChatGPT) {
|
|
243
|
-
confidence = 85;
|
|
244
|
-
reasons.push("signature_agent:chatgpt");
|
|
245
|
-
detectedAgent = { type: "chatgpt", name: "ChatGPT" };
|
|
246
|
-
verificationMethod = "signature";
|
|
247
|
-
} else if (signaturePresent) {
|
|
248
|
-
confidence = Math.max(confidence, 40);
|
|
249
|
-
reasons.push("signature_present");
|
|
250
|
-
}
|
|
251
|
-
const userAgent = input.userAgent || input.headers?.["user-agent"] || "";
|
|
252
|
-
if (userAgent) {
|
|
253
|
-
for (const [agentKey, agentRule] of Object.entries(this.rules.rules.userAgents)) {
|
|
254
|
-
const matched = agentRule.patterns.some((pattern) => {
|
|
255
|
-
const regex = new RegExp(pattern, "i");
|
|
256
|
-
return regex.test(userAgent);
|
|
257
|
-
});
|
|
258
|
-
if (matched) {
|
|
259
|
-
const agentType = this.getAgentType(agentKey);
|
|
260
|
-
const agentName = this.getAgentName(agentKey);
|
|
261
|
-
confidence = Math.max(confidence, Math.round(agentRule.confidence * 0.85 * 100));
|
|
262
|
-
reasons.push(`known_pattern:${agentType}`);
|
|
263
|
-
if (!detectedAgent) {
|
|
264
|
-
detectedAgent = { type: agentType, name: agentName };
|
|
265
|
-
verificationMethod = "pattern";
|
|
266
|
-
}
|
|
267
|
-
break;
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
const suspiciousHeaders = this.rules.rules.headers.suspicious;
|
|
272
|
-
const foundAiHeaders = suspiciousHeaders.filter(
|
|
273
|
-
(headerRule) => normalizedHeaders[headerRule.name.toLowerCase()]
|
|
274
|
-
);
|
|
275
|
-
if (foundAiHeaders.length > 0) {
|
|
276
|
-
const maxConfidence = Math.max(...foundAiHeaders.map((h) => h.confidence));
|
|
277
|
-
confidence = Math.max(confidence, maxConfidence);
|
|
278
|
-
reasons.push(`ai_headers:${foundAiHeaders.length}`);
|
|
279
|
-
}
|
|
280
|
-
const ip = input.ip || input.ipAddress;
|
|
281
|
-
if (ip && !normalizedHeaders["x-forwarded-for"] && !normalizedHeaders["x-real-ip"]) {
|
|
282
|
-
const ipRanges = "providers" in this.rules.rules.ipRanges ? this.rules.rules.ipRanges.providers : this.rules.rules.ipRanges;
|
|
283
|
-
for (const [provider, ipRule] of Object.entries(ipRanges)) {
|
|
284
|
-
if (!ipRule || typeof ipRule !== "object" || !("ranges" in ipRule) || !Array.isArray(ipRule.ranges))
|
|
285
|
-
continue;
|
|
286
|
-
const matched = ipRule.ranges.some((range) => {
|
|
287
|
-
const prefix = range.split("/")[0];
|
|
288
|
-
const prefixParts = prefix.split(".");
|
|
289
|
-
const ipParts = ip.split(".");
|
|
290
|
-
for (let i = 0; i < Math.min(prefixParts.length - 1, 2); i++) {
|
|
291
|
-
if (prefixParts[i] !== ipParts[i] && prefixParts[i] !== "0") {
|
|
292
|
-
return false;
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
return true;
|
|
296
|
-
});
|
|
297
|
-
if (matched) {
|
|
298
|
-
confidence = Math.max(confidence, Math.round(ipRule.confidence * 0.4 * 100));
|
|
299
|
-
reasons.push(`cloud_provider:${provider}`);
|
|
300
|
-
break;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
if (reasons.length > 2) {
|
|
305
|
-
confidence = Math.min(Math.round(confidence * 1.2), 95);
|
|
306
|
-
}
|
|
307
|
-
confidence = Math.min(Math.max(confidence, 0), 100);
|
|
308
|
-
return {
|
|
309
|
-
isAgent: confidence > 30,
|
|
310
|
-
// 30% threshold
|
|
311
|
-
confidence,
|
|
312
|
-
detectionClass: confidence > 30 && detectedAgent ? { type: "AiAgent", agentType: detectedAgent.name } : confidence > 30 ? { type: "Unknown" } : { type: "Human" },
|
|
313
|
-
signals: [],
|
|
314
|
-
// Will be populated by enhanced detection engine in future tasks
|
|
315
|
-
...detectedAgent && { detectedAgent },
|
|
316
|
-
reasons,
|
|
317
|
-
...verificationMethod && {
|
|
318
|
-
verificationMethod: mapVerificationMethod(verificationMethod)
|
|
319
|
-
},
|
|
320
|
-
forgeabilityRisk: confidence > 80 ? "medium" : "high",
|
|
321
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
322
|
-
};
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
|
-
* Analyze request with WASM enhancement when available
|
|
326
|
-
*/
|
|
327
|
-
async analyze(input) {
|
|
328
|
-
await this.init();
|
|
329
|
-
if (this.wasmEnabled) {
|
|
330
|
-
try {
|
|
331
|
-
const wasmResult = await detectAgentWithWasm(
|
|
332
|
-
input.userAgent || input.headers?.["user-agent"],
|
|
333
|
-
input.headers || {},
|
|
334
|
-
input.ip || input.ipAddress
|
|
335
|
-
);
|
|
336
|
-
if (wasmResult) {
|
|
337
|
-
const detectedAgent = wasmResult.agent ? this.mapAgentName(wasmResult.agent) : void 0;
|
|
338
|
-
return {
|
|
339
|
-
isAgent: wasmResult.isAgent,
|
|
340
|
-
confidence: wasmResult.confidence,
|
|
341
|
-
detectionClass: wasmResult.isAgent && detectedAgent ? { type: "AiAgent", agentType: detectedAgent.name } : wasmResult.isAgent ? { type: "Unknown" } : { type: "Human" },
|
|
342
|
-
signals: [],
|
|
343
|
-
// Will be populated by enhanced detection engine in future tasks
|
|
344
|
-
...detectedAgent && { detectedAgent },
|
|
345
|
-
reasons: [`wasm:${wasmResult.verificationMethod}`],
|
|
346
|
-
verificationMethod: mapVerificationMethod(wasmResult.verificationMethod),
|
|
347
|
-
forgeabilityRisk: wasmResult.verificationMethod === "signature" ? "low" : wasmResult.confidence > 90 ? "medium" : "high",
|
|
348
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
349
|
-
};
|
|
350
|
-
}
|
|
351
|
-
} catch (error) {
|
|
352
|
-
console.error("[AgentShield] WASM detection error:", error);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
const patternResult = await this.patternDetection(input);
|
|
356
|
-
if (this.wasmEnabled && patternResult.confidence >= 85) {
|
|
357
|
-
patternResult.confidence = Math.min(95, patternResult.confidence + 10);
|
|
358
|
-
patternResult.reasons.push("wasm_enhanced");
|
|
359
|
-
}
|
|
360
|
-
return patternResult;
|
|
361
|
-
}
|
|
362
|
-
/**
|
|
363
|
-
* Get agent type from rule key
|
|
364
|
-
*/
|
|
365
|
-
getAgentType(agentKey) {
|
|
366
|
-
const typeMap = {
|
|
367
|
-
openai_gptbot: "openai",
|
|
368
|
-
anthropic_claude: "anthropic",
|
|
369
|
-
perplexity_bot: "perplexity",
|
|
370
|
-
google_ai: "google",
|
|
371
|
-
microsoft_ai: "microsoft",
|
|
372
|
-
meta_ai: "meta",
|
|
373
|
-
cohere_bot: "cohere",
|
|
374
|
-
huggingface_bot: "huggingface",
|
|
375
|
-
generic_bot: "generic",
|
|
376
|
-
dev_tools: "dev",
|
|
377
|
-
automation_tools: "automation"
|
|
378
|
-
};
|
|
379
|
-
return typeMap[agentKey] || agentKey;
|
|
380
|
-
}
|
|
381
|
-
/**
|
|
382
|
-
* Get agent name from rule key
|
|
383
|
-
*/
|
|
384
|
-
getAgentName(agentKey) {
|
|
385
|
-
const nameMap = {
|
|
386
|
-
openai_gptbot: "ChatGPT/GPTBot",
|
|
387
|
-
anthropic_claude: "Claude",
|
|
388
|
-
perplexity_bot: "Perplexity",
|
|
389
|
-
google_ai: "Google AI",
|
|
390
|
-
microsoft_ai: "Microsoft Copilot",
|
|
391
|
-
meta_ai: "Meta AI",
|
|
392
|
-
cohere_bot: "Cohere",
|
|
393
|
-
huggingface_bot: "HuggingFace",
|
|
394
|
-
generic_bot: "Generic Bot",
|
|
395
|
-
dev_tools: "Development Tool",
|
|
396
|
-
automation_tools: "Automation Tool"
|
|
397
|
-
};
|
|
398
|
-
return nameMap[agentKey] || agentKey;
|
|
399
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* Map agent names from WASM to consistent format
|
|
402
|
-
*/
|
|
403
|
-
mapAgentName(agent) {
|
|
404
|
-
const lowerAgent = agent.toLowerCase();
|
|
405
|
-
if (lowerAgent.includes("chatgpt")) {
|
|
406
|
-
return { type: "chatgpt", name: "ChatGPT" };
|
|
407
|
-
} else if (lowerAgent.includes("claude")) {
|
|
408
|
-
return { type: "claude", name: "Claude" };
|
|
409
|
-
} else if (lowerAgent.includes("perplexity")) {
|
|
410
|
-
return { type: "perplexity", name: "Perplexity" };
|
|
411
|
-
} else if (lowerAgent.includes("bing")) {
|
|
412
|
-
return { type: "bing", name: "Bing AI" };
|
|
413
|
-
} else if (lowerAgent.includes("anthropic")) {
|
|
414
|
-
return { type: "anthropic", name: "Anthropic" };
|
|
415
|
-
}
|
|
416
|
-
return { type: "unknown", name: agent };
|
|
417
|
-
}
|
|
418
|
-
};
|
|
419
|
-
EdgeAgentDetectorWrapperWithWasm = class {
|
|
420
|
-
detector;
|
|
421
|
-
events = /* @__PURE__ */ new Map();
|
|
422
|
-
constructor(config) {
|
|
423
|
-
this.detector = new EdgeAgentDetectorWithWasm(config?.enableWasm ?? true);
|
|
424
|
-
if (config?.baseUrl) {
|
|
425
|
-
this.detector.setBaseUrl(config.baseUrl);
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
setBaseUrl(url) {
|
|
429
|
-
this.detector.setBaseUrl(url);
|
|
430
|
-
}
|
|
431
|
-
async analyze(input) {
|
|
432
|
-
const result = await this.detector.analyze(input);
|
|
433
|
-
if (result.isAgent && this.events.has("agent.detected")) {
|
|
434
|
-
const handlers = this.events.get("agent.detected") || [];
|
|
435
|
-
handlers.forEach((handler) => handler(result, input));
|
|
436
|
-
}
|
|
437
|
-
return result;
|
|
438
|
-
}
|
|
439
|
-
on(event, handler) {
|
|
440
|
-
if (!this.events.has(event)) {
|
|
441
|
-
this.events.set(event, []);
|
|
442
|
-
}
|
|
443
|
-
this.events.get(event).push(handler);
|
|
444
|
-
}
|
|
445
|
-
emit(event, ...args) {
|
|
446
|
-
const handlers = this.events.get(event) || [];
|
|
447
|
-
handlers.forEach((handler) => handler(...args));
|
|
448
|
-
}
|
|
449
|
-
async init() {
|
|
450
|
-
await this.detector.init();
|
|
451
|
-
}
|
|
452
|
-
};
|
|
453
|
-
}
|
|
454
|
-
});
|
|
455
|
-
ed25519.etc.sha512Sync = (...m) => sha512(ed25519.etc.concatBytes(...m));
|
|
456
|
-
var KNOWN_KEYS = {
|
|
457
|
-
chatgpt: [
|
|
458
|
-
{
|
|
459
|
-
kid: "otMqcjr17mGyruktGvJU8oojQTSMHlVm7uO-lrcqbdg",
|
|
460
|
-
// ChatGPT's current Ed25519 public key (base64)
|
|
461
|
-
// Source: https://chatgpt.com/.well-known/http-message-signatures-directory
|
|
462
|
-
publicKey: "7F_3jDlxaquwh291MiACkcS3Opq88NksyHiakzS-Y1g",
|
|
463
|
-
validFrom: 1735689600,
|
|
464
|
-
// Jan 1, 2025 (nbf from OpenAI)
|
|
465
|
-
validUntil: 1769029093
|
|
466
|
-
// Jan 21, 2026 (exp from OpenAI)
|
|
467
|
-
}
|
|
468
|
-
]
|
|
469
|
-
};
|
|
470
|
-
var keyCache = /* @__PURE__ */ new Map();
|
|
471
|
-
var CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
472
|
-
var CACHE_MAX_SIZE = 100;
|
|
473
|
-
function getApiBaseUrl() {
|
|
474
|
-
if (typeof window !== "undefined") {
|
|
475
|
-
return "/api/internal";
|
|
476
|
-
}
|
|
477
|
-
const baseUrl2 = process.env.NEXT_PUBLIC_APP_URL || process.env.NEXT_PUBLIC_API_URL || process.env.API_URL || (process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : null);
|
|
478
|
-
if (baseUrl2) {
|
|
479
|
-
return baseUrl2.replace(/\/$/, "") + "/api/internal";
|
|
480
|
-
}
|
|
481
|
-
if (process.env.NODE_ENV !== "production") {
|
|
482
|
-
console.warn(
|
|
483
|
-
"[Signature] No base URL configured for server-side fetch. Using localhost fallback."
|
|
484
|
-
);
|
|
485
|
-
return "http://localhost:3000/api/internal";
|
|
486
|
-
}
|
|
487
|
-
console.error(
|
|
488
|
-
"[Signature] CRITICAL: No base URL configured for server-side fetch in production!"
|
|
489
|
-
);
|
|
490
|
-
return "/api/internal";
|
|
491
|
-
}
|
|
492
|
-
function cleanupExpiredCache() {
|
|
493
|
-
const now = Date.now();
|
|
494
|
-
const entriesToDelete = [];
|
|
495
|
-
for (const [agent, cached] of keyCache.entries()) {
|
|
496
|
-
if (now - cached.cachedAt > CACHE_TTL_MS) {
|
|
497
|
-
entriesToDelete.push(agent);
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
for (const agent of entriesToDelete) {
|
|
501
|
-
keyCache.delete(agent);
|
|
502
|
-
}
|
|
503
|
-
if (keyCache.size > CACHE_MAX_SIZE) {
|
|
504
|
-
const entries = Array.from(keyCache.entries()).map(([agent, cached]) => ({
|
|
505
|
-
agent,
|
|
506
|
-
cachedAt: cached.cachedAt
|
|
507
|
-
}));
|
|
508
|
-
entries.sort((a, b) => a.cachedAt - b.cachedAt);
|
|
509
|
-
const toRemove = entries.slice(0, keyCache.size - CACHE_MAX_SIZE);
|
|
510
|
-
for (const entry of toRemove) {
|
|
511
|
-
keyCache.delete(entry.agent);
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
async function fetchKeysFromApi(agent) {
|
|
516
|
-
if (keyCache.size > CACHE_MAX_SIZE) {
|
|
517
|
-
cleanupExpiredCache();
|
|
518
|
-
}
|
|
519
|
-
const cached = keyCache.get(agent);
|
|
520
|
-
if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) {
|
|
521
|
-
return cached.keys;
|
|
522
|
-
}
|
|
523
|
-
if (typeof fetch === "undefined") {
|
|
524
|
-
console.warn("[Signature] fetch() not available in this environment");
|
|
525
|
-
return null;
|
|
526
|
-
}
|
|
527
|
-
try {
|
|
528
|
-
const apiBaseUrl = getApiBaseUrl();
|
|
529
|
-
const url = `${apiBaseUrl}/signature-keys?agent=${encodeURIComponent(agent)}`;
|
|
530
|
-
const response = await fetch(url, {
|
|
531
|
-
method: "GET",
|
|
532
|
-
headers: {
|
|
533
|
-
"Content-Type": "application/json"
|
|
534
|
-
},
|
|
535
|
-
// 5 second timeout
|
|
536
|
-
signal: AbortSignal.timeout(5e3)
|
|
537
|
-
});
|
|
538
|
-
if (!response.ok) {
|
|
539
|
-
console.warn(`[Signature] Failed to fetch keys from API: ${response.status}`);
|
|
540
|
-
return null;
|
|
541
|
-
}
|
|
542
|
-
const data = await response.json();
|
|
543
|
-
if (!data.keys || !Array.isArray(data.keys) || data.keys.length === 0) {
|
|
544
|
-
console.warn(`[Signature] No keys returned from API for agent: ${agent}`);
|
|
545
|
-
return null;
|
|
546
|
-
}
|
|
547
|
-
keyCache.set(agent, {
|
|
548
|
-
keys: data.keys,
|
|
549
|
-
cachedAt: Date.now()
|
|
550
|
-
});
|
|
551
|
-
return data.keys;
|
|
552
|
-
} catch (error) {
|
|
553
|
-
console.warn("[Signature] Error fetching keys from API, using fallback", {
|
|
554
|
-
error: error instanceof Error ? error.message : "Unknown error",
|
|
555
|
-
agent
|
|
556
|
-
});
|
|
557
|
-
return null;
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
function isValidAgent(agent) {
|
|
561
|
-
return agent in KNOWN_KEYS;
|
|
562
|
-
}
|
|
563
|
-
async function getKeysForAgent(agent) {
|
|
564
|
-
const apiKeys = await fetchKeysFromApi(agent);
|
|
565
|
-
if (apiKeys && apiKeys.length > 0) {
|
|
566
|
-
return apiKeys;
|
|
567
|
-
}
|
|
568
|
-
if (isValidAgent(agent)) {
|
|
569
|
-
return KNOWN_KEYS[agent];
|
|
570
|
-
}
|
|
571
|
-
return [];
|
|
572
|
-
}
|
|
573
|
-
function parseSignatureInput(signatureInput) {
|
|
574
|
-
try {
|
|
575
|
-
const match = signatureInput.match(/sig1=\((.*?)\);(.+)/);
|
|
576
|
-
if (!match) return null;
|
|
577
|
-
const [, headersList, params] = match;
|
|
578
|
-
const signedHeaders = headersList ? headersList.split(" ").map((h) => h.replace(/"/g, "").trim()).filter((h) => h.length > 0) : [];
|
|
579
|
-
const keyidMatch = params ? params.match(/keyid="([^"]+)"/) : null;
|
|
580
|
-
const createdMatch = params ? params.match(/created=(\d+)/) : null;
|
|
581
|
-
const expiresMatch = params ? params.match(/expires=(\d+)/) : null;
|
|
582
|
-
if (!keyidMatch || !keyidMatch[1]) return null;
|
|
583
|
-
return {
|
|
584
|
-
keyid: keyidMatch[1],
|
|
585
|
-
created: createdMatch && createdMatch[1] ? parseInt(createdMatch[1]) : void 0,
|
|
586
|
-
expires: expiresMatch && expiresMatch[1] ? parseInt(expiresMatch[1]) : void 0,
|
|
587
|
-
signedHeaders
|
|
588
|
-
};
|
|
589
|
-
} catch (error) {
|
|
590
|
-
console.error("[Signature] Failed to parse Signature-Input:", error);
|
|
591
|
-
return null;
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
function buildSignatureBase(method, path, headers, signedHeaders) {
|
|
595
|
-
const components = [];
|
|
596
|
-
for (const headerName of signedHeaders) {
|
|
597
|
-
let value;
|
|
598
|
-
switch (headerName) {
|
|
599
|
-
case "@method":
|
|
600
|
-
value = method.toUpperCase();
|
|
601
|
-
break;
|
|
602
|
-
case "@path":
|
|
603
|
-
value = path;
|
|
604
|
-
break;
|
|
605
|
-
case "@authority":
|
|
606
|
-
value = headers["host"] || headers["Host"] || "";
|
|
607
|
-
break;
|
|
608
|
-
default: {
|
|
609
|
-
const key = Object.keys(headers).find((k) => k.toLowerCase() === headerName.toLowerCase());
|
|
610
|
-
value = key ? headers[key] || "" : "";
|
|
611
|
-
break;
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
components.push(`"${headerName}": ${value}`);
|
|
615
|
-
}
|
|
616
|
-
return components.join("\n");
|
|
617
|
-
}
|
|
618
|
-
function base64ToBytes(base64) {
|
|
619
|
-
let standardBase64 = base64.replace(/-/g, "+").replace(/_/g, "/");
|
|
620
|
-
const padding = standardBase64.length % 4;
|
|
621
|
-
if (padding) {
|
|
622
|
-
standardBase64 += "=".repeat(4 - padding);
|
|
623
|
-
}
|
|
624
|
-
const binaryString = atob(standardBase64);
|
|
625
|
-
return Uint8Array.from(binaryString, (c) => c.charCodeAt(0));
|
|
626
|
-
}
|
|
627
|
-
async function verifyEd25519Signature(publicKeyBase64, signatureBase64, message) {
|
|
628
|
-
try {
|
|
629
|
-
const publicKeyBytes = base64ToBytes(publicKeyBase64);
|
|
630
|
-
const signatureBytes = base64ToBytes(signatureBase64);
|
|
631
|
-
const messageBytes = new TextEncoder().encode(message);
|
|
632
|
-
if (publicKeyBytes.length !== 32) {
|
|
633
|
-
console.error("[Signature] Invalid public key length:", publicKeyBytes.length);
|
|
634
|
-
return false;
|
|
635
|
-
}
|
|
636
|
-
if (signatureBytes.length !== 64) {
|
|
637
|
-
console.error("[Signature] Invalid signature length:", signatureBytes.length);
|
|
638
|
-
return false;
|
|
639
|
-
}
|
|
640
|
-
return ed25519.verify(signatureBytes, messageBytes, publicKeyBytes);
|
|
641
|
-
} catch (nobleError) {
|
|
642
|
-
console.warn("[Signature] @noble/ed25519 failed, trying Web Crypto fallback:", nobleError);
|
|
643
|
-
try {
|
|
644
|
-
const publicKeyBytes = base64ToBytes(publicKeyBase64);
|
|
645
|
-
const signatureBytes = base64ToBytes(signatureBase64);
|
|
646
|
-
const messageBytes = new TextEncoder().encode(message);
|
|
647
|
-
const publicKey = await crypto.subtle.importKey(
|
|
648
|
-
"raw",
|
|
649
|
-
publicKeyBytes.buffer,
|
|
650
|
-
{
|
|
651
|
-
name: "Ed25519",
|
|
652
|
-
namedCurve: "Ed25519"
|
|
653
|
-
},
|
|
654
|
-
false,
|
|
655
|
-
["verify"]
|
|
656
|
-
);
|
|
657
|
-
return await crypto.subtle.verify(
|
|
658
|
-
"Ed25519",
|
|
659
|
-
publicKey,
|
|
660
|
-
signatureBytes.buffer,
|
|
661
|
-
messageBytes
|
|
662
|
-
);
|
|
663
|
-
} catch (cryptoError) {
|
|
664
|
-
console.error("[Signature] Both @noble/ed25519 and Web Crypto failed:", {
|
|
665
|
-
nobleError: nobleError instanceof Error ? nobleError.message : "Unknown",
|
|
666
|
-
cryptoError: cryptoError instanceof Error ? cryptoError.message : "Unknown"
|
|
667
|
-
});
|
|
668
|
-
return false;
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
async function verifyAgentSignature(method, path, headers) {
|
|
673
|
-
const signature = headers["signature"] || headers["Signature"];
|
|
674
|
-
const signatureInput = headers["signature-input"] || headers["Signature-Input"];
|
|
675
|
-
const signatureAgent = headers["signature-agent"] || headers["Signature-Agent"];
|
|
676
|
-
if (!signature || !signatureInput) {
|
|
677
|
-
return {
|
|
678
|
-
isValid: false,
|
|
679
|
-
confidence: 0,
|
|
680
|
-
reason: "No signature headers present",
|
|
681
|
-
verificationMethod: "none"
|
|
682
|
-
};
|
|
683
|
-
}
|
|
684
|
-
const parsed = parseSignatureInput(signatureInput);
|
|
685
|
-
if (!parsed) {
|
|
686
|
-
return {
|
|
687
|
-
isValid: false,
|
|
688
|
-
confidence: 0,
|
|
689
|
-
reason: "Invalid Signature-Input header",
|
|
690
|
-
verificationMethod: "none"
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
if (parsed.created) {
|
|
694
|
-
const now2 = Math.floor(Date.now() / 1e3);
|
|
695
|
-
const age = now2 - parsed.created;
|
|
696
|
-
if (age > 300) {
|
|
697
|
-
return {
|
|
698
|
-
isValid: false,
|
|
699
|
-
confidence: 0,
|
|
700
|
-
reason: "Signature expired (older than 5 minutes)",
|
|
701
|
-
verificationMethod: "none"
|
|
702
|
-
};
|
|
703
|
-
}
|
|
704
|
-
if (age < -30) {
|
|
705
|
-
return {
|
|
706
|
-
isValid: false,
|
|
707
|
-
confidence: 0,
|
|
708
|
-
reason: "Signature timestamp is in the future",
|
|
709
|
-
verificationMethod: "none"
|
|
710
|
-
};
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
let agent;
|
|
714
|
-
let agentKey;
|
|
715
|
-
const isChatGPT = signatureAgent === '"https://chatgpt.com"' || (() => {
|
|
716
|
-
try {
|
|
717
|
-
const url = new URL(signatureAgent?.replace(/^"|"$/g, "") || "");
|
|
718
|
-
return url.hostname === "chatgpt.com" || url.hostname.endsWith(".chatgpt.com");
|
|
719
|
-
} catch {
|
|
720
|
-
return false;
|
|
721
|
-
}
|
|
722
|
-
})();
|
|
723
|
-
if (isChatGPT) {
|
|
724
|
-
agent = "ChatGPT";
|
|
725
|
-
agentKey = "chatgpt";
|
|
726
|
-
}
|
|
727
|
-
if (!agent || !agentKey) {
|
|
728
|
-
return {
|
|
729
|
-
isValid: false,
|
|
730
|
-
confidence: 0,
|
|
731
|
-
reason: "Unknown signature agent",
|
|
732
|
-
verificationMethod: "none"
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
const knownKeys = await getKeysForAgent(agentKey);
|
|
736
|
-
if (knownKeys.length === 0) {
|
|
737
|
-
return {
|
|
738
|
-
isValid: false,
|
|
739
|
-
confidence: 0,
|
|
740
|
-
reason: "No keys available for agent",
|
|
741
|
-
verificationMethod: "none"
|
|
742
|
-
};
|
|
743
|
-
}
|
|
744
|
-
const key = knownKeys.find((k) => k.kid === parsed.keyid);
|
|
745
|
-
if (!key) {
|
|
746
|
-
return {
|
|
747
|
-
isValid: false,
|
|
748
|
-
confidence: 0,
|
|
749
|
-
reason: `Unknown key ID: ${parsed.keyid}`,
|
|
750
|
-
verificationMethod: "none"
|
|
751
|
-
};
|
|
752
|
-
}
|
|
753
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
754
|
-
if (now < key.validFrom || now > key.validUntil) {
|
|
755
|
-
return {
|
|
756
|
-
isValid: false,
|
|
757
|
-
confidence: 0,
|
|
758
|
-
reason: "Key is not valid at current time",
|
|
759
|
-
verificationMethod: "none"
|
|
760
|
-
};
|
|
761
|
-
}
|
|
762
|
-
const signatureBase = buildSignatureBase(method, path, headers, parsed.signedHeaders);
|
|
763
|
-
let signatureValue = signature;
|
|
764
|
-
if (signatureValue.startsWith("sig1=:")) {
|
|
765
|
-
signatureValue = signatureValue.substring(6);
|
|
766
|
-
}
|
|
767
|
-
if (signatureValue.endsWith(":")) {
|
|
768
|
-
signatureValue = signatureValue.slice(0, -1);
|
|
769
|
-
}
|
|
770
|
-
const isValid = await verifyEd25519Signature(key.publicKey, signatureValue, signatureBase);
|
|
771
|
-
if (isValid) {
|
|
772
|
-
return {
|
|
773
|
-
isValid: true,
|
|
774
|
-
agent,
|
|
775
|
-
keyid: parsed.keyid,
|
|
776
|
-
confidence: 1,
|
|
777
|
-
// 100% confidence for valid signature
|
|
778
|
-
verificationMethod: "signature"
|
|
779
|
-
};
|
|
780
|
-
} else {
|
|
781
|
-
return {
|
|
782
|
-
isValid: false,
|
|
783
|
-
confidence: 0,
|
|
784
|
-
reason: "Signature verification failed",
|
|
785
|
-
verificationMethod: "none"
|
|
786
|
-
};
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
function hasSignatureHeaders(headers) {
|
|
790
|
-
return !!((headers["signature"] || headers["Signature"]) && (headers["signature-input"] || headers["Signature-Input"]));
|
|
791
|
-
}
|
|
792
|
-
function isChatGPTSignature(headers) {
|
|
793
|
-
const signatureAgent = headers["signature-agent"] || headers["Signature-Agent"];
|
|
794
|
-
if (!signatureAgent) {
|
|
795
|
-
return false;
|
|
796
|
-
}
|
|
797
|
-
const agentUrlStr = signatureAgent.replace(/^"+|"+$/g, "");
|
|
798
|
-
if (agentUrlStr === "https://chatgpt.com") {
|
|
799
|
-
return true;
|
|
800
|
-
}
|
|
801
|
-
try {
|
|
802
|
-
const agentUrl = new URL(agentUrlStr);
|
|
803
|
-
const allowedHosts = ["chatgpt.com", "www.chatgpt.com"];
|
|
804
|
-
return allowedHosts.includes(agentUrl.host);
|
|
805
|
-
} catch {
|
|
806
|
-
return false;
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
var rules = loadRulesSync();
|
|
810
|
-
var EdgeAgentDetector = class {
|
|
811
|
-
rules;
|
|
812
|
-
constructor() {
|
|
813
|
-
this.rules = rules;
|
|
814
|
-
}
|
|
815
|
-
async analyze(input) {
|
|
816
|
-
const reasons = [];
|
|
817
|
-
let detectedAgent;
|
|
818
|
-
let verificationMethod;
|
|
819
|
-
let confidence = 0;
|
|
820
|
-
const headers = input.headers || {};
|
|
821
|
-
const normalizedHeaders = {};
|
|
822
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
823
|
-
normalizedHeaders[key.toLowerCase()] = value;
|
|
824
|
-
}
|
|
825
|
-
if (hasSignatureHeaders(headers)) {
|
|
826
|
-
try {
|
|
827
|
-
const signatureResult = await verifyAgentSignature(
|
|
828
|
-
input.method || "GET",
|
|
829
|
-
input.url || "/",
|
|
830
|
-
headers
|
|
831
|
-
);
|
|
832
|
-
if (signatureResult.isValid) {
|
|
833
|
-
confidence = signatureResult.confidence * 100;
|
|
834
|
-
reasons.push(`verified_signature:${signatureResult.agent?.toLowerCase() || "unknown"}`);
|
|
835
|
-
if (signatureResult.agent) {
|
|
836
|
-
detectedAgent = {
|
|
837
|
-
type: signatureResult.agent.toLowerCase(),
|
|
838
|
-
name: signatureResult.agent
|
|
839
|
-
};
|
|
840
|
-
}
|
|
841
|
-
verificationMethod = signatureResult.verificationMethod;
|
|
842
|
-
if (signatureResult.keyid) {
|
|
843
|
-
reasons.push(`keyid:${signatureResult.keyid}`);
|
|
844
|
-
}
|
|
845
|
-
} else {
|
|
846
|
-
console.warn("[EdgeAgentDetector] Signature verification failed:", {
|
|
847
|
-
reason: signatureResult.reason,
|
|
848
|
-
agent: signatureResult.agent,
|
|
849
|
-
hasSignatureAgent: !!headers["signature-agent"] || !!headers["Signature-Agent"],
|
|
850
|
-
signatureAgentValue: headers["signature-agent"] || headers["Signature-Agent"]
|
|
851
|
-
});
|
|
852
|
-
confidence = Math.max(confidence, 30);
|
|
853
|
-
reasons.push("invalid_signature");
|
|
854
|
-
if (signatureResult.reason) {
|
|
855
|
-
reasons.push(`signature_error:${signatureResult.reason}`);
|
|
856
|
-
}
|
|
857
|
-
if (isChatGPTSignature(headers)) {
|
|
858
|
-
reasons.push("claims_chatgpt");
|
|
859
|
-
detectedAgent = { type: "chatgpt", name: "ChatGPT (unverified)" };
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
} catch (error) {
|
|
863
|
-
console.error("[EdgeAgentDetector] Signature verification error:", error);
|
|
864
|
-
confidence = Math.max(confidence, 20);
|
|
865
|
-
reasons.push("signature_verification_error");
|
|
866
|
-
}
|
|
867
|
-
}
|
|
868
|
-
const userAgent = input.userAgent || input.headers?.["user-agent"] || "";
|
|
869
|
-
if (userAgent) {
|
|
870
|
-
const userAgentEntries = Object.entries(this.rules.rules.userAgents);
|
|
871
|
-
const genericKeys = ["generic_bot", "dev_tools", "automation_tools"];
|
|
872
|
-
const sortedEntries = userAgentEntries.sort((a, b) => {
|
|
873
|
-
const aIsGeneric = genericKeys.includes(a[0]);
|
|
874
|
-
const bIsGeneric = genericKeys.includes(b[0]);
|
|
875
|
-
if (aIsGeneric && !bIsGeneric) return 1;
|
|
876
|
-
if (!aIsGeneric && bIsGeneric) return -1;
|
|
877
|
-
return 0;
|
|
878
|
-
});
|
|
879
|
-
for (const [agentKey, agentRule] of sortedEntries) {
|
|
880
|
-
const rule = agentRule;
|
|
881
|
-
const matched = rule.patterns.some((pattern) => {
|
|
882
|
-
const regex = new RegExp(pattern, "i");
|
|
883
|
-
return regex.test(userAgent);
|
|
884
|
-
});
|
|
885
|
-
if (matched) {
|
|
886
|
-
const agentType = this.getAgentType(agentKey);
|
|
887
|
-
const agentName = this.getAgentName(agentKey);
|
|
888
|
-
confidence = Math.max(confidence, rule.confidence * 100);
|
|
889
|
-
reasons.push(`known_pattern:${agentType}`);
|
|
890
|
-
if (!detectedAgent) {
|
|
891
|
-
detectedAgent = { type: agentType, name: agentName };
|
|
892
|
-
verificationMethod = "pattern";
|
|
893
|
-
}
|
|
894
|
-
break;
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
|
-
const suspiciousHeaders = this.rules.rules.headers.suspicious;
|
|
899
|
-
const foundAiHeaders = suspiciousHeaders.filter(
|
|
900
|
-
(headerRule) => normalizedHeaders[headerRule.name.toLowerCase()]
|
|
901
|
-
);
|
|
902
|
-
if (foundAiHeaders.length > 0) {
|
|
903
|
-
const maxConfidence = Math.max(...foundAiHeaders.map((h) => h.confidence * 100));
|
|
904
|
-
confidence = Math.max(confidence, maxConfidence);
|
|
905
|
-
reasons.push(`ai_headers:${foundAiHeaders.length}`);
|
|
906
|
-
}
|
|
907
|
-
const ip = input.ip || input.ipAddress;
|
|
908
|
-
if (ip && !normalizedHeaders["x-forwarded-for"] && !normalizedHeaders["x-real-ip"]) {
|
|
909
|
-
const ipRanges = "providers" in this.rules.rules.ipRanges ? this.rules.rules.ipRanges.providers : this.rules.rules.ipRanges;
|
|
910
|
-
for (const [provider, ipRule] of Object.entries(ipRanges)) {
|
|
911
|
-
if (!ipRule || typeof ipRule !== "object" || !("ranges" in ipRule) || !Array.isArray(ipRule.ranges))
|
|
912
|
-
continue;
|
|
913
|
-
const matched = ipRule.ranges.some((range) => {
|
|
914
|
-
const prefix = range.split("/")[0];
|
|
915
|
-
const prefixParts = prefix.split(".");
|
|
916
|
-
const ipParts = ip.split(".");
|
|
917
|
-
for (let i = 0; i < Math.min(prefixParts.length - 1, 2); i++) {
|
|
918
|
-
if (prefixParts[i] !== ipParts[i] && prefixParts[i] !== "0") {
|
|
919
|
-
return false;
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
return true;
|
|
923
|
-
});
|
|
924
|
-
if (matched) {
|
|
925
|
-
const rule = ipRule;
|
|
926
|
-
confidence = Math.max(confidence, rule.confidence * 40);
|
|
927
|
-
reasons.push(`cloud_provider:${provider}`);
|
|
928
|
-
break;
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
if (reasons.length > 2 && confidence < 100) {
|
|
933
|
-
confidence = Math.min(confidence * 1.2, 95);
|
|
934
|
-
}
|
|
935
|
-
confidence = Math.min(Math.max(confidence, 0), 100);
|
|
936
|
-
return {
|
|
937
|
-
isAgent: confidence > 30,
|
|
938
|
-
// Updated to 0-100 scale (was 0.3)
|
|
939
|
-
confidence,
|
|
940
|
-
detectionClass: confidence > 30 && detectedAgent ? { type: "AiAgent", agentType: detectedAgent.name } : confidence > 30 ? { type: "Unknown" } : { type: "Human" },
|
|
941
|
-
signals: [],
|
|
942
|
-
// Will be populated by enhanced detection engine in future tasks
|
|
943
|
-
...detectedAgent && { detectedAgent },
|
|
944
|
-
reasons,
|
|
945
|
-
...verificationMethod && {
|
|
946
|
-
verificationMethod
|
|
947
|
-
},
|
|
948
|
-
forgeabilityRisk: verificationMethod === "signature" ? "low" : confidence > 80 ? "medium" : "high",
|
|
949
|
-
// Updated to 0-100 scale
|
|
950
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
951
|
-
};
|
|
952
|
-
}
|
|
953
|
-
/**
|
|
954
|
-
* Get agent type from rule key
|
|
955
|
-
*/
|
|
956
|
-
getAgentType(agentKey) {
|
|
957
|
-
const typeMap = {
|
|
958
|
-
openai_gptbot: "openai",
|
|
959
|
-
anthropic_claude: "anthropic",
|
|
960
|
-
perplexity_bot: "perplexity",
|
|
961
|
-
google_ai: "google",
|
|
962
|
-
microsoft_ai: "microsoft",
|
|
963
|
-
meta_ai: "meta",
|
|
964
|
-
cohere_bot: "cohere",
|
|
965
|
-
huggingface_bot: "huggingface",
|
|
966
|
-
generic_bot: "generic",
|
|
967
|
-
dev_tools: "dev",
|
|
968
|
-
automation_tools: "automation"
|
|
969
|
-
};
|
|
970
|
-
return typeMap[agentKey] || agentKey;
|
|
971
|
-
}
|
|
972
|
-
/**
|
|
973
|
-
* Get agent name from rule key
|
|
974
|
-
*/
|
|
975
|
-
getAgentName(agentKey) {
|
|
976
|
-
const nameMap = {
|
|
977
|
-
openai_gptbot: "ChatGPT/GPTBot",
|
|
978
|
-
anthropic_claude: "Claude",
|
|
979
|
-
perplexity_bot: "Perplexity",
|
|
980
|
-
google_ai: "Google AI",
|
|
981
|
-
microsoft_ai: "Microsoft Copilot",
|
|
982
|
-
meta_ai: "Meta AI",
|
|
983
|
-
cohere_bot: "Cohere",
|
|
984
|
-
huggingface_bot: "HuggingFace",
|
|
985
|
-
generic_bot: "Generic Bot",
|
|
986
|
-
dev_tools: "Development Tool",
|
|
987
|
-
automation_tools: "Automation Tool"
|
|
988
|
-
};
|
|
989
|
-
return nameMap[agentKey] || agentKey;
|
|
990
|
-
}
|
|
991
|
-
};
|
|
992
|
-
var EdgeAgentDetectorWrapper = class {
|
|
993
|
-
detector;
|
|
994
|
-
events = /* @__PURE__ */ new Map();
|
|
995
|
-
constructor(_config) {
|
|
996
|
-
this.detector = new EdgeAgentDetector();
|
|
997
|
-
}
|
|
998
|
-
async analyze(input) {
|
|
999
|
-
const result = await this.detector.analyze(input);
|
|
1000
|
-
if (result.isAgent && this.events.has("agent.detected")) {
|
|
1001
|
-
const handlers = this.events.get("agent.detected") || [];
|
|
1002
|
-
handlers.forEach((handler) => handler(result, input));
|
|
1003
|
-
}
|
|
1004
|
-
return result;
|
|
1005
|
-
}
|
|
1006
|
-
on(event, handler) {
|
|
1007
|
-
if (!this.events.has(event)) {
|
|
1008
|
-
this.events.set(event, []);
|
|
1009
|
-
}
|
|
1010
|
-
this.events.get(event).push(handler);
|
|
1011
|
-
}
|
|
1012
|
-
emit(event, ...args) {
|
|
1013
|
-
const handlers = this.events.get(event) || [];
|
|
1014
|
-
handlers.forEach((handler) => handler(...args));
|
|
1015
|
-
}
|
|
1016
|
-
async init() {
|
|
1017
|
-
return;
|
|
1018
|
-
}
|
|
1019
|
-
};
|
|
1020
|
-
var EdgeSessionTracker = class {
|
|
1021
|
-
config;
|
|
1022
|
-
constructor(config) {
|
|
1023
|
-
this.config = {
|
|
1024
|
-
enabled: config.enabled,
|
|
1025
|
-
cookieName: config.cookieName || "__agentshield_session",
|
|
1026
|
-
cookieMaxAge: config.cookieMaxAge || 3600,
|
|
1027
|
-
// 1 hour default
|
|
1028
|
-
encryptionKey: config.encryptionKey || process.env.AGENTSHIELD_SECRET || "agentshield-default-key"
|
|
1029
|
-
};
|
|
1030
|
-
}
|
|
1031
|
-
/**
|
|
1032
|
-
* Track a new AI agent session
|
|
1033
|
-
*/
|
|
1034
|
-
async track(_request, response, result) {
|
|
1035
|
-
try {
|
|
1036
|
-
if (!this.config.enabled || !shouldEnforce(result)) {
|
|
1037
|
-
return response;
|
|
1038
|
-
}
|
|
1039
|
-
const sessionData = {
|
|
1040
|
-
id: crypto.randomUUID(),
|
|
1041
|
-
agent: result.detectedAgent?.name || "unknown",
|
|
1042
|
-
confidence: result.confidence,
|
|
1043
|
-
detectedAt: Date.now(),
|
|
1044
|
-
expires: Date.now() + this.config.cookieMaxAge * 1e3
|
|
1045
|
-
};
|
|
1046
|
-
const encrypted = await this.encrypt(JSON.stringify(sessionData));
|
|
1047
|
-
response.cookies.set(this.config.cookieName, encrypted, {
|
|
1048
|
-
httpOnly: true,
|
|
1049
|
-
secure: process.env.NODE_ENV === "production",
|
|
1050
|
-
sameSite: "lax",
|
|
1051
|
-
maxAge: this.config.cookieMaxAge,
|
|
1052
|
-
path: "/"
|
|
1053
|
-
});
|
|
1054
|
-
return response;
|
|
1055
|
-
} catch (error) {
|
|
1056
|
-
if (process.env.DEBUG_AGENTSHIELD) {
|
|
1057
|
-
console.warn("AgentShield: Failed to track session:", error);
|
|
1058
|
-
}
|
|
1059
|
-
return response;
|
|
1060
|
-
}
|
|
1061
|
-
}
|
|
1062
|
-
/**
|
|
1063
|
-
* Check for existing AI agent session
|
|
1064
|
-
*/
|
|
1065
|
-
async check(request) {
|
|
1066
|
-
try {
|
|
1067
|
-
if (!this.config.enabled) {
|
|
1068
|
-
return null;
|
|
1069
|
-
}
|
|
1070
|
-
const cookie = request.cookies.get(this.config.cookieName);
|
|
1071
|
-
if (!cookie?.value) {
|
|
1072
|
-
return null;
|
|
1073
|
-
}
|
|
1074
|
-
const decrypted = await this.decrypt(cookie.value);
|
|
1075
|
-
const session = JSON.parse(decrypted);
|
|
1076
|
-
if (session.expires < Date.now()) {
|
|
1077
|
-
return null;
|
|
1078
|
-
}
|
|
1079
|
-
return session;
|
|
1080
|
-
} catch (error) {
|
|
1081
|
-
if (process.env.DEBUG_AGENTSHIELD) {
|
|
1082
|
-
console.warn("AgentShield: Failed to check session:", error);
|
|
1083
|
-
}
|
|
1084
|
-
return null;
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1087
|
-
/**
|
|
1088
|
-
* Clear an existing session
|
|
1089
|
-
*/
|
|
1090
|
-
clear(response) {
|
|
1091
|
-
try {
|
|
1092
|
-
response.cookies.delete(this.config.cookieName);
|
|
1093
|
-
} catch (error) {
|
|
1094
|
-
if (process.env.DEBUG_AGENTSHIELD) {
|
|
1095
|
-
console.warn("AgentShield: Failed to clear session:", error);
|
|
1096
|
-
}
|
|
1097
|
-
}
|
|
1098
|
-
return response;
|
|
1099
|
-
}
|
|
1100
|
-
/**
|
|
1101
|
-
* Simple encryption using Web Crypto API (Edge-compatible)
|
|
1102
|
-
*/
|
|
1103
|
-
async encrypt(data) {
|
|
1104
|
-
try {
|
|
1105
|
-
const key = this.config.encryptionKey;
|
|
1106
|
-
const encoded = new TextEncoder().encode(data);
|
|
1107
|
-
const obfuscated = new Uint8Array(encoded.length);
|
|
1108
|
-
for (let i = 0; i < encoded.length; i++) {
|
|
1109
|
-
obfuscated[i] = (encoded[i] || 0) ^ key.charCodeAt(i % key.length);
|
|
1110
|
-
}
|
|
1111
|
-
return btoa(Array.from(obfuscated, (byte) => String.fromCharCode(byte)).join(""));
|
|
1112
|
-
} catch (error) {
|
|
1113
|
-
return btoa(data);
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
/**
|
|
1117
|
-
* Simple decryption (Edge-compatible)
|
|
1118
|
-
*/
|
|
1119
|
-
async decrypt(data) {
|
|
1120
|
-
try {
|
|
1121
|
-
const key = this.config.encryptionKey;
|
|
1122
|
-
const decoded = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
|
|
1123
|
-
const deobfuscated = new Uint8Array(decoded.length);
|
|
1124
|
-
for (let i = 0; i < decoded.length; i++) {
|
|
1125
|
-
deobfuscated[i] = (decoded[i] || 0) ^ key.charCodeAt(i % key.length);
|
|
1126
|
-
}
|
|
1127
|
-
return new TextDecoder().decode(deobfuscated);
|
|
1128
|
-
} catch (error) {
|
|
1129
|
-
return atob(data);
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
};
|
|
1133
|
-
|
|
1134
|
-
// src/utils.ts
|
|
1135
|
-
function getClientIp(request) {
|
|
1136
|
-
const forwardedFor = request.headers.get("x-forwarded-for");
|
|
1137
|
-
if (forwardedFor) {
|
|
1138
|
-
const ip = forwardedFor.split(",")[0]?.trim();
|
|
1139
|
-
if (ip) return ip;
|
|
1140
|
-
}
|
|
1141
|
-
const realIp = request.headers.get("x-real-ip");
|
|
1142
|
-
if (realIp) return realIp;
|
|
1143
|
-
const cfIp = request.headers.get("cf-connecting-ip");
|
|
1144
|
-
if (cfIp) return cfIp;
|
|
1145
|
-
const clientIp = request.headers.get("x-client-ip");
|
|
1146
|
-
if (clientIp) return clientIp;
|
|
1147
|
-
return void 0;
|
|
1148
|
-
}
|
|
1149
|
-
function createAgentShieldMiddleware(config = {}) {
|
|
1150
|
-
let detector = config.enableWasm ? null : new EdgeAgentDetectorWrapper(config);
|
|
1151
|
-
let detectorInitPromise = null;
|
|
1152
|
-
const sessionTracker = config.sessionTracking?.enabled || config.enableWasm ? new EdgeSessionTracker({
|
|
1153
|
-
enabled: true,
|
|
1154
|
-
...config.sessionTracking
|
|
1155
|
-
}) : null;
|
|
1156
|
-
if (detector && config.events) {
|
|
1157
|
-
Object.entries(config.events).forEach(([event, handler]) => {
|
|
1158
|
-
if (handler) {
|
|
1159
|
-
detector.on(event, handler);
|
|
1160
|
-
}
|
|
1161
|
-
});
|
|
1162
|
-
}
|
|
1163
|
-
const {
|
|
1164
|
-
onAgentDetected = "log",
|
|
1165
|
-
onDetection,
|
|
1166
|
-
skipPaths = [],
|
|
1167
|
-
blockedResponse = {
|
|
1168
|
-
status: 403,
|
|
1169
|
-
message: "Access denied: Automated agent detected",
|
|
1170
|
-
headers: { "Content-Type": "application/json" }
|
|
1171
|
-
},
|
|
1172
|
-
redirectUrl = "/blocked",
|
|
1173
|
-
rewriteUrl = "/blocked"
|
|
1174
|
-
} = config;
|
|
1175
|
-
return async (request) => {
|
|
1176
|
-
try {
|
|
1177
|
-
if (!detector) {
|
|
1178
|
-
if (!detectorInitPromise) {
|
|
1179
|
-
detectorInitPromise = (async () => {
|
|
1180
|
-
const { EdgeAgentDetectorWrapperWithWasm: EdgeAgentDetectorWrapperWithWasm2 } = await Promise.resolve().then(() => (init_edge_detector_with_wasm(), edge_detector_with_wasm_exports));
|
|
1181
|
-
detector = new EdgeAgentDetectorWrapperWithWasm2({ enableWasm: true });
|
|
1182
|
-
if (config.events) {
|
|
1183
|
-
Object.entries(config.events).forEach(([event, handler]) => {
|
|
1184
|
-
if (handler) {
|
|
1185
|
-
detector.on(event, handler);
|
|
1186
|
-
}
|
|
1187
|
-
});
|
|
1188
|
-
}
|
|
1189
|
-
})();
|
|
1190
|
-
}
|
|
1191
|
-
await detectorInitPromise;
|
|
1192
|
-
}
|
|
1193
|
-
const activeDetector = detector;
|
|
1194
|
-
const shouldSkip = skipPaths.some((pattern) => {
|
|
1195
|
-
if (typeof pattern === "string") {
|
|
1196
|
-
return request.nextUrl.pathname.startsWith(pattern);
|
|
1197
|
-
}
|
|
1198
|
-
return pattern.test(request.nextUrl.pathname);
|
|
1199
|
-
});
|
|
1200
|
-
if (shouldSkip) {
|
|
1201
|
-
request.agentShield = { skipped: true };
|
|
1202
|
-
return NextResponse.next();
|
|
1203
|
-
}
|
|
1204
|
-
const existingSession = sessionTracker ? await sessionTracker.check(request) : null;
|
|
1205
|
-
if (existingSession) {
|
|
1206
|
-
const response2 = NextResponse.next();
|
|
1207
|
-
response2.headers.set("kya-detected", "true");
|
|
1208
|
-
response2.headers.set("kya-agent", existingSession.agent);
|
|
1209
|
-
response2.headers.set("kya-confidence", existingSession.confidence.toString());
|
|
1210
|
-
response2.headers.set("kya-session", "continued");
|
|
1211
|
-
response2.headers.set("kya-session-id", existingSession.id);
|
|
1212
|
-
request.agentShield = {
|
|
1213
|
-
result: {
|
|
1214
|
-
isAgent: true,
|
|
1215
|
-
confidence: existingSession.confidence,
|
|
1216
|
-
detectionClass: { type: "AiAgent" },
|
|
1217
|
-
detectedAgent: {
|
|
1218
|
-
type: "ai_agent",
|
|
1219
|
-
name: existingSession.agent
|
|
1220
|
-
},
|
|
1221
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
1222
|
-
verificationMethod: "behavioral",
|
|
1223
|
-
reasons: ["Session continued"],
|
|
1224
|
-
signals: []
|
|
1225
|
-
},
|
|
1226
|
-
session: existingSession,
|
|
1227
|
-
skipped: false
|
|
1228
|
-
};
|
|
1229
|
-
const context2 = {
|
|
1230
|
-
userAgent: request.headers.get("user-agent") || "",
|
|
1231
|
-
ipAddress: getClientIp(request) || "",
|
|
1232
|
-
headers: Object.fromEntries(request.headers.entries()),
|
|
1233
|
-
url: request.url,
|
|
1234
|
-
method: request.method,
|
|
1235
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
1236
|
-
};
|
|
1237
|
-
activeDetector.emit("agent.session.continued", existingSession, context2);
|
|
1238
|
-
return response2;
|
|
1239
|
-
}
|
|
1240
|
-
const userAgent = request.headers.get("user-agent");
|
|
1241
|
-
const ipAddress = getClientIp(request);
|
|
1242
|
-
const url = new URL(request.url);
|
|
1243
|
-
const pathWithQuery = url.pathname + url.search;
|
|
1244
|
-
const context = {
|
|
1245
|
-
...userAgent && { userAgent },
|
|
1246
|
-
...ipAddress && { ipAddress },
|
|
1247
|
-
headers: Object.fromEntries(request.headers.entries()),
|
|
1248
|
-
url: pathWithQuery,
|
|
1249
|
-
// Use path instead of full URL for signature verification
|
|
1250
|
-
method: request.method,
|
|
1251
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
1252
|
-
};
|
|
1253
|
-
const result = await activeDetector.analyze(context);
|
|
1254
|
-
const decision = evaluateEnforcement(result, {
|
|
1255
|
-
confidenceThreshold: config.confidenceThreshold,
|
|
1256
|
-
defaultAction: onAgentDetected
|
|
1257
|
-
});
|
|
1258
|
-
if (decision.shouldNotify) {
|
|
1259
|
-
if (onDetection) {
|
|
1260
|
-
const customResponse = await onDetection(request, result);
|
|
1261
|
-
if (customResponse) {
|
|
1262
|
-
return customResponse;
|
|
1263
|
-
}
|
|
1264
|
-
}
|
|
1265
|
-
switch (decision.action) {
|
|
1266
|
-
case "block": {
|
|
1267
|
-
const response2 = NextResponse.json(
|
|
1268
|
-
{
|
|
1269
|
-
error: blockedResponse.message,
|
|
1270
|
-
detected: true,
|
|
1271
|
-
confidence: result.confidence,
|
|
1272
|
-
timestamp: result.timestamp
|
|
1273
|
-
},
|
|
1274
|
-
{ status: blockedResponse.status }
|
|
1275
|
-
);
|
|
1276
|
-
if (blockedResponse.headers) {
|
|
1277
|
-
Object.entries(blockedResponse.headers).forEach(([key, value]) => {
|
|
1278
|
-
response2.headers.set(key, value);
|
|
1279
|
-
});
|
|
1280
|
-
}
|
|
1281
|
-
activeDetector.emit("agent.blocked", result, context);
|
|
1282
|
-
return response2;
|
|
1283
|
-
}
|
|
1284
|
-
case "redirect": {
|
|
1285
|
-
const redirectTarget = new URL(redirectUrl, request.url);
|
|
1286
|
-
const agentName = result.detectedAgent?.name;
|
|
1287
|
-
if (agentName && !redirectTarget.searchParams.has("agent")) {
|
|
1288
|
-
redirectTarget.searchParams.set("agent", agentName.toLowerCase());
|
|
1289
|
-
}
|
|
1290
|
-
return NextResponse.redirect(redirectTarget);
|
|
1291
|
-
}
|
|
1292
|
-
case "rewrite":
|
|
1293
|
-
return NextResponse.rewrite(new URL(rewriteUrl, request.url));
|
|
1294
|
-
case "log":
|
|
1295
|
-
if (process.env.NODE_ENV !== "production") {
|
|
1296
|
-
console.debug("AgentShield: Agent detected", {
|
|
1297
|
-
ipAddress: context.ipAddress,
|
|
1298
|
-
userAgent: context.userAgent,
|
|
1299
|
-
confidence: result.confidence,
|
|
1300
|
-
reasons: result.reasons,
|
|
1301
|
-
pathname: request.nextUrl.pathname
|
|
1302
|
-
});
|
|
1303
|
-
}
|
|
1304
|
-
break;
|
|
1305
|
-
case "allow":
|
|
1306
|
-
default:
|
|
1307
|
-
activeDetector.emit("agent.allowed", result, context);
|
|
1308
|
-
break;
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
request.agentShield = {
|
|
1312
|
-
result,
|
|
1313
|
-
skipped: false
|
|
1314
|
-
};
|
|
1315
|
-
let response = NextResponse.next();
|
|
1316
|
-
response.headers.set("kya-detected", result.isAgent.toString());
|
|
1317
|
-
response.headers.set("kya-confidence", result.confidence.toString());
|
|
1318
|
-
if (result.detectedAgent?.name) {
|
|
1319
|
-
response.headers.set("kya-agent", result.detectedAgent.name);
|
|
1320
|
-
}
|
|
1321
|
-
if (sessionTracker && decision.shouldNotify) {
|
|
1322
|
-
response = await sessionTracker.track(request, response, result);
|
|
1323
|
-
response.headers.set("kya-session", "new");
|
|
1324
|
-
activeDetector.emit("agent.session.started", result, context);
|
|
1325
|
-
}
|
|
1326
|
-
return response;
|
|
1327
|
-
} catch (error) {
|
|
1328
|
-
console.error("AgentShield middleware error:", error);
|
|
1329
|
-
return NextResponse.next();
|
|
1330
|
-
}
|
|
1331
|
-
};
|
|
1332
|
-
}
|
|
1333
|
-
function agentShield(config = {}) {
|
|
1334
|
-
return createAgentShieldMiddleware(config);
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
export { agentShield, createAgentShieldMiddleware };
|
|
1338
|
-
//# sourceMappingURL=middleware.mjs.map
|
|
1339
|
-
//# sourceMappingURL=middleware.mjs.map
|