@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,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `wsh-mcp` (wsh #127): a stdio bridge so an MCP client that launches a command can reach an MCP server behind a wsh host.
|
|
3
|
+
*
|
|
4
|
+
* The client speaks MCP over stdio (one JSON-RPC message per line); this connects to a wsh host, opens the host's `mcp` rpc
|
|
5
|
+
* channel (`createWshServer({ rpc: { mcp: mcpServerAdapter(server) } })`, or `createMemoryHost({ rpc: { mcp } })` reached through
|
|
6
|
+
* any WebSocket) and passes the messages both ways, verbatim: ids, notifications, progress and cancellation (`src/rpc-mcp.mjs`).
|
|
7
|
+
*
|
|
8
|
+
* If the connection drops after it was up, the bridge reconnects with a backoff and, when the client had already initialized,
|
|
9
|
+
* replays that `initialize` / `notifications/initialized` to the new channel (its answer is not shown to the client), so the
|
|
10
|
+
* session carries on. A request that was in flight when the connection dropped is answered with a JSON-RPC error (the client may
|
|
11
|
+
* retry); messages the client sends meanwhile are held (bounded) and delivered once the channel is back.
|
|
12
|
+
*
|
|
13
|
+
* Node only (it reads a key file and talks to stdio); the package root never imports it.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { createPrivateKey, createPublicKey, sign as nodeSign } from 'node:crypto';
|
|
17
|
+
import { readFile } from 'node:fs/promises';
|
|
18
|
+
import { homedir } from 'node:os';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { WshClient, mcpClientTransport, rpcProtocolFeature, RPC_PROTOCOL_NAME_RE } from './index.mjs';
|
|
21
|
+
|
|
22
|
+
/** A failure the bridge cannot recover from, with the process exit status it asks for (2: could not start; 1: lost for good). */
|
|
23
|
+
export class McpBridgeError extends Error {
|
|
24
|
+
constructor(message, { code = 'bridge', exitCode = 2, cause } = {}) {
|
|
25
|
+
super(message, cause ? { cause } : undefined);
|
|
26
|
+
this.name = 'McpBridgeError';
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.exitCode = exitCode;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const PKCS8_ED25519_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
|
|
33
|
+
|
|
34
|
+
/** The default identity: the key `wsh keygen` makes (`~/.wsh/keys/default.pem`). */
|
|
35
|
+
export const defaultIdentityPath = () => path.join(homedir(), '.wsh', 'keys', 'default.pem');
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Read an Ed25519 private key file: the `wsh keygen` format (`-----BEGIN WSH PRIVATE KEY-----`, the 32-byte secret in base64) or
|
|
39
|
+
* a PKCS#8 PEM (`-----BEGIN PRIVATE KEY-----`). Returns a signer for `WshClient.connect`.
|
|
40
|
+
*
|
|
41
|
+
* @param {string} file
|
|
42
|
+
* @returns {Promise<{ publicKey: Uint8Array, sign(data: Uint8Array): Promise<Uint8Array> }>}
|
|
43
|
+
*/
|
|
44
|
+
export async function loadIdentity(file) {
|
|
45
|
+
let text;
|
|
46
|
+
try { text = await readFile(file, 'utf8'); } catch (e) {
|
|
47
|
+
throw new McpBridgeError(`cannot read the identity file ${file}: ${e.code === 'ENOENT' ? 'no such file (make one with `wsh keygen`, or pass --identity)' : e.message}`, { code: 'identity' });
|
|
48
|
+
}
|
|
49
|
+
let key;
|
|
50
|
+
try {
|
|
51
|
+
const wsh = /-----BEGIN WSH PRIVATE KEY-----([\s\S]*?)-----END WSH PRIVATE KEY-----/.exec(text);
|
|
52
|
+
if (wsh) {
|
|
53
|
+
const seed = Buffer.from(wsh[1].replace(/\s+/g, ''), 'base64');
|
|
54
|
+
if (seed.length !== 32) throw new Error('the secret is not 32 bytes');
|
|
55
|
+
key = createPrivateKey({ key: Buffer.concat([PKCS8_ED25519_PREFIX, seed]), format: 'der', type: 'pkcs8' });
|
|
56
|
+
} else if (/-----BEGIN PRIVATE KEY-----/.test(text)) {
|
|
57
|
+
key = createPrivateKey(text);
|
|
58
|
+
} else {
|
|
59
|
+
throw new Error('not a WSH PRIVATE KEY or PKCS#8 PRIVATE KEY PEM');
|
|
60
|
+
}
|
|
61
|
+
if (key.asymmetricKeyType !== 'ed25519') throw new Error('not an Ed25519 key');
|
|
62
|
+
} catch (e) {
|
|
63
|
+
throw new McpBridgeError(`cannot use the identity file ${file}: ${e.message}`, { code: 'identity' });
|
|
64
|
+
}
|
|
65
|
+
const jwk = createPublicKey(key).export({ format: 'jwk' });
|
|
66
|
+
const publicKey = new Uint8Array(Buffer.from(jwk.x, 'base64url'));
|
|
67
|
+
return { publicKey, sign: async (data) => new Uint8Array(nodeSign(null, data, key)) };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const sleep = (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.(); });
|
|
71
|
+
const errorResponse = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Bridge `input` / `output` (newline-delimited JSON-RPC, as MCP stdio does) to the `mcp` channel of the host at `url`.
|
|
75
|
+
* Resolves with the exit status once `input` ends (0) or the connection is lost for good (1); rejects with an `McpBridgeError`
|
|
76
|
+
* (exit status 2) when it cannot start: no connection, a refused login, or a host with no such channel.
|
|
77
|
+
*
|
|
78
|
+
* @param {object} options
|
|
79
|
+
* @param {string} options.url - `ws://`, `wss://` or `https://` URL of the host
|
|
80
|
+
* @param {string} options.username
|
|
81
|
+
* @param {{ publicKey: Uint8Array, sign(data: Uint8Array): Promise<Uint8Array> }} options.signer - see `loadIdentity`
|
|
82
|
+
* @param {string} [options.channel='mcp'] - the rpc protocol to open
|
|
83
|
+
* @param {string | Uint8Array} [options.expectHostKey] - pin the host key (hex fingerprint, raw key or `ssh-ed25519` line)
|
|
84
|
+
* @param {false | { attempts?: number, delayMs?: number, maxDelayMs?: number }} [options.reconnect] - default 5 attempts from 500 ms, doubling
|
|
85
|
+
* @param {number} [options.timeoutMs=15000] - to log in and to open the channel
|
|
86
|
+
* @param {number} [options.maxLineBytes=8388608] - longest message accepted from the client
|
|
87
|
+
* @param {number} [options.maxQueued=200] - messages held while reconnecting
|
|
88
|
+
* @param {AsyncIterable<Uint8Array | string>} [options.input=process.stdin]
|
|
89
|
+
* @param {{ write(chunk: string): unknown }} [options.output=process.stdout] - protocol only; nothing else is ever written here
|
|
90
|
+
* @param {{ write(chunk: string): unknown }} [options.errorOutput=process.stderr]
|
|
91
|
+
* @param {() => WshClient} [options.clientFactory]
|
|
92
|
+
* @param {{ close(): Promise<void> } | null} [options.signalHandle] - set `close` to end the bridge from outside (a signal)
|
|
93
|
+
* @returns {Promise<number>}
|
|
94
|
+
*/
|
|
95
|
+
export async function runMcpStdioBridge({
|
|
96
|
+
url, username, signer, channel = 'mcp', expectHostKey, reconnect, timeoutMs = 15_000, maxLineBytes = 8 * 1024 * 1024, maxQueued = 200,
|
|
97
|
+
input = process.stdin, output = process.stdout, errorOutput = process.stderr, clientFactory = () => new WshClient(), signalHandle = null,
|
|
98
|
+
}) {
|
|
99
|
+
if (typeof url !== 'string' || !url) throw new McpBridgeError('a host URL is required');
|
|
100
|
+
if (!username) throw new McpBridgeError('a login name is required (--user)');
|
|
101
|
+
if (!RPC_PROTOCOL_NAME_RE.test(channel)) throw new McpBridgeError(`${JSON.stringify(channel)} is not a valid channel name`);
|
|
102
|
+
const policy = reconnect === false ? { attempts: 0 } : { attempts: 5, delayMs: 500, maxDelayMs: 10_000, ...(reconnect ?? {}) };
|
|
103
|
+
const note = (line) => { try { errorOutput.write(`wsh-mcp: ${line}\n`); } catch { /* stderr gone */ } };
|
|
104
|
+
const emit = (message) => { output.write(`${JSON.stringify(message)}\n`); };
|
|
105
|
+
|
|
106
|
+
/** @type {{ client: WshClient, transport: ReturnType<typeof mcpClientTransport> } | null} */
|
|
107
|
+
let current = null;
|
|
108
|
+
let closing = false;
|
|
109
|
+
let finished = false;
|
|
110
|
+
let exitCode = 0;
|
|
111
|
+
let resolveDone;
|
|
112
|
+
const done = new Promise((resolve) => { resolveDone = resolve; });
|
|
113
|
+
/** Ids of requests forwarded to the host and not answered yet. */
|
|
114
|
+
const inflight = new Set();
|
|
115
|
+
/** What the client sent to initialize, kept to replay on a new channel. */
|
|
116
|
+
let initializeRequest = null;
|
|
117
|
+
let initializedNotification = null;
|
|
118
|
+
let replaySeq = 0;
|
|
119
|
+
/** Messages from the client while the connection is being re-made. */
|
|
120
|
+
const held = [];
|
|
121
|
+
let reconnecting = false;
|
|
122
|
+
let warnedUnpinned = false;
|
|
123
|
+
|
|
124
|
+
async function open() {
|
|
125
|
+
const client = clientFactory();
|
|
126
|
+
try {
|
|
127
|
+
await client.connect(url, { username, signer, timeout: timeoutMs, ...(expectHostKey ? { expectHostKey } : {}) });
|
|
128
|
+
} catch (e) {
|
|
129
|
+
throw new McpBridgeError(`cannot connect to ${url}: ${e?.message ?? e}`, { code: /Authentication failed|not authorized|host key/i.test(String(e?.message)) ? 'auth' : 'connect', cause: e });
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
if (!warnedUnpinned && client.hostKey?.status === 'unpinned') {
|
|
133
|
+
warnedUnpinned = true;
|
|
134
|
+
note(`the host key of ${url} is not pinned (${client.hostKey.fingerprint ?? 'none proven'}); pass --host-key to verify it`);
|
|
135
|
+
}
|
|
136
|
+
if (!client.hasFeature(rpcProtocolFeature(channel))) {
|
|
137
|
+
const offered = client.serverFeatures.filter((f) => f.startsWith('rpc-protocol:')).map((f) => f.slice('rpc-protocol:'.length));
|
|
138
|
+
throw new McpBridgeError(
|
|
139
|
+
`the host at ${url} offers no "${channel}" channel${offered.length ? ` (it offers: ${offered.join(', ')})` : ' (it offers no rpc channels)'}. `
|
|
140
|
+
+ 'Serve one with createWshServer({ rpc: { mcp: mcpServerAdapter(server) } }) or createMemoryHost({ rpc: { mcp } }).',
|
|
141
|
+
{ code: 'no-channel' },
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
let rpc;
|
|
145
|
+
try { rpc = await client.openRpc(channel, { openTimeout: timeoutMs }); } catch (e) {
|
|
146
|
+
throw new McpBridgeError(`the host at ${url} did not open the "${channel}" channel: ${e?.message ?? e}`, { code: 'no-channel', cause: e });
|
|
147
|
+
}
|
|
148
|
+
const transport = mcpClientTransport(rpc);
|
|
149
|
+
transport.onmessage = (message) => fromHost(transport, message);
|
|
150
|
+
transport.onclose = () => lost(transport);
|
|
151
|
+
transport.onerror = (e) => note(`channel error: ${e?.message ?? e}`);
|
|
152
|
+
client.onClose = () => lost(transport);
|
|
153
|
+
await transport.start();
|
|
154
|
+
return { client, transport };
|
|
155
|
+
} catch (e) {
|
|
156
|
+
await client.disconnect().catch(() => {});
|
|
157
|
+
throw e;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function fromHost(transport, message) {
|
|
162
|
+
if (!current || current.transport !== transport) return;
|
|
163
|
+
const isResponse = message && message.id !== undefined && message.id !== null && typeof message.method !== 'string';
|
|
164
|
+
if (isResponse) inflight.delete(message.id);
|
|
165
|
+
try { emit(message); } catch (e) { note(`cannot write to the client: ${e.message}`); }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The channel or the connection is gone. */
|
|
169
|
+
function lost(transport) {
|
|
170
|
+
if (finished || !current || current.transport !== transport) return;
|
|
171
|
+
const { client } = current;
|
|
172
|
+
current = null;
|
|
173
|
+
client.disconnect().catch(() => {});
|
|
174
|
+
if (closing) return;
|
|
175
|
+
for (const id of inflight) emit(errorResponse(id, -32603, 'the connection to the wsh host was lost before this request was answered'));
|
|
176
|
+
inflight.clear();
|
|
177
|
+
void recover();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function recover() {
|
|
181
|
+
if (reconnecting) return;
|
|
182
|
+
reconnecting = true;
|
|
183
|
+
try {
|
|
184
|
+
let delay = policy.delayMs ?? 500;
|
|
185
|
+
for (let attempt = 1; attempt <= policy.attempts && !closing; attempt++) {
|
|
186
|
+
note(`connection lost; reconnecting (attempt ${attempt} of ${policy.attempts})`);
|
|
187
|
+
await sleep(delay);
|
|
188
|
+
delay = Math.min(delay * 2, policy.maxDelayMs ?? 10_000);
|
|
189
|
+
if (closing) return;
|
|
190
|
+
let next;
|
|
191
|
+
try {
|
|
192
|
+
next = await open();
|
|
193
|
+
await replayInitialization(next);
|
|
194
|
+
} catch (e) {
|
|
195
|
+
note(`reconnect failed: ${e?.message ?? e}`);
|
|
196
|
+
if (next) await next.client.disconnect().catch(() => {});
|
|
197
|
+
if (e instanceof McpBridgeError && (e.code === 'auth' || e.code === 'no-channel')) break;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
current = next;
|
|
201
|
+
note('reconnected');
|
|
202
|
+
for (const message of held.splice(0)) await forward(message);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (closing) return;
|
|
206
|
+
note(policy.attempts > 0 ? 'could not reconnect; giving up' : 'connection lost');
|
|
207
|
+
for (const message of held.splice(0)) if (message.id !== undefined && message.id !== null && typeof message.method === 'string') emit(errorResponse(message.id, -32603, 'the wsh host is unreachable'));
|
|
208
|
+
exitCode = 1;
|
|
209
|
+
await finish();
|
|
210
|
+
} finally {
|
|
211
|
+
reconnecting = false;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** On a new channel the MCP server has not been initialized: do it again, as the client did, and keep the answer to ourselves. */
|
|
216
|
+
async function replayInitialization(next) {
|
|
217
|
+
if (!initializeRequest) return;
|
|
218
|
+
const id = `wsh-mcp-replay-${++replaySeq}`;
|
|
219
|
+
// `current` is not this channel yet: its answer is caught here and never reaches the client.
|
|
220
|
+
const normal = next.transport.onmessage;
|
|
221
|
+
const reply = new Promise((resolve) => {
|
|
222
|
+
next.transport.onmessage = (message) => {
|
|
223
|
+
if (message?.id === id && typeof message.method !== 'string') resolve(message);
|
|
224
|
+
else normal(message);
|
|
225
|
+
};
|
|
226
|
+
});
|
|
227
|
+
await next.transport.send({ ...initializeRequest, id });
|
|
228
|
+
const message = await Promise.race([reply, sleep(timeoutMs).then(() => null)]);
|
|
229
|
+
next.transport.onmessage = normal;
|
|
230
|
+
if (!message || message.error) throw new McpBridgeError(`the host did not accept the replayed initialize: ${message?.error?.message ?? 'no answer'}`, { code: 'replay' });
|
|
231
|
+
if (initializedNotification) await next.transport.send(initializedNotification);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function forward(message) {
|
|
235
|
+
const isRequest = typeof message.method === 'string' && message.id !== undefined && message.id !== null;
|
|
236
|
+
if (isRequest) inflight.add(message.id);
|
|
237
|
+
try {
|
|
238
|
+
await current.transport.send(message);
|
|
239
|
+
} catch (e) {
|
|
240
|
+
if (isRequest) { inflight.delete(message.id); emit(errorResponse(message.id, -32603, `wsh: ${e?.message ?? e}`)); }
|
|
241
|
+
else note(`could not send ${message.method ?? 'a response'}: ${e?.message ?? e}`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function fromClient(line) {
|
|
246
|
+
let message;
|
|
247
|
+
try { message = JSON.parse(line); } catch { emit(errorResponse(null, -32700, 'Parse error')); return; }
|
|
248
|
+
if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0') {
|
|
249
|
+
emit(errorResponse(message?.id ?? null, -32600, 'Invalid Request: expected one JSON-RPC 2.0 message per line'));
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (message.method === 'initialize' && message.id !== undefined) initializeRequest = message;
|
|
253
|
+
else if (message.method === 'notifications/initialized') initializedNotification = message;
|
|
254
|
+
if (!current) {
|
|
255
|
+
if (held.length >= maxQueued) {
|
|
256
|
+
if (message.id !== undefined && message.id !== null && typeof message.method === 'string') emit(errorResponse(message.id, -32603, 'too many messages while reconnecting'));
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
held.push(message);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
await forward(message);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function finish() {
|
|
266
|
+
if (finished) return;
|
|
267
|
+
finished = true;
|
|
268
|
+
closing = true;
|
|
269
|
+
const c = current;
|
|
270
|
+
current = null;
|
|
271
|
+
if (c) { await c.transport.close().catch(() => {}); await c.client.disconnect().catch(() => {}); }
|
|
272
|
+
resolveDone(exitCode);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (signalHandle) signalHandle.close = finish;
|
|
276
|
+
|
|
277
|
+
current = await open(); // a failure to start is the caller's (exit status 2)
|
|
278
|
+
|
|
279
|
+
// Read the client's side: lines, in order, bounded.
|
|
280
|
+
(async () => {
|
|
281
|
+
let buf = '';
|
|
282
|
+
let skipping = false;
|
|
283
|
+
let chain = Promise.resolve();
|
|
284
|
+
const decoder = new TextDecoder();
|
|
285
|
+
const push = (line) => { chain = chain.then(() => fromClient(line)).catch((e) => note(`internal error: ${e?.message ?? e}`)); };
|
|
286
|
+
try {
|
|
287
|
+
for await (const chunk of input) {
|
|
288
|
+
buf += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
|
|
289
|
+
let nl;
|
|
290
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
291
|
+
const line = buf.slice(0, nl).replace(/\r$/, '');
|
|
292
|
+
buf = buf.slice(nl + 1);
|
|
293
|
+
if (skipping) { skipping = false; continue; }
|
|
294
|
+
if (line.length > maxLineBytes) { emit(errorResponse(null, -32600, `message too large (more than ${maxLineBytes} bytes)`)); continue; }
|
|
295
|
+
if (line.trim()) push(line);
|
|
296
|
+
}
|
|
297
|
+
if (buf.length > maxLineBytes) {
|
|
298
|
+
emit(errorResponse(null, -32600, `message too large (more than ${maxLineBytes} bytes)`));
|
|
299
|
+
buf = '';
|
|
300
|
+
skipping = true;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (buf.trim() && !skipping) push(buf);
|
|
304
|
+
} catch (e) { note(`cannot read the client: ${e?.message ?? e}`); }
|
|
305
|
+
await chain;
|
|
306
|
+
await finish();
|
|
307
|
+
})();
|
|
308
|
+
|
|
309
|
+
return done;
|
|
310
|
+
}
|
package/src/memory-host.d.ts
CHANGED
|
@@ -28,7 +28,7 @@ export interface WshMemoryRpcContext {
|
|
|
28
28
|
|
|
29
29
|
export interface WshMemoryHostOptions {
|
|
30
30
|
/** As for `createWshServer`. Omitted = refuse everyone. */
|
|
31
|
-
auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>);
|
|
31
|
+
auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | { capabilities?: string | string[]; expires?: string | Date | number } | Promise<boolean | { capabilities?: string | string[]; expires?: string | Date | number }>);
|
|
32
32
|
/** `run(command, io)`; there is no shell in memory, so there is no `true`. */
|
|
33
33
|
exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
|
|
34
34
|
/** `node-pty`-shaped `{ spawn }`, injected (a browser has no pty of its own). Input arrives at `write` as a `Uint8Array`. Off unless given. */
|
package/src/memory-host.mjs
CHANGED
|
@@ -228,7 +228,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
|
|
|
228
228
|
// A target's own endpoints (#121) need the endpoints-only gateway too, even when the host has none of its own.
|
|
229
229
|
if (targetTable && [...targetTable.values()].some((t) => t.endpoints)) gatewayCfg = { ...(gatewayCfg ?? normalizeEndpointGateway({})), targetEndpoints: true };
|
|
230
230
|
|
|
231
|
-
const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
|
|
231
|
+
const ready = Promise.all([buildAuthorizer(auth, { log: onLog }), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
|
|
232
232
|
authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
|
|
233
233
|
methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
|
|
234
234
|
targets: targetTable, requireTarget: mustHaveTarget,
|
package/src/refusal.mjs
CHANGED
|
@@ -13,12 +13,18 @@
|
|
|
13
13
|
* - `bad-request` a malformed login (bad username, malformed key, the wrong message)
|
|
14
14
|
* - `seal-failed` a sealed session's key exchange failed, or one of its frames did not open
|
|
15
15
|
* - `busy` (reverse host) it already serves its operators
|
|
16
|
+
* - `key-expired` the key is past the `expires` of its `authorized_keys` line (or of what `authorize` returned), at login or on a
|
|
17
|
+
* later request (#122)
|
|
18
|
+
* - `not-permitted` a request the key's options or capabilities do not allow (`restrict`, `command=`, `capabilities="..."`): an
|
|
19
|
+
* `Open`, `FileOp`, MCP call, gateway request, relay request ...; `detail` is `<code>: <reason> (<request>)`, with
|
|
20
|
+
* the missing capability named for `capability-missing` (#122). Unlike the login reasons it can come
|
|
21
|
+
* any number of times on one connection
|
|
16
22
|
* - `proof-required` (reverse host) it requires the operator to prove its identity and the operator offered none
|
|
17
23
|
* - `proof-failed` (reverse host) the operator's proof did not arrive, did not verify or names someone else
|
|
18
24
|
*/
|
|
19
25
|
export const REFUSAL_REASONS = Object.freeze([
|
|
20
26
|
'not-sealed', 'unauthorized', 'binding-required', 'bad-signature', 'method-disabled', 'rate-limited', 'bad-request',
|
|
21
|
-
'seal-failed', 'busy', 'proof-required', 'proof-failed',
|
|
27
|
+
'seal-failed', 'busy', 'proof-required', 'proof-failed', 'key-expired', 'not-permitted',
|
|
22
28
|
]);
|
|
23
29
|
|
|
24
30
|
/** @throws {TypeError} when `onRefused` is given and is not a function */
|
package/src/server/auth.mjs
CHANGED
|
@@ -3,31 +3,41 @@
|
|
|
3
3
|
* Ed25519 public keys (SSH `authorized_keys` style) and/or a custom callback.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
} from '../auth.mjs';
|
|
6
|
+
import { fingerprint } from '../auth.mjs';
|
|
7
|
+
import { parseAuthorizedKeyLine, grantPermissions } from '../key-options.mjs';
|
|
9
8
|
|
|
10
9
|
/**
|
|
11
|
-
* Parse an `authorized_keys`-style blob (one `ssh-ed25519 AAAA... [comment]`
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* Parse an `authorized_keys`-style blob (one `[options] ssh-ed25519 AAAA... [comment]` per line; blank lines and `#` comments
|
|
11
|
+
* ignored) into entries `{ key, options, permissions, line }` (raw 32-byte key, the raw options token or `null`, what the
|
|
12
|
+
* options allow -- see `src/key-options.mjs` -- and the 1-based line number).
|
|
13
|
+
*
|
|
14
|
+
* A line this host cannot make sense of never yields a usable key: one whose options it does not understand is listed in
|
|
15
|
+
* `refused` (`{ line, code, reason, key }`), and a malformed one or another key type is skipped. The same rules and vectors as
|
|
16
|
+
* the Rust server's (`spec/key-options.vectors.json`).
|
|
17
|
+
*
|
|
18
|
+
* @param {string} text
|
|
19
|
+
* @returns {{ entries: Array<{ key: Uint8Array, options: string | null, permissions: object, line: number }>, refused: Array<{ line: number, code: string, reason: string, key: Uint8Array }> }}
|
|
20
|
+
*/
|
|
21
|
+
export function parseAuthorizedKeyEntries(text) {
|
|
22
|
+
const entries = [];
|
|
23
|
+
const refused = [];
|
|
24
|
+
String(text ?? '').split('\n').forEach((raw, i) => {
|
|
25
|
+
const r = parseAuthorizedKeyLine(raw);
|
|
26
|
+
if (r.refused) refused.push({ line: i + 1, ...r.refused, key: r.key });
|
|
27
|
+
else if (r.key) entries.push({ key: r.key, options: r.options, permissions: r.permissions, line: i + 1 });
|
|
28
|
+
});
|
|
29
|
+
return { entries, refused };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The raw 32-byte keys of the lines of an `authorized_keys`-style blob that carry NO options. A line with options is not
|
|
34
|
+
* returned (its restrictions would be lost): use `parseAuthorizedKeyEntries` for those. Malformed lines are skipped.
|
|
14
35
|
*
|
|
15
36
|
* @param {string} text
|
|
16
37
|
* @returns {Uint8Array[]}
|
|
17
38
|
*/
|
|
18
39
|
export function parseAuthorizedKeys(text) {
|
|
19
|
-
|
|
20
|
-
for (const raw of String(text ?? '').split('\n')) {
|
|
21
|
-
const line = raw.trim();
|
|
22
|
-
if (!line || line.startsWith('#')) continue;
|
|
23
|
-
try {
|
|
24
|
-
const parsed = parseSSHPublicKey(line);
|
|
25
|
-
keys.push(extractRawFromSSHWire(parsed.data));
|
|
26
|
-
} catch {
|
|
27
|
-
// skip malformed line
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
return keys;
|
|
40
|
+
return parseAuthorizedKeyEntries(text).entries.filter((e) => e.options === null).map((e) => e.key);
|
|
31
41
|
}
|
|
32
42
|
|
|
33
43
|
/**
|
|
@@ -43,11 +53,29 @@ export function parseAuthorizedKeys(text) {
|
|
|
43
53
|
* authorizedKeys?: string | Uint8Array | Array<string | Uint8Array>,
|
|
44
54
|
* authorize?: (who: {username: string, fingerprint: string, publicKey: Uint8Array}) => boolean | Promise<boolean>,
|
|
45
55
|
* }} auth
|
|
46
|
-
*
|
|
56
|
+
* The function also carries `permissionsFor(fingerprint)`: what the key's `authorized_keys` options allow (`null` for a key
|
|
57
|
+
* without options, a raw key, or a custom `authorize`: full access). A line whose options this host does not understand puts
|
|
58
|
+
* no key on the list and is logged with its reason (`log`).
|
|
59
|
+
*
|
|
60
|
+
* @param {{ log?: (line: string) => void }} [opts]
|
|
61
|
+
* @returns {Promise<((who: {username: string, fingerprint: string, publicKey: Uint8Array}) => Promise<boolean>) & { permissionsFor(fingerprint: string | null | undefined): object | null }>}
|
|
47
62
|
*/
|
|
48
|
-
export async function buildAuthorizer(auth) {
|
|
49
|
-
|
|
50
|
-
|
|
63
|
+
export async function buildAuthorizer(auth, { log = () => {} } = {}) {
|
|
64
|
+
/** @type {Map<string, object>} */
|
|
65
|
+
const perms = new Map();
|
|
66
|
+
const withPerms = (fn) => Object.assign(fn, { permissionsFor: (fp) => (fp ? perms.get(fp) ?? null : null) });
|
|
67
|
+
/** `true` stays `true`; `{ capabilities, expires? }` is a grant (`{ permissions }`, #122); anything else is no. */
|
|
68
|
+
const verdict = (r) => {
|
|
69
|
+
if (r === true) return true;
|
|
70
|
+
if (r && typeof r === 'object' && !Array.isArray(r) && (r.capabilities !== undefined || r.expires !== undefined)) {
|
|
71
|
+
const g = grantPermissions(r);
|
|
72
|
+
if (g.ok) return { permissions: g.permissions };
|
|
73
|
+
log(`authorize returned a grant that is not understood (${g.code}): ${g.reason}`);
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
};
|
|
77
|
+
if (typeof auth === 'function') return withPerms(async (who) => verdict(await auth(who)));
|
|
78
|
+
if (!auth) return withPerms(async () => false);
|
|
51
79
|
|
|
52
80
|
/** @type {Set<string> | null} */
|
|
53
81
|
let allowed = null;
|
|
@@ -55,23 +83,33 @@ export async function buildAuthorizer(auth) {
|
|
|
55
83
|
allowed = new Set();
|
|
56
84
|
const items = Array.isArray(auth.authorizedKeys) ? auth.authorizedKeys : [auth.authorizedKeys];
|
|
57
85
|
for (const item of items) {
|
|
58
|
-
|
|
59
|
-
|
|
86
|
+
let list;
|
|
87
|
+
if (typeof item === 'string') {
|
|
88
|
+
const { entries, refused } = parseAuthorizedKeyEntries(item);
|
|
89
|
+
for (const r of refused) log(`authorized_keys line ${r.line}: key refused (${r.code}): ${r.reason}`);
|
|
90
|
+
list = entries;
|
|
91
|
+
} else {
|
|
92
|
+
list = [{ key: item, permissions: null }];
|
|
93
|
+
}
|
|
94
|
+
for (const { key: raw, permissions } of list) {
|
|
60
95
|
if (!(raw instanceof Uint8Array) || raw.byteLength !== 32) {
|
|
61
96
|
throw new TypeError('createWshServer: auth.authorizedKeys entries must be ssh-ed25519 lines or raw 32-byte Ed25519 keys');
|
|
62
97
|
}
|
|
63
|
-
|
|
98
|
+
const fp = await fingerprint(raw);
|
|
99
|
+
// The first entry for a key decides what it may do, as on the Rust server.
|
|
100
|
+
if (!allowed.has(fp) && permissions) perms.set(fp, permissions);
|
|
101
|
+
allowed.add(fp);
|
|
64
102
|
}
|
|
65
103
|
}
|
|
66
104
|
}
|
|
67
105
|
const custom = typeof auth.authorize === 'function' ? auth.authorize : null;
|
|
68
|
-
if (!allowed && !custom) return async () => false;
|
|
106
|
+
if (!allowed && !custom) return withPerms(async () => false);
|
|
69
107
|
|
|
70
|
-
return async (who) => {
|
|
108
|
+
return withPerms(async (who) => {
|
|
71
109
|
if (allowed && !allowed.has(who.fingerprint)) return false;
|
|
72
|
-
if (custom) return (await custom(who))
|
|
110
|
+
if (custom) return verdict(await custom(who));
|
|
73
111
|
return true;
|
|
74
|
-
};
|
|
112
|
+
});
|
|
75
113
|
}
|
|
76
114
|
|
|
77
115
|
/**
|