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/esm/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as path from 'node:path';
2
2
  import path__default from 'node:path';
3
- import { getRandomBytes, Cipher, XStringify, Random, XyPriStringify, SecureInMemoryCache, SecureCacheAdapter, Hash } from 'xypriss-security';
3
+ import { getRandomBytes, XStringify, Cipher, Random, XyPriStringify, SecureInMemoryCache, SecureCacheAdapter, Hash } from 'xypriss-security';
4
4
  import * as crypto$1 from 'crypto';
5
5
  import crypto__default, { timingSafeEqual } from 'crypto';
6
- import { execFileSync, spawn } from 'node:child_process';
6
+ import { spawn, execFileSync } from 'node:child_process';
7
7
  import * as fs from 'node:fs';
8
8
  import fs__default from 'node:fs';
9
9
  import { fileURLToPath } from 'node:url';
@@ -14,6 +14,7 @@ import * as fs$1 from 'fs';
14
14
  import fs__default$1 from 'fs';
15
15
  import * as path$1 from 'path';
16
16
  import path__default$1 from 'path';
17
+ import util from 'node:util';
17
18
  import { ID, NehoID } from 'nehoid';
18
19
  import net$1 from 'net';
19
20
  import { Interface, Mod } from 'reliant-type';
@@ -939,7 +940,7 @@ class Logger {
939
940
  // Module helpers
940
941
  // ─────────────────────────────────────────────
941
942
  /** Shared singleton — ready to use immediately. */
942
- const logger$2 = Logger.getInstance();
943
+ const logger$1 = Logger.getInstance();
943
944
  /** Configure and return the singleton logger. */
944
945
  function initializeLogger(config) {
945
946
  return Logger.getInstance(config);
@@ -1061,7 +1062,7 @@ const defaultHelmetOpts = {
1061
1062
  };
1062
1063
  // Log a warning if the development profile is active
1063
1064
  if (isDev) {
1064
- 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");
1065
+ 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");
1065
1066
  }
1066
1067
 
1067
1068
  const xemsKeyPlaceholder = "CHANGE_ME_TO_A_SECURE_32_CHAR_KEY";
@@ -3721,6 +3722,20 @@ let socket = null;
3721
3722
  let rxChunks = [];
3722
3723
  let rxBytesTotal = 0;
3723
3724
  let isHandshaked = false;
3725
+ let pendingDispatch = false;
3726
+
3727
+ function flushDispatch() {
3728
+ if (!socket || socket.destroyed || !isHandshaked) return;
3729
+ const reqLen = Atomics.load(int32, IDX_REQ_LEN);
3730
+ const reqBytes = uint8.subarray(DATA_OFFSET, DATA_OFFSET + reqLen);
3731
+
3732
+ const h = Buffer.alloc(6);
3733
+ h.writeUInt8(0x53, 0);
3734
+ h.writeUInt8(0x03, 1); // MSG_CALL
3735
+ h.writeUInt32BE(reqBytes.length, 2);
3736
+
3737
+ socket.write(Buffer.concat([h, reqBytes]));
3738
+ }
3724
3739
 
3725
3740
  function pushChunk(chunk) {
3726
3741
  rxChunks.push(chunk);
@@ -3806,6 +3821,10 @@ function connectSocket() {
3806
3821
  isHandshaked = true;
3807
3822
  try { socket.unref(); } catch {}
3808
3823
  parentPort.postMessage({ type: "READY" });
3824
+ if (pendingDispatch) {
3825
+ pendingDispatch = false;
3826
+ flushDispatch();
3827
+ }
3809
3828
  }
3810
3829
  } else if (header.type === 0x04) { // MSG_RESPONSE
3811
3830
  uint8.set(payload, DATA_OFFSET);
@@ -3834,24 +3853,16 @@ function connectSocket() {
3834
3853
 
3835
3854
  parentPort.on("message", (msg) => {
3836
3855
  if (msg.type === "DISPATCH") {
3837
- if (!socket || socket.destroyed || !isHandshaked) {
3838
- const errPayload = Buffer.from(JSON.stringify({ ok: false, err: "libSynapx worker socket disconnected" }));
3839
- uint8.set(errPayload, DATA_OFFSET);
3840
- Atomics.store(int32, IDX_RESP_LEN, errPayload.length);
3841
- Atomics.store(int32, IDX_STATUS, STATUS_ERROR);
3842
- Atomics.notify(int32, IDX_STATUS, 1);
3856
+ if (!socket || socket.destroyed) {
3857
+ pendingDispatch = true;
3858
+ connectSocket();
3843
3859
  return;
3844
3860
  }
3845
-
3846
- const reqLen = Atomics.load(int32, IDX_REQ_LEN);
3847
- const reqBytes = uint8.subarray(DATA_OFFSET, DATA_OFFSET + reqLen);
3848
-
3849
- const h = Buffer.alloc(6);
3850
- h.writeUInt8(0x53, 0);
3851
- h.writeUInt8(0x03, 1); // MSG_CALL
3852
- h.writeUInt32BE(reqBytes.length, 2);
3853
-
3854
- socket.write(Buffer.concat([h, reqBytes]));
3861
+ if (!isHandshaked) {
3862
+ pendingDispatch = true;
3863
+ return;
3864
+ }
3865
+ flushDispatch();
3855
3866
  }
3856
3867
  });
3857
3868
 
@@ -3991,1725 +4002,872 @@ class SynapxSyncBridge {
3991
4002
  }
3992
4003
  SynapxSyncBridge.instance = null;
3993
4004
 
4005
+ /* *****************************************************************************
4006
+ * Nehonix libSynapx — TypeScript Client
4007
+ *
4008
+ * High-performance, persistent Zero-Trust IPC client connecting XyPriss
4009
+ * to the Go libSynapx engine over isolated Unix Domain Sockets / Named Pipes.
4010
+ ***************************************************************************** */
4011
+ // Protocol Constants (matching libSynapx Go wire format)
4012
+ const MAGIC_BYTE = 0x53; // 'S'
4013
+ const MSG_HANDSHAKE = 0x01;
4014
+ const MSG_HANDSHAKE_ACK = 0x02;
4015
+ const MSG_CALL = 0x03;
4016
+ const MSG_RESPONSE = 0x04;
4017
+ const MSG_PONG = 0x08;
4018
+ const MSG_ERROR = 0xff;
4019
+ const HEADER_SIZE$1 = 6;
3994
4020
  /**
3995
- * ANSI color codes for terminal output
4021
+ * **SynapxClient**
4022
+ *
4023
+ * Persistent, multiplexed IPC client connecting TypeScript to the Go libSynapx core.
3996
4024
  */
3997
- const ANSI = {
3998
- reset: "\x1b[0m",
3999
- bold: "\x1b[1m",
4000
- dim: "\x1b[2m",
4001
- // Foreground colors
4002
- black: "\x1b[30m",
4003
- yellow: "\x1b[33m",
4004
- blue: "\x1b[34m",
4005
- cyan: "\x1b[36m",
4006
- white: "\x1b[37m",
4007
- gray: "\x1b[90m",
4008
- // Bright foreground
4009
- brightRed: "\x1b[91m",
4010
- brightGreen: "\x1b[92m",
4011
- brightYellow: "\x1b[93m",
4012
- brightBlue: "\x1b[94m",
4013
- brightMagenta: "\x1b[95m",
4014
- brightCyan: "\x1b[96m",
4015
- // Background colors
4016
- bgRed: "\x1b[41m",
4017
- bgGreen: "\x1b[42m",
4018
- bgYellow: "\x1b[43m",
4019
- bgBlue: "\x1b[44m",
4020
- bgMagenta: "\x1b[45m",
4021
- bgCyan: "\x1b[46m",
4022
- };
4023
- const LOG_CONFIGS = {
4024
- info: {
4025
- icon: "ℹ️ ",
4026
- color: ANSI.brightCyan,
4027
- label: "INFO",
4028
- labelColor: `${ANSI.bgCyan}${ANSI.black}`,
4029
- },
4030
- success: {
4031
- icon: "✅",
4032
- color: ANSI.brightGreen,
4033
- label: "OK",
4034
- labelColor: `${ANSI.bgGreen}${ANSI.black}`,
4035
- },
4036
- warn: {
4037
- icon: "⚠️ ",
4038
- color: ANSI.brightYellow,
4039
- label: "WARN",
4040
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4041
- },
4042
- error: {
4043
- icon: "❌",
4044
- color: ANSI.brightRed,
4045
- label: "ERROR",
4046
- labelColor: `${ANSI.bgRed}${ANSI.white}`,
4047
- },
4048
- debug: {
4049
- icon: "-",
4050
- color: ANSI.gray,
4051
- label: "DEBUG",
4052
- labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
4053
- },
4054
- http: {
4055
- icon: "🌐",
4056
- color: ANSI.brightBlue,
4057
- label: "HTTP",
4058
- labelColor: `${ANSI.bgBlue}${ANSI.white}`,
4059
- },
4060
- swagger: {
4061
- icon: "🛡️ ",
4062
- color: ANSI.brightMagenta,
4063
- label: "SWAGGER",
4064
- labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
4065
- },
4066
- db: {
4067
- icon: "🗄️ ",
4068
- color: ANSI.yellow,
4069
- label: "DB",
4070
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4071
- },
4072
- auth: {
4073
- icon: "🔐",
4074
- color: ANSI.brightYellow,
4075
- label: "AUTH",
4076
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4077
- },
4078
- };
4079
- const LEVEL_RANK = {
4080
- silent: 0,
4081
- error: 1,
4082
- warn: 2,
4083
- info: 3,
4084
- success: 3,
4085
- http: 3,
4086
- swagger: 3,
4087
- db: 3,
4088
- auth: 3,
4089
- debug: 4,
4090
- verbose: 5,
4091
- };
4092
- class QuickLogger {
4093
- constructor(context) {
4094
- this.context = context;
4095
- }
4096
- // ─── Static factory ───────────────────────────────────────────────────────
4097
- static for(context) {
4098
- return new QuickLogger(context);
4025
+ class SynapxClient {
4026
+ /**
4027
+ * Appends a newly received socket chunk to the internal accumulator.
4028
+ */
4029
+ pushChunk(chunk) {
4030
+ this.rxChunks.push(chunk);
4031
+ this.rxBytesTotal += chunk.length;
4099
4032
  }
4100
- static shouldLog(level) {
4101
- const sys = getSysApi();
4102
- let isDebug = false;
4103
- if (sys?.__env__) {
4104
- isDebug =
4105
- sys.__env__.get("DEBUG") ||
4106
- sys.__env__.get("XYPRISS_DEBUG") ||
4107
- sys.__env__.get("DEBUG_FS");
4033
+ /**
4034
+ * Peeks at the framing header without mutating or eagerly concatenating the chunk buffer.
4035
+ */
4036
+ peekHeader() {
4037
+ if (this.rxBytesTotal < HEADER_SIZE$1)
4038
+ return null;
4039
+ const first = this.rxChunks[0];
4040
+ if (first.length >= HEADER_SIZE$1) {
4041
+ return {
4042
+ magic: first.readUInt8(0),
4043
+ msgType: first.readUInt8(1),
4044
+ length: first.readUInt32BE(2),
4045
+ };
4108
4046
  }
4109
- else if (typeof process !== "undefined" && process.env) {
4110
- isDebug =
4111
- process.env.DEBUG ||
4112
- process.env.XYPRISS_DEBUG ||
4113
- process.env.DEBUG_FS;
4047
+ const hdr = Buffer.allocUnsafe(HEADER_SIZE$1);
4048
+ let copied = 0;
4049
+ for (const chunk of this.rxChunks) {
4050
+ const toCopy = Math.min(chunk.length, HEADER_SIZE$1 - copied);
4051
+ chunk.copy(hdr, copied, 0, toCopy);
4052
+ copied += toCopy;
4053
+ if (copied >= HEADER_SIZE$1)
4054
+ break;
4114
4055
  }
4115
- if (isDebug) {
4116
- return true;
4056
+ return {
4057
+ magic: hdr.readUInt8(0),
4058
+ msgType: hdr.readUInt8(1),
4059
+ length: hdr.readUInt32BE(2),
4060
+ };
4061
+ }
4062
+ /**
4063
+ * Consumes exactly numBytes from the front of the chunk list in a single fast copy.
4064
+ */
4065
+ consumeBytes(numBytes) {
4066
+ if (numBytes === 0)
4067
+ return Buffer.alloc(0);
4068
+ if (this.rxChunks.length === 1 && this.rxChunks[0].length === numBytes) {
4069
+ const buf = this.rxChunks[0];
4070
+ this.rxChunks = [];
4071
+ this.rxBytesTotal = 0;
4072
+ return buf;
4117
4073
  }
4118
- try {
4119
- const logging = ConfigurationManager.get("logging");
4120
- if (logging) {
4121
- if (logging.enabled === false) {
4122
- return false;
4123
- }
4124
- // Check logging.types overrides
4125
- if (level === "error" && logging.types?.errors === false)
4126
- return false;
4127
- if (level === "warn" && logging.types?.warnings === false)
4128
- return false;
4129
- if (level === "debug" && logging.types?.debug === false)
4130
- return false;
4131
- if (level === "debug" && logging.types?.debug === true)
4132
- return true;
4133
- // Check logging.level rank
4134
- const configuredLevel = (logging.level || "info").toLowerCase();
4135
- const configuredRank = LEVEL_RANK[configuredLevel] ?? 3;
4136
- const messageRank = LEVEL_RANK[level] ?? 3;
4137
- return messageRank <= configuredRank;
4074
+ const result = Buffer.allocUnsafe(numBytes);
4075
+ let offset = 0;
4076
+ while (this.rxChunks.length > 0 && offset < numBytes) {
4077
+ const head = this.rxChunks[0];
4078
+ const needed = numBytes - offset;
4079
+ if (head.length <= needed) {
4080
+ head.copy(result, offset);
4081
+ offset += head.length;
4082
+ this.rxChunks.shift();
4083
+ }
4084
+ else {
4085
+ head.copy(result, offset, 0, needed);
4086
+ offset += needed;
4087
+ this.rxChunks[0] = head.subarray(needed);
4138
4088
  }
4139
4089
  }
4140
- catch { }
4141
- // Default ranking if no config: info level (rank 3)
4142
- const defaultRank = 3;
4143
- const messageRank = LEVEL_RANK[level] ?? 3;
4144
- return messageRank <= defaultRank;
4090
+ this.rxBytesTotal -= numBytes;
4091
+ return result;
4145
4092
  }
4146
- // ─── Core log method ──────────────────────────────────────────────────────
4147
- log(level, ...args) {
4148
- if (!QuickLogger.shouldLog(level)) {
4149
- return;
4093
+ /**
4094
+ * Resynchronizes stream by advancing past corrupt bytes to the next magic byte.
4095
+ */
4096
+ discardUntilMagic() {
4097
+ while (this.rxChunks.length > 0) {
4098
+ const head = this.rxChunks[0];
4099
+ const idx = head.indexOf(MAGIC_BYTE);
4100
+ if (idx !== -1) {
4101
+ if (idx > 0) {
4102
+ this.consumeBytes(idx);
4103
+ }
4104
+ return true;
4105
+ }
4106
+ else {
4107
+ this.rxBytesTotal -= head.length;
4108
+ this.rxChunks.shift();
4109
+ }
4150
4110
  }
4151
- const cfg = LOG_CONFIGS[level];
4152
- const timestamp = QuickLogger.showTimestamp
4153
- ? `${ANSI.dim}${ANSI.gray}${new Date().toISOString()}${ANSI.reset} `
4154
- : "";
4155
- const label = `${cfg.labelColor}${ANSI.bold} ${cfg.label} ${ANSI.reset}`;
4156
- const ctx = `${ANSI.dim}${ANSI.cyan}[${this.context}]${ANSI.reset}`;
4157
- // First arg gets the level color + icon, rest are passed raw so Node.js
4158
- // pretty-prints objects/arrays/Errors natively (no JSON.stringify needed).
4159
- const [first, ...rest] = args;
4160
- const prefix = `${timestamp}${label} ${ctx} ${cfg.color}${cfg.icon} ${String(first)}${ANSI.reset}`;
4161
- const consoleFn = level === "error"
4162
- ? console.error
4163
- : level === "warn"
4164
- ? console.warn
4165
- : console.log;
4166
- rest.length > 0 ? consoleFn(prefix, ...rest) : consoleFn(prefix);
4167
- }
4168
- // ─── Public methods ───────────────────────────────────────────────────────
4169
- info(...args) {
4170
- this.log("info", ...args);
4171
- }
4172
- success(...args) {
4173
- this.log("success", ...args);
4174
- }
4175
- warn(...args) {
4176
- this.log("warn", ...args);
4177
- }
4178
- error(...args) {
4179
- this.log("error", ...args);
4180
- }
4181
- debug(...args) {
4182
- this.log("debug", ...args);
4183
- }
4184
- http(...args) {
4185
- this.log("http", ...args);
4186
- }
4187
- swagger(...args) {
4188
- this.log("swagger", ...args);
4189
- }
4190
- db(...args) {
4191
- this.log("db", ...args);
4192
- }
4193
- auth(...args) {
4194
- this.log("auth", ...args);
4195
- }
4196
- // ─── Convenience: banner / separator ─────────────────────────────────────
4197
- banner(title) {
4198
- const line = `${ANSI.blue}${"─".repeat(60)}${ANSI.reset}`;
4199
- const centered = title
4200
- .padStart(30 + Math.floor(title.length / 2))
4201
- .padEnd(60);
4202
- console.log(`\n${line}`);
4203
- console.log(`${ANSI.bold}${ANSI.brightCyan}${centered}${ANSI.reset}`);
4204
- console.log(`${line}\n`);
4205
- }
4206
- }
4207
- QuickLogger.showTimestamp = true;
4208
- // ─── Default singleton logger ──────────────────────────────────────────────
4209
- // export const logger = QuickLogger.for("");
4210
-
4211
- /**
4212
- * Returns the absolute path to the XyPriss shared temp directory.
4213
- *
4214
- * @returns {string} Path to `<os.tmpdir>/nehonix.xypriss.data`
4215
- */
4216
- function getXyprissTempDir() {
4217
- const sys = getSysApi();
4218
- return sys.path.join(sys.path.tempDir(), "nehonix.xypriss.data");
4219
- }
4220
- /**
4221
- * Resolves and ensures a sub-path within the XyPriss temp directory exists.
4222
- *
4223
- * @param {string | string[]} _p - Sub-path segment(s) to append.
4224
- * @returns {string} The absolute resolved temp sub-path.
4225
- */
4226
- function createXyprissTempDir(_p) {
4227
- const sys = getSysApi();
4228
- const base = getXyprissTempDir();
4229
- const segment = typeof _p === "string"
4230
- ? _p
4231
- : _p.includes("/")
4232
- ? _p.map((p) => p.replace("/", "")).join("/")
4233
- : _p.join("/");
4234
- // Use the native corrective layer to prevent doubling or redundant separators
4235
- const rawPath = segment.startsWith(base)
4236
- ? segment
4237
- : sys.path.join(base, segment);
4238
- const normalisedPath = sys.path.correct(rawPath, { tentative: 2 });
4239
- if (!sys.fs.exist(normalisedPath)) {
4240
- sys.fs.mkdir(normalisedPath, { parents: true });
4241
- }
4242
- return normalisedPath;
4243
- }
4244
- /**
4245
- * **Session Temp Directory (singleton)**
4246
- *
4247
- * Unique sub-path generated once per process lifetime under the XyPriss
4248
- * temp root (`<os.tmpdir>/nehonix.xypriss.data/xuser/<hex4>`).
4249
- *
4250
- * The value is memoized on first access and remains stable for the entire
4251
- * duration of the running process, ensuring all callers within the same
4252
- * session share the same isolated scratch space.
4253
- */
4254
- let _sessionTmpDir = null;
4255
- /**
4256
- * Returns the process-scoped user temp directory path for THIS active server instance.
4257
- *
4258
- * Generates an instance ID hash once and caches it for the lifetime of the process.
4259
- * E.g. `/tmp/nehonix.xypriss.data/xuser/12daa75a`
4260
- *
4261
- * @returns {string} Absolute path to instance temp directory
4262
- */
4263
- function generateXUserTmpDir() {
4264
- if (_sessionTmpDir !== null) {
4265
- return _sessionTmpDir;
4111
+ return false;
4266
4112
  }
4267
- const sys = getSysApi();
4268
- // 1. Adopt the session directory allocated exclusively by the libProc supervisor
4269
- const envSession = sys?.__env__?.get("XYPRISS_USER_TMP") ||
4270
- sys?.__env__?.get("XESS_SESSION_TMP") ||
4271
- (typeof process !== "undefined"
4272
- ? (process.env?.XYPRISS_USER_TMP || process.env?.XESS_SESSION_TMP)
4273
- : undefined);
4274
- if (envSession && typeof envSession === "string") {
4275
- _sessionTmpDir = envSession;
4276
- if (sys?.fs && !sys.fs.exist(_sessionTmpDir)) {
4277
- sys.fs.mkdir(_sessionTmpDir, { parents: true });
4113
+ constructor(customSocketPath) {
4114
+ this.socket = null;
4115
+ this.connectingPromise = null;
4116
+ this.isHandshakeComplete = false;
4117
+ this.sessionKey = "";
4118
+ this.seqId = 0;
4119
+ this.pendingCalls = new Map();
4120
+ this.rxChunks = [];
4121
+ this.rxBytesTotal = 0;
4122
+ this.syncBridge = null;
4123
+ this.lastDaemonSpawnTime = 0;
4124
+ const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP || "";
4125
+ this.sessionHash =
4126
+ process.env.XYPRISS_SESSION_HASH ||
4127
+ (sessionDir ? path.basename(sessionDir) : "");
4128
+ this.authToken =
4129
+ process.env.XYPRISS_INTERNAL_TOKEN ||
4130
+ process.env.XYPRISS_XESS_AUTH_TOKEN ||
4131
+ "";
4132
+ if (!this.authToken && sessionDir) {
4133
+ try {
4134
+ const tokenFile = path.join(sessionDir, ".auth_token");
4135
+ if (fs.existsSync(tokenFile)) {
4136
+ this.authToken = fs.readFileSync(tokenFile, "utf8").trim();
4137
+ }
4138
+ }
4139
+ catch { }
4278
4140
  }
4279
- return _sessionTmpDir;
4280
- }
4281
- // No supervisor session provisioned by libProc: unconfined execution has no valid session
4282
- return "";
4283
- }
4284
- /**
4285
- * Returns the unique 8-character session hash ID for the active server instance.
4286
- * Delegated exclusively to the libProc supervisor (Single Source of Truth).
4287
- */
4288
- function getSessionHash() {
4289
- const sys = getSysApi();
4290
- const envHash = sys?.__env__?.get("XYPRISS_SESSION_HASH") ||
4291
- (typeof process !== "undefined" ? process.env?.XYPRISS_SESSION_HASH : undefined);
4292
- if (envHash && typeof envHash === "string") {
4293
- return envHash;
4141
+ this.socketPath =
4142
+ customSocketPath ||
4143
+ (sessionDir ? path.join(sessionDir, "synapx.sock") : "");
4294
4144
  }
4295
- if (_sessionTmpDir) {
4296
- if (sys?.path) {
4297
- return sys.path.basename(_sessionTmpDir);
4145
+ /**
4146
+ * Singleton instance accessor bound to the active process session.
4147
+ */
4148
+ static getInstance(socketPath) {
4149
+ if (!SynapxClient.instance) {
4150
+ SynapxClient.instance = new SynapxClient(socketPath);
4298
4151
  }
4299
- const parts = _sessionTmpDir.split(/[/\\]/).filter(Boolean);
4300
- return parts[parts.length - 1] || "";
4301
- }
4302
- return "";
4303
- }
4304
- /**
4305
- * Backward-compatibility alias for getSessionHash().
4306
- */
4307
- function getInstanceId() {
4308
- return getSessionHash();
4309
- }
4310
- /**
4311
- * **Scoped libXESS Temp Directory**
4312
- *
4313
- * Scopes libXESS temporary decoys and IPC socket files inside the dedicated
4314
- * session temp directory under `xuser` (`<tmpdir>/nehonix.xypriss.data/xuser/<instanceId>/xess`).
4315
- *
4316
- * @returns {string} Absolute path to instance xess temp directory
4317
- */
4318
- function getXessTempDir() {
4319
- const sys = getSysApi();
4320
- const envXess = sys?.__env__?.get("XESS_TEMP_DIR") ||
4321
- (typeof process !== "undefined" ? process.env?.XESS_TEMP_DIR : undefined);
4322
- if (envXess && typeof envXess === "string") {
4323
- return envXess;
4324
- }
4325
- const sessionDir = generateXUserTmpDir();
4326
- if (!sessionDir) {
4327
- return "";
4328
- }
4329
- const xessDir = sys?.path ? sys.path.join(sessionDir, "xess") : `${sessionDir}/xess`;
4330
- if (sys?.fs && !sys.fs.exist(xessDir)) {
4331
- sys.fs.mkdir(xessDir, { parents: true });
4332
- }
4333
- return xessDir;
4334
- }
4335
-
4336
- /**
4337
- * Checks if a given file path belongs to the deep engine core.
4338
- * These files are skipped during stack analysis to find the user/plugin caller.
4339
- */
4340
- function isEngineCorePath(filePath) {
4341
- if (!filePath)
4342
- return false;
4343
- const normalizedPath = filePath.replace(/\\/g, "/");
4344
- if (normalizedPath.includes("/XyPriss/src/") ||
4345
- normalizedPath.includes("/XyPriss/dist/") ||
4346
- normalizedPath.includes("/node_modules/xypriss/")) {
4347
- return true;
4152
+ return SynapxClient.instance;
4348
4153
  }
4349
- return false;
4350
- }
4351
- /**
4352
- * Checks if a given file path belongs directly to the XyPriss Core Engine
4353
- * or if it comes from an external plugin / user space.
4354
- * This is used for SECURITY authorization.
4355
- */
4356
- function isCoreFrameworkPath(filePath) {
4357
- if (!filePath)
4358
- return false;
4359
- const normalizedPath = filePath.replace(/\\/g, "/");
4360
- // Authorize trusted internal mods within the framework repository
4361
- if (normalizedPath.includes("/XyPriss/mods/"))
4362
- return true;
4363
- // Exclude other plugins even if they contain 'src' or are named 'xypriss-something'
4364
- if (normalizedPath.includes("/mods/"))
4365
- return false;
4366
- // Engine Core is always trusted
4367
- return isEngineCorePath(filePath);
4368
- }
4369
-
4370
- const logger$1 = new QuickLogger("LibXESS");
4371
- // Module-scoped security closures - strictly isolated from globalThis and reflection APIs
4372
- const _secretsCache = new Map();
4373
- let _ephemeralAuthToken = "";
4374
- let _activeSessionKey = "";
4375
- let _isLibxessActive = false;
4376
- // Immediately consume the one-shot token at module evaluation time
4377
- if (typeof process !== "undefined") {
4378
- if (process.env?.LIBXESS_ACTIVE === "1") {
4379
- _isLibxessActive = true;
4380
- }
4381
- if (process.env?.XYPRISS_XESS_SESSION_KEY) {
4382
- _activeSessionKey = process.env.XYPRISS_XESS_SESSION_KEY;
4383
- _isLibxessActive = true;
4384
- }
4385
- if (process.env?.XYPRISS_XESS_AUTH_TOKEN) {
4386
- _ephemeralAuthToken = process.env.XYPRISS_XESS_AUTH_TOKEN;
4387
- _isLibxessActive = true;
4388
- try {
4389
- delete process.env.XYPRISS_XESS_AUTH_TOKEN;
4390
- }
4391
- catch { }
4154
+ getSocketPath() {
4155
+ return this.socketPath;
4392
4156
  }
4393
- }
4394
- const ppidScope = typeof process !== "undefined" && process.ppid ? process.ppid : "sys";
4395
- const SESSION_BRIDGE_KEY = Symbol.for(`__xypriss_session_bridge_${ppidScope}__`);
4396
- function getSessionBridge() {
4397
- const g = globalThis;
4398
- if (!g[SESSION_BRIDGE_KEY]) {
4399
- let bridgeSessionKey = "";
4400
- let bridgeCache = new Map();
4401
- const bridge = {
4402
- getSessionKey: () => {
4403
- assertInternalCaller();
4404
- return bridgeSessionKey;
4405
- },
4406
- getSecretsCache: () => {
4407
- assertInternalCaller();
4408
- return bridgeCache;
4409
- },
4410
- registerSession: (key, cache) => {
4411
- assertInternalCaller();
4412
- if (key) {
4413
- bridgeSessionKey = key;
4414
- }
4415
- if (cache) {
4416
- bridgeCache = cache;
4417
- }
4418
- },
4419
- };
4157
+ isAvailable() {
4158
+ if (!this.socketPath)
4159
+ return false;
4420
4160
  try {
4421
- Object.defineProperty(g, SESSION_BRIDGE_KEY, {
4422
- value: bridge,
4423
- writable: false,
4424
- enumerable: false,
4425
- configurable: false,
4426
- });
4161
+ return fs.existsSync(this.socketPath);
4427
4162
  }
4428
4163
  catch {
4429
- g[SESSION_BRIDGE_KEY] = bridge;
4164
+ return false;
4430
4165
  }
4431
4166
  }
4432
- return g[SESSION_BRIDGE_KEY];
4433
- }
4434
- /**
4435
- * Asserts that the caller executing this method is directly part of the internal
4436
- * XyPriss engine core. External plugins or untrusted scripts attempting to invoke
4437
- * XessIpcClient are immediately rejected and halted.
4438
- */
4439
- function assertInternalCaller() {
4440
- const stack = new Error().stack || "";
4441
- const lines = stack.split("\n");
4442
- let callerFile = "";
4443
- for (let i = 1; i < lines.length; i++) {
4444
- const line = lines[i];
4445
- if (line.includes("XessIpcClient.") ||
4446
- line.includes("assertInternalCaller") ||
4447
- line.includes("getSessionBridge") ||
4448
- line.includes("registerSession") ||
4449
- line.includes("getSessionKey") ||
4450
- line.includes("getSecretsCache")) {
4451
- continue;
4452
- }
4453
- const match = line.match(/\((.*):\d+:\d+\)$/) ||
4454
- line.match(/at (.*):\d+:\d+$/) ||
4455
- line.match(/at (.*)$/);
4456
- if (match) {
4457
- callerFile = match[1];
4458
- break;
4459
- }
4460
- }
4461
- if (callerFile && !isCoreFrameworkPath(callerFile)) {
4462
- logger$1.error(`[libXESS Security Violation] Direct invocation of XessIpcClient from unauthorized caller '${callerFile}'. Confinement violation: halting process.`);
4463
- process.exit(1);
4464
- }
4465
- }
4466
- /**
4467
- * **XessIpcClient**
4468
- *
4469
- * Client IPC sécurisé pour communiquer avec le superviseur libXESS.
4470
- * Permet de récupérer les secrets authentiques en mémoire RAM via Unix Domain Socket
4471
- * tout en maintenant l'isolation bipolaire (le fichier .env sur disque étant un leurre canary).
4472
- *
4473
- * L'adresse du socket IPC est résolue de manière déterministe hors process.env
4474
- * à partir de l'empreinte cryptographique XSec de la racine du projet.
4475
- */
4476
- class XessIpcClient {
4477
- static get secretsCache() {
4478
- try {
4479
- const bridge = getSessionBridge();
4480
- const cache = bridge.getSecretsCache();
4481
- if (cache) {
4482
- return cache;
4483
- }
4484
- }
4485
- catch { }
4486
- return _secretsCache;
4167
+ resolveBinary() {
4168
+ const envPath = Discovery.getFromEnv("XYPRISS_XHSC_PATH");
4169
+ if (envPath)
4170
+ return envPath;
4171
+ const osPart = Platform.getOsPart();
4172
+ const archPart = Platform.getArchPart();
4173
+ const suffix = Platform.getBinarySuffix();
4174
+ const goBinName = `xhsc-${osPart}-${archPart}${suffix}`;
4175
+ const genericBinName = osPart === "windows" ? "xhsc.exe" : "xhsc";
4176
+ const candidates = [goBinName, genericBinName];
4177
+ const searchBases = [];
4178
+ const scriptDir = Discovery.getScriptDir();
4179
+ if (scriptDir)
4180
+ searchBases.push(scriptDir);
4181
+ searchBases.push(process.cwd());
4182
+ const resolved = Discovery.resolveBinary(candidates, searchBases);
4183
+ if (resolved)
4184
+ return resolved;
4185
+ return genericBinName;
4487
4186
  }
4488
4187
  /**
4489
- * Calcule la liste des emplacements potentiels du socket IPC libXESS pour un répertoire donné.
4490
- * Privilégie le dossier dédié scoped dans xuser/ tout en conservant les fallbacks.
4188
+ * Ensures the confined xhsc background daemon is spawned inside the libXESS sandbox
4189
+ * if the IPC socket is not yet accessible.
4491
4190
  */
4492
- static getSocketCandidatesForDir(dir) {
4493
- const hash = Cipher.hash
4494
- .create(path.resolve(dir), { algorithm: "sha256" })
4495
- .toString("hex")
4496
- .slice(0, 12);
4497
- const fileName = `xess_ipc_${hash}.sock`;
4498
- const candidates = [];
4499
- // Emplacement unique scoped sous la session courante fournie par libproc
4500
- try {
4501
- const xessDir = getXessTempDir();
4502
- if (xessDir) {
4503
- candidates.push(path.join(xessDir, fileName));
4504
- }
4191
+ ensureDaemon() {
4192
+ if (this.isAvailable()) {
4193
+ return;
4505
4194
  }
4506
- catch { }
4507
- try {
4508
- const sessionDir = generateXUserTmpDir();
4509
- if (sessionDir) {
4510
- candidates.push(path.join(sessionDir, "xess", fileName));
4511
- candidates.push(path.join(sessionDir, fileName));
4512
- }
4195
+ const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP;
4196
+ if (!sessionDir) {
4197
+ return;
4513
4198
  }
4514
- catch { }
4515
- return candidates;
4516
- }
4517
- /**
4518
- * Liste ordonnée de tous les chemins de sockets candidats potentiels :
4519
- * 1. process.cwd() (dossier d'exécution du CLI xfpm / superviseur libXESS)
4520
- * 2. projectDir (dossier du projet ou plugin ciblé)
4521
- * 3. Répertoires parents ascendants
4522
- */
4523
- static getCandidateSocketPaths(projectDir) {
4524
- const candidates = [];
4525
- const seen = new Set();
4526
- const addDirHierarchy = (dir) => {
4527
- let current = path.resolve(dir);
4528
- while (current && !seen.has(current)) {
4529
- seen.add(current);
4530
- const candidatesForDir = XessIpcClient.getSocketCandidatesForDir(current);
4531
- for (const candidate of candidatesForDir) {
4532
- if (fs.existsSync(candidate) && !candidates.includes(candidate)) {
4533
- candidates.push(candidate);
4534
- }
4535
- }
4536
- const parent = path.dirname(current);
4537
- if (parent === current)
4538
- break;
4539
- current = parent;
4540
- }
4541
- };
4542
- // 2. Dossier de travail courant (process.cwd()) où xfpm ancre son superviseur
4543
- if (typeof process !== "undefined" && process.cwd) {
4544
- addDirHierarchy(process.cwd());
4199
+ if (Date.now() - this.lastDaemonSpawnTime < 3000) {
4200
+ return;
4545
4201
  }
4546
- // 3. Dossier de projet spécifique si différent
4547
- if (projectDir) {
4548
- addDirHierarchy(projectDir);
4202
+ this.lastDaemonSpawnTime = Date.now();
4203
+ const binPath = this.resolveBinary();
4204
+ if (!binPath) {
4205
+ return;
4549
4206
  }
4550
- // 4. Sockets provisionnés directement dans le xessDir de cette session supervisée
4207
+ const internalSig = getInternalSignature();
4551
4208
  try {
4552
- const xessDir = getXessTempDir();
4553
- if (xessDir && fs.existsSync(xessDir)) {
4554
- const files = fs.readdirSync(xessDir);
4555
- for (const f of files) {
4556
- if (f.startsWith("xess_ipc_") && f.endsWith(".sock")) {
4557
- const sock = path.join(xessDir, f);
4558
- if (!candidates.includes(sock)) {
4559
- candidates.push(sock);
4560
- }
4561
- }
4209
+ const child = spawn(binPath, ["daemon", process.cwd()], {
4210
+ detached: true,
4211
+ stdio: "inherit",
4212
+ env: {
4213
+ ...process.env,
4214
+ ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
4215
+ NO_COLOR: "1",
4216
+ },
4217
+ });
4218
+ let childExited = false;
4219
+ child.on("exit", () => {
4220
+ childExited = true;
4221
+ });
4222
+ child.on("error", () => {
4223
+ childExited = true;
4224
+ });
4225
+ child.unref();
4226
+ // Wait for socket to appear (up to 1500ms)
4227
+ const start = Date.now();
4228
+ while (Date.now() - start < 1500) {
4229
+ if (this.isAvailable() || childExited) {
4230
+ break;
4231
+ }
4232
+ try {
4233
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
4234
+ }
4235
+ catch {
4236
+ const t = Date.now() + 20;
4237
+ while (Date.now() < t) { }
4562
4238
  }
4563
4239
  }
4564
4240
  }
4565
- catch { }
4566
- return candidates;
4567
- }
4568
- /**
4569
- * Effectue une vérification synchrone de liveness sur un socket IPC.
4570
- * Si le fichier socket existe sur le disque mais que le superviseur est mort (ECONNREFUSED / timeout),
4571
- * le socket fantôme est immédiatement purgé du disque et la fonction retourne false.
4572
- */
4573
- static probeSocketSync(socketPath) {
4574
- if (!fs.existsSync(socketPath))
4575
- return false;
4576
- // Fast-path: When running under active libXESS supervisor, socket presence confirms shielding
4577
- if (_isLibxessActive ||
4578
- process.env?.LIBXESS_ACTIVE === "1" ||
4579
- process.env?.XYPRISS_USER_TMP ||
4580
- process.env?.XESS_TEMP_DIR) {
4581
- return true;
4582
- }
4583
- const script = `
4584
- const net = require("net");
4585
- const sock = process.argv[1];
4586
- const client = net.createConnection(sock, () => {
4587
- client.end();
4588
- process.exit(0);
4589
- });
4590
- client.on("error", () => process.exit(1));
4591
- setTimeout(() => process.exit(1), 1000);
4592
- `;
4593
- try {
4594
- execFileSync(process.execPath, ["-e", script, socketPath], {
4595
- timeout: 1500,
4596
- stdio: "ignore",
4597
- });
4598
- return true;
4599
- }
4600
4241
  catch {
4601
- return false;
4242
+ // Silently allow fallback
4602
4243
  }
4603
4244
  }
4604
4245
  /**
4605
- * Résout déterministement le chemin du socket IPC libXESS actif.
4246
+ * Connects to the libSynapx server and performs the Zero-Trust handshake.
4606
4247
  */
4607
- static resolveSocketPath(projectDir) {
4608
- const candidates = this.getCandidateSocketPaths(projectDir);
4609
- for (const candidate of candidates) {
4610
- if (this.probeSocketSync(candidate)) {
4611
- return candidate;
4612
- }
4248
+ async connect() {
4249
+ if (this.socket && !this.socket.destroyed && this.isHandshakeComplete) {
4250
+ return;
4613
4251
  }
4614
- return undefined;
4615
- }
4616
- /**
4617
- * Vérifie si le runtime tourne sous le confinement actif de libXESS.
4618
- */
4619
- static isShielded(projectDir) {
4620
- const authToken = this.getOrConsumeAuthToken();
4621
- const sessionKey = this.getSessionKey();
4622
- const isActive = typeof process !== "undefined" &&
4623
- (_isLibxessActive ||
4624
- process.env?.LIBXESS_ACTIVE === "1" ||
4625
- !!authToken ||
4626
- !!sessionKey);
4627
- if (!isActive) {
4628
- return false;
4252
+ if (!this.isAvailable()) {
4253
+ this.ensureDaemon();
4629
4254
  }
4630
- const candidates = this.getCandidateSocketPaths(projectDir);
4631
- for (const candidate of candidates) {
4632
- if (this.probeSocketSync(candidate)) {
4633
- return true;
4634
- }
4255
+ if (this.connectingPromise) {
4256
+ return this.connectingPromise;
4635
4257
  }
4636
- return false;
4258
+ this.connectingPromise = new Promise((resolve, reject) => {
4259
+ if (!this.socketPath) {
4260
+ return reject(new Error("libSynapx: No active session socket path configured (XYPRISS_USER_TMP is unset)"));
4261
+ }
4262
+ const client = net.createConnection(this.socketPath, () => {
4263
+ this.socket = client;
4264
+ this.performHandshake()
4265
+ .then(() => {
4266
+ this.isHandshakeComplete = true;
4267
+ resolve();
4268
+ })
4269
+ .catch((err) => {
4270
+ this.destroy();
4271
+ reject(err);
4272
+ });
4273
+ });
4274
+ client.on("data", (chunk) => this.onData(chunk));
4275
+ client.on("error", (err) => {
4276
+ if (!this.isHandshakeComplete) {
4277
+ reject(err);
4278
+ }
4279
+ this.destroy();
4280
+ });
4281
+ client.on("close", () => {
4282
+ this.destroy();
4283
+ });
4284
+ }).finally(() => {
4285
+ this.connectingPromise = null;
4286
+ });
4287
+ return this.connectingPromise;
4637
4288
  }
4638
4289
  /**
4639
- * Récupère le chemin du socket IPC libXESS.
4290
+ * Writes a framed packet to the socket.
4640
4291
  */
4641
- static getSocketPath(projectDir) {
4642
- return this.resolveSocketPath(projectDir);
4292
+ writeFrame(msgType, payload) {
4293
+ if (!this.socket || this.socket.destroyed) {
4294
+ throw new Error("libSynapx: socket is not connected");
4295
+ }
4296
+ const header = Buffer.alloc(HEADER_SIZE$1);
4297
+ header.writeUInt8(MAGIC_BYTE, 0);
4298
+ header.writeUInt8(msgType, 1);
4299
+ header.writeUInt32BE(payload.length, 2);
4300
+ this.socket.write(Buffer.concat([header, payload]));
4643
4301
  }
4644
4302
  /**
4645
- * Récupère le jeton d'authentification éphémère libXESS et purge immédiatement
4646
- * la variable d'environnement de la mémoire pour empêcher toute réutilisation non autorisée.
4303
+ * Performs initial zero-trust handshake.
4647
4304
  */
4648
- static getOrConsumeAuthToken() {
4649
- if (_ephemeralAuthToken) {
4650
- return _ephemeralAuthToken;
4651
- }
4652
- if (typeof process !== "undefined" && process.env?.XYPRISS_XESS_AUTH_TOKEN) {
4653
- _ephemeralAuthToken = process.env.XYPRISS_XESS_AUTH_TOKEN;
4305
+ async performHandshake() {
4306
+ return new Promise((resolve, reject) => {
4307
+ const timeout = setTimeout(() => {
4308
+ reject(new Error("libSynapx: Handshake timed out"));
4309
+ }, 3000);
4310
+ const hsPayload = Buffer.from(JSON.stringify({
4311
+ sessionHash: this.sessionHash,
4312
+ token: this.authToken,
4313
+ clientPid: process.pid,
4314
+ }));
4315
+ // Temporarily intercept handshake response frame
4316
+ const originalOnData = this.onData;
4317
+ this.onData = (chunk) => {
4318
+ this.pushChunk(chunk);
4319
+ while (true) {
4320
+ const header = this.peekHeader();
4321
+ if (!header)
4322
+ return;
4323
+ if (header.magic !== MAGIC_BYTE) {
4324
+ clearTimeout(timeout);
4325
+ this.onData = originalOnData;
4326
+ return reject(new Error("libSynapx: Invalid magic byte in handshake response"));
4327
+ }
4328
+ if (this.rxBytesTotal < HEADER_SIZE$1 + header.length) {
4329
+ return; // Wait for full frame
4330
+ }
4331
+ this.consumeBytes(HEADER_SIZE$1);
4332
+ const payloadBuf = this.consumeBytes(header.length);
4333
+ clearTimeout(timeout);
4334
+ this.onData = originalOnData;
4335
+ if (header.msgType === MSG_HANDSHAKE_ACK) {
4336
+ try {
4337
+ const ack = JSON.parse(payloadBuf.toString("utf8"));
4338
+ if (ack.auth) {
4339
+ this.sessionKey = ack.sessionKey || "";
4340
+ try {
4341
+ this.socket?.unref();
4342
+ }
4343
+ catch { }
4344
+ return resolve();
4345
+ }
4346
+ return reject(new Error(`libSynapx: Handshake unauthorized: ${ack.err || "unknown"}`));
4347
+ }
4348
+ catch (e) {
4349
+ return reject(e);
4350
+ }
4351
+ }
4352
+ else {
4353
+ return reject(new Error(`libSynapx: Expected HandshakeAck (0x02), received 0x${header.msgType.toString(16)}`));
4354
+ }
4355
+ }
4356
+ };
4654
4357
  try {
4655
- delete process.env.XYPRISS_XESS_AUTH_TOKEN;
4358
+ this.writeFrame(MSG_HANDSHAKE, hsPayload);
4656
4359
  }
4657
- catch { }
4658
- }
4659
- return _ephemeralAuthToken;
4360
+ catch (err) {
4361
+ clearTimeout(timeout);
4362
+ this.onData = originalOnData;
4363
+ reject(err);
4364
+ }
4365
+ });
4660
4366
  }
4661
4367
  /**
4662
- * Exposes the currently active session key for secure propagation to child worker processes.
4368
+ * Processes incoming streamed chunks from the socket.
4663
4369
  */
4664
- static getActiveSessionKey() {
4665
- return this.getSessionKey();
4666
- }
4667
- static getSessionKey() {
4668
- if (_activeSessionKey) {
4669
- return _activeSessionKey;
4670
- }
4671
- if (typeof process !== "undefined" && process.env?.XYPRISS_XESS_SESSION_KEY) {
4672
- _activeSessionKey = process.env.XYPRISS_XESS_SESSION_KEY;
4673
- return _activeSessionKey;
4674
- }
4675
- try {
4676
- const bridge = getSessionBridge();
4677
- const key = bridge.getSessionKey();
4678
- if (key) {
4679
- _activeSessionKey = key;
4680
- return key;
4370
+ onData(chunk) {
4371
+ this.pushChunk(chunk);
4372
+ while (true) {
4373
+ const header = this.peekHeader();
4374
+ if (!header)
4375
+ break;
4376
+ if (header.magic !== MAGIC_BYTE) {
4377
+ this.consumeBytes(1);
4378
+ this.discardUntilMagic();
4379
+ continue;
4380
+ }
4381
+ if (this.rxBytesTotal < HEADER_SIZE$1 + header.length) {
4382
+ break; // Incomplete packet, wait for more data
4681
4383
  }
4384
+ this.consumeBytes(HEADER_SIZE$1);
4385
+ const payloadBuf = this.consumeBytes(header.length);
4386
+ this.dispatchIncomingFrame(header.msgType, payloadBuf);
4682
4387
  }
4683
- catch { }
4684
- return "";
4685
- }
4686
- static setSessionKey(key) {
4687
- _activeSessionKey = key;
4688
- _ephemeralAuthToken = "";
4689
- try {
4690
- const bridge = getSessionBridge();
4691
- bridge.registerSession(key, _secretsCache);
4692
- }
4693
- catch { }
4694
4388
  }
4695
4389
  /**
4696
- * Récupération synchrone des secrets lors du bootstrap initial.
4697
- * Tente les sockets candidats et purge automatiquement les sockets fantômes résiduels.
4390
+ * Routes decoded incoming packets to pending call promises.
4698
4391
  */
4699
- static fetchSecretsSync(projectDirOrSocket) {
4700
- assertInternalCaller();
4701
- let candidates = [];
4702
- if (projectDirOrSocket &&
4703
- (projectDirOrSocket.endsWith(".sock") ||
4704
- (fs.existsSync(projectDirOrSocket) &&
4705
- !fs.statSync(projectDirOrSocket).isDirectory()))) {
4706
- candidates = [projectDirOrSocket];
4707
- }
4708
- else {
4709
- candidates = this.getCandidateSocketPaths(projectDirOrSocket);
4710
- }
4711
- const targetDir = projectDirOrSocket && !projectDirOrSocket.endsWith(".sock")
4712
- ? path.resolve(projectDirOrSocket)
4713
- : "";
4714
- const cacheKey = targetDir || "__root__";
4715
- if (this.secretsCache.has(cacheKey)) {
4716
- return this.secretsCache.get(cacheKey);
4717
- }
4718
- const authToken = this.getOrConsumeAuthToken();
4719
- const sessionKey = this.getSessionKey();
4720
- const isShieldedActive = typeof process !== "undefined" &&
4721
- (_isLibxessActive ||
4722
- process.env?.LIBXESS_ACTIVE === "1" ||
4723
- !!authToken ||
4724
- !!sessionKey);
4725
- if (!isShieldedActive) {
4726
- // Mode sans confinement libXESS (ex: exécution hors xfpm ou sans le flag -l xess)
4727
- const envPath = path.join(targetDir || (typeof process !== "undefined" ? process.cwd() : ""), ".env");
4728
- if (fs.existsSync(envPath)) {
4392
+ dispatchIncomingFrame(msgType, payloadBuf) {
4393
+ switch (msgType) {
4394
+ case MSG_RESPONSE: {
4729
4395
  try {
4730
- const raw = fs.readFileSync(envPath, "utf-8");
4731
- const parsed = {};
4732
- for (const line of raw.split("\n")) {
4733
- const trimmed = line.trim();
4734
- if (!trimmed || trimmed.startsWith("#"))
4735
- continue;
4736
- const eqIdx = trimmed.indexOf("=");
4737
- if (eqIdx !== -1) {
4738
- const k = trimmed.slice(0, eqIdx).trim();
4739
- let v = trimmed.slice(eqIdx + 1).trim();
4740
- if ((v.startsWith('"') && v.endsWith('"')) ||
4741
- (v.startsWith("'") && v.endsWith("'"))) {
4742
- v = v.slice(1, -1);
4743
- }
4744
- parsed[k] = v;
4396
+ const resp = JSON.parse(payloadBuf.toString("utf8"));
4397
+ const pending = this.pendingCalls.get(resp.id);
4398
+ if (pending) {
4399
+ clearTimeout(pending.timeout);
4400
+ this.pendingCalls.delete(resp.id);
4401
+ if (resp.ok) {
4402
+ pending.resolve(resp.data);
4403
+ }
4404
+ else {
4405
+ pending.reject(new Error(resp.err || "libSynapx operation failed"));
4745
4406
  }
4746
4407
  }
4747
- this.secretsCache.set(cacheKey, parsed);
4748
- return parsed;
4749
4408
  }
4750
4409
  catch { }
4410
+ break;
4411
+ }
4412
+ case MSG_PONG:
4413
+ break;
4414
+ case MSG_ERROR: {
4415
+ try {
4416
+ const errObj = JSON.parse(payloadBuf.toString("utf8"));
4417
+ const errMsg = errObj.error || "libSynapx protocol error";
4418
+ for (const [id, pending] of this.pendingCalls.entries()) {
4419
+ clearTimeout(pending.timeout);
4420
+ pending.reject(new Error(errMsg));
4421
+ }
4422
+ this.pendingCalls.clear();
4423
+ }
4424
+ catch { }
4425
+ break;
4751
4426
  }
4752
- return {};
4753
4427
  }
4754
- if (candidates.length === 0) {
4755
- const msg = "[libXESS] No active libXESS Bridge found for project. Direct execution without libXESS confinement is strictly prohibited.";
4756
- logger$1.error(msg);
4757
- process.exit(1);
4428
+ }
4429
+ /**
4430
+ * Executes a multiplexed RPC call over the persistent private channel with full args and options descriptors.
4431
+ */
4432
+ async call(module, action, args = [], opts = {}, timeoutMs = 60000) {
4433
+ await this.connect();
4434
+ const stringArgs = Array.isArray(args)
4435
+ ? args.map((a) => String(a))
4436
+ : [];
4437
+ const id = ++this.seqId;
4438
+ const callPayload = Buffer.from(JSON.stringify({
4439
+ id,
4440
+ mod: module,
4441
+ action,
4442
+ args: stringArgs,
4443
+ opts: opts || {},
4444
+ }));
4445
+ const effectiveTimeout = typeof opts?.timeout === "number" ? opts.timeout : timeoutMs;
4446
+ return new Promise((resolve, reject) => {
4447
+ const timeout = setTimeout(() => {
4448
+ this.pendingCalls.delete(id);
4449
+ reject(new Error(`libSynapx: Call timed out after ${effectiveTimeout}ms [${module}.${action}]`));
4450
+ }, effectiveTimeout);
4451
+ this.pendingCalls.set(id, {
4452
+ resolve,
4453
+ reject,
4454
+ timeout,
4455
+ });
4456
+ try {
4457
+ this.writeFrame(MSG_CALL, callPayload);
4458
+ }
4459
+ catch (err) {
4460
+ clearTimeout(timeout);
4461
+ this.pendingCalls.delete(id);
4462
+ reject(err);
4463
+ }
4464
+ });
4465
+ }
4466
+ /**
4467
+ * Synchronous RPC via ultra-fast SharedArrayBuffer Futex Bridge (Path 1)
4468
+ * with transparent automatic fallback to stdin pipe subprocess on edge platforms.
4469
+ */
4470
+ callSync(module, action, args = [], opts = {}) {
4471
+ if (!this.socketPath || !fs.existsSync(this.socketPath)) {
4472
+ this.ensureDaemon();
4473
+ if (!this.socketPath || !fs.existsSync(this.socketPath)) {
4474
+ throw new Error(`libSynapx: socket '${this.socketPath || "unknown"}' not found or active daemon is offline`);
4475
+ }
4476
+ }
4477
+ try {
4478
+ if (!this.syncBridge) {
4479
+ this.syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.authToken);
4480
+ }
4481
+ return this.syncBridge.callSync(module, action, args, opts);
4482
+ }
4483
+ catch {
4484
+ // Resilient fallback to stdin subprocess pipeline
4485
+ return this.callSyncSubprocess(module, action, args, opts);
4758
4486
  }
4759
- const action = sessionKey ? "GET_PROJECT" : "HANDSHAKE";
4760
- const credential = sessionKey || authToken;
4487
+ }
4488
+ /**
4489
+ * Subprocess-based synchronous fallback pipeline (streaming via stdin to prevent E2BIG).
4490
+ */
4491
+ callSyncSubprocess(module, action, args = [], opts = {}) {
4492
+ const stringArgs = Array.isArray(args)
4493
+ ? args.map((a) => String(a))
4494
+ : [];
4761
4495
  const script = `
4762
4496
  const net = require("net");
4763
4497
  const fs = require("fs");
4764
4498
  const sock = process.argv[1];
4765
- let rawInput = "";
4766
- try {
4767
- rawInput = fs.readFileSync(0, "utf-8");
4768
- } catch (e) {
4769
- process.exit(1);
4770
- }
4771
- let payload;
4499
+ const hash = process.argv[2] || "";
4500
+ const token = process.argv[3] || "";
4501
+
4502
+ let inputData = "";
4772
4503
  try {
4773
- payload = JSON.parse(rawInput);
4774
- } catch (e) {
4775
- process.exit(1);
4776
- }
4504
+ inputData = fs.readFileSync(0, "utf8");
4505
+ } catch {}
4506
+
4507
+ const req = JSON.parse(inputData || "{}");
4508
+ const mod = req.mod;
4509
+ const act = req.action;
4510
+ const args = req.args || [];
4511
+ const opts = req.opts || {};
4512
+
4777
4513
  const client = net.createConnection(sock, () => {
4778
- client.write(JSON.stringify(payload) + "\\n");
4514
+ // 1. Handshake
4515
+ const hs = Buffer.from(JSON.stringify({ sessionHash: hash, token: token, clientPid: process.pid }));
4516
+ const h1 = Buffer.alloc(6);
4517
+ h1.writeUInt8(0x53, 0);
4518
+ h1.writeUInt8(0x01, 1);
4519
+ h1.writeUInt32BE(hs.length, 2);
4520
+ client.write(Buffer.concat([h1, hs]));
4779
4521
  });
4780
- let data = "";
4522
+
4523
+ let buf = Buffer.alloc(0);
4524
+ let handshaked = false;
4525
+
4781
4526
  client.on("data", (chunk) => {
4782
- data += chunk.toString();
4783
- if (data.includes("\\n")) {
4784
- client.end();
4785
- process.stdout.write(data.trim());
4786
- process.exit(0);
4527
+ buf = Buffer.concat([buf, chunk]);
4528
+ while (buf.length >= 6) {
4529
+ if (buf.readUInt8(0) !== 0x53) { process.exit(1); }
4530
+ const type = buf.readUInt8(1);
4531
+ const len = buf.readUInt32BE(2);
4532
+ if (buf.length < 6 + len) return;
4533
+ const payload = buf.subarray(6, 6 + len);
4534
+ buf = buf.subarray(6 + len);
4535
+
4536
+ if (!handshaked) {
4537
+ if (type === 0x02) {
4538
+ handshaked = true;
4539
+ const call = Buffer.from(JSON.stringify({ id: 1, mod: mod, action: act, args: args, opts: opts }));
4540
+ const h2 = Buffer.alloc(6);
4541
+ h2.writeUInt8(0x53, 0);
4542
+ h2.writeUInt8(0x03, 1);
4543
+ h2.writeUInt32BE(call.length, 2);
4544
+ client.write(Buffer.concat([h2, call]));
4545
+ } else { process.exit(1); }
4546
+ } else {
4547
+ if (type === 0x04) {
4548
+ process.stdout.write(payload);
4549
+ client.end();
4550
+ process.exit(0);
4551
+ } else { process.exit(1); }
4552
+ }
4787
4553
  }
4788
4554
  });
4789
- client.on("error", (err) => {
4790
- process.stderr.write(err.message);
4791
- process.exit(1);
4792
- });
4793
- setTimeout(() => { process.exit(1); }, 3000);
4555
+ setTimeout(() => process.exit(1), 5000);
4794
4556
  `;
4795
- const inputPayload = JSON.stringify(action === "HANDSHAKE"
4796
- ? { action: "HANDSHAKE", projectDir: targetDir, token: credential }
4797
- : { action: action, projectDir: targetDir, sessionKey: credential });
4798
- let lastErr;
4799
- for (const sock of candidates) {
4800
- try {
4801
- // Pass sensitive credentials exclusively via private stdin pipe, NEVER in process.argv
4802
- const output = execFileSync(process.execPath, ["-e", script, sock], {
4803
- input: inputPayload,
4804
- encoding: "utf8",
4805
- timeout: 3000,
4806
- stdio: ["pipe", "pipe", "pipe"],
4807
- });
4808
- const parsed = JSON.parse(output.trim());
4809
- if (parsed.action === "UNAUTHORIZED" || parsed.error) {
4810
- const msg = `[libXESS] Authentication rejected: ${parsed.error || "Unauthorized"}. Confinement violation.`;
4811
- logger$1.error(msg);
4812
- process.exit(1);
4813
- }
4814
- if (parsed.sessionKey) {
4815
- this.setSessionKey(parsed.sessionKey);
4816
- }
4817
- if (parsed && parsed.secrets) {
4818
- this.secretsCache.set(cacheKey, parsed.secrets);
4819
- return parsed.secrets;
4820
- }
4821
- }
4822
- catch (err) {
4823
- lastErr = err;
4824
- }
4557
+ const inputPayload = JSON.stringify({
4558
+ mod: module,
4559
+ action,
4560
+ args: stringArgs,
4561
+ opts: opts || {},
4562
+ });
4563
+ const output = execFileSync(process.execPath, [
4564
+ "-e",
4565
+ script,
4566
+ this.socketPath,
4567
+ this.sessionHash,
4568
+ this.authToken,
4569
+ ], {
4570
+ input: inputPayload,
4571
+ encoding: "utf8",
4572
+ timeout: 5000,
4573
+ maxBuffer: 100 * 1024 * 1024,
4574
+ stdio: ["pipe", "pipe", "pipe"],
4575
+ });
4576
+ const parsed = JSON.parse(output.trim());
4577
+ if (!parsed.ok) {
4578
+ throw new Error(parsed.err || "libSynapx call failed");
4825
4579
  }
4826
- const msg = `[libXESS] Failed to fetch secrets from libXESS: ${lastErr?.message || "unknown error"}. Confinement violation: halting execution.`;
4827
- logger$1.error(msg);
4828
- process.exit(1);
4580
+ return parsed.data;
4829
4581
  }
4830
- /**
4831
- * Récupération asynchrone des secrets via net.Socket natif.
4832
- */
4833
- static async fetchSecretsAsync(projectDirOrSocket) {
4834
- assertInternalCaller();
4835
- let candidates = [];
4836
- if (projectDirOrSocket &&
4837
- (projectDirOrSocket.endsWith(".sock") ||
4838
- (fs.existsSync(projectDirOrSocket) &&
4839
- !fs.statSync(projectDirOrSocket).isDirectory()))) {
4840
- candidates = [projectDirOrSocket];
4841
- }
4842
- else {
4843
- candidates = this.getCandidateSocketPaths(projectDirOrSocket);
4844
- }
4845
- const targetDir = projectDirOrSocket && !projectDirOrSocket.endsWith(".sock")
4846
- ? path.resolve(projectDirOrSocket)
4847
- : "";
4848
- const cacheKey = targetDir || "__root__";
4849
- if (this.secretsCache.has(cacheKey)) {
4850
- return this.secretsCache.get(cacheKey);
4851
- }
4852
- const authToken = this.getOrConsumeAuthToken();
4853
- const sessionKey = this.getSessionKey();
4854
- const isShieldedActive = typeof process !== "undefined" &&
4855
- (_isLibxessActive ||
4856
- process.env?.LIBXESS_ACTIVE === "1" ||
4857
- !!authToken ||
4858
- !!sessionKey);
4859
- if (!isShieldedActive) {
4860
- const envPath = path.join(targetDir || (typeof process !== "undefined" ? process.cwd() : ""), ".env");
4861
- if (fs.existsSync(envPath)) {
4862
- try {
4863
- const raw = fs.readFileSync(envPath, "utf-8");
4864
- const parsed = {};
4865
- for (const line of raw.split("\n")) {
4866
- const trimmed = line.trim();
4867
- if (!trimmed || trimmed.startsWith("#"))
4868
- continue;
4869
- const eqIdx = trimmed.indexOf("=");
4870
- if (eqIdx !== -1) {
4871
- const k = trimmed.slice(0, eqIdx).trim();
4872
- let v = trimmed.slice(eqIdx + 1).trim();
4873
- if ((v.startsWith('"') && v.endsWith('"')) ||
4874
- (v.startsWith("'") && v.endsWith("'"))) {
4875
- v = v.slice(1, -1);
4876
- }
4877
- parsed[k] = v;
4878
- }
4879
- }
4880
- this.secretsCache.set(cacheKey, parsed);
4881
- return parsed;
4882
- }
4883
- catch { }
4884
- }
4885
- return {};
4582
+ destroy() {
4583
+ this.isHandshakeComplete = false;
4584
+ if (this.syncBridge) {
4585
+ this.syncBridge.destroy();
4586
+ this.syncBridge = null;
4886
4587
  }
4887
- if (candidates.length === 0) {
4888
- const msg = "[libXESS] No active libXESS Bridge found for project. Direct execution without libXESS confinement is strictly prohibited.";
4889
- logger$1.error(msg);
4890
- process.exit(1);
4588
+ if (this.socket) {
4589
+ this.socket.removeAllListeners();
4590
+ this.socket.destroy();
4591
+ this.socket = null;
4891
4592
  }
4892
- const action = sessionKey ? "GET_PROJECT" : "HANDSHAKE";
4893
- const credential = sessionKey || authToken;
4894
- let lastErr;
4895
- for (const sock of candidates) {
4896
- try {
4897
- const secrets = await new Promise((resolve, reject) => {
4898
- const client = net.createConnection(sock, () => {
4899
- const payload = action === "HANDSHAKE"
4900
- ? { action: "HANDSHAKE", projectDir: targetDir, token: credential }
4901
- : { action: action, projectDir: targetDir, sessionKey: credential };
4902
- client.write(JSON.stringify(payload) + "\n");
4903
- });
4904
- let buffer = "";
4905
- const timeout = setTimeout(() => {
4906
- client.destroy();
4907
- reject(new Error("Socket timeout"));
4908
- }, 3000);
4909
- client.on("data", (chunk) => {
4910
- buffer += chunk.toString();
4911
- if (buffer.includes("\n")) {
4912
- clearTimeout(timeout);
4913
- client.end();
4914
- try {
4915
- const parsed = JSON.parse(buffer.trim());
4916
- if (parsed.action === "UNAUTHORIZED" || parsed.error) {
4917
- logger$1.error(`[libXESS] Authentication rejected: ${parsed.error || "Unauthorized"}`);
4918
- process.exit(1);
4919
- }
4920
- if (parsed.sessionKey) {
4921
- this.setSessionKey(parsed.sessionKey);
4922
- }
4923
- const sec = parsed.secrets || {};
4924
- this.secretsCache.set(cacheKey, sec);
4925
- resolve(sec);
4926
- }
4927
- catch (e) {
4928
- resolve({});
4929
- }
4930
- }
4931
- });
4932
- client.on("error", (err) => {
4933
- clearTimeout(timeout);
4934
- client.destroy();
4935
- reject(err);
4936
- });
4937
- });
4938
- return secrets;
4939
- }
4940
- catch (err) {
4941
- lastErr = err;
4942
- }
4593
+ for (const [id, pending] of this.pendingCalls.entries()) {
4594
+ clearTimeout(pending.timeout);
4595
+ pending.reject(new Error("libSynapx: socket disconnected"));
4943
4596
  }
4944
- const msg = `[libXESS] Failed to fetch secrets from libXESS: ${lastErr?.message || "unknown error"}. Confinement violation: halting execution.`;
4945
- logger$1.error(msg);
4946
- process.exit(1);
4597
+ this.pendingCalls.clear();
4598
+ this.rxChunks = [];
4599
+ this.rxBytesTotal = 0;
4947
4600
  }
4948
4601
  }
4602
+ SynapxClient.instance = null;
4949
4603
 
4950
- /* *****************************************************************************
4951
- * Nehonix libSynapx — TypeScript Client
4952
- *
4953
- * High-performance, persistent Zero-Trust IPC client connecting XyPriss
4954
- * to the Go libSynapx engine over isolated Unix Domain Sockets / Named Pipes.
4955
- ***************************************************************************** */
4956
- // Protocol Constants (matching libSynapx Go wire format)
4957
- const MAGIC_BYTE = 0x53; // 'S'
4958
- const MSG_HANDSHAKE = 0x01;
4959
- const MSG_HANDSHAKE_ACK = 0x02;
4960
- const MSG_CALL = 0x03;
4961
- const MSG_RESPONSE = 0x04;
4962
- const MSG_PONG = 0x08;
4963
- const MSG_ERROR = 0xff;
4964
- const HEADER_SIZE$1 = 6;
4965
4604
  /**
4966
- * **SynapxClient**
4967
- *
4968
- * Persistent, multiplexed IPC client connecting TypeScript to the Go libSynapx core.
4605
+ * Custom error class for XyPriss system operations.
4969
4606
  */
4970
- class SynapxClient {
4971
- /**
4972
- * Appends a newly received socket chunk to the internal accumulator.
4973
- */
4974
- pushChunk(chunk) {
4975
- this.rxChunks.push(chunk);
4976
- this.rxBytesTotal += chunk.length;
4977
- }
4978
- /**
4979
- * Peeks at the framing header without mutating or eagerly concatenating the chunk buffer.
4980
- */
4981
- peekHeader() {
4982
- if (this.rxBytesTotal < HEADER_SIZE$1)
4983
- return null;
4984
- const first = this.rxChunks[0];
4985
- if (first.length >= HEADER_SIZE$1) {
4986
- return {
4987
- magic: first.readUInt8(0),
4988
- msgType: first.readUInt8(1),
4989
- length: first.readUInt32BE(2),
4990
- };
4991
- }
4992
- const hdr = Buffer.allocUnsafe(HEADER_SIZE$1);
4993
- let copied = 0;
4994
- for (const chunk of this.rxChunks) {
4995
- const toCopy = Math.min(chunk.length, HEADER_SIZE$1 - copied);
4996
- chunk.copy(hdr, copied, 0, toCopy);
4997
- copied += toCopy;
4998
- if (copied >= HEADER_SIZE$1)
4999
- break;
5000
- }
5001
- return {
5002
- magic: hdr.readUInt8(0),
5003
- msgType: hdr.readUInt8(1),
5004
- length: hdr.readUInt32BE(2),
5005
- };
4607
+ class XyPrissError extends Error {
4608
+ constructor(module, action, details, raw) {
4609
+ super(`[XyPriss Error] ${module}.${action} failed: ${details}`);
4610
+ this.module = module;
4611
+ this.action = action;
4612
+ this.details = details;
4613
+ this.raw = raw;
4614
+ this.name = "XyPrissError";
5006
4615
  }
5007
- /**
5008
- * Consumes exactly numBytes from the front of the chunk list in a single fast copy.
5009
- */
5010
- consumeBytes(numBytes) {
5011
- if (numBytes === 0)
5012
- return Buffer.alloc(0);
5013
- if (this.rxChunks.length === 1 && this.rxChunks[0].length === numBytes) {
5014
- const buf = this.rxChunks[0];
5015
- this.rxChunks = [];
5016
- this.rxBytesTotal = 0;
5017
- return buf;
5018
- }
5019
- const result = Buffer.allocUnsafe(numBytes);
5020
- let offset = 0;
5021
- while (this.rxChunks.length > 0 && offset < numBytes) {
5022
- const head = this.rxChunks[0];
5023
- const needed = numBytes - offset;
5024
- if (head.length <= needed) {
5025
- head.copy(result, offset);
5026
- offset += head.length;
5027
- this.rxChunks.shift();
5028
- }
5029
- else {
5030
- head.copy(result, offset, 0, needed);
5031
- offset += needed;
5032
- this.rxChunks[0] = head.subarray(needed);
5033
- }
5034
- }
5035
- this.rxBytesTotal -= numBytes;
5036
- return result;
4616
+ }
4617
+ /**
4618
+ * **Native System Runner**
4619
+ *
4620
+ * This class serves as the core bridge between the Node.js runtime and the
4621
+ * high-performance system core. It manages process spawning, argument
4622
+ * serialization, and bidirectional streaming.
4623
+ */
4624
+ class XyPrissRunner {
4625
+ constructor(root) {
4626
+ this.root = root;
4627
+ this.binaryPath = this.discoverBinary();
4628
+ // console.log(
4629
+ // "[XyPrissRunner:getBinaryPath] Binary path: ",
4630
+ // this.discoverBinary(),
4631
+ // );
5037
4632
  }
5038
- /**
5039
- * Resynchronizes stream by advancing past corrupt bytes to the next magic byte.
5040
- */
5041
- discardUntilMagic() {
5042
- while (this.rxChunks.length > 0) {
5043
- const head = this.rxChunks[0];
5044
- const idx = head.indexOf(MAGIC_BYTE);
5045
- if (idx !== -1) {
5046
- if (idx > 0) {
5047
- this.consumeBytes(idx);
5048
- }
5049
- return true;
5050
- }
5051
- else {
5052
- this.rxBytesTotal -= head.length;
5053
- this.rxChunks.shift();
5054
- }
5055
- }
5056
- return false;
4633
+ getRoot() {
4634
+ // console.log("[XyPrissRunner:getRoot] Binary root: ", this.root);
4635
+ return this.root;
5057
4636
  }
5058
- constructor(customSocketPath) {
5059
- this.socket = null;
5060
- this.connectingPromise = null;
5061
- this.isHandshakeComplete = false;
5062
- this.sessionKey = "";
5063
- this.seqId = 0;
5064
- this.pendingCalls = new Map();
5065
- this.rxChunks = [];
5066
- this.rxBytesTotal = 0;
5067
- this.syncBridge = null;
5068
- this.lastDaemonSpawnTime = 0;
5069
- const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP || "";
5070
- this.sessionHash =
5071
- process.env.XYPRISS_SESSION_HASH ||
5072
- (sessionDir ? path.basename(sessionDir) : "");
5073
- this.authToken =
5074
- process.env.XYPRISS_INTERNAL_TOKEN ||
5075
- process.env.XYPRISS_XESS_AUTH_TOKEN ||
5076
- "";
5077
- this.socketPath =
5078
- customSocketPath ||
5079
- (sessionDir ? path.join(sessionDir, "synapx.sock") : "");
4637
+ getBinaryPath() {
4638
+ return this.binaryPath;
5080
4639
  }
5081
4640
  /**
5082
- * Singleton instance accessor bound to the active process session.
4641
+ * Strategic discovery of the XyPriss System binary.
4642
+ * Prioritizes the high-performance Go implementation (XHSC-GO).
5083
4643
  */
5084
- static getInstance(socketPath) {
5085
- if (!SynapxClient.instance) {
5086
- SynapxClient.instance = new SynapxClient(socketPath);
5087
- }
5088
- return SynapxClient.instance;
5089
- }
5090
- getSocketPath() {
5091
- return this.socketPath;
5092
- }
5093
- isAvailable() {
5094
- if (!this.socketPath)
5095
- return false;
5096
- try {
5097
- return fs.existsSync(this.socketPath);
5098
- }
5099
- catch {
5100
- return false;
5101
- }
5102
- }
5103
- resolveBinary() {
4644
+ discoverBinary() {
4645
+ // 1. Environment Variable Override (Highest Priority)
5104
4646
  const envPath = Discovery.getFromEnv("XYPRISS_XHSC_PATH");
5105
4647
  if (envPath)
5106
4648
  return envPath;
5107
4649
  const osPart = Platform.getOsPart();
5108
4650
  const archPart = Platform.getArchPart();
5109
4651
  const suffix = Platform.getBinarySuffix();
4652
+ // Candidate names in order of preference
5110
4653
  const goBinName = `xhsc-${osPart}-${archPart}${suffix}`;
5111
4654
  const genericBinName = osPart === "windows" ? "xhsc.exe" : "xhsc";
5112
4655
  const candidates = [goBinName, genericBinName];
5113
4656
  const searchBases = [];
4657
+ // 2. Add Script Directory (where the library is located)
5114
4658
  const scriptDir = Discovery.getScriptDir();
5115
4659
  if (scriptDir)
5116
4660
  searchBases.push(scriptDir);
4661
+ // 3. Add Current Working Directory
5117
4662
  searchBases.push(process.cwd());
4663
+ // Perform recursive search from all bases using Discovery engine
5118
4664
  const resolved = Discovery.resolveBinary(candidates, searchBases);
5119
4665
  if (resolved)
5120
4666
  return resolved;
4667
+ // Final fallback (generic name which might be in PATH via system spawn)
5121
4668
  return genericBinName;
5122
4669
  }
5123
4670
  /**
5124
- * Ensures the confined xhsc background daemon is spawned inside the libXESS sandbox
5125
- * if the IPC socket is not yet accessible.
4671
+ * Executes a command synchronously and returns the parsed JSON result.
4672
+ * Standardizes all responses into a Promise-like data structure.
5126
4673
  */
5127
- ensureDaemon() {
5128
- if (this.isAvailable()) {
5129
- return;
5130
- }
5131
- const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP;
5132
- if (!sessionDir) {
5133
- return;
5134
- }
5135
- if (Date.now() - this.lastDaemonSpawnTime < 3000) {
5136
- return;
5137
- }
5138
- this.lastDaemonSpawnTime = Date.now();
5139
- const binPath = this.resolveBinary();
5140
- if (!binPath) {
5141
- return;
5142
- }
5143
- const internalSig = getInternalSignature();
5144
- let sessionKey = "";
5145
- try {
5146
- sessionKey = XessIpcClient.getActiveSessionKey();
5147
- }
5148
- catch { }
4674
+ /**
4675
+ * Executes a command synchronously via libSynapx IPC and returns the parsed result.
4676
+ */
4677
+ runSync(module, action, args = [], options = {}) {
5149
4678
  try {
5150
- const child = spawn(binPath, ["daemon", process.cwd()], {
5151
- detached: true,
5152
- stdio: "inherit",
5153
- env: {
5154
- ...process.env,
5155
- ...(sessionKey ? { XYPRISS_XESS_SESSION_KEY: sessionKey } : {}),
5156
- ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5157
- NO_COLOR: "1",
5158
- },
5159
- });
5160
- let childExited = false;
5161
- child.on("exit", () => {
5162
- childExited = true;
5163
- });
5164
- child.on("error", () => {
5165
- childExited = true;
5166
- });
5167
- child.unref();
5168
- // Wait for socket to appear (up to 1500ms)
5169
- const start = Date.now();
5170
- while (Date.now() - start < 1500) {
5171
- if (this.isAvailable() || childExited) {
5172
- break;
5173
- }
5174
- try {
5175
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
5176
- }
5177
- catch {
5178
- const t = Date.now() + 20;
5179
- while (Date.now() < t) { }
5180
- }
5181
- }
4679
+ const synapx = SynapxClient.getInstance();
4680
+ return synapx.callSync(module, action, args, options);
5182
4681
  }
5183
- catch {
5184
- // Silently allow fallback
4682
+ catch (error) {
4683
+ if (error instanceof XyPrissError)
4684
+ throw error;
4685
+ throw new XyPrissError(module, action, error.message || String(error), error);
5185
4686
  }
5186
4687
  }
5187
4688
  /**
5188
- * Connects to the libSynapx server and performs the Zero-Trust handshake.
4689
+ * Executes a command asynchronously via libSynapx IPC and returns the parsed result.
5189
4690
  */
5190
- async connect() {
5191
- if (this.socket && !this.socket.destroyed && this.isHandshakeComplete) {
5192
- return;
4691
+ async runAsync(module, action, args = [], options = {}) {
4692
+ try {
4693
+ const synapx = SynapxClient.getInstance();
4694
+ return await synapx.call(module, action, args, options);
5193
4695
  }
5194
- if (!this.isAvailable()) {
5195
- this.ensureDaemon();
4696
+ catch (error) {
4697
+ if (error instanceof XyPrissError)
4698
+ throw error;
4699
+ throw new XyPrissError(module, action, error.message || String(error), error);
5196
4700
  }
5197
- if (this.connectingPromise) {
5198
- return this.connectingPromise;
5199
- }
5200
- this.connectingPromise = new Promise((resolve, reject) => {
5201
- if (!this.socketPath) {
5202
- return reject(new Error("libSynapx: No active session socket path configured (XYPRISS_USER_TMP is unset)"));
5203
- }
5204
- const client = net.createConnection(this.socketPath, () => {
5205
- this.socket = client;
5206
- this.performHandshake()
5207
- .then(() => {
5208
- this.isHandshakeComplete = true;
5209
- resolve();
5210
- })
5211
- .catch((err) => {
5212
- this.destroy();
5213
- reject(err);
5214
- });
5215
- });
5216
- client.on("data", (chunk) => this.onData(chunk));
5217
- client.on("error", (err) => {
5218
- if (!this.isHandshakeComplete) {
5219
- reject(err);
5220
- }
5221
- this.destroy();
5222
- });
5223
- client.on("close", () => {
5224
- this.destroy();
5225
- });
5226
- }).finally(() => {
5227
- this.connectingPromise = null;
5228
- });
5229
- return this.connectingPromise;
5230
- }
5231
- /**
5232
- * Writes a framed packet to the socket.
5233
- */
5234
- writeFrame(msgType, payload) {
5235
- if (!this.socket || this.socket.destroyed) {
5236
- throw new Error("libSynapx: socket is not connected");
5237
- }
5238
- const header = Buffer.alloc(HEADER_SIZE$1);
5239
- header.writeUInt8(MAGIC_BYTE, 0);
5240
- header.writeUInt8(msgType, 1);
5241
- header.writeUInt32BE(payload.length, 2);
5242
- this.socket.write(Buffer.concat([header, payload]));
5243
- }
5244
- /**
5245
- * Performs initial zero-trust handshake.
5246
- */
5247
- async performHandshake() {
5248
- return new Promise((resolve, reject) => {
5249
- const timeout = setTimeout(() => {
5250
- reject(new Error("libSynapx: Handshake timed out"));
5251
- }, 3000);
5252
- const hsPayload = Buffer.from(JSON.stringify({
5253
- sessionHash: this.sessionHash,
5254
- token: this.authToken,
5255
- clientPid: process.pid,
5256
- }));
5257
- // Temporarily intercept handshake response frame
5258
- const originalOnData = this.onData;
5259
- this.onData = (chunk) => {
5260
- this.pushChunk(chunk);
5261
- while (true) {
5262
- const header = this.peekHeader();
5263
- if (!header)
5264
- return;
5265
- if (header.magic !== MAGIC_BYTE) {
5266
- clearTimeout(timeout);
5267
- this.onData = originalOnData;
5268
- return reject(new Error("libSynapx: Invalid magic byte in handshake response"));
5269
- }
5270
- if (this.rxBytesTotal < HEADER_SIZE$1 + header.length) {
5271
- return; // Wait for full frame
5272
- }
5273
- this.consumeBytes(HEADER_SIZE$1);
5274
- const payloadBuf = this.consumeBytes(header.length);
5275
- clearTimeout(timeout);
5276
- this.onData = originalOnData;
5277
- if (header.msgType === MSG_HANDSHAKE_ACK) {
5278
- try {
5279
- const ack = JSON.parse(payloadBuf.toString("utf8"));
5280
- if (ack.auth) {
5281
- this.sessionKey = ack.sessionKey || "";
5282
- try {
5283
- this.socket?.unref();
5284
- }
5285
- catch { }
5286
- return resolve();
5287
- }
5288
- return reject(new Error(`libSynapx: Handshake unauthorized: ${ack.err || "unknown"}`));
5289
- }
5290
- catch (e) {
5291
- return reject(e);
5292
- }
5293
- }
5294
- else {
5295
- return reject(new Error(`libSynapx: Expected HandshakeAck (0x02), received 0x${header.msgType.toString(16)}`));
5296
- }
5297
- }
5298
- };
5299
- try {
5300
- this.writeFrame(MSG_HANDSHAKE, hsPayload);
5301
- }
5302
- catch (err) {
5303
- clearTimeout(timeout);
5304
- this.onData = originalOnData;
5305
- reject(err);
5306
- }
5307
- });
5308
4701
  }
5309
4702
  /**
5310
- * Processes incoming streamed chunks from the socket.
4703
+ * Run a module action and return the stdout as a Readable stream
5311
4704
  */
5312
- onData(chunk) {
5313
- this.pushChunk(chunk);
5314
- while (true) {
5315
- const header = this.peekHeader();
5316
- if (!header)
5317
- break;
5318
- if (header.magic !== MAGIC_BYTE) {
5319
- this.consumeBytes(1);
5320
- this.discardUntilMagic();
4705
+ runStream(module, action, args = [], options = {}) {
4706
+ const internalSig = getInternalSignature();
4707
+ const cmdArgs = [
4708
+ "--root",
4709
+ this.root,
4710
+ module,
4711
+ action,
4712
+ ...args,
4713
+ ];
4714
+ for (const [key, value] of Object.entries(options)) {
4715
+ if (["input"].includes(key))
5321
4716
  continue;
4717
+ const flag = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
4718
+ if (value === true)
4719
+ cmdArgs.push(`--${flag}`);
4720
+ else if (value !== false && value !== undefined) {
4721
+ cmdArgs.push(`--${flag}`, String(value));
5322
4722
  }
5323
- if (this.rxBytesTotal < HEADER_SIZE$1 + header.length) {
5324
- break; // Incomplete packet, wait for more data
5325
- }
5326
- this.consumeBytes(HEADER_SIZE$1);
5327
- const payloadBuf = this.consumeBytes(header.length);
5328
- this.dispatchIncomingFrame(header.msgType, payloadBuf);
5329
4723
  }
5330
- }
5331
- /**
5332
- * Routes decoded incoming packets to pending call promises.
5333
- */
5334
- dispatchIncomingFrame(msgType, payloadBuf) {
5335
- switch (msgType) {
5336
- case MSG_RESPONSE: {
5337
- try {
5338
- const resp = JSON.parse(payloadBuf.toString("utf8"));
5339
- const pending = this.pendingCalls.get(resp.id);
5340
- if (pending) {
5341
- clearTimeout(pending.timeout);
5342
- this.pendingCalls.delete(resp.id);
5343
- if (resp.ok) {
5344
- pending.resolve(resp.data);
5345
- }
5346
- else {
5347
- pending.reject(new Error(resp.err || "libSynapx operation failed"));
5348
- }
5349
- }
5350
- }
5351
- catch { }
5352
- break;
5353
- }
5354
- case MSG_PONG:
5355
- break;
5356
- case MSG_ERROR: {
5357
- try {
5358
- const errObj = JSON.parse(payloadBuf.toString("utf8"));
5359
- const errMsg = errObj.error || "libSynapx protocol error";
5360
- for (const [id, pending] of this.pendingCalls.entries()) {
5361
- clearTimeout(pending.timeout);
5362
- pending.reject(new Error(errMsg));
5363
- }
5364
- this.pendingCalls.clear();
5365
- }
5366
- catch { }
5367
- break;
5368
- }
4724
+ const child = spawn(this.binaryPath, cmdArgs, {
4725
+ cwd: this.root,
4726
+ env: {
4727
+ ...process.env,
4728
+ ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
4729
+ },
4730
+ });
4731
+ if (options.input !== undefined) {
4732
+ child.stdin.write(options.input);
4733
+ child.stdin.end();
5369
4734
  }
4735
+ // Return the stdout stream
4736
+ return child.stdout;
5370
4737
  }
5371
4738
  /**
5372
- * Executes a multiplexed RPC call over the persistent private channel with full args and options descriptors.
4739
+ * Run a module action and return the stdin as a Writable stream
5373
4740
  */
5374
- async call(module, action, args = [], opts = {}, timeoutMs = 60000) {
5375
- await this.connect();
5376
- const stringArgs = Array.isArray(args)
5377
- ? args.map((a) => String(a))
5378
- : [];
5379
- const id = ++this.seqId;
5380
- const callPayload = Buffer.from(JSON.stringify({
5381
- id,
5382
- mod: module,
4741
+ runWritableStream(module, action, args = [], options = {}) {
4742
+ const internalSig = getInternalSignature();
4743
+ const cmdArgs = [
4744
+ "--root",
4745
+ this.root,
4746
+ module,
5383
4747
  action,
5384
- args: stringArgs,
5385
- opts: opts || {},
5386
- }));
5387
- const effectiveTimeout = typeof opts?.timeout === "number" ? opts.timeout : timeoutMs;
5388
- return new Promise((resolve, reject) => {
5389
- const timeout = setTimeout(() => {
5390
- this.pendingCalls.delete(id);
5391
- reject(new Error(`libSynapx: Call timed out after ${effectiveTimeout}ms [${module}.${action}]`));
5392
- }, effectiveTimeout);
5393
- this.pendingCalls.set(id, {
5394
- resolve,
5395
- reject,
5396
- timeout,
5397
- });
5398
- try {
5399
- this.writeFrame(MSG_CALL, callPayload);
5400
- }
5401
- catch (err) {
5402
- clearTimeout(timeout);
5403
- this.pendingCalls.delete(id);
5404
- reject(err);
4748
+ ...args,
4749
+ ];
4750
+ for (const [key, value] of Object.entries(options)) {
4751
+ const flag = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
4752
+ if (value === true)
4753
+ cmdArgs.push(`--${flag}`);
4754
+ else if (value !== false && value !== undefined) {
4755
+ cmdArgs.push(`--${flag}`, String(value));
5405
4756
  }
4757
+ }
4758
+ const child = spawn(this.binaryPath, cmdArgs, {
4759
+ cwd: this.root,
4760
+ env: {
4761
+ ...process.env,
4762
+ ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
4763
+ },
5406
4764
  });
5407
- }
5408
- /**
5409
- * Synchronous RPC via ultra-fast SharedArrayBuffer Futex Bridge (Path 1)
5410
- * with transparent automatic fallback to stdin pipe subprocess on edge platforms.
5411
- */
5412
- callSync(module, action, args = [], opts = {}) {
5413
- if (!this.socketPath || !fs.existsSync(this.socketPath)) {
5414
- this.ensureDaemon();
5415
- if (!this.socketPath || !fs.existsSync(this.socketPath)) {
5416
- throw new Error(`libSynapx: socket '${this.socketPath || "unknown"}' not found or active daemon is offline`);
5417
- }
5418
- }
5419
- try {
5420
- if (!this.syncBridge) {
5421
- this.syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.authToken);
5422
- }
5423
- return this.syncBridge.callSync(module, action, args, opts);
5424
- }
5425
- catch {
5426
- // Resilient fallback to stdin subprocess pipeline
5427
- return this.callSyncSubprocess(module, action, args, opts);
5428
- }
5429
- }
5430
- /**
5431
- * Subprocess-based synchronous fallback pipeline (streaming via stdin to prevent E2BIG).
5432
- */
5433
- callSyncSubprocess(module, action, args = [], opts = {}) {
5434
- const stringArgs = Array.isArray(args)
5435
- ? args.map((a) => String(a))
5436
- : [];
5437
- const script = `
5438
- const net = require("net");
5439
- const fs = require("fs");
5440
- const sock = process.argv[1];
5441
- const hash = process.argv[2] || "";
5442
- const token = process.argv[3] || "";
5443
-
5444
- let inputData = "";
5445
- try {
5446
- inputData = fs.readFileSync(0, "utf8");
5447
- } catch {}
5448
-
5449
- const req = JSON.parse(inputData || "{}");
5450
- const mod = req.mod;
5451
- const act = req.action;
5452
- const args = req.args || [];
5453
- const opts = req.opts || {};
5454
-
5455
- const client = net.createConnection(sock, () => {
5456
- // 1. Handshake
5457
- const hs = Buffer.from(JSON.stringify({ sessionHash: hash, token: token, clientPid: process.pid }));
5458
- const h1 = Buffer.alloc(6);
5459
- h1.writeUInt8(0x53, 0);
5460
- h1.writeUInt8(0x01, 1);
5461
- h1.writeUInt32BE(hs.length, 2);
5462
- client.write(Buffer.concat([h1, hs]));
5463
- });
5464
-
5465
- let buf = Buffer.alloc(0);
5466
- let handshaked = false;
5467
-
5468
- client.on("data", (chunk) => {
5469
- buf = Buffer.concat([buf, chunk]);
5470
- while (buf.length >= 6) {
5471
- if (buf.readUInt8(0) !== 0x53) { process.exit(1); }
5472
- const type = buf.readUInt8(1);
5473
- const len = buf.readUInt32BE(2);
5474
- if (buf.length < 6 + len) return;
5475
- const payload = buf.subarray(6, 6 + len);
5476
- buf = buf.subarray(6 + len);
5477
-
5478
- if (!handshaked) {
5479
- if (type === 0x02) {
5480
- handshaked = true;
5481
- const call = Buffer.from(JSON.stringify({ id: 1, mod: mod, action: act, args: args, opts: opts }));
5482
- const h2 = Buffer.alloc(6);
5483
- h2.writeUInt8(0x53, 0);
5484
- h2.writeUInt8(0x03, 1);
5485
- h2.writeUInt32BE(call.length, 2);
5486
- client.write(Buffer.concat([h2, call]));
5487
- } else { process.exit(1); }
5488
- } else {
5489
- if (type === 0x04) {
5490
- process.stdout.write(payload);
5491
- client.end();
5492
- process.exit(0);
5493
- } else { process.exit(1); }
5494
- }
5495
- }
5496
- });
5497
- setTimeout(() => process.exit(1), 5000);
5498
- `;
5499
- const inputPayload = JSON.stringify({
5500
- mod: module,
5501
- action,
5502
- args: stringArgs,
5503
- opts: opts || {},
5504
- });
5505
- const output = execFileSync(process.execPath, [
5506
- "-e",
5507
- script,
5508
- this.socketPath,
5509
- this.sessionHash,
5510
- this.authToken,
5511
- ], {
5512
- input: inputPayload,
5513
- encoding: "utf8",
5514
- timeout: 5000,
5515
- maxBuffer: 100 * 1024 * 1024,
5516
- stdio: ["pipe", "pipe", "pipe"],
5517
- });
5518
- const parsed = JSON.parse(output.trim());
5519
- if (!parsed.ok) {
5520
- throw new Error(parsed.err || "libSynapx call failed");
5521
- }
5522
- return parsed.data;
5523
- }
5524
- destroy() {
5525
- this.isHandshakeComplete = false;
5526
- if (this.syncBridge) {
5527
- this.syncBridge.destroy();
5528
- this.syncBridge = null;
5529
- }
5530
- if (this.socket) {
5531
- this.socket.removeAllListeners();
5532
- this.socket.destroy();
5533
- this.socket = null;
5534
- }
5535
- for (const [id, pending] of this.pendingCalls.entries()) {
5536
- clearTimeout(pending.timeout);
5537
- pending.reject(new Error("libSynapx: socket disconnected"));
5538
- }
5539
- this.pendingCalls.clear();
5540
- this.rxChunks = [];
5541
- this.rxBytesTotal = 0;
4765
+ // Return the stdin stream with an explicit close() method
4766
+ const stdin = child.stdin;
4767
+ // @ts-ignore
4768
+ stdin.close = () => stdin.end();
4769
+ return stdin;
5542
4770
  }
5543
4771
  }
5544
- SynapxClient.instance = null;
5545
4772
 
5546
4773
  /**
5547
- * Custom error class for XyPriss system operations.
4774
+ * Returns the absolute path to the XyPriss shared temp directory.
4775
+ *
4776
+ * @returns {string} Path to `<os.tmpdir>/nehonix.xypriss.data`
5548
4777
  */
5549
- class XyPrissError extends Error {
5550
- constructor(module, action, details, raw) {
5551
- super(`[XyPriss Error] ${module}.${action} failed: ${details}`);
5552
- this.module = module;
5553
- this.action = action;
5554
- this.details = details;
5555
- this.raw = raw;
5556
- this.name = "XyPrissError";
4778
+ function getXyprissTempDir() {
4779
+ const sys = getSysApi();
4780
+ return sys.path.join(sys.path.tempDir(), "nehonix.xypriss.data");
4781
+ }
4782
+ /**
4783
+ * Resolves and ensures a sub-path within the XyPriss temp directory exists.
4784
+ *
4785
+ * @param {string | string[]} _p - Sub-path segment(s) to append.
4786
+ * @returns {string} The absolute resolved temp sub-path.
4787
+ */
4788
+ function createXyprissTempDir(_p) {
4789
+ const sys = getSysApi();
4790
+ const base = getXyprissTempDir();
4791
+ const segment = typeof _p === "string"
4792
+ ? _p
4793
+ : _p.includes("/")
4794
+ ? _p.map((p) => p.replace("/", "")).join("/")
4795
+ : _p.join("/");
4796
+ // Use the native corrective layer to prevent doubling or redundant separators
4797
+ const rawPath = segment.startsWith(base)
4798
+ ? segment
4799
+ : sys.path.join(base, segment);
4800
+ const normalisedPath = sys.path.correct(rawPath, { tentative: 2 });
4801
+ if (!sys.fs.exist(normalisedPath)) {
4802
+ sys.fs.mkdir(normalisedPath, { parents: true });
5557
4803
  }
4804
+ return normalisedPath;
5558
4805
  }
5559
4806
  /**
5560
- * **Native System Runner**
4807
+ * **Session Temp Directory (singleton)**
5561
4808
  *
5562
- * This class serves as the core bridge between the Node.js runtime and the
5563
- * high-performance system core. It manages process spawning, argument
5564
- * serialization, and bidirectional streaming.
4809
+ * Unique sub-path generated once per process lifetime under the XyPriss
4810
+ * temp root (`<os.tmpdir>/nehonix.xypriss.data/xuser/<hex4>`).
4811
+ *
4812
+ * The value is memoized on first access and remains stable for the entire
4813
+ * duration of the running process, ensuring all callers within the same
4814
+ * session share the same isolated scratch space.
5565
4815
  */
5566
- class XyPrissRunner {
5567
- constructor(root) {
5568
- this.root = root;
5569
- this.binaryPath = this.discoverBinary();
5570
- // console.log(
5571
- // "[XyPrissRunner:getBinaryPath] Binary path: ",
5572
- // this.discoverBinary(),
5573
- // );
4816
+ let _sessionTmpDir = null;
4817
+ /**
4818
+ * Returns the process-scoped user temp directory path for THIS active server instance.
4819
+ *
4820
+ * Generates an instance ID hash once and caches it for the lifetime of the process.
4821
+ * E.g. `/tmp/nehonix.xypriss.data/xuser/12daa75a`
4822
+ *
4823
+ * @returns {string} Absolute path to instance temp directory
4824
+ */
4825
+ function generateXUserTmpDir() {
4826
+ if (_sessionTmpDir !== null) {
4827
+ return _sessionTmpDir;
5574
4828
  }
5575
- getRoot() {
5576
- // console.log("[XyPrissRunner:getRoot] Binary root: ", this.root);
5577
- return this.root;
4829
+ const sys = getSysApi();
4830
+ // 1. Adopt the session directory allocated exclusively by the libProc supervisor
4831
+ const envSession = sys?.__env__?.get("XYPRISS_USER_TMP") ||
4832
+ sys?.__env__?.get("XESS_SESSION_TMP") ||
4833
+ (typeof process !== "undefined"
4834
+ ? (process.env?.XYPRISS_USER_TMP || process.env?.XESS_SESSION_TMP)
4835
+ : undefined);
4836
+ if (envSession && typeof envSession === "string") {
4837
+ _sessionTmpDir = envSession;
4838
+ if (sys?.fs && !sys.fs.exist(_sessionTmpDir)) {
4839
+ sys.fs.mkdir(_sessionTmpDir, { parents: true });
4840
+ }
4841
+ return _sessionTmpDir;
5578
4842
  }
5579
- getBinaryPath() {
5580
- return this.binaryPath;
4843
+ // No supervisor session provisioned by libProc: unconfined execution has no valid session
4844
+ return "";
4845
+ }
4846
+ /**
4847
+ * Returns the unique 8-character session hash ID for the active server instance.
4848
+ * Delegated exclusively to the libProc supervisor (Single Source of Truth).
4849
+ */
4850
+ function getSessionHash() {
4851
+ const sys = getSysApi();
4852
+ const envHash = sys?.__env__?.get("XYPRISS_SESSION_HASH") ||
4853
+ (typeof process !== "undefined" ? process.env?.XYPRISS_SESSION_HASH : undefined);
4854
+ if (envHash && typeof envHash === "string") {
4855
+ return envHash;
5581
4856
  }
5582
- /**
5583
- * Strategic discovery of the XyPriss System binary.
5584
- * Prioritizes the high-performance Go implementation (XHSC-GO).
5585
- */
5586
- discoverBinary() {
5587
- // 1. Environment Variable Override (Highest Priority)
5588
- const envPath = Discovery.getFromEnv("XYPRISS_XHSC_PATH");
5589
- if (envPath)
5590
- return envPath;
5591
- const osPart = Platform.getOsPart();
5592
- const archPart = Platform.getArchPart();
5593
- const suffix = Platform.getBinarySuffix();
5594
- // Candidate names in order of preference
5595
- const goBinName = `xhsc-${osPart}-${archPart}${suffix}`;
5596
- const genericBinName = osPart === "windows" ? "xhsc.exe" : "xhsc";
5597
- const candidates = [goBinName, genericBinName];
5598
- const searchBases = [];
5599
- // 2. Add Script Directory (where the library is located)
5600
- const scriptDir = Discovery.getScriptDir();
5601
- if (scriptDir)
5602
- searchBases.push(scriptDir);
5603
- // 3. Add Current Working Directory
5604
- searchBases.push(process.cwd());
5605
- // Perform recursive search from all bases using Discovery engine
5606
- const resolved = Discovery.resolveBinary(candidates, searchBases);
5607
- if (resolved)
5608
- return resolved;
5609
- // Final fallback (generic name which might be in PATH via system spawn)
5610
- return genericBinName;
5611
- }
5612
- /**
5613
- * Executes a command synchronously and returns the parsed JSON result.
5614
- * Standardizes all responses into a Promise-like data structure.
5615
- */
5616
- /**
5617
- * Executes a command synchronously via libSynapx IPC and returns the parsed result.
5618
- */
5619
- runSync(module, action, args = [], options = {}) {
5620
- try {
5621
- const synapx = SynapxClient.getInstance();
5622
- return synapx.callSync(module, action, args, options);
5623
- }
5624
- catch (error) {
5625
- if (error instanceof XyPrissError)
5626
- throw error;
5627
- throw new XyPrissError(module, action, error.message || String(error), error);
5628
- }
5629
- }
5630
- /**
5631
- * Executes a command asynchronously via libSynapx IPC and returns the parsed result.
5632
- */
5633
- async runAsync(module, action, args = [], options = {}) {
5634
- try {
5635
- const synapx = SynapxClient.getInstance();
5636
- return await synapx.call(module, action, args, options);
5637
- }
5638
- catch (error) {
5639
- if (error instanceof XyPrissError)
5640
- throw error;
5641
- throw new XyPrissError(module, action, error.message || String(error), error);
5642
- }
5643
- }
5644
- /**
5645
- * Run a module action and return the stdout as a Readable stream
5646
- */
5647
- runStream(module, action, args = [], options = {}) {
5648
- const internalSig = getInternalSignature();
5649
- const cmdArgs = [
5650
- "--root",
5651
- this.root,
5652
- module,
5653
- action,
5654
- ...args,
5655
- ];
5656
- for (const [key, value] of Object.entries(options)) {
5657
- if (["input"].includes(key))
5658
- continue;
5659
- const flag = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
5660
- if (value === true)
5661
- cmdArgs.push(`--${flag}`);
5662
- else if (value !== false && value !== undefined) {
5663
- cmdArgs.push(`--${flag}`, String(value));
5664
- }
5665
- }
5666
- const child = spawn(this.binaryPath, cmdArgs, {
5667
- cwd: this.root,
5668
- env: {
5669
- ...process.env,
5670
- ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5671
- },
5672
- });
5673
- if (options.input !== undefined) {
5674
- child.stdin.write(options.input);
5675
- child.stdin.end();
5676
- }
5677
- // Return the stdout stream
5678
- return child.stdout;
5679
- }
5680
- /**
5681
- * Run a module action and return the stdin as a Writable stream
5682
- */
5683
- runWritableStream(module, action, args = [], options = {}) {
5684
- const internalSig = getInternalSignature();
5685
- const cmdArgs = [
5686
- "--root",
5687
- this.root,
5688
- module,
5689
- action,
5690
- ...args,
5691
- ];
5692
- for (const [key, value] of Object.entries(options)) {
5693
- const flag = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
5694
- if (value === true)
5695
- cmdArgs.push(`--${flag}`);
5696
- else if (value !== false && value !== undefined) {
5697
- cmdArgs.push(`--${flag}`, String(value));
5698
- }
4857
+ if (_sessionTmpDir) {
4858
+ if (sys?.path) {
4859
+ return sys.path.basename(_sessionTmpDir);
5699
4860
  }
5700
- const child = spawn(this.binaryPath, cmdArgs, {
5701
- cwd: this.root,
5702
- env: {
5703
- ...process.env,
5704
- ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5705
- },
5706
- });
5707
- // Return the stdin stream with an explicit close() method
5708
- const stdin = child.stdin;
5709
- // @ts-ignore
5710
- stdin.close = () => stdin.end();
5711
- return stdin;
4861
+ const parts = _sessionTmpDir.split(/[/\\]/).filter(Boolean);
4862
+ return parts[parts.length - 1] || "";
5712
4863
  }
4864
+ return "";
4865
+ }
4866
+ /**
4867
+ * Backward-compatibility alias for getSessionHash().
4868
+ */
4869
+ function getInstanceId() {
4870
+ return getSessionHash();
5713
4871
  }
5714
4872
 
5715
4873
  /* *****************************************************************************
@@ -6370,103 +5528,320 @@ class FileHandle {
6370
5528
  this.runner = runner;
6371
5529
  this.synapx = SynapxClient.getInstance();
6372
5530
  }
6373
- /**
6374
- * **Get Native Handle ID**
6375
- */
6376
- get nativeId() {
6377
- return this.id;
5531
+ /**
5532
+ * **Get Native Handle ID**
5533
+ */
5534
+ get nativeId() {
5535
+ return this.id;
5536
+ }
5537
+ /**
5538
+ * **Read from File**
5539
+ * @param length - Max bytes to read
5540
+ */
5541
+ async read(length) {
5542
+ if (this.synapx.isAvailable()) {
5543
+ const res = await this.synapx.call("fs", "read-handle", [
5544
+ String(this.id),
5545
+ String(length),
5546
+ ]);
5547
+ if (typeof res === "string") {
5548
+ return Buffer.from(res, "hex");
5549
+ }
5550
+ if (Buffer.isBuffer(res))
5551
+ return res;
5552
+ if (res && res.content) {
5553
+ return Buffer.from(res.content, "base64");
5554
+ }
5555
+ return Buffer.from(res || "");
5556
+ }
5557
+ const res = (await this.runner.runAsync("fs", "read-handle", [
5558
+ String(this.id),
5559
+ String(length),
5560
+ ]));
5561
+ return Buffer.from(res?.content || res || "", "hex");
5562
+ }
5563
+ /**
5564
+ * **Write to File**
5565
+ * @param data - Buffer or String
5566
+ */
5567
+ async write(data) {
5568
+ const raw = typeof data === "string" ? Buffer.from(data) : data;
5569
+ if (this.synapx.isAvailable()) {
5570
+ const res = await this.synapx.call("fs", "write-handle", [
5571
+ String(this.id),
5572
+ raw.toString("hex"),
5573
+ ]);
5574
+ return typeof res === "number" ? res : (res?.n ?? raw.length);
5575
+ }
5576
+ const res = (await this.runner.runAsync("fs", "write-handle", [
5577
+ String(this.id),
5578
+ raw.toString("hex"),
5579
+ ]));
5580
+ return typeof res === "number" ? res : (res?.n ?? raw.length);
5581
+ }
5582
+ /**
5583
+ * **Seek within File**
5584
+ * @param offset - Position
5585
+ * @param whence - 0: Start, 1: Current, 2: End
5586
+ */
5587
+ async seek(offset, whence = 0) {
5588
+ if (this.synapx.isAvailable()) {
5589
+ const res = await this.synapx.call("fs", "seek-handle", [
5590
+ String(this.id),
5591
+ String(offset),
5592
+ String(whence),
5593
+ ]);
5594
+ return typeof res === "number" ? res : (res?.pos ?? 0);
5595
+ }
5596
+ const res = (await this.runner.runAsync("fs", "seek-handle", [
5597
+ String(this.id),
5598
+ String(offset),
5599
+ String(whence),
5600
+ ]));
5601
+ return typeof res === "number" ? res : (res?.pos ?? 0);
5602
+ }
5603
+ /**
5604
+ * **Get File Statistics**
5605
+ */
5606
+ async stat() {
5607
+ if (this.synapx.isAvailable()) {
5608
+ return await this.synapx.call("fs", "stat-handle", [
5609
+ String(this.id),
5610
+ ]);
5611
+ }
5612
+ return (await this.runner.runAsync("fs", "stat-handle", [
5613
+ String(this.id),
5614
+ ]));
5615
+ }
5616
+ /**
5617
+ * **Close Handle**
5618
+ */
5619
+ async close() {
5620
+ if (this.synapx.isAvailable()) {
5621
+ await this.synapx.call("fs", "close", [String(this.id)]);
5622
+ }
5623
+ else {
5624
+ await this.runner.runAsync("fs", "close", [String(this.id)]);
5625
+ }
5626
+ }
5627
+ }
5628
+
5629
+ /**
5630
+ * ANSI color codes for terminal output
5631
+ */
5632
+ const ANSI = {
5633
+ reset: "\x1b[0m",
5634
+ bold: "\x1b[1m",
5635
+ dim: "\x1b[2m",
5636
+ // Foreground colors
5637
+ black: "\x1b[30m",
5638
+ yellow: "\x1b[33m",
5639
+ blue: "\x1b[34m",
5640
+ cyan: "\x1b[36m",
5641
+ white: "\x1b[37m",
5642
+ gray: "\x1b[90m",
5643
+ // Bright foreground
5644
+ brightRed: "\x1b[91m",
5645
+ brightGreen: "\x1b[92m",
5646
+ brightYellow: "\x1b[93m",
5647
+ brightBlue: "\x1b[94m",
5648
+ brightMagenta: "\x1b[95m",
5649
+ brightCyan: "\x1b[96m",
5650
+ // Background colors
5651
+ bgRed: "\x1b[41m",
5652
+ bgGreen: "\x1b[42m",
5653
+ bgYellow: "\x1b[43m",
5654
+ bgBlue: "\x1b[44m",
5655
+ bgMagenta: "\x1b[45m",
5656
+ bgCyan: "\x1b[46m",
5657
+ };
5658
+ const LOG_CONFIGS = {
5659
+ info: {
5660
+ icon: "ℹ️ ",
5661
+ color: ANSI.brightCyan,
5662
+ label: "INFO",
5663
+ labelColor: `${ANSI.bgCyan}${ANSI.black}`,
5664
+ },
5665
+ success: {
5666
+ icon: "✅",
5667
+ color: ANSI.brightGreen,
5668
+ label: "OK",
5669
+ labelColor: `${ANSI.bgGreen}${ANSI.black}`,
5670
+ },
5671
+ warn: {
5672
+ icon: "⚠️ ",
5673
+ color: ANSI.brightYellow,
5674
+ label: "WARN",
5675
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
5676
+ },
5677
+ error: {
5678
+ icon: "❌",
5679
+ color: ANSI.brightRed,
5680
+ label: "ERROR",
5681
+ labelColor: `${ANSI.bgRed}${ANSI.white}`,
5682
+ },
5683
+ debug: {
5684
+ icon: "-",
5685
+ color: ANSI.gray,
5686
+ label: "DEBUG",
5687
+ labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
5688
+ },
5689
+ http: {
5690
+ icon: "🌐",
5691
+ color: ANSI.brightBlue,
5692
+ label: "HTTP",
5693
+ labelColor: `${ANSI.bgBlue}${ANSI.white}`,
5694
+ },
5695
+ swagger: {
5696
+ icon: "🛡️ ",
5697
+ color: ANSI.brightMagenta,
5698
+ label: "SWAGGER",
5699
+ labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
5700
+ },
5701
+ db: {
5702
+ icon: "🗄️ ",
5703
+ color: ANSI.yellow,
5704
+ label: "DB",
5705
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
5706
+ },
5707
+ auth: {
5708
+ icon: "🔐",
5709
+ color: ANSI.brightYellow,
5710
+ label: "AUTH",
5711
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
5712
+ },
5713
+ };
5714
+ const LEVEL_RANK = {
5715
+ silent: 0,
5716
+ error: 1,
5717
+ warn: 2,
5718
+ info: 3,
5719
+ success: 3,
5720
+ http: 3,
5721
+ swagger: 3,
5722
+ db: 3,
5723
+ auth: 3,
5724
+ debug: 4,
5725
+ verbose: 5,
5726
+ };
5727
+ class QuickLogger {
5728
+ constructor(context) {
5729
+ this.context = context;
5730
+ }
5731
+ // ─── Static factory ───────────────────────────────────────────────────────
5732
+ static for(context) {
5733
+ return new QuickLogger(context);
5734
+ }
5735
+ static shouldLog(level) {
5736
+ const sys = getSysApi();
5737
+ let isDebug = false;
5738
+ if (sys?.__env__) {
5739
+ isDebug =
5740
+ sys.__env__.get("DEBUG") ||
5741
+ sys.__env__.get("XYPRISS_DEBUG") ||
5742
+ sys.__env__.get("DEBUG_FS");
5743
+ }
5744
+ else if (typeof process !== "undefined" && process.env) {
5745
+ isDebug =
5746
+ process.env.DEBUG ||
5747
+ process.env.XYPRISS_DEBUG ||
5748
+ process.env.DEBUG_FS;
5749
+ }
5750
+ if (isDebug) {
5751
+ return true;
5752
+ }
5753
+ try {
5754
+ const logging = ConfigurationManager.get("logging");
5755
+ if (logging) {
5756
+ if (logging.enabled === false) {
5757
+ return false;
5758
+ }
5759
+ // Check logging.types overrides
5760
+ if (level === "error" && logging.types?.errors === false)
5761
+ return false;
5762
+ if (level === "warn" && logging.types?.warnings === false)
5763
+ return false;
5764
+ if (level === "debug" && logging.types?.debug === false)
5765
+ return false;
5766
+ if (level === "debug" && logging.types?.debug === true)
5767
+ return true;
5768
+ // Check logging.level rank
5769
+ const configuredLevel = (logging.level || "info").toLowerCase();
5770
+ const configuredRank = LEVEL_RANK[configuredLevel] ?? 3;
5771
+ const messageRank = LEVEL_RANK[level] ?? 3;
5772
+ return messageRank <= configuredRank;
5773
+ }
5774
+ }
5775
+ catch { }
5776
+ // Default ranking if no config: info level (rank 3)
5777
+ const defaultRank = 3;
5778
+ const messageRank = LEVEL_RANK[level] ?? 3;
5779
+ return messageRank <= defaultRank;
5780
+ }
5781
+ // ─── Core log method ──────────────────────────────────────────────────────
5782
+ log(level, ...args) {
5783
+ if (!QuickLogger.shouldLog(level)) {
5784
+ return;
5785
+ }
5786
+ const cfg = LOG_CONFIGS[level];
5787
+ const timestamp = QuickLogger.showTimestamp
5788
+ ? `${ANSI.dim}${ANSI.gray}${new Date().toISOString()}${ANSI.reset} `
5789
+ : "";
5790
+ const label = `${cfg.labelColor}${ANSI.bold} ${cfg.label} ${ANSI.reset}`;
5791
+ const ctx = `${ANSI.dim}${ANSI.cyan}[${this.context}]${ANSI.reset}`;
5792
+ // First arg gets the level color + icon, rest are passed raw so Node.js
5793
+ // pretty-prints objects/arrays/Errors natively (no JSON.stringify needed).
5794
+ const [first, ...rest] = args;
5795
+ const prefix = `${timestamp}${label} ${ctx} ${cfg.color}${cfg.icon} ${String(first)}${ANSI.reset}`;
5796
+ const consoleFn = level === "error"
5797
+ ? console.error
5798
+ : level === "warn"
5799
+ ? console.warn
5800
+ : console.log;
5801
+ rest.length > 0 ? consoleFn(prefix, ...rest) : consoleFn(prefix);
5802
+ }
5803
+ // ─── Public methods ───────────────────────────────────────────────────────
5804
+ info(...args) {
5805
+ this.log("info", ...args);
5806
+ }
5807
+ success(...args) {
5808
+ this.log("success", ...args);
5809
+ }
5810
+ warn(...args) {
5811
+ this.log("warn", ...args);
5812
+ }
5813
+ error(...args) {
5814
+ this.log("error", ...args);
5815
+ }
5816
+ debug(...args) {
5817
+ this.log("debug", ...args);
6378
5818
  }
6379
- /**
6380
- * **Read from File**
6381
- * @param length - Max bytes to read
6382
- */
6383
- async read(length) {
6384
- if (this.synapx.isAvailable()) {
6385
- const res = await this.synapx.call("fs", "read-handle", [
6386
- String(this.id),
6387
- String(length),
6388
- ]);
6389
- if (typeof res === "string") {
6390
- return Buffer.from(res, "hex");
6391
- }
6392
- if (Buffer.isBuffer(res))
6393
- return res;
6394
- if (res && res.content) {
6395
- return Buffer.from(res.content, "base64");
6396
- }
6397
- return Buffer.from(res || "");
6398
- }
6399
- const res = (await this.runner.runAsync("fs", "read-handle", [
6400
- String(this.id),
6401
- String(length),
6402
- ]));
6403
- return Buffer.from(res?.content || res || "", "hex");
5819
+ http(...args) {
5820
+ this.log("http", ...args);
6404
5821
  }
6405
- /**
6406
- * **Write to File**
6407
- * @param data - Buffer or String
6408
- */
6409
- async write(data) {
6410
- const raw = typeof data === "string" ? Buffer.from(data) : data;
6411
- if (this.synapx.isAvailable()) {
6412
- const res = await this.synapx.call("fs", "write-handle", [
6413
- String(this.id),
6414
- raw.toString("hex"),
6415
- ]);
6416
- return typeof res === "number" ? res : (res?.n ?? raw.length);
6417
- }
6418
- const res = (await this.runner.runAsync("fs", "write-handle", [
6419
- String(this.id),
6420
- raw.toString("hex"),
6421
- ]));
6422
- return typeof res === "number" ? res : (res?.n ?? raw.length);
5822
+ swagger(...args) {
5823
+ this.log("swagger", ...args);
6423
5824
  }
6424
- /**
6425
- * **Seek within File**
6426
- * @param offset - Position
6427
- * @param whence - 0: Start, 1: Current, 2: End
6428
- */
6429
- async seek(offset, whence = 0) {
6430
- if (this.synapx.isAvailable()) {
6431
- const res = await this.synapx.call("fs", "seek-handle", [
6432
- String(this.id),
6433
- String(offset),
6434
- String(whence),
6435
- ]);
6436
- return typeof res === "number" ? res : (res?.pos ?? 0);
6437
- }
6438
- const res = (await this.runner.runAsync("fs", "seek-handle", [
6439
- String(this.id),
6440
- String(offset),
6441
- String(whence),
6442
- ]));
6443
- return typeof res === "number" ? res : (res?.pos ?? 0);
5825
+ db(...args) {
5826
+ this.log("db", ...args);
6444
5827
  }
6445
- /**
6446
- * **Get File Statistics**
6447
- */
6448
- async stat() {
6449
- if (this.synapx.isAvailable()) {
6450
- return await this.synapx.call("fs", "stat-handle", [
6451
- String(this.id),
6452
- ]);
6453
- }
6454
- return (await this.runner.runAsync("fs", "stat-handle", [
6455
- String(this.id),
6456
- ]));
5828
+ auth(...args) {
5829
+ this.log("auth", ...args);
6457
5830
  }
6458
- /**
6459
- * **Close Handle**
6460
- */
6461
- async close() {
6462
- if (this.synapx.isAvailable()) {
6463
- await this.synapx.call("fs", "close", [String(this.id)]);
6464
- }
6465
- else {
6466
- await this.runner.runAsync("fs", "close", [String(this.id)]);
6467
- }
5831
+ // ─── Convenience: banner / separator ─────────────────────────────────────
5832
+ banner(title) {
5833
+ const line = `${ANSI.blue}${"─".repeat(60)}${ANSI.reset}`;
5834
+ const centered = title
5835
+ .padStart(30 + Math.floor(title.length / 2))
5836
+ .padEnd(60);
5837
+ console.log(`\n${line}`);
5838
+ console.log(`${ANSI.bold}${ANSI.brightCyan}${centered}${ANSI.reset}`);
5839
+ console.log(`${line}\n`);
6468
5840
  }
6469
5841
  }
5842
+ QuickLogger.showTimestamp = true;
5843
+ // ─── Default singleton logger ──────────────────────────────────────────────
5844
+ // export const logger = QuickLogger.for("");
6470
5845
 
6471
5846
  const logger = QuickLogger.for("XHSC:TempFile");
6472
5847
  class TempFileManager {
@@ -8681,39 +8056,13 @@ class ConfigSyntaxParser {
8681
8056
  }
8682
8057
 
8683
8058
  // ---------------------------------------------------------------------------
8684
- // Internal RAM store for project environments — purely module-scoped.
8059
+ // Zero-RAM-Store Architecture (libSynapx + libXESS):
8685
8060
  //
8686
- // CRITICAL SECURITY FIX:
8687
- // Do NOT store this on `globalThis` using a Symbol. `Object.getOwnPropertySymbols(globalThis)`
8688
- // allows any script or untrusted dependency to enumerate all symbols on globalThis
8689
- // and exfiltrate secrets without using __sys__.__env__.
8690
- // By encapsulating the store in module-scoped closures, the data is completely
8691
- // invisible to global reflection APIs.
8061
+ // CRITICAL SECURITY GUARANTEE:
8062
+ // Environment secrets are NEVER cached or stored in JavaScript/V8 RAM.
8063
+ // All secret reads and mutations are delegated synchronously over the
8064
+ // authenticated libSynapx bridge to the native Go libXESS Vault.
8692
8065
  // ---------------------------------------------------------------------------
8693
- let _internalProjectEnvs;
8694
- function setInternalProjectEnvs(store) {
8695
- _internalProjectEnvs = store;
8696
- }
8697
- function getInternalProjectEnvs() {
8698
- const stack = new Error().stack || "";
8699
- const lines = stack.split("\n");
8700
- for (let i = 1; i < lines.length; i++) {
8701
- const line = lines[i];
8702
- if (line.includes("env.") || line.includes("getInternalProjectEnvs"))
8703
- continue;
8704
- const match = line.match(/\((.*):\d+:\d+\)$/) ||
8705
- line.match(/at (.*):\d+:\d+$/) ||
8706
- line.match(/at (.*)$/);
8707
- if (match) {
8708
- const callerFile = match[1];
8709
- if (!isCoreFrameworkPath(callerFile)) {
8710
- return undefined;
8711
- }
8712
- break;
8713
- }
8714
- }
8715
- return _internalProjectEnvs;
8716
- }
8717
8066
  const XY_XHSC_REGISTER_FS = Symbol();
8718
8067
  /**
8719
8068
  * **Internal Root-Scoped Env Access Key**
@@ -8802,21 +8151,6 @@ class EnvKeyError extends Error {
8802
8151
  Object.setPrototypeOf(this, EnvKeyError.prototype);
8803
8152
  }
8804
8153
  }
8805
- /**
8806
- * Thrown when {@link EnvApi} methods are called before the internal store has
8807
- * been initialised by the XyPriss bootstrap process.
8808
- *
8809
- * This error should never occur in correctly bootstrapped applications.
8810
- * If it does, it indicates that framework initialisation was bypassed.
8811
- */
8812
- class EnvStoreError extends Error {
8813
- constructor() {
8814
- super("The XyPriss environment store has not been initialised. " +
8815
- "Ensure that createServer() has completed before accessing __sys__.__env__.");
8816
- this.name = "EnvStoreError";
8817
- Object.setPrototypeOf(this, EnvStoreError.prototype);
8818
- }
8819
- }
8820
8154
  /**
8821
8155
  * Thrown when an application attempts to boot without the mandatory libXESS confinement shield.
8822
8156
  */
@@ -8831,6 +8165,46 @@ class XessShieldRequiredError extends Error {
8831
8165
  }
8832
8166
  }
8833
8167
 
8168
+ /**
8169
+ * Checks if a given file path belongs to the deep engine core.
8170
+ * These files are skipped during stack analysis to find the user/plugin caller.
8171
+ */
8172
+ function isEngineCorePath(filePath) {
8173
+ if (!filePath)
8174
+ return false;
8175
+ const normalizedPath = filePath.replace(/\\/g, "/");
8176
+ if (normalizedPath.includes("/XyPriss/src/") ||
8177
+ normalizedPath.includes("/XyPriss/dist/") ||
8178
+ normalizedPath.includes("/node_modules/xypriss/")) {
8179
+ return true;
8180
+ }
8181
+ return false;
8182
+ }
8183
+ /**
8184
+ * Checks if a given file path belongs directly to the XyPriss Core Engine
8185
+ * or if it comes from an external plugin / user space.
8186
+ * This is used for SECURITY authorization.
8187
+ */
8188
+ function isCoreFrameworkPath(filePath) {
8189
+ if (!filePath)
8190
+ return false;
8191
+ const normalizedPath = filePath.replace(/\\/g, "/");
8192
+ // Authorize trusted internal mods within the framework repository
8193
+ if (normalizedPath.includes("/XyPriss/mods/"))
8194
+ return true;
8195
+ // Exclude other plugins even if they contain 'src' or are named 'xypriss-something'
8196
+ if (normalizedPath.includes("/mods/"))
8197
+ return false;
8198
+ // Engine Core is always trusted
8199
+ return isEngineCorePath(filePath);
8200
+ }
8201
+
8202
+ // Capture native V8 C++ CallSite bindings at module bootstrap before any third-party code executes.
8203
+ // `util.getCallSites` invokes v8::StackTrace::CurrentStackTrace directly in C++, completely
8204
+ // bypassing `Error.prepareStackTrace` overrides and ignoring `//# sourceURL` directives.
8205
+ const _nativeGetCallSites = typeof util.getCallSites === "function"
8206
+ ? util.getCallSites.bind(util)
8207
+ : null;
8834
8208
  let cachedManifest = null;
8835
8209
  /**
8836
8210
  * Loads the authoritative plugins manifest provided by xfpm.
@@ -8929,43 +8303,167 @@ function identifyProjectRoot(filePath) {
8929
8303
  }
8930
8304
  return undefined;
8931
8305
  }
8306
+ function normalizeScriptName(rawScript) {
8307
+ if (!rawScript)
8308
+ return "";
8309
+ if (rawScript.startsWith("file://")) {
8310
+ try {
8311
+ return fileURLToPath(rawScript);
8312
+ }
8313
+ catch {
8314
+ return rawScript.slice(7);
8315
+ }
8316
+ }
8317
+ return rawScript;
8318
+ }
8319
+ function isRuntimeLoaderPath(filePath) {
8320
+ const norm = filePath.replace(/\\/g, "/");
8321
+ return (norm.includes("/node_modules/tsx/") ||
8322
+ norm.includes("/node_modules/ts-node/") ||
8323
+ norm.includes("/node_modules/.bin/"));
8324
+ }
8932
8325
  /**
8933
- * Retrieves the project root of the code currently executing by analyzing the stack trace.
8326
+ * Captures raw C++ V8/JSC CallSite frames by temporarily overriding `Error.prepareStackTrace`
8327
+ * synchronously during stack generation. This neutralizes any user/attacker `Error.prepareStackTrace`
8328
+ * hijack and returns the full un-truncated call stack across both Node.js (V8) and Bun (JSC).
8934
8329
  */
8935
- function getCallerProjectRoot() {
8936
- const stack = new Error().stack;
8937
- if (!stack)
8938
- return getPrimaryProjectRoot();
8939
- const lines = stack.split("\n");
8940
- let callerFilePath = "";
8941
- // Line 0 is 'Error', Line 1 is getCallerProjectRoot itself
8942
- for (let i = 2; i < lines.length; i++) {
8943
- const line = lines[i];
8944
- if (!line || line.includes(" (node:") || line.includes(" (bun:") || line.includes(" (native"))
8330
+ function captureNativeFrames() {
8331
+ const frames = [];
8332
+ // 1. Capture full CallSite array via controlled prepareStackTrace override (immune to prior Error.prepareStackTrace hijacks)
8333
+ const prevPrepare = Error.prepareStackTrace;
8334
+ const prevLimit = Error.stackTraceLimit;
8335
+ let rawSites = [];
8336
+ try {
8337
+ Error.stackTraceLimit = 64;
8338
+ Error.prepareStackTrace = (_err, stack) => {
8339
+ rawSites = Array.isArray(stack) ? stack : [];
8340
+ return "";
8341
+ };
8342
+ const probe = new Error();
8343
+ void probe.stack;
8344
+ }
8345
+ catch {
8346
+ // ignore
8347
+ }
8348
+ finally {
8349
+ Error.prepareStackTrace = prevPrepare;
8350
+ Error.stackTraceLimit = prevLimit;
8351
+ }
8352
+ for (const site of rawSites) {
8353
+ if (!site)
8945
8354
  continue;
8946
- const match = line.match(/\((.*\.([jt]s|[cm]js)):\d+:\d+\)$/) ||
8947
- line.match(/at (.*\.([jt]s|[cm]js)):\d+:\d+$/);
8948
- if (!match)
8355
+ try {
8356
+ const rawFile = typeof site.getFileName === "function"
8357
+ ? site.getFileName() || ""
8358
+ : "";
8359
+ const fnName = typeof site.getFunctionName === "function"
8360
+ ? site.getFunctionName() || ""
8361
+ : "";
8362
+ const isEval = typeof site.isEval === "function" ? Boolean(site.isEval()) : false;
8363
+ frames.push({
8364
+ filePath: normalizeScriptName(rawFile),
8365
+ fnName,
8366
+ isEval,
8367
+ });
8368
+ }
8369
+ catch {
8370
+ // ignore
8371
+ }
8372
+ }
8373
+ // 2. Also merge frames from Node C++ util.getCallSites (which strips //# sourceURL on V8)
8374
+ if (_nativeGetCallSites) {
8375
+ try {
8376
+ const nativeSites = _nativeGetCallSites(64);
8377
+ for (const s of nativeSites) {
8378
+ if (!s)
8379
+ continue;
8380
+ const rawScript = s.scriptName || "";
8381
+ const fnName = s.functionName || "";
8382
+ frames.push({
8383
+ filePath: normalizeScriptName(rawScript),
8384
+ fnName,
8385
+ isEval: !rawScript && (fnName === "eval" || fnName === "anonymous"),
8386
+ });
8387
+ }
8388
+ }
8389
+ catch {
8390
+ // ignore
8391
+ }
8392
+ }
8393
+ return frames;
8394
+ }
8395
+ /**
8396
+ * Extracts verified caller information by inspecting the ENTIRE active call stack.
8397
+ * Immune to `Error.prepareStackTrace` hijacking AND `//# sourceURL` spoofing:
8398
+ * even if an attacker injects a fake frame via `new Function("//# sourceURL=...")`,
8399
+ * the attacker's own `node_modules/...` frame remains on the call stack and is detected.
8400
+ */
8401
+ function getVerifiedCallerInfo() {
8402
+ const frames = captureNativeFrames();
8403
+ let immediateCallerRoot;
8404
+ let immediateCallerFile = "";
8405
+ for (let i = 0; i < frames.length; i++) {
8406
+ const { filePath, isEval } = frames[i];
8407
+ if (isEval) {
8408
+ return {
8409
+ root: undefined,
8410
+ isUntrusted: true,
8411
+ callerFile: filePath || "<eval>",
8412
+ };
8413
+ }
8414
+ if (!filePath)
8949
8415
  continue;
8950
- const filePath = match[1];
8951
- if (!filePath || filePath === "native" || filePath === "node:fs" || filePath === "fs")
8416
+ if (filePath.startsWith("node:") ||
8417
+ filePath.startsWith("bun:") ||
8418
+ filePath === "native" ||
8419
+ filePath.includes("[eval]")) {
8952
8420
  continue;
8953
- // Skip internal engine files to locate the user/plugin caller
8421
+ }
8422
+ // Skip XyPriss internal engine frames
8954
8423
  if (isEngineCorePath(filePath)) {
8955
8424
  continue;
8956
8425
  }
8957
- if (line.includes("at get [") ||
8958
- line.includes("at getStrict (") ||
8959
- line.includes("PluginAPI.") ||
8960
- line.includes("Plugin."))
8426
+ // Skip CLI TypeScript loaders (tsx / ts-node) at the bottom of the stack
8427
+ if (isRuntimeLoaderPath(filePath)) {
8961
8428
  continue;
8962
- callerFilePath = filePath;
8963
- break;
8429
+ }
8430
+ const root = identifyProjectRoot(filePath);
8431
+ // If ANY frame in the call chain originates from an undeclared/untrusted node_modules package,
8432
+ // reject the entire operation immediately (defeats //# sourceURL wrapper functions).
8433
+ if (!root) {
8434
+ return {
8435
+ root: undefined,
8436
+ isUntrusted: true,
8437
+ callerFile: filePath,
8438
+ };
8439
+ }
8440
+ if (!immediateCallerRoot) {
8441
+ immediateCallerRoot = root;
8442
+ immediateCallerFile = filePath;
8443
+ }
8964
8444
  }
8965
- if (!callerFilePath)
8966
- return getPrimaryProjectRoot();
8967
- const root = identifyProjectRoot(callerFilePath);
8968
- return root;
8445
+ if (immediateCallerRoot) {
8446
+ return {
8447
+ root: immediateCallerRoot,
8448
+ isUntrusted: false,
8449
+ callerFile: immediateCallerFile,
8450
+ };
8451
+ }
8452
+ return {
8453
+ root: getPrimaryProjectRoot(),
8454
+ isUntrusted: false,
8455
+ callerFile: "",
8456
+ };
8457
+ }
8458
+ /**
8459
+ * Retrieves the project root of the code currently executing by analyzing the native V8 call stack.
8460
+ */
8461
+ function getCallerProjectRoot() {
8462
+ const info = getVerifiedCallerInfo();
8463
+ if (info.isUntrusted) {
8464
+ return undefined;
8465
+ }
8466
+ return info.root;
8969
8467
  }
8970
8468
  /**
8971
8469
  * Loads and cleans a XyPriss configuration file (JSON or JSONC).
@@ -9295,8 +8793,11 @@ class EnvApi {
9295
8793
  set(key, value) {
9296
8794
  this.validateKey(key);
9297
8795
  this.validateValue(key, value);
9298
- const store = this.getStoreForCaller();
9299
- store[key] = value;
8796
+ const root = this.resolveAuthorizedRoot();
8797
+ if (!root) {
8798
+ return;
8799
+ }
8800
+ this.runner.runSync("env", "set", [key, value], { root });
9300
8801
  // Keep process.env in sync for whitelisted keys and framework keys to maintain system stability.
9301
8802
  // Issue #43: Ensures internal components and child processes have immediate access to
9302
8803
  // framework configuration without triggering proxy descriptor violations under strict runtimes (Bun).
@@ -9327,8 +8828,11 @@ class EnvApi {
9327
8828
  * __sys__.__env__.delete("CI_DEPLOY_TOKEN");
9328
8829
  */
9329
8830
  delete(key) {
9330
- const store = this.getStoreForCaller();
9331
- delete store[key];
8831
+ const root = this.resolveAuthorizedRoot();
8832
+ if (!root) {
8833
+ return;
8834
+ }
8835
+ this.runner.runSync("env", "delete", [key], { root });
9332
8836
  if (this.whitelistedFields.has(key) ||
9333
8837
  key.startsWith("XY_") ||
9334
8838
  key.startsWith("XYPRISS_") ||
@@ -9345,12 +8849,15 @@ class EnvApi {
9345
8849
  }
9346
8850
  }
9347
8851
  get(key, defaultValue) {
8852
+ const root = this.resolveAuthorizedRoot();
8853
+ if (!root) {
8854
+ return defaultValue;
8855
+ }
9348
8856
  if (key === "__root__") {
9349
- return (this.isDynamic ? getCallerProjectRoot() : null) || this.runner.getRoot();
8857
+ return root;
9350
8858
  }
9351
- const store = this.getStoreForCaller();
9352
- const value = store[key];
9353
- return value !== undefined ? value : defaultValue;
8859
+ const res = this.runner.runSync("env", "get", [key], { root });
8860
+ return res?.found && res.value !== undefined ? res.value : defaultValue;
9354
8861
  }
9355
8862
  /**
9356
8863
  * Reads a variable from the secure internal store for a specific root.
@@ -9369,8 +8876,8 @@ class EnvApi {
9369
8876
  if (key === "__root__") {
9370
8877
  return root;
9371
8878
  }
9372
- const store = this.getStoreForCaller(root);
9373
- return store[key];
8879
+ const res = this.runner.runSync("env", "get", [key], { root });
8880
+ return res?.found ? res.value : undefined;
9374
8881
  }
9375
8882
  /**
9376
8883
  * Reads a required variable from the secure internal store and throws if
@@ -9400,15 +8907,7 @@ class EnvApi {
9400
8907
  * };
9401
8908
  */
9402
8909
  getStrict(key, options) {
9403
- if (key === "__root__") {
9404
- const rootVal = (this.isDynamic ? getCallerProjectRoot() : null) || this.runner.getRoot();
9405
- if (!rootVal) {
9406
- throw new EnvAccessError(key, "missing");
9407
- }
9408
- return rootVal;
9409
- }
9410
- const store = this.getStoreForCaller();
9411
- const value = store[key];
8910
+ const value = this.get(key);
9412
8911
  if (value === undefined) {
9413
8912
  throw new EnvAccessError(key, "missing");
9414
8913
  }
@@ -9432,8 +8931,12 @@ class EnvApi {
9432
8931
  * const betaEnabled = __sys__.__env__.has("ENABLE_BETA_UI");
9433
8932
  */
9434
8933
  has(key) {
9435
- const store = this.getStoreForCaller();
9436
- return store[key] !== undefined;
8934
+ const root = this.resolveAuthorizedRoot();
8935
+ if (!root) {
8936
+ return false;
8937
+ }
8938
+ const res = this.runner.runSync("env", "has", [key], { root });
8939
+ return Boolean(res?.found);
9437
8940
  }
9438
8941
  /**
9439
8942
  * Returns a frozen, point-in-time snapshot of stored variables.
@@ -9460,7 +8963,12 @@ class EnvApi {
9460
8963
  * logger.debug("Env snapshot", { count: Object.keys(full).length });
9461
8964
  */
9462
8965
  all(options) {
9463
- const store = this.getStoreForCaller();
8966
+ const root = this.resolveAuthorizedRoot();
8967
+ if (!root) {
8968
+ return Object.freeze({});
8969
+ }
8970
+ const res = this.runner.runSync("env", "all", [], { root });
8971
+ const store = res?.secrets || {};
9464
8972
  if (options?.keys && options.keys.length > 0) {
9465
8973
  const subset = {};
9466
8974
  for (const key of options.keys) {
@@ -9545,7 +9053,7 @@ class EnvApi {
9545
9053
  const callerRoot = getCallerProjectRoot();
9546
9054
  const hostRoot = this.runner.getRoot();
9547
9055
  if (callerRoot && callerRoot !== hostRoot && !isCoreFrameworkPath(callerRoot)) {
9548
- logger$2.warn("security", `Blocked unauthorized attempt by third-party plugin at '${callerRoot}' to configure Environment Security Shield.`);
9056
+ logger$1.warn("security", `Blocked unauthorized attempt by third-party plugin at '${callerRoot}' to configure Environment Security Shield.`);
9549
9057
  return;
9550
9058
  }
9551
9059
  this[XY_ENV_CONFIGURE_SHIELD](config);
@@ -9604,57 +9112,30 @@ class EnvApi {
9604
9112
  }
9605
9113
  }
9606
9114
  // -------------------------------------------------------------------------
9607
- // Private — store access
9115
+ // Private — Zero-Trust Caller Verification (V8 C++ CallSites + libSynapx)
9608
9116
  // -------------------------------------------------------------------------
9609
9117
  /**
9610
- * Returns the internal store, throwing {@link EnvStoreError} if it has not
9611
- * yet been initialised.
9612
- *
9613
- * SECURITY: This is the single point of store access. Every read and write
9614
- * method must go through here — never access `globalThis[XY_ENV_STORE_KEY]`
9615
- * directly outside this method.
9118
+ * Resolves the authorized project root for the current caller using native V8 C++ CallSites.
9616
9119
  *
9617
- * Eliminating the `?? process.env` fallback is intentional. A silent
9618
- * fallback to `process.env` during the bootstrap race window would bypass
9619
- * the Shield and leak values without any warning. A thrown error is
9620
- * immediately visible during development and integration testing.
9120
+ * SECURITY POLICY:
9121
+ * - If the caller originates from an undeclared `node_modules/` dependency or dynamic `eval` / `new Function`,
9122
+ * `callerInfo.isUntrusted` is true and this method returns `null` (NEVER falling back to `this.runner.getRoot()`).
9123
+ * - Zero secrets are stored in JavaScript RAM; all queries go through `this.runner.runSync("env", ...)` (`libSynapx`).
9621
9124
  *
9622
9125
  * @internal
9623
- * @throws {EnvStoreError}
9624
- */
9625
- requireStoreMap() {
9626
- const storeMap = getInternalProjectEnvs();
9627
- if (!storeMap) {
9628
- throw new EnvStoreError();
9629
- }
9630
- return storeMap;
9631
- }
9632
- getStoreForCaller(callerRoot) {
9633
- const storeMap = this.requireStoreMap();
9634
- // 🛡️ Security & Scope Policy (Sandboxing):
9635
- // 1. If an explicit root is provided, use it.
9636
- // 2. Fallback to dynamic project discovery based on the caller's stack (Restricted Context) if enabled.
9637
- // 3. Fallback to this EnvApi instance's pinned runner root (System Baseline/Forced root).
9638
- const root = callerRoot ||
9639
- (this.isDynamic ? getCallerProjectRoot() : null) ||
9640
- this.runner.getRoot() ||
9641
- getCallerProjectRoot();
9642
- if (!root)
9643
- return {};
9644
- let store = storeMap.get(root);
9645
- if (!store) {
9646
- // Dynamic loading for projects/plugins not encountered during bootstrap.
9647
- // Under Zero-Trust, all environment secrets must transit through libXESS IPC.
9648
- const envData = {};
9649
- const ipcSecrets = XessIpcClient.fetchSecretsSync(root);
9650
- for (const key in ipcSecrets) {
9651
- envData[key] = ipcSecrets[key];
9652
- }
9653
- // Cache the loaded env for this project
9654
- storeMap.set(root, envData);
9655
- store = envData;
9126
+ */
9127
+ resolveAuthorizedRoot(explicitRoot) {
9128
+ if (explicitRoot) {
9129
+ return explicitRoot;
9130
+ }
9131
+ const callerInfo = getVerifiedCallerInfo();
9132
+ if (callerInfo.isUntrusted) {
9133
+ return null;
9134
+ }
9135
+ if (this.isDynamic && callerInfo.root) {
9136
+ return callerInfo.root;
9656
9137
  }
9657
- return store;
9138
+ return this.runner.getRoot() || callerInfo.root || null;
9658
9139
  }
9659
9140
  // -------------------------------------------------------------------------
9660
9141
  // Private — validation
@@ -9775,16 +9256,7 @@ class EnvApi {
9775
9256
  }
9776
9257
  // Emit one warning per unique blocked key.
9777
9258
  if (!warnedKeys.has(prop)) {
9778
- const storeMap = getInternalProjectEnvs();
9779
- let isSilent = target["XYPRISS_ENV_SHIELD"] === "silent";
9780
- if (storeMap) {
9781
- for (const env of storeMap.values()) {
9782
- if (env["XYPRISS_ENV_SHIELD"] === "silent") {
9783
- isSilent = true;
9784
- break;
9785
- }
9786
- }
9787
- }
9259
+ const isSilent = target["XYPRISS_ENV_SHIELD"] === "silent";
9788
9260
  if (!isSilent) {
9789
9261
  process.stderr.write(`\x1b[33m[SECURITY]\x1b[0m ` +
9790
9262
  `Direct access to process.env["${prop}"] is blocked. ` +
@@ -16432,7 +15904,7 @@ class XyPrissXHSC extends XyPrissFS {
16432
15904
  enumerable: true,
16433
15905
  configurable: false,
16434
15906
  });
16435
- logger$2.debug("security", `Plugin ${pluginId} authorized. Workspace root: ${resolvedRoot} (Context: ${callerRoot})`);
15907
+ logger$1.debug("security", `Plugin ${pluginId} authorized. Workspace root: ${resolvedRoot} (Context: ${callerRoot})`);
16436
15908
  this._pluginMap.set(cacheKey, instance);
16437
15909
  return instance;
16438
15910
  }
@@ -16440,7 +15912,7 @@ class XyPrissXHSC extends XyPrissFS {
16440
15912
  // Void Sandbox — plugin non autorisé dans la config
16441
15913
  const voidPath = path__default$1.join(generateXUserTmpDir(), "void", "sandbox", pluginId.replace(/[^a-zA-Z0-9-]/g, "_"));
16442
15914
  this.fs.mkdir(voidPath, { parents: true });
16443
- logger$2.warn("security", `Plugin ${pluginId} requested workspace but was not explicitly authorized in config. Assigned implicit Void Sandbox (${voidPath}).`);
15915
+ logger$1.warn("security", `Plugin ${pluginId} requested workspace but was not explicitly authorized in config. Assigned implicit Void Sandbox (${voidPath}).`);
16444
15916
  return undefined;
16445
15917
  }
16446
15918
  }
@@ -16541,41 +16013,24 @@ if (typeof globalThis !== "undefined") {
16541
16013
  tempDir = path__default$1.dirname(tempDir);
16542
16014
  }
16543
16015
  }
16544
- // Load environment variables for each project hierarchy independently
16545
- const projectEnvs = new Map();
16546
- // Enforce libXESS Bipolar Shield as strictly mandatory
16547
- if (!XessIpcClient.isShielded(foundRoot)) {
16016
+ // Enforce libXESS Bipolar Shield via libSynapx (Go-to-Go Vault verification, zero secrets in JS RAM)
16017
+ const synapx = SynapxClient.getInstance();
16018
+ synapx.ensureDaemon();
16019
+ let envStatus = null;
16020
+ try {
16021
+ envStatus = synapx.callSync("env", "status", [], { root: foundRoot });
16022
+ }
16023
+ catch {
16024
+ envStatus = null;
16025
+ }
16026
+ if (!envStatus?.shielded) {
16548
16027
  const err = new XessShieldRequiredError();
16549
16028
  const l = new QuickLogger("XHSC");
16550
16029
  l.error(`[XyPriss Security Violation] ${err.message}`);
16551
16030
  throw err;
16552
16031
  }
16553
- const ipcSecrets = XessIpcClient.fetchSecretsSync(foundRoot);
16554
- // Process each project found in the hierarchy
16555
- for (const projectPath of projects) {
16556
- const envData = {};
16557
- if (projectPath === foundRoot) {
16558
- for (const key in ipcSecrets) {
16559
- envData[key] = ipcSecrets[key];
16560
- }
16561
- }
16562
- else {
16563
- // For descendant sub-projects: if an .env exists on disk (canary decoy),
16564
- // authentic secrets MUST be fetched from libXESS IPC. No silent fallback.
16565
- const subEnv = path__default$1.join(projectPath, ".env");
16566
- if (fs__default$1.existsSync(subEnv)) {
16567
- const projectSecrets = XessIpcClient.fetchSecretsSync(projectPath);
16568
- for (const key in projectSecrets) {
16569
- envData[key] = projectSecrets[key];
16570
- }
16571
- }
16572
- }
16573
- projectEnvs.set(projectPath, envData);
16574
- }
16575
- // Initialize the internal secure store as a Map of project environments in module closure
16576
- setInternalProjectEnvs(projectEnvs);
16577
- const primaryEnv = projectEnvs.get(foundRoot) || {};
16578
- const defaultPort = parseInt(primaryEnv["PORT"] || "3000");
16032
+ const defaultPort = parseInt(envStatus.port || "3000", 10) || 3000;
16033
+ const defaultMode = envStatus.mode || "development";
16579
16034
  // Read xypriss.config.jsonc or xypriss.config.json early to apply XESS configuration declaratively
16580
16035
  let earlyXessConfig = null;
16581
16036
  try {
@@ -16599,7 +16054,7 @@ if (typeof globalThis !== "undefined") {
16599
16054
  __root__: foundRoot,
16600
16055
  __port__: defaultPort,
16601
16056
  __PORT__: defaultPort,
16602
- __mode__: primaryEnv["NODE_ENV"] || "development",
16057
+ __mode__: defaultMode,
16603
16058
  });
16604
16059
  // Apply declarative XESS early configuration if found
16605
16060
  let earlyConfig = null;
@@ -16661,7 +16116,7 @@ class MetaConfigRunner {
16661
16116
  result.catch(this.handleFatalError.bind(this, metaPath));
16662
16117
  }
16663
16118
  }
16664
- logger$2.debug("server", `Executed meta file: ${metaPath}`);
16119
+ logger$1.debug("server", `Executed meta file: ${metaPath}`);
16665
16120
  })
16666
16121
  .catch(this.handleFatalError.bind(this, metaPath));
16667
16122
  }
@@ -16701,7 +16156,7 @@ class MetaConfigRunner {
16701
16156
  }
16702
16157
  }
16703
16158
  handleFatalError(metaPath, error) {
16704
- logger$2.error("server", `FATAL: Failed to execute meta file ${metaPath}: ${error.message || error}`);
16159
+ logger$1.error("server", `FATAL: Failed to execute meta file ${metaPath}: ${error.message || error}`);
16705
16160
  // Terminate process securely via system API
16706
16161
  if (globalThis.__sys__ && typeof globalThis.__sys__.exit === "function") {
16707
16162
  globalThis.__sys__.exit(1);
@@ -16733,19 +16188,19 @@ class ConfigLoader {
16733
16188
  return;
16734
16189
  this.isConfigApplied = true;
16735
16190
  const root = getCallerProjectRoot() || __sys__$1.__root__;
16736
- logger$2.debug("server", `ConfigLoader: Initializing discovery from root: ${root}`);
16191
+ logger$1.debug("server", `ConfigLoader: Initializing discovery from root: ${root}`);
16737
16192
  const configFiles = [];
16738
16193
  // Only look for config at the absolute project root (preferring .jsonc)
16739
16194
  for (const name of ["xypriss.config.jsonc", "xypriss.config.json"]) {
16740
16195
  const potentialConfig = this.sys.path.join(root, name);
16741
16196
  if (this.sys.fs.exist(potentialConfig)) {
16742
- logger$2.debug("server", `ConfigLoader: Found configuration file: ${potentialConfig}`);
16197
+ logger$1.debug("server", `ConfigLoader: Found configuration file: ${potentialConfig}`);
16743
16198
  configFiles.push(potentialConfig);
16744
16199
  break; // Stop after first match in root
16745
16200
  }
16746
16201
  }
16747
16202
  if (configFiles.length === 0) {
16748
- logger$2.debug("server", `ConfigLoader: No configuration file found in ${root}`);
16203
+ logger$1.debug("server", `ConfigLoader: No configuration file found in ${root}`);
16749
16204
  }
16750
16205
  // Process only the root configuration
16751
16206
  for (const configPath of configFiles) {
@@ -16765,10 +16220,10 @@ class ConfigLoader {
16765
16220
  const rawConfig = JsonUtils.parse(rawContent);
16766
16221
  // Load package.json if not already loaded
16767
16222
  this.loadPackageJson(projectRoot);
16768
- logger$2.debug("server", `ConfigLoader: Resolving references for ${this.sys.path.basename(configPath)}`);
16223
+ logger$1.debug("server", `ConfigLoader: Resolving references for ${this.sys.path.basename(configPath)}`);
16769
16224
  if (__sys__$1?.__env__) {
16770
16225
  const envSnapshot = __sys__$1.__env__.all();
16771
- logger$2.debug("server", `ConfigLoader: Env keys available in store for ${projectRoot}: ${Object.keys(envSnapshot).join(", ")}`);
16226
+ logger$1.debug("server", `ConfigLoader: Env keys available in store for ${projectRoot}: ${Object.keys(envSnapshot).join(", ")}`);
16772
16227
  }
16773
16228
  const envProvider = __sys__$1?.__env__
16774
16229
  ? {
@@ -16791,11 +16246,11 @@ class ConfigLoader {
16791
16246
  const config = this.resolveRefs(rawConfig, envProvider);
16792
16247
  if (!config)
16793
16248
  return;
16794
- logger$2.debug("server", `ConfigLoader: Applied configuration from: ${this.sys.path.relative(projectRoot, configPath)}`);
16249
+ logger$1.debug("server", `ConfigLoader: Applied configuration from: ${this.sys.path.relative(projectRoot, configPath)}`);
16795
16250
  // Apply __sys__ config if present
16796
16251
  if (config?.$vars) {
16797
16252
  if (__sys__$1) {
16798
- logger$2.debug("server", `ConfigLoader: Updating system variables with $vars: ${JSON.stringify(config.$vars)}`);
16253
+ logger$1.debug("server", `ConfigLoader: Updating system variables with $vars: ${JSON.stringify(config.$vars)}`);
16799
16254
  __sys__$1.vars.update(config.$vars);
16800
16255
  }
16801
16256
  }
@@ -16822,7 +16277,7 @@ class ConfigLoader {
16822
16277
  }
16823
16278
  }
16824
16279
  if (Object.keys(serverOptionsToApply).length > 0) {
16825
- logger$2.debug("server", `ConfigLoader: Merging discovered server configuration into Configs`);
16280
+ logger$1.debug("server", `ConfigLoader: Merging discovered server configuration into Configs`);
16826
16281
  ConfigurationManager.merge(serverOptionsToApply);
16827
16282
  }
16828
16283
  // Process internal configuration
@@ -16862,7 +16317,7 @@ class ConfigLoader {
16862
16317
  __mode__: __sys__$1.__env__.mode,
16863
16318
  });
16864
16319
  __sys__$1[XY_XHSC_REGISTER_FS](pluginId, specializedFS);
16865
- logger$2.debug("server", `Specialized filesystem mapped: ${pluginId} -> ${resolvedFsPath} (from: ${rawPath})`);
16320
+ logger$1.debug("server", `Specialized filesystem mapped: ${pluginId} -> ${resolvedFsPath} (from: ${rawPath})`);
16866
16321
  }
16867
16322
  }
16868
16323
  // 2. Execute additional meta logic if __meta__ is present
@@ -16890,7 +16345,7 @@ class ConfigLoader {
16890
16345
  }
16891
16346
  if (allPermissions.length > 0) {
16892
16347
  __sys__$1.vars.set("pluginPermissions", allPermissions);
16893
- logger$2.debug("server", `Loaded ${allPermissions.length} plugin permission rules from configuration`);
16348
+ logger$1.debug("server", `Loaded ${allPermissions.length} plugin permission rules from configuration`);
16894
16349
  }
16895
16350
  }
16896
16351
  /**
@@ -16926,7 +16381,7 @@ class ConfigLoader {
16926
16381
  this.packageJson = JSON.parse(this.sys.fs.readSync(pkgPath));
16927
16382
  }
16928
16383
  catch (error) {
16929
- logger$2.warn("server", "Failed to parse package.json for configuration resolution");
16384
+ logger$1.warn("server", "Failed to parse package.json for configuration resolution");
16930
16385
  }
16931
16386
  }
16932
16387
  }
@@ -27718,11 +27173,6 @@ class EngineManager {
27718
27173
  // Zero CLI Flags: 100% encrypted single descriptor argument
27719
27174
  const args = [configPath];
27720
27175
  const internalSig = getInternalSignature();
27721
- let sessionKey = "";
27722
- try {
27723
- sessionKey = XessIpcClient.getActiveSessionKey();
27724
- }
27725
- catch { }
27726
27176
  this.logger.debug("server", `Starting XHSC engine: ${args.join(" ")}`);
27727
27177
  const binaryPath = this.runner.getBinaryPath();
27728
27178
  const child = spawn(binaryPath, args, {
@@ -27730,7 +27180,6 @@ class EngineManager {
27730
27180
  detached: true,
27731
27181
  env: {
27732
27182
  ...process.env,
27733
- ...(sessionKey ? { XYPRISS_XESS_SESSION_KEY: sessionKey } : {}),
27734
27183
  ...(internalSig
27735
27184
  ? { XYPRISS_INTERNAL_TOKEN: internalSig }
27736
27185
  : {}),
@@ -28095,7 +27544,7 @@ class RequestProcessor {
28095
27544
  });
28096
27545
  }
28097
27546
  catch (error) {
28098
- logger$2.warn("other", `High-performance path failed for ${req.method} ${req.path}:`, error.message);
27547
+ logger$1.warn("other", `High-performance path failed for ${req.method} ${req.path}:`, error.message);
28099
27548
  return await this.handleStandardPath(req, res, next, requestId, classification);
28100
27549
  }
28101
27550
  }
@@ -28143,7 +27592,7 @@ class RequestProcessor {
28143
27592
  next();
28144
27593
  }
28145
27594
  catch (error) {
28146
- logger$2.warn("other", `Fast path failed for ${req.method} ${req.path}:`, error.message);
27595
+ logger$1.warn("other", `Fast path failed for ${req.method} ${req.path}:`, error.message);
28147
27596
  return await this.handleStandardPath(req, res, next, requestId, classification);
28148
27597
  }
28149
27598
  }
@@ -28187,7 +27636,7 @@ class RequestProcessor {
28187
27636
  next();
28188
27637
  }
28189
27638
  catch (error) {
28190
- logger$2.error("other", `Standard path failed for ${req.method} ${req.path}:`, error.message);
27639
+ logger$1.error("other", `Standard path failed for ${req.method} ${req.path}:`, error.message);
28191
27640
  next(error);
28192
27641
  }
28193
27642
  }
@@ -28223,10 +27672,10 @@ class RequestProcessor {
28223
27672
  await this.dependencies.cacheManager
28224
27673
  .getCache()
28225
27674
  .set(cacheKey, data, { ttl });
28226
- logger$2.debug("other", `CACHED (${pathType}): ${cacheKey} (TTL: ${ttl}ms)`);
27675
+ logger$1.debug("other", `CACHED (${pathType}): ${cacheKey} (TTL: ${ttl}ms)`);
28227
27676
  }
28228
27677
  catch (error) {
28229
- logger$2.error("other", "Cache set error:", error.message);
27678
+ logger$1.error("other", "Cache set error:", error.message);
28230
27679
  }
28231
27680
  });
28232
27681
  return originalJson(data);
@@ -28246,7 +27695,7 @@ class RouteManager {
28246
27695
  * Add all HTTP methods with caching support to the XyPriss app
28247
27696
  */
28248
27697
  addMethods() {
28249
- logger$2.debug("routes", "Adding HTTP methods with caching support...");
27698
+ logger$1.debug("routes", "Adding HTTP methods with caching support...");
28250
27699
  this.addCacheManagementMethods();
28251
27700
  // logger.debug( "routes","HTTP methods added successfully");
28252
27701
  }
@@ -31855,7 +31304,7 @@ function createSafeJsonMiddleware(options = {}) {
31855
31304
  catch (error) {
31856
31305
  if (opts.logCircularRefs &&
31857
31306
  error.message.includes("circular")) {
31858
- logger$2.debug("server", "🔄 Circular reference detected, using safe serialization:", {
31307
+ logger$1.debug("server", "🔄 Circular reference detected, using safe serialization:", {
31859
31308
  url: req.url,
31860
31309
  method: req.method,
31861
31310
  error: error.message,
@@ -31868,7 +31317,7 @@ function createSafeJsonMiddleware(options = {}) {
31868
31317
  return originalJson(parsedResult);
31869
31318
  }
31870
31319
  catch (safeError) {
31871
- logger$2.debug("server", "❌ Safe JSON serialization failed:", safeError);
31320
+ logger$1.debug("server", "❌ Safe JSON serialization failed:", safeError);
31872
31321
  return originalJson({
31873
31322
  error: "Serialization failed",
31874
31323
  message: "Unable to serialize response object",
@@ -32592,7 +32041,7 @@ class CacheManager {
32592
32041
  await this.cache.connect();
32593
32042
  }
32594
32043
  catch (error) {
32595
- logger$2.error("cache", "Cache initialization failed:", error);
32044
+ logger$1.error("cache", "Cache initialization failed:", error);
32596
32045
  throw error;
32597
32046
  }
32598
32047
  }
@@ -32653,13 +32102,13 @@ class CacheManager {
32653
32102
  });
32654
32103
  }
32655
32104
  catch (error) {
32656
- logger$2.warn("cache", `Failed to warm up ${item.key}:`, error.message);
32105
+ logger$1.warn("cache", `Failed to warm up ${item.key}:`, error.message);
32657
32106
  }
32658
32107
  });
32659
32108
  await Promise.all(warmupPromises);
32660
32109
  }
32661
32110
  catch (error) {
32662
- logger$2.warn("cache", "Cache warmup failed:", error.message);
32111
+ logger$1.warn("cache", "Cache warmup failed:", error.message);
32663
32112
  }
32664
32113
  }
32665
32114
  /**
@@ -32747,7 +32196,7 @@ class WorkerPoolComponent {
32747
32196
  }
32748
32197
  }
32749
32198
  initialize() {
32750
- logger$2.debug("other", "Initializing WorkerPool delegation to XHSC (Go Core)...");
32199
+ logger$1.debug("other", "Initializing WorkerPool delegation to XHSC (Go Core)...");
32751
32200
  this.addWorkerPoolMethods();
32752
32201
  }
32753
32202
  addWorkerPoolMethods() {
@@ -32766,7 +32215,7 @@ class WorkerPoolComponent {
32766
32215
  });
32767
32216
  }
32768
32217
  else {
32769
- logger$2.warn("cluster", "WorkerPool task executed locally (XHSC disabled/Master)");
32218
+ logger$1.warn("cluster", "WorkerPool task executed locally (XHSC disabled/Master)");
32770
32219
  // Local execution fallback if needed, or just log
32771
32220
  }
32772
32221
  };
@@ -32796,7 +32245,7 @@ class WorkerPoolComponent {
32796
32245
  app.executeTask(task);
32797
32246
  };
32798
32247
  app.isWorkerPoolEnabled = () => true;
32799
- logger$2.debug("other", "Worker pool delegated methods added to app");
32248
+ logger$1.debug("other", "Worker pool delegated methods added to app");
32800
32249
  }
32801
32250
  shutdown() {
32802
32251
  // delegated to Go