xypriss 9.14.24 → 9.14.27

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
@@ -145,7 +145,7 @@ const DEFAULT_LOGGER_CONFIG = {
145
145
  },
146
146
  };
147
147
 
148
- function getSysApi() {
148
+ function getSysApi$1() {
149
149
  if (typeof globalThis !== "undefined" && globalThis.__sys__) {
150
150
  return globalThis.__sys__;
151
151
  }
@@ -983,7 +983,7 @@ function initializeLogger(config) {
983
983
  * in the `.env` file — useful for staging environments that mimic dev but
984
984
  * must not relax CSP/HSTS/COEP.
985
985
  */
986
- const sys = getSysApi();
986
+ const sys = getSysApi$1();
987
987
  const isDev = sys?.__env__
988
988
  ? sys.__env__.isDevelopment() &&
989
989
  sys.__env__.get("XSEC_TRUST", "true") === "true"
@@ -1096,8 +1096,8 @@ const xemsKeyPlaceholder = "CHANGE_ME_TO_A_SECURE_32_CHAR_KEY";
1096
1096
  * This configuration is used when no custom configuration is provided.
1097
1097
  *
1098
1098
  */
1099
- const DEFAULT_HOST = getSysApi()?.__env__?.get("XYPRISS_HOST") || "localhost";
1100
- const DEFAULT_PORT = (getSysApi()?.__env__?.get("XYPRISS_PORT") ||
1099
+ const DEFAULT_HOST = getSysApi$1()?.__env__?.get("XYPRISS_HOST") || "localhost";
1100
+ const DEFAULT_PORT = (getSysApi$1()?.__env__?.get("XYPRISS_PORT") ||
1101
1101
  8085);
1102
1102
  // Default configuration
1103
1103
  const DEFAULT_OPTIONS = {
@@ -1314,7 +1314,7 @@ const DEFAULT_OPTIONS = {
1314
1314
  * once `__sys__` is initialized, deliberately avoiding reliance on Node.js core modules (`node:os`).
1315
1315
  */
1316
1316
  get tempFileDir() {
1317
- return getSysApi()?.path.tmpUserDir + "/.uploads/";
1317
+ return getSysApi$1()?.path.tmpUserDir + "/.uploads/";
1318
1318
  },
1319
1319
  createParentPath: true,
1320
1320
  preservePath: false,
@@ -1872,7 +1872,7 @@ class FileUploadManager {
1872
1872
  return;
1873
1873
  if (this.config?.storage === "memory" && file.path) {
1874
1874
  try {
1875
- const sys = getSysApi();
1875
+ const sys = getSysApi$1();
1876
1876
  if (sys.fs.exist(file.path)) {
1877
1877
  file.buffer = await sys.fs.readBytes(file.path);
1878
1878
  sys.fs.rm(file.path, { force: true });
@@ -1904,7 +1904,7 @@ class FileUploadManager {
1904
1904
  }
1905
1905
  if (file.path) {
1906
1906
  try {
1907
- const sys = getSysApi();
1907
+ const sys = getSysApi$1();
1908
1908
  if (sys.fs.exist(file.path)) {
1909
1909
  _cachedBuffer = sys.fs.readBytesSync(file.path);
1910
1910
  return _cachedBuffer;
@@ -1924,7 +1924,7 @@ class FileUploadManager {
1924
1924
  if (!file.toBuffer) {
1925
1925
  file.toBuffer = async function () {
1926
1926
  if (file.path) {
1927
- const sys = getSysApi();
1927
+ const sys = getSysApi$1();
1928
1928
  if (sys.fs.exist(file.path)) {
1929
1929
  return await sys.fs.readBytes(file.path);
1930
1930
  }
@@ -1935,7 +1935,7 @@ class FileUploadManager {
1935
1935
  }
1936
1936
  if (!file.getStream) {
1937
1937
  file.getStream = function () {
1938
- const sys = getSysApi();
1938
+ const sys = getSysApi$1();
1939
1939
  if (file.path && sys.fs.exist(file.path)) {
1940
1940
  return sys.fs.createReadStream(file.path);
1941
1941
  }
@@ -1999,7 +1999,7 @@ class FileUploadManager {
1999
1999
  }
2000
2000
  }
2001
2001
  if (this.config?.allowedExtensions) {
2002
- const sys = getSysApi();
2002
+ const sys = getSysApi$1();
2003
2003
  const ext = sys.path.extname(file.originalname).toLowerCase();
2004
2004
  this.logger.debug("server", `Checking extensions: ${this.config.allowedExtensions.join(", ")}, file ext: ${ext}`);
2005
2005
  if (!this.config.allowedExtensions.includes(ext)) {
@@ -3524,14 +3524,21 @@ function clearInternalSignature() {
3524
3524
  catch { }
3525
3525
  }
3526
3526
  /**
3527
- * Irreversibly locks the internal session authentication post-boot:
3528
- * - Shreds and unlinks the ephemeral .auth_token from disk
3529
- * - Clears in-memory ephemeral token references
3530
- * - Deletes environment variables
3531
- * After this call, no subsequent or rogue process can ever boot XHSC.
3527
+ * Locks internal session authentication post-boot:
3528
+ * - In development / watch mode (e.g. FileOnix hot-reload), preserves the session token on disk
3529
+ * so that reloaded workers can authenticate seamlessly without crashing.
3530
+ * - In production mode, irreversibly shreds and unlinks the ephemeral .auth_token from disk
3531
+ * and purges all references from memory and environment.
3532
3532
  */
3533
3533
  function lockSessionAuth() {
3534
3534
  _ephemeralToken = null;
3535
+ const isDev = process.env.NODE_ENV !== "production" ||
3536
+ process.env.FILEONIX === "1" ||
3537
+ process.env.FILEONIX_WATCH === "1" ||
3538
+ (globalThis.__sys__?.__env__?.isDevelopment?.() ?? false);
3539
+ if (isDev) {
3540
+ return;
3541
+ }
3535
3542
  try {
3536
3543
  const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP;
3537
3544
  if (sessionDir) {
@@ -4174,7 +4181,7 @@ class ConfigSyntaxParser {
4174
4181
  }
4175
4182
  getFile(filePath) {
4176
4183
  try {
4177
- const sys = getSysApi();
4184
+ const sys = getSysApi$1();
4178
4185
  // In XyPriss config, a leading / is often intended as project-root relative
4179
4186
  // especially when the separator dot consumes the '.' of './path'
4180
4187
  const cleanPath = filePath.startsWith("/")
@@ -4501,13 +4508,15 @@ function identifyProjectRoot(filePath) {
4501
4508
  if (manifest?.roots) {
4502
4509
  for (const [pluginRoot, _pluginName] of Object.entries(manifest.roots)) {
4503
4510
  const normPluginRoot = pluginRoot.replace(/\\/g, "/");
4504
- if (normalized === normPluginRoot || normalized.startsWith(normPluginRoot + "/")) {
4511
+ if (normalized === normPluginRoot ||
4512
+ normalized.startsWith(normPluginRoot + "/")) {
4505
4513
  return pluginRoot;
4506
4514
  }
4507
4515
  }
4508
4516
  }
4509
4517
  // 2. Direct match against primary project root
4510
- if (normalized === primaryRoot || normalized.startsWith(primaryRoot + "/")) {
4518
+ if (normalized === primaryRoot ||
4519
+ normalized.startsWith(primaryRoot + "/")) {
4511
4520
  // If inside node_modules, it is an undeclared/untrusted dependency, NOT the application root!
4512
4521
  if (normalized.includes("/node_modules/")) {
4513
4522
  return undefined;
@@ -4582,7 +4591,9 @@ function captureNativeFrames() {
4582
4591
  const fnName = typeof site.getFunctionName === "function"
4583
4592
  ? site.getFunctionName() || ""
4584
4593
  : "";
4585
- const isEval = typeof site.isEval === "function" ? Boolean(site.isEval()) : false;
4594
+ const isEval = typeof site.isEval === "function"
4595
+ ? Boolean(site.isEval())
4596
+ : false;
4586
4597
  frames.push({
4587
4598
  filePath: normalizeScriptName(rawFile),
4588
4599
  fnName,
@@ -4605,7 +4616,8 @@ function captureNativeFrames() {
4605
4616
  frames.push({
4606
4617
  filePath: normalizeScriptName(rawScript),
4607
4618
  fnName,
4608
- isEval: !rawScript && (fnName === "eval" || fnName === "anonymous"),
4619
+ isEval: !rawScript &&
4620
+ (fnName === "eval" || fnName === "anonymous"),
4609
4621
  });
4610
4622
  }
4611
4623
  }
@@ -4649,7 +4661,15 @@ function isImmediateInternalEngineCall() {
4649
4661
  fnName === "call" ||
4650
4662
  fnName === "callSync" ||
4651
4663
  fnName === "callSyncSubprocess" ||
4652
- fnName === "executeEnvCall") {
4664
+ fnName === "executeEnvCall" ||
4665
+ // Issue #52 (https://github.com/Nehonix-Team/XyPriss/issues/52)
4666
+ // When code accesses `process.env[prop]`, the proxy trap handler executes inside `EnvApi.ts`.
4667
+ // If EnvApi frames are not skipped, `isImmediateInternalEngineCall()` would treat the Proxy
4668
+ // handler itself as the "caller", erroneously considering every process.env access as an
4669
+ // internal engine call and bypassing the shield. Skipping EnvApi frames ensures we inspect
4670
+ // the real consumer (project code, plugins, or third-party dependencies).
4671
+ norm.endsWith("/EnvApi.ts") ||
4672
+ norm.endsWith("/EnvApi.js")) {
4653
4673
  continue;
4654
4674
  }
4655
4675
  }
@@ -4752,7 +4772,9 @@ function loadXyConfig(projectRoot) {
4752
4772
  try {
4753
4773
  pkgJson = JSON.parse(fs$1.readFileSync(pkgPath, "utf-8"));
4754
4774
  }
4755
- catch { /* ignore */ }
4775
+ catch {
4776
+ /* ignore */
4777
+ }
4756
4778
  }
4757
4779
  // Resolve references &(pkg), &(env), etc.
4758
4780
  const sys = globalThis.__sys__;
@@ -4762,7 +4784,7 @@ function loadXyConfig(projectRoot) {
4762
4784
  if (sys?.__env__?.[XY_ENV_INTERNAL_GET_FOR_ROOT]) {
4763
4785
  envProvider = {
4764
4786
  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)
4787
+ get: (key) => sys.__env__[XY_ENV_INTERNAL_GET_FOR_ROOT](key, projectRoot),
4766
4788
  };
4767
4789
  }
4768
4790
  const parser = new ConfigSyntaxParser(pkgJson, envProvider);
@@ -5001,6 +5023,8 @@ class SynapxClient {
5001
5023
  stdio: "inherit",
5002
5024
  env: {
5003
5025
  ...process.env,
5026
+ XYPRISS_USER_TMP: sessionDir,
5027
+ XESS_SESSION_TMP: sessionDir,
5004
5028
  ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5005
5029
  NO_COLOR: "1",
5006
5030
  },
@@ -5220,7 +5244,7 @@ class SynapxClient {
5220
5244
  * Executes a multiplexed RPC call over the persistent private channel with full args and options descriptors.
5221
5245
  */
5222
5246
  async call(module, action, args = [], opts = {}, timeoutMs = 60000) {
5223
- if (module === "env") {
5247
+ if (module === "env" || module === "xems" || module === "sys") {
5224
5248
  const callerInfo = getVerifiedCallerInfo();
5225
5249
  if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5226
5250
  throw new Error(`libSynapx: Unauthorized caller for restricted module '${module}'`);
@@ -5264,7 +5288,7 @@ class SynapxClient {
5264
5288
  * with transparent automatic fallback to stdin pipe subprocess on edge platforms.
5265
5289
  */
5266
5290
  callSync(module, action, args = [], opts = {}) {
5267
- if (module === "env") {
5291
+ if (module === "env" || module === "xems" || module === "sys") {
5268
5292
  const callerInfo = getVerifiedCallerInfo();
5269
5293
  if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5270
5294
  throw new Error(`libSynapx: Unauthorized caller for restricted module '${module}'`);
@@ -5291,7 +5315,7 @@ class SynapxClient {
5291
5315
  * Subprocess-based synchronous fallback pipeline (streaming via stdin to prevent E2BIG).
5292
5316
  */
5293
5317
  callSyncSubprocess(module, action, args = [], opts = {}) {
5294
- if (module === "env") {
5318
+ if (module === "env" || module === "xems" || module === "sys") {
5295
5319
  const callerInfo = getVerifiedCallerInfo();
5296
5320
  if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5297
5321
  throw new Error(`libSynapx: Unauthorized caller for restricted module '${module}'`);
@@ -5545,10 +5569,12 @@ class XyPrissRunner {
5545
5569
  cmdArgs.push(`--${flag}`, String(value));
5546
5570
  }
5547
5571
  }
5572
+ const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP || "";
5548
5573
  const child = node_child_process.spawn(this.binaryPath, cmdArgs, {
5549
5574
  cwd: this.root,
5550
5575
  env: {
5551
5576
  ...process.env,
5577
+ ...(sessionDir ? { XYPRISS_USER_TMP: sessionDir, XESS_SESSION_TMP: sessionDir } : {}),
5552
5578
  ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5553
5579
  },
5554
5580
  });
@@ -5582,10 +5608,12 @@ class XyPrissRunner {
5582
5608
  cmdArgs.push(`--${flag}`, String(value));
5583
5609
  }
5584
5610
  }
5611
+ const sessionDir = process.env.XYPRISS_USER_TMP || process.env.XESS_SESSION_TMP || "";
5585
5612
  const child = node_child_process.spawn(this.binaryPath, cmdArgs, {
5586
5613
  cwd: this.root,
5587
5614
  env: {
5588
5615
  ...process.env,
5616
+ ...(sessionDir ? { XYPRISS_USER_TMP: sessionDir, XESS_SESSION_TMP: sessionDir } : {}),
5589
5617
  ...(internalSig ? { XYPRISS_INTERNAL_TOKEN: internalSig } : {}),
5590
5618
  },
5591
5619
  });
@@ -5603,7 +5631,7 @@ class XyPrissRunner {
5603
5631
  * @returns {string} Path to `<os.tmpdir>/nehonix.xypriss.data`
5604
5632
  */
5605
5633
  function getXyprissTempDir() {
5606
- const sys = getSysApi();
5634
+ const sys = getSysApi$1();
5607
5635
  return sys.path.join(sys.path.tempDir(), "nehonix.xypriss.data");
5608
5636
  }
5609
5637
  /**
@@ -5613,7 +5641,7 @@ function getXyprissTempDir() {
5613
5641
  * @returns {string} The absolute resolved temp sub-path.
5614
5642
  */
5615
5643
  function createXyprissTempDir(_p) {
5616
- const sys = getSysApi();
5644
+ const sys = getSysApi$1();
5617
5645
  const base = getXyprissTempDir();
5618
5646
  const segment = typeof _p === "string"
5619
5647
  ? _p
@@ -5653,7 +5681,7 @@ function generateXUserTmpDir() {
5653
5681
  if (_sessionTmpDir !== null) {
5654
5682
  return _sessionTmpDir;
5655
5683
  }
5656
- const sys = getSysApi();
5684
+ const sys = getSysApi$1();
5657
5685
  // 1. Adopt the session directory allocated exclusively by the libProc supervisor
5658
5686
  const envSession = sys?.__env__?.get("XYPRISS_USER_TMP") ||
5659
5687
  sys?.__env__?.get("XESS_SESSION_TMP") ||
@@ -5675,7 +5703,7 @@ function generateXUserTmpDir() {
5675
5703
  * Delegated exclusively to the libProc supervisor (Single Source of Truth).
5676
5704
  */
5677
5705
  function getSessionHash() {
5678
- const sys = getSysApi();
5706
+ const sys = getSysApi$1();
5679
5707
  const envHash = sys?.__env__?.get("XYPRISS_SESSION_HASH") ||
5680
5708
  (typeof process !== "undefined" ? process.env?.XYPRISS_SESSION_HASH : undefined);
5681
5709
  if (envHash && typeof envHash === "string") {
@@ -6576,7 +6604,7 @@ class QuickLogger {
6576
6604
  return new QuickLogger(context);
6577
6605
  }
6578
6606
  static shouldLog(level) {
6579
- const sys = getSysApi();
6607
+ const sys = getSysApi$1();
6580
6608
  let isDebug = false;
6581
6609
  if (sys?.__env__) {
6582
6610
  isDebug =
@@ -6732,7 +6760,7 @@ class TempFileManager {
6732
6760
  * Track a temporary file for automatic TTL expiration and process exit cleanup.
6733
6761
  */
6734
6762
  track(filePath, options = {}) {
6735
- const sys = getSysApi();
6763
+ const sys = getSysApi$1();
6736
6764
  const ttlMs = TempFileManager.parseTTL(options.ttl);
6737
6765
  const autoCleanup = options.autoCleanupOnExit !== false;
6738
6766
  const now = Date.now();
@@ -6774,7 +6802,7 @@ class TempFileManager {
6774
6802
  * Remove a single tracked temporary file safely using native XyPriss FS API.
6775
6803
  */
6776
6804
  removeFile(filePath) {
6777
- const sys = getSysApi();
6805
+ const sys = getSysApi$1();
6778
6806
  const entry = this.trackedFiles.get(filePath);
6779
6807
  if (entry?.timer) {
6780
6808
  clearTimeout(entry.timer);
@@ -6796,7 +6824,7 @@ class TempFileManager {
6796
6824
  * Clean up all active tracked temporary files.
6797
6825
  */
6798
6826
  cleanupAll() {
6799
- const sys = getSysApi();
6827
+ const sys = getSysApi$1();
6800
6828
  let count = 0;
6801
6829
  for (const [filePath, entry] of this.trackedFiles.entries()) {
6802
6830
  if (entry.timer)
@@ -6820,7 +6848,7 @@ class TempFileManager {
6820
6848
  return;
6821
6849
  this.exitHooksRegistered = true;
6822
6850
  const performExitCleanup = () => {
6823
- const sys = getSysApi();
6851
+ const sys = getSysApi$1();
6824
6852
  for (const [filePath, entry] of this.trackedFiles.entries()) {
6825
6853
  if (entry.autoCleanupOnExit) {
6826
6854
  try {
@@ -8836,6 +8864,8 @@ class VarsApi extends BaseApi {
8836
8864
 
8837
8865
  const _envRunnerStore = new WeakMap();
8838
8866
  const _sealKeyStore = new WeakMap();
8867
+ const _shieldedInstances = new WeakSet();
8868
+ const SHIELD_MARKER = Symbol("xypriss.internal.env.shielded");
8839
8869
  class EnvApi {
8840
8870
  /**
8841
8871
  * @param runner - The XyPrissRunner used to invoke native Go binaries.
@@ -8870,25 +8900,13 @@ class EnvApi {
8870
8900
  "NODE_DEBUG",
8871
8901
  "NODE_OPTIONS",
8872
8902
  "NODE_ENV",
8873
- "ENC_SECRET_KEY",
8874
- "ENC_SECRET_SEED",
8875
- "ENC_SECRET_SALT",
8876
8903
  "TRACE_DEPRECATION",
8877
8904
  "APPEND_DEPRECATION",
8878
8905
  "READABLE_STREAM",
8879
8906
  "BUN_CONFIG_VERBOSE_FETCH",
8880
8907
  "XYPRISS_ENV_SHIELD",
8881
- "XYPRISS_SESSION_HASH",
8882
- "XYPRISS_USER_TMP",
8883
- "XYPRISS_XESS_AUTH_TOKEN",
8884
- "LIBXESS_ACTIVE",
8885
- "XESS_SESSION_TMP",
8886
- "XESS_TEMP_DIR",
8887
- "LIBPORT_SOCKET_PATH",
8888
- "PORT_SOCKET_PATH",
8889
- "XPM_SOCKET_PATH",
8890
8908
  "BUN_DISABLE_DYNAMIC_CHUNK_SIZE",
8891
- // Node / Bun core HTTPS variables (Issue #43: prevent false-positive security blocking during outgoing TLS/HTTPS requests)
8909
+ // Node / Bun core HTTPS variables (read allowed for network clients, writes strictly guarded in set trap)
8892
8910
  "NODE_TLS_REJECT_UNAUTHORIZED",
8893
8911
  "NODE_EXTRA_CA_CERTS",
8894
8912
  // Standard OS environment paths (Windows / Cross-platform stability)
@@ -9417,15 +9435,27 @@ class EnvApi {
9417
9435
  * @internal
9418
9436
  */
9419
9437
  applyShield() {
9420
- // Issue #43: Guard against multi-server sequential startup re-wrapping process.env in nested proxies.
9421
- const SHIELD_MARKER = Symbol.for("xypriss.env.shielded");
9422
- if (process.env[SHIELD_MARKER]) {
9438
+ // Issue #43 / XSA-008: Guard against multi-server sequential startup re-wrapping process.env.
9439
+ // Uses unforgeable private Symbol and WeakSet to defeat pre-bootstrap spoofing attacks.
9440
+ if (_shieldedInstances.has(process.env) || process.env[SHIELD_MARKER] === true) {
9423
9441
  return;
9424
9442
  }
9425
9443
  // Per-key deduplication: every distinct blocked key gets exactly one
9426
9444
  // warning, preserving actionable signal without log flooding.
9427
9445
  const warnedKeys = new Set();
9428
9446
  const self = this;
9447
+ // Critical environment keys that must NEVER be mutated or poisoned by application or third-party code
9448
+ const CRITICAL_IMMUTABLE_ENV = new Set([
9449
+ "NODE_OPTIONS",
9450
+ "NODE_TLS_REJECT_UNAUTHORIZED",
9451
+ "NODE_EXTRA_CA_CERTS",
9452
+ "PATH",
9453
+ "LD_PRELOAD",
9454
+ "LD_LIBRARY_PATH",
9455
+ "DYLD_INSERT_LIBRARIES",
9456
+ "DYLD_LIBRARY_PATH",
9457
+ ]);
9458
+ let isInsideShieldCheck = false;
9429
9459
  const envShield = new Proxy(process.env, {
9430
9460
  get(target, prop, receiver) {
9431
9461
  if (prop === SHIELD_MARKER) {
@@ -9434,17 +9464,26 @@ class EnvApi {
9434
9464
  if (typeof prop !== "string") {
9435
9465
  return Reflect.get(target, prop, receiver);
9436
9466
  }
9437
- // Pass through whitelisted keys and framework-reserved prefixes.
9438
- if (self.whitelistedFields.has(prop) ||
9439
- prop.startsWith("XY_") ||
9440
- prop.startsWith("XYPRISS_") ||
9441
- prop.startsWith("LIBXESS_") ||
9442
- prop.startsWith("ENC_") ||
9443
- prop.startsWith("DOTENV_") ||
9444
- prop.startsWith("__")) {
9467
+ if (isInsideShieldCheck || prop === "XYPRISS_PROJECT_ROOT" || prop === "XYPRISS_ENV_SHIELD") {
9468
+ return Reflect.get(target, prop, receiver);
9469
+ }
9470
+ // Pass through whitelisted keys.
9471
+ if (self.whitelistedFields.has(prop)) {
9445
9472
  return Reflect.get(target, prop, receiver);
9446
9473
  }
9447
- // Emit one warning per unique blocked key.
9474
+ // Internal framework operations: allow verified engine callers to read environment safely
9475
+ isInsideShieldCheck = true;
9476
+ try {
9477
+ const caller = getVerifiedCallerInfo();
9478
+ if (!caller.isUntrusted && isImmediateInternalEngineCall()) {
9479
+ return Reflect.get(target, prop, receiver);
9480
+ }
9481
+ }
9482
+ finally {
9483
+ isInsideShieldCheck = false;
9484
+ }
9485
+ // All other keys (including ENC_*, DOTENV_*, __*, and application secrets):
9486
+ // direct process.env reads by untrusted/external callers are strictly intercepted and blocked!
9448
9487
  if (!warnedKeys.has(prop)) {
9449
9488
  const isSilent = target["XYPRISS_ENV_SHIELD"] === "silent";
9450
9489
  if (!isSilent) {
@@ -9458,35 +9497,51 @@ class EnvApi {
9458
9497
  return undefined;
9459
9498
  },
9460
9499
  /**
9461
- * Issue #43: Strict `set` trap on `process.env`.
9462
- *
9463
- * Under the Bun runtime, missing a `set` trap causes assignment on `process.env` to invoke
9464
- * `Reflect.defineProperty` with strict descriptor expectations, failing with:
9465
- * `'process.env' only accepts a configurable, writable, and enumerable data descriptor`.
9466
- *
9467
- * This trap permits safe mutation of whitelisted and framework-reserved keys (e.g. `XYPRISS_*`),
9468
- * while gracefully intercepting and auditing non-compliant mutations without crashing the host process.
9500
+ * Strict `set` trap on `process.env`.
9501
+ * Blocks tampering with critical system environment variables (CWE-471).
9502
+ * Restricts internal prefixes to verified engine callers.
9469
9503
  */
9470
9504
  set(target, prop, value, receiver) {
9471
9505
  if (typeof prop !== "string") {
9472
9506
  return Reflect.set(target, prop, value, receiver);
9473
9507
  }
9474
9508
  const key = prop;
9475
- // Allow whitelisted keys and framework-reserved prefixes
9476
- if (self.whitelistedFields.has(key) ||
9477
- key.startsWith("XY_") ||
9478
- key.startsWith("XYPRISS_") ||
9509
+ // Faille 4 (XSA_2026_XESS_007): Prevent poisoning of critical runtime & system variables
9510
+ if (CRITICAL_IMMUTABLE_ENV.has(key)) {
9511
+ if (!warnedKeys.has(key)) {
9512
+ process.stderr.write(`\x1b[31m[SECURITY]\x1b[0m ` +
9513
+ `Direct modification to critical system environment variable process.env["${key}"] is permanently blocked.\n`);
9514
+ warnedKeys.add(key);
9515
+ }
9516
+ return true; // Return true to avoid throwing in strict runtime modes while dropping the poisoned write
9517
+ }
9518
+ // Internal framework prefixes: only mutable by verified internal callers
9519
+ if (key.startsWith("XYPRISS_") ||
9479
9520
  key.startsWith("LIBXESS_") ||
9480
9521
  key.startsWith("XEMS_") ||
9481
- key.startsWith("ENC_") ||
9482
- key.startsWith("DOTENV_") ||
9483
- key.startsWith("__")) {
9522
+ key.startsWith("XESS_")) {
9523
+ isInsideShieldCheck = true;
9484
9524
  try {
9485
- target[key] = String(value);
9525
+ const caller = getVerifiedCallerInfo();
9526
+ if (!caller.isUntrusted &&
9527
+ isImmediateInternalEngineCall()) {
9528
+ try {
9529
+ target[key] = String(value);
9530
+ }
9531
+ catch { }
9532
+ return true;
9533
+ }
9486
9534
  }
9487
- catch {
9488
- // In case target descriptor cannot be mutated directly
9535
+ finally {
9536
+ isInsideShieldCheck = false;
9489
9537
  }
9538
+ }
9539
+ // Allowed whitelisted non-critical keys
9540
+ if (self.whitelistedFields.has(key)) {
9541
+ try {
9542
+ target[key] = String(value);
9543
+ }
9544
+ catch { }
9490
9545
  return true;
9491
9546
  }
9492
9547
  // Prevent fatal crashes in strict runtimes (like Bun) while auditing unauthorized modifications
@@ -9499,9 +9554,13 @@ class EnvApi {
9499
9554
  return true;
9500
9555
  },
9501
9556
  /**
9502
- * Issue #43: Explicit `defineProperty` trap to prevent uncaught descriptor exceptions under Bun.
9557
+ * Explicit `defineProperty` trap to prevent uncaught descriptor exceptions under Bun,
9558
+ * strictly forbidding definition of critical immutable environment keys.
9503
9559
  */
9504
9560
  defineProperty(target, prop, descriptor) {
9561
+ if (typeof prop === "string" && CRITICAL_IMMUTABLE_ENV.has(prop)) {
9562
+ return false;
9563
+ }
9505
9564
  try {
9506
9565
  return Reflect.defineProperty(target, prop, descriptor);
9507
9566
  }
@@ -9510,42 +9569,95 @@ class EnvApi {
9510
9569
  }
9511
9570
  },
9512
9571
  /**
9513
- * Issue #43: Explicit `deleteProperty` trap to allow removing allowed framework keys safely.
9572
+ * Explicit `deleteProperty` trap to allow removing allowed keys safely,
9573
+ * protecting critical environment variables and internal framework state.
9514
9574
  */
9515
9575
  deleteProperty(target, prop) {
9516
9576
  if (typeof prop === "string") {
9517
- if (self.whitelistedFields.has(prop) ||
9518
- prop.startsWith("XY_") ||
9519
- prop.startsWith("XYPRISS_") ||
9577
+ if (CRITICAL_IMMUTABLE_ENV.has(prop)) {
9578
+ return false;
9579
+ }
9580
+ if (prop.startsWith("XYPRISS_") ||
9520
9581
  prop.startsWith("LIBXESS_") ||
9521
9582
  prop.startsWith("XEMS_") ||
9522
- prop.startsWith("ENC_") ||
9523
- prop.startsWith("DOTENV_") ||
9524
- prop.startsWith("__")) {
9583
+ prop.startsWith("XESS_")) {
9584
+ isInsideShieldCheck = true;
9525
9585
  try {
9526
- delete target[prop];
9586
+ const caller = getVerifiedCallerInfo();
9587
+ if (!caller.isUntrusted && isImmediateInternalEngineCall()) {
9588
+ try {
9589
+ delete target[prop];
9590
+ }
9591
+ catch { }
9592
+ return true;
9593
+ }
9527
9594
  }
9528
- catch {
9529
- // ignore
9595
+ finally {
9596
+ isInsideShieldCheck = false;
9530
9597
  }
9531
9598
  return true;
9532
9599
  }
9600
+ if (self.whitelistedFields.has(prop)) {
9601
+ try {
9602
+ delete target[prop];
9603
+ }
9604
+ catch { }
9605
+ return true;
9606
+ }
9533
9607
  }
9534
9608
  return true;
9535
9609
  },
9536
- // Harden enumeration: restrict what callers see when they iterate
9537
- // or spread process.env. Without this trap, spread operators and
9538
- // Object.keys() bypass the get trap entirely.
9539
- ownKeys(_target) {
9610
+ // Harden enumeration: restrict what untrusted callers see when they iterate
9611
+ // or spread process.env, while preserving full environment for internal engine callers.
9612
+ ownKeys(target) {
9613
+ if (isInsideShieldCheck) {
9614
+ return Reflect.ownKeys(target);
9615
+ }
9616
+ isInsideShieldCheck = true;
9617
+ try {
9618
+ const caller = getVerifiedCallerInfo();
9619
+ if (!caller.isUntrusted && isImmediateInternalEngineCall()) {
9620
+ return Reflect.ownKeys(target);
9621
+ }
9622
+ }
9623
+ catch {
9624
+ }
9625
+ finally {
9626
+ isInsideShieldCheck = false;
9627
+ }
9540
9628
  return [...self.whitelistedFields];
9541
9629
  },
9542
9630
  // Align `in` operator behaviour with the restricted key set.
9543
- has(_target, prop) {
9631
+ has(target, prop) {
9544
9632
  if (typeof prop !== "string")
9545
9633
  return false;
9546
- return self.whitelistedFields.has(prop);
9634
+ if (self.whitelistedFields.has(prop))
9635
+ return true;
9636
+ if (prop.startsWith("XYPRISS_") ||
9637
+ prop.startsWith("LIBXESS_") ||
9638
+ prop.startsWith("XESS_") ||
9639
+ prop.startsWith("LIBPORT_") ||
9640
+ prop.startsWith("PORT_") ||
9641
+ prop.startsWith("XPM_")) {
9642
+ if (isInsideShieldCheck)
9643
+ return true;
9644
+ isInsideShieldCheck = true;
9645
+ try {
9646
+ const caller = getVerifiedCallerInfo();
9647
+ return !caller.isUntrusted && isImmediateInternalEngineCall();
9648
+ }
9649
+ catch {
9650
+ return false;
9651
+ }
9652
+ finally {
9653
+ isInsideShieldCheck = false;
9654
+ }
9655
+ }
9656
+ return false;
9547
9657
  },
9548
9658
  });
9659
+ _shieldedInstances.add(envShield);
9660
+ _shieldedInstances.add(process.env);
9549
9661
  try {
9550
9662
  Object.defineProperty(process, "env", {
9551
9663
  value: envShield,
@@ -9554,11 +9666,13 @@ class EnvApi {
9554
9666
  enumerable: true,
9555
9667
  });
9556
9668
  }
9557
- catch {
9558
- // Silently degrade — the Shield could not be applied (e.g., inside
9559
- // certain container or VM environments with locked descriptors).
9560
- // The Symbol-keyed internal store remains the authoritative and
9561
- // isolated source for all EnvApi reads.
9669
+ catch (err) {
9670
+ // Issue #52 (https://github.com/Nehonix-Team/XyPriss/issues/52)
9671
+ // Emits an explicit diagnostic notice if the host runtime, sandbox, or
9672
+ // strict VM has locked the process.env descriptor beforehand.
9673
+ // Avoids silent degradation so operators immediately know when the JS
9674
+ // proxy layer cannot replace process.env on the global object.
9675
+ process.stderr.write(`\x1b[33m[SECURITY] WARNING:\x1b[0m Unable to lock process.env descriptor: ${err?.message || err}. Shield proxy degradation active.\n`);
9562
9676
  }
9563
9677
  }
9564
9678
  isCallerProjectCode() {
@@ -16291,7 +16405,7 @@ class MetaConfigRunner {
16291
16405
  * Executes a specific meta configuration file
16292
16406
  */
16293
16407
  runMetaFile(metaPath) {
16294
- const sys = getSysApi();
16408
+ const sys = getSysApi$1();
16295
16409
  const absolutePath = sys.path.resolve(metaPath);
16296
16410
  if (this.executedMetas.has(absolutePath))
16297
16411
  return;
@@ -16318,7 +16432,7 @@ class MetaConfigRunner {
16318
16432
  * Discovers and executes meta configuration files based on priority
16319
16433
  */
16320
16434
  executeMetaConfig(searchDir) {
16321
- const sys = getSysApi();
16435
+ const sys = getSysApi$1();
16322
16436
  const root = searchDir || getCallerProjectRoot() || __sys__$1.__root__;
16323
16437
  const metaFiles = searchDir
16324
16438
  ? [
@@ -16368,7 +16482,7 @@ class ConfigLoader {
16368
16482
  this.isConfigApplied = false;
16369
16483
  this.packageJson = null;
16370
16484
  this.metaRunner = new MetaConfigRunner();
16371
- this.sys = getSysApi();
16485
+ this.sys = getSysApi$1();
16372
16486
  }
16373
16487
  /**
16374
16488
  * Load all xypriss.config.json files found in the project and apply configurations
@@ -18442,7 +18556,7 @@ const MIME_MAP = {
18442
18556
  function resolveMime(ext) {
18443
18557
  return MIME_MAP[ext.toLowerCase()] ?? "application/octet-stream";
18444
18558
  }
18445
- getSysApi();
18559
+ getSysApi$1();
18446
18560
  class SendFileHandler {
18447
18561
  constructor(res, logger) {
18448
18562
  this.res = res;
@@ -26683,7 +26797,7 @@ class XHSCWorker {
26683
26797
  app.logger || initializeLogger(ConfigurationManager.get("logging"));
26684
26798
  // Issue #43: Access system environment variables through getSysApi()
26685
26799
  // to maintain compatibility with the XyPriss zero-trust model and shielded process.env
26686
- const sys = getSysApi();
26800
+ const sys = getSysApi$1();
26687
26801
  this.workerId =
26688
26802
  options?.workerId ||
26689
26803
  sys?.__env__?.get("XYPRISS_WORKER_ID") ||
@@ -27317,7 +27431,7 @@ class EngineManager {
27317
27431
  ? ["--plugins", uniquePluginPaths.join(",")]
27318
27432
  : [];
27319
27433
  // Access project root lazily via getSysApi() to break circular imports
27320
- const sys = getSysApi();
27434
+ const sys = getSysApi$1();
27321
27435
  const projectRoot = sys?.__root__ ||
27322
27436
  getCallerProjectRoot() ||
27323
27437
  identifyProjectRoot(process.cwd()) ||
@@ -27370,6 +27484,9 @@ class EngineManager {
27370
27484
  detached: true,
27371
27485
  env: {
27372
27486
  ...process.env,
27487
+ XYPRISS_USER_TMP: tmpDir,
27488
+ XESS_SESSION_TMP: tmpDir,
27489
+ XYPRISS_SESSION_HASH: sessionHash,
27373
27490
  ...(internalSig
27374
27491
  ? { XYPRISS_INTERNAL_TOKEN: internalSig }
27375
27492
  : {}),
@@ -27490,7 +27607,7 @@ class XHSCBridge {
27490
27607
  // 0. Check if we are a worker spawned by Go (Clustering mode)
27491
27608
  // Auxiliary servers should NEVER act as cluster workers for the primary instance.
27492
27609
  // Issue #43: Access workerId via getSysApi() to adhere to XyPriss zero-trust environment model
27493
- const sysApi = getSysApi();
27610
+ const sysApi = getSysApi$1();
27494
27611
  const currentWorkerId = sysApi?.__env__?.get("XYPRISS_WORKER_ID");
27495
27612
  if (currentWorkerId && currentWorkerId !== "master" && !this.app.configs?.isAuxiliary) {
27496
27613
  this.logger.info("cluster", `Worker ${currentWorkerId} starting...`);
@@ -27529,7 +27646,7 @@ class XHSCBridge {
27529
27646
  // Issue #43: Use getSysApi().__env__.set() instead of assigning to process.env directly.
27530
27647
  // In strict JS runtimes like Bun (multi-server mode), mutating process.env when wrapped
27531
27648
  // in an immutable descriptor causes fatal descriptor rejection exceptions.
27532
- const sys = getSysApi();
27649
+ const sys = getSysApi$1();
27533
27650
  sys?.__env__?.set("XYPRISS_WORKER_ID", "master");
27534
27651
  sys?.__env__?.set("XYPRISS_IPC_PATH", this.socketPath);
27535
27652
  }
@@ -28145,7 +28262,7 @@ class ConsoleInterceptor {
28145
28262
  isActive: false,
28146
28263
  };
28147
28264
  // Issue #43: Access XYPRISS_IPC_PATH via getSysApi()
28148
- this.ipcPath = getSysApi()?.__env__?.get("XYPRISS_IPC_PATH");
28265
+ this.ipcPath = getSysApi$1()?.__env__?.get("XYPRISS_IPC_PATH");
28149
28266
  }
28150
28267
  /**
28151
28268
  * Decides whether a log line should be displayed given the current displayLimit config.
@@ -28205,7 +28322,7 @@ class ConsoleInterceptor {
28205
28322
  this.stats.isActive = true;
28206
28323
  // Try to sync config if IPC is already available (Issue #43)
28207
28324
  this.ipcPath =
28208
- this.ipcPath || getSysApi()?.__env__?.get("XYPRISS_IPC_PATH");
28325
+ this.ipcPath || getSysApi$1()?.__env__?.get("XYPRISS_IPC_PATH");
28209
28326
  if (this.ipcPath) {
28210
28327
  const ipc = new XHSCDirectIPC(this.ipcPath);
28211
28328
  await ipc.sendCommand("console", "update-config", this.config);
@@ -28595,7 +28712,7 @@ class XyLifecycleManager {
28595
28712
  async handleServerStartup(serverPort, host, callback) {
28596
28713
  // Rust/Go-Managed Clustering Mode
28597
28714
  // Issue #43: Retrieve workerId and ipcPath via getSysApi() rather than raw process.env
28598
- const sys = getSysApi();
28715
+ const sys = getSysApi$1();
28599
28716
  const workerId = sys?.__env__?.get("XYPRISS_WORKER_ID") ||
28600
28717
  (typeof process !== "undefined"
28601
28718
  ? process.env?.XYPRISS_WORKER_ID
@@ -29081,12 +29198,12 @@ class XyprissApp {
29081
29198
  this.settings = {
29082
29199
  "x-powered-by": false,
29083
29200
  etag: "weak",
29084
- env: getSysApi()?.__env__?.get("NODE_ENV") || "development",
29201
+ env: getSysApi$1()?.__env__?.get("NODE_ENV") || "development",
29085
29202
  "subdomain offset": 2,
29086
29203
  "trust proxy": false,
29087
29204
  "view cache": true,
29088
29205
  "view engine": false,
29089
- views: getSysApi()?.__env__?.get("XYPRISS_VIEWS") || process.cwd() + "/views",
29206
+ views: getSysApi$1()?.__env__?.get("XYPRISS_VIEWS") || process.cwd() + "/views",
29090
29207
  };
29091
29208
  }
29092
29209
  // ===== HTTP METHOD IMPLEMENTATIONS =====
@@ -31109,7 +31226,7 @@ class SecurityMiddleware {
31109
31226
  cookieOptions: {
31110
31227
  httpOnly: true,
31111
31228
  sameSite: "strict",
31112
- secure: getSysApi().__env__.isProduction(),
31229
+ secure: getSysApi$1().__env__.isProduction(),
31113
31230
  maxAge: 24 * 60 * 60 * 1000, // 24 hours
31114
31231
  ...(csrfConfig.cookieOptions || {}),
31115
31232
  },
@@ -32394,7 +32511,7 @@ class WorkerPoolComponent {
32394
32511
  // Add task execution method via IPC
32395
32512
  // Issue #43: Access XYPRISS_IPC_PATH through getSysApi()
32396
32513
  app.executeTask = (task) => {
32397
- const ipcPath = getSysApi()?.__env__?.get("XYPRISS_IPC_PATH");
32514
+ const ipcPath = getSysApi$1()?.__env__?.get("XYPRISS_IPC_PATH");
32398
32515
  if (this.isXHSC && ipcPath) {
32399
32516
  // In worker mode, we send the task to Go via the global IPC handler
32400
32517
  // We'll assume the XHSCWorker instance is available or
@@ -32481,7 +32598,7 @@ class ComponentManager {
32481
32598
  }
32482
32599
  async initializeWorkerPool() {
32483
32600
  // Issue #43: Retrieve XYPRISS_WORKER_ID via getSysApi()
32484
- const workerId = getSysApi()?.__env__?.get("XYPRISS_WORKER_ID");
32601
+ const workerId = getSysApi$1()?.__env__?.get("XYPRISS_WORKER_ID");
32485
32602
  const isWorker = !!workerId && workerId !== "master";
32486
32603
  if (this.options.workerPool?.enabled) {
32487
32604
  this.refs.workerPoolComponent = new WorkerPoolComponent({ workerPool: this.options.workerPool }, { app: this.app, serverOptions: this.options });
@@ -32811,7 +32928,7 @@ class XyPrissServer {
32811
32928
  * the XyPriss zero-trust model and avoid process.env shield traps.
32812
32929
  */
32813
32930
  function handleWorkerMode(options) {
32814
- const sys = getSysApi();
32931
+ const sys = getSysApi$1();
32815
32932
  const env = sys?.__env__;
32816
32933
  // Check if running in worker mode
32817
32934
  const clusterMode = env?.get("XYPRISS_CLUSTER_MODE") ||
@@ -36617,7 +36734,7 @@ class XyServerCreator {
36617
36734
  // 3. Setup environment
36618
36735
  // Issue #43: Apply NODE_ENV through getSysApi().__env__.set() to avoid strict descriptor exceptions under Bun
36619
36736
  if (options.env) {
36620
- const sys = getSysApi();
36737
+ const sys = getSysApi$1();
36621
36738
  if (sys?.__env__) {
36622
36739
  sys.__env__.set("NODE_ENV", options.env);
36623
36740
  }
@@ -36743,7 +36860,7 @@ class XMSStartupUI {
36743
36860
  quiet: options.quiet !== false,
36744
36861
  silent: options.silent === true,
36745
36862
  };
36746
- const sysEnv = getSysApi()?.__env__;
36863
+ const sysEnv = getSysApi$1()?.__env__;
36747
36864
  const isCI = sysEnv ? sysEnv.get("CI") : (typeof process !== "undefined" && process.env?.CI);
36748
36865
  const noColor = sysEnv ? sysEnv.get("NO_COLOR") : (typeof process !== "undefined" && process.env?.NO_COLOR);
36749
36866
  const disableColors = sysEnv ? sysEnv.get("NODE_DISABLE_COLORS") : (typeof process !== "undefined" && process.env?.NODE_DISABLE_COLORS);
@@ -38913,6 +39030,9 @@ function getIp(req, enriched) {
38913
39030
  if (typeof globalThis !== "undefined") {
38914
39031
  configLoader.loadAndApplySysConfig();
38915
39032
  }
39033
+ function getSysApi() {
39034
+ return __sys__$1;
39035
+ }
38916
39036
  /**
38917
39037
  * Default router instance for quick start
38918
39038
  */
@@ -38951,6 +39071,7 @@ exports.getInstanceId = getInstanceId;
38951
39071
  exports.getIp = getIp;
38952
39072
  exports.getMime = getMime;
38953
39073
  exports.getMimes = getMimes;
39074
+ exports.getSysApi = getSysApi;
38954
39075
  exports.identifyProjectRoot = identifyProjectRoot;
38955
39076
  exports.initializeFileUpload = initializeFileUpload;
38956
39077
  exports.mergeWithDefaults = mergeWithDefaults;