@nekzus/liop 1.0.0-alpha.1

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.
Files changed (87) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +24 -0
  3. package/README.md +641 -0
  4. package/dist/bin/agent.d.ts +1 -0
  5. package/dist/bin/agent.js +897 -0
  6. package/dist/bin/agent.js.map +1 -0
  7. package/dist/bridge.d.ts +105 -0
  8. package/dist/bridge.js +5 -0
  9. package/dist/bridge.js.map +1 -0
  10. package/dist/chunk-3L2O2XKG.js +723 -0
  11. package/dist/chunk-3L2O2XKG.js.map +1 -0
  12. package/dist/chunk-7BSCUYUE.js +421 -0
  13. package/dist/chunk-7BSCUYUE.js.map +1 -0
  14. package/dist/chunk-7PITYWOV.js +68 -0
  15. package/dist/chunk-7PITYWOV.js.map +1 -0
  16. package/dist/chunk-7RXOIDXP.js +877 -0
  17. package/dist/chunk-7RXOIDXP.js.map +1 -0
  18. package/dist/chunk-BOISQ45Z.js +558 -0
  19. package/dist/chunk-BOISQ45Z.js.map +1 -0
  20. package/dist/chunk-DZ2FQGJD.js +206712 -0
  21. package/dist/chunk-DZ2FQGJD.js.map +1 -0
  22. package/dist/chunk-EG46XMJT.js +77 -0
  23. package/dist/chunk-EG46XMJT.js.map +1 -0
  24. package/dist/chunk-ESRXG36Y.js +115 -0
  25. package/dist/chunk-ESRXG36Y.js.map +1 -0
  26. package/dist/chunk-FTF6AMF6.js +3 -0
  27. package/dist/chunk-FTF6AMF6.js.map +1 -0
  28. package/dist/chunk-HA6YZ42O.js +64 -0
  29. package/dist/chunk-HA6YZ42O.js.map +1 -0
  30. package/dist/chunk-HD2N3IJX.js +3634 -0
  31. package/dist/chunk-HD2N3IJX.js.map +1 -0
  32. package/dist/chunk-IK7CGWAZ.js +24 -0
  33. package/dist/chunk-IK7CGWAZ.js.map +1 -0
  34. package/dist/chunk-L6J72C5X.js +1477 -0
  35. package/dist/chunk-L6J72C5X.js.map +1 -0
  36. package/dist/chunk-PAICJCKJ.js +332 -0
  37. package/dist/chunk-PAICJCKJ.js.map +1 -0
  38. package/dist/chunk-PEN3KFLF.js +114 -0
  39. package/dist/chunk-PEN3KFLF.js.map +1 -0
  40. package/dist/chunk-T7R5HUFD.js +775 -0
  41. package/dist/chunk-T7R5HUFD.js.map +1 -0
  42. package/dist/chunk-TKRX6CFI.js +168 -0
  43. package/dist/chunk-TKRX6CFI.js.map +1 -0
  44. package/dist/chunk-UCVP3XAL.js +279 -0
  45. package/dist/chunk-UCVP3XAL.js.map +1 -0
  46. package/dist/chunk-VH4K4U45.js +180 -0
  47. package/dist/chunk-VH4K4U45.js.map +1 -0
  48. package/dist/chunk-Y62GORQF.js +51 -0
  49. package/dist/chunk-Y62GORQF.js.map +1 -0
  50. package/dist/chunk-ZP3VVXOI.js +66 -0
  51. package/dist/chunk-ZP3VVXOI.js.map +1 -0
  52. package/dist/client.d.ts +7 -0
  53. package/dist/client.js +13 -0
  54. package/dist/client.js.map +1 -0
  55. package/dist/gateway.d.ts +7 -0
  56. package/dist/gateway.js +13 -0
  57. package/dist/gateway.js.map +1 -0
  58. package/dist/hybrid-CrKB50nh.d.ts +170 -0
  59. package/dist/index-CX43dvMs.d.ts +170 -0
  60. package/dist/index-DoW2gzBZ.d.ts +566 -0
  61. package/dist/index.d.ts +810 -0
  62. package/dist/index.js +357 -0
  63. package/dist/index.js.map +1 -0
  64. package/dist/kyber-CGOA7Q6A.js +3 -0
  65. package/dist/kyber-CGOA7Q6A.js.map +1 -0
  66. package/dist/mesh.d.ts +32 -0
  67. package/dist/mesh.js +6 -0
  68. package/dist/mesh.js.map +1 -0
  69. package/dist/node-B0b2vUFS.d.ts +164 -0
  70. package/dist/protocol/liop_core.proto +47 -0
  71. package/dist/server.d.ts +5 -0
  72. package/dist/server.js +9 -0
  73. package/dist/server.js.map +1 -0
  74. package/dist/types-lJIxBlWF.d.ts +256 -0
  75. package/dist/types.d.ts +3 -0
  76. package/dist/types.js +3 -0
  77. package/dist/types.js.map +1 -0
  78. package/dist/verifier-COnid_dg.d.ts +31 -0
  79. package/dist/verifier-HRFXBKT5.js +6 -0
  80. package/dist/verifier-HRFXBKT5.js.map +1 -0
  81. package/dist/workers/logic-execution.d.ts +26 -0
  82. package/dist/workers/logic-execution.js +272 -0
  83. package/dist/workers/logic-execution.js.map +1 -0
  84. package/dist/workers/zk-verifier.d.ts +26 -0
  85. package/dist/workers/zk-verifier.js +174 -0
  86. package/dist/workers/zk-verifier.js.map +1 -0
  87. package/package.json +230 -0
