@nekzus/liop 2.0.1-beta.1 → 2.1.0-alpha.2
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 +39 -11
- package/dist/bin/agent.js +1 -1
- package/dist/bridge.d.ts +1 -1
- package/dist/bridge.js +1 -1
- package/dist/{chunk-L5A64CNT.js → chunk-CXMVL5IW.js} +18 -18
- package/dist/chunk-CXMVL5IW.js.map +1 -0
- package/dist/{chunk-YZVCAJJO.js → chunk-GI2LSJYZ.js} +3 -3
- package/dist/{chunk-YZVCAJJO.js.map → chunk-GI2LSJYZ.js.map} +1 -1
- package/dist/{chunk-VGXNGTIC.js → chunk-I46YEWND.js} +7 -7
- package/dist/chunk-I46YEWND.js.map +1 -0
- package/dist/{chunk-W2QGWRTT.js → chunk-I7OTWNFM.js} +3 -3
- package/dist/{chunk-W2QGWRTT.js.map → chunk-I7OTWNFM.js.map} +1 -1
- package/dist/chunk-PWCXZWSE.js +2 -0
- package/dist/chunk-PWCXZWSE.js.map +1 -0
- package/dist/{chunk-N6FGTZ6A.js → chunk-T3L6OCM3.js} +3 -3
- package/dist/chunk-T3L6OCM3.js.map +1 -0
- package/dist/{chunk-2MGFSIXN.js → chunk-VQUSWD4U.js} +2 -2
- package/dist/chunk-VQUSWD4U.js.map +1 -0
- package/dist/chunk-XOITNPU3.js +2 -0
- package/dist/{chunk-TYVG6TXQ.js.map → chunk-XOITNPU3.js.map} +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -1
- package/dist/gateway.d.ts +2 -2
- package/dist/gateway.js +1 -1
- package/dist/{index-B_Vbrb_I.d.ts → index-Brfvxmdt.d.ts} +1 -1
- package/dist/{index-CL8m1L1d.d.ts → index-DO97j6hP.d.ts} +14 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/types.js +1 -1
- package/dist/{verifier-DTCD9imJ.d.ts → verifier-COnid_dg.d.ts} +1 -1
- package/dist/verifier-XU2DB56Z.js +2 -0
- package/dist/{verifier-Z26UC7M4.js.map → verifier-XU2DB56Z.js.map} +1 -1
- package/dist/workers/zk-verifier.d.ts +2 -0
- package/dist/workers/zk-verifier.js +1 -1
- package/dist/workers/zk-verifier.js.map +1 -1
- package/package.json +43 -43
- package/dist/chunk-2MGFSIXN.js.map +0 -1
- package/dist/chunk-L5A64CNT.js.map +0 -1
- package/dist/chunk-N6FGTZ6A.js.map +0 -1
- package/dist/chunk-SW53FNSN.js +0 -2
- package/dist/chunk-SW53FNSN.js.map +0 -1
- package/dist/chunk-TYVG6TXQ.js +0 -2
- package/dist/chunk-VGXNGTIC.js.map +0 -1
- package/dist/verifier-Z26UC7M4.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {g}from'./chunk-
|
|
1
|
+
import {g}from'./chunk-I46YEWND.js';import {b}from'./chunk-SB5XJXKV.js';import {a}from'./chunk-S6RJHZV2.js';import*as v from'http';import*as m from'http2';import*as y from'net';function u(h,t){return {resource:t,authorization_servers:[h],scopes_supported:b,bearer_methods_supported:["header"],resource_documentation:"https://github.com/nekzus/liop"}}var f=class{constructor(t,e=null,i=50051){this.liopServer=t;this.meshNode=e;this.jwtValidator=this.liopServer.jwtValidator,this.oauthProvider=this.liopServer.oauthProvider,this.router=new g(this.liopServer,this.meshNode,i),this.h2Server=m.createServer(),this.setupH2Routes(),this.h1Server=v.createServer(),this.setupH1Routes(),this.netServer=y.createServer(r=>{r.once("data",o=>{let n=o.toString().startsWith("PRI * HTTP/2.0");a.info(`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${n?"HTTP/2 (gRPC)":"HTTP/1.1 (MCP)"}`),n?this.h2Server.emit("connection",r):this.h1Server.emit("connection",r),r.unshift(o);}),r.on("error",o=>a.error(`[LIOP-Gateway] NetServer Socket Error: ${o.message}`));}),this.h1Server.on("error",r=>a.error(`[LIOP-Gateway] H1 Server Error: ${r.message}`)),this.h2Server.on("error",r=>a.error(`[LIOP-Gateway] H2 Server Error: ${r.message}`)),a.info("[LIOP-Gateway] Hybrid adapter initialized.");}netServer;h2Server;h1Server;router;jwtValidator;oauthProvider;setupH2Routes(){this.h2Server.on("stream",(t,e)=>{let i=e["content-type"],r=e[":path"];i==="application/grpc"?this.handleGrpcStream(t):r==="/mcp"&&this.handleMcpH2Stream(t,e);});}setupH1Routes(){this.h1Server.on("request",async(t,e)=>{let i=t.url||"",r=t.method;if(i.startsWith("/oidc")&&this.oauthProvider){let o=typeof this.oauthProvider.callback=="function"?this.oauthProvider.callback():this.oauthProvider,n=t.url;t.url=(n||"").slice(5)||"/";try{return o(t,e)}finally{t.url=n;}}if(r==="GET"&&i==="/.well-known/oauth-protected-resource"){if(this.jwtValidator){let o=u(this.jwtValidator.getIssuer(),this.jwtValidator.getAudience());e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(o));return}e.writeHead(404),e.end("Not Found");return}if(r==="GET"&&(i==="/"||i==="/mcp"||i==="/health")){if(i==="/health"&&t.headers.accept?.includes("application/json")){let o=this.meshNode?{peerId:this.meshNode.getPeerId()?.toString()||"",multiaddrs:this.meshNode.getMultiaddrs().map(p=>p.toString())}:null,n=this.jwtValidator?.getIssuer(),a=n?n.endsWith("/oidc")?n:`${n}/oidc`:"",d=this.jwtValidator&&n?{issuer:n,jwks_uri:`${a}/jwks`,...this.oauthProvider?{token_endpoint:`${a}/token`}:{}}:void 0;e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:"healthy",node:this.liopServer.getServerInfo(),mesh:o,tools:this.liopServer.listTools().map(p=>p.name),auth:d,timestamp:new Date().toISOString()}));return}e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(`
|
|
2
2
|
<body style="background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0">
|
|
3
3
|
<div style="background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)">
|
|
4
4
|
<h1 style="color:#38bdf8;margin-top:0">LIOP Protocol Transformer</h1>
|
|
@@ -9,5 +9,5 @@ import {g}from'./chunk-VGXNGTIC.js';import {b}from'./chunk-SB5XJXKV.js';import {
|
|
|
9
9
|
</div>
|
|
10
10
|
</div>
|
|
11
11
|
</body>
|
|
12
|
-
`);return}if(i==="/mcp"&&r==="POST"){let o=null;if(this.jwtValidator){let a=t.headers.authorization;if(!a?.startsWith("Bearer ")){e.writeHead(401,{"WWW-Authenticate":'Bearer error="invalid_token", error_description="Missing or malformed Authorization header"',"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Unauthorized"}));return}try{o=await this.jwtValidator.validate(a.slice(7));}catch(d){e.writeHead(401,{"WWW-Authenticate":`Bearer error="invalid_token", error_description="${d.message}"`,"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Invalid token"}));return}}let n="";t.on("data",a=>n+=a.toString()),t.on("end",async()=>{try{let a=JSON.parse(n),d=await this.router.dispatch(a,o);e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(d));}catch(a$1){a.info(`[LIOP-Gateway] Error processing JSON-RPC payload: ${a$1.message}`),e.writeHead(400),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}}));}});}else e.writeHead(404),e.end("Not Found");});}handleGrpcStream(t){t.on("data",e=>{let i=e;i&&a.info(`[LIOP-Gateway] Native gRPC Proxy passing ${i.length} bytes`);}),t.respond({":status":200,"content-type":"application/grpc"}),t.end();}handleMcpH2Stream(t,e){let i="";t.on("data",r=>i+=r.toString()),t.on("end",async()=>{try{let r=null;if(this.jwtValidator){let n=e.authorization;if(!n?.startsWith("Bearer ")){t.respond({":status":401,"www-authenticate":'Bearer error="invalid_token", error_description="Missing or malformed Authorization header"',"content-type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}try{r=await this.jwtValidator.validate(n.slice(7));}catch(a){t.respond({":status":401,"www-authenticate":`Bearer error="invalid_token", error_description="${a.message}"`,"content-type":"application/json"}),t.end(JSON.stringify({error:"Invalid token"}));return}}let o=await this.router.dispatch(JSON.parse(i),r);o?(t.respond({":status":200,"content-type":"application/json"}),t.end(JSON.stringify(o))):t.close();}catch{t.respond({":status":400}),t.end();}});}async listen(t,e="0.0.0.0"){if(this.meshNode){await this.meshNode.start();let i=this.liopServer.listTools();for(let r of i)await this.meshNode.announceCapability(r.name),a.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${r.name}`);}return new Promise((i,r)=>{this.netServer.on("error",o=>{o.code==="EADDRINUSE"?a.info(`[LIOP-Gateway] FATAL: Port ${t} is already in use by another process.`):a.error(`[LIOP-Gateway] Binding Error: ${o.message}`),r(o);}),this.netServer.listen(t,e,()=>{let o=this.netServer.address(),n=typeof o=="string"?o:o?.address||e,a$1=typeof o=="string"?t:o?.port||t;a.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${n}:${a$1}`),i(a$1);});})}async stop(){this.meshNode&&await this.meshNode.stop(),this.netServer.close(),this.h2Server.close(),this.h1Server.close();}getRouter(){return this.router}};export{u as a,f as b};//# sourceMappingURL=chunk-
|
|
13
|
-
//# sourceMappingURL=chunk-
|
|
12
|
+
`);return}if(i==="/mcp"&&r==="POST"){let o=null;if(this.jwtValidator){let a=t.headers.authorization;if(!a?.startsWith("Bearer ")){e.writeHead(401,{"WWW-Authenticate":'Bearer error="invalid_token", error_description="Missing or malformed Authorization header"',"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Unauthorized"}));return}try{o=await this.jwtValidator.validate(a.slice(7));}catch(d){e.writeHead(401,{"WWW-Authenticate":`Bearer error="invalid_token", error_description="${d.message}"`,"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Invalid token"}));return}}let n="";t.on("data",a=>n+=a.toString()),t.on("end",async()=>{try{let a=JSON.parse(n),d=await this.router.dispatch(a,o);e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(d));}catch(a$1){a.info(`[LIOP-Gateway] Error processing JSON-RPC payload: ${a$1.message}`),e.writeHead(400),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}}));}});}else e.writeHead(404),e.end("Not Found");});}handleGrpcStream(t){t.on("data",e=>{let i=e;i&&a.info(`[LIOP-Gateway] Native gRPC Proxy passing ${i.length} bytes`);}),t.respond({":status":200,"content-type":"application/grpc"}),t.end();}handleMcpH2Stream(t,e){let i="";t.on("data",r=>i+=r.toString()),t.on("end",async()=>{try{let r=null;if(this.jwtValidator){let n=e.authorization;if(!n?.startsWith("Bearer ")){t.respond({":status":401,"www-authenticate":'Bearer error="invalid_token", error_description="Missing or malformed Authorization header"',"content-type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}try{r=await this.jwtValidator.validate(n.slice(7));}catch(a){t.respond({":status":401,"www-authenticate":`Bearer error="invalid_token", error_description="${a.message}"`,"content-type":"application/json"}),t.end(JSON.stringify({error:"Invalid token"}));return}}let o=await this.router.dispatch(JSON.parse(i),r);o?(t.respond({":status":200,"content-type":"application/json"}),t.end(JSON.stringify(o))):t.close();}catch{t.respond({":status":400}),t.end();}});}async listen(t,e="0.0.0.0"){if(this.meshNode){await this.meshNode.start();let i=this.liopServer.listTools();for(let r of i)await this.meshNode.announceCapability(r.name),a.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${r.name}`);}return new Promise((i,r)=>{this.netServer.on("error",o=>{o.code==="EADDRINUSE"?a.info(`[LIOP-Gateway] FATAL: Port ${t} is already in use by another process.`):a.error(`[LIOP-Gateway] Binding Error: ${o.message}`),r(o);}),this.netServer.listen(t,e,()=>{let o=this.netServer.address(),n=typeof o=="string"?o:o?.address||e,a$1=typeof o=="string"?t:o?.port||t;a.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${n}:${a$1}`),i(a$1);});})}async stop(){this.meshNode&&await this.meshNode.stop(),this.netServer.close(),this.h2Server.close(),this.h1Server.close();}getRouter(){return this.router}};export{u as a,f as b};//# sourceMappingURL=chunk-GI2LSJYZ.js.map
|
|
13
|
+
//# sourceMappingURL=chunk-GI2LSJYZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/security/prm.ts","../src/gateway/hybrid.ts"],"names":["buildProtectedResourceMetadata","issuer","audience","LIOP_SCOPES","LiopHybridGateway","liopServer","meshNode","rpcPort","LiopMcpRouter","socket","buffer","isHttp2","log","err","stream","headers","contentType","path","req","res","url","method","callback","originalUrl","prm","meshInfo","m","baseUrl","authInfoResponse","t","authInfo","authHeader","e","body","chunk","jsonRequest","response","data","port","host","tools","tool","resolve","reject","addr","actualHost","assignedPort"],"mappings":"iLAoCO,SAASA,CAAAA,CACfC,CAAAA,CACAC,CAAAA,CAC4B,CAC5B,OAAO,CACN,QAAA,CAAUA,CAAAA,CACV,qBAAA,CAAuB,CAACD,CAAM,CAAA,CAC9B,gBAAA,CAAkBE,CAAAA,CAClB,wBAAA,CAA0B,CAAC,QAAQ,CAAA,CACnC,uBAAwB,gCACzB,CACD,CCjCO,IAAMC,CAAAA,CAAN,KAAwB,CAS9B,WAAA,CACSC,CAAAA,CACAC,CAAAA,CAA4B,IAAA,CACpCC,CAAAA,CAAkB,KAAA,CACjB,CAHO,IAAA,CAAA,UAAA,CAAAF,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,CAAAA,CAGR,IAAA,CAAK,YAAA,CAAe,IAAA,CAAK,UAAA,CAAW,YAAA,CACpC,IAAA,CAAK,aAAA,CAAgB,IAAA,CAAK,UAAA,CAAW,aAAA,CAGrC,KAAK,MAAA,CAAS,IAAIE,CAAAA,CAAc,IAAA,CAAK,UAAA,CAAY,IAAA,CAAK,SAAUD,CAAO,CAAA,CAGvE,IAAA,CAAK,QAAA,CAAiB,CAAA,CAAA,YAAA,EAAa,CACnC,KAAK,aAAA,EAAc,CAGnB,IAAA,CAAK,QAAA,CAAg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BD,CAAAA,CAAI,IAAA,CACH,CAAA,2BAAA,EAA8B0B,CAAI,CAAA,sCAAA,CACnC,CAAA,CAEA1B,CAAAA,CAAI,KAAA,CAAM,CAAA,8BAAA,EAAiCC,CAAAA,CAAI,OAAO,CAAA,CAAE,CAAA,CAEzD8B,CAAAA,CAAO9B,CAAG,EACX,CAAC,CAAA,CAED,IAAA,CAAK,SAAA,CAAU,MAAA,CAAOyB,CAAAA,CAAMC,CAAAA,CAAM,IAAM,CACvC,IAAMK,CAAAA,CAAO,IAAA,CAAK,SAAA,CAAU,OAAA,EAAQ,CAC9BC,CAAAA,CACL,OAAOD,CAAAA,EAAS,QAAA,CAAWA,CAAAA,CAAOA,CAAAA,EAAM,OAAA,EAAWL,CAAAA,CAC9CO,GAAAA,CACL,OAAOF,CAAAA,EAAS,QAAA,CAAWN,CAAAA,CAAOM,CAAAA,EAAM,IAAA,EAAQN,CAAAA,CAEjD1B,CAAAA,CAAI,IAAA,CACH,CAAA,sEAAA,EAAoEiC,CAAU,CAAA,CAAA,EAAIC,GAAY,CAAA,CAC/F,CAAA,CACAJ,CAAAA,CAAQI,GAAY,EACrB,CAAC,EACF,CAAC,CACF,CAEA,MAAa,IAAA,EAAO,CACf,IAAA,CAAK,QAAA,EACR,MAAM,IAAA,CAAK,QAAA,CAAS,IAAA,EAAK,CAE1B,IAAA,CAAK,SAAA,CAAU,KAAA,EAAM,CACrB,IAAA,CAAK,QAAA,CAAS,KAAA,EAAM,CACpB,IAAA,CAAK,QAAA,CAAS,KAAA,GACf,CAEO,SAAA,EAA2B,CACjC,OAAO,IAAA,CAAK,MACb,CACD","file":"chunk-YZVCAJJO.js","sourcesContent":["/**\n * LIOP Protected Resource Metadata — RFC 9728\n *\n * Builds the JSON document served at /.well-known/oauth-protected-resource.\n * This enables MCP clients to discover the authorization server and\n * required scopes for accessing LIOP tools and resources.\n *\n * Standards: RFC 9728, MCP Spec 2025-11-25\n */\n\nimport { LIOP_SCOPES } from \"./rbac.js\";\n\n/**\n * RFC 9728 Protected Resource Metadata response.\n *\n * @see https://datatracker.ietf.org/doc/rfc9728\n */\nexport interface ProtectedResourceMetadata {\n\t/** Identifier for the protected resource. */\n\tresource: string;\n\t/** Array of authorization server issuer URLs that can issue tokens for this resource. */\n\tauthorization_servers: string[];\n\t/** OAuth scopes accepted by this resource. */\n\tscopes_supported: readonly string[];\n\t/** Methods of presenting the bearer token (always \"header\" for LIOP). */\n\tbearer_methods_supported: string[];\n\t/** URL to the resource documentation. */\n\tresource_documentation: string;\n}\n\n/**\n * Builds the Protected Resource Metadata document (RFC 9728).\n *\n * @param issuer - OIDC issuer URL of the Nexus authorization server\n * @param audience - JWT audience claim (resource identifier)\n */\nexport function buildProtectedResourceMetadata(\n\tissuer: string,\n\taudience: string,\n): ProtectedResourceMetadata {\n\treturn {\n\t\tresource: audience,\n\t\tauthorization_servers: [issuer],\n\t\tscopes_supported: LIOP_SCOPES,\n\t\tbearer_methods_supported: [\"header\"],\n\t\tresource_documentation: \"https://github.com/nekzus/liop\",\n\t};\n}\n","import * as http from \"node:http\";\nimport * as http2 from \"node:http2\";\nimport * as net from \"node:net\";\nimport type { MeshNode } from \"../mesh/index.js\";\nimport type { AuthInfo, JwtValidator } from \"../security/jwt-validator.js\";\nimport { buildProtectedResourceMetadata } from \"../security/prm.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpRouter } from \"./router.js\";\n\n/**\n * LIOP Hybrid Gateway\n * High-level orchestration for connecting MCP (JSON-RPC) clients to the LIOP Mesh.\n */\nexport class LiopHybridGateway {\n\tprivate netServer: net.Server;\n\tprivate h2Server: http2.Http2Server;\n\tprivate h1Server: http.Server;\n\tprivate router: LiopMcpRouter;\n\tprivate jwtValidator?: JwtValidator;\n\t// biome-ignore lint/suspicious/noExplicitAny: oidc-provider is loaded in Phase C\n\tprivate oauthProvider?: any;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\trpcPort: number = 50051,\n\t) {\n\t\tthis.jwtValidator = this.liopServer.jwtValidator;\n\t\tthis.oauthProvider = this.liopServer.oauthProvider;\n\n\t\t// Initialize the Universal Router\n\t\tthis.router = new LiopMcpRouter(this.liopServer, this.meshNode, rpcPort);\n\n\t\t// Internal HTTP/2 Server (for Native gRPC Proxying)\n\t\tthis.h2Server = http2.createServer();\n\t\tthis.setupH2Routes();\n\n\t\t// Internal HTTP/1 Server (for Browser/MCP)\n\t\tthis.h1Server = http.createServer();\n\t\tthis.setupH1Routes();\n\n\t\t// Primary Multiplexer (L4)\n\t\tthis.netServer = net.createServer((socket) => {\n\t\t\tsocket.once(\"data\", (buffer) => {\n\t\t\t\tconst isHttp2 = buffer.toString().startsWith(\"PRI * HTTP/2.0\");\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${isHttp2 ? \"HTTP/2 (gRPC)\" : \"HTTP/1.1 (MCP)\"}`,\n\t\t\t\t);\n\t\t\t\tif (isHttp2) {\n\t\t\t\t\tthis.h2Server.emit(\"connection\", socket);\n\t\t\t\t} else {\n\t\t\t\t\tthis.h1Server.emit(\"connection\", socket);\n\t\t\t\t}\n\t\t\t\tsocket.unshift(buffer);\n\t\t\t});\n\t\t\tsocket.on(\"error\", (err) =>\n\t\t\t\tlog.error(`[LIOP-Gateway] NetServer Socket Error: ${err.message}`),\n\t\t\t);\n\t\t});\n\n\t\t// Attach error listeners to sub-servers to catch silent failures\n\t\tthis.h1Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H1 Server Error: ${err.message}`),\n\t\t);\n\t\tthis.h2Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H2 Server Error: ${err.message}`),\n\t\t);\n\n\t\tlog.info(\"[LIOP-Gateway] Hybrid adapter initialized.\");\n\t}\n\n\tprivate setupH2Routes() {\n\t\tthis.h2Server.on(\"stream\", (stream, headers) => {\n\t\t\tconst contentType = headers[\"content-type\"] as string;\n\t\t\tconst path = headers[\":path\"] as string;\n\n\t\t\tif (contentType === \"application/grpc\") {\n\t\t\t\tthis.handleGrpcStream(stream as http2.ServerHttp2Stream);\n\t\t\t} else if (path === \"/mcp\") {\n\t\t\t\tthis.handleMcpH2Stream(stream as http2.ServerHttp2Stream, headers);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate setupH1Routes() {\n\t\tthis.h1Server.on(\"request\", async (req, res) => {\n\t\t\tconst url = req.url || \"\";\n\t\t\tconst method = req.method;\n\n\t\t\t// [SEC] M2M OAuth 2.1 OIDC Authorization Server Router (Phase C proxy)\n\t\t\tif (url.startsWith(\"/oidc\") && this.oauthProvider) {\n\t\t\t\tconst callback =\n\t\t\t\t\ttypeof this.oauthProvider.callback === \"function\"\n\t\t\t\t\t\t? this.oauthProvider.callback()\n\t\t\t\t\t\t: this.oauthProvider;\n\t\t\t\t// Rewrite req.url to strip the '/oidc' prefix before delegating to oidc-provider\n\t\t\t\tconst originalUrl = req.url;\n\t\t\t\treq.url = (originalUrl || \"\").slice(5) || \"/\";\n\t\t\t\ttry {\n\t\t\t\t\treturn callback(req, res);\n\t\t\t\t} finally {\n\t\t\t\t\treq.url = originalUrl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// [SEC] RFC 9728 Protected Resource Metadata (PRM) Endpoint\n\t\t\tif (method === \"GET\" && url === \"/.well-known/oauth-protected-resource\") {\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst prm = buildProtectedResourceMetadata(\n\t\t\t\t\t\tthis.jwtValidator.getIssuer(),\n\t\t\t\t\t\tthis.jwtValidator.getAudience(),\n\t\t\t\t\t);\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(JSON.stringify(prm));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tmethod === \"GET\" &&\n\t\t\t\t(url === \"/\" || url === \"/mcp\" || url === \"/health\")\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\turl === \"/health\" &&\n\t\t\t\t\treq.headers.accept?.includes(\"application/json\")\n\t\t\t\t) {\n\t\t\t\t\tconst meshInfo = this.meshNode\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpeerId: this.meshNode.getPeerId()?.toString() || \"\",\n\t\t\t\t\t\t\t\tmultiaddrs: this.meshNode\n\t\t\t\t\t\t\t\t\t.getMultiaddrs()\n\t\t\t\t\t\t\t\t\t.map((m) => m.toString()),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null;\n\t\t\t\t\tconst issuer = this.jwtValidator?.getIssuer();\n\t\t\t\t\tconst baseUrl = issuer\n\t\t\t\t\t\t? issuer.endsWith(\"/oidc\")\n\t\t\t\t\t\t\t? issuer\n\t\t\t\t\t\t\t: `${issuer}/oidc`\n\t\t\t\t\t\t: \"\";\n\t\t\t\t\tconst authInfoResponse =\n\t\t\t\t\t\tthis.jwtValidator && issuer\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tissuer,\n\t\t\t\t\t\t\t\t\tjwks_uri: `${baseUrl}/jwks`,\n\t\t\t\t\t\t\t\t\t...(this.oauthProvider\n\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\ttoken_endpoint: `${baseUrl}/token`,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"healthy\",\n\t\t\t\t\t\t\tnode: this.liopServer.getServerInfo(),\n\t\t\t\t\t\t\tmesh: meshInfo,\n\t\t\t\t\t\t\ttools: this.liopServer.listTools().map((t) => t.name),\n\t\t\t\t\t\t\tauth: authInfoResponse,\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(`\n <body style=\"background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0\">\n <div style=\"background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)\">\n <h1 style=\"color:#38bdf8;margin-top:0\">LIOP Protocol Transformer</h1>\n <p style=\"opacity:0.8;font-weight:600\">L4/L7 Transcoding: JSON-RPC ↔ gRPC</p>\n <p style=\"opacity:0.6;font-size:14px\">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>\n <div style=\"background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155\">\n <code style=\"color:#10b981\">Endpoint: http://localhost:3000/mcp</code>\n </div>\n </div>\n </body>\n `);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (url === \"/mcp\" && method === \"POST\") {\n\t\t\t\tlet authInfo: AuthInfo | null = null;\n\n\t\t\t\t// [SEC] Continuous verification of Bearer token (NIST SP 800-207)\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst authHeader = req.headers.authorization;\n\t\t\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\t\t\tres.writeHead(401, {\n\t\t\t\t\t\t\t\"WWW-Authenticate\":\n\t\t\t\t\t\t\t\t'Bearer error=\"invalid_token\", error_description=\"Missing or malformed Authorization header\"',\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(JSON.stringify({ error: \"Unauthorized\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tauthInfo = await this.jwtValidator.validate(authHeader.slice(7));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tres.writeHead(401, {\n\t\t\t\t\t\t\t\"WWW-Authenticate\": `Bearer error=\"invalid_token\", error_description=\"${(e as Error).message}\"`,\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(JSON.stringify({ error: \"Invalid token\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlet body = \"\";\n\t\t\t\treq.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\t\t\treq.on(\"end\", async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst jsonRequest = JSON.parse(body);\n\t\t\t\t\t\tconst response = await this.router.dispatch(jsonRequest, authInfo);\n\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify(response));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Gateway] Error processing JSON-RPC payload: ${(e as Error).message}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tres.writeHead(400);\n\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\terror: { code: -32700, message: \"Parse error\" },\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} else {\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate handleGrpcStream(stream: http2.ServerHttp2Stream) {\n\t\tstream.on(\"data\", (chunk: unknown) => {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Standard gRPC stream data is Buffer\n\t\t\tconst data = chunk as any;\n\t\t\tif (data)\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Native gRPC Proxy passing ${data.length} bytes`,\n\t\t\t\t);\n\t\t});\n\t\tstream.respond({ \":status\": 200, \"content-type\": \"application/grpc\" });\n\t\tstream.end();\n\t}\n\n\tprivate handleMcpH2Stream(\n\t\tstream: http2.ServerHttp2Stream,\n\t\theaders: http2.IncomingHttpHeaders,\n\t) {\n\t\tlet body = \"\";\n\t\tstream.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\tstream.on(\"end\", async () => {\n\t\t\ttry {\n\t\t\t\tlet authInfo: AuthInfo | null = null;\n\n\t\t\t\t// [SEC] Continuous verification of Bearer token over HTTP/2 (NIST SP 800-207)\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst authHeader = headers.authorization as string;\n\t\t\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 401,\n\t\t\t\t\t\t\t\"www-authenticate\":\n\t\t\t\t\t\t\t\t'Bearer error=\"invalid_token\", error_description=\"Missing or malformed Authorization header\"',\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(JSON.stringify({ error: \"Unauthorized\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tauthInfo = await this.jwtValidator.validate(authHeader.slice(7));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 401,\n\t\t\t\t\t\t\t\"www-authenticate\": `Bearer error=\"invalid_token\", error_description=\"${(e as Error).message}\"`,\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(JSON.stringify({ error: \"Invalid token\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst response = await this.router.dispatch(JSON.parse(body), authInfo);\n\t\t\t\tif (response) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 200,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(JSON.stringify(response));\n\t\t\t\t} else stream.close();\n\t\t\t} catch (_e) {\n\t\t\t\tstream.respond({ \":status\": 400 });\n\t\t\t\tstream.end();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async listen(port: number, host: string = \"0.0.0.0\"): Promise<number> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.start();\n\n\t\t\t// Announce all local tools to the DHT\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\tfor (const tool of tools) {\n\t\t\t\tawait this.meshNode.announceCapability(tool.name);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] 📡 Announced local tool to Mesh: ${tool.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.netServer.on(\"error\", (err: Error & { code?: string }) => {\n\t\t\t\tif (err.code === \"EADDRINUSE\") {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Gateway] FATAL: Port ${port} is already in use by another process.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlog.error(`[LIOP-Gateway] Binding Error: ${err.message}`);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tthis.netServer.listen(port, host, () => {\n\t\t\t\tconst addr = this.netServer.address();\n\t\t\t\tconst actualHost =\n\t\t\t\t\ttypeof addr === \"string\" ? addr : addr?.address || host;\n\t\t\t\tconst assignedPort =\n\t\t\t\t\ttypeof addr === \"string\" ? port : addr?.port || port;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] ✅ Transformer Mesh Gateway READY and listening on ${actualHost}:${assignedPort}`,\n\t\t\t\t);\n\t\t\t\tresolve(assignedPort);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic async stop() {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t\tthis.netServer.close();\n\t\tthis.h2Server.close();\n\t\tthis.h1Server.close();\n\t}\n\n\tpublic getRouter(): LiopMcpRouter {\n\t\treturn this.router;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/security/prm.ts","../src/gateway/hybrid.ts"],"names":["buildProtectedResourceMetadata","issuer","audience","LIOP_SCOPES","LiopHybridGateway","liopServer","meshNode","rpcPort","LiopMcpRouter","socket","buffer","isHttp2","log","err","stream","headers","contentType","path","req","res","url","method","callback","originalUrl","prm","meshInfo","m","baseUrl","authInfoResponse","t","authInfo","authHeader","e","body","chunk","jsonRequest","response","data","port","host","tools","tool","resolve","reject","addr","actualHost","assignedPort"],"mappings":"iLAoCO,SAASA,CAAAA,CACfC,CAAAA,CACAC,CAAAA,CAC4B,CAC5B,OAAO,CACN,QAAA,CAAUA,CAAAA,CACV,qBAAA,CAAuB,CAACD,CAAM,CAAA,CAC9B,gBAAA,CAAkBE,CAAAA,CAClB,wBAAA,CAA0B,CAAC,QAAQ,CAAA,CACnC,uBAAwB,gCACzB,CACD,CCjCO,IAAMC,CAAAA,CAAN,KAAwB,CAS9B,WAAA,CACSC,CAAAA,CACAC,CAAAA,CAA4B,IAAA,CACpCC,CAAAA,CAAkB,KAAA,CACjB,CAHO,IAAA,CAAA,UAAA,CAAAF,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,CAAAA,CAGR,IAAA,CAAK,YAAA,CAAe,IAAA,CAAK,UAAA,CAAW,YAAA,CACpC,IAAA,CAAK,aAAA,CAAgB,IAAA,CAAK,UAAA,CAAW,aAAA,CAGrC,KAAK,MAAA,CAAS,IAAIE,CAAAA,CAAc,IAAA,CAAK,UAAA,CAAY,IAAA,CAAK,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C,CAAAA,GAAW,CACvC,IAAA,CAAK,SAAA,CAAU,EAAA,CAAG,OAAA,CAAU9B,CAAAA,EAAmC,CAC1DA,CAAAA,CAAI,IAAA,GAAS,YAAA,CAChBD,CAAAA,CAAI,IAAA,CACH,CAAA,2BAAA,EAA8B0B,CAAI,CAAA,sCAAA,CACnC,CAAA,CAEA1B,CAAAA,CAAI,KAAA,CAAM,CAAA,8BAAA,EAAiCC,CAAAA,CAAI,OAAO,CAAA,CAAE,CAAA,CAEzD8B,CAAAA,CAAO9B,CAAG,EACX,CAAC,CAAA,CAED,IAAA,CAAK,SAAA,CAAU,MAAA,CAAOyB,CAAAA,CAAMC,CAAAA,CAAM,IAAM,CACvC,IAAMK,CAAAA,CAAO,IAAA,CAAK,SAAA,CAAU,OAAA,EAAQ,CAC9BC,CAAAA,CACL,OAAOD,CAAAA,EAAS,QAAA,CAAWA,CAAAA,CAAOA,CAAAA,EAAM,OAAA,EAAWL,CAAAA,CAC9CO,GAAAA,CACL,OAAOF,CAAAA,EAAS,QAAA,CAAWN,CAAAA,CAAOM,CAAAA,EAAM,IAAA,EAAQN,CAAAA,CAEjD1B,CAAAA,CAAI,IAAA,CACH,CAAA,sEAAA,EAAoEiC,CAAU,CAAA,CAAA,EAAIC,GAAY,CAAA,CAC/F,CAAA,CACAJ,CAAAA,CAAQI,GAAY,EACrB,CAAC,EACF,CAAC,CACF,CAEA,MAAa,IAAA,EAAO,CACf,IAAA,CAAK,QAAA,EACR,MAAM,IAAA,CAAK,QAAA,CAAS,IAAA,EAAK,CAE1B,IAAA,CAAK,SAAA,CAAU,KAAA,EAAM,CACrB,IAAA,CAAK,QAAA,CAAS,KAAA,EAAM,CACpB,IAAA,CAAK,QAAA,CAAS,KAAA,GACf,CAEO,SAAA,EAA2B,CACjC,OAAO,IAAA,CAAK,MACb,CACD","file":"chunk-GI2LSJYZ.js","sourcesContent":["/**\n * LIOP Protected Resource Metadata — RFC 9728\n *\n * Builds the JSON document served at /.well-known/oauth-protected-resource.\n * This enables MCP clients to discover the authorization server and\n * required scopes for accessing LIOP tools and resources.\n *\n * Standards: RFC 9728, MCP Spec 2025-11-25\n */\n\nimport { LIOP_SCOPES } from \"./rbac.js\";\n\n/**\n * RFC 9728 Protected Resource Metadata response.\n *\n * @see https://datatracker.ietf.org/doc/rfc9728\n */\nexport interface ProtectedResourceMetadata {\n\t/** Identifier for the protected resource. */\n\tresource: string;\n\t/** Array of authorization server issuer URLs that can issue tokens for this resource. */\n\tauthorization_servers: string[];\n\t/** OAuth scopes accepted by this resource. */\n\tscopes_supported: readonly string[];\n\t/** Methods of presenting the bearer token (always \"header\" for LIOP). */\n\tbearer_methods_supported: string[];\n\t/** URL to the resource documentation. */\n\tresource_documentation: string;\n}\n\n/**\n * Builds the Protected Resource Metadata document (RFC 9728).\n *\n * @param issuer - OIDC issuer URL of the Nexus authorization server\n * @param audience - JWT audience claim (resource identifier)\n */\nexport function buildProtectedResourceMetadata(\n\tissuer: string,\n\taudience: string,\n): ProtectedResourceMetadata {\n\treturn {\n\t\tresource: audience,\n\t\tauthorization_servers: [issuer],\n\t\tscopes_supported: LIOP_SCOPES,\n\t\tbearer_methods_supported: [\"header\"],\n\t\tresource_documentation: \"https://github.com/nekzus/liop\",\n\t};\n}\n","import * as http from \"node:http\";\nimport * as http2 from \"node:http2\";\nimport * as net from \"node:net\";\nimport type { MeshNode } from \"../mesh/index.js\";\nimport type { AuthInfo, JwtValidator } from \"../security/jwt-validator.js\";\nimport { buildProtectedResourceMetadata } from \"../security/prm.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpRouter } from \"./router.js\";\n\n/**\n * LIOP Hybrid Gateway\n * High-level orchestration for connecting MCP (JSON-RPC) clients to the LIOP Mesh.\n */\nexport class LiopHybridGateway {\n\tprivate netServer: net.Server;\n\tprivate h2Server: http2.Http2Server;\n\tprivate h1Server: http.Server;\n\tprivate router: LiopMcpRouter;\n\tprivate jwtValidator?: JwtValidator;\n\t// biome-ignore lint/suspicious/noExplicitAny: oidc-provider is loaded in Phase C\n\tprivate oauthProvider?: any;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\trpcPort: number = 50051,\n\t) {\n\t\tthis.jwtValidator = this.liopServer.jwtValidator;\n\t\tthis.oauthProvider = this.liopServer.oauthProvider;\n\n\t\t// Initialize the Universal Router\n\t\tthis.router = new LiopMcpRouter(this.liopServer, this.meshNode, rpcPort);\n\n\t\t// Internal HTTP/2 Server (for Native gRPC Proxying)\n\t\tthis.h2Server = http2.createServer();\n\t\tthis.setupH2Routes();\n\n\t\t// Internal HTTP/1 Server (for Browser/MCP)\n\t\tthis.h1Server = http.createServer();\n\t\tthis.setupH1Routes();\n\n\t\t// Primary Multiplexer (L4)\n\t\tthis.netServer = net.createServer((socket) => {\n\t\t\tsocket.once(\"data\", (buffer) => {\n\t\t\t\tconst isHttp2 = buffer.toString().startsWith(\"PRI * HTTP/2.0\");\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${isHttp2 ? \"HTTP/2 (gRPC)\" : \"HTTP/1.1 (MCP)\"}`,\n\t\t\t\t);\n\t\t\t\tif (isHttp2) {\n\t\t\t\t\tthis.h2Server.emit(\"connection\", socket);\n\t\t\t\t} else {\n\t\t\t\t\tthis.h1Server.emit(\"connection\", socket);\n\t\t\t\t}\n\t\t\t\tsocket.unshift(buffer);\n\t\t\t});\n\t\t\tsocket.on(\"error\", (err) =>\n\t\t\t\tlog.error(`[LIOP-Gateway] NetServer Socket Error: ${err.message}`),\n\t\t\t);\n\t\t});\n\n\t\t// Attach error listeners to sub-servers to catch silent failures\n\t\tthis.h1Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H1 Server Error: ${err.message}`),\n\t\t);\n\t\tthis.h2Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H2 Server Error: ${err.message}`),\n\t\t);\n\n\t\tlog.info(\"[LIOP-Gateway] Hybrid adapter initialized.\");\n\t}\n\n\tprivate setupH2Routes() {\n\t\tthis.h2Server.on(\"stream\", (stream, headers) => {\n\t\t\tconst contentType = headers[\"content-type\"] as string;\n\t\t\tconst path = headers[\":path\"] as string;\n\n\t\t\tif (contentType === \"application/grpc\") {\n\t\t\t\tthis.handleGrpcStream(stream as http2.ServerHttp2Stream);\n\t\t\t} else if (path === \"/mcp\") {\n\t\t\t\tthis.handleMcpH2Stream(stream as http2.ServerHttp2Stream, headers);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate setupH1Routes() {\n\t\tthis.h1Server.on(\"request\", async (req, res) => {\n\t\t\tconst url = req.url || \"\";\n\t\t\tconst method = req.method;\n\n\t\t\t// [SEC] M2M OAuth 2.1 OIDC Authorization Server Router (Phase C proxy)\n\t\t\tif (url.startsWith(\"/oidc\") && this.oauthProvider) {\n\t\t\t\tconst callback =\n\t\t\t\t\ttypeof this.oauthProvider.callback === \"function\"\n\t\t\t\t\t\t? this.oauthProvider.callback()\n\t\t\t\t\t\t: this.oauthProvider;\n\t\t\t\t// Rewrite req.url to strip the '/oidc' prefix before delegating to oidc-provider\n\t\t\t\tconst originalUrl = req.url;\n\t\t\t\treq.url = (originalUrl || \"\").slice(5) || \"/\";\n\t\t\t\ttry {\n\t\t\t\t\treturn callback(req, res);\n\t\t\t\t} finally {\n\t\t\t\t\treq.url = originalUrl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// [SEC] RFC 9728 Protected Resource Metadata (PRM) Endpoint\n\t\t\tif (method === \"GET\" && url === \"/.well-known/oauth-protected-resource\") {\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst prm = buildProtectedResourceMetadata(\n\t\t\t\t\t\tthis.jwtValidator.getIssuer(),\n\t\t\t\t\t\tthis.jwtValidator.getAudience(),\n\t\t\t\t\t);\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(JSON.stringify(prm));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tmethod === \"GET\" &&\n\t\t\t\t(url === \"/\" || url === \"/mcp\" || url === \"/health\")\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\turl === \"/health\" &&\n\t\t\t\t\treq.headers.accept?.includes(\"application/json\")\n\t\t\t\t) {\n\t\t\t\t\tconst meshInfo = this.meshNode\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpeerId: this.meshNode.getPeerId()?.toString() || \"\",\n\t\t\t\t\t\t\t\tmultiaddrs: this.meshNode\n\t\t\t\t\t\t\t\t\t.getMultiaddrs()\n\t\t\t\t\t\t\t\t\t.map((m) => m.toString()),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null;\n\t\t\t\t\tconst issuer = this.jwtValidator?.getIssuer();\n\t\t\t\t\tconst baseUrl = issuer\n\t\t\t\t\t\t? issuer.endsWith(\"/oidc\")\n\t\t\t\t\t\t\t? issuer\n\t\t\t\t\t\t\t: `${issuer}/oidc`\n\t\t\t\t\t\t: \"\";\n\t\t\t\t\tconst authInfoResponse =\n\t\t\t\t\t\tthis.jwtValidator && issuer\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tissuer,\n\t\t\t\t\t\t\t\t\tjwks_uri: `${baseUrl}/jwks`,\n\t\t\t\t\t\t\t\t\t...(this.oauthProvider\n\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\ttoken_endpoint: `${baseUrl}/token`,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"healthy\",\n\t\t\t\t\t\t\tnode: this.liopServer.getServerInfo(),\n\t\t\t\t\t\t\tmesh: meshInfo,\n\t\t\t\t\t\t\ttools: this.liopServer.listTools().map((t) => t.name),\n\t\t\t\t\t\t\tauth: authInfoResponse,\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(`\n <body style=\"background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0\">\n <div style=\"background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)\">\n <h1 style=\"color:#38bdf8;margin-top:0\">LIOP Protocol Transformer</h1>\n <p style=\"opacity:0.8;font-weight:600\">L4/L7 Transcoding: JSON-RPC ↔ gRPC</p>\n <p style=\"opacity:0.6;font-size:14px\">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>\n <div style=\"background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155\">\n <code style=\"color:#10b981\">Endpoint: http://localhost:3000/mcp</code>\n </div>\n </div>\n </body>\n `);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (url === \"/mcp\" && method === \"POST\") {\n\t\t\t\tlet authInfo: AuthInfo | null = null;\n\n\t\t\t\t// [SEC] Continuous verification of Bearer token (NIST SP 800-207)\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst authHeader = req.headers.authorization;\n\t\t\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\t\t\tres.writeHead(401, {\n\t\t\t\t\t\t\t\"WWW-Authenticate\":\n\t\t\t\t\t\t\t\t'Bearer error=\"invalid_token\", error_description=\"Missing or malformed Authorization header\"',\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(JSON.stringify({ error: \"Unauthorized\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tauthInfo = await this.jwtValidator.validate(authHeader.slice(7));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tres.writeHead(401, {\n\t\t\t\t\t\t\t\"WWW-Authenticate\": `Bearer error=\"invalid_token\", error_description=\"${(e as Error).message}\"`,\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(JSON.stringify({ error: \"Invalid token\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlet body = \"\";\n\t\t\t\treq.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\t\t\treq.on(\"end\", async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst jsonRequest = JSON.parse(body);\n\t\t\t\t\t\tconst response = await this.router.dispatch(jsonRequest, authInfo);\n\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify(response));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Gateway] Error processing JSON-RPC payload: ${(e as Error).message}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tres.writeHead(400);\n\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\terror: { code: -32700, message: \"Parse error\" },\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} else {\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate handleGrpcStream(stream: http2.ServerHttp2Stream) {\n\t\tstream.on(\"data\", (chunk: unknown) => {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Standard gRPC stream data is Buffer\n\t\t\tconst data = chunk as any;\n\t\t\tif (data)\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Native gRPC Proxy passing ${data.length} bytes`,\n\t\t\t\t);\n\t\t});\n\t\tstream.respond({ \":status\": 200, \"content-type\": \"application/grpc\" });\n\t\tstream.end();\n\t}\n\n\tprivate handleMcpH2Stream(\n\t\tstream: http2.ServerHttp2Stream,\n\t\theaders: http2.IncomingHttpHeaders,\n\t) {\n\t\tlet body = \"\";\n\t\tstream.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\tstream.on(\"end\", async () => {\n\t\t\ttry {\n\t\t\t\tlet authInfo: AuthInfo | null = null;\n\n\t\t\t\t// [SEC] Continuous verification of Bearer token over HTTP/2 (NIST SP 800-207)\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst authHeader = headers.authorization as string;\n\t\t\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 401,\n\t\t\t\t\t\t\t\"www-authenticate\":\n\t\t\t\t\t\t\t\t'Bearer error=\"invalid_token\", error_description=\"Missing or malformed Authorization header\"',\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(JSON.stringify({ error: \"Unauthorized\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tauthInfo = await this.jwtValidator.validate(authHeader.slice(7));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 401,\n\t\t\t\t\t\t\t\"www-authenticate\": `Bearer error=\"invalid_token\", error_description=\"${(e as Error).message}\"`,\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(JSON.stringify({ error: \"Invalid token\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst response = await this.router.dispatch(JSON.parse(body), authInfo);\n\t\t\t\tif (response) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 200,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(JSON.stringify(response));\n\t\t\t\t} else stream.close();\n\t\t\t} catch (_e) {\n\t\t\t\tstream.respond({ \":status\": 400 });\n\t\t\t\tstream.end();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async listen(port: number, host: string = \"0.0.0.0\"): Promise<number> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.start();\n\n\t\t\t// Announce all local tools to the DHT\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\tfor (const tool of tools) {\n\t\t\t\tawait this.meshNode.announceCapability(tool.name);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] 📡 Announced local tool to Mesh: ${tool.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.netServer.on(\"error\", (err: Error & { code?: string }) => {\n\t\t\t\tif (err.code === \"EADDRINUSE\") {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Gateway] FATAL: Port ${port} is already in use by another process.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlog.error(`[LIOP-Gateway] Binding Error: ${err.message}`);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tthis.netServer.listen(port, host, () => {\n\t\t\t\tconst addr = this.netServer.address();\n\t\t\t\tconst actualHost =\n\t\t\t\t\ttypeof addr === \"string\" ? addr : addr?.address || host;\n\t\t\t\tconst assignedPort =\n\t\t\t\t\ttypeof addr === \"string\" ? port : addr?.port || port;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] ✅ Transformer Mesh Gateway READY and listening on ${actualHost}:${assignedPort}`,\n\t\t\t\t);\n\t\t\t\tresolve(assignedPort);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic async stop() {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t\tthis.netServer.close();\n\t\tthis.h2Server.close();\n\t\tthis.h1Server.close();\n\t}\n\n\tpublic getRouter(): LiopMcpRouter {\n\t\treturn this.router;\n\t}\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-PWCXZWSE.js';import {a as a$4}from'./chunk-DBXGYHKY.js';import {a as a$2}from'./chunk-SB5XJXKV.js';import {a as a$3,c}from'./chunk-V5MKJT6S.js';import {a}from'./chunk-S6RJHZV2.js';import*as K from'crypto';import*as ce from'@grpc/grpc-js';var W=class{name="o200k_base";countFn;constructor(e,t){this.countFn=e,t&&t(1e4);}countTokens(e){return e.length===0?0:this.countFn(e)}},B=class{name="heuristic (chars/4)";countTokens(e){return e.length===0?0:Math.ceil(e.length/4)}};async function fe(){try{let c=await import('gpt-tokenizer'),e=new W(c.countTokens,c.setMergeCacheSize);return a.debug("[LIOP-Economy] Token estimator initialized: o200k_base"),e}catch{return a.info("[LIOP-Economy] gpt-tokenizer unavailable, falling back to heuristic estimator"),new B}}function he(){return new B}var N="1.9.1";var ge=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ee(c){let e=new Set([c]),t=new Set,r=c.match(ge);if(!r)return ()=>false;let n={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(n.prerelease!=null)return function(a){return a===c};function i(s){return t.add(s),false}function o(s){return e.add(s),true}return function(a){if(e.has(a))return true;if(t.has(a))return false;let l=a.match(ge);if(!l)return i(a);let u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||n.major!==u.major?i(a):n.major===0?n.minor===u.minor&&n.patch<=u.patch?o(a):i(a):n.minor<=u.minor?o(a):i(a)}}var Te=Ee(N);var ke=N.split(".")[0],$=Symbol.for(`opentelemetry.js.api.${ke}`),A=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function V(c,e,t,r=false){var n;let i=A[$]=(n=A[$])!==null&&n!==void 0?n:{version:N};if(!r&&i[c]){let o=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${c}`);return t.error(o.stack||o.message),false}if(i.version!==N){let o=new Error(`@opentelemetry/api: Registration of version v${i.version} for ${c} does not match previously registered API v${N}`);return t.error(o.stack||o.message),false}return i[c]=e,t.debug(`@opentelemetry/api: Registered a global for ${c} v${N}.`),true}function b(c){var e,t;let r=(e=A[$])===null||e===void 0?void 0:e.version;if(!(!r||!Te(r)))return (t=A[$])===null||t===void 0?void 0:t[c]}function F(c,e){e.debug(`@opentelemetry/api: Unregistering a global for ${c} v${N}.`);let t=A[$];t&&delete t[c];}var z=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger";}debug(...e){return x("debug",this._namespace,e)}error(...e){return x("error",this._namespace,e)}info(...e){return x("info",this._namespace,e)}warn(...e){return x("warn",this._namespace,e)}verbose(...e){return x("verbose",this._namespace,e)}};function x(c,e,t){let r=b("diag");if(r)return r[c](e,...t)}var v;(function(c){c[c.NONE=0]="NONE",c[c.ERROR=30]="ERROR",c[c.WARN=50]="WARN",c[c.INFO=60]="INFO",c[c.DEBUG=70]="DEBUG",c[c.VERBOSE=80]="VERBOSE",c[c.ALL=9999]="ALL";})(v||(v={}));function ye(c,e){c<v.NONE?c=v.NONE:c>v.ALL&&(c=v.ALL),e=e||{};function t(r,n){let i=e[r];return typeof i=="function"&&c>=n?i.bind(e):function(){}}return {error:t("error",v.ERROR),warn:t("warn",v.WARN),info:t("info",v.INFO),debug:t("debug",v.DEBUG),verbose:t("verbose",v.VERBOSE)}}var Se="diag",D=class c{static instance(){return this._instance||(this._instance=new c),this._instance}constructor(){function e(n){return function(...i){let o=b("diag");if(o)return o[n](...i)}}let t=this,r=(n,i={logLevel:v.INFO})=>{var o,s,a;if(n===t){let p=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((o=p.stack)!==null&&o!==void 0?o:p.message),false}typeof i=="number"&&(i={logLevel:i});let l=b("diag"),u=ye((s=i.logLevel)!==null&&s!==void 0?s:v.INFO,n);if(l&&!i.suppressOverrideMessage){let p=(a=new Error().stack)!==null&&a!==void 0?a:"<failed to generate stacktrace>";l.warn(`Current logger will be overwritten from ${p}`),u.warn(`Current logger will overwrite one already registered from ${p}`);}return V("diag",u,t,true)};t.setLogger=r,t.disable=()=>{F(Se,t);},t.createComponentLogger=n=>new z(n),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error");}};var J=class{constructor(){}createGauge(e,t){return Ne}createHistogram(e,t){return we}createCounter(e,t){return Re}createUpDownCounter(e,t){return be}createObservableGauge(e,t){return Le}createObservableCounter(e,t){return Ce}createObservableUpDownCounter(e,t){return Me}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}},C=class{},Q=class extends C{add(e,t){}},Z=class extends C{add(e,t){}},X=class extends C{record(e,t){}},Y=class extends C{record(e,t){}},U=class{addCallback(e){}removeCallback(e){}},ee=class extends U{},te=class extends U{},oe=class extends U{},_e=new J,Re=new Q,Ne=new X,we=new Y,be=new Z,Ce=new ee,Le=new te,Me=new oe;var re=class{getMeter(e,t,r){return _e}},Oe=new re;var ne="metrics",G=class c{constructor(){}static getInstance(){return this._instance||(this._instance=new c),this._instance}setGlobalMeterProvider(e){return V(ne,e,D.instance())}getMeterProvider(){return b(ne)||Oe}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){F(ne,D.instance());}};var se=G.getInstance();var $e="@nekzus/liop",Ae="1.2.0-alpha.9",xe=[1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864],De=[.01,.02,.04,.08,.16,.32,.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92],H=class{tokenUsage;operationDuration;active=false;constructor(){try{let e=se.getMeter($e,Ae);this.tokenUsage=e.createHistogram("gen_ai.client.token.usage",{description:"Number of tokens used in LIOP Logic-on-Origin operations",unit:"{token}",advice:{explicitBucketBoundaries:xe}}),this.operationDuration=e.createHistogram("gen_ai.client.operation.duration",{description:"Duration of LIOP operations",unit:"s",advice:{explicitBucketBoundaries:De}}),this.active=!0,a.debug("[LIOP-OTel] gen_ai.* metrics bridge initialized");}catch(e){a.debug(`[LIOP-OTel] Bridge disabled: ${e instanceof Error?e.message:String(e)}`);let t={record:()=>{}};this.tokenUsage=t,this.operationDuration=t;}}recordTokens(e,t,r,n){this.tokenUsage.record(e,{"gen_ai.system":"liop","gen_ai.operation.name":r,"gen_ai.token.type":t,"gen_ai.request.model":"liop-mesh",...n?{"liop.tool.name":n}:{}});}recordDuration(e,t,r){this.operationDuration.record(e/1e3,{"gen_ai.system":"liop","gen_ai.operation.name":t,...r?{"error.type":r}:{}});}isActive(){return this.active}};var Ue={tools_list:"chat",tool_call:"execute_tool",resource_read:"chat",resource_list:"chat",prompt_get:"chat",prompt_list:"chat",diagnostic:"chat"},P=class c{static instance=null;operations=[];sessionId;startedAt;estimator;otelBridge;constructor(){this.sessionId=crypto.randomUUID(),this.startedAt=Date.now(),this.estimator=he(),this.otelBridge=new H,this.initRealEstimator();}initRealEstimator(){fe().then(e=>{this.estimator=e;}).catch(()=>{});}static getInstance(){return c.instance||(c.instance=new c),c.instance}countTokens(e){try{return this.estimator.countTokens(e)}catch{return Math.ceil(e.length/4)}}record(e){let t={...e,timestamp:Date.now()};this.operations.push(t);try{let r=Ue[e.type]||"chat";e.estimatedInputTokens>0&&this.otelBridge.recordTokens(e.estimatedInputTokens,"input",r,e.toolName),e.estimatedOutputTokens>0&&this.otelBridge.recordTokens(e.estimatedOutputTokens,"output",r,e.toolName),e.durationMs!==void 0&&this.otelBridge.recordDuration(e.durationMs,r);}catch{}}estimateTokens(e){return this.countTokens(e)}getReport(){return {sessionId:this.sessionId,operations:[...this.operations],totalInputTokens:this.operations.reduce((e,t)=>e+t.estimatedInputTokens,0),totalOutputTokens:this.operations.reduce((e,t)=>e+t.estimatedOutputTokens,0),estimatorName:this.estimator.name,sessionUptimeMs:Date.now()-this.startedAt}}getPerToolReport(){let e=new Map;for(let t of this.operations){let r=t.toolName||t.method,n=e.get(r)||{input:0,output:0,calls:0,avgDurationMs:0},i=n.avgDurationMs*n.calls+(t.durationMs||0),o=n.calls+1;e.set(r,{input:n.input+t.estimatedInputTokens,output:n.output+t.estimatedOutputTokens,calls:o,avgDurationMs:o>0?i/o:0});}return e}formatStatusBlock(){let e=this.getReport();if(e.operations.length===0)return "";let t=this.formatUptime(e.sessionUptimeMs),r=e.totalInputTokens+e.totalOutputTokens,n=new Map;for(let d of e.operations){let g=d.type,T=n.get(g)||{count:0,input:0,output:0};n.set(g,{count:T.count+1,input:T.input+d.estimatedInputTokens,output:T.output+d.estimatedOutputTokens});}let i=Array.from(n.entries()),o=i.map(([d,g],T)=>{let y=T===i.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",R=g.output>0?` / ${g.output.toLocaleString()} out`:"";return `${y} ${d} \xD7${g.count} \u2192 ${g.input.toLocaleString()} in${R}`}),s=this.getPerToolReport(),a=Array.from(s.entries()).filter(([d])=>d!=="tools/list"&&d!=="LiopMeshStatus"),l=[];a.length>0&&(l.push("\u251C\u2500 By Tool:"),a.forEach(([d,g],T)=>{let y=T===a.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",R=g.output>0?` / ${g.output.toLocaleString()} out`:"",k=g.avgDurationMs>0?` ~${Math.round(g.avgDurationMs)}ms`:"";l.push(`${y} ${d}: ${g.input.toLocaleString()} in${R} (\xD7${g.calls})${k}`);}));let u=e.operations.filter(d=>d.durationMs!==void 0),p=u.length>0?Math.round(u.reduce((d,g)=>d+(g.durationMs||0),0)/u.length):0,m=this.otelBridge.isActive()?"gen_ai.client.token.usage \u2192 active":"disabled";return [`
|
|
2
2
|
Token Economy:`,`\u251C\u2500 Session: ${e.sessionId.slice(0,8)} (${t})`,`\u251C\u2500 Estimator: ${e.estimatorName}`,`\u251C\u2500 Operations: ${e.operations.length}`,...o,`\u251C\u2500 Total: ${e.totalInputTokens.toLocaleString()} in / ${e.totalOutputTokens.toLocaleString()} out (${r.toLocaleString()} combined)`,...l,...p>0?[`\u251C\u2500 Avg Latency: ${p}ms`]:[],`\u2514\u2500 OTel: ${m}`].join(`
|
|
3
3
|
`)}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return `${t}s`;let r=Math.floor(t/60),n=t%60;if(r<60)return `${r}m ${n}s`;let i=Math.floor(r/60),o=r%60;return `${i}h ${o}m`}reset(){this.operations=[];}static destroy(){c.instance=null;}};function L(){let c=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(c==="0"||c==="false"||c==="no")}function ie(c){let e=c,t=[`
|
|
4
4
|
|
|
@@ -6,7 +6,7 @@ Token Economy:`,`\u251C\u2500 Session: ${e.sessionId.slice(0,8)} (${t})`,`\u251C
|
|
|
6
6
|
\r
|
|
7
7
|
[LIOP-PROTO-V1:`,`
|
|
8
8
|
[LIOP-PROTO-V1:`];for(let r of t){let n=e.indexOf(r);if(n!==-1){e=e.slice(0,n);break}}return e.trimEnd()}var ve=300,ae=5,Ie=class c$1{constructor(e,t=null,r=50051){this.liopServer=e;this.meshNode=t;this.defaultRpcPort=r;this.meshNode&&(this.meshNode.registerManifestHandler(()=>{let n=this.liopServer.listTools().map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema})),i=this.liopServer.listResources().map(s=>({name:s.name,uri:s.uri,description:s.description,mimeType:s.mimeType})),o=this.liopServer.config;return {peerId:this.meshNode?.getPeerId()||"unknown",grpcPort:this.defaultRpcPort,tools:[...n],resources:i,serverInfo:this.liopServer.getServerInfo(),authRequired:this.liopServer.jwtValidator!==void 0,tokenSlug:o?.tokenSlug,taxonomy:o?.taxonomy?{domain:o.taxonomy.domain||"Unknown Domain",clearanceTier:o.taxonomy.clearanceTier??0,executionTypes:o.taxonomy.executionTypes||[]}:void 0}}),this.meshNode.announceManifest().catch(n=>{a.info(`[LIOP-Router] Failed to announce manifest: ${n instanceof Error?n.message:String(n)}`);})),process.env.LIOP_DIAGNOSTIC_LEVEL==="full"&&process.stderr.write(`\u26A0\uFE0F [LIOP-Security] Diagnostic level set to FULL \u2014 PeerIDs and network topology are exposed. Do NOT use in production.
|
|
9
|
-
`);}manifestCache=new Map;currentDiscovery=null;verifier=new a$1;onToolsChanged;manifestFailureState=new Map;static MANIFEST_FAILURE_BASE_COOLDOWN_MS=15e3;static MANIFEST_FAILURE_MAX_COOLDOWN_MS=5*6e4;static MANIFEST_SKIP_LOG_THROTTLE_MS=3e4;shouldSkipManifestQuery(e){let t=this.manifestFailureState.get(e);if(!t)return false;let r=Date.now();return r>=t.cooldownUntil?false:(r-t.lastSkipLogAt>c$1.MANIFEST_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Router] Skipping manifest query for ${e} during cooldown (${Math.ceil((t.cooldownUntil-r)/1e3)}s remaining)`),t.lastSkipLogAt=r),true)}recordManifestQuerySuccess(e){this.manifestFailureState.delete(e);}recordManifestQueryFailure(e){let t=Date.now(),n=(this.manifestFailureState.get(e)?.failures||0)+1,i=Math.min(c$1.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,n-1),c$1.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(e,{failures:n,cooldownUntil:t+i,lastSkipLogAt:0});}async dispatch(e,t){let{method:r,params:n,id:i}=e;if(a.info(`[LIOP-Router] Processing: ${r}`),this.liopServer.jwtValidator){let o=a$2(r,t??null);if(!o.allowed)return a.info(`[LIOP-Router] RBAC Access Denied for method '${r}': ${o.reason}`),{jsonrpc:"2.0",id:i,error:{code:-32099,message:o.reason||"Access Denied"}}}switch(r){case "initialize":return {jsonrpc:"2.0",id:i,result:{protocolVersion:"2025-11-25",capabilities:{tools:{listChanged:true},resources:{listChanged:true},prompts:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()}};case "notifications/initialized":return this.kickDiscoveryAfterInitialized().catch(()=>{}),null;case "notifications/cancelled":return null;case "ping":return {jsonrpc:"2.0",id:i,result:{}};case "tools/list":{let o=this.liopServer.listTools(),s=await this.getRemoteTools(),a$1=L()?o.map(d=>({...d,description:ie(d.description??"")})):o;a.info(`[LIOP-Router] tools/list: ${o.length} local, ${s.length} remote tools found`);let u=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...a$1,...s],p=
|
|
9
|
+
`);}manifestCache=new Map;currentDiscovery=null;verifier=new a$1;onToolsChanged;manifestFailureState=new Map;static MANIFEST_FAILURE_BASE_COOLDOWN_MS=15e3;static MANIFEST_FAILURE_MAX_COOLDOWN_MS=5*6e4;static MANIFEST_SKIP_LOG_THROTTLE_MS=3e4;shouldSkipManifestQuery(e){let t=this.manifestFailureState.get(e);if(!t)return false;let r=Date.now();return r>=t.cooldownUntil?false:(r-t.lastSkipLogAt>c$1.MANIFEST_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Router] Skipping manifest query for ${e} during cooldown (${Math.ceil((t.cooldownUntil-r)/1e3)}s remaining)`),t.lastSkipLogAt=r),true)}recordManifestQuerySuccess(e){this.manifestFailureState.delete(e);}recordManifestQueryFailure(e){let t=Date.now(),n=(this.manifestFailureState.get(e)?.failures||0)+1,i=Math.min(c$1.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,n-1),c$1.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(e,{failures:n,cooldownUntil:t+i,lastSkipLogAt:0});}async dispatch(e,t){let{method:r,params:n,id:i}=e;if(a.info(`[LIOP-Router] Processing: ${r}`),this.liopServer.jwtValidator){let o=a$2(r,t??null);if(!o.allowed)return a.info(`[LIOP-Router] RBAC Access Denied for method '${r}': ${o.reason}`),{jsonrpc:"2.0",id:i,error:{code:-32099,message:o.reason||"Access Denied"}}}switch(r){case "initialize":return {jsonrpc:"2.0",id:i,result:{protocolVersion:"2025-11-25",capabilities:{tools:{listChanged:true},resources:{listChanged:true},prompts:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()}};case "notifications/initialized":return this.kickDiscoveryAfterInitialized().catch(()=>{}),null;case "notifications/cancelled":return null;case "ping":return {jsonrpc:"2.0",id:i,result:{}};case "tools/list":{let o=this.liopServer.listTools(),s=await this.getRemoteTools(),a$1=L()?o.map(d=>({...d,description:ie(d.description??"")})):o;a.info(`[LIOP-Router] tools/list: ${o.length} local, ${s.length} remote tools found`);let u=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...a$1,...s],p=P.getInstance(),m=JSON.stringify(u),h=JSON.stringify({tools:u});return p.record({type:"tools_list",method:"tools/list",estimatedInputTokens:p.countTokens(m),estimatedOutputTokens:p.countTokens(h)}),{jsonrpc:"2.0",id:i,result:{tools:u}}}case "tools/call":return this.transcodeMcpToLiop(i,n,t?.token);case "resources/list":{let o=this.liopServer.listResources(),s=await this.getRemoteResources(),a=[...o,...s],l=P.getInstance(),u=JSON.stringify(a);return l.record({type:"resource_list",method:"resources/list",estimatedInputTokens:0,estimatedOutputTokens:l.countTokens(u)}),{jsonrpc:"2.0",id:i,result:{resources:a}}}case "resources/read":{let o=n;if(!o?.uri)return {jsonrpc:"2.0",id:i,error:{code:-32602,message:"Missing resource uri"}};try{let s=Date.now(),a=await this.liopServer.readResource(o.uri),l=P.getInstance(),u=JSON.stringify(a);return l.record({type:"resource_read",method:"resources/read",toolName:o.uri,estimatedInputTokens:l.countTokens(o.uri),estimatedOutputTokens:l.countTokens(u),durationMs:Date.now()-s}),{jsonrpc:"2.0",id:i,result:a}}catch(s){let a$1=o.uri;for(let{manifest:l}of this.manifestCache.values()){let u=l.resources.find(p=>p.uri===a$1);if(u)return a.info(`[LIOP-Router] Resolved resource ${a$1} from cache (Peer: ${l.peerId})`),{jsonrpc:"2.0",id:i,result:{contents:[{uri:u.uri,mimeType:u.mimeType||"text/plain",text:u.text||u.description||"No content provided"}]}}}return {jsonrpc:"2.0",id:i,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}}}}case "prompts/list":{let o=this.liopServer.listPrompts(),s=P.getInstance(),a=JSON.stringify(o);return s.record({type:"prompt_list",method:"prompts/list",estimatedInputTokens:0,estimatedOutputTokens:s.countTokens(a)}),{jsonrpc:"2.0",id:i,result:{prompts:o}}}case "prompts/get":{let o=n;if(!o?.name)return {jsonrpc:"2.0",id:i,error:{code:-32602,message:"Missing prompt name"}};try{let s=Date.now(),a=await this.liopServer.getPrompt({name:o.name,arguments:o.arguments||{}}),l=P.getInstance(),u=JSON.stringify({name:o.name,arguments:o.arguments}),p=JSON.stringify(a);return l.record({type:"prompt_get",method:"prompts/get",toolName:o.name,estimatedInputTokens:l.countTokens(u),estimatedOutputTokens:l.countTokens(p),durationMs:Date.now()-s}),{jsonrpc:"2.0",id:i,result:a}}catch(s){return {jsonrpc:"2.0",id:i,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}}}}default:return {jsonrpc:"2.0",id:i,error:{code:-32601,message:`Method not found: ${r}`}}}}kickDiscoveryAfterInitialized(){return (async()=>{await new Promise(e=>setTimeout(e,250)),await Promise.race([this.refreshManifestCache(true),new Promise(e=>setTimeout(e,15e3))]).catch(()=>{});})()}async refreshManifestCache(e=false){if(this.meshNode){if(this.currentDiscovery)return this.currentDiscovery;if(!e&&this.manifestCache.size>0){let t=Date.now();if(Array.from(this.manifestCache.values()).every(({cachedAt:n})=>t-n<ve*1e3))return}return this.currentDiscovery=(async()=>{try{let t=Array.from(this.manifestCache.values()).reduce((m,{manifest:h})=>m+h.tools.length,0);if(this.manifestCache.size===0)for(let m=0;m<3;m++){if((this.meshNode.node?.getConnections().length||0)>0){a.info("[LIOP-Router] P2P Connection established. Starting discovery...");break}a.info(`[LIOP-Router] Waiting for P2P connections (attempt ${m+1}/10)...`),await new Promise(d=>setTimeout(d,1e3));}let r=[],n=this.manifestCache.size===0?5:1;for(let m=0;m<n;m++){for(let T=0;T<ae;T++){r=await this.meshNode?.discoverManifestProviders()||[];let y=this.meshNode?.getPeerId();if(r.filter(k=>k!==y).length>0)break;T<ae-1&&(a.info(`[LIOP-Router] DHT discovery attempt ${T+1}/${ae}...`),await new Promise(k=>setTimeout(k,1e3)));}let h=this.meshNode.node?.getConnections().map(T=>T.remotePeer.toString())||[];h.length>0&&(r=Array.from(new Set([...r,...h])));let d=this.meshNode?.getPeerId();if(r.filter(T=>T!==d).length>0)break;m<n-1&&(a.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${m+1}/${n})...`),await new Promise(T=>setTimeout(T,1e3)));}if(r.length===0){a.info("[LIOP-Router] No manifest providers found after all attempts.");return}e||a.info(`[LIOP-Router] Discovered ${r.length} candidate manifest providers`);let i=new Set((this.meshNode.node?.getConnections?.()||[]).map(m=>m.remotePeer.toString()));r=[...r].sort((m,h)=>{let d=i.has(m)?1:0;return (i.has(h)?1:0)-d});let o=0,s=0,a$1=!1,l=this.meshNode?.getPeerId(),u=r.filter(m=>{if(!this.meshNode||m===l||this.shouldSkipManifestQuery(m))return !1;let h=this.manifestCache.get(m);return h&&Date.now()-h.cachedAt<ve*1e3?(o++,!1):!0}),p=await Promise.allSettled(u.map(async m=>this.meshNode?(a.info(`[LIOP-Router] Querying manifest from: ${m}`),{peerId:m,manifest:await this.meshNode.queryManifest(m)}):null));for(let m of p)if(m.status==="fulfilled"&&m.value?.manifest){let{peerId:h,manifest:d}=m.value;this.manifestCache.set(h,{manifest:d,cachedAt:Date.now()}),this.recordManifestQuerySuccess(h),a$1=!0,o++,a.info(`[LIOP-Router] Manifest received from ${h} (${d.tools.length} tools)`);}else m.status==="fulfilled"&&m.value?(this.recordManifestQueryFailure(m.value.peerId),s++,a.info(`[LIOP-Router] Manifest query returned NULL for ${m.value.peerId}`)):m.status==="rejected"&&(s++,a.info("[LIOP-Router] Fatal error querying manifest:",m.reason instanceof Error?m.reason.message:String(m.reason)));this._discoveryStats={candidates:r.length,success:o,failures:s,lastDiscovery:Date.now()},a$1&&Array.from(this.manifestCache.values()).reduce((h,{manifest:d})=>h+d.tools.length,0)!==t&&this.onToolsChanged&&(process.stderr.write(`[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.
|
|
10
10
|
`),this.onToolsChanged());}finally{this.currentDiscovery=null;}})(),this.currentDiscovery}}getCacheSize(){return this.manifestCache.size}async getRemoteTools(){let e=Number.parseInt(process.env.LIOP_EXPECTED_PROVIDERS??"1",10);if(this.manifestCache.size<e&&this.meshNode){let i=Number.parseInt(process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS??"8000",10),o=Number.isFinite(i)&&i>0?i:12e3,s=Date.now()+o,a$1=0,l=-1;for(;Date.now()<s&&!(this.manifestCache.size>=e||(await Promise.race([this.refreshManifestCache(true),new Promise(u=>setTimeout(u,3e3))]).catch(()=>{}),this.manifestCache.size>=e));){if(this.manifestCache.size===l){if(a$1++,a$1>=3&&this.manifestCache.size>0){a.info(`[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${e}. Proceeding with available mesh.`);break}}else a$1=0,l=this.manifestCache.size;await new Promise(u=>setTimeout(u,1e3));}this.manifestCache.size<e&&(a.info(`[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${e} providers. Some tools may be unavailable. Check Docker containers.`),this.refreshManifestCache(true).catch(()=>{}));}let t=[],r=new Set,n=new Set(this.liopServer.listTools().map(i=>i.name));for(let[i,{manifest:o}]of this.manifestCache.entries())for(let s of o.tools){if(s.name==="LiopMeshStatus")continue;let a=s.name;(r.has(s.name)||n.has(s.name))&&(a=`${s.name}_${i.slice(-4)}`),r.add(a);let l=o.serverInfo?.name||"Unknown Provider",u=s.description||`Remote tool from ${l}`,p={name:a,description:L()?ie(u):u,inputSchema:s.inputSchema||{type:"object",properties:{}}};typeof p.inputSchema=="object"&&!p.inputSchema.type&&(p.inputSchema.type="object"),typeof p.inputSchema=="object"&&!p.inputSchema.properties&&(p.inputSchema.properties={});let m="";o.taxonomy&&(m=`
|
|
11
11
|
[LIOP-DOMAIN: ${o.taxonomy.domain}]`);let h=p.inputSchema.properties||{},d="";!L()&&h.payload&&(d=`
|
|
12
12
|
[REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!L()&&p.description.includes("STRICT SCHEMA ADHERENCE")&&(p.description=p.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let g=L()?`
|
|
@@ -20,14 +20,14 @@ Execution Types: ${n.taxonomy.executionTypes.join(", ")}`));let l=`
|
|
|
20
20
|
|
|
21
21
|
[LIOP Zero-Trust Origin]
|
|
22
22
|
Provider: ${s}
|
|
23
|
-
Network ID: ${r}${a}`;o.uri.startsWith("liop://schema/")?(o.name=`[SCHEMA] ${o.name}`,o.description=`[CRITICAL SCHEMA] ${o.description||"Data Dictionary for Zero-Shot Autonomy"}${l}`):o.description=o.description?`${o.description}${l}`:l.trim(),e.push(o),t.add(i.uri);}return e}resolveManifestTarget(e){for(let[r,{manifest:n}]of this.manifestCache.entries())if(n.tools.find(o=>o.name===e))return {peerId:r,originalToolName:e};let t=e.split("_");if(t.length>1){let r=t.pop(),n=t.join("_");for(let[i,{manifest:o}]of this.manifestCache.entries())if(i.endsWith(r||"")&&o.tools.find(a=>a.name===n))return {peerId:i,originalToolName:n}}return null}redactPeerId(e){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?e:`***${e.slice(-8)}`}async transcodeMcpToLiop(e,t,r){let n=t.name;if(n==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let o=this._discoveryStats||{candidates:0,success:0,failures:0},s=this.manifestCache.size,a=this.meshNode?"Active":"Offline",l=Array.from(this.manifestCache.values()).reduce((
|
|
24
|
-
`):"",T=this.meshNode?this.meshNode.getRoutingTableSize():0,y=this.meshNode?.getPeerId()||"Offline",R=y==="Offline"?y:this.redactPeerId(y),k=Array.from(this.manifestCache.entries()).flatMap(([
|
|
23
|
+
Network ID: ${r}${a}`;o.uri.startsWith("liop://schema/")?(o.name=`[SCHEMA] ${o.name}`,o.description=`[CRITICAL SCHEMA] ${o.description||"Data Dictionary for Zero-Shot Autonomy"}${l}`):o.description=o.description?`${o.description}${l}`:l.trim(),e.push(o),t.add(i.uri);}return e}resolveManifestTarget(e){for(let[r,{manifest:n}]of this.manifestCache.entries())if(n.tools.find(o=>o.name===e))return {peerId:r,originalToolName:e};let t=e.split("_");if(t.length>1){let r=t.pop(),n=t.join("_");for(let[i,{manifest:o}]of this.manifestCache.entries())if(i.endsWith(r||"")&&o.tools.find(a=>a.name===n))return {peerId:i,originalToolName:n}}return null}redactPeerId(e){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?e:`***${e.slice(-8)}`}async transcodeMcpToLiop(e,t,r){let n=t.name;if(n==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let o=this._discoveryStats||{candidates:0,success:0,failures:0},s=this.manifestCache.size,a=this.meshNode?"Active":"Offline",l=Array.from(this.manifestCache.values()).reduce((E,{manifest:I})=>E+I.tools.length,0),u=this.meshNode?this.meshNode.node?.getConnections().length:0,p=this.meshNode&&this.meshNode.config?.bootstrapNodes?this.meshNode.config.bootstrapNodes:[],m=p.length,d=(process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")!=="minimal",g=d?p.map(E=>{let I=E.split("/"),S=I[I.length-1];return ` \u2022 ${S?S.slice(-8):"Unknown"} (bootstrap)`}).join(`
|
|
24
|
+
`):"",T=this.meshNode?this.meshNode.getRoutingTableSize():0,y=this.meshNode?.getPeerId()||"Offline",R=y==="Offline"?y:this.redactPeerId(y),k=Array.from(this.manifestCache.entries()).flatMap(([E,{manifest:I}])=>I.tools.map(S=>` \u2022 ${S.name} (from origin: ${this.redactPeerId(E)})`)).join(`
|
|
25
25
|
`),j=[`LIOP Mesh Status: ${a==="Active"?"Active":"Offline"}`,`Local Agent Identity: ${R}`,`Network: ${u} Conns | ${T} Mesh Nodes | ${m} Bootstraps`,d&&m>0?`
|
|
26
26
|
Active Bootstraps:
|
|
27
27
|
${g}
|
|
28
28
|
`:"",`Discovery: ${o.candidates} Candidates | ${o.success} OK | ${o.failures} FAIL`,`Tooling: ${s} Providers | ${l} Total Remote Tools`,l>0?`
|
|
29
29
|
Discovered Remote Tools (Zero-Trust Origins):
|
|
30
30
|
${k}`:`
|
|
31
|
-
No remote tools discovered yet.`,
|
|
32
|
-
`),M=
|
|
33
|
-
//# sourceMappingURL=chunk-
|
|
31
|
+
No remote tools discovered yet.`,P.getInstance().formatStatusBlock()].filter(E=>E!=="").join(`
|
|
32
|
+
`),M=P.getInstance();return M.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:M.countTokens(j)}),{jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:j}]}}}let i=this.liopServer.listTools().some(o=>o.name===n);if(!i&&this.meshNode){let o=this.resolveManifestTarget(n);if(o||(await this.refreshManifestCache(),o=this.resolveManifestTarget(n)),o){a.info(`[LIOP-Router] Resolved ${n} via manifest cache (Peer: ${o.peerId}, Original: ${o.originalToolName})`);let a$1=this.manifestCache.get(o.peerId),l=r;if(a$1?.manifest.authRequired){let u=r||await this.getOrAcquireMeshAgentToken(o.peerId);if(!u){let p=a$1.manifest.serverInfo?.name?.toLowerCase()||"unknown",m=a$1.manifest.tokenSlug,h=o.peerId.slice(-8).toUpperCase(),d=m?`LIOP_TOKEN_${m}`:`LIOP_TOKEN_${p.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${p}) requires an access token. Please define the ${d} or LIOP_TOKEN_${h} environment variable on your agent/client host.`}],isError:true}}}l=u;}return this.routeToRemoteProvider(e,o.originalToolName,o.peerId,t,l)}let s=[];for(let a=0;a<3&&(s=await this.meshNode.findProviders(n),!(s.length>0));a++)a<2&&await new Promise(l=>setTimeout(l,1e3));if(s.length>0)return this.routeToRemoteProvider(e,n,s[0],t,r)}if(i)try{let o=Date.now(),s=await this.liopServer.callTool({name:n,arguments:t.arguments||{}}),a=P.getInstance(),l=JSON.stringify(t.arguments||{}),u=JSON.stringify(s);return a.record({type:"tool_call",method:"tools/call",toolName:n,estimatedInputTokens:a.countTokens(l),estimatedOutputTokens:a.countTokens(u),durationMs:Date.now()-o}),{jsonrpc:"2.0",id:e,result:s}}catch(o){return {jsonrpc:"2.0",id:e,error:{code:-32e3,message:o instanceof Error?o.message:String(o)}}}return {jsonrpc:"2.0",id:e,error:{code:-32002,message:`No provider found for tool: ${n}. Ensure the provider node is active and connected to the mesh.`}}}async routeToRemoteProvider(e,t,r,n,i){if(!this.meshNode)return {jsonrpc:"2.0",id:e,error:{code:-32603,message:"Mesh Node inactive"}};let o=this.manifestCache.get(r),s=this.defaultRpcPort;if(o)s=o.manifest.grpcPort;else {let d=await this.meshNode.queryManifest(r);d&&(s=d.grpcPort,this.manifestCache.set(r,{manifest:d,cachedAt:Date.now()}),o=this.manifestCache.get(r));}if((process.env.LIOP_USE_PUBLISHED_GRPC_PORTS==="1"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test")&&o){let d=o.manifest.serverInfo?.name?.toLowerCase()||"";d.includes("vault")?s=13011:d.includes("bank")?s=13021:d.includes("oracle")&&(s=13031);}let l=await this.meshNode.resolvePeer(r),u=null,p=await import('os'),m=Object.values(p.networkInterfaces()).flat().filter(d=>d?.family==="IPv4").map(d=>d?.address);for(let d of l){let g=d.split("/"),T=g.indexOf("ip4");if(T!==-1){let y=g[T+1];if(y==="127.0.0.1"||m.includes(y)){u=`127.0.0.1:${s}`;break}u||(u=`${y}:${s}`);}}u||(u=`127.0.0.1:${s}`),a.info(`[LIOP-Router] Dynamic route: ${t} -> ${u} (PeerID: ${r})`);let h=new a$3.LogicMesh(u,c());return this.performTranscoding(e,h,t,n,r,i)}meshAgentToken;async getOrAcquireMeshAgentToken(e){if(e){let s=this.manifestCache.get(e),a$1=s?.manifest.serverInfo?.name?.toLowerCase()||"",l,u=s?.manifest.tokenSlug;if(u){let p=`LIOP_TOKEN_${u}`;l=process.env[p]||process.env[`LIOP_OAUTH_TOKEN_${u}`],a.info(`[LIOP-Router] Step0 tokenSlug=${u} envKey=${p} found=${!!l} peer=${e.slice(-8)}`);}else a.info(`[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${e.slice(-8)} provider=${a$1}`);if(!l){let p=e.slice(-8).toUpperCase();l=process.env[`LIOP_TOKEN_${p}`]||process.env[`LIOP_OAUTH_TOKEN_${p}`];}if(!l&&a$1){let p=a$1.toUpperCase().replace(/[^A-Z0-9_]/g,"_");l=process.env[`LIOP_TOKEN_${p}`]||process.env[`LIOP_OAUTH_TOKEN_${p}`];}if(l)return a.info(`[LIOP-Router] Resolved node-specific token for peer ${e.slice(-8)} (${a$1||"unknown"})`),l}if(this.meshAgentToken)return this.meshAgentToken;let t=process.env.LIOP_OAUTH_TOKEN||process.env.LIOP_TOKEN;if(t)return this.meshAgentToken=t,this.meshAgentToken;let r=process.env.LIOP_NEXUS_URL;if(!r)return;let n=process.env.LIOP_OAUTH_CLIENT_ID||process.env.LIOP_CLIENT_ID||"liop-mesh-agent",i=process.env.LIOP_OAUTH_CLIENT_SECRET||process.env.LIOP_CLIENT_SECRET||"dev-secret-change-me",o=process.env.LIOP_OAUTH_AUDIENCE||process.env.LIOP_AUDIENCE||"urn:liop:mesh:api";try{let a$1=`${r.endsWith("/oidc")?r:`${r}/oidc`}/token`;a.info(`[LIOP-Router] Proactively acquiring M2M token from Nexus: ${a$1}`);let l=new URLSearchParams({grant_type:"client_credentials",scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",resource:o,client_id:n,client_secret:i}),u=await fetch(a$1,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!u.ok){let m=await u.text();a.warn(`[LIOP-Router] M2M Token acquisition failed: ${u.status} ${m}`);return}let p=await u.json();if(p.access_token)return this.meshAgentToken=p.access_token,a.info("[LIOP-Router] M2M Token acquired successfully for router routing."),this.meshAgentToken}catch(s){a.warn(`[LIOP-Router] Failed to acquire M2M token: ${s instanceof Error?s.message:String(s)}`);}}async performTranscoding(e,t,r,n,i,o){let s=r,a=this.meshNode?await this.meshNode.sign(Buffer.from(s)):Buffer.from([]),l=Date.now(),u=o;if(u||(u=await this.getOrAcquireMeshAgentToken(i)),i){let p=this.manifestCache.get(i);if(p?.manifest.authRequired&&!u){let m=p.manifest.serverInfo?.name?.toLowerCase()||"unknown",h=p.manifest.tokenSlug,d=i.slice(-8).toUpperCase(),g=h?`LIOP_TOKEN_${h}`:`LIOP_TOKEN_${m.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${m}) requires an access token. Please define the ${g} or LIOP_TOKEN_${d} environment variable on your agent/client host.`}],isError:true}}}}return new Promise(p=>{let m=new ce.Metadata;u&&m.add("authorization",`Bearer ${u}`),t.negotiateIntent({agent_did:`did:liop:${this.meshNode?.getPeerId()||"mcp-proxy"}`,capability_hash:s,proof_of_intent:a},m,async(h,d)=>{if(h||!d.accepted)return p({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`PQC Handshake Failed: ${h?.message||"Rejected"}`}],isError:true}});let{ciphertext:g,sharedSecret:T}=await a$4.encapsulateAsymmetric(d.kyber_public_key),y=JSON.stringify(n.arguments||{}),R=`return { "__liop_proxy_tool": "${r}", "__liop_proxy_args": ${y} };`,k=K.randomBytes(12),j=this.encryptWithNonce(Buffer.from(R),T,k),M=new ce.Metadata;u&&M.add("authorization",`Bearer ${u}`);let E=t.executeLogic({session_token:d.session_token,wasm_binary:new Uint8Array(j),inputs:{},pqc_ciphertext:g,aes_nonce:k},M),I="",S=null;E.on("data",w=>{I+=w.semantic_evidence,S=w;}),E.on("end",async()=>{try{if(S&&!S.is_error){let Pe=Buffer.from(S.cryptographic_proof).toString("hex");if(!await this.verifier.verifyZkReceipt(Buffer.from(R),Pe,Buffer.from(S.zk_receipt),Buffer.from(T),I))return p({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:"SECURITY ALERT: Remote response failed cryptographic integrity audit."}],isError:!0}})}let w=JSON.parse(I),q=P.getInstance();q.record({type:"tool_call",method:"tools/call",toolName:r,peerId:i,estimatedInputTokens:q.countTokens(y),estimatedOutputTokens:q.countTokens(I),durationMs:Date.now()-l}),p({jsonrpc:"2.0",id:e,result:w});}catch{p({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:I}]}});}}),E.on("error",w=>p({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`LIOP gRPC Error: ${w.message}`}],isError:true}}));});})}encryptWithNonce(e,t,r){let n=K.createCipheriv("aes-256-gcm",t,r),i=Buffer.concat([n.update(e),n.final()]);return Buffer.concat([i,n.getAuthTag()])}};export{W as a,B as b,fe as c,he as d,H as e,P as f,Ie as g};//# sourceMappingURL=chunk-I46YEWND.js.map
|
|
33
|
+
//# sourceMappingURL=chunk-I46YEWND.js.map
|