@johnhenry/wsh 0.36.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.
@@ -16,9 +16,11 @@
16
16
 
17
17
  import { WshClient } from './client.mjs';
18
18
  import { exportPublicKeyRaw, fingerprint } from './auth.mjs';
19
- import { reverseAccept, reverseReject } from './messages.gen.mjs';
19
+ import { MSG, reverseAccept, reverseReject, reverseChallenge } from './messages.gen.mjs';
20
20
  import { MULTI_OPERATOR_FEATURE } from './server/relay.mjs';
21
- import { E2E_SIGN_FEATURE } from './e2e-exchange.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';
22
24
  import { resolveBackends } from './host-backends.mjs';
23
25
  import { createConnectionFactory, hostFeatures } from './server/connection.mjs';
24
26
 
@@ -30,7 +32,7 @@ const BACKOFF_MAX_MS = 30_000;
30
32
  * @param {string} options.url - The relay (`ws://` or `wss://`).
31
33
  * @param {string} options.username
32
34
  * @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]
35
+ * @param {(operator: { fingerprint: string, username: string, proven?: boolean, publicKey?: Uint8Array }) => boolean | Promise<boolean>} [options.accept]
34
36
  * Who may be bridged to this host. Default: nobody.
35
37
  * @param {true | object | Function} [options.exec]
36
38
  * @param {object} [options.pty]
@@ -55,6 +57,16 @@ const BACKOFF_MAX_MS = 30_000;
55
57
  * @param {boolean} [options.reportFeatures=true] - State this host's features in `ReverseAccept.features`, so the operator's
56
58
  * feature gates follow this host rather than the relay. Turn off only for a relay (a Rust `wsh-server` older than the field)
57
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.
58
70
  * @param {(line: string) => void} [options.onLog]
59
71
  */
