@nekzus/liop 2.5.0 → 2.6.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 (95) hide show
  1. package/NOTICE +19 -0
  2. package/README.md +67 -34
  3. package/dist/bin/agent.js +673 -82
  4. package/dist/bin/agent.js.map +1 -1
  5. package/dist/bridge.d.ts +3 -3
  6. package/dist/bridge.js +3 -3
  7. package/dist/{chunk-PYKRQAER.js → chunk-2KSO3W4A.js} +2 -2
  8. package/dist/chunk-2KSO3W4A.js.map +1 -0
  9. package/dist/{chunk-32ADSAJS.js → chunk-2STZHJ24.js} +14 -4
  10. package/dist/chunk-2STZHJ24.js.map +1 -0
  11. package/dist/chunk-3QH44NKZ.js +115 -0
  12. package/dist/chunk-3QH44NKZ.js.map +1 -0
  13. package/dist/{chunk-WCCGE4QR.js → chunk-5SWHE62F.js} +196 -33
  14. package/dist/chunk-5SWHE62F.js.map +1 -0
  15. package/dist/{chunk-SONUORBT.js → chunk-7BSCUYUE.js} +2 -2
  16. package/dist/chunk-7BSCUYUE.js.map +1 -0
  17. package/dist/{chunk-QLCOEP5J.js → chunk-7PITYWOV.js} +2 -2
  18. package/dist/chunk-7PITYWOV.js.map +1 -0
  19. package/dist/{chunk-T5IUZF47.js → chunk-EJ426URA.js} +109 -7
  20. package/dist/chunk-EJ426URA.js.map +1 -0
  21. package/dist/{chunk-CRZBVFDV.js → chunk-FCFTYOAS.js} +243 -66
  22. package/dist/chunk-FCFTYOAS.js.map +1 -0
  23. package/dist/chunk-FTF6AMF6.js +3 -0
  24. package/dist/{chunk-RWRRBYG4.js.map → chunk-FTF6AMF6.js.map} +1 -1
  25. package/dist/{chunk-OUUTDSOW.js → chunk-IK7CGWAZ.js} +3 -3
  26. package/dist/chunk-IK7CGWAZ.js.map +1 -0
  27. package/dist/chunk-K3DGJLUY.js +106 -0
  28. package/dist/chunk-K3DGJLUY.js.map +1 -0
  29. package/dist/{chunk-U5BZ66VX.js → chunk-PAICJCKJ.js} +60 -175
  30. package/dist/chunk-PAICJCKJ.js.map +1 -0
  31. package/dist/chunk-PUDETPL4.js +279 -0
  32. package/dist/chunk-PUDETPL4.js.map +1 -0
  33. package/dist/{chunk-547TYL27.js → chunk-UJFWPRDM.js} +164 -1389
  34. package/dist/chunk-UJFWPRDM.js.map +1 -0
  35. package/dist/chunk-VRB5HUYU.js +1492 -0
  36. package/dist/chunk-VRB5HUYU.js.map +1 -0
  37. package/dist/{chunk-GA3Q2S7O.js → chunk-VRDZ5IKE.js} +5 -5
  38. package/dist/chunk-VRDZ5IKE.js.map +1 -0
  39. package/dist/chunk-WPTOJYN5.js +181 -0
  40. package/dist/chunk-WPTOJYN5.js.map +1 -0
  41. package/dist/{chunk-74CISO2I.js → chunk-XRDN232O.js} +28 -4
  42. package/dist/chunk-XRDN232O.js.map +1 -0
  43. package/dist/{chunk-JIJPZFR2.js → chunk-Y62GORQF.js} +2 -2
  44. package/dist/chunk-Y62GORQF.js.map +1 -0
  45. package/dist/chunk-ZP3VVXOI.js +66 -0
  46. package/dist/chunk-ZP3VVXOI.js.map +1 -0
  47. package/dist/client.d.ts +4 -3
  48. package/dist/client.js +10 -8
  49. package/dist/gateway.d.ts +4 -4
  50. package/dist/gateway.js +10 -9
  51. package/dist/{hybrid-CF__0YnC.d.ts → hybrid-DWe1bMoV.d.ts} +5 -4
  52. package/dist/{index-cMV0_yD9.d.ts → index-BuEQtBHD.d.ts} +39 -34
  53. package/dist/{index-BW95kAL4.d.ts → index-CdW8j8Bn.d.ts} +9 -72
  54. package/dist/index.d.ts +172 -48
  55. package/dist/index.js +20 -15
  56. package/dist/index.js.map +1 -1
  57. package/dist/kyber-CGOA7Q6A.js +3 -0
  58. package/dist/{kyber-3ULIJSE3.js.map → kyber-CGOA7Q6A.js.map} +1 -1
  59. package/dist/mesh.d.ts +27 -143
  60. package/dist/mesh.js +4 -3
  61. package/dist/node-B0b2vUFS.d.ts +164 -0
  62. package/dist/protocol/liop_core.proto +3 -0
  63. package/dist/server.d.ts +3 -3
  64. package/dist/server.js +7 -6
  65. package/dist/types-CzRSOlOo.d.ts +452 -0
  66. package/dist/types.d.ts +1 -1
  67. package/dist/types.js +1 -1
  68. package/dist/verifier-XFU7ZB2W.js +6 -0
  69. package/dist/{verifier-3FAKCFNN.js.map → verifier-XFU7ZB2W.js.map} +1 -1
  70. package/dist/workers/logic-execution.js +3 -3
  71. package/dist/workers/logic-execution.js.map +1 -1
  72. package/dist/workers/zk-verifier.js +1 -1
  73. package/dist/workers/zk-verifier.js.map +1 -1
  74. package/package.json +50 -44
  75. package/dist/chunk-32ADSAJS.js.map +0 -1
  76. package/dist/chunk-547TYL27.js.map +0 -1
  77. package/dist/chunk-72MNYFR6.js +0 -64
  78. package/dist/chunk-72MNYFR6.js.map +0 -1
  79. package/dist/chunk-74CISO2I.js.map +0 -1
  80. package/dist/chunk-CRZBVFDV.js.map +0 -1
  81. package/dist/chunk-GA3Q2S7O.js.map +0 -1
  82. package/dist/chunk-JIJPZFR2.js.map +0 -1
  83. package/dist/chunk-OUUTDSOW.js.map +0 -1
  84. package/dist/chunk-PYKRQAER.js.map +0 -1
  85. package/dist/chunk-QLCOEP5J.js.map +0 -1
  86. package/dist/chunk-RWRRBYG4.js +0 -3
  87. package/dist/chunk-SONUORBT.js.map +0 -1
  88. package/dist/chunk-T5IUZF47.js.map +0 -1
  89. package/dist/chunk-U5BZ66VX.js.map +0 -1
  90. package/dist/chunk-WCCGE4QR.js.map +0 -1
  91. package/dist/chunk-WSW6YJNY.js +0 -168
  92. package/dist/chunk-WSW6YJNY.js.map +0 -1
  93. package/dist/kyber-3ULIJSE3.js +0 -3
  94. package/dist/types-lJIxBlWF.d.ts +0 -256
  95. package/dist/verifier-3FAKCFNN.js +0 -5
@@ -1,11 +1,10 @@
1
- import { LiopVerifier } from './chunk-32ADSAJS.js';
2
- import { Kyber768Wrapper } from './chunk-QLCOEP5J.js';
3
- import { authorizeRequest, Dilithium65Wrapper } from './chunk-U5BZ66VX.js';
4
- import { liopV1, createChannelCredentials, GRPC_CHANNEL_OPTIONS } from './chunk-WSW6YJNY.js';
5
- import { MCP_PROTOCOL_VERSION, MCP_LEGACY_SUPPORT_ENABLED, isLegacyRequest, adaptResponseForLegacyClient, MCP_PROTOCOL_VERSION_LEGACY, buildLegacyInitializeResponse } from './chunk-PYKRQAER.js';
6
- import { log } from './chunk-72MNYFR6.js';
7
- import * as crypto2 from 'crypto';
1
+ import { tokensInputTotal, tokensOutputTotal, tokensSavedTotal, operationDurationMs } from './chunk-PAICJCKJ.js';
2
+ import { log } from './chunk-K3DGJLUY.js';
3
+ import * as fs from 'fs';
8
4
  import * as grpc from '@grpc/grpc-js';
5
+ import path from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import * as protoLoader from '@grpc/proto-loader';
9
8
 
10
9
  // ../../node_modules/.pnpm/gpt-tokenizer@4.0.0/node_modules/gpt-tokenizer/esm/constants.js
11
10
  var DEFAULT_MERGE_CACHE_SIZE = 1e5;
@@ -206560,6 +206559,27 @@ var TokenTelemetryEngine = class _TokenTelemetryEngine {
206560
206559
  }
206561
206560
  } catch {
206562
206561
  }
206562
+ try {
206563
+ const promLabels = {
206564
+ type: metric.type,
206565
+ method: metric.method,
206566
+ tool: metric.toolName || "none"
206567
+ };
206568
+ if (metric.estimatedInputTokens > 0) {
206569
+ tokensInputTotal.inc(promLabels, metric.estimatedInputTokens);
206570
+ }
206571
+ if (metric.estimatedOutputTokens > 0) {
206572
+ tokensOutputTotal.inc(promLabels, metric.estimatedOutputTokens);
206573
+ }
206574
+ if (metric.originDatasetTokens !== void 0 && metric.originDatasetTokens > metric.estimatedOutputTokens) {
206575
+ const actualSaved = metric.originDatasetTokens - metric.estimatedOutputTokens;
206576
+ tokensSavedTotal.inc({ tool: metric.toolName || "none" }, actualSaved);
206577
+ }
206578
+ if (metric.durationMs !== void 0 && metric.durationMs >= 0) {
206579
+ operationDurationMs.observe(promLabels, metric.durationMs);
206580
+ }
206581
+ } catch {
206582
+ }
206563
206583
  }
