mcp-patchbay 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/process.js ADDED
@@ -0,0 +1,367 @@
1
+ // Process-tree killing, pidfiles and reaping of leftovers. See SPEC.md §9.
2
+ import { createHash } from 'node:crypto';
3
+ import { execFile, execFileSync, spawn } from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+
8
+ const IS_WINDOWS = process.platform === 'win32';
9
+
10
+ /** A per-user id usable in a directory name. */
11
+ function userTag() {
12
+ const uid = process.getuid?.();
13
+ if (uid !== undefined) return String(uid);
14
+ let name = 'user';
15
+ try { name = os.userInfo().username; } catch { /* keep default */ }
16
+ return name.replace(/[^A-Za-z0-9_-]/g, '_') || 'user';
17
+ }
18
+
19
+ /**
20
+ * `${XDG_RUNTIME_DIR or os.tmpdir()}/mcp-patchbay-<uid>`
21
+ * @param {NodeJS.ProcessEnv} [env]
22
+ */
23
+ export function pidDirFor(env = process.env) {
24
+ const base = env.XDG_RUNTIME_DIR || os.tmpdir();
25
+ return path.join(base, `mcp-patchbay-${userTag()}`);
26
+ }
27
+
28
+ /**
29
+ * The command line of a running process as the OS reports it, or null.
30
+ * @param {number} pid
31
+ * @returns {string | null}
32
+ */
33
+ export function commandLineOf(pid) {
34
+ if (!Number.isInteger(pid) || pid <= 0) return null;
35
+ try {
36
+ if (process.platform === 'linux') {
37
+ const raw = fs.readFileSync(`/proc/${pid}/cmdline`);
38
+ const s = raw.toString('utf8').split('\0').filter((x) => x !== '').join(' ');
39
+ return s || null;
40
+ }
41
+ const c = commandLineQuery(pid);
42
+ return execFileSync(c.file, c.args, { ...c.opts, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * commandLineOf without blocking the event loop on ps / PowerShell (slow on Windows).
50
+ * @param {number} pid
51
+ * @returns {Promise<string | null>}
52
+ */
53
+ export function commandLineOfAsync(pid) {
54
+ if (process.platform === 'linux' || !Number.isInteger(pid) || pid <= 0) return Promise.resolve(commandLineOf(pid));
55
+ const c = commandLineQuery(pid);
56
+ return new Promise((resolve) => {
57
+ try {
58
+ execFile(c.file, c.args, c.opts, (err, out) => resolve(err ? null : String(out).trim() || null));
59
+ } catch {
60
+ resolve(null);
61
+ }
62
+ });
63
+ }
64
+
65
+ /** The ps / PowerShell query for a process's command line (not used on Linux). @param {number} pid */
66
+ function commandLineQuery(pid) {
67
+ if (IS_WINDOWS) {
68
+ return {
69
+ file: 'powershell.exe',
70
+ args: ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`],
71
+ opts: { encoding: /** @type {const} */ ('utf8'), windowsHide: true, timeout: 10000 },
72
+ };
73
+ }
74
+ return { file: 'ps', args: ['-ww', '-o', 'command=', '-p', String(pid)], opts: { encoding: /** @type {const} */ ('utf8'), timeout: 5000 } };
75
+ }
76
+
77
+ /** @param {string} s */
78
+ export function hashCommandLine(s) {
79
+ return createHash('sha256').update(s).digest('hex');
80
+ }
81
+
82
+ /**
83
+ * Linux: the process start time (field 22 of /proc/<pid>/stat, clock ticks since boot) and its
84
+ * process group id (field 5). Elsewhere, or if the process is gone: null.
85
+ * @param {number} pid
86
+ * @returns {{start: string, pgid: number} | null}
87
+ */
88
+ export function procStat(pid) {
89
+ if (process.platform !== 'linux' || !Number.isInteger(pid) || pid <= 0) return null;
90
+ try {
91
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
92
+ // The command name (field 2) is in parentheses and may contain spaces; fields after it are
93
+ // plain. parts[0] is field 3.
94
+ const parts = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
95
+ return { pgid: Number(parts[2]), start: parts[19] };
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /** @param {number} pid @returns {string | undefined} Linux only */
102
+ export function processStartTime(pid) {
103
+ return procStat(pid)?.start;
104
+ }
105
+
106
+ /** @param {number} pid */
107
+ export function pidAlive(pid) {
108
+ try {
109
+ process.kill(pid, 0);
110
+ return true;
111
+ } catch (e) {
112
+ return /** @type {any} */ (e).code === 'EPERM';
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Kills a child's whole tree, synchronously as far as the OS allows.
118
+ * POSIX: signal the process group (the child leads its own group, spawned detached).
119
+ * Windows: a detached, unref'd `taskkill /T /F /PID` (it outlives us if we exit next).
120
+ * @param {number} pid
121
+ * @param {NodeJS.Signals} [signal]
122
+ * @param {{bare?: boolean}} [o] bare: false never falls back to signalling the bare pid. The
123
+ * fallback is only safe for a child we have not reaped yet (its pid cannot be reused); post-exit
124
+ * cleanup and the reaper pass false.
125
+ * @returns {boolean} whether anything was signalled
126
+ */
127
+ export function killTree(pid, signal = 'SIGTERM', o = {}) {
128
+ if (!Number.isInteger(pid) || pid <= 0) return false;
129
+ if (IS_WINDOWS) {
130
+ try {
131
+ const k = spawn('taskkill', ['/T', '/F', '/PID', String(pid)], { detached: true, stdio: 'ignore', windowsHide: true });
132
+ k.on('error', () => {});
133
+ k.unref();
134
+ return true;
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+ try {
140
+ process.kill(-pid, signal);
141
+ return true;
142
+ } catch {
143
+ if (o.bare === false) return false;
144
+ try {
145
+ process.kill(pid, signal);
146
+ return true;
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+ }
152
+
153
+ /** Delay before the shutdown helper SIGKILLs the groups that survived SIGTERM. */
154
+ export const SHUTDOWN_KILL_DELAY_MS = 500;
155
+
156
+ // Runs in a detached `node -e` helper: argv[1] is the delay, argv[2] a JSON list of
157
+ // {pid, start, file}. After the delay it SIGKILLs each group whose leader is either gone
158
+ // (then the id is still reserved by the group's members, or unused) or still the same process
159
+ // (same start time, Linux). Then it removes the pidfiles of leaders that are gone.
160
+ const KILL_HELPER = `
161
+ const fs = require('fs');
162
+ const stat = (pid) => { try { const s = fs.readFileSync('/proc/' + pid + '/stat', 'utf8'); return s.slice(s.lastIndexOf(')') + 2).split(' ')[19]; } catch { return null; } };
163
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
164
+ const items = JSON.parse(process.argv[2]);
165
+ setTimeout(() => {
166
+ for (const it of items) {
167
+ if (alive(it.pid) && it.start && stat(it.pid) !== it.start) continue;
168
+ try { process.kill(-it.pid, 'SIGKILL'); } catch {}
169
+ }
170
+ setTimeout(() => {
171
+ for (const it of items) if (it.file && !alive(it.pid)) { try { fs.rmSync(it.file, { force: true }); } catch {} }
172
+ }, 200);
173
+ }, Number(process.argv[1]));
174
+ `;
175
+
176
+ /**
177
+ * POSIX: starts a detached helper that SIGKILLs the given process groups after `delayMs`, so
178
+ * children that ignore SIGTERM do not outlive the patchbay. Returns at once; the helper is
179
+ * unref'd and survives our exit.
180
+ * @param {Array<{pid: number, start?: string, file?: string}>} items
181
+ * @param {number} [delayMs]
182
+ */
183
+ export function killGroupsLater(items, delayMs = SHUTDOWN_KILL_DELAY_MS) {
184
+ if (IS_WINDOWS || !items.length) return;
185
+ try {
186
+ const h = spawn(process.execPath, ['-e', KILL_HELPER, String(delayMs), JSON.stringify(items)], { detached: true, stdio: 'ignore' });
187
+ h.on('error', () => {});
188
+ h.unref();
189
+ } catch { /* the reaper of the next start is the fallback */ }
190
+ }
191
+
192
+ /** How long the reaper waits after SIGTERM before it sends SIGKILL. */
193
+ export const REAP_GRACE_MS = 1000;
194
+
195
+ /**
196
+ * The process group id of `pid` (POSIX), or null.
197
+ * @param {number} pid
198
+ * @returns {number | null}
199
+ */
200
+ export function processGroupOf(pid) {
201
+ if (IS_WINDOWS) return null;
202
+ if (process.platform === 'linux') return procStat(pid)?.pgid ?? null;
203
+ try {
204
+ const out = execFileSync('ps', ['-o', 'pgid=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
205
+ const g = Number(out.trim());
206
+ return Number.isInteger(g) && g > 0 ? g : null;
207
+ } catch {
208
+ return null;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Is `pid` still the process a pidfile recorded? Its command line must hash to the recorded
214
+ * value; on Linux its start time must equal the recorded one (a pidfile without it is not
215
+ * trusted); on POSIX it must still lead its own process group, as the children we spawn do.
216
+ * @param {number} pid
217
+ * @param {any} rec
218
+ */
219
+ function isLeftover(pid, rec) {
220
+ if (!pidAlive(pid)) return false;
221
+ if (process.platform === 'linux') {
222
+ const st = procStat(pid);
223
+ if (!st || typeof rec.start !== 'string' || st.start !== rec.start || st.pgid !== pid) return false;
224
+ } else if (!IS_WINDOWS && processGroupOf(pid) !== pid) {
225
+ return false;
226
+ }
227
+ const cmd = commandLineOf(pid);
228
+ return Boolean(cmd && typeof rec.cmd === 'string' && hashCommandLine(cmd) === rec.cmd);
229
+ }
230
+
231
+ /** Pidfiles for the children of this patchbay process. */
232
+ export class PidFiles {
233
+ /**
234
+ * @param {string} dir
235
+ * @param {import('./log.js').Logger} log
236
+ */
237
+ constructor(dir, log) {
238
+ this.dir = dir;
239
+ this.log = log;
240
+ this.enabled = this.#prepare();
241
+ /** @type {Set<string>} */
242
+ this.mine = new Set();
243
+ /** Pids whose command line is still being looked up, with the lookup's number; remove() drops them. */
244
+ /** @type {Map<number, number>} */
245
+ this.pending = new Map();
246
+ this.lookups = 0;
247
+ }
248
+
249
+ #prepare() {
250
+ try {
251
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
252
+ const st = fs.lstatSync(this.dir);
253
+ if (!st.isDirectory()) throw new Error('not a directory');
254
+ if (!IS_WINDOWS) {
255
+ const uid = process.getuid?.();
256
+ if (uid !== undefined && st.uid !== uid) throw new Error(`owned by uid ${st.uid}`);
257
+ if ((st.mode & 0o777) !== 0o700) fs.chmodSync(this.dir, 0o700);
258
+ }
259
+ return true;
260
+ } catch (e) {
261
+ this.log.warn(`pidfiles disabled: cannot use ${this.dir} (${/** @type {Error} */ (e).message})`);
262
+ return false;
263
+ }
264
+ }
265
+
266
+ /** @param {number} pid */
267
+ file(pid) {
268
+ return path.join(this.dir, `${process.pid}-${pid}.json`);
269
+ }
270
+
271
+ /**
272
+ * Records a freshly spawned child. Reads its command line from the OS so the reaper can later
273
+ * compare like with like; only the hash is stored.
274
+ * @param {number} pid
275
+ */
276
+ record(pid) {
277
+ if (!this.enabled) return;
278
+ const write = (cmd) => {
279
+ if (!cmd) return;
280
+ const f = this.file(pid);
281
+ try {
282
+ const start = processStartTime(pid);
283
+ fs.writeFileSync(f, JSON.stringify({ v: 2, owner: process.pid, pid, cmd: hashCommandLine(cmd), ...(start ? { start } : {}), created: new Date().toISOString() }), { mode: 0o600 });
284
+ this.mine.add(f);
285
+ } catch (e) {
286
+ this.log.warn(`cannot write pidfile: ${/** @type {Error} */ (e).message}`);
287
+ }
288
+ };
289
+ if (process.platform === 'linux') {
290
+ write(commandLineOf(pid));
291
+ } else {
292
+ // ps / PowerShell are slow; do not block the event loop for them. A child removed
293
+ // meanwhile (it exited) gets no pidfile, and only the latest lookup for a pid is written.
294
+ const n = ++this.lookups;
295
+ this.pending.set(pid, n);
296
+ commandLineOfAsync(pid).then((cmd) => {
297
+ if (this.pending.get(pid) !== n) return;
298
+ this.pending.delete(pid);
299
+ write(cmd);
300
+ });
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Records a child again once it is serving. A `#!/usr/bin/env node` script (npx and most
306
+ * Node CLIs) still shows `env`'s command line when it is spawned, which the reaper would
307
+ * later never match. Also covers a spawn-time read that found no command line (mid-exec).
308
+ * The caller passes only a child that is still running.
309
+ * @param {number} pid
310
+ */
311
+ refresh(pid) {
312
+ this.record(pid);
313
+ }
314
+
315
+ /** @param {number} pid */
316
+ remove(pid) {
317
+ this.pending.delete(pid);
318
+ const f = this.file(pid);
319
+ this.mine.delete(f);
320
+ try { fs.rmSync(f, { force: true }); } catch { /* already gone */ }
321
+ }
322
+
323
+ /**
324
+ * Kills leftovers of patchbay processes that died without cleaning up. A leftover is killed only
325
+ * if its owner is gone, it is still alive, and its command line hashes to the recorded value.
326
+ * It gets SIGTERM, then SIGKILL after REAP_GRACE_MS if it is still the same process; its
327
+ * pidfile is removed only after that, so a patchbay that dies meanwhile leaves it for the next.
328
+ * @param {number} [graceMs]
329
+ * @returns {number} how many trees were signalled
330
+ */
331
+ reap(graceMs = REAP_GRACE_MS) {
332
+ if (!this.enabled) return 0;
333
+ let killed = 0;
334
+ let files = [];
335
+ try { files = fs.readdirSync(this.dir); } catch { return 0; }
336
+ for (const f of files) {
337
+ const m = /^(\d+)-(\d+)\.json$/.exec(f);
338
+ if (!m) continue;
339
+ const full = path.join(this.dir, f);
340
+ let rec;
341
+ try {
342
+ rec = JSON.parse(fs.readFileSync(full, 'utf8'));
343
+ } catch {
344
+ continue;
345
+ }
346
+ const owner = Number(rec.owner);
347
+ const pid = Number(rec.pid);
348
+ if (owner === process.pid || pidAlive(owner)) continue;
349
+ if (isLeftover(pid, rec)) {
350
+ killTree(pid, 'SIGTERM', { bare: false });
351
+ killed++;
352
+ this.log.info(`reaped leftover child pid ${pid} of dead patchbay pid ${owner}`);
353
+ const t = setTimeout(() => {
354
+ if (isLeftover(pid, rec)) {
355
+ killTree(pid, 'SIGKILL', { bare: false });
356
+ this.log.info(`leftover child pid ${pid} ignored SIGTERM; sent SIGKILL`);
357
+ }
358
+ try { fs.rmSync(full, { force: true }); } catch { /* ignore */ }
359
+ }, graceMs);
360
+ t.unref?.();
361
+ continue;
362
+ }
363
+ try { fs.rmSync(full, { force: true }); } catch { /* ignore */ }
364
+ }
365
+ return killed;
366
+ }
367
+ }
package/src/redact.js ADDED
@@ -0,0 +1,132 @@
1
+ // Redaction of secrets in text that the patchbay itself emits: logs, errors, `servers`/`info`
2
+ // output, doctor output. Pass-through content (tool results, tool lists, child instructions) is
3
+ // not touched. See SPEC.md §6.
4
+
5
+ const R = '[redacted]';
6
+
7
+ /** Minimum length for an exact-match secret (entry env values, args, header values). */
8
+ export const MIN_SECRET_LENGTH = 6;
9
+
10
+ const SECRET_KEY = '(?:access[_-]?token|refresh[_-]?token|id[_-]?token|token|secret|client[_-]?secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session(?:[_-]?id)?)';
11
+
12
+ /** @type {Array<[RegExp, string | ((...m: string[]) => string)]>} */
13
+ const RULES = [
14
+ // URL userinfo: scheme://user:pass@host. The scheme is bounded: unbounded, it rescanned the
15
+ // rest of a long run such as `a.a.a.` from every word boundary (quadratic).
16
+ [/\b([a-z][a-z0-9+.-]{0,31}:\/\/)[^\s/@'"<>]+@/gi, `$1${R}@`],
17
+ // URL query strings: keep the path, drop everything from ? to whitespace, quote or #. The
18
+ // query is optional so a url without one is consumed whole, not rescanned from each scheme.
19
+ [/\b((?:https?|wss?|ftp|file):\/\/[^\s?#'"<>]*)(\?[^\s#'"<>]*)?/gi, (m, url, query) => (query ? `${url}?${R}` : m)],
20
+ // Authorization schemes
21
+ [/\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=-]+/g, `$1 ${R}`],
22
+ // "key": "value" in JSON-ish text
23
+ [new RegExp(`("${SECRET_KEY}"\\s*:\\s*")[^"]*(")`, 'gi'), `$1${R}$2`],
24
+ // key=value / key: value
25
+ [new RegExp(`\\b(${SECRET_KEY})(\\s*[=:]\\s*)(?!\\[redacted\\])(?!Bearer\\b|Basic\\b)[^\\s,;&'"]+`, 'gi'), `$1$2${R}`],
26
+ // Well-known token prefixes
27
+ [/\b(?:sk|pk|rk)-(?:[A-Za-z0-9]+-)*[A-Za-z0-9_-]{16,}/g, R],
28
+ [/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g, R],
29
+ [/\bgh[pousr]_[A-Za-z0-9]{20,}/g, R],
30
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, R],
31
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, R],
32
+ [/\bglpat-[A-Za-z0-9_-]{16,}/g, R],
33
+ [/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g, R],
34
+ // JWT-shaped
35
+ [/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g, R],
36
+ // long hex runs
37
+ [/\b[0-9a-fA-F]{32,}\b/g, R],
38
+ ];
39
+
40
+ // Long base64 / base64url runs with mixed character classes. Runs that start with "/" are left
41
+ // alone, which spares most absolute paths.
42
+ const B64 = /(^|[^A-Za-z0-9+/_=-])([A-Za-z0-9+_-][A-Za-z0-9+/_-]{39,}={0,2})/g;
43
+
44
+ /**
45
+ * Redacts secrets from `input`.
46
+ * @param {unknown} input
47
+ * @param {string[]} [secrets] exact strings to scrub (already filtered by length)
48
+ * @returns {string}
49
+ */
50
+ export function redact(input, secrets = []) {
51
+ let s;
52
+ if (input === undefined || input === null) return '';
53
+ if (input instanceof Error) s = `${input.name}: ${input.message}`;
54
+ else s = typeof input === 'string' ? input : String(input);
55
+ if (secrets.length) {
56
+ const sorted = [...new Set(secrets)].sort((a, b) => b.length - a.length);
57
+ for (const secret of sorted) {
58
+ if (secret.length >= MIN_SECRET_LENGTH) s = s.split(secret).join(R);
59
+ }
60
+ }
61
+ for (const [re, rep] of RULES) s = s.replace(re, /** @type {any} */ (rep));
62
+ s = s.replace(B64, (m, pre, run) => {
63
+ if (/[A-Z]/.test(run) && /[a-z]/.test(run) && /[0-9]/.test(run)) return `${pre}${R}`;
64
+ return m;
65
+ });
66
+ return s;
67
+ }
68
+
69
+ /**
70
+ * The parts of a remote url that may carry a credential: the whole url, each path segment, each
71
+ * query value and the userinfo, raw and decoded. Hosted endpoints often put the key in the path
72
+ * (https://host/s/<token>/mcp).
73
+ * @param {string} url
74
+ * @returns {string[]}
75
+ */
76
+ function urlSecrets(url) {
77
+ const out = [url];
78
+ let u;
79
+ try { u = new URL(url); } catch { return out; }
80
+ const dec = (s) => { try { return decodeURIComponent(s); } catch { return s; } };
81
+ for (const seg of u.pathname.split('/')) out.push(seg, dec(seg));
82
+ for (const pair of u.search.slice(1).split('&')) {
83
+ const v = pair.slice(pair.indexOf('=') + 1);
84
+ out.push(v, dec(v.replace(/\+/g, ' ')));
85
+ }
86
+ out.push(u.username, dec(u.username), u.password, dec(u.password));
87
+ return out;
88
+ }
89
+
90
+ /**
91
+ * The exact strings to scrub for one server entry: its env values, args, header values and url.
92
+ * @param {{args?: string[], env?: Record<string,string>, headers?: Record<string,string>, url?: string}} entry
93
+ * @returns {string[]}
94
+ */
95
+ export function secretsFor(entry) {
96
+ const out = [];
97
+ if (typeof entry.url === 'string') out.push(...urlSecrets(entry.url));
98
+ for (const v of entry.args ?? []) out.push(v);
99
+ for (const v of Object.values(entry.env ?? {})) out.push(v);
100
+ for (const v of Object.values(entry.headers ?? {})) {
101
+ out.push(v);
102
+ // "Bearer xyz": also the bare credential
103
+ const parts = v.split(/\s+/);
104
+ if (parts.length > 1) out.push(parts.slice(1).join(' '));
105
+ }
106
+ return out.filter((v) => typeof v === 'string' && v.length >= MIN_SECRET_LENGTH);
107
+ }
108
+
109
+ /** A fixed-size buffer of the most recent lines. */
110
+ export class RingBuffer {
111
+ /** @param {number} size */
112
+ constructor(size) {
113
+ this.size = size;
114
+ /** @type {string[]} */
115
+ this.buf = [];
116
+ }
117
+
118
+ /** @param {string} line */
119
+ push(line) {
120
+ this.buf.push(line);
121
+ if (this.buf.length > this.size) this.buf.splice(0, this.buf.length - this.size);
122
+ }
123
+
124
+ /** @param {number} [n] */
125
+ lines(n) {
126
+ return n === undefined ? [...this.buf] : this.buf.slice(-n);
127
+ }
128
+
129
+ last() {
130
+ return this.buf[this.buf.length - 1];
131
+ }
132
+ }
@@ -0,0 +1,158 @@
1
+ // `mcp-patchbay rename-permissions`: add mcp__patchbay__ twins of existing MCP permission rules.
2
+ // Never removes or reorders a rule. See SPEC.md §10.
3
+ import fs from 'node:fs';
4
+ import { ConfigError, EX_CONFIG, jsonSyntaxMessage, loadConfig, resolveConfigPath } from './config.js';
5
+ import { backup, writeAtomic } from './fsutil.js';
6
+ import { CLIENT_PREFIX, MAX_CLIENT_NAME, isValidSegment } from './naming.js';
7
+ import { ruleMatchesEnableConfirm } from './permissions.js';
8
+
9
+ const LISTS = ['allow', 'ask', 'deny'];
10
+
11
+ /** @param {string} rule @returns {string | null} reason to skip, or null */
12
+ function unproxyable(rule) {
13
+ if (rule.includes('(')) return 'has a parenthesised specifier';
14
+ if (rule.startsWith('mcp__claude-in-chrome__') || rule === 'mcp__claude-in-chrome') return 'claude-in-chrome is built into Claude Code';
15
+ if (rule.startsWith('mcp__plugin_')) return 'plugin servers are managed by Claude Code';
16
+ if (rule.startsWith('mcp__claude_ai_')) return 'claude.ai connectors are hosted by Claude Code';
17
+ if (rule === 'mcp__patchbay' || rule.startsWith(CLIENT_PREFIX)) return 'already a patchbay rule';
18
+ return null;
19
+ }
20
+
21
+ /**
22
+ * @param {any} settings parsed settings.json
23
+ * @param {{segmentFor?: (server: string) => string}} [o]
24
+ * @returns {{additions: Record<string, string[]>, skipped: Array<{list: string, rule: string, reason: string}>}}
25
+ */
26
+ export function computeAdditions(settings, o = {}) {
27
+ const segmentFor = o.segmentFor ?? ((s) => s);
28
+ /** @type {Record<string, string[]>} */
29
+ const additions = { allow: [], ask: [], deny: [] };
30
+ const skipped = [];
31
+ const perms = settings?.permissions ?? {};
32
+ for (const list of LISTS) {
33
+ const rules = Array.isArray(perms[list]) ? perms[list] : [];
34
+ const have = new Set(rules);
35
+ for (const rule of rules) {
36
+ if (typeof rule !== 'string' || !rule.startsWith('mcp__')) continue;
37
+ const why = unproxyable(rule);
38
+ if (why) {
39
+ skipped.push({ list, rule, reason: why });
40
+ continue;
41
+ }
42
+ const rest = rule.slice('mcp__'.length);
43
+ const i = rest.indexOf('__');
44
+ const server = i === -1 ? rest : rest.slice(0, i);
45
+ const tool = i === -1 ? '*' : rest.slice(i + 2);
46
+ if (!isValidSegment(server) || !tool) {
47
+ skipped.push({ list, rule, reason: 'server name cannot be hosted by the patchbay' });
48
+ continue;
49
+ }
50
+ const twin = `${CLIENT_PREFIX}${segmentFor(server)}__${tool}`;
51
+ if (twin.length > MAX_CLIENT_NAME) {
52
+ skipped.push({ list, rule, reason: `the patchbay name would exceed ${MAX_CLIENT_NAME} characters` });
53
+ continue;
54
+ }
55
+ // A server segment never contains "__" or "*", so no twin can match enable_confirm today;
56
+ // this keeps it that way. Such a rule would let the host approve it without asking.
57
+ if (ruleMatchesEnableConfirm(twin)) {
58
+ skipped.push({ list, rule, reason: 'its patchbay twin would match enable_confirm' });
59
+ continue;
60
+ }
61
+ if (have.has(twin)) continue;
62
+ have.add(twin);
63
+ additions[list].push(twin);
64
+ }
65
+ }
66
+ return { additions, skipped };
67
+ }
68
+
69
+ /**
70
+ * @param {string[]} argv
71
+ * @returns {Promise<number>}
72
+ */
73
+ export async function runRenamePermissions(argv) {
74
+ let file;
75
+ let write = false;
76
+ let configPath;
77
+ for (let i = 0; i < argv.length; i++) {
78
+ const a = argv[i];
79
+ if (a === '--write') write = true;
80
+ else if (a === '--config') configPath = argv[++i];
81
+ else if (!a.startsWith('--') && !file) file = a;
82
+ else {
83
+ process.stderr.write(`rename-permissions: unknown argument ${a}\n`);
84
+ return 64;
85
+ }
86
+ }
87
+ if (!file) {
88
+ process.stderr.write('Usage: mcp-patchbay rename-permissions <settings.json> [--write] [--config <servers.json>]\n');
89
+ return 64;
90
+ }
91
+ /** @type {(s: string) => string} */
92
+ let segmentFor = (s) => s;
93
+ // Without --config, use the config the patchbay itself would load: its prefixes decide the
94
+ // real tool names, and a deny rule with the wrong segment would silently stop matching.
95
+ const explicit = Boolean(configPath);
96
+ const cfgPath = configPath ?? resolveConfigPath({});
97
+ if (!explicit && !fs.existsSync(cfgPath)) {
98
+ process.stderr.write(
99
+ `rename-permissions: warning: no patchbay config at ${cfgPath}, so server prefixes are unknown. ` +
100
+ 'Names were mapped as-is (mcp__<server>__… → mcp__patchbay__<server>__…). If any server has a ' +
101
+ '"prefix", these rules will not match its tools; pass --config <servers.json>.\n',
102
+ );
103
+ } else {
104
+ try {
105
+ const cfg = loadConfig(cfgPath);
106
+ segmentFor = (s) => (Object.hasOwn(cfg.servers, s) ? cfg.servers[s].segment : s);
107
+ } catch (e) {
108
+ if (e instanceof ConfigError) {
109
+ process.stderr.write(`rename-permissions: ${e.message}${explicit ? '' : ' (pass --config <servers.json> to use another file)'}\n`);
110
+ return EX_CONFIG;
111
+ }
112
+ throw e;
113
+ }
114
+ }
115
+ let text;
116
+ let settings;
117
+ try {
118
+ text = fs.readFileSync(file, 'utf8');
119
+ } catch (e) {
120
+ process.stderr.write(`rename-permissions: cannot read ${file}: ${/** @type {any} */ (e).code ?? /** @type {Error} */ (e).message}\n`);
121
+ return 1;
122
+ }
123
+ try {
124
+ settings = JSON.parse(text);
125
+ } catch {
126
+ // Never the parser's message: it quotes the text around the error (settings can hold env).
127
+ process.stderr.write(`rename-permissions: ${jsonSyntaxMessage(file, text)}\n`);
128
+ return 1;
129
+ }
130
+ const { additions, skipped } = computeAdditions(settings, { segmentFor });
131
+ const total = LISTS.reduce((n, l) => n + additions[l].length, 0);
132
+ const lines = [];
133
+ for (const list of LISTS) for (const r of additions[list]) lines.push(`+ permissions.${list}: ${r}`);
134
+ for (const s of skipped) lines.push(` skipped permissions.${s.list}: ${s.rule} (${s.reason})`);
135
+ if (!total) {
136
+ lines.push('Nothing to add: every proxyable MCP rule already has its patchbay twin.');
137
+ process.stdout.write(lines.join('\n') + '\n');
138
+ return 0;
139
+ }
140
+ if (!write) {
141
+ lines.push(`Dry run: ${total} rule(s) would be added. Run again with --write to apply (a backup is made first).`);
142
+ process.stdout.write(lines.join('\n') + '\n');
143
+ return 0;
144
+ }
145
+ settings.permissions ??= {};
146
+ for (const list of LISTS) {
147
+ if (!additions[list].length) continue;
148
+ if (!Array.isArray(settings.permissions[list])) settings.permissions[list] = [];
149
+ settings.permissions[list].push(...additions[list]);
150
+ }
151
+ const mode = fs.statSync(file).mode & 0o777;
152
+ const bak = backup(file);
153
+ const indent = /^\{\n(\s+)/.exec(text)?.[1] ?? ' ';
154
+ writeAtomic(file, JSON.stringify(settings, null, indent) + (text.endsWith('\n') ? '\n' : ''), mode);
155
+ lines.push(`Added ${total} rule(s) to ${file}. Backup: ${bak}`);
156
+ process.stdout.write(lines.join('\n') + '\n');
157
+ return 0;
158
+ }