@johnhenry/wsh 0.45.0 → 0.46.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.
@@ -28,6 +28,8 @@ export interface McpStdioBridgeOptions {
28
28
  channel?: string;
29
29
  /** Pin the host: a hex fingerprint, a raw key or an `ssh-ed25519` line. */
30
30
  expectHostKey?: string | Uint8Array;
31
+ /** `true` seals the whole session end to end and refuses a host that cannot (key login only); the `--sealed` flag. Default: the client's `'auto'`. */
32
+ sealSession?: boolean | 'auto';
31
33
  /** After a lost connection: attempts (default 5), first delay in ms (500, doubling) and the longest delay (10000); `false` to exit instead. */
32
34
  reconnect?: false | { attempts?: number; delayMs?: number; maxDelayMs?: number };
33
35
  /** To log in and to open the channel, ms. Default 15000. */
package/src/mcp-stdio.mjs CHANGED
@@ -81,6 +81,8 @@ const errorResponse = (id, code, message) => ({ jsonrpc: '2.0', id, error: { cod
81
81
  * @param {{ publicKey: Uint8Array, sign(data: Uint8Array): Promise<Uint8Array> }} options.signer - see `loadIdentity`
82
82
  * @param {string} [options.channel='mcp'] - the rpc protocol to open
83
83
  * @param {string | Uint8Array} [options.expectHostKey] - pin the host key (hex fingerprint, raw key or `ssh-ed25519` line)
84
+ * @param {boolean | 'auto'} [options.sealSession] - the client's `sealSession` (#155): `true` seals the whole session end to end and
85
+ * refuses a host that cannot (the `--sealed` flag); needs a key login. Omitted: the client's default (`'auto'`).
84
86
  * @param {false | { attempts?: number, delayMs?: number, maxDelayMs?: number }} [options.reconnect] - default 5 attempts from 500 ms, doubling
85
87
  * @param {number} [options.timeoutMs=15000] - to log in and to open the channel
86
88
  * @param {number} [options.maxLineBytes=8388608] - longest message accepted from the client
@@ -93,7 +95,7 @@ const errorResponse = (id, code, message) => ({ jsonrpc: '2.0', id, error: { cod
93
95
  * @returns {Promise<number>}
94
96
  */
95
97
  export async function runMcpStdioBridge({
96
- url, username, signer, channel = 'mcp', expectHostKey, reconnect, timeoutMs = 15_000, maxLineBytes = 8 * 1024 * 1024, maxQueued = 200,
98
+ url, username, signer, channel = 'mcp', expectHostKey, sealSession, reconnect, timeoutMs = 15_000, maxLineBytes = 8 * 1024 * 1024, maxQueued = 200,
97
99
  input = process.stdin, output = process.stdout, errorOutput = process.stderr, clientFactory = () => new WshClient(), signalHandle = null,
98
100
  }) {
99
101
  if (typeof url !== 'string' || !url) throw new McpBridgeError('a host URL is required');
@@ -124,7 +126,7 @@ export async function runMcpStdioBridge({
124
126
  async function open() {
125
127
  const client = clientFactory();
126
128
  try {
127
- await client.connect(url, { username, signer, timeout: timeoutMs, ...(expectHostKey ? { expectHostKey } : {}) });
129
+ await client.connect(url, { username, signer, timeout: timeoutMs, ...(expectHostKey ? { expectHostKey } : {}), ...(sealSession !== undefined ? { sealSession } : {}) });
128
130
  } catch (e) {
129
131
  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
132
  }
@@ -22,6 +22,10 @@ export interface WshMemoryRpcContext {
22
22
  user: string | null;
23
23
  fingerprint: string | null;
24
24
  features: string[];
25
+ /** The capability list of the key this channel serves, or `null` for a key with none (for display: `permits` decides). */
26
+ capabilities: string[] | null;
27
+ /** Whether the key's options and capabilities allow a request such as `{ kind: 'mcp-tool', tool }`, asked afresh each call. */
28
+ permits(request: { kind: string; [field: string]: unknown }, options?: { now?: number }): boolean;
25
29
  log(line: string): void;
26
30
  [key: string]: unknown;
27
31
  }
@@ -42,7 +46,7 @@ export interface WshMemoryHostOptions {
42
46
  hostKey?: WshHostKeyOption;
43
47
  /**
44
48
  * Offer client-opened QMux data streams (default `true`). `false` serves exec output as `SessionData` instead and
45
- * offers neither `stream-announce` nor `rpc`: needed for a peer that cannot open streams, the released Rust client over
49
+ * offers no `stream-announce`, and states rpc as `rpc-virtual` (rpc rides the control plane, #191) instead of `rpc`: needed for a peer that cannot open streams, the released Rust client over
46
50
  * WebSocket (#132). Released clients state nothing a host could choose on, so this is an option, not a negotiation;
47
51
  * `accept(socket, { dataStreams })` overrides it for one connection.
48
52
  */
@@ -94,6 +98,13 @@ export interface WshMemoryHostOptions {
94
98
  targets?: Record<string, import('./host.js').WshTargetOptions>;
95
99
  /** With `targets`: an `Open`, `FileOp` or `OpenEndpoint` that names no target is refused (nothing runs on the host itself). */
96
100
  requireTarget?: boolean;
101
+ /**
102
+ * Which login names this host admits (a RegExp, or a pattern string). Default `/^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/`, the shape of an
103
+ * OS account name. A host that does not map names to OS accounts (a page, a peer named by a base64url identity hash that may start
104
+ * with a digit or `-`) can admit its own shape, e.g. `/^[A-Za-z0-9_-]{1,64}$/`. Whatever the pattern, a name is 1 to 256 characters
105
+ * with no control character, no `/` and no `\`, and the pattern may not match the empty name.
106
+ */
107
+ usernamePattern?: RegExp | string;
97
108
  onLog?: (line: string) => void;
98
109
  }
99
110
 
@@ -31,12 +31,13 @@
31
31
  import { WshClient } from './client.mjs';
32
32
  import { WebSocketTransport } from './transport-ws.mjs';
33
33
  import { createConnectionFactory } from './server/connection.mjs';
34
+ import { resolveUsernamePattern } from './server/username.mjs';
34
35
  import { buildAuthorizer, authMethods, FailureLimiter } from './server/auth.mjs';
35
- import { resolveBackends, resolveHostKey } from './host-backends.mjs';
36
+ import { resolveBackends, resolveHostKey, createRpcTable } from './host-backends.mjs';
36
37
  import { bindSocket } from './server/socket.mjs';
37
38
  import { normalizeEndpointGateway, createEndpointGatewaySession } from './server/gateway-core.mjs';
38
39
  import { CHANNEL_BINDING_KINDS } from './channel-binding.mjs';
39
- import { RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
40
+ import { RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
40
41
  import { SessionRegistry, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED } from './session-registry.mjs';
41
42
  import { validateOnShare } from './shares.mjs';
42
43
  import { validateOnRefused } from './refusal.mjs';
@@ -105,21 +106,6 @@ export function createSocketPair() {
105
106
  return [a, b];
106
107
  }
107
108
 
108
- /** Validate the `rpc` option into the table the connection handler reads (`createRpcHost` in `server/rpc.mjs` minus the Node-only built-ins). */
109
- function createRpcTable(rpc, maxMessageBytes, maxInflight) {
110
- if (typeof rpc !== 'object' || Array.isArray(rpc)) throw new TypeError('createMemoryHost: rpc must be an object of { [protocol]: handler }');
111
- if (!(maxMessageBytes >= 256)) throw new TypeError('createMemoryHost: rpcMaxMessageBytes must be at least 256');
112
- if (!Number.isSafeInteger(maxInflight) || maxInflight < 1) throw new TypeError('createMemoryHost: rpcMaxInflight must be a positive integer');
113
- const protocols = new Map();
114
- for (const [name, handler] of Object.entries(rpc)) {
115
- if (handler === undefined || handler === false || handler === null) continue;
116
- if (!RPC_PROTOCOL_NAME_RE.test(name)) throw new TypeError(`createMemoryHost: rpc protocol name ${JSON.stringify(name)} is not allowed (letters, digits, ".", "_", "-")`);
117
- if (typeof handler !== 'function') throw new TypeError(`createMemoryHost: rpc[${JSON.stringify(name)}] needs a handler function (channel, ctx) => void (the wsh-host / wsh-fs built-ins need Node; use @johnhenry/wsh/server)`);
118
- protocols.set(name, handler);
119
- }
120
- return { protocols, maxMessageBytes, maxInflight };
121
- }
122
-
123
109
  function createRegistry(sessions, log) {
124
110
  const o = sessions === true ? {} : sessions;
125
111
  if (typeof o !== 'object' || Array.isArray(o)) throw new TypeError('createMemoryHost: sessions must be true or { detachTtlMs, maxDetached, ringBytes }');
@@ -153,7 +139,7 @@ function createRegistry(sessions, log) {
153
139
  * `{ publicKey, sign(data) }`, or `true` for a fresh non-extractable key.
154
140
  * @param {boolean} [options.dataStreams=true] - Offer client-opened QMux data streams for exec output (`stream-announce`,
155
141
  * rpc). Set `false` for a peer that cannot open them -- the released Rust client over WebSocket -- so exec output rides
156
- * `SessionData` instead (and `rpc` is not offered). The released clients state nothing in their `Hello` that a host could
142
+ * `SessionData` instead (and rpc is stated as `rpc-virtual`, #191). The released clients state nothing in their `Hello` that a host could
157
143
  * key an automatic choice on, so this is an option; `accept(socket, { dataStreams })` overrides it per connection.
158
144
  * @param {{ tools?: object[] | object, client?: object, authorize?: Function, maxConcurrent?: number, timeoutMs?: number }} [options.mcp]
159
145
  * @param {Record<string, Function>} [options.extensions] - Handlers for application-defined messages, as for `createWshServer`.
@@ -194,7 +180,8 @@ function createRegistry(sessions, log) {
194
180
  * @param {(line: string) => void} [options.onLog]
195
181
  */
196
182
  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 = () => {},
197
- onShare, onRefused, targets, requireTarget } = {}) {
183
+ onShare, onRefused, targets, requireTarget, usernamePattern } = {}) {
184
+ resolveUsernamePattern(usernamePattern, 'createMemoryHost');
198
185
  validateOnShare(onShare, 'createMemoryHost');
199
186
  validateOnRefused(onRefused, 'createMemoryHost');
200
187
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
@@ -211,7 +198,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
211
198
  }
212
199
  if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createMemoryHost: extensions must be an object of handlers');
213
200
  if (typeof dataStreams !== 'boolean') throw new TypeError('createMemoryHost: dataStreams must be true or false');
214
- const rpcHost = rpc === undefined || rpc === null ? null : createRpcTable(rpc, rpcMaxMessageBytes, rpcMaxInflight);
201
+ const rpcHost = rpc === undefined || rpc === null ? null : createRpcTable(rpc, rpcMaxMessageBytes, rpcMaxInflight, 'createMemoryHost');
215
202
  const registry = sessions === undefined || sessions === null || sessions === false ? null : createRegistry(sessions, onLog);
216
203
  const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost, targets: targetTable, requireTarget: mustHaveTarget } = resolveBackends({ exec, pty, fs, mcp, targets, requireTarget });
217
204
  const hostKeyReady = hostKey === undefined || hostKey === null || hostKey === false ? Promise.resolve(null) : resolveHostKey(hostKey, 'createMemoryHost: hostKey');
@@ -231,7 +218,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
231
218
  const ready = Promise.all([buildAuthorizer(auth, { log: onLog }), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
232
219
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
233
220
  methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
234
- targets: targetTable, requireTarget: mustHaveTarget,
221
+ targets: targetTable, requireTarget: mustHaveTarget, usernamePattern,
235
222
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
236
223
  }));
237
224
  ready.catch(() => {});