xypriss 9.14.18 → 9.14.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cjs/index.js CHANGED
@@ -18,7 +18,6 @@ var events = require('events');
18
18
  var vm = require('vm');
19
19
  var compression = require('xypriss-compression');
20
20
  var strulink = require('strulink');
21
- var readline = require('node:readline');
22
21
  var promises = require('node:fs/promises');
23
22
  var http = require('http');
24
23
  var stream = require('stream');
@@ -50,7 +49,6 @@ var net__namespace = /*#__PURE__*/_interopNamespaceDefault(net);
50
49
  var fs__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(fs$1);
51
50
  var path__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(path$1);
52
51
  var vm__namespace = /*#__PURE__*/_interopNamespaceDefault(vm);
53
- var readline__namespace = /*#__PURE__*/_interopNamespaceDefault(readline);
54
52
 
55
53
  /**
56
54
  * Type definitions for Console Interception System
@@ -18274,6 +18272,9 @@ class XyPrisRequestApp {
18274
18272
  if (prop in target || prop === "constructor") {
18275
18273
  return Reflect.get(target, prop, receiver);
18276
18274
  }
18275
+ if (prop === "xems") {
18276
+ return this.appInstance?.xems || this.appInstance?._xems;
18277
+ }
18277
18278
  // Otherwise, proxy to appInstance
18278
18279
  if (this.appInstance && prop in this.appInstance) {
18279
18280
  const value = this.appInstance[prop];
@@ -29687,11 +29688,19 @@ class XyprissApp {
29687
29688
  const self = this;
29688
29689
  return new Proxy(this, {
29689
29690
  set(target, prop, value) {
29691
+ if (prop === "xems" || prop === "_xems") {
29692
+ target[prop] = value;
29693
+ return true;
29694
+ }
29690
29695
  const errorMsg = `[XyPriss Security] Mutation Attempt Detected: Application instance is immutable after creation. Property '${String(prop)}' cannot be changed.`;
29691
29696
  self.logger.error("security", errorMsg);
29692
29697
  throw new Error(errorMsg);
29693
29698
  },
29694
29699
  defineProperty(target, prop, descriptor) {
29700
+ if (prop === "xems" || prop === "_xems") {
29701
+ Object.defineProperty(target, prop, descriptor);
29702
+ return true;
29703
+ }
29695
29704
  const errorMsg = `[XyPriss Security] Mutation Attempt Detected: Cannot define new property '${String(prop)}' on locked app instance.`;
29696
29705
  self.logger.error("security", errorMsg);
29697
29706
  throw new Error(errorMsg);
@@ -34090,6 +34099,7 @@ class PluginSecurity {
34090
34099
  ...allowedMiddlewareMethods,
34091
34100
  "logger",
34092
34101
  "configs",
34102
+ "xems",
34093
34103
  ];
34094
34104
  // Facade for the app instance to avoid Proxy invariants on non-configurable properties
34095
34105
  const appFacade = {};
@@ -34108,6 +34118,9 @@ class PluginSecurity {
34108
34118
  return undefined;
34109
34119
  }
34110
34120
  }
34121
+ if (prop === "xems") {
34122
+ return target.xems || target._xems;
34123
+ }
34111
34124
  const originalMethod = target[prop];
34112
34125
  if (typeof originalMethod === "function") {
34113
34126
  if (allowedRoutingMethods.includes(prop) || allowedMiddlewareMethods.includes(prop)) {
@@ -34175,7 +34188,26 @@ class PluginSecurity {
34175
34188
  return originalMethod.bind(target);
34176
34189
  }
34177
34190
  return originalMethod;
34178
- }
34191
+ },
34192
+ set: (value) => {
34193
+ const target = server.app;
34194
+ if (prop === "xems" && OFFICIAL_PLUGINS.includes(pluginName)) {
34195
+ try {
34196
+ target.xems = value;
34197
+ }
34198
+ catch { }
34199
+ try {
34200
+ target._xems = value;
34201
+ }
34202
+ catch { }
34203
+ }
34204
+ else {
34205
+ try {
34206
+ target[prop] = value;
34207
+ }
34208
+ catch { }
34209
+ }
34210
+ },
34179
34211
  });
34180
34212
  }
34181
34213
  // Facade for the server instance
@@ -34990,6 +35022,9 @@ class XemsError extends Error {
34990
35022
  class XemsRunner {
34991
35023
  constructor(options = {}) {
34992
35024
  this.process = null;
35025
+ this.synapxClient = null;
35026
+ this.socketPath = null;
35027
+ this.initPromise = null;
34993
35028
  this.queue = [];
34994
35029
  this.isReady = false;
34995
35030
  this.options = {};
@@ -35052,9 +35087,21 @@ class XemsRunner {
35052
35087
  // Remove the close listener before killing to prevent auto-respawn in a loop
35053
35088
  this.process.removeAllListeners("close");
35054
35089
  this.process.kill();
35090
+ this.process = null;
35091
+ }
35092
+ if (this.synapxClient) {
35093
+ try {
35094
+ this.synapxClient.destroy();
35095
+ }
35096
+ catch { }
35097
+ this.synapxClient = null;
35055
35098
  }
35099
+ this.isReady = false;
35100
+ this.initPromise = null;
35056
35101
  // Re-init immediately
35057
- this.init();
35102
+ this.init().catch((err) => {
35103
+ this.logger.error("xems", `Failed to restart XEMS with persistence: ${err}`);
35104
+ });
35058
35105
  }
35059
35106
  /**
35060
35107
  * Finds the XEMS binary location.
@@ -35120,90 +35167,167 @@ class XemsRunner {
35120
35167
  // 5. Global fallback to PATH (Binary must be globally available)
35121
35168
  return binName;
35122
35169
  }
35123
- init() {
35124
- if (!fs.existsSync(this.binaryPath) &&
35125
- !this.binaryPath.endsWith("xems")) {
35126
- this.logger.error("xems", `Critical: Binary not found at ${this.binaryPath}`);
35127
- return; // Cannot spawn
35170
+ async init() {
35171
+ if (this.initPromise) {
35172
+ return this.initPromise;
35128
35173
  }
35129
- try {
35130
- const args = [];
35131
- if (this.options.persistPath) {
35132
- args.push("--persist", this.options.persistPath);
35133
- }
35134
- if (this.options.secret) {
35135
- args.push("--secret", this.options.secret);
35136
- }
35137
- if (this.options.cacheSize) {
35138
- args.push("--cache-size", this.options.cacheSize.toString());
35174
+ this.initPromise = (async () => {
35175
+ if (!fs.existsSync(this.binaryPath) &&
35176
+ !this.binaryPath.endsWith("xems")) {
35177
+ this.logger.error("xems", `Critical: Binary not found at ${this.binaryPath}`);
35178
+ return;
35139
35179
  }
35140
- this.process = node_child_process.spawn(this.binaryPath, args);
35141
- const rl = readline__namespace.createInterface({
35142
- input: this.process.stdout,
35143
- terminal: false,
35144
- });
35145
- rl.on("line", (line) => {
35146
- if (line.trim()) {
35147
- this.handleResponse(line);
35180
+ try {
35181
+ // Determine isolated session directory (inherits from libXESS confinement environment)
35182
+ const sessionDir = process.env.XYPRISS_USER_TMP ||
35183
+ process.env.XESS_SESSION_TMP ||
35184
+ path.resolve(process.cwd(), ".private");
35185
+ if (!fs.existsSync(sessionDir)) {
35186
+ try {
35187
+ fs.mkdirSync(sessionDir, { recursive: true });
35188
+ }
35189
+ catch { }
35148
35190
  }
35149
- });
35150
- this.process.stderr?.on("data", (data) => {
35151
- this.logger.error("xems", `[XEMS Log] ${data}`);
35152
- });
35153
- this.process.on("close", (code) => {
35154
- this.isReady = false;
35155
- if (code !== 0 && code !== null) {
35156
- this.logger.warn("xems", `Process exited unexpectedly with code ${code}. Restarting in 2s...`);
35157
- setTimeout(() => this.init(), 2000);
35191
+ // Dedicated private socket inside the mode 0700 session folder
35192
+ const hash = process.env.XYPRISS_SESSION_HASH || String(process.pid);
35193
+ this.socketPath = path.join(sessionDir, `xems_${hash}.sock`);
35194
+ // Clean stale socket if it exists
35195
+ if (fs.existsSync(this.socketPath)) {
35196
+ try {
35197
+ fs.unlinkSync(this.socketPath);
35198
+ }
35199
+ catch { }
35158
35200
  }
35159
- });
35160
- this.isReady = true;
35161
- }
35162
- catch (e) {
35163
- this.logger.error("xems", `Failed to spawn process ${e}`);
35164
- }
35165
- }
35166
- handleResponse(jsonString) {
35167
- if (this.queue.length > 0) {
35168
- const resolver = this.queue.shift();
35169
- try {
35170
- const response = JSON.parse(jsonString);
35171
- if (response.status === "error") {
35172
- // We resolve even on error to let the caller handle it via the response object,
35173
- // or we could reject. For XyPriss style, let's just return the response object.
35174
- resolver && resolver(response, null);
35201
+ const args = ["--socket", this.socketPath];
35202
+ if (this.options.persistPath) {
35203
+ args.push("--persist", this.options.persistPath);
35175
35204
  }
35176
- else {
35177
- resolver && resolver(response, null);
35205
+ // CRITICAL SECURITY REMEDIATION:
35206
+ // NEVER pass this.options.secret in CLI args!
35207
+ // It is transmitted exclusively over the authenticated libSynapx private IPC stream.
35208
+ if (this.options.cacheSize) {
35209
+ args.push("--cache-size", this.options.cacheSize.toString());
35210
+ }
35211
+ this.process = node_child_process.spawn(this.binaryPath, args, {
35212
+ stdio: ["ignore", "pipe", "pipe"],
35213
+ });
35214
+ this.process.stderr?.on("data", (data) => {
35215
+ this.logger.error("xems", `[XEMS Log] ${data}`);
35216
+ });
35217
+ this.process.on("close", (code) => {
35218
+ this.isReady = false;
35219
+ if (this.synapxClient) {
35220
+ try {
35221
+ this.synapxClient.destroy();
35222
+ }
35223
+ catch { }
35224
+ this.synapxClient = null;
35225
+ }
35226
+ this.initPromise = null;
35227
+ if (code !== 0 && code !== null) {
35228
+ this.logger.warn("xems", `Process exited unexpectedly with code ${code}. Restarting in 2s...`);
35229
+ setTimeout(() => this.init(), 2000);
35230
+ }
35231
+ });
35232
+ // Wait for socket to become active (up to 3 seconds)
35233
+ let connected = false;
35234
+ for (let i = 0; i < 30; i++) {
35235
+ if (fs.existsSync(this.socketPath)) {
35236
+ connected = true;
35237
+ break;
35238
+ }
35239
+ await new Promise((r) => setTimeout(r, 100));
35178
35240
  }
35241
+ if (!connected) {
35242
+ throw new Error(`Timeout waiting for XEMS IPC socket at ${this.socketPath}`);
35243
+ }
35244
+ // Connect SynapxClient to xems.sock
35245
+ this.synapxClient = new SynapxClient(this.socketPath);
35246
+ await this.synapxClient.connect();
35247
+ // Zero-Trust Handshake: Transmit vault secret over private IPC stream
35248
+ if (this.options.secret || this.options.persistPath) {
35249
+ await this.synapxClient.call("xems", "init", [], {
35250
+ secret: this.options.secret || "",
35251
+ persistPath: this.options.persistPath || "",
35252
+ });
35253
+ }
35254
+ this.isReady = true;
35179
35255
  }
35180
35256
  catch (e) {
35181
- this.logger.error("xems", `Failed to parse response ${e}`);
35257
+ this.logger.error("xems", `Failed to spawn/initialize XEMS process: ${e}`);
35258
+ this.initPromise = null;
35182
35259
  }
35183
- }
35260
+ })();
35261
+ return this.initPromise;
35184
35262
  }
35185
35263
  async execute(cmd) {
35186
- // Auto-initialize if process not started
35187
- if (!this.process) {
35188
- this.init();
35264
+ if (!this.process || !this.synapxClient) {
35265
+ await this.init();
35189
35266
  }
35190
- // Wait a bit if not ready (startup grace period)
35191
35267
  if (!this.isReady) {
35192
- for (let i = 0; i < 10; i++) {
35268
+ for (let i = 0; i < 30; i++) {
35193
35269
  if (this.isReady)
35194
35270
  break;
35195
35271
  await new Promise((r) => setTimeout(r, 100));
35196
35272
  }
35197
35273
  }
35198
- return new Promise((resolve, reject) => {
35199
- if (!this.isReady || !this.process || !this.process.stdin) {
35200
- reject(new XemsError(cmd.action, "XEMS not ready (process dead or initializing)"));
35201
- return;
35274
+ if (!this.isReady || !this.synapxClient) {
35275
+ throw new XemsError(cmd.action, "XEMS not ready (process dead or initializing)");
35276
+ }
35277
+ try {
35278
+ switch (cmd.action) {
35279
+ case "ping": {
35280
+ const res = await this.synapxClient.call("xems", "ping");
35281
+ return { status: "ok", data: typeof res === "object" ? res.data : res };
35282
+ }
35283
+ case "set": {
35284
+ const args = [cmd.sandbox || "default", cmd.key || "", cmd.value || ""];
35285
+ const opts = {};
35286
+ if (cmd.ttl)
35287
+ opts.ttl = cmd.ttl;
35288
+ const res = await this.synapxClient.call("xems", "set", args, opts);
35289
+ return { status: "ok", data: typeof res === "object" ? res.data : res };
35290
+ }
35291
+ case "get": {
35292
+ const args = [cmd.sandbox || "default", cmd.key || ""];
35293
+ const opts = {};
35294
+ if (cmd.rotate)
35295
+ opts.rotate = true;
35296
+ if (cmd.grace_period)
35297
+ opts.gracePeriod = cmd.grace_period;
35298
+ if (cmd.ttl)
35299
+ opts.ttl = cmd.ttl;
35300
+ const res = await this.synapxClient.call("xems", "get", args, opts);
35301
+ if (typeof res === "object" && res !== null) {
35302
+ return {
35303
+ status: "ok",
35304
+ data: res.data !== undefined ? res.data : res.value,
35305
+ new_token: res.new_token || res.newToken,
35306
+ };
35307
+ }
35308
+ return { status: "ok", data: res };
35309
+ }
35310
+ case "del": {
35311
+ const args = [cmd.sandbox || "default", cmd.key || ""];
35312
+ const res = await this.synapxClient.call("xems", "del", args);
35313
+ return { status: "ok", data: typeof res === "object" ? res.data : res };
35314
+ }
35315
+ default: {
35316
+ const res = await this.synapxClient.call("xems", cmd.action, [
35317
+ cmd.sandbox || "",
35318
+ cmd.key || "",
35319
+ cmd.value || "",
35320
+ ]);
35321
+ return { status: "ok", data: typeof res === "object" ? res.data : res };
35322
+ }
35202
35323
  }
35203
- this.queue.push((res, _err) => resolve(res));
35204
- const payload = JSON.stringify(cmd) + "\n";
35205
- this.process.stdin.write(payload);
35206
- });
35324
+ }
35325
+ catch (err) {
35326
+ return {
35327
+ status: "error",
35328
+ error: err?.message || String(err),
35329
+ };
35330
+ }
35207
35331
  }
35208
35332
  // --- Public API Sugar ---
35209
35333
  async ping() {
@@ -35312,18 +35436,38 @@ class XemsRunner {
35312
35436
  * otherwise returns this instance.
35313
35437
  */
