@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.
- package/LICENSE +201 -0
- package/NOTICE +24 -0
- package/README.md +641 -0
- package/dist/bin/agent.d.ts +1 -0
- package/dist/bin/agent.js +897 -0
- package/dist/bin/agent.js.map +1 -0
- package/dist/bridge.d.ts +105 -0
- package/dist/bridge.js +5 -0
- package/dist/bridge.js.map +1 -0
- package/dist/chunk-3L2O2XKG.js +723 -0
- package/dist/chunk-3L2O2XKG.js.map +1 -0
- package/dist/chunk-7BSCUYUE.js +421 -0
- package/dist/chunk-7BSCUYUE.js.map +1 -0
- package/dist/chunk-7PITYWOV.js +68 -0
- package/dist/chunk-7PITYWOV.js.map +1 -0
- package/dist/chunk-7RXOIDXP.js +877 -0
- package/dist/chunk-7RXOIDXP.js.map +1 -0
- package/dist/chunk-BOISQ45Z.js +558 -0
- package/dist/chunk-BOISQ45Z.js.map +1 -0
- package/dist/chunk-DZ2FQGJD.js +206712 -0
- package/dist/chunk-DZ2FQGJD.js.map +1 -0
- package/dist/chunk-EG46XMJT.js +77 -0
- package/dist/chunk-EG46XMJT.js.map +1 -0
- package/dist/chunk-ESRXG36Y.js +115 -0
- package/dist/chunk-ESRXG36Y.js.map +1 -0
- package/dist/chunk-FTF6AMF6.js +3 -0
- package/dist/chunk-FTF6AMF6.js.map +1 -0
- package/dist/chunk-HA6YZ42O.js +64 -0
- package/dist/chunk-HA6YZ42O.js.map +1 -0
- package/dist/chunk-HD2N3IJX.js +3634 -0
- package/dist/chunk-HD2N3IJX.js.map +1 -0
- package/dist/chunk-IK7CGWAZ.js +24 -0
- package/dist/chunk-IK7CGWAZ.js.map +1 -0
- package/dist/chunk-L6J72C5X.js +1477 -0
- package/dist/chunk-L6J72C5X.js.map +1 -0
- package/dist/chunk-PAICJCKJ.js +332 -0
- package/dist/chunk-PAICJCKJ.js.map +1 -0
- package/dist/chunk-PEN3KFLF.js +114 -0
- package/dist/chunk-PEN3KFLF.js.map +1 -0
- package/dist/chunk-T7R5HUFD.js +775 -0
- package/dist/chunk-T7R5HUFD.js.map +1 -0
- package/dist/chunk-TKRX6CFI.js +168 -0
- package/dist/chunk-TKRX6CFI.js.map +1 -0
- package/dist/chunk-UCVP3XAL.js +279 -0
- package/dist/chunk-UCVP3XAL.js.map +1 -0
- package/dist/chunk-VH4K4U45.js +180 -0
- package/dist/chunk-VH4K4U45.js.map +1 -0
- package/dist/chunk-Y62GORQF.js +51 -0
- package/dist/chunk-Y62GORQF.js.map +1 -0
- package/dist/chunk-ZP3VVXOI.js +66 -0
- package/dist/chunk-ZP3VVXOI.js.map +1 -0
- package/dist/client.d.ts +7 -0
- package/dist/client.js +13 -0
- package/dist/client.js.map +1 -0
- package/dist/gateway.d.ts +7 -0
- package/dist/gateway.js +13 -0
- package/dist/gateway.js.map +1 -0
- package/dist/hybrid-CrKB50nh.d.ts +170 -0
- package/dist/index-CX43dvMs.d.ts +170 -0
- package/dist/index-DoW2gzBZ.d.ts +566 -0
- package/dist/index.d.ts +810 -0
- package/dist/index.js +357 -0
- package/dist/index.js.map +1 -0
- package/dist/kyber-CGOA7Q6A.js +3 -0
- package/dist/kyber-CGOA7Q6A.js.map +1 -0
- package/dist/mesh.d.ts +32 -0
- package/dist/mesh.js +6 -0
- package/dist/mesh.js.map +1 -0
- package/dist/node-B0b2vUFS.d.ts +164 -0
- package/dist/protocol/liop_core.proto +47 -0
- package/dist/server.d.ts +5 -0
- package/dist/server.js +9 -0
- package/dist/server.js.map +1 -0
- package/dist/types-lJIxBlWF.d.ts +256 -0
- package/dist/types.d.ts +3 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/verifier-COnid_dg.d.ts +31 -0
- package/dist/verifier-HRFXBKT5.js +6 -0
- package/dist/verifier-HRFXBKT5.js.map +1 -0
- package/dist/workers/logic-execution.d.ts +26 -0
- package/dist/workers/logic-execution.js +272 -0
- package/dist/workers/logic-execution.js.map +1 -0
- package/dist/workers/zk-verifier.d.ts +26 -0
- package/dist/workers/zk-verifier.js +174 -0
- package/dist/workers/zk-verifier.js.map +1 -0
- package/package.json +230 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
export { WasiSandbox, calculateAstInstructionFuel, getDefaultEnvironment } from './chunk-7BSCUYUE.js';
|
|
2
|
+
export { AesGcmWrapper, LiopClient, LiopRpcClient } from './chunk-T7R5HUFD.js';
|
|
3
|
+
export { LiopMcpBridge, LiopStreamBridge } from './chunk-BOISQ45Z.js';
|
|
4
|
+
export { GRPC_WEB_CONSTANTS, InMemoryRateLimiter, LiopHybridGateway, buildProtectedResourceMetadata, decodeFrames, dispatchGrpcWebRequest, encodeDataFrame, encodeTrailerFrame, isGrpcWebRequest } from './chunk-3L2O2XKG.js';
|
|
5
|
+
export { RoutingTable, probeTopology } from './chunk-UCVP3XAL.js';
|
|
6
|
+
export { TokenManager } from './chunk-ESRXG36Y.js';
|
|
7
|
+
export { AUTH_DEFAULTS, AuditLogger, GENESIS_HASH, JwtValidator, LiopRpcServer, LiopServer, NerScanner, PII_PATTERNS, PII_PRESETS, PiiScanner, computeEntryHash, createOAuthServer, globalAuditLogger } from './chunk-HD2N3IJX.js';
|
|
8
|
+
export { sanitizeOutput } from './chunk-Y62GORQF.js';
|
|
9
|
+
export { LiopMcpRouter } from './chunk-L6J72C5X.js';
|
|
10
|
+
export { HeuristicTokenEstimator, LiopOTelBridge, RealTokenEstimator, TokenTelemetryEngine, createSyncTokenEstimator, createTokenEstimator } from './chunk-DZ2FQGJD.js';
|
|
11
|
+
import './chunk-PEN3KFLF.js';
|
|
12
|
+
import './chunk-IK7CGWAZ.js';
|
|
13
|
+
export { Kyber768Wrapper } from './chunk-7PITYWOV.js';
|
|
14
|
+
export { DILITHIUM65_CONSTANTS, Dilithium65Wrapper, LIOP_SCOPES, authorizeRequest } from './chunk-VH4K4U45.js';
|
|
15
|
+
export { GRPC_CHANNEL_OPTIONS } from './chunk-TKRX6CFI.js';
|
|
16
|
+
export { Counter, Gauge, Histogram, MetricsRegistry, egressBlocksTotal, fuelConsumed, manifestCacheSize, meshPeersConnected, operationDurationMs, pqcHandshakeDurationMs, pqcHandshakesTotal, protocolMetrics, tokensInputTotal, tokensOutputTotal, tokensSavedTotal, toolCallErrorsTotal, toolCallsTotal, wireEgressBytesTotal, wireSavedBytesTotal, zkVerificationDurationMs, zkVerificationsTotal } from './chunk-PAICJCKJ.js';
|
|
17
|
+
export { MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY, PromptSchema, ResourceSchema, ToolSchema } from './chunk-EG46XMJT.js';
|
|
18
|
+
export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey } from './chunk-ZP3VVXOI.js';
|
|
19
|
+
export { MeshNode } from './chunk-7RXOIDXP.js';
|
|
20
|
+
import { log } from './chunk-HA6YZ42O.js';
|
|
21
|
+
import * as crypto from 'crypto';
|
|
22
|
+
import { EventEmitter } from 'events';
|
|
23
|
+
import * as fs from 'fs';
|
|
24
|
+
|
|
25
|
+
// src/errors.ts
|
|
26
|
+
var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
|
|
27
|
+
ErrorCode2["CapabilityViolation"] = "CapabilityViolation";
|
|
28
|
+
ErrorCode2["SandboxEscape"] = "SandboxEscape";
|
|
29
|
+
ErrorCode2["PiiLeak"] = "PiiLeak";
|
|
30
|
+
ErrorCode2["InvalidIntent"] = "InvalidIntent";
|
|
31
|
+
ErrorCode2["Throttled"] = "Throttled";
|
|
32
|
+
ErrorCode2["ZkVerificationFailed"] = "ZkVerificationFailed";
|
|
33
|
+
ErrorCode2["MeshUnavailable"] = "MeshUnavailable";
|
|
34
|
+
ErrorCode2["ConnectionFailed"] = "ConnectionFailed";
|
|
35
|
+
return ErrorCode2;
|
|
36
|
+
})(ErrorCode || {});
|
|
37
|
+
var LiopError = class extends Error {
|
|
38
|
+
code;
|
|
39
|
+
constructor(code, message) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.name = "LiopError";
|
|
42
|
+
this.code = code;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var TRACEPARENT_REGEX = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
|
|
46
|
+
var LiopTracer = class _LiopTracer {
|
|
47
|
+
static generateTraceId() {
|
|
48
|
+
let id;
|
|
49
|
+
do {
|
|
50
|
+
id = crypto.randomBytes(16).toString("hex");
|
|
51
|
+
} while (id === "0".repeat(32));
|
|
52
|
+
return id;
|
|
53
|
+
}
|
|
54
|
+
static generateSpanId() {
|
|
55
|
+
let id;
|
|
56
|
+
do {
|
|
57
|
+
id = crypto.randomBytes(8).toString("hex");
|
|
58
|
+
} while (id === "0".repeat(16));
|
|
59
|
+
return id;
|
|
60
|
+
}
|
|
61
|
+
static formatTraceparent(traceId, spanId, sampled = true) {
|
|
62
|
+
const flags = sampled ? "01" : "00";
|
|
63
|
+
return `00-${traceId}-${spanId}-${flags}`;
|
|
64
|
+
}
|
|
65
|
+
static parseTraceparent(header) {
|
|
66
|
+
if (!header || typeof header !== "string") {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
const trimmed = header.trim();
|
|
70
|
+
const match = TRACEPARENT_REGEX.exec(trimmed);
|
|
71
|
+
if (!match) {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
const [, version, traceId, spanId, flags] = match;
|
|
75
|
+
if (version === "00") {
|
|
76
|
+
if (traceId === "0".repeat(32) || spanId === "0".repeat(16)) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const sampled = (Number.parseInt(flags, 16) & 1) === 1;
|
|
81
|
+
return {
|
|
82
|
+
traceId,
|
|
83
|
+
spanId,
|
|
84
|
+
sampled
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
static injectTraceparent(carrier, context) {
|
|
88
|
+
carrier.traceparent = _LiopTracer.formatTraceparent(
|
|
89
|
+
context.traceId,
|
|
90
|
+
context.spanId,
|
|
91
|
+
context.sampled
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
static extractTraceparent(carrier) {
|
|
95
|
+
const val = carrier.traceparent || carrier.Traceparent;
|
|
96
|
+
if (Array.isArray(val)) {
|
|
97
|
+
return _LiopTracer.parseTraceparent(val[0]);
|
|
98
|
+
}
|
|
99
|
+
return _LiopTracer.parseTraceparent(val);
|
|
100
|
+
}
|
|
101
|
+
startSpan(name, parent, attributes = {}) {
|
|
102
|
+
const traceId = parent?.traceId || _LiopTracer.generateTraceId();
|
|
103
|
+
const spanId = _LiopTracer.generateSpanId();
|
|
104
|
+
const sampled = parent ? parent.sampled : true;
|
|
105
|
+
const context = {
|
|
106
|
+
traceId,
|
|
107
|
+
spanId,
|
|
108
|
+
sampled
|
|
109
|
+
};
|
|
110
|
+
const span = {
|
|
111
|
+
name,
|
|
112
|
+
context,
|
|
113
|
+
startTime: Date.now(),
|
|
114
|
+
attributes: { ...attributes },
|
|
115
|
+
status: "OK",
|
|
116
|
+
setAttribute(key, value) {
|
|
117
|
+
this.attributes[key] = value;
|
|
118
|
+
return this;
|
|
119
|
+
},
|
|
120
|
+
recordException(err) {
|
|
121
|
+
this.status = "ERROR";
|
|
122
|
+
this.error = typeof err === "string" ? err : err.message;
|
|
123
|
+
return this;
|
|
124
|
+
},
|
|
125
|
+
end() {
|
|
126
|
+
this.endTime = Date.now();
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
return span;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
var defaultTracer = new LiopTracer();
|
|
133
|
+
|
|
134
|
+
// src/prompts/adapters.ts
|
|
135
|
+
var PROVIDER_CONFIGS = {
|
|
136
|
+
claude: { xmlStandard: true, jsonSchemaPreferred: false },
|
|
137
|
+
openai: { xmlStandard: false, jsonSchemaPreferred: true },
|
|
138
|
+
gemini: { xmlStandard: false, jsonSchemaPreferred: true }
|
|
139
|
+
};
|
|
140
|
+
function generateSystemInstructions(provider) {
|
|
141
|
+
const config = PROVIDER_CONFIGS[provider];
|
|
142
|
+
let instructions = `[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
|
|
143
|
+
You are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.
|
|
144
|
+
Unlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.
|
|
145
|
+
|
|
146
|
+
### CORE PARADIGM
|
|
147
|
+
When you call a tool or resource, you MUST provide a payload that represents secure sandboxed logic to be executed on the remote Node.
|
|
148
|
+
The node will execute your logic securely on the raw secure data, and return only the RESULT, avoiding PII data egress.
|
|
149
|
+
|
|
150
|
+
### EXECUTION RULES
|
|
151
|
+
1. Provide a self-contained JavaScript syntax block that we will compile to WASM-Sandboxed logic.
|
|
152
|
+
2. Rely only on standard ECMA script features (No Node.js polyfills).
|
|
153
|
+
3. The logic must end by returning the calculated insights, not the raw data.
|
|
154
|
+
|
|
155
|
+
### DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism)
|
|
156
|
+
To prevent database reconstruction and inference attacks, numeric query outputs are processed by a Laplace DP engine:
|
|
157
|
+
- 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.
|
|
158
|
+
- AVERAGE queries: Return keys containing 'avg', 'mean', or 'average' scale down noise automatically by dividing global sensitivity by the dataset size (sensitivity / n).
|
|
159
|
+
- 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.
|
|
160
|
+
|
|
161
|
+
### SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS
|
|
162
|
+
- Date is poisoned: The 'Date' class/constructor is undefined (calling 'new Date()', 'Date.now()', or 'Date.parse()' will crash the execution).
|
|
163
|
+
- Workaround: Perform chronological sorting and comparisons lexicographically on ISO 8601 string dates (e.g. record.date >= '2024-01-01').
|
|
164
|
+
- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.
|
|
165
|
+
- Frozen prototypes: Modifications to Object.prototype, Array.prototype, etc., are blocked.
|
|
166
|
+
- 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.
|
|
167
|
+
`;
|
|
168
|
+
if (config.xmlStandard) {
|
|
169
|
+
instructions += `
|
|
170
|
+
### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)
|
|
171
|
+
You must wrap your logic precisely within <liop_logic> tags.
|
|
172
|
+
Example:
|
|
173
|
+
<liop_logic>
|
|
174
|
+
const records = await liop.readResource("liop://vault/patients");
|
|
175
|
+
const filtered = records.filter(r => r.disease === "Hypertension");
|
|
176
|
+
return { alert: "High risk demographic", targetCount: filtered.length };
|
|
177
|
+
</liop_logic>
|
|
178
|
+
`;
|
|
179
|
+
} else if (config.jsonSchemaPreferred) {
|
|
180
|
+
instructions += `
|
|
181
|
+
### PAYLOAD FORMATTING (JSON PARSING PREFERRED)
|
|
182
|
+
You must provide your logic strictly within a JSON string key called \`"logic_blob"\` inside your tool call parameters.
|
|
183
|
+
Example:
|
|
184
|
+
{
|
|
185
|
+
"target": "liop://vault/patients",
|
|
186
|
+
"logic_blob": "const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };"
|
|
187
|
+
}
|
|
188
|
+
`;
|
|
189
|
+
}
|
|
190
|
+
return instructions;
|
|
191
|
+
}
|
|
192
|
+
var CertManager = class extends EventEmitter {
|
|
193
|
+
constructor(options) {
|
|
194
|
+
super();
|
|
195
|
+
this.options = options;
|
|
196
|
+
this.warningDays = options.warningDays ?? 30;
|
|
197
|
+
this.debounceMs = options.debounceMs ?? 150;
|
|
198
|
+
this.loadCertificates();
|
|
199
|
+
if (options.watchFiles !== false) {
|
|
200
|
+
this.setupWatchers();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
options;
|
|
204
|
+
rootCertBuffer = null;
|
|
205
|
+
certChainBuffer = null;
|
|
206
|
+
privateKeyBuffer = null;
|
|
207
|
+
watchers = [];
|
|
208
|
+
reloadDebounceTimer = null;
|
|
209
|
+
warningDays;
|
|
210
|
+
debounceMs;
|
|
211
|
+
/**
|
|
212
|
+
* Synchronously loads or reloads certificates from filesystem into memory.
|
|
213
|
+
*/
|
|
214
|
+
loadCertificates() {
|
|
215
|
+
try {
|
|
216
|
+
if (this.options.rootCertPath && fs.existsSync(this.options.rootCertPath)) {
|
|
217
|
+
this.rootCertBuffer = fs.readFileSync(this.options.rootCertPath);
|
|
218
|
+
}
|
|
219
|
+
if (!fs.existsSync(this.options.certChainPath)) {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`Certificate chain file not found: ${this.options.certChainPath}`
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
if (!fs.existsSync(this.options.privateKeyPath)) {
|
|
225
|
+
throw new Error(
|
|
226
|
+
`Private key file not found: ${this.options.privateKeyPath}`
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
this.certChainBuffer = fs.readFileSync(this.options.certChainPath);
|
|
230
|
+
this.privateKeyBuffer = fs.readFileSync(this.options.privateKeyPath);
|
|
231
|
+
log.info("[CertManager] Certificates loaded successfully.");
|
|
232
|
+
} catch (error) {
|
|
233
|
+
log.error(`[CertManager] Failed to load certificates: ${error}`);
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Inspects the loaded server/client certificate chain using Node.js native X509Certificate.
|
|
239
|
+
*/
|
|
240
|
+
inspectCertificate() {
|
|
241
|
+
if (!this.certChainBuffer) {
|
|
242
|
+
throw new Error("[CertManager] No certificate loaded to inspect.");
|
|
243
|
+
}
|
|
244
|
+
const x509 = new crypto.X509Certificate(this.certChainBuffer);
|
|
245
|
+
const validToDate = new Date(x509.validTo);
|
|
246
|
+
const now = /* @__PURE__ */ new Date();
|
|
247
|
+
const msRemaining = validToDate.getTime() - now.getTime();
|
|
248
|
+
const daysRemaining = Math.max(
|
|
249
|
+
0,
|
|
250
|
+
Math.floor(msRemaining / (1e3 * 60 * 60 * 24))
|
|
251
|
+
);
|
|
252
|
+
const isExpired = msRemaining <= 0;
|
|
253
|
+
const isExpiringSoon = daysRemaining <= this.warningDays;
|
|
254
|
+
return {
|
|
255
|
+
subject: x509.subject,
|
|
256
|
+
issuer: x509.issuer,
|
|
257
|
+
validFrom: x509.validFrom,
|
|
258
|
+
validTo: x509.validTo,
|
|
259
|
+
fingerprint256: x509.fingerprint256,
|
|
260
|
+
daysRemaining,
|
|
261
|
+
isExpired,
|
|
262
|
+
isExpiringSoon
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Sets up non-blocking filesystem watchers to detect certificate renewals
|
|
267
|
+
* and trigger hot-reloading without process restarts.
|
|
268
|
+
*/
|
|
269
|
+
setupWatchers() {
|
|
270
|
+
const filesToWatch = [
|
|
271
|
+
this.options.certChainPath,
|
|
272
|
+
this.options.privateKeyPath,
|
|
273
|
+
this.options.rootCertPath
|
|
274
|
+
].filter((p) => Boolean(p && fs.existsSync(p)));
|
|
275
|
+
for (const filePath of filesToWatch) {
|
|
276
|
+
try {
|
|
277
|
+
const watcher = fs.watch(filePath, () => {
|
|
278
|
+
this.scheduleReload();
|
|
279
|
+
});
|
|
280
|
+
this.watchers.push(watcher);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
log.warn(
|
|
283
|
+
`[CertManager] Could not watch ${filePath} for hot reloading: ${err}`
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Debounces reload events to ensure files have finished writing.
|
|
290
|
+
*/
|
|
291
|
+
scheduleReload() {
|
|
292
|
+
if (this.reloadDebounceTimer) {
|
|
293
|
+
clearTimeout(this.reloadDebounceTimer);
|
|
294
|
+
}
|
|
295
|
+
this.reloadDebounceTimer = setTimeout(() => {
|
|
296
|
+
try {
|
|
297
|
+
this.loadCertificates();
|
|
298
|
+
const certInfo = this.inspectCertificate();
|
|
299
|
+
log.info(
|
|
300
|
+
`[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`
|
|
301
|
+
);
|
|
302
|
+
this.emit("reload", certInfo);
|
|
303
|
+
} catch (error) {
|
|
304
|
+
log.error(`[CertManager] Hot reload failed: ${error}`);
|
|
305
|
+
this.emit("error", error);
|
|
306
|
+
}
|
|
307
|
+
}, this.debounceMs);
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Manually triggers a reload of certificates and emits the 'reload' event.
|
|
311
|
+
*/
|
|
312
|
+
reload() {
|
|
313
|
+
this.loadCertificates();
|
|
314
|
+
const certInfo = this.inspectCertificate();
|
|
315
|
+
log.info(
|
|
316
|
+
`[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`
|
|
317
|
+
);
|
|
318
|
+
this.emit("reload", certInfo);
|
|
319
|
+
return certInfo;
|
|
320
|
+
}
|
|
321
|
+
getRootCert() {
|
|
322
|
+
return this.rootCertBuffer;
|
|
323
|
+
}
|
|
324
|
+
getCertChain() {
|
|
325
|
+
if (!this.certChainBuffer) {
|
|
326
|
+
throw new Error("[CertManager] Certificate chain not loaded.");
|
|
327
|
+
}
|
|
328
|
+
return this.certChainBuffer;
|
|
329
|
+
}
|
|
330
|
+
getPrivateKey() {
|
|
331
|
+
if (!this.privateKeyBuffer) {
|
|
332
|
+
throw new Error("[CertManager] Private key not loaded.");
|
|
333
|
+
}
|
|
334
|
+
return this.privateKeyBuffer;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Stops all active file watchers and releases resources.
|
|
338
|
+
*/
|
|
339
|
+
dispose() {
|
|
340
|
+
if (this.reloadDebounceTimer) {
|
|
341
|
+
clearTimeout(this.reloadDebounceTimer);
|
|
342
|
+
this.reloadDebounceTimer = null;
|
|
343
|
+
}
|
|
344
|
+
for (const watcher of this.watchers) {
|
|
345
|
+
try {
|
|
346
|
+
watcher.close();
|
|
347
|
+
} catch {
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
this.watchers = [];
|
|
351
|
+
this.removeAllListeners();
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
export { CertManager, ErrorCode, LiopError, LiopTracer, defaultTracer, generateSystemInstructions };
|
|
356
|
+
//# sourceMappingURL=index.js.map
|
|
357
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/observability/tracing.ts","../src/prompts/adapters.ts","../src/security/cert-manager.ts"],"names":["ErrorCode","crypto2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAGO,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;AAA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A,OAAO,QAAA;AAAA,EACR;AAAA,EAEO,WAAA,GAA6B;AACnC,IAAA,OAAO,IAAA,CAAK,cAAA;AAAA,EACb;AAAA,EAEO,YAAA,GAAuB;AAC7B,IAAA,IAAI,CAAC,KAAK,eAAA,EAAiB;AAC1B,MAAA,MAAM,IAAI,MAAM,6CAA6C,CAAA;AAAA,IAC9D;AACA,IAAA,OAAO,IAAA,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":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nexport 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","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\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","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\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","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"kyber-CGOA7Q6A.js"}
|
package/dist/mesh.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export { L as LiopManifest, a as MeshNode, M as MeshNodeConfig } from './node-B0b2vUFS.js';
|
|
2
|
+
|
|
3
|
+
declare const SWARM_KEY_BYTE_LENGTH = 95;
|
|
4
|
+
/**
|
|
5
|
+
* Creates a freshly generated 95-byte Pre-Shared Key (PSK) for libp2p Private Networks (pnet).
|
|
6
|
+
* Follows the canonical format `/key/swarm/psk/1.0.0/\n/base16/\n<hex>\n`.
|
|
7
|
+
*/
|
|
8
|
+
declare function createSwarmKey(): Uint8Array;
|
|
9
|
+
/**
|
|
10
|
+
* Serializes a 95-byte PSK into a Base64 string for safe environment variable passing or JSON config.
|
|
11
|
+
*/
|
|
12
|
+
declare function serializeSwarmKey(psk: Uint8Array): string;
|
|
13
|
+
/**
|
|
14
|
+
* Deserializes a Base64-encoded string into a 95-byte PSK Uint8Array.
|
|
15
|
+
*/
|
|
16
|
+
declare function deserializeSwarmKey(base64Str: string): Uint8Array;
|
|
17
|
+
/**
|
|
18
|
+
* Parses raw text format PSK or Base64 string into a 95-byte PSK Uint8Array.
|
|
19
|
+
* Allows loading either the canonical multiline text (`/key/swarm/psk/1.0.0/...`) or Base64.
|
|
20
|
+
*/
|
|
21
|
+
declare function parseSwarmKey(rawText: string): Uint8Array;
|
|
22
|
+
/**
|
|
23
|
+
* Saves a 95-byte Swarm Key to a file on disk (written as canonical text).
|
|
24
|
+
*/
|
|
25
|
+
declare function saveSwarmKey(psk: Uint8Array, filePath: string): Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* Loads a 95-byte Swarm Key from a file on disk.
|
|
28
|
+
* Supports both raw binary/canonical format and Base64-encoded text.
|
|
29
|
+
*/
|
|
30
|
+
declare function loadSwarmKey(filePath: string): Promise<Uint8Array>;
|
|
31
|
+
|
|
32
|
+
export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey };
|
package/dist/mesh.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import './chunk-FTF6AMF6.js';
|
|
2
|
+
export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey } from './chunk-ZP3VVXOI.js';
|
|
3
|
+
export { MeshNode } from './chunk-7RXOIDXP.js';
|
|
4
|
+
import './chunk-HA6YZ42O.js';
|
|
5
|
+
//# sourceMappingURL=mesh.js.map
|
|
6
|
+
//# sourceMappingURL=mesh.js.map
|
package/dist/mesh.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"mesh.js"}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manifest describing a node's capabilities in the LIOP Mesh.
|
|
3
|
+
* Exchanged via the /liop/manifest/1.0.0 protocol stream.
|
|
4
|
+
*/
|
|
5
|
+
interface LiopManifest {
|
|
6
|
+
peerId: string;
|
|
7
|
+
grpcPort: number;
|
|
8
|
+
tools: Array<{
|
|
9
|
+
name: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
inputSchema?: Record<string, unknown>;
|
|
12
|
+
}>;
|
|
13
|
+
resources: Array<{
|
|
14
|
+
name: string;
|
|
15
|
+
uri: string;
|
|
16
|
+
description?: string;
|
|
17
|
+
mimeType?: string;
|
|
18
|
+
text?: string;
|
|
19
|
+
}>;
|
|
20
|
+
serverInfo: {
|
|
21
|
+
name: string;
|
|
22
|
+
version: string;
|
|
23
|
+
};
|
|
24
|
+
taxonomy?: {
|
|
25
|
+
domain: string;
|
|
26
|
+
clearanceTier: number;
|
|
27
|
+
executionTypes: string[];
|
|
28
|
+
};
|
|
29
|
+
authRequired?: boolean;
|
|
30
|
+
/** Canonical slug for deterministic token resolution. Agents resolve LIOP_TOKEN_<tokenSlug>. Must match /^[A-Z][A-Z0-9_]*$/. */
|
|
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;
|
|
36
|
+
}
|
|
37
|
+
interface MeshNodeConfig {
|
|
38
|
+
listenAddresses?: string[];
|
|
39
|
+
bootstrapNodes?: string[];
|
|
40
|
+
identityPath?: string;
|
|
41
|
+
enableWAN?: boolean;
|
|
42
|
+
dhtStoragePath?: string;
|
|
43
|
+
/** Optional function to translate multiaddrs (e.g. for Docker NAT traversal). Return null to drop an address. */
|
|
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;
|
|
53
|
+
/**
|
|
54
|
+
* Pre-Shared Key for libp2p Private Network isolation (Tier 1 Enclave Hardening).
|
|
55
|
+
* When provided, the node will reject ALL connections from peers that do not
|
|
56
|
+
* possess the identical 95-byte PSK at the transport framing layer,
|
|
57
|
+
* BEFORE the Noise XX handshake is attempted.
|
|
58
|
+
* @see https://github.com/libp2p/specs/blob/master/pnet/Private-Networks-PSK-V1.md
|
|
59
|
+
*/
|
|
60
|
+
swarmKey?: Uint8Array;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* P2P Mesh Node backed by libp2p + Kademlia DHT.
|
|
64
|
+
*
|
|
65
|
+
* Provides capability advertisement via CID-based content routing
|
|
66
|
+
* and decentralized peer discovery.
|
|
67
|
+
*/
|
|
68
|
+
declare class MeshNode {
|
|
69
|
+
private node;
|
|
70
|
+
private config;
|
|
71
|
+
private manifestDialFailureState;
|
|
72
|
+
private static readonly MANIFEST_DIAL_BASE_COOLDOWN_MS;
|
|
73
|
+
private static readonly MANIFEST_DIAL_MAX_COOLDOWN_MS;
|
|
74
|
+
private static readonly MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS;
|
|
75
|
+
/**
|
|
76
|
+
* Buffer of capability hashes that have been announced.
|
|
77
|
+
* Used to re-announce capabilities when new peers connect
|
|
78
|
+
* (critical for small / isolated clusters where the initial
|
|
79
|
+
* provide() finds zero peers in the routing table).
|
|
80
|
+
*/
|
|
81
|
+
private announcedCapabilities;
|
|
82
|
+
/** Guards against concurrent re-announcement storms. */
|
|
83
|
+
private reannouncing;
|
|
84
|
+
/** Callback that returns the local node's manifest on request. */
|
|
85
|
+
private manifestProvider;
|
|
86
|
+
/** Flag to ensure the manifest protocol is only registered once. */
|
|
87
|
+
private manifestProtocolRegistered;
|
|
88
|
+
/** Local Ed25519 Private Key for protocol signatures */
|
|
89
|
+
private localPrivateKey;
|
|
90
|
+
constructor(config?: MeshNodeConfig);
|
|
91
|
+
private shouldSkipManifestDial;
|
|
92
|
+
private recordManifestDialFailure;
|
|
93
|
+
private clearManifestDialFailure;
|
|
94
|
+
/**
|
|
95
|
+
* Loads a persistent identity from disk or generates a new Ed25519 keypair.
|
|
96
|
+
* Uses privateKeyToProtobuf/privateKeyFromProtobuf (libp2p v3.x official API).
|
|
97
|
+
*/
|
|
98
|
+
private loadOrCreateIdentity;
|
|
99
|
+
/**
|
|
100
|
+
* Persists the private key to disk using protobuf serialization (libp2p v3.x).
|
|
101
|
+
*/
|
|
102
|
+
private saveIdentity;
|
|
103
|
+
/**
|
|
104
|
+
* Creates a CID v1 (raw codec 0x55) from a SHA-256 hash of the capability string.
|
|
105
|
+
* Required by @libp2p/kad-dht v16+ for provide/findProviders.
|
|
106
|
+
*/
|
|
107
|
+
private capabilityToCID;
|
|
108
|
+
/**
|
|
109
|
+
* Re-announces all buffered capabilities after a new peer connects.
|
|
110
|
+
* Uses a small delay to allow the DHT protocol handshake to complete.
|
|
111
|
+
*/
|
|
112
|
+
private reannounceAll;
|
|
113
|
+
start(): Promise<void>;
|
|
114
|
+
stop(): Promise<void>;
|
|
115
|
+
private loadRoutingTable;
|
|
116
|
+
private saveRoutingTable;
|
|
117
|
+
/**
|
|
118
|
+
* Internal logic to register protocol handlers against the libp2p node.
|
|
119
|
+
* Can be called multiple times; handles idempotent registration.
|
|
120
|
+
*/
|
|
121
|
+
private applyHandlers;
|
|
122
|
+
/**
|
|
123
|
+
* Registers a callback as the manifest provider.
|
|
124
|
+
* Will be applied immediately if the node is already initialized.
|
|
125
|
+
*/
|
|
126
|
+
registerManifestHandler(provider: () => LiopManifest): void;
|
|
127
|
+
/**
|
|
128
|
+
* Queries a remote peer's manifest by opening a /liop/manifest/1.0.0 stream.
|
|
129
|
+
* Returns null if the peer doesn't support the protocol or is unreachable.
|
|
130
|
+
*/
|
|
131
|
+
queryManifest(peerIdStr: string): Promise<LiopManifest | null>;
|
|
132
|
+
/**
|
|
133
|
+
* Discovers all peers in the DHT that have announced "liop:manifest".
|
|
134
|
+
* Returns their PeerIDs for subsequent manifest queries.
|
|
135
|
+
*/
|
|
136
|
+
discoverManifestProviders(): Promise<string[]>;
|
|
137
|
+
/**
|
|
138
|
+
* Announces this node as a manifest provider in the DHT.
|
|
139
|
+
* Should be called after tools/resources have been registered.
|
|
140
|
+
*/
|
|
141
|
+
announceManifest(): Promise<void>;
|
|
142
|
+
/**
|
|
143
|
+
* Returns the current size of the routing table for diagnostic purposes.
|
|
144
|
+
*/
|
|
145
|
+
getRoutingTableSize(): number;
|
|
146
|
+
getPeerId(): string;
|
|
147
|
+
sign(data: Uint8Array): Promise<Uint8Array>;
|
|
148
|
+
getMultiaddrs(): string[];
|
|
149
|
+
announceCapability(hash: string): Promise<void>;
|
|
150
|
+
findProviders(hash: string): Promise<string[]>;
|
|
151
|
+
resolvePeer(peerIdStr: string): Promise<string[]>;
|
|
152
|
+
isStarted(): boolean;
|
|
153
|
+
getPeers(): string[];
|
|
154
|
+
/**
|
|
155
|
+
* Returns true if this MeshNode was booted inside an isolated libp2p private network (pnet PSK).
|
|
156
|
+
*/
|
|
157
|
+
isPrivateNetwork(): boolean;
|
|
158
|
+
/**
|
|
159
|
+
* Returns the configured 95-byte Swarm Key, or undefined if running in a public/consortium mesh.
|
|
160
|
+
*/
|
|
161
|
+
getSwarmKey(): Uint8Array | undefined;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export { type LiopManifest as L, type MeshNodeConfig as M, MeshNode as a };
|