xypriss 9.14.36 → 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/README.md +8 -3
- package/dist/cjs/index.js +1651 -452
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/index.js +1651 -452
- package/dist/esm/index.js.map +1 -1
- package/dist/index.d.ts +123 -79
- package/package.json +1 -1
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
|
-
*
|
|
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
|
-
|
|
1880
|
-
try {
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
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
|
-
|
|
1900
|
+
return _StringSlice(thisFile, 0, distIdx + 1); // root directory with trailing '/'
|
|
1897
1901
|
}
|
|
1898
1902
|
}
|
|
1899
1903
|
}
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
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
|
|
1906
|
-
*
|
|
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
|
|
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
|
|
1916
|
-
//
|
|
1917
|
-
|
|
1918
|
-
if (
|
|
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
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
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
|
-
|
|
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 =
|
|
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 =
|
|
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.
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
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
|
-
//
|
|
2107
|
-
// @see XSA-XESS-018
|
|
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
|
-
|
|
2111
|
-
|
|
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
|
-
|
|
4891
|
-
|
|
4892
|
-
|
|
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
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
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
|
|
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 ||
|
|
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
|
|
5139
|
-
|
|
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.
|
|
5143
|
-
this.
|
|
5144
|
-
|
|
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
|
|
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(
|
|
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
|
|
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,
|
|
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 ||
|
|
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;
|
|
@@ -5351,11 +5865,19 @@ class SynapxClient {
|
|
|
5351
5865
|
if (!this.socketPath)
|
|
5352
5866
|
return false;
|
|
5353
5867
|
try {
|
|
5354
|
-
|
|
5868
|
+
if (fs__namespace.existsSync(this.socketPath))
|
|
5869
|
+
return true;
|
|
5355
5870
|
}
|
|
5356
|
-
catch {
|
|
5357
|
-
|
|
5871
|
+
catch { }
|
|
5872
|
+
if (process.platform === "win32") {
|
|
5873
|
+
try {
|
|
5874
|
+
const dir = path__namespace.dirname(this.socketPath);
|
|
5875
|
+
const base = path__namespace.basename(this.socketPath);
|
|
5876
|
+
return fs__namespace.readdirSync(dir).includes(base);
|
|
5877
|
+
}
|
|
5878
|
+
catch { }
|
|
5358
5879
|
}
|
|
5880
|
+
return false;
|
|
5359
5881
|
}
|
|
5360
5882
|
lastDaemonSpawnTime = 0;
|
|
5361
5883
|
resolveBinary() {
|
|
@@ -5419,9 +5941,10 @@ class SynapxClient {
|
|
|
5419
5941
|
childExited = true;
|
|
5420
5942
|
});
|
|
5421
5943
|
child.unref();
|
|
5422
|
-
// Wait for socket to appear (
|
|
5944
|
+
// Wait for socket to appear (accounts for UPX cold-start decompression)
|
|
5945
|
+
const maxWait = process.platform === "win32" ? 6000 : 5000;
|
|
5423
5946
|
const start = Date.now();
|
|
5424
|
-
while (Date.now() - start <
|
|
5947
|
+
while (Date.now() - start < maxWait) {
|
|
5425
5948
|
if (this.isAvailable() || childExited) {
|
|
5426
5949
|
break;
|
|
5427
5950
|
}
|
|
@@ -5692,19 +6215,29 @@ class SynapxClient {
|
|
|
5692
6215
|
throw new Error(`libSynapx: Unauthorized caller for restricted module '${module}'`);
|
|
5693
6216
|
}
|
|
5694
6217
|
}
|
|
5695
|
-
if (!this
|
|
5696
|
-
this.
|
|
5697
|
-
|
|
5698
|
-
|
|
6218
|
+
if (!this.#syncBridge) {
|
|
6219
|
+
if (!this.socketPath || !this.isAvailable()) {
|
|
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
|
+
}
|
|
5699
6224
|
}
|
|
6225
|
+
this.#syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.#authToken);
|
|
5700
6226
|
}
|
|
5701
6227
|
try {
|
|
5702
|
-
if (!this.#syncBridge) {
|
|
5703
|
-
this.#syncBridge = SynapxSyncBridge.getInstance(this.socketPath, this.sessionHash, this.#authToken);
|
|
5704
|
-
}
|
|
5705
6228
|
return this.#syncBridge.callSync(module, action, args, opts);
|
|
5706
6229
|
}
|
|
5707
|
-
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
|
+
}
|
|
5708
6241
|
// Resilient fallback to stdin subprocess pipeline
|
|
5709
6242
|
return this.callSyncSubprocess(module, action, args, opts);
|
|
5710
6243
|
}
|
|
@@ -6212,12 +6745,23 @@ function getInstanceId() {
|
|
|
6212
6745
|
*/
|
|
6213
6746
|
class BaseApi {
|
|
6214
6747
|
#runner;
|
|
6748
|
+
#assignedRoot;
|
|
6215
6749
|
/**
|
|
6216
6750
|
* Initializes the Base API with a shared runner instance.
|
|
6217
6751
|
* @param runner - The XyPrissRunner used to invoke native XHSC binaries.
|
|
6218
6752
|
*/
|
|
6219
6753
|
constructor(runner) {
|
|
6220
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;
|
|
6221
6765
|
}
|
|
6222
6766
|
/**
|
|
6223
6767
|
* Protected accessor for internal engine classes only.
|
|
@@ -6247,6 +6791,21 @@ class BaseApi {
|
|
|
6247
6791
|
* @extends BaseApi
|
|
6248
6792
|
*/
|
|
6249
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
|
+
}
|
|
6250
6809
|
/**
|
|
6251
6810
|
* **Resolve to Absolute Path**
|
|
6252
6811
|
*
|
|
@@ -6272,12 +6831,18 @@ class PathApi extends BaseApi {
|
|
|
6272
6831
|
* // Output: "/home/user/project" (Back to root)
|
|
6273
6832
|
*/
|
|
6274
6833
|
resolve = (...paths) => {
|
|
6275
|
-
|
|
6276
|
-
|
|
6834
|
+
const baseRoot = this.__root__;
|
|
6835
|
+
if (paths.length === 0) {
|
|
6836
|
+
return baseRoot || "/";
|
|
6277
6837
|
}
|
|
6278
|
-
|
|
6838
|
+
if (path.isAbsolute(paths[0])) {
|
|
6279
6839
|
return path.resolve(...paths);
|
|
6280
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);
|
|
6281
6846
|
};
|
|
6282
6847
|
join = (...paths) => {
|
|
6283
6848
|
try {
|
|
@@ -6335,7 +6900,7 @@ class PathApi extends BaseApi {
|
|
|
6335
6900
|
]);
|
|
6336
6901
|
}
|
|
6337
6902
|
catch {
|
|
6338
|
-
const rel = path.relative(
|
|
6903
|
+
const rel = path.relative(this.resolve(parent), this.resolve(child));
|
|
6339
6904
|
return !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
6340
6905
|
}
|
|
6341
6906
|
};
|
|
@@ -6347,7 +6912,7 @@ class PathApi extends BaseApi {
|
|
|
6347
6912
|
]);
|
|
6348
6913
|
}
|
|
6349
6914
|
catch {
|
|
6350
|
-
const resolvedBase =
|
|
6915
|
+
const resolvedBase = this.resolve(base);
|
|
6351
6916
|
const target = path.resolve(resolvedBase, ...segments);
|
|
6352
6917
|
if (!this.isChild(resolvedBase, target) && resolvedBase !== target) {
|
|
6353
6918
|
throw new Error(`Path traversal attempt detected: ${target} escapes ${resolvedBase}`);
|
|
@@ -6403,8 +6968,8 @@ class PathApi extends BaseApi {
|
|
|
6403
6968
|
if (paths.length === 0)
|
|
6404
6969
|
return "";
|
|
6405
6970
|
if (paths.length === 1)
|
|
6406
|
-
return path.dirname(
|
|
6407
|
-
const splitPaths = paths.map((p) =>
|
|
6971
|
+
return path.dirname(this.resolve(paths[0]));
|
|
6972
|
+
const splitPaths = paths.map((p) => this.resolve(p).split(path.sep));
|
|
6408
6973
|
const minLen = Math.min(...splitPaths.map((p) => p.length));
|
|
6409
6974
|
let common = [];
|
|
6410
6975
|
for (let i = 0; i < minLen; i++) {
|
|
@@ -6518,7 +7083,8 @@ class PathApi extends BaseApi {
|
|
|
6518
7083
|
*/
|
|
6519
7084
|
exist = (p) => {
|
|
6520
7085
|
try {
|
|
6521
|
-
const
|
|
7086
|
+
const resolvedPath = this.resolve(p);
|
|
7087
|
+
const res = this.runner.runSync("fs", "check", [resolvedPath]);
|
|
6522
7088
|
return res?.exists === true;
|
|
6523
7089
|
}
|
|
6524
7090
|
catch {
|
|
@@ -6536,7 +7102,8 @@ class PathApi extends BaseApi {
|
|
|
6536
7102
|
*/
|
|
6537
7103
|
isDir = (p) => {
|
|
6538
7104
|
try {
|
|
6539
|
-
const
|
|
7105
|
+
const resolvedPath = this.resolve(p);
|
|
7106
|
+
const res = this.runner.runSync("fs", "stats", [resolvedPath]);
|
|
6540
7107
|
return res?.is_dir === true;
|
|
6541
7108
|
}
|
|
6542
7109
|
catch {
|
|
@@ -6548,7 +7115,8 @@ class PathApi extends BaseApi {
|
|
|
6548
7115
|
*/
|
|
6549
7116
|
isFile = (p) => {
|
|
6550
7117
|
try {
|
|
6551
|
-
const
|
|
7118
|
+
const resolvedPath = this.resolve(p);
|
|
7119
|
+
const res = this.runner.runSync("fs", "stats", [resolvedPath]);
|
|
6552
7120
|
return res?.is_file === true;
|
|
6553
7121
|
}
|
|
6554
7122
|
catch {
|
|
@@ -6560,7 +7128,8 @@ class PathApi extends BaseApi {
|
|
|
6560
7128
|
*/
|
|
6561
7129
|
isSymlink = (p) => {
|
|
6562
7130
|
try {
|
|
6563
|
-
const
|
|
7131
|
+
const resolvedPath = this.resolve(p);
|
|
7132
|
+
const res = this.runner.runSync("fs", "stats", [resolvedPath]);
|
|
6564
7133
|
return res?.is_symlink === true;
|
|
6565
7134
|
}
|
|
6566
7135
|
catch {
|
|
@@ -6572,12 +7141,13 @@ class PathApi extends BaseApi {
|
|
|
6572
7141
|
*/
|
|
6573
7142
|
isEmpty = (p) => {
|
|
6574
7143
|
try {
|
|
6575
|
-
|
|
6576
|
-
|
|
7144
|
+
const resolvedPath = this.resolve(p);
|
|
7145
|
+
if (this.isFile(resolvedPath)) {
|
|
7146
|
+
const res = this.runner.runSync("fs", "size", [resolvedPath]);
|
|
6577
7147
|
return res?.bytes === 0;
|
|
6578
7148
|
}
|
|
6579
|
-
if (this.isDir(
|
|
6580
|
-
const res = this.runner.runSync("fs", "ls", [
|
|
7149
|
+
if (this.isDir(resolvedPath)) {
|
|
7150
|
+
const res = this.runner.runSync("fs", "ls", [resolvedPath]);
|
|
6581
7151
|
return res?.length === 0;
|
|
6582
7152
|
}
|
|
6583
7153
|
return false;
|
|
@@ -6731,11 +7301,16 @@ class OSApi extends BaseApi {
|
|
|
6731
7301
|
* @returns {ProcessMonitorSnapshot[] | void} Captured snapshots.
|
|
6732
7302
|
*/
|
|
6733
7303
|
monitorProcess = (pid, duration = 60) => {
|
|
6734
|
-
|
|
6735
|
-
|
|
6736
|
-
|
|
6737
|
-
|
|
6738
|
-
|
|
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
|
+
}
|
|
6739
7314
|
};
|
|
6740
7315
|
/**
|
|
6741
7316
|
* **Terminate Process**
|
|
@@ -6808,7 +7383,7 @@ class OSApi extends BaseApi {
|
|
|
6808
7383
|
* **Base Filesystem API**
|
|
6809
7384
|
*
|
|
6810
7385
|
* Provides the foundation for all filesystem operations, including
|
|
6811
|
-
* logger initialization and
|
|
7386
|
+
* logger initialization, runner access, and strict sandbox enforcement.
|
|
6812
7387
|
*/
|
|
6813
7388
|
class FSBase extends PathApi {
|
|
6814
7389
|
logger;
|
|
@@ -6816,6 +7391,67 @@ class FSBase extends PathApi {
|
|
|
6816
7391
|
super(runner);
|
|
6817
7392
|
this.logger = new Logger();
|
|
6818
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
|
+
}
|
|
6819
7455
|
}
|
|
6820
7456
|
|
|
6821
7457
|
/* *****************************************************************************
|
|
@@ -7346,11 +7982,19 @@ class TempFileManager {
|
|
|
7346
7982
|
*/
|
|
7347
7983
|
class FSCore extends FSBase {
|
|
7348
7984
|
ls(p, options = {}) {
|
|
7349
|
-
|
|
7350
|
-
|
|
7351
|
-
|
|
7352
|
-
|
|
7353
|
-
|
|
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
|
+
}
|
|
7354
7998
|
}
|
|
7355
7999
|
/**
|
|
7356
8000
|
* **Read File Content (Asynchronous)**
|
|
@@ -7368,8 +8012,19 @@ class FSCore extends FSBase {
|
|
|
7368
8012
|
* console.log(content);
|
|
7369
8013
|
*/
|
|
7370
8014
|
read = async (p, options = {}) => {
|
|
7371
|
-
const
|
|
7372
|
-
|
|
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
|
+
}
|
|
7373
8028
|
};
|
|
7374
8029
|
/**
|
|
7375
8030
|
* **Read File Content (Synchronous)**
|
|
@@ -7386,8 +8041,11 @@ class FSCore extends FSBase {
|
|
|
7386
8041
|
* const content = __sys__.fs.readSync("/etc/hosts");
|
|
7387
8042
|
*/
|
|
7388
8043
|
readSync = (p, options = {}) => {
|
|
8044
|
+
const safePath = this.resolvePathInSandbox(p, "readSync");
|
|
8045
|
+
if (!safePath)
|
|
8046
|
+
return "";
|
|
7389
8047
|
try {
|
|
7390
|
-
const res = this.runner.runSync("fs", "read", [
|
|
8048
|
+
const res = this.runner.runSync("fs", "read", [safePath, String(Boolean(options.bytes))], options);
|
|
7391
8049
|
return res?.data !== undefined ? res.data : res;
|
|
7392
8050
|
}
|
|
7393
8051
|
catch (err) {
|
|
@@ -7458,9 +8116,12 @@ class FSCore extends FSBase {
|
|
|
7458
8116
|
* await __sys__.fs.writeFile("log.txt", "Event happened\n", { append: true });
|
|
7459
8117
|
*/
|
|
7460
8118
|
writeFile = async (p, data, options = {}) => {
|
|
8119
|
+
const safePath = this.resolvePathInSandbox(p, "writeFile");
|
|
8120
|
+
if (!safePath)
|
|
8121
|
+
return;
|
|
7461
8122
|
const { ensureFile = true } = options;
|
|
7462
8123
|
if (ensureFile) {
|
|
7463
|
-
const dir = this.dirname(
|
|
8124
|
+
const dir = this.dirname(safePath);
|
|
7464
8125
|
if (dir && dir !== "." && !this.exist(dir)) {
|
|
7465
8126
|
this.mkdir(dir, { parents: true });
|
|
7466
8127
|
}
|
|
@@ -7471,7 +8132,7 @@ class FSCore extends FSBase {
|
|
|
7471
8132
|
? data.toString("hex")
|
|
7472
8133
|
: Buffer.from(data).toString("hex");
|
|
7473
8134
|
await this.runner.runAsync("fs", "write-bytes", [
|
|
7474
|
-
|
|
8135
|
+
safePath,
|
|
7475
8136
|
hexData,
|
|
7476
8137
|
String(Boolean(options.append)),
|
|
7477
8138
|
]);
|
|
@@ -7484,7 +8145,7 @@ class FSCore extends FSBase {
|
|
|
7484
8145
|
else {
|
|
7485
8146
|
writeData = String(data);
|
|
7486
8147
|
}
|
|
7487
|
-
await this.runner.runAsync("fs", "write", [
|
|
8148
|
+
await this.runner.runAsync("fs", "write", [safePath, writeData, String(Boolean(options.append))], {
|
|
7488
8149
|
...options,
|
|
7489
8150
|
input: writeData,
|
|
7490
8151
|
});
|
|
@@ -7502,9 +8163,12 @@ class FSCore extends FSBase {
|
|
|
7502
8163
|
* @param {boolean} [options.ensureFile=true] - If true, creates parent directories if they don't exist.
|
|
7503
8164
|
*/
|
|
7504
8165
|
writeFileSync = (p, data, options = {}) => {
|
|
8166
|
+
const safePath = this.resolvePathInSandbox(p, "writeFileSync");
|
|
8167
|
+
if (!safePath)
|
|
8168
|
+
return;
|
|
7505
8169
|
const { ensureFile = true } = options;
|
|
7506
8170
|
if (ensureFile) {
|
|
7507
|
-
const dir = this.dirname(
|
|
8171
|
+
const dir = this.dirname(safePath);
|
|
7508
8172
|
if (dir && dir !== "." && !this.exist(dir)) {
|
|
7509
8173
|
this.mkdir(dir, { parents: true });
|
|
7510
8174
|
}
|
|
@@ -7566,7 +8230,12 @@ class FSCore extends FSBase {
|
|
|
7566
8230
|
* @example
|
|
7567
8231
|
* __sys__.fs.rm("./tmp/cache", { force: true });
|
|
7568
8232
|
*/
|
|
7569
|
-
rm = (p, 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
|
+
};
|
|
7570
8239
|
/**
|
|
7571
8240
|
* **Remove Multiple Files or Directories**
|
|
7572
8241
|
*
|
|
@@ -7587,7 +8256,10 @@ class FSCore extends FSBase {
|
|
|
7587
8256
|
*/
|
|
7588
8257
|
rmMany = (paths, options = {}) => {
|
|
7589
8258
|
for (const p of paths) {
|
|
7590
|
-
this.
|
|
8259
|
+
const safePath = this.resolvePathInSandbox(p, "rmMany");
|
|
8260
|
+
if (!safePath)
|
|
8261
|
+
continue;
|
|
8262
|
+
this.runner.runSync("fs", "rm", [safePath, String(Boolean(options.force))], options);
|
|
7591
8263
|
}
|
|
7592
8264
|
};
|
|
7593
8265
|
/**
|
|
@@ -7602,7 +8274,12 @@ class FSCore extends FSBase {
|
|
|
7602
8274
|
* @example
|
|
7603
8275
|
* __sys__.fs.mkdir("/path/to/new-dir", { parents: true });
|
|
7604
8276
|
*/
|
|
7605
|
-
mkdir = (p, 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
|
+
};
|
|
7606
8283
|
/**
|
|
7607
8284
|
* **Touch File**
|
|
7608
8285
|
*
|
|
@@ -8112,7 +8789,18 @@ class FSHelpers extends FSCore {
|
|
|
8112
8789
|
* @example
|
|
8113
8790
|
* const config = __sys__.fs.readJsonSync("package.json");
|
|
8114
8791
|
*/
|
|
8115
|
-
readJsonSync = (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
|
+
};
|
|
8116
8804
|
/**
|
|
8117
8805
|
* **Read File as Binary (Asynchronous)**
|
|
8118
8806
|
*
|
|
@@ -8122,7 +8810,10 @@ class FSHelpers extends FSCore {
|
|
|
8122
8810
|
* @returns {Promise<Buffer>} Binary data.
|
|
8123
8811
|
*/
|
|
8124
8812
|
readBytes = async (p) => {
|
|
8125
|
-
const
|
|
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]));
|
|
8126
8817
|
const hexData = res?.data !== undefined ? res.data : res;
|
|
8127
8818
|
if (Buffer.isBuffer(hexData))
|
|
8128
8819
|
return hexData;
|
|
@@ -8140,7 +8831,10 @@ class FSHelpers extends FSCore {
|
|
|
8140
8831
|
* @returns {Buffer} Binary data.
|
|
8141
8832
|
*/
|
|
8142
8833
|
readBytesSync = (p) => {
|
|
8143
|
-
const
|
|
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]);
|
|
8144
8838
|
const hexData = res?.data !== undefined ? res.data : res;
|
|
8145
8839
|
if (Buffer.isBuffer(hexData))
|
|
8146
8840
|
return hexData;
|
|
@@ -8159,10 +8853,13 @@ class FSHelpers extends FSCore {
|
|
|
8159
8853
|
* @returns {Promise<void>}
|
|
8160
8854
|
*/
|
|
8161
8855
|
writeBytes = async (p, data) => {
|
|
8856
|
+
const safePath = this.resolvePathInSandbox(p, "writeBytes");
|
|
8857
|
+
if (!safePath)
|
|
8858
|
+
return;
|
|
8162
8859
|
const hexData = Buffer.isBuffer(data)
|
|
8163
8860
|
? data.toString("hex")
|
|
8164
8861
|
: Buffer.from(data).toString("hex");
|
|
8165
|
-
await this.runner.runAsync("fs", "write-bytes", [
|
|
8862
|
+
await this.runner.runAsync("fs", "write-bytes", [safePath, hexData]);
|
|
8166
8863
|
};
|
|
8167
8864
|
/**
|
|
8168
8865
|
* **Write Binary Data (Synchronous)**
|
|
@@ -8173,10 +8870,13 @@ class FSHelpers extends FSCore {
|
|
|
8173
8870
|
* @param {Buffer} data - Binary data to write.
|
|
8174
8871
|
*/
|
|
8175
8872
|
writeBytesSync = (p, data) => {
|
|
8873
|
+
const safePath = this.resolvePathInSandbox(p, "writeBytesSync");
|
|
8874
|
+
if (!safePath)
|
|
8875
|
+
return;
|
|
8176
8876
|
const hexData = Buffer.isBuffer(data)
|
|
8177
8877
|
? data.toString("hex")
|
|
8178
8878
|
: Buffer.from(data).toString("hex");
|
|
8179
|
-
this.runner.runSync("fs", "write-bytes", [
|
|
8879
|
+
this.runner.runSync("fs", "write-bytes", [safePath, hexData]);
|
|
8180
8880
|
};
|
|
8181
8881
|
/**
|
|
8182
8882
|
* **Fault-Tolerant JSON Read (Asynchronous)**
|
|
@@ -8535,7 +9235,12 @@ class FSSearch extends FSHelpers {
|
|
|
8535
9235
|
* const matches = __sys__.fs.searchInFiles("./src", "TODO");
|
|
8536
9236
|
*/
|
|
8537
9237
|
searchInFiles = (dir, pattern) => {
|
|
8538
|
-
|
|
9238
|
+
try {
|
|
9239
|
+
return this.runner.runSync("search", "grep", [dir, pattern]);
|
|
9240
|
+
}
|
|
9241
|
+
catch (err) {
|
|
9242
|
+
throw err;
|
|
9243
|
+
}
|
|
8539
9244
|
};
|
|
8540
9245
|
/**
|
|
8541
9246
|
* **Filenames Search (Find)**
|
|
@@ -8550,7 +9255,12 @@ class FSSearch extends FSHelpers {
|
|
|
8550
9255
|
* const tsFiles = __sys__.fs.findByPattern("./src", "*.ts");
|
|
8551
9256
|
*/
|
|
8552
9257
|
findByPattern = (dir, pattern) => {
|
|
8553
|
-
|
|
9258
|
+
try {
|
|
9259
|
+
return this.runner.runSync("search", "find", [dir], { pattern });
|
|
9260
|
+
}
|
|
9261
|
+
catch (err) {
|
|
9262
|
+
throw err;
|
|
9263
|
+
}
|
|
8554
9264
|
};
|
|
8555
9265
|
/**
|
|
8556
9266
|
* **Filter by File Extension**
|
|
@@ -8567,7 +9277,12 @@ class FSSearch extends FSHelpers {
|
|
|
8567
9277
|
findByExt = (dir, ext) => {
|
|
8568
9278
|
const cleanExt = ext.startsWith(".") ? ext : "." + ext;
|
|
8569
9279
|
const pattern = ".*\\" + cleanExt + "$";
|
|
8570
|
-
|
|
9280
|
+
try {
|
|
9281
|
+
return this.findByPattern(dir, pattern);
|
|
9282
|
+
}
|
|
9283
|
+
catch (err) {
|
|
9284
|
+
throw err;
|
|
9285
|
+
}
|
|
8571
9286
|
};
|
|
8572
9287
|
/**
|
|
8573
9288
|
* **Pattern-Based Batch Renaming**
|
|
@@ -8585,11 +9300,16 @@ class FSSearch extends FSHelpers {
|
|
|
8585
9300
|
* __sys__.fs.batchRename("./logs", "log-", "archive-");
|
|
8586
9301
|
*/
|
|
8587
9302
|
batchRename = (path, pattern, replacement, dryRun = false) => {
|
|
8588
|
-
|
|
8589
|
-
|
|
8590
|
-
|
|
8591
|
-
|
|
8592
|
-
|
|
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
|
+
}
|
|
8593
9313
|
};
|
|
8594
9314
|
/**
|
|
8595
9315
|
* **Recent Modification Discovery**
|
|
@@ -8604,7 +9324,12 @@ class FSSearch extends FSHelpers {
|
|
|
8604
9324
|
* const changedInLastDay = __sys__.fs.findModifiedSince("./src", 24);
|
|
8605
9325
|
*/
|
|
8606
9326
|
findModifiedSince = (dir, hours) => {
|
|
8607
|
-
|
|
9327
|
+
try {
|
|
9328
|
+
return this.runner.runSync("search", "modified", [dir], { hours });
|
|
9329
|
+
}
|
|
9330
|
+
catch (err) {
|
|
9331
|
+
throw err;
|
|
9332
|
+
}
|
|
8608
9333
|
};
|
|
8609
9334
|
}
|
|
8610
9335
|
|
|
@@ -8715,7 +9440,12 @@ class FSWatch extends FSArchive {
|
|
|
8715
9440
|
flags.chunkSize = options.chunkSize;
|
|
8716
9441
|
if (options.hex)
|
|
8717
9442
|
flags.hex = true;
|
|
8718
|
-
|
|
9443
|
+
try {
|
|
9444
|
+
return this.runner.runSync("fs", "stream", [p], flags);
|
|
9445
|
+
}
|
|
9446
|
+
catch (err) {
|
|
9447
|
+
throw err;
|
|
9448
|
+
}
|
|
8719
9449
|
};
|
|
8720
9450
|
/**
|
|
8721
9451
|
* **Reactive File Watching**
|
|
@@ -8892,7 +9622,12 @@ class FSExtended extends FSWatch {
|
|
|
8892
9622
|
* const lastLogs = __sys__.fs.tail("server.log", 50);
|
|
8893
9623
|
*/
|
|
8894
9624
|
tail = (p, lines = 10) => {
|
|
8895
|
-
|
|
9625
|
+
try {
|
|
9626
|
+
return this.runner.runSync("fs", "tail", [p], { lines });
|
|
9627
|
+
}
|
|
9628
|
+
catch (err) {
|
|
9629
|
+
throw err;
|
|
9630
|
+
}
|
|
8896
9631
|
};
|
|
8897
9632
|
/**
|
|
8898
9633
|
* **In-Place File Patching**
|
|
@@ -8927,10 +9662,15 @@ class FSExtended extends FSWatch {
|
|
|
8927
9662
|
* @returns {string[]} Paths to the generated chunks.
|
|
8928
9663
|
*/
|
|
8929
9664
|
split = (p, bytesPerChunk, outDir) => {
|
|
8930
|
-
|
|
8931
|
-
|
|
8932
|
-
|
|
8933
|
-
|
|
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
|
+
}
|
|
8934
9674
|
};
|
|
8935
9675
|
/**
|
|
8936
9676
|
* **File Reconstruction (Merge)**
|
|
@@ -9082,7 +9822,12 @@ class FSExtended extends FSWatch {
|
|
|
9082
9822
|
* @returns {Array<Object>} List of differences with line numbers.
|
|
9083
9823
|
*/
|
|
9084
9824
|
diffFiles = (fileA, fileB) => {
|
|
9085
|
-
|
|
9825
|
+
try {
|
|
9826
|
+
return this.runner.runSync("fs", "diff-files", [fileA, fileB]);
|
|
9827
|
+
}
|
|
9828
|
+
catch (err) {
|
|
9829
|
+
throw err;
|
|
9830
|
+
}
|
|
9086
9831
|
};
|
|
9087
9832
|
/**
|
|
9088
9833
|
* **Storage Analysis**
|
|
@@ -9094,9 +9839,14 @@ class FSExtended extends FSWatch {
|
|
|
9094
9839
|
* @returns {Array<Object>} List of paths and sizes.
|
|
9095
9840
|
*/
|
|
9096
9841
|
topBigFiles = (dir, limit = 50) => {
|
|
9097
|
-
|
|
9098
|
-
|
|
9099
|
-
|
|
9842
|
+
try {
|
|
9843
|
+
return this.runner.runSync("fs", "top-big-files", [dir], {
|
|
9844
|
+
limit,
|
|
9845
|
+
});
|
|
9846
|
+
}
|
|
9847
|
+
catch (err) {
|
|
9848
|
+
throw err;
|
|
9849
|
+
}
|
|
9100
9850
|
};
|
|
9101
9851
|
}
|
|
9102
9852
|
|
|
@@ -9148,6 +9898,58 @@ class FSExtended extends FSWatch {
|
|
|
9148
9898
|
class FSApi extends FSExtended {
|
|
9149
9899
|
}
|
|
9150
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
|
+
}
|
|
9151
9953
|
/**
|
|
9152
9954
|
* **Dynamic Variables & Configuration API**
|
|
9153
9955
|
*
|
|
@@ -9198,9 +10000,34 @@ class VarsApi extends BaseApi {
|
|
|
9198
10000
|
*/
|
|
9199
10001
|
get(key, defaultValue) {
|
|
9200
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
|
+
}
|
|
9201
10019
|
if (caller.isUntrusted) {
|
|
9202
10020
|
return defaultValue;
|
|
9203
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
|
+
}
|
|
9204
10031
|
// First check explicit properties
|
|
9205
10032
|
if (key in this &&
|
|
9206
10033
|
![
|
|
@@ -9228,17 +10055,27 @@ class VarsApi extends BaseApi {
|
|
|
9228
10055
|
*
|
|
9229
10056
|
* Sets or updates a dynamic variable.
|
|
9230
10057
|
* Denied for untrusted third-party callers in `node_modules`.
|
|
10058
|
+
* System-critical variables (e.g. `pluginPermissions`) are strictly restricted to engine core.
|
|
9231
10059
|
*
|
|
9232
10060
|
* @see XSA-VARS-001
|
|
10061
|
+
* @see XSA-VARS-002 Protected system keys
|
|
9233
10062
|
* @param {string} key - The variable name.
|
|
9234
10063
|
* @param {any} value - The value to store.
|
|
9235
10064
|
* @returns {void}
|
|
9236
10065
|
*/
|
|
9237
10066
|
set(key, value) {
|
|
9238
10067
|
const caller = getVerifiedCallerInfo();
|
|
9239
|
-
|
|
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`);
|
|
9240
10071
|
return;
|
|
9241
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
|
+
}
|
|
9242
10079
|
// Sync with explicit properties if they match
|
|
9243
10080
|
if (key in this &&
|
|
9244
10081
|
![
|
|
@@ -9278,13 +10115,21 @@ class VarsApi extends BaseApi {
|
|
|
9278
10115
|
* **Remove Variable**
|
|
9279
10116
|
*
|
|
9280
10117
|
* @see XSA-VARS-001
|
|
10118
|
+
* @see XSA-VARS-002 Protected system keys
|
|
9281
10119
|
* @param {string} key - The variable name.
|
|
9282
10120
|
*/
|
|
9283
10121
|
delete(key) {
|
|
9284
10122
|
const caller = getVerifiedCallerInfo();
|
|
9285
|
-
|
|
10123
|
+
const pkg = extractPackageNameFromPath(caller.callerFile);
|
|
10124
|
+
if (caller.isUntrusted || pkg !== null) {
|
|
9286
10125
|
return;
|
|
9287
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
|
+
}
|
|
9288
10133
|
this.#vars.delete(key);
|
|
9289
10134
|
}
|
|
9290
10135
|
/**
|
|
@@ -9298,7 +10143,8 @@ class VarsApi extends BaseApi {
|
|
|
9298
10143
|
*/
|
|
9299
10144
|
update(data) {
|
|
9300
10145
|
const caller = getVerifiedCallerInfo();
|
|
9301
|
-
|
|
10146
|
+
const pkg = extractPackageNameFromPath(caller.callerFile);
|
|
10147
|
+
if (caller.isUntrusted || pkg !== null) {
|
|
9302
10148
|
return;
|
|
9303
10149
|
}
|
|
9304
10150
|
for (const [key, value] of Object.entries(data)) {
|
|
@@ -9316,7 +10162,8 @@ class VarsApi extends BaseApi {
|
|
|
9316
10162
|
*/
|
|
9317
10163
|
keys() {
|
|
9318
10164
|
const caller = getVerifiedCallerInfo();
|
|
9319
|
-
|
|
10165
|
+
const pkg = extractPackageNameFromPath(caller.callerFile);
|
|
10166
|
+
if (caller.isUntrusted || pkg !== null) {
|
|
9320
10167
|
return [];
|
|
9321
10168
|
}
|
|
9322
10169
|
const explicitKeys = [
|
|
@@ -9339,7 +10186,8 @@ class VarsApi extends BaseApi {
|
|
|
9339
10186
|
*/
|
|
9340
10187
|
all() {
|
|
9341
10188
|
const caller = getVerifiedCallerInfo();
|
|
9342
|
-
|
|
10189
|
+
const pkg = extractPackageNameFromPath(caller.callerFile);
|
|
10190
|
+
if (caller.isUntrusted || pkg !== null) {
|
|
9343
10191
|
return {};
|
|
9344
10192
|
}
|
|
9345
10193
|
const json = {};
|
|
@@ -9366,6 +10214,10 @@ class VarsApi extends BaseApi {
|
|
|
9366
10214
|
* **Clear All**
|
|
9367
10215
|
*/
|
|
9368
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
|
+
}
|
|
9369
10221
|
this.#vars.clear();
|
|
9370
10222
|
}
|
|
9371
10223
|
}
|
|
@@ -9433,6 +10285,20 @@ class EnvApi {
|
|
|
9433
10285
|
"SYSTEMROOT",
|
|
9434
10286
|
"TEMP",
|
|
9435
10287
|
"TMP",
|
|
10288
|
+
// Internal infrastructure & IPC socket paths (Zero-secret runtime transport)
|
|
10289
|
+
"LIBPORT_SOCKET_PATH",
|
|
10290
|
+
"PORT_SOCKET_PATH",
|
|
10291
|
+
"XPM_SOCKET_PATH",
|
|
10292
|
+
"XESS_IPC_SOCKET",
|
|
10293
|
+
"XYPRISS_USER_TMP",
|
|
10294
|
+
"XESS_SESSION_TMP",
|
|
10295
|
+
"XESS_TEMP_DIR",
|
|
10296
|
+
"XYPRISS_PROJECT_ROOT",
|
|
10297
|
+
"XYPRISS_PLUGINS_MANIFEST",
|
|
10298
|
+
"XYPRISS_SESSION_HASH",
|
|
10299
|
+
"XYPRISS_XHSC_PATH",
|
|
10300
|
+
"XFPM_VERSION",
|
|
10301
|
+
"LIBXESS_ACTIVE",
|
|
9436
10302
|
]);
|
|
9437
10303
|
/**
|
|
9438
10304
|
* Keys that may pass through the Shield to the real `process.env`.
|
|
@@ -9467,16 +10333,33 @@ class EnvApi {
|
|
|
9467
10333
|
this.applyShield();
|
|
9468
10334
|
}
|
|
9469
10335
|
/**
|
|
9470
|
-
*
|
|
9471
|
-
*
|
|
9472
|
-
|
|
9473
|
-
|
|
9474
|
-
|
|
9475
|
-
|
|
9476
|
-
|
|
9477
|
-
|
|
9478
|
-
|
|
9479
|
-
|
|
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
|
+
// }
|
|
9480
10363
|
executeEnvCall(action, args = [], options = {}) {
|
|
9481
10364
|
const sealKey = this.#sealKey;
|
|
9482
10365
|
const runner = this.#runner;
|
|
@@ -9584,6 +10467,47 @@ class EnvApi {
|
|
|
9584
10467
|
const res = this.executeEnvCall("get", [key], { root });
|
|
9585
10468
|
return res?.found && res.value !== undefined ? res.value : defaultValue;
|
|
9586
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
|
+
}
|
|
9587
10511
|
/**
|
|
9588
10512
|
* Reads a variable from the secure internal store for a specific root.
|
|
9589
10513
|
*
|
|
@@ -10527,11 +11451,6 @@ class EnvApi {
|
|
|
10527
11451
|
process.stderr.write(`\x1b[33m[SECURITY] WARNING:\x1b[0m Unable to lock process.env descriptor: ${err?.message || err}. Shield proxy degradation active.\n`);
|
|
10528
11452
|
}
|
|
10529
11453
|
}
|
|
10530
|
-
isCallerProjectCode() {
|
|
10531
|
-
const callerRoot = getCallerProjectRoot();
|
|
10532
|
-
const sysRoot = globalThis.__sys__?.__root__;
|
|
10533
|
-
return !!callerRoot && callerRoot === sysRoot;
|
|
10534
|
-
}
|
|
10535
11454
|
}
|
|
10536
11455
|
|
|
10537
11456
|
class StringWrapper {
|
|
@@ -16828,12 +17747,156 @@ class UtilsApi {
|
|
|
16828
17747
|
* @extends SysApi
|
|
16829
17748
|
*/
|
|
16830
17749
|
class XyPrissFS {
|
|
16831
|
-
vars;
|
|
16832
|
-
fs;
|
|
16833
|
-
path;
|
|
16834
|
-
os;
|
|
16835
|
-
utils;
|
|
16836
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
|
+
}
|
|
16837
17900
|
/**
|
|
16838
17901
|
* **Project Root Path**
|
|
16839
17902
|
*
|
|
@@ -16849,77 +17912,6 @@ class XyPrissFS {
|
|
|
16849
17912
|
}
|
|
16850
17913
|
return callerRoot;
|
|
16851
17914
|
}
|
|
16852
|
-
/**
|
|
16853
|
-
* **EnvApi — Environment & Security Manager**
|
|
16854
|
-
*
|
|
16855
|
-
* `EnvApi` is the sole authorised gateway for reading and writing environment
|
|
16856
|
-
* variables inside XyPriss applications. It enforces the XyPriss
|
|
16857
|
-
* **Environment Security Shield**, which prevents direct `process.env` access
|
|
16858
|
-
* via a hardened runtime Proxy.
|
|
16859
|
-
*
|
|
16860
|
-
* ---
|
|
16861
|
-
*
|
|
16862
|
-
* ### Security model
|
|
16863
|
-
*
|
|
16864
|
-
* Four independent mechanisms work together:
|
|
16865
|
-
*
|
|
16866
|
-
* **1. Symbol-keyed internal store**
|
|
16867
|
-
* The backing store lives at `globalThis[XY_ENV_STORE_KEY]` where
|
|
16868
|
-
* `XY_ENV_STORE_KEY` is a module-scoped, unexported `Symbol`. There is no
|
|
16869
|
-
* string key to guess or enumerate; external code cannot reach the store
|
|
16870
|
-
* without a direct reference to the Symbol.
|
|
16871
|
-
*
|
|
16872
|
-
* **2. Strict store initialisation guard**
|
|
16873
|
-
* Every read and write method calls `requireStore()`, which throws
|
|
16874
|
-
* {@link EnvStoreError} if the store has not yet been initialised by the
|
|
16875
|
-
* XyPriss bootstrap. This eliminates the silent `process.env` fallback that
|
|
16876
|
-
* would otherwise leak values during the startup race window.
|
|
16877
|
-
*
|
|
16878
|
-
* **3. Value sanitisation**
|
|
16879
|
-
* `set()` rejects values containing CR (`\r`), LF (`\n`), or NUL (`\0`).
|
|
16880
|
-
* These characters can corrupt downstream log sinks, `.env` parsers, and
|
|
16881
|
-
* HTTP header serialisers.
|
|
16882
|
-
*
|
|
16883
|
-
* **4. Shield — Proxy with enumeration hardening**
|
|
16884
|
-
* `process.env` is replaced with a Proxy. Non-whitelisted reads return
|
|
16885
|
-
* `undefined`. The `ownKeys` and `has` traps restrict the apparent key set to
|
|
16886
|
-
* the whitelist, preventing third-party code (loggers, serialisers) from
|
|
16887
|
-
* enumerating the real store through `process.env`.
|
|
16888
|
-
*
|
|
16889
|
-
* ---
|
|
16890
|
-
*
|
|
16891
|
-
* ### Usage
|
|
16892
|
-
*
|
|
16893
|
-
* Do not instantiate this class directly. Use the pre-configured instance
|
|
16894
|
-
* exposed by the framework at `__sys__.__env__`:
|
|
16895
|
-
*
|
|
16896
|
-
* ```typescript
|
|
16897
|
-
* // Reading with a fallback
|
|
16898
|
-
* const port = __sys__.__env__.get("PORT", "3000");
|
|
16899
|
-
*
|
|
16900
|
-
* // Reading a required variable — throws EnvAccessError if absent
|
|
16901
|
-
* const jwtSecret = __sys__.__env__.getStrict("JWT_SECRET");
|
|
16902
|
-
*
|
|
16903
|
-
* // Reading a required variable, also rejecting empty strings
|
|
16904
|
-
* const dbPassword = __sys__.__env__.getStrict("DB_PASSWORD", { rejectEmpty: true });
|
|
16905
|
-
*
|
|
16906
|
-
* // Writing a variable at runtime
|
|
16907
|
-
* __sys__.__env__.set("FEATURE_FLAG_BETA", "true");
|
|
16908
|
-
*
|
|
16909
|
-
* // Checking the execution mode
|
|
16910
|
-
* if (__sys__.__env__.isProduction()) {
|
|
16911
|
-
* // Apply production hardening
|
|
16912
|
-
* }
|
|
16913
|
-
* ```
|
|
16914
|
-
*
|
|
16915
|
-
* ---
|
|
16916
|
-
*
|
|
16917
|
-
* @see {@link IEnvApi} for the public interface contract.
|
|
16918
|
-
* @see {@link EnvAccessError} for the error thrown by `getStrict`.
|
|
16919
|
-
* @see {@link EnvKeyError} for the error thrown on invalid keys or values.
|
|
16920
|
-
* @see {@link EnvStoreError} for the error thrown when the store is not ready.
|
|
16921
|
-
*/
|
|
16922
|
-
__env__;
|
|
16923
17915
|
/**
|
|
16924
17916
|
* **Initialize System API**
|
|
16925
17917
|
*
|
|
@@ -16931,13 +17923,15 @@ class XyPrissFS {
|
|
|
16931
17923
|
*/
|
|
16932
17924
|
constructor(context) {
|
|
16933
17925
|
this._internalRoot = context.__root__;
|
|
16934
|
-
|
|
16935
|
-
this.
|
|
16936
|
-
this.
|
|
16937
|
-
this.
|
|
16938
|
-
this.
|
|
16939
|
-
this.
|
|
16940
|
-
this.
|
|
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);
|
|
16941
17935
|
}
|
|
16942
17936
|
}
|
|
16943
17937
|
|
|
@@ -17495,18 +18489,18 @@ class MetaConfigRunner {
|
|
|
17495
18489
|
* This loader identifies the project root and applies system variables to the global __sys__ object.
|
|
17496
18490
|
*/
|
|
17497
18491
|
class ConfigLoader {
|
|
17498
|
-
|
|
18492
|
+
appliedRoots = new Set();
|
|
17499
18493
|
packageJson = null;
|
|
17500
18494
|
metaRunner = new MetaConfigRunner();
|
|
17501
18495
|
sys = getSysApi$1();
|
|
17502
18496
|
/**
|
|
17503
18497
|
* Load all xypriss.config.json files found in the project and apply configurations
|
|
17504
18498
|
*/
|
|
17505
|
-
loadAndApplySysConfig() {
|
|
17506
|
-
|
|
18499
|
+
loadAndApplySysConfig(targetRoot) {
|
|
18500
|
+
const root = targetRoot || getCallerProjectRoot() || __sys__$1.__root__;
|
|
18501
|
+
if (!root || this.appliedRoots.has(root))
|
|
17507
18502
|
return;
|
|
17508
|
-
this.
|
|
17509
|
-
const root = getCallerProjectRoot() || __sys__$1.__root__;
|
|
18503
|
+
this.appliedRoots.add(root);
|
|
17510
18504
|
logger$1.debug("server", `ConfigLoader: Initializing discovery from root: ${root}`);
|
|
17511
18505
|
const configFiles = [];
|
|
17512
18506
|
// Only look for config at the absolute project root (preferring .jsonc)
|
|
@@ -17665,7 +18659,18 @@ class ConfigLoader {
|
|
|
17665
18659
|
}
|
|
17666
18660
|
}
|
|
17667
18661
|
if (allPermissions.length > 0) {
|
|
17668
|
-
__sys__$1.vars.
|
|
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);
|
|
17669
18674
|
logger$1.debug("server", `Loaded ${allPermissions.length} plugin permission rules from configuration`);
|
|
17670
18675
|
}
|
|
17671
18676
|
}
|
|
@@ -17694,8 +18699,6 @@ class ConfigLoader {
|
|
|
17694
18699
|
}
|
|
17695
18700
|
}
|
|
17696
18701
|
loadPackageJson(root) {
|
|
17697
|
-
if (this.packageJson)
|
|
17698
|
-
return;
|
|
17699
18702
|
const pkgPath = this.sys.path.join(root, "package.json");
|
|
17700
18703
|
if (this.sys.fs.exist(pkgPath)) {
|
|
17701
18704
|
try {
|
|
@@ -19083,6 +20086,15 @@ class XyPrisRequestApp {
|
|
|
19083
20086
|
if (prop === "xems") {
|
|
19084
20087
|
return this.appInstance?.xems || this.appInstance?._xems;
|
|
19085
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
|
+
}
|
|
19086
20098
|
// Otherwise, proxy to appInstance
|
|
19087
20099
|
if (this.appInstance && prop in this.appInstance) {
|
|
19088
20100
|
const value = this.appInstance[prop];
|
|
@@ -19148,10 +20160,15 @@ class XyPrisRequestApp {
|
|
|
19148
20160
|
}
|
|
19149
20161
|
/**
|
|
19150
20162
|
* Provides direct access to the application's Plugin Manager.
|
|
20163
|
+
* Strictly restricted to genuine engine core callers.
|
|
19151
20164
|
*
|
|
19152
|
-
* @returns The PluginManager instance associated with the application.
|
|
20165
|
+
* @returns The PluginManager instance associated with the application, or undefined for unauthorized callers.
|
|
19153
20166
|
*/
|
|
19154
20167
|
get pluginManager() {
|
|
20168
|
+
const caller = getVerifiedCallerInfo();
|
|
20169
|
+
if (caller.isUntrusted || !isEngineCorePath(caller.callerFile)) {
|
|
20170
|
+
return undefined;
|
|
20171
|
+
}
|
|
19155
20172
|
return this.appInstance?.pluginManager;
|
|
19156
20173
|
}
|
|
19157
20174
|
}
|
|
@@ -27968,9 +28985,12 @@ class XHSCWorker {
|
|
|
27968
28985
|
});
|
|
27969
28986
|
}
|
|
27970
28987
|
register() {
|
|
28988
|
+
const token = process.env.XYPRISS_INTERNAL_TOKEN ||
|
|
28989
|
+
process.env.XYPRISS_XESS_AUTH_TOKEN ||
|
|
28990
|
+
"";
|
|
27971
28991
|
const message = {
|
|
27972
28992
|
type: "RegisterWorker",
|
|
27973
|
-
payload: { id: this.workerId },
|
|
28993
|
+
payload: { id: this.workerId, ...(token ? { token } : {}) },
|
|
27974
28994
|
};
|
|
27975
28995
|
this.sendMessage(message);
|
|
27976
28996
|
this.syncRoutes();
|
|
@@ -28601,6 +29621,12 @@ class EngineManager {
|
|
|
28601
29621
|
const internalSig = getInternalSignature();
|
|
28602
29622
|
this.logger.debug("server", `Starting XHSC engine: ${args.join(" ")}`);
|
|
28603
29623
|
const binaryPath = this.runner.getBinaryPath();
|
|
29624
|
+
const libportSock = process.env.LIBPORT_SOCKET_PATH ||
|
|
29625
|
+
globalThis.__sys__?.__env__?.get("LIBPORT_SOCKET_PATH") ||
|
|
29626
|
+
path.join(tmpDir, "libport.sock");
|
|
29627
|
+
const xessIpcSock = process.env.XESS_IPC_SOCKET ||
|
|
29628
|
+
globalThis.__sys__?.__env__?.get("XESS_IPC_SOCKET") ||
|
|
29629
|
+
path.join(tmpDir, "xess", "xess.sock");
|
|
28604
29630
|
const child = node_child_process.spawn(binaryPath, args, {
|
|
28605
29631
|
stdio: ["ignore", "pipe", "pipe"],
|
|
28606
29632
|
detached: true,
|
|
@@ -28609,6 +29635,10 @@ class EngineManager {
|
|
|
28609
29635
|
XYPRISS_USER_TMP: tmpDir,
|
|
28610
29636
|
XESS_SESSION_TMP: tmpDir,
|
|
28611
29637
|
XYPRISS_SESSION_HASH: sessionHash,
|
|
29638
|
+
LIBPORT_SOCKET_PATH: libportSock,
|
|
29639
|
+
PORT_SOCKET_PATH: libportSock,
|
|
29640
|
+
XPM_SOCKET_PATH: libportSock,
|
|
29641
|
+
XESS_IPC_SOCKET: xessIpcSock,
|
|
28612
29642
|
...(internalSig
|
|
28613
29643
|
? { XYPRISS_INTERNAL_TOKEN: internalSig }
|
|
28614
29644
|
: {}),
|
|
@@ -29238,116 +30268,6 @@ class RouteManager {
|
|
|
29238
30268
|
}
|
|
29239
30269
|
}
|
|
29240
30270
|
|
|
29241
|
-
/**
|
|
29242
|
-
* **XHSC Direct IPC Client**
|
|
29243
|
-
*
|
|
29244
|
-
* Provides high-performance, direct Unix socket communication with the
|
|
29245
|
-
* XHSC background server, bypassing the overhead of process spawning.
|
|
29246
|
-
*/
|
|
29247
|
-
class XHSCDirectIPC {
|
|
29248
|
-
ipcPath;
|
|
29249
|
-
socket = null;
|
|
29250
|
-
constructor(ipcPath) {
|
|
29251
|
-
this.ipcPath = ipcPath;
|
|
29252
|
-
}
|
|
29253
|
-
/**
|
|
29254
|
-
* **Connect to the IPC Server**
|
|
29255
|
-
*/
|
|
29256
|
-
async connect() {
|
|
29257
|
-
if (this.socket && !this.socket.destroyed)
|
|
29258
|
-
return;
|
|
29259
|
-
return new Promise((resolve, reject) => {
|
|
29260
|
-
this.socket = net__namespace.connect(this.ipcPath, () => {
|
|
29261
|
-
resolve();
|
|
29262
|
-
});
|
|
29263
|
-
this.socket.on("error", (err) => {
|
|
29264
|
-
reject(err);
|
|
29265
|
-
});
|
|
29266
|
-
});
|
|
29267
|
-
}
|
|
29268
|
-
/**
|
|
29269
|
-
* **Send a Command and Wait for Response**
|
|
29270
|
-
*/
|
|
29271
|
-
async sendCommand(module, action, params = {}) {
|
|
29272
|
-
await this.connect();
|
|
29273
|
-
return new Promise((resolve, reject) => {
|
|
29274
|
-
const timeout = setTimeout(() => {
|
|
29275
|
-
cleanup();
|
|
29276
|
-
reject(new Error(`XHSC Engine request timed out: ${module}.${action}`));
|
|
29277
|
-
}, 5000);
|
|
29278
|
-
const message = {
|
|
29279
|
-
type: "CoreCommand",
|
|
29280
|
-
payload: {
|
|
29281
|
-
module,
|
|
29282
|
-
action,
|
|
29283
|
-
params,
|
|
29284
|
-
},
|
|
29285
|
-
};
|
|
29286
|
-
const payload = Buffer.from(JSON.stringify(message));
|
|
29287
|
-
const size = Buffer.alloc(4);
|
|
29288
|
-
size.writeUInt32BE(payload.length, 0);
|
|
29289
|
-
let buffer = Buffer.alloc(0);
|
|
29290
|
-
const cleanup = () => {
|
|
29291
|
-
clearTimeout(timeout);
|
|
29292
|
-
this.socket?.removeListener("data", onData);
|
|
29293
|
-
this.socket?.removeListener("error", onError);
|
|
29294
|
-
this.socket?.removeListener("close", onClose);
|
|
29295
|
-
};
|
|
29296
|
-
const onData = (data) => {
|
|
29297
|
-
buffer = Buffer.concat([buffer, data]);
|
|
29298
|
-
if (buffer.length >= 4) {
|
|
29299
|
-
const resSize = buffer.readUInt32BE(0);
|
|
29300
|
-
if (buffer.length >= 4 + resSize) {
|
|
29301
|
-
const resPayload = buffer.subarray(4, 4 + resSize);
|
|
29302
|
-
cleanup();
|
|
29303
|
-
try {
|
|
29304
|
-
const resMsg = JSON.parse(resPayload.toString());
|
|
29305
|
-
if (resMsg.type === "Response") {
|
|
29306
|
-
const res = resMsg.payload;
|
|
29307
|
-
if (res.status === "error") {
|
|
29308
|
-
reject(new Error(res.error));
|
|
29309
|
-
}
|
|
29310
|
-
else {
|
|
29311
|
-
resolve(res.data);
|
|
29312
|
-
}
|
|
29313
|
-
}
|
|
29314
|
-
else {
|
|
29315
|
-
reject(new Error("Unexpected message type: " +
|
|
29316
|
-
resMsg.type));
|
|
29317
|
-
}
|
|
29318
|
-
}
|
|
29319
|
-
catch (e) {
|
|
29320
|
-
reject(e);
|
|
29321
|
-
}
|
|
29322
|
-
}
|
|
29323
|
-
}
|
|
29324
|
-
};
|
|
29325
|
-
const onError = (err) => {
|
|
29326
|
-
cleanup();
|
|
29327
|
-
reject(err);
|
|
29328
|
-
};
|
|
29329
|
-
const onClose = () => {
|
|
29330
|
-
cleanup();
|
|
29331
|
-
reject(new Error("XHSC Engine connection closed unexpectedly during request"));
|
|
29332
|
-
};
|
|
29333
|
-
this.socket.on("data", onData);
|
|
29334
|
-
this.socket.on("error", onError);
|
|
29335
|
-
this.socket.on("close", onClose);
|
|
29336
|
-
this.socket.write(size);
|
|
29337
|
-
this.socket.write(payload);
|
|
29338
|
-
});
|
|
29339
|
-
}
|
|
29340
|
-
/**
|
|
29341
|
-
* **Close Connection**
|
|
29342
|
-
*/
|
|
29343
|
-
close() {
|
|
29344
|
-
if (this.socket) {
|
|
29345
|
-
this.socket.destroy();
|
|
29346
|
-
this.socket = null;
|
|
29347
|
-
}
|
|
29348
|
-
}
|
|
29349
|
-
}
|
|
29350
|
-
|
|
29351
30271
|
/***************************************************************************
|
|
29352
30272
|
* ConsoleInterceptor.ts - Lightweight Console Interception System
|
|
29353
30273
|
* Delegated to XHSC (Go) for heavy lifting
|
|
@@ -29458,13 +30378,10 @@ class ConsoleInterceptor {
|
|
|
29458
30378
|
this.patchConsole();
|
|
29459
30379
|
this.isIntercepting = true;
|
|
29460
30380
|
this.stats.isActive = true;
|
|
29461
|
-
//
|
|
29462
|
-
|
|
29463
|
-
|
|
29464
|
-
|
|
29465
|
-
const ipc = new XHSCDirectIPC(this.ipcPath);
|
|
29466
|
-
await ipc.sendCommand("console", "update-config", this.config);
|
|
29467
|
-
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);
|
|
29468
30385
|
}
|
|
29469
30386
|
}
|
|
29470
30387
|
catch (err) {
|
|
@@ -29638,33 +30555,31 @@ class ConsoleInterceptor {
|
|
|
29638
30555
|
console[method] = this.originalConsole[method];
|
|
29639
30556
|
});
|
|
29640
30557
|
this.originalConsole = {};
|
|
29641
|
-
|
|
29642
|
-
|
|
29643
|
-
|
|
29644
|
-
await
|
|
30558
|
+
try {
|
|
30559
|
+
const synapx = SynapxClient.getInstance();
|
|
30560
|
+
if (synapx.isAvailable()) {
|
|
30561
|
+
await synapx.call("console", "update-config", [], {
|
|
29645
30562
|
...this.config,
|
|
29646
30563
|
enabled: false,
|
|
29647
30564
|
});
|
|
29648
|
-
ipc.close();
|
|
29649
|
-
}
|
|
29650
|
-
catch (err) {
|
|
29651
|
-
// Ignore stop errors
|
|
29652
30565
|
}
|
|
29653
30566
|
}
|
|
30567
|
+
catch {
|
|
30568
|
+
// Ignore stop errors
|
|
30569
|
+
}
|
|
29654
30570
|
this.isIntercepting = false;
|
|
29655
30571
|
this.stats.isActive = false;
|
|
29656
30572
|
}
|
|
29657
30573
|
async getStats() {
|
|
29658
|
-
if (this.
|
|
30574
|
+
if (this.isIntercepting) {
|
|
29659
30575
|
try {
|
|
29660
|
-
const
|
|
29661
|
-
|
|
29662
|
-
|
|
29663
|
-
|
|
29664
|
-
|
|
29665
|
-
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
|
+
}
|
|
29666
30581
|
}
|
|
29667
|
-
catch
|
|
30582
|
+
catch {
|
|
29668
30583
|
return { ...this.stats };
|
|
29669
30584
|
}
|
|
29670
30585
|
}
|
|
@@ -29675,16 +30590,15 @@ class ConsoleInterceptor {
|
|
|
29675
30590
|
...this.config,
|
|
29676
30591
|
...newConfig,
|
|
29677
30592
|
};
|
|
29678
|
-
|
|
29679
|
-
|
|
29680
|
-
|
|
29681
|
-
await
|
|
29682
|
-
ipc.close();
|
|
29683
|
-
}
|
|
29684
|
-
catch (err) {
|
|
29685
|
-
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);
|
|
29686
30597
|
}
|
|
29687
30598
|
}
|
|
30599
|
+
catch (err) {
|
|
30600
|
+
this.logger.error("console", `Failed to update console config: ${err.message}`);
|
|
30601
|
+
}
|
|
29688
30602
|
}
|
|
29689
30603
|
setPluginEngine(engine) {
|
|
29690
30604
|
this.pluginEngine = engine;
|
|
@@ -34457,11 +35371,156 @@ const HOOK_METADATA = {
|
|
|
34457
35371
|
},
|
|
34458
35372
|
};
|
|
34459
35373
|
|
|
34460
|
-
|
|
34461
|
-
|
|
34462
|
-
|
|
34463
|
-
|
|
34464
|
-
|
|
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
|
+
}
|
|
34465
35524
|
|
|
34466
35525
|
/***************************************************************************
|
|
34467
35526
|
* XyPrissJS - Fast And Secure
|
|
@@ -34522,8 +35581,20 @@ class PermissionManager {
|
|
|
34522
35581
|
return false;
|
|
34523
35582
|
}
|
|
34524
35583
|
// --- BUILT-IN PLUGINS BYPASS ---
|
|
34525
|
-
// Built-in (official) plugins always bypass security checks for full capabilities
|
|
34526
|
-
|
|
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
|
+
}
|
|
34527
35598
|
return true;
|
|
34528
35599
|
}
|
|
34529
35600
|
const hookId = HOOK_ID_MAP[internalHookName] || internalHookName;
|
|
@@ -34613,13 +35684,35 @@ class PermissionManager {
|
|
|
34613
35684
|
* Creates a masked version of the request object for security in plugin hooks.
|
|
34614
35685
|
* Prevents plugins from accessing sensitive data like body, query, and cookies
|
|
34615
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.
|
|
34616
35689
|
*/
|
|
34617
35690
|
maskRequest(req, pluginName) {
|
|
34618
35691
|
if (!req)
|
|
34619
35692
|
return req;
|
|
34620
|
-
|
|
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) {
|
|
34621
35713
|
return req;
|
|
34622
35714
|
}
|
|
35715
|
+
let allowSensitiveData = false;
|
|
34623
35716
|
if (pluginName) {
|
|
34624
35717
|
const permissions = __sys__$1?.vars.get("pluginPermissions");
|
|
34625
35718
|
if (permissions) {
|
|
@@ -34630,7 +35723,7 @@ class PermissionManager {
|
|
|
34630
35723
|
allowedHooks.includes(PluginHookIds.ACCESS_SENSITIVE_DATA);
|
|
34631
35724
|
const isDenied = pluginPerm.deniedHooks?.includes(PluginHookIds.ACCESS_SENSITIVE_DATA);
|
|
34632
35725
|
if (isAllowed && !isDenied) {
|
|
34633
|
-
|
|
35726
|
+
allowSensitiveData = true;
|
|
34634
35727
|
}
|
|
34635
35728
|
}
|
|
34636
35729
|
}
|
|
@@ -34645,7 +35738,52 @@ class PermissionManager {
|
|
|
34645
35738
|
];
|
|
34646
35739
|
return new Proxy(req, {
|
|
34647
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
|
+
}
|
|
34648
35783
|
if (typeof prop === "string" && prop === "headers") {
|
|
35784
|
+
if (allowSensitiveData) {
|
|
35785
|
+
return target[prop];
|
|
35786
|
+
}
|
|
34649
35787
|
const originalHeaders = target[prop] || {};
|
|
34650
35788
|
const safeHeaders = [
|
|
34651
35789
|
"user-agent",
|
|
@@ -34669,6 +35807,9 @@ class PermissionManager {
|
|
|
34669
35807
|
}
|
|
34670
35808
|
if (typeof prop === "string" &&
|
|
34671
35809
|
sensitiveFields.includes(prop)) {
|
|
35810
|
+
if (allowSensitiveData) {
|
|
35811
|
+
return target[prop];
|
|
35812
|
+
}
|
|
34672
35813
|
return `[${pluginName}] Access to sensitive request data '${prop}' is restricted for security reasons. Requires XHS.PERM.SECURITY.SENSITIVE_DATA.`;
|
|
34673
35814
|
}
|
|
34674
35815
|
const value = target[prop];
|
|
@@ -34800,7 +35941,7 @@ const schm = reliantType.Interface({
|
|
|
34800
35941
|
function validatePlgInput(d) {
|
|
34801
35942
|
try {
|
|
34802
35943
|
// First check if it's an official whitelisted plugin
|
|
34803
|
-
const isOfficial =
|
|
35944
|
+
const isOfficial = isOfficialPlugin(d.name);
|
|
34804
35945
|
// If not official, enforce strict alphanumeric/hyphen rules
|
|
34805
35946
|
if (!isOfficial) {
|
|
34806
35947
|
if (!/^[a-zA-Z0-9-]+$/.test(d.name)) {
|
|
@@ -34865,6 +36006,16 @@ class PluginSecurity {
|
|
|
34865
36006
|
*/
|
|
34866
36007
|
verifyContract(plugin, callerStack, isExecutionPhase = false) {
|
|
34867
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
|
+
}
|
|
34868
36019
|
// We now prioritize the root provided explicitly via Plugin.create(..., __sys__)
|
|
34869
36020
|
let pluginRoot = plugin.__root__ || "";
|
|
34870
36021
|
if (!pluginRoot && !isExecutionPhase) {
|
|
@@ -34876,8 +36027,8 @@ class PluginSecurity {
|
|
|
34876
36027
|
// If we still have no root, we cannot verify the contract.
|
|
34877
36028
|
// During registration, this is a FATAL error if we're not inside the core.
|
|
34878
36029
|
if (!isExecutionPhase) {
|
|
34879
|
-
const
|
|
34880
|
-
if (
|
|
36030
|
+
const caller = getVerifiedCallerInfo();
|
|
36031
|
+
if (claimsOfficial && isEngineCorePath(caller.callerFile)) {
|
|
34881
36032
|
// Safe fallback for official built-in plugins if discovery failed
|
|
34882
36033
|
return "";
|
|
34883
36034
|
}
|
|
@@ -34885,14 +36036,16 @@ class PluginSecurity {
|
|
|
34885
36036
|
}
|
|
34886
36037
|
return "";
|
|
34887
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
|
+
}
|
|
34888
36044
|
// Always verify if it's NOT a core framework path
|
|
34889
|
-
|
|
34890
|
-
|
|
34891
|
-
if (!
|
|
34892
|
-
|
|
34893
|
-
if (!contractOk) {
|
|
34894
|
-
this.throwViolation(plugin.name, pluginRoot);
|
|
34895
|
-
}
|
|
36045
|
+
if (!isCorePath) {
|
|
36046
|
+
const contractOk = verifyPluginContract(pluginRoot, plugin.name);
|
|
36047
|
+
if (!contractOk) {
|
|
36048
|
+
this.throwViolation(plugin.name, pluginRoot);
|
|
34896
36049
|
}
|
|
34897
36050
|
// Perform static source code analysis to catch ESM namespace imports
|
|
34898
36051
|
// which bypass the execution-level NativeApiBlocker.
|
|
@@ -34903,6 +36056,18 @@ class PluginSecurity {
|
|
|
34903
36056
|
plugin.__root__ = pluginRoot;
|
|
34904
36057
|
return pluginRoot;
|
|
34905
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
|
+
}
|
|
34906
36071
|
/**
|
|
34907
36072
|
* Throw a security contract violation error
|
|
34908
36073
|
*/
|
|
@@ -34995,7 +36160,7 @@ class PluginSecurity {
|
|
|
34995
36160
|
* and verifying Ed25519 signature of xypriss.plugin.xsig
|
|
34996
36161
|
*/
|
|
34997
36162
|
verifyContentIntegrity(pluginRoot, pluginName) {
|
|
34998
|
-
const isOfficial =
|
|
36163
|
+
const isOfficial = isOfficialPlugin(pluginName) && isCoreFrameworkPath(pluginRoot);
|
|
34999
36164
|
if (isOfficial || isCoreFrameworkPath(pluginRoot)) {
|
|
35000
36165
|
return;
|
|
35001
36166
|
}
|
|
@@ -35173,7 +36338,7 @@ class PluginSecurity {
|
|
|
35173
36338
|
const target = server.app;
|
|
35174
36339
|
// --- SECURITY CHECK: Configuration Access ---
|
|
35175
36340
|
if (prop === "configs") {
|
|
35176
|
-
if (
|
|
36341
|
+
if (isOfficialPlugin(pluginName)) {
|
|
35177
36342
|
return target[prop];
|
|
35178
36343
|
}
|
|
35179
36344
|
const hasPermission = permissionManager.checkPermission(pluginName, "configs");
|
|
@@ -35197,7 +36362,7 @@ class PluginSecurity {
|
|
|
35197
36362
|
}
|
|
35198
36363
|
// Intercept the method execution to wrap the actual route handlers/middlewares
|
|
35199
36364
|
return (...args) => {
|
|
35200
|
-
const isOfficial =
|
|
36365
|
+
const isOfficial = isOfficialPlugin(pluginName);
|
|
35201
36366
|
// --- SECURITY ENFORCEMENT: Routing Boundaries ---
|
|
35202
36367
|
if (allowedRoutingMethods.includes(prop) && args.length > 0 && !isOfficial) {
|
|
35203
36368
|
const pathArg = args[0];
|
|
@@ -35255,7 +36420,7 @@ class PluginSecurity {
|
|
|
35255
36420
|
},
|
|
35256
36421
|
set: (value) => {
|
|
35257
36422
|
const target = server.app;
|
|
35258
|
-
if (prop === "xems" &&
|
|
36423
|
+
if (prop === "xems" && isOfficialPlugin(pluginName)) {
|
|
35259
36424
|
try {
|
|
35260
36425
|
target.xems = value;
|
|
35261
36426
|
}
|
|
@@ -36287,7 +37452,13 @@ class XemsRunner {
|
|
|
36287
37452
|
const hash = process.env.XYPRISS_SESSION_HASH || String(process.pid);
|
|
36288
37453
|
this.socketPath = path.join(sessionDir, `xems_${hash}.sock`);
|
|
36289
37454
|
// Clean stale socket if it exists
|
|
36290
|
-
if (
|
|
37455
|
+
if (process.platform === "win32") {
|
|
37456
|
+
try {
|
|
37457
|
+
fs$1.unlinkSync(this.socketPath);
|
|
37458
|
+
}
|
|
37459
|
+
catch { }
|
|
37460
|
+
}
|
|
37461
|
+
else if (fs$1.existsSync(this.socketPath)) {
|
|
36291
37462
|
try {
|
|
36292
37463
|
fs$1.unlinkSync(this.socketPath);
|
|
36293
37464
|
}
|
|
@@ -36327,7 +37498,19 @@ class XemsRunner {
|
|
|
36327
37498
|
// Wait for socket to become active (up to 3 seconds)
|
|
36328
37499
|
let connected = false;
|
|
36329
37500
|
for (let i = 0; i < 30; i++) {
|
|
36330
|
-
|
|
37501
|
+
let exists = false;
|
|
37502
|
+
try {
|
|
37503
|
+
if (process.platform === "win32") {
|
|
37504
|
+
const dir = path.dirname(this.socketPath);
|
|
37505
|
+
const file = path.basename(this.socketPath);
|
|
37506
|
+
exists = fs$1.existsSync(dir) && fs$1.readdirSync(dir).includes(file);
|
|
37507
|
+
}
|
|
37508
|
+
else {
|
|
37509
|
+
exists = fs$1.existsSync(this.socketPath);
|
|
37510
|
+
}
|
|
37511
|
+
}
|
|
37512
|
+
catch { }
|
|
37513
|
+
if (exists) {
|
|
36331
37514
|
connected = true;
|
|
36332
37515
|
break;
|
|
36333
37516
|
}
|
|
@@ -36623,6 +37806,7 @@ class XemsBuiltinPlugin {
|
|
|
36623
37806
|
version = "1.1.23";
|
|
36624
37807
|
type = "security";
|
|
36625
37808
|
description = "XyPriss Entry Management System (Session & Storage)";
|
|
37809
|
+
__root__ = ENGINE_CORE_DIR;
|
|
36626
37810
|
runner;
|
|
36627
37811
|
sessionOptions = {
|
|
36628
37812
|
sandbox: "xems.internal-session",
|
|
@@ -38418,11 +39602,15 @@ class XMSStartupUI {
|
|
|
38418
39602
|
console[m] = (...args) => {
|
|
38419
39603
|
const str = args
|
|
38420
39604
|
.map((a) => typeof a === "object"
|
|
38421
|
-
? JSON.stringify(a)
|
|
39605
|
+
? (a instanceof Error ? (a.stack || a.message) : JSON.stringify(a))
|
|
38422
39606
|
: String(a))
|
|
38423
39607
|
.join(" ");
|
|
38424
39608
|
this.consoleBuffer.push(str);
|
|
38425
|
-
|
|
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) {
|
|
38426
39614
|
this.printPassthroughLog(str);
|
|
38427
39615
|
}
|
|
38428
39616
|
};
|
|
@@ -38439,10 +39627,11 @@ class XMSStartupUI {
|
|
|
38439
39627
|
this.originalConsole = {};
|
|
38440
39628
|
}
|
|
38441
39629
|
/**
|
|
38442
|
-
* Check if a log entry represents a critical startup milestone
|
|
39630
|
+
* Check if a log entry represents a critical startup milestone or diagnostic alert
|
|
38443
39631
|
* that must remain visible even during quiet initialization.
|
|
38444
39632
|
*
|
|
38445
39633
|
* Allowed:
|
|
39634
|
+
* - Errors, unhandled rejections, exceptions, violations, and emergency alerts
|
|
38446
39635
|
* - "Initializing Version XHSC..." (XHSC binary version identification)
|
|
38447
39636
|
* - "Initializing XRMS (XyPriss Request Management System)..." (XRMS stack initialization)
|
|
38448
39637
|
*/
|
|
@@ -38450,18 +39639,28 @@ class XMSStartupUI {
|
|
|
38450
39639
|
if (!message)
|
|
38451
39640
|
return false;
|
|
38452
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
|
+
}
|
|
38453
39647
|
return (/(?:i|n)?nitializing version xhsc/i.test(clean) ||
|
|
38454
39648
|
/(?:i|n)?nitializing xrms/i.test(clean));
|
|
38455
39649
|
}
|
|
38456
39650
|
handleCapturedLog(entry) {
|
|
38457
39651
|
const fullMsg = [
|
|
38458
39652
|
entry.message,
|
|
38459
|
-
...(entry.args || []).map((a) => typeof a === "object"
|
|
39653
|
+
...(entry.args || []).map((a) => typeof a === "object"
|
|
39654
|
+
? (a instanceof Error ? (a.stack || a.message) : JSON.stringify(a))
|
|
39655
|
+
: String(a)),
|
|
38460
39656
|
].join(" ");
|
|
38461
|
-
|
|
39657
|
+
// Always passthrough errors, warnings, and vital startup milestones
|
|
39658
|
+
if (entry.level === "error" ||
|
|
39659
|
+
entry.level === "warn" ||
|
|
39660
|
+
this.isAllowedStartupLog(fullMsg)) {
|
|
38462
39661
|
const formatted = Logger.getInstance().formatEntry(entry);
|
|
38463
39662
|
const extraArgs = entry.args && entry.args.length > 0
|
|
38464
|
-
? ` ${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(" ")}`
|
|
38465
39664
|
: "";
|
|
38466
39665
|
this.printPassthroughLog(`${formatted}${extraArgs}`);
|
|
38467
39666
|
}
|