@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.
Files changed (41) hide show
  1. package/README.md +453 -21
  2. package/package.json +18 -1
  3. package/src/bridge-seal.mjs +77 -0
  4. package/src/channel-binding.mjs +124 -0
  5. package/src/client.mjs +351 -62
  6. package/src/e2e-exchange.mjs +51 -1
  7. package/src/features.mjs +28 -0
  8. package/src/forward-node.mjs +118 -0
  9. package/src/gateway-channel.mjs +250 -0
  10. package/src/gateway-client.mjs +252 -0
  11. package/src/host-backends.mjs +100 -0
  12. package/src/host.d.ts +146 -0
  13. package/src/host.mjs +30 -0
  14. package/src/index.d.ts +114 -0
  15. package/src/index.mjs +13 -0
  16. package/src/memory-host.d.ts +34 -3
  17. package/src/memory-host.mjs +57 -13
  18. package/src/messages.gen.mjs +59 -7
  19. package/src/operator-proof.mjs +135 -0
  20. package/src/pipe-relay.d.ts +49 -0
  21. package/src/pipe-relay.mjs +274 -0
  22. package/src/reverse-host.d.ts +25 -0
  23. package/src/reverse-host.mjs +339 -0
  24. package/src/server/address-guard.mjs +164 -0
  25. package/src/server/backends.mjs +10 -16
  26. package/src/server/client-env.mjs +60 -0
  27. package/src/server/connection.mjs +100 -23
  28. package/src/server/constants.mjs +3 -0
  29. package/src/server/fs.mjs +2 -3
  30. package/src/server/gateway-core.mjs +188 -0
  31. package/src/server/gateway.mjs +483 -80
  32. package/src/server/index.d.ts +103 -5
  33. package/src/server/index.mjs +25 -4
  34. package/src/server/pty.mjs +1 -0
  35. package/src/server/relay.mjs +45 -2
  36. package/src/server/reverse-host.mjs +7 -213
  37. package/src/server/socket.mjs +25 -4
  38. package/src/server/unix-policy.mjs +120 -0
  39. package/src/server/webtransport.mjs +2 -0
  40. package/src/transport-ws.mjs +16 -0
  41. package/src/transport.mjs +11 -0
@@ -24,12 +24,15 @@ import {
24
24
  generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
25
25
  } from '../auth.mjs';
26
26
  import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
27
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from '../client.mjs';
27
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from '../features.mjs';
28
28
  import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
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 { createGatewaySession } from './gateway.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';
33
36
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
34
37
 
35
38
  export const STREAM_ANNOUNCE = 'stream-announce';
