@johnhenry/wsh 0.35.0 → 0.37.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 +453 -21
- package/package.json +18 -1
- package/src/bridge-seal.mjs +77 -0
- package/src/channel-binding.mjs +124 -0
- package/src/client.mjs +351 -62
- package/src/e2e-exchange.mjs +51 -1
- package/src/features.mjs +28 -0
- package/src/forward-node.mjs +118 -0
- package/src/gateway-channel.mjs +250 -0
- package/src/gateway-client.mjs +252 -0
- package/src/host-backends.mjs +100 -0
- package/src/host.d.ts +146 -0
- package/src/host.mjs +30 -0
- package/src/index.d.ts +114 -0
- package/src/index.mjs +13 -0
- package/src/memory-host.d.ts +34 -3
- package/src/memory-host.mjs +57 -13
- package/src/messages.gen.mjs +59 -7
- package/src/operator-proof.mjs +135 -0
- package/src/pipe-relay.d.ts +49 -0
- package/src/pipe-relay.mjs +274 -0
- package/src/reverse-host.d.ts +25 -0
- package/src/reverse-host.mjs +339 -0
- package/src/server/address-guard.mjs +164 -0
- package/src/server/backends.mjs +10 -16
- package/src/server/client-env.mjs +60 -0
- package/src/server/connection.mjs +100 -23
- package/src/server/constants.mjs +3 -0
- package/src/server/fs.mjs +2 -3
- package/src/server/gateway-core.mjs +188 -0
- package/src/server/gateway.mjs +483 -80
- package/src/server/index.d.ts +103 -5
- package/src/server/index.mjs +25 -4
- package/src/server/pty.mjs +1 -0
- package/src/server/relay.mjs +45 -2
- package/src/server/reverse-host.mjs +7 -213
- package/src/server/socket.mjs +25 -4
- package/src/server/unix-policy.mjs +120 -0
- package/src/server/webtransport.mjs +2 -0
- package/src/transport-ws.mjs +16 -0
- package/src/transport.mjs +11 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** A WebSocket-like duplex: the `ws` package's, a browser's, or a Worker's. */
|
|
2
|
+
export interface PipeSocket {
|
|
3
|
+
send(data: Uint8Array | ArrayBuffer): void;
|
|
4
|
+
close(code?: number, reason?: string): void;
|
|
5
|
+
readonly readyState: number;
|
|
6
|
+
readonly bufferedAmount?: number;
|
|
7
|
+
pause?(): void;
|
|
8
|
+
resume?(): void;
|
|
9
|
+
on?(event: string, listener: (...args: any[]) => void): unknown;
|
|
10
|
+
addEventListener?(event: string, listener: (ev: any) => void): unknown;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface PipeRelayOptions {
|
|
14
|
+
/** Halves waiting for a partner, over all ids (default 1024). */
|
|
15
|
+
maxWaiting?: number;
|
|
16
|
+
/** How long a half waits for its partner (default 120000). */
|
|
17
|
+
rendezvousTimeoutMs?: number;
|
|
18
|
+
/** A pipe that carried no byte either way for this long is closed (default 300000). */
|
|
19
|
+
idleTimeoutMs?: number;
|
|
20
|
+
/** A pipe is closed this long after pairing (default 12 hours). */
|
|
21
|
+
maxLifetimeMs?: number;
|
|
22
|
+
/** Total bytes copied per pipe, both directions (default 1 GiB). */
|
|
23
|
+
maxBytes?: number;
|
|
24
|
+
/** Largest single message (default 4 MiB). */
|
|
25
|
+
maxMessageBytes?: number;
|
|
26
|
+
/** What a half may send before its partner arrives (default 64 KiB). */
|
|
27
|
+
earlyBytes?: number;
|
|
28
|
+
/** Outgoing buffer size past which the sender is paused (default 1 MiB). */
|
|
29
|
+
highWaterBytes?: number;
|
|
30
|
+
/** Optional gate before a half may wait or pair; default: anyone holding a well-formed id. */
|
|
31
|
+
authorize?: (who: { id: string; role: 'host' | 'operator'; remote?: object }) => boolean | Promise<boolean>;
|
|
32
|
+
onLog?: (line: string) => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface PipeRelay {
|
|
36
|
+
/** Hand the relay one accepted connection; resolves false when it was refused (and closed). */
|
|
37
|
+
accept(socket: PipeSocket, who: { id: string; role?: 'host' | 'operator'; remote?: object }): Promise<boolean>;
|
|
38
|
+
/** Listen for WebSocket upgrades on `<path>/<id>` (default `/r`); `?role=host` is the host side. Needs the `ws` package. */
|
|
39
|
+
listen(options?: { host?: string; port?: number; path?: string; tls?: object }): Promise<{ port: number; address: string; close(): Promise<void> }>;
|
|
40
|
+
close(): Promise<void>;
|
|
41
|
+
stats(): { waiting: number; pipes: number };
|
|
42
|
+
newRendezvousId(): string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function createPipeRelay(options?: PipeRelayOptions): PipeRelay;
|
|
46
|
+
/** A fresh 128-bit rendezvous id, base64url. */
|
|
47
|
+
export function newRendezvousId(): string;
|
|
48
|
+
/** The URL one side dials: `<relay>/r/<id>`, with `?role=host` for the host. */
|
|
49
|
+
export function pipeUrl(relayUrl: string, id: string, role?: 'host' | 'operator'): string;
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A pipe relay (wsh #118): rendezvous and byte copying, nothing else.
|
|
3
|
+
*
|
|
4
|
+
* Two parties that cannot reach each other directly both dial the relay with the same unguessable rendezvous id --
|
|
5
|
+
* the host (`role: 'host'`) and the operator (`role: 'operator'`) -- and the relay joins them and copies WebSocket
|
|
6
|
+
* messages in both directions. It does not parse wsh: it holds no keys, runs nothing, reads no files, and cannot
|
|
7
|
+
* tell who either party is. The host serves its connection with the ordinary `createWshServer().accept(socket)` (or
|
|
8
|
+
* `createMemoryHost().accept`), so it runs the ordinary handshake and verifies the OPERATOR'S OWN signature; the
|
|
9
|
+
* operator connects with the ordinary `WshClient.connect(pipeUrl(...))` and can pin the host key. Compare relay
|
|
10
|
+
* mode (`createWshServer({ relay })`), where the relay authenticates the operator and tells the peer who it is.
|
|
11
|
+
* What a pipe relay can still do is in the README's Security model: it sees metadata and ciphertext-free traffic
|
|
12
|
+
* volume, can drop or delay bytes, and can offer a host or operator to whoever holds the rendezvous id.
|
|
13
|
+
*
|
|
14
|
+
* THIS MODULE IMPORTS NOTHING STATICALLY, and its only dynamic imports are `ws`, `node:http` and `node:https` (in
|
|
15
|
+
* `listen()`, for embedders that do not already run an HTTP server). test/pipe-relay.test.mjs asserts that the
|
|
16
|
+
* module graph reaches nothing that can execute code or read files. That is the point of shipping it as its own
|
|
17
|
+
* entry point (`@johnhenry/wsh/pipe-relay`) rather than a mode of the server.
|
|
18
|
+
*
|
|
19
|
+
* Bounds (every one has a default; 0 turns a limit off only where noted):
|
|
20
|
+
* maxWaiting halves waiting for a partner, over all ids (default 1024); more are refused
|
|
21
|
+
* rendezvousTimeoutMs how long a half waits for its partner (default 120000)
|
|
22
|
+
* idleTimeoutMs a pipe that carried no byte either way for this long is closed (default 300000; wsh clients ping)
|
|
23
|
+
* maxLifetimeMs a pipe is closed this long after pairing (default 12 h)
|
|
24
|
+
* maxBytes total bytes copied per pipe, both directions (default 1 GiB)
|
|
25
|
+
* maxMessageBytes largest single message (default 4 MiB)
|
|
26
|
+
* earlyBytes what a half may send before its partner arrives (default 64 KiB); more closes it
|
|
27
|
+
* highWaterBytes a socket whose outgoing buffer exceeds this is not fed further until it drains (default 1 MiB)
|
|
28
|
+
*
|
|
29
|
+
* Backpressure: when the receiving socket's `bufferedAmount` passes `highWaterBytes`, the sending socket is
|
|
30
|
+
* `pause()`d (the `ws` package's flow control, which stops reading its TCP socket) and resumed once the buffer is
|
|
31
|
+
* below half of it. A socket that cannot pause (a browser's, say) is closed instead of buffered without bound.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
const OPEN = 1;
|
|
35
|
+
const ID_RE = /^[A-Za-z0-9_-]{22,128}$/;
|
|
36
|
+
const ROLES = new Set(['host', 'operator']);
|
|
37
|
+
const MIN_ID_LENGTH = 22; // 16 random bytes, base64url
|
|
38
|
+
|
|
39
|
+
/** A fresh rendezvous id: 128 bits from the platform CSPRNG, base64url (22 characters). */
|
|
40
|
+
export function newRendezvousId() {
|
|
41
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
42
|
+
let s = '';
|
|
43
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
44
|
+
return btoa(s).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The URL one side dials: `<relay>/r/<id>`, with `?role=host` for the host (the operator is the default).
|
|
49
|
+
* @param {string} relayUrl - `ws://` / `wss://` (or `http(s)://`) base of the relay
|
|
50
|
+
* @param {string} id
|
|
51
|
+
* @param {'host' | 'operator'} [role='operator']
|
|
52
|
+
*/
|
|
53
|
+
export function pipeUrl(relayUrl, id, role = 'operator') {
|
|
54
|
+
if (!ID_RE.test(id)) throw new TypeError(`pipeUrl: the rendezvous id must be ${MIN_ID_LENGTH}-128 base64url characters (use newRendezvousId())`);
|
|
55
|
+
if (!ROLES.has(role)) throw new TypeError("pipeUrl: role must be 'host' or 'operator'");
|
|
56
|
+
const u = new URL(relayUrl);
|
|
57
|
+
u.pathname = `${u.pathname.replace(/\/+$/, '')}/r/${id}`;
|
|
58
|
+
u.search = role === 'host' ? '?role=host' : '';
|
|
59
|
+
return u.toString();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const sane = (code) => (Number.isInteger(code) && code >= 1000 && code <= 4999 && ![1004, 1005, 1006, 1015].includes(code) ? code : 1000);
|
|
63
|
+
|
|
64
|
+
/** Adapt a `ws`-style (`on`) or browser-style (`addEventListener`) socket to message/close callbacks. */
|
|
65
|
+
function listenOn(socket, onMessage, onClose) {
|
|
66
|
+
if (typeof socket.addEventListener === 'function') {
|
|
67
|
+
socket.addEventListener('message', (ev) => onMessage(ev?.data));
|
|
68
|
+
socket.addEventListener('close', (ev) => onClose(ev?.code));
|
|
69
|
+
socket.addEventListener('error', () => {});
|
|
70
|
+
} else if (typeof socket.on === 'function') {
|
|
71
|
+
socket.on('message', (data, isBinary) => onMessage(data, isBinary));
|
|
72
|
+
socket.on('close', (code) => onClose(code));
|
|
73
|
+
socket.on('error', () => {});
|
|
74
|
+
} else {
|
|
75
|
+
throw new TypeError('createPipeRelay: socket must support on() or addEventListener()');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const sizeOf = (data) => (typeof data === 'string' ? -1
|
|
80
|
+
: Array.isArray(data) ? data.reduce((n, d) => n + d.byteLength, 0)
|
|
81
|
+
: data?.byteLength ?? data?.size ?? -1);
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {object} [options]
|
|
85
|
+
* @param {number} [options.maxWaiting=1024]
|
|
86
|
+
* @param {number} [options.rendezvousTimeoutMs=120000]
|
|
87
|
+
* @param {number} [options.idleTimeoutMs=300000]
|
|
88
|
+
* @param {number} [options.maxLifetimeMs=43200000]
|
|
89
|
+
* @param {number} [options.maxBytes=1073741824]
|
|
90
|
+
* @param {number} [options.maxMessageBytes=4194304]
|
|
91
|
+
* @param {number} [options.earlyBytes=65536]
|
|
92
|
+
* @param {number} [options.highWaterBytes=1048576]
|
|
93
|
+
* @param {(who: { id: string, role: 'host' | 'operator', remote?: object }) => boolean | Promise<boolean>} [options.authorize]
|
|
94
|
+
* Optional gate, called before a half may wait or pair (rate limiting, an allow-list of ids you minted). Default:
|
|
95
|
+
* anyone holding a well-formed id; the id is the capability.
|
|
96
|
+
* @param {(line: string) => void} [options.onLog]
|
|
97
|
+
*/
|
|
98
|
+
export function createPipeRelay({
|
|
99
|
+
maxWaiting = 1024, rendezvousTimeoutMs = 120_000, idleTimeoutMs = 300_000, maxLifetimeMs = 12 * 3600_000,
|
|
100
|
+
maxBytes = 1024 ** 3, maxMessageBytes = 4 * 1024 * 1024, earlyBytes = 64 * 1024, highWaterBytes = 1024 * 1024,
|
|
101
|
+
authorize, onLog = () => {},
|
|
102
|
+
} = {}) {
|
|
103
|
+
for (const [name, v] of Object.entries({ maxWaiting, rendezvousTimeoutMs, idleTimeoutMs, maxLifetimeMs, maxBytes, maxMessageBytes, earlyBytes, highWaterBytes })) {
|
|
104
|
+
if (!Number.isFinite(v) || v < 1) throw new TypeError(`createPipeRelay: ${name} must be a positive number`);
|
|
105
|
+
}
|
|
106
|
+
if (authorize !== undefined && typeof authorize !== 'function') throw new TypeError('createPipeRelay: authorize must be a function');
|
|
107
|
+
|
|
108
|
+
/** id -> the one half waiting for its partner. */
|
|
109
|
+
const waiting = new Map();
|
|
110
|
+
/** Live pipes. */
|
|
111
|
+
const pipes = new Set();
|
|
112
|
+
let closed = false;
|
|
113
|
+
let server = null;
|
|
114
|
+
|
|
115
|
+
const closeSocket = (socket, code = 1000, reason = '') => { try { socket.close(code, reason); } catch { /* gone */ } };
|
|
116
|
+
|
|
117
|
+
function wait(half) {
|
|
118
|
+
half.timer = setTimeout(() => { waiting.delete(half.id); closeSocket(half.socket, 1000, 'no partner arrived'); onLog(`pipe ${half.id.slice(0, 6)}: ${half.role} waited too long`); }, rendezvousTimeoutMs);
|
|
119
|
+
half.timer.unref?.();
|
|
120
|
+
waiting.set(half.id, half);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function pair(first, second) {
|
|
124
|
+
clearTimeout(first.timer);
|
|
125
|
+
waiting.delete(first.id);
|
|
126
|
+
const pipe = { halves: [first, second], bytes: 0, last: Date.now(), timers: [], done: false };
|
|
127
|
+
pipes.add(pipe);
|
|
128
|
+
const end = (code, reason, from) => {
|
|
129
|
+
if (pipe.done) return;
|
|
130
|
+
pipe.done = true;
|
|
131
|
+
pipes.delete(pipe);
|
|
132
|
+
for (const t of pipe.timers) { clearInterval(t); clearTimeout(t); }
|
|
133
|
+
for (const h of pipe.halves) { h.resume?.(); if (h !== from) closeSocket(h.socket, sane(code), reason); }
|
|
134
|
+
onLog(`pipe ${first.id.slice(0, 6)} closed (${reason || code}) after ${pipe.bytes} bytes`);
|
|
135
|
+
};
|
|
136
|
+
pipe.end = end;
|
|
137
|
+
const life = setTimeout(() => end(1000, 'maximum lifetime reached'), maxLifetimeMs);
|
|
138
|
+
const idle = setInterval(() => { if (Date.now() - pipe.last > idleTimeoutMs) end(1000, 'idle'); }, Math.max(1000, Math.min(idleTimeoutMs / 4, 30_000)));
|
|
139
|
+
for (const t of [life, idle]) t.unref?.();
|
|
140
|
+
pipe.timers.push(life, idle);
|
|
141
|
+
|
|
142
|
+
const [a, b] = pipe.halves;
|
|
143
|
+
for (const [from, to] of [[a, b], [b, a]]) {
|
|
144
|
+
from.forward = (data, isBinary) => {
|
|
145
|
+
if (pipe.done) return;
|
|
146
|
+
const n = sizeOf(data);
|
|
147
|
+
if (n < 0 || isBinary === false) return end(1003, 'binary messages only', null);
|
|
148
|
+
if (n > maxMessageBytes) return end(1009, 'message too large', null);
|
|
149
|
+
pipe.bytes += n;
|
|
150
|
+
pipe.last = Date.now();
|
|
151
|
+
if (pipe.bytes > maxBytes) return end(1008, 'byte limit reached', null);
|
|
152
|
+
if (to.socket.readyState !== OPEN) return;
|
|
153
|
+
try { to.socket.send(data); } catch { return end(1011, 'send failed', null); }
|
|
154
|
+
if ((to.socket.bufferedAmount ?? 0) > highWaterBytes) throttle(from, to, pipe);
|
|
155
|
+
};
|
|
156
|
+
// Whatever it said before its partner arrived.
|
|
157
|
+
for (const m of from.early.splice(0)) from.forward(m.data, m.isBinary);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function throttle(from, to, pipe) {
|
|
162
|
+
if (from.paused) return;
|
|
163
|
+
if (typeof from.socket.pause !== 'function' || typeof from.socket.resume !== 'function') return pipe.end(1013, 'receiver too slow', null);
|
|
164
|
+
from.paused = true;
|
|
165
|
+
from.socket.pause();
|
|
166
|
+
from.resume = () => { if (from.paused) { from.paused = false; try { from.socket.resume(); } catch { /* gone */ } } };
|
|
167
|
+
const poll = setInterval(() => {
|
|
168
|
+
if (pipe.done) return clearInterval(poll);
|
|
169
|
+
if ((to.socket.bufferedAmount ?? 0) < highWaterBytes / 2) { clearInterval(poll); from.resume(); }
|
|
170
|
+
}, 10);
|
|
171
|
+
poll.unref?.();
|
|
172
|
+
pipe.timers.push(poll);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Hand the relay one accepted connection.
|
|
177
|
+
* @param {object} socket - a WebSocket-like duplex (`send`, `close`, `readyState`, `on` or `addEventListener`)
|
|
178
|
+
* @param {{ id: string, role?: 'host' | 'operator', remote?: object }} who
|
|
179
|
+
* @returns {Promise<boolean>} whether the connection is now waiting or paired (false: it was refused and closed)
|
|
180
|
+
*/
|
|
181
|
+
async function accept(socket, { id, role = 'operator', remote } = {}) {
|
|
182
|
+
if (!socket || typeof socket.send !== 'function' || typeof socket.close !== 'function') throw new TypeError('createPipeRelay.accept: socket must be a WebSocket-like duplex');
|
|
183
|
+
const refuse = (code, reason) => { closeSocket(socket, code, reason); return false; };
|
|
184
|
+
if (closed) return refuse(1001, 'relay is shutting down');
|
|
185
|
+
if (typeof id !== 'string' || !ID_RE.test(id)) return refuse(1008, 'bad rendezvous id');
|
|
186
|
+
if (!ROLES.has(role)) return refuse(1008, 'bad role');
|
|
187
|
+
|
|
188
|
+
// Listeners first, so nothing the peer says while we decide is lost; it is held (bounded) until it can be passed on.
|
|
189
|
+
const half = { id, role, socket, early: [], earlyBytes: 0, timer: null, forward: null, paused: false, resume: null };
|
|
190
|
+
let pipeRef = null;
|
|
191
|
+
listenOn(socket, (data, isBinary) => {
|
|
192
|
+
if (half.forward) return half.forward(data, isBinary);
|
|
193
|
+
const n = sizeOf(data);
|
|
194
|
+
half.earlyBytes += Math.max(n, 0);
|
|
195
|
+
if (n < 0 || isBinary === false || half.earlyBytes > earlyBytes) {
|
|
196
|
+
waiting.get(id) === half && (clearTimeout(half.timer), waiting.delete(id));
|
|
197
|
+
return closeSocket(socket, n < 0 || isBinary === false ? 1003 : 1009, 'too much before the partner arrived');
|
|
198
|
+
}
|
|
199
|
+
half.early.push({ data, isBinary });
|
|
200
|
+
}, (code) => {
|
|
201
|
+
if (waiting.get(id) === half) { clearTimeout(half.timer); waiting.delete(id); }
|
|
202
|
+
for (const p of pipes) if (p.halves.includes(half)) { pipeRef = p; break; }
|
|
203
|
+
pipeRef?.end(code, 'peer closed', half);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
if (authorize) {
|
|
207
|
+
let ok = false;
|
|
208
|
+
try { ok = (await authorize({ id, role, remote })) === true; } catch (e) { onLog(`authorize threw: ${e.message}`); }
|
|
209
|
+
if (!ok) return refuse(1008, 'not permitted');
|
|
210
|
+
if (closed || socket.readyState !== OPEN) return false;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const other = waiting.get(id);
|
|
214
|
+
if (!other) {
|
|
215
|
+
if (waiting.size >= maxWaiting) return refuse(1013, 'too many waiting connections');
|
|
216
|
+
wait(half);
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
if (other.role === role) return refuse(1008, 'rendezvous id in use');
|
|
220
|
+
pair(other, half);
|
|
221
|
+
onLog(`pipe ${id.slice(0, 6)}: paired`);
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Listen for WebSocket upgrades on `<path>/<id>` (default path `/r`), `?role=host` for the host side.
|
|
227
|
+
* Convenience for embedders without an HTTP server; needs the `ws` package. `tls` is the options of `https.createServer`.
|
|
228
|
+
* @returns {Promise<{ port: number, address: string, close(): Promise<void> }>}
|
|
229
|
+
*/
|
|
230
|
+
async function listen({ host = '127.0.0.1', port = 0, path = '/r', tls } = {}) {
|
|
231
|
+
if (server) throw new Error('createPipeRelay: already listening');
|
|
232
|
+
const { WebSocketServer } = await import('ws');
|
|
233
|
+
const http = tls ? await import('node:https') : await import('node:http');
|
|
234
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: maxMessageBytes });
|
|
235
|
+
const srv = tls ? http.createServer(tls) : http.createServer();
|
|
236
|
+
srv.on('request', (_req, res) => { res.statusCode = 426; res.end('WebSocket only'); });
|
|
237
|
+
srv.on('upgrade', (req, sock, head) => {
|
|
238
|
+
let url;
|
|
239
|
+
try { url = new URL(req.url, 'http://x'); } catch { sock.destroy(); return; }
|
|
240
|
+
const m = url.pathname.startsWith(`${path}/`) ? url.pathname.slice(path.length + 1) : null;
|
|
241
|
+
const role = url.searchParams.get('role') ?? 'operator';
|
|
242
|
+
if (!m || !ID_RE.test(m) || !ROLES.has(role)) { sock.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); sock.destroy(); return; }
|
|
243
|
+
wss.handleUpgrade(req, sock, head, (ws) => { accept(ws, { id: m, role, remote: { address: req.socket.remoteAddress, headers: req.headers } }).catch(() => closeSocket(ws, 1011, 'error')); });
|
|
244
|
+
});
|
|
245
|
+
await new Promise((resolve, reject) => { srv.once('error', reject); srv.listen(port, host, () => { srv.off('error', reject); resolve(); }); });
|
|
246
|
+
server = { srv, wss };
|
|
247
|
+
const addr = srv.address();
|
|
248
|
+
return {
|
|
249
|
+
port: addr.port, address: addr.address,
|
|
250
|
+
close: () => close(),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async function close() {
|
|
255
|
+
closed = true;
|
|
256
|
+
for (const h of waiting.values()) { clearTimeout(h.timer); closeSocket(h.socket, 1001, 'relay is shutting down'); }
|
|
257
|
+
waiting.clear();
|
|
258
|
+
for (const p of [...pipes]) p.end(1001, 'relay is shutting down', null);
|
|
259
|
+
if (server) {
|
|
260
|
+
const { srv, wss } = server;
|
|
261
|
+
server = null;
|
|
262
|
+
for (const c of wss.clients) c.terminate();
|
|
263
|
+
await new Promise((r) => wss.close(r));
|
|
264
|
+
await new Promise((r) => { srv.close(() => r()); srv.closeAllConnections?.(); });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return {
|
|
269
|
+
accept, listen, close,
|
|
270
|
+
/** `{ waiting, pipes }` right now. */
|
|
271
|
+
stats: () => ({ waiting: waiting.size, pipes: pipes.size }),
|
|
272
|
+
newRendezvousId,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshReverseHostOptions, WshReverseHost, WshClientEnv } 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?: WshClientEnv };
|
|
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;
|