@johnhenry/wsh 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.d.ts CHANGED
@@ -1284,6 +1284,15 @@ export class WshTransport {
1284
1284
  /** Callback on transport error. */
1285
1285
  onError: ((err: Error) => void) | null;
1286
1286
 
1287
+ /** Callback for an unreliable datagram (WebTransport only). */
1288
+ onDatagram: ((bytes: Uint8Array) => void) | null;
1289
+ /** True where the transport can carry unreliable datagrams (WebTransport). */
1290
+ readonly supportsDatagrams: boolean;
1291
+ /** The largest datagram the connection can carry now, in bytes (0 = none). Read it again before sending. */
1292
+ readonly maxDatagramSize: number;
1293
+ /** Send one datagram without waiting or queueing; false = dropped. */
1294
+ sendDatagram(bytes: Uint8Array): boolean;
1295
+
1287
1296
  /** Current transport state. */
1288
1297
  readonly state: 'disconnected' | 'connecting' | 'connected' | 'closed';
1289
1298
 
@@ -1824,8 +1833,17 @@ export interface WshHostKeyOptions {
1824
1833
  hostLabel?: string;
1825
1834
  /** Sees the verified key before any credential is sent; return `false` (or throw) to refuse. */
1826
1835
  onHostKey?: (hostKey: WshHostKey) => boolean | void | Promise<boolean | void>;
1836
+ /**
1837
+ * Refuse to sign the login unless the signature can be bound to this connection (#119): `true` needs at least one
1838
+ * binding kind the host offers and this client can supply (`host`, `cert-hash`, `tls-exporter`), an array names
1839
+ * kinds that must all be bound. Nothing is signed otherwise. Key logins only.
1840
+ */
1841
+ requireChannelBinding?: boolean | WshChannelBindingKind[];
1827
1842
  }
1828
1843
 
1844
+ /** What a login signature can be bound to (wsh #119). */
1845
+ export type WshChannelBindingKind = 'cert-hash' | 'host' | 'tls-exporter';
1846
+
1829
1847
  /** Options for WshClient.connect(). */
1830
1848
  export interface WshConnectOptions extends WshHostKeyOptions {
1831
1849
  username: string;
@@ -1921,6 +1939,7 @@ export interface WshConnectReverseOptions {
1921
1939
  trustOnFirstUse?: boolean;
1922
1940
  hostLabel?: string;
1923
1941
  onHostKey?: WshHostKeyOptions['onHostKey'];
1942
+ requireChannelBinding?: WshHostKeyOptions['requireChannelBinding'];
1924
1943
  expose?: {
1925
1944
  shell?: boolean;
1926
1945
  exec?: boolean;
@@ -2010,6 +2029,31 @@ export const E2E_FEATURE: 'e2e';
2010
2029
  /** Host feature: it signs its `KeyExchange` reply, so `initiateE2E(..., { verifyPeer })` can authenticate it. */
2011
2030
  export const E2E_SIGN_FEATURE: 'e2e-sign';
2012
2031
 
2032
+ /** Relay feature / operator feature: a `ReverseChallenge` / `ReverseProof` crosses the relay (#117). */
2033
+ export const OPERATOR_PROOF_FEATURE: 'operator-proof';
2034
+ /** Host feature (`ReverseAccept.features`): it takes a signed initiator half and a sealed bridge (#117). */
2035
+ export const E2E_SEALED_FEATURE: 'e2e-sealed';
2036
+ export function challengeTranscript(t: { peerPublicKey: Uint8Array; operatorFingerprint: string; nonce: Uint8Array; sessionId: string }): Uint8Array;
2037
+ export function proofTranscript(t: { peerPublicKey: Uint8Array; operatorPublicKey: Uint8Array; username: string; nonce: Uint8Array; sessionId: string }): Uint8Array;
2038
+ /** `EncryptedFrame.channel_id` of a bridge-level frame (real channels start at 1). */
2039
+ export const BRIDGE_CHANNEL_ID: 0;
2040
+ /** A sealed reverse bridge (#117): seals every message that would cross it into an `EncryptedFrame` and opens them. */
2041
+ export class SealedBridge {
2042
+ constructor(p: { key: CryptoKey; sessionId: string; role: 'initiator' | 'responder' });
2043
+ readonly sessionId: string;
2044
+ isFrame(msg: WshMessage): boolean;
2045
+ seal(msg: WshMessage): Promise<WshMessage>;
2046
+ open(frame: WshMessage): Promise<WshMessage>;
2047
+ }
2048
+ /** Operator proof (#117): the peer's signed `ReverseChallenge` fields, and the checks on each side. */
2049
+ export function createReverseChallenge(identity: { keyPair?: CryptoKeyPair; signer?: WshSigner }, operatorFingerprint: string): Promise<{ fields: object; nonce: Uint8Array; sessionId: string; peerPublicKey: Uint8Array }>;
2050
+ export function verifyReverseChallenge(msg: WshMessage, expect: { target: string; ownFingerprint: string }): Promise<{ peerPublicKey: Uint8Array; peerFingerprint: string; nonce: Uint8Array; sessionId: string }>;
2051
+ export function createOperatorProof(signer: { publicKeyRaw: Uint8Array; sign(data: Uint8Array): Promise<Uint8Array> }, challenge: { peerPublicKey: Uint8Array; nonce: Uint8Array; sessionId: string }, username: string): Promise<object>;
2052
+ export function verifyOperatorProof(msg: WshMessage, issued: { nonce: Uint8Array; sessionId: string; peerPublicKey: Uint8Array }): Promise<{ publicKey: Uint8Array; fingerprint: string; username: string } | null>;
2053
+ /** The binding a login signature carries (#119): SHA-256 over the kinds present, or empty when there are none. */
2054
+ export function computeChannelBinding(values: Partial<Record<WshChannelBindingKind, Uint8Array>>): Promise<Uint8Array>;
2055
+ export const CHANNEL_BINDING_KINDS: readonly WshChannelBindingKind[];
2056
+
2013
2057
  /** The bytes a responder signs in `KeyExchange.signature`. */
2014
2058
  export function keyExchangeTranscript(t: {
2015
2059
  sessionId: string;
@@ -2073,6 +2117,44 @@ export interface WshFileOperationResult {
2073
2117
  * Supports forward connections (client opens sessions on a remote server) and
2074
2118
  * reverse mode (client registers as a peer for incoming connections).
2075
2119
  */
2120
+ /** Options for `openUnix` / `openEndpoint` / `openTcp`. */
2121
+ export interface WshGatewayOpenOptions { signal?: AbortSignal; timeoutMs?: number }
2122
+
2123
+ /** One gateway connection as web streams with backpressure (credit-based flow control when both ends offer `gateway-credit`). */
2124
+ export interface WshGatewayDuplex {
2125
+ /** What the peer sends. Read it to keep credit flowing: a reader that stops reading stops the peer. */
2126
+ readable: ReadableStream<Uint8Array>;
2127
+ /** What you send. Each write waits for credit; closing it half-closes (the peer finishes and closes its side). */
2128
+ writable: WritableStream<Uint8Array>;
2129
+ /** Half-close: nothing more will be written. */
2130
+ close(reason?: string): void;
2131
+ /** Tear the connection down now. */
2132
+ destroy(reason?: string): void;
2133
+ /** Settles once the connection is over. */
2134
+ closed: Promise<string | undefined>;
2135
+ }
2136
+
2137
+ /** A UDP flow (`client.openUdp()`): one chunk = one datagram, and a datagram may be dropped without notice. */
2138
+ export interface WshUdpFlow extends WshGatewayDuplex {
2139
+ /** 'datagram': WebTransport datagrams. 'stream': the reliable control stream (WebSocket, or a host without `gateway-datagram`). */
2140
+ readonly transport: 'datagram' | 'stream';
2141
+ /** The largest payload that travels as one datagram right now (it can change; read it again). */
2142
+ readonly maxDatagramSize: number;
2143
+ /** Resolves true when handed to the transport, false when dropped locally. Rejects with RangeError for a payload over 65507 bytes (or over the datagram size with `oversize: 'drop'`). */
2144
+ send(bytes: Uint8Array): Promise<boolean>;
2145
+ stats: { sent: number; received: number; sentReliable: number; receivedReliable: number; sendDropped: number; receiveDropped: number };
2146
+ }
2147
+ /** Feature string for UDP over WebTransport datagrams. */
2148
+ export const GATEWAY_DATAGRAM_FEATURE: 'gateway-datagram';
2149
+
2150
+ /** A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target. */
2151
+ export class GatewayError extends Error { code: number }
2152
+
2153
+ /** The feature a client lists in `Hello.features` and a host in `ServerHello.features` to meter gateway data with `GatewayCredit`. */
2154
+ export const GATEWAY_CREDIT_FEATURE: 'gateway-credit';
2155
+ /** Credit, in bytes, each direction of a gateway connection starts with. */
2156
+ export const GATEWAY_CREDIT_WINDOW: 262144;
2157
+
2076
2158
  export class WshClient {
2077
2159
  /** Current client state. */
2078
2160
  readonly state: 'disconnected' | 'connecting' | 'connected' | 'authenticated' | 'closed';
@@ -2088,6 +2170,9 @@ export class WshClient {
2088
2170
  */
2089
2171
  readonly authToken: Uint8Array | null;
2090
2172
 
2173
+ /** Seconds the host said it will keep this connection (`AuthOk.ttl`); 0 = no limit promised. Hosts older than 0.36 sent an unenforced 3600. */
2174
+ readonly authTtl: number;
2175
+
2091
2176
  /** Read-only view of active sessions. */
2092
2177
  readonly sessions: Map<number, WshSession>;
2093
2178
 
@@ -2161,6 +2246,31 @@ export class WshClient {
2161
2246
  */
2162
2247
  openSession(opts?: WshOpenSessionOptions): Promise<WshSession>;
2163
2248
 
2249
+ // ── Gateway: unix sockets, named endpoints, TCP egress (#120, #123) ──
2250
+
2251
+ /** Connect to a unix-domain socket on the HOST (needs the host feature `gateway-unix`; refused unless its policy lists the path). */
2252
+ openUnix(path: string, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2253
+ /** Open the host's named virtual endpoint (needs the host feature `gateway-endpoints`). */
2254
+ openEndpoint(name: string, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2255
+ /** Connect to host:port FROM THE HOST (needs the host feature `gateway`; refused unless its `gateway.allow` lists it). */
2256
+ openTcp(host: string, port: number, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2257
+ /**
2258
+ * A UDP flow to ONE destination, host:port, FROM THE HOST. Datagram semantics: any payload may be dropped. Over WebTransport, when the
2259
+ * host lists `gateway-datagram`, payloads are WebTransport datagrams (unordered, no retransmission, no head-of-line blocking between
2260
+ * flows); otherwise they ride the reliable control stream. A payload too big for one datagram goes on the control stream unless `oversize: 'drop'`.
2261
+ */
2262
+ openUdp(host: string, port: number, opts?: WshGatewayOpenOptions & { oversize?: 'reliable' | 'drop' }): Promise<WshUdpFlow>;
2263
+ /** Ask the host to listen on a TCP port (a reverse tunnel); needs `gateway` and the host's `gateway.reverse`. `bindAddr` is a request the host may ignore. */
2264
+ listenTcp(port: number, opts: { bindAddr?: string; timeoutMs?: number; onConnection: (duplex: WshGatewayDuplex, info: { peer: string; peerPort: number }) => void }): Promise<{ port: number; close(): Promise<void> }>;
2265
+ /** Ask the host to listen on a unix-domain socket and hand each connection to `onConnection` (OpenSSH `-R`). */
2266
+ listenUnix(path: string, opts: { replace?: boolean; timeoutMs?: number; onConnection: (duplex: WshGatewayDuplex, info: { peer: string }) => void }): Promise<{ path: string; close(): Promise<void> }>;
2267
+ /**
2268
+ * Node only: forward between a local endpoint and a remote one (`ssh -L` / `-R` with unix sockets and TCP ports mixed).
2269
+ * Each of `local` and `remote` is a socket path (starts with `/`, `./` or `@`) or `host:port`. With `reverse: true` the
2270
+ * HOST listens on `remote` (a unix path) and connections are made to `local` from here.
2271
+ */
2272
+ 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> }>;
2273
+
2164
2274
  /**
2165
2275
  * Open a typed (object-mode) RPC channel (wsh #85): JSON-RPC 2.0 over a CBOR sequence on one stream. Sugar over
2166
2276
  * `openSession({ type: 'rpc', protocol })`. Throws `RpcError` (`UNSUPPORTED_PROTOCOL`) before sending any bytes
@@ -2297,6 +2407,34 @@ export class WshClient {
2297
2407
  */
2298
2408
  reverseConnectTo(targetFingerprint: string, timeout?: number): Promise<void>;
2299
2409
 
2410
+ /**
2411
+ * Connect to a registered peer and wait for its accept or reject. Against a relay that lists `operator-proof` and a
2412
+ * peer that asks, this operator PROVES its identity to the peer (a signature over the peer's key, a nonce the peer
2413
+ * chose and the bridge's session) instead of leaving the peer to trust the relay's `from_fingerprint` (#117).
2414
+ */
2415
+ reverseConnect(
2416
+ targetFingerprint: string,
2417
+ timeout?: number,
2418
+ opts?: {
2419
+ /** `'auto'` (default): prove when the relay carries it and the peer asks; `false`: never; `true`: refuse if the relay cannot carry it. */
2420
+ proof?: 'auto' | boolean;
2421
+ /** Refuse the bridge unless the peer signed its challenge (so it proved its key to this operator). */
2422
+ requirePeerProof?: boolean;
2423
+ /**
2424
+ * Seal the bridge: a key exchange both sides sign comes first, and everything after crosses the relay as
2425
+ * `EncryptedFrame`s. Nothing that names a command, a path or a session is sent before the key exists.
2426
+ * The peer must state `e2e-sealed`. `{ hybrid: false }` skips ML-KEM.
2427
+ */
2428
+ sealed?: boolean | { hybrid?: boolean };
2429
+ },
2430
+ ): Promise<WshMessage>;
2431
+
2432
+ /** The binding kinds the last login's signature covered (`[]` = unbound). */
2433
+ readonly channelBinding: WshChannelBindingKind[];
2434
+
2435
+ /** Called with the operator's `ReverseProof` when this peer sent a `ReverseChallenge` (reverse mode). */
2436
+ onReverseProof: ((msg: WshMessage) => void) | null;
2437
+
2300
2438
  /**
2301
2439
  * Send a control message over the authenticated relay connection.
2302
2440
  */
@@ -2340,6 +2478,10 @@ export class WshClient {
2340
2478
  opts?: {
2341
2479
  /** The peer's long-term Ed25519 public key; the exchange is refused (`E2E_PEER_UNAUTHENTICATED`) unless it signed its half. */
2342
2480
  verifyPeer?: Uint8Array | CryptoKey;
2481
+ /** Sign this (initiator) half with the operator's key; send only to a peer that stated `e2e-sealed`. */
2482
+ signAs?: { sign(data: Uint8Array): Promise<Uint8Array> };
2483
+ /** The responder's raw identity key, bound into the initiator signature (default: `verifyPeer` when raw). */
2484
+ responderIdentity?: Uint8Array;
2343
2485
  },
2344
2486
  ): Promise<WshE2EResult>;
2345
2487
 
package/src/index.mjs CHANGED
@@ -76,10 +76,24 @@ 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';
82
+ export { GATEWAY_DATAGRAM_FEATURE } from './gateway-datagram.mjs';
79
83
 
80
84
  // End-to-end key exchange (responder side, feature names, signed transcript) -- wsh #90
81
85
  export { E2E_FEATURE, E2E_SIGN_FEATURE, keyExchangeTranscript, verifyKeyExchangeSignature } from './e2e-exchange.mjs';
82
86
 
87
+ // The operator proves its identity to the peer; sealed bridges -- wsh #117
88
+ export {
89
+ OPERATOR_PROOF_FEATURE, E2E_SEALED_FEATURE, createReverseChallenge, verifyReverseChallenge, createOperatorProof, verifyOperatorProof,
90
+ challengeTranscript, proofTranscript,
91
+ } from './operator-proof.mjs';
92
+ export { SealedBridge, BRIDGE_CHANNEL_ID } from './bridge-seal.mjs';
93
+
94
+ // Channel binding for the login signature -- wsh #119
95
+ export { computeChannelBinding, CHANNEL_BINDING_KINDS } from './channel-binding.mjs';
96
+
83
97
  // Key storage
84
98
  export { WshKeyStore } from './keystore.mjs';
85
99
 
@@ -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
 
@@ -65,6 +65,8 @@ export const MSG = Object.freeze({
65
65
  REVERSE_REJECT: 0x55,
66
66
  RELAY_FORWARD: 0x56,
67
67
  REVERSE_CLOSE: 0x57,
68
+ REVERSE_CHALLENGE: 0x58,
69
+ REVERSE_PROOF: 0x59,
68
70
 
69
71
  // Session
70
72
  SESSION_LIST: 0x5f,
@@ -73,6 +75,9 @@ export const MSG = Object.freeze({
73
75
  DETACH_FAIL: 0x62,
74
76
 
75
77
  // Gateway
78
+ OPEN_UNIX: 0x63,
79
+ OPEN_ENDPOINT: 0x64,
80
+ LISTEN_UNIX: 0x65,
76
81
  OPEN_TCP: 0x70,
77
82
  OPEN_UDP: 0x71,
78
83
  RESOLVE_DNS: 0x72,
@@ -88,6 +93,7 @@ export const MSG = Object.freeze({
88
93
  LISTEN_FAIL: 0x7c,
89
94
  LISTEN_CLOSE: 0x7d,
90
95
  GATEWAY_DATA: 0x7e,
96
+ GATEWAY_CREDIT: 0x7f,
91
97
 
92
98
  // Guest
93
99
  GUEST_INVITE: 0x80,
@@ -497,13 +503,10 @@ export function reversePeers({ peers } = {}) {
497
503
  };
498
504
  }
499
505
 
500
- export function reverseConnect({ targetFingerprint, username, fromFingerprint } = {}) {
501
- return {
502
- type: MSG.REVERSE_CONNECT,
503
- target_fingerprint: targetFingerprint,
504
- username,
505
- from_fingerprint: fromFingerprint,
506
- };
506
+ export function reverseConnect({ targetFingerprint, username, fromFingerprint, features } = {}) {
507
+ const msg = { type: MSG.REVERSE_CONNECT, target_fingerprint: targetFingerprint, username, from_fingerprint: fromFingerprint };
508
+ if (features !== undefined) msg.features = features;
509
+ return msg;
507
510
  }
508
511
 
509
512
  export function reverseAccept({ targetFingerprint, username, capabilities = [], peerType = "host", shellBackend = "pty", supportsAttach = false, supportsReplay = false, supportsEcho = false, supportsTermSync = false, features } = {}) {
@@ -533,6 +536,24 @@ export function reverseClose({ targetFingerprint, reason } = {}) {
533
536
  return msg;
534
537
  }
535
538
 
539
+ export function reverseChallenge({ targetFingerprint, publicKey, operatorFingerprint, nonce, sessionId, signature } = {}) {
540
+ return {
541
+ type: MSG.REVERSE_CHALLENGE,
542
+ target_fingerprint: targetFingerprint,
543
+ public_key: publicKey,
544
+ operator_fingerprint: operatorFingerprint,
545
+ nonce,
546
+ session_id: sessionId,
547
+ signature,
548
+ };
549
+ }
550
+
551
+ export function reverseProof({ targetFingerprint, publicKey, username, nonce, sessionId, signature, fromFingerprint } = {}) {
552
+ const msg = { type: MSG.REVERSE_PROOF, target_fingerprint: targetFingerprint, public_key: publicKey, username, nonce, session_id: sessionId, signature };
553
+ if (fromFingerprint !== undefined) msg.from_fingerprint = fromFingerprint;
554
+ return msg;
555
+ }
556
+
536
557
  export function sessionList({ sessions } = {}) {
537
558
  return {
538
559
  type: MSG.SESSION_LIST,
@@ -561,6 +582,28 @@ export function detachFail({ reason } = {}) {
561
582
  };
562
583
  }
563
584
 
585
+ export function openUnix({ gatewayId, path } = {}) {
586
+ return {
587
+ type: MSG.OPEN_UNIX,
588
+ gateway_id: gatewayId,
589
+ path,
590
+ };
591
+ }
592
+
593
+ export function openEndpoint({ gatewayId, name } = {}) {
594
+ return {
595
+ type: MSG.OPEN_ENDPOINT,
596
+ gateway_id: gatewayId,
597
+ name,
598
+ };
599
+ }
600
+
601
+ export function listenUnix({ listenerId, path, replace } = {}) {
602
+ const msg = { type: MSG.LISTEN_UNIX, listener_id: listenerId, path };
603
+ if (replace !== undefined) msg.replace = replace;
604
+ return msg;
605
+ }
606
+
564
607
  export function openTcp({ gatewayId, host, port } = {}) {
565
608
  return {
566
609
  type: MSG.OPEN_TCP,
@@ -677,6 +720,14 @@ export function gatewayData({ gatewayId, data } = {}) {
677
720
  };
678
721
  }
679
722
 
723
+ export function gatewayCredit({ gatewayId, bytes } = {}) {
724
+ return {
725
+ type: MSG.GATEWAY_CREDIT,
726
+ gateway_id: gatewayId,
727
+ bytes,
728
+ };
729
+ }
730
+
680
731
  export function guestInvite({ sessionId, ttl, permissions = ["read"] } = {}) {
681
732
  return {
682
733
  type: MSG.GUEST_INVITE,
@@ -948,6 +999,7 @@ export const RELAY_FORWARDABLE = new Set([
948
999
  MSG.SIGNAL,
949
1000
  MSG.SESSION_DATA,
950
1001
  MSG.GATEWAY_DATA,
1002
+ MSG.GATEWAY_CREDIT,
951
1003
  MSG.GATEWAY_OK,
952
1004
  MSG.GATEWAY_FAIL,
953
1005
  MSG.GATEWAY_CLOSE,
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The operator proves its identity to the PEER (wsh #117).
3
+ *
4
+ * In reverse mode the relay authenticates the operator (its login key) and stamps `from_fingerprint` on what it
5
+ * forwards, so a peer that took `accept({ fingerprint })` at face value trusted the relay for authorization. With
6
+ * proof the peer does not have to:
7
+ *
8
+ * operator -> relay -> peer ReverseConnect { features: ['operator-proof'] }
9
+ * peer -> relay -> operator ReverseChallenge { public_key, operator_fingerprint, nonce, session_id, signature }
10
+ * operator -> relay -> peer ReverseProof { public_key, username, nonce, session_id, signature }
11
+ * peer: verifies, THEN runs `accept({ fingerprint, username, proven: true })`
12
+ *
13
+ * Both signatures are Ed25519 over a labelled, length-prefixed byte string (not a hash, so nothing is truncated):
14
+ *
15
+ * challenge = "wsh-reverse-challenge-v1\0" || lp(peer key) || lp(operator fingerprint) || lp(nonce) || lp(session id)
16
+ * proof = "wsh-operator-proof-v1\0" || lp(peer key) || lp(operator key) || lp(username) || lp(nonce) || lp(session id)
17
+ *
18
+ * The peer signs its challenge so the operator knows whom it is proving itself to and that the peer saw the
19
+ * operator's own fingerprint (a relay that rewrote `from_fingerprint` shows). The operator's proof names the peer it
20
+ * is for, the peer's single-use nonce and the bridge's session id: it cannot be replayed to another peer, later, or
21
+ * for another bridge, and a relay that swaps `public_key` cannot sign for the key it put there.
22
+ *
23
+ * What it does NOT do on its own: it proves who was at the other end when the bridge was set up. A relay can still
24
+ * stamp that identity on a plain message afterwards; closing that is the sealed bridge (`bridge-seal.mjs`), which a
25
+ * host that requires operator proof also requires.
26
+ */
27
+
28
+ import { verify as verifyBytes, importPublicKeyRaw, fingerprint, resolveSigner } from './auth.mjs';
29
+
30
+ /** `ServerHello.features` of a relay that carries `ReverseChallenge` / `ReverseProof`, and `ReverseConnect.features` of an operator that answers one. */
31
+ export const OPERATOR_PROOF_FEATURE = 'operator-proof';
32
+ /** `ReverseAccept.features` of a peer that takes a signed initiator half and a sealed bridge. */
33
+ export const E2E_SEALED_FEATURE = 'e2e-sealed';
34
+
35
+ const enc = new TextEncoder();
36
+ const CHALLENGE_LABEL = enc.encode('wsh-reverse-challenge-v1\0');
37
+ const PROOF_LABEL = enc.encode('wsh-operator-proof-v1\0');
38
+ export const NONCE_LENGTH = 32;
39
+
40
+ const lp = (bytes) => {
41
+ const out = new Uint8Array(4 + bytes.length);
42
+ new DataView(out.buffer).setUint32(0, bytes.length);
43
+ out.set(bytes, 4);
44
+ return out;
45
+ };
46
+ const concat = (parts) => {
47
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
48
+ let off = 0;
49
+ for (const p of parts) { out.set(p, off); off += p.length; }
50
+ return out;
51
+ };
52
+ const isKey = (v) => v instanceof Uint8Array && v.length === 32;
53
+ const str = (v, max = 256) => typeof v === 'string' && v.length > 0 && v.length <= max;
54
+
55
+ /** The bytes a peer signs in a `ReverseChallenge`. */
56
+ export function challengeTranscript({ peerPublicKey, operatorFingerprint, nonce, sessionId }) {
57
+ return concat([CHALLENGE_LABEL, lp(peerPublicKey), lp(enc.encode(operatorFingerprint)), lp(nonce), lp(enc.encode(sessionId))]);
58
+ }
59
+
60
+ /** The bytes an operator signs in a `ReverseProof`. */
61
+ export function proofTranscript({ peerPublicKey, operatorPublicKey, username, nonce, sessionId }) {
62
+ return concat([PROOF_LABEL, lp(peerPublicKey), lp(operatorPublicKey), lp(enc.encode(username)), lp(nonce), lp(enc.encode(sessionId))]);
63
+ }
64
+
65
+ async function verifyWith(rawKey, signature, data) {
66
+ if (!isKey(rawKey) || !(signature instanceof Uint8Array) || signature.length !== 64) return false;
67
+ try { return await verifyBytes(await importPublicKeyRaw(rawKey), signature, data); } catch { return false; }
68
+ }
69
+
70
+ /**
71
+ * Peer side: make a challenge for the operator `operatorFingerprint` (as the relay stamped it).
72
+ * @param {{ keyPair?: CryptoKeyPair, signer?: object }} identity - this peer's key
73
+ * @param {string} operatorFingerprint
74
+ * @returns {Promise<{ fields: object, nonce: Uint8Array, sessionId: string, peerPublicKey: Uint8Array }>}
75
+ * `fields` is what goes into `reverseChallenge({ targetFingerprint, ...fields })`
76
+ */
77
+ export async function createReverseChallenge(identity, operatorFingerprint) {
78
+ const signer = await resolveSigner(identity);
79
+ if (!signer) throw new TypeError('createReverseChallenge: a keyPair or signer is required');
80
+ const nonce = crypto.getRandomValues(new Uint8Array(NONCE_LENGTH));
81
+ const sessionId = crypto.randomUUID();
82
+ const signature = await signer.sign(challengeTranscript({ peerPublicKey: signer.publicKeyRaw, operatorFingerprint, nonce, sessionId }));
83
+ return {
84
+ fields: { publicKey: signer.publicKeyRaw, operatorFingerprint, nonce, sessionId, signature },
85
+ nonce, sessionId, peerPublicKey: signer.publicKeyRaw,
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Operator side: check a `ReverseChallenge` and return the peer's identity, or throw.
91
+ * @param {object} msg - the decoded message (snake_case)
92
+ * @param {{ target: string, ownFingerprint: string }} expect - the peer fingerprint (or prefix) asked for; this operator's own
93
+ * @returns {Promise<{ peerPublicKey: Uint8Array, peerFingerprint: string, nonce: Uint8Array, sessionId: string }>}
94
+ */
95
+ export async function verifyReverseChallenge(msg, { target, ownFingerprint }) {
96
+ const fail = (why) => Object.assign(new Error(`reverse challenge refused: ${why}`), { code: 'REVERSE_CHALLENGE_INVALID' });
97
+ if (!isKey(msg.public_key) || !(msg.nonce instanceof Uint8Array) || msg.nonce.length !== NONCE_LENGTH || !str(msg.session_id) || !str(msg.operator_fingerprint)) throw fail('malformed');
98
+ const peerFingerprint = await fingerprint(msg.public_key);
99
+ if (typeof target !== 'string' || !target || !peerFingerprint.startsWith(target)) throw fail('the key that signed it is not the peer that was asked for');
100
+ if (msg.operator_fingerprint !== ownFingerprint) throw fail('the peer saw a different operator fingerprint than this connection\'s (the relay rewrote it)');
101
+ const ok = await verifyWith(msg.public_key, msg.signature, challengeTranscript({
102
+ peerPublicKey: msg.public_key, operatorFingerprint: msg.operator_fingerprint, nonce: msg.nonce, sessionId: msg.session_id,
103
+ }));
104
+ if (!ok) throw fail('the signature does not verify');
105
+ return { peerPublicKey: msg.public_key, peerFingerprint, nonce: msg.nonce, sessionId: msg.session_id };
106
+ }
107
+
108
+ /**
109
+ * Operator side: answer a verified challenge.
110
+ * @param {{ publicKeyRaw: Uint8Array, sign: (d: Uint8Array) => Promise<Uint8Array> }} signer - from `resolveSigner`
111
+ * @returns {Promise<object>} fields for `reverseProof({ targetFingerprint, ...fields })`
112
+ */
113
+ export async function createOperatorProof(signer, challenge, username) {
114
+ const signature = await signer.sign(proofTranscript({
115
+ peerPublicKey: challenge.peerPublicKey, operatorPublicKey: signer.publicKeyRaw, username, nonce: challenge.nonce, sessionId: challenge.sessionId,
116
+ }));
117
+ return { publicKey: signer.publicKeyRaw, username, nonce: challenge.nonce, sessionId: challenge.sessionId, signature };
118
+ }
119
+
120
+ /**
121
+ * Peer side: check a `ReverseProof` against the challenge it issued.
122
+ * @param {object} msg - the decoded message
123
+ * @param {{ nonce: Uint8Array, sessionId: string, peerPublicKey: Uint8Array }} issued
124
+ * @returns {Promise<{ publicKey: Uint8Array, fingerprint: string, username: string } | null>} null when it does not verify
125
+ */
126
+ export async function verifyOperatorProof(msg, issued) {
127
+ if (!isKey(msg.public_key) || !str(msg.username, 64)) return null;
128
+ const same = (a, b) => a instanceof Uint8Array && a.length === b.length && a.every((x, i) => x === b[i]);
129
+ if (!same(msg.nonce, issued.nonce) || msg.session_id !== issued.sessionId) return null;
130
+ const ok = await verifyWith(msg.public_key, msg.signature, proofTranscript({
131
+ peerPublicKey: issued.peerPublicKey, operatorPublicKey: msg.public_key, username: msg.username, nonce: issued.nonce, sessionId: issued.sessionId,
132
+ }));
133
+ return ok ? { publicKey: msg.public_key, fingerprint: await fingerprint(msg.public_key), username: msg.username } : null;
134
+ }
135
+