206564
206584
  /**
206565
206585
  * @deprecated Use countTokens() instead. Kept for backward compatibility.
@@ -206691,1419 +206711,174 @@ var TokenTelemetryEngine = class _TokenTelemetryEngine {
206691
206711
  _TokenTelemetryEngine.instance = null;
206692
206712
  }
206693
206713
  };
206694
-
206695
- // src/utils/mcpCompact.ts
206696
- function mcpCompactToolDescriptions() {
206697
- const v = process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();
206698
- if (v === "0" || v === "false" || v === "no") return false;
206699
- return true;
206700
- }
206701
- function stripVerboseLiopToolDescription(description) {
206702
- let d = description;
206703
- const markers = [
206704
- "\n\n[LIOP-PROTO-V1:",
206705
- "\r\n\r\n[LIOP-PROTO-V1:",
206706
- "\n[LIOP-PROTO-V1:"
206707
- // rare
206708
- ];
206709
- for (const m of markers) {
206710
- const i = d.indexOf(m);
206711
- if (i !== -1) {
206712
- d = d.slice(0, i);
206713
- break;
206714
- }
206715
- }
206716
- return d.trimEnd();
206717
- }
206718
-
206719
- // src/gateway/router.ts
206720
- var MANIFEST_CACHE_TTL_S = 300;
206721
- var MANIFEST_DISCOVERY_RETRIES = 5;
206722
- var LiopMcpRouter = class _LiopMcpRouter {
206723
- constructor(liopServer, meshNode = null, defaultRpcPort = 50051) {
206724
- this.liopServer = liopServer;
206725
- this.meshNode = meshNode;
206726
- this.defaultRpcPort = defaultRpcPort;
206727
- if (this.meshNode) {
206728
- this.meshNode.registerManifestHandler(() => {
206729
- const remoteTools = this.liopServer.listTools().map((t) => ({
206730
- name: t.name,
206731
- description: t.description,
206732
- inputSchema: t.inputSchema
206733
- }));
206734
- const resources = this.liopServer.listResources().map((r) => ({
206735
- name: r.name,
206736
- uri: r.uri,
206737
- description: r.description,
206738
- mimeType: r.mimeType
206739
- }));
206740
- const serverConfig = this.liopServer.config;
206741
- return {
206742
- peerId: this.meshNode?.getPeerId() || "unknown",
206743
- grpcPort: this.defaultRpcPort,
206744
- tools: [...remoteTools],
206745
- resources,
206746
- serverInfo: this.liopServer.getServerInfo(),
206747
- authRequired: this.liopServer.jwtValidator !== void 0,
206748
- tokenSlug: serverConfig?.tokenSlug,
206749
- taxonomy: serverConfig?.taxonomy ? {
206750
- domain: serverConfig.taxonomy.domain || "Unknown Domain",
206751
- clearanceTier: serverConfig.taxonomy.clearanceTier ?? 0,
206752
- executionTypes: serverConfig.taxonomy.executionTypes || []
206753
- } : void 0
206754
- };
206755
- });
206756
- this.meshNode.announceManifest().catch((err) => {
206757
- log.info(
206758
- `[LIOP-Router] Failed to announce manifest: ${err instanceof Error ? err.message : String(err)}`
206759
- );
206760
- });
206761
- }
206762
- if (process.env.LIOP_DIAGNOSTIC_LEVEL === "full") {
206763
- process.stderr.write(
206764
- "\u26A0\uFE0F [LIOP-Security] Diagnostic level set to FULL \u2014 PeerIDs and network topology are exposed. Do NOT use in production.\n"
206765
- );
206766
- }
206767
- }
206768
- liopServer;
206769
- meshNode;
206770
- defaultRpcPort;
206771
- /** Cached manifests from remote peers. Key = PeerID */
206772
- manifestCache = /* @__PURE__ */ new Map();
206773
- /** Guards against concurrent discovery storms */
206774
- currentDiscovery = null;
206775
- /** Verifier for Tier-0 integrity checks */
206776
- verifier = new LiopVerifier();
206777
- /** Callback when new remote tools are discovered */
206778
- onToolsChanged;
206779
- /** Circuit-breaker state for peers that repeatedly fail manifest queries. */
206780
- manifestFailureState = /* @__PURE__ */ new Map();
206781
- static MANIFEST_FAILURE_BASE_COOLDOWN_MS = 15e3;
206782
- static MANIFEST_FAILURE_MAX_COOLDOWN_MS = 5 * 6e4;
206783
- static MANIFEST_SKIP_LOG_THROTTLE_MS = 3e4;
206784
- getManifestCacheSize() {
206785
- return this.manifestCache.size;
206786
- }
206787
- shouldSkipManifestQuery(peerId) {
206788
- const state = this.manifestFailureState.get(peerId);
206789
- if (!state) return false;
206790
- const now = Date.now();
206791
- if (now >= state.cooldownUntil) return false;
206792
- if (now - state.lastSkipLogAt > _LiopMcpRouter.MANIFEST_SKIP_LOG_THROTTLE_MS) {
206793
- log.info(
206794
- `[LIOP-Router] Skipping manifest query for ${peerId} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1e3)}s remaining)`
206795
- );
206796
- state.lastSkipLogAt = now;
206797
- }
206798
- return true;
206799
- }
206800
- recordManifestQuerySuccess(peerId) {
206801
- this.manifestFailureState.delete(peerId);
206802
- }
206803
- recordManifestQueryFailure(peerId) {
206804
- const now = Date.now();
206805
- const prev = this.manifestFailureState.get(peerId);
206806
- const failures = (prev?.failures || 0) + 1;
206807
- const backoff = Math.min(
206808
- _LiopMcpRouter.MANIFEST_FAILURE_BASE_COOLDOWN_MS * 2 ** Math.max(0, failures - 1),
206809
- _LiopMcpRouter.MANIFEST_FAILURE_MAX_COOLDOWN_MS
206714
+ var isTlsEnforced = () => process.env.NODE_ENV === "production" || process.env.LIOP_ENFORCE_TLS === "true";
206715
+ var isTlsWarningSuppressed = (tls) => tls?.insecure === true || tls?.suppressWarning === true || process.env.LIOP_SUPPRESS_TLS_WARNING === "true";
206716
+ var hasWarnedInsecureServer = false;
206717
+ var hasWarnedInsecureChannel = false;
206718
+ function createServerCredentials(tls) {
206719
+ if (tls?.mutualTls && !tls.rootCert && !tls.certManager?.getRootCert()) {
206720
+ throw new Error(
206721
+ "[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but no root CA certificate (rootCert) provided to verify client certificates."
206810
206722
  );
206811
- this.manifestFailureState.set(peerId, {
206812
- failures,
206813
- cooldownUntil: now + backoff,
206814
- lastSkipLogAt: 0
206815
- });
206816
206723
  }
206817
- /**
206818
- * Detects the protocol era of an incoming request.
206819
- * Modern requests carry '_meta' with protocol version "2026-07-28" or use modern RPCs.
206820
- * Legacy requests use 'initialize' handshake or lack '_meta' envelopes.
206821
- */
206822
- detectEra(request) {
206823
- const params = request.params;
206824
- const meta = params?._meta;
206825
- const version = meta?.["io.modelcontextprotocol/protocolVersion"];
206826
- if (version === MCP_PROTOCOL_VERSION) {
206827
- return "modern";
206828
- }
206829
- if (MCP_LEGACY_SUPPORT_ENABLED && isLegacyRequest(request)) {
206830
- return "legacy";
206831
- }
206832
- return "modern";
206833
- }
206834
- async dispatch(request, authInfo) {
206835
- const { method, params, id } = request;
206836
- log.info(`[LIOP-Router] Processing: ${method}`);
206837
- if (this.liopServer.jwtValidator) {
206838
- const authResult = authorizeRequest(method, authInfo ?? null);
206839
- if (!authResult.allowed) {
206840
- log.info(
206841
- `[LIOP-Router] RBAC Access Denied for method '${method}': ${authResult.reason}`
206842
- );
206843
- return {
206844
- jsonrpc: "2.0",
206845
- id,
206846
- error: {
206847
- code: -32099,
206848
- // Custom authentication/authorization failure code
206849
- message: authResult.reason || "Access Denied"
206850
- }
206851
- };
206852
- }
206853
- }
206854
- switch (method) {
206855
- /** @mcp-legacy Initialize handshake for 2025-era clients. Remove when v1 EOL. */
206856
- case "initialize": {
206857
- if (!MCP_LEGACY_SUPPORT_ENABLED) {
206858
- return {
206859
- jsonrpc: "2.0",
206860
- id,
206861
- error: {
206862
- code: -32601,
206863
- message: "Method retired: initialize (MCP 2026-07-28 is stateless)"
206864
- }
206865
- };
206866
- }
206867
- log.info(
206868
- "[LIOP-Router] \u26A0\uFE0F Legacy MCP client detected (2025-era initialize)."
206869
- );
206870
- return buildLegacyInitializeResponse(
206871
- this.liopServer.getServerInfo(),
206872
- id
206873
- );
206874
- }
206875
- /** @mcp-legacy Initialized notification for 2025-era clients. Remove when v1 EOL. */
206876
- case "notifications/initialized":
206877
- if (!MCP_LEGACY_SUPPORT_ENABLED) return null;
206878
- this.kickDiscoveryAfterInitialized().catch(() => {
206879
- });
206880
- return null;
206881
- case "notifications/cancelled":
206882
- return null;
206883
- // No-op for MCP spec compliance
206884
- case "server/discover":
206885
- return {
206886
- jsonrpc: "2.0",
206887
- id,
206888
- result: {
206889
- resultType: "complete",
206890
- supportedVersions: MCP_LEGACY_SUPPORT_ENABLED ? [MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY] : [MCP_PROTOCOL_VERSION],
206891
- capabilities: {
206892
- tools: { listChanged: true },
206893
- resources: { listChanged: true },
206894
- prompts: { listChanged: true }
206895
- },
206896
- serverInfo: this.liopServer.getServerInfo()
206897
- }
206898
- };
206899
- case "ping":
206900
- return { jsonrpc: "2.0", id, result: {} };
206901
- case "tools/list": {
206902
- const localTools = this.liopServer.listTools();
206903
- const remoteTools = await this.getRemoteTools();
206904
- const listedLocals = mcpCompactToolDescriptions() ? localTools.map((t) => ({
206905
- ...t,
206906
- description: stripVerboseLiopToolDescription(t.description ?? "")
206907
- })) : localTools;
206908
- log.info(
206909
- `[LIOP-Router] tools/list: ${localTools.length} local, ${remoteTools.length} remote tools found`
206910
- );
206911
- const diagnosticTool = {
206912
- name: "LiopMeshStatus",
206913
- description: "LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",
206914
- inputSchema: {
206915
- type: "object",
206916
- properties: {},
206917
- additionalProperties: false
206918
- }
206919
- };
206920
- const allTools = [diagnosticTool, ...listedLocals, ...remoteTools].sort(
206921
- (a, b) => a.name.localeCompare(b.name)
206922
- );
206923
- const telemetry = TokenTelemetryEngine.getInstance();
206924
- const toolsPayload = JSON.stringify(allTools);
206925
- const toolsResponsePayload = JSON.stringify({ tools: allTools });
206926
- telemetry.record({
206927
- type: "tools_list",
206928
- method: "tools/list",
206929
- estimatedInputTokens: telemetry.countTokens(toolsPayload),
206930
- estimatedOutputTokens: telemetry.countTokens(toolsResponsePayload)
206931
- });
206932
- const era = this.detectEra(request);
206933
- let response = {
206934
- jsonrpc: "2.0",
206935
- id,
206936
- result: {
206937
- resultType: "complete",
206938
- ttlMs: 3e5,
206939
- cacheScope: "public",
206940
- tools: allTools
206941
- }
206942
- };
206943
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
206944
- response = adaptResponseForLegacyClient(response);
206945
- }
206946
- return response;
206947
- }
206948
- case "tools/call": {
206949
- const response = await this.transcodeMcpToLiop(
206950
- id,
206951
- params,
206952
- authInfo?.token
206953
- );
206954
- if (!response) return null;
206955
- const era = this.detectEra(request);
206956
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
206957
- return adaptResponseForLegacyClient(response);
206958
- }
206959
- if (response.result && typeof response.result === "object") {
206960
- const resObj = response.result;
206961
- if (!resObj.resultType) {
206962
- resObj.resultType = "complete";
206963
- }
206964
- }
206965
- return response;
206966
- }
206967
- case "resources/list": {
206968
- const localResources = this.liopServer.listResources();
206969
- const remoteResources = await this.getRemoteResources();
206970
- const allResources = [...localResources, ...remoteResources].sort(
206971
- (a, b) => a.uri.localeCompare(b.uri)
206724
+ if (tls?.certManager) {
206725
+ try {
206726
+ const certChain = tls.certManager.getCertChain();
206727
+ const privateKey = tls.certManager.getPrivateKey();
206728
+ const rootCert = tls.certManager.getRootCert();
206729
+ if (tls.mutualTls && !rootCert) {
206730
+ throw new Error(
206731
+ "[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but CertManager has no root CA certificate loaded."
206972
206732
  );
206973
- const rlTelemetry = TokenTelemetryEngine.getInstance();
206974
- const rlPayload = JSON.stringify(allResources);
206975
- rlTelemetry.record({
206976
- type: "resource_list",
206977
- method: "resources/list",
206978
- estimatedInputTokens: 0,
206979
- estimatedOutputTokens: rlTelemetry.countTokens(rlPayload)
206980
- });
206981
- const era = this.detectEra(request);
206982
- let response = {
206983
- jsonrpc: "2.0",
206984
- id,
206985
- result: {
206986
- resultType: "complete",
206987
- ttlMs: 3e5,
206988
- cacheScope: "public",
206989
- resources: allResources
206990
- }
206991
- };
206992
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
206993
- response = adaptResponseForLegacyClient(response);
206994
- }
206995
- return response;
206996
- }
206997
- case "resources/read": {
206998
- const typedParams = params;
206999
- if (!typedParams?.uri)
207000
- return {
207001
- jsonrpc: "2.0",
207002
- id,
207003
- error: { code: -32602, message: "Missing resource uri" }
207004
- };
207005
- try {
207006
- const rrStartTime = Date.now();
207007
- const result = await this.liopServer.readResource(typedParams.uri);
207008
- const rrTelemetry = TokenTelemetryEngine.getInstance();
207009
- const rrOutputPayload = JSON.stringify(result);
207010
- rrTelemetry.record({
207011
- type: "resource_read",
207012
- method: "resources/read",
207013
- toolName: typedParams.uri,
207014
- estimatedInputTokens: rrTelemetry.countTokens(typedParams.uri),
207015
- estimatedOutputTokens: rrTelemetry.countTokens(rrOutputPayload),
207016
- durationMs: Date.now() - rrStartTime
207017
- });
207018
- const era = this.detectEra(request);
207019
- const rawResult = typeof result === "object" && result !== null ? {
207020
- resultType: "complete",
207021
- ttlMs: 6e4,
207022
- cacheScope: "private",
207023
- ...result
207024
- } : {
207025
- resultType: "complete",
207026
- ttlMs: 6e4,
207027
- cacheScope: "private",
207028
- contents: result
207029
- };
207030
- let response = { jsonrpc: "2.0", id, result: rawResult };
207031
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
207032
- response = adaptResponseForLegacyClient(response);
207033
- }
207034
- return response;
207035
- } catch (err) {
207036
- const targetUri = typedParams.uri;
207037
- for (const { manifest } of this.manifestCache.values()) {
207038
- const remoteResource = manifest.resources.find(
207039
- (r) => r.uri === targetUri
207040
- );
207041
- if (remoteResource) {
207042
- log.info(
207043
- `[LIOP-Router] Resolved resource ${targetUri} from cache (Peer: ${manifest.peerId})`
207044
- );
207045
- const era = this.detectEra(request);
207046
- let response = {
207047
- jsonrpc: "2.0",
207048
- id,
207049
- result: {
207050
- resultType: "complete",
207051
- ttlMs: 6e4,
207052
- cacheScope: "private",
207053
- contents: [
207054
- {
207055
- uri: remoteResource.uri,
207056
- mimeType: remoteResource.mimeType || "text/plain",
207057
- text: remoteResource.text || remoteResource.description || "No content provided"
207058
- }
207059
- ]
207060
- }
207061
- };
207062
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
207063
- response = adaptResponseForLegacyClient(response);
207064
- }
207065
- return response;
207066
- }
207067
- }
207068
- return {
207069
- jsonrpc: "2.0",
207070
- id,
207071
- error: {
207072
- code: -32e3,
207073
- message: err instanceof Error ? err.message : String(err)
207074
- }
207075
- };
207076
- }
207077
- }
207078
- case "prompts/list": {
207079
- const promptsList = this.liopServer.listPrompts().sort((a, b) => a.name.localeCompare(b.name));
207080
- const plTelemetry = TokenTelemetryEngine.getInstance();
207081
- const plPayload = JSON.stringify(promptsList);
207082
- plTelemetry.record({
207083
- type: "prompt_list",
207084
- method: "prompts/list",
207085
- estimatedInputTokens: 0,
207086
- estimatedOutputTokens: plTelemetry.countTokens(plPayload)
207087
- });
207088
- const era = this.detectEra(request);
207089
- let response = {
207090
- jsonrpc: "2.0",
207091
- id,
207092
- result: {
207093
- resultType: "complete",
207094
- ttlMs: 3e5,
207095
- cacheScope: "public",
207096
- prompts: promptsList
207097
- }
207098
- };
207099
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
207100
- response = adaptResponseForLegacyClient(response);
207101
- }
207102
- return response;
207103
- }
207104
- case "prompts/get": {
207105
- const typedParams = params;
207106
- if (!typedParams?.name)
207107
- return {
207108
- jsonrpc: "2.0",
207109
- id,
207110
- error: { code: -32602, message: "Missing prompt name" }
207111
- };
207112
- try {
207113
- const pgStartTime = Date.now();
207114
- const result = await this.liopServer.getPrompt({
207115
- name: typedParams.name,
207116
- arguments: typedParams.arguments || {}
207117
- });
207118
- const pgTelemetry = TokenTelemetryEngine.getInstance();
207119
- const pgInputPayload = JSON.stringify({
207120
- name: typedParams.name,
207121
- arguments: typedParams.arguments
207122
- });
207123
- const pgOutputPayload = JSON.stringify(result);
207124
- pgTelemetry.record({
207125
- type: "prompt_get",
207126
- method: "prompts/get",
207127
- toolName: typedParams.name,
207128
- estimatedInputTokens: pgTelemetry.countTokens(pgInputPayload),
207129
- estimatedOutputTokens: pgTelemetry.countTokens(pgOutputPayload),
207130
- durationMs: Date.now() - pgStartTime
207131
- });
207132
- const era = this.detectEra(request);
207133
- const rawResult = typeof result === "object" && result !== null ? { resultType: "complete", ...result } : result;
207134
- let response = { jsonrpc: "2.0", id, result: rawResult };
207135
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
207136
- response = adaptResponseForLegacyClient(response);
207137
- }
207138
- return response;
207139
- } catch (err) {
207140
- return {
207141
- jsonrpc: "2.0",
207142
- id,
207143
- error: {
207144
- code: -32e3,
207145
- message: err instanceof Error ? err.message : String(err)
207146
- }
207147
- };
207148
- }
207149
206733
  }
207150
- case "resources/templates/list": {
207151
- const era = this.detectEra(request);
207152
- let response = {
207153
- jsonrpc: "2.0",
207154
- id,
207155
- result: {
207156
- resultType: "complete",
207157
- ttlMs: 3e5,
207158
- cacheScope: "public",
207159
- resourceTemplates: []
207160
- }
207161
- };
207162
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
207163
- response = adaptResponseForLegacyClient(response);
207164
- }
207165
- return response;
207166
- }
207167
- case "subscriptions/listen": {
207168
- const era = this.detectEra(request);
207169
- let response = {
207170
- jsonrpc: "2.0",
207171
- id,
207172
- result: {
207173
- resultType: "complete"
207174
- }
207175
- };
207176
- if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
207177
- response = adaptResponseForLegacyClient(response);
207178
- }
207179
- return response;
207180
- }
207181
- default:
207182
- return {
207183
- jsonrpc: "2.0",
207184
- id,
207185
- error: { code: -32601, message: `Method not found: ${method}` }
207186
- };
207187
- }
207188
- }
207189
- /**
207190
- * MCP clients often send notifications/initialized then immediately tools/list.
207191
- * Start manifest discovery without blocking the notification handler.
207192
- */
207193
- kickDiscoveryAfterInitialized() {
207194
- return (async () => {
207195
- await new Promise((r) => setTimeout(r, 250));
207196
- await Promise.race([
207197
- this.refreshManifestCache(true),
207198
- new Promise((r) => setTimeout(r, 15e3))
207199
- ]).catch(() => {
207200
- });
207201
- })();
207202
- }
207203
- /**
207204
- * Discovers and caches manifests from all remote LIOP providers in the mesh.
207205
- * Uses Kademlia DHT to find "liop:manifest" providers, then opens
207206
- * /liop/manifest/1.0.0 protocol streams to retrieve their full metadata.
207207
- */
207208
- async refreshManifestCache(silent = false) {
207209
- if (!this.meshNode) return;
207210
- if (this.currentDiscovery) return this.currentDiscovery;
207211
- if (!silent && this.manifestCache.size > 0) {
207212
- const now = Date.now();
207213
- const allFresh = Array.from(this.manifestCache.values()).every(
207214
- ({ cachedAt }) => now - cachedAt < MANIFEST_CACHE_TTL_S * 1e3
206734
+ return grpc.ServerCredentials.createSsl(
206735
+ rootCert,
206736
+ [{ cert_chain: certChain, private_key: privateKey }],
206737
+ Boolean(tls.mutualTls)
207215
206738
  );
207216
- if (allFresh) return;
207217
- }
207218
- this.currentDiscovery = (async () => {
207219
- try {
207220
- const prevCount = Array.from(this.manifestCache.values()).reduce(
207221
- (acc, { manifest }) => acc + manifest.tools.length,
207222
- 0
206739
+ } catch (error) {
206740
+ if (isTlsEnforced()) {
206741
+ throw new Error(
206742
+ `[LIOP-TLS] FATAL: CertManager server credential creation failed in enforced mode: ${error}`
207223
206743
  );
207224
- if (this.manifestCache.size === 0) {
207225
- for (let i = 0; i < 3; i++) {
207226
- const connections = (
207227
- // biome-ignore lint/suspicious/noExplicitAny: access internal nodes for connection count
207228
- this.meshNode.node?.getConnections().length || 0
207229
- );
207230
- if (connections > 0) {
207231
- log.info(
207232
- `[LIOP-Router] P2P Connection established. Starting discovery...`
207233
- );
207234
- break;
207235
- }
207236
- log.info(
207237
- `[LIOP-Router] Waiting for P2P connections (attempt ${i + 1}/10)...`
207238
- );
207239
- await new Promise((r) => setTimeout(r, 1e3));
207240
- }
207241
- }
207242
- let providerIds = [];
207243
- const MAX_COLD_ATTEMPTS = this.manifestCache.size === 0 ? 5 : 1;
207244
- for (let coldAttempt = 0; coldAttempt < MAX_COLD_ATTEMPTS; coldAttempt++) {
207245
- for (let attempt = 0; attempt < MANIFEST_DISCOVERY_RETRIES; attempt++) {
207246
- providerIds = await this.meshNode?.discoverManifestProviders() || [];
207247
- const selfId2 = this.meshNode?.getPeerId();
207248
- const remoteIds = providerIds.filter((id) => id !== selfId2);
207249
- if (remoteIds.length > 0) break;
207250
- if (attempt < MANIFEST_DISCOVERY_RETRIES - 1) {
207251
- log.info(
207252
- `[LIOP-Router] DHT discovery attempt ${attempt + 1}/${MANIFEST_DISCOVERY_RETRIES}...`
207253
- );
207254
- await new Promise((r) => setTimeout(r, 1e3));
207255
- }
207256
- }
207257
- const activePeers = (
207258
- // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
207259
- this.meshNode.node?.getConnections().map(
207260
- (c) => c.remotePeer.toString()
207261
- ) || []
207262
- );
207263
- if (activePeers.length > 0) {
207264
- providerIds = Array.from(/* @__PURE__ */ new Set([...providerIds, ...activePeers]));
207265
- }
207266
- const selfIdEnd = this.meshNode?.getPeerId();
207267
- const remoteIdsEnd = providerIds.filter((id) => id !== selfIdEnd);
207268
- if (remoteIdsEnd.length > 0) break;
207269
- if (coldAttempt < MAX_COLD_ATTEMPTS - 1) {
207270
- log.info(
207271
- `[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${coldAttempt + 1}/${MAX_COLD_ATTEMPTS})...`
207272
- );
207273
- await new Promise((r) => setTimeout(r, 1e3));
207274
- }
207275
- }
207276
- if (providerIds.length === 0) {
207277
- log.info(
207278
- `[LIOP-Router] No manifest providers found after all attempts.`
207279
- );
207280
- return;
207281
- }
207282
- if (!silent) {
207283
- log.info(
207284
- `[LIOP-Router] Discovered ${providerIds.length} candidate manifest providers`
207285
- );
207286
- }
207287
- const connectedPeers = new Set(
207288
- // biome-ignore lint/suspicious/noExplicitAny: internal node access for fast peer ordering
207289
- (this.meshNode.node?.getConnections?.() || []).map(
207290
- (c) => c.remotePeer.toString()
207291
- )
207292
- );
207293
- providerIds = [...providerIds].sort((a, b) => {
207294
- const aConnected = connectedPeers.has(a) ? 1 : 0;
207295
- const bConnected = connectedPeers.has(b) ? 1 : 0;
207296
- return bConnected - aConnected;
207297
- });
207298
- let successCount = 0;
207299
- let errorCount = 0;
207300
- let cacheUpdated = false;
207301
- const selfId = this.meshNode?.getPeerId();
207302
- const eligiblePeers = providerIds.filter((peerId) => {
207303
- if (!this.meshNode) return false;
207304
- if (peerId === selfId) return false;
207305
- if (this.shouldSkipManifestQuery(peerId)) return false;
207306
- const cached = this.manifestCache.get(peerId);
207307
- if (cached && Date.now() - cached.cachedAt < MANIFEST_CACHE_TTL_S * 1e3) {
207308
- successCount++;
207309
- return false;
207310
- }
207311
- return true;
207312
- });
207313
- const queryResults = await Promise.allSettled(
207314
- eligiblePeers.map(async (peerId) => {
207315
- if (!this.meshNode) return null;
207316
- log.info(`[LIOP-Router] Querying manifest from: ${peerId}`);
207317
- return {
207318
- peerId,
207319
- manifest: await this.meshNode.queryManifest(peerId)
207320
- };
207321
- })
207322
- );
207323
- for (const result of queryResults) {
207324
- if (result.status === "fulfilled" && result.value?.manifest) {
207325
- const { peerId, manifest } = result.value;
207326
- if (manifest.pqcSignature && manifest.pqcPublicKey) {
207327
- const isValid = Dilithium65Wrapper.verifyManifest(
207328
- manifest,
207329
- manifest.pqcSignature,
207330
- manifest.pqcPublicKey
207331
- );
207332
- if (!isValid) {
207333
- log.warn(
207334
- `[LIOP-Router] \u26A0\uFE0F Tampered manifest rejected for peer ${peerId} (ML-DSA-65 signature invalid)`
207335
- );
207336
- this.recordManifestQueryFailure(peerId);
207337
- errorCount++;
207338
- continue;
207339
- }
207340
- log.info(
207341
- `[LIOP-Router] \u{1F512} ML-DSA-65 (FIPS 204) Manifest attestation verified for peer ${peerId}`
207342
- );
207343
- }
207344
- this.manifestCache.set(peerId, {
207345
- manifest,
207346
- cachedAt: Date.now()
207347
- });
207348
- this.recordManifestQuerySuccess(peerId);
207349
- cacheUpdated = true;
207350
- successCount++;
207351
- log.info(
207352
- `[LIOP-Router] Manifest received from ${peerId} (${manifest.tools.length} tools)`
207353
- );
207354
- } else if (result.status === "fulfilled" && result.value) {
207355
- this.recordManifestQueryFailure(result.value.peerId);
207356
- errorCount++;
207357
- log.info(
207358
- `[LIOP-Router] Manifest query returned NULL for ${result.value.peerId}`
207359
- );
207360
- } else if (result.status === "rejected") {
207361
- errorCount++;
207362
- log.info(
207363
- `[LIOP-Router] Fatal error querying manifest:`,
207364
- result.reason instanceof Error ? result.reason.message : String(result.reason)
207365
- );
207366
- }
207367
- }
207368
- this._discoveryStats = {
207369
- candidates: providerIds.length,
207370
- success: successCount,
207371
- failures: errorCount,
207372
- lastDiscovery: Date.now()
207373
- };
207374
- if (cacheUpdated) {
207375
- const newCount = Array.from(this.manifestCache.values()).reduce(
207376
- (acc, { manifest }) => acc + manifest.tools.length,
207377
- 0
207378
- );
207379
- if (newCount !== prevCount && this.onToolsChanged) {
207380
- process.stderr.write(
207381
- "[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.\n"
207382
- );
207383
- this.onToolsChanged();
207384
- }
207385
- }
207386
- } finally {
207387
- this.currentDiscovery = null;
207388
206744
  }
207389
- })();
207390
- return this.currentDiscovery;
207391
- }
207392
- /**
207393
- * Returns the current manifest cache size for external telemetry.
207394
- * Used by the adaptive polling system to detect topology stabilization.
207395
- */
207396
- getCacheSize() {
207397
- return this.manifestCache.size;
207398
- }
207399
- /**
207400
- * Returns all remote tools discovered via the manifest protocol.
207401
- */
207402
- async getRemoteTools() {
207403
- const EXPECTED_PROVIDERS = Number.parseInt(
207404
- process.env.LIOP_EXPECTED_PROVIDERS ?? "1",
207405
- 10
207406
- );
207407
- if (this.manifestCache.size < EXPECTED_PROVIDERS && this.meshNode) {
207408
- const initialTimeoutMs = Number.parseInt(
207409
- process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS ?? "8000",
207410
- 10
206745
+ log.warn(
206746
+ `[LIOP-TLS] CertManager failed, falling back to insecure: ${error}`
207411
206747
  );
207412
- const boundedTimeoutMs = Number.isFinite(initialTimeoutMs) && initialTimeoutMs > 0 ? initialTimeoutMs : 12e3;
207413
- const deadline = Date.now() + boundedTimeoutMs;
207414
- let stableCount = 0;
207415
- let lastCacheSize = -1;
207416
- while (Date.now() < deadline) {
207417
- if (this.manifestCache.size >= EXPECTED_PROVIDERS) break;
207418
- await Promise.race([
207419
- this.refreshManifestCache(true),
207420
- new Promise((resolve) => setTimeout(resolve, 3e3))
207421
- ]).catch(() => {
207422
- });
207423
- if (this.manifestCache.size >= EXPECTED_PROVIDERS) break;
207424
- if (this.manifestCache.size === lastCacheSize) {
207425
- stableCount++;
207426
- if (stableCount >= 3 && this.manifestCache.size > 0) {
207427
- log.info(
207428
- `[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${EXPECTED_PROVIDERS}. Proceeding with available mesh.`
207429
- );
207430
- break;
207431
- }
207432
- } else {
207433
- stableCount = 0;
207434
- lastCacheSize = this.manifestCache.size;
207435
- }
207436
- await new Promise((r) => setTimeout(r, 1e3));
207437
- }
207438
- if (this.manifestCache.size < EXPECTED_PROVIDERS) {
207439
- log.info(
207440
- `[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${EXPECTED_PROVIDERS} providers. Some tools may be unavailable. Check Docker containers.`
207441
- );
207442
- this.refreshManifestCache(true).catch(() => {
207443
- });
207444
- }
206748
+ return grpc.ServerCredentials.createInsecure();
207445
206749
  }
207446
- const tools = [];
207447
- const seenNames = /* @__PURE__ */ new Set();
207448
- const localToolNames = new Set(
207449
- this.liopServer.listTools().map((t) => t.name)
207450
- );
207451
- for (const [peerId, { manifest }] of this.manifestCache.entries()) {
207452
- for (const tool of manifest.tools) {
207453
- if (tool.name === "LiopMeshStatus") continue;
207454
- let finalName = tool.name;
207455
- if (seenNames.has(tool.name) || localToolNames.has(tool.name)) {
207456
- finalName = `${tool.name}_${peerId.slice(-4)}`;
207457
- }
207458
- seenNames.add(finalName);
207459
- const providerName = manifest.serverInfo?.name || "Unknown Provider";
207460
- const baseDesc = tool.description || `Remote tool from ${providerName}`;
207461
- const cleanTool = {
207462
- name: finalName,
207463
- description: mcpCompactToolDescriptions() ? stripVerboseLiopToolDescription(baseDesc) : baseDesc,
207464
- inputSchema: tool.inputSchema || {
207465
- type: "object",
207466
- properties: {}
207467
- }
207468
- };
207469
- if (typeof cleanTool.inputSchema === "object" && !cleanTool.inputSchema.type) {
207470
- cleanTool.inputSchema.type = "object";
207471
- }
207472
- if (typeof cleanTool.inputSchema === "object" && !cleanTool.inputSchema.properties) {
207473
- cleanTool.inputSchema.properties = {};
207474
- }
207475
- let blueprint = "";
207476
- if (manifest.taxonomy) {
207477
- blueprint = `
207478
- [LIOP-DOMAIN: ${manifest.taxonomy.domain}]`;
207479
- }
207480
- const properties = cleanTool.inputSchema.properties || {};
207481
- let envelopeDoc = "";
207482
- if (!mcpCompactToolDescriptions() && properties.payload) {
207483
- envelopeDoc = `
207484
- [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`;
207485
- }
207486
- if (!mcpCompactToolDescriptions() && cleanTool.description.includes("STRICT SCHEMA ADHERENCE")) {
207487
- cleanTool.description = cleanTool.description.replace(
207488
- "STRICT SCHEMA ADHERENCE:",
207489
- "[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"
207490
- );
207491
- }
207492
- const originStamp = mcpCompactToolDescriptions() ? `
207493
- (Peer: ${peerId.slice(-8)})${blueprint}` : `
207494
- (Origin: ${peerId.slice(-8)})${blueprint}${envelopeDoc}`;
207495
- cleanTool.description = `${cleanTool.description}${originStamp}`;
207496
- tools.push(cleanTool);
207497
- }
207498
- }
207499
- return tools;
207500
- }
207501
- /**
207502
- * Returns all remote resources discovered via the manifest protocol.
207503
- */
207504
- async getRemoteResources() {
207505
- if (!this.currentDiscovery) {
207506
- this.refreshManifestCache(true).catch(() => {
207507
- });
207508
- }
207509
- const resources = [];
207510
- const seenUris = new Set(this.liopServer.listResources().map((r) => r.uri));
207511
- for (const [peerId, { manifest }] of this.manifestCache.entries()) {
207512
- for (const resource of manifest.resources) {
207513
- if (!seenUris.has(resource.uri)) {
207514
- const augmentedResource = { ...resource };
207515
- const providerName = manifest.serverInfo?.name || "Unknown Provider";
207516
- let blueprint = "";
207517
- if (manifest.taxonomy) {
207518
- blueprint = `
207519
-
207520
- [LIOP Zero-Trust Blueprint]
207521
- Domain: ${manifest.taxonomy.domain}
207522
- Clearance Tier: ${manifest.taxonomy.clearanceTier}`;
207523
- if (manifest.taxonomy.executionTypes && manifest.taxonomy.executionTypes.length > 0) {
207524
- blueprint += `
207525
- Execution Types: ${manifest.taxonomy.executionTypes.join(", ")}`;
207526
- }
207527
- }
207528
- const originStamp = `
207529
-
207530
- [LIOP Zero-Trust Origin]
207531
- Provider: ${providerName}
207532
- Network ID: ${peerId}${blueprint}`;
207533
- if (augmentedResource.uri.startsWith("liop://schema/")) {
207534
- augmentedResource.name = `[SCHEMA] ${augmentedResource.name}`;
207535
- augmentedResource.description = `[CRITICAL SCHEMA] ${augmentedResource.description || "Data Dictionary for Zero-Shot Autonomy"}${originStamp}`;
207536
- } else {
207537
- augmentedResource.description = augmentedResource.description ? `${augmentedResource.description}${originStamp}` : originStamp.trim();
207538
- }
207539
- resources.push(augmentedResource);
207540
- seenUris.add(resource.uri);
207541
- }
207542
- }
207543
- }
207544
- return resources;
207545
- }
207546
- /**
207547
- * Resolves the gRPC target (host:port) AND the peerId for a given tool name
207548
- * by searching the manifest cache. Supports exact names and suffixed names.
207549
- */
207550
- resolveManifestTarget(toolName) {
207551
- for (const [peerId, { manifest }] of this.manifestCache.entries()) {
207552
- const tool = manifest.tools.find((t) => t.name === toolName);
207553
- if (tool) {
207554
- return {
207555
- peerId,
207556
- originalToolName: toolName
207557
- };
207558
- }
207559
- }
207560
- const parts = toolName.split("_");
207561
- if (parts.length > 1) {
207562
- const suffix = parts.pop();
207563
- const baseName = parts.join("_");
207564
- for (const [peerId, { manifest }] of this.manifestCache.entries()) {
207565
- if (peerId.endsWith(suffix || "")) {
207566
- const tool = manifest.tools.find((t) => t.name === baseName);
207567
- if (tool) {
207568
- return {
207569
- peerId,
207570
- originalToolName: baseName
207571
- };
207572
- }
207573
- }
207574
- }
207575
- }
207576
- return null;
207577
206750
  }
207578
- /**
207579
- * Redacts a PeerID for external-facing diagnostics.
207580
- * LIOP_DIAGNOSTIC_LEVEL controls verbosity:
207581
- * - "redacted" (default): truncated to last 8 chars
207582
- * - "full": complete PeerID (development only)
207583
- */
207584
- redactPeerId(peerId) {
207585
- const level = process.env.LIOP_DIAGNOSTIC_LEVEL || "redacted";
207586
- if (level === "full") return peerId;
207587
- return `***${peerId.slice(-8)}`;
207588
- }
207589
- async transcodeMcpToLiop(id, params, token) {
207590
- const toolName = params.name;
207591
- if (toolName === "LiopMeshStatus") {
207592
- this.refreshManifestCache(true).catch(() => {
207593
- });
207594
- const stats = this._discoveryStats || {
207595
- candidates: 0,
207596
- success: 0,
207597
- failures: 0
207598
- };
207599
- const providerCount = this.manifestCache.size;
207600
- const meshState = this.meshNode ? "Active" : "Offline";
207601
- const cachedTools = Array.from(this.manifestCache.values()).reduce(
207602
- (acc, { manifest }) => acc + manifest.tools.length,
207603
- 0
206751
+ if (!tls?.certChain || !tls?.privateKey) {
206752
+ if (isTlsEnforced()) {
206753
+ throw new Error(
206754
+ "[LIOP-TLS] FATAL: TLS certificates required in production or when LIOP_ENFORCE_TLS=true."
207604
206755
  );
207605
- const connections = this.meshNode ? (
207606
- // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
207607
- this.meshNode.node?.getConnections().length
207608
- ) : 0;
207609
- const bootstrapNodes = this.meshNode && // biome-ignore lint/suspicious/noExplicitAny: access internal config
207610
- this.meshNode.config?.bootstrapNodes ? (
207611
- // biome-ignore lint/suspicious/noExplicitAny: access internal config
207612
- this.meshNode.config.bootstrapNodes
207613
- ) : [];
207614
- const bootstrapCount = bootstrapNodes.length;
207615
- const diagLevel = process.env.LIOP_DIAGNOSTIC_LEVEL || "redacted";
207616
- const showBootstraps = diagLevel !== "minimal";
207617
- const bootstrapList = showBootstraps ? bootstrapNodes.map((addr) => {
207618
- const parts = addr.split("/");
207619
- const id2 = parts[parts.length - 1];
207620
- return ` \u2022 ${id2 ? id2.slice(-8) : "Unknown"} (bootstrap)`;
207621
- }).join("\n") : "";
207622
- const routingTableSize = this.meshNode ? (
207623
- // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
207624
- this.meshNode.getRoutingTableSize()
207625
- ) : 0;
207626
- const rawPeerId = this.meshNode?.getPeerId() || "Offline";
207627
- const localPeerId = rawPeerId === "Offline" ? rawPeerId : this.redactPeerId(rawPeerId);
207628
- const cachedToolList = Array.from(this.manifestCache.entries()).flatMap(
207629
- ([peerId, { manifest }]) => manifest.tools.map(
207630
- (t) => ` \u2022 ${t.name} (from origin: ${this.redactPeerId(peerId)})`
207631
- )
207632
- ).join("\n");
207633
- const statusText = [
207634
- `LIOP Mesh Status: ${meshState === "Active" ? "Active" : "Offline"}`,
207635
- `Local Agent Identity: ${localPeerId}`,
207636
- `Network: ${connections} Conns | ${routingTableSize} Mesh Nodes | ${bootstrapCount} Bootstraps`,
207637
- showBootstraps && bootstrapCount > 0 ? `
207638
- Active Bootstraps:
207639
- ${bootstrapList}
207640
- ` : "",
207641
- `Discovery: ${stats.candidates} Candidates | ${stats.success} OK | ${stats.failures} FAIL`,
207642
- `Tooling: ${providerCount} Providers | ${cachedTools} Total Remote Tools`,
207643
- cachedTools > 0 ? `
207644
- Discovered Remote Tools (Zero-Trust Origins):
207645
- ${cachedToolList}` : "\nNo remote tools discovered yet.",
207646
- // [Token Economy] Telemetry block (only appears when operations exist)
207647
- TokenTelemetryEngine.getInstance().formatStatusBlock()
207648
- ].filter((line) => line !== "").join("\n");
207649
- const diagTelemetry = TokenTelemetryEngine.getInstance();
207650
- diagTelemetry.record({
207651
- type: "diagnostic",
207652
- method: "tools/call",
207653
- toolName: "LiopMeshStatus",
207654
- estimatedInputTokens: 0,
207655
- estimatedOutputTokens: diagTelemetry.countTokens(statusText)
207656
- });
207657
- return {
207658
- jsonrpc: "2.0",
207659
- id,
207660
- result: {
207661
- content: [
207662
- {
207663
- type: "text",
207664
- text: statusText
207665
- }
207666
- ]
207667
- }
207668
- };
207669
- }
207670
- const isLocal = this.liopServer.listTools().some((t) => t.name === toolName);
207671
- if (!isLocal && this.meshNode) {
207672
- let target = this.resolveManifestTarget(toolName);
207673
- if (!target) {
207674
- await this.refreshManifestCache();
207675
- target = this.resolveManifestTarget(toolName);
207676
- }
207677
- if (target) {
207678
- log.info(
207679
- `[LIOP-Router] Resolved ${toolName} via manifest cache (Peer: ${target.peerId}, Original: ${target.originalToolName})`
207680
- );
207681
- const manifestEntry = this.manifestCache.get(target.peerId);
207682
- let effectiveToken = token;
207683
- if (manifestEntry?.manifest.authRequired) {
207684
- const resolvedToken = token || await this.getOrAcquireMeshAgentToken(target.peerId);
207685
- if (!resolvedToken) {
207686
- const providerName = manifestEntry.manifest.serverInfo?.name?.toLowerCase() || "unknown";
207687
- const slug = manifestEntry.manifest.tokenSlug;
207688
- const shortId = target.peerId.slice(-8).toUpperCase();
207689
- const primaryVar = slug ? `LIOP_TOKEN_${slug}` : `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}`;
207690
- return {
207691
- jsonrpc: "2.0",
207692
- id,
207693
- result: {
207694
- content: [
207695
- {
207696
- type: "text",
207697
- text: `Authentication Required: The restricted node (${providerName}) requires an access token. Please define the ${primaryVar} or LIOP_TOKEN_${shortId} environment variable on your agent/client host.`
207698
- }
207699
- ],
207700
- isError: true
207701
- }
207702
- };
207703
- }
207704
- effectiveToken = resolvedToken;
207705
- }
207706
- return this.routeToRemoteProvider(
207707
- id,
207708
- target.originalToolName,
207709
- target.peerId,
207710
- params,
207711
- effectiveToken
207712
- );
207713
- }
207714
- let providers = [];
207715
- for (let i = 0; i < 3; i++) {
207716
- providers = await this.meshNode.findProviders(toolName);
207717
- if (providers.length > 0) break;
207718
- if (i < 2) await new Promise((r) => setTimeout(r, 1e3));
207719
- }
207720
- if (providers.length > 0) {
207721
- return this.routeToRemoteProvider(
207722
- id,
207723
- toolName,
207724
- providers[0],
207725
- params,
207726
- token
207727
- );
207728
- }
207729
206756
  }
207730
- if (isLocal) {
207731
- try {
207732
- const localStartTime = Date.now();
207733
- const result = await this.liopServer.callTool({
207734
- name: toolName,
207735
- arguments: params.arguments || {}
207736
- });
207737
- const localTelemetry = TokenTelemetryEngine.getInstance();
207738
- const localInputPayload = JSON.stringify(params.arguments || {});
207739
- const localOutputPayload = JSON.stringify(result);
207740
- localTelemetry.record({
207741
- type: "tool_call",
207742
- method: "tools/call",
207743
- toolName,
207744
- estimatedInputTokens: localTelemetry.countTokens(localInputPayload),
207745
- estimatedOutputTokens: localTelemetry.countTokens(localOutputPayload),
207746
- durationMs: Date.now() - localStartTime
207747
- });
207748
- return { jsonrpc: "2.0", id, result };
207749
- } catch (err) {
207750
- return {
207751
- jsonrpc: "2.0",
207752
- id,
207753
- error: {
207754
- code: -32e3,
207755
- message: err instanceof Error ? err.message : String(err)
207756
- }
207757
- };
207758
- }
206757
+ if (!isTlsWarningSuppressed(tls) && !hasWarnedInsecureServer) {
206758
+ hasWarnedInsecureServer = true;
206759
+ log.debug(
206760
+ "[LIOP-TLS] No TLS certificates configured \u2014 using insecure server credentials"
206761
+ );
207759
206762
  }
207760
- return {
207761
- jsonrpc: "2.0",
207762
- id,
207763
- error: {
207764
- code: -32002,
207765
- message: `No provider found for tool: ${toolName}. Ensure the provider node is active and connected to the mesh.`
207766
- }
207767
- };
206763
+ return grpc.ServerCredentials.createInsecure();
207768
206764
  }
207769
- async routeToRemoteProvider(id, toolName, peerId, params, token) {
207770
- if (!this.meshNode)
207771
- return {
207772
- jsonrpc: "2.0",
207773
- id,
207774
- error: { code: -32603, message: "Mesh Node inactive" }
207775
- };
207776
- let manifestEntry = this.manifestCache.get(peerId);
207777
- let grpcPort = this.defaultRpcPort;
207778
- if (manifestEntry) {
207779
- grpcPort = manifestEntry.manifest.grpcPort;
207780
- } else {
207781
- const manifest = await this.meshNode.queryManifest(peerId);
207782
- if (manifest) {
207783
- grpcPort = manifest.grpcPort;
207784
- this.manifestCache.set(peerId, {
207785
- manifest,
207786
- cachedAt: Date.now()
207787
- });
207788
- manifestEntry = this.manifestCache.get(peerId);
207789
- }
206765
+ try {
206766
+ const rootCert = tls.rootCert ? fs.readFileSync(tls.rootCert) : null;
206767
+ const certChain = fs.readFileSync(tls.certChain);
206768
+ const privateKey = fs.readFileSync(tls.privateKey);
206769
+ if (tls.mutualTls && !rootCert) {
206770
+ throw new Error(
206771
+ "[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but no root CA certificate (rootCert) provided to verify client certificates."
206772
+ );
207790
206773
  }
207791
- const addrs = await this.meshNode.resolvePeer(peerId);
207792
- const nexusUrl = process.env.LIOP_NEXUS_URL || "";
207793
- const isDockerDemo = nexusUrl.includes("127.0.0.1:13000") || nexusUrl.includes("localhost:13000") || nexusUrl.includes("127.0.0.1:13001") || nexusUrl.includes("localhost:13001");
207794
- const isDockerPort = addrs.some(
207795
- (a) => a.includes("13001") || a.includes("13003") || a.includes("13004") || a.includes("13005") || a.includes("13011") || a.includes("13021") || a.includes("13031")
206774
+ return grpc.ServerCredentials.createSsl(
206775
+ rootCert,
206776
+ [{ cert_chain: certChain, private_key: privateKey }],
206777
+ Boolean(tls.mutualTls)
207796
206778
  );
207797
- const shouldRemapGrpcPorts = process.env.LIOP_USE_PUBLISHED_GRPC_PORTS === "1" || process.env.LIOP_DOCKER_MAP === "true" || process.env.LIOP_DEV_MODE === "true" || process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" || isDockerDemo || isDockerPort;
207798
- if (shouldRemapGrpcPorts) {
207799
- const providerName = manifestEntry?.manifest?.serverInfo?.name?.toLowerCase() || "";
207800
- const tn = toolName.toLowerCase();
207801
- if (providerName.includes("vault") || tn.includes("medical")) {
207802
- grpcPort = 13011;
207803
- } else if (providerName.includes("bank") || tn.includes("bank")) {
207804
- grpcPort = 13021;
207805
- } else if (providerName.includes("oracle") || tn.includes("hft") || tn.includes("market")) {
207806
- grpcPort = 13031;
207807
- }
207808
- }
207809
- let targetAddr = null;
207810
- if (shouldRemapGrpcPorts) {
207811
- targetAddr = `127.0.0.1:${grpcPort}`;
207812
- } else {
207813
- const os = await import('os');
207814
- const localInterfaces = Object.values(os.networkInterfaces()).flat().filter((i) => i?.family === "IPv4").map((i) => i?.address);
207815
- for (const addr of addrs) {
207816
- const parts = addr.split("/");
207817
- const ipIdx = parts.indexOf("ip4");
207818
- if (ipIdx !== -1) {
207819
- const advertisedIp = parts[ipIdx + 1];
207820
- if (advertisedIp === "127.0.0.1" || localInterfaces.includes(advertisedIp)) {
207821
- targetAddr = `127.0.0.1:${grpcPort}`;
207822
- break;
207823
- }
207824
- if (!targetAddr) {
207825
- targetAddr = `${advertisedIp}:${grpcPort}`;
207826
- }
207827
- }
207828
- }
207829
- }
207830
- if (!targetAddr) {
207831
- targetAddr = `127.0.0.1:${grpcPort}`;
206779
+ } catch (error) {
206780
+ if (isTlsEnforced()) {
206781
+ throw new Error(
206782
+ `[LIOP-TLS] FATAL: Server certificate loading failed in production or enforced mode. Refusing insecure fallback to prevent MITM/eavesdropping: ${error}`
206783
+ );
207832
206784
  }
207833
- log.info(
207834
- `[LIOP-Router] Dynamic route: ${toolName} -> ${targetAddr} (PeerID: ${peerId})`
207835
- );
207836
- const remoteClient = new liopV1.LogicMesh(
207837
- targetAddr,
207838
- createChannelCredentials(),
207839
- GRPC_CHANNEL_OPTIONS
207840
- );
207841
- return this.performTranscoding(
207842
- id,
207843
- remoteClient,
207844
- toolName,
207845
- params,
207846
- peerId,
207847
- token
206785
+ log.warn(
206786
+ `[LIOP-TLS] Server certificate loading failed, falling back to insecure (dev mode): ${error}`
207848
206787
  );
206788
+ return grpc.ServerCredentials.createInsecure();
207849
206789
  }
207850
- /** Cached M2M token for dynamic gateway-to-node routing */
207851
- meshAgentToken;
207852
- /**
207853
- * Dynamically acquires an M2M access token from the Nexus Authorization Server.
207854
- * If peerId is provided, checks if there are node-specific environment tokens
207855
- * before falling back to the global static token or Nexus acquisition.
207856
- */
207857
- async getOrAcquireMeshAgentToken(peerId) {
207858
- if (peerId) {
207859
- const manifestEntry = this.manifestCache.get(peerId);
207860
- const providerName = manifestEntry?.manifest.serverInfo?.name?.toLowerCase() || "";
207861
- let nodeToken;
207862
- const slug = manifestEntry?.manifest.tokenSlug;
207863
- if (slug) {
207864
- const envKey = `LIOP_TOKEN_${slug}`;
207865
- nodeToken = process.env[envKey] || process.env[`LIOP_OAUTH_TOKEN_${slug}`];
207866
- log.info(
207867
- `[LIOP-Router] Step0 tokenSlug=${slug} envKey=${envKey} found=${!!nodeToken} peer=${peerId.slice(-8)}`
207868
- );
207869
- } else {
207870
- log.info(
207871
- `[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${peerId.slice(-8)} provider=${providerName}`
207872
- );
207873
- }
207874
- if (!nodeToken) {
207875
- const shortId = peerId.slice(-8).toUpperCase();
207876
- nodeToken = process.env[`LIOP_TOKEN_${shortId}`] || process.env[`LIOP_OAUTH_TOKEN_${shortId}`];
207877
- }
207878
- if (!nodeToken && providerName) {
207879
- const cleanName = providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
207880
- nodeToken = process.env[`LIOP_TOKEN_${cleanName}`] || process.env[`LIOP_OAUTH_TOKEN_${cleanName}`];
207881
- }
207882
- if (nodeToken) {
207883
- log.info(
207884
- `[LIOP-Router] Resolved node-specific token for peer ${peerId.slice(-8)} (${providerName || "unknown"})`
207885
- );
207886
- return nodeToken;
207887
- }
207888
- }
207889
- if (this.meshAgentToken) return this.meshAgentToken;
207890
- const staticToken = process.env.LIOP_OAUTH_TOKEN || process.env.LIOP_TOKEN;
207891
- if (staticToken) {
207892
- this.meshAgentToken = staticToken;
207893
- return this.meshAgentToken;
207894
- }
207895
- const nexusUrl = process.env.LIOP_NEXUS_URL;
207896
- if (!nexusUrl) return void 0;
207897
- const clientId = process.env.LIOP_OAUTH_CLIENT_ID || process.env.LIOP_CLIENT_ID || "liop-mesh-agent";
207898
- const clientSecret = process.env.LIOP_OAUTH_CLIENT_SECRET || process.env.LIOP_CLIENT_SECRET || "dev-secret-change-me";
207899
- const audience = process.env.LIOP_OAUTH_AUDIENCE || process.env.LIOP_AUDIENCE || "urn:liop:mesh:api";
206790
+ }
206791
+ function createChannelCredentials(tls) {
206792
+ if (tls?.certManager) {
207900
206793
  try {
207901
- const baseUrl = nexusUrl.endsWith("/oidc") ? nexusUrl : `${nexusUrl}/oidc`;
207902
- const tokenUrl = `${baseUrl}/token`;
207903
- log.info(
207904
- `[LIOP-Router] Proactively acquiring M2M token from Nexus: ${tokenUrl}`
207905
- );
207906
- const params = new URLSearchParams({
207907
- grant_type: "client_credentials",
207908
- scope: "liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",
207909
- resource: audience,
207910
- client_id: clientId,
207911
- client_secret: clientSecret
207912
- });
207913
- const response = await fetch(tokenUrl, {
207914
- method: "POST",
207915
- headers: {
207916
- "Content-Type": "application/x-www-form-urlencoded"
207917
- },
207918
- body: params.toString()
207919
- });
207920
- if (!response.ok) {
207921
- const text = await response.text();
207922
- log.warn(
207923
- `[LIOP-Router] M2M Token acquisition failed: ${response.status} ${text}`
206794
+ const rootCert = tls.certManager.getRootCert();
206795
+ if (!rootCert) {
206796
+ throw new Error(
206797
+ "[LIOP-TLS] FATAL: Channel TLS requires a root CA certificate in CertManager."
207924
206798
  );
207925
- return void 0;
207926
206799
  }
207927
- const data = await response.json();
207928
- if (data.access_token) {
207929
- this.meshAgentToken = data.access_token;
207930
- log.info(
207931
- "[LIOP-Router] M2M Token acquired successfully for router routing."
206800
+ const certChain = tls.certManager.getCertChain();
206801
+ const privateKey = tls.certManager.getPrivateKey();
206802
+ return grpc.credentials.createSsl(rootCert, privateKey, certChain);
206803
+ } catch (error) {
206804
+ if (isTlsEnforced()) {
206805
+ throw new Error(
206806
+ `[LIOP-TLS] FATAL: Channel certificate loading failed in enforced mode: ${error}`
207932
206807
  );
207933
- return this.meshAgentToken;
207934
206808
  }
207935
- } catch (err) {
207936
206809
  log.warn(
207937
- `[LIOP-Router] Failed to acquire M2M token: ${err instanceof Error ? err.message : String(err)}`
206810
+ `[LIOP-TLS] Channel CertManager failed, falling back to insecure: ${error}`
207938
206811
  );
206812
+ return grpc.credentials.createInsecure();
207939
206813
  }
207940
- return void 0;
207941
206814
  }
207942
- async performTranscoding(id, client, toolName, params, peerId, token) {
207943
- const capabilityHash = toolName;
207944
- const proofOfIntent = this.meshNode ? await this.meshNode.sign(Buffer.from(capabilityHash)) : Buffer.from([]);
207945
- const transcodingStartTime = Date.now();
207946
- let activeToken = token;
207947
- if (!activeToken) {
207948
- activeToken = await this.getOrAcquireMeshAgentToken(peerId);
207949
- }
207950
- if (peerId) {
207951
- const manifestEntry = this.manifestCache.get(peerId);
207952
- if (manifestEntry?.manifest.authRequired && !activeToken) {
207953
- const providerName = manifestEntry.manifest.serverInfo?.name?.toLowerCase() || "unknown";
207954
- const slug = manifestEntry.manifest.tokenSlug;
207955
- const shortId = peerId.slice(-8).toUpperCase();
207956
- const primaryVar = slug ? `LIOP_TOKEN_${slug}` : `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}`;
207957
- return {
207958
- jsonrpc: "2.0",
207959
- id,
207960
- result: {
207961
- content: [
207962
- {
207963
- type: "text",
207964
- text: `Authentication Required: The restricted node (${providerName}) requires an access token. Please define the ${primaryVar} or LIOP_TOKEN_${shortId} environment variable on your agent/client host.`
207965
- }
207966
- ],
207967
- isError: true
207968
- }
207969
- };
207970
- }
206815
+ if (!tls?.rootCert) {
206816
+ if (isTlsEnforced()) {
206817
+ throw new Error(
206818
+ "[LIOP-TLS] FATAL: TLS root certificate required in production or when LIOP_ENFORCE_TLS=true."
206819
+ );
207971
206820
  }
207972
- return new Promise((resolve) => {
207973
- const metadata = new grpc.Metadata();
207974
- if (activeToken) {
207975
- metadata.add("authorization", `Bearer ${activeToken}`);
207976
- }
207977
- client.negotiateIntent(
207978
- {
207979
- agent_did: `did:liop:${this.meshNode?.getPeerId() || "mcp-proxy"}`,
207980
- capability_hash: capabilityHash,
207981
- proof_of_intent: proofOfIntent
207982
- },
207983
- metadata,
207984
- async (err, response) => {
207985
- if (err || !response.accepted) {
207986
- return resolve({
207987
- jsonrpc: "2.0",
207988
- id,
207989
- result: {
207990
- content: [
207991
- {
207992
- type: "text",
207993
- text: `PQC Handshake Failed: ${err?.message || "Rejected"}`
207994
- }
207995
- ],
207996
- isError: true
207997
- }
207998
- });
207999
- }
208000
- const { ciphertext, sharedSecret } = await Kyber768Wrapper.encapsulateAsymmetric(
208001
- response.kyber_public_key
208002
- );
208003
- const embeddedArgs = params?.arguments ?? (params?.payload !== void 0 ? params : {});
208004
- const embeddedArgsJson = JSON.stringify(embeddedArgs);
208005
- const proxyLogic = `return { "__liop_proxy_tool": "${toolName}", "__liop_proxy_args": ${embeddedArgsJson} };`;
208006
- const nonce = crypto2.randomBytes(12);
208007
- const sealedLogic = this.encryptWithNonce(
208008
- Buffer.from(proxyLogic),
208009
- sharedSecret,
208010
- nonce
208011
- );
208012
- const metadataCall = new grpc.Metadata();
208013
- if (activeToken) {
208014
- metadataCall.add("authorization", `Bearer ${activeToken}`);
208015
- }
208016
- const call = client.executeLogic(
208017
- {
208018
- session_token: response.session_token,
208019
- wasm_binary: new Uint8Array(sealedLogic),
208020
- inputs: {},
208021
- pqc_ciphertext: ciphertext,
208022
- aes_nonce: nonce
208023
- },
208024
- metadataCall
208025
- );
208026
- let resultBody = "";
208027
- let lastResponse = null;
208028
- call.on("data", (grpcRes) => {
208029
- resultBody += grpcRes.semantic_evidence;
208030
- lastResponse = grpcRes;
208031
- });
208032
- call.on("end", async () => {
208033
- try {
208034
- if (lastResponse) {
208035
- if (!lastResponse.is_error) {
208036
- const proofHex = Buffer.from(
208037
- lastResponse.cryptographic_proof
208038
- ).toString("hex");
208039
- const isValid = await this.verifier.verifyZkReceipt(
208040
- Buffer.from(proxyLogic),
208041
- proofHex,
208042
- Buffer.from(lastResponse.zk_receipt),
208043
- Buffer.from(sharedSecret),
208044
- resultBody
208045
- );
208046
- if (!isValid) {
208047
- return resolve({
208048
- jsonrpc: "2.0",
208049
- id,
208050
- result: {
208051
- content: [
208052
- {
208053
- type: "text",
208054
- text: "SECURITY ALERT: Remote response failed cryptographic integrity audit."
208055
- }
208056
- ],
208057
- isError: true
208058
- }
208059
- });
208060
- }
208061
- }
208062
- }
208063
- const parsedResult = JSON.parse(resultBody);
208064
- const remoteTelemetry = TokenTelemetryEngine.getInstance();
208065
- remoteTelemetry.record({
208066
- type: "tool_call",
208067
- method: "tools/call",
208068
- toolName,
208069
- peerId,
208070
- estimatedInputTokens: remoteTelemetry.countTokens(embeddedArgsJson),
208071
- estimatedOutputTokens: remoteTelemetry.countTokens(resultBody),
208072
- durationMs: Date.now() - transcodingStartTime
208073
- });
208074
- resolve({ jsonrpc: "2.0", id, result: parsedResult });
208075
- } catch (_e) {
208076
- resolve({
208077
- jsonrpc: "2.0",
208078
- id,
208079
- result: { content: [{ type: "text", text: resultBody }] }
208080
- });
208081
- }
208082
- });
208083
- call.on(
208084
- "error",
208085
- (e) => resolve({
208086
- jsonrpc: "2.0",
208087
- id,
208088
- result: {
208089
- content: [
208090
- { type: "text", text: `LIOP gRPC Error: ${e.message}` }
208091
- ],
208092
- isError: true
208093
- }
208094
- })
208095
- );
208096
- }
206821
+ if (!isTlsWarningSuppressed(tls) && !hasWarnedInsecureChannel) {
206822
+ hasWarnedInsecureChannel = true;
206823
+ log.debug(
206824
+ "[LIOP-TLS] No TLS root certificate configured \u2014 using insecure channel credentials"
208097
206825
  );
208098
- });
206826
+ }
206827
+ return grpc.credentials.createInsecure();
208099
206828
  }
208100
- encryptWithNonce(payload, key, nonce) {
208101
- const cipher = crypto2.createCipheriv("aes-256-gcm", key, nonce);
208102
- const encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);
208103
- return Buffer.concat([encrypted, cipher.getAuthTag()]);
206829
+ try {
206830
+ const rootCert = fs.readFileSync(tls.rootCert);
206831
+ const certChain = tls.certChain ? fs.readFileSync(tls.certChain) : void 0;
206832
+ const privateKey = tls.privateKey ? fs.readFileSync(tls.privateKey) : void 0;
206833
+ return grpc.credentials.createSsl(rootCert, privateKey, certChain);
206834
+ } catch (error) {
206835
+ if (isTlsEnforced()) {
206836
+ throw new Error(
206837
+ `[LIOP-TLS] FATAL: Channel certificate loading failed in production or enforced mode. Refusing insecure fallback to prevent MITM/eavesdropping: ${error}`
206838
+ );
206839
+ }
206840
+ log.warn(
206841
+ `[LIOP-TLS] Channel certificate loading failed, falling back to insecure (dev mode): ${error}`
206842
+ );
206843
+ return grpc.credentials.createInsecure();
208104
206844
  }
206845
+ }
206846
+
206847
+ // src/rpc/channel-options.ts
206848
+ var GRPC_CHANNEL_OPTIONS = {
206849
+ "grpc.keepalive_time_ms": 3e4,
206850
+ "grpc.keepalive_timeout_ms": 1e4,
206851
+ "grpc.keepalive_permit_without_calls": 1,
206852
+ "grpc.max_send_message_length": -1,
206853
+ "grpc.max_receive_message_length": -1,
206854
+ "grpc.enable_retries": 1
208105
206855
  };
206856
+ var __filename2 = fileURLToPath(import.meta.url);
206857
+ var __dirname2 = path.dirname(__filename2);
206858
+ var PROD_PATHS = [
206859
+ path.resolve(__dirname2, "./protocol/liop_core.proto"),
206860
+ // Flat dist/ (tsup)
206861
+ path.resolve(__dirname2, "../protocol/liop_core.proto")
206862
+ // dist/rpc/ (tsc)
206863
+ ];
206864
+ var DEV_PROTO_PATH = path.resolve(
206865
+ __dirname2,
206866
+ "../../../../protocol/proto/liop_core.proto"
206867
+ );
206868
+ var PROTO_PATH = PROD_PATHS.find((p) => fs.existsSync(p)) || DEV_PROTO_PATH;
206869
+ if (!fs.existsSync(PROTO_PATH)) {
206870
+ log.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${PROTO_PATH}`);
206871
+ }
206872
+ var packageDefinition = protoLoader.loadSync(PROTO_PATH, {
206873
+ keepCase: true,
206874
+ longs: String,
206875
+ enums: String,
206876
+ defaults: true,
206877
+ oneofs: true
206878
+ });
206879
+ var liopProto = grpc.loadPackageDefinition(packageDefinition);
206880
+ var liopV1 = liopProto.liop.v1;
208106
206881
 
208107
- export { HeuristicTokenEstimator, LiopMcpRouter, LiopOTelBridge, RealTokenEstimator, TokenTelemetryEngine, createSyncTokenEstimator, createTokenEstimator };
208108
- //# sourceMappingURL=chunk-547TYL27.js.map
208109
- //# sourceMappingURL=chunk-547TYL27.js.map
206882
+ export { GRPC_CHANNEL_OPTIONS, HeuristicTokenEstimator, LiopOTelBridge, RealTokenEstimator, TokenTelemetryEngine, createChannelCredentials, createServerCredentials, createSyncTokenEstimator, createTokenEstimator, liopV1 };
206883
+ //# sourceMappingURL=chunk-UJFWPRDM.js.map
206884
+ //# sourceMappingURL=chunk-UJFWPRDM.js.map