35314
35438
  forApp(app) {
35315
- return app?.xems || this;
35439
+ if (!app)
35440
+ return this;
35441
+ const candidate = app.xems ||
35442
+ app._xems ||
35443
+ (app.appInstance && (app.appInstance.xems || app.appInstance._xems)) ||
35444
+ (app.server && (app.server.app?.xems || app.server.xems));
35445
+ return candidate || this;
35316
35446
  }
35317
35447
  /**
35318
35448
  * Forcefully stops the XEMS process and cleans up resources.
35319
35449
  */
35320
35450
  destroy() {
35451
+ if (this.synapxClient) {
35452
+ try {
35453
+ this.synapxClient.destroy();
35454
+ }
35455
+ catch { }
35456
+ this.synapxClient = null;
35457
+ }
35321
35458
  if (this.process) {
35322
35459
  this.process.removeAllListeners("close");
35323
35460
  this.process.kill();
35324
35461
  this.process = null;
35325
- this.isReady = false;
35326
35462
  }
35463
+ if (this.socketPath && fs.existsSync(this.socketPath)) {
35464
+ try {
35465
+ fs.unlinkSync(this.socketPath);
35466
+ }
35467
+ catch { }
35468
+ }
35469
+ this.isReady = false;
35470
+ this.initPromise = null;
35327
35471
  }
