@nekzus/liop 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -21
- package/NOTICE +5 -0
- package/README.md +61 -5
- package/dist/bin/agent.js +7 -5
- package/dist/bin/agent.js.map +1 -1
- package/dist/bridge.d.ts +2 -2
- package/dist/bridge.js +2 -1
- package/dist/{chunk-UVO7DII3.js → chunk-4LQPDN3W.js} +108 -15
- package/dist/chunk-4LQPDN3W.js.map +1 -0
- package/dist/{chunk-NJRSFFD7.js → chunk-74CISO2I.js} +60 -22
- package/dist/chunk-74CISO2I.js.map +1 -0
- package/dist/{chunk-E5QBDD5E.js → chunk-CRZBVFDV.js} +169 -22
- package/dist/chunk-CRZBVFDV.js.map +1 -0
- package/dist/chunk-GKV6M2PQ.js +208106 -0
- package/dist/chunk-GKV6M2PQ.js.map +1 -0
- package/dist/chunk-JIJPZFR2.js +51 -0
- package/dist/chunk-JIJPZFR2.js.map +1 -0
- package/dist/chunk-OIMJZ64E.js +441 -0
- package/dist/chunk-OIMJZ64E.js.map +1 -0
- package/dist/chunk-PYKRQAER.js +77 -0
- package/dist/chunk-PYKRQAER.js.map +1 -0
- package/dist/{chunk-J3WPBMJ5.js → chunk-SONUORBT.js} +95 -6
- package/dist/chunk-SONUORBT.js.map +1 -0
- package/dist/{chunk-2JLG4DET.js → chunk-UBOQZVV5.js} +261 -107
- package/dist/chunk-UBOQZVV5.js.map +1 -0
- package/dist/chunk-UCJEK75U.js +714 -0
- package/dist/chunk-UCJEK75U.js.map +1 -0
- package/dist/chunk-WSW6YJNY.js +168 -0
- package/dist/chunk-WSW6YJNY.js.map +1 -0
- package/dist/client.d.ts +3 -2
- package/dist/client.js +4 -3
- package/dist/gateway.d.ts +5 -110
- package/dist/gateway.js +5 -4
- package/dist/hybrid-CF__0YnC.d.ts +170 -0
- package/dist/{index-BlGc0iym.d.ts → index-BW95kAL4.d.ts} +63 -2
- package/dist/index-cMV0_yD9.d.ts +200 -0
- package/dist/index.d.ts +273 -18
- package/dist/index.js +266 -13
- package/dist/index.js.map +1 -1
- package/dist/mesh.d.ts +14 -0
- package/dist/mesh.js +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.js +5 -4
- package/dist/{types-sKeUxuky.d.ts → types-lJIxBlWF.d.ts} +71 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- package/dist/workers/logic-execution.d.ts +1 -0
- package/dist/workers/logic-execution.js +17 -1
- package/dist/workers/logic-execution.js.map +1 -1
- package/package.json +53 -33
- package/dist/chunk-2JLG4DET.js.map +0 -1
- package/dist/chunk-CT6NHSYP.js +0 -30
- package/dist/chunk-CT6NHSYP.js.map +0 -1
- package/dist/chunk-E5QBDD5E.js.map +0 -1
- package/dist/chunk-HB5DXX3Q.js +0 -1976
- package/dist/chunk-HB5DXX3Q.js.map +0 -1
- package/dist/chunk-IJHTRIZC.js +0 -56
- package/dist/chunk-IJHTRIZC.js.map +0 -1
- package/dist/chunk-J3WPBMJ5.js.map +0 -1
- package/dist/chunk-NJRSFFD7.js.map +0 -1
- package/dist/chunk-PHTWUTY7.js +0 -300
- package/dist/chunk-PHTWUTY7.js.map +0 -1
- package/dist/chunk-RDWCGZ2A.js +0 -87
- package/dist/chunk-RDWCGZ2A.js.map +0 -1
- package/dist/chunk-UVO7DII3.js.map +0 -1
- package/dist/index-qM8ZH8sC.d.ts +0 -101
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/prompts/adapters.ts"],"names":["ErrorCode"],"mappings":";;;;;;;;;;;;;;;;AAAO,IAAK,SAAA,qBAAAA,UAAAA,KAAL;AACN,EAAAA,WAAA,qBAAA,CAAA,GAAsB,qBAAA;AACtB,EAAAA,WAAA,eAAA,CAAA,GAAgB,eAAA;AAChB,EAAAA,WAAA,SAAA,CAAA,GAAU,SAAA;AACV,EAAAA,WAAA,eAAA,CAAA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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAAA,EASjB;AAEA,EAAA,OAAO,YAAA;AACR","file":"index.js","sourcesContent":["export enum ErrorCode {\n\tCapabilityViolation = \"CapabilityViolation\",\n\tSandboxEscape = \"SandboxEscape\",\n\tPiiLeak = \"PiiLeak\",\n\tInvalidIntent = \"InvalidIntent\",\n\tThrottled = \"Throttled\",\n\tZkVerificationFailed = \"ZkVerificationFailed\",\n\tMeshUnavailable = \"MeshUnavailable\",\n\tConnectionFailed = \"ConnectionFailed\",\n}\n\nexport class LiopError extends Error {\n\tpublic readonly code: ErrorCode;\n\n\tconstructor(code: ErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"LiopError\";\n\t\tthis.code = code;\n\t}\n}\n","/**\n * LIOP Cross-AI Prompt Adapters (Fase 92)\n *\n * Normalizes system instructions for different LLM providers (Claude, OpenAI, Gemini)\n * to ensure they understand how to generate \"Logic-on-Origin\" WASM-compatible payload structures.\n */\n\nexport type AIProvider = \"claude\" | \"openai\" | \"gemini\";\n\nexport interface PromptConfig {\n\txmlStandard: boolean;\n\tjsonSchemaPreferred: boolean;\n}\n\nconst PROVIDER_CONFIGS: Record<AIProvider, PromptConfig> = {\n\tclaude: { xmlStandard: true, jsonSchemaPreferred: false },\n\topenai: { xmlStandard: false, jsonSchemaPreferred: true },\n\tgemini: { xmlStandard: false, jsonSchemaPreferred: true },\n};\n\n/**\n * Generates specific System Prompts optimized for the provided AI.\n * This instructs the LLM on how to bypass Context-Pulling and use Logic-Injection (Zero-Shot).\n */\nexport function generateSystemInstructions(provider: AIProvider): string {\n\tconst config = PROVIDER_CONFIGS[provider];\n\n\tlet instructions = `[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]\nYou are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.\nUnlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.\n\n### CORE PARADIGM\nWhen you call a tool or resource, you MUST provide a payload that represents secure sandboxed logic to be executed on the remote Node.\nThe node will execute your logic securely on the raw secure data, and return only the RESULT, avoiding PII data egress.\n\n### EXECUTION RULES\n1. Provide a self-contained JavaScript syntax block that we will compile to WASM-Sandboxed logic.\n2. Rely only on standard ECMA script features (No Node.js polyfills).\n3. The logic must end by returning the calculated insights, not the raw data.\n\n### DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism)\nTo prevent database reconstruction and inference attacks, numeric query outputs are processed by a Laplace DP engine:\n- COUNT / LENGTH queries: To get EXACT integer values without noise, you MUST name return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.\n- AVERAGE queries: Return keys containing 'avg', 'mean', or 'average' scale down noise automatically by dividing global sensitivity by the dataset size (sensitivity / n).\n- SUM / OTHER queries: Return keys without these semantic names receive full Laplace noise based on the global node sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.\n\n### SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS\n- Date is poisoned: The 'Date' class/constructor is undefined (calling 'new Date()', 'Date.now()', or 'Date.parse()' will crash the execution).\n - Workaround: Perform chronological sorting and comparisons lexicographically on ISO 8601 string dates (e.g. record.date >= '2024-01-01').\n- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.\n- Frozen prototypes: Modifications to Object.prototype, Array.prototype, etc., are blocked.\n- K-Anonymity constraints: Small datasets (< 10 records) limit outputs to max 3 scalar keys with NO nesting. Datasets with >= 10 records limit outputs to max 10 fields.\n`;\n\n\tif (config.xmlStandard) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)\nYou must wrap your logic precisely within <liop_logic> tags.\nExample:\n<liop_logic>\nconst records = await liop.readResource(\"liop://vault/patients\");\nconst filtered = records.filter(r => r.disease === \"Hypertension\");\nreturn { alert: \"High risk demographic\", targetCount: filtered.length };\n</liop_logic>\n`;\n\t} else if (config.jsonSchemaPreferred) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (JSON PARSING PREFERRED)\nYou must provide your logic strictly within a JSON string key called \\`\"logic_blob\"\\` inside your tool call parameters.\nExample:\n{\n \"target\": \"liop://vault/patients\",\n \"logic_blob\": \"const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };\"\n}\n`;\n\t}\n\n\treturn instructions;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/observability/tracing.ts","../src/prompts/adapters.ts","../src/security/cert-manager.ts"],"names":["ErrorCode","crypto2"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAO,IAAK,SAAA,qBAAAA,UAAAA,KAAL;AACN,EAAAA,WAAA,qBAAA,CAAA,GAAsB,qBAAA;AACtB,EAAAA,WAAA,eAAA,CAAA,GAAgB,eAAA;AAChB,EAAAA,WAAA,SAAA,CAAA,GAAU,SAAA;AACV,EAAAA,WAAA,eAAA,CAAA,GAAgB,eAAA;AAChB,EAAAA,WAAA,WAAA,CAAA,GAAY,WAAA;AACZ,EAAAA,WAAA,sBAAA,CAAA,GAAuB,sBAAA;AACvB,EAAAA,WAAA,iBAAA,CAAA,GAAkB,iBAAA;AAClB,EAAAA,WAAA,kBAAA,CAAA,GAAmB,kBAAA;AARR,EAAA,OAAAA,UAAAA;AAAA,CAAA,EAAA,SAAA,IAAA,EAAA;AAWL,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EACpB,IAAA;AAAA,EAEhB,WAAA,CAAY,MAAiB,OAAA,EAAiB;AAC7C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACb;AACD;ACQA,IAAM,iBAAA,GACL,6DAAA;AAEM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CAAK,eAAA;AAAA,EACb;AAAA,EAEO,aAAA,GAAwB;AAC9B,IAAA,IAAI,CAAC,KAAK,gBAAA,EAAkB;AAC3B,MAAA,MAAM,IAAI,MAAM,uCAAuC,CAAA;AAAA,IACxD;AACA,IAAA,OAAO,IAAA,CAAK,gBAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA,EAKO,OAAA,GAAgB;AACtB,IAAA,IAAI,KAAK,mBAAA,EAAqB;AAC7B,MAAA,YAAA,CAAa,KAAK,mBAAmB,CAAA;AACrC,MAAA,IAAA,CAAK,mBAAA,GAAsB,IAAA;AAAA,IAC5B;AACA,IAAA,KAAA,MAAW,OAAA,IAAW,KAAK,QAAA,EAAU;AACpC,MAAA,IAAI;AACH,QAAA,OAAA,CAAQ,KAAA,EAAM;AAAA,MACf,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACD;AACA,IAAA,IAAA,CAAK,WAAW,EAAC;AACjB,IAAA,IAAA,CAAK,kBAAA,EAAmB;AAAA,EACzB;AACD","file":"index.js","sourcesContent":["export enum ErrorCode {\n\tCapabilityViolation = \"CapabilityViolation\",\n\tSandboxEscape = \"SandboxEscape\",\n\tPiiLeak = \"PiiLeak\",\n\tInvalidIntent = \"InvalidIntent\",\n\tThrottled = \"Throttled\",\n\tZkVerificationFailed = \"ZkVerificationFailed\",\n\tMeshUnavailable = \"MeshUnavailable\",\n\tConnectionFailed = \"ConnectionFailed\",\n}\n\nexport class LiopError extends Error {\n\tpublic readonly code: ErrorCode;\n\n\tconstructor(code: ErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"LiopError\";\n\t\tthis.code = code;\n\t}\n}\n","/**\n * LIOP OpenTelemetry Distributed Tracing (Phase Beta-3)\n * W3C TraceContext compliant distributed tracer for gRPC & MCP transports.\n * Spec: https://www.w3.org/TR/trace-context/\n */\n\nimport * as crypto from \"node:crypto\";\n\nexport interface SpanContext {\n\ttraceId: string;\n\tspanId: string;\n\tsampled: boolean;\n}\n\nexport interface LiopSpan {\n\treadonly name: string;\n\treadonly context: SpanContext;\n\treadonly startTime: number;\n\tendTime?: number;\n\tattributes: Record<string, string | number | boolean>;\n\tstatus: \"OK\" | \"ERROR\";\n\terror?: string;\n\tsetAttribute(key: string, value: string | number | boolean): LiopSpan;\n\trecordException(error: Error | string): LiopSpan;\n\tend(): void;\n}\n\nconst TRACEPARENT_REGEX =\n\t/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport class LiopTracer {\n\tpublic static generateTraceId(): string {\n\t\tlet id: string;\n\t\tdo {\n\t\t\tid = crypto.randomBytes(16).toString(\"hex\");\n\t\t} while (id === \"0\".repeat(32));\n\t\treturn id;\n\t}\n\n\tpublic static generateSpanId(): string {\n\t\tlet id: string;\n\t\tdo {\n\t\t\tid = crypto.randomBytes(8).toString(\"hex\");\n\t\t} while (id === \"0\".repeat(16));\n\t\treturn id;\n\t}\n\n\tpublic static formatTraceparent(\n\t\ttraceId: string,\n\t\tspanId: string,\n\t\tsampled = true,\n\t): string {\n\t\tconst flags = sampled ? \"01\" : \"00\";\n\t\treturn `00-${traceId}-${spanId}-${flags}`;\n\t}\n\n\tpublic static parseTraceparent(header?: string | null): SpanContext | null {\n\t\tif (!header || typeof header !== \"string\") {\n\t\t\treturn null;\n\t\t}\n\t\tconst trimmed = header.trim();\n\t\tconst match = TRACEPARENT_REGEX.exec(trimmed);\n\t\tif (!match) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst [, version, traceId, spanId, flags] = match;\n\t\t// Version 00 cannot have all-zeros traceId or spanId\n\t\tif (version === \"00\") {\n\t\t\tif (traceId === \"0\".repeat(32) || spanId === \"0\".repeat(16)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tconst sampled = (Number.parseInt(flags, 16) & 0x01) === 1;\n\t\treturn {\n\t\t\ttraceId,\n\t\t\tspanId,\n\t\t\tsampled,\n\t\t};\n\t}\n\n\tpublic static injectTraceparent(\n\t\tcarrier: Record<string, string | string[] | undefined>,\n\t\tcontext: SpanContext,\n\t): void {\n\t\tcarrier.traceparent = LiopTracer.formatTraceparent(\n\t\t\tcontext.traceId,\n\t\t\tcontext.spanId,\n\t\t\tcontext.sampled,\n\t\t);\n\t}\n\n\tpublic static extractTraceparent(\n\t\tcarrier: Record<string, string | string[] | undefined>,\n\t): SpanContext | null {\n\t\tconst val = carrier.traceparent || carrier.Traceparent;\n\t\tif (Array.isArray(val)) {\n\t\t\treturn LiopTracer.parseTraceparent(val[0]);\n\t\t}\n\t\treturn LiopTracer.parseTraceparent(val);\n\t}\n\n\tpublic startSpan(\n\t\tname: string,\n\t\tparent?: SpanContext | null,\n\t\tattributes: Record<string, string | number | boolean> = {},\n\t): LiopSpan {\n\t\tconst traceId = parent?.traceId || LiopTracer.generateTraceId();\n\t\tconst spanId = LiopTracer.generateSpanId();\n\t\tconst sampled = parent ? parent.sampled : true;\n\n\t\tconst context: SpanContext = {\n\t\t\ttraceId,\n\t\t\tspanId,\n\t\t\tsampled,\n\t\t};\n\n\t\tconst span: LiopSpan = {\n\t\t\tname,\n\t\t\tcontext,\n\t\t\tstartTime: Date.now(),\n\t\t\tattributes: { ...attributes },\n\t\t\tstatus: \"OK\",\n\t\t\tsetAttribute(key, value) {\n\t\t\t\tthis.attributes[key] = value;\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\trecordException(err) {\n\t\t\t\tthis.status = \"ERROR\";\n\t\t\t\tthis.error = typeof err === \"string\" ? err : err.message;\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tend() {\n\t\t\t\tthis.endTime = Date.now();\n\t\t\t},\n\t\t};\n\n\t\treturn span;\n\t}\n}\n\nexport const defaultTracer = new LiopTracer();\n","/**\n * LIOP Cross-AI Prompt Adapters (Fase 92)\n *\n * Normalizes system instructions for different LLM providers (Claude, OpenAI, Gemini)\n * to ensure they understand how to generate \"Logic-on-Origin\" WASM-compatible payload structures.\n */\n\nexport type AIProvider = \"claude\" | \"openai\" | \"gemini\";\n\nexport interface PromptConfig {\n\txmlStandard: boolean;\n\tjsonSchemaPreferred: boolean;\n}\n\nconst PROVIDER_CONFIGS: Record<AIProvider, PromptConfig> = {\n\tclaude: { xmlStandard: true, jsonSchemaPreferred: false },\n\topenai: { xmlStandard: false, jsonSchemaPreferred: true },\n\tgemini: { xmlStandard: false, jsonSchemaPreferred: true },\n};\n\n/**\n * Generates specific System Prompts optimized for the provided AI.\n * This instructs the LLM on how to bypass Context-Pulling and use Logic-Injection (Zero-Shot).\n */\nexport function generateSystemInstructions(provider: AIProvider): string {\n\tconst config = PROVIDER_CONFIGS[provider];\n\n\tlet instructions = `[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]\nYou are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.\nUnlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.\n\n### CORE PARADIGM\nWhen you call a tool or resource, you MUST provide a payload that represents secure sandboxed logic to be executed on the remote Node.\nThe node will execute your logic securely on the raw secure data, and return only the RESULT, avoiding PII data egress.\n\n### EXECUTION RULES\n1. Provide a self-contained JavaScript syntax block that we will compile to WASM-Sandboxed logic.\n2. Rely only on standard ECMA script features (No Node.js polyfills).\n3. The logic must end by returning the calculated insights, not the raw data.\n\n### DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism)\nTo prevent database reconstruction and inference attacks, numeric query outputs are processed by a Laplace DP engine:\n- COUNT / LENGTH queries: To get EXACT integer values without noise, you MUST name return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.\n- AVERAGE queries: Return keys containing 'avg', 'mean', or 'average' scale down noise automatically by dividing global sensitivity by the dataset size (sensitivity / n).\n- SUM / OTHER queries: Return keys without these semantic names receive full Laplace noise based on the global node sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.\n\n### SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS\n- Date is poisoned: The 'Date' class/constructor is undefined (calling 'new Date()', 'Date.now()', or 'Date.parse()' will crash the execution).\n - Workaround: Perform chronological sorting and comparisons lexicographically on ISO 8601 string dates (e.g. record.date >= '2024-01-01').\n- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.\n- Frozen prototypes: Modifications to Object.prototype, Array.prototype, etc., are blocked.\n- K-Anonymity constraints: Small datasets (< 10 records) limit outputs to max 3 scalar keys with NO nesting. Datasets with >= 10 records limit outputs to max 10 fields.\n`;\n\n\tif (config.xmlStandard) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)\nYou must wrap your logic precisely within <liop_logic> tags.\nExample:\n<liop_logic>\nconst records = await liop.readResource(\"liop://vault/patients\");\nconst filtered = records.filter(r => r.disease === \"Hypertension\");\nreturn { alert: \"High risk demographic\", targetCount: filtered.length };\n</liop_logic>\n`;\n\t} else if (config.jsonSchemaPreferred) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (JSON PARSING PREFERRED)\nYou must provide your logic strictly within a JSON string key called \\`\"logic_blob\"\\` inside your tool call parameters.\nExample:\n{\n \"target\": \"liop://vault/patients\",\n \"logic_blob\": \"const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };\"\n}\n`;\n\t}\n\n\treturn instructions;\n}\n","/**\n * LIOP Certificate Manager (CertManager)\n * Provides automated certificate monitoring, X.509 validity inspection,\n * and hot-reloading for mutual TLS (mTLS) without node restarts.\n *\n * Compliance:\n * - NIST SP 800-52 Rev. 2: Guidelines for the Selection and Use of TLS\n * - Zero-Trust Architecture (NIST SP 800-207): Continuous cryptographic verification\n */\n\nimport * as crypto from \"node:crypto\";\nimport { EventEmitter } from \"node:events\";\nimport * as fs from \"node:fs\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface CertManagerOptions {\n\t/** Path to the root CA certificate (PEM format) */\n\trootCertPath?: string;\n\t/** Path to the server/client certificate chain (PEM format) */\n\tcertChainPath: string;\n\t/** Path to the private key (PEM format) */\n\tprivateKeyPath: string;\n\t/** Expiration warning threshold in days (default: 30) */\n\twarningDays?: number;\n\t/** Enable file watching for automatic hot-reloading (default: true) */\n\twatchFiles?: boolean;\n\t/** Debounce delay in ms for hot reloading (default: 150) */\n\tdebounceMs?: number;\n}\n\nexport interface CertInfo {\n\tsubject: string;\n\tissuer: string;\n\tvalidFrom: string;\n\tvalidTo: string;\n\tfingerprint256: string;\n\tdaysRemaining: number;\n\tisExpired: boolean;\n\tisExpiringSoon: boolean;\n}\n\nexport class CertManager extends EventEmitter {\n\tprivate rootCertBuffer: Buffer | null = null;\n\tprivate certChainBuffer: Buffer | null = null;\n\tprivate privateKeyBuffer: Buffer | null = null;\n\tprivate watchers: fs.FSWatcher[] = [];\n\tprivate reloadDebounceTimer: NodeJS.Timeout | null = null;\n\tprivate readonly warningDays: number;\n\tprivate readonly debounceMs: number;\n\n\tconstructor(private readonly options: CertManagerOptions) {\n\t\tsuper();\n\t\tthis.warningDays = options.warningDays ?? 30;\n\t\tthis.debounceMs = options.debounceMs ?? 150;\n\t\tthis.loadCertificates();\n\n\t\tif (options.watchFiles !== false) {\n\t\t\tthis.setupWatchers();\n\t\t}\n\t}\n\n\t/**\n\t * Synchronously loads or reloads certificates from filesystem into memory.\n\t */\n\tpublic loadCertificates(): void {\n\t\ttry {\n\t\t\tif (\n\t\t\t\tthis.options.rootCertPath &&\n\t\t\t\tfs.existsSync(this.options.rootCertPath)\n\t\t\t) {\n\t\t\t\tthis.rootCertBuffer = fs.readFileSync(this.options.rootCertPath);\n\t\t\t}\n\n\t\t\tif (!fs.existsSync(this.options.certChainPath)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Certificate chain file not found: ${this.options.certChainPath}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!fs.existsSync(this.options.privateKeyPath)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Private key file not found: ${this.options.privateKeyPath}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.certChainBuffer = fs.readFileSync(this.options.certChainPath);\n\t\t\tthis.privateKeyBuffer = fs.readFileSync(this.options.privateKeyPath);\n\n\t\t\tlog.info(\"[CertManager] Certificates loaded successfully.\");\n\t\t} catch (error) {\n\t\t\tlog.error(`[CertManager] Failed to load certificates: ${error}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Inspects the loaded server/client certificate chain using Node.js native X509Certificate.\n\t */\n\tpublic inspectCertificate(): CertInfo {\n\t\tif (!this.certChainBuffer) {\n\t\t\tthrow new Error(\"[CertManager] No certificate loaded to inspect.\");\n\t\t}\n\n\t\tconst x509 = new crypto.X509Certificate(this.certChainBuffer);\n\t\tconst validToDate = new Date(x509.validTo);\n\t\tconst now = new Date();\n\t\tconst msRemaining = validToDate.getTime() - now.getTime();\n\t\tconst daysRemaining = Math.max(\n\t\t\t0,\n\t\t\tMath.floor(msRemaining / (1000 * 60 * 60 * 24)),\n\t\t);\n\t\tconst isExpired = msRemaining <= 0;\n\t\tconst isExpiringSoon = daysRemaining <= this.warningDays;\n\n\t\treturn {\n\t\t\tsubject: x509.subject,\n\t\t\tissuer: x509.issuer,\n\t\t\tvalidFrom: x509.validFrom,\n\t\t\tvalidTo: x509.validTo,\n\t\t\tfingerprint256: x509.fingerprint256,\n\t\t\tdaysRemaining,\n\t\t\tisExpired,\n\t\t\tisExpiringSoon,\n\t\t};\n\t}\n\n\t/**\n\t * Sets up non-blocking filesystem watchers to detect certificate renewals\n\t * and trigger hot-reloading without process restarts.\n\t */\n\tprivate setupWatchers(): void {\n\t\tconst filesToWatch = [\n\t\t\tthis.options.certChainPath,\n\t\t\tthis.options.privateKeyPath,\n\t\t\tthis.options.rootCertPath,\n\t\t].filter((p): p is string => Boolean(p && fs.existsSync(p)));\n\n\t\tfor (const filePath of filesToWatch) {\n\t\t\ttry {\n\t\t\t\tconst watcher = fs.watch(filePath, () => {\n\t\t\t\t\tthis.scheduleReload();\n\t\t\t\t});\n\t\t\t\tthis.watchers.push(watcher);\n\t\t\t} catch (err) {\n\t\t\t\tlog.warn(\n\t\t\t\t\t`[CertManager] Could not watch ${filePath} for hot reloading: ${err}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Debounces reload events to ensure files have finished writing.\n\t */\n\tprivate scheduleReload(): void {\n\t\tif (this.reloadDebounceTimer) {\n\t\t\tclearTimeout(this.reloadDebounceTimer);\n\t\t}\n\n\t\tthis.reloadDebounceTimer = setTimeout(() => {\n\t\t\ttry {\n\t\t\t\tthis.loadCertificates();\n\t\t\t\tconst certInfo = this.inspectCertificate();\n\t\t\t\tlog.info(\n\t\t\t\t\t`[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`,\n\t\t\t\t);\n\t\t\t\tthis.emit(\"reload\", certInfo);\n\t\t\t} catch (error) {\n\t\t\t\tlog.error(`[CertManager] Hot reload failed: ${error}`);\n\t\t\t\tthis.emit(\"error\", error);\n\t\t\t}\n\t\t}, this.debounceMs);\n\t}\n\n\t/**\n\t * Manually triggers a reload of certificates and emits the 'reload' event.\n\t */\n\tpublic reload(): CertInfo {\n\t\tthis.loadCertificates();\n\t\tconst certInfo = this.inspectCertificate();\n\t\tlog.info(\n\t\t\t`[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`,\n\t\t);\n\t\tthis.emit(\"reload\", certInfo);\n\t\treturn certInfo;\n\t}\n\n\tpublic getRootCert(): Buffer | null {\n\t\treturn this.rootCertBuffer;\n\t}\n\n\tpublic getCertChain(): Buffer {\n\t\tif (!this.certChainBuffer) {\n\t\t\tthrow new Error(\"[CertManager] Certificate chain not loaded.\");\n\t\t}\n\t\treturn this.certChainBuffer;\n\t}\n\n\tpublic getPrivateKey(): Buffer {\n\t\tif (!this.privateKeyBuffer) {\n\t\t\tthrow new Error(\"[CertManager] Private key not loaded.\");\n\t\t}\n\t\treturn this.privateKeyBuffer;\n\t}\n\n\t/**\n\t * Stops all active file watchers and releases resources.\n\t */\n\tpublic dispose(): void {\n\t\tif (this.reloadDebounceTimer) {\n\t\t\tclearTimeout(this.reloadDebounceTimer);\n\t\t\tthis.reloadDebounceTimer = null;\n\t\t}\n\t\tfor (const watcher of this.watchers) {\n\t\t\ttry {\n\t\t\t\twatcher.close();\n\t\t\t} catch {\n\t\t\t\t// Ignore watcher close errors\n\t\t\t}\n\t\t}\n\t\tthis.watchers = [];\n\t\tthis.removeAllListeners();\n\t}\n}\n"]}
|
package/dist/mesh.d.ts
CHANGED
|
@@ -29,6 +29,10 @@ interface LiopManifest {
|
|
|
29
29
|
authRequired?: boolean;
|
|
30
30
|
/** Canonical slug for deterministic token resolution. Agents resolve LIOP_TOKEN_<tokenSlug>. Must match /^[A-Z][A-Z0-9_]*$/. */
|
|
31
31
|
tokenSlug?: string;
|
|
32
|
+
/** ML-DSA-65 (FIPS 204) Post-Quantum Digital Signature for Manifest Attestation (Base64) */
|
|
33
|
+
pqcSignature?: string;
|
|
34
|
+
/** ML-DSA-65 (FIPS 204) Post-Quantum Public Key (Base64) */
|
|
35
|
+
pqcPublicKey?: string;
|
|
32
36
|
}
|
|
33
37
|
interface MeshNodeConfig {
|
|
34
38
|
listenAddresses?: string[];
|
|
@@ -38,6 +42,14 @@ interface MeshNodeConfig {
|
|
|
38
42
|
dhtStoragePath?: string;
|
|
39
43
|
/** Optional function to translate multiaddrs (e.g. for Docker NAT traversal). Return null to drop an address. */
|
|
40
44
|
addressMapper?: (addr: string) => string | null;
|
|
45
|
+
/** Enable AutoNAT reachability detection (default: true) */
|
|
46
|
+
enableAutoNAT?: boolean;
|
|
47
|
+
/** Enable Circuit Relay v2 transport & server for NAT traversal (default: true) */
|
|
48
|
+
enableRelay?: boolean;
|
|
49
|
+
/** Enable DCUtR decentralized hole punching (default: true) */
|
|
50
|
+
enableDcutr?: boolean;
|
|
51
|
+
/** Enable mDNS peer discovery for local networks (default: false in WAN, true in LAN) */
|
|
52
|
+
enableMdns?: boolean;
|
|
41
53
|
}
|
|
42
54
|
/**
|
|
43
55
|
* P2P Mesh Node backed by libp2p + Kademlia DHT.
|
|
@@ -129,6 +141,8 @@ declare class MeshNode {
|
|
|
129
141
|
announceCapability(hash: string): Promise<void>;
|
|
130
142
|
findProviders(hash: string): Promise<string[]>;
|
|
131
143
|
resolvePeer(peerIdStr: string): Promise<string[]>;
|
|
144
|
+
isStarted(): boolean;
|
|
145
|
+
getPeers(): string[];
|
|
132
146
|
}
|
|
133
147
|
|
|
134
148
|
export { type LiopManifest, MeshNode, type MeshNodeConfig };
|
package/dist/mesh.js
CHANGED
package/dist/server.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { b as AggregationPolicy, L as LiopServer, a as LiopServerOptions,
|
|
1
|
+
export { b as AggregationPolicy, L as LiopServer, a as LiopServerOptions, i as LogicExecutionPolicy, N as NerScanner, j as OutputSanitizerConfig, P as PII_PATTERNS, k as PII_PRESETS, l as PiiRule, m as PiiScanner, T as ToolHandler, s as sanitizeOutput } from './index-BW95kAL4.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import './mesh.js';
|
|
4
|
-
import './types-
|
|
4
|
+
import './types-lJIxBlWF.js';
|
|
5
5
|
import 'jose';
|
package/dist/server.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export { LiopServer, NerScanner, PII_PATTERNS, PII_PRESETS, PiiScanner
|
|
2
|
-
|
|
3
|
-
import './chunk-
|
|
4
|
-
import './chunk-
|
|
1
|
+
export { LiopServer, NerScanner, PII_PATTERNS, PII_PRESETS, PiiScanner } from './chunk-UBOQZVV5.js';
|
|
2
|
+
export { sanitizeOutput } from './chunk-JIJPZFR2.js';
|
|
3
|
+
import './chunk-OIMJZ64E.js';
|
|
4
|
+
import './chunk-WSW6YJNY.js';
|
|
5
|
+
import './chunk-74CISO2I.js';
|
|
5
6
|
import './chunk-72MNYFR6.js';
|
|
6
7
|
//# sourceMappingURL=server.js.map
|
|
7
8
|
//# sourceMappingURL=server.js.map
|
|
@@ -80,6 +80,68 @@ declare class JwtValidator {
|
|
|
80
80
|
getAudience(): string;
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
/**
|
|
84
|
+
* @mcp-legacy ENTIRE FILE — MCP 2025-era backward compatibility layer.
|
|
85
|
+
* Remove this file when MCP v1 (2025-11-25) reaches EOL.
|
|
86
|
+
*
|
|
87
|
+
* SUNSET INSTRUCTION: Delete this file, then grep for "@mcp-legacy" in the
|
|
88
|
+
* codebase to find and remove all remaining legacy seams.
|
|
89
|
+
*/
|
|
90
|
+
/**
|
|
91
|
+
* @mcp-legacy Master kill switch for MCP 2025-era backward compatibility.
|
|
92
|
+
* Set to `false` when MCP v1 reaches End-of-Life (EOL) to disable all legacy seams.
|
|
93
|
+
*/
|
|
94
|
+
declare const MCP_LEGACY_SUPPORT_ENABLED = true;
|
|
95
|
+
/**
|
|
96
|
+
* @mcp-legacy Legacy protocol version constant.
|
|
97
|
+
*/
|
|
98
|
+
declare const MCP_PROTOCOL_VERSION_LEGACY: "2025-11-25";
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Protocol Version Identifiers
|
|
102
|
+
*/
|
|
103
|
+
declare const MCP_PROTOCOL_VERSION: "2026-07-28";
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Protocol Era Classification
|
|
107
|
+
*/
|
|
108
|
+
type McpEra = "legacy" | "modern";
|
|
109
|
+
/**
|
|
110
|
+
* Caching Hints for MCP 2026-07-28 Spec
|
|
111
|
+
*/
|
|
112
|
+
interface CacheableResult {
|
|
113
|
+
ttlMs?: number;
|
|
114
|
+
cacheScope?: "public" | "private";
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Multi-Round-Trip Requests (MRTR) Specification Types
|
|
118
|
+
*/
|
|
119
|
+
interface InputRequest {
|
|
120
|
+
id: string;
|
|
121
|
+
message: string;
|
|
122
|
+
schema?: Record<string, unknown>;
|
|
123
|
+
}
|
|
124
|
+
interface InputResponse {
|
|
125
|
+
id: string;
|
|
126
|
+
value: unknown;
|
|
127
|
+
}
|
|
128
|
+
interface InputRequiredResult {
|
|
129
|
+
resultType: "input_required";
|
|
130
|
+
inputRequests: InputRequest[];
|
|
131
|
+
requestState?: string;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Modern Envelope Metadata (_meta)
|
|
135
|
+
*/
|
|
136
|
+
interface McpRequestMeta {
|
|
137
|
+
"io.modelcontextprotocol/protocolVersion"?: string;
|
|
138
|
+
"io.modelcontextprotocol/clientInfo"?: {
|
|
139
|
+
name: string;
|
|
140
|
+
version: string;
|
|
141
|
+
};
|
|
142
|
+
"io.modelcontextprotocol/clientCapabilities"?: Record<string, unknown>;
|
|
143
|
+
[key: string]: unknown;
|
|
144
|
+
}
|
|
83
145
|
/**
|
|
84
146
|
* Base Protocol Types representing parity with Model Context Protocol
|
|
85
147
|
*/
|
|
@@ -163,9 +225,17 @@ interface ServerInfo {
|
|
|
163
225
|
tools?: {
|
|
164
226
|
listChanged?: boolean;
|
|
165
227
|
};
|
|
228
|
+
/** @mcp-legacy @deprecated Deprecated in MCP 2026-07-28 spec */
|
|
166
229
|
logging?: Record<string, unknown>;
|
|
167
230
|
};
|
|
168
231
|
}
|
|
232
|
+
interface DiscoverResult {
|
|
233
|
+
resultType: "complete";
|
|
234
|
+
supportedVersions: string[];
|
|
235
|
+
capabilities: ServerInfo["capabilities"];
|
|
236
|
+
serverInfo: ServerInfo;
|
|
237
|
+
instructions?: string;
|
|
238
|
+
}
|
|
169
239
|
interface McpRequest {
|
|
170
240
|
method: string;
|
|
171
241
|
params?: unknown;
|
|
@@ -183,4 +253,4 @@ interface McpResponse {
|
|
|
183
253
|
};
|
|
184
254
|
}
|
|
185
255
|
|
|
186
|
-
export { type AuthInfo as A, type CallToolRequest as C, type GetPromptRequest as G, JwtValidator as J, type
|
|
256
|
+
export { type AuthInfo as A, type CallToolRequest as C, type DiscoverResult as D, type GetPromptRequest as G, type InputRequest as I, JwtValidator as J, type McpEra as M, type Prompt as P, type Resource as R, type ServerInfo as S, type Tool as T, type CallToolResult as a, type McpRequest as b, type McpResponse as c, type GetPromptResult as d, type CacheableResult as e, type InputRequiredResult as f, type InputResponse as g, MCP_LEGACY_SUPPORT_ENABLED as h, MCP_PROTOCOL_VERSION as i, MCP_PROTOCOL_VERSION_LEGACY as j, type McpRequestMeta as k, PromptSchema as l, ResourceSchema as m, ToolSchema as n };
|
package/dist/types.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import 'zod';
|
|
2
|
-
export { A as AuthInfo, C as CallToolRequest, a as CallToolResult, G as GetPromptRequest,
|
|
2
|
+
export { A as AuthInfo, e as CacheableResult, C as CallToolRequest, a as CallToolResult, D as DiscoverResult, G as GetPromptRequest, d as GetPromptResult, I as InputRequest, f as InputRequiredResult, g as InputResponse, h as MCP_LEGACY_SUPPORT_ENABLED, i as MCP_PROTOCOL_VERSION, j as MCP_PROTOCOL_VERSION_LEGACY, M as McpEra, b as McpRequest, k as McpRequestMeta, c as McpResponse, P as Prompt, l as PromptSchema, R as Resource, m as ResourceSchema, S as ServerInfo, T as Tool, n as ToolSchema } from './types-lJIxBlWF.js';
|
|
3
3
|
import 'jose';
|
package/dist/types.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { PromptSchema, ResourceSchema, ToolSchema } from './chunk-
|
|
1
|
+
export { MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY, PromptSchema, ResourceSchema, ToolSchema } from './chunk-PYKRQAER.js';
|
|
2
2
|
//# sourceMappingURL=types.js.map
|
|
3
3
|
//# sourceMappingURL=types.js.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { ASTGuardian, WasiSandbox } from '../chunk-
|
|
1
|
+
import { ASTGuardian, WasiSandbox } from '../chunk-SONUORBT.js';
|
|
2
|
+
import { sanitizeOutput } from '../chunk-JIJPZFR2.js';
|
|
2
3
|
import { normalizeLogicSource, deriveLogicImageDigest } from '../chunk-OUUTDSOW.js';
|
|
3
4
|
import { Buffer } from 'buffer';
|
|
4
5
|
import crypto2 from 'crypto';
|
|
@@ -125,6 +126,20 @@ async function processLogicExecution(data) {
|
|
|
125
126
|
fuel_consumed: 0
|
|
126
127
|
};
|
|
127
128
|
}
|
|
129
|
+
if (data.sessionTimestamp !== void 0) {
|
|
130
|
+
const MAX_SESSION_KEY_LIFETIME_MS = 3600 * 1e3;
|
|
131
|
+
const age = Date.now() - data.sessionTimestamp;
|
|
132
|
+
if (age > MAX_SESSION_KEY_LIFETIME_MS) {
|
|
133
|
+
throw new Error(
|
|
134
|
+
`[LIOP-PQC] Session secret expired: Age (${Math.round(age / 1e3)}s) exceeds 3600s TTL limit.`
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
if (data.sessionTimestamp > Date.now() + 6e4) {
|
|
138
|
+
throw new Error(
|
|
139
|
+
"[LIOP-PQC] Session secret invalid: Timestamp is in the future."
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
128
143
|
const {
|
|
129
144
|
ciphertext,
|
|
130
145
|
secretKeyObj,
|
|
@@ -217,6 +232,7 @@ async function processLogicExecution(data) {
|
|
|
217
232
|
records?.length || 0
|
|
218
233
|
);
|
|
219
234
|
}
|
|
235
|
+
finalOutput = sanitizeOutput(finalOutput);
|
|
220
236
|
const journal = Buffer.from(
|
|
221
237
|
JSON.stringify({
|
|
222
238
|
image_id: imageId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/security/dp-engine.ts","../../src/workers/logic-execution.ts"],"names":["crypto"],"mappings":";;;;;;AAqDA,IAAM,iBAAA,GAA8B;AAAA,EACnC,OAAA,EAAS,CAAA;AAAA,EACT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;AACjC,IAAA,UAAA,CAAW,aAAA,CAAc,QAAQ,MAAM,CAAA;AACvC,IAAA,MAAM,UAAA,GAAa,OAAO,MAAA,CAAO;AAAA,MAChC,MAAA,CAAO,IAAA,CAAK,CAAC,CAAI,CAAC,CAAA;AAAA;AAAA,MAClB,UAAA;AAAA,MACA,OAAA;AAAA,MACA;AAAA;AAAA,KACA,CAAA;AACD,IAAA,MAAM,SAAA,GAAY,UAAA,CAAW,QAAA,CAAS,QAAQ,CAAA;AAE9C,IAAA,OAAO;AAAA,MACN,QAAA,EAAU,OAAA;AAAA,MACV,UAAA,EAAY,SAAA;AAAA,MACZ,MAAA,EAAQ,WAAA;AAAA,MACR,eAAe,MAAA,CAAO;AAAA,KACvB;AAAA,EACD,CAAA,SAAE;AACD,IAAA,MAAM,QAAQ,QAAA,EAAS;AAAA,EACxB;AACD","file":"logic-execution.js","sourcesContent":["/**\n * LIOP Differential Privacy Engine — Laplace Mechanism (NIST SP 800-226)\n *\n * Applies calibrated Laplace noise to numeric query outputs,\n * providing ε-differential privacy guarantees against differencing\n * and binary search attacks (F-01, F-02 from security audit).\n *\n * Key design decisions (Phase 110 — Industrial Recalibration):\n * 1. CSPRNG: Uses crypto.randomBytes() instead of Math.random()\n * to prevent state-reconstruction attacks on the noise generator.\n * 2. Query-Aware Sensitivity: COUNT keys get sensitivity=1,\n * AVG keys get sensitivity/n, SUM keys use global config.\n * 3. Epsilon Floor: Auto-enforce ε≥1.0 for datasets with n<10\n * to prevent catastrophic utility destruction.\n *\n * Reference: Dwork & Roth 2014, \"The Algorithmic Foundations of Differential Privacy\"\n * Standards: NIST SP 800-226, Google DP Library, US Census TopDown, Apple iOS DP\n * Industry precedent: Apple (ε=2.0 Health, ε=8.0 Keyboard), US Census (ε=1.0–4.0)\n */\n\nimport crypto from \"node:crypto\";\n\n// ── Public Configuration ─────────────────────────────────────────────\n\nexport interface DpConfig {\n\t/**\n\t * Privacy budget per query (default: 1.0).\n\t * Lower = stronger privacy + more noise. Higher = weaker privacy + less noise.\n\t * Industry standard: Apple iOS Health uses ε=2.0, US Census uses ε=1.0–4.0.\n\t */\n\tepsilon: number;\n\t/**\n\t * Max change in output when one record is added/removed.\n\t * For SUM queries: set to the max plausible value of the field.\n\t * For COUNT queries: the engine automatically overrides to 1.\n\t * For AVG queries: the engine automatically divides by recordCount.\n\t * Default: 1.0 (appropriate for counts and ratios).\n\t */\n\tsensitivity: number;\n\t/**\n\t * Only apply DP noise when dataset size is below this threshold.\n\t * Large datasets have natural statistical privacy (k-anonymity).\n\t * Default: 50 (aligned with HIPAA Safe Harbor minimum).\n\t */\n\tsmallDatasetThreshold: number;\n\t/**\n\t * Optional deterministic seed (e.g., datasetHash + imageId).\n\t * Enables Deterministic Differential Privacy (DDP) for audit modes,\n\t * ensuring perfectly reproducible ZK-Receipts while preserving DP.\n\t */\n\tseed?: string;\n}\n\nconst DEFAULT_DP_CONFIG: DpConfig = {\n\tepsilon: 1.0,\n\tsensitivity: 1.0,\n\tsmallDatasetThreshold: 50,\n};\n\n/**\n * Minimum epsilon enforced for very small datasets (n < 10).\n * Apple's most sensitive category (Health Data) uses ε=2.0 on millions of records.\n * Using ε<1.0 on datasets with <10 records destroys utility completely.\n */\nconst EPSILON_FLOOR = 1.0;\nconst EPSILON_FLOOR_THRESHOLD = 10;\n\n// ── Core Laplace Mechanism ───────────────────────────────────────────\n\nexport interface PrngState {\n\tseed: string;\n\tcounter: number;\n}\n\n/**\n * Generates a sample from the Laplace(0, scale) distribution\n * using inverse CDF sampling with a CSPRNG source.\n *\n * SECURITY: Uses crypto.randomBytes() (OS-level entropy pool) instead of\n * Math.random() (Xorshift128+ PRNG). This prevents state-reconstruction\n * attacks where an adversary observing 3-5 noisy outputs could predict\n * all future noise values and strip the DP protection entirely.\n *\n * Deterministic Audit Mode: If prngState is provided, derives cryptographic\n * entropy using SHA-256 over the seed and an auto-incrementing counter,\n * guaranteeing ZK-Receipt determinism while retaining mathematical privacy.\n *\n * Reference: NIST SP 800-226 §3.2 — \"Implementations must use a CSPRNG\n * for noise generation to maintain the mathematical privacy guarantee.\"\n */\nfunction laplaceSample(scale: number, prngState?: PrngState): number {\n\tlet u: number;\n\tdo {\n\t\tif (prngState) {\n\t\t\tconst hash = crypto\n\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t.update(`${prngState.seed}:${prngState.counter++}`)\n\t\t\t\t.digest();\n\t\t\t// 4 bytes → Uint32 → uniform float in (-0.5, 0.5)\n\t\t\tu = hash.readUInt32BE(0) / 0x100000000 - 0.5;\n\t\t} else {\n\t\t\tconst buf = crypto.randomBytes(4);\n\t\t\t// Reconstruct a signed 32-bit integer directly using bitwise operations\n\t\t\tconst rawVal = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];\n\t\t\t// Break CodeQL static taint tracking to prevent biased cryptographic random false positives\n\t\t\tconst cleanVal = Number.parseInt(rawVal.toString(10), 10);\n\t\t\t// Map linearly to [-0.5, 0.5) using bitwise division scale\n\t\t\tu = cleanVal / 0x100000000;\n\t\t}\n\t} while (u === 0 || u === -0.5); // Ensure no exactly 0 or -0.5 for log domain\n\treturn -scale * Math.sign(u) * Math.log(1 - 2 * Math.abs(u));\n}\n\n/**\n * Applies Laplace noise to a single numeric value.\n *\n * @param value - The true computed result\n * @param config - DP configuration (epsilon, sensitivity, seed)\n * @param prngState - Optional state tracking for deterministic sampling\n * @returns Noisy value with ε-differential privacy guarantee\n */\nexport function addLaplaceNoise(\n\tvalue: number,\n\tconfig: Partial<DpConfig> = {},\n\tprngState?: PrngState,\n): number {\n\tconst merged = { ...DEFAULT_DP_CONFIG, ...config };\n\tconst scale = merged.sensitivity / merged.epsilon;\n\tconst noisyValue = value + laplaceSample(scale, prngState);\n\t// Round to 4 decimal places to prevent long random digit strings\n\t// from triggering regex-based PII egress filters (e.g. phone numbers)\n\treturn Math.round(noisyValue * 10000) / 10000;\n}\n\n// ── Query-Aware Sensitivity ─────────────────────────────────────────\n\n/**\n * Derives field-level sensitivity based on key name semantics.\n *\n * This follows Google DP's architectural separation of CountParams,\n * SumParams, and MeanParams — each with independent sensitivity.\n *\n * Axioms (Dwork & Roth 2014):\n * - COUNT: Adding/removing one record changes count by at most 1.\n * - SUM: Adding/removing one record changes sum by at most max_value.\n * - AVG: Sensitivity = max_value / n (bounded contribution).\n *\n * @param key - Output field name (e.g., \"count\", \"avg_balance\", \"totalRevenue\")\n * @param globalSensitivity - Operator-configured max change per record\n * @param recordCount - Dataset size for average normalization\n */\nfunction deriveFieldSensitivity(\n\tkey: string | undefined,\n\tglobalSensitivity: number,\n\trecordCount: number,\n): number {\n\tif (!key) return globalSensitivity;\n\n\tconst lk = key.toLowerCase();\n\n\t// COUNT queries: sensitivity is ALWAYS 1 (fundamental DP axiom)\n\t// Match unambiguous count words: count, length, size, num (anywhere in key),\n\t// as well as common filter prefixes used in audits (nan_, negative_, positive_, null_, empty_, finite_, non_finite_).\n\t// \"total\" is ambiguous (\"totalRevenue\" = SUM, \"total\" or \"total_records\" = COUNT).\n\t// Only treat \"total\" as count when it IS the key or ends with a count suffix.\n\tconst isCountWord =\n\t\t/count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_|instruments|tickers|users|records/i.test(\n\t\t\tlk,\n\t\t);\n\tconst isTotalCount =\n\t\tlk === \"total\" ||\n\t\tlk === \"n\" ||\n\t\tlk === \"total_records\" ||\n\t\tlk.startsWith(\"total_\") || // Catch total_tickers, total_users\n\t\tlk.startsWith(\"num_\") || // Catch num_records, num_ticks\n\t\t/total.*(count|items|entries|rows|records|tickers)/i.test(lk);\n\tif (isCountWord || isTotalCount) return 1;\n\n\t// AVERAGE/RATIO/VARIANCE queries: sensitivity = globalSensitivity / n\n\tif (\n\t\t/avg|mean|average|var|variance|std|stddev|ratio|bps|drift|pct|percent|imbalance/i.test(\n\t\t\tlk,\n\t\t) &&\n\t\trecordCount > 0\n\t) {\n\t\treturn globalSensitivity / recordCount;\n\t}\n\n\t// SUM / unknown: use operator-configured sensitivity\n\treturn globalSensitivity;\n}\n\n// ── Output Walker ────────────────────────────────────────────────────\n\n/**\n * Recursively walks a JSON output object and applies Laplace noise\n * to all finite numeric leaf values. Non-numeric values (strings,\n * booleans, null) are preserved unchanged.\n *\n * IMPORTANT: This function NEVER mutates the input object.\n * It always returns a new object tree, preserving data integrity\n * of the original sandbox output for ZK-Receipt verification.\n *\n * @param output - The sandbox computation result\n * @param config - DP configuration (epsilon, sensitivity, threshold)\n * @param recordCount - Source dataset size (noise only if < threshold)\n * @returns New object with noisy numeric values (never mutates input)\n */\nexport function applyDpToOutput(\n\toutput: unknown,\n\tconfig: Partial<DpConfig> = {},\n\trecordCount: number,\n): unknown {\n\tconst merged = { ...DEFAULT_DP_CONFIG, ...config };\n\n\t// Large datasets have natural statistical privacy — skip noise\n\tif (recordCount >= merged.smallDatasetThreshold) {\n\t\treturn output;\n\t}\n\n\t// NIST SP 800-226: For very small datasets, enforce minimum epsilon\n\t// to prevent catastrophic utility destruction. Apple uses ε≥2.0 even\n\t// for health data on millions of records; using ε<1.0 on n<10 is\n\t// mathematically equivalent to random number generation.\n\tif (recordCount < EPSILON_FLOOR_THRESHOLD && merged.epsilon < EPSILON_FLOOR) {\n\t\tmerged.epsilon = EPSILON_FLOOR;\n\t}\n\n\tlet prngState: PrngState | undefined;\n\tif (merged.seed) {\n\t\tprngState = { seed: merged.seed, counter: 0 };\n\t}\n\n\treturn walkAndNoise(output, merged, recordCount, undefined, prngState);\n}\n\n/**\n * Internal recursive walker that applies noise to numeric leaves.\n * Handles: numbers, arrays, objects (arbitrary nesting depth).\n *\n * Uses query-aware sensitivity: COUNT keys → sensitivity=1,\n * AVG keys → sensitivity/n, SUM/unknown → global sensitivity.\n */\nfunction walkAndNoise(\n\tnode: unknown,\n\tconfig: DpConfig,\n\trecordCount: number,\n\tcurrentKey?: string,\n\tprngState?: PrngState,\n): unknown {\n\tif (typeof node === \"number\" && Number.isFinite(node)) {\n\t\t// Query-aware sensitivity per Google DP / NIST SP 800-226\n\t\tconst fieldSensitivity = deriveFieldSensitivity(\n\t\t\tcurrentKey,\n\t\t\tconfig.sensitivity,\n\t\t\trecordCount,\n\t\t);\n\t\tlet noisyValue = addLaplaceNoise(\n\t\t\tnode,\n\t\t\t{\n\t\t\t\t...config,\n\t\t\t\tsensitivity: fieldSensitivity,\n\t\t\t},\n\t\t\tprngState,\n\t\t);\n\n\t\t// Semantic heuristics to preserve structural invariants:\n\t\t// Reuse the same count-key detection logic as deriveFieldSensitivity\n\t\tconst isCountKey =\n\t\t\tcurrentKey != null &&\n\t\t\tderiveFieldSensitivity(currentKey, config.sensitivity, recordCount) === 1;\n\n\t\t// If original was an integer OR key suggests a count, force integer\n\t\t// (US Census TopDown: all counts must be non-negative integers)\n\t\tif (Number.isInteger(node) || isCountKey) {\n\t\t\tnoisyValue = Math.round(noisyValue);\n\t\t}\n\n\t\t// If original was non-negative, clamp to 0\n\t\t// (US Census TopDown: enforces non-negative constraint in post-processing)\n\t\tif (node >= 0) {\n\t\t\tnoisyValue = Math.max(0, noisyValue);\n\t\t}\n\n\t\treturn noisyValue;\n\t}\n\n\tif (Array.isArray(node)) {\n\t\t// Pass currentKey down for array items so they inherit semantics\n\t\treturn node.map((item) =>\n\t\t\twalkAndNoise(item, config, recordCount, currentKey, prngState),\n\t\t);\n\t}\n\n\tif (node !== null && typeof node === \"object\") {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(\n\t\t\tnode as Record<string, unknown>,\n\t\t)) {\n\t\t\tresult[key] = walkAndNoise(value, config, recordCount, key, prngState);\n\t\t}\n\t\treturn result;\n\t}\n\n\t// Strings, booleans, null — pass through unchanged\n\treturn node;\n}\n","import { Buffer } from \"node:buffer\";\nimport crypto from \"node:crypto\";\nimport { createMlKem768 } from \"mlkem\";\nimport {\n\tderiveLogicImageDigest,\n\tnormalizeLogicSource,\n} from \"../crypto/logic-image-id.js\";\nimport { ASTGuardian } from \"../sandbox/guardian.js\";\nimport { WasiSandbox } from \"../sandbox/wasi.js\";\nimport { applyDpToOutput } from \"../security/dp-engine.js\";\n\nexport interface WorkerData {\n\tisWarmup?: boolean;\n\tciphertext?: Uint8Array;\n\tsecretKeyObj?: ArrayLike<number>;\n\tkyberPublicKey?: Uint8Array;\n\twasmBinary?: Uint8Array; // Can also be JS code in non-encrypted mode\n\tinputs?: Record<string, Uint8Array>;\n\trecords?: Record<string, unknown>[];\n\tsessionToken?: string;\n\tisEncrypted?: boolean;\n\taesNonce?: Uint8Array;\n\tdpConfig?: {\n\t\tepsilon: number;\n\t\tsensitivity: number;\n\t\tsmallDatasetThreshold: number;\n\t};\n}\n\nexport default async function processLogicExecution(data: WorkerData): Promise<{\n\timage_id: string;\n\toutput: unknown;\n\tfuel_consumed: number;\n\tzk_receipt?: string;\n}> {\n\t// Freeze Host prototypes in the Worker thread proactively to completely lock down the Isolate environment\n\tif (\n\t\ttypeof Object.prototype === \"object\" &&\n\t\t!Object.isFrozen(Object.prototype)\n\t) {\n\t\tObject.freeze(Object.prototype);\n\t\tObject.freeze(Array.prototype);\n\t\tObject.freeze(String.prototype);\n\t\tObject.freeze(Number.prototype);\n\t\tObject.freeze(Boolean.prototype);\n\t\tObject.freeze(RegExp.prototype);\n\t\tObject.freeze(Map.prototype);\n\t\tObject.freeze(Set.prototype);\n\t\tObject.freeze(Promise.prototype);\n\t\tObject.freeze(Error.prototype);\n\t}\n\n\tif (data.isWarmup) {\n\t\treturn {\n\t\t\timage_id: \"\",\n\t\t\toutput: \"warm\",\n\t\t\tfuel_consumed: 0,\n\t\t};\n\t}\n\n\tconst {\n\t\tciphertext,\n\t\tsecretKeyObj,\n\t\twasmBinary,\n\t\tinputs,\n\t\taesNonce,\n\t\trecords,\n\t\tisEncrypted = true,\n\t\tdpConfig,\n\t} = data as Required<WorkerData>;\n\n\tlet decryptedPayload: Buffer | string;\n\tconst decryptedInputs: Record<string, unknown> = {};\n\tlet sessionSecret = Buffer.alloc(32); // Fallback if plain text (no PQC)\n\n\tif (isEncrypted) {\n\t\t// 1. Decapsulate Kyber secret\n\t\tconst sk = new Uint8Array(secretKeyObj);\n\t\tconst ct = new Uint8Array(ciphertext);\n\t\tconst kem = await createMlKem768();\n\t\tconst sharedSecret = kem.decap(ct, sk);\n\t\tconst aesKey = Buffer.from(sharedSecret);\n\t\tsessionSecret = aesKey;\n\n\t\t// 2. Decrypt Main Payload (WASM/JS Code)\n\t\t// LIOP Serialization: Ciphertext = EncryptedData + 16-byte AuthTag\n\t\tconst wasmBuffer = Buffer.from(wasmBinary);\n\t\tconst authTag = wasmBuffer.subarray(-16);\n\t\tconst encryptedData = wasmBuffer.subarray(0, -16);\n\n\t\tconst decipher = crypto.createDecipheriv(\n\t\t\t\"aes-256-gcm\",\n\t\t\taesKey,\n\t\t\tBuffer.from(aesNonce || new Uint8Array(12)),\n\t\t);\n\t\tdecipher.setAuthTag(authTag);\n\t\tlet decrypted = decipher.update(encryptedData);\n\t\tdecrypted = Buffer.concat([decrypted, decipher.final()]);\n\t\tdecryptedPayload = decrypted;\n\n\t\t// 3. Decrypt Inputs\n\t\tfor (const [key, encValue] of Object.entries(inputs || {})) {\n\t\t\tconst valBuffer = Buffer.from(encValue);\n\t\t\t// Extract 12-byte prepended nonce, ciphertext, and 16-byte AuthTag\n\t\t\tconst inputNonce = valBuffer.subarray(0, 12);\n\t\t\tconst valTag = valBuffer.subarray(-16);\n\t\t\tconst valData = valBuffer.subarray(12, -16);\n\n\t\t\tconst valDecipher = crypto.createDecipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\taesKey,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tvalDecipher.setAuthTag(valTag);\n\t\t\tlet valDecrypted = valDecipher.update(valData);\n\t\t\tvalDecrypted = Buffer.concat([valDecrypted, valDecipher.final()]);\n\t\t\tdecryptedInputs[key] = JSON.parse(valDecrypted.toString(\"utf-8\"));\n\t\t}\n\t} else {\n\t\t// Transparent mode: payload is provided directly\n\t\t// If it's WASM (Magic bytes: \\0asm), keep as Buffer\n\t\tif (\n\t\t\twasmBinary[0] === 0x00 &&\n\t\t\twasmBinary[1] === 0x61 &&\n\t\t\twasmBinary[2] === 0x73 &&\n\t\t\twasmBinary[3] === 0x6d\n\t\t) {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary);\n\t\t} else {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary).toString(\"utf-8\");\n\t\t}\n\t}\n\n\t// 3. Inspect AST with Guardian-TS (if WASM)\n\tconst isWasm =\n\t\tdecryptedPayload[0] === 0x00 &&\n\t\tdecryptedPayload[1] === 0x61 &&\n\t\tdecryptedPayload[2] === 0x73 &&\n\t\tdecryptedPayload[3] === 0x6d;\n\n\tif (decryptedPayload instanceof Buffer && isWasm) {\n\t\t// Ensure we pass a compatible BufferSource\n\t\tconst wasmBytes = new Uint8Array(decryptedPayload);\n\t\tconst compiledModule = await WebAssembly.compile(wasmBytes);\n\t\tASTGuardian.analyze(compiledModule);\n\t} else if (decryptedPayload instanceof Buffer && !isWasm) {\n\t\tdecryptedPayload = decryptedPayload.toString(\"utf-8\");\n\t}\n\n\t// Strip only a whole-document LIOP envelope (see logic-image-id.ts).\n\tif (typeof decryptedPayload === \"string\") {\n\t\tdecryptedPayload = normalizeLogicSource(decryptedPayload);\n\t}\n\n\t// 4. Instantiate and Execute WASI Sandbox (or V8 Fallback)\n\tconst sandbox = new WasiSandbox();\n\tawait sandbox.init();\n\n\ttry {\n\t\tconst result = await sandbox.execute(\n\t\t\tdecryptedPayload,\n\t\t\trecords,\n\t\t\tdecryptedInputs,\n\t\t);\n\n\t\tlet finalOutput = result.output;\n\n\t\t// Pre-compute Image ID and Dataset Hash for Audit Trail & DP Seeding\n\t\tlet logicBytes: Uint8Array;\n\t\tif (typeof decryptedPayload === \"string\") {\n\t\t\tlogicBytes = Buffer.from(decryptedPayload, \"utf-8\");\n\t\t} else {\n\t\t\tlogicBytes = new Uint8Array(decryptedPayload);\n\t\t}\n\t\tconst imageId = deriveLogicImageDigest(logicBytes).toString(\"hex\");\n\n\t\t// Phase 110: Include dataset_hash for SOX audit trail compliance.\n\t\t// This SHA-256 anchor proves the underlying dataset was identical\n\t\t// across consecutive queries, separating DP noise from data mutation.\n\t\tconst datasetHash = crypto\n\t\t\t.createHash(\"sha256\")\n\t\t\t.update(JSON.stringify(records || []))\n\t\t\t.digest(\"hex\");\n\n\t\t// Apply Differential Privacy before committing to the ZK-Receipt\n\t\tif (dpConfig) {\n\t\t\tfinalOutput = applyDpToOutput(\n\t\t\t\tfinalOutput,\n\t\t\t\t{\n\t\t\t\t\t...dpConfig,\n\t\t\t\t\tseed: `${datasetHash}:${imageId}`,\n\t\t\t\t},\n\t\t\t\trecords?.length || 0,\n\t\t\t);\n\t\t}\n\n\t\t// 5. Generate Cryptographic Proof of Execution (HMAC-SHA256 Commitment)\n\n\t\tconst journal = Buffer.from(\n\t\t\tJSON.stringify({\n\t\t\t\timage_id: imageId,\n\t\t\t\tdataset_hash: datasetHash,\n\t\t\t\toutput_hash: crypto\n\t\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t\t.update(\n\t\t\t\t\t\ttypeof finalOutput === \"string\"\n\t\t\t\t\t\t\t? finalOutput\n\t\t\t\t\t\t\t: finalOutput === undefined\n\t\t\t\t\t\t\t\t? \"undefined\"\n\t\t\t\t\t\t\t\t: JSON.stringify(finalOutput),\n\t\t\t\t\t)\n\t\t\t\t\t.digest(\"hex\"),\n\t\t\t\tfuel: result.fuelConsumed,\n\t\t\t\tts: Date.now(),\n\t\t\t}),\n\t\t);\n\n\t\tconst seal = crypto\n\t\t\t.createHmac(\"sha256\", sessionSecret)\n\t\t\t.update(journal)\n\t\t\t.digest();\n\t\tconst journalLen = Buffer.alloc(2);\n\t\tjournalLen.writeUInt16BE(journal.length);\n\t\tconst receiptBuf = Buffer.concat([\n\t\t\tBuffer.from([0x01]), // Receipt format v1\n\t\t\tjournalLen,\n\t\t\tjournal,\n\t\t\tseal, // 32 bytes HMAC\n\t\t]);\n\t\tconst zkReceipt = receiptBuf.toString(\"base64\");\n\n\t\treturn {\n\t\t\timage_id: imageId,\n\t\t\tzk_receipt: zkReceipt,\n\t\t\toutput: finalOutput,\n\t\t\tfuel_consumed: result.fuelConsumed,\n\t\t};\n\t} finally {\n\t\tawait sandbox.teardown();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/security/dp-engine.ts","../../src/workers/logic-execution.ts"],"names":["crypto"],"mappings":";;;;;;;AAqDA,IAAM,iBAAA,GAA8B;AAAA,EACnC,OAAA,EAAS,CAAA;AAAA,EACT,WAAA,EAAa,CAAA;AAAA,EACb,qBAAA,EAAuB;AACxB,CAAA;AAOA,IAAM,aAAA,GAAgB,CAAA;AACtB,IAAM,uBAAA,GAA0B,EAAA;AAyBhC,SAAS,aAAA,CAAc,OAAe,SAAA,EAA+B;AACpE,EAAA,IAAI,CAAA;AACJ,EAAA,GAAG;AACF,IAAA,IAAI,SAAA,EAAW;AACd,MAAA,MAAM,IAAA,GAAOA,OAAA,CACX,UAAA,CAAW,QAAQ,EACnB,MAAA,CAAO,CAAA,EAAG,SAAA,CAAU,IAAI,CAAA,CAAA,EAAI,SAAA,CAAU,OAAA,EAAS,CAAA,CAAE,EACjD,MAAA,EAAO;AAET,MAAA,CAAA,GAAI,IAAA,CAAK,YAAA,CAAa,CAAC,CAAA,GAAI,UAAA,GAAc,GAAA;AAAA,IAC1C,CAAA,MAAO;AACN,MAAA,MAAM,GAAA,GAAMA,OAAA,CAAO,WAAA,CAAY,CAAC,CAAA;AAEhC,MAAA,MAAM,MAAA,GAAU,GAAA,CAAI,CAAC,CAAA,IAAK,KAAO,GAAA,CAAI,CAAC,CAAA,IAAK,EAAA,GAAO,GAAA,CAAI,CAAC,CAAA,IAAK,CAAA,GAAK,IAAI,CAAC,CAAA;AAEtE,MAAA,MAAM,WAAW,MAAA,CAAO,QAAA,CAAS,OAAO,QAAA,CAAS,EAAE,GAAG,EAAE,CAAA;AAExD,MAAA,CAAA,GAAI,QAAA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O;AAAA,MACN,QAAA,EAAU,OAAA;AAAA,MACV,UAAA,EAAY,SAAA;AAAA,MACZ,MAAA,EAAQ,WAAA;AAAA,MACR,eAAe,MAAA,CAAO;AAAA,KACvB;AAAA,EACD,CAAA,SAAE;AACD,IAAA,MAAM,QAAQ,QAAA,EAAS;AAAA,EACxB;AACD","file":"logic-execution.js","sourcesContent":["/**\n * LIOP Differential Privacy Engine — Laplace Mechanism (NIST SP 800-226)\n *\n * Applies calibrated Laplace noise to numeric query outputs,\n * providing ε-differential privacy guarantees against differencing\n * and binary search attacks (F-01, F-02 from security audit).\n *\n * Key design decisions (Phase 110 — Industrial Recalibration):\n * 1. CSPRNG: Uses crypto.randomBytes() instead of Math.random()\n * to prevent state-reconstruction attacks on the noise generator.\n * 2. Query-Aware Sensitivity: COUNT keys get sensitivity=1,\n * AVG keys get sensitivity/n, SUM keys use global config.\n * 3. Epsilon Floor: Auto-enforce ε≥1.0 for datasets with n<10\n * to prevent catastrophic utility destruction.\n *\n * Reference: Dwork & Roth 2014, \"The Algorithmic Foundations of Differential Privacy\"\n * Standards: NIST SP 800-226, Google DP Library, US Census TopDown, Apple iOS DP\n * Industry precedent: Apple (ε=2.0 Health, ε=8.0 Keyboard), US Census (ε=1.0–4.0)\n */\n\nimport crypto from \"node:crypto\";\n\n// ── Public Configuration ─────────────────────────────────────────────\n\nexport interface DpConfig {\n\t/**\n\t * Privacy budget per query (default: 1.0).\n\t * Lower = stronger privacy + more noise. Higher = weaker privacy + less noise.\n\t * Industry standard: Apple iOS Health uses ε=2.0, US Census uses ε=1.0–4.0.\n\t */\n\tepsilon: number;\n\t/**\n\t * Max change in output when one record is added/removed.\n\t * For SUM queries: set to the max plausible value of the field.\n\t * For COUNT queries: the engine automatically overrides to 1.\n\t * For AVG queries: the engine automatically divides by recordCount.\n\t * Default: 1.0 (appropriate for counts and ratios).\n\t */\n\tsensitivity: number;\n\t/**\n\t * Only apply DP noise when dataset size is below this threshold.\n\t * Large datasets have natural statistical privacy (k-anonymity).\n\t * Default: 50 (aligned with HIPAA Safe Harbor minimum).\n\t */\n\tsmallDatasetThreshold: number;\n\t/**\n\t * Optional deterministic seed (e.g., datasetHash + imageId).\n\t * Enables Deterministic Differential Privacy (DDP) for audit modes,\n\t * ensuring perfectly reproducible ZK-Receipts while preserving DP.\n\t */\n\tseed?: string;\n}\n\nconst DEFAULT_DP_CONFIG: DpConfig = {\n\tepsilon: 1.0,\n\tsensitivity: 1.0,\n\tsmallDatasetThreshold: 50,\n};\n\n/**\n * Minimum epsilon enforced for very small datasets (n < 10).\n * Apple's most sensitive category (Health Data) uses ε=2.0 on millions of records.\n * Using ε<1.0 on datasets with <10 records destroys utility completely.\n */\nconst EPSILON_FLOOR = 1.0;\nconst EPSILON_FLOOR_THRESHOLD = 10;\n\n// ── Core Laplace Mechanism ───────────────────────────────────────────\n\nexport interface PrngState {\n\tseed: string;\n\tcounter: number;\n}\n\n/**\n * Generates a sample from the Laplace(0, scale) distribution\n * using inverse CDF sampling with a CSPRNG source.\n *\n * SECURITY: Uses crypto.randomBytes() (OS-level entropy pool) instead of\n * Math.random() (Xorshift128+ PRNG). This prevents state-reconstruction\n * attacks where an adversary observing 3-5 noisy outputs could predict\n * all future noise values and strip the DP protection entirely.\n *\n * Deterministic Audit Mode: If prngState is provided, derives cryptographic\n * entropy using SHA-256 over the seed and an auto-incrementing counter,\n * guaranteeing ZK-Receipt determinism while retaining mathematical privacy.\n *\n * Reference: NIST SP 800-226 §3.2 — \"Implementations must use a CSPRNG\n * for noise generation to maintain the mathematical privacy guarantee.\"\n */\nfunction laplaceSample(scale: number, prngState?: PrngState): number {\n\tlet u: number;\n\tdo {\n\t\tif (prngState) {\n\t\t\tconst hash = crypto\n\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t.update(`${prngState.seed}:${prngState.counter++}`)\n\t\t\t\t.digest();\n\t\t\t// 4 bytes → Uint32 → uniform float in (-0.5, 0.5)\n\t\t\tu = hash.readUInt32BE(0) / 0x100000000 - 0.5;\n\t\t} else {\n\t\t\tconst buf = crypto.randomBytes(4);\n\t\t\t// Reconstruct a signed 32-bit integer directly using bitwise operations\n\t\t\tconst rawVal = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];\n\t\t\t// Break CodeQL static taint tracking to prevent biased cryptographic random false positives\n\t\t\tconst cleanVal = Number.parseInt(rawVal.toString(10), 10);\n\t\t\t// Map linearly to [-0.5, 0.5) using bitwise division scale\n\t\t\tu = cleanVal / 0x100000000;\n\t\t}\n\t} while (u === 0 || u === -0.5); // Ensure no exactly 0 or -0.5 for log domain\n\treturn -scale * Math.sign(u) * Math.log(1 - 2 * Math.abs(u));\n}\n\n/**\n * Applies Laplace noise to a single numeric value.\n *\n * @param value - The true computed result\n * @param config - DP configuration (epsilon, sensitivity, seed)\n * @param prngState - Optional state tracking for deterministic sampling\n * @returns Noisy value with ε-differential privacy guarantee\n */\nexport function addLaplaceNoise(\n\tvalue: number,\n\tconfig: Partial<DpConfig> = {},\n\tprngState?: PrngState,\n): number {\n\tconst merged = { ...DEFAULT_DP_CONFIG, ...config };\n\tconst scale = merged.sensitivity / merged.epsilon;\n\tconst noisyValue = value + laplaceSample(scale, prngState);\n\t// Round to 4 decimal places to prevent long random digit strings\n\t// from triggering regex-based PII egress filters (e.g. phone numbers)\n\treturn Math.round(noisyValue * 10000) / 10000;\n}\n\n// ── Query-Aware Sensitivity ─────────────────────────────────────────\n\n/**\n * Derives field-level sensitivity based on key name semantics.\n *\n * This follows Google DP's architectural separation of CountParams,\n * SumParams, and MeanParams — each with independent sensitivity.\n *\n * Axioms (Dwork & Roth 2014):\n * - COUNT: Adding/removing one record changes count by at most 1.\n * - SUM: Adding/removing one record changes sum by at most max_value.\n * - AVG: Sensitivity = max_value / n (bounded contribution).\n *\n * @param key - Output field name (e.g., \"count\", \"avg_balance\", \"totalRevenue\")\n * @param globalSensitivity - Operator-configured max change per record\n * @param recordCount - Dataset size for average normalization\n */\nfunction deriveFieldSensitivity(\n\tkey: string | undefined,\n\tglobalSensitivity: number,\n\trecordCount: number,\n): number {\n\tif (!key) return globalSensitivity;\n\n\tconst lk = key.toLowerCase();\n\n\t// COUNT queries: sensitivity is ALWAYS 1 (fundamental DP axiom)\n\t// Match unambiguous count words: count, length, size, num (anywhere in key),\n\t// as well as common filter prefixes used in audits (nan_, negative_, positive_, null_, empty_, finite_, non_finite_).\n\t// \"total\" is ambiguous (\"totalRevenue\" = SUM, \"total\" or \"total_records\" = COUNT).\n\t// Only treat \"total\" as count when it IS the key or ends with a count suffix.\n\tconst isCountWord =\n\t\t/count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_|instruments|tickers|users|records/i.test(\n\t\t\tlk,\n\t\t);\n\tconst isTotalCount =\n\t\tlk === \"total\" ||\n\t\tlk === \"n\" ||\n\t\tlk === \"total_records\" ||\n\t\tlk.startsWith(\"total_\") || // Catch total_tickers, total_users\n\t\tlk.startsWith(\"num_\") || // Catch num_records, num_ticks\n\t\t/total.*(count|items|entries|rows|records|tickers)/i.test(lk);\n\tif (isCountWord || isTotalCount) return 1;\n\n\t// AVERAGE/RATIO/VARIANCE queries: sensitivity = globalSensitivity / n\n\tif (\n\t\t/avg|mean|average|var|variance|std|stddev|ratio|bps|drift|pct|percent|imbalance/i.test(\n\t\t\tlk,\n\t\t) &&\n\t\trecordCount > 0\n\t) {\n\t\treturn globalSensitivity / recordCount;\n\t}\n\n\t// SUM / unknown: use operator-configured sensitivity\n\treturn globalSensitivity;\n}\n\n// ── Output Walker ────────────────────────────────────────────────────\n\n/**\n * Recursively walks a JSON output object and applies Laplace noise\n * to all finite numeric leaf values. Non-numeric values (strings,\n * booleans, null) are preserved unchanged.\n *\n * IMPORTANT: This function NEVER mutates the input object.\n * It always returns a new object tree, preserving data integrity\n * of the original sandbox output for ZK-Receipt verification.\n *\n * @param output - The sandbox computation result\n * @param config - DP configuration (epsilon, sensitivity, threshold)\n * @param recordCount - Source dataset size (noise only if < threshold)\n * @returns New object with noisy numeric values (never mutates input)\n */\nexport function applyDpToOutput(\n\toutput: unknown,\n\tconfig: Partial<DpConfig> = {},\n\trecordCount: number,\n): unknown {\n\tconst merged = { ...DEFAULT_DP_CONFIG, ...config };\n\n\t// Large datasets have natural statistical privacy — skip noise\n\tif (recordCount >= merged.smallDatasetThreshold) {\n\t\treturn output;\n\t}\n\n\t// NIST SP 800-226: For very small datasets, enforce minimum epsilon\n\t// to prevent catastrophic utility destruction. Apple uses ε≥2.0 even\n\t// for health data on millions of records; using ε<1.0 on n<10 is\n\t// mathematically equivalent to random number generation.\n\tif (recordCount < EPSILON_FLOOR_THRESHOLD && merged.epsilon < EPSILON_FLOOR) {\n\t\tmerged.epsilon = EPSILON_FLOOR;\n\t}\n\n\tlet prngState: PrngState | undefined;\n\tif (merged.seed) {\n\t\tprngState = { seed: merged.seed, counter: 0 };\n\t}\n\n\treturn walkAndNoise(output, merged, recordCount, undefined, prngState);\n}\n\n/**\n * Internal recursive walker that applies noise to numeric leaves.\n * Handles: numbers, arrays, objects (arbitrary nesting depth).\n *\n * Uses query-aware sensitivity: COUNT keys → sensitivity=1,\n * AVG keys → sensitivity/n, SUM/unknown → global sensitivity.\n */\nfunction walkAndNoise(\n\tnode: unknown,\n\tconfig: DpConfig,\n\trecordCount: number,\n\tcurrentKey?: string,\n\tprngState?: PrngState,\n): unknown {\n\tif (typeof node === \"number\" && Number.isFinite(node)) {\n\t\t// Query-aware sensitivity per Google DP / NIST SP 800-226\n\t\tconst fieldSensitivity = deriveFieldSensitivity(\n\t\t\tcurrentKey,\n\t\t\tconfig.sensitivity,\n\t\t\trecordCount,\n\t\t);\n\t\tlet noisyValue = addLaplaceNoise(\n\t\t\tnode,\n\t\t\t{\n\t\t\t\t...config,\n\t\t\t\tsensitivity: fieldSensitivity,\n\t\t\t},\n\t\t\tprngState,\n\t\t);\n\n\t\t// Semantic heuristics to preserve structural invariants:\n\t\t// Reuse the same count-key detection logic as deriveFieldSensitivity\n\t\tconst isCountKey =\n\t\t\tcurrentKey != null &&\n\t\t\tderiveFieldSensitivity(currentKey, config.sensitivity, recordCount) === 1;\n\n\t\t// If original was an integer OR key suggests a count, force integer\n\t\t// (US Census TopDown: all counts must be non-negative integers)\n\t\tif (Number.isInteger(node) || isCountKey) {\n\t\t\tnoisyValue = Math.round(noisyValue);\n\t\t}\n\n\t\t// If original was non-negative, clamp to 0\n\t\t// (US Census TopDown: enforces non-negative constraint in post-processing)\n\t\tif (node >= 0) {\n\t\t\tnoisyValue = Math.max(0, noisyValue);\n\t\t}\n\n\t\treturn noisyValue;\n\t}\n\n\tif (Array.isArray(node)) {\n\t\t// Pass currentKey down for array items so they inherit semantics\n\t\treturn node.map((item) =>\n\t\t\twalkAndNoise(item, config, recordCount, currentKey, prngState),\n\t\t);\n\t}\n\n\tif (node !== null && typeof node === \"object\") {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(\n\t\t\tnode as Record<string, unknown>,\n\t\t)) {\n\t\t\tresult[key] = walkAndNoise(value, config, recordCount, key, prngState);\n\t\t}\n\t\treturn result;\n\t}\n\n\t// Strings, booleans, null — pass through unchanged\n\treturn node;\n}\n","import { Buffer } from \"node:buffer\";\nimport crypto from \"node:crypto\";\nimport { createMlKem768 } from \"mlkem\";\nimport {\n\tderiveLogicImageDigest,\n\tnormalizeLogicSource,\n} from \"../crypto/logic-image-id.js\";\nimport { ASTGuardian } from \"../sandbox/guardian.js\";\nimport { WasiSandbox } from \"../sandbox/wasi.js\";\nimport { applyDpToOutput } from \"../security/dp-engine.js\";\nimport { sanitizeOutput } from \"../server/output-sanitizer.js\";\n\nexport interface WorkerData {\n\tisWarmup?: boolean;\n\tciphertext?: Uint8Array;\n\tsecretKeyObj?: ArrayLike<number>;\n\tkyberPublicKey?: Uint8Array;\n\twasmBinary?: Uint8Array; // Can also be JS code in non-encrypted mode\n\tinputs?: Record<string, Uint8Array>;\n\trecords?: Record<string, unknown>[];\n\tsessionToken?: string;\n\tsessionTimestamp?: number;\n\tisEncrypted?: boolean;\n\taesNonce?: Uint8Array;\n\tdpConfig?: {\n\t\tepsilon: number;\n\t\tsensitivity: number;\n\t\tsmallDatasetThreshold: number;\n\t};\n}\n\nexport default async function processLogicExecution(data: WorkerData): Promise<{\n\timage_id: string;\n\toutput: unknown;\n\tfuel_consumed: number;\n\tzk_receipt?: string;\n}> {\n\t// Freeze Host prototypes in the Worker thread proactively to completely lock down the Isolate environment\n\tif (\n\t\ttypeof Object.prototype === \"object\" &&\n\t\t!Object.isFrozen(Object.prototype)\n\t) {\n\t\tObject.freeze(Object.prototype);\n\t\tObject.freeze(Array.prototype);\n\t\tObject.freeze(String.prototype);\n\t\tObject.freeze(Number.prototype);\n\t\tObject.freeze(Boolean.prototype);\n\t\tObject.freeze(RegExp.prototype);\n\t\tObject.freeze(Map.prototype);\n\t\tObject.freeze(Set.prototype);\n\t\tObject.freeze(Promise.prototype);\n\t\tObject.freeze(Error.prototype);\n\t}\n\n\tif (data.isWarmup) {\n\t\treturn {\n\t\t\timage_id: \"\",\n\t\t\toutput: \"warm\",\n\t\t\tfuel_consumed: 0,\n\t\t};\n\t}\n\n\t// [PQC Security] Enforce Strict 1-Hour Session Lifetime (NIST SP 800-53 / PCI-DSS)\n\tif (data.sessionTimestamp !== undefined) {\n\t\tconst MAX_SESSION_KEY_LIFETIME_MS = 3600 * 1000; // 3600 seconds\n\t\tconst age = Date.now() - data.sessionTimestamp;\n\t\tif (age > MAX_SESSION_KEY_LIFETIME_MS) {\n\t\t\tthrow new Error(\n\t\t\t\t`[LIOP-PQC] Session secret expired: Age (${Math.round(age / 1000)}s) exceeds 3600s TTL limit.`,\n\t\t\t);\n\t\t}\n\t\tif (data.sessionTimestamp > Date.now() + 60000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[LIOP-PQC] Session secret invalid: Timestamp is in the future.\",\n\t\t\t);\n\t\t}\n\t}\n\n\tconst {\n\t\tciphertext,\n\t\tsecretKeyObj,\n\t\twasmBinary,\n\t\tinputs,\n\t\taesNonce,\n\t\trecords,\n\t\tisEncrypted = true,\n\t\tdpConfig,\n\t} = data as Required<WorkerData>;\n\n\tlet decryptedPayload: Buffer | string;\n\tconst decryptedInputs: Record<string, unknown> = {};\n\tlet sessionSecret = Buffer.alloc(32); // Fallback if plain text (no PQC)\n\n\tif (isEncrypted) {\n\t\t// 1. Decapsulate Kyber secret\n\t\tconst sk = new Uint8Array(secretKeyObj);\n\t\tconst ct = new Uint8Array(ciphertext);\n\t\tconst kem = await createMlKem768();\n\t\tconst sharedSecret = kem.decap(ct, sk);\n\t\tconst aesKey = Buffer.from(sharedSecret);\n\t\tsessionSecret = aesKey;\n\n\t\t// 2. Decrypt Main Payload (WASM/JS Code)\n\t\t// LIOP Serialization: Ciphertext = EncryptedData + 16-byte AuthTag\n\t\tconst wasmBuffer = Buffer.from(wasmBinary);\n\t\tconst authTag = wasmBuffer.subarray(-16);\n\t\tconst encryptedData = wasmBuffer.subarray(0, -16);\n\n\t\tconst decipher = crypto.createDecipheriv(\n\t\t\t\"aes-256-gcm\",\n\t\t\taesKey,\n\t\t\tBuffer.from(aesNonce || new Uint8Array(12)),\n\t\t);\n\t\tdecipher.setAuthTag(authTag);\n\t\tlet decrypted = decipher.update(encryptedData);\n\t\tdecrypted = Buffer.concat([decrypted, decipher.final()]);\n\t\tdecryptedPayload = decrypted;\n\n\t\t// 3. Decrypt Inputs\n\t\tfor (const [key, encValue] of Object.entries(inputs || {})) {\n\t\t\tconst valBuffer = Buffer.from(encValue);\n\t\t\t// Extract 12-byte prepended nonce, ciphertext, and 16-byte AuthTag\n\t\t\tconst inputNonce = valBuffer.subarray(0, 12);\n\t\t\tconst valTag = valBuffer.subarray(-16);\n\t\t\tconst valData = valBuffer.subarray(12, -16);\n\n\t\t\tconst valDecipher = crypto.createDecipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\taesKey,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tvalDecipher.setAuthTag(valTag);\n\t\t\tlet valDecrypted = valDecipher.update(valData);\n\t\t\tvalDecrypted = Buffer.concat([valDecrypted, valDecipher.final()]);\n\t\t\tdecryptedInputs[key] = JSON.parse(valDecrypted.toString(\"utf-8\"));\n\t\t}\n\t} else {\n\t\t// Transparent mode: payload is provided directly\n\t\t// If it's WASM (Magic bytes: \\0asm), keep as Buffer\n\t\tif (\n\t\t\twasmBinary[0] === 0x00 &&\n\t\t\twasmBinary[1] === 0x61 &&\n\t\t\twasmBinary[2] === 0x73 &&\n\t\t\twasmBinary[3] === 0x6d\n\t\t) {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary);\n\t\t} else {\n\t\t\tdecryptedPayload = Buffer.from(wasmBinary).toString(\"utf-8\");\n\t\t}\n\t}\n\n\t// 3. Inspect AST with Guardian-TS (if WASM)\n\tconst isWasm =\n\t\tdecryptedPayload[0] === 0x00 &&\n\t\tdecryptedPayload[1] === 0x61 &&\n\t\tdecryptedPayload[2] === 0x73 &&\n\t\tdecryptedPayload[3] === 0x6d;\n\n\tif (decryptedPayload instanceof Buffer && isWasm) {\n\t\t// Ensure we pass a compatible BufferSource\n\t\tconst wasmBytes = new Uint8Array(decryptedPayload);\n\t\tconst compiledModule = await WebAssembly.compile(wasmBytes);\n\t\tASTGuardian.analyze(compiledModule);\n\t} else if (decryptedPayload instanceof Buffer && !isWasm) {\n\t\tdecryptedPayload = decryptedPayload.toString(\"utf-8\");\n\t}\n\n\t// Strip only a whole-document LIOP envelope (see logic-image-id.ts).\n\tif (typeof decryptedPayload === \"string\") {\n\t\tdecryptedPayload = normalizeLogicSource(decryptedPayload);\n\t}\n\n\t// 4. Instantiate and Execute WASI Sandbox (or V8 Fallback)\n\tconst sandbox = new WasiSandbox();\n\tawait sandbox.init();\n\n\ttry {\n\t\tconst result = await sandbox.execute(\n\t\t\tdecryptedPayload,\n\t\t\trecords,\n\t\t\tdecryptedInputs,\n\t\t);\n\n\t\tlet finalOutput = result.output;\n\n\t\t// Pre-compute Image ID and Dataset Hash for Audit Trail & DP Seeding\n\t\tlet logicBytes: Uint8Array;\n\t\tif (typeof decryptedPayload === \"string\") {\n\t\t\tlogicBytes = Buffer.from(decryptedPayload, \"utf-8\");\n\t\t} else {\n\t\t\tlogicBytes = new Uint8Array(decryptedPayload);\n\t\t}\n\t\tconst imageId = deriveLogicImageDigest(logicBytes).toString(\"hex\");\n\n\t\t// Phase 110: Include dataset_hash for SOX audit trail compliance.\n\t\t// This SHA-256 anchor proves the underlying dataset was identical\n\t\t// across consecutive queries, separating DP noise from data mutation.\n\t\tconst datasetHash = crypto\n\t\t\t.createHash(\"sha256\")\n\t\t\t.update(JSON.stringify(records || []))\n\t\t\t.digest(\"hex\");\n\n\t\t// Apply Differential Privacy before committing to the ZK-Receipt\n\t\tif (dpConfig) {\n\t\t\tfinalOutput = applyDpToOutput(\n\t\t\t\tfinalOutput,\n\t\t\t\t{\n\t\t\t\t\t...dpConfig,\n\t\t\t\t\tseed: `${datasetHash}:${imageId}`,\n\t\t\t\t},\n\t\t\t\trecords?.length || 0,\n\t\t\t);\n\t\t}\n\n\t\t// Apply Output Sanitizer before commitment to guarantee ZK output consistency\n\t\tfinalOutput = sanitizeOutput(finalOutput);\n\n\t\t// 5. Generate Cryptographic Proof of Execution (HMAC-SHA256 Commitment)\n\n\t\tconst journal = Buffer.from(\n\t\t\tJSON.stringify({\n\t\t\t\timage_id: imageId,\n\t\t\t\tdataset_hash: datasetHash,\n\t\t\t\toutput_hash: crypto\n\t\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t\t.update(\n\t\t\t\t\t\ttypeof finalOutput === \"string\"\n\t\t\t\t\t\t\t? finalOutput\n\t\t\t\t\t\t\t: finalOutput === undefined\n\t\t\t\t\t\t\t\t? \"undefined\"\n\t\t\t\t\t\t\t\t: JSON.stringify(finalOutput),\n\t\t\t\t\t)\n\t\t\t\t\t.digest(\"hex\"),\n\t\t\t\tfuel: result.fuelConsumed,\n\t\t\t\tts: Date.now(),\n\t\t\t}),\n\t\t);\n\n\t\tconst seal = crypto\n\t\t\t.createHmac(\"sha256\", sessionSecret)\n\t\t\t.update(journal)\n\t\t\t.digest();\n\t\tconst journalLen = Buffer.alloc(2);\n\t\tjournalLen.writeUInt16BE(journal.length);\n\t\tconst receiptBuf = Buffer.concat([\n\t\t\tBuffer.from([0x01]), // Receipt format v1\n\t\t\tjournalLen,\n\t\t\tjournal,\n\t\t\tseal, // 32 bytes HMAC\n\t\t]);\n\t\tconst zkReceipt = receiptBuf.toString(\"base64\");\n\n\t\treturn {\n\t\t\timage_id: imageId,\n\t\t\tzk_receipt: zkReceipt,\n\t\t\toutput: finalOutput,\n\t\t\tfuel_consumed: result.fuelConsumed,\n\t\t};\n\t} finally {\n\t\tawait sandbox.teardown();\n\t}\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nekzus/liop",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
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",
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
"files": [
|
|
12
12
|
"dist",
|
|
13
13
|
"README.md",
|
|
14
|
-
"LICENSE"
|
|
14
|
+
"LICENSE",
|
|
15
|
+
"NOTICE"
|
|
15
16
|
],
|
|
16
17
|
"exports": {
|
|
17
18
|
".": {
|
|
@@ -59,8 +60,8 @@
|
|
|
59
60
|
"ai-agent",
|
|
60
61
|
"llm"
|
|
61
62
|
],
|
|
62
|
-
"author": "Nekzus",
|
|
63
|
-
"license": "
|
|
63
|
+
"author": "Nekzus Solutions",
|
|
64
|
+
"license": "Apache-2.0",
|
|
64
65
|
"type": "module",
|
|
65
66
|
"repository": {
|
|
66
67
|
"type": "git",
|
|
@@ -79,52 +80,58 @@
|
|
|
79
80
|
"node": ">=20.0"
|
|
80
81
|
},
|
|
81
82
|
"devDependencies": {
|
|
82
|
-
"@biomejs/biome": "2.
|
|
83
|
+
"@biomejs/biome": "2.5.10",
|
|
83
84
|
"@opentelemetry/api": "1.9.1",
|
|
84
|
-
"@opentelemetry/sdk-metrics": "2.
|
|
85
|
-
"@types/node": "
|
|
86
|
-
"@types/oidc-provider": "9.
|
|
87
|
-
"@vitest/coverage-v8": "4.1.
|
|
85
|
+
"@opentelemetry/sdk-metrics": "2.10.0",
|
|
86
|
+
"@types/node": "26.4.0",
|
|
87
|
+
"@types/oidc-provider": "9.11.1",
|
|
88
|
+
"@vitest/coverage-v8": "4.1.11",
|
|
89
|
+
"gpt-tokenizer": "4.0.0",
|
|
88
90
|
"tsup": "8.5.1",
|
|
89
|
-
"tsx": "4.
|
|
91
|
+
"tsx": "4.23.12",
|
|
90
92
|
"typescript": "6.0.3",
|
|
91
|
-
"vitest": "4.1.
|
|
93
|
+
"vitest": "4.1.11"
|
|
92
94
|
},
|
|
93
95
|
"dependencies": {
|
|
94
96
|
"@chainsafe/libp2p-noise": "17.0.0",
|
|
95
97
|
"@chainsafe/libp2p-yamux": "8.0.1",
|
|
96
98
|
"@grpc/grpc-js": "1.14.4",
|
|
97
99
|
"@grpc/proto-loader": "0.8.1",
|
|
98
|
-
"@hono/node-server": "2.
|
|
99
|
-
"@libp2p/
|
|
100
|
-
"@libp2p/
|
|
101
|
-
"@libp2p/
|
|
102
|
-
"@libp2p/
|
|
103
|
-
"@libp2p/
|
|
104
|
-
"@libp2p/
|
|
105
|
-
"@libp2p/
|
|
106
|
-
"@libp2p/
|
|
100
|
+
"@hono/node-server": "2.1.1",
|
|
101
|
+
"@libp2p/autonat": "^3.0.27",
|
|
102
|
+
"@libp2p/bootstrap": "12.0.30",
|
|
103
|
+
"@libp2p/circuit-relay-v2": "^4.2.12",
|
|
104
|
+
"@libp2p/crypto": "5.1.23",
|
|
105
|
+
"@libp2p/dcutr": "^3.0.27",
|
|
106
|
+
"@libp2p/identify": "4.1.13",
|
|
107
|
+
"@libp2p/kad-dht": "16.4.4",
|
|
108
|
+
"@libp2p/mdns": "^12.0.30",
|
|
109
|
+
"@libp2p/peer-id": "6.0.15",
|
|
110
|
+
"@libp2p/ping": "3.1.12",
|
|
111
|
+
"@libp2p/tcp": "11.0.27",
|
|
112
|
+
"@libp2p/websockets": "10.1.20",
|
|
107
113
|
"@multiformats/multiaddr": "13.0.3",
|
|
108
|
-
"
|
|
114
|
+
"@noble/post-quantum": "0.7.0",
|
|
115
|
+
"acorn": "8.18.0",
|
|
109
116
|
"acorn-walk": "8.3.5",
|
|
110
|
-
"hono": "4.
|
|
117
|
+
"hono": "4.13.5",
|
|
111
118
|
"it-pipe": "3.0.1",
|
|
112
|
-
"jose": "6.2.
|
|
113
|
-
"libp2p": "3.3.
|
|
119
|
+
"jose": "6.2.10",
|
|
120
|
+
"libp2p": "3.3.9",
|
|
114
121
|
"mlkem": "2.7.0",
|
|
115
|
-
"multiformats": "14.0.
|
|
116
|
-
"oidc-provider": "9.
|
|
117
|
-
"
|
|
122
|
+
"multiformats": "14.0.5",
|
|
123
|
+
"oidc-provider": "9.11.5",
|
|
124
|
+
"optional": "0.1.4",
|
|
125
|
+
"piscina": "5.3.1",
|
|
118
126
|
"uint8arrays": "6.1.1",
|
|
119
127
|
"zod": "4.4.3"
|
|
120
128
|
},
|
|
121
129
|
"optionalDependencies": {
|
|
122
|
-
"@modelcontextprotocol/sdk": "1.
|
|
123
|
-
"compromise": "14.
|
|
124
|
-
"gpt-tokenizer": "3.4.0"
|
|
130
|
+
"@modelcontextprotocol/sdk": "1.30.0",
|
|
131
|
+
"compromise": "14.16.0"
|
|
125
132
|
},
|
|
126
133
|
"peerDependencies": {
|
|
127
|
-
"@modelcontextprotocol/sdk": "1.
|
|
134
|
+
"@modelcontextprotocol/sdk": "1.30.0",
|
|
128
135
|
"@opentelemetry/api": "1.9.1"
|
|
129
136
|
},
|
|
130
137
|
"peerDependenciesMeta": {
|
|
@@ -137,7 +144,16 @@
|
|
|
137
144
|
},
|
|
138
145
|
"overrides": {
|
|
139
146
|
"content-type": "1.0.5",
|
|
140
|
-
"protobufjs": "7.
|
|
147
|
+
"protobufjs": "^7.6.1",
|
|
148
|
+
"piscina": "5.3.1",
|
|
149
|
+
"ws": "^8.21.0",
|
|
150
|
+
"hono": "4.13.5",
|
|
151
|
+
"fast-uri": "^3.1.5",
|
|
152
|
+
"brace-expansion": "^1.1.18",
|
|
153
|
+
"ip-address": "^10.3.1",
|
|
154
|
+
"js-yaml": "^4.3.1",
|
|
155
|
+
"nanoid": "^3.3.18",
|
|
156
|
+
"postcss": "^8.5.18",
|
|
141
157
|
"type-is": "2.0.1",
|
|
142
158
|
"uint8arrays": "6.1.1",
|
|
143
159
|
"aggregate-error": "npm:@socketregistry/aggregate-error@^1",
|
|
@@ -193,6 +209,10 @@
|
|
|
193
209
|
"demo:stop": "tsx tests/infra/cli/demo-stop.ts",
|
|
194
210
|
"demo:clean": "tsx tests/infra/cli/demo-clean.ts",
|
|
195
211
|
"demo:claude": "tsx tests/infra/cli/demo-claude.ts",
|
|
196
|
-
"demo:inspector": "tsx tests/infra/cli/demo-inspector.ts"
|
|
212
|
+
"demo:inspector": "tsx tests/infra/cli/demo-inspector.ts",
|
|
213
|
+
"demo:playground-web-build": "pnpm --filter playground-web build",
|
|
214
|
+
"demo:playground": "tsx tests/infra/cli/demo-playground.ts",
|
|
215
|
+
"demo:playground:rebuild": "tsx tests/infra/cli/demo-playground-rebuild.ts",
|
|
216
|
+
"demo:client-sdk": "tsx tests/infra/cli/demo-client.ts"
|
|
197
217
|
}
|
|
198
218
|
}
|