@johnhenry/wsh 0.43.0 → 0.44.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/README.md +165 -2
- package/bin/wsh-mcp.mjs +92 -0
- package/package.json +9 -1
- package/src/host.d.ts +3 -1
- package/src/key-options.mjs +508 -0
- package/src/mcp-stdio.d.ts +54 -0
- package/src/mcp-stdio.mjs +310 -0
- package/src/memory-host.d.ts +1 -1
- package/src/memory-host.mjs +1 -1
- package/src/refusal.mjs +7 -1
- package/src/server/auth.mjs +67 -29
- package/src/server/connection.mjs +115 -6
- package/src/server/index.d.ts +51 -4
- package/src/server/index.mjs +3 -3
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `authorized_keys` options (wsh #122): what a key's leading options mean, parsed the same way by the Node host (this file) and
|
|
3
|
+
* the Rust `wsh-server` (`crates/wsh-server/src/auth/permissions.rs`). `spec/key-options.vectors.json` holds the shared test
|
|
4
|
+
* vectors both suites run, so the two cannot drift. Browser-safe (no Node imports): the in-memory host uses it too.
|
|
5
|
+
*
|
|
6
|
+
* A line is `[options] ssh-ed25519 <base64> [comment]`. `options` is one token (no whitespace outside double quotes) of
|
|
7
|
+
* comma-separated items, each `name` or `name=value`, where a value is `"..."` (a `\"` is a quote, any other backslash is
|
|
8
|
+
* literal) or a bare token. Anything this file does not understand REFUSES the key: it is not on the allowlist at all, with a
|
|
9
|
+
* reason. Nothing is ever skipped silently and then granted.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { parseSSHPublicKey, extractRawFromSSHWire } from './auth.mjs';
|
|
13
|
+
|
|
14
|
+
/** The refusal codes of a key line, stable across both hosts. */
|
|
15
|
+
export const KEY_OPTION_ERRORS = Object.freeze(['unknown-option', 'bad-syntax', 'bad-value', 'duplicate-option', 'unknown-capability', 'bad-capability']);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The refusal codes of a request a key's options do not allow, stable across both hosts. `capability-missing` (#122, step two)
|
|
19
|
+
* says which capability the request needed (`refusal.capability`); `key-expired` is a key past its `expires`.
|
|
20
|
+
*/
|
|
21
|
+
export const KEY_REQUEST_REFUSALS = Object.freeze([
|
|
22
|
+
'pty-not-permitted', 'exec-not-permitted', 'file-transfer-not-permitted', 'forced-command', 'max-sessions',
|
|
23
|
+
'mcp-not-permitted', 'relay-not-permitted', 'key-admin-not-permitted', 'capability-missing', 'key-expired',
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
/** Options that only ask for less than wsh offers anyway: accepted, no effect (wsh has no agent, X11 or user rc to forward). */
|
|
27
|
+
const NO_OP_OPTIONS = new Set(['no-agent-forwarding', 'no-X11-forwarding', 'no-user-rc', 'no-port-forwarding']);
|
|
28
|
+
const FLAG_OPTIONS = new Set(['restrict', 'no-pty', 'permit-pty', 'permit-exec', 'permit-mcp', 'permit-file-transfer', 'permit-relay', ...NO_OP_OPTIONS]);
|
|
29
|
+
const VALUE_OPTIONS = new Set(['command', 'max-sessions', 'capabilities', 'expires']);
|
|
30
|
+
const NAME_RE = /^[A-Za-z][A-Za-z0-9_-]*$/;
|
|
31
|
+
const MAX_SESSIONS_RE = /^[1-9][0-9]{0,8}$/;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* What a key may do when it has no options at all. `capabilities` is `null` (no capability list: the options above decide
|
|
35
|
+
* everything) or the list `capabilities="..."` gave (default-deny: only what it names); `expires` is `null` or the epoch second
|
|
36
|
+
* from which the key is refused.
|
|
37
|
+
*/
|
|
38
|
+
export function fullAccess() {
|
|
39
|
+
return { pty: true, exec: true, mcp: true, fileTransfer: true, relay: true, forcedCommand: null, maxSessions: null, capabilities: null, expires: null };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const fail = (code, reason) => ({ ok: false, code, reason });
|
|
43
|
+
|
|
44
|
+
// ── Capabilities (#122, step two) ────────────────────────────────────────────────────────────────────────────────────────
|
|
45
|
+
//
|
|
46
|
+
// exec pty relay fs:read fs:write
|
|
47
|
+
// gateway:tcp:<host>:<port> gateway:udp:<host>:<port> gateway:listen:tcp:<port>
|
|
48
|
+
// unix:<path> unix:listen:<path> endpoint:<name> mcp:<tool> target:<name> rpc:<protocol>
|
|
49
|
+
//
|
|
50
|
+
// `<host>` is a name, an IP literal (IPv6 in brackets), `*`, or `*.suffix` (any subdomain, not the apex); `<port>` a number or
|
|
51
|
+
// `*`; `<path>` absolute, exact or `/dir/*` (anything below `/dir`), no `.` or `..`; `<name>`, `<tool>` exact or `*`.
|
|
52
|
+
|
|
53
|
+
const NAME_CAP_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
54
|
+
const TOOL_CAP_RE = /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/;
|
|
55
|
+
const DOMAIN_RE = /^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$/;
|
|
56
|
+
const SIMPLE_CAPS = new Set(['exec', 'pty', 'relay', 'fs:read', 'fs:write']);
|
|
57
|
+
|
|
58
|
+
const capFail = (code, reason) => ({ ok: false, code, reason });
|
|
59
|
+
|
|
60
|
+
function parsePort(s) {
|
|
61
|
+
if (s === '*') return { port: '*' };
|
|
62
|
+
if (!/^[1-9][0-9]{0,4}$/.test(s) || Number(s) > 65535) return null;
|
|
63
|
+
return { port: Number(s) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function parseHostPort(s) {
|
|
67
|
+
let host; let port;
|
|
68
|
+
if (s.startsWith('[')) {
|
|
69
|
+
const close = s.indexOf(']');
|
|
70
|
+
if (close < 0 || s[close + 1] !== ':') return null;
|
|
71
|
+
host = s.slice(0, close + 1);
|
|
72
|
+
port = s.slice(close + 2);
|
|
73
|
+
if (!/^\[[0-9A-Fa-f:.]+\]$/.test(host)) return null;
|
|
74
|
+
} else {
|
|
75
|
+
const idx = s.lastIndexOf(':');
|
|
76
|
+
if (idx < 0) return null;
|
|
77
|
+
host = s.slice(0, idx);
|
|
78
|
+
port = s.slice(idx + 1);
|
|
79
|
+
const domain = host.startsWith('*.') ? host.slice(2) : host;
|
|
80
|
+
if (host !== '*' && !DOMAIN_RE.test(domain)) return null;
|
|
81
|
+
}
|
|
82
|
+
const p = parsePort(port);
|
|
83
|
+
return p ? { host: host.toLowerCase(), port: p.port } : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The segments of an absolute path with no empty, `.` or `..` segment, or null. */
|
|
87
|
+
function pathSegments(path) {
|
|
88
|
+
if (typeof path !== 'string' || !path.startsWith('/')) return null;
|
|
89
|
+
const segs = path.slice(1).split('/');
|
|
90
|
+
return segs.every((s) => s !== '' && s !== '.' && s !== '..') ? segs : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function parsePathPattern(s) {
|
|
94
|
+
// eslint-disable-next-line no-control-regex
|
|
95
|
+
if (/[\u0000-\u0020\u007f,"'\\]/.test(s)) return null;
|
|
96
|
+
if (s === '/*') return { path: '/', prefix: true };
|
|
97
|
+
if (s.endsWith('/*')) {
|
|
98
|
+
const dir = s.slice(0, -2);
|
|
99
|
+
return pathSegments(dir) && !dir.includes('*') ? { path: dir, prefix: true } : null;
|
|
100
|
+
}
|
|
101
|
+
return pathSegments(s) && !s.includes('*') ? { path: s, prefix: false } : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** One capability, or a `{ ok: false }` with the stable code. */
|
|
105
|
+
function parseCapability(raw) {
|
|
106
|
+
if (raw === '') return capFail('bad-capability', 'empty capability');
|
|
107
|
+
if (/\s/.test(raw)) return capFail('bad-capability', `capability ${JSON.stringify(raw)} contains whitespace`);
|
|
108
|
+
const bad = (why) => capFail('bad-capability', `capability ${JSON.stringify(raw)}: ${why}`);
|
|
109
|
+
if (SIMPLE_CAPS.has(raw)) return { ok: true, cap: { raw, kind: raw } };
|
|
110
|
+
if (raw.startsWith('gateway:')) {
|
|
111
|
+
const rest = raw.slice('gateway:'.length);
|
|
112
|
+
if (rest.startsWith('tcp:') || rest.startsWith('udp:')) {
|
|
113
|
+
const hp = parseHostPort(rest.slice(4));
|
|
114
|
+
return hp ? { ok: true, cap: { raw, kind: rest.slice(0, 3), host: hp.host, port: hp.port } } : bad('expected gateway:<tcp|udp>:<host>:<port>');
|
|
115
|
+
}
|
|
116
|
+
if (rest.startsWith('listen:tcp:')) {
|
|
117
|
+
const p = parsePort(rest.slice('listen:tcp:'.length));
|
|
118
|
+
return p ? { ok: true, cap: { raw, kind: 'listen-tcp', port: p.port } } : bad('expected gateway:listen:tcp:<port>');
|
|
119
|
+
}
|
|
120
|
+
return capFail('unknown-capability', `unknown capability ${JSON.stringify(raw)}`);
|
|
121
|
+
}
|
|
122
|
+
if (raw.startsWith('unix:')) {
|
|
123
|
+
const listen = raw.startsWith('unix:listen:');
|
|
124
|
+
const pat = parsePathPattern(raw.slice(listen ? 'unix:listen:'.length : 'unix:'.length));
|
|
125
|
+
return pat ? { ok: true, cap: { raw, kind: listen ? 'listen-unix' : 'unix', ...pat } } : bad('expected an absolute path, exact or ending in /*, without . or ..');
|
|
126
|
+
}
|
|
127
|
+
const named = (prefix, kind, re, allowStar) => {
|
|
128
|
+
const v = raw.slice(prefix.length);
|
|
129
|
+
return (allowStar && v === '*') || re.test(v) ? { ok: true, cap: { raw, kind, name: v } } : bad(`expected ${prefix}<name>`);
|
|
130
|
+
};
|
|
131
|
+
if (raw.startsWith('endpoint:')) return named('endpoint:', 'endpoint', NAME_CAP_RE, true);
|
|
132
|
+
if (raw.startsWith('target:')) return named('target:', 'target', NAME_CAP_RE, true);
|
|
133
|
+
if (raw.startsWith('mcp:')) return named('mcp:', 'mcp', TOOL_CAP_RE, true);
|
|
134
|
+
if (raw.startsWith('rpc:')) return named('rpc:', 'rpc', NAME_CAP_RE, false);
|
|
135
|
+
return capFail('unknown-capability', `unknown capability ${JSON.stringify(raw)}`);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Parse a capability list (`capabilities="exec,fs:read"`, or what an `authorize()` callback returns).
|
|
140
|
+
* @param {string | string[]} list
|
|
141
|
+
* @returns {{ ok: true, capabilities: string[], parsed: object[] } | { ok: false, code: string, reason: string }}
|
|
142
|
+
*/
|
|
143
|
+
export function parseCapabilityList(list) {
|
|
144
|
+
const raws = Array.isArray(list) ? list : (list === '' ? [] : String(list).split(','));
|
|
145
|
+
const parsed = [];
|
|
146
|
+
for (const raw of raws) {
|
|
147
|
+
if (typeof raw !== 'string') return capFail('bad-capability', 'capabilities must be strings');
|
|
148
|
+
const r = parseCapability(raw);
|
|
149
|
+
if (!r.ok) return r;
|
|
150
|
+
parsed.push(r.cap);
|
|
151
|
+
}
|
|
152
|
+
return { ok: true, capabilities: raws.slice(), parsed };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
156
|
+
const isLeap = (y) => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
|
|
157
|
+
/** Days since 1970-01-01 of a proleptic Gregorian date (Howard Hinnant's `days_from_civil`). */
|
|
158
|
+
function daysFromCivil(y, m, d) {
|
|
159
|
+
const yy = m <= 2 ? y - 1 : y;
|
|
160
|
+
const era = Math.floor(yy / 400);
|
|
161
|
+
const yoe = yy - era * 400;
|
|
162
|
+
const doy = Math.floor((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5) + d - 1;
|
|
163
|
+
return era * 146097 + yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy - 719468;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* An RFC 3339 timestamp (`2030-01-01T00:00:00Z`, `...+01:00`, fractional seconds allowed and dropped; `T` and `Z` upper case;
|
|
168
|
+
* no leap second) as whole epoch seconds, or `null`. The Rust server parses the same way.
|
|
169
|
+
* @param {string} s
|
|
170
|
+
* @returns {number | null}
|
|
171
|
+
*/
|
|
172
|
+
export function parseRfc3339(s) {
|
|
173
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))$/.exec(String(s));
|
|
174
|
+
if (!m) return null;
|
|
175
|
+
const [y, mo, d, h, mi, se] = [m[1], m[2], m[3], m[4], m[5], m[6]].map(Number);
|
|
176
|
+
if (y < 1970 || mo < 1 || mo > 12 || d < 1 || d > (mo === 2 && isLeap(y) ? 29 : DAYS[mo - 1])) return null;
|
|
177
|
+
if (h > 23 || mi > 59 || se > 59) return null;
|
|
178
|
+
let offset = 0;
|
|
179
|
+
if (m[7]) {
|
|
180
|
+
const oh = Number(m[8]); const om = Number(m[9]);
|
|
181
|
+
if (oh > 23 || om > 59) return null;
|
|
182
|
+
offset = (m[7] === '+' ? 1 : -1) * (oh * 3600 + om * 60);
|
|
183
|
+
}
|
|
184
|
+
return daysFromCivil(y, mo, d) * 86400 + h * 3600 + mi * 60 + se - offset;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Split the options token into `[name, value | null]` items, or fail.
|
|
189
|
+
* @returns {{ ok: true, items: Array<[string, string | null]> } | { ok: false, code: string, reason: string }}
|
|
190
|
+
*/
|
|
191
|
+
function tokenize(text) {
|
|
192
|
+
const items = [];
|
|
193
|
+
let i = 0;
|
|
194
|
+
const n = text.length;
|
|
195
|
+
for (;;) {
|
|
196
|
+
let name = '';
|
|
197
|
+
while (i < n && text[i] !== ',' && text[i] !== '=') {
|
|
198
|
+
const ch = text[i];
|
|
199
|
+
if (ch === '"' || ch === "'" || ch === ' ' || ch === '\t') return fail('bad-syntax', `unexpected ${JSON.stringify(ch)} in an option name`);
|
|
200
|
+
name += ch; i++;
|
|
201
|
+
}
|
|
202
|
+
if (!name) return fail('bad-syntax', 'empty option (a stray comma)');
|
|
203
|
+
let value = null;
|
|
204
|
+
if (text[i] === '=') {
|
|
205
|
+
i++;
|
|
206
|
+
if (text[i] === '"') {
|
|
207
|
+
i++;
|
|
208
|
+
let v = '';
|
|
209
|
+
let closed = false;
|
|
210
|
+
while (i < n) {
|
|
211
|
+
const ch = text[i];
|
|
212
|
+
if (ch === '\\' && text[i + 1] === '"') { v += '"'; i += 2; continue; }
|
|
213
|
+
if (ch === '"') { closed = true; i++; break; }
|
|
214
|
+
v += ch; i++;
|
|
215
|
+
}
|
|
216
|
+
if (!closed) return fail('bad-syntax', `unterminated quote in ${name}=`);
|
|
217
|
+
if (i < n && text[i] !== ',') return fail('bad-syntax', `text after the closing quote of ${name}=`);
|
|
218
|
+
value = v;
|
|
219
|
+
} else {
|
|
220
|
+
let v = '';
|
|
221
|
+
while (i < n && text[i] !== ',') {
|
|
222
|
+
const ch = text[i];
|
|
223
|
+
if (ch === '"' || ch === "'" || ch === '=' || ch === ' ' || ch === '\t') return fail('bad-syntax', `unexpected ${JSON.stringify(ch)} in the value of ${name}= (quote the value with double quotes)`);
|
|
224
|
+
v += ch; i++;
|
|
225
|
+
}
|
|
226
|
+
value = v;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
items.push([name, value]);
|
|
230
|
+
if (i >= n) return { ok: true, items };
|
|
231
|
+
i++; // the comma
|
|
232
|
+
if (i >= n) return fail('bad-syntax', 'empty option (a trailing comma)');
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Parse an options string into effective permissions. `null`/`undefined`/`''` mean "no options": full access.
|
|
238
|
+
* @param {string | null | undefined} text
|
|
239
|
+
* @returns {{ ok: true, permissions: ReturnType<typeof fullAccess> } | { ok: false, code: string, reason: string }}
|
|
240
|
+
*/
|
|
241
|
+
export function parseKeyOptions(text) {
|
|
242
|
+
if (text === null || text === undefined || text === '') return { ok: true, permissions: fullAccess() };
|
|
243
|
+
const tok = tokenize(String(text));
|
|
244
|
+
if (!tok.ok) return tok;
|
|
245
|
+
const seen = new Set();
|
|
246
|
+
const flags = new Set();
|
|
247
|
+
let command = null;
|
|
248
|
+
let maxSessions = null;
|
|
249
|
+
let caps = null;
|
|
250
|
+
let expires = null;
|
|
251
|
+
for (const [name, value] of tok.items) {
|
|
252
|
+
if (!NAME_RE.test(name) || !(FLAG_OPTIONS.has(name) || VALUE_OPTIONS.has(name))) return fail('unknown-option', `unknown option ${JSON.stringify(name)}`);
|
|
253
|
+
if (seen.has(name)) return fail('duplicate-option', `option ${name} given twice`);
|
|
254
|
+
seen.add(name);
|
|
255
|
+
if (FLAG_OPTIONS.has(name)) {
|
|
256
|
+
if (value !== null) return fail('bad-value', `option ${name} takes no value`);
|
|
257
|
+
flags.add(name);
|
|
258
|
+
} else if (value === null) {
|
|
259
|
+
return fail('bad-value', `option ${name} needs a value`);
|
|
260
|
+
} else if (name === 'command') {
|
|
261
|
+
// eslint-disable-next-line no-control-regex
|
|
262
|
+
if (!value || /[\u0000-\u001f\u007f]/.test(value)) return fail('bad-value', 'command must be a non-empty string without control characters');
|
|
263
|
+
command = value;
|
|
264
|
+
} else if (name === 'capabilities') {
|
|
265
|
+
const r = parseCapabilityList(value);
|
|
266
|
+
if (!r.ok) return r;
|
|
267
|
+
caps = r;
|
|
268
|
+
} else if (name === 'expires') {
|
|
269
|
+
expires = parseRfc3339(value);
|
|
270
|
+
if (expires === null) return fail('bad-value', 'expires must be an RFC 3339 timestamp such as 2030-01-01T00:00:00Z');
|
|
271
|
+
} else {
|
|
272
|
+
if (!MAX_SESSIONS_RE.test(value)) return fail('bad-value', 'max-sessions must be a positive whole number');
|
|
273
|
+
maxSessions = Number(value);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const restricted = flags.has('restrict');
|
|
277
|
+
const grant = (permit) => (restricted ? flags.has(permit) : true);
|
|
278
|
+
const shell = grant('permit-pty');
|
|
279
|
+
const out = {
|
|
280
|
+
pty: shell && !flags.has('no-pty'),
|
|
281
|
+
exec: restricted ? (flags.has('permit-exec') || flags.has('permit-pty') || command !== null) : true,
|
|
282
|
+
mcp: grant('permit-mcp'),
|
|
283
|
+
fileTransfer: grant('permit-file-transfer'),
|
|
284
|
+
relay: grant('permit-relay'),
|
|
285
|
+
forcedCommand: command,
|
|
286
|
+
maxSessions,
|
|
287
|
+
capabilities: caps ? caps.capabilities : null,
|
|
288
|
+
expires,
|
|
289
|
+
};
|
|
290
|
+
// The parsed form of the list, for the checks; not part of the permissions' value.
|
|
291
|
+
Object.defineProperty(out, '_caps', { value: caps ? caps.parsed : null, enumerable: false });
|
|
292
|
+
// A key tied to one command is not a shell, a file, an MCP or a relay key, whatever else the line says.
|
|
293
|
+
if (command !== null) { out.pty = false; out.fileTransfer = false; out.mcp = false; out.relay = false; out.exec = true; }
|
|
294
|
+
return { ok: true, permissions: out };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** The parsed capability list of `p`, or null when the key has none. */
|
|
298
|
+
const capsOf = (p) => p._caps ?? (Array.isArray(p.capabilities) ? parseCapabilityList(p.capabilities).parsed : null);
|
|
299
|
+
|
|
300
|
+
const FS_READ_OPS = new Set(['stat', 'list', 'read']);
|
|
301
|
+
|
|
302
|
+
function hostMatches(patternHost, host) {
|
|
303
|
+
const h = String(host).toLowerCase();
|
|
304
|
+
const norm = h.includes(':') && !h.startsWith('[') ? `[${h}]` : h;
|
|
305
|
+
if (patternHost === '*') return true;
|
|
306
|
+
if (patternHost.startsWith('*.')) return norm.endsWith(patternHost.slice(1)) && norm.length > patternHost.length - 1;
|
|
307
|
+
return norm === patternHost;
|
|
308
|
+
}
|
|
309
|
+
const portMatches = (patternPort, port) => patternPort === '*' || patternPort === port;
|
|
310
|
+
function pathMatches(cap, path) {
|
|
311
|
+
const segs = pathSegments(path);
|
|
312
|
+
if (!segs) return false;
|
|
313
|
+
if (!cap.prefix) return path === cap.path;
|
|
314
|
+
const dir = cap.path === '/' ? '' : cap.path;
|
|
315
|
+
return path.startsWith(`${dir}/`) && path.length > dir.length + 1;
|
|
316
|
+
}
|
|
317
|
+
const nameMatches = (cap, name) => cap.name === '*' || cap.name === name;
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* The capability part of a request check (the key has a capability list): `null` when the list covers `req`, else
|
|
321
|
+
* `{ code: 'capability-missing', capability, reason }`.
|
|
322
|
+
*/
|
|
323
|
+
function capabilityRefusal(p, req) {
|
|
324
|
+
const caps = capsOf(p);
|
|
325
|
+
const has = (kind) => caps.some((c) => c.kind === kind);
|
|
326
|
+
const need = (raw, ok) => (ok ? null : { code: 'capability-missing', capability: raw, reason: `missing capability ${raw}` });
|
|
327
|
+
const target = () => (req.target === undefined || req.target === null ? null
|
|
328
|
+
: need(`target:${req.target}`, caps.some((c) => c.kind === 'target' && nameMatches(c, req.target))));
|
|
329
|
+
switch (req.kind) {
|
|
330
|
+
case 'open': {
|
|
331
|
+
let r;
|
|
332
|
+
if (req.channel === 'pty') r = need('pty', has('pty'));
|
|
333
|
+
else if (req.channel === 'exec') r = need('exec', has('exec'));
|
|
334
|
+
else if (req.channel === 'file') { const need_ = req.direction === 'download' ? 'fs:read' : 'fs:write'; r = need(need_, has(need_)); }
|
|
335
|
+
else if (req.channel === 'rpc') {
|
|
336
|
+
const proto = req.protocol;
|
|
337
|
+
// The file rpc has read and write methods on one channel: a key without both is refused it (a client falls back to
|
|
338
|
+
// FileOp and the file channels, which are checked per operation).
|
|
339
|
+
if (proto === 'wsh-fs') r = need('fs:read', has('fs:read')) ?? need('fs:write', has('fs:write'));
|
|
340
|
+
else if (proto === 'mcp') r = need('mcp:*', caps.some((c) => c.kind === 'mcp' && c.name === '*'));
|
|
341
|
+
else r = need(`rpc:${proto}`, caps.some((c) => c.kind === 'rpc' && c.name === proto));
|
|
342
|
+
} else r = need(req.channel, false);
|
|
343
|
+
return r ?? target();
|
|
344
|
+
}
|
|
345
|
+
case 'file-op': {
|
|
346
|
+
const raw = FS_READ_OPS.has(req.op) ? 'fs:read' : 'fs:write';
|
|
347
|
+
return need(raw, has(raw)) ?? target();
|
|
348
|
+
}
|
|
349
|
+
case 'mcp': return need('mcp:*', has('mcp'));
|
|
350
|
+
case 'mcp-call': case 'mcp-tool': return need(`mcp:${req.tool}`, caps.some((c) => c.kind === 'mcp' && nameMatches(c, req.tool)));
|
|
351
|
+
case 'relay': return need('relay', has('relay'));
|
|
352
|
+
// Installing a key gives a key with no capability list, so a key with one never may.
|
|
353
|
+
case 'key-admin': return { code: 'key-admin-not-permitted', reason: 'installing a key is not permitted for a restricted key' };
|
|
354
|
+
case 'tcp': case 'udp': {
|
|
355
|
+
const raw = `gateway:${req.kind}:${req.host}:${req.port}`;
|
|
356
|
+
return need(raw, caps.some((c) => c.kind === req.kind && hostMatches(c.host, req.host) && portMatches(c.port, req.port)));
|
|
357
|
+
}
|
|
358
|
+
case 'dns': return need(`gateway:tcp:${req.name}:*`, caps.some((c) => c.kind === 'tcp' && hostMatches(c.host, req.name)));
|
|
359
|
+
case 'listen-tcp': return need(`gateway:listen:tcp:${req.port}`, caps.some((c) => c.kind === 'listen-tcp' && portMatches(c.port, req.port)));
|
|
360
|
+
case 'unix': return need(`unix:${req.path}`, caps.some((c) => c.kind === 'unix' && pathMatches(c, req.path)));
|
|
361
|
+
case 'listen-unix': return need(`unix:listen:${req.path}`, caps.some((c) => c.kind === 'listen-unix' && pathMatches(c, req.path)));
|
|
362
|
+
case 'endpoint': return need(`endpoint:${req.name}`, caps.some((c) => c.kind === 'endpoint' && nameMatches(c, req.name))) ?? target();
|
|
363
|
+
case 'target': return need(`target:${req.name}`, caps.some((c) => c.kind === 'target' && nameMatches(c, req.name)));
|
|
364
|
+
default: return need(String(req.kind), false);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Whether a key with `permissions` may make this request: `null` when allowed, else `{ code, reason }` (`code` is one of
|
|
370
|
+
* `KEY_REQUEST_REFUSALS`; for `capability-missing` also `capability`, what the request needed). Checked in this order: expiry,
|
|
371
|
+
* the options (`restrict`, `permit-*`, `command=`, `max-sessions=`), then the capability list when the key has one.
|
|
372
|
+
*
|
|
373
|
+
* Requests: `{ kind: 'login' }`; `{ kind: 'open', channel: 'pty' | 'exec' }`; `{ kind: 'open', channel: 'file', direction:
|
|
374
|
+
* 'upload' | 'download' }`; `{ kind: 'open', channel: 'rpc', protocol }`; `{ kind: 'file-op', op }`; `{ kind: 'mcp' }`
|
|
375
|
+
* (discovery), `{ kind: 'mcp-call' | 'mcp-tool', tool }`; `{ kind: 'relay' }`; `{ kind: 'key-admin' }`; the gateway:
|
|
376
|
+
* `{ kind: 'tcp' | 'udp', host, port }`, `{ kind: 'dns', name }`, `{ kind: 'listen-tcp', port }`, `{ kind: 'unix' |
|
|
377
|
+
* 'listen-unix', path }`, `{ kind: 'endpoint', name, target? }`; `{ kind: 'target', name }`. A request may carry `target` (open,
|
|
378
|
+
* file-op, endpoint): the target it names. `activeSessions` is how many pty/exec sessions the key has open (for
|
|
379
|
+
* `max-sessions`); `now` is the epoch second to test `expires` against (default: now).
|
|
380
|
+
*
|
|
381
|
+
* @param {ReturnType<typeof fullAccess>} p
|
|
382
|
+
* @param {object} req
|
|
383
|
+
* @param {{ activeSessions?: number, now?: number }} [state]
|
|
384
|
+
* @returns {null | { code: string, reason: string, capability?: string }}
|
|
385
|
+
*/
|
|
386
|
+
export function checkKeyRequest(p, req, { activeSessions = 0, now } = {}) {
|
|
387
|
+
if (p.expires !== null && p.expires !== undefined && (now ?? Math.floor(Date.now() / 1000)) >= p.expires) {
|
|
388
|
+
return { code: 'key-expired', reason: 'this key has expired' };
|
|
389
|
+
}
|
|
390
|
+
if (req.kind === 'login') return null;
|
|
391
|
+
const refused = optionsRefusal(p, req, activeSessions);
|
|
392
|
+
if (refused) return refused;
|
|
393
|
+
return capsOf(p) ? capabilityRefusal(p, req) : null;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** The options part (`restrict`, `permit-*`, `command=`, `max-sessions=`) of a request check. */
|
|
397
|
+
function optionsRefusal(p, req, activeSessions) {
|
|
398
|
+
const no = (code, reason) => ({ code, reason });
|
|
399
|
+
switch (req.kind) {
|
|
400
|
+
case 'open': {
|
|
401
|
+
const ch = req.channel;
|
|
402
|
+
if (p.forcedCommand !== null && ch !== 'exec') return no('forced-command', 'key is restricted to forced exec command');
|
|
403
|
+
if (ch === 'pty' && !p.pty) return no('pty-not-permitted', 'PTY not permitted for this key');
|
|
404
|
+
if (ch === 'exec' && !p.exec) return no('exec-not-permitted', 'exec access not permitted for this key');
|
|
405
|
+
if (ch === 'file' && !p.fileTransfer) return no('file-transfer-not-permitted', 'file transfer not permitted for this key');
|
|
406
|
+
if (ch === 'rpc') {
|
|
407
|
+
// wsh-fs is the file channel, mcp is the MCP bridge, wsh-host only says what the host is; any other protocol is the
|
|
408
|
+
// embedder's own and is open to a key that is not restricted at all.
|
|
409
|
+
const proto = req.protocol;
|
|
410
|
+
if (proto === 'wsh-fs' && !p.fileTransfer) return no('file-transfer-not-permitted', 'file transfer not permitted for this key');
|
|
411
|
+
if (proto === 'mcp' && !p.mcp) return no('mcp-not-permitted', 'MCP not permitted for this key');
|
|
412
|
+
if (proto !== 'wsh-fs' && proto !== 'mcp' && proto !== 'wsh-host' && !(p.pty && p.exec && p.mcp && p.fileTransfer && p.relay)) {
|
|
413
|
+
return no('exec-not-permitted', 'this protocol is not permitted for a restricted key');
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
if ((ch === 'pty' || ch === 'exec') && p.maxSessions !== null && activeSessions >= p.maxSessions) {
|
|
417
|
+
return no('max-sessions', `max sessions for this key reached (${p.maxSessions})`);
|
|
418
|
+
}
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
case 'file-op':
|
|
422
|
+
if (p.forcedCommand !== null) return no('forced-command', 'key is restricted to forced exec command');
|
|
423
|
+
return p.fileTransfer ? null : no('file-transfer-not-permitted', 'file transfer not permitted for this key');
|
|
424
|
+
case 'mcp': case 'mcp-call': case 'mcp-tool': return p.mcp ? null : no('mcp-not-permitted', 'MCP not permitted for this key');
|
|
425
|
+
case 'relay': return p.relay ? null : no('relay-not-permitted', 'relay not permitted for this key');
|
|
426
|
+
// The gateway, endpoints and targets are not scoped by the options (only by capabilities).
|
|
427
|
+
case 'tcp': case 'udp': case 'dns': case 'listen-tcp': case 'unix': case 'listen-unix': case 'endpoint': case 'target': return null;
|
|
428
|
+
// Installing another key (`AuthorizedKeyAdd`, which the Rust server serves): the new key has no options, so only a key that
|
|
429
|
+
// is not restricted at all may add one -- a restricted key would otherwise mint an unrestricted one.
|
|
430
|
+
case 'key-admin':
|
|
431
|
+
return p.pty && p.exec && p.mcp && p.fileTransfer && p.relay && p.forcedCommand === null ? null
|
|
432
|
+
: no('key-admin-not-permitted', 'installing a key is not permitted for a restricted key');
|
|
433
|
+
default: return no('exec-not-permitted', `unknown request ${JSON.stringify(req.kind)}`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* What an `authorize()` callback may return instead of `true`: `{ capabilities: string | string[], expires?: string | Date | number }`.
|
|
439
|
+
* The same grammar as `capabilities="..."` (a string is comma-separated); `expires` an RFC 3339 string, a `Date` or epoch
|
|
440
|
+
* milliseconds. The result is a permission set that narrows the key's own options (it never widens them).
|
|
441
|
+
*
|
|
442
|
+
* @param {{ capabilities?: string | string[], expires?: string | Date | number }} grant
|
|
443
|
+
* @returns {{ ok: true, permissions: ReturnType<typeof fullAccess> } | { ok: false, code: string, reason: string }}
|
|
444
|
+
*/
|
|
445
|
+
export function grantPermissions(grant) {
|
|
446
|
+
const out = fullAccess();
|
|
447
|
+
let parsed = null;
|
|
448
|
+
if (grant.capabilities !== undefined) {
|
|
449
|
+
const r = parseCapabilityList(grant.capabilities);
|
|
450
|
+
if (!r.ok) return r;
|
|
451
|
+
out.capabilities = r.capabilities;
|
|
452
|
+
parsed = r.parsed;
|
|
453
|
+
}
|
|
454
|
+
if (grant.expires !== undefined) {
|
|
455
|
+
let secs = null;
|
|
456
|
+
if (typeof grant.expires === 'string') secs = parseRfc3339(grant.expires);
|
|
457
|
+
else if (grant.expires instanceof Date && Number.isFinite(grant.expires.getTime())) secs = Math.floor(grant.expires.getTime() / 1000);
|
|
458
|
+
else if (typeof grant.expires === 'number' && Number.isFinite(grant.expires)) secs = Math.floor(grant.expires / 1000);
|
|
459
|
+
if (secs === null) return fail('bad-value', 'expires must be an RFC 3339 string, a Date or epoch milliseconds');
|
|
460
|
+
out.expires = secs;
|
|
461
|
+
}
|
|
462
|
+
Object.defineProperty(out, '_caps', { value: parsed, enumerable: false });
|
|
463
|
+
return { ok: true, permissions: out };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const isSpace = (c) => c === ' ' || c === '\t';
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Parse one `authorized_keys` line.
|
|
470
|
+
* - `{ skip: reason }` -- nothing to act on: blank, a comment, a key type this host does not serve (only `ssh-ed25519` is
|
|
471
|
+
* used), or a line that cannot be split into options and a key (an unterminated quote);
|
|
472
|
+
* - `{ refused: { code, reason }, key }` -- an ed25519 key whose options are not understood: it must not be let in;
|
|
473
|
+
* - `{ key, options, permissions }` -- a usable entry (`options` is the raw options token or `null`).
|
|
474
|
+
*
|
|
475
|
+
* @param {string} raw
|
|
476
|
+
*/
|
|
477
|
+
export function parseAuthorizedKeyLine(raw) {
|
|
478
|
+
const line = String(raw).trim();
|
|
479
|
+
if (!line || line.startsWith('#')) return { skip: 'blank or comment' };
|
|
480
|
+
let rest = line;
|
|
481
|
+
let options = null;
|
|
482
|
+
if (!/^ssh-ed25519[ \t]/.test(line)) {
|
|
483
|
+
// Options end at the first whitespace outside double quotes.
|
|
484
|
+
let inQuote = false;
|
|
485
|
+
let i = 0;
|
|
486
|
+
for (; i < line.length; i++) {
|
|
487
|
+
const c = line[i];
|
|
488
|
+
if (inQuote) {
|
|
489
|
+
if (c === '\\' && line[i + 1] === '"') { i++; continue; }
|
|
490
|
+
if (c === '"') inQuote = false;
|
|
491
|
+
} else if (c === '"') inQuote = true;
|
|
492
|
+
else if (isSpace(c)) break;
|
|
493
|
+
}
|
|
494
|
+
if (inQuote) return { skip: 'unterminated quote in the options' };
|
|
495
|
+
options = line.slice(0, i);
|
|
496
|
+
rest = line.slice(i).trim();
|
|
497
|
+
if (!/^ssh-ed25519[ \t]/.test(rest)) return { skip: 'not an ssh-ed25519 key' };
|
|
498
|
+
}
|
|
499
|
+
let key;
|
|
500
|
+
try {
|
|
501
|
+
const parsed = parseSSHPublicKey(rest);
|
|
502
|
+
key = extractRawFromSSHWire(parsed.data);
|
|
503
|
+
if (!(key instanceof Uint8Array) || key.byteLength !== 32) return { skip: 'malformed key' };
|
|
504
|
+
} catch { return { skip: 'malformed key' }; }
|
|
505
|
+
const parsed = parseKeyOptions(options);
|
|
506
|
+
if (!parsed.ok) return { refused: { code: parsed.code, reason: parsed.reason }, key, options };
|
|
507
|
+
return { key, options, permissions: parsed.permissions };
|
|
508
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// `@johnhenry/wsh/mcp-stdio` (wsh #127): the stdio bridge behind the `wsh-mcp` command. Node only.
|
|
2
|
+
|
|
3
|
+
import type { WshClient } from './index.js';
|
|
4
|
+
|
|
5
|
+
/** A failure the bridge cannot recover from. `exitCode` is what the `wsh-mcp` command exits with (2: could not start). */
|
|
6
|
+
export class McpBridgeError extends Error {
|
|
7
|
+
constructor(message: string, options?: { code?: string; exitCode?: number; cause?: unknown });
|
|
8
|
+
/** `connect`, `auth`, `no-channel`, `identity`, `replay` or `bridge`. */
|
|
9
|
+
code: string;
|
|
10
|
+
exitCode: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** `~/.wsh/keys/default.pem`, the key `wsh keygen` makes. */
|
|
14
|
+
export function defaultIdentityPath(): string;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Read an Ed25519 private key file (`-----BEGIN WSH PRIVATE KEY-----`, the 32-byte secret in base64, or a PKCS#8 PEM) as a
|
|
18
|
+
* signer for `WshClient.connect({ signer })`.
|
|
19
|
+
*/
|
|
20
|
+
export function loadIdentity(file: string): Promise<{ publicKey: Uint8Array; sign(data: Uint8Array): Promise<Uint8Array> }>;
|
|
21
|
+
|
|
22
|
+
export interface McpStdioBridgeOptions {
|
|
23
|
+
/** `ws://`, `wss://` or `https://` URL of the wsh host. */
|
|
24
|
+
url: string;
|
|
25
|
+
username: string;
|
|
26
|
+
signer: { publicKey: Uint8Array; sign(data: Uint8Array): Promise<Uint8Array> };
|
|
27
|
+
/** The rpc protocol to open. Default `'mcp'`. */
|
|
28
|
+
channel?: string;
|
|
29
|
+
/** Pin the host: a hex fingerprint, a raw key or an `ssh-ed25519` line. */
|
|
30
|
+
expectHostKey?: string | Uint8Array;
|
|
31
|
+
/** After a lost connection: attempts (default 5), first delay in ms (500, doubling) and the longest delay (10000); `false` to exit instead. */
|
|
32
|
+
reconnect?: false | { attempts?: number; delayMs?: number; maxDelayMs?: number };
|
|
33
|
+
/** To log in and to open the channel, ms. Default 15000. */
|
|
34
|
+
timeoutMs?: number;
|
|
35
|
+
/** Longest message accepted from the client, bytes. Default 8 MiB. */
|
|
36
|
+
maxLineBytes?: number;
|
|
37
|
+
/** Messages held while reconnecting. Default 200. */
|
|
38
|
+
maxQueued?: number;
|
|
39
|
+
/** Newline-delimited JSON-RPC from the MCP client. Default `process.stdin`. */
|
|
40
|
+
input?: AsyncIterable<Uint8Array | string>;
|
|
41
|
+
/** MCP messages to the client, one JSON-RPC message per line; nothing else is ever written here. Default `process.stdout`. */
|
|
42
|
+
output?: { write(chunk: string): unknown };
|
|
43
|
+
/** Diagnostics. Default `process.stderr`. */
|
|
44
|
+
errorOutput?: { write(chunk: string): unknown };
|
|
45
|
+
clientFactory?: () => WshClient;
|
|
46
|
+
/** Set `close` to end the bridge from outside (a signal handler). */
|
|
47
|
+
signalHandle?: { close: (() => Promise<void>) | null } | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Bridge `input` / `output` to the `mcp` channel of a wsh host. Resolves with the exit status (0: the client closed its side;
|
|
52
|
+
* 1: the host was lost for good); rejects with an `McpBridgeError` when it cannot start.
|
|
53
|
+
*/
|
|
54
|
+
export function runMcpStdioBridge(options: McpStdioBridgeOptions): Promise<number>;
|