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/CHANGELOG.md +103 -0
- package/LICENSE +201 -0
- package/NOTICE +8 -0
- package/README.md +376 -2
- package/SECURITY-MODEL.md +229 -0
- package/SECURITY.md +26 -0
- package/examples/servers.json +54 -0
- package/package.json +47 -4
- package/src/children.js +521 -0
- package/src/cli.js +155 -0
- package/src/config.js +465 -0
- package/src/doctor.js +124 -0
- package/src/fsutil.js +55 -0
- package/src/import.js +168 -0
- package/src/instructions.js +88 -0
- package/src/log.js +22 -0
- package/src/naming.js +96 -0
- package/src/permissions.js +72 -0
- package/src/process.js +367 -0
- package/src/redact.js +132 -0
- package/src/rename-permissions.js +158 -0
- package/src/server.js +864 -0
- package/src/version.js +4 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// mcp-patchbay command line. With no subcommand it serves MCP over stdio.
|
|
3
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
|
+
import { ConfigError, EX_CONFIG, loadConfig, resolveConfigPath } from './config.js';
|
|
5
|
+
import { createLogger } from './log.js';
|
|
6
|
+
import { PidFiles, pidDirFor } from './process.js';
|
|
7
|
+
import { redact } from './redact.js';
|
|
8
|
+
import { Patchbay } from './server.js';
|
|
9
|
+
import { VERSION } from './version.js';
|
|
10
|
+
|
|
11
|
+
const USAGE = `mcp-patchbay ${VERSION}: host MCP servers and switch them on and off mid-session
|
|
12
|
+
|
|
13
|
+
Usage:
|
|
14
|
+
mcp-patchbay [--config <path>]
|
|
15
|
+
Serve MCP over stdio. Config: --config, else $MCP_PATCHBAY_CONFIG,
|
|
16
|
+
else ~/.config/mcp-patchbay/servers.json
|
|
17
|
+
mcp-patchbay import --from <claude.json> [--project <dir>] [--out <servers.json>]
|
|
18
|
+
Write a patchbay config from a Claude Code config.
|
|
19
|
+
mcp-patchbay doctor [--config <path>] [--project <dir>] [--all] [--no-start]
|
|
20
|
+
Validate the config, warn about Claude Code allow rules that would approve
|
|
21
|
+
enable_confirm (user settings, plus <dir>/.claude with --project), and briefly
|
|
22
|
+
start each allow server (--all: confirm ones too; --no-start: none).
|
|
23
|
+
mcp-patchbay rename-permissions <settings.json> [--write] [--config <path>]
|
|
24
|
+
Add mcp__patchbay__... twins of mcp__... permission rules (dry run unless --write).
|
|
25
|
+
mcp-patchbay --help | --version
|
|
26
|
+
`;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Minimal argv parser: --flag value, --switch, positionals.
|
|
30
|
+
* @param {string[]} argv
|
|
31
|
+
* @param {string[]} switches flags without a value
|
|
32
|
+
*/
|
|
33
|
+
export function parseArgs(argv, switches = []) {
|
|
34
|
+
/** @type {Record<string, string | boolean>} */
|
|
35
|
+
const flags = {};
|
|
36
|
+
const positionals = [];
|
|
37
|
+
for (let i = 0; i < argv.length; i++) {
|
|
38
|
+
const a = argv[i];
|
|
39
|
+
if (a.startsWith('--')) {
|
|
40
|
+
const eq = a.indexOf('=');
|
|
41
|
+
if (eq !== -1) {
|
|
42
|
+
flags[a.slice(2, eq)] = a.slice(eq + 1);
|
|
43
|
+
} else if (switches.includes(a.slice(2))) {
|
|
44
|
+
flags[a.slice(2)] = true;
|
|
45
|
+
} else {
|
|
46
|
+
const v = argv[i + 1];
|
|
47
|
+
if (v === undefined || v.startsWith('--')) throw new Error(`${a} needs a value`);
|
|
48
|
+
flags[a.slice(2)] = v;
|
|
49
|
+
i++;
|
|
50
|
+
}
|
|
51
|
+
} else {
|
|
52
|
+
positionals.push(a);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return { flags, positionals };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @param {string[]} argv */
|
|
59
|
+
async function serve(argv) {
|
|
60
|
+
const log = createLogger();
|
|
61
|
+
let flags;
|
|
62
|
+
try {
|
|
63
|
+
({ flags } = parseArgs(argv));
|
|
64
|
+
} catch (e) {
|
|
65
|
+
process.stderr.write(`mcp-patchbay: ${/** @type {Error} */ (e).message}\n\n${USAGE}`);
|
|
66
|
+
process.exit(64);
|
|
67
|
+
}
|
|
68
|
+
const unknown = Object.keys(flags).filter((k) => k !== 'config');
|
|
69
|
+
if (unknown.length) {
|
|
70
|
+
process.stderr.write(`mcp-patchbay: unknown option --${unknown[0]}\n\n${USAGE}`);
|
|
71
|
+
process.exit(64);
|
|
72
|
+
}
|
|
73
|
+
const configPath = resolveConfigPath({ flag: /** @type {string | undefined} */ (flags.config) });
|
|
74
|
+
let config;
|
|
75
|
+
try {
|
|
76
|
+
config = loadConfig(configPath);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
if (e instanceof ConfigError) {
|
|
79
|
+
process.stderr.write(`mcp-patchbay: ${e.message}\n`);
|
|
80
|
+
process.exit(EX_CONFIG);
|
|
81
|
+
}
|
|
82
|
+
throw e;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// From here on the patchbay must never die from a child's misbehaviour.
|
|
86
|
+
process.on('uncaughtException', (err) => log.error(`uncaught exception: ${err?.stack ?? err}`));
|
|
87
|
+
process.on('unhandledRejection', (reason) => log.error(`unhandled rejection: ${/** @type {any} */ (reason)?.stack ?? reason}`));
|
|
88
|
+
|
|
89
|
+
const pidFiles = new PidFiles(pidDirFor(process.env), log);
|
|
90
|
+
try {
|
|
91
|
+
pidFiles.reap();
|
|
92
|
+
} catch (e) {
|
|
93
|
+
log.warn(`reaping leftovers failed: ${/** @type {Error} */ (e).message}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const patchbay = new Patchbay(config, { log, pidFiles });
|
|
97
|
+
let down = false;
|
|
98
|
+
const shutdown = (why) => {
|
|
99
|
+
if (down) return;
|
|
100
|
+
down = true;
|
|
101
|
+
patchbay.shutdownSync();
|
|
102
|
+
log.debug(`shut down (${why})`);
|
|
103
|
+
process.exit(0);
|
|
104
|
+
};
|
|
105
|
+
const signals = process.platform === 'win32' ? ['SIGINT', 'SIGTERM', 'SIGBREAK'] : ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
106
|
+
for (const sig of signals) process.on(sig, () => shutdown(sig));
|
|
107
|
+
process.stdin.on('end', () => shutdown('stdin end'));
|
|
108
|
+
process.stdin.on('close', () => shutdown('stdin closed'));
|
|
109
|
+
process.stdout.on('error', (e) => {
|
|
110
|
+
if (/** @type {any} */ (e).code === 'EPIPE') shutdown('stdout closed');
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
const transport = new StdioServerTransport();
|
|
114
|
+
await patchbay.connect(transport);
|
|
115
|
+
log.info(`serving ${config.order.length} server(s) from ${configPath}`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function main() {
|
|
119
|
+
const argv = process.argv.slice(2);
|
|
120
|
+
const cmd = argv[0];
|
|
121
|
+
if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
|
|
122
|
+
process.stdout.write(USAGE);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (cmd === '--version' || cmd === '-v') {
|
|
126
|
+
process.stdout.write(`${VERSION}\n`);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (cmd === 'import') {
|
|
130
|
+
const { runImport } = await import('./import.js');
|
|
131
|
+
process.exitCode = await runImport(argv.slice(1));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (cmd === 'doctor') {
|
|
135
|
+
const { runDoctor } = await import('./doctor.js');
|
|
136
|
+
process.exitCode = await runDoctor(argv.slice(1));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (cmd === 'rename-permissions') {
|
|
140
|
+
const { runRenamePermissions } = await import('./rename-permissions.js');
|
|
141
|
+
process.exitCode = await runRenamePermissions(argv.slice(1));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (cmd && !cmd.startsWith('--')) {
|
|
145
|
+
process.stderr.write(`mcp-patchbay: unknown command "${cmd}"\n\n${USAGE}`);
|
|
146
|
+
process.exitCode = 64;
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
await serve(argv);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
main().catch((e) => {
|
|
153
|
+
process.stderr.write(`mcp-patchbay: ${redact(/** @type {Error} */ (e)?.stack ?? e)}\n`);
|
|
154
|
+
process.exit(1);
|
|
155
|
+
});
|
package/src/config.js
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
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
|
+
/**
|
|
40
|
+
* @param {{flag?: string, env?: NodeJS.ProcessEnv}} o
|
|
41
|
+
*/
|
|
42
|
+
export function resolveConfigPath({ flag, env = process.env }) {
|
|
43
|
+
if (flag) return flag;
|
|
44
|
+
if (env.MCP_PATCHBAY_CONFIG) return env.MCP_PATCHBAY_CONFIG;
|
|
45
|
+
return defaultConfigPath();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** @param {string} p */
|
|
49
|
+
export function expandHome(p) {
|
|
50
|
+
if (p === '~') return os.homedir();
|
|
51
|
+
if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));
|
|
52
|
+
return p;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
56
|
+
const where = (p) => (p ? p : '(root)');
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {Record<string, unknown>} obj
|
|
60
|
+
* @param {string[]} allowed
|
|
61
|
+
* @param {string} at
|
|
62
|
+
*/
|
|
63
|
+
function onlyKeys(obj, allowed, at) {
|
|
64
|
+
for (const k of Object.keys(obj)) {
|
|
65
|
+
if (!allowed.includes(k)) {
|
|
66
|
+
throw new ConfigError(`unknown key "${k}" at ${where(at)} (allowed: ${allowed.join(', ')})`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param {unknown} v @param {string} at */
|
|
72
|
+
function stringMap(v, at, keyRe, keyWhat) {
|
|
73
|
+
if (!isObj(v)) throw new ConfigError(`${at} must be an object of strings`);
|
|
74
|
+
/** @type {Record<string,string>} */
|
|
75
|
+
const out = {};
|
|
76
|
+
for (const [k, val] of Object.entries(/** @type {object} */ (v))) {
|
|
77
|
+
if (!keyRe.test(k)) throw new ConfigError(`${keyWhat} "${k}" at ${at} is not valid`);
|
|
78
|
+
if (typeof val !== 'string') throw new ConfigError(`${at}.${k} must be a string`);
|
|
79
|
+
// defineProperty, not out[k] = …: a key "__proto__" must stay a key, not set the prototype.
|
|
80
|
+
Object.defineProperty(out, k, { value: val, enumerable: true, writable: true, configurable: true });
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
86
|
+
const HEADER_KEY = /^[A-Za-z0-9_-]+$/; // mcp-remote 0.15.2 parseHeaderLine
|
|
87
|
+
const SERVER_KEYS = ['description', 'policy', 'command', 'args', 'env', 'cwd', 'url', 'headers', 'prefix', 'timeoutMs'];
|
|
88
|
+
const POLICIES = ['allow', 'confirm', 'deny'];
|
|
89
|
+
export const CONFIRM_VIA = ['elicitation', 'host'];
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* @param {string} name
|
|
93
|
+
* @param {any} raw
|
|
94
|
+
* @returns {ServerEntry}
|
|
95
|
+
*/
|
|
96
|
+
function validateServer(name, raw) {
|
|
97
|
+
const at = `servers.${name}`;
|
|
98
|
+
if (!isValidSegment(name)) {
|
|
99
|
+
throw new ConfigError(`server name "${name}" is not valid: use 1-64 of [A-Za-z0-9_-], no "__", and no trailing "_"`);
|
|
100
|
+
}
|
|
101
|
+
if (!isObj(raw)) throw new ConfigError(`${at} must be an object`);
|
|
102
|
+
onlyKeys(raw, SERVER_KEYS, at);
|
|
103
|
+
const hasCommand = raw.command !== undefined;
|
|
104
|
+
const hasUrl = raw.url !== undefined;
|
|
105
|
+
if (hasCommand === hasUrl) throw new ConfigError(`${at} must have exactly one of command or url`);
|
|
106
|
+
|
|
107
|
+
const description = raw.description ?? '';
|
|
108
|
+
if (typeof description !== 'string') throw new ConfigError(`${at}.description must be a string`);
|
|
109
|
+
if (/[\r\n]/.test(description)) throw new ConfigError(`${at}.description must be one line`);
|
|
110
|
+
if (description.length > 300) throw new ConfigError(`${at}.description must be at most 300 characters`);
|
|
111
|
+
|
|
112
|
+
const policy = raw.policy ?? 'confirm';
|
|
113
|
+
if (!POLICIES.includes(policy)) throw new ConfigError(`${at}.policy must be one of ${POLICIES.join(', ')}`);
|
|
114
|
+
|
|
115
|
+
const timeoutMs = raw.timeoutMs ?? 0;
|
|
116
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMEOUT_MS) {
|
|
117
|
+
throw new ConfigError(`${at}.timeoutMs must be an integer from 0 (no cap) to ${MAX_TIMEOUT_MS}`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let prefix;
|
|
121
|
+
if (raw.prefix !== undefined) {
|
|
122
|
+
if (!isValidSegment(raw.prefix)) {
|
|
123
|
+
throw new ConfigError(`${at}.prefix "${raw.prefix}" is not valid: use 1-64 of [A-Za-z0-9_-], no "__", and no trailing "_"`);
|
|
124
|
+
}
|
|
125
|
+
prefix = raw.prefix;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const env = raw.env === undefined ? {} : stringMap(raw.env, `${at}.env`, ENV_KEY, 'env key');
|
|
129
|
+
|
|
130
|
+
/** @type {ServerEntry} */
|
|
131
|
+
const entry = {
|
|
132
|
+
name,
|
|
133
|
+
segment: prefix ?? name,
|
|
134
|
+
kind: hasCommand ? 'stdio' : 'url',
|
|
135
|
+
description,
|
|
136
|
+
policy,
|
|
137
|
+
args: [],
|
|
138
|
+
env,
|
|
139
|
+
headers: {},
|
|
140
|
+
timeoutMs,
|
|
141
|
+
};
|
|
142
|
+
if (prefix) entry.prefix = prefix;
|
|
143
|
+
|
|
144
|
+
if (hasCommand) {
|
|
145
|
+
if (typeof raw.command !== 'string' || !raw.command) throw new ConfigError(`${at}.command must be a non-empty string`);
|
|
146
|
+
if (raw.headers !== undefined) throw new ConfigError(`${at}.headers applies only to url servers`);
|
|
147
|
+
entry.command = raw.command;
|
|
148
|
+
if (raw.args !== undefined) {
|
|
149
|
+
if (!Array.isArray(raw.args) || !raw.args.every((a) => typeof a === 'string')) {
|
|
150
|
+
throw new ConfigError(`${at}.args must be an array of strings`);
|
|
151
|
+
}
|
|
152
|
+
entry.args = [...raw.args];
|
|
153
|
+
}
|
|
154
|
+
if (raw.cwd !== undefined) {
|
|
155
|
+
if (typeof raw.cwd !== 'string' || !(path.isAbsolute(raw.cwd) || path.win32.isAbsolute(raw.cwd))) {
|
|
156
|
+
throw new ConfigError(`${at}.cwd must be an absolute path`);
|
|
157
|
+
}
|
|
158
|
+
entry.cwd = raw.cwd;
|
|
159
|
+
}
|
|
160
|
+
} else {
|
|
161
|
+
if (raw.args !== undefined) throw new ConfigError(`${at}.args applies only to command servers`);
|
|
162
|
+
if (raw.cwd !== undefined) throw new ConfigError(`${at}.cwd applies only to command servers`);
|
|
163
|
+
if (typeof raw.url !== 'string') throw new ConfigError(`${at}.url must be a string`);
|
|
164
|
+
let u;
|
|
165
|
+
try {
|
|
166
|
+
u = new URL(raw.url);
|
|
167
|
+
} catch {
|
|
168
|
+
throw new ConfigError(`${at}.url must be an absolute http(s) URL`);
|
|
169
|
+
}
|
|
170
|
+
const loopback = u.hostname === 'localhost' || u.hostname === '127.0.0.1';
|
|
171
|
+
if (!(u.protocol === 'https:' || (u.protocol === 'http:' && loopback))) {
|
|
172
|
+
throw new ConfigError(`${at}.url must use https (plain http is only allowed for localhost and 127.0.0.1)`);
|
|
173
|
+
}
|
|
174
|
+
entry.url = raw.url;
|
|
175
|
+
if (raw.headers !== undefined) {
|
|
176
|
+
entry.headers = stringMap(raw.headers, `${at}.headers`, HEADER_KEY, 'header name');
|
|
177
|
+
for (const [k, v] of Object.entries(entry.headers)) {
|
|
178
|
+
if (/[\r\n]/.test(v)) throw new ConfigError(`${at}.headers.${k} must not contain line breaks`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return entry;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Validates a parsed config strictly and returns a normalised copy.
|
|
187
|
+
* @param {any} raw
|
|
188
|
+
* @returns {Config}
|
|
189
|
+
*/
|
|
190
|
+
export function validateConfig(raw) {
|
|
191
|
+
if (!isObj(raw)) throw new ConfigError('the config must be a JSON object');
|
|
192
|
+
onlyKeys(raw, ['version', 'confirmVia', 'servers', 'autostart', 'oauth'], '');
|
|
193
|
+
if (raw.version !== 1) throw new ConfigError('version must be 1');
|
|
194
|
+
const confirmVia = raw.confirmVia === undefined ? 'elicitation' : raw.confirmVia;
|
|
195
|
+
if (!CONFIRM_VIA.includes(confirmVia)) throw new ConfigError(`confirmVia must be one of ${CONFIRM_VIA.join(', ')}`);
|
|
196
|
+
if (raw.servers === undefined) throw new ConfigError('servers is required');
|
|
197
|
+
if (!isObj(raw.servers)) throw new ConfigError('servers must be an object');
|
|
198
|
+
|
|
199
|
+
/** @type {Record<string, ServerEntry>} */
|
|
200
|
+
const servers = {};
|
|
201
|
+
const order = [];
|
|
202
|
+
/** @type {Map<string, string>} */
|
|
203
|
+
const segments = new Map();
|
|
204
|
+
for (const [name, entry] of Object.entries(raw.servers)) {
|
|
205
|
+
const s = validateServer(name, entry);
|
|
206
|
+
const key = s.segment.toLowerCase();
|
|
207
|
+
const other = segments.get(key);
|
|
208
|
+
if (other !== undefined) {
|
|
209
|
+
throw new ConfigError(`servers.${name}: tool-name segment "${s.segment}" is already used by server "${other}" (names and prefixes must be unique, ignoring case)`);
|
|
210
|
+
}
|
|
211
|
+
segments.set(key, name);
|
|
212
|
+
servers[name] = s;
|
|
213
|
+
order.push(name);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const autostart = { default: /** @type {string[]} */ ([]), projects: /** @type {Record<string,string[]>} */ ({}) };
|
|
217
|
+
if (raw.autostart !== undefined) {
|
|
218
|
+
if (!isObj(raw.autostart)) throw new ConfigError('autostart must be an object');
|
|
219
|
+
onlyKeys(raw.autostart, ['default', 'projects'], 'autostart');
|
|
220
|
+
const names = (v, at) => {
|
|
221
|
+
if (!Array.isArray(v) || !v.every((x) => typeof x === 'string')) throw new ConfigError(`${at} must be an array of server names`);
|
|
222
|
+
for (const n of v) {
|
|
223
|
+
// hasOwn: "constructor", "toString" and "__proto__" are inherited, not configured servers.
|
|
224
|
+
if (!Object.hasOwn(servers, n)) throw new ConfigError(`${at} names unknown server "${n}"`);
|
|
225
|
+
if (servers[n].policy === 'deny') throw new ConfigError(`${at} names "${n}", whose policy is deny`);
|
|
226
|
+
}
|
|
227
|
+
return [...new Set(v)];
|
|
228
|
+
};
|
|
229
|
+
if (raw.autostart.default !== undefined) autostart.default = names(raw.autostart.default, 'autostart.default');
|
|
230
|
+
if (raw.autostart.projects !== undefined) {
|
|
231
|
+
if (!isObj(raw.autostart.projects)) throw new ConfigError('autostart.projects must be an object');
|
|
232
|
+
for (const [dir, list] of Object.entries(raw.autostart.projects)) {
|
|
233
|
+
if (!(path.isAbsolute(dir) || path.win32.isAbsolute(dir))) {
|
|
234
|
+
throw new ConfigError(`autostart.projects key "${dir}" must be an absolute path`);
|
|
235
|
+
}
|
|
236
|
+
autostart.projects[dir] = names(list, `autostart.projects["${dir}"]`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const oauth = { configDir: expandHome('~/.config/mcp-patchbay/oauth'), authTimeoutSeconds: 300 };
|
|
242
|
+
if (raw.oauth !== undefined) {
|
|
243
|
+
if (!isObj(raw.oauth)) throw new ConfigError('oauth must be an object');
|
|
244
|
+
onlyKeys(raw.oauth, ['configDir', 'authTimeoutSeconds'], 'oauth');
|
|
245
|
+
if (raw.oauth.configDir !== undefined) {
|
|
246
|
+
if (typeof raw.oauth.configDir !== 'string' || !raw.oauth.configDir) throw new ConfigError('oauth.configDir must be a path');
|
|
247
|
+
const dir = expandHome(raw.oauth.configDir);
|
|
248
|
+
if (!(path.isAbsolute(dir) || path.win32.isAbsolute(dir))) throw new ConfigError('oauth.configDir must be absolute (or start with ~)');
|
|
249
|
+
oauth.configDir = dir;
|
|
250
|
+
}
|
|
251
|
+
if (raw.oauth.authTimeoutSeconds !== undefined) {
|
|
252
|
+
const t = raw.oauth.authTimeoutSeconds;
|
|
253
|
+
if (!Number.isInteger(t) || t < 1 || t > 86400) throw new ConfigError('oauth.authTimeoutSeconds must be an integer from 1 to 86400');
|
|
254
|
+
oauth.authTimeoutSeconds = t;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
return { version: 1, confirmVia, order, servers, autostart, oauth };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Refuses a config file that someone else could have rewritten (POSIX only).
|
|
263
|
+
* @param {string} file
|
|
264
|
+
* @param {fs.Stats} st
|
|
265
|
+
*/
|
|
266
|
+
export function checkFilePermissions(file, st) {
|
|
267
|
+
if (process.platform === 'win32') return;
|
|
268
|
+
if (st.mode & 0o022) {
|
|
269
|
+
throw new ConfigError(
|
|
270
|
+
`refusing to start: ${file} is group- or world-writable (mode ${(st.mode & 0o777).toString(8)}). ` +
|
|
271
|
+
`The config decides which programs run, so only you may be able to change it. Fix it with: chmod 600 ${file}`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
const uid = process.getuid?.();
|
|
275
|
+
if (uid !== undefined && st.uid !== uid && st.uid !== 0) {
|
|
276
|
+
throw new ConfigError(`refusing to start: ${file} is owned by uid ${st.uid}, not by you (uid ${uid}) or root.`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The offset of the first JSON syntax error in `text`, or -1 if it is valid JSON. Used to report
|
|
282
|
+
* a location without quoting the text: V8's own message ("Unexpected token 'g', ..."B_TOKEN":
|
|
283
|
+
* ghp_abc"... is not valid JSON") includes a snippet of the file, which may hold a secret.
|
|
284
|
+
* @param {string} text
|
|
285
|
+
* @returns {number}
|
|
286
|
+
*/
|
|
287
|
+
export function jsonErrorPosition(text) {
|
|
288
|
+
let i = 0;
|
|
289
|
+
const n = text.length;
|
|
290
|
+
const stop = {};
|
|
291
|
+
const fail = () => { throw stop; };
|
|
292
|
+
const ws = () => { while (i < n && ' \t\n\r'.includes(text[i])) i++; };
|
|
293
|
+
const str = () => {
|
|
294
|
+
i++;
|
|
295
|
+
while (i < n) {
|
|
296
|
+
const c = text[i];
|
|
297
|
+
if (c === '"') { i++; return; }
|
|
298
|
+
if (c < ' ') fail();
|
|
299
|
+
if (c === '\\') {
|
|
300
|
+
const e = text[i + 1];
|
|
301
|
+
if (e !== undefined && '"\\/bfnrt'.includes(e)) i += 2;
|
|
302
|
+
else if (e === 'u' && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) i += 6;
|
|
303
|
+
else { i++; fail(); }
|
|
304
|
+
} else i++;
|
|
305
|
+
}
|
|
306
|
+
fail();
|
|
307
|
+
};
|
|
308
|
+
const NUM = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
|
|
309
|
+
const value = () => {
|
|
310
|
+
ws();
|
|
311
|
+
const c = text[i];
|
|
312
|
+
if (c === '{' || c === '[') {
|
|
313
|
+
const close = c === '{' ? '}' : ']';
|
|
314
|
+
i++;
|
|
315
|
+
ws();
|
|
316
|
+
if (text[i] === close) { i++; return; }
|
|
317
|
+
for (;;) {
|
|
318
|
+
if (c === '{') {
|
|
319
|
+
ws();
|
|
320
|
+
if (text[i] !== '"') fail();
|
|
321
|
+
str();
|
|
322
|
+
ws();
|
|
323
|
+
if (text[i] !== ':') fail();
|
|
324
|
+
i++;
|
|
325
|
+
}
|
|
326
|
+
value();
|
|
327
|
+
ws();
|
|
328
|
+
if (text[i] === ',') { i++; continue; }
|
|
329
|
+
if (text[i] === close) { i++; return; }
|
|
330
|
+
fail();
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (c === '"') return str();
|
|
334
|
+
for (const word of ['true', 'false', 'null']) {
|
|
335
|
+
if (c === word[0]) {
|
|
336
|
+
for (const ch of word) { if (text[i] !== ch) fail(); i++; }
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
NUM.lastIndex = i;
|
|
341
|
+
if (!NUM.exec(text)) fail();
|
|
342
|
+
i = NUM.lastIndex;
|
|
343
|
+
};
|
|
344
|
+
try {
|
|
345
|
+
value();
|
|
346
|
+
ws();
|
|
347
|
+
if (i < n) fail();
|
|
348
|
+
return -1;
|
|
349
|
+
} catch (e) {
|
|
350
|
+
if (e === stop) return i;
|
|
351
|
+
return -1; // too deeply nested to scan
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* "<what> is not valid JSON (line L, column C)", without quoting any of the text.
|
|
357
|
+
* @param {string} what e.g. "config /path/to/servers.json"
|
|
358
|
+
* @param {string} text
|
|
359
|
+
*/
|
|
360
|
+
export function jsonSyntaxMessage(what, text) {
|
|
361
|
+
const pos = jsonErrorPosition(text);
|
|
362
|
+
if (pos < 0) return `${what} is not valid JSON`;
|
|
363
|
+
const before = text.slice(0, pos);
|
|
364
|
+
const line = before.split('\n').length;
|
|
365
|
+
const column = pos - before.lastIndexOf('\n');
|
|
366
|
+
return `${what} is not valid JSON (line ${line}, column ${column})`;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Refuses a directory holding the config (or the file a config symlink points to) that someone
|
|
371
|
+
* else could change: group- or world-writable (sticky or not), or owned by someone other than
|
|
372
|
+
* you or root. Whoever can write the directory can replace the file (POSIX only).
|
|
373
|
+
* @param {string} file the config path, for the message
|
|
374
|
+
* @param {string} dir
|
|
375
|
+
*/
|
|
376
|
+
export function checkDirPermissions(file, dir) {
|
|
377
|
+
if (process.platform === 'win32') return;
|
|
378
|
+
let st;
|
|
379
|
+
try {
|
|
380
|
+
st = fs.statSync(dir);
|
|
381
|
+
} catch (e) {
|
|
382
|
+
throw new ConfigError(`cannot check the directory of config ${file}: ${/** @type {any} */ (e).code ?? e}`);
|
|
383
|
+
}
|
|
384
|
+
if (st.mode & 0o022) {
|
|
385
|
+
throw new ConfigError(
|
|
386
|
+
`refusing to start: the directory ${dir} holding config ${file} is group- or world-writable ` +
|
|
387
|
+
`(mode ${(st.mode & 0o7777).toString(8)}), so someone else could replace the config. ` +
|
|
388
|
+
`Fix it with: chmod go-w ${dir}, or move the config to a directory only you can write.`,
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
const uid = process.getuid?.();
|
|
392
|
+
if (uid !== undefined && st.uid !== uid && st.uid !== 0) {
|
|
393
|
+
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.`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Reads, checks and validates the config file once. The file is opened once and the checks and
|
|
399
|
+
* the read use that descriptor, so it cannot be swapped between check and read. A symlink is
|
|
400
|
+
* followed; then its target must pass the same checks, and so must the directories holding the
|
|
401
|
+
* link and the target (DECISIONS.md).
|
|
402
|
+
* @param {string} file
|
|
403
|
+
* @returns {Config}
|
|
404
|
+
*/
|
|
405
|
+
export function loadConfig(file) {
|
|
406
|
+
const posix = process.platform !== 'win32';
|
|
407
|
+
let fd;
|
|
408
|
+
try {
|
|
409
|
+
// O_NONBLOCK: opening a FIFO must not hang startup; it is refused below as not a regular file.
|
|
410
|
+
fd = fs.openSync(file, posix ? fs.constants.O_RDONLY | fs.constants.O_NONBLOCK : 'r');
|
|
411
|
+
} catch (e) {
|
|
412
|
+
throw new ConfigError(`cannot read config ${file}: ${/** @type {any} */ (e).code ?? e}. Create it (see examples/servers.json) or pass --config <path>.`);
|
|
413
|
+
}
|
|
414
|
+
let text;
|
|
415
|
+
try {
|
|
416
|
+
const st = fs.fstatSync(fd);
|
|
417
|
+
if (!st.isFile()) throw new ConfigError(`config ${file} is not a regular file`);
|
|
418
|
+
checkFilePermissions(file, st);
|
|
419
|
+
if (posix) {
|
|
420
|
+
const dirs = new Set([path.dirname(path.resolve(file))]);
|
|
421
|
+
if (fs.lstatSync(file).isSymbolicLink()) dirs.add(path.dirname(fs.realpathSync(file)));
|
|
422
|
+
for (const dir of dirs) checkDirPermissions(file, dir);
|
|
423
|
+
}
|
|
424
|
+
try {
|
|
425
|
+
text = fs.readFileSync(fd, 'utf8');
|
|
426
|
+
} catch (e) {
|
|
427
|
+
throw new ConfigError(`cannot read config ${file}: ${/** @type {any} */ (e).code ?? e}`);
|
|
428
|
+
}
|
|
429
|
+
} finally {
|
|
430
|
+
fs.closeSync(fd);
|
|
431
|
+
}
|
|
432
|
+
let raw;
|
|
433
|
+
try {
|
|
434
|
+
raw = JSON.parse(text);
|
|
435
|
+
} catch {
|
|
436
|
+
// Never e.message: V8 quotes the text around the error, which may be a secret.
|
|
437
|
+
throw new ConfigError(jsonSyntaxMessage(`config ${file}`, text));
|
|
438
|
+
}
|
|
439
|
+
try {
|
|
440
|
+
return validateConfig(raw);
|
|
441
|
+
} catch (e) {
|
|
442
|
+
if (e instanceof ConfigError) e.message = `config ${file}: ${e.message}`;
|
|
443
|
+
throw e;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** @param {string} p */
|
|
448
|
+
function normDir(p) {
|
|
449
|
+
let r = path.resolve(p);
|
|
450
|
+
if (process.platform === 'win32') r = r.toLowerCase();
|
|
451
|
+
return r;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* The servers to autostart for a project directory.
|
|
456
|
+
* @param {Config} config
|
|
457
|
+
* @param {string} projectDir
|
|
458
|
+
*/
|
|
459
|
+
export function autostartFor(config, projectDir) {
|
|
460
|
+
const want = normDir(projectDir);
|
|
461
|
+
for (const [dir, list] of Object.entries(config.autostart.projects)) {
|
|
462
|
+
if (normDir(dir) === want) return [...list];
|
|
463
|
+
}
|
|
464
|
+
return [...config.autostart.default];
|
|
465
|
+
}
|