xypriss 9.14.21 → 9.14.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -11,6 +11,7 @@ var node_worker_threads = require('node:worker_threads');
11
11
  var os = require('node:os');
12
12
  var fs$1 = require('fs');
13
13
  var path$1 = require('path');
14
+ var util = require('node:util');
14
15
  var nehoid = require('nehoid');
15
16
  var net$1 = require('net');
16
17
  var reliantType = require('reliant-type');
@@ -962,7 +963,7 @@ class Logger {
962
963
  // Module helpers
963
964
  // ─────────────────────────────────────────────
964
965
  /** Shared singleton — ready to use immediately. */
965
- const logger$2 = Logger.getInstance();
966
+ const logger$1 = Logger.getInstance();
966
967
  /** Configure and return the singleton logger. */
967
968
  function initializeLogger(config) {
968
969
  return Logger.getInstance(config);
@@ -1084,7 +1085,7 @@ const defaultHelmetOpts = {
1084
1085
  };
1085
1086
  // Log a warning if the development profile is active
1086
1087
  if (isDev) {
1087
- logger$2.warn("security", "Development security profile active. CSP, COEP, and CORP headers are relaxed for local development. Learn more or customize: https://xypriss.nehonix.com/docs/security/enhanced-csp-configuration#development-security-profile-automatic");
1088
+ logger$1.warn("security", "Development security profile active. CSP, COEP, and CORP headers are relaxed for local development. Learn more or customize: https://xypriss.nehonix.com/docs/security/enhanced-csp-configuration#development-security-profile-automatic");
1088
1089
  }
1089
1090
 
1090
1091
  const xemsKeyPlaceholder = "CHANGE_ME_TO_A_SECURE_32_CHAR_KEY";
@@ -3744,6 +3745,20 @@ let socket = null;
3744
3745
  let rxChunks = [];
3745
3746
  let rxBytesTotal = 0;
3746
3747
  let isHandshaked = false;
3748
+ let pendingDispatch = false;
3749
+
3750
+ function flushDispatch() {
3751
+ if (!socket || socket.destroyed || !isHandshaked) return;
3752
+ const reqLen = Atomics.load(int32, IDX_REQ_LEN);
3753
+ const reqBytes = uint8.subarray(DATA_OFFSET, DATA_OFFSET + reqLen);
3754
+
3755
+ const h = Buffer.alloc(6);
3756
+ h.writeUInt8(0x53, 0);
3757
+ h.writeUInt8(0x03, 1); // MSG_CALL
3758
+ h.writeUInt32BE(reqBytes.length, 2);
3759
+
3760
+ socket.write(Buffer.concat([h, reqBytes]));
3761
+ }
3747
3762
 
3748
3763
  function pushChunk(chunk) {
3749
3764
  rxChunks.push(chunk);
@@ -3829,6 +3844,10 @@ function connectSocket() {
3829
3844
  isHandshaked = true;
3830
3845
  try { socket.unref(); } catch {}
3831
3846
  parentPort.postMessage({ type: "READY" });
3847
+ if (pendingDispatch) {
3848
+ pendingDispatch = false;
3849
+ flushDispatch();
3850
+ }
3832
3851
  }
3833
3852
  } else if (header.type === 0x04) { // MSG_RESPONSE
3834
3853
  uint8.set(payload, DATA_OFFSET);
@@ -3857,24 +3876,16 @@ function connectSocket() {
3857
3876
 
3858
3877
  parentPort.on("message", (msg) => {
3859
3878
  if (msg.type === "DISPATCH") {
3860
- if (!socket || socket.destroyed || !isHandshaked) {
3861
- const errPayload = Buffer.from(JSON.stringify({ ok: false, err: "libSynapx worker socket disconnected" }));
3862
- uint8.set(errPayload, DATA_OFFSET);
3863
- Atomics.store(int32, IDX_RESP_LEN, errPayload.length);
3864
- Atomics.store(int32, IDX_STATUS, STATUS_ERROR);
3865
- Atomics.notify(int32, IDX_STATUS, 1);
3879
+ if (!socket || socket.destroyed) {
3880
+ pendingDispatch = true;
3881
+ connectSocket();
3866
3882
  return;
3867
3883
  }
3868
-
3869
- const reqLen = Atomics.load(int32, IDX_REQ_LEN);
3870
- const reqBytes = uint8.subarray(DATA_OFFSET, DATA_OFFSET + reqLen);
3871
-
3872
- const h = Buffer.alloc(6);
3873
- h.writeUInt8(0x53, 0);
3874
- h.writeUInt8(0x03, 1); // MSG_CALL
3875
- h.writeUInt32BE(reqBytes.length, 2);
3876
-
3877
- socket.write(Buffer.concat([h, reqBytes]));
3884
+ if (!isHandshaked) {
3885
+ pendingDispatch = true;
3886
+ return;
3887
+ }
3888
+ flushDispatch();
3878
3889
  }
3879
3890
  });
3880
3891
 
@@ -4014,1725 +4025,872 @@ class SynapxSyncBridge {
4014
4025
  }
4015
4026
  SynapxSyncBridge.instance = null;
4016
4027
 
4028
+ /* *****************************************************************************
4029
+ * Nehonix libSynapx — TypeScript Client
4030
+ *
4031
+ * High-performance, persistent Zero-Trust IPC client connecting XyPriss
4032
+ * to the Go libSynapx engine over isolated Unix Domain Sockets / Named Pipes.
4033
+ ***************************************************************************** */
4034
+ // Protocol Constants (matching libSynapx Go wire format)
4035
+ const MAGIC_BYTE = 0x53; // 'S'
4036
+ const MSG_HANDSHAKE = 0x01;
4037
+ const MSG_HANDSHAKE_ACK = 0x02;
4038
+ const MSG_CALL = 0x03;
4039
+ const MSG_RESPONSE = 0x04;
4040
+ const MSG_PONG = 0x08;
4041
+ const MSG_ERROR = 0xff;
4042
+ const HEADER_SIZE$1 = 6;
4017
4043
  /**
4018
- * ANSI color codes for terminal output
4044
+ * **SynapxClient**
4045
+ *
4046
+ * Persistent, multiplexed IPC client connecting TypeScript to the Go libSynapx core.
4019
4047
  */
4020
- const ANSI = {
4021
- reset: "\x1b[0m",
4022
- bold: "\x1b[1m",
4023
- dim: "\x1b[2m",
4024
- // Foreground colors
4025
- black: "\x1b[30m",
4026
- yellow: "\x1b[33m",
4027
- blue: "\x1b[34m",
4028
- cyan: "\x1b[36m",
4029
- white: "\x1b[37m",
4030
- gray: "\x1b[90m",
4031
- // Bright foreground
4032
- brightRed: "\x1b[91m",
4033
- brightGreen: "\x1b[92m",
4034
- brightYellow: "\x1b[93m",
4035
- brightBlue: "\x1b[94m",
4036
- brightMagenta: "\x1b[95m",
4037
- brightCyan: "\x1b[96m",
4038
- // Background colors
4039
- bgRed: "\x1b[41m",
4040
- bgGreen: "\x1b[42m",
4041
- bgYellow: "\x1b[43m",
4042
- bgBlue: "\x1b[44m",
4043
- bgMagenta: "\x1b[45m",
4044
- bgCyan: "\x1b[46m",
4045
- };
4046
- const LOG_CONFIGS = {
4047
- info: {
4048
- icon: "ℹ️ ",
4049
- color: ANSI.brightCyan,
4050
- label: "INFO",
4051
- labelColor: `${ANSI.bgCyan}${ANSI.black}`,
4052
- },
4053
- success: {
4054
- icon: "✅",
4055
- color: ANSI.brightGreen,
4056
- label: "OK",
4057
- labelColor: `${ANSI.bgGreen}${ANSI.black}`,
4058
- },
4059
- warn: {
4060
- icon: "⚠️ ",
4061
- color: ANSI.brightYellow,
4062
- label: "WARN",
4063
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4064
- },
4065
- error: {
4066
- icon: "❌",
4067
- color: ANSI.brightRed,
4068
- label: "ERROR",
4069
- labelColor: `${ANSI.bgRed}${ANSI.white}`,
4070
- },
4071
- debug: {
4072
- icon: "-",
4073
- color: ANSI.gray,
4074
- label: "DEBUG",
4075
- labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
4076
- },
4077
- http: {
4078
- icon: "🌐",
4079
- color: ANSI.brightBlue,
4080
- label: "HTTP",
4081
- labelColor: `${ANSI.bgBlue}${ANSI.white}`,
4082
- },
4083
- swagger: {
4084
- icon: "🛡️ ",
4085
- color: ANSI.brightMagenta,
4086
- label: "SWAGGER",
4087
- labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
4088
- },
4089
- db: {
4090
- icon: "🗄️ ",
4091
- color: ANSI.yellow,
4092
- label: "DB",
4093
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4094
- },
4095
- auth: {
4096
- icon: "🔐",
4097
- color: ANSI.brightYellow,
4098
- label: "AUTH",
4099
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4100
- },
4101
- };
4102
- const LEVEL_RANK = {
4103
- silent: 0,
4104
- error: 1,
4105
- warn: 2,
4106
- info: 3,
4107
- success: 3,
4108
- http: 3,
4109
- swagger: 3,
4110
- db: 3,
4111
- auth: 3,
4112
- debug: 4,
4113
- verbose: 5,
4114
- };
4115
- class QuickLogger {
4116
- constructor(context) {
4117
- this.context = context;
4118
- }
4119
- // ─── Static factory ───────────────────────────────────────────────────────
4120
- static for(context) {
4121
- return new QuickLogger(context);
4048
+ class SynapxClient {
4049
+ /**
4050
+ * Appends a newly received socket chunk to the internal accumulator.
4051
+ */
4052
+ pushChunk(chunk) {
4053
+ this.rxChunks.push(chunk);
4054
+ this.rxBytesTotal += chunk.length;
4122
4055
  }
4123
- static shouldLog(level) {
4124
- const sys = getSysApi();
4125
- let isDebug = false;
4126
- if (sys?.__env__) {
4127
- isDebug =
4128
- sys.__env__.get("DEBUG") ||
4129
- sys.__env__.get("XYPRISS_DEBUG") ||
4130
- sys.__env__.get("DEBUG_FS");
4056
+ /**
4057
+ * Peeks at the framing header without mutating or eagerly concatenating the chunk buffer.
4058
+ */
4059
+ peekHeader() {
4060
+ if (this.rxBytesTotal < HEADER_SIZE$1)
4061
+ return null;
4062
+ const first = this.rxChunks[0];
4063
+ if (first.length >= HEADER_SIZE$1) {
4064
+ return {
4065
+ magic: first.readUInt8(0),
4066
+ msgType: first.readUInt8(1),
4067
+ length: first.readUInt32BE(2),
4068
+ };
4131
4069
  }
4132
- else if (typeof process !== "undefined" && process.env) {
4133
- isDebug =
4134
- process.env.DEBUG ||
4135
- process.env.XYPRISS_DEBUG ||
4136
- process.env.DEBUG_FS;
4070
+ const hdr = Buffer.allocUnsafe(HEADER_SIZE$1);
4071
+ let copied = 0;
4072
+ for (const chunk of this.rxChunks) {
4073
+ const toCopy = Math.min(chunk.length, HEADER_SIZE$1 - copied);
4074
+ chunk.copy(hdr, copied, 0, toCopy);
4075
+ copied += toCopy;
4076
+ if (copied >= HEADER_SIZE$1)
4077
+ break;
4137
4078
  }
4138
- if (isDebug) {
4139
- return true;
4079
+ return {
4080
+ magic: hdr.readUInt8(0),
4081
+ msgType: hdr.readUInt8(1),
4082
+ length: hdr.readUInt32BE(2),
4083
+ };
4084
+ }
4085
+ /**
4086
+ * Consumes exactly numBytes from the front of the chunk list in a single fast copy.
4087
+ */
4088
+ consumeBytes(numBytes) {
4089
+ if (numBytes === 0)
4090
+ return Buffer.alloc(0);
4091
+ if (this.rxChunks.length === 1 && this.rxChunks[0].length === numBytes) {
4092
+ const buf = this.rxChunks[0];
4093
+ this.rxChunks = [];
4094
+ this.rxBytesTotal = 0;
4095
+ return buf;
4140
4096
  }
4141
- try {
4142
- const logging = ConfigurationManager.get("logging");
4143
- if (logging) {
4144
- if (logging.enabled === false) {
4145
- return false;
4146
- }
4147
- // Check logging.types overrides
4148
- if (level === "error" && logging.types?.errors === false)
4149
- return false;
4150
- if (level === "warn" && logging.types?.warnings === false)
4151
- return false;
4152
- if (level === "debug" && logging.types?.debug === false)
4153
- return false;
4154
- if (level === "debug" && logging.types?.debug === true)
4155
- return true;
4156
- // Check logging.level rank
4157
- const configuredLevel = (logging.level || "info").toLowerCase();
4158
- const configuredRank = LEVEL_RANK[configuredLevel] ?? 3;
4159
- const messageRank = LEVEL_RANK[level] ?? 3;
4160
- return messageRank <= configuredRank;
4097
+ const result = Buffer.allocUnsafe(numBytes);
4098
+ let offset = 0;
4099
+ while (this.rxChunks.length > 0 && offset < numBytes) {
4100
+ const head = this.rxChunks[0];
4101
+ const needed = numBytes - offset;
4102
+ if (head.length <= needed) {
4103
+ head.copy(result, offset);
4104
+ offset += head.length;
4105
+ this.rxChunks.shift();
4106
+ }
4107
+ else {
4108
+ head.copy(result, offset, 0, needed);
4109
+ offset += needed;
4110
+ this.rxChunks[0] = head.subarray(needed);
4161
4111
  }
4162
4112
  }
4163
- catch { }
4164
- // Default ranking if no config: info level (rank 3)
4165
- const defaultRank = 3;
4166
- const messageRank = LEVEL_RANK[level] ?? 3;
4167
- return messageRank <= defaultRank;
4113
+ this.rxBytesTotal -= numBytes;
4114
+ return result;
4168
4115
  }
4169
- // ─── Core log method ──────────────────────────────────────────────────────
4170
- log(level, ...args) {
4171
- if (!QuickLogger.shouldLog(level)) {
4172
- return;
4116
+ /**
4117
+ * Resynchronizes stream by advancing past corrupt bytes to the next magic byte.
4118
+ */
4119
+ discardUntilMagic() {
4120
+ while (this.rxChunks.length > 0) {
4121
+ const head = this.rxChunks[0];
4122
+ const idx = head.indexOf(MAGIC_BYTE);
4123
+ if (idx !== -1) {
4124
+ if (idx > 0) {
4125
+ this.consumeBytes(idx);
4126
+ }
4127
+ return true;
4128
+ }
4129
+ else {
4130
+ this.rxBytesTotal -= head.length;
4131
+ this.rxChunks.shift();
4132
+ }
4173
4133
  }
4174
- const cfg = LOG_CONFIGS[level];
4175
- const timestamp = QuickLogger.showTimestamp
4176
- ? `${ANSI.dim}${ANSI.gray}${new Date().toISOString()}${ANSI.reset} `
4177
- : "";
4178
- const label = `${cfg.labelColor}${ANSI.bold} ${cfg.label} ${ANSI.reset}`;
4179
- const ctx = `${ANSI.dim}${ANSI.cyan}[${this.context}]${ANSI.reset}`;
4180
- // First arg gets the level color + icon, rest are passed raw so Node.js
4181
- // pretty-prints objects/arrays/Errors natively (no JSON.stringify needed).
4182
- const [first, ...rest] = args;
4183
- const prefix = `${timestamp}${label} ${ctx} ${cfg.color}${cfg.icon} ${String(first)}${ANSI.reset}`;
4184
- const consoleFn = level === "error"
4185
- ? console.error
4186
- : level === "warn"
4187
- ? console.warn
4188
- : console.log;
4189
- rest.length > 0 ? consoleFn(prefix, ...rest) : consoleFn(prefix);
4190
- }
4191
- // ─── Public methods ───────────────────────────────────────────────────────
4192
- info(...args) {
4193
- this.log("info", ...args);
4194
- }
4195
- success(...args) {
4196
- this.log("success", ...args);
4197
- }
4198
- warn(...args) {
4199
- this.log("warn", ...args);
4200
- }
4201
- error(...args) {
4202
- this.log("error", ...args);
4203
- }
4204
- debug(...args) {
4205
- this.log("debug", ...args);
4206
- }
4207
- http(...args) {
4208
- this.log("http", ...args);
4209
- }
4210
- swagger(...args) {
4211
- this.log("swagger", ...args);
4212
- }
4213
- db(...args) {
4214
- this.log("db", ...args);
4215
- }
4216
- auth(...args) {
4217
- this.log("auth", ...args);
4218
- }
4219
- // ─── Convenience: banner / separator ─────────────────────────────────────
4220
- banner(title) {
4221
- const line = `${ANSI.blue}${"─".repeat(60)}${ANSI.reset}`;
4222
- const centered = title
4223
- .padStart(30 + Math.floor(title.length / 2))
4224
- .padEnd(60);
4225
- console.log(`\n${line}`);
4226
- console.log(`${ANSI.bold}${ANSI.brightCyan}${centered}${ANSI.reset}`);
4227
- console.log(`${line}\n`);
4228
- }
4229
- }
4230
- QuickLogger.showTimestamp = true;
4231
- // ─── Default singleton logger ──────────────────────────────────────────────
4232
- // export const logger = QuickLogger.for("");
4233
-
4234
- /**
4235
- * Returns the absolute path to the XyPriss shared temp directory.
4236
- *
4237
- * @returns {string} Path to `<os.tmpdir>/nehonix.xypriss.data`
4238
- */
4239
- function getXyprissTempDir() {
4240
- const sys = getSysApi();
4241
- return sys.path.join(sys.path.tempDir(), "nehonix.xypriss.data");
4242
- }
4243
- /**
4244
- * Resolves and ensures a sub-path within the XyPriss temp directory exists.
4245
- *
4246
- * @param {string | string[]} _p - Sub-path segment(s) to append.
4247
- * @returns {string} The absolute resolved temp sub-path.
4248
- */
4249
- function createXyprissTempDir(_p) {
4250
- const sys = getSysApi();
4251
- const base = getXyprissTempDir();
4252
- const segment = typeof _p === "string"
4253
- ? _p
4254
- : _p.includes("/")
4255
- ? _p.map((p) => p.replace("/", "")).join("/")
4256
- : _p.join("/");
4257
- // Use the native corrective layer to prevent doubling or redundant separators
4258
- const rawPath = segment.startsWith(base)
4259
- ? segment
4260
- : sys.path.join(base, segment);
4261
- const normalisedPath = sys.path.correct(rawPath, { tentative: 2 });
4262
- if (!sys.fs.exist(normalisedPath)) {
4263
- sys.fs.mkdir(normalisedPath, { parents: true });
4264
- }
4265
- return normalisedPath;
4266
- }
4267
- /**
4268
- * **Session Temp Directory (singleton)**
4269
- *
4270
- * Unique sub-path generated once per process lifetime under the XyPriss
4271
- * temp root (`<os.tmpdir>/nehonix.xypriss.data/xuser/<hex4>`).
4272
- *
4273
- * The value is memoized on first access and remains stable for the entire
4274
- * duration of the running process, ensuring all callers within the same
4275
- * session share the same isolated scratch space.
4276
- */
4277
- let _sessionTmpDir = null;
4278
- /**
4279
- * Returns the process-scoped user temp directory path for THIS active server instance.
4280
- *
4281
- * Generates an instance ID hash once and caches it for the lifetime of the process.
4282
- * E.g. `/tmp/nehonix.xypriss.data/xuser/12daa75a`
4283
- *
4284
- * @returns {string} Absolute path to instance temp directory
4285
- */
4286
- function generateXUserTmpDir() {
4287
- if (_sessionTmpDir !== null) {
4288
- return _sessionTmpDir;
4134
+ return false;
4289
4135
  }
4290
- const sys = getSysApi();
4291
- // 1. Adopt the session directory allocated exclusively by the libProc supervisor
4292
- const envSession = sys?.__env__?.get("XYPRISS_USER_TMP") ||
4293
- sys?.__env__?.get("XESS_SESSION_TMP") ||
4294
- (typeof process !== "undefined"
4295
- ? (process.env?.XYPRISS_USER_TMP || process.env?.XESS_SESSION_TMP)
4296
- : undefined);
4297
- if (envSession && typeof envSession === "string") {
4298
- _sessionTmpDir = envSession;
4299
- if (sys?.fs && !sys.fs.exist(_sessionTmpDir)) {
4300
- sys.fs.mkdir(_sessionTmpDir, { parents: true });
4136
+ constructor(customSocketPath) {
4137
+ this.socket = null;
4138
+ this.connectingPromise = null;
4139
+ this.isHandshakeComplete = false;
4140
+ this.sessionKey = "";
4141
+ this.seqId = 0;
4142
+ this.pendingCalls = new Map();
4143
+ this.rxChunks = [];
4144
+ this.rxBytesTotal = 0;
4145
+ this.syncBridge = null;
4146
+ this.lastDaemonSpawnTime = 0;
4147
+ const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP || "";
4148
+ this.sessionHash =
4149
+ process.env.XYPRISS_SESSION_HASH ||
4150
+ (sessionDir ? path__namespace.basename(sessionDir) : "");
4151
+ this.authToken =
4152
+ process.env.XYPRISS_INTERNAL_TOKEN ||
4153
+ process.env.XYPRISS_XESS_AUTH_TOKEN ||
4154
+ "";
4155
+ if (!this.authToken && sessionDir) {
4156
+ try {
4157
+ const tokenFile = path__namespace.join(sessionDir, ".auth_token");
4158
+ if (fs__namespace.existsSync(tokenFile)) {
4159
+ this.authToken = fs__namespace.readFileSync(tokenFile, "utf8").trim();
4160
+ }
4161
+ }
4162
+ catch { }
4301
4163
  }
4302
- return _sessionTmpDir;
4303
- }
4304
- // No supervisor session provisioned by libProc: unconfined execution has no valid session
4305
- return "";
4306
- }
4307
- /**
4308
- * Returns the unique 8-character session hash ID for the active server instance.
4309
- * Delegated exclusively to the libProc supervisor (Single Source of Truth).
4310
- */
4311
- function getSessionHash() {
4312
- const sys = getSysApi();
4313
- const envHash = sys?.__env__?.get("XYPRISS_SESSION_HASH") ||
4314
- (typeof process !== "undefined" ? process.env?.XYPRISS_SESSION_HASH : undefined);
4315
- if (envHash && typeof envHash === "string") {
4316
- return envHash;
4164
+ this.socketPath =
4165
+ customSocketPath ||
4166
+ (sessionDir ? path__namespace.join(sessionDir, "synapx.sock") : "");
4317
4167
  }
4318
- if (_sessionTmpDir) {
4319
- if (sys?.path) {
4320
- return sys.path.basename(_sessionTmpDir);
4168
+ /**
4169
+ * Singleton instance accessor bound to the active process session.
4170
+ */
4171
+ static getInstance(socketPath) {
4172
+ if (!SynapxClient.instance) {
4173
+ SynapxClient.instance = new SynapxClient(socketPath);
4321
4174
  }
4322
- const parts = _sessionTmpDir.split(/[/\\]/).filter(Boolean);
4323
- return parts[parts.length - 1] || "";
4324
- }
4325
- return "";
4326
- }
4327
- /**
4328
- * Backward-compatibility alias for getSessionHash().
4329
- */
4330
- function getInstanceId() {
4331
- return getSessionHash();
4332
- }
4333
- /**
4334
- * **Scoped libXESS Temp Directory**
4335
- *
4336
- * Scopes libXESS temporary decoys and IPC socket files inside the dedicated
4337
- * session temp directory under `xuser` (`<tmpdir>/nehonix.xypriss.data/xuser/<instanceId>/xess`).
4338
- *
4339
- * @returns {string} Absolute path to instance xess temp directory
4340
- */
4341
- function getXessTempDir() {
4342
- const sys = getSysApi();
4343
- const envXess = sys?.__env__?.get("XESS_TEMP_DIR") ||
4344
- (typeof process !== "undefined" ? process.env?.XESS_TEMP_DIR : undefined);
4345
- if (envXess && typeof envXess === "string") {
4346
- return envXess;
4347
- }
4348
- const sessionDir = generateXUserTmpDir();
4349
- if (!sessionDir) {
4350
- return "";
4351
- }
4352
- const xessDir = sys?.path ? sys.path.join(sessionDir, "xess") : `${sessionDir}/xess`;
4353
- if (sys?.fs && !sys.fs.exist(xessDir)) {
4354
- sys.fs.mkdir(xessDir, { parents: true });
4355
- }
4356
- return xessDir;
4357
- }
4358
-
4359
- /**
4360
- * Checks if a given file path belongs to the deep engine core.
4361
- * These files are skipped during stack analysis to find the user/plugin caller.
4362
- */
4363
- function isEngineCorePath(filePath) {
4364
- if (!filePath)
4365
- return false;
4366
- const normalizedPath = filePath.replace(/\\/g, "/");
4367
- if (normalizedPath.includes("/XyPriss/src/") ||
4368
- normalizedPath.includes("/XyPriss/dist/") ||
4369
- normalizedPath.includes("/node_modules/xypriss/")) {
4370
- return true;
4175
+ return SynapxClient.instance;
4371
4176
  }
4372
- return false;
4373
- }
4374
- /**
4375
- * Checks if a given file path belongs directly to the XyPriss Core Engine
4376
- * or if it comes from an external plugin / user space.
4377
- * This is used for SECURITY authorization.
4378
- */
4379
- function isCoreFrameworkPath(filePath) {
4380
- if (!filePath)
4381
- return false;
4382
- const normalizedPath = filePath.replace(/\\/g, "/");
4383
- // Authorize trusted internal mods within the framework repository
4384
- if (normalizedPath.includes("/XyPriss/mods/"))
4385
- return true;
4386
- // Exclude other plugins even if they contain 'src' or are named 'xypriss-something'
4387
- if (normalizedPath.includes("/mods/"))
4388
- return false;
4389
- // Engine Core is always trusted
4390
- return isEngineCorePath(filePath);
4391
- }
4392
-
4393
- const logger$1 = new QuickLogger("LibXESS");
4394
- // Module-scoped security closures - strictly isolated from globalThis and reflection APIs
4395
- const _secretsCache = new Map();
4396
- let _ephemeralAuthToken = "";
4397
- let _activeSessionKey = "";
4398
- let _isLibxessActive = false;
4399
- // Immediately consume the one-shot token at module evaluation time
4400
- if (typeof process !== "undefined") {
4401
- if (process.env?.LIBXESS_ACTIVE === "1") {
4402
- _isLibxessActive = true;
4403
- }
4404
- if (process.env?.XYPRISS_XESS_SESSION_KEY) {
4405
- _activeSessionKey = process.env.XYPRISS_XESS_SESSION_KEY;
4406
- _isLibxessActive = true;
4407
- }
4408
- if (process.env?.XYPRISS_XESS_AUTH_TOKEN) {
4409
- _ephemeralAuthToken = process.env.XYPRISS_XESS_AUTH_TOKEN;
4410
- _isLibxessActive = true;
4411
- try {
4412
- delete process.env.XYPRISS_XESS_AUTH_TOKEN;
4413
- }
4414
- catch { }
4177
+ getSocketPath() {
4178
+ return this.socketPath;
4415
4179
  }
4416
- }
4417
- const ppidScope = typeof process !== "undefined" && process.ppid ? process.ppid : "sys";
4418
- const SESSION_BRIDGE_KEY = Symbol.for(`__xypriss_session_bridge_${ppidScope}__`);
4419
- function getSessionBridge() {
4420
- const g = globalThis;
4421
- if (!g[SESSION_BRIDGE_KEY]) {
4422
- let bridgeSessionKey = "";
4423
- let bridgeCache = new Map();
4424
- const bridge = {
4425
- getSessionKey: () => {
4426
- assertInternalCaller();
4427
- return bridgeSessionKey;
4428
- },
4429
- getSecretsCache: () => {
4430
- assertInternalCaller();
4431
- return bridgeCache;
4432
- },
4433
- registerSession: (key, cache) => {
4434
- assertInternalCaller();
4435
- if (key) {
4436
- bridgeSessionKey = key;
4437
- }
4438
- if (cache) {
4439
- bridgeCache = cache;
4440
- }
4441
- },
4442
- };
4180
+ isAvailable() {
4181
+ if (!this.socketPath)
4182
+ return false;
4443
4183
  try {
4444
- Object.defineProperty(g, SESSION_BRIDGE_KEY, {
4445
- value: bridge,
4446
- writable: false,
4447
- enumerable: false,
4448
- configurable: false,
4449
- });
4184
+ return fs__namespace.existsSync(this.socketPath);
4450
4185
  }
4451
4186
  catch {
4452
- g[SESSION_BRIDGE_KEY] = bridge;
4187
+ return false;
4453
4188
  }
4454
4189
  }
4455
- return g[SESSION_BRIDGE_KEY];
4456
- }
4457
- /**
4458
- * Asserts that the caller executing this method is directly part of the internal
4459
- * XyPriss engine core. External plugins or untrusted scripts attempting to invoke
4460
- * XessIpcClient are immediately rejected and halted.
4461
- */
4462
- function assertInternalCaller() {
4463
- const stack = new Error().stack || "";
4464
- const lines = stack.split("\n");
4465
- let callerFile = "";
4466
- for (let i = 1; i < lines.length; i++) {
4467
- const line = lines[i];
4468
- if (line.includes("XessIpcClient.") ||
4469
- line.includes("assertInternalCaller") ||
4470
- line.includes("getSessionBridge") ||
4471
- line.includes("registerSession") ||
4472
- line.includes("getSessionKey") ||
4473
- line.includes("getSecretsCache")) {
4474
- continue;
4475
- }
4476
- const match = line.match(/\((.*):\d+:\d+\)$/) ||
4477
- line.match(/at (.*):\d+:\d+$/) ||
4478
- line.match(/at (.*)$/);
4479
- if (match) {
4480
- callerFile = match[1];
4481
- break;
4482
- }
4483
- }
4484
- if (callerFile && !isCoreFrameworkPath(callerFile)) {
4485
- logger$1.error(`[libXESS Security Violation] Direct invocation of XessIpcClient from unauthorized caller '${callerFile}'. Confinement violation: halting process.`);
4486
- process.exit(1);
4487
- }
4488
- }
4489
- /**
4490
- * **XessIpcClient**
4491
- *
4492
- * Client IPC sécurisé pour communiquer avec le superviseur libXESS.
4493
- * Permet de récupérer les secrets authentiques en mémoire RAM via Unix Domain Socket
4494
- * tout en maintenant l'isolation bipolaire (le fichier .env sur disque étant un leurre canary).
4495
- *
4496
- * L'adresse du socket IPC est résolue de manière déterministe hors process.env
4497
- * à partir de l'empreinte cryptographique XSec de la racine du projet.
4498
- */
4499
- class XessIpcClient {
4500
- static get secretsCache() {
4501
- try {
4502
- const bridge = getSessionBridge();
4503
- const cache = bridge.getSecretsCache();
4504
- if (cache) {
4505
- return cache;
4506
- }
4507
- }
4508
- catch { }
4509
- return _secretsCache;
4190
+ resolveBinary() {
4191
+ const envPath = Discovery.getFromEnv("XYPRISS_XHSC_PATH");
4192
+ if (envPath)
4193
+ return envPath;
4194
+ const osPart = Platform.getOsPart();
4195
+ const archPart = Platform.getArchPart();
4196
+ const suffix = Platform.getBinarySuffix();
4197
+ const goBinName = `xhsc-${osPart}-${archPart}${suffix}`;
4198
+ const genericBinName = osPart === "windows" ? "xhsc.exe" : "xhsc";
4199
+ const candidates = [goBinName, genericBinName];
4200
+ const searchBases = [];
4201
+ const scriptDir = Discovery.getScriptDir();
4202
+ if (scriptDir)
4203
+ searchBases.push(scriptDir);
4204
+ searchBases.push(process.cwd());
4205
+ const resolved = Discovery.resolveBinary(candidates, searchBases);
4206
+ if (resolved)
4207
+ return resolved;
4208
+ return genericBinName;
4510
4209
  }
4511
4210
  /**
4512
- * Calcule la liste des emplacements potentiels du socket IPC libXESS pour un répertoire donné.
4513
- * Privilégie le dossier dédié scoped dans xuser/ tout en conservant les fallbacks.
4211
+ * Ensures the confined xhsc background daemon is spawned inside the libXESS sandbox
4212
+ * if the IPC socket is not yet accessible.
4514
4213
  */
4515
- static getSocketCandidatesForDir(dir) {
4516
- const hash = xyprissSecurity.Cipher.hash
4517
- .create(path__namespace.resolve(dir), { algorithm: "sha256" })
4518
- .toString("hex")
4519
- .slice(0, 12);
4520
- const fileName = `xess_ipc_${hash}.sock`;
4521
- const candidates = [];
4522
- // Emplacement unique scoped sous la session courante fournie par libproc
4523
- try {
4524
- const xessDir = getXessTempDir();
4525
- if (xessDir) {
4526
- candidates.push(path__namespace.join(xessDir, fileName));
4527
- }
4214
+ ensureDaemon() {
4215
+ if (this.isAvailable()) {
4216
+ return;
4528
4217
  }
4529
- catch { }
4530
- try {
4531
- const sessionDir = generateXUserTmpDir();
4532
- if (sessionDir) {
4533
- candidates.push(path__namespace.join(sessionDir, "xess", fileName));
4534
- candidates.push(path__namespace.join(sessionDir, fileName));
4535
- }
4218
+ const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP;
4219
+ if (!sessionDir) {
4220
+ return;
4536
4221
  }
4537
- catch { }
4538
- return candidates;
4539
- }
4540
- /**
4541
- * Liste ordonnée de tous les chemins de sockets candidats potentiels :
4542
- * 1. process.cwd() (dossier d'exécution du CLI xfpm / superviseur libXESS)
4543
- * 2. projectDir (dossier du projet ou plugin ciblé)
4544
- * 3. Répertoires parents ascendants
4545
- */
4546
- static getCandidateSocketPaths(projectDir) {
4547
- const candidates = [];
4548
- const seen = new Set();
4549
- const addDirHierarchy = (dir) => {
4550
- let current = path__namespace.resolve(dir);
4551
- while (current && !seen.has(current)) {
4552
- seen.add(current);
4553
- const candidatesForDir = XessIpcClient.getSocketCandidatesForDir(current);
4554
- for (const candidate of candidatesForDir) {
4555
- if (fs__namespace.existsSync(candidate) && !candidates.includes(candidate)) {
4556
- candidates.push(candidate);
4557
- }
4558
- }
4559
- const parent = path__namespace.dirname(current);
4560
- if (parent === current)
4561
- break;
4562
- current = parent;
4563
- }
4564
- };
4565
- // 2. Dossier de travail courant (process.cwd()) où xfpm ancre son superviseur
4566
- if (typeof process !== "undefined" && process.cwd) {
4567
- addDirHierarchy(process.cwd());
4222
+ if (Date.now() - this.lastDaemonSpawnTime < 3000) {
4223
+ return;
4568
4224
  }
4569
- // 3. Dossier de projet spécifique si différent
4570
- if (projectDir) {
4571
- addDirHierarchy(projectDir);
4225
+ this.lastDaemonSpawnTime = Date.now();
4226
+ const binPath = this.resolveBinary();
4227
+ if (!binPath) {
4228
+ return;
4572
4229
  }
4573
- // 4. Sockets provisionnés directement dans le xessDir de cette session supervisée
4230
+ const internalSig = getInternalSignature();
4574
4231
  try {
4575
- const xessDir = getXessTempDir();
4576
- if (xessDir && fs__namespace.existsSync(xessDir)) {
4577
- const files = fs__namespace.readdirSync(xessDir);
4578
- for (const f of files) {
4579
- if (f.startsWith("xess_ipc_") && f.endsWith(".sock")) {
4580
- const sock = path__namespace.join(xessDir, f);
4581
- if (!candidates.includes(sock)) {
4582
- candidates.push(sock);
4583
- }
4584
- }
4232
+ const child = node_child_process.spawn(binPath, ["daemon", process.cwd()], {
4233
+ detached: true,
4234
+ stdio: "inherit",
4235
+ env: {
4236
+ ...process.env,
4237
+ ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
4238
+ NO_COLOR: "1",
4239
+ },
4240
+ });
4241
+ let childExited = false;
4242
+ child.on("exit", () => {
4243
+ childExited = true;
4244
+ });
4245
+ child.on("error", () => {
4246
+ childExited = true;
4247
+ });
4248
+ child.unref();
4249
+ // Wait for socket to appear (up to 1500ms)
4250
+ const start = Date.now();
4251
+ while (Date.now() - start < 1500) {
4252
+ if (this.isAvailable() || childExited) {
4253
+ break;
4254
+ }
4255
+ try {
4256
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
4257
+ }
4258
+ catch {
4259
+ const t = Date.now() + 20;
4260
+ while (Date.now() < t) { }
4585
4261
  }
4586
4262
  }
4587
4263
  }
4588
- catch { }
4589
- return candidates;
4590
- }
4591
- /**
4592
- * Effectue une vérification synchrone de liveness sur un socket IPC.
4593
- * Si le fichier socket existe sur le disque mais que le superviseur est mort (ECONNREFUSED / timeout),
4594
- * le socket fantôme est immédiatement purgé du disque et la fonction retourne false.
4595
- */
4596
- static probeSocketSync(socketPath) {
4597
- if (!fs__namespace.existsSync(socketPath))
4598
- return false;
4599
- // Fast-path: When running under active libXESS supervisor, socket presence confirms shielding
4600
- if (_isLibxessActive ||
4601
- process.env?.LIBXESS_ACTIVE === "1" ||
4602
- process.env?.XYPRISS_USER_TMP ||
4603
- process.env?.XESS_TEMP_DIR) {
4604
- return true;
4605
- }
4606
- const script = `
4607
- const net = require("net");
4608
- const sock = process.argv[1];
4609
- const client = net.createConnection(sock, () => {
4610
- client.end();
4611
- process.exit(0);
4612
- });
4613
- client.on("error", () => process.exit(1));
4614
- setTimeout(() => process.exit(1), 1000);
4615
- `;
4616
- try {
4617
- node_child_process.execFileSync(process.execPath, ["-e", script, socketPath], {
4618
- timeout: 1500,
4619
- stdio: "ignore",
4620
- });
4621
- return true;
4622
- }
4623
4264
  catch {
4624
- return false;
4265
+ // Silently allow fallback
4625
4266
  }
4626
4267
  }
4627
4268
  /**
4628
- * Résout déterministement le chemin du socket IPC libXESS actif.
4269
+ * Connects to the libSynapx server and performs the Zero-Trust handshake.
4629
4270
  */
4630
- static resolveSocketPath(projectDir) {
4631
- const candidates = this.getCandidateSocketPaths(projectDir);
4632
- for (const candidate of candidates) {
4633
- if (this.probeSocketSync(candidate)) {
4634
- return candidate;
4635
- }
4271
+ async connect() {
4272
+ if (this.socket && !this.socket.destroyed && this.isHandshakeComplete) {
4273
+ return;
4636
4274
  }
4637
- return undefined;
4638
- }
4639
- /**
4640
- * Vérifie si le runtime tourne sous le confinement actif de libXESS.
4641
- */
4642
- static isShielded(projectDir) {
4643
- const authToken = this.getOrConsumeAuthToken();
4644
- const sessionKey = this.getSessionKey();
4645
- const isActive = typeof process !== "undefined" &&
4646
- (_isLibxessActive ||
4647
- process.env?.LIBXESS_ACTIVE === "1" ||
4648
- !!authToken ||
4649
- !!sessionKey);
4650
- if (!isActive) {
4651
- return false;
4275
+ if (!this.isAvailable()) {
4276
+ this.ensureDaemon();
4652
4277
  }
4653
- const candidates = this.getCandidateSocketPaths(projectDir);
4654
- for (const candidate of candidates) {
4655
- if (this.probeSocketSync(candidate)) {
4656
- return true;
4657
- }
4278
+ if (this.connectingPromise) {
4279
+ return this.connectingPromise;
4658
4280
  }
4659
- return false;
4281
+ this.connectingPromise = new Promise((resolve, reject) => {
4282
+ if (!this.socketPath) {
4283
+ return reject(new Error("libSynapx: No active session socket path configured (XYPRISS_USER_TMP is unset)"));
4284
+ }
4285
+ const client = net__namespace.createConnection(this.socketPath, () => {
4286
+ this.socket = client;
4287
+ this.performHandshake()
4288
+ .then(() => {
4289
+ this.isHandshakeComplete = true;
4290
+ resolve();
4291
+ })
4292
+ .catch((err) => {
4293
+ this.destroy();
4294
+ reject(err);
4295
+ });
4296
+ });
4297
+ client.on("data", (chunk) => this.onData(chunk));
4298
+ client.on("error", (err) => {
4299
+ if (!this.isHandshakeComplete) {
4300
+ reject(err);
4301
+ }
4302
+ this.destroy();
4303
+ });
4304
+ client.on("close", () => {
4305
+ this.destroy();
4306
+ });
4307
+ }).finally(() => {
4308
+ this.connectingPromise = null;
4309
+ });
4310
+ return this.connectingPromise;
4660
4311
  }
4661
4312
  /**
4662
- * Récupère le chemin du socket IPC libXESS.
4313
+ * Writes a framed packet to the socket.
4663
4314
  */
4664
- static getSocketPath(projectDir) {
4665
- return this.resolveSocketPath(projectDir);
4315
+ writeFrame(msgType, payload) {
4316
+ if (!this.socket || this.socket.destroyed) {
4317
+ throw new Error("libSynapx: socket is not connected");
4318
+ }
4319
+ const header = Buffer.alloc(HEADER_SIZE$1);
4320
+ header.writeUInt8(MAGIC_BYTE, 0);
4321
+ header.writeUInt8(msgType, 1);
4322
+ header.writeUInt32BE(payload.length, 2);
4323
+ this.socket.write(Buffer.concat([header, payload]));
4666
4324
  }
4667
4325
  /**
4668
- * Récupère le jeton d'authentification éphémère libXESS et purge immédiatement
4669
- * la variable d'environnement de la mémoire pour empêcher toute réutilisation non autorisée.
4326
+ * Performs initial zero-trust handshake.
4670
4327
  */
4671
- static getOrConsumeAuthToken() {
4672
- if (_ephemeralAuthToken) {
4673
- return _ephemeralAuthToken;
4674
- }
4675
- if (typeof process !== "undefined" && process.env?.XYPRISS_XESS_AUTH_TOKEN) {
4676
- _ephemeralAuthToken = process.env.XYPRISS_XESS_AUTH_TOKEN;
4328
+ async performHandshake() {
4329
+ return new Promise((resolve, reject) => {
4330
+ const timeout = setTimeout(() => {
4331
+ reject(new Error("libSynapx: Handshake timed out"));
4332
+ }, 3000);
4333
+ const hsPayload = Buffer.from(JSON.stringify({
4334
+ sessionHash: this.sessionHash,
4335
+ token: this.authToken,
4336
+ clientPid: process.pid,
4337
+ }));
4338
+ // Temporarily intercept handshake response frame
4339
+ const originalOnData = this.onData;
4340
+ this.onData = (chunk) => {
4341
+ this.pushChunk(chunk);
4342
+ while (true) {
4343
+ const header = this.peekHeader();
4344
+ if (!header)
4345
+ return;
4346
+ if (header.magic !== MAGIC_BYTE) {
4347
+ clearTimeout(timeout);
4348
+ this.onData = originalOnData;
4349
+ return reject(new Error("libSynapx: Invalid magic byte in handshake response"));
4350
+ }
4351
+ if (this.rxBytesTotal < HEADER_SIZE$1 + header.length) {
4352
+ return; // Wait for full frame
4353
+ }
4354
+ this.consumeBytes(HEADER_SIZE$1);
4355
+ const payloadBuf = this.consumeBytes(header.length);
4356
+ clearTimeout(timeout);
4357
+ this.onData = originalOnData;
4358
+ if (header.msgType === MSG_HANDSHAKE_ACK) {
4359
+ try {
4360
+ const ack = JSON.parse(payloadBuf.toString("utf8"));
4361
+ if (ack.auth) {
4362
+ this.sessionKey = ack.sessionKey || "";
4363
+ try {
4364
+ this.socket?.unref();
4365
+ }
4366
+ catch { }
4367
+ return resolve();
4368
+ }
4369
+ return reject(new Error(`libSynapx: Handshake unauthorized: ${ack.err || "unknown"}`));
4370
+ }
4371
+ catch (e) {
4372
+ return reject(e);
4373
+ }
4374
+ }
4375
+ else {
4376
+ return reject(new Error(`libSynapx: Expected HandshakeAck (0x02), received 0x${header.msgType.toString(16)}`));
4377
+ }
4378
+ }
4379
+ };
4677
4380
  try {
4678
- delete process.env.XYPRISS_XESS_AUTH_TOKEN;
4381
+ this.writeFrame(MSG_HANDSHAKE, hsPayload);
4679
4382
  }
4680
- catch { }
4681
- }
4682
- return _ephemeralAuthToken;
4383
+ catch (err) {
4384
+ clearTimeout(timeout);
4385
+ this.onData = originalOnData;
4386
+ reject(err);
4387
+ }
4388
+ });
4683
4389
  }
4684
4390
  /**
4685
- * Exposes the currently active session key for secure propagation to child worker processes.
4391
+ * Processes incoming streamed chunks from the socket.
4686
4392
  */
4687
- static getActiveSessionKey() {
4688
- return this.getSessionKey();
4689
- }
4690
- static getSessionKey() {
4691
- if (_activeSessionKey) {
4692
- return _activeSessionKey;
4693
- }
4694
- if (typeof process !== "undefined" && process.env?.XYPRISS_XESS_SESSION_KEY) {
4695
- _activeSessionKey = process.env.XYPRISS_XESS_SESSION_KEY;
4696
- return _activeSessionKey;
4697
- }
4698
- try {
4699
- const bridge = getSessionBridge();
4700
- const key = bridge.getSessionKey();
4701
- if (key) {
4702
- _activeSessionKey = key;
4703
- return key;
4393
+ onData(chunk) {
4394
+ this.pushChunk(chunk);
4395
+ while (true) {
4396
+ const header = this.peekHeader();
4397
+ if (!header)
4398
+ break;
4399
+ if (header.magic !== MAGIC_BYTE) {
4400
+ this.consumeBytes(1);
4401
+ this.discardUntilMagic();
4402
+ continue;
4403
+ }
4404
+ if (this.rxBytesTotal < HEADER_SIZE$1 + header.length) {
4405
+ break; // Incomplete packet, wait for more data
4704
4406
  }
4407
+ this.consumeBytes(HEADER_SIZE$1);
4408
+ const payloadBuf = this.consumeBytes(header.length);
4409
+ this.dispatchIncomingFrame(header.msgType, payloadBuf);
4705
4410
  }
4706
- catch { }
4707
- return "";
4708
- }
4709
- static setSessionKey(key) {
4710
- _activeSessionKey = key;
4711
- _ephemeralAuthToken = "";
4712
- try {
4713
- const bridge = getSessionBridge();
4714
- bridge.registerSession(key, _secretsCache);
4715
- }
4716
- catch { }
4717
4411
  }
4718
4412
  /**
4719
- * Récupération synchrone des secrets lors du bootstrap initial.
4720
- * Tente les sockets candidats et purge automatiquement les sockets fantômes résiduels.
4413
+ * Routes decoded incoming packets to pending call promises.
4721
4414
  */
4722
- static fetchSecretsSync(projectDirOrSocket) {
4723
- assertInternalCaller();
4724
- let candidates = [];
4725
- if (projectDirOrSocket &&
4726
- (projectDirOrSocket.endsWith(".sock") ||
4727
- (fs__namespace.existsSync(projectDirOrSocket) &&
4728
- !fs__namespace.statSync(projectDirOrSocket).isDirectory()))) {
4729
- candidates = [projectDirOrSocket];
4730
- }
4731
- else {
4732
- candidates = this.getCandidateSocketPaths(projectDirOrSocket);
4733
- }
4734
- const targetDir = projectDirOrSocket && !projectDirOrSocket.endsWith(".sock")
4735
- ? path__namespace.resolve(projectDirOrSocket)
4736
- : "";
4737
- const cacheKey = targetDir || "__root__";
4738
- if (this.secretsCache.has(cacheKey)) {
4739
- return this.secretsCache.get(cacheKey);
4740
- }
4741
- const authToken = this.getOrConsumeAuthToken();
4742
- const sessionKey = this.getSessionKey();
4743
- const isShieldedActive = typeof process !== "undefined" &&
4744
- (_isLibxessActive ||
4745
- process.env?.LIBXESS_ACTIVE === "1" ||
4746
- !!authToken ||
4747
- !!sessionKey);
4748
- if (!isShieldedActive) {
4749
- // Mode sans confinement libXESS (ex: exécution hors xfpm ou sans le flag -l xess)
4750
- const envPath = path__namespace.join(targetDir || (typeof process !== "undefined" ? process.cwd() : ""), ".env");
4751
- if (fs__namespace.existsSync(envPath)) {
4415
+ dispatchIncomingFrame(msgType, payloadBuf) {
4416
+ switch (msgType) {
4417
+ case MSG_RESPONSE: {
4752
4418
  try {
4753
- const raw = fs__namespace.readFileSync(envPath, "utf-8");
4754
- const parsed = {};
4755
- for (const line of raw.split("\n")) {
4756
- const trimmed = line.trim();
4757
- if (!trimmed || trimmed.startsWith("#"))
4758
- continue;
4759
- const eqIdx = trimmed.indexOf("=");
4760
- if (eqIdx !== -1) {
4761
- const k = trimmed.slice(0, eqIdx).trim();
4762
- let v = trimmed.slice(eqIdx + 1).trim();
4763
- if ((v.startsWith('"') && v.endsWith('"')) ||
4764
- (v.startsWith("'") && v.endsWith("'"))) {
4765
- v = v.slice(1, -1);
4766
- }
4767
- parsed[k] = v;
4419
+ const resp = JSON.parse(payloadBuf.toString("utf8"));
4420
+ const pending = this.pendingCalls.get(resp.id);
4421
+ if (pending) {
4422
+ clearTimeout(pending.timeout);
4423
+ this.pendingCalls.delete(resp.id);
4424
+ if (resp.ok) {
4425
+ pending.resolve(resp.data);
4426
+ }
4427
+ else {
4428
+ pending.reject(new Error(resp.err || "libSynapx operation failed"));
4768
4429
  }
4769
4430
  }
4770
- this.secretsCache.set(cacheKey, parsed);
4771
- return parsed;
4772
4431
  }
4773
4432
  catch { }
4433
+ break;
4434
+ }
4435
+ case MSG_PONG:
4436
+ break;
4437
+ case MSG_ERROR: {
4438
+ try {
4439
+ const errObj = JSON.parse(payloadBuf.toString("utf8"));
4440
+ const errMsg = errObj.error || "libSynapx protocol error";
4441
+ for (const [id, pending] of this.pendingCalls.entries()) {
4442
+ clearTimeout(pending.timeout);
4443
+ pending.reject(new Error(errMsg));
4444
+ }
4445
+ this.pendingCalls.clear();
4446
+ }
4447
+ catch { }
4448
+ break;
4774
4449
  }
4775
- return {};
4776
4450
  }
4777
- if (candidates.length === 0) {
4778
- const msg = "[libXESS] No active libXESS Bridge found for project. Direct execution without libXESS confinement is strictly prohibited.";
4779
- logger$1.error(msg);
4780
- process.exit(1);
4451
+ }
4452
+ /**
4453
+ * Executes a multiplexed RPC call over the persistent private channel with full args and options descriptors.
4454
+ */
4455
+ async call(module, action, args = [], opts = {}, timeoutMs = 60000) {
4456
+ await this.connect();
4457
+ const stringArgs = Array.isArray(args)
4458
+ ? args.map((a) => String(a))
4459
+ : [];
4460
+ const id = ++this.seqId;
4461
+ const callPayload = Buffer.from(JSON.stringify({
4462
+ id,
4463
+ mod: module,
4464
+ action,
4465
+ args: stringArgs,
4466
+ opts: opts || {},
4467
+ }));
4468
+ const effectiveTimeout = typeof opts?.timeout === "number" ? opts.timeout : timeoutMs;
4469
+ return new Promise((resolve, reject) => {
4470
+ const timeout = setTimeout(() => {
4471
+ this.pendingCalls.delete(id);
4472
+ reject(new Error(`libSynapx: Call timed out after ${effectiveTimeout}ms [${module}.${action}]`));
4473
+ }, effectiveTimeout);
4474
+ this.pendingCalls.set(id, {
4475
+ resolve,
4476
+ reject,
4477
+ timeout,
4478
+ });
4479
+ try {
4480
+ this.writeFrame(MSG_CALL, callPayload);
4481
+ }
4482
+ catch (err) {
4483
+ clearTimeout(timeout);
4484
+ this.pendingCalls.delete(id);
4485
+ reject(err);
4486
+ }
4487
+ });
4488
+ }
4489
+ /**
4490
+ * Synchronous RPC via ultra-fast SharedArrayBuffer Futex Bridge (Path 1)
4491
+ * with transparent automatic fallback to stdin pipe subprocess on edge platforms.
4492
+ */
4493
+ callSync(module, action, args = [], opts = {}) {
4494
+ if (!this.socketPath || !fs__namespace.existsSync(this.socketPath)) {
4495
+ this.ensureDaemon();
4496
+ if (!this.socketPath || !fs__namespace.existsSync(this.socketPath)) {
4497
+ throw new Error(`libSynapx: socket '${this.socketPath || "unknown"}' not found or active daemon is offline`);
4498
+ }
4499
+ }
4500
+ try {
4501
+ if (!this.syncBridge) {
4502
+ this.syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.authToken);
4503
+ }
4504
+ return this.syncBridge.callSync(module, action, args, opts);
4505
+ }
4506
+ catch {
4507
+ // Resilient fallback to stdin subprocess pipeline
4508
+ return this.callSyncSubprocess(module, action, args, opts);
4781
4509
  }
4782
- const action = sessionKey ? "GET_PROJECT" : "HANDSHAKE";
4783
- const credential = sessionKey || authToken;
4510
+ }
4511
+ /**
4512
+ * Subprocess-based synchronous fallback pipeline (streaming via stdin to prevent E2BIG).
4513
+ */
4514
+ callSyncSubprocess(module, action, args = [], opts = {}) {
4515
+ const stringArgs = Array.isArray(args)
4516
+ ? args.map((a) => String(a))
4517
+ : [];
4784
4518
  const script = `
4785
4519
  const net = require("net");
4786
4520
  const fs = require("fs");
4787
4521
  const sock = process.argv[1];
4788
- let rawInput = "";
4789
- try {
4790
- rawInput = fs.readFileSync(0, "utf-8");
4791
- } catch (e) {
4792
- process.exit(1);
4793
- }
4794
- let payload;
4522
+ const hash = process.argv[2] || "";
4523
+ const token = process.argv[3] || "";
4524
+
4525
+ let inputData = "";
4795
4526
  try {
4796
- payload = JSON.parse(rawInput);
4797
- } catch (e) {
4798
- process.exit(1);
4799
- }
4527
+ inputData = fs.readFileSync(0, "utf8");
4528
+ } catch {}
4529
+
4530
+ const req = JSON.parse(inputData || "{}");
4531
+ const mod = req.mod;
4532
+ const act = req.action;
4533
+ const args = req.args || [];
4534
+ const opts = req.opts || {};
4535
+
4800
4536
  const client = net.createConnection(sock, () => {
4801
- client.write(JSON.stringify(payload) + "\\n");
4537
+ // 1. Handshake
4538
+ const hs = Buffer.from(JSON.stringify({ sessionHash: hash, token: token, clientPid: process.pid }));
4539
+ const h1 = Buffer.alloc(6);
4540
+ h1.writeUInt8(0x53, 0);
4541
+ h1.writeUInt8(0x01, 1);
4542
+ h1.writeUInt32BE(hs.length, 2);
4543
+ client.write(Buffer.concat([h1, hs]));
4802
4544
  });
4803
- let data = "";
4545
+
4546
+ let buf = Buffer.alloc(0);
4547
+ let handshaked = false;
4548
+
4804
4549
  client.on("data", (chunk) => {
4805
- data += chunk.toString();
4806
- if (data.includes("\\n")) {
4807
- client.end();
4808
- process.stdout.write(data.trim());
4809
- process.exit(0);
4550
+ buf = Buffer.concat([buf, chunk]);
4551
+ while (buf.length >= 6) {
4552
+ if (buf.readUInt8(0) !== 0x53) { process.exit(1); }
4553
+ const type = buf.readUInt8(1);
4554
+ const len = buf.readUInt32BE(2);
4555
+ if (buf.length < 6 + len) return;
4556
+ const payload = buf.subarray(6, 6 + len);
4557
+ buf = buf.subarray(6 + len);
4558
+
4559
+ if (!handshaked) {
4560
+ if (type === 0x02) {
4561
+ handshaked = true;
4562
+ const call = Buffer.from(JSON.stringify({ id: 1, mod: mod, action: act, args: args, opts: opts }));
4563
+ const h2 = Buffer.alloc(6);
4564
+ h2.writeUInt8(0x53, 0);
4565
+ h2.writeUInt8(0x03, 1);
4566
+ h2.writeUInt32BE(call.length, 2);
4567
+ client.write(Buffer.concat([h2, call]));
4568
+ } else { process.exit(1); }
4569
+ } else {
4570
+ if (type === 0x04) {
4571
+ process.stdout.write(payload);
4572
+ client.end();
4573
+ process.exit(0);
4574
+ } else { process.exit(1); }
4575
+ }
4810
4576
  }
4811
4577
  });
4812
- client.on("error", (err) => {
4813
- process.stderr.write(err.message);
4814
- process.exit(1);
4815
- });
4816
- setTimeout(() => { process.exit(1); }, 3000);
4578
+ setTimeout(() => process.exit(1), 5000);
4817
4579
  `;
4818
- const inputPayload = JSON.stringify(action === "HANDSHAKE"
4819
- ? { action: "HANDSHAKE", projectDir: targetDir, token: credential }
4820
- : { action: action, projectDir: targetDir, sessionKey: credential });
4821
- let lastErr;
4822
- for (const sock of candidates) {
4823
- try {
4824
- // Pass sensitive credentials exclusively via private stdin pipe, NEVER in process.argv
4825
- const output = node_child_process.execFileSync(process.execPath, ["-e", script, sock], {
4826
- input: inputPayload,
4827
- encoding: "utf8",
4828
- timeout: 3000,
4829
- stdio: ["pipe", "pipe", "pipe"],
4830
- });
4831
- const parsed = JSON.parse(output.trim());
4832
- if (parsed.action === "UNAUTHORIZED" || parsed.error) {
4833
- const msg = `[libXESS] Authentication rejected: ${parsed.error || "Unauthorized"}. Confinement violation.`;
4834
- logger$1.error(msg);
4835
- process.exit(1);
4836
- }
4837
- if (parsed.sessionKey) {
4838
- this.setSessionKey(parsed.sessionKey);
4839
- }
4840
- if (parsed && parsed.secrets) {
4841
- this.secretsCache.set(cacheKey, parsed.secrets);
4842
- return parsed.secrets;
4843
- }
4844
- }
4845
- catch (err) {
4846
- lastErr = err;
4847
- }
4580
+ const inputPayload = JSON.stringify({
4581
+ mod: module,
4582
+ action,
4583
+ args: stringArgs,
4584
+ opts: opts || {},
4585
+ });
4586
+ const output = node_child_process.execFileSync(process.execPath, [
4587
+ "-e",
4588
+ script,
4589
+ this.socketPath,
4590
+ this.sessionHash,
4591
+ this.authToken,
4592
+ ], {
4593
+ input: inputPayload,
4594
+ encoding: "utf8",
4595
+ timeout: 5000,
4596
+ maxBuffer: 100 * 1024 * 1024,
4597
+ stdio: ["pipe", "pipe", "pipe"],
4598
+ });
4599
+ const parsed = JSON.parse(output.trim());
4600
+ if (!parsed.ok) {
4601
+ throw new Error(parsed.err || "libSynapx call failed");
4848
4602
  }
4849
- const msg = `[libXESS] Failed to fetch secrets from libXESS: ${lastErr?.message || "unknown error"}. Confinement violation: halting execution.`;
4850
- logger$1.error(msg);
4851
- process.exit(1);
4603
+ return parsed.data;
4852
4604
  }
4853
- /**
4854
- * Récupération asynchrone des secrets via net.Socket natif.
4855
- */
4856
- static async fetchSecretsAsync(projectDirOrSocket) {
4857
- assertInternalCaller();
4858
- let candidates = [];
4859
- if (projectDirOrSocket &&
4860
- (projectDirOrSocket.endsWith(".sock") ||
4861
- (fs__namespace.existsSync(projectDirOrSocket) &&
4862
- !fs__namespace.statSync(projectDirOrSocket).isDirectory()))) {
4863
- candidates = [projectDirOrSocket];
4864
- }
4865
- else {
4866
- candidates = this.getCandidateSocketPaths(projectDirOrSocket);
4867
- }
4868
- const targetDir = projectDirOrSocket && !projectDirOrSocket.endsWith(".sock")
4869
- ? path__namespace.resolve(projectDirOrSocket)
4870
- : "";
4871
- const cacheKey = targetDir || "__root__";
4872
- if (this.secretsCache.has(cacheKey)) {
4873
- return this.secretsCache.get(cacheKey);
4874
- }
4875
- const authToken = this.getOrConsumeAuthToken();
4876
- const sessionKey = this.getSessionKey();
4877
- const isShieldedActive = typeof process !== "undefined" &&
4878
- (_isLibxessActive ||
4879
- process.env?.LIBXESS_ACTIVE === "1" ||
4880
- !!authToken ||
4881
- !!sessionKey);
4882
- if (!isShieldedActive) {
4883
- const envPath = path__namespace.join(targetDir || (typeof process !== "undefined" ? process.cwd() : ""), ".env");
4884
- if (fs__namespace.existsSync(envPath)) {
4885
- try {
4886
- const raw = fs__namespace.readFileSync(envPath, "utf-8");
4887
- const parsed = {};
4888
- for (const line of raw.split("\n")) {
4889
- const trimmed = line.trim();
4890
- if (!trimmed || trimmed.startsWith("#"))
4891
- continue;
4892
- const eqIdx = trimmed.indexOf("=");
4893
- if (eqIdx !== -1) {
4894
- const k = trimmed.slice(0, eqIdx).trim();
4895
- let v = trimmed.slice(eqIdx + 1).trim();
4896
- if ((v.startsWith('"') && v.endsWith('"')) ||
4897
- (v.startsWith("'") && v.endsWith("'"))) {
4898
- v = v.slice(1, -1);
4899
- }
4900
- parsed[k] = v;
4901
- }
4902
- }
4903
- this.secretsCache.set(cacheKey, parsed);
4904
- return parsed;
4905
- }
4906
- catch { }
4907
- }
4908
- return {};
4605
+ destroy() {
4606
+ this.isHandshakeComplete = false;
4607
+ if (this.syncBridge) {
4608
+ this.syncBridge.destroy();
4609
+ this.syncBridge = null;
4909
4610
  }
4910
- if (candidates.length === 0) {
4911
- const msg = "[libXESS] No active libXESS Bridge found for project. Direct execution without libXESS confinement is strictly prohibited.";
4912
- logger$1.error(msg);
4913
- process.exit(1);
4611
+ if (this.socket) {
4612
+ this.socket.removeAllListeners();
4613
+ this.socket.destroy();
4614
+ this.socket = null;
4914
4615
  }
4915
- const action = sessionKey ? "GET_PROJECT" : "HANDSHAKE";
4916
- const credential = sessionKey || authToken;
4917
- let lastErr;
4918
- for (const sock of candidates) {
4919
- try {
4920
- const secrets = await new Promise((resolve, reject) => {
4921
- const client = net__namespace.createConnection(sock, () => {
4922
- const payload = action === "HANDSHAKE"
4923
- ? { action: "HANDSHAKE", projectDir: targetDir, token: credential }
4924
- : { action: action, projectDir: targetDir, sessionKey: credential };
4925
- client.write(JSON.stringify(payload) + "\n");
4926
- });
4927
- let buffer = "";
4928
- const timeout = setTimeout(() => {
4929
- client.destroy();
4930
- reject(new Error("Socket timeout"));
4931
- }, 3000);
4932
- client.on("data", (chunk) => {
4933
- buffer += chunk.toString();
4934
- if (buffer.includes("\n")) {
4935
- clearTimeout(timeout);
4936
- client.end();
4937
- try {
4938
- const parsed = JSON.parse(buffer.trim());
4939
- if (parsed.action === "UNAUTHORIZED" || parsed.error) {
4940
- logger$1.error(`[libXESS] Authentication rejected: ${parsed.error || "Unauthorized"}`);
4941
- process.exit(1);
4942
- }
4943
- if (parsed.sessionKey) {
4944
- this.setSessionKey(parsed.sessionKey);
4945
- }
4946
- const sec = parsed.secrets || {};
4947
- this.secretsCache.set(cacheKey, sec);
4948
- resolve(sec);
4949
- }
4950
- catch (e) {
4951
- resolve({});
4952
- }
4953
- }
4954
- });
4955
- client.on("error", (err) => {
4956
- clearTimeout(timeout);
4957
- client.destroy();
4958
- reject(err);
4959
- });
4960
- });
4961
- return secrets;
4962
- }
4963
- catch (err) {
4964
- lastErr = err;
4965
- }
4616
+ for (const [id, pending] of this.pendingCalls.entries()) {
4617
+ clearTimeout(pending.timeout);
4618
+ pending.reject(new Error("libSynapx: socket disconnected"));
4966
4619
  }
4967
- const msg = `[libXESS] Failed to fetch secrets from libXESS: ${lastErr?.message || "unknown error"}. Confinement violation: halting execution.`;
4968
- logger$1.error(msg);
4969
- process.exit(1);
4620
+ this.pendingCalls.clear();
4621
+ this.rxChunks = [];
4622
+ this.rxBytesTotal = 0;
4970
4623
  }
4971
4624
  }
4625
+ SynapxClient.instance = null;
4972
4626
 
4973
- /* *****************************************************************************
4974
- * Nehonix libSynapx — TypeScript Client
4975
- *
4976
- * High-performance, persistent Zero-Trust IPC client connecting XyPriss
4977
- * to the Go libSynapx engine over isolated Unix Domain Sockets / Named Pipes.
4978
- ***************************************************************************** */
4979
- // Protocol Constants (matching libSynapx Go wire format)
4980
- const MAGIC_BYTE = 0x53; // 'S'
4981
- const MSG_HANDSHAKE = 0x01;
4982
- const MSG_HANDSHAKE_ACK = 0x02;
4983
- const MSG_CALL = 0x03;
4984
- const MSG_RESPONSE = 0x04;
4985
- const MSG_PONG = 0x08;
4986
- const MSG_ERROR = 0xff;
4987
- const HEADER_SIZE$1 = 6;
4988
4627
  /**
4989
- * **SynapxClient**
4990
- *
4991
- * Persistent, multiplexed IPC client connecting TypeScript to the Go libSynapx core.
4628
+ * Custom error class for XyPriss system operations.
4992
4629
  */
4993
- class SynapxClient {
4994
- /**
4995
- * Appends a newly received socket chunk to the internal accumulator.
4996
- */
4997
- pushChunk(chunk) {
4998
- this.rxChunks.push(chunk);
4999
- this.rxBytesTotal += chunk.length;
5000
- }
5001
- /**
5002
- * Peeks at the framing header without mutating or eagerly concatenating the chunk buffer.
5003
- */
5004
- peekHeader() {
5005
- if (this.rxBytesTotal < HEADER_SIZE$1)
5006
- return null;
5007
- const first = this.rxChunks[0];
5008
- if (first.length >= HEADER_SIZE$1) {
5009
- return {
5010
- magic: first.readUInt8(0),
5011
- msgType: first.readUInt8(1),
5012
- length: first.readUInt32BE(2),
5013
- };
5014
- }
5015
- const hdr = Buffer.allocUnsafe(HEADER_SIZE$1);
5016
- let copied = 0;
5017
- for (const chunk of this.rxChunks) {
5018
- const toCopy = Math.min(chunk.length, HEADER_SIZE$1 - copied);
5019
- chunk.copy(hdr, copied, 0, toCopy);
5020
- copied += toCopy;
5021
- if (copied >= HEADER_SIZE$1)
5022
- break;
5023
- }
5024
- return {
5025
- magic: hdr.readUInt8(0),
5026
- msgType: hdr.readUInt8(1),
5027
- length: hdr.readUInt32BE(2),
5028
- };
4630
+ class XyPrissError extends Error {
4631
+ constructor(module, action, details, raw) {
4632
+ super(`[XyPriss Error] ${module}.${action} failed: ${details}`);
4633
+ this.module = module;
4634
+ this.action = action;
4635
+ this.details = details;
4636
+ this.raw = raw;
4637
+ this.name = "XyPrissError";
5029
4638
  }
5030
- /**
5031
- * Consumes exactly numBytes from the front of the chunk list in a single fast copy.
5032
- */
5033
- consumeBytes(numBytes) {
5034
- if (numBytes === 0)
5035
- return Buffer.alloc(0);
5036
- if (this.rxChunks.length === 1 && this.rxChunks[0].length === numBytes) {
5037
- const buf = this.rxChunks[0];
5038
- this.rxChunks = [];
5039
- this.rxBytesTotal = 0;
5040
- return buf;
5041
- }
5042
- const result = Buffer.allocUnsafe(numBytes);
5043
- let offset = 0;
5044
- while (this.rxChunks.length > 0 && offset < numBytes) {
5045
- const head = this.rxChunks[0];
5046
- const needed = numBytes - offset;
5047
- if (head.length <= needed) {
5048
- head.copy(result, offset);
5049
- offset += head.length;
5050
- this.rxChunks.shift();
5051
- }
5052
- else {
5053
- head.copy(result, offset, 0, needed);
5054
- offset += needed;
5055
- this.rxChunks[0] = head.subarray(needed);
5056
- }
5057
- }
5058
- this.rxBytesTotal -= numBytes;
5059
- return result;
4639
+ }
4640
+ /**
4641
+ * **Native System Runner**
4642
+ *
4643
+ * This class serves as the core bridge between the Node.js runtime and the
4644
+ * high-performance system core. It manages process spawning, argument
4645
+ * serialization, and bidirectional streaming.
4646
+ */
4647
+ class XyPrissRunner {
4648
+ constructor(root) {
4649
+ this.root = root;
4650
+ this.binaryPath = this.discoverBinary();
4651
+ // console.log(
4652
+ // "[XyPrissRunner:getBinaryPath] Binary path: ",
4653
+ // this.discoverBinary(),
4654
+ // );
5060
4655
  }
5061
- /**
5062
- * Resynchronizes stream by advancing past corrupt bytes to the next magic byte.
5063
- */
5064
- discardUntilMagic() {
5065
- while (this.rxChunks.length > 0) {
5066
- const head = this.rxChunks[0];
5067
- const idx = head.indexOf(MAGIC_BYTE);
5068
- if (idx !== -1) {
5069
- if (idx > 0) {
5070
- this.consumeBytes(idx);
5071
- }
5072
- return true;
5073
- }
5074
- else {
5075
- this.rxBytesTotal -= head.length;
5076
- this.rxChunks.shift();
5077
- }
5078
- }
5079
- return false;
4656
+ getRoot() {
4657
+ // console.log("[XyPrissRunner:getRoot] Binary root: ", this.root);
4658
+ return this.root;
5080
4659
  }
5081
- constructor(customSocketPath) {
5082
- this.socket = null;
5083
- this.connectingPromise = null;
5084
- this.isHandshakeComplete = false;
5085
- this.sessionKey = "";
5086
- this.seqId = 0;
5087
- this.pendingCalls = new Map();
5088
- this.rxChunks = [];
5089
- this.rxBytesTotal = 0;
5090
- this.syncBridge = null;
5091
- this.lastDaemonSpawnTime = 0;
5092
- const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP || "";
5093
- this.sessionHash =
5094
- process.env.XYPRISS_SESSION_HASH ||
5095
- (sessionDir ? path__namespace.basename(sessionDir) : "");
5096
- this.authToken =
5097
- process.env.XYPRISS_INTERNAL_TOKEN ||
5098
- process.env.XYPRISS_XESS_AUTH_TOKEN ||
5099
- "";
5100
- this.socketPath =
5101
- customSocketPath ||
5102
- (sessionDir ? path__namespace.join(sessionDir, "synapx.sock") : "");
4660
+ getBinaryPath() {
4661
+ return this.binaryPath;
5103
4662
  }
5104
4663
  /**
5105
- * Singleton instance accessor bound to the active process session.
4664
+ * Strategic discovery of the XyPriss System binary.
4665
+ * Prioritizes the high-performance Go implementation (XHSC-GO).
5106
4666
  */
5107
- static getInstance(socketPath) {
5108
- if (!SynapxClient.instance) {
5109
- SynapxClient.instance = new SynapxClient(socketPath);
5110
- }
5111
- return SynapxClient.instance;
5112
- }
5113
- getSocketPath() {
5114
- return this.socketPath;
5115
- }
5116
- isAvailable() {
5117
- if (!this.socketPath)
5118
- return false;
5119
- try {
5120
- return fs__namespace.existsSync(this.socketPath);
5121
- }
5122
- catch {
5123
- return false;
5124
- }
5125
- }
5126
- resolveBinary() {
4667
+ discoverBinary() {
4668
+ // 1. Environment Variable Override (Highest Priority)
5127
4669
  const envPath = Discovery.getFromEnv("XYPRISS_XHSC_PATH");
5128
4670
  if (envPath)
5129
4671
  return envPath;
5130
4672
  const osPart = Platform.getOsPart();
5131
4673
  const archPart = Platform.getArchPart();
5132
4674
  const suffix = Platform.getBinarySuffix();
4675
+ // Candidate names in order of preference
5133
4676
  const goBinName = `xhsc-${osPart}-${archPart}${suffix}`;
5134
4677
  const genericBinName = osPart === "windows" ? "xhsc.exe" : "xhsc";
5135
4678
  const candidates = [goBinName, genericBinName];
5136
4679
  const searchBases = [];
4680
+ // 2. Add Script Directory (where the library is located)
5137
4681
  const scriptDir = Discovery.getScriptDir();
5138
4682
  if (scriptDir)
5139
4683
  searchBases.push(scriptDir);
4684
+ // 3. Add Current Working Directory
5140
4685
  searchBases.push(process.cwd());
4686
+ // Perform recursive search from all bases using Discovery engine
5141
4687
  const resolved = Discovery.resolveBinary(candidates, searchBases);
5142
4688
  if (resolved)
5143
4689
  return resolved;
4690
+ // Final fallback (generic name which might be in PATH via system spawn)
5144
4691
  return genericBinName;
5145
4692
  }
5146
4693
  /**
5147
- * Ensures the confined xhsc background daemon is spawned inside the libXESS sandbox
5148
- * if the IPC socket is not yet accessible.
4694
+ * Executes a command synchronously and returns the parsed JSON result.
4695
+ * Standardizes all responses into a Promise-like data structure.
5149
4696
  */
5150
- ensureDaemon() {
5151
- if (this.isAvailable()) {
5152
- return;
5153
- }
5154
- const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP;
5155
- if (!sessionDir) {
5156
- return;
5157
- }
5158
- if (Date.now() - this.lastDaemonSpawnTime < 3000) {
5159
- return;
5160
- }
5161
- this.lastDaemonSpawnTime = Date.now();
5162
- const binPath = this.resolveBinary();
5163
- if (!binPath) {
5164
- return;
5165
- }
5166
- const internalSig = getInternalSignature();
5167
- let sessionKey = "";
5168
- try {
5169
- sessionKey = XessIpcClient.getActiveSessionKey();
5170
- }
5171
- catch { }
4697
+ /**
4698
+ * Executes a command synchronously via libSynapx IPC and returns the parsed result.
4699
+ */
4700
+ runSync(module, action, args = [], options = {}) {
5172
4701
  try {
5173
- const child = node_child_process.spawn(binPath, ["daemon", process.cwd()], {
5174
- detached: true,
5175
- stdio: "inherit",
5176
- env: {
5177
- ...process.env,
5178
- ...(sessionKey ? { XYPRISS_XESS_SESSION_KEY: sessionKey } : {}),
5179
- ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5180
- NO_COLOR: "1",
5181
- },
5182
- });
5183
- let childExited = false;
5184
- child.on("exit", () => {
5185
- childExited = true;
5186
- });
5187
- child.on("error", () => {
5188
- childExited = true;
5189
- });
5190
- child.unref();
5191
- // Wait for socket to appear (up to 1500ms)
5192
- const start = Date.now();
5193
- while (Date.now() - start < 1500) {
5194
- if (this.isAvailable() || childExited) {
5195
- break;
5196
- }
5197
- try {
5198
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
5199
- }
5200
- catch {
5201
- const t = Date.now() + 20;
5202
- while (Date.now() < t) { }
5203
- }
5204
- }
4702
+ const synapx = SynapxClient.getInstance();
4703
+ return synapx.callSync(module, action, args, options);
5205
4704
  }
5206
- catch {
5207
- // Silently allow fallback
4705
+ catch (error) {
4706
+ if (error instanceof XyPrissError)
4707
+ throw error;
4708
+ throw new XyPrissError(module, action, error.message || String(error), error);
5208
4709
  }
5209
4710
  }
5210
4711
  /**
5211
- * Connects to the libSynapx server and performs the Zero-Trust handshake.
4712
+ * Executes a command asynchronously via libSynapx IPC and returns the parsed result.
5212
4713
  */
5213
- async connect() {
5214
- if (this.socket && !this.socket.destroyed && this.isHandshakeComplete) {
5215
- return;
4714
+ async runAsync(module, action, args = [], options = {}) {
4715
+ try {
4716
+ const synapx = SynapxClient.getInstance();
4717
+ return await synapx.call(module, action, args, options);
5216
4718
  }
5217
- if (!this.isAvailable()) {
5218
- this.ensureDaemon();
4719
+ catch (error) {
4720
+ if (error instanceof XyPrissError)
4721
+ throw error;
4722
+ throw new XyPrissError(module, action, error.message || String(error), error);
5219
4723
  }
5220
- if (this.connectingPromise) {
5221
- return this.connectingPromise;
5222
- }
5223
- this.connectingPromise = new Promise((resolve, reject) => {
5224
- if (!this.socketPath) {
5225
- return reject(new Error("libSynapx: No active session socket path configured (XYPRISS_USER_TMP is unset)"));
5226
- }
5227
- const client = net__namespace.createConnection(this.socketPath, () => {
5228
- this.socket = client;
5229
- this.performHandshake()
5230
- .then(() => {
5231
- this.isHandshakeComplete = true;
5232
- resolve();
5233
- })
5234
- .catch((err) => {
5235
- this.destroy();
5236
- reject(err);
5237
- });
5238
- });
5239
- client.on("data", (chunk) => this.onData(chunk));
5240
- client.on("error", (err) => {
5241
- if (!this.isHandshakeComplete) {
5242
- reject(err);
5243
- }
5244
- this.destroy();
5245
- });
5246
- client.on("close", () => {
5247
- this.destroy();
5248
- });
5249
- }).finally(() => {
5250
- this.connectingPromise = null;
5251
- });
5252
- return this.connectingPromise;
5253
- }
5254
- /**
5255
- * Writes a framed packet to the socket.
5256
- */
5257
- writeFrame(msgType, payload) {
5258
- if (!this.socket || this.socket.destroyed) {
5259
- throw new Error("libSynapx: socket is not connected");
5260
- }
5261
- const header = Buffer.alloc(HEADER_SIZE$1);
5262
- header.writeUInt8(MAGIC_BYTE, 0);
5263
- header.writeUInt8(msgType, 1);
5264
- header.writeUInt32BE(payload.length, 2);
5265
- this.socket.write(Buffer.concat([header, payload]));
5266
- }
5267
- /**
5268
- * Performs initial zero-trust handshake.
5269
- */
5270
- async performHandshake() {
5271
- return new Promise((resolve, reject) => {
5272
- const timeout = setTimeout(() => {
5273
- reject(new Error("libSynapx: Handshake timed out"));
5274
- }, 3000);
5275
- const hsPayload = Buffer.from(JSON.stringify({
5276
- sessionHash: this.sessionHash,
5277
- token: this.authToken,
5278
- clientPid: process.pid,
5279
- }));
5280
- // Temporarily intercept handshake response frame
5281
- const originalOnData = this.onData;
5282
- this.onData = (chunk) => {
5283
- this.pushChunk(chunk);
5284
- while (true) {
5285
- const header = this.peekHeader();
5286
- if (!header)
5287
- return;
5288
- if (header.magic !== MAGIC_BYTE) {
5289
- clearTimeout(timeout);
5290
- this.onData = originalOnData;
5291
- return reject(new Error("libSynapx: Invalid magic byte in handshake response"));
5292
- }
5293
- if (this.rxBytesTotal < HEADER_SIZE$1 + header.length) {
5294
- return; // Wait for full frame
5295
- }
5296
- this.consumeBytes(HEADER_SIZE$1);
5297
- const payloadBuf = this.consumeBytes(header.length);
5298
- clearTimeout(timeout);
5299
- this.onData = originalOnData;
5300
- if (header.msgType === MSG_HANDSHAKE_ACK) {
5301
- try {
5302
- const ack = JSON.parse(payloadBuf.toString("utf8"));
5303
- if (ack.auth) {
5304
- this.sessionKey = ack.sessionKey || "";
5305
- try {
5306
- this.socket?.unref();
5307
- }
5308
- catch { }
5309
- return resolve();
5310
- }
5311
- return reject(new Error(`libSynapx: Handshake unauthorized: ${ack.err || "unknown"}`));
5312
- }
5313
- catch (e) {
5314
- return reject(e);
5315
- }
5316
- }
5317
- else {
5318
- return reject(new Error(`libSynapx: Expected HandshakeAck (0x02), received 0x${header.msgType.toString(16)}`));
5319
- }
5320
- }
5321
- };
5322
- try {
5323
- this.writeFrame(MSG_HANDSHAKE, hsPayload);
5324
- }
5325
- catch (err) {
5326
- clearTimeout(timeout);
5327
- this.onData = originalOnData;
5328
- reject(err);
5329
- }
5330
- });
5331
4724
  }
5332
4725
  /**
5333
- * Processes incoming streamed chunks from the socket.
4726
+ * Run a module action and return the stdout as a Readable stream
5334
4727
  */
5335
- onData(chunk) {
5336
- this.pushChunk(chunk);
5337
- while (true) {
5338
- const header = this.peekHeader();
5339
- if (!header)
5340
- break;
5341
- if (header.magic !== MAGIC_BYTE) {
5342
- this.consumeBytes(1);
5343
- this.discardUntilMagic();
4728
+ runStream(module, action, args = [], options = {}) {
4729
+ const internalSig = getInternalSignature();
4730
+ const cmdArgs = [
4731
+ "--root",
4732
+ this.root,
4733
+ module,
4734
+ action,
4735
+ ...args,
4736
+ ];
4737
+ for (const [key, value] of Object.entries(options)) {
4738
+ if (["input"].includes(key))
5344
4739
  continue;
4740
+ const flag = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
4741
+ if (value === true)
4742
+ cmdArgs.push(`--${flag}`);
4743
+ else if (value !== false && value !== undefined) {
4744
+ cmdArgs.push(`--${flag}`, String(value));
5345
4745
  }
5346
- if (this.rxBytesTotal < HEADER_SIZE$1 + header.length) {
5347
- break; // Incomplete packet, wait for more data
5348
- }
5349
- this.consumeBytes(HEADER_SIZE$1);
5350
- const payloadBuf = this.consumeBytes(header.length);
5351
- this.dispatchIncomingFrame(header.msgType, payloadBuf);
5352
4746
  }
5353
- }
5354
- /**
5355
- * Routes decoded incoming packets to pending call promises.
5356
- */
5357
- dispatchIncomingFrame(msgType, payloadBuf) {
5358
- switch (msgType) {
5359
- case MSG_RESPONSE: {
5360
- try {
5361
- const resp = JSON.parse(payloadBuf.toString("utf8"));
5362
- const pending = this.pendingCalls.get(resp.id);
5363
- if (pending) {
5364
- clearTimeout(pending.timeout);
5365
- this.pendingCalls.delete(resp.id);
5366
- if (resp.ok) {
5367
- pending.resolve(resp.data);
5368
- }
5369
- else {
5370
- pending.reject(new Error(resp.err || "libSynapx operation failed"));
5371
- }
5372
- }
5373
- }
5374
- catch { }
5375
- break;
5376
- }
5377
- case MSG_PONG:
5378
- break;
5379
- case MSG_ERROR: {
5380
- try {
5381
- const errObj = JSON.parse(payloadBuf.toString("utf8"));
5382
- const errMsg = errObj.error || "libSynapx protocol error";
5383
- for (const [id, pending] of this.pendingCalls.entries()) {
5384
- clearTimeout(pending.timeout);
5385
- pending.reject(new Error(errMsg));
5386
- }
5387
- this.pendingCalls.clear();
5388
- }
5389
- catch { }
5390
- break;
5391
- }
4747
+ const child = node_child_process.spawn(this.binaryPath, cmdArgs, {
4748
+ cwd: this.root,
4749
+ env: {
4750
+ ...process.env,
4751
+ ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
4752
+ },
4753
+ });
4754
+ if (options.input !== undefined) {
4755
+ child.stdin.write(options.input);
4756
+ child.stdin.end();
5392
4757
  }
4758
+ // Return the stdout stream
4759
+ return child.stdout;
5393
4760
  }
5394
4761
  /**
5395
- * Executes a multiplexed RPC call over the persistent private channel with full args and options descriptors.
4762
+ * Run a module action and return the stdin as a Writable stream
5396
4763
  */
5397
- async call(module, action, args = [], opts = {}, timeoutMs = 60000) {
5398
- await this.connect();
5399
- const stringArgs = Array.isArray(args)
5400
- ? args.map((a) => String(a))
5401
- : [];
5402
- const id = ++this.seqId;
5403
- const callPayload = Buffer.from(JSON.stringify({
5404
- id,
5405
- mod: module,
4764
+ runWritableStream(module, action, args = [], options = {}) {
4765
+ const internalSig = getInternalSignature();
4766
+ const cmdArgs = [
4767
+ "--root",
4768
+ this.root,
4769
+ module,
5406
4770
  action,
5407
- args: stringArgs,
5408
- opts: opts || {},
5409
- }));
5410
- const effectiveTimeout = typeof opts?.timeout === "number" ? opts.timeout : timeoutMs;
5411
- return new Promise((resolve, reject) => {
5412
- const timeout = setTimeout(() => {
5413
- this.pendingCalls.delete(id);
5414
- reject(new Error(`libSynapx: Call timed out after ${effectiveTimeout}ms [${module}.${action}]`));
5415
- }, effectiveTimeout);
5416
- this.pendingCalls.set(id, {
5417
- resolve,
5418
- reject,
5419
- timeout,
5420
- });
5421
- try {
5422
- this.writeFrame(MSG_CALL, callPayload);
5423
- }
5424
- catch (err) {
5425
- clearTimeout(timeout);
5426
- this.pendingCalls.delete(id);
5427
- reject(err);
4771
+ ...args,
4772
+ ];
4773
+ for (const [key, value] of Object.entries(options)) {
4774
+ const flag = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
4775
+ if (value === true)
4776
+ cmdArgs.push(`--${flag}`);
4777
+ else if (value !== false && value !== undefined) {
4778
+ cmdArgs.push(`--${flag}`, String(value));
5428
4779
  }
4780
+ }
4781
+ const child = node_child_process.spawn(this.binaryPath, cmdArgs, {
4782
+ cwd: this.root,
4783
+ env: {
4784
+ ...process.env,
4785
+ ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
4786
+ },
5429
4787
  });
5430
- }
5431
- /**
5432
- * Synchronous RPC via ultra-fast SharedArrayBuffer Futex Bridge (Path 1)
5433
- * with transparent automatic fallback to stdin pipe subprocess on edge platforms.
5434
- */
5435
- callSync(module, action, args = [], opts = {}) {
5436
- if (!this.socketPath || !fs__namespace.existsSync(this.socketPath)) {
5437
- this.ensureDaemon();
5438
- if (!this.socketPath || !fs__namespace.existsSync(this.socketPath)) {
5439
- throw new Error(`libSynapx: socket '${this.socketPath || "unknown"}' not found or active daemon is offline`);
5440
- }
5441
- }
5442
- try {
5443
- if (!this.syncBridge) {
5444
- this.syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.authToken);
5445
- }
5446
- return this.syncBridge.callSync(module, action, args, opts);
5447
- }
5448
- catch {
5449
- // Resilient fallback to stdin subprocess pipeline
5450
- return this.callSyncSubprocess(module, action, args, opts);
5451
- }
5452
- }
5453
- /**
5454
- * Subprocess-based synchronous fallback pipeline (streaming via stdin to prevent E2BIG).
5455
- */
5456
- callSyncSubprocess(module, action, args = [], opts = {}) {
5457
- const stringArgs = Array.isArray(args)
5458
- ? args.map((a) => String(a))
5459
- : [];
5460
- const script = `
5461
- const net = require("net");
5462
- const fs = require("fs");
5463
- const sock = process.argv[1];
5464
- const hash = process.argv[2] || "";
5465
- const token = process.argv[3] || "";
5466
-
5467
- let inputData = "";
5468
- try {
5469
- inputData = fs.readFileSync(0, "utf8");
5470
- } catch {}
5471
-
5472
- const req = JSON.parse(inputData || "{}");
5473
- const mod = req.mod;
5474
- const act = req.action;
5475
- const args = req.args || [];
5476
- const opts = req.opts || {};
5477
-
5478
- const client = net.createConnection(sock, () => {
5479
- // 1. Handshake
5480
- const hs = Buffer.from(JSON.stringify({ sessionHash: hash, token: token, clientPid: process.pid }));
5481
- const h1 = Buffer.alloc(6);
5482
- h1.writeUInt8(0x53, 0);
5483
- h1.writeUInt8(0x01, 1);
5484
- h1.writeUInt32BE(hs.length, 2);
5485
- client.write(Buffer.concat([h1, hs]));
5486
- });
5487
-
5488
- let buf = Buffer.alloc(0);
5489
- let handshaked = false;
5490
-
5491
- client.on("data", (chunk) => {
5492
- buf = Buffer.concat([buf, chunk]);
5493
- while (buf.length >= 6) {
5494
- if (buf.readUInt8(0) !== 0x53) { process.exit(1); }
5495
- const type = buf.readUInt8(1);
5496
- const len = buf.readUInt32BE(2);
5497
- if (buf.length < 6 + len) return;
5498
- const payload = buf.subarray(6, 6 + len);
5499
- buf = buf.subarray(6 + len);
5500
-
5501
- if (!handshaked) {
5502
- if (type === 0x02) {
5503
- handshaked = true;
5504
- const call = Buffer.from(JSON.stringify({ id: 1, mod: mod, action: act, args: args, opts: opts }));
5505
- const h2 = Buffer.alloc(6);
5506
- h2.writeUInt8(0x53, 0);
5507
- h2.writeUInt8(0x03, 1);
5508
- h2.writeUInt32BE(call.length, 2);
5509
- client.write(Buffer.concat([h2, call]));
5510
- } else { process.exit(1); }
5511
- } else {
5512
- if (type === 0x04) {
5513
- process.stdout.write(payload);
5514
- client.end();
5515
- process.exit(0);
5516
- } else { process.exit(1); }
5517
- }
5518
- }
5519
- });
5520
- setTimeout(() => process.exit(1), 5000);
5521
- `;
5522
- const inputPayload = JSON.stringify({
5523
- mod: module,
5524
- action,
5525
- args: stringArgs,
5526
- opts: opts || {},
5527
- });
5528
- const output = node_child_process.execFileSync(process.execPath, [
5529
- "-e",
5530
- script,
5531
- this.socketPath,
5532
- this.sessionHash,
5533
- this.authToken,
5534
- ], {
5535
- input: inputPayload,
5536
- encoding: "utf8",
5537
- timeout: 5000,
5538
- maxBuffer: 100 * 1024 * 1024,
5539
- stdio: ["pipe", "pipe", "pipe"],
5540
- });
5541
- const parsed = JSON.parse(output.trim());
5542
- if (!parsed.ok) {
5543
- throw new Error(parsed.err || "libSynapx call failed");
5544
- }
5545
- return parsed.data;
5546
- }
5547
- destroy() {
5548
- this.isHandshakeComplete = false;
5549
- if (this.syncBridge) {
5550
- this.syncBridge.destroy();
5551
- this.syncBridge = null;
5552
- }
5553
- if (this.socket) {
5554
- this.socket.removeAllListeners();
5555
- this.socket.destroy();
5556
- this.socket = null;
5557
- }
5558
- for (const [id, pending] of this.pendingCalls.entries()) {
5559
- clearTimeout(pending.timeout);
5560
- pending.reject(new Error("libSynapx: socket disconnected"));
5561
- }
5562
- this.pendingCalls.clear();
5563
- this.rxChunks = [];
5564
- this.rxBytesTotal = 0;
4788
+ // Return the stdin stream with an explicit close() method
4789
+ const stdin = child.stdin;
4790
+ // @ts-ignore
4791
+ stdin.close = () => stdin.end();
4792
+ return stdin;
5565
4793
  }
5566
4794
  }
5567
- SynapxClient.instance = null;
5568
4795
 
5569
4796
  /**
5570
- * Custom error class for XyPriss system operations.
4797
+ * Returns the absolute path to the XyPriss shared temp directory.
4798
+ *
4799
+ * @returns {string} Path to `<os.tmpdir>/nehonix.xypriss.data`
5571
4800
  */
5572
- class XyPrissError extends Error {
5573
- constructor(module, action, details, raw) {
5574
- super(`[XyPriss Error] ${module}.${action} failed: ${details}`);
5575
- this.module = module;
5576
- this.action = action;
5577
- this.details = details;
5578
- this.raw = raw;
5579
- this.name = "XyPrissError";
4801
+ function getXyprissTempDir() {
4802
+ const sys = getSysApi();
4803
+ return sys.path.join(sys.path.tempDir(), "nehonix.xypriss.data");
4804
+ }
4805
+ /**
4806
+ * Resolves and ensures a sub-path within the XyPriss temp directory exists.
4807
+ *
4808
+ * @param {string | string[]} _p - Sub-path segment(s) to append.
4809
+ * @returns {string} The absolute resolved temp sub-path.
4810
+ */
4811
+ function createXyprissTempDir(_p) {
4812
+ const sys = getSysApi();
4813
+ const base = getXyprissTempDir();
4814
+ const segment = typeof _p === "string"
4815
+ ? _p
4816
+ : _p.includes("/")
4817
+ ? _p.map((p) => p.replace("/", "")).join("/")
4818
+ : _p.join("/");
4819
+ // Use the native corrective layer to prevent doubling or redundant separators
4820
+ const rawPath = segment.startsWith(base)
4821
+ ? segment
4822
+ : sys.path.join(base, segment);
4823
+ const normalisedPath = sys.path.correct(rawPath, { tentative: 2 });
4824
+ if (!sys.fs.exist(normalisedPath)) {
4825
+ sys.fs.mkdir(normalisedPath, { parents: true });
5580
4826
  }
4827
+ return normalisedPath;
5581
4828
  }
5582
4829
  /**
5583
- * **Native System Runner**
4830
+ * **Session Temp Directory (singleton)**
5584
4831
  *
5585
- * This class serves as the core bridge between the Node.js runtime and the
5586
- * high-performance system core. It manages process spawning, argument
5587
- * serialization, and bidirectional streaming.
4832
+ * Unique sub-path generated once per process lifetime under the XyPriss
4833
+ * temp root (`<os.tmpdir>/nehonix.xypriss.data/xuser/<hex4>`).
4834
+ *
4835
+ * The value is memoized on first access and remains stable for the entire
4836
+ * duration of the running process, ensuring all callers within the same
4837
+ * session share the same isolated scratch space.
5588
4838
  */
5589
- class XyPrissRunner {
5590
- constructor(root) {
5591
- this.root = root;
5592
- this.binaryPath = this.discoverBinary();
5593
- // console.log(
5594
- // "[XyPrissRunner:getBinaryPath] Binary path: ",
5595
- // this.discoverBinary(),
5596
- // );
4839
+ let _sessionTmpDir = null;
4840
+ /**
4841
+ * Returns the process-scoped user temp directory path for THIS active server instance.
4842
+ *
4843
+ * Generates an instance ID hash once and caches it for the lifetime of the process.
4844
+ * E.g. `/tmp/nehonix.xypriss.data/xuser/12daa75a`
4845
+ *
4846
+ * @returns {string} Absolute path to instance temp directory
4847
+ */
4848
+ function generateXUserTmpDir() {
4849
+ if (_sessionTmpDir !== null) {
4850
+ return _sessionTmpDir;
5597
4851
  }
5598
- getRoot() {
5599
- // console.log("[XyPrissRunner:getRoot] Binary root: ", this.root);
5600
- return this.root;
4852
+ const sys = getSysApi();
4853
+ // 1. Adopt the session directory allocated exclusively by the libProc supervisor
4854
+ const envSession = sys?.__env__?.get("XYPRISS_USER_TMP") ||
4855
+ sys?.__env__?.get("XESS_SESSION_TMP") ||
4856
+ (typeof process !== "undefined"
4857
+ ? (process.env?.XYPRISS_USER_TMP || process.env?.XESS_SESSION_TMP)
4858
+ : undefined);
4859
+ if (envSession && typeof envSession === "string") {
4860
+ _sessionTmpDir = envSession;
4861
+ if (sys?.fs && !sys.fs.exist(_sessionTmpDir)) {
4862
+ sys.fs.mkdir(_sessionTmpDir, { parents: true });
4863
+ }
4864
+ return _sessionTmpDir;
5601
4865
  }
5602
- getBinaryPath() {
5603
- return this.binaryPath;
4866
+ // No supervisor session provisioned by libProc: unconfined execution has no valid session
4867
+ return "";
4868
+ }
4869
+ /**
4870
+ * Returns the unique 8-character session hash ID for the active server instance.
4871
+ * Delegated exclusively to the libProc supervisor (Single Source of Truth).
4872
+ */
4873
+ function getSessionHash() {
4874
+ const sys = getSysApi();
4875
+ const envHash = sys?.__env__?.get("XYPRISS_SESSION_HASH") ||
4876
+ (typeof process !== "undefined" ? process.env?.XYPRISS_SESSION_HASH : undefined);
4877
+ if (envHash && typeof envHash === "string") {
4878
+ return envHash;
5604
4879
  }
5605
- /**
5606
- * Strategic discovery of the XyPriss System binary.
5607
- * Prioritizes the high-performance Go implementation (XHSC-GO).
5608
- */
5609
- discoverBinary() {
5610
- // 1. Environment Variable Override (Highest Priority)
5611
- const envPath = Discovery.getFromEnv("XYPRISS_XHSC_PATH");
5612
- if (envPath)
5613
- return envPath;
5614
- const osPart = Platform.getOsPart();
5615
- const archPart = Platform.getArchPart();
5616
- const suffix = Platform.getBinarySuffix();
5617
- // Candidate names in order of preference
5618
- const goBinName = `xhsc-${osPart}-${archPart}${suffix}`;
5619
- const genericBinName = osPart === "windows" ? "xhsc.exe" : "xhsc";
5620
- const candidates = [goBinName, genericBinName];
5621
- const searchBases = [];
5622
- // 2. Add Script Directory (where the library is located)
5623
- const scriptDir = Discovery.getScriptDir();
5624
- if (scriptDir)
5625
- searchBases.push(scriptDir);
5626
- // 3. Add Current Working Directory
5627
- searchBases.push(process.cwd());
5628
- // Perform recursive search from all bases using Discovery engine
5629
- const resolved = Discovery.resolveBinary(candidates, searchBases);
5630
- if (resolved)
5631
- return resolved;
5632
- // Final fallback (generic name which might be in PATH via system spawn)
5633
- return genericBinName;
5634
- }
5635
- /**
5636
- * Executes a command synchronously and returns the parsed JSON result.
5637
- * Standardizes all responses into a Promise-like data structure.
5638
- */
5639
- /**
5640
- * Executes a command synchronously via libSynapx IPC and returns the parsed result.
5641
- */
5642
- runSync(module, action, args = [], options = {}) {
5643
- try {
5644
- const synapx = SynapxClient.getInstance();
5645
- return synapx.callSync(module, action, args, options);
5646
- }
5647
- catch (error) {
5648
- if (error instanceof XyPrissError)
5649
- throw error;
5650
- throw new XyPrissError(module, action, error.message || String(error), error);
5651
- }
5652
- }
5653
- /**
5654
- * Executes a command asynchronously via libSynapx IPC and returns the parsed result.
5655
- */
5656
- async runAsync(module, action, args = [], options = {}) {
5657
- try {
5658
- const synapx = SynapxClient.getInstance();
5659
- return await synapx.call(module, action, args, options);
5660
- }
5661
- catch (error) {
5662
- if (error instanceof XyPrissError)
5663
- throw error;
5664
- throw new XyPrissError(module, action, error.message || String(error), error);
5665
- }
5666
- }
5667
- /**
5668
- * Run a module action and return the stdout as a Readable stream
5669
- */
5670
- runStream(module, action, args = [], options = {}) {
5671
- const internalSig = getInternalSignature();
5672
- const cmdArgs = [
5673
- "--root",
5674
- this.root,
5675
- module,
5676
- action,
5677
- ...args,
5678
- ];
5679
- for (const [key, value] of Object.entries(options)) {
5680
- if (["input"].includes(key))
5681
- continue;
5682
- const flag = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
5683
- if (value === true)
5684
- cmdArgs.push(`--${flag}`);
5685
- else if (value !== false && value !== undefined) {
5686
- cmdArgs.push(`--${flag}`, String(value));
5687
- }
5688
- }
5689
- const child = node_child_process.spawn(this.binaryPath, cmdArgs, {
5690
- cwd: this.root,
5691
- env: {
5692
- ...process.env,
5693
- ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5694
- },
5695
- });
5696
- if (options.input !== undefined) {
5697
- child.stdin.write(options.input);
5698
- child.stdin.end();
5699
- }
5700
- // Return the stdout stream
5701
- return child.stdout;
5702
- }
5703
- /**
5704
- * Run a module action and return the stdin as a Writable stream
5705
- */
5706
- runWritableStream(module, action, args = [], options = {}) {
5707
- const internalSig = getInternalSignature();
5708
- const cmdArgs = [
5709
- "--root",
5710
- this.root,
5711
- module,
5712
- action,
5713
- ...args,
5714
- ];
5715
- for (const [key, value] of Object.entries(options)) {
5716
- const flag = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
5717
- if (value === true)
5718
- cmdArgs.push(`--${flag}`);
5719
- else if (value !== false && value !== undefined) {
5720
- cmdArgs.push(`--${flag}`, String(value));
5721
- }
4880
+ if (_sessionTmpDir) {
4881
+ if (sys?.path) {
4882
+ return sys.path.basename(_sessionTmpDir);
5722
4883
  }
5723
- const child = node_child_process.spawn(this.binaryPath, cmdArgs, {
5724
- cwd: this.root,
5725
- env: {
5726
- ...process.env,
5727
- ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5728
- },
5729
- });
5730
- // Return the stdin stream with an explicit close() method
5731
- const stdin = child.stdin;
5732
- // @ts-ignore
5733
- stdin.close = () => stdin.end();
5734
- return stdin;
4884
+ const parts = _sessionTmpDir.split(/[/\\]/).filter(Boolean);
4885
+ return parts[parts.length - 1] || "";
5735
4886
  }
4887
+ return "";
4888
+ }
4889
+ /**
4890
+ * Backward-compatibility alias for getSessionHash().
4891
+ */
4892
+ function getInstanceId() {
4893
+ return getSessionHash();
5736
4894
  }
5737
4895
 
5738
4896
  /* *****************************************************************************
@@ -6393,103 +5551,320 @@ class FileHandle {
6393
5551
  this.runner = runner;
6394
5552
  this.synapx = SynapxClient.getInstance();
6395
5553
  }
6396
- /**
6397
- * **Get Native Handle ID**
6398
- */
6399
- get nativeId() {
6400
- return this.id;
5554
+ /**
5555
+ * **Get Native Handle ID**
5556
+ */
5557
+ get nativeId() {
5558
+ return this.id;
5559
+ }
5560
+ /**
5561
+ * **Read from File**
5562
+ * @param length - Max bytes to read
5563
+ */
5564
+ async read(length) {
5565
+ if (this.synapx.isAvailable()) {
5566
+ const res = await this.synapx.call("fs", "read-handle", [
5567
+ String(this.id),
5568
+ String(length),
5569
+ ]);
5570
+ if (typeof res === "string") {
5571
+ return Buffer.from(res, "hex");
5572
+ }
5573
+ if (Buffer.isBuffer(res))
5574
+ return res;
5575
+ if (res && res.content) {
5576
+ return Buffer.from(res.content, "base64");
5577
+ }
5578
+ return Buffer.from(res || "");
5579
+ }
5580
+ const res = (await this.runner.runAsync("fs", "read-handle", [
5581
+ String(this.id),
5582
+ String(length),
5583
+ ]));
5584
+ return Buffer.from(res?.content || res || "", "hex");
5585
+ }
5586
+ /**
5587
+ * **Write to File**
5588
+ * @param data - Buffer or String
5589
+ */
5590
+ async write(data) {
5591
+ const raw = typeof data === "string" ? Buffer.from(data) : data;
5592
+ if (this.synapx.isAvailable()) {
5593
+ const res = await this.synapx.call("fs", "write-handle", [
5594
+ String(this.id),
5595
+ raw.toString("hex"),
5596
+ ]);
5597
+ return typeof res === "number" ? res : (res?.n ?? raw.length);
5598
+ }
5599
+ const res = (await this.runner.runAsync("fs", "write-handle", [
5600
+ String(this.id),
5601
+ raw.toString("hex"),
5602
+ ]));
5603
+ return typeof res === "number" ? res : (res?.n ?? raw.length);
5604
+ }
5605
+ /**
5606
+ * **Seek within File**
5607
+ * @param offset - Position
5608
+ * @param whence - 0: Start, 1: Current, 2: End
5609
+ */
5610
+ async seek(offset, whence = 0) {
5611
+ if (this.synapx.isAvailable()) {
5612
+ const res = await this.synapx.call("fs", "seek-handle", [
5613
+ String(this.id),
5614
+ String(offset),
5615
+ String(whence),
5616
+ ]);
5617
+ return typeof res === "number" ? res : (res?.pos ?? 0);
5618
+ }
5619
+ const res = (await this.runner.runAsync("fs", "seek-handle", [
5620
+ String(this.id),
5621
+ String(offset),
5622
+ String(whence),
5623
+ ]));
5624
+ return typeof res === "number" ? res : (res?.pos ?? 0);
5625
+ }
5626
+ /**
5627
+ * **Get File Statistics**
5628
+ */
5629
+ async stat() {
5630
+ if (this.synapx.isAvailable()) {
5631
+ return await this.synapx.call("fs", "stat-handle", [
5632
+ String(this.id),
5633
+ ]);
5634
+ }
5635
+ return (await this.runner.runAsync("fs", "stat-handle", [
5636
+ String(this.id),
5637
+ ]));
5638
+ }
5639
+ /**
5640
+ * **Close Handle**
5641
+ */
5642
+ async close() {
5643
+ if (this.synapx.isAvailable()) {
5644
+ await this.synapx.call("fs", "close", [String(this.id)]);
5645
+ }
5646
+ else {
5647
+ await this.runner.runAsync("fs", "close", [String(this.id)]);
5648
+ }
5649
+ }
5650
+ }
5651
+
5652
+ /**
5653
+ * ANSI color codes for terminal output
5654
+ */
5655
+ const ANSI = {
5656
+ reset: "\x1b[0m",
5657
+ bold: "\x1b[1m",
5658
+ dim: "\x1b[2m",
5659
+ // Foreground colors
5660
+ black: "\x1b[30m",
5661
+ yellow: "\x1b[33m",
5662
+ blue: "\x1b[34m",
5663
+ cyan: "\x1b[36m",
5664
+ white: "\x1b[37m",
5665
+ gray: "\x1b[90m",
5666
+ // Bright foreground
5667
+ brightRed: "\x1b[91m",
5668
+ brightGreen: "\x1b[92m",
5669
+ brightYellow: "\x1b[93m",
5670
+ brightBlue: "\x1b[94m",
5671
+ brightMagenta: "\x1b[95m",
5672
+ brightCyan: "\x1b[96m",
5673
+ // Background colors
5674
+ bgRed: "\x1b[41m",
5675
+ bgGreen: "\x1b[42m",
5676
+ bgYellow: "\x1b[43m",
5677
+ bgBlue: "\x1b[44m",
5678
+ bgMagenta: "\x1b[45m",
5679
+ bgCyan: "\x1b[46m",
5680
+ };
5681
+ const LOG_CONFIGS = {
5682
+ info: {
5683
+ icon: "ℹ️ ",
5684
+ color: ANSI.brightCyan,
5685
+ label: "INFO",
5686
+ labelColor: `${ANSI.bgCyan}${ANSI.black}`,
5687
+ },
5688
+ success: {
5689
+ icon: "✅",
5690
+ color: ANSI.brightGreen,
5691
+ label: "OK",
5692
+ labelColor: `${ANSI.bgGreen}${ANSI.black}`,
5693
+ },
5694
+ warn: {
5695
+ icon: "⚠️ ",
5696
+ color: ANSI.brightYellow,
5697
+ label: "WARN",
5698
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
5699
+ },
5700
+ error: {
5701
+ icon: "❌",
5702
+ color: ANSI.brightRed,
5703
+ label: "ERROR",
5704
+ labelColor: `${ANSI.bgRed}${ANSI.white}`,
5705
+ },
5706
+ debug: {
5707
+ icon: "-",
5708
+ color: ANSI.gray,
5709
+ label: "DEBUG",
5710
+ labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
5711
+ },
5712
+ http: {
5713
+ icon: "🌐",
5714
+ color: ANSI.brightBlue,
5715
+ label: "HTTP",
5716
+ labelColor: `${ANSI.bgBlue}${ANSI.white}`,
5717
+ },
5718
+ swagger: {
5719
+ icon: "🛡️ ",
5720
+ color: ANSI.brightMagenta,
5721
+ label: "SWAGGER",
5722
+ labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
5723
+ },
5724
+ db: {
5725
+ icon: "🗄️ ",
5726
+ color: ANSI.yellow,
5727
+ label: "DB",
5728
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
5729
+ },
5730
+ auth: {
5731
+ icon: "🔐",
5732
+ color: ANSI.brightYellow,
5733
+ label: "AUTH",
5734
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
5735
+ },
5736
+ };
5737
+ const LEVEL_RANK = {
5738
+ silent: 0,
5739
+ error: 1,
5740
+ warn: 2,
5741
+ info: 3,
5742
+ success: 3,
5743
+ http: 3,
5744
+ swagger: 3,
5745
+ db: 3,
5746
+ auth: 3,
5747
+ debug: 4,
5748
+ verbose: 5,
5749
+ };
5750
+ class QuickLogger {
5751
+ constructor(context) {
5752
+ this.context = context;
5753
+ }
5754
+ // ─── Static factory ───────────────────────────────────────────────────────
5755
+ static for(context) {
5756
+ return new QuickLogger(context);
5757
+ }
5758
+ static shouldLog(level) {
5759
+ const sys = getSysApi();
5760
+ let isDebug = false;
5761
+ if (sys?.__env__) {
5762
+ isDebug =
5763
+ sys.__env__.get("DEBUG") ||
5764
+ sys.__env__.get("XYPRISS_DEBUG") ||
5765
+ sys.__env__.get("DEBUG_FS");
5766
+ }
5767
+ else if (typeof process !== "undefined" && process.env) {
5768
+ isDebug =
5769
+ process.env.DEBUG ||
5770
+ process.env.XYPRISS_DEBUG ||
5771
+ process.env.DEBUG_FS;
5772
+ }
5773
+ if (isDebug) {
5774
+ return true;
5775
+ }
5776
+ try {
5777
+ const logging = ConfigurationManager.get("logging");
5778
+ if (logging) {
5779
+ if (logging.enabled === false) {
5780
+ return false;
5781
+ }
5782
+ // Check logging.types overrides
5783
+ if (level === "error" && logging.types?.errors === false)
5784
+ return false;
5785
+ if (level === "warn" && logging.types?.warnings === false)
5786
+ return false;
5787
+ if (level === "debug" && logging.types?.debug === false)
5788
+ return false;
5789
+ if (level === "debug" && logging.types?.debug === true)
5790
+ return true;
5791
+ // Check logging.level rank
5792
+ const configuredLevel = (logging.level || "info").toLowerCase();
5793
+ const configuredRank = LEVEL_RANK[configuredLevel] ?? 3;
5794
+ const messageRank = LEVEL_RANK[level] ?? 3;
5795
+ return messageRank <= configuredRank;
5796
+ }
5797
+ }
5798
+ catch { }
5799
+ // Default ranking if no config: info level (rank 3)
5800
+ const defaultRank = 3;
5801
+ const messageRank = LEVEL_RANK[level] ?? 3;
5802
+ return messageRank <= defaultRank;
5803
+ }
5804
+ // ─── Core log method ──────────────────────────────────────────────────────
5805
+ log(level, ...args) {
5806
+ if (!QuickLogger.shouldLog(level)) {
5807
+ return;
5808
+ }
5809
+ const cfg = LOG_CONFIGS[level];
5810
+ const timestamp = QuickLogger.showTimestamp
5811
+ ? `${ANSI.dim}${ANSI.gray}${new Date().toISOString()}${ANSI.reset} `
5812
+ : "";
5813
+ const label = `${cfg.labelColor}${ANSI.bold} ${cfg.label} ${ANSI.reset}`;
5814
+ const ctx = `${ANSI.dim}${ANSI.cyan}[${this.context}]${ANSI.reset}`;
5815
+ // First arg gets the level color + icon, rest are passed raw so Node.js
5816
+ // pretty-prints objects/arrays/Errors natively (no JSON.stringify needed).
5817
+ const [first, ...rest] = args;
5818
+ const prefix = `${timestamp}${label} ${ctx} ${cfg.color}${cfg.icon} ${String(first)}${ANSI.reset}`;
5819
+ const consoleFn = level === "error"
5820
+ ? console.error
5821
+ : level === "warn"
5822
+ ? console.warn
5823
+ : console.log;
5824
+ rest.length > 0 ? consoleFn(prefix, ...rest) : consoleFn(prefix);
5825
+ }
5826
+ // ─── Public methods ───────────────────────────────────────────────────────
5827
+ info(...args) {
5828
+ this.log("info", ...args);
5829
+ }
5830
+ success(...args) {
5831
+ this.log("success", ...args);
5832
+ }
5833
+ warn(...args) {
5834
+ this.log("warn", ...args);
5835
+ }
5836
+ error(...args) {
5837
+ this.log("error", ...args);
5838
+ }
5839
+ debug(...args) {
5840
+ this.log("debug", ...args);
6401
5841
  }
6402
- /**
6403
- * **Read from File**
6404
- * @param length - Max bytes to read
6405
- */
6406
- async read(length) {
6407
- if (this.synapx.isAvailable()) {
6408
- const res = await this.synapx.call("fs", "read-handle", [
6409
- String(this.id),
6410
- String(length),
6411
- ]);
6412
- if (typeof res === "string") {
6413
- return Buffer.from(res, "hex");
6414
- }
6415
- if (Buffer.isBuffer(res))
6416
- return res;
6417
- if (res && res.content) {
6418
- return Buffer.from(res.content, "base64");
6419
- }
6420
- return Buffer.from(res || "");
6421
- }
6422
- const res = (await this.runner.runAsync("fs", "read-handle", [
6423
- String(this.id),
6424
- String(length),
6425
- ]));
6426
- return Buffer.from(res?.content || res || "", "hex");
5842
+ http(...args) {
5843
+ this.log("http", ...args);
6427
5844
  }
6428
- /**
6429
- * **Write to File**
6430
- * @param data - Buffer or String
6431
- */
6432
- async write(data) {
6433
- const raw = typeof data === "string" ? Buffer.from(data) : data;
6434
- if (this.synapx.isAvailable()) {
6435
- const res = await this.synapx.call("fs", "write-handle", [
6436
- String(this.id),
6437
- raw.toString("hex"),
6438
- ]);
6439
- return typeof res === "number" ? res : (res?.n ?? raw.length);
6440
- }
6441
- const res = (await this.runner.runAsync("fs", "write-handle", [
6442
- String(this.id),
6443
- raw.toString("hex"),
6444
- ]));
6445
- return typeof res === "number" ? res : (res?.n ?? raw.length);
5845
+ swagger(...args) {
5846
+ this.log("swagger", ...args);
6446
5847
  }
6447
- /**
6448
- * **Seek within File**
6449
- * @param offset - Position
6450
- * @param whence - 0: Start, 1: Current, 2: End
6451
- */
6452
- async seek(offset, whence = 0) {
6453
- if (this.synapx.isAvailable()) {
6454
- const res = await this.synapx.call("fs", "seek-handle", [
6455
- String(this.id),
6456
- String(offset),
6457
- String(whence),
6458
- ]);
6459
- return typeof res === "number" ? res : (res?.pos ?? 0);
6460
- }
6461
- const res = (await this.runner.runAsync("fs", "seek-handle", [
6462
- String(this.id),
6463
- String(offset),
6464
- String(whence),
6465
- ]));
6466
- return typeof res === "number" ? res : (res?.pos ?? 0);
5848
+ db(...args) {
5849
+ this.log("db", ...args);
6467
5850
  }
6468
- /**
6469
- * **Get File Statistics**
6470
- */
6471
- async stat() {
6472
- if (this.synapx.isAvailable()) {
6473
- return await this.synapx.call("fs", "stat-handle", [
6474
- String(this.id),
6475
- ]);
6476
- }
6477
- return (await this.runner.runAsync("fs", "stat-handle", [
6478
- String(this.id),
6479
- ]));
5851
+ auth(...args) {
5852
+ this.log("auth", ...args);
6480
5853
  }
6481
- /**
6482
- * **Close Handle**
6483
- */
6484
- async close() {
6485
- if (this.synapx.isAvailable()) {
6486
- await this.synapx.call("fs", "close", [String(this.id)]);
6487
- }
6488
- else {
6489
- await this.runner.runAsync("fs", "close", [String(this.id)]);
6490
- }
5854
+ // ─── Convenience: banner / separator ─────────────────────────────────────
5855
+ banner(title) {
5856
+ const line = `${ANSI.blue}${"─".repeat(60)}${ANSI.reset}`;
5857
+ const centered = title
5858
+ .padStart(30 + Math.floor(title.length / 2))
5859
+ .padEnd(60);
5860
+ console.log(`\n${line}`);
5861
+ console.log(`${ANSI.bold}${ANSI.brightCyan}${centered}${ANSI.reset}`);
5862
+ console.log(`${line}\n`);
6491
5863
  }
6492
5864
  }
5865
+ QuickLogger.showTimestamp = true;
5866
+ // ─── Default singleton logger ──────────────────────────────────────────────
5867
+ // export const logger = QuickLogger.for("");
6493
5868
 
6494
5869
  const logger = QuickLogger.for("XHSC:TempFile");
6495
5870
  class TempFileManager {
@@ -8704,39 +8079,13 @@ class ConfigSyntaxParser {
8704
8079
  }
8705
8080
 
8706
8081
  // ---------------------------------------------------------------------------
8707
- // Internal RAM store for project environments — purely module-scoped.
8082
+ // Zero-RAM-Store Architecture (libSynapx + libXESS):
8708
8083
  //
8709
- // CRITICAL SECURITY FIX:
8710
- // Do NOT store this on `globalThis` using a Symbol. `Object.getOwnPropertySymbols(globalThis)`
8711
- // allows any script or untrusted dependency to enumerate all symbols on globalThis
8712
- // and exfiltrate secrets without using __sys__.__env__.
8713
- // By encapsulating the store in module-scoped closures, the data is completely
8714
- // invisible to global reflection APIs.
8084
+ // CRITICAL SECURITY GUARANTEE:
8085
+ // Environment secrets are NEVER cached or stored in JavaScript/V8 RAM.
8086
+ // All secret reads and mutations are delegated synchronously over the
8087
+ // authenticated libSynapx bridge to the native Go libXESS Vault.
8715
8088
  // ---------------------------------------------------------------------------
8716
- let _internalProjectEnvs;
8717
- function setInternalProjectEnvs(store) {
8718
- _internalProjectEnvs = store;
8719
- }
8720
- function getInternalProjectEnvs() {
8721
- const stack = new Error().stack || "";
8722
- const lines = stack.split("\n");
8723
- for (let i = 1; i < lines.length; i++) {
8724
- const line = lines[i];
8725
- if (line.includes("env.") || line.includes("getInternalProjectEnvs"))
8726
- continue;
8727
- const match = line.match(/\((.*):\d+:\d+\)$/) ||
8728
- line.match(/at (.*):\d+:\d+$/) ||
8729
- line.match(/at (.*)$/);
8730
- if (match) {
8731
- const callerFile = match[1];
8732
- if (!isCoreFrameworkPath(callerFile)) {
8733
- return undefined;
8734
- }
8735
- break;
8736
- }
8737
- }
8738
- return _internalProjectEnvs;
8739
- }
8740
8089
  const XY_XHSC_REGISTER_FS = Symbol();
8741
8090
  /**
8742
8091
  * **Internal Root-Scoped Env Access Key**
@@ -8825,21 +8174,6 @@ class EnvKeyError extends Error {
8825
8174
  Object.setPrototypeOf(this, EnvKeyError.prototype);
8826
8175
  }
8827
8176
  }
8828
- /**
8829
- * Thrown when {@link EnvApi} methods are called before the internal store has
8830
- * been initialised by the XyPriss bootstrap process.
8831
- *
8832
- * This error should never occur in correctly bootstrapped applications.
8833
- * If it does, it indicates that framework initialisation was bypassed.
8834
- */
8835
- class EnvStoreError extends Error {
8836
- constructor() {
8837
- super("The XyPriss environment store has not been initialised. " +
8838
- "Ensure that createServer() has completed before accessing __sys__.__env__.");
8839
- this.name = "EnvStoreError";
8840
- Object.setPrototypeOf(this, EnvStoreError.prototype);
8841
- }
8842
- }
8843
8177
  /**
8844
8178
  * Thrown when an application attempts to boot without the mandatory libXESS confinement shield.
8845
8179
  */
@@ -8854,6 +8188,46 @@ class XessShieldRequiredError extends Error {
8854
8188
  }
8855
8189
  }
8856
8190
 
8191
+ /**
8192
+ * Checks if a given file path belongs to the deep engine core.
8193
+ * These files are skipped during stack analysis to find the user/plugin caller.
8194
+ */
8195
+ function isEngineCorePath(filePath) {
8196
+ if (!filePath)
8197
+ return false;
8198
+ const normalizedPath = filePath.replace(/\\/g, "/");
8199
+ if (normalizedPath.includes("/XyPriss/src/") ||
8200
+ normalizedPath.includes("/XyPriss/dist/") ||
8201
+ normalizedPath.includes("/node_modules/xypriss/")) {
8202
+ return true;
8203
+ }
8204
+ return false;
8205
+ }
8206
+ /**
8207
+ * Checks if a given file path belongs directly to the XyPriss Core Engine
8208
+ * or if it comes from an external plugin / user space.
8209
+ * This is used for SECURITY authorization.
8210
+ */
8211
+ function isCoreFrameworkPath(filePath) {
8212
+ if (!filePath)
8213
+ return false;
8214
+ const normalizedPath = filePath.replace(/\\/g, "/");
8215
+ // Authorize trusted internal mods within the framework repository
8216
+ if (normalizedPath.includes("/XyPriss/mods/"))
8217
+ return true;
8218
+ // Exclude other plugins even if they contain 'src' or are named 'xypriss-something'
8219
+ if (normalizedPath.includes("/mods/"))
8220
+ return false;
8221
+ // Engine Core is always trusted
8222
+ return isEngineCorePath(filePath);
8223
+ }
8224
+
8225
+ // Capture native V8 C++ CallSite bindings at module bootstrap before any third-party code executes.
8226
+ // `util.getCallSites` invokes v8::StackTrace::CurrentStackTrace directly in C++, completely
8227
+ // bypassing `Error.prepareStackTrace` overrides and ignoring `//# sourceURL` directives.
8228
+ const _nativeGetCallSites = typeof util.getCallSites === "function"
8229
+ ? util.getCallSites.bind(util)
8230
+ : null;
8857
8231
  let cachedManifest = null;
8858
8232
  /**
8859
8233
  * Loads the authoritative plugins manifest provided by xfpm.
@@ -8952,43 +8326,167 @@ function identifyProjectRoot(filePath) {
8952
8326
  }
8953
8327
  return undefined;
8954
8328
  }
8329
+ function normalizeScriptName(rawScript) {
8330
+ if (!rawScript)
8331
+ return "";
8332
+ if (rawScript.startsWith("file://")) {
8333
+ try {
8334
+ return node_url.fileURLToPath(rawScript);
8335
+ }
8336
+ catch {
8337
+ return rawScript.slice(7);
8338
+ }
8339
+ }
8340
+ return rawScript;
8341
+ }
8342
+ function isRuntimeLoaderPath(filePath) {
8343
+ const norm = filePath.replace(/\\/g, "/");
8344
+ return (norm.includes("/node_modules/tsx/") ||
8345
+ norm.includes("/node_modules/ts-node/") ||
8346
+ norm.includes("/node_modules/.bin/"));
8347
+ }
8955
8348
  /**
8956
- * Retrieves the project root of the code currently executing by analyzing the stack trace.
8349
+ * Captures raw C++ V8/JSC CallSite frames by temporarily overriding `Error.prepareStackTrace`
8350
+ * synchronously during stack generation. This neutralizes any user/attacker `Error.prepareStackTrace`
8351
+ * hijack and returns the full un-truncated call stack across both Node.js (V8) and Bun (JSC).
8957
8352
  */
8958
- function getCallerProjectRoot() {
8959
- const stack = new Error().stack;
8960
- if (!stack)
8961
- return getPrimaryProjectRoot();
8962
- const lines = stack.split("\n");
8963
- let callerFilePath = "";
8964
- // Line 0 is 'Error', Line 1 is getCallerProjectRoot itself
8965
- for (let i = 2; i < lines.length; i++) {
8966
- const line = lines[i];
8967
- if (!line || line.includes(" (node:") || line.includes(" (bun:") || line.includes(" (native"))
8353
+ function captureNativeFrames() {
8354
+ const frames = [];
8355
+ // 1. Capture full CallSite array via controlled prepareStackTrace override (immune to prior Error.prepareStackTrace hijacks)
8356
+ const prevPrepare = Error.prepareStackTrace;
8357
+ const prevLimit = Error.stackTraceLimit;
8358
+ let rawSites = [];
8359
+ try {
8360
+ Error.stackTraceLimit = 64;
8361
+ Error.prepareStackTrace = (_err, stack) => {
8362
+ rawSites = Array.isArray(stack) ? stack : [];
8363
+ return "";
8364
+ };
8365
+ const probe = new Error();
8366
+ void probe.stack;
8367
+ }
8368
+ catch {
8369
+ // ignore
8370
+ }
8371
+ finally {
8372
+ Error.prepareStackTrace = prevPrepare;
8373
+ Error.stackTraceLimit = prevLimit;
8374
+ }
8375
+ for (const site of rawSites) {
8376
+ if (!site)
8968
8377
  continue;
8969
- const match = line.match(/\((.*\.([jt]s|[cm]js)):\d+:\d+\)$/) ||
8970
- line.match(/at (.*\.([jt]s|[cm]js)):\d+:\d+$/);
8971
- if (!match)
8378
+ try {
8379
+ const rawFile = typeof site.getFileName === "function"
8380
+ ? site.getFileName() || ""
8381
+ : "";
8382
+ const fnName = typeof site.getFunctionName === "function"
8383
+ ? site.getFunctionName() || ""
8384
+ : "";
8385
+ const isEval = typeof site.isEval === "function" ? Boolean(site.isEval()) : false;
8386
+ frames.push({
8387
+ filePath: normalizeScriptName(rawFile),
8388
+ fnName,
8389
+ isEval,
8390
+ });
8391
+ }
8392
+ catch {
8393
+ // ignore
8394
+ }
8395
+ }
8396
+ // 2. Also merge frames from Node C++ util.getCallSites (which strips //# sourceURL on V8)
8397
+ if (_nativeGetCallSites) {
8398
+ try {
8399
+ const nativeSites = _nativeGetCallSites(64);
8400
+ for (const s of nativeSites) {
8401
+ if (!s)
8402
+ continue;
8403
+ const rawScript = s.scriptName || "";
8404
+ const fnName = s.functionName || "";
8405
+ frames.push({
8406
+ filePath: normalizeScriptName(rawScript),
8407
+ fnName,
8408
+ isEval: !rawScript && (fnName === "eval" || fnName === "anonymous"),
8409
+ });
8410
+ }
8411
+ }
8412
+ catch {
8413
+ // ignore
8414
+ }
8415
+ }
8416
+ return frames;
8417
+ }
8418
+ /**
8419
+ * Extracts verified caller information by inspecting the ENTIRE active call stack.
8420
+ * Immune to `Error.prepareStackTrace` hijacking AND `//# sourceURL` spoofing:
8421
+ * even if an attacker injects a fake frame via `new Function("//# sourceURL=...")`,
8422
+ * the attacker's own `node_modules/...` frame remains on the call stack and is detected.
8423
+ */
8424
+ function getVerifiedCallerInfo() {
8425
+ const frames = captureNativeFrames();
8426
+ let immediateCallerRoot;
8427
+ let immediateCallerFile = "";
8428
+ for (let i = 0; i < frames.length; i++) {
8429
+ const { filePath, isEval } = frames[i];
8430
+ if (isEval) {
8431
+ return {
8432
+ root: undefined,
8433
+ isUntrusted: true,
8434
+ callerFile: filePath || "<eval>",
8435
+ };
8436
+ }
8437
+ if (!filePath)
8972
8438
  continue;
8973
- const filePath = match[1];
8974
- if (!filePath || filePath === "native" || filePath === "node:fs" || filePath === "fs")
8439
+ if (filePath.startsWith("node:") ||
8440
+ filePath.startsWith("bun:") ||
8441
+ filePath === "native" ||
8442
+ filePath.includes("[eval]")) {
8975
8443
  continue;
8976
- // Skip internal engine files to locate the user/plugin caller
8444
+ }
8445
+ // Skip XyPriss internal engine frames
8977
8446
  if (isEngineCorePath(filePath)) {
8978
8447
  continue;
8979
8448
  }
8980
- if (line.includes("at get [") ||
8981
- line.includes("at getStrict (") ||
8982
- line.includes("PluginAPI.") ||
8983
- line.includes("Plugin."))
8449
+ // Skip CLI TypeScript loaders (tsx / ts-node) at the bottom of the stack
8450
+ if (isRuntimeLoaderPath(filePath)) {
8984
8451
  continue;
8985
- callerFilePath = filePath;
8986
- break;
8452
+ }
8453
+ const root = identifyProjectRoot(filePath);
8454
+ // If ANY frame in the call chain originates from an undeclared/untrusted node_modules package,
8455
+ // reject the entire operation immediately (defeats //# sourceURL wrapper functions).
8456
+ if (!root) {
8457
+ return {
8458
+ root: undefined,
8459
+ isUntrusted: true,
8460
+ callerFile: filePath,
8461
+ };
8462
+ }
8463
+ if (!immediateCallerRoot) {
8464
+ immediateCallerRoot = root;
8465
+ immediateCallerFile = filePath;
8466
+ }
8987
8467
  }
8988
- if (!callerFilePath)
8989
- return getPrimaryProjectRoot();
8990
- const root = identifyProjectRoot(callerFilePath);
8991
- return root;
8468
+ if (immediateCallerRoot) {
8469
+ return {
8470
+ root: immediateCallerRoot,
8471
+ isUntrusted: false,
8472
+ callerFile: immediateCallerFile,
8473
+ };
8474
+ }
8475
+ return {
8476
+ root: getPrimaryProjectRoot(),
8477
+ isUntrusted: false,
8478
+ callerFile: "",
8479
+ };
8480
+ }
8481
+ /**
8482
+ * Retrieves the project root of the code currently executing by analyzing the native V8 call stack.
8483
+ */
8484
+ function getCallerProjectRoot() {
8485
+ const info = getVerifiedCallerInfo();
8486
+ if (info.isUntrusted) {
8487
+ return undefined;
8488
+ }
8489
+ return info.root;
8992
8490
  }
8993
8491
  /**
8994
8492
  * Loads and cleans a XyPriss configuration file (JSON or JSONC).
@@ -9318,8 +8816,11 @@ class EnvApi {
9318
8816
  set(key, value) {
9319
8817
  this.validateKey(key);
9320
8818
  this.validateValue(key, value);
9321
- const store = this.getStoreForCaller();
9322
- store[key] = value;
8819
+ const root = this.resolveAuthorizedRoot();
8820
+ if (!root) {
8821
+ return;
8822
+ }
8823
+ this.runner.runSync("env", "set", [key, value], { root });
9323
8824
  // Keep process.env in sync for whitelisted keys and framework keys to maintain system stability.
9324
8825
  // Issue #43: Ensures internal components and child processes have immediate access to
9325
8826
  // framework configuration without triggering proxy descriptor violations under strict runtimes (Bun).
@@ -9350,8 +8851,11 @@ class EnvApi {
9350
8851
  * __sys__.__env__.delete("CI_DEPLOY_TOKEN");
9351
8852
  */
9352
8853
  delete(key) {
9353
- const store = this.getStoreForCaller();
9354
- delete store[key];
8854
+ const root = this.resolveAuthorizedRoot();
8855
+ if (!root) {
8856
+ return;
8857
+ }
8858
+ this.runner.runSync("env", "delete", [key], { root });
9355
8859
  if (this.whitelistedFields.has(key) ||
9356
8860
  key.startsWith("XY_") ||
9357
8861
  key.startsWith("XYPRISS_") ||
@@ -9368,12 +8872,15 @@ class EnvApi {
9368
8872
  }
9369
8873
  }
9370
8874
  get(key, defaultValue) {
8875
+ const root = this.resolveAuthorizedRoot();
8876
+ if (!root) {
8877
+ return defaultValue;
8878
+ }
9371
8879
  if (key === "__root__") {
9372
- return (this.isDynamic ? getCallerProjectRoot() : null) || this.runner.getRoot();
8880
+ return root;
9373
8881
  }
9374
- const store = this.getStoreForCaller();
9375
- const value = store[key];
9376
- return value !== undefined ? value : defaultValue;
8882
+ const res = this.runner.runSync("env", "get", [key], { root });
8883
+ return res?.found && res.value !== undefined ? res.value : defaultValue;
9377
8884
  }
9378
8885
  /**
9379
8886
  * Reads a variable from the secure internal store for a specific root.
@@ -9392,8 +8899,8 @@ class EnvApi {
9392
8899
  if (key === "__root__") {
9393
8900
  return root;
9394
8901
  }
9395
- const store = this.getStoreForCaller(root);
9396
- return store[key];
8902
+ const res = this.runner.runSync("env", "get", [key], { root });
8903
+ return res?.found ? res.value : undefined;
9397
8904
  }
9398
8905
  /**
9399
8906
  * Reads a required variable from the secure internal store and throws if
@@ -9423,15 +8930,7 @@ class EnvApi {
9423
8930
  * };
9424
8931
  */
9425
8932
  getStrict(key, options) {
9426
- if (key === "__root__") {
9427
- const rootVal = (this.isDynamic ? getCallerProjectRoot() : null) || this.runner.getRoot();
9428
- if (!rootVal) {
9429
- throw new EnvAccessError(key, "missing");
9430
- }
9431
- return rootVal;
9432
- }
9433
- const store = this.getStoreForCaller();
9434
- const value = store[key];
8933
+ const value = this.get(key);
9435
8934
  if (value === undefined) {
9436
8935
  throw new EnvAccessError(key, "missing");
9437
8936
  }
@@ -9455,8 +8954,12 @@ class EnvApi {
9455
8954
  * const betaEnabled = __sys__.__env__.has("ENABLE_BETA_UI");
9456
8955
  */
9457
8956
  has(key) {
9458
- const store = this.getStoreForCaller();
9459
- return store[key] !== undefined;
8957
+ const root = this.resolveAuthorizedRoot();
8958
+ if (!root) {
8959
+ return false;
8960
+ }
8961
+ const res = this.runner.runSync("env", "has", [key], { root });
8962
+ return Boolean(res?.found);
9460
8963
  }
9461
8964
  /**
9462
8965
  * Returns a frozen, point-in-time snapshot of stored variables.
@@ -9483,7 +8986,12 @@ class EnvApi {
9483
8986
  * logger.debug("Env snapshot", { count: Object.keys(full).length });
9484
8987
  */
9485
8988
  all(options) {
9486
- const store = this.getStoreForCaller();
8989
+ const root = this.resolveAuthorizedRoot();
8990
+ if (!root) {
8991
+ return Object.freeze({});
8992
+ }
8993
+ const res = this.runner.runSync("env", "all", [], { root });
8994
+ const store = res?.secrets || {};
9487
8995
  if (options?.keys && options.keys.length > 0) {
9488
8996
  const subset = {};
9489
8997
  for (const key of options.keys) {
@@ -9568,7 +9076,7 @@ class EnvApi {
9568
9076
  const callerRoot = getCallerProjectRoot();
9569
9077
  const hostRoot = this.runner.getRoot();
9570
9078
  if (callerRoot && callerRoot !== hostRoot && !isCoreFrameworkPath(callerRoot)) {
9571
- logger$2.warn("security", `Blocked unauthorized attempt by third-party plugin at '${callerRoot}' to configure Environment Security Shield.`);
9079
+ logger$1.warn("security", `Blocked unauthorized attempt by third-party plugin at '${callerRoot}' to configure Environment Security Shield.`);
9572
9080
  return;
9573
9081
  }
9574
9082
  this[XY_ENV_CONFIGURE_SHIELD](config);
@@ -9627,57 +9135,30 @@ class EnvApi {
9627
9135
  }
9628
9136
  }
9629
9137
  // -------------------------------------------------------------------------
9630
- // Private — store access
9138
+ // Private — Zero-Trust Caller Verification (V8 C++ CallSites + libSynapx)
9631
9139
  // -------------------------------------------------------------------------
9632
9140
  /**
9633
- * Returns the internal store, throwing {@link EnvStoreError} if it has not
9634
- * yet been initialised.
9635
- *
9636
- * SECURITY: This is the single point of store access. Every read and write
9637
- * method must go through here — never access `globalThis[XY_ENV_STORE_KEY]`
9638
- * directly outside this method.
9141
+ * Resolves the authorized project root for the current caller using native V8 C++ CallSites.
9639
9142
  *
9640
- * Eliminating the `?? process.env` fallback is intentional. A silent
9641
- * fallback to `process.env` during the bootstrap race window would bypass
9642
- * the Shield and leak values without any warning. A thrown error is
9643
- * immediately visible during development and integration testing.
9143
+ * SECURITY POLICY:
9144
+ * - If the caller originates from an undeclared `node_modules/` dependency or dynamic `eval` / `new Function`,
9145
+ * `callerInfo.isUntrusted` is true and this method returns `null` (NEVER falling back to `this.runner.getRoot()`).
9146
+ * - Zero secrets are stored in JavaScript RAM; all queries go through `this.runner.runSync("env", ...)` (`libSynapx`).
9644
9147
  *
9645
9148
  * @internal
9646
- * @throws {EnvStoreError}
9647
- */
9648
- requireStoreMap() {
9649
- const storeMap = getInternalProjectEnvs();
9650
- if (!storeMap) {
9651
- throw new EnvStoreError();
9652
- }
9653
- return storeMap;
9654
- }
9655
- getStoreForCaller(callerRoot) {
9656
- const storeMap = this.requireStoreMap();
9657
- // 🛡️ Security & Scope Policy (Sandboxing):
9658
- // 1. If an explicit root is provided, use it.
9659
- // 2. Fallback to dynamic project discovery based on the caller's stack (Restricted Context) if enabled.
9660
- // 3. Fallback to this EnvApi instance's pinned runner root (System Baseline/Forced root).
9661
- const root = callerRoot ||
9662
- (this.isDynamic ? getCallerProjectRoot() : null) ||
9663
- this.runner.getRoot() ||
9664
- getCallerProjectRoot();
9665
- if (!root)
9666
- return {};
9667
- let store = storeMap.get(root);
9668
- if (!store) {
9669
- // Dynamic loading for projects/plugins not encountered during bootstrap.
9670
- // Under Zero-Trust, all environment secrets must transit through libXESS IPC.
9671
- const envData = {};
9672
- const ipcSecrets = XessIpcClient.fetchSecretsSync(root);
9673
- for (const key in ipcSecrets) {
9674
- envData[key] = ipcSecrets[key];
9675
- }
9676
- // Cache the loaded env for this project
9677
- storeMap.set(root, envData);
9678
- store = envData;
9149
+ */
9150
+ resolveAuthorizedRoot(explicitRoot) {
9151
+ if (explicitRoot) {
9152
+ return explicitRoot;
9153
+ }
9154
+ const callerInfo = getVerifiedCallerInfo();
9155
+ if (callerInfo.isUntrusted) {
9156
+ return null;
9157
+ }
9158
+ if (this.isDynamic && callerInfo.root) {
9159
+ return callerInfo.root;
9679
9160
  }
9680
- return store;
9161
+ return this.runner.getRoot() || callerInfo.root || null;
9681
9162
  }
9682
9163
  // -------------------------------------------------------------------------
9683
9164
  // Private — validation
@@ -9798,16 +9279,7 @@ class EnvApi {
9798
9279
  }
9799
9280
  // Emit one warning per unique blocked key.
9800
9281
  if (!warnedKeys.has(prop)) {
9801
- const storeMap = getInternalProjectEnvs();
9802
- let isSilent = target["XYPRISS_ENV_SHIELD"] === "silent";
9803
- if (storeMap) {
9804
- for (const env of storeMap.values()) {
9805
- if (env["XYPRISS_ENV_SHIELD"] === "silent") {
9806
- isSilent = true;
9807
- break;
9808
- }
9809
- }
9810
- }
9282
+ const isSilent = target["XYPRISS_ENV_SHIELD"] === "silent";
9811
9283
  if (!isSilent) {
9812
9284
  process.stderr.write(`\x1b[33m[SECURITY]\x1b[0m ` +
9813
9285
  `Direct access to process.env["${prop}"] is blocked. ` +
@@ -16455,7 +15927,7 @@ class XyPrissXHSC extends XyPrissFS {
16455
15927
  enumerable: true,
16456
15928
  configurable: false,
16457
15929
  });
16458
- logger$2.debug("security", `Plugin ${pluginId} authorized. Workspace root: ${resolvedRoot} (Context: ${callerRoot})`);
15930
+ logger$1.debug("security", `Plugin ${pluginId} authorized. Workspace root: ${resolvedRoot} (Context: ${callerRoot})`);
16459
15931
  this._pluginMap.set(cacheKey, instance);
16460
15932
  return instance;
16461
15933
  }
@@ -16463,7 +15935,7 @@ class XyPrissXHSC extends XyPrissFS {
16463
15935
  // Void Sandbox — plugin non autorisé dans la config
16464
15936
  const voidPath = path$1.join(generateXUserTmpDir(), "void", "sandbox", pluginId.replace(/[^a-zA-Z0-9-]/g, "_"));
16465
15937
  this.fs.mkdir(voidPath, { parents: true });
16466
- logger$2.warn("security", `Plugin ${pluginId} requested workspace but was not explicitly authorized in config. Assigned implicit Void Sandbox (${voidPath}).`);
15938
+ logger$1.warn("security", `Plugin ${pluginId} requested workspace but was not explicitly authorized in config. Assigned implicit Void Sandbox (${voidPath}).`);
16467
15939
  return undefined;
16468
15940
  }
16469
15941
  }
@@ -16564,41 +16036,24 @@ if (typeof globalThis !== "undefined") {
16564
16036
  tempDir = path$1.dirname(tempDir);
16565
16037
  }
16566
16038
  }
16567
- // Load environment variables for each project hierarchy independently
16568
- const projectEnvs = new Map();
16569
- // Enforce libXESS Bipolar Shield as strictly mandatory
16570
- if (!XessIpcClient.isShielded(foundRoot)) {
16039
+ // Enforce libXESS Bipolar Shield via libSynapx (Go-to-Go Vault verification, zero secrets in JS RAM)
16040
+ const synapx = SynapxClient.getInstance();
16041
+ synapx.ensureDaemon();
16042
+ let envStatus = null;
16043
+ try {
16044
+ envStatus = synapx.callSync("env", "status", [], { root: foundRoot });
16045
+ }
16046
+ catch {
16047
+ envStatus = null;
16048
+ }
16049
+ if (!envStatus?.shielded) {
16571
16050
  const err = new XessShieldRequiredError();
16572
16051
  const l = new QuickLogger("XHSC");
16573
16052
  l.error(`[XyPriss Security Violation] ${err.message}`);
16574
16053
  throw err;
16575
16054
  }
16576
- const ipcSecrets = XessIpcClient.fetchSecretsSync(foundRoot);
16577
- // Process each project found in the hierarchy
16578
- for (const projectPath of projects) {
16579
- const envData = {};
16580
- if (projectPath === foundRoot) {
16581
- for (const key in ipcSecrets) {
16582
- envData[key] = ipcSecrets[key];
16583
- }
16584
- }
16585
- else {
16586
- // For descendant sub-projects: if an .env exists on disk (canary decoy),
16587
- // authentic secrets MUST be fetched from libXESS IPC. No silent fallback.
16588
- const subEnv = path$1.join(projectPath, ".env");
16589
- if (fs$1.existsSync(subEnv)) {
16590
- const projectSecrets = XessIpcClient.fetchSecretsSync(projectPath);
16591
- for (const key in projectSecrets) {
16592
- envData[key] = projectSecrets[key];
16593
- }
16594
- }
16595
- }
16596
- projectEnvs.set(projectPath, envData);
16597
- }
16598
- // Initialize the internal secure store as a Map of project environments in module closure
16599
- setInternalProjectEnvs(projectEnvs);
16600
- const primaryEnv = projectEnvs.get(foundRoot) || {};
16601
- const defaultPort = parseInt(primaryEnv["PORT"] || "3000");
16055
+ const defaultPort = parseInt(envStatus.port || "3000", 10) || 3000;
16056
+ const defaultMode = envStatus.mode || "development";
16602
16057
  // Read xypriss.config.jsonc or xypriss.config.json early to apply XESS configuration declaratively
16603
16058
  let earlyXessConfig = null;
16604
16059
  try {
@@ -16622,7 +16077,7 @@ if (typeof globalThis !== "undefined") {
16622
16077
  __root__: foundRoot,
16623
16078
  __port__: defaultPort,
16624
16079
  __PORT__: defaultPort,
16625
- __mode__: primaryEnv["NODE_ENV"] || "development",
16080
+ __mode__: defaultMode,
16626
16081
  });
16627
16082
  // Apply declarative XESS early configuration if found
16628
16083
  let earlyConfig = null;
@@ -16684,7 +16139,7 @@ class MetaConfigRunner {
16684
16139
  result.catch(this.handleFatalError.bind(this, metaPath));
16685
16140
  }
16686
16141
  }
16687
- logger$2.debug("server", `Executed meta file: ${metaPath}`);
16142
+ logger$1.debug("server", `Executed meta file: ${metaPath}`);
16688
16143
  })
16689
16144
  .catch(this.handleFatalError.bind(this, metaPath));
16690
16145
  }
@@ -16724,7 +16179,7 @@ class MetaConfigRunner {
16724
16179
  }
16725
16180
  }
16726
16181
  handleFatalError(metaPath, error) {
16727
- logger$2.error("server", `FATAL: Failed to execute meta file ${metaPath}: ${error.message || error}`);
16182
+ logger$1.error("server", `FATAL: Failed to execute meta file ${metaPath}: ${error.message || error}`);
16728
16183
  // Terminate process securely via system API
16729
16184
  if (globalThis.__sys__ && typeof globalThis.__sys__.exit === "function") {
16730
16185
  globalThis.__sys__.exit(1);
@@ -16756,19 +16211,19 @@ class ConfigLoader {
16756
16211
  return;
16757
16212
  this.isConfigApplied = true;
16758
16213
  const root = getCallerProjectRoot() || __sys__$1.__root__;
16759
- logger$2.debug("server", `ConfigLoader: Initializing discovery from root: ${root}`);
16214
+ logger$1.debug("server", `ConfigLoader: Initializing discovery from root: ${root}`);
16760
16215
  const configFiles = [];
16761
16216
  // Only look for config at the absolute project root (preferring .jsonc)
16762
16217
  for (const name of ["xypriss.config.jsonc", "xypriss.config.json"]) {
16763
16218
  const potentialConfig = this.sys.path.join(root, name);
16764
16219
  if (this.sys.fs.exist(potentialConfig)) {
16765
- logger$2.debug("server", `ConfigLoader: Found configuration file: ${potentialConfig}`);
16220
+ logger$1.debug("server", `ConfigLoader: Found configuration file: ${potentialConfig}`);
16766
16221
  configFiles.push(potentialConfig);
16767
16222
  break; // Stop after first match in root
16768
16223
  }
16769
16224
  }
16770
16225
  if (configFiles.length === 0) {
16771
- logger$2.debug("server", `ConfigLoader: No configuration file found in ${root}`);
16226
+ logger$1.debug("server", `ConfigLoader: No configuration file found in ${root}`);
16772
16227
  }
16773
16228
  // Process only the root configuration
16774
16229
  for (const configPath of configFiles) {
@@ -16788,10 +16243,10 @@ class ConfigLoader {
16788
16243
  const rawConfig = JsonUtils.parse(rawContent);
16789
16244
  // Load package.json if not already loaded
16790
16245
  this.loadPackageJson(projectRoot);
16791
- logger$2.debug("server", `ConfigLoader: Resolving references for ${this.sys.path.basename(configPath)}`);
16246
+ logger$1.debug("server", `ConfigLoader: Resolving references for ${this.sys.path.basename(configPath)}`);
16792
16247
  if (__sys__$1?.__env__) {
16793
16248
  const envSnapshot = __sys__$1.__env__.all();
16794
- logger$2.debug("server", `ConfigLoader: Env keys available in store for ${projectRoot}: ${Object.keys(envSnapshot).join(", ")}`);
16249
+ logger$1.debug("server", `ConfigLoader: Env keys available in store for ${projectRoot}: ${Object.keys(envSnapshot).join(", ")}`);
16795
16250
  }
16796
16251
  const envProvider = __sys__$1?.__env__
16797
16252
  ? {
@@ -16814,11 +16269,11 @@ class ConfigLoader {
16814
16269
  const config = this.resolveRefs(rawConfig, envProvider);
16815
16270
  if (!config)
16816
16271
  return;
16817
- logger$2.debug("server", `ConfigLoader: Applied configuration from: ${this.sys.path.relative(projectRoot, configPath)}`);
16272
+ logger$1.debug("server", `ConfigLoader: Applied configuration from: ${this.sys.path.relative(projectRoot, configPath)}`);
16818
16273
  // Apply __sys__ config if present
16819
16274
  if (config?.$vars) {
16820
16275
  if (__sys__$1) {
16821
- logger$2.debug("server", `ConfigLoader: Updating system variables with $vars: ${JSON.stringify(config.$vars)}`);
16276
+ logger$1.debug("server", `ConfigLoader: Updating system variables with $vars: ${JSON.stringify(config.$vars)}`);
16822
16277
  __sys__$1.vars.update(config.$vars);
16823
16278
  }
16824
16279
  }
@@ -16845,7 +16300,7 @@ class ConfigLoader {
16845
16300
  }
16846
16301
  }
16847
16302
  if (Object.keys(serverOptionsToApply).length > 0) {
16848
- logger$2.debug("server", `ConfigLoader: Merging discovered server configuration into Configs`);
16303
+ logger$1.debug("server", `ConfigLoader: Merging discovered server configuration into Configs`);
16849
16304
  ConfigurationManager.merge(serverOptionsToApply);
16850
16305
  }
16851
16306
  // Process internal configuration
@@ -16885,7 +16340,7 @@ class ConfigLoader {
16885
16340
  __mode__: __sys__$1.__env__.mode,
16886
16341
  });
16887
16342
  __sys__$1[XY_XHSC_REGISTER_FS](pluginId, specializedFS);
16888
- logger$2.debug("server", `Specialized filesystem mapped: ${pluginId} -> ${resolvedFsPath} (from: ${rawPath})`);
16343
+ logger$1.debug("server", `Specialized filesystem mapped: ${pluginId} -> ${resolvedFsPath} (from: ${rawPath})`);
16889
16344
  }
16890
16345
  }
16891
16346
  // 2. Execute additional meta logic if __meta__ is present
@@ -16913,7 +16368,7 @@ class ConfigLoader {
16913
16368
  }
16914
16369
  if (allPermissions.length > 0) {
16915
16370
  __sys__$1.vars.set("pluginPermissions", allPermissions);
16916
- logger$2.debug("server", `Loaded ${allPermissions.length} plugin permission rules from configuration`);
16371
+ logger$1.debug("server", `Loaded ${allPermissions.length} plugin permission rules from configuration`);
16917
16372
  }
16918
16373
  }
16919
16374
  /**
@@ -16949,7 +16404,7 @@ class ConfigLoader {
16949
16404
  this.packageJson = JSON.parse(this.sys.fs.readSync(pkgPath));
16950
16405
  }
16951
16406
  catch (error) {
16952
- logger$2.warn("server", "Failed to parse package.json for configuration resolution");
16407
+ logger$1.warn("server", "Failed to parse package.json for configuration resolution");
16953
16408
  }
16954
16409
  }
16955
16410
  }
@@ -27741,11 +27196,6 @@ class EngineManager {
27741
27196
  // Zero CLI Flags: 100% encrypted single descriptor argument
27742
27197
  const args = [configPath];
27743
27198
  const internalSig = getInternalSignature();
27744
- let sessionKey = "";
27745
- try {
27746
- sessionKey = XessIpcClient.getActiveSessionKey();
27747
- }
27748
- catch { }
27749
27199
  this.logger.debug("server", `Starting XHSC engine: ${args.join(" ")}`);
27750
27200
  const binaryPath = this.runner.getBinaryPath();
27751
27201
  const child = node_child_process.spawn(binaryPath, args, {
@@ -27753,7 +27203,6 @@ class EngineManager {
27753
27203
  detached: true,
27754
27204
  env: {
27755
27205
  ...process.env,
27756
- ...(sessionKey ? { XYPRISS_XESS_SESSION_KEY: sessionKey } : {}),
27757
27206
  ...(internalSig
27758
27207
  ? { XYPRISS_INTERNAL_TOKEN: internalSig }
27759
27208
  : {}),
@@ -28118,7 +27567,7 @@ class RequestProcessor {
28118
27567
  });
28119
27568
  }
28120
27569
  catch (error) {
28121
- logger$2.warn("other", `High-performance path failed for ${req.method} ${req.path}:`, error.message);
27570
+ logger$1.warn("other", `High-performance path failed for ${req.method} ${req.path}:`, error.message);
28122
27571
  return await this.handleStandardPath(req, res, next, requestId, classification);
28123
27572
  }
28124
27573
  }
@@ -28166,7 +27615,7 @@ class RequestProcessor {
28166
27615
  next();
28167
27616
  }
28168
27617
  catch (error) {
28169
- logger$2.warn("other", `Fast path failed for ${req.method} ${req.path}:`, error.message);
27618
+ logger$1.warn("other", `Fast path failed for ${req.method} ${req.path}:`, error.message);
28170
27619
  return await this.handleStandardPath(req, res, next, requestId, classification);
28171
27620
  }
28172
27621
  }
@@ -28210,7 +27659,7 @@ class RequestProcessor {
28210
27659
  next();
28211
27660
  }
28212
27661
  catch (error) {
28213
- logger$2.error("other", `Standard path failed for ${req.method} ${req.path}:`, error.message);
27662
+ logger$1.error("other", `Standard path failed for ${req.method} ${req.path}:`, error.message);
28214
27663
  next(error);
28215
27664
  }
28216
27665
  }
@@ -28246,10 +27695,10 @@ class RequestProcessor {
28246
27695
  await this.dependencies.cacheManager
28247
27696
  .getCache()
28248
27697
  .set(cacheKey, data, { ttl });
28249
- logger$2.debug("other", `CACHED (${pathType}): ${cacheKey} (TTL: ${ttl}ms)`);
27698
+ logger$1.debug("other", `CACHED (${pathType}): ${cacheKey} (TTL: ${ttl}ms)`);
28250
27699
  }
28251
27700
  catch (error) {
28252
- logger$2.error("other", "Cache set error:", error.message);
27701
+ logger$1.error("other", "Cache set error:", error.message);
28253
27702
  }
28254
27703
  });
28255
27704
  return originalJson(data);
@@ -28269,7 +27718,7 @@ class RouteManager {
28269
27718
  * Add all HTTP methods with caching support to the XyPriss app
28270
27719
  */
28271
27720
  addMethods() {
28272
- logger$2.debug("routes", "Adding HTTP methods with caching support...");
27721
+ logger$1.debug("routes", "Adding HTTP methods with caching support...");
28273
27722
  this.addCacheManagementMethods();
28274
27723
  // logger.debug( "routes","HTTP methods added successfully");
28275
27724
  }
@@ -31878,7 +31327,7 @@ function createSafeJsonMiddleware(options = {}) {
31878
31327
  catch (error) {
31879
31328
  if (opts.logCircularRefs &&
31880
31329
  error.message.includes("circular")) {
31881
- logger$2.debug("server", "🔄 Circular reference detected, using safe serialization:", {
31330
+ logger$1.debug("server", "🔄 Circular reference detected, using safe serialization:", {
31882
31331
  url: req.url,
31883
31332
  method: req.method,
31884
31333
  error: error.message,
@@ -31891,7 +31340,7 @@ function createSafeJsonMiddleware(options = {}) {
31891
31340
  return originalJson(parsedResult);
31892
31341
  }
31893
31342
  catch (safeError) {
31894
- logger$2.debug("server", "❌ Safe JSON serialization failed:", safeError);
31343
+ logger$1.debug("server", "❌ Safe JSON serialization failed:", safeError);
31895
31344
  return originalJson({
31896
31345
  error: "Serialization failed",
31897
31346
  message: "Unable to serialize response object",
@@ -32615,7 +32064,7 @@ class CacheManager {
32615
32064
  await this.cache.connect();
32616
32065
  }
32617
32066
  catch (error) {
32618
- logger$2.error("cache", "Cache initialization failed:", error);
32067
+ logger$1.error("cache", "Cache initialization failed:", error);
32619
32068
  throw error;
32620
32069
  }
32621
32070
  }
@@ -32676,13 +32125,13 @@ class CacheManager {
32676
32125
  });
32677
32126
  }
32678
32127
  catch (error) {
32679
- logger$2.warn("cache", `Failed to warm up ${item.key}:`, error.message);
32128
+ logger$1.warn("cache", `Failed to warm up ${item.key}:`, error.message);
32680
32129
  }
32681
32130
  });
32682
32131
  await Promise.all(warmupPromises);
32683
32132
  }
32684
32133
  catch (error) {
32685
- logger$2.warn("cache", "Cache warmup failed:", error.message);
32134
+ logger$1.warn("cache", "Cache warmup failed:", error.message);
32686
32135
  }
32687
32136
  }
32688
32137
  /**
@@ -32770,7 +32219,7 @@ class WorkerPoolComponent {
32770
32219
  }
32771
32220
  }
32772
32221
  initialize() {
32773
- logger$2.debug("other", "Initializing WorkerPool delegation to XHSC (Go Core)...");
32222
+ logger$1.debug("other", "Initializing WorkerPool delegation to XHSC (Go Core)...");
32774
32223
  this.addWorkerPoolMethods();
32775
32224
  }
32776
32225
  addWorkerPoolMethods() {
@@ -32789,7 +32238,7 @@ class WorkerPoolComponent {
32789
32238
  });
32790
32239
  }
32791
32240
  else {
32792
- logger$2.warn("cluster", "WorkerPool task executed locally (XHSC disabled/Master)");
32241
+ logger$1.warn("cluster", "WorkerPool task executed locally (XHSC disabled/Master)");
32793
32242
  // Local execution fallback if needed, or just log
32794
32243
  }
32795
32244
  };
@@ -32819,7 +32268,7 @@ class WorkerPoolComponent {
32819
32268
  app.executeTask(task);
32820
32269
  };
32821
32270
  app.isWorkerPoolEnabled = () => true;
32822
- logger$2.debug("other", "Worker pool delegated methods added to app");
32271
+ logger$1.debug("other", "Worker pool delegated methods added to app");
32823
32272
  }
32824
32273
  shutdown() {
32825
32274
  // delegated to Go