@nekzus/liop 2.4.0-alpha.11 → 2.4.0-alpha.13

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 (36) hide show
  1. package/dist/bin/agent.js +4 -4
  2. package/dist/bridge.d.ts +2 -2
  3. package/dist/bridge.js +2 -2
  4. package/dist/{chunk-TKRX6CFI.js → chunk-3BJ5QQHK.js} +70 -60
  5. package/dist/chunk-3BJ5QQHK.js.map +1 -0
  6. package/dist/{chunk-3L2O2XKG.js → chunk-5SQLODJS.js} +100 -5
  7. package/dist/chunk-5SQLODJS.js.map +1 -0
  8. package/dist/{chunk-EG46XMJT.js → chunk-NFFBJALJ.js} +2 -2
  9. package/dist/{chunk-EG46XMJT.js.map → chunk-NFFBJALJ.js.map} +1 -1
  10. package/dist/{chunk-L6J72C5X.js → chunk-NFPQJCWL.js} +5 -5
  11. package/dist/chunk-NFPQJCWL.js.map +1 -0
  12. package/dist/{chunk-BOISQ45Z.js → chunk-OPYSUDSW.js} +3 -3
  13. package/dist/{chunk-BOISQ45Z.js.map → chunk-OPYSUDSW.js.map} +1 -1
  14. package/dist/{chunk-T7R5HUFD.js → chunk-PXSXQEXO.js} +23 -4
  15. package/dist/chunk-PXSXQEXO.js.map +1 -0
  16. package/dist/{chunk-HD2N3IJX.js → chunk-UWC7OY7K.js} +3 -3
  17. package/dist/{chunk-HD2N3IJX.js.map → chunk-UWC7OY7K.js.map} +1 -1
  18. package/dist/client.d.ts +3 -2
  19. package/dist/client.js +3 -3
  20. package/dist/gateway.d.ts +3 -3
  21. package/dist/gateway.js +4 -4
  22. package/dist/{hybrid-CrKB50nh.d.ts → hybrid-FFII2lHf.d.ts} +4 -3
  23. package/dist/{index-CX43dvMs.d.ts → index-BLu6LG_C.d.ts} +37 -2
  24. package/dist/{index-DoW2gzBZ.d.ts → index-DckIVTsW.d.ts} +1 -1
  25. package/dist/index.d.ts +7 -7
  26. package/dist/index.js +7 -7
  27. package/dist/server.d.ts +2 -2
  28. package/dist/server.js +2 -2
  29. package/dist/{types-lJIxBlWF.d.ts → types-DDiBZWEq.d.ts} +60 -1
  30. package/dist/types.d.ts +1 -1
  31. package/dist/types.js +1 -1
  32. package/package.json +21 -21
  33. package/dist/chunk-3L2O2XKG.js.map +0 -1
  34. package/dist/chunk-L6J72C5X.js.map +0 -1
  35. package/dist/chunk-T7R5HUFD.js.map +0 -1
  36. package/dist/chunk-TKRX6CFI.js.map +0 -1
package/dist/bin/agent.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { probeTopology, RoutingTable } from '../chunk-UCVP3XAL.js';
3
3
  import { TokenManager } from '../chunk-ESRXG36Y.js';
4
- import { LiopServer } from '../chunk-HD2N3IJX.js';
4
+ import { LiopServer } from '../chunk-UWC7OY7K.js';
5
5
  import '../chunk-Y62GORQF.js';
6
- import { LiopMcpRouter } from '../chunk-L6J72C5X.js';
6
+ import { LiopMcpRouter } from '../chunk-NFPQJCWL.js';
7
7
  import '../chunk-DZ2FQGJD.js';
8
8
  import '../chunk-PEN3KFLF.js';
9
9
  import '../chunk-IK7CGWAZ.js';
10
10
  import '../chunk-7PITYWOV.js';
11
11
  import '../chunk-VH4K4U45.js';
12
- import '../chunk-TKRX6CFI.js';
12
+ import '../chunk-3BJ5QQHK.js';
13
13
  import '../chunk-PAICJCKJ.js';
14
- import { isLegacyRequest } from '../chunk-EG46XMJT.js';
14
+ import { isLegacyRequest } from '../chunk-NFFBJALJ.js';
15
15
  import '../chunk-FTF6AMF6.js';
16
16
  import '../chunk-ZP3VVXOI.js';
17
17
  import { MeshNode } from '../chunk-7RXOIDXP.js';
package/dist/bridge.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import { L as LiopServer, a as LiopServerOptions } from './index-DoW2gzBZ.js';
2
+ import { L as LiopServer, a as LiopServerOptions } from './index-DckIVTsW.js';
3
3
  import 'zod';
4
4
  import './node-B0b2vUFS.js';
5
- import './types-lJIxBlWF.js';
5
+ import './types-DDiBZWEq.js';
6
6
  import 'jose';
7
7
 
