@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/node.js ADDED
@@ -0,0 +1,972 @@
1
+ 'use strict';
2
+
3
+ var checkpointShared = require('@kya-os/checkpoint-shared');
4
+
5
+ // src/types.ts
6
+ var CONFIDENCE = {
7
+ /** Minimum confidence for isAgent=true */
8
+ THRESHOLD_AGENT: 30,
9
+ /** Cryptographic signature verified */
10
+ SIGNATURE_VERIFIED: 100,
11
+ /** Signature header present but not verified */
12
+ SIGNATURE_PRESENT: 85,
13
+ /** Strong pattern match */
14
+ PATTERN_HIGH: 85,
15
+ /** Moderate pattern match */
16
+ PATTERN_MEDIUM: 60,
17
+ /** Weak pattern match */
18
+ PATTERN_LOW: 40,
19
+ /** Cloud IP detection only */
20
+ CLOUD_IP: 30
21
+ };
22
+
23
+ // src/wasm-detector.ts
24
+ function parseVerificationMethod(method) {
25
+ switch (method.toLowerCase()) {
26
+ case "signature":
27
+ return "signature";
28
+ case "pattern":
29
+ return "pattern";
30
+ case "behavioral":
31
+ return "behavioral";
32
+ case "network":
33
+ return "network";
34
+ case "mcp_i_handshake":
35
+ return "mcp_i_handshake";
36
+ default:
37
+ return "none";
38
+ }
39
+ }
40
+ function determineForgeabilityRisk(method, confidence) {
41
+ if (method === "signature" && confidence >= 90) {
42
+ return "low";
43
+ }
44
+ if (confidence >= 80) {
45
+ return "medium";
46
+ }
47
+ return "high";
48
+ }
49
+ function determineDetectionClass(isAgent, agentName, confidence) {
50
+ if (!isAgent || confidence < CONFIDENCE.THRESHOLD_AGENT) {
51
+ return { type: "Human" };
52
+ }
53
+ if (agentName) {
54
+ const aiAgentPatterns = [
55
+ "chatgpt",
56
+ "gpt",
57
+ "openai",
58
+ "claude",
59
+ "anthropic",
60
+ "perplexity",
61
+ "gemini",
62
+ "google ai",
63
+ "copilot",
64
+ "bing chat"
65
+ ];
66
+ const lowerName = agentName.toLowerCase();
67
+ if (aiAgentPatterns.some((pattern) => lowerName.includes(pattern))) {
68
+ return { type: "AiAgent", agentType: agentName };
69
+ }
70
+ const botPatterns = ["bot", "crawler", "spider", "scraper"];
71
+ if (botPatterns.some((pattern) => lowerName.includes(pattern))) {
72
+ return { type: "Bot", botType: agentName };
73
+ }
74
+ const automationPatterns = ["selenium", "puppeteer", "playwright", "cypress"];
75
+ if (automationPatterns.some((pattern) => lowerName.includes(pattern))) {
76
+ return { type: "Automation", toolType: agentName };
77
+ }
78
+ return { type: "AiAgent", agentType: agentName };
79
+ }
80
+ return { type: "Unknown" };
81
+ }
82
+ var WasmDetector = class {
83
+ /**
84
+ * Create a new WasmDetector
85
+ * @param loader - WASM loader (static for Edge, dynamic for Node.js)
86
+ * @param policyLoader - Optional policy loader for API key support
87
+ * @param options - Detector configuration options
88
+ */
89
+ constructor(loader, policyLoader, options = {}) {
90
+ this.loader = loader;
91
+ this.policyLoader = policyLoader;
92
+ this.options = options;
93
+ }
94
+ ready = false;
95
+ loadPromise = null;
96
+ /**
97
+ * Analyze a request and detect if it's from an agent
98
+ */
99
+ async detect(input) {
100
+ await this.ensureReady();
101
+ try {
102
+ const bindings = this.loader.getBindings();
103
+ const metadata = {
104
+ user_agent: input.userAgent || null,
105
+ ip_address: input.ipAddress || null,
106
+ headers: JSON.stringify(input.headers || {}),
107
+ timestamp: (input.timestamp || /* @__PURE__ */ new Date()).toISOString(),
108
+ url: input.url || null,
109
+ method: input.method || null,
110
+ client_fingerprint: input.clientFingerprint || null,
111
+ free: () => {
112
+ }
113
+ // No-op for JS
114
+ };
115
+ const wasmResult = bindings.detect_agent(metadata);
116
+ const verificationMethod = parseVerificationMethod(wasmResult.verification_method);
117
+ const forgeabilityRisk = determineForgeabilityRisk(verificationMethod, wasmResult.confidence);
118
+ const detectionClass = determineDetectionClass(
119
+ wasmResult.is_agent,
120
+ wasmResult.agent,
121
+ wasmResult.confidence
122
+ );
123
+ let result = {
124
+ isAgent: wasmResult.is_agent,
125
+ confidence: wasmResult.confidence,
126
+ // Already 0-100, no conversion!
127
+ detectionClass,
128
+ detectedAgent: wasmResult.agent ? {
129
+ type: this.inferAgentType(wasmResult.agent),
130
+ name: wasmResult.agent
131
+ } : void 0,
132
+ verificationMethod,
133
+ forgeabilityRisk,
134
+ reasons: this.extractReasons(wasmResult),
135
+ timestamp: /* @__PURE__ */ new Date()
136
+ };
137
+ if (this.policyLoader && this.options.apiKey) {
138
+ result = await this.applyPolicy(result);
139
+ }
140
+ return result;
141
+ } catch (error) {
142
+ if (this.options.debug) {
143
+ console.error("[WasmDetector] Detection error:", error);
144
+ }
145
+ return this.createDefaultResult();
146
+ }
147
+ }
148
+ /**
149
+ * Check if the detector is ready
150
+ */
151
+ isReady() {
152
+ return this.ready;
153
+ }
154
+ /**
155
+ * Ensure the detector is initialized
156
+ */
157
+ async ensureReady() {
158
+ if (this.ready) {
159
+ return;
160
+ }
161
+ if (this.loadPromise) {
162
+ return this.loadPromise;
163
+ }
164
+ this.loadPromise = this.initialize();
165
+ return this.loadPromise;
166
+ }
167
+ /**
168
+ * Get detector version
169
+ */
170
+ async getVersion() {
171
+ await this.ensureReady();
172
+ return this.loader.getBindings().get_version();
173
+ }
174
+ /**
175
+ * Initialize the detector
176
+ */
177
+ async initialize() {
178
+ try {
179
+ await this.loader.load();
180
+ this.ready = true;
181
+ if (this.options.debug) {
182
+ const version = this.loader.getBindings().get_version();
183
+ console.log(
184
+ `[WasmDetector] Initialized with WASM v${version} (${this.loader.getStrategy()})`
185
+ );
186
+ }
187
+ } catch (error) {
188
+ this.loadPromise = null;
189
+ throw error;
190
+ }
191
+ }
192
+ /**
193
+ * Apply customer policy to detection result
194
+ */
195
+ async applyPolicy(result) {
196
+ if (!this.policyLoader || !this.options.apiKey) {
197
+ return result;
198
+ }
199
+ try {
200
+ let policy = this.policyLoader.getCachedPolicy(this.options.apiKey);
201
+ if (!policy) {
202
+ policy = await this.policyLoader.loadPolicy(this.options.apiKey);
203
+ }
204
+ return this.applyPolicyRules(result, policy);
205
+ } catch (error) {
206
+ if (this.options.debug) {
207
+ console.warn("[WasmDetector] Failed to load policy:", error);
208
+ }
209
+ return result;
210
+ }
211
+ }
212
+ /**
213
+ * Check if agent name matches a policy list entry
214
+ * Uses exact match or word-boundary prefix match to avoid false positives
215
+ * e.g., "gpt" matches "ChatGPT" and "GPT-4" but not "EgyptBot"
216
+ */
217
+ matchesPolicyEntry(agentName, policyEntry) {
218
+ const lowerAgent = agentName.toLowerCase();
219
+ const lowerEntry = policyEntry.toLowerCase();
220
+ if (lowerAgent === lowerEntry) {
221
+ return true;
222
+ }
223
+ const wordBoundaryRegex = new RegExp(
224
+ `(^|[^a-z0-9])${this.escapeRegex(lowerEntry)}($|[^a-z0-9])`,
225
+ "i"
226
+ );
227
+ return wordBoundaryRegex.test(lowerAgent);
228
+ }
229
+ /**
230
+ * Escape special regex characters in a string
231
+ */
232
+ escapeRegex(str) {
233
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
234
+ }
235
+ /**
236
+ * Apply policy rules to detection result
237
+ */
238
+ applyPolicyRules(result, policy) {
239
+ if (policy.denyList && result.detectedAgent) {
240
+ const agentName = result.detectedAgent.name;
241
+ const isDenied = policy.denyList.some((denied) => this.matchesPolicyEntry(agentName, denied));
242
+ if (isDenied) {
243
+ return {
244
+ ...result,
245
+ shouldBlock: true,
246
+ blockReason: "deny_list"
247
+ };
248
+ }
249
+ }
250
+ if (policy.allowList && policy.allowList.length > 0 && result.isAgent) {
251
+ const agentName = result.detectedAgent?.name;
252
+ if (!agentName) ; else {
253
+ const isAllowed = policy.allowList.some(
254
+ (allowed) => this.matchesPolicyEntry(agentName, allowed)
255
+ );
256
+ if (!isAllowed) {
257
+ return {
258
+ ...result,
259
+ shouldBlock: true,
260
+ blockReason: "not_in_allow_list"
261
+ };
262
+ }
263
+ return {
264
+ ...result,
265
+ shouldBlock: false
266
+ };
267
+ }
268
+ }
269
+ if (policy.blockThreshold !== void 0 && result.isAgent && result.confidence >= policy.blockThreshold) {
270
+ return {
271
+ ...result,
272
+ shouldBlock: true,
273
+ blockReason: "threshold"
274
+ };
275
+ }
276
+ return result;
277
+ }
278
+ /**
279
+ * Infer agent type from name
280
+ */
281
+ inferAgentType(agentName) {
282
+ const lowerName = agentName.toLowerCase();
283
+ if (lowerName.includes("chatgpt") || lowerName.includes("openai") || lowerName.includes("gpt")) {
284
+ return "openai";
285
+ }
286
+ if (lowerName.includes("claude") || lowerName.includes("anthropic")) {
287
+ return "anthropic";
288
+ }
289
+ if (lowerName.includes("perplexity")) {
290
+ return "perplexity";
291
+ }
292
+ if (lowerName.includes("gemini") || lowerName.includes("google")) {
293
+ return "google";
294
+ }
295
+ if (lowerName.includes("copilot") || lowerName.includes("bing")) {
296
+ return "microsoft";
297
+ }
298
+ return "unknown";
299
+ }
300
+ /**
301
+ * Extract reasons from WASM result
302
+ */
303
+ extractReasons(wasmResult) {
304
+ const reasons = [];
305
+ if (wasmResult.verification_method) {
306
+ reasons.push(`method:${wasmResult.verification_method}`);
307
+ }
308
+ if (wasmResult.agent) {
309
+ reasons.push(`agent:${wasmResult.agent.toLowerCase()}`);
310
+ }
311
+ return reasons;
312
+ }
313
+ /**
314
+ * Create default result (assumed human)
315
+ */
316
+ createDefaultResult() {
317
+ return {
318
+ isAgent: false,
319
+ confidence: 0,
320
+ detectionClass: { type: "Human" },
321
+ verificationMethod: "none",
322
+ forgeabilityRisk: "high",
323
+ reasons: ["detection_failed"],
324
+ timestamp: /* @__PURE__ */ new Date()
325
+ };
326
+ }
327
+ };
328
+
329
+ // src/loaders/dynamic-loader.ts
330
+ async function findWasmModule() {
331
+ const wasmPaths = [
332
+ // Relative to this package
333
+ "../wasm/agentshield_wasm_bg.wasm",
334
+ "./wasm/agentshield_wasm_bg.wasm",
335
+ // From agentshield-core package
336
+ "@kya-os/checkpoint/wasm/agentshield_wasm_bg.wasm",
337
+ // From monorepo build output
338
+ "../../rust/target/wasm32-unknown-unknown/release/agentshield_wasm_bg.wasm"
339
+ ];
340
+ for (const path of wasmPaths) {
341
+ try {
342
+ const module = await import(
343
+ /* webpackIgnore: true */
344
+ path
345
+ );
346
+ if (module.default && module.default instanceof ArrayBuffer) {
347
+ return module.default;
348
+ }
349
+ } catch {
350
+ }
351
+ }
352
+ try {
353
+ const fs = await import('fs/promises');
354
+ const nodePath = await import('path');
355
+ let moduleDir = null;
356
+ try {
357
+ const importMetaUrl = eval('typeof import.meta !== "undefined" && import.meta.url');
358
+ if (importMetaUrl) {
359
+ const url = await import('url');
360
+ moduleDir = nodePath.dirname(url.fileURLToPath(importMetaUrl));
361
+ }
362
+ } catch {
363
+ }
364
+ if (!moduleDir) {
365
+ try {
366
+ const cjsDirname = eval('typeof __dirname !== "undefined" && __dirname');
367
+ if (cjsDirname) {
368
+ moduleDir = cjsDirname;
369
+ }
370
+ } catch {
371
+ }
372
+ }
373
+ const fsWasmPaths = [
374
+ nodePath.resolve(
375
+ process.cwd(),
376
+ "node_modules/@kya-os/checkpoint-wasm-runtime/wasm/agentshield_wasm_bg.wasm"
377
+ ),
378
+ nodePath.resolve(
379
+ process.cwd(),
380
+ "node_modules/@kya-os/checkpoint/dist/wasm/agentshield_wasm_bg.wasm"
381
+ )
382
+ ];
383
+ if (moduleDir) {
384
+ fsWasmPaths.unshift(
385
+ nodePath.resolve(moduleDir, "../wasm/agentshield_wasm_bg.wasm"),
386
+ nodePath.resolve(moduleDir, "../../wasm/agentshield_wasm_bg.wasm")
387
+ );
388
+ }
389
+ for (const wasmPath of fsWasmPaths) {
390
+ try {
391
+ const buffer = await fs.readFile(wasmPath);
392
+ const arrayBuffer = new ArrayBuffer(buffer.byteLength);
393
+ new Uint8Array(arrayBuffer).set(buffer);
394
+ return arrayBuffer;
395
+ } catch {
396
+ }
397
+ }
398
+ } catch {
399
+ }
400
+ throw new Error(
401
+ "Could not find WASM module. Ensure @kya-os/checkpoint-wasm-runtime/wasm is installed."
402
+ );
403
+ }
404
+ var JsRequestMetadata = class {
405
+ constructor(user_agent, ip_address, headers, timestamp, url, method, client_fingerprint) {
406
+ this.user_agent = user_agent;
407
+ this.ip_address = ip_address;
408
+ this.headers = headers;
409
+ this.timestamp = timestamp;
410
+ this.url = url;
411
+ this.method = method;
412
+ this.client_fingerprint = client_fingerprint;
413
+ }
414
+ free() {
415
+ }
416
+ };
417
+ var DynamicWasmLoader = class {
418
+ /**
419
+ * Create a new DynamicWasmLoader
420
+ * @param wasmPath - Optional custom path to WASM file
421
+ */
422
+ constructor(wasmPath) {
423
+ this.wasmPath = wasmPath;
424
+ }
425
+ bindings = null;
426
+ instance = null;
427
+ loadPromise = null;
428
+ /**
429
+ * Load and compile the WASM module
430
+ */
431
+ async load() {
432
+ if (this.bindings) {
433
+ return;
434
+ }
435
+ if (this.loadPromise) {
436
+ return this.loadPromise;
437
+ }
438
+ this.loadPromise = this.doLoad();
439
+ return this.loadPromise;
440
+ }
441
+ async doLoad() {
442
+ try {
443
+ let wasmBuffer;
444
+ if (this.wasmPath) {
445
+ const fs2 = await import('fs/promises');
446
+ const buffer = await fs2.readFile(this.wasmPath);
447
+ wasmBuffer = new ArrayBuffer(buffer.byteLength);
448
+ new Uint8Array(wasmBuffer).set(buffer);
449
+ } else {
450
+ wasmBuffer = await findWasmModule();
451
+ }
452
+ const compiled = await WebAssembly.compile(wasmBuffer);
453
+ const imports = {
454
+ wbg: this.createWasmBindgenImports()
455
+ };
456
+ this.instance = await WebAssembly.instantiate(compiled, imports);
457
+ const exports$1 = this.instance.exports;
458
+ this.bindings = this.createBindings(exports$1);
459
+ } catch (error) {
460
+ this.loadPromise = null;
461
+ throw new Error(
462
+ `Failed to load WASM module: ${error instanceof Error ? error.message : String(error)}`
463
+ );
464
+ }
465
+ }
466
+ /**
467
+ * Get the WASM bindings after loading
468
+ */
469
+ getBindings() {
470
+ if (!this.bindings) {
471
+ throw new Error("WASM not loaded. Call load() first.");
472
+ }
473
+ return this.bindings;
474
+ }
475
+ /**
476
+ * Check if WASM is loaded
477
+ */
478
+ isLoaded() {
479
+ return this.bindings !== null;
480
+ }
481
+ /**
482
+ * Get the loading strategy name
483
+ */
484
+ getStrategy() {
485
+ return "dynamic-compile";
486
+ }
487
+ /**
488
+ * Create wasm-bindgen required imports
489
+ */
490
+ createWasmBindgenImports() {
491
+ return {
492
+ __wbg_log_f740dc2253ea759b: (ptr, len) => {
493
+ console.log("[WASM]", ptr, len);
494
+ },
495
+ __wbg_error_f851667af71bcfc6: (ptr, len) => {
496
+ console.error("[WASM Error]", ptr, len);
497
+ },
498
+ __wbg_now_c644db5194be8437: () => Date.now(),
499
+ __wbindgen_throw: (ptr, len) => {
500
+ throw new Error(`WASM threw: ${ptr}, ${len}`);
501
+ },
502
+ __wbindgen_object_drop_ref: () => {
503
+ }
504
+ };
505
+ }
506
+ /**
507
+ * Create bindings wrapper from WASM exports
508
+ */
509
+ createBindings(exports$1) {
510
+ const detectAgent = exports$1["detect_agent"];
511
+ const getVersion = exports$1["get_version"];
512
+ const getBuildInfo = exports$1["get_build_info"];
513
+ if (!detectAgent) {
514
+ throw new Error("WASM module missing detect_agent export");
515
+ }
516
+ return {
517
+ detect_agent: (metadata) => {
518
+ const wasmMetadata = new JsRequestMetadata(
519
+ metadata.user_agent,
520
+ metadata.ip_address,
521
+ metadata.headers,
522
+ metadata.timestamp,
523
+ metadata.url,
524
+ metadata.method,
525
+ metadata.client_fingerprint
526
+ );
527
+ try {
528
+ return detectAgent(wasmMetadata);
529
+ } finally {
530
+ wasmMetadata.free();
531
+ }
532
+ },
533
+ get_version: () => {
534
+ if (getVersion) {
535
+ return getVersion();
536
+ }
537
+ return "0.1.0-dynamic";
538
+ },
539
+ get_build_info: () => {
540
+ if (getBuildInfo) {
541
+ return getBuildInfo();
542
+ }
543
+ return JSON.stringify({ version: "0.1.0", strategy: "dynamic-compile" });
544
+ }
545
+ };
546
+ }
547
+ };
548
+ function createDynamicLoader(wasmPath) {
549
+ return new DynamicWasmLoader(wasmPath);
550
+ }
551
+
552
+ // src/policy/policy-loader.ts
553
+ var DEFAULT_CONFIG = {
554
+ apiUrl: "https://api.agentshield.io",
555
+ cacheTTL: 5 * 60 * 1e3,
556
+ // 5 minutes
557
+ maxCacheSize: 100,
558
+ backgroundRefresh: true,
559
+ timeout: 5e3
560
+ };
561
+ var PolicyLoader = class {
562
+ cache = /* @__PURE__ */ new Map();
563
+ config;
564
+ constructor(config = {}) {
565
+ this.config = { ...DEFAULT_CONFIG, ...config };
566
+ }
567
+ /**
568
+ * Load policy for an API key
569
+ */
570
+ async loadPolicy(apiKey) {
571
+ const cached = this.getCachedPolicy(apiKey);
572
+ if (cached) {
573
+ if (this.config.backgroundRefresh && this.shouldRefresh(apiKey)) {
574
+ this.refreshInBackground(apiKey);
575
+ }
576
+ return cached;
577
+ }
578
+ return this.fetchPolicy(apiKey);
579
+ }
580
+ /**
581
+ * Get cached policy if available and not expired
582
+ */
583
+ getCachedPolicy(apiKey) {
584
+ const entry = this.cache.get(apiKey);
585
+ if (!entry) {
586
+ return null;
587
+ }
588
+ if (this.isExpired(entry)) {
589
+ this.cache.delete(apiKey);
590
+ return null;
591
+ }
592
+ return entry.policy;
593
+ }
594
+ /**
595
+ * Invalidate cached policy
596
+ */
597
+ invalidateCache(apiKey) {
598
+ this.cache.delete(apiKey);
599
+ }
600
+ /**
601
+ * Fetch policy from API and cache it
602
+ */
603
+ async fetchPolicy(apiKey) {
604
+ const policy = await this.fetchPolicyFromApi(apiKey);
605
+ this.cachePolicy(apiKey, policy);
606
+ return policy;
607
+ }
608
+ /**
609
+ * Fetch policy from API without caching
610
+ * Used internally for both direct fetches and background refreshes
611
+ */
612
+ async fetchPolicyFromApi(apiKey) {
613
+ const controller = new AbortController();
614
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
615
+ try {
616
+ const response = await fetch(`${this.config.apiUrl}/api/v1/policy`, {
617
+ method: "GET",
618
+ headers: {
619
+ Authorization: `Bearer ${apiKey}`,
620
+ "Content-Type": "application/json",
621
+ "User-Agent": "agentshield-wasm-runtime/0.1.0"
622
+ },
623
+ signal: controller.signal
624
+ });
625
+ clearTimeout(timeoutId);
626
+ if (!response.ok) {
627
+ if (response.status === 401) {
628
+ throw new PolicyLoadError("Invalid API key", "INVALID_API_KEY");
629
+ }
630
+ if (response.status === 404) {
631
+ return this.getDefaultPolicy(apiKey);
632
+ }
633
+ throw new PolicyLoadError(`Failed to load policy: ${response.status}`, "API_ERROR");
634
+ }
635
+ return await response.json();
636
+ } catch (error) {
637
+ clearTimeout(timeoutId);
638
+ if (error instanceof PolicyLoadError) {
639
+ throw error;
640
+ }
641
+ if (error instanceof Error && error.name === "AbortError") {
642
+ throw new PolicyLoadError("Policy request timeout", "TIMEOUT");
643
+ }
644
+ throw new PolicyLoadError(
645
+ `Failed to load policy: ${error instanceof Error ? error.message : "Unknown error"}`,
646
+ "NETWORK_ERROR"
647
+ );
648
+ }
649
+ }
650
+ /**
651
+ * Cache a policy
652
+ */
653
+ cachePolicy(apiKey, policy) {
654
+ if (this.cache.size >= this.config.maxCacheSize) {
655
+ const oldestKey = this.cache.keys().next().value;
656
+ if (oldestKey) {
657
+ this.cache.delete(oldestKey);
658
+ }
659
+ }
660
+ this.cache.set(apiKey, {
661
+ policy,
662
+ loadedAt: Date.now(),
663
+ refreshing: false
664
+ });
665
+ }
666
+ /**
667
+ * Check if cached entry is expired
668
+ */
669
+ isExpired(entry) {
670
+ return Date.now() - entry.loadedAt > this.config.cacheTTL;
671
+ }
672
+ /**
673
+ * Check if cache entry should be refreshed
674
+ */
675
+ shouldRefresh(apiKey) {
676
+ const entry = this.cache.get(apiKey);
677
+ if (!entry) {
678
+ return false;
679
+ }
680
+ const refreshThreshold = this.config.cacheTTL * 0.8;
681
+ return Date.now() - entry.loadedAt > refreshThreshold && !entry.refreshing;
682
+ }
683
+ /**
684
+ * Refresh policy in background
685
+ */
686
+ async refreshInBackground(apiKey) {
687
+ const entry = this.cache.get(apiKey);
688
+ if (!entry || entry.refreshing) {
689
+ return;
690
+ }
691
+ entry.refreshing = true;
692
+ try {
693
+ const policy = await this.fetchPolicyFromApi(apiKey);
694
+ this.cachePolicy(apiKey, policy);
695
+ } catch {
696
+ } finally {
697
+ const currentEntry = this.cache.get(apiKey);
698
+ if (currentEntry && currentEntry.refreshing) {
699
+ currentEntry.refreshing = false;
700
+ }
701
+ }
702
+ }
703
+ /**
704
+ * Get default policy for a project
705
+ */
706
+ getDefaultPolicy(apiKey) {
707
+ return {
708
+ projectId: apiKey.split("_")[1] || "unknown",
709
+ blockThreshold: 90
710
+ };
711
+ }
712
+ };
713
+ var PolicyLoadError = class extends Error {
714
+ constructor(message, code) {
715
+ super(message);
716
+ this.code = code;
717
+ this.name = "PolicyLoadError";
718
+ }
719
+ };
720
+ function createPolicyLoader(config) {
721
+ return new PolicyLoader(config);
722
+ }
723
+ var RulesDetector = class {
724
+ rules = null;
725
+ ready = false;
726
+ /**
727
+ * Analyze a request and detect if it's from an agent
728
+ */
729
+ async detect(input) {
730
+ await this.ensureReady();
731
+ const reasons = [];
732
+ let confidence = 0;
733
+ let detectedAgentName = null;
734
+ let verificationMethod = "none";
735
+ const userAgent = input.userAgent || input.headers["user-agent"] || "";
736
+ const normalizedHeaders = this.normalizeHeaders(input.headers);
737
+ if (userAgent && this.rules) {
738
+ const uaMatch = this.matchUserAgent(userAgent);
739
+ if (uaMatch) {
740
+ confidence = Math.max(confidence, uaMatch.confidence);
741
+ detectedAgentName = uaMatch.agentName;
742
+ verificationMethod = "pattern";
743
+ reasons.push(`pattern:${uaMatch.agentKey}`);
744
+ }
745
+ }
746
+ if (this.rules) {
747
+ const headerMatch = this.matchHeaders(normalizedHeaders);
748
+ if (headerMatch.confidence > 0) {
749
+ confidence = Math.max(confidence, headerMatch.confidence);
750
+ reasons.push(`headers:${headerMatch.count}`);
751
+ }
752
+ }
753
+ if (this.hasSignatureHeaders(normalizedHeaders)) {
754
+ confidence = Math.max(confidence, CONFIDENCE.SIGNATURE_PRESENT);
755
+ reasons.push("signature_headers_present");
756
+ verificationMethod = "pattern";
757
+ }
758
+ const isAgent = confidence > CONFIDENCE.THRESHOLD_AGENT;
759
+ const detectionClass = this.determineDetectionClass(isAgent, detectedAgentName, confidence);
760
+ return {
761
+ isAgent,
762
+ confidence,
763
+ detectionClass,
764
+ detectedAgent: detectedAgentName ? {
765
+ type: this.inferAgentType(detectedAgentName),
766
+ name: detectedAgentName
767
+ } : void 0,
768
+ verificationMethod,
769
+ forgeabilityRisk: "high",
770
+ // JS fallback is always high risk
771
+ reasons,
772
+ timestamp: /* @__PURE__ */ new Date()
773
+ };
774
+ }
775
+ /**
776
+ * Check if the detector is ready
777
+ */
778
+ isReady() {
779
+ return this.ready;
780
+ }
781
+ /**
782
+ * Ensure the detector is initialized
783
+ */
784
+ async ensureReady() {
785
+ if (this.ready) {
786
+ return;
787
+ }
788
+ try {
789
+ this.rules = checkpointShared.loadRulesSync();
790
+ this.ready = true;
791
+ } catch (error) {
792
+ console.warn("[RulesDetector] Failed to load rules:", error);
793
+ this.ready = true;
794
+ }
795
+ }
796
+ /**
797
+ * Get detector version
798
+ */
799
+ async getVersion() {
800
+ return "0.1.0-js-fallback";
801
+ }
802
+ /**
803
+ * Normalize headers to lowercase keys
804
+ */
805
+ normalizeHeaders(headers) {
806
+ const normalized = {};
807
+ for (const [key, value] of Object.entries(headers)) {
808
+ normalized[key.toLowerCase()] = value;
809
+ }
810
+ return normalized;
811
+ }
812
+ /**
813
+ * Match user agent against rules
814
+ */
815
+ matchUserAgent(userAgent) {
816
+ if (!this.rules) {
817
+ return null;
818
+ }
819
+ const userAgents = this.rules.rules.userAgents;
820
+ const genericKeys = ["generic_bot", "dev_tools", "automation_tools"];
821
+ const entries = Object.entries(userAgents).sort((a, b) => {
822
+ const aIsGeneric = genericKeys.includes(a[0]);
823
+ const bIsGeneric = genericKeys.includes(b[0]);
824
+ if (aIsGeneric && !bIsGeneric) return 1;
825
+ if (!aIsGeneric && bIsGeneric) return -1;
826
+ return 0;
827
+ });
828
+ for (const [agentKey, rule] of entries) {
829
+ for (const pattern of rule.patterns) {
830
+ try {
831
+ const regex = new RegExp(pattern, "i");
832
+ if (regex.test(userAgent)) {
833
+ return {
834
+ // Convert 0-1 rule confidence to 0-100 scale
835
+ confidence: rule.confidence * 100,
836
+ agentName: this.getAgentName(agentKey),
837
+ agentKey
838
+ };
839
+ }
840
+ } catch {
841
+ }
842
+ }
843
+ }
844
+ return null;
845
+ }
846
+ /**
847
+ * Match headers against suspicious header rules
848
+ */
849
+ matchHeaders(headers) {
850
+ if (!this.rules) {
851
+ return { confidence: 0, count: 0 };
852
+ }
853
+ const suspicious = this.rules.rules.headers.suspicious || [];
854
+ let maxConfidence = 0;
855
+ let count = 0;
856
+ for (const headerRule of suspicious) {
857
+ if (headers[headerRule.name.toLowerCase()]) {
858
+ maxConfidence = Math.max(maxConfidence, headerRule.confidence * 100);
859
+ count++;
860
+ }
861
+ }
862
+ return { confidence: maxConfidence, count };
863
+ }
864
+ /**
865
+ * Check if signature headers are present
866
+ */
867
+ hasSignatureHeaders(headers) {
868
+ return !!(headers["signature"] || headers["signature-input"] || headers["signature-agent"]);
869
+ }
870
+ /**
871
+ * Get human-readable agent name from rule key
872
+ */
873
+ getAgentName(agentKey) {
874
+ const nameMap = {
875
+ openai_gptbot: "ChatGPT/GPTBot",
876
+ anthropic_claude: "Claude",
877
+ perplexity_bot: "Perplexity",
878
+ google_ai: "Google AI",
879
+ microsoft_ai: "Microsoft Copilot",
880
+ meta_ai: "Meta AI",
881
+ cohere_bot: "Cohere",
882
+ huggingface_bot: "HuggingFace",
883
+ generic_bot: "Generic Bot",
884
+ dev_tools: "Development Tool",
885
+ automation_tools: "Automation Tool"
886
+ };
887
+ return nameMap[agentKey] || agentKey;
888
+ }
889
+ /**
890
+ * Infer agent type from name
891
+ */
892
+ inferAgentType(agentName) {
893
+ const lowerName = agentName.toLowerCase();
894
+ if (lowerName.includes("chatgpt") || lowerName.includes("gpt")) return "openai";
895
+ if (lowerName.includes("claude")) return "anthropic";
896
+ if (lowerName.includes("perplexity")) return "perplexity";
897
+ if (lowerName.includes("google")) return "google";
898
+ if (lowerName.includes("copilot") || lowerName.includes("bing")) return "microsoft";
899
+ return "unknown";
900
+ }
901
+ /**
902
+ * Determine detection class
903
+ */
904
+ determineDetectionClass(isAgent, agentName, confidence) {
905
+ if (!isAgent || confidence < CONFIDENCE.THRESHOLD_AGENT) {
906
+ return { type: "Human" };
907
+ }
908
+ if (agentName) {
909
+ const lowerName = agentName.toLowerCase();
910
+ const aiPatterns = ["chatgpt", "gpt", "claude", "perplexity", "gemini", "copilot"];
911
+ if (aiPatterns.some((p) => lowerName.includes(p))) {
912
+ return { type: "AiAgent", agentType: agentName };
913
+ }
914
+ if (lowerName.includes("bot") || lowerName.includes("crawler")) {
915
+ return { type: "Bot", botType: agentName };
916
+ }
917
+ if (lowerName.includes("automation") || lowerName.includes("tool")) {
918
+ return { type: "Automation", toolType: agentName };
919
+ }
920
+ return { type: "AiAgent", agentType: agentName };
921
+ }
922
+ return { type: "Unknown" };
923
+ }
924
+ };
925
+ function createRulesDetector() {
926
+ return new RulesDetector();
927
+ }
928
+
929
+ // src/node.ts
930
+ function createNodeDetector(options = {}) {
931
+ const loader = new DynamicWasmLoader();
932
+ let policyLoader;
933
+ if (options.apiKey) {
934
+ policyLoader = new PolicyLoader({
935
+ apiUrl: options.policyApiUrl,
936
+ cacheTTL: options.policyTTL
937
+ });
938
+ }
939
+ return new WasmDetector(loader, policyLoader, options);
940
+ }
941
+ function createFallbackDetector() {
942
+ return new RulesDetector();
943
+ }
944
+ function extractInputFromExpressRequest(req) {
945
+ const headers = {};
946
+ for (const [key, value] of Object.entries(req.headers)) {
947
+ if (value) {
948
+ headers[key] = Array.isArray(value) ? value[0] : value;
949
+ }
950
+ }
951
+ return {
952
+ userAgent: headers["user-agent"],
953
+ ipAddress: req.ip || headers["x-forwarded-for"]?.split(",")[0]?.trim() || headers["x-real-ip"],
954
+ headers,
955
+ url: req.url,
956
+ method: req.method
957
+ };
958
+ }
959
+
960
+ exports.CONFIDENCE = CONFIDENCE;
961
+ exports.DynamicWasmLoader = DynamicWasmLoader;
962
+ exports.PolicyLoader = PolicyLoader;
963
+ exports.RulesDetector = RulesDetector;
964
+ exports.WasmDetector = WasmDetector;
965
+ exports.createDynamicLoader = createDynamicLoader;
966
+ exports.createFallbackDetector = createFallbackDetector;
967
+ exports.createNodeDetector = createNodeDetector;
968
+ exports.createPolicyLoader = createPolicyLoader;
969
+ exports.createRulesDetector = createRulesDetector;
970
+ exports.extractInputFromExpressRequest = extractInputFromExpressRequest;
971
+ //# sourceMappingURL=node.js.map
972
+ //# sourceMappingURL=node.js.map