@ecubelabs/mysql-mcp 1.0.0-next.6 → 1.0.0-next.7

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.
@@ -0,0 +1,169 @@
1
+ import * as fs from 'node:fs';
2
+ import * as os from 'node:os';
3
+ import * as path from 'node:path';
4
+ import { expandHome } from '../ssh/config.js';
5
+ import { ConfigValidationError, WRITE_KINDS, validateConfig, } from './schema.js';
6
+ export const DEFAULT_STATE_DIR = path.join(os.homedir(), '.mysql-mcp');
7
+ export const DEFAULT_CONFIG_PATH = path.join(DEFAULT_STATE_DIR, 'config.json');
8
+ const WRITE_FORBIDDEN_ENVS = new Set(['prod', 'production']);
9
+ export function isWriteForbiddenEnv(name) {
10
+ return WRITE_FORBIDDEN_ENVS.has(name.trim().toLowerCase());
11
+ }
12
+ export class ConfigLoadError extends Error {
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = 'ConfigLoadError';
16
+ }
17
+ }
18
+ export function permissionProblems(configPath, options = {}) {
19
+ const platform = options.platform ?? process.platform;
20
+ if (platform === 'win32') {
21
+ return [];
22
+ }
23
+ const uid = options.uid ?? process.getuid?.();
24
+ const stat = options.stat ?? ((target) => fs.statSync(target));
25
+ const problems = [];
26
+ const checks = [
27
+ { target: path.dirname(configPath), wanted: 0o700 },
28
+ { target: configPath, wanted: 0o600 },
29
+ ];
30
+ for (const { target, wanted } of checks) {
31
+ const info = stat(target);
32
+ if (uid !== undefined && info.uid !== uid) {
33
+ problems.push(`${target} is owned by uid ${info.uid}, not the current user (uid ${uid})`);
34
+ }
35
+ if ((info.mode & 0o077) !== 0) {
36
+ const mode = (info.mode & 0o777).toString(8).padStart(3, '0');
37
+ problems.push(`${target} has mode ${mode}; group and other must have no access. Run: chmod ${wanted.toString(8)} ${target}`);
38
+ }
39
+ }
40
+ return problems;
41
+ }
42
+ function emptyPermissions() {
43
+ return {
44
+ insert: Object.create(null),
45
+ update: Object.create(null),
46
+ delete: Object.create(null),
47
+ ddl: Object.create(null),
48
+ };
49
+ }
50
+ function mergeWritePolicy(env, account) {
51
+ const allow = {};
52
+ const schemas = emptyPermissions();
53
+ for (const kind of WRITE_KINDS) {
54
+ allow[kind] = account?.[kind] ?? env?.[kind] ?? false;
55
+ for (const layer of [env, account]) {
56
+ for (const [schema, flags] of Object.entries(layer?.schemas ?? {})) {
57
+ const flag = flags[kind];
58
+ if (flag !== undefined) {
59
+ schemas[kind][schema] = flag;
60
+ }
61
+ }
62
+ }
63
+ }
64
+ return { allow, schemas };
65
+ }
66
+ function hasWriteSettings(policy) {
67
+ return policy !== undefined && Object.keys(policy).length > 0;
68
+ }
69
+ const READ_ONLY_POLICY = () => ({
70
+ allow: { insert: false, update: false, delete: false, ddl: false },
71
+ schemas: emptyPermissions(),
72
+ });
73
+ function resolveDefaults(config, stateDir) {
74
+ const d = config.defaults;
75
+ const maxTimeoutSeconds = d.maxTimeoutSeconds ?? 30;
76
+ return {
77
+ maxResponseRows: d.maxResponseRows ?? 5000,
78
+ maxTimeoutSeconds,
79
+ defaultTimeoutSeconds: Math.min(10, maxTimeoutSeconds),
80
+ catalogTimeoutSeconds: d.catalogTimeoutSeconds ?? 60,
81
+ poolSize: d.poolSize ?? 10,
82
+ queueLimit: d.queueLimit ?? 100,
83
+ connectTimeoutMs: d.connectTimeoutMs ?? 10_000,
84
+ logging: d.logging ?? false,
85
+ catalog: {
86
+ enabled: d.catalog?.enabled ?? true,
87
+ ttlHours: d.catalog?.ttlHours ?? 24,
88
+ dir: d.catalog?.path
89
+ ? path.resolve(stateDir, expandHome(d.catalog.path))
90
+ : path.join(stateDir, 'cache', 'catalog'),
91
+ },
92
+ };
93
+ }
94
+ export function resolveEnvironment(config, envName, paths = { configPath: DEFAULT_CONFIG_PATH }) {
95
+ if (!Object.hasOwn(config.environments, envName)) {
96
+ const known = Object.keys(config.environments);
97
+ throw new ConfigLoadError(`environment "${envName}" is not defined in ${paths.configPath}. ` +
98
+ `Defined: ${known.length > 0 ? known.join(', ') : '(none)'}.`);
99
+ }
100
+ const env = config.environments[envName];
101
+ const writeForbidden = isWriteForbiddenEnv(envName);
102
+ const warnings = [];
103
+ if (writeForbidden) {
104
+ const requested = [
105
+ ...(hasWriteSettings(env.write) ? [`environments.${envName}.write`] : []),
106
+ ...Object.entries(env.accounts)
107
+ .filter(([, account]) => hasWriteSettings(account.write))
108
+ .map(([name]) => `environments.${envName}.accounts.${name}.write`),
109
+ ];
110
+ if (requested.length > 0) {
111
+ warnings.push(`environment "${envName}" is read-only by policy; ignoring ${requested.join(', ')}.`);
112
+ }
113
+ }
114
+ const bastion = env.bastion ? { name: env.bastion, ...config.bastions[env.bastion] } : null;
115
+ const connections = Object.entries(env.accounts).map(([name, account]) => ({
116
+ name,
117
+ env: envName,
118
+ instance: {
119
+ ...env.instances[account.instance],
120
+ name: account.instance,
121
+ port: env.instances[account.instance].port ?? 3306,
122
+ },
123
+ bastion,
124
+ user: account.user,
125
+ password: account.password,
126
+ ...(account.database ? { database: account.database } : {}),
127
+ write: writeForbidden ? READ_ONLY_POLICY() : mergeWritePolicy(env.write, account.write),
128
+ }));
129
+ const stateDir = paths.stateDir ?? path.dirname(paths.configPath);
130
+ return {
131
+ name: envName,
132
+ label: envName.toUpperCase(),
133
+ writeForbidden,
134
+ connections,
135
+ defaults: resolveDefaults(config, stateDir),
136
+ configPath: paths.configPath,
137
+ stateDir,
138
+ warnings,
139
+ };
140
+ }
141
+ export function loadEnvironment(options) {
142
+ const configPath = path.resolve(expandHome(options.configPath ?? DEFAULT_CONFIG_PATH));
143
+ if (!fs.existsSync(configPath)) {
144
+ throw new ConfigLoadError(`config not found at ${configPath}. Run \`npx @ecubelabs/mysql-mcp init\` to create it.`);
145
+ }
146
+ return resolveEnvironment(readConfigFile(configPath, options), options.envName, { configPath });
147
+ }
148
+ export function readConfigFile(configPath, options = {}) {
149
+ const problems = permissionProblems(configPath, options);
150
+ if (problems.length > 0) {
151
+ throw new ConfigLoadError(`refusing to read ${configPath}:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
152
+ }
153
+ let raw;
154
+ try {
155
+ raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
156
+ }
157
+ catch (error) {
158
+ throw new ConfigLoadError(`could not parse ${configPath}: ${error.message}`);
159
+ }
160
+ try {
161
+ return validateConfig(raw);
162
+ }
163
+ catch (error) {
164
+ if (error instanceof ConfigValidationError) {
165
+ throw new ConfigLoadError(`${configPath} is ${error.message}`);
166
+ }
167
+ throw error;
168
+ }
169
+ }
@@ -0,0 +1,351 @@
1
+ export const CONFIG_VERSION = 1;
2
+ export const WRITE_KINDS = ['insert', 'update', 'delete', 'ddl'];
3
+ export class ConfigValidationError extends Error {
4
+ problems;
5
+ constructor(problems) {
6
+ super(`invalid config:\n${problems.map((problem) => ` - ${problem}`).join('\n')}`);
7
+ this.problems = problems;
8
+ this.name = 'ConfigValidationError';
9
+ }
10
+ }
11
+ export const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
12
+ const ENV_VAR_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
13
+ class Checker {
14
+ problems = [];
15
+ fail(path, message) {
16
+ this.problems.push(`${path}: ${message}`);
17
+ }
18
+ object(path, value) {
19
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
20
+ this.fail(path, 'expected an object');
21
+ return null;
22
+ }
23
+ return value;
24
+ }
25
+ keys(path, value, allowed) {
26
+ for (const key of Object.keys(value)) {
27
+ if (!allowed.includes(key)) {
28
+ this.fail(join(path, key), `unknown key (allowed: ${allowed.join(', ')})`);
29
+ }
30
+ }
31
+ }
32
+ string(path, value) {
33
+ if (typeof value !== 'string' || value.trim() === '') {
34
+ this.fail(path, 'expected a non-empty string');
35
+ return undefined;
36
+ }
37
+ return value;
38
+ }
39
+ boolean(path, value) {
40
+ if (typeof value !== 'boolean') {
41
+ this.fail(path, 'expected true or false');
42
+ return undefined;
43
+ }
44
+ return value;
45
+ }
46
+ positiveInt(path, value) {
47
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {
48
+ this.fail(path, 'expected a positive integer');
49
+ return undefined;
50
+ }
51
+ return value;
52
+ }
53
+ positiveNumber(path, value) {
54
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
55
+ this.fail(path, 'expected a positive number');
56
+ return undefined;
57
+ }
58
+ return value;
59
+ }
60
+ port(path, value) {
61
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 65535) {
62
+ this.fail(path, 'expected an integer between 1 and 65535');
63
+ return undefined;
64
+ }
65
+ return value;
66
+ }
67
+ named(path, value) {
68
+ const map = this.object(path, value);
69
+ if (!map) {
70
+ return [];
71
+ }
72
+ const entries = [];
73
+ for (const [name, entry] of Object.entries(map)) {
74
+ if (!NAME_PATTERN.test(name)) {
75
+ this.fail(join(path, name), 'name must match [A-Za-z0-9][A-Za-z0-9_.-]*');
76
+ continue;
77
+ }
78
+ entries.push([name, entry]);
79
+ }
80
+ return entries;
81
+ }
82
+ }
83
+ function join(path, key) {
84
+ return path ? `${path}.${key}` : key;
85
+ }
86
+ function optional(target, key, source, path, check) {
87
+ if (!Object.hasOwn(source, key) || source[key] === undefined) {
88
+ return;
89
+ }
90
+ const value = check(join(path, key), source[key]);
91
+ if (value !== undefined) {
92
+ target[key] = value;
93
+ }
94
+ }
95
+ function checkSecretRef(c, path, value) {
96
+ const ref = c.object(path, value);
97
+ if (!ref) {
98
+ return undefined;
99
+ }
100
+ const kinds = Object.keys(ref);
101
+ if (kinds.length !== 1 || !['keychain', 'env', 'command'].includes(kinds[0])) {
102
+ c.fail(path, 'expected exactly one of { "keychain": { "service", "account" } }, { "env": "VAR" }, { "command": [...] }' +
103
+ ' (plain-text secrets are not accepted)');
104
+ return undefined;
105
+ }
106
+ const kind = kinds[0];
107
+ if (kind === 'keychain') {
108
+ const item = c.object(join(path, 'keychain'), ref.keychain);
109
+ if (!item) {
110
+ return undefined;
111
+ }
112
+ c.keys(join(path, 'keychain'), item, ['service', 'account']);
113
+ const service = c.string(join(path, 'keychain.service'), item.service);
114
+ const account = c.string(join(path, 'keychain.account'), item.account);
115
+ return service && account ? { keychain: { service, account } } : undefined;
116
+ }
117
+ if (kind === 'env') {
118
+ const name = c.string(join(path, 'env'), ref.env);
119
+ if (name && !ENV_VAR_PATTERN.test(name)) {
120
+ c.fail(join(path, 'env'), 'expected an environment variable name');
121
+ return undefined;
122
+ }
123
+ return name ? { env: name } : undefined;
124
+ }
125
+ const argv = ref.command;
126
+ if (!Array.isArray(argv) || argv.length === 0) {
127
+ c.fail(join(path, 'command'), 'expected a non-empty array of strings (argv; no shell is used)');
128
+ return undefined;
129
+ }
130
+ const checked = argv.map((arg, index) => c.string(join(path, `command.${index}`), arg));
131
+ return checked.every((arg) => arg !== undefined) ? { command: checked } : undefined;
132
+ }
133
+ function checkWriteFlags(c, path, source, target) {
134
+ for (const kind of WRITE_KINDS) {
135
+ optional(target, kind, source, path, (p, v) => c.boolean(p, v));
136
+ }
137
+ }
138
+ function checkWritePolicy(c, path, value) {
139
+ const source = c.object(path, value);
140
+ if (!source) {
141
+ return undefined;
142
+ }
143
+ c.keys(path, source, [...WRITE_KINDS, 'schemas']);
144
+ const policy = {};
145
+ checkWriteFlags(c, path, source, policy);
146
+ if (Object.hasOwn(source, 'schemas')) {
147
+ const schemasPath = join(path, 'schemas');
148
+ const schemas = c.object(schemasPath, source.schemas);
149
+ if (schemas) {
150
+ policy.schemas = Object.create(null);
151
+ for (const [schema, flags] of Object.entries(schemas)) {
152
+ const flagsPath = join(schemasPath, schema);
153
+ const flagSource = c.object(flagsPath, flags);
154
+ if (!flagSource) {
155
+ continue;
156
+ }
157
+ c.keys(flagsPath, flagSource, WRITE_KINDS);
158
+ const checked = {};
159
+ checkWriteFlags(c, flagsPath, flagSource, checked);
160
+ policy.schemas[schema] = checked;
161
+ }
162
+ }
163
+ }
164
+ return policy;
165
+ }
166
+ function checkBastion(c, path, value) {
167
+ const source = c.object(path, value);
168
+ if (!source) {
169
+ return undefined;
170
+ }
171
+ c.keys(path, source, ['sshConfigHost', 'host', 'port', 'user', 'privateKeyPath', 'passphrase']);
172
+ const bastion = {};
173
+ optional(bastion, 'sshConfigHost', source, path, (p, v) => c.string(p, v));
174
+ optional(bastion, 'host', source, path, (p, v) => c.string(p, v));
175
+ optional(bastion, 'port', source, path, (p, v) => c.port(p, v));
176
+ optional(bastion, 'user', source, path, (p, v) => c.string(p, v));
177
+ optional(bastion, 'privateKeyPath', source, path, (p, v) => c.string(p, v));
178
+ optional(bastion, 'passphrase', source, path, (p, v) => checkSecretRef(c, p, v));
179
+ if (!bastion.sshConfigHost && !bastion.host) {
180
+ c.fail(path, 'set "sshConfigHost" (an alias in ~/.ssh/config) or "host"');
181
+ }
182
+ return bastion;
183
+ }
184
+ function checkInstance(c, path, value, tunneled) {
185
+ const source = c.object(path, value);
186
+ if (!source) {
187
+ return undefined;
188
+ }
189
+ c.keys(path, source, [
190
+ 'host',
191
+ 'port',
192
+ 'socketPath',
193
+ 'ssl',
194
+ 'timezone',
195
+ 'dateStrings',
196
+ 'bigNumberStrings',
197
+ 'disableReadOnlyTransactions',
198
+ ]);
199
+ const instance = {};
200
+ optional(instance, 'host', source, path, (p, v) => c.string(p, v));
201
+ optional(instance, 'port', source, path, (p, v) => c.port(p, v));
202
+ optional(instance, 'socketPath', source, path, (p, v) => c.string(p, v));
203
+ optional(instance, 'timezone', source, path, (p, v) => c.string(p, v));
204
+ optional(instance, 'dateStrings', source, path, (p, v) => c.boolean(p, v));
205
+ optional(instance, 'bigNumberStrings', source, path, (p, v) => c.boolean(p, v));
206
+ optional(instance, 'disableReadOnlyTransactions', source, path, (p, v) => c.boolean(p, v));
207
+ optional(instance, 'ssl', source, path, (p, v) => {
208
+ const ssl = c.object(p, v);
209
+ if (!ssl) {
210
+ return undefined;
211
+ }
212
+ c.keys(p, ssl, ['rejectUnauthorized', 'ca', 'cert', 'key']);
213
+ const checked = {};
214
+ optional(checked, 'rejectUnauthorized', ssl, p, (pp, vv) => c.boolean(pp, vv));
215
+ optional(checked, 'ca', ssl, p, (pp, vv) => c.string(pp, vv));
216
+ optional(checked, 'cert', ssl, p, (pp, vv) => c.string(pp, vv));
217
+ optional(checked, 'key', ssl, p, (pp, vv) => c.string(pp, vv));
218
+ return checked;
219
+ });
220
+ if (instance.socketPath && tunneled) {
221
+ c.fail(join(path, 'socketPath'), 'cannot be used in an environment that goes through a bastion');
222
+ }
223
+ if (!instance.socketPath && !instance.host) {
224
+ c.fail(path, 'set "host" (as seen from the bastion when one is used) or "socketPath"');
225
+ }
226
+ return instance;
227
+ }
228
+ function checkAccount(c, path, value, instances) {
229
+ const source = c.object(path, value);
230
+ if (!source) {
231
+ return undefined;
232
+ }
233
+ c.keys(path, source, ['instance', 'user', 'password', 'database', 'write']);
234
+ const instance = c.string(join(path, 'instance'), source.instance);
235
+ if (instance && !Object.hasOwn(instances, instance)) {
236
+ c.fail(join(path, 'instance'), `no instance named "${instance}" in this environment`);
237
+ }
238
+ const user = c.string(join(path, 'user'), source.user);
239
+ const password = Object.hasOwn(source, 'password')
240
+ ? checkSecretRef(c, join(path, 'password'), source.password)
241
+ : (c.fail(join(path, 'password'), 'required (a secret reference)'), undefined);
242
+ const account = { instance, user, password };
243
+ optional(account, 'database', source, path, (p, v) => c.string(p, v));
244
+ optional(account, 'write', source, path, (p, v) => checkWritePolicy(c, p, v));
245
+ return account;
246
+ }
247
+ function checkEnvironment(c, path, value, bastions) {
248
+ const source = c.object(path, value);
249
+ if (!source) {
250
+ return undefined;
251
+ }
252
+ c.keys(path, source, ['bastion', 'instances', 'accounts', 'write']);
253
+ const env = { instances: {}, accounts: {} };
254
+ optional(env, 'bastion', source, path, (p, v) => c.string(p, v));
255
+ if (env.bastion && !Object.hasOwn(bastions, env.bastion)) {
256
+ c.fail(join(path, 'bastion'), `no bastion named "${env.bastion}" under "bastions"`);
257
+ }
258
+ for (const [name, instance] of c.named(join(path, 'instances'), source.instances)) {
259
+ const checked = checkInstance(c, join(path, `instances.${name}`), instance, Boolean(env.bastion));
260
+ if (checked) {
261
+ env.instances[name] = checked;
262
+ }
263
+ }
264
+ const accounts = c.named(join(path, 'accounts'), source.accounts);
265
+ const rawAccounts = source.accounts;
266
+ if (rawAccounts && typeof rawAccounts === 'object' && Object.keys(rawAccounts).length === 0) {
267
+ c.fail(join(path, 'accounts'), 'define at least one account; each account is one connection');
268
+ }
269
+ for (const [name, account] of accounts) {
270
+ const checked = checkAccount(c, join(path, `accounts.${name}`), account, env.instances);
271
+ if (checked) {
272
+ env.accounts[name] = checked;
273
+ }
274
+ }
275
+ optional(env, 'write', source, path, (p, v) => checkWritePolicy(c, p, v));
276
+ return env;
277
+ }
278
+ function checkDefaults(c, path, value) {
279
+ const source = c.object(path, value);
280
+ if (!source) {
281
+ return {};
282
+ }
283
+ c.keys(path, source, [
284
+ 'maxResponseRows',
285
+ 'maxTimeoutSeconds',
286
+ 'catalogTimeoutSeconds',
287
+ 'poolSize',
288
+ 'queueLimit',
289
+ 'connectTimeoutMs',
290
+ 'logging',
291
+ 'catalog',
292
+ ]);
293
+ const defaults = {};
294
+ optional(defaults, 'maxResponseRows', source, path, (p, v) => c.positiveInt(p, v));
295
+ optional(defaults, 'maxTimeoutSeconds', source, path, (p, v) => c.positiveInt(p, v));
296
+ optional(defaults, 'catalogTimeoutSeconds', source, path, (p, v) => c.positiveInt(p, v));
297
+ optional(defaults, 'poolSize', source, path, (p, v) => c.positiveInt(p, v));
298
+ optional(defaults, 'queueLimit', source, path, (p, v) => c.positiveInt(p, v));
299
+ optional(defaults, 'connectTimeoutMs', source, path, (p, v) => c.positiveInt(p, v));
300
+ optional(defaults, 'logging', source, path, (p, v) => c.boolean(p, v));
301
+ optional(defaults, 'catalog', source, path, (p, v) => {
302
+ const catalog = c.object(p, v);
303
+ if (!catalog) {
304
+ return undefined;
305
+ }
306
+ c.keys(p, catalog, ['enabled', 'ttlHours', 'path']);
307
+ const checked = {};
308
+ optional(checked, 'enabled', catalog, p, (pp, vv) => c.boolean(pp, vv));
309
+ optional(checked, 'ttlHours', catalog, p, (pp, vv) => c.positiveNumber(pp, vv));
310
+ optional(checked, 'path', catalog, p, (pp, vv) => c.string(pp, vv));
311
+ return checked;
312
+ });
313
+ return defaults;
314
+ }
315
+ export function validateConfig(raw) {
316
+ const c = new Checker();
317
+ const root = c.object('', raw);
318
+ if (!root) {
319
+ throw new ConfigValidationError(['(root): expected a JSON object']);
320
+ }
321
+ c.keys('', root, ['version', 'bastions', 'environments', 'defaults']);
322
+ if (root.version !== CONFIG_VERSION) {
323
+ c.fail('version', `expected ${CONFIG_VERSION} (this server reads config version ${CONFIG_VERSION} only)`);
324
+ }
325
+ const bastions = {};
326
+ if (Object.hasOwn(root, 'bastions')) {
327
+ for (const [name, bastion] of c.named('bastions', root.bastions)) {
328
+ const checked = checkBastion(c, `bastions.${name}`, bastion);
329
+ if (checked) {
330
+ bastions[name] = checked;
331
+ }
332
+ }
333
+ }
334
+ const environments = {};
335
+ if (!Object.hasOwn(root, 'environments')) {
336
+ c.fail('environments', 'required');
337
+ }
338
+ else {
339
+ for (const [name, env] of c.named('environments', root.environments)) {
340
+ const checked = checkEnvironment(c, `environments.${name}`, env, bastions);
341
+ if (checked) {
342
+ environments[name] = checked;
343
+ }
344
+ }
345
+ }
346
+ const defaults = Object.hasOwn(root, 'defaults') ? checkDefaults(c, 'defaults', root.defaults) : {};
347
+ if (c.problems.length > 0) {
348
+ throw new ConfigValidationError(c.problems);
349
+ }
350
+ return { version: CONFIG_VERSION, bastions, environments, defaults };
351
+ }
@@ -0,0 +1,128 @@
1
+ import { execFile } from 'node:child_process';
2
+ export const SECRET_TIMEOUT_MS = 5_000;
3
+ function runFile(file, args, timeoutMs) {
4
+ return new Promise((resolve, reject) => {
5
+ execFile(file, args, { timeout: timeoutMs, maxBuffer: 64 * 1024, encoding: 'utf8' }, (error, stdout, stderr) => {
6
+ if (error) {
7
+ const detail = stderr.trim().split('\n')[0]?.slice(0, 200);
8
+ reject(new Error(detail ? `${error.message.split('\n')[0]} (${detail})` : error.message.split('\n')[0]));
9
+ return;
10
+ }
11
+ resolve(stdout);
12
+ });
13
+ });
14
+ }
15
+ export const defaultSecretRuntime = {
16
+ platform: process.platform,
17
+ run: runFile,
18
+ readEnv: (name) => process.env[name],
19
+ };
20
+ export function describeSecretRef(ref) {
21
+ if ('keychain' in ref) {
22
+ return `keychain item (service "${ref.keychain.service}", account "${ref.keychain.account}")`;
23
+ }
24
+ if ('env' in ref) {
25
+ return `environment variable ${ref.env}`;
26
+ }
27
+ return `command \`${ref.command.join(' ')}\``;
28
+ }
29
+ function stripTrailingNewline(output) {
30
+ return output.replace(/\r?\n$/, '');
31
+ }
32
+ function withTimeout(promise, timeoutMs, what) {
33
+ return new Promise((resolve, reject) => {
34
+ const timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs / 1000}s reading ${what}`)), timeoutMs);
35
+ promise.then((value) => {
36
+ clearTimeout(timer);
37
+ resolve(value);
38
+ }, (error) => {
39
+ clearTimeout(timer);
40
+ reject(error instanceof Error ? error : new Error(String(error)));
41
+ });
42
+ });
43
+ }
44
+ async function lookup(ref, runtime, timeoutMs) {
45
+ const what = describeSecretRef(ref);
46
+ if ('env' in ref) {
47
+ const value = runtime.readEnv(ref.env);
48
+ if (value === undefined || value === '') {
49
+ throw new Error(`${what} is not set or empty in the MCP server's environment`);
50
+ }
51
+ return value;
52
+ }
53
+ let file;
54
+ let args;
55
+ if ('keychain' in ref) {
56
+ const { service, account } = ref.keychain;
57
+ if (runtime.platform === 'darwin') {
58
+ file = 'security';
59
+ args = ['find-generic-password', '-s', service, '-a', account, '-w'];
60
+ }
61
+ else if (runtime.platform === 'linux') {
62
+ file = 'secret-tool';
63
+ args = ['lookup', 'service', service, 'account', account];
64
+ }
65
+ else {
66
+ throw new Error(`${what}: keychain references work on macOS and Linux only; use "env" or "command"`);
67
+ }
68
+ }
69
+ else {
70
+ [file, ...args] = ref.command;
71
+ }
72
+ let output;
73
+ try {
74
+ output = await withTimeout(runtime.run(file, args, timeoutMs), timeoutMs, what);
75
+ }
76
+ catch (error) {
77
+ throw new Error(`could not read ${what}: ${error.message}`);
78
+ }
79
+ const value = stripTrailingNewline(output);
80
+ if (value === '') {
81
+ throw new Error(`${what} returned an empty value`);
82
+ }
83
+ return value;
84
+ }
85
+ export class SecretResolver {
86
+ runtime;
87
+ timeoutMs;
88
+ cache = new Map();
89
+ constructor(runtime = defaultSecretRuntime, timeoutMs = SECRET_TIMEOUT_MS) {
90
+ this.runtime = runtime;
91
+ this.timeoutMs = timeoutMs;
92
+ }
93
+ resolve(ref) {
94
+ const key = JSON.stringify(ref);
95
+ let pending = this.cache.get(key);
96
+ if (!pending) {
97
+ pending = lookup(ref, this.runtime, this.timeoutMs);
98
+ this.cache.set(key, pending);
99
+ pending.catch(() => {
100
+ if (this.cache.get(key) === pending) {
101
+ this.cache.delete(key);
102
+ }
103
+ });
104
+ }
105
+ return pending;
106
+ }
107
+ invalidate(ref) {
108
+ this.cache.delete(JSON.stringify(ref));
109
+ }
110
+ }
111
+ export function isAccessDeniedError(error) {
112
+ const { errno, code } = (error ?? {});
113
+ return errno === 1045 || code === 'ER_ACCESS_DENIED_ERROR';
114
+ }
115
+ export async function withSecretRetry(resolver, ref, attempt) {
116
+ const first = await resolver.resolve(ref);
117
+ try {
118
+ return await attempt(first);
119
+ }
120
+ catch (error) {
121
+ if (!isAccessDeniedError(error)) {
122
+ throw error;
123
+ }
124
+ resolver.invalidate(ref);
125
+ const second = await resolver.resolve(ref);
126
+ return attempt(second);
127
+ }
128
+ }
@@ -0,0 +1,25 @@
1
+ import * as fs from 'fs';
2
+ export function readSSLFile(filePath, label) {
3
+ try {
4
+ if (!fs.existsSync(filePath)) {
5
+ throw new Error(`SSL ${label} file not found: ${filePath}`);
6
+ }
7
+ const data = fs.readFileSync(filePath);
8
+ if (data.length === 0) {
9
+ throw new Error(`SSL ${label} file is empty: ${filePath}`);
10
+ }
11
+ return data;
12
+ }
13
+ catch (error) {
14
+ if (error instanceof Error) {
15
+ if (error.message.startsWith('SSL ')) {
16
+ throw error;
17
+ }
18
+ throw new Error(`Failed to read SSL ${label}: ${error.message}`);
19
+ }
20
+ throw error;
21
+ }
22
+ }
23
+ export function readCACertificate(filePath) {
24
+ return readSSLFile(filePath, 'CA certificate');
25
+ }