xypriss 9.14.37 → 9.15.0

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
@@ -1861,6 +1861,7 @@ const _StringIndexOf = Function.prototype.call.bind(String.prototype.indexOf);
1861
1861
  const _StringLastIndexOf = Function.prototype.call.bind(String.prototype.lastIndexOf);
1862
1862
  const _PathResolve = path.resolve.bind(path);
1863
1863
  const _PathIsAbsolute = path.isAbsolute.bind(path);
1864
+ const _PathPosixNormalize = path.posix.normalize.bind(path.posix);
1864
1865
  const _JSONParse = JSON.parse;
1865
1866
  const _JSONStringify = JSON.stringify;
1866
1867
  const _Uint8ArrayFill = Function.prototype.call.bind(Uint8Array.prototype.fill);
@@ -1870,65 +1871,86 @@ Function.prototype.call.bind(WeakMap.prototype.has);
1870
1871
  Function.prototype.call.bind(WeakMap.prototype.delete);
1871
1872
  /**
1872
1873
  * Resolved canonical installation directory for the XyPriss engine core.
1873
- * Anchoring this path at module load time eliminates heuristic substring bypasses.
1874
+ * Immutable const anchored at module load time to eliminate heuristic substring bypasses
1875
+ * and CJS/namespace mutation.
1874
1876
  *
1875
1877
  * @internal
1876
1878
  * @see XSA-XESS-018
1877
1879
  * @see XSA-XESS-026
1880
+ * @see XSA-CORE-002
1881
+ * @see XSA-CORE-006
1878
1882
  */
1879
- let ENGINE_CORE_DIR = "";
1880
- try {
1881
- let thisFile = "";
1882
- if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))) {
1883
- thisFile = _StringReplace(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))), /\\/g, "/");
1884
- }
1885
- else if (typeof __filename !== "undefined") {
1886
- thisFile = _StringReplace(__filename, /\\/g, "/");
1887
- }
1888
- if (thisFile) {
1889
- const srcIdx = _StringLastIndexOf(thisFile, "/src/");
1890
- if (srcIdx !== -1) {
1891
- ENGINE_CORE_DIR = _StringSlice(thisFile, 0, srcIdx + 1); // root directory with trailing '/'
1883
+ const ENGINE_CORE_DIR = (() => {
1884
+ try {
1885
+ let thisFile = "";
1886
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))) {
1887
+ thisFile = _StringReplace(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))), /\\/g, "/");
1892
1888
  }
1893
- else {
1889
+ else if (typeof __filename !== "undefined") {
1890
+ thisFile = _StringReplace(__filename, /\\/g, "/");
1891
+ }
1892
+ if (thisFile) {
1893
+ thisFile = _PathPosixNormalize(thisFile);
1894
+ const srcIdx = _StringLastIndexOf(thisFile, "/src/");
1895
+ if (srcIdx !== -1) {
1896
+ return _StringSlice(thisFile, 0, srcIdx + 1); // root directory with trailing '/'
1897
+ }
1894
1898
  const distIdx = _StringLastIndexOf(thisFile, "/dist/");
1895
1899
  if (distIdx !== -1) {
1896
- ENGINE_CORE_DIR = _StringSlice(thisFile, 0, distIdx + 1); // root directory with trailing '/'
1900
+ return _StringSlice(thisFile, 0, distIdx + 1); // root directory with trailing '/'
1897
1901
  }
1898
1902
  }
1899
1903
  }
1900
- }
1901
- catch {
1902
- // fallback
1904
+ catch {
1905
+ // fail-closed: empty string disables core-path matching
1906
+ }
1907
+ return "";
1908
+ })();
1909
+ const ENGINE_SRC_DIR = ENGINE_CORE_DIR ? ENGINE_CORE_DIR + "src/" : "";
1910
+ const ENGINE_DIST_DIR = ENGINE_CORE_DIR ? ENGINE_CORE_DIR + "dist/" : "";
1911
+ /**
1912
+ * Canonicalizes a raw file path by converting Windows separators and resolving
1913
+ * any relative traversal segments (`..`, `.`, `//`).
1914
+ *
1915
+ * @see XSA-CORE-003
1916
+ */
1917
+ function canonicalizePath(filePath) {
1918
+ const slashed = _StringReplace(filePath, /\\/g, "/");
1919
+ return _PathPosixNormalize(slashed);
1903
1920
  }
1904
1921
  /**
1905
- * Checks if a given file path belongs to the deep engine core.
1906
- * These files are skipped during stack analysis to find the user/plugin caller.
1922
+ * Checks if a given file path belongs strictly to the XyPriss engine core
1923
+ * (`${ENGINE_CORE_DIR}src/` or `${ENGINE_CORE_DIR}dist/`).
1924
+ * These files are skipped during stack analysis to locate the user/plugin caller.
1907
1925
  *
1908
1926
  * @see XSA-XESS-015 - Immune to prototype pollution on String.prototype
1909
1927
  * @see XSA-XESS-018 - Heuristic path evaluation hardening anchored on ENGINE_CORE_DIR
1910
- * @see XSA-XESS-026 - Rejects any node_modules subpath not strictly starting with ENGINE_CORE_DIR
1928
+ * @see XSA-XESS-026 - Rejects any node_modules subpath not strictly inside engine core
1929
+ * @see XSA-CORE-001 - Eliminates substring spoofing (`/XyPriss/src/`, `/XyPriss/dist/`)
1930
+ * @see XSA-CORE-002 - Restricts trust strictly to `src/` and `dist/` (excludes sibling `mods/` & nested `node_modules/`)
1931
+ * @see XSA-CORE-003 - Canonicalizes `..` path traversal before prefix checks
1911
1932
  */
