@johnhenry/wsh 0.42.0 → 0.44.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/client.mjs CHANGED
@@ -8,7 +8,7 @@
8
8
  * reverse mode (client registers as a peer for incoming connections).
9
9
  */
10
10
 
11
- import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from './features.mjs';
11
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, TARGETS_FEATURE, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_FEATURE } from './features.mjs';
12
12
  import { WebTransportTransport, normalizeWebTransportOptions } from './transport.mjs';
13
13
  import { clientChannelBinding, offeredKinds, TLS_EXPORTER_LABEL, TLS_EXPORTER_LENGTH } from './channel-binding.mjs';
14
14
  import { WebSocketTransport } from './transport-ws.mjs';
@@ -36,6 +36,7 @@ import {
36
36
  policyEval as policyEvalMsg, policyUpdate as policyUpdateMsg,
37
37
  detach as detachMsg,
38
38
  sessionListRequest as sessionListRequestMsg,
39
+ listTargets as listTargetsMsg,
39
40
  sessionGrant as sessionGrantMsg, sessionRevoke as sessionRevokeMsg,
40
41
  isRelayForwardable,
41
42
  } from './messages.mjs';
@@ -74,7 +75,16 @@ const DEFAULT_OPEN_TIMEOUT = 10_000; // ms
74
75
  const FS_RPC_OPS = new Set(['stat', 'list', 'read', 'write', 'mkdir', 'remove', 'rename']);
75
76
 
76
77
  // The feature strings live in features.mjs (a host names them without importing this file); re-exported here.
77
- export { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE };
78
+ export { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE, TARGETS_FEATURE };
79
+
80
+ /** `target` must be a non-empty string, and only a host that advertises `targets` may be sent one (#121). */
81
+ function assertTargetUsable(client, target, who) {
82
+ if (target === undefined) return;
83
+ if (typeof target !== 'string' || !target) throw new TypeError(`${who}: target must be a non-empty string`);
84
+ if (!client.hasFeature(TARGETS_FEATURE)) {
85
+ throw new Error(`${who}: this host does not advertise "${TARGETS_FEATURE}" (execution targets); it would run the request on its own default, or reject the unknown field -- it was not sent`);
86
+ }
87
+ }
78
88
 
79
89
  /** An `AbortError` for `signal`, with the signal's reason as `cause`. */
