@kya-os/agentshield-nextjs 0.1.30 → 0.1.32

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.
@@ -4,6 +4,219 @@ var server = require('next/server');
4
4
 
5
5
  // src/create-middleware.ts
6
6
 
7
+ // src/signature-verifier.ts
8
+ var KNOWN_KEYS = {
9
+ chatgpt: [
10
+ {
11
+ kid: "otMqcjr17mGyruktGvJU8oojQTSMHlVm7uO-lrcqbdg",
12
+ // ChatGPT's current Ed25519 public key (base64)
13
+ publicKey: "7F_3jDlxaquwh291MiACkcS3Opq88NksyHiakzS-Y1g",
14
+ validFrom: (/* @__PURE__ */ new Date("2025-01-01")).getTime() / 1e3,
15
+ validUntil: (/* @__PURE__ */ new Date("2025-04-11")).getTime() / 1e3
16
+ }
17
+ ]
18
+ };
19
+ function parseSignatureInput(signatureInput) {
20
+ try {
21
+ const match = signatureInput.match(/sig1=\((.*?)\);(.+)/);
22
+ if (!match) return null;
23
+ const [, headersList, params] = match;
24
+ const signedHeaders = headersList ? headersList.split(" ").map((h) => h.replace(/"/g, "").trim()).filter((h) => h.length > 0) : [];
25
+ const keyidMatch = params ? params.match(/keyid="([^"]+)"/) : null;
26
+ const createdMatch = params ? params.match(/created=(\d+)/) : null;
27
+ const expiresMatch = params ? params.match(/expires=(\d+)/) : null;
28
+ if (!keyidMatch || !keyidMatch[1]) return null;
29
+ return {
30
+ keyid: keyidMatch[1],
31
+ created: createdMatch && createdMatch[1] ? parseInt(createdMatch[1]) : void 0,
32
+ expires: expiresMatch && expiresMatch[1] ? parseInt(expiresMatch[1]) : void 0,
33
+ signedHeaders
34
+ };
35
+ } catch (error) {
36
+ console.error("[Signature] Failed to parse Signature-Input:", error);
37
+ return null;
38
+ }
39
+ }
40
+ function buildSignatureBase(method, path, headers, signedHeaders) {
41
+ const components = [];
42
+ for (const headerName of signedHeaders) {
43
+ let value;
44
+ switch (headerName) {
45
+ case "@method":
46
+ value = method.toUpperCase();
47
+ break;
48
+ case "@path":
49
+ value = path;
50
+ break;
51
+ case "@authority":
52
+ value = headers["host"] || headers["Host"] || "";
53
+ break;
54
+ default:
55
+ const key = Object.keys(headers).find(
56
+ (k) => k.toLowerCase() === headerName.toLowerCase()
57
+ );
58
+ value = key ? headers[key] || "" : "";
59
+ break;
60
+ }
61
+ components.push(`"${headerName}": ${value}`);
62
+ }
63
+ return components.join("\n");
64
+ }
65
+ async function verifyEd25519Signature(publicKeyBase64, signatureBase64, message) {
66
+ try {
67
+ const publicKeyBytes = Uint8Array.from(atob(publicKeyBase64), (c) => c.charCodeAt(0));
68
+ const signatureBytes = Uint8Array.from(atob(signatureBase64), (c) => c.charCodeAt(0));
69
+ const messageBytes = new TextEncoder().encode(message);
70
+ if (publicKeyBytes.length !== 32) {
71
+ console.error("[Signature] Invalid public key length:", publicKeyBytes.length);
72
+ return false;
73
+ }
74
+ if (signatureBytes.length !== 64) {
75
+ console.error("[Signature] Invalid signature length:", signatureBytes.length);
76
+ return false;
77
+ }
78
+ const publicKey = await crypto.subtle.importKey(
79
+ "raw",
80
+ publicKeyBytes,
81
+ {
82
+ name: "Ed25519",
83
+ namedCurve: "Ed25519"
84
+ },
85
+ false,
86
+ ["verify"]
87
+ );
88
+ const isValid = await crypto.subtle.verify(
89
+ "Ed25519",
90
+ publicKey,
91
+ signatureBytes,
92
+ messageBytes
93
+ );
94
+ return isValid;
95
+ } catch (error) {
96
+ console.error("[Signature] Ed25519 verification failed:", error);
97
+ if (typeof window === "undefined") {
98
+ try {
99
+ console.warn("[Signature] Ed25519 not supported in this environment");
100
+ return false;
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+ return false;
106
+ }
107
+ }
108
+ async function verifyAgentSignature(method, path, headers) {
109
+ const signature = headers["signature"] || headers["Signature"];
110
+ const signatureInput = headers["signature-input"] || headers["Signature-Input"];
111
+ const signatureAgent = headers["signature-agent"] || headers["Signature-Agent"];
112
+ if (!signature || !signatureInput) {
113
+ return {
114
+ isValid: false,
115
+ confidence: 0,
116
+ reason: "No signature headers present",
117
+ verificationMethod: "none"
118
+ };
119
+ }
120
+ const parsed = parseSignatureInput(signatureInput);
121
+ if (!parsed) {
122
+ return {
123
+ isValid: false,
124
+ confidence: 0,
125
+ reason: "Invalid Signature-Input header",
126
+ verificationMethod: "none"
127
+ };
128
+ }
129
+ if (parsed.created) {
130
+ const now2 = Math.floor(Date.now() / 1e3);
131
+ const age = now2 - parsed.created;
132
+ if (age > 300) {
133
+ return {
134
+ isValid: false,
135
+ confidence: 0,
136
+ reason: "Signature expired (older than 5 minutes)",
137
+ verificationMethod: "none"
138
+ };
139
+ }
140
+ if (age < -30) {
141
+ return {
142
+ isValid: false,
143
+ confidence: 0,
144
+ reason: "Signature timestamp is in the future",
145
+ verificationMethod: "none"
146
+ };
147
+ }
148
+ }
149
+ let agent;
150
+ let knownKeys;
151
+ if (signatureAgent === '"https://chatgpt.com"' || signatureAgent?.includes("chatgpt.com")) {
152
+ agent = "ChatGPT";
153
+ knownKeys = KNOWN_KEYS.chatgpt;
154
+ }
155
+ if (!agent || !knownKeys) {
156
+ return {
157
+ isValid: false,
158
+ confidence: 0,
159
+ reason: "Unknown signature agent",
160
+ verificationMethod: "none"
161
+ };
162
+ }
163
+ const key = knownKeys.find((k) => k.kid === parsed.keyid);
164
+ if (!key) {
165
+ return {
166
+ isValid: false,
167
+ confidence: 0,
168
+ reason: `Unknown key ID: ${parsed.keyid}`,
169
+ verificationMethod: "none"
170
+ };
171
+ }
172
+ const now = Math.floor(Date.now() / 1e3);
173
+ if (now < key.validFrom || now > key.validUntil) {
174
+ return {
175
+ isValid: false,
176
+ confidence: 0,
177
+ reason: "Key is not valid at current time",
178
+ verificationMethod: "none"
179
+ };
180
+ }
181
+ const signatureBase = buildSignatureBase(method, path, headers, parsed.signedHeaders);
182
+ let signatureValue = signature;
183
+ if (signatureValue.startsWith("sig1=:")) {
184
+ signatureValue = signatureValue.substring(6);
185
+ }
186
+ if (signatureValue.endsWith(":")) {
187
+ signatureValue = signatureValue.slice(0, -1);
188
+ }
189
+ const isValid = await verifyEd25519Signature(
190
+ key.publicKey,
191
+ signatureValue,
192
+ signatureBase
193
+ );
194
+ if (isValid) {
195
+ return {
196
+ isValid: true,
197
+ agent,
198
+ keyid: parsed.keyid,
199
+ confidence: 1,
200
+ // 100% confidence for valid signature
201
+ verificationMethod: "signature"
202
+ };
203
+ } else {
204
+ return {
205
+ isValid: false,
206
+ confidence: 0,
207
+ reason: "Signature verification failed",
208
+ verificationMethod: "none"
209
+ };
210
+ }
211
+ }
212
+ function hasSignatureHeaders(headers) {
213
+ return !!((headers["signature"] || headers["Signature"]) && (headers["signature-input"] || headers["Signature-Input"]));
214
+ }
215
+ function isChatGPTSignature(headers) {
216
+ const signatureAgent = headers["signature-agent"] || headers["Signature-Agent"];
217
+ return signatureAgent === '"https://chatgpt.com"' || (signatureAgent?.includes("chatgpt.com") || false);
218
+ }
219
+
7
220
  // src/edge-detector-wrapper.ts
8
221
  var AI_AGENT_PATTERNS = [
9
222
  { pattern: /chatgpt-user/i, type: "chatgpt", name: "ChatGPT" },
@@ -32,16 +245,42 @@ var EdgeAgentDetector = class {
32
245
  for (const [key, value] of Object.entries(headers)) {
33
246
  normalizedHeaders[key.toLowerCase()] = value;
34
247
  }
35
- const signaturePresent = !!(normalizedHeaders["signature"] || normalizedHeaders["signature-input"]);
36
- const signatureAgent = normalizedHeaders["signature-agent"];
37
- if (signatureAgent?.includes("chatgpt.com")) {
38
- confidence = 0.85;
39
- reasons.push("signature_agent:chatgpt");
40
- detectedAgent = { type: "chatgpt", name: "ChatGPT" };
41
- verificationMethod = "signature";
42
- } else if (signaturePresent) {
43
- confidence = Math.max(confidence, 0.4);
44
- reasons.push("signature_present");
248
+ if (hasSignatureHeaders(headers)) {
249
+ try {
250
+ const signatureResult = await verifyAgentSignature(
251
+ input.method || "GET",
252
+ input.url || "/",
253
+ headers
254
+ );
255
+ if (signatureResult.isValid) {
256
+ confidence = signatureResult.confidence;
257
+ reasons.push(`verified_signature:${signatureResult.agent?.toLowerCase() || "unknown"}`);
258
+ if (signatureResult.agent) {
259
+ detectedAgent = {
260
+ type: signatureResult.agent.toLowerCase(),
261
+ name: signatureResult.agent
262
+ };
263
+ }
264
+ verificationMethod = signatureResult.verificationMethod;
265
+ if (signatureResult.keyid) {
266
+ reasons.push(`keyid:${signatureResult.keyid}`);
267
+ }
268
+ } else {
269
+ confidence = Math.max(confidence, 0.3);
270
+ reasons.push("invalid_signature");
271
+ if (signatureResult.reason) {
272
+ reasons.push(`signature_error:${signatureResult.reason}`);
273
+ }
274
+ if (isChatGPTSignature(headers)) {
275
+ reasons.push("claims_chatgpt");
276
+ detectedAgent = { type: "chatgpt", name: "ChatGPT (unverified)" };
277
+ }
278
+ }
279
+ } catch (error) {
280
+ console.error("[EdgeAgentDetector] Signature verification error:", error);
281
+ confidence = Math.max(confidence, 0.2);
282
+ reasons.push("signature_verification_error");
283
+ }
45
284
  }
46
285
  const userAgent = input.userAgent || input.headers?.["user-agent"] || "";
47
286
  if (userAgent) {
@@ -88,7 +327,7 @@ var EdgeAgentDetector = class {
88
327
  }
89
328
  }
90
329
  }
91
- if (reasons.length > 2) {
330
+ if (reasons.length > 2 && confidence < 1) {
92
331
  confidence = Math.min(confidence * 1.2, 0.95);
93
332
  }
94
333
  return {
@@ -97,7 +336,7 @@ var EdgeAgentDetector = class {
97
336
  ...detectedAgent && { detectedAgent },
98
337
  reasons,
99
338
  ...verificationMethod && { verificationMethod },
100
- forgeabilityRisk: confidence > 0.8 ? "medium" : "high",
339
+ forgeabilityRisk: verificationMethod === "signature" ? "low" : confidence > 0.8 ? "medium" : "high",
101
340
  timestamp: /* @__PURE__ */ new Date()
102
341
  };
103
342
  }
@@ -144,6 +383,34 @@ async function initWasm() {
144
383
  }
145
384
  initPromise = (async () => {
146
385
  try {
386
+ if (typeof WebAssembly.instantiateStreaming === "function") {
387
+ try {
388
+ const response2 = await fetch(WASM_PATH);
389
+ if (!response2.ok) {
390
+ throw new Error(`Failed to fetch WASM: ${response2.status}`);
391
+ }
392
+ const streamResponse = response2.clone();
393
+ const { instance } = await WebAssembly.instantiateStreaming(
394
+ streamResponse,
395
+ {
396
+ wbg: {
397
+ __wbg_log_1d3ae13c3d5e6b8e: (ptr, len) => {
398
+ console.log("WASM:", ptr, len);
399
+ },
400
+ __wbindgen_throw: (ptr, len) => {
401
+ throw new Error(`WASM Error at ${ptr}, length ${len}`);
402
+ }
403
+ }
404
+ }
405
+ );
406
+ wasmInstance = instance;
407
+ wasmExports = instance.exports;
408
+ console.log("[AgentShield] \u2705 WASM module initialized with streaming");
409
+ return;
410
+ } catch (streamError) {
411
+ console.log("[AgentShield] Streaming compilation failed, falling back to standard compilation");
412
+ }
413
+ }
147
414
  const response = await fetch(WASM_PATH);
148
415
  if (!response.ok) {
149
416
  throw new Error(`Failed to fetch WASM: ${response.status}`);
@@ -628,11 +895,14 @@ function createAgentShieldMiddleware(config = {}) {
628
895
  }
629
896
  const userAgent = request.headers.get("user-agent");
630
897
  const ipAddress = request.ip ?? request.headers.get("x-forwarded-for");
898
+ const url = new URL(request.url);
899
+ const pathWithQuery = url.pathname + url.search;
631
900
  const context = {
632
901
  ...userAgent && { userAgent },
633
902
  ...ipAddress && { ipAddress },
634
903
  headers: Object.fromEntries(request.headers.entries()),
635
- url: request.url,
904
+ url: pathWithQuery,
905
+ // Use path instead of full URL for signature verification
636
906
  method: request.method,
637
907
  timestamp: /* @__PURE__ */ new Date()
638
908
  };