@johnhenry/wsh 0.34.2 → 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 +121 -8
- package/package.json +14 -1
- package/src/client.mjs +3 -22
- package/src/features.mjs +28 -0
- package/src/host-backends.mjs +100 -0
- package/src/host.d.ts +146 -0
- package/src/host.mjs +30 -0
- package/src/memory-host.d.ts +50 -2
- package/src/memory-host.mjs +72 -11
- package/src/reverse-host.d.ts +25 -0
- package/src/reverse-host.mjs +228 -0
- package/src/server/backends.mjs +10 -16
- package/src/server/connection.mjs +37 -13
- package/src/server/constants.mjs +3 -0
- package/src/server/fs.mjs +2 -3
- package/src/server/index.d.ts +6 -0
- package/src/server/index.mjs +2 -2
- package/src/server/reverse-host.mjs +7 -213
- package/src/server/sessions.mjs +10 -230
- package/src/server/socket.mjs +25 -4
- package/src/session-registry.mjs +255 -0
package/src/memory-host.d.ts
CHANGED
|
@@ -1,17 +1,65 @@
|
|
|
1
|
-
import type { WshClient } from './index.js';
|
|
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
|
|
|
9
|
+
export interface WshMemorySessionsOptions {
|
|
10
|
+
/** How long a session nobody is attached to keeps running (default 300000; 0 = kill at once). */
|
|
11
|
+
detachTtlMs?: number;
|
|
12
|
+
/** Unattended sessions kept at once (default 16); beyond that the longest-detached is killed. */
|
|
13
|
+
maxDetached?: number;
|
|
14
|
+
/** Output history kept per session, i.e. what a resume can replay (default 1048576 bytes). */
|
|
15
|
+
ringBytes?: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** What an rpc handler is told about its channel. */
|
|
19
|
+
export interface WshMemoryRpcContext {
|
|
20
|
+
protocol: string;
|
|
21
|
+
channelId: number;
|
|
22
|
+
user: string | null;
|
|
23
|
+
fingerprint: string | null;
|
|
24
|
+
features: string[];
|
|
25
|
+
log(line: string): void;
|
|
26
|
+
[key: string]: unknown;
|
|
27
|
+
}
|
|
28
|
+
|
|
8
29
|
export interface WshMemoryHostOptions {
|
|
9
30
|
/** As for `createWshServer`. Omitted = refuse everyone. */
|
|
10
31
|
auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>);
|
|
11
32
|
/** `run(command, io)`; there is no shell in memory, so there is no `true`. */
|
|
12
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;
|
|
13
50
|
mcp?: WshServerMcpOptions;
|
|
14
51
|
extensions?: WshServerOptions['extensions'];
|
|
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. */
|
|
53
|
+
rpc?: Record<string, ((channel: RpcChannel, ctx: WshMemoryRpcContext) => void | Promise<void>) | false | null | undefined>;
|
|
54
|
+
/** Largest single rpc message (default 1048576; at least 256). */
|
|
55
|
+
rpcMaxMessageBytes?: number;
|
|
56
|
+
/** Concurrent requests per rpc channel before `-32002` (default 64). */
|
|
57
|
+
rpcMaxInflight?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Keep exec sessions alive across disconnects so `resumeSession()` / `attachSession()` work, with the same
|
|
60
|
+
* defaults as `createWshServer`. `true` for the defaults. Off unless given.
|
|
61
|
+
*/
|
|
62
|
+
sessions?: true | false | null | WshMemorySessionsOptions;
|
|
15
63
|
bindTimeoutMs?: number;
|
|
16
64
|
onLog?: (line: string) => void;
|
|
17
65
|
}
|
package/src/memory-host.mjs
CHANGED
|
@@ -6,8 +6,16 @@
|
|
|
6
6
|
* It is the real protocol end to end -- the same connection handler `createWshServer` runs (handshake, Ed25519 or
|
|
7
7
|
* password auth, exec channels, MCP tools, extensions), speaking QMux over a pair of in-memory WebSocket-like
|
|
8
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
|
|
10
|
-
* `sessions
|
|
9
|
+
* function you provide (there is no shell), `mcp` tools, `extensions`, typed `rpc` channels (handler functions you
|
|
10
|
+
* provide) and `sessions` (detach / attach / resume of exec sessions, output replayed from an in-memory ring buffer).
|
|
11
|
+
* Backends are injected, shaped like the Node host's: `pty` (`{ spawn }`, node-pty shaped), `fs` (an object of file
|
|
12
|
+
* operations, not a root path), `hostKey` (a `CryptoKeyPair`, which may be non-extractable, or a signer
|
|
13
|
+
* `{ publicKey, sign }`).
|
|
14
|
+
* Not available: `gateway`, `relay`, WebTransport, `exec: true` and `fs: { root }` (they need Node), the `wsh-host` /
|
|
15
|
+
* `wsh-fs` rpc built-ins (use `@johnhenry/wsh/server`).
|
|
16
|
+
*
|
|
17
|
+
* To serve a socket someone else upgraded (a WebSocket the page opened to a relay, a byte pipe) use `host.accept(socket)`;
|
|
18
|
+
* a peer that cannot open QMux data streams (the released Rust client over WebSocket) needs `dataStreams: false`.
|
|
11
19
|
*
|
|
12
20
|
* ```js
|
|
13
21
|
* import { createMemoryHost } from '@johnhenry/wsh/memory';
|
|
@@ -23,8 +31,10 @@ import { WshClient } from './client.mjs';
|
|
|
23
31
|
import { WebSocketTransport } from './transport-ws.mjs';
|
|
24
32
|
import { createConnectionFactory } from './server/connection.mjs';
|
|
25
33
|
import { buildAuthorizer, authMethods, FailureLimiter } from './server/auth.mjs';
|
|
26
|
-
import {
|
|
34
|
+
import { resolveBackends, resolveHostKey } from './host-backends.mjs';
|
|
27
35
|
import { bindSocket } from './server/socket.mjs';
|
|
36
|
+
import { RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
|
|
37
|
+
import { SessionRegistry, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED } from './session-registry.mjs';
|
|
28
38
|
|
|
29
39
|
const CONNECTING = 0;
|
|
30
40
|
const OPEN = 1;
|
|
@@ -90,24 +100,75 @@ export function createSocketPair() {
|
|
|
90
100
|
return [a, b];
|
|
91
101
|
}
|
|
92
102
|
|
|
103
|
+
/** Validate the `rpc` option into the table the connection handler reads (`createRpcHost` in `server/rpc.mjs` minus the Node-only built-ins). */
|
|
104
|
+
function createRpcTable(rpc, maxMessageBytes, maxInflight) {
|
|
105
|
+
if (typeof rpc !== 'object' || Array.isArray(rpc)) throw new TypeError('createMemoryHost: rpc must be an object of { [protocol]: handler }');
|
|
106
|
+
if (!(maxMessageBytes >= 256)) throw new TypeError('createMemoryHost: rpcMaxMessageBytes must be at least 256');
|
|
107
|
+
if (!Number.isSafeInteger(maxInflight) || maxInflight < 1) throw new TypeError('createMemoryHost: rpcMaxInflight must be a positive integer');
|
|
108
|
+
const protocols = new Map();
|
|
109
|
+
for (const [name, handler] of Object.entries(rpc)) {
|
|
110
|
+
if (handler === undefined || handler === false || handler === null) continue;
|
|
111
|
+
if (!RPC_PROTOCOL_NAME_RE.test(name)) throw new TypeError(`createMemoryHost: rpc protocol name ${JSON.stringify(name)} is not allowed (letters, digits, ".", "_", "-")`);
|
|
112
|
+
if (typeof handler !== 'function') throw new TypeError(`createMemoryHost: rpc[${JSON.stringify(name)}] needs a handler function (channel, ctx) => void (the wsh-host / wsh-fs built-ins need Node; use @johnhenry/wsh/server)`);
|
|
113
|
+
protocols.set(name, handler);
|
|
114
|
+
}
|
|
115
|
+
return { protocols, maxMessageBytes, maxInflight };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function createRegistry(sessions, log) {
|
|
119
|
+
const o = sessions === true ? {} : sessions;
|
|
120
|
+
if (typeof o !== 'object' || Array.isArray(o)) throw new TypeError('createMemoryHost: sessions must be true or { detachTtlMs, maxDetached, ringBytes }');
|
|
121
|
+
const { detachTtlMs = DEFAULT_DETACH_TTL_MS, maxDetached = DEFAULT_MAX_DETACHED, ringBytes = DEFAULT_RING_BYTES } = o;
|
|
122
|
+
if (!(Number.isFinite(detachTtlMs) && detachTtlMs >= 0)) throw new TypeError('createMemoryHost: sessions.detachTtlMs must be a non-negative number');
|
|
123
|
+
if (!Number.isSafeInteger(maxDetached) || maxDetached < 0) throw new TypeError('createMemoryHost: sessions.maxDetached must be a non-negative integer');
|
|
124
|
+
if (!Number.isSafeInteger(ringBytes) || ringBytes < 1) throw new TypeError('createMemoryHost: sessions.ringBytes must be a positive integer');
|
|
125
|
+
return new SessionRegistry({ detachTtlMs, maxDetached, ringBytes, log });
|
|
126
|
+
}
|
|
127
|
+
|
|
93
128
|
/**
|
|
94
129
|
* @param {object} [options]
|
|
95
130
|
* @param {object | Function} [options.auth] - As for `createWshServer`. Omitted = refuse everyone.
|
|
96
131
|
* @param {Function | { run: Function, timeoutMs?: number, clientEnv?: boolean }} [options.exec]
|
|
97
132
|
* `run(command, io) => Promise<exitCode>` (see `ExecIo` in `server/exec.mjs`): the host has no shell, so there is no `true`.
|
|
133
|
+
* @param {{ spawn: Function, shell?: string, cwd?: string, env?: object, term?: string }} [options.pty]
|
|
134
|
+
* `pty.spawn(file, args, { name, cols, rows, cwd, env })` as `node-pty`'s `spawn` (or anything shaped like it) returns
|
|
135
|
+
* `{ onData(cb), onExit(cb), write(data), resize(cols, rows), kill(signal?) }`. Input arrives at `write` as a `Uint8Array`.
|
|
136
|
+
* `shell` is the `file` it is called with (default `/bin/sh`: name the program your `spawn` understands).
|
|
137
|
+
* @param {{ operate: Function, readWhole: Function, writeWhole: Function, writeAt: Function, openRange?: Function, maxFileBytes?: number }} [options.fs]
|
|
138
|
+
* File operations, as `createFileAccess` in `@johnhenry/wsh/server` returns them (see `normalizeFileBackend` in
|
|
139
|
+
* `host-backends.mjs`). Not a root path: confining paths is the backend's job.
|
|
140
|
+
* @param {true | CryptoKeyPair | { publicKey: Uint8Array | CryptoKey, sign: Function }} [options.hostKey]
|
|
141
|
+
* This host's own identity, so clients can pin it (TOFU): a `CryptoKeyPair` (non-extractable is fine), a signer
|
|
142
|
+
* `{ publicKey, sign(data) }`, or `true` for a fresh non-extractable key.
|
|
143
|
+
* @param {boolean} [options.dataStreams=true] - Offer client-opened QMux data streams for exec output (`stream-announce`,
|
|
144
|
+
* rpc). Set `false` for a peer that cannot open them -- the released Rust client over WebSocket -- so exec output rides
|
|
145
|
+
* `SessionData` instead (and `rpc` is not offered). The released clients state nothing in their `Hello` that a host could
|
|
146
|
+
* key an automatic choice on, so this is an option; `accept(socket, { dataStreams })` overrides it per connection.
|
|
98
147
|
* @param {{ tools?: object[] | object, client?: object, authorize?: Function, maxConcurrent?: number, timeoutMs?: number }} [options.mcp]
|
|
99
148
|
* @param {Record<string, Function>} [options.extensions] - Handlers for application-defined messages, as for `createWshServer`.
|
|
149
|
+
* @param {Record<string, Function>} [options.rpc] - Typed RPC channels: `{ [protocol]: (channel, ctx) => void | Promise<void> }`,
|
|
150
|
+
* a handler per protocol that registers methods on an `RpcChannel`. Off unless given. Handler functions only (no built-ins).
|
|
151
|
+
* @param {number} [options.rpcMaxMessageBytes=1048576] - Largest single rpc message (advertised as `rpc-max-message:<n>`; at least 256).
|
|
152
|
+
* @param {number} [options.rpcMaxInflight=64] - Concurrent requests per rpc channel before `-32002`.
|
|
153
|
+
* @param {true | { detachTtlMs?: number, maxDetached?: number, ringBytes?: number }} [options.sessions]
|
|
154
|
+
* Keep exec sessions alive across disconnects so a client can `resumeSession()` / `attachSession()`: as for
|
|
155
|
+
* `createWshServer`, with the same defaults (300000 ms detached, 16 detached sessions, 1 MiB of replayable output
|
|
156
|
+
* per session). Off unless given: sessions then die with their connection. There is no `sessionSecret`: session
|
|
157
|
+
* tokens are random per session.
|
|
100
158
|
* @param {number} [options.bindTimeoutMs=3000]
|
|
101
159
|
* @param {(line: string) => void} [options.onLog]
|
|
102
160
|
*/
|
|
103
|
-
export function createMemoryHost({ auth, exec, mcp, extensions, bindTimeoutMs = 3000, onLog = () => {} } = {}) {
|
|
161
|
+
export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, dataStreams = true, bindTimeoutMs = 3000, onLog = () => {} } = {}) {
|
|
104
162
|
if (exec === true) throw new TypeError('createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with');
|
|
105
163
|
if (exec !== undefined && typeof exec !== 'function' && typeof exec?.run !== 'function') {
|
|
106
164
|
throw new TypeError('createMemoryHost: exec must be a function or { run }');
|
|
107
165
|
}
|
|
108
166
|
if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createMemoryHost: extensions must be an object of handlers');
|
|
109
|
-
|
|
110
|
-
const
|
|
167
|
+
if (typeof dataStreams !== 'boolean') throw new TypeError('createMemoryHost: dataStreams must be true or false');
|
|
168
|
+
const rpcHost = rpc === undefined || rpc === null ? null : createRpcTable(rpc, rpcMaxMessageBytes, rpcMaxInflight);
|
|
169
|
+
const registry = sessions === undefined || sessions === null || sessions === false ? null : createRegistry(sessions, onLog);
|
|
170
|
+
const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost } = resolveBackends({ exec, pty, fs, mcp });
|
|
171
|
+
const hostKeyReady = hostKey === undefined || hostKey === null || hostKey === false ? Promise.resolve(null) : resolveHostKey(hostKey, 'createMemoryHost: hostKey');
|
|
111
172
|
const rl = auth?.rateLimit ?? {};
|
|
112
173
|
const rateLimit = {
|
|
113
174
|
limiter: new FailureLimiter(rl),
|
|
@@ -115,11 +176,10 @@ export function createMemoryHost({ auth, exec, mcp, extensions, bindTimeoutMs =
|
|
|
115
176
|
failureDelayMs: rl.failureDelayMs ?? 250,
|
|
116
177
|
};
|
|
117
178
|
const methods = authMethods(auth);
|
|
118
|
-
const mcpHost = mcp ? createMcpHost(mcp) : null;
|
|
119
179
|
|
|
120
|
-
const ready = buildAuthorizer(auth).then((authorize) => createConnectionFactory({
|
|
121
|
-
authorize, execRunner, execOptions, pty:
|
|
122
|
-
methods, hostKey:
|
|
180
|
+
const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
|
|
181
|
+
authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, log: onLog,
|
|
182
|
+
methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: null, sessions: registry, relay: null,
|
|
123
183
|
}));
|
|
124
184
|
ready.catch(() => {});
|
|
125
185
|
|
|
@@ -128,7 +188,7 @@ export function createMemoryHost({ auth, exec, mcp, extensions, bindTimeoutMs =
|
|
|
128
188
|
|
|
129
189
|
async function accept(socket, options) {
|
|
130
190
|
if (closed) throw new Error('createMemoryHost: host is closed');
|
|
131
|
-
const handle = await bindSocket(socket, ready, options);
|
|
191
|
+
const handle = await bindSocket(socket, ready, { dataStreams, ...options });
|
|
132
192
|
accepted.add(handle);
|
|
133
193
|
return handle;
|
|
134
194
|
}
|
|
@@ -169,6 +229,7 @@ export function createMemoryHost({ auth, exec, mcp, extensions, bindTimeoutMs =
|
|
|
169
229
|
closed = true;
|
|
170
230
|
for (const handle of accepted) handle.close();
|
|
171
231
|
accepted.clear();
|
|
232
|
+
registry?.closeAll();
|
|
172
233
|
},
|
|
173
234
|
};
|
|
174
235
|
return host;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshReverseHostOptions, WshReverseHost } from './server/index.js';
|
|
2
|
+
import type { WshFileBackend } from './host.js';
|
|
3
|
+
|
|
4
|
+
export type { WshReverseHost } from './server/index.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Options of the browser-safe `createReverseHost`: those of `@johnhenry/wsh/server`'s, with the backends that need
|
|
8
|
+
* Node taken out (`exec: true` and `fs: { root }`).
|
|
9
|
+
*/
|
|
10
|
+
export interface WshBrowserReverseHostOptions extends Omit<WshReverseHostOptions, 'exec' | 'fs' | 'pty' | 'mcp'> {
|
|
11
|
+
/** `run(command, io)` or `{ run }`: there is no shell in a browser to run `true` with. */
|
|
12
|
+
exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
|
|
13
|
+
/** `node-pty`-shaped `{ spawn }`, injected. Input arrives at `write` as a `Uint8Array`. */
|
|
14
|
+
pty?: WshServerPtyOptions;
|
|
15
|
+
/** An object of file operations, not a root path. */
|
|
16
|
+
fs?: WshFileBackend;
|
|
17
|
+
mcp?: WshServerMcpOptions;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A host that dials OUT to a relay (`createWshServer({ relay })`) and serves the operator it bridges to it, in a page
|
|
22
|
+
* or a Worker: `createReverseHost` of `@johnhenry/wsh/server` without the Node-only backends, so it imports nothing from
|
|
23
|
+
* `node:*`. The relay needs the page's WebSocket (`connect` options are the client's).
|
|
24
|
+
*/
|
|
25
|
+
export function createReverseHost(options: WshBrowserReverseHostOptions): WshReverseHost;
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A reverse host: this process dials OUT to a relay (`createWshServer({ relay })`),
|
|
3
|
+
* registers itself as a peer, and serves whichever operator the relay bridges to
|
|
4
|
+
* it -- with the same exec / pty / fs / mcp backends `createWshServer` serves
|
|
5
|
+
* direct clients with. Use it for a machine that cannot accept connections.
|
|
6
|
+
*
|
|
7
|
+
* The relay has already authenticated the operator (its key), so the bridged
|
|
8
|
+
* connection is pre-authenticated; what a relay-asserted identity is worth is
|
|
9
|
+
* yours to decide in `accept`, which defaults to refusing everyone.
|
|
10
|
+
*
|
|
11
|
+
* One operator at a time by default. With `maxOperators` > 1 (and a relay
|
|
12
|
+
* configured with `relay.maxOperatorsPerPeer`) several operators are served at
|
|
13
|
+
* once, each with its own connection state -- channels, processes, files -- and
|
|
14
|
+
* when one leaves only what belongs to it is cleaned up (wsh #89).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { WshClient } from './client.mjs';
|
|
18
|
+
import { exportPublicKeyRaw, fingerprint } from './auth.mjs';
|
|
19
|
+
import { reverseAccept, reverseReject } from './messages.gen.mjs';
|
|
20
|
+
import { MULTI_OPERATOR_FEATURE } from './server/relay.mjs';
|
|
21
|
+
import { E2E_SIGN_FEATURE } from './e2e-exchange.mjs';
|
|
22
|
+
import { resolveBackends } from './host-backends.mjs';
|
|
23
|
+
import { createConnectionFactory, hostFeatures } from './server/connection.mjs';
|
|
24
|
+
|
|
25
|
+
const BACKOFF_START_MS = 500;
|
|
26
|
+
const BACKOFF_MAX_MS = 30_000;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {object} options
|
|
30
|
+
* @param {string} options.url - The relay (`ws://` or `wss://`).
|
|
31
|
+
* @param {string} options.username
|
|
32
|
+
* @param {CryptoKeyPair} options.keyPair - This host's identity; its fingerprint is what operators connect to.
|
|
33
|
+
* @param {(operator: { fingerprint: string, username: string }) => boolean | Promise<boolean>} [options.accept]
|
|
34
|
+
* Who may be bridged to this host. Default: nobody.
|
|
35
|
+
* @param {true | object | Function} [options.exec]
|
|
36
|
+
* @param {object} [options.pty]
|
|
37
|
+
* @param {object} [options.fs]
|
|
38
|
+
* @param {object} [options.mcp]
|
|
39
|
+
* @param {boolean} [options.reconnect=true] - Dial again (with backoff) after the relay connection ends. A relay ends it when a bridge does.
|
|
40
|
+
* @param {object} [options.connect] - Extra options for the relay connection (`expectHostKey`, `knownHosts`, ...).
|
|
41
|
+
* @param {string} [options.peerType='host']
|
|
42
|
+
* @param {false | { sign?: boolean | 'auto', hybrid?: boolean }} [options.e2e] - End-to-end encryption for the bridged operator (wsh #90).
|
|
43
|
+
* On by default: this host answers an operator's `KeyExchange` (for a session it has opened), then seals that
|
|
44
|
+
* session's output and opens its input as `EncryptedFrame`s the relay cannot read, and ignores plaintext input for it.
|
|
45
|
+
* `sign` signs the reply with `keyPair` so the operator can authenticate this host
|
|
46
|
+
* (`initiateE2E(..., { verifyPeer })`). Default `'auto'`: sign when the relay says (`e2e-sign` in its ServerHello) it
|
|
47
|
+
* carries a signed `KeyExchange` -- a relay that predates the `signature` field (a Rust relay built before it)
|
|
48
|
+
* would drop the connection on one. `true` signs regardless; `false` never does. `hybrid` (default true) offers
|
|
49
|
+
* X25519+ML-KEM-768 when asked.
|
|
50
|
+
* `false` turns the layer off: no `e2e` feature, `KeyExchange` unanswered.
|
|
51
|
+
* @param {number} [options.maxOperators=1] - Operators served at once. Above 1 this host states `relay-multi-operator`
|
|
52
|
+
* (it addresses each reply to its operator and handles `ReverseClose`), so it needs `reportFeatures` and a relay with
|
|
53
|
+
* `relay.maxOperatorsPerPeer` above 1 (which says so in its ServerHello); against any other relay it serves one
|
|
54
|
+
* operator, as before. Each operator is passed through `accept` on its own identity.
|
|
55
|
+
* @param {boolean} [options.reportFeatures=true] - State this host's features in `ReverseAccept.features`, so the operator's
|
|
56
|
+
* feature gates follow this host rather than the relay. Turn off only for a relay (a Rust `wsh-server` older than the field)
|
|
57
|
+
* that rejects a `ReverseAccept` carrying it.
|
|
58
|
+
* @param {(line: string) => void} [options.onLog]
|
|
59
|
+
*/
|
|
60
|
+
export function createReverseHost(options = {}) {
|
|
61
|
+
return createReverseHostWith(options, resolveBackends(options));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The reverse host proper, given its backends already built: `createReverseHost` here builds them from injected
|
|
66
|
+
* parts only (browser-safe); `@johnhenry/wsh/server`'s builds them with `exec: true` and `fs: { root }` as well.
|
|
67
|
+
* @param {object} options - as for `createReverseHost` (its `exec`, `pty`, `fs` and `mcp` are read by the caller, not here)
|
|
68
|
+
* @param {ReturnType<typeof resolveBackends>} backends
|
|
69
|
+
*/
|
|
70
|
+
export function createReverseHostWith({
|
|
71
|
+
url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {}, onLog = () => {},
|
|
72
|
+
} = {}, backends) {
|
|
73
|
+
if (!url) throw new TypeError('createReverseHost: url is required');
|
|
74
|
+
if (!username) throw new TypeError('createReverseHost: username is required');
|
|
75
|
+
if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
|
|
76
|
+
if (accept !== undefined && typeof accept !== 'function') throw new TypeError('createReverseHost: accept must be a function');
|
|
77
|
+
if (!Number.isSafeInteger(maxOperators) || maxOperators < 1) throw new TypeError('createReverseHost: maxOperators must be a positive integer');
|
|
78
|
+
if (maxOperators > 1 && !reportFeatures) throw new TypeError('createReverseHost: maxOperators > 1 needs reportFeatures (the relay learns "relay-multi-operator" from ReverseAccept.features)');
|
|
79
|
+
if (e2e !== false && (e2e === null || typeof e2e !== 'object')) throw new TypeError('createReverseHost: e2e must be false or an options object');
|
|
80
|
+
const multi = maxOperators > 1;
|
|
81
|
+
if (e2e !== false && e2e.sign !== undefined && e2e.sign !== 'auto' && typeof e2e.sign !== 'boolean') throw new TypeError("createReverseHost: e2e.sign must be true, false or 'auto'");
|
|
82
|
+
const e2eSign = e2e === false ? false : (e2e.sign ?? 'auto');
|
|
83
|
+
|
|
84
|
+
const expose = { shell: !!backends.pty, exec: !!backends.execRunner, fs: !!backends.files, tools: !!backends.mcp };
|
|
85
|
+
const capabilities = Object.entries(expose).filter(([, on]) => on).map(([k]) => k);
|
|
86
|
+
const shellBackend = backends.pty ? 'pty' : 'exec-only';
|
|
87
|
+
// What this host can do over a bridge, for the operator's feature gates (`ReverseAccept.features`).
|
|
88
|
+
// `reportFeatures: false` leaves them out (a Rust peer or relay older than the field rejects a ReverseAccept that has it).
|
|
89
|
+
/** What this host does with end-to-end encryption on a given relay connection (null = off). */
|
|
90
|
+
const e2eFor = (c) => (e2e === false ? null : {
|
|
91
|
+
signKey: e2eSign === true || (e2eSign === 'auto' && c.hasFeature(E2E_SIGN_FEATURE)) ? keyPair.privateKey : null,
|
|
92
|
+
hybrid: e2e.hybrid !== false,
|
|
93
|
+
});
|
|
94
|
+
/** Features for `ReverseAccept` on this relay connection. */
|
|
95
|
+
const bridgeFeatures = (c, e2eConfig, manyOperators) => [
|
|
96
|
+
...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig }, { dataStreams: false }),
|
|
97
|
+
...(manyOperators ? [MULTI_OPERATOR_FEATURE] : []),
|
|
98
|
+
];
|
|
99
|
+
const factory = createConnectionFactory({
|
|
100
|
+
authorize: async () => false, methods: { pubkey: false, password: null }, hostKey: null, rateLimit: null,
|
|
101
|
+
execRunner: backends.execRunner, execOptions: backends.execOptions, pty: backends.pty, files: backends.files, mcp: backends.mcp,
|
|
102
|
+
sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`),
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
let client = null;
|
|
106
|
+
/** The live connection's bridges (operator fingerprint -> connection), for `operators`. */
|
|
107
|
+
let operatorsNow = new Map();
|
|
108
|
+
/** Ends every bridge of the live connection (the client's own `disconnect()` does not call its `onClose`). */
|
|
109
|
+
let endAllBridges = () => {};
|
|
110
|
+
let myFingerprint = null;
|
|
111
|
+
let closed = false;
|
|
112
|
+
let timer = null;
|
|
113
|
+
let backoff = BACKOFF_START_MS;
|
|
114
|
+
|
|
115
|
+
async function dial() {
|
|
116
|
+
const c = new WshClient();
|
|
117
|
+
/** operator fingerprint -> that operator's connection (its own channels, processes, files). */
|
|
118
|
+
const bridges = new Map();
|
|
119
|
+
// Several operators only on a relay that says it can route to them; anywhere else, one, and bare messages.
|
|
120
|
+
const manyOperators = () => multi && c.hasFeature(MULTI_OPERATOR_FEATURE);
|
|
121
|
+
const operatorLimit = () => (manyOperators() ? maxOperators : 1);
|
|
122
|
+
/** Operators whose `accept` is still running: they count towards the cap. */
|
|
123
|
+
const reserved = new Set();
|
|
124
|
+
operatorsNow = bridges;
|
|
125
|
+
|
|
126
|
+
const endBridge = (fp) => {
|
|
127
|
+
const bridge = bridges.get(fp);
|
|
128
|
+
if (!bridge) return;
|
|
129
|
+
bridges.delete(fp);
|
|
130
|
+
c.untrustRelayPeer(fp);
|
|
131
|
+
bridge.close();
|
|
132
|
+
onLog(`[reverse] operator ${fp.slice(0, 12)} left (${bridges.size} still bridged)`);
|
|
133
|
+
};
|
|
134
|
+
const endAll = () => { for (const fp of [...bridges.keys()]) endBridge(fp); };
|
|
135
|
+
endAllBridges = endAll;
|
|
136
|
+
c.onRelayMessage = (msg, from) => bridges.get(from)?.receiveMessage(msg);
|
|
137
|
+
// The relay says one operator left; the others carry on (it sends this only to a host that stated multi-operator support).
|
|
138
|
+
c.onReverseClose = (m) => endBridge(String(m.target_fingerprint ?? ''));
|
|
139
|
+
c.onReverseConnect = async (req) => {
|
|
140
|
+
const from = req.from_fingerprint;
|
|
141
|
+
const answer = (m) => c.sendRelayControl(m).catch(() => {});
|
|
142
|
+
const refuse = (reason) => answer(reverseReject({ targetFingerprint: myFingerprint, username, reason }));
|
|
143
|
+
if (typeof from !== 'string' || !from) { await refuse('busy: this host is already serving an operator'); return; }
|
|
144
|
+
if (bridges.has(from) || reserved.has(from)) { await refuse('busy: you already have a bridge with this host'); return; }
|
|
145
|
+
if (bridges.size + reserved.size >= operatorLimit()) {
|
|
146
|
+
await refuse(manyOperators() ? `busy: this host is already serving its maximum of ${maxOperators} operators` : 'busy: this host is already serving an operator');
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
reserved.add(from);
|
|
150
|
+
let ok = false;
|
|
151
|
+
try {
|
|
152
|
+
try { ok = (await accept?.({ fingerprint: from, username: String(req.username ?? '') })) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
|
|
153
|
+
if (!ok || bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
|
|
154
|
+
c.trustRelayPeer(from);
|
|
155
|
+
const bridge = factory({
|
|
156
|
+
// With several operators every message names its recipient; with one the relay knows.
|
|
157
|
+
sendMessage: (m) => c.sendRelayControl(m, manyOperators() ? { to: from } : undefined),
|
|
158
|
+
authenticated: { username: String(req.username ?? 'operator'), fingerprint: from },
|
|
159
|
+
dataStreams: false,
|
|
160
|
+
e2e: e2eFor(c),
|
|
161
|
+
});
|
|
162
|
+
bridges.set(from, bridge);
|
|
163
|
+
onLog(`[reverse] bridged to ${from.slice(0, 12)}`);
|
|
164
|
+
await answer(reverseAccept({
|
|
165
|
+
targetFingerprint: myFingerprint, username, capabilities, peerType, shellBackend,
|
|
166
|
+
supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
|
|
167
|
+
features: reportFeatures ? bridgeFeatures(c, e2eFor(c), manyOperators()) : undefined,
|
|
168
|
+
}));
|
|
169
|
+
} finally { reserved.delete(from); }
|
|
170
|
+
};
|
|
171
|
+
c.onClose = () => {
|
|
172
|
+
endAll();
|
|
173
|
+
if (operatorsNow === bridges) operatorsNow = new Map();
|
|
174
|
+
if (client === c) client = null;
|
|
175
|
+
if (closed || !reconnect) return;
|
|
176
|
+
onLog(`[reverse] relay connection ended; redialling in ${backoff}ms`);
|
|
177
|
+
timer = setTimeout(() => { redial().catch(() => {}); }, backoff);
|
|
178
|
+
timer.unref?.();
|
|
179
|
+
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
await c.connectReverse(url, {
|
|
183
|
+
username, keyPair, expose, peerType, shellBackend,
|
|
184
|
+
supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
|
|
185
|
+
...connect,
|
|
186
|
+
});
|
|
187
|
+
client = c;
|
|
188
|
+
backoff = BACKOFF_START_MS;
|
|
189
|
+
onLog(`[reverse] registered ${myFingerprint.slice(0, 12)} on ${url}`);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function redial() {
|
|
193
|
+
if (closed) return;
|
|
194
|
+
try { await dial(); } catch (e) {
|
|
195
|
+
onLog(`[reverse] redial failed: ${e.message}`);
|
|
196
|
+
if (closed || !reconnect) return;
|
|
197
|
+
timer = setTimeout(() => { redial().catch(() => {}); }, backoff);
|
|
198
|
+
timer.unref?.();
|
|
199
|
+
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
/** Dial the relay and register. Rejects if the first attempt fails; later drops are retried. */
|
|
205
|
+
async start() {
|
|
206
|
+
if (client) throw new Error('createReverseHost: already started');
|
|
207
|
+
closed = false;
|
|
208
|
+
myFingerprint = await fingerprint(await exportPublicKeyRaw(keyPair.publicKey));
|
|
209
|
+
await dial();
|
|
210
|
+
return { fingerprint: myFingerprint };
|
|
211
|
+
},
|
|
212
|
+
/** Leave the relay and end any bridged session. */
|
|
213
|
+
async close() {
|
|
214
|
+
closed = true;
|
|
215
|
+
clearTimeout(timer);
|
|
216
|
+
const c = client;
|
|
217
|
+
client = null;
|
|
218
|
+
endAllBridges(); // no operator's process may outlive the host
|
|
219
|
+
await c?.disconnect().catch(() => {});
|
|
220
|
+
},
|
|
221
|
+
/** This host's fingerprint (what operators `reverseConnect()` to); `null` before `start()`. */
|
|
222
|
+
get fingerprint() { return myFingerprint; },
|
|
223
|
+
/** Is the relay connection up right now? */
|
|
224
|
+
get connected() { return client !== null; },
|
|
225
|
+
/** Fingerprints of the operators bridged right now. */
|
|
226
|
+
get operators() { return [...operatorsNow.keys()]; },
|
|
227
|
+
};
|
|
228
|
+
}
|
package/src/server/backends.mjs
CHANGED
|
@@ -2,31 +2,25 @@
|
|
|
2
2
|
* What a host can do for the client on the other end: shared by
|
|
3
3
|
* `createWshServer` (clients that connect to it) and `createReverseHost`
|
|
4
4
|
* (operators bridged to it by a relay), so the two cannot drift.
|
|
5
|
+
*
|
|
6
|
+
* The browser-safe part (injected exec function, pty, file operations, mcp) is `../host-backends.mjs`;
|
|
7
|
+
* this adds what needs Node: `exec: true` / `{ cwd, env, ... }` (a shell through child_process) and
|
|
8
|
+
* `fs: { root }` (a directory).
|
|
5
9
|
*/
|
|
6
10
|
|
|
7
11
|
import { spawnRunner } from './exec.mjs';
|
|
8
|
-
import { normalizePty } from './pty.mjs';
|
|
9
12
|
import { createFileAccess } from './fs.mjs';
|
|
10
|
-
import {
|
|
13
|
+
import { resolveBackends } from '../host-backends.mjs';
|
|
11
14
|
|
|
12
15
|
/**
|
|
13
16
|
* @param {{ exec?: true | object | Function, pty?: object, fs?: object, mcp?: object }} options
|
|
14
17
|
* @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null }}
|
|
15
18
|
*/
|
|
16
19
|
export function buildBackends({ exec, pty, fs, mcp } = {}) {
|
|
17
|
-
let
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
} else if (exec) {
|
|
22
|
-
execOptions = exec === true ? {} : exec;
|
|
23
|
-
execRunner = typeof execOptions.run === 'function' ? execOptions.run : spawnRunner(execOptions);
|
|
20
|
+
let hostExec = exec;
|
|
21
|
+
if (exec && typeof exec !== 'function') {
|
|
22
|
+
const execOptions = exec === true ? {} : exec;
|
|
23
|
+
hostExec = typeof execOptions.run === 'function' ? execOptions : { ...execOptions, run: spawnRunner(execOptions) };
|
|
24
24
|
}
|
|
25
|
-
return {
|
|
26
|
-
execRunner,
|
|
27
|
-
execOptions,
|
|
28
|
-
pty: pty ? normalizePty(pty) : null,
|
|
29
|
-
files: fs ? createFileAccess(fs) : null,
|
|
30
|
-
mcp: mcp ? createMcpHost(mcp) : null,
|
|
31
|
-
};
|
|
25
|
+
return resolveBackends({ exec: hostExec, pty, fs: fs && typeof fs.root === 'string' ? createFileAccess(fs) : fs, mcp });
|
|
32
26
|
}
|
|
@@ -24,12 +24,11 @@ import {
|
|
|
24
24
|
generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
|
|
25
25
|
} from '../auth.mjs';
|
|
26
26
|
import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
|
|
27
|
-
import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from '../
|
|
27
|
+
import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from '../features.mjs';
|
|
28
28
|
import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
|
|
29
29
|
import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
|
|
30
30
|
import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
|
|
31
31
|
import { MULTI_OPERATOR_FEATURE } from './relay.mjs';
|
|
32
|
-
import { createGatewaySession } from './gateway.mjs';
|
|
33
32
|
import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
|
|
34
33
|
|
|
35
34
|
export const STREAM_ANNOUNCE = 'stream-announce';
|
|
@@ -73,14 +72,24 @@ const randomBytes = (n) => crypto.getRandomValues(new Uint8Array(n));
|
|
|
73
72
|
const toBytes = (d) => (typeof d === 'string' ? enc.encode(d) : d);
|
|
74
73
|
|
|
75
74
|
/**
|
|
75
|
+
* The connection handler every host runs -- `createWshServer`, `createMemoryHost`, `createReverseHost` -- exported
|
|
76
|
+
* (as `@johnhenry/wsh/host`) for an embedder that wires its own transport: a WebSocket it opened itself, a
|
|
77
|
+
* `MessagePort`, a byte pipe to another process. It returns `attach(...)`, called once per connection; see below.
|
|
78
|
+
* Build the backends with `resolveBackends()` and the host key with `resolveHostKey()` (same entry point), and
|
|
79
|
+
* answer `authorize` yourself; for the common cases `createMemoryHost()` does all of this and `bindSocket()` does the
|
|
80
|
+
* socket side.
|
|
81
|
+
*
|
|
82
|
+
* Everything here is browser-safe: no `node:*` import and no `Buffer` is reachable from this module.
|
|
83
|
+
*
|
|
76
84
|
* @param {object} cfg
|
|
77
|
-
* @param {(who:
|
|
78
|
-
*
|
|
79
|
-
* @param {
|
|
80
|
-
* @param {object
|
|
81
|
-
* @param {object | null} cfg.
|
|
82
|
-
* @param {
|
|
83
|
-
* @param {
|
|
85
|
+
* @param {(who: { username: string, fingerprint?: string, publicKey?: Uint8Array }) => Promise<boolean>} cfg.authorize - required;
|
|
86
|
+
* decides who is let in (`buildAuthorizer` in `server/auth.mjs` builds one from `authorizedKeys` / a callback)
|
|
87
|
+
* @param {Function | null} [cfg.execRunner] - `run(command, io)`; null = exec is off
|
|
88
|
+
* @param {object} [cfg.execOptions] - `{ timeoutMs, clientEnv }` (default `{}`)
|
|
89
|
+
* @param {object | null} [cfg.pty] - normalized (see pty.mjs): `{ spawn, shell, cwd, env, term }`; null = pty is off
|
|
90
|
+
* @param {object | null} [cfg.files] - a file backend (see `normalizeFileBackend` in `host-backends.mjs`); null = file access is off
|
|
91
|
+
* @param {{ pubkey: boolean, password: Function | null }} [cfg.methods] - which auth methods are on (default pubkey only)
|
|
92
|
+
* @param {object | null} [cfg.hostKey] - from `resolveHostKey` / `loadHostKey`
|
|
84
93
|
* @param {object | null} cfg.mcp - from createMcpHost
|
|
85
94
|
* @param {{ protocols: Map<string, Function>, maxMessageBytes: number, maxInflight: number } | null} cfg.rpc - from createRpcHost
|
|
86
95
|
* @param {{ signKey: CryptoKey | null, hybrid?: boolean } | null} cfg.e2e - answer KeyExchange and seal virtual-mode traffic (bridged connections only)
|
|
@@ -89,10 +98,18 @@ const toBytes = (d) => (typeof d === 'string' ? enc.encode(d) : d);
|
|
|
89
98
|
* @param {object | null} cfg.relay - a RelayHub (see relay.mjs); null = not a relay
|
|
90
99
|
* @param {object | null} cfg.sessions - a SessionRegistry (see sessions.mjs); null = sessions die with their connection
|
|
91
100
|
* @param {{ limiter: object, key: Function, failureDelayMs: number } | null} cfg.rateLimit - password throttle
|
|
92
|
-
* @param {number} cfg.bindTimeoutMs - how long exec output waits for the data stream
|
|
93
|
-
* @param {(line: string) => void} cfg.log
|
|
101
|
+
* @param {number} [cfg.bindTimeoutMs=3000] - how long exec output waits for the data stream
|
|
102
|
+
* @param {(line: string) => void} [cfg.log]
|
|
94
103
|
*/
|
|
95
104
|
export function createConnectionFactory(cfg) {
|
|
105
|
+
if (!cfg || typeof cfg.authorize !== 'function') throw new TypeError('createConnectionFactory: authorize(who) is required (a host that lets everyone in is not a default)');
|
|
106
|
+
cfg = {
|
|
107
|
+
...cfg,
|
|
108
|
+
execOptions: cfg.execOptions ?? {},
|
|
109
|
+
methods: cfg.methods ?? { pubkey: true, password: null },
|
|
110
|
+
bindTimeoutMs: cfg.bindTimeoutMs ?? 3000,
|
|
111
|
+
log: cfg.log ?? (() => {}),
|
|
112
|
+
};
|
|
96
113
|
let counter = 0;
|
|
97
114
|
|
|
98
115
|
/**
|
|
@@ -128,7 +145,10 @@ export function createConnectionFactory(cfg) {
|
|
|
128
145
|
/** This connection as the relay hub sees it (created on first need). */
|
|
129
146
|
let relayHandle = null;
|
|
130
147
|
|
|
131
|
-
|
|
148
|
+
// The gateway needs Node sockets, so `gateway.mjs` is not imported here (a browser host must not pull it in):
|
|
149
|
+
// the embedder that has them (`createWshServer`) passes `cfg.createGatewaySession` along with `cfg.gateway`.
|
|
150
|
+
if (cfg.gateway && typeof cfg.createGatewaySession !== 'function') throw new TypeError('createConnectionFactory: gateway needs createGatewaySession (only @johnhenry/wsh/server provides one)');
|
|
151
|
+
const gateway = cfg.gateway ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log) : null;
|
|
132
152
|
|
|
133
153
|
const qmux = sendMessage ? null : new QMuxConnection({ isClient: false, send: (b) => { if (!state.closed) sendBytes(b); } });
|
|
134
154
|
|
|
@@ -841,7 +861,11 @@ export function createConnectionFactory(cfg) {
|
|
|
841
861
|
return send(openFail({ reason: `pty spawn failed: ${e.message}` }));
|
|
842
862
|
}
|
|
843
863
|
const ctl = {
|
|
844
|
-
|
|
864
|
+
// Bytes, not a `Buffer`: there is none in a browser (#133), and node-pty's streams take a Uint8Array as is.
|
|
865
|
+
// A write to a process that has exited throws; that is expected and dropped, anything else is logged.
|
|
866
|
+
input: (data) => {
|
|
867
|
+
try { proc.write(Uint8Array.from(data)); } catch (e) { log(`pty channel ${channelId}: input not written: ${e?.message ?? e}`); }
|
|
868
|
+
},
|
|
845
869
|
resize: (c, r) => { try { proc.resize(c || cols, r || rows); } catch { /* exited */ } },
|
|
846
870
|
signal: (name) => { try { proc.kill(`SIG${name.replace(/^SIG/, '').toUpperCase()}`); } catch { /* exited */ } },
|
|
847
871
|
kill: () => { try { proc.kill(); } catch { /* exited */ } },
|
package/src/server/constants.mjs
CHANGED
|
@@ -8,3 +8,6 @@ export const FILE_CHUNK_BYTES = 64 * 1024;
|
|
|
8
8
|
|
|
9
9
|
/** Most clients attached to one detached-session at once. */
|
|
10
10
|
export const MAX_ATTACHMENTS = 16;
|
|
11
|
+
|
|
12
|
+
/** Default cap on one file read or written through a file backend. */
|
|
13
|
+
export const DEFAULT_MAX_FILE_BYTES = 64 * 1024 * 1024;
|
package/src/server/fs.mjs
CHANGED
|
@@ -13,9 +13,8 @@ import {
|
|
|
13
13
|
import { constants as fsc } from 'node:fs';
|
|
14
14
|
import path from 'node:path';
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
export { FILE_CHUNK_BYTES };
|
|
16
|
+
import { FILE_CHUNK_BYTES, DEFAULT_MAX_FILE_BYTES } from './constants.mjs';
|
|
17
|
+
export { FILE_CHUNK_BYTES, DEFAULT_MAX_FILE_BYTES };
|
|
19
18
|
|
|
20
19
|
/**
|
|
21
20
|
* @param {{ root: string, readOnly?: boolean, maxFileBytes?: number }} opts
|
package/src/server/index.d.ts
CHANGED
|
@@ -417,6 +417,12 @@ export interface WshAcceptableSocket {
|
|
|
417
417
|
export interface WshAcceptOptions {
|
|
418
418
|
/** What the embedder knows of the peer; `address` keys the password-failure throttle. */
|
|
419
419
|
remote?: { address?: string; headers?: Record<string, unknown> };
|
|
420
|
+
/**
|
|
421
|
+
* Serve this connection without client-opened QMux data streams: exec output rides `SessionData`
|
|
422
|
+
* (`data_mode: 'virtual'`) and `stream-announce` / `rpc` are not offered. For a peer that cannot open streams
|
|
423
|
+
* (the released Rust client over WebSocket). Default `true`.
|
|
424
|
+
*/
|
|
425
|
+
dataStreams?: boolean;
|
|
420
426
|
}
|
|
421
427
|
|
|
422
428
|
export interface WshServer {
|