60
72
  export function createReverseHost(options = {}) {
@@ -68,8 +80,12 @@ export function createReverseHost(options = {}) {
68
80
  * @param {ReturnType<typeof resolveBackends>} backends
69
81
  */
70
82
  export function createReverseHostWith({
71
- url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {}, onLog = () => {},
83
+ url, username, keyPair, accept, reconnect = true, connect = {}, peerType = 'host', reportFeatures = true, maxOperators = 1, e2e = {},
84
+ requireOperatorProof = false, proofTimeoutMs = 5000, onLog = () => {},
72
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)');
73
89
  if (!url) throw new TypeError('createReverseHost: url is required');
74
90
  if (!username) throw new TypeError('createReverseHost: username is required');
75
91
  if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
@@ -108,6 +124,7 @@ export function createReverseHostWith({
108
124
  /** Ends every bridge of the live connection (the client's own `disconnect()` does not call its `onClose`). */
109
125
  let endAllBridges = () => {};
110
126
  let myFingerprint = null;
127
+ let myPublicKeyRaw = null;
111
128
  let closed = false;
112
129
  let timer = null;
113
130
  let backoff = BACKOFF_START_MS;
@@ -121,6 +138,8 @@ export function createReverseHostWith({
121
138
  const operatorLimit = () => (manyOperators() ? maxOperators : 1);
122
139
  /** Operators whose `accept` is still running: they count towards the cap. */
123
140
  const reserved = new Set();
141
+ /** challenge nonce (hex) -> resolves with the operator's ReverseProof (or null on timeout) */
142
+ const proofWaiters = new Map();
124
143
  operatorsNow = bridges;
125
144
 
126
145
  const endBridge = (fp) => {
@@ -149,25 +168,116 @@ export function createReverseHostWith({
149
168
  reserved.add(from);
150
169
  let ok = false;
151
170
  try {
152
- try { ok = (await accept?.({ fingerprint: from, username: String(req.username ?? '') })) === true; } catch (e) { onLog(`[reverse] accept threw: ${e.message}`); }
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}`); }
153
186
  if (!ok || bridges.size >= operatorLimit()) { await refuse('not accepted'); return; }
154
187
  c.trustRelayPeer(from);
155
- const bridge = factory({
156
- // With several operators every message names its recipient; with one the relay knows.
157
- sendMessage: (m) => c.sendRelayControl(m, manyOperators() ? { to: from } : undefined),
158
- authenticated: { username: String(req.username ?? 'operator'), fingerprint: from },
159
- dataStreams: false,
160
- e2e: e2eFor(c),
161
- });
188
+ const bridge = makeBridge(c, from, String(req.username ?? 'operator'), proven, challenge);
162
189
  bridges.set(from, bridge);
163
- onLog(`[reverse] bridged to ${from.slice(0, 12)}`);
190
+ onLog(`[reverse] bridged to ${from.slice(0, 12)}${proven ? ' (operator proven)' : ''}${requireOperatorProof ? ', sealed' : ''}`);
164
191
  await answer(reverseAccept({
165
192
  targetFingerprint: myFingerprint, username, capabilities, peerType, shellBackend,
166
193
  supportsAttach: false, supportsReplay: false, supportsEcho: false, supportsTermSync: false,
167
- features: reportFeatures ? bridgeFeatures(c, e2eFor(c), manyOperators()) : undefined,
194
+ features: reportFeatures ? [...bridgeFeatures(c, e2eFor(c), manyOperators()), ...(proven && e2e !== false ? [E2E_SEALED_FEATURE] : [])] : undefined,
168
195
  }));
169
196
  } finally { reserved.delete(from); }
170
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
+ }
171
281
  c.onClose = () => {
172
282
  endAll();
173
283
  if (operatorsNow === bridges) operatorsNow = new Map();
@@ -205,7 +315,8 @@ export function createReverseHostWith({
205
315
  async start() {
206
316
  if (client) throw new Error('createReverseHost: already started');
207
317
  closed = false;
208
- myFingerprint = await fingerprint(await exportPublicKeyRaw(keyPair.publicKey));
318
+ myPublicKeyRaw = await exportPublicKeyRaw(keyPair.publicKey);
319
+ myFingerprint = await fingerprint(myPublicKeyRaw);
209
320
  await dial();
210
321
  return { fingerprint: myFingerprint };
211
322
  },
@@ -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
+ }
@@ -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
+ }
@@ -29,6 +29,10 @@ import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } f
29
29
  import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
30
30
  import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
31
31
  import { MULTI_OPERATOR_FEATURE } from './relay.mjs';
32
+ import { gatewayFeatures } from './gateway-core.mjs';
33
+ import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
34
+ import { clientEnvFilter } from './client-env.mjs';
35
+ import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
32
36
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
33
37
 
34
38
  export const STREAM_ANNOUNCE = 'stream-announce';
@@ -42,14 +46,14 @@ export const STREAM_ANNOUNCE = 'stream-announce';
42
46
  export function hostFeatures(cfg, { dataStreams = true } = {}) {
43
47
  const features = dataStreams ? [STREAM_ANNOUNCE] : [];
44
48
  if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
45
- if (cfg.gateway) features.push('gateway');
49
+ if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
46
50
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
47
51
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
48
52
  // client-opened streams: over a relay bridge.
49
53
  // A relay carries a signed KeyExchange untouched, and (when configured) several operators per peer: peers read
50
54
  // these from its ServerHello before relying on either, since an older relay would drop the connection on them.
51
55
  if (cfg.relay) {
52
- features.push(E2E_SIGN_FEATURE);
56
+ features.push(E2E_SIGN_FEATURE, OPERATOR_PROOF_FEATURE);
53
57
  if (cfg.relay.maxOperatorsPerPeer > 1) features.push(MULTI_OPERATOR_FEATURE);
54
58
  }
55
59
  if (cfg.e2e && !dataStreams) features.push(E2E_FEATURE, ...(cfg.e2e.signKey ? [E2E_SIGN_FEATURE] : []));
@@ -111,6 +115,9 @@ export function createConnectionFactory(cfg) {
111
115
  log: cfg.log ?? (() => {}),
112
116
  };
113
117
  let counter = 0;
118
+ // What a client may put in `Open.env` (#126): an allow-list unless the host says otherwise.
119
+ const execEnv = clientEnvFilter(cfg.execOptions?.clientEnv);
120
+ const ptyEnv = clientEnvFilter(cfg.pty?.clientEnv);
114
121
 
115
122
  /**
116
123
  * Attach one connection. Two shapes:
@@ -121,7 +128,7 @@ export function createConnectionFactory(cfg) {
121
128
  * `dataStreams: false` means there are no client-opened streams to bind, so exec output rides SessionData.
122
129
  * `e2e` overrides `cfg.e2e` for this connection.
123
130
  */
124
- return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride }) {
131
+ return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride, channelBinding = null }) {
125
132
  const cid = ++counter;
126
133
  const log = (m) => cfg.log(`[conn ${cid}] ${m}`);
127
134
  const state = {
@@ -144,11 +151,16 @@ export function createConnectionFactory(cfg) {
144
151
  let chain = Promise.resolve();
145
152
  /** This connection as the relay hub sees it (created on first need). */
146
153
  let relayHandle = null;
154
+ /** Ends the connection at `connectionTtlMs` after authentication (#125). */
155
+ let ttlTimer = null;
147
156
 
148
157
  // The gateway needs Node sockets, so `gateway.mjs` is not imported here (a browser host must not pull it in):
149
- // the embedder that has them (`createWshServer`) passes `cfg.createGatewaySession` along with `cfg.gateway`.
158
+ // the embedder that has them (`createWshServer`) passes `cfg.createGatewaySession` along with `cfg.gateway`; a
159
+ // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
150
160
  if (cfg.gateway && typeof cfg.createGatewaySession !== 'function') throw new TypeError('createConnectionFactory: gateway needs createGatewaySession (only @johnhenry/wsh/server provides one)');
151
- const gateway = cfg.gateway ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log) : null;
161
+ const gateway = cfg.gateway
162
+ ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }) })
163
+ : null;
152
164
 
153
165
  const qmux = sendMessage ? null : new QMuxConnection({ isClient: false, send: (b) => { if (!state.closed) sendBytes(b); } });
154
166
 
@@ -198,6 +210,7 @@ export function createConnectionFactory(cfg) {
198
210
  function shutdown(why) {
199
211
  if (state.closed) return;
200
212
  state.closed = true;
213
+ clearTimeout(ttlTimer);
201
214
  // A hosted session survives its connection (it is detached, then expires or is resumed);
202
215
  // everything else dies with it.
203
216
  for (const ch of [...channels.values()]) (ch.detach ?? ch.kill)?.call(ch);
@@ -317,6 +330,20 @@ export function createConnectionFactory(cfg) {
317
330
  channels.get(m.channel_id)?.input?.(plain);
318
331
  }
319
332
 
333
+ /**
334
+ * `AuthOk` (#125). `ttl` is the lifetime this host enforces on the connection, in seconds (0 = unlimited, the
335
+ * default); `token` is an opaque per-connection value that carries no authority -- the spec requires the field
336
+ * and released peers parse it, but nothing on this host accepts it back.
337
+ */
338
+ async function grantAuth() {
339
+ const ttlMs = cfg.connectionTtlMs ?? 0;
340
+ if (ttlMs > 0) {
341
+ ttlTimer = setTimeout(() => { log('connection ttl reached'); shutdownAfterQueue('connection ttl reached'); }, ttlMs);
342
+ ttlTimer.unref?.();
343
+ }
344
+ await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: Math.ceil(ttlMs / 1000) }));
345
+ }
346
+
320
347
  async function refuse(reason) {
321
348
  log(`AUTH_FAIL: ${reason}`);
322
349
  await send(authFail({ reason }));
@@ -337,6 +364,7 @@ export function createConnectionFactory(cfg) {
337
364
  }
338
365
  state.username = user;
339
366
  state.method = method;
367
+ gateway?.setPeerFeatures(m.features);
340
368
  const features = hostFeatures(cfg, { dataStreams });
341
369
  let hostFingerprint;
342
370
  if (cfg.hostKey) {
@@ -347,6 +375,13 @@ export function createConnectionFactory(cfg) {
347
375
  features.push(HOST_KEY_PREFIX + toHex(cfg.hostKey.publicKey), HOST_KEY_SIG_PREFIX + toHex(sig));
348
376
  }
349
377
  }
378
+ // Channel binding (#119): what this host can tie the client's signature to on this connection.
379
+ if (method === 'pubkey') {
380
+ state.bindingHeld = { ...(channelBinding ?? {}) };
381
+ if (cfg.hostKey) state.bindingHeld.host = [cfg.hostKey.publicKey];
382
+ const kinds = Object.keys(state.bindingHeld).filter((k) => state.bindingHeld[k]?.length);
383
+ features.push(...bindingFeatures(kinds, { required: !!cfg.requireChannelBinding }));
384
+ }
350
385
  state.features = features;
351
386
  state.hostFingerprint = hostFingerprint ?? null;
352
387
  await send(serverHello({ sessionId: state.sessionId, features, hostFingerprint }));
@@ -372,11 +407,27 @@ export function createConnectionFactory(cfg) {
372
407
  } catch { return refuse('malformed public key'); }
373
408
  // Verify the signature first: nothing about who is on the allowlist
374
409
  // is revealed to a caller who cannot even prove they hold a key.
410
+ // The signature may be over the empty binding (a client that knows nothing of #119, or a browser that can
411
+ // bind nothing) or over any combination of the kinds this host offered; a host that requires a binding
412
+ // accepts only the latter.
413
+ const required = cfg.requireChannelBinding ?? false;
414
+ const acceptable = await acceptableBindings(state.bindingHeld ?? {}, { required });
375
415
  let ok = false;
416
+ let boundKinds = [];
376
417
  try {
377
- ok = await verifyChallenge(key, m.signature, state.sessionId, state.nonce, { username: state.username });
418
+ for (const cand of acceptable) {
419
+ if (await verifyChallenge(key, m.signature, state.sessionId, state.nonce, { username: state.username, channelBinding: cand.binding })) { ok = true; boundKinds = cand.kinds; break; }
420
+ }
378
421
  } catch { ok = false; }
379
- if (!ok) return refuse('signature does not verify over the transcript');
422
+ if (!ok) {
423
+ if (required) {
424
+ let unbound = false;
425
+ try { unbound = await verifyChallenge(key, m.signature, state.sessionId, state.nonce, { username: state.username }); } catch { /* not that either */ }
426
+ if (unbound) return refuse('channel binding required: the signature is not bound to this connection');
427
+ }
428
+ return refuse('signature does not verify over the transcript');
429
+ }
430
+ state.channelBinding = boundKinds;
380
431
  let allowed = false;
381
432
  try {
382
433
  allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key });
@@ -385,7 +436,7 @@ export function createConnectionFactory(cfg) {
385
436
  state.authed = true;
386
437
  state.fingerprint = fp;
387
438
  state.nonce = null;
388
- await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: 3600 }));
439
+ await grantAuth();
389
440
  log(`authenticated ${state.username} (${fp.slice(0, 12)}...)`);
390
441
  }
391
442
  }
@@ -409,13 +460,13 @@ export function createConnectionFactory(cfg) {
409
460
  }
410
461
  rl.limiter.succeed(key);
411
462
  state.authed = true;
412
- await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: 3600 }));
463
+ await grantAuth();
413
464
  log(`authenticated ${state.username} (password)`);
414
465
  }
415
466
 
416
467
  // ── Relay (createWshServer({ relay })) ────────────────────────────
417
468
 
418
- const RELAY_TYPES = new Set([MSG.REVERSE_REGISTER, MSG.REVERSE_LIST, MSG.REVERSE_CONNECT, MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT, MSG.RELAY_FORWARD]);
469
+ const RELAY_TYPES = new Set([MSG.REVERSE_REGISTER, MSG.REVERSE_LIST, MSG.REVERSE_CONNECT, MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT, MSG.RELAY_FORWARD, MSG.REVERSE_CHALLENGE, MSG.REVERSE_PROOF]);
419
470
 
420
471
  function hubHandle() {
421
472
  relayHandle ??= {
@@ -459,6 +510,8 @@ export function createConnectionFactory(cfg) {
459
510
  case MSG.REVERSE_LIST: await send(await hub.list({ username: state.username, fingerprint: state.fingerprint })); return true;
460
511
  case MSG.REVERSE_CONNECT: await hub.connect(h, m); return true;
461
512
  case MSG.REVERSE_ACCEPT: case MSG.REVERSE_REJECT: hub.answer(h, m); return true;
513
+ case MSG.REVERSE_CHALLENGE: hub.challenge(h, m); return true;
514
+ case MSG.REVERSE_PROOF: hub.proof(h, m); return true;
462
515
  default: hub.forward(h, m); return true; // a RelayForward the client wrote itself
463
516
  }
464
517
  }
@@ -752,7 +805,7 @@ export function createConnectionFactory(cfg) {
752
805
 
753
806
  const io = {
754
807
  user: state.username,
755
- env: m.env && typeof m.env === 'object' && cfg.execOptions.clientEnv !== false ? m.env : {},
808
+ env: execEnv(m.env),
756
809
  cols: m.cols || 80,
757
810
  rows: m.rows || 24,
758
811
  signal: abort.signal,
@@ -855,7 +908,7 @@ export function createConnectionFactory(cfg) {
855
908
  const args = m.command ? ['-c', String(m.command)] : [];
856
909
  proc = p.spawn(p.shell, args, {
857
910
  name: p.term, cols, rows, cwd: p.cwd,
858
- env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...(m.env && typeof m.env === 'object' ? m.env : {}) },
911
+ env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...ptyEnv(m.env) },
859
912
  });
860
913
  } catch (e) {
861
914
  return send(openFail({ reason: `pty spawn failed: ${e.message}` }));