@nekzus/liop 2.0.0-alpha.26 → 2.0.0-alpha.27

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.
@@ -1,13 +1,20 @@
1
- import A from'crypto';import*as n from'fs/promises';import*as b from'os';import*as c from'path';import h from'vm';import {WASI}from'wasi';var f=class extends Error{constructor(t){super(`AST Sec-Policy Violation: ${t}`),this.name="GuardianError";}},w={analyze(d){let t=WebAssembly.Module.imports(d),s=0,l=new Set(["fd_write","fd_read","fd_close","fd_seek","environ_get","environ_sizes_get","args_get","args_sizes_get","clock_time_get","random_get","proc_exit","fd_prestat_get","fd_prestat_dir_name","fd_fdstat_get"]);for(let o of t){if(o.module==="wasi_snapshot_preview1"){if(!l.has(o.name))throw new f(`Banned WASI Import Detected: ${o.module}/${o.name}`)}else throw new f(`Banned Host Import Module Detected: ${o.module}`);if(s++,s>128)throw new f("Import limit exceeded. Possible resource exhaustion attack.")}}};var x=process.emit;process.emit=(d,t,...s)=>d==="warning"&&typeof t=="object"&&t.name==="ExperimentalWarning"&&String(t.message).includes("WASI")||String(t.message).includes("importing WASI")?false:x.call(process,d,t,...s);var y=class{wasi;sandboxId;workingDir;config;stdoutHandle=null;stderrHandle=null;constructor(t={}){this.sandboxId=A.randomUUID(),this.workingDir=c.join(b.tmpdir(),"liop-mesh","sandboxes",this.sandboxId),this.config=t;}async init(){try{await n.mkdir(this.workingDir,{recursive:!0}),this.stdoutHandle=await n.open(c.join(this.workingDir,"stdout.log"),"w+"),this.stderrHandle=await n.open(c.join(this.workingDir,"stderr.log"),"w+"),this.wasi=new WASI({version:"preview1",args:["liop_runtime"],env:this.config.allowEnv?process.env:{NODE_ENV:"production",LIOP_NODE:"true",RUNTIME_ID:this.sandboxId},preopens:{"/sandbox":this.workingDir,...this.config.allowedDirectories},stdout:this.stdoutHandle.fd,stderr:this.stderrHandle.fd});}catch(t){throw new Error(`Sandbox Initialization Failed: ${t instanceof Error?t.message:"FS Error"}`)}}async execute(t,s=[],l={}){let o=performance.now();if(t instanceof Buffer)try{let e=await WebAssembly.compile(new Uint8Array(t));w.analyze(e);let p=await WebAssembly.instantiate(e,this.wasi.getImportObject());this.wasi.start(p);let u=c.join(this.workingDir,"stdout.log"),i=c.join(this.workingDir,"stderr.log"),m=await n.readFile(u,"utf-8"),r=await n.readFile(i,"utf-8"),a=performance.now()-o;return {output:m||(r?`Error: ${r}`:"WASM_EXECUTION_SUCCESS"),fuelConsumed:Math.floor(a*1e3)}}catch(e){throw new Error(`WASM Runtime Error: ${e instanceof Error?e.message:String(e)}`)}else {let e=Object.create(null),p={records:s,...l};e.require=void 0,e.process=void 0,e.global=void 0,e.globalThis=void 0,e.Buffer=void 0,e.setTimeout=void 0,e.setInterval=void 0,e.setImmediate=void 0,e.queueMicrotask=void 0,e.eval=void 0,e.Function=void 0,e.SharedArrayBuffer=void 0,e.Date=void 0,e.ArrayBuffer=void 0,e.Uint8Array=void 0,e.Int8Array=void 0,e.Uint16Array=void 0,e.Int16Array=void 0,e.Uint32Array=void 0,e.Int32Array=void 0,e.Float32Array=void 0,e.Float64Array=void 0,e.BigInt64Array=void 0,e.BigUint64Array=void 0,e.DataView=void 0,e.records=JSON.parse(JSON.stringify(s)),e.env=JSON.parse(JSON.stringify(p));for(let[r,a]of Object.entries(l))e[r]=JSON.parse(JSON.stringify(a));let u=r=>{if(r&&typeof r=="object"&&!Object.isFrozen(r)){Object.freeze(r);for(let a of Object.keys(r))u(r[a]);}return r};u(e.records),u(e.env);for(let r of Object.keys(e))Object.defineProperty(e,r,{writable:false,configurable:false});let i=String(t);(/^\s*return\s/m.test(i)||!i.includes("function liop_main"))&&(i.includes("function liop_main")||(i=`function liop_main(env) {
1
+ import A from'crypto';import*as n from'fs/promises';import*as b from'os';import*as c from'path';import y from'vm';import {WASI}from'wasi';var u=class extends Error{constructor(t){super(`AST Sec-Policy Violation: ${t}`),this.name="GuardianError";}},w={analyze(d){let t=WebAssembly.Module.imports(d),s=0,l=new Set(["fd_write","fd_read","fd_close","fd_seek","environ_get","environ_sizes_get","args_get","args_sizes_get","clock_time_get","random_get","proc_exit","fd_prestat_get","fd_prestat_dir_name","fd_fdstat_get"]);for(let o of t){if(o.module==="wasi_snapshot_preview1"){if(!l.has(o.name))throw new u(`Banned WASI Import Detected: ${o.module}/${o.name}`)}else throw new u(`Banned Host Import Module Detected: ${o.module}`);if(s++,s>128)throw new u("Import limit exceeded. Possible resource exhaustion attack.")}}};var x=process.emit;process.emit=(d,t,...s)=>d==="warning"&&typeof t=="object"&&t.name==="ExperimentalWarning"&&String(t.message).includes("WASI")||String(t.message).includes("importing WASI")?false:x.call(process,d,t,...s);var h=class{wasi;sandboxId;workingDir;config;stdoutHandle=null;stderrHandle=null;constructor(t={}){this.sandboxId=A.randomUUID(),this.workingDir=c.join(b.tmpdir(),"liop-mesh","sandboxes",this.sandboxId),this.config=t;}async init(){try{await n.mkdir(this.workingDir,{recursive:!0}),this.stdoutHandle=await n.open(c.join(this.workingDir,"stdout.log"),"w+"),this.stderrHandle=await n.open(c.join(this.workingDir,"stderr.log"),"w+"),this.wasi=new WASI({version:"preview1",args:["liop_runtime"],env:this.config.allowEnv?process.env:{NODE_ENV:"production",LIOP_NODE:"true",RUNTIME_ID:this.sandboxId},preopens:{"/sandbox":this.workingDir,...this.config.allowedDirectories},stdout:this.stdoutHandle.fd,stderr:this.stderrHandle.fd});}catch(t){throw new Error(`Sandbox Initialization Failed: ${t instanceof Error?t.message:"FS Error"}`)}}async execute(t,s=[],l={}){let o=performance.now();if(t instanceof Buffer)try{let e=await WebAssembly.compile(new Uint8Array(t));w.analyze(e);let p=await WebAssembly.instantiate(e,this.wasi.getImportObject());this.wasi.start(p);let f=c.join(this.workingDir,"stdout.log"),i=c.join(this.workingDir,"stderr.log"),m=await n.readFile(f,"utf-8"),r=await n.readFile(i,"utf-8"),a=performance.now()-o;return {output:m||(r?`Error: ${r}`:"WASM_EXECUTION_SUCCESS"),fuelConsumed:Math.floor(a*1e3)}}catch(e){throw new Error(`WASM Runtime Error: ${e instanceof Error?e.message:String(e)}`)}else {let e=Object.create(null),p={records:s,...l};e.require=void 0,e.process=void 0,e.global=void 0,e.globalThis=void 0,e.Buffer=void 0,e.setTimeout=void 0,e.setInterval=void 0,e.setImmediate=void 0,e.queueMicrotask=void 0,e.eval=void 0,e.Function=void 0,e.SharedArrayBuffer=void 0,e.Date=void 0,e.ArrayBuffer=void 0,e.Uint8Array=void 0,e.Int8Array=void 0,e.Uint16Array=void 0,e.Int16Array=void 0,e.Uint32Array=void 0,e.Int32Array=void 0,e.Float32Array=void 0,e.Float64Array=void 0,e.BigInt64Array=void 0,e.BigUint64Array=void 0,e.DataView=void 0,e.records=JSON.parse(JSON.stringify(s)),e.env=JSON.parse(JSON.stringify(p));for(let[r,a]of Object.entries(l))e[r]=JSON.parse(JSON.stringify(a));let f=r=>{if(r&&typeof r=="object"&&!Object.isFrozen(r)){Object.freeze(r);for(let a of Object.keys(r))f(r[a]);}return r};f(e.records),f(e.env);for(let r of Object.keys(e))Object.defineProperty(e,r,{writable:false,configurable:false});let i=String(t);(/^\s*return\s/m.test(i)||!i.includes("function liop_main"))&&(i.includes("function liop_main")||(i=`function liop_main(env) {
2
2
  ${i}
3
3
  }`));let m=`
4
4
  (function() {
5
+ "use strict";
5
6
  try {
7
+ // Pre-execution prototype freezing (PCI-DSS Compliance)
6
8
  Object.freeze(Object.prototype);
7
9
  Object.freeze(Array.prototype);
8
10
  Object.freeze(String.prototype);
9
11
  Object.freeze(Number.prototype);
10
12
  Object.freeze(Boolean.prototype);
13
+ Object.freeze(RegExp.prototype);
14
+ Object.freeze(Map.prototype);
15
+ Object.freeze(Set.prototype);
16
+ Object.freeze(Promise.prototype);
17
+ Object.freeze(Error.prototype);
11
18
  Object.freeze(Object.getPrototypeOf(function(){}));
12
19
 
13
20
  ${i}
@@ -19,6 +26,6 @@ ${i}
19
26
  return "LogicError: " + e.message;
20
27
  }
21
28
  })();
22
- `;try{let r=new h.Script(m,{filename:`liop-sandbox-${this.sandboxId.slice(0,8)}.js`}),a=h.createContext(e,{name:"LIOP Isolate",origin:"liop://sandbox",microtaskMode:"afterEvaluate"}),_=r.runInContext(a,{timeout:5e3,breakOnSigint:!0,displayErrors:!0}),S=performance.now()-o,E=Math.floor(S*1500+100),g=Math.ceil(E/100)*100;if(g>1e6)throw new Error("LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.");return {output:_,fuelConsumed:g}}catch(r){throw new Error(`V8 Isolate Fault: ${r instanceof Error?r.message:"Execution Timeout"}`)}}}async teardown(){try{this.stdoutHandle&&await this.stdoutHandle.close(),this.stderrHandle&&await this.stderrHandle.close(),await n.rm(this.workingDir,{recursive:!0,force:!0});}catch{}}};
23
- export{w as a,y as b};//# sourceMappingURL=chunk-C65RM2A3.js.map
24
- //# sourceMappingURL=chunk-C65RM2A3.js.map
29
+ `;try{let r=new y.Script(m,{filename:`liop-sandbox-${this.sandboxId.slice(0,8)}.js`}),a=y.createContext(e,{name:"LIOP Isolate",origin:"liop://sandbox",microtaskMode:"afterEvaluate"}),_=r.runInContext(a,{timeout:5e3,breakOnSigint:!0,displayErrors:!0}),O=performance.now()-o,S=Math.floor(O*1500+100),g=Math.ceil(S/100)*100;if(g>1e6)throw new Error("LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.");return {output:_,fuelConsumed:g}}catch(r){throw new Error(`V8 Isolate Fault: ${r instanceof Error?r.message:"Execution Timeout"}`)}}}async teardown(){try{this.stdoutHandle&&await this.stdoutHandle.close(),this.stderrHandle&&await this.stderrHandle.close(),await n.rm(this.workingDir,{recursive:!0,force:!0});}catch{}}};
30
+ export{w as a,h as b};//# sourceMappingURL=chunk-RNS4FR5L.js.map
31
+ //# sourceMappingURL=chunk-RNS4FR5L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sandbox/guardian.ts","../src/sandbox/wasi.ts"],"names":["GuardianError","message","ASTGuardian","module","imports","_importCount","ALLOWED_WASI_FUNCTIONS","imp","originalEmit","name","data","args","WasiSandbox","config","crypto","WASI","error","compiledLogic","records","inputs","startTime","instance","stdoutPath","stderrPath","stdout","stderr","duration","sandboxEnv","env","key","value","deepFreeze","obj","processedLogic","scriptCode","script","vm","context","output","rawFuel","fuelUsed"],"mappings":"0IAAO,IAAMA,CAAAA,CAAN,cAA4B,KAAM,CACxC,YAAYC,CAAAA,CAAiB,CAC5B,KAAA,CAAM,CAAA,0BAAA,EAA6BA,CAAO,CAAA,CAAE,CAAA,CAC5C,IAAA,CAAK,IAAA,CAAO,gBACb,CACD,CAAA,CAQaC,CAAAA,CAAc,CAO1B,OAAA,CAAQC,CAAAA,CAAkC,CACzC,IAAMC,EAAU,WAAA,CAAY,MAAA,CAAO,OAAA,CAAQD,CAAM,EAC7CE,CAAAA,CAAe,CAAA,CAEbC,CAAAA,CAAyB,IAAI,IAAI,CACtC,UAAA,CACA,SAAA,CACA,UAAA,CACA,SAAA,CACA,aAAA,CACA,mBAAA,CACA,UAAA,CACA,iBACA,gBAAA,CACA,YAAA,CACA,WAAA,CACA,gBAAA,CACA,sBACA,eACD,CAAC,CAAA,CAED,IAAA,IAAWC,KAAOH,CAAAA,CAAS,CAE1B,GAAIG,CAAAA,CAAI,MAAA,GAAW,wBAAA,CAAA,CAClB,GAAI,CAACD,EAAuB,GAAA,CAAIC,CAAAA,CAAI,IAAI,CAAA,CACvC,MAAM,IAAIP,CAAAA,CACT,CAAA,6BAAA,EAAgCO,CAAAA,CAAI,MAAM,CAAA,CAAA,EAAIA,CAAAA,CAAI,IAAI,CAAA,CACvD,CAAA,CAAA,KAGD,MAAM,IAAIP,CAAAA,CACT,uCAAuCO,CAAAA,CAAI,MAAM,CAAA,CAClD,CAAA,CAID,GAFAF,CAAAA,EAAAA,CAEIA,CAAAA,CAAe,GAAA,CAClB,MAAM,IAAIL,CAAAA,CACT,6DACD,CAEF,CAKD,CACD,EC1DA,IAAMQ,CAAAA,CAAe,QAAQ,IAAA,CAE7B,OAAA,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AAM,IAAI,KAAA,CACT,yDACD,CAAA,CAGD,OAAO,CAAE,MAAA,CAAAF,CAAAA,CAAQ,YAAA,CAAcE,CAAS,CACzC,CAAA,MAASxB,CAAAA,CAAO,CACf,MAAM,IAAI,KAAA,CACT,CAAA,kBAAA,EAAqBA,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,mBAAmB,CAAA,CAClF,CACD,CACD,CACD,CAKA,MAAa,QAAA,EAA0B,CACtC,GAAI,CACC,IAAA,CAAK,YAAA,EAAc,MAAM,IAAA,CAAK,YAAA,CAAa,KAAA,EAAM,CACjD,IAAA,CAAK,YAAA,EAAc,MAAM,KAAK,YAAA,CAAa,KAAA,EAAM,CACrD,MAAS,CAAA,CAAA,EAAA,CAAG,IAAA,CAAK,UAAA,CAAY,CAAE,SAAA,CAAW,CAAA,CAAA,CAAM,KAAA,CAAO,CAAA,CAAK,CAAC,EAC9D,CAAA,KAAa,CAEb,CACD,CACD","file":"chunk-RNS4FR5L.js","sourcesContent":["export class GuardianError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(`AST Sec-Policy Violation: ${message}`);\n\t\tthis.name = \"GuardianError\";\n\t}\n}\n\n/**\n * The Guardian-TS Module\n * Scans the Abstract Syntax Tree (AST) imports of incoming WASM\n * before it reaches the V8 Wasmtime engine to prevent sandbox-escape\n * zero-days, resource exhaustion bombs, and evasive execution.\n */\nexport const ASTGuardian = {\n\t/**\n\t * Analyzes the WebAssembly Module interface proactively.\n\t *\n\t * @param module - The compiled WebAssembly.Module to inspect\n\t * @throws {GuardianError} If illegal imports or capabilities are detected\n\t */\n\tanalyze(module: WebAssembly.Module): void {\n\t\tconst imports = WebAssembly.Module.imports(module);\n\t\tlet _importCount = 0;\n\n\t\tconst ALLOWED_WASI_FUNCTIONS = new Set([\n\t\t\t\"fd_write\",\n\t\t\t\"fd_read\",\n\t\t\t\"fd_close\",\n\t\t\t\"fd_seek\",\n\t\t\t\"environ_get\",\n\t\t\t\"environ_sizes_get\",\n\t\t\t\"args_get\",\n\t\t\t\"args_sizes_get\",\n\t\t\t\"clock_time_get\",\n\t\t\t\"random_get\",\n\t\t\t\"proc_exit\",\n\t\t\t\"fd_prestat_get\",\n\t\t\t\"fd_prestat_dir_name\",\n\t\t\t\"fd_fdstat_get\",\n\t\t]);\n\n\t\tfor (const imp of imports) {\n\t\t\t// Strict Sandbox Validation: Only allow WASI preview 1 specific whitelisted functions.\n\t\t\tif (imp.module === \"wasi_snapshot_preview1\") {\n\t\t\t\tif (!ALLOWED_WASI_FUNCTIONS.has(imp.name)) {\n\t\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\t`Banned WASI Import Detected: ${imp.module}/${imp.name}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t`Banned Host Import Module Detected: ${imp.module}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t_importCount++;\n\n\t\t\tif (_importCount > 128) {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\"Import limit exceeded. Possible resource exhaustion attack.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// In Node.js / V8, the maximum module size and function limits\n\t\t// are natively enforced by the engine during compilation.\n\t\t// A successfully compiled WebAssembly.Module already passed structural checks.\n\t},\n};\n","import crypto from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport vm from \"node:vm\";\nimport { WASI } from \"node:wasi\";\nimport { ASTGuardian } from \"./guardian.js\";\n\n// Silence Node.js ExperimentalWarning for WASI (Industrial console parity)\nconst originalEmit = process.emit;\n// @ts-expect-error\nprocess.emit = (name, data, ...args) => {\n\tif (\n\t\t(name === \"warning\" &&\n\t\t\ttypeof data === \"object\" &&\n\t\t\t(data as Record<string, unknown>).name === \"ExperimentalWarning\" &&\n\t\t\tString((data as Record<string, unknown>).message).includes(\"WASI\")) ||\n\t\tString((data as Record<string, unknown>).message).includes(\"importing WASI\")\n\t) {\n\t\treturn false;\n\t}\n\treturn originalEmit.call(process, name, data, ...args);\n};\n\nexport interface SandboxConfig {\n\tallowEnv?: boolean;\n\tallowedDirectories?: Record<string, string>; // guestPath -> hostPath\n\tmemoryLimitMb?: number;\n}\n\n/**\n * LIOP WasiSandbox (Industrial Grade)\n *\n * Provides a production-grade isolated environment for executing untrusted logic.\n * Primarily uses WebAssembly (WASI) for byte-code isolation, with a hardened\n * V8 Isolate fallback for dynamic JS-to-WASM logic injection.\n */\nexport class WasiSandbox {\n\tprivate wasi!: WASI;\n\tprivate sandboxId: string;\n\tprivate workingDir: string;\n\tprivate config: SandboxConfig;\n\tprivate stdoutHandle: fs.FileHandle | null = null;\n\tprivate stderrHandle: fs.FileHandle | null = null;\n\n\tconstructor(config: SandboxConfig = {}) {\n\t\tthis.sandboxId = crypto.randomUUID();\n\t\t// Use a dedicated LIOP directory in the OS temp folder\n\t\tthis.workingDir = path.join(\n\t\t\tos.tmpdir(),\n\t\t\t\"liop-mesh\",\n\t\t\t\"sandboxes\",\n\t\t\tthis.sandboxId,\n\t\t);\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Initializes the physical sandbox environment with strict directory lockdown.\n\t */\n\tpublic async init(): Promise<void> {\n\t\ttry {\n\t\t\tawait fs.mkdir(this.workingDir, { recursive: true });\n\n\t\t\t// Initialize WASI with explicit limits\n\t\t\tthis.stdoutHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stdout.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\t\t\tthis.stderrHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stderr.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\n\t\t\tthis.wasi = new WASI({\n\t\t\t\tversion: \"preview1\",\n\t\t\t\targs: [\"liop_runtime\"],\n\t\t\t\tenv: this.config.allowEnv\n\t\t\t\t\t? process.env\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tNODE_ENV: \"production\",\n\t\t\t\t\t\t\tLIOP_NODE: \"true\",\n\t\t\t\t\t\t\tRUNTIME_ID: this.sandboxId,\n\t\t\t\t\t\t},\n\t\t\t\tpreopens: {\n\t\t\t\t\t\"/sandbox\": this.workingDir,\n\t\t\t\t\t...this.config.allowedDirectories,\n\t\t\t\t},\n\t\t\t\tstdout: this.stdoutHandle.fd,\n\t\t\t\tstderr: this.stderrHandle.fd,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Sandbox Initialization Failed: ${error instanceof Error ? error.message : \"FS Error\"}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Executes logic (WASM or JS-Wrapped) with hard resource limits.\n\t */\n\tpublic async execute(\n\t\tcompiledLogic: Buffer | string,\n\t\trecords: Record<string, unknown>[] = [],\n\t\tinputs: Record<string, unknown> = {},\n\t): Promise<{ output: unknown; fuelConsumed: number }> {\n\t\tconst startTime = performance.now();\n\n\t\tif (compiledLogic instanceof Buffer) {\n\t\t\t// Path A: Native WebAssembly Isolation\n\t\t\ttry {\n\t\t\t\tconst module = await WebAssembly.compile(new Uint8Array(compiledLogic));\n\n\t\t\t\t// Tier-0 Guardian: Static analysis to prevent sandbox escapes\n\t\t\t\tASTGuardian.analyze(module);\n\n\t\t\t\tconst instance = await WebAssembly.instantiate(\n\t\t\t\t\tmodule,\n\t\t\t\t\tthis.wasi.getImportObject() as WebAssembly.Imports,\n\t\t\t\t);\n\n\t\t\t\t// Standard entry point\n\t\t\t\tthis.wasi.start(instance);\n\n\t\t\t\t// Capture output from the sandbox\n\t\t\t\tconst stdoutPath = path.join(this.workingDir, \"stdout.log\");\n\t\t\t\tconst stderrPath = path.join(this.workingDir, \"stderr.log\");\n\t\t\t\tconst stdout = await fs.readFile(stdoutPath, \"utf-8\");\n\t\t\t\tconst stderr = await fs.readFile(stderrPath, \"utf-8\");\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\treturn {\n\t\t\t\t\toutput:\n\t\t\t\t\t\tstdout || (stderr ? `Error: ${stderr}` : \"WASM_EXECUTION_SUCCESS\"),\n\t\t\t\t\tfuelConsumed: Math.floor(duration * 1000),\n\t\t\t\t};\n\t\t\t} catch (error: unknown) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`WASM Runtime Error: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\t// Path B: Hardened V8 Isolate Fallback\n\t\t\t// Uses node:vm with zero-prototype objects to prevent prototype pollution escapes.\n\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for Sandbox global poisoning\n\t\t\tconst sandboxEnv: any = Object.create(null); // Isolated global object\n\t\t\tconst env = { records, ...inputs };\n\n\t\t\t// Explicitly poison Node.js escape vectors in the context\n\t\t\tsandboxEnv.require = undefined;\n\t\t\tsandboxEnv.process = undefined;\n\t\t\tsandboxEnv.global = undefined;\n\t\t\tsandboxEnv.globalThis = undefined;\n\t\t\tsandboxEnv.Buffer = undefined;\n\t\t\tsandboxEnv.setTimeout = undefined;\n\t\t\tsandboxEnv.setInterval = undefined;\n\t\t\tsandboxEnv.setImmediate = undefined;\n\t\t\tsandboxEnv.queueMicrotask = undefined;\n\t\t\tsandboxEnv.eval = undefined;\n\t\t\tsandboxEnv.Function = undefined;\n\t\t\tsandboxEnv.SharedArrayBuffer = undefined;\n\t\t\tsandboxEnv.Date = undefined;\n\n\t\t\t// [DoS Defense] Block off-heap memory allocation vectors.\n\t\t\t// Logic-on-Origin operates on JSON data (env.records) — binary buffers\n\t\t\t// serve no legitimate purpose and enable memory exhaustion DoS.\n\t\t\t// (Uint8Array(2GB) bypassed Piscina's maxOldGenerationSizeMb limit)\n\t\t\tsandboxEnv.ArrayBuffer = undefined;\n\t\t\tsandboxEnv.Uint8Array = undefined;\n\t\t\tsandboxEnv.Int8Array = undefined;\n\t\t\tsandboxEnv.Uint16Array = undefined;\n\t\t\tsandboxEnv.Int16Array = undefined;\n\t\t\tsandboxEnv.Uint32Array = undefined;\n\t\t\tsandboxEnv.Int32Array = undefined;\n\t\t\tsandboxEnv.Float32Array = undefined;\n\t\t\tsandboxEnv.Float64Array = undefined;\n\t\t\tsandboxEnv.BigInt64Array = undefined;\n\t\t\tsandboxEnv.BigUint64Array = undefined;\n\t\t\tsandboxEnv.DataView = undefined;\n\n\t\t\t// Inject strictly monitored globals\n\t\t\tsandboxEnv.records = JSON.parse(JSON.stringify(records)); // Deep copy safety\n\t\t\tsandboxEnv.env = JSON.parse(JSON.stringify(env));\n\n\t\t\tfor (const [key, value] of Object.entries(inputs)) {\n\t\t\t\tsandboxEnv[key] = JSON.parse(JSON.stringify(value));\n\t\t\t}\n\n\t\t\t// Freeze the sandbox context to prevent mutation (SEC-GAP-1)\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for recursive deep freeze of unknown data\n\t\t\tconst deepFreeze = (obj: any) => {\n\t\t\t\tif (obj && typeof obj === \"object\" && !Object.isFrozen(obj)) {\n\t\t\t\t\tObject.freeze(obj);\n\t\t\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\t\t\tdeepFreeze(obj[key]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn obj;\n\t\t\t};\n\n\t\t\tdeepFreeze(sandboxEnv.records);\n\t\t\tdeepFreeze(sandboxEnv.env);\n\n\t\t\t// Prevent property addition/modification on global scope\n\t\t\tfor (const key of Object.keys(sandboxEnv)) {\n\t\t\t\tObject.defineProperty(sandboxEnv, key, {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// LIOP Execution Wrapper\n\t\t\t// Host-side logic transformation to avoid 'new Function' in sandbox\n\t\t\tlet processedLogic = String(compiledLogic);\n\t\t\tif (\n\t\t\t\t/^\\s*return\\s/m.test(processedLogic) ||\n\t\t\t\t!processedLogic.includes(\"function liop_main\")\n\t\t\t) {\n\t\t\t\tif (!processedLogic.includes(\"function liop_main\")) {\n\t\t\t\t\tprocessedLogic = `function liop_main(env) {\\n${processedLogic}\\n}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst scriptCode = `\n\t\t\t\t(function() {\n\t\t\t\t\t\"use strict\";\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Pre-execution prototype freezing (PCI-DSS Compliance)\n\t\t\t\t\t\tObject.freeze(Object.prototype);\n\t\t\t\t\t\tObject.freeze(Array.prototype);\n\t\t\t\t\t\tObject.freeze(String.prototype);\n\t\t\t\t\t\tObject.freeze(Number.prototype);\n\t\t\t\t\t\tObject.freeze(Boolean.prototype);\n\t\t\t\t\t\tObject.freeze(RegExp.prototype);\n\t\t\t\t\t\tObject.freeze(Map.prototype);\n\t\t\t\t\t\tObject.freeze(Set.prototype);\n\t\t\t\t\t\tObject.freeze(Promise.prototype);\n\t\t\t\t\t\tObject.freeze(Error.prototype);\n\t\t\t\t\t\tObject.freeze(Object.getPrototypeOf(function(){}));\n\n\t\t\t\t\t\t${processedLogic}\n\t\t\t\t\t\tif (typeof liop_main === 'function') {\n\t\t\t\t\t\t\treturn liop_main(env);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"ERR_NO_ENTRY_POINT\";\n\t\t\t\t\t} catch(e) {\n\t\t\t\t\t\treturn \"LogicError: \" + e.message;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t`;\n\n\t\t\ttry {\n\t\t\t\tconst script = new vm.Script(scriptCode, {\n\t\t\t\t\tfilename: `liop-sandbox-${this.sandboxId.slice(0, 8)}.js`,\n\t\t\t\t});\n\n\t\t\t\t// microtaskMode: Ensures Promises created inside the sandbox are\n\t\t\t\t// resolved within the timeout/breakOnSigint scope (Node.js ≥14.6).\n\t\t\t\t// Without this, async microtasks could escape the 5s CPU limit.\n\t\t\t\tconst context = vm.createContext(sandboxEnv, {\n\t\t\t\t\tname: \"LIOP Isolate\",\n\t\t\t\t\torigin: \"liop://sandbox\",\n\t\t\t\t\tmicrotaskMode: \"afterEvaluate\",\n\t\t\t\t});\n\n\t\t\t\t// Execution with hard CPU and Memory limits (Fuel)\n\t\t\t\tconst output = script.runInContext(context, {\n\t\t\t\t\ttimeout: 5000,\n\t\t\t\t\tbreakOnSigint: true,\n\t\t\t\t\tdisplayErrors: true,\n\t\t\t\t});\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\t// SEC: Normalize fuel to buckets of 100 to prevent timing side-channel inference\n\t\t\t\tconst rawFuel = Math.floor(duration * 1500 + 100);\n\t\t\t\tconst fuelUsed = Math.ceil(rawFuel / 100) * 100;\n\n\t\t\t\tif (fuelUsed > 1000000) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn { output, fuelConsumed: fuelUsed };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`V8 Isolate Fault: ${error instanceof Error ? error.message : \"Execution Timeout\"}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Physically cleans up the sandbox and releases resources.\n\t */\n\tpublic async teardown(): Promise<void> {\n\t\ttry {\n\t\t\tif (this.stdoutHandle) await this.stdoutHandle.close();\n\t\t\tif (this.stderrHandle) await this.stderrHandle.close();\n\t\t\tawait fs.rm(this.workingDir, { recursive: true, force: true });\n\t\t} catch (_e) {\n\t\t\t// Silent fail on teardown to prevent process crashes\n\t\t}\n\t}\n}\n"]}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export{b as WasiSandbox}from'./chunk-C65RM2A3.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-AKTU6ZMX.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-TNMS53OP.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-GYK2HORK.js';export{a as LiopHybridGateway}from'./chunk-YTIMVS2I.js';export{a as LiopRpcServer,g as LiopServer,b as NerScanner,d as PII_PATTERNS,e as PII_PRESETS,f as PiiScanner,c as sanitizeOutput}from'./chunk-BDQZURCS.js';import'./chunk-2MGFSIXN.js';export{b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-GFRRQ2EB.js';import'./chunk-SW53FNSN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-V5MKJT6S.js';export{a as MeshNode}from'./chunk-7I6YJS3C.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';var m=(e=>(e.CapabilityViolation="CapabilityViolation",e.SandboxEscape="SandboxEscape",e.PiiLeak="PiiLeak",e.InvalidIntent="InvalidIntent",e.Throttled="Throttled",e.ZkVerificationFailed="ZkVerificationFailed",e.MeshUnavailable="MeshUnavailable",e.ConnectionFailed="ConnectionFailed",e))(m||{}),n=class extends Error{code;constructor(o,t){super(t),this.name="LiopError",this.code=o;}};var g={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function _(i){let o=g[i],t=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
1
+ export{b as WasiSandbox}from'./chunk-RNS4FR5L.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-AKTU6ZMX.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-TNMS53OP.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-GYK2HORK.js';export{a as LiopHybridGateway}from'./chunk-YTIMVS2I.js';export{a as LiopRpcServer,g as LiopServer,b as NerScanner,d as PII_PATTERNS,e as PII_PRESETS,f as PiiScanner,c as sanitizeOutput}from'./chunk-BDQZURCS.js';import'./chunk-2MGFSIXN.js';export{b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-GFRRQ2EB.js';import'./chunk-SW53FNSN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-V5MKJT6S.js';export{a as MeshNode}from'./chunk-7I6YJS3C.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';var m=(e=>(e.CapabilityViolation="CapabilityViolation",e.SandboxEscape="SandboxEscape",e.PiiLeak="PiiLeak",e.InvalidIntent="InvalidIntent",e.Throttled="Throttled",e.ZkVerificationFailed="ZkVerificationFailed",e.MeshUnavailable="MeshUnavailable",e.ConnectionFailed="ConnectionFailed",e))(m||{}),n=class extends Error{code;constructor(o,t){super(t),this.name="LiopError",this.code=o;}};var g={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function _(i){let o=g[i],t=`[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
 
@@ -1,2 +1,2 @@
1
- import {a,b}from'../chunk-C65RM2A3.js';import {a as a$1,b as b$1}from'../chunk-ANFXJGMP.js';import'../chunk-4C666HHU.js';import {Buffer}from'buffer';import g from'crypto';import {createMlKem768}from'mlkem';var R={epsilon:1,sensitivity:1,smallDatasetThreshold:50},E=1,K=10;function V(t,r){let n;do r?n=g.createHash("sha256").update(`${r.seed}:${r.counter++}`).digest().readUInt32BE(0)/4294967296-.5:n=g.randomBytes(4).readUInt32BE(0)/4294967296-.5;while(n===0||n===-0.5);return -t*Math.sign(n)*Math.log(1-2*Math.abs(n))}function G(t,r={},n){let e={...R,...r},a=e.sensitivity/e.epsilon,o=t+V(a,n);return Math.round(o*1e4)/1e4}function I(t,r,n){if(!t)return r;let e=t.toLowerCase(),a=/count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_/i.test(e),o=e==="total"||e==="n"||e==="total_records"||e.startsWith("total_")||e.startsWith("num_")||/total.*(count|items|entries|rows|records|tickers)/i.test(e);return a||o?1:/avg|mean|average/.test(e)&&n>0?r/n:r}function C(t,r={},n){let e={...R,...r};if(n>=e.smallDatasetThreshold)return t;n<K&&e.epsilon<E&&(e.epsilon=E);let a;return e.seed&&(a={seed:e.seed,counter:0}),A(t,e,n,void 0,a)}function A(t,r,n,e,a){if(typeof t=="number"&&Number.isFinite(t)){let o=I(e,r.sensitivity,n),u=G(t,{...r,sensitivity:o},a),p=e!=null&&I(e,r.sensitivity,n)===1;return (Number.isInteger(t)||p)&&(u=Math.round(u)),t>=0&&(u=Math.max(0,u)),u}if(Array.isArray(t))return t.map(o=>A(o,r,n,e,a));if(t!==null&&typeof t=="object"){let o={};for(let[u,p]of Object.entries(t))o[u]=A(p,r,n,u,a);return o}return t}async function Q(t){if(t.isWarmup)return {image_id:"",output:"warm",fuel_consumed:0};let{ciphertext:r,secretKeyObj:n,wasmBinary:e,inputs:a$2,aesNonce:o,records:u,isEncrypted:p=true,dpConfig:S}=t,s,O={},T=Buffer.alloc(32);if(p){let l=new Uint8Array(n),c=new Uint8Array(r),d=(await createMlKem768()).decap(c,l),f=Buffer.from(d);T=f;let m=Buffer.from(e),k=m.subarray(-16),b=m.subarray(0,-16),w=g.createDecipheriv("aes-256-gcm",f,Buffer.from(o||new Uint8Array(12)));w.setAuthTag(k);let y=w.update(b);y=Buffer.concat([y,w.final()]),s=y;for(let[M,j]of Object.entries(a$2||{})){let D=Buffer.from(j),H=D.subarray(0,12),z=D.subarray(-16),F=D.subarray(12,-16),_=g.createDecipheriv("aes-256-gcm",f,H);_.setAuthTag(z);let v=_.update(F);v=Buffer.concat([v,_.final()]),O[M]=JSON.parse(v.toString("utf-8"));}}else e[0]===0&&e[1]===97&&e[2]===115&&e[3]===109?s=Buffer.from(e):s=Buffer.from(e).toString("utf-8");let U=s[0]===0&&s[1]===97&&s[2]===115&&s[3]===109;if(s instanceof Buffer&&U){let l=new Uint8Array(s),c=await WebAssembly.compile(l);a.analyze(c);}else s instanceof Buffer&&!U&&(s=s.toString("utf-8"));typeof s=="string"&&(s=a$1(s));let x=new b;await x.init();try{let l=await x.execute(s,u,O),c=l.output,h;typeof s=="string"?h=Buffer.from(s,"utf-8"):h=new Uint8Array(s);let d=b$1(h).toString("hex"),f=g.createHash("sha256").update(JSON.stringify(u||[])).digest("hex");S&&(c=C(c,{...S,seed:`${f}:${d}`},u?.length||0));let m=Buffer.from(JSON.stringify({image_id:d,dataset_hash:f,output_hash:g.createHash("sha256").update(typeof c=="string"?c:JSON.stringify(c)).digest("hex"),fuel:l.fuelConsumed,ts:Date.now()})),k=g.createHmac("sha256",T).update(m).digest(),b=Buffer.alloc(2);b.writeUInt16BE(m.length);let y=Buffer.concat([Buffer.from([1]),b,m,k]).toString("base64");return {image_id:d,zk_receipt:y,output:c,fuel_consumed:l.fuelConsumed}}finally{await x.teardown();}}export{Q as default};//# sourceMappingURL=logic-execution.js.map
1
+ import {a,b}from'../chunk-RNS4FR5L.js';import {a as a$1,b as b$1}from'../chunk-ANFXJGMP.js';import'../chunk-4C666HHU.js';import {Buffer}from'buffer';import g from'crypto';import {createMlKem768}from'mlkem';var R={epsilon:1,sensitivity:1,smallDatasetThreshold:50},E=1,K=10;function V(t,r){let n;do r?n=g.createHash("sha256").update(`${r.seed}:${r.counter++}`).digest().readUInt32BE(0)/4294967296-.5:n=g.randomBytes(4).readUInt32BE(0)/4294967296-.5;while(n===0||n===-0.5);return -t*Math.sign(n)*Math.log(1-2*Math.abs(n))}function G(t,r={},n){let e={...R,...r},a=e.sensitivity/e.epsilon,o=t+V(a,n);return Math.round(o*1e4)/1e4}function I(t,r,n){if(!t)return r;let e=t.toLowerCase(),a=/count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_/i.test(e),o=e==="total"||e==="n"||e==="total_records"||e.startsWith("total_")||e.startsWith("num_")||/total.*(count|items|entries|rows|records|tickers)/i.test(e);return a||o?1:/avg|mean|average/.test(e)&&n>0?r/n:r}function C(t,r={},n){let e={...R,...r};if(n>=e.smallDatasetThreshold)return t;n<K&&e.epsilon<E&&(e.epsilon=E);let a;return e.seed&&(a={seed:e.seed,counter:0}),A(t,e,n,void 0,a)}function A(t,r,n,e,a){if(typeof t=="number"&&Number.isFinite(t)){let o=I(e,r.sensitivity,n),u=G(t,{...r,sensitivity:o},a),p=e!=null&&I(e,r.sensitivity,n)===1;return (Number.isInteger(t)||p)&&(u=Math.round(u)),t>=0&&(u=Math.max(0,u)),u}if(Array.isArray(t))return t.map(o=>A(o,r,n,e,a));if(t!==null&&typeof t=="object"){let o={};for(let[u,p]of Object.entries(t))o[u]=A(p,r,n,u,a);return o}return t}async function Q(t){if(t.isWarmup)return {image_id:"",output:"warm",fuel_consumed:0};let{ciphertext:r,secretKeyObj:n,wasmBinary:e,inputs:a$2,aesNonce:o,records:u,isEncrypted:p=true,dpConfig:S}=t,s,O={},T=Buffer.alloc(32);if(p){let l=new Uint8Array(n),c=new Uint8Array(r),d=(await createMlKem768()).decap(c,l),f=Buffer.from(d);T=f;let m=Buffer.from(e),k=m.subarray(-16),b=m.subarray(0,-16),w=g.createDecipheriv("aes-256-gcm",f,Buffer.from(o||new Uint8Array(12)));w.setAuthTag(k);let y=w.update(b);y=Buffer.concat([y,w.final()]),s=y;for(let[M,j]of Object.entries(a$2||{})){let D=Buffer.from(j),H=D.subarray(0,12),z=D.subarray(-16),F=D.subarray(12,-16),_=g.createDecipheriv("aes-256-gcm",f,H);_.setAuthTag(z);let v=_.update(F);v=Buffer.concat([v,_.final()]),O[M]=JSON.parse(v.toString("utf-8"));}}else e[0]===0&&e[1]===97&&e[2]===115&&e[3]===109?s=Buffer.from(e):s=Buffer.from(e).toString("utf-8");let U=s[0]===0&&s[1]===97&&s[2]===115&&s[3]===109;if(s instanceof Buffer&&U){let l=new Uint8Array(s),c=await WebAssembly.compile(l);a.analyze(c);}else s instanceof Buffer&&!U&&(s=s.toString("utf-8"));typeof s=="string"&&(s=a$1(s));let x=new b;await x.init();try{let l=await x.execute(s,u,O),c=l.output,h;typeof s=="string"?h=Buffer.from(s,"utf-8"):h=new Uint8Array(s);let d=b$1(h).toString("hex"),f=g.createHash("sha256").update(JSON.stringify(u||[])).digest("hex");S&&(c=C(c,{...S,seed:`${f}:${d}`},u?.length||0));let m=Buffer.from(JSON.stringify({image_id:d,dataset_hash:f,output_hash:g.createHash("sha256").update(typeof c=="string"?c:JSON.stringify(c)).digest("hex"),fuel:l.fuelConsumed,ts:Date.now()})),k=g.createHmac("sha256",T).update(m).digest(),b=Buffer.alloc(2);b.writeUInt16BE(m.length);let y=Buffer.concat([Buffer.from([1]),b,m,k]).toString("base64");return {image_id:d,zk_receipt:y,output:c,fuel_consumed:l.fuelConsumed}}finally{await x.teardown();}}export{Q as default};//# sourceMappingURL=logic-execution.js.map
2
2
  //# sourceMappingURL=logic-execution.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nekzus/liop",
3
- "version": "2.0.0-alpha.26",
3
+ "version": "2.0.0-alpha.27",
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",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sandbox/guardian.ts","../src/sandbox/wasi.ts"],"names":["GuardianError","message","ASTGuardian","module","imports","_importCount","ALLOWED_WASI_FUNCTIONS","imp","originalEmit","name","data","args","WasiSandbox","config","crypto","WASI","error","compiledLogic","records","inputs","startTime","instance","stdoutPath","stderrPath","stdout","stderr","duration","sandboxEnv","env","key","value","deepFreeze","obj","processedLogic","scriptCode","script","vm","context","output","rawFuel","fuelUsed"],"mappings":"0IAAO,IAAMA,CAAAA,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CAClF,CACD,CACD,CACD,CAKA,MAAa,QAAA,EAA0B,CACtC,GAAI,CACC,IAAA,CAAK,YAAA,EAAc,MAAM,IAAA,CAAK,YAAA,CAAa,KAAA,EAAM,CACjD,IAAA,CAAK,YAAA,EAAc,MAAM,KAAK,YAAA,CAAa,KAAA,EAAM,CACrD,MAAS,CAAA,CAAA,EAAA,CAAG,IAAA,CAAK,UAAA,CAAY,CAAE,SAAA,CAAW,CAAA,CAAA,CAAM,KAAA,CAAO,CAAA,CAAK,CAAC,EAC9D,CAAA,KAAa,CAEb,CACD,CACD","file":"chunk-C65RM2A3.js","sourcesContent":["export class GuardianError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(`AST Sec-Policy Violation: ${message}`);\n\t\tthis.name = \"GuardianError\";\n\t}\n}\n\n/**\n * The Guardian-TS Module\n * Scans the Abstract Syntax Tree (AST) imports of incoming WASM\n * before it reaches the V8 Wasmtime engine to prevent sandbox-escape\n * zero-days, resource exhaustion bombs, and evasive execution.\n */\nexport const ASTGuardian = {\n\t/**\n\t * Analyzes the WebAssembly Module interface proactively.\n\t *\n\t * @param module - The compiled WebAssembly.Module to inspect\n\t * @throws {GuardianError} If illegal imports or capabilities are detected\n\t */\n\tanalyze(module: WebAssembly.Module): void {\n\t\tconst imports = WebAssembly.Module.imports(module);\n\t\tlet _importCount = 0;\n\n\t\tconst ALLOWED_WASI_FUNCTIONS = new Set([\n\t\t\t\"fd_write\",\n\t\t\t\"fd_read\",\n\t\t\t\"fd_close\",\n\t\t\t\"fd_seek\",\n\t\t\t\"environ_get\",\n\t\t\t\"environ_sizes_get\",\n\t\t\t\"args_get\",\n\t\t\t\"args_sizes_get\",\n\t\t\t\"clock_time_get\",\n\t\t\t\"random_get\",\n\t\t\t\"proc_exit\",\n\t\t\t\"fd_prestat_get\",\n\t\t\t\"fd_prestat_dir_name\",\n\t\t\t\"fd_fdstat_get\",\n\t\t]);\n\n\t\tfor (const imp of imports) {\n\t\t\t// Strict Sandbox Validation: Only allow WASI preview 1 specific whitelisted functions.\n\t\t\tif (imp.module === \"wasi_snapshot_preview1\") {\n\t\t\t\tif (!ALLOWED_WASI_FUNCTIONS.has(imp.name)) {\n\t\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\t`Banned WASI Import Detected: ${imp.module}/${imp.name}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t`Banned Host Import Module Detected: ${imp.module}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t_importCount++;\n\n\t\t\tif (_importCount > 128) {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\"Import limit exceeded. Possible resource exhaustion attack.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// In Node.js / V8, the maximum module size and function limits\n\t\t// are natively enforced by the engine during compilation.\n\t\t// A successfully compiled WebAssembly.Module already passed structural checks.\n\t},\n};\n","import crypto from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport vm from \"node:vm\";\nimport { WASI } from \"node:wasi\";\nimport { ASTGuardian } from \"./guardian.js\";\n\n// Silence Node.js ExperimentalWarning for WASI (Industrial console parity)\nconst originalEmit = process.emit;\n// @ts-expect-error\nprocess.emit = (name, data, ...args) => {\n\tif (\n\t\t(name === \"warning\" &&\n\t\t\ttypeof data === \"object\" &&\n\t\t\t(data as Record<string, unknown>).name === \"ExperimentalWarning\" &&\n\t\t\tString((data as Record<string, unknown>).message).includes(\"WASI\")) ||\n\t\tString((data as Record<string, unknown>).message).includes(\"importing WASI\")\n\t) {\n\t\treturn false;\n\t}\n\treturn originalEmit.call(process, name, data, ...args);\n};\n\nexport interface SandboxConfig {\n\tallowEnv?: boolean;\n\tallowedDirectories?: Record<string, string>; // guestPath -> hostPath\n\tmemoryLimitMb?: number;\n}\n\n/**\n * LIOP WasiSandbox (Industrial Grade)\n *\n * Provides a production-grade isolated environment for executing untrusted logic.\n * Primarily uses WebAssembly (WASI) for byte-code isolation, with a hardened\n * V8 Isolate fallback for dynamic JS-to-WASM logic injection.\n */\nexport class WasiSandbox {\n\tprivate wasi!: WASI;\n\tprivate sandboxId: string;\n\tprivate workingDir: string;\n\tprivate config: SandboxConfig;\n\tprivate stdoutHandle: fs.FileHandle | null = null;\n\tprivate stderrHandle: fs.FileHandle | null = null;\n\n\tconstructor(config: SandboxConfig = {}) {\n\t\tthis.sandboxId = crypto.randomUUID();\n\t\t// Use a dedicated LIOP directory in the OS temp folder\n\t\tthis.workingDir = path.join(\n\t\t\tos.tmpdir(),\n\t\t\t\"liop-mesh\",\n\t\t\t\"sandboxes\",\n\t\t\tthis.sandboxId,\n\t\t);\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Initializes the physical sandbox environment with strict directory lockdown.\n\t */\n\tpublic async init(): Promise<void> {\n\t\ttry {\n\t\t\tawait fs.mkdir(this.workingDir, { recursive: true });\n\n\t\t\t// Initialize WASI with explicit limits\n\t\t\tthis.stdoutHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stdout.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\t\t\tthis.stderrHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stderr.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\n\t\t\tthis.wasi = new WASI({\n\t\t\t\tversion: \"preview1\",\n\t\t\t\targs: [\"liop_runtime\"],\n\t\t\t\tenv: this.config.allowEnv\n\t\t\t\t\t? process.env\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tNODE_ENV: \"production\",\n\t\t\t\t\t\t\tLIOP_NODE: \"true\",\n\t\t\t\t\t\t\tRUNTIME_ID: this.sandboxId,\n\t\t\t\t\t\t},\n\t\t\t\tpreopens: {\n\t\t\t\t\t\"/sandbox\": this.workingDir,\n\t\t\t\t\t...this.config.allowedDirectories,\n\t\t\t\t},\n\t\t\t\tstdout: this.stdoutHandle.fd,\n\t\t\t\tstderr: this.stderrHandle.fd,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Sandbox Initialization Failed: ${error instanceof Error ? error.message : \"FS Error\"}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Executes logic (WASM or JS-Wrapped) with hard resource limits.\n\t */\n\tpublic async execute(\n\t\tcompiledLogic: Buffer | string,\n\t\trecords: Record<string, unknown>[] = [],\n\t\tinputs: Record<string, unknown> = {},\n\t): Promise<{ output: unknown; fuelConsumed: number }> {\n\t\tconst startTime = performance.now();\n\n\t\tif (compiledLogic instanceof Buffer) {\n\t\t\t// Path A: Native WebAssembly Isolation\n\t\t\ttry {\n\t\t\t\tconst module = await WebAssembly.compile(new Uint8Array(compiledLogic));\n\n\t\t\t\t// Tier-0 Guardian: Static analysis to prevent sandbox escapes\n\t\t\t\tASTGuardian.analyze(module);\n\n\t\t\t\tconst instance = await WebAssembly.instantiate(\n\t\t\t\t\tmodule,\n\t\t\t\t\tthis.wasi.getImportObject() as WebAssembly.Imports,\n\t\t\t\t);\n\n\t\t\t\t// Standard entry point\n\t\t\t\tthis.wasi.start(instance);\n\n\t\t\t\t// Capture output from the sandbox\n\t\t\t\tconst stdoutPath = path.join(this.workingDir, \"stdout.log\");\n\t\t\t\tconst stderrPath = path.join(this.workingDir, \"stderr.log\");\n\t\t\t\tconst stdout = await fs.readFile(stdoutPath, \"utf-8\");\n\t\t\t\tconst stderr = await fs.readFile(stderrPath, \"utf-8\");\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\treturn {\n\t\t\t\t\toutput:\n\t\t\t\t\t\tstdout || (stderr ? `Error: ${stderr}` : \"WASM_EXECUTION_SUCCESS\"),\n\t\t\t\t\tfuelConsumed: Math.floor(duration * 1000),\n\t\t\t\t};\n\t\t\t} catch (error: unknown) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`WASM Runtime Error: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\t// Path B: Hardened V8 Isolate Fallback\n\t\t\t// Uses node:vm with zero-prototype objects to prevent prototype pollution escapes.\n\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for Sandbox global poisoning\n\t\t\tconst sandboxEnv: any = Object.create(null); // Isolated global object\n\t\t\tconst env = { records, ...inputs };\n\n\t\t\t// Explicitly poison Node.js escape vectors in the context\n\t\t\tsandboxEnv.require = undefined;\n\t\t\tsandboxEnv.process = undefined;\n\t\t\tsandboxEnv.global = undefined;\n\t\t\tsandboxEnv.globalThis = undefined;\n\t\t\tsandboxEnv.Buffer = undefined;\n\t\t\tsandboxEnv.setTimeout = undefined;\n\t\t\tsandboxEnv.setInterval = undefined;\n\t\t\tsandboxEnv.setImmediate = undefined;\n\t\t\tsandboxEnv.queueMicrotask = undefined;\n\t\t\tsandboxEnv.eval = undefined;\n\t\t\tsandboxEnv.Function = undefined;\n\t\t\tsandboxEnv.SharedArrayBuffer = undefined;\n\t\t\tsandboxEnv.Date = undefined;\n\n\t\t\t// [DoS Defense] Block off-heap memory allocation vectors.\n\t\t\t// Logic-on-Origin operates on JSON data (env.records) — binary buffers\n\t\t\t// serve no legitimate purpose and enable memory exhaustion DoS.\n\t\t\t// (Uint8Array(2GB) bypassed Piscina's maxOldGenerationSizeMb limit)\n\t\t\tsandboxEnv.ArrayBuffer = undefined;\n\t\t\tsandboxEnv.Uint8Array = undefined;\n\t\t\tsandboxEnv.Int8Array = undefined;\n\t\t\tsandboxEnv.Uint16Array = undefined;\n\t\t\tsandboxEnv.Int16Array = undefined;\n\t\t\tsandboxEnv.Uint32Array = undefined;\n\t\t\tsandboxEnv.Int32Array = undefined;\n\t\t\tsandboxEnv.Float32Array = undefined;\n\t\t\tsandboxEnv.Float64Array = undefined;\n\t\t\tsandboxEnv.BigInt64Array = undefined;\n\t\t\tsandboxEnv.BigUint64Array = undefined;\n\t\t\tsandboxEnv.DataView = undefined;\n\n\t\t\t// Inject strictly monitored globals\n\t\t\tsandboxEnv.records = JSON.parse(JSON.stringify(records)); // Deep copy safety\n\t\t\tsandboxEnv.env = JSON.parse(JSON.stringify(env));\n\n\t\t\tfor (const [key, value] of Object.entries(inputs)) {\n\t\t\t\tsandboxEnv[key] = JSON.parse(JSON.stringify(value));\n\t\t\t}\n\n\t\t\t// Freeze the sandbox context to prevent mutation (SEC-GAP-1)\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for recursive deep freeze of unknown data\n\t\t\tconst deepFreeze = (obj: any) => {\n\t\t\t\tif (obj && typeof obj === \"object\" && !Object.isFrozen(obj)) {\n\t\t\t\t\tObject.freeze(obj);\n\t\t\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\t\t\tdeepFreeze(obj[key]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn obj;\n\t\t\t};\n\n\t\t\tdeepFreeze(sandboxEnv.records);\n\t\t\tdeepFreeze(sandboxEnv.env);\n\n\t\t\t// Prevent property addition/modification on global scope\n\t\t\tfor (const key of Object.keys(sandboxEnv)) {\n\t\t\t\tObject.defineProperty(sandboxEnv, key, {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// LIOP Execution Wrapper\n\t\t\t// Host-side logic transformation to avoid 'new Function' in sandbox\n\t\t\tlet processedLogic = String(compiledLogic);\n\t\t\tif (\n\t\t\t\t/^\\s*return\\s/m.test(processedLogic) ||\n\t\t\t\t!processedLogic.includes(\"function liop_main\")\n\t\t\t) {\n\t\t\t\tif (!processedLogic.includes(\"function liop_main\")) {\n\t\t\t\t\tprocessedLogic = `function liop_main(env) {\\n${processedLogic}\\n}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst scriptCode = `\n\t\t\t\t(function() {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tObject.freeze(Object.prototype);\n\t\t\t\t\t\tObject.freeze(Array.prototype);\n\t\t\t\t\t\tObject.freeze(String.prototype);\n\t\t\t\t\t\tObject.freeze(Number.prototype);\n\t\t\t\t\t\tObject.freeze(Boolean.prototype);\n\t\t\t\t\t\tObject.freeze(Object.getPrototypeOf(function(){}));\n\n\t\t\t\t\t\t${processedLogic}\n\t\t\t\t\t\tif (typeof liop_main === 'function') {\n\t\t\t\t\t\t\treturn liop_main(env);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"ERR_NO_ENTRY_POINT\";\n\t\t\t\t\t} catch(e) {\n\t\t\t\t\t\treturn \"LogicError: \" + e.message;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t`;\n\n\t\t\ttry {\n\t\t\t\tconst script = new vm.Script(scriptCode, {\n\t\t\t\t\tfilename: `liop-sandbox-${this.sandboxId.slice(0, 8)}.js`,\n\t\t\t\t});\n\n\t\t\t\t// microtaskMode: Ensures Promises created inside the sandbox are\n\t\t\t\t// resolved within the timeout/breakOnSigint scope (Node.js ≥14.6).\n\t\t\t\t// Without this, async microtasks could escape the 5s CPU limit.\n\t\t\t\tconst context = vm.createContext(sandboxEnv, {\n\t\t\t\t\tname: \"LIOP Isolate\",\n\t\t\t\t\torigin: \"liop://sandbox\",\n\t\t\t\t\tmicrotaskMode: \"afterEvaluate\",\n\t\t\t\t});\n\n\t\t\t\t// Execution with hard CPU and Memory limits (Fuel)\n\t\t\t\tconst output = script.runInContext(context, {\n\t\t\t\t\ttimeout: 5000,\n\t\t\t\t\tbreakOnSigint: true,\n\t\t\t\t\tdisplayErrors: true,\n\t\t\t\t});\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\t// SEC: Normalize fuel to buckets of 100 to prevent timing side-channel inference\n\t\t\t\tconst rawFuel = Math.floor(duration * 1500 + 100);\n\t\t\t\tconst fuelUsed = Math.ceil(rawFuel / 100) * 100;\n\n\t\t\t\tif (fuelUsed > 1000000) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn { output, fuelConsumed: fuelUsed };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`V8 Isolate Fault: ${error instanceof Error ? error.message : \"Execution Timeout\"}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Physically cleans up the sandbox and releases resources.\n\t */\n\tpublic async teardown(): Promise<void> {\n\t\ttry {\n\t\t\tif (this.stdoutHandle) await this.stdoutHandle.close();\n\t\t\tif (this.stderrHandle) await this.stderrHandle.close();\n\t\t\tawait fs.rm(this.workingDir, { recursive: true, force: true });\n\t\t} catch (_e) {\n\t\t\t// Silent fail on teardown to prevent process crashes\n\t\t}\n\t}\n}\n"]}