80
90
  function abortError(signal) {
@@ -825,10 +835,13 @@ export class WshClient {
825
835
  * Throws `RpcError` (`UNSUPPORTED_PROTOCOL`) before sending anything if the host does not advertise it.
826
836
  * @param {(session: WshSession) => void} [opts.attach] - Advanced: called synchronously the moment the data
827
837
  * stream is bound, before any received byte can be delivered (`openRpc` uses it to set `onData`).
838
+ * @param {string} [opts.target] - Which of the host's execution targets to run on (#121; see `listTargets()`).
839
+ * Throws before sending anything if the host does not advertise `targets`. Omitted: the host's own default.
828
840
  * @returns {Promise<WshSession>}
829
841
  */
830
- async openSession({ type = 'pty', command, protocol, cols = 80, rows = 24, env, timeout = DEFAULT_OPEN_TIMEOUT, primer = true, attach, stdio } = {}) {
842
+ async openSession({ type = 'pty', command, protocol, cols = 80, rows = 24, env, timeout = DEFAULT_OPEN_TIMEOUT, primer = true, attach, stdio, target } = {}) {
831
843
  this.#assertAuthenticated('openSession');
844
+ assertTargetUsable(this, target, 'openSession');
832
845
  if (stdio !== undefined && stdio !== 'pty' && stdio !== 'pipes') {
833
846
  throw new TypeError('openSession: stdio must be "pty" or "pipes"');
834
847
  }
@@ -845,7 +858,7 @@ export class WshClient {
845
858
  const requestedChannelId = this._nextChannelId();
846
859
 
847
860
  await this.#transport.sendControl(
848
- openMsg({ kind: type, command, cols, rows, env, stdio: stdio === 'pipes' ? 'pipes' : undefined })
861
+ openMsg({ kind: type, command, cols, rows, env, stdio: stdio === 'pipes' ? 'pipes' : undefined, target })
849
862
  );
850
863
 
851
864
  // Registered as a dedicated pending-open (not the generic
@@ -1188,10 +1201,11 @@ export class WshClient {
1188
1201
  * when the host advertises `exec-pipes` (no echo, stderr kept apart, EOF), else the host's native
1189
1202
  * mode; without `stdin`, the host's native mode (a PTY on the Rust server), exactly as before.
1190
1203
  * `'pipes'` throws if the host does not advertise `exec-pipes`; `'pty'` never asks for pipes.
1204
+ * @param {string} [opts.target] - The host's execution target to run on (#121; needs `targets`, see `openSession`).
1191
1205
  * @returns {Promise<{stdout: Uint8Array, exitCode: number, stderr?: Uint8Array}>} `stderr` is present
1192
1206
  * only when the command ran on pipes.
1193
1207
  */
1194
- static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, stdio, ...hostKeyOpts } = {}) {
1208
+ static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, stdio, target, ...hostKeyOpts } = {}) {
1195
1209
  if (stdin !== undefined) assertStdinSource(stdin);
1196
1210
  if (stdio !== undefined && stdio !== 'pipes' && stdio !== 'pty') throw new TypeError('exec: stdio must be "pipes" or "pty"');
1197
1211
  const client = new WshClient();
@@ -1206,7 +1220,7 @@ export class WshClient {
1206
1220
 
1207
1221
  // The first stdin byte (or the EOF itself) announces the data stream to a
1208
1222
  // legacy host, so the primer byte is only needed when there is no stdin.
1209
- const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false, stdio: piped ? 'pipes' : undefined });
1223
+ const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false, stdio: piped ? 'pipes' : undefined, target });
1210
1224
 
