@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,339 @@
|
|
|
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 { MSG, reverseAccept, reverseReject, reverseChallenge } from './messages.gen.mjs';
|
|
20
|
+
import { MULTI_OPERATOR_FEATURE } from './server/relay.mjs';
|
|
21
|
+
import { E2E_SIGN_FEATURE, E2EResponder } from './e2e-exchange.mjs';
|
|
22
|
+
import { OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, createReverseChallenge, verifyOperatorProof } from './operator-proof.mjs';
|
|
23
|
+
import { SealedBridge } from './bridge-seal.mjs';
|
|
24
|
+
import { resolveBackends } from './host-backends.mjs';
|
|
25
|
+
import { createConnectionFactory, hostFeatures } from './server/connection.mjs';
|
|
26
|
+
|
|
27
|
+
const BACKOFF_START_MS = 500;
|
|
28
|
+
const BACKOFF_MAX_MS = 30_000;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {object} options
|
|
32
|
+
* @param {string} options.url - The relay (`ws://` or `wss://`).
|
|
33
|
+
* @param {string} options.username
|
|
34
|
+
* @param {CryptoKeyPair} options.keyPair - This host's identity; its fingerprint is what operators connect to.
|
|
35
|
+
* @param {(operator: { fingerprint: string, username: string, proven?: boolean, publicKey?: Uint8Array }) => boolean | Promise<boolean>} [options.accept]
|
|
36
|
+
* Who may be bridged to this host. Default: nobody.
|
|
37
|
+
* @param {true | object | Function} [options.exec]
|
|
38
|
+
* @param {object} [options.pty]
|
|
39
|
+
* @param {object} [options.fs]
|
|
40
|
+
* @param {object} [options.mcp]
|
|
41
|
+
* @param {boolean} [options.reconnect=true] - Dial again (with backoff) after the relay connection ends. A relay ends it when a bridge does.
|
|
42
|
+
* @param {object} [options.connect] - Extra options for the relay connection (`expectHostKey`, `knownHosts`, ...).
|
|
43
|
+
* @param {string} [options.peerType='host']
|
|
44
|
+
* @param {false | { sign?: boolean | 'auto', hybrid?: boolean }} [options.e2e] - End-to-end encryption for the bridged operator (wsh #90).
|
|
45
|
+
* On by default: this host answers an operator's `KeyExchange` (for a session it has opened), then seals that
|
|
46
|
+
* session's output and opens its input as `EncryptedFrame`s the relay cannot read, and ignores plaintext input for it.
|
|
47
|
+
* `sign` signs the reply with `keyPair` so the operator can authenticate this host
|
|
48
|
+
* (`initiateE2E(..., { verifyPeer })`). Default `'auto'`: sign when the relay says (`e2e-sign` in its ServerHello) it
|
|
49
|
+
* carries a signed `KeyExchange` -- a relay that predates the `signature` field (a Rust relay built before it)
|
|
50
|
+
* would drop the connection on one. `true` signs regardless; `false` never does. `hybrid` (default true) offers
|
|
51
|
+
* X25519+ML-KEM-768 when asked.
|
|
52
|
+
* `false` turns the layer off: no `e2e` feature, `KeyExchange` unanswered.
|
|
53
|
+
* @param {number} [options.maxOperators=1] - Operators served at once. Above 1 this host states `relay-multi-operator`
|
|
54
|
+
* (it addresses each reply to its operator and handles `ReverseClose`), so it needs `reportFeatures` and a relay with
|
|
55
|
+
* `relay.maxOperatorsPerPeer` above 1 (which says so in its ServerHello); against any other relay it serves one
|
|
56
|
+
* operator, as before. Each operator is passed through `accept` on its own identity.
|
|
57
|
+
* @param {boolean} [options.reportFeatures=true] - State this host's features in `ReverseAccept.features`, so the operator's
|
|
58
|
+
* feature gates follow this host rather than the relay. Turn off only for a relay (a Rust `wsh-server` older than the field)
|
|
59
|
+
* that rejects a `ReverseAccept` carrying it.
|
|
60
|
+
* @param {boolean} [options.requireOperatorProof=false] - wsh #117. Do not take the operator's identity from the relay.
|
|
61
|
+
* When the relay carries `operator-proof` (its ServerHello says so) and the operator can answer, this host sends it a
|
|
62
|
+
* signed challenge and verifies the operator's signature over this host's fingerprint, a nonce it chose and the
|
|
63
|
+
* bridge's session BEFORE `accept` runs; `accept` then receives `{ fingerprint, username, proven: true, publicKey }`
|
|
64
|
+
* taken from the proof, not from the relay (a relay that rewrote `from_fingerprint` is refused). This option makes
|
|
65
|
+
* that mandatory: an operator that does not prove itself is refused, and the bridge is SEALED -- this host acts only on
|
|
66
|
+
* messages the operator sealed under a key exchange both sides signed, because a relay can stamp any identity on a
|
|
67
|
+
* plain message (it could inject an `Open`). Needs `e2e` (on by default) and `reportFeatures`. Without this option the
|
|
68
|
+
* proof is requested when it can be and reported as `proven`, and the bridge is sealed only if the operator asks.
|
|
69
|
+
* @param {number} [options.proofTimeoutMs=5000] - How long an operator has to answer the challenge.
|
|
70
|
+
* @param {(line: string) => void} [options.onLog]
|
|
71
|
+
*/
|
|
72
|
+
export function createReverseHost(options = {}) {
|
|
73
|
+
return createReverseHostWith(options, resolveBackends(options));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The reverse host proper, given its backends already built: `createReverseHost` here builds them from injected
|
|
78
|
+
* parts only (browser-safe); `@johnhenry/wsh/server`'s builds them with `exec: true` and `fs: { root }` as well.
|
|
79
|
+
* @param {object} options - as for `createReverseHost` (its `exec`, `pty`, `fs` and `mcp` are read by the caller, not here)
|
|
80
|
+
* @param {ReturnType<typeof resolveBackends>} backends
|
|
81
|
+
*/
|
|
82
|
+
export function createReverseHostWith({
|
|
83
|
+
url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {},
|
|
84
|
+
requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {},
|
|
85
|
+
} = {}, backends) {
|
|
86
|
+
if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
|
|
87
|
+
if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
|
|
88
|
+
if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
|
|
89
|
+
if (!url) throw new TypeError('createReverseHost: url is required');
|
|
90
|
+
if (!username) throw new TypeError('createReverseHost: username is required');
|
|
91
|
+
if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
|
|
92
|
+
if (accept !== undefined && typeof accept !== 'function') throw new TypeError('createReverseHost: accept must be a function');
|
|
93
|
+
if (!Number.isSafeInteger(maxOperators) || maxOperators < 1) throw new TypeError('createReverseHost: maxOperators must be a positive integer');
|
|
94
|
+
if (maxOperators > 1 && !reportFeatures) throw new TypeError('createReverseHost: maxOperators > 1 needs reportFeatures (the relay learns "relay-multi-operator" from ReverseAccept.features)');
|
|
95
|
+
if (e2e !== false && (e2e === null || typeof e2e !== 'object')) throw new TypeError('createReverseHost: e2e must be false or an options object');
|
|
96
|
+
const multi = maxOperators > 1;
|
|
97
|
+
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'");
|
|
98
|
+
const e2eSign = e2e === false ? false : (e2e.sign ?? 'auto');
|
|
99
|
+
|
|
100
|
+
const expose = { shell: !!backends.pty, exec: !!backends.execRunner, fs: !!backends.files, tools: !!backends.mcp };
|
|
101
|
+
const capabilities = Object.entries(expose).filter(([, on]) => on).map(([k]) => k);
|
|
102
|
+
const shellBackend = backends.pty ? 'pty' : 'exec-only';
|
|
103
|
+
// What this host can do over a bridge, for the operator's feature gates (`ReverseAccept.features`).
|
|
104
|
+
// `reportFeatures: false` leaves them out (a Rust peer or relay older than the field rejects a ReverseAccept that has it).
|
|
105
|
+
/** What this host does with end-to-end encryption on a given relay connection (null = off). */
|
|
106
|
+
const e2eFor = (c) => (e2e === false ? null : {
|
|
107
|
+
signKey: e2eSign === true || (e2eSign === 'auto' && c.hasFeature(E2E_SIGN_FEATURE)) ? keyPair.privateKey : null,
|
|
108
|
+
hybrid: e2e.hybrid !== false,
|
|
109
|
+
});
|
|
110
|
+
/** Features for `ReverseAccept` on this relay connection. */
|
|
111
|
+
const bridgeFeatures = (c, e2eConfig, manyOperators) => [
|
|
112
|
+
...hostFeatures({ mcp: backends.mcp, files: backends.files, e2e: e2eConfig }, { dataStreams: false }),
|
|
113
|
+
...(manyOperators ? [MULTI_OPERATOR_FEATURE] : []),
|
|
114
|
+
];
|
|
115
|
+
const factory = createConnectionFactory({
|
|
116
|
+
authorize: async () => false, methods: { pubkey: false, password: null }, hostKey: null, rateLimit: null,
|
|
117
|
+
execRunner: backends.execRunner, execOptions: backends.execOptions, pty: backends.pty, files: backends.files, mcp: backends.mcp,
|
|
118
|
+
sessions: null, relay: null, e2e: null, bindTimeoutMs: 3000, log: (l) => onLog(`[reverse] ${l}`),
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
let client = null;
|
|
122
|
+
/** The live connection's bridges (operator fingerprint -> connection), for `operators`. */
|
|
123
|
+
let operatorsNow = new Map();
|
|
124
|
+
/** Ends every bridge of the live connection (the client's own `disconnect()` does not call its `onClose`). */
|
|
125
|
+
let endAllBridges = () => {};
|
|
126
|
+
let myFingerprint = null;
|
|
127
|
+
let myPublicKeyRaw = null;
|
|
128
|
+
let closed = false;
|
|
129
|
+
let timer = null;
|
|
130
|
+
let backoff = BACKOFF_START_MS;
|
|
131
|
+
|
|
132
|
+
async function dial() {
|
|
133
|
+
const c = new WshClient();
|
|
134
|
+
/** operator fingerprint -> that operator's connection (its own channels, processes, files). */
|
|
135
|
+
const bridges = new Map();
|
|
136
|
+
// Several operators only on a relay that says it can route to them; anywhere else, one, and bare messages.
|
|
137
|
+
const manyOperators = () => multi && c.hasFeature(MULTI_OPERATOR_FEATURE);
|
|
138
|
+
const operatorLimit = () => (manyOperators() ? maxOperators : 1);
|
|
139
|
+
/** Operators whose `accept` is still running: they count towards the cap. */
|
|
140
|
+
const reserved = new Set();
|
|
141
|
+
/** challenge nonce (hex) -> resolves with the operator's ReverseProof (or null on timeout) */
|
|
142
|
+
const proofWaiters = new Map();
|
|
143
|
+
operatorsNow = bridges;
|
|
144
|
+
|
|
145
|
+
const endBridge = (fp) => {
|
|
146
|
+
const bridge = bridges.get(fp);
|
|
147
|
+
if (!bridge) return;
|
|
148
|
+
bridges.delete(fp);
|
|
149
|
+
c.untrustRelayPeer(fp);
|
|
150
|
+
bridge.close();
|
|
151
|
+
onLog(`[reverse] operator ${fp.slice(0, 12)} left (${bridges.size} still bridged)`);
|
|
152
|
+
};
|
|
153
|
+
const endAll = () => { for (const fp of [...bridges.keys()]) endBridge(fp); };
|
|
154
|
+
endAllBridges = endAll;
|
|
155
|
+
c.onRelayMessage = (msg, from) => bridges.get(from)?.receiveMessage(msg);
|
|
156
|
+
// The relay says one operator left; the others carry on (it sends this only to a host that stated multi-operator support).
|
|
157
|
+
c.onReverseClose = (m) => endBridge(String(m.target_fingerprint ?? ''));
|
|
158
|
+
c.onReverseConnect = async (req) => {
|
|
159
|
+
const from = req.from_fingerprint;
|
|
160
|
+
const answer = (m) => c.sendRelayControl(m).catch(() => {});
|
|
161
|
+
const refuse = (reason) => answer(reverseReject({ targetFingerprint: myFingerprint, username, reason }));
|
|
162
|
+
if (typeof from !== 'string' || !from) { await refuse('busy: this host is already serving an operator'); return; }
|
|
163
|
+
if (bridges.has(from) || reserved.has(from)) { await refuse('busy: you already have a bridge with this host'); return; }
|
|
164
|
+
if (bridges.size + reserved.size >= operatorLimit()) {
|
|
165
|
+
await refuse(manyOperators() ? `busy: this host is already serving its maximum of ${maxOperators} operators` : 'busy: this host is already serving an operator');
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
reserved.add(from);
|
|
169
|
+
let ok = false;
|
|
170
|
+
try {
|
|
171
|
+
// Who is this operator? The relay says (`from`); with proof the operator says so itself (#117).
|
|
172
|
+
const canProve = c.hasFeature(OPERATOR_PROOF_FEATURE) && Array.isArray(req.features) && req.features.includes(OPERATOR_PROOF_FEATURE);
|
|
173
|
+
if (requireOperatorProof && !canProve) { await refuse('operator proof required'); return; }
|
|
174
|
+
let proven = null;
|
|
175
|
+
let challenge = null;
|
|
176
|
+
if (canProve) {
|
|
177
|
+
const outcome = await challengeOperator(c, from);
|
|
178
|
+
if (outcome.error) { await refuse(outcome.error); return; }
|
|
179
|
+
({ proven, challenge } = outcome);
|
|
180
|
+
// The relay's claim and the operator's own must agree: a relay that rewrote from_fingerprint is caught here.
|
|
181
|
+
if (proven.fingerprint !== from) { onLog(`[reverse] proof is by ${proven.fingerprint.slice(0, 12)}, the relay said ${from.slice(0, 12)}`); await refuse('operator proof does not match the identity the relay asserted'); return; }
|
|
182
|
+
if (proven.username !== String(req.username ?? '')) { await refuse('operator proof names another username than the relay asserted'); return; }
|
|
183
|
+
}
|
|
184
|
+
const who = { fingerprint: from, username: String(req.username ?? ''), proven: !!proven, ...(proven ? { publicKey: proven.publicKey } : {}) };
|
|
185
|
+
try { ok = (await accept?.(who)) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
|
|
186
|
+
if (!ok || bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
|
|
187
|
+
c.trustRelayPeer(from);
|
|
188
|
+
const bridge = makeBridge(c, from, String(req.username ?? 'operator'), proven, challenge);
|
|
189
|
+
bridges.set(from, bridge);
|
|
190
|
+
onLog(`[reverse] bridged to ${from.slice(0, 12)}${proven ? ' (operator proven)' : ''}${requireOperatorProof ? ', sealed' : ''}`);
|
|
191
|
+
await answer(reverseAccept({
|
|
192
|
+
targetFingerprint: myFingerprint, username, capabilities, peerType, shellBackend,
|
|
193
|
+
supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
|
|
194
|
+
features: reportFeatures ? [...bridgeFeatures(c, e2eFor(c), manyOperators()), ...(proven && e2e !== false ? [E2E_SEALED_FEATURE] : [])] : undefined,
|
|
195
|
+
}));
|
|
196
|
+
} finally { reserved.delete(from); }
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/** Send a signed challenge, wait for the operator's proof and verify it. @returns {Promise<{ error?: string, proven?: object, challenge?: object }>} */
|
|
200
|
+
async function challengeOperator(conn, from) {
|
|
201
|
+
const issued = await createReverseChallenge({ keyPair }, from);
|
|
202
|
+
const key = Array.from(issued.nonce, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
203
|
+
const proofMsg = new Promise((resolve) => { proofWaiters.set(key, resolve); });
|
|
204
|
+
const timer = setTimeout(() => { proofWaiters.get(key)?.(null); }, proofTimeoutMs);
|
|
205
|
+
timer.unref?.();
|
|
206
|
+
try {
|
|
207
|
+
await conn.sendRelayControl(reverseChallenge({ targetFingerprint: from, ...issued.fields }));
|
|
208
|
+
const msg = await proofMsg;
|
|
209
|
+
if (!msg) return { error: 'operator did not answer the challenge' };
|
|
210
|
+
const proven = await verifyOperatorProof(msg, issued);
|
|
211
|
+
if (!proven) return { error: 'operator proof does not verify' };
|
|
212
|
+
return { proven, challenge: issued };
|
|
213
|
+
} catch (e) {
|
|
214
|
+
onLog(`[reverse] challenge failed: ${e.message}`);
|
|
215
|
+
return { error: 'operator proof failed' };
|
|
216
|
+
} finally { clearTimeout(timer); proofWaiters.delete(key); }
|
|
217
|
+
}
|
|
218
|
+
c.onReverseProof = (m) => {
|
|
219
|
+
if (!(m.nonce instanceof Uint8Array)) return;
|
|
220
|
+
const key = Array.from(m.nonce, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
221
|
+
proofWaiters.get(key)?.(m);
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* The connection for one bridged operator. A proven operator may seal the bridge (a signed `KeyExchange` for the
|
|
226
|
+
* challenge's session id); with `requireOperatorProof` it must, and until it has the host hears nothing else.
|
|
227
|
+
*/
|
|
228
|
+
function makeBridge(conn, from, operatorName, proven, challenge) {
|
|
229
|
+
const to = () => (manyOperators() ? { to: from } : undefined);
|
|
230
|
+
let sealed = null;
|
|
231
|
+
const mustSeal = requireOperatorProof;
|
|
232
|
+
const base = factory({
|
|
233
|
+
// With several operators every message names its recipient; with one the relay knows.
|
|
234
|
+
sendMessage: async (m) => {
|
|
235
|
+
if (sealed) return conn.sendRelayControl(await sealed.seal(m), to());
|
|
236
|
+
if (mustSeal) return undefined; // nothing may leave a bridge that is not sealed yet
|
|
237
|
+
return conn.sendRelayControl(m, to());
|
|
238
|
+
},
|
|
239
|
+
authenticated: { username: operatorName, fingerprint: from },
|
|
240
|
+
dataStreams: false,
|
|
241
|
+
e2e: e2eFor(conn),
|
|
242
|
+
});
|
|
243
|
+
if (!proven || e2e === false) return base;
|
|
244
|
+
|
|
245
|
+
const responder = new E2EResponder({
|
|
246
|
+
signKey: keyPair.privateKey, hybrid: e2e.hybrid !== false, identity: myPublicKeyRaw,
|
|
247
|
+
initiator: { publicKey: proven.publicKey, require: true },
|
|
248
|
+
});
|
|
249
|
+
let chain = Promise.resolve();
|
|
250
|
+
let giveUp = null;
|
|
251
|
+
const fail = (why) => { onLog(`[reverse] sealed bridge with ${from.slice(0, 12)} failed: ${why}`); endBridge(from); };
|
|
252
|
+
if (mustSeal) {
|
|
253
|
+
giveUp = setTimeout(() => { if (!sealed) fail('no key exchange in time'); }, proofTimeoutMs * 2);
|
|
254
|
+
giveUp.unref?.();
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
receiveMessage(msg) {
|
|
258
|
+
if (sealed) {
|
|
259
|
+
if (!sealed.isFrame(msg)) { onLog('[reverse] dropped a plaintext message on a sealed bridge'); return; }
|
|
260
|
+
chain = chain.then(async () => base.receiveMessage(await sealed.open(msg))).catch((e) => onLog(`[reverse] dropped a sealed frame: ${e.message}`));
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === challenge.sessionId) {
|
|
264
|
+
chain = chain.then(async () => {
|
|
265
|
+
const result = await responder.respond(msg, (reply) => conn.sendRelayControl(reply, to()));
|
|
266
|
+
if (result.key) {
|
|
267
|
+
sealed = new SealedBridge({ key: result.key, sessionId: challenge.sessionId, role: 'responder' });
|
|
268
|
+
clearTimeout(giveUp);
|
|
269
|
+
onLog(`[reverse] bridge to ${from.slice(0, 12)} sealed${result.hybrid ? ' (hybrid)' : ''}`);
|
|
270
|
+
}
|
|
271
|
+
}).catch((e) => fail(e.message));
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (mustSeal) { onLog(`[reverse] dropped a message that is not sealed (type ${msg.type}) on a bridge that must be`); return; }
|
|
275
|
+
base.receiveMessage(msg);
|
|
276
|
+
},
|
|
277
|
+
bindStream: (s) => base.bindStream?.(s),
|
|
278
|
+
close() { clearTimeout(giveUp); responder.close(); base.close(); },
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
c.onClose = () => {
|
|
282
|
+
endAll();
|
|
283
|
+
if (operatorsNow === bridges) operatorsNow = new Map();
|
|
284
|
+
if (client === c) client = null;
|
|
285
|
+
if (closed || !reconnect) return;
|
|
286
|
+
onLog(`[reverse] relay connection ended; redialling in ${backoff}ms`);
|
|
287
|
+
timer = setTimeout(() => { redial().catch(() => {}); }, backoff);
|
|
288
|
+
timer.unref?.();
|
|
289
|
+
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
await c.connectReverse(url, {
|
|
293
|
+
username, keyPair, expose, peerType, shellBackend,
|
|
294
|
+
supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
|
|
295
|
+
...connect,
|
|
296
|
+
});
|
|
297
|
+
client = c;
|
|
298
|
+
backoff = BACKOFF_START_MS;
|
|
299
|
+
onLog(`[reverse] registered ${myFingerprint.slice(0, 12)} on ${url}`);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function redial() {
|
|
303
|
+
if (closed) return;
|
|
304
|
+
try { await dial(); } catch (e) {
|
|
305
|
+
onLog(`[reverse] redial failed: ${e.message}`);
|
|
306
|
+
if (closed || !reconnect) return;
|
|
307
|
+
timer = setTimeout(() => { redial().catch(() => {}); }, backoff);
|
|
308
|
+
timer.unref?.();
|
|
309
|
+
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
/** Dial the relay and register. Rejects if the first attempt fails; later drops are retried. */
|
|
315
|
+
async start() {
|
|
316
|
+
if (client) throw new Error('createReverseHost: already started');
|
|
317
|
+
closed = false;
|
|
318
|
+
myPublicKeyRaw = await exportPublicKeyRaw(keyPair.publicKey);
|
|
319
|
+
myFingerprint = await fingerprint(myPublicKeyRaw);
|
|
320
|
+
await dial();
|
|
321
|
+
return { fingerprint: myFingerprint };
|
|
322
|
+
},
|
|
323
|
+
/** Leave the relay and end any bridged session. */
|
|
324
|
+
async close() {
|
|
325
|
+
closed = true;
|
|
326
|
+
clearTimeout(timer);
|
|
327
|
+
const c = client;
|
|
328
|
+
client = null;
|
|
329
|
+
endAllBridges(); // no operator's process may outlive the host
|
|
330
|
+
await c?.disconnect().catch(() => {});
|
|
331
|
+
},
|
|
332
|
+
/** This host's fingerprint (what operators `reverseConnect()` to); `null` before `start()`. */
|
|
333
|
+
get fingerprint() { return myFingerprint; },
|
|
334
|
+
/** Is the relay connection up right now? */
|
|
335
|
+
get connected() { return client !== null; },
|
|
336
|
+
/** Fingerprints of the operators bridged right now. */
|
|
337
|
+
get operators() { return [...operatorsNow.keys()]; },
|
|
338
|
+
};
|
|
339
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The destination-address guard of the gateway: is an IP address one a host may dial on a client's behalf without
|
|
3
|
+
* an explicit rule? "Public" here means globally routable unicast. Loopback, private (RFC 1918, ULA), link-local,
|
|
4
|
+
* carrier-grade NAT, documentation, benchmarking, multicast and reserved ranges are NOT public, and neither is an
|
|
5
|
+
* address that merely wraps one of those: an IPv4-mapped IPv6 address (`::ffff:127.0.0.1`), a NAT64 address
|
|
6
|
+
* (`64:ff9b::7f00:1`), a 6to4 address (`2002:7f00:1::`) or an IPv4-compatible one (`::127.0.0.1`).
|
|
7
|
+
*
|
|
8
|
+
* Pure JavaScript with no `node:*` import (the gateway module is part of the browser-safe memory host's import
|
|
9
|
+
* graph). It parses text strictly: it is given the addresses a resolver RETURNED, never a name or a number a client
|
|
10
|
+
* wrote, so the odd spellings `getaddrinfo` accepts (`2130706433`, `0x7f.1`) never reach it as an address.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** @returns {Uint8Array | null} 4 bytes */
|
|
14
|
+
function parseV4(text) {
|
|
15
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(text);
|
|
16
|
+
if (!m) return null;
|
|
17
|
+
const out = new Uint8Array(4);
|
|
18
|
+
for (let i = 0; i < 4; i++) {
|
|
19
|
+
const part = m[i + 1];
|
|
20
|
+
if (part.length > 1 && part[0] === '0') return null; // no leading zeros: "010" is octal to some parsers
|
|
21
|
+
const n = Number(part);
|
|
22
|
+
if (n > 255) return null;
|
|
23
|
+
out[i] = n;
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @returns {Uint8Array | null} 16 bytes */
|
|
29
|
+
function parseV6(text) {
|
|
30
|
+
if (text.includes('%')) return null; // a zone id is local to the host's interfaces: never public
|
|
31
|
+
let s = text;
|
|
32
|
+
let tail = null;
|
|
33
|
+
const lastColon = s.lastIndexOf(':');
|
|
34
|
+
if (lastColon !== -1 && s.includes('.', lastColon)) {
|
|
35
|
+
const v4 = parseV4(s.slice(lastColon + 1));
|
|
36
|
+
if (!v4) return null;
|
|
37
|
+
tail = v4;
|
|
38
|
+
s = `${s.slice(0, lastColon + 1)}0:0`; // two groups stand in for the dotted tail
|
|
39
|
+
}
|
|
40
|
+
const dbl = s.split('::');
|
|
41
|
+
if (dbl.length > 2) return null;
|
|
42
|
+
const groups = (part) => (part === '' ? [] : part.split(':'));
|
|
43
|
+
const head = groups(dbl[0]);
|
|
44
|
+
const rest = dbl.length === 2 ? groups(dbl[1]) : [];
|
|
45
|
+
const all = [...head, ...rest];
|
|
46
|
+
if (all.some((g) => !/^[0-9a-fA-F]{1,4}$/.test(g))) return null;
|
|
47
|
+
let words;
|
|
48
|
+
if (dbl.length === 2) {
|
|
49
|
+
const fill = 8 - head.length - rest.length;
|
|
50
|
+
if (fill < 1) return null;
|
|
51
|
+
words = [...head, ...Array(fill).fill('0'), ...rest];
|
|
52
|
+
} else {
|
|
53
|
+
if (head.length !== 8) return null;
|
|
54
|
+
words = head;
|
|
55
|
+
}
|
|
56
|
+
const out = new Uint8Array(16);
|
|
57
|
+
words.forEach((w, i) => { const n = parseInt(w, 16); out[2 * i] = n >> 8; out[2 * i + 1] = n & 255; });
|
|
58
|
+
if (tail) out.set(tail, 12);
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @param {string} text
|
|
64
|
+
* @returns {{ v: 4 | 6, bytes: Uint8Array } | null}
|
|
65
|
+
*/
|
|
66
|
+
export function parseIp(text) {
|
|
67
|
+
if (typeof text !== 'string') return null;
|
|
68
|
+
const t = text.trim();
|
|
69
|
+
const v4 = parseV4(t);
|
|
70
|
+
if (v4) return { v: 4, bytes: v4 };
|
|
71
|
+
const v6 = parseV6(t);
|
|
72
|
+
return v6 ? { v: 6, bytes: v6 } : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const V4_NON_PUBLIC = [
|
|
76
|
+
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12],
|
|
77
|
+
['192.0.0.0', 24], ['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15],
|
|
78
|
+
['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4],
|
|
79
|
+
].map(([a, bits]) => ({ bytes: parseV4(a), bits }));
|
|
80
|
+
|
|
81
|
+
/** Do the first `bits` bits of `a` and `b` agree? */
|
|
82
|
+
function samePrefix(a, b, bits) {
|
|
83
|
+
const whole = bits >> 3;
|
|
84
|
+
for (let i = 0; i < whole; i++) if (a[i] !== b[i]) return false;
|
|
85
|
+
const rem = bits & 7;
|
|
86
|
+
if (!rem) return true;
|
|
87
|
+
const mask = (0xff << (8 - rem)) & 0xff;
|
|
88
|
+
return (a[whole] & mask) === (b[whole] & mask);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function v4Public(b) {
|
|
92
|
+
return !V4_NON_PUBLIC.some((r) => samePrefix(b, r.bytes, r.bits));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const zero = (b, from, to) => { for (let i = from; i < to; i++) if (b[i] !== 0) return false; return true; };
|
|
96
|
+
|
|
97
|
+
/** The IPv4 address an IPv6 one wraps (mapped, NAT64, 6to4), or null if it wraps none. */
|
|
98
|
+
function embeddedV4(b) {
|
|
99
|
+
if (zero(b, 0, 10) && b[10] === 0xff && b[11] === 0xff) return b.subarray(12, 16); // ::ffff:a.b.c.d
|
|
100
|
+
if (b[0] === 0 && b[1] === 0x64 && b[2] === 0xff && b[3] === 0x9b && zero(b, 4, 12)) return b.subarray(12, 16); // 64:ff9b::/96
|
|
101
|
+
if (b[0] === 0x20 && b[1] === 0x02) return b.subarray(2, 6); // 2002::/16 (6to4)
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Is this address (text, as a resolver returns it) globally routable unicast, wrapped forms included? */
|
|
106
|
+
export function isPublicAddress(text) {
|
|
107
|
+
const ip = parseIp(text);
|
|
108
|
+
if (!ip) return false;
|
|
109
|
+
if (ip.v === 4) return v4Public(ip.bytes);
|
|
110
|
+
const b = ip.bytes;
|
|
111
|
+
const inner = embeddedV4(b);
|
|
112
|
+
if (inner) return v4Public(inner);
|
|
113
|
+
if (zero(b, 0, 12)) return false; // ::/96: unspecified, loopback, the deprecated IPv4-compatible form
|
|
114
|
+
if ((b[0] & 0xe0) !== 0x20) return false; // only 2000::/3 is global unicast
|
|
115
|
+
if (b[0] === 0x20 && b[1] === 0x01 && b[2] <= 0x01) return false; // 2001::/23: IETF protocol assignments, Teredo, ORCHID...
|
|
116
|
+
if (b[0] === 0x20 && b[1] === 0x01 && b[2] === 0x0d && b[3] === 0xb8) return false; // 2001:db8::/32 documentation
|
|
117
|
+
if (b[0] === 0x3f && b[1] === 0xff && (b[2] & 0xf0) === 0) return false; // 3fff::/20 documentation
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* A CIDR block or a single address: `10.0.0.0/8`, `127.0.0.1`, `::1`, `fd00::/8`.
|
|
123
|
+
* @returns {{ v: 4 | 6, bytes: Uint8Array, bits: number } | null}
|
|
124
|
+
*/
|
|
125
|
+
export function parseCidr(text) {
|
|
126
|
+
if (typeof text !== 'string') return null;
|
|
127
|
+
const [addr, len, ...extra] = text.trim().split('/');
|
|
128
|
+
if (extra.length) return null;
|
|
129
|
+
const ip = parseIp(addr);
|
|
130
|
+
if (!ip) return null;
|
|
131
|
+
const max = ip.v === 4 ? 32 : 128;
|
|
132
|
+
let bits = max;
|
|
133
|
+
if (len !== undefined) {
|
|
134
|
+
if (!/^\d{1,3}$/.test(len)) return null;
|
|
135
|
+
bits = Number(len);
|
|
136
|
+
if (bits > max) return null;
|
|
137
|
+
}
|
|
138
|
+
return { v: ip.v, bytes: ip.bytes, bits };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** An IPv4-mapped IPv6 address is compared as the IPv4 address it wraps. */
|
|
142
|
+
function normalized(ip) {
|
|
143
|
+
if (ip.v === 6 && zero(ip.bytes, 0, 10) && ip.bytes[10] === 0xff && ip.bytes[11] === 0xff) return { v: 4, bytes: ip.bytes.subarray(12, 16) };
|
|
144
|
+
return ip;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Is `text` inside the CIDR block (see `parseCidr`)? A mapped IPv6 address is tested as the IPv4 one it wraps. */
|
|
148
|
+
export function addressInCidr(text, cidr) {
|
|
149
|
+
const ip = parseIp(text);
|
|
150
|
+
if (!ip || !cidr) return false;
|
|
151
|
+
const a = normalized(ip);
|
|
152
|
+
const c = normalized({ v: cidr.v, bytes: cidr.bytes });
|
|
153
|
+
const bits = cidr.v === 6 && c.v === 4 ? cidr.bits - 96 : cidr.bits;
|
|
154
|
+
if (a.v !== c.v || bits < 0) return false;
|
|
155
|
+
return samePrefix(a.bytes, c.bytes, bits);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Do two address strings name the same address (a mapped IPv6 address equals the IPv4 one it wraps)? */
|
|
159
|
+
export function sameAddress(a, b) {
|
|
160
|
+
const x = parseIp(a); const y = parseIp(b);
|
|
161
|
+
if (!x || !y) return false;
|
|
162
|
+
const nx = normalized(x); const ny = normalized(y);
|
|
163
|
+
return nx.v === ny.v && samePrefix(nx.bytes, ny.bytes, nx.v === 4 ? 32 : 128);
|
|
164
|
+
}
|
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
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which environment variables a client may set for the command or shell a host runs (`Open.env`).
|
|
3
|
+
*
|
|
4
|
+
* The default is an allow-list in the spirit of sshd's `AcceptEnv`: `TERM`, `COLORTERM`, `LANG`, `LANGUAGE` and
|
|
5
|
+
* `LC_*`. Anything else -- `PATH`, `LD_PRELOAD`, `BASH_ENV`, `NODE_OPTIONS` -- lets a client change what a host that
|
|
6
|
+
* restricts what runs (an `exec` function, a fixed command set, a restricted shell) actually executes, so it takes
|
|
7
|
+
* an explicit opt-in.
|
|
8
|
+
*
|
|
9
|
+
* Accepted forms of the option (`exec.clientEnv`, `pty.clientEnv`):
|
|
10
|
+
* undefined the default allow-list above
|
|
11
|
+
* true accept everything (the behaviour before this list existed)
|
|
12
|
+
* false accept nothing
|
|
13
|
+
* string[] exact names, or a prefix ending in `*` (`'LC_*'`); NOT merged with the default list
|
|
14
|
+
* (name, value) => boolean decide per variable
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
18
|
+
export const MAX_ENV_VARS = 64;
|
|
19
|
+
export const MAX_ENV_VALUE_BYTES = 4096;
|
|
20
|
+
|
|
21
|
+
/** The names a host accepts when `clientEnv` is not set. */
|
|
22
|
+
export const DEFAULT_CLIENT_ENV = Object.freeze(['TERM', 'COLORTERM', 'LANG', 'LANGUAGE', 'LC_*']);
|
|
23
|
+
|
|
24
|
+
const matcher = (patterns) => {
|
|
25
|
+
const exact = new Set();
|
|
26
|
+
const prefixes = [];
|
|
27
|
+
for (const p of patterns) {
|
|
28
|
+
if (typeof p !== 'string' || !p) throw new TypeError('clientEnv: list entries must be non-empty strings');
|
|
29
|
+
if (p.endsWith('*')) prefixes.push(p.slice(0, -1)); else exact.add(p);
|
|
30
|
+
}
|
|
31
|
+
return (name) => exact.has(name) || prefixes.some((pre) => name.startsWith(pre));
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {undefined | boolean | string[] | ((name: string, value: string) => boolean)} option
|
|
36
|
+
* @returns {(requested: unknown) => Record<string, string>} keeps only what the host accepts
|
|
37
|
+
*/
|
|
38
|
+
export function clientEnvFilter(option) {
|
|
39
|
+
let allow;
|
|
40
|
+
if (option === undefined) allow = matcher(DEFAULT_CLIENT_ENV);
|
|
41
|
+
else if (option === true) allow = () => true;
|
|
42
|
+
else if (option === false) allow = () => false;
|
|
43
|
+
else if (Array.isArray(option)) allow = matcher(option);
|
|
44
|
+
else if (typeof option === 'function') allow = option;
|
|
45
|
+
else throw new TypeError('clientEnv must be true, false, an array of names or a function (name, value) => boolean');
|
|
46
|
+
|
|
47
|
+
return (requested) => {
|
|
48
|
+
const out = {};
|
|
49
|
+
if (!requested || typeof requested !== 'object' || Array.isArray(requested)) return out;
|
|
50
|
+
let seen = 0;
|
|
51
|
+
for (const [name, value] of Object.entries(requested)) {
|
|
52
|
+
if (++seen > MAX_ENV_VARS) break;
|
|
53
|
+
if (!NAME_RE.test(name) || typeof value !== 'string' || value.length > MAX_ENV_VALUE_BYTES || value.includes('\0')) continue;
|
|
54
|
+
let ok = false;
|
|
55
|
+
try { ok = allow(name, value) === true; } catch { ok = false; }
|
|
56
|
+
if (ok) out[name] = value;
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
};
|
|
60
|
+
}
|