@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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/wasm-detector.ts","../src/loaders/dynamic-loader.ts","../src/policy/policy-loader.ts","../src/fallback/rules-detector.ts","../src/node.ts"],"names":["fs","exports"],"mappings":";;;AAuOO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,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,GAA8C,EAAC,EAClB;AAC7B,EAAA,MAAM,MAAA,GAAS,IAAI,iBAAA,EAAkB;AAErC,EAAA,IAAI,YAAA;AACJ,EAAA,IAAI,QAAQ,MAAA,EAAQ;AAClB,IAAA,YAAA,GAAe,IAAI,YAAA,CAAa;AAAA,MAC9B,QAAQ,OAAA,CAAQ,YAAA;AAAA,MAChB,UAAU,OAAA,CAAQ;AAAA,KACnB,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,IAAI,YAAA,CAAa,MAAA,EAAQ,YAAA,EAAc,OAAO,CAAA;AACvD;AAMO,SAAS,sBAAA,GAAsD;AACpE,EAAA,OAAO,IAAI,aAAA,EAAc;AAC3B;AAKO,SAAS,+BAA+B,GAAA,EAKT;AAEpC,EAAA,MAAM,UAAkC,EAAC;AACzC,EAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,GAAA,CAAI,OAAO,CAAA,EAAG;AACtD,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,OAAA,CAAQ,GAAG,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAA,CAAM,CAAC,CAAA,GAAI,KAAA;AAAA,IACnD;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,QAAQ,YAAY,CAAA;AAAA,IAC/B,SAAA,EAAW,GAAA,CAAI,EAAA,IAAM,OAAA,CAAQ,iBAAiB,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAG,IAAA,EAAK,IAAK,QAAQ,WAAW,CAAA;AAAA,IAC7F,OAAA;AAAA,IACA,KAAK,GAAA,CAAI,GAAA;AAAA,IACT,QAAQ,GAAA,CAAI;AAAA,GACd;AACF","file":"node.mjs","sourcesContent":["/**\n * AgentShield WASM Runtime Types\n *\n * Core interfaces following SOLID principles:\n * - Interface Segregation: Small, focused interfaces\n * - Dependency Inversion: Depend on abstractions\n */\n\n/**\n * Detection input - information about the request to analyze\n */\nexport interface IDetectionInput {\n /** User-Agent header value */\n userAgent?: string;\n /** Client IP address */\n ipAddress?: string;\n /** All request headers */\n headers: Record<string, string>;\n /** Request URL path */\n url?: string;\n /** HTTP method (GET, POST, etc.) */\n method?: string;\n /** Client fingerprint data (for browser detection) */\n clientFingerprint?: string;\n /** Request timestamp */\n timestamp?: Date;\n}\n\n/**\n * Verification method used to detect the agent\n */\nexport type VerificationMethod =\n | 'signature' // Cryptographic signature verification (highest confidence)\n | 'pattern' // User-agent or header pattern matching\n | 'behavioral' // Behavioral analysis\n | 'network' // Network/IP-based detection\n | 'mcp_i_handshake' // MCP-I protocol handshake\n | 'none'; // No verification method\n\n/**\n * Detection class - categorization of the detected entity\n */\nexport type DetectionClass =\n | { type: 'Human' }\n | { type: 'AiAgent'; agentType: string }\n | { type: 'Bot'; botType?: string }\n | { type: 'Automation'; toolType?: string }\n | { type: 'Unknown' };\n\n/**\n * Forgeability risk level\n * How easy it is to spoof the detection signals\n */\nexport type ForgeabilityRisk = 'low' | 'medium' | 'high';\n\n/**\n * Detected agent information\n */\nexport interface IDetectedAgent {\n /** Agent type identifier (e.g., 'openai', 'anthropic') */\n type: string;\n /** Human-readable agent name (e.g., 'ChatGPT', 'Claude') */\n name: string;\n /** Vendor/company name */\n vendor?: string;\n /** Model identifier if known */\n model?: string;\n /** Version if known */\n version?: string;\n}\n\n/**\n * Detection result - output from the detection engine\n * Confidence is ALWAYS on 0-100 scale\n */\nexport interface IDetectionResult {\n /** Whether the request was identified as coming from an agent */\n isAgent: boolean;\n /** Confidence score on 0-100 scale (NOT 0-1) */\n confidence: number;\n /** Detection classification */\n detectionClass: DetectionClass;\n /** Detected agent details if identified */\n detectedAgent?: IDetectedAgent;\n /** Method used for verification */\n verificationMethod: VerificationMethod;\n /** Risk level of signal forgeability */\n forgeabilityRisk: ForgeabilityRisk;\n /** Reasons/signals that contributed to detection */\n reasons: string[];\n /** Detection timestamp */\n timestamp: Date;\n /** Whether the request should be blocked (set by policy) */\n shouldBlock?: boolean;\n /** Reason for blocking (set by policy) */\n blockReason?: string;\n}\n\n/**\n * WASM bindings interface - functions exposed by the WASM module\n */\nexport interface IWasmBindings {\n /** Detect an agent from request metadata */\n detect_agent(metadata: IWasmRequestMetadata): IWasmDetectionResult;\n /** Get WASM module version */\n get_version(): string;\n /** Get build information */\n get_build_info(): string;\n}\n\n/**\n * WASM request metadata - input to WASM detect_agent function\n */\nexport interface IWasmRequestMetadata {\n user_agent: string | null;\n ip_address: string | null;\n headers: string; // JSON string\n timestamp: string; // ISO 8601\n url: string | null;\n method: string | null;\n client_fingerprint: string | null;\n free(): void;\n}\n\n/**\n * WASM detection result - output from WASM detect_agent function\n */\nexport interface IWasmDetectionResult {\n is_agent: boolean;\n confidence: number; // 0-100 scale (converted at WASM boundary)\n agent: string | null;\n verification_method: string;\n risk_level: string;\n timestamp: string;\n}\n\n/**\n * WASM loader interface - abstracts WASM loading strategy\n */\nexport interface IWasmLoader {\n /** Load the WASM module */\n load(): Promise<void>;\n /** Get the WASM bindings after loading */\n getBindings(): IWasmBindings;\n /** Check if WASM is loaded */\n isLoaded(): boolean;\n /** Get the loading strategy name */\n getStrategy(): string;\n}\n\n/**\n * Agent detector interface - main detection API\n */\nexport interface IDetector {\n /** Analyze a request and detect if it's from an agent */\n detect(input: IDetectionInput): Promise<IDetectionResult>;\n /** Check if the detector is ready */\n isReady(): boolean;\n /** Ensure the detector is initialized */\n ensureReady(): Promise<void>;\n /** Get detector version */\n getVersion(): Promise<string>;\n}\n\n/**\n * Customer policy - rules for agent handling\n */\nexport interface ICustomerPolicy {\n /** Project ID */\n projectId: string;\n /** Agents to always block */\n denyList?: string[];\n /** Agents to always allow (if set, blocks all others) */\n allowList?: string[];\n /** Minimum confidence to trigger blocking */\n blockThreshold?: number;\n /** Path-based rules */\n pathRules?: IPathRule[];\n /** Policy version for cache invalidation */\n version?: string;\n /** Last updated timestamp */\n updatedAt?: Date;\n}\n\n/**\n * Path-based rule for policy\n */\nexport interface IPathRule {\n /** Path pattern (glob or regex) */\n pattern: string;\n /** Action for matching paths */\n action: 'allow' | 'block' | 'challenge';\n /** Specific agents this rule applies to */\n agents?: string[];\n}\n\n/**\n * Policy loader interface - loads customer policies\n */\nexport interface IPolicyLoader {\n /** Load policy for an API key */\n loadPolicy(apiKey: string): Promise<ICustomerPolicy>;\n /** Get cached policy if available */\n getCachedPolicy(apiKey: string): ICustomerPolicy | null;\n /** Invalidate cached policy */\n invalidateCache(apiKey: string): void;\n}\n\n/**\n * Detector configuration options\n */\nexport interface IDetectorOptions {\n /** API key for loading customer policies */\n apiKey?: string;\n /** Custom WASM loader (for Edge Runtime static imports) */\n wasmLoader?: IWasmLoader;\n /** Whether to fall back to JavaScript if WASM fails */\n fallbackToJS?: boolean;\n /** Whether to cache policies */\n cachePolicy?: boolean;\n /** Policy cache TTL in milliseconds */\n policyTTL?: number;\n /** Base URL for policy API */\n policyApiUrl?: string;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Confidence thresholds - centralized constants\n */\nexport const CONFIDENCE = {\n /** Minimum confidence for isAgent=true */\n THRESHOLD_AGENT: 30,\n /** Cryptographic signature verified */\n SIGNATURE_VERIFIED: 100,\n /** Signature header present but not verified */\n SIGNATURE_PRESENT: 85,\n /** Strong pattern match */\n PATTERN_HIGH: 85,\n /** Moderate pattern match */\n PATTERN_MEDIUM: 60,\n /** Weak pattern match */\n PATTERN_LOW: 40,\n /** Cloud IP detection only */\n CLOUD_IP: 30,\n} as const;\n","/**\n * Unified WASM Detector\n *\n * Single implementation of the AgentShield detection engine used by all packages.\n * Follows the Single Responsibility Principle: this class only handles detection.\n *\n * Key design decisions:\n * - Confidence is ALWAYS on 0-100 scale (no conversions needed)\n * - WASM output is used directly (no post-processing adjustments)\n * - Policy application is optional and happens after detection\n */\n\nimport type {\n IDetector,\n IDetectionInput,\n IDetectionResult,\n IWasmLoader,\n IWasmRequestMetadata,\n IPolicyLoader,\n ICustomerPolicy,\n DetectionClass,\n VerificationMethod,\n ForgeabilityRisk,\n IDetectorOptions,\n} from './types';\nimport { CONFIDENCE } from './types';\n\n/**\n * Convert verification method string from WASM to typed enum\n */\nfunction parseVerificationMethod(method: string): VerificationMethod {\n switch (method.toLowerCase()) {\n case 'signature':\n return 'signature';\n case 'pattern':\n return 'pattern';\n case 'behavioral':\n return 'behavioral';\n case 'network':\n return 'network';\n case 'mcp_i_handshake':\n return 'mcp_i_handshake';\n default:\n return 'none';\n }\n}\n\n/**\n * Determine forgeability risk based on verification method and confidence\n */\nfunction determineForgeabilityRisk(\n method: VerificationMethod,\n confidence: number\n): ForgeabilityRisk {\n // Cryptographic signature verification = low risk\n if (method === 'signature' && confidence >= 90) {\n return 'low';\n }\n\n // High confidence pattern match = medium risk\n if (confidence >= 80) {\n return 'medium';\n }\n\n // Everything else = high risk (easily spoofable)\n return 'high';\n}\n\n/**\n * Determine detection class from WASM result\n */\nfunction determineDetectionClass(\n isAgent: boolean,\n agentName: string | null,\n confidence: number\n): DetectionClass {\n if (!isAgent || confidence < CONFIDENCE.THRESHOLD_AGENT) {\n return { type: 'Human' };\n }\n\n if (agentName) {\n // Check if it's an AI agent\n const aiAgentPatterns = [\n 'chatgpt',\n 'gpt',\n 'openai',\n 'claude',\n 'anthropic',\n 'perplexity',\n 'gemini',\n 'google ai',\n 'copilot',\n 'bing chat',\n ];\n\n const lowerName = agentName.toLowerCase();\n if (aiAgentPatterns.some((pattern) => lowerName.includes(pattern))) {\n return { type: 'AiAgent', agentType: agentName };\n }\n\n // Check if it's a bot\n const botPatterns = ['bot', 'crawler', 'spider', 'scraper'];\n if (botPatterns.some((pattern) => lowerName.includes(pattern))) {\n return { type: 'Bot', botType: agentName };\n }\n\n // Check if it's automation\n const automationPatterns = ['selenium', 'puppeteer', 'playwright', 'cypress'];\n if (automationPatterns.some((pattern) => lowerName.includes(pattern))) {\n return { type: 'Automation', toolType: agentName };\n }\n\n // Default to AI agent if detected but unrecognized\n return { type: 'AiAgent', agentType: agentName };\n }\n\n return { type: 'Unknown' };\n}\n\n/**\n * Unified WASM Detector\n *\n * Main detection class that wraps the WASM engine and provides\n * a consistent interface across all AgentShield packages.\n */\nexport class WasmDetector implements IDetector {\n private ready = false;\n private loadPromise: Promise<void> | null = null;\n\n /**\n * Create a new WasmDetector\n * @param loader - WASM loader (static for Edge, dynamic for Node.js)\n * @param policyLoader - Optional policy loader for API key support\n * @param options - Detector configuration options\n */\n constructor(\n private readonly loader: IWasmLoader,\n private readonly policyLoader?: IPolicyLoader,\n private readonly options: IDetectorOptions = {}\n ) {}\n\n /**\n * Analyze a request and detect if it's from an agent\n */\n async detect(input: IDetectionInput): Promise<IDetectionResult> {\n // Ensure WASM is loaded\n await this.ensureReady();\n\n try {\n // Get WASM bindings\n const bindings = this.loader.getBindings();\n\n // Create WASM metadata\n const metadata: IWasmRequestMetadata = {\n user_agent: input.userAgent || null,\n ip_address: input.ipAddress || null,\n headers: JSON.stringify(input.headers || {}),\n timestamp: (input.timestamp || new Date()).toISOString(),\n url: input.url || null,\n method: input.method || null,\n client_fingerprint: input.clientFingerprint || null,\n free: () => {}, // No-op for JS\n };\n\n // Call WASM detection\n const wasmResult = bindings.detect_agent(metadata);\n\n // Convert WASM result to IDetectionResult\n // NOTE: WASM already outputs confidence on 0-100 scale\n // No conversion needed!\n const verificationMethod = parseVerificationMethod(wasmResult.verification_method);\n const forgeabilityRisk = determineForgeabilityRisk(verificationMethod, wasmResult.confidence);\n const detectionClass = determineDetectionClass(\n wasmResult.is_agent,\n wasmResult.agent,\n wasmResult.confidence\n );\n\n let result: IDetectionResult = {\n isAgent: wasmResult.is_agent,\n confidence: wasmResult.confidence, // Already 0-100, no conversion!\n detectionClass,\n detectedAgent: wasmResult.agent\n ? {\n type: this.inferAgentType(wasmResult.agent),\n name: wasmResult.agent,\n }\n : undefined,\n verificationMethod,\n forgeabilityRisk,\n reasons: this.extractReasons(wasmResult),\n timestamp: new Date(),\n };\n\n // Apply customer policy if available\n if (this.policyLoader && this.options.apiKey) {\n result = await this.applyPolicy(result);\n }\n\n return result;\n } catch (error) {\n // Log error if debug enabled\n if (this.options.debug) {\n console.error('[WasmDetector] Detection error:', error);\n }\n\n // Return safe default (assume human)\n return this.createDefaultResult();\n }\n }\n\n /**\n * Check if the detector is ready\n */\n isReady(): boolean {\n return this.ready;\n }\n\n /**\n * Ensure the detector is initialized\n */\n async ensureReady(): Promise<void> {\n if (this.ready) {\n return;\n }\n\n if (this.loadPromise) {\n return this.loadPromise;\n }\n\n this.loadPromise = this.initialize();\n return this.loadPromise;\n }\n\n /**\n * Get detector version\n */\n async getVersion(): Promise<string> {\n await this.ensureReady();\n return this.loader.getBindings().get_version();\n }\n\n /**\n * Initialize the detector\n */\n private async initialize(): Promise<void> {\n try {\n await this.loader.load();\n this.ready = true;\n\n if (this.options.debug) {\n const version = this.loader.getBindings().get_version();\n console.log(\n `[WasmDetector] Initialized with WASM v${version} (${this.loader.getStrategy()})`\n );\n }\n } catch (error) {\n this.loadPromise = null;\n throw error;\n }\n }\n\n /**\n * Apply customer policy to detection result\n */\n private async applyPolicy(result: IDetectionResult): Promise<IDetectionResult> {\n if (!this.policyLoader || !this.options.apiKey) {\n return result;\n }\n\n try {\n // Try to get cached policy first\n let policy = this.policyLoader.getCachedPolicy(this.options.apiKey);\n\n // Load policy if not cached\n if (!policy) {\n policy = await this.policyLoader.loadPolicy(this.options.apiKey);\n }\n\n return this.applyPolicyRules(result, policy);\n } catch (error) {\n if (this.options.debug) {\n console.warn('[WasmDetector] Failed to load policy:', error);\n }\n // Return original result if policy loading fails\n return result;\n }\n }\n\n /**\n * Check if agent name matches a policy list entry\n * Uses exact match or word-boundary prefix match to avoid false positives\n * e.g., \"gpt\" matches \"ChatGPT\" and \"GPT-4\" but not \"EgyptBot\"\n */\n private matchesPolicyEntry(agentName: string, policyEntry: string): boolean {\n const lowerAgent = agentName.toLowerCase();\n const lowerEntry = policyEntry.toLowerCase();\n\n // Exact match\n if (lowerAgent === lowerEntry) {\n return true;\n }\n\n // Word boundary match: entry appears as a complete word or at word boundaries\n // This prevents \"ai\" from matching \"baidubot\" while allowing \"gpt\" to match \"chatgpt\"\n const wordBoundaryRegex = new RegExp(\n `(^|[^a-z0-9])${this.escapeRegex(lowerEntry)}($|[^a-z0-9])`,\n 'i'\n );\n return wordBoundaryRegex.test(lowerAgent);\n }\n\n /**\n * Escape special regex characters in a string\n */\n private escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n\n /**\n * Apply policy rules to detection result\n */\n private applyPolicyRules(result: IDetectionResult, policy: ICustomerPolicy): IDetectionResult {\n // Check deny list\n if (policy.denyList && result.detectedAgent) {\n const agentName = result.detectedAgent.name;\n const isDenied = policy.denyList.some((denied) => this.matchesPolicyEntry(agentName, denied));\n\n if (isDenied) {\n return {\n ...result,\n shouldBlock: true,\n blockReason: 'deny_list',\n };\n }\n }\n\n // Check allow list (if set, blocks everything not in list, but allows listed agents)\n if (policy.allowList && policy.allowList.length > 0 && result.isAgent) {\n const agentName = result.detectedAgent?.name;\n\n // If agent was detected but not identified (no name), skip allow list check\n // Allow list is for named agents only - unidentified agents go through threshold check\n if (!agentName) {\n // Fall through to threshold check below\n } else {\n const isAllowed = policy.allowList.some((allowed) =>\n this.matchesPolicyEntry(agentName, allowed)\n );\n\n if (!isAllowed) {\n return {\n ...result,\n shouldBlock: true,\n blockReason: 'not_in_allow_list',\n };\n }\n\n // Agent is explicitly allowed - skip threshold check and don't block\n return {\n ...result,\n shouldBlock: false,\n };\n }\n }\n\n // Check confidence threshold (only for detected agents not in allow list)\n // Use !== undefined instead of truthiness check since 0 is a valid threshold\n // (meaning \"block all detected agents regardless of confidence\")\n if (\n policy.blockThreshold !== undefined &&\n result.isAgent &&\n result.confidence >= policy.blockThreshold\n ) {\n return {\n ...result,\n shouldBlock: true,\n blockReason: 'threshold',\n };\n }\n\n return result;\n }\n\n /**\n * Infer agent type from name\n */\n private inferAgentType(agentName: string): string {\n const lowerName = agentName.toLowerCase();\n\n if (\n lowerName.includes('chatgpt') ||\n lowerName.includes('openai') ||\n lowerName.includes('gpt')\n ) {\n return 'openai';\n }\n if (lowerName.includes('claude') || lowerName.includes('anthropic')) {\n return 'anthropic';\n }\n if (lowerName.includes('perplexity')) {\n return 'perplexity';\n }\n if (lowerName.includes('gemini') || lowerName.includes('google')) {\n return 'google';\n }\n if (lowerName.includes('copilot') || lowerName.includes('bing')) {\n return 'microsoft';\n }\n\n return 'unknown';\n }\n\n /**\n * Extract reasons from WASM result\n */\n private extractReasons(wasmResult: {\n verification_method: string;\n agent: string | null;\n }): string[] {\n const reasons: string[] = [];\n\n if (wasmResult.verification_method) {\n reasons.push(`method:${wasmResult.verification_method}`);\n }\n\n if (wasmResult.agent) {\n reasons.push(`agent:${wasmResult.agent.toLowerCase()}`);\n }\n\n return reasons;\n }\n\n /**\n * Create default result (assumed human)\n */\n private createDefaultResult(): IDetectionResult {\n return {\n isAgent: false,\n confidence: 0,\n detectionClass: { type: 'Human' },\n verificationMethod: 'none',\n forgeabilityRisk: 'high',\n reasons: ['detection_failed'],\n timestamp: new Date(),\n };\n }\n}\n","/**\n * Dynamic WASM Loader for Node.js\n *\n * This loader dynamically loads and compiles WASM at runtime,\n * which is supported in Node.js but NOT in Edge Runtime.\n *\n * Usage:\n * ```typescript\n * import { DynamicWasmLoader, WasmDetector } from '@kya-os/checkpoint-wasm-runtime/node';\n *\n * const loader = new DynamicWasmLoader();\n * const detector = new WasmDetector(loader);\n * ```\n */\n\nimport type {\n IWasmLoader,\n IWasmBindings,\n IWasmRequestMetadata,\n IWasmDetectionResult,\n} from '../types';\n\n/**\n * Try to import the WASM module from various locations\n */\nasync function findWasmModule(): Promise<ArrayBuffer> {\n const wasmPaths = [\n // Relative to this package\n '../wasm/agentshield_wasm_bg.wasm',\n './wasm/agentshield_wasm_bg.wasm',\n // From agentshield-core package\n '@kya-os/checkpoint/wasm/agentshield_wasm_bg.wasm',\n // From monorepo build output\n '../../rust/target/wasm32-unknown-unknown/release/agentshield_wasm_bg.wasm',\n ];\n\n // Try dynamic imports first (works with bundlers)\n for (const path of wasmPaths) {\n try {\n // Try webpack/bundler style import\n const module = await import(/* webpackIgnore: true */ path);\n if (module.default && module.default instanceof ArrayBuffer) {\n return module.default;\n }\n } catch {\n // Continue to next path\n }\n }\n\n // Try Node.js fs for file system loading\n try {\n const fs = await import('node:fs/promises');\n const nodePath = await import('node:path');\n\n // Get current module's directory - handle both ESM and CJS\n let moduleDir: string | null = null;\n\n // Try ESM approach first (import.meta.url)\n try {\n // Use eval to prevent bundlers from statically analyzing import.meta\n // which would cause CJS builds to fail at parse time\n const importMetaUrl = eval('typeof import.meta !== \"undefined\" && import.meta.url');\n if (importMetaUrl) {\n const url = await import('node:url');\n moduleDir = nodePath.dirname(url.fileURLToPath(importMetaUrl));\n }\n } catch {\n // ESM not available, try CJS\n }\n\n // Try CJS approach (__dirname)\n if (!moduleDir) {\n try {\n // __dirname is available in CJS but not ESM\n // Use eval to prevent ESM bundlers from complaining\n const cjsDirname = eval('typeof __dirname !== \"undefined\" && __dirname');\n if (cjsDirname) {\n moduleDir = cjsDirname;\n }\n } catch {\n // CJS __dirname not available\n }\n }\n\n // Build paths to try - start with process.cwd() based paths that work in both\n const fsWasmPaths = [\n nodePath.resolve(\n process.cwd(),\n 'node_modules/@kya-os/checkpoint-wasm-runtime/wasm/agentshield_wasm_bg.wasm'\n ),\n nodePath.resolve(\n process.cwd(),\n 'node_modules/@kya-os/checkpoint/dist/wasm/agentshield_wasm_bg.wasm'\n ),\n ];\n\n // Add module-relative paths if we found the module directory\n if (moduleDir) {\n fsWasmPaths.unshift(\n nodePath.resolve(moduleDir, '../wasm/agentshield_wasm_bg.wasm'),\n nodePath.resolve(moduleDir, '../../wasm/agentshield_wasm_bg.wasm')\n );\n }\n\n for (const wasmPath of fsWasmPaths) {\n try {\n const buffer = await fs.readFile(wasmPath);\n // Create a new ArrayBuffer to avoid SharedArrayBuffer issues\n const arrayBuffer = new ArrayBuffer(buffer.byteLength);\n new Uint8Array(arrayBuffer).set(buffer);\n return arrayBuffer;\n } catch {\n // Continue to next path\n }\n }\n } catch {\n // fs not available (browser/edge)\n }\n\n throw new Error(\n 'Could not find WASM module. Ensure @kya-os/checkpoint-wasm-runtime/wasm is installed.'\n );\n}\n\n/**\n * JsRequestMetadata constructor class\n * Matches the WASM JsRequestMetadata struct\n */\nclass JsRequestMetadata implements IWasmRequestMetadata {\n constructor(\n public user_agent: string | null,\n public ip_address: string | null,\n public headers: string,\n public timestamp: string,\n public url: string | null,\n public method: string | null,\n public client_fingerprint: string | null\n ) {}\n\n free(): void {\n // No-op for JavaScript implementation\n }\n}\n\n/**\n * Dynamic WASM Loader\n *\n * For Node.js environments that support dynamic WASM compilation.\n * Automatically finds and loads the WASM module.\n */\nexport class DynamicWasmLoader implements IWasmLoader {\n private bindings: IWasmBindings | null = null;\n private instance: WebAssembly.Instance | null = null;\n private loadPromise: Promise<void> | null = null;\n\n /**\n * Create a new DynamicWasmLoader\n * @param wasmPath - Optional custom path to WASM file\n */\n constructor(private readonly wasmPath?: string) {}\n\n /**\n * Load and compile the WASM module\n */\n async load(): Promise<void> {\n if (this.bindings) {\n return; // Already loaded\n }\n\n // Prevent concurrent loading\n if (this.loadPromise) {\n return this.loadPromise;\n }\n\n this.loadPromise = this.doLoad();\n return this.loadPromise;\n }\n\n private async doLoad(): Promise<void> {\n try {\n let wasmBuffer: ArrayBuffer;\n\n if (this.wasmPath) {\n // Load from custom path\n const fs = await import('node:fs/promises');\n const buffer = await fs.readFile(this.wasmPath);\n // Create a new ArrayBuffer to avoid SharedArrayBuffer issues\n wasmBuffer = new ArrayBuffer(buffer.byteLength);\n new Uint8Array(wasmBuffer).set(buffer);\n } else {\n // Auto-find WASM module\n wasmBuffer = await findWasmModule();\n }\n\n // Compile and instantiate\n const compiled = await WebAssembly.compile(wasmBuffer);\n const imports: WebAssembly.Imports = {\n wbg: this.createWasmBindgenImports() as WebAssembly.ModuleImports,\n };\n this.instance = await WebAssembly.instantiate(compiled, imports);\n\n // Create bindings wrapper\n const exports = this.instance.exports as Record<string, unknown>;\n this.bindings = this.createBindings(exports);\n } catch (error) {\n this.loadPromise = null;\n throw new Error(\n `Failed to load WASM module: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Get the WASM bindings after loading\n */\n getBindings(): IWasmBindings {\n if (!this.bindings) {\n throw new Error('WASM not loaded. Call load() first.');\n }\n return this.bindings;\n }\n\n /**\n * Check if WASM is loaded\n */\n isLoaded(): boolean {\n return this.bindings !== null;\n }\n\n /**\n * Get the loading strategy name\n */\n getStrategy(): string {\n return 'dynamic-compile';\n }\n\n /**\n * Create wasm-bindgen required imports\n */\n private createWasmBindgenImports(): Record<string, unknown> {\n return {\n __wbg_log_f740dc2253ea759b: (ptr: number, len: number) => {\n console.log('[WASM]', ptr, len);\n },\n __wbg_error_f851667af71bcfc6: (ptr: number, len: number) => {\n console.error('[WASM Error]', ptr, len);\n },\n __wbg_now_c644db5194be8437: () => Date.now(),\n __wbindgen_throw: (ptr: number, len: number) => {\n throw new Error(`WASM threw: ${ptr}, ${len}`);\n },\n __wbindgen_object_drop_ref: () => {},\n };\n }\n\n /**\n * Create bindings wrapper from WASM exports\n */\n private createBindings(exports: Record<string, unknown>): IWasmBindings {\n const detectAgent = exports['detect_agent'] as\n | ((metadata: IWasmRequestMetadata) => IWasmDetectionResult)\n | undefined;\n const getVersion = exports['get_version'] as (() => string) | undefined;\n const getBuildInfo = exports['get_build_info'] as (() => string) | undefined;\n\n if (!detectAgent) {\n throw new Error('WASM module missing detect_agent export');\n }\n\n return {\n detect_agent: (metadata: IWasmRequestMetadata): IWasmDetectionResult => {\n const wasmMetadata = new JsRequestMetadata(\n metadata.user_agent,\n metadata.ip_address,\n metadata.headers,\n metadata.timestamp,\n metadata.url,\n metadata.method,\n metadata.client_fingerprint\n );\n\n try {\n return detectAgent(wasmMetadata);\n } finally {\n wasmMetadata.free();\n }\n },\n get_version: () => {\n if (getVersion) {\n return getVersion();\n }\n return '0.1.0-dynamic';\n },\n get_build_info: () => {\n if (getBuildInfo) {\n return getBuildInfo();\n }\n return JSON.stringify({ version: '0.1.0', strategy: 'dynamic-compile' });\n },\n };\n }\n}\n\n/**\n * Create a dynamic loader\n */\nexport function createDynamicLoader(wasmPath?: string): DynamicWasmLoader {\n return new DynamicWasmLoader(wasmPath);\n}\n","/**\n * Policy Loader\n *\n * Loads customer policies from the AgentShield API.\n * Supports LRU caching with background refresh.\n */\n\nimport type { IPolicyLoader, ICustomerPolicy } from '../types';\n\n/**\n * Cached policy entry\n */\ninterface CachedPolicy {\n policy: ICustomerPolicy;\n loadedAt: number;\n refreshing: boolean;\n}\n\n/**\n * Policy loader configuration\n */\nexport interface PolicyLoaderConfig {\n /** Base URL for the policy API */\n apiUrl?: string;\n /** Cache TTL in milliseconds (default: 5 minutes) */\n cacheTTL?: number;\n /** Maximum number of policies to cache (default: 100) */\n maxCacheSize?: number;\n /** Enable background refresh (default: true) */\n backgroundRefresh?: boolean;\n /** Timeout for API requests in milliseconds (default: 5000) */\n timeout?: number;\n}\n\nconst DEFAULT_CONFIG: Required<PolicyLoaderConfig> = {\n apiUrl: 'https://api.agentshield.io',\n cacheTTL: 5 * 60 * 1000, // 5 minutes\n maxCacheSize: 100,\n backgroundRefresh: true,\n timeout: 5000,\n};\n\n/**\n * Policy Loader\n *\n * Loads and caches customer policies from the AgentShield API.\n * Follows Single Responsibility Principle: only handles policy loading.\n */\nexport class PolicyLoader implements IPolicyLoader {\n private cache = new Map<string, CachedPolicy>();\n private config: Required<PolicyLoaderConfig>;\n\n constructor(config: PolicyLoaderConfig = {}) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Load policy for an API key\n */\n async loadPolicy(apiKey: string): Promise<ICustomerPolicy> {\n // Check cache first\n const cached = this.getCachedPolicy(apiKey);\n if (cached) {\n // Trigger background refresh if nearing expiry\n if (this.config.backgroundRefresh && this.shouldRefresh(apiKey)) {\n this.refreshInBackground(apiKey);\n }\n return cached;\n }\n\n // Fetch from API\n return this.fetchPolicy(apiKey);\n }\n\n /**\n * Get cached policy if available and not expired\n */\n getCachedPolicy(apiKey: string): ICustomerPolicy | null {\n const entry = this.cache.get(apiKey);\n if (!entry) {\n return null;\n }\n\n // Check if expired\n if (this.isExpired(entry)) {\n this.cache.delete(apiKey);\n return null;\n }\n\n return entry.policy;\n }\n\n /**\n * Invalidate cached policy\n */\n invalidateCache(apiKey: string): void {\n this.cache.delete(apiKey);\n }\n\n /**\n * Fetch policy from API and cache it\n */\n private async fetchPolicy(apiKey: string): Promise<ICustomerPolicy> {\n const policy = await this.fetchPolicyFromApi(apiKey);\n this.cachePolicy(apiKey, policy);\n return policy;\n }\n\n /**\n * Fetch policy from API without caching\n * Used internally for both direct fetches and background refreshes\n */\n private async fetchPolicyFromApi(apiKey: string): Promise<ICustomerPolicy> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n try {\n const response = await fetch(`${this.config.apiUrl}/api/v1/policy`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'User-Agent': 'agentshield-wasm-runtime/0.1.0',\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n if (response.status === 401) {\n throw new PolicyLoadError('Invalid API key', 'INVALID_API_KEY');\n }\n if (response.status === 404) {\n // Return default policy if not found\n return this.getDefaultPolicy(apiKey);\n }\n throw new PolicyLoadError(`Failed to load policy: ${response.status}`, 'API_ERROR');\n }\n\n return (await response.json()) as ICustomerPolicy;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof PolicyLoadError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === 'AbortError') {\n throw new PolicyLoadError('Policy request timeout', 'TIMEOUT');\n }\n\n throw new PolicyLoadError(\n `Failed to load policy: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'NETWORK_ERROR'\n );\n }\n }\n\n /**\n * Cache a policy\n */\n private cachePolicy(apiKey: string, policy: ICustomerPolicy): void {\n // Enforce cache size limit (simple LRU: delete oldest)\n if (this.cache.size >= this.config.maxCacheSize) {\n const oldestKey = this.cache.keys().next().value;\n if (oldestKey) {\n this.cache.delete(oldestKey);\n }\n }\n\n this.cache.set(apiKey, {\n policy,\n loadedAt: Date.now(),\n refreshing: false,\n });\n }\n\n /**\n * Check if cached entry is expired\n */\n private isExpired(entry: CachedPolicy): boolean {\n return Date.now() - entry.loadedAt > this.config.cacheTTL;\n }\n\n /**\n * Check if cache entry should be refreshed\n */\n private shouldRefresh(apiKey: string): boolean {\n const entry = this.cache.get(apiKey);\n if (!entry) {\n return false;\n }\n\n // Refresh when 80% of TTL has passed\n const refreshThreshold = this.config.cacheTTL * 0.8;\n return Date.now() - entry.loadedAt > refreshThreshold && !entry.refreshing;\n }\n\n /**\n * Refresh policy in background\n */\n private async refreshInBackground(apiKey: string): Promise<void> {\n const entry = this.cache.get(apiKey);\n if (!entry || entry.refreshing) {\n return;\n }\n\n // Mark as refreshing\n entry.refreshing = true;\n\n try {\n // Use fetch-only method to avoid double caching\n const policy = await this.fetchPolicyFromApi(apiKey);\n this.cachePolicy(apiKey, policy);\n } catch {\n // Ignore errors in background refresh, keep serving stale cache\n } finally {\n // Reset refreshing flag on the current entry\n // (cachePolicy creates a new entry with refreshing: false, so this is\n // only needed if the fetch failed and we're still serving the old entry)\n const currentEntry = this.cache.get(apiKey);\n if (currentEntry && currentEntry.refreshing) {\n currentEntry.refreshing = false;\n }\n }\n }\n\n /**\n * Get default policy for a project\n */\n private getDefaultPolicy(apiKey: string): ICustomerPolicy {\n return {\n projectId: apiKey.split('_')[1] || 'unknown',\n blockThreshold: 90,\n };\n }\n}\n\n/**\n * Policy load error\n */\nexport class PolicyLoadError extends Error {\n constructor(\n message: string,\n public readonly code: 'INVALID_API_KEY' | 'API_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT'\n ) {\n super(message);\n this.name = 'PolicyLoadError';\n }\n}\n\n/**\n * Create a policy loader with default configuration\n */\nexport function createPolicyLoader(config?: PolicyLoaderConfig): PolicyLoader {\n return new PolicyLoader(config);\n}\n","/**\n * Rules-Based Fallback Detector\n *\n * JavaScript fallback detector that uses merged-rules.json when WASM is unavailable.\n * This provides consistent detection using the same rules as WASM, just implemented in JS.\n */\n\nimport type {\n IDetector,\n IDetectionInput,\n IDetectionResult,\n DetectionClass,\n VerificationMethod,\n} from '../types';\nimport { CONFIDENCE } from '../types';\nimport { loadRulesSync, type DetectionRules } from '@kya-os/checkpoint-shared';\n\n/**\n * Rules-Based Fallback Detector\n *\n * Uses the same merged-rules.json as the WASM engine to provide\n * consistent detection when WASM is not available.\n */\nexport class RulesDetector implements IDetector {\n private rules: DetectionRules | null = null;\n private ready = false;\n\n /**\n * Analyze a request and detect if it's from an agent\n */\n async detect(input: IDetectionInput): Promise<IDetectionResult> {\n await this.ensureReady();\n\n const reasons: string[] = [];\n let confidence = 0;\n let detectedAgentName: string | null = null;\n let verificationMethod: VerificationMethod = 'none';\n\n const userAgent = input.userAgent || input.headers['user-agent'] || '';\n const normalizedHeaders = this.normalizeHeaders(input.headers);\n\n // Check User-Agent patterns\n if (userAgent && this.rules) {\n const uaMatch = this.matchUserAgent(userAgent);\n if (uaMatch) {\n confidence = Math.max(confidence, uaMatch.confidence);\n detectedAgentName = uaMatch.agentName;\n verificationMethod = 'pattern';\n reasons.push(`pattern:${uaMatch.agentKey}`);\n }\n }\n\n // Check suspicious headers\n if (this.rules) {\n const headerMatch = this.matchHeaders(normalizedHeaders);\n if (headerMatch.confidence > 0) {\n confidence = Math.max(confidence, headerMatch.confidence);\n reasons.push(`headers:${headerMatch.count}`);\n }\n }\n\n // Check for signature headers (indicates AI agent)\n if (this.hasSignatureHeaders(normalizedHeaders)) {\n confidence = Math.max(confidence, CONFIDENCE.SIGNATURE_PRESENT);\n reasons.push('signature_headers_present');\n verificationMethod = 'pattern'; // Can't verify signature in JS fallback\n }\n\n // Determine detection class\n const isAgent = confidence > CONFIDENCE.THRESHOLD_AGENT;\n const detectionClass = this.determineDetectionClass(isAgent, detectedAgentName, confidence);\n\n return {\n isAgent,\n confidence,\n detectionClass,\n detectedAgent: detectedAgentName\n ? {\n type: this.inferAgentType(detectedAgentName),\n name: detectedAgentName,\n }\n : undefined,\n verificationMethod,\n forgeabilityRisk: 'high', // JS fallback is always high risk\n reasons,\n timestamp: new Date(),\n };\n }\n\n /**\n * Check if the detector is ready\n */\n isReady(): boolean {\n return this.ready;\n }\n\n /**\n * Ensure the detector is initialized\n */\n async ensureReady(): Promise<void> {\n if (this.ready) {\n return;\n }\n\n try {\n this.rules = loadRulesSync();\n this.ready = true;\n } catch (error) {\n console.warn('[RulesDetector] Failed to load rules:', error);\n // Continue without rules - will return default results\n this.ready = true;\n }\n }\n\n /**\n * Get detector version\n */\n async getVersion(): Promise<string> {\n return '0.1.0-js-fallback';\n }\n\n /**\n * Normalize headers to lowercase keys\n */\n private normalizeHeaders(headers: Record<string, string>): Record<string, string> {\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n normalized[key.toLowerCase()] = value;\n }\n return normalized;\n }\n\n /**\n * Match user agent against rules\n */\n private matchUserAgent(\n userAgent: string\n ): { confidence: number; agentName: string; agentKey: string } | null {\n if (!this.rules) {\n return null;\n }\n\n const userAgents = this.rules.rules.userAgents;\n\n // Sort to check specific patterns first (generic_bot, dev_tools, automation_tools last)\n const genericKeys = ['generic_bot', 'dev_tools', 'automation_tools'];\n const entries = Object.entries(userAgents).sort((a, b) => {\n const aIsGeneric = genericKeys.includes(a[0]);\n const bIsGeneric = genericKeys.includes(b[0]);\n if (aIsGeneric && !bIsGeneric) return 1;\n if (!aIsGeneric && bIsGeneric) return -1;\n return 0;\n });\n\n for (const [agentKey, rule] of entries) {\n for (const pattern of rule.patterns) {\n try {\n const regex = new RegExp(pattern, 'i');\n if (regex.test(userAgent)) {\n return {\n // Convert 0-1 rule confidence to 0-100 scale\n confidence: rule.confidence * 100,\n agentName: this.getAgentName(agentKey),\n agentKey,\n };\n }\n } catch {\n // Invalid regex, skip\n }\n }\n }\n\n return null;\n }\n\n /**\n * Match headers against suspicious header rules\n */\n private matchHeaders(headers: Record<string, string>): { confidence: number; count: number } {\n if (!this.rules) {\n return { confidence: 0, count: 0 };\n }\n\n const suspicious = this.rules.rules.headers.suspicious || [];\n let maxConfidence = 0;\n let count = 0;\n\n for (const headerRule of suspicious) {\n if (headers[headerRule.name.toLowerCase()]) {\n // Convert 0-1 rule confidence to 0-100 scale\n maxConfidence = Math.max(maxConfidence, headerRule.confidence * 100);\n count++;\n }\n }\n\n return { confidence: maxConfidence, count };\n }\n\n /**\n * Check if signature headers are present\n */\n private hasSignatureHeaders(headers: Record<string, string>): boolean {\n return !!(headers['signature'] || headers['signature-input'] || headers['signature-agent']);\n }\n\n /**\n * Get human-readable agent name from rule key\n */\n private getAgentName(agentKey: string): string {\n const nameMap: Record<string, string> = {\n openai_gptbot: 'ChatGPT/GPTBot',\n anthropic_claude: 'Claude',\n perplexity_bot: 'Perplexity',\n google_ai: 'Google AI',\n microsoft_ai: 'Microsoft Copilot',\n meta_ai: 'Meta AI',\n cohere_bot: 'Cohere',\n huggingface_bot: 'HuggingFace',\n generic_bot: 'Generic Bot',\n dev_tools: 'Development Tool',\n automation_tools: 'Automation Tool',\n };\n return nameMap[agentKey] || agentKey;\n }\n\n /**\n * Infer agent type from name\n */\n private inferAgentType(agentName: string): string {\n const lowerName = agentName.toLowerCase();\n\n if (lowerName.includes('chatgpt') || lowerName.includes('gpt')) return 'openai';\n if (lowerName.includes('claude')) return 'anthropic';\n if (lowerName.includes('perplexity')) return 'perplexity';\n if (lowerName.includes('google')) return 'google';\n if (lowerName.includes('copilot') || lowerName.includes('bing')) return 'microsoft';\n\n return 'unknown';\n }\n\n /**\n * Determine detection class\n */\n private determineDetectionClass(\n isAgent: boolean,\n agentName: string | null,\n confidence: number\n ): DetectionClass {\n if (!isAgent || confidence < CONFIDENCE.THRESHOLD_AGENT) {\n return { type: 'Human' };\n }\n\n if (agentName) {\n const lowerName = agentName.toLowerCase();\n\n // AI agents\n const aiPatterns = ['chatgpt', 'gpt', 'claude', 'perplexity', 'gemini', 'copilot'];\n if (aiPatterns.some((p) => lowerName.includes(p))) {\n return { type: 'AiAgent', agentType: agentName };\n }\n\n // Bots\n if (lowerName.includes('bot') || lowerName.includes('crawler')) {\n return { type: 'Bot', botType: agentName };\n }\n\n // Automation\n if (lowerName.includes('automation') || lowerName.includes('tool')) {\n return { type: 'Automation', toolType: agentName };\n }\n\n return { type: 'AiAgent', agentType: agentName };\n }\n\n return { type: 'Unknown' };\n }\n}\n\n/**\n * Create a rules-based fallback detector\n */\nexport function createRulesDetector(): RulesDetector {\n return new RulesDetector();\n}\n","/**\n * AgentShield WASM Runtime - Node.js Entry\n *\n * Optimized exports for Node.js environments.\n * Uses dynamic WASM loading for Node.js compatibility.\n *\n * @example\n * ```typescript\n * import { createNodeDetector } from '@kya-os/checkpoint-wasm-runtime/node';\n *\n * const detector = createNodeDetector({\n * apiKey: process.env.AGENTSHIELD_API_KEY,\n * });\n *\n * // In Express middleware:\n * app.use(async (req, res, next) => {\n * const result = await detector.detect({\n * userAgent: req.get('User-Agent'),\n * headers: req.headers as Record<string, string>,\n * ipAddress: req.ip,\n * });\n *\n * if (result.shouldBlock) {\n * return res.status(403).send('Forbidden');\n * }\n *\n * req.agentShield = result;\n * next();\n * });\n * ```\n */\n\n// Export types\nexport type {\n IDetectionInput,\n IDetectionResult,\n IDetector,\n IWasmLoader,\n IPolicyLoader,\n ICustomerPolicy,\n IDetectedAgent,\n IDetectorOptions,\n DetectionClass,\n VerificationMethod,\n ForgeabilityRisk,\n} from './types';\n\nexport { CONFIDENCE } from './types';\n\n// Import classes for use in this module\nimport { WasmDetector } from './wasm-detector';\nimport { DynamicWasmLoader, createDynamicLoader } from './loaders/dynamic-loader';\nimport { PolicyLoader, createPolicyLoader } from './policy/policy-loader';\nimport { RulesDetector, createRulesDetector } from './fallback/rules-detector';\n\n// Re-export for consumers\nexport { WasmDetector };\nexport { DynamicWasmLoader, createDynamicLoader };\nexport { PolicyLoader, createPolicyLoader };\nexport { RulesDetector, createRulesDetector };\n\n/**\n * Create a detector for Node.js with dynamic WASM loading\n *\n * @param options - Detector configuration\n */\nexport function createNodeDetector(\n options: import('./types').IDetectorOptions = {}\n): import('./types').IDetector {\n const loader = new DynamicWasmLoader();\n\n let policyLoader: import('./types').IPolicyLoader | undefined;\n if (options.apiKey) {\n policyLoader = new PolicyLoader({\n apiUrl: options.policyApiUrl,\n cacheTTL: options.policyTTL,\n });\n }\n\n return new WasmDetector(loader, policyLoader, options);\n}\n\n/**\n * Create a fallback detector using JavaScript rules\n * Use this when WASM loading fails\n */\nexport function createFallbackDetector(): import('./types').IDetector {\n return new RulesDetector();\n}\n\n/**\n * Extract detection input from an Express-like request object\n */\nexport function extractInputFromExpressRequest(req: {\n headers: Record<string, string | string[] | undefined>;\n ip?: string;\n url?: string;\n method?: string;\n}): import('./types').IDetectionInput {\n // Normalize headers (Express headers can be string or string[])\n const headers: Record<string, string> = {};\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n headers[key] = Array.isArray(value) ? value[0] : value;\n }\n }\n\n return {\n userAgent: headers['user-agent'],\n ipAddress: req.ip || headers['x-forwarded-for']?.split(',')[0]?.trim() || headers['x-real-ip'],\n headers,\n url: req.url,\n method: req.method,\n };\n}\n"]}
@@ -0,0 +1,243 @@
1
+ export { initEngineEdge } from './engine-edge.mjs';
2
+ import { E as EnforcementMode, A as AgentRequest, V as VerifyResult } from './types-D0j85fF0.mjs';
3
+ import { DidResolverAdapter, StatusListCacheAdapter, ReputationOracleAdapter, PolicyEvaluatorAdapter, ClockAdapter } from './adapters.mjs';
4
+ import '@kya-os/checkpoint-shared';
5
+
6
+ /**
7
+ * Orchestrator-layer types — Phase C, host-side only.
8
+ *
9
+ * Nothing here crosses the WASM boundary. The engine ABI types live
10
+ * in `../types.ts`; the adapter interfaces live in
11
+ * `../adapters/index.ts`. This file is the host-wrapper-facing
12
+ * surface — what Phase D (Next.js) and Phase E (Express) import.
13
+ */
14
+
15
+ /**
16
+ * Framework-agnostic HTTP request shape.
17
+ *
18
+ * Next.js / Express / Cloudflare Workers / Hono adapters marshal
19
+ * their native request type into this shape before calling
20
+ * `verifyRequest`. The shape is intentionally minimal — only what
21
+ * the engine needs to make a verdict.
22
+ */
23
+ interface IncomingHttpLike {
24
+ method: string;
25
+ /** Path + query string (no scheme + host). */
26
+ url: string;
27
+ headers: Record<string, string | string[] | undefined>;
28
+ /**
29
+ * Parsed body if the framework has already parsed it (Next.js
30
+ * with `await req.json()`, Express with `body-parser`). Falsy if
31
+ * the caller hasn't materialised the body — the orchestrator
32
+ * treats that as "no MCP-I envelope present" and routes to
33
+ * PlainHttp.
34
+ */
35
+ body?: Buffer | string | object | null;
36
+ /** Client IP if the framework surfaces one (Express `req.ip`). */
37
+ remoteAddress?: string;
38
+ }
39
+ /**
40
+ * Options the host wrapper passes per-`verifyRequest`-construction.
41
+ * The five adapters + clock + tenant identifier + enforcement mode.
42
+ */
43
+ interface VerifyRequestOpts {
44
+ didResolver: DidResolverAdapter;
45
+ statusListCache: StatusListCacheAdapter;
46
+ reputationOracle: ReputationOracleAdapter;
47
+ policyEvaluator: PolicyEvaluatorAdapter;
48
+ clock: ClockAdapter;
49
+ /** Tenant identifier — the host customer this request targets. */
50
+ tenantHost: string;
51
+ enforcementMode: EnforcementMode;
52
+ /** Returned to the PolicyEvaluator when the request has no agent DID. Default 1.0. */
53
+ reputationBaseline?: number;
54
+ /**
55
+ * **Envelope-1 (#2537) coordination flag.** Pre-Envelope-1 the TS
56
+ * bouncer ships MCP-I proofs as `{protected,payload,signature}` JSON
57
+ * in a `KYA-Delegation` header. Post-Envelope-1 they ship compact
58
+ * JWS in `_meta.proof.jws` of the body. When this flag is true the
59
+ * orchestrator also accepts the legacy header form. **Default off.**
60
+ * Delete this flag once Envelope-1 ships end-to-end.
61
+ */
62
+ legacyEnvelopeFallback?: boolean;
63
+ /**
64
+ * Argus URL — passed only so the orchestrator can detect "Argus
65
+ * not configured" at construction time and log the one-shot
66
+ * warning. The actual reputation fetch goes through `reputationOracle`.
67
+ */
68
+ argusUrl?: string;
69
+ /** Injectable for the once-only Argus configuration warning. */
70
+ logger?: (msg: string) => void;
71
+ }
72
+ /**
73
+ * Transport-agnostic response shape `renderDecisionAsResponse`
74
+ * produces. Host wrappers adapt this to their framework's response
75
+ * type (NextResponse / Express `res` / Cloudflare Response).
76
+ *
77
+ * `status === null` means "pass through" — the request continues to
78
+ * the next handler. Happens in two cases:
79
+ * 1. `Decision::Permit` (no block in Enforce mode).
80
+ * 2. **Any verdict in Observe mode** — Observe never blocks, but
81
+ * the response headers still carry the would-have-been verdict.
82
+ */
83
+ interface RenderedResponse {
84
+ status: number | null;
85
+ headers: Record<string, string>;
86
+ body?: string | object;
87
+ }
88
+
89
+ /**
90
+ * HTTP-to-`AgentRequest` translator — Phase C.1.
91
+ *
92
+ * Detects which engine protocol the request belongs to and builds
93
+ * the typed `AgentRequest` the WASM consumes. Conservative
94
+ * detection: never escalates an ambiguous request into a higher
95
+ * verification tier. Anonymous PlainHttp is the default.
96
+ *
97
+ * **What this layer parses and what it doesn't.** It parses *only
98
+ * what's needed to drive conditional pre-fetch* — header presence,
99
+ * the MCP-I envelope's payload segment (to extract `iss` + `sub` +
100
+ * optional credentialStatus URL). It does **not** verify
101
+ * signatures, decode VC chains for revocation bits, or evaluate
102
+ * scope. Those live in the engine (H-1's parser + Stages 2-5).
103
+ *
104
+ * **Buffer-portability note.** This module uses `Buffer.from(...)` and
105
+ * `Buffer.isBuffer(...)` at multiple call sites (the JWS preflight
106
+ * `hasMalformedJwsBody`, both `tryBuildMcpIFromBody` variants, the
107
+ * legacy-header reconstitution path, and `bodyAsBytes`). All of these
108
+ * assume the Node `Buffer` global is available — provided natively by
109
+ * the Node runtime, polyfilled on Vercel Edge, and gated behind
110
+ * `nodejs_compat` on Cloudflare Workers. Bare-Edge and pure-browser
111
+ * embedders would need a `Buffer` polyfill or a refactor to
112
+ * `TextEncoder` / `Uint8Array.from`. Tracked as a follow-up since
113
+ * Phase D's Vercel Node + Vercel Edge targets are both covered today.
114
+ */
115
+
116
+ interface BuildAgentRequestOpts {
117
+ /** See `VerifyRequestOpts.legacyEnvelopeFallback`. */
118
+ legacyEnvelopeFallback?: boolean;
119
+ }
120
+ /**
121
+ * Translate an HTTP-like request into the engine's `AgentRequest`.
122
+ *
123
+ * Detection order (conservative — never escalate ambiguous input):
124
+ * 1. MCP-I L2 detached proof in `_meta.proof.jws` (spec form).
125
+ * 2. (Legacy, opt-in) MCP-I in `KYA-Delegation` header
126
+ * (Envelope-1 #2537 transition window only).
127
+ * 3. RFC 9421 HTTP Message Signatures (`Signature-Input` header).
128
+ * 4. PlainHttp (default — anonymous traffic).
129
+ */
130
+ declare function buildAgentRequest(req: IncomingHttpLike, opts?: BuildAgentRequestOpts): AgentRequest;
131
+ /**
132
+ * Preflight check — does the request body carry a `_meta.proof.jws`
133
+ * string that `parseJwsPayloadStruct` cannot project into a typed
134
+ * `McpIPayload`?
135
+ *
136
+ * The caller declared intent (an MCP-I envelope) by including the
137
+ * JWS field; structural failure to extract the payload means the
138
+ * envelope is malformed, not absent. Without this preflight, the
139
+ * orchestrator would silently fall through to PlainHttp — pre-#2560
140
+ * that happened to also Block (engine returned `Block(ParseError)`
141
+ * for every PlainHttp), so the regression was invisible; post-#2560
142
+ * the engine's Stage 1 + stub policy returns `Permit` for anonymous
143
+ * PlainHttp and tampered envelopes would be silently accepted.
144
+ *
145
+ * Returns `true` when the orchestrator should synthesize
146
+ * `Block(ParseError)` BEFORE calling `buildAgentRequest`.
147
+ */
148
+ declare function hasMalformedJwsBody(req: IncomingHttpLike): boolean;
149
+ /**
150
+ * Issuer DID — Stage 1 (identity resolution) targets this. `null`
151
+ * for PlainHttp (anonymous → no DID to resolve).
152
+ */
153
+ declare function extractIssuer(request: AgentRequest): string | null;
154
+ /**
155
+ * Agent DID — used by ReputationOracle. Defaults to `payload.sub`
156
+ * for MCP-I (subject = the agent the proof is *about*).
157
+ */
158
+ declare function extractAgentDid(request: AgentRequest): string | null;
159
+ /**
160
+ * Status-list URL for revocation pre-fetch. Pulled from the JWS
161
+ * payload's `vc.credentialStatus.id` (W3C VC Data Model 1.1).
162
+ * `null` when the envelope is L1 (no VC chain) — Stage 3 will skip.
163
+ */
164
+ declare function extractCredentialStatusUrl(request: AgentRequest): string | null;
165
+
166
+ /**
167
+ * Transport-agnostic `Decision` → HTTP renderer — Phase C.3.
168
+ *
169
+ * Translates a `VerifyResult` into a framework-neutral
170
+ * `{ status, headers, body }` shape. Phase D (Next.js) adapts this
171
+ * to `NextResponse`; Phase E (Express) adapts it to `res.status().set().send()`.
172
+ * One source of truth for the verdict→HTTP mapping.
173
+ *
174
+ * Mapping table (§ 4.5 of Phase C kickoff):
175
+ *
176
+ * | Decision | HTTP | Notes |
177
+ * |-----------------------------------|------|-----------------------------------------|
178
+ * | Permit | null | Pass through to next handler |
179
+ * | Block(Unauthenticated) | 401 | WWW-Authenticate header |
180
+ * | Block(InvalidSignature) | 403 | |
181
+ * | Block(Revoked) | 403 | |
182
+ * | Block(Expired) | 401 | Refresh-the-credential semantics |
183
+ * | Block(OutOfScope) | 403 | Body carries requested + granted |
184
+ * | Block(LowReputation) | 403 | Body carries score + threshold |
185
+ * | Block(PolicyDenied) | 403 | Body carries detail |
186
+ * | Block(ParseError) | 400 | Body carries detail |
187
+ * | Challenge | 401 | Body carries ChallengeParams |
188
+ * | Redirect | 302 | Location header |
189
+ * | Instruct | 422 | application/problem+json body |
190
+ *
191
+ * Observe mode overrides: every verdict renders as `status: null`
192
+ * (pass through) with an `X-Checkpoint-Would-Have-Been` header
193
+ * carrying the verdict kind, plus the standard attribution headers.
194
+ *
195
+ * Every response carries the Phase 0.1 attribution headers:
196
+ * `X-Checkpoint-Engine`, `X-Checkpoint-Engine-Version`, and
197
+ * (when present) `X-Checkpoint-Ruleset-Hash`.
198
+ */
199
+
200
+ declare function renderDecisionAsResponse(result: VerifyResult): RenderedResponse;
201
+
202
+ /**
203
+ * `verifyRequestEdge` async-init orchestrator — Edge-WASM-2 (folded into
204
+ * Phase D's PR).
205
+ *
206
+ * Mirror of [[./verify-request.ts]] for edge runtimes. Differs in only
207
+ * three places:
208
+ *
209
+ * 1. Imports `engineVerifyEdge` + `initEngineEdge` from `../edge`
210
+ * instead of `engineVerify` from `../index` (Node target).
211
+ * 2. Awaits `initEngineEdge()` before the engine call — async-init
212
+ * pattern required by the `--target web` wasm-bindgen build.
213
+ * 3. The final engine call is `await engineVerifyEdge(...)` rather
214
+ * than the synchronous `engineVerify(...)`.
215
+ *
216
+ * **The two files MUST stay in sync.** Any change to verify-request.ts
217
+ * (new adapter, new error-classification rule, new ContextSpec field)
218
+ * MUST be mirrored here. The cross-target parity test in
219
+ * [[__tests__/verify-request-parity.test.ts]] guards the verdict-shape
220
+ * invariant — both orchestrators must produce identical
221
+ * `VerifyResult.decision` / `engineInfo.name` on identical inputs.
222
+ *
223
+ * Cedar-1 forward-compat: same seam as the Node variant — step (5)
224
+ * (tenant policy eval) is the only place the PolicyEvaluator
225
+ * interface gets exercised. When Cedar-1 swaps implementations, this
226
+ * orchestrator does not change.
227
+ */
228
+
229
+ /**
230
+ * Factory — constructs a `verifyRequestEdge` closure that remembers the
231
+ * one-shot Argus-not-configured warning state. Use this when the
232
+ * host wrapper wants the startup log; call `verifyRequestEdge` directly
233
+ * (the loose function below) if you don't.
234
+ */
235
+ declare function makeVerifyRequestEdge(opts: VerifyRequestOpts): (req: IncomingHttpLike) => Promise<VerifyResult>;
236
+ /**
237
+ * Single-shot async entry. Use [`makeVerifyRequestEdge`] in long-lived
238
+ * hosts (so the Argus warning is one-shot per process); use this
239
+ * loose form in tests + one-off invocations.
240
+ */
241
+ declare function verifyRequestEdge(req: IncomingHttpLike, opts: VerifyRequestOpts): Promise<VerifyResult>;
242
+
243
+ export { type BuildAgentRequestOpts, type IncomingHttpLike, type RenderedResponse, type VerifyRequestOpts, buildAgentRequest, extractAgentDid, extractCredentialStatusUrl, extractIssuer, hasMalformedJwsBody, makeVerifyRequestEdge, renderDecisionAsResponse, verifyRequestEdge };