1211
1225
  await new Promise((resolve, reject) => {
1212
1226
  const timer = setTimeout(() => {
@@ -1385,6 +1399,22 @@ export class WshClient {
1385
1399
  return Promise.all(peers.map(async (peer) => ({ ...peer, verified: await verifyPeerInfoRecord(peer) })));
1386
1400
  }
1387
1401
 
1402
+ /**
1403
+ * The execution targets this connection may use (#121): what the host decides to show THIS key, in the host's order.
1404
+ * Each is `{ name, description?, capabilities }` (`capabilities` is a hint: any of `exec`, `pty`, `file`, `endpoint`);
1405
+ * pass `name` as `target` to `openSession`, `fileOperation` or `openEndpoint`. Throws if the host does not advertise `targets`.
1406
+ *
1407
+ * @param {number} [timeout=10000] - Timeout in ms
1408
+ * @returns {Promise<Array<{ name: string, description?: string, capabilities: string[] }>>}
1409
+ */
1410
+ async listTargets(timeout = DEFAULT_OPEN_TIMEOUT) {
1411
+ this.#assertAuthenticated('listTargets');
1412
+ if (!this.hasFeature(TARGETS_FEATURE)) throw new Error(`listTargets: this host does not advertise "${TARGETS_FEATURE}" (execution targets)`);
1413
+ await this.#transport.sendControl(listTargetsMsg());
1414
+ const response = await this.#waitForMessage([MSG.TARGET_LIST], timeout, 'Timed out waiting for the target list');
1415
+ return response.targets ?? [];
1416
+ }
1417
+
1388
1418
  /**
1389
1419
  * Initiate a reverse connection to a registered peer.
1390
1420
  *
@@ -2418,14 +2448,18 @@ export class WshClient {
2418
2448
  *
2419
2449
  * @param {string} op - Operation: 'stat', 'list', 'read', 'write', 'mkdir', 'remove', 'rename'
2420
2450
  * @param {string} path - File path
2421
- * @param {object} [opts] - Optional: offset, length for read; `data` (+ `offset`) for write; `newPath` for rename
2451
+ * @param {object} [opts] - Optional: offset, length for read; `data` (+ `offset`) for write; `newPath` for rename;
2452
+ * `target` (#121): the execution target whose files these are (needs a host that advertises `targets`; the
2453
+ * `wsh-fs` rpc is not per target, so a request with a target always goes over FileOp)
2422
2454
  * @param {number} [timeout=10000]
2423
2455
  * @returns {Promise<object>} FileResult response
2424
2456
  */
2425
2457
  async fileOperation(op, path, opts = {}, timeout = DEFAULT_OPEN_TIMEOUT) {
2426
2458
  this.#assertAuthenticated('fileOperation');
2459
+ assertTargetUsable(this, opts.target, 'fileOperation');
2460
+ const { target } = opts;
2427
2461
  // wsh #85: a host that serves the `wsh-fs` rpc protocol is preferred over the FileOp/FileResult control path.
2428
- if (this.preferRpcFiles && FS_RPC_OPS.has(op) && this.hasFeature(rpcProtocolFeature('wsh-fs'))) {
2462
+ if (target === undefined && this.preferRpcFiles && FS_RPC_OPS.has(op) && this.hasFeature(rpcProtocolFeature('wsh-fs'))) {
2429
2463
  let rpc = null;
2430
2464
  try { rpc = await this.#fsChannel(); } catch { /* fall back to FileOp */ }
2431
2465
  if (rpc) return this.#fileOperationRpc(rpc, op, path, opts, timeout);
@@ -2451,7 +2485,7 @@ export class WshClient {
2451
2485
  const result = this.#waitForMessage([MSG.FILE_RESULT], timeout, `Timed out waiting for file ${op} result`, byChannel);
2452
2486
  result.catch(() => {});
2453
2487
  await this.#transport.sendControl(fileOpMsg({
2454
- channelId, op, path, offset: op === 'write' ? opts.offset : undefined, length: data.byteLength,
2488
+ channelId, op, path, offset: op === 'write' ? opts.offset : undefined, length: data.byteLength, target,
2455
2489
  }));
2456
2490
  let off = 0;
2457
2491
  do {
@@ -2465,7 +2499,7 @@ export class WshClient {
2465
2499
  }
2466
2500
 
2467
2501
  await this.#transport.sendControl(
2468
- fileOpMsg({ channelId, op, path, offset: opts.offset, length: opts.length })
2502
+ fileOpMsg({ channelId, op, path, offset: opts.offset, length: opts.length, target })
2469
2503
  );
2470
2504
  return this.#waitForMessage(
2471
2505
  [MSG.FILE_RESULT],
package/src/features.mjs CHANGED
@@ -27,6 +27,13 @@ export const MCP_CANCEL_FEATURE = 'mcp-cancel';
27
27
  export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
28
28
  export const EXEC_PIPES_FEATURE = 'exec-pipes';
29
29
 
30
+ /**
31
+ * ServerHello feature (#121): this host serves several execution targets. `Open`, `FileOp` and `OpenEndpoint` take an optional
32
+ * `target`, and `ListTargets` is answered with `TargetList`. Negotiated rather than assumed: the Rust types deny unknown
33
+ * fields, so an older host rejects an `Open` that carries `target`.
34
+ */
35
+ export const TARGETS_FEATURE = 'targets';
36
+
30
37
  /**
31
38
  * Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the
32
39
  * connection's session id, then every message but the keepalive as an `EncryptedFrame` on channel 0).
@@ -145,11 +145,16 @@ export class GatewayConnections {
145
145
  return this.#open((id) => openUnixMsg({ gatewayId: id, path }), opts);
146
146
  }
147
147
 
148
- /** Open a named virtual endpoint of the host. */
148
+ /** Open a named virtual endpoint of the host (`opts.target`, #121: of one of its execution targets; needs `targets`). */
149
149
  async openEndpoint(name, opts) {
150
150
  this.#need('gateway-endpoints', 'named endpoints');
151
151
  if (typeof name !== 'string' || !name) throw new TypeError('openEndpoint: name must be a non-empty string');
152
- return this.#open((id) => openEndpointMsg({ gatewayId: id, name }), opts);
152
+ const target = opts?.target;
153
+ if (target !== undefined) {
154
+ if (typeof target !== 'string' || !target) throw new TypeError('openEndpoint: target must be a non-empty string');
155
+ this.#need('targets', 'execution targets');
156
+ }
157
+ return this.#open((id) => openEndpointMsg({ gatewayId: id, name, target }), opts);
153
158
  }
154
159
 
155
160
  /** Connect to host:port FROM THE HOST (the gateway's TCP egress, subject to the host's allow list). */
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { normalizePty } from './server/pty.mjs';
8
8
  import { createMcpHost } from './server/mcp.mjs';
9
+ import { normalizeEndpoints } from './server/gateway-core.mjs';
9
10
  import { DEFAULT_MAX_FILE_BYTES } from './server/constants.mjs';
10
11
  import { generateKeyPair, resolveSigner, fingerprint, exportPublicKeySSH, importPublicKeyRaw } from './auth.mjs';
11
12
 
@@ -51,11 +52,75 @@ export function normalizeFileBackend(fs, who = 'fs') {
51
52
  return files;
52
53
  }
53
54
 
55
+ /** A target's name: what a client puts in `Open.target`. */
56
+ export const TARGET_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
57
+ const TARGET_KEYS = ['description', 'authorize', 'exec', 'pty', 'fs', 'endpoints'];
58
+
59
+ /** A file backend that tells every call which target it serves (the last argument's `target`). */
60
+ function fileBackendForTarget(files, name) {
61
+ return {
62
+ maxFileBytes: files.maxFileBytes,
63
+ operate: (op, path, opts = {}) => files.operate(op, path, { ...opts, target: name }),
64
+ readWhole: (path, opts = {}) => files.readWhole(path, { ...opts, target: name }),
65
+ writeWhole: (path, data, opts = {}) => files.writeWhole(path, data, { ...opts, target: name }),
66
+ writeAt: (path, data, offset, opts = {}) => files.writeAt(path, data, offset, { ...opts, target: name }),
67
+ ...(files.openRange ? { openRange: (path, opts = {}) => files.openRange(path, { ...opts, target: name }) } : {}),
68
+ };
69
+ }
70
+
54
71
  /**
55
- * @param {{ exec?: Function | { run: Function }, pty?: { spawn: Function }, fs?: object, mcp?: object }} options
56
- * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null }}
72
+ * Validate the `targets` option (#121) and build one entry per target: its own exec / pty / files / endpoints
73
+ * (`buildOne({ exec, pty, fs })` makes the first three: `resolveBackends` in a browser, `buildBackends` in Node), the
74
+ * `authorize(who, { target, kind })` that decides who may use it, and a description. Nothing here is on by default: no
75
+ * `targets` option, no targets.
76
+ *
77
+ * @param {object | undefined} targets - `{ [name]: { description?, authorize?, exec?, pty?, fs?, endpoints? } }`
78
+ * @param {boolean | undefined} requireTarget
79
+ * @param {(spec: object) => { execRunner: Function | null, execOptions: object, pty: object | null, files: object | null }} buildOne
80
+ * @param {string} [who] - the host's name in error messages
81
+ * @returns {{ targets: Map<string, object> | null, requireTarget: boolean }}
57
82
  */
58
- export function resolveBackends({ exec, pty, fs, mcp } = {}) {
83
+ export function normalizeTargets(targets, requireTarget, buildOne, who = 'host') {
84
+ if (requireTarget !== undefined && typeof requireTarget !== 'boolean') throw new TypeError(`${who}: requireTarget must be a boolean`);
85
+ if (targets === undefined || targets === null) {
86
+ if (requireTarget) throw new TypeError(`${who}: requireTarget needs targets`);
87
+ return { targets: null, requireTarget: false };
88
+ }
89
+ if (typeof targets !== 'object' || Array.isArray(targets)) throw new TypeError(`${who}: targets must be an object of { name: { exec, pty, fs, endpoints, authorize, description } }`);
90
+ const map = new Map();
91
+ for (const [name, spec] of Object.entries(targets)) {
92
+ if (!TARGET_NAME_RE.test(name)) throw new TypeError(`${who}: targets: ${JSON.stringify(name)} is not a valid target name (letters, digits, ".", "_", "-"; at most 64)`);
93
+ if (spec === null || typeof spec !== 'object' || Array.isArray(spec)) throw new TypeError(`${who}: targets.${name} must be an object`);
94
+ for (const key of Object.keys(spec)) {
95
+ if (!TARGET_KEYS.includes(key)) throw new TypeError(`${who}: targets.${name}.${key} is not an option of a target (${TARGET_KEYS.join(', ')})`);
96
+ }
97
+ if (spec.authorize !== undefined && typeof spec.authorize !== 'function') throw new TypeError(`${who}: targets.${name}.authorize must be a function (who, { target, kind }) => boolean`);
98
+ if (spec.description !== undefined && typeof spec.description !== 'string') throw new TypeError(`${who}: targets.${name}.description must be a string`);
99
+ const built = buildOne({ exec: spec.exec, pty: spec.pty, fs: spec.fs });
100
+ map.set(name, {
101
+ name,
102
+ description: spec.description,
103
+ authorize: spec.authorize ?? null,
104
+ execRunner: built.execRunner,
105
+ execOptions: built.execOptions,
106
+ pty: built.pty,
107
+ files: built.files ? fileBackendForTarget(built.files, name) : null,
108
+ endpoints: normalizeEndpoints(spec.endpoints),
109
+ });
110
+ }
111
+ return { targets: map.size ? map : null, requireTarget: map.size ? !!requireTarget : false };
112
+ }
113
+
114
+ /**
115
+ * @param {{ exec?: Function | { run: Function }, pty?: { spawn: Function }, fs?: object, mcp?: object, targets?: object, requireTarget?: boolean }} options
116
+ * @returns {{ execRunner: Function | null, execOptions: object, pty: object | null, files: object | null, mcp: object | null, targets: Map<string, object> | null, requireTarget: boolean }}
117
+ */
118
+ export function resolveBackends({ exec, pty, fs, mcp, targets, requireTarget } = {}) {
119
+ const base = resolveOwnBackends({ exec, pty, fs, mcp });
120
+ return { ...base, ...normalizeTargets(targets, requireTarget, (spec) => resolveOwnBackends(spec), 'host') };
121
+ }
122
+
123
+ function resolveOwnBackends({ exec, pty, fs, mcp } = {}) {
59
124
  let execRunner = null;
60
125
  let execOptions = {};
61
126
  if (typeof exec === 'function') {
package/src/host.d.ts CHANGED
@@ -14,15 +14,15 @@ export interface WshFileBackend {
14
14
  * `read` (`offset`, `length`) -> `{ metadata: { data, size } }`; `write` (`offset`, `data`) -> `{ metadata: { written } }`;
15
15
  * `rename` (`newPath`); `mkdir`; `remove`. Anything else should throw.
16
16
  */
17
- operate(op: string, path: string, args?: { offset?: number; length?: number; newPath?: string; data?: Uint8Array }): Promise<{ metadata?: Record<string, unknown>; entries?: Array<Record<string, unknown>> }>;
17
+ operate(op: string, path: string, args?: { offset?: number; length?: number; newPath?: string; data?: Uint8Array; target?: string }): Promise<{ metadata?: Record<string, unknown>; entries?: Array<Record<string, unknown>> }>;
18
18
  /** The whole file, for a `download:` channel. Throw if it is larger than `maxFileBytes`. */
19
- readWhole(path: string): Promise<Uint8Array>;
19
+ readWhole(path: string, options?: { target?: string }): Promise<Uint8Array>;
20
20
  /** Create or replace a file (creating its directories), for an `upload:` channel. */
21
- writeWhole(path: string, data: Uint8Array): Promise<void>;
21
+ writeWhole(path: string, data: Uint8Array, options?: { target?: string }): Promise<void>;
22
22
  /** Write `data` at `offset` (omitted = replace the file), without truncating when an offset is given. */
23
- writeAt(path: string, data: Uint8Array, offset?: number, options?: { mkdirs?: boolean }): Promise<void>;
23
+ writeAt(path: string, data: Uint8Array, offset?: number, options?: { mkdirs?: boolean; target?: string }): Promise<void>;
24
24
  /** A byte range as chunks; only the `wsh-fs` rpc built-in (Node) reads it. */
25
- openRange?(path: string, options?: { offset?: number; length?: number; chunkBytes?: number }): Promise<{ size: number; offset: number; length: number; chunks: AsyncIterable<Uint8Array> }>;
25
+ openRange?(path: string, options?: { offset?: number; length?: number; chunkBytes?: number; target?: string }): Promise<{ size: number; offset: number; length: number; chunks: AsyncIterable<Uint8Array> }>;
26
26
  /** Largest file read or written whole, in bytes (default 64 MiB). */
27
27
  maxFileBytes?: number;
28
28
  }
@@ -39,12 +39,35 @@ export interface WshResolvedHostKey {
39
39
  sign(data: Uint8Array): Promise<Uint8Array>;
40
40
  }
41
41
 
42
+ /** What a host that serves several execution targets takes for each (#121). The same forms as the host's own backends. */
43
+ export interface WshTargetOptions {
44
+ /** A human line shown by `ListTargets`. */
45
+ description?: string;
46
+ /**
47
+ * Who may use this target. Called for every `Open`, `FileOp` and `OpenEndpoint` naming it (`kind`: `exec`, `pty`, `file`,
48
+ * `endpoint`) and for `ListTargets` (`kind: 'list'`); only `true` lets the caller on. Absent: any authenticated key.
49
+ * A refusal looks like an unknown target to the client.
50
+ */
51
+ authorize?: (who: { username: string | null; fingerprint: string | null }, request: { target: string; kind: 'exec' | 'pty' | 'file' | 'endpoint' | 'list' }) => boolean | Promise<boolean>;
52
+ /** `run(command, io)`; `io.target` is this target's name. (`true`, a shell, is for `createWshServer`.) */
53
+ exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
54
+ /** `spawn` is also given `{ target }` in its options. */
55
+ pty?: WshServerPtyOptions;
56
+ /** Every call is also given `{ target }`. */
57
+ fs?: WshFileBackend;
58
+ /** Named virtual endpoints of this target; the handler's `duplex.target` is its name. */
59
+ endpoints?: Record<string, ((duplex: object, who: { username: string | null; fingerprint: string | null }) => void | Promise<void>) | { open: Function; authorize?: (who: object) => boolean | Promise<boolean> }>;
60
+ }
61
+
42
62
  export interface WshResolvedBackends {
43
63
  execRunner: WshExecRunner | null;
44
64
  execOptions: { timeoutMs?: number; clientEnv?: WshClientEnv };
45
65
  pty: { spawn: WshServerPtyOptions['spawn']; shell: string; cwd?: string; env?: Record<string, string | undefined>; term: string } | null;
46
66
  files: Required<Pick<WshFileBackend, 'operate' | 'readWhole' | 'writeWhole' | 'writeAt' | 'maxFileBytes'>> & Pick<WshFileBackend, 'openRange'> | null;
47
67
  mcp: object | null;
68
+ /** The validated `targets` option (#121), by name; null when the host has none. */
69
+ targets: Map<string, object> | null;
70
+ requireTarget: boolean;
48
71
  }
49
72
 
50
73
  /** Validate injected backends (no shell, no directory: `exec` is a function or `{ run }`, `fs` an object of operations). */
@@ -53,6 +76,10 @@ export function resolveBackends(options?: {
53
76
  pty?: WshServerPtyOptions;
54
77
  fs?: WshFileBackend;
55
78
  mcp?: WshServerMcpOptions;
79
+ /** #121: execution targets, each with its own backends. Off unless given. */
80
+ targets?: Record<string, WshTargetOptions>;
81
+ /** With `targets`: a request that names none is refused. */
82
+ requireTarget?: boolean;
56
83
  }): WshResolvedBackends;
57
84
 
58
85
  /** Validate a file backend (see {@link WshFileBackend}). */
@@ -234,10 +261,12 @@ export type WshOnShare = (name: string, fs: WshShareFs, who: { username: string
234
261
  export const REFUSAL_REASONS: readonly WshRefusalReason[];
235
262
  export type WshRefusalReason =
236
263
  | 'not-sealed' | 'unauthorized' | 'binding-required' | 'bad-signature' | 'method-disabled' | 'rate-limited' | 'bad-request'
237
- | 'seal-failed' | 'busy' | 'proof-required' | 'proof-failed';
264
+ | 'seal-failed' | 'busy' | 'proof-required' | 'proof-failed' | 'key-expired' | 'not-permitted';
238
265
  /**
239
266
  * Called once per connection a host turned away (#163): `reason` is a stable code, `who` what is known of the peer (a
240
267
  * refusal before the login names no one), `detail` human text that is not stable. Not for parsing `onLog`.
241
268
  * Reverse hosts also use `busy`, `proof-required`, `proof-failed`; a sealed session that fails mid-way reports `seal-failed`.
269
+ * `key-expired` (a key past its `expires`, at login or later) and `not-permitted` (a request the key's options or capabilities do not
270
+ * allow; `detail` names the missing capability) are not per connection: `not-permitted` can come any number of times on one (#122).
242
271
  */
243
272
  export type WshOnRefused = (refusal: { reason: WshRefusalReason; who: { username?: string; fingerprint?: string; address?: string }; detail: string }) => void;
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?: {
@@ -1899,6 +1912,11 @@ export interface WshOpenSessionOptions {
1899
1912
  * advertises `exec-pipes`. `'pty'` or omitted: the host's native mode.
1900
1913
  */
1901
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;
1902
1920
  }
1903
1921
 
1904
1922
  /**
@@ -1988,6 +2006,8 @@ export interface WshExecOptions extends WshHostKeyOptions {
1988
2006
  * `'pipes'` throws if the host lacks `exec-pipes`; `'pty'` never asks for pipes.
1989
2007
  */
1990
2008
  stdio?: 'pty' | 'pipes';
2009
+ /** See {@link WshOpenSessionOptions.target}. */
2010
+ target?: string;
1991
2011
  }
1992
2012
 
1993
2013
  /** Result from WshClient.exec(). */
@@ -2130,7 +2150,22 @@ export interface WshFileOperationResult {
2130
2150
  * reverse mode (client registers as a peer for incoming connections).
2131
2151
  */
2132
2152
  /** Options for `openUnix` / `openEndpoint` / `openTcp`. */
2133
- 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
+ }
2134
2169
 
2135
2170
  /** One gateway connection as web streams with backpressure (credit-based flow control when both ends offer `gateway-credit`). */
2136
2171
  export interface WshGatewayDuplex {
@@ -2417,6 +2452,18 @@ export class WshClient {
2417
2452
  */
2418
2453
  listPeers(timeout?: number): Promise<WshPeerInfo[]>;
2419
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
+
2420
2467
  /**
2421
2468
  * Initiate a reverse connection to a registered peer.
2422
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';