@johnhenry/wsh 0.36.0 → 0.38.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.
@@ -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,11 @@ 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 { GATEWAY_DATAGRAM_FEATURE } from '../gateway-datagram.mjs';
34
+ import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
35
+ import { clientEnvFilter } from './client-env.mjs';
36
+ import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
32
37
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
33
38
 
34
39
  export const STREAM_ANNOUNCE = 'stream-announce';
@@ -42,14 +47,14 @@ export const STREAM_ANNOUNCE = 'stream-announce';
42
47
  export function hostFeatures(cfg, { dataStreams = true } = {}) {
43
48
  const features = dataStreams ? [STREAM_ANNOUNCE] : [];
44
49
  if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
45
- if (cfg.gateway) features.push('gateway');
50
+ if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
46
51
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
47
52
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
48
53
  // client-opened streams: over a relay bridge.
49
54
  // A relay carries a signed KeyExchange untouched, and (when configured) several operators per peer: peers read
50
55
  // these from its ServerHello before relying on either, since an older relay would drop the connection on them.
51
56
  if (cfg.relay) {
52
- features.push(E2E_SIGN_FEATURE);
57
+ features.push(E2E_SIGN_FEATURE, OPERATOR_PROOF_FEATURE);
53
58
  if (cfg.relay.maxOperatorsPerPeer > 1) features.push(MULTI_OPERATOR_FEATURE);
54
59
  }
55
60
  if (cfg.e2e && !dataStreams) features.push(E2E_FEATURE, ...(cfg.e2e.signKey ? [E2E_SIGN_FEATURE] : []));
@@ -111,6 +116,9 @@ export function createConnectionFactory(cfg) {
111
116
  log: cfg.log ?? (() => {}),
112
117
  };
113
118
  let counter = 0;
119
+ // What a client may put in `Open.env` (#126): an allow-list unless the host says otherwise.
120
+ const execEnv = clientEnvFilter(cfg.execOptions?.clientEnv);
121
+ const ptyEnv = clientEnvFilter(cfg.pty?.clientEnv);
114
122
 
115
123
  /**
116
124
  * Attach one connection. Two shapes:
@@ -121,7 +129,7 @@ export function createConnectionFactory(cfg) {
121
129
  * `dataStreams: false` means there are no client-opened streams to bind, so exec output rides SessionData.
122
130
  * `e2e` overrides `cfg.e2e` for this connection.
123
131
  */
124
- return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride }) {
132
+ return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride, channelBinding = null, datagrams = null }) {
125
133
  const cid = ++counter;
126
134
  const log = (m) => cfg.log(`[conn ${cid}] ${m}`);
127
135
  const state = {
@@ -144,11 +152,16 @@ export function createConnectionFactory(cfg) {
144
152
  let chain = Promise.resolve();
145
153
  /** This connection as the relay hub sees it (created on first need). */
146
154
  let relayHandle = null;
155
+ /** Ends the connection at `connectionTtlMs` after authentication (#125). */
156
+ let ttlTimer = null;
147
157
 
148
158
  // 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`.
159
+ // the embedder that has them (`createWshServer`) passes `cfg.createGatewaySession` along with `cfg.gateway`; a
160
+ // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
150
161
  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;
162
+ const gateway = cfg.gateway
163
+ ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }), datagrams })
164
+ : null;
152
165
 
153
166
  const qmux = sendMessage ? null : new QMuxConnection({ isClient: false, send: (b) => { if (!state.closed) sendBytes(b); } });
154
167
 