35328
35472
  }
35329
35473
  /**
@@ -35414,12 +35558,15 @@ class XemsBuiltinPlugin {
35414
35558
  const app = server.app;
35415
35559
  const logger = app.logger;
35416
35560
  // 1. Configuration Extraction
35417
- // Cascade defaults from global configuration if child only specified partial options or none
35561
+ // Child server xems configuration takes absolute precedence over global defaults
35418
35562
  const globalXems = ConfigurationManager.get("server")?.xems;
35419
- const localXems = app.configs?.server?.xems;
35563
+ const localXems = app.configs?.server?.xems ||
35564
+ app.configs?.xems ||
35565
+ server?.app?.configs?.server?.xems ||
35566
+ server?.app?.configs?.xems;
35420
35567
  let xemsOptions;
35421
35568
  if (localXems && globalXems && typeof globalXems === "object") {
35422
- // Intelligent cascade merge: child inherits parent defaults but can override selectively
35569
+ // Intelligent cascade merge: child inherits parent defaults, but child options strictly override
35423
35570
  xemsOptions = mergeWithDefaults(globalXems, localXems);
35424
35571
  }
35425
35572
  else if (localXems) {
@@ -35485,8 +35632,35 @@ class XemsBuiltinPlugin {
35485
35632
  cacheSize: rawResources?.cacheSize,
35486
35633
  });
35487
35634
  this.logger.debug("xems", `XemsRunner instances count: ${XemsRunner.runnersByPath?.size ?? 0} for path: ${pathStr}`);
35488
- // Attach the shared runner to the app
35489
- app.xems = this.runner;
35635
+ // Attach the runner to the app and underlying server instances
35636
+ try {
35637
+ app.xems = this.runner;
35638
+ }
35639
+ catch { }
35640
+ try {
35641
+ app._xems = this.runner;
35642
+ }
35643
+ catch { }
35644
+ if (server && server.app) {
35645
+ try {
35646
+ server.app.xems = this.runner;
35647
+ }
35648
+ catch { }
35649
+ try {
35650
+ server.app._xems = this.runner;
35651
+ }
35652
+ catch { }
35653
+ }
35654
+ if (app.server && app.server.app) {
35655
+ try {
35656
+ app.server.app.xems = this.runner;
35657
+ }
35658
+ catch { }
35659
+ try {
35660
+ app.server.app._xems = this.runner;
35661
+ }
35662
+ catch { }
35663
+ }
35490
35664
  if (rawPath) {
35491
35665
  try {
35492
35666
  this.runner.enablePersistence(rawPath, secret, {
@@ -35500,7 +35674,24 @@ class XemsBuiltinPlugin {
35500
35674
  }
35501
35675
  else {
35502
35676
  // Expose fallback runner on app
35503
- app.xems = this.runner;
35677
+ try {
35678
+ app.xems = this.runner;
35679
+ }
35680
+ catch { }
35681
+ try {
35682
+ app._xems = this.runner;
35683
+ }
35684
+ catch { }
35685
+ if (server && server.app) {
35686
+ try {
35687
+ server.app.xems = this.runner;
35688
+ }
35689
+ catch { }
35690
+ try {
35691
+ server.app._xems = this.runner;
35692
+ }
35693
+ catch { }
35694
+ }
35504
35695
  if (!isAuxiliary && xemsOptions.enable !== false) {
35505
35696
  logger.warn("plugins", "XEMS requested but mandatory 'path' or 32-byte 'secret' is missing. Please provide both.");
35506
35697
  }
@@ -37234,8 +37425,15 @@ class MultiServerManager {
37234
37425
  }
37235
37426
  // Cascade server options (specifically server.xems, cookieOptions, secret, etc.)
37236
37427
  const baseServer = this.baseConfig?.server || {};
37237
- const childServer = config.server || {};
37428
+ const childServer = { ...(config.server || {}) };
37429
+ const childXems = childServer.xems || config.xems;
37430
+ if (childXems) {
37431
+ childServer.xems = childXems;
37432
+ }
37238
37433
  const mergedServer = mergeWithDefaults(baseServer, childServer);
37434
+ if (childXems) {
37435
+ mergedServer.xems = mergeWithDefaults(baseServer.xems || {}, childXems);
37436
+ }
37239
37437
  if (config.port)
37240
37438
  mergedServer.port = config.port;
37241
37439
  if (config.host)
@@ -38485,8 +38683,19 @@ function createServer(options = {}) {
38485
38683
  ConfigurationManager.update("multiServer", options.multiServer);
38486
38684
  }
38487
38685
  const servers = (xms || []).map((server) => {
38686
+ // Hoist top-level xems if child specified it directly on MultiServerConfig
38687
+ if (server.xems && !server.server?.xems) {
38688
+ server.server = server.server || {};
38689
+ server.server.xems = server.xems;
38690
+ }
38488
38691
  // Individual server options take precedence over global ones
38489
38692
  const merged = mergeWithDefaults(globalOptions, server);
38693
+ // Ensure child server xems explicitly overrides global server xems
38694
+ const explicitChildXems = server.server?.xems || server.xems;
38695
+ if (explicitChildXems) {
38696
+ merged.server = merged.server || {};
38697
+ merged.server.xems = mergeWithDefaults(globalOptions.server?.xems || {}, explicitChildXems);
38698
+ }
38490
38699
  // Ensure child server port & host override global server block
38491
38700
  if (server.port) {
38492
38701
  merged.server = merged.server || {};