@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.
package/bin/wsh-mcp.mjs CHANGED
@@ -16,6 +16,7 @@ Usage: wsh-mcp [options] [user@]<url>
16
16
  -l, --user NAME login name (default: the user@ part of the URL, else $WSH_USER, $USER, or the OS user)
17
17
  -i, --identity FILE Ed25519 private key (default: ~/.wsh/keys/default.pem, the key \`wsh keygen\` makes)
18
18
  --channel NAME the rpc channel to open (default: mcp)
19
+ --sealed seal the whole session end to end and refuse a host that cannot (a host behind a relay, a page); key login only
19
20
  --host-key KEY pin the host: a hex fingerprint, or an ssh-ed25519 line (default: not pinned, with a warning)
20
21
  --no-reconnect exit when the connection is lost instead of reconnecting
21
22
  --reconnect-attempts N attempts before giving up (default: 5, from 500 ms, doubling)
@@ -44,6 +45,7 @@ try {
44
45
  user: { type: 'string', short: 'l' },
45
46
  identity: { type: 'string', short: 'i' },
46
47
  channel: { type: 'string' },
48
+ sealed: { type: 'boolean' },
47
49
  'host-key': { type: 'string' },
48
50
  'no-reconnect': { type: 'boolean' },
49
51
  'reconnect-attempts': { type: 'string' },
@@ -81,7 +83,7 @@ try {
81
83
  const signer = await loadIdentity(values.identity ?? defaultIdentityPath());
82
84
  for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, () => { void handle.close?.(); });
83
85
  exitCode = await runMcpStdioBridge({
84
- url, username, signer, channel: values.channel, expectHostKey: values['host-key'], timeoutMs,
86
+ url, username, signer, channel: values.channel, expectHostKey: values['host-key'], sealSession: values.sealed ? true : undefined, timeoutMs,
85
87
  reconnect: values['no-reconnect'] ? false : (attempts === undefined ? undefined : { attempts }),
86
88
  signalHandle: handle,
87
89
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.45.0",
3
+ "version": "0.46.0",
4
4
  "description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -29,6 +29,18 @@
29
29
  "types": "./src/reverse-host.d.ts",
30
30
  "import": "./src/reverse-host.mjs"
31
31
  },
32
+ "./page": {
33
+ "types": "./src/page-host.d.ts",
34
+ "import": "./src/page-host.mjs"
35
+ },
36
+ "./objects": {
37
+ "types": "./src/objects.d.ts",
38
+ "import": "./src/objects.mjs"
39
+ },
40
+ "./testing": {
41
+ "types": "./src/testing.d.ts",
42
+ "import": "./src/testing.mjs"
43
+ },
32
44
  "./mcp-stdio": {
33
45
  "types": "./src/mcp-stdio.d.ts",
34
46
  "import": "./src/mcp-stdio.mjs"
package/src/cbor.mjs CHANGED
@@ -54,11 +54,13 @@ function encodeValue(value, parts) {
54
54
  return;
55
55
  }
56
56
  if (typeof value === 'number') {
57
- if (Number.isInteger(value)) {
58
- if (value >= 0) {
59
- parts.push(encodeHead(MT_UNSIGNED, value));
57
+ // An integral double within the 64-bit ranges is an integer (exactly: BigInt past 2^53); anything else -- a fraction, NaN,
58
+ // an infinity, -0, or an integer at or beyond 2^64 in magnitude -- is a float64, so every finite double round-trips.
59
+ if (Number.isInteger(value) && !Object.is(value, -0) && value >= -TWO_64 && value < TWO_64) {
60
+ if (Number.isSafeInteger(value)) {
61
+ parts.push(value >= 0 ? encodeHead(MT_UNSIGNED, value) : encodeHead(MT_NEGATIVE, -1 - value));
60
62
  } else {
61
- parts.push(encodeHead(MT_NEGATIVE, -1 - value));
63
+ parts.push(value >= 0 ? encodeHead64(MT_UNSIGNED, BigInt(value)) : encodeHead64(MT_NEGATIVE, -1n - BigInt(value)));
62
64
  }
63
65
  } else {
64
66
  // float64
@@ -104,6 +106,17 @@ function encodeValue(value, parts) {
104
106
  throw new Error(`cborEncode: unsupported type ${typeof value}`);
105
107
  }
106
108
 
109
+ const TWO_64 = 2 ** 64;
110
+
111
+ /** An 8-byte head for a value that is beyond the safe-integer range (exact, from a BigInt in 0 .. 2^64-1). */
112
+ function encodeHead64(majorType, big) {
113
+ const buf = new ArrayBuffer(9);
114
+ const view = new DataView(buf);
115
+ view.setUint8(0, (majorType << 5) | 27);
116
+ view.setBigUint64(1, big);
117
+ return new Uint8Array(buf);
118
+ }
119
+
107
120
  function encodeHead(majorType, value) {
108
121
  const mt = majorType << 5;
109
122
  if (value < 24) {
@@ -159,7 +172,15 @@ function decodeValue(state) {
159
172
 
160
173
  switch (mt) {
161
174
  case MT_UNSIGNED: return decodeUint(state, ai);
162
- case MT_NEGATIVE: return -1 - decodeUint(state, ai);
175
+ case MT_NEGATIVE: {
176
+ if (ai === 27) {
177
+ // Past 2^53 `-1 - n` would round twice (n, then the sum): take the nearest double of the exact value once.
178
+ const view = new DataView(state.data.buffer, state.data.byteOffset + state.offset, 8);
179
+ state.offset += 8;
180
+ return Number(-1n - view.getBigUint64(0));
181
+ }
182
+ return -1 - decodeUint(state, ai);
183
+ }
163
184
  case MT_BYTES: {
164
185
  if (ai === BREAK) return decodeIndefiniteBytes(state);
165
186
  const len = decodeUint(state, ai);
@@ -187,7 +208,7 @@ function decodeValue(state) {
187
208
  const obj = {};
188
209
  for (let i = 0; i < len; i++) {
189
210
  const key = decodeValue(state);
190
- obj[key] = decodeValue(state);
211
+ setOwn(obj, key, decodeValue(state));
191
212
  }
192
213
  return obj;
193
214
  }
@@ -260,11 +281,23 @@ function decodeIndefiniteMap(state) {
260
281
  const obj = {};
261
282
  while (!consumeBreak(state)) {
262
283
  const key = decodeValue(state);
263
- obj[key] = decodeValue(state);
284
+ setOwn(obj, key, decodeValue(state));
264
285
  }
265
286
  return obj;
266
287
  }
267
288
 
289
+ /**
290
+ * Set a decoded map entry as plain own data. A key is untrusted wire input: `obj['__proto__'] = value` would run the
291
+ * prototype setter and change what the object inherits, so that one key is defined as an own property instead (the key is
292
+ * coerced to a string first, because `obj[['__proto__']]` reaches the same setter). Every other key, `constructor` and
293
+ * `prototype` included, is an ordinary assignment: it creates an own property and inherits no setter.
294
+ */
295
+ function setOwn(obj, key, value) {
296
+ const name = typeof key === 'string' ? key : String(key);
297
+ if (name === '__proto__') Object.defineProperty(obj, name, { value, writable: true, enumerable: true, configurable: true });
298
+ else obj[name] = value;
299
+ }
300
+
268
301
  function consumeBreak(state) {
269
302
  if (state.offset >= state.data.length) {
270
303
  throw new Error('cborDecode: unexpected end in indefinite value');
package/src/client.mjs CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  detach as detachMsg,
38
38
  sessionListRequest as sessionListRequestMsg,
39
39
  listTargets as listTargetsMsg,
40
+ gatewayCredit as gatewayCreditMsg,
40
41
  sessionGrant as sessionGrantMsg, sessionRevoke as sessionRevokeMsg,
41
42
  isRelayForwardable,
42
43
  } from './messages.mjs';
@@ -49,15 +50,20 @@ import { WshSession } from './session.mjs';
49
50
  import { GatewayConnections } from './gateway-client.mjs';
50
51
  import { GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
51
52
  import { GATEWAY_DATAGRAM_FEATURE } from './gateway-datagram.mjs';
53
+ import { RpcCreditLink, rpcCreditId, rpcChannelOfCredit } from './rpc-virtual.mjs';
52
54
  import { cborDecode, cborEncode } from './cbor.mjs';
53
55
  import {
54
- RpcChannel, RpcError, RPC_ERROR, RPC_FEATURE, RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE,
56
+ RpcChannel, RpcError, RPC_ERROR, RPC_FEATURE, RPC_VIRTUAL_FEATURE, RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE,
55
57
  rpcProtocolFeature, parseRpcFeatures,
56
58
  } from './rpc.mjs';
57
59
  import {
58
60
  HostKeyError, newHostKeyNonce, hostKeyProofMessage, findHostKeyAdvert,
59
61
  HOST_KEY_NONCE_PREFIX,
60
62
  } from './host-key.mjs';
63
+ import { WshAuthError, WshConnectionError } from './errors.mjs';
64
+
65
+ /** The error of a login step the host did not answer in time (same message as ever, now with a code). */
66
+ const handshakeTimeout = (message) => new WshConnectionError('HANDSHAKE_TIMEOUT', message);
61
67
  import { verify as verifySignature, exportPublicKeySSH, parseSSHPublicKey, extractRawFromSSHWire } from './auth.mjs';
62
68
 
63
69
  // ── Client states ─────────────────────────────────────────────────────
@@ -314,6 +320,9 @@ export class WshClient {
314
320
  /** @type {Map<number, WshSession>} Active sessions keyed by channel ID. */
315
321
  #sessions = new Map();
316
322
 
323
+ /** @type {Map<number, RpcCreditLink>} The credit link of each rpc channel in virtual data mode (#191), by channel ID. */
324
+ #rpcLinks = new Map();
325
+
317
326
  /**
318
327
  * In-flight attachSession()/resumeSession() calls awaiting the Presence
319
328
  * that answers them. Like #pendingOpens, matched synchronously in
@@ -419,6 +428,29 @@ export class WshClient {
419
428
  /** Called on connection-level errors. */
420
429
  onError = null;
421
430
 
431
+ /**
432
+ * Called when the client hears a message a sealed session or sealed bridge does not accept and drops it: a plain message
433
+ * where only sealed frames are heard (a relay in the middle can write any plain message), or a bridge frame that does not
434
+ * open. Not an error of the connection (the session carries on), so not `onError`; also counted in `droppedMessages`.
435
+ * Nothing is written to the console. A handler that throws is ignored.
436
+ * @type {((drop: { reason: 'plaintext-on-sealed-session' | 'plaintext-before-seal' | 'plaintext-on-sealed-bridge' | 'unopenable-bridge-frame', messageType?: number, detail?: string }) => void) | null}
437
+ */
438
+ onDrop = null;
439
+
440
+ #droppedPlaintext = 0;
441
+ #droppedUnopened = 0;
442
+
443
+ /** How many messages this client has dropped because a sealed session or bridge did not accept them. */
444
+ get droppedMessages() {
445
+ return { plaintext: this.#droppedPlaintext, unopened: this.#droppedUnopened };
446
+ }
447
+
448
+ /** @param {{ reason: string, messageType?: number, detail?: string }} drop */
449
+ #countDrop(drop) {
450
+ if (drop.reason === 'unopenable-bridge-frame') this.#droppedUnopened++; else this.#droppedPlaintext++;
451
+ try { this.onDrop?.(drop); } catch { /* a handler's bug does not decide what the client does */ }
452
+ }
453
+
422
454
  /**
423
455
  * Called when a reverse-connect request arrives (reverse mode only).
424
456
  * @type {function(object): void|null}
@@ -657,7 +689,7 @@ export class WshClient {
657
689
  this.#sealState = null;
658
690
  this.#sessionSeal = null;
659
691
  this.#peerProof = null;
660
- this.#sessions.clear();
692
+ this.#sessions.clear(); this.#rpcLinks.clear();
661
693
  this.#channelCounter = 0;
662
694
  this.#waiters.clear();
663
695
  this.#sessionId = null;
@@ -683,11 +715,11 @@ export class WshClient {
683
715
  const firstResponse = await this.#waitForMessage(
684
716
  [MSG.SERVER_HELLO, MSG.CHALLENGE, MSG.AUTH_FAIL],
685
717
  timeout,
686
- 'Auth handshake timed out waiting for server response'
718
+ handshakeTimeout('Auth handshake timed out waiting for server response')
687
719
  );
688
720
 
689
721
  if (firstResponse.type === MSG.AUTH_FAIL) {
690
- throw new Error(`Authentication failed: ${firstResponse.reason || 'unknown'}`);
722
+ throw new WshAuthError(firstResponse.reason || 'unknown');
691
723
  }
692
724
 
693
725
  let tempSessionId = null;
@@ -704,7 +736,7 @@ export class WshClient {
704
736
  // Challenge right behind ServerHello, and a message nobody is waiting
705
737
  // for yet is dropped.
706
738
  const challengeWait = authMethod === AUTH_METHOD.PUBKEY
707
- ? this.#waitForMessage([MSG.CHALLENGE, MSG.AUTH_OK], timeout, 'Auth handshake timed out waiting for challenge')
739
+ ? this.#waitForMessage([MSG.CHALLENGE, MSG.AUTH_OK], timeout, handshakeTimeout('Auth handshake timed out waiting for challenge'))
708
740
  : null;
709
741
  challengeWait?.catch(() => {});
710
742
  await this.#verifyHostKey(firstResponse, hostCtx);
@@ -786,11 +818,11 @@ export class WshClient {
786
818
  const authResult = await this.#waitForMessage(
787
819
  [MSG.AUTH_OK, MSG.AUTH_FAIL],
788
820
  timeout,
789
- 'Auth handshake timed out waiting for auth result'
821
+ handshakeTimeout('Auth handshake timed out waiting for auth result')
790
822
  );
791
823
 
792
824
  if (authResult.type === MSG.AUTH_FAIL) {
793
- throw new Error(`Authentication failed: ${authResult.reason || 'rejected'}`);
825
+ throw new WshAuthError(authResult.reason || 'rejected');
794
826
  }
795
827
 
796
828
  this.#sessionId = authResult.session_id || tempSessionId;
@@ -889,7 +921,7 @@ export class WshClient {
889
921
  if (typeof protocol !== 'string' || !RPC_PROTOCOL_NAME_RE.test(protocol)) {
890
922
  throw new RpcError(RPC_ERROR.INVALID_PARAMS, 'openSession({ type: "rpc" }) needs a protocol name', undefined, 'INVALID_PROTOCOL');
891
923
  }
892
- if (!this.hasFeature(RPC_FEATURE)) {
924
+ if (!this.hasFeature(RPC_FEATURE) && !this.hasFeature(RPC_VIRTUAL_FEATURE)) {
893
925
  throw new RpcError(RPC_ERROR.UNSUPPORTED_PROTOCOL, `UNSUPPORTED_PROTOCOL: this host does not advertise "${RPC_FEATURE}" channels (cannot open "${protocol}")`, undefined, 'UNSUPPORTED_PROTOCOL');
894
926
  }
895
927
  if (!this.hasFeature(rpcProtocolFeature(protocol))) {
@@ -909,11 +941,32 @@ export class WshClient {
909
941
  */
910
942
  async openRpc(protocol, { timeoutMs, openTimeout = DEFAULT_OPEN_TIMEOUT } = {}) {
911
943
  this.#assertAuthenticated('openRpc');
912
- const { maxMessageBytes } = parseRpcFeatures(this.#serverFeatures);
944
+ // The limit is the host's own: behind a relay it is what the host reported in `ReverseAccept`, not the relay's.
945
+ const { maxMessageBytes } = parseRpcFeatures(this.#bridgedFeatures ?? this.#serverFeatures);
946
+ // The mode follows what the host states: `rpc` is a data stream, `rpc-virtual` rides the control plane (#191).
947
+ const virtual = !this.hasFeature(RPC_FEATURE) && this.hasFeature(RPC_VIRTUAL_FEATURE);
913
948
  let channel = null;
914
949
  const session = await this.openSession({
915
950
  type: 'rpc', protocol, timeout: openTimeout,
916
951
  attach: (s) => {
952
+ if (virtual) {
953
+ const link = new RpcCreditLink({
954
+ sendData: (bytes) => s.write(bytes),
955
+ sendCredit: (n) => this.sendRelayControl(gatewayCreditMsg({ gatewayId: rpcCreditId(s.channelId), bytes: n })),
956
+ onViolation: () => { void channel?.close('credit-violation'); },
957
+ });
958
+ this.#rpcLinks.set(s.channelId, link);
959
+ channel = new RpcChannel({
960
+ maxMessageBytes: maxMessageBytes ?? RPC_DEFAULT_MAX_MESSAGE,
961
+ timeoutMs,
962
+ write: (bytes) => link.write(bytes),
963
+ close: async () => { link.close(); await s.close(); },
964
+ onConsumed: (n) => link.consumed(n),
965
+ });
966
+ s.onData = (bytes) => { if (link.receive(bytes.length)) channel.feed(bytes); };
967
+ s.onClose = (err) => { link.close(); this.#rpcLinks.delete(s.channelId); channel.handleClose(err ? 'stream-error' : 'channel-closed'); };
968
+ return;
969
+ }
917
970
  channel = new RpcChannel({
918
971
  maxMessageBytes: maxMessageBytes ?? RPC_DEFAULT_MAX_MESSAGE,
919
972
  timeoutMs,
@@ -1166,7 +1219,7 @@ export class WshClient {
1166
1219
  closePromises.push(session.close().catch(() => {}));
1167
1220
  }
1168
1221
  await Promise.allSettled(closePromises);
1169
- this.#sessions.clear();
1222
+ this.#sessions.clear(); this.#rpcLinks.clear();
1170
1223
 
1171
1224
  // Close the transport.
1172
1225
  if (this.#transport) {
@@ -2708,7 +2761,7 @@ export class WshClient {
2708
2761
  }
2709
2762
  }
2710
2763
 
2711
- throw new Error(`Connection failed across transports (${errors.join('; ')})`);
2764
+ throw new WshConnectionError('CONNECTION_FAILED', `Connection failed across transports (${errors.join('; ')})`, { attempts: errors });
2712
2765
  }
2713
2766
 
2714
2767
  /**
@@ -2990,7 +3043,7 @@ export class WshClient {
2990
3043
  if (!seal || msg.type === MSG.PING || msg.type === MSG.PONG) { this.#handleControl(msg); return; }
2991
3044
  if (seal.bridge) {
2992
3045
  if (!seal.bridge.isFrame(msg)) {
2993
- console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) on a sealed session`);
3046
+ this.#countDrop({ reason: 'plaintext-on-sealed-session', messageType: msg.type });
2994
3047
  return;
