@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 +109 -11
- 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 +18 -1
- package/src/memory-host.mjs +31 -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/socket.mjs +25 -4
|
@@ -1,219 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
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).
|
|
2
|
+
* `createReverseHost` for `@johnhenry/wsh/server`: the browser-safe reverse host (`../reverse-host.mjs`, also
|
|
3
|
+
* `@johnhenry/wsh/reverse`) with the Node-only backends added -- `exec: true` (a shell through child_process)
|
|
4
|
+
* and `fs: { root }` (a directory). The reverse host itself lives in `../reverse-host.mjs`.
|
|
15
5
|
*/
|
|
16
6
|
|
|
17
|
-
import {
|
|
18
|
-
import { exportPublicKeyRaw, fingerprint } from '../auth.mjs';
|
|
19
|
-
import { reverseAccept, reverseReject } from '../messages.gen.mjs';
|
|
20
|
-
import { MULTI_OPERATOR_FEATURE } from './relay.mjs';
|
|
21
|
-
import { E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
|
|
7
|
+
import { createReverseHostWith } from '../reverse-host.mjs';
|
|
22
8
|
import { buildBackends } from './backends.mjs';
|
|
23
|
-
import { createConnectionFactory, hostFeatures } from './connection.mjs';
|
|
24
9
|
|
|
25
|
-
|
|
26
|
-
|
|
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({
|
|
61
|
-
url, username, keyPair, accept, exec, pty, fs, mcp, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {}, onLog = () => {},
|
|
62
|
-
} = {}) {
|
|
63
|
-
if (!url) throw new TypeError('createReverseHost: url is required');
|
|
64
|
-
if (!username) throw new TypeError('createReverseHost: username is required');
|
|
65
|
-
if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
|
|
66
|
-
if (accept !== undefined && typeof accept !== 'function') throw new TypeError('createReverseHost: accept must be a function');
|
|
67
|
-
if (!Number.isSafeInteger(maxOperators) || maxOperators < 1) throw new TypeError('createReverseHost: maxOperators must be a positive integer');
|
|
68
|
-
if (maxOperators > 1 && !reportFeatures) throw new TypeError('createReverseHost: maxOperators > 1 needs reportFeatures (the relay learns "relay-multi-operator" from ReverseAccept.features)');
|
|
69
|
-
if (e2e !== false && (e2e === null || typeof e2e !== 'object')) throw new TypeError('createReverseHost: e2e must be false or an options object');
|
|
70
|
-
const multi = maxOperators > 1;
|
|
71
|
-
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'");
|
|
72
|
-
const e2eSign = e2e === false ? false : (e2e.sign ?? 'auto');
|
|
73
|
-
|
|
74
|
-
const backends = buildBackends({ exec, pty, fs, mcp });
|
|
75
|
-
const expose = { shell: !!backends.pty, exec: !!backends.execRunner, fs: !!backends.files, tools: !!backends.mcp };
|
|
76
|
-
const capabilities = Object.entries(expose).filter(([, on]) => on).map(([k]) => k);
|
|
77
|
-
const shellBackend = backends.pty ? 'pty' : 'exec-only';
|
|
78
|
-
// What this host can do over a bridge, for the operator's feature gates (`ReverseAccept.features`).
|
|
79
|
-
// `reportFeatures: false` leaves them out (a Rust peer or relay older than the field rejects a ReverseAccept that has it).
|
|
80
|
-
/** What this host does with end-to-end encryption on a given relay connection (null = off). */
|
|
81
|
-
const e2eFor = (c) => (e2e === false ? null : {
|
|
82
|
-
signKey: e2eSign === true || (e2eSign === 'auto' && c.hasFeature(E2E_SIGN_FEATURE)) ? keyPair.privateKey : null,
|
|
83
|
-
hybrid: e2e.hybrid !== false,
|
|
84
|
-
});
|
|
85
|
-
/** Features for `ReverseAccept` on this relay connection. */
|
|
86
|
-
const bridgeFeatures = (c, e2eConfig, manyOperators) => [
|
|
87
|
-
...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig }, { dataStreams: false }),
|
|
88
|
-
...(manyOperators ? [MULTI_OPERATOR_FEATURE] : []),
|
|
89
|
-
];
|
|
90
|
-
const factory = createConnectionFactory({
|
|
91
|
-
authorize: async () => false, methods: { pubkey: false, password: null }, hostKey: null, rateLimit: null,
|
|
92
|
-
execRunner: backends.execRunner, execOptions: backends.execOptions, pty: backends.pty, files: backends.files, mcp: backends.mcp,
|
|
93
|
-
sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`),
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
let client = null;
|
|
97
|
-
/** The live connection's bridges (operator fingerprint -> connection), for `operators`. */
|
|
98
|
-
let operatorsNow = new Map();
|
|
99
|
-
/** Ends every bridge of the live connection (the client's own `disconnect()` does not call its `onClose`). */
|
|
100
|
-
let endAllBridges = () => {};
|
|
101
|
-
let myFingerprint = null;
|
|
102
|
-
let closed = false;
|
|
103
|
-
let timer = null;
|
|
104
|
-
let backoff = BACKOFF_START_MS;
|
|
105
|
-
|
|
106
|
-
async function dial() {
|
|
107
|
-
const c = new WshClient();
|
|
108
|
-
/** operator fingerprint -> that operator's connection (its own channels, processes, files). */
|
|
109
|
-
const bridges = new Map();
|
|
110
|
-
// Several operators only on a relay that says it can route to them; anywhere else, one, and bare messages.
|
|
111
|
-
const manyOperators = () => multi && c.hasFeature(MULTI_OPERATOR_FEATURE);
|
|
112
|
-
const operatorLimit = () => (manyOperators() ? maxOperators : 1);
|
|
113
|
-
/** Operators whose `accept` is still running: they count towards the cap. */
|
|
114
|
-
const reserved = new Set();
|
|
115
|
-
operatorsNow = bridges;
|
|
116
|
-
|
|
117
|
-
const endBridge = (fp) => {
|
|
118
|
-
const bridge = bridges.get(fp);
|
|
119
|
-
if (!bridge) return;
|
|
120
|
-
bridges.delete(fp);
|
|
121
|
-
c.untrustRelayPeer(fp);
|
|
122
|
-
bridge.close();
|
|
123
|
-
onLog(`[reverse] operator ${fp.slice(0, 12)} left (${bridges.size} still bridged)`);
|
|
124
|
-
};
|
|
125
|
-
const endAll = () => { for (const fp of [...bridges.keys()]) endBridge(fp); };
|
|
126
|
-
endAllBridges = endAll;
|
|
127
|
-
c.onRelayMessage = (msg, from) => bridges.get(from)?.receiveMessage(msg);
|
|
128
|
-
// The relay says one operator left; the others carry on (it sends this only to a host that stated multi-operator support).
|
|
129
|
-
c.onReverseClose = (m) => endBridge(String(m.target_fingerprint ?? ''));
|
|
130
|
-
c.onReverseConnect = async (req) => {
|
|
131
|
-
const from = req.from_fingerprint;
|
|
132
|
-
const answer = (m) => c.sendRelayControl(m).catch(() => {});
|
|
133
|
-
const refuse = (reason) => answer(reverseReject({ targetFingerprint: myFingerprint, username, reason }));
|
|
134
|
-
if (typeof from !== 'string' || !from) { await refuse('busy: this host is already serving an operator'); return; }
|
|
135
|
-
if (bridges.has(from) || reserved.has(from)) { await refuse('busy: you already have a bridge with this host'); return; }
|
|
136
|
-
if (bridges.size + reserved.size >= operatorLimit()) {
|
|
137
|
-
await refuse(manyOperators() ? `busy: this host is already serving its maximum of ${maxOperators} operators` : 'busy: this host is already serving an operator');
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
reserved.add(from);
|
|
141
|
-
let ok = false;
|
|
142
|
-
try {
|
|
143
|
-
try { ok = (await accept?.({ fingerprint: from, username: String(req.username ?? '') })) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
|
|
144
|
-
if (!ok || bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
|
|
145
|
-
c.trustRelayPeer(from);
|
|
146
|
-
const bridge = factory({
|
|
147
|
-
// With several operators every message names its recipient; with one the relay knows.
|
|
148
|
-
sendMessage: (m) => c.sendRelayControl(m, manyOperators() ? { to: from } : undefined),
|
|
149
|
-
authenticated: { username: String(req.username ?? 'operator'), fingerprint: from },
|
|
150
|
-
dataStreams: false,
|
|
151
|
-
e2e: e2eFor(c),
|
|
152
|
-
});
|
|
153
|
-
bridges.set(from, bridge);
|
|
154
|
-
onLog(`[reverse] bridged to ${from.slice(0, 12)}`);
|
|
155
|
-
await answer(reverseAccept({
|
|
156
|
-
targetFingerprint: myFingerprint, username, capabilities, peerType, shellBackend,
|
|
157
|
-
supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
|
|
158
|
-
features: reportFeatures ? bridgeFeatures(c, e2eFor(c), manyOperators()) : undefined,
|
|
159
|
-
}));
|
|
160
|
-
} finally { reserved.delete(from); }
|
|
161
|
-
};
|
|
162
|
-
c.onClose = () => {
|
|
163
|
-
endAll();
|
|
164
|
-
if (operatorsNow === bridges) operatorsNow = new Map();
|
|
165
|
-
if (client === c) client = null;
|
|
166
|
-
if (closed || !reconnect) return;
|
|
167
|
-
onLog(`[reverse] relay connection ended; redialling in ${backoff}ms`);
|
|
168
|
-
timer = setTimeout(() => { redial().catch(() => {}); }, backoff);
|
|
169
|
-
timer.unref?.();
|
|
170
|
-
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
await c.connectReverse(url, {
|
|
174
|
-
username, keyPair, expose, peerType, shellBackend,
|
|
175
|
-
supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
|
|
176
|
-
...connect,
|
|
177
|
-
});
|
|
178
|
-
client = c;
|
|
179
|
-
backoff = BACKOFF_START_MS;
|
|
180
|
-
onLog(`[reverse] registered ${myFingerprint.slice(0, 12)} on ${url}`);
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
async function redial() {
|
|
184
|
-
if (closed) return;
|
|
185
|
-
try { await dial(); } catch (e) {
|
|
186
|
-
onLog(`[reverse] redial failed: ${e.message}`);
|
|
187
|
-
if (closed || !reconnect) return;
|
|
188
|
-
timer = setTimeout(() => { redial().catch(() => {}); }, backoff);
|
|
189
|
-
timer.unref?.();
|
|
190
|
-
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
return {
|
|
195
|
-
/** Dial the relay and register. Rejects if the first attempt fails; later drops are retried. */
|
|
196
|
-
async start() {
|
|
197
|
-
if (client) throw new Error('createReverseHost: already started');
|
|
198
|
-
closed = false;
|
|
199
|
-
myFingerprint = await fingerprint(await exportPublicKeyRaw(keyPair.publicKey));
|
|
200
|
-
await dial();
|
|
201
|
-
return { fingerprint: myFingerprint };
|
|
202
|
-
},
|
|
203
|
-
/** Leave the relay and end any bridged session. */
|
|
204
|
-
async close() {
|
|
205
|
-
closed = true;
|
|
206
|
-
clearTimeout(timer);
|
|
207
|
-
const c = client;
|
|
208
|
-
client = null;
|
|
209
|
-
endAllBridges(); // no operator's process may outlive the host
|
|
210
|
-
await c?.disconnect().catch(() => {});
|
|
211
|
-
},
|
|
212
|
-
/** This host's fingerprint (what operators `reverseConnect()` to); `null` before `start()`. */
|
|
213
|
-
get fingerprint() { return myFingerprint; },
|
|
214
|
-
/** Is the relay connection up right now? */
|
|
215
|
-
get connected() { return client !== null; },
|
|
216
|
-
/** Fingerprints of the operators bridged right now. */
|
|
217
|
-
get operators() { return [...operatorsNow.keys()]; },
|
|
218
|
-
};
|
|
10
|
+
/** @param {Parameters<typeof import('../reverse-host.mjs').createReverseHost>[0]} [options] - see `../reverse-host.mjs` */
|
|
11
|
+
export function createReverseHost(options = {}) {
|
|
12
|
+
return createReverseHostWith(options, buildBackends(options));
|
|
219
13
|
}
|
package/src/server/socket.mjs
CHANGED
|
@@ -8,7 +8,10 @@
|
|
|
8
8
|
* is ignored, as the QMux framing never carries one.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
const CONNECTING = 0;
|
|
11
12
|
const OPEN = 1;
|
|
13
|
+
/** Most bytes held for a socket that is still connecting (a handshake is a few hundred). */
|
|
14
|
+
const MAX_WAITING_BYTES = 256 * 1024;
|
|
12
15
|
|
|
13
16
|
/** @param {unknown} data - a message payload as `ws` (Buffer, ArrayBuffer, Buffer[]) or a browser (ArrayBuffer, view, Blob) delivers it */
|
|
14
17
|
async function toBytes(data) {
|
|
@@ -29,11 +32,13 @@ async function toBytes(data) {
|
|
|
29
32
|
/**
|
|
30
33
|
* @param {object} socket - the WebSocket-like duplex
|
|
31
34
|
* @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)
|
|
35
|
+
* @param {{ remote?: { address?: string, headers?: object }, dataStreams?: boolean }} [options] - what the host knows about the peer
|
|
36
|
+
* (`address` keys the password-failure throttle; the default key is shared by every socket without one).
|
|
37
|
+
* `dataStreams: false` serves this connection without client-opened data streams (exec output rides SessionData), for a
|
|
38
|
+
* client that cannot open them (the Rust client over WebSocket, #132).
|
|
34
39
|
* @returns {Promise<{ close(): void }>} resolves once the connection is attached; `close()` drops it
|
|
35
40
|
*/
|
|
36
|
-
export function bindSocket(socket, ready, { remote = {} } = {}) {
|
|
41
|
+
export function bindSocket(socket, ready, { remote = {}, dataStreams } = {}) {
|
|
37
42
|
if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') {
|
|
38
43
|
throw new TypeError('accept: socket must be a WebSocket-like duplex with send() and close()');
|
|
39
44
|
}
|
|
@@ -49,11 +54,26 @@ export function bindSocket(socket, ready, { remote = {} } = {}) {
|
|
|
49
54
|
// chained behind `ready`: a peer that speaks first (a client's QMux handshake) is not dropped.
|
|
50
55
|
let conn = null;
|
|
51
56
|
let closed = false;
|
|
57
|
+
// A socket handed over while it is still connecting (`accept(new WebSocket(url))`) cannot be written to yet, but the host
|
|
58
|
+
// speaks first (its QMux handshake): those bytes wait for `open`, in order, and are dropped if it never opens.
|
|
59
|
+
let waiting = [];
|
|
60
|
+
let waitingBytes = 0;
|
|
61
|
+
const flush = () => {
|
|
62
|
+
const out = waiting;
|
|
63
|
+
waiting = []; waitingBytes = 0;
|
|
64
|
+
if (socket.readyState !== OPEN) return;
|
|
65
|
+
for (const b of out) socket.send(b);
|
|
66
|
+
};
|
|
67
|
+
const write = (bytes) => {
|
|
68
|
+
if (socket.readyState === OPEN) { if (waiting.length) flush(); socket.send(bytes); return; }
|
|
69
|
+
if (socket.readyState === CONNECTING && waitingBytes + bytes.byteLength <= MAX_WAITING_BYTES) { waiting.push(bytes); waitingBytes += bytes.byteLength; }
|
|
70
|
+
};
|
|
52
71
|
let chain = ready.then((attach) => {
|
|
53
72
|
if (closed) return;
|
|
54
73
|
conn = attach({
|
|
55
|
-
send:
|
|
74
|
+
send: write,
|
|
56
75
|
remote: { address: remote.address, headers: remote.headers ?? {} },
|
|
76
|
+
dataStreams,
|
|
57
77
|
closeTransport: () => { try { socket.close(1000); } catch { /* already closed */ } },
|
|
58
78
|
});
|
|
59
79
|
});
|
|
@@ -65,6 +85,7 @@ export function bindSocket(socket, ready, { remote = {} } = {}) {
|
|
|
65
85
|
if (bytes && !closed) conn.receive(bytes);
|
|
66
86
|
}).catch(() => {});
|
|
67
87
|
});
|
|
88
|
+
listen('open', flush);
|
|
68
89
|
listen('close', drop);
|
|
69
90
|
listen('error', () => {});
|
|
70
91
|
return chain.then(() => ({
|