8
8
  /**
package/dist/bridge.js CHANGED
@@ -1,5 +1,5 @@
1
- export { LiopMcpBridge, LiopStreamBridge } from './chunk-BOISQ45Z.js';
2
- import './chunk-EG46XMJT.js';
1
+ export { LiopMcpBridge, LiopStreamBridge } from './chunk-OPYSUDSW.js';
2
+ import './chunk-NFFBJALJ.js';
3
3
  import './chunk-HA6YZ42O.js';
4
4
  //# sourceMappingURL=bridge.js.map
5
5
  //# sourceMappingURL=bridge.js.map
@@ -1,45 +1,14 @@
1
1
  import { log } from './chunk-HA6YZ42O.js';
2
+ import * as fs from 'fs';
3
+ import * as grpc from '@grpc/grpc-js';
2
4
  import path from 'path';
3
5
  import { fileURLToPath } from 'url';
4
- import * as grpc2 from '@grpc/grpc-js';
5
6
  import * as protoLoader from '@grpc/proto-loader';
6
- import * as fs2 from 'fs';
7
7
 
8
- // src/rpc/channel-options.ts
9
- var GRPC_CHANNEL_OPTIONS = {
10
- "grpc.keepalive_time_ms": 3e4,
11
- "grpc.keepalive_timeout_ms": 1e4,
12
- "grpc.keepalive_permit_without_calls": 1,
13
- "grpc.max_send_message_length": -1,
14
- "grpc.max_receive_message_length": -1,
15
- "grpc.enable_retries": 1
16
- };
17
- var __filename2 = fileURLToPath(import.meta.url);
18
- var __dirname2 = path.dirname(__filename2);
19
- var PROD_PATHS = [
20
- path.resolve(__dirname2, "./protocol/liop_core.proto"),
21
- // Flat dist/ (tsup)
22
- path.resolve(__dirname2, "../protocol/liop_core.proto")
23
- // dist/rpc/ (tsc)
24
- ];
25
- var DEV_PROTO_PATH = path.resolve(
26
- __dirname2,
27
- "../../../../protocol/proto/liop_core.proto"
28
- );
29
- var PROTO_PATH = PROD_PATHS.find((p) => fs2.existsSync(p)) || DEV_PROTO_PATH;
30
- if (!fs2.existsSync(PROTO_PATH)) {
31
- log.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${PROTO_PATH}`);
32
- }
33
- var packageDefinition = protoLoader.loadSync(PROTO_PATH, {
34
- keepCase: true,
35
- longs: String,
36
- enums: String,
37
- defaults: true,
38
- oneofs: true
39
- });
40
- var liopProto = grpc2.loadPackageDefinition(packageDefinition);
41
- var liopV1 = liopProto.liop.v1;
42
8
  var isTlsEnforced = () => process.env.NODE_ENV === "production" || process.env.LIOP_ENFORCE_TLS === "true";
9
+ var isTlsWarningSuppressed = (tls) => tls?.insecure === true || tls?.suppressWarning === true || process.env.LIOP_SUPPRESS_TLS_WARNING === "true";
10
+ var hasWarnedInsecureServer = false;
11
+ var hasWarnedInsecureChannel = false;
43
12
  function createServerCredentials(tls) {
44
13
  if (tls?.mutualTls && !tls.rootCert && !tls.certManager?.getRootCert()) {
45
14
  throw new Error(
@@ -56,7 +25,7 @@ function createServerCredentials(tls) {
56
25
  "[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but CertManager has no root CA certificate loaded."
57
26
  );
58
27
  }
59
- return grpc2.ServerCredentials.createSsl(
28
+ return grpc.ServerCredentials.createSsl(
60
29
  rootCert,
61
30
  [{ cert_chain: certChain, private_key: privateKey }],
62
31
  Boolean(tls.mutualTls)
@@ -70,7 +39,7 @@ function createServerCredentials(tls) {
70
39
  log.warn(
71
40
  `[LIOP-TLS] CertManager failed, falling back to insecure: ${error}`
72
41
  );
73
- return grpc2.ServerCredentials.createInsecure();
42
+ return grpc.ServerCredentials.createInsecure();
74
43
  }
75
44
  }
76
45
  if (!tls?.certChain || !tls?.privateKey) {
@@ -79,21 +48,24 @@ function createServerCredentials(tls) {
79
48
  "[LIOP-TLS] FATAL: TLS certificates required in production or when LIOP_ENFORCE_TLS=true."
80
49
  );
81
50
  }
82
- log.warn(
83
- "[LIOP-TLS] No TLS certificates configured \u2014 using insecure server credentials"
84
- );
85
- return grpc2.ServerCredentials.createInsecure();
51
+ if (!isTlsWarningSuppressed(tls) && !hasWarnedInsecureServer) {
52
+ hasWarnedInsecureServer = true;
53
+ log.debug(
54
+ "[LIOP-TLS] No TLS certificates configured \u2014 using insecure server credentials"
55
+ );
56
+ }
57
+ return grpc.ServerCredentials.createInsecure();
86
58
  }
87
59
  try {
88
- const rootCert = tls.rootCert ? fs2.readFileSync(tls.rootCert) : null;
89
- const certChain = fs2.readFileSync(tls.certChain);
90
- const privateKey = fs2.readFileSync(tls.privateKey);
60
+ const rootCert = tls.rootCert ? fs.readFileSync(tls.rootCert) : null;
61
+ const certChain = fs.readFileSync(tls.certChain);
62
+ const privateKey = fs.readFileSync(tls.privateKey);
91
63
  if (tls.mutualTls && !rootCert) {
92
64
  throw new Error(
93
65
  "[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but no root CA certificate (rootCert) provided to verify client certificates."
94
66
  );
95
67
  }
96
- return grpc2.ServerCredentials.createSsl(
68
+ return grpc.ServerCredentials.createSsl(
97
69
  rootCert,
98
70
  [{ cert_chain: certChain, private_key: privateKey }],
99
71
  Boolean(tls.mutualTls)
@@ -107,7 +79,7 @@ function createServerCredentials(tls) {
107
79
  log.warn(
108
80
  `[LIOP-TLS] Server certificate loading failed, falling back to insecure (dev mode): ${error}`
109
81
  );
110
- return grpc2.ServerCredentials.createInsecure();
82
+ return grpc.ServerCredentials.createInsecure();
111
83
  }
112
84
  }
113
85
  function createChannelCredentials(tls) {
@@ -121,7 +93,7 @@ function createChannelCredentials(tls) {
121
93
  }
122
94
  const certChain = tls.certManager.getCertChain();
123
95
  const privateKey = tls.certManager.getPrivateKey();
124
- return grpc2.credentials.createSsl(rootCert, privateKey, certChain);
96
+ return grpc.credentials.createSsl(rootCert, privateKey, certChain);
125
97
  } catch (error) {
126
98
  if (isTlsEnforced()) {
127
99
  throw new Error(
@@ -131,7 +103,7 @@ function createChannelCredentials(tls) {
131
103
  log.warn(
132
104
  `[LIOP-TLS] Channel CertManager failed, falling back to insecure: ${error}`
133
105
  );
134
- return grpc2.credentials.createInsecure();
106
+ return grpc.credentials.createInsecure();
135
107
  }
136
108
  }
137
109
  if (!tls?.rootCert) {
@@ -140,16 +112,19 @@ function createChannelCredentials(tls) {
140
112
  "[LIOP-TLS] FATAL: TLS root certificate required in production or when LIOP_ENFORCE_TLS=true."
141
113
  );
142
114
  }
143
- log.warn(
144
- "[LIOP-TLS] No TLS root certificate configured \u2014 using insecure channel credentials"
145
- );
146
- return grpc2.credentials.createInsecure();
115
+ if (!isTlsWarningSuppressed(tls) && !hasWarnedInsecureChannel) {
116
+ hasWarnedInsecureChannel = true;
117
+ log.debug(
118
+ "[LIOP-TLS] No TLS root certificate configured \u2014 using insecure channel credentials"
119
+ );
120
+ }
121
+ return grpc.credentials.createInsecure();
147
122
  }
148
123
  try {
149
- const rootCert = fs2.readFileSync(tls.rootCert);
150
- const certChain = tls.certChain ? fs2.readFileSync(tls.certChain) : void 0;
151
- const privateKey = tls.privateKey ? fs2.readFileSync(tls.privateKey) : void 0;
152
- return grpc2.credentials.createSsl(rootCert, privateKey, certChain);
124
+ const rootCert = fs.readFileSync(tls.rootCert);
125
+ const certChain = tls.certChain ? fs.readFileSync(tls.certChain) : void 0;
126
+ const privateKey = tls.privateKey ? fs.readFileSync(tls.privateKey) : void 0;
127
+ return grpc.credentials.createSsl(rootCert, privateKey, certChain);
153
128
  } catch (error) {
154
129
  if (isTlsEnforced()) {
155
130
  throw new Error(
@@ -159,10 +134,45 @@ function createChannelCredentials(tls) {
159
134
  log.warn(
160
135
  `[LIOP-TLS] Channel certificate loading failed, falling back to insecure (dev mode): ${error}`
161
136
  );
162
- return grpc2.credentials.createInsecure();
137
+ return grpc.credentials.createInsecure();
163
138
  }
164
139
  }
165
140
 
141
+ // src/rpc/channel-options.ts
142
+ var GRPC_CHANNEL_OPTIONS = {
143
+ "grpc.keepalive_time_ms": 3e4,
144
+ "grpc.keepalive_timeout_ms": 1e4,
145
+ "grpc.keepalive_permit_without_calls": 1,
146
+ "grpc.max_send_message_length": -1,
147
+ "grpc.max_receive_message_length": -1,
148
+ "grpc.enable_retries": 1
149
+ };
150
+ var __filename2 = fileURLToPath(import.meta.url);
151
+ var __dirname2 = path.dirname(__filename2);
152
+ var PROD_PATHS = [
153
+ path.resolve(__dirname2, "./protocol/liop_core.proto"),
154
+ // Flat dist/ (tsup)
155
+ path.resolve(__dirname2, "../protocol/liop_core.proto")
156
+ // dist/rpc/ (tsc)
157
+ ];
158
+ var DEV_PROTO_PATH = path.resolve(
159
+ __dirname2,
160
+ "../../../../protocol/proto/liop_core.proto"
161
+ );
162
+ var PROTO_PATH = PROD_PATHS.find((p) => fs.existsSync(p)) || DEV_PROTO_PATH;
163
+ if (!fs.existsSync(PROTO_PATH)) {
164
+ log.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${PROTO_PATH}`);
165
+ }
166
+ var packageDefinition = protoLoader.loadSync(PROTO_PATH, {
167
+ keepCase: true,
168
+ longs: String,
169
+ enums: String,
170
+ defaults: true,
171
+ oneofs: true
172
+ });
173
+ var liopProto = grpc.loadPackageDefinition(packageDefinition);
174
+ var liopV1 = liopProto.liop.v1;
175
+
166
176
  export { GRPC_CHANNEL_OPTIONS, createChannelCredentials, createServerCredentials, liopV1 };
167
- //# sourceMappingURL=chunk-TKRX6CFI.js.map
168
- //# sourceMappingURL=chunk-TKRX6CFI.js.map
177
+ //# sourceMappingURL=chunk-3BJ5QQHK.js.map
178
+ //# sourceMappingURL=chunk-3BJ5QQHK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/rpc/tls.ts","../src/rpc/channel-options.ts","../src/rpc/proto.ts"],"names":["__filename","__dirname","fs2","grpc2"],"mappings":";;;;;;;AAgDA,IAAM,aAAA,GAAgB,MACrB,OAAA,CAAQ,GAAA,CAAI,aAAa,YAAA,IACzB,OAAA,CAAQ,IAAI,gBAAA,KAAqB,MAAA;AAElC,IAAM,sBAAA,GAAyB,CAAC,GAAA,KAC/B,GAAA,EAAK,QAAA,KAAa,IAAA,IAClB,GAAA,EAAK,eAAA,KAAoB,IAAA,IACzB,OAAA,CAAQ,GAA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/D,IAAI,CAAIA,EAAA,CAAA,UAAA,CAAW,UAAU,CAAA,EAAG;AAC/B,EAAA,GAAA,CAAI,KAAA,CAAM,CAAA,+CAAA,EAAkD,UAAU,CAAA,CAAE,CAAA;AACzE;AAMA,IAAM,iBAAA,GAAgC,qBAAS,UAAA,EAAY;AAAA,EAC1D,QAAA,EAAU,IAAA;AAAA,EACV,KAAA,EAAO,MAAA;AAAA,EACP,KAAA,EAAO,MAAA;AAAA,EACP,QAAA,EAAU,IAAA;AAAA,EACV,MAAA,EAAQ;AACT,CAAC,CAAA;AAGM,IAAM,SAAA,GAAiBC,2BAAsB,iBAAiB,CAAA;AAC9D,IAAM,MAAA,GAAS,UAAU,IAAA,CAAK","file":"chunk-3BJ5QQHK.js","sourcesContent":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP TLS Configuration\n *\n * Provides conditional TLS credential factories for gRPC connections.\n * When TLS options are provided, connections are secured with mutual TLS.\n * Otherwise, falls back to insecure credentials (alpha/development mode).\n *\n * Production Hardening (Phase 128):\n * - When NODE_ENV=production and TLS is configured but certificate loading\n * fails, the system throws a fatal error instead of silently degrading\n * to insecure credentials. This prevents MITM/eavesdropping attacks\n * caused by misconfigured certificate paths going unnoticed.\n * - Reference: gRPC-node official docs — \"Using insecure credentials in\n * production poses significant security risks including eavesdropping,\n * MITM attacks, and lack of authentication.\"\n */\n\nimport * as fs from \"node:fs\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport type { CertManager } from \"../security/cert-manager.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopTlsOptions {\n\t/** Path to the root CA certificate (PEM format) */\n\trootCert?: string;\n\t/** Path to the server/client certificate (PEM format) */\n\tcertChain?: string;\n\t/** Path to the private key (PEM format) */\n\tprivateKey?: string;\n\t/** Require mutual TLS (mTLS): verify client certificate against root CA */\n\tmutualTls?: boolean;\n\t/** Optional CertManager instance for automated certificate management and hot reloading */\n\tcertManager?: CertManager;\n\t/**\n\t * Explicitly permit unencrypted (insecure) credentials for local development,\n\t * Docker testbeds, or tooling harnesses without emitting console warnings.\n\t * Ignored if isTlsEnforced() is true (production/enforced mode always throws).\n\t */\n\tinsecure?: boolean;\n\t/**\n\t * Explicitly suppress the fallback warning when insecure credentials are created.\n\t */\n\tsuppressWarning?: boolean;\n}\n\nconst isTlsEnforced = () =>\n\tprocess.env.NODE_ENV === \"production\" ||\n\tprocess.env.LIOP_ENFORCE_TLS === \"true\";\n\nconst isTlsWarningSuppressed = (tls?: LiopTlsOptions) =>\n\ttls?.insecure === true ||\n\ttls?.suppressWarning === true ||\n\tprocess.env.LIOP_SUPPRESS_TLS_WARNING === \"true\";\n\nlet hasWarnedInsecureServer = false;\nlet hasWarnedInsecureChannel = false;\n\n/**\n * Creates gRPC server credentials from TLS options.\n * In production or when LIOP_ENFORCE_TLS=true, refuses to fall back to insecure.\n * When mutualTls=true, enforces client certificate authentication against root CA.\n */\nexport function createServerCredentials(\n\ttls?: LiopTlsOptions,\n): grpc.ServerCredentials {\n\t// Mutual TLS requires a root CA certificate to authenticate clients\n\tif (tls?.mutualTls && !tls.rootCert && !tls.certManager?.getRootCert()) {\n\t\tthrow new Error(\n\t\t\t\"[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but no root CA certificate (rootCert) provided to verify client certificates.\",\n\t\t);\n\t}\n\n\t// If CertManager is provided, use its in-memory cached buffers\n\tif (tls?.certManager) {\n\t\ttry {\n\t\t\tconst certChain = tls.certManager.getCertChain();\n\t\t\tconst privateKey = tls.certManager.getPrivateKey();\n\t\t\tconst rootCert = tls.certManager.getRootCert();\n\n\t\t\tif (tls.mutualTls && !rootCert) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but CertManager has no root CA certificate loaded.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn grpc.ServerCredentials.createSsl(\n\t\t\t\trootCert,\n\t\t\t\t[{ cert_chain: certChain, private_key: privateKey }],\n\t\t\t\tBoolean(tls.mutualTls),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isTlsEnforced()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[LIOP-TLS] FATAL: CertManager server credential creation failed in enforced mode: ${error}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlog.warn(\n\t\t\t\t`[LIOP-TLS] CertManager failed, falling back to insecure: ${error}`,\n\t\t\t);\n\t\t\treturn grpc.ServerCredentials.createInsecure();\n\t\t}\n\t}\n\n\tif (!tls?.certChain || !tls?.privateKey) {\n\t\tif (isTlsEnforced()) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[LIOP-TLS] FATAL: TLS certificates required in production or when LIOP_ENFORCE_TLS=true.\",\n\t\t\t);\n\t\t}\n\t\tif (!isTlsWarningSuppressed(tls) && !hasWarnedInsecureServer) {\n\t\t\thasWarnedInsecureServer = true;\n\t\t\tlog.debug(\n\t\t\t\t\"[LIOP-TLS] No TLS certificates configured — using insecure server credentials\",\n\t\t\t);\n\t\t}\n\t\treturn grpc.ServerCredentials.createInsecure();\n\t}\n\n\ttry {\n\t\tconst rootCert = tls.rootCert ? fs.readFileSync(tls.rootCert) : null;\n\t\tconst certChain = fs.readFileSync(tls.certChain);\n\t\tconst privateKey = fs.readFileSync(tls.privateKey);\n\n\t\tif (tls.mutualTls && !rootCert) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but no root CA certificate (rootCert) provided to verify client certificates.\",\n\t\t\t);\n\t\t}\n\n\t\treturn grpc.ServerCredentials.createSsl(\n\t\t\trootCert,\n\t\t\t[{ cert_chain: certChain, private_key: privateKey }],\n\t\t\tBoolean(tls.mutualTls),\n\t\t);\n\t} catch (error) {\n\t\tif (isTlsEnforced()) {\n\t\t\tthrow new Error(\n\t\t\t\t`[LIOP-TLS] FATAL: Server certificate loading failed in production or enforced mode. ` +\n\t\t\t\t\t`Refusing insecure fallback to prevent MITM/eavesdropping: ${error}`,\n\t\t\t);\n\t\t}\n\t\tlog.warn(\n\t\t\t`[LIOP-TLS] Server certificate loading failed, falling back to insecure (dev mode): ${error}`,\n\t\t);\n\t\treturn grpc.ServerCredentials.createInsecure();\n\t}\n}\n\n/**\n * Creates gRPC channel credentials from TLS options.\n * In production or when LIOP_ENFORCE_TLS=true, refuses to fall back to insecure.\n */\nexport function createChannelCredentials(\n\ttls?: LiopTlsOptions,\n): grpc.ChannelCredentials {\n\t// If CertManager is provided, use its in-memory cached credentials\n\tif (tls?.certManager) {\n\t\ttry {\n\t\t\tconst rootCert = tls.certManager.getRootCert();\n\t\t\tif (!rootCert) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"[LIOP-TLS] FATAL: Channel TLS requires a root CA certificate in CertManager.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst certChain = tls.certManager.getCertChain();\n\t\t\tconst privateKey = tls.certManager.getPrivateKey();\n\t\t\treturn grpc.credentials.createSsl(rootCert, privateKey, certChain);\n\t\t} catch (error) {\n\t\t\tif (isTlsEnforced()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[LIOP-TLS] FATAL: Channel certificate loading failed in enforced mode: ${error}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlog.warn(\n\t\t\t\t`[LIOP-TLS] Channel CertManager failed, falling back to insecure: ${error}`,\n\t\t\t);\n\t\t\treturn grpc.credentials.createInsecure();\n\t\t}\n\t}\n\n\tif (!tls?.rootCert) {\n\t\tif (isTlsEnforced()) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[LIOP-TLS] FATAL: TLS root certificate required in production or when LIOP_ENFORCE_TLS=true.\",\n\t\t\t);\n\t\t}\n\t\tif (!isTlsWarningSuppressed(tls) && !hasWarnedInsecureChannel) {\n\t\t\thasWarnedInsecureChannel = true;\n\t\t\tlog.debug(\n\t\t\t\t\"[LIOP-TLS] No TLS root certificate configured — using insecure channel credentials\",\n\t\t\t);\n\t\t}\n\t\treturn grpc.credentials.createInsecure();\n\t}\n\n\ttry {\n\t\tconst rootCert = fs.readFileSync(tls.rootCert);\n\t\tconst certChain = tls.certChain\n\t\t\t? fs.readFileSync(tls.certChain)\n\t\t\t: undefined;\n\t\tconst privateKey = tls.privateKey\n\t\t\t? fs.readFileSync(tls.privateKey)\n\t\t\t: undefined;\n\n\t\treturn grpc.credentials.createSsl(rootCert, privateKey, certChain);\n\t} catch (error) {\n\t\tif (isTlsEnforced()) {\n\t\t\tthrow new Error(\n\t\t\t\t`[LIOP-TLS] FATAL: Channel certificate loading failed in production or enforced mode. ` +\n\t\t\t\t\t`Refusing insecure fallback to prevent MITM/eavesdropping: ${error}`,\n\t\t\t);\n\t\t}\n\t\tlog.warn(\n\t\t\t`[LIOP-TLS] Channel certificate loading failed, falling back to insecure (dev mode): ${error}`,\n\t\t);\n\t\treturn grpc.credentials.createInsecure();\n\t}\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP Production-Grade gRPC Channel Options\n *\n * Enforces bidirectional symmetry between LiopRpcServer, LiopRpcClient,\n * and gateway proxy channels per NIST SP 800-207 continuous verification.\n * Prevents silent disconnections behind corporate stateful firewalls and NAT gateways.\n */\nexport const GRPC_CHANNEL_OPTIONS: Readonly<Record<string, string | number>> = {\n\t\"grpc.keepalive_time_ms\": 30_000,\n\t\"grpc.keepalive_timeout_ms\": 10_000,\n\t\"grpc.keepalive_permit_without_calls\": 1,\n\t\"grpc.max_send_message_length\": -1,\n\t\"grpc.max_receive_message_length\": -1,\n\t\"grpc.enable_retries\": 1,\n};\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport * as protoLoader from \"@grpc/proto-loader\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nimport * as fs from \"node:fs\";\nimport { log } from \"../utils/logger.js\";\n\n// Selection logic: support both flat dist/ and original src/ structure\nconst PROD_PATHS = [\n\tpath.resolve(__dirname, \"./protocol/liop_core.proto\"), // Flat dist/ (tsup)\n\tpath.resolve(__dirname, \"../protocol/liop_core.proto\"), // dist/rpc/ (tsc)\n];\n\nconst DEV_PROTO_PATH = path.resolve(\n\t__dirname,\n\t\"../../../../protocol/proto/liop_core.proto\",\n);\n\n// Selection logic\nconst PROTO_PATH = PROD_PATHS.find((p) => fs.existsSync(p)) || DEV_PROTO_PATH;\n\nif (!fs.existsSync(PROTO_PATH)) {\n\tlog.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${PROTO_PATH}`);\n}\n\n/**\n * LIOP Proto Loader\n * Loads the core gRPC definitions for the Logic-Injection-on-Origin Protocol.\n */\nconst packageDefinition = protoLoader.loadSync(PROTO_PATH, {\n\tkeepCase: true,\n\tlongs: String,\n\tenums: String,\n\tdefaults: true,\n\toneofs: true,\n});\n\n// biome-ignore lint/suspicious/noExplicitAny: gRPC dynamic loading requires any for the service definition map\nexport const liopProto = grpc.loadPackageDefinition(packageDefinition) as any;\nexport const liopV1 = liopProto.liop.v1;\n"]}
@@ -1,4 +1,4 @@
1
- import { LiopMcpRouter } from './chunk-L6J72C5X.js';
1
+ import { LiopMcpRouter } from './chunk-NFPQJCWL.js';
2
2
  import { LIOP_SCOPES } from './chunk-VH4K4U45.js';