@@ -43,14 +46,14 @@ export const STREAM_ANNOUNCE = 'stream-announce';
43
46
  export function hostFeatures(cfg, { dataStreams = true } = {}) {
44
47
  const features = dataStreams ? [STREAM_ANNOUNCE] : [];
45
48
  if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
46
- if (cfg.gateway) features.push('gateway');
49
+ if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
47
50
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
48
51
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
49
52
  // client-opened streams: over a relay bridge.
50
53
  // A relay carries a signed KeyExchange untouched, and (when configured) several operators per peer: peers read
51
54
  // these from its ServerHello before relying on either, since an older relay would drop the connection on them.
52
55
  if (cfg.relay) {
53
- features.push(E2E_SIGN_FEATURE);
56
+ features.push(E2E_SIGN_FEATURE, OPERATOR_PROOF_FEATURE);
54
57
  if (cfg.relay.maxOperatorsPerPeer > 1) features.push(MULTI_OPERATOR_FEATURE);
55
58
  }
56
59
  if (cfg.e2e && !dataStreams) features.push(E2E_FEATURE, ...(cfg.e2e.signKey ? [E2E_SIGN_FEATURE] : []));
@@ -73,14 +76,24 @@ const randomBytes = (n) => crypto.getRandomValues(new Uint8Array(n));
73
76
  const toBytes = (d) => (typeof d === 'string' ? enc.encode(d) : d);
74
77
 
75
78
  /**
79
+ * The connection handler every host runs -- `createWshServer`, `createMemoryHost`, `createReverseHost` -- exported
80
+ * (as `@johnhenry/wsh/host`) for an embedder that wires its own transport: a WebSocket it opened itself, a
81
+ * `MessagePort`, a byte pipe to another process. It returns `attach(...)`, called once per connection; see below.
82
+ * Build the backends with `resolveBackends()` and the host key with `resolveHostKey()` (same entry point), and
83
+ * answer `authorize` yourself; for the common cases `createMemoryHost()` does all of this and `bindSocket()` does the
84
+ * socket side.
85
+ *
86
+ * Everything here is browser-safe: no `node:*` import and no `Buffer` is reachable from this module.
87
+ *
76
88
  * @param {object} cfg
77
- * @param {(who: object) => Promise<boolean>} cfg.authorize
78
- * @param {Function | null} cfg.execRunner
79
- * @param {object} cfg.execOptions
80
- * @param {object | null} cfg.pty - normalized (see pty.mjs)
81
- * @param {object | null} cfg.files - from createFileAccess
82
- * @param {{ pubkey: boolean, password: Function | null }} cfg.methods - which auth methods are on
83
- * @param {object | null} cfg.hostKey - from loadHostKey
89
+ * @param {(who: { username: string, fingerprint?: string, publicKey?: Uint8Array }) => Promise<boolean>} cfg.authorize - required;
90
+ * decides who is let in (`buildAuthorizer` in `server/auth.mjs` builds one from `authorizedKeys` / a callback)
91
+ * @param {Function | null} [cfg.execRunner] - `run(command, io)`; null = exec is off
92
+ * @param {object} [cfg.execOptions] - `{ timeoutMs, clientEnv }` (default `{}`)
93
+ * @param {object | null} [cfg.pty] - normalized (see pty.mjs): `{ spawn, shell, cwd, env, term }`; null = pty is off
94
+ * @param {object | null} [cfg.files] - a file backend (see `normalizeFileBackend` in `host-backends.mjs`); null = file access is off
95
+ * @param {{ pubkey: boolean, password: Function | null }} [cfg.methods] - which auth methods are on (default pubkey only)
96
+ * @param {object | null} [cfg.hostKey] - from `resolveHostKey` / `loadHostKey`
84
97
  * @param {object | null} cfg.mcp - from createMcpHost
85
98
  * @param {{ protocols: Map<string, Function>, maxMessageBytes: number, maxInflight: number } | null} cfg.rpc - from createRpcHost
86
99
  * @param {{ signKey: CryptoKey | null, hybrid?: boolean } | null} cfg.e2e - answer KeyExchange and seal virtual-mode traffic (bridged connections only)
@@ -89,11 +102,22 @@ const toBytes = (d) => (typeof d === 'string' ? enc.encode(d) : d);
89
102
  * @param {object | null} cfg.relay - a RelayHub (see relay.mjs); null = not a relay
90
103
  * @param {object | null} cfg.sessions - a SessionRegistry (see sessions.mjs); null = sessions die with their connection
91
104
  * @param {{ limiter: object, key: Function, failureDelayMs: number } | null} cfg.rateLimit - password throttle
92
- * @param {number} cfg.bindTimeoutMs - how long exec output waits for the data stream
93
- * @param {(line: string) => void} cfg.log
105
+ * @param {number} [cfg.bindTimeoutMs=3000] - how long exec output waits for the data stream
106
+ * @param {(line: string) => void} [cfg.log]
94
107
  */
95
108
  export function createConnectionFactory(cfg) {
109
+ if (!cfg || typeof cfg.authorize !== 'function') throw new TypeError('createConnectionFactory: authorize(who) is required (a host that lets everyone in is not a default)');
110
+ cfg = {
111
+ ...cfg,
112
+ execOptions: cfg.execOptions ?? {},
113
+ methods: cfg.methods ?? { pubkey: true, password: null },
114
+ bindTimeoutMs: cfg.bindTimeoutMs ?? 3000,
115
+ log: cfg.log ?? (() => {}),
116
+ };
96
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);
97
121
 
98
122
  /**
99
123
  * Attach one connection. Two shapes:
@@ -104,7 +128,7 @@ export function createConnectionFactory(cfg) {
104
128
  * `dataStreams: false` means there are no client-opened streams to bind, so exec output rides SessionData.
105
129
  * `e2e` overrides `cfg.e2e` for this connection.
106
130
  */
107
- 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 }) {
108
132
  const cid = ++counter;
109
133
  const log = (m) => cfg.log(`[conn ${cid}] ${m}`);
110
134
  const state = {
@@ -127,8 +151,16 @@ export function createConnectionFactory(cfg) {
127
151
  let chain = Promise.resolve();
128
152
  /** This connection as the relay hub sees it (created on first need). */
129
153
  let relayHandle = null;
154
+ /** Ends the connection at `connectionTtlMs` after authentication (#125). */
155
+ let ttlTimer = null;
130
156
 
131
- const gateway = cfg.gateway ? createGatewaySession(cfg.gateway, (m) => send(m), log) : null;
157
+ // The gateway needs Node sockets, so `gateway.mjs` is not imported here (a browser host must not pull it in):
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 })`).
160
+ if (cfg.gateway && typeof cfg.createGatewaySession !== 'function') throw new TypeError('createConnectionFactory: gateway needs createGatewaySession (only @johnhenry/wsh/server provides one)');
161
+ const gateway = cfg.gateway
162
+ ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }) })
163
+ : null;
132
164
 
133
165
  const qmux = sendMessage ? null : new QMuxConnection({ isClient: false, send: (b) => { if (!state.closed) sendBytes(b); } });
134
166
 
@@ -178,6 +210,7 @@ export function createConnectionFactory(cfg) {
178
210
  function shutdown(why) {
179
211
  if (state.closed) return;
180
212
  state.closed = true;
213
+ clearTimeout(ttlTimer);
181
214
  // A hosted session survives its connection (it is detached, then expires or is resumed);
182
215
  // everything else dies with it.
183
216
  for (const ch of [...channels.values()]) (ch.detach ?? ch.kill)?.call(ch);
@@ -297,6 +330,20 @@ export function createConnectionFactory(cfg) {
297
330
  channels.get(m.channel_id)?.input?.(plain);
298
331
  }
299
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
+
300
347
  async function refuse(reason) {
301
348
  log(`AUTH_FAIL: ${reason}`);
302
349
  await send(authFail({ reason }));
@@ -317,6 +364,7 @@ export function createConnectionFactory(cfg) {
317
364
  }
318
365
  state.username = user;
319
366
  state.method = method;
367
+ gateway?.setPeerFeatures(m.features);
320
368
  const features = hostFeatures(cfg, { dataStreams });
321
369
  let hostFingerprint;
322
370
  if (cfg.hostKey) {
@@ -327,6 +375,13 @@ export function createConnectionFactory(cfg) {
327
375
  features.push(HOST_KEY_PREFIX + toHex(cfg.hostKey.publicKey), HOST_KEY_SIG_PREFIX + toHex(sig));
328
376
  }
329
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
+ }
330
385
  state.features = features;
331
386
  state.hostFingerprint = hostFingerprint ?? null;
332
387
  await send(serverHello({ sessionId: state.sessionId, features, hostFingerprint }));
@@ -352,11 +407,27 @@ export function createConnectionFactory(cfg) {
352
407
  } catch { return refuse('malformed public key'); }
353
408
  // Verify the signature first: nothing about who is on the allowlist
354
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 });
355
415
  let ok = false;
416
+ let boundKinds = [];
356
417
  try {
357
- 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
+ }
358
421
  } catch { ok = false; }
359
- 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;
360
431
  let allowed = false;
361
432
  try {
362
433
  allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key });
@@ -365,7 +436,7 @@ export function createConnectionFactory(cfg) {
365
436
  state.authed = true;
366
437
  state.fingerprint = fp;
367
438
  state.nonce = null;
368
- await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: 3600 }));
439
+ await grantAuth();
369
440
  log(`authenticated ${state.username} (${fp.slice(0, 12)}...)`);
370
441
  }
371
442
  }
@@ -389,13 +460,13 @@ export function createConnectionFactory(cfg) {
389
460
  }
390
461
  rl.limiter.succeed(key);
391
462
  state.authed = true;
392
- await send(authOk({ sessionId: state.sessionId, token: randomBytes(16), ttl: 3600 }));
463
+ await grantAuth();
393
464
  log(`authenticated ${state.username} (password)`);
394
465
  }
395
466
 
396
467
  // ── Relay (createWshServer({ relay })) ────────────────────────────
397
468
 
398
- 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]);
399
470
 
400
471
  function hubHandle() {
401
472
  relayHandle ??= {
@@ -439,6 +510,8 @@ export function createConnectionFactory(cfg) {
439
510
  case MSG.REVERSE_LIST: await send(await hub.list({ username: state.username, fingerprint: state.fingerprint })); return true;
440
511
  case MSG.REVERSE_CONNECT: await hub.connect(h, m); return true;
441
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;
442
515
  default: hub.forward(h, m); return true; // a RelayForward the client wrote itself
443
516
  }
444
517
  }
@@ -732,7 +805,7 @@ export function createConnectionFactory(cfg) {
732
805
 
733
806
  const io = {
734
807
  user: state.username,
735
- env: m.env && typeof m.env === 'object' && cfg.execOptions.clientEnv !== false ? m.env : {},
808
+ env: execEnv(m.env),
736
809
  cols: m.cols || 80,
737
810
  rows: m.rows || 24,
738
811
  signal: abort.signal,
@@ -835,13 +908,17 @@ export function createConnectionFactory(cfg) {
835
908
  const args = m.command ? ['-c', String(m.command)] : [];
836
909
  proc = p.spawn(p.shell, args, {
837
910
  name: p.term, cols, rows, cwd: p.cwd,
838
- 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) },
839
912
  });
840
913
  } catch (e) {
841
914
  return send(openFail({ reason: `pty spawn failed: ${e.message}` }));
842
915
  }
843
916
  const ctl = {
844
- input: (data) => { try { proc.write(Buffer.from(data)); } catch { /* exited */ } },
917
+ // Bytes, not a `Buffer`: there is none in a browser (#133), and node-pty's streams take a Uint8Array as is.
918
+ // A write to a process that has exited throws; that is expected and dropped, anything else is logged.
919
+ input: (data) => {
920
+ try { proc.write(Uint8Array.from(data)); } catch (e) { log(`pty channel ${channelId}: input not written: ${e?.message ?? e}`); }
921
+ },
845
922
  resize: (c, r) => { try { proc.resize(c || cols, r || rows); } catch { /* exited */ } },
846
923
  signal: (name) => { try { proc.kill(`SIG${name.replace(/^SIG/, '').toUpperCase()}`); } catch { /* exited */ } },
847
924
  kill: () => { try { proc.kill(); } catch { /* exited */ } },
@@ -8,3 +8,6 @@ export const FILE_CHUNK_BYTES = 64 * 1024;
8
8
 
9
9
  /** Most clients attached to one detached-session at once. */
10
10
  export const MAX_ATTACHMENTS = 16;
11
+
12
+ /** Default cap on one file read or written through a file backend. */
13
+ export const DEFAULT_MAX_FILE_BYTES = 64 * 1024 * 1024;
package/src/server/fs.mjs CHANGED
@@ -13,9 +13,8 @@ import {
13
13
  import { constants as fsc } from 'node:fs';
14
14
  import path from 'node:path';
15
15
 
16
- export const DEFAULT_MAX_FILE_BYTES = 64 * 1024 * 1024;
17
- import { FILE_CHUNK_BYTES } from './constants.mjs';
18
- export { FILE_CHUNK_BYTES };
16
+ import { FILE_CHUNK_BYTES, DEFAULT_MAX_FILE_BYTES } from './constants.mjs';
17
+ export { FILE_CHUNK_BYTES, DEFAULT_MAX_FILE_BYTES };
19
18
 
20
19
  /**
21
20
  * @param {{ root: string, readOnly?: boolean, maxFileBytes?: number }} opts
@@ -0,0 +1,188 @@
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
+ if (cfg.tcp) f.push('gateway');
62
+ f.push(GATEWAY_CREDIT_FEATURE);
63
+ if (cfg.unix) f.push('gateway-unix');
64
+ if (cfg.endpoints) f.push('gateway-endpoints');
65
+ return f;
66
+ }
67
+
68
+ /**
69
+ * The per-connection core: the table of open gateway connections, the per-client byte budget, credit negotiation and
70
+ * the opcodes that need no Node API. `gateway.mjs` builds its socket-backed session on the same object.
71
+ * @param {{ maxConnections: number, maxBufferedBytes: number, maxClientBufferedBytes: number, endpoints: Map<string, object> | null }} cfg
72
+ * @param {(msg: object) => unknown} send
73
+ * @param {(line: string) => void} log
74
+ * @param {{ who?: () => { username: string | null, fingerprint: string | null } }} [ctx]
75
+ */
76
+ export function createGatewayCore(cfg, send, log = () => {}, ctx = {}) {
77
+ /** @type {Map<number, { channel: GatewayChannel, sock: any }>} */
78
+ const conns = new Map();
79
+ /** gateway_ids whose connect is still in flight (they count against the cap). */
80
+ const pending = new Set();
81
+ let credit = false;
82
+ let closed = false;
83
+ const budget = { used: 0, max: cfg.maxClientBufferedBytes };
84
+
85
+ const reply = (m) => { try { return Promise.resolve(send(m)).catch(() => {}); } catch { return Promise.resolve(); } };
86
+ const fail = (gatewayId, code, message) => reply(gatewayFail({ gatewayId, code, message }));
87
+ const active = () => conns.size + pending.size;
88
+ const idInUse = (id) => conns.has(id) || pending.has(id);
89
+
90
+ /** A channel wired to the wire; `extra` adds the sink (a socket's writer) and the close hooks. */
91
+ function makeChannel(id, extra) {
92
+ return new GatewayChannel({
93
+ id, credit, maxQueued: cfg.maxBufferedBytes, budget,
94
+ sendData: (data) => reply(gatewayData({ gatewayId: id, data })),
95
+ sendCredit: (n) => reply(gatewayCredit({ gatewayId: id, bytes: n })),
96
+ sendClose: (reason) => reply(gatewayClose({ gatewayId: id, reason })),
97
+ ...extra,
98
+ onClose: (reason) => { conns.delete(id); extra?.onClose?.(reason); },
99
+ });
100
+ }
101
+
102
+ async function openEndpoint(m) {
103
+ const id = m.gateway_id;
104
+ if (!Number.isInteger(id) || typeof m.name !== 'string') return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenEndpoint');
105
+ if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
106
+ const ep = cfg.endpoints && ENDPOINT_NAME_RE.test(m.name) ? cfg.endpoints.get(m.name) : undefined;
107
+ if (!ep) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'no such endpoint');
108
+ if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
109
+ const who = ctx.who?.() ?? { username: null, fingerprint: null };
110
+ pending.add(id);
111
+ try {
112
+ if (ep.authorize && !(await ep.authorize(who))) { pending.delete(id); return await fail(id, GATEWAY_FAIL.POLICY_DENIED, 'endpoint refused this caller'); }
113
+ } 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'); }
114
+ pending.delete(id);
115
+ if (closed) return undefined;
116
+ const channel = makeChannel(id, { writeAfterRemoteClose: true, graceMs: HALF_CLOSE_GRACE_MS });
117
+ conns.set(id, { channel, sock: null });
118
+ const { readable, writable } = channel.streams();
119
+ const duplex = {
120
+ readable, writable, who,
121
+ /** Half-close: nothing more will be sent. */
122
+ close: (reason) => channel.end(reason),
123
+ /** Tear the connection down now. */
124
+ destroy: (reason) => channel.destroy(reason),
125
+ closed: channel.closedPromise,
126
+ };
127
+ try {
128
+ const out = ep.open(duplex, who);
129
+ if (out && typeof out.then === 'function') out.then(undefined, (e) => { log(`gateway endpoint ${m.name} failed: ${e?.message}`); channel.destroy('endpoint error'); });
130
+ } catch (e) {
131
+ log(`gateway endpoint ${m.name} threw: ${e.message}`);
132
+ channel.abandon();
133
+ return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'endpoint refused the connection');
134
+ }
135
+ log(`gateway: ${id} -> endpoint ${m.name}`);
136
+ return reply(gatewayOk({ gatewayId: id }));
137
+ }
138
+
139
+ return {
140
+ conns, pending, budget, reply, fail, active, idInUse, makeChannel,
141
+ get closed() { return closed; },
142
+ /** Credit is used on this connection only when the client listed "gateway-credit" in its Hello. */
143
+ setPeerFeatures(features) { credit = Array.isArray(features) && features.includes(GATEWAY_CREDIT_FEATURE); },
144
+ /** @returns {Promise<boolean>} true when the message was a gateway message this session consumed */
145
+ async handle(m) {
146
+ if (closed) return true;
147
+ switch (m.type) {
148
+ case MSG.OPEN_ENDPOINT: await openEndpoint(m); return true;
149
+ case MSG.GATEWAY_DATA: {
150
+ const c = conns.get(m.gateway_id)?.channel;
151
+ const d = m.data;
152
+ if (c && d && d.length <= MAX_DATA_BYTES) c.receive(d);
153
+ return true;
154
+ }
155
+ case MSG.GATEWAY_CREDIT: {
156
+ if (credit && Number.isInteger(m.bytes)) conns.get(m.gateway_id)?.channel.grant(m.bytes);
157
+ return true;
158
+ }
159
+ case MSG.GATEWAY_CLOSE: {
160
+ conns.get(m.gateway_id)?.channel.remoteClosed(m.reason);
161
+ return true;
162
+ }
163
+ // What this host does not serve is refused, not ignored, so the client does not wait for an answer.
164
+ case MSG.OPEN_TCP: case MSG.OPEN_UDP: case MSG.RESOLVE_DNS:
165
+ await fail(m.gateway_id, GATEWAY_FAIL.POLICY_DENIED, 'only named endpoints are available on this host'); return true;
166
+ case MSG.OPEN_UNIX:
167
+ await fail(m.gateway_id, GATEWAY_FAIL.POLICY_DENIED, 'unix sockets are not available on this host'); return true;
168
+ case MSG.LISTEN_REQUEST: case MSG.LISTEN_UNIX:
169
+ await reply(listenFail({ listenerId: m.listener_id, reason: 'listening is not available on this host' })); return true;
170
+ default: return false;
171
+ }
172
+ },
173
+ close() {
174
+ closed = true;
175
+ for (const { channel } of [...conns.values()]) channel.abandon('connection closed');
176
+ conns.clear();
177
+ },
178
+ get size() { return conns.size; },
179
+ /** Bytes received from the client for its origins and not yet taken by them (what the caps bound). */
180
+ get bufferedBytes() { return budget.used; },
181
+ get listenerCount() { return 0; },
182
+ };
183
+ }
184
+
185
+ /** The session factory of an endpoints-only host (`cfg.createGatewaySession`). */
186
+ export function createEndpointGatewaySession(cfg, send, log, ctx) {
187
+ return createGatewayCore(cfg, send, log, ctx);
188
+ }