@johnhenry/wsh 0.42.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.
@@ -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
+ }
@@ -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. */
@@ -86,6 +86,14 @@ export interface WshMemoryHostOptions {
86
86
  sealSession?: false | 'offer' | 'require';
87
87
  /** #163: told once per connection this host turned away (a key it does not allow, a plain client on a host that requires a sealed session, ...), with a stable reason code. */
88
88
  onRefused?: WshOnRefused;
89
+ /**
90
+ * #121: execution targets, each with its own `exec`, `pty`, `fs` and `endpoints` and an `authorize(who, { target, kind })`.
91
+ * A client names one in `Open`, `FileOp` or `OpenEndpoint` and lists what it may use with `listTargets()`. Off unless given:
92
+ * the host then advertises no `targets` and refuses a request that names one.
93
+ */
94
+ targets?: Record<string, import('./host.js').WshTargetOptions>;
95
+ /** With `targets`: an `Open`, `FileOp` or `OpenEndpoint` that names no target is refused (nothing runs on the host itself). */
96
+ requireTarget?: boolean;
89
97
  onLog?: (line: string) => void;
90
98
  }
91
99
 
@@ -172,6 +172,10 @@ function createRegistry(sessions, log) {
172
172
  * backpressure) and `who` is the authenticated `{ username, fingerprint }`, so the handler can authorise per call:
173
173
  * throw synchronously to refuse, or give `{ open, authorize(who) }`. Only the names listed here exist (an allow-list by
174
174
  * construction); nothing else of the gateway (TCP, DNS, unix sockets) is on in memory.
175
+ * @param {Record<string, { description?: string, authorize?: Function, exec?: Function | { run: Function }, pty?: object, fs?: object, endpoints?: object }>} [options.targets]
176
+ * Execution targets (#121), as for `createWshServer`: each with its own `exec`, `pty`, `fs` and `endpoints` (the injected
177
+ * forms only: there is no shell or directory here) and an `authorize(who, { target, kind })`. Off unless given.
178
+ * @param {boolean} [options.requireTarget=false] - With `targets`: a request that names no target is refused. As for `createWshServer`.
175
179
  * @param {number} [options.bindTimeoutMs=3000]
176
180
  * @param {number} [options.connectionTtlMs=0] - End each authenticated connection this long after login; advertised as
177
181
  * `AuthOk.ttl` in whole seconds (#125). 0 = never.
@@ -190,7 +194,7 @@ function createRegistry(sessions, log) {
190
194
  * @param {(line: string) => void} [options.onLog]
191
195
  */
192
196
  export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, sealSession = false, onLog = () => {},
193
- onShare, onRefused } = {}) {
197
+ onShare, onRefused, targets, requireTarget } = {}) {
194
198
  validateOnShare(onShare, 'createMemoryHost');
195
199
  validateOnRefused(onRefused, 'createMemoryHost');
196
200
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
@@ -209,7 +213,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
209
213
  if (typeof dataStreams !== 'boolean') throw new TypeError('createMemoryHost: dataStreams must be true or false');
210
214
  const rpcHost = rpc === undefined || rpc === null ? null : createRpcTable(rpc, rpcMaxMessageBytes, rpcMaxInflight);
211
215
  const registry = sessions === undefined || sessions === null || sessions === false ? null : createRegistry(sessions, onLog);
212
- const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost } = resolveBackends({ exec, pty, fs, mcp });
216
+ const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost, targets: targetTable, requireTarget: mustHaveTarget } = resolveBackends({ exec, pty, fs, mcp, targets, requireTarget });
213
217
  const hostKeyReady = hostKey === undefined || hostKey === null || hostKey === false ? Promise.resolve(null) : resolveHostKey(hostKey, 'createMemoryHost: hostKey');
214
218
  const rl = auth?.rateLimit ?? {};
215
219
  const rateLimit = {
@@ -220,11 +224,14 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
220
224
  const methods = authMethods(auth);
221
225
  // Named virtual endpoints: a gateway with no TCP, DNS or unix sockets that answers only `OpenEndpoint`, built from
222
226
  // the browser-safe core (`server/gateway-core.mjs`), so a page can have it.
223
- const gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
227
+ let gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
228
+ // A target's own endpoints (#121) need the endpoints-only gateway too, even when the host has none of its own.
229
+ if (targetTable && [...targetTable.values()].some((t) => t.endpoints)) gatewayCfg = { ...(gatewayCfg ?? normalizeEndpointGateway({})), targetEndpoints: true };
224
230
 
225
- 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({
226
232
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
227
233
  methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
234
+ targets: targetTable, requireTarget: mustHaveTarget,
228
235
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
229
236
  }));
230
237
  ready.catch(() => {});
@@ -162,6 +162,10 @@ export const MSG = Object.freeze({
162
162
  SHARE_OFFER: 0xa8,
163
163
  SHARE_REQUEST: 0xa9,
164
164
  SHARE_REPLY: 0xaa,
165
+
166
+ // Targets
167
+ LIST_TARGETS: 0xab,
168
+ TARGET_LIST: 0xac,
165
169
  });
166
170
 
167
171
  // Reverse lookup: number → name
@@ -252,13 +256,14 @@ export function authFail({ reason } = {}) {
252
256
  };
253
257
  }
254
258
 