3
3
  import { meshPeersConnected, manifestCacheSize, protocolMetrics } from './chunk-PAICJCKJ.js';
4
4
  import { log } from './chunk-HA6YZ42O.js';
@@ -123,6 +123,53 @@ async function dispatchGrpcWebRequest(req, res, handler) {
123
123
  });
124
124
  }
125
125
 
126
+ // src/gateway/interceptor.ts
127
+ var DEFAULT_TIMEOUT_MS = 2500;
128
+ async function executeGatewayInterceptor(request, context, options) {
129
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
130
+ const failMode = options.failMode ?? "closed";
131
+ const signal = AbortSignal.timeout(timeoutMs);
132
+ const frozenRequest = Object.freeze(structuredClone(request));
133
+ let onAbortListener;
134
+ const abortPromise = new Promise((_, reject) => {
135
+ onAbortListener = () => reject(signal.reason);
136
+ signal.addEventListener("abort", onAbortListener, { once: true });
137
+ });
138
+ try {
139
+ const result = await Promise.race([
140
+ Promise.resolve(
141
+ options.interceptor(frozenRequest, { ...context, signal })
142
+ ),
143
+ abortPromise
144
+ ]);
145
+ return result;
146
+ } catch (error) {
147
+ const errorMessage = error instanceof Error ? error.message : String(error);
148
+ if (failMode === "open") {
149
+ log.warn(
150
+ `[LIOP-Gateway] Interceptor error (fail-open, allowing request): ${errorMessage}`
151
+ );
152
+ return {
153
+ allowed: true,
154
+ metadata: { interceptorError: errorMessage, failMode: "open" }
155
+ };
156
+ }
157
+ log.error(
158
+ `[LIOP-Gateway] Interceptor error (fail-closed, rejecting request): ${errorMessage}`
159
+ );
160
+ return {
161
+ allowed: false,
162
+ reason: `Interceptor unavailable: ${errorMessage}`,
163
+ errorCode: -32098,
164
+ metadata: { interceptorError: errorMessage, failMode: "closed" }
165
+ };
166
+ } finally {
167
+ if (onAbortListener) {
168
+ signal.removeEventListener("abort", onAbortListener);
169
+ }
170
+ }
171
+ }
172
+
126
173
  // src/gateway/rate-limiter.ts
