xypriss 9.14.22 → 9.14.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -6,11 +6,14 @@ var crypto$1 = require('crypto');
6
6
  var node_child_process = require('node:child_process');
7
7
  var fs = require('node:fs');
8
8
  var node_url = require('node:url');
9
+ var tslib_es6_js = require('/home/idevo/Documents/projects/XyPriss/node_modules/.xfpm/vstore/@rollup+plugin-typescript@11.1.6/node_modules/tslib/tslib.es6.js');
9
10
  var net = require('node:net');
10
11
  var node_worker_threads = require('node:worker_threads');
11
- var os = require('node:os');
12
12
  var fs$1 = require('fs');
13
13
  var path$1 = require('path');
14
+ var util = require('node:util');
15
+ var os = require('node:os');
16
+ var crypto$2 = require('node:crypto');
14
17
  var nehoid = require('nehoid');
15
18
  var net$1 = require('net');
16
19
  var reliantType = require('reliant-type');
@@ -21,7 +24,6 @@ var strulink = require('strulink');
21
24
  var promises = require('node:fs/promises');
22
25
  var http = require('http');
23
26
  var stream = require('stream');
24
- var crypto$2 = require('node:crypto');
25
27
  var async_hooks = require('async_hooks');
26
28
 
27
29
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -962,7 +964,7 @@ class Logger {
962
964
  // Module helpers
963
965
  // ─────────────────────────────────────────────
964
966
  /** Shared singleton — ready to use immediately. */
965
- const logger$2 = Logger.getInstance();
967
+ const logger$1 = Logger.getInstance();
966
968
  /** Configure and return the singleton logger. */
967
969
  function initializeLogger(config) {
968
970
  return Logger.getInstance(config);
@@ -1084,7 +1086,7 @@ const defaultHelmetOpts = {
1084
1086
  };
1085
1087
  // Log a warning if the development profile is active
1086
1088
  if (isDev) {
1087
- logger$2.warn("security", "Development security profile active. CSP, COEP, and CORP headers are relaxed for local development. Learn more or customize: https://xypriss.nehonix.com/docs/security/enhanced-csp-configuration#development-security-profile-automatic");
1089
+ logger$1.warn("security", "Development security profile active. CSP, COEP, and CORP headers are relaxed for local development. Learn more or customize: https://xypriss.nehonix.com/docs/security/enhanced-csp-configuration#development-security-profile-automatic");
1088
1090
  }
1089
1091
 
1090
1092
  const xemsKeyPlaceholder = "CHANGE_ME_TO_A_SECURE_32_CHAR_KEY";
@@ -3744,6 +3746,20 @@ let socket = null;
3744
3746
  let rxChunks = [];
3745
3747
  let rxBytesTotal = 0;
3746
3748
  let isHandshaked = false;
3749
+ let pendingDispatch = false;
3750
+
3751
+ function flushDispatch() {
3752
+ if (!socket || socket.destroyed || !isHandshaked) return;
3753
+ const reqLen = Atomics.load(int32, IDX_REQ_LEN);
3754
+ const reqBytes = uint8.subarray(DATA_OFFSET, DATA_OFFSET + reqLen);
3755
+
3756
+ const h = Buffer.alloc(6);
3757
+ h.writeUInt8(0x53, 0);
3758
+ h.writeUInt8(0x03, 1); // MSG_CALL
3759
+ h.writeUInt32BE(reqBytes.length, 2);
3760
+
3761
+ socket.write(Buffer.concat([h, reqBytes]));
3762
+ }
3747
3763
 
3748
3764
  function pushChunk(chunk) {
3749
3765
  rxChunks.push(chunk);
@@ -3829,6 +3845,10 @@ function connectSocket() {
3829
3845
  isHandshaked = true;
3830
3846
  try { socket.unref(); } catch {}
3831
3847
  parentPort.postMessage({ type: "READY" });
3848
+ if (pendingDispatch) {
3849
+ pendingDispatch = false;
3850
+ flushDispatch();
3851
+ }
3832
3852
  }
3833
3853
  } else if (header.type === 0x04) { // MSG_RESPONSE
3834
3854
  uint8.set(payload, DATA_OFFSET);
@@ -3857,24 +3877,16 @@ function connectSocket() {
3857
3877
 
3858
3878
  parentPort.on("message", (msg) => {
3859
3879
  if (msg.type === "DISPATCH") {
3860
- if (!socket || socket.destroyed || !isHandshaked) {
3861
- const errPayload = Buffer.from(JSON.stringify({ ok: false, err: "libSynapx worker socket disconnected" }));
3862
- uint8.set(errPayload, DATA_OFFSET);
3863
- Atomics.store(int32, IDX_RESP_LEN, errPayload.length);
3864
- Atomics.store(int32, IDX_STATUS, STATUS_ERROR);
3865
- Atomics.notify(int32, IDX_STATUS, 1);
3880
+ if (!socket || socket.destroyed) {
3881
+ pendingDispatch = true;
3882
+ connectSocket();
3866
3883
  return;
3867
3884
  }
3868
-
3869
- const reqLen = Atomics.load(int32, IDX_REQ_LEN);
3870
- const reqBytes = uint8.subarray(DATA_OFFSET, DATA_OFFSET + reqLen);
3871
-
3872
- const h = Buffer.alloc(6);
3873
- h.writeUInt8(0x53, 0);
3874
- h.writeUInt8(0x03, 1); // MSG_CALL
3875
- h.writeUInt32BE(reqBytes.length, 2);
3876
-
3877
- socket.write(Buffer.concat([h, reqBytes]));
3885
+ if (!isHandshaked) {
3886
+ pendingDispatch = true;
3887
+ return;
3888
+ }
3889
+ flushDispatch();
3878
3890
  }
3879
3891
  });
3880
3892
 
@@ -4015,345 +4027,365 @@ class SynapxSyncBridge {
4015
4027
  SynapxSyncBridge.instance = null;
4016
4028
 
4017
4029
  /**
4018
- * ANSI color codes for terminal output
4030
+ * **Config Syntax Parser**
4031
+ *
4032
+ * Handles resolution of dynamic references in configuration files:
4033
+ * - `&(env).KEY` : Environment variables
4034
+ * - `&(pkg).path` : package.json properties (dot-notation)
4035
+ * - `&(this).KEY` : Properties from the currently parsed object
4036
+ * - `&(const).KEY` : Build-time constants injected at construction
4037
+ * - `&(date).FMT` : Current date/time helpers (ISO, YEAR, MONTH, DAY, TS)
4038
+ * - `&(file).path` : Synchronous file content (use for secrets, certs, etc.)
4019
4039
  */
4020
- const ANSI = {
4021
- reset: "\x1b[0m",
4022
- bold: "\x1b[1m",
4023
- dim: "\x1b[2m",
4024
- // Foreground colors
4025
- black: "\x1b[30m",
4026
- yellow: "\x1b[33m",
4027
- blue: "\x1b[34m",
4028
- cyan: "\x1b[36m",
4029
- white: "\x1b[37m",
4030
- gray: "\x1b[90m",
4031
- // Bright foreground
4032
- brightRed: "\x1b[91m",
4033
- brightGreen: "\x1b[92m",
4034
- brightYellow: "\x1b[93m",
4035
- brightBlue: "\x1b[94m",
4036
- brightMagenta: "\x1b[95m",
4037
- brightCyan: "\x1b[96m",
4038
- // Background colors
4039
- bgRed: "\x1b[41m",
4040
- bgGreen: "\x1b[42m",
4041
- bgYellow: "\x1b[43m",
4042
- bgBlue: "\x1b[44m",
4043
- bgMagenta: "\x1b[45m",
4044
- bgCyan: "\x1b[46m",
4045
- };
4046
- const LOG_CONFIGS = {
4047
- info: {
4048
- icon: "ℹ️ ",
4049
- color: ANSI.brightCyan,
4050
- label: "INFO",
4051
- labelColor: `${ANSI.bgCyan}${ANSI.black}`,
4052
- },
4053
- success: {
4054
- icon: "✅",
4055
- color: ANSI.brightGreen,
4056
- label: "OK",
4057
- labelColor: `${ANSI.bgGreen}${ANSI.black}`,
4058
- },
4059
- warn: {
4060
- icon: "⚠️ ",
4061
- color: ANSI.brightYellow,
4062
- label: "WARN",
4063
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4064
- },
4065
- error: {
4066
- icon: "❌",
4067
- color: ANSI.brightRed,
4068
- label: "ERROR",
4069
- labelColor: `${ANSI.bgRed}${ANSI.white}`,
4070
- },
4071
- debug: {
4072
- icon: "-",
4073
- color: ANSI.gray,
4074
- label: "DEBUG",
4075
- labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
4076
- },
4077
- http: {
4078
- icon: "🌐",
4079
- color: ANSI.brightBlue,
4080
- label: "HTTP",
4081
- labelColor: `${ANSI.bgBlue}${ANSI.white}`,
4082
- },
4083
- swagger: {
4084
- icon: "🛡️ ",
4085
- color: ANSI.brightMagenta,
4086
- label: "SWAGGER",
4087
- labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
4088
- },
4089
- db: {
4090
- icon: "🗄️ ",
4091
- color: ANSI.yellow,
4092
- label: "DB",
4093
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4094
- },
4095
- auth: {
4096
- icon: "🔐",
4097
- color: ANSI.brightYellow,
4098
- label: "AUTH",
4099
- labelColor: `${ANSI.bgYellow}${ANSI.black}`,
4100
- },
4101
- };
4102
- const LEVEL_RANK = {
4103
- silent: 0,
4104
- error: 1,
4105
- warn: 2,
4106
- info: 3,
4107
- success: 3,
4108
- http: 3,
4109
- swagger: 3,
4110
- db: 3,
4111
- auth: 3,
4112
- debug: 4,
4113
- verbose: 5,
4040
+ // Date format tokens supported by &(date).TOKEN
4041
+ const DATE_TOKENS = {
4042
+ ISO: () => new Date().toISOString(),
4043
+ YEAR: () => String(new Date().getFullYear()),
4044
+ MONTH: () => String(new Date().getMonth() + 1).padStart(2, "0"),
4045
+ DAY: () => String(new Date().getDate()).padStart(2, "0"),
4046
+ TS: () => String(Date.now()),
4047
+ TIME: () => new Date().toTimeString().split(" ")[0], // HH:MM:SS
4114
4048
  };
4115
- class QuickLogger {
4116
- constructor(context) {
4117
- this.context = context;
4118
- }
4119
- // ─── Static factory ───────────────────────────────────────────────────────
4120
- static for(context) {
4121
- return new QuickLogger(context);
4049
+ // ---------------------------------------------------------------------------
4050
+ // Parser
4051
+ // ---------------------------------------------------------------------------
4052
+ class ConfigSyntaxParser {
4053
+ constructor(packageJson = null, envProvider = null, constants = {}, options = {}) {
4054
+ this.packageJson = packageJson;
4055
+ this.envProvider = envProvider;
4056
+ this.constants = constants;
4057
+ // LRU-style cache for getDeepValue on the same object reference
4058
+ this.deepValueCache = new WeakMap();
4059
+ this.fileBasePath = options.fileBasePath ?? process.cwd();
4060
+ this.maxPasses = options.maxPasses ?? 20;
4122
4061
  }
4123
- static shouldLog(level) {
4124
- const sys = getSysApi();
4125
- let isDebug = false;
4126
- if (sys?.__env__) {
4127
- isDebug =
4128
- sys.__env__.get("DEBUG") ||
4129
- sys.__env__.get("XYPRISS_DEBUG") ||
4130
- sys.__env__.get("DEBUG_FS");
4131
- }
4132
- else if (typeof process !== "undefined" && process.env) {
4133
- isDebug =
4134
- process.env.DEBUG ||
4135
- process.env.XYPRISS_DEBUG ||
4136
- process.env.DEBUG_FS;
4137
- }
4138
- if (isDebug) {
4139
- return true;
4140
- }
4141
- try {
4142
- const logging = ConfigurationManager.get("logging");
4143
- if (logging) {
4144
- if (logging.enabled === false) {
4145
- return false;
4146
- }
4147
- // Check logging.types overrides
4148
- if (level === "error" && logging.types?.errors === false)
4149
- return false;
4150
- if (level === "warn" && logging.types?.warnings === false)
4151
- return false;
4152
- if (level === "debug" && logging.types?.debug === false)
4153
- return false;
4154
- if (level === "debug" && logging.types?.debug === true)
4155
- return true;
4156
- // Check logging.level rank
4157
- const configuredLevel = (logging.level || "info").toLowerCase();
4158
- const configuredRank = LEVEL_RANK[configuredLevel] ?? 3;
4159
- const messageRank = LEVEL_RANK[level] ?? 3;
4160
- return messageRank <= configuredRank;
4062
+ // -------------------------------------------------------------------------
4063
+ // Public API — signatures intentionally unchanged
4064
+ // -------------------------------------------------------------------------
4065
+ /**
4066
+ * Resolves all dynamic references in a configuration object or string.
4067
+ * Non-string/array/object values are returned as-is.
4068
+ */
4069
+ resolve(obj, rootObj) {
4070
+ if (rootObj === undefined)
4071
+ rootObj = obj;
4072
+ if (typeof obj === "string")
4073
+ return this.resolveString(obj, rootObj);
4074
+ if (Array.isArray(obj))
4075
+ return obj.map((item) => this.resolve(item, rootObj));
4076
+ if (typeof obj === "object" && obj !== null) {
4077
+ const resolved = {};
4078
+ for (const key of Object.keys(obj)) {
4079
+ const resolvedKey = String(this.resolve(key, rootObj));
4080
+ resolved[resolvedKey] = this.resolve(obj[key], rootObj);
4161
4081
  }
4082
+ return resolved;
4162
4083
  }
4163
- catch { }
4164
- // Default ranking if no config: info level (rank 3)
4165
- const defaultRank = 3;
4166
- const messageRank = LEVEL_RANK[level] ?? 3;
4167
- return messageRank <= defaultRank;
4084
+ return obj; // number, boolean, null, undefined — pass through untouched
4168
4085
  }
4169
- // ─── Core log method ──────────────────────────────────────────────────────
4170
- log(level, ...args) {
4171
- if (!QuickLogger.shouldLog(level)) {
4172
- return;
4086
+ // -------------------------------------------------------------------------
4087
+ // Core resolution
4088
+ // -------------------------------------------------------------------------
4089
+ /**
4090
+ * Resolves dynamic references in a string, supporting chained || fallbacks.
4091
+ */
4092
+ resolveString(value, rootObj) {
4093
+ // Validate before any resolution to catch syntax errors even in unused fallbacks
4094
+ this.validateSyntax(value);
4095
+ // Matches: &(type).key || &(type).key || literal-fallback
4096
+ // Group 1 — type
4097
+ // Group 2 — key/path
4098
+ // Group 3 — remainder of the || chain
4099
+ // Separate simple types (env, const, date) from complex types (pkg, this, file)
4100
+ // to prevent over-matching separators like '.' or '-' in strings.
4101
+ const chainRegex = /&\((env|const|date)\)\.([\w\d_$]+)((?:\s*\|\|\s*(?:&\((?:[\w]+)\)\.[\w\d_./$]+(?:-[\w\d_./$]+)*|[^|,]+))*)|&\((pkg|this|file)\)\.([\w\d_/$][\w\d_./$]*(?:-[\w\d_./$]+)*)((?:\s*\|\|\s*(?:&\((?:[\w]+)\)\.[\w\d_./$]+(?:-[\w\d_./$]+)*|[^|,]+))*)/g;
4102
+ let result = value;
4103
+ let passes = 0;
4104
+ while (passes++ < this.maxPasses) {
4105
+ const prev = result;
4106
+ // Reset regex before each pass (global flag keeps lastIndex)
4107
+ chainRegex.lastIndex = 0;
4108
+ result = result.replace(chainRegex, (_match, type1, key1, chain1, type2, key2, chain2) => {
4109
+ const type = type1 || type2;
4110
+ const key = key1 || key2;
4111
+ const chain = chain1 || chain2;
4112
+ const val = this.getValue(type, key, rootObj);
4113
+ if (val !== undefined)
4114
+ return val;
4115
+ if (chain) {
4116
+ // Strip leading " || " and let the next pass handle it
4117
+ return chain.replace(/^\s*\|\|\s*/, "");
4118
+ }
4119
+ throw new Error(this.buildMissingError(type, key));
4120
+ });
4121
+ if (result === prev)
4122
+ break;
4173
4123
  }
4174
- const cfg = LOG_CONFIGS[level];
4175
- const timestamp = QuickLogger.showTimestamp
4176
- ? `${ANSI.dim}${ANSI.gray}${new Date().toISOString()}${ANSI.reset} `
4177
- : "";
4178
- const label = `${cfg.labelColor}${ANSI.bold} ${cfg.label} ${ANSI.reset}`;
4179
- const ctx = `${ANSI.dim}${ANSI.cyan}[${this.context}]${ANSI.reset}`;
4180
- // First arg gets the level color + icon, rest are passed raw so Node.js
4181
- // pretty-prints objects/arrays/Errors natively (no JSON.stringify needed).
4182
- const [first, ...rest] = args;
4183
- const prefix = `${timestamp}${label} ${ctx} ${cfg.color}${cfg.icon} ${String(first)}${ANSI.reset}`;
4184
- const consoleFn = level === "error"
4185
- ? console.error
4186
- : level === "warn"
4187
- ? console.warn
4188
- : console.log;
4189
- rest.length > 0 ? consoleFn(prefix, ...rest) : consoleFn(prefix);
4190
- }
4191
- // ─── Public methods ───────────────────────────────────────────────────────
4192
- info(...args) {
4193
- this.log("info", ...args);
4124
+ if (passes > this.maxPasses) {
4125
+ throw new Error(`ESYNC: Resolution did not stabilise after ${this.maxPasses} passes in "${value}". ` +
4126
+ `Possible circular reference.`);
4127
+ }
4128
+ this.validateSyntax(result);
4129
+ return result;
4194
4130
  }
4195
- success(...args) {
4196
- this.log("success", ...args);
4131
+ // -------------------------------------------------------------------------
4132
+ // Value retrieval
4133
+ // -------------------------------------------------------------------------
4134
+ /**
4135
+ * Dispatches value retrieval to the appropriate provider.
4136
+ */
4137
+ getValue(type, key, rootObj) {
4138
+ switch (type) {
4139
+ case "env":
4140
+ return this.getEnv(key);
4141
+ case "pkg":
4142
+ return this.getPkg(key);
4143
+ case "this":
4144
+ return this.getThis(key, rootObj);
4145
+ case "date":
4146
+ return this.getDate(key);
4147
+ case "file":
4148
+ return this.getFile(key);
4149
+ default:
4150
+ return undefined; // validateSyntax will catch this
4151
+ }
4197
4152
  }
4198
- warn(...args) {
4199
- this.log("warn", ...args);
4153
+ getEnv(key) {
4154
+ return this.envProvider?.has(key)
4155
+ ? this.envProvider.get(key)
4156
+ : undefined;
4200
4157
  }
4201
- error(...args) {
4202
- this.log("error", ...args);
4158
+ getPkg(key) {
4159
+ if (!this.packageJson)
4160
+ return undefined;
4161
+ const val = this.getDeepValue(this.packageJson, key);
4162
+ return val !== undefined ? String(val) : undefined;
4203
4163
  }
4204
- debug(...args) {
4205
- this.log("debug", ...args);
4164
+ getThis(key, rootObj) {
4165
+ if (rootObj === null || typeof rootObj !== "object")
4166
+ return undefined;
4167
+ const val = this.getDeepValue(rootObj, key);
4168
+ return val !== undefined ? String(val) : undefined;
4206
4169
  }
4207
- http(...args) {
4208
- this.log("http", ...args);
4170
+ getDate(token) {
4171
+ const upper = token.toUpperCase();
4172
+ return DATE_TOKENS[upper]?.();
4173
+ // Unknown date tokens fall through to the error handler
4209
4174
  }
4210
- swagger(...args) {
4211
- this.log("swagger", ...args);
4175
+ getFile(filePath) {
4176
+ try {
4177
+ const sys = getSysApi();
4178
+ // In XyPriss config, a leading / is often intended as project-root relative
4179
+ // especially when the separator dot consumes the '.' of './path'
4180
+ const cleanPath = filePath.startsWith("/")
4181
+ ? filePath.substring(1)
4182
+ : filePath;
4183
+ const resolved = sys.path.isAbsolute(cleanPath)
4184
+ ? cleanPath
4185
+ : sys.path.resolve(this.fileBasePath, cleanPath);
4186
+ return sys.fs.readSync(resolved).trim();
4187
+ }
4188
+ catch {
4189
+ return undefined; // triggers fallback chain or missing-key error
4190
+ }
4212
4191
  }
4213
- db(...args) {
4214
- this.log("db", ...args);
4192
+ // -------------------------------------------------------------------------
4193
+ // Deep value with caching
4194
+ // -------------------------------------------------------------------------
4195
+ /**
4196
+ * Retrieves a value from a nested object using dot notation.
4197
+ * Results are cached per object reference to avoid repeated traversal.
4198
+ */
4199
+ getDeepValue(obj, path) {
4200
+ // Check cache
4201
+ let pathMap = this.deepValueCache.get(obj);
4202
+ if (pathMap?.has(path))
4203
+ return pathMap.get(path);
4204
+ const parts = path.split(".");
4205
+ let current = obj;
4206
+ for (const part of parts) {
4207
+ if (current === null || typeof current !== "object") {
4208
+ current = undefined;
4209
+ break;
4210
+ }
4211
+ current = current[part];
4212
+ }
4213
+ // Store in cache
4214
+ if (!pathMap) {
4215
+ pathMap = new Map();
4216
+ this.deepValueCache.set(obj, pathMap);
4217
+ }
4218
+ pathMap.set(path, current);
4219
+ return current;
4215
4220
  }
4216
- auth(...args) {
4217
- this.log("auth", ...args);
4221
+ // -------------------------------------------------------------------------
4222
+ // Validation
4223
+ // -------------------------------------------------------------------------
4224
+ /**
4225
+ * Validates that no unresolved or malformed markers remain in the string.
4226
+ */
4227
+ validateSyntax(value) {
4228
+ if (!/&\(/.test(value))
4229
+ return;
4230
+ const malformedRegex = /&\((env|const|date)\)\.([\w\d_$]+)?|&\((pkg|this|file)\)\.([\w\d_/$][\w\d_./$]*(?:-[\w\d_./$]+)*)?/g;
4231
+ let match;
4232
+ while ((match = malformedRegex.exec(value)) !== null) {
4233
+ const [full, type1, key1, type2, key2] = match;
4234
+ const type = type1 || type2;
4235
+ const key = key1 || key2;
4236
+ if (!type) {
4237
+ // This shouldn't happen with the current regex, but safety first
4238
+ throw new Error(`ESYNC: Invalid or malformed injection syntax detected in "${full}".`);
4239
+ }
4240
+ if (!key) {
4241
+ throw new Error(`ESYNC: Malformed syntax "${full}". Missing key or property path.`);
4242
+ }
4243
+ }
4244
+ // Catch any `&(` that didn't even loosely match the malformedRegex
4245
+ const stripped = value.replace(malformedRegex, "");
4246
+ if (/&\(/.test(stripped)) {
4247
+ throw new Error(`ESYNC: Invalid or malformed injection syntax detected in "${value}".`);
4248
+ }
4218
4249
  }
4219
- // ─── Convenience: banner / separator ─────────────────────────────────────
4220
- banner(title) {
4221
- const line = `${ANSI.blue}${"─".repeat(60)}${ANSI.reset}`;
4222
- const centered = title
4223
- .padStart(30 + Math.floor(title.length / 2))
4224
- .padEnd(60);
4225
- console.log(`\n${line}`);
4226
- console.log(`${ANSI.bold}${ANSI.brightCyan}${centered}${ANSI.reset}`);
4227
- console.log(`${line}\n`);
4250
+ // -------------------------------------------------------------------------
4251
+ // Error formatting
4252
+ // -------------------------------------------------------------------------
4253
+ buildMissingError(type, key) {
4254
+ const descriptions = {
4255
+ env: `Environment variable "${key}"`,
4256
+ pkg: `Property "${key}" in package.json`,
4257
+ this: `Property "${key}" in current object`,
4258
+ date: `Date token "${key}" (valid: ${Object.keys(DATE_TOKENS).join(", ")})`,
4259
+ file: `File "${key}"`,
4260
+ };
4261
+ const desc = descriptions[type] ?? `Reference "${key}" (type: ${type})`;
4262
+ return `EDYNC: ${desc} not found or could not be resolved.`;
4228
4263
  }
4229
4264
  }
4230
- QuickLogger.showTimestamp = true;
4231
- // ─── Default singleton logger ──────────────────────────────────────────────
4232
- // export const logger = QuickLogger.for("");
4233
4265
 
4266
+ // ---------------------------------------------------------------------------
4267
+ // Zero-RAM-Store Architecture (libSynapx + libXESS):
4268
+ //
4269
+ // CRITICAL SECURITY GUARANTEE:
4270
+ // Environment secrets are NEVER cached or stored in JavaScript/V8 RAM.
4271
+ // All secret reads and mutations are delegated synchronously over the
4272
+ // authenticated libSynapx bridge to the native Go libXESS Vault.
4273
+ // ---------------------------------------------------------------------------
4274
+ const XY_XHSC_REGISTER_FS = Symbol();
4234
4275
  /**
4235
- * Returns the absolute path to the XyPriss shared temp directory.
4276
+ * **Internal Root-Scoped Env Access Key**
4236
4277
  *
4237
- * @returns {string} Path to `<os.tmpdir>/nehonix.xypriss.data`
4238
- */
4239
- function getXyprissTempDir() {
4240
- const sys = getSysApi();
4241
- return sys.path.join(sys.path.tempDir(), "nehonix.xypriss.data");
4242
- }
4243
- /**
4244
- * Resolves and ensures a sub-path within the XyPriss temp directory exists.
4278
+ * Used exclusively by internal engine modules (such as `ProjectDiscovery.loadXyConfig`)
4279
+ * to resolve configuration references `&(env:...)` within a target project context.
4245
4280
  *
4246
- * @param {string | string[]} _p - Sub-path segment(s) to append.
4247
- * @returns {string} The absolute resolved temp sub-path.
4281
+ * **Security Decision:**
4282
+ * Previously, this capability was exposed as a public method `__sys__.__env__.getForRoot(key, root)`.
4283
+ * That allowed third-party plugins in `node_modules` to pass the host project's root (`process.cwd()`
4284
+ * or `__sys__._primaryRoot`), completely bypassing caller-isolated Zero-Trust sandboxing.
4285
+ * Moving this method behind an unexported module `Symbol` prevents external code from invoking it.
4286
+ *
4287
+ * @internal
4248
4288
  */
4249
- function createXyprissTempDir(_p) {
4250
- const sys = getSysApi();
4251
- const base = getXyprissTempDir();
4252
- const segment = typeof _p === "string"
4253
- ? _p
4254
- : _p.includes("/")
4255
- ? _p.map((p) => p.replace("/", "")).join("/")
4256
- : _p.join("/");
4257
- // Use the native corrective layer to prevent doubling or redundant separators
4258
- const rawPath = segment.startsWith(base)
4259
- ? segment
4260
- : sys.path.join(base, segment);
4261
- const normalisedPath = sys.path.correct(rawPath, { tentative: 2 });
4262
- if (!sys.fs.exist(normalisedPath)) {
4263
- sys.fs.mkdir(normalisedPath, { parents: true });
4264
- }
4265
- return normalisedPath;
4266
- }
4289
+ const XY_ENV_INTERNAL_GET_FOR_ROOT = Symbol("__xy_env_internal_get_for_root__");
4267
4290
  /**
4268
- * **Session Temp Directory (singleton)**
4291
+ * **Internal Security Shield Configuration Key**
4269
4292
  *
4270
- * Unique sub-path generated once per process lifetime under the XyPriss
4271
- * temp root (`<os.tmpdir>/nehonix.xypriss.data/xuser/<hex4>`).
4293
+ * Used exclusively during framework startup (`xhsc.ts`) to apply declarative
4294
+ * XESS shield rules configured in `xypriss.config.json(c)`.
4272
4295
  *
4273
- * The value is memoized on first access and remains stable for the entire
4274
- * duration of the running process, ensuring all callers within the same
4275
- * session share the same isolated scratch space.
4296
+ * **Security Decision:**
4297
+ * Exposing `configureShield` as a public method on `__sys__.__env__` created a critical vulnerability,
4298
+ * allowing untrusted plugins to dynamically modify the whitelist and leak forbidden secrets through
4299
+ * `process.env`. Restricting it to this unexported Symbol guarantees that only the engine bootstrap
4300
+ * can configure the whitelist.
4301
+ *
4302
+ * @internal
4276
4303
  */
4277
- let _sessionTmpDir = null;
4304
+ const XY_ENV_CONFIGURE_SHIELD = Symbol("__xy_env_configure_shield__");
4305
+ // ---------------------------------------------------------------------------
4306
+ // Internal value sanitisation
4307
+ //
4308
+ // Detects byte sequences that can corrupt downstream parsers, log sinks, or
4309
+ // serialisers when stored as environment variable values.
4310
+ // ---------------------------------------------------------------------------
4311
+ /** Characters that are unconditionally rejected in environment variable values. */
4312
+ const FORBIDDEN_VALUE_PATTERN = /[\r\n\0]/;
4313
+ // ---------------------------------------------------------------------------
4314
+ // Errors
4315
+ // ---------------------------------------------------------------------------
4278
4316
  /**
4279
- * Returns the process-scoped user temp directory path for THIS active server instance.
4280
- *
4281
- * Generates an instance ID hash once and caches it for the lifetime of the process.
4282
- * E.g. `/tmp/nehonix.xypriss.data/xuser/12daa75a`
4317
+ * Thrown by {@link EnvApi.getStrict} when a required environment variable is
4318
+ * absent or — when `rejectEmpty` is set — when it is present but empty.
4283
4319
  *
4284
- * @returns {string} Absolute path to instance temp directory
4285
- */
4286
- function generateXUserTmpDir() {
4287
- if (_sessionTmpDir !== null) {
4288
- return _sessionTmpDir;
4289
- }
4290
- const sys = getSysApi();
4291
- // 1. Adopt the session directory allocated exclusively by the libProc supervisor
4292
- const envSession = sys?.__env__?.get("XYPRISS_USER_TMP") ||
4293
- sys?.__env__?.get("XESS_SESSION_TMP") ||
4294
- (typeof process !== "undefined"
4295
- ? (process.env?.XYPRISS_USER_TMP || process.env?.XESS_SESSION_TMP)
4296
- : undefined);
4297
- if (envSession && typeof envSession === "string") {
4298
- _sessionTmpDir = envSession;
4299
- if (sys?.fs && !sys.fs.exist(_sessionTmpDir)) {
4300
- sys.fs.mkdir(_sessionTmpDir, { parents: true });
4301
- }
4302
- return _sessionTmpDir;
4320
+ * @example
4321
+ * try {
4322
+ * const dbUrl = __sys__.__env__.getStrict("DATABASE_URL");
4323
+ * } catch (err) {
4324
+ * if (err instanceof EnvAccessError) {
4325
+ * process.exit(1); // Fail fast on missing critical configuration
4326
+ * }
4327
+ * }
4328
+ */
4329
+ class EnvAccessError extends Error {
4330
+ constructor(key, reason) {
4331
+ super(reason === "empty"
4332
+ ? `Environment variable "${key}" is set but contains an empty value. ` +
4333
+ `Use __sys__.__env__.get("${key}") if an empty value is acceptable.`
4334
+ : `Required environment variable "${key}" is not defined. ` +
4335
+ `Ensure it is present in your .env file or execution environment.`);
4336
+ this.name = "EnvAccessError";
4337
+ this.key = key;
4338
+ Object.setPrototypeOf(this, EnvAccessError.prototype);
4303
4339
  }
4304
- // No supervisor session provisioned by libProc: unconfined execution has no valid session
4305
- return "";
4306
4340
  }
4307
4341
  /**
4308
- * Returns the unique 8-character session hash ID for the active server instance.
4309
- * Delegated exclusively to the libProc supervisor (Single Source of Truth).
4342
+ * Thrown by {@link EnvApi.set} when the key or value fails validation.
4343
+ *
4344
+ * @example
4345
+ * try {
4346
+ * __sys__.__env__.set("", "value"); // empty key
4347
+ * __sys__.__env__.set("FOO", "bar\nbaz"); // newline injection attempt
4348
+ * } catch (err) {
4349
+ * if (err instanceof EnvKeyError) {
4350
+ * logger.error("Invalid env write", { key: err.key, reason: err.message });
4351
+ * }
4352
+ * }
4310
4353
  */
4311
- function getSessionHash() {
4312
- const sys = getSysApi();
4313
- const envHash = sys?.__env__?.get("XYPRISS_SESSION_HASH") ||
4314
- (typeof process !== "undefined" ? process.env?.XYPRISS_SESSION_HASH : undefined);
4315
- if (envHash && typeof envHash === "string") {
4316
- return envHash;
4317
- }
4318
- if (_sessionTmpDir) {
4319
- if (sys?.path) {
4320
- return sys.path.basename(_sessionTmpDir);
4321
- }
4322
- const parts = _sessionTmpDir.split(/[/\\]/).filter(Boolean);
4323
- return parts[parts.length - 1] || "";
4354
+ class EnvKeyError extends Error {
4355
+ constructor(key, reason) {
4356
+ super(`Invalid environment variable "${key}": ${reason}`);
4357
+ this.name = "EnvKeyError";
4358
+ this.key = key;
4359
+ Object.setPrototypeOf(this, EnvKeyError.prototype);
4324
4360
  }
4325
- return "";
4326
4361
  }
4327
4362
  /**
4328
- * Backward-compatibility alias for getSessionHash().
4363
+ * Thrown when {@link EnvApi} methods are called before the internal store has
4364
+ * been initialised by the XyPriss bootstrap process.
4365
+ *
4366
+ * This error should never occur in correctly bootstrapped applications.
4367
+ * If it does, it indicates that framework initialisation was bypassed.
4329
4368
  */
4330
- function getInstanceId() {
4331
- return getSessionHash();
4369
+ class EnvStoreError extends Error {
4370
+ constructor() {
4371
+ super("The XyPriss environment store has not been initialised. " +
4372
+ "Ensure that createServer() has completed before accessing __sys__.__env__.");
4373
+ this.name = "EnvStoreError";
4374
+ Object.setPrototypeOf(this, EnvStoreError.prototype);
4375
+ }
4332
4376
  }
4333
4377
  /**
4334
- * **Scoped libXESS Temp Directory**
4335
- *
4336
- * Scopes libXESS temporary decoys and IPC socket files inside the dedicated
4337
- * session temp directory under `xuser` (`<tmpdir>/nehonix.xypriss.data/xuser/<instanceId>/xess`).
4338
- *
4339
- * @returns {string} Absolute path to instance xess temp directory
4378
+ * Thrown when an application attempts to boot without the mandatory libXESS confinement shield.
4340
4379
  */
4341
- function getXessTempDir() {
4342
- const sys = getSysApi();
4343
- const envXess = sys?.__env__?.get("XESS_TEMP_DIR") ||
4344
- (typeof process !== "undefined" ? process.env?.XESS_TEMP_DIR : undefined);
4345
- if (envXess && typeof envXess === "string") {
4346
- return envXess;
4347
- }
4348
- const sessionDir = generateXUserTmpDir();
4349
- if (!sessionDir) {
4350
- return "";
4351
- }
4352
- const xessDir = sys?.path ? sys.path.join(sessionDir, "xess") : `${sessionDir}/xess`;
4353
- if (sys?.fs && !sys.fs.exist(xessDir)) {
4354
- sys.fs.mkdir(xessDir, { parents: true });
4380
+ class XessShieldRequiredError extends Error {
4381
+ constructor(message) {
4382
+ super(message ||
4383
+ "XyPriss Security Violation: libXESS environment confinement is mandatory.\n" +
4384
+ "Applications must be launched through the official XFPM CLI (e.g. 'xfpm run', 'xfpm dev', 'xfpm start').\n" +
4385
+ "Unconfined direct runtime execution exposes secrets to host disk leaks and is strictly prohibited.");
4386
+ this.name = "XessShieldRequiredError";
4387
+ Object.setPrototypeOf(this, XessShieldRequiredError.prototype);
4355
4388
  }
4356
- return xessDir;
4357
4389
  }
4358
4390
 
4359
4391
  /**
@@ -4390,584 +4422,373 @@ function isCoreFrameworkPath(filePath) {
4390
4422
  return isEngineCorePath(filePath);
4391
4423
  }
4392
4424
 
4393
- const logger$1 = new QuickLogger("LibXESS");
4394
- // Module-scoped security closures - strictly isolated from globalThis and reflection APIs
4395
- const _secretsCache = new Map();
4396
- let _ephemeralAuthToken = "";
4397
- let _activeSessionKey = "";
4398
- let _isLibxessActive = false;
4399
- // Immediately consume the one-shot token at module evaluation time
4400
- if (typeof process !== "undefined") {
4401
- if (process.env?.LIBXESS_ACTIVE === "1") {
4402
- _isLibxessActive = true;
4403
- }
4404
- if (process.env?.XYPRISS_XESS_SESSION_KEY) {
4405
- _activeSessionKey = process.env.XYPRISS_XESS_SESSION_KEY;
4406
- _isLibxessActive = true;
4407
- }
4408
- if (process.env?.XYPRISS_XESS_AUTH_TOKEN) {
4409
- _ephemeralAuthToken = process.env.XYPRISS_XESS_AUTH_TOKEN;
4410
- _isLibxessActive = true;
4411
- try {
4412
- delete process.env.XYPRISS_XESS_AUTH_TOKEN;
4413
- }
4414
- catch { }
4415
- }
4416
- }
4417
- const ppidScope = typeof process !== "undefined" && process.ppid ? process.ppid : "sys";
4418
- const SESSION_BRIDGE_KEY = Symbol.for(`__xypriss_session_bridge_${ppidScope}__`);
4419
- function getSessionBridge() {
4420
- const g = globalThis;
4421
- if (!g[SESSION_BRIDGE_KEY]) {
4422
- let bridgeSessionKey = "";
4423
- let bridgeCache = new Map();
4424
- const bridge = {
4425
- getSessionKey: () => {
4426
- assertInternalCaller();
4427
- return bridgeSessionKey;
4428
- },
4429
- getSecretsCache: () => {
4430
- assertInternalCaller();
4431
- return bridgeCache;
4432
- },
4433
- registerSession: (key, cache) => {
4434
- assertInternalCaller();
4435
- if (key) {
4436
- bridgeSessionKey = key;
4437
- }
4438
- if (cache) {
4439
- bridgeCache = cache;
4440
- }
4441
- },
4442
- };
4425
+ // Capture native V8 C++ CallSite bindings at module bootstrap before any third-party code executes.
4426
+ // `util.getCallSites` invokes v8::StackTrace::CurrentStackTrace directly in C++, completely
4427
+ // bypassing `Error.prepareStackTrace` overrides and ignoring `//# sourceURL` directives.
4428
+ const _nativeGetCallSites = typeof util.getCallSites === "function"
4429
+ ? util.getCallSites.bind(util)
4430
+ : null;
4431
+ let cachedManifest = null;
4432
+ /**
4433
+ * Loads the authoritative plugins manifest provided by xfpm.
4434
+ */
4435
+ function getPluginsManifest() {
4436
+ if (cachedManifest)
4437
+ return cachedManifest;
4438
+ const manifestPath = process.env.XYPRISS_PLUGINS_MANIFEST ||
4439
+ (process.env.XYPRISS_PROJECT_ROOT
4440
+ ? path$1.join(process.env.XYPRISS_PROJECT_ROOT, "node_modules", ".xfpm", "plugins_manifest.json")
4441
+ : null);
4442
+ if (manifestPath && fs$1.existsSync(manifestPath)) {
4443
4443
  try {
4444
- Object.defineProperty(g, SESSION_BRIDGE_KEY, {
4445
- value: bridge,
4446
- writable: false,
4447
- enumerable: false,
4448
- configurable: false,
4449
- });
4444
+ const raw = fs$1.readFileSync(manifestPath, "utf-8");
4445
+ cachedManifest = JSON.parse(raw);
4446
+ return cachedManifest;
4450
4447
  }
4451
4448
  catch {
4452
- g[SESSION_BRIDGE_KEY] = bridge;
4449
+ // ignore
4453
4450
  }
4454
4451
  }
4455
- return g[SESSION_BRIDGE_KEY];
4452
+ return null;
4456
4453
  }
4457
4454
  /**
4458
- * Asserts that the caller executing this method is directly part of the internal
4459
- * XyPriss engine core. External plugins or untrusted scripts attempting to invoke
4460
- * XessIpcClient are immediately rejected and halted.
4455
+ * Returns the primary project root determined by xfpm CLI.
4461
4456
  */
4462
- function assertInternalCaller() {
4463
- const stack = new Error().stack || "";
4464
- const lines = stack.split("\n");
4465
- let callerFile = "";
4466
- for (let i = 1; i < lines.length; i++) {
4467
- const line = lines[i];
4468
- if (line.includes("XessIpcClient.") ||
4469
- line.includes("assertInternalCaller") ||
4470
- line.includes("getSessionBridge") ||
4471
- line.includes("registerSession") ||
4472
- line.includes("getSessionKey") ||
4473
- line.includes("getSecretsCache")) {
4474
- continue;
4457
+ function getPrimaryProjectRoot() {
4458
+ return process.env.XYPRISS_PROJECT_ROOT || process.cwd();
4459
+ }
4460
+ /**
4461
+ * Checks if a directory is a valid project root.
4462
+ */
4463
+ function isProjectRoot(dir) {
4464
+ if (!dir)
4465
+ return false;
4466
+ try {
4467
+ const resolved = path$1.resolve(dir);
4468
+ const primaryRoot = process.env.XYPRISS_PROJECT_ROOT;
4469
+ if (primaryRoot && resolved === path$1.resolve(primaryRoot)) {
4470
+ return true;
4475
4471
  }
4476
- const match = line.match(/\((.*):\d+:\d+\)$/) ||
4477
- line.match(/at (.*):\d+:\d+$/) ||
4478
- line.match(/at (.*)$/);
4479
- if (match) {
4480
- callerFile = match[1];
4481
- break;
4472
+ const manifest = getPluginsManifest();
4473
+ if (manifest?.roots && manifest.roots[resolved]) {
4474
+ return true;
4482
4475
  }
4476
+ const pkgPath = path$1.join(resolved, "package.json");
4477
+ return fs$1.existsSync(pkgPath);
4483
4478
  }
4484
- if (callerFile && !isCoreFrameworkPath(callerFile)) {
4485
- logger$1.error(`[libXESS Security Violation] Direct invocation of XessIpcClient from unauthorized caller '${callerFile}'. Confinement violation: halting process.`);
4486
- process.exit(1);
4479
+ catch {
4480
+ return false;
4487
4481
  }
4488
4482
  }
4489
4483
  /**
4490
- * **XessIpcClient**
4491
- *
4492
- * Client IPC sécurisé pour communiquer avec le superviseur libXESS.
4493
- * Permet de récupérer les secrets authentiques en mémoire RAM via Unix Domain Socket
4494
- * tout en maintenant l'isolation bipolaire (le fichier .env sur disque étant un leurre canary).
4495
- *
4496
- * L'adresse du socket IPC est résolue de manière déterministe hors process.env
4497
- * à partir de l'empreinte cryptographique XSec de la racine du projet.
4484
+ * Identifies the project or plugin root for a given caller path using xfpm metadata.
4498
4485
  */
4499
- class XessIpcClient {
4500
- static get secretsCache() {
4486
+ function identifyProjectRoot(filePath) {
4487
+ if (!filePath)
4488
+ return undefined;
4489
+ if (!path$1.isAbsolute(filePath)) {
4501
4490
  try {
4502
- const bridge = getSessionBridge();
4503
- const cache = bridge.getSecretsCache();
4504
- if (cache) {
4505
- return cache;
4506
- }
4491
+ filePath = path$1.resolve(filePath);
4507
4492
  }
4508
- catch { }
4509
- return _secretsCache;
4510
- }
4511
- /**
4512
- * Calcule la liste des emplacements potentiels du socket IPC libXESS pour un répertoire donné.
4513
- * Privilégie le dossier dédié scoped dans xuser/ tout en conservant les fallbacks.
4514
- */
4515
- static getSocketCandidatesForDir(dir) {
4516
- const hash = xyprissSecurity.Cipher.hash
4517
- .create(path__namespace.resolve(dir), { algorithm: "sha256" })
4518
- .toString("hex")
4519
- .slice(0, 12);
4520
- const fileName = `xess_ipc_${hash}.sock`;
4521
- const candidates = [];
4522
- // Emplacement unique scoped sous la session courante fournie par libproc
4523
- try {
4524
- const xessDir = getXessTempDir();
4525
- if (xessDir) {
4526
- candidates.push(path__namespace.join(xessDir, fileName));
4527
- }
4493
+ catch {
4494
+ return undefined;
4528
4495
  }
4529
- catch { }
4530
- try {
4531
- const sessionDir = generateXUserTmpDir();
4532
- if (sessionDir) {
4533
- candidates.push(path__namespace.join(sessionDir, "xess", fileName));
4534
- candidates.push(path__namespace.join(sessionDir, fileName));
4496
+ }
4497
+ const normalized = filePath.replace(/\\/g, "/");
4498
+ const primaryRoot = (process.env.XYPRISS_PROJECT_ROOT || process.cwd()).replace(/\\/g, "/");
4499
+ // 1. Direct O(1) match against verified plugins registered by xfpm
4500
+ const manifest = getPluginsManifest();
4501
+ if (manifest?.roots) {
4502
+ for (const [pluginRoot, _pluginName] of Object.entries(manifest.roots)) {
4503
+ const normPluginRoot = pluginRoot.replace(/\\/g, "/");
4504
+ if (normalized === normPluginRoot || normalized.startsWith(normPluginRoot + "/")) {
4505
+ return pluginRoot;
4535
4506
  }
4536
4507
  }
4537
- catch { }
4538
- return candidates;
4539
- }
4540
- /**
4541
- * Liste ordonnée de tous les chemins de sockets candidats potentiels :
4542
- * 1. process.cwd() (dossier d'exécution du CLI xfpm / superviseur libXESS)
4543
- * 2. projectDir (dossier du projet ou plugin ciblé)
4544
- * 3. Répertoires parents ascendants
4545
- */
4546
- static getCandidateSocketPaths(projectDir) {
4547
- const candidates = [];
4548
- const seen = new Set();
4549
- const addDirHierarchy = (dir) => {
4550
- let current = path__namespace.resolve(dir);
4551
- while (current && !seen.has(current)) {
4552
- seen.add(current);
4553
- const candidatesForDir = XessIpcClient.getSocketCandidatesForDir(current);
4554
- for (const candidate of candidatesForDir) {
4555
- if (fs__namespace.existsSync(candidate) && !candidates.includes(candidate)) {
4556
- candidates.push(candidate);
4557
- }
4558
- }
4559
- const parent = path__namespace.dirname(current);
4560
- if (parent === current)
4561
- break;
4562
- current = parent;
4563
- }
4564
- };
4565
- // 2. Dossier de travail courant (process.cwd()) où xfpm ancre son superviseur
4566
- if (typeof process !== "undefined" && process.cwd) {
4567
- addDirHierarchy(process.cwd());
4508
+ }
4509
+ // 2. Direct match against primary project root
4510
+ if (normalized === primaryRoot || normalized.startsWith(primaryRoot + "/")) {
4511
+ // If inside node_modules, it is an undeclared/untrusted dependency, NOT the application root!
4512
+ if (normalized.includes("/node_modules/")) {
4513
+ return undefined;
4568
4514
  }
4569
- // 3. Dossier de projet spécifique si différent
4570
- if (projectDir) {
4571
- addDirHierarchy(projectDir);
4515
+ return primaryRoot;
4516
+ }
4517
+ // 3. Monorepo development mods (/mods/<name>/) fallback
4518
+ const modsIdx = normalized.lastIndexOf("/mods/");
4519
+ if (modsIdx !== -1) {
4520
+ const afterMods = normalized.substring(modsIdx + 6);
4521
+ const nextSlash = afterMods.indexOf("/");
4522
+ const modName = nextSlash === -1 ? afterMods : afterMods.substring(0, nextSlash);
4523
+ if (modName) {
4524
+ return normalized.substring(0, modsIdx + 6 + modName.length);
4572
4525
  }
4573
- // 4. Sockets provisionnés directement dans le xessDir de cette session supervisée
4526
+ }
4527
+ return undefined;
4528
+ }
4529
+ function normalizeScriptName(rawScript) {
4530
+ if (!rawScript)
4531
+ return "";
4532
+ if (rawScript.startsWith("file://")) {
4574
4533
  try {
4575
- const xessDir = getXessTempDir();
4576
- if (xessDir && fs__namespace.existsSync(xessDir)) {
4577
- const files = fs__namespace.readdirSync(xessDir);
4578
- for (const f of files) {
4579
- if (f.startsWith("xess_ipc_") && f.endsWith(".sock")) {
4580
- const sock = path__namespace.join(xessDir, f);
4581
- if (!candidates.includes(sock)) {
4582
- candidates.push(sock);
4583
- }
4584
- }
4585
- }
4586
- }
4534
+ return node_url.fileURLToPath(rawScript);
4587
4535
  }
4588
- catch { }
4589
- return candidates;
4590
- }
4591
- /**
4592
- * Effectue une vérification synchrone de liveness sur un socket IPC.
4593
- * Si le fichier socket existe sur le disque mais que le superviseur est mort (ECONNREFUSED / timeout),
4594
- * le socket fantôme est immédiatement purgé du disque et la fonction retourne false.
4595
- */
4596
- static probeSocketSync(socketPath) {
4597
- if (!fs__namespace.existsSync(socketPath))
4598
- return false;
4599
- // Fast-path: When running under active libXESS supervisor, socket presence confirms shielding
4600
- if (_isLibxessActive ||
4601
- process.env?.LIBXESS_ACTIVE === "1" ||
4602
- process.env?.XYPRISS_USER_TMP ||
4603
- process.env?.XESS_TEMP_DIR) {
4604
- return true;
4536
+ catch {
4537
+ return rawScript.slice(7);
4605
4538
  }
4606
- const script = `
4607
- const net = require("net");
4608
- const sock = process.argv[1];
4609
- const client = net.createConnection(sock, () => {
4610
- client.end();
4611
- process.exit(0);
4612
- });
4613
- client.on("error", () => process.exit(1));
4614
- setTimeout(() => process.exit(1), 1000);
4615
- `;
4539
+ }
4540
+ return rawScript;
4541
+ }
4542
+ function isRuntimeLoaderPath(filePath) {
4543
+ const norm = filePath.replace(/\\/g, "/");
4544
+ return (norm.includes("/node_modules/tsx/") ||
4545
+ norm.includes("/node_modules/ts-node/") ||
4546
+ norm.includes("/node_modules/.bin/"));
4547
+ }
4548
+ /**
4549
+ * Captures raw C++ V8/JSC CallSite frames by temporarily overriding `Error.prepareStackTrace`
4550
+ * synchronously during stack generation. This neutralizes any user/attacker `Error.prepareStackTrace`
4551
+ * hijack and returns the full un-truncated call stack across both Node.js (V8) and Bun (JSC).
4552
+ */
4553
+ function captureNativeFrames() {
4554
+ const frames = [];
4555
+ // 1. Capture full CallSite array via controlled prepareStackTrace override (immune to prior Error.prepareStackTrace hijacks)
4556
+ const prevPrepare = Error.prepareStackTrace;
4557
+ const prevLimit = Error.stackTraceLimit;
4558
+ let rawSites = [];
4559
+ try {
4560
+ Error.stackTraceLimit = 64;
4561
+ Error.prepareStackTrace = (_err, stack) => {
4562
+ rawSites = Array.isArray(stack) ? stack : [];
4563
+ return "";
4564
+ };
4565
+ const probe = new Error();
4566
+ void probe.stack;
4567
+ }
4568
+ catch {
4569
+ // ignore
4570
+ }
4571
+ finally {
4572
+ Error.prepareStackTrace = prevPrepare;
4573
+ Error.stackTraceLimit = prevLimit;
4574
+ }
4575
+ for (const site of rawSites) {
4576
+ if (!site)
4577
+ continue;
4616
4578
  try {
4617
- node_child_process.execFileSync(process.execPath, ["-e", script, socketPath], {
4618
- timeout: 1500,
4619
- stdio: "ignore",
4579
+ const rawFile = typeof site.getFileName === "function"
4580
+ ? site.getFileName() || ""
4581
+ : "";
4582
+ const fnName = typeof site.getFunctionName === "function"
4583
+ ? site.getFunctionName() || ""
4584
+ : "";
4585
+ const isEval = typeof site.isEval === "function" ? Boolean(site.isEval()) : false;
4586
+ frames.push({
4587
+ filePath: normalizeScriptName(rawFile),
4588
+ fnName,
4589
+ isEval,
4620
4590
  });
4621
- return true;
4622
4591
  }
4623
4592
  catch {
4624
- return false;
4593
+ // ignore
4625
4594
  }
4626
4595
  }
4627
- /**
4628
- * Résout déterministement le chemin du socket IPC libXESS actif.
4629
- */
4630
- static resolveSocketPath(projectDir) {
4631
- const candidates = this.getCandidateSocketPaths(projectDir);
4632
- for (const candidate of candidates) {
4633
- if (this.probeSocketSync(candidate)) {
4634
- return candidate;
4596
+ // 2. Also merge frames from Node C++ util.getCallSites (which strips //# sourceURL on V8)
4597
+ if (_nativeGetCallSites) {
4598
+ try {
4599
+ const nativeSites = _nativeGetCallSites(64);
4600
+ for (const s of nativeSites) {
4601
+ if (!s)
4602
+ continue;
4603
+ const rawScript = s.scriptName || "";
4604
+ const fnName = s.functionName || "";
4605
+ frames.push({
4606
+ filePath: normalizeScriptName(rawScript),
4607
+ fnName,
4608
+ isEval: !rawScript && (fnName === "eval" || fnName === "anonymous"),
4609
+ });
4635
4610
  }
4636
4611
  }
4637
- return undefined;
4638
- }
4639
- /**
4640
- * Vérifie si le runtime tourne sous le confinement actif de libXESS.
4641
- */
4642
- static isShielded(projectDir) {
4643
- const authToken = this.getOrConsumeAuthToken();
4644
- const sessionKey = this.getSessionKey();
4645
- const isActive = typeof process !== "undefined" &&
4646
- (_isLibxessActive ||
4647
- process.env?.LIBXESS_ACTIVE === "1" ||
4648
- !!authToken ||
4649
- !!sessionKey);
4650
- if (!isActive) {
4651
- return false;
4652
- }
4653
- const candidates = this.getCandidateSocketPaths(projectDir);
4654
- for (const candidate of candidates) {
4655
- if (this.probeSocketSync(candidate)) {
4656
- return true;
4657
- }
4658
- }
4659
- return false;
4660
- }
4661
- /**
4662
- * Récupère le chemin du socket IPC libXESS.
4663
- */
4664
- static getSocketPath(projectDir) {
4665
- return this.resolveSocketPath(projectDir);
4666
- }
4667
- /**
4668
- * Récupère le jeton d'authentification éphémère libXESS et purge immédiatement
4669
- * la variable d'environnement de la mémoire pour empêcher toute réutilisation non autorisée.
4670
- */
4671
- static getOrConsumeAuthToken() {
4672
- if (_ephemeralAuthToken) {
4673
- return _ephemeralAuthToken;
4674
- }
4675
- if (typeof process !== "undefined" && process.env?.XYPRISS_XESS_AUTH_TOKEN) {
4676
- _ephemeralAuthToken = process.env.XYPRISS_XESS_AUTH_TOKEN;
4677
- try {
4678
- delete process.env.XYPRISS_XESS_AUTH_TOKEN;
4679
- }
4680
- catch { }
4612
+ catch {
4613
+ // ignore
4681
4614
  }
4682
- return _ephemeralAuthToken;
4683
- }
4684
- /**
4685
- * Exposes the currently active session key for secure propagation to child worker processes.
4686
- */
4687
- static getActiveSessionKey() {
4688
- return this.getSessionKey();
4689
4615
  }
4690
- static getSessionKey() {
4691
- if (_activeSessionKey) {
4692
- return _activeSessionKey;
4616
+ return frames;
4617
+ }
4618
+ /**
4619
+ * Verifies that an internal property accessor (such as `BaseApi.prototype.runner`)
4620
+ * or internal engine method is being invoked directly by an internal XyPriss core module
4621
+ * and not by userland or third-party `node_modules` code.
4622
+ */
4623
+ function isImmediateInternalEngineCall() {
4624
+ const frames = captureNativeFrames();
4625
+ for (let i = 0; i < frames.length; i++) {
4626
+ const { filePath, fnName, isEval } = frames[i];
4627
+ if (isEval) {
4628
+ return false;
4693
4629
  }
4694
- if (typeof process !== "undefined" && process.env?.XYPRISS_XESS_SESSION_KEY) {
4695
- _activeSessionKey = process.env.XYPRISS_XESS_SESSION_KEY;
4696
- return _activeSessionKey;
4630
+ if (!filePath)
4631
+ continue;
4632
+ if (filePath.startsWith("node:") ||
4633
+ filePath.startsWith("bun:") ||
4634
+ filePath === "native" ||
4635
+ filePath.includes("[eval]")) {
4636
+ continue;
4697
4637
  }
4698
- try {
4699
- const bridge = getSessionBridge();
4700
- const key = bridge.getSessionKey();
4701
- if (key) {
4702
- _activeSessionKey = key;
4703
- return key;
4638
+ const norm = filePath.replace(/\\/g, "/");
4639
+ // Skip stack-tracing plumbing and entrypoint caller wrappers inside the engine
4640
+ if (isEngineCorePath(norm)) {
4641
+ if (fnName === "captureNativeFrames" ||
4642
+ fnName === "isImmediateInternalEngineCall" ||
4643
+ fnName === "get runner" ||
4644
+ fnName === "runner" ||
4645
+ fnName === "runSync" ||
4646
+ fnName === "runAsync" ||
4647
+ fnName === "runStream" ||
4648
+ fnName === "runWritableStream" ||
4649
+ fnName === "call" ||
4650
+ fnName === "callSync" ||
4651
+ fnName === "callSyncSubprocess" ||
4652
+ fnName === "executeEnvCall") {
4653
+ continue;
4704
4654
  }
4705
4655
  }
4706
- catch { }
4707
- return "";
4656
+ // The very first frame outside the entrypoint plumbing is the direct caller
4657
+ return isEngineCorePath(norm);
4708
4658
  }
4709
- static setSessionKey(key) {
4710
- _activeSessionKey = key;
4711
- _ephemeralAuthToken = "";
4712
- try {
4713
- const bridge = getSessionBridge();
4714
- bridge.registerSession(key, _secretsCache);
4659
+ return false;
4660
+ }
4661
+ /**
4662
+ * Extracts verified caller information by inspecting the ENTIRE active call stack.
4663
+ * Immune to `Error.prepareStackTrace` hijacking AND `//# sourceURL` spoofing:
4664
+ * even if an attacker injects a fake frame via `new Function("//# sourceURL=...")`,
4665
+ * the attacker's own `node_modules/...` frame remains on the call stack and is detected.
4666
+ */
4667
+ function getVerifiedCallerInfo() {
4668
+ const frames = captureNativeFrames();
4669
+ let immediateCallerRoot;
4670
+ let immediateCallerFile = "";
4671
+ for (let i = 0; i < frames.length; i++) {
4672
+ const { filePath, isEval } = frames[i];
4673
+ if (isEval) {
4674
+ return {
4675
+ root: undefined,
4676
+ isUntrusted: true,
4677
+ callerFile: filePath || "<eval>",
4678
+ };
4715
4679
  }
4716
- catch { }
4717
- }
4718
- /**
4719
- * Récupération synchrone des secrets lors du bootstrap initial.
4720
- * Tente les sockets candidats et purge automatiquement les sockets fantômes résiduels.
4721
- */
4722
- static fetchSecretsSync(projectDirOrSocket) {
4723
- assertInternalCaller();
4724
- let candidates = [];
4725
- if (projectDirOrSocket &&
4726
- (projectDirOrSocket.endsWith(".sock") ||
4727
- (fs__namespace.existsSync(projectDirOrSocket) &&
4728
- !fs__namespace.statSync(projectDirOrSocket).isDirectory()))) {
4729
- candidates = [projectDirOrSocket];
4680
+ if (!filePath)
4681
+ continue;
4682
+ if (filePath.startsWith("node:") ||
4683
+ filePath.startsWith("bun:") ||
4684
+ filePath === "native" ||
4685
+ filePath.includes("[eval]")) {
4686
+ continue;
4730
4687
  }
4731
- else {
4732
- candidates = this.getCandidateSocketPaths(projectDirOrSocket);
4688
+ // Skip XyPriss internal engine frames
4689
+ if (isEngineCorePath(filePath)) {
4690
+ continue;
4733
4691
  }
4734
- const targetDir = projectDirOrSocket && !projectDirOrSocket.endsWith(".sock")
4735
- ? path__namespace.resolve(projectDirOrSocket)
4736
- : "";
4737
- const cacheKey = targetDir || "__root__";
4738
- if (this.secretsCache.has(cacheKey)) {
4739
- return this.secretsCache.get(cacheKey);
4740
- }
4741
- const authToken = this.getOrConsumeAuthToken();
4742
- const sessionKey = this.getSessionKey();
4743
- const isShieldedActive = typeof process !== "undefined" &&
4744
- (_isLibxessActive ||
4745
- process.env?.LIBXESS_ACTIVE === "1" ||
4746
- !!authToken ||
4747
- !!sessionKey);
4748
- if (!isShieldedActive) {
4749
- // Mode sans confinement libXESS (ex: exécution hors xfpm ou sans le flag -l xess)
4750
- const envPath = path__namespace.join(targetDir || (typeof process !== "undefined" ? process.cwd() : ""), ".env");
4751
- if (fs__namespace.existsSync(envPath)) {
4752
- try {
4753
- const raw = fs__namespace.readFileSync(envPath, "utf-8");
4754
- const parsed = {};
4755
- for (const line of raw.split("\n")) {
4756
- const trimmed = line.trim();
4757
- if (!trimmed || trimmed.startsWith("#"))
4758
- continue;
4759
- const eqIdx = trimmed.indexOf("=");
4760
- if (eqIdx !== -1) {
4761
- const k = trimmed.slice(0, eqIdx).trim();
4762
- let v = trimmed.slice(eqIdx + 1).trim();
4763
- if ((v.startsWith('"') && v.endsWith('"')) ||
4764
- (v.startsWith("'") && v.endsWith("'"))) {
4765
- v = v.slice(1, -1);
4766
- }
4767
- parsed[k] = v;
4768
- }
4769
- }
4770
- this.secretsCache.set(cacheKey, parsed);
4771
- return parsed;
4772
- }
4773
- catch { }
4774
- }
4775
- return {};
4692
+ // Skip CLI TypeScript loaders (tsx / ts-node) at the bottom of the stack
4693
+ if (isRuntimeLoaderPath(filePath)) {
4694
+ continue;
4776
4695
  }
4777
- if (candidates.length === 0) {
4778
- const msg = "[libXESS] No active libXESS Bridge found for project. Direct execution without libXESS confinement is strictly prohibited.";
4779
- logger$1.error(msg);
4780
- process.exit(1);
4696
+ const root = identifyProjectRoot(filePath);
4697
+ // If ANY frame in the call chain originates from an undeclared/untrusted node_modules package,
4698
+ // reject the entire operation immediately (defeats //# sourceURL wrapper functions).
4699
+ if (!root) {
4700
+ return {
4701
+ root: undefined,
4702
+ isUntrusted: true,
4703
+ callerFile: filePath,
4704
+ };
4781
4705
  }
4782
- const action = sessionKey ? "GET_PROJECT" : "HANDSHAKE";
4783
- const credential = sessionKey || authToken;
4784
- const script = `
4785
- const net = require("net");
4786
- const fs = require("fs");
4787
- const sock = process.argv[1];
4788
- let rawInput = "";
4789
- try {
4790
- rawInput = fs.readFileSync(0, "utf-8");
4791
- } catch (e) {
4792
- process.exit(1);
4793
- }
4794
- let payload;
4795
- try {
4796
- payload = JSON.parse(rawInput);
4797
- } catch (e) {
4798
- process.exit(1);
4706
+ if (!immediateCallerRoot) {
4707
+ immediateCallerRoot = root;
4708
+ immediateCallerFile = filePath;
4709
+ }
4710
+ }
4711
+ if (immediateCallerRoot) {
4712
+ return {
4713
+ root: immediateCallerRoot,
4714
+ isUntrusted: false,
4715
+ callerFile: immediateCallerFile,
4716
+ };
4717
+ }
4718
+ return {
4719
+ root: getPrimaryProjectRoot(),
4720
+ isUntrusted: false,
4721
+ callerFile: "",
4722
+ };
4799
4723
  }
4800
- const client = net.createConnection(sock, () => {
4801
- client.write(JSON.stringify(payload) + "\\n");
4802
- });
4803
- let data = "";
4804
- client.on("data", (chunk) => {
4805
- data += chunk.toString();
4806
- if (data.includes("\\n")) {
4807
- client.end();
4808
- process.stdout.write(data.trim());
4809
- process.exit(0);
4724
+ /**
4725
+ * Retrieves the project root of the code currently executing by analyzing the native V8 call stack.
4726
+ */
4727
+ function getCallerProjectRoot() {
4728
+ const info = getVerifiedCallerInfo();
4729
+ if (info.isUntrusted) {
4730
+ return undefined;
4810
4731
  }
4811
- });
4812
- client.on("error", (err) => {
4813
- process.stderr.write(err.message);
4814
- process.exit(1);
4815
- });
4816
- setTimeout(() => { process.exit(1); }, 3000);
4817
- `;
4818
- const inputPayload = JSON.stringify(action === "HANDSHAKE"
4819
- ? { action: "HANDSHAKE", projectDir: targetDir, token: credential }
4820
- : { action: action, projectDir: targetDir, sessionKey: credential });
4821
- let lastErr;
4822
- for (const sock of candidates) {
4732
+ return info.root;
4733
+ }
4734
+ /**
4735
+ * Loads and cleans a XyPriss configuration file (JSON or JSONC).
4736
+ * Removes comments and trailing commas to ensure compatibility with standard JSON.parse.
4737
+ */
4738
+ function loadXyConfig(projectRoot) {
4739
+ for (const name of ["xypriss.config.jsonc", "xypriss.config.json"]) {
4740
+ const configPath = path$1.join(projectRoot, name);
4741
+ if (fs$1.existsSync(configPath)) {
4823
4742
  try {
4824
- // Pass sensitive credentials exclusively via private stdin pipe, NEVER in process.argv
4825
- const output = node_child_process.execFileSync(process.execPath, ["-e", script, sock], {
4826
- input: inputPayload,
4827
- encoding: "utf8",
4828
- timeout: 3000,
4829
- stdio: ["pipe", "pipe", "pipe"],
4830
- });
4831
- const parsed = JSON.parse(output.trim());
4832
- if (parsed.action === "UNAUTHORIZED" || parsed.error) {
4833
- const msg = `[libXESS] Authentication rejected: ${parsed.error || "Unauthorized"}. Confinement violation.`;
4834
- logger$1.error(msg);
4835
- process.exit(1);
4836
- }
4837
- if (parsed.sessionKey) {
4838
- this.setSessionKey(parsed.sessionKey);
4839
- }
4840
- if (parsed && parsed.secrets) {
4841
- this.secretsCache.set(cacheKey, parsed.secrets);
4842
- return parsed.secrets;
4843
- }
4844
- }
4845
- catch (err) {
4846
- lastErr = err;
4847
- }
4848
- }
4849
- const msg = `[libXESS] Failed to fetch secrets from libXESS: ${lastErr?.message || "unknown error"}. Confinement violation: halting execution.`;
4850
- logger$1.error(msg);
4851
- process.exit(1);
4852
- }
4853
- /**
4854
- * Récupération asynchrone des secrets via net.Socket natif.
4855
- */
4856
- static async fetchSecretsAsync(projectDirOrSocket) {
4857
- assertInternalCaller();
4858
- let candidates = [];
4859
- if (projectDirOrSocket &&
4860
- (projectDirOrSocket.endsWith(".sock") ||
4861
- (fs__namespace.existsSync(projectDirOrSocket) &&
4862
- !fs__namespace.statSync(projectDirOrSocket).isDirectory()))) {
4863
- candidates = [projectDirOrSocket];
4864
- }
4865
- else {
4866
- candidates = this.getCandidateSocketPaths(projectDirOrSocket);
4867
- }
4868
- const targetDir = projectDirOrSocket && !projectDirOrSocket.endsWith(".sock")
4869
- ? path__namespace.resolve(projectDirOrSocket)
4870
- : "";
4871
- const cacheKey = targetDir || "__root__";
4872
- if (this.secretsCache.has(cacheKey)) {
4873
- return this.secretsCache.get(cacheKey);
4874
- }
4875
- const authToken = this.getOrConsumeAuthToken();
4876
- const sessionKey = this.getSessionKey();
4877
- const isShieldedActive = typeof process !== "undefined" &&
4878
- (_isLibxessActive ||
4879
- process.env?.LIBXESS_ACTIVE === "1" ||
4880
- !!authToken ||
4881
- !!sessionKey);
4882
- if (!isShieldedActive) {
4883
- const envPath = path__namespace.join(targetDir || (typeof process !== "undefined" ? process.cwd() : ""), ".env");
4884
- if (fs__namespace.existsSync(envPath)) {
4885
- try {
4886
- const raw = fs__namespace.readFileSync(envPath, "utf-8");
4887
- const parsed = {};
4888
- for (const line of raw.split("\n")) {
4889
- const trimmed = line.trim();
4890
- if (!trimmed || trimmed.startsWith("#"))
4891
- continue;
4892
- const eqIdx = trimmed.indexOf("=");
4893
- if (eqIdx !== -1) {
4894
- const k = trimmed.slice(0, eqIdx).trim();
4895
- let v = trimmed.slice(eqIdx + 1).trim();
4896
- if ((v.startsWith('"') && v.endsWith('"')) ||
4897
- (v.startsWith("'") && v.endsWith("'"))) {
4898
- v = v.slice(1, -1);
4899
- }
4900
- parsed[k] = v;
4901
- }
4743
+ const raw = fs$1.readFileSync(configPath, "utf-8");
4744
+ const clean = raw
4745
+ .replace(/("(?:[^"\\]|\\.)*")|\/\/.*|\/\*[\s\S]*?\*\//g, (m, g) => (g ? g : ""))
4746
+ .replace(/("(?:[^"\\]|\\.)*")|,\s*([}\]])/g, (m, g1, g2) => g1 ? g1 : g2);
4747
+ const rawJson = JSON.parse(clean);
4748
+ // Load package.json from the same directory for resolution
4749
+ let pkgJson = null;
4750
+ const pkgPath = path$1.join(projectRoot, "package.json");
4751
+ if (fs$1.existsSync(pkgPath)) {
4752
+ try {
4753
+ pkgJson = JSON.parse(fs$1.readFileSync(pkgPath, "utf-8"));
4902
4754
  }
4903
- this.secretsCache.set(cacheKey, parsed);
4904
- return parsed;
4755
+ catch { /* ignore */ }
4905
4756
  }
4906
- catch { }
4907
- }
4908
- return {};
4909
- }
4910
- if (candidates.length === 0) {
4911
- const msg = "[libXESS] No active libXESS Bridge found for project. Direct execution without libXESS confinement is strictly prohibited.";
4912
- logger$1.error(msg);
4913
- process.exit(1);
4914
- }
4915
- const action = sessionKey ? "GET_PROJECT" : "HANDSHAKE";
4916
- const credential = sessionKey || authToken;
4917
- let lastErr;
4918
- for (const sock of candidates) {
4919
- try {
4920
- const secrets = await new Promise((resolve, reject) => {
4921
- const client = net__namespace.createConnection(sock, () => {
4922
- const payload = action === "HANDSHAKE"
4923
- ? { action: "HANDSHAKE", projectDir: targetDir, token: credential }
4924
- : { action: action, projectDir: targetDir, sessionKey: credential };
4925
- client.write(JSON.stringify(payload) + "\n");
4926
- });
4927
- let buffer = "";
4928
- const timeout = setTimeout(() => {
4929
- client.destroy();
4930
- reject(new Error("Socket timeout"));
4931
- }, 3000);
4932
- client.on("data", (chunk) => {
4933
- buffer += chunk.toString();
4934
- if (buffer.includes("\n")) {
4935
- clearTimeout(timeout);
4936
- client.end();
4937
- try {
4938
- const parsed = JSON.parse(buffer.trim());
4939
- if (parsed.action === "UNAUTHORIZED" || parsed.error) {
4940
- logger$1.error(`[libXESS] Authentication rejected: ${parsed.error || "Unauthorized"}`);
4941
- process.exit(1);
4942
- }
4943
- if (parsed.sessionKey) {
4944
- this.setSessionKey(parsed.sessionKey);
4945
- }
4946
- const sec = parsed.secrets || {};
4947
- this.secretsCache.set(cacheKey, sec);
4948
- resolve(sec);
4949
- }
4950
- catch (e) {
4951
- resolve({});
4952
- }
4953
- }
4954
- });
4955
- client.on("error", (err) => {
4956
- clearTimeout(timeout);
4957
- client.destroy();
4958
- reject(err);
4959
- });
4960
- });
4961
- return secrets;
4757
+ // Resolve references &(pkg), &(env), etc.
4758
+ const sys = globalThis.__sys__;
4759
+ // Safely resolve &(env:...) variables scoped to the target project root
4760
+ // using the internal symbol (safe from third-party / plugin tampering).
4761
+ let envProvider = sys?.__env__;
4762
+ if (sys?.__env__?.[XY_ENV_INTERNAL_GET_FOR_ROOT]) {
4763
+ envProvider = {
4764
+ has: (key) => sys.__env__[XY_ENV_INTERNAL_GET_FOR_ROOT](key, projectRoot) !== undefined,
4765
+ get: (key) => sys.__env__[XY_ENV_INTERNAL_GET_FOR_ROOT](key, projectRoot)
4766
+ };
4767
+ }
4768
+ const parser = new ConfigSyntaxParser(pkgJson, envProvider);
4769
+ return parser.resolve(rawJson);
4962
4770
  }
4963
- catch (err) {
4964
- lastErr = err;
4771
+ catch (e) {
4772
+ return null;
4965
4773
  }
4966
4774
  }
4967
- const msg = `[libXESS] Failed to fetch secrets from libXESS: ${lastErr?.message || "unknown error"}. Confinement violation: halting execution.`;
4968
- logger$1.error(msg);
4969
- process.exit(1);
4970
4775
  }
4776
+ return null;
4777
+ }
4778
+ /**
4779
+ * Verifies if a given directory contains a valid XyPriss plugin contract.
4780
+ * Required: xypriss.config.json(c) with the plugin's namespace under '$internal'
4781
+ */
4782
+ function verifyPluginContract(pluginRoot, pluginName) {
4783
+ const config = loadXyConfig(pluginRoot);
4784
+ if (!config)
4785
+ return false;
4786
+ const internal = config.$internal || config.internal;
4787
+ if (!internal)
4788
+ return false;
4789
+ const pluginContract = internal[pluginName];
4790
+ // The plugin must declare itself in the $internal block WITH 'type': 'plugin'
4791
+ return !!(pluginContract && pluginContract.type === "plugin");
4971
4792
  }
4972
4793
 
4973
4794
  /* *****************************************************************************
@@ -4976,6 +4797,7 @@ setTimeout(() => { process.exit(1); }, 3000);
4976
4797
  * High-performance, persistent Zero-Trust IPC client connecting XyPriss
4977
4798
  * to the Go libSynapx engine over isolated Unix Domain Sockets / Named Pipes.
4978
4799
  ***************************************************************************** */
4800
+ var _SynapxClient_socket, _SynapxClient_sessionKey, _SynapxClient_authToken, _SynapxClient_syncBridge;
4979
4801
  // Protocol Constants (matching libSynapx Go wire format)
4980
4802
  const MAGIC_BYTE = 0x53; // 'S'
4981
4803
  const MSG_HANDSHAKE = 0x01;
@@ -5079,24 +4901,33 @@ class SynapxClient {
5079
4901
  return false;
5080
4902
  }
5081
4903
  constructor(customSocketPath) {
5082
- this.socket = null;
4904
+ _SynapxClient_socket.set(this, null);
5083
4905
  this.connectingPromise = null;
5084
4906
  this.isHandshakeComplete = false;
5085
- this.sessionKey = "";
4907
+ _SynapxClient_sessionKey.set(this, "");
5086
4908
  this.seqId = 0;
5087
4909
  this.pendingCalls = new Map();
5088
4910
  this.rxChunks = [];
5089
4911
  this.rxBytesTotal = 0;
5090
- this.syncBridge = null;
4912
+ _SynapxClient_authToken.set(this, void 0);
4913
+ _SynapxClient_syncBridge.set(this, null);
5091
4914
  this.lastDaemonSpawnTime = 0;
5092
4915
  const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP || "";
5093
4916
  this.sessionHash =
5094
4917
  process.env.XYPRISS_SESSION_HASH ||
5095
4918
  (sessionDir ? path__namespace.basename(sessionDir) : "");
5096
- this.authToken =
5097
- process.env.XYPRISS_INTERNAL_TOKEN ||
5098
- process.env.XYPRISS_XESS_AUTH_TOKEN ||
5099
- "";
4919
+ tslib_es6_js.__classPrivateFieldSet(this, _SynapxClient_authToken, process.env.XYPRISS_INTERNAL_TOKEN ||
4920
+ process.env.XYPRISS_XESS_AUTH_TOKEN ||
4921
+ "", "f");
4922
+ if (!tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_authToken, "f") && sessionDir) {
4923
+ try {
4924
+ const tokenFile = path__namespace.join(sessionDir, ".auth_token");
4925
+ if (fs__namespace.existsSync(tokenFile)) {
4926
+ tslib_es6_js.__classPrivateFieldSet(this, _SynapxClient_authToken, fs__namespace.readFileSync(tokenFile, "utf8").trim(), "f");
4927
+ }
4928
+ }
4929
+ catch { }
4930
+ }
5100
4931
  this.socketPath =
5101
4932
  customSocketPath ||
5102
4933
  (sessionDir ? path__namespace.join(sessionDir, "synapx.sock") : "");
@@ -5164,18 +4995,12 @@ class SynapxClient {
5164
4995
  return;
5165
4996
  }
5166
4997
  const internalSig = getInternalSignature();
5167
- let sessionKey = "";
5168
- try {
5169
- sessionKey = XessIpcClient.getActiveSessionKey();
5170
- }
5171
- catch { }
5172
4998
  try {
5173
4999
  const child = node_child_process.spawn(binPath, ["daemon", process.cwd()], {
5174
5000
  detached: true,
5175
5001
  stdio: "inherit",
5176
5002
  env: {
5177
5003
  ...process.env,
5178
- ...(sessionKey ? { XYPRISS_XESS_SESSION_KEY: sessionKey } : {}),
5179
5004
  ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5180
5005
  NO_COLOR: "1",
5181
5006
  },
@@ -5211,7 +5036,7 @@ class SynapxClient {
5211
5036
  * Connects to the libSynapx server and performs the Zero-Trust handshake.
5212
5037
  */
5213
5038
  async connect() {
5214
- if (this.socket && !this.socket.destroyed && this.isHandshakeComplete) {
5039
+ if (tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f") && !tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f").destroyed && this.isHandshakeComplete) {
5215
5040
  return;
5216
5041
  }
5217
5042
  if (!this.isAvailable()) {
@@ -5225,7 +5050,7 @@ class SynapxClient {
5225
5050
  return reject(new Error("libSynapx: No active session socket path configured (XYPRISS_USER_TMP is unset)"));
5226
5051
  }
5227
5052
  const client = net__namespace.createConnection(this.socketPath, () => {
5228
- this.socket = client;
5053
+ tslib_es6_js.__classPrivateFieldSet(this, _SynapxClient_socket, client, "f");
5229
5054
  this.performHandshake()
5230
5055
  .then(() => {
5231
5056
  this.isHandshakeComplete = true;
@@ -5255,14 +5080,14 @@ class SynapxClient {
5255
5080
  * Writes a framed packet to the socket.
5256
5081
  */
5257
5082
  writeFrame(msgType, payload) {
5258
- if (!this.socket || this.socket.destroyed) {
5083
+ if (!tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f") || tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f").destroyed) {
5259
5084
  throw new Error("libSynapx: socket is not connected");
5260
5085
  }
5261
5086
  const header = Buffer.alloc(HEADER_SIZE$1);
5262
5087
  header.writeUInt8(MAGIC_BYTE, 0);
5263
5088
  header.writeUInt8(msgType, 1);
5264
5089
  header.writeUInt32BE(payload.length, 2);
5265
- this.socket.write(Buffer.concat([header, payload]));
5090
+ tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f").write(Buffer.concat([header, payload]));
5266
5091
  }
5267
5092
  /**
5268
5093
  * Performs initial zero-trust handshake.
@@ -5274,7 +5099,7 @@ class SynapxClient {
5274
5099
  }, 3000);
5275
5100
  const hsPayload = Buffer.from(JSON.stringify({
5276
5101
  sessionHash: this.sessionHash,
5277
- token: this.authToken,
5102
+ token: tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_authToken, "f"),
5278
5103
  clientPid: process.pid,
5279
5104
  }));
5280
5105
  // Temporarily intercept handshake response frame
@@ -5301,9 +5126,9 @@ class SynapxClient {
5301
5126
  try {
5302
5127
  const ack = JSON.parse(payloadBuf.toString("utf8"));
5303
5128
  if (ack.auth) {
5304
- this.sessionKey = ack.sessionKey || "";
5129
+ tslib_es6_js.__classPrivateFieldSet(this, _SynapxClient_sessionKey, ack.sessionKey || "", "f");
5305
5130
  try {
5306
- this.socket?.unref();
5131
+ tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f")?.unref();
5307
5132
  }
5308
5133
  catch { }
5309
5134
  return resolve();
@@ -5395,6 +5220,12 @@ class SynapxClient {
5395
5220
  * Executes a multiplexed RPC call over the persistent private channel with full args and options descriptors.
5396
5221
  */
5397
5222
  async call(module, action, args = [], opts = {}, timeoutMs = 60000) {
5223
+ if (module === "env") {
5224
+ const callerInfo = getVerifiedCallerInfo();
5225
+ if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5226
+ throw new Error(`libSynapx: Unauthorized caller for restricted module '${module}'`);
5227
+ }
5228
+ }
5398
5229
  await this.connect();
5399
5230
  const stringArgs = Array.isArray(args)
5400
5231
  ? args.map((a) => String(a))
@@ -5433,6 +5264,12 @@ class SynapxClient {
5433
5264
  * with transparent automatic fallback to stdin pipe subprocess on edge platforms.
5434
5265
  */
5435
5266
  callSync(module, action, args = [], opts = {}) {
5267
+ if (module === "env") {
5268
+ const callerInfo = getVerifiedCallerInfo();
5269
+ if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5270
+ throw new Error(`libSynapx: Unauthorized caller for restricted module '${module}'`);
5271
+ }
5272
+ }
5436
5273
  if (!this.socketPath || !fs__namespace.existsSync(this.socketPath)) {
5437
5274
  this.ensureDaemon();
5438
5275
  if (!this.socketPath || !fs__namespace.existsSync(this.socketPath)) {
@@ -5440,10 +5277,10 @@ class SynapxClient {
5440
5277
  }
5441
5278
  }
5442
5279
  try {
5443
- if (!this.syncBridge) {
5444
- this.syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.authToken);
5280
+ if (!tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_syncBridge, "f")) {
5281
+ tslib_es6_js.__classPrivateFieldSet(this, _SynapxClient_syncBridge, SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_authToken, "f")), "f");
5445
5282
  }
5446
- return this.syncBridge.callSync(module, action, args, opts);
5283
+ return tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_syncBridge, "f").callSync(module, action, args, opts);
5447
5284
  }
5448
5285
  catch {
5449
5286
  // Resilient fallback to stdin subprocess pipeline
@@ -5454,6 +5291,12 @@ class SynapxClient {
5454
5291
  * Subprocess-based synchronous fallback pipeline (streaming via stdin to prevent E2BIG).
5455
5292
  */
5456
5293
  callSyncSubprocess(module, action, args = [], opts = {}) {
5294
+ if (module === "env") {
5295
+ const callerInfo = getVerifiedCallerInfo();
5296
+ if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5297
+ throw new Error(`libSynapx: Unauthorized caller for restricted module '${module}'`);
5298
+ }
5299
+ }
5457
5300
  const stringArgs = Array.isArray(args)
5458
5301
  ? args.map((a) => String(a))
5459
5302
  : [];
@@ -5530,7 +5373,7 @@ setTimeout(() => process.exit(1), 5000);
5530
5373
  script,
5531
5374
  this.socketPath,
5532
5375
  this.sessionHash,
5533
- this.authToken,
5376
+ tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_authToken, "f"),
5534
5377
  ], {
5535
5378
  input: inputPayload,
5536
5379
  encoding: "utf8",
@@ -5546,14 +5389,14 @@ setTimeout(() => process.exit(1), 5000);
5546
5389
  }
5547
5390
  destroy() {
5548
5391
  this.isHandshakeComplete = false;
5549
- if (this.syncBridge) {
5550
- this.syncBridge.destroy();
5551
- this.syncBridge = null;
5392
+ if (tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_syncBridge, "f")) {
5393
+ tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_syncBridge, "f").destroy();
5394
+ tslib_es6_js.__classPrivateFieldSet(this, _SynapxClient_syncBridge, null, "f");
5552
5395
  }
5553
- if (this.socket) {
5554
- this.socket.removeAllListeners();
5555
- this.socket.destroy();
5556
- this.socket = null;
5396
+ if (tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f")) {
5397
+ tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f").removeAllListeners();
5398
+ tslib_es6_js.__classPrivateFieldGet(this, _SynapxClient_socket, "f").destroy();
5399
+ tslib_es6_js.__classPrivateFieldSet(this, _SynapxClient_socket, null, "f");
5557
5400
  }
5558
5401
  for (const [id, pending] of this.pendingCalls.entries()) {
5559
5402
  clearTimeout(pending.timeout);
@@ -5564,6 +5407,7 @@ setTimeout(() => process.exit(1), 5000);
5564
5407
  this.rxBytesTotal = 0;
5565
5408
  }
5566
5409
  }
5410
+ _SynapxClient_socket = new WeakMap(), _SynapxClient_sessionKey = new WeakMap(), _SynapxClient_authToken = new WeakMap(), _SynapxClient_syncBridge = new WeakMap();
5567
5411
  SynapxClient.instance = null;
5568
5412
 
5569
5413
  /**
@@ -5640,6 +5484,12 @@ class XyPrissRunner {
5640
5484
  * Executes a command synchronously via libSynapx IPC and returns the parsed result.
5641
5485
  */
5642
5486
  runSync(module, action, args = [], options = {}) {
5487
+ if (module === "env") {
5488
+ const callerInfo = getVerifiedCallerInfo();
5489
+ if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5490
+ throw new XyPrissError(module, action, "Access denied: untrusted caller for env module");
5491
+ }
5492
+ }
5643
5493
  try {
5644
5494
  const synapx = SynapxClient.getInstance();
5645
5495
  return synapx.callSync(module, action, args, options);
@@ -5654,6 +5504,12 @@ class XyPrissRunner {
5654
5504
  * Executes a command asynchronously via libSynapx IPC and returns the parsed result.
5655
5505
  */
5656
5506
  async runAsync(module, action, args = [], options = {}) {
5507
+ if (module === "env") {
5508
+ const callerInfo = getVerifiedCallerInfo();
5509
+ if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5510
+ throw new XyPrissError(module, action, "Access denied: untrusted caller for env module");
5511
+ }
5512
+ }
5657
5513
  try {
5658
5514
  const synapx = SynapxClient.getInstance();
5659
5515
  return await synapx.call(module, action, args, options);
@@ -5668,6 +5524,9 @@ class XyPrissRunner {
5668
5524
  * Run a module action and return the stdout as a Readable stream
5669
5525
  */
5670
5526
  runStream(module, action, args = [], options = {}) {
5527
+ if (module === "env") {
5528
+ throw new XyPrissError(module, action, "Streaming env module is forbidden");
5529
+ }
5671
5530
  const internalSig = getInternalSignature();
5672
5531
  const cmdArgs = [
5673
5532
  "--root",
@@ -5704,6 +5563,9 @@ class XyPrissRunner {
5704
5563
  * Run a module action and return the stdin as a Writable stream
5705
5564
  */
5706
5565
  runWritableStream(module, action, args = [], options = {}) {
5566
+ if (module === "env") {
5567
+ throw new XyPrissError(module, action, "Streaming env module is forbidden");
5568
+ }
5707
5569
  const internalSig = getInternalSignature();
5708
5570
  const cmdArgs = [
5709
5571
  "--root",
@@ -5735,57 +5597,168 @@ class XyPrissRunner {
5735
5597
  }
5736
5598
  }
5737
5599
 
5738
- /* *****************************************************************************
5739
- * Nehonix XyPriss System
5740
- *
5741
- * ACCESS RESTRICTIONS:
5742
- * - This software is exclusively for use by Authorized Personnel of NEHONIX
5743
- * - Intended for Internal Use only within NEHONIX operations
5744
- * - No rights granted to unauthorized individuals or entities
5745
- * - All modifications are works made for hire assigned to NEHONIX
5746
- *
5747
- * PROHIBITED ACTIVITIES:
5748
- * - Copying, distributing, or sublicensing without written permission
5749
- * - Reverse engineering, decompiling, or disassembling
5750
- * - Creating derivative works without explicit authorization
5751
- * - External use or commercial distribution outside NEHONIX
5752
- *
5753
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5754
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
5755
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
5756
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
5757
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
5758
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
5759
- * SOFTWARE.
5760
- *
5761
- * For questions or permissions, contact:
5762
- * NEHONIX Legal Department
5763
- * Email: legal@nehonix.com
5764
- * Website: www.nehonix.com
5765
- ***************************************************************************** */
5766
5600
  /**
5767
- * **Base API Class**
5601
+ * Returns the absolute path to the XyPriss shared temp directory.
5768
5602
  *
5769
- * Serves as the foundational layer for all XyPriss domain-specific APIs.
5770
- * It encapsulates the `XyPrissRunner` instance, ensuring that all subclasses
5771
- * have unified access to the underlying XHSC bridge for high-performance system operations.
5603
+ * @returns {string} Path to `<os.tmpdir>/nehonix.xypriss.data`
5772
5604
  */
5773
- class BaseApi {
5774
- /**
5775
- * Initializes the Base API with a shared runner instance.
5776
- * @param runner - The XyPrissRunner used to invoke native XHSC binaries.
5777
- */
5778
- constructor(runner) {
5779
- this.runner = runner;
5780
- }
5605
+ function getXyprissTempDir() {
5606
+ const sys = getSysApi();
5607
+ return sys.path.join(sys.path.tempDir(), "nehonix.xypriss.data");
5781
5608
  }
5782
5609
  /**
5783
- * **Professional Path Manipulation API**
5784
- *
5785
- * The `PathApi` class provides a comprehensive suite of robust, platform-independent
5786
- * utilities for working with file and directory paths. By bridging directly to
5787
- * the XHSC native binary, it ensures rigorous adherence to filesystem standards
5788
- * across Windows, macOS, and Linux environments.
5610
+ * Resolves and ensures a sub-path within the XyPriss temp directory exists.
5611
+ *
5612
+ * @param {string | string[]} _p - Sub-path segment(s) to append.
5613
+ * @returns {string} The absolute resolved temp sub-path.
5614
+ */
5615
+ function createXyprissTempDir(_p) {
5616
+ const sys = getSysApi();
5617
+ const base = getXyprissTempDir();
5618
+ const segment = typeof _p === "string"
5619
+ ? _p
5620
+ : _p.includes("/")
5621
+ ? _p.map((p) => p.replace("/", "")).join("/")
5622
+ : _p.join("/");
5623
+ // Use the native corrective layer to prevent doubling or redundant separators
5624
+ const rawPath = segment.startsWith(base)
5625
+ ? segment
5626
+ : sys.path.join(base, segment);
5627
+ const normalisedPath = sys.path.correct(rawPath, { tentative: 2 });
5628
+ if (!sys.fs.exist(normalisedPath)) {
5629
+ sys.fs.mkdir(normalisedPath, { parents: true });
5630
+ }
5631
+ return normalisedPath;
5632
+ }
5633
+ /**
5634
+ * **Session Temp Directory (singleton)**
5635
+ *
5636
+ * Unique sub-path generated once per process lifetime under the XyPriss
5637
+ * temp root (`<os.tmpdir>/nehonix.xypriss.data/xuser/<hex4>`).
5638
+ *
5639
+ * The value is memoized on first access and remains stable for the entire
5640
+ * duration of the running process, ensuring all callers within the same
5641
+ * session share the same isolated scratch space.
5642
+ */
5643
+ let _sessionTmpDir = null;
5644
+ /**
5645
+ * Returns the process-scoped user temp directory path for THIS active server instance.
5646
+ *
5647
+ * Generates an instance ID hash once and caches it for the lifetime of the process.
5648
+ * E.g. `/tmp/nehonix.xypriss.data/xuser/12daa75a`
5649
+ *
5650
+ * @returns {string} Absolute path to instance temp directory
5651
+ */
5652
+ function generateXUserTmpDir() {
5653
+ if (_sessionTmpDir !== null) {
5654
+ return _sessionTmpDir;
5655
+ }
5656
+ const sys = getSysApi();
5657
+ // 1. Adopt the session directory allocated exclusively by the libProc supervisor
5658
+ const envSession = sys?.__env__?.get("XYPRISS_USER_TMP") ||
5659
+ sys?.__env__?.get("XESS_SESSION_TMP") ||
5660
+ (typeof process !== "undefined"
5661
+ ? (process.env?.XYPRISS_USER_TMP || process.env?.XESS_SESSION_TMP)
5662
+ : undefined);
5663
+ if (envSession && typeof envSession === "string") {
5664
+ _sessionTmpDir = envSession;
5665
+ if (sys?.fs && !sys.fs.exist(_sessionTmpDir)) {
5666
+ sys.fs.mkdir(_sessionTmpDir, { parents: true });
5667
+ }
5668
+ return _sessionTmpDir;
5669
+ }
5670
+ // No supervisor session provisioned by libProc: unconfined execution has no valid session
5671
+ return "";
5672
+ }
5673
+ /**
5674
+ * Returns the unique 8-character session hash ID for the active server instance.
5675
+ * Delegated exclusively to the libProc supervisor (Single Source of Truth).
5676
+ */
5677
+ function getSessionHash() {
5678
+ const sys = getSysApi();
5679
+ const envHash = sys?.__env__?.get("XYPRISS_SESSION_HASH") ||
5680
+ (typeof process !== "undefined" ? process.env?.XYPRISS_SESSION_HASH : undefined);
5681
+ if (envHash && typeof envHash === "string") {
5682
+ return envHash;
5683
+ }
5684
+ if (_sessionTmpDir) {
5685
+ if (sys?.path) {
5686
+ return sys.path.basename(_sessionTmpDir);
5687
+ }
5688
+ const parts = _sessionTmpDir.split(/[/\\]/).filter(Boolean);
5689
+ return parts[parts.length - 1] || "";
5690
+ }
5691
+ return "";
5692
+ }
5693
+ /**
5694
+ * Backward-compatibility alias for getSessionHash().
5695
+ */
5696
+ function getInstanceId() {
5697
+ return getSessionHash();
5698
+ }
5699
+
5700
+ /* *****************************************************************************
5701
+ * Nehonix XyPriss System
5702
+ *
5703
+ * ACCESS RESTRICTIONS:
5704
+ * - This software is exclusively for use by Authorized Personnel of NEHONIX
5705
+ * - Intended for Internal Use only within NEHONIX operations
5706
+ * - No rights granted to unauthorized individuals or entities
5707
+ * - All modifications are works made for hire assigned to NEHONIX
5708
+ *
5709
+ * PROHIBITED ACTIVITIES:
5710
+ * - Copying, distributing, or sublicensing without written permission
5711
+ * - Reverse engineering, decompiling, or disassembling
5712
+ * - Creating derivative works without explicit authorization
5713
+ * - External use or commercial distribution outside NEHONIX
5714
+ *
5715
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5716
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
5717
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
5718
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
5719
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
5720
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
5721
+ * SOFTWARE.
5722
+ *
5723
+ * For questions or permissions, contact:
5724
+ * NEHONIX Legal Department
5725
+ * Email: legal@nehonix.com
5726
+ * Website: www.nehonix.com
5727
+ ***************************************************************************** */
5728
+ const _runnerStore = new WeakMap();
5729
+ /**
5730
+ * **Base API Class**
5731
+ *
5732
+ * Serves as the foundational layer for all XyPriss domain-specific APIs.
5733
+ * It encapsulates the `XyPrissRunner` instance, ensuring that all subclasses
5734
+ * have unified access to the underlying XHSC bridge for high-performance system operations.
5735
+ */
5736
+ class BaseApi {
5737
+ /**
5738
+ * Initializes the Base API with a shared runner instance.
5739
+ * @param runner - The XyPrissRunner used to invoke native XHSC binaries.
5740
+ */
5741
+ constructor(runner) {
5742
+ _runnerStore.set(this, runner);
5743
+ }
5744
+ /**
5745
+ * Protected accessor for internal engine classes only.
5746
+ * Blocked for external callers and third-party modules.
5747
+ */
5748
+ get runner() {
5749
+ if (!isImmediateInternalEngineCall()) {
5750
+ return undefined;
5751
+ }
5752
+ return _runnerStore.get(this);
5753
+ }
5754
+ }
5755
+ /**
5756
+ * **Professional Path Manipulation API**
5757
+ *
5758
+ * The `PathApi` class provides a comprehensive suite of robust, platform-independent
5759
+ * utilities for working with file and directory paths. By bridging directly to
5760
+ * the XHSC native binary, it ensures rigorous adherence to filesystem standards
5761
+ * across Windows, macOS, and Linux environments.
5789
5762
  *
5790
5763
  * **Key Benefits:**
5791
5764
  * - **Cross-Platform Consistency:** Eliminates separator issues (`/` vs `\`).
@@ -6383,30 +6356,34 @@ class FSBase extends PathApi {
6383
6356
  * Email: legal@nehonix.com
6384
6357
  * Website: www.nehonix.com
6385
6358
  ***************************************************************************** */
6359
+ var _FileHandle_id, _FileHandle_runner, _FileHandle_synapx;
6386
6360
  /**
6387
6361
  * **High-Performance File Toolbox**
6388
6362
  * Exposed via __sys__.fs.open(path, callback)
6389
6363
  */
6390
6364
  class FileHandle {
6391
6365
  constructor(id, runner) {
6392
- this.id = id;
6393
- this.runner = runner;
6394
- this.synapx = SynapxClient.getInstance();
6366
+ _FileHandle_id.set(this, void 0);
6367
+ _FileHandle_runner.set(this, void 0);
6368
+ _FileHandle_synapx.set(this, void 0);
6369
+ tslib_es6_js.__classPrivateFieldSet(this, _FileHandle_id, id, "f");
6370
+ tslib_es6_js.__classPrivateFieldSet(this, _FileHandle_runner, runner, "f");
6371
+ tslib_es6_js.__classPrivateFieldSet(this, _FileHandle_synapx, SynapxClient.getInstance(), "f");
6395
6372
  }
6396
6373
  /**
6397
6374
  * **Get Native Handle ID**
6398
6375
  */
6399
6376
  get nativeId() {
6400
- return this.id;
6377
+ return tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f");
6401
6378
  }
6402
6379
  /**
6403
6380
  * **Read from File**
6404
6381
  * @param length - Max bytes to read
6405
6382
  */
6406
6383
  async read(length) {
6407
- if (this.synapx.isAvailable()) {
6408
- const res = await this.synapx.call("fs", "read-handle", [
6409
- String(this.id),
6384
+ if (tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").isAvailable()) {
6385
+ const res = await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").call("fs", "read-handle", [
6386
+ String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f")),
6410
6387
  String(length),
6411
6388
  ]);
6412
6389
  if (typeof res === "string") {
@@ -6419,8 +6396,8 @@ class FileHandle {
6419
6396
  }
6420
6397
  return Buffer.from(res || "");
6421
6398
  }
6422
- const res = (await this.runner.runAsync("fs", "read-handle", [
6423
- String(this.id),
6399
+ const res = (await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_runner, "f").runAsync("fs", "read-handle", [
6400
+ String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f")),
6424
6401
  String(length),
6425
6402
  ]));
6426
6403
  return Buffer.from(res?.content || res || "", "hex");
@@ -6431,15 +6408,15 @@ class FileHandle {
6431
6408
  */
6432
6409
  async write(data) {
6433
6410
  const raw = typeof data === "string" ? Buffer.from(data) : data;
6434
- if (this.synapx.isAvailable()) {
6435
- const res = await this.synapx.call("fs", "write-handle", [
6436
- String(this.id),
6411
+ if (tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").isAvailable()) {
6412
+ const res = await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").call("fs", "write-handle", [
6413
+ String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f")),
6437
6414
  raw.toString("hex"),
6438
6415
  ]);
6439
6416
  return typeof res === "number" ? res : (res?.n ?? raw.length);
6440
6417
  }
6441
- const res = (await this.runner.runAsync("fs", "write-handle", [
6442
- String(this.id),
6418
+ const res = (await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_runner, "f").runAsync("fs", "write-handle", [
6419
+ String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f")),
6443
6420
  raw.toString("hex"),
6444
6421
  ]));
6445
6422
  return typeof res === "number" ? res : (res?.n ?? raw.length);
@@ -6450,16 +6427,16 @@ class FileHandle {
6450
6427
  * @param whence - 0: Start, 1: Current, 2: End
6451
6428
  */
6452
6429
  async seek(offset, whence = 0) {
6453
- if (this.synapx.isAvailable()) {
6454
- const res = await this.synapx.call("fs", "seek-handle", [
6455
- String(this.id),
6430
+ if (tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").isAvailable()) {
6431
+ const res = await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").call("fs", "seek-handle", [
6432
+ String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f")),
6456
6433
  String(offset),
6457
6434
  String(whence),
6458
6435
  ]);
6459
6436
  return typeof res === "number" ? res : (res?.pos ?? 0);
6460
6437
  }
6461
- const res = (await this.runner.runAsync("fs", "seek-handle", [
6462
- String(this.id),
6438
+ const res = (await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_runner, "f").runAsync("fs", "seek-handle", [
6439
+ String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f")),
6463
6440
  String(offset),
6464
6441
  String(whence),
6465
6442
  ]));
@@ -6469,39 +6446,257 @@ class FileHandle {
6469
6446
  * **Get File Statistics**
6470
6447
  */
6471
6448
  async stat() {
6472
- if (this.synapx.isAvailable()) {
6473
- return await this.synapx.call("fs", "stat-handle", [
6474
- String(this.id),
6449
+ if (tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").isAvailable()) {
6450
+ return await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").call("fs", "stat-handle", [
6451
+ String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f")),
6475
6452
  ]);
6476
6453
  }
6477
- return (await this.runner.runAsync("fs", "stat-handle", [
6478
- String(this.id),
6454
+ return (await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_runner, "f").runAsync("fs", "stat-handle", [
6455
+ String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f")),
6479
6456
  ]));
6480
6457
  }
6481
6458
  /**
6482
6459
  * **Close Handle**
6483
6460
  */
6484
6461
  async close() {
6485
- if (this.synapx.isAvailable()) {
6486
- await this.synapx.call("fs", "close", [String(this.id)]);
6462
+ if (tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").isAvailable()) {
6463
+ await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_synapx, "f").call("fs", "close", [String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f"))]);
6487
6464
  }
6488
6465
  else {
6489
- await this.runner.runAsync("fs", "close", [String(this.id)]);
6466
+ await tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_runner, "f").runAsync("fs", "close", [String(tslib_es6_js.__classPrivateFieldGet(this, _FileHandle_id, "f"))]);
6490
6467
  }
6491
6468
  }
6492
6469
  }
6470
+ _FileHandle_id = new WeakMap(), _FileHandle_runner = new WeakMap(), _FileHandle_synapx = new WeakMap();
6493
6471
 
6494
- const logger = QuickLogger.for("XHSC:TempFile");
6495
- class TempFileManager {
6496
- constructor() {
6497
- this.trackedFiles = new Map();
6498
- this.exitHooksRegistered = false;
6499
- this.registerExitHooks();
6472
+ /**
6473
+ * ANSI color codes for terminal output
6474
+ */
6475
+ const ANSI = {
6476
+ reset: "\x1b[0m",
6477
+ bold: "\x1b[1m",
6478
+ dim: "\x1b[2m",
6479
+ // Foreground colors
6480
+ black: "\x1b[30m",
6481
+ yellow: "\x1b[33m",
6482
+ blue: "\x1b[34m",
6483
+ cyan: "\x1b[36m",
6484
+ white: "\x1b[37m",
6485
+ gray: "\x1b[90m",
6486
+ // Bright foreground
6487
+ brightRed: "\x1b[91m",
6488
+ brightGreen: "\x1b[92m",
6489
+ brightYellow: "\x1b[93m",
6490
+ brightBlue: "\x1b[94m",
6491
+ brightMagenta: "\x1b[95m",
6492
+ brightCyan: "\x1b[96m",
6493
+ // Background colors
6494
+ bgRed: "\x1b[41m",
6495
+ bgGreen: "\x1b[42m",
6496
+ bgYellow: "\x1b[43m",
6497
+ bgBlue: "\x1b[44m",
6498
+ bgMagenta: "\x1b[45m",
6499
+ bgCyan: "\x1b[46m",
6500
+ };
6501
+ const LOG_CONFIGS = {
6502
+ info: {
6503
+ icon: "ℹ️ ",
6504
+ color: ANSI.brightCyan,
6505
+ label: "INFO",
6506
+ labelColor: `${ANSI.bgCyan}${ANSI.black}`,
6507
+ },
6508
+ success: {
6509
+ icon: "✅",
6510
+ color: ANSI.brightGreen,
6511
+ label: "OK",
6512
+ labelColor: `${ANSI.bgGreen}${ANSI.black}`,
6513
+ },
6514
+ warn: {
6515
+ icon: "⚠️ ",
6516
+ color: ANSI.brightYellow,
6517
+ label: "WARN",
6518
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
6519
+ },
6520
+ error: {
6521
+ icon: "❌",
6522
+ color: ANSI.brightRed,
6523
+ label: "ERROR",
6524
+ labelColor: `${ANSI.bgRed}${ANSI.white}`,
6525
+ },
6526
+ debug: {
6527
+ icon: "-",
6528
+ color: ANSI.gray,
6529
+ label: "DEBUG",
6530
+ labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
6531
+ },
6532
+ http: {
6533
+ icon: "🌐",
6534
+ color: ANSI.brightBlue,
6535
+ label: "HTTP",
6536
+ labelColor: `${ANSI.bgBlue}${ANSI.white}`,
6537
+ },
6538
+ swagger: {
6539
+ icon: "🛡️ ",
6540
+ color: ANSI.brightMagenta,
6541
+ label: "SWAGGER",
6542
+ labelColor: `${ANSI.bgMagenta}${ANSI.white}`,
6543
+ },
6544
+ db: {
6545
+ icon: "🗄️ ",
6546
+ color: ANSI.yellow,
6547
+ label: "DB",
6548
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
6549
+ },
6550
+ auth: {
6551
+ icon: "🔐",
6552
+ color: ANSI.brightYellow,
6553
+ label: "AUTH",
6554
+ labelColor: `${ANSI.bgYellow}${ANSI.black}`,
6555
+ },
6556
+ };
6557
+ const LEVEL_RANK = {
6558
+ silent: 0,
6559
+ error: 1,
6560
+ warn: 2,
6561
+ info: 3,
6562
+ success: 3,
6563
+ http: 3,
6564
+ swagger: 3,
6565
+ db: 3,
6566
+ auth: 3,
6567
+ debug: 4,
6568
+ verbose: 5,
6569
+ };
6570
+ class QuickLogger {
6571
+ constructor(context) {
6572
+ this.context = context;
6500
6573
  }
6501
- static getInstance() {
6502
- if (!TempFileManager.instance) {
6503
- TempFileManager.instance = new TempFileManager();
6504
- }
6574
+ // ─── Static factory ───────────────────────────────────────────────────────
6575
+ static for(context) {
6576
+ return new QuickLogger(context);
6577
+ }
6578
+ static shouldLog(level) {
6579
+ const sys = getSysApi();
6580
+ let isDebug = false;
6581
+ if (sys?.__env__) {
6582
+ isDebug =
6583
+ sys.__env__.get("DEBUG") ||
6584
+ sys.__env__.get("XYPRISS_DEBUG") ||
6585
+ sys.__env__.get("DEBUG_FS");
6586
+ }
6587
+ else if (typeof process !== "undefined" && process.env) {
6588
+ isDebug =
6589
+ process.env.DEBUG ||
6590
+ process.env.XYPRISS_DEBUG ||
6591
+ process.env.DEBUG_FS;
6592
+ }
6593
+ if (isDebug) {
6594
+ return true;
6595
+ }
6596
+ try {
6597
+ const logging = ConfigurationManager.get("logging");
6598
+ if (logging) {
6599
+ if (logging.enabled === false) {
6600
+ return false;
6601
+ }
6602
+ // Check logging.types overrides
6603
+ if (level === "error" && logging.types?.errors === false)
6604
+ return false;
6605
+ if (level === "warn" && logging.types?.warnings === false)
6606
+ return false;
6607
+ if (level === "debug" && logging.types?.debug === false)
6608
+ return false;
6609
+ if (level === "debug" && logging.types?.debug === true)
6610
+ return true;
6611
+ // Check logging.level rank
6612
+ const configuredLevel = (logging.level || "info").toLowerCase();
6613
+ const configuredRank = LEVEL_RANK[configuredLevel] ?? 3;
6614
+ const messageRank = LEVEL_RANK[level] ?? 3;
6615
+ return messageRank <= configuredRank;
6616
+ }
6617
+ }
6618
+ catch { }
6619
+ // Default ranking if no config: info level (rank 3)
6620
+ const defaultRank = 3;
6621
+ const messageRank = LEVEL_RANK[level] ?? 3;
6622
+ return messageRank <= defaultRank;
6623
+ }
6624
+ // ─── Core log method ──────────────────────────────────────────────────────
6625
+ log(level, ...args) {
6626
+ if (!QuickLogger.shouldLog(level)) {
6627
+ return;
6628
+ }
6629
+ const cfg = LOG_CONFIGS[level];
6630
+ const timestamp = QuickLogger.showTimestamp
6631
+ ? `${ANSI.dim}${ANSI.gray}${new Date().toISOString()}${ANSI.reset} `
6632
+ : "";
6633
+ const label = `${cfg.labelColor}${ANSI.bold} ${cfg.label} ${ANSI.reset}`;
6634
+ const ctx = `${ANSI.dim}${ANSI.cyan}[${this.context}]${ANSI.reset}`;
6635
+ // First arg gets the level color + icon, rest are passed raw so Node.js
6636
+ // pretty-prints objects/arrays/Errors natively (no JSON.stringify needed).
6637
+ const [first, ...rest] = args;
6638
+ const prefix = `${timestamp}${label} ${ctx} ${cfg.color}${cfg.icon} ${String(first)}${ANSI.reset}`;
6639
+ const consoleFn = level === "error"
6640
+ ? console.error
6641
+ : level === "warn"
6642
+ ? console.warn
6643
+ : console.log;
6644
+ rest.length > 0 ? consoleFn(prefix, ...rest) : consoleFn(prefix);
6645
+ }
6646
+ // ─── Public methods ───────────────────────────────────────────────────────
6647
+ info(...args) {
6648
+ this.log("info", ...args);
6649
+ }
6650
+ success(...args) {
6651
+ this.log("success", ...args);
6652
+ }
6653
+ warn(...args) {
6654
+ this.log("warn", ...args);
6655
+ }
6656
+ error(...args) {
6657
+ this.log("error", ...args);
6658
+ }
6659
+ debug(...args) {
6660
+ this.log("debug", ...args);
6661
+ }
6662
+ http(...args) {
6663
+ this.log("http", ...args);
6664
+ }
6665
+ swagger(...args) {
6666
+ this.log("swagger", ...args);
6667
+ }
6668
+ db(...args) {
6669
+ this.log("db", ...args);
6670
+ }
6671
+ auth(...args) {
6672
+ this.log("auth", ...args);
6673
+ }
6674
+ // ─── Convenience: banner / separator ─────────────────────────────────────
6675
+ banner(title) {
6676
+ const line = `${ANSI.blue}${"─".repeat(60)}${ANSI.reset}`;
6677
+ const centered = title
6678
+ .padStart(30 + Math.floor(title.length / 2))
6679
+ .padEnd(60);
6680
+ console.log(`\n${line}`);
6681
+ console.log(`${ANSI.bold}${ANSI.brightCyan}${centered}${ANSI.reset}`);
6682
+ console.log(`${line}\n`);
6683
+ }
6684
+ }
6685
+ QuickLogger.showTimestamp = true;
6686
+ // ─── Default singleton logger ──────────────────────────────────────────────
6687
+ // export const logger = QuickLogger.for("");
6688
+
6689
+ const logger = QuickLogger.for("XHSC:TempFile");
6690
+ class TempFileManager {
6691
+ constructor() {
6692
+ this.trackedFiles = new Map();
6693
+ this.exitHooksRegistered = false;
6694
+ this.registerExitHooks();
6695
+ }
6696
+ static getInstance() {
6697
+ if (!TempFileManager.instance) {
6698
+ TempFileManager.instance = new TempFileManager();
6699
+ }
6505
6700
  return TempFileManager.instance;
6506
6701
  }
6507
6702
  /**
@@ -8279,775 +8474,191 @@ class FSExtended extends FSWatch {
8279
8474
  *
8280
8475
  * @param {string} p - Path to the file.
8281
8476
  *
8282
- * @example
8283
- * __sys__.fs.unlock("exclusive.data");
8284
- */
8285
- this.unlock = (p) => {
8286
- this.runner.runSync("fs", "unlock", [p]);
8287
- };
8288
- /**
8289
- * **Secure Permission Write (Asynchronous)**
8290
- *
8291
- * Writes data to a file and immediately applies a restricted permission mode.
8292
- *
8293
- * @param {string} p - Destination path.
8294
- * @param {any} data - Data to write.
8295
- * @param {string} mode - Octal mode (e.g., '600').
8296
- * @returns {Promise<void>}
8297
- */
8298
- this.writeSecure = async (p, data, mode) => {
8299
- let writeData = "";
8300
- if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) {
8301
- writeData = data;
8302
- }
8303
- else if (typeof data === "object" && data !== null) {
8304
- writeData = xyprissSecurity.XStringify(data);
8305
- }
8306
- else {
8307
- writeData = String(data);
8308
- }
8309
- await this.runner.runAsync("fs", "write-secure", [p], {
8310
- mode,
8311
- input: writeData,
8312
- });
8313
- };
8314
- /**
8315
- * **Secure Permission Write (Synchronous)**
8316
- *
8317
- * Synchronously writes data and applies a restricted mode.
8318
- *
8319
- * @param {string} p - Destination path.
8320
- * @param {any} data - Data to write.
8321
- * @param {string} mode - Octal mode.
8322
- */
8323
- this.writeSecureSync = (p, data, mode) => {
8324
- let writeData = "";
8325
- if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) {
8326
- writeData = data;
8327
- }
8328
- else if (typeof data === "object" && data !== null) {
8329
- writeData = xyprissSecurity.XStringify(data);
8330
- }
8331
- else {
8332
- writeData = String(data);
8333
- }
8334
- this.runner.runSync("fs", "write-secure", [p], {
8335
- mode,
8336
- input: writeData,
8337
- });
8338
- };
8339
- /**
8340
- * **Transparent File Encryption (AES-256-GCM)**
8341
- *
8342
- * Encrypts the contents of a file in-place using a symmetric key.
8343
- *
8344
- * @param {string} p - Path to the file.
8345
- * @param {string} key - Secret encryption key.
8346
- * @returns {Promise<void>}
8347
- */
8348
- this.encryptFile = async (p, key) => {
8349
- await xyprissSecurity.Cipher.crypto.encryptFile(p, p, key, "AES-256-GCM");
8350
- };
8351
- /**
8352
- * **Transparent File Decryption**
8353
- *
8354
- * Decrypts a file previously encrypted with `encryptFile()`.
8355
- *
8356
- * @param {string} p - Path to the file.
8357
- * @param {string} key - Secret decryption key.
8358
- * @returns {Promise<void>}
8359
- *
8360
- * @example
8361
- * await __sys__.fs.decryptFile("vault.bin", "passphrase");
8362
- */
8363
- this.decryptFile = async (p, key) => {
8364
- await xyprissSecurity.Cipher.crypto.decryptFile(p, p, key);
8365
- };
8366
- /**
8367
- * **Hardware-Bound Encryption**
8368
- *
8369
- * Encrypts a file using a key derived from the system's unique hardware ID.
8370
- * This file can ONLY be decrypted on this specific machine.
8371
- *
8372
- * @param {string} p - Path to the file.
8373
- * @param {string} key - User-provided part of the secret.
8374
- * @returns {Promise<void>}
8375
- */
8376
- this.hardwareEncryptFile = async (p, key) => {
8377
- await this.runner.runAsync("fs", "hardware-encrypt", [p], { key });
8378
- };
8379
- /**
8380
- * **Hardware-Bound Decryption**
8381
- *
8382
- * Decrypts a file using the system's hardware ID.
8383
- *
8384
- * @param {string} p - Path to the file.
8385
- * @param {string} key - User-provided part of the secret.
8386
- * @returns {Promise<void>}
8387
- */
8388
- this.hardwareDecryptFile = async (p, key) => {
8389
- await this.runner.runAsync("fs", "hardware-decrypt", [p], { key });
8390
- };
8391
- /**
8392
- * **Deep File Diff**
8393
- *
8394
- * Performs a line-by-line comparison between two files and returns
8395
- * all differences.
8396
- *
8397
- * @param {string} fileA - First file.
8398
- * @param {string} fileB - Second file.
8399
- * @returns {Array<Object>} List of differences with line numbers.
8400
- */
8401
- this.diffFiles = (fileA, fileB) => {
8402
- return this.runner.runSync("fs", "diff-files", [fileA, fileB]);
8403
- };
8404
- /**
8405
- * **Storage Analysis**
8406
- *
8407
- * Scans a directory and returns a list of the largest files found.
8408
- *
8409
- * @param {string} dir - Directory to scan.
8410
- * @param {number} [limit=50] - Number of top files to return.
8411
- * @returns {Array<Object>} List of paths and sizes.
8412
- */
8413
- this.topBigFiles = (dir, limit = 50) => {
8414
- return this.runner.runSync("fs", "top-big-files", [dir], {
8415
- limit,
8416
- });
8417
- };
8418
- }
8419
- }
8420
-
8421
- /* *****************************************************************************
8422
- * Nehonix XyPriss System
8423
- *
8424
- * ACCESS RESTRICTIONS:
8425
- * - This software is exclusively for use by Authorized Personnel of NEHONIX
8426
- * - Intended for Internal Use only within NEHONIX operations
8427
- * - No rights granted to unauthorized individuals or entities
8428
- * - All modifications are works made for hire assigned to NEHONIX
8429
- *
8430
- * PROHIBITED ACTIVITIES:
8431
- * - Copying, distributing, or sublicensing without written permission
8432
- * - Reverse engineering, decompiling, or disassembling
8433
- * - Creating derivative works without explicit authorization
8434
- * - External use or commercial distribution outside NEHONIX
8435
- *
8436
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
8437
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
8438
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8439
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8440
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
8441
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
8442
- * SOFTWARE.
8443
- *
8444
- * For questions or permissions, contact:
8445
- * NEHONIX Legal Department
8446
- * Email: legal@nehonix.com
8447
- * Website: www.nehonix.com
8448
- * ***************************************************************************** */
8449
- /**
8450
- * **Professional Filesystem API (High Performance)**
8451
- *
8452
- * The `FSApi` class provides a unified, high-performance interface for all filesystem operations.
8453
- * It is modularized into several specialized layers while maintaining a single cohesive API.
8454
- *
8455
- * **Modular Structure:**
8456
- * - `FSCore`: Fundamental operations (ls, read, write, move, rm)
8457
- * - `FSHelpers`: Convenience methods (JSON patterns, type checks)
8458
- * - `FSSearch`: Regex-based discovery and grep
8459
- * - `FSArchive`: Compression and TAR handling
8460
- * - `FSWatch`: Real-time monitoring and streaming
8461
- * - `FSExtended`: Advanced security and atomic operations
8462
- *
8463
- * @class FSApi
8464
- * @extends FSExtended
8465
- */
8466
- class FSApi extends FSExtended {
8467
- }
8468
-
8469
- /**
8470
- * **Config Syntax Parser**
8471
- *
8472
- * Handles resolution of dynamic references in configuration files:
8473
- * - `&(env).KEY` : Environment variables
8474
- * - `&(pkg).path` : package.json properties (dot-notation)
8475
- * - `&(this).KEY` : Properties from the currently parsed object
8476
- * - `&(const).KEY` : Build-time constants injected at construction
8477
- * - `&(date).FMT` : Current date/time helpers (ISO, YEAR, MONTH, DAY, TS)
8478
- * - `&(file).path` : Synchronous file content (use for secrets, certs, etc.)
8479
- */
8480
- // Date format tokens supported by &(date).TOKEN
8481
- const DATE_TOKENS = {
8482
- ISO: () => new Date().toISOString(),
8483
- YEAR: () => String(new Date().getFullYear()),
8484
- MONTH: () => String(new Date().getMonth() + 1).padStart(2, "0"),
8485
- DAY: () => String(new Date().getDate()).padStart(2, "0"),
8486
- TS: () => String(Date.now()),
8487
- TIME: () => new Date().toTimeString().split(" ")[0], // HH:MM:SS
8488
- };
8489
- // ---------------------------------------------------------------------------
8490
- // Parser
8491
- // ---------------------------------------------------------------------------
8492
- class ConfigSyntaxParser {
8493
- constructor(packageJson = null, envProvider = null, constants = {}, options = {}) {
8494
- this.packageJson = packageJson;
8495
- this.envProvider = envProvider;
8496
- this.constants = constants;
8497
- // LRU-style cache for getDeepValue on the same object reference
8498
- this.deepValueCache = new WeakMap();
8499
- this.fileBasePath = options.fileBasePath ?? process.cwd();
8500
- this.maxPasses = options.maxPasses ?? 20;
8501
- }
8502
- // -------------------------------------------------------------------------
8503
- // Public API — signatures intentionally unchanged
8504
- // -------------------------------------------------------------------------
8505
- /**
8506
- * Resolves all dynamic references in a configuration object or string.
8507
- * Non-string/array/object values are returned as-is.
8508
- */
8509
- resolve(obj, rootObj) {
8510
- if (rootObj === undefined)
8511
- rootObj = obj;
8512
- if (typeof obj === "string")
8513
- return this.resolveString(obj, rootObj);
8514
- if (Array.isArray(obj))
8515
- return obj.map((item) => this.resolve(item, rootObj));
8516
- if (typeof obj === "object" && obj !== null) {
8517
- const resolved = {};
8518
- for (const key of Object.keys(obj)) {
8519
- const resolvedKey = String(this.resolve(key, rootObj));
8520
- resolved[resolvedKey] = this.resolve(obj[key], rootObj);
8521
- }
8522
- return resolved;
8523
- }
8524
- return obj; // number, boolean, null, undefined — pass through untouched
8525
- }
8526
- // -------------------------------------------------------------------------
8527
- // Core resolution
8528
- // -------------------------------------------------------------------------
8529
- /**
8530
- * Resolves dynamic references in a string, supporting chained || fallbacks.
8531
- */
8532
- resolveString(value, rootObj) {
8533
- // Validate before any resolution to catch syntax errors even in unused fallbacks
8534
- this.validateSyntax(value);
8535
- // Matches: &(type).key || &(type).key || literal-fallback
8536
- // Group 1 — type
8537
- // Group 2 — key/path
8538
- // Group 3 — remainder of the || chain
8539
- // Separate simple types (env, const, date) from complex types (pkg, this, file)
8540
- // to prevent over-matching separators like '.' or '-' in strings.
8541
- const chainRegex = /&\((env|const|date)\)\.([\w\d_$]+)((?:\s*\|\|\s*(?:&\((?:[\w]+)\)\.[\w\d_./$]+(?:-[\w\d_./$]+)*|[^|,]+))*)|&\((pkg|this|file)\)\.([\w\d_/$][\w\d_./$]*(?:-[\w\d_./$]+)*)((?:\s*\|\|\s*(?:&\((?:[\w]+)\)\.[\w\d_./$]+(?:-[\w\d_./$]+)*|[^|,]+))*)/g;
8542
- let result = value;
8543
- let passes = 0;
8544
- while (passes++ < this.maxPasses) {
8545
- const prev = result;
8546
- // Reset regex before each pass (global flag keeps lastIndex)
8547
- chainRegex.lastIndex = 0;
8548
- result = result.replace(chainRegex, (_match, type1, key1, chain1, type2, key2, chain2) => {
8549
- const type = type1 || type2;
8550
- const key = key1 || key2;
8551
- const chain = chain1 || chain2;
8552
- const val = this.getValue(type, key, rootObj);
8553
- if (val !== undefined)
8554
- return val;
8555
- if (chain) {
8556
- // Strip leading " || " and let the next pass handle it
8557
- return chain.replace(/^\s*\|\|\s*/, "");
8558
- }
8559
- throw new Error(this.buildMissingError(type, key));
8560
- });
8561
- if (result === prev)
8562
- break;
8563
- }
8564
- if (passes > this.maxPasses) {
8565
- throw new Error(`ESYNC: Resolution did not stabilise after ${this.maxPasses} passes in "${value}". ` +
8566
- `Possible circular reference.`);
8567
- }
8568
- this.validateSyntax(result);
8569
- return result;
8570
- }
8571
- // -------------------------------------------------------------------------
8572
- // Value retrieval
8573
- // -------------------------------------------------------------------------
8574
- /**
8575
- * Dispatches value retrieval to the appropriate provider.
8576
- */
8577
- getValue(type, key, rootObj) {
8578
- switch (type) {
8579
- case "env":
8580
- return this.getEnv(key);
8581
- case "pkg":
8582
- return this.getPkg(key);
8583
- case "this":
8584
- return this.getThis(key, rootObj);
8585
- case "date":
8586
- return this.getDate(key);
8587
- case "file":
8588
- return this.getFile(key);
8589
- default:
8590
- return undefined; // validateSyntax will catch this
8591
- }
8592
- }
8593
- getEnv(key) {
8594
- return this.envProvider?.has(key)
8595
- ? this.envProvider.get(key)
8596
- : undefined;
8597
- }
8598
- getPkg(key) {
8599
- if (!this.packageJson)
8600
- return undefined;
8601
- const val = this.getDeepValue(this.packageJson, key);
8602
- return val !== undefined ? String(val) : undefined;
8603
- }
8604
- getThis(key, rootObj) {
8605
- if (rootObj === null || typeof rootObj !== "object")
8606
- return undefined;
8607
- const val = this.getDeepValue(rootObj, key);
8608
- return val !== undefined ? String(val) : undefined;
8609
- }
8610
- getDate(token) {
8611
- const upper = token.toUpperCase();
8612
- return DATE_TOKENS[upper]?.();
8613
- // Unknown date tokens fall through to the error handler
8614
- }
8615
- getFile(filePath) {
8616
- try {
8617
- const sys = getSysApi();
8618
- // In XyPriss config, a leading / is often intended as project-root relative
8619
- // especially when the separator dot consumes the '.' of './path'
8620
- const cleanPath = filePath.startsWith("/")
8621
- ? filePath.substring(1)
8622
- : filePath;
8623
- const resolved = sys.path.isAbsolute(cleanPath)
8624
- ? cleanPath
8625
- : sys.path.resolve(this.fileBasePath, cleanPath);
8626
- return sys.fs.readSync(resolved).trim();
8627
- }
8628
- catch {
8629
- return undefined; // triggers fallback chain or missing-key error
8630
- }
8631
- }
8632
- // -------------------------------------------------------------------------
8633
- // Deep value with caching
8634
- // -------------------------------------------------------------------------
8635
- /**
8636
- * Retrieves a value from a nested object using dot notation.
8637
- * Results are cached per object reference to avoid repeated traversal.
8638
- */
8639
- getDeepValue(obj, path) {
8640
- // Check cache
8641
- let pathMap = this.deepValueCache.get(obj);
8642
- if (pathMap?.has(path))
8643
- return pathMap.get(path);
8644
- const parts = path.split(".");
8645
- let current = obj;
8646
- for (const part of parts) {
8647
- if (current === null || typeof current !== "object") {
8648
- current = undefined;
8649
- break;
8650
- }
8651
- current = current[part];
8652
- }
8653
- // Store in cache
8654
- if (!pathMap) {
8655
- pathMap = new Map();
8656
- this.deepValueCache.set(obj, pathMap);
8657
- }
8658
- pathMap.set(path, current);
8659
- return current;
8660
- }
8661
- // -------------------------------------------------------------------------
8662
- // Validation
8663
- // -------------------------------------------------------------------------
8664
- /**
8665
- * Validates that no unresolved or malformed markers remain in the string.
8666
- */
8667
- validateSyntax(value) {
8668
- if (!/&\(/.test(value))
8669
- return;
8670
- const malformedRegex = /&\((env|const|date)\)\.([\w\d_$]+)?|&\((pkg|this|file)\)\.([\w\d_/$][\w\d_./$]*(?:-[\w\d_./$]+)*)?/g;
8671
- let match;
8672
- while ((match = malformedRegex.exec(value)) !== null) {
8673
- const [full, type1, key1, type2, key2] = match;
8674
- const type = type1 || type2;
8675
- const key = key1 || key2;
8676
- if (!type) {
8677
- // This shouldn't happen with the current regex, but safety first
8678
- throw new Error(`ESYNC: Invalid or malformed injection syntax detected in "${full}".`);
8679
- }
8680
- if (!key) {
8681
- throw new Error(`ESYNC: Malformed syntax "${full}". Missing key or property path.`);
8682
- }
8683
- }
8684
- // Catch any `&(` that didn't even loosely match the malformedRegex
8685
- const stripped = value.replace(malformedRegex, "");
8686
- if (/&\(/.test(stripped)) {
8687
- throw new Error(`ESYNC: Invalid or malformed injection syntax detected in "${value}".`);
8688
- }
8689
- }
8690
- // -------------------------------------------------------------------------
8691
- // Error formatting
8692
- // -------------------------------------------------------------------------
8693
- buildMissingError(type, key) {
8694
- const descriptions = {
8695
- env: `Environment variable "${key}"`,
8696
- pkg: `Property "${key}" in package.json`,
8697
- this: `Property "${key}" in current object`,
8698
- date: `Date token "${key}" (valid: ${Object.keys(DATE_TOKENS).join(", ")})`,
8699
- file: `File "${key}"`,
8700
- };
8701
- const desc = descriptions[type] ?? `Reference "${key}" (type: ${type})`;
8702
- return `EDYNC: ${desc} not found or could not be resolved.`;
8703
- }
8704
- }
8705
-
8706
- // ---------------------------------------------------------------------------
8707
- // Internal RAM store for project environments — purely module-scoped.
8708
- //
8709
- // CRITICAL SECURITY FIX:
8710
- // Do NOT store this on `globalThis` using a Symbol. `Object.getOwnPropertySymbols(globalThis)`
8711
- // allows any script or untrusted dependency to enumerate all symbols on globalThis
8712
- // and exfiltrate secrets without using __sys__.__env__.
8713
- // By encapsulating the store in module-scoped closures, the data is completely
8714
- // invisible to global reflection APIs.
8715
- // ---------------------------------------------------------------------------
8716
- let _internalProjectEnvs;
8717
- function setInternalProjectEnvs(store) {
8718
- _internalProjectEnvs = store;
8719
- }
8720
- function getInternalProjectEnvs() {
8721
- const stack = new Error().stack || "";
8722
- const lines = stack.split("\n");
8723
- for (let i = 1; i < lines.length; i++) {
8724
- const line = lines[i];
8725
- if (line.includes("env.") || line.includes("getInternalProjectEnvs"))
8726
- continue;
8727
- const match = line.match(/\((.*):\d+:\d+\)$/) ||
8728
- line.match(/at (.*):\d+:\d+$/) ||
8729
- line.match(/at (.*)$/);
8730
- if (match) {
8731
- const callerFile = match[1];
8732
- if (!isCoreFrameworkPath(callerFile)) {
8733
- return undefined;
8734
- }
8735
- break;
8736
- }
8737
- }
8738
- return _internalProjectEnvs;
8739
- }
8740
- const XY_XHSC_REGISTER_FS = Symbol();
8741
- /**
8742
- * **Internal Root-Scoped Env Access Key**
8743
- *
8744
- * Used exclusively by internal engine modules (such as `ProjectDiscovery.loadXyConfig`)
8745
- * to resolve configuration references `&(env:...)` within a target project context.
8746
- *
8747
- * **Security Decision:**
8748
- * Previously, this capability was exposed as a public method `__sys__.__env__.getForRoot(key, root)`.
8749
- * That allowed third-party plugins in `node_modules` to pass the host project's root (`process.cwd()`
8750
- * or `__sys__._primaryRoot`), completely bypassing caller-isolated Zero-Trust sandboxing.
8751
- * Moving this method behind an unexported module `Symbol` prevents external code from invoking it.
8752
- *
8753
- * @internal
8754
- */
8755
- const XY_ENV_INTERNAL_GET_FOR_ROOT = Symbol("__xy_env_internal_get_for_root__");
8756
- /**
8757
- * **Internal Security Shield Configuration Key**
8758
- *
8759
- * Used exclusively during framework startup (`xhsc.ts`) to apply declarative
8760
- * XESS shield rules configured in `xypriss.config.json(c)`.
8761
- *
8762
- * **Security Decision:**
8763
- * Exposing `configureShield` as a public method on `__sys__.__env__` created a critical vulnerability,
8764
- * allowing untrusted plugins to dynamically modify the whitelist and leak forbidden secrets through
8765
- * `process.env`. Restricting it to this unexported Symbol guarantees that only the engine bootstrap
8766
- * can configure the whitelist.
8767
- *
8768
- * @internal
8769
- */
8770
- const XY_ENV_CONFIGURE_SHIELD = Symbol("__xy_env_configure_shield__");
8771
- // ---------------------------------------------------------------------------
8772
- // Internal value sanitisation
8773
- //
8774
- // Detects byte sequences that can corrupt downstream parsers, log sinks, or
8775
- // serialisers when stored as environment variable values.
8776
- // ---------------------------------------------------------------------------
8777
- /** Characters that are unconditionally rejected in environment variable values. */
8778
- const FORBIDDEN_VALUE_PATTERN = /[\r\n\0]/;
8779
- // ---------------------------------------------------------------------------
8780
- // Errors
8781
- // ---------------------------------------------------------------------------
8782
- /**
8783
- * Thrown by {@link EnvApi.getStrict} when a required environment variable is
8784
- * absent or — when `rejectEmpty` is set — when it is present but empty.
8785
- *
8786
- * @example
8787
- * try {
8788
- * const dbUrl = __sys__.__env__.getStrict("DATABASE_URL");
8789
- * } catch (err) {
8790
- * if (err instanceof EnvAccessError) {
8791
- * process.exit(1); // Fail fast on missing critical configuration
8792
- * }
8793
- * }
8794
- */
8795
- class EnvAccessError extends Error {
8796
- constructor(key, reason) {
8797
- super(reason === "empty"
8798
- ? `Environment variable "${key}" is set but contains an empty value. ` +
8799
- `Use __sys__.__env__.get("${key}") if an empty value is acceptable.`
8800
- : `Required environment variable "${key}" is not defined. ` +
8801
- `Ensure it is present in your .env file or execution environment.`);
8802
- this.name = "EnvAccessError";
8803
- this.key = key;
8804
- Object.setPrototypeOf(this, EnvAccessError.prototype);
8805
- }
8806
- }
8807
- /**
8808
- * Thrown by {@link EnvApi.set} when the key or value fails validation.
8809
- *
8810
- * @example
8811
- * try {
8812
- * __sys__.__env__.set("", "value"); // empty key
8813
- * __sys__.__env__.set("FOO", "bar\nbaz"); // newline injection attempt
8814
- * } catch (err) {
8815
- * if (err instanceof EnvKeyError) {
8816
- * logger.error("Invalid env write", { key: err.key, reason: err.message });
8817
- * }
8818
- * }
8819
- */
8820
- class EnvKeyError extends Error {
8821
- constructor(key, reason) {
8822
- super(`Invalid environment variable "${key}": ${reason}`);
8823
- this.name = "EnvKeyError";
8824
- this.key = key;
8825
- Object.setPrototypeOf(this, EnvKeyError.prototype);
8826
- }
8827
- }
8828
- /**
8829
- * Thrown when {@link EnvApi} methods are called before the internal store has
8830
- * been initialised by the XyPriss bootstrap process.
8831
- *
8832
- * This error should never occur in correctly bootstrapped applications.
8833
- * If it does, it indicates that framework initialisation was bypassed.
8834
- */
8835
- class EnvStoreError extends Error {
8836
- constructor() {
8837
- super("The XyPriss environment store has not been initialised. " +
8838
- "Ensure that createServer() has completed before accessing __sys__.__env__.");
8839
- this.name = "EnvStoreError";
8840
- Object.setPrototypeOf(this, EnvStoreError.prototype);
8841
- }
8842
- }
8843
- /**
8844
- * Thrown when an application attempts to boot without the mandatory libXESS confinement shield.
8845
- */
8846
- class XessShieldRequiredError extends Error {
8847
- constructor(message) {
8848
- super(message ||
8849
- "XyPriss Security Violation: libXESS environment confinement is mandatory.\n" +
8850
- "Applications must be launched through the official XFPM CLI (e.g. 'xfpm run', 'xfpm dev', 'xfpm start').\n" +
8851
- "Unconfined direct runtime execution exposes secrets to host disk leaks and is strictly prohibited.");
8852
- this.name = "XessShieldRequiredError";
8853
- Object.setPrototypeOf(this, XessShieldRequiredError.prototype);
8854
- }
8855
- }
8856
-
8857
- let cachedManifest = null;
8858
- /**
8859
- * Loads the authoritative plugins manifest provided by xfpm.
8860
- */
8861
- function getPluginsManifest() {
8862
- if (cachedManifest)
8863
- return cachedManifest;
8864
- const manifestPath = process.env.XYPRISS_PLUGINS_MANIFEST ||
8865
- (process.env.XYPRISS_PROJECT_ROOT
8866
- ? path$1.join(process.env.XYPRISS_PROJECT_ROOT, "node_modules", ".xfpm", "plugins_manifest.json")
8867
- : null);
8868
- if (manifestPath && fs$1.existsSync(manifestPath)) {
8869
- try {
8870
- const raw = fs$1.readFileSync(manifestPath, "utf-8");
8871
- cachedManifest = JSON.parse(raw);
8872
- return cachedManifest;
8873
- }
8874
- catch {
8875
- // ignore
8876
- }
8877
- }
8878
- return null;
8879
- }
8880
- /**
8881
- * Returns the primary project root determined by xfpm CLI.
8882
- */
8883
- function getPrimaryProjectRoot() {
8884
- return process.env.XYPRISS_PROJECT_ROOT || process.cwd();
8885
- }
8886
- /**
8887
- * Checks if a directory is a valid project root.
8888
- */
8889
- function isProjectRoot(dir) {
8890
- if (!dir)
8891
- return false;
8892
- try {
8893
- const resolved = path$1.resolve(dir);
8894
- const primaryRoot = process.env.XYPRISS_PROJECT_ROOT;
8895
- if (primaryRoot && resolved === path$1.resolve(primaryRoot)) {
8896
- return true;
8897
- }
8898
- const manifest = getPluginsManifest();
8899
- if (manifest?.roots && manifest.roots[resolved]) {
8900
- return true;
8901
- }
8902
- const pkgPath = path$1.join(resolved, "package.json");
8903
- return fs$1.existsSync(pkgPath);
8904
- }
8905
- catch {
8906
- return false;
8907
- }
8908
- }
8909
- /**
8910
- * Identifies the project or plugin root for a given caller path using xfpm metadata.
8911
- */
8912
- function identifyProjectRoot(filePath) {
8913
- if (!filePath)
8914
- return undefined;
8915
- if (!path$1.isAbsolute(filePath)) {
8916
- try {
8917
- filePath = path$1.resolve(filePath);
8918
- }
8919
- catch {
8920
- return undefined;
8921
- }
8922
- }
8923
- const normalized = filePath.replace(/\\/g, "/");
8924
- const primaryRoot = (process.env.XYPRISS_PROJECT_ROOT || process.cwd()).replace(/\\/g, "/");
8925
- // 1. Direct O(1) match against verified plugins registered by xfpm
8926
- const manifest = getPluginsManifest();
8927
- if (manifest?.roots) {
8928
- for (const [pluginRoot, _pluginName] of Object.entries(manifest.roots)) {
8929
- const normPluginRoot = pluginRoot.replace(/\\/g, "/");
8930
- if (normalized === normPluginRoot || normalized.startsWith(normPluginRoot + "/")) {
8931
- return pluginRoot;
8932
- }
8933
- }
8934
- }
8935
- // 2. Direct match against primary project root
8936
- if (normalized === primaryRoot || normalized.startsWith(primaryRoot + "/")) {
8937
- // If inside node_modules, it is an undeclared/untrusted dependency, NOT the application root!
8938
- if (normalized.includes("/node_modules/")) {
8939
- return undefined;
8940
- }
8941
- return primaryRoot;
8942
- }
8943
- // 3. Monorepo development mods (/mods/<name>/) fallback
8944
- const modsIdx = normalized.lastIndexOf("/mods/");
8945
- if (modsIdx !== -1) {
8946
- const afterMods = normalized.substring(modsIdx + 6);
8947
- const nextSlash = afterMods.indexOf("/");
8948
- const modName = nextSlash === -1 ? afterMods : afterMods.substring(0, nextSlash);
8949
- if (modName) {
8950
- return normalized.substring(0, modsIdx + 6 + modName.length);
8951
- }
8952
- }
8953
- return undefined;
8954
- }
8955
- /**
8956
- * Retrieves the project root of the code currently executing by analyzing the stack trace.
8957
- */
8958
- function getCallerProjectRoot() {
8959
- const stack = new Error().stack;
8960
- if (!stack)
8961
- return getPrimaryProjectRoot();
8962
- const lines = stack.split("\n");
8963
- let callerFilePath = "";
8964
- // Line 0 is 'Error', Line 1 is getCallerProjectRoot itself
8965
- for (let i = 2; i < lines.length; i++) {
8966
- const line = lines[i];
8967
- if (!line || line.includes(" (node:") || line.includes(" (bun:") || line.includes(" (native"))
8968
- continue;
8969
- const match = line.match(/\((.*\.([jt]s|[cm]js)):\d+:\d+\)$/) ||
8970
- line.match(/at (.*\.([jt]s|[cm]js)):\d+:\d+$/);
8971
- if (!match)
8972
- continue;
8973
- const filePath = match[1];
8974
- if (!filePath || filePath === "native" || filePath === "node:fs" || filePath === "fs")
8975
- continue;
8976
- // Skip internal engine files to locate the user/plugin caller
8977
- if (isEngineCorePath(filePath)) {
8978
- continue;
8979
- }
8980
- if (line.includes("at get [") ||
8981
- line.includes("at getStrict (") ||
8982
- line.includes("PluginAPI.") ||
8983
- line.includes("Plugin."))
8984
- continue;
8985
- callerFilePath = filePath;
8986
- break;
8987
- }
8988
- if (!callerFilePath)
8989
- return getPrimaryProjectRoot();
8990
- const root = identifyProjectRoot(callerFilePath);
8991
- return root;
8992
- }
8993
- /**
8994
- * Loads and cleans a XyPriss configuration file (JSON or JSONC).
8995
- * Removes comments and trailing commas to ensure compatibility with standard JSON.parse.
8996
- */
8997
- function loadXyConfig(projectRoot) {
8998
- for (const name of ["xypriss.config.jsonc", "xypriss.config.json"]) {
8999
- const configPath = path$1.join(projectRoot, name);
9000
- if (fs$1.existsSync(configPath)) {
9001
- try {
9002
- const raw = fs$1.readFileSync(configPath, "utf-8");
9003
- const clean = raw
9004
- .replace(/("(?:[^"\\]|\\.)*")|\/\/.*|\/\*[\s\S]*?\*\//g, (m, g) => (g ? g : ""))
9005
- .replace(/("(?:[^"\\]|\\.)*")|,\s*([}\]])/g, (m, g1, g2) => g1 ? g1 : g2);
9006
- const rawJson = JSON.parse(clean);
9007
- // Load package.json from the same directory for resolution
9008
- let pkgJson = null;
9009
- const pkgPath = path$1.join(projectRoot, "package.json");
9010
- if (fs$1.existsSync(pkgPath)) {
9011
- try {
9012
- pkgJson = JSON.parse(fs$1.readFileSync(pkgPath, "utf-8"));
9013
- }
9014
- catch { /* ignore */ }
9015
- }
9016
- // Resolve references &(pkg), &(env), etc.
9017
- const sys = globalThis.__sys__;
9018
- // Safely resolve &(env:...) variables scoped to the target project root
9019
- // using the internal symbol (safe from third-party / plugin tampering).
9020
- let envProvider = sys?.__env__;
9021
- if (sys?.__env__?.[XY_ENV_INTERNAL_GET_FOR_ROOT]) {
9022
- envProvider = {
9023
- has: (key) => sys.__env__[XY_ENV_INTERNAL_GET_FOR_ROOT](key, projectRoot) !== undefined,
9024
- get: (key) => sys.__env__[XY_ENV_INTERNAL_GET_FOR_ROOT](key, projectRoot)
9025
- };
9026
- }
9027
- const parser = new ConfigSyntaxParser(pkgJson, envProvider);
9028
- return parser.resolve(rawJson);
8477
+ * @example
8478
+ * __sys__.fs.unlock("exclusive.data");
8479
+ */
8480
+ this.unlock = (p) => {
8481
+ this.runner.runSync("fs", "unlock", [p]);
8482
+ };
8483
+ /**
8484
+ * **Secure Permission Write (Asynchronous)**
8485
+ *
8486
+ * Writes data to a file and immediately applies a restricted permission mode.
8487
+ *
8488
+ * @param {string} p - Destination path.
8489
+ * @param {any} data - Data to write.
8490
+ * @param {string} mode - Octal mode (e.g., '600').
8491
+ * @returns {Promise<void>}
8492
+ */
8493
+ this.writeSecure = async (p, data, mode) => {
8494
+ let writeData = "";
8495
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) {
8496
+ writeData = data;
9029
8497
  }
9030
- catch (e) {
9031
- return null;
8498
+ else if (typeof data === "object" && data !== null) {
8499
+ writeData = xyprissSecurity.XStringify(data);
9032
8500
  }
9033
- }
8501
+ else {
8502
+ writeData = String(data);
8503
+ }
8504
+ await this.runner.runAsync("fs", "write-secure", [p], {
8505
+ mode,
8506
+ input: writeData,
8507
+ });
8508
+ };
8509
+ /**
8510
+ * **Secure Permission Write (Synchronous)**
8511
+ *
8512
+ * Synchronously writes data and applies a restricted mode.
8513
+ *
8514
+ * @param {string} p - Destination path.
8515
+ * @param {any} data - Data to write.
8516
+ * @param {string} mode - Octal mode.
8517
+ */
8518
+ this.writeSecureSync = (p, data, mode) => {
8519
+ let writeData = "";
8520
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) {
8521
+ writeData = data;
8522
+ }
8523
+ else if (typeof data === "object" && data !== null) {
8524
+ writeData = xyprissSecurity.XStringify(data);
8525
+ }
8526
+ else {
8527
+ writeData = String(data);
8528
+ }
8529
+ this.runner.runSync("fs", "write-secure", [p], {
8530
+ mode,
8531
+ input: writeData,
8532
+ });
8533
+ };
8534
+ /**
8535
+ * **Transparent File Encryption (AES-256-GCM)**
8536
+ *
8537
+ * Encrypts the contents of a file in-place using a symmetric key.
8538
+ *
8539
+ * @param {string} p - Path to the file.
8540
+ * @param {string} key - Secret encryption key.
8541
+ * @returns {Promise<void>}
8542
+ */
8543
+ this.encryptFile = async (p, key) => {
8544
+ await xyprissSecurity.Cipher.crypto.encryptFile(p, p, key, "AES-256-GCM");
8545
+ };
8546
+ /**
8547
+ * **Transparent File Decryption**
8548
+ *
8549
+ * Decrypts a file previously encrypted with `encryptFile()`.
8550
+ *
8551
+ * @param {string} p - Path to the file.
8552
+ * @param {string} key - Secret decryption key.
8553
+ * @returns {Promise<void>}
8554
+ *
8555
+ * @example
8556
+ * await __sys__.fs.decryptFile("vault.bin", "passphrase");
8557
+ */
8558
+ this.decryptFile = async (p, key) => {
8559
+ await xyprissSecurity.Cipher.crypto.decryptFile(p, p, key);
8560
+ };
8561
+ /**
8562
+ * **Hardware-Bound Encryption**
8563
+ *
8564
+ * Encrypts a file using a key derived from the system's unique hardware ID.
8565
+ * This file can ONLY be decrypted on this specific machine.
8566
+ *
8567
+ * @param {string} p - Path to the file.
8568
+ * @param {string} key - User-provided part of the secret.
8569
+ * @returns {Promise<void>}
8570
+ */
8571
+ this.hardwareEncryptFile = async (p, key) => {
8572
+ await this.runner.runAsync("fs", "hardware-encrypt", [p], { key });
8573
+ };
8574
+ /**
8575
+ * **Hardware-Bound Decryption**
8576
+ *
8577
+ * Decrypts a file using the system's hardware ID.
8578
+ *
8579
+ * @param {string} p - Path to the file.
8580
+ * @param {string} key - User-provided part of the secret.
8581
+ * @returns {Promise<void>}
8582
+ */
8583
+ this.hardwareDecryptFile = async (p, key) => {
8584
+ await this.runner.runAsync("fs", "hardware-decrypt", [p], { key });
8585
+ };
8586
+ /**
8587
+ * **Deep File Diff**
8588
+ *
8589
+ * Performs a line-by-line comparison between two files and returns
8590
+ * all differences.
8591
+ *
8592
+ * @param {string} fileA - First file.
8593
+ * @param {string} fileB - Second file.
8594
+ * @returns {Array<Object>} List of differences with line numbers.
8595
+ */
8596
+ this.diffFiles = (fileA, fileB) => {
8597
+ return this.runner.runSync("fs", "diff-files", [fileA, fileB]);
8598
+ };
8599
+ /**
8600
+ * **Storage Analysis**
8601
+ *
8602
+ * Scans a directory and returns a list of the largest files found.
8603
+ *
8604
+ * @param {string} dir - Directory to scan.
8605
+ * @param {number} [limit=50] - Number of top files to return.
8606
+ * @returns {Array<Object>} List of paths and sizes.
8607
+ */
8608
+ this.topBigFiles = (dir, limit = 50) => {
8609
+ return this.runner.runSync("fs", "top-big-files", [dir], {
8610
+ limit,
8611
+ });
8612
+ };
9034
8613
  }
9035
- return null;
9036
8614
  }
8615
+
8616
+ /* *****************************************************************************
8617
+ * Nehonix XyPriss System
8618
+ *
8619
+ * ACCESS RESTRICTIONS:
8620
+ * - This software is exclusively for use by Authorized Personnel of NEHONIX
8621
+ * - Intended for Internal Use only within NEHONIX operations
8622
+ * - No rights granted to unauthorized individuals or entities
8623
+ * - All modifications are works made for hire assigned to NEHONIX
8624
+ *
8625
+ * PROHIBITED ACTIVITIES:
8626
+ * - Copying, distributing, or sublicensing without written permission
8627
+ * - Reverse engineering, decompiling, or disassembling
8628
+ * - Creating derivative works without explicit authorization
8629
+ * - External use or commercial distribution outside NEHONIX
8630
+ *
8631
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
8632
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
8633
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
8634
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8635
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
8636
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
8637
+ * SOFTWARE.
8638
+ *
8639
+ * For questions or permissions, contact:
8640
+ * NEHONIX Legal Department
8641
+ * Email: legal@nehonix.com
8642
+ * Website: www.nehonix.com
8643
+ * ***************************************************************************** */
9037
8644
  /**
9038
- * Verifies if a given directory contains a valid XyPriss plugin contract.
9039
- * Required: xypriss.config.json(c) with the plugin's namespace under '$internal'
8645
+ * **Professional Filesystem API (High Performance)**
8646
+ *
8647
+ * The `FSApi` class provides a unified, high-performance interface for all filesystem operations.
8648
+ * It is modularized into several specialized layers while maintaining a single cohesive API.
8649
+ *
8650
+ * **Modular Structure:**
8651
+ * - `FSCore`: Fundamental operations (ls, read, write, move, rm)
8652
+ * - `FSHelpers`: Convenience methods (JSON patterns, type checks)
8653
+ * - `FSSearch`: Regex-based discovery and grep
8654
+ * - `FSArchive`: Compression and TAR handling
8655
+ * - `FSWatch`: Real-time monitoring and streaming
8656
+ * - `FSExtended`: Advanced security and atomic operations
8657
+ *
8658
+ * @class FSApi
8659
+ * @extends FSExtended
9040
8660
  */
9041
- function verifyPluginContract(pluginRoot, pluginName) {
9042
- const config = loadXyConfig(pluginRoot);
9043
- if (!config)
9044
- return false;
9045
- const internal = config.$internal || config.internal;
9046
- if (!internal)
9047
- return false;
9048
- const pluginContract = internal[pluginName];
9049
- // The plugin must declare itself in the $internal block WITH 'type': 'plugin'
9050
- return !!(pluginContract && pluginContract.type === "plugin");
8661
+ class FSApi extends FSExtended {
9051
8662
  }
9052
8663
 
9053
8664
  /**
@@ -9223,6 +8834,8 @@ class VarsApi extends BaseApi {
9223
8834
  }
9224
8835
  }
9225
8836
 
8837
+ const _envRunnerStore = new WeakMap();
8838
+ const _sealKeyStore = new WeakMap();
9226
8839
  class EnvApi {
9227
8840
  /**
9228
8841
  * @param runner - The XyPrissRunner used to invoke native Go binaries.
@@ -9289,11 +8902,49 @@ class EnvApi {
9289
8902
  "TMP",
9290
8903
  ]);
9291
8904
  this.whitelistedFields = new Set(this.defaultWhitelist);
9292
- this.runner = runner;
8905
+ _envRunnerStore.set(this, runner);
8906
+ const sealKey = crypto$2.randomBytes(32).toString("hex");
8907
+ _sealKeyStore.set(this, sealKey);
8908
+ try {
8909
+ runner.runSync("env", "seal", [sealKey], { __seal__: sealKey, pid: process.pid });
8910
+ }
8911
+ catch { }
9293
8912
  this.mode = mode;
9294
8913
  this.isDynamic = isDynamic;
9295
8914
  this.applyShield();
9296
8915
  }
8916
+ getSealKey() {
8917
+ let key = _sealKeyStore.get(this);
8918
+ if (!key) {
8919
+ key = crypto$2.randomBytes(32).toString("hex");
8920
+ _sealKeyStore.set(this, key);
8921
+ }
8922
+ return key;
8923
+ }
8924
+ executeEnvCall(action, args = [], options = {}) {
8925
+ const sealKey = this.getSealKey();
8926
+ const runner = _envRunnerStore.get(this);
8927
+ if (!runner) {
8928
+ throw new EnvStoreError();
8929
+ }
8930
+ const optsWithSeal = { ...options, __seal__: sealKey, pid: process.pid };
8931
+ try {
8932
+ return runner.runSync("env", action, args, optsWithSeal);
8933
+ }
8934
+ catch (err) {
8935
+ if (err?.message?.includes("missing environment capability seal") ||
8936
+ err?.message?.includes("UNAUTHORIZED")) {
8937
+ try {
8938
+ runner.runSync("env", "seal", [sealKey], { __seal__: sealKey, pid: process.pid });
8939
+ return runner.runSync("env", action, args, optsWithSeal);
8940
+ }
8941
+ catch {
8942
+ throw err;
8943
+ }
8944
+ }
8945
+ throw err;
8946
+ }
8947
+ }
9297
8948
  // -------------------------------------------------------------------------
9298
8949
  // Write
9299
8950
  // -------------------------------------------------------------------------
@@ -9318,8 +8969,11 @@ class EnvApi {
9318
8969
  set(key, value) {
9319
8970
  this.validateKey(key);
9320
8971
  this.validateValue(key, value);
9321
- const store = this.getStoreForCaller();
9322
- store[key] = value;
8972
+ const root = this.resolveAuthorizedRoot();
8973
+ if (!root) {
8974
+ return;
8975
+ }
8976
+ this.executeEnvCall("set", [key, value], { root });
9323
8977
  // Keep process.env in sync for whitelisted keys and framework keys to maintain system stability.
9324
8978
  // Issue #43: Ensures internal components and child processes have immediate access to
9325
8979
  // framework configuration without triggering proxy descriptor violations under strict runtimes (Bun).
@@ -9350,8 +9004,11 @@ class EnvApi {
9350
9004
  * __sys__.__env__.delete("CI_DEPLOY_TOKEN");
9351
9005
  */
9352
9006
  delete(key) {
9353
- const store = this.getStoreForCaller();
9354
- delete store[key];
9007
+ const root = this.resolveAuthorizedRoot();
9008
+ if (!root) {
9009
+ return;
9010
+ }
9011
+ this.executeEnvCall("delete", [key], { root });
9355
9012
  if (this.whitelistedFields.has(key) ||
9356
9013
  key.startsWith("XY_") ||
9357
9014
  key.startsWith("XYPRISS_") ||
@@ -9368,12 +9025,15 @@ class EnvApi {
9368
9025
  }
9369
9026
  }
9370
9027
  get(key, defaultValue) {
9028
+ const root = this.resolveAuthorizedRoot();
9029
+ if (!root) {
9030
+ return defaultValue;
9031
+ }
9371
9032
  if (key === "__root__") {
9372
- return (this.isDynamic ? getCallerProjectRoot() : null) || this.runner.getRoot();
9033
+ return root;
9373
9034
  }
9374
- const store = this.getStoreForCaller();
9375
- const value = store[key];
9376
- return value !== undefined ? value : defaultValue;
9035
+ const res = this.executeEnvCall("get", [key], { root });
9036
+ return res?.found && res.value !== undefined ? res.value : defaultValue;
9377
9037
  }
9378
9038
  /**
9379
9039
  * Reads a variable from the secure internal store for a specific root.
@@ -9389,11 +9049,15 @@ class EnvApi {
9389
9049
  * @returns The resolved variable value or undefined.
9390
9050
  */
9391
9051
  [XY_ENV_INTERNAL_GET_FOR_ROOT](key, root) {
9052
+ const callerInfo = getVerifiedCallerInfo();
9053
+ if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
9054
+ return undefined;
9055
+ }
9392
9056
  if (key === "__root__") {
9393
9057
  return root;
9394
9058
  }
9395
- const store = this.getStoreForCaller(root);
9396
- return store[key];
9059
+ const res = this.executeEnvCall("get", [key], { root });
9060
+ return res?.found ? res.value : undefined;
9397
9061
  }
9398
9062
  /**
9399
9063
  * Reads a required variable from the secure internal store and throws if
@@ -9423,15 +9087,7 @@ class EnvApi {
9423
9087
  * };
9424
9088
  */
9425
9089
  getStrict(key, options) {
9426
- if (key === "__root__") {
9427
- const rootVal = (this.isDynamic ? getCallerProjectRoot() : null) || this.runner.getRoot();
9428
- if (!rootVal) {
9429
- throw new EnvAccessError(key, "missing");
9430
- }
9431
- return rootVal;
9432
- }
9433
- const store = this.getStoreForCaller();
9434
- const value = store[key];
9090
+ const value = this.get(key);
9435
9091
  if (value === undefined) {
9436
9092
  throw new EnvAccessError(key, "missing");
9437
9093
  }
@@ -9455,8 +9111,12 @@ class EnvApi {
9455
9111
  * const betaEnabled = __sys__.__env__.has("ENABLE_BETA_UI");
9456
9112
  */
9457
9113
  has(key) {
9458
- const store = this.getStoreForCaller();
9459
- return store[key] !== undefined;
9114
+ const root = this.resolveAuthorizedRoot();
9115
+ if (!root) {
9116
+ return false;
9117
+ }
9118
+ const res = this.executeEnvCall("has", [key], { root });
9119
+ return Boolean(res?.found);
9460
9120
  }
9461
9121
  /**
9462
9122
  * Returns a frozen, point-in-time snapshot of stored variables.
@@ -9483,7 +9143,12 @@ class EnvApi {
9483
9143
  * logger.debug("Env snapshot", { count: Object.keys(full).length });
9484
9144
  */
9485
9145
  all(options) {
9486
- const store = this.getStoreForCaller();
9146
+ const root = this.resolveAuthorizedRoot();
9147
+ if (!root) {
9148
+ return Object.freeze({});
9149
+ }
9150
+ const res = this.executeEnvCall("all", [], { root });
9151
+ const store = res?.secrets || {};
9487
9152
  if (options?.keys && options.keys.length > 0) {
9488
9153
  const subset = {};
9489
9154
  for (const key of options.keys) {
@@ -9566,9 +9231,10 @@ class EnvApi {
9566
9231
  */
9567
9232
  configureShield(config) {
9568
9233
  const callerRoot = getCallerProjectRoot();
9569
- const hostRoot = this.runner.getRoot();
9234
+ const runner = _envRunnerStore.get(this);
9235
+ const hostRoot = runner ? runner.getRoot() : "";
9570
9236
  if (callerRoot && callerRoot !== hostRoot && !isCoreFrameworkPath(callerRoot)) {
9571
- logger$2.warn("security", `Blocked unauthorized attempt by third-party plugin at '${callerRoot}' to configure Environment Security Shield.`);
9237
+ logger$1.warn("security", `Blocked unauthorized attempt by third-party plugin at '${callerRoot}' to configure Environment Security Shield.`);
9572
9238
  return;
9573
9239
  }
9574
9240
  this[XY_ENV_CONFIGURE_SHIELD](config);
@@ -9586,6 +9252,10 @@ class EnvApi {
9586
9252
  * @param config - XESS configuration options.
9587
9253
  */
9588
9254
  [XY_ENV_CONFIGURE_SHIELD](config) {
9255
+ const callerInfo = getVerifiedCallerInfo();
9256
+ if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
9257
+ return;
9258
+ }
9589
9259
  if (!config)
9590
9260
  return;
9591
9261
  if (config.whitelist !== undefined) {
@@ -9619,7 +9289,10 @@ class EnvApi {
9619
9289
  */
9620
9290
  user() {
9621
9291
  try {
9622
- const result = this.runner.runSync("sys", "user");
9292
+ const runner = _envRunnerStore.get(this);
9293
+ if (!runner)
9294
+ return "";
9295
+ const result = runner.runSync("sys", "user");
9623
9296
  return result?.username ?? "";
9624
9297
  }
9625
9298
  catch {
@@ -9627,57 +9300,32 @@ class EnvApi {
9627
9300
  }
9628
9301
  }
9629
9302
  // -------------------------------------------------------------------------
9630
- // Private — store access
9303
+ // Private — Zero-Trust Caller Verification (V8 C++ CallSites + libSynapx)
9631
9304
  // -------------------------------------------------------------------------
9632
9305
  /**
9633
- * Returns the internal store, throwing {@link EnvStoreError} if it has not
9634
- * yet been initialised.
9306
+ * Resolves the authorized project root for the current caller using native V8 C++ CallSites.
9635
9307
  *
9636
- * SECURITY: This is the single point of store access. Every read and write
9637
- * method must go through here — never access `globalThis[XY_ENV_STORE_KEY]`
9638
- * directly outside this method.
9639
- *
9640
- * Eliminating the `?? process.env` fallback is intentional. A silent
9641
- * fallback to `process.env` during the bootstrap race window would bypass
9642
- * the Shield and leak values without any warning. A thrown error is
9643
- * immediately visible during development and integration testing.
9308
+ * SECURITY POLICY:
9309
+ * - If the caller originates from an undeclared `node_modules/` dependency or dynamic `eval` / `new Function`,
9310
+ * `callerInfo.isUntrusted` is true and this method returns `null` (NEVER falling back to `this.runner.getRoot()`).
9311
+ * - Zero secrets are stored in JavaScript RAM; all queries go through `this.runner.runSync("env", ...)` (`libSynapx`).
9644
9312
  *
9645
9313
  * @internal
9646
- * @throws {EnvStoreError}
9647
9314
  */
9648
- requireStoreMap() {
9649
- const storeMap = getInternalProjectEnvs();
9650
- if (!storeMap) {
9651
- throw new EnvStoreError();
9315
+ resolveAuthorizedRoot(explicitRoot) {
9316
+ if (explicitRoot) {
9317
+ return explicitRoot;
9652
9318
  }
9653
- return storeMap;
9654
- }
9655
- getStoreForCaller(callerRoot) {
9656
- const storeMap = this.requireStoreMap();
9657
- // 🛡️ Security & Scope Policy (Sandboxing):
9658
- // 1. If an explicit root is provided, use it.
9659
- // 2. Fallback to dynamic project discovery based on the caller's stack (Restricted Context) if enabled.
9660
- // 3. Fallback to this EnvApi instance's pinned runner root (System Baseline/Forced root).
9661
- const root = callerRoot ||
9662
- (this.isDynamic ? getCallerProjectRoot() : null) ||
9663
- this.runner.getRoot() ||
9664
- getCallerProjectRoot();
9665
- if (!root)
9666
- return {};
9667
- let store = storeMap.get(root);
9668
- if (!store) {
9669
- // Dynamic loading for projects/plugins not encountered during bootstrap.
9670
- // Under Zero-Trust, all environment secrets must transit through libXESS IPC.
9671
- const envData = {};
9672
- const ipcSecrets = XessIpcClient.fetchSecretsSync(root);
9673
- for (const key in ipcSecrets) {
9674
- envData[key] = ipcSecrets[key];
9675
- }
9676
- // Cache the loaded env for this project
9677
- storeMap.set(root, envData);
9678
- store = envData;
9319
+ const callerInfo = getVerifiedCallerInfo();
9320
+ if (callerInfo.isUntrusted) {
9321
+ return null;
9322
+ }
9323
+ if (this.isDynamic && callerInfo.root) {
9324
+ return callerInfo.root;
9679
9325
  }
9680
- return store;
9326
+ const runner = _envRunnerStore.get(this);
9327
+ const hostRoot = runner ? runner.getRoot() : null;
9328
+ return hostRoot || callerInfo.root || null;
9681
9329
  }
9682
9330
  // -------------------------------------------------------------------------
9683
9331
  // Private — validation
@@ -9798,16 +9446,7 @@ class EnvApi {
9798
9446
  }
9799
9447
  // Emit one warning per unique blocked key.
9800
9448
  if (!warnedKeys.has(prop)) {
9801
- const storeMap = getInternalProjectEnvs();
9802
- let isSilent = target["XYPRISS_ENV_SHIELD"] === "silent";
9803
- if (storeMap) {
9804
- for (const env of storeMap.values()) {
9805
- if (env["XYPRISS_ENV_SHIELD"] === "silent") {
9806
- isSilent = true;
9807
- break;
9808
- }
9809
- }
9810
- }
9449
+ const isSilent = target["XYPRISS_ENV_SHIELD"] === "silent";
9811
9450
  if (!isSilent) {
9812
9451
  process.stderr.write(`\x1b[33m[SECURITY]\x1b[0m ` +
9813
9452
  `Direct access to process.env["${prop}"] is blocked. ` +
@@ -16455,7 +16094,7 @@ class XyPrissXHSC extends XyPrissFS {
16455
16094
  enumerable: true,
16456
16095
  configurable: false,
16457
16096
  });
16458
- logger$2.debug("security", `Plugin ${pluginId} authorized. Workspace root: ${resolvedRoot} (Context: ${callerRoot})`);
16097
+ logger$1.debug("security", `Plugin ${pluginId} authorized. Workspace root: ${resolvedRoot} (Context: ${callerRoot})`);
16459
16098
  this._pluginMap.set(cacheKey, instance);
16460
16099
  return instance;
16461
16100
  }
@@ -16463,7 +16102,7 @@ class XyPrissXHSC extends XyPrissFS {
16463
16102
  // Void Sandbox — plugin non autorisé dans la config
16464
16103
  const voidPath = path$1.join(generateXUserTmpDir(), "void", "sandbox", pluginId.replace(/[^a-zA-Z0-9-]/g, "_"));
16465
16104
  this.fs.mkdir(voidPath, { parents: true });
16466
- logger$2.warn("security", `Plugin ${pluginId} requested workspace but was not explicitly authorized in config. Assigned implicit Void Sandbox (${voidPath}).`);
16105
+ logger$1.warn("security", `Plugin ${pluginId} requested workspace but was not explicitly authorized in config. Assigned implicit Void Sandbox (${voidPath}).`);
16467
16106
  return undefined;
16468
16107
  }
16469
16108
  }
@@ -16564,41 +16203,24 @@ if (typeof globalThis !== "undefined") {
16564
16203
  tempDir = path$1.dirname(tempDir);
16565
16204
  }
16566
16205
  }
16567
- // Load environment variables for each project hierarchy independently
16568
- const projectEnvs = new Map();
16569
- // Enforce libXESS Bipolar Shield as strictly mandatory
16570
- if (!XessIpcClient.isShielded(foundRoot)) {
16206
+ // Enforce libXESS Bipolar Shield via libSynapx (Go-to-Go Vault verification, zero secrets in JS RAM)
16207
+ const synapx = SynapxClient.getInstance();
16208
+ synapx.ensureDaemon();
16209
+ let envStatus = null;
16210
+ try {
16211
+ envStatus = synapx.callSync("env", "status", [], { root: foundRoot });
16212
+ }
16213
+ catch {
16214
+ envStatus = null;
16215
+ }
16216
+ if (!envStatus?.shielded) {
16571
16217
  const err = new XessShieldRequiredError();
16572
16218
  const l = new QuickLogger("XHSC");
16573
16219
  l.error(`[XyPriss Security Violation] ${err.message}`);
16574
16220
  throw err;
16575
16221
  }
16576
- const ipcSecrets = XessIpcClient.fetchSecretsSync(foundRoot);
16577
- // Process each project found in the hierarchy
16578
- for (const projectPath of projects) {
16579
- const envData = {};
16580
- if (projectPath === foundRoot) {
16581
- for (const key in ipcSecrets) {
16582
- envData[key] = ipcSecrets[key];
16583
- }
16584
- }
16585
- else {
16586
- // For descendant sub-projects: if an .env exists on disk (canary decoy),
16587
- // authentic secrets MUST be fetched from libXESS IPC. No silent fallback.
16588
- const subEnv = path$1.join(projectPath, ".env");
16589
- if (fs$1.existsSync(subEnv)) {
16590
- const projectSecrets = XessIpcClient.fetchSecretsSync(projectPath);
16591
- for (const key in projectSecrets) {
16592
- envData[key] = projectSecrets[key];
16593
- }
16594
- }
16595
- }
16596
- projectEnvs.set(projectPath, envData);
16597
- }
16598
- // Initialize the internal secure store as a Map of project environments in module closure
16599
- setInternalProjectEnvs(projectEnvs);
16600
- const primaryEnv = projectEnvs.get(foundRoot) || {};
16601
- const defaultPort = parseInt(primaryEnv["PORT"] || "3000");
16222
+ const defaultPort = parseInt(envStatus.port || "3000", 10) || 3000;
16223
+ const defaultMode = envStatus.mode || "development";
16602
16224
  // Read xypriss.config.jsonc or xypriss.config.json early to apply XESS configuration declaratively
16603
16225
  let earlyXessConfig = null;
16604
16226
  try {
@@ -16622,7 +16244,7 @@ if (typeof globalThis !== "undefined") {
16622
16244
  __root__: foundRoot,
16623
16245
  __port__: defaultPort,
16624
16246
  __PORT__: defaultPort,
16625
- __mode__: primaryEnv["NODE_ENV"] || "development",
16247
+ __mode__: defaultMode,
16626
16248
  });
16627
16249
  // Apply declarative XESS early configuration if found
16628
16250
  let earlyConfig = null;
@@ -16684,7 +16306,7 @@ class MetaConfigRunner {
16684
16306
  result.catch(this.handleFatalError.bind(this, metaPath));
16685
16307
  }
16686
16308
  }
16687
- logger$2.debug("server", `Executed meta file: ${metaPath}`);
16309
+ logger$1.debug("server", `Executed meta file: ${metaPath}`);
16688
16310
  })
16689
16311
  .catch(this.handleFatalError.bind(this, metaPath));
16690
16312
  }
@@ -16724,7 +16346,7 @@ class MetaConfigRunner {
16724
16346
  }
16725
16347
  }
16726
16348
  handleFatalError(metaPath, error) {
16727
- logger$2.error("server", `FATAL: Failed to execute meta file ${metaPath}: ${error.message || error}`);
16349
+ logger$1.error("server", `FATAL: Failed to execute meta file ${metaPath}: ${error.message || error}`);
16728
16350
  // Terminate process securely via system API
16729
16351
  if (globalThis.__sys__ && typeof globalThis.__sys__.exit === "function") {
16730
16352
  globalThis.__sys__.exit(1);
@@ -16756,19 +16378,19 @@ class ConfigLoader {
16756
16378
  return;
16757
16379
  this.isConfigApplied = true;
16758
16380
  const root = getCallerProjectRoot() || __sys__$1.__root__;
16759
- logger$2.debug("server", `ConfigLoader: Initializing discovery from root: ${root}`);
16381
+ logger$1.debug("server", `ConfigLoader: Initializing discovery from root: ${root}`);
16760
16382
  const configFiles = [];
16761
16383
  // Only look for config at the absolute project root (preferring .jsonc)
16762
16384
  for (const name of ["xypriss.config.jsonc", "xypriss.config.json"]) {
16763
16385
  const potentialConfig = this.sys.path.join(root, name);
16764
16386
  if (this.sys.fs.exist(potentialConfig)) {
16765
- logger$2.debug("server", `ConfigLoader: Found configuration file: ${potentialConfig}`);
16387
+ logger$1.debug("server", `ConfigLoader: Found configuration file: ${potentialConfig}`);
16766
16388
  configFiles.push(potentialConfig);
16767
16389
  break; // Stop after first match in root
16768
16390
  }
16769
16391
  }
16770
16392
  if (configFiles.length === 0) {
16771
- logger$2.debug("server", `ConfigLoader: No configuration file found in ${root}`);
16393
+ logger$1.debug("server", `ConfigLoader: No configuration file found in ${root}`);
16772
16394
  }
16773
16395
  // Process only the root configuration
16774
16396
  for (const configPath of configFiles) {
@@ -16788,10 +16410,10 @@ class ConfigLoader {
16788
16410
  const rawConfig = JsonUtils.parse(rawContent);
16789
16411
  // Load package.json if not already loaded
16790
16412
  this.loadPackageJson(projectRoot);
16791
- logger$2.debug("server", `ConfigLoader: Resolving references for ${this.sys.path.basename(configPath)}`);
16413
+ logger$1.debug("server", `ConfigLoader: Resolving references for ${this.sys.path.basename(configPath)}`);
16792
16414
  if (__sys__$1?.__env__) {
16793
16415
  const envSnapshot = __sys__$1.__env__.all();
16794
- logger$2.debug("server", `ConfigLoader: Env keys available in store for ${projectRoot}: ${Object.keys(envSnapshot).join(", ")}`);
16416
+ logger$1.debug("server", `ConfigLoader: Env keys available in store for ${projectRoot}: ${Object.keys(envSnapshot).join(", ")}`);
16795
16417
  }
16796
16418
  const envProvider = __sys__$1?.__env__
16797
16419
  ? {
@@ -16814,11 +16436,11 @@ class ConfigLoader {
16814
16436
  const config = this.resolveRefs(rawConfig, envProvider);
16815
16437
  if (!config)
16816
16438
  return;
16817
- logger$2.debug("server", `ConfigLoader: Applied configuration from: ${this.sys.path.relative(projectRoot, configPath)}`);
16439
+ logger$1.debug("server", `ConfigLoader: Applied configuration from: ${this.sys.path.relative(projectRoot, configPath)}`);
16818
16440
  // Apply __sys__ config if present
16819
16441
  if (config?.$vars) {
16820
16442
  if (__sys__$1) {
16821
- logger$2.debug("server", `ConfigLoader: Updating system variables with $vars: ${JSON.stringify(config.$vars)}`);
16443
+ logger$1.debug("server", `ConfigLoader: Updating system variables with $vars: ${JSON.stringify(config.$vars)}`);
16822
16444
  __sys__$1.vars.update(config.$vars);
16823
16445
  }
16824
16446
  }
@@ -16845,7 +16467,7 @@ class ConfigLoader {
16845
16467
  }
16846
16468
  }
16847
16469
  if (Object.keys(serverOptionsToApply).length > 0) {
16848
- logger$2.debug("server", `ConfigLoader: Merging discovered server configuration into Configs`);
16470
+ logger$1.debug("server", `ConfigLoader: Merging discovered server configuration into Configs`);
16849
16471
  ConfigurationManager.merge(serverOptionsToApply);
16850
16472
  }
16851
16473
  // Process internal configuration
@@ -16885,7 +16507,7 @@ class ConfigLoader {
16885
16507
  __mode__: __sys__$1.__env__.mode,
16886
16508
  });
16887
16509
  __sys__$1[XY_XHSC_REGISTER_FS](pluginId, specializedFS);
16888
- logger$2.debug("server", `Specialized filesystem mapped: ${pluginId} -> ${resolvedFsPath} (from: ${rawPath})`);
16510
+ logger$1.debug("server", `Specialized filesystem mapped: ${pluginId} -> ${resolvedFsPath} (from: ${rawPath})`);
16889
16511
  }
16890
16512
  }
16891
16513
  // 2. Execute additional meta logic if __meta__ is present
@@ -16913,7 +16535,7 @@ class ConfigLoader {
16913
16535
  }
16914
16536
  if (allPermissions.length > 0) {
16915
16537
  __sys__$1.vars.set("pluginPermissions", allPermissions);
16916
- logger$2.debug("server", `Loaded ${allPermissions.length} plugin permission rules from configuration`);
16538
+ logger$1.debug("server", `Loaded ${allPermissions.length} plugin permission rules from configuration`);
16917
16539
  }
16918
16540
  }
16919
16541
  /**
@@ -16949,7 +16571,7 @@ class ConfigLoader {
16949
16571
  this.packageJson = JSON.parse(this.sys.fs.readSync(pkgPath));
16950
16572
  }
16951
16573
  catch (error) {
16952
- logger$2.warn("server", "Failed to parse package.json for configuration resolution");
16574
+ logger$1.warn("server", "Failed to parse package.json for configuration resolution");
16953
16575
  }
16954
16576
  }
16955
16577
  }
@@ -27741,11 +27363,6 @@ class EngineManager {
27741
27363
  // Zero CLI Flags: 100% encrypted single descriptor argument
27742
27364
  const args = [configPath];
27743
27365
  const internalSig = getInternalSignature();
27744
- let sessionKey = "";
27745
- try {
27746
- sessionKey = XessIpcClient.getActiveSessionKey();
27747
- }
27748
- catch { }
27749
27366
  this.logger.debug("server", `Starting XHSC engine: ${args.join(" ")}`);
27750
27367
  const binaryPath = this.runner.getBinaryPath();
27751
27368
  const child = node_child_process.spawn(binaryPath, args, {
@@ -27753,7 +27370,6 @@ class EngineManager {
27753
27370
  detached: true,
27754
27371
  env: {
27755
27372
  ...process.env,
27756
- ...(sessionKey ? { XYPRISS_XESS_SESSION_KEY: sessionKey } : {}),
27757
27373
  ...(internalSig
27758
27374
  ? { XYPRISS_INTERNAL_TOKEN: internalSig }
27759
27375
  : {}),
@@ -28118,7 +27734,7 @@ class RequestProcessor {
28118
27734
  });
28119
27735
  }
28120
27736
  catch (error) {
28121
- logger$2.warn("other", `High-performance path failed for ${req.method} ${req.path}:`, error.message);
27737
+ logger$1.warn("other", `High-performance path failed for ${req.method} ${req.path}:`, error.message);
28122
27738
  return await this.handleStandardPath(req, res, next, requestId, classification);
28123
27739
  }
28124
27740
  }
@@ -28166,7 +27782,7 @@ class RequestProcessor {
28166
27782
  next();
28167
27783
  }
28168
27784
  catch (error) {
28169
- logger$2.warn("other", `Fast path failed for ${req.method} ${req.path}:`, error.message);
27785
+ logger$1.warn("other", `Fast path failed for ${req.method} ${req.path}:`, error.message);
28170
27786
  return await this.handleStandardPath(req, res, next, requestId, classification);
28171
27787
  }
28172
27788
  }
@@ -28210,7 +27826,7 @@ class RequestProcessor {
28210
27826
  next();
28211
27827
  }
28212
27828
  catch (error) {
28213
- logger$2.error("other", `Standard path failed for ${req.method} ${req.path}:`, error.message);
27829
+ logger$1.error("other", `Standard path failed for ${req.method} ${req.path}:`, error.message);
28214
27830
  next(error);
28215
27831
  }
28216
27832
  }
@@ -28246,10 +27862,10 @@ class RequestProcessor {
28246
27862
  await this.dependencies.cacheManager
28247
27863
  .getCache()
28248
27864
  .set(cacheKey, data, { ttl });
28249
- logger$2.debug("other", `CACHED (${pathType}): ${cacheKey} (TTL: ${ttl}ms)`);
27865
+ logger$1.debug("other", `CACHED (${pathType}): ${cacheKey} (TTL: ${ttl}ms)`);
28250
27866
  }
28251
27867
  catch (error) {
28252
- logger$2.error("other", "Cache set error:", error.message);
27868
+ logger$1.error("other", "Cache set error:", error.message);
28253
27869
  }
28254
27870
  });
28255
27871
  return originalJson(data);
@@ -28269,7 +27885,7 @@ class RouteManager {
28269
27885
  * Add all HTTP methods with caching support to the XyPriss app
28270
27886
  */
28271
27887
  addMethods() {
28272
- logger$2.debug("routes", "Adding HTTP methods with caching support...");
27888
+ logger$1.debug("routes", "Adding HTTP methods with caching support...");
28273
27889
  this.addCacheManagementMethods();
28274
27890
  // logger.debug( "routes","HTTP methods added successfully");
28275
27891
  }
@@ -31878,7 +31494,7 @@ function createSafeJsonMiddleware(options = {}) {
31878
31494
  catch (error) {
31879
31495
  if (opts.logCircularRefs &&
31880
31496
  error.message.includes("circular")) {
31881
- logger$2.debug("server", "🔄 Circular reference detected, using safe serialization:", {
31497
+ logger$1.debug("server", "🔄 Circular reference detected, using safe serialization:", {
31882
31498
  url: req.url,
31883
31499
  method: req.method,
31884
31500
  error: error.message,
@@ -31891,7 +31507,7 @@ function createSafeJsonMiddleware(options = {}) {
31891
31507
  return originalJson(parsedResult);
31892
31508
  }
31893
31509
  catch (safeError) {
31894
- logger$2.debug("server", "❌ Safe JSON serialization failed:", safeError);
31510
+ logger$1.debug("server", "❌ Safe JSON serialization failed:", safeError);
31895
31511
  return originalJson({
31896
31512
  error: "Serialization failed",
31897
31513
  message: "Unable to serialize response object",
@@ -32615,7 +32231,7 @@ class CacheManager {
32615
32231
  await this.cache.connect();
32616
32232
  }
32617
32233
  catch (error) {
32618
- logger$2.error("cache", "Cache initialization failed:", error);
32234
+ logger$1.error("cache", "Cache initialization failed:", error);
32619
32235
  throw error;
32620
32236
  }
32621
32237
  }
@@ -32676,13 +32292,13 @@ class CacheManager {
32676
32292
  });
32677
32293
  }
32678
32294
  catch (error) {
32679
- logger$2.warn("cache", `Failed to warm up ${item.key}:`, error.message);
32295
+ logger$1.warn("cache", `Failed to warm up ${item.key}:`, error.message);
32680
32296
  }
32681
32297
  });
32682
32298
  await Promise.all(warmupPromises);
32683
32299
  }
32684
32300
  catch (error) {
32685
- logger$2.warn("cache", "Cache warmup failed:", error.message);
32301
+ logger$1.warn("cache", "Cache warmup failed:", error.message);
32686
32302
  }
32687
32303
  }
32688
32304
  /**
@@ -32770,7 +32386,7 @@ class WorkerPoolComponent {
32770
32386
  }
32771
32387
  }
32772
32388
  initialize() {
32773
- logger$2.debug("other", "Initializing WorkerPool delegation to XHSC (Go Core)...");
32389
+ logger$1.debug("other", "Initializing WorkerPool delegation to XHSC (Go Core)...");
32774
32390
  this.addWorkerPoolMethods();
32775
32391
  }
32776
32392
  addWorkerPoolMethods() {
@@ -32789,7 +32405,7 @@ class WorkerPoolComponent {
32789
32405
  });
32790
32406
  }
32791
32407
  else {
32792
- logger$2.warn("cluster", "WorkerPool task executed locally (XHSC disabled/Master)");
32408
+ logger$1.warn("cluster", "WorkerPool task executed locally (XHSC disabled/Master)");
32793
32409
  // Local execution fallback if needed, or just log
32794
32410
  }
32795
32411
  };
@@ -32819,7 +32435,7 @@ class WorkerPoolComponent {
32819
32435
  app.executeTask(task);
32820
32436
  };
32821
32437
  app.isWorkerPoolEnabled = () => true;
32822
- logger$2.debug("other", "Worker pool delegated methods added to app");
32438
+ logger$1.debug("other", "Worker pool delegated methods added to app");
32823
32439
  }
32824
32440
  shutdown() {
32825
32441
  // delegated to Go