@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.
@@ -0,0 +1,252 @@
1
+ /**
2
+ * The client half of gateway forwarding: `openUnix`, `openEndpoint`, `openTcp` and `listenUnix` on `WshClient`.
3
+ * Browser-safe (no `node:*`): the connections are web streams with backpressure (see `gateway-channel.mjs`);
4
+ * `forward-node.mjs` builds the Node helper `client.forwardUnix()` on top.
5
+ *
6
+ * gateway_ids and listener_ids this client allocates start at 0x40000000, so they cannot collide with the small
7
+ * ids an application that drives the raw gateway messages itself (netway's `GatewayBackend`) hands out; messages for
8
+ * ids this class does not own go on to `client.onGatewayMessage`.
9
+ */
10
+
11
+ import {
12
+ MSG, openTcp as openTcpMsg, openUdp as openUdpMsg, openUnix as openUnixMsg, openEndpoint as openEndpointMsg, listenUnix as listenUnixMsg,
13
+ listenClose as listenCloseMsg, inboundAccept as inboundAcceptMsg, inboundReject as inboundRejectMsg,
14
+ gatewayData as gatewayDataMsg, gatewayCredit as gatewayCreditMsg, gatewayClose as gatewayCloseMsg,
15
+ } from './messages.mjs';
16
+ import { GatewayChannel, GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
17
+
18
+ const ID_BASE = 0x40000000;
19
+ const ID_LIMIT = 0xffffffff;
20
+ const DEFAULT_TIMEOUT_MS = 30_000;
21
+ const CLIENT_GRACE_MS = 5_000;
22
+
23
+ /** An Error from a GatewayFail / ListenFail: `.code` is the GatewayFail code (4 = refused by policy), `.reason` the host's text. */
24
+ export class GatewayError extends Error {
25
+ constructor(message, code) {
26
+ super(message);
27
+ this.name = 'GatewayError';
28
+ this.code = code;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * @typedef {object} GatewayDuplex
34
+ * @property {ReadableStream<Uint8Array>} readable what the peer sends; read it to keep the peer's credit coming
35
+ * @property {WritableStream<Uint8Array>} writable what you send; each write waits for credit
36
+ * @property {(reason?: string) => void} close half-close: nothing more will be written
37
+ * @property {(reason?: string) => void} destroy tear the connection down now
38
+ * @property {Promise<string | undefined>} closed settles when the connection is over
39
+ */
40
+
41
+ export class GatewayConnections {
42
+ #send;
43
+ #hasFeature;
44
+ #nextId = ID_BASE;
45
+ /** @type {Map<number, GatewayChannel>} */
46
+ #channels = new Map();
47
+ /** @type {Map<number, { channel: GatewayChannel, resolve: Function, reject: Function, timer: any }>} */
48
+ #opening = new Map();
49
+ /** @type {Map<number, { onConnection: Function, resolve?: Function, reject?: Function, timer?: any, path: string, closed: boolean }>} */
50
+ #listeners = new Map();
51
+
52
+ /**
53
+ * @param {object} o
54
+ * @param {(msg: object) => Promise<void>} o.send
55
+ * @param {(feature: string) => boolean} o.hasFeature
56
+ */
57
+ constructor({ send, hasFeature }) {
58
+ this.#send = send;
59
+ this.#hasFeature = hasFeature;
60
+ }
61
+
62
+ #id() {
63
+ if (this.#nextId >= ID_LIMIT) throw new Error('gateway ids exhausted on this connection');
64
+ return this.#nextId++;
65
+ }
66
+
67
+ #need(feature, what) {
68
+ if (!this.#hasFeature(feature)) throw new GatewayError(`this host does not support ${what} (it did not advertise "${feature}")`, 0);
69
+ }
70
+
71
+ /** @param {{ datagram?: boolean }} [kind] a datagram flow has no half-close: the peer's close ends it */
72
+ #makeChannel(id, { datagram = false } = {}) {
73
+ const channel = new GatewayChannel({
74
+ id,
75
+ credit: this.#hasFeature(GATEWAY_CREDIT_FEATURE),
76
+ // After the peer's GatewayClose the application has this long to finish writing (a half-open connection) before
77
+ // our side closes too, so a connection nobody closes does not stay in the table forever.
78
+ graceMs: CLIENT_GRACE_MS,
79
+ onRemoteClose: datagram ? () => channel.destroy() : undefined,
80
+ sendData: (data) => this.#send(gatewayDataMsg({ gatewayId: id, data })),
81
+ sendCredit: (n) => this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n })),
82
+ sendClose: (reason) => this.#send(gatewayCloseMsg({ gatewayId: id, reason })),
83
+ onClose: () => { this.#channels.delete(id); },
84
+ });
85
+ this.#channels.set(id, channel);
86
+ return channel;
87
+ }
88
+
89
+ #duplex(channel) {
90
+ const { readable, writable } = channel.streams();
91
+ return { readable, writable, close: (r) => channel.end(r), destroy: (r) => channel.destroy(r), closed: channel.closedPromise };
92
+ }
93
+
94
+ async #open(build, { timeoutMs = DEFAULT_TIMEOUT_MS, signal } = {}, kind) {
95
+ if (signal?.aborted) throw signal.reason ?? new DOMException('aborted', 'AbortError');
96
+ const id = this.#id();
97
+ const channel = this.#makeChannel(id, kind);
98
+ const done = new Promise((resolve, reject) => {
99
+ const timer = setTimeout(() => { this.#opening.delete(id); channel.abandon(); reject(new GatewayError('the host did not answer the open request in time', 5)); }, timeoutMs);
100
+ timer.unref?.();
101
+ this.#opening.set(id, { channel, resolve, reject, timer });
102
+ });
103
+ const onAbort = () => {
104
+ const o = this.#opening.get(id);
105
+ if (!o) return;
106
+ this.#opening.delete(id); clearTimeout(o.timer);
107
+ channel.destroy(); // the host's Ok, if it comes, finds nothing; its connection is closed by this GatewayClose
108
+ o.reject(signal.reason ?? new DOMException('aborted', 'AbortError'));
109
+ };
110
+ signal?.addEventListener('abort', onAbort, { once: true });
111
+ try {
112
+ await this.#send(build(id));
113
+ } catch (e) {
114
+ const o = this.#opening.get(id);
115
+ if (o) { clearTimeout(o.timer); this.#opening.delete(id); }
116
+ channel.abandon();
117
+ throw e;
118
+ }
119
+ try { return await done; } finally { signal?.removeEventListener('abort', onAbort); }
120
+ }
121
+
122
+ /** Connect to a unix-domain socket on the HOST. */
123
+ async openUnix(path, opts) {
124
+ this.#need('gateway-unix', 'unix-domain socket forwarding');
125
+ if (typeof path !== 'string' || !path) throw new TypeError('openUnix: path must be a non-empty string');
126
+ return this.#open((id) => openUnixMsg({ gatewayId: id, path }), opts);
127
+ }
128
+
129
+ /** Open a named virtual endpoint of the host. */
130
+ async openEndpoint(name, opts) {
131
+ this.#need('gateway-endpoints', 'named endpoints');
132
+ if (typeof name !== 'string' || !name) throw new TypeError('openEndpoint: name must be a non-empty string');
133
+ return this.#open((id) => openEndpointMsg({ gatewayId: id, name }), opts);
134
+ }
135
+
136
+ /** Connect to host:port FROM THE HOST (the gateway's TCP egress, subject to the host's allow list). */
137
+ async openTcp(host, port, opts) {
138
+ this.#need('gateway', 'TCP egress');
139
+ if (typeof host !== 'string' || !host || !Number.isInteger(port)) throw new TypeError('openTcp: host and port are required');
140
+ return this.#open((id) => openTcpMsg({ gatewayId: id, host, port }), opts);
141
+ }
142
+
143
+ /**
144
+ * A UDP "connection" to host:port FROM THE HOST: each chunk written is one datagram, each chunk read is one datagram
145
+ * (at most 65507 bytes). It rides the reliable control stream, so it is ordered and retransmitted; datagrams the
146
+ * receiving side cannot keep up with are dropped by the host. Same destination policy as TCP.
147
+ */
148
+ async openUdp(host, port, opts) {
149
+ this.#need('gateway', 'UDP egress');
150
+ if (typeof host !== 'string' || !host || !Number.isInteger(port)) throw new TypeError('openUdp: host and port are required');
151
+ return this.#open((id) => openUdpMsg({ gatewayId: id, host, port }), opts, { datagram: true });
152
+ }
153
+
154
+ /**
155
+ * Ask the host to listen on a unix-domain socket and hand each connection to `onConnection(duplex)`.
156
+ * @param {string} path
157
+ * @param {{ replace?: boolean, onConnection: (duplex: GatewayDuplex) => void, timeoutMs?: number }} opts
158
+ * @returns {Promise<{ path: string, close: () => Promise<void> }>}
159
+ */
160
+ async listenUnix(path, { replace, onConnection, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
161
+ this.#need('gateway-unix', 'unix-domain socket forwarding');
162
+ if (typeof path !== 'string' || !path) throw new TypeError('listenUnix: path must be a non-empty string');
163
+ if (typeof onConnection !== 'function') throw new TypeError('listenUnix: onConnection is required');
164
+ const id = this.#id();
165
+ const entry = { onConnection, path, closed: false };
166
+ const answered = new Promise((resolve, reject) => {
167
+ entry.resolve = resolve; entry.reject = reject;
168
+ entry.timer = setTimeout(() => { this.#listeners.delete(id); reject(new GatewayError('the host did not answer the listen request in time', 5)); }, timeoutMs);
169
+ entry.timer.unref?.();
170
+ });
171
+ this.#listeners.set(id, entry);
172
+ try {
173
+ await this.#send(listenUnixMsg({ listenerId: id, path, replace: replace === true ? true : undefined }));
174
+ await answered;
175
+ } catch (e) { this.#listeners.delete(id); throw e; }
176
+ return {
177
+ path,
178
+ close: async () => {
179
+ if (entry.closed) return;
180
+ entry.closed = true;
181
+ this.#listeners.delete(id);
182
+ await this.#send(listenCloseMsg({ listenerId: id })).catch(() => {});
183
+ },
184
+ };
185
+ }
186
+
187
+ /** Feed a control message in. Returns true when it belonged to a connection or listener this object owns. */
188
+ handle(m) {
189
+ switch (m.type) {
190
+ case MSG.GATEWAY_OK: {
191
+ const o = this.#opening.get(m.gateway_id);
192
+ if (!o) return this.#channels.has(m.gateway_id);
193
+ this.#opening.delete(m.gateway_id);
194
+ clearTimeout(o.timer);
195
+ o.resolve(this.#duplex(o.channel));
196
+ return true;
197
+ }
198
+ case MSG.GATEWAY_FAIL: {
199
+ const o = this.#opening.get(m.gateway_id);
200
+ if (!o) return false;
201
+ this.#opening.delete(m.gateway_id);
202
+ clearTimeout(o.timer);
203
+ o.channel.abandon();
204
+ o.reject(new GatewayError(m.message || 'refused by the host', m.code));
205
+ return true;
206
+ }
207
+ case MSG.GATEWAY_DATA: { const c = this.#channels.get(m.gateway_id); if (!c) return false; c.receive(m.data); return true; }
208
+ case MSG.GATEWAY_CREDIT: { const c = this.#channels.get(m.gateway_id); if (!c) return false; c.grant(m.bytes); return true; }
209
+ case MSG.GATEWAY_CLOSE: {
210
+ const c = this.#channels.get(m.gateway_id);
211
+ if (!c) return false;
212
+ const o = this.#opening.get(m.gateway_id);
213
+ if (o) { this.#opening.delete(m.gateway_id); clearTimeout(o.timer); c.abandon(); o.reject(new GatewayError('closed by the host', 6)); return true; }
214
+ c.remoteClosed(m.reason);
215
+ return true;
216
+ }
217
+ case MSG.LISTEN_OK: { const l = this.#listeners.get(m.listener_id); if (!l?.resolve) return false; clearTimeout(l.timer); l.resolve(); l.resolve = undefined; return true; }
218
+ case MSG.LISTEN_FAIL: {
219
+ const l = this.#listeners.get(m.listener_id);
220
+ if (!l?.reject) return false;
221
+ clearTimeout(l.timer);
222
+ this.#listeners.delete(m.listener_id);
223
+ l.reject(new GatewayError(m.reason || 'refused by the host', 4));
224
+ return true;
225
+ }
226
+ case MSG.INBOUND_OPEN: {
227
+ const l = this.#listeners.get(m.listener_id);
228
+ if (!l) return false;
229
+ if (l.closed) { void this.#send(inboundRejectMsg({ channelId: m.channel_id, reason: 'listener closed' })).catch(() => {}); return true; }
230
+ let id;
231
+ try { id = this.#id(); } catch { void this.#send(inboundRejectMsg({ channelId: m.channel_id, reason: 'out of ids' })).catch(() => {}); return true; }
232
+ const channel = this.#makeChannel(id);
233
+ const duplex = this.#duplex(channel);
234
+ void this.#send(inboundAcceptMsg({ channelId: m.channel_id, gatewayId: id })).then(() => {
235
+ try { l.onConnection(duplex, { peer: m.peer_addr }); } catch { channel.destroy('handler error'); }
236
+ }, () => channel.abandon());
237
+ return true;
238
+ }
239
+ default: return false;
240
+ }
241
+ }
242
+
243
+ /** The connection is gone: every open connection ends, every pending open fails. */
244
+ abandonAll(reason = 'connection closed') {
245
+ for (const o of this.#opening.values()) { clearTimeout(o.timer); o.reject(new GatewayError(reason, 6)); }
246
+ this.#opening.clear();
247
+ for (const l of this.#listeners.values()) { clearTimeout(l.timer); l.reject?.(new GatewayError(reason, 6)); }
248
+ this.#listeners.clear();
249
+ for (const c of [...this.#channels.values()]) c.abandon(reason);
250
+ this.#channels.clear();
251
+ }
252
+ }
package/src/host.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { WshSigner } from './index.js';
2
2
  import type {
3
- WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshServerAuthOptions, WshServerPrincipal, WshAcceptableSocket, WshAcceptOptions,
3
+ WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshServerAuthOptions, WshServerPrincipal, WshAcceptableSocket, WshAcceptOptions, WshClientEnv,
4
4
  } from './server/index.js';
5
5
 
6
6
  /**
@@ -41,7 +41,7 @@ export interface WshResolvedHostKey {
41
41
 
42
42
  export interface WshResolvedBackends {
43
43
  execRunner: WshExecRunner | null;
44
- execOptions: { timeoutMs?: number; clientEnv?: boolean };
44
+ execOptions: { timeoutMs?: number; clientEnv?: WshClientEnv };
45
45
  pty: { spawn: WshServerPtyOptions['spawn']; shell: string; cwd?: string; env?: Record<string, string | undefined>; term: string } | null;
46
46
  files: Required<Pick<WshFileBackend, 'operate' | 'readWhole' | 'writeWhole' | 'writeAt' | 'maxFileBytes'>> & Pick<WshFileBackend, 'openRange'> | null;
47
47
  mcp: object | null;
@@ -49,7 +49,7 @@ export interface WshResolvedBackends {
49
49
 
50
50
  /** Validate injected backends (no shell, no directory: `exec` is a function or `{ run }`, `fs` an object of operations). */
51
51
  export function resolveBackends(options?: {
52
- exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
52
+ exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
53
53
  pty?: WshServerPtyOptions;
54
54
  fs?: WshFileBackend;
55
55
  mcp?: WshServerMcpOptions;
package/src/index.d.ts CHANGED
@@ -1824,8 +1824,17 @@ export interface WshHostKeyOptions {
1824
1824
  hostLabel?: string;
1825
1825
  /** Sees the verified key before any credential is sent; return `false` (or throw) to refuse. */
1826
1826
  onHostKey?: (hostKey: WshHostKey) => boolean | void | Promise<boolean | void>;
1827
+ /**
1828
+ * Refuse to sign the login unless the signature can be bound to this connection (#119): `true` needs at least one
1829
+ * binding kind the host offers and this client can supply (`host`, `cert-hash`, `tls-exporter`), an array names
1830
+ * kinds that must all be bound. Nothing is signed otherwise. Key logins only.
1831
+ */
1832
+ requireChannelBinding?: boolean | WshChannelBindingKind[];
1827
1833
  }
1828
1834
 
1835
+ /** What a login signature can be bound to (wsh #119). */
1836
+ export type WshChannelBindingKind = 'cert-hash' | 'host' | 'tls-exporter';
1837
+
1829
1838
  /** Options for WshClient.connect(). */
1830
1839
  export interface WshConnectOptions extends WshHostKeyOptions {
1831
1840
  username: string;
@@ -1921,6 +1930,7 @@ export interface WshConnectReverseOptions {
1921
1930
  trustOnFirstUse?: boolean;
1922
1931
  hostLabel?: string;
1923
1932
  onHostKey?: WshHostKeyOptions['onHostKey'];
1933
+ requireChannelBinding?: WshHostKeyOptions['requireChannelBinding'];
1924
1934
  expose?: {
1925
1935
  shell?: boolean;
1926
1936
  exec?: boolean;
@@ -2010,6 +2020,31 @@ export const E2E_FEATURE: 'e2e';
2010
2020
  /** Host feature: it signs its `KeyExchange` reply, so `initiateE2E(..., { verifyPeer })` can authenticate it. */
2011
2021
  export const E2E_SIGN_FEATURE: 'e2e-sign';
2012
2022
 
2023
+ /** Relay feature / operator feature: a `ReverseChallenge` / `ReverseProof` crosses the relay (#117). */
2024
+ export const OPERATOR_PROOF_FEATURE: 'operator-proof';
2025
+ /** Host feature (`ReverseAccept.features`): it takes a signed initiator half and a sealed bridge (#117). */
2026
+ export const E2E_SEALED_FEATURE: 'e2e-sealed';
2027
+ export function challengeTranscript(t: { peerPublicKey: Uint8Array; operatorFingerprint: string; nonce: Uint8Array; sessionId: string }): Uint8Array;
2028
+ export function proofTranscript(t: { peerPublicKey: Uint8Array; operatorPublicKey: Uint8Array; username: string; nonce: Uint8Array; sessionId: string }): Uint8Array;
2029
+ /** `EncryptedFrame.channel_id` of a bridge-level frame (real channels start at 1). */
2030
+ export const BRIDGE_CHANNEL_ID: 0;
2031
+ /** A sealed reverse bridge (#117): seals every message that would cross it into an `EncryptedFrame` and opens them. */
2032
+ export class SealedBridge {
2033
+ constructor(p: { key: CryptoKey; sessionId: string; role: 'initiator' | 'responder' });
2034
+ readonly sessionId: string;
2035
+ isFrame(msg: WshMessage): boolean;
2036
+ seal(msg: WshMessage): Promise<WshMessage>;
2037
+ open(frame: WshMessage): Promise<WshMessage>;
2038
+ }
2039
+ /** Operator proof (#117): the peer's signed `ReverseChallenge` fields, and the checks on each side. */
2040
+ export function createReverseChallenge(identity: { keyPair?: CryptoKeyPair; signer?: WshSigner }, operatorFingerprint: string): Promise<{ fields: object; nonce: Uint8Array; sessionId: string; peerPublicKey: Uint8Array }>;
2041
+ export function verifyReverseChallenge(msg: WshMessage, expect: { target: string; ownFingerprint: string }): Promise<{ peerPublicKey: Uint8Array; peerFingerprint: string; nonce: Uint8Array; sessionId: string }>;
2042
+ export function createOperatorProof(signer: { publicKeyRaw: Uint8Array; sign(data: Uint8Array): Promise<Uint8Array> }, challenge: { peerPublicKey: Uint8Array; nonce: Uint8Array; sessionId: string }, username: string): Promise<object>;
2043
+ export function verifyOperatorProof(msg: WshMessage, issued: { nonce: Uint8Array; sessionId: string; peerPublicKey: Uint8Array }): Promise<{ publicKey: Uint8Array; fingerprint: string; username: string } | null>;
2044
+ /** The binding a login signature carries (#119): SHA-256 over the kinds present, or empty when there are none. */
2045
+ export function computeChannelBinding(values: Partial<Record<WshChannelBindingKind, Uint8Array>>): Promise<Uint8Array>;
2046
+ export const CHANNEL_BINDING_KINDS: readonly WshChannelBindingKind[];
2047
+
2013
2048
  /** The bytes a responder signs in `KeyExchange.signature`. */
2014
2049
  export function keyExchangeTranscript(t: {
2015
2050
  sessionId: string;
@@ -2073,6 +2108,31 @@ export interface WshFileOperationResult {
2073
2108
  * Supports forward connections (client opens sessions on a remote server) and
2074
2109
  * reverse mode (client registers as a peer for incoming connections).
2075
2110
  */
2111
+ /** Options for `openUnix` / `openEndpoint` / `openTcp`. */
2112
+ export interface WshGatewayOpenOptions { signal?: AbortSignal; timeoutMs?: number }
2113
+
2114
+ /** One gateway connection as web streams with backpressure (credit-based flow control when both ends offer `gateway-credit`). */
2115
+ export interface WshGatewayDuplex {
2116
+ /** What the peer sends. Read it to keep credit flowing: a reader that stops reading stops the peer. */
2117
+ readable: ReadableStream<Uint8Array>;
2118
+ /** What you send. Each write waits for credit; closing it half-closes (the peer finishes and closes its side). */
2119
+ writable: WritableStream<Uint8Array>;
2120
+ /** Half-close: nothing more will be written. */
2121
+ close(reason?: string): void;
2122
+ /** Tear the connection down now. */
2123
+ destroy(reason?: string): void;
2124
+ /** Settles once the connection is over. */
2125
+ closed: Promise<string | undefined>;
2126
+ }
2127
+
2128
+ /** A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target. */
2129
+ export class GatewayError extends Error { code: number }
2130
+
2131
+ /** The feature a client lists in `Hello.features` and a host in `ServerHello.features` to meter gateway data with `GatewayCredit`. */
2132
+ export const GATEWAY_CREDIT_FEATURE: 'gateway-credit';
2133
+ /** Credit, in bytes, each direction of a gateway connection starts with. */
2134
+ export const GATEWAY_CREDIT_WINDOW: 262144;
2135
+
2076
2136
  export class WshClient {
2077
2137
  /** Current client state. */
2078
2138
  readonly state: 'disconnected' | 'connecting' | 'connected' | 'authenticated' | 'closed';
@@ -2088,6 +2148,9 @@ export class WshClient {
2088
2148
  */
2089
2149
  readonly authToken: Uint8Array | null;
2090
2150
 
2151
+ /** Seconds the host said it will keep this connection (`AuthOk.ttl`); 0 = no limit promised. Hosts older than 0.36 sent an unenforced 3600. */
2152
+ readonly authTtl: number;
2153
+
2091
2154
  /** Read-only view of active sessions. */
2092
2155
  readonly sessions: Map<number, WshSession>;
2093
2156
 
@@ -2161,6 +2224,25 @@ export class WshClient {
2161
2224
  */
2162
2225
  openSession(opts?: WshOpenSessionOptions): Promise<WshSession>;
2163
2226
 
2227
+ // ── Gateway: unix sockets, named endpoints, TCP egress (#120, #123) ──
2228
+
2229
+ /** Connect to a unix-domain socket on the HOST (needs the host feature `gateway-unix`; refused unless its policy lists the path). */
2230
+ openUnix(path: string, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2231
+ /** Open the host's named virtual endpoint (needs the host feature `gateway-endpoints`). */
2232
+ openEndpoint(name: string, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2233
+ /** Connect to host:port FROM THE HOST (needs the host feature `gateway`; refused unless its `gateway.allow` lists it). */
2234
+ openTcp(host: string, port: number, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2235
+ /** A UDP flow to host:port FROM THE HOST over the reliable control stream: each chunk is one datagram (at most 65507 bytes); the host drops what the receiver cannot keep up with. */
2236
+ openUdp(host: string, port: number, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2237
+ /** Ask the host to listen on a unix-domain socket and hand each connection to `onConnection` (OpenSSH `-R`). */
2238
+ listenUnix(path: string, opts: { replace?: boolean; timeoutMs?: number; onConnection: (duplex: WshGatewayDuplex, info: { peer: string }) => void }): Promise<{ path: string; close(): Promise<void> }>;
2239
+ /**
2240
+ * Node only: forward between a local endpoint and a remote one (`ssh -L` / `-R` with unix sockets and TCP ports mixed).
2241
+ * Each of `local` and `remote` is a socket path (starts with `/`, `./` or `@`) or `host:port`. With `reverse: true` the
2242
+ * HOST listens on `remote` (a unix path) and connections are made to `local` from here.
2243
+ */
2244
+ forwardUnix(opts: { local: string; remote: string; reverse?: boolean; replace?: boolean; onError?: (err: Error) => void }): Promise<{ local: string; remote: string; address?: { address: string; family: string; port: number } | string | null; close(): Promise<void> }>;
2245
+
2164
2246
  /**
2165
2247
  * Open a typed (object-mode) RPC channel (wsh #85): JSON-RPC 2.0 over a CBOR sequence on one stream. Sugar over
2166
2248
  * `openSession({ type: 'rpc', protocol })`. Throws `RpcError` (`UNSUPPORTED_PROTOCOL`) before sending any bytes
@@ -2297,6 +2379,34 @@ export class WshClient {
2297
2379
  */
2298
2380
  reverseConnectTo(targetFingerprint: string, timeout?: number): Promise<void>;
2299
2381
 
2382
+ /**
2383
+ * Connect to a registered peer and wait for its accept or reject. Against a relay that lists `operator-proof` and a
2384
+ * peer that asks, this operator PROVES its identity to the peer (a signature over the peer's key, a nonce the peer
2385
+ * chose and the bridge's session) instead of leaving the peer to trust the relay's `from_fingerprint` (#117).
2386
+ */
2387
+ reverseConnect(
2388
+ targetFingerprint: string,
2389
+ timeout?: number,
2390
+ opts?: {
2391
+ /** `'auto'` (default): prove when the relay carries it and the peer asks; `false`: never; `true`: refuse if the relay cannot carry it. */
2392
+ proof?: 'auto' | boolean;
2393
+ /** Refuse the bridge unless the peer signed its challenge (so it proved its key to this operator). */
2394
+ requirePeerProof?: boolean;
2395
+ /**
2396
+ * Seal the bridge: a key exchange both sides sign comes first, and everything after crosses the relay as
2397
+ * `EncryptedFrame`s. Nothing that names a command, a path or a session is sent before the key exists.
2398
+ * The peer must state `e2e-sealed`. `{ hybrid: false }` skips ML-KEM.
2399
+ */
2400
+ sealed?: boolean | { hybrid?: boolean };
2401
+ },
2402
+ ): Promise<WshMessage>;
2403
+
2404
+ /** The binding kinds the last login's signature covered (`[]` = unbound). */
2405
+ readonly channelBinding: WshChannelBindingKind[];
2406
+
2407
+ /** Called with the operator's `ReverseProof` when this peer sent a `ReverseChallenge` (reverse mode). */
2408
+ onReverseProof: ((msg: WshMessage) => void) | null;
2409
+
2300
2410
  /**
2301
2411
  * Send a control message over the authenticated relay connection.
2302
2412
  */
@@ -2340,6 +2450,10 @@ export class WshClient {
2340
2450
  opts?: {
2341
2451
  /** The peer's long-term Ed25519 public key; the exchange is refused (`E2E_PEER_UNAUTHENTICATED`) unless it signed its half. */
2342
2452
  verifyPeer?: Uint8Array | CryptoKey;
2453
+ /** Sign this (initiator) half with the operator's key; send only to a peer that stated `e2e-sealed`. */
2454
+ signAs?: { sign(data: Uint8Array): Promise<Uint8Array> };
2455
+ /** The responder's raw identity key, bound into the initiator signature (default: `verifyPeer` when raw). */
2456
+ responderIdentity?: Uint8Array;
2343
2457
  },
2344
2458
  ): Promise<WshE2EResult>;
2345
2459
 
package/src/index.mjs CHANGED
@@ -76,10 +76,23 @@ export {
76
76
  export { WshSession } from './session.mjs';
77
77
  export { WshVirtualSessionBackend, normalizeSessionData } from './virtual-session.mjs';
78
78
  export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './client.mjs';
79
+ // Gateway forwarding (unix sockets, named endpoints, flow control) -- wsh #120, #123
80
+ export { GatewayError } from './gateway-client.mjs';
81
+ export { GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from './gateway-channel.mjs';
79
82
 
80
83
  // End-to-end key exchange (responder side, feature names, signed transcript) -- wsh #90
81
84
  export { E2E_FEATURE, E2E_SIGN_FEATURE, keyExchangeTranscript, verifyKeyExchangeSignature } from './e2e-exchange.mjs';
82
85
 
86
+ // The operator proves its identity to the peer; sealed bridges -- wsh #117
87
+ export {
88
+ OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, createReverseChallenge, verifyReverseChallenge, createOperatorProof, verifyOperatorProof,
89
+ challengeTranscript, proofTranscript,
90
+ } from './operator-proof.mjs';
91
+ export { SealedBridge, BRIDGE_CHANNEL_ID } from './bridge-seal.mjs';
92
+
93
+ // Channel binding for the login signature -- wsh #119
94
+ export { computeChannelBinding, CHANNEL_BINDING_KINDS } from './channel-binding.mjs';
95
+
83
96
  // Key storage
84
97
  export { WshKeyStore } from './keystore.mjs';
85
98
 
@@ -2,8 +2,8 @@ import type { WshClient, RpcChannel } from './index.js';
2
2
  import type { WshSigner } from './index.js';
3
3
  import type { WshFileBackend, WshHostKeyOption } from './host.js';
4
4
  import type {
5
- WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions, WshServerPtyOptions,
6
- WshAcceptableSocket, WshAcceptOptions,
5
+ WshServerAuthOptions, WshServerPrincipal, WshServerMcpOptions, WshExecRunner, WshServerOptions, WshServerPtyOptions, WshClientEnv,
6
+ WshAcceptableSocket, WshAcceptOptions, WshGatewayEndpointHandler as WshMemoryEndpointHandler,
7
7
  } from './server/index.js';
8
8
 
9
9
  export interface WshMemorySessionsOptions {
@@ -30,7 +30,7 @@ export interface WshMemoryHostOptions {
30
30
  /** As for `createWshServer`. Omitted = refuse everyone. */
31
31
  auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>);
32
32
  /** `run(command, io)`; there is no shell in memory, so there is no `true`. */
33
- exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
33
+ exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
34
34
  /** `node-pty`-shaped `{ spawn }`, injected (a browser has no pty of its own). Input arrives at `write` as a `Uint8Array`. Off unless given. */
35
35
  pty?: WshServerPtyOptions;
36
36
  /** An object of file operations, not a root path (confining paths is the backend's job). Off unless given. */
@@ -60,7 +60,21 @@ export interface WshMemoryHostOptions {
60
60
  * defaults as `createWshServer`. `true` for the defaults. Off unless given.
61
61
  */
62
62
  sessions?: true | false | null | WshMemorySessionsOptions;
63
+ /**
64
+ * Named virtual endpoints: a host with no file system exposes these instead of unix sockets; a client reaches one with
65
+ * `client.openEndpoint(name)`. The handler gets web streams with backpressure and `who` (the authenticated
66
+ * `{ username, fingerprint }`) and refuses by throwing; `{ open, authorize(who) }` authorises per call. Only the
67
+ * names listed exist. Nothing else of the gateway (TCP, DNS, unix sockets) is available in memory.
68
+ */
69
+ endpoints?: Record<string, WshMemoryEndpointHandler | { open: WshMemoryEndpointHandler; authorize?: (who: { username: string | null; fingerprint: string | null }) => boolean | Promise<boolean> }>;
63
70
  bindTimeoutMs?: number;
71
+ /** End each authenticated connection this long after login; advertised as `AuthOk.ttl` in whole seconds. 0 / omitted = never. */
72
+ connectionTtlMs?: number;
73
+ /**
74
+ * Accept a key login only when its signature is bound to this host's key (`host`, the one binding a memory host has).
75
+ * Needs `hostKey`; a client older than 0.36 cannot satisfy it.
76
+ */
77
+ requireChannelBinding?: boolean | Array<'host'>;
64
78
  onLog?: (line: string) => void;
65
79
  }
66
80
 
@@ -7,12 +7,13 @@
7
7
  * password auth, exec channels, MCP tools, extensions), speaking QMux over a pair of in-memory WebSocket-like
8
8
  * sockets -- so what a client does here is what it does against a server. It serves what a browser can: `exec` as a
9
9
  * function you provide (there is no shell), `mcp` tools, `extensions`, typed `rpc` channels (handler functions you
10
- * provide) and `sessions` (detach / attach / resume of exec sessions, output replayed from an in-memory ring buffer).
10
+ * provide), `sessions` (detach / attach / resume of exec sessions, output replayed from an in-memory ring buffer) and
11
+ * `endpoints` (named virtual endpoints, the in-memory stand-in for unix sockets, with flow control).
11
12
  * Backends are injected, shaped like the Node host's: `pty` (`{ spawn }`, node-pty shaped), `fs` (an object of file
12
13
  * operations, not a root path), `hostKey` (a `CryptoKeyPair`, which may be non-extractable, or a signer
13
14
  * `{ publicKey, sign }`).
14
- * Not available: `gateway`, `relay`, WebTransport, `exec: true` and `fs: { root }` (they need Node), the `wsh-host` /
15
- * `wsh-fs` rpc built-ins (use `@johnhenry/wsh/server`).
15
+ * Not available: the TCP, DNS, UDP and unix-socket parts of `gateway` (named `endpoints` are), `relay`, WebTransport,
16
+ * `exec: true` and `fs: { root }` (they need Node), the `wsh-host` / `wsh-fs` rpc built-ins (use `@johnhenry/wsh/server`).
16
17
  *
17
18
  * To serve a socket someone else upgraded (a WebSocket the page opened to a relay, a byte pipe) use `host.accept(socket)`;
18
19
  * a peer that cannot open QMux data streams (the released Rust client over WebSocket) needs `dataStreams: false`.
@@ -33,6 +34,8 @@ import { createConnectionFactory } from './server/connection.mjs';
33
34
  import { buildAuthorizer, authMethods, FailureLimiter } from './server/auth.mjs';
34
35
  import { resolveBackends, resolveHostKey } from './host-backends.mjs';
35
36
  import { bindSocket } from './server/socket.mjs';
37
+ import { normalizeEndpointGateway, createEndpointGatewaySession } from './server/gateway-core.mjs';
38
+ import { CHANNEL_BINDING_KINDS } from './channel-binding.mjs';
36
39
  import { RPC_PROTOCOL_NAME_RE, RPC_DEFAULT_MAX_MESSAGE } from './rpc.mjs';
37
40
  import { SessionRegistry, DEFAULT_RING_BYTES, DEFAULT_DETACH_TTL_MS, DEFAULT_MAX_DETACHED } from './session-registry.mjs';
38
41
 
@@ -128,7 +131,7 @@ function createRegistry(sessions, log) {
128
131
  /**
129
132
  * @param {object} [options]
130
133
  * @param {object | Function} [options.auth] - As for `createWshServer`. Omitted = refuse everyone.
131
- * @param {Function | { run: Function, timeoutMs?: number, clientEnv?: boolean }} [options.exec]
134
+ * @param {Function | { run: Function, timeoutMs?: number, clientEnv?: boolean | string[] | Function }} [options.exec]
132
135
  * `run(command, io) => Promise<exitCode>` (see `ExecIo` in `server/exec.mjs`): the host has no shell, so there is no `true`.
133
136
  * @param {{ spawn: Function, shell?: string, cwd?: string, env?: object, term?: string }} [options.pty]
134
137
  * `pty.spawn(file, args, { name, cols, rows, cwd, env })` as `node-pty`'s `spawn` (or anything shaped like it) returns
@@ -155,10 +158,27 @@ function createRegistry(sessions, log) {
155
158
  * `createWshServer`, with the same defaults (300000 ms detached, 16 detached sessions, 1 MiB of replayable output
156
159
  * per session). Off unless given: sessions then die with their connection. There is no `sessionSecret`: session
157
160
  * tokens are random per session.
161
+ * @param {Record<string, ((duplex: object, who: { username: string | null, fingerprint: string | null }) => void | Promise<void>) | { open: Function, authorize?: (who: object) => boolean | Promise<boolean> }>} [options.endpoints]
162
+ * Named virtual endpoints (a host with no file system exposes these instead of unix sockets): a client reaches one with
163
+ * `client.openEndpoint(name)`. `duplex` is `{ readable, writable, close(), destroy(), closed, who }` (web streams with
164
+ * backpressure) and `who` is the authenticated `{ username, fingerprint }`, so the handler can authorise per call:
165
+ * throw synchronously to refuse, or give `{ open, authorize(who) }`. Only the names listed here exist (an allow-list by
166
+ * construction); nothing else of the gateway (TCP, DNS, unix sockets) is on in memory.
158
167
  * @param {number} [options.bindTimeoutMs=3000]
168
+ * @param {number} [options.connectionTtlMs=0] - End each authenticated connection this long after login; advertised as
169
+ * `AuthOk.ttl` in whole seconds (#125). 0 = never.
170
+ * @param {boolean | string[]} [options.requireChannelBinding=false] - Accept a key login only when its signature is bound
171
+ * to this host's key (#119). A memory host can bind only `host` (it has no TLS of its own), so this needs `hostKey`;
172
+ * `true` or `['host']`.
159
173
  * @param {(line: string) => void} [options.onLog]
160
174
  */
161
- export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, dataStreams = true, bindTimeoutMs = 3000, onLog = () => {} } = {}) {
175
+ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions, rpc, rpcMaxMessageBytes = RPC_DEFAULT_MAX_MESSAGE, rpcMaxInflight = 64, sessions, endpoints, dataStreams = true, bindTimeoutMs = 3000, connectionTtlMs = 0, requireChannelBinding = false, onLog = () => {} } = {}) {
176
+ if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
177
+ if (requireChannelBinding !== false && requireChannelBinding !== true && !(Array.isArray(requireChannelBinding) && requireChannelBinding.every((k) => CHANNEL_BINDING_KINDS.includes(k)))) {
178
+ throw new TypeError(`createMemoryHost: requireChannelBinding must be true, false or an array of kinds (${CHANNEL_BINDING_KINDS.join(', ')})`);
179
+ }
180
+ if (Array.isArray(requireChannelBinding) && requireChannelBinding.some((k) => k !== 'host')) throw new TypeError('createMemoryHost: requireChannelBinding can name only "host" (a memory host has no TLS connection or certificate to bind)');
181
+ if (requireChannelBinding && !hostKey) throw new TypeError('createMemoryHost: requireChannelBinding needs a hostKey (the only thing a memory host can bind a login to)');
162
182
  if (exec === true) throw new TypeError('createMemoryHost: exec must be a function (run(command, io)); there is no shell to run `true` with');
163
183
  if (exec !== undefined && typeof exec !== 'function' && typeof exec?.run !== 'function') {
164
184
  throw new TypeError('createMemoryHost: exec must be a function or { run }');
@@ -176,10 +196,14 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
176
196
  failureDelayMs: rl.failureDelayMs ?? 250,
177
197
  };
178
198
  const methods = authMethods(auth);
199
+ // Named virtual endpoints: a gateway with no TCP, DNS or unix sockets that answers only `OpenEndpoint`, built from
200
+ // the browser-safe core (`server/gateway-core.mjs`), so a page can have it.
201
+ const gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
179
202
 
180
203
  const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
181
- authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, log: onLog,
182
- methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, gateway: null, sessions: registry, relay: null,
204
+ authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, log: onLog,
205
+ methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost,
206
+ gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
183
207
  }));
184
208
  ready.catch(() => {});
185
209