@johnhenry/wsh 0.45.0 → 0.46.1

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/src/index.d.ts CHANGED
@@ -258,6 +258,16 @@ export const TARGETS_FEATURE: 'targets';
258
258
 
259
259
  /** ServerHello feature: the host serves `rpc` sessions (`openSession({ type: 'rpc', protocol })`). */
260
260
  export const RPC_FEATURE: 'rpc';
261
+ /**
262
+ * ServerHello (or `ReverseAccept`) feature (#191): the host serves rpc channels in virtual data mode (the CBOR sequence rides
263
+ * `SessionData`, inside `EncryptedFrame` on a sealed session, metered by credit). A host states this INSTEAD of `rpc` on a
264
+ * connection with no client-opened data streams. `openRpc` picks the form from what the host states.
265
+ */
266
+ export const RPC_VIRTUAL_FEATURE: 'rpc-virtual';
267
+ /** Does this feature list offer rpc in virtual data mode? */
268
+ export function rpcVirtualOffered(features?: string[]): boolean;
269
+ /** Credit, in bytes, each direction of a virtual-mode rpc channel starts with (a protocol constant). */
270
+ export const RPC_CREDIT_WINDOW: 262144;
261
271
  /** ServerHello feature prefix: one `rpc-protocol:<name>` per protocol the host serves. */
262
272
  export const RPC_PROTOCOL_PREFIX: 'rpc-protocol:';
263
273
  /** ServerHello feature prefix: `rpc-max-message:<bytes>`. */
@@ -338,6 +348,8 @@ export interface RpcChannelOptions {
338
348
  maxMessageBytes?: number;
339
349
  timeoutMs?: number;
340
350
  maxInflight?: number;
351
+ /** For a metered transport (virtual-mode rpc): called with the received bytes taken in and dispatched, so credit can be returned. */
352
+ onConsumed?: (bytes: number) => void;
341
353
  }
342
354
 
343
355
  /**
@@ -1826,6 +1838,46 @@ export interface WshHostKey {
1826
1838
  export type WshHostKeyErrorCode =
1827
1839
  | 'HOST_KEY_MISSING' | 'HOST_KEY_INVALID' | 'HOST_KEY_MISMATCH' | 'HOST_KEY_UNKNOWN' | 'HOST_KEY_REJECTED';
1828
1840
 
1841
+ /** Stable `code` values of `WshAuthError` and `WshConnectionError`. */
1842
+ export const WSH_ERROR_CODES: Readonly<{
1843
+ AUTH_FAILED: 'AUTH_FAILED';
1844
+ AUTH_UNAUTHORIZED: 'AUTH_UNAUTHORIZED';
1845
+ AUTH_BAD_SIGNATURE: 'AUTH_BAD_SIGNATURE';
1846
+ AUTH_METHOD_DISABLED: 'AUTH_METHOD_DISABLED';
1847
+ AUTH_RATE_LIMITED: 'AUTH_RATE_LIMITED';
1848
+ AUTH_KEY_EXPIRED: 'AUTH_KEY_EXPIRED';
1849
+ AUTH_BINDING_REQUIRED: 'AUTH_BINDING_REQUIRED';
1850
+ AUTH_NOT_SEALED: 'AUTH_NOT_SEALED';
1851
+ AUTH_BAD_REQUEST: 'AUTH_BAD_REQUEST';
1852
+ CONNECTION_FAILED: 'CONNECTION_FAILED';
1853
+ HANDSHAKE_TIMEOUT: 'HANDSHAKE_TIMEOUT';
1854
+ }>;
1855
+ export type WshAuthErrorCode = Exclude<keyof typeof WSH_ERROR_CODES, 'CONNECTION_FAILED' | 'HANDSHAKE_TIMEOUT'>;
1856
+
1857
+ /**
1858
+ * Thrown by `connect()` when the host refuses the login. The message is `Authentication failed: <reason>`, as it always was.
1859
+ * `refusal` is the reason the host reports to its own `onRefused` (`REFUSAL_REASONS` of `@johnhenry/wsh/host`), recognised from the
1860
+ * wording of the hosts this package ships (the wire carries the text only); `null` for a host that words it otherwise.
1861
+ */
1862
+ export class WshAuthError extends Error {
1863
+ constructor(reason: string, message?: string);
1864
+ readonly code: WshAuthErrorCode;
1865
+ /** What the host said, verbatim. */
1866
+ readonly reason: string;
1867
+ readonly refusal: 'unauthorized' | 'bad-signature' | 'method-disabled' | 'rate-limited' | 'key-expired' | 'binding-required' | 'not-sealed' | 'bad-request' | null;
1868
+ }
1869
+
1870
+ /** Thrown by `connect()` when no transport could be opened (`CONNECTION_FAILED`, with `attempts`) or the host did not answer a login step in time (`HANDSHAKE_TIMEOUT`). */
1871
+ export class WshConnectionError extends Error {
1872
+ constructor(code: 'CONNECTION_FAILED' | 'HANDSHAKE_TIMEOUT', message: string, details?: { attempts?: string[]; cause?: unknown });
1873
+ readonly code: 'CONNECTION_FAILED' | 'HANDSHAKE_TIMEOUT';
1874
+ /** One line per transport tried. */
1875
+ readonly attempts?: string[];
1876
+ }
1877
+
1878
+ /** Map an `AuthFail` reason to the stable code and `onRefused` reason (`AUTH_FAILED` / `null` when it is not recognised). */
1879
+ export function classifyAuthRefusal(reason: unknown): { code: WshAuthErrorCode; refusal: WshAuthError['refusal'] };
1880
+
1829
1881
  /** Thrown by `connect()` when the host key fails the caller's policy. No credential has been sent. */
