@kya-os/checkpoint-wasm-runtime 1.0.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/adapters.d.mts +257 -0
  3. package/dist/adapters.d.ts +257 -0
  4. package/dist/adapters.js +603 -0
  5. package/dist/adapters.js.map +1 -0
  6. package/dist/adapters.mjs +586 -0
  7. package/dist/adapters.mjs.map +1 -0
  8. package/dist/dynamic-loader-cS-pUisw.d.ts +65 -0
  9. package/dist/dynamic-loader-qGJacfEC.d.mts +65 -0
  10. package/dist/edge.d.mts +22 -0
  11. package/dist/edge.d.ts +22 -0
  12. package/dist/edge.js +1403 -0
  13. package/dist/edge.js.map +1 -0
  14. package/dist/edge.mjs +1391 -0
  15. package/dist/edge.mjs.map +1 -0
  16. package/dist/engine-edge.d.mts +58 -0
  17. package/dist/engine-edge.d.ts +58 -0
  18. package/dist/engine-edge.js +537 -0
  19. package/dist/engine-edge.js.map +1 -0
  20. package/dist/engine-edge.mjs +533 -0
  21. package/dist/engine-edge.mjs.map +1 -0
  22. package/dist/engine.d.mts +34 -0
  23. package/dist/engine.d.ts +34 -0
  24. package/dist/engine.js +11 -0
  25. package/dist/engine.js.map +1 -0
  26. package/dist/engine.mjs +9 -0
  27. package/dist/engine.mjs.map +1 -0
  28. package/dist/index.d.mts +58 -0
  29. package/dist/index.d.ts +58 -0
  30. package/dist/index.js +1652 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/index.mjs +1637 -0
  33. package/dist/index.mjs.map +1 -0
  34. package/dist/node.d.mts +26 -0
  35. package/dist/node.d.ts +26 -0
  36. package/dist/node.js +972 -0
  37. package/dist/node.js.map +1 -0
  38. package/dist/node.mjs +960 -0
  39. package/dist/node.mjs.map +1 -0
  40. package/dist/orchestrator-edge.d.mts +243 -0
  41. package/dist/orchestrator-edge.d.ts +243 -0
  42. package/dist/orchestrator-edge.js +1076 -0
  43. package/dist/orchestrator-edge.js.map +1 -0
  44. package/dist/orchestrator-edge.mjs +1065 -0
  45. package/dist/orchestrator-edge.mjs.map +1 -0
  46. package/dist/orchestrator.d.mts +50 -0
  47. package/dist/orchestrator.d.ts +50 -0
  48. package/dist/orchestrator.js +1185 -0
  49. package/dist/orchestrator.js.map +1 -0
  50. package/dist/orchestrator.mjs +1172 -0
  51. package/dist/orchestrator.mjs.map +1 -0
  52. package/dist/rules-detector-DjbTJ1-Q.d.mts +470 -0
  53. package/dist/rules-detector-DjbTJ1-Q.d.ts +470 -0
  54. package/dist/static-loader-C1hUlksK.d.ts +72 -0
  55. package/dist/static-loader-Ds4iNw7c.d.mts +72 -0
  56. package/dist/types-D0j85fF0.d.mts +163 -0
  57. package/dist/types-D0j85fF0.d.ts +163 -0
  58. package/package.json +141 -0
  59. package/wasm/agentshield_wasm.d.ts +485 -0
  60. package/wasm/agentshield_wasm.js +1551 -0
  61. package/wasm/agentshield_wasm_bg.wasm +0 -0
  62. package/wasm/agentshield_wasm_bg.wasm.d.ts +97 -0
  63. package/wasm/kya-os-engine/kya_os_engine.d.ts +24 -0
  64. package/wasm/kya-os-engine/kya_os_engine.js +517 -0
  65. package/wasm/kya-os-engine/kya_os_engine_bg.wasm +0 -0
  66. package/wasm/kya-os-engine/kya_os_engine_bg.wasm.d.ts +8 -0
  67. package/wasm/kya-os-engine-web/kya_os_engine.d.ts +56 -0
  68. package/wasm/kya-os-engine-web/kya_os_engine.js +574 -0
  69. package/wasm/kya-os-engine-web/kya_os_engine_bg.wasm +0 -0
  70. package/wasm/kya-os-engine-web/kya_os_engine_bg.wasm.d.ts +8 -0
  71. package/wasm/package.json +30 -0