@@ -198,6 +211,7 @@ export function createConnectionFactory(cfg) {
198
211
  function shutdown(why) {
199
212
  if (state.closed) return;
200
213
  state.closed = true;
214
+ clearTimeout(ttlTimer);
201
215
  // A hosted session survives its connection (it is detached, then expires or is resumed);
202
216
  // everything else dies with it.
203
217
  for (const ch of [...channels.values()]) (ch.detach ?? ch.kill)?.call(ch);
@@ -317,6 +331,20 @@ export function createConnectionFactory(cfg) {
317
331
  channels.get(m.channel_id)?.input?.(plain);
318
332
  }
319
333
 
334
+ /**
335
+ * `AuthOk` (#125). `ttl` is the lifetime this host enforces on the connection, in seconds (0 = unlimited, the
336
+ * default); `token` is an opaque per-connection value that carries no authority -- the spec requires the field
337
+ * and released peers parse it, but nothing on this host accepts it back.
338
+ */
339
+ async function grantAuth() {
340
+ const ttlMs = cfg.connectionTtlMs ?? 0;
341
+ if (ttlMs > 0) {
342
+ ttlTimer = setTimeout(() => { log('connection ttl reached'); shutdownAfterQueue('connection ttl reached'); }, ttlMs);
343
+ ttlTimer.unref?.();
344
+ }
345
+ await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: Math.ceil(ttlMs / 1000) }));
346
+ }
347
+
320
348
  async function refuse(reason) {
321
349
  log(`AUTH_FAIL: ${reason}`);
322
350
  await send(authFail({ reason }));
@@ -337,7 +365,10 @@ export function createConnectionFactory(cfg) {
337
365
  }
338
366
  state.username = user;
339
367
  state.method = method;
368
+ gateway?.setPeerFeatures(m.features);
340
369
  const features = hostFeatures(cfg, { dataStreams });
370
+ // UDP over datagrams only where this transport has them and the gateway serves (and allows) UDP.
371
+ if (datagrams && cfg.gateway?.tcp && cfg.gateway.udp?.datagrams) features.push(GATEWAY_DATAGRAM_FEATURE);
341
372
  let hostFingerprint;
342
373
  if (cfg.hostKey) {
343
374
  hostFingerprint = cfg.hostKey.fingerprint;
@@ -347,6 +378,13 @@ export function createConnectionFactory(cfg) {
347
378
  features.push(HOST_KEY_PREFIX + toHex(cfg.hostKey.publicKey), HOST_KEY_SIG_PREFIX + toHex(sig));
348
379
  }
349
380
  }
381
+ // Channel binding (#119): what this host can tie the client's signature to on this connection.
382
+ if (method === 'pubkey') {
383
+ state.bindingHeld = { ...(channelBinding ?? {}) };
384
+ if (cfg.hostKey) state.bindingHeld.host = [cfg.hostKey.publicKey];
385
+ const kinds = Object.keys(state.bindingHeld).filter((k) => state.bindingHeld[k]?.length);
386
+ features.push(...bindingFeatures(kinds, { required: !!cfg.requireChannelBinding }));
387
+ }
350
388
  state.features = features;
351
389
  state.hostFingerprint = hostFingerprint ?? null;
352
390
  await send(serverHello({ sessionId: state.sessionId, features, hostFingerprint }));
@@ -372,11 +410,27 @@ export function createConnectionFactory(cfg) {
372
410
  } catch { return refuse('malformed public key'); }
373
411
  // Verify the signature first: nothing about who is on the allowlist
374
412
  // is revealed to a caller who cannot even prove they hold a key.
413
+ // The signature may be over the empty binding (a client that knows nothing of #119, or a browser that can
414
+ // bind nothing) or over any combination of the kinds this host offered; a host that requires a binding
415
+ // accepts only the latter.
416
+ const required = cfg.requireChannelBinding ?? false;
417
+ const acceptable = await acceptableBindings(state.bindingHeld ?? {}, { required });
375
418
  let ok = false;
419
+ let boundKinds = [];
376
420
  try {
377
- ok = await verifyChallenge(key, m.signature, state.sessionId, state.nonce, { username: state.username });
421
+ for (const cand of acceptable) {
422
+ if (await verifyChallenge(key, m.signature, state.sessionId, state.nonce, { username: state.username, channelBinding: cand.binding })) { ok = true; boundKinds = cand.kinds; break; }
423
+ }
378
424
  } catch { ok = false; }
379
- if (!ok) return refuse('signature does not verify over the transcript');
425
+ if (!ok) {
426
+ if (required) {
427
+ let unbound = false;
428
+ try { unbound = await verifyChallenge(key, m.signature, state.sessionId, state.nonce, { username: state.username }); } catch { /* not that either */ }
429
+ if (unbound) return refuse('channel binding required: the signature is not bound to this connection');
430
+ }
431
+ return refuse('signature does not verify over the transcript');
432
+ }
433
+ state.channelBinding = boundKinds;
380
434
  let allowed = false;
381
435
  try {
382
436
  allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key });