255
- export function open({ kind, command, cols, rows, env, stdio } = {}) {
259
+ export function open({ kind, command, cols, rows, env, stdio, target } = {}) {
256
260
  const msg = { type: MSG.OPEN, kind };
257
261
  if (command !== undefined) msg.command = command;
258
262
  if (cols !== undefined) msg.cols = cols;
259
263
  if (rows !== undefined) msg.rows = rows;
260
264
  if (env !== undefined) msg.env = env;
261
265
  if (stdio !== undefined) msg.stdio = stdio;
266
+ if (target !== undefined) msg.target = target;
262
267
  return msg;
263
268
  }
264
269
 
@@ -595,12 +600,10 @@ export function openUnix({ gatewayId, path } = {}) {
595
600
  };
596
601
  }
597
602
 
598
- export function openEndpoint({ gatewayId, name } = {}) {
599
- return {
600
- type: MSG.OPEN_ENDPOINT,
601
- gateway_id: gatewayId,
602
- name,
603
- };
603
+ export function openEndpoint({ gatewayId, name, target } = {}) {
604
+ const msg = { type: MSG.OPEN_ENDPOINT, gateway_id: gatewayId, name };
605
+ if (target !== undefined) msg.target = target;
606
+ return msg;
604
607
  }
605
608
 
606
609
  export function listenUnix({ listenerId, path, replace } = {}) {
@@ -921,10 +924,11 @@ export function sessionRevoke({ sessionId, principal, reason } = {}) {
921
924
  return msg;
922
925
  }
923
926
 
924
- export function fileOp({ channelId, op, path, offset, length } = {}) {
927
+ export function fileOp({ channelId, op, path, offset, length, target } = {}) {
925
928
  const msg = { type: MSG.FILE_OP, channel_id: channelId, op, path };
926
929
  if (offset !== undefined) msg.offset = offset;
927
930
  if (length !== undefined) msg.length = length;
931
+ if (target !== undefined) msg.target = target;
928
932
  return msg;
929
933
  }
930
934
 
@@ -1023,6 +1027,17 @@ export function shareReply({ requestId, ok, errno, message, attr = {}, entries =
1023
1027
  return msg;
1024
1028
  }
1025
1029
 
1030
+ export function listTargets() {
1031
+ return { type: MSG.LIST_TARGETS };
1032
+ }
1033
+
1034
+ export function targetList({ targets } = {}) {
1035
+ return {
1036
+ type: MSG.TARGET_LIST,
1037
+ targets,
1038
+ };
1039
+ }
1040
+
1026
1041
  // ── Relay forwarding ─────────────────────────────────────────────────
1027
1042
 
1028
1043
  // Message types a relay may forward inside a RelayForward wrapper.
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 */
@@ -97,6 +97,7 @@ export function createReverseHostWith({
97
97
  if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
98
98
  if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
99
99
  if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
100
+ if (backends.targets) throw new TypeError('createReverseHost: targets are not supported by a reverse host (a bridged operator reaches the one machine behind it); use createWshServer or createMemoryHost');
100
101
  if (!url) throw new TypeError('createReverseHost: url is required');
101
102
  if (!username) throw new TypeError('createReverseHost: username is required');
102
103
  if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
@@ -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
- parseSSHPublicKey, extractRawFromSSHWire, fingerprint,
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
- * per line; blank lines and `#` comments ignored) into raw 32-byte keys.
13
- * Malformed lines are skipped rather than failing the whole list.
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
- const keys = [];
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
- * @returns {Promise<(who: {username: string, fingerprint: string, publicKey: Uint8Array}) => Promise<boolean>>}
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
- if (typeof auth === 'function') return async (who) => (await auth(who)) === true;
50
- if (!auth) return async () => false;
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
- const raws = typeof item === 'string' ? parseAuthorizedKeys(item) : [item];
59
- for (const raw of raws) {
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
- allowed.add(await fingerprint(raw));
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)) === true;
110
+ if (custom) return verdict(await custom(who));
73
111
  return true;
74
- };
112
+ });
75
113
  }
76
114
 
77
115
  /**
@@ -10,13 +10,10 @@
10
10
 
11
11
  import { spawnRunner } from './exec.mjs';
12
12
  import { createFileAccess } from './fs.mjs';
13
- import { resolveBackends } from '../host-backends.mjs';
13
+ import { resolveBackends, normalizeTargets } from '../host-backends.mjs';
14
14
 
15
- /**
16
- * @param {{ exec?: true | object | Function, pty?: object, fs?: object, mcp?: object }} options
17
- * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null }}
18
- */
19
- export function buildBackends({ exec, pty, fs, mcp } = {}) {
15
+ /** The backends of one host (or one target) from `exec`, `pty`, `fs`, `mcp`, with the Node forms (`exec: true`, `fs: { root }`). */
16
+ function buildOwnBackends({ exec, pty, fs, mcp } = {}) {
20
17
  let hostExec = exec;
21
18
  if (exec && typeof exec !== 'function') {
22
19
  const execOptions = exec === true ? {} : exec;
@@ -24,3 +21,11 @@ export function buildBackends({ exec, pty, fs, mcp } = {}) {
24
21
  }
25
22
  return resolveBackends({ exec: hostExec, pty, fs: fs && typeof fs.root === 'string' ? createFileAccess(fs) : fs, mcp });
26
23
  }
24
+
25
+ /**
26
+ * @param {{ exec?: true | object | Function, pty?: object, fs?: object, mcp?: object, targets?: object, requireTarget?: boolean }} options
27
+ * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null, targets: Map<string, object> | null, requireTarget: boolean }}
28
+ */
29
+ export function buildBackends({ exec, pty, fs, mcp, targets, requireTarget } = {}) {
30
+ return { ...buildOwnBackends({ exec, pty, fs, mcp }), ...normalizeTargets(targets, requireTarget, buildOwnBackends, 'createWshServer') };
31
+ }