@johnhenry/wsh 0.35.0 → 0.36.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
@@ -4,9 +4,10 @@
4
4
  > Renamed to `@johnhenry/wsh` on import into the @johnhenry family. Unlike
5
5
  > other packages in this family, wsh did **not** restart its version at
6
6
  > `0.0.0` on adoption — it was already a mature, actively-depended-upon
7
- > release, so versioning continued forward and now stands at `0.17.0`. This
8
- > is a deliberate, permanent exception to the family's usual 0.0.0-restart
9
- > convention, not an oversight.
7
+ > release, so versioning continued forward from there (see
8
+ > [CHANGELOG.md](CHANGELOG.md) for the current version). This is a deliberate,
9
+ > permanent exception to the family's usual 0.0.0-restart convention, not an
10
+ > oversight.
10
11
 
11
12
  [![npm version](https://img.shields.io/npm/v/%40johnhenry%2Fwsh.svg)](https://www.npmjs.com/package/@johnhenry/wsh)
12
13
  [![CI](https://github.com/johnhenry/wsh/actions/workflows/ci.yml/badge.svg)](https://github.com/johnhenry/wsh/actions/workflows/ci.yml)
@@ -34,6 +35,8 @@ wsh is a pure-JS client library (with an optional Node server at `@johnhenry/wsh
34
35
  - [Rust implementation](#rust-implementation)
35
36
  - [Security model](#security-model)
36
37
  - [Browser Compatibility](#browser-compatibility)
38
+ - [Browser tests and bundle size](#browser-tests-and-bundle-size)
39
+ - [Related projects](#related-projects)
37
40
  - [Family](#family)
38
41
  - [License](#license)
39
42
 
@@ -112,8 +115,10 @@ server implementations can speak the same framing.
112
115
  ```js
113
116
  import { WshClient, generateKeyPair } from '@johnhenry/wsh';
114
117
 
115
- // Generate an Ed25519 key pair
116
- const keyPair = await generateKeyPair(true);
118
+ // Generate an Ed25519 key pair. Non-extractable (the default): this page's code can sign with the private key
119
+ // but nothing can read it out. Authorize it on the host by exporting the PUBLIC half
120
+ // (`exportPublicKeySSH(keyPair.publicKey)`); keep keys across reloads with `WshKeyStore`.
121
+ const keyPair = await generateKeyPair();
117
122
 
118
123
  // Connect to a wsh server
119
124
  const client = new WshClient();
@@ -153,7 +158,7 @@ await client.disconnect();
153
158
  ```js
154
159
  import { WshClient, generateKeyPair } from '@johnhenry/wsh';
155
160
 
156
- const keyPair = await generateKeyPair(true);
161
+ const keyPair = await generateKeyPair(); // non-extractable; see Quick Start
157
162
  const { stdout, exitCode } = await WshClient.exec(
158
163
  'wss://shell.example.com',
159
164
  'ls -la /tmp',
@@ -274,9 +279,33 @@ session.onData = (d) => console.log(new TextDecoder().decode(d)); // "ran hi"
274
279
 
275
280
  It is the real connection handler speaking QMux over an in-memory socket pair, so the client code you test is the code
276
281
  you ship. `host.createClient()` / `host.WebSocket` / `host.accept(socket)` / `createSocketPair()` are the lower-level pieces.
277
- Supported: `auth`, `exec` (a function; there is no shell), `mcp`, `extensions`, `rpc` and `sessions` (below). Not
278
- available in memory: `pty`, `fs`, `gateway`, `relay`, `hostKey`, WebTransport and the `wsh-host` / `wsh-fs` rpc
279
- built-ins (use `@johnhenry/wsh/server`).
282
+ Supported: `auth`, `exec` (a function; there is no shell), `pty`, `fs` and `hostKey` (injected, below), `mcp`,
283
+ `extensions`, `rpc` and `sessions` (below). Not available in memory: `gateway`, `relay`, WebTransport, `exec: true` and
284
+ `fs: { root }` (they need Node) and the `wsh-host` / `wsh-fs` rpc built-ins (use `@johnhenry/wsh/server`).
285
+
286
+ **Injected backends**, shaped like the Node host's, so a page can be a real host (#114):
287
+
288
+ - `pty: { spawn, shell?, cwd?, env?, term? }` -- `spawn` is `node-pty`'s `spawn(file, args, { name, cols, rows, cwd, env })`
289
+ or anything shaped like it, returning `{ onData(cb), onExit(cb), write(data), resize(cols, rows), kill(signal?) }`.
290
+ `write` receives a `Uint8Array` (there is no `Buffer` in a browser, and none is needed anywhere in the host). `shell` is
291
+ the `file` your `spawn` is called with (default `/bin/sh`).
292
+ - `fs: { operate, readWhole, writeWhole, writeAt, openRange?, maxFileBytes? }` -- an object of operations, **not** a root path
293
+ (`fs: { root }` needs Node and is refused here). The types are `WshFileBackend` in `@johnhenry/wsh/host`; the file
294
+ operations (`list`, `stat`, `read`, `write`, `rename`, `mkdir`, `remove`) reach `operate` with the path exactly as the
295
+ client sent it, so **confining paths is the backend's job** -- see [Security model](#security-model).
296
+ - `hostKey` -- a `CryptoKeyPair` (generate it with `generateKeyPair()` and the private key stays non-extractable), a signer
297
+ `{ publicKey, sign(data) }` for a key held elsewhere, or `true` for a fresh non-extractable key. Clients pin it as for
298
+ any host ([Host key](#host-key-fingerprint--tofu)); the proof is signed through `sign`, so the key never has to be readable.
299
+ - `dataStreams` (default `true`) -- whether to offer client-opened QMux data streams. **Set it to `false` for a peer that
300
+ cannot open them: the released Rust client over WebSocket** (`wsh`, `rust-v0.6.0`: "WebSocket transport does not support
301
+ real data streams for this server", #132). Exec output then rides `SessionData` (`data_mode: "virtual"`, as over a relay
302
+ bridge) and `stream-announce` and `rpc` are not offered. It is an option rather than a negotiation because no released
303
+ client says whether it can open streams: the Rust client's `Hello` carries only `mcp` and `file-transfer`. The JS client works
304
+ either way. `host.accept(socket, { dataStreams })` overrides it per connection.
305
+
306
+ **Serving a socket you opened yourself:** `host.accept(new WebSocket(url))` works on a socket that is still connecting (the
307
+ host's first bytes are held until it opens). `accept()` of an in-page host through a relay or a byte pipe is what the
308
+ [browser suite](#browser-tests-and-bundle-size) runs against the released Rust CLI.
280
309
 
281
310
  **`rpc`** takes handler functions only, `rpc: { calc: (channel, ctx) => channel.onRequest('add', ({ a, b }) => a + b) }`
282
311
  (the `RpcChannel` is the one `@johnhenry/wsh/server` hands its handlers), with `rpcMaxMessageBytes` (default 1 MiB) and
@@ -288,10 +317,39 @@ messages, `seq` counted in output bytes, and the same errors (unknown or expired
288
317
  of the session, an output gap). The limits and defaults are the server's: 300000 ms detached before a session is
289
318
  dropped, at most 16 detached sessions (the longest-detached is dropped first), 1 MiB of replayable output per session
290
319
  (a resume older than the ring is refused as a gap; `attachSession` gets the retained tail). The session list lives in
291
- the page's memory, so it ends with the page or `host.close()`. Differences from the server: no `pty`, no
292
- `sessionSecret` (tokens are random per session instead of HMAC-signed, so they cannot be checked across restarts), and
320
+ the page's memory, so it ends with the page or `host.close()`. Differences from the server: no `sessionSecret` (tokens are random per session instead of HMAC-signed, so they cannot be checked across restarts), and
293
321
  the host still runs no command by itself: sessions only wrap whatever `exec` function you pass.
294
322
 
323
+ ### Browser entry points, the connection factory and bundle size
324
+
325
+ Every `exports` entry except `./server` is browser-safe: no `node:*` import and no `Buffer` is reachable from it (a test
326
+ bundles each one for the browser and fails if one is, `test/browser-bundle.test.mjs`), and `"sideEffects": false` lets a
327
+ bundler drop what you do not use.
328
+
329
+ | Entry | What it is |
330
+ |---|---|
331
+ | `@johnhenry/wsh` | the client (`WshClient`, `WshKeyStore`, ...) |
332
+ | `@johnhenry/wsh/memory` | `createMemoryHost()`, a host in this realm (above) |
333
+ | `@johnhenry/wsh/host` | the pieces under it, for your own transport: `createConnectionFactory(config)` -- the connection handler `createWshServer`, `createMemoryHost` and `createReverseHost` all run -- plus `bindSocket(socket, ready, { dataStreams })`, `resolveBackends()`, `resolveHostKey()`, `buildAuthorizer()` and `authMethods()`. It does not import the client |
334
+ | `@johnhenry/wsh/reverse` | `createReverseHost()` for a page or Worker: dial out to a relay and serve the operator it bridges. The same function `@johnhenry/wsh/server` exports, minus `exec: true` and `fs: { root }` |
335
+ | `@johnhenry/wsh/server` | Node only |
336
+
337
+ ```js
338
+ import { createConnectionFactory, bindSocket, resolveBackends, buildAuthorizer, authMethods } from '@johnhenry/wsh/host';
339
+
340
+ const auth = { authorizedKeys: [rawPublicKey] };
341
+ const attach = createConnectionFactory({ // authorize is required: there is no open default
342
+ authorize: await buildAuthorizer(auth), methods: authMethods(auth),
343
+ ...resolveBackends({ exec: async (command, io) => { await io.write('hi\n'); return 0; } }),
344
+ });
345
+ await bindSocket(upgradedSocket, Promise.resolve(attach), { dataStreams: false }); // or attach({ send, ... }) on a byte pipe
346
+ ```
347
+
348
+ `npm run size` prints raw and gzip bytes per entry point (and a few single-import probes, which show tree-shaking at
349
+ work) against `scripts/bundle-budget.json`; CI runs it and `npm test` fails a bundle more than 10% over its budget.
350
+ `npm run size -- --update` rewrites the budget after a deliberate change. Sizes are of this package's own code:
351
+ `@noble/post-quantum`, the optional ML-KEM backend, is left out of the measurement.
352
+
295
353
  ### Signing with a page-held signer
296
354
 
297
355
  `connect()`, `WshClient.exec()` and `connectReverse()` take `signer: { publicKey, sign(data) }` instead of `keyPair`
@@ -1113,6 +1171,7 @@ than left to be found.
1113
1171
  | 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" |
1114
1172
  | 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 |
1115
1173
  | 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 |
1174
+ | Host that runs in a browser page (`createMemoryHost`, `@johnhenry/wsh/reverse`) | yes, with injected `pty` / `fs` / `hostKey` | no (a Rust host is a process) | **JS-only**. A Rust *client* can operate such a host only with `dataStreams: false` (#132): the released Rust client over WebSocket cannot open QMux data streams, and says nothing in `Hello` that a host could use to decide. Its `scp` download also reads a raw stream, not the `FileChunk` messages this host sends, so `wsh scp` from such a host does not work (`wsh ls` and exec do) |
1116
1175
  | 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 |
1117
1176
  | 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) |
1118
1177
  | 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 |
@@ -1248,6 +1307,17 @@ out explicitly below rather than left to be discovered.
1248
1307
  auth, or make sure the transport is actually encrypted, before sending a
1249
1308
  password.
1250
1309
 
1310
+ - **A host that lives in a page (`createMemoryHost`, `@johnhenry/wsh/reverse`) is only as trustworthy as the page.** A
1311
+ non-extractable host key or client key keeps the private key from being *read*, not from being *used*: any script that
1312
+ runs in the page (an XSS, a malicious dependency, an extension with page access) can still have it sign, which means
1313
+ impersonate the host or log in as the user for as long as it runs. The injected `pty`, `fs` and `exec` backends are
1314
+ code you wrote and run with the page's authority -- wsh authenticates who may call them, and confines nothing about what
1315
+ they do: a file backend that resolves `..`, a `pty.spawn` that starts a real process, an `exec` that evals its
1316
+ command are yours to make safe (the Node server's `fs: { root }` is the one with confinement built in, and the
1317
+ browser-safe `fs` option takes no root). Pinning a page-held host key protects a client from the wrong host, not from
1318
+ a byte pipe or relay between them reading and altering the bytes: confidentiality needs `wss://` or the end-to-end layer.
1319
+ `dataStreams: false` changes how output is framed (as `SessionData`), not who is let in.
1320
+
1251
1321
  ## Browser Compatibility
1252
1322
 
1253
1323
  Requires a browser (or Node.js 24+) with `TextEncoder`/`TextDecoder`,
@@ -1325,6 +1395,34 @@ browser the optional `@noble/post-quantum` dependency is what actually
1325
1395
  runs, loaded dynamically by `src/mlkem.mjs`. Treat it as required, not
1326
1396
  optional, if you want the hybrid handshake on the web today.
1327
1397
 
1398
+ ## Browser tests and bundle size
1399
+
1400
+ `npm test` is JS-only and needs no browser. `npm run test:browser` runs the real-Chromium suite (Playwright; install it
1401
+ once with `npx playwright install chromium`) and has its own CI job:
1402
+
1403
+ - a browser client against a Node `createWshServer` over a real WebSocket: auth with a non-extractable key, exec, a pty with
1404
+ resize, file transfer, and resuming a session after the socket drops;
1405
+ - a host that lives in the page, `createMemoryHost().accept(new WebSocket(url))`, joined to its operator by a tiny byte pipe
1406
+ the test owns, driven by the JS client (exec, stdin, pty, files, a pinned non-extractable host key) **and by the released
1407
+ Rust `wsh` CLI**: that test downloads the latest `rust-v*` release's archive for the platform from this repository's
1408
+ GitHub releases, verifies it against the release's `SHA256SUMS`, and runs it with `HOME` pointed at a temp directory (so
1409
+ it never touches `~/.wsh`). It is skipped, with the reason printed, on a platform with no release asset or when the
1410
+ download fails, and fails (rather than skips) in CI. The released CLI only dials `wss://`, so the pipe terminates TLS with
1411
+ a self-signed certificate and the CLI runs with its loopback-only `WSH_INSECURE_LOOPBACK_TLS=1`;
1412
+ - `WshKeyStore` with a non-extractable key surviving a reload and still authenticating.
1413
+
1414
+ The bundle-size report is described under [Browser entry points](#browser-entry-points-the-connection-factory-and-bundle-size).
1415
+
1416
+ ## Related projects
1417
+
1418
+ - **[`@johnhenry/browsermesh-netway`](https://github.com/johnhenry/browsermesh)** takes a `WshClient` as its gateway backend
1419
+ (see [Family](#family) below).
1420
+ - **The Rust crates** in [`crates/`](crates) (`wsh-core`, `wsh-client`, `wsh-cli`, `wsh-server`) are a native
1421
+ implementation of the same wire protocol, versioned separately (`rust-v*` tags) and generated from the same
1422
+ `spec/wsh-v1.yaml`; see [Rust implementation](#rust-implementation) for what each side can do.
1423
+ - **[clawser](https://github.com/erisera-code/clawser)** downloads the Rust release binaries by their archive names and is
1424
+ where the Rust workspace came from.
1425
+
1328
1426
  ## Family
1329
1427
 
1330
1428
  wsh isn't just a standalone remote-shell client -- its `WshClient` is the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.35.0",
3
+ "version": "0.36.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",
@@ -16,8 +16,17 @@
16
16
  "./memory": {
17
17
  "types": "./src/memory-host.d.ts",
18
18
  "import": "./src/memory-host.mjs"
19
+ },
20
+ "./host": {
21
+ "types": "./src/host.d.ts",
22
+ "import": "./src/host.mjs"
23
+ },
24
+ "./reverse": {
25
+ "types": "./src/reverse-host.d.ts",
26
+ "import": "./src/reverse-host.mjs"
19
27
  }
20
28
  },
29
+ "sideEffects": false,
21
30
  "types": "./src/index.d.ts",
22
31
  "files": [
23
32
  "src",
@@ -51,6 +60,8 @@
51
60
  "@fails-components/webtransport": "^1.6.4",
52
61
  "@fails-components/webtransport-transport-http3-quiche": "^1.6.4",
53
62
  "@johnhenry/browsermesh-primitives": "^0.2.0",
63
+ "@playwright/test": "^1.65.1",
64
+ "esbuild": "^0.28.2",
54
65
  "typescript": "^7.0.0",
55
66
  "ws": "^8.21.0",
56
67
  "@modelcontextprotocol/sdk": "^1.17.0"
@@ -58,6 +69,8 @@
58
69
  "scripts": {
59
70
  "test": "node --test test/*.test.mjs",
60
71
  "test:rust": "node --test test/rust/*.test.mjs",
72
+ "test:browser": "playwright test --config test/browser/playwright.config.mjs",
73
+ "size": "node scripts/bundle-size.mjs",
61
74
  "typecheck": "tsc --noEmit -p tsconfig.json",
62
75
  "codegen": "node spec/codegen.mjs",
63
76
  "codegen:check": "node scripts/codegen-check.mjs",
package/src/client.mjs CHANGED
@@ -8,6 +8,7 @@
8
8
  * reverse mode (client registers as a peer for incoming connections).
9
9
  */
10
10
 
11
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './features.mjs';
11
12
  import { WebTransportTransport } from './transport.mjs';
12
13
  import { WebSocketTransport } from './transport-ws.mjs';
13
14
  import {
@@ -66,21 +67,8 @@ const DEFAULT_AUTH_TIMEOUT = 10_000; // ms
66
67
  const DEFAULT_OPEN_TIMEOUT = 10_000; // ms
67
68
  const FS_RPC_OPS = new Set(['stat', 'list', 'read', 'write', 'mkdir', 'remove', 'rename']);
68
69
 
69
- /**
70
- * ServerHello feature advertising that McpResult echoes McpCall's call_id.
71
- *
72
- * Negotiated rather than assumed: McpCallPayload is `deny_unknown_fields` on
73
- * the Rust side, so sending call_id to a server predating it does not
74
- * degrade -- it makes the server reject the call.
75
- */
76
- export const MCP_CALL_ID_FEATURE = 'mcp-call-id';
77
-
78
- /**
79
- * ServerHello feature advertising that the host understands `McpCancel` (stop an in-flight `McpCall`).
80
- * Negotiated rather than assumed: McpCancelPayload is `deny_unknown_fields` on the Rust side, so an older
81
- * server would reject it. Implies `mcp-call-id` (the cancel names a call by its id).
82
- */
83
- export const MCP_CANCEL_FEATURE = 'mcp-cancel';
70
+ // The feature strings live in features.mjs (a host names them without importing this file); re-exported here.
71
+ export { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE };
84
72
 
85
73
  /** An `AbortError` for `signal`, with the signal's reason as `cause`. */
86
74
  function abortError(signal) {
@@ -89,13 +77,6 @@ function abortError(signal) {
89
77
  return e;
90
78
  }
91
79
 
92
- /**
93
- * ServerHello feature: the host discovers a client-opened exec data stream
94
- * on its own (the transport announces it), so the client must NOT write the
95
- * one-byte "primer" -- against such a host it would reach the process's stdin.
96
- */
97
- export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
98
- export const EXEC_PIPES_FEATURE = 'exec-pipes';
99
80
 
100
81
  /**
101
82
  * Reject a missing argument that maps to a `required: true` wire field.
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Feature strings both the client and the host handlers state or look for. Kept in a module of their own so a host
3
+ * (`@johnhenry/wsh/host`, `/memory`, `/reverse`) can name them without importing the whole client.
4
+ */
5
+
6
+ /**
7
+ * ServerHello feature advertising that McpResult echoes McpCall's call_id.
8
+ *
9
+ * Negotiated rather than assumed: McpCallPayload is `deny_unknown_fields` on
10
+ * the Rust side, so sending call_id to a server predating it does not
11
+ * degrade -- it makes the server reject the call.
12
+ */
13
+ export const MCP_CALL_ID_FEATURE = 'mcp-call-id';
14
+
15
+ /**
16
+ * ServerHello feature advertising that the host understands `McpCancel` (stop an in-flight `McpCall`).
17
+ * Negotiated rather than assumed: McpCancelPayload is `deny_unknown_fields` on the Rust side, so an older
18
+ * server would reject it. Implies `mcp-call-id` (the cancel names a call by its id).
19
+ */
20
+ export const MCP_CANCEL_FEATURE = 'mcp-cancel';
21
+
22
+ /**
23
+ * ServerHello feature: the host discovers a client-opened exec data stream
24
+ * on its own (the transport announces it), so the client must NOT write the
25
+ * one-byte "primer" -- against such a host it would reach the process's stdin.
26
+ */
27
+ export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
28
+ export const EXEC_PIPES_FEATURE = 'exec-pipes';
@@ -0,0 +1,100 @@
1
+ /**
2
+ * What a host serves, built from injected parts only: no shell to spawn and no directory to read, so nothing here
3
+ * imports from `node:*` and a browser host (`@johnhenry/wsh/memory`, `/reverse`, `/host`) can use it. The Node
4
+ * server wraps it (`server/backends.mjs`) with the two backends that need Node: `exec: true` and `fs: { root }`.
5
+ */
6
+
7
+ import { normalizePty } from './server/pty.mjs';
8
+ import { createMcpHost } from './server/mcp.mjs';
9
+ import { DEFAULT_MAX_FILE_BYTES } from './server/constants.mjs';
10
+ import { generateKeyPair, resolveSigner, fingerprint, exportPublicKeySSH, importPublicKeyRaw } from './auth.mjs';
11
+
12
+ /** The operations a file backend must have (`openRange` is optional: only the `wsh-fs` rpc built-in, which needs Node, reads it). */
13
+ const FILE_OPERATIONS = ['operate', 'readWhole', 'writeWhole', 'writeAt'];
14
+
15
+ /**
16
+ * Validate a file backend: an object of operations, as `createFileAccess` (`@johnhenry/wsh/server`, confined to a
17
+ * root directory) returns one. Paths arrive exactly as the client sent them -- confining them is the backend's job.
18
+ *
19
+ * - `operate(op, path, { offset, length, newPath, data })` -> `{ metadata?, entries? }`, for the FileOp requests
20
+ * `list`, `stat`, `read`, `write`, `rename`, `mkdir`, `remove`
21
+ * - `readWhole(path)` -> `Uint8Array` (a `download:` channel)
22
+ * - `writeWhole(path, bytes)` (an `upload:` channel)
23
+ * - `writeAt(path, bytes, offset?, { mkdirs? })`
24
+ * - `maxFileBytes` (default 64 MiB)
25
+ *
26
+ * Throw an `Error` with `wsh: true` to have its message sent to the client as is; any other error is reported by its message too.
27
+ *
28
+ * @param {object} fs
29
+ * @param {string} [who] - the option's name in error messages
30
+ */
31
+ export function normalizeFileBackend(fs, who = 'fs') {
32
+ if (!fs || typeof fs !== 'object') throw new TypeError(`${who} must be an object of file operations`);
33
+ if (typeof fs.root === 'string' && typeof fs.operate !== 'function') {
34
+ throw new TypeError(`${who}.root names a directory, which needs Node: use @johnhenry/wsh/server, or give ${who} as an object of operations ({ operate, readWhole, writeWhole, writeAt })`);
35
+ }
36
+ for (const name of FILE_OPERATIONS) {
37
+ if (typeof fs[name] !== 'function') throw new TypeError(`${who}.${name} must be a function`);
38
+ }
39
+ if (fs.openRange !== undefined && typeof fs.openRange !== 'function') throw new TypeError(`${who}.openRange must be a function`);
40
+ const maxFileBytes = fs.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
41
+ if (!Number.isSafeInteger(maxFileBytes) || maxFileBytes < 1) throw new TypeError(`${who}.maxFileBytes must be a positive integer`);
42
+ // Call through `fs` so a backend written with `this` keeps working.
43
+ const files = {
44
+ maxFileBytes,
45
+ operate: (...a) => fs.operate(...a),
46
+ readWhole: (...a) => fs.readWhole(...a),
47
+ writeWhole: (...a) => fs.writeWhole(...a),
48
+ writeAt: (...a) => fs.writeAt(...a),
49
+ };
50
+ if (fs.openRange) files.openRange = (...a) => fs.openRange(...a);
51
+ return files;
52
+ }
53
+
54
+ /**
55
+ * @param {{ exec?: Function | { run: Function }, pty?: { spawn: Function }, fs?: object, mcp?: object }} options
56
+ * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null }}
57
+ */
58
+ export function resolveBackends({ exec, pty, fs, mcp } = {}) {
59
+ let execRunner = null;
60
+ let execOptions = {};
61
+ if (typeof exec === 'function') {
62
+ execRunner = exec;
63
+ } else if (exec !== undefined && exec !== null && exec !== false) {
64
+ if (typeof exec !== 'object' || typeof exec.run !== 'function') {
65
+ throw new TypeError('exec must be a function run(command, io) or { run }: there is no shell to run `true` with here (use @johnhenry/wsh/server for that)');
66
+ }
67
+ execOptions = exec;
68
+ execRunner = exec.run;
69
+ }
70
+ return {
71
+ execRunner,
72
+ execOptions,
73
+ pty: pty ? normalizePty(pty) : null,
74
+ files: fs ? normalizeFileBackend(fs) : null,
75
+ mcp: mcp ? createMcpHost(mcp) : null,
76
+ };
77
+ }
78
+
79
+ /**
80
+ * The host's own identity (`ServerHello.host_fingerprint` and the host-key proof; see `host-key.mjs`), from what a page
81
+ * can hold: a `CryptoKeyPair` (generate it with `generateKeyPair(false)` and the private key never leaves the browser),
82
+ * or a signer `{ publicKey, sign(data) }` (`WshSigner`) when the key lives elsewhere (a hardware key, a Worker, an
83
+ * HSM). `true` makes a fresh non-extractable key for this host (TOFU clients see "changed" next time: demos and tests).
84
+ * The Node server's `hostKey` also takes `{ file }`.
85
+ *
86
+ * @returns {Promise<{ publicKey: Uint8Array, fingerprint: string, openssh: string, sign(data: Uint8Array): Promise<Uint8Array> }>}
87
+ */
88
+ export async function resolveHostKey(option, who = 'hostKey') {
89
+ if (option === true) option = await generateKeyPair(false);
90
+ const isPair = option && typeof option === 'object' && option.privateKey && option.publicKey;
91
+ const isSigner = option && typeof option === 'object' && typeof option.sign === 'function' && option.publicKey;
92
+ if (!isPair && !isSigner) throw new TypeError(`${who} must be true, a CryptoKeyPair, or a signer { publicKey, sign(data) }`);
93
+ const resolved = await resolveSigner(isPair ? { keyPair: option } : { signer: option });
94
+ return {
95
+ publicKey: resolved.publicKeyRaw,
96
+ fingerprint: await fingerprint(resolved.publicKeyRaw),
97
+ openssh: await exportPublicKeySSH(await importPublicKeyRaw(resolved.publicKeyRaw)),
98
+ sign: resolved.sign,
99
+ };
100
+ }
package/src/host.d.ts ADDED
@@ -0,0 +1,146 @@
1
+ import type { WshSigner } from './index.js';
2
+ import type {
3
+ WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshServerAuthOptions, WshServerPrincipal, WshAcceptableSocket, WshAcceptOptions,
4
+ } from './server/index.js';
5
+
6
+ /**
7
+ * File operations a host serves `FileOp` requests and `upload:` / `download:` channels from. An object of
8
+ * operations, not a root path: confining client paths to what the host may expose is the backend's job.
9
+ * (`createWshServer({ fs: { root } })` builds one of these over a directory.)
10
+ */
11
+ export interface WshFileBackend {
12
+ /**
13
+ * `list` -> `{ entries, metadata: { path } }`; `stat` -> `{ metadata: { name, size, modified, type } }`;
14
+ * `read` (`offset`, `length`) -> `{ metadata: { data, size } }`; `write` (`offset`, `data`) -> `{ metadata: { written } }`;
15
+ * `rename` (`newPath`); `mkdir`; `remove`. Anything else should throw.
16
+ */
17
+ operate(op: string, path: string, args?: { offset?: number; length?: number; newPath?: string; data?: Uint8Array }): Promise<{ metadata?: Record<string, unknown>; entries?: Array<Record<string, unknown>> }>;
18
+ /** The whole file, for a `download:` channel. Throw if it is larger than `maxFileBytes`. */
19
+ readWhole(path: string): Promise<Uint8Array>;
20
+ /** Create or replace a file (creating its directories), for an `upload:` channel. */
21
+ writeWhole(path: string, data: Uint8Array): Promise<void>;
22
+ /** Write `data` at `offset` (omitted = replace the file), without truncating when an offset is given. */
23
+ writeAt(path: string, data: Uint8Array, offset?: number, options?: { mkdirs?: boolean }): Promise<void>;
24
+ /** A byte range as chunks; only the `wsh-fs` rpc built-in (Node) reads it. */
25
+ openRange?(path: string, options?: { offset?: number; length?: number; chunkBytes?: number }): Promise<{ size: number; offset: number; length: number; chunks: AsyncIterable<Uint8Array> }>;
26
+ /** Largest file read or written whole, in bytes (default 64 MiB). */
27
+ maxFileBytes?: number;
28
+ }
29
+
30
+ /** A host's own identity: a key pair (the private key may be non-extractable) or a signer for a key held elsewhere. */
31
+ export type WshHostKeyOption = true | CryptoKeyPair | WshSigner;
32
+
33
+ /** The identity `resolveHostKey` makes of a `WshHostKeyOption`. */
34
+ export interface WshResolvedHostKey {
35
+ /** Raw 32-byte Ed25519 public key. */
36
+ publicKey: Uint8Array;
37
+ fingerprint: string;
38
+ openssh: string;
39
+ sign(data: Uint8Array): Promise<Uint8Array>;
40
+ }
41
+
42
+ export interface WshResolvedBackends {
43
+ execRunner: WshExecRunner | null;
44
+ execOptions: { timeoutMs?: number; clientEnv?: boolean };
45
+ pty: { spawn: WshServerPtyOptions['spawn']; shell: string; cwd?: string; env?: Record<string, string | undefined>; term: string } | null;
46
+ files: Required<Pick<WshFileBackend, 'operate' | 'readWhole' | 'writeWhole' | 'writeAt' | 'maxFileBytes'>> & Pick<WshFileBackend, 'openRange'> | null;
47
+ mcp: object | null;
48
+ }
49
+
50
+ /** Validate injected backends (no shell, no directory: `exec` is a function or `{ run }`, `fs` an object of operations). */
51
+ export function resolveBackends(options?: {
52
+ exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
53
+ pty?: WshServerPtyOptions;
54
+ fs?: WshFileBackend;
55
+ mcp?: WshServerMcpOptions;
56
+ }): WshResolvedBackends;
57
+
58
+ /** Validate a file backend (see {@link WshFileBackend}). */
59
+ export function normalizeFileBackend(fs: WshFileBackend, who?: string): NonNullable<WshResolvedBackends['files']>;
60
+
61
+ /** Make the identity a host presents from a `CryptoKeyPair`, a signer, or `true` (a fresh non-extractable key). */
62
+ export function resolveHostKey(option: WshHostKeyOption, who?: string): Promise<WshResolvedHostKey>;
63
+
64
+ /** The `authorize(who)` function for a host's `auth` option (as `createWshServer` reads it). */
65
+ export function buildAuthorizer(auth: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>) | undefined): Promise<(who: { username: string; fingerprint: string; publicKey: Uint8Array }) => Promise<boolean>>;
66
+
67
+ /** Which auth methods an `auth` option turns on. */
68
+ export function authMethods(auth: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>) | undefined): { pubkey: boolean; password: ((user: string, pass: string) => boolean | Promise<boolean>) | null };
69
+
70
+ /** What the connection handler is given. Everything but `authorize` is optional. */
71
+ export interface WshConnectionConfig extends Partial<WshResolvedBackends> {
72
+ /** Required: decides who is let in. A host with no authorizer would let everyone in, so there is no default. */
73
+ authorize(who: { username: string; fingerprint?: string; publicKey?: Uint8Array }): Promise<boolean>;
74
+ /** Auth methods on (default: pubkey only). */
75
+ methods?: { pubkey: boolean; password: ((user: string, pass: string) => boolean | Promise<boolean>) | null };
76
+ hostKey?: WshResolvedHostKey | null;
77
+ /** Handlers for application-defined (string-typed) messages. */
78
+ extensions?: Record<string, (message: any, ctx: { username: string | null; fingerprint: string | null; send(message: object): Promise<void> }) => unknown>;
79
+ /** A `SessionRegistry` (see `src/session-registry.mjs`): detach / attach / resume. Null = sessions die with their connection. */
80
+ sessions?: object | null;
81
+ /** End-to-end encryption for a message-framed (relay-bridged) connection. */
82
+ e2e?: { signKey: CryptoKey | null; hybrid?: boolean } | null;
83
+ /** How long exec output waits for the client-opened data stream (default 3000). */
84
+ bindTimeoutMs?: number;
85
+ log?: (line: string) => void;
86
+ [key: string]: unknown;
87
+ }
88
+
89
+ /** One connection over a byte pipe. */
90
+ export interface WshConnectionPipe {
91
+ /** Send these bytes to the peer. */
92
+ send(bytes: Uint8Array): void;
93
+ remote?: { address?: string; headers?: Record<string, unknown> };
94
+ /** End the underlying transport (the host ends the connection: a refused login, say). */
95
+ closeTransport?(): void;
96
+ /**
97
+ * Serve the connection without client-opened QMux streams: exec output rides `SessionData` (`data_mode: 'virtual'`) and
98
+ * `stream-announce` / `rpc` are not offered. Default `true`. Needed for a peer that cannot open streams (#132).
99
+ */
100
+ dataStreams?: boolean;
101
+ }
102
+
103
+ /** One connection over messages (a transport that does its own framing, e.g. a relay bridge). */
104
+ export interface WshConnectionMessages {
105
+ sendMessage(message: object): unknown;
106
+ /** The identity something else already authenticated: skips the handshake. */
107
+ authenticated?: { username: string; fingerprint: string } | null;
108
+ dataStreams?: boolean;
109
+ e2e?: { signKey: CryptoKey | null; hybrid?: boolean } | null;
110
+ remote?: { address?: string; headers?: Record<string, unknown> };
111
+ closeTransport?(): void;
112
+ }
113
+
114
+ export interface WshConnection {
115
+ /** Bytes from the peer (byte-pipe form). */
116
+ receive(bytes: Uint8Array): void;
117
+ /** One decoded message from the peer (message form). */
118
+ receiveMessage(message: object): void;
119
+ /** A QMux-style stream opened by the peer (message form, when it has them). */
120
+ bindStream?(stream: object): void;
121
+ close(): void;
122
+ }
123
+
124
+ export type WshConnectionAttach = (pipe: WshConnectionPipe | WshConnectionMessages) => WshConnection;
125
+
126
+ /**
127
+ * The connection handler every wsh host runs. Returns `attach`, called once per connection. Over a WebSocket-like
128
+ * duplex use {@link bindSocket} rather than calling it by hand.
129
+ */
130
+ export function createConnectionFactory(config: WshConnectionConfig): WshConnectionAttach;
131
+
132
+ /** The features a host built from `config` advertises in `ServerHello` (minus the host-key proof). */
133
+ export function hostFeatures(config: Partial<WshConnectionConfig>, options?: { dataStreams?: boolean }): string[];
134
+
135
+ /** ServerHello feature: the host discovers client-opened exec data streams itself (no primer byte). */
136
+ export const STREAM_ANNOUNCE: 'stream-announce';
137
+
138
+ /**
139
+ * Serve a pre-upgraded WebSocket-like duplex (`send`, `close`, `readyState`, and `addEventListener` or `on`) with the
140
+ * connection handler `ready` resolves to. Resolves once attached; the handle's `close()` drops the connection.
141
+ */
142
+ export function bindSocket(
143
+ socket: WshAcceptableSocket,
144
+ ready: Promise<WshConnectionAttach>,
145
+ options?: WshAcceptOptions,
146
+ ): Promise<{ close(): void }>;
package/src/host.mjs ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `@johnhenry/wsh/host` -- the building blocks of a wsh host that runs anywhere JavaScript does (a page, a Worker,
3
+ * Deno, Bun, Node), for an embedder that brings its own transport. No `node:*` import and no `Buffer` is reachable
4
+ * from here (a test bundles this entry point for the browser and fails if one is), and it does not import the client.
5
+ *
6
+ * - `createConnectionFactory(cfg)` -- the connection handler `createWshServer`, `createMemoryHost` and
7
+ * `createReverseHost` all run: handshake, auth, exec / pty / file / MCP channels, sessions, end-to-end encryption.
8
+ * `attach(...)` is called once per connection, over a byte pipe (QMux framing, what a WebSocket carries) or, for a
9
+ * transport that frames messages itself, over messages.
10
+ * - `bindSocket(socket, ready, options)` -- the byte-pipe side for a WebSocket-like duplex.
11
+ * - `resolveBackends({ exec, pty, fs, mcp })`, `resolveHostKey(key)`, `buildAuthorizer(auth)`, `authMethods(auth)` --
12
+ * turn the options a host takes into what the factory wants.
13
+ *
14
+ * ```js
15
+ * import { createConnectionFactory, resolveBackends, buildAuthorizer, authMethods, bindSocket } from '@johnhenry/wsh/host';
16
+ *
17
+ * const auth = { authorizedKeys: [rawPublicKey] };
18
+ * const backends = resolveBackends({ exec: async (command, io) => { await io.write('hi\n'); return 0; } });
19
+ * const attach = createConnectionFactory({
20
+ * authorize: await buildAuthorizer(auth), methods: authMethods(auth), ...backends,
21
+ * });
22
+ * // `attach` is what `bindSocket` wants, as a promise:
23
+ * await bindSocket(upgradedSocket, Promise.resolve(attach), { dataStreams: false });
24
+ * ```
25
+ */
26
+
27
+ export { createConnectionFactory, hostFeatures, STREAM_ANNOUNCE } from './server/connection.mjs';
28
+ export { bindSocket } from './server/socket.mjs';
29
+ export { resolveBackends, resolveHostKey, normalizeFileBackend } from './host-backends.mjs';
30
+ export { buildAuthorizer, authMethods } from './server/auth.mjs';
@@ -1,7 +1,8 @@
1
1
  import type { WshClient, RpcChannel } from './index.js';
2
2
  import type { WshSigner } from './index.js';
3
+ import type { WshFileBackend, WshHostKeyOption } from './host.js';
3
4
  import type {
4
- WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions,
5
+ WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions, WshServerPtyOptions,
5
6
  WshAcceptableSocket, WshAcceptOptions,
6
7
  } from './server/index.js';
7
8
 
@@ -30,6 +31,22 @@ export interface WshMemoryHostOptions {
30
31
  auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>);
31
32
  /** `run(command, io)`; there is no shell in memory, so there is no `true`. */
32
33
  exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
34
+ /** `node-pty`-shaped `{ spawn }`, injected (a browser has no pty of its own). Input arrives at `write` as a `Uint8Array`. Off unless given. */
35
+ pty?: WshServerPtyOptions;
36
+ /** An object of file operations, not a root path (confining paths is the backend's job). Off unless given. */
37
+ fs?: WshFileBackend;
38
+ /**
39
+ * This host's own identity, so clients can pin it: a `CryptoKeyPair` (the private key may be non-extractable), a signer
40
+ * `{ publicKey, sign }` for a key held elsewhere, or `true` for a fresh non-extractable key. Off unless given.
41
+ */
42
+ hostKey?: WshHostKeyOption;
43
+ /**
44
+ * 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
46
+ * WebSocket (#132). Released clients state nothing a host could choose on, so this is an option, not a negotiation;
47
+ * `accept(socket, { dataStreams })` overrides it for one connection.
48
+ */
49
+ dataStreams?: boolean;
33
50
  mcp?: WshServerMcpOptions;
34
51
  extensions?: WshServerOptions['extensions'];
35
52
  /** Typed RPC channels: one handler per protocol, called once per opened channel to register methods. Handler functions only (the `wsh-host` / `wsh-fs` built-ins need Node). Off unless given. */