1830
1882
  export class HostKeyError extends Error {
1831
1883
  constructor(code: WshHostKeyErrorCode, message: string, details?: { expected?: string; actual?: string });
@@ -2247,6 +2299,20 @@ export class WshClient {
2247
2299
  /** Called on connection-level errors. */
2248
2300
  onError: ((err: Error) => void) | null;
2249
2301
 
2302
+ /**
2303
+ * Called when a sealed session or bridge drops a message it does not accept (a plain message where only sealed frames are
2304
+ * heard, or a bridge frame that does not open). The connection carries on, so this is not `onError`; the drops are also
2305
+ * counted in `droppedMessages`. Nothing is written to the console.
2306
+ */
2307
+ onDrop: ((drop: {
2308
+ reason: 'plaintext-on-sealed-session' | 'plaintext-before-seal' | 'plaintext-on-sealed-bridge' | 'unopenable-bridge-frame';
2309
+ messageType?: number;
2310
+ detail?: string;
2311
+ }) => void) | null;
2312
+
2313
+ /** How many messages a sealed session or bridge has dropped: plain ones, and bridge frames that did not open. */
2314
+ readonly droppedMessages: { plaintext: number; unopened: number };
2315
+
2250
2316
  /** Called when a reverse-connect request arrives (reverse mode only). */
2251
2317
  onReverseConnect: ((msg: WshMessage) => void) | null;
2252
2318
 
package/src/index.mjs CHANGED
@@ -102,6 +102,9 @@ export { WshKeyStore } from './keystore.mjs';
102
102
  export { WshKnownHosts } from './known-hosts.mjs';
103
103
  export { HostKeyError } from './host-key.mjs';
104
104
 
105
+ // Typed refusals: a refused login, a failed connection
106
+ export { WshAuthError, WshConnectionError, WSH_ERROR_CODES, classifyAuthRefusal } from './errors.mjs';
107
+
105
108
  // File transfer
106
109
  export { WshFileTransfer } from './file-transfer.mjs';
107
110
 
@@ -115,5 +118,7 @@ export { WshMcpBridge } from './mcp-bridge.mjs';
115
118
  export {
116
119
  RpcChannel, RpcError, CborSequenceDecoder, RPC_ERROR, RPC_FEATURE, RPC_PROTOCOL_PREFIX, RPC_MAX_MESSAGE_PREFIX,
117
120
  RPC_DEFAULT_MAX_MESSAGE, RPC_PROTOCOL_NAME_RE, rpcProtocolFeature, parseRpcFeatures,
121
+ RPC_VIRTUAL_FEATURE, rpcVirtualOffered,
118
122
  } from './rpc.mjs';
123
+ export { RPC_CREDIT_WINDOW } from './rpc-virtual.mjs';
119
124
  export { RpcMcpTransport, mcpClientTransport, mcpServerTransport } from './rpc-mcp.mjs';
@@ -337,7 +337,9 @@ function capabilityRefusal(p, req) {
337
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
338
  // FileOp and the file channels, which are checked per operation).
339
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 === '*'));
340
+ // A handler that narrows by capability itself (`capabilityScoped`, req.scoped) may be opened by a key that names any
341
+ // tool; every other `mcp` handler would show a `mcp:search` key all of its tools, so it still needs `mcp:*`.
342
+ else if (proto === 'mcp') r = req.scoped ? need('mcp:<tool>', has('mcp')) : need('mcp:*', caps.some((c) => c.kind === 'mcp' && c.name === '*'));
341
343
  else r = need(`rpc:${proto}`, caps.some((c) => c.kind === 'rpc' && c.name === proto));
342
344
  } else r = need(req.channel, false);
343
345
  return r ?? target();
@@ -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(() => {});