@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/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.1",
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"
@@ -79,7 +91,7 @@
79
91
  "@modelcontextprotocol/sdk": "^1.17.0"
80
92
  },
81
93
  "scripts": {
82
- "test": "node --test test/*.test.mjs",
94
+ "test": "node scripts/run-tests.mjs",
83
95
  "test:rust": "node --test --test-timeout=180000 test/rust/*.test.mjs",
84
96
  "test:browser": "playwright test --config test/browser/playwright.config.mjs",
85
97
  "size": "node scripts/bundle-size.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
  /**
@@ -2762,7 +2815,9 @@ export class WshClient {
2762
2815
  */
2763
2816
  #attachTransportHandlers(transport) {
2764
2817
  transport.onControl = (msg) => this.#onTransportControl(msg);
2765
- transport.onClose = () => this.#handleTransportClose();
2818
+ // A sealed frame is opened asynchronously, so the close of the socket behind the last frame must wait for it: the frames
2819
+ // that arrived before the close are delivered first (the host's last words, the exit of a command), then the close is handled.
2820
+ transport.onClose = () => this.#afterOpens(() => this.#handleTransportClose());
2766
2821
  transport.onError = (err) => this.#handleTransportError(err);
2767
2822
  // A datagram is not a frame: on a sealed session a relay could inject one, so none is heard (UDP uses the reliable path).
2768
2823
  transport.onDatagram = (bytes) => { if (!this.#sessionSeal) this.#gateway?.handleDatagram(bytes); };
@@ -2990,17 +3045,36 @@ export class WshClient {
2990
3045
  if (!seal || msg.type === MSG.PING || msg.type === MSG.PONG) { this.#handleControl(msg); return; }
2991
3046
  if (seal.bridge) {
2992
3047
  if (!seal.bridge.isFrame(msg)) {
2993
- console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) on a sealed session`);
3048
+ this.#countDrop({ reason: 'plaintext-on-sealed-session', messageType: msg.type });
2994
3049
  return;
2995
3050
  }
2996
- seal.bridge.open(msg).then(
3051
+ this.#trackOpen(seal.bridge.open(msg).then(
2997
3052
  (inner) => { if (this.#sessionSeal === seal) this.#handleControl(inner); },
2998
3053
  (err) => this.#sealedFrameFailed(seal, err),
2999
- );
3054
+ ));
3000
3055
  return;
3001
3056
  }
3002
3057
  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`);
3058
+ this.#countDrop({ reason: 'plaintext-before-seal', messageType: msg.type });
3059
+ }
3060
+
3061
+ /** Sealed frames being opened (each is one pending promise), and what is waiting for them to be delivered. */
3062
+ #opening = 0;
3063
+ #afterOpening = [];
3064
+
3065
+ /** @param {Promise<unknown>} p a frame being opened and delivered; never rejects */
3066
+ #trackOpen(p) {
3067
+ this.#opening++;
3068
+ const done = () => {
3069
+ if (--this.#opening > 0) return;
3070
+ for (const fn of this.#afterOpening.splice(0)) fn();
3071
+ };
3072
+ p.then(done, done);
3073
+ }
3074
+
3075
+ /** Run `fn` now, or once every sealed frame that has already arrived has been opened and delivered. */
3076
+ #afterOpens(fn) {
3077
+ if (this.#opening === 0) fn(); else this.#afterOpening.push(fn);
3004
3078
  }
3005
3079
 
3006
3080
  #sealedFrameFailed(seal, err) {
@@ -3046,11 +3120,11 @@ export class WshClient {
3046
3120
  const firstResponse = await this.#waitForMessage(
3047
3121
  [MSG.SERVER_HELLO, MSG.CHALLENGE, MSG.AUTH_FAIL],
3048
3122
  timeout,
3049
- 'Auth handshake timed out'
3123
+ handshakeTimeout('Auth handshake timed out')
3050
3124
  );
3051
3125
 
3052
3126
  if (firstResponse.type === MSG.AUTH_FAIL) {
3053
- throw new Error(`Authentication failed: ${firstResponse.reason || 'unknown'}`);
3127
+ throw new WshAuthError(firstResponse.reason || 'unknown');
3054
3128
  }
3055
3129
 
3056
3130
  let tempSessionId = null;
@@ -3120,7 +3194,7 @@ export class WshClient {
3120
3194
  );
3121
3195
 
3122
3196
  if (authResult.type === MSG.AUTH_FAIL) {
3123
- throw new Error(`Authentication failed: ${authResult.reason || 'rejected'}`);
3197
+ throw new WshAuthError(authResult.reason || 'rejected');
3124
3198
  }
3125
3199
 
3126
3200
  this.#sessionId = authResult.session_id || tempSessionId;
@@ -3178,14 +3252,14 @@ export class WshClient {
3178
3252
  const sealState = this.#sealState;
3179
3253
  if (sealState) {
3180
3254
  if (sealState.bridge?.isFrame(inner)) {
3181
- sealState.bridge.open(inner)
3255
+ this.#trackOpen(sealState.bridge.open(inner)
3182
3256
  .then((opened) => this.#handleControl(opened, msg.from_fingerprint))
3183
- .catch((err) => console.warn('[wsh:client] dropping a sealed frame:', err.message));
3257
+ .catch((err) => this.#countDrop({ reason: 'unopenable-bridge-frame', detail: err.message })));
3184
3258
  return;
3185
3259
  }
3186
3260
  const setup = !sealState.bridge && inner.type === MSG.KEY_EXCHANGE && inner.session_id === sealState.sessionId;
3187
3261
  if (!setup) {
3188
- console.warn('[wsh:client] dropping a plaintext message on a sealed bridge');
3262
+ this.#countDrop({ reason: 'plaintext-on-sealed-bridge', messageType: inner.type });
3189
3263
  return;
3190
3264
  }
3191
3265
  }
@@ -3332,6 +3406,12 @@ export class WshClient {
3332
3406
  }
3333
3407
  }
3334
3408
 
3409
+ // Credit for an rpc channel in virtual data mode (#191) is a GatewayCredit in a number space of its own.
3410
+ if (type === MSG.GATEWAY_CREDIT && rpcChannelOfCredit(msg.gateway_id) !== undefined) {
3411
+ this.#rpcLinks.get(rpcChannelOfCredit(msg.gateway_id))?.grant(msg.bytes);
3412
+ return;
3413
+ }
3414
+
3335
3415
  // Route gateway messages (0x70–0x7f) to the gateway handler.
3336
3416
  if (type >= 0x70 && type <= 0x7f) {
3337
3417
  // Connections opened through openUnix()/openEndpoint()/openTcp()/listenUnix() own their ids.
@@ -3500,7 +3580,7 @@ export class WshClient {
3500
3580
  for (const session of this.#sessions.values()) {
3501
3581
  session._handleControlMessage({ type: MSG.CLOSE });
3502
3582
  }
3503
- this.#sessions.clear();
3583
+ this.#sessions.clear(); this.#rpcLinks.clear();
3504
3584
 
3505
3585
  try {
3506
3586
  this.onClose?.();
@@ -3535,7 +3615,7 @@ export class WshClient {
3535
3615
  // Remove this waiter.
3536
3616
  this.#removeWaiter(key, waiter);
3537
3617
  signal?.removeEventListener('abort', onAbort);
3538
- reject(new Error(timeoutMessage));
3618
+ reject(timeoutMessage instanceof Error ? timeoutMessage : new Error(timeoutMessage));
3539
3619
  }, timeout);
3540
3620
  const onAbort = () => {
3541
3621
  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
  }