@@ -385,7 +439,7 @@ export function createConnectionFactory(cfg) {
385
439
  state.authed = true;
386
440
  state.fingerprint = fp;
387
441
  state.nonce = null;
388
- await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: 3600 }));
442
+ await grantAuth();
389
443
  log(`authenticated ${state.username} (${fp.slice(0, 12)}...)`);
390
444
  }
391
445
  }
@@ -409,13 +463,13 @@ export function createConnectionFactory(cfg) {
409
463
  }
410
464
  rl.limiter.succeed(key);
411
465
  state.authed = true;
412
- await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: 3600 }));
466
+ await grantAuth();
413
467
  log(`authenticated ${state.username} (password)`);
414
468
  }
415
469
 
416
470
  // ── Relay (createWshServer({ relay })) ────────────────────────────
417
471
 
418
- const RELAY_TYPES = new Set([MSG.REVERSE_REGISTER, MSG.REVERSE_LIST, MSG.REVERSE_CONNECT, MSG.REVERSE_ACCEPT, MSG.REVERSE_REJECT, MSG.RELAY_FORWARD]);
472
+ 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
473
 
420
474
  function hubHandle() {
421
475
  relayHandle ??= {
@@ -459,6 +513,8 @@ export function createConnectionFactory(cfg) {
459
513
  case MSG.REVERSE_LIST: await send(await hub.list({ username: state.username, fingerprint: state.fingerprint })); return true;
460
514
  case MSG.REVERSE_CONNECT: await hub.connect(h, m); return true;
461
515
  case MSG.REVERSE_ACCEPT: case MSG.REVERSE_REJECT: hub.answer(h, m); return true;
516
+ case MSG.REVERSE_CHALLENGE: hub.challenge(h, m); return true;
517
+ case MSG.REVERSE_PROOF: hub.proof(h, m); return true;
462
518
  default: hub.forward(h, m); return true; // a RelayForward the client wrote itself
463
519
  }
464
520
  }
@@ -752,7 +808,7 @@ export function createConnectionFactory(cfg) {
752
808
 
753
809
  const io = {
754
810
  user: state.username,
755
- env: m.env && typeof m.env === 'object' && cfg.execOptions.clientEnv !== false ? m.env : {},
811
+ env: execEnv(m.env),
756
812
  cols: m.cols || 80,
757
813
  rows: m.rows || 24,
758
814
  signal: abort.signal,
@@ -855,7 +911,7 @@ export function createConnectionFactory(cfg) {
855
911
  const args = m.command ? ['-c', String(m.command)] : [];
856
912
  proc = p.spawn(p.shell, args, {
857
913
  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 : {}) },
914
+ env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...ptyEnv(m.env) },
859
915
  });
860
916
  } catch (e) {
861
917
  return send(openFail({ reason: `pty spawn failed: ${e.message}` }));
@@ -1019,6 +1075,8 @@ export function createConnectionFactory(cfg) {
1019
1075
 
1020
1076
  return {
1021
1077
  receive(bytes) { if (!state.closed) qmux?.receiveBytes(bytes); },
1078
+ /** A transport datagram (WebTransport) arrived: only the gateway's UDP flows use them. */
1079
+ receiveDatagram(bytes) { if (!state.closed && state.authed) gateway?.handleDatagram?.(bytes); },
1022
1080
  receiveMessage(msg) { if (!state.closed) chain = chain.then(() => handle(msg)).catch((e) => log(`handler error: ${e.message}`)); },
1023
1081
  bindStream: bindDataStream,
1024
1082
  close() { shutdownAfterQueue('transport closed'); },
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The browser-safe half of the gateway: configuration of the parts that need no Node API (limits, named endpoints,
3
+ * the features a host advertises), and the per-connection core that serves `OpenEndpoint`, `GatewayData`,
4
+ * `GatewayCredit` and `GatewayClose` with flow control (`src/gateway-channel.mjs`). A host in a page
5
+ * (`createMemoryHost({ endpoints })`) is built from this alone; `gateway.mjs` (Node: TCP, DNS, UDP, unix sockets)
6
+ * extends it. Nothing here imports a Node built-in.
7
+ */
8
+
9
+ import { MSG, gatewayOk, gatewayFail, gatewayClose, gatewayData, gatewayCredit, listenFail } from '../messages.gen.mjs';
10
+ import { GatewayChannel, GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from '../gateway-channel.mjs';
11
+
12
+ /** Numeric codes of GatewayFail (the same table `@johnhenry/browsermesh-netway` decodes). */
13
+ export const GATEWAY_FAIL = Object.freeze({
14
+ CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
15
+ });
16
+
17
+ export const DEFAULT_MAX_CONNECTIONS = 32;
18
+ export const DEFAULT_MAX_BUFFERED = 4 * 1024 * 1024;
19
+ export const DEFAULT_MAX_CLIENT_BUFFERED = 32 * 1024 * 1024;
20
+ export const MAX_DATA_BYTES = 1024 * 1024;
21
+ export const HALF_CLOSE_GRACE_MS = 1000;
22
+ export const ENDPOINT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
23
+
24
+ /** The limits shared by every gateway (validated here so the Node and the in-page host agree). */
25
+ export function normalizeGatewayLimits(opts) {
26
+ const maxConnections = opts.maxConnections ?? DEFAULT_MAX_CONNECTIONS;
27
+ if (!Number.isInteger(maxConnections) || maxConnections < 1) throw new TypeError('gateway.maxConnections must be a positive integer');
28
+ const maxBufferedBytes = opts.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED;
29
+ const maxClientBufferedBytes = opts.maxClientBufferedBytes ?? DEFAULT_MAX_CLIENT_BUFFERED;
30
+ if (!Number.isInteger(maxBufferedBytes) || maxBufferedBytes < GATEWAY_CREDIT_WINDOW) throw new TypeError(`gateway.maxBufferedBytes must be an integer of at least ${GATEWAY_CREDIT_WINDOW}`);
31
+ if (!Number.isInteger(maxClientBufferedBytes) || maxClientBufferedBytes < maxBufferedBytes) throw new TypeError('gateway.maxClientBufferedBytes must be an integer of at least maxBufferedBytes');
32
+ return { maxConnections, maxBufferedBytes, maxClientBufferedBytes };
33
+ }
34
+
35
+ /** `{ name: handler | { open, authorize } }` -> a Map, or null when there are none. */
36
+ export function normalizeEndpoints(endpoints) {
37
+ if (endpoints === undefined || endpoints === null) return null;
38
+ if (typeof endpoints !== 'object' || Array.isArray(endpoints)) throw new TypeError('gateway.endpoints must be an object of { name: handler }');
39
+ const map = new Map();
40
+ for (const [name, h] of Object.entries(endpoints)) {
41
+ if (!ENDPOINT_NAME_RE.test(name)) throw new TypeError(`gateway.endpoints: ${JSON.stringify(name)} is not a valid endpoint name (letters, digits, ".", "_", "-"; at most 64)`);
42
+ const open = typeof h === 'function' ? h : h?.open;
43
+ if (typeof open !== 'function') throw new TypeError(`gateway.endpoints[${JSON.stringify(name)}] needs a handler function (duplex, who) => void, or { open, authorize }`);
44
+ if (h?.authorize !== undefined && typeof h.authorize !== 'function') throw new TypeError(`gateway.endpoints[${JSON.stringify(name)}].authorize must be a function (who) => boolean`);
45
+ map.set(name, { open, authorize: h?.authorize ?? null });
46
+ }
47
+ return map.size === 0 ? null : map;
48
+ }
49
+
50
+ /**
51
+ * The configuration of a gateway that serves named endpoints only (no TCP, DNS or unix sockets): what
52
+ * `createMemoryHost({ endpoints })` passes as `gateway`, with `createEndpointGatewaySession` as the session factory.
53
+ */
54
+ export function normalizeEndpointGateway(opts = {}) {
55
+ return { ...normalizeGatewayLimits(opts), tcp: false, unix: null, endpoints: normalizeEndpoints(opts.endpoints) };
56
+ }
57
+
58
+ /** Which gateway-related features a host with this config advertises (besides what the connection adds). */
59
+ export function gatewayFeatures(cfg) {
60
+ const f = [];
61
+ // "gateway" also covers reverse tunnels (the Rust server lists nothing more specific for ListenRequest).
62
+ if (cfg.tcp || cfg.reverse) f.push('gateway');
63
+ f.push(GATEWAY_CREDIT_FEATURE);
64
+ if (cfg.unix) f.push('gateway-unix');
65
+ if (cfg.endpoints) f.push('gateway-endpoints');
66
+ return f;
67
+ }
68
+
69
+ /**
70
+ * The per-connection core: the table of open gateway connections, the per-client byte budget, credit negotiation and
71
+ * the opcodes that need no Node API. `gateway.mjs` builds its socket-backed session on the same object.
72
+ * @param {{ maxConnections: number, maxBufferedBytes: number, maxClientBufferedBytes: number, endpoints: Map<string, object> | null }} cfg
73
+ * @param {(msg: object) => unknown} send
74
+ * @param {(line: string) => void} log
75
+ * @param {{ who?: () => { username: string | null, fingerprint: string | null } }} [ctx]
76
+ */
77
+ export function createGatewayCore(cfg, send, log = () => {}, ctx = {}) {
78
+ /** @type {Map<number, { channel: GatewayChannel, sock: any }>} */
79
+ const conns = new Map();
80
+ /** gateway_ids whose connect is still in flight (they count against the cap). */
81
+ const pending = new Set();
82
+ let credit = false;
83
+ let closed = false;
84
+ const budget = { used: 0, max: cfg.maxClientBufferedBytes };
85
+
86
+ const reply = (m) => { try { return Promise.resolve(send(m)).catch(() => {}); } catch { return Promise.resolve(); } };
87
+ const fail = (gatewayId, code, message) => reply(gatewayFail({ gatewayId, code, message }));
88
+ const active = () => conns.size + pending.size;
89
+ const idInUse = (id) => conns.has(id) || pending.has(id);
90
+
91
+ /** A channel wired to the wire; `extra` adds the sink (a socket's writer) and the close hooks. */
92
+ function makeChannel(id, extra) {
93
+ return new GatewayChannel({
94
+ id, credit, maxQueued: cfg.maxBufferedBytes, budget,
95
+ sendData: (data) => reply(gatewayData({ gatewayId: id, data })),
96
+ sendCredit: (n) => reply(gatewayCredit({ gatewayId: id, bytes: n })),
97
+ sendClose: (reason) => reply(gatewayClose({ gatewayId: id, reason })),
98
+ ...extra,
99
+ onClose: (reason) => { conns.delete(id); extra?.onClose?.(reason); },
100
+ });
101
+ }
102
+
103
+ async function openEndpoint(m) {
104
+ const id = m.gateway_id;
105
+ if (!Number.isInteger(id) || typeof m.name !== 'string') return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenEndpoint');
106
+ if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
107
+ const ep = cfg.endpoints && ENDPOINT_NAME_RE.test(m.name) ? cfg.endpoints.get(m.name) : undefined;
108
+ if (!ep) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'no such endpoint');
109
+ if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
110
+ const who = ctx.who?.() ?? { username: null, fingerprint: null };
111
+ pending.add(id);
112
+ try {
113
+ if (ep.authorize && !(await ep.authorize(who))) { pending.delete(id); return await fail(id, GATEWAY_FAIL.POLICY_DENIED, 'endpoint refused this caller'); }
114
+ } catch (e) { pending.delete(id); log(`gateway endpoint ${m.name} authorize threw: ${e.message}`); return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'endpoint refused this caller'); }
115
+ pending.delete(id);
116
+ if (closed) return undefined;
117
+ const channel = makeChannel(id, { writeAfterRemoteClose: true, graceMs: HALF_CLOSE_GRACE_MS });
118
+ conns.set(id, { channel, sock: null });
119
+ const { readable, writable } = channel.streams();
120
+ const duplex = {
121
+ readable, writable, who,
122
+ /** Half-close: nothing more will be sent. */
123
+ close: (reason) => channel.end(reason),
124
+ /** Tear the connection down now. */
125
+ destroy: (reason) => channel.destroy(reason),
126
+ closed: channel.closedPromise,
127
+ };
128
+ try {
129
+ const out = ep.open(duplex, who);
130
+ if (out && typeof out.then === 'function') out.then(undefined, (e) => { log(`gateway endpoint ${m.name} failed: ${e?.message}`); channel.destroy('endpoint error'); });
131
+ } catch (e) {
132
+ log(`gateway endpoint ${m.name} threw: ${e.message}`);
133
+ channel.abandon();
134
+ return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'endpoint refused the connection');
135
+ }
136
+ log(`gateway: ${id} -> endpoint ${m.name}`);
137
+ return reply(gatewayOk({ gatewayId: id }));
138
+ }
139
+
140
+ return {
141
+ conns, pending, budget, reply, fail, active, idInUse, makeChannel,
142
+ get closed() { return closed; },
143
+ /** Credit is used on this connection only when the client listed "gateway-credit" in its Hello. */
144
+ setPeerFeatures(features) { credit = Array.isArray(features) && features.includes(GATEWAY_CREDIT_FEATURE); },
145
+ /** @returns {Promise<boolean>} true when the message was a gateway message this session consumed */
146
+ async handle(m) {
147
+ if (closed) return true;
148
+ switch (m.type) {
149
+ case MSG.OPEN_ENDPOINT: await openEndpoint(m); return true;
150
+ case MSG.GATEWAY_DATA: {
151
+ const c = conns.get(m.gateway_id)?.channel;
152
+ const d = m.data;
153
+ if (c && d && d.length <= MAX_DATA_BYTES) c.receive(d);
154
+ return true;
155
+ }
156
+ case MSG.GATEWAY_CREDIT: {
157
+ if (credit && Number.isInteger(m.bytes)) conns.get(m.gateway_id)?.channel.grant(m.bytes);
158
+ return true;
159
+ }
160
+ case MSG.GATEWAY_CLOSE: {
161
+ conns.get(m.gateway_id)?.channel.remoteClosed(m.reason);
162
+ return true;
163
+ }
164
+ // What this host does not serve is refused, not ignored, so the client does not wait for an answer.
165
+ case MSG.OPEN_TCP: case MSG.OPEN_UDP: case MSG.RESOLVE_DNS:
166
+ await fail(m.gateway_id, GATEWAY_FAIL.POLICY_DENIED, 'only named endpoints are available on this host'); return true;
167
+ case MSG.OPEN_UNIX:
168
+ await fail(m.gateway_id, GATEWAY_FAIL.POLICY_DENIED, 'unix sockets are not available on this host'); return true;
169
+ case MSG.LISTEN_REQUEST: case MSG.LISTEN_UNIX:
170
+ await reply(listenFail({ listenerId: m.listener_id, reason: 'listening is not available on this host' })); return true;
171
+ default: return false;
172
+ }
173
+ },
174
+ close() {
175
+ closed = true;
176
+ for (const { channel } of [...conns.values()]) channel.abandon('connection closed');
177
+ conns.clear();
178
+ },
179
+ get size() { return conns.size; },
180
+ /** Bytes received from the client for its origins and not yet taken by them (what the caps bound). */
181
+ get bufferedBytes() { return budget.used; },
182
+ get listenerCount() { return 0; },
183
+ };
184
+ }
185
+
186
+ /** The session factory of an endpoints-only host (`cfg.createGatewaySession`). */
187
+ export function createEndpointGatewaySession(cfg, send, log, ctx) {
188
+ return createGatewayCore(cfg, send, log, ctx);
189
+ }