@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/server/index.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { SessionRegistry } from './sessions.mjs';
|
|
|
15
15
|
import { RelayHub } from './relay.mjs';
|
|
16
16
|
import { startWebTransport } from './webtransport.mjs';
|
|
17
17
|
import { createConnectionFactory, STREAM_ANNOUNCE } from './connection.mjs';
|
|
18
|
-
import { normalizeGateway } from './gateway.mjs';
|
|
18
|
+
import { normalizeGateway, createGatewaySession } from './gateway.mjs';
|
|
19
19
|
import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
|
|
20
20
|
import { bindSocket } from './socket.mjs';
|
|
21
21
|
|
|
@@ -126,7 +126,7 @@ export function createWshServer({
|
|
|
126
126
|
if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createWshServer: extensions must be an object of handlers');
|
|
127
127
|
return createConnectionFactory({
|
|
128
128
|
authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, log: onLog,
|
|
129
|
-
methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, sessions: registry, relay: hub,
|
|
129
|
+
methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
|
|
130
130
|
});
|
|
131
131
|
})();
|
|
132
132
|
ready.catch(() => { ready = null; });
|
|
@@ -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/sessions.mjs
CHANGED
|
@@ -2,81 +2,17 @@
|
|
|
2
2
|
* Session registry for `@johnhenry/wsh/server`: what lets an exec/pty session
|
|
3
3
|
* outlive the connection that opened it (`createWshServer({ sessions })`).
|
|
4
4
|
*
|
|
5
|
-
* The
|
|
6
|
-
*
|
|
7
|
-
* appended to the session's ring buffer and fanned out to every attachment,
|
|
8
|
-
* so when a socket drops the process keeps running and its newest output keeps
|
|
9
|
-
* accumulating until `detachTtlMs` elapses or a client resumes.
|
|
10
|
-
*
|
|
11
|
-
* `seq` -- the one design question the wire does not answer -- is defined as
|
|
12
|
-
* the cumulative count of output BYTES the host has produced for a session.
|
|
13
|
-
* A client counts what it has received (it sees every byte), passes that as
|
|
14
|
-
* `Resume.last_seq`, and the host replays `ring[last_seq - ringStart ..]`.
|
|
15
|
-
* See spec/wsh-v1.yaml (`Resume`, `AttachmentInfo`).
|
|
5
|
+
* The store itself (ring buffer, attachments, TTL, eviction) lives in `../session-registry.mjs`, which has no Node
|
|
6
|
+
* dependency so the in-memory host can use it too. This file adds HMAC-signed session tokens (`node:crypto`).
|
|
16
7
|
*/
|
|
17
8
|
|
|
18
|
-
import { createHmac, randomBytes,
|
|
9
|
+
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
10
|
+
import { SessionRegistry as CoreSessionRegistry } from '../session-registry.mjs';
|
|
19
11
|
|
|
20
|
-
export
|
|
21
|
-
export const DEFAULT_DETACH_TTL_MS = 300_000;
|
|
22
|
-
export const DEFAULT_MAX_DETACHED = 16;
|
|
23
|
-
import { MAX_ATTACHMENTS } from './constants.mjs';
|
|
24
|
-
export { MAX_ATTACHMENTS };
|
|
12
|
+
export { ByteRing, HostedSession, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED, MAX_ATTACHMENTS } from '../session-registry.mjs';
|
|
25
13
|
|
|
26
14
|
const NO_EXPIRY = Buffer.alloc(8, 0xff);
|
|
27
15
|
|
|
28
|
-
/**
|
|
29
|
-
* A bounded byte history addressed by absolute stream position.
|
|
30
|
-
* `start` is the seq of the oldest retained byte, `end` the seq one past the newest.
|
|
31
|
-
*/
|
|
32
|
-
export class ByteRing {
|
|
33
|
-
#chunks = [];
|
|
34
|
-
#size = 0;
|
|
35
|
-
start = 0;
|
|
36
|
-
end = 0;
|
|
37
|
-
|
|
38
|
-
constructor(maxBytes) {
|
|
39
|
-
this.max = maxBytes;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
push(bytes) {
|
|
43
|
-
if (!bytes.byteLength) return;
|
|
44
|
-
this.#chunks.push(Uint8Array.from(bytes));
|
|
45
|
-
this.#size += bytes.byteLength;
|
|
46
|
-
this.end += bytes.byteLength;
|
|
47
|
-
while (this.#size > this.max) {
|
|
48
|
-
const excess = this.#size - this.max;
|
|
49
|
-
const first = this.#chunks[0];
|
|
50
|
-
if (first.byteLength <= excess) {
|
|
51
|
-
this.#chunks.shift();
|
|
52
|
-
this.#size -= first.byteLength;
|
|
53
|
-
this.start += first.byteLength;
|
|
54
|
-
} else {
|
|
55
|
-
this.#chunks[0] = first.subarray(excess);
|
|
56
|
-
this.#size -= excess;
|
|
57
|
-
this.start += excess;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** Bytes from absolute position `from` (clamped to `start`) to the end. */
|
|
63
|
-
read(from = this.start) {
|
|
64
|
-
const skip = Math.max(0, from - this.start);
|
|
65
|
-
const out = new Uint8Array(Math.max(0, this.#size - skip));
|
|
66
|
-
let at = 0;
|
|
67
|
-
let seen = 0;
|
|
68
|
-
for (const c of this.#chunks) {
|
|
69
|
-
if (seen + c.byteLength > skip) {
|
|
70
|
-
const part = c.subarray(Math.max(0, skip - seen));
|
|
71
|
-
out.set(part, at);
|
|
72
|
-
at += part.byteLength;
|
|
73
|
-
}
|
|
74
|
-
seen += c.byteLength;
|
|
75
|
-
}
|
|
76
|
-
return out;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
16
|
/**
|
|
81
17
|
* Mint a session token in the spec's format: `[8B expiry][32B HMAC-SHA256(secret, session_id || expiry)]`.
|
|
82
18
|
* A session's lifetime is governed by `detachTtlMs`, not by its token, so the expiry is the maximum.
|
|
@@ -96,169 +32,13 @@ export function verifyToken(secret, sessionId, token) {
|
|
|
96
32
|
return timingSafeEqual(want, buf.subarray(8));
|
|
97
33
|
}
|
|
98
34
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
* @property {number} connId
|
|
103
|
-
* @property {number} channelId
|
|
104
|
-
* @property {'control' | 'readonly'} mode
|
|
105
|
-
* @property {string} username
|
|
106
|
-
* @property {string} principal - who this connection authenticated as (see `principalKey`)
|
|
107
|
-
* @property {(bytes: Uint8Array) => unknown} write - live output
|
|
108
|
-
* @property {(msg: object) => unknown} notify - an ordered control message (e.g. Presence)
|
|
109
|
-
* @property {(code: number) => unknown} exit - the session ended
|
|
110
|
-
*/
|
|
111
|
-
|
|
112
|
-
export class HostedSession {
|
|
113
|
-
/** @type {Set<Attachment>} */
|
|
114
|
-
attachments = new Set();
|
|
115
|
-
state = 'attached';
|
|
116
|
-
exitCode = null;
|
|
117
|
-
createdAt = Date.now();
|
|
118
|
-
lastActivity = Date.now();
|
|
119
|
-
detachedAt = 0;
|
|
120
|
-
name;
|
|
121
|
-
#timer = null;
|
|
122
|
-
|
|
123
|
-
constructor(registry, { id, token, owner, kind, command, ringBytes }) {
|
|
124
|
-
this.registry = registry;
|
|
125
|
-
this.id = id;
|
|
126
|
-
this.token = token;
|
|
127
|
-
this.owner = owner;
|
|
128
|
-
this.kind = kind;
|
|
129
|
-
this.command = command;
|
|
130
|
-
this.ring = new ByteRing(ringBytes);
|
|
131
|
-
/** Set by the connection once the process exists: `{ input, inputEnd, resize, signal, kill }`. */
|
|
132
|
-
this.handlers = {};
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** Output from the process: retained in the ring, delivered to every attachment. */
|
|
136
|
-
push(bytes) {
|
|
137
|
-
this.lastActivity = Date.now();
|
|
138
|
-
this.ring.push(bytes);
|
|
139
|
-
for (const a of this.attachments) a.write(bytes);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
attach(att) {
|
|
143
|
-
this.attachments.add(att);
|
|
144
|
-
this.state = 'attached';
|
|
145
|
-
this.#clearTimer();
|
|
146
|
-
this.broadcastPresence(att);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
detach(att) {
|
|
150
|
-
if (!this.attachments.delete(att)) return;
|
|
151
|
-
this.broadcastPresence();
|
|
152
|
-
if (this.attachments.size === 0) this.#markDetached();
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
roster() {
|
|
156
|
-
return [...this.attachments].map((a) => ({ session_id: this.id, mode: a.mode, username: a.username }));
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** Tell every attachment (except `except`) who is attached now. */
|
|
160
|
-
broadcastPresence(except) {
|
|
161
|
-
if (this.attachments.size === 0) return;
|
|
162
|
-
const msg = { attachments: this.roster() };
|
|
163
|
-
for (const a of this.attachments) if (a !== except) a.notify(msg);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/** The process ended. Everyone attached hears Exit + Close; the record lingers for late resumes. */
|
|
167
|
-
finish(code) {
|
|
168
|
-
if (this.state === 'exited') return;
|
|
169
|
-
this.exitCode = code;
|
|
170
|
-
this.state = 'exited';
|
|
171
|
-
const att = [...this.attachments];
|
|
172
|
-
this.attachments.clear();
|
|
173
|
-
for (const a of att) a.exit(code);
|
|
174
|
-
this.#markDetached();
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
kill() {
|
|
178
|
-
try { this.handlers.kill?.(); } catch { /* already gone */ }
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
/** Forget the session (and stop it if it is still running). */
|
|
182
|
-
dispose() {
|
|
183
|
-
this.#clearTimer();
|
|
184
|
-
this.registry._forget(this);
|
|
185
|
-
if (this.state !== 'exited') {
|
|
186
|
-
this.kill();
|
|
187
|
-
this.state = 'exited';
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
#markDetached() {
|
|
192
|
-
this.detachedAt = Date.now();
|
|
193
|
-
if (this.state !== 'exited') this.state = 'detached';
|
|
194
|
-
this.#clearTimer();
|
|
195
|
-
const ttl = this.registry.detachTtlMs;
|
|
196
|
-
if (ttl <= 0) { this.dispose(); return; }
|
|
197
|
-
this.#timer = setTimeout(() => {
|
|
198
|
-
this.registry.log(`session ${this.id} expired after ${ttl}ms detached`);
|
|
199
|
-
this.dispose();
|
|
200
|
-
}, ttl);
|
|
201
|
-
this.#timer.unref?.();
|
|
202
|
-
this.registry._enforceMaxDetached(this);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
#clearTimer() {
|
|
206
|
-
clearTimeout(this.#timer);
|
|
207
|
-
this.#timer = null;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
export class SessionRegistry {
|
|
212
|
-
/** @type {Map<string, HostedSession>} */
|
|
213
|
-
#sessions = new Map();
|
|
214
|
-
|
|
215
|
-
constructor({ secret, detachTtlMs = DEFAULT_DETACH_TTL_MS, maxDetached = DEFAULT_MAX_DETACHED, ringBytes = DEFAULT_RING_BYTES, log = () => {} } = {}) {
|
|
35
|
+
export class SessionRegistry extends CoreSessionRegistry {
|
|
36
|
+
constructor({ secret, ...rest } = {}) {
|
|
37
|
+
super(rest);
|
|
216
38
|
this.secret = secret ?? randomBytes(32);
|
|
217
|
-
this.detachTtlMs = detachTtlMs;
|
|
218
|
-
this.maxDetached = maxDetached;
|
|
219
|
-
this.ringBytes = ringBytes;
|
|
220
|
-
this.log = log;
|
|
221
39
|
}
|
|
222
40
|
|
|
223
|
-
|
|
224
|
-
create({ owner, kind, command }) {
|
|
225
|
-
const id = randomUUID();
|
|
226
|
-
const s = new HostedSession(this, { id, token: mintToken(this.secret, id), owner, kind, command, ringBytes: this.ringBytes });
|
|
227
|
-
this.#sessions.set(id, s);
|
|
228
|
-
return s;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
get(id) {
|
|
232
|
-
return typeof id === 'string' ? this.#sessions.get(id) : undefined;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
checkToken(session, token) {
|
|
236
|
-
return verifyToken(this.secret, session.id, token);
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/** Sessions this principal owns. */
|
|
240
|
-
listFor(principal) {
|
|
241
|
-
return [...this.#sessions.values()].filter((s) => s.owner.principal === principal);
|
|
242
|
-
}
|
|
41
|
+
mintToken(sessionId) { return mintToken(this.secret, sessionId); }
|
|
243
42
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
/** Kill everything (server shutdown). */
|
|
247
|
-
closeAll() {
|
|
248
|
-
for (const s of [...this.#sessions.values()]) s.dispose();
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
_forget(session) {
|
|
252
|
-
this.#sessions.delete(session.id);
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
/** Keep at most `maxDetached` unattended sessions: the longest-detached are killed first. */
|
|
256
|
-
_enforceMaxDetached() {
|
|
257
|
-
const detached = [...this.#sessions.values()].filter((s) => s.attachments.size === 0).sort((a, b) => a.detachedAt - b.detachedAt);
|
|
258
|
-
while (detached.length > this.maxDetached) {
|
|
259
|
-
const victim = detached.shift();
|
|
260
|
-
this.log(`session ${victim.id} evicted (more than ${this.maxDetached} detached)`);
|
|
261
|
-
victim.dispose();
|
|
262
|
-
}
|
|
263
|
-
}
|
|
43
|
+
checkToken(session, token) { return verifyToken(this.secret, session.id, token); }
|
|
264
44
|
}
|
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(() => ({
|