package/dist/edge.mjs ADDED
@@ -0,0 +1,1391 @@
1
+ import { loadRulesSync } from '@kya-os/checkpoint-shared';
2
+
3
+ // src/types.ts
4
+ var CONFIDENCE = {
5
+ /** Minimum confidence for isAgent=true */
6
+ THRESHOLD_AGENT: 30,
7
+ /** Cryptographic signature verified */
8
+ SIGNATURE_VERIFIED: 100,
9
+ /** Signature header present but not verified */
10
+ SIGNATURE_PRESENT: 85,
11
+ /** Strong pattern match */
12
+ PATTERN_HIGH: 85,
13
+ /** Moderate pattern match */
14
+ PATTERN_MEDIUM: 60,
15
+ /** Weak pattern match */
16
+ PATTERN_LOW: 40,
17
+ /** Cloud IP detection only */
18
+ CLOUD_IP: 30
19
+ };
20
+
21
+ // src/wasm-detector.ts
22
+ function parseVerificationMethod(method) {
23
+ switch (method.toLowerCase()) {
24
+ case "signature":
25
+ return "signature";
26
+ case "pattern":
27
+ return "pattern";
28
+ case "behavioral":
29
+ return "behavioral";
30
+ case "network":
31
+ return "network";
32
+ case "mcp_i_handshake":
33
+ return "mcp_i_handshake";
34
+ default:
35
+ return "none";
36
+ }
37
+ }
38
+ function determineForgeabilityRisk(method, confidence) {
39
+ if (method === "signature" && confidence >= 90) {
40
+ return "low";
41
+ }
42
+ if (confidence >= 80) {
43
+ return "medium";
44
+ }
45
+ return "high";
46
+ }
47
+ function determineDetectionClass(isAgent, agentName, confidence) {
48
+ if (!isAgent || confidence < CONFIDENCE.THRESHOLD_AGENT) {
49
+ return { type: "Human" };
50
+ }
51
+ if (agentName) {
52
+ const aiAgentPatterns = [
53
+ "chatgpt",
54
+ "gpt",
55
+ "openai",
56
+ "claude",
57
+ "anthropic",
58
+ "perplexity",
59
+ "gemini",
60
+ "google ai",
61
+ "copilot",
62
+ "bing chat"
63
+ ];
64
+ const lowerName = agentName.toLowerCase();
65
+ if (aiAgentPatterns.some((pattern) => lowerName.includes(pattern))) {
66
+ return { type: "AiAgent", agentType: agentName };
67
+ }
68
+ const botPatterns = ["bot", "crawler", "spider", "scraper"];
69
+ if (botPatterns.some((pattern) => lowerName.includes(pattern))) {
70
+ return { type: "Bot", botType: agentName };
71
+ }
72
+ const automationPatterns = ["selenium", "puppeteer", "playwright", "cypress"];
73
+ if (automationPatterns.some((pattern) => lowerName.includes(pattern))) {
74
+ return { type: "Automation", toolType: agentName };
75
+ }
76
+ return { type: "AiAgent", agentType: agentName };
77
+ }
78
+ return { type: "Unknown" };
79
+ }
80
+ var WasmDetector = class {
81
+ /**
82
+ * Create a new WasmDetector
83
+ * @param loader - WASM loader (static for Edge, dynamic for Node.js)
84
+ * @param policyLoader - Optional policy loader for API key support
85
+ * @param options - Detector configuration options
86
+ */
87
+ constructor(loader, policyLoader, options = {}) {
88
+ this.loader = loader;
89
+ this.policyLoader = policyLoader;
90
+ this.options = options;
91
+ }
92
+ ready = false;
93
+ loadPromise = null;
94
+ /**
95
+ * Analyze a request and detect if it's from an agent
96
+ */
97
+ async detect(input) {
98
+ await this.ensureReady();
99
+ try {
100
+ const bindings = this.loader.getBindings();
101
+ const metadata = {
102
+ user_agent: input.userAgent || null,
103
+ ip_address: input.ipAddress || null,
104
+ headers: JSON.stringify(input.headers || {}),
105
+ timestamp: (input.timestamp || /* @__PURE__ */ new Date()).toISOString(),
106
+ url: input.url || null,
107
+ method: input.method || null,
108
+ client_fingerprint: input.clientFingerprint || null,
109
+ free: () => {
110
+ }
111
+ // No-op for JS
112
+ };
113
+ const wasmResult = bindings.detect_agent(metadata);
114
+ const verificationMethod = parseVerificationMethod(wasmResult.verification_method);
115
+ const forgeabilityRisk = determineForgeabilityRisk(verificationMethod, wasmResult.confidence);
116
+ const detectionClass = determineDetectionClass(
117
+ wasmResult.is_agent,
118
+ wasmResult.agent,
119
+ wasmResult.confidence
120
+ );
121
+ let result = {
122
+ isAgent: wasmResult.is_agent,
123
+ confidence: wasmResult.confidence,
124
+ // Already 0-100, no conversion!
125
+ detectionClass,
126
+ detectedAgent: wasmResult.agent ? {
127
+ type: this.inferAgentType(wasmResult.agent),
128
+ name: wasmResult.agent
129
+ } : void 0,
130
+ verificationMethod,
131
+ forgeabilityRisk,
132
+ reasons: this.extractReasons(wasmResult),
133
+ timestamp: /* @__PURE__ */ new Date()
134
+ };
135
+ if (this.policyLoader && this.options.apiKey) {
136
+ result = await this.applyPolicy(result);
137
+ }
138
+ return result;
139
+ } catch (error) {
140
+ if (this.options.debug) {
141
+ console.error("[WasmDetector] Detection error:", error);
142
+ }
143
+ return this.createDefaultResult();
144
+ }
145
+ }
146
+ /**
147
+ * Check if the detector is ready
148
+ */
149
+ isReady() {
150
+ return this.ready;
151
+ }
152
+ /**
153
+ * Ensure the detector is initialized
154
+ */
155
+ async ensureReady() {
156
+ if (this.ready) {
157
+ return;
158
+ }
159
+ if (this.loadPromise) {
160
+ return this.loadPromise;
161
+ }
162
+ this.loadPromise = this.initialize();
163
+ return this.loadPromise;
164
+ }
165
+ /**
166
+ * Get detector version
167
+ */
168
+ async getVersion() {
169
+ await this.ensureReady();
170
+ return this.loader.getBindings().get_version();
171
+ }
172
+ /**
173
+ * Initialize the detector
174
+ */
175
+ async initialize() {
176
+ try {
177
+ await this.loader.load();
178
+ this.ready = true;
179
+ if (this.options.debug) {
180
+ const version2 = this.loader.getBindings().get_version();
181
+ console.log(
182
+ `[WasmDetector] Initialized with WASM v${version2} (${this.loader.getStrategy()})`
183
+ );
184
+ }
185
+ } catch (error) {
186
+ this.loadPromise = null;
187
+ throw error;
188
+ }
189
+ }
190
+ /**
191
+ * Apply customer policy to detection result
192
+ */
193
+ async applyPolicy(result) {
194
+ if (!this.policyLoader || !this.options.apiKey) {
195
+ return result;
196
+ }
197
+ try {
198
+ let policy = this.policyLoader.getCachedPolicy(this.options.apiKey);
199
+ if (!policy) {
200
+ policy = await this.policyLoader.loadPolicy(this.options.apiKey);
201
+ }
202
+ return this.applyPolicyRules(result, policy);
203
+ } catch (error) {
204
+ if (this.options.debug) {
205
+ console.warn("[WasmDetector] Failed to load policy:", error);
206
+ }
207
+ return result;
208
+ }
209
+ }
210
+ /**
211
+ * Check if agent name matches a policy list entry
212
+ * Uses exact match or word-boundary prefix match to avoid false positives
213
+ * e.g., "gpt" matches "ChatGPT" and "GPT-4" but not "EgyptBot"
214
+ */
215
+ matchesPolicyEntry(agentName, policyEntry) {
216
+ const lowerAgent = agentName.toLowerCase();
217
+ const lowerEntry = policyEntry.toLowerCase();
218
+ if (lowerAgent === lowerEntry) {
219
+ return true;
220
+ }
221
+ const wordBoundaryRegex = new RegExp(
222
+ `(^|[^a-z0-9])${this.escapeRegex(lowerEntry)}($|[^a-z0-9])`,
223
+ "i"
224
+ );
225
+ return wordBoundaryRegex.test(lowerAgent);
226
+ }
227
+ /**
228
+ * Escape special regex characters in a string
229
+ */
230
+ escapeRegex(str) {
231
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
232
+ }
233
+ /**
234
+ * Apply policy rules to detection result
235
+ */
236
+ applyPolicyRules(result, policy) {
237
+ if (policy.denyList && result.detectedAgent) {
238
+ const agentName = result.detectedAgent.name;
239
+ const isDenied = policy.denyList.some((denied) => this.matchesPolicyEntry(agentName, denied));
240
+ if (isDenied) {
241
+ return {
242
+ ...result,
243
+ shouldBlock: true,
244
+ blockReason: "deny_list"
245
+ };
246
+ }
247
+ }
248
+ if (policy.allowList && policy.allowList.length > 0 && result.isAgent) {
249
+ const agentName = result.detectedAgent?.name;
250
+ if (!agentName) ; else {
251
+ const isAllowed = policy.allowList.some(
252
+ (allowed) => this.matchesPolicyEntry(agentName, allowed)
253
+ );
254
+ if (!isAllowed) {
255
+ return {
256
+ ...result,
257
+ shouldBlock: true,
258
+ blockReason: "not_in_allow_list"
259
+ };
260
+ }
261
+ return {
262
+ ...result,
263
+ shouldBlock: false
264
+ };
265
+ }
266
+ }
267
+ if (policy.blockThreshold !== void 0 && result.isAgent && result.confidence >= policy.blockThreshold) {
268
+ return {
269
+ ...result,
270
+ shouldBlock: true,
271
+ blockReason: "threshold"
272
+ };
273
+ }
274
+ return result;
275
+ }
276
+ /**
277
+ * Infer agent type from name
278
+ */
279
+ inferAgentType(agentName) {
280
+ const lowerName = agentName.toLowerCase();
281
+ if (lowerName.includes("chatgpt") || lowerName.includes("openai") || lowerName.includes("gpt")) {
282
+ return "openai";
283
+ }
284
+ if (lowerName.includes("claude") || lowerName.includes("anthropic")) {
285
+ return "anthropic";
286
+ }
287
+ if (lowerName.includes("perplexity")) {
288
+ return "perplexity";
289
+ }
290
+ if (lowerName.includes("gemini") || lowerName.includes("google")) {
291
+ return "google";
292
+ }
293
+ if (lowerName.includes("copilot") || lowerName.includes("bing")) {
294
+ return "microsoft";
295
+ }
296
+ return "unknown";
297
+ }
298
+ /**
299
+ * Extract reasons from WASM result
300
+ */
301
+ extractReasons(wasmResult) {
302
+ const reasons = [];
303
+ if (wasmResult.verification_method) {
304
+ reasons.push(`method:${wasmResult.verification_method}`);
305
+ }
306
+ if (wasmResult.agent) {
307
+ reasons.push(`agent:${wasmResult.agent.toLowerCase()}`);
308
+ }
309
+ return reasons;
310
+ }
311
+ /**
312
+ * Create default result (assumed human)
313
+ */
314
+ createDefaultResult() {
315
+ return {
316
+ isAgent: false,
317
+ confidence: 0,
318
+ detectionClass: { type: "Human" },
319
+ verificationMethod: "none",
320
+ forgeabilityRisk: "high",
321
+ reasons: ["detection_failed"],
322
+ timestamp: /* @__PURE__ */ new Date()
323
+ };
324
+ }
325
+ };
326
+
327
+ // src/wasm-bindgen/agentshield_wasm.js
328
+ var wasm;
329
+ var cachedTextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }) : {
330
+ decode: () => {
331
+ throw Error("TextDecoder not available");
332
+ }
333
+ };
334
+ if (typeof TextDecoder !== "undefined") {
335
+ cachedTextDecoder.decode();
336
+ }
337
+ var cachedUint8ArrayMemory0 = null;
338
+ function getUint8ArrayMemory0() {
339
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
340
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
341
+ }
342
+ return cachedUint8ArrayMemory0;
343
+ }
344
+ function getStringFromWasm0(ptr, len) {
345
+ ptr = ptr >>> 0;
346
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
347
+ }
348
+ function logError(f, args) {
349
+ try {
350
+ return f.apply(this, args);
351
+ } catch (e) {
352
+ let error = (function() {
353
+ try {
354
+ return e instanceof Error ? `${e.message}
355
+
356
+ Stack:
357
+ ${e.stack}` : e.toString();
358
+ } catch (_) {
359
+ return "<failed to stringify thrown value>";
360
+ }
361
+ })();
362
+ console.error(
363
+ "wasm-bindgen: imported JS function that was not marked as `catch` threw an error:",
364
+ error
365
+ );
366
+ throw e;
367
+ }
368
+ }
369
+ var WASM_VECTOR_LEN = 0;
370
+ var cachedTextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : {
371
+ encode: () => {
372
+ throw Error("TextEncoder not available");
373
+ }
374
+ };
375
+ var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
376
+ return cachedTextEncoder.encodeInto(arg, view);
377
+ } : function(arg, view) {
378
+ const buf = cachedTextEncoder.encode(arg);
379
+ view.set(buf);
380
+ return {
381
+ read: arg.length,
382
+ written: buf.length
383
+ };
384
+ };
385
+ function passStringToWasm0(arg, malloc, realloc) {
386
+ if (typeof arg !== "string") throw new Error(`expected a string argument, found ${typeof arg}`);
387
+ if (realloc === void 0) {
388
+ const buf = cachedTextEncoder.encode(arg);
389
+ const ptr2 = malloc(buf.length, 1) >>> 0;
390
+ getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
391
+ WASM_VECTOR_LEN = buf.length;
392
+ return ptr2;
393
+ }
394
+ let len = arg.length;
395
+ let ptr = malloc(len, 1) >>> 0;
396
+ const mem = getUint8ArrayMemory0();
397
+ let offset = 0;
398
+ for (; offset < len; offset++) {
399
+ const code = arg.charCodeAt(offset);
400
+ if (code > 127) break;
401
+ mem[ptr + offset] = code;
402
+ }
403
+ if (offset !== len) {
404
+ if (offset !== 0) {
405
+ arg = arg.slice(offset);
406
+ }
407
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
408
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
409
+ const ret = encodeString(arg, view);
410
+ if (ret.read !== arg.length) throw new Error("failed to pass whole string");
411
+ offset += ret.written;
412
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
413
+ }
414
+ WASM_VECTOR_LEN = offset;
415
+ return ptr;
416
+ }
417
+ var cachedDataViewMemory0 = null;
418
+ function getDataViewMemory0() {
419
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
420
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
421
+ }
422
+ return cachedDataViewMemory0;
423
+ }
424
+ function _assertNum(n) {
425
+ if (typeof n !== "number") throw new Error(`expected a number argument, found ${typeof n}`);
426
+ }
427
+ function _assertBoolean(n) {
428
+ if (typeof n !== "boolean") {
429
+ throw new Error(`expected a boolean argument, found ${typeof n}`);
430
+ }
431
+ }
432
+ function isLikeNone(x) {
433
+ return x === void 0 || x === null;
434
+ }
435
+ function _assertClass(instance, klass) {
436
+ if (!(instance instanceof klass)) {
437
+ throw new Error(`expected instance of ${klass.name}`);
438
+ }
439
+ }
440
+ function takeFromExternrefTable0(idx) {
441
+ const value = wasm.__wbindgen_export_3.get(idx);
442
+ wasm.__externref_table_dealloc(idx);
443
+ return value;
444
+ }
445
+ function detect_agent(metadata) {
446
+ _assertClass(metadata, JsRequestMetadata);
447
+ if (metadata.__wbg_ptr === 0) {
448
+ throw new Error("Attempt to use a moved value");
449
+ }
450
+ const ret = wasm.detect_agent(metadata.__wbg_ptr);
451
+ if (ret[2]) {
452
+ throw takeFromExternrefTable0(ret[1]);
453
+ }
454
+ return JsDetectionResult.__wrap(ret[0]);
455
+ }
456
+ function version() {
457
+ let deferred1_0;
458
+ let deferred1_1;
459
+ try {
460
+ const ret = wasm.version();
461
+ deferred1_0 = ret[0];
462
+ deferred1_1 = ret[1];
463
+ return getStringFromWasm0(ret[0], ret[1]);
464
+ } finally {
465
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
466
+ }
467
+ }
468
+ var JsDetectionResultFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
469
+ }, unregister: () => {
470
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_jsdetectionresult_free(ptr >>> 0, 1));
471
+ var JsDetectionResult = class _JsDetectionResult {
472
+ constructor() {
473
+ throw new Error("cannot invoke `new` directly");
474
+ }
475
+ static __wrap(ptr) {
476
+ ptr = ptr >>> 0;
477
+ const obj = Object.create(_JsDetectionResult.prototype);
478
+ obj.__wbg_ptr = ptr;
479
+ JsDetectionResultFinalization.register(obj, obj.__wbg_ptr, obj);
480
+ return obj;
481
+ }
482
+ __destroy_into_raw() {
483
+ const ptr = this.__wbg_ptr;
484
+ this.__wbg_ptr = 0;
485
+ JsDetectionResultFinalization.unregister(this);
486
+ return ptr;
487
+ }
488
+ free() {
489
+ const ptr = this.__destroy_into_raw();
490
+ wasm.__wbg_jsdetectionresult_free(ptr, 0);
491
+ }
492
+ /**
493
+ * Whether the request was identified as coming from an agent
494
+ * @returns {boolean}
495
+ */
496
+ get is_agent() {
497
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
498
+ _assertNum(this.__wbg_ptr);
499
+ const ret = wasm.__wbg_get_jsdetectionresult_is_agent(this.__wbg_ptr);
500
+ return ret !== 0;
501
+ }
502
+ /**
503
+ * Whether the request was identified as coming from an agent
504
+ * @param {boolean} arg0
505
+ */
506
+ set is_agent(arg0) {
507
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
508
+ _assertNum(this.__wbg_ptr);
509
+ _assertBoolean(arg0);
510
+ wasm.__wbg_set_jsdetectionresult_is_agent(this.__wbg_ptr, arg0);
511
+ }
512
+ /**
513
+ * Confidence score (0.0 to 1.0)
514
+ * @returns {number}
515
+ */
516
+ get confidence() {
517
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
518
+ _assertNum(this.__wbg_ptr);
519
+ const ret = wasm.__wbg_get_jsdetectionresult_confidence(this.__wbg_ptr);
520
+ return ret;
521
+ }
522
+ /**
523
+ * Confidence score (0.0 to 1.0)
524
+ * @param {number} arg0
525
+ */
526
+ set confidence(arg0) {
527
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
528
+ _assertNum(this.__wbg_ptr);
529
+ wasm.__wbg_set_jsdetectionresult_confidence(this.__wbg_ptr, arg0);
530
+ }
531
+ /**
532
+ * Get the detected agent name
533
+ * @returns {string | undefined}
534
+ */
535
+ get agent() {
536
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
537
+ _assertNum(this.__wbg_ptr);
538
+ const ret = wasm.jsdetectionresult_agent(this.__wbg_ptr);
539
+ let v1;
540
+ if (ret[0] !== 0) {
541
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
542
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
543
+ }
544
+ return v1;
545
+ }
546
+ /**
547
+ * Get the verification method as a string
548
+ * @returns {string}
549
+ */
550
+ get verification_method() {
551
+ let deferred1_0;
552
+ let deferred1_1;
553
+ try {
554
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
555
+ _assertNum(this.__wbg_ptr);
556
+ const ret = wasm.jsdetectionresult_verification_method(this.__wbg_ptr);
557
+ deferred1_0 = ret[0];
558
+ deferred1_1 = ret[1];
559
+ return getStringFromWasm0(ret[0], ret[1]);
560
+ } finally {
561
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
562
+ }
563
+ }
564
+ /**
565
+ * Get the risk level as a string
566
+ * @returns {string}
567
+ */
568
+ get risk_level() {
569
+ let deferred1_0;
570
+ let deferred1_1;
571
+ try {
572
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
573
+ _assertNum(this.__wbg_ptr);
574
+ const ret = wasm.jsdetectionresult_risk_level(this.__wbg_ptr);
575
+ deferred1_0 = ret[0];
576
+ deferred1_1 = ret[1];
577
+ return getStringFromWasm0(ret[0], ret[1]);
578
+ } finally {
579
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
580
+ }
581
+ }
582
+ /**
583
+ * Get the timestamp as a string
584
+ * @returns {string}
585
+ */
586
+ get timestamp() {
587
+ let deferred1_0;
588
+ let deferred1_1;
589
+ try {
590
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
591
+ _assertNum(this.__wbg_ptr);
592
+ const ret = wasm.jsdetectionresult_timestamp(this.__wbg_ptr);
593
+ deferred1_0 = ret[0];
594
+ deferred1_1 = ret[1];
595
+ return getStringFromWasm0(ret[0], ret[1]);
596
+ } finally {
597
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
598
+ }
599
+ }
600
+ };
601
+ var JsRequestMetadataFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
602
+ }, unregister: () => {
603
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_jsrequestmetadata_free(ptr >>> 0, 1));
604
+ var JsRequestMetadata = class {
605
+ __destroy_into_raw() {
606
+ const ptr = this.__wbg_ptr;
607
+ this.__wbg_ptr = 0;
608
+ JsRequestMetadataFinalization.unregister(this);
609
+ return ptr;
610
+ }
611
+ free() {
612
+ const ptr = this.__destroy_into_raw();
613
+ wasm.__wbg_jsrequestmetadata_free(ptr, 0);
614
+ }
615
+ /**
616
+ * Constructor for JsRequestMetadata
617
+ * @param {string | null | undefined} user_agent
618
+ * @param {string | null | undefined} ip_address
619
+ * @param {string} headers
620
+ * @param {string} timestamp
621
+ * @param {string | null} [url]
622
+ * @param {string | null} [method]
623
+ * @param {string | null} [client_fingerprint]
624
+ */
625
+ constructor(user_agent, ip_address, headers, timestamp, url, method, client_fingerprint) {
626
+ var ptr0 = isLikeNone(user_agent) ? 0 : passStringToWasm0(user_agent, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
627
+ var len0 = WASM_VECTOR_LEN;
628
+ var ptr1 = isLikeNone(ip_address) ? 0 : passStringToWasm0(ip_address, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
629
+ var len1 = WASM_VECTOR_LEN;
630
+ const ptr2 = passStringToWasm0(headers, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
631
+ const len2 = WASM_VECTOR_LEN;
632
+ const ptr3 = passStringToWasm0(timestamp, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
633
+ const len3 = WASM_VECTOR_LEN;
634
+ var ptr4 = isLikeNone(url) ? 0 : passStringToWasm0(url, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
635
+ var len4 = WASM_VECTOR_LEN;
636
+ var ptr5 = isLikeNone(method) ? 0 : passStringToWasm0(method, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
637
+ var len5 = WASM_VECTOR_LEN;
638
+ var ptr6 = isLikeNone(client_fingerprint) ? 0 : passStringToWasm0(client_fingerprint, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
639
+ var len6 = WASM_VECTOR_LEN;
640
+ const ret = wasm.jsrequestmetadata_new(
641
+ ptr0,
642
+ len0,
643
+ ptr1,
644
+ len1,
645
+ ptr2,
646
+ len2,
647
+ ptr3,
648
+ len3,
649
+ ptr4,
650
+ len4,
651
+ ptr5,
652
+ len5,
653
+ ptr6,
654
+ len6
655
+ );
656
+ this.__wbg_ptr = ret >>> 0;
657
+ JsRequestMetadataFinalization.register(this, this.__wbg_ptr, this);
658
+ return this;
659
+ }
660
+ /**
661
+ * Get the user agent
662
+ * @returns {string | undefined}
663
+ */
664
+ get user_agent() {
665
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
666
+ _assertNum(this.__wbg_ptr);
667
+ const ret = wasm.jsrequestmetadata_user_agent(this.__wbg_ptr);
668
+ let v1;
669
+ if (ret[0] !== 0) {
670
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
671
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
672
+ }
673
+ return v1;
674
+ }
675
+ /**
676
+ * Get the IP address
677
+ * @returns {string | undefined}
678
+ */
679
+ get ip_address() {
680
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
681
+ _assertNum(this.__wbg_ptr);
682
+ const ret = wasm.jsrequestmetadata_ip_address(this.__wbg_ptr);
683
+ let v1;
684
+ if (ret[0] !== 0) {
685
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
686
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
687
+ }
688
+ return v1;
689
+ }
690
+ /**
691
+ * Get the headers as JSON string
692
+ * @returns {string}
693
+ */
694
+ get headers() {
695
+ let deferred1_0;
696
+ let deferred1_1;
697
+ try {
698
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
699
+ _assertNum(this.__wbg_ptr);
700
+ const ret = wasm.jsrequestmetadata_headers(this.__wbg_ptr);
701
+ deferred1_0 = ret[0];
702
+ deferred1_1 = ret[1];
703
+ return getStringFromWasm0(ret[0], ret[1]);
704
+ } finally {
705
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
706
+ }
707
+ }
708
+ /**
709
+ * Get the timestamp
710
+ * @returns {string}
711
+ */
712
+ get timestamp() {
713
+ let deferred1_0;
714
+ let deferred1_1;
715
+ try {
716
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
717
+ _assertNum(this.__wbg_ptr);
718
+ const ret = wasm.jsrequestmetadata_timestamp(this.__wbg_ptr);
719
+ deferred1_0 = ret[0];
720
+ deferred1_1 = ret[1];
721
+ return getStringFromWasm0(ret[0], ret[1]);
722
+ } finally {
723
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
724
+ }
725
+ }
726
+ /**
727
+ * Get the URL
728
+ * @returns {string | undefined}
729
+ */
730
+ get url() {
731
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
732
+ _assertNum(this.__wbg_ptr);
733
+ const ret = wasm.jsrequestmetadata_url(this.__wbg_ptr);
734
+ let v1;
735
+ if (ret[0] !== 0) {
736
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
737
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
738
+ }
739
+ return v1;
740
+ }
741
+ /**
742
+ * Get the method
743
+ * @returns {string | undefined}
744
+ */
745
+ get method() {
746
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
747
+ _assertNum(this.__wbg_ptr);
748
+ const ret = wasm.jsrequestmetadata_method(this.__wbg_ptr);
749
+ let v1;
750
+ if (ret[0] !== 0) {
751
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
752
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
753
+ }
754
+ return v1;
755
+ }
756
+ /**
757
+ * Get the client fingerprint
758
+ * @returns {string | undefined}
759
+ */
760
+ get client_fingerprint() {
761
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
762
+ _assertNum(this.__wbg_ptr);
763
+ const ret = wasm.jsrequestmetadata_client_fingerprint(this.__wbg_ptr);
764
+ let v1;
765
+ if (ret[0] !== 0) {
766
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
767
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
768
+ }
769
+ return v1;
770
+ }
771
+ };
772
+ function __wbg_get_imports() {
773
+ const imports = {};
774
+ imports.wbg = {};
775
+ imports.wbg.__wbg_error_7534b8e9a36f1ab4 = function() {
776
+ return logError(function(arg0, arg1) {
777
+ let deferred0_0;
778
+ let deferred0_1;
779
+ try {
780
+ deferred0_0 = arg0;
781
+ deferred0_1 = arg1;
782
+ console.error(getStringFromWasm0(arg0, arg1));
783
+ } finally {
784
+ wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
785
+ }
786
+ }, arguments);
787
+ };
788
+ imports.wbg.__wbg_getTime_46267b1c24877e30 = function() {
789
+ return logError(function(arg0) {
790
+ const ret = arg0.getTime();
791
+ return ret;
792
+ }, arguments);
793
+ };
794
+ imports.wbg.__wbg_log_c222819a41e063d3 = function() {
795
+ return logError(function(arg0) {
796
+ console.log(arg0);
797
+ }, arguments);
798
+ };
799
+ imports.wbg.__wbg_new_31a97dac4f10fab7 = function() {
800
+ return logError(function(arg0) {
801
+ const ret = new Date(arg0);
802
+ return ret;
803
+ }, arguments);
804
+ };
805
+ imports.wbg.__wbg_new_8a6f238a6ece86ea = function() {
806
+ return logError(function() {
807
+ const ret = new Error();
808
+ return ret;
809
+ }, arguments);
810
+ };
811
+ imports.wbg.__wbg_now_807e54c39636c349 = function() {
812
+ return logError(function() {
813
+ const ret = Date.now();
814
+ return ret;
815
+ }, arguments);
816
+ };
817
+ imports.wbg.__wbg_stack_0ed75d68575b0f3c = function() {
818
+ return logError(function(arg0, arg1) {
819
+ const ret = arg1.stack;
820
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
821
+ const len1 = WASM_VECTOR_LEN;
822
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
823
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
824
+ }, arguments);
825
+ };
826
+ imports.wbg.__wbindgen_init_externref_table = function() {
827
+ const table = wasm.__wbindgen_export_3;
828
+ const offset = table.grow(4);
829
+ table.set(0, void 0);
830
+ table.set(offset + 0, void 0);
831
+ table.set(offset + 1, null);
832
+ table.set(offset + 2, true);
833
+ table.set(offset + 3, false);
834
+ };
835
+ imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
836
+ const ret = getStringFromWasm0(arg0, arg1);
837
+ return ret;
838
+ };
839
+ imports.wbg.__wbindgen_throw = function(arg0, arg1) {
840
+ throw new Error(getStringFromWasm0(arg0, arg1));
841
+ };
842
+ return imports;
843
+ }
844
+ function __wbg_finalize_init(instance, module) {
845
+ wasm = instance.exports;
846
+ cachedDataViewMemory0 = null;
847
+ cachedUint8ArrayMemory0 = null;
848
+ wasm.__wbindgen_start();
849
+ return wasm;
850
+ }
851
+ function initSync(module) {
852
+ if (wasm !== void 0) return wasm;
853
+ if (typeof module !== "undefined") {
854
+ if (Object.getPrototypeOf(module) === Object.prototype) {
855
+ ({ module } = module);
856
+ } else {
857
+ console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
858
+ }
859
+ }
860
+ const imports = __wbg_get_imports();
861
+ if (!(module instanceof WebAssembly.Module)) {
862
+ module = new WebAssembly.Module(module);
863
+ }
864
+ const instance = new WebAssembly.Instance(module, imports);
865
+ return __wbg_finalize_init(instance);
866
+ }
867
+
868
+ // src/loaders/static-loader.ts
869
+ var StaticWasmLoader = class {
870
+ /**
871
+ * Create a new StaticWasmLoader
872
+ * @param wasmModule - Pre-compiled WebAssembly.Module from static import
873
+ */
874
+ constructor(wasmModule) {
875
+ this.wasmModule = wasmModule;
876
+ if (!wasmModule) {
877
+ throw new Error(
878
+ "StaticWasmLoader requires a WebAssembly.Module. Import with: import wasmModule from './wasm.wasm?module'"
879
+ );
880
+ }
881
+ }
882
+ bindings = null;
883
+ loadPromise = null;
884
+ wasmExports = null;
885
+ /**
886
+ * Load and instantiate the WASM module
887
+ */
888
+ async load() {
889
+ if (this.bindings) {
890
+ return;
891
+ }
892
+ if (this.loadPromise) {
893
+ return this.loadPromise;
894
+ }
895
+ this.loadPromise = this.doLoad();
896
+ return this.loadPromise;
897
+ }
898
+ /**
899
+ * Internal load implementation using wasm-bindgen initSync
900
+ */
901
+ async doLoad() {
902
+ try {
903
+ this.wasmExports = initSync({ module: this.wasmModule });
904
+ this.bindings = this.createBindings();
905
+ } catch (error) {
906
+ this.loadPromise = null;
907
+ throw new Error(
908
+ `Failed to instantiate WASM module: ${error instanceof Error ? error.message : String(error)}`
909
+ );
910
+ }
911
+ }
912
+ /**
913
+ * Get the WASM bindings after loading
914
+ */
915
+ getBindings() {
916
+ if (!this.bindings) {
917
+ throw new Error("WASM not loaded. Call load() first.");
918
+ }
919
+ return this.bindings;
920
+ }
921
+ /**
922
+ * Check if WASM is loaded
923
+ */
924
+ isLoaded() {
925
+ return this.bindings !== null;
926
+ }
927
+ /**
928
+ * Get the loading strategy name
929
+ */
930
+ getStrategy() {
931
+ return "static-import";
932
+ }
933
+ /**
934
+ * Create bindings wrapper using wasm-bindgen exports
935
+ */
936
+ createBindings() {
937
+ return {
938
+ detect_agent: (metadata) => {
939
+ const wasmMetadata = new JsRequestMetadata(
940
+ metadata.user_agent,
941
+ metadata.ip_address,
942
+ metadata.headers,
943
+ metadata.timestamp,
944
+ metadata.url,
945
+ metadata.method,
946
+ metadata.client_fingerprint
947
+ );
948
+ let result = null;
949
+ try {
950
+ result = detect_agent(wasmMetadata);
951
+ return {
952
+ is_agent: result.is_agent,
953
+ confidence: result.confidence,
954
+ agent: result.agent ?? null,
955
+ // Convert undefined to null
956
+ verification_method: result.verification_method,
957
+ risk_level: result.risk_level,
958
+ timestamp: result.timestamp
959
+ };
960
+ } finally {
961
+ result?.free();
962
+ wasmMetadata.free();
963
+ }
964
+ },
965
+ get_version: () => {
966
+ try {
967
+ return version();
968
+ } catch {
969
+ return "0.1.0-static";
970
+ }
971
+ },
972
+ get_build_info: () => {
973
+ return JSON.stringify({ version: "0.1.0", strategy: "static-import" });
974
+ }
975
+ };
976
+ }
977
+ };
978
+ function createStaticLoader(wasmModule) {
979
+ return new StaticWasmLoader(wasmModule);
980
+ }
981
+
982
+ // src/policy/policy-loader.ts
983
+ var DEFAULT_CONFIG = {
984
+ apiUrl: "https://api.agentshield.io",
985
+ cacheTTL: 5 * 60 * 1e3,
986
+ // 5 minutes
987
+ maxCacheSize: 100,
988
+ backgroundRefresh: true,
989
+ timeout: 5e3
990
+ };
991
+ var PolicyLoader = class {
992
+ cache = /* @__PURE__ */ new Map();
993
+ config;
994
+ constructor(config = {}) {
995
+ this.config = { ...DEFAULT_CONFIG, ...config };
996
+ }
997
+ /**
998
+ * Load policy for an API key
999
+ */
1000
+ async loadPolicy(apiKey) {
1001
+ const cached = this.getCachedPolicy(apiKey);
1002
+ if (cached) {
1003
+ if (this.config.backgroundRefresh && this.shouldRefresh(apiKey)) {
1004
+ this.refreshInBackground(apiKey);
1005
+ }
1006
+ return cached;
1007
+ }
1008
+ return this.fetchPolicy(apiKey);
1009
+ }
1010
+ /**
1011
+ * Get cached policy if available and not expired
1012
+ */
1013
+ getCachedPolicy(apiKey) {
1014
+ const entry = this.cache.get(apiKey);
1015
+ if (!entry) {
1016
+ return null;
1017
+ }
1018
+ if (this.isExpired(entry)) {
1019
+ this.cache.delete(apiKey);
1020
+ return null;
1021
+ }
1022
+ return entry.policy;
1023
+ }
1024
+ /**
1025
+ * Invalidate cached policy
1026
+ */
1027
+ invalidateCache(apiKey) {
1028
+ this.cache.delete(apiKey);
1029
+ }
1030
+ /**
1031
+ * Fetch policy from API and cache it
1032
+ */
1033
+ async fetchPolicy(apiKey) {
1034
+ const policy = await this.fetchPolicyFromApi(apiKey);
1035
+ this.cachePolicy(apiKey, policy);
1036
+ return policy;
1037
+ }
1038
+ /**
1039
+ * Fetch policy from API without caching
1040
+ * Used internally for both direct fetches and background refreshes
1041
+ */
1042
+ async fetchPolicyFromApi(apiKey) {
1043
+ const controller = new AbortController();
1044
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1045
+ try {
1046
+ const response = await fetch(`${this.config.apiUrl}/api/v1/policy`, {
1047
+ method: "GET",
1048
+ headers: {
1049
+ Authorization: `Bearer ${apiKey}`,
1050
+ "Content-Type": "application/json",
1051
+ "User-Agent": "agentshield-wasm-runtime/0.1.0"
1052
+ },
1053
+ signal: controller.signal
1054
+ });
1055
+ clearTimeout(timeoutId);
1056
+ if (!response.ok) {
1057
+ if (response.status === 401) {
1058
+ throw new PolicyLoadError("Invalid API key", "INVALID_API_KEY");
1059
+ }
1060
+ if (response.status === 404) {
1061
+ return this.getDefaultPolicy(apiKey);
1062
+ }
1063
+ throw new PolicyLoadError(`Failed to load policy: ${response.status}`, "API_ERROR");
1064
+ }
1065
+ return await response.json();
1066
+ } catch (error) {
1067
+ clearTimeout(timeoutId);
1068
+ if (error instanceof PolicyLoadError) {
1069
+ throw error;
1070
+ }
1071
+ if (error instanceof Error && error.name === "AbortError") {
1072
+ throw new PolicyLoadError("Policy request timeout", "TIMEOUT");
1073
+ }
1074
+ throw new PolicyLoadError(
1075
+ `Failed to load policy: ${error instanceof Error ? error.message : "Unknown error"}`,
1076
+ "NETWORK_ERROR"
1077
+ );
1078
+ }
1079
+ }
1080
+ /**
1081
+ * Cache a policy
1082
+ */
1083
+ cachePolicy(apiKey, policy) {
1084
+ if (this.cache.size >= this.config.maxCacheSize) {
1085
+ const oldestKey = this.cache.keys().next().value;
1086
+ if (oldestKey) {
1087
+ this.cache.delete(oldestKey);
1088
+ }
1089
+ }
1090
+ this.cache.set(apiKey, {
1091
+ policy,
1092
+ loadedAt: Date.now(),
1093
+ refreshing: false
1094
+ });
1095
+ }
1096
+ /**
1097
+ * Check if cached entry is expired
1098
+ */
1099
+ isExpired(entry) {
1100
+ return Date.now() - entry.loadedAt > this.config.cacheTTL;
1101
+ }
1102
+ /**
1103
+ * Check if cache entry should be refreshed
1104
+ */
1105
+ shouldRefresh(apiKey) {
1106
+ const entry = this.cache.get(apiKey);
1107
+ if (!entry) {
1108
+ return false;
1109
+ }
1110
+ const refreshThreshold = this.config.cacheTTL * 0.8;
1111
+ return Date.now() - entry.loadedAt > refreshThreshold && !entry.refreshing;
1112
+ }
1113
+ /**
1114
+ * Refresh policy in background
1115
+ */
1116
+ async refreshInBackground(apiKey) {
1117
+ const entry = this.cache.get(apiKey);
1118
+ if (!entry || entry.refreshing) {
1119
+ return;
1120
+ }
1121
+ entry.refreshing = true;
1122
+ try {
1123
+ const policy = await this.fetchPolicyFromApi(apiKey);
1124
+ this.cachePolicy(apiKey, policy);
1125
+ } catch {
1126
+ } finally {
1127
+ const currentEntry = this.cache.get(apiKey);
1128
+ if (currentEntry && currentEntry.refreshing) {
1129
+ currentEntry.refreshing = false;
1130
+ }
1131
+ }
1132
+ }
1133
+ /**
1134
+ * Get default policy for a project
1135
+ */
1136
+ getDefaultPolicy(apiKey) {
1137
+ return {
1138
+ projectId: apiKey.split("_")[1] || "unknown",
1139
+ blockThreshold: 90
1140
+ };
1141
+ }
1142
+ };
1143
+ var PolicyLoadError = class extends Error {
1144
+ constructor(message, code) {
1145
+ super(message);
1146
+ this.code = code;
1147
+ this.name = "PolicyLoadError";
1148
+ }
1149
+ };
1150
+ function createPolicyLoader(config) {
1151
+ return new PolicyLoader(config);
1152
+ }
1153
+ var RulesDetector = class {
1154
+ rules = null;
1155
+ ready = false;
1156
+ /**
1157
+ * Analyze a request and detect if it's from an agent
1158
+ */
1159
+ async detect(input) {
1160
+ await this.ensureReady();
1161
+ const reasons = [];
1162
+ let confidence = 0;
1163
+ let detectedAgentName = null;
1164
+ let verificationMethod = "none";
1165
+ const userAgent = input.userAgent || input.headers["user-agent"] || "";
1166
+ const normalizedHeaders = this.normalizeHeaders(input.headers);
1167
+ if (userAgent && this.rules) {
1168
+ const uaMatch = this.matchUserAgent(userAgent);
1169
+ if (uaMatch) {
1170
+ confidence = Math.max(confidence, uaMatch.confidence);
1171
+ detectedAgentName = uaMatch.agentName;
1172
+ verificationMethod = "pattern";
1173
+ reasons.push(`pattern:${uaMatch.agentKey}`);
1174
+ }
1175
+ }
1176
+ if (this.rules) {
1177
+ const headerMatch = this.matchHeaders(normalizedHeaders);
1178
+ if (headerMatch.confidence > 0) {
1179
+ confidence = Math.max(confidence, headerMatch.confidence);
1180
+ reasons.push(`headers:${headerMatch.count}`);
1181
+ }
1182
+ }
1183
+ if (this.hasSignatureHeaders(normalizedHeaders)) {
1184
+ confidence = Math.max(confidence, CONFIDENCE.SIGNATURE_PRESENT);
1185
+ reasons.push("signature_headers_present");
1186
+ verificationMethod = "pattern";
1187
+ }
1188
+ const isAgent = confidence > CONFIDENCE.THRESHOLD_AGENT;
1189
+ const detectionClass = this.determineDetectionClass(isAgent, detectedAgentName, confidence);
1190
+ return {
1191
+ isAgent,
1192
+ confidence,
1193
+ detectionClass,
1194
+ detectedAgent: detectedAgentName ? {
1195
+ type: this.inferAgentType(detectedAgentName),
1196
+ name: detectedAgentName
1197
+ } : void 0,
1198
+ verificationMethod,
1199
+ forgeabilityRisk: "high",
1200
+ // JS fallback is always high risk
1201
+ reasons,
1202
+ timestamp: /* @__PURE__ */ new Date()
1203
+ };
1204
+ }
1205
+ /**
1206
+ * Check if the detector is ready
1207
+ */
1208
+ isReady() {
1209
+ return this.ready;
1210
+ }
1211
+ /**
1212
+ * Ensure the detector is initialized
1213
+ */
1214
+ async ensureReady() {
1215
+ if (this.ready) {
1216
+ return;
1217
+ }
1218
+ try {
1219
+ this.rules = loadRulesSync();
1220
+ this.ready = true;
1221
+ } catch (error) {
1222
+ console.warn("[RulesDetector] Failed to load rules:", error);
1223
+ this.ready = true;
1224
+ }
1225
+ }
1226
+ /**
1227
+ * Get detector version
1228
+ */
1229
+ async getVersion() {
1230
+ return "0.1.0-js-fallback";
1231
+ }
1232
+ /**
1233
+ * Normalize headers to lowercase keys
1234
+ */
1235
+ normalizeHeaders(headers) {
1236
+ const normalized = {};
1237
+ for (const [key, value] of Object.entries(headers)) {
1238
+ normalized[key.toLowerCase()] = value;
1239
+ }
1240
+ return normalized;
1241
+ }
1242
+ /**
1243
+ * Match user agent against rules
1244
+ */
1245
+ matchUserAgent(userAgent) {
1246
+ if (!this.rules) {
1247
+ return null;
1248
+ }
1249
+ const userAgents = this.rules.rules.userAgents;
1250
+ const genericKeys = ["generic_bot", "dev_tools", "automation_tools"];
1251
+ const entries = Object.entries(userAgents).sort((a, b) => {
1252
+ const aIsGeneric = genericKeys.includes(a[0]);
1253
+ const bIsGeneric = genericKeys.includes(b[0]);
1254
+ if (aIsGeneric && !bIsGeneric) return 1;
1255
+ if (!aIsGeneric && bIsGeneric) return -1;
1256
+ return 0;
1257
+ });
1258
+ for (const [agentKey, rule] of entries) {
1259
+ for (const pattern of rule.patterns) {
1260
+ try {
1261
+ const regex = new RegExp(pattern, "i");
1262
+ if (regex.test(userAgent)) {
1263
+ return {
1264
+ // Convert 0-1 rule confidence to 0-100 scale
1265
+ confidence: rule.confidence * 100,
1266
+ agentName: this.getAgentName(agentKey),
1267
+ agentKey
1268
+ };
1269
+ }
1270
+ } catch {
1271
+ }
1272
+ }
1273
+ }
1274
+ return null;
1275
+ }
1276
+ /**
1277
+ * Match headers against suspicious header rules
1278
+ */
1279
+ matchHeaders(headers) {
1280
+ if (!this.rules) {
1281
+ return { confidence: 0, count: 0 };
1282
+ }
1283
+ const suspicious = this.rules.rules.headers.suspicious || [];
1284
+ let maxConfidence = 0;
1285
+ let count = 0;
1286
+ for (const headerRule of suspicious) {
1287
+ if (headers[headerRule.name.toLowerCase()]) {
1288
+ maxConfidence = Math.max(maxConfidence, headerRule.confidence * 100);
1289
+ count++;
1290
+ }
1291
+ }
1292
+ return { confidence: maxConfidence, count };
1293
+ }
1294
+ /**
1295
+ * Check if signature headers are present
1296
+ */
1297
+ hasSignatureHeaders(headers) {
1298
+ return !!(headers["signature"] || headers["signature-input"] || headers["signature-agent"]);
1299
+ }
1300
+ /**
1301
+ * Get human-readable agent name from rule key
1302
+ */
1303
+ getAgentName(agentKey) {
1304
+ const nameMap = {
1305
+ openai_gptbot: "ChatGPT/GPTBot",
1306
+ anthropic_claude: "Claude",
1307
+ perplexity_bot: "Perplexity",
1308
+ google_ai: "Google AI",
1309
+ microsoft_ai: "Microsoft Copilot",
1310
+ meta_ai: "Meta AI",
1311
+ cohere_bot: "Cohere",
1312
+ huggingface_bot: "HuggingFace",
1313
+ generic_bot: "Generic Bot",
1314
+ dev_tools: "Development Tool",
1315
+ automation_tools: "Automation Tool"
1316
+ };
1317
+ return nameMap[agentKey] || agentKey;
1318
+ }
1319
+ /**
1320
+ * Infer agent type from name
1321
+ */
1322
+ inferAgentType(agentName) {
1323
+ const lowerName = agentName.toLowerCase();
1324
+ if (lowerName.includes("chatgpt") || lowerName.includes("gpt")) return "openai";
1325
+ if (lowerName.includes("claude")) return "anthropic";
1326
+ if (lowerName.includes("perplexity")) return "perplexity";
1327
+ if (lowerName.includes("google")) return "google";
1328
+ if (lowerName.includes("copilot") || lowerName.includes("bing")) return "microsoft";
1329
+ return "unknown";
1330
+ }
1331
+ /**
1332
+ * Determine detection class
1333
+ */
1334
+ determineDetectionClass(isAgent, agentName, confidence) {
1335
+ if (!isAgent || confidence < CONFIDENCE.THRESHOLD_AGENT) {
1336
+ return { type: "Human" };
1337
+ }
1338
+ if (agentName) {
1339
+ const lowerName = agentName.toLowerCase();
1340
+ const aiPatterns = ["chatgpt", "gpt", "claude", "perplexity", "gemini", "copilot"];
1341
+ if (aiPatterns.some((p) => lowerName.includes(p))) {
1342
+ return { type: "AiAgent", agentType: agentName };
1343
+ }
1344
+ if (lowerName.includes("bot") || lowerName.includes("crawler")) {
1345
+ return { type: "Bot", botType: agentName };
1346
+ }
1347
+ if (lowerName.includes("automation") || lowerName.includes("tool")) {
1348
+ return { type: "Automation", toolType: agentName };
1349
+ }
1350
+ return { type: "AiAgent", agentType: agentName };
1351
+ }
1352
+ return { type: "Unknown" };
1353
+ }
1354
+ };
1355
+ function createRulesDetector() {
1356
+ return new RulesDetector();
1357
+ }
1358
+
1359
+ // src/edge.ts
1360
+ function createEdgeDetector(wasmModule, options = {}) {
1361
+ const loader = new StaticWasmLoader(wasmModule);
1362
+ let policyLoader;
1363
+ if (options.apiKey) {
1364
+ policyLoader = new PolicyLoader({
1365
+ apiUrl: options.policyApiUrl,
1366
+ cacheTTL: options.policyTTL
1367
+ });
1368
+ }
1369
+ return new WasmDetector(loader, policyLoader, options);
1370
+ }
1371
+ function createFallbackDetector() {
1372
+ return new RulesDetector();
1373
+ }
1374
+ function extractInputFromRequest(request) {
1375
+ const headers = {};
1376
+ request.headers.forEach((value, key) => {
1377
+ headers[key] = value;
1378
+ });
1379
+ const url = new URL(request.url);
1380
+ return {
1381
+ userAgent: request.headers.get("user-agent") || void 0,
1382
+ ipAddress: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || void 0,
1383
+ headers,
1384
+ url: url.pathname + url.search,
1385
+ method: request.method
1386
+ };
1387
+ }
1388
+
1389
+ export { CONFIDENCE, PolicyLoader, RulesDetector, StaticWasmLoader, WasmDetector, createEdgeDetector, createFallbackDetector, createPolicyLoader, createRulesDetector, createStaticLoader, extractInputFromRequest };
1390
+ //# sourceMappingURL=edge.mjs.map
1391
+ //# sourceMappingURL=edge.mjs.map