@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.
@@ -54,6 +54,9 @@ export interface WshServerHostKey {
54
54
  openssh: string;
55
55
  }
56
56
 
57
+ /** The `clientEnv` option of `exec` and `pty`: see {@link WshServerExecOptions.clientEnv}. */
58
+ export type WshClientEnv = boolean | string[] | ((name: string, value: string) => boolean);
59
+
57
60
  /** What a custom `exec` runner receives for one session. */
58
61
  export interface WshExecIo {
59
62
  user: string;
@@ -85,8 +88,12 @@ export interface WshServerExecOptions {
85
88
  shell?: boolean | string;
86
89
  /** Kill a session after this long (0 / omitted = never). */
87
90
  timeoutMs?: number;
88
- /** Apply `env` sent by the client (default `true`). */
89
- clientEnv?: boolean;
91
+ /**
92
+ * Which `env` variables a client may set. Default: an allow-list (`TERM`, `COLORTERM`, `LANG`, `LANGUAGE`, `LC_*`).
93
+ * `true` accepts everything (the behaviour before 0.36), `false` nothing, a list names exact variables or `PREFIX_*`
94
+ * patterns (replacing the default list), a function decides per variable.
95
+ */
96
+ clientEnv?: WshClientEnv;
90
97
  /** Replace the child_process runner entirely (e.g. a restricted, no-shell host). */
91
98
  run?: WshExecRunner;
92
99
  }
@@ -100,6 +107,59 @@ export interface WshPtyProcess {
100
107
  kill(signal?: string): void;
101
108
  }
102
109
 
110
+ /** Who is calling a named endpoint: the authenticated identity of the connection. */
111
+ export interface WshGatewayWho { username: string | null; fingerprint: string | null }
112
+
113
+ /** What a named endpoint handler (or a client's `openEndpoint`) gets: web streams with backpressure. */
114
+ export interface WshGatewayEndpointDuplex {
115
+ readable: ReadableStream<Uint8Array>;
116
+ writable: WritableStream<Uint8Array>;
117
+ who: WshGatewayWho;
118
+ /** Half-close: nothing more will be sent. */
119
+ close(reason?: string): void;
120
+ /** Tear the connection down now. */
121
+ destroy(reason?: string): void;
122
+ /** Settles when the connection is over (either side, or the client disconnected). */
123
+ closed: Promise<string | undefined>;
124
+ }
125
+
126
+ export type WshGatewayEndpointHandler = (duplex: WshGatewayEndpointDuplex, who: WshGatewayWho) => void | Promise<void>;
127
+
128
+ export interface WshServerGatewayOptions {
129
+ /** Destinations a client may reach: `"*"`, `"host"` (any port), `"host:port"`. Default deny. An IP-literal entry permits exactly that address even if private. */
130
+ allow: string[];
131
+ /** CIDR blocks or addresses the host may dial although they are not globally routable (`"10.0.0.0/8"`, `"127.0.0.1"`, `"fd00::/8"`). Default none. */
132
+ allowPrivate?: string[];
133
+ /** Concurrent gateway connections per client (default 32). */
134
+ maxConnections?: number;
135
+ connectTimeoutMs?: number;
136
+ /** A UDP flow with no datagram in either direction for this long is closed (default 60000). */
137
+ udpIdleMs?: number;
138
+ /** Bytes received from a client for one connection and not yet taken by its origin before it is closed (default 4 MiB; at least 262144). */
139
+ maxBufferedBytes?: number;
140
+ /** The same, summed over one client's connections (default 32 MiB). */
141
+ maxClientBufferedBytes?: number;
142
+ socks?: string | { host: string; port: number };
143
+ /**
144
+ * Unix-domain sockets a client may reach (`OpenUnix`, feature `gateway-unix`) or ask the host to create
145
+ * (`ListenUnix`). Off unless given; each entry is an absolute path (exact), a directory prefix with a trailing `/`,
146
+ * or `@name` / `@prefix/` for the Linux abstract namespace. Checked after `realpath` of the parent directory; the
147
+ * file must be a socket, not a symlink. Sockets the host creates are mode 0600 and removed on close.
148
+ */
149
+ unix?: {
150
+ connect?: string[];
151
+ listen?: string[];
152
+ /** Let a client replace an existing STALE socket file when it asks to (OpenSSH `StreamLocalBindUnlink`). Default false. */
153
+ replaceStale?: boolean;
154
+ /** Unix listeners per client (default 4). */
155
+ maxListeners?: number;
156
+ };
157
+ /** Named virtual endpoints (`OpenEndpoint`, feature `gateway-endpoints`): only these names exist. */
158
+ endpoints?: Record<string, WshGatewayEndpointHandler | { open: WshGatewayEndpointHandler; authorize?: (who: WshGatewayWho) => boolean | Promise<boolean> }>;
159
+ /** `false`: no TCP or DNS at all (an endpoints-only gateway). Default true. */
160
+ tcp?: boolean;
161
+ }
162
+
103
163
  export interface WshServerPtyOptions {
104
164
  /** `node-pty`'s `spawn(file, args, options)`, or anything shaped like it. */
105
165
  spawn(file: string, args: string[], options: {
@@ -111,6 +171,8 @@ export interface WshServerPtyOptions {
111
171
  env?: Record<string, string | undefined>;
112
172
  /** `TERM` value (default `xterm-256color`). */
113
173
  term?: string;
174
+ /** Which `env` variables a client may add to the shell's environment; same forms and default as `exec.clientEnv`. */
175
+ clientEnv?: WshClientEnv;
114
176
  }
115
177
 
116
178
  export interface WshServerFsOptions {
@@ -343,9 +405,14 @@ export interface WshServerOptions {
343
405
  * Answer the gateway opcodes (OpenTcp, ResolveDns, GatewayData, GatewayClose) so a client can open TCP connections and
344
406
  * resolve names from this host. Default deny: a destination must match `allow` (`"*"`, `"host"` any port, `"host:port"`).
345
407
  * `socks` dials through a SOCKS5 proxy (e.g. Tor at `127.0.0.1:9050`) with the name left unresolved; `ResolveDns` is then
346
- * refused. UDP and reverse tunnels are answered with a failure. Off by default.
408
+ * refused. UDP and TCP reverse tunnels are answered with a failure. Off by default.
409
+ *
410
+ * The ADDRESS a name resolves to is checked too: the host resolves once, refuses every address
411
+ * that is not globally routable (loopback, private, link-local, CGNAT, ULA, multicast, reserved, and IPv4 wrapped as
412
+ * mapped / NAT64 / 6to4 IPv6) unless `allowPrivate` or an IP-literal `allow` entry says so, and connects to that
413
+ * address. `ResolveDns` answers are filtered the same way. Gateway data is flow controlled (`gateway-credit`).
347
414
  */
348
- gateway?: { allow: string[]; maxConnections?: number; connectTimeoutMs?: number; socks?: string | { host: string; port: number } };
415
+ gateway?: WshServerGatewayOptions;
349
416
  /**
350
417
  * Handlers for application-defined control messages: one whose `type` is a string (protocol messages are numeric, so
351
418
  * there is no collision) from an authenticated connection is handed to `extensions[type]`. A throw is logged.
@@ -372,6 +439,14 @@ export interface WshServerOptions {
372
439
  rpcMaxInflight?: number;
373
440
  /** How long exec output waits for a client that has not yet opened its data stream (default 3000). */
374
441
  bindTimeoutMs?: number;
442
+ /** End every authenticated connection this long after login; advertised as `AuthOk.ttl` (whole seconds, rounded up). 0 / omitted = never. */
443
+ connectionTtlMs?: number;
444
+ /**
445
+ * Accept a key login only when its signature is bound to this connection (#119): `true` needs any binding kind, an array
446
+ * names kinds that must all be bound (`host` needs `hostKey`; `tls-exporter` needs `wss://` served by this process, not a
447
+ * TLS-terminating proxy; `cert-hash` needs WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it.
448
+ */
449
+ requireChannelBinding?: boolean | Array<'cert-hash' | 'host' | 'tls-exporter'>;
375
450
  onLog?: (line: string) => void;
376
451
  }
377
452
 
@@ -474,7 +549,14 @@ export interface WshReverseHostOptions {
474
549
  /** This host's identity; its fingerprint is what operators connect to. */
475
550
  keyPair: CryptoKeyPair;
476
551
  /** Who may be bridged to this host. Default: nobody. */
477
- accept?: (operator: { fingerprint: string; username: string }) => boolean | Promise<boolean>;
552
+ accept?: (operator: {
553
+ fingerprint: string;
554
+ username: string;
555
+ /** True when the operator signed a challenge from THIS host (wsh #117): `fingerprint` and `username` are then the operator's own claim, not the relay's. */
556
+ proven: boolean;
557
+ /** The operator's raw Ed25519 key, when `proven`. */
558
+ publicKey?: Uint8Array;
559
+ }) => boolean | Promise<boolean>;
478
560
  exec?: true | WshServerExecOptions | WshExecRunner;
479
561
  pty?: WshServerPtyOptions;
480
562
  fs?: WshServerFsOptions;
@@ -501,6 +583,16 @@ export interface WshReverseHostOptions {
501
583
  * `hybrid` (default true) offers X25519+ML-KEM-768 when asked and available.
502
584
  */
503
585
  e2e?: false | { sign?: boolean | 'auto'; hybrid?: boolean };
586
+ /**
587
+ * Require the operator to prove its identity to this host (wsh #117) and seal the bridge: an operator that does not
588
+ * offer proof is refused, `accept` runs only after the proof verifies (with the identity taken from the proof, not
589
+ * the relay), and this host acts only on messages sealed under a key exchange both sides signed -- a relay cannot
590
+ * inject an `Open`. Needs `e2e` and `reportFeatures`. Without it the proof is still requested when the relay and the
591
+ * operator can do it, and reported as `proven`.
592
+ */
593
+ requireOperatorProof?: boolean;
594
+ /** How long an operator has to answer the challenge (default 5000). */
595
+ proofTimeoutMs?: number;
504
596
  onLog?: (line: string) => void;
505
597
  }
506
598
 
@@ -18,11 +18,21 @@ import { createConnectionFactory, STREAM_ANNOUNCE } from './connection.mjs';
18
18
  import { normalizeGateway, createGatewaySession } from './gateway.mjs';
19
19
  import { createRpcHost, mcpServerAdapter } from './rpc.mjs';
20
20
  import { bindSocket } from './socket.mjs';
21
+ import { TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH, CHANNEL_BINDING_KINDS } from '../channel-binding.mjs';
21
22
 
22
23
  export { parseAuthorizedKeys, STREAM_ANNOUNCE, mcpServerAdapter };
23
24
  export { createReverseHost } from './reverse-host.mjs';
24
25
  export { generateSelfSignedCertificate } from './self-signed.mjs';
25
26
 
27
+ /** The TLS exporter of a `wss://` connection as a channel binding (#119); null on a plain socket or a TLS-terminating proxy hop. */
28
+ function tlsChannelBinding(socket) {
29
+ try {
30
+ if (!socket || socket.encrypted !== true || typeof socket.exportKeyingMaterial !== 'function') return null;
31
+ const out = socket.exportKeyingMaterial(TLS_EXPORTER_LENGTH, TLS_EXPORTER_LABEL);
32
+ return out?.length === TLS_EXPORTER_LENGTH ? { 'tls-exporter': [new Uint8Array(out.buffer, out.byteOffset, out.byteLength).slice()] } : null;
33
+ } catch { return null; }
34
+ }
35
+
26
36
  /**
27
37
  * @param {object} [options]
28
38
  * @param {string} [options.host='127.0.0.1']
@@ -74,12 +84,22 @@ export { generateSelfSignedCertificate } from './self-signed.mjs';
74
84
  * names from this host. Default deny: a destination must match `allow` (`"*"`, `"host"`, `"host:port"`). `socks` dials
75
85
  * through a SOCKS5 proxy (Tor) with the name unresolved. UDP and reverse tunnels are refused. Off unless given. See `gateway.mjs`.
76
86
  * @param {number} [options.bindTimeoutMs=3000]
87
+ * @param {number} [options.connectionTtlMs=0] - End every authenticated connection this long after login (0 = never).
88
+ * Advertised as `AuthOk.ttl` in whole seconds, rounded up; the client reads it as `client.authTtl`.
89
+ * @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound to
90
+ * this connection (#119): `true` needs any binding kind, an array names kinds that must all be bound (`host` needs
91
+ * `hostKey`; `tls-exporter` needs `wss://` served by this process, not a TLS-terminating proxy; `cert-hash` needs
92
+ * WebTransport with `selfSigned`). Clients older than 0.36 cannot satisfy it. Off by default.
77
93
  * @param {(line: string) => void} [options.onLog]
78
94
  * @returns {{ listen(): Promise<{address: string, port: number}>, accept(socket: object, options?: object): Promise<{ close(): void }>, close(): Promise<void>, address(): ({address: string, port: number} | null) }}
79
95
  */
80
96
  export function createWshServer({
81
- host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, onLog = () => {},
97
+ host = '127.0.0.1', port = 0, tls, auth, exec, pty, fs, hostKey, mcp, rpc, rpcMaxMessageBytes, rpcMaxInflight, sessions, sessionSecret, relay, extensions, gateway, webTransport, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {},
82
98
  } = {}) {
99
+ if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
100
+ throw new TypeError(`createWshServer: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
101
+ }
102
+ if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createWshServer: connectionTtlMs must be a non-negative number of milliseconds (0 = no limit)');
83
103
  let wss = null;
84
104
  let httpsServer = null;
85
105
  let bound = null;
@@ -125,7 +145,7 @@ export function createWshServer({
125
145
  if (relay) hub = new RelayHub({ ...relay, log: onLog });
126
146
  if (extensions !== undefined && (extensions === null || typeof extensions !== 'object')) throw new TypeError('createWshServer: extensions must be an object of handlers');
127
147
  return createConnectionFactory({
128
- authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, log: onLog,
148
+ authorize, execRunner, execOptions, pty: ptyConfig, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
129
149
  methods, hostKey: host_, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: gatewayCfg, createGatewaySession, sessions: registry, relay: hub,
130
150
  });
131
151
  })();
@@ -156,6 +176,7 @@ export function createWshServer({
156
176
  send: (b) => { if (ws.readyState === 1) ws.send(b); },
157
177
  remote: { address: req?.socket?.remoteAddress, headers: req?.headers ?? {} },
158
178
  closeTransport: () => ws.close(1000),
179
+ channelBinding: tlsChannelBinding(req?.socket),
159
180
  });
160
181
  ws.on('message', (d) => {
161
182
  const buf = Array.isArray(d) ? Buffer.concat(d) : Buffer.isBuffer(d) ? d : Buffer.from(d);
@@ -21,5 +21,6 @@ export function normalizePty(pty) {
21
21
  cwd: pty.cwd,
22
22
  env: pty.env,
23
23
  term: pty.term ?? 'xterm-256color',
24
+ clientEnv: pty.clientEnv,
24
25
  };
25
26
  }
@@ -36,6 +36,7 @@ const MAX_REMEMBERED_SEQS = 4096;
36
36
  const MAX_CAPABILITIES = 32;
37
37
  const MAX_FEATURES = 64;
38
38
  const MAX_FEATURE_LENGTH = 128;
39
+ const MAX_OPERATOR_FEATURES = 16;
39
40
  const SHORT_PREFIX_MIN = 8;
40
41
 
41
42
  /** `ReverseReject.reason` for a peer that already has an operator (or a request awaiting its answer). */
@@ -245,12 +246,15 @@ export class RelayHub {
245
246
  timer.unref?.();
246
247
  this.#pending.set(target.handle, { operator, timer });
247
248
  // The relay speaks for the operator's identity; whatever the client wrote in these fields is discarded.
248
- target.handle.send({
249
+ const forwarded = {
249
250
  type: MSG.REVERSE_CONNECT,
250
251
  target_fingerprint: target.meta.fingerprint,
251
252
  username: operator.username,
252
253
  from_fingerprint: operator.fingerprint,
253
- });
254
+ };
255
+ // What the operator says it can do (#117), bounded; it is the operator's own claim and decides nothing here.
256
+ if (Array.isArray(msg.features) && msg.features.length <= MAX_OPERATOR_FEATURES && msg.features.every((f) => isStr(f, MAX_FEATURE_LENGTH))) forwarded.features = [...msg.features];
257
+ target.handle.send(forwarded);
254
258
  this.log(`relay: ${operator.fingerprint.slice(0, 12)} -> ${target.meta.fingerprint.slice(0, 12)} requested`);
255
259
  }
256
260
 
@@ -278,6 +282,45 @@ export class RelayHub {
278
282
  }
279
283
  }
280
284
 
285
+ /**
286
+ * `ReverseChallenge` from a peer to the operator whose `ReverseConnect` it is answering (#117). Carried, not
287
+ * interpreted: the relay cannot forge it (the peer signed it) and gains nothing by reading it.
288
+ */
289
+ challenge(peer, msg) {
290
+ const p = this.#pending.get(peer);
291
+ if (!p || !(msg.public_key instanceof Uint8Array) || !(msg.signature instanceof Uint8Array) || !(msg.nonce instanceof Uint8Array)
292
+ || !isStr(msg.session_id, 256) || !isStr(msg.operator_fingerprint, 256) || msg.public_key.length > 64 || msg.signature.length > 128 || msg.nonce.length > 64) return;
293
+ p.operator.send({
294
+ type: MSG.REVERSE_CHALLENGE,
295
+ target_fingerprint: peer.fingerprint,
296
+ public_key: msg.public_key,
297
+ operator_fingerprint: msg.operator_fingerprint,
298
+ nonce: msg.nonce,
299
+ session_id: msg.session_id,
300
+ signature: msg.signature,
301
+ });
302
+ }
303
+
304
+ /** `ReverseProof` from an operator to the peer it has a pending `ReverseConnect` with (#117). */
305
+ proof(operator, msg) {
306
+ for (const [target, p] of this.#pending) {
307
+ if (p.operator !== operator) continue;
308
+ if (!(msg.public_key instanceof Uint8Array) || !(msg.signature instanceof Uint8Array) || !(msg.nonce instanceof Uint8Array)
309
+ || !isStr(msg.session_id, 256) || !isStr(msg.username, 64) || msg.public_key.length > 64 || msg.signature.length > 128 || msg.nonce.length > 64) return;
310
+ target.send({
311
+ type: MSG.REVERSE_PROOF,
312
+ target_fingerprint: target.fingerprint,
313
+ public_key: msg.public_key,
314
+ username: msg.username,
315
+ nonce: msg.nonce,
316
+ session_id: msg.session_id,
317
+ signature: msg.signature,
318
+ from_fingerprint: operator.fingerprint,
319
+ });
320
+ return;
321
+ }
322
+ }
323
+
281
324
  /** Is `handle` one end of a bridge? */
282
325
  bridged(handle) {
283
326
  return this.#operatorPeer.has(handle) || (this.#peerOperators.get(handle)?.size ?? 0) > 0;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Which unix-domain socket paths may a client reach on (or create on) the host? Default deny: nothing unless the
3
+ * operator listed it. Node only (it touches the file system); loaded lazily by the gateway so the browser-safe
4
+ * memory host never imports it.
5
+ *
6
+ * A pattern is an absolute path, exact (`/var/run/docker.sock`) or a directory prefix with a trailing slash
7
+ * (`/run/user/1000/wsh/`), or, for the Linux abstract namespace, `@name` / `@prefix/`. A requested path is accepted
8
+ * only when, AFTER the parent directory has been resolved with `realpath`, it equals an exact pattern or lies under
9
+ * a prefix (patterns are resolved the same way, so `/var/run` and `/private/var/run` agree). The file itself must
10
+ * be a socket and not a symlink. A `..` segment is refused outright. This closes the "allowed directory contains a
11
+ * symlink to somewhere else" escape; it cannot close the window between the check and the connect (the path is
12
+ * connected by its resolved name, which narrows it), so allow only directories no other local user can write to.
13
+ */
14
+
15
+ import path from 'node:path';
16
+
17
+ let fsp = null;
18
+ const loadFs = async () => (fsp ??= (await import('node:fs/promises')).default);
19
+
20
+ export const ABSTRACT_PREFIX = '@';
21
+ const MAX_PATH = 4096;
22
+
23
+ /** @param {string[] | undefined} list @param {string} what */
24
+ function checkPatterns(list, what) {
25
+ if (list === undefined) return [];
26
+ if (!Array.isArray(list) || list.some((p) => typeof p !== 'string' || !p)) throw new TypeError(`gateway.unix.${what} must be an array of non-empty strings`);
27
+ for (const p of list) {
28
+ if (p.includes('\0') || p.length > MAX_PATH) throw new TypeError(`gateway.unix.${what}: bad pattern ${JSON.stringify(p.slice(0, 80))}`);
29
+ if (!p.startsWith('/') && !p.startsWith(ABSTRACT_PREFIX)) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} must be an absolute path or an abstract name starting with "@"`);
30
+ if (p === '/' || p === ABSTRACT_PREFIX || p === `${ABSTRACT_PREFIX}/`) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} would allow everything; list a specific path or directory`);
31
+ if (p.split('/').includes('..')) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} must not contain ".."`);
32
+ }
33
+ return [...list];
34
+ }
35
+
36
+ /**
37
+ * @param {object} [opts]
38
+ * @param {string[]} [opts.connect] sockets a client may connect to (`OpenUnix`)
39
+ * @param {string[]} [opts.listen] sockets a client may ask the host to create (`ListenUnix`)
40
+ * @param {boolean} [opts.replaceStale=false] a client may ask to replace a stale socket file (OpenSSH `StreamLocalBindUnlink`)
41
+ * @param {number} [opts.maxListeners=4] unix listeners per client connection
42
+ */
43
+ export function normalizeUnixPolicy(opts) {
44
+ if (opts === undefined || opts === null || opts === false) return null;
45
+ if (opts === true || typeof opts !== 'object') throw new TypeError('gateway.unix needs explicit paths (default deny): { connect: [...], listen: [...] }');
46
+ const maxListeners = opts.maxListeners ?? 4;
47
+ if (!Number.isInteger(maxListeners) || maxListeners < 0) throw new TypeError('gateway.unix.maxListeners must be a non-negative integer');
48
+ return {
49
+ connect: checkPatterns(opts.connect, 'connect'),
50
+ listen: checkPatterns(opts.listen, 'listen'),
51
+ replaceStale: opts.replaceStale === true,
52
+ maxListeners,
53
+ };
54
+ }
55
+
56
+ /** Is `target` the pattern, or under it (prefix patterns end with "/")? Both already resolved. */
57
+ function matches(pattern, target) {
58
+ return pattern.endsWith('/') ? target.startsWith(pattern) : target === pattern;
59
+ }
60
+
61
+ /** The pattern as the file system sees it today: its parent (or itself, for a prefix) through realpath. */
62
+ async function resolvePattern(p) {
63
+ const fs = await loadFs();
64
+ try {
65
+ if (p.endsWith('/')) return `${(await fs.realpath(p)).replace(/\/+$/, '')}/`;
66
+ return path.join(await fs.realpath(path.dirname(p)), path.basename(p));
67
+ } catch { return null; } // a pattern whose directory does not exist matches nothing
68
+ }
69
+
70
+ /**
71
+ * @param {string} requested what the client sent
72
+ * @param {string[]} patterns
73
+ * @returns {Promise<{ ok: true, abstract: boolean, path: string } | { ok: false, reason: string }>}
74
+ * `path` is what to connect to or bind: the resolved path, or `\0name` for an abstract socket.
75
+ */
76
+ export async function checkUnixPath(requested, patterns) {
77
+ if (typeof requested !== 'string' || !requested || requested.length > MAX_PATH || requested.indexOf('\0', 1) !== -1) return { ok: false, reason: 'malformed path' };
78
+ // Abstract namespace: refused unless a pattern lists it; there is no file system to resolve.
79
+ if (requested.startsWith(ABSTRACT_PREFIX) || requested.startsWith('\0')) {
80
+ const name = ABSTRACT_PREFIX + requested.slice(1);
81
+ if (name.length < 2) return { ok: false, reason: 'malformed path' };
82
+ if (name.split('/').includes('..')) return { ok: false, reason: 'malformed path' };
83
+ const listed = patterns.some((p) => p.startsWith(ABSTRACT_PREFIX) && matches(p, name));
84
+ return listed ? { ok: true, abstract: true, path: `\0${name.slice(1)}` } : { ok: false, reason: 'path not allowed by the gateway policy' };
85
+ }
86
+ if (!requested.startsWith('/') || requested.split('/').includes('..')) return { ok: false, reason: 'path must be absolute and without ".."' };
87
+ const base = path.basename(requested);
88
+ if (!base || base === '.' || base === '..' || requested.endsWith('/')) return { ok: false, reason: 'malformed path' };
89
+ const fs = await loadFs();
90
+ let resolved;
91
+ try { resolved = path.join(await fs.realpath(path.dirname(requested)), base); } catch { return { ok: false, reason: 'path not allowed by the gateway policy' }; }
92
+ for (const p of patterns) {
93
+ if (p.startsWith(ABSTRACT_PREFIX)) continue;
94
+ const rp = await resolvePattern(p);
95
+ if (rp && matches(rp, resolved)) return { ok: true, abstract: false, path: resolved };
96
+ }
97
+ return { ok: false, reason: 'path not allowed by the gateway policy' };
98
+ }
99
+
100
+ /** `lstat` of an allowed path: `null` when absent, else `{ socket, ino, dev }` (a symlink is never a socket here). */
101
+ export async function statSocket(p) {
102
+ const fs = await loadFs();
103
+ try {
104
+ const st = await fs.lstat(p);
105
+ return { socket: st.isSocket(), ino: st.ino, dev: st.dev };
106
+ } catch (e) {
107
+ if (e.code === 'ENOENT') return null;
108
+ throw e;
109
+ }
110
+ }
111
+
112
+ export async function unlinkIfSocket(p, expect) {
113
+ const fs = await loadFs();
114
+ try {
115
+ const st = await fs.lstat(p);
116
+ if (!st.isSocket()) return;
117
+ if (expect && (st.ino !== expect.ino || st.dev !== expect.dev)) return; // someone else's socket now
118
+ await fs.unlink(p);
119
+ } catch { /* already gone */ }
120
+ }
@@ -121,6 +121,8 @@ export async function startWebTransport({ options, host, attach, log }) {
121
121
  sendMessage: (msg) => (controlWriter ? controlWriter.write(frameEncode(msg)) : undefined),
122
122
  remote: { address: session.peerAddress, headers: session.header ?? {} },
123
123
  closeTransport: () => { try { session.close(); } catch { /* already closed */ } },
124
+ // A client that pinned this self-signed certificate can bind its login signature to it (#119).
125
+ channelBinding: current?.hash ? { 'cert-hash': [current.hash] } : null,
124
126
  });
125
127
 
126
128
  const incoming = session.incomingBidirectionalStreams.getReader();
@@ -324,6 +324,22 @@ export class WebSocketTransport extends WshTransport {
324
324
  this._emitClose();
325
325
  }
326
326
 
327
+ /**
328
+ * The TLS exporter, when the WebSocket implementation exposes its TLS socket (the `ws` package does, as
329
+ * `_socket`, over `wss://`); `null` for a browser, Node's global `WebSocket`, or a plain `ws://`. See `WshTransport`.
330
+ * @param {string} label
331
+ * @param {number} length
332
+ * @returns {Uint8Array | null}
333
+ */
334
+ tlsExporter(label, length) {
335
+ try {
336
+ const sock = this.#ws?._socket;
337
+ if (!sock || typeof sock.exportKeyingMaterial !== 'function' || sock.encrypted !== true) return null;
338
+ const out = sock.exportKeyingMaterial(length, label);
339
+ return out && out.length === length ? new Uint8Array(out.buffer, out.byteOffset, out.byteLength).slice() : null;
340
+ } catch { return null; }
341
+ }
342
+
327
343
  // ── Outbound helper ──────────────────────────────────────────────
328
344
 
329
345
  /**
package/src/transport.mjs CHANGED
@@ -136,6 +136,17 @@ export class WshTransport {
136
136
  return this.#state;
137
137
  }
138
138
 
139
+ /**
140
+ * TLS keying material for channel binding (#119): `length` bytes exported with `label` (RFC 5705 / 8446 7.5), or
141
+ * `null` where the platform does not expose it (every browser, and Node's own global `WebSocket`).
142
+ * @param {string} label
143
+ * @param {number} length
144
+ * @returns {Uint8Array | null}
145
+ */
146
+ tlsExporter(label, length) { // eslint-disable-line no-unused-vars
147
+ return null;
148
+ }
149
+
139
150
  /** @protected Update internal state. */
140
151
  _setState(s) {
141
152
  this.#state = s;