127
174
  var InMemoryRateLimiter = class {
128
175
  windowMs;
@@ -206,12 +253,13 @@ var InMemoryRateLimiter = class {
206
253
 
207
254
  // src/gateway/hybrid.ts
208
255
  var LiopHybridGateway = class {
209
- constructor(liopServer, meshNode = null, rpcPort = 50051, rateLimiterOptions) {
256
+ constructor(liopServer, meshNode = null, rpcPort = 50051, rateLimiterOptions, interceptorOptions) {
210
257
  this.liopServer = liopServer;
211
258
  this.meshNode = meshNode;
212
259
  this.jwtValidator = this.liopServer.jwtValidator;
213
260
  this.oauthProvider = this.liopServer.oauthProvider;
214
261
  this.rateLimiter = new InMemoryRateLimiter(rateLimiterOptions);
262
+ this.interceptorOptions = interceptorOptions;
215
263
  this.router = new LiopMcpRouter(this.liopServer, this.meshNode, rpcPort);
216
264
  this.h2Server = http2.createServer();
217
265
  this.setupH2Routes();
@@ -255,6 +303,7 @@ var LiopHybridGateway = class {
255
303
  // biome-ignore lint/suspicious/noExplicitAny: oidc-provider is loaded in Phase C
256
304
  oauthProvider;
257
305
  rateLimiter;
306
+ interceptorOptions;
258
307
  isDraining = false;
259
308
  activeRequests = 0;
260
309
  setupH2Routes() {
@@ -496,6 +545,27 @@ var LiopHybridGateway = class {
496
545
  }
497
546
  try {
498
547
  const jsonRequest = JSON.parse(body);
548
+ if (this.interceptorOptions?.interceptor) {
549
+ const verdict = await executeGatewayInterceptor(
550
+ jsonRequest,
551
+ { clientIp, authInfo, protocol: "http1" },
552
+ this.interceptorOptions
553
+ );
554
+ if (!verdict.allowed) {
555
+ res.writeHead(403, { "Content-Type": "application/json" });
556
+ res.end(
557
+ JSON.stringify({
558
+ jsonrpc: "2.0",
559
+ id: jsonRequest.id ?? null,
560
+ error: {
561
+ code: verdict.errorCode ?? -32099,
562
+ message: verdict.reason || "Forbidden: Rejected by Gateway Interceptor"
563
+ }
564
+ })
565
+ );
566
+ return;
567
+ }
568
+ }
499
569
  const mcpMethod = req.headers["mcp-method"];
500
570
  const mcpName = req.headers["mcp-name"];
501
571
  const mcpVersion = req.headers["mcp-protocol-version"];
@@ -598,6 +668,31 @@ var LiopHybridGateway = class {
598
668
  }
599
669
  }
600
670
  const jsonRequest = JSON.parse(body);
671
+ if (this.interceptorOptions?.interceptor) {
672
+ const h2ClientIp = stream.session?.socket?.remoteAddress || "127.0.0.1";
673
+ const verdict = await executeGatewayInterceptor(
674
+ jsonRequest,
675
+ { clientIp: h2ClientIp, authInfo, protocol: "http2" },
676
+ this.interceptorOptions
677
+ );
678
+ if (!verdict.allowed) {
679
+ stream.respond({
680
+ ":status": 403,
681
+ "content-type": "application/json"
682
+ });
683
+ stream.end(
684
+ JSON.stringify({
685
+ jsonrpc: "2.0",
686
+ id: jsonRequest.id ?? null,
687
+ error: {
688
+ code: verdict.errorCode ?? -32099,
689
+ message: verdict.reason || "Forbidden: Rejected by Gateway Interceptor"
690
+ }
691
+ })
692
+ );
693
+ return;
694
+ }
695
+ }
601
696
  const mcpMethod = headers["mcp-method"];
602
697
  const mcpName = headers["mcp-name"];
603
698
  const mcpVersion = headers["mcp-protocol-version"];
@@ -718,6 +813,6 @@ var LiopHybridGateway = class {
718
813
  }
719
814
  };
720
815
 
721
- export { GRPC_WEB_CONSTANTS, InMemoryRateLimiter, LiopHybridGateway, buildProtectedResourceMetadata, decodeFrames, dispatchGrpcWebRequest, encodeDataFrame, encodeTrailerFrame, isGrpcWebRequest };
722
- //# sourceMappingURL=chunk-3L2O2XKG.js.map
723
- //# sourceMappingURL=chunk-3L2O2XKG.js.map
816
+ export { GRPC_WEB_CONSTANTS, InMemoryRateLimiter, LiopHybridGateway, buildProtectedResourceMetadata, decodeFrames, dispatchGrpcWebRequest, encodeDataFrame, encodeTrailerFrame, executeGatewayInterceptor, isGrpcWebRequest };
817
+ //# sourceMappingURL=chunk-5SQLODJS.js.map
818
+ //# sourceMappingURL=chunk-5SQLODJS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/security/prm.ts","../src/gateway/grpc-web.ts","../src/gateway/interceptor.ts","../src/gateway/rate-limiter.ts","../src/gateway/hybrid.ts"],"names":[],"mappings":";;;;;;;;;AAuCO,SAAS,8BAAA,CACf,QACA,QAAA,EAC4B;AAC5B,EAAA,OAAO;AAAA,IACN,QAAA,EAAU,QAAA;AAAA,IACV,qBAAA,EAAuB,CAAC,MAAM,CAAA;AAAA,IAC9B,gBAAA,EAAkB,WAAA;AAAA,IAClB,wBAAA,EAA0B,CAAC,QAAQ,CAAA;AAAA,IACnC,sBAAA,EAAwB;AAAA,GACzB;AACD;;;AC7BO,IAAM,kBAAA,GAAqB;AAAA,EACjC,SAAA,EAAW,CAAA;AAAA,EACX,aAAA,EAAe,GAAA;AAAA,EACf,aAAA,EAAe,CAA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AAM,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AAAA,IACvD;AACA,IAAA,MAAM,KAAK,IAAA,EAAK;AAAA,EACjB;AAAA,EAEA,MAAa,IAAA,GAAO;AACnB,IAAA,IAAI,KAAK,QAAA,EAAU;AAClB,MAAA,MAAM,IAAA,CAAK,SAAS,IAAA,EAAK;AAAA,IAC1B;AACA,IAAA,IAAA,CAAK,YAAY,KAAA,EAAM;AACvB,IAAA,IAAA,CAAK,UAAU,KAAA,EAAM;AACrB,IAAA,IAAA,CAAK,SAAS,KAAA,EAAM;AACpB,IAAA,IAAA,CAAK,SAAS,KAAA,EAAM;AAAA,EACrB;AAAA,EAEO,SAAA,GAA2B;AACjC,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACb;AACD","file":"chunk-5SQLODJS.js","sourcesContent":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP Protected Resource Metadata — RFC 9728\n *\n * Builds the JSON document served at /.well-known/oauth-protected-resource.\n * This enables MCP clients to discover the authorization server and\n * required scopes for accessing LIOP tools and resources.\n *\n * Standards: RFC 9728, MCP Spec 2025-11-25\n */\n\nimport { LIOP_SCOPES } from \"./rbac.js\";\n\n/**\n * RFC 9728 Protected Resource Metadata response.\n *\n * @see https://datatracker.ietf.org/doc/rfc9728\n */\nexport interface ProtectedResourceMetadata {\n\t/** Identifier for the protected resource. */\n\tresource: string;\n\t/** Array of authorization server issuer URLs that can issue tokens for this resource. */\n\tauthorization_servers: string[];\n\t/** OAuth scopes accepted by this resource. */\n\tscopes_supported: readonly string[];\n\t/** Methods of presenting the bearer token (always \"header\" for LIOP). */\n\tbearer_methods_supported: string[];\n\t/** URL to the resource documentation. */\n\tresource_documentation: string;\n}\n\n/**\n * Builds the Protected Resource Metadata document (RFC 9728).\n *\n * @param issuer - OIDC issuer URL of the Nexus authorization server\n * @param audience - JWT audience claim (resource identifier)\n */\nexport function buildProtectedResourceMetadata(\n\tissuer: string,\n\taudience: string,\n): ProtectedResourceMetadata {\n\treturn {\n\t\tresource: audience,\n\t\tauthorization_servers: [issuer],\n\t\tscopes_supported: LIOP_SCOPES,\n\t\tbearer_methods_supported: [\"header\"],\n\t\tresource_documentation: \"https://github.com/nekzus/liop\",\n\t};\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP gRPC-Web Protocol Adapter (HTTP/1.1 Fallback)\n *\n * Implements standard gRPC-Web framing per the official gRPC-Web specification:\n * https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md\n *\n * Allows web browsers, corporate Layer 7 HTTP/1.1 proxies, and enterprise WAFs\n * to invoke LIOP nodes over HTTP/1.1 without requiring HTTP/2 streaming or h2c.\n *\n * Frame Format:\n * - 1 byte: Frame Flag (0x00 = Data Frame, 0x80 = Trailers Frame)\n * - 4 bytes: 32-bit Big-Endian Unsigned Integer (payload length in bytes)\n * - N bytes: Message or Trailer payload\n */\n\nimport type * as http from \"node:http\";\nimport { log } from \"../utils/logger.js\";\n\nexport const GRPC_WEB_CONSTANTS = {\n\tFLAG_DATA: 0x00,\n\tFLAG_TRAILERS: 0x80,\n\tHEADER_LENGTH: 5,\n\tCONTENT_TYPE_PREFIX: \"application/grpc-web\",\n\tSTATUS_OK: 0,\n\tSTATUS_CANCELLED: 1,\n\tSTATUS_UNKNOWN: 2,\n\tSTATUS_INVALID_ARGUMENT: 3,\n\tSTATUS_DEADLINE_EXCEEDED: 4,\n\tSTATUS_NOT_FOUND: 5,\n\tSTATUS_PERMISSION_DENIED: 7,\n\tSTATUS_UNAUTHENTICATED: 16,\n\tSTATUS_INTERNAL: 13,\n} as const;\n\nexport interface GrpcWebFrame {\n\tisTrailer: boolean;\n\tpayload: Buffer;\n}\n\n/**\n * Checks if an incoming HTTP request is a gRPC-Web request.\n */\nexport function isGrpcWebRequest(contentType?: string): boolean {\n\tif (!contentType) return false;\n\tconst lower = contentType.toLowerCase();\n\treturn (\n\t\tlower.startsWith(\"application/grpc-web\") ||\n\t\tlower.startsWith(\"application/grpc-web+proto\") ||\n\t\tlower.startsWith(\"application/grpc-web+json\")\n\t);\n}\n\n/**\n * Encodes a binary payload into a standard 5-byte framed gRPC-Web Data Frame.\n */\nexport function encodeDataFrame(payload: Buffer | Uint8Array): Buffer {\n\tconst buf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);\n\tconst header = Buffer.alloc(GRPC_WEB_CONSTANTS.HEADER_LENGTH);\n\theader.writeUInt8(GRPC_WEB_CONSTANTS.FLAG_DATA, 0);\n\theader.writeUInt32BE(buf.length, 1);\n\treturn Buffer.concat([header, buf]);\n}\n\n/**\n * Encodes gRPC status and optional message into a 5-byte framed gRPC-Web Trailer Frame.\n */\nexport function encodeTrailerFrame(\n\tstatus: number = GRPC_WEB_CONSTANTS.STATUS_OK,\n\tmessage: string = \"\",\n\tcustomTrailers: Record<string, string> = {},\n): Buffer {\n\tconst lines = [\n\t\t`grpc-status:${status}`,\n\t\t`grpc-message:${encodeURIComponent(message)}`,\n\t];\n\n\tfor (const [key, value] of Object.entries(customTrailers)) {\n\t\tlines.push(`${key}:${value}`);\n\t}\n\n\tconst trailerText = `${lines.join(\"\\r\\n\")}\\r\\n`;\n\tconst trailerBuf = Buffer.from(trailerText, \"utf-8\");\n\n\tconst header = Buffer.alloc(GRPC_WEB_CONSTANTS.HEADER_LENGTH);\n\theader.writeUInt8(GRPC_WEB_CONSTANTS.FLAG_TRAILERS, 0);\n\theader.writeUInt32BE(trailerBuf.length, 1);\n\n\treturn Buffer.concat([header, trailerBuf]);\n}\n\n/**\n * Parses raw gRPC-Web byte streams into an array of frames.\n */\nexport function decodeFrames(buffer: Buffer): GrpcWebFrame[] {\n\tconst frames: GrpcWebFrame[] = [];\n\tlet offset = 0;\n\n\twhile (offset + GRPC_WEB_CONSTANTS.HEADER_LENGTH <= buffer.length) {\n\t\tconst flag = buffer.readUInt8(offset);\n\t\tconst length = buffer.readUInt32BE(offset + 1);\n\t\tconst payloadStart = offset + GRPC_WEB_CONSTANTS.HEADER_LENGTH;\n\t\tconst payloadEnd = payloadStart + length;\n\n\t\tif (payloadEnd > buffer.length) {\n\t\t\tbreak; // Incomplete frame\n\t\t}\n\n\t\tconst payload = buffer.subarray(payloadStart, payloadEnd);\n\t\tframes.push({\n\t\t\tisTrailer:\n\t\t\t\t(flag & GRPC_WEB_CONSTANTS.FLAG_TRAILERS) ===\n\t\t\t\tGRPC_WEB_CONSTANTS.FLAG_TRAILERS,\n\t\t\tpayload: Buffer.from(payload),\n\t\t});\n\n\t\toffset = payloadEnd;\n\t}\n\n\treturn frames;\n}\n\n/**\n * Dispatches an HTTP/1.1 gRPC-Web request to an underlying protocol handler\n * and serializes data and trailer frames back to the client.\n */\nexport async function dispatchGrpcWebRequest(\n\treq: http.IncomingMessage,\n\tres: http.ServerResponse,\n\thandler: (\n\t\tpath: string,\n\t\tpayload: Buffer,\n\t) => Promise<{ status: number; message?: string; data?: Buffer }>,\n): Promise<void> {\n\tconst chunks: Buffer[] = [];\n\n\treq.on(\"data\", (chunk: Buffer) => {\n\t\tchunks.push(chunk);\n\t});\n\n\treq.on(\"end\", async () => {\n\t\ttry {\n\t\t\tconst fullBody = Buffer.concat(chunks);\n\t\t\tconst frames = decodeFrames(fullBody);\n\t\t\tconst dataPayload =\n\t\t\t\tframes.find((f) => !f.isTrailer)?.payload ?? Buffer.alloc(0);\n\t\t\tconst requestPath = req.url || \"/\";\n\n\t\t\tlog.info(\n\t\t\t\t`[gRPC-Web] Handling request for ${requestPath} (${dataPayload.length} bytes)`,\n\t\t\t);\n\n\t\t\tconst result = await handler(requestPath, dataPayload);\n\n\t\t\tres.statusCode = 200;\n\t\t\tres.setHeader(\"content-type\", \"application/grpc-web+proto\");\n\t\t\tres.setHeader(\"access-control-allow-origin\", \"*\");\n\t\t\tres.setHeader(\n\t\t\t\t\"access-control-expose-headers\",\n\t\t\t\t\"grpc-status, grpc-message, content-type\",\n\t\t\t);\n\n\t\t\t// Write Data Frame (if response payload exists)\n\t\t\tif (result.data && result.data.length > 0) {\n\t\t\t\tres.write(encodeDataFrame(result.data));\n\t\t\t}\n\n\t\t\t// Write Trailer Frame (status and message)\n\t\t\tres.write(encodeTrailerFrame(result.status, result.message || \"\"));\n\t\t\tres.end();\n\t\t} catch (error) {\n\t\t\tlog.error(`[gRPC-Web] Dispatch error: ${error}`);\n\t\t\tres.statusCode = 200;\n\t\t\tres.setHeader(\"content-type\", \"application/grpc-web+proto\");\n\t\t\tres.write(\n\t\t\t\tencodeTrailerFrame(\n\t\t\t\t\tGRPC_WEB_CONSTANTS.STATUS_INTERNAL,\n\t\t\t\t\t(error as Error).message || \"Internal server error\",\n\t\t\t\t),\n\t\t\t);\n\t\t\tres.end();\n\t\t}\n\t});\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { AuthInfo } from \"../security/jwt-validator.js\";\nimport type { McpRequest } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\n/**\n * Verdict returned by a GatewayInterceptor function.\n * Determines whether the request is admitted into the routing pipeline.\n */\nexport interface GatewayAdmissionResult {\n\t/** true = request passes to router.dispatch(). false = rejected at perimeter. */\n\tallowed: boolean;\n\t/** Human-readable denial reason (included in JSON-RPC error response). */\n\treason?: string;\n\t/** Custom JSON-RPC error code. Defaults to -32099 when omitted. */\n\terrorCode?: number;\n\t/** Opaque metadata bag for telemetry or audit logging downstream. */\n\tmetadata?: Record<string, unknown>;\n}\n\n/**\n * Contextual information passed to the interceptor alongside the request.\n * Contains only non-sensitive, non-cryptographic perimeter metadata.\n */\nexport interface GatewayInterceptorContext {\n\t/** Originating client IP address (post-JWT, post-rate-limit). */\n\tclientIp: string;\n\t/** Authenticated identity from JWT validation, or null for unauthenticated gateways. */\n\tauthInfo: AuthInfo | null;\n\t/** Transport protocol that received this request. */\n\tprotocol: \"http1\" | \"http2\";\n\t/** Abort signal that fires when the interceptor timeout expires. */\n\tsignal: AbortSignal;\n}\n\n/**\n * Technology-agnostic admission function.\n * The developer implements this in their application code, connecting\n * any decision engine (TypeSafe Jev, ONNX, regex rules, custom logic).\n *\n * Receives a frozen deep-clone of the request to prevent prototype pollution.\n * May return synchronously or asynchronously.\n */\nexport type GatewayInterceptor = (\n\trequest: Readonly<McpRequest>,\n\tcontext: GatewayInterceptorContext,\n) => Promise<GatewayAdmissionResult> | GatewayAdmissionResult;\n\n/**\n * Configuration for the perimeter admission hook.\n */\nexport interface GatewayInterceptorOptions {\n\t/** The interceptor function. When undefined, the gateway skips interception entirely. */\n\tinterceptor?: GatewayInterceptor;\n\t/** Maximum milliseconds to wait for the interceptor. Default: 2500. */\n\ttimeoutMs?: number;\n\t/** Behavior when the interceptor throws or times out. Default: \"closed\". */\n\tfailMode?: \"closed\" | \"open\";\n}\n\nconst DEFAULT_TIMEOUT_MS = 2500;\n\n/**\n * Executes the interceptor with timeout enforcement via AbortSignal.timeout(),\n * prototype pollution isolation via structuredClone + Object.freeze,\n * and fail-mode policy enforcement.\n *\n * AbortSignal.timeout() is stable since Node.js 17.3 (available in Node.js 20+ LTS).\n * Promise.race guarantees the gateway never blocks beyond timeoutMs even if the\n * interceptor ignores the signal.\n */\nexport async function executeGatewayInterceptor(\n\trequest: McpRequest,\n\tcontext: Omit<GatewayInterceptorContext, \"signal\">,\n\toptions: Required<Pick<GatewayInterceptorOptions, \"interceptor\">> &\n\t\tGatewayInterceptorOptions,\n): Promise<GatewayAdmissionResult> {\n\tconst timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\tconst failMode = options.failMode ?? \"closed\";\n\tconst signal = AbortSignal.timeout(timeoutMs);\n\n\t// structuredClone severs all prototype chain references (deep copy).\n\t// Object.freeze blocks top-level mutation on the clone.\n\t// Even if the interceptor mutates nested properties, the original\n\t// jsonRequest in the gateway scope remains untouched.\n\tconst frozenRequest = Object.freeze(structuredClone(request));\n\n\tlet onAbortListener: (() => void) | undefined;\n\tconst abortPromise = new Promise<never>((_, reject) => {\n\t\tonAbortListener = () => reject(signal.reason);\n\t\tsignal.addEventListener(\"abort\", onAbortListener, { once: true });\n\t});\n\n\ttry {\n\t\tconst result = await Promise.race([\n\t\t\tPromise.resolve(\n\t\t\t\toptions.interceptor(frozenRequest, { ...context, signal }),\n\t\t\t),\n\t\t\tabortPromise,\n\t\t]);\n\t\treturn result;\n\t} catch (error: unknown) {\n\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\n\t\tif (failMode === \"open\") {\n\t\t\tlog.warn(\n\t\t\t\t`[LIOP-Gateway] Interceptor error (fail-open, allowing request): ${errorMessage}`,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tallowed: true,\n\t\t\t\tmetadata: { interceptorError: errorMessage, failMode: \"open\" },\n\t\t\t};\n\t\t}\n\n\t\t// fail-closed: reject with error response\n\t\tlog.error(\n\t\t\t`[LIOP-Gateway] Interceptor error (fail-closed, rejecting request): ${errorMessage}`,\n\t\t);\n\t\treturn {\n\t\t\tallowed: false,\n\t\t\treason: `Interceptor unavailable: ${errorMessage}`,\n\t\t\terrorCode: -32098,\n\t\t\tmetadata: { interceptorError: errorMessage, failMode: \"closed\" },\n\t\t};\n\t} finally {\n\t\tif (onAbortListener) {\n\t\t\tsignal.removeEventListener(\"abort\", onAbortListener);\n\t\t}\n\t}\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP Sliding-Window Rate Limiter\n *\n * High-performance, zero-dependency in-memory rate limiter designed\n * to protect the LIOP Hybrid Gateway and Mesh Nodes against Denial of Service (DoS),\n * worker pool exhaustion, and brute-force attacks.\n *\n * Conforms to OWASP API Security Top 10 (API4:2023 - Unrestricted Resource Consumption).\n */\n\nexport interface RateLimiterOptions {\n\t/** Window duration in milliseconds (default: 60,000ms = 1 minute) */\n\twindowMs?: number;\n\t/** Maximum number of allowed requests per window (default: 120) */\n\tmaxRequests?: number;\n}\n\nexport interface RateLimitStatus {\n\tallowed: boolean;\n\tremaining: number;\n\tlimit: number;\n\tresetMs: number;\n}\n\ninterface WindowRecord {\n\tcount: number;\n\tresetTime: number;\n}\n\nexport class InMemoryRateLimiter {\n\tprivate readonly windowMs: number;\n\tprivate readonly maxRequests: number;\n\tprivate readonly records: Map<string, WindowRecord> = new Map();\n\tprivate cleanupTimer?: NodeJS.Timeout;\n\n\tconstructor(options: RateLimiterOptions = {}) {\n\t\tthis.windowMs = options.windowMs ?? 60_000;\n\t\tthis.maxRequests = options.maxRequests ?? 120;\n\n\t\t// Clean up expired buckets periodically (every 30s)\n\t\tthis.cleanupTimer = setInterval(() => this.cleanup(), 30_000);\n\t\tif (typeof this.cleanupTimer.unref === \"function\") {\n\t\t\tthis.cleanupTimer.unref();\n\t\t}\n\t}\n\n\t/**\n\t * Evaluates whether a request from the given key (IP, token, or clientId) is permitted.\n\t *\n\t * @param key Identifier for the client (e.g., remote IP or OAuth client ID)\n\t * @returns Status containing allowed boolean, remaining quota, and time until reset\n\t */\n\tpublic check(key: string): RateLimitStatus {\n\t\tconst now = Date.now();\n\t\tlet record = this.records.get(key);\n\n\t\tif (!record || now >= record.resetTime) {\n\t\t\trecord = {\n\t\t\t\tcount: 1,\n\t\t\t\tresetTime: now + this.windowMs,\n\t\t\t};\n\t\t\tthis.records.set(key, record);\n\t\t\treturn {\n\t\t\t\tallowed: true,\n\t\t\t\tremaining: this.maxRequests - 1,\n\t\t\t\tlimit: this.maxRequests,\n\t\t\t\tresetMs: this.windowMs,\n\t\t\t};\n\t\t}\n\n\t\tif (record.count >= this.maxRequests) {\n\t\t\treturn {\n\t\t\t\tallowed: false,\n\t\t\t\tremaining: 0,\n\t\t\t\tlimit: this.maxRequests,\n\t\t\t\tresetMs: Math.max(0, record.resetTime - now),\n\t\t\t};\n\t\t}\n\n\t\trecord.count++;\n\t\treturn {\n\t\t\tallowed: true,\n\t\t\tremaining: this.maxRequests - record.count,\n\t\t\tlimit: this.maxRequests,\n\t\t\tresetMs: Math.max(0, record.resetTime - now),\n\t\t};\n\t}\n\n\t/**\n\t * Explicitly resets the rate limit bucket for a given key.\n\t */\n\tpublic reset(key: string): void {\n\t\tthis.records.delete(key);\n\t}\n\n\t/**\n\t * Cleans up expired rate-limiting buckets to prevent memory leaks.\n\t */\n\tpublic cleanup(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [key, record] of this.records.entries()) {\n\t\t\tif (now >= record.resetTime) {\n\t\t\t\tthis.records.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Destroys internal timers and clears records.\n\t */\n\tpublic close(): void {\n\t\tif (this.cleanupTimer) {\n\t\t\tclearInterval(this.cleanupTimer);\n\t\t\tthis.cleanupTimer = undefined;\n\t\t}\n\t\tthis.records.clear();\n\t}\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport * as http from \"node:http\";\nimport * as http2 from \"node:http2\";\nimport * as net from \"node:net\";\nimport type { MeshNode } from \"../mesh/index.js\";\nimport {\n\tmanifestCacheSize,\n\tmeshPeersConnected,\n\tprotocolMetrics,\n} from \"../observability/metrics.js\";\nimport type { AuthInfo, JwtValidator } from \"../security/jwt-validator.js\";\nimport { buildProtectedResourceMetadata } from \"../security/prm.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport {\n\tdispatchGrpcWebRequest,\n\tGRPC_WEB_CONSTANTS,\n\tisGrpcWebRequest,\n} from \"./grpc-web.js\";\nimport {\n\texecuteGatewayInterceptor,\n\ttype GatewayInterceptorOptions,\n} from \"./interceptor.js\";\nimport {\n\tInMemoryRateLimiter,\n\ttype RateLimiterOptions,\n} from \"./rate-limiter.js\";\nimport { LiopMcpRouter } from \"./router.js\";\n\n/**\n * LIOP Hybrid Gateway\n * High-level orchestration for connecting MCP (JSON-RPC) clients to the LIOP Mesh.\n */\nexport class LiopHybridGateway {\n\tprivate netServer: net.Server;\n\tprivate h2Server: http2.Http2Server;\n\tprivate h1Server: http.Server;\n\tprivate router: LiopMcpRouter;\n\tprivate jwtValidator?: JwtValidator;\n\t// biome-ignore lint/suspicious/noExplicitAny: oidc-provider is loaded in Phase C\n\tprivate oauthProvider?: any;\n\tprivate rateLimiter: InMemoryRateLimiter;\n\tprivate readonly interceptorOptions?: GatewayInterceptorOptions;\n\tprivate isDraining = false;\n\tprivate activeRequests = 0;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\trpcPort: number = 50051,\n\t\trateLimiterOptions?: RateLimiterOptions,\n\t\tinterceptorOptions?: GatewayInterceptorOptions,\n\t) {\n\t\tthis.jwtValidator = this.liopServer.jwtValidator;\n\t\tthis.oauthProvider = this.liopServer.oauthProvider;\n\t\tthis.rateLimiter = new InMemoryRateLimiter(rateLimiterOptions);\n\t\tthis.interceptorOptions = interceptorOptions;\n\n\t\t// Initialize the Universal Router\n\t\tthis.router = new LiopMcpRouter(this.liopServer, this.meshNode, rpcPort);\n\n\t\t// Internal HTTP/2 Server (for Native gRPC Proxying)\n\t\tthis.h2Server = http2.createServer();\n\t\tthis.setupH2Routes();\n\n\t\t// Internal HTTP/1 Server (for Browser/MCP)\n\t\tthis.h1Server = http.createServer();\n\t\tthis.setupH1Routes();\n\n\t\t// Primary Multiplexer (L4)\n\t\tthis.netServer = net.createServer((socket) => {\n\t\t\tsocket.once(\"data\", (buffer) => {\n\t\t\t\tconst isHttp2 = buffer.toString().startsWith(\"PRI * HTTP/2.0\");\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${isHttp2 ? \"HTTP/2 (gRPC)\" : \"HTTP/1.1 (MCP)\"}`,\n\t\t\t\t);\n\t\t\t\tif (isHttp2) {\n\t\t\t\t\tthis.h2Server.emit(\"connection\", socket);\n\t\t\t\t} else {\n\t\t\t\t\tthis.h1Server.emit(\"connection\", socket);\n\t\t\t\t}\n\t\t\t\tsocket.unshift(buffer);\n\t\t\t});\n\t\t\tsocket.on(\"error\", (err) =>\n\t\t\t\tlog.error(`[LIOP-Gateway] NetServer Socket Error: ${err.message}`),\n\t\t\t);\n\t\t});\n\n\t\t// Attach error listeners to sub-servers to catch silent failures\n\t\tthis.h1Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H1 Server Error: ${err.message}`),\n\t\t);\n\t\tthis.h2Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H2 Server Error: ${err.message}`),\n\t\t);\n\n\t\tlog.info(\"[LIOP-Gateway] Hybrid adapter initialized.\");\n\t}\n\n\tprivate setupH2Routes() {\n\t\tthis.h2Server.on(\"stream\", (stream, headers) => {\n\t\t\tconst contentType = headers[\"content-type\"] as string;\n\t\t\tconst path = headers[\":path\"] as string;\n\n\t\t\tif (contentType === \"application/grpc\") {\n\t\t\t\tthis.handleGrpcStream(stream as http2.ServerHttp2Stream);\n\t\t\t} else if (path === \"/mcp\") {\n\t\t\t\tthis.handleMcpH2Stream(stream as http2.ServerHttp2Stream, headers);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate setupH1Routes() {\n\t\tthis.h1Server.on(\"request\", async (req, res) => {\n\t\t\tthis.activeRequests += 1;\n\t\t\tconst onDone = () => {\n\t\t\t\tres.removeListener(\"finish\", onDone);\n\t\t\t\tres.removeListener(\"close\", onDone);\n\t\t\t\tthis.activeRequests = Math.max(0, this.activeRequests - 1);\n\t\t\t};\n\t\t\tres.on(\"finish\", onDone);\n\t\t\tres.on(\"close\", onDone);\n\n\t\t\tconst url = req.url || \"\";\n\t\t\tconst method = req.method;\n\n\t\t\t// [Phase Beta-3] Prometheus Metrics Endpoint\n\t\t\tif (method === \"GET\" && url === \"/metrics\") {\n\t\t\t\tif (this.meshNode) {\n\t\t\t\t\tmeshPeersConnected.set({}, this.meshNode.getPeers().length);\n\t\t\t\t}\n\t\t\t\tif (this.router) {\n\t\t\t\t\tmanifestCacheSize.set({}, this.router.getManifestCacheSize());\n\t\t\t\t}\n\t\t\t\tres.writeHead(200, {\n\t\t\t\t\t\"Content-Type\": \"text/plain; version=0.0.4; charset=utf-8\",\n\t\t\t\t});\n\t\t\t\tres.end(protocolMetrics.exportPrometheusText());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// [Phase Beta-3] K8s Liveness Probe\n\t\t\tif (method === \"GET\" && url === \"/healthz\") {\n\t\t\t\tif (this.isDraining) {\n\t\t\t\t\tres.writeHead(503, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"draining\",\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\tres.end(\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\tstatus: \"ok\",\n\t\t\t\t\t\tuptime: Math.floor(process.uptime()),\n\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// [Phase Beta-3] K8s Readiness Probe\n\t\t\tif (method === \"GET\" && url === \"/readyz\") {\n\t\t\t\tif (this.isDraining) {\n\t\t\t\t\tres.writeHead(503, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"draining\",\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst meshStarted = this.meshNode ? this.meshNode.isStarted() : true;\n\t\t\t\tif (!meshStarted) {\n\t\t\t\t\tres.writeHead(503, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"unready\",\n\t\t\t\t\t\t\tmeshStarted: false,\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\tres.end(\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\tstatus: \"ready\",\n\t\t\t\t\t\tmeshStarted: true,\n\t\t\t\t\t\tpeers: this.meshNode ? this.meshNode.getPeers().length : 0,\n\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Reject new MCP requests if draining\n\t\t\tif (this.isDraining && url === \"/mcp\") {\n\t\t\t\tres.writeHead(503, { \"Content-Type\": \"application/json\" });\n\t\t\t\tres.end(\n\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\t\tmessage: \"Gateway is draining connections for shutdown\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// [Phase Beta-2] gRPC-Web HTTP/1.1 Framing Fallback\n\t\t\tconst contentType = req.headers[\"content-type\"];\n\t\t\tif (isGrpcWebRequest(contentType)) {\n\t\t\t\tawait dispatchGrpcWebRequest(req, res, async (reqPath, payload) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Gateway] gRPC-Web fallback call: ${reqPath} (${payload.length} bytes)`,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: GRPC_WEB_CONSTANTS.STATUS_OK,\n\t\t\t\t\t\tmessage: \"OK\",\n\t\t\t\t\t\tdata: Buffer.from(\"\"),\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// [SEC] M2M OAuth 2.1 OIDC Authorization Server Router (Phase C proxy)\n\t\t\tif (url.startsWith(\"/oidc\") && this.oauthProvider) {\n\t\t\t\tconst callback =\n\t\t\t\t\ttypeof this.oauthProvider.callback === \"function\"\n\t\t\t\t\t\t? this.oauthProvider.callback()\n\t\t\t\t\t\t: this.oauthProvider;\n\t\t\t\t// Rewrite req.url to strip the '/oidc' prefix before delegating to oidc-provider\n\t\t\t\tconst originalUrl = req.url;\n\t\t\t\treq.url = (originalUrl || \"\").slice(5) || \"/\";\n\t\t\t\ttry {\n\t\t\t\t\treturn callback(req, res);\n\t\t\t\t} finally {\n\t\t\t\t\treq.url = originalUrl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// [SEC] RFC 9728 Protected Resource Metadata (PRM) Endpoint\n\t\t\tif (method === \"GET\" && url === \"/.well-known/oauth-protected-resource\") {\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst prm = buildProtectedResourceMetadata(\n\t\t\t\t\t\tthis.jwtValidator.getIssuer(),\n\t\t\t\t\t\tthis.jwtValidator.getAudience(),\n\t\t\t\t\t);\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(JSON.stringify(prm));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tmethod === \"GET\" &&\n\t\t\t\t(url === \"/\" || url === \"/mcp\" || url === \"/health\")\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\turl === \"/health\" &&\n\t\t\t\t\treq.headers.accept?.includes(\"application/json\")\n\t\t\t\t) {\n\t\t\t\t\tconst meshInfo = this.meshNode\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpeerId: this.meshNode.getPeerId()?.toString() || \"\",\n\t\t\t\t\t\t\t\tmultiaddrs: this.meshNode\n\t\t\t\t\t\t\t\t\t.getMultiaddrs()\n\t\t\t\t\t\t\t\t\t.map((m) => m.toString()),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null;\n\t\t\t\t\tconst issuer = this.jwtValidator?.getIssuer();\n\t\t\t\t\tconst baseUrl = issuer\n\t\t\t\t\t\t? issuer.endsWith(\"/oidc\")\n\t\t\t\t\t\t\t? issuer\n\t\t\t\t\t\t\t: `${issuer}/oidc`\n\t\t\t\t\t\t: \"\";\n\t\t\t\t\tconst authInfoResponse =\n\t\t\t\t\t\tthis.jwtValidator && issuer\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tissuer,\n\t\t\t\t\t\t\t\t\tjwks_uri: `${baseUrl}/jwks`,\n\t\t\t\t\t\t\t\t\t...(this.oauthProvider\n\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\ttoken_endpoint: `${baseUrl}/token`,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tconst topologyInfo = {\n\t\t\t\t\t\ttier: this.meshNode?.isPrivateNetwork?.() ? 1 : 2,\n\t\t\t\t\t\tprmEndpoint: this.jwtValidator\n\t\t\t\t\t\t\t? \"/.well-known/oauth-protected-resource\"\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\ttransportCapabilities: [\"http-mcp\", \"grpc-lio\", \"p2p-dht\"],\n\t\t\t\t\t};\n\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"healthy\",\n\t\t\t\t\t\t\tnode: this.liopServer.getServerInfo(),\n\t\t\t\t\t\t\tmesh: meshInfo,\n\t\t\t\t\t\t\ttools: this.liopServer.listTools().map((t) => t.name),\n\t\t\t\t\t\t\tauth: authInfoResponse,\n\t\t\t\t\t\t\ttopology: topologyInfo,\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(`\n <body style=\"background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0\">\n <div style=\"background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)\">\n <h1 style=\"color:#38bdf8;margin-top:0\">LIOP Protocol Transformer</h1>\n <p style=\"opacity:0.8;font-weight:600\">L4/L7 Transcoding: JSON-RPC &harr; gRPC</p>\n <p style=\"opacity:0.6;font-size:14px\">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>\n <div style=\"background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155\">\n <code style=\"color:#10b981\">Endpoint: http://localhost:3000/mcp</code>\n </div>\n </div>\n </body>\n `);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (url === \"/mcp\" && method === \"POST\") {\n\t\t\t\tlet authInfo: AuthInfo | null = null;\n\n\t\t\t\t// [SEC] Continuous verification of Bearer token (NIST SP 800-207)\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst authHeader = req.headers.authorization;\n\t\t\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\t\t\tres.writeHead(401, {\n\t\t\t\t\t\t\t\"WWW-Authenticate\":\n\t\t\t\t\t\t\t\t'Bearer error=\"invalid_token\", error_description=\"Missing or malformed Authorization header\"',\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(JSON.stringify({ error: \"Unauthorized\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tauthInfo = await this.jwtValidator.validate(authHeader.slice(7));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tres.writeHead(401, {\n\t\t\t\t\t\t\t\"WWW-Authenticate\": `Bearer error=\"invalid_token\", error_description=\"${(e as Error).message}\"`,\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(JSON.stringify({ error: \"Invalid token\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlet body = \"\";\n\t\t\t\treq.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\t\t\treq.on(\"end\", async () => {\n\t\t\t\t\t// [SEC] Rate limiting per IP or authenticated client (OWASP API4:2023)\n\t\t\t\t\tconst clientIp = req.socket.remoteAddress || \"127.0.0.1\";\n\t\t\t\t\tconst rateLimitKey = authInfo?.clientId\n\t\t\t\t\t\t? `client:${authInfo.clientId}`\n\t\t\t\t\t\t: `ip:${clientIp}`;\n\t\t\t\t\tconst rateStatus = this.rateLimiter.check(rateLimitKey);\n\t\t\t\t\tif (!rateStatus.allowed) {\n\t\t\t\t\t\tres.writeHead(429, {\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t\"Retry-After\": Math.ceil(rateStatus.resetMs / 1000).toString(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid: null,\n\t\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\t\tcode: -32029,\n\t\t\t\t\t\t\t\t\tmessage: \"Rate limit exceeded. Too many requests.\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst jsonRequest = JSON.parse(body);\n\n\t\t\t\t\t\t// [SEC] Perimeter Admission Hook (technology-agnostic)\n\t\t\t\t\t\t// Executes AFTER JWT + RateLimiter to prevent attackers from\n\t\t\t\t\t\t// exhausting external API quotas (e.g., TYPESAFE_API_KEY) with\n\t\t\t\t\t\t// unauthenticated or rate-limited traffic.\n\t\t\t\t\t\tif (this.interceptorOptions?.interceptor) {\n\t\t\t\t\t\t\tconst verdict = await executeGatewayInterceptor(\n\t\t\t\t\t\t\t\tjsonRequest,\n\t\t\t\t\t\t\t\t{ clientIp, authInfo, protocol: \"http1\" },\n\t\t\t\t\t\t\t\tthis.interceptorOptions as Required<\n\t\t\t\t\t\t\t\t\tPick<GatewayInterceptorOptions, \"interceptor\">\n\t\t\t\t\t\t\t\t> &\n\t\t\t\t\t\t\t\t\tGatewayInterceptorOptions,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!verdict.allowed) {\n\t\t\t\t\t\t\t\tres.writeHead(403, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\t\tid: jsonRequest.id ?? null,\n\t\t\t\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\t\t\t\tcode: verdict.errorCode ?? -32099,\n\t\t\t\t\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\t\t\t\tverdict.reason ||\n\t\t\t\t\t\t\t\t\t\t\t\t\"Forbidden: Rejected by Gateway Interceptor\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// [SEP-2243] Header-based routing validation\n\t\t\t\t\t\tconst mcpMethod = req.headers[\"mcp-method\"] as string | undefined;\n\t\t\t\t\t\tconst mcpName = req.headers[\"mcp-name\"] as string | undefined;\n\t\t\t\t\t\tconst mcpVersion = req.headers[\"mcp-protocol-version\"] as\n\t\t\t\t\t\t\t| string\n\t\t\t\t\t\t\t| undefined;\n\n\t\t\t\t\t\tif (mcpMethod && mcpMethod !== jsonRequest.method) {\n\t\t\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\tid: jsonRequest.id ?? null,\n\t\t\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\t\t\tcode: -32020,\n\t\t\t\t\t\t\t\t\t\tmessage: `HeaderMismatch: 'Mcp-Method' header (${mcpMethod}) does not match JSON-RPC method (${jsonRequest.method})`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tmcpName &&\n\t\t\t\t\t\t\tjsonRequest.params?.name &&\n\t\t\t\t\t\t\tmcpName !== jsonRequest.params.name\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\tid: jsonRequest.id ?? null,\n\t\t\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\t\t\tcode: -32020,\n\t\t\t\t\t\t\t\t\t\tmessage: `HeaderMismatch: 'Mcp-Name' header (${mcpName}) does not match target name (${jsonRequest.params.name})`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (mcpVersion && jsonRequest.params) {\n\t\t\t\t\t\t\tif (!jsonRequest.params._meta) {\n\t\t\t\t\t\t\t\tjsonRequest.params._meta = {};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!jsonRequest.params._meta[\n\t\t\t\t\t\t\t\t\t\"io.modelcontextprotocol/protocolVersion\"\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tjsonRequest.params._meta[\n\t\t\t\t\t\t\t\t\t\"io.modelcontextprotocol/protocolVersion\"\n\t\t\t\t\t\t\t\t] = mcpVersion;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst response = await this.router.dispatch(jsonRequest, authInfo);\n\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify(response));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Gateway] Error processing JSON-RPC payload: ${(e as Error).message}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tres.writeHead(400);\n\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\terror: { code: -32700, message: \"Parse error\" },\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate handleGrpcStream(stream: http2.ServerHttp2Stream) {\n\t\tstream.on(\"data\", (chunk: unknown) => {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Standard gRPC stream data is Buffer\n\t\t\tconst data = chunk as any;\n\t\t\tif (data)\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Native gRPC Proxy passing ${data.length} bytes`,\n\t\t\t\t);\n\t\t});\n\t\tstream.respond({ \":status\": 200, \"content-type\": \"application/grpc\" });\n\t\tstream.end();\n\t}\n\n\tprivate handleMcpH2Stream(\n\t\tstream: http2.ServerHttp2Stream,\n\t\theaders: http2.IncomingHttpHeaders,\n\t) {\n\t\tlet body = \"\";\n\t\tstream.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\tstream.on(\"end\", async () => {\n\t\t\ttry {\n\t\t\t\tlet authInfo: AuthInfo | null = null;\n\n\t\t\t\t// [SEC] Continuous verification of Bearer token over HTTP/2 (NIST SP 800-207)\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst authHeader = headers.authorization as string;\n\t\t\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 401,\n\t\t\t\t\t\t\t\"www-authenticate\":\n\t\t\t\t\t\t\t\t'Bearer error=\"invalid_token\", error_description=\"Missing or malformed Authorization header\"',\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(JSON.stringify({ error: \"Unauthorized\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tauthInfo = await this.jwtValidator.validate(authHeader.slice(7));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 401,\n\t\t\t\t\t\t\t\"www-authenticate\": `Bearer error=\"invalid_token\", error_description=\"${(e as Error).message}\"`,\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(JSON.stringify({ error: \"Invalid token\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst jsonRequest = JSON.parse(body);\n\n\t\t\t\t// [SEC] Perimeter Admission Hook (HTTP/2 symmetry)\n\t\t\t\tif (this.interceptorOptions?.interceptor) {\n\t\t\t\t\tconst h2ClientIp =\n\t\t\t\t\t\tstream.session?.socket?.remoteAddress || \"127.0.0.1\";\n\t\t\t\t\tconst verdict = await executeGatewayInterceptor(\n\t\t\t\t\t\tjsonRequest,\n\t\t\t\t\t\t{ clientIp: h2ClientIp, authInfo, protocol: \"http2\" },\n\t\t\t\t\t\tthis.interceptorOptions as Required<\n\t\t\t\t\t\t\tPick<GatewayInterceptorOptions, \"interceptor\">\n\t\t\t\t\t\t> &\n\t\t\t\t\t\t\tGatewayInterceptorOptions,\n\t\t\t\t\t);\n\t\t\t\t\tif (!verdict.allowed) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 403,\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid: jsonRequest.id ?? null,\n\t\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\t\tcode: verdict.errorCode ?? -32099,\n\t\t\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t\t\tverdict.reason ||\n\t\t\t\t\t\t\t\t\t\t\"Forbidden: Rejected by Gateway Interceptor\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// [SEP-2243] Header-based routing validation in HTTP/2\n\t\t\t\tconst mcpMethod = headers[\"mcp-method\"] as string | undefined;\n\t\t\t\tconst mcpName = headers[\"mcp-name\"] as string | undefined;\n\t\t\t\tconst mcpVersion = headers[\"mcp-protocol-version\"] as\n\t\t\t\t\t| string\n\t\t\t\t\t| undefined;\n\n\t\t\t\tif (mcpMethod && mcpMethod !== jsonRequest.method) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 400,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid: jsonRequest.id ?? null,\n\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: -32020,\n\t\t\t\t\t\t\t\tmessage: `HeaderMismatch: 'Mcp-Method' header (${mcpMethod}) does not match JSON-RPC method (${jsonRequest.method})`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tmcpName &&\n\t\t\t\t\tjsonRequest.params?.name &&\n\t\t\t\t\tmcpName !== jsonRequest.params.name\n\t\t\t\t) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 400,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid: jsonRequest.id ?? null,\n\t\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: -32020,\n\t\t\t\t\t\t\t\tmessage: `HeaderMismatch: 'Mcp-Name' header (${mcpName}) does not match target name (${jsonRequest.params.name})`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (mcpVersion && jsonRequest.params) {\n\t\t\t\t\tif (!jsonRequest.params._meta) {\n\t\t\t\t\t\tjsonRequest.params._meta = {};\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\t!jsonRequest.params._meta[\"io.modelcontextprotocol/protocolVersion\"]\n\t\t\t\t\t) {\n\t\t\t\t\t\tjsonRequest.params._meta[\n\t\t\t\t\t\t\t\"io.modelcontextprotocol/protocolVersion\"\n\t\t\t\t\t\t] = mcpVersion;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst response = await this.router.dispatch(jsonRequest, authInfo);\n\t\t\t\tif (response) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 200,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(JSON.stringify(response));\n\t\t\t\t} else stream.close();\n\t\t\t} catch (_e) {\n\t\t\t\tstream.respond({ \":status\": 400 });\n\t\t\t\tstream.end();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async listen(port: number, host: string = \"0.0.0.0\"): Promise<number> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.start();\n\n\t\t\t// Announce all local tools to the DHT\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\tfor (const tool of tools) {\n\t\t\t\tawait this.meshNode.announceCapability(tool.name);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] 📡 Announced local tool to Mesh: ${tool.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.netServer.on(\"error\", (err: Error & { code?: string }) => {\n\t\t\t\tif (err.code === \"EADDRINUSE\") {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Gateway] FATAL: Port ${port} is already in use by another process.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlog.error(`[LIOP-Gateway] Binding Error: ${err.message}`);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tthis.netServer.listen(port, host, () => {\n\t\t\t\tconst addr = this.netServer.address();\n\t\t\t\tconst actualHost =\n\t\t\t\t\ttypeof addr === \"string\" ? addr : addr?.address || host;\n\t\t\t\tconst assignedPort =\n\t\t\t\t\ttypeof addr === \"string\" ? port : addr?.port || port;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] ✅ Transformer Mesh Gateway READY and listening on ${actualHost}:${assignedPort}`,\n\t\t\t\t);\n\t\t\t\tresolve(assignedPort);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic isDrained(): boolean {\n\t\treturn this.isDraining;\n\t}\n\n\tpublic async drain(timeoutMs = 5000): Promise<void> {\n\t\tthis.isDraining = true;\n\t\tlog.info(\n\t\t\t`[LIOP-Gateway] Draining gateway connections (active: ${this.activeRequests}, timeout: ${timeoutMs}ms)...`,\n\t\t);\n\t\tconst start = Date.now();\n\t\twhile (this.activeRequests > 0 && Date.now() - start < timeoutMs) {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 50));\n\t\t}\n\t\tawait this.stop();\n\t}\n\n\tpublic async stop() {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t\tthis.rateLimiter.close();\n\t\tthis.netServer.close();\n\t\tthis.h2Server.close();\n\t\tthis.h1Server.close();\n\t}\n\n\tpublic getRouter(): LiopMcpRouter {\n\t\treturn this.router;\n\t}\n}\n"]}
@@ -73,5 +73,5 @@ var PromptSchema = z.object({
73
73
  });
74
74
 
75
75
  export { MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY, PromptSchema, ResourceSchema, ToolSchema, adaptResponseForLegacyClient, buildLegacyInitializeResponse, isLegacyRequest };
76
- //# sourceMappingURL=chunk-EG46XMJT.js.map
77
- //# sourceMappingURL=chunk-EG46XMJT.js.map
76
+ //# sourceMappingURL=chunk-NFFBJALJ.js.map
77
+ //# sourceMappingURL=chunk-NFFBJALJ.js.map