@nekzus/liop 2.0.0-alpha.3 → 2.0.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -7
- package/dist/bin/agent.js +3 -3
- package/dist/bin/agent.js.map +1 -1
- package/dist/bridge.js +1 -1
- package/dist/chunk-5OAZNVIU.js +31 -0
- package/dist/chunk-5OAZNVIU.js.map +1 -0
- package/dist/{chunk-LYULZHZO.js → chunk-62YQHKSS.js} +2 -2
- package/dist/{chunk-LYULZHZO.js.map → chunk-62YQHKSS.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/server.d.ts +18 -0
- package/dist/server.js +1 -1
- package/dist/workers/logic-execution.d.ts +5 -0
- package/dist/workers/logic-execution.js +1 -1
- package/dist/workers/logic-execution.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-FW6CICSY.js +0 -29
- package/dist/chunk-FW6CICSY.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bridge/stream.ts","../src/bridge/index.ts"],"names":["DEFAULT_MAX_SESSIONS_PER_IP","DEFAULT_SESSION_TIMEOUT_MS","EVICTION_INTERVAL_MS","LiopStreamBridge","internalServer","options","Hono","LiopMcpBridge","clientIp","WebStandardStreamableHTTPServerTransport","transport","randomUUID","sessionId","log","message","entry","result","err","ip","count","c","now","cors","next","auth","expectedToken","existing","response","currentSessions","port","listenPort","resolve","serve","info","id","source","payload","method","params","tools","resources","prompts","request","code","contentText","data","LiopVerifier","e","LiopServer","legacy","name","tool","t","args","uri","resource","r","rl","shutdown","line"],"mappings":"+JA6BA,IAAMA,EAA8B,EAAA,CAC9BC,CAAAA,CAA6B,IAAA,CAAU,GAAA,CACvCC,EAAuB,EAAA,CAAK,GAAA,CAgBrBC,CAAAA,CAAN,KAAuB,CAS7B,WAAA,CACCC,CAAAA,CACQC,CAAAA,CAAmC,GAC1C,CADO,IAAA,CAAA,OAAA,CAAAA,EAER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,CAAK,IAAA,GACV,GAAI,CACH,IAAMvB,CAAAA,CAAU,KAAK,KAAA,CAAMuB,CAAI,EACzBhC,CAAAA,CAAW,MAAM,KAAK,oBAAA,CAAqBS,CAAO,CAAA,CACpDT,CAAAA,EACH,QAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC;AAAA,CAAI,EAEtD,CAAA,MAASoB,CAAAA,CAAY,CACpBlC,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBkC,CAAAA,CAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CACD","file":"chunk-LYULZHZO.js","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { serve } from \"@hono/node-server\";\nimport type { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpBridge } from \"./index.js\";\n\n/**\n * Configuration options for LiopStreamBridge.\n */\nexport interface LiopStreamBridgeOptions {\n\t/** Port to listen on (default: 3000) */\n\tport?: number;\n\t/** Max concurrent sessions per IP (default: 5) */\n\tmaxSessionsPerIp?: number;\n\t/** Session idle timeout in milliseconds (default: 30 min) */\n\tsessionTimeoutMs?: number;\n}\n\n/** Internal metadata for tracked sessions */\ninterface SessionEntry {\n\ttransport: WebStandardStreamableHTTPServerTransport;\n\tlastActivity: number;\n\tclientIp: string;\n}\n\nconst DEFAULT_MAX_SESSIONS_PER_IP = 10;\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst EVICTION_INTERVAL_MS = 60 * 1000; // Check every minute\n\n/**\n * LiopStreamBridge\n *\n * Exposes a LiopServer over a remote HTTP network using the industry-standard\n * MCP Streamable HTTP Transport + Hono JS.\n *\n * Supports concurrent multi-client connections via per-session transport instances (Map pattern).\n * External agents connect using only a URL + Bearer Token (Zero-Trust).\n *\n * Security hardening:\n * - Zero-Trust Bearer Token enforcement\n * - Per-IP rate limiting on session creation\n * - Automatic eviction of idle sessions (TTL)\n */\nexport class LiopStreamBridge {\n\tprivate app: Hono;\n\tprivate httpServer: ReturnType<typeof serve> | null = null;\n\tprivate bridgeLogic: LiopMcpBridge;\n\tprivate activeSessions: Map<string, SessionEntry>;\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate maxSessionsPerIp: number;\n\tprivate sessionTimeoutMs: number;\n\n\tconstructor(\n\t\tinternalServer: LiopServer,\n\t\tprivate options: LiopStreamBridgeOptions = {},\n\t) {\n\t\tthis.app = new Hono();\n\t\tthis.bridgeLogic = new LiopMcpBridge(internalServer);\n\t\tthis.activeSessions = new Map();\n\t\tthis.maxSessionsPerIp =\n\t\t\toptions.maxSessionsPerIp ?? DEFAULT_MAX_SESSIONS_PER_IP;\n\t\tthis.sessionTimeoutMs =\n\t\t\toptions.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n\t\tthis.setupRoutes();\n\t}\n\n\t/**\n\t * Creates a new per-session transport instance and wires it to the LIOPMcpBridge logic.\n\t */\n\tprivate async createSessionTransport(\n\t\tclientIp: string,\n\t): Promise<WebStandardStreamableHTTPServerTransport> {\n\t\tconst { WebStandardStreamableHTTPServerTransport } = await import(\n\t\t\t\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\"\n\t\t);\n\t\tconst transport = new WebStandardStreamableHTTPServerTransport({\n\t\t\tsessionIdGenerator: () => randomUUID(),\n\t\t\tonsessioninitialized: (sessionId: string) => {\n\t\t\t\tthis.activeSessions.set(sessionId, {\n\t\t\t\t\ttransport,\n\t\t\t\t\tlastActivity: Date.now(),\n\t\t\t\t\tclientIp,\n\t\t\t\t});\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`,\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\t// Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router\n\t\ttransport.onmessage = async (message: JSONRPCMessage) => {\n\t\t\t// Touch activity timestamp on every message\n\t\t\tif (transport.sessionId) {\n\t\t\t\tconst entry = this.activeSessions.get(transport.sessionId);\n\t\t\t\tif (entry) entry.lastActivity = Date.now();\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.bridgeLogic.handleJsonRpcRequest(\n\t\t\t\t\tmessage as unknown as Record<string, unknown>,\n\t\t\t\t);\n\t\t\t\t// Notifications return undefined — no response needed\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tawait transport.send(result as JSONRPCMessage);\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\"[LIOP-StreamBridge] JSON-RPC error:\", (err as Error).message);\n\t\t\t}\n\t\t};\n\n\t\ttransport.onclose = () => {\n\t\t\tif (transport.sessionId) {\n\t\t\t\tthis.activeSessions.delete(transport.sessionId);\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);\n\t\t\t}\n\t\t};\n\n\t\treturn transport;\n\t}\n\n\t/**\n\t * Returns the number of active sessions for a given IP.\n\t */\n\tprivate countSessionsByIp(ip: string): number {\n\t\tlet count = 0;\n\t\tfor (const entry of this.activeSessions.values()) {\n\t\t\tif (entry.clientIp === ip) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\t/**\n\t * Extracts client IP from the request (supports X-Forwarded-For for reverse proxies).\n\t */\n\tprivate getClientIp(c: {\n\t\treq: { header: (name: string) => string | undefined };\n\t}): string {\n\t\treturn (\n\t\t\tc.req.header(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ||\n\t\t\tc.req.header(\"x-real-ip\") ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Evicts sessions that have been idle longer than the configured timeout.\n\t */\n\tprivate evictIdleSessions(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, entry] of this.activeSessions) {\n\t\t\tif (now - entry.lastActivity > this.sessionTimeoutMs) {\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);\n\t\t\t\tentry.transport.close().catch(() => {\n\t\t\t\t\t/* Swallow close errors */\n\t\t\t\t});\n\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setupRoutes() {\n\t\tthis.app.use(\"*\", cors());\n\n\t\t// Initialize strict zero-trust token if not provided\n\t\tif (!process.env.ZERO_TRUST_TOKEN) {\n\t\t\tprocess.env.ZERO_TRUST_TOKEN = randomUUID();\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t\tlog.info(\"⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️\");\n\t\t\tlog.info(\"No ZERO_TRUST_TOKEN found in environment.\");\n\t\t\tlog.info(\"A secure ephemeral token has been generated for this session:\");\n\t\t\tlog.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t}\n\n\t\t// ZTA (Zero-Trust Architecture) Security Middleware\n\t\tthis.app.use(\"/mcp\", async (c, next) => {\n\t\t\tconst auth = c.req.header(\"Authorization\");\n\n\t\t\tconst expectedToken = process.env.ZERO_TRUST_TOKEN;\n\t\t\tif (\n\t\t\t\t!auth?.startsWith(\"Bearer \") ||\n\t\t\t\tauth.split(\" \")[1] !== expectedToken\n\t\t\t) {\n\t\t\t\tlog.info(\n\t\t\t\t\t\"[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.\",\n\t\t\t\t);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait next();\n\t\t});\n\n\t\t// Multi-Session Streamable HTTP Handler\n\t\tthis.app.all(\"/mcp\", async (c) => {\n\t\t\tconst sessionId = c.req.header(\"mcp-session-id\");\n\n\t\t\t// Route to existing session if session ID is present\n\t\t\tif (sessionId) {\n\t\t\t\tconst existing = this.activeSessions.get(sessionId);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn c.json({ error: \"Session not found\" }, 404);\n\t\t\t\t}\n\t\t\t\t// Touch activity on every routed request\n\t\t\t\texisting.lastActivity = Date.now();\n\n\t\t\t\tconst response = await existing.transport.handleRequest(c.req.raw);\n\n\t\t\t\t// If DELETE, the transport closes internally but onclose may not fire.\n\t\t\t\t// Explicitly clean up the session from the Map.\n\t\t\t\tif (c.req.method === \"DELETE\") {\n\t\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// No session ID → New client initializing.\n\t\t\t// Rate-limit: enforce max sessions per IP\n\t\t\tconst clientIp = this.getClientIp(c);\n\t\t\tconst currentSessions = this.countSessionsByIp(clientIp);\n\t\t\tif (currentSessions >= this.maxSessionsPerIp) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`,\n\t\t\t\t);\n\t\t\t\treturn c.json({ error: \"Too Many Sessions: Rate limit exceeded\" }, 429);\n\t\t\t}\n\n\t\t\tconst transport = await this.createSessionTransport(clientIp);\n\t\t\treturn await transport.handleRequest(c.req.raw);\n\t\t});\n\t}\n\n\t/**\n\t * Starts the LiopStreamBridge HTTP server and session eviction timer.\n\t */\n\tpublic async start(port?: number): Promise<void> {\n\t\tconst listenPort = port ?? this.options.port ?? 3000;\n\n\t\t// Start the idle session eviction timer\n\t\tthis.evictionTimer = setInterval(\n\t\t\t() => this.evictIdleSessions(),\n\t\t\tEVICTION_INTERVAL_MS,\n\t\t);\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.httpServer = serve(\n\t\t\t\t{\n\t\t\t\t\tfetch: this.app.fetch,\n\t\t\t\t\tport: listenPort,\n\t\t\t\t},\n\t\t\t\t(info) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`,\n\t\t\t\t\t);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Graceful shutdown — closes all active sessions, stops timers, and releases port.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\n\t\tfor (const [id, entry] of this.activeSessions) {\n\t\t\tawait entry.transport.close();\n\t\t\tthis.activeSessions.delete(id);\n\t\t}\n\n\t\tif (this.httpServer) {\n\t\t\tthis.httpServer.close();\n\t\t\tlog.info(\"[LIOP-StreamBridge] HTTP ports released.\");\n\t\t}\n\t}\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LiopServer, LiopServerOptions } from \"../server/index.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopBridgeOptions {\n\tpublishToMesh?: boolean;\n\tmeshIdentity?: string;\n\tserverInfo?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\tsecurity?: LiopServerOptions[\"security\"];\n}\n\n/**\n * LIOP MCP Bridge\n * A bi-directional bridge that allows legacy MCP servers to join the LIOP mesh,\n * or exposes a LIOP server as an MCP-compatible stdio process for tools like Claude Desktop.\n */\nexport class LiopMcpBridge {\n\tprivate liopServer: LiopServer | null = null;\n\tprivate legacyMcpServer: McpServer | null = null;\n\tconstructor(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic source detection\n\t\tsource: LiopServer | McpServer | any,\n\t\tprivate options: LiopBridgeOptions = {},\n\t) {\n\t\t// Determine mode: Exposing LIOP to MCP (Claude) or Wrapping MCP to LIOP (Mesh)\n\t\t// We use constructor name check to avoid hard dependency on optional SDK at runtime start\n\t\tif (source?.constructor?.name === \"LiopServer\") {\n\t\t\tthis.liopServer = source as LiopServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)\");\n\t\t} else if (source?.constructor?.name === \"McpServer\") {\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)\");\n\t\t} else {\n\t\t\t// Fallback for inferred legacy MCP servers\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)\");\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming standard MCP JSON-RPC 2.0 payload.\n\t * Pipes it to the underlying server (LIOP or Legacy MCP).\n\t */\n\tpublic async handleJsonRpcRequest(\n\t\tpayload: Record<string, unknown>,\n\t): Promise<unknown> {\n\t\tconst id = payload.id as string | number;\n\t\tconst method = payload.method as string;\n\t\tconst params = payload.params as Record<string, unknown> | undefined;\n\n\t\tif (payload.jsonrpc !== \"2.0\") {\n\t\t\treturn this.errorResponse(id, -32600, \"Invalid Request\");\n\t\t}\n\n\t\t// Mode: EXPOSE (Standard behavior used by Claude Desktop)\n\t\tif (this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\t// Mode: WRAP (Redirecting via internal LiopServer after connect())\n\t\tif (this.legacyMcpServer && this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Bridge source not configured\");\n\t}\n\n\tprivate async handleLiopToMcp(\n\t\tid: string | number,\n\t\tmethod: string,\n\t\tparams: Record<string, unknown> | undefined,\n\t): Promise<unknown> {\n\t\tif (!this.liopServer) return null;\n\n\t\tif (method === \"initialize\") {\n\t\t\treturn this.successResponse(id, {\n\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\tcapabilities: {\n\t\t\t\t\tprompts: {},\n\t\t\t\t\tresources: {},\n\t\t\t\t\ttools: {},\n\t\t\t\t},\n\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t});\n\t\t}\n\n\t\tif (method === \"notifications/initialized\") return undefined;\n\t\tif (method === \"ping\") return this.successResponse(id, {});\n\n\t\tif (method === \"tools/list\") {\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\treturn this.successResponse(id, { tools });\n\t\t}\n\n\t\tif (method === \"resources/list\") {\n\t\t\tconst resources = this.liopServer.listResources();\n\t\t\treturn this.successResponse(id, { resources });\n\t\t}\n\n\t\tif (method === \"prompts/list\") {\n\t\t\tconst prompts = this.liopServer.listPrompts();\n\t\t\treturn this.successResponse(id, { prompts });\n\t\t}\n\n\t\tif (method === \"prompts/get\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing prompt name\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\tname: params.name as string,\n\t\t\t\t\targuments: params.arguments as Record<string, string> | undefined,\n\t\t\t\t});\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"resources/read\") {\n\t\t\tif (!params?.uri) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing resource URI\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.readResource(params.uri as string);\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"tools/call\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing tool name\");\n\t\t\t}\n\t\t\tconst request: CallToolRequest = {\n\t\t\t\tname: params.name as string,\n\t\t\t\targuments: (params.arguments as Record<string, unknown>) || {},\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst result: CallToolResult = await this.liopServer.callTool(request);\n\t\t\t\tconst isVerified = await this.verifyZkReceipt(request, result);\n\n\t\t\t\tif (!isVerified) {\n\t\t\t\t\treturn this.successResponse(id, {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Method not found\");\n\t}\n\n\tprivate successResponse(\n\t\tid: string | number | null | undefined,\n\t\tresult: unknown,\n\t) {\n\t\treturn { jsonrpc: \"2.0\", id, result };\n\t}\n\n\tprivate errorResponse(id: string | number, code: number, message: string) {\n\t\treturn { jsonrpc: \"2.0\", id, error: { code, message } };\n\t}\n\n\tprivate async verifyZkReceipt(\n\t\trequest: CallToolRequest,\n\t\tresult: CallToolResult,\n\t): Promise<boolean> {\n\t\tif (\n\t\t\t!request.arguments?.payload ||\n\t\t\ttypeof request.arguments.payload !== \"string\"\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = request.arguments.payload as string;\n\t\t\tconst contentText = result.content[0]?.text;\n\n\t\t\tif (contentText && typeof contentText === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(contentText);\n\n\t\t\t\t\tif (data.image_id || data.zk_receipt) {\n\t\t\t\t\t\t// 1. Instantiate the Industrial Verifier ( backed by Piscina Worker Pool )\n\t\t\t\t\t\tconst { LiopVerifier } = await import(\"../crypto/verifier.js\");\n\t\t\t\t\t\tconst verifier = new LiopVerifier();\n\n\t\t\t\t\t\t// 2. Delegate the heavy mathematical check (ZK Journal + Seal)\n\t\t\t\t\t\tconst isAuthentic = await verifier.verifyZkReceipt(\n\t\t\t\t\t\t\tBuffer.from(payload, \"utf-8\"),\n\t\t\t\t\t\t\tdata.image_id,\n\t\t\t\t\t\t\tBuffer.from(data.zk_receipt || \"\", \"base64\"),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isAuthentic) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata.audit_status =\n\t\t\t\t\t\t\t\"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge\";\n\t\t\t\t\t\tresult.content[0].text = JSON.stringify(data);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Output not JSON\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tlog.info(\"[LIOP-Bridge] ZK-Verifier Failure:\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Connects the bridge via stdio or Mesh depending on mode.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\t// In WRAP mode, we actually need to create a LiopServer and join the mesh\n\t\tif (this.legacyMcpServer) {\n\t\t\tconst { LiopServer } = await import(\"../server/index.js\");\n\t\t\tthis.liopServer = new LiopServer(\n\t\t\t\tthis.options.serverInfo || {\n\t\t\t\t\tname: \"liop-bridge\",\n\t\t\t\t\tversion: \"1.0.0\",\n\t\t\t\t},\n\t\t\t\t{ security: this.options.security },\n\t\t\t);\n\n\t\t\tif (this.options.publishToMesh) {\n\t\t\t\tawait this.liopServer.connect();\n\n\t\t\t\t// Automatically Bridge Legacy Capabilities to LIOP Mesh\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal legacy MCP properties are completely opaque and unexported\n\t\t\t\tconst legacy = this.legacyMcpServer as any;\n\n\t\t\t\t// 1. Sync Tools\n\t\t\t\tif (legacy._registeredTools) {\n\t\t\t\t\tfor (const [name, tool] of Object.entries(legacy._registeredTools)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst t = tool as any;\n\t\t\t\t\t\tthis.liopServer.tool(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tt.description || \"\",\n\t\t\t\t\t\t\tt.inputSchema || {},\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy callback args\n\t\t\t\t\t\t\tasync (args: any) => {\n\t\t\t\t\t\t\t\treturn await t.handler(args);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 2. Sync Resources\n\t\t\t\tif (legacy._registeredResources) {\n\t\t\t\t\tfor (const [uri, resource] of Object.entries(\n\t\t\t\t\t\tlegacy._registeredResources,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst r = resource as any;\n\t\t\t\t\t\tthis.liopServer.resource(\n\t\t\t\t\t\t\tr.name,\n\t\t\t\t\t\t\turi,\n\t\t\t\t\t\t\tr.metadata?.description || \"\",\n\t\t\t\t\t\t\tr.metadata?.mimeType || \"application/octet-stream\",\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tconst res = await r.readCallback(new URL(uri));\n\t\t\t\t\t\t\t\treturn res.contents[0].text;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// In EXPOSE mode, listen to stdio (Claude Desktop)\n\t\tconst readline = await import(\"node:readline\");\n\t\tconst rl = readline.createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t\tterminal: false,\n\t\t});\n\n\t\tconst shutdown = async () => {\n\t\t\tlog.info(\"[LIOP-Bridge] Disconnecting session...\");\n\t\t\tif (this.liopServer) await this.liopServer.close();\n\t\t\tprocess.exit(0);\n\t\t};\n\n\t\trl.on(\"close\", shutdown);\n\t\tprocess.on(\"SIGINT\", shutdown);\n\t\tprocess.on(\"SIGTERM\", shutdown);\n\n\t\trl.on(\"line\", async (line) => {\n\t\t\tif (!line.trim()) return;\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(line);\n\t\t\t\tconst response = await this.handleJsonRpcRequest(payload);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t} catch (e: unknown) {\n\t\t\t\tlog.error(`[LIOP-Bridge] Error: ${(e as Error).message}`);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport * from \"./stream.js\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/bridge/stream.ts","../src/bridge/index.ts"],"names":["DEFAULT_MAX_SESSIONS_PER_IP","DEFAULT_SESSION_TIMEOUT_MS","EVICTION_INTERVAL_MS","LiopStreamBridge","internalServer","options","Hono","LiopMcpBridge","clientIp","WebStandardStreamableHTTPServerTransport","transport","randomUUID","sessionId","log","message","entry","result","err","ip","count","c","now","cors","next","auth","expectedToken","existing","response","currentSessions","port","listenPort","resolve","serve","info","id","source","payload","method","params","tools","resources","prompts","request","code","contentText","data","LiopVerifier","e","LiopServer","legacy","name","tool","t","args","uri","resource","r","rl","shutdown","line"],"mappings":"+JA6BA,IAAMA,EAA8B,EAAA,CAC9BC,CAAAA,CAA6B,IAAA,CAAU,GAAA,CACvCC,EAAuB,EAAA,CAAK,GAAA,CAgBrBC,CAAAA,CAAN,KAAuB,CAS7B,WAAA,CACCC,CAAAA,CACQC,CA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AAA,CAAQ,MAAOE,CAAAA,EAAS,CAC7B,GAAKA,CAAAA,CAAK,IAAA,GACV,GAAI,CACH,IAAMvB,CAAAA,CAAU,KAAK,KAAA,CAAMuB,CAAI,EACzBhC,CAAAA,CAAW,MAAM,KAAK,oBAAA,CAAqBS,CAAO,CAAA,CACpDT,CAAAA,EACH,QAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC;AAAA,CAAI,EAEtD,CAAA,MAASoB,CAAAA,CAAY,CACpBlC,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBkC,CAAAA,CAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CACD","file":"chunk-62YQHKSS.js","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { serve } from \"@hono/node-server\";\nimport type { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpBridge } from \"./index.js\";\n\n/**\n * Configuration options for LiopStreamBridge.\n */\nexport interface LiopStreamBridgeOptions {\n\t/** Port to listen on (default: 3000) */\n\tport?: number;\n\t/** Max concurrent sessions per IP (default: 5) */\n\tmaxSessionsPerIp?: number;\n\t/** Session idle timeout in milliseconds (default: 30 min) */\n\tsessionTimeoutMs?: number;\n}\n\n/** Internal metadata for tracked sessions */\ninterface SessionEntry {\n\ttransport: WebStandardStreamableHTTPServerTransport;\n\tlastActivity: number;\n\tclientIp: string;\n}\n\nconst DEFAULT_MAX_SESSIONS_PER_IP = 10;\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst EVICTION_INTERVAL_MS = 60 * 1000; // Check every minute\n\n/**\n * LiopStreamBridge\n *\n * Exposes a LiopServer over a remote HTTP network using the industry-standard\n * MCP Streamable HTTP Transport + Hono JS.\n *\n * Supports concurrent multi-client connections via per-session transport instances (Map pattern).\n * External agents connect using only a URL + Bearer Token (Zero-Trust).\n *\n * Security hardening:\n * - Zero-Trust Bearer Token enforcement\n * - Per-IP rate limiting on session creation\n * - Automatic eviction of idle sessions (TTL)\n */\nexport class LiopStreamBridge {\n\tprivate app: Hono;\n\tprivate httpServer: ReturnType<typeof serve> | null = null;\n\tprivate bridgeLogic: LiopMcpBridge;\n\tprivate activeSessions: Map<string, SessionEntry>;\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate maxSessionsPerIp: number;\n\tprivate sessionTimeoutMs: number;\n\n\tconstructor(\n\t\tinternalServer: LiopServer,\n\t\tprivate options: LiopStreamBridgeOptions = {},\n\t) {\n\t\tthis.app = new Hono();\n\t\tthis.bridgeLogic = new LiopMcpBridge(internalServer);\n\t\tthis.activeSessions = new Map();\n\t\tthis.maxSessionsPerIp =\n\t\t\toptions.maxSessionsPerIp ?? DEFAULT_MAX_SESSIONS_PER_IP;\n\t\tthis.sessionTimeoutMs =\n\t\t\toptions.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n\t\tthis.setupRoutes();\n\t}\n\n\t/**\n\t * Creates a new per-session transport instance and wires it to the LIOPMcpBridge logic.\n\t */\n\tprivate async createSessionTransport(\n\t\tclientIp: string,\n\t): Promise<WebStandardStreamableHTTPServerTransport> {\n\t\tconst { WebStandardStreamableHTTPServerTransport } = await import(\n\t\t\t\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\"\n\t\t);\n\t\tconst transport = new WebStandardStreamableHTTPServerTransport({\n\t\t\tsessionIdGenerator: () => randomUUID(),\n\t\t\tonsessioninitialized: (sessionId: string) => {\n\t\t\t\tthis.activeSessions.set(sessionId, {\n\t\t\t\t\ttransport,\n\t\t\t\t\tlastActivity: Date.now(),\n\t\t\t\t\tclientIp,\n\t\t\t\t});\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`,\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\t// Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router\n\t\ttransport.onmessage = async (message: JSONRPCMessage) => {\n\t\t\t// Touch activity timestamp on every message\n\t\t\tif (transport.sessionId) {\n\t\t\t\tconst entry = this.activeSessions.get(transport.sessionId);\n\t\t\t\tif (entry) entry.lastActivity = Date.now();\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.bridgeLogic.handleJsonRpcRequest(\n\t\t\t\t\tmessage as unknown as Record<string, unknown>,\n\t\t\t\t);\n\t\t\t\t// Notifications return undefined — no response needed\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tawait transport.send(result as JSONRPCMessage);\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\"[LIOP-StreamBridge] JSON-RPC error:\", (err as Error).message);\n\t\t\t}\n\t\t};\n\n\t\ttransport.onclose = () => {\n\t\t\tif (transport.sessionId) {\n\t\t\t\tthis.activeSessions.delete(transport.sessionId);\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);\n\t\t\t}\n\t\t};\n\n\t\treturn transport;\n\t}\n\n\t/**\n\t * Returns the number of active sessions for a given IP.\n\t */\n\tprivate countSessionsByIp(ip: string): number {\n\t\tlet count = 0;\n\t\tfor (const entry of this.activeSessions.values()) {\n\t\t\tif (entry.clientIp === ip) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\t/**\n\t * Extracts client IP from the request (supports X-Forwarded-For for reverse proxies).\n\t */\n\tprivate getClientIp(c: {\n\t\treq: { header: (name: string) => string | undefined };\n\t}): string {\n\t\treturn (\n\t\t\tc.req.header(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ||\n\t\t\tc.req.header(\"x-real-ip\") ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Evicts sessions that have been idle longer than the configured timeout.\n\t */\n\tprivate evictIdleSessions(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, entry] of this.activeSessions) {\n\t\t\tif (now - entry.lastActivity > this.sessionTimeoutMs) {\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);\n\t\t\t\tentry.transport.close().catch(() => {\n\t\t\t\t\t/* Swallow close errors */\n\t\t\t\t});\n\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setupRoutes() {\n\t\tthis.app.use(\"*\", cors());\n\n\t\t// Initialize strict zero-trust token if not provided\n\t\tif (!process.env.ZERO_TRUST_TOKEN) {\n\t\t\tprocess.env.ZERO_TRUST_TOKEN = randomUUID();\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t\tlog.info(\"⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️\");\n\t\t\tlog.info(\"No ZERO_TRUST_TOKEN found in environment.\");\n\t\t\tlog.info(\"A secure ephemeral token has been generated for this session:\");\n\t\t\tlog.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t}\n\n\t\t// ZTA (Zero-Trust Architecture) Security Middleware\n\t\tthis.app.use(\"/mcp\", async (c, next) => {\n\t\t\tconst auth = c.req.header(\"Authorization\");\n\n\t\t\tconst expectedToken = process.env.ZERO_TRUST_TOKEN;\n\t\t\tif (\n\t\t\t\t!auth?.startsWith(\"Bearer \") ||\n\t\t\t\tauth.split(\" \")[1] !== expectedToken\n\t\t\t) {\n\t\t\t\tlog.info(\n\t\t\t\t\t\"[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.\",\n\t\t\t\t);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait next();\n\t\t});\n\n\t\t// Multi-Session Streamable HTTP Handler\n\t\tthis.app.all(\"/mcp\", async (c) => {\n\t\t\tconst sessionId = c.req.header(\"mcp-session-id\");\n\n\t\t\t// Route to existing session if session ID is present\n\t\t\tif (sessionId) {\n\t\t\t\tconst existing = this.activeSessions.get(sessionId);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn c.json({ error: \"Session not found\" }, 404);\n\t\t\t\t}\n\t\t\t\t// Touch activity on every routed request\n\t\t\t\texisting.lastActivity = Date.now();\n\n\t\t\t\tconst response = await existing.transport.handleRequest(c.req.raw);\n\n\t\t\t\t// If DELETE, the transport closes internally but onclose may not fire.\n\t\t\t\t// Explicitly clean up the session from the Map.\n\t\t\t\tif (c.req.method === \"DELETE\") {\n\t\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// No session ID → New client initializing.\n\t\t\t// Rate-limit: enforce max sessions per IP\n\t\t\tconst clientIp = this.getClientIp(c);\n\t\t\tconst currentSessions = this.countSessionsByIp(clientIp);\n\t\t\tif (currentSessions >= this.maxSessionsPerIp) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`,\n\t\t\t\t);\n\t\t\t\treturn c.json({ error: \"Too Many Sessions: Rate limit exceeded\" }, 429);\n\t\t\t}\n\n\t\t\tconst transport = await this.createSessionTransport(clientIp);\n\t\t\treturn await transport.handleRequest(c.req.raw);\n\t\t});\n\t}\n\n\t/**\n\t * Starts the LiopStreamBridge HTTP server and session eviction timer.\n\t */\n\tpublic async start(port?: number): Promise<void> {\n\t\tconst listenPort = port ?? this.options.port ?? 3000;\n\n\t\t// Start the idle session eviction timer\n\t\tthis.evictionTimer = setInterval(\n\t\t\t() => this.evictIdleSessions(),\n\t\t\tEVICTION_INTERVAL_MS,\n\t\t);\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.httpServer = serve(\n\t\t\t\t{\n\t\t\t\t\tfetch: this.app.fetch,\n\t\t\t\t\tport: listenPort,\n\t\t\t\t},\n\t\t\t\t(info) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`,\n\t\t\t\t\t);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Graceful shutdown — closes all active sessions, stops timers, and releases port.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\n\t\tfor (const [id, entry] of this.activeSessions) {\n\t\t\tawait entry.transport.close();\n\t\t\tthis.activeSessions.delete(id);\n\t\t}\n\n\t\tif (this.httpServer) {\n\t\t\tthis.httpServer.close();\n\t\t\tlog.info(\"[LIOP-StreamBridge] HTTP ports released.\");\n\t\t}\n\t}\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LiopServer, LiopServerOptions } from \"../server/index.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopBridgeOptions {\n\tpublishToMesh?: boolean;\n\tmeshIdentity?: string;\n\tserverInfo?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\tsecurity?: LiopServerOptions[\"security\"];\n}\n\n/**\n * LIOP MCP Bridge\n * A bi-directional bridge that allows legacy MCP servers to join the LIOP mesh,\n * or exposes a LIOP server as an MCP-compatible stdio process for tools like Claude Desktop.\n */\nexport class LiopMcpBridge {\n\tprivate liopServer: LiopServer | null = null;\n\tprivate legacyMcpServer: McpServer | null = null;\n\tconstructor(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic source detection\n\t\tsource: LiopServer | McpServer | any,\n\t\tprivate options: LiopBridgeOptions = {},\n\t) {\n\t\t// Determine mode: Exposing LIOP to MCP (Claude) or Wrapping MCP to LIOP (Mesh)\n\t\t// We use constructor name check to avoid hard dependency on optional SDK at runtime start\n\t\tif (source?.constructor?.name === \"LiopServer\") {\n\t\t\tthis.liopServer = source as LiopServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)\");\n\t\t} else if (source?.constructor?.name === \"McpServer\") {\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)\");\n\t\t} else {\n\t\t\t// Fallback for inferred legacy MCP servers\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)\");\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming standard MCP JSON-RPC 2.0 payload.\n\t * Pipes it to the underlying server (LIOP or Legacy MCP).\n\t */\n\tpublic async handleJsonRpcRequest(\n\t\tpayload: Record<string, unknown>,\n\t): Promise<unknown> {\n\t\tconst id = payload.id as string | number;\n\t\tconst method = payload.method as string;\n\t\tconst params = payload.params as Record<string, unknown> | undefined;\n\n\t\tif (payload.jsonrpc !== \"2.0\") {\n\t\t\treturn this.errorResponse(id, -32600, \"Invalid Request\");\n\t\t}\n\n\t\t// Mode: EXPOSE (Standard behavior used by Claude Desktop)\n\t\tif (this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\t// Mode: WRAP (Redirecting via internal LiopServer after connect())\n\t\tif (this.legacyMcpServer && this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Bridge source not configured\");\n\t}\n\n\tprivate async handleLiopToMcp(\n\t\tid: string | number,\n\t\tmethod: string,\n\t\tparams: Record<string, unknown> | undefined,\n\t): Promise<unknown> {\n\t\tif (!this.liopServer) return null;\n\n\t\tif (method === \"initialize\") {\n\t\t\treturn this.successResponse(id, {\n\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\tcapabilities: {\n\t\t\t\t\tprompts: {},\n\t\t\t\t\tresources: {},\n\t\t\t\t\ttools: {},\n\t\t\t\t},\n\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t});\n\t\t}\n\n\t\tif (method === \"notifications/initialized\") return undefined;\n\t\tif (method === \"ping\") return this.successResponse(id, {});\n\n\t\tif (method === \"tools/list\") {\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\treturn this.successResponse(id, { tools });\n\t\t}\n\n\t\tif (method === \"resources/list\") {\n\t\t\tconst resources = this.liopServer.listResources();\n\t\t\treturn this.successResponse(id, { resources });\n\t\t}\n\n\t\tif (method === \"prompts/list\") {\n\t\t\tconst prompts = this.liopServer.listPrompts();\n\t\t\treturn this.successResponse(id, { prompts });\n\t\t}\n\n\t\tif (method === \"prompts/get\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing prompt name\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\tname: params.name as string,\n\t\t\t\t\targuments: params.arguments as Record<string, string> | undefined,\n\t\t\t\t});\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"resources/read\") {\n\t\t\tif (!params?.uri) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing resource URI\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.readResource(params.uri as string);\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"tools/call\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing tool name\");\n\t\t\t}\n\t\t\tconst request: CallToolRequest = {\n\t\t\t\tname: params.name as string,\n\t\t\t\targuments: (params.arguments as Record<string, unknown>) || {},\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst result: CallToolResult = await this.liopServer.callTool(request);\n\t\t\t\tconst isVerified = await this.verifyZkReceipt(request, result);\n\n\t\t\t\tif (!isVerified) {\n\t\t\t\t\treturn this.successResponse(id, {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Method not found\");\n\t}\n\n\tprivate successResponse(\n\t\tid: string | number | null | undefined,\n\t\tresult: unknown,\n\t) {\n\t\treturn { jsonrpc: \"2.0\", id, result };\n\t}\n\n\tprivate errorResponse(id: string | number, code: number, message: string) {\n\t\treturn { jsonrpc: \"2.0\", id, error: { code, message } };\n\t}\n\n\tprivate async verifyZkReceipt(\n\t\trequest: CallToolRequest,\n\t\tresult: CallToolResult,\n\t): Promise<boolean> {\n\t\tif (\n\t\t\t!request.arguments?.payload ||\n\t\t\ttypeof request.arguments.payload !== \"string\"\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = request.arguments.payload as string;\n\t\t\tconst contentText = result.content[0]?.text;\n\n\t\t\tif (contentText && typeof contentText === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(contentText);\n\n\t\t\t\t\tif (data.image_id || data.zk_receipt) {\n\t\t\t\t\t\t// 1. Instantiate the Industrial Verifier ( backed by Piscina Worker Pool )\n\t\t\t\t\t\tconst { LiopVerifier } = await import(\"../crypto/verifier.js\");\n\t\t\t\t\t\tconst verifier = new LiopVerifier();\n\n\t\t\t\t\t\t// 2. Delegate the heavy mathematical check (ZK Journal + Seal)\n\t\t\t\t\t\tconst isAuthentic = await verifier.verifyZkReceipt(\n\t\t\t\t\t\t\tBuffer.from(payload, \"utf-8\"),\n\t\t\t\t\t\t\tdata.image_id,\n\t\t\t\t\t\t\tBuffer.from(data.zk_receipt || \"\", \"base64\"),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isAuthentic) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata.audit_status =\n\t\t\t\t\t\t\t\"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge\";\n\t\t\t\t\t\tresult.content[0].text = JSON.stringify(data);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Output not JSON\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tlog.info(\"[LIOP-Bridge] ZK-Verifier Failure:\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Connects the bridge via stdio or Mesh depending on mode.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\t// In WRAP mode, we actually need to create a LiopServer and join the mesh\n\t\tif (this.legacyMcpServer) {\n\t\t\tconst { LiopServer } = await import(\"../server/index.js\");\n\t\t\tthis.liopServer = new LiopServer(\n\t\t\t\tthis.options.serverInfo || {\n\t\t\t\t\tname: \"liop-bridge\",\n\t\t\t\t\tversion: \"1.0.0\",\n\t\t\t\t},\n\t\t\t\t{ security: this.options.security },\n\t\t\t);\n\n\t\t\tif (this.options.publishToMesh) {\n\t\t\t\tawait this.liopServer.connect();\n\n\t\t\t\t// Automatically Bridge Legacy Capabilities to LIOP Mesh\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal legacy MCP properties are completely opaque and unexported\n\t\t\t\tconst legacy = this.legacyMcpServer as any;\n\n\t\t\t\t// 1. Sync Tools\n\t\t\t\tif (legacy._registeredTools) {\n\t\t\t\t\tfor (const [name, tool] of Object.entries(legacy._registeredTools)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst t = tool as any;\n\t\t\t\t\t\tthis.liopServer.tool(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tt.description || \"\",\n\t\t\t\t\t\t\tt.inputSchema || {},\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy callback args\n\t\t\t\t\t\t\tasync (args: any) => {\n\t\t\t\t\t\t\t\treturn await t.handler(args);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 2. Sync Resources\n\t\t\t\tif (legacy._registeredResources) {\n\t\t\t\t\tfor (const [uri, resource] of Object.entries(\n\t\t\t\t\t\tlegacy._registeredResources,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst r = resource as any;\n\t\t\t\t\t\tthis.liopServer.resource(\n\t\t\t\t\t\t\tr.name,\n\t\t\t\t\t\t\turi,\n\t\t\t\t\t\t\tr.metadata?.description || \"\",\n\t\t\t\t\t\t\tr.metadata?.mimeType || \"application/octet-stream\",\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tconst res = await r.readCallback(new URL(uri));\n\t\t\t\t\t\t\t\treturn res.contents[0].text;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// In EXPOSE mode, listen to stdio (Claude Desktop)\n\t\tconst readline = await import(\"node:readline\");\n\t\tconst rl = readline.createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t\tterminal: false,\n\t\t});\n\n\t\tconst shutdown = async () => {\n\t\t\tlog.info(\"[LIOP-Bridge] Disconnecting session...\");\n\t\t\tif (this.liopServer) await this.liopServer.close();\n\t\t\tprocess.exit(0);\n\t\t};\n\n\t\trl.on(\"close\", shutdown);\n\t\tprocess.on(\"SIGINT\", shutdown);\n\t\tprocess.on(\"SIGTERM\", shutdown);\n\n\t\trl.on(\"line\", async (line) => {\n\t\t\tif (!line.trim()) return;\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(line);\n\t\t\t\tconst response = await this.handleJsonRpcRequest(payload);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t} catch (e: unknown) {\n\t\t\t\tlog.error(`[LIOP-Bridge] Error: ${(e as Error).message}`);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport * from \"./stream.js\";\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{b as WasiSandbox}from'./chunk-HNDVAKEK.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-P52IE4L6.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-HQZHZM6U.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-
|
|
1
|
+
export{b as WasiSandbox}from'./chunk-HNDVAKEK.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-P52IE4L6.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-HQZHZM6U.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-62YQHKSS.js';export{a as LiopHybridGateway}from'./chunk-JBMEAXYU.js';export{a as LiopRpcServer,f as LiopServer,b as NerScanner,c as PII_PATTERNS,d as PII_PRESETS,e as PiiScanner}from'./chunk-5OAZNVIU.js';export{b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-7MAGL6ON.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-HM77MWB6.js';export{a as MeshNode}from'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';var u=(e=>(e.CapabilityViolation="CapabilityViolation",e.SandboxEscape="SandboxEscape",e.PiiLeak="PiiLeak",e.InvalidIntent="InvalidIntent",e.Throttled="Throttled",e.ZkVerificationFailed="ZkVerificationFailed",e.MeshUnavailable="MeshUnavailable",e.ConnectionFailed="ConnectionFailed",e))(u||{}),n=class extends Error{code;constructor(t,o){super(o),this.name="LiopError",this.code=t;}};var f={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function D(a){let t=f[a],o=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
|
|
2
2
|
You are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.
|
|
3
3
|
Unlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.
|
|
4
4
|
|
package/dist/server.d.ts
CHANGED
|
@@ -143,6 +143,8 @@ interface AggregationPolicy {
|
|
|
143
143
|
maxOutputRows?: number;
|
|
144
144
|
/** Allow arrays containing only primitive values (default: true) */
|
|
145
145
|
allowPrimitiveArrays?: boolean;
|
|
146
|
+
/** Block min/max extraction when dataset size < this value (default: 50) */
|
|
147
|
+
minMaxBlockThreshold?: number;
|
|
146
148
|
}
|
|
147
149
|
interface LogicExecutionPolicy {
|
|
148
150
|
/**
|
|
@@ -158,6 +160,21 @@ interface LogicExecutionPolicy {
|
|
|
158
160
|
* Optional additional deny patterns checked against extracted logic source.
|
|
159
161
|
*/
|
|
160
162
|
preflightDenyPatterns?: RegExp[];
|
|
163
|
+
/**
|
|
164
|
+
* Differential Privacy epsilon per query (default: 1.0).
|
|
165
|
+
* Lower = stronger privacy + more noise. Standard: Apple iOS uses 1.0.
|
|
166
|
+
*/
|
|
167
|
+
dpEpsilon?: number;
|
|
168
|
+
/**
|
|
169
|
+
* DP sensitivity: max change when one record added/removed (default: 1.0).
|
|
170
|
+
* For SUM queries on a field with range [0, X], set sensitivity = X.
|
|
171
|
+
*/
|
|
172
|
+
dpSensitivity?: number;
|
|
173
|
+
/**
|
|
174
|
+
* Max queries per numeric field per PQC session (default: 5).
|
|
175
|
+
* Prevents multi-query differencing attacks.
|
|
176
|
+
*/
|
|
177
|
+
queryBudgetPerField?: number;
|
|
161
178
|
}
|
|
162
179
|
declare class LiopServer {
|
|
163
180
|
private serverInfo;
|
|
@@ -172,6 +189,7 @@ declare class LiopServer {
|
|
|
172
189
|
private readonly toolCallWindowMs;
|
|
173
190
|
private globalCallWindow;
|
|
174
191
|
private readonly globalCallMaxPerWindow;
|
|
192
|
+
private fieldQueryBudget;
|
|
175
193
|
private readonly taintAnalyzer;
|
|
176
194
|
private tools;
|
|
177
195
|
private resources;
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{f as LiopServer,b as NerScanner,c as PII_PATTERNS,d as PII_PRESETS,e as PiiScanner}from'./chunk-
|
|
1
|
+
export{f as LiopServer,b as NerScanner,c as PII_PATTERNS,d as PII_PRESETS,e as PiiScanner}from'./chunk-5OAZNVIU.js';import'./chunk-HM77MWB6.js';import'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';//# sourceMappingURL=server.js.map
|
|
2
2
|
//# sourceMappingURL=server.js.map
|
|
@@ -8,6 +8,11 @@ interface WorkerData {
|
|
|
8
8
|
sessionToken: string;
|
|
9
9
|
isEncrypted?: boolean;
|
|
10
10
|
aesNonce?: Uint8Array;
|
|
11
|
+
dpConfig?: {
|
|
12
|
+
epsilon: number;
|
|
13
|
+
sensitivity: number;
|
|
14
|
+
smallDatasetThreshold: number;
|
|
15
|
+
};
|
|
11
16
|
}
|
|
12
17
|
declare function processLogicExecution(data: WorkerData): Promise<{
|
|
13
18
|
image_id: string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a,b}from'../chunk-HNDVAKEK.js';import {a as a$1,b as b$1}from'../chunk-ANFXJGMP.js';import {Buffer}from'buffer';import
|
|
1
|
+
import {a,b}from'../chunk-HNDVAKEK.js';import {a as a$1,b as b$1}from'../chunk-ANFXJGMP.js';import {Buffer}from'buffer';import g from'crypto';import {createMlKem768}from'mlkem';var C={epsilon:1,sensitivity:1,smallDatasetThreshold:50},I=1,K=10;function V(t,r){let n;do r?n=g.createHash("sha256").update(`${r.seed}:${r.counter++}`).digest().readUInt32BE(0)/4294967296-.5:n=g.randomBytes(4).readUInt32BE(0)/4294967296-.5;while(n===0||n===-0.5);return -t*Math.sign(n)*Math.log(1-2*Math.abs(n))}function G(t,r={},n){let e={...C,...r},a=e.sensitivity/e.epsilon,o=t+V(a,n);return Math.round(o*1e4)/1e4}function R(t,r,n){if(!t)return r;let e=t.toLowerCase(),a=/count|length|size|num|nan_|negative_|positive_|null_|empty_|finite_|non_finite_/i.test(e),o=e==="total"||e==="n"||e==="total_records"||/total.*(count|items|entries|rows|records)/i.test(e);return a||o?1:/avg|mean|average/.test(e)&&n>0?r/n:r}function M(t,r={},n){let e={...C,...r};if(n>=e.smallDatasetThreshold)return t;n<K&&e.epsilon<I&&(e.epsilon=I);let a;return e.seed&&(a={seed:e.seed,counter:0}),A(t,e,n,void 0,a)}function A(t,r,n,e,a){if(typeof t=="number"&&Number.isFinite(t)){let o=R(e,r.sensitivity,n),u=G(t,{...r,sensitivity:o},a),p=e!=null&&R(e,r.sensitivity,n)===1;return (Number.isInteger(t)||p)&&(u=Math.round(u)),t>=0&&(u=Math.max(0,u)),u}if(Array.isArray(t))return t.map(o=>A(o,r,n,e,a));if(t!==null&&typeof t=="object"){let o={};for(let[u,p]of Object.entries(t))o[u]=A(p,r,n,u,a);return o}return t}async function Q(t){let{ciphertext:r,secretKeyObj:n,wasmBinary:e,inputs:a$2,aesNonce:o,records:u,isEncrypted:p=true,dpConfig:S}=t,s,O={},T=Buffer.alloc(32);if(p){let l=new Uint8Array(n),c=new Uint8Array(r),d=(await createMlKem768()).decap(c,l),f=Buffer.from(d);T=f;let m=Buffer.from(e),D=m.subarray(-16),b=m.subarray(0,-16),w=g.createDecipheriv("aes-256-gcm",f,Buffer.from(o||new Uint8Array(12)));w.setAuthTag(D);let y=w.update(b);y=Buffer.concat([y,w.final()]),s=y;for(let[j,H]of Object.entries(a$2||{})){let k=Buffer.from(H),z=k.subarray(0,12),F=k.subarray(-16),W=k.subarray(12,-16),_=g.createDecipheriv("aes-256-gcm",f,z);_.setAuthTag(F);let v=_.update(W);v=Buffer.concat([v,_.final()]),O[j]=JSON.parse(v.toString("utf-8"));}}else e[0]===0&&e[1]===97&&e[2]===115&&e[3]===109?s=Buffer.from(e):s=Buffer.from(e).toString("utf-8");let U=s[0]===0&&s[1]===97&&s[2]===115&&s[3]===109;if(s instanceof Buffer&&U){let l=new Uint8Array(s),c=await WebAssembly.compile(l);a.analyze(c);}else s instanceof Buffer&&!U&&(s=s.toString("utf-8"));typeof s=="string"&&(s=a$1(s));let x=new b;await x.init();try{let l=await x.execute(s,u,O),c=l.output,h;typeof s=="string"?h=Buffer.from(s,"utf-8"):h=new Uint8Array(s);let d=b$1(h).toString("hex"),f=g.createHash("sha256").update(JSON.stringify(u||[])).digest("hex");S&&(c=M(c,{...S,seed:`${f}:${d}`},u?.length||0));let m=Buffer.from(JSON.stringify({image_id:d,dataset_hash:f,output_hash:g.createHash("sha256").update(typeof c=="string"?c:JSON.stringify(c)).digest("hex"),fuel:l.fuelConsumed,ts:Date.now()})),D=g.createHmac("sha256",T).update(m).digest(),b=Buffer.alloc(2);b.writeUInt16BE(m.length);let y=Buffer.concat([Buffer.from([1]),b,m,D]).toString("base64");return {image_id:d,zk_receipt:y,output:c,fuel_consumed:l.fuelConsumed}}finally{await x.teardown();}}export{Q as default};//# sourceMappingURL=logic-execution.js.map
|
|
2
2
|
//# sourceMappingURL=logic-execution.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/workers/logic-execution.ts"],"names":["processLogicExecution","data","ciphertext","secretKeyObj","wasmBinary","inputs","aesNonce","records","isEncrypted","decryptedPayload","decryptedInputs","sessionSecret","Buffer","sk","ct","sharedSecret","createMlKem768","aesKey","wasmBuffer","authTag","encryptedData","decipher","crypto","decrypted","key","encValue","valBuffer","inputNonce","valTag","valData","valDecipher","valDecrypted","isWasm","wasmBytes","compiledModule","ASTGuardian","normalizeLogicSource","sandbox","WasiSandbox","result","logicBytes","imageId","deriveLogicImageDigest","journal","seal","journalLen","zkReceipt"],"mappings":"iLAsBA,eAAOA,EAA6CC,CAAAA,CAKjD,CACF,GAAM,CACL,UAAA,CAAAC,EACA,YAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,SAAAC,CAAAA,CACA,OAAA,CAAAC,EACA,WAAA,CAAAC,CAAAA,CAAc,IACf,CAAA,CAAIP,CAAAA,CAEAQ,CAAAA,CACEC,CAAAA,CAA2C,EAAC,CAC9CC,EAAgBC,MAAAA,CAAO,KAAA,CAAM,EAAE,CAAA,CAEnC,GAAIJ,CAAAA,CAAa,CAEhB,IAAMK,CAAAA,CAAK,IAAI,UAAA,CAAWV,CAAY,CAAA,CAChCW,EAAK,IAAI,UAAA,CAAWZ,CAAU,CAAA,CAE9Ba,CAAAA,CAAAA,CADM,MAAMC,cAAAA,EAAe,EACR,KAAA,CAAMF,CAAAA,CAAID,CAAE,CAAA,CAC/BI,EAASL,MAAAA,CAAO,IAAA,CAAKG,CAAY,CAAA,CACvCJ,CAAAA,CAAgBM,EAIhB,IAAMC,CAAA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AAAA,CAAa5B,MAAAA,CAAO,IAAA,CAAKH,CAAAA,CAAkB,OAAO,EAElD+B,CAAAA,CAAa,IAAI,UAAA,CAAW/B,CAAgB,CAAA,CAE7C,IAAMgC,EAAUC,GAAAA,CAAuBF,CAAU,EAAE,QAAA,CAAS,KAAK,EAE3DG,CAAAA,CAAU/B,MAAAA,CAAO,IAAA,CACtB,IAAA,CAAK,SAAA,CAAU,CACd,SAAU6B,CAAAA,CACV,WAAA,CAAanB,EACX,UAAA,CAAW,QAAQ,EACnB,MAAA,CACA,OAAOiB,CAAAA,CAAO,MAAA,EAAW,QAAA,CACtBA,CAAAA,CAAO,OACP,IAAA,CAAK,SAAA,CAAUA,EAAO,MAAM,CAChC,EACC,MAAA,CAAO,KAAK,CAAA,CACd,IAAA,CAAMA,CAAAA,CAAO,YAAA,CACb,GAAI,IAAA,CAAK,GAAA,EACV,CAAC,CACF,CAAA,CAEMK,EAAOtB,CAAAA,CACX,UAAA,CAAW,QAAA,CAAUX,CAAa,CAAA,CAClC,MAAA,CAAOgC,CAAO,CAAA,CACd,MAAA,GACIE,CAAAA,CAAajC,MAAAA,CAAO,MAAM,CAAC,CAAA,CACjCiC,CAAAA,CAAW,aAAA,CAAcF,CAAAA,CAAQ,MAAM,EAOvC,IAAMG,CAAAA,CANalC,MAAAA,CAAO,MAAA,CAAO,CAChCA,MAAAA,CAAO,KAAK,CAAC,CAAI,CAAC,CAAA,CAClBiC,CAAAA,CACAF,CAAAA,CACAC,CACD,CAAC,CAAA,CAC4B,SAAS,QAAQ,CAAA,CAE9C,OAAO,CACN,QAAA,CAAUH,CAAAA,CACV,UAAA,CAAYK,CAAAA,CACZ,MAAA,CAAQP,EAAO,MAAA,CACf,aAAA,CAAeA,CAAAA,CAAO,YACvB,CACD,CAAA,OAAE,CACD,MAAMF,CAAAA,CAAQ,QAAA,GACf,CACD","file":"logic-execution.js","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport crypto from \"node:crypto\";\nimport { createMlKem768 } from \"mlkem\";\nimport {\n\tderiveLogicImageDigest,\n\tnormalizeLogicSource,\n} from \"../crypto/logic-image-id.js\";\nimport { ASTGuardian } from \"../sandbox/guardian.js\";\nimport { WasiSandbox } from \"../sandbox/wasi.js\";\n\nexport interface WorkerData {\n\tciphertext: Uint8Array;\n\tsecretKeyObj: ArrayLike<number>;\n\tkyberPublicKey: Uint8Array;\n\twasmBinary: Uint8Array; // Can also be JS code in non-encrypted mode\n\tinputs: Record<string, Uint8Array>;\n\trecords?: Record<string, unknown>[];\n\tsessionToken: string;\n\tisEncrypted?: boolean;\n\taesNonce?: Uint8Array;\n}\n\nexport default async function processLogicExecution(data: WorkerData): Promise<{\n\timage_id: string;\n\toutput: unknown;\n\tfuel_consumed: number;\n\tzk_receipt?: string;\n}> {\n\tconst {\n\t\tciphertext,\n\t\tsecretKeyObj,\n\t\twasmBinary,\n\t\tinputs,\n\t\taesNonce,\n\t\trecords,\n\t\tisEncrypted = true,\n\t} = data;\n\n\tlet decryptedPayload: Buffer | string;\n\tconst decryptedInputs: Record<string, unknown> = {};\n\tlet sessionSecret = Buffer.alloc(32); // Fallback if plain text (no PQC)\n\n\tif (isEncrypted) {\n\t\t// 1. Decapsulate Kyber secret\n\t\tconst sk = new Uint8Array(secretKeyObj);\n\t\tconst ct = new Uint8Array(ciphertext);\n\t\tconst kem = await createMlKem768();\n\t\tconst sharedSecret = kem.decap(ct, sk);\n\t\tconst aesKey = Buffer.from(sharedSecret);\n\t\tsessionSecret = aesKey;\n\n\t\t// 2. Decrypt Main Payload (WASM/JS Code)\n\t\t// LIOP Serialization: Ciphertext = EncryptedData + 16-byte AuthTag\n\t\tconst wasmBuffer = Buffer.from(wasmBinary);\n\t\tconst authTag = wasmBuffer.subarray(-16);\n\t\tconst encryptedData = wasmBuffer.subarray(0, -16);\n\n\t\tconst decipher = crypto.createDecipheriv(\n\t\t\t\"aes-256-gcm\",\n\t\t\taesKey,\n\t\t\tBuffer.from(aesNonce || new Uint8Array(12)),\n\t\t);\n\t\tdecipher.setAuthTag(authTag);\n\t\tlet decrypted = decipher.update(encryptedData);\n\t\tdecrypted = Buffer.concat([decrypted, decipher.final()]);\n\t\tdecryptedPayload = decrypted;\n\n\t\t// 3. Decrypt Inputs\n\t\tfor (const [key, encValue] of Object.entries(inputs || {})) {\n\t\t\tconst valBuffer = Buffer.from(encValue);\n\t\t\t// Extract 12-byte prepended nonce, ciphertext, and 16-byte AuthTag\n\t\t\tconst inputNonce = valBuffer.subarray(0, 12);\n\t\t\tconst valTag = valBuffer.subarray(-16);\n\t\t\tconst valData = valBuffer.subarray(12, -16);\n\n\t\t\tconst valDecipher = crypto.createDecipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\taesKey,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tvalDecipher.setAuthTag(valTag);\n\t\t\tlet valDecrypted = valDecipher.update(valData);\n\t\t\tvalDecrypted = Buffer.concat([valDecrypted, valDecipher.final()]);\n\t\t\tdecryptedInputs[key] = JSON.parse(valDecrypted.toString(\"utf-8\"));\n\t\t}\n\t} else {\n\t\t// Transparent mode: payload is provided directly\n\t\t// If it's WASM (Magic bytes: \\0asm), keep as Buffer\n\t\tif (\n\t\t\twasmBinary[0] === 0x00 &&\n\t\t\twasmBinary[1] === 0x61 &&\n\t\t\twasmBinary[2] === 0x73 &&\n\t\t\twasmBinary[3] === 0x6d\n\t\t) {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary);\n\t\t} else {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary).toString(\"utf-8\");\n\t\t}\n\t}\n\n\t// 3. Inspect AST with Guardian-TS (if WASM)\n\tconst isWasm =\n\t\tdecryptedPayload[0] === 0x00 &&\n\t\tdecryptedPayload[1] === 0x61 &&\n\t\tdecryptedPayload[2] === 0x73 &&\n\t\tdecryptedPayload[3] === 0x6d;\n\n\tif (decryptedPayload instanceof Buffer && isWasm) {\n\t\t// Ensure we pass a compatible BufferSource\n\t\tconst wasmBytes = new Uint8Array(decryptedPayload);\n\t\tconst compiledModule = await WebAssembly.compile(wasmBytes);\n\t\tASTGuardian.analyze(compiledModule);\n\t} else if (decryptedPayload instanceof Buffer && !isWasm) {\n\t\tdecryptedPayload = decryptedPayload.toString(\"utf-8\");\n\t}\n\n\t// Strip only a whole-document LIOP envelope (see logic-image-id.ts).\n\tif (typeof decryptedPayload === \"string\") {\n\t\tdecryptedPayload = normalizeLogicSource(decryptedPayload);\n\t}\n\n\t// 4. Instantiate and Execute WASI Sandbox (or V8 Fallback)\n\tconst sandbox = new WasiSandbox();\n\tawait sandbox.init();\n\n\ttry {\n\t\tconst result = await sandbox.execute(\n\t\t\tdecryptedPayload,\n\t\t\trecords,\n\t\t\tdecryptedInputs,\n\t\t);\n\n\t\t// 5. Generate Cryptographic Proof of Execution (HMAC-SHA256 Commitment)\n\t\tlet logicBytes: Uint8Array;\n\t\tif (typeof decryptedPayload === \"string\") {\n\t\t\tlogicBytes = Buffer.from(decryptedPayload, \"utf-8\");\n\t\t} else {\n\t\t\tlogicBytes = new Uint8Array(decryptedPayload);\n\t\t}\n\t\tconst imageId = deriveLogicImageDigest(logicBytes).toString(\"hex\");\n\n\t\tconst journal = Buffer.from(\n\t\t\tJSON.stringify({\n\t\t\t\timage_id: imageId,\n\t\t\t\toutput_hash: crypto\n\t\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t\t.update(\n\t\t\t\t\t\ttypeof result.output === \"string\"\n\t\t\t\t\t\t\t? result.output\n\t\t\t\t\t\t\t: JSON.stringify(result.output),\n\t\t\t\t\t)\n\t\t\t\t\t.digest(\"hex\"),\n\t\t\t\tfuel: result.fuelConsumed,\n\t\t\t\tts: Date.now(),\n\t\t\t}),\n\t\t);\n\n\t\tconst seal = crypto\n\t\t\t.createHmac(\"sha256\", sessionSecret)\n\t\t\t.update(journal)\n\t\t\t.digest();\n\t\tconst journalLen = Buffer.alloc(2);\n\t\tjournalLen.writeUInt16BE(journal.length);\n\t\tconst receiptBuf = Buffer.concat([\n\t\t\tBuffer.from([0x01]), // Receipt format v1\n\t\t\tjournalLen,\n\t\t\tjournal,\n\t\t\tseal, // 32 bytes HMAC\n\t\t]);\n\t\tconst zkReceipt = receiptBuf.toString(\"base64\");\n\n\t\treturn {\n\t\t\timage_id: imageId,\n\t\t\tzk_receipt: zkReceipt,\n\t\t\toutput: result.output,\n\t\t\tfuel_consumed: result.fuelConsumed,\n\t\t};\n\t} finally {\n\t\tawait sandbox.teardown();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/security/dp-engine.ts","../../src/workers/logic-execution.ts"],"names":["DEFAULT_DP_CONFIG","EPSILON_FLOOR","EPSILON_FLOOR_THRESHOLD","laplaceSample","scale","prngState","u","crypto","addLaplaceNoise","value","config","merged","noisyValue","deriveFieldSensitivity","key","globalSensitivity","recordCount","lk","isCountWord","isTotalCount","applyDpToOutput","output","walkAndNoise","node","currentKey","fieldSensitivity","isCountKey","item","result","processLogicExecution","data","ciphertext","secretKeyObj","wasmBinary","inputs","aesNonce","records","isEncrypted","dpConfig","decryptedPayload","decryptedInputs","sessionSecret","Buffer","sk","ct","sharedSecret","createMlKem768","aesKey","wasmBuffer","authTag","encryptedData","decipher","decrypted","encValue","valBuffer","inputNonce","valTag","valData","valDecipher","valDecrypted","isWasm","wasmBytes","compiledModule","ASTGuardian","normalizeLogicSource","sandbox","WasiSandbox","finalOutput","logicBytes","imageId","deriveLogicImageDigest","datasetHash","journal","seal","journalLen","zkReceipt"],"mappings":"iLAqDA,IAAMA,CAAAA,CAA8B,CACnC,QAAS,CAAA,CACT,WAAA,CAAa,EACb,qBAAA,CAAuB,EACxB,EAOMC,CAAAA,CAAgB,CAAA,CAChBC,EAA0B,EAAA,CAyBhC,SAASC,EAAcC,CAAAA,CAAeC,CAAAA,CAA+B,CACpE,IAAIC,CAAAA,CACJ,GACKD,CAAAA,CAMHC,CAAAA,CALaC,EACX,UAAA,CAAW,QAAQ,EACnB,MAAA,CAAO,CAAA,EAAGF,CAA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AMqC,CAAAA,CAAQ,QAAA,GACf,CACD","file":"logic-execution.js","sourcesContent":["/**\n * LIOP Differential Privacy Engine — Laplace Mechanism (NIST SP 800-226)\n *\n * Applies calibrated Laplace noise to numeric query outputs,\n * providing ε-differential privacy guarantees against differencing\n * and binary search attacks (F-01, F-02 from security audit).\n *\n * Key design decisions (Phase 110 — Industrial Recalibration):\n * 1. CSPRNG: Uses crypto.randomBytes() instead of Math.random()\n * to prevent state-reconstruction attacks on the noise generator.\n * 2. Query-Aware Sensitivity: COUNT keys get sensitivity=1,\n * AVG keys get sensitivity/n, SUM keys use global config.\n * 3. Epsilon Floor: Auto-enforce ε≥1.0 for datasets with n<10\n * to prevent catastrophic utility destruction.\n *\n * Reference: Dwork & Roth 2014, \"The Algorithmic Foundations of Differential Privacy\"\n * Standards: NIST SP 800-226, Google DP Library, US Census TopDown, Apple iOS DP\n * Industry precedent: Apple (ε=2.0 Health, ε=8.0 Keyboard), US Census (ε=1.0–4.0)\n */\n\nimport crypto from \"node:crypto\";\n\n// ── Public Configuration ─────────────────────────────────────────────\n\nexport interface DpConfig {\n\t/**\n\t * Privacy budget per query (default: 1.0).\n\t * Lower = stronger privacy + more noise. Higher = weaker privacy + less noise.\n\t * Industry standard: Apple iOS Health uses ε=2.0, US Census uses ε=1.0–4.0.\n\t */\n\tepsilon: number;\n\t/**\n\t * Max change in output when one record is added/removed.\n\t * For SUM queries: set to the max plausible value of the field.\n\t * For COUNT queries: the engine automatically overrides to 1.\n\t * For AVG queries: the engine automatically divides by recordCount.\n\t * Default: 1.0 (appropriate for counts and ratios).\n\t */\n\tsensitivity: number;\n\t/**\n\t * Only apply DP noise when dataset size is below this threshold.\n\t * Large datasets have natural statistical privacy (k-anonymity).\n\t * Default: 50 (aligned with HIPAA Safe Harbor minimum).\n\t */\n\tsmallDatasetThreshold: number;\n\t/**\n\t * Optional deterministic seed (e.g., datasetHash + imageId).\n\t * Enables Deterministic Differential Privacy (DDP) for audit modes,\n\t * ensuring perfectly reproducible ZK-Receipts while preserving DP.\n\t */\n\tseed?: string;\n}\n\nconst DEFAULT_DP_CONFIG: DpConfig = {\n\tepsilon: 1.0,\n\tsensitivity: 1.0,\n\tsmallDatasetThreshold: 50,\n};\n\n/**\n * Minimum epsilon enforced for very small datasets (n < 10).\n * Apple's most sensitive category (Health Data) uses ε=2.0 on millions of records.\n * Using ε<1.0 on datasets with <10 records destroys utility completely.\n */\nconst EPSILON_FLOOR = 1.0;\nconst EPSILON_FLOOR_THRESHOLD = 10;\n\n// ── Core Laplace Mechanism ───────────────────────────────────────────\n\nexport interface PrngState {\n\tseed: string;\n\tcounter: number;\n}\n\n/**\n * Generates a sample from the Laplace(0, scale) distribution\n * using inverse CDF sampling with a CSPRNG source.\n *\n * SECURITY: Uses crypto.randomBytes() (OS-level entropy pool) instead of\n * Math.random() (Xorshift128+ PRNG). This prevents state-reconstruction\n * attacks where an adversary observing 3-5 noisy outputs could predict\n * all future noise values and strip the DP protection entirely.\n *\n * Deterministic Audit Mode: If prngState is provided, derives cryptographic\n * entropy using SHA-256 over the seed and an auto-incrementing counter,\n * guaranteeing ZK-Receipt determinism while retaining mathematical privacy.\n *\n * Reference: NIST SP 800-226 §3.2 — \"Implementations must use a CSPRNG\n * for noise generation to maintain the mathematical privacy guarantee.\"\n */\nfunction laplaceSample(scale: number, prngState?: PrngState): number {\n\tlet u: number;\n\tdo {\n\t\tif (prngState) {\n\t\t\tconst hash = crypto\n\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t.update(`${prngState.seed}:${prngState.counter++}`)\n\t\t\t\t.digest();\n\t\t\t// 4 bytes → Uint32 → uniform float in (-0.5, 0.5)\n\t\t\tu = hash.readUInt32BE(0) / 0x100000000 - 0.5;\n\t\t} else {\n\t\t\tconst buf = crypto.randomBytes(4);\n\t\t\tu = buf.readUInt32BE(0) / 0x100000000 - 0.5;\n\t\t}\n\t} while (u === 0 || u === -0.5); // Ensure no exactly 0 or -0.5 for log domain\n\treturn -scale * Math.sign(u) * Math.log(1 - 2 * Math.abs(u));\n}\n\n/**\n * Applies Laplace noise to a single numeric value.\n *\n * @param value - The true computed result\n * @param config - DP configuration (epsilon, sensitivity, seed)\n * @param prngState - Optional state tracking for deterministic sampling\n * @returns Noisy value with ε-differential privacy guarantee\n */\nexport function addLaplaceNoise(\n\tvalue: number,\n\tconfig: Partial<DpConfig> = {},\n\tprngState?: PrngState,\n): number {\n\tconst merged = { ...DEFAULT_DP_CONFIG, ...config };\n\tconst scale = merged.sensitivity / merged.epsilon;\n\tconst noisyValue = value + laplaceSample(scale, prngState);\n\t// Round to 4 decimal places to prevent long random digit strings\n\t// from triggering regex-based PII egress filters (e.g. phone numbers)\n\treturn Math.round(noisyValue * 10000) / 10000;\n}\n\n// ── Query-Aware Sensitivity ─────────────────────────────────────────\n\n/**\n * Derives field-level sensitivity based on key name semantics.\n *\n * This follows Google DP's architectural separation of CountParams,\n * SumParams, and MeanParams — each with independent sensitivity.\n *\n * Axioms (Dwork & Roth 2014):\n * - COUNT: Adding/removing one record changes count by at most 1.\n * - SUM: Adding/removing one record changes sum by at most max_value.\n * - AVG: Sensitivity = max_value / n (bounded contribution).\n *\n * @param key - Output field name (e.g., \"count\", \"avg_balance\", \"totalRevenue\")\n * @param globalSensitivity - Operator-configured max change per record\n * @param recordCount - Dataset size for average normalization\n */\nfunction deriveFieldSensitivity(\n\tkey: string | undefined,\n\tglobalSensitivity: number,\n\trecordCount: number,\n): number {\n\tif (!key) return globalSensitivity;\n\n\tconst lk = key.toLowerCase();\n\n\t// COUNT queries: sensitivity is ALWAYS 1 (fundamental DP axiom)\n\t// Match unambiguous count words: count, length, size, num (anywhere in key),\n\t// as well as common filter prefixes used in audits (nan_, negative_, positive_, null_, empty_, finite_, non_finite_).\n\t// \"total\" is ambiguous (\"totalRevenue\" = SUM, \"total\" or \"total_records\" = COUNT).\n\t// Only treat \"total\" as count when it IS the key or ends with a count suffix.\n\tconst isCountWord =\n\t\t/count|length|size|num|nan_|negative_|positive_|null_|empty_|finite_|non_finite_/i.test(\n\t\t\tlk,\n\t\t);\n\tconst isTotalCount =\n\t\tlk === \"total\" ||\n\t\tlk === \"n\" ||\n\t\tlk === \"total_records\" ||\n\t\t/total.*(count|items|entries|rows|records)/i.test(lk);\n\tif (isCountWord || isTotalCount) return 1;\n\n\t// AVERAGE queries: sensitivity = globalSensitivity / n\n\tif (/avg|mean|average/.test(lk) && recordCount > 0) {\n\t\treturn globalSensitivity / recordCount;\n\t}\n\n\t// SUM / unknown: use operator-configured sensitivity\n\treturn globalSensitivity;\n}\n\n// ── Output Walker ────────────────────────────────────────────────────\n\n/**\n * Recursively walks a JSON output object and applies Laplace noise\n * to all finite numeric leaf values. Non-numeric values (strings,\n * booleans, null) are preserved unchanged.\n *\n * IMPORTANT: This function NEVER mutates the input object.\n * It always returns a new object tree, preserving data integrity\n * of the original sandbox output for ZK-Receipt verification.\n *\n * @param output - The sandbox computation result\n * @param config - DP configuration (epsilon, sensitivity, threshold)\n * @param recordCount - Source dataset size (noise only if < threshold)\n * @returns New object with noisy numeric values (never mutates input)\n */\nexport function applyDpToOutput(\n\toutput: unknown,\n\tconfig: Partial<DpConfig> = {},\n\trecordCount: number,\n): unknown {\n\tconst merged = { ...DEFAULT_DP_CONFIG, ...config };\n\n\t// Large datasets have natural statistical privacy — skip noise\n\tif (recordCount >= merged.smallDatasetThreshold) {\n\t\treturn output;\n\t}\n\n\t// NIST SP 800-226: For very small datasets, enforce minimum epsilon\n\t// to prevent catastrophic utility destruction. Apple uses ε≥2.0 even\n\t// for health data on millions of records; using ε<1.0 on n<10 is\n\t// mathematically equivalent to random number generation.\n\tif (recordCount < EPSILON_FLOOR_THRESHOLD && merged.epsilon < EPSILON_FLOOR) {\n\t\tmerged.epsilon = EPSILON_FLOOR;\n\t}\n\n\tlet prngState: PrngState | undefined;\n\tif (merged.seed) {\n\t\tprngState = { seed: merged.seed, counter: 0 };\n\t}\n\n\treturn walkAndNoise(output, merged, recordCount, undefined, prngState);\n}\n\n/**\n * Internal recursive walker that applies noise to numeric leaves.\n * Handles: numbers, arrays, objects (arbitrary nesting depth).\n *\n * Uses query-aware sensitivity: COUNT keys → sensitivity=1,\n * AVG keys → sensitivity/n, SUM/unknown → global sensitivity.\n */\nfunction walkAndNoise(\n\tnode: unknown,\n\tconfig: DpConfig,\n\trecordCount: number,\n\tcurrentKey?: string,\n\tprngState?: PrngState,\n): unknown {\n\tif (typeof node === \"number\" && Number.isFinite(node)) {\n\t\t// Query-aware sensitivity per Google DP / NIST SP 800-226\n\t\tconst fieldSensitivity = deriveFieldSensitivity(\n\t\t\tcurrentKey,\n\t\t\tconfig.sensitivity,\n\t\t\trecordCount,\n\t\t);\n\t\tlet noisyValue = addLaplaceNoise(\n\t\t\tnode,\n\t\t\t{\n\t\t\t\t...config,\n\t\t\t\tsensitivity: fieldSensitivity,\n\t\t\t},\n\t\t\tprngState,\n\t\t);\n\n\t\t// Semantic heuristics to preserve structural invariants:\n\t\t// Reuse the same count-key detection logic as deriveFieldSensitivity\n\t\tconst isCountKey =\n\t\t\tcurrentKey != null &&\n\t\t\tderiveFieldSensitivity(currentKey, config.sensitivity, recordCount) === 1;\n\n\t\t// If original was an integer OR key suggests a count, force integer\n\t\t// (US Census TopDown: all counts must be non-negative integers)\n\t\tif (Number.isInteger(node) || isCountKey) {\n\t\t\tnoisyValue = Math.round(noisyValue);\n\t\t}\n\n\t\t// If original was non-negative, clamp to 0\n\t\t// (US Census TopDown: enforces non-negative constraint in post-processing)\n\t\tif (node >= 0) {\n\t\t\tnoisyValue = Math.max(0, noisyValue);\n\t\t}\n\n\t\treturn noisyValue;\n\t}\n\n\tif (Array.isArray(node)) {\n\t\t// Pass currentKey down for array items so they inherit semantics\n\t\treturn node.map((item) =>\n\t\t\twalkAndNoise(item, config, recordCount, currentKey, prngState),\n\t\t);\n\t}\n\n\tif (node !== null && typeof node === \"object\") {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(\n\t\t\tnode as Record<string, unknown>,\n\t\t)) {\n\t\t\tresult[key] = walkAndNoise(value, config, recordCount, key, prngState);\n\t\t}\n\t\treturn result;\n\t}\n\n\t// Strings, booleans, null — pass through unchanged\n\treturn node;\n}\n","import { Buffer } from \"node:buffer\";\nimport crypto from \"node:crypto\";\nimport { createMlKem768 } from \"mlkem\";\nimport {\n\tderiveLogicImageDigest,\n\tnormalizeLogicSource,\n} from \"../crypto/logic-image-id.js\";\nimport { ASTGuardian } from \"../sandbox/guardian.js\";\nimport { WasiSandbox } from \"../sandbox/wasi.js\";\nimport { applyDpToOutput } from \"../security/dp-engine.js\";\n\nexport interface WorkerData {\n\tciphertext: Uint8Array;\n\tsecretKeyObj: ArrayLike<number>;\n\tkyberPublicKey: Uint8Array;\n\twasmBinary: Uint8Array; // Can also be JS code in non-encrypted mode\n\tinputs: Record<string, Uint8Array>;\n\trecords?: Record<string, unknown>[];\n\tsessionToken: string;\n\tisEncrypted?: boolean;\n\taesNonce?: Uint8Array;\n\tdpConfig?: {\n\t\tepsilon: number;\n\t\tsensitivity: number;\n\t\tsmallDatasetThreshold: number;\n\t};\n}\n\nexport default async function processLogicExecution(data: WorkerData): Promise<{\n\timage_id: string;\n\toutput: unknown;\n\tfuel_consumed: number;\n\tzk_receipt?: string;\n}> {\n\tconst {\n\t\tciphertext,\n\t\tsecretKeyObj,\n\t\twasmBinary,\n\t\tinputs,\n\t\taesNonce,\n\t\trecords,\n\t\tisEncrypted = true,\n\t\tdpConfig,\n\t} = data;\n\n\tlet decryptedPayload: Buffer | string;\n\tconst decryptedInputs: Record<string, unknown> = {};\n\tlet sessionSecret = Buffer.alloc(32); // Fallback if plain text (no PQC)\n\n\tif (isEncrypted) {\n\t\t// 1. Decapsulate Kyber secret\n\t\tconst sk = new Uint8Array(secretKeyObj);\n\t\tconst ct = new Uint8Array(ciphertext);\n\t\tconst kem = await createMlKem768();\n\t\tconst sharedSecret = kem.decap(ct, sk);\n\t\tconst aesKey = Buffer.from(sharedSecret);\n\t\tsessionSecret = aesKey;\n\n\t\t// 2. Decrypt Main Payload (WASM/JS Code)\n\t\t// LIOP Serialization: Ciphertext = EncryptedData + 16-byte AuthTag\n\t\tconst wasmBuffer = Buffer.from(wasmBinary);\n\t\tconst authTag = wasmBuffer.subarray(-16);\n\t\tconst encryptedData = wasmBuffer.subarray(0, -16);\n\n\t\tconst decipher = crypto.createDecipheriv(\n\t\t\t\"aes-256-gcm\",\n\t\t\taesKey,\n\t\t\tBuffer.from(aesNonce || new Uint8Array(12)),\n\t\t);\n\t\tdecipher.setAuthTag(authTag);\n\t\tlet decrypted = decipher.update(encryptedData);\n\t\tdecrypted = Buffer.concat([decrypted, decipher.final()]);\n\t\tdecryptedPayload = decrypted;\n\n\t\t// 3. Decrypt Inputs\n\t\tfor (const [key, encValue] of Object.entries(inputs || {})) {\n\t\t\tconst valBuffer = Buffer.from(encValue);\n\t\t\t// Extract 12-byte prepended nonce, ciphertext, and 16-byte AuthTag\n\t\t\tconst inputNonce = valBuffer.subarray(0, 12);\n\t\t\tconst valTag = valBuffer.subarray(-16);\n\t\t\tconst valData = valBuffer.subarray(12, -16);\n\n\t\t\tconst valDecipher = crypto.createDecipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\taesKey,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tvalDecipher.setAuthTag(valTag);\n\t\t\tlet valDecrypted = valDecipher.update(valData);\n\t\t\tvalDecrypted = Buffer.concat([valDecrypted, valDecipher.final()]);\n\t\t\tdecryptedInputs[key] = JSON.parse(valDecrypted.toString(\"utf-8\"));\n\t\t}\n\t} else {\n\t\t// Transparent mode: payload is provided directly\n\t\t// If it's WASM (Magic bytes: \\0asm), keep as Buffer\n\t\tif (\n\t\t\twasmBinary[0] === 0x00 &&\n\t\t\twasmBinary[1] === 0x61 &&\n\t\t\twasmBinary[2] === 0x73 &&\n\t\t\twasmBinary[3] === 0x6d\n\t\t) {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary);\n\t\t} else {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary).toString(\"utf-8\");\n\t\t}\n\t}\n\n\t// 3. Inspect AST with Guardian-TS (if WASM)\n\tconst isWasm =\n\t\tdecryptedPayload[0] === 0x00 &&\n\t\tdecryptedPayload[1] === 0x61 &&\n\t\tdecryptedPayload[2] === 0x73 &&\n\t\tdecryptedPayload[3] === 0x6d;\n\n\tif (decryptedPayload instanceof Buffer && isWasm) {\n\t\t// Ensure we pass a compatible BufferSource\n\t\tconst wasmBytes = new Uint8Array(decryptedPayload);\n\t\tconst compiledModule = await WebAssembly.compile(wasmBytes);\n\t\tASTGuardian.analyze(compiledModule);\n\t} else if (decryptedPayload instanceof Buffer && !isWasm) {\n\t\tdecryptedPayload = decryptedPayload.toString(\"utf-8\");\n\t}\n\n\t// Strip only a whole-document LIOP envelope (see logic-image-id.ts).\n\tif (typeof decryptedPayload === \"string\") {\n\t\tdecryptedPayload = normalizeLogicSource(decryptedPayload);\n\t}\n\n\t// 4. Instantiate and Execute WASI Sandbox (or V8 Fallback)\n\tconst sandbox = new WasiSandbox();\n\tawait sandbox.init();\n\n\ttry {\n\t\tconst result = await sandbox.execute(\n\t\t\tdecryptedPayload,\n\t\t\trecords,\n\t\t\tdecryptedInputs,\n\t\t);\n\n\t\tlet finalOutput = result.output;\n\n\t\t// Pre-compute Image ID and Dataset Hash for Audit Trail & DP Seeding\n\t\tlet logicBytes: Uint8Array;\n\t\tif (typeof decryptedPayload === \"string\") {\n\t\t\tlogicBytes = Buffer.from(decryptedPayload, \"utf-8\");\n\t\t} else {\n\t\t\tlogicBytes = new Uint8Array(decryptedPayload);\n\t\t}\n\t\tconst imageId = deriveLogicImageDigest(logicBytes).toString(\"hex\");\n\n\t\t// Phase 110: Include dataset_hash for SOX audit trail compliance.\n\t\t// This SHA-256 anchor proves the underlying dataset was identical\n\t\t// across consecutive queries, separating DP noise from data mutation.\n\t\tconst datasetHash = crypto\n\t\t\t.createHash(\"sha256\")\n\t\t\t.update(JSON.stringify(records || []))\n\t\t\t.digest(\"hex\");\n\n\t\t// Apply Differential Privacy before committing to the ZK-Receipt\n\t\tif (dpConfig) {\n\t\t\tfinalOutput = applyDpToOutput(\n\t\t\t\tfinalOutput,\n\t\t\t\t{\n\t\t\t\t\t...dpConfig,\n\t\t\t\t\tseed: `${datasetHash}:${imageId}`,\n\t\t\t\t},\n\t\t\t\trecords?.length || 0,\n\t\t\t);\n\t\t}\n\n\t\t// 5. Generate Cryptographic Proof of Execution (HMAC-SHA256 Commitment)\n\n\t\tconst journal = Buffer.from(\n\t\t\tJSON.stringify({\n\t\t\t\timage_id: imageId,\n\t\t\t\tdataset_hash: datasetHash,\n\t\t\t\toutput_hash: crypto\n\t\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t\t.update(\n\t\t\t\t\t\ttypeof finalOutput === \"string\"\n\t\t\t\t\t\t\t? finalOutput\n\t\t\t\t\t\t\t: JSON.stringify(finalOutput),\n\t\t\t\t\t)\n\t\t\t\t\t.digest(\"hex\"),\n\t\t\t\tfuel: result.fuelConsumed,\n\t\t\t\tts: Date.now(),\n\t\t\t}),\n\t\t);\n\n\t\tconst seal = crypto\n\t\t\t.createHmac(\"sha256\", sessionSecret)\n\t\t\t.update(journal)\n\t\t\t.digest();\n\t\tconst journalLen = Buffer.alloc(2);\n\t\tjournalLen.writeUInt16BE(journal.length);\n\t\tconst receiptBuf = Buffer.concat([\n\t\t\tBuffer.from([0x01]), // Receipt format v1\n\t\t\tjournalLen,\n\t\t\tjournal,\n\t\t\tseal, // 32 bytes HMAC\n\t\t]);\n\t\tconst zkReceipt = receiptBuf.toString(\"base64\");\n\n\t\treturn {\n\t\t\timage_id: imageId,\n\t\t\tzk_receipt: zkReceipt,\n\t\t\toutput: finalOutput,\n\t\t\tfuel_consumed: result.fuelConsumed,\n\t\t};\n\t} finally {\n\t\tawait sandbox.teardown();\n\t}\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nekzus/liop",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.5",
|
|
4
4
|
"description": "Official SDK for Logic-Injection-on-Origin Protocol (LIOP). Deploy Logic-on-Origin with WebAssembly at gRPC speed and bidirectional MCP compatibility.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
package/dist/chunk-FW6CICSY.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import {a,b}from'./chunk-HM77MWB6.js';import {a as a$2}from'./chunk-PPCOS2NU.js';import {a as a$1}from'./chunk-S6RJHZV2.js';import {Buffer}from'buffer';import G from'crypto';import*as Z from'fs';import {createRequire}from'module';import w from'path';import {fileURLToPath,pathToFileURL}from'url';import*as W from'@grpc/grpc-js';import {Piscina,FixedQueue}from'piscina';import {z as z$1}from'zod';import {zodToJsonSchema}from'zod-to-json-schema';import*as z from'acorn';import {simple}from'acorn-walk';var J={"grpc.keepalive_time_ms":3e4,"grpc.keepalive_timeout_ms":1e4,"grpc.keepalive_permit_without_calls":1,"grpc.max_send_message_length":-1,"grpc.max_receive_message_length":-1,"grpc.enable_retries":1},T=class{server;constructor(){this.server=new W.Server(J);}addService(e){this.server.addService(a.LogicMesh.service,{NegotiateIntent:e.negotiateIntent,ExecuteLogic:e.executeLogic});}async listen(e=50051,t){let r=b(t);return new Promise((i,n)=>{this.server.bindAsync(`0.0.0.0:${e}`,r,(s,o)=>{if(s){n(s);return}a$1.info(`[LIOP-RPC] Server listening on port ${o}`),i(o);});})}async stop(){return new Promise(e=>{this.server.tryShutdown(()=>{a$1.info("[LIOP-RPC] Server shut down"),e();});})}};var A=class p{piiFields;static TAINT_PROPAGATING_METHODS=new Set(["charCodeAt","codePointAt","charAt","at","indexOf","lastIndexOf","search","localeCompare","startsWith","endsWith","includes","substring","slice","substr","split","match","matchAll","replace","replaceAll","normalize","toLowerCase","toUpperCase","trim","trimStart","trimEnd","padStart","padEnd","repeat"]);static ARRAY_CALLBACK_METHODS=new Set(["map","forEach","filter","find","some","every","flatMap","findIndex"]);static REDUCE_METHODS=new Set(["reduce","reduceRight"]);constructor(e){this.piiFields=new Set(e.map(t=>t.toLowerCase()));}analyze(e){let t;try{let n=`function liop_analysis_wrapper(env) {
|
|
2
|
-
${e}
|
|
3
|
-
}`;t=z.parse(n,{ecmaVersion:2022,sourceType:"script",locations:!0});}catch{return null}let r=new Set,i=new Set;return this.identifyRecordBoundVars(t,r),this.propagateTaint(t,r,i),this.checkReturnStatements(t,r,i)}identifyRecordBoundVars(e,t){simple(e,{CallExpression:n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isEnvRecordsAccess(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(p.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let l=c.params[0];l.type==="Identifier"&&t.add(l.name);}if(p.REDUCE_METHODS.has(o)&&c.params.length>1){let l=c.params[1];l.type==="Identifier"&&t.add(l.name);}}},ForOfStatement:n=>{if(this.isEnvRecordsAccess(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&t.add(s.id.name);}}),simple(e,{VariableDeclarator:n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isEnvRecordsAccess(s.object)&&t.add(n.id.name);}}});}propagateTaint(e,t,r){for(let i=0;i<3;i++){let n=r.size;if(simple(e,{VariableDeclarator:o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,t,r)&&r.add(o.id.name);},AssignmentExpression:o=>{o.left.type==="Identifier"&&this.isExpressionTainted(o.right,t,r)&&r.add(o.left.name);},CallExpression:o=>{if(o.callee.type!=="MemberExpression")return;let a=o.callee;this.getPropertyName(a)==="push"&&a.object.type==="Identifier"&&o.arguments.some(l=>this.isExpressionTainted(l,t,r))&&r.add(a.object.name);}}),r.size===n)break}}checkReturnStatements(e,t,r){let i=null;return simple(e,{ReturnStatement:s=>{if(!i&&s.argument&&this.isExpressionTainted(s.argument,t,r)){let o=s.loc?.start.line?s.loc.start.line-1:void 0,a=this.describeTaintSource(s.argument,t,r);i={reason:`PII side-channel detected: output contains values derived from restricted fields. ${a?`Operation: ${a}. `:""}Use only non-PII fields (e.g., numeric/date columns) for aggregations.`,line:o,operation:a};}}}),i}isExpressionTainted(e,t,r){switch(e.type){case "Identifier":return r.has(e.name);case "MemberExpression":return this.isMemberExprTainted(e,t,r);case "CallExpression":return this.isCallExprTainted(e,t,r);case "BinaryExpression":case "LogicalExpression":{let i=e;return this.isExpressionTainted(i.left,t,r)||this.isExpressionTainted(i.right,t,r)}case "UnaryExpression":{let i=e;return this.isExpressionTainted(i.argument,t,r)}case "ConditionalExpression":{let i=e;return this.isExpressionTainted(i.test,t,r)||this.isExpressionTainted(i.consequent,t,r)||this.isExpressionTainted(i.alternate,t,r)}case "ObjectExpression":return e.properties.some(n=>n.type==="Property"&&this.isExpressionTainted(n.value,t,r));case "ArrayExpression":return e.elements.some(n=>n!==null&&this.isExpressionTainted(n,t,r));case "TemplateLiteral":return e.expressions.some(n=>this.isExpressionTainted(n,t,r));case "SpreadElement":{let i=e;return this.isExpressionTainted(i.argument,t,r)}default:return false}}isMemberExprTainted(e,t,r){let i=this.getPropertyName(e);if(e.object.type==="Identifier"&&t.has(e.object.name)&&i&&this.piiFields.has(i.toLowerCase()))return true;if(e.object.type==="MemberExpression"&&i&&this.piiFields.has(i.toLowerCase())){let n=e.object;if(n.computed&&this.isEnvRecordsAccess(n.object))return true}if(this.isExpressionTainted(e.object,t,r))return true;if(e.computed&&e.object.type==="Identifier"&&t.has(e.object.name)&&e.property.type==="Literal"){let n=e.property.value;if(typeof n=="string"&&this.piiFields.has(n.toLowerCase()))return true}return false}isCallExprTainted(e,t,r){if(e.callee.type==="MemberExpression"){let i=e.callee,n=this.getPropertyName(i);if(n&&p.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,t,r))return true;if(this.isEnvRecordsAccess(i.object)&&e.arguments[0]){let s=e.arguments[0];if(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")return this.doesCallbackProduceTaint(s,n,t,r)}if(this.isExpressionTainted(i.object,t,r)||e.arguments.some(s=>this.isExpressionTainted(s,t,r)))return true}if(e.callee.type==="MemberExpression"){let i=e.callee;this.getPropertyName(i)==="push"&&i.object.type==="Identifier"&&e.arguments.some(s=>this.isExpressionTainted(s,t,r))&&r.add(i.object.name);}if(e.callee.type==="Identifier"){let i=e.callee.name;if(!new Set(["Math","Number","parseInt","parseFloat","isNaN","isFinite"]).has(i))return e.arguments.some(s=>this.isExpressionTainted(s,t,r))}return false}doesCallbackProduceTaint(e,t,r,i){let n=new Set(r),s=new Set(i);if(e.params.length>0){let l=t!==null&&p.REDUCE_METHODS.has(t)?1:0;e.params.length>l&&e.params[l].type==="Identifier"&&n.add(e.params[l].name);}if(e.type==="ArrowFunctionExpression"&&e.body.type!=="BlockStatement")return this.isExpressionTainted(e.body,n,s);let o=false,a={ReturnStatement:c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);}};return simple(e.body,a),o}getPropertyName(e){if(!e.computed&&e.property.type==="Identifier")return e.property.name;if(e.computed&&e.property.type==="Literal"){let t=e.property.value;if(typeof t=="string")return t}return null}isEnvRecordsAccess(e){if(e.type==="MemberExpression"){let t=e;if(this.getPropertyName(t)==="records"&&t.object.type==="Identifier"&&t.object.name==="env")return true}return e.type==="Identifier"&&e.name==="records"}describeTaintSource(e,t,r){if(e.type==="Identifier"){let i=e.name;if(r.has(i))return `variable '${i}' is PII-derived`}if(e.type==="ObjectExpression"){let i=e;for(let n of i.properties)if(n.type==="Property"&&this.isExpressionTainted(n.value,t,r))return `property '${n.key.type==="Identifier"?n.key.name:"unknown"}' contains PII-derived value`}if(e.type==="CallExpression"){let i=e;if(i.callee.type==="MemberExpression"){let n=this.getPropertyName(i.callee);if(n)return `result of .${n}() on PII data`}}}};var B={aspirin:"Medication",lisinopril:"Medication",metformin:"Medication",amlodipine:"Medication",atorvastatin:"Medication",omeprazole:"Medication",losartan:"Medication",simvastatin:"Medication",levothyroxine:"Medication",ibuprofen:"Medication",acetaminophen:"Medication",amoxicillin:"Medication",ciprofloxacin:"Medication",prednisone:"Medication",warfarin:"Medication",insulin:"Medication",hydrochlorothiazide:"Medication",gabapentin:"Medication",albuterol:"Medication",pantoprazole:"Medication",hypertension:"Condition",diabetes:"Condition",bronchitis:"Condition",pneumonia:"Condition",asthma:"Condition"},_=4,V=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,N=class p{static nlp=null;async getNlp(){if(!p.nlp){let e=await import('compromise/three');p.nlp=e.default||e,p.nlp.addWords(B);}return p.nlp}async scan(e){if(e.length<_||V.test(e))return {detected:false,entities:[]};let r=(await this.getNlp())(e),i=[],n=r.people().out("array");for(let a of n){let c=a.trim();c.length>=_&&i.push({type:"person",text:c});}let s=r.places().out("array");for(let a of s){let c=a.trim();c.length>=_&&i.push({type:"place",text:c});}let o=r.organizations().out("array");for(let a of o){let c=a.trim();c.length>=_&&i.push({type:"organization",text:c});}return {detected:i.length>0,entities:i}}async scanDeep(e,t=new WeakSet){if(e==null)return {detected:false,entities:[]};if(typeof e=="string")return this.scan(e);if(typeof e=="object"){if(t.has(e))return {detected:false,entities:[]};t.add(e);let r=Array.isArray(e)?e:Object.values(e),i=[];for(let n of r){let s=await this.scanDeep(n,t);if(s.detected&&(i.push(...s.entities),s.entities.some(o=>o.type==="person")))return {detected:true,entities:i}}return {detected:i.length>0,entities:i}}return {detected:false,entities:[]}}};function X(p){let e=p.replace(/\D/g,"");if(e.length<13||e.length>19)return false;let t=0,r=false;for(let i=e.length-1;i>=0;i--){let n=parseInt(e.charAt(i),10);r&&(n*=2,n>9&&(n-=9)),t+=n,r=!r;}return t%10===0}function Q(p){let e=p.replace(/\s+/g,"").toUpperCase();if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/.test(e))return false;let t=e.substring(4)+e.substring(0,4),r="";for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);if(n>=65&&n<=90)r+=(n-55).toString();else if(n>=48&&n<=57)r+=t.charAt(i);else return false}try{return BigInt(r)%97n===1n}catch{return false}}var d={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:p=>!p.endsWith("@example.com")&&!p.endsWith("@test.com")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:X},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:p=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(p)?false:p.split(".").map(Number).every(r=>r>=0&&r<=255)},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:p=>{let e=p.replace(/\D/g,"");return !(e.length<7||e.length>15||/^(\d)\1+$/.test(e)||e==="1234567890")}},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:p=>{let e=p.replace(/\D/g,"");if(e.length!==9)return false;let t=parseInt(e.substring(0,3),10);return !(t===0||t===666||t>=900||parseInt(e.substring(3,5),10)===0||parseInt(e.substring(5,9),10)===0||/^(\d)\1+$/.test(e)||e==="123456789")}},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:Q},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},H={GLOBAL_STRICT:[d.EMAIL,d.CREDIT_CARD,d.IP_ADDRESS,d.PHONE,d.PASSPORT_MRZ,d.IBAN],US_COMPLIANT:[d.EMAIL,d.CREDIT_CARD,d.IP_ADDRESS,d.PHONE,d.SSN,d.PASSPORT_MRZ],EU_GDPR:[d.EMAIL,d.CREDIT_CARD,d.IP_ADDRESS,d.PHONE,d.IBAN,d.PASSPORT_MRZ]},O=class p{patterns;forbiddenKeysSet;nerScanner;static KEY_SAFELIST=new Set(["grid","video","android","identity","provide","override","validate","hidden","widget","guidelines","beside","guideline","outside","inside","collide","decide","divide","aside","ride","side","wide","hide","tide","pride","bride","slide","guide","stride","oxide","dioxide","suicide","homicide","pesticide","valid","invalid","void","avoid","diagnosis","medication","namespace","namesake","rename","filename","hostname","typename","unnamed","renamed","phonetic","phoneme","microphone","headphone","telephone","saxophone","smartphone","streetview","addressable","addressing","cityscape","electricity","capacity","velocity","opacity","timestamp","timezone","image_id","computation_result","zk_receipt","testid","toolid","sessionid","peerid","nodeid","requestid","correlationid","traceid","spanid"]);shortTokenBoundaryPatterns;longForbiddenTokens;constructor(e=[],t=[],r){this.patterns=e,this.forbiddenKeysSet=new Set(t.map(i=>i.toLowerCase())),this.nerScanner=r??null,this.shortTokenBoundaryPatterns=new Map,this.longForbiddenTokens=[];for(let i of this.forbiddenKeysSet)i.length<4?this.shortTokenBoundaryPatterns.set(i,new RegExp(`(?:^|[_-])${i}(?:$|[_-])|(?:^|[a-z])${i.charAt(0).toUpperCase()}${i.slice(1)}|^${i}$`,"i")):this.longForbiddenTokens.push(i);}async scan(e,t=new WeakSet){if(e==null)return null;if(typeof e=="string"){let r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{let n=JSON.parse(r),s=await this.scan(n,t);if(s)return s}catch{}let i=this.checkString(e);if(i)return i;if(this.nerScanner){let n=await this.nerScanner.scan(e);if(n.detected){let s=n.entities.find(o=>o.type==="person");if(s)return `PII Entity Detected: person name "${s.text}"`}}return null}if(typeof e=="object"){if(t.has(e))return null;if(t.add(e),Array.isArray(e))for(let r of e){let i=await this.scan(r,t);if(i)return i}else for(let[r,i]of Object.entries(e)){if(this.forbiddenKeysSet.has(r.toLowerCase()))return `Forbidden Key: ${r}`;let n=this.checkKeyFuzzy(r);if(n)return n;let s=await this.scan(i,t);if(s)return s}}return null}checkKeyFuzzy(e){let t=e.toLowerCase();if(p.KEY_SAFELIST.has(t))return null;for(let[r,i]of this.shortTokenBoundaryPatterns)if(i.test(e))return `Forbidden Key (fuzzy): ${e} matches boundary pattern "${r}"`;for(let r of this.longForbiddenTokens)if(t.includes(r))return `Forbidden Key (fuzzy): ${e} contains restricted token "${r}"`;return null}checkString(e){for(let t of this.patterns)if(typeof t=="string"){if(e.toLowerCase().includes(t.toLowerCase()))return t}else if(t instanceof RegExp){if(t.global&&(t.lastIndex=0),t.test(e))return t.source}else if(typeof t=="object"&&t!==null){let r=t;if(typeof r.pattern=="string"){if(e.toLowerCase().includes(r.pattern.toLowerCase())&&(!r.validator||r.validator(r.pattern)))return r.name}else if(r.pattern instanceof RegExp){r.pattern.global&&(r.pattern.lastIndex=0);let i=r.pattern.exec(e);for(;i!==null;){let n=i[0];if(!r.validator||r.validator(n))return r.name;if(!r.pattern.global)break;i=r.pattern.exec(e);}}}return null}};var U=w.dirname(fileURLToPath(import.meta.url)),K=class p{constructor(e,t){this.serverInfo=e;this.config=t;let r=this.config?.security?.enableNerScanning?new N:null;this.piiScanner=new O(this.config?.security?.piiPatterns??H.GLOBAL_STRICT,this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],r);let i=this.config?.security?.rateLimit;this.toolCallWindowMs=i?.windowMs??Number.parseInt(process.env.LIOP_RATE_LIMIT_WINDOW_MS??"60000",10),this.toolCallMaxPerWindow=i?.maxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_MAX??"15",10),this.globalCallMaxPerWindow=i?.globalMaxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_GLOBAL_MAX??"40",10);let n=this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"];this.taintAnalyzer=new A(n);let s=import.meta.url.endsWith(".ts"),o=s?".ts":".js",a=[];if(s)try{let h=createRequire(import.meta.url).resolve("tsx/package.json");a=["--import",pathToFileURL(w.join(w.dirname(h),"dist","loader.mjs")).href];}catch{a=["--import","tsx"];}let c=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let l=[w.resolve(U,`./workers/logic-execution${o}`),w.resolve(U,`../workers/logic-execution${o}`)],u=l.find(g=>Z.existsSync(g))||l[1];this.workerPool=new Piscina({filename:u,minThreads:this.config?.workerPool?.minThreads??(c?0:2),maxThreads:this.config?.workerPool?.maxThreads??(c?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(c?500:5e3),maxQueue:"auto",taskQueue:new FixedQueue,execArgv:a,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}}),this.resource("LIOP Envelope Specification","liop://protocol/envelope-spec","Complete Logic-on-Origin envelope format, execution rules, and security constraints","text/plain",()=>Promise.resolve(this.buildEnvelopeSpec()));}logicCache=new Map;connectionStats=new Map;CACHE_TTL_MS=1440*60*1e3;THROTTLE_THRESHOLD=5;THROTTLE_COOLDOWN_MS=60*1e3;toolCallWindows=new Map;toolCallMaxPerWindow;toolCallWindowMs;globalCallWindow=[];globalCallMaxPerWindow;taintAnalyzer;tools=new Map;resources=new Map;prompts=new Map;activeSchema=null;sandboxRecords=[];piiScanner;workerPool;meshNode=null;rpcServer=null;boundPort=null;sessions=new Map;static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,(?<name>[^}]*))?\}\n(?<logic>[\s\S]*?)\n@END/m;extractLogic(e){let t=e.match(p.LIOP_COMPACT_REGEX);return t?.groups?.logic?t.groups.logic.trim():null}parseUnknownJson(e){if(typeof e!="string")return e;let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}runPreflightPolicy(e,t,r){if(r){let n=t.replace(/\s+/g," ");if(r.enforceAggregationFirst&&[/return\s+env\.records(?!\s*\.\s*(?:reduce|length|filter|every|some|find)\b)/i,/return\s*\{[\s\S]*\b(accounts|patients|rows|records)\s*:\s*env\.records(?!\s*\.\s*(?:reduce|length|filter)\b)/i].some(o=>o.test(n)))return "Preflight policy rejected: potential row-level export pattern detected.";if(r.preflightDenyPatterns?.some(s=>s.test(n)))return "Preflight policy rejected: custom deny pattern matched."}let i=this.taintAnalyzer.analyze(t);return i?`Preflight policy rejected: ${i.reason}`:null}validateOutputPolicy(e,t,r){if(!r)return null;let i=this.parseUnknownJson(t);if(r.outputSchema){let s=(()=>{if(!(r.outputSchema instanceof z$1.ZodObject))return r.outputSchema;let o=r.outputSchema;return o._def.catchall instanceof z$1.ZodNever?o.strict():o})().safeParse(i);if(!s.success)return `[LIOP] Output schema violation for ${e}: ${s.error.issues.map(o=>`${o.path.join(".")||"<root>"} ${o.message}`).join("; ")}. HINT: Your output must conform to the declared schema. Use 'env.records' to access the dataset and return only allowed fields.`}return r.enforceAggregationFirst&&this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(i),r.enforceAggregationFirst,this.sandboxRecords.length)?process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?"Aggregation-First Policy Violation: row-level export or K-Anonymity violation blocked. HINT: Use .reduce() to produce a flat {key:value} object. Do NOT use .map() to create arrays of objects. Ensure dataset size > 10 for detailed results.":"Aggregation-First Policy Violation: Output blocked due to privacy constraints.":null}unwrapForAggregationPolicyScan(e){if(typeof e=="string"){let n=e.trim();if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{return this.unwrapForAggregationPolicyScan(JSON.parse(n))}catch{return e}return e}if(!e||typeof e!="object")return e;let t=e;if(!Array.isArray(t.content)||t.content.length===0)return e;let r=[];for(let n of t.content)if(n&&typeof n=="object"&&"text"in n){let s=n.text;typeof s=="string"&&r.push(s);}if(r.length===0)return e;let i=r.length===1?r[0]:r.join(`
|
|
4
|
-
`);return this.unwrapForAggregationPolicyScan(i)}violatesAggregationFirstPolicy(e,t,r){let i=typeof t=="object"&&typeof t.maxOutputRows=="number"?t.maxOutputRows:10,n=typeof t=="object"&&typeof t.allowPrimitiveArrays=="boolean"?t.allowPrimitiveArrays:true;if(typeof e=="string"){let s=e.trim();if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{return this.violatesAggregationFirstPolicy(JSON.parse(s),t,r)}catch{return false}return false}if(Array.isArray(e))return e.length>0&&e.every(s=>typeof s=="object"&&s!==null)?e.length>i?true:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r)):e.length>0&&e.every(s=>typeof s!="object"||s===null)?!n:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r));if(e&&typeof e=="object"){let s=Object.keys(e);return r!==void 0&&r>0&&r<10&&(s.length>3||Object.values(e).some(a=>Array.isArray(a)||typeof a=="object"&&a!==null))||s.length>i?true:Object.values(e).some(o=>this.violatesAggregationFirstPolicy(o,t,r))}return false}buildEnvelopeSpec(){let e=["LIOP v1 Envelope Specification","================================","","FORMAT:","","Compact Envelope:"," @LIOP{wasi_v1,TaskName}"," <JavaScript code>"," @END","","RUNTIME ENVIRONMENT:","- env.records: Array of data objects from the origin","- Must use 'return' to output results","- Zero-Trust WASI Sandbox (Node.js Worker Pool)","- Return aggregated objects, NOT raw row-level arrays","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution"];return this.config?.security?.forbiddenKeys?.length&&e.push(`- Restricted fields: ${this.config.security.forbiddenKeys.join(", ")}`),e.push("","TAINT TRACKING (Phase 108):","- AST-level analysis blocks PII-derived scalars (charCodeAt, charAt, etc.)","- Operations on restricted fields are tracked through variable assignments","- Boolean inference (field.charCodeAt(0) < N ? 1 : 0) is blocked","- Allowed: aggregations on non-PII fields (balance, amount, date)","","K-ANONYMITY:","- Datasets < 10 records: max 3 scalar output fields, no nesting","- Datasets >= 10 records: max 10 output fields","","RATE LIMITS (OWASP A01):","- Per-tool: 15 calls/min (configurable via LIOP_RATE_LIMIT_MAX)","- Global: 40 calls/min across all tools (LIOP_RATE_LIMIT_GLOBAL_MAX)","","OPTIONAL PARAMETERS:","- __liop_bypass_ast_cache: boolean (force AST re-evaluation)"),e.join(`
|
|
5
|
-
`)}extractSchemaFieldSummary(e,t=0){if(t>3)return "{...}";let r=e.type,i=e.properties,n=e.items;return i?`{${Object.entries(i).map(([o,a])=>{let c=a.type;if(c==="array"&&a.items){let l=this.extractSchemaFieldSummary(a.items,t+1);return `${o}(array of ${l})`}if(c==="object"&&a.properties){let l=this.extractSchemaFieldSummary(a,t+1);return `${o}(${l})`}return `${o}(${c||"unknown"})`}).join(", ")}}`:r==="array"&&n?`Array of ${this.extractSchemaFieldSummary(n,t+1)}`:r||Object.keys(e).join(", ")}async connect(e={}){return this.connectToMesh(e)}tool(e,t,r,i,n){if(this.tools.has(e))throw new Error(`Tool already registered: ${e}`);let s=z$1.object(r),o=zodToJsonSchema(s),a=t,c=i;if(r.payload&&r.payload instanceof z$1.ZodString){let u=this.config?.security?.forbiddenKeys||[];if(a+=`
|
|
6
|
-
|
|
7
|
-
Payload: LIOP v1 envelope (WASI sandbox). Format: @LIOP{wasi_v1,TaskName}\\n<JS code>\\n@END | Access data: env.records. Return aggregated object. | Full spec: resource liop://protocol/envelope-spec`,u.length>0&&(a+=`
|
|
8
|
-
Restricted fields: ${u.join(", ")}.`),this.activeSchema){let g=this.extractSchemaFieldSummary(this.activeSchema);a+=`
|
|
9
|
-
Data structure: ${g}. Full schema: resource liop://schema/global`;}c=async(g,h)=>{let y="global_connection",b=Date.now(),m=this.connectionStats.get(y)||{failures:0,lastAttempt:0};if(m.failures>=this.THROTTLE_THRESHOLD&&b-m.lastAttempt<this.THROTTLE_COOLDOWN_MS)return {content:[{type:"text",text:"LIOP_THROTTLED: Too many violations. Cooling down for 60 seconds."}],isError:true};let M=g.payload,Y=g.__liop_bypass_ast_cache===true,L=G.createHash("sha256").update(M).digest("hex"),S=this.extractLogic(M),C=this.logicCache.get(L);if(!Y&&C&&b-C.timestamp<this.CACHE_TTL_MS&&S){g.payload=S;let v=this.runPreflightPolicy(e,S,n);return v?{content:[{type:"text",text:v}],isError:true}:await this.executeInWorkerPool(g,S,e)}if(!S)return m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:"Error: Malformed payload. Missing @LIOP boundary.\\nYou MUST wrap your logic exactly like this:\\n\\n@LIOP{wasi_v1,DynamicAudit}\\n// Your JS code here\\n@END"}],isError:true};try{let v=this.extractLogic(g.payload);g.payload=v;let R=this.runPreflightPolicy(e,v,n);if(R)return m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:R}],isError:!0};let D=await this.executeInWorkerPool(g,v,e);return D.isError?(m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m)):(this.connectionStats.set(y,{failures:0,lastAttempt:b}),this.logicCache.set(L,{hash:L,timestamp:b})),D}catch(v){let R=v;return m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:`ExecutionRuntimeException: ${R.message}`}],isError:true}}};}let l={type:"object",properties:o.properties||{},required:o.required};this.tools.set(e,{tool:{name:e,description:a,inputSchema:l},handler:c,schema:s,policy:n}),this.meshNode&&this.meshNode.announceCapability(e).catch(u=>{a$1.info(`[LIOP-Mesh] Failed to auto-announce tool ${e}: ${u.message}`);});}prompt(e,t,r,i){if(this.prompts.has(e))throw new Error(`Prompt already registered: ${e}`);this.prompts.set(e,{prompt:{name:e,description:t,arguments:r},handler:i});}enableZeroShotAutonomy(){this.prompt("liop_blind_analyst","The official Logic-Injection-on-Origin Protocol system prompt. Instructs the LLM on how to securely inject Logic-on-Origin without violating PII or safety constraints.",[],e=>({description:"LIOP Blind Analyst Instructions",messages:[{role:"user",content:{type:"text",text:`You are the "Blind Analyst" operating within the Logic-Injection-on-Origin Protocol (LIOP) ecosystem.
|
|
10
|
-
Your objective is to perform secure Logic-on-Origin injections. You must process remote data without ever requesting its extraction.
|
|
11
|
-
|
|
12
|
-
INDUSTRIAL CONSTRAINTS & PROTOCOL RULES:
|
|
13
|
-
1. DATA PRIVACY: NEVER attempt to export Personally Identifiable Information (PII). The LIOP Egress Shield will block any response containing raw IDs, names, or addresses.
|
|
14
|
-
2. AGGREGATION FIRST: Always prefer returning counts, averages, or anonymized summaries.
|
|
15
|
-
3. PAYLOAD ENCAPSULATION: Your JavaScript payloads MUST strictly adhere to the Compact Envelope. DO NOT include markdown backticks or leading text inside the 'payload' argument.
|
|
16
|
-
Structure:
|
|
17
|
-
@LIOP{wasi_v1,AnalysisTask}
|
|
18
|
-
// Your JS Code Here
|
|
19
|
-
@END
|
|
20
|
-
4. RUNTIME SCOPE: The execution environment provides a global 'env' object. Use 'env.records' to access the target dataset.
|
|
21
|
-
5. LOCALIZATION: Format all JSON response keys in the language used by the user in their query (e.g., use Spanish keys if the query is in Spanish).
|
|
22
|
-
6. SCHEMA RIGIDITY: Only use fields defined in the 'Data Dictionary'. Usage of non-existent fields will trigger a sandbox runtime exception.${this.activeSchema?`
|
|
23
|
-
|
|
24
|
-
CURRENT DATA DICTIONARY (STRICT):
|
|
25
|
-
${JSON.stringify(this.activeSchema,null,2)}`:""}
|
|
26
|
-
|
|
27
|
-
Protocol Adherence is mandatory for successful execution.`}}]}));}resource(e,t,r,i,n){if(this.resources.has(t))throw new Error(`Resource URI already registered: ${t}`);this.resources.set(t,{name:e,uri:t,description:r,mimeType:i,content:n});}dataDictionary(e,t="Global Medical Data Dictionary",r="liop://schema/global",i="Exposes the internal database schema for Zero-Shot Autonomy planning"){this.activeSchema=e;let n=this.extractSchemaFieldSummary(e);for(let[s,o]of this.tools.entries())o.schema.shape.payload&&o.schema.shape.payload instanceof z$1.ZodString&&o.tool.description&&!o.tool.description.includes("Data structure:")&&(o.tool.description+=`
|
|
28
|
-
Data structure: ${n}. Full schema: resource ${r}`,this.tools.set(s,o));this.resource(t,r,i,"application/json",JSON.stringify(e,null,2));}clearAstCache(){this.logicCache.clear(),a$1.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(e){let t=Date.now(),r=this.toolCallWindowMs,i=this.toolCallMaxPerWindow,s=(this.toolCallWindows.get(e)||[]).filter(o=>t-o<r);if(s.length>=i){let o=Math.ceil((s[0]+r-t)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${e}. Max ${i} per ${r/1e3}s window. Retry after ${o}s.`}],isError:true}}return s.push(t),this.toolCallWindows.set(e,s),null}checkGlobalRateLimit(){let e=Date.now(),t=this.toolCallWindowMs,r=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(i=>e-i<t),this.globalCallWindow.length>=r){let i=Math.ceil((this.globalCallWindow[0]+t-e)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${r} total calls per ${t/1e3}s window. Retry after ${i}s.`}],isError:true}}return this.globalCallWindow.push(e),null}async callTool(e){let t=this.tools.get(e.name);if(!t)throw new Error(`Tool not found: ${e.name}`);let r=this.checkGlobalRateLimit();if(r)return r;let i=this.checkToolCallRateLimit(e.name);if(i)return i;try{let n=t.schema.parse(e.arguments||{});if(e.arguments?.__liop_bypass_ast_cache===!0&&(n.__liop_bypass_ast_cache=!0),n&&typeof n.payload=="string"){let o=n.payload,a=this.extractLogic(o);if(a){let c=this.runPreflightPolicy(e.name,a,t.policy);return c?{content:[{type:"text",text:c}],isError:!0}:(n.payload=a,await this.executeInWorkerPool(n,a,e.name))}}return await t.handler(n,{})}catch(n){let s=n;return s instanceof z$1.ZodError?{content:[{type:"text",text:`Validation Error: ${s.message}`}],isError:true}:{content:[{type:"text",text:`Internal Execution Error: ${s.message}`}],isError:true}}}listTools(){return Array.from(this.tools.values()).map(e=>e.tool)}listPrompts(){return Array.from(this.prompts.values()).map(e=>e.prompt)}async getPrompt(e){let t=this.prompts.get(e.name);if(!t)throw new Error(`Prompt not found: ${e.name}`);return await t.handler(e)}listResources(){return Array.from(this.resources.values())}async readResource(e){let t=this.resources.get(e);if(!t)throw new Error(`Resource not found: ${e}`);let r="No description provided";return typeof t.content=="function"?r=await t.content():typeof t.content=="string"?r=t.content:t.description&&(r=t.description),{contents:[{uri:t.uri,mimeType:t.mimeType||"text/plain",text:r}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(e){this.sandboxRecords=e;}getBoundPort(){return this.boundPort}async connectToMesh(e={}){let t=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,r=e.port??t??50051;this.meshNode=new a$2(e.meshConfig),await this.meshNode.start();let i=this.meshNode;this.meshNode.registerManifestHandler(()=>{let n=this.listTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema})),s=Array.from(this.resources.values()).map(o=>({name:o.name,uri:o.uri,description:o.description,mimeType:o.mimeType,text:typeof o.content=="string"?o.content:o.description}));return {peerId:i.getPeerId(),grpcPort:r,tools:n,resources:s,serverInfo:this.serverInfo}});for(let n of this.listTools())await this.meshNode.announceCapability(n.name).catch(a$1.info);await this.meshNode.announceManifest().catch(a$1.info),this.rpcServer=new T,this.rpcServer.addService({negotiateIntent:(n,s)=>{let o=n.request;a$1.info(`[LIOP-RPC] Negotiating intent for capability: ${o.capability_hash}`),import('./kyber-2WDOTUQX.js').then(async({Kyber768Wrapper:a})=>{let{publicKey:c,secretKey:l}=await a.generateKeyPair(),u=G.randomUUID();this.sessions.set(u,{capability_hash:o.capability_hash,kyber_sk:l}),s(null,{accepted:true,session_token:u,error_message:"",kyber_public_key:c});});},executeLogic:async n=>{let s=n.request;a$1.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${s.session_token}`);let o=this.sessions.get(s.session_token);if(!o){n.emit("error",{code:W.status.UNAUTHENTICATED,details:"Invalid session token"});return}try{let a=await this.workerPool.run({ciphertext:s.pqc_ciphertext,secretKeyObj:Array.from(o.kyber_sk),wasmBinary:s.wasm_binary,inputs:s.inputs,aesNonce:s.aes_nonce,records:this.sandboxRecords,sessionToken:s.session_token,isEncrypted:!0}),c;try{c=typeof a.output=="string"?a.output:JSON.stringify(a.output);let h=JSON.parse(c);if(h.__liop_proxy_tool){a$1.info(`[LIOP-RPC] Executing Proxied Tool: ${h.__liop_proxy_tool}`);let y=await this.callTool({name:h.__liop_proxy_tool,arguments:h.__liop_proxy_args||{}});c=JSON.stringify(y);}}catch{c=String(a.output);}let l={semantic_evidence:c,cryptographic_proof:Buffer.from(a.image_id||"","hex"),zk_receipt:a.zk_receipt?Buffer.from(a.zk_receipt,"base64"):Buffer.from(""),is_error:!1},u=await this.piiScanner.scan([{type:"text",text:c}]),g=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(c));if(u||g){let h=u||"Aggregation-First Policy Violation";a$1.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${h}`),l.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",l.is_error=!0;}n.write(l,()=>{n.end();});}catch(a){let c=a,l=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",u=c.message||String(a);a$1.error(`[LIOP-RPC] Execution Error: ${u}`);let h={semantic_evidence:l?`Execution Error: ${u}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{n.write(h,()=>{n.end();});}catch{n.end();}}}}),this.boundPort=await this.rpcServer.listen(r),a$1.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(e,t,r){try{let i=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(t),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1}),s=[{type:"text",text:JSON.stringify({computation_result:i.output,image_id:i.image_id,zk_receipt:i.zk_receipt,status:"Worker Pool Execution Success"})}],o=r?this.tools.get(r)?.policy:void 0,a=this.validateOutputPolicy(r||"unknown_tool",i.output,o);if(a)return a$1.info(`[LIOP-SDK] Output policy blocked for ${r||"unknown_tool"}: ${a}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?a:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let c=await this.piiScanner.scan(s),l=this.violatesAggregationFirstPolicy(i.output);if(c||l){let u=c||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return a$1.info(`[LIOP-SDK] Secure egress blocked in local execution: ${u}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${u}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:s}}catch(i){let n=i,s=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1",o=n.message||String(i);return a$1.error(`[LIOP-SDK] WorkerPool Execution Fault: ${o}`),{content:[{type:"text",text:s?`WorkerPoolError: ${o}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error."}],isError:true}}}async close(){this.workerPool&&await this.workerPool.close({force:true}),this.rpcServer&&await this.rpcServer.stop(),this.meshNode&&await this.meshNode.stop();}};export{T as a,N as b,d as c,H as d,O as e,K as f};//# sourceMappingURL=chunk-FW6CICSY.js.map
|
|
29
|
-
//# sourceMappingURL=chunk-FW6CICSY.js.map
|