mcp-patchbay 0.0.0 → 0.1.1

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/src/config.js ADDED
@@ -0,0 +1,533 @@
1
+ // Config location, strict validation and the permission check. See SPEC.md §2.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { isValidSegment } from './naming.js';
6
+
7
+ export const EX_CONFIG = 78;
8
+ export const MAX_TIMEOUT_MS = 2147483647;
9
+
10
+ export class ConfigError extends Error {
11
+ /** @param {string} message */
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = 'ConfigError';
15
+ this.exitCode = EX_CONFIG;
16
+ }
17
+ }
18
+
19
+ /**
20
+ * @typedef {'allow'|'confirm'|'deny'} Policy
21
+ * @typedef {{
22
+ * name: string, segment: string, kind: 'stdio'|'url', description: string, policy: Policy,
23
+ * command?: string, args: string[], env: Record<string,string>, cwd?: string,
24
+ * url?: string, headers: Record<string,string>, prefix?: string, timeoutMs: number
25
+ * }} ServerEntry
26
+ * @typedef {'elicitation'|'host'} ConfirmVia
27
+ * @typedef {{
28
+ * version: 1, confirmVia: ConfirmVia, order: string[], servers: Record<string, ServerEntry>,
29
+ * autostart: {default: string[], projects: Record<string, string[]>},
30
+ * oauth: {configDir: string, authTimeoutSeconds: number}
31
+ * }} Config
32
+ */
33
+
34
+ /** @param {string} [home] */
35
+ export function defaultConfigPath(home = os.homedir()) {
36
+ return path.join(home, '.config', 'mcp-patchbay', 'servers.json');
37
+ }
38
+
39
+ /** The config the first run writes at the default path: version 1, no servers, no secrets. */
40
+ export const STARTER_CONFIG = '{\n "version": 1,\n "servers": {}\n}\n';
41
+
42
+ /** @param {string} p */
43
+ const samePath = (p) => (process.platform === 'win32' ? path.resolve(p).toLowerCase() : path.resolve(p));
44
+
45
+ /**
46
+ * Creates the starter config when `file` is the default config path and nothing is there yet:
47
+ * a missing directory at 0700 and the file at 0600 (POSIX; Windows has no such modes) (DECISIONS.md, "Zero-config first run"). Any other
48
+ * path is left alone, so a missing `--config` or `$MCP_PATCHBAY_CONFIG` file stays an error in
49
+ * loadConfig. An existing directory must pass checkDirPermissions before anything is written,
50
+ * and an existing entry (a file, or a dangling symlink) is never replaced or followed.
51
+ * @param {string} file
52
+ * @param {string} [home]
53
+ * @returns {boolean} true if this call created the file
54
+ */
55
+ export function ensureStarterConfig(file, home = os.homedir()) {
56
+ const def = defaultConfigPath(home);
57
+ // A trailing separator names a directory, which loadConfig must still refuse.
58
+ if (/[\\/]$/.test(file) || samePath(file) !== samePath(def)) return false;
59
+ try {
60
+ fs.lstatSync(def);
61
+ return false;
62
+ } catch (e) {
63
+ if (/** @type {any} */ (e).code !== 'ENOENT') return false; // loadConfig reports it
64
+ }
65
+ const dir = path.dirname(def);
66
+ const posix = process.platform !== 'win32';
67
+ try {
68
+ const made = fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
69
+ if (posix && made !== undefined) fs.chmodSync(dir, 0o700);
70
+ } catch (e) {
71
+ throw new ConfigError(`cannot create the config directory ${dir}: ${/** @type {any} */ (e).code ?? e}`);
72
+ }
73
+ if (posix) checkDirPermissions(def, dir);
74
+ let fd;
75
+ try {
76
+ // 'wx': never replaces or follows anything that appeared since the check above.
77
+ fd = fs.openSync(def, 'wx', 0o600);
78
+ } catch (e) {
79
+ if (/** @type {any} */ (e).code === 'EEXIST') return false;
80
+ throw new ConfigError(`cannot create config ${def}: ${/** @type {any} */ (e).code ?? e}`);
81
+ }
82
+ try {
83
+ if (posix) fs.fchmodSync(fd, 0o600);
84
+ fs.writeFileSync(fd, STARTER_CONFIG); // loops over short writes, unlike writeSync
85
+ fs.fsyncSync(fd);
86
+ } catch (e) {
87
+ // Never leave a half-written file that the next start would report as invalid JSON.
88
+ fs.closeSync(fd);
89
+ try { fs.rmSync(def, { force: true }); } catch { /* best effort */ }
90
+ throw new ConfigError(`cannot write config ${def}: ${/** @type {any} */ (e).code ?? e}`);
91
+ }
92
+ fs.closeSync(fd);
93
+ return true;
94
+ }
95
+
96
+ /**
97
+ * @param {{flag?: string, env?: NodeJS.ProcessEnv}} o
98
+ */
99
+ export function resolveConfigPath({ flag, env = process.env }) {
100
+ if (flag) return expandConfigPath(flag);
101
+ if (env.MCP_PATCHBAY_CONFIG) return expandConfigPath(env.MCP_PATCHBAY_CONFIG);
102
+ return defaultConfigPath();
103
+ }
104
+
105
+ /**
106
+ * Expands a leading `~` or `${HOME}` in a config path. A client that runs the Claude Desktop
107
+ * bundle may pass the manifest's default (`${HOME}/...`) through unexpanded; nothing else in
108
+ * the path is touched.
109
+ * @param {string} p
110
+ */
111
+ export function expandConfigPath(p) {
112
+ if (p === '${HOME}' || p.startsWith('${HOME}/') || p.startsWith('${HOME}\\')) return os.homedir() + p.slice('${HOME}'.length);
113
+ return expandHome(p);
114
+ }
115
+
116
+ /** @param {string} p */
117
+ export function expandHome(p) {
118
+ if (p === '~') return os.homedir();
119
+ if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));
120
+ return p;
121
+ }
122
+
123
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
124
+ const where = (p) => (p ? p : '(root)');
125
+
126
+ /**
127
+ * @param {Record<string, unknown>} obj
128
+ * @param {string[]} allowed
129
+ * @param {string} at
130
+ */
131
+ function onlyKeys(obj, allowed, at) {
132
+ for (const k of Object.keys(obj)) {
133
+ if (!allowed.includes(k)) {
134
+ throw new ConfigError(`unknown key "${k}" at ${where(at)} (allowed: ${allowed.join(', ')})`);
135
+ }
136
+ }
137
+ }
138
+
139
+ /** @param {unknown} v @param {string} at */
140
+ function stringMap(v, at, keyRe, keyWhat) {
141
+ if (!isObj(v)) throw new ConfigError(`${at} must be an object of strings`);
142
+ /** @type {Record<string,string>} */
143
+ const out = {};
144
+ for (const [k, val] of Object.entries(/** @type {object} */ (v))) {
145
+ if (!keyRe.test(k)) throw new ConfigError(`${keyWhat} "${k}" at ${at} is not valid`);
146
+ if (typeof val !== 'string') throw new ConfigError(`${at}.${k} must be a string`);
147
+ // defineProperty, not out[k] = …: a key "__proto__" must stay a key, not set the prototype.
148
+ Object.defineProperty(out, k, { value: val, enumerable: true, writable: true, configurable: true });
149
+ }
150
+ return out;
151
+ }
152
+
153
+ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
154
+ const HEADER_KEY = /^[A-Za-z0-9_-]+$/; // mcp-remote 0.15.2 parseHeaderLine
155
+ const SERVER_KEYS = ['description', 'policy', 'command', 'args', 'env', 'cwd', 'url', 'headers', 'prefix', 'timeoutMs'];
156
+ const POLICIES = ['allow', 'confirm', 'deny'];
157
+ export const CONFIRM_VIA = ['elicitation', 'host'];
158
+
159
+ /**
160
+ * @param {string} name
161
+ * @param {any} raw
162
+ * @returns {ServerEntry}
163
+ */
164
+ function validateServer(name, raw) {
165
+ const at = `servers.${name}`;
166
+ if (!isValidSegment(name)) {
167
+ throw new ConfigError(`server name "${name}" is not valid: use 1-64 of [A-Za-z0-9_-], no "__", and no trailing "_"`);
168
+ }
169
+ if (!isObj(raw)) throw new ConfigError(`${at} must be an object`);
170
+ onlyKeys(raw, SERVER_KEYS, at);
171
+ const hasCommand = raw.command !== undefined;
172
+ const hasUrl = raw.url !== undefined;
173
+ if (hasCommand === hasUrl) throw new ConfigError(`${at} must have exactly one of command or url`);
174
+
175
+ const description = raw.description ?? '';
176
+ if (typeof description !== 'string') throw new ConfigError(`${at}.description must be a string`);
177
+ if (/[\r\n]/.test(description)) throw new ConfigError(`${at}.description must be one line`);
178
+ if (description.length > 300) throw new ConfigError(`${at}.description must be at most 300 characters`);
179
+
180
+ const policy = raw.policy ?? 'confirm';
181
+ if (!POLICIES.includes(policy)) throw new ConfigError(`${at}.policy must be one of ${POLICIES.join(', ')}`);
182
+
183
+ const timeoutMs = raw.timeoutMs ?? 0;
184
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMEOUT_MS) {
185
+ throw new ConfigError(`${at}.timeoutMs must be an integer from 0 (no cap) to ${MAX_TIMEOUT_MS}`);
186
+ }
187
+
188
+ let prefix;
189
+ if (raw.prefix !== undefined) {
190
+ if (!isValidSegment(raw.prefix)) {
191
+ throw new ConfigError(`${at}.prefix "${raw.prefix}" is not valid: use 1-64 of [A-Za-z0-9_-], no "__", and no trailing "_"`);
192
+ }
193
+ prefix = raw.prefix;
194
+ }
195
+
196
+ const env = raw.env === undefined ? {} : stringMap(raw.env, `${at}.env`, ENV_KEY, 'env key');
197
+
198
+ /** @type {ServerEntry} */
199
+ const entry = {
200
+ name,
201
+ segment: prefix ?? name,
202
+ kind: hasCommand ? 'stdio' : 'url',
203
+ description,
204
+ policy,
205
+ args: [],
206
+ env,
207
+ headers: {},
208
+ timeoutMs,
209
+ };
210
+ if (prefix) entry.prefix = prefix;
211
+
212
+ if (hasCommand) {
213
+ if (typeof raw.command !== 'string' || !raw.command) throw new ConfigError(`${at}.command must be a non-empty string`);
214
+ if (raw.headers !== undefined) throw new ConfigError(`${at}.headers applies only to url servers`);
215
+ entry.command = raw.command;
216
+ if (raw.args !== undefined) {
217
+ if (!Array.isArray(raw.args) || !raw.args.every((a) => typeof a === 'string')) {
218
+ throw new ConfigError(`${at}.args must be an array of strings`);
219
+ }
220
+ entry.args = [...raw.args];
221
+ }
222
+ if (raw.cwd !== undefined) {
223
+ if (typeof raw.cwd !== 'string' || !(path.isAbsolute(raw.cwd) || path.win32.isAbsolute(raw.cwd))) {
224
+ throw new ConfigError(`${at}.cwd must be an absolute path`);
225
+ }
226
+ entry.cwd = raw.cwd;
227
+ }
228
+ } else {
229
+ if (raw.args !== undefined) throw new ConfigError(`${at}.args applies only to command servers`);
230
+ if (raw.cwd !== undefined) throw new ConfigError(`${at}.cwd applies only to command servers`);
231
+ if (typeof raw.url !== 'string') throw new ConfigError(`${at}.url must be a string`);
232
+ let u;
233
+ try {
234
+ u = new URL(raw.url);
235
+ } catch {
236
+ throw new ConfigError(`${at}.url must be an absolute http(s) URL`);
237
+ }
238
+ const loopback = u.hostname === 'localhost' || u.hostname === '127.0.0.1';
239
+ if (!(u.protocol === 'https:' || (u.protocol === 'http:' && loopback))) {
240
+ throw new ConfigError(`${at}.url must use https (plain http is only allowed for localhost and 127.0.0.1)`);
241
+ }
242
+ entry.url = raw.url;
243
+ if (raw.headers !== undefined) {
244
+ entry.headers = stringMap(raw.headers, `${at}.headers`, HEADER_KEY, 'header name');
245
+ for (const [k, v] of Object.entries(entry.headers)) {
246
+ if (/[\r\n]/.test(v)) throw new ConfigError(`${at}.headers.${k} must not contain line breaks`);
247
+ }
248
+ }
249
+ }
250
+ return entry;
251
+ }
252
+
253
+ /**
254
+ * Validates a parsed config strictly and returns a normalised copy.
255
+ * @param {any} raw
256
+ * @returns {Config}
257
+ */
258
+ export function validateConfig(raw) {
259
+ if (!isObj(raw)) throw new ConfigError('the config must be a JSON object');
260
+ onlyKeys(raw, ['version', 'confirmVia', 'servers', 'autostart', 'oauth'], '');
261
+ if (raw.version !== 1) throw new ConfigError('version must be 1');
262
+ const confirmVia = raw.confirmVia === undefined ? 'elicitation' : raw.confirmVia;
263
+ if (!CONFIRM_VIA.includes(confirmVia)) throw new ConfigError(`confirmVia must be one of ${CONFIRM_VIA.join(', ')}`);
264
+ if (raw.servers === undefined) throw new ConfigError('servers is required');
265
+ if (!isObj(raw.servers)) throw new ConfigError('servers must be an object');
266
+
267
+ /** @type {Record<string, ServerEntry>} */
268
+ const servers = {};
269
+ const order = [];
270
+ /** @type {Map<string, string>} */
271
+ const segments = new Map();
272
+ for (const [name, entry] of Object.entries(raw.servers)) {
273
+ const s = validateServer(name, entry);
274
+ const key = s.segment.toLowerCase();
275
+ const other = segments.get(key);
276
+ if (other !== undefined) {
277
+ throw new ConfigError(`servers.${name}: tool-name segment "${s.segment}" is already used by server "${other}" (names and prefixes must be unique, ignoring case)`);
278
+ }
279
+ segments.set(key, name);
280
+ servers[name] = s;
281
+ order.push(name);
282
+ }
283
+
284
+ const autostart = { default: /** @type {string[]} */ ([]), projects: /** @type {Record<string,string[]>} */ ({}) };
285
+ if (raw.autostart !== undefined) {
286
+ if (!isObj(raw.autostart)) throw new ConfigError('autostart must be an object');
287
+ onlyKeys(raw.autostart, ['default', 'projects'], 'autostart');
288
+ const names = (v, at) => {
289
+ if (!Array.isArray(v) || !v.every((x) => typeof x === 'string')) throw new ConfigError(`${at} must be an array of server names`);
290
+ for (const n of v) {
291
+ // hasOwn: "constructor", "toString" and "__proto__" are inherited, not configured servers.
292
+ if (!Object.hasOwn(servers, n)) throw new ConfigError(`${at} names unknown server "${n}"`);
293
+ if (servers[n].policy === 'deny') throw new ConfigError(`${at} names "${n}", whose policy is deny`);
294
+ }
295
+ return [...new Set(v)];
296
+ };
297
+ if (raw.autostart.default !== undefined) autostart.default = names(raw.autostart.default, 'autostart.default');
298
+ if (raw.autostart.projects !== undefined) {
299
+ if (!isObj(raw.autostart.projects)) throw new ConfigError('autostart.projects must be an object');
300
+ for (const [dir, list] of Object.entries(raw.autostart.projects)) {
301
+ if (!(path.isAbsolute(dir) || path.win32.isAbsolute(dir))) {
302
+ throw new ConfigError(`autostart.projects key "${dir}" must be an absolute path`);
303
+ }
304
+ autostart.projects[dir] = names(list, `autostart.projects["${dir}"]`);
305
+ }
306
+ }
307
+ }
308
+
309
+ const oauth = { configDir: expandHome('~/.config/mcp-patchbay/oauth'), authTimeoutSeconds: 300 };
310
+ if (raw.oauth !== undefined) {
311
+ if (!isObj(raw.oauth)) throw new ConfigError('oauth must be an object');
312
+ onlyKeys(raw.oauth, ['configDir', 'authTimeoutSeconds'], 'oauth');
313
+ if (raw.oauth.configDir !== undefined) {
314
+ if (typeof raw.oauth.configDir !== 'string' || !raw.oauth.configDir) throw new ConfigError('oauth.configDir must be a path');
315
+ const dir = expandHome(raw.oauth.configDir);
316
+ if (!(path.isAbsolute(dir) || path.win32.isAbsolute(dir))) throw new ConfigError('oauth.configDir must be absolute (or start with ~)');
317
+ oauth.configDir = dir;
318
+ }
319
+ if (raw.oauth.authTimeoutSeconds !== undefined) {
320
+ const t = raw.oauth.authTimeoutSeconds;
321
+ if (!Number.isInteger(t) || t < 1 || t > 86400) throw new ConfigError('oauth.authTimeoutSeconds must be an integer from 1 to 86400');
322
+ oauth.authTimeoutSeconds = t;
323
+ }
324
+ }
325
+
326
+ return { version: 1, confirmVia, order, servers, autostart, oauth };
327
+ }
328
+
329
+ /**
330
+ * Refuses a config file that someone else could have rewritten (POSIX only).
331
+ * @param {string} file
332
+ * @param {fs.Stats} st
333
+ */
334
+ export function checkFilePermissions(file, st) {
335
+ if (process.platform === 'win32') return;
336
+ if (st.mode & 0o022) {
337
+ throw new ConfigError(
338
+ `refusing to start: ${file} is group- or world-writable (mode ${(st.mode & 0o777).toString(8)}). ` +
339
+ `The config decides which programs run, so only you may be able to change it. Fix it with: chmod 600 ${file}`,
340
+ );
341
+ }
342
+ const uid = process.getuid?.();
343
+ if (uid !== undefined && st.uid !== uid && st.uid !== 0) {
344
+ throw new ConfigError(`refusing to start: ${file} is owned by uid ${st.uid}, not by you (uid ${uid}) or root.`);
345
+ }
346
+ }
347
+
348
+ /**
349
+ * The offset of the first JSON syntax error in `text`, or -1 if it is valid JSON. Used to report
350
+ * a location without quoting the text: V8's own message ("Unexpected token 'g', ..."B_TOKEN":
351
+ * ghp_abc"... is not valid JSON") includes a snippet of the file, which may hold a secret.
352
+ * @param {string} text
353
+ * @returns {number}
354
+ */
355
+ export function jsonErrorPosition(text) {
356
+ let i = 0;
357
+ const n = text.length;
358
+ const stop = {};
359
+ const fail = () => { throw stop; };
360
+ const ws = () => { while (i < n && ' \t\n\r'.includes(text[i])) i++; };
361
+ const str = () => {
362
+ i++;
363
+ while (i < n) {
364
+ const c = text[i];
365
+ if (c === '"') { i++; return; }
366
+ if (c < ' ') fail();
367
+ if (c === '\\') {
368
+ const e = text[i + 1];
369
+ if (e !== undefined && '"\\/bfnrt'.includes(e)) i += 2;
370
+ else if (e === 'u' && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) i += 6;
371
+ else { i++; fail(); }
372
+ } else i++;
373
+ }
374
+ fail();
375
+ };
376
+ const NUM = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
377
+ const value = () => {
378
+ ws();
379
+ const c = text[i];
380
+ if (c === '{' || c === '[') {
381
+ const close = c === '{' ? '}' : ']';
382
+ i++;
383
+ ws();
384
+ if (text[i] === close) { i++; return; }
385
+ for (;;) {
386
+ if (c === '{') {
387
+ ws();
388
+ if (text[i] !== '"') fail();
389
+ str();
390
+ ws();
391
+ if (text[i] !== ':') fail();
392
+ i++;
393
+ }
394
+ value();
395
+ ws();
396
+ if (text[i] === ',') { i++; continue; }
397
+ if (text[i] === close) { i++; return; }
398
+ fail();
399
+ }
400
+ }
401
+ if (c === '"') return str();
402
+ for (const word of ['true', 'false', 'null']) {
403
+ if (c === word[0]) {
404
+ for (const ch of word) { if (text[i] !== ch) fail(); i++; }
405
+ return;
406
+ }
407
+ }
408
+ NUM.lastIndex = i;
409
+ if (!NUM.exec(text)) fail();
410
+ i = NUM.lastIndex;
411
+ };
412
+ try {
413
+ value();
414
+ ws();
415
+ if (i < n) fail();
416
+ return -1;
417
+ } catch (e) {
418
+ if (e === stop) return i;
419
+ return -1; // too deeply nested to scan
420
+ }
421
+ }
422
+
423
+ /**
424
+ * "<what> is not valid JSON (line L, column C)", without quoting any of the text.
425
+ * @param {string} what e.g. "config /path/to/servers.json"
426
+ * @param {string} text
427
+ */
428
+ export function jsonSyntaxMessage(what, text) {
429
+ const pos = jsonErrorPosition(text);
430
+ if (pos < 0) return `${what} is not valid JSON`;
431
+ const before = text.slice(0, pos);
432
+ const line = before.split('\n').length;
433
+ const column = pos - before.lastIndexOf('\n');
434
+ return `${what} is not valid JSON (line ${line}, column ${column})`;
435
+ }
436
+
437
+ /**
438
+ * Refuses a directory holding the config (or the file a config symlink points to) that someone
439
+ * else could change: group- or world-writable (sticky or not), or owned by someone other than
440
+ * you or root. Whoever can write the directory can replace the file (POSIX only).
441
+ * @param {string} file the config path, for the message
442
+ * @param {string} dir
443
+ */
444
+ export function checkDirPermissions(file, dir) {
445
+ if (process.platform === 'win32') return;
446
+ let st;
447
+ try {
448
+ st = fs.statSync(dir);
449
+ } catch (e) {
450
+ throw new ConfigError(`cannot check the directory of config ${file}: ${/** @type {any} */ (e).code ?? e}`);
451
+ }
452
+ if (st.mode & 0o022) {
453
+ throw new ConfigError(
454
+ `refusing to start: the directory ${dir} holding config ${file} is group- or world-writable ` +
455
+ `(mode ${(st.mode & 0o7777).toString(8)}), so someone else could replace the config. ` +
456
+ `Fix it with: chmod go-w ${dir}, or move the config to a directory only you can write.`,
457
+ );
458
+ }
459
+ const uid = process.getuid?.();
460
+ if (uid !== undefined && st.uid !== uid && st.uid !== 0) {
461
+ throw new ConfigError(`refusing to start: the directory ${dir} holding config ${file} is owned by uid ${st.uid}, not by you (uid ${uid}) or root.`);
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Reads, checks and validates the config file once. The file is opened once and the checks and
467
+ * the read use that descriptor, so it cannot be swapped between check and read. A symlink is
468
+ * followed; then its target must pass the same checks, and so must the directories holding the
469
+ * link and the target (DECISIONS.md).
470
+ * @param {string} file
471
+ * @returns {Config}
472
+ */
473
+ export function loadConfig(file) {
474
+ const posix = process.platform !== 'win32';
475
+ let fd;
476
+ try {
477
+ // O_NONBLOCK: opening a FIFO must not hang startup; it is refused below as not a regular file.
478
+ fd = fs.openSync(file, posix ? fs.constants.O_RDONLY | fs.constants.O_NONBLOCK : 'r');
479
+ } catch (e) {
480
+ throw new ConfigError(`cannot read config ${file}: ${/** @type {any} */ (e).code ?? e}. Create it (see examples/servers.json) or pass --config <path>.`);
481
+ }
482
+ let text;
483
+ try {
484
+ const st = fs.fstatSync(fd);
485
+ if (!st.isFile()) throw new ConfigError(`config ${file} is not a regular file`);
486
+ checkFilePermissions(file, st);
487
+ if (posix) {
488
+ const dirs = new Set([path.dirname(path.resolve(file))]);
489
+ if (fs.lstatSync(file).isSymbolicLink()) dirs.add(path.dirname(fs.realpathSync(file)));
490
+ for (const dir of dirs) checkDirPermissions(file, dir);
491
+ }
492
+ try {
493
+ text = fs.readFileSync(fd, 'utf8');
494
+ } catch (e) {
495
+ throw new ConfigError(`cannot read config ${file}: ${/** @type {any} */ (e).code ?? e}`);
496
+ }
497
+ } finally {
498
+ fs.closeSync(fd);
499
+ }
500
+ let raw;
501
+ try {
502
+ raw = JSON.parse(text);
503
+ } catch {
504
+ // Never e.message: V8 quotes the text around the error, which may be a secret.
505
+ throw new ConfigError(jsonSyntaxMessage(`config ${file}`, text));
506
+ }
507
+ try {
508
+ return validateConfig(raw);
509
+ } catch (e) {
510
+ if (e instanceof ConfigError) e.message = `config ${file}: ${e.message}`;
511
+ throw e;
512
+ }
513
+ }
514
+
515
+ /** @param {string} p */
516
+ function normDir(p) {
517
+ let r = path.resolve(p);
518
+ if (process.platform === 'win32') r = r.toLowerCase();
519
+ return r;
520
+ }
521
+
522
+ /**
523
+ * The servers to autostart for a project directory.
524
+ * @param {Config} config
525
+ * @param {string} projectDir
526
+ */
527
+ export function autostartFor(config, projectDir) {
528
+ const want = normDir(projectDir);
529
+ for (const [dir, list] of Object.entries(config.autostart.projects)) {
530
+ if (normDir(dir) === want) return [...list];
531
+ }
532
+ return [...config.autostart.default];
533
+ }
package/src/doctor.js ADDED
@@ -0,0 +1,124 @@
1
+ // `mcp-patchbay doctor`: validate the config, check Claude Code's allow rules against
2
+ // enable_confirm, and briefly start servers. See SPEC.md §10.
3
+ import path from 'node:path';
4
+ import { Child } from './children.js';
5
+ import { ConfigError, EX_CONFIG, loadConfig, resolveConfigPath } from './config.js';
6
+ import { createLogger } from './log.js';
7
+ import { ENABLE_CONFIRM_CLIENT_NAME, scanSettings, settingsFiles } from './permissions.js';
8
+ import { PidFiles, pidDirFor } from './process.js';
9
+ import { redact } from './redact.js';
10
+
11
+ const STDIO_BUDGET_MS = 60000;
12
+
13
+ /**
14
+ * Prints what in Claude Code's settings would approve enable_confirm without asking the person.
15
+ * @param {import('./config.js').Config} config
16
+ * @param {string | undefined} project
17
+ * @param {(s: string) => void} out
18
+ * @returns {number} how many findings would weaken a confirm (counted only with confirmVia "host")
19
+ */
20
+ function checkPermissions(config, project, out) {
21
+ const host = config.confirmVia === 'host';
22
+ out(`confirmVia: ${config.confirmVia}${host ? ` (confirm servers are turned on with ${ENABLE_CONFIRM_CLIENT_NAME}, approved in the host's permission prompt)` : ''}\n`);
23
+ let findings = 0;
24
+ const label = host ? 'warning' : 'note';
25
+ const why = host
26
+ ? 'the host would run it without asking, so a confirm server would start with no person approving'
27
+ : 'harmless while confirmVia is elicitation, but it would approve enable_confirm without asking if you switch to host';
28
+ for (const r of scanSettings(settingsFiles({ project }))) {
29
+ if (r.status === 'missing') {
30
+ out(`permissions: ${r.file}: not found\n`);
31
+ continue;
32
+ }
33
+ if (r.status === 'unreadable') {
34
+ out(`permissions: ${r.file}: ${r.error}; not checked\n`);
35
+ if (host) findings++;
36
+ continue;
37
+ }
38
+ if (!r.rules.length && !r.bypass) {
39
+ out(`permissions: ${r.file}: ok, no allow rule matches ${ENABLE_CONFIRM_CLIENT_NAME}\n`);
40
+ continue;
41
+ }
42
+ for (const rule of r.rules) {
43
+ out(`permissions: ${label}: ${r.file}: allow rule "${rule}" matches ${ENABLE_CONFIRM_CLIENT_NAME}; ${why}. Remove it, or allow individual tools instead.\n`);
44
+ }
45
+ if (r.bypass) {
46
+ out(`permissions: ${label}: ${r.file}: permissions.defaultMode is bypassPermissions, which approves every tool, ${ENABLE_CONFIRM_CLIENT_NAME} included, without asking.\n`);
47
+ }
48
+ if (host) findings += r.rules.length + (r.bypass ? 1 : 0);
49
+ }
50
+ return findings;
51
+ }
52
+
53
+ /**
54
+ * @param {string[]} argv
55
+ * @param {{out?: (s: string) => void, err?: (s: string) => void}} [io]
56
+ * @returns {Promise<number>} exit code
57
+ */
58
+ export async function runDoctor(argv, io = {}) {
59
+ const out = io.out ?? ((s) => process.stdout.write(s));
60
+ const err = io.err ?? ((s) => process.stderr.write(s));
61
+ let configFlag;
62
+ let project;
63
+ let all = false;
64
+ let start = true;
65
+ for (let i = 0; i < argv.length; i++) {
66
+ if (argv[i] === '--all') all = true;
67
+ else if (argv[i] === '--no-start') start = false;
68
+ else if (argv[i] === '--config' && argv[i + 1] !== undefined) configFlag = argv[++i];
69
+ else if (argv[i].startsWith('--config=')) configFlag = argv[i].slice(9);
70
+ else if (argv[i] === '--project' && argv[i + 1] !== undefined) project = argv[++i];
71
+ else if (argv[i].startsWith('--project=')) project = argv[i].slice(10);
72
+ else {
73
+ err(`doctor: unknown argument ${argv[i]}\n`);
74
+ return 64;
75
+ }
76
+ }
77
+ if (project !== undefined) project = path.resolve(project);
78
+ const configPath = resolveConfigPath({ flag: configFlag });
79
+ let config;
80
+ try {
81
+ config = loadConfig(configPath);
82
+ } catch (e) {
83
+ if (e instanceof ConfigError) {
84
+ err(`mcp-patchbay doctor: ${e.message}\n`);
85
+ return EX_CONFIG;
86
+ }
87
+ throw e;
88
+ }
89
+ out(`config ok: ${configPath} (${config.order.length} servers)\n`);
90
+ const findings = checkPermissions(config, project, out);
91
+ if (!start) return findings ? 1 : 0;
92
+
93
+ // Child chatter goes to stderr only with MCP_PATCHBAY_DEBUG=1.
94
+ const log = createLogger({ write: (s) => err(s) });
95
+ const pidFiles = new PidFiles(pidDirFor(process.env), log);
96
+ let failed = 0;
97
+ for (const name of config.order) {
98
+ const entry = config.servers[name];
99
+ if (entry.policy === 'deny') {
100
+ out(`${name}: skipped (policy deny)\n`);
101
+ continue;
102
+ }
103
+ if (entry.policy === 'confirm' && !all) {
104
+ out(`${name}: skipped (policy confirm; use --all)\n`);
105
+ continue;
106
+ }
107
+ const child = new Child({ entry, oauth: config.oauth, clientCapabilities: {}, log, pidFiles });
108
+ child.on('auth-url', () => err(`${name}: needs a sign-in; mcp-remote should open your browser (waiting up to ${config.oauth.authTimeoutSeconds} s)\n`));
109
+ const budget = entry.kind === 'url' ? config.oauth.authTimeoutSeconds * 1000 + 60000 : STDIO_BUDGET_MS;
110
+ try {
111
+ await child.start(budget);
112
+ const tools = await child.listTools(budget);
113
+ out(`${name}: ok, ${tools.length} tool${tools.length === 1 ? '' : 's'}\n`);
114
+ } catch (e) {
115
+ failed++;
116
+ const last = child.stderrTail(1)[0];
117
+ const why = String(/** @type {any} */ (e)?.code === 'ENOENT' ? 'command not found (ENOENT)' : /** @type {Error} */ (e)?.message ?? e).replace(/^MCP error -?\d+: /, '');
118
+ out(`${name}: failed: ${redact(last ? `${why}; first stderr: ${child.stderrTail(20)[0]}` : why, child.secrets)}\n`);
119
+ } finally {
120
+ await child.close().catch(() => {});
121
+ }
122
+ }
123
+ return failed || findings ? 1 : 0;
124
+ }