@nekzus/liop 2.4.0-alpha.29 → 2.4.0-alpha.30
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/dist/bin/agent.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {b as b$2,a as a$3}from'../chunk-2XHSALII.js';import {a as a$4}from'../chunk-N35BC62H.js';import {m}from'../chunk-
|
|
2
|
+
import {b as b$2,a as a$3}from'../chunk-2XHSALII.js';import {a as a$4}from'../chunk-N35BC62H.js';import {m}from'../chunk-PRNQM5KL.js';import'../chunk-MQ5SU26J.js';import {a as a$2}from'../chunk-AN5NODTN.js';import'../chunk-6KFKO6ZX.js';import'../chunk-TKLRW52V.js';import'../chunk-Y675R34Z.js';import'../chunk-XLVEDKM6.js';import'../chunk-2ZYX736J.js';import'../chunk-ECRS6N33.js';import'../chunk-ZZMSFCJP.js';import {g,f,d}from'../chunk-GWVSCZUS.js';import'../chunk-6VK2XALI.js';import'../chunk-FTF6AMF6.js';import'../chunk-YLCNV764.js';import {a as a$1}from'../chunk-V35CXJQN.js';import {b as b$1}from'../chunk-3WRKTVOF.js';import {a}from'../chunk-AYDF3IFZ.js';import*as L from'fs';import*as G from'os';import*as R from'path';import*as N from'readline';import {multiaddr}from'@multiformats/multiaddr';var b={name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}};async function F(e){try{let s=e.endsWith("/health")?e:`${e}/health`,a=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!a.ok)return null;let n=await a.json();if(!n.mesh?.multiaddrs?.length||!n.mesh?.peerId)return null;let c=n.mesh.multiaddrs.find(t=>t.includes("/tcp/")&&!t.includes("/ws")&&!t.includes("/ip4/127.0.0.1/"));if(!c)return null;let i=C()?k(c):c;if(!i||i===c){let t=new URL(e).hostname;i=c.replace(/\/ip4\/[^/]+/,`/ip4/${t}`);}return i?(i+=i.includes("/p2p/")?"":`/p2p/${n.mesh.peerId}`,i):null}catch{return null}}a(F,"resolveBootstrapFromUrl");function V(e){let s=e.trim(),a=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,n=/\/ip4\/127\.0\.0\.1/,c=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(a.test(s)||n.test(s)||c.test(s)){let i="127.0.0.1",t=s.replace(a,`/ip4/${i}`).replace(n,`/ip4/${i}`).replace(c,`/ip4/${i}`);return t!==s&&b$1.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${t}`),t}return s}a(V,"normalizeBootstrap");function k(e){return e.includes("/ip4/172.23.0.10")?e.replace(/\/ip4\/172\.23\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15001"):e.includes("/ip4/172.23.0.20")?e.replace(/\/ip4\/172\.23\.0\.20\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15011"):e.includes("/ip4/172.21.0.13")?e.replace(/\/ip4\/172\.21\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15031"):e.includes("/ip4/172.21.0.14")?e.replace(/\/ip4\/172\.21\.0\.14\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15041"):e.includes("/ip4/172.20.0.10")?e.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):e.includes("/ip4/172.20.0.11")?e.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):e.includes("/ip4/172.20.0.12")?e.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):e.includes("/ip4/172.20.0.13")?e.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):e.includes("/ip4/127.0.0.1/tcp/4000")||e.includes("/ip4/127.0.0.1/tcp/3000")?null:e}a(k,"industrialAddressMapper");function q(e){try{let s=new URL(e);return (s.hostname==="127.0.0.1"||s.hostname==="localhost")&&(s.port==="13000"||s.port==="13001"||s.port==="15000"||s.port==="15018")}catch{return false}}a(q,"isDockerDemoHost");function C(){return process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||!!process.env.LIOP_NEXUS_URL&&q(process.env.LIOP_NEXUS_URL)}a(C,"shouldEnableDockerMap");async function X(e){let s=[],a=process.argv.slice(2);if(a.length>0&&(s=a.filter(n=>n.startsWith("/"))),process.env.LIOP_NEXUS_URL||process.env.LIOP_BLG_URL){let n=process.env.LIOP_NEXUS_URL||process.env.LIOP_BLG_URL;if(n){let c=await F(n);if(c){let i=V(c);s.includes(i)||(s.push(i),b$1.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${i}`));}}}if(s.length===0){let n=[process.cwd(),R.join(process.cwd(),"tests/infra/nexus-data"),e,R.join(R.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data")];for(let c of n)try{if(L.existsSync(c)){let t=L.readdirSync(c).filter(l=>l.endsWith(".multiaddr"));for(let l of t){let d=R.join(c,l),r=L.readFileSync(d,"utf8").trim();if(r){let m=V(r);s.includes(m)||(s.push(m),b$1.info(`[LIOP-Agent] \u2705 Loaded beacon: ${l} from ${c}`));}}if(s.length>0)break}}catch{}}return s.length===0&&process.env.LIOP_BOOTSTRAP&&s.push(process.env.LIOP_BOOTSTRAP.trim()),s.filter(n=>{try{return multiaddr(n),!0}catch{return false}})}a(X,"resolveBootstrapNodes");async function _(e,s,a$1){let n=a(async t=>{let l={"Content-Type":"application/json"};t&&(l.Authorization=`Bearer ${t}`),s.method&&(l["Mcp-Method"]=s.method);let d=s.params;return d?.name&&(l["Mcp-Name"]=d.name),await fetch(e,{method:"POST",headers:l,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)})},"send"),c;try{c=await a$1.getToken();}catch(t){b$1.warn(`[LIOP-Agent] Token acquisition warning: ${t instanceof Error?t.message:String(t)}`);}let i=await n(c);if(i.status===401&&c){b$1.info("[LIOP-Agent] \u{1F504} 401 received from Gateway. Refreshing token and retrying..."),a$1.invalidate();try{c=await a$1.getToken(),i=await n(c);}catch{}}if(!i.ok){let t=await i.text(),l=null;try{l=JSON.parse(t);}catch{}let d=l?.error;return {jsonrpc:"2.0",id:s.id,error:{code:d?.code??-32603,message:d?.message??`Gateway returned HTTP ${i.status}: ${t}`}}}return await i.json()}a(_,"forwardToGateway");async function z(e,s,a){b$1.info(`[LIOP-Agent] \u{1F6E1}\uFE0F Running in ADAPTIVE GATEWAY MODE -> ${e.mcpEndpoint}`),a.registerLocalTool(b),a.registerGatewayTools(e.tools.map(t=>({name:t})),e.mcpEndpoint);let n=e.tools.length,c=setInterval(async()=>{try{let t=await fetch(e.healthEndpoint,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(4e3)});if(t.ok){let l=await t.json();l.tools&&l.tools.length!==n&&(b$1.info(`[LIOP-Agent] Gateway tools topology updated (${n} -> ${l.tools.length})`),n=l.tools.length,a.registerGatewayTools(l.tools.map(d=>({name:d})),e.mcpEndpoint),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
|
|
3
3
|
`),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
|
|
4
4
|
`));}}catch{}},15e3),i=N.createInterface({input:process.stdin,terminal:false});process.stdout.on("error",t=>{t.code==="EPIPE"&&(clearInterval(c),process.exit(0));}),i.on("line",async t=>{let l=t.trim();if(!l)return;let d$1;try{d$1=JSON.parse(l);}catch{return}let{id:r,method:m}=d$1;if(m==="server/discover"){let o={jsonrpc:"2.0",id:r,result:{resultType:"complete",supportedVersions:["2026-07-28","2025-11-25"],capabilities:{tools:{listChanged:true},resources:{listChanged:true,subscribe:true},prompts:{listChanged:true}},serverInfo:{name:"liop-adaptive-agent",version:"2.5.0"}}};process.stdout.write(`${JSON.stringify(o)}
|
|
5
5
|
`);return}if(m==="initialize"){let u=(d$1.params?.protocolVersion??d$1.params?._meta?.["io.modelcontextprotocol/protocolVersion"])==="2026-07-28"?"2026-07-28":"2025-11-25",f={jsonrpc:"2.0",id:r,result:{protocolVersion:u,capabilities:{tools:{listChanged:true},resources:{listChanged:true,subscribe:true},prompts:{listChanged:true}},serverInfo:{name:"liop-adaptive-agent",version:"2.5.0"}}};process.stdout.write(`${JSON.stringify(f)}
|
package/dist/bridge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-
|
|
1
|
+
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-ZEU57HJP.js';import'./chunk-GWVSCZUS.js';import'./chunk-6VK2XALI.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=bridge.js.map
|
|
2
2
|
//# sourceMappingURL=bridge.js.map
|
|
@@ -5,7 +5,7 @@ import {a as a$2}from'./chunk-MQ5SU26J.js';import {a as a$3,b as b$2}from'./chun
|
|
|
5
5
|
${e}
|
|
6
6
|
}`;i=ne.parse(a,{ecmaVersion:"latest",sourceType:"script",locations:!0,allowReturnOutsideFunction:!0});}catch{return null}let n=new Set,s=new Set;this.identifyRecordBoundVars(i,n),this.propagateTaint(i,n,s);let o=this.checkReturnStatements(i,n,s);if(o)return o;if(r!==void 0&&r>0&&r<t){let a=this.detectCorrelatedAggregations(i);if(a)return a.reason=a.reason.replace("50 records",`${t} records`),a}if(r!==void 0&&r>0&&r<t){let a=this.detectMinMaxExtraction(i);if(a)return a.reason=a.reason.replace("50 records",`${t} records`),a}return null}extractQueriedFields(e){let r;try{r=ne.parse(`function w(env) {
|
|
7
7
|
${e}
|
|
8
|
-
}`,{ecmaVersion:"latest",sourceType:"script",allowReturnOutsideFunction:!0});}catch{return []}let t=new Set;this.identifyRecordBoundVars(r,t);let i=new Set;return simple(r,{MemberExpression:a(s=>{let o=this.getPropertyName(s);if(!(!o||o==="length")&&(s.object.type==="Identifier"&&t.has(s.object.name)&&i.add(o),s.object.type==="MemberExpression")){let a=s.object;a.computed&&this.isEnvRecordsAccess(a.object)&&i.add(o);}},"MemberExpression")}),Array.from(i)}detectCorrelatedAggregations(e){let r=new Map;simple(e,{CallExpression:a(i=>{if(i.callee.type!=="MemberExpression")return;let n=i.callee,s=this.getPropertyName(n);if(!s||!h.REDUCE_METHODS.has(s)||!this.isEnvRecordsChain(n.object))return;let o=i.arguments[0];if(!o||o.type!=="ArrowFunctionExpression"&&o.type!=="FunctionExpression")return;let a=o,c=a.params.length>1?a.params[1]:a.params[0];if(c?.type!=="Identifier")return;let l=c.name,u=this.extractFieldsFromBody(a.body,l);for(let y of u){let v=r.get(y)??0;r.set(y,v+1);}},"CallExpression")});for(let[i,n]of r)if(n>=2)return {reason:`Correlation guard: ${n} aggregations detected on field '${i}'. Multiple correlated aggregations on the same field can enable differencing attacks. Use a single aggregation per numeric field, or increase dataset size above 50 records.`};return null}isEnvRecordsChain(e){if(this.isEnvRecordsAccess(e))return true;if(e.type==="CallExpression"){let r=e;if(r.callee.type==="MemberExpression"){let t=r.callee,i=this.getPropertyName(t);if(i&&(i==="slice"||i==="filter"||i==="toSorted"))return this.isEnvRecordsChain(t.object)}}return false}isRecordsSource(e){if(this.isEnvRecordsAccess(e)||e.type==="Identifier"&&this.currentRecordCollections.has(e.name))return true;if(e.type==="CallExpression"){let r=e;if(r.callee.type==="MemberExpression"){let t=r.callee,i=this.getPropertyName(t);if(i&&(i==="slice"||i==="filter"||i==="toSorted"||i==="map"||i==="concat"))return this.isRecordsSource(t.object)}}return false}identifyRecordCollections(e){this.currentRecordCollections.clear();for(let r=0;r<3;r++)simple(e,{VariableDeclarator:a(i=>{!i.init||i.id.type!=="Identifier"||this.isRecordsSource(i.init)&&this.currentRecordCollections.add(i.id.name);},"VariableDeclarator"),AssignmentExpression:a(i=>{i.left.type==="Identifier"&&this.isRecordsSource(i.right)&&this.currentRecordCollections.add(i.left.name);},"AssignmentExpression")});}extractFieldsFromBody(e,r){let t=[];return simple(e,{MemberExpression:a(n=>{if(n.object.type==="Identifier"&&n.object.name===r){let s=this.getPropertyName(n);s&&s!=="length"&&t.push(s);}},"MemberExpression")}),t}detectMinMaxExtraction(e){let r=null;return simple(e,{CallExpression:a(i=>{if(!r&&i.callee.type==="MemberExpression"){let n=i.callee;if(n.object.type==="Identifier"&&n.object.name==="Math"){let s=this.getPropertyName(n);(s==="min"||s==="max")&&i.arguments.some(o=>o.type==="SpreadElement"&&this.isRecordsMapCall(o.argument))&&(r={reason:`Min/Max gate: Math.${s}() on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations.`});}}},"CallExpression"),MemberExpression:a(i=>{if(!r&&i.computed&&i.object.type==="CallExpression"){let n=i.object;if(n.callee.type==="MemberExpression"){let s=this.getPropertyName(n.callee);if(s==="sort"||s==="toSorted"){let o=n.callee.object;this.isEnvRecordsChain(o)&&(r={reason:"Min/Max gate: .sort()[index] on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations."});}}}},"MemberExpression")}),r}isRecordsMapCall(e){if(e.type!=="CallExpression")return false;let r=e;if(r.callee.type!=="MemberExpression")return false;let t=r.callee;return this.getPropertyName(t)==="map"&&this.isRecordsSource(t.object)}identifyRecordBoundVars(e,r){this.identifyRecordCollections(e),simple(e,{CallExpression:a(n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isRecordsSource(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(h.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let l=c.params[0];l.type==="Identifier"&&r.add(l.name);}if(h.REDUCE_METHODS.has(o)&&c.params.length>1){let l=c.params[1];l.type==="Identifier"&&r.add(l.name);}}},"CallExpression"),ForOfStatement:a(n=>{if(this.isRecordsSource(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&r.add(s.id.name);},"ForOfStatement")}),simple(e,{VariableDeclarator:a(n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isRecordsSource(s.object)&&r.add(n.id.name);}},"VariableDeclarator")});}propagateTaint(e,r,t){for(let i=0;i<3;i++){let n=t.size;if(simple(e,{VariableDeclarator:a(o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,r,t)&&t.add(o.id.name);},"VariableDeclarator"),AssignmentExpression:a(o=>{if(o.left.type==="MemberExpression"){let a=o.left;a.computed&&this.isExpressionTainted(a.property,r,t)&&a.object.type==="Identifier"&&t.add(a.object.name);}o.left.type==="Identifier"&&this.isExpressionTainted(o.right,r,t)&&t.add(o.left.name);},"AssignmentExpression"),FunctionDeclaration:a(o=>{o.id&&o.id.type==="Identifier"&&this.doesCallbackProduceTaint(o,null,r,t)&&t.add(o.id.name);},"FunctionDeclaration"),CallExpression:a(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,r,t))&&t.add(a.object.name);},"CallExpression")}),t.size===n)break}}checkReturnStatements(e,r,t){let i=null;return simple(e,{ReturnStatement:a(s=>{if(!i&&s.argument&&this.isExpressionTainted(s.argument,r,t)){let o=s.loc?.start.line?s.loc.start.line-1:void 0,a=this.describeTaintSource(s.argument,r,t);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};}},"ReturnStatement")}),i}isExpressionTainted(e,r,t){switch(e.type){case "Identifier":return t.has(e.name);case "MemberExpression":return this.isMemberExprTainted(e,r,t);case "CallExpression":return this.isCallExprTainted(e,r,t);case "YieldExpression":{let i=e;return i.argument?this.isExpressionTainted(i.argument,r,t):false}case "FunctionExpression":case "ArrowFunctionExpression":{let i=e;return this.doesCallbackProduceTaint(i,null,r,t)}case "BinaryExpression":case "LogicalExpression":{let i=e;return this.isExpressionTainted(i.left,r,t)||this.isExpressionTainted(i.right,r,t)}case "UnaryExpression":{let i=e;return this.isExpressionTainted(i.argument,r,t)}case "ConditionalExpression":{let i=e;return this.isExpressionTainted(i.test,r,t)||this.isExpressionTainted(i.consequent,r,t)||this.isExpressionTainted(i.alternate,r,t)}case "ObjectExpression":return e.properties.some(n=>n.type==="Property"?n.computed&&this.isExpressionTainted(n.key,r,t)?true:this.isExpressionTainted(n.value,r,t):n.type==="SpreadElement"?this.isExpressionTainted(n.argument,r,t):false);case "ArrayExpression":return e.elements.some(n=>n!==null&&this.isExpressionTainted(n,r,t));case "TemplateLiteral":return e.expressions.some(n=>this.isExpressionTainted(n,r,t));case "SpreadElement":{let i=e;return this.isExpressionTainted(i.argument,r,t)}default:return false}}isMemberExprTainted(e,r,t){let i=this.getPropertyName(e);if(e.object.type==="Identifier"&&r.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.isRecordsSource(n.object))return true}if(this.isExpressionTainted(e.object,r,t))return true;if(e.computed&&e.object.type==="Identifier"&&r.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,r,t){if(e.callee.type==="MemberExpression"){let i=e.callee,n=this.getPropertyName(i);if(n&&h.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,r,t))return true;if(this.isRecordsSource(i.object)&&e.arguments[0]){let s=e.arguments[0];if(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")return this.doesCallbackProduceTaint(s,n,r,t)}if(this.isExpressionTainted(i.object,r,t)||e.arguments.some(s=>this.isExpressionTainted(s,r,t)))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,r,t))&&t.add(i.object.name);}if(e.callee.type==="Identifier"){let i=e.callee.name;if(t.has(i))return true;if(!new Set(["Math","Number","parseInt","parseFloat","isNaN","isFinite"]).has(i))return e.arguments.some(s=>this.isExpressionTainted(s,r,t))}return false}doesCallbackProduceTaint(e,r,t,i){let n=new Set(t),s=new Set(i);if(e.params.length>0){let l=r!==null&&h.REDUCE_METHODS.has(r)?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);this.propagateTaint(e.body,n,s);let o=false,a$1={ReturnStatement:a(c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);},"ReturnStatement"),YieldExpression:a(c=>{let l=c;l.argument&&this.isExpressionTainted(l.argument,n,s)&&(o=true);},"YieldExpression")};return simple(e.body,a$1),o}getPropertyName(e){if(!e.computed&&e.property.type==="Identifier")return e.property.name;if(e.computed&&e.property.type==="Literal"){let r=e.property.value;if(typeof r=="string")return r}return null}isEnvRecordsAccess(e){if(e.type==="MemberExpression"){let r=e;if(this.getPropertyName(r)==="records"&&r.object.type==="Identifier"&&r.object.name==="env")return true}return e.type==="Identifier"&&e.name==="records"}describeTaintSource(e,r,t){if(e.type==="Identifier"){let i=e.name;if(t.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,r,t))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 ke={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"},Q=4,Oe=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,X=class h{static{a(this,"NerScanner");}static nlp=null;async getNlp(){if(!h.nlp){let e=await import('compromise/three');h.nlp=e.default||e,h.nlp.addWords(ke);}return h.nlp}async scan(e){if(e.length<Q||Oe.test(e))return {detected:false,entities:[]};let t=(await this.getNlp())(e),i=[],n=t.people().out("array");for(let a of n){let c=a.trim();c.length>=Q&&i.push({type:"person",text:c});}let s=t.places().out("array");for(let a of s){let c=a.trim();c.length>=Q&&i.push({type:"place",text:c});}let o=t.organizations().out("array");for(let a of o){let c=a.trim();c.length>=Q&&i.push({type:"organization",text:c});}return {detected:i.length>0,entities:i}}async scanDeep(e,r=new WeakSet){if(e==null)return {detected:false,entities:[]};if(typeof e=="string")return this.scan(e);if(typeof e=="object"){if(r.has(e))return {detected:false,entities:[]};r.add(e);let t=Array.isArray(e)?e:Object.values(e),i=[];for(let n of t){let s=await this.scanDeep(n,r);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 Ne(h){let e=h.replace(/\D/g,"");if(e.length<13||e.length>19)return false;let r=0,t=false;for(let i=e.length-1;i>=0;i--){let n=parseInt(e.charAt(i),10);t&&(n*=2,n>9&&(n-=9)),r+=n,t=!t;}return r%10===0}a(Ne,"isLuhnValid");function Ce(h){let e=h.replace(/\s+/g,"").toUpperCase();if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/.test(e))return false;let r=e.substring(4)+e.substring(0,4),t="";for(let i=0;i<r.length;i++){let n=r.charCodeAt(i);if(n>=65&&n<=90)t+=(n-55).toString();else if(n>=48&&n<=57)t+=r.charAt(i);else return false}try{return BigInt(t)%97n===1n}catch{return false}}a(Ce,"isIbanValid");var R={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:a(h=>!h.endsWith("@example.com")&&!h.endsWith("@test.com"),"validator")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:Ne},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:a(h=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(h)?false:h.split(".").map(Number).every(t=>t>=0&&t<=255),"validator")},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");return !(e.length<7||e.length>15||/^(\d)\1+$/.test(e)||e==="1234567890")},"validator")},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");if(e.length!==9)return false;let r=parseInt(e.substring(0,3),10);return !(r===0||r===666||r>=900||parseInt(e.substring(3,5),10)===0||parseInt(e.substring(5,9),10)===0||/^(\d)\1+$/.test(e)||e==="123456789")},"validator")},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:Ce},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},Te={GLOBAL_STRICT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.PASSPORT_MRZ,R.IBAN],US_COMPLIANT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.SSN,R.PASSPORT_MRZ],EU_GDPR:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.IBAN,R.PASSPORT_MRZ]},ee=class h{static{a(this,"PiiScanner");}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=[],r=[],t){this.patterns=e,this.forbiddenKeysSet=new Set(r.map(i=>i.toLowerCase())),this.nerScanner=t??null,this.shortTokenBoundaryPatterns=new Map,this.longForbiddenTokens=[];for(let i of this.forbiddenKeysSet)i.length<4?this.shortTokenBoundaryPatterns.set(i,new RegExp((()=>{let n=i.split("").map(o=>`[${o.toLowerCase()}${o.toUpperCase()}]`).join(""),s=`[a-z]${i.charAt(0).toUpperCase()}${i.slice(1)}`;return `(?:^|[_-])${n}(?:$|[_-])|${s}(?:$|[A-Z_-])|^${n}$`})())):this.longForbiddenTokens.push(i);}async scan(e,r=new WeakSet){if(e==null)return null;if(typeof e=="string"){let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let n=JSON.parse(t),s=await this.scan(n,r);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=="number"||typeof e=="bigint"){let t=e.toString();if(t.length>=7){let i=this.checkString(t);if(i)return i}return null}if(typeof e=="object"){if(r.has(e))return null;if(r.add(e),Array.isArray(e))for(let t of e){let i=await this.scan(t,r);if(i)return i}else for(let[t,i]of Object.entries(e)){if(this.forbiddenKeysSet.has(t.toLowerCase()))return `Forbidden Key: ${t}`;let n=this.checkKeyFuzzy(t);if(n)return n;let s=await this.scan(i,r);if(s)return s}}return null}checkKeyFuzzy(e){let r=e.toLowerCase();if(h.KEY_SAFELIST.has(r))return null;for(let[t,i]of this.shortTokenBoundaryPatterns)if(i.test(e))return `Forbidden Key (fuzzy): ${e} matches boundary pattern "${t}"`;for(let t of this.longForbiddenTokens)if(r.includes(t))return `Forbidden Key (fuzzy): ${e} contains restricted token "${t}"`;return null}checkString(e){for(let r of this.patterns)if(typeof r=="string"){if(e.toLowerCase().includes(r.toLowerCase()))return r}else if(r instanceof RegExp){if(r.global&&(r.lastIndex=0),r.test(e))return r.source}else if(typeof r=="object"&&r!==null){let t=r;if(typeof t.pattern=="string"){if(e.toLowerCase().includes(t.pattern.toLowerCase())&&(!t.validator||t.validator(t.pattern)))return t.name}else if(t.pattern instanceof RegExp){t.pattern.global&&(t.pattern.lastIndex=0);let i=t.pattern.exec(e);for(;i!==null;){let n=i[0];if(!t.validator||t.validator(n))return t.name;if(!t.pattern.global)break;i=t.pattern.exec(e);}}}return null}};var Pe=L.dirname(fileURLToPath(import.meta.url)),Re=class h{constructor(e,r){this.serverInfo=e;this.config=r;let t=this.config?.security?.enableNerScanning?new X:null;this.piiScanner=new ee(this.config?.security?.piiPatterns??Te.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"],t);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"],s=this.config?.security?.sensitiveKeys??[];this.taintAnalyzer=new V(n,s),this.auditLogger=this.config?.auditLogger||Se;let o=import.meta.url.endsWith(".ts"),a=o?".ts":".js",c=[];if(o)try{let f=createRequire(import.meta.url).resolve("tsx/package.json"),d=pathToFileURL(L.join(L.dirname(f),"dist","loader.mjs")).href;c.push("--import",d);}catch{c.push("--import","tsx");}let l=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let u=[L.resolve(Pe,`./workers/logic-execution${a}`),L.resolve(Pe,`../workers/logic-execution${a}`)],y=u.find(p=>S.existsSync(p))||u[1];this.workerPool=new Piscina({filename:y,minThreads:this.config?.workerPool?.minThreads??(l?0:2),maxThreads:this.config?.workerPool?.maxThreads??(l?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(l?500:5e3),maxQueue:this.config?.workerPool?.maxQueue??"auto",taskQueue:new FixedQueue,execArgv:c,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}});let v=this.config?.workerPool?.minThreads??(l?0:2);if(this.workerPool&&v>0)for(let p=0;p<v;p++)this.workerPool.run({isWarmup:true}).catch(f=>{b.debug(`[LiopServer] Worker pool warm-up ping failed: ${f.message}`);});try{this.enclavePqcKeypair=b$1.generateKeyPair();}catch{this.enclavePqcKeypair=void 0;}if(this.config?.auth?.role==="nexus"){let p=this.config.auth.issuer||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=this.config.auth.clients||[{client_id:process.env.LIOP_OAUTH_CLIENT_ID||"liop-mesh-agent",client_secret:process.env.LIOP_OAUTH_CLIENT_SECRET||"dev-secret-change-me",grant_types:["client_credentials"],scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query"}],{provider:m,jwks:b}=be({issuer:p,clients:d});this.oauthProvider=m,this.jwtValidator=new q(p,f,b);}else if(this.config?.auth?.role==="node"){let p=this.config.auth.nexusUrl||process.env.LIOP_NEXUS_URL||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=p.endsWith("/oidc")?p:`${p}/oidc`,m=new URL(`${d}/jwks`);this.jwtValidator=new q(p,f,m);}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())),this.config?.auth?.revocationPath&&this.loadRevocationList();}serverInfo;config;static{a(this,"LiopServer");}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;fieldQueryBudget=new Map;taintAnalyzer;tools=new Map;resources=new Map;prompts=new Map;activeSchema=null;sandboxRecords=[];piiScanner;workerPool;meshNode=null;rpcServer=null;boundPort=null;enclavePqcKeypair;jwtValidator;oauthProvider;sessions=new Map;revokedTokenHashes=new Set;lastRevocationLoadTime=0;pqcKeyPair=b$1.generateKeyPair();auditLogger;getDatasetHash(){return O__default.createHash("sha256").update(JSON.stringify(this.sandboxRecords||[])).digest("hex")}static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,\s*(?<name>[^}]*))?\}[\r\n]+(?<logic>[\s\S]*?)[\r\n]+@END/m;extractLogic(e){if(!e||typeof e!="string")return null;let r=e.trim().match(h.LIOP_COMPACT_REGEX);return r?.groups?.logic?r.groups.logic.trim():null}parseUnknownJson(e){if(typeof e!="string")return e;let r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r)}catch{return e}return e}runPreflightPolicy(e,r,t,i="local-client"){if(t){let a=r.replace(/\s+/g," ");if(t.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(l=>l.test(a)))return "Preflight policy rejected: potential row-level export pattern detected.";if(t.preflightDenyPatterns?.some(c=>c.test(a)))return "Preflight policy rejected: custom deny pattern matched."}let n=50;typeof t?.enforceAggregationFirst=="object"&&(n=t.enforceAggregationFirst.minMaxBlockThreshold??50);let s=this.taintAnalyzer.analyze(r,this.sandboxRecords.length,n);if(s)return `Preflight policy rejected: ${s.reason}`;let o=this.taintAnalyzer.extractQueriedFields(r);if(o.length>0){if(i==="__proto__"||i==="constructor"||i==="prototype"||e==="__proto__"||e==="constructor"||e==="prototype")return "Preflight policy rejected: invalid property key names (prototype pollution guard).";let a=t?.budgetStorePath||this.config?.budgetStorePath;if(a)try{let c=this.executeWithBudgetLock(a,l=>{let u=l[i]||{},y=u[e]||{};for(let d of o){let m=this.taintAnalyzer.classifyField(d,t?.sensitiveKeys),b=25,T="public";if(t?.queryBudgetPerField!==void 0?(b=t.queryBudgetPerField,T="override"):m==="forbidden"?(b=3,T="forbidden"):m==="sensitive"&&(b=8,T="sensitive"),(y[d]??0)>=b)return {result:`Preflight policy rejected: Query budget exceeded for field '${d}' (max ${b} per session for ${T} fields). Rotate PQC session to reset budget.`}}let v={...y};for(let d of o)v[d]=(v[d]??0)+1;let p={...u};p[e]=v;let f={...l};return f[i]=p,{result:null,updatedBudget:f}});if(c)return c}catch(c){let l=c instanceof Error?c.message:String(c);b.error(`[LIOP-Server] Error applying persistent query budget: ${l}. Falling back to in-memory.`);let u=this.applyInMemoryBudget(i,e,o,t);if(u)return u}else {let c=this.applyInMemoryBudget(i,e,o,t);if(c)return c}}return null}validateOutputPolicy(e,r,t){if(!t)return null;let i=this.parseUnknownJson(r);if(i&&typeof i=="object"&&i.isError===true)return null;if(t.outputSchema){let s=(()=>{if(!(t.outputSchema instanceof z.ZodObject))return t.outputSchema;let o=t.outputSchema,a=o.def||o._def;return a&&a.catchall!==void 0&&!(a.catchall instanceof z.ZodNever)?o:o.strict()})().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 t.enforceAggregationFirst&&this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(i),t.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 r=e;if(r.computation_result!==void 0)return this.unwrapForAggregationPolicyScan(r.computation_result);if(!Array.isArray(r.content)||r.content.length===0)return e;let t=[];for(let n of r.content)if(n&&typeof n=="object"&&"text"in n){let s=n.text;typeof s=="string"&&t.push(s);}if(t.length===0)return e;let i=t.length===1?t[0]:t.join(`
|
|
8
|
+
}`,{ecmaVersion:"latest",sourceType:"script",allowReturnOutsideFunction:!0});}catch{return []}let t=new Set;this.identifyRecordBoundVars(r,t);let i=new Set;return simple(r,{MemberExpression:a(s=>{let o=this.getPropertyName(s);if(!(!o||o==="length")&&(s.object.type==="Identifier"&&t.has(s.object.name)&&i.add(o),s.object.type==="MemberExpression")){let a=s.object;a.computed&&this.isEnvRecordsAccess(a.object)&&i.add(o);}},"MemberExpression")}),Array.from(i)}detectCorrelatedAggregations(e){let r=new Map;simple(e,{CallExpression:a(i=>{if(i.callee.type!=="MemberExpression")return;let n=i.callee,s=this.getPropertyName(n);if(!s||!h.REDUCE_METHODS.has(s)||!this.isEnvRecordsChain(n.object))return;let o=i.arguments[0];if(!o||o.type!=="ArrowFunctionExpression"&&o.type!=="FunctionExpression")return;let a=o,c=a.params.length>1?a.params[1]:a.params[0];if(c?.type!=="Identifier")return;let l=c.name,u=this.extractFieldsFromBody(a.body,l);for(let y of u){let v=r.get(y)??0;r.set(y,v+1);}},"CallExpression")});for(let[i,n]of r)if(n>=2)return {reason:`Correlation guard: ${n} aggregations detected on field '${i}'. Multiple correlated aggregations on the same field can enable differencing attacks. Use a single aggregation per numeric field, or increase dataset size above 50 records.`};return null}isEnvRecordsChain(e){if(this.isEnvRecordsAccess(e))return true;if(e.type==="CallExpression"){let r=e;if(r.callee.type==="MemberExpression"){let t=r.callee,i=this.getPropertyName(t);if(i&&(i==="slice"||i==="filter"||i==="toSorted"))return this.isEnvRecordsChain(t.object)}}return false}isRecordsSource(e){if(this.isEnvRecordsAccess(e)||e.type==="Identifier"&&this.currentRecordCollections.has(e.name))return true;if(e.type==="CallExpression"){let r=e;if(r.callee.type==="MemberExpression"){let t=r.callee,i=this.getPropertyName(t);if(i&&(i==="slice"||i==="filter"||i==="toSorted"||i==="map"||i==="concat"))return this.isRecordsSource(t.object)}}return false}identifyRecordCollections(e){this.currentRecordCollections.clear();for(let r=0;r<3;r++)simple(e,{VariableDeclarator:a(i=>{!i.init||i.id.type!=="Identifier"||this.isRecordsSource(i.init)&&this.currentRecordCollections.add(i.id.name);},"VariableDeclarator"),AssignmentExpression:a(i=>{i.left.type==="Identifier"&&this.isRecordsSource(i.right)&&this.currentRecordCollections.add(i.left.name);},"AssignmentExpression")});}extractFieldsFromBody(e,r){let t=[];return simple(e,{MemberExpression:a(n=>{if(n.object.type==="Identifier"&&n.object.name===r){let s=this.getPropertyName(n);s&&s!=="length"&&t.push(s);}},"MemberExpression")}),t}detectMinMaxExtraction(e){let r=null;return simple(e,{CallExpression:a(i=>{if(!r&&i.callee.type==="MemberExpression"){let n=i.callee;if(n.object.type==="Identifier"&&n.object.name==="Math"){let s=this.getPropertyName(n);(s==="min"||s==="max")&&i.arguments.some(o=>o.type==="SpreadElement"&&this.isRecordsMapCall(o.argument))&&(r={reason:`Min/Max gate: Math.${s}() on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations.`});}}},"CallExpression"),MemberExpression:a(i=>{if(!r&&i.computed&&i.object.type==="CallExpression"){let n=i.object;if(n.callee.type==="MemberExpression"){let s=this.getPropertyName(n.callee);if(s==="sort"||s==="toSorted"){let o=n.callee.object;this.isEnvRecordsChain(o)&&(r={reason:"Min/Max gate: .sort()[index] on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations."});}}}},"MemberExpression")}),r}isRecordsMapCall(e){if(e.type!=="CallExpression")return false;let r=e;if(r.callee.type!=="MemberExpression")return false;let t=r.callee;return this.getPropertyName(t)==="map"&&this.isRecordsSource(t.object)}identifyRecordBoundVars(e,r){this.identifyRecordCollections(e),simple(e,{CallExpression:a(n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isRecordsSource(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(h.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let l=c.params[0];l.type==="Identifier"&&r.add(l.name);}if(h.REDUCE_METHODS.has(o)&&c.params.length>1){let l=c.params[1];l.type==="Identifier"&&r.add(l.name);}}},"CallExpression"),ForOfStatement:a(n=>{if(this.isRecordsSource(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&r.add(s.id.name);},"ForOfStatement")}),simple(e,{VariableDeclarator:a(n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isRecordsSource(s.object)&&r.add(n.id.name);}},"VariableDeclarator")});}propagateTaint(e,r,t){for(let i=0;i<3;i++){let n=t.size;if(simple(e,{VariableDeclarator:a(o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,r,t)&&t.add(o.id.name);},"VariableDeclarator"),AssignmentExpression:a(o=>{if(o.left.type==="MemberExpression"){let a=o.left;a.computed&&this.isExpressionTainted(a.property,r,t)&&a.object.type==="Identifier"&&t.add(a.object.name);}o.left.type==="Identifier"&&this.isExpressionTainted(o.right,r,t)&&t.add(o.left.name);},"AssignmentExpression"),FunctionDeclaration:a(o=>{o.id&&o.id.type==="Identifier"&&this.doesCallbackProduceTaint(o,null,r,t)&&t.add(o.id.name);},"FunctionDeclaration"),CallExpression:a(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,r,t))&&t.add(a.object.name);},"CallExpression")}),t.size===n)break}}checkReturnStatements(e,r,t){let i=null;return simple(e,{ReturnStatement:a(s=>{if(!i&&s.argument&&this.isExpressionTainted(s.argument,r,t)){let o=s.loc?.start.line?s.loc.start.line-1:void 0,a=this.describeTaintSource(s.argument,r,t);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};}},"ReturnStatement")}),i}isExpressionTainted(e,r,t){switch(e.type){case "Identifier":return t.has(e.name);case "MemberExpression":return this.isMemberExprTainted(e,r,t);case "CallExpression":return this.isCallExprTainted(e,r,t);case "YieldExpression":{let i=e;return i.argument?this.isExpressionTainted(i.argument,r,t):false}case "FunctionExpression":case "ArrowFunctionExpression":{let i=e;return this.doesCallbackProduceTaint(i,null,r,t)}case "BinaryExpression":case "LogicalExpression":{let i=e;return this.isExpressionTainted(i.left,r,t)||this.isExpressionTainted(i.right,r,t)}case "UnaryExpression":{let i=e;return this.isExpressionTainted(i.argument,r,t)}case "ConditionalExpression":{let i=e;return this.isExpressionTainted(i.test,r,t)||this.isExpressionTainted(i.consequent,r,t)||this.isExpressionTainted(i.alternate,r,t)}case "ObjectExpression":return e.properties.some(n=>n.type==="Property"?n.computed&&this.isExpressionTainted(n.key,r,t)?true:this.isExpressionTainted(n.value,r,t):n.type==="SpreadElement"?this.isExpressionTainted(n.argument,r,t):false);case "ArrayExpression":return e.elements.some(n=>n!==null&&this.isExpressionTainted(n,r,t));case "TemplateLiteral":return e.expressions.some(n=>this.isExpressionTainted(n,r,t));case "SpreadElement":{let i=e;return this.isExpressionTainted(i.argument,r,t)}default:return false}}isMemberExprTainted(e,r,t){let i=this.getPropertyName(e);if(e.object.type==="Identifier"&&r.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.isRecordsSource(n.object))return true}if(this.isExpressionTainted(e.object,r,t))return true;if(e.computed&&e.object.type==="Identifier"&&r.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,r,t){if(e.callee.type==="MemberExpression"){let i=e.callee,n=this.getPropertyName(i);if(n&&h.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,r,t))return true;if(this.isRecordsSource(i.object)&&e.arguments[0]){let s=e.arguments[0];if(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")return this.doesCallbackProduceTaint(s,n,r,t)}if(this.isExpressionTainted(i.object,r,t)||e.arguments.some(s=>this.isExpressionTainted(s,r,t)))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,r,t))&&t.add(i.object.name);}if(e.callee.type==="Identifier"){let i=e.callee.name;if(t.has(i))return true;if(!new Set(["Math","Number","parseInt","parseFloat","isNaN","isFinite"]).has(i))return e.arguments.some(s=>this.isExpressionTainted(s,r,t))}return false}doesCallbackProduceTaint(e,r,t,i){let n=new Set(t),s=new Set(i);if(e.params.length>0){let l=r!==null&&h.REDUCE_METHODS.has(r)?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);this.propagateTaint(e.body,n,s);let o=false,a$1={ReturnStatement:a(c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);},"ReturnStatement"),YieldExpression:a(c=>{let l=c;l.argument&&this.isExpressionTainted(l.argument,n,s)&&(o=true);},"YieldExpression")};return simple(e.body,a$1),o}getPropertyName(e){if(!e.computed&&e.property.type==="Identifier")return e.property.name;if(e.computed&&e.property.type==="Literal"){let r=e.property.value;if(typeof r=="string")return r}return null}isEnvRecordsAccess(e){if(e.type==="MemberExpression"){let r=e;if(this.getPropertyName(r)==="records"&&r.object.type==="Identifier"&&r.object.name==="env")return true}return e.type==="Identifier"&&e.name==="records"}describeTaintSource(e,r,t){if(e.type==="Identifier"){let i=e.name;if(t.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,r,t))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 ke={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"},Q=4,Oe=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,X=class h{static{a(this,"NerScanner");}static nlp=null;async getNlp(){if(!h.nlp){let e=await import('compromise/three');h.nlp=e.default||e,h.nlp.addWords(ke);}return h.nlp}async scan(e){if(e.length<Q||Oe.test(e))return {detected:false,entities:[]};let t=(await this.getNlp())(e),i=[],n=t.people().out("array");for(let a of n){let c=a.trim();c.length>=Q&&i.push({type:"person",text:c});}let s=t.places().out("array");for(let a of s){let c=a.trim();c.length>=Q&&i.push({type:"place",text:c});}let o=t.organizations().out("array");for(let a of o){let c=a.trim();c.length>=Q&&i.push({type:"organization",text:c});}return {detected:i.length>0,entities:i}}async scanDeep(e,r=new WeakSet){if(e==null)return {detected:false,entities:[]};if(typeof e=="string")return this.scan(e);if(typeof e=="object"){if(r.has(e))return {detected:false,entities:[]};r.add(e);let t=Array.isArray(e)?e:Object.values(e),i=[];for(let n of t){let s=await this.scanDeep(n,r);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 Ne(h){let e=h.replace(/\D/g,"");if(e.length<13||e.length>19)return false;let r=0,t=false;for(let i=e.length-1;i>=0;i--){let n=parseInt(e.charAt(i),10);t&&(n*=2,n>9&&(n-=9)),r+=n,t=!t;}return r%10===0}a(Ne,"isLuhnValid");function Ce(h){let e=h.replace(/\s+/g,"").toUpperCase();if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/.test(e))return false;let r=e.substring(4)+e.substring(0,4),t="";for(let i=0;i<r.length;i++){let n=r.charCodeAt(i);if(n>=65&&n<=90)t+=(n-55).toString();else if(n>=48&&n<=57)t+=r.charAt(i);else return false}try{return BigInt(t)%97n===1n}catch{return false}}a(Ce,"isIbanValid");var R={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:a(h=>!h.endsWith("@example.com")&&!h.endsWith("@test.com"),"validator")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:Ne},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:a(h=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(h)?false:h.split(".").map(Number).every(t=>t>=0&&t<=255),"validator")},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");return !(e.length<7||e.length>15||h.includes(".")&&h.split(".").some(t=>t.replace(/\D/g,"").length>4)||/^(\d)\1+$/.test(e)||e==="1234567890")},"validator")},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");if(e.length!==9)return false;let r=parseInt(e.substring(0,3),10);return !(r===0||r===666||r>=900||parseInt(e.substring(3,5),10)===0||parseInt(e.substring(5,9),10)===0||/^(\d)\1+$/.test(e)||e==="123456789")},"validator")},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:Ce},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},Te={GLOBAL_STRICT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.PASSPORT_MRZ,R.IBAN],US_COMPLIANT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.SSN,R.PASSPORT_MRZ],EU_GDPR:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.IBAN,R.PASSPORT_MRZ]},ee=class h{static{a(this,"PiiScanner");}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=[],r=[],t){this.patterns=e,this.forbiddenKeysSet=new Set(r.map(i=>i.toLowerCase())),this.nerScanner=t??null,this.shortTokenBoundaryPatterns=new Map,this.longForbiddenTokens=[];for(let i of this.forbiddenKeysSet)i.length<4?this.shortTokenBoundaryPatterns.set(i,new RegExp((()=>{let n=i.split("").map(o=>`[${o.toLowerCase()}${o.toUpperCase()}]`).join(""),s=`[a-z]${i.charAt(0).toUpperCase()}${i.slice(1)}`;return `(?:^|[_-])${n}(?:$|[_-])|${s}(?:$|[A-Z_-])|^${n}$`})())):this.longForbiddenTokens.push(i);}async scan(e,r=new WeakSet){if(e==null)return null;if(typeof e=="string"){let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let n=JSON.parse(t),s=await this.scan(n,r);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=="number"||typeof e=="bigint"){if(typeof e=="number"&&!Number.isInteger(e))return null;let t=e.toString();if(t.length>=7){let i=this.checkString(t);if(i)return i}return null}if(typeof e=="object"){if(r.has(e))return null;if(r.add(e),Array.isArray(e))for(let t of e){let i=await this.scan(t,r);if(i)return i}else for(let[t,i]of Object.entries(e)){if(this.forbiddenKeysSet.has(t.toLowerCase()))return `Forbidden Key: ${t}`;let n=this.checkKeyFuzzy(t);if(n)return n;let s=await this.scan(i,r);if(s)return s}}return null}checkKeyFuzzy(e){let r=e.toLowerCase();if(h.KEY_SAFELIST.has(r))return null;for(let[t,i]of this.shortTokenBoundaryPatterns)if(i.test(e))return `Forbidden Key (fuzzy): ${e} matches boundary pattern "${t}"`;for(let t of this.longForbiddenTokens)if(r.includes(t))return `Forbidden Key (fuzzy): ${e} contains restricted token "${t}"`;return null}checkString(e){for(let r of this.patterns)if(typeof r=="string"){if(e.toLowerCase().includes(r.toLowerCase()))return r}else if(r instanceof RegExp){if(r.global&&(r.lastIndex=0),r.test(e))return r.source}else if(typeof r=="object"&&r!==null){let t=r;if(typeof t.pattern=="string"){if(e.toLowerCase().includes(t.pattern.toLowerCase())&&(!t.validator||t.validator(t.pattern)))return t.name}else if(t.pattern instanceof RegExp){t.pattern.global&&(t.pattern.lastIndex=0);let i=t.pattern.exec(e);for(;i!==null;){let n=i[0];if(!t.validator||t.validator(n))return t.name;if(!t.pattern.global)break;i=t.pattern.exec(e);}}}return null}};var Pe=L.dirname(fileURLToPath(import.meta.url)),Re=class h{constructor(e,r){this.serverInfo=e;this.config=r;let t=this.config?.security?.enableNerScanning?new X:null;this.piiScanner=new ee(this.config?.security?.piiPatterns??Te.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"],t);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"],s=this.config?.security?.sensitiveKeys??[];this.taintAnalyzer=new V(n,s),this.auditLogger=this.config?.auditLogger||Se;let o=import.meta.url.endsWith(".ts"),a=o?".ts":".js",c=[];if(o)try{let f=createRequire(import.meta.url).resolve("tsx/package.json"),d=pathToFileURL(L.join(L.dirname(f),"dist","loader.mjs")).href;c.push("--import",d);}catch{c.push("--import","tsx");}let l=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let u=[L.resolve(Pe,`./workers/logic-execution${a}`),L.resolve(Pe,`../workers/logic-execution${a}`)],y=u.find(p=>S.existsSync(p))||u[1];this.workerPool=new Piscina({filename:y,minThreads:this.config?.workerPool?.minThreads??(l?0:2),maxThreads:this.config?.workerPool?.maxThreads??(l?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(l?500:5e3),maxQueue:this.config?.workerPool?.maxQueue??"auto",taskQueue:new FixedQueue,execArgv:c,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}});let v=this.config?.workerPool?.minThreads??(l?0:2);if(this.workerPool&&v>0)for(let p=0;p<v;p++)this.workerPool.run({isWarmup:true}).catch(f=>{b.debug(`[LiopServer] Worker pool warm-up ping failed: ${f.message}`);});try{this.enclavePqcKeypair=b$1.generateKeyPair();}catch{this.enclavePqcKeypair=void 0;}if(this.config?.auth?.role==="nexus"){let p=this.config.auth.issuer||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=this.config.auth.clients||[{client_id:process.env.LIOP_OAUTH_CLIENT_ID||"liop-mesh-agent",client_secret:process.env.LIOP_OAUTH_CLIENT_SECRET||"dev-secret-change-me",grant_types:["client_credentials"],scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query"}],{provider:m,jwks:b}=be({issuer:p,clients:d});this.oauthProvider=m,this.jwtValidator=new q(p,f,b);}else if(this.config?.auth?.role==="node"){let p=this.config.auth.nexusUrl||process.env.LIOP_NEXUS_URL||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=p.endsWith("/oidc")?p:`${p}/oidc`,m=new URL(`${d}/jwks`);this.jwtValidator=new q(p,f,m);}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())),this.config?.auth?.revocationPath&&this.loadRevocationList();}serverInfo;config;static{a(this,"LiopServer");}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;fieldQueryBudget=new Map;taintAnalyzer;tools=new Map;resources=new Map;prompts=new Map;activeSchema=null;sandboxRecords=[];piiScanner;workerPool;meshNode=null;rpcServer=null;boundPort=null;enclavePqcKeypair;jwtValidator;oauthProvider;sessions=new Map;revokedTokenHashes=new Set;lastRevocationLoadTime=0;pqcKeyPair=b$1.generateKeyPair();auditLogger;getDatasetHash(){return O__default.createHash("sha256").update(JSON.stringify(this.sandboxRecords||[])).digest("hex")}static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,\s*(?<name>[^}]*))?\}[\r\n]+(?<logic>[\s\S]*?)[\r\n]+@END/m;extractLogic(e){if(!e||typeof e!="string")return null;let r=e.trim().match(h.LIOP_COMPACT_REGEX);return r?.groups?.logic?r.groups.logic.trim():null}parseUnknownJson(e){if(typeof e!="string")return e;let r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r)}catch{return e}return e}runPreflightPolicy(e,r,t,i="local-client"){if(t){let a=r.replace(/\s+/g," ");if(t.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(l=>l.test(a)))return "Preflight policy rejected: potential row-level export pattern detected.";if(t.preflightDenyPatterns?.some(c=>c.test(a)))return "Preflight policy rejected: custom deny pattern matched."}let n=50;typeof t?.enforceAggregationFirst=="object"&&(n=t.enforceAggregationFirst.minMaxBlockThreshold??50);let s=this.taintAnalyzer.analyze(r,this.sandboxRecords.length,n);if(s)return `Preflight policy rejected: ${s.reason}`;let o=this.taintAnalyzer.extractQueriedFields(r);if(o.length>0){if(i==="__proto__"||i==="constructor"||i==="prototype"||e==="__proto__"||e==="constructor"||e==="prototype")return "Preflight policy rejected: invalid property key names (prototype pollution guard).";let a=t?.budgetStorePath||this.config?.budgetStorePath;if(a)try{let c=this.executeWithBudgetLock(a,l=>{let u=l[i]||{},y=u[e]||{};for(let d of o){let m=this.taintAnalyzer.classifyField(d,t?.sensitiveKeys),b=25,T="public";if(t?.queryBudgetPerField!==void 0?(b=t.queryBudgetPerField,T="override"):m==="forbidden"?(b=3,T="forbidden"):m==="sensitive"&&(b=8,T="sensitive"),(y[d]??0)>=b)return {result:`Preflight policy rejected: Query budget exceeded for field '${d}' (max ${b} per session for ${T} fields). Rotate PQC session to reset budget.`}}let v={...y};for(let d of o)v[d]=(v[d]??0)+1;let p={...u};p[e]=v;let f={...l};return f[i]=p,{result:null,updatedBudget:f}});if(c)return c}catch(c){let l=c instanceof Error?c.message:String(c);b.error(`[LIOP-Server] Error applying persistent query budget: ${l}. Falling back to in-memory.`);let u=this.applyInMemoryBudget(i,e,o,t);if(u)return u}else {let c=this.applyInMemoryBudget(i,e,o,t);if(c)return c}}return null}validateOutputPolicy(e,r,t){if(!t)return null;let i=this.parseUnknownJson(r);if(i&&typeof i=="object"&&i.isError===true)return null;if(t.outputSchema){let s=(()=>{if(!(t.outputSchema instanceof z.ZodObject))return t.outputSchema;let o=t.outputSchema,a=o.def||o._def;return a&&a.catchall!==void 0&&!(a.catchall instanceof z.ZodNever)?o:o.strict()})().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 t.enforceAggregationFirst&&this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(i),t.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 r=e;if(r.computation_result!==void 0)return this.unwrapForAggregationPolicyScan(r.computation_result);if(!Array.isArray(r.content)||r.content.length===0)return e;let t=[];for(let n of r.content)if(n&&typeof n=="object"&&"text"in n){let s=n.text;typeof s=="string"&&t.push(s);}if(t.length===0)return e;let i=t.length===1?t[0]:t.join(`
|
|
9
9
|
`);return this.unwrapForAggregationPolicyScan(i)}violatesAggregationFirstPolicy(e,r,t){if(!r)return false;let i=typeof r=="object"&&typeof r.maxOutputRows=="number"?r.maxOutputRows:10,n=typeof r=="object"&&typeof r.allowPrimitiveArrays=="boolean"?r.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),r,t)}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,r,t)):e.length>0&&e.every(s=>typeof s!="object"||s===null)?!n:e.some(s=>this.violatesAggregationFirstPolicy(s,r,t));if(e&&typeof e=="object"){let s=Object.keys(e);return t!==void 0&&t>0&&t<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,r,t))}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","","SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS:","- Date is poisoned: The 'Date' class/constructor is undefined (Date.now(), Date.parse(), etc. will throw)."," Workaround: Use lexicographical string comparison on ISO 8601 date strings (e.g., record.date >= '2024-01-01').","- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.","- Frozen prototypes: Any modifications to Object.prototype, Array.prototype, etc., are blocked.","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution","","DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism):","- Default field noise scale is derived from node global sensitivity.","- COUNT / LENGTH Optimization: To obtain EXACT counts without noise (sensitivity=1),"," the return keys MUST contain 'count', 'length', 'size', 'num', 'positive', 'negative',"," or start with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count').","- AVERAGE Optimization: Keys containing 'avg', 'mean' or 'average' scale noise"," down automatically by dividing sensitivity by dataset size (sensitivity / n).","- SUM / OTHER queries: Receive full Laplace noise based on global node sensitivity"," (e.g., Sensitivity=100,000 in Bank to protect balances)."];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 THRESHOLDS:","- Small Datasets (< 10 records): Maximum of 3 scalar output fields. Nesting or arrays in output are strictly forbidden.","- Large Datasets (>= 10 records): Maximum of 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)","","QUERY BUDGET TIERS (NIST SP 800-226):","- FORBIDDEN (PII fields like name, accountHolder): Blocked in AST preflight. Never executed, does not consume budget.","- SENSITIVE (fields marked via sensitiveKeys): 8 queries per agent identity (or queryBudgetPerField override).","- PUBLIC (all other fields): 25 queries per agent identity.","- PERSISTENCE: The budget is tracked by agent DID and persisted to disk, NOT by MCP session."," Reconnecting or starting a new session does NOT reset the budget."," Reset requires: administrator calling resetFieldBudget() or manual deletion of the budget store file.","","AUTHENTICATION (tokenSlug Convention):","- Restricted nodes declare authRequired: true in their manifest.","- Token resolution: LIOP_TOKEN_<tokenSlug> (deterministic) > LIOP_TOKEN_<PeerID> > LIOP_TOKEN_<ProviderName>","- Format: tokenSlug must match SCREAMING_SNAKE_CASE /^[A-Z][A-Z0-9_]*$/ (e.g., BANK, VAULT, HFT_ORACLE)."),e.join(`
|
|
10
10
|
`)}extractSchemaFieldSummary(e,r=0){if(r>3)return "{...}";let t=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,r+1);return `${o}(array of ${l})`}if(c==="object"&&a.properties){let l=this.extractSchemaFieldSummary(a,r+1);return `${o}(${l})`}return `${o}(${c||"unknown"})`}).join(", ")}}`:t==="array"&&n?`Array of ${this.extractSchemaFieldSummary(n,r+1)}`:t||Object.keys(e).join(", ")}async connect(e={}){return this.connectToMesh(e)}tool(e,r,t,i,n){if(this.tools.has(e))throw new Error(`Tool already registered: ${e}`);let s=z.object(t),o=z.toJSONSchema(s,{target:"draft-07"}),a$1=r,c=i;if(t.payload&&t.payload instanceof z.ZodString){let u=this.config?.security?.forbiddenKeys||[];if(a$1+=`
|
|
11
11
|
|
|
@@ -42,5 +42,5 @@ ${JSON.stringify(this.activeSchema,null,2)}`:""}
|
|
|
42
42
|
Protocol Adherence is mandatory for successful execution.`}}]}));}resource(e,r,t,i,n){if(this.resources.has(r))throw new Error(`Resource URI already registered: ${r}`);this.resources.set(r,{name:e,uri:r,description:t,mimeType:i,content:n});}buildExecutionGuidelines(){return ["LIOP Sandbox Execution Guidelines","=================================","","1. DATE POISONING & FILTERING WORKAROUND:"," The global 'Date' class is set to undefined inside the sandbox. Calling 'new Date()', 'Date.now()', or 'Date.parse()' will throw a ReferenceError."," - Workaround: Perform chronological filtering using lexicographical string comparisons on ISO 8601 strings."," Example: const filtered = env.records.filter(r => r.date >= '2024-01-01' && r.date <= '2024-12-31');","","2. K-ANONYMITY CONSTRAINTS:"," - Datasets with LESS than 10 records: The returned object must contain at most 3 scalar fields, and must NOT contain any arrays or nested objects."," - Datasets with 10 or MORE records: The returned object can contain up to 10 fields.","","3. DIFFERENTIAL PRIVACY SUFFIXES:"," To avoid Laplacian noise adding random perturbations to your counts or averages, you must name your object keys using specific terms:"," - Counts (Exact, no noise): Key names must contain 'count', 'length', 'size', 'num', 'positive', 'negative', or start with 'total_' or 'num_'."," - Averages (Reduced noise): Key names must contain 'avg', 'mean', or 'average'."," - Sums/Other: Will receive full Laplace noise.","","4. GENERAL RESTRICTIONS:"," - Do not use 'eval', 'Function', 'setTimeout', 'setInterval', 'Buffer', 'ArrayBuffer', or TypedArrays."," - Do not attempt to modify prototypes (Object.prototype, Array.prototype).","","5. QUERY BUDGET TIERS (NIST SP 800-226):"," The per-field query budget is tracked by agent DID and persisted to disk (not per MCP session)."," - FORBIDDEN (PII fields): Always blocked in AST preflight. Does not consume budget."," - SENSITIVE (sensitiveKeys): 8 queries per agent identity (or queryBudgetPerField override)."," - PUBLIC (other fields): 25 queries per agent identity."," - Reset requires administrator intervention via resetFieldBudget()."].join(`
|
|
43
43
|
`)}dataDictionary(e,r="Global Medical Data Dictionary",t="liop://schema/global",i="Exposes the internal database schema for Zero-Shot Autonomy planning"){e.$comment="LIOP DIRECTIVES: 1. Date is undefined (Date.now(), new Date() throw). Workaround: use lexicographical string comparison on ISO 8601 string dates (e.g. record.date >= '2024-01-01'). 2. Small datasets (<10 records) limit outputs to max 3 scalar keys with NO nesting. 3. DP counts must contain count/length/size/num/total_ prefix/suffix.",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.ZodString&&o.tool.description&&!o.tool.description.includes("Data structure:")&&(o.tool.description+=`
|
|
44
44
|
Data structure: ${n}. Full schema: resource ${t}. Guidelines: resource liop://schema/guidelines`,this.tools.set(s,o));this.resources.has("liop://schema/guidelines")||this.resource("LIOP Execution Guidelines","liop://schema/guidelines","Directives for generating compliant JavaScript code for the LIOP Sandbox runtime","text/plain",()=>Promise.resolve(this.buildExecutionGuidelines())),this.resource(r,t,i,"application/json",JSON.stringify(e,null,2));}clearAstCache(){this.logicCache.clear(),b.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(e){let r=Date.now(),t=this.toolCallWindowMs,i=this.toolCallMaxPerWindow,s=(this.toolCallWindows.get(e)||[]).filter(o=>r-o<t);if(s.length>=i){let o=Math.ceil((s[0]+t-r)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${e}. Max ${i} per ${t/1e3}s window. Retry after ${o}s.`}],isError:true}}return s.push(r),this.toolCallWindows.set(e,s),null}checkGlobalRateLimit(){let e=Date.now(),r=this.toolCallWindowMs,t=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(i=>e-i<r),this.globalCallWindow.length>=t){let i=Math.ceil((this.globalCallWindow[0]+r-e)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${t} total calls per ${r/1e3}s window. Retry after ${i}s.`}],isError:true}}return this.globalCallWindow.push(e),null}async callTool(e,r="local-client"){let t=this.tools.get(e.name);if(!t)throw new Error(`Tool not found: ${e.name}`);let i=this.checkGlobalRateLimit();if(i)return i;let n=this.checkToolCallRateLimit(e.name);if(n)return n;try{let s=t.schema.parse(e.arguments||{});if(e.arguments?.__liop_bypass_ast_cache===!0&&(s.__liop_bypass_ast_cache=!0),s&&typeof s.payload=="string"){let a=s.payload,c=this.extractLogic(a);if(c){let l=this.runPreflightPolicy(e.name,c,t.policy,r);return l?{content:[{type:"text",text:l}],isError:!0}:(s.payload=c,await this.executeInWorkerPool(s,c,e.name))}}return await t.handler(s,{})}catch(s){let o=s;return o instanceof z.ZodError?{content:[{type:"text",text:`Validation Error: ${o.message}`}],isError:true}:{content:[{type:"text",text:`Internal Execution Error: ${o.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 r=this.prompts.get(e.name);if(!r)throw new Error(`Prompt not found: ${e.name}`);return await r.handler(e)}listResources(){return Array.from(this.resources.values())}async readResource(e){let r=this.resources.get(e);if(!r)throw new Error(`Resource not found: ${e}`);let t="No description provided";return typeof r.content=="function"?t=await r.content():typeof r.content=="string"?t=r.content:r.description&&(t=r.description),{contents:[{uri:r.uri,mimeType:r.mimeType||"text/plain",text:t}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(e){this.sandboxRecords=e;}getSandboxData(){return this.sandboxRecords}getBoundPort(){return this.boundPort}async connectToMesh(e={}){let r=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,t=e.port??r??50051,i=/^[A-Z][A-Z0-9_]*$/;if(this.config?.tokenSlug&&!i.test(this.config.tokenSlug))throw new Error(`Invalid tokenSlug "${this.config.tokenSlug}". Must match SCREAMING_SNAKE_CASE: /^[A-Z][A-Z0-9_]*$/ (e.g., "BANK", "VAULT", "HFT_ORACLE").`);this.meshNode=new a$1(e.meshConfig),await this.meshNode.start();let n=this.meshNode;this.meshNode.registerManifestHandler(()=>{let s=this.listTools().map(l=>{let u=this.tools.get(l.name);return {name:l.name,description:l.description,inputSchema:l.inputSchema,zkMode:u?.policy?.zkMode,guestImageId:u?.policy?.guestImageId??this.config?.guestImageId,circuitName:u?.policy?.circuitName,vkey:u?.policy?.vkey}}),o=Array.from(this.resources.values()).map(l=>({name:l.name,uri:l.uri,description:l.description,mimeType:l.mimeType,text:typeof l.content=="string"?l.content:l.description})),a={peerId:n.getPeerId(),grpcPort:t,tools:s,resources:o,serverInfo:this.serverInfo,authRequired:this.jwtValidator!==void 0,tokenSlug:this.config?.tokenSlug,guestImageId:this.config?.guestImageId,vkeys:this.config?.zkVkeys,taxonomy:this.config?.taxonomy?{domain:this.config.taxonomy.domain||"Unknown Domain",clearanceTier:this.config.taxonomy.clearanceTier??0,executionTypes:this.config.taxonomy.executionTypes||[]}:void 0},c=b$1.signManifest(a,this.pqcKeyPair.secretKey,this.pqcKeyPair.publicKey);return {...a,pqcSignature:c.signature,pqcPublicKey:c.publicKey}});for(let s of this.listTools())await this.meshNode.announceCapability(s.name).catch(b.info);await this.meshNode.announceManifest().catch(b.info),this.rpcServer=new J,this.rpcServer.addService({negotiateIntent:a((s,o)=>{let a=s.request;if(b.info(`[LIOP-RPC] Negotiating intent for capability: ${a.capability_hash}`),this.jwtValidator){let c=s.metadata.get("authorization")[0];if(!c){o({code:_.status.UNAUTHENTICATED,details:"Missing Authorization header in gRPC metadata"});return}let l=c.startsWith("Bearer ")?c.slice(7):c,u=O__default.createHash("sha256").update(l).digest("hex").toLowerCase();if(this.loadRevocationList(),this.revokedTokenHashes.has(u)){o({code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let y=this.config?.auth?.localTestToken,v=/^[a-zA-Z0-9_-]+-local-test-token$/;if(y){if(l===y){b.info("[LIOP-RPC] Bypass authentication for matching localTestToken: [REDACTED]"),import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:p})=>{let{publicKey:f,secretKey:d}=await p.generateKeyPair(),m=O__default.randomUUID();this.sessions.set(m,{capability_hash:a.capability_hash,kyber_sk:d,agent_did:a.agent_did,tokenHash:u,createdAt:Date.now()}),o(null,{accepted:true,session_token:m,error_message:"",kyber_public_key:f});});return}o({code:_.status.PERMISSION_DENIED,details:l&&v.test(l)?"Pre-shared local test token is invalid for this resource domain (segregation violation).":"Access Denied: This restricted node requires its specific static access token."});return}this.jwtValidator.validate(l).then(p=>{let f=a$3("tools/call",p);if(!f.allowed){o({code:_.status.PERMISSION_DENIED,details:f.reason||"Access Denied"});return}import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:d})=>{let{publicKey:m,secretKey:b}=await d.generateKeyPair(),T=O__default.randomUUID();this.sessions.set(T,{capability_hash:a.capability_hash,kyber_sk:b,agent_did:a.agent_did,tokenHash:u,createdAt:Date.now()}),o(null,{accepted:true,session_token:T,error_message:"",kyber_public_key:m});});}).catch(p=>{o({code:_.status.UNAUTHENTICATED,details:`Invalid JWT token: ${p.message}`});});}else import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:c})=>{let{publicKey:l,secretKey:u}=await c.generateKeyPair(),y=O__default.randomUUID();this.sessions.set(y,{capability_hash:a.capability_hash,kyber_sk:u,agent_did:a.agent_did,createdAt:Date.now()}),o(null,{accepted:true,session_token:y,error_message:"",kyber_public_key:l});});},"negotiateIntent"),executeLogic:a(async s=>{let o=s.request;b.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${o.session_token}`);let a$1=a(async()=>{let c=this.sessions.get(o.session_token);if(!c){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Invalid session token"});return}let l=3600*1e3;if(c.createdAt){let f=Date.now()-c.createdAt;if(f>l){this.sessions.delete(o.session_token),s.emit("error",{code:_.status.UNAUTHENTICATED,details:`[LIOP-PQC] Session secret expired: Age (${Math.round(f/1e3)}s) exceeds 3600s TTL limit. Re-handshake required.`});return}}if(c.tokenHash&&(this.loadRevocationList(),this.revokedTokenHashes.has(c.tokenHash))){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let u=c.capability_hash,v=(u?this.tools.get(u):void 0)?.policy,p="";try{let d=(await createMlKem768()).decap(new Uint8Array(o.pqc_ciphertext),c.kyber_sk),m=Buffer.from(d),b$1=Buffer.from(o.wasm_binary),T=b$1.subarray(-16),A=b$1.subarray(0,-16),w=O__default.createDecipheriv("aes-256-gcm",m,Buffer.from(o.aes_nonce||new Uint8Array(12)));w.setAuthTag(T);let x=w.update(A);x=Buffer.concat([x,w.final()]),p=x.toString("utf-8");let I=this.extractLogic(p)||p.trim(),N=this.runPreflightPolicy(u||"unknown_tool",I,v,c.agent_did||o.session_token);if(N){b.info(`[LIOP-RPC] Preflight blocked: ${N}`);let M={semantic_evidence:N,cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(M,()=>{s.end();});return}}catch(f){let d=f instanceof Error?f.message:String(f);b.error(`[LIOP-RPC] Preflight decryption failed: ${d}`),s.emit("error",{code:_.status.INTERNAL,details:`Preflight logic analysis failed: ${d}`});return}try{let f$2=v?{epsilon:v.dpEpsilon??1,sensitivity:v.dpSensitivity??1,smallDatasetThreshold:v.dpSmallDatasetThreshold??50}:void 0,d=o.requested_proof_mode;(d===void 0||d===0)&&(v?.zkMode==="required"?d=2:v?.zkMode==="optimistic"?d=1:d=0);let m=await this.workerPool.run({ciphertext:o.pqc_ciphertext,secretKeyObj:Array.from(c.kyber_sk),wasmBinary:o.wasm_binary,inputs:o.inputs,aesNonce:o.aes_nonce,records:this.sandboxRecords,sessionToken:o.session_token,sessionTimestamp:c.createdAt,isEncrypted:!0,proofMode:d,guestImageId:v?.guestImageId??this.config?.guestImageId,pqcSigningKey:v?.pqcSign?this.enclavePqcKeypair?.secretKey:void 0,dpConfig:f$2});if(d===2&&m.proof_type!==2&&m.proof_type!==3){b.error(`[LIOP-RPC] Enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable for ${u||"tool"}`);let k={semantic_evidence:"[LIOP-ZK] Clearance Tier 1 enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0,proof_type:0};s.write(k,()=>{s.end();});return}let b$1=a$2(m.output),T,A=b$1;try{T=typeof b$1=="string"?b$1:JSON.stringify(b$1);let k=JSON.parse(T);if(k.__liop_proxy_tool){b.info(`[LIOP-RPC] Executing Proxied Tool: ${k.__liop_proxy_tool}`);let W=c.agent_did||"unknown-client",D=await this.callTool({name:k.__liop_proxy_tool,arguments:k.__liop_proxy_args||{}},W);if(D.isError){b.info(`[LIOP-RPC] Proxy tool execution failed: ${D.content[0].text}`);let U={semantic_evidence:D.content[0].text||"Unknown error",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(U,()=>{s.end();});return}let G=a$2(D);T=JSON.stringify(G),A=this.unwrapForAggregationPolicyScan(G);}}catch{T=String(b$1);}let w$1=this.validateOutputPolicy(u||"unknown_tool",A,v);if(w$1){b.info(`[LIOP-RPC] Output policy blocked for ${u||"unknown_tool"}: ${w$1}`);let D={semantic_evidence:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?w$1:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(D,()=>{s.end();});return}let x$1={semantic_evidence:T,cryptographic_proof:Buffer.from(m.image_id||"","hex"),zk_receipt:m.zk_receipt?Buffer.from(m.zk_receipt,"base64"):Buffer.from(""),is_error:!1,proof_type:m.proof_type===3?3:m.proof_type===2?2:0,guest_image_id:m.guest_image_id||v?.guestImageId||this.config?.guestImageId||""},I=await this.piiScanner.scan(A),N=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(A),v?.enforceAggregationFirst,this.sandboxRecords?.length),M=!!(I||N);if(M){let k$1=I||"Aggregation-First Policy Violation";b.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${k$1}`),x$1.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",x$1.is_error=!0,k.inc({reason:I?"pii_scanner":"aggregation_policy"});}this.auditLogger.recordExecution({agentDid:c.agent_did||"unknown",peerId:c.tokenHash||"unknown",toolName:u||"unknown",datasetHash:this.getDatasetHash(),fuelConsumed:m.fuel_consumed||0,outputHash:O__default.createHash("sha256").update(x$1.semantic_evidence).digest("hex"),zkReceiptSig:m.zk_receipt||"",status:M?"BLOCKED_EGRESS":"SUCCESS"}),f.inc({capability:u||"unknown",tool:u||"unknown",status:M?"blocked_egress":"success",role:"executor"}),h$1.observe({capability:u||"unknown",tool:u||"unknown"},m.fuel_consumed||0);try{let k=Buffer.byteLength(x$1.semantic_evidence||"")+(x$1.cryptographic_proof?x$1.cryptographic_proof.length:0)+(x$1.zk_receipt?x$1.zk_receipt.length:0);if(w.inc({capability:u||"unknown"},k),this.sandboxRecords&&this.sandboxRecords.length>0){let W=JSON.stringify(this.sandboxRecords),D=Buffer.byteLength(W),G=Math.max(0,D-k);G>0&&x.inc({capability:u||"unknown"},G);try{let U=f$1.getInstance(),xe=U.countTokens(W),we=U.countTokens(x$1.semantic_evidence||""),Ie=U.countTokens(p||"");U.record({type:"tool_call",method:"ExecuteLogic",toolName:u||"unknown",estimatedInputTokens:Ie,estimatedOutputTokens:we,originDatasetTokens:xe});}catch{}}}catch{}s.write(x$1,()=>{s.end();});}catch(f$1){let d=f$1,m=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",b$1=d.message||String(f$1);b.error(`[LIOP-RPC] Execution Error: ${b$1}`);let T=m?`Execution Error: ${b$1}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.";this.auditLogger.recordExecution({agentDid:c.agent_did||"unknown",peerId:c.tokenHash||"unknown",toolName:u||"unknown",datasetHash:this.getDatasetHash(),fuelConsumed:0,outputHash:O__default.createHash("sha256").update(T).digest("hex"),zkReceiptSig:"",status:"ERROR"}),f.inc({capability:u||"unknown",tool:u||"unknown",status:"error",role:"executor"}),g$1.inc({capability:u||"unknown",error_type:"runtime_error"});let A={semantic_evidence:T,cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{s.write(A,()=>{s.end();});}catch{s.end();}}},"proceed");if(this.jwtValidator){let c=s.metadata.get("authorization")[0];if(!c){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Missing Authorization header in gRPC metadata"});return}let l=c.startsWith("Bearer ")?c.slice(7):c,u=O__default.createHash("sha256").update(l).digest("hex").toLowerCase();if(this.loadRevocationList(),this.revokedTokenHashes.has(u)){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let y=this.config?.auth?.localTestToken,v=/^[a-zA-Z0-9_-]+-local-test-token$/;if(y){if(l===y){b.info("[LIOP-RPC] Bypass authentication in executeLogic for matching localTestToken: [REDACTED]"),await a$1();return}s.emit("error",{code:_.status.PERMISSION_DENIED,details:l&&v.test(l)?"Pre-shared local test token is invalid for this resource domain (segregation violation).":"Access Denied: This restricted node requires its specific static access token."});return}try{let p=await this.jwtValidator.validate(l),f=a$3("tools/call",p);if(!f.allowed){s.emit("error",{code:_.status.PERMISSION_DENIED,details:f.reason||"Access Denied"});return}await a$1();}catch(p){s.emit("error",{code:_.status.UNAUTHENTICATED,details:`Invalid JWT token: ${p instanceof Error?p.message:String(p)}`});}}else await a$1();},"executeLogic")}),this.boundPort=await this.rpcServer.listen(t),b.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(e,r,t){try{let i=t?this.tools.get(t)?.policy:void 0,n=i?{epsilon:i.dpEpsilon??1,sensitivity:i.dpSensitivity??1,smallDatasetThreshold:i.dpSmallDatasetThreshold??50}:void 0,s=0;i?.zkMode==="required"?s=2:i?.zkMode==="optimistic"&&(s=1);let o=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(r),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1,proofMode:s,guestImageId:i?.guestImageId??this.config?.guestImageId,pqcSigningKey:i?.pqcSign?this.enclavePqcKeypair?.secretKey:void 0,dpConfig:n});if(s===2&&o.proof_type!==2&&o.proof_type!==3)return {content:[{type:"text",text:"[LIOP-ZK] Clearance Tier 1 enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable."}],isError:!0};let a=o.output,c=a$2(a),u=[{type:"text",text:JSON.stringify({computation_result:c,image_id:o.image_id,zk_receipt:o.zk_receipt,proof_type:o.proof_type===3?"GROTH16_PQC_HYBRID":o.proof_type===2?"GROTH16":"HMAC_LEGACY",guest_image_id:o.guest_image_id,status:"Worker Pool Execution Success"})}],y=t?this.tools.get(t)?.policy:void 0,v=this.validateOutputPolicy(t||"unknown_tool",c,y);if(v)return b.info(`[LIOP-SDK] Output policy blocked for ${t||"unknown_tool"}: ${v}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?v:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let p=await this.piiScanner.scan(c),f=this.violatesAggregationFirstPolicy(c,y?.enforceAggregationFirst,this.sandboxRecords?.length);if(p||f){let d=p||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return b.info(`[LIOP-SDK] Secure egress blocked in local execution: ${d}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${d}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:u}}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 b.error(`[LIOP-SDK] WorkerPool Execution Fault: ${o}`),{content:[{type:"text",text:o.includes("worker_thread_exited")||o.includes("ERR_WORKER_OUT_OF_MEMORY")||o.includes("terminated")||o.includes("heap limit")?"[LIOP] Execution terminated: memory limit exceeded (64MB heap). Reduce data processing volume.":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();}loadRevocationList(){let e=this.config?.auth?.revocationPath;if(e)try{if(S.existsSync(e)){let r=S.statSync(e);if(r.mtimeMs<=this.lastRevocationLoadTime)return;let t=S.readFileSync(e,"utf-8"),i=JSON.parse(t);if(Array.isArray(i)){this.revokedTokenHashes.clear();for(let n of i)typeof n=="string"&&this.revokedTokenHashes.add(n.trim().toLowerCase());this.lastRevocationLoadTime=r.mtimeMs,b.info(`[LiopServer] Loaded ${this.revokedTokenHashes.size} revoked token hashes from ${e}`);}}else {let r=L.dirname(e);S.existsSync(r)||S.mkdirSync(r,{recursive:!0}),S.writeFileSync(e,JSON.stringify([],null,2),"utf-8"),this.lastRevocationLoadTime=Date.now(),b.info(`[LiopServer] Created empty local revocation list at ${e}`);}}catch(r){b.error(`[LiopServer] Failed to load revocation list: ${r instanceof Error?r.message:String(r)}`);}}revokeToken(e){if(!e)return;let r=O__default.createHash("sha256").update(e).digest("hex").toLowerCase();this.revokeTokenHash(r);}revokeTokenHash(e){if(!e)return;let r=e.toLowerCase();this.loadRevocationList(),this.revokedTokenHashes.add(r);let t=this.config?.auth?.revocationPath;if(t)try{let i=L.dirname(t);S.existsSync(i)||S.mkdirSync(i,{recursive:!0});let n=Array.from(this.revokedTokenHashes);S.writeFileSync(t,JSON.stringify(n,null,2),"utf-8");let s=S.statSync(t);this.lastRevocationLoadTime=s.mtimeMs,b.info(`[LiopServer] Persisted revocation for hash ${r} to ${t}`);}catch(i){b.error(`[LiopServer] Failed to persist revocation: ${i instanceof Error?i.message:String(i)}`);}}resetFieldBudget(e,r){if(e==="__proto__"||e==="constructor"||e==="prototype"||r&&(r==="__proto__"||r==="constructor"||r==="prototype")){b.warn(`[LiopServer] Rejected resetFieldBudget for unsafe clientId/toolName: ${e}`);return}if(r){let i=this.fieldQueryBudget.get(e);i&&i.delete(r);}else this.fieldQueryBudget.delete(e);let t=this.config?.budgetStorePath;if(t)try{this.executeWithBudgetLock(t,i=>(r?Object.hasOwn(i,e)&&i[e]&&delete i[e][r]:Object.hasOwn(i,e)&&delete i[e],{result:void 0,updatedBudget:i})),b.info(`[LiopServer] Reset query budget for client ${e}${r?` / tool ${r}`:""}`);}catch(i){b.error(`[LiopServer] Failed to reset persistent budget: ${i instanceof Error?i.message:String(i)}`);}}getPersistentBudget(e){try{if(!S.existsSync(e))return Object.create(null);let r=S.readFileSync(e,"utf-8"),t=JSON.parse(r||"{}");if(t&&typeof t=="object"){let i=Object.create(null);for(let[n,s]of Object.entries(t))n!=="__proto__"&&n!=="constructor"&&n!=="prototype"&&(i[n]=s);return i}return Object.create(null)}catch{return Object.create(null)}}savePersistentBudget(e,r){let t=`${e}.tmp`,i=L.dirname(e);S.existsSync(i)||S.mkdirSync(i,{recursive:true}),S.writeFileSync(t,JSON.stringify(r,null,2),"utf-8"),S.renameSync(t,e);}executeWithBudgetLock(e,r){let t=`${e}.lock`,i=100,s=0,o=L.dirname(e);if(!S.existsSync(o))try{S.mkdirSync(o,{recursive:!0});}catch{}for(;s<i;)try{S.writeFileSync(t,process.pid.toString(),{flag:"wx"});break}catch(a){if(a&&typeof a=="object"&&"code"in a&&a.code==="EEXIST"){s++;}else throw a}if(s>=i)throw new Error("Timeout acquiring lock for persistent query budget database");try{let a=this.getPersistentBudget(e),{result:c,updatedBudget:l}=r(a);return l&&this.savePersistentBudget(e,l),c}finally{try{S.existsSync(t)&&S.unlinkSync(t);}catch{}}}applyInMemoryBudget(e,r,t,i){let n=this.fieldQueryBudget.get(e);n||(n=new Map,this.fieldQueryBudget.set(e,n));let s=n.get(r);s||(s=new Map,n.set(r,s));for(let o of t){let a=this.taintAnalyzer.classifyField(o,i?.sensitiveKeys),c=25,l="public";if(i?.queryBudgetPerField!==void 0?(c=i.queryBudgetPerField,l="override"):a==="forbidden"?(c=3,l="forbidden"):a==="sensitive"&&(c=8,l="sensitive"),(s.get(o)??0)>=c)return `Preflight policy rejected: Query budget exceeded for field '${o}' (max ${c} per session for ${l} fields). Rotate PQC session to reset budget.`}for(let o of t){let a=s.get(o)??0;s.set(o,a+1);}return null}};
|
|
45
|
-
export{J as a,ve as b,Ee as c,ie as d,Se as e,H as f,q as g,be as h,X as i,R as j,Te as k,ee as l,Re as m};//# sourceMappingURL=chunk-
|
|
46
|
-
//# sourceMappingURL=chunk-
|
|
45
|
+
export{J as a,ve as b,Ee as c,ie as d,Se as e,H as f,q as g,be as h,X as i,R as j,Te as k,ee as l,Re as m};//# sourceMappingURL=chunk-PRNQM5KL.js.map
|
|
46
|
+
//# sourceMappingURL=chunk-PRNQM5KL.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import {d as d$1,b as b$1,h}from'./chunk-GWVSCZUS.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import {randomUUID}from'crypto';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';var O=10,L=1800*1e3,w=60*1e3,g=class{constructor(e,t={}){this.options=t;this.app=new Hono,this.bridgeLogic=new d(e),this.activeSessions=new Map,this.maxSessionsPerIp=t.maxSessionsPerIp??O,this.sessionTimeoutMs=t.sessionTimeoutMs??L,this.setupRoutes();}options;static{a(this,"LiopStreamBridge");}app;httpServer=null;bridgeLogic;activeSessions;evictionTimer=null;maxSessionsPerIp;sessionTimeoutMs;async createSessionTransport(e){let{WebStandardStreamableHTTPServerTransport:t}=await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),s=new t({sessionIdGenerator:a(()=>randomUUID(),"sessionIdGenerator"),onsessioninitialized:a(i=>{this.activeSessions.set(i,{transport:s,lastActivity:Date.now(),clientIp:e}),b.info(`[LIOP-StreamBridge] Session opened: ${i} (IP: ${e})`);},"onsessioninitialized")});return s.onmessage=async i=>{if(s.sessionId){let r=this.activeSessions.get(s.sessionId);r&&(r.lastActivity=Date.now());}try{let r=await this.bridgeLogic.handleJsonRpcRequest(i);r!==void 0&&await s.send(r);}catch(r){b.info("[LIOP-StreamBridge] JSON-RPC error:",r.message);}},s.onclose=()=>{s.sessionId&&(this.activeSessions.delete(s.sessionId),b.info(`[LIOP-StreamBridge] Session closed: ${s.sessionId}`));},s}countSessionsByIp(e){let t=0;for(let s of this.activeSessions.values())s.clientIp===e&&t++;return t}getClientIp(e){return e.req.header("x-forwarded-for")?.split(",")[0]?.trim()||e.req.header("x-real-ip")||"unknown"}evictIdleSessions(){let e=Date.now();for(let[t,s]of this.activeSessions)e-s.lastActivity>this.sessionTimeoutMs&&(b.info(`[LIOP-StreamBridge] Evicting idle session: ${t}`),s.transport.close().catch(()=>{}),this.activeSessions.delete(t));}setupRoutes(){this.app.use("*",cors()),process.env.ZERO_TRUST_TOKEN||(process.env.ZERO_TRUST_TOKEN=randomUUID(),b.info("=".repeat(60)),b.info("\u26A0\uFE0F STRICT ZERO-TRUST MODE ENABLED \u26A0\uFE0F"),b.info("No ZERO_TRUST_TOKEN found in environment."),b.info("A secure ephemeral token has been generated for this session:"),b.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`),b.info("=".repeat(60))),this.app.use("/mcp",async(e,t)=>{let s=e.req.header("Authorization");if(!s?.startsWith("Bearer "))return e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401);let i=s.slice(7),r=process.env.ZERO_TRUST_TOKEN;if(r&&i===r){await t();return}let o=this.bridgeLogic.getServer()?.jwtValidator;if(o)try{await o.validate(i),await t();return}catch(a){return b.info(`[LIOP-StreamBridge] JWT Validation failed: ${a.message}`),e.json({error:`Unauthorized: JWT Validation failed - ${a.message}`},401)}return b.info("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token."),e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401)}),this.app.all("/mcp",async e=>{let t=e.req.header("mcp-session-id");if(t){let a=this.activeSessions.get(t);if(!a)return e.json({error:"Session not found"},404);a.lastActivity=Date.now();let c=await a.transport.handleRequest(e.req.raw);return e.req.method==="DELETE"&&(this.activeSessions.delete(t),b.info(`[LIOP-StreamBridge] Session closed (DELETE): ${t}`)),c}let s=e.req.header("content-type")||"";if(e.req.method==="POST"&&s.includes("application/json"))try{let a=await e.req.json();if(a.method==="server/discover"||a.params?._meta||!!0){let c=await this.bridgeLogic.handleJsonRpcRequest(a);return c!==void 0?e.json(c):e.body(null,204)}}catch{}let i=this.getClientIp(e),r=this.countSessionsByIp(i);return r>=this.maxSessionsPerIp?(b.info(`[LIOP-StreamBridge] Rate limit hit for IP: ${i} (${r} sessions)`),e.json({error:"Too Many Sessions: Rate limit exceeded"},429)):await(await this.createSessionTransport(i)).handleRequest(e.req.raw)});}async start(e){let t=e??this.options.port??3e3;return this.evictionTimer=setInterval(()=>this.evictIdleSessions(),w),new Promise(s=>{this.httpServer=serve({fetch:this.app.fetch,port:t},i=>{b.info(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${i.port}/mcp`),s();});})}async stop(){this.evictionTimer&&(clearInterval(this.evictionTimer),this.evictionTimer=null);for(let[e,t]of this.activeSessions)await t.transport.close(),this.activeSessions.delete(e);this.httpServer&&(this.httpServer.close(),b.info("[LIOP-StreamBridge] HTTP ports released."));}};var d=class{constructor(e,t={}){this.options=t;e?.constructor?.name==="LiopServer"?(this.liopServer=e,b.info("[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)")):e?.constructor?.name==="McpServer"?(this.legacyMcpServer=e,b.info("[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)")):(this.legacyMcpServer=e,b.info("[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)"));}options;static{a(this,"LiopMcpBridge");}liopServer=null;legacyMcpServer=null;async handleJsonRpcRequest(e){let t=e.id,s=e.method,i=e.params;return e.jsonrpc!=="2.0"?this.errorResponse(t,-32600,"Invalid Request"):this.liopServer?this.handleLiopToMcp(t,s,i):this.legacyMcpServer&&this.liopServer?this.handleLiopToMcp(t,s,i):this.errorResponse(t,-32601,"Bridge source not configured")}async handleLiopToMcp(e,t,s){if(!this.liopServer)return null;let i=d$1({method:t,params:s,id:e});if(t==="initialize")return this.successResponse(e,{protocolVersion:b$1,capabilities:{prompts:{listChanged:true},resources:{listChanged:true},tools:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()});if(t==="server/discover")return this.successResponse(e,{resultType:"complete",supportedVersions:[h,b$1],capabilities:{prompts:{listChanged:true},resources:{listChanged:true},tools:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()});if(t!=="notifications/initialized"){if(t==="ping")return this.successResponse(e,{});if(t==="tools/list"){let r=this.liopServer.listTools().sort((o,a)=>o.name.localeCompare(a.name));return this.successResponse(e,i?{tools:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",tools:r})}if(t==="resources/list"){let r=this.liopServer.listResources().sort((o,a)=>o.uri.localeCompare(a.uri));return this.successResponse(e,i?{resources:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resources:r})}if(t==="prompts/list"){let r=this.liopServer.listPrompts().sort((o,a)=>o.name.localeCompare(a.name));return this.successResponse(e,i?{prompts:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",prompts:r})}if(t==="prompts/get"){if(!s?.name)return this.errorResponse(e,-32602,"Missing prompt name");try{let r=await this.liopServer.getPrompt({name:s.name,arguments:s.arguments});return this.successResponse(e,i||typeof r!="object"||r===null?r:{resultType:"complete",...r})}catch(r){return this.errorResponse(e,-32e3,r.message)}}if(t==="resources/read"){if(!s?.uri)return this.errorResponse(e,-32602,"Missing resource URI");try{let r=await this.liopServer.readResource(s.uri);return this.successResponse(e,i?r:typeof r=="object"&&r!==null?{resultType:"complete",ttlMs:6e4,cacheScope:"private",...r}:{resultType:"complete",ttlMs:6e4,cacheScope:"private",contents:r})}catch(r){return this.errorResponse(e,-32e3,r.message)}}if(t==="tools/call"){if(!s?.name)return this.errorResponse(e,-32602,"Missing tool name");let r={name:s.name,arguments:s.arguments||{}};try{let o=await this.liopServer.callTool(r);return (o.isError?!0:await this.verifyZkReceipt(r,o))?this.successResponse(e,i?o:{resultType:"complete",...o}):this.successResponse(e,{content:[{type:"text",text:"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload."}],isError:!0})}catch(o){return this.errorResponse(e,-32e3,o.message)}}return this.errorResponse(e,-32601,"Method not found")}}successResponse(e,t){return {jsonrpc:"2.0",id:e,result:t}}errorResponse(e,t,s){return {jsonrpc:"2.0",id:e,error:{code:t,message:s}}}async verifyZkReceipt(e,t){if(!e.arguments?.payload||typeof e.arguments.payload!="string")return true;try{let s=e.arguments.payload,i=t.content[0]?.text;if(i&&typeof i=="string")try{let r=JSON.parse(i);if(r.image_id||r.zk_receipt){let{LiopVerifier:o}=await import('./verifier-J4NQYZX5.js'),a=new o,c=Buffer.from(r.zk_receipt||"","base64"),u=c.length>0&&c[0]===2;if(!await a.verifyZkReceipt(Buffer.from(s,"utf-8"),r.image_id||"",c,{guestImageIdHex:r.guest_image_id,circuitName:r.circuit_name,expectedOutput:r.computation_result,zkPolicy:u?"required":"none"}))return !1;r.audit_status=u?"VERIFIED: Groth16 Zero-Knowledge Proof Certified by LiopMcpBridge":"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge",t.content[0].text=JSON.stringify(r);}}catch{}return !0}catch(s){return b.info("[LIOP-Bridge] ZK-Verifier Failure:",s),false}}async connect(){if(this.legacyMcpServer){let{LiopServer:i}=await import('./server.js');if(this.liopServer=new i(this.options.serverInfo||{name:"liop-bridge",version:"1.0.0"},{security:this.options.security}),this.options.publishToMesh){await this.liopServer.connect();let r=this.legacyMcpServer;if(r._registeredTools)for(let[o,a]of Object.entries(r._registeredTools)){let c=a;this.liopServer.tool(o,c.description||"",c.inputSchema||{},async u=>await c.handler(u));}if(r._registeredResources)for(let[o,a]of Object.entries(r._registeredResources)){let c=a;this.liopServer.resource(c.name,o,c.metadata?.description||"",c.metadata?.mimeType||"application/octet-stream",async()=>(await c.readCallback(new URL(o))).contents[0].text);}}return}let t=(await import('readline')).createInterface({input:process.stdin,output:process.stdout,terminal:false}),s=a(async()=>{b.info("[LIOP-Bridge] Disconnecting session..."),this.liopServer&&await this.liopServer.close(),process.exit(0);},"shutdown");t.on("close",s),process.on("SIGINT",s),process.on("SIGTERM",s),t.on("line",async i=>{if(i.trim())try{let r=JSON.parse(i),o=await this.handleJsonRpcRequest(r);o&&process.stdout.write(`${JSON.stringify(o)}
|
|
2
|
-
`);}catch(r){b.error(`[LIOP-Bridge] Error: ${r.message}`);}});}getServer(){return this.liopServer}};export{g as a,d as b};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
`);}catch(r){b.error(`[LIOP-Bridge] Error: ${r.message}`);}});}getServer(){return this.liopServer}};export{g as a,d as b};//# sourceMappingURL=chunk-ZEU57HJP.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-ZEU57HJP.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{d as WasiSandbox,c as calculateAstInstructionFuel,b as getDefaultEnvironment}from'./chunk-HLAQ3HVD.js';export{a as VERIFICATION_LATENCY_BUDGET_MS,f as deserializeGrothProof,d as deserializeVKey,e as serializeGrothProof,c as serializeVKey,b as verifyGroth16Proof}from'./chunk-FDJMH4CB.js';export{b as AesGcmWrapper,c as LiopClient,a as LiopRpcClient}from'./chunk-WP5ER7RH.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-
|
|
1
|
+
export{d as WasiSandbox,c as calculateAstInstructionFuel,b as getDefaultEnvironment}from'./chunk-HLAQ3HVD.js';export{a as VERIFICATION_LATENCY_BUDGET_MS,f as deserializeGrothProof,d as deserializeVKey,e as serializeGrothProof,c as serializeVKey,b as verifyGroth16Proof}from'./chunk-FDJMH4CB.js';export{b as AesGcmWrapper,c as LiopClient,a as LiopRpcClient}from'./chunk-WP5ER7RH.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-ZEU57HJP.js';export{a as GRPC_WEB_CONSTANTS,i as InMemoryRateLimiter,j as LiopHybridGateway,g as buildProtectedResourceMetadata,e as decodeFrames,f as dispatchGrpcWebRequest,c as encodeDataFrame,d as encodeTrailerFrame,h as executeGatewayInterceptor,b as isGrpcWebRequest}from'./chunk-LZIEMSYZ.js';export{a as RoutingTable,b as probeTopology}from'./chunk-2XHSALII.js';export{a as TokenManager}from'./chunk-N35BC62H.js';export{f as AUTH_DEFAULTS,d as AuditLogger,b as GENESIS_HASH,g as JwtValidator,a as LiopRpcServer,m as LiopServer,i as NerScanner,j as PII_PATTERNS,k as PII_PRESETS,l as PiiScanner,c as computeEntryHash,h as createOAuthServer,e as globalAuditLogger}from'./chunk-PRNQM5KL.js';export{a as sanitizeOutput}from'./chunk-MQ5SU26J.js';export{a as LiopMcpRouter}from'./chunk-AN5NODTN.js';export{a as LiopVerifier}from'./chunk-6KFKO6ZX.js';import'./chunk-TKLRW52V.js';export{a as Kyber768Wrapper}from'./chunk-Y675R34Z.js';export{b as LIOP_SCOPES,a as authorizeRequest}from'./chunk-XLVEDKM6.js';export{a as DILITHIUM65_CONSTANTS,b as Dilithium65Wrapper}from'./chunk-2ZYX736J.js';export{j as GRPC_CHANNEL_OPTIONS,b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,i as createChannelCredentials,h as createServerCredentials,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-ECRS6N33.js';export{a as Counter,b as Gauge,c as Histogram,d as MetricsRegistry,k as egressBlocksTotal,h as fuelConsumed,j as manifestCacheSize,i as meshPeersConnected,t as operationDurationMs,u as pqcHandshakeDurationMs,v as pqcHandshakesTotal,e as protocolMetrics,q as tokensInputTotal,r as tokensOutputTotal,s as tokensSavedTotal,g as toolCallErrorsTotal,f as toolCallsTotal,w as wireEgressBytesTotal,x as wireSavedBytesTotal,n as zkProofsByTypeTotal,o as zkProvingDurationMs,l as zkVerificationDurationMs,m as zkVerificationsTotal,p as zkVkeyCacheSize}from'./chunk-ZZMSFCJP.js';export{a as MCP_LEGACY_SUPPORT_ENABLED,h as MCP_PROTOCOL_VERSION,b as MCP_PROTOCOL_VERSION_LEGACY,k as PromptSchema,j as ResourceSchema,i as ToolSchema}from'./chunk-GWVSCZUS.js';export{a as ProofType,b as RECEIPT_VERSION_V1,c as RECEIPT_VERSION_V2,d as ZK_JOURNAL_V2_SIZE,e as ZkVerificationError,i as ZkVerifier,g as decodeJournalV2,f as encodeJournalV2,h as receiptCodec}from'./chunk-6VK2XALI.js';export{a as SWARM_KEY_BYTE_LENGTH,b as createSwarmKey,d as deserializeSwarmKey,g as loadSwarmKey,e as parseSwarmKey,f as saveSwarmKey,c as serializeSwarmKey}from'./chunk-YLCNV764.js';export{a as MeshNode}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';export{a as LiopLogger,b as log}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as h from'crypto';import {EventEmitter}from'events';import*as i from'fs';var A=(o=>(o.CapabilityViolation="CapabilityViolation",o.SandboxEscape="SandboxEscape",o.PiiLeak="PiiLeak",o.InvalidIntent="InvalidIntent",o.Throttled="Throttled",o.ZkVerificationFailed="ZkVerificationFailed",o.MeshUnavailable="MeshUnavailable",o.ConnectionFailed="ConnectionFailed",o))(A||{}),y=class extends Error{static{a(this,"LiopError");}code;constructor(t,e){super(e),this.name="LiopError",this.code=t;}};var D=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,g=class n{static{a(this,"LiopTracer");}static generateTraceId(){let t;do t=h.randomBytes(16).toString("hex");while(t==="0".repeat(32));return t}static generateSpanId(){let t;do t=h.randomBytes(8).toString("hex");while(t==="0".repeat(16));return t}static formatTraceparent(t,e,r=true){return `00-${t}-${e}-${r?"01":"00"}`}static parseTraceparent(t){if(!t||typeof t!="string")return null;let e=t.trim(),r=D.exec(e);if(!r)return null;let[,a,c,l,m]=r;if(a==="00"&&(c==="0".repeat(32)||l==="0".repeat(16)))return null;let o=(Number.parseInt(m,16)&1)===1;return {traceId:c,spanId:l,sampled:o}}static injectTraceparent(t,e){t.traceparent=n.formatTraceparent(e.traceId,e.spanId,e.sampled);}static extractTraceparent(t){let e=t.traceparent||t.Traceparent;return Array.isArray(e)?n.parseTraceparent(e[0]):n.parseTraceparent(e)}startSpan(t,e,r={}){let a=e?.traceId||n.generateTraceId(),c=n.generateSpanId(),l=e?e.sampled:true;return {name:t,context:{traceId:a,spanId:c,sampled:l},startTime:Date.now(),attributes:{...r},status:"OK",setAttribute(d,T){return this.attributes[d]=T,this},recordException(d){return this.status="ERROR",this.error=typeof d=="string"?d:d.message,this},end(){this.endTime=Date.now();}}}},Mt=new g;var k={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function Bt(n){let t=k[n],e=`[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.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{m as LiopServer,i as NerScanner,j as PII_PATTERNS,k as PII_PRESETS,l as PiiScanner}from'./chunk-
|
|
1
|
+
export{m as LiopServer,i as NerScanner,j as PII_PATTERNS,k as PII_PRESETS,l as PiiScanner}from'./chunk-PRNQM5KL.js';export{a as sanitizeOutput}from'./chunk-MQ5SU26J.js';import'./chunk-XLVEDKM6.js';import'./chunk-2ZYX736J.js';import'./chunk-ECRS6N33.js';import'./chunk-ZZMSFCJP.js';import'./chunk-6VK2XALI.js';import'./chunk-V35CXJQN.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=server.js.map
|
|
2
2
|
//# sourceMappingURL=server.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nekzus/liop",
|
|
3
|
-
"version": "2.4.0-alpha.
|
|
3
|
+
"version": "2.4.0-alpha.30",
|
|
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",
|
|
@@ -136,11 +136,11 @@
|
|
|
136
136
|
"zod": "4.6.5"
|
|
137
137
|
},
|
|
138
138
|
"optionalDependencies": {
|
|
139
|
-
"@modelcontextprotocol/sdk": "1.
|
|
139
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
140
140
|
"compromise": "14.17.0"
|
|
141
141
|
},
|
|
142
142
|
"peerDependencies": {
|
|
143
|
-
"@modelcontextprotocol/sdk": "1.
|
|
143
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
144
144
|
"@opentelemetry/api": "1.9.1"
|
|
145
145
|
},
|
|
146
146
|
"peerDependenciesMeta": {
|