@johnhenry/wsh 0.32.0 → 0.33.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/README.md CHANGED
@@ -182,10 +182,14 @@ const { stdout } = await WshClient.exec(url, 'wc -c', { username, keyPair, stdin
182
182
  On an open exec session, `await session.write(data); await session.closeStdin()` sends EOF without closing the
183
183
  session: output keeps arriving and `onExit` / `onClose` fire as usual. Without `stdin`, `exec` never touches stdin.
184
184
 
185
- EOF is the end of the session's stdin data stream, so it needs a **stream-mode** host: `@johnhenry/wsh/server` (any
186
- version, nothing to upgrade server-side). The Rust `wsh-server` runs exec on a PTY with stdin carried as control
187
- messages (`data_mode: virtual`) and has no EOF message; `closeStdin()` throws there and `exec({ stdin })` rejects
188
- rather than silently hanging (tracked in #105).
185
+ EOF is either the end of the session's stdin data stream (a **stream-mode** host: `@johnhenry/wsh/server`, any
186
+ version) or, on a virtual-mode host, a zero-length `SessionData`. The Rust `wsh-server` from `rust-v0.5.0` supports the
187
+ second form: it advertises the `exec-pipes` feature, and a client that sees it opens the exec channel with
188
+ `stdio: 'pipes'` (`exec({ stdin })` does this by itself), so the command runs on plain pipes -- byte-exact input, no
189
+ echo, stderr kept apart (`session.onStderr`, and `stderr` in the `exec()` result) -- and `closeStdin()` works. Against
190
+ an older Rust server (no `exec-pipes`; its exec is a PTY) nothing is sent that it would reject, and `closeStdin()` /
191
+ `exec({ stdin })` fail with a clear error instead of hanging. `exec` without `stdin`, `pty` sessions and shells keep
192
+ the PTY.
189
193
 
190
194
  ## Node Server
191
195
 
@@ -1053,7 +1057,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1053
1057
  browser-app repo. It was previously deleted from clawser by accident
1054
1058
  (2026-03-14) and restored (2026-07-05) before this move.
1055
1059
 
1056
- Four crates, workspace-versioned at `0.1.0`:
1060
+ Four crates, workspace-versioned (currently `0.5.0`):
1057
1061
 
1058
1062
  | Crate | Kind | Description |
1059
1063
  |-------|------|--------------|
@@ -1077,6 +1081,7 @@ than left to be found.
1077
1081
  | Install an authorized key | `WshClient.addAuthorizedKey()` | `wsh_client::WshClient::add_authorized_key()`, `wsh copy-id` | **Wire-unified** (wsh #59): `AuthorizedKeyAdd`/`AuthorizedKeyResult`, replacing a Rust-CLI-only shell command with a message every implementation can send |
1078
1082
  | Host identity / TOFU | `WshKnownHosts` (localStorage-backed) | `KnownHosts`/`HostStatus` (`~/.wsh/known_hosts`-backed) | **Record unified, policy is not** (wsh #59): both pin `ServerHello.host_fingerprint`, which `@johnhenry/wsh/server` populates (with a proof of possession, [Host key](#host-key-fingerprint--tofu)) but no Rust `wsh-server` release does yet (see [Security](#security-model)). *When* to trust, prompt, or persist is deliberately left per-implementation -- a browser and a CLI have different UX for "first time seeing this host" |
1079
1083
  | Typed RPC channels (`openRpc`, `rpc` sessions; `wsh-host`, `wsh-fs`, `mcp`) | `WshClient.openRpc()`, `RpcChannel` | Rust `wsh-server` (`rust-v0.4.0`+): `wsh-host`, and `wsh-fs` when `[rpc] fs_root` is set; no client yet in `wsh-client` | **No wire change**: `Open { kind: 'rpc', command: <protocol> }` plus `rpc*` `ServerHello` features, negotiated so it fails fast elsewhere; the Rust server serves it on WebSocket/QMux only |
1084
+ | Exec stdin + EOF, separate stderr | `exec({ stdin })`, `session.closeStdin()`, `session.onStderr` | none yet in `wsh-client` | **Wire-unified, negotiated** (#105): `Open.stdio = "pipes"` + `OpenOk.stderr_channel_id` + zero-length `SessionData` as EOF, offered by the `exec-pipes` `ServerHello` feature. `@johnhenry/wsh/server` needs none of it (stream-mode EOF); the Rust `wsh-server` (`rust-v0.5.0`+) runs such an exec on pipes, everything else on the PTY |
1080
1085
  | Interactive shell UI | none -- this SDK is a protocol client, not a terminal emulator; pair with xterm.js/ghostty-web | `wsh connect`, `wsh sftp` (line-oriented REPL) | **Deliberately not unified** -- a browser embeds a terminal widget the host page owns; a CLI process owns its own TTY |
1081
1086
  | Attach / resume | `attachSession()`, `resumeSession()`, `WshSession.seq` | `attach_session()`, `resume_session()` | **Wire-unified** (`Attach`/`Resume`/`Presence`); `seq` = cumulative output bytes. `@johnhenry/wsh/server` honours `last_seq` (bounded ring, gap errors) and answers Presence with `channel_id`/`seq`; the Rust `wsh-server` does the same (`rust-v0.2.0`+; fixed 256 KiB ring) |
1082
1087
  | Reverse-connect / relay peer | `connectReverse()`, `trustRelayPeer()`; `@johnhenry/wsh/server`: `relay` option and `createReverseHost()` | `wsh reverse`, `wsh agent` (persistent, with startup-unit install) | **Wire-unified** (registration, discovery, signed peer records); **daemonization is CLI-only** -- a browser tab cannot be a background OS service. The Node relay is default-deny and bridges one operator per peer unless `maxOperatorsPerPeer` is raised (`busy:` reasons say so); E2E and bridged feature gates need `rust-v0.3.0`+ on the Rust side; several operators per peer and the signed `KeyExchange` are JS-relay only for now |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.32.0",
3
+ "version": "0.33.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",
package/src/client.mjs CHANGED
@@ -81,6 +81,7 @@ export const MCP_CALL_ID_FEATURE = 'mcp-call-id';
81
81
  * one-byte "primer" -- against such a host it would reach the process's stdin.
82
82
  */
83
83
  export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
84
+ export const EXEC_PIPES_FEATURE = 'exec-pipes';
84
85
 
85
86
  /**
86
87
  * Reject a missing argument that maps to a `required: true` wire field.
@@ -713,8 +714,17 @@ export class WshClient {
713
714
  * stream is bound, before any received byte can be delivered (`openRpc` uses it to set `onData`).
714
715
  * @returns {Promise<WshSession>}
715
716
  */
716
- async openSession({ type = 'pty', command, protocol, cols = 80, rows = 24, env, timeout = DEFAULT_OPEN_TIMEOUT, primer = true, attach } = {}) {
717
+ async openSession({ type = 'pty', command, protocol, cols = 80, rows = 24, env, timeout = DEFAULT_OPEN_TIMEOUT, primer = true, attach, stdio } = {}) {
717
718
  this.#assertAuthenticated('openSession');
719
+ if (stdio !== undefined && stdio !== 'pty' && stdio !== 'pipes') {
720
+ throw new TypeError('openSession: stdio must be "pty" or "pipes"');
721
+ }
722
+ if (stdio === 'pipes') {
723
+ if (type !== 'exec') throw new TypeError('openSession: stdio "pipes" is only for type "exec"');
724
+ if (!this.hasFeature(EXEC_PIPES_FEATURE)) {
725
+ throw new Error(`openSession: this host does not advertise "${EXEC_PIPES_FEATURE}" (exec on plain pipes with stdin EOF); it runs exec on a PTY, which cannot signal end of input`);
726
+ }
727
+ }
718
728
  if (type === 'rpc') {
719
729
  this.#assertRpcProtocol(protocol);
720
730
  command = protocol;
@@ -722,7 +732,7 @@ export class WshClient {
722
732
  const requestedChannelId = this._nextChannelId();
723
733
 
724
734
  await this.#transport.sendControl(
725
- openMsg({ kind: type, command, cols, rows, env })
735
+ openMsg({ kind: type, command, cols, rows, env, stdio: stdio === 'pipes' ? 'pipes' : undefined })
726
736
  );
727
737
 
728
738
  // Registered as a dedicated pending-open (not the generic
@@ -1038,21 +1048,32 @@ export class WshClient {
1038
1048
  * @param {boolean} [opts.primer=true] - See `openSession({ primer })`
1039
1049
  * @param {string|Uint8Array|ReadableStream|AsyncIterable|Iterable} [opts.stdin] - Input for the
1040
1050
  * command. It is written, then stdin is closed (EOF), so `cat`, `wc -c` and `sh -s` finish.
1041
- * Omitted: stdin is never touched (unchanged behaviour). Needs a stream-mode host.
1042
- * @returns {Promise<{stdout: Uint8Array, exitCode: number}>}
1043
- */
1044
- static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, ...hostKeyOpts } = {}) {
1051
+ * Omitted: stdin is never touched (unchanged behaviour). Needs a stream-mode host or a host
1052
+ * advertising `exec-pipes` (the Rust `wsh-server` from `rust-v0.5.0`); against any other
1053
+ * virtual-mode host it fails with a clear error rather than hanging.
1054
+ * @param {'pipes'|'pty'} [opts.stdio] - Where the command runs. Default: with `stdin`, plain pipes
1055
+ * when the host advertises `exec-pipes` (no echo, stderr kept apart, EOF), else the host's native
1056
+ * mode; without `stdin`, the host's native mode (a PTY on the Rust server), exactly as before.
1057
+ * `'pipes'` throws if the host does not advertise `exec-pipes`; `'pty'` never asks for pipes.
1058
+ * @returns {Promise<{stdout: Uint8Array, exitCode: number, stderr?: Uint8Array}>} `stderr` is present
1059
+ * only when the command ran on pipes.
1060
+ */
1061
+ static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, stdio, ...hostKeyOpts } = {}) {
1045
1062
  if (stdin !== undefined) assertStdinSource(stdin);
1063
+ if (stdio !== undefined && stdio !== 'pipes' && stdio !== 'pty') throw new TypeError('exec: stdio must be "pipes" or "pty"');
1046
1064
  const client = new WshClient();
1047
1065
  const chunks = [];
1066
+ const errChunks = [];
1048
1067
  let exitCode = -1;
1068
+ let piped = false;
1049
1069
 
1050
1070
  try {
1051
1071
  await client.connect(url, { username, keyPair, signer, password, ...hostKeyOpts });
1072
+ piped = stdio === 'pipes' || (stdio === undefined && stdin !== undefined && client.hasFeature(EXEC_PIPES_FEATURE));
1052
1073
 
1053
1074
  // The first stdin byte (or the EOF itself) announces the data stream to a
1054
1075
  // legacy host, so the primer byte is only needed when there is no stdin.
1055
- const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false });
1076
+ const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false, stdio: piped ? 'pipes' : undefined });
1056
1077
 
1057
1078
  await new Promise((resolve, reject) => {
1058
1079
  const timer = setTimeout(() => {
@@ -1063,6 +1084,10 @@ export class WshClient {
1063
1084
  chunks.push(data);
1064
1085
  };
1065
1086
 
1087
+ session.onStderr = (data) => {
1088
+ errChunks.push(data);
1089
+ };
1090
+
1066
1091
  session.onExit = (code) => {
1067
1092
  exitCode = code;
1068
1093
  };
@@ -1084,16 +1109,18 @@ export class WshClient {
1084
1109
  await client.disconnect().catch(() => {});
1085
1110
  }
1086
1111
 
1087
- // Concatenate output chunks.
1088
- const totalLength = chunks.reduce((sum, c) => sum + c.byteLength, 0);
1089
- const stdout = new Uint8Array(totalLength);
1090
- let offset = 0;
1091
- for (const chunk of chunks) {
1092
- stdout.set(chunk, offset);
1093
- offset += chunk.byteLength;
1094
- }
1112
+ const concat = (parts) => {
1113
+ const out = new Uint8Array(parts.reduce((sum, c) => sum + c.byteLength, 0));
1114
+ let offset = 0;
1115
+ for (const chunk of parts) {
1116
+ out.set(chunk, offset);
1117
+ offset += chunk.byteLength;
1118
+ }
1119
+ return out;
1120
+ };
1095
1121
 
1096
- return { stdout, exitCode };
1122
+ const stdout = concat(chunks);
1123
+ return piped ? { stdout, exitCode, stderr: concat(errChunks) } : { stdout, exitCode };
1097
1124
  }
1098
1125
 
1099
1126
  // ── Reverse mode ────────────────────────────────────────────────────
@@ -2596,9 +2623,12 @@ export class WshClient {
2596
2623
  // different connection.
2597
2624
  sessionId: msg.session_id,
2598
2625
  resumeToken: msg.token,
2626
+ stderrChannelId: msg.stderr_channel_id,
2599
2627
  }
2600
2628
  );
2601
2629
  this.#sessions.set(serverChannelId, session);
2630
+ // stderr of a pipes session arrives on its own channel id; route it to the same session.
2631
+ if (session.stderrChannelId !== undefined) this.#sessions.set(session.stderrChannelId, session);
2602
2632
 
2603
2633
  if (dataMode === 'virtual') {
2604
2634
  session._activateVirtual((m) => this.sendRelayControl(m));
@@ -2705,6 +2735,7 @@ export class WshClient {
2705
2735
  // Remove session from tracking if it's closed.
2706
2736
  if (type === MSG.CLOSE) {
2707
2737
  this.#sessions.delete(channelId);
2738
+ if (session.stderrChannelId !== undefined) this.#sessions.delete(session.stderrChannelId);
2708
2739
  }
2709
2740
  return;
2710
2741
  }
package/src/index.d.ts CHANGED
@@ -244,6 +244,8 @@ export const MCP_CALL_ID_FEATURE: 'mcp-call-id';
244
244
  * one-byte primer against it.
245
245
  */
246
246
  export const STREAM_ANNOUNCE_FEATURE: 'stream-announce';
247
+ /** ServerHello feature: the host runs `exec` on plain pipes (stderr apart, stdin EOF) when asked with `stdio: 'pipes'`. */
248
+ export const EXEC_PIPES_FEATURE: 'exec-pipes';
247
249
 
248
250
  // ── Typed (object-mode) RPC channels -- wsh #85 ────────────────────────
249
251
 
@@ -1633,6 +1635,12 @@ export class WshSession {
1633
1635
  /** Called when stdout/stderr data arrives. */
1634
1636
  onData: ((data: Uint8Array) => void) | null;
1635
1637
 
1638
+ /** stderr of a `stdio: 'pipes'` exec session (the host keeps it apart from stdout). */
1639
+ onStderr: ((data: Uint8Array) => void) | null;
1640
+
1641
+ /** Channel id carrying stderr for a `stdio: 'pipes'` session, else undefined. */
1642
+ readonly stderrChannelId: number | undefined;
1643
+
1636
1644
  /** Called when the remote process exits. */
1637
1645
  onExit: ((code: number) => void) | null;
1638
1646
 
@@ -1849,6 +1857,12 @@ export interface WshOpenSessionOptions {
1849
1857
  * never sends it.
1850
1858
  */
1851
1859
  primer?: boolean;
1860
+ /**
1861
+ * `exec` only: `'pipes'` runs the command on plain pipes (no echo, stderr on
1862
+ * `session.onStderr`, `closeStdin()` works) and throws unless the host
1863
+ * advertises `exec-pipes`. `'pty'` or omitted: the host's native mode.
1864
+ */
1865
+ stdio?: 'pty' | 'pipes';
1852
1866
  }
1853
1867
 
1854
1868
  /**
@@ -1929,12 +1943,20 @@ export interface WshExecOptions extends WshHostKeyOptions {
1929
1943
  * stream-mode host (`@johnhenry/wsh/server`).
1930
1944
  */
1931
1945
  stdin?: string | Uint8Array | ReadableStream<Uint8Array | string> | AsyncIterable<Uint8Array | string> | Iterable<Uint8Array | string>;
1946
+ /**
1947
+ * Default: with `stdin`, plain pipes when the host advertises `exec-pipes`,
1948
+ * else the host's native mode; without `stdin`, the host's native mode.
1949
+ * `'pipes'` throws if the host lacks `exec-pipes`; `'pty'` never asks for pipes.
1950
+ */
1951
+ stdio?: 'pty' | 'pipes';
1932
1952
  }
1933
1953
 
1934
1954
  /** Result from WshClient.exec(). */
1935
1955
  export interface WshExecResult {
1936
1956
  stdout: Uint8Array;
1937
1957
  exitCode: number;
1958
+ /** Present only when the command ran on plain pipes (`exec-pipes`). */
1959
+ stderr?: Uint8Array;
1938
1960
  }
1939
1961
 
1940
1962
  /** Session list entry. */
package/src/index.mjs CHANGED
@@ -75,7 +75,7 @@ export {
75
75
  // Session + Client
76
76
  export { WshSession } from './session.mjs';
77
77
  export { WshVirtualSessionBackend, normalizeSessionData } from './virtual-session.mjs';
78
- export { WshClient, MCP_CALL_ID_FEATURE, STREAM_ANNOUNCE_FEATURE } from './client.mjs';
78
+ export { WshClient, MCP_CALL_ID_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './client.mjs';
79
79
 
80
80
  // End-to-end key exchange (responder side, feature names, signed transcript) -- wsh #90
81
81
  export { E2E_FEATURE, E2E_SIGN_FEATURE, keyExchangeTranscript, verifyKeyExchangeSignature } from './e2e-exchange.mjs';
@@ -240,19 +240,21 @@ export function authFail({ reason } = {}) {
240
240
  };
241
241
  }
242
242
 
243
- export function open({ kind, command, cols, rows, env } = {}) {
243
+ export function open({ kind, command, cols, rows, env, stdio } = {}) {
244
244
  const msg = { type: MSG.OPEN, kind };
245
245
  if (command !== undefined) msg.command = command;
246
246
  if (cols !== undefined) msg.cols = cols;
247
247
  if (rows !== undefined) msg.rows = rows;
248
248
  if (env !== undefined) msg.env = env;
249
+ if (stdio !== undefined) msg.stdio = stdio;
249
250
  return msg;
250
251
  }
251
252
 
252
- export function openOk({ channelId, streamIds = [], dataMode = "stream", capabilities = [], sessionId, token } = {}) {
253
+ export function openOk({ channelId, streamIds = [], dataMode = "stream", capabilities = [], sessionId, token, stderrChannelId } = {}) {
253
254
  const msg = { type: MSG.OPEN_OK, channel_id: channelId, stream_ids: streamIds, data_mode: dataMode, capabilities };
254
255
  if (sessionId !== undefined) msg.session_id = sessionId;
255
256
  if (token !== undefined) msg.token = token;
257
+ if (stderrChannelId !== undefined) msg.stderr_channel_id = stderrChannelId;
256
258
  return msg;
257
259
  }
258
260
 
package/src/session.mjs CHANGED
@@ -173,6 +173,14 @@ export class WshSession {
173
173
  */
174
174
  onData = null;
175
175
 
176
+ /**
177
+ * Called when stderr data arrives, for a session opened with `stdio: 'pipes'`
178
+ * (a host advertising `exec-pipes` keeps stderr apart from stdout). Always
179
+ * null-safe to leave unset: it only ever fires for such sessions.
180
+ * @type {function(Uint8Array): void|null}
181
+ */
182
+ onStderr = null;
183
+
176
184
  /**
177
185
  * Called when the remote process exits.
178
186
  * @type {function(number): void|null}
@@ -246,10 +254,12 @@ export class WshSession {
246
254
  */
247
255
  constructor(
248
256
  transport, channelId, streamIds, kind,
249
- { dataMode = 'stream', capabilities = [], sessionId, resumeToken } = {}
257
+ { dataMode = 'stream', capabilities = [], sessionId, resumeToken, stderrChannelId } = {}
250
258
  ) {
251
259
  this.#transport = transport;
252
260
  this.channelId = channelId;
261
+ /** Channel id carrying stderr for a `stdio: 'pipes'` session, else undefined. */
262
+ this.stderrChannelId = Number.isSafeInteger(stderrChannelId) ? stderrChannelId : undefined;
253
263
  this.#streamIds = streamIds;
254
264
  this.kind = kind;
255
265
  this.id = String(channelId);
@@ -536,6 +546,12 @@ export class WshSession {
536
546
  if (this.#virtualBackend === null) {
537
547
  throw new Error('Session not yet activated — virtual backend unavailable');
538
548
  }
549
+ if (this.#stdinClosed) {
550
+ throw new Error('Cannot write to a session whose stdin is closed');
551
+ }
552
+ // A zero-length SessionData is the EOF signal on a pipes session; an empty
553
+ // write must never be mistaken for it.
554
+ if (this.#capabilities.includes('stdin-eof') && (typeof data === 'string' ? data.length === 0 : data.byteLength === 0)) return;
539
555
  if (this.#e2eKey !== null) {
540
556
  const bytes = typeof data === 'string' ? textEncoder.encode(data) : data;
541
557
  const counter = this.#e2eSendCounter++;
@@ -586,8 +602,21 @@ export class WshSession {
586
602
  async closeStdin() {
587
603
  if (this.#stdinClosed) return;
588
604
  if (this.#state === STATE_CLOSED) return;
605
+ if (this.#dataMode === 'virtual' && this.#capabilities.includes('stdin-eof')) {
606
+ // Pipes exec on a host that granted `stdio: 'pipes'`: a zero-length
607
+ // SessionData is the EOF (spec Open.stdio / OpenOk.stderr_channel_id).
608
+ if (this.#virtualBackend === null) {
609
+ throw new Error('Session not yet activated — virtual backend unavailable');
610
+ }
611
+ if (this.#e2eKey !== null) {
612
+ throw new Error('closeStdin() is not supported on an end-to-end encrypted virtual session');
613
+ }
614
+ this.#stdinClosed = true;
615
+ await this.#virtualBackend.write(new Uint8Array(0));
616
+ return;
617
+ }
589
618
  if (this.#dataMode !== 'stream') {
590
- throw new Error('closeStdin() needs a stream-mode session; this session\'s host carries stdin as control messages, which have no EOF');
619
+ throw new Error('closeStdin() needs a stream-mode session or a host advertising "exec-pipes"; this session\'s host carries stdin as control messages, which have no EOF');
591
620
  }
592
621
  if (this.#stdinWriter === null) {
593
622
  throw new Error('Session not yet bound — stdin writer unavailable');
@@ -715,6 +744,16 @@ export class WshSession {
715
744
  _handleControlMessage(msg) {
716
745
  switch (msg.type) {
717
746
  case MSG.SESSION_DATA: {
747
+ if (this.stderrChannelId !== undefined && msg.channel_id === this.stderrChannelId) {
748
+ if (msg.data && msg.data.byteLength > 0) {
749
+ try {
750
+ this.onStderr?.(msg.data);
751
+ } catch (err) {
752
+ console.error('[wsh:session] onStderr handler error:', err);
753
+ }
754
+ }
755
+ break;
756
+ }
718
757
  if (msg.data && msg.data.byteLength > 0) {
719
758
  this.#virtualBackend?.pushData(msg.data);
720
759
  try {