@johnhenry/wsh 0.30.0 → 0.32.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.
@@ -0,0 +1,48 @@
1
+ import type { WshClient } from './index.js';
2
+ import type { WshSigner } from './index.js';
3
+ import type {
4
+ WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions,
5
+ WshAcceptableSocket, WshAcceptOptions,
6
+ } from './server/index.js';
7
+
8
+ export interface WshMemoryHostOptions {
9
+ /** As for `createWshServer`. Omitted = refuse everyone. */
10
+ auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>);
11
+ /** `run(command, io)`; there is no shell in memory, so there is no `true`. */
12
+ exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
13
+ mcp?: WshServerMcpOptions;
14
+ extensions?: WshServerOptions['extensions'];
15
+ bindTimeoutMs?: number;
16
+ onLog?: (line: string) => void;
17
+ }
18
+
19
+ /** Credentials for `host.connect()`: the options of `WshClient.connect()` minus the URL. */
20
+ export interface WshMemoryConnectOptions {
21
+ username: string;
22
+ keyPair?: CryptoKeyPair;
23
+ signer?: WshSigner;
24
+ password?: string;
25
+ timeout?: number;
26
+ }
27
+
28
+ export interface WshMemoryHost {
29
+ /** The URL to give `client.connect()`; the host ignores it. */
30
+ readonly url: string;
31
+ /** A `WebSocket` constructor that dials this host. */
32
+ readonly WebSocket: new (url?: string) => any;
33
+ /** Serve any pre-upgraded socket (see `createSocketPair()`). */
34
+ accept(socket: WshAcceptableSocket, options?: WshAcceptOptions): Promise<{ close(): void }>;
35
+ socketPair: typeof createSocketPair;
36
+ /** A `WshClient` whose transport is this host: `await client.connect(host.url, { username, keyPair, transport: 'ws' })`. */
37
+ createClient(options?: ConstructorParameters<typeof WshClient>[0]): WshClient;
38
+ /** `createClient()` and `connect()` in one. */
39
+ connect(credentials: WshMemoryConnectOptions): Promise<WshClient>;
40
+ /** Drop every connection. */
41
+ close(): Promise<void>;
42
+ }
43
+
44
+ /** Two connected in-memory WebSocket-like sockets. */
45
+ export function createSocketPair(): [WshAcceptableSocket & EventTarget, WshAcceptableSocket & EventTarget];
46
+
47
+ /** A browser-safe wsh host in this JavaScript realm: no sockets, no Node. */
48
+ export function createMemoryHost(options?: WshMemoryHostOptions): WshMemoryHost;
@@ -0,0 +1,175 @@
1
+ /**
2
+ * `@johnhenry/wsh/memory` -- a wsh host that lives in the same JavaScript realm as its clients, with no sockets, no
3
+ * ports and no Node. Browser-safe (a page, a Worker, Deno, Bun, Node): it imports nothing from `node:*`, and a test
4
+ * (`test/memory-host.test.mjs`) keeps it that way. For demos, docs and tests of an application that talks wsh.
5
+ *
6
+ * It is the real protocol end to end -- the same connection handler `createWshServer` runs (handshake, Ed25519 or
7
+ * password auth, exec channels, MCP tools, extensions), speaking QMux over a pair of in-memory WebSocket-like
8
+ * sockets -- so what a client does here is what it does against a server. It serves what a browser can: `exec` as a
9
+ * function you provide (there is no shell), `mcp` tools, `extensions`. Not available: `pty`, `fs`, `gateway`, `relay`,
10
+ * `sessions`, `rpc`, `hostKey`, WebTransport (they need Node; use `@johnhenry/wsh/server`).
11
+ *
12
+ * ```js
13
+ * import { createMemoryHost } from '@johnhenry/wsh/memory';
14
+ * const host = createMemoryHost({
15
+ * auth: { authorizedKeys: [rawPublicKey] },
16
+ * exec: async (command, io) => { await io.write(`you ran: ${command}\n`); return 0; },
17
+ * });
18
+ * const client = await host.connect({ username: 'demo', keyPair });
19
+ * ```
20
+ */
21
+
22
+ import { WshClient } from './client.mjs';
23
+ import { WebSocketTransport } from './transport-ws.mjs';
24
+ import { createConnectionFactory } from './server/connection.mjs';
25
+ import { buildAuthorizer, authMethods, FailureLimiter } from './server/auth.mjs';
26
+ import { createMcpHost } from './server/mcp.mjs';
27
+ import { bindSocket } from './server/socket.mjs';
28
+
29
+ const CONNECTING = 0;
30
+ const OPEN = 1;
31
+ const CLOSING = 2;
32
+ const CLOSED = 3;
33
+
34
+ /** The URL to hand `client.connect()` (the host ignores it; it only has to look like a WebSocket URL). */
35
+ const MEMORY_URL = 'ws://memory.invalid/';
36
+
37
+ function event(type, props) {
38
+ const ev = new Event(type);
39
+ Object.assign(ev, props);
40
+ return ev;
41
+ }
42
+
43
+ /** One end of an in-memory socket pair: just enough WebSocket for `WebSocketTransport` and `bindSocket`. */
44
+ class MemorySocket extends EventTarget {
45
+ static CONNECTING = CONNECTING;
46
+ static OPEN = OPEN;
47
+ static CLOSING = CLOSING;
48
+ static CLOSED = CLOSED;
49
+
50
+ readyState = CONNECTING;
51
+ binaryType = 'arraybuffer';
52
+ /** @type {MemorySocket | null} */
53
+ peer = null;
54
+
55
+ send(data) {
56
+ if (this.readyState !== OPEN) throw new Error('WebSocket is not open');
57
+ if (typeof data === 'string') return; // wsh frames are binary
58
+ const view = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
59
+ const copy = view.slice().buffer;
60
+ const peer = this.peer;
61
+ queueMicrotask(() => { if (peer.readyState === OPEN) peer.dispatchEvent(event('message', { data: copy })); });
62
+ }
63
+
64
+ close(code = 1000, reason = '') {
65
+ if (this.readyState >= CLOSING) return;
66
+ this.readyState = CLOSING;
67
+ const peer = this.peer;
68
+ queueMicrotask(() => {
69
+ for (const s of [this, peer]) {
70
+ if (s.readyState === CLOSED) continue;
71
+ s.readyState = CLOSED;
72
+ s.dispatchEvent(event('close', { code, reason, wasClean: true }));
73
+ }
74
+ });
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Two connected sockets: what one sends, the other receives (asynchronously, in order). Both are open after a tick.
80
+ * @returns {[MemorySocket, MemorySocket]}
81
+ */
82
+ export function createSocketPair() {
83
+ const a = new MemorySocket();
84
+ const b = new MemorySocket();
85
+ a.peer = b;
86
+ b.peer = a;
87
+ queueMicrotask(() => {
88
+ for (const s of [a, b]) { s.readyState = OPEN; s.dispatchEvent(new Event('open')); }
89
+ });
90
+ return [a, b];
91
+ }
92
+
93
+ /**
94
+ * @param {object} [options]
95
+ * @param {object | Function} [options.auth] - As for `createWshServer`. Omitted = refuse everyone.
96
+ * @param {Function | { run: Function, timeoutMs?: number, clientEnv?: boolean }} [options.exec]
97
+ * `run(command, io) => Promise<exitCode>` (see `ExecIo` in `server/exec.mjs`): the host has no shell, so there is no `true`.
98
+ * @param {{ tools?: object[] | object, client?: object, authorize?: Function, maxConcurrent?: number, timeoutMs?: number }} [options.mcp]
99
+ * @param {Record<string, Function>} [options.extensions] - Handlers for application-defined messages, as for `createWshServer`.
100
+ * @param {number} [options.bindTimeoutMs=3000]
101
+ * @param {(line: string) => void} [options.onLog]
102
+ */
103
+ export function createMemoryHost({ auth, exec, mcp, extensions, bindTimeoutMs = 3000, onLog = () => {} } = {}) {
104
+ if (exec === true) throw new TypeError('createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with');
105
+ if (exec !== undefined && typeof exec !== 'function' && typeof exec?.run !== 'function') {
106
+ throw new TypeError('createMemoryHost: exec must be a function or { run }');
107
+ }
108
+ if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createMemoryHost: extensions must be an object of handlers');
109
+ const execOptions = typeof exec === 'function' || !exec ? {} : exec;
110
+ const execRunner = typeof exec === 'function' ? exec : exec?.run ?? null;
111
+ const rl = auth?.rateLimit ?? {};
112
+ const rateLimit = {
113
+ limiter: new FailureLimiter(rl),
114
+ key: typeof rl.key === 'function' ? rl.key : ({ address }) => String(address ?? 'unknown'),
115
+ failureDelayMs: rl.failureDelayMs ?? 250,
116
+ };
117
+ const methods = authMethods(auth);
118
+ const mcpHost = mcp ? createMcpHost(mcp) : null;
119
+
120
+ const ready = buildAuthorizer(auth).then((authorize) => createConnectionFactory({
121
+ authorize, execRunner, execOptions, pty: null, files: null, bindTimeoutMs, log: onLog,
122
+ methods, hostKey: null, rateLimit, extensions, mcp: mcpHost, rpc: null, gateway: null, sessions: null, relay: null,
123
+ }));
124
+ ready.catch(() => {});
125
+
126
+ const accepted = new Set();
127
+ let closed = false;
128
+
129
+ async function accept(socket, options) {
130
+ if (closed) throw new Error('createMemoryHost: host is closed');
131
+ const handle = await bindSocket(socket, ready, options);
132
+ accepted.add(handle);
133
+ return handle;
134
+ }
135
+
136
+ /** A `WebSocket` constructor that dials this host: `new host.WebSocket(url)` ignores the URL. */
137
+ class HostWebSocket extends MemorySocket {
138
+ constructor() {
139
+ super();
140
+ const [client, server] = createSocketPair();
141
+ void accept(server, { remote: { address: 'memory' } }).catch(onLog);
142
+ return client;
143
+ }
144
+ }
145
+
146
+ const host = {
147
+ /** Pass to `client.connect()`. */
148
+ url: MEMORY_URL,
149
+ WebSocket: HostWebSocket,
150
+ accept,
151
+ socketPair: createSocketPair,
152
+ /** A `WshClient` whose transport is this host (`await client.connect(host.url, ...)`). */
153
+ createClient(clientOptions = {}) {
154
+ return new WshClient({
155
+ ...clientOptions,
156
+ transportFactories: {
157
+ ws: () => new WebSocketTransport({ WebSocket: HostWebSocket }),
158
+ wt: () => { throw new Error('createMemoryHost: WebTransport is not available in memory'); },
159
+ },
160
+ });
161
+ },
162
+ /** `createClient()` and `connect()` in one: resolves to a connected client. */
163
+ async connect(credentials) {
164
+ const client = host.createClient();
165
+ await client.connect(MEMORY_URL, { transport: 'ws', ...credentials });
166
+ return client;
167
+ },
168
+ async close() {
169
+ closed = true;
170
+ for (const handle of accepted) handle.close();
171
+ accepted.clear();
172
+ },
173
+ };
174
+ return host;
175
+ }
package/src/recording.mjs CHANGED
@@ -2,8 +2,14 @@
2
2
  * Session recording and playback for wsh PTY sessions.
3
3
  *
4
4
  * Records all terminal I/O with timestamps for later replay.
5
- * The export format is compatible with the asciicast v2 structure
6
- * used by asciinema, enabling interop with standard terminal players.
5
+ * The export (`toJSON()`) is asciicast-v2-*shaped*, not an asciicast v2 file: the header
6
+ * fields (`version: 2`, `width`, `height`, `timestamp`, `env`) and the `[seconds, code, data]`
7
+ * events with the `o` / `i` / `r` codes are asciicast's, but it is one JSON document (asciicast
8
+ * v2 is newline-delimited JSON: a header line, then one event per line), the header carries
9
+ * wsh's own `sessionId`, `width`/`height` follow the latest resize rather than the start size,
10
+ * and the lifecycle events `open` / `exit` have no asciicast code. `asciinema play` therefore
11
+ * cannot read it as-is. The README ("Session recording") shows the short conversion to a real
12
+ * `.cast` file (header line + the `o`/`i`/`r` events); `fromJSON()` reads this document shape.
7
13
  */
8
14
 
9
15
  // ── SessionRecorder ──────────────────────────────────────────────────
@@ -66,16 +72,17 @@ export class SessionRecorder {
66
72
  /**
67
73
  * Export the recording as a JSON-serializable object.
68
74
  *
69
- * The format is compatible with asciicast v2:
75
+ * The shape follows asciicast v2 but this is NOT a playable asciicast file (see the file header):
70
76
  * - version: 2
71
- * - width, height: terminal dimensions at start
77
+ * - width, height: terminal dimensions as of the latest resize (asciicast: at start)
72
78
  * - timestamp: Unix epoch seconds when recording started
73
- * - env: optional environment metadata
74
- * - events: array of [time_seconds, event_type, data]
79
+ * - env: environment metadata
80
+ * - sessionId: wsh's own field
81
+ * - events: array of [time_seconds, event_type, data] -- one JSON document, not one line per event
75
82
  *
76
- * Event types in asciicast:
77
- * "o" = output, "i" = input, "r" = resize
78
- * We extend with: "open", "exit" for session lifecycle.
83
+ * Event types from asciicast:
84
+ * "o" = output, "i" = input, "r" = resize ("COLSxROWS")
85
+ * Not in asciicast, so dropped by the conversion in the README: "open", "exit" (session lifecycle).
79
86
  *
80
87
  * @returns {object}
81
88
  */
@@ -111,7 +118,8 @@ export class SessionRecorder {
111
118
  }
112
119
 
113
120
  /**
114
- * Import a recording from JSON (as produced by toJSON or parsed from asciicast).
121
+ * Import a recording from the JSON document `toJSON()` produces. An asciicast v2 `.cast` file is not read directly:
122
+ * parse its lines and gather them into `{ ...header, events }` first.
115
123
  *
116
124
  * @param {object | string} json - Recording object or JSON string
117
125
  * @returns {SessionRecorder}
@@ -13,7 +13,6 @@
13
13
  * dropped rather than forwarded to the process's stdin.
14
14
  */
15
15
 
16
- import { randomUUID } from 'node:crypto';
17
16
  import { QMuxConnection } from '../qmux-connection.mjs';
18
17
  import { FrameDecoder, frameEncode } from '../cbor.mjs';
19
18
  import {
@@ -24,8 +23,7 @@ import {
24
23
  import {
25
24
  generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
26
25
  } from '../auth.mjs';
27
- import { FILE_CHUNK_BYTES } from './fs.mjs';
28
- import { MAX_ATTACHMENTS } from './sessions.mjs';
26
+ import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
29
27
  import { MCP_CALL_ID_FEATURE } from '../client.mjs';
30
28
  import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
31
29
  import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
@@ -70,6 +68,7 @@ const REPLAY_CHUNK_BYTES = 32 * 1024;
70
68
  const USERNAME_RE = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
71
69
  const enc = new TextEncoder();
72
70
 
71
+ const randomUUID = () => crypto.randomUUID();
73
72
  const randomBytes = (n) => crypto.getRandomValues(new Uint8Array(n));
74
73
  const toBytes = (d) => (typeof d === 'string' ? enc.encode(d) : d);
75
74
 
@@ -831,7 +830,7 @@ export function createConnectionFactory(cfg) {
831
830
  const args = m.command ? ['-c', String(m.command)] : [];
832
831
  proc = p.spawn(p.shell, args, {
833
832
  name: p.term, cols, rows, cwd: p.cwd,
834
- env: { ...(p.env ?? process.env), TERM: p.term, ...(m.env && typeof m.env === 'object' ? m.env : {}) },
833
+ env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...(m.env && typeof m.env === 'object' ? m.env : {}) },
835
834
  });
836
835
  } catch (e) {
837
836
  return send(openFail({ reason: `pty spawn failed: ${e.message}` }));
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Limits shared by the connection handler and the Node-only modules that also export them
3
+ * (kept here so the connection handler imports nothing from `node:*` -- see `src/memory-host.mjs`).
4
+ */
5
+
6
+ /** Size of one FileChunk when a file is streamed to the client. */
7
+ export const FILE_CHUNK_BYTES = 64 * 1024;
8
+
9
+ /** Most clients attached to one detached-session at once. */
10
+ export const MAX_ATTACHMENTS = 16;
package/src/server/fs.mjs CHANGED
@@ -14,7 +14,8 @@ import { constants as fsc } from 'node:fs';
14
14
  import path from 'node:path';
15
15
 
16
16
  export const DEFAULT_MAX_FILE_BYTES = 64 * 1024 * 1024;
17
- export const FILE_CHUNK_BYTES = 64 * 1024;
17
+ import { FILE_CHUNK_BYTES } from './constants.mjs';
18
+ export { FILE_CHUNK_BYTES };
18
19
 
19
20
  /**
20
21
  * @param {{ root: string, readOnly?: boolean, maxFileBytes?: number }} opts
@@ -22,10 +22,15 @@
22
22
  * the host would have to resolve the name itself.
23
23
  */
24
24
 
25
- import net from 'node:net';
26
- import dns from 'node:dns/promises';
27
25
  import { MSG, gatewayOk, gatewayFail, gatewayClose, gatewayData, dnsResult, listenFail } from '../messages.gen.mjs';
28
26
 
27
+ // Loaded on first use so that importing the connection handler (which serves the gateway opcodes)
28
+ // does not pull `node:net` into a browser bundle (see `src/memory-host.mjs`).
29
+ let netModule = null;
30
+ let dnsModule = null;
31
+ const loadNet = async () => (netModule ??= (await import('node:net')).default);
32
+ const loadDns = async () => (dnsModule ??= (await import('node:dns/promises')).default);
33
+
29
34
  /** Numeric codes of GatewayFail (the same table `@johnhenry/browsermesh-netway` decodes). */
30
35
  export const GATEWAY_FAIL = Object.freeze({
31
36
  CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
@@ -62,7 +67,8 @@ export function destinationAllowed(allow, host, port) {
62
67
  * Resolves with the connected socket, or rejects with an Error carrying `.code`
63
68
  * (a GATEWAY_FAIL value).
64
69
  */
65
- export function socksConnect(proxy, host, port, { timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS } = {}) {
70
+ export async function socksConnect(proxy, host, port, { timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS } = {}) {
71
+ const net = await loadNet();
66
72
  return new Promise((resolve, reject) => {
67
73
  const name = Buffer.from(host, 'utf8');
68
74
  const fail = (code, message, sock) => { sock?.destroy(); const e = new Error(message); e.code = code; reject(e); };
@@ -161,6 +167,7 @@ export function createGatewaySession(cfg, send, log = () => {}) {
161
167
  pending.add(id);
162
168
  let sock;
163
169
  try {
170
+ const net = await loadNet();
164
171
  if (cfg.socks) sock = await socksConnect(cfg.socks, m.host, m.port, { timeoutMs: cfg.connectTimeoutMs });
165
172
  else {
166
173
  sock = await new Promise((resolve, reject) => {
@@ -202,7 +209,7 @@ export function createGatewaySession(cfg, send, log = () => {}) {
202
209
  try {
203
210
  const family = m.record_type === 'AAAA' ? 6 : m.record_type === 'A' || m.record_type === undefined ? 4 : 0;
204
211
  if (!family) return fail(id, GATEWAY_FAIL.DNS_FAILED, `unsupported record type ${String(m.record_type).slice(0, 8)}`);
205
- const addresses = (await dns.lookup(m.name, { family, all: true })).map((a) => a.address);
212
+ const addresses = (await (await loadDns()).lookup(m.name, { family, all: true })).map((a) => a.address);
206
213
  return reply(dnsResult({ gatewayId: id, addresses }));
207
214
  } catch (e) {
208
215
  return fail(id, GATEWAY_FAIL.DNS_FAILED, String(e.code === 'ENOTFOUND' ? 'name not found' : e.message).slice(0, 200));
@@ -402,9 +402,32 @@ export interface WshServerAddress {
402
402
  port: number;
403
403
  }
404
404
 
405
+ /**
406
+ * An already-accepted WebSocket-like duplex: `send(bytes)`, `close(code?)`, `readyState` (1 = open), and either Node-style
407
+ * `on(event, fn)` or `addEventListener(event, fn)`. A `ws` socket, a browser/Worker `WebSocket`, or a test double.
408
+ */
409
+ export interface WshAcceptableSocket {
410
+ send(data: Uint8Array): void;
411
+ close(code?: number): void;
412
+ readonly readyState: number;
413
+ on?(event: string, listener: (...args: any[]) => void): unknown;
414
+ addEventListener?(event: string, listener: (ev: any) => void): unknown;
415
+ }
416
+
417
+ export interface WshAcceptOptions {
418
+ /** What the embedder knows of the peer; `address` keys the password-failure throttle. */
419
+ remote?: { address?: string; headers?: Record<string, unknown> };
420
+ }
421
+
405
422
  export interface WshServer {
406
423
  /** Start listening. Requires the `ws` package. */
407
424
  listen(): Promise<WshServerAddress>;
425
+ /**
426
+ * Serve a pre-upgraded transport -- a socket your own HTTP server, Worker or test already accepted -- with this
427
+ * server's auth, features and sessions, so no listener of wsh's own is needed (`listen()` is optional).
428
+ * Resolves once the connection is attached; the handle's `close()` drops it. `close()` of the server drops all of them.
429
+ */
430
+ accept(socket: WshAcceptableSocket, options?: WshAcceptOptions): Promise<{ close(): void }>;
408
431
  /** Drop every connection and stop listening. */
409
432
  close(): Promise<void>;
410
433
  /** The bound address, or `null` when not listening. */
@@ -17,6 +17,7 @@ import { startWebTransport } from './webtransport.mjs';
17
17
  import { createConnectionFactory, STREAM_ANNOUNCE } from './connection.mjs';
18
18
  import { normalizeGateway } from './gateway.mjs';
19
19
  import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
20
+ import { bindSocket } from './socket.mjs';
20
21
 
21
22
  export { parseAuthorizedKeys, STREAM_ANNOUNCE, mcpServerAdapter };
22
23
  export { createReverseHost } from './reverse-host.mjs';
@@ -74,7 +75,7 @@ export { generateSelfSignedCertificate } from './self-signed.mjs';
74
75
  * through a SOCKS5 proxy (Tor) with the name unresolved. UDP and reverse tunnels are refused. Off unless given. See `gateway.mjs`.
75
76
  * @param {number} [options.bindTimeoutMs=3000]
76
77
  * @param {(line: string) => void} [options.onLog]
77
- * @returns {{ listen(): Promise<{address: string, port: number}>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
78
+ * @returns {{ listen(): Promise<{address: string, port: number}>, accept(socket: object, options?: object): Promise<{ close(): void }>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
78
79
  */
79
80
  export function createWshServer({
80
81
  host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, onLog = () => {},
@@ -102,15 +103,13 @@ export function createWshServer({
102
103
  const gatewayCfg = gateway === undefined ? null : normalizeGateway(gateway);
103
104
  const sessionOptions = sessions ? (sessions === true ? {} : sessions) : null;
104
105
 
105
- return {
106
- async listen() {
107
- if (wss) throw new Error('createWshServer: already listening');
108
- let WebSocketServer;
109
- try {
110
- ({ WebSocketServer } = await import('ws'));
111
- } catch (err) {
112
- throw new Error('@johnhenry/wsh/server needs the "ws" package: npm install ws', { cause: err });
113
- }
106
+ /** Sockets handed to `accept()` that are still open. */
107
+ const accepted = new Set();
108
+ /** The connection factory, built once on first use (`listen()` or `accept()`) and torn down by `close()`. */
109
+ let ready = null;
110
+
111
+ function start() {
112
+ ready ??= (async () => {
114
113
  const authorize = await buildAuthorizer(auth);
115
114
  host_ = hostKey ? await loadHostKey(hostKey) : null;
116
115
  if (sessionOptions) {
@@ -125,10 +124,25 @@ export function createWshServer({
125
124
  }
126
125
  if (relay) hub = new RelayHub({ ...relay, log: onLog });
127
126
  if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createWshServer: extensions must be an object of handlers');
128
- const attach = createConnectionFactory({
127
+ return createConnectionFactory({
129
128
  authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, log: onLog,
130
129
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, sessions: registry, relay: hub,
131
130
  });
131
+ })();
132
+ ready.catch(() => { ready = null; });
133
+ return ready;
134
+ }
135
+
136
+ return {
137
+ async listen() {
138
+ if (wss) throw new Error('createWshServer: already listening');
139
+ let WebSocketServer;
140
+ try {
141
+ ({ WebSocketServer } = await import('ws'));
142
+ } catch (err) {
143
+ throw new Error('@johnhenry/wsh/server needs the "ws" package: npm install ws', { cause: err });
144
+ }
145
+ const attach = await start();
132
146
 
133
147
  if (tls) {
134
148
  const { createServer } = await import('node:https');
@@ -172,20 +186,45 @@ export function createWshServer({
172
186
  return bound;
173
187
  },
174
188
 
189
+ /**
190
+ * Serve a pre-upgraded transport: an already-accepted WebSocket-like duplex (see `socket.mjs`) that the embedder's
191
+ * own HTTP server, Worker or test upgraded. Same auth, features and session registry as `listen()`'s connections, and
192
+ * no listener of this server's own is needed -- `accept()` works without `listen()`, and with both.
193
+ * `remote: { address, headers }` is what the embedder knows of the peer (`address` keys the password-failure throttle).
194
+ * `close()` drops every accepted socket. Resolves once the connection is attached.
195
+ *
196
+ * @param {object} socket - `send`, `close`, `readyState`, and `on` or `addEventListener`
197
+ * @param {{ remote?: { address?: string, headers?: object } }} [options]
198
+ * @returns {Promise<{ close(): void }>}
199
+ */
200
+ async accept(socket, options = {}) {
201
+ const handle = await bindSocket(socket, start(), options);
202
+ const entry = { socket, handle };
203
+ accepted.add(entry);
204
+ const forget = () => accepted.delete(entry);
205
+ if (typeof socket.addEventListener === 'function') socket.addEventListener('close', forget);
206
+ else socket.on('close', forget);
207
+ return handle;
208
+ },
209
+
175
210
  async close() {
176
- if (!wss) return;
211
+ for (const entry of [...accepted]) entry.handle.close();
212
+ accepted.clear();
177
213
  const server = wss;
178
214
  wss = null;
179
215
  bound = null;
180
- for (const client of server.clients) client.terminate();
181
- await wt?.close();
182
- wt = null;
183
- await new Promise((resolve) => server.close(resolve));
184
- if (httpsServer) { const h = httpsServer; httpsServer = null; await new Promise((resolve) => h.close(resolve)); }
216
+ if (server) {
217
+ for (const client of server.clients) client.terminate();
218
+ await wt?.close();
219
+ wt = null;
220
+ await new Promise((resolve) => server.close(resolve));
221
+ if (httpsServer) { const h = httpsServer; httpsServer = null; await new Promise((resolve) => h.close(resolve)); }
222
+ }
185
223
  registry?.closeAll();
186
224
  registry = null;
187
225
  hub?.closeAll();
188
226
  hub = null;
227
+ ready = null;
189
228
  },
190
229
 
191
230
  address() {
@@ -17,7 +17,7 @@ export function normalizePty(pty) {
17
17
  }
18
18
  return {
19
19
  spawn: pty.spawn,
20
- shell: pty.shell ?? process.env.SHELL ?? '/bin/sh',
20
+ shell: pty.shell ?? globalThis.process?.env?.SHELL ?? '/bin/sh',
21
21
  cwd: pty.cwd,
22
22
  env: pty.env,
23
23
  term: pty.term ?? 'xterm-256color',
@@ -20,7 +20,8 @@ import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypt
20
20
  export const DEFAULT_RING_BYTES = 1024 * 1024;
21
21
  export const DEFAULT_DETACH_TTL_MS = 300_000;
22
22
  export const DEFAULT_MAX_DETACHED = 16;
23
- export const MAX_ATTACHMENTS = 16;
23
+ import { MAX_ATTACHMENTS } from './constants.mjs';
24
+ export { MAX_ATTACHMENTS };
24
25
 
25
26
  const NO_EXPIRY = Buffer.alloc(8, 0xff);
26
27
 
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Serve a pre-upgraded transport: an already-accepted WebSocket-like duplex handed to a host by whoever did the
3
+ * upgrade (an HTTP server of the embedder's, a Worker, a message port wrapper, a test). Browser-safe -- it touches
4
+ * nothing but the object it is given -- and shared by `createWshServer().accept()` and `createMemoryHost()`.
5
+ *
6
+ * The duplex needs `send(bytes)`, `close(code?)`, `readyState` (1 = open) and either Node-style `on(event, fn)`
7
+ * (`ws`) or `addEventListener(event, fn)` (browsers, Workers, undici). Incoming frames must be binary; a text frame
8
+ * is ignored, as the QMux framing never carries one.
9
+ */
10
+
11
+ const OPEN = 1;
12
+
13
+ /** @param {unknown} data - a message payload as `ws` (Buffer, ArrayBuffer, Buffer[]) or a browser (ArrayBuffer, view, Blob) delivers it */
14
+ async function toBytes(data) {
15
+ if (data instanceof Uint8Array) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
16
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
17
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
18
+ if (Array.isArray(data)) {
19
+ const parts = await Promise.all(data.map(toBytes));
20
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.byteLength, 0));
21
+ let off = 0;
22
+ for (const p of parts) { out.set(p, off); off += p.byteLength; }
23
+ return out;
24
+ }
25
+ if (data && typeof data.arrayBuffer === 'function') return new Uint8Array(await data.arrayBuffer());
26
+ return null;
27
+ }
28
+
29
+ /**
30
+ * @param {object} socket - the WebSocket-like duplex
31
+ * @param {Promise<(opts: object) => { receive: Function, close: Function }>} ready - resolves to the connection factory's `attach`
32
+ * @param {{ remote?: { address?: string, headers?: object } }} [options] - what the host knows about the peer
33
+ * (`address` keys the password-failure throttle; the default key is shared by every socket without one)
34
+ * @returns {Promise<{ close(): void }>} resolves once the connection is attached; `close()` drops it
35
+ */
36
+ export function bindSocket(socket, ready, { remote = {} } = {}) {
37
+ if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') {
38
+ throw new TypeError('accept: socket must be a WebSocket-like duplex with send() and close()');
39
+ }
40
+ const listen = typeof socket.addEventListener === 'function'
41
+ ? (event, fn) => socket.addEventListener(event, (ev) => fn(event === 'message' ? ev?.data : ev))
42
+ : typeof socket.on === 'function'
43
+ ? (event, fn) => socket.on(event, fn)
44
+ : null;
45
+ if (!listen) throw new TypeError('accept: socket must support addEventListener() or on()');
46
+ try { socket.binaryType = 'arraybuffer'; } catch { /* read-only on some implementations; toBytes copes with any */ }
47
+
48
+ // Listeners are attached now, before the host has finished starting, and the frames they see are
49
+ // chained behind `ready`: a peer that speaks first (a client's QMux handshake) is not dropped.
50
+ let conn = null;
51
+ let closed = false;
52
+ let chain = ready.then((attach) => {
53
+ if (closed) return;
54
+ conn = attach({
55
+ send: (bytes) => { if (socket.readyState === OPEN) socket.send(bytes); },
56
+ remote: { address: remote.address, headers: remote.headers ?? {} },
57
+ closeTransport: () => { try { socket.close(1000); } catch { /* already closed */ } },
58
+ });
59
+ });
60
+ const drop = () => { if (closed) return; closed = true; chain = chain.then(() => conn?.close()).catch(() => {}); };
61
+ listen('message', (data) => {
62
+ chain = chain.then(async () => {
63
+ if (closed || !conn) return;
64
+ const bytes = await toBytes(data);
65
+ if (bytes && !closed) conn.receive(bytes);
66
+ }).catch(() => {});
67
+ });
68
+ listen('close', drop);
69
+ listen('error', () => {});
70
+ return chain.then(() => ({
71
+ close() { drop(); try { socket.close(1000); } catch { /* already closed */ } },
72
+ }));
73
+ }