2995
3048
  }
2996
3049
  seal.bridge.open(msg).then(
@@ -3000,7 +3053,7 @@ export class WshClient {
3000
3053
  return;
3001
3054
  }
3002
3055
  if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === seal.sessionId) { this.#handleControl(msg); return; }
3003
- console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) before the session is sealed`);
3056
+ this.#countDrop({ reason: 'plaintext-before-seal', messageType: msg.type });
3004
3057
  }
3005
3058
 
3006
3059
  #sealedFrameFailed(seal, err) {
@@ -3046,11 +3099,11 @@ export class WshClient {
3046
3099
  const firstResponse = await this.#waitForMessage(
3047
3100
  [MSG.SERVER_HELLO, MSG.CHALLENGE, MSG.AUTH_FAIL],
3048
3101
  timeout,
3049
- 'Auth handshake timed out'
3102
+ handshakeTimeout('Auth handshake timed out')
3050
3103
  );
3051
3104
 
3052
3105
  if (firstResponse.type === MSG.AUTH_FAIL) {
3053
- throw new Error(`Authentication failed: ${firstResponse.reason || 'unknown'}`);
3106
+ throw new WshAuthError(firstResponse.reason || 'unknown');
3054
3107
  }
3055
3108
 
3056
3109
  let tempSessionId = null;
@@ -3120,7 +3173,7 @@ export class WshClient {
3120
3173
  );
3121
3174
 
3122
3175
  if (authResult.type === MSG.AUTH_FAIL) {
3123
- throw new Error(`Authentication failed: ${authResult.reason || 'rejected'}`);
3176
+ throw new WshAuthError(authResult.reason || 'rejected');
3124
3177
  }
3125
3178
 
3126
3179
  this.#sessionId = authResult.session_id || tempSessionId;
@@ -3180,12 +3233,12 @@ export class WshClient {
3180
3233
  if (sealState.bridge?.isFrame(inner)) {
3181
3234
  sealState.bridge.open(inner)
3182
3235
  .then((opened) => this.#handleControl(opened, msg.from_fingerprint))
3183
- .catch((err) => console.warn('[wsh:client] dropping a sealed frame:', err.message));
3236
+ .catch((err) => this.#countDrop({ reason: 'unopenable-bridge-frame', detail: err.message }));
3184
3237
  return;
3185
3238
  }
3186
3239
  const setup = !sealState.bridge && inner.type === MSG.KEY_EXCHANGE && inner.session_id === sealState.sessionId;
3187
3240
  if (!setup) {
3188
- console.warn('[wsh:client] dropping a plaintext message on a sealed bridge');
3241
+ this.#countDrop({ reason: 'plaintext-on-sealed-bridge', messageType: inner.type });
3189
3242
  return;
3190
3243
  }
3191
3244
  }
@@ -3332,6 +3385,12 @@ export class WshClient {
3332
3385
  }
3333
3386
  }
3334
3387
 
3388
+ // Credit for an rpc channel in virtual data mode (#191) is a GatewayCredit in a number space of its own.
3389
+ if (type === MSG.GATEWAY_CREDIT && rpcChannelOfCredit(msg.gateway_id) !== undefined) {
3390
+ this.#rpcLinks.get(rpcChannelOfCredit(msg.gateway_id))?.grant(msg.bytes);
3391
+ return;
3392
+ }
3393
+
3335
3394
  // Route gateway messages (0x70–0x7f) to the gateway handler.
3336
3395
  if (type >= 0x70 && type <= 0x7f) {
3337
3396
  // Connections opened through openUnix()/openEndpoint()/openTcp()/listenUnix() own their ids.
@@ -3500,7 +3559,7 @@ export class WshClient {
3500
3559
  for (const session of this.#sessions.values()) {
3501
3560
  session._handleControlMessage({ type: MSG.CLOSE });
3502
3561
  }
3503
- this.#sessions.clear();
3562
+ this.#sessions.clear(); this.#rpcLinks.clear();
3504
3563
 
3505
3564
  try {
3506
3565
  this.onClose?.();
@@ -3535,7 +3594,7 @@ export class WshClient {
3535
3594
  // Remove this waiter.
3536
3595
  this.#removeWaiter(key, waiter);
3537
3596
  signal?.removeEventListener('abort', onAbort);
3538
- reject(new Error(timeoutMessage));
3597
+ reject(timeoutMessage instanceof Error ? timeoutMessage : new Error(timeoutMessage));
3539
3598
  }, timeout);
3540
3599
  const onAbort = () => {
3541
3600
  clearTimeout(timer);
package/src/errors.mjs ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Typed errors for a refused login or a failed connection, so a caller branches on a stable `code` instead of matching
3
+ * message text. The messages are unchanged (`Authentication failed: <host's reason>`, `Connection failed across transports (...)`,
4
+ * `Auth handshake timed out ...`): code that matched them keeps working, and `HostKeyError` (`./host-key.mjs`) is the same
5
+ * idea for a refused host key. Browser-safe.
6
+ *
7
+ * The wire carries only the host's human `reason` in `AuthFail`; it does not carry the machine code the host reports to its own
8
+ * `onRefused`. So `refusal` here is derived from the reason text of the hosts this repository ships (the Node host and the
9
+ * Rust `wsh-server`), checked against the Node host's `onRefused` reasons by a test; a host that words its refusal otherwise
10
+ * gives `AUTH_FAILED` with `refusal: null` and the text in `reason`.
11
+ */
12
+
13
+ export const WSH_ERROR_CODES = Object.freeze({
14
+ /** The host refused the login and the client could not tell why from its words. */
15
+ AUTH_FAILED: 'AUTH_FAILED',
16
+ /** A key the host does not allow, or a wrong password. (`onRefused` reason `unauthorized`.) */
17
+ AUTH_UNAUTHORIZED: 'AUTH_UNAUTHORIZED',
18
+ AUTH_BAD_SIGNATURE: 'AUTH_BAD_SIGNATURE',
19
+ /** The login method (password or key) is not on at the host. */
20
+ AUTH_METHOD_DISABLED: 'AUTH_METHOD_DISABLED',
21
+ AUTH_RATE_LIMITED: 'AUTH_RATE_LIMITED',
22
+ AUTH_KEY_EXPIRED: 'AUTH_KEY_EXPIRED',
23
+ AUTH_BINDING_REQUIRED: 'AUTH_BINDING_REQUIRED',
24
+ AUTH_NOT_SEALED: 'AUTH_NOT_SEALED',
25
+ /** A malformed login: a bad username, an unsupported method, a missing field. */
26
+ AUTH_BAD_REQUEST: 'AUTH_BAD_REQUEST',
27
+ /** No transport could be opened. */
28
+ CONNECTION_FAILED: 'CONNECTION_FAILED',
29
+ /** The host did not answer a step of the login in time. */
30
+ HANDSHAKE_TIMEOUT: 'HANDSHAKE_TIMEOUT',
31
+ });
32
+
33
+ /** Reason text of the shipped hosts, mapped to the `onRefused` reason codes (`REFUSAL_REASONS`). Order matters: first match. */
34
+ const REFUSAL_PATTERNS = [
35
+ ['key-expired', /\bexpired\b/i],
36
+ ['binding-required', /channel binding required/i],
37
+ ['not-sealed', /sealed session/i],
38
+ ['rate-limited', /too many (failed )?(auth )?attempts|rate limited/i],
39
+ ['method-disabled', /auth(entication)? (is )?(not enabled|disabled)/i],
40
+ ['bad-signature', /signature (does not verify|verification failed)/i],
41
+ ['unauthorized', /^(key not authorized|authentication failed|invalid password)$/i],
42
+ ['bad-request', /^bad username|^unsupported auth method|^expected (a |an )?(pubkey|password )?auth|^malformed|^missing /i],
43
+ ];
44
+
45
+ /**
46
+ * @param {unknown} reason the `reason` of an `AuthFail`
47
+ * @returns {{ code: string, refusal: string | null }}
48
+ */
49
+ export function classifyAuthRefusal(reason) {
50
+ if (typeof reason === 'string') {
51
+ for (const [refusal, re] of REFUSAL_PATTERNS) {
52
+ if (re.test(reason.trim())) return { code: `AUTH_${refusal.toUpperCase().replace(/-/g, '_')}`, refusal };
53
+ }
54
+ }
55
+ return { code: WSH_ERROR_CODES.AUTH_FAILED, refusal: null };
56
+ }
57
+
58
+ /** The host refused the login (`AuthFail`). No credential beyond what the login itself sent was exposed to anyone else. */
59
+ export class WshAuthError extends Error {
60
+ /**
61
+ * @param {string} reason what the host said
62
+ * @param {string} [message] default `Authentication failed: <reason>`
63
+ */
64
+ constructor(reason, message) {
65
+ super(message ?? `Authentication failed: ${reason}`);
66
+ this.name = 'WshAuthError';
67
+ const { code, refusal } = classifyAuthRefusal(reason);
68
+ /** A `WSH_ERROR_CODES` value starting `AUTH_`. */
69
+ this.code = code;
70
+ /** What the host said, verbatim. */
71
+ this.reason = reason;
72
+ /** The `onRefused` reason code (`REFUSAL_REASONS`) this corresponds to, or null when the wording is not recognised. */
73
+ this.refusal = refusal;
74
+ }
75
+ }
76
+
77
+ /** A connection could not be made or a step of the handshake did not complete. */
78
+ export class WshConnectionError extends Error {
79
+ /**
80
+ * @param {'CONNECTION_FAILED' | 'HANDSHAKE_TIMEOUT'} code
81
+ * @param {string} message
82
+ * @param {{ attempts?: string[], cause?: unknown }} [details]
83
+ */
84
+ constructor(code, message, details = {}) {
85
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
86
+ this.name = 'WshConnectionError';
87
+ this.code = code;
88
+ if (details.attempts) /** One line per transport tried (`wt: ...`, `ws: ...`). */ this.attempts = details.attempts;
89
+ }
90
+ }
@@ -8,6 +8,7 @@ import { normalizePty } from './server/pty.mjs';
8
8
  import { createMcpHost } from './server/mcp.mjs';
