@pixlcore/xycli 1.2.2 → 1.2.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # xyCLI Changelog
2
2
 
3
+ ## Version v1.2.3
4
+
5
+ > November 5, 2026
6
+
7
+ - [`e7da2e7`](https://github.com/pixlcore/xycli/commit/e7da2e7251d4a4834b569fe581cc4338ed9ecaf1): Version 1.2.3
8
+ - [`48c1fca`](https://github.com/pixlcore/xycli/commit/48c1fcac6e1128f132a571eb915da66df7c6705e): Fix: Prevent a theoretically compromised xyOps server client config from infecting CLI sync config.
9
+ - [`023129a`](https://github.com/pixlcore/xycli/commit/023129a91b7f2c64062bad3e5d4300d0f8c10d4b): Fix: Use secure JSON parsing at user trust boundaries.
10
+
11
+ ## Version v1.2.2
12
+
13
+ > November 2, 2026
14
+
15
+ - [`660ba0a`](https://github.com/pixlcore/xycli/commit/660ba0afe7187d97313ca9bf9260a1db64a377cb): Version 1.2.2
16
+ - [`b302242`](https://github.com/pixlcore/xycli/commit/b3022422a340e088f4bab89bbaece233addd94b3): Fix: Reject unsupported config keys with typo suggestions
17
+ - [`b7973a9`](https://github.com/pixlcore/xycli/commit/b7973a9ad1cead3b746bd304feb3193abeb59b28): Meta: Add flag to force fresh pull of base docker image on GH actions build.
18
+
3
19
  ## Version v1.2.1
4
20
 
5
21
  > October 29, 2026
package/index.js CHANGED
@@ -286,7 +286,8 @@ const app = {
286
286
  this.toast('⚠️', 'orange', bold("DRY RUN: ") + "No changes will actually be made.");
287
287
  }
288
288
 
289
- // optionally read STDIN into a named arg (use curl @- convention)
289
+ // Parse user JSON securely before any argument objects can be merged.
290
+ // Optionally read STDIN into a named arg (use curl @- convention).
290
291
  var stdin_arg_key = null;
291
292
  for (var key in args) {
292
293
  if (args[key] === '@-') { stdin_arg_key = key; break; }
@@ -299,7 +300,7 @@ const app = {
299
300
 
300
301
  // Some API parameters are opaque strings even when they look like JSON.
301
302
  if (!JSON_ARG_EXCEPTIONS.includes(stdin_arg_key) && (args[stdin_arg_key].trim().match(/^\{[\s\S]*\}$/) || args[stdin_arg_key].trim().match(/^\[[\s\S]*\]$/))) {
302
- try { args[stdin_arg_key] = JSON.parse(args[stdin_arg_key]); }
303
+ try { args[stdin_arg_key] = Tools.sjson.parse(args[stdin_arg_key]); }
303
304
  catch (err) { this.die("Failed to parse JSON from STDIN: " + err); }
304
305
  }
305
306
  }
@@ -309,7 +310,7 @@ const app = {
309
310
  if (String(args[key]).match(/^@(.+)$/)) {
310
311
  var file = RegExp.$1;
311
312
  if (!fs.existsSync(file)) this.die("File not found: " + file);
312
- if (!JSON_ARG_EXCEPTIONS.includes(key) && file.match(/\.json$/i)) args[key] = JSON.parse( fs.readFileSync(file, 'utf8') );
313
+ if (!JSON_ARG_EXCEPTIONS.includes(key) && file.match(/\.json$/i)) args[key] = Tools.sjson.parse( fs.readFileSync(file, 'utf8') );
313
314
  else args[key] = fs.readFileSync(file, 'utf8');
314
315
  }
315
316
  }
@@ -324,7 +325,7 @@ const app = {
324
325
  // any arg value that looks like json will be parsed
325
326
  for (var key in args) {
326
327
  if (!JSON_ARG_EXCEPTIONS.includes(key) && args[key] && (typeof(args[key]) == 'string') && (args[key].trim().match(/^\{[\s\S]*\}$/) || args[key].trim().match(/^\[[\s\S]*\]$/))) {
327
- try { args[key] = JSON.parse( args[key] ); }
328
+ try { args[key] = Tools.sjson.parse( args[key] ); }
328
329
  catch (err) { this.die("Failed to parse JSON from argument: " + err); }
329
330
  }
330
331
  }
package/lib/categories.js CHANGED
@@ -283,7 +283,7 @@ module.exports = {
283
283
  Tools.alwaysArray(params[singular]).forEach( item => {
284
284
  // Repeated options arrive as an array of unparsed JSON strings.
285
285
  if (typeof(item) == 'string') {
286
- try { item = JSON.parse(item); }
286
+ try { item = Tools.sjson.parse(item); }
287
287
  catch (err) { this.die("Category --" + singular + " must contain a JSON object."); }
288
288
  }
289
289
  if (!Tools.isaHash(item)) this.die("Category --" + singular + " must contain a JSON object.");
package/lib/config.js CHANGED
@@ -54,9 +54,11 @@ var config_layer = module.exports = {
54
54
  var config = {};
55
55
  var config_files = this.configFiles = getConfigFiles(process.platform, process.env, os.homedir());
56
56
 
57
+ // Settings may come from external files or deployment environments.
58
+ // Reject prototype properties before merging or exporting parsed values.
57
59
  config_files.forEach( function(file) {
58
60
  if (!fs.existsSync(file)) return;
59
- Tools.mergeHashInto( config, JSON.parse(fs.readFileSync(file, 'utf8')) );
61
+ Tools.mergeHashInto( config, Tools.sjson.parse(fs.readFileSync(file, 'utf8')) );
60
62
  } );
61
63
 
62
64
  for (var ekey in process.env) {
@@ -65,7 +67,7 @@ var config_layer = module.exports = {
65
67
  var value = process.env[ekey];
66
68
  // Parse object and array values just like JSON-looking CLI arguments.
67
69
  if (value.trim().match(/^\{[\s\S]*\}$/) || value.trim().match(/^\[[\s\S]*\]$/)) {
68
- try { value = JSON.parse(value); }
70
+ try { value = Tools.sjson.parse(value); }
69
71
  catch (err) { throw new Error('Failed to parse JSON from environment variable: ' + ekey); }
70
72
  }
71
73
  else if (value === "true") value = true;
@@ -121,7 +123,7 @@ var config_layer = module.exports = {
121
123
  // configuration also contains system settings and environment overrides,
122
124
  // which must not be copied into the user's file when saving preferences.
123
125
  var dest_file = this.configFiles[this.configFiles.length - 1];
124
- var user_config = fs.existsSync(dest_file) ? JSON.parse(fs.readFileSync(dest_file, 'utf8')) : {};
126
+ var user_config = fs.existsSync(dest_file) ? Tools.sjson.parse(fs.readFileSync(dest_file, 'utf8')) : {};
125
127
 
126
128
  // Apply only the supplied arguments, preserving other user settings.
127
129
  print("\n");
package/lib/groups.js CHANGED
@@ -429,7 +429,7 @@ module.exports = {
429
429
  if (!Array.isArray(params.alert_actions)) this.die('Server Group alert_actions must be a JSON array.');
430
430
  Tools.alwaysArray(params.action).forEach( action => {
431
431
  if (typeof(action) == 'string') {
432
- try { action = JSON.parse(action); }
432
+ try { action = Tools.sjson.parse(action); }
433
433
  catch (err) { this.die('Server Group --action must contain a JSON object.'); }
434
434
  }
435
435
  if (!Tools.isaHash(action)) this.die('Server Group --action must contain a JSON object.');
package/lib/mcp/server.js CHANGED
@@ -9,7 +9,12 @@ module.exports = function serverFactory(tools, context) {
9
9
  // STDIO uses the configured context. HTTP supplies a key for each
10
10
  // exchange, shared by all API calls made by that exchange's tools.
11
11
  const scoped = apiKey === undefined ? context : context.withApiKey(apiKey);
12
- const server = new McpServer({ name: 'xyops', version: pkg.version });
12
+ // Our catalog is fixed when this instance is built. Override the SDK's
13
+ // listChanged:true default so clients do not open unused subscriptions.
14
+ const server = new McpServer({ name: 'xyops', version: pkg.version }, {
15
+ capabilities: { tools: { listChanged: false } }
16
+ });
17
+
13
18
  for (const tool of tools.values()) {
14
19
  const { name, ...description } = tool.description;
15
20
  if (scoped.readOnly && !description.annotations.readOnlyHint) continue;
@@ -2,10 +2,21 @@
2
2
  const http = require('node:http');
3
3
  const https = require('node:https');
4
4
  const fs = require('node:fs');
5
+ const { AsyncLocalStorage } = require('node:async_hooks');
5
6
  const { createMcpHandler } = require('@modelcontextprotocol/server');
6
7
  const { toNodeHandler, hostHeaderValidation } = require('@modelcontextprotocol/node');
7
8
 
8
9
  module.exports = async function startHTTP(factory, options) {
10
+ // SDK callbacks are shared by all requests. Keep diagnostic redaction in
11
+ // the caller's async scope rather than storing a mutable "current" key.
12
+ const requestKeys = new AsyncLocalStorage();
13
+ function logError(label, error) {
14
+ let message = String(error?.message || error);
15
+ const apiKey = requestKeys.getStore();
16
+ if (apiKey) message = message.split(apiKey).join('[redacted]');
17
+ options.log(label + ': ' + message);
18
+ }
19
+
9
20
  // Check only the header shape here. xyOps validates the key and enforces
10
21
  // privileges when the tool calls its API; there is no separate MCP secret.
11
22
  function bearerKey(authorization) {
@@ -19,9 +30,18 @@ module.exports = async function startHTTP(factory, options) {
19
30
  // Auto returns JSON for ordinary calls and preserves streamed messages
20
31
  // if a future tool needs progress notifications during its response.
21
32
  responseMode: 'auto', maxRequestBodySize: options.max_request_bytes,
22
- maxSubscriptions: 0, onerror: () => options.log('MCP protocol error on HTTP request.')
33
+ maxSubscriptions: 0, onerror(error) {
34
+ // A client may subscribe even though our catalog is static. The SDK
35
+ // still returns its refusal, but our deliberate zero limit is quiet.
36
+ // Match only this exact SDK diagnostic; other protocol faults matter.
37
+ if (error?.message === 'subscriptions/listen refused: subscription limit reached (0)') return;
38
+ logError('MCP protocol error on HTTP request', error);
39
+ }
40
+ });
41
+ const nodeHandler = toNodeHandler(handler, {
42
+ maxRequestBodySize: options.max_request_bytes,
43
+ onerror: error => logError('MCP HTTP adapter error', error)
23
44
  });
24
- const nodeHandler = toNodeHandler(handler, { maxRequestBodySize: options.max_request_bytes, onerror: () => options.log('MCP HTTP adapter error.') });
25
45
  const validateHost = hostHeaderValidation(options.allowed_hosts);
26
46
 
27
47
  function respond(response, status, text) {
@@ -35,16 +55,17 @@ module.exports = async function startHTTP(factory, options) {
35
55
  if (!validateHost(request, response)) return;
36
56
  const origin = request.headers.origin;
37
57
  if (origin && !options.allowed_origins.includes(origin)) return respond(response, 403, 'Origin not allowed');
38
- if (!bearerKey(request.headers.authorization)) {
58
+ const apiKey = bearerKey(request.headers.authorization);
59
+ if (!apiKey) {
39
60
  response.setHeader('WWW-Authenticate', 'Bearer');
40
61
  return respond(response, 401, 'Supply a xyOps API key as a Bearer token');
41
62
  }
42
63
  response.setHeader('Cache-Control', 'no-store');
43
- nodeHandler(request, response).catch(function() {
44
- options.log('MCP HTTP request failed.');
64
+ requestKeys.run(apiKey, () => nodeHandler(request, response).catch(function(error) {
65
+ logError('MCP HTTP request failed', error);
45
66
  if (!response.headersSent) respond(response, 500, 'Internal server error');
46
67
  else response.destroy();
47
- });
68
+ }));
48
69
  }
49
70
 
50
71
  const server = options.tls_cert ? https.createServer({ cert: fs.readFileSync(options.tls_cert), key: fs.readFileSync(options.tls_key) }, request) : http.createServer(request);
@@ -3,5 +3,9 @@ const { serveStdio, StdioServerTransport } = require('@modelcontextprotocol/serv
3
3
 
4
4
  module.exports = function startStdio(factory, options) {
5
5
  const transport = new StdioServerTransport(process.stdin, process.stdout, { maxBufferSize: options.max_request_bytes });
6
- return serveStdio(factory, { transport, maxSubscriptions: 0, onerror: () => options.log('MCP protocol error on stdin.') });
6
+ return serveStdio(factory, {
7
+ transport, maxSubscriptions: 0,
8
+ // The context logger already redacts the configured STDIO API key.
9
+ onerror: error => options.log('MCP protocol error on stdin: ' + (error?.message || String(error)))
10
+ });
7
11
  };
package/lib/plugins.js CHANGED
@@ -403,7 +403,7 @@ module.exports = {
403
403
  // parsed object and repeated objects both become a clean object array here.
404
404
  return Tools.alwaysArray(value).map( item => {
405
405
  if (typeof(item) == 'string') {
406
- try { item = JSON.parse(item); }
406
+ try { item = Tools.sjson.parse(item); }
407
407
  catch (err) { this.die("Plugin --" + name + " must contain a JSON object."); }
408
408
  }
409
409
  if (!Tools.isaHash(item)) this.die("Plugin --" + name + " must contain a JSON object.");
@@ -69,7 +69,7 @@ module.exports = {
69
69
  var paths = this.getSyncBucketPaths(item);
70
70
  var stat = fs.lstatSync(paths.data);
71
71
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Invalid bucket data file: " + paths.data);
72
- var data = JSON.parse(fs.readFileSync(paths.data, 'utf8'));
72
+ var data = Tools.sjson.parse(fs.readFileSync(paths.data, 'utf8'));
73
73
  if (!Tools.isaHash(data)) throw new Error("Bucket data must be a JSON object: " + paths.data);
74
74
 
75
75
  var dir_stat = fs.lstatSync(paths.files);
@@ -233,7 +233,7 @@ module.exports = {
233
233
  if (Tools.stableStringify(updated.data) !== Tools.stableStringify(local.data)) {
234
234
  throw new Error("Bucket data changed during upload: " + id);
235
235
  }
236
- if (Tools.stableStringify(JSON.parse(fs.readFileSync(local.paths.data, 'utf8'))) !== Tools.stableStringify(local.data)) {
236
+ if (Tools.stableStringify(Tools.sjson.parse(fs.readFileSync(local.paths.data, 'utf8'))) !== Tools.stableStringify(local.data)) {
237
237
  throw new Error("Local bucket data changed during upload: " + local.paths.data);
238
238
  }
239
239
  this.stampSyncBucketFile(local.paths.data, updated.meta.mod);
@@ -42,7 +42,7 @@ async function readHookPayload() {
42
42
 
43
43
  if (!size) throw new Error("System Hook activity payload is empty.");
44
44
 
45
- try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
45
+ try { return Tools.sjson.parse(Buffer.concat(chunks).toString('utf8')); }
46
46
  catch (err) { throw new Error("Invalid System Hook activity JSON: " + err.message); }
47
47
  }
48
48
 
@@ -76,7 +76,7 @@ function scanSources(files) {
76
76
  catch (err) { throw new Error("Failed to read JSON file: " + file + ": " + err.message); }
77
77
 
78
78
  var xypdf = null;
79
- try { xypdf = JSON.parse(raw); }
79
+ try { xypdf = Tools.sjson.parse(raw); }
80
80
  catch (err) {
81
81
  parse_errors.push({ file, err });
82
82
  continue;
package/lib/sync.js CHANGED
@@ -119,9 +119,14 @@ module.exports = {
119
119
  // source basename instead of also being claimed by every shorter prefix.
120
120
  var source_stems_by_dir = new Map();
121
121
  var bucket_extra_dirs = [];
122
+ // Keep parseJSON's line-number diagnostics, then scan each parsed value
123
+ // before using it. Null is valid JSON and has no properties to inspect.
122
124
  files.filter( file => !!file.path.match(/\.json$/i) ).forEach( file => {
123
125
  var xypdf = null;
124
- try { xypdf = Tools.parseJSON( fs.readFileSync(file.path, 'utf8') ); }
126
+ try {
127
+ xypdf = Tools.parseJSON( fs.readFileSync(file.path, 'utf8') );
128
+ if (xypdf) Tools.sjson.scan(xypdf);
129
+ }
125
130
  catch (err) { return; } // the normal scan below reports malformed JSON
126
131
  if (!xypdf || !Tools.isaHash(xypdf) || (xypdf.type !== 'xypdf')) return;
127
132
  if (Array.isArray(xypdf.items) && xypdf.items.length == 1 && xypdf.items[0].type == 'bucket') {
@@ -154,7 +159,8 @@ module.exports = {
154
159
  // try to parse JSON
155
160
  var xypdf = null;
156
161
  try {
157
- xypdf = Tools.parseJSON( fs.readFileSync(file.path, 'utf8') );
162
+ xypdf = Tools.parseJSON( fs.readFileSync(file.path, 'utf8') );
163
+ if (xypdf) Tools.sjson.scan(xypdf);
158
164
  }
159
165
  catch (err) {
160
166
  this.logSyncWarning("Failed to parse JSON file: " + file.path + ": " + err);
@@ -263,6 +269,7 @@ module.exports = {
263
269
  if (neighbor.path.match(/\.json$/i)) {
264
270
  try {
265
271
  var neighbor_json = Tools.parseJSON(content);
272
+ if (neighbor_json) Tools.sjson.scan(neighbor_json);
266
273
  if (neighbor_json && Tools.isaHash(neighbor_json) && (neighbor_json.type === 'xypdf')) return;
267
274
  }
268
275
  catch (err) {;} // leave non-JSON content for normal neighbor handling
@@ -494,6 +501,7 @@ module.exports = {
494
501
  if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Local deletion target is not a regular directory: " + dir);
495
502
  }
496
503
  var source = Tools.parseJSON(fs.readFileSync(item.file, 'utf8'));
504
+ if (source) Tools.sjson.scan(source);
497
505
  var source_item = source && Array.isArray(source.items) && (source.items.length === 1) ? source.items[0] : null;
498
506
  if (!source || (source.type !== 'xypdf') || (source.version !== '1.0') || !source_item ||
499
507
  (source_item.type !== item.type) || !source_item.data || (source_item.data.id !== item.data.id)) {
@@ -612,7 +620,7 @@ module.exports = {
612
620
  }
613
621
 
614
622
  var old_lock = null;
615
- try { old_lock = raw.match(/^\d+$/) ? { pid: parseInt(raw) } : JSON.parse(raw); }
623
+ try { old_lock = raw.match(/^\d+$/) ? { pid: parseInt(raw) } : Tools.sjson.parse(raw); }
616
624
  catch (err) { this.die("Invalid sync lock file: " + lock_file + ". Verify no sync is running before removing it."); }
617
625
 
618
626
  var old_pid = old_lock && Number(old_lock.pid);
@@ -693,7 +701,7 @@ module.exports = {
693
701
  }
694
702
 
695
703
  try {
696
- var current = JSON.parse(fs.readFileSync(lock.file, 'utf8'));
704
+ var current = Tools.sjson.parse(fs.readFileSync(lock.file, 'utf8'));
697
705
  if (current.token === lock.token) fs.unlinkSync(lock.file);
698
706
  }
699
707
  catch (err) {
@@ -1027,6 +1035,7 @@ module.exports = {
1027
1035
  files.filter( file => !!file.path.match(/\.json$/i) ).forEach( file => {
1028
1036
  try {
1029
1037
  var xypdf = Tools.parseJSON( fs.readFileSync(file.path, 'utf8') );
1038
+ if (xypdf) Tools.sjson.scan(xypdf);
1030
1039
  if (xypdf && xypdf.type == 'xypdf' && Array.isArray(xypdf.items) &&
1031
1040
  xypdf.items.length == 1 && xypdf.items[0].type == 'bucket') {
1032
1041
  bucket_extra_dirs.push(file.path.replace(/\.json$/i, ''));
@@ -1036,7 +1045,10 @@ module.exports = {
1036
1045
  });
1037
1046
  files.filter( file => !!file.path.match(/\.json$/i) && !this.isSyncBucketExtraFile(file.path, bucket_extra_dirs) ).forEach( file => {
1038
1047
  var xypdf = null;
1039
- try { xypdf = Tools.parseJSON( fs.readFileSync(file.path, 'utf8') ); }
1048
+ try {
1049
+ xypdf = Tools.parseJSON( fs.readFileSync(file.path, 'utf8') );
1050
+ if (xypdf) Tools.sjson.scan(xypdf);
1051
+ }
1040
1052
  catch (err) { this.die("Failed to parse JSON file: " + file.path + ": " + err); }
1041
1053
 
1042
1054
  // Ordinary JSON files are unrelated and may coexist in the tree.
package/lib/transfer.js CHANGED
@@ -185,6 +185,7 @@ module.exports = {
185
185
 
186
186
  cleanTransferData(data) {
187
187
  // Strip server-managed metadata without mutating cached or parsed objects.
188
+ // This JSON round trip only clones data already validated at its boundary.
188
189
  var clean = JSON.parse(JSON.stringify(data));
189
190
  AUDIT_FIELDS.forEach( key => delete clean[key] );
190
191
  if (clean.id === '') delete clean.id;
@@ -235,7 +236,7 @@ module.exports = {
235
236
  // Accept gzip by signature as well as extension, including UI .json.gz.
236
237
  if (/\.gz$/i.test(filename) || (bytes[0] == 0x1f && bytes[1] == 0x8b)) bytes = zlib.gunzipSync(bytes);
237
238
 
238
- payload = JSON.parse(bytes.toString('utf8').replace(/^\uFEFF/, ''));
239
+ payload = Tools.sjson.parse(bytes.toString('utf8').replace(/^\uFEFF/, ''));
239
240
  }
240
241
  catch (err) { return this.die("Failed to read XYPDF file: " + err.message); }
241
242
 
package/lib/upgrade.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const cp = require('node:child_process');
4
4
 
5
5
  const cli = require('pixl-cli');
6
+ const Tools = cli.Tools;
6
7
  const chalk = cli.chalk;
7
8
 
8
9
  const PACKAGE_NAME = '@pixlcore/xycli';
@@ -98,7 +99,12 @@ module.exports = {
98
99
  if (!response.ok) this.die("npm registry request failed with HTTP status: " + response.status);
99
100
 
100
101
  var data;
101
- try { data = await response.json(); }
102
+ try {
103
+ data = await response.json();
104
+
105
+ // Fetch owns JSON decoding, so scan the registry's object before use.
106
+ Tools.sjson.scan(data);
107
+ }
102
108
  catch (err) { this.die("Could not parse the npm registry response: " + err.message); }
103
109
 
104
110
  if (!data || (typeof(data.version) != 'string') || !data.version.length) {
package/lib/utils.js CHANGED
@@ -1017,6 +1017,10 @@ module.exports = {
1017
1017
 
1018
1018
  // merge, but do not clobber keys already in local config
1019
1019
  for (var key in data.config) {
1020
+ // Sync settings can execute local commands and must only come from
1021
+ // local config or CLI arguments, never the server's client config.
1022
+ if (key == 'sync') continue;
1023
+
1020
1024
  if (!(key in this.config)) this.config[key] = data.config[key];
1021
1025
  }
1022
1026
 
@@ -1039,8 +1043,9 @@ module.exports = {
1039
1043
  catch (err) { stats = null; }
1040
1044
 
1041
1045
  if (stats && (stats.mtimeMs / 1000 > Tools.timeNow() - ttl)) {
1042
- // cache object still fresh
1043
- return { data: JSON.parse( fs.readFileSync(cache_file, 'utf8') ) };
1046
+ // Cache files can be modified outside this process. Validate their JSON
1047
+ // just like the original API response before returning a fresh object.
1048
+ return { data: Tools.sjson.parse( fs.readFileSync(cache_file, 'utf8') ) };
1044
1049
  }
1045
1050
 
1046
1051
  // fetch from origin
package/lib/webhook.js CHANGED
@@ -315,7 +315,7 @@ module.exports = {
315
315
  if (!Array.isArray(params.headers)) this.die("Web Hook headers must be a JSON array.");
316
316
  Tools.alwaysArray(params.header).forEach( header => {
317
317
  if (typeof(header) == 'string') {
318
- try { header = JSON.parse(header); }
318
+ try { header = Tools.sjson.parse(header); }
319
319
  catch (err) { this.die("Web Hook --header must contain a JSON object."); }
320
320
  }
321
321
  if (!Tools.isaHash(header)) this.die("Web Hook --header must contain a JSON object.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pixlcore/xycli",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
4
4
  "description": "A complete command-line interface for the xyOps workflow automation system.",
5
5
  "author": "Joseph Huckaby <jhuckaby@pixlcore.com>",
6
6
  "homepage": "https://github.com/pixlcore/xycli",
@@ -21,17 +21,17 @@
21
21
  ],
22
22
  "scripts": {
23
23
  "test": "node test.js",
24
- "test:offline": "node --test test/config.test.js test/help.test.js test/jobs-follow-unit.test.js test/markdown.test.js test/sync-buckets-unit.test.js test/sync-syshook-unit.test.js test/sync-unit.test.js test/toast.test.js test/upgrade.test.js test/utils-unit.test.js test/mcp-tools-unit.test.js test/mcp-stdio-unit.test.js test/mcp-http-unit.test.js",
24
+ "test:offline": "node --test test/config.test.js test/help.test.js test/jobs-follow-unit.test.js test/markdown.test.js test/secure-json-unit.test.js test/sync-buckets-unit.test.js test/sync-syshook-unit.test.js test/sync-unit.test.js test/toast.test.js test/upgrade.test.js test/utils-unit.test.js test/mcp-tools-unit.test.js test/mcp-stdio-unit.test.js test/mcp-http-unit.test.js",
25
25
  "changelog": "node tools/changelog.js"
26
26
  },
27
27
  "overrides": {
28
28
  "basic-ftp": "6.2.1"
29
29
  },
30
30
  "dependencies": {
31
- "@pixlcore/xyops-sdk": "^1.0.8",
31
+ "@pixlcore/xyops-sdk": "^1.0.9",
32
32
  "cli-highlight": "2.1.11",
33
33
  "diff": "9.0.0",
34
- "pixl-cli": "^1.1.6",
34
+ "pixl-cli": "^1.1.7",
35
35
  "html-to-text": "10.0.1",
36
36
  "marked": "15.0.12",
37
37
  "marked-terminal": "7.3.0",
@@ -9,7 +9,120 @@ const { createContext } = require('../lib/mcp/context.js');
9
9
  const factory = require('../lib/mcp/server.js');
10
10
  const start = require('../lib/mcp/transports/http.js');
11
11
  const tools = require('../lib/mcp/registry.js')();
12
- const { httpRPC } = require('./helpers/mcp.js');
12
+ const { decode, httpRPC } = require('./helpers/mcp.js');
13
+
14
+ test('HTTP advertises a static tool catalog for modern and legacy clients', async t => {
15
+ // Both permission modes use the same static catalog capabilities. Check the
16
+ // wire responses so an SDK default cannot silently re-enable notifications.
17
+ for (const read_only of [false, true]) {
18
+ const service = await start(factory(tools, createContext({}, { read_only })), { ...configuration({}, {}), port: 0, log() {} });
19
+ t.after(() => service.close());
20
+ const url = 'http://127.0.0.1:' + service.address.port + '/mcp';
21
+ const headers = { Authorization: 'Bearer fixture-key' };
22
+ const modern = await httpRPC(url, 'server/discover', {}, { headers, modern: true });
23
+ const legacy = await httpRPC(url, 'initialize', {
24
+ protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'xycli-test', version: '1' }
25
+ }, { headers });
26
+ for (const reply of [modern, legacy]) assert.deepEqual(reply.result.capabilities.tools, { listChanged: false });
27
+ const listing = await httpRPC(url, 'tools/list', {}, { headers, modern: true });
28
+ assert.equal(listing.result.tools.length, read_only ? 8 : tools.size);
29
+ }
30
+ });
31
+
32
+ test('HTTP keeps intentional subscription refusals quiet and reports other protocol errors', async t => {
33
+ const logs = [];
34
+ const service = await start(factory(tools, createContext({})), { ...configuration({}, {}), port: 0, log: line => logs.push(line) });
35
+ t.after(() => service.close());
36
+ const url = 'http://127.0.0.1:' + service.address.port + '/mcp';
37
+ const headers = { Authorization: 'Bearer fixture-key' };
38
+
39
+ // Clients may subscribe despite listChanged:false. Keep the SDK's refusal
40
+ // on the wire, without treating our deliberate zero limit as a server fault.
41
+ for (let attempt = 0; attempt < 2; attempt++) {
42
+ const response = await fetch(url, {
43
+ method: 'POST', headers: {
44
+ ...headers, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream',
45
+ 'MCP-Protocol-Version': '2026-07-28', 'Mcp-Method': 'subscriptions/listen'
46
+ },
47
+ body: JSON.stringify({ jsonrpc: '2.0', id: attempt + 1, method: 'subscriptions/listen', params: {
48
+ notifications: { toolsListChanged: true },
49
+ _meta: { 'io.modelcontextprotocol/protocolVersion': '2026-07-28', 'io.modelcontextprotocol/clientCapabilities': {} }
50
+ } })
51
+ });
52
+ assert.equal(response.status, 200);
53
+ assert.deepEqual((await decode(response)).error, { code: -32603, message: 'Subscription limit reached' });
54
+ }
55
+ assert.deepEqual(logs, []);
56
+
57
+ // A mismatched routing header must still produce a useful diagnostic.
58
+ // Include the caller's key in that header to exercise diagnostic redaction.
59
+ const rejected = await httpRPC(url, 'tools/list', {}, {
60
+ modern: true, headers: { ...headers, 'Mcp-Method': 'fixture-key' }
61
+ });
62
+ assert.ok(rejected.error);
63
+ assert.equal(logs.length, 1);
64
+ assert.match(logs[0], /^MCP protocol error on HTTP request: .*Mcp-Method/i);
65
+ assert.doesNotMatch(logs[0], /fixture-key/);
66
+ assert.ok((await httpRPC(url, 'tools/list', {}, { headers, modern: true })).result.tools.length);
67
+ });
68
+
69
+ test('HTTP protocol errors include the cause and redact each concurrent caller key', async t => {
70
+ const logs = [];
71
+ const service = await start(async ({ apiKey }) => {
72
+ // A failed factory reaches the SDK's protocol error callback. Vary the
73
+ // timing to verify request-scoped diagnostics across concurrent callers.
74
+ await new Promise(resolve => setTimeout(resolve, apiKey === 'slow-secret' ? 20 : 1));
75
+ throw new Error('Fixture setup failed for ' + apiKey);
76
+ }, { ...configuration({}, {}), port: 0, log: line => logs.push(line) });
77
+ t.after(() => service.close());
78
+ const url = 'http://127.0.0.1:' + service.address.port + '/mcp';
79
+ const replies = await Promise.all(['slow-secret', 'fast-secret'].map(key => httpRPC(url, 'server/discover', {}, {
80
+ modern: true, headers: { Authorization: 'Bearer ' + key }
81
+ })));
82
+ assert.ok(replies.every(reply => reply.error));
83
+ assert.deepEqual(logs, [
84
+ 'MCP protocol error on HTTP request: Fixture setup failed for [redacted]',
85
+ 'MCP protocol error on HTTP request: Fixture setup failed for [redacted]'
86
+ ]);
87
+ });
88
+
89
+ test('HTTP logs subscription faults other than the intentional zero limit', async t => {
90
+ const logs = [];
91
+ // Inject a nearby SDK diagnostic through its real error callback. A broad
92
+ // match for subscription errors would hide a future nonzero capacity fault.
93
+ const message = 'subscriptions/listen refused: subscription limit reached (1)';
94
+ const service = await start(() => { throw new Error(message); }, {
95
+ ...configuration({}, {}), port: 0, log: line => logs.push(line)
96
+ });
97
+ t.after(() => service.close());
98
+ const reply = await httpRPC('http://127.0.0.1:' + service.address.port + '/mcp', 'server/discover', {}, {
99
+ modern: true, headers: { Authorization: 'Bearer fixture-key' }
100
+ });
101
+ assert.ok(reply.error);
102
+ assert.deepEqual(logs, ['MCP protocol error on HTTP request: ' + message]);
103
+ });
104
+
105
+ test('HTTP adapter errors include their underlying cause', async t => {
106
+ const logs = [];
107
+ const service = await start(factory(tools, createContext({})), { ...configuration({}, {}), port: 0, log: line => logs.push(line) });
108
+ t.after(() => service.close());
109
+ // Node's web Request conversion rejects TRACE before MCP dispatch. Use a
110
+ // native request because fetch itself refuses to send this HTTP method.
111
+ const status = await new Promise((resolve, reject) => {
112
+ const request = http.request({
113
+ hostname: '127.0.0.1', port: service.address.port, path: '/mcp', method: 'TRACE',
114
+ headers: { Authorization: 'Bearer fixture-key' }
115
+ }, response => {
116
+ response.resume();
117
+ response.on('end', () => resolve(response.statusCode));
118
+ });
119
+ request.on('error', reject);
120
+ request.end();
121
+ });
122
+ assert.equal(status, 500);
123
+ assert.equal(logs.length, 1);
124
+ assert.match(logs[0], /^MCP HTTP adapter error: .*TRACE.*unsupported/i);
125
+ });
13
126
 
14
127
  test('HTTP serves both protocol generations, validates calls and rejects unauthorized access', async t => {
15
128
  let calls = 0;
@@ -2,8 +2,27 @@ const { test } = require('node:test');
2
2
  const assert = require('node:assert/strict');
3
3
  const http = require('node:http');
4
4
  const { spawnSync } = require('node:child_process');
5
+ const { once } = require('node:events');
5
6
  const { httpRPC, stdioClient } = require('./helpers/mcp.js');
6
7
 
8
+ test('modern STDIO advertises a static catalog and logs useful protocol errors', async t => {
9
+ const client = stdioClient(t, { XYOPS_BASE_URL: 'http://127.0.0.1:1', XYOPS_API_KEY: 'fixture-key' });
10
+ const _meta = { 'io.modelcontextprotocol/protocolVersion': '2026-07-28', 'io.modelcontextprotocol/clientCapabilities': {} };
11
+ assert.deepEqual((await client.request('server/discover', { _meta })).result.capabilities.tools, { listChanged: false });
12
+ assert.ok((await client.request('tools/list', { _meta })).result.tools.length);
13
+
14
+ // Once modern traffic pins the connection, legacy requests are rejected.
15
+ // Observe stderr before sending to avoid missing a fast child's diagnostic.
16
+ const diagnostic = once(client.child.stderr, 'data', { signal: AbortSignal.timeout(5000) });
17
+ assert.ok((await client.initialize()).error);
18
+ await diagnostic;
19
+ assert.match(client.stderr(), /MCP protocol error on stdin: Rejected 2025-era request/);
20
+ assert.doesNotMatch(client.stderr(), /fixture-key/);
21
+ assert.ok((await client.request('tools/list', { _meta })).result.tools.length);
22
+ client.child.stdin.end();
23
+ assert.equal((await client.exit)[0], 0);
24
+ });
25
+
7
26
  test('STDIO uses the real CLI and SDK with protocol-only stdout and clean EOF', async t => {
8
27
  let calls = 0;
9
28
  const backend = http.createServer((request, response) => {
@@ -16,7 +35,7 @@ test('STDIO uses the real CLI and SDK with protocol-only stdout and clean EOF',
16
35
  await new Promise(resolve => backend.listen(0, '127.0.0.1', resolve));
17
36
  t.after(() => new Promise(resolve => { backend.close(resolve); backend.closeAllConnections(); }));
18
37
  const client = stdioClient(t, { XYOPS_BASE_URL: 'http://127.0.0.1:' + backend.address().port, XYOPS_API_KEY: 'fixture-key', XYOPS_RETRIES: '4' }, ['mcp', 'stdio', '--verbose', '--debug', '--read-only']);
19
- assert.ok((await client.initialize()).result);
38
+ assert.deepEqual((await client.initialize()).result.capabilities.tools, { listChanged: false });
20
39
  const listing = await client.request('tools/list');
21
40
  assert.equal(listing.result.tools.length, 8);
22
41
  assert.equal((await client.call('get_event', { id: 'fixture' })).result.structuredContent.event.revision, 2);
@@ -0,0 +1,140 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const Path = require('node:path');
6
+ const zlib = require('node:zlib');
7
+ const { spawnSync } = require('node:child_process');
8
+ const cli = require('pixl-cli');
9
+ const Tools = cli.Tools;
10
+ const utils = require('../lib/utils.js');
11
+ const transfer = require('../lib/transfer.js');
12
+ const upgrade = require('../lib/upgrade.js');
13
+
14
+ // Keep these as JSON text so JavaScript's object literal syntax cannot consume
15
+ // __proto__ before the input reaches the actual CLI boundary under test.
16
+ const unsafe = [
17
+ '{"nested":[{"__proto__":{"polluted":true}}]}',
18
+ '{"nested":[{"constructor":{"prototype":{"polluted":true}}}]}',
19
+ '{"nested":[{"\\u005f_proto__":{"polluted":true}}]}'
20
+ ];
21
+
22
+ function fixture(t) {
23
+ // Each subprocess gets a private config, cache and SDK stub. Any attempted
24
+ // API call leaves a marker, without contacting a real xyOps server.
25
+ const dir = fs.mkdtempSync(Path.join(os.tmpdir(), 'xycli-secure-json-'));
26
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
27
+ const marker = Path.join(dir, 'api-called');
28
+ const preload = Path.join(dir, 'preload.js');
29
+ fs.writeFileSync(preload, `
30
+ const fs = require('node:fs');
31
+ const sdk = require(${JSON.stringify(require.resolve('@pixlcore/xyops-sdk'))});
32
+ sdk.api = new Proxy({}, {
33
+ get() { return async function() {
34
+ fs.writeFileSync(${JSON.stringify(marker)}, 'called');
35
+ return { data: { config: {}, masters: [], version: '99.0.0' } };
36
+ }; }
37
+ });
38
+ `);
39
+ const env = { ...process.env, HOME: dir, USERPROFILE: dir, ProgramData: dir };
40
+ for (const key of Object.keys(env)) {
41
+ if (key.startsWith('XYOPS_')) delete env[key];
42
+ }
43
+ Object.assign(env, {
44
+ XYOPS_API_KEY: 'fixture-key', XYOPS_BASE_URL: 'https://fixture.invalid',
45
+ XYOPS_TEMP_DIR: dir, XYOPS_COLOR: 'false'
46
+ });
47
+
48
+ return {
49
+ dir, marker, env,
50
+ run(args, input) {
51
+ const result = spawnSync(process.execPath, [
52
+ '--require', preload, Path.join(__dirname, '..', 'index.js'), ...args
53
+ ], { env, input, encoding: 'utf8', timeout: 10000 });
54
+ assert.ifError(result.error);
55
+ assert.equal(result.signal, null);
56
+ return result;
57
+ }
58
+ };
59
+ }
60
+
61
+ test('untrusted argument JSON is rejected before API access', t => {
62
+ const env = fixture(t);
63
+ const file = Path.join(env.dir, 'input.json');
64
+ for (const payload of unsafe) {
65
+ fs.writeFileSync(file, payload);
66
+ for (const [args, input] of [
67
+ [['--params', payload]],
68
+ [['--json', '@-'], payload],
69
+ [['--json', '@' + file]]
70
+ ]) {
71
+ const result = env.run(['api', 'run_event', ...args], input);
72
+ assert.equal(result.status, 1);
73
+ assert.match(result.stderr, /forbidden prototype property/);
74
+ assert.equal(fs.existsSync(env.marker), false);
75
+ }
76
+ }
77
+ });
78
+
79
+ test('config files and environment JSON reject forbidden properties', t => {
80
+ const env = fixture(t);
81
+ const file = Path.join(env.dir, '.config', 'xyops', 'cli.json');
82
+ fs.mkdirSync(Path.dirname(file), { recursive: true });
83
+ for (const payload of unsafe) {
84
+ fs.writeFileSync(file, payload);
85
+ assert.equal(env.run(['config']).status, 1);
86
+ assert.equal(fs.readFileSync(file, 'utf8'), payload);
87
+ fs.unlinkSync(file);
88
+
89
+ env.env.XYOPS_SYNC = payload;
90
+ const result = env.run(['config']);
91
+ assert.equal(result.status, 1);
92
+ assert.match(result.stderr, /Failed to parse JSON from environment variable: XYOPS_SYNC/);
93
+ delete env.env.XYOPS_SYNC;
94
+ }
95
+ });
96
+
97
+ test('cached API JSON rejects forbidden properties before returning data', async t => {
98
+ const env = fixture(t);
99
+ const config = { base_url: 'https://fixture.invalid' };
100
+ const file = Path.join(env.dir, 'config-' + Tools.digestHex(config.base_url, 'sha256', 16) + '.json');
101
+ const context = { config, tempDir: env.dir };
102
+ for (const payload of unsafe) {
103
+ fs.writeFileSync(file, payload);
104
+ await assert.rejects(utils.cacheAPI.call(context, 'config', {}), /forbidden prototype property/);
105
+ }
106
+ });
107
+
108
+ test('plain and gzip imports reject forbidden properties before planning API calls', async t => {
109
+ const env = fixture(t);
110
+ for (const payload of unsafe) {
111
+ const text = '{"type":"xypdf","version":"1.0","items":[{"type":"event","data":' + payload + '}]}';
112
+ for (const gzip of [false, true]) {
113
+ const file = Path.join(env.dir, gzip ? 'input.json.gz' : 'input.json');
114
+ fs.writeFileSync(file, gzip ? zlib.gzipSync(text) : text);
115
+ const context = {
116
+ args: { other: [file] },
117
+ requireTransferFilename: transfer.requireTransferFilename,
118
+ die(message) { throw new Error(message); },
119
+ async getMultiple() { assert.fail('Import must reject JSON before loading resources'); }
120
+ };
121
+ await assert.rejects(transfer.cmd_import.call(context), /Failed to read XYPDF file: .*forbidden prototype property/);
122
+ }
123
+ }
124
+ });
125
+
126
+ test('npm registry objects are scanned before accepting a version', async t => {
127
+ const fetch = global.fetch;
128
+ t.after(() => { global.fetch = fetch; });
129
+ const context = {
130
+ cli: { progress: { start() {}, end() {} } },
131
+ color() { return text => text; },
132
+ die(message) { throw new Error(message); }
133
+ };
134
+ for (const payload of unsafe) {
135
+ global.fetch = async () => ({ ok: true, async json() {
136
+ return { version: '99.0.0', extra: JSON.parse(payload) };
137
+ } });
138
+ await assert.rejects(upgrade.getLatestXYCLIVersion.call(context), /Could not parse the npm registry response: .*forbidden prototype property/);
139
+ }
140
+ });
@@ -45,6 +45,27 @@ function markerCommand(name) {
45
45
  return `${JSON.stringify(process.execPath)} -e ${JSON.stringify(code)}`;
46
46
  }
47
47
 
48
+ test('syshook rejects forbidden payload and source properties before deleting files', t => {
49
+ for (const property of ['"__proto__":{"polluted":true}', '"constructor":{"prototype":{"polluted":true}}']) {
50
+ var dir = makeTree(t);
51
+ var target = writeSource(dir, 'Event.json', 'event', { id: 'evt_one' });
52
+ var payload = { xy: 1, action: 'event_delete', event: { id: 'evt_one' } };
53
+ // Native parsing here deliberately preserves the unsafe own property so
54
+ // runHook sends the exact attack text through the real STDIN reader.
55
+ var bad_payload = JSON.parse('{"xy":1,"action":"event_delete","event":{"id":"evt_one"},' + property + '}');
56
+ var result = runHook(dir, 'event_delete', bad_payload);
57
+ assert.equal(result.status, 1);
58
+ assert.match(result.stderr, /Invalid System Hook activity JSON: .*forbidden prototype property/);
59
+ assert.equal(fs.existsSync(target), true);
60
+
61
+ fs.writeFileSync(target, '{"type":"xypdf","version":"1.0","items":[{"type":"event","data":{"id":"evt_one",' + property + '}}]}');
62
+ result = runHook(dir, 'event_delete', payload);
63
+ assert.equal(result.status, 1);
64
+ assert.match(result.stderr, /Failed to parse JSON file: .*forbidden prototype property/);
65
+ assert.equal(fs.existsSync(target), true);
66
+ }
67
+ });
68
+
48
69
  test('syshook deletes only the exact Event and its owned neighbors', t => {
49
70
  var dir = makeTree(t);
50
71
  var event = writeSource(dir, 'events/Ops/Nightly.json', 'event', {
@@ -135,6 +135,32 @@ function getSetupMarkerCommand(filename) {
135
135
  return `${JSON.stringify(process.execPath)} -e ${JSON.stringify(code)}`;
136
136
  }
137
137
 
138
+ test('sync rejects forbidden JSON properties before updating managed objects', t => {
139
+ for (const property of ['"__proto__":{"polluted":true}', '"constructor":{"prototype":{"polluted":true}}']) {
140
+ const contents = '{"type":"xypdf","version":"1.0","items":[{"type":"category","data":{"id":"cat_one","title":"Unsafe",' + property + '}}]}';
141
+ const result = runSync(t, {
142
+ args: { up: 'categories' },
143
+ existingSources: [{ path: 'Unsafe.json', contents }],
144
+ categories: [{ id: 'cat_one', title: 'Original' }]
145
+ });
146
+
147
+ assert.equal(result.status, 1);
148
+ assert.match(result.report.warnings.join('\n'), /forbidden prototype property/);
149
+ assert.deepEqual(result.report.calls, []);
150
+ }
151
+ });
152
+
153
+ test('sync still ignores unrelated null JSON after security scanning', t => {
154
+ const result = runSync(t, {
155
+ args: { up: 'categories' },
156
+ existingSources: [{ path: 'Unrelated.json', contents: 'null' }]
157
+ });
158
+
159
+ assert.equal(result.status, 0);
160
+ assert.deepEqual(result.report.warnings, []);
161
+ assert.deepEqual(result.report.calls, []);
162
+ });
163
+
138
164
  test('sync update guard requires confirmation only for the exact managed object', async () => {
139
165
  var warnings = [];
140
166
  var loads = 0;
@@ -5,6 +5,31 @@ const utils = require('../lib/utils.js');
5
5
 
6
6
  cli.global();
7
7
 
8
+ test('server client config cannot supply sync settings or overwrite local settings', async () => {
9
+ const remote = {
10
+ config: { sync: { down_cmd: 'untrusted-command' }, items_per_page: 50, suggest: true },
11
+ masters: ['fixture-master'],
12
+ version: '1.2.3'
13
+ };
14
+
15
+ // Cover an absent setting, an explicitly disabled setting and a configured
16
+ // local command. The server must never introduce or extend sync settings.
17
+ for (const local of [{}, { sync: false }, { sync: { up: ['events'], down_cmd: 'local-command' } }]) {
18
+ const config = { items_per_page: 10, ...local };
19
+ const context = {
20
+ config,
21
+ async cacheAPI() { return { data: remote }; }
22
+ };
23
+ await utils.cacheConfig.call(context);
24
+
25
+ assert.deepEqual(config, { items_per_page: 10, ...local, suggest: true });
26
+ assert.equal(Object.hasOwn(config, 'sync'), Object.hasOwn(local, 'sync'));
27
+ if (Object.hasOwn(local, 'sync')) assert.equal(config.sync, local.sync);
28
+ assert.deepEqual(context.masters, remote.masters);
29
+ assert.equal(context.xyopsVersion, remote.version);
30
+ }
31
+ });
32
+
8
33
  test('executable language detection accepts Unix and Windows command forms', () => {
9
34
  // Plugin definitions are portable, so exercise both path styles regardless of
10
35
  // the operating system running this test.
@@ -5,7 +5,8 @@
5
5
  var fs = require('fs');
6
6
  var Path = require('path');
7
7
  var cp = require('child_process');
8
- var Tools = require('pixl-tools');
8
+ var cli = require('pixl-cli');
9
+ var Tools = cli.Tools;
9
10
 
10
11
  var debug = (process.argv[2] == 'debug');
11
12