package/README.md ADDED
@@ -0,0 +1,641 @@
1
+ <div align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://res.cloudinary.com/dsvsl0b0b/image/upload/v1774702621/Neural-Mesh-Protocol/qaqsa28yrtpnxnbclv3p.svg?v=20260328">
4
+ <img alt="Logic-Injection-on-Origin Protocol Logo" src="https://res.cloudinary.com/dsvsl0b0b/image/upload/v1774702621/Neural-Mesh-Protocol/hoanw0m6tybpz5fbl12n.svg?v=20260328" width="700">
5
+ </picture>
6
+
7
+ <h1>Logic-Injection-on-Origin Protocol (LIOP) — TypeScript SDK</h1>
8
+ <p align="center">
9
+ <a href="https://github.com/Nekzus/LIOP/actions/workflows/ci.yml"><img src="https://github.com/Nekzus/LIOP/actions/workflows/ci.yml/badge.svg?event=push" alt="Github Workflow"></a>
10
+ <a href="https://www.npmjs.com/package/@nekzus/liop"><img src="https://img.shields.io/npm/v/@nekzus/liop.svg" alt="npm version"></a>
11
+ <a href="https://www.npmjs.com/package/@nekzus/liop"><img src="https://img.shields.io/npm/dm/@nekzus/liop.svg" alt="npm-month"></a>
12
+ <a href="https://www.npmjs.com/package/@nekzus/liop"><img src="https://img.shields.io/npm/dt/@nekzus/liop.svg?style=flat" alt="npm-total"></a>
13
+ <a href="https://github.com/Nekzus/LIOP/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Nekzus/LIOP.svg" alt="License"></a>
14
+ <a href="https://nekzus-32.mintlify.app/"><img src="https://img.shields.io/badge/docs-mintlify-0D9373?style=flat" alt="Docs"></a>
15
+ <a href="https://deepwiki.com/Nekzus/LIOP"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"></a>
16
+ <a href="https://paypal.me/maseortega"><img src="https://img.shields.io/badge/donate-paypal-blue.svg?style=flat-square" alt="Donate"></a>
17
+ </p>
18
+
19
+ <p><strong>The official TypeScript SDK for the Logic-Injection-on-Origin Protocol.</strong></p>
20
+ <p>Deploy Logic-on-Origin with WebAssembly sandboxing, gRPC-speed execution, and full MCP backward compatibility.</p>
21
+ </div>
22
+
23
+ ---
24
+
25
+ ## Overview
26
+
27
+ `@nekzus/liop` is an SDK that implements the **Logic-Injection-on-Origin (LIO)** paradigm: instead of extracting raw data from a server and sending it to an LLM, the LLM injects a micro-module of logic to be executed *at the data source*, inside a secure sandbox. The result — never the raw data — is returned.
28
+
29
+ This addresses the data privacy, bandwidth, and latency bottlenecks of distributed agent data analysis.
30
+
31
+ ### Key Capabilities
32
+
33
+ | Feature | Description |
34
+ | :---------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |
35
+ | **Logic-Injection-on-Origin** | LLMs send code, not queries. Data never leaves the origin server. |
36
+ | **Dual-Era MCP Compliance** | Dual-era compatibility supporting modern stateless MCP v2 (2026-07-28) and legacy MCP (2025-11-25) clients (Claude Desktop, Cursor). |
37
+ | **Token Economy Engine** | Inlined BPE `o200k_base` tokenizer with zero runtime dependencies (16.5MB footprint reduction) and OpenTelemetry `gen_ai.*` bridge. |
38
+ | **Interactive Playground UI** | Real-time Web UI (`:16000` prod / `:14000` dev) with 4-tab modular architecture (`Output`, `Debug`, `Telemetry`, `Export`), code generation (TS/cURL/Python), and dual OLED/Slate themes. |
39
+ | **Multi-Tier Sovereign Enclaves** | Physical socket isolation via `@libp2p/pnet` (256-bit Swarm Key PSK) and Border LIO Gateway (`blg`) with OAuth 2.1 authentication. |
40
+ | **AST Fuel Metering** | Deterministic AST instruction fuel scoring with 100-bucket quantization for NIST SP 800-53 timing side-channel elimination (`stddev = 0`).|
41
+ | **Differential Privacy Engine** | NIST SP 800-226 Laplace mechanism with CSPRNG entropy, query-aware sensitivity, and deterministic ZK-Receipt auditing (`DpEngine`). |
42
+ | **MCP Drop-in Replacement** | `LiopServer` mirrors the Anthropic MCP `Server` API — tools, resources, and prompts with `Zod` schemas. |
43
+ | **Guardian AST** | Pre-execution heuristic inspection blocks sandbox escapes (`require`, `fs`, `eval`, `fetch`, prototype pollution). |
44
+ | **IFC Taint Analyzer** | 5-pass Acorn AST information flow control tracking collection aliases, correlation guards, and extrema gates at preflight. |
45
+ | **WASI Sandbox** | JavaScript payloads execute inside V8 isolates with CPU fuel limits, no Node.js globals, and safe environment isolation (`allowEnv`). |
46
+ | **Adaptive Network Discovery**| Single-URL RFC 9728 Protected Resource Metadata probe and adaptive execution mode resolution (`TopologyProbe`). |
47
+ | **Resilient Hybrid Routing** | Deterministic per-tool multiplexing across `http-gateway`, `p2p-grpc`, and `local` with 5-failure circuit breaker (`RoutingTable`).|
48
+ | **OAuth 2.1 M2M Lifecycle** | Concurrency in-flight de-duplication, 30-second preemptive refresh buffer, and reactive invalidation (`TokenManager`). |
49
+ | **Sliding-Window Rate Limiter**| In-memory OWASP API4:2023 rate limiting with background cleanup unreferenced intervals (`InMemoryRateLimiter`). |
50
+ | **PII Shield** | Multi-layer egress filter with Regional Presets, custom keys, and recursive floats sanitization (`sanitizeOutput`). |
51
+ | **ZK-Receipts** | Cryptographic proof with `output_hash` cross-verification (Replay Mitigation) and balanced-brace proxy extraction. |
52
+ | **Worker Pool** | Heavy computation (crypto, sandboxing) dispatched to OS threads via `piscina` with background async warmup. |
53
+ | **Post-Quantum Ready** | ML-KEM-768 (Kyber) + ML-DSA-65 (Dilithium) with 1-hour session lifetime and AES-256-GCM encryption. |
54
+ | **Enterprise Observability** | Immutable SOC 2 Hash-Chain audit log (`AuditLogger`), physical wire egress tracking, Prometheus metrics (`/metrics`), and K8s probes. |
55
+ | **P2P Mesh** | Kademlia DHT discovery via `libp2p` with TCP + WebSocket + Yamux multiplexing and Noise encryption. |
56
+
57
+ ---
58
+
59
+ ## Installation
60
+
61
+ ```bash
62
+ npm install @nekzus/liop@latest
63
+ ```
64
+
65
+ Or for the latest stable zero-trust features on the beta channel:
66
+
67
+ ```bash
68
+ npm install @nekzus/liop@beta
69
+ ```
70
+
71
+ > **Requirements:** Node.js ≥ 20.0. The SDK uses `node:crypto`, `node:vm`, and `piscina` (worker threads) internally.
72
+
73
+ ### Zero-Bloat & Micro-Deployments (Opt-Out)
74
+
75
+ By default, the SDK provides backward compatibility with MCP (`LiopMcpBridge`) by declaring `@modelcontextprotocol/sdk` as an optional dependency (which is automatically resolved by standard installations of NPM, PNPM, or Yarn).
76
+
77
+ For constrained production environments (e.g., Docker, AWS Lambda, Edge/IoT) where every megabyte counts, you can perform a **pure, zero-bloat LIOP installation** by opting out of the optional dependencies:
78
+
79
+ ```bash
80
+ # npm
81
+ npm install @nekzus/liop@latest --no-optional
82
+
83
+ # pnpm
84
+ pnpm add @nekzus/liop@latest --without optional
85
+
86
+ # yarn
87
+ yarn add @nekzus/liop@latest --ignore-optional
88
+ ```
89
+
90
+ The SDK uses dynamic `import()` statements under the hood to ensure that MCP translator modules are only loaded if they are actually instantiated, guaranteeing a lightweight memory footprint.
91
+
92
+ ---
93
+
94
+ ## LIOP Agent (CLI)
95
+
96
+ The SDK includes a zero-config agent CLI (`liop`) designed to bridge the Logic-Injection-on-Origin Protocol with local AI clients like **Claude Desktop**.
97
+
98
+ ### Installation & Run
99
+
100
+ You can run the agent directly using `npx` (recommended) or install it globally:
101
+
102
+ ```bash
103
+ # Run instantly
104
+ npx @nekzus/liop@latest
105
+
106
+ # Or install globally
107
+ npm install -g @nekzus/liop@latest
108
+ liop
109
+ ```
110
+
111
+ ### 🤖 Claude Desktop Configuration
112
+
113
+ To integrate LIOP into Claude Desktop, update your `claude_desktop_config.json` (typically found in `%APPDATA%\Claude\claude_desktop_config.json` on Windows):
114
+
115
+ ```json
116
+ {
117
+ "mcpServers": {
118
+ "liop": {
119
+ "command": "npx",
120
+ "args": ["-y", "@nekzus/liop@latest"],
121
+ "env": {
122
+ "LIOP_NEXUS_URL": "http://your-nexus-host:3000",
123
+ "LIOP_LOG_LEVEL": "info",
124
+ "LIOP_TOKEN_BANK": "your-secure-bank-token",
125
+ "LIOP_TOKEN_VAULT": "your-secure-vault-token",
126
+ "NODE_OPTIONS": "--use-system-ca"
127
+ }
128
+ }
129
+ }
130
+ }
131
+ ```
132
+
133
+ ### Persistence & Identity
134
+
135
+ The agent automatically manages your P2P identity:
136
+
137
+ - **Identity Path**: `~/.liop/identity.json`. This file contains your unique PeerID. Keep it safe if you want to maintain a consistent identity in the mesh.
138
+ - **Bootstrap Nodes**: By default, the agent connects to the **LIOP Alpha Nexus**. You can provide custom bootstrap addresses as CLI arguments:
139
+ ```bash
140
+ npx @nekzus/liop@latest /ip4/1.2.3.4/tcp/4001/p2p/PEER_ID
141
+ ```
142
+
143
+ ---
144
+
145
+ ## Quick Start
146
+
147
+ ### 1. Create a Server
148
+
149
+ ```typescript
150
+ import { LiopServer, PII_PATTERNS } from "@nekzus/liop/server";
151
+ import { z } from "zod";
152
+
153
+ const server = new LiopServer(
154
+ { name: "MyDataNode", version: "1.0.0" },
155
+ {
156
+ capabilities: { tools: { listChanged: true } },
157
+ security: {
158
+ // Built-in PII detection (Email, Credit Card, IP, Phone)
159
+ piiPatterns: [PII_PATTERNS.EMAIL, PII_PATTERNS.CREDIT_CARD],
160
+ // Keys that will be stripped from any outgoing response
161
+ forbiddenKeys: ["id", "ssn", "password", "email", "name"],
162
+ },
163
+ }
164
+ );
165
+ ```
166
+
167
+ ### 2. Register a Tool
168
+
169
+ ```typescript
170
+ server.tool(
171
+ "analyze_logs",
172
+ "Analyzes local log files without sending raw data to the LLM.",
173
+ { target_error: z.string().describe("The error pattern to search for") },
174
+ async ({ target_error }) => {
175
+ // This logic runs at origin — data never leaves the server
176
+ return {
177
+ content: [{ type: "text", text: `Found 51 occurrences of ${target_error}` }],
178
+ };
179
+ }
180
+ );
181
+ ```
182
+
183
+ ### 3. Connect to Claude Desktop / Cursor (MCP Bridge)
184
+
185
+ ```typescript
186
+ import { LiopMcpBridge } from "@nekzus/liop/bridge";
187
+
188
+ const bridge = new LiopMcpBridge(server);
189
+ await bridge.connect(); // Listens on stdio (JSON-RPC 2.0)
190
+ ```
191
+
192
+ **Claude Desktop config** (`claude_desktop_config.json`):
193
+
194
+ ```json
195
+ {
196
+ "mcpServers": {
197
+ "my-data-node": {
198
+ "command": "npx",
199
+ "args": ["tsx", "src/server.ts"]
200
+ }
201
+ }
202
+ }
203
+ ```
204
+
205
+ ---
206
+
207
+ ## Module Exports
208
+
209
+ The package exposes targeted entry points to minimize bundle size:
210
+
211
+ ```typescript
212
+ import { LiopServer, PII_PATTERNS } from "@nekzus/liop/server";
213
+ import { LiopMcpBridge } from "@nekzus/liop/bridge";
214
+ import { LiopClient } from "@nekzus/liop/client";
215
+ import type { Tool, Resource, Prompt, CallToolRequest, CallToolResult } from "@nekzus/liop/types";
216
+ ```
217
+
218
+ ---
219
+
220
+ ## API Reference
221
+
222
+ ### `LiopServer`
223
+
224
+ The core class for declaring data nodes. API-compatible with Anthropic's MCP `Server`.
225
+
226
+ #### Constructor
227
+
228
+ ```typescript
229
+ new LiopServer(
230
+ serverInfo: { name: string; version: string },
231
+ config?: {
232
+ capabilities?: Record<string, unknown>;
233
+ workerPool?: {
234
+ enabled?: boolean; // Enable OS-thread sandboxing (default: true)
235
+ minThreads?: number; // Min worker threads (default: CPU count based)
236
+ maxThreads?: number; // Max worker threads (default: CPU count)
237
+ idleTimeout?: number; // Idle timeout in milliseconds for workers
238
+ maxHeapMb?: number; // V8 heap limit per worker (default: 64, env: LIOP_WORKER_MAX_HEAP_MB)
239
+ };
240
+ security?: {
241
+ piiPatterns?: PiiRule[]; // Regex/validator rules for PII detection
242
+ forbiddenKeys?: string[]; // Keys stripped from outgoing responses
243
+ sensitiveKeys?: string[]; // Keys that trigger sensitive query budget
244
+ enableNerScanning?: boolean; // NLP entity detection via compromise (default: false)
245
+ rateLimit?: { // Sliding window rate limiter configuration
246
+ maxPerWindow?: number; // Max calls per window per tool (default: 15)
247
+ globalMaxPerWindow?: number; // Max total calls across all tools (default: 40)
248
+ windowMs?: number; // Window duration in ms (default: 60000)
249
+ };
250
+ };
251
+ taxonomy?: { // Data domain classification
252
+ domain?: string; // e.g., "finance", "healthcare"
253
+ clearanceTier?: number; // e.g., 3, 5 (strictly numeric)
254
+ executionTypes?: string[]; // e.g., ["aggregation", "analytics"]
255
+ };
256
+ auth?: LiopAuthConfig; // OAuth 2.1 Hybrid authentication config
257
+ tokenSlug?: string; // Deterministic token resolution slug (e.g., "BANK", "VAULT")
258
+ allowEnv?: boolean; // Enable safe host environment propagation (default: false)
259
+ budgetStorePath?: string; // Path to a shared JSON file for persistent Query Budget tracking
260
+ }
261
+ )
262
+ ```
263
+
264
+ #### Methods
265
+
266
+ | Method | Signature | Description |
267
+ | :--------------------------- | :------------------------------------------------- | :---------------------------------------------------------------------------------- |
268
+ | `tool()` | `(name, description, shape, handler, policy?)` | Registers a callable tool with Zod input validation and logic execution policies. |
269
+ | `prompt()` | `(name, description, args, handler)` | Registers a dynamic prompt template. |
270
+ | `resource()` | `(name, uri, description?, mimeType?, content?)` | Registers a readable resource. |
271
+ | `dataDictionary()` | `(schema, name?, uri?, description?)` | Broadcasts a data schema so LLMs can write accurate Logic-Injection-on-Origin code. |
272
+ | `setSandboxData()` | `(records: Record[])` | Injects data into the sandbox as `env.records` for Logic-on-Origin tools. |
273
+ | `enableZeroShotAutonomy()` | `()` | Registers the "Blind Analyst" prompt for autonomous code generation. |
274
+ | `callTool()` | `(request: CallToolRequest)` | Invokes a registered tool (used locally or via MCP Bridge). |
275
+ | `listTools()` | `()` | Returns all registered tools. |
276
+ | `listPrompts()` | `()` | Returns all registered prompts. |
277
+ | `getPrompt()` | `(request: GetPromptRequest)` | Returns a specific prompt by name. |
278
+ | `listResources()` | `()` | Returns all registered resources. |
279
+ | `readResource()` | `(uri: string)` | Reads a resource by URI. |
280
+ | `getServerInfo()` | `()` | Returns the server's name and version. |
281
+ | `connectToMesh()` | `()` | Connects to the libp2p Kademlia DHT. |
282
+ | `clearAstCache()` | `()` | Invalidates the Guardian AST logic cache. |
283
+ | `close()` | `()` | Destroys the worker pool and releases threads. |
284
+
285
+ #### LogicExecutionPolicy Options
286
+
287
+ When registering a tool via `server.tool()`, you can optionally pass a `policy` object to configure security and privacy guards for that specific tool:
288
+
289
+ ```typescript
290
+ interface LogicExecutionPolicy {
291
+ outputSchema?: z.ZodType<unknown>; // Validate returned business payload (strict by default)
292
+ enforceAggregationFirst?: boolean | AggregationPolicy; // Block row-level exports & enforce K-Anonymity
293
+ preflightDenyPatterns?: RegExp[]; // Custom regex patterns blocked in static analysis
294
+ dpEpsilon?: number; // Laplace Differential Privacy epsilon (default: 1.0)
295
+ dpSensitivity?: number; // Maximum change per single record (default: 1.0)
296
+ dpSmallDatasetThreshold?: number; // Size threshold below which DP is active (default: 50)
297
+ queryBudgetPerField?: number; // Uniform session query limit per field (legacy compatibility)
298
+ sensitiveKeys?: string[]; // Tool-level fields under the 8-query sensitive budget tier
299
+ budgetStorePath?: string; // Shared path for persistent and concurrent query budgets
300
+ }
301
+ ```
302
+
303
+ ### `LiopMcpBridge`
304
+
305
+ Adapter that connects any `LiopServer` to MCP-compatible clients via JSON-RPC 2.0 over stdio.
306
+
307
+ ```typescript
308
+ const bridge = new LiopMcpBridge(server);
309
+ await bridge.connect();
310
+ ```
311
+
312
+ **Supported JSON-RPC methods:**
313
+
314
+ - `initialize` — Returns server capabilities and info
315
+ - `tools/list` — Lists available tools
316
+ - `tools/call` — Calls a tool (with ZK-Receipt verification)
317
+ - `resources/list` — Lists available resources
318
+ - `resources/read` — Reads a resource
319
+ - `prompts/list` — Lists available prompts
320
+ - `prompts/get` — Gets a specific prompt
321
+
322
+ ---
323
+
324
+ ## Security Architecture
325
+
326
+ ### Defense-in-Depth Architecture
327
+
328
+ ```
329
+ ┌───────────────────────────────────────────────────────────┐
330
+ │ Layer 1: Guardian AST (Pre-Execution Static Analysis) │
331
+ │ 14-function WASI allowlist • 128 import cap • Blocks │
332
+ │ require, import(), fs, eval, fetch, __proto__ │
333
+ ├───────────────────────────────────────────────────────────┐
334
+ │ Layer 2: WASI Sandbox (V8 Isolate) │
335
+ │ 25 poisoned globals (incl. Date, TypedArrays) • │
336
+ │ CPU Fuel limits • 5s timeout • maxHeapMb (64MB default) │
337
+ │ Object.freeze() on 11 core prototypes • allowEnv allowlist │
338
+ ├───────────────────────────────────────────────────────────┤
339
+ │ Layer 3: Taint Analyzer (IFC — Static) │
340
+ │ Acorn AST 3-pass analysis blocks PII side-channels: │
341
+ │ charCodeAt, boolean inference, arithmetic derivation │
342
+ ├───────────────────────────────────────────────────────────┤
343
+ │ Layer 4: PII Shield (Egress Filter) │
344
+ │ 4-stage pipeline: exact key → fuzzy key → pattern │
345
+ │ validators (Luhn, IBAN Mod-97) → NER (compromise) • │
346
+ │ Recursive In-Memory Numerical Sanitization (4 decimals) │
347
+ ├───────────────────────────────────────────────────────────┤
348
+ │ Layer 5: Aggregation-First Policy │
349
+ │ Blocks raw row export • maxOutputRows (default: 10) • │
350
+ │ Conditional error: detailed (dev) vs opaque (production) │
351
+ ├───────────────────────────────────────────────────────────┤
352
+ │ Layer 6: ZK-Receipt (Integrity & Replay Mitigation) │
353
+ │ SHA-256 ImageID + HMAC-SHA256 Seal (Kyber768-derived) • │
354
+ │ output_hash cross-verification • Balanced-brace extractor │
355
+ └───────────────────────────────────────────────────────────┘
356
+ ```
357
+
358
+ ### PII Patterns
359
+
360
+ Built-in patterns with multi-layer verification:
361
+
362
+ ```typescript
363
+ import { PII_PATTERNS, PII_PRESETS } from "@nekzus/liop/server";
364
+
365
+ // Available patterns:
366
+ PII_PATTERNS.EMAIL // RFC 5322 compliant, excludes @example.com/@test.com
367
+ PII_PATTERNS.CREDIT_CARD // Visa/MC/Amex + Luhn algorithm validation
368
+ PII_PATTERNS.IP_ADDRESS // IPv4 with octet range validation (excludes localhost)
369
+ PII_PATTERNS.PHONE // International phone formats with digit-length validation
370
+ PII_PATTERNS.SSN // USA Social Security Number rules (blocks 000 segments)
371
+ PII_PATTERNS.IBAN // ISO 7064 Modulo 97-10 algorithm precision via BigInt
372
+ PII_PATTERNS.PASSPORT_MRZ // Strict 44-character TD3 international passport MRZ string
373
+
374
+ // Pre-built Regional Presets ready to drop-in via LiopServer(options):
375
+ PII_PRESETS.GLOBAL_STRICT
376
+ PII_PRESETS.US_COMPLIANT
377
+ PII_PRESETS.EU_GDPR
378
+ ```
379
+
380
+ ### Forbidden Keys
381
+
382
+ The PII Shield automatically strips any key from outgoing responses that matches your configured list:
383
+
384
+ ```typescript
385
+ const server = new LiopServer(info, {
386
+ security: {
387
+ forbiddenKeys: ["id", "ssn", "password", "token", "secret", "email", "name"],
388
+ },
389
+ });
390
+ // Any response containing these keys → instantly blocked with "Egress Security Violation"
391
+ ```
392
+
393
+ ### Envelope & Cryptographic Unwrapping
394
+
395
+ To avoid false positive triggers caused by HMAC-SHA256 ZK-Receipt signatures or transport wrapper frames (such as `{ content: [{ type: "text", text: "..." }] }`), the PII Shield and Aggregation-First engines scan only the unwrapped business data (via `unwrapForAggregationPolicyScan`). Cryptographic seals and protocol routing structures are isolated and excluded from compliance scans.
396
+
397
+ ### 📊 3-Tier Query Budget (NIST SP 800-226)
398
+
399
+ To prevent advanced statistical differentiation or database reconstruction attacks, the SDK implements a tiered, session-based budget engine:
400
+
401
+ - **Forbidden Tier** (Limit: `3` queries/session): Applied to highly restricted variables like user IDs, passwords, emails, SSNs (configured via `forbiddenKeys`).
402
+ - **Sensitive Tier** (Limit: `8` queries/session): Applied to moderately sensitive variables like account types, medical diagnoses, blood types, financial tickers (configured via `sensitiveKeys`).
403
+ - **Public Tier** (Limit: `25` queries/session): Default budget for non-sensitive public metadata.
404
+
405
+ If an injected payload queries a field beyond its budget limit, the preflight static analysis immediately blocks execution.
406
+
407
+ ### 🛡️ K-Anonymity on Small Datasets
408
+
409
+ When operating on high-privacy datasets, if the source records count is **less than 10**, the SDK forces a strict K-Anonymity restriction:
410
+ - Rejects any output that contains nested objects or arrays.
411
+ - Restricts the returned structure to a maximum of **3 scalar keys** (e.g., simple aggregate counts or statistics).
412
+ - Prevents structural data leakage in low-entropy datasets.
413
+
414
+ ### ❄️ Sandbox Poisoned Globals & Date Workaround
415
+
416
+ For maximum host security, the WASI sandbox enforces a poisoned environment that strips dangerous globals and prevents timing side-channels:
417
+ - **Poisoned/Disabled**: `Date` (Date.now, parse, etc. throw an exception to prevent timing analysis), `eval`, `Function`, `setTimeout`, `setInterval`, `Buffer`, `ArrayBuffer`, and all `TypedArrays`.
418
+ - **Date Workaround**: To perform date checks, use lexicographical string comparison on ISO 8601 strings (e.g., `record.date >= "2026-01-01"`).
419
+
420
+ ### 🧹 Recursive In-Memory Numerical Sanitization
421
+
422
+ To mitigate timing channels, statistical differentiation, and floats side-channels, the SDK executes a recursive sanitization pipeline before the PII scanner runs:
423
+ - Positive floating-point numbers are recursively rounded to exactly **4 decimal places**.
424
+ - Negative values are safely clamped to **0** (via `sanitizeOutput()`).
425
+ - This operation runs entirely in-memory and recursively on all fields, preserving data structure immutability without expensive and fragile serialization-deserialization cycles.
426
+
427
+ ### 🌐 Environment Isolation & allowEnv Allowlist
428
+
429
+ For robust sandboxing, the WASI execution path isolates host environment variables. Propagation can be enabled explicitly:
430
+ ```typescript
431
+ const server = new LiopServer(info, {
432
+ allowEnv: true
433
+ });
434
+ ```
435
+ To block arbitrary command execution (e.g., Shellshock) and prevent exposure of host credentials, the SDK filters environment variables through a **strict system allowlist** (`getDefaultEnvironment()`):
436
+ - **Windows Allowlist**: `APPDATA`, `HOMEDRIVE`, `HOMEPATH`, `LOCALAPPDATA`, `PATH`, `PROCESSOR_ARCHITECTURE`, `SYSTEMDRIVE`, `SYSTEMROOT`, `TEMP`, `USERNAME`, `USERPROFILE`, `PROGRAMFILES`.
437
+ - **Unix/Linux Allowlist**: `HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM`, `USER`.
438
+ Variables starting with shell functions `()` are dropped.
439
+
440
+ ### 🔒 ZK-Receipt Replay & Tampering Mitigation
441
+
442
+ LIOP ZK-Receipts provide cryptographic evidence that a computation was executed honestly under zero-trust bounds. To defeat **Man-in-the-Middle (MITM) reply tampering and replay attacks** (re-using old signatures on new query data):
443
+ - The verification pipeline computes the SHA-256 hash of the received business output (`expectedOutput`) and strictly asserts its equivalence with `Journal.output_hash` signed inside the ZK-Receipt (via `verifyZkReceipt`).
444
+ - **Balanced-Brace Proxy Extractor**: If the tool call was delegated to a proxied tool (`__liop_proxy_tool`), the verifier invokes an in-process balanced-brace state machine to safely isolate proxy arguments from the response metadata, preventing false validation failures.
445
+
446
+ ---
447
+
448
+ ## Logic-Injection-on-Origin Flow
449
+
450
+ The following shows a complete Logic-Injection-on-Origin execution cycle (handled internally by the SDK):
451
+
452
+ ```
453
+ 1. LLM generates JavaScript analysis code wrapped in @LIOP / @END boundaries
454
+ 2. LiopServer receives the payload via tools/call (JSON-RPC or direct)
455
+ 3. Guardian AST inspects for sandbox escapes (pre-execution heuristic analysis)
456
+ 4. Code executes inside a V8 isolate with CPU fuel limits (no Node.js globals)
457
+ 5. Taint Analyzer blocks PII side-channel derivation (charCodeAt, boolean inference)
458
+ 6. PII Shield scans output for forbidden data and keys
459
+ 7. ZK-Receipt generated (SHA-256 ImageID + HMAC-SHA256 seal)
460
+ 8. Result + receipt returned to the LLM (raw data never exposed)
461
+ ```
462
+
463
+ ### Data Dictionary & Zero-Shot Autonomy
464
+
465
+ The Data Dictionary tells the LLM exactly what fields exist in `env.records`, enabling accurate code generation without seeing the actual data:
466
+
467
+ ```typescript
468
+ server.dataDictionary({
469
+ id: "string (Anonymized patient identifier, strictly PII)",
470
+ age: "number (Patient age in years)",
471
+ condition: "string (Healthy, Hypertension, Diabetes Type 1, Diabetes Type 2, Heart Disease, Asthma)",
472
+ riskScore: "number (Float 0.0 to 1.0)",
473
+ lastVisit: "string (ISO 8601 date)",
474
+ });
475
+
476
+ server.enableZeroShotAutonomy(); // Registers the "Blind Analyst" prompt
477
+ ```
478
+
479
+ ---
480
+
481
+ ## Worker Pool (Multi-Core Scaling)
482
+
483
+ Node.js is single-threaded. Heavy operations like Kyber768 decryption, AES-GCM authentication, AST validation, and V8 sandbox instantiation would block the event loop in a standard setup.
484
+
485
+ This SDK dispatches all heavy computation to OS-level threads via [`piscina`](https://github.com/piscinajs/piscina), achieving Rust-like concurrency. On server or verifier initialization, background warmup tasks are automatically dispatched to pre-warm the pool workers, eliminating V8/WASI cold-start overhead (~820k fuel units) for subsequent calls:
486
+
487
+ ```typescript
488
+ // Automatic — no configuration needed
489
+ // When a Logic-Injection-on-Origin payload is received:
490
+ // 1. Main thread receives JSON-RPC request
491
+ // 2. Worker thread: AST inspection + PQC decryption + Sandbox execution
492
+ // 3. Main thread: Returns result (non-blocking)
493
+
494
+ // Cleanup on shutdown:
495
+ await server.close();
496
+ ```
497
+
498
+ ---
499
+
500
+ ## Post-Quantum Cryptography
501
+
502
+ Transport-layer security using ML-KEM-768 (Kyber) for key encapsulation and AES-256-GCM for symmetric encryption:
503
+
504
+ ```typescript
505
+ import { LiopClient } from "@nekzus/liop/client";
506
+
507
+ const client = new LiopClient();
508
+ await client.connect();
509
+
510
+ // Discover remote tools via Kademlia DHT
511
+ const tools = await client.discoverTools();
512
+
513
+ // Call a tool with PQC-encrypted WASM payload
514
+ // Kyber768 key encapsulation + AES-256-GCM happens automatically
515
+ const result = await client.callTool(request, wasmPayload, serverPublicKey);
516
+
517
+ // Verify the ZK-Receipt from the remote server
518
+ const isValid = await client.verifyZkReceipt(payload, imageId, receipt);
519
+ ```
520
+
521
+ ---
522
+
523
+ ## P2P Mesh Network
524
+
525
+ Decentralized tool discovery via Kademlia DHT:
526
+
527
+ ```typescript
528
+ await server.connectToMesh();
529
+ // Server is now discoverable on the libp2p network
530
+ // Transports: TCP + WebSocket
531
+ // Multiplexing: Yamux
532
+ // Encryption: Noise Protocol
533
+ ```
534
+
535
+ ---
536
+
537
+ ---
538
+
539
+ ## Interactive Web Playground (`:16000` prod / `:14000` dev)
540
+
541
+ The SDK includes a real-time developer interface to test Logic-Injection-on-Origin, trace post-quantum handshakes, evaluate AST fuel consumption, and inspect cryptographic proofs:
542
+
543
+ ```bash
544
+ # 1. Launch the full 8-node production audit mesh with traffic shaping (http://localhost:16000)
545
+ pnpm run audit:prod:start
546
+
547
+ # Run the 10-suite automated production audit against the mesh
548
+ pnpm run audit:prod:run
549
+
550
+ # Teardown and cleanup production containers
551
+ pnpm run audit:prod:clean
552
+
553
+ # 2. Alternatively, launch the lightweight 5-node demo (http://localhost:14000)
554
+ pnpm run demo:start
555
+ ```
556
+
557
+ Navigate to **`http://localhost:16000`** in your browser:
558
+
559
+ * **Live 7-Phase Streaming:** Visualizes Bootstrap, DHT Discovery, ML-KEM-768 Handshake, AES-256-GCM Sealing, WASI Sandbox Execution, ZK-Receipt Verification, and Output Aggregation via real-time Server-Sent Events (SSE).
560
+ * **Tri-Tab Results Panel:** Switch between `Aggregated Output` (sanitized JSON), `Fuel & Telemetry` (WASI fuel metering, token economy comparison banner), and `Crypto Proofs` (ImageID, Dataset Hash, and HMAC-SHA256 signature with instant copy).
561
+ * **Token Economy Dashboard:** Live comparison showing **98.9% – 99.6% token reduction** and **99.6% network bandwidth savings** over traditional MCP context-pulling.
562
+ * **REST Telemetry Endpoint:** Query session analytics programmatically at `GET http://localhost:16000/api/telemetry`.
563
+ * **Built-in Scenario Presets:** Ready-to-run micro-modules for High-Frequency Trading (HFT Level 2 order books), Banking transaction analysis, Medical Vault HIPAA records, and Edge IoT industrial sensor telemetry.
564
+ * **Dual Dark Modes:** Toggle between Obsidian OLED (`#000000`) and Slate Navy (`#0f172a`) interfaces.
565
+
566
+ ---
567
+
568
+ ## Token Economy & Telemetry
569
+
570
+ The SDK ships with a zero-runtime-dependency **`o200k_base`** BPE token estimation and telemetry engine:
571
+
572
+ ```typescript
573
+ import {
574
+ createTokenEstimator,
575
+ createSyncTokenEstimator,
576
+ TokenTelemetryEngine,
577
+ LiopOTelBridge
578
+ } from "@nekzus/liop";
579
+
580
+ // 1. Exact BPE Token Counting (Bundled inlined o200k_base vocab, zero network/disk lag)
581
+ const estimator = createSyncTokenEstimator();
582
+ const tokens = estimator.countTokens("Hello world! Logic-Injection-on-Origin"); // 12
583
+
584
+ // 2. Operation-Level Token Telemetry
585
+ const telemetry = TokenTelemetryEngine.getInstance();
586
+ telemetry.record({
587
+ type: "tool_call",
588
+ method: "tools/call",
589
+ toolName: "Analyze_HFT_Market_Data",
590
+ estimatedInputTokens: 120,
591
+ estimatedOutputTokens: 42
592
+ });
593
+
594
+ // 3. OpenTelemetry gen_ai.* Bridge
595
+ // Automatically exports gen_ai.client.token.usage and gen_ai.client.operation.duration histograms
596
+ ```
597
+
598
+ ---
599
+
600
+ ## Testing & Quality
601
+
602
+ This package is continuously tested across multiple platforms and Node.js versions via CI/CD:
603
+
604
+ - **490+ tests** spanning unit, integration, conformance, adversarial, and live Docker mesh suites
605
+ - **Multi-OS matrix:** Ubuntu, Windows, macOS
606
+ - **Node.js versions:** 20.x, 22.x
607
+ - **Code quality:** Enforced by [Biome.js](https://biomejs.dev/) (linting + formatting)
608
+ - **Security:** Verified 6-layer defense-in-depth architecture — see [Security Architecture](https://nekzus-32.mintlify.app/typescript-sdk/security)
609
+
610
+ > To run tests locally or contribute, clone the [repository](https://github.com/Nekzus/LIOP) and follow the [Contributing Guide](https://github.com/Nekzus/LIOP/blob/main/CONTRIBUTING.md).
611
+
612
+ ## Security Auditing & Supply Chain
613
+
614
+ This repository is integrated with [Socket.dev](https://socket.dev) to continuously monitor and secure the software supply chain against malicious packages, hidden telemetry, and dependency vulnerabilities.
615
+
616
+ You can run security audits and check package health scores directly from the monorepo root:
617
+
618
+ - **Scan Monorepo Dependencies:** `pnpm socket:scan` (performs a security scan and generates a report)
619
+ - **Check SDK Security Score:** `pnpm socket:score` (shows the detailed package score for the SDK in Markdown format)
620
+ - **Fix Vulnerabilities:** `pnpm socket:fix` (automatically remediates known CVEs in package.json)
621
+
622
+ The codebase undergoes regular dependencies audits. As of June 2026, the SDK is verified to be 100% free of orphan packages and dead dependencies, ensuring a minimal deployment footprint.
623
+
624
+ ---
625
+
626
+ ## Related
627
+
628
+ - [LIOP Documentation](https://nekzus-32.mintlify.app/) — Full conceptual and API documentation
629
+ - [LIOP Specification](https://github.com/Nekzus/LIOP/blob/main/protocol/SPECIFICATION.md) — Technical specification
630
+ - [LIOP Manifesto](https://github.com/Nekzus/LIOP/blob/main/MANIFESTO.md) — Project philosophy
631
+ - [Contributing Guide](https://github.com/Nekzus/LIOP/blob/main/CONTRIBUTING.md) — How to contribute
632
+ - [Rust Mesh Node](https://github.com/Nekzus/LIOP/tree/main/servers/liop-node) — Native high-performance backend
633
+ - [LIOP CLI](https://github.com/Nekzus/LIOP/tree/main/tools/liop-cli) — Developer diagnostics
634
+
635
+ ---
636
+
637
+ ## License
638
+
639
+ Licensed under the [Apache License, Version 2.0](https://github.com/Nekzus/LIOP/blob/main/LICENSE) (the "License"). You may not use this file except in compliance with the License. See [NOTICE](https://github.com/Nekzus/LIOP/blob/main/NOTICE) and [TRADEMARKS.md](https://github.com/Nekzus/LIOP/blob/main/TRADEMARKS.md) for attribution and trademark details.
640
+
641
+ Copyright 2026 [Nekzus Solutions](https://github.com/Nekzus) and contributors.
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node