9
9
  import { normalizeEndpoints } from './server/gateway-core.mjs';
10
10
  import { DEFAULT_MAX_FILE_BYTES } from './server/constants.mjs';
11
+ import { RPC_PROTOCOL_NAME_RE } from './rpc.mjs';
11
12
  import { generateKeyPair, resolveSigner, fingerprint, exportPublicKeySSH, importPublicKeyRaw } from './auth.mjs';
12
13
 
13
14
  /** The operations a file backend must have (`openRange` is optional: only the `wsh-fs` rpc built-in, which needs Node, reads it). */
@@ -52,6 +53,28 @@ export function normalizeFileBackend(fs, who = 'fs') {
52
53
  return files;
53
54
  }
54
55
 
56
+ /**
57
+ * Validate an `rpc` option into the table the connection handler reads: `{ protocols, maxMessageBytes, maxInflight }`
58
+ * (`createRpcHost` in `server/rpc.mjs` is this plus the Node-only built-ins). Handlers only: `wsh-host` and `wsh-fs` need Node.
59
+ * @param {Record<string, Function | false | null | undefined>} rpc
60
+ * @param {number} maxMessageBytes
61
+ * @param {number} maxInflight
62
+ * @param {string} [who] - the host's name in error messages
63
+ */
64
+ export function createRpcTable(rpc, maxMessageBytes, maxInflight, who = 'createMemoryHost') {
65
+ if (!rpc || typeof rpc !== 'object' || Array.isArray(rpc)) throw new TypeError(`${who}: rpc must be an object of { [protocol]: handler }`);
66
+ if (!(maxMessageBytes >= 256)) throw new TypeError(`${who}: rpcMaxMessageBytes must be at least 256`);
67
+ if (!Number.isSafeInteger(maxInflight) || maxInflight < 1) throw new TypeError(`${who}: rpcMaxInflight must be a positive integer`);
68
+ const protocols = new Map();
69
+ for (const [name, handler] of Object.entries(rpc)) {
70
+ if (handler === undefined || handler === false || handler === null) continue;
71
+ if (!RPC_PROTOCOL_NAME_RE.test(name)) throw new TypeError(`${who}: rpc protocol name ${JSON.stringify(name)} is not allowed (letters, digits, ".", "_", "-")`);
72
+ if (typeof handler !== 'function') throw new TypeError(`${who}: rpc[${JSON.stringify(name)}] needs a handler function (channel, ctx) => void (the wsh-host / wsh-fs built-ins need Node; use @johnhenry/wsh/server)`);
73
+ protocols.set(name, handler);
74
+ }
75
+ return { protocols, maxMessageBytes, maxInflight };
76
+ }
77
+
55
78
  /** A target's name: what a client puts in `Open.target`. */
56
79
  export const TARGET_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
57
80
  const TARGET_KEYS = ['description', 'authorize', 'exec', 'pty', 'fs', 'endpoints'];
package/src/host.d.ts CHANGED
@@ -129,7 +129,7 @@ export interface WshConnectionPipe {
129
129
  closeTransport?(): void;
130
130
  /**
131
131
  * Serve the connection without client-opened QMux streams: exec output rides `SessionData` (`data_mode: 'virtual'`) and
132
- * `stream-announce` / `rpc` are not offered. Default `true`. Needed for a peer that cannot open streams (#132).
132
+ * `stream-announce` is not offered, and rpc is stated as `rpc-virtual` (#191). Default `true`. Needed for a peer that cannot open streams (#132).
133
133
  */
134
134
  dataStreams?: boolean;
135
135
  }
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();