1912
1933
  function isEngineCorePath(filePath) {
1913
- if (!filePath)
1934
+ if (!filePath || !ENGINE_CORE_DIR)
1914
1935
  return false;
1915
- const normalizedPath = _StringReplace(filePath, /\\/g, "/");
1916
- // Any path inside node_modules that is NOT inside our resolved ENGINE_CORE_DIR
1917
- // is an untrusted third-party package and CANNOT be the engine core.
1918
- if (_StringIncludes(normalizedPath, "/node_modules/")) {
1919
- if (ENGINE_CORE_DIR && _StringStartsWith(normalizedPath, ENGINE_CORE_DIR)) {
1920
- return true;
1921
- }
1922
- return false;
1923
- }
1924
- if (ENGINE_CORE_DIR && _StringStartsWith(normalizedPath, ENGINE_CORE_DIR)) {
1936
+ const canonical = canonicalizePath(filePath);
1937
+ // Canonical match for ENGINE_CORE_DIR itself (with or without trailing slash)
1938
+ const normCore = canonicalizePath(ENGINE_CORE_DIR);
1939
+ if (canonical === normCore) {
1925
1940
  return true;
1926
1941
  }
1927
- if (_StringIncludes(normalizedPath, "/XyPriss/src/") ||
1928
- _StringIncludes(normalizedPath, "/XyPriss/dist/")) {
1929
- return true;
1942
+ // Must reside strictly inside the engine's own `src/` or `dist/` directory
1943
+ const inSrc = ENGINE_SRC_DIR !== "" && _StringStartsWith(canonical, ENGINE_SRC_DIR);
1944
+ const inDist = ENGINE_DIST_DIR !== "" && _StringStartsWith(canonical, ENGINE_DIST_DIR);
1945
+ if (!inSrc && !inDist) {
1946
+ return false;
1930
1947
  }
1931
- return false;
1948
+ // Reject any nested node_modules inside the engine directory (e.g. transitive dependencies)
1949
+ const rel = _StringSlice(canonical, ENGINE_CORE_DIR.length);
1950
+ if (_StringIncludes(rel, "node_modules/")) {
1951
+ return false;
1952
+ }
1953
+ return true;
1932
1954
  }
1933
1955
  /**
1934
1956
  * Checks if a given file path belongs directly to the XyPriss Core Engine
@@ -1938,18 +1960,13 @@ function isEngineCorePath(filePath) {
1938
1960
  * @see XSA-XESS-015
1939
1961
  * @see XSA-XESS-018
1940
1962
  * @see XSA-XESS-026
1963
+ * @see XSA-CORE-001 - Eliminates `/XyPriss/mods/` substring bypass
1964
+ * @see XSA-CORE-002 - Plugins in `mods/` are sandboxed under their own root, never treated as core framework
1965
+ * @see XSA-CORE-003 - Canonicalizes `..` path traversal before verification
1941
1966
  */
1942
1967
  function isCoreFrameworkPath(filePath) {
1943
1968
  if (!filePath)
1944
1969
  return false;
1945
- const normalizedPath = _StringReplace(filePath, /\\/g, "/");
1946
- // Authorize trusted internal mods within the framework repository
1947
- if (_StringIncludes(normalizedPath, "/XyPriss/mods/"))
1948
- return true;
1949
- // Exclude other plugins even if they contain 'src' or are named 'xypriss-something'
1950
- if (_StringIncludes(normalizedPath, "/mods/"))
1951
- return false;
1952
- // Engine Core is always trusted
1953
1970
  return isEngineCorePath(filePath);
1954
1971
  }
1955
1972
 
@@ -2011,16 +2028,38 @@ const _nativeGetCallSites = typeof util.getCallSites === "function"
2011
2028
  ? util.getCallSites.bind(util)
2012
2029
  : null;
2013
2030
  let cachedManifest = null;
2031
+ /**
2032
+ * Anchored primary project root captured once at early module bootstrap.
2033
+ * Prevents runtime `process.chdir()` or ambient `process.env` mutation from shifting
2034
+ * the primary sandbox boundary after startup.
2035
+ *
2036
+ * @see XSA-CORE-005
2037
+ */
2038
+ const BOOTSTRAPPED_PRIMARY_ROOT = (() => {
2039
+ try {
2040
+ const raw = process.env.XYPRISS_PROJECT_ROOT || process.cwd();
2041
+ return _PathPosixNormalize(_StringReplace(_PathResolve(raw), /\\/g, "/"));
2042
+ }
2043
+ catch {
2044
+ return "";
2045
+ }
2046
+ })();
2047
+ const BOOTSTRAPPED_MANIFEST_PATH = (() => {
2048
+ if (process.env.XYPRISS_PLUGINS_MANIFEST) {
2049
+ return process.env.XYPRISS_PLUGINS_MANIFEST;
2050
+ }
2051
+ if (BOOTSTRAPPED_PRIMARY_ROOT) {
2052
+ return path$1.join(BOOTSTRAPPED_PRIMARY_ROOT, "node_modules", ".xfpm", "plugins_manifest.json");
2053
+ }
2054
+ return null;
2055
+ })();
2014
2056
  /**
2015
2057
  * Loads the authoritative plugins manifest provided by xfpm.
2016
2058
  */
2017
2059
  function getPluginsManifest() {
2018
2060
  if (cachedManifest)
2019
2061
  return cachedManifest;
2020
- const manifestPath = process.env.XYPRISS_PLUGINS_MANIFEST ||
2021
- (process.env.XYPRISS_PROJECT_ROOT
2022
- ? path$1.join(process.env.XYPRISS_PROJECT_ROOT, "node_modules", ".xfpm", "plugins_manifest.json")
2023
- : null);
2062
+ const manifestPath = BOOTSTRAPPED_MANIFEST_PATH;
2024
2063
  if (manifestPath && fs.existsSync(manifestPath)) {
2025
2064
  try {
2026
2065
  const raw = fs.readFileSync(manifestPath, "utf-8");
@@ -2033,6 +2072,14 @@ function getPluginsManifest() {
2033
2072
  }
2034
2073
  return null;
2035
2074
  }
2075
+ /**
2076
+ * Returns the primary project root determined by xfpm CLI (anchored at bootstrap).
2077
+ *
2078
+ * @see XSA-CORE-005
2079
+ */
2080
+ function getPrimaryProjectRoot() {
2081
+ return BOOTSTRAPPED_PRIMARY_ROOT;
2082
+ }
2036
2083
  /**
2037
2084
  * Checks if a directory is a valid project root.
2038
2085
  */
@@ -2056,6 +2103,49 @@ function isProjectRoot(dir) {
2056
2103
  return false;
2057
2104
  }
2058
2105
  }
2106
+ /**
2107
+ * Extracts the node package root directory from a file path located in node_modules.
2108
+ * Handles standard node_modules, scoped packages (@scope/name), and virtual stores (.xfpm/vstore).
2109
+ *
2110
+ * @param filePath - The absolute or relative file path.
2111
+ * @returns The normalized package root directory, or null if not inside node_modules.
2112
+ *
2113
+ * @see XSA-XESS-028 Scoped Package Environment Sandboxing
2114
+ */
2115
+ function extractPackageRootFromPath(filePath) {
2116
+ if (!filePath)
2117
+ return null;
2118
+ const normalized = _PathPosixNormalize(_StringReplace(filePath, /\\/g, "/"));
2119
+ const nmIdx = _StringLastIndexOf(normalized, "/node_modules/");
2120
+ let afterNm;
2121
+ let nmPrefix;
2122
+ if (nmIdx !== -1) {
2123
+ nmPrefix = _StringSubstring(normalized, 0, nmIdx + 14);
2124
+ afterNm = _StringSubstring(normalized, nmIdx + 14);
2125
+ }
2126
+ else if (_StringStartsWith(normalized, "node_modules/")) {
2127
+ nmPrefix = "node_modules/";
2128
+ afterNm = _StringSubstring(normalized, 13);
2129
+ }
2130
+ else {
2131
+ return null;
2132
+ }
2133
+ if (!afterNm)
2134
+ return null;
2135
+ if (_StringStartsWith(afterNm, "@")) {
2136
+ const firstSlash = _StringIndexOf(afterNm, "/");
2137
+ if (firstSlash === -1)
2138
+ return null;
2139
+ const secondSlash = _StringIndexOf(afterNm, "/", firstSlash + 1);
2140
+ const pkgRel = secondSlash === -1
2141
+ ? afterNm
2142
+ : _StringSubstring(afterNm, 0, secondSlash);
2143
+ return nmPrefix + pkgRel;
2144
+ }
2145
+ const slash = _StringIndexOf(afterNm, "/");
2146
+ const pkgRel = slash === -1 ? afterNm : _StringSubstring(afterNm, 0, slash);
2147
+ return nmPrefix + pkgRel;
2148
+ }
2059
2149
  /**
2060
2150
  * Identifies the project or plugin root for a given caller path using xfpm metadata.
2061
2151
  *
@@ -2063,12 +2153,18 @@ function isProjectRoot(dir) {
2063
2153
  * @see XSA-XESS-018 - Anchored path verification
2064
2154
  * @see XSA-XESS-020 - Immune to path.resolve / path.isAbsolute monkey-patching
2065
2155
  * @see XSA-XESS-025 - Rejects synthetic VM / eval script paths
2156
+ * @see XSA-XESS-028 - Discrete package sandboxing for node_modules dependencies
2066
2157
  */
2067
2158
  function identifyProjectRoot(filePath) {
2068
2159
  if (!filePath)
2069
2160
  return undefined;
2070
2161
  if (_StringIncludes(filePath, "[vm]") ||
2071
- _StringIncludes(filePath, "[eval]")) {
2162
+ _StringIncludes(filePath, "[eval]") ||
2163
+ _StringStartsWith(filePath, "[") ||
2164
+ _StringStartsWith(filePath, "<") ||
2165
+ filePath === "[unknown]" ||
2166
+ filePath === "<anonymous>" ||
2167
+ filePath === "[native code]") {
2072
2168
  return undefined;
2073
2169
  }
2074
2170
  if (!_PathIsAbsolute(filePath)) {
@@ -2079,36 +2175,73 @@ function identifyProjectRoot(filePath) {
2079
2175
  return undefined;
2080
2176
  }
2081
2177
  }
2082
- const normalized = _StringReplace(filePath, /\\/g, "/");
2083
- const primaryRoot = _StringReplace(process.env.XYPRISS_PROJECT_ROOT || process.cwd(), /\\/g, "/");
2178
+ const normalized = _PathPosixNormalize(_StringReplace(filePath, /\\/g, "/"));
2179
+ const primaryRoot = BOOTSTRAPPED_PRIMARY_ROOT;
2084
2180
  // 1. Direct O(1) match against verified plugins registered by xfpm
2085
2181
  const manifest = getPluginsManifest();
2086
2182
  if (manifest?.roots) {
2087
2183
  const rootEntries = _ObjectEntries(manifest.roots);
2088
2184
  for (let i = 0; i < rootEntries.length; i++) {
2089
2185
  const [pluginRoot] = rootEntries[i];
2090
- const normPluginRoot = _StringReplace(pluginRoot, /\\/g, "/");
2186
+ const normPluginRoot = _PathPosixNormalize(_StringReplace(pluginRoot, /\\/g, "/"));
2091
2187
  if (normalized === normPluginRoot ||
2092
2188
  _StringStartsWith(normalized, normPluginRoot + "/")) {
2093
2189
  return pluginRoot;
2094
2190
  }
2095
2191
  }
2096
2192
  }
2097
- // 2. Direct match against primary project root
2098
- if (normalized === primaryRoot ||
2099
- _StringStartsWith(normalized, primaryRoot + "/")) {
2100
- // If inside node_modules, it is an undeclared/untrusted dependency, NOT the application root!
2101
- if (_StringIncludes(normalized, "/node_modules/")) {
2102
- return undefined;
2193
+ // 2. Node modules discrete sandbox isolation
2194
+ // Every module in node_modules must have its own isolated sandbox environment.
2195
+ // It should never leak into or inherit the host project root unless explicitly permitted.
2196
+ const pkgRoot = extractPackageRootFromPath(normalized);
2197
+ if (pkgRoot) {
2198
+ let canonicalPkgRoot = pkgRoot;
2199
+ try {
2200
+ canonicalPkgRoot = _PathPosixNormalize(_StringReplace(fs.realpathSync(pkgRoot), /\\/g, "/"));
2201
+ }
2202
+ catch {
2203
+ // keep pkgRoot if realpath resolution fails
2204
+ }
2205
+ // Check if canonical path matches a registered plugin root in manifest
2206
+ if (manifest?.roots) {
2207
+ const rootEntries = _ObjectEntries(manifest.roots);
2208
+ for (let i = 0; i < rootEntries.length; i++) {
2209
+ const [pluginRoot] = rootEntries[i];
2210
+ const normPluginRoot = _PathPosixNormalize(_StringReplace(pluginRoot, /\\/g, "/"));
2211
+ if (canonicalPkgRoot === normPluginRoot ||
2212
+ _StringStartsWith(canonicalPkgRoot, normPluginRoot + "/")) {
2213
+ return pluginRoot;
2214
+ }
2215
+ }
2216
+ }
2217
+ // Return the discrete module package root sandbox
2218
+ return canonicalPkgRoot;
2219
+ }
2220
+ // 3. Direct match against primary project root
2221
+ if (primaryRoot &&
2222
+ (normalized === primaryRoot ||
2223
+ _StringStartsWith(normalized, primaryRoot + "/"))) {
2224
+ // Monorepo safety: if a sibling /mods/<name>/ lives under the monorepo root,
2225
+ // give it its own sandbox root rather than the host root!
2226
+ const modsIdxPrimary = _StringLastIndexOf(normalized, "/mods/");
2227
+ if (modsIdxPrimary !== -1) {
2228
+ const afterMods = _StringSubstring(normalized, modsIdxPrimary + 6);
2229
+ const nextSlash = _StringIndexOf(afterMods, "/");
2230
+ const modName = nextSlash === -1
2231
+ ? afterMods
2232
+ : _StringSubstring(afterMods, 0, nextSlash);
2233
+ if (modName) {
2234
+ return _StringSubstring(normalized, 0, modsIdxPrimary + 6 + modName.length);
2235
+ }
2103
2236
  }
2104
2237
  return primaryRoot;
2105
2238
  }
2106
- // 3. Monorepo development mods (/mods/<name>/) fallback
2107
- // @see XSA-XESS-018: Must be strictly anchored to the primary project root or framework monorepo
2239
+ // 4. Monorepo development mods (/mods/<name>/) fallback
2240
+ // @see XSA-XESS-018 / XSA-CORE-002: Strictly anchored to ENGINE_CORE_DIR + "mods/"
2108
2241
  const modsIdx = _StringLastIndexOf(normalized, "/mods/");
2109
2242
  if (modsIdx !== -1 &&
2110
- (_StringStartsWith(normalized, primaryRoot + "/") ||
2111
- isEngineCorePath(normalized))) {
2243
+ ENGINE_CORE_DIR !== "" &&
2244
+ _StringStartsWith(normalized, ENGINE_CORE_DIR + "mods/")) {
2112
2245
  const afterMods = _StringSubstring(normalized, modsIdx + 6);
2113
2246
  const nextSlash = _StringIndexOf(afterMods, "/");
2114
2247
  const modName = nextSlash === -1
@@ -2347,7 +2480,8 @@ function isImmediateInternalEngineCall() {
2347
2480
  fnName === "callSync" ||
2348
2481
  fnName === "callSyncSubprocess" ||
2349
2482
  fnName === "executeEnvCall" ||
2350
- fnName === "configureShield") {
2483
+ fnName === "configureShield" ||
2484
+ fnName === "setRootInterceptor") {
2351
2485
  continue;
2352
2486
  }
2353
2487
  }
@@ -2386,7 +2520,10 @@ function getVerifiedCallerInfo() {
2386
2520
  continue;
2387
2521
  if (_StringStartsWith(filePath, "node:") ||
2388
2522
  _StringStartsWith(filePath, "bun:") ||
2389
- filePath === "native") {
2523
+ filePath === "native" ||
2524
+ filePath === "[unknown]" ||
2525
+ filePath === "<anonymous>" ||
2526
+ filePath === "[native code]") {
2390
2527
  continue;
2391
2528
  }
2392
2529
  // Skip XyPriss internal engine frames
@@ -4844,6 +4981,310 @@ class Discovery {
4844
4981
  }
4845
4982
  }
4846
4983
 
4984
+ /* *****************************************************************************
4985
+ * Nehonix libSynapx — XyPrss Native Synchronous Unix Domain Socket Transport (XNatSUDT) (bun:ffi)
4986
+ *
4987
+ * Ultra-low latency synchronous IPC transport directly invoking POSIX libc
4988
+ * socket/connect/send/recv syscalls without Worker threads, postMessage, or futex hops.
4989
+ *
4990
+ * Security invariants:
4991
+ * - XSA-SYNAPX-001: Immediate zero-scrubbing of TX/RX buffers after every call.
4992
+ * - XSA-XESS-021: Uses frozen JSON/Uint8Array primordials against prototype pollution.
4993
+ * - XSA-XESS-027: Hardened with native ES private fields.
4994
+ * - Automatic graceful fallback to Worker SharedArrayBuffer bridge on Node.js/Windows.
4995
+ ***************************************************************************** */
4996
+ const MAGIC_BYTE$1 = 0x53; // 'S'
4997
+ const MSG_HANDSHAKE$1 = 0x01;
4998
+ const MSG_HANDSHAKE_ACK$1 = 0x02;
4999
+ const MSG_CALL$1 = 0x03;
5000
+ const MSG_ERROR$1 = 0xff;
5001
+ const DEFAULT_BUF_SIZE = 64 * 1024; // 64 KB reusable slab (auto-grows for large payloads)
5002
+ const MAX_UNIX_PATH_LEN = 104;
5003
+ let cachedFfi = undefined;
5004
+ function loadFfiRuntime() {
5005
+ if (cachedFfi !== undefined) {
5006
+ return cachedFfi;
5007
+ }
5008
+ if (typeof globalThis.Bun === "undefined") {
5009
+ cachedFfi = null;
5010
+ return null;
5011
+ }
5012
+ const platform = process.platform;
5013
+ if (platform !== "linux" && platform !== "darwin") {
5014
+ cachedFfi = null;
5015
+ return null;
5016
+ }
5017
+ try {
5018
+ // Dynamic require keeps TypeScript/Node.js bundles completely clean
5019
+ const bunFfi = require("bun:ffi");
5020
+ const { dlopen, FFIType, ptr } = bunFfi;
5021
+ const isLinux = platform === "linux";
5022
+ const libName = isLinux ? "libc.so.6" : "libSystem.B.dylib";
5023
+ const lib = dlopen(libName, {
5024
+ socket: {
5025
+ args: [FFIType.i32, FFIType.i32, FFIType.i32],
5026
+ returns: FFIType.i32,
5027
+ },
5028
+ connect: {
5029
+ args: [FFIType.i32, FFIType.ptr, FFIType.u32],
5030
+ returns: FFIType.i32,
5031
+ },
5032
+ send: {
5033
+ args: [FFIType.i32, FFIType.ptr, FFIType.u64, FFIType.i32],
5034
+ returns: FFIType.i64,
5035
+ },
5036
+ recv: {
5037
+ args: [FFIType.i32, FFIType.ptr, FFIType.u64, FFIType.i32],
5038
+ returns: FFIType.i64,
5039
+ },
5040
+ setsockopt: {
5041
+ args: [
5042
+ FFIType.i32,
5043
+ FFIType.i32,
5044
+ FFIType.i32,
5045
+ FFIType.ptr,
5046
+ FFIType.u32,
5047
+ ],
5048
+ returns: FFIType.i32,
5049
+ },
5050
+ close: { args: [FFIType.i32], returns: FFIType.i32 },
5051
+ });
5052
+ cachedFfi = {
5053
+ symbols: lib.symbols,
5054
+ ptr,
5055
+ isLinux,
5056
+ // MSG_NOSIGNAL (0x4000) on Linux prevents SIGPIPE crash if daemon closes socket
5057
+ msgFlags: isLinux ? 0x4000 : 0,
5058
+ solSocket: isLinux ? 1 : 0xffff,
5059
+ soRcvTimeo: isLinux ? 20 : 0x1006,
5060
+ soSndTimeo: isLinux ? 21 : 0x1005,
5061
+ };
5062
+ return cachedFfi;
5063
+ }
5064
+ catch {
5065
+ cachedFfi = null;
5066
+ return null;
5067
+ }
5068
+ }
5069
+ class NativeUnixSyncTransport {
5070
+ #ffi;
5071
+ #socketPath;
5072
+ #sessionHash;
5073
+ #authToken;
5074
+ #fd = -1;
5075
+ #txBuf;
5076
+ #rxBuf;
5077
+ #hdrBuf;
5078
+ constructor(ffi, socketPath, sessionHash, authToken) {
5079
+ this.#ffi = ffi;
5080
+ this.#socketPath = socketPath;
5081
+ this.#sessionHash = sessionHash;
5082
+ this.#authToken = authToken;
5083
+ this.#txBuf = Buffer.allocUnsafe(DEFAULT_BUF_SIZE);
5084
+ this.#rxBuf = Buffer.allocUnsafe(DEFAULT_BUF_SIZE);
5085
+ this.#hdrBuf = Buffer.allocUnsafe(6);
5086
+ }
5087
+ static tryCreate(socketPath, sessionHash, authToken) {
5088
+ if (!socketPath || socketPath.startsWith("\\\\.\\pipe\\")) {
5089
+ return null;
5090
+ }
5091
+ if (Buffer.byteLength(socketPath, "utf8") >= MAX_UNIX_PATH_LEN) {
5092
+ return null;
5093
+ }
5094
+ const ffi = loadFfiRuntime();
5095
+ if (!ffi) {
5096
+ return null;
5097
+ }
5098
+ return new NativeUnixSyncTransport(ffi, socketPath, sessionHash, authToken);
5099
+ }
5100
+ #applySocketTimeout(fd, timeoutMs) {
5101
+ const secs = Math.max(1, Math.ceil(timeoutMs / 1000));
5102
+ // 64-bit POSIX struct timeval { int64 tv_sec; int64 tv_usec; }
5103
+ const tv = new BigInt64Array(2);
5104
+ tv[0] = BigInt(secs);
5105
+ tv[1] = 0n;
5106
+ const tvBytes = new Uint8Array(tv.buffer);
5107
+ this.#ffi.symbols.setsockopt(fd, this.#ffi.solSocket, this.#ffi.soRcvTimeo, this.#ffi.ptr(tvBytes), 16);
5108
+ this.#ffi.symbols.setsockopt(fd, this.#ffi.solSocket, this.#ffi.soSndTimeo, this.#ffi.ptr(tvBytes), 16);
5109
+ }
5110
+ #sendAll(fd, buf, totalLen) {
5111
+ let offset = 0;
5112
+ const { symbols, ptr, msgFlags } = this.#ffi;
5113
+ while (offset < totalLen) {
5114
+ const n = Number(symbols.send(fd, ptr(buf, offset), totalLen - offset, msgFlags));
5115
+ if (n <= 0) {
5116
+ return false;
5117
+ }
5118
+ offset += n;
5119
+ }
5120
+ return true;
5121
+ }
5122
+ #recvExact(fd, buf, totalLen) {
5123
+ let offset = 0;
5124
+ const { symbols, ptr } = this.#ffi;
5125
+ while (offset < totalLen) {
5126
+ const n = Number(symbols.recv(fd, ptr(buf, offset), totalLen - offset, 0));
5127
+ if (n <= 0) {
5128
+ return false;
5129
+ }
5130
+ offset += n;
5131
+ }
5132
+ return true;
5133
+ }
5134
+ #connectAndHandshake(timeoutMs) {
5135
+ this.close();
5136
+ const { symbols, ptr, isLinux } = this.#ffi;
5137
+ // AF_UNIX = 1, SOCK_STREAM = 1
5138
+ const fd = symbols.socket(1, 1, 0);
5139
+ if (fd < 0) {
5140
+ return false;
5141
+ }
5142
+ const pathBytes = Buffer.from(this.#socketPath, "utf8");
5143
+ const sockaddr = new Uint8Array(110);
5144
+ if (isLinux) {
5145
+ // Linux struct sockaddr_un { uint16 sun_family; char sun_path[108]; }
5146
+ sockaddr[0] = 1; // AF_UNIX
5147
+ sockaddr[1] = 0;
5148
+ }
5149
+ else {
5150
+ // macOS struct sockaddr_un { uint8 sun_len; uint8 sun_family; char sun_path[104]; }
5151
+ sockaddr[0] = 2 + pathBytes.length + 1;
5152
+ sockaddr[1] = 1; // AF_UNIX
5153
+ }
5154
+ sockaddr.set(pathBytes, 2);
5155
+ const addrLen = 2 + pathBytes.length + 1;
5156
+ const rc = symbols.connect(fd, ptr(sockaddr), addrLen);
5157
+ if (rc !== 0) {
5158
+ symbols.close(fd);
5159
+ return false;
5160
+ }
5161
+ this.#applySocketTimeout(fd, timeoutMs);
5162
+ // Perform mandatory Zero-Trust libSynapx handshake
5163
+ const hsJson = _JSONStringify({
5164
+ sessionHash: this.#sessionHash || "",
5165
+ token: this.#authToken || "",
5166
+ clientPid: process.pid,
5167
+ });
5168
+ const hsLen = Buffer.byteLength(hsJson, "utf8");
5169
+ const hsFrame = Buffer.allocUnsafe(6 + hsLen);
5170
+ hsFrame.writeUInt8(MAGIC_BYTE$1, 0);
5171
+ hsFrame.writeUInt8(MSG_HANDSHAKE$1, 1);
5172
+ hsFrame.writeUInt32BE(hsLen, 2);
5173
+ hsFrame.write(hsJson, 6, hsLen, "utf8");
5174
+ const sent = this.#sendAll(fd, hsFrame, 6 + hsLen);
5175
+ _Uint8ArrayFill(hsFrame, 0, 0, hsFrame.length);
5176
+ if (!sent) {
5177
+ symbols.close(fd);
5178
+ return false;
5179
+ }
5180
+ if (!this.#recvExact(fd, this.#hdrBuf, 6)) {
5181
+ symbols.close(fd);
5182
+ return false;
5183
+ }
5184
+ const magic = this.#hdrBuf[0];
5185
+ const msgType = this.#hdrBuf[1];
5186
+ const respLen = this.#hdrBuf.readUInt32BE(2);
5187
+ if (magic !== MAGIC_BYTE$1 || msgType !== MSG_HANDSHAKE_ACK$1) {
5188
+ symbols.close(fd);
5189
+ return false;
5190
+ }
5191
+ if (respLen > 0) {
5192
+ const ackBuf = respLen <= this.#rxBuf.length
5193
+ ? this.#rxBuf
5194
+ : Buffer.allocUnsafe(respLen);
5195
+ const ok = this.#recvExact(fd, ackBuf, respLen);
5196
+ _Uint8ArrayFill(ackBuf, 0, 0, respLen);
5197
+ if (!ok) {
5198
+ symbols.close(fd);
5199
+ return false;
5200
+ }
5201
+ }
5202
+ this.#fd = fd;
5203
+ return true;
5204
+ }
5205
+ callSync(module, action, args = [], opts = {}, timeoutMs = 5000) {
5206
+ const stringArgs = Array.isArray(args) ? args.map(String) : [];
5207
+ const jsonStr = _JSONStringify({
5208
+ id: 1,
5209
+ mod: module,
5210
+ action,
5211
+ args: stringArgs,
5212
+ opts: opts || {},
5213
+ });
5214
+ const reqLen = Buffer.byteLength(jsonStr, "utf8");
5215
+ const frameLen = 6 + reqLen;
5216
+ const tx = frameLen <= this.#txBuf.length
5217
+ ? this.#txBuf
5218
+ : Buffer.allocUnsafe(frameLen);
5219
+ tx.writeUInt8(MAGIC_BYTE$1, 0);
5220
+ tx.writeUInt8(MSG_CALL$1, 1);
5221
+ tx.writeUInt32BE(reqLen, 2);
5222
+ tx.write(jsonStr, 6, reqLen, "utf8");
5223
+ let rx = this.#rxBuf;
5224
+ let respLen = 0;
5225
+ try {
5226
+ // Up to 2 attempts: 1st reuses persistent socket; 2nd transparently reconnects if stale
5227
+ let msgType = 0;
5228
+ let ioSuccess = false;
5229
+ for (let attempt = 0; attempt < 2; attempt++) {
5230
+ if (this.#fd < 0) {
5231
+ if (!this.#connectAndHandshake(timeoutMs)) {
5232
+ throw new Error(`libSynapx: FFI socket connect failed [${module}.${action}]`);
5233
+ }
5234
+ }
5235
+ if (!this.#sendAll(this.#fd, tx, frameLen)) {
5236
+ this.close();
5237
+ continue;
5238
+ }
5239
+ if (!this.#recvExact(this.#fd, this.#hdrBuf, 6)) {
5240
+ this.close();
5241
+ continue;
5242
+ }
5243
+ if (this.#hdrBuf[0] !== MAGIC_BYTE$1) {
5244
+ this.close();
5245
+ continue;
5246
+ }
5247
+ msgType = this.#hdrBuf[1];
5248
+ respLen = this.#hdrBuf.readUInt32BE(2);
5249
+ if (respLen > rx.length) {
5250
+ rx = Buffer.allocUnsafe(respLen);
5251
+ }
5252
+ if (respLen > 0 && !this.#recvExact(this.#fd, rx, respLen)) {
5253
+ this.close();
5254
+ continue;
5255
+ }
5256
+ ioSuccess = true;
5257
+ break;
5258
+ }
5259
+ if (!ioSuccess) {
5260
+ throw new Error(`libSynapx: FFI synchronous RPC failed [${module}.${action}]`);
5261
+ }
5262
+ const parsed = _JSONParse(rx.toString("utf8", 0, respLen));
5263
+ if (msgType === MSG_ERROR$1 || !parsed.ok) {
5264
+ throw new Error(parsed.err ||
5265
+ `libSynapx [${module}.${action}] execution failed`);
5266
+ }
5267
+ return parsed.data;
5268
+ }
5269
+ finally {
5270
+ // XSA-SYNAPX-001: Scrub plaintext TX/RX buffers immediately
5271
+ _Uint8ArrayFill(tx, 0, 0, frameLen);
5272
+ if (respLen > 0) {
5273
+ _Uint8ArrayFill(rx, 0, 0, respLen);
5274
+ }
5275
+ }
5276
+ }
5277
+ close() {
5278
+ if (this.#fd >= 0) {
5279
+ try {
5280
+ this.#ffi.symbols.close(this.#fd);
5281
+ }
5282
+ catch { }
5283
+ this.#fd = -1;
5284
+ }
5285
+ }
5286
+ }
5287
+
4847
5288
  /* *****************************************************************************
4848
5289
  * Nehonix libSynapx — Synchronous Zero-Process-Spawn Shared Memory Bridge
4849
5290
  *
@@ -4857,6 +5298,7 @@ const IDX_STATUS = 0; // 0: IDLE, 1: PENDING, 2: READY, 3: ERROR
4857
5298
  const IDX_REQ_LEN = 1; // Request payload byte length
4858
5299
  const IDX_RESP_LEN = 2; // Response payload byte length
4859
5300
  const DATA_OFFSET = 64; // 64-byte aligned boundary for payload data
5301
+ const FRAME_OFFSET = DATA_OFFSET - 6; // 6-byte binary frame header directly preceding payload
4860
5302
  const STATUS_IDLE = 0;
4861
5303
  const STATUS_PENDING = 1;
4862
5304
  const STATUS_ERROR = 3;
@@ -4874,7 +5316,9 @@ const IDX_STATUS = 0;
4874
5316
  const IDX_REQ_LEN = 1;
4875
5317
  const IDX_RESP_LEN = 2;
4876
5318
  const DATA_OFFSET = 64;
5319
+ const FRAME_OFFSET = 58;
4877
5320
 
5321
+ const STATUS_PENDING = 1;
4878
5322
  const STATUS_READY = 2;
4879
5323
  const STATUS_ERROR = 3;
4880
5324
 
@@ -4884,17 +5328,21 @@ let rxBytesTotal = 0;
4884
5328
  let isHandshaked = false;
4885
5329
  let pendingDispatch = false;
4886
5330
 
5331
+ function wakeWithError(errMsg) {
5332
+ if (Atomics.load(int32, IDX_STATUS) !== STATUS_PENDING) return;
5333
+ const errBuf = Buffer.from(JSON.stringify({ id: 1, ok: false, err: errMsg }));
5334
+ uint8.set(errBuf, DATA_OFFSET);
5335
+ Atomics.store(int32, IDX_RESP_LEN, errBuf.length);
5336
+ Atomics.store(int32, IDX_STATUS, STATUS_ERROR);
5337
+ Atomics.notify(int32, IDX_STATUS, 1);
5338
+ }
5339
+
4887
5340
  function flushDispatch() {
4888
5341
  if (!socket || socket.destroyed || !isHandshaked) return;
4889
5342
  const reqLen = Atomics.load(int32, IDX_REQ_LEN);
4890
- const reqBytes = uint8.subarray(DATA_OFFSET, DATA_OFFSET + reqLen);
4891
-
4892
- const h = Buffer.alloc(6);
4893
- h.writeUInt8(0x53, 0);
4894
- h.writeUInt8(0x03, 1); // MSG_CALL
4895
- h.writeUInt32BE(reqBytes.length, 2);
4896
-
4897
- socket.write(Buffer.concat([h, reqBytes]));
5343
+ // Zero-copy write: 6-byte header was written at FRAME_OFFSET (58..63) by main thread
5344
+ const frameSlice = uint8.subarray(FRAME_OFFSET, DATA_OFFSET + reqLen);
5345
+ socket.write(frameSlice);
4898
5346
  }
4899
5347
 
4900
5348
  function pushChunk(chunk) {
@@ -4947,20 +5395,37 @@ function consumeBytes(numBytes) {
4947
5395
  }
4948
5396
 
4949
5397
  function connectSocket() {
5398
+ rxChunks = [];
5399
+ rxBytesTotal = 0;
4950
5400
  socket = net.createConnection(socketPath, () => {
5401
+ try { socket.setNoDelay(true); } catch {}
4951
5402
  const hsPayload = Buffer.from(JSON.stringify({
4952
5403
  sessionHash: sessionHash || "",
4953
5404
  token: authToken || "",
4954
5405
  clientPid: process.pid,
4955
5406
  }));
4956
- const h = Buffer.alloc(6);
4957
- h.writeUInt8(0x53, 0); // 'S'
4958
- h.writeUInt8(0x01, 1); // MSG_HANDSHAKE
4959
- h.writeUInt32BE(hsPayload.length, 2);
4960
- socket.write(Buffer.concat([h, hsPayload]));
5407
+ const frame = Buffer.allocUnsafe(6 + hsPayload.length);
5408
+ frame.writeUInt8(0x53, 0); // 'S'
5409
+ frame.writeUInt8(0x01, 1); // MSG_HANDSHAKE
5410
+ frame.writeUInt32BE(hsPayload.length, 2);
5411
+ hsPayload.copy(frame, 6);
5412
+ socket.write(frame);
4961
5413
  });
4962
5414
 
4963
5415
  socket.on("data", (chunk) => {
5416
+ // Fast path: complete single-frame response on hot path (0 allocations)
5417
+ if (rxBytesTotal === 0 && isHandshaked && chunk.length >= 6 && chunk[0] === 0x53) {
5418
+ const type = chunk[1];
5419
+ const len = ((chunk[2] << 24) | (chunk[3] << 16) | (chunk[4] << 8) | chunk[5]) >>> 0;
5420
+ if (chunk.length === 6 + len && (type === 0x04 || type === 0xff)) {
5421
+ uint8.set(chunk.subarray(6, 6 + len), DATA_OFFSET);
5422
+ Atomics.store(int32, IDX_RESP_LEN, len);
5423
+ Atomics.store(int32, IDX_STATUS, type === 0x04 ? STATUS_READY : STATUS_ERROR);
5424
+ Atomics.notify(int32, IDX_STATUS, 1);
5425
+ return;
5426
+ }
5427
+ }
5428
+
4964
5429
  pushChunk(chunk);
4965
5430
  while (true) {
4966
5431
  const header = peekHeader();
@@ -5004,10 +5469,12 @@ function connectSocket() {
5004
5469
  if (!isHandshaked) {
5005
5470
  parentPort.postMessage({ type: "ERROR", err: err.message });
5006
5471
  }
5472
+ wakeWithError("libSynapx socket error: " + err.message);
5007
5473
  });
5008
5474
 
5009
5475
  socket.on("close", () => {
5010
5476
  isHandshaked = false;
5477
+ wakeWithError("libSynapx socket closed unexpectedly");
5011
5478
  });
5012
5479
  }
5013
5480
 
@@ -5042,14 +5509,30 @@ class SynapxSyncBridge {
5042
5509
  #socketPath;
5043
5510
  #sessionHash;
5044
5511
  #authToken;
5512
+ #sabSize;
5513
+ #sabBuf;
5514
+ #sabAllocated = false;
5515
+ #nativeTransport = null;
5045
5516
  constructor(socketPath, sessionHash, authToken, sabSize = DEFAULT_SAB_SIZE) {
5046
5517
  this.#socketPath = socketPath;
5047
5518
  this.#sessionHash = sessionHash;
5048
5519
  this.#authToken = authToken;
5049
- this.sab = new SharedArrayBuffer(sabSize);
5520
+ this.#sabSize = sabSize;
5521
+ // Fast-path: direct synchronous POSIX Unix socket via bun:ffi (no Worker, no postMessage, no 128MB SAB)
5522
+ this.#nativeTransport = NativeUnixSyncTransport.tryCreate(socketPath, sessionHash, authToken);
5523
+ if (!this.#nativeTransport) {
5524
+ this.#ensureSabAllocated();
5525
+ }
5526
+ }
5527
+ #ensureSabAllocated() {
5528
+ if (this.#sabAllocated)
5529
+ return;
5530
+ this.sab = new SharedArrayBuffer(this.#sabSize);
5050
5531
  this.int32 = new Int32Array(this.sab);
5051
5532
  this.uint8 = new Uint8Array(this.sab);
5533
+ this.#sabBuf = Buffer.from(this.sab);
5052
5534
  Atomics.store(this.int32, IDX_STATUS, STATUS_IDLE);
5535
+ this.#sabAllocated = true;
5053
5536
  }
5054
5537
  static getInstance(socketPath, sessionHash, authToken) {
5055
5538
  if (!SynapxSyncBridge.instance) {
@@ -5058,6 +5541,10 @@ class SynapxSyncBridge {
5058
5541
  return SynapxSyncBridge.instance;
5059
5542
  }
5060
5543
  init() {
5544
+ if (this.#nativeTransport) {
5545
+ return Promise.resolve();
5546
+ }
5547
+ this.#ensureSabAllocated();
5061
5548
  if (this.#isReady && this.#worker) {
5062
5549
  return Promise.resolve();
5063
5550
  }
@@ -5085,7 +5572,8 @@ class SynapxSyncBridge {
5085
5572
  resolve();
5086
5573
  }
5087
5574
  else if (msg.type === "ERROR") {
5088
- reject(new Error(msg.err || "Failed to initialize libSynapx sync worker"));
5575
+ reject(new Error(msg.err ||
5576
+ "Failed to initialize libSynapx sync worker"));
5089
5577
  }
5090
5578
  });
5091
5579
  this.#worker.on("error", (err) => {
@@ -5118,11 +5606,27 @@ class SynapxSyncBridge {
5118
5606
  if (callerInfo.isUntrusted || !isImmediateInternalEngineCall()) {
5119
5607
  throw new Error("libSynapx: Unauthorized caller for bridge");
5120
5608
  }
5609
+ // Fast-path: native POSIX synchronous Unix socket (bun:ffi)
5610
+ if (this.#nativeTransport) {
5611
+ try {
5612
+ return this.#nativeTransport.callSync(module, action, args, opts, timeoutMs);
5613
+ }
5614
+ catch (err) {
5615
+ const msg = String(err?.message || "");
5616
+ // Propagate genuine daemon application/security errors directly; only fallback on transport failure
5617
+ if (!msg.includes("FFI socket connect failed") &&
5618
+ !msg.includes("FFI synchronous RPC failed")) {
5619
+ throw err;
5620
+ }
5621
+ // Disable broken native transport and fall back cleanly to Worker SAB bridge
5622
+ this.#nativeTransport.close();
5623
+ this.#nativeTransport = null;
5624
+ }
5625
+ }
5626
+ this.#ensureSabAllocated();
5121
5627
  if (!this.#isReady || !this.#worker) {
5122
5628
  // Lazy synchronous initialization if called before explicit init()
5123
5629
  try {
5124
- const sab = this.sab;
5125
- // Wait for worker startup if in-flight
5126
5630
  this.init();
5127
5631
  }
5128
5632
  catch { }
@@ -5135,13 +5639,18 @@ class SynapxSyncBridge {
5135
5639
  args: stringArgs,
5136
5640
  opts: opts || {},
5137
5641
  };
5138
- const serialized = Buffer.from(_JSONStringify(payloadObj));
5139
- if (DATA_OFFSET + serialized.length > this.sab.byteLength) {
5642
+ const jsonStr = _JSONStringify(payloadObj);
5643
+ const maxPayloadLen = this.sab.byteLength - DATA_OFFSET;
5644
+ const reqLen = Buffer.byteLength(jsonStr, "utf8");
5645
+ if (reqLen > maxPayloadLen) {
5140
5646
  throw new Error(`libSynapx: Payload exceeds SharedArrayBuffer capacity (${this.sab.byteLength} bytes)`);
5141
5647
  }
5142
- // 1. Copy serialized payload into shared memory data segment
5143
- this.uint8.set(serialized, DATA_OFFSET);
5144
- Atomics.store(this.int32, IDX_REQ_LEN, serialized.length);
5648
+ // 1. Zero-copy write: 6-byte binary header at FRAME_OFFSET + UTF-8 payload at DATA_OFFSET
5649
+ this.#sabBuf.writeUInt8(0x53, FRAME_OFFSET);
5650
+ this.#sabBuf.writeUInt8(0x03, FRAME_OFFSET + 1); // MSG_CALL
5651
+ this.#sabBuf.writeUInt32BE(reqLen, FRAME_OFFSET + 2);
5652
+ this.#sabBuf.write(jsonStr, DATA_OFFSET, reqLen, "utf8");
5653
+ Atomics.store(this.int32, IDX_REQ_LEN, reqLen);
5145
5654
  Atomics.store(this.int32, IDX_STATUS, STATUS_PENDING);
5146
5655
  // 2. Dispatch event to background worker thread
5147
5656
  this.#worker?.postMessage({ type: "DISPATCH" });
@@ -5149,17 +5658,17 @@ class SynapxSyncBridge {
5149
5658
  const waitStatus = Atomics.wait(this.int32, IDX_STATUS, STATUS_PENDING, timeoutMs);
5150
5659
  if (waitStatus === "timed-out") {
5151
5660
  Atomics.store(this.int32, IDX_STATUS, STATUS_IDLE);
5661
+ _Uint8ArrayFill(this.uint8, 0, FRAME_OFFSET, DATA_OFFSET + reqLen);
5152
5662
  throw new Error(`libSynapx: callSync timed out after ${timeoutMs}ms [${module}.${action}]`);
5153
5663
  }
5154
- // 4. Thread awoken by kernel! Read response directly from shared memory
5664
+ // 4. Thread awoken by kernel! Read response directly from shared memory (zero-copy)
5155
5665
  const status = Atomics.load(this.int32, IDX_STATUS);
5156
5666
  const respLen = Atomics.load(this.int32, IDX_RESP_LEN);
5157
- const respBytes = this.uint8.subarray(DATA_OFFSET, DATA_OFFSET + respLen);
5158
- const totalUsedLen = Math.max(serialized.length, respLen);
5667
+ const totalUsedLen = Math.max(reqLen, respLen);
5159
5668
  Atomics.store(this.int32, IDX_STATUS, STATUS_IDLE);
5160
5669
  let parsed;
5161
5670
  try {
5162
- parsed = _JSONParse(Buffer.from(respBytes).toString("utf8"));
5671
+ parsed = _JSONParse(this.#sabBuf.toString("utf8", DATA_OFFSET, DATA_OFFSET + respLen));
5163
5672
  }
5164
5673
  catch (e) {
5165
5674
  throw new Error(`libSynapx: Failed to decode response JSON: ${e.message}`);
@@ -5168,21 +5677,26 @@ class SynapxSyncBridge {
5168
5677
  /**
5169
5678
  * Ref: XSA-SYNAPX-001 (SharedArrayBuffer Memory Scrubbing)
5170
5679
  * Overwrite shared memory with zeros immediately following response consumption.
5171
- * Prevents plaintext credential retention across the 128 MB SharedArrayBuffer lifecycle.
5680
+ * Prevents plaintext credential retention across the SharedArrayBuffer lifecycle.
5172
5681
  *
5173
5682
  * @see XSA-XESS-021 - Uses frozen _Uint8ArrayFill primordial to prevent interception
5174
5683
  */
5175
- _Uint8ArrayFill(this.uint8, 0, DATA_OFFSET, DATA_OFFSET + totalUsedLen);
5684
+ _Uint8ArrayFill(this.uint8, 0, FRAME_OFFSET, DATA_OFFSET + totalUsedLen);
5176
5685
  Atomics.store(this.int32, IDX_REQ_LEN, 0);
5177
5686
  Atomics.store(this.int32, IDX_RESP_LEN, 0);
5178
5687
  }
5179
5688
  if (status === STATUS_ERROR || !parsed.ok) {
5180
- throw new Error(parsed.err || `libSynapx [${module}.${action}] execution failed`);
5689
+ throw new Error(parsed.err ||
5690
+ `libSynapx [${module}.${action}] execution failed`);
5181
5691
  }
5182
5692
  return parsed.data;
5183
5693
  }
5184
5694
  destroy() {
5185
5695
  this.#isReady = false;
5696
+ if (this.#nativeTransport) {
5697
+ this.#nativeTransport.close();
5698
+ this.#nativeTransport = null;
5699
+ }
5186
5700
  if (this.#worker) {
5187
5701
  this.#worker.terminate();
5188
5702
  this.#worker = null;
@@ -5427,8 +5941,8 @@ class SynapxClient {
5427
5941
  childExited = true;
5428
5942
  });
5429
5943
  child.unref();
5430
- // Wait for socket to appear (up to 3500ms on Windows, 1500ms on POSIX)
5431
- const maxWait = process.platform === "win32" ? 3500 : 1500;
5944
+ // Wait for socket to appear (accounts for UPX cold-start decompression)
5945
+ const maxWait = process.platform === "win32" ? 6000 : 5000;
5432
5946
  const start = Date.now();
5433
5947
  while (Date.now() - start < maxWait) {
5434
5948
  if (this.isAvailable() || childExited) {
@@ -5701,19 +6215,29 @@ class SynapxClient {
5701
6215
  throw new Error(`libSynapx: Unauthorized caller for restricted module '${module}'`);
5702
6216
  }
5703
6217
  }
5704
- if (!this.socketPath || !this.isAvailable()) {
5705
- this.ensureDaemon();
6218
+ if (!this.#syncBridge) {
5706
6219
  if (!this.socketPath || !this.isAvailable()) {
5707
- throw new Error(`libSynapx: socket '${this.socketPath || "unknown"}' not found or active daemon is offline`);
6220
+ this.ensureDaemon();
6221
+ if (!this.socketPath || !this.isAvailable()) {
6222
+ throw new Error(`libSynapx: socket '${this.socketPath || "unknown"}' not found or active daemon is offline`);
6223
+ }
5708
6224
  }
6225
+ this.#syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.#authToken);
5709
6226
  }
5710
6227
  try {
5711
- if (!this.#syncBridge) {
5712
- this.#syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.#authToken);
5713
- }
5714
6228
  return this.#syncBridge.callSync(module, action, args, opts);
5715
6229
  }
5716
- catch {
6230
+ catch (err) {
6231
+ const msg = String(err?.message || "");
6232
+ // Only fallback to subprocess on genuine transport failures, not daemon authorization/logic errors
6233
+ if (msg.includes("UNAUTHORIZED") ||
6234
+ msg.includes("INVALID_SEAL") ||
6235
+ msg.includes("Unauthorized caller")) {
6236
+ throw err;
6237
+ }
6238
+ if (!this.isAvailable()) {
6239
+ this.ensureDaemon();
6240
+ }
5717
6241
  // Resilient fallback to stdin subprocess pipeline
5718
6242
  return this.callSyncSubprocess(module, action, args, opts);
5719
6243
  }
@@ -6221,12 +6745,23 @@ function getInstanceId() {
6221
6745
  */
6222
6746
  class BaseApi {
6223
6747
  #runner;
6748
+ #assignedRoot;
6224
6749
  /**
6225
6750
  * Initializes the Base API with a shared runner instance.
6226
6751
  * @param runner - The XyPrissRunner used to invoke native XHSC binaries.
6227
6752
  */
6228
6753
  constructor(runner) {
6229
6754
  this.#runner = runner;
6755
+ this.#assignedRoot =
6756
+ runner && typeof runner.getRoot === "function"
6757
+ ? runner.getRoot()
6758
+ : "";
6759
+ }
6760
+ /**
6761
+ * Statically assigned sandbox root configured at instantiation.
6762
+ */
6763
+ get assignedRoot() {
6764
+ return this.#assignedRoot;
6230
6765
  }
6231
6766
  /**
6232
6767
  * Protected accessor for internal engine classes only.
@@ -6256,6 +6791,21 @@ class BaseApi {
6256
6791
  * @extends BaseApi
6257
6792
  */
6258
6793
  class PathApi extends BaseApi {
6794
+ /**
6795
+ * Active project/sandbox root for this path context.
6796
+ * Never falls back to host `process.cwd()` to prevent host sandbox escape.
6797
+ */
6798
+ get __root__() {
6799
+ const callerRoot = getCallerProjectRoot();
6800
+ if (callerRoot)
6801
+ return callerRoot;
6802
+ if (this.assignedRoot)
6803
+ return this.assignedRoot;
6804
+ const runnerRoot = this.runner ? this.runner.getRoot() : "";
6805
+ if (runnerRoot)
6806
+ return runnerRoot;
6807
+ return "";
6808
+ }
6259
6809
  /**
6260
6810
  * **Resolve to Absolute Path**
6261
6811
  *
@@ -6281,12 +6831,18 @@ class PathApi extends BaseApi {
6281
6831
  * // Output: "/home/user/project" (Back to root)
6282
6832
  */
6283
6833
  resolve = (...paths) => {
6284
- try {
6285
- return this.runner.runSync("path", "resolve", paths);
6834
+ const baseRoot = this.__root__;
6835
+ if (paths.length === 0) {
6836
+ return baseRoot || "/";
6286
6837
  }
6287
- catch {
6838
+ if (path.isAbsolute(paths[0])) {
6288
6839
  return path.resolve(...paths);
6289
6840
  }
6841
+ if (baseRoot) {
6842
+ return path.resolve(baseRoot, ...paths);
6843
+ }
6844
+ // Strict sandbox confinement: Never fall back to process.cwd() host path
6845
+ return path.resolve("/", ...paths);
6290
6846
  };
6291
6847
  join = (...paths) => {
6292
6848
  try {
@@ -6344,7 +6900,7 @@ class PathApi extends BaseApi {
6344
6900
  ]);
6345
6901
  }
6346
6902
  catch {
6347
- const rel = path.relative(path.resolve(parent), path.resolve(child));
6903
+ const rel = path.relative(this.resolve(parent), this.resolve(child));
6348
6904
  return !rel.startsWith("..") && !path.isAbsolute(rel);
6349
6905
  }
6350
6906
  };
@@ -6356,7 +6912,7 @@ class PathApi extends BaseApi {
6356
6912
  ]);
6357
6913
  }
6358
6914
  catch {
6359
- const resolvedBase = path.resolve(base);
6915
+ const resolvedBase = this.resolve(base);
6360
6916
  const target = path.resolve(resolvedBase, ...segments);
6361
6917
  if (!this.isChild(resolvedBase, target) && resolvedBase !== target) {
6362
6918
  throw new Error(`Path traversal attempt detected: ${target} escapes ${resolvedBase}`);
@@ -6412,8 +6968,8 @@ class PathApi extends BaseApi {
6412
6968
  if (paths.length === 0)
6413
6969
  return "";
6414
6970
  if (paths.length === 1)
6415
- return path.dirname(path.resolve(paths[0]));
6416
- const splitPaths = paths.map((p) => path.resolve(p).split(path.sep));
6971
+ return path.dirname(this.resolve(paths[0]));
6972
+ const splitPaths = paths.map((p) => this.resolve(p).split(path.sep));
6417
6973
  const minLen = Math.min(...splitPaths.map((p) => p.length));
6418
6974
  let common = [];
6419
6975
  for (let i = 0; i < minLen; i++) {
@@ -6527,7 +7083,8 @@ class PathApi extends BaseApi {
6527
7083
  */
6528
7084
  exist = (p) => {
6529
7085
  try {
6530
- const res = this.runner.runSync("fs", "check", [p]);
7086
+ const resolvedPath = this.resolve(p);
7087
+ const res = this.runner.runSync("fs", "check", [resolvedPath]);
6531
7088
  return res?.exists === true;
6532
7089
  }
6533
7090
  catch {
@@ -6545,7 +7102,8 @@ class PathApi extends BaseApi {
6545
7102
  */
6546
7103
  isDir = (p) => {
6547
7104
  try {
6548
- const res = this.runner.runSync("fs", "stats", [p]);
7105
+ const resolvedPath = this.resolve(p);
7106
+ const res = this.runner.runSync("fs", "stats", [resolvedPath]);
6549
7107
  return res?.is_dir === true;
6550
7108
  }
6551
7109
  catch {
@@ -6557,7 +7115,8 @@ class PathApi extends BaseApi {
6557
7115
  */
6558
7116
  isFile = (p) => {
6559
7117
  try {
6560
- const res = this.runner.runSync("fs", "stats", [p]);
7118
+ const resolvedPath = this.resolve(p);
7119
+ const res = this.runner.runSync("fs", "stats", [resolvedPath]);
6561
7120
  return res?.is_file === true;
6562
7121
  }
6563
7122
  catch {
@@ -6569,7 +7128,8 @@ class PathApi extends BaseApi {
6569
7128
  */
6570
7129
  isSymlink = (p) => {
6571
7130
  try {
6572
- const res = this.runner.runSync("fs", "stats", [p]);
7131
+ const resolvedPath = this.resolve(p);
7132
+ const res = this.runner.runSync("fs", "stats", [resolvedPath]);
6573
7133
  return res?.is_symlink === true;
6574
7134
  }
6575
7135
  catch {
@@ -6581,12 +7141,13 @@ class PathApi extends BaseApi {
6581
7141
  */
6582
7142
  isEmpty = (p) => {
6583
7143
  try {
6584
- if (this.isFile(p)) {
6585
- const res = this.runner.runSync("fs", "size", [p]);
7144
+ const resolvedPath = this.resolve(p);
7145
+ if (this.isFile(resolvedPath)) {
7146
+ const res = this.runner.runSync("fs", "size", [resolvedPath]);
6586
7147
  return res?.bytes === 0;
6587
7148
  }
6588
- if (this.isDir(p)) {
6589
- const res = this.runner.runSync("fs", "ls", [p]);
7149
+ if (this.isDir(resolvedPath)) {
7150
+ const res = this.runner.runSync("fs", "ls", [resolvedPath]);
6590
7151
  return res?.length === 0;
6591
7152
  }
6592
7153
  return false;
@@ -6740,11 +7301,16 @@ class OSApi extends BaseApi {
6740
7301
  * @returns {ProcessMonitorSnapshot[] | void} Captured snapshots.
6741
7302
  */
6742
7303
  monitorProcess = (pid, duration = 60) => {
6743
- return this.runner.runSync("monitor", "process", [], {
6744
- pid,
6745
- duration,
6746
- interactive: true,
6747
- });
7304
+ try {
7305
+ return this.runner.runSync("monitor", "process", [], {
7306
+ pid,
7307
+ duration,
7308
+ interactive: true,
7309
+ });
7310
+ }
7311
+ catch (err) {
7312
+ throw err;
7313
+ }
6748
7314
  };
6749
7315
  /**
6750
7316
  * **Terminate Process**
@@ -6817,7 +7383,7 @@ class OSApi extends BaseApi {
6817
7383
  * **Base Filesystem API**
6818
7384
  *
6819
7385
  * Provides the foundation for all filesystem operations, including
6820
- * logger initialization and runner access.
7386
+ * logger initialization, runner access, and strict sandbox enforcement.
6821
7387
  */
6822
7388
  class FSBase extends PathApi {
6823
7389
  logger;
@@ -6825,6 +7391,67 @@ class FSBase extends PathApi {
6825
7391
  super(runner);
6826
7392
  this.logger = new Logger();
6827
7393
  }
7394
+ /**
7395
+ * Resolves and verifies that a target path resides strictly within the authorized sandbox.
7396
+ * Denies access and logs a security violation if the path attempts to escape outside the sandbox boundary.
7397
+ *
7398
+ * @param targetPath The raw requested path (relative or absolute)
7399
+ * @param operation The filesystem operation being attempted
7400
+ * @returns The resolved canonical path within the sandbox, or null if access is denied
7401
+ */
7402
+ resolvePathInSandbox(targetPath, operation = "fs") {
7403
+ if (!targetPath || typeof targetPath !== "string") {
7404
+ return null;
7405
+ }
7406
+ const runnerRoot = this.runner ? this.runner.getRoot() : "";
7407
+ const baseRoot = runnerRoot || this.assignedRoot;
7408
+ const caller = getVerifiedCallerInfo();
7409
+ // If the verified application caller is genuine engine core, allow direct access
7410
+ if (caller.callerFile && isEngineCorePath(caller.callerFile)) {
7411
+ if (path.isAbsolute(targetPath)) {
7412
+ return path.resolve(targetPath);
7413
+ }
7414
+ return baseRoot ? path.resolve(baseRoot, targetPath) : null;
7415
+ }
7416
+ // If there are no external application frames in the call stack, this is engine bootstrap
7417
+ if (!caller.callerFile && isImmediateInternalEngineCall()) {
7418
+ if (path.isAbsolute(targetPath)) {
7419
+ return path.resolve(targetPath);
7420
+ }
7421
+ return baseRoot ? path.resolve(baseRoot, targetPath) : null;
7422
+ }
7423
+ const callerRoot = caller.root || getCallerProjectRoot() || baseRoot;
7424
+ const effectiveSandbox = callerRoot || baseRoot;
7425
+ if (!effectiveSandbox) {
7426
+ console.error(`\x1b[31m[XyPriss Security] Sandbox Violation: No valid sandbox root resolved for caller during '${operation}' on '${targetPath}'. Access denied.\x1b[0m`);
7427
+ return null;
7428
+ }
7429
+ let normSandbox = _PathPosixNormalize(_StringReplace(effectiveSandbox, /\\/g, "/"));
7430
+ while (normSandbox.length > 1 && normSandbox.endsWith("/")) {
7431
+ normSandbox = normSandbox.slice(0, -1);
7432
+ }
7433
+ const resolved = path.isAbsolute(targetPath)
7434
+ ? path.resolve(targetPath)
7435
+ : path.resolve(normSandbox, targetPath);
7436
+ const normResolved = _PathPosixNormalize(_StringReplace(resolved, /\\/g, "/"));
7437
+ // Allow temporary files inside the session user temp directory
7438
+ const userTmp = generateXUserTmpDir();
7439
+ const normUserTmp = userTmp
7440
+ ? _PathPosixNormalize(_StringReplace(userTmp, /\\/g, "/"))
7441
+ : "";
7442
+ if (normUserTmp &&
7443
+ (normResolved === normUserTmp ||
7444
+ normResolved.startsWith(normUserTmp + "/"))) {
7445
+ return resolved;
7446
+ }
7447
+ // Check if resolved path is strictly within the effective sandbox
7448
+ if (normResolved === normSandbox ||
7449
+ normResolved.startsWith(normSandbox + "/")) {
7450
+ return resolved;
7451
+ }
7452
+ console.error(`\x1b[31m[XyPriss Security] Sandbox Violation: Access denied during '${operation}'. Path '${targetPath}' is outside the assigned sandbox root '${normSandbox}'.\x1b[0m`);
7453
+ return null;
7454
+ }
6828
7455
  }
6829
7456
 
6830
7457
  /* *****************************************************************************
@@ -7355,11 +7982,19 @@ class TempFileManager {
7355
7982
  */
7356
7983
  class FSCore extends FSBase {
7357
7984
  ls(p, options = {}) {
7358
- return this.runner.runSync("fs", "ls", [
7359
- p,
7360
- String(Boolean(options.recursive)),
7361
- String(Boolean(options.stats)),
7362
- ], options);
7985
+ const safePath = this.resolvePathInSandbox(p, "ls");
7986
+ if (!safePath)
7987
+ return [];
7988
+ try {
7989
+ return this.runner.runSync("fs", "ls", [
7990
+ safePath,
7991
+ String(Boolean(options.recursive)),
7992
+ String(Boolean(options.stats)),
7993
+ ], options);
7994
+ }
7995
+ catch (err) {
7996
+ throw err;
7997
+ }
7363
7998
  }
7364
7999
  /**
7365
8000
  * **Read File Content (Asynchronous)**
@@ -7377,8 +8012,19 @@ class FSCore extends FSBase {
7377
8012
  * console.log(content);
7378
8013
  */
7379
8014
  read = async (p, options = {}) => {
7380
- const res = (await this.runner.runAsync("fs", "read", [p, String(Boolean(options.bytes))], options));
7381
- return res?.data !== undefined ? res.data : res;
8015
+ const safePath = this.resolvePathInSandbox(p, "read");
8016
+ if (!safePath)
8017
+ return "";
8018
+ try {
8019
+ const res = (await this.runner.runAsync("fs", "read", [safePath, String(Boolean(options.bytes))], options));
8020
+ return res?.data !== undefined ? res.data : res;
8021
+ }
8022
+ catch (err) {
8023
+ if (err?.message?.includes("Access denied: untrusted caller")) {
8024
+ return "";
8025
+ }
8026
+ throw err;
8027
+ }
7382
8028
  };
7383
8029
  /**
7384
8030
  * **Read File Content (Synchronous)**
@@ -7395,8 +8041,11 @@ class FSCore extends FSBase {
7395
8041
  * const content = __sys__.fs.readSync("/etc/hosts");
7396
8042
  */
7397
8043
  readSync = (p, options = {}) => {
8044
+ const safePath = this.resolvePathInSandbox(p, "readSync");
8045
+ if (!safePath)
8046
+ return "";
7398
8047
  try {
7399
- const res = this.runner.runSync("fs", "read", [p, String(Boolean(options.bytes))], options);
8048
+ const res = this.runner.runSync("fs", "read", [safePath, String(Boolean(options.bytes))], options);
7400
8049
  return res?.data !== undefined ? res.data : res;
7401
8050
  }
7402
8051
  catch (err) {
@@ -7467,9 +8116,12 @@ class FSCore extends FSBase {
7467
8116
  * await __sys__.fs.writeFile("log.txt", "Event happened\n", { append: true });
7468
8117
  */
7469
8118
  writeFile = async (p, data, options = {}) => {
8119
+ const safePath = this.resolvePathInSandbox(p, "writeFile");
8120
+ if (!safePath)
8121
+ return;
7470
8122
  const { ensureFile = true } = options;
7471
8123
  if (ensureFile) {
7472
- const dir = this.dirname(p);
8124
+ const dir = this.dirname(safePath);
7473
8125
  if (dir && dir !== "." && !this.exist(dir)) {
7474
8126
  this.mkdir(dir, { parents: true });
7475
8127
  }
@@ -7480,7 +8132,7 @@ class FSCore extends FSBase {
7480
8132
  ? data.toString("hex")
7481
8133
  : Buffer.from(data).toString("hex");
7482
8134
  await this.runner.runAsync("fs", "write-bytes", [
7483
- p,
8135
+ safePath,
7484
8136
  hexData,
7485
8137
  String(Boolean(options.append)),
7486
8138
  ]);
@@ -7493,7 +8145,7 @@ class FSCore extends FSBase {
7493
8145
  else {
7494
8146
  writeData = String(data);
7495
8147
  }
7496
- await this.runner.runAsync("fs", "write", [p, writeData, String(Boolean(options.append))], {
8148
+ await this.runner.runAsync("fs", "write", [safePath, writeData, String(Boolean(options.append))], {
7497
8149
  ...options,
7498
8150
  input: writeData,
7499
8151
  });
@@ -7511,9 +8163,12 @@ class FSCore extends FSBase {
7511
8163
  * @param {boolean} [options.ensureFile=true] - If true, creates parent directories if they don't exist.
7512
8164
  */
7513
8165
  writeFileSync = (p, data, options = {}) => {
8166
+ const safePath = this.resolvePathInSandbox(p, "writeFileSync");
8167
+ if (!safePath)
8168
+ return;
7514
8169
  const { ensureFile = true } = options;
7515
8170
  if (ensureFile) {
7516
- const dir = this.dirname(p);
8171
+ const dir = this.dirname(safePath);
7517
8172
  if (dir && dir !== "." && !this.exist(dir)) {
7518
8173
  this.mkdir(dir, { parents: true });
7519
8174
  }
@@ -7575,7 +8230,12 @@ class FSCore extends FSBase {
7575
8230
  * @example
7576
8231
  * __sys__.fs.rm("./tmp/cache", { force: true });
7577
8232
  */
7578
- rm = (p, options = {}) => this.runner.runSync("fs", "rm", [p, String(Boolean(options.force))], options);
8233
+ rm = (p, options = {}) => {
8234
+ const safePath = this.resolvePathInSandbox(p, "rm");
8235
+ if (!safePath)
8236
+ return;
8237
+ this.runner.runSync("fs", "rm", [safePath, String(Boolean(options.force))], options);
8238
+ };
7579
8239
  /**
7580
8240
  * **Remove Multiple Files or Directories**
7581
8241
  *
@@ -7596,7 +8256,10 @@ class FSCore extends FSBase {
7596
8256
  */
7597
8257
  rmMany = (paths, options = {}) => {
7598
8258
  for (const p of paths) {
7599
- this.runner.runSync("fs", "rm", [p, String(Boolean(options.force))], options);
8259
+ const safePath = this.resolvePathInSandbox(p, "rmMany");
8260
+ if (!safePath)
8261
+ continue;
8262
+ this.runner.runSync("fs", "rm", [safePath, String(Boolean(options.force))], options);
7600
8263
  }
7601
8264
  };
7602
8265
  /**
@@ -7611,7 +8274,12 @@ class FSCore extends FSBase {
7611
8274
  * @example
7612
8275
  * __sys__.fs.mkdir("/path/to/new-dir", { parents: true });
7613
8276
  */
7614
- mkdir = (p, options = {}) => this.runner.runSync("fs", "mkdir", [p, String(Boolean(options.parents))], options);
8277
+ mkdir = (p, options = {}) => {
8278
+ const safePath = this.resolvePathInSandbox(p, "mkdir");
8279
+ if (!safePath)
8280
+ return;
8281
+ this.runner.runSync("fs", "mkdir", [safePath, String(Boolean(options.parents))], options);
8282
+ };
7615
8283
  /**
7616
8284
  * **Touch File**
7617
8285
  *
@@ -8121,7 +8789,18 @@ class FSHelpers extends FSCore {
8121
8789
  * @example
8122
8790
  * const config = __sys__.fs.readJsonSync("package.json");
8123
8791
  */
8124
- readJsonSync = (p) => JSON.parse(this.readSync(p));
8792
+ readJsonSync = (p) => {
8793
+ const raw = this.readSync(p);
8794
+ if (!raw || typeof raw !== "string" || raw.trim() === "") {
8795
+ return {};
8796
+ }
8797
+ try {
8798
+ return JSON.parse(raw);
8799
+ }
8800
+ catch {
8801
+ return {};
8802
+ }
8803
+ };
8125
8804
  /**
8126
8805
  * **Read File as Binary (Asynchronous)**
8127
8806
  *
@@ -8131,7 +8810,10 @@ class FSHelpers extends FSCore {
8131
8810
  * @returns {Promise<Buffer>} Binary data.
8132
8811
  */
8133
8812
  readBytes = async (p) => {
8134
- const res = (await this.runner.runAsync("fs", "read-bytes", [p]));
8813
+ const safePath = this.resolvePathInSandbox(p, "readBytes");
8814
+ if (!safePath)
8815
+ return Buffer.alloc(0);
8816
+ const res = (await this.runner.runAsync("fs", "read-bytes", [safePath]));
8135
8817
  const hexData = res?.data !== undefined ? res.data : res;
8136
8818
  if (Buffer.isBuffer(hexData))
8137
8819
  return hexData;
@@ -8149,7 +8831,10 @@ class FSHelpers extends FSCore {
8149
8831
  * @returns {Buffer} Binary data.
8150
8832
  */
8151
8833
  readBytesSync = (p) => {
8152
- const res = this.runner.runSync("fs", "read-bytes", [p]);
8834
+ const safePath = this.resolvePathInSandbox(p, "readBytesSync");
8835
+ if (!safePath)
8836
+ return Buffer.alloc(0);
8837
+ const res = this.runner.runSync("fs", "read-bytes", [safePath]);
8153
8838
  const hexData = res?.data !== undefined ? res.data : res;
8154
8839
  if (Buffer.isBuffer(hexData))
8155
8840
  return hexData;
@@ -8168,10 +8853,13 @@ class FSHelpers extends FSCore {
8168
8853
  * @returns {Promise<void>}
8169
8854
  */
8170
8855
  writeBytes = async (p, data) => {
8856
+ const safePath = this.resolvePathInSandbox(p, "writeBytes");
8857
+ if (!safePath)
8858
+ return;
8171
8859
  const hexData = Buffer.isBuffer(data)
8172
8860
  ? data.toString("hex")
8173
8861
  : Buffer.from(data).toString("hex");
8174
- await this.runner.runAsync("fs", "write-bytes", [p, hexData]);
8862
+ await this.runner.runAsync("fs", "write-bytes", [safePath, hexData]);
8175
8863
  };
8176
8864
  /**
8177
8865
  * **Write Binary Data (Synchronous)**
@@ -8182,10 +8870,13 @@ class FSHelpers extends FSCore {
8182
8870
  * @param {Buffer} data - Binary data to write.
8183
8871
  */
8184
8872
  writeBytesSync = (p, data) => {
8873
+ const safePath = this.resolvePathInSandbox(p, "writeBytesSync");
8874
+ if (!safePath)
8875
+ return;
8185
8876
  const hexData = Buffer.isBuffer(data)
8186
8877
  ? data.toString("hex")
8187
8878
  : Buffer.from(data).toString("hex");
8188
- this.runner.runSync("fs", "write-bytes", [p, hexData]);
8879
+ this.runner.runSync("fs", "write-bytes", [safePath, hexData]);
8189
8880
  };
8190
8881
  /**
8191
8882
  * **Fault-Tolerant JSON Read (Asynchronous)**
@@ -8544,7 +9235,12 @@ class FSSearch extends FSHelpers {
8544
9235
  * const matches = __sys__.fs.searchInFiles("./src", "TODO");
8545
9236
  */
8546
9237
  searchInFiles = (dir, pattern) => {
8547
- return this.runner.runSync("search", "grep", [dir, pattern]);
9238
+ try {
9239
+ return this.runner.runSync("search", "grep", [dir, pattern]);
9240
+ }
9241
+ catch (err) {
9242
+ throw err;
9243
+ }
8548
9244
  };
8549
9245
  /**
8550
9246
  * **Filenames Search (Find)**
@@ -8559,7 +9255,12 @@ class FSSearch extends FSHelpers {
8559
9255
  * const tsFiles = __sys__.fs.findByPattern("./src", "*.ts");
8560
9256
  */
8561
9257
  findByPattern = (dir, pattern) => {
8562
- return this.runner.runSync("search", "find", [dir], { pattern });
9258
+ try {
9259
+ return this.runner.runSync("search", "find", [dir], { pattern });
9260
+ }
9261
+ catch (err) {
9262
+ throw err;
9263
+ }
8563
9264
  };
8564
9265
  /**
8565
9266
  * **Filter by File Extension**
@@ -8576,7 +9277,12 @@ class FSSearch extends FSHelpers {
8576
9277
  findByExt = (dir, ext) => {
8577
9278
  const cleanExt = ext.startsWith(".") ? ext : "." + ext;
8578
9279
  const pattern = ".*\\" + cleanExt + "$";
8579
- return this.findByPattern(dir, pattern);
9280
+ try {
9281
+ return this.findByPattern(dir, pattern);
9282
+ }
9283
+ catch (err) {
9284
+ throw err;
9285
+ }
8580
9286
  };
8581
9287
  /**
8582
9288
  * **Pattern-Based Batch Renaming**
@@ -8594,11 +9300,16 @@ class FSSearch extends FSHelpers {
8594
9300
  * __sys__.fs.batchRename("./logs", "log-", "archive-");
8595
9301
  */
8596
9302
  batchRename = (path, pattern, replacement, dryRun = false) => {
8597
- return this.runner.runSync("search", "rename", [path], {
8598
- pattern,
8599
- replacement,
8600
- dryRun,
8601
- });
9303
+ try {
9304
+ return this.runner.runSync("search", "rename", [path], {
9305
+ pattern,
9306
+ replacement,
9307
+ dryRun,
9308
+ });
9309
+ }
9310
+ catch (err) {
9311
+ throw err;
9312
+ }
8602
9313
  };
8603
9314
  /**
8604
9315
  * **Recent Modification Discovery**
@@ -8613,7 +9324,12 @@ class FSSearch extends FSHelpers {
8613
9324
  * const changedInLastDay = __sys__.fs.findModifiedSince("./src", 24);
8614
9325
  */
8615
9326
  findModifiedSince = (dir, hours) => {
8616
- return this.runner.runSync("search", "modified", [dir], { hours });
9327
+ try {
9328
+ return this.runner.runSync("search", "modified", [dir], { hours });
9329
+ }
9330
+ catch (err) {
9331
+ throw err;
9332
+ }
8617
9333
  };
8618
9334
  }
8619
9335
 
@@ -8724,7 +9440,12 @@ class FSWatch extends FSArchive {
8724
9440
  flags.chunkSize = options.chunkSize;
8725
9441
  if (options.hex)
8726
9442
  flags.hex = true;
8727
- return this.runner.runSync("fs", "stream", [p], flags);
9443
+ try {
9444
+ return this.runner.runSync("fs", "stream", [p], flags);
9445
+ }
9446
+ catch (err) {
9447
+ throw err;
9448
+ }
8728
9449
  };
8729
9450
  /**
8730
9451
  * **Reactive File Watching**
@@ -8901,7 +9622,12 @@ class FSExtended extends FSWatch {
8901
9622
  * const lastLogs = __sys__.fs.tail("server.log", 50);
8902
9623
  */
8903
9624
  tail = (p, lines = 10) => {
8904
- return this.runner.runSync("fs", "tail", [p], { lines });
9625
+ try {
9626
+ return this.runner.runSync("fs", "tail", [p], { lines });
9627
+ }
9628
+ catch (err) {
9629
+ throw err;
9630
+ }
8905
9631
  };
8906
9632
  /**
8907
9633
  * **In-Place File Patching**
@@ -8936,10 +9662,15 @@ class FSExtended extends FSWatch {
8936
9662
  * @returns {string[]} Paths to the generated chunks.
8937
9663
  */
8938
9664
  split = (p, bytesPerChunk, outDir) => {
8939
- return this.runner.runSync("fs", "split", [p], {
8940
- bytes: bytesPerChunk,
8941
- out: outDir || "",
8942
- });
9665
+ try {
9666
+ return this.runner.runSync("fs", "split", [p], {
9667
+ bytes: bytesPerChunk,
9668
+ out: outDir || "",
9669
+ });
9670
+ }
9671
+ catch (err) {
9672
+ throw err;
9673
+ }
8943
9674
  };
8944
9675
  /**
8945
9676
  * **File Reconstruction (Merge)**
@@ -9091,7 +9822,12 @@ class FSExtended extends FSWatch {
9091
9822
  * @returns {Array<Object>} List of differences with line numbers.
9092
9823
  */
9093
9824
  diffFiles = (fileA, fileB) => {
9094
- return this.runner.runSync("fs", "diff-files", [fileA, fileB]);
9825
+ try {
9826
+ return this.runner.runSync("fs", "diff-files", [fileA, fileB]);
9827
+ }
9828
+ catch (err) {
9829
+ throw err;
9830
+ }
9095
9831
  };
9096
9832
  /**
9097
9833
  * **Storage Analysis**
@@ -9103,9 +9839,14 @@ class FSExtended extends FSWatch {
9103
9839
  * @returns {Array<Object>} List of paths and sizes.
9104
9840
  */
9105
9841
  topBigFiles = (dir, limit = 50) => {
9106
- return this.runner.runSync("fs", "top-big-files", [dir], {
9107
- limit,
9108
- });
9842
+ try {
9843
+ return this.runner.runSync("fs", "top-big-files", [dir], {
9844
+ limit,
9845
+ });
9846
+ }
9847
+ catch (err) {
9848
+ throw err;
9849
+ }
9109
9850
  };
9110
9851
  }
9111
9852
 
@@ -9157,6 +9898,58 @@ class FSExtended extends FSWatch {
9157
9898
  class FSApi extends FSExtended {
9158
9899
  }
9159
9900
 
9901
+ /**
9902
+ * System keys that cannot be modified, updated, or deleted by user code or plugins.
9903
+ * Only internal engine core components can write to these keys.
9904
+ *
9905
+ * @internal
9906
+ * @see XSA-VARS-002
9907
+ */
9908
+ const PROTECTED_SYSTEM_KEYS = new Set([
9909
+ "pluginPermissions",
9910
+ "__engine__",
9911
+ "__sys__",
9912
+ ]);
9913
+ function isProtectedKey(key) {
9914
+ return (PROTECTED_SYSTEM_KEYS.has(key) ||
9915
+ _StringStartsWith(key, "__sys") ||
9916
+ _StringStartsWith(key, "sys."));
9917
+ }
9918
+ function deepFreeze(obj) {
9919
+ if (obj === null || typeof obj !== "object")
9920
+ return obj;
9921
+ Object.freeze(obj);
9922
+ for (const key of Object.keys(obj)) {
9923
+ deepFreeze(obj[key]);
9924
+ }
9925
+ return obj;
9926
+ }
9927
+ function isCallerEngineCore() {
9928
+ const frames = captureNativeFrames();
9929
+ for (let i = 0; i < frames.length; i++) {
9930
+ const { filePath, fnName, isEval } = frames[i];
9931
+ if (isEval)
9932
+ return false;
9933
+ if (!filePath)
9934
+ continue;
9935
+ if (_StringStartsWith(filePath, "node:") ||
9936
+ _StringStartsWith(filePath, "bun:") ||
9937
+ filePath === "native" ||
9938
+ _StringIncludes(filePath, "[eval]") ||
9939
+ _StringIncludes(filePath, "[vm]")) {
9940
+ continue;
9941
+ }
9942
+ const normalized = _StringReplace(filePath, /\\/g, "/");
9943
+ if (fnName === "captureNativeFrames" ||
9944
+ fnName === "isCallerEngineCore" ||
9945
+ _StringEndsWith(normalized, "/src/xhsc/VarsApi.ts") ||
9946
+ _StringEndsWith(normalized, "/dist/xhsc/VarsApi.js")) {
9947
+ continue;
9948
+ }
9949
+ return isEngineCorePath(normalized);
9950
+ }
9951
+ return false;
9952
+ }
9160
9953
  /**
9161
9954
  * **Dynamic Variables & Configuration API**
9162
9955
  *
@@ -9207,9 +10000,34 @@ class VarsApi extends BaseApi {
9207
10000
  */
9208
10001
  get(key, defaultValue) {
9209
10002
  const caller = getVerifiedCallerInfo();
10003
+ const pkg = extractPackageNameFromPath(caller.callerFile);
10004
+ // System-critical variables (e.g. pluginPermissions) are strictly reserved to engine core
10005
+ if (isProtectedKey(key)) {
10006
+ if (isCallerEngineCore()) {
10007
+ const raw = this.#vars.get(key);
10008
+ if (!raw)
10009
+ return defaultValue;
10010
+ try {
10011
+ return deepFreeze(structuredClone(raw));
10012
+ }
10013
+ catch {
10014
+ return deepFreeze(_JSONParse(_JSONStringify(raw)));
10015
+ }
10016
+ }
10017
+ return defaultValue;
10018
+ }
9210
10019
  if (caller.isUntrusted) {
9211
10020
  return defaultValue;
9212
10021
  }
10022
+ // For third-party callers in node_modules, do not expose host variables.
10023
+ // Third-party packages only access their own scoped variables.
10024
+ if (pkg !== null) {
10025
+ return defaultValue !== undefined
10026
+ ? defaultValue
10027
+ : key === "servers"
10028
+ ? {}
10029
+ : defaultValue;
10030
+ }
9213
10031
  // First check explicit properties
9214
10032
  if (key in this &&
9215
10033
  ![
@@ -9237,17 +10055,27 @@ class VarsApi extends BaseApi {
9237
10055
  *
9238
10056
  * Sets or updates a dynamic variable.
9239
10057
  * Denied for untrusted third-party callers in `node_modules`.
10058
+ * System-critical variables (e.g. `pluginPermissions`) are strictly restricted to engine core.
9240
10059
  *
9241
10060
  * @see XSA-VARS-001
10061
+ * @see XSA-VARS-002 Protected system keys
9242
10062
  * @param {string} key - The variable name.
9243
10063
  * @param {any} value - The value to store.
9244
10064
  * @returns {void}
9245
10065
  */
9246
10066
  set(key, value) {
9247
10067
  const caller = getVerifiedCallerInfo();
9248
- if (caller.isUntrusted) {
10068
+ const pkg = extractPackageNameFromPath(caller.callerFile);
10069
+ if (caller.isUntrusted || pkg !== null) {
10070
+ console.error(`\x1b[31m[XyPriss Security] PERMISSION DENIED: Third-party dependency '${pkg || "unknown"}' is not authorized to set variable '${key}'. Blocked.\x1b[0m`);
9249
10071
  return;
9250
10072
  }
10073
+ if (isProtectedKey(key)) {
10074
+ if (!isCallerEngineCore()) {
10075
+ console.error(`\x1b[31m[XyPriss Security] PERMISSION DENIED: Unauthorized modification of protected system variable '${key}' blocked. Only internal engine components can modify system variables.\x1b[0m`);
10076
+ return;
10077
+ }
10078
+ }
9251
10079
  // Sync with explicit properties if they match
9252
10080
  if (key in this &&
9253
10081
  ![
@@ -9287,13 +10115,21 @@ class VarsApi extends BaseApi {
9287
10115
  * **Remove Variable**
9288
10116
  *
9289
10117
  * @see XSA-VARS-001
10118
+ * @see XSA-VARS-002 Protected system keys
9290
10119
  * @param {string} key - The variable name.
9291
10120
  */
9292
10121
  delete(key) {
9293
10122
  const caller = getVerifiedCallerInfo();
9294
- if (caller.isUntrusted) {
10123
+ const pkg = extractPackageNameFromPath(caller.callerFile);
10124
+ if (caller.isUntrusted || pkg !== null) {
9295
10125
  return;
9296
10126
  }
10127
+ if (isProtectedKey(key)) {
10128
+ if (!isCallerEngineCore()) {
10129
+ console.error(`\x1b[31m[XyPriss Security] PERMISSION DENIED: Unauthorized deletion of protected system variable '${key}' blocked.\x1b[0m`);
10130
+ return;
10131
+ }
10132
+ }
9297
10133
  this.#vars.delete(key);
9298
10134
  }
9299
10135
  /**
@@ -9307,7 +10143,8 @@ class VarsApi extends BaseApi {
9307
10143
  */
9308
10144
  update(data) {
9309
10145
  const caller = getVerifiedCallerInfo();
9310
- if (caller.isUntrusted) {
10146
+ const pkg = extractPackageNameFromPath(caller.callerFile);
10147
+ if (caller.isUntrusted || pkg !== null) {
9311
10148
  return;
9312
10149
  }
9313
10150
  for (const [key, value] of Object.entries(data)) {
@@ -9325,7 +10162,8 @@ class VarsApi extends BaseApi {
9325
10162
  */
9326
10163
  keys() {
9327
10164
  const caller = getVerifiedCallerInfo();
9328
- if (caller.isUntrusted) {
10165
+ const pkg = extractPackageNameFromPath(caller.callerFile);
10166
+ if (caller.isUntrusted || pkg !== null) {
9329
10167
  return [];
9330
10168
  }
9331
10169
  const explicitKeys = [
@@ -9348,7 +10186,8 @@ class VarsApi extends BaseApi {
9348
10186
  */
9349
10187
  all() {
9350
10188
  const caller = getVerifiedCallerInfo();
9351
- if (caller.isUntrusted) {
10189
+ const pkg = extractPackageNameFromPath(caller.callerFile);
10190
+ if (caller.isUntrusted || pkg !== null) {
9352
10191
  return {};
9353
10192
  }
9354
10193
  const json = {};
@@ -9375,6 +10214,10 @@ class VarsApi extends BaseApi {
9375
10214
  * **Clear All**
9376
10215
  */
9377
10216
  clear() {
10217
+ if (!isCallerEngineCore()) {
10218
+ console.error(`\x1b[31m[XyPriss Security] PERMISSION DENIED: Unauthorized attempt to clear system variables blocked.\x1b[0m`);
10219
+ return;
10220
+ }
9378
10221
  this.#vars.clear();
9379
10222
  }
9380
10223
  }
@@ -9490,16 +10333,33 @@ class EnvApi {
9490
10333
  this.applyShield();
9491
10334
  }
9492
10335
  /**
9493
- * @see XSA-XESS-022 Prevents seal key theft from untrusted callers
9494
- * @see XSA-XESS-027 Immune to prototype pollution / WeakMap hooking
9495
- */
9496
- getSealKey() {
9497
- const caller = getVerifiedCallerInfo();
9498
- if (caller.isUntrusted || !isImmediateInternalEngineCall()) {
9499
- return undefined;
9500
- }
9501
- return this.#sealKey;
9502
- }
10336
+ * **Environment Capability Seal Token (`#sealKey`)**
10337
+ *
10338
+ * Retrieves the cryptographic capability seal used exclusively by the XyPriss
10339
+ * internal engine to authorize IPC requests to the native Go daemon (XHSC).
10340
+ *
10341
+ * ---
10342
+ * ### Architecture & Security Model
10343
+ * - **Rôle** : Ce jeton (32 octets aléatoires générés au bootstrap) est verrouillé
10344
+ * auprès du daemon XHSC et lié au PID du processus Node/Bun actif. Il prouve que
10345
+ * chaque requête IPC (`get`, `setStrict`, etc.) émane bien du moteur légitime.
10346
+ * - **Fail-Closed Sandbox Guard** : Cette méthode est strictement restreinte aux
10347
+ * appels directs du cœur du moteur (`isImmediateInternalEngineCall()`).
10348
+ * Tout appel provenant de l'application hôte, d'un plugin ou d'une dépendance
10349
+ * tierce de `node_modules` retourne **systématiquement `undefined`**.
10350
+ *
10351
+ * @internal Réservé à l'audit de sécurité et aux routines internes du moteur.
10352
+ * @see XSA-XESS-022 Protection contre l'exfiltration du Capability Seal par des appelants non fiables.
10353
+ * @see XSA-XESS-027 Immunisé contre les attaques par prototype pollution et hooking WeakMap.
10354
+ * @returns {string | undefined} Le token de scellement si l'appelant est le moteur interne, sinon `undefined`.
10355
+ */
10356
+ // public getSealKey(): string {
10357
+ // const caller = getVerifiedCallerInfo();
10358
+ // if (caller.isUntrusted || !isImmediateInternalEngineCall()) {
10359
+ // return undefined as unknown as string;
10360
+ // }
10361
+ // return this.#sealKey;
10362
+ // }
9503
10363
  executeEnvCall(action, args = [], options = {}) {
9504
10364
  const sealKey = this.#sealKey;
9505
10365
  const runner = this.#runner;
@@ -9607,6 +10467,47 @@ class EnvApi {
9607
10467
  const res = this.executeEnvCall("get", [key], { root });
9608
10468
  return res?.found && res.value !== undefined ? res.value : defaultValue;
9609
10469
  }
10470
+ /**
10471
+ * Reads multiple variables from the secure internal store in a single
10472
+ * Zero-Trust IPC round-trip.
10473
+ *
10474
+ * Preferred over repeated `get()` calls when loading multiple configuration
10475
+ * keys together (e.g. database + auth + telemetry settings).
10476
+ *
10477
+ * @param keys - List of variable names to resolve atomically.
10478
+ * @returns A frozen key-value map containing the resolved variables.
10479
+ * @throws {EnvStoreError} When the store has not been initialised.
10480
+ */
10481
+ getMany(keys) {
10482
+ const root = this.resolveAuthorizedRoot();
10483
+ if (!root || !Array.isArray(keys) || keys.length === 0) {
10484
+ return Object.freeze({});
10485
+ }
10486
+ const queryKeys = [];
10487
+ let includeRoot = false;
10488
+ for (let i = 0; i < keys.length; i++) {
10489
+ const k = keys[i];
10490
+ if (k === "__root__") {
10491
+ includeRoot = true;
10492
+ }
10493
+ else if (typeof k === "string" && k.length > 0) {
10494
+ queryKeys.push(k);
10495
+ }
10496
+ }
10497
+ let resolved = {};
10498
+ if (queryKeys.length > 0) {
10499
+ const res = this.executeEnvCall("getMany", queryKeys, { root });
10500
+ const secrets = res?.secrets || {};
10501
+ for (let i = 0; i < queryKeys.length; i++) {
10502
+ const k = queryKeys[i];
10503
+ resolved[k] = secrets[k];
10504
+ }
10505
+ }
10506
+ if (includeRoot) {
10507
+ resolved.__root__ = root;
10508
+ }
10509
+ return Object.freeze(resolved);
10510
+ }
9610
10511
  /**
9611
10512
  * Reads a variable from the secure internal store for a specific root.
9612
10513
  *
@@ -10550,11 +11451,6 @@ class EnvApi {
10550
11451
  process.stderr.write(`\x1b[33m[SECURITY] WARNING:\x1b[0m Unable to lock process.env descriptor: ${err?.message || err}. Shield proxy degradation active.\n`);
10551
11452
  }
10552
11453
  }
10553
- isCallerProjectCode() {
10554
- const callerRoot = getCallerProjectRoot();
10555
- const sysRoot = globalThis.__sys__?.__root__;
10556
- return !!callerRoot && callerRoot === sysRoot;
10557
- }
10558
11454
  }
10559
11455
 
10560
11456
  class StringWrapper {
@@ -16851,12 +17747,156 @@ class UtilsApi {
16851
17747
  * @extends SysApi
16852
17748
  */
16853
17749
  class XyPrissFS {
16854
- vars;
16855
- fs;
16856
- path;
16857
- os;
16858
- utils;
16859
17750
  _internalRoot;
17751
+ _mode = "development";
17752
+ _isDynamicEnv = false;
17753
+ // Primary instances for host application and internal engine components
17754
+ _primaryRunner;
17755
+ _primaryVars;
17756
+ _primaryFs;
17757
+ _primaryPath;
17758
+ _primaryOs;
17759
+ _primaryUtils;
17760
+ _primaryEnv;
17761
+ // Discrete isolated sandboxes cached by authorized root paths
17762
+ // Guarantees that every caller runs strictly inside the sandbox directory reserved for it
17763
+ _scopedSandboxes = new Map();
17764
+ /**
17765
+ * Identifies the caller's authorized sandbox boundary.
17766
+ * Internal engine components and host application files receive primary access.
17767
+ * Third-party dependencies and isolated plugins receive their own discrete sandbox partition.
17768
+ *
17769
+ * @internal
17770
+ */
17771
+ _resolveCallerContext() {
17772
+ const caller = getVerifiedCallerInfo();
17773
+ if (caller.callerFile && isEngineCorePath(caller.callerFile)) {
17774
+ return { root: this._internalRoot, isPrimaryOrCore: true };
17775
+ }
17776
+ // If the immediate caller is internal engine, check if there is an outer application caller
17777
+ if (isImmediateInternalEngineCall() && !caller.callerFile) {
17778
+ return { root: this._internalRoot, isPrimaryOrCore: true };
17779
+ }
17780
+ const callerRoot = caller.root || getCallerProjectRoot();
17781
+ if (!callerRoot) {
17782
+ return { root: this._internalRoot, isPrimaryOrCore: false };
17783
+ }
17784
+ let normCallerRoot = _PathPosixNormalize(_StringReplace(callerRoot, /\\/g, "/"));
17785
+ while (normCallerRoot.length > 1 && normCallerRoot.endsWith("/")) {
17786
+ normCallerRoot = normCallerRoot.slice(0, -1);
17787
+ }
17788
+ let normInternalRoot = this._internalRoot
17789
+ ? _PathPosixNormalize(_StringReplace(this._internalRoot, /\\/g, "/"))
17790
+ : "";
17791
+ while (normInternalRoot.length > 1 && normInternalRoot.endsWith("/")) {
17792
+ normInternalRoot = normInternalRoot.slice(0, -1);
17793
+ }
17794
+ const primaryRoot = getPrimaryProjectRoot();
17795
+ let normPrimaryRoot = primaryRoot
17796
+ ? _PathPosixNormalize(_StringReplace(primaryRoot, /\\/g, "/"))
17797
+ : "";
17798
+ while (normPrimaryRoot.length > 1 && normPrimaryRoot.endsWith("/")) {
17799
+ normPrimaryRoot = normPrimaryRoot.slice(0, -1);
17800
+ }
17801
+ // Any caller originating from a third-party dependency in node_modules
17802
+ // is strictly confined to its package sandbox and is NEVER primary.
17803
+ const pkg = caller.callerFile
17804
+ ? extractPackageNameFromPath(caller.callerFile)
17805
+ : null;
17806
+ if (pkg !== null) {
17807
+ return {
17808
+ root: normCallerRoot,
17809
+ isPrimaryOrCore: false,
17810
+ };
17811
+ }
17812
+ const isPrimary = normCallerRoot === normInternalRoot ||
17813
+ (normPrimaryRoot !== "" && normCallerRoot === normPrimaryRoot);
17814
+ return {
17815
+ root: normCallerRoot,
17816
+ isPrimaryOrCore: isPrimary,
17817
+ };
17818
+ }
17819
+ /**
17820
+ * Retrieves or instantiates an isolated sandbox suite confined strictly to targetRoot.
17821
+ *
17822
+ * @internal
17823
+ */
17824
+ _getOrCreateScoped(targetRoot) {
17825
+ let scoped = this._scopedSandboxes.get(targetRoot);
17826
+ if (!scoped) {
17827
+ const scopedRunner = new XyPrissRunner(targetRoot);
17828
+ scoped = {
17829
+ vars: new VarsApi(scopedRunner),
17830
+ fs: new FSApi(scopedRunner),
17831
+ path: new PathApi(scopedRunner),
17832
+ os: new OSApi(scopedRunner),
17833
+ utils: new UtilsApi(),
17834
+ env: new EnvApi(scopedRunner, this._mode, true),
17835
+ };
17836
+ this._scopedSandboxes.set(targetRoot, scoped);
17837
+ }
17838
+ return scoped;
17839
+ }
17840
+ /**
17841
+ * **Dynamic Variables & Configuration API (Sandboxed)**
17842
+ *
17843
+ * Returns the variable store scoped strictly to the caller's assigned sandbox.
17844
+ */
17845
+ get vars() {
17846
+ const ctx = this._resolveCallerContext();
17847
+ if (ctx.isPrimaryOrCore)
17848
+ return this._primaryVars;
17849
+ return this._getOrCreateScoped(ctx.root).vars;
17850
+ }
17851
+ /**
17852
+ * **Filesystem API (Sandboxed)**
17853
+ *
17854
+ * Returns the filesystem interface confined strictly to the caller's assigned sandbox directory.
17855
+ */
17856
+ get fs() {
17857
+ const ctx = this._resolveCallerContext();
17858
+ if (ctx.isPrimaryOrCore)
17859
+ return this._primaryFs;
17860
+ return this._getOrCreateScoped(ctx.root).fs;
17861
+ }
17862
+ /**
17863
+ * **Path API (Sandboxed)**
17864
+ *
17865
+ * Returns the path manipulation interface rooted in the caller's assigned sandbox directory.
17866
+ */
17867
+ get path() {
17868
+ const ctx = this._resolveCallerContext();
17869
+ if (ctx.isPrimaryOrCore)
17870
+ return this._primaryPath;
17871
+ return this._getOrCreateScoped(ctx.root).path;
17872
+ }
17873
+ /**
17874
+ * **OS & System Diagnostics API (Sandboxed)**
17875
+ */
17876
+ get os() {
17877
+ const ctx = this._resolveCallerContext();
17878
+ if (ctx.isPrimaryOrCore)
17879
+ return this._primaryOs;
17880
+ return this._getOrCreateScoped(ctx.root).os;
17881
+ }
17882
+ /**
17883
+ * **Utility API**
17884
+ */
17885
+ get utils() {
17886
+ const ctx = this._resolveCallerContext();
17887
+ if (ctx.isPrimaryOrCore)
17888
+ return this._primaryUtils;
17889
+ return this._getOrCreateScoped(ctx.root).utils;
17890
+ }
17891
+ /**
17892
+ * **EnvApi — Environment & Security Manager (Sandboxed)**
17893
+ */
17894
+ get __env__() {
17895
+ const ctx = this._resolveCallerContext();
17896
+ if (ctx.isPrimaryOrCore)
17897
+ return this._primaryEnv;
17898
+ return this._getOrCreateScoped(ctx.root).env;
17899
+ }
16860
17900
  /**
16861
17901
  * **Project Root Path**
16862
17902
  *
@@ -16872,77 +17912,6 @@ class XyPrissFS {
16872
17912
  }
16873
17913
  return callerRoot;
16874
17914
  }
16875
- /**
16876
- * **EnvApi — Environment & Security Manager**
16877
- *
16878
- * `EnvApi` is the sole authorised gateway for reading and writing environment
16879
- * variables inside XyPriss applications. It enforces the XyPriss
16880
- * **Environment Security Shield**, which prevents direct `process.env` access
16881
- * via a hardened runtime Proxy.
16882
- *
16883
- * ---
16884
- *
16885
- * ### Security model
16886
- *
16887
- * Four independent mechanisms work together:
16888
- *
16889
- * **1. Symbol-keyed internal store**
16890
- * The backing store lives at `globalThis[XY_ENV_STORE_KEY]` where
16891
- * `XY_ENV_STORE_KEY` is a module-scoped, unexported `Symbol`. There is no
16892
- * string key to guess or enumerate; external code cannot reach the store
16893
- * without a direct reference to the Symbol.
16894
- *
16895
- * **2. Strict store initialisation guard**
16896
- * Every read and write method calls `requireStore()`, which throws
16897
- * {@link EnvStoreError} if the store has not yet been initialised by the
16898
- * XyPriss bootstrap. This eliminates the silent `process.env` fallback that
16899
- * would otherwise leak values during the startup race window.
16900
- *
16901
- * **3. Value sanitisation**
16902
- * `set()` rejects values containing CR (`\r`), LF (`\n`), or NUL (`\0`).
16903
- * These characters can corrupt downstream log sinks, `.env` parsers, and
16904
- * HTTP header serialisers.
16905
- *
16906
- * **4. Shield — Proxy with enumeration hardening**
16907
- * `process.env` is replaced with a Proxy. Non-whitelisted reads return
16908
- * `undefined`. The `ownKeys` and `has` traps restrict the apparent key set to
16909
- * the whitelist, preventing third-party code (loggers, serialisers) from
16910
- * enumerating the real store through `process.env`.
16911
- *
16912
- * ---
16913
- *
16914
- * ### Usage
16915
- *
16916
- * Do not instantiate this class directly. Use the pre-configured instance
16917
- * exposed by the framework at `__sys__.__env__`:
16918
- *
16919
- * ```typescript
16920
- * // Reading with a fallback
16921
- * const port = __sys__.__env__.get("PORT", "3000");
16922
- *
16923
- * // Reading a required variable — throws EnvAccessError if absent
16924
- * const jwtSecret = __sys__.__env__.getStrict("JWT_SECRET");
16925
- *
16926
- * // Reading a required variable, also rejecting empty strings
16927
- * const dbPassword = __sys__.__env__.getStrict("DB_PASSWORD", { rejectEmpty: true });
16928
- *
16929
- * // Writing a variable at runtime
16930
- * __sys__.__env__.set("FEATURE_FLAG_BETA", "true");
16931
- *
16932
- * // Checking the execution mode
16933
- * if (__sys__.__env__.isProduction()) {
16934
- * // Apply production hardening
16935
- * }
16936
- * ```
16937
- *
16938
- * ---
16939
- *
16940
- * @see {@link IEnvApi} for the public interface contract.
16941
- * @see {@link EnvAccessError} for the error thrown by `getStrict`.
16942
- * @see {@link EnvKeyError} for the error thrown on invalid keys or values.
16943
- * @see {@link EnvStoreError} for the error thrown when the store is not ready.
16944
- */
16945
- __env__;
16946
17915
  /**
16947
17916
  * **Initialize System API**
16948
17917
  *
@@ -16954,13 +17923,15 @@ class XyPrissFS {
16954
17923
  */
16955
17924
  constructor(context) {
16956
17925
  this._internalRoot = context.__root__;
16957
- const runner = new XyPrissRunner(context.__root__);
16958
- this.vars = new VarsApi(runner);
16959
- this.fs = new FSApi(runner);
16960
- this.path = new PathApi(runner);
16961
- this.os = new OSApi(runner);
16962
- this.utils = new UtilsApi();
16963
- this.__env__ = new EnvApi(runner, context.__mode__, context.isDynamicEnv || false);
17926
+ this._mode = context.__mode__ || "development";
17927
+ this._isDynamicEnv = Boolean(context.isDynamicEnv);
17928
+ this._primaryRunner = new XyPrissRunner(context.__root__);
17929
+ this._primaryVars = new VarsApi(this._primaryRunner);
17930
+ this._primaryFs = new FSApi(this._primaryRunner);
17931
+ this._primaryPath = new PathApi(this._primaryRunner);
17932
+ this._primaryOs = new OSApi(this._primaryRunner);
17933
+ this._primaryUtils = new UtilsApi();
17934
+ this._primaryEnv = new EnvApi(this._primaryRunner, context.__mode__, context.isDynamicEnv || false);
16964
17935
  }
16965
17936
  }
16966
17937
 
@@ -17518,18 +18489,18 @@ class MetaConfigRunner {
17518
18489
  * This loader identifies the project root and applies system variables to the global __sys__ object.
17519
18490
  */
17520
18491
  class ConfigLoader {
17521
- isConfigApplied = false;
18492
+ appliedRoots = new Set();
17522
18493
  packageJson = null;
17523
18494
  metaRunner = new MetaConfigRunner();
17524
18495
  sys = getSysApi$1();
17525
18496
  /**
17526
18497
  * Load all xypriss.config.json files found in the project and apply configurations
17527
18498
  */
17528
- loadAndApplySysConfig() {
17529
- if (this.isConfigApplied)
18499
+ loadAndApplySysConfig(targetRoot) {
18500
+ const root = targetRoot || getCallerProjectRoot() || __sys__$1.__root__;
18501
+ if (!root || this.appliedRoots.has(root))
17530
18502
  return;
17531
- this.isConfigApplied = true;
17532
- const root = getCallerProjectRoot() || __sys__$1.__root__;
18503
+ this.appliedRoots.add(root);
17533
18504
  logger$1.debug("server", `ConfigLoader: Initializing discovery from root: ${root}`);
17534
18505
  const configFiles = [];
17535
18506
  // Only look for config at the absolute project root (preferring .jsonc)
@@ -17688,7 +18659,18 @@ class ConfigLoader {
17688
18659
  }
17689
18660
  }
17690
18661
  if (allPermissions.length > 0) {
17691
- __sys__$1.vars.set("pluginPermissions", allPermissions);
18662
+ const existing = __sys__$1.vars.get("pluginPermissions") || [];
18663
+ const merged = [...existing];
18664
+ for (const newPerm of allPermissions) {
18665
+ const idx = merged.findIndex((p) => p.name === newPerm.name);
18666
+ if (idx !== -1) {
18667
+ merged[idx] = { ...merged[idx], ...newPerm };
18668
+ }
18669
+ else {
18670
+ merged.push(newPerm);
18671
+ }
18672
+ }
18673
+ __sys__$1.vars.set("pluginPermissions", merged);
17692
18674
  logger$1.debug("server", `Loaded ${allPermissions.length} plugin permission rules from configuration`);
17693
18675
  }
17694
18676
  }
@@ -17717,8 +18699,6 @@ class ConfigLoader {
17717
18699
  }
17718
18700
  }
17719
18701
  loadPackageJson(root) {
17720
- if (this.packageJson)
17721
- return;
17722
18702
  const pkgPath = this.sys.path.join(root, "package.json");
17723
18703
  if (this.sys.fs.exist(pkgPath)) {
17724
18704
  try {
@@ -19106,6 +20086,15 @@ class XyPrisRequestApp {
19106
20086
  if (prop === "xems") {
19107
20087
  return this.appInstance?.xems || this.appInstance?._xems;
19108
20088
  }
20089
+ // Block unauthorized callers from accessing administrative engine properties
20090
+ if (prop === "pluginManager" ||
20091
+ prop === "xyPluginManager" ||
20092
+ prop === "configs") {
20093
+ const caller = getVerifiedCallerInfo();
20094
+ if (caller.isUntrusted || !isEngineCorePath(caller.callerFile)) {
20095
+ return undefined;
20096
+ }
20097
+ }
19109
20098
  // Otherwise, proxy to appInstance
19110
20099
  if (this.appInstance && prop in this.appInstance) {
19111
20100
  const value = this.appInstance[prop];
@@ -19171,10 +20160,15 @@ class XyPrisRequestApp {
19171
20160
  }
19172
20161
  /**
19173
20162
  * Provides direct access to the application's Plugin Manager.
20163
+ * Strictly restricted to genuine engine core callers.
19174
20164
  *
19175
- * @returns The PluginManager instance associated with the application.
20165
+ * @returns The PluginManager instance associated with the application, or undefined for unauthorized callers.
19176
20166
  */
19177
20167
  get pluginManager() {
20168
+ const caller = getVerifiedCallerInfo();
20169
+ if (caller.isUntrusted || !isEngineCorePath(caller.callerFile)) {
20170
+ return undefined;
20171
+ }
19178
20172
  return this.appInstance?.pluginManager;
19179
20173
  }
19180
20174
  }
@@ -27991,9 +28985,12 @@ class XHSCWorker {
27991
28985
  });
27992
28986
  }
27993
28987
  register() {
28988
+ const token = process.env.XYPRISS_INTERNAL_TOKEN ||
28989
+ process.env.XYPRISS_XESS_AUTH_TOKEN ||
28990
+ "";
27994
28991
  const message = {
27995
28992
  type: "RegisterWorker",
27996
- payload: { id: this.workerId },
28993
+ payload: { id: this.workerId, ...(token ? { token } : {}) },
27997
28994
  };
27998
28995
  this.sendMessage(message);
27999
28996
  this.syncRoutes();
@@ -29271,116 +30268,6 @@ class RouteManager {
29271
30268
  }
29272
30269
  }
29273
30270
 
29274
- /**
29275
- * **XHSC Direct IPC Client**
29276
- *
29277
- * Provides high-performance, direct Unix socket communication with the
29278
- * XHSC background server, bypassing the overhead of process spawning.
29279
- */
29280
- class XHSCDirectIPC {
29281
- ipcPath;
29282
- socket = null;
29283
- constructor(ipcPath) {
29284
- this.ipcPath = ipcPath;
29285
- }
29286
- /**
29287
- * **Connect to the IPC Server**
29288
- */
29289
- async connect() {
29290
- if (this.socket && !this.socket.destroyed)
29291
- return;
29292
- return new Promise((resolve, reject) => {
29293
- this.socket = net__namespace.connect(this.ipcPath, () => {
29294
- resolve();
29295
- });
29296
- this.socket.on("error", (err) => {
29297
- reject(err);
29298
- });
29299
- });
29300
- }
29301
- /**
29302
- * **Send a Command and Wait for Response**
29303
- */
29304
- async sendCommand(module, action, params = {}) {
29305
- await this.connect();
29306
- return new Promise((resolve, reject) => {
29307
- const timeout = setTimeout(() => {
29308
- cleanup();
29309
- reject(new Error(`XHSC Engine request timed out: ${module}.${action}`));
29310
- }, 5000);
29311
- const message = {
29312
- type: "CoreCommand",
29313
- payload: {
29314
- module,
29315
- action,
29316
- params,
29317
- },
29318
- };
29319
- const payload = Buffer.from(JSON.stringify(message));
29320
- const size = Buffer.alloc(4);
29321
- size.writeUInt32BE(payload.length, 0);
29322
- let buffer = Buffer.alloc(0);
29323
- const cleanup = () => {
29324
- clearTimeout(timeout);
29325
- this.socket?.removeListener("data", onData);
29326
- this.socket?.removeListener("error", onError);
29327
- this.socket?.removeListener("close", onClose);
29328
- };
29329
- const onData = (data) => {
29330
- buffer = Buffer.concat([buffer, data]);
29331
- if (buffer.length >= 4) {
29332
- const resSize = buffer.readUInt32BE(0);
29333
- if (buffer.length >= 4 + resSize) {
29334
- const resPayload = buffer.subarray(4, 4 + resSize);
29335
- cleanup();
29336
- try {
29337
- const resMsg = JSON.parse(resPayload.toString());
29338
- if (resMsg.type === "Response") {
29339
- const res = resMsg.payload;
29340
- if (res.status === "error") {
29341
- reject(new Error(res.error));
29342
- }
29343
- else {
29344
- resolve(res.data);
29345
- }
29346
- }
29347
- else {
29348
- reject(new Error("Unexpected message type: " +
29349
- resMsg.type));
29350
- }
29351
- }
29352
- catch (e) {
29353
- reject(e);
29354
- }
29355
- }
29356
- }
29357
- };
29358
- const onError = (err) => {
29359
- cleanup();
29360
- reject(err);
29361
- };
29362
- const onClose = () => {
29363
- cleanup();
29364
- reject(new Error("XHSC Engine connection closed unexpectedly during request"));
29365
- };
29366
- this.socket.on("data", onData);
29367
- this.socket.on("error", onError);
29368
- this.socket.on("close", onClose);
29369
- this.socket.write(size);
29370
- this.socket.write(payload);
29371
- });
29372
- }
29373
- /**
29374
- * **Close Connection**
29375
- */
29376
- close() {
29377
- if (this.socket) {
29378
- this.socket.destroy();
29379
- this.socket = null;
29380
- }
29381
- }
29382
- }
29383
-
29384
30271
  /***************************************************************************
29385
30272
  * ConsoleInterceptor.ts - Lightweight Console Interception System
29386
30273
  * Delegated to XHSC (Go) for heavy lifting
@@ -29491,13 +30378,10 @@ class ConsoleInterceptor {
29491
30378
  this.patchConsole();
29492
30379
  this.isIntercepting = true;
29493
30380
  this.stats.isActive = true;
29494
- // Try to sync config if IPC is already available (Issue #43)
29495
- this.ipcPath =
29496
- this.ipcPath || getSysApi$1()?.__env__?.get("XYPRISS_IPC_PATH");
29497
- if (this.ipcPath) {
29498
- const ipc = new XHSCDirectIPC(this.ipcPath);
29499
- await ipc.sendCommand("console", "update-config", this.config);
29500
- ipc.close();
30381
+ // Sync config over authenticated libSynapx IPC
30382
+ const synapx = SynapxClient.getInstance();
30383
+ if (synapx.isAvailable()) {
30384
+ await synapx.call("console", "update-config", [], this.config);
29501
30385
  }
29502
30386
  }
29503
30387
  catch (err) {
@@ -29671,33 +30555,31 @@ class ConsoleInterceptor {
29671
30555
  console[method] = this.originalConsole[method];
29672
30556
  });
29673
30557
  this.originalConsole = {};
29674
- if (this.ipcPath) {
29675
- try {
29676
- const ipc = new XHSCDirectIPC(this.ipcPath);
29677
- await ipc.sendCommand("console", "update-config", {
30558
+ try {
30559
+ const synapx = SynapxClient.getInstance();
30560
+ if (synapx.isAvailable()) {
30561
+ await synapx.call("console", "update-config", [], {
29678
30562
  ...this.config,
29679
30563
  enabled: false,
29680
30564
  });
29681
- ipc.close();
29682
- }
29683
- catch (err) {
29684
- // Ignore stop errors
29685
30565
  }
29686
30566
  }
30567
+ catch {
30568
+ // Ignore stop errors
30569
+ }
29687
30570
  this.isIntercepting = false;
29688
30571
  this.stats.isActive = false;
29689
30572
  }
29690
30573
  async getStats() {
29691
- if (this.ipcPath && this.isIntercepting) {
30574
+ if (this.isIntercepting) {
29692
30575
  try {
29693
- const ipc = new XHSCDirectIPC(this.ipcPath);
29694
- const res = await ipc.sendCommand("console", "get-stats", {});
29695
- ipc.close();
29696
- // Merge/process remote stats if needed
29697
- // For now, return local state with remote markers
29698
- return { ...this.stats, methodCounts: res.data || {} };
30576
+ const synapx = SynapxClient.getInstance();
30577
+ if (synapx.isAvailable()) {
30578
+ const res = await synapx.call("console", "get-stats", [], {});
30579
+ return { ...this.stats, methodCounts: res?.data || {} };
30580
+ }
29699
30581
  }
29700
- catch (err) {
30582
+ catch {
29701
30583
  return { ...this.stats };
29702
30584
  }
29703
30585
  }
@@ -29708,16 +30590,15 @@ class ConsoleInterceptor {
29708
30590
  ...this.config,
29709
30591
  ...newConfig,
29710
30592
  };
29711
- if (this.ipcPath) {
29712
- try {
29713
- const ipc = new XHSCDirectIPC(this.ipcPath);
29714
- await ipc.sendCommand("console", "update-config", this.config);
29715
- ipc.close();
29716
- }
29717
- catch (err) {
29718
- this.logger.error("console", `Failed to update console config: ${err.message}`);
30593
+ try {
30594
+ const synapx = SynapxClient.getInstance();
30595
+ if (synapx.isAvailable()) {
30596
+ await synapx.call("console", "update-config", [], this.config);
29719
30597
  }
29720
30598
  }
30599
+ catch (err) {
30600
+ this.logger.error("console", `Failed to update console config: ${err.message}`);
30601
+ }
29721
30602
  }
29722
30603
  setPluginEngine(engine) {
29723
30604
  this.pluginEngine = engine;
@@ -34490,11 +35371,156 @@ const HOOK_METADATA = {
34490
35371
  },
34491
35372
  };
34492
35373
 
34493
- const OFFICIAL_PLUGINS = [
34494
- "xypriss::xems.core",
34495
- "Connection Management Plugin",
34496
- "Proxy Routing Plugin",
34497
- ];
35374
+ /***************************************************************************
35375
+ * XyPrissJS - Fast And Secure
35376
+ *
35377
+ * @author Nehonix
35378
+ * @license Nehonix OSL (NOSL)
35379
+ *
35380
+ * Copyright (c) 2025 Nehonix. All rights reserved.
35381
+ ***************************************************************************** */
35382
+ /**
35383
+ * OfficialPluginAuthority
35384
+ *
35385
+ * Implements the 2-Layer Zero-Trust attestation architecture for official plugins.
35386
+ * The list of official plugins is NEVER defined as a static JavaScript array in client memory.
35387
+ * Instead, the authoritative manifest and single-use cryptographic tickets are obtained
35388
+ * dynamically from the native Go XHSC supervisor over authenticated IPC (Synapx).
35389
+ *
35390
+ * @see XSA-PLUG-001
35391
+ * @see XSA-PLUG-002 Native XHSC Plugin Authority
35392
+ */
35393
+ class OfficialPluginAuthority {
35394
+ static instance = null;
35395
+ #officials = new Set();
35396
+ #tickets = new Map();
35397
+ #claimed = new Set();
35398
+ #isLoaded = false;
35399
+ constructor() { }
35400
+ static getInstance() {
35401
+ if (!OfficialPluginAuthority.instance) {
35402
+ OfficialPluginAuthority.instance = new OfficialPluginAuthority();
35403
+ }
35404
+ return OfficialPluginAuthority.instance;
35405
+ }
35406
+ /**
35407
+ * Loads the official plugins manifest and ephemeral capability tickets
35408
+ * dynamically from XHSC over authenticated libSynapx IPC.
35409
+ */
35410
+ loadManifest() {
35411
+ try {
35412
+ const synapx = SynapxClient.getInstance();
35413
+ if (synapx.isAvailable()) {
35414
+ const res = synapx.callSync("plugin", "manifest");
35415
+ if (res && Array.isArray(res.officials)) {
35416
+ this.#officials.clear();
35417
+ for (const name of res.officials) {
35418
+ this.#officials.add(name);
35419
+ }
35420
+ if (res.tickets) {
35421
+ this.#tickets.clear();
35422
+ for (const [name, token] of Object.entries(res.tickets)) {
35423
+ this.#tickets.set(name, token);
35424
+ }
35425
+ }
35426
+ this.#isLoaded = true;
35427
+ return;
35428
+ }
35429
+ }
35430
+ }
35431
+ catch {
35432
+ // Fail-closed fallback: if XHSC IPC is offline, no unverified plugins are trusted
35433
+ }
35434
+ // Offline / Test Fallback: When XHSC daemon is offline (e.g. standalone test runners)
35435
+ if (!this.#isLoaded) {
35436
+ this.#officials = new Set([
35437
+ "xypriss::xems.core",
35438
+ "Connection Management Plugin",
35439
+ "Proxy Routing Plugin",
35440
+ ]);
35441
+ this.#isLoaded = true;
35442
+ }
35443
+ }
35444
+ /**
35445
+ * Checks whether a plugin name corresponds to a verified official built-in plugin.
35446
+ * Queries the dynamic XHSC manifest.
35447
+ */
35448
+ isOfficialPlugin(pluginName) {
35449
+ if (!pluginName)
35450
+ return false;
35451
+ if (!this.#isLoaded) {
35452
+ this.loadManifest();
35453
+ }
35454
+ return this.#officials.has(pluginName);
35455
+ }
35456
+ /**
35457
+ * Retrieves the list of recognized official plugin names.
35458
+ * Read-only array defensively copied.
35459
+ */
35460
+ getOfficialNames() {
35461
+ if (!this.#isLoaded) {
35462
+ this.loadManifest();
35463
+ }
35464
+ return Array.from(this.#officials);
35465
+ }
35466
+ /**
35467
+ * Claims a single-use capability ticket for a built-in plugin during registration.
35468
+ * Strictly restricted to genuine internal engine components.
35469
+ */
35470
+ claimTicket(pluginName) {
35471
+ const caller = getVerifiedCallerInfo();
35472
+ if (caller.isUntrusted || !isEngineCorePath(caller.callerFile)) {
35473
+ return null;
35474
+ }
35475
+ if (!this.#isLoaded) {
35476
+ this.loadManifest();
35477
+ }
35478
+ if (this.#claimed.has(pluginName)) {
35479
+ // Already claimed: single-use token exhausted!
35480
+ return null;
35481
+ }
35482
+ const ticket = this.#tickets.get(pluginName) || null;
35483
+ if (ticket) {
35484
+ this.#tickets.delete(pluginName);
35485
+ this.#claimed.add(pluginName);
35486
+ }
35487
+ return ticket;
35488
+ }
35489
+ /**
35490
+ * Verifies an activation claim ticket with XHSC.
35491
+ */
35492
+ verifyClaimWithXHSC(pluginName, ticket) {
35493
+ try {
35494
+ const synapx = SynapxClient.getInstance();
35495
+ if (synapx.isAvailable()) {
35496
+ const res = synapx.callSync("plugin", "verify", [pluginName, ticket]);
35497
+ return Boolean(res?.valid);
35498
+ }
35499
+ }
35500
+ catch {
35501
+ // If XHSC is offline, check local claimed state
35502
+ }
35503
+ return this.#claimed.has(pluginName);
35504
+ }
35505
+ /**
35506
+ * Resets the authority state (internal test use only).
35507
+ */
35508
+ _resetForTest() {
35509
+ const caller = getVerifiedCallerInfo();
35510
+ if (isEngineCorePath(caller.callerFile)) {
35511
+ this.#officials.clear();
35512
+ this.#tickets.clear();
35513
+ this.#claimed.clear();
35514
+ this.#isLoaded = false;
35515
+ }
35516
+ }
35517
+ }
35518
+ /**
35519
+ * Helper to check if a plugin is official using the dynamic authority.
35520
+ */
35521
+ function isOfficialPlugin(name) {
35522
+ return OfficialPluginAuthority.getInstance().isOfficialPlugin(name);
35523
+ }
34498
35524
 
34499
35525
  /***************************************************************************
34500
35526
  * XyPrissJS - Fast And Secure
@@ -34555,8 +35581,20 @@ class PermissionManager {
34555
35581
  return false;
34556
35582
  }
34557
35583
  // --- BUILT-IN PLUGINS BYPASS ---
34558
- // Built-in (official) plugins always bypass security checks for full capabilities.
34559
- if (OFFICIAL_PLUGINS.includes(pluginName)) {
35584
+ // Built-in (official) plugins always bypass security checks for full capabilities,
35585
+ // provided their physical origin is verified to be inside the engine core.
35586
+ if (isOfficialPlugin(pluginName)) {
35587
+ const registry = this.server?.pluginManager?.registry ||
35588
+ this.server?.app?.xyPluginManager?.registry;
35589
+ if (registry) {
35590
+ const registeredPlugin = registry.get(pluginName);
35591
+ if (registeredPlugin &&
35592
+ registeredPlugin.__root__ &&
35593
+ !isCoreFrameworkPath(registeredPlugin.__root__)) {
35594
+ console.error(`\x1b[31m[XyPriss Security] SECURITY VIOLATION: Plugin '${pluginName}' claims official status but resides at '${registeredPlugin.__root__}' outside engine core! Access denied.\x1b[0m`);
35595
+ return false;
35596
+ }
35597
+ }
34560
35598
  return true;
34561
35599
  }
34562
35600
  const hookId = HOOK_ID_MAP[internalHookName] || internalHookName;
@@ -34646,13 +35684,35 @@ class PermissionManager {
34646
35684
  * Creates a masked version of the request object for security in plugin hooks.
34647
35685
  * Prevents plugins from accessing sensitive data like body, query, and cookies
34648
35686
  * unless explicitly authorized with ACCESS_SENSITIVE_DATA permission.
35687
+ * Administrative engine properties (req.app.pluginManager, req.app.xyPluginManager)
35688
+ * are strictly isolated from all external plugins regardless of data permissions.
34649
35689
  */
34650
35690
  maskRequest(req, pluginName) {
34651
35691
  if (!req)
34652
35692
  return req;
34653
- if (pluginName && OFFICIAL_PLUGINS.includes(pluginName)) {
35693
+ let isGenuineOfficial = false;
35694
+ if (pluginName && isOfficialPlugin(pluginName)) {
35695
+ const registry = this.server?.pluginManager?.registry ||
35696
+ this.server?.app?.xyPluginManager?.registry;
35697
+ if (registry) {
35698
+ const registeredPlugin = registry.get(pluginName);
35699
+ if (registeredPlugin &&
35700
+ registeredPlugin.__root__ &&
35701
+ !isCoreFrameworkPath(registeredPlugin.__root__)) {
35702
+ isGenuineOfficial = false;
35703
+ }
35704
+ else {
35705
+ isGenuineOfficial = true;
35706
+ }
35707
+ }
35708
+ else {
35709
+ isGenuineOfficial = true;
35710
+ }
35711
+ }
35712
+ if (isGenuineOfficial) {
34654
35713
  return req;
34655
35714
  }
35715
+ let allowSensitiveData = false;
34656
35716
  if (pluginName) {
34657
35717
  const permissions = __sys__$1?.vars.get("pluginPermissions");
34658
35718
  if (permissions) {
@@ -34663,7 +35723,7 @@ class PermissionManager {
34663
35723
  allowedHooks.includes(PluginHookIds.ACCESS_SENSITIVE_DATA);
34664
35724
  const isDenied = pluginPerm.deniedHooks?.includes(PluginHookIds.ACCESS_SENSITIVE_DATA);
34665
35725
  if (isAllowed && !isDenied) {
34666
- return req; // Explicitly allowed: return unmasked real request
35726
+ allowSensitiveData = true;
34667
35727
  }
34668
35728
  }
34669
35729
  }
@@ -34678,7 +35738,52 @@ class PermissionManager {
34678
35738
  ];
34679
35739
  return new Proxy(req, {
34680
35740
  get(target, prop) {
35741
+ // Administrative engine isolation: protect req.app against capability leakage
35742
+ if (prop === "app") {
35743
+ const originalApp = target.app;
35744
+ if (!originalApp)
35745
+ return undefined;
35746
+ return new Proxy(originalApp, {
35747
+ get(appTarget, appProp) {
35748
+ if (typeof appProp === "string" &&
35749
+ [
35750
+ "pluginManager",
35751
+ "xyPluginManager",
35752
+ "configs",
35753
+ "server",
35754
+ "settings",
35755
+ ].includes(appProp)) {
35756
+ console.error(`\x1b[31m[XyPriss Security] PERMISSION DENIED: Plugin '${pluginName || "unknown"}' is not authorized to access internal engine property 'req.app.${appProp}'.\x1b[0m`);
35757
+ return undefined;
35758
+ }
35759
+ const val = appTarget[appProp];
35760
+ if (typeof val === "function") {
35761
+ return val.bind(appTarget);
35762
+ }
35763
+ return val;
35764
+ },
35765
+ has(appTarget, appProp) {
35766
+ if (typeof appProp === "string" &&
35767
+ [
35768
+ "pluginManager",
35769
+ "xyPluginManager",
35770
+ "configs",
35771
+ "server",
35772
+ "settings",
35773
+ ].includes(appProp)) {
35774
+ return false;
35775
+ }
35776
+ return appProp in appTarget;
35777
+ },
35778
+ });
35779
+ }
35780
+ if (prop === "server") {
35781
+ return undefined;
35782
+ }
34681
35783
  if (typeof prop === "string" && prop === "headers") {
35784
+ if (allowSensitiveData) {
35785
+ return target[prop];
35786
+ }
34682
35787
  const originalHeaders = target[prop] || {};
34683
35788
  const safeHeaders = [
34684
35789
  "user-agent",
@@ -34702,6 +35807,9 @@ class PermissionManager {
34702
35807
  }
34703
35808
  if (typeof prop === "string" &&
34704
35809
  sensitiveFields.includes(prop)) {
35810
+ if (allowSensitiveData) {
35811
+ return target[prop];
35812
+ }
34705
35813
  return `[${pluginName}] Access to sensitive request data '${prop}' is restricted for security reasons. Requires XHS.PERM.SECURITY.SENSITIVE_DATA.`;
34706
35814
  }
34707
35815
  const value = target[prop];
@@ -34833,7 +35941,7 @@ const schm = reliantType.Interface({
34833
35941
  function validatePlgInput(d) {
34834
35942
  try {
34835
35943
  // First check if it's an official whitelisted plugin
34836
- const isOfficial = OFFICIAL_PLUGINS.includes(d.name);
35944
+ const isOfficial = isOfficialPlugin(d.name);
34837
35945
  // If not official, enforce strict alphanumeric/hyphen rules
34838
35946
  if (!isOfficial) {
34839
35947
  if (!/^[a-zA-Z0-9-]+$/.test(d.name)) {
@@ -34898,6 +36006,16 @@ class PluginSecurity {
34898
36006
  */
34899
36007
  verifyContract(plugin, callerStack, isExecutionPhase = false) {
34900
36008
  // --- ROOT DISCOVERY ---
36009
+ const claimsOfficial = isOfficialPlugin(plugin.name);
36010
+ // Built-in plugin registration detection:
36011
+ // When the engine initializes its built-in plugins (XemsBuiltinPlugin, etc.),
36012
+ // the registration originates from XPluginManager.initializeBuiltinPlugins inside the engine core.
36013
+ const isBuiltinRegistration = callerStack.includes("initializeBuiltinPlugins") ||
36014
+ (callerStack.includes("XPluginManager") && claimsOfficial);
36015
+ if (claimsOfficial && isBuiltinRegistration) {
36016
+ plugin.__root__ = ENGINE_CORE_DIR;
36017
+ return ENGINE_CORE_DIR;
36018
+ }
34901
36019
  // We now prioritize the root provided explicitly via Plugin.create(..., __sys__)
34902
36020
  let pluginRoot = plugin.__root__ || "";
34903
36021
  if (!pluginRoot && !isExecutionPhase) {
@@ -34909,8 +36027,8 @@ class PluginSecurity {
34909
36027
  // If we still have no root, we cannot verify the contract.
34910
36028
  // During registration, this is a FATAL error if we're not inside the core.
34911
36029
  if (!isExecutionPhase) {
34912
- const isOfficial = OFFICIAL_PLUGINS.includes(plugin.name);
34913
- if (isOfficial) {
36030
+ const caller = getVerifiedCallerInfo();
36031
+ if (claimsOfficial && isEngineCorePath(caller.callerFile)) {
34914
36032
  // Safe fallback for official built-in plugins if discovery failed
34915
36033
  return "";
34916
36034
  }
@@ -34918,14 +36036,16 @@ class PluginSecurity {
34918
36036
  }
34919
36037
  return "";
34920
36038
  }
36039
+ const isCorePath = isCoreFrameworkPath(pluginRoot);
36040
+ // Anti-spoofing enforcement: An external plugin CANNOT claim a reserved official plugin name!
36041
+ if (claimsOfficial && !isCorePath) {
36042
+ this.throwSpoofingViolation(plugin.name, pluginRoot);
36043
+ }
34921
36044
  // Always verify if it's NOT a core framework path
34922
- const isOfficial = OFFICIAL_PLUGINS.includes(plugin.name);
34923
- if (!isCoreFrameworkPath(pluginRoot)) {
34924
- if (!isOfficial) {
34925
- const contractOk = verifyPluginContract(pluginRoot, plugin.name);
34926
- if (!contractOk) {
34927
- this.throwViolation(plugin.name, pluginRoot);
34928
- }
36045
+ if (!isCorePath) {
36046
+ const contractOk = verifyPluginContract(pluginRoot, plugin.name);
36047
+ if (!contractOk) {
36048
+ this.throwViolation(plugin.name, pluginRoot);
34929
36049
  }
34930
36050
  // Perform static source code analysis to catch ESM namespace imports
34931
36051
  // which bypass the execution-level NativeApiBlocker.
@@ -34936,6 +36056,18 @@ class PluginSecurity {
34936
36056
  plugin.__root__ = pluginRoot;
34937
36057
  return pluginRoot;
34938
36058
  }
36059
+ /**
36060
+ * Throw a spoofing violation error when an external plugin attempts to impersonate an official identity
36061
+ */
36062
+ throwSpoofingViolation(pluginName, pluginRoot) {
36063
+ const errorMsg = `\x1b[41m\x1b[37m [XyPriss Security] FATAL ERROR::SPOOFING_ATTEMPT \x1b[0m\n` +
36064
+ `\x1b[31mPlugin '${pluginName}' refused registration!\x1b[0m\n` +
36065
+ `\x1b[33mReason:\x1b[0m Unauthorized external plugin attempting to impersonate reserved official plugin '${pluginName}'.\n` +
36066
+ `\x1b[34mPlugin Path:\x1b[0m ${pluginRoot || "Unknown"}\n` +
36067
+ `\x1b[32mAction Required:\x1b[0m Official plugin names are strictly reserved for internal engine components. Rename your plugin.`;
36068
+ console.error(errorMsg);
36069
+ throw new Error(`Security Violation: Plugin '${pluginName}' attempted to impersonate reserved official core plugin identity`);
36070
+ }
34939
36071
  /**
34940
36072
  * Throw a security contract violation error
34941
36073
  */
@@ -35028,7 +36160,7 @@ class PluginSecurity {
35028
36160
  * and verifying Ed25519 signature of xypriss.plugin.xsig
35029
36161
  */
35030
36162
  verifyContentIntegrity(pluginRoot, pluginName) {
35031
- const isOfficial = OFFICIAL_PLUGINS.includes(pluginName);
36163
+ const isOfficial = isOfficialPlugin(pluginName) && isCoreFrameworkPath(pluginRoot);
35032
36164
  if (isOfficial || isCoreFrameworkPath(pluginRoot)) {
35033
36165
  return;
35034
36166
  }
@@ -35206,7 +36338,7 @@ class PluginSecurity {
35206
36338
  const target = server.app;
35207
36339
  // --- SECURITY CHECK: Configuration Access ---
35208
36340
  if (prop === "configs") {
35209
- if (OFFICIAL_PLUGINS.includes(pluginName)) {
36341
+ if (isOfficialPlugin(pluginName)) {
35210
36342
  return target[prop];
35211
36343
  }
35212
36344
  const hasPermission = permissionManager.checkPermission(pluginName, "configs");
@@ -35230,7 +36362,7 @@ class PluginSecurity {
35230
36362
  }
35231
36363
  // Intercept the method execution to wrap the actual route handlers/middlewares
35232
36364
  return (...args) => {
35233
- const isOfficial = OFFICIAL_PLUGINS.includes(pluginName);
36365
+ const isOfficial = isOfficialPlugin(pluginName);
35234
36366
  // --- SECURITY ENFORCEMENT: Routing Boundaries ---
35235
36367
  if (allowedRoutingMethods.includes(prop) && args.length > 0 && !isOfficial) {
35236
36368
  const pathArg = args[0];
@@ -35288,7 +36420,7 @@ class PluginSecurity {
35288
36420
  },
35289
36421
  set: (value) => {
35290
36422
  const target = server.app;
35291
- if (prop === "xems" && OFFICIAL_PLUGINS.includes(pluginName)) {
36423
+ if (prop === "xems" && isOfficialPlugin(pluginName)) {
35292
36424
  try {
35293
36425
  target.xems = value;
35294
36426
  }
@@ -36674,6 +37806,7 @@ class XemsBuiltinPlugin {
36674
37806
  version = "1.1.23";
36675
37807
  type = "security";
36676
37808
  description = "XyPriss Entry Management System (Session & Storage)";
37809
+ __root__ = ENGINE_CORE_DIR;
36677
37810
  runner;
36678
37811
  sessionOptions = {
36679
37812
  sandbox: "xems.internal-session",
@@ -38469,11 +39602,15 @@ class XMSStartupUI {
38469
39602
  console[m] = (...args) => {
38470
39603
  const str = args
38471
39604
  .map((a) => typeof a === "object"
38472
- ? JSON.stringify(a)
39605
+ ? (a instanceof Error ? (a.stack || a.message) : JSON.stringify(a))
38473
39606
  : String(a))
38474
39607
  .join(" ");
38475
39608
  this.consoleBuffer.push(str);
38476
- if (this.isAllowedStartupLog(str)) {
39609
+ // Critical Rule: Never swallow errors, warnings, or vital system milestones!
39610
+ const isCriticalOrError = m === "error" ||
39611
+ m === "warn" ||
39612
+ this.isAllowedStartupLog(str);
39613
+ if (isCriticalOrError) {
38477
39614
  this.printPassthroughLog(str);
38478
39615
  }
38479
39616
  };
@@ -38490,10 +39627,11 @@ class XMSStartupUI {
38490
39627
  this.originalConsole = {};
38491
39628
  }
38492
39629
  /**
38493
- * Check if a log entry represents a critical startup milestone
39630
+ * Check if a log entry represents a critical startup milestone or diagnostic alert
38494
39631
  * that must remain visible even during quiet initialization.
38495
39632
  *
38496
39633
  * Allowed:
39634
+ * - Errors, unhandled rejections, exceptions, violations, and emergency alerts
38497
39635
  * - "Initializing Version XHSC..." (XHSC binary version identification)
38498
39636
  * - "Initializing XRMS (XyPriss Request Management System)..." (XRMS stack initialization)
38499
39637
  */
@@ -38501,18 +39639,28 @@ class XMSStartupUI {
38501
39639
  if (!message)
38502
39640
  return false;
38503
39641
  const clean = message.replace(/\x1b\[[0-9;]*m/g, "");
39642
+ // Never swallow internal errors, unhandled rejections, or security violations
39643
+ if (/error|exception|uncaught|unhandled|fatal|emergency|violation|failed|rejected/i.test(clean) ||
39644
+ /\[(?:security|emergency|plugins|error)\]/i.test(clean)) {
39645
+ return true;
39646
+ }
38504
39647
  return (/(?:i|n)?nitializing version xhsc/i.test(clean) ||
38505
39648
  /(?:i|n)?nitializing xrms/i.test(clean));
38506
39649
  }
38507
39650
  handleCapturedLog(entry) {
38508
39651
  const fullMsg = [
38509
39652
  entry.message,
38510
- ...(entry.args || []).map((a) => typeof a === "object" ? JSON.stringify(a) : String(a)),
39653
+ ...(entry.args || []).map((a) => typeof a === "object"
39654
+ ? (a instanceof Error ? (a.stack || a.message) : JSON.stringify(a))
39655
+ : String(a)),
38511
39656
  ].join(" ");
38512
- if (this.isAllowedStartupLog(fullMsg)) {
39657
+ // Always passthrough errors, warnings, and vital startup milestones
39658
+ if (entry.level === "error" ||
39659
+ entry.level === "warn" ||
39660
+ this.isAllowedStartupLog(fullMsg)) {
38513
39661
  const formatted = Logger.getInstance().formatEntry(entry);
38514
39662
  const extraArgs = entry.args && entry.args.length > 0
38515
- ? ` ${entry.args.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a))).join(" ")}`
39663
+ ? ` ${entry.args.map((a) => (typeof a === "object" ? (a instanceof Error ? (a.stack || a.message) : JSON.stringify(a)) : String(a))).join(" ")}`
38516
39664
  : "";
38517
39665
  this.printPassthroughLog(`${formatted}${extraArgs}`);
38518
39666
  }