@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
@@ -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;