@johnhenry/wsh 0.41.0 → 0.43.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
@@ -249,6 +249,8 @@ export const MCP_CANCEL_FEATURE: 'mcp-cancel';
249
249
  export const STREAM_ANNOUNCE_FEATURE: 'stream-announce';
250
250
  /** ServerHello feature: the host runs `exec` on plain pipes (stderr apart, stdin EOF) when asked with `stdio: 'pipes'`. */
251
251
  export const EXEC_PIPES_FEATURE: 'exec-pipes';
252
+ /** ServerHello feature (#121): the host has execution targets; `Open`, `FileOp` and `OpenEndpoint` take `target`. */
253
+ export const TARGETS_FEATURE: 'targets';
252
254
 
253
255
  // ── Typed (object-mode) RPC channels -- wsh #85 ────────────────────────
254
256
 
@@ -444,6 +446,9 @@ export function open(opts?: {
444
446
  cols?: number;
445
447
  rows?: number;
446
448
  env?: Record<string, string>;
449
+ stdio?: string;
450
+ /** #121: the host's execution target (only to a host that advertises `targets`). */
451
+ target?: string;
447
452
  }): WshMessage;
448
453
 
449
454
  export function openOk(opts?: {
@@ -761,6 +766,12 @@ export function restartPty(opts?: {
761
766
 
762
767
  export function sessionListRequest(): WshMessage;
763
768
 
769
+ export function listTargets(): WshMessage;
770
+
771
+ export function targetList(opts?: {
772
+ targets?: WshTargetInfo[];
773
+ }): WshMessage;
774
+
764
775
  export function sessionList(opts?: {
765
776
  sessions?: unknown[];
766
777
  }): WshMessage;
@@ -941,6 +952,8 @@ export function fileOp(opts?: {
941
952
  path?: string;
942
953
  offset?: number;
943
954
  length?: number;
955
+ /** #121: the host's execution target (only to a host that advertises `targets`). */
956
+ target?: string;
944
957
  }): WshMessage;
945
958
 
946
959
  export function fileResult(opts?: {
@@ -1839,6 +1852,16 @@ export interface WshHostKeyOptions {
1839
1852
  * kinds that must all be bound. Nothing is signed otherwise. Key logins only.
1840
1853
  */
1841
1854
  requireChannelBinding?: boolean | WshChannelBindingKind[];
1855
+ /**
1856
+ * Seal the WHOLE session end to end (#155): after login a signed key exchange with the host (bound to its proven host
1857
+ * key and this login key), then every message but the keepalive -- gateway and endpoint data included -- is an
1858
+ * authenticated encrypted frame a relay that copies bytes can neither read nor alter; a frame that does not open
1859
+ * closes the connection. Default `'auto'`: seal only against a host that says `e2e-session-required`. `true` seals or
1860
+ * fails, BEFORE a credential is sent (a host that does not offer `e2e-session`, one that proved no host key, a password
1861
+ * login). `false` never seals. Only `true` is a guarantee (a relay can strip the ServerHello feature `'auto'` rests
1862
+ * on); pin the host (`expectHostKey` / `knownHosts`) as well, since the exchange authenticates the key the host proved.
1863
+ */
1864
+ sealSession?: false | 'auto' | true;
1842
1865
  }
1843
1866
 
1844
1867
  /** What a login signature can be bound to (wsh #119). */
@@ -1889,6 +1912,11 @@ export interface WshOpenSessionOptions {
1889
1912
  * advertises `exec-pipes`. `'pty'` or omitted: the host's native mode.
1890
1913
  */
1891
1914
  stdio?: 'pty' | 'pipes';
1915
+ /**
1916
+ * #121: which of the host's execution targets this channel runs on (see {@link WshClient.listTargets}). Throws before sending
1917
+ * anything unless the host advertises `targets`. Omitted: the host's own default, as before.
1918
+ */
1919
+ target?: string;
1892
1920
  }
1893
1921
 
1894
1922
  /**
@@ -1978,6 +2006,8 @@ export interface WshExecOptions extends WshHostKeyOptions {
1978
2006
  * `'pipes'` throws if the host lacks `exec-pipes`; `'pty'` never asks for pipes.
1979
2007
  */
1980
2008
  stdio?: 'pty' | 'pipes';
2009
+ /** See {@link WshOpenSessionOptions.target}. */
2010
+ target?: string;
1981
2011
  }
1982
2012
 
1983
2013
  /** Result from WshClient.exec(). */
@@ -2120,7 +2150,22 @@ export interface WshFileOperationResult {
2120
2150
  * reverse mode (client registers as a peer for incoming connections).
2121
2151
  */
2122
2152
  /** Options for `openUnix` / `openEndpoint` / `openTcp`. */
2123
- export interface WshGatewayOpenOptions { signal?: AbortSignal; timeoutMs?: number }
2153
+ export interface WshGatewayOpenOptions {
2154
+ signal?: AbortSignal;
2155
+ timeoutMs?: number;
2156
+ /** `openEndpoint` only (#121): the host's execution target whose endpoint this is. Needs the `targets` feature. */
2157
+ target?: string;
2158
+ }
2159
+
2160
+ /** One execution target a host shows this key (`ListTargets` / `TargetList`, #121). */
2161
+ export interface WshTargetInfo {
2162
+ /** What to pass as `target`. */
2163
+ name: string;
2164
+ /** A human line about the target; not for parsing. */
2165
+ description?: string;
2166
+ /** What the caller can do there: any of `exec`, `pty`, `file`, `endpoint` (a hint; the host decides on each request). */
2167
+ capabilities: string[];
2168
+ }
2124
2169
 
2125
2170
  /** One gateway connection as web streams with backpressure (credit-based flow control when both ends offer `gateway-credit`). */
2126
2171
  export interface WshGatewayDuplex {
@@ -2235,6 +2280,9 @@ export class WshClient {
2235
2280
  */
2236
2281
  readonly hostKey: WshHostKey | null;
2237
2282
 
2283
+ /** Is this whole session sealed end to end (`connect(url, { sealSession })`, #155)? */
2284
+ readonly sessionSealed: boolean;
2285
+
2238
2286
  /** Default `onHostKey` for `connect()` (a per-call option wins). */
2239
2287
  onHostKey: ((hostKey: WshHostKey) => boolean | void | Promise<boolean | void>) | null;
2240
2288
 
@@ -2404,6 +2452,18 @@ export class WshClient {
2404
2452
  */
2405
2453
  listPeers(timeout?: number): Promise<WshPeerInfo[]>;
2406
2454
 
2455
+ /**
2456
+ * The execution targets this connection may use (#121): what the host decides to show THIS key. Pass a `name` as `target` to
2457
+ * `openSession`, `exec`, `fileOperation` or `openEndpoint`. Throws if the host does not advertise `targets`.
2458
+ */
2459
+ listTargets(timeout?: number): Promise<WshTargetInfo[]>;
2460
+
2461
+ /**
2462
+ * One structured file operation (`FileOp`), the raw wire-shaped result. `opts.target` (#121) names the execution target whose
2463
+ * files these are (needs `targets`; such a request is never sent over the `wsh-fs` rpc, which is not per target).
2464
+ */
2465
+ fileOperation(op: string, path: string, opts?: { offset?: number; length?: number; data?: Uint8Array | string; newPath?: string; target?: string }, timeout?: number): Promise<WshFileOperationResult>;
2466
+
2407
2467
  /**
2408
2468
  * Initiate a reverse connection to a registered peer.
2409
2469
  */
package/src/index.mjs CHANGED
@@ -35,6 +35,7 @@ export {
35
35
  nodeAnnounce, nodeRedirect,
36
36
  sessionGrant, sessionRevoke,
37
37
  fileOp, fileResult, fileChunk,
38
+ listTargets, targetList,
38
39
  authorizedKeyAdd, authorizedKeyResult,
39
40
  policyEval, policyResult, policyUpdate,
40
41
  terminalConfig,
@@ -75,7 +76,7 @@ export {
75
76
  // Session + Client
76
77
  export { WshSession } from './session.mjs';
77
78
  export { WshVirtualSessionBackend, normalizeSessionData } from './virtual-session.mjs';
78
- export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './client.mjs';
79
+ export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, TARGETS_FEATURE } from './client.mjs';
79
80
  // Gateway forwarding (unix sockets, named endpoints, flow control) -- wsh #120, #123
80
81
  export { GatewayError } from './gateway-client.mjs';
81
82
  export { GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from './gateway-channel.mjs';
@@ -86,6 +86,14 @@ export interface WshMemoryHostOptions {
86
86
  sealSession?: false | 'offer' | 'require';
87
87
  /** #163: told once per connection this host turned away (a key it does not allow, a plain client on a host that requires a sealed session, ...), with a stable reason code. */
88
88
  onRefused?: WshOnRefused;
89
+ /**
90
+ * #121: execution targets, each with its own `exec`, `pty`, `fs` and `endpoints` and an `authorize(who, { target, kind })`.
91
+ * A client names one in `Open`, `FileOp` or `OpenEndpoint` and lists what it may use with `listTargets()`. Off unless given:
92
+ * the host then advertises no `targets` and refuses a request that names one.
93
+ */
94
+ targets?: Record<string, import('./host.js').WshTargetOptions>;
95
+ /** With `targets`: an `Open`, `FileOp` or `OpenEndpoint` that names no target is refused (nothing runs on the host itself). */
96
+ requireTarget?: boolean;
89
97
  onLog?: (line: string) => void;
90
98
  }
91
99
 
@@ -172,6 +172,10 @@ function createRegistry(sessions, log) {
172
172
  * backpressure) and `who` is the authenticated `{ username, fingerprint }`, so the handler can authorise per call:
173
173
  * throw synchronously to refuse, or give `{ open, authorize(who) }`. Only the names listed here exist (an allow-list by
174
174
  * construction); nothing else of the gateway (TCP, DNS, unix sockets) is on in memory.
175
+ * @param {Record<string, { description?: string, authorize?: Function, exec?: Function | { run: Function }, pty?: object, fs?: object, endpoints?: object }>} [options.targets]
176
+ * Execution targets (#121), as for `createWshServer`: each with its own `exec`, `pty`, `fs` and `endpoints` (the injected
177
+ * forms only: there is no shell or directory here) and an `authorize(who, { target, kind })`. Off unless given.
178
+ * @param {boolean} [options.requireTarget=false] - With `targets`: a request that names no target is refused. As for `createWshServer`.
175
179
  * @param {number} [options.bindTimeoutMs=3000]
176
180
  * @param {number} [options.connectionTtlMs=0] - End each authenticated connection this long after login; advertised as
177
181
  * `AuthOk.ttl` in whole seconds (#125). 0 = never.
@@ -190,7 +194,7 @@ function createRegistry(sessions, log) {
190
194
  * @param {(line: string) => void} [options.onLog]
191
195
  */
192
196
  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, sealSession = false, onLog = () => {},
193
- onShare, onRefused } = {}) {
197
+ onShare, onRefused, targets, requireTarget } = {}) {
194
198
  validateOnShare(onShare, 'createMemoryHost');
195
199
  validateOnRefused(onRefused, 'createMemoryHost');
196
200
  if (!Number.isFinite(connectionTtlMs) || connectionTtlMs < 0) throw new TypeError('createMemoryHost: connectionTtlMs must be a non-negative number');
@@ -209,7 +213,7 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
209
213
  if (typeof dataStreams !== 'boolean') throw new TypeError('createMemoryHost: dataStreams must be true or false');
210
214
  const rpcHost = rpc === undefined || rpc === null ? null : createRpcTable(rpc, rpcMaxMessageBytes, rpcMaxInflight);
211
215
  const registry = sessions === undefined || sessions === null || sessions === false ? null : createRegistry(sessions, onLog);
212
- const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost } = resolveBackends({ exec, pty, fs, mcp });
216
+ const { execRunner, execOptions, pty: ptyBackend, files, mcp: mcpHost, targets: targetTable, requireTarget: mustHaveTarget } = resolveBackends({ exec, pty, fs, mcp, targets, requireTarget });
213
217
  const hostKeyReady = hostKey === undefined || hostKey === null || hostKey === false ? Promise.resolve(null) : resolveHostKey(hostKey, 'createMemoryHost: hostKey');
214
218
  const rl = auth?.rateLimit ?? {};
215
219
  const rateLimit = {
@@ -220,11 +224,14 @@ export function createMemoryHost({ auth, exec, pty, fs, hostKey, mcp, extensions
220
224
  const methods = authMethods(auth);
221
225
  // Named virtual endpoints: a gateway with no TCP, DNS or unix sockets that answers only `OpenEndpoint`, built from
222
226
  // the browser-safe core (`server/gateway-core.mjs`), so a page can have it.
223
- const gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
227
+ let gatewayCfg = endpoints === undefined || endpoints === null ? null : normalizeEndpointGateway({ endpoints });
228
+ // A target's own endpoints (#121) need the endpoints-only gateway too, even when the host has none of its own.
229
+ if (targetTable && [...targetTable.values()].some((t) => t.endpoints)) gatewayCfg = { ...(gatewayCfg ?? normalizeEndpointGateway({})), targetEndpoints: true };
224
230
 
225
231
  const ready = Promise.all([buildAuthorizer(auth), hostKeyReady]).then(([authorize, hostKeyResolved]) => createConnectionFactory({
226
232
  authorize, execRunner, execOptions, pty: ptyBackend, files, bindTimeoutMs, connectionTtlMs, requireChannelBinding, sealSession, log: onLog,
227
233
  methods, hostKey: hostKeyResolved, rateLimit, extensions, mcp: mcpHost, rpc: rpcHost, onShare, onRefused,
234
+ targets: targetTable, requireTarget: mustHaveTarget,
228
235
  gateway: gatewayCfg, createGatewaySession: gatewayCfg ? createEndpointGatewaySession : undefined, sessions: registry, relay: null,
229
236
  }));
230
237
  ready.catch(() => {});
@@ -162,6 +162,10 @@ export const MSG = Object.freeze({
162
162
  SHARE_OFFER: 0xa8,
163
163
  SHARE_REQUEST: 0xa9,
164
164
  SHARE_REPLY: 0xaa,
165
+
166
+ // Targets
167
+ LIST_TARGETS: 0xab,
168
+ TARGET_LIST: 0xac,
165
169
  });
166
170
 
167
171
  // Reverse lookup: number → name
@@ -252,13 +256,14 @@ export function authFail({ reason } = {}) {
252
256
  };
253
257
  }
254
258
 
255
- export function open({ kind, command, cols, rows, env, stdio } = {}) {
259
+ export function open({ kind, command, cols, rows, env, stdio, target } = {}) {
256
260
  const msg = { type: MSG.OPEN, kind };
257
261
  if (command !== undefined) msg.command = command;
258
262
  if (cols !== undefined) msg.cols = cols;
259
263
  if (rows !== undefined) msg.rows = rows;
260
264
  if (env !== undefined) msg.env = env;
261
265
  if (stdio !== undefined) msg.stdio = stdio;
266
+ if (target !== undefined) msg.target = target;
262
267
  return msg;
263
268
  }
264
269
 
@@ -595,12 +600,10 @@ export function openUnix({ gatewayId, path } = {}) {
595
600
  };
596
601
  }
597
602
 
598
- export function openEndpoint({ gatewayId, name } = {}) {
599
- return {
600
- type: MSG.OPEN_ENDPOINT,
601
- gateway_id: gatewayId,
602
- name,
603
- };
603
+ export function openEndpoint({ gatewayId, name, target } = {}) {
604
+ const msg = { type: MSG.OPEN_ENDPOINT, gateway_id: gatewayId, name };
605
+ if (target !== undefined) msg.target = target;
606
+ return msg;
604
607
  }
605
608
 
606
609
  export function listenUnix({ listenerId, path, replace } = {}) {
@@ -921,10 +924,11 @@ export function sessionRevoke({ sessionId, principal, reason } = {}) {
921
924
  return msg;
922
925
  }
923
926
 
924
- export function fileOp({ channelId, op, path, offset, length } = {}) {
927
+ export function fileOp({ channelId, op, path, offset, length, target } = {}) {
925
928
  const msg = { type: MSG.FILE_OP, channel_id: channelId, op, path };
926
929
  if (offset !== undefined) msg.offset = offset;
927
930
  if (length !== undefined) msg.length = length;
931
+ if (target !== undefined) msg.target = target;
928
932
  return msg;
929
933
  }
930
934
 
@@ -1023,6 +1027,17 @@ export function shareReply({ requestId, ok, errno, message, attr = {}, entries =
1023
1027
  return msg;
1024
1028
  }
1025
1029
 
1030
+ export function listTargets() {
1031
+ return { type: MSG.LIST_TARGETS };
1032
+ }
1033
+
1034
+ export function targetList({ targets } = {}) {
1035
+ return {
1036
+ type: MSG.TARGET_LIST,
1037
+ targets,
1038
+ };
1039
+ }
1040
+
1026
1041
  // ── Relay forwarding ─────────────────────────────────────────────────
1027
1042
 
1028
1043
  // Message types a relay may forward inside a RelayForward wrapper.
@@ -97,6 +97,7 @@ export function createReverseHostWith({
97
97
  if (typeof requireOperatorProof !== 'boolean') throw new TypeError('createReverseHost: requireOperatorProof must be a boolean');
98
98
  if (requireOperatorProof && e2e === false) throw new TypeError('createReverseHost: requireOperatorProof seals the bridge, which needs e2e (do not set e2e: false)');
99
99
  if (requireOperatorProof && !reportFeatures) throw new TypeError('createReverseHost: requireOperatorProof needs reportFeatures (the operator learns "e2e-sealed" from ReverseAccept.features)');
100
+ if (backends.targets) throw new TypeError('createReverseHost: targets are not supported by a reverse host (a bridged operator reaches the one machine behind it); use createWshServer or createMemoryHost');
100
101
  if (!url) throw new TypeError('createReverseHost: url is required');
101
102
  if (!username) throw new TypeError('createReverseHost: username is required');
102
103
  if (!keyPair) throw new TypeError('createReverseHost: keyPair is required (the relay keys peers by fingerprint)');
@@ -10,13 +10,10 @@
10
10
 
11
11
  import { spawnRunner } from './exec.mjs';
12
12
  import { createFileAccess } from './fs.mjs';
13
- import { resolveBackends } from '../host-backends.mjs';
13
+ import { resolveBackends, normalizeTargets } from '../host-backends.mjs';
14
14
 
15
- /**
16
- * @param {{ exec?: true | object | Function, pty?: object, fs?: object, mcp?: object }} options
17
- * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null }}
18
- */
19
- export function buildBackends({ exec, pty, fs, mcp } = {}) {
15
+ /** The backends of one host (or one target) from `exec`, `pty`, `fs`, `mcp`, with the Node forms (`exec: true`, `fs: { root }`). */
16
+ function buildOwnBackends({ exec, pty, fs, mcp } = {}) {
20
17
  let hostExec = exec;
21
18
  if (exec && typeof exec !== 'function') {
22
19
  const execOptions = exec === true ? {} : exec;
@@ -24,3 +21,11 @@ export function buildBackends({ exec, pty, fs, mcp } = {}) {
24
21
  }
25
22
  return resolveBackends({ exec: hostExec, pty, fs: fs && typeof fs.root === 'string' ? createFileAccess(fs) : fs, mcp });
26
23
  }
24
+
25
+ /**
26
+ * @param {{ exec?: true | object | Function, pty?: object, fs?: object, mcp?: object, targets?: object, requireTarget?: boolean }} options
27
+ * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null, targets: Map<string, object> | null, requireTarget: boolean }}
28
+ */
29
+ export function buildBackends({ exec, pty, fs, mcp, targets, requireTarget } = {}) {
30
+ return { ...buildOwnBackends({ exec, pty, fs, mcp }), ...normalizeTargets(targets, requireTarget, buildOwnBackends, 'createWshServer') };
31
+ }
@@ -19,12 +19,14 @@ import {
19
19
  MSG, serverHello, challenge, authOk, authFail, openOk, openFail, sessionData,
20
20
  exit as exitMsg, close as closeMsg, encryptedFrame as encryptedFrameMsg, pong, fileResult, fileChunk, mcpTools, mcpResult,
21
21
  presence as presenceMsg, error as errorMsg, sessionList, detachOk, detachFail, reversePeers, reverseReject,
22
+ targetList as targetListMsg,
22
23
  } from '../messages.gen.mjs';
23
24
  import {
24
25
  generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
25
26
  } from '../auth.mjs';
26
27
  import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
27
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from '../features.mjs';
28
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE, TARGETS_FEATURE } from '../features.mjs';
29
+ import { TARGET_NAME_RE } from '../host-backends.mjs';
28
30
  import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
29
31
  import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
30
32
  import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
@@ -40,10 +42,7 @@ import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMess
40
42
  import { SHARES_FEATURE, createShareSession } from '../shares.mjs';
41
43
 
42
44
  export const STREAM_ANNOUNCE = 'stream-announce';
43
- /** Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the connection's session id). */
44
- export const SESSION_SEAL_FEATURE = 'e2e-session';
45
- /** Host feature: this host serves nothing on a session that is not sealed. */
46
- export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
45
+ export { SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE };
47
46
 
48
47
  /**
49
48
  * The features a host built from `cfg` advertises (`ServerHello.features`, minus the host-key proof).
@@ -56,6 +55,12 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
56
55
  if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
57
56
  if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
58
57
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
58
+ // Execution targets (#121): `Open`, `FileOp` and `OpenEndpoint` take `target`, and `ListTargets` is answered. A target with files is
59
+ // reached over FileOp, so the file features are stated for it too (the host's own may have none).
60
+ if (cfg.targets) {
61
+ features.push(TARGETS_FEATURE);
62
+ if (!cfg.files && [...cfg.targets.values()].some((t) => t.files)) features.push('file-transfer', 'file-write', 'file-rename');
63
+ }
59
64
  if (cfg.onShare) features.push(SHARES_FEATURE); // #159: this host can use folders the operator's client offers
60
65
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
61
66
  // client-opened streams: over a relay bridge.
@@ -131,6 +136,17 @@ export function createConnectionFactory(cfg) {
131
136
  // What a client may put in `Open.env` (#126): an allow-list unless the host says otherwise.
132
137
  const execEnv = clientEnvFilter(cfg.execOptions?.clientEnv);
133
138
  const ptyEnv = clientEnvFilter(cfg.pty?.clientEnv);
139
+ // Execution targets (#121): each has its own backends (and its own `clientEnv` rules). A request that names no target uses
140
+ // the host's own, unless `requireTarget` says nothing may run on the host itself.
141
+ /** @type {Map<string, object> | null} */
142
+ const targetTable = cfg.targets && cfg.targets.size
143
+ ? new Map([...cfg.targets].map(([name, spec]) => [name, { ...spec, execEnv: clientEnvFilter(spec.execOptions?.clientEnv), ptyEnv: clientEnvFilter(spec.pty?.clientEnv) }]))
144
+ : null;
145
+ const requireTarget = !!targetTable && !!cfg.requireTarget;
146
+ const ownBackends = { execRunner: cfg.execRunner, execOptions: cfg.execOptions, execEnv, pty: cfg.pty, ptyEnv, files: cfg.files, ownHost: true };
147
+ /** One answer for a target that does not exist and for one the caller may not use: the reply does not say which targets exist. */
148
+ const NO_SUCH_TARGET = 'no such target';
149
+ const targetCapabilities = (spec) => [...(spec.execRunner ? ['exec'] : []), ...(spec.pty ? ['pty'] : []), ...(spec.files ? ['file'] : []), ...(spec.endpoints ? ['endpoint'] : [])];
134
150
 
135
151
  /**
136
152
  * Attach one connection. Two shapes:
@@ -179,7 +195,13 @@ export function createConnectionFactory(cfg) {
179
195
  // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
180
196
  if (cfg.gateway && typeof cfg.createGatewaySession !== 'function') throw new TypeError('createConnectionFactory: gateway needs createGatewaySession (only @johnhenry/wsh/server provides one)');
181
197
  const gateway = cfg.gateway
182
- ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }), datagrams })
198
+ ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, {
199
+ who: () => ({ username: state.username, fingerprint: state.fingerprint }),
200
+ datagrams,
201
+ // #121: a named target's own endpoints, once `authorize` has let the caller onto it
202
+ target: async (name) => { const r = await resolveTarget(name, 'endpoint'); return r.refuse ? { refuse: r.refuse } : { endpoints: r.b.endpoints ?? null }; },
203
+ requireTarget: () => requireTarget,
204
+ })
183
205
  : null;
184
206
 
185
207
  // Operator-side shared folders (#159): created with the connection, used only after the client's ShareOffer.
@@ -325,6 +347,7 @@ export function createConnectionFactory(cfg) {
325
347
  case MSG.RESUME: return handleAttach(m, true);
326
348
  case MSG.DETACH: return handleDetach(m);
327
349
  case MSG.SESSION_LIST_REQUEST: return handleSessionList();
350
+ case MSG.LIST_TARGETS: return handleListTargets();
328
351
  case MSG.MCP_DISCOVER: return handleMcpDiscover();
329
352
  // Not awaited: the handler chain is serial, and a slow tool must not hold up
330
353
  // the next call (or a Close) behind it.
@@ -672,13 +695,55 @@ export function createConnectionFactory(cfg) {
672
695
 
673
696
  // ── Open ──────────────────────────────────────────────────────────
674
697
 
675
- function handleOpen(m) {
698
+ /**
699
+ * The backends a request is served by (#121): the host's own when it names no target (and `requireTarget` is off), else the
700
+ * target's, once the host knows the name and its `authorize(who, { target, kind })` lets this caller on. `{ refuse }`
701
+ * otherwise, never a fallback to the host's own: a request for somewhere else is not run here.
702
+ * @returns {Promise<{ b: object } | { refuse: string }>}
703
+ */
704
+ async function resolveTarget(target, kind) {
705
+ if (target === undefined || target === null) return requireTarget ? { refuse: 'a target is required' } : { b: ownBackends };
706
+ if (!targetTable) return { refuse: 'this host has no targets' };
707
+ const spec = typeof target === 'string' && TARGET_NAME_RE.test(target) ? targetTable.get(target) : undefined;
708
+ if (!spec) return { refuse: NO_SUCH_TARGET };
709
+ if (spec.authorize) {
710
+ let allowed = false;
711
+ try { allowed = (await spec.authorize({ username: state.username, fingerprint: state.fingerprint }, { target, kind })) === true; } catch (e) { log(`target ${target} authorize threw: ${e.message}`); }
712
+ if (!allowed) {
713
+ log(`target ${target} refused for ${state.username ?? '?'} (${kind})`);
714
+ return { refuse: NO_SUCH_TARGET };
715
+ }
716
+ }
717
+ return { b: spec };
718
+ }
719
+
720
+ /** `ListTargets`: the targets this caller may use, as the host shows them. */
721
+ async function handleListTargets() {
722
+ if (!targetTable) return send(errorMsg({ code: 3, message: 'this host has no targets' }));
723
+ const out = [];
724
+ for (const [name, spec] of targetTable) {
725
+ const r = await resolveTarget(name, 'list');
726
+ if (r.refuse) continue;
727
+ out.push({ name, ...(spec.description !== undefined ? { description: spec.description } : {}), capabilities: targetCapabilities(spec) });
728
+ }
729
+ return send(targetListMsg({ targets: out }));
730
+ }
731
+
732
+ async function handleOpen(m) {
676
733
  if (channels.size >= MAX_CHANNELS) return send(openFail({ reason: 'too many open channels' }));
734
+ const target = m.target ?? undefined;
677
735
  switch (m.kind) {
678
- case 'exec': return openExec(m);
679
- case 'pty': return openPty(m);
680
- case 'file': return openFile(m);
681
- case 'rpc': return openRpc(m);
736
+ case 'exec': case 'pty': case 'file': {
737
+ const r = await resolveTarget(target, m.kind);
738
+ if (r.refuse) return send(openFail({ reason: r.refuse }));
739
+ if (m.kind === 'exec') return openExec(m, r.b, target);
740
+ return m.kind === 'pty' ? openPty(m, r.b, target) : openFile(m, r.b);
741
+ }
742
+ case 'rpc':
743
+ // rpc channels (`wsh-fs`, `wsh-host`, `mcp`) are the host's own, not per target.
744
+ if (target !== undefined) return send(openFail({ reason: 'rpc channels do not take a target' }));
745
+ if (requireTarget) return send(openFail({ reason: 'a target is required' }));
746
+ return openRpc(m);
682
747
  default: return send(openFail({ reason: `kind "${m.kind}" is not supported by this server` }));
683
748
  }
684
749
  }
@@ -801,8 +866,8 @@ export function createConnectionFactory(cfg) {
801
866
  return send(sessionList({ sessions }));
802
867
  }
803
868
 
804
- async function openExec(m) {
805
- if (!cfg.execRunner) return send(openFail({ reason: 'exec is not enabled on this server' }));
869
+ async function openExec(m, b, target) {
870
+ if (!b.execRunner) return send(openFail({ reason: `exec is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
806
871
  const command = String(m.command ?? '').trim();
807
872
  if (!command) return send(openFail({ reason: 'command is required for kind "exec"' }));
808
873
 
@@ -850,7 +915,7 @@ export function createConnectionFactory(cfg) {
850
915
  else ch.input = (d) => { for (const cb of inputCbs) cb(d); };
851
916
 
852
917
  let timer = null;
853
- if (cfg.execOptions.timeoutMs > 0) timer = setTimeout(() => abort.abort(), cfg.execOptions.timeoutMs);
918
+ if (b.execOptions.timeoutMs > 0) timer = setTimeout(() => abort.abort(), b.execOptions.timeoutMs);
854
919
 
855
920
  // Output to the opening connection's data stream (held until the client has opened it).
856
921
  const toStream = (bytes) => {
@@ -901,7 +966,9 @@ export function createConnectionFactory(cfg) {
901
966
 
902
967
  const io = {
903
968
  user: state.username,
904
- env: execEnv(m.env),
969
+ // Which execution target this command runs on (#121); undefined on the host's own.
970
+ target,
971
+ env: b.execEnv(m.env),
905
972
  cols: m.cols || 80,
906
973
  rows: m.rows || 24,
907
974
  signal: abort.signal,
@@ -928,7 +995,7 @@ export function createConnectionFactory(cfg) {
928
995
 
929
996
  async function runExec() {
930
997
  let code;
931
- try { code = await cfg.execRunner(command, io); } catch (e) {
998
+ try { code = await b.execRunner(command, io); } catch (e) {
932
999
  await io.write(`wsh: ${e.message}\n`);
933
1000
  code = 1;
934
1001
  }
@@ -993,18 +1060,20 @@ export function createConnectionFactory(cfg) {
993
1060
  log(`rpc channel ${channelId}: ${protocol}`);
994
1061
  }
995
1062
 
996
- async function openPty(m) {
997
- if (!cfg.pty) return send(openFail({ reason: 'pty is not enabled on this server' }));
1063
+ async function openPty(m, b, target) {
1064
+ if (!b.pty) return send(openFail({ reason: `pty is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
998
1065
  const channelId = ++state.nextChannel;
999
1066
  const cols = m.cols || 80;
1000
1067
  const rows = m.rows || 24;
1001
- const p = cfg.pty;
1068
+ const p = b.pty;
1002
1069
  let proc;
1003
1070
  try {
1004
1071
  const args = m.command ? ['-c', String(m.command)] : [];
1005
1072
  proc = p.spawn(p.shell, args, {
1006
1073
  name: p.term, cols, rows, cwd: p.cwd,
1007
- env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...ptyEnv(m.env) },
1074
+ env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...b.ptyEnv(m.env) },
1075
+ // Which execution target this shell is for (#121); absent on the host's own.
1076
+ ...(target !== undefined ? { target } : {}),
1008
1077
  });
1009
1078
  } catch (e) {
1010
1079
  return send(openFail({ reason: `pty spawn failed: ${e.message}` }));
@@ -1048,8 +1117,9 @@ export function createConnectionFactory(cfg) {
1048
1117
  log(`pty channel ${channelId} opened (${cols}x${rows})`);
1049
1118
  }
1050
1119
 
1051
- async function openFile(m) {
1052
- if (!cfg.files) return send(openFail({ reason: 'file access is not enabled on this server' }));
1120
+ async function openFile(m, b) {
1121
+ const files = b.files;
1122
+ if (!files) return send(openFail({ reason: `file access is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
1053
1123
  const spec = String(m.command ?? '');
1054
1124
  const mm = spec.match(/^(upload|download):(.*)$/s);
1055
1125
  if (!mm) return send(openFail({ reason: 'file channel expects upload:<path> or download:<path>' }));
@@ -1058,7 +1128,7 @@ export function createConnectionFactory(cfg) {
1058
1128
 
1059
1129
  if (direction === 'download') {
1060
1130
  let data;
1061
- try { data = await cfg.files.readWhole(filePath); } catch (e) { return send(openFail({ reason: e.message })); }
1131
+ try { data = await files.readWhole(filePath); } catch (e) { return send(openFail({ reason: e.message })); }
1062
1132
  let cancelled = false;
1063
1133
  channels.set(channelId, { kill: () => { if (channels.delete(channelId)) { cancelled = true; log(`download ${filePath}: closed before completion`); } } });
1064
1134
  await send(openOk({ channelId, dataMode: 'virtual', capabilities: [] }));
@@ -1084,13 +1154,13 @@ export function createConnectionFactory(cfg) {
1084
1154
  ch.chunk = async (c) => {
1085
1155
  if (ch.failed) return;
1086
1156
  const total = Number(c.total_size ?? 0);
1087
- if (total > cfg.files.maxFileBytes) { ch.failed = true; return done(1, `refused: ${total} B exceeds ${cfg.files.maxFileBytes} B`); }
1157
+ if (total > files.maxFileBytes) { ch.failed = true; return done(1, `refused: ${total} B exceeds ${files.maxFileBytes} B`); }
1088
1158
  ch.buf ??= new Uint8Array(total);
1089
1159
  const data = c.data instanceof Uint8Array ? c.data : new Uint8Array(0);
1090
1160
  if (c.offset + data.byteLength > ch.buf.byteLength) { ch.failed = true; return done(1, 'chunk past total_size'); }
1091
1161
  ch.buf.set(data, c.offset);
1092
1162
  if (c.is_final) {
1093
- try { await cfg.files.writeWhole(filePath, ch.buf); } catch (e) { ch.failed = true; return done(1, e.message); }
1163
+ try { await files.writeWhole(filePath, ch.buf); } catch (e) { ch.failed = true; return done(1, e.message); }
1094
1164
  return done(0, `stored ${ch.buf.byteLength} B`);
1095
1165
  }
1096
1166
  };
@@ -1099,10 +1169,14 @@ export function createConnectionFactory(cfg) {
1099
1169
 
1100
1170
  async function handleFileOp(m) {
1101
1171
  const channelId = m.channel_id;
1102
- if (!cfg.files) return send(fileResult({ channelId, success: false, errorMessage: 'file access is not enabled on this server' }));
1103
- if (m.op === 'write' || m.op === 'rename') return startPayloadOp(m);
1172
+ const target = m.target ?? undefined;
1173
+ const r0 = await resolveTarget(target, 'file');
1174
+ if (r0.refuse) return send(fileResult({ channelId, success: false, errorMessage: r0.refuse }));
1175
+ const files = r0.b.files;
1176
+ if (!files) return send(fileResult({ channelId, success: false, errorMessage: `file access is not enabled ${r0.b.ownHost ? 'on this server' : 'for this target'}` }));
1177
+ if (m.op === 'write' || m.op === 'rename') return startPayloadOp(m, files);
1104
1178
  try {
1105
- const r = await cfg.files.operate(m.op, m.path, { offset: m.offset, length: m.length });
1179
+ const r = await files.operate(m.op, m.path, { offset: m.offset, length: m.length });
1106
1180
  return send(fileResult({ channelId, success: true, metadata: r.metadata ?? {}, entries: r.entries ?? [] }));
1107
1181
  } catch (e) {
1108
1182
  const message = e.wsh ? e.message : (e.code === 'ENOENT' ? 'no such file or directory' : `${m.op} failed`);
@@ -1114,17 +1188,17 @@ export function createConnectionFactory(cfg) {
1114
1188
  // write / rename = FileOp then FileChunk frame(s) on the same channel id
1115
1189
  // (rename's payload is the UTF-8 destination path); one FileResult once
1116
1190
  // the last chunk lands (see WshClient.fileOperation).
1117
- async function startPayloadOp(m) {
1191
+ async function startPayloadOp(m, files) {
1118
1192
  const channelId = m.channel_id;
1119
1193
  const failWrite = (errorMessage) => send(fileResult({ channelId, success: false, errorMessage }));
1120
1194
  const rename = m.op === 'rename';
1121
1195
  const length = Number(m.length);
1122
1196
  if (!Number.isSafeInteger(length) || length < 0) return failWrite(`${m.op} needs a length`);
1123
- const limit = rename ? MAX_RENAME_PATH_BYTES : cfg.files.maxFileBytes;
1197
+ const limit = rename ? MAX_RENAME_PATH_BYTES : files.maxFileBytes;
1124
1198
  if (length > limit) return failWrite(`${m.op} payload of ${length} bytes exceeds the ${limit} byte limit`);
1125
1199
  if (channels.has(channelId) || fileWrites.has(channelId)) return failWrite('channel id already in use');
1126
1200
  if (fileWrites.size >= MAX_PENDING_WRITES) return failWrite('too many writes in flight');
1127
- const w = { rename, path: m.path, offset: m.offset, length, buf: new Uint8Array(length), next: 0, timer: null };
1201
+ const w = { rename, files, path: m.path, offset: m.offset, length, buf: new Uint8Array(length), next: 0, timer: null };
1128
1202
  const arm = () => {
1129
1203
  clearTimeout(w.timer);
1130
1204
  w.timer = setTimeout(() => {
@@ -1156,8 +1230,8 @@ export function createConnectionFactory(cfg) {
1156
1230
  if (w.next !== w.length) return send(fileResult({ channelId, success: false, errorMessage: 'payload ended short of the declared length' }));
1157
1231
  try {
1158
1232
  const r = w.rename
1159
- ? await cfg.files.operate('rename', w.path, { newPath: new TextDecoder('utf-8', { fatal: true }).decode(w.buf) })
1160
- : await cfg.files.operate('write', w.path, { offset: w.offset, data: w.buf });
1233
+ ? await w.files.operate('rename', w.path, { newPath: new TextDecoder('utf-8', { fatal: true }).decode(w.buf) })
1234
+ : await w.files.operate('write', w.path, { offset: w.offset, data: w.buf });
1161
1235
  return send(fileResult({ channelId, success: true, metadata: r.metadata ?? {} }));
1162
1236
  } catch (e) {
1163
1237
  const message = e.wsh ? e.message : (e.code === 'ENOENT' ? 'no such file or directory' : `${w.rename ? 'rename' : 'write'} failed`);
@@ -62,7 +62,7 @@ export function gatewayFeatures(cfg) {
62
62
  if (cfg.tcp || cfg.reverse) f.push('gateway');
63
63
  f.push(GATEWAY_CREDIT_FEATURE);
64
64
  if (cfg.unix) f.push('gateway-unix');
65
- if (cfg.endpoints) f.push('gateway-endpoints');
65
+ if (cfg.endpoints || cfg.targetEndpoints) f.push('gateway-endpoints');
66
66
  return f;
67
67
  }
68
68
 
@@ -104,7 +104,17 @@ export function createGatewayCore(cfg, send, log = () => {}, ctx = {}) {
104
104
  const id = m.gateway_id;
105
105
  if (!Number.isInteger(id) || typeof m.name !== 'string') return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenEndpoint');
106
106
  if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
107
- const ep = cfg.endpoints && ENDPOINT_NAME_RE.test(m.name) ? cfg.endpoints.get(m.name) : undefined;
107
+ // Execution targets (#121): a named target has its own endpoints, and the host decides (`ctx.target`) whether the caller
108
+ // may use it; the answer for a target that does not exist and one that is refused is the same. Without a target, the host's own.
109
+ let endpoints = cfg.endpoints;
110
+ if (m.target !== undefined && m.target !== null) {
111
+ const t = ctx.target ? await ctx.target(m.target) : { refuse: 'this host has no targets' };
112
+ if (t.refuse) return fail(id, GATEWAY_FAIL.POLICY_DENIED, t.refuse);
113
+ endpoints = t.endpoints;
114
+ } else if (ctx.requireTarget?.()) {
115
+ return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'a target is required');
116
+ }
117
+ const ep = endpoints && ENDPOINT_NAME_RE.test(m.name) ? endpoints.get(m.name) : undefined;
108
118
  if (!ep) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'no such endpoint');
109
119
  if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
110
120
  const who = ctx.who?.() ?? { username: null, fingerprint: null };
@@ -119,6 +129,8 @@ export function createGatewayCore(cfg, send, log = () => {}, ctx = {}) {
119
129
  const { readable, writable } = channel.streams();
120
130
  const duplex = {
121
131
  readable, writable, who,
132
+ /** The execution target this endpoint belongs to (#121); undefined for the host's own. */
133
+ target: m.target ?? undefined,
122
134
  /** Half-close: nothing more will be sent. */
123
135
  close: (reason) => channel.end(reason),
124
136
  /** Tear the connection down now. */