@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.
@@ -19,17 +19,19 @@ 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, gatewayFail, listenFail,
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, SESSION_SEAL_FEATURE, SESSION_SEAL_REQUIRED_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';
31
33
  import { MULTI_OPERATOR_FEATURE } from './relay.mjs';
32
- import { gatewayFeatures } from './gateway-core.mjs';
34
+ import { gatewayFeatures, GATEWAY_FAIL } from './gateway-core.mjs';
33
35
  import { GATEWAY_DATAGRAM_FEATURE } from '../gateway-datagram.mjs';
34
36
  import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
35
37
  import { clientEnvFilter } from './client-env.mjs';
@@ -37,6 +39,7 @@ import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
37
39
  import { SealedBridge } from '../bridge-seal.mjs';
38
40
  import { refusalNotifier, validateOnRefused } from '../refusal.mjs';
39
41
  import { HOST_KEY_PREFIX, HOST_KEY_SIG_PREFIX, findClientNonce, hostKeyProofMessage, toHex } from '../host-key.mjs';
42
+ import { checkKeyRequest } from '../key-options.mjs';
40
43
  import { SHARES_FEATURE, createShareSession } from '../shares.mjs';
41
44
 
42
45
  export const STREAM_ANNOUNCE = 'stream-announce';
@@ -53,6 +56,12 @@ export function hostFeatures(cfg, { dataStreams = true } = {}) {
53
56
  if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
54
57
  if (cfg.gateway) features.push(...gatewayFeatures(cfg.gateway));
55
58
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
59
+ // Execution targets (#121): `Open`, `FileOp` and `OpenEndpoint` take `target`, and `ListTargets` is answered. A target with files is
60
+ // reached over FileOp, so the file features are stated for it too (the host's own may have none).
61
+ if (cfg.targets) {
62
+ features.push(TARGETS_FEATURE);
63
+ if (!cfg.files && [...cfg.targets.values()].some((t) => t.files)) features.push('file-transfer', 'file-write', 'file-rename');
64
+ }
56
65
  if (cfg.onShare) features.push(SHARES_FEATURE); // #159: this host can use folders the operator's client offers
57
66
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
58
67
  // client-opened streams: over a relay bridge.
@@ -128,6 +137,19 @@ export function createConnectionFactory(cfg) {
128
137
  // What a client may put in `Open.env` (#126): an allow-list unless the host says otherwise.
129
138
  const execEnv = clientEnvFilter(cfg.execOptions?.clientEnv);
130
139
  const ptyEnv = clientEnvFilter(cfg.pty?.clientEnv);
140
+ // Execution targets (#121): each has its own backends (and its own `clientEnv` rules). A request that names no target uses
141
+ // the host's own, unless `requireTarget` says nothing may run on the host itself.
142
+ /** @type {Map<string, object> | null} */
143
+ const targetTable = cfg.targets && cfg.targets.size
144
+ ? new Map([...cfg.targets].map(([name, spec]) => [name, { ...spec, execEnv: clientEnvFilter(spec.execOptions?.clientEnv), ptyEnv: clientEnvFilter(spec.pty?.clientEnv) }]))
145
+ : null;
146
+ const requireTarget = !!targetTable && !!cfg.requireTarget;
147
+ const ownBackends = { execRunner: cfg.execRunner, execOptions: cfg.execOptions, execEnv, pty: cfg.pty, ptyEnv, files: cfg.files, ownHost: true };
148
+ /** 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. */
149
+ const NO_SUCH_TARGET = 'no such target';
150
+ /** Every attached connection, for counting what a key holds open (`max-sessions`, #122). */
151
+ const liveConnections = new Set();
152
+ const targetCapabilities = (spec) =>[...(spec.execRunner ? ['exec'] : []), ...(spec.pty ? ['pty'] : []), ...(spec.files ? ['file'] : []), ...(spec.endpoints ? ['endpoint'] : [])];
131
153
 
132
154
  /**
133
155
  * Attach one connection. Two shapes:
@@ -144,9 +166,70 @@ export function createConnectionFactory(cfg) {
144
166
  const state = {
145
167
  sessionId: randomUUID(), nonce: null, username: authenticated?.username ?? null, authed: !!authenticated,
146
168
  closed: false, nextChannel: 0, fingerprint: authenticated?.fingerprint ?? null,
169
+ /** What `authorize()` granted, when it returned a capability set instead of `true` (#122). */
170
+ grant: null,
147
171
  };
148
172
  /** @type {Map<number, any>} */
149
173
  const channels = new Map();
174
+ const live = { channels, fingerprint: () => state.fingerprint };
175
+ liveConnections.add(live);
176
+
177
+ // ── What the key's authorized_keys options allow (#122) ──────────
178
+ // Looked up per request from the key this connection authenticated as (a bridged peer included); `null` = no options.
179
+ const keyPermissions = () => (state.fingerprint ? cfg.authorize.permissionsFor?.(state.fingerprint) ?? null : null);
180
+ /** pty/exec sessions this key holds open on this host: live unhosted channels of every connection, and hosted sessions. */
181
+ function activeSessionsFor(fingerprint) {
182
+ let n = 0;
183
+ for (const c of liveConnections) {
184
+ if (c.fingerprint() !== fingerprint) continue;
185
+ for (const ch of c.channels.values()) if (ch.keyed) n++;
186
+ }
187
+ if (cfg.sessions) n += cfg.sessions.listFor(fingerprint).filter((s) => s.state !== 'exited').length;
188
+ return n;
189
+ }
190
+ /** What this connection may do: its key's options, and what `authorize()` granted (#122, step two); each narrows the other. */
191
+ const permissionSets = () => [keyPermissions(), state.grant].filter(Boolean);
192
+ /** First refusal of `req` by any of the sets, or null; `silent` skips the log and `onRefused` (discovery filters). */
193
+ function refusalOf(req, silent) {
194
+ for (const perms of permissionSets()) {
195
+ const counts = req.kind === 'open' && (req.channel === 'pty' || req.channel === 'exec') && perms.maxSessions !== null;
196
+ const refusal = checkKeyRequest(perms, req, { activeSessions: counts ? activeSessionsFor(state.fingerprint) : 0 });
197
+ if (!refusal) continue;
198
+ if (!silent) {
199
+ const what = `${req.kind}${req.channel ? ` ${req.channel}` : ''}${req.protocol ? ` ${req.protocol}` : ''}`;
200
+ log(`key permissions refused ${what} for ${state.username ?? '?'} (${refusal.code}${refusal.capability ? `: ${refusal.capability}` : ''})`);
201
+ // #122: the embedder hears of it with a stable reason (`not-permitted`; `key-expired` for a key past its `expires`).
202
+ notifyRefused(refusal.code === 'key-expired' ? 'key-expired' : 'not-permitted', { username: state.username, fingerprint: state.fingerprint, address: remote.address }, `${refusal.code}: ${refusal.reason} (${what})`);
203
+ }
204
+ return refusal;
205
+ }
206
+ return null;
207
+ }
208
+ /**
209
+ * `null` when the key's options and capabilities allow this request, else `{ code, reason, capability? }` (logged, and
210
+ * reported through `onRefused`). Requests are described in `checkKeyRequest`.
211
+ * @param {object} req
212
+ */
213
+ const keyRefusal = (req) => refusalOf(req, false);
214
+ /** Whether this request would be allowed, without saying anything about it (what a discovery answer lists). */
215
+ const keyAllows = (req) => refusalOf(req, true) === null;
216
+ /** The reply that refuses a gateway message the key's capabilities do not cover (`GatewayFail` / `ListenFail`), or null. */
217
+ function gatewayRefusal(m) {
218
+ let req; let listener = false;
219
+ switch (m.type) {
220
+ case MSG.OPEN_TCP: req = { kind: 'tcp', host: m.host, port: m.port }; break;
221
+ case MSG.OPEN_UDP: req = { kind: 'udp', host: m.host, port: m.port }; break;
222
+ case MSG.RESOLVE_DNS: req = { kind: 'dns', name: m.name }; break;
223
+ case MSG.OPEN_UNIX: req = { kind: 'unix', path: m.path }; break;
224
+ case MSG.OPEN_ENDPOINT: req = { kind: 'endpoint', name: m.name, target: m.target ?? undefined }; break;
225
+ case MSG.LISTEN_REQUEST: req = { kind: 'listen-tcp', port: m.port }; listener = true; break;
226
+ case MSG.LISTEN_UNIX: req = { kind: 'listen-unix', path: m.path }; listener = true; break;
227
+ default: return null;
228
+ }
229
+ const refusal = keyRefusal(req);
230
+ if (!refusal) return null;
231
+ return listener ? listenFail({ listenerId: m.listener_id, reason: refusal.reason }) : gatewayFail({ gatewayId: m.gateway_id, code: GATEWAY_FAIL.POLICY_DENIED, message: refusal.reason });
232
+ }
150
233
  /** FileOp `write`/`rename`s awaiting their FileChunk frames, by client-chosen channel id. */
151
234
  const fileWrites = new Map();
152
235
  /** AbortControllers of in-flight MCP calls: aborted on disconnect, counted for the cap. */
@@ -176,7 +259,13 @@ export function createConnectionFactory(cfg) {
176
259
  // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
177
260
  if (cfg.gateway && typeof cfg.createGatewaySession !== 'function') throw new TypeError('createConnectionFactory: gateway needs createGatewaySession (only @johnhenry/wsh/server provides one)');
178
261
  const gateway = cfg.gateway
179
- ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }), datagrams })
262
+ ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, {
263
+ who: () => ({ username: state.username, fingerprint: state.fingerprint }),
264
+ datagrams,
265
+ // #121: a named target's own endpoints, once `authorize` has let the caller onto it
266
+ target: async (name) => { const r = await resolveTarget(name, 'endpoint'); return r.refuse ? { refuse: r.refuse } : { endpoints: r.b.endpoints ?? null }; },
267
+ requireTarget: () => requireTarget,
268
+ })
180
269
  : null;
181
270
 
182
271
  // Operator-side shared folders (#159): created with the connection, used only after the client's ShareOffer.
@@ -240,6 +329,7 @@ export function createConnectionFactory(cfg) {
240
329
  function shutdown(why) {
241
330
  if (state.closed) return;
242
331
  state.closed = true;
332
+ liveConnections.delete(live);
243
333
  clearTimeout(ttlTimer);
244
334
  // A hosted session survives its connection (it is detached, then expires or is resumed);
245
335
  // everything else dies with it.
@@ -302,7 +392,12 @@ export function createConnectionFactory(cfg) {
302
392
  m = inner;
303
393
  }
304
394
  if (await handleRelay(m)) return;
305
- if (gateway && await gateway.handle(m)) return;
395
+ if (gateway) {
396
+ // What the key's capabilities allow of the gateway (#122), before the gateway's own policy is asked.
397
+ const refusal = gatewayRefusal(m);
398
+ if (refusal) return send(refusal);
399
+ if (await gateway.handle(m)) return;
400
+ }
306
401
  if (shares && shares.handle(m)) return;
307
402
  switch (m.type) {
308
403
  case MSG.PING: return send(pong({ id: m.id }));
@@ -322,6 +417,7 @@ export function createConnectionFactory(cfg) {
322
417
  case MSG.RESUME: return handleAttach(m, true);
323
418
  case MSG.DETACH: return handleDetach(m);
324
419
  case MSG.SESSION_LIST_REQUEST: return handleSessionList();
420
+ case MSG.LIST_TARGETS: return handleListTargets();
325
421
  case MSG.MCP_DISCOVER: return handleMcpDiscover();
326
422
  // Not awaited: the handler chain is serial, and a slow tool must not hold up
327
423
  // the next call (or a Close) behind it.
@@ -483,6 +579,13 @@ export function createConnectionFactory(cfg) {
483
579
  allowed = await cfg.authorize({ username: state.username, fingerprint: fp, publicKey: m.public_key });
484
580
  } catch (e) { log(`authorize threw: ${e.message}`); }
485
581
  if (!allowed) return refuse('key not authorized', 'unauthorized', claimed);
582
+ // `authorize` may answer with a capability set (`{ permissions }` from `buildAuthorizer`): it narrows what the key's own options allow.
583
+ const grant = typeof allowed === 'object' ? allowed.permissions ?? null : null;
584
+ // A key past its `expires` does not log in (#122).
585
+ for (const perms of [cfg.authorize.permissionsFor?.(fp) ?? null, grant]) {
586
+ if (perms && checkKeyRequest(perms, { kind: 'login' })) return refuse('key has expired', 'key-expired', claimed);
587
+ }
588
+ state.grant = grant;
486
589
  state.authed = true;
487
590
  state.fingerprint = fp;
488
591
  state.publicKey = m.public_key;
@@ -590,6 +693,15 @@ export function createConnectionFactory(cfg) {
590
693
  await send(errorMsg({ code: 2, message: 'relay operations need a key login' }));
591
694
  return true;
592
695
  }
696
+ // The entry points to the relay (#122): a key without `permit-relay` cannot register, list or connect.
697
+ if (m.type === MSG.REVERSE_REGISTER || m.type === MSG.REVERSE_LIST || m.type === MSG.REVERSE_CONNECT) {
698
+ const refusal = keyRefusal({ kind: 'relay' });
699
+ if (refusal) {
700
+ if (m.type === MSG.REVERSE_CONNECT) await send(reverseReject({ targetFingerprint: String(m.target_fingerprint ?? ''), username: '', reason: refusal.reason }));
701
+ else await send(errorMsg({ code: 2, message: refusal.reason }));
702
+ return true;
703
+ }
704
+ }
593
705
  const h = hubHandle();
594
706
  switch (m.type) {
595
707
  case MSG.REVERSE_REGISTER: {
@@ -615,8 +727,11 @@ export function createConnectionFactory(cfg) {
615
727
 
616
728
  async function handleMcpDiscover() {
617
729
  let tools = [];
618
- if (cfg.mcp) {
730
+ // A key without MCP (#122) sees no tools, as it would on a host that has none.
731
+ if (cfg.mcp && keyAllows({ kind: 'mcp' })) {
619
732
  try { tools = await cfg.mcp.list(state.username, principal()); } catch (e) { log(`mcp discover failed: ${e.message}`); }
733
+ // A key with `mcp:<tool>` capabilities is told only of those tools.
734
+ tools = tools.filter((t) => keyAllows({ kind: 'mcp-tool', tool: t.name }));
620
735
  }
621
736
  return send(mcpTools({ tools }));
622
737
  }
@@ -631,6 +746,7 @@ export function createConnectionFactory(cfg) {
631
746
  };
632
747
  const fail = (error) => reply({ success: false, error });
633
748
  if (!cfg.mcp) { fail('mcp is not enabled on this server'); return; }
749
+ { const refusal = keyRefusal({ kind: 'mcp-call', tool: typeof m.tool === 'string' ? m.tool : '' }); if (refusal) { fail(refusal.reason); return; } }
634
750
  if (mcpCalls.size >= cfg.mcp.maxConcurrent) { fail('too many concurrent MCP calls'); return; }
635
751
 
636
752
  const abort = new AbortController();
@@ -669,13 +785,69 @@ export function createConnectionFactory(cfg) {
669
785
 
670
786
  // ── Open ──────────────────────────────────────────────────────────
671
787
 
672
- function handleOpen(m) {
788
+ /**
789
+ * The backends a request is served by (#121): the host's own when it names no target (and `requireTarget` is off), else the
790
+ * target's, once the host knows the name and its `authorize(who, { target, kind })` lets this caller on. `{ refuse }`
791
+ * otherwise, never a fallback to the host's own: a request for somewhere else is not run here.
792
+ * @returns {Promise<{ b: object } | { refuse: string }>}
793
+ */
794
+ async function resolveTarget(target, kind) {
795
+ if (target === undefined || target === null) return requireTarget ? { refuse: 'a target is required' } : { b: ownBackends };
796
+ if (!targetTable) return { refuse: 'this host has no targets' };
797
+ const spec = typeof target === 'string' && TARGET_NAME_RE.test(target) ? targetTable.get(target) : undefined;
798
+ if (!spec) return { refuse: NO_SUCH_TARGET };
799
+ if (spec.authorize) {
800
+ let allowed = false;
801
+ try { allowed = (await spec.authorize({ username: state.username, fingerprint: state.fingerprint }, { target, kind })) === true; } catch (e) { log(`target ${target} authorize threw: ${e.message}`); }
802
+ if (!allowed) {
803
+ log(`target ${target} refused for ${state.username ?? '?'} (${kind})`);
804
+ return { refuse: NO_SUCH_TARGET };
805
+ }
806
+ }
807
+ return { b: spec };
808
+ }
809
+
810
+ /** `ListTargets`: the targets this caller may use, as the host shows them. */
811
+ async function handleListTargets() {
812
+ if (!targetTable) return send(errorMsg({ code: 3, message: 'this host has no targets' }));
813
+ const out = [];
814
+ for (const [name, spec] of targetTable) {
815
+ // A key with capabilities is told only of the targets it holds (`target:NAME`).
816
+ if (!keyAllows({ kind: 'target', name })) continue;
817
+ const r = await resolveTarget(name, 'list');
818
+ if (r.refuse) continue;
819
+ out.push({ name, ...(spec.description !== undefined ? { description: spec.description } : {}), capabilities: targetCapabilities(spec) });
820
+ }
821
+ return send(targetListMsg({ targets: out }));
822
+ }
823
+
824
+ async function handleOpen(m) {
673
825
  if (channels.size >= MAX_CHANNELS) return send(openFail({ reason: 'too many open channels' }));
826
+ const target = m.target ?? undefined;
674
827
  switch (m.kind) {
675
- case 'exec': return openExec(m);
676
- case 'pty': return openPty(m);
677
- case 'file': return openFile(m);
678
- case 'rpc': return openRpc(m);
828
+ case 'exec': case 'pty': case 'file': {
829
+ // The key's options and capabilities (#122): asked before the target is looked up (a key without `target:NAME` learns
830
+ // nothing about whether it exists), and again once it is, because no await may separate the `max-sessions` check from
831
+ // the channel being registered (two opens must not both pass when one slot is left).
832
+ const req = { kind: 'open', channel: m.kind, target, direction: m.kind === 'file' ? (String(m.command ?? '').startsWith('download:') ? 'download' : 'upload') : undefined };
833
+ const early = keyRefusal(req);
834
+ if (early) return send(openFail({ reason: early.reason }));
835
+ const r = await resolveTarget(target, m.kind);
836
+ if (r.refuse) return send(openFail({ reason: r.refuse }));
837
+ const refusal = keyAllows(req) ? null : keyRefusal(req);
838
+ if (refusal) return send(openFail({ reason: refusal.reason }));
839
+ if (m.kind === 'exec') return openExec(m, r.b, target);
840
+ return m.kind === 'pty' ? openPty(m, r.b, target) : openFile(m, r.b);
841
+ }
842
+ case 'rpc':
843
+ // rpc channels (`wsh-fs`, `wsh-host`, `mcp`) are the host's own, not per target.
844
+ if (target !== undefined) return send(openFail({ reason: 'rpc channels do not take a target' }));
845
+ if (requireTarget) return send(openFail({ reason: 'a target is required' }));
846
+ {
847
+ const refusal = keyRefusal({ kind: 'open', channel: 'rpc', protocol: typeof m.command === 'string' ? m.command : '' });
848
+ if (refusal) return send(openFail({ reason: refusal.reason }));
849
+ }
850
+ return openRpc(m);
679
851
  default: return send(openFail({ reason: `kind "${m.kind}" is not supported by this server` }));
680
852
  }
681
853
  }
@@ -798,9 +970,10 @@ export function createConnectionFactory(cfg) {
798
970
  return send(sessionList({ sessions }));
799
971
  }
800
972
 
801
- async function openExec(m) {
802
- if (!cfg.execRunner) return send(openFail({ reason: 'exec is not enabled on this server' }));
803
- const command = String(m.command ?? '').trim();
973
+ async function openExec(m, b, target) {
974
+ if (!b.execRunner) return send(openFail({ reason: `exec is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
975
+ // A key tied to one command (`command="..."`, #122) runs that, whatever the client asked for.
976
+ const command = keyPermissions()?.forcedCommand ?? String(m.command ?? '').trim();
804
977
  if (!command) return send(openFail({ reason: 'command is required for kind "exec"' }));
805
978
 
806
979
  const channelId = ++state.nextChannel;
@@ -821,6 +994,7 @@ export function createConnectionFactory(cfg) {
821
994
  if (/^(INT|TERM|KILL|HUP)$/.test(n) && signalCbs.length === 0) abort.abort();
822
995
  };
823
996
  const ch = {
997
+ keyed: !hosted, // counts toward the key's `max-sessions` (a hosted session is counted by the registry)
824
998
  kill: () => abort.abort(),
825
999
  signal: signalTo,
826
1000
  bind(s) {
@@ -847,7 +1021,7 @@ export function createConnectionFactory(cfg) {
847
1021
  else ch.input = (d) => { for (const cb of inputCbs) cb(d); };
848
1022
 
849
1023
  let timer = null;
850
- if (cfg.execOptions.timeoutMs > 0) timer = setTimeout(() => abort.abort(), cfg.execOptions.timeoutMs);
1024
+ if (b.execOptions.timeoutMs > 0) timer = setTimeout(() => abort.abort(), b.execOptions.timeoutMs);
851
1025
 
852
1026
  // Output to the opening connection's data stream (held until the client has opened it).
853
1027
  const toStream = (bytes) => {
@@ -898,7 +1072,9 @@ export function createConnectionFactory(cfg) {
898
1072
 
899
1073
  const io = {
900
1074
  user: state.username,
901
- env: execEnv(m.env),
1075
+ // Which execution target this command runs on (#121); undefined on the host's own.
1076
+ target,
1077
+ env: b.execEnv(m.env),
902
1078
  cols: m.cols || 80,
903
1079
  rows: m.rows || 24,
904
1080
  signal: abort.signal,
@@ -925,7 +1101,7 @@ export function createConnectionFactory(cfg) {
925
1101
 
926
1102
  async function runExec() {
927
1103
  let code;
928
- try { code = await cfg.execRunner(command, io); } catch (e) {
1104
+ try { code = await b.execRunner(command, io); } catch (e) {
929
1105
  await io.write(`wsh: ${e.message}\n`);
930
1106
  code = 1;
931
1107
  }
@@ -990,23 +1166,26 @@ export function createConnectionFactory(cfg) {
990
1166
  log(`rpc channel ${channelId}: ${protocol}`);
991
1167
  }
992
1168
 
993
- async function openPty(m) {
994
- if (!cfg.pty) return send(openFail({ reason: 'pty is not enabled on this server' }));
1169
+ async function openPty(m, b, target) {
1170
+ if (!b.pty) return send(openFail({ reason: `pty is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
995
1171
  const channelId = ++state.nextChannel;
996
1172
  const cols = m.cols || 80;
997
1173
  const rows = m.rows || 24;
998
- const p = cfg.pty;
1174
+ const p = b.pty;
999
1175
  let proc;
1000
1176
  try {
1001
1177
  const args = m.command ? ['-c', String(m.command)] : [];
1002
1178
  proc = p.spawn(p.shell, args, {
1003
1179
  name: p.term, cols, rows, cwd: p.cwd,
1004
- env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...ptyEnv(m.env) },
1180
+ env: { ...(p.env ?? globalThis.process?.env), TERM: p.term, ...b.ptyEnv(m.env) },
1181
+ // Which execution target this shell is for (#121); absent on the host's own.
1182
+ ...(target !== undefined ? { target } : {}),
1005
1183
  });
1006
1184
  } catch (e) {
1007
1185
  return send(openFail({ reason: `pty spawn failed: ${e.message}` }));
1008
1186
  }
1009
1187
  const ctl = {
1188
+ keyed: !cfg.sessions, // counts toward the key's `max-sessions` (a hosted session is counted by the registry)
1010
1189
  // Bytes, not a `Buffer`: there is none in a browser (#133), and node-pty's streams take a Uint8Array as is.
1011
1190
  // A write to a process that has exited throws; that is expected and dropped, anything else is logged.
1012
1191
  input: (data) => {
@@ -1045,8 +1224,9 @@ export function createConnectionFactory(cfg) {
1045
1224
  log(`pty channel ${channelId} opened (${cols}x${rows})`);
1046
1225
  }
1047
1226
 
1048
- async function openFile(m) {
1049
- if (!cfg.files) return send(openFail({ reason: 'file access is not enabled on this server' }));
1227
+ async function openFile(m, b) {
1228
+ const files = b.files;
1229
+ if (!files) return send(openFail({ reason: `file access is not enabled ${b.ownHost ? 'on this server' : 'for this target'}` }));
1050
1230
  const spec = String(m.command ?? '');
1051
1231
  const mm = spec.match(/^(upload|download):(.*)$/s);
1052
1232
  if (!mm) return send(openFail({ reason: 'file channel expects upload:<path> or download:<path>' }));
@@ -1055,7 +1235,7 @@ export function createConnectionFactory(cfg) {
1055
1235
 
1056
1236
  if (direction === 'download') {
1057
1237
  let data;
1058
- try { data = await cfg.files.readWhole(filePath); } catch (e) { return send(openFail({ reason: e.message })); }
1238
+ try { data = await files.readWhole(filePath); } catch (e) { return send(openFail({ reason: e.message })); }
1059
1239
  let cancelled = false;
1060
1240
  channels.set(channelId, { kill: () => { if (channels.delete(channelId)) { cancelled = true; log(`download ${filePath}: closed before completion`); } } });
1061
1241
  await send(openOk({ channelId, dataMode: 'virtual', capabilities: [] }));
@@ -1081,13 +1261,13 @@ export function createConnectionFactory(cfg) {
1081
1261
  ch.chunk = async (c) => {
1082
1262
  if (ch.failed) return;
1083
1263
  const total = Number(c.total_size ?? 0);
1084
- if (total > cfg.files.maxFileBytes) { ch.failed = true; return done(1, `refused: ${total} B exceeds ${cfg.files.maxFileBytes} B`); }
1264
+ if (total > files.maxFileBytes) { ch.failed = true; return done(1, `refused: ${total} B exceeds ${files.maxFileBytes} B`); }
1085
1265
  ch.buf ??= new Uint8Array(total);
1086
1266
  const data = c.data instanceof Uint8Array ? c.data : new Uint8Array(0);
1087
1267
  if (c.offset + data.byteLength > ch.buf.byteLength) { ch.failed = true; return done(1, 'chunk past total_size'); }
1088
1268
  ch.buf.set(data, c.offset);
1089
1269
  if (c.is_final) {
1090
- try { await cfg.files.writeWhole(filePath, ch.buf); } catch (e) { ch.failed = true; return done(1, e.message); }
1270
+ try { await files.writeWhole(filePath, ch.buf); } catch (e) { ch.failed = true; return done(1, e.message); }
1091
1271
  return done(0, `stored ${ch.buf.byteLength} B`);
1092
1272
  }
1093
1273
  };
@@ -1096,10 +1276,16 @@ export function createConnectionFactory(cfg) {
1096
1276
 
1097
1277
  async function handleFileOp(m) {
1098
1278
  const channelId = m.channel_id;
1099
- if (!cfg.files) return send(fileResult({ channelId, success: false, errorMessage: 'file access is not enabled on this server' }));
1100
- if (m.op === 'write' || m.op === 'rename') return startPayloadOp(m);
1279
+ const target = m.target ?? undefined;
1280
+ const refusal = keyRefusal({ kind: 'file-op', op: m.op, target });
1281
+ if (refusal) return send(fileResult({ channelId, success: false, errorMessage: refusal.reason }));
1282
+ const r0 = await resolveTarget(target, 'file');
1283
+ if (r0.refuse) return send(fileResult({ channelId, success: false, errorMessage: r0.refuse }));
1284
+ const files = r0.b.files;
1285
+ if (!files) return send(fileResult({ channelId, success: false, errorMessage: `file access is not enabled ${r0.b.ownHost ? 'on this server' : 'for this target'}` }));
1286
+ if (m.op === 'write' || m.op === 'rename') return startPayloadOp(m, files);
1101
1287
  try {
1102
- const r = await cfg.files.operate(m.op, m.path, { offset: m.offset, length: m.length });
1288
+ const r = await files.operate(m.op, m.path, { offset: m.offset, length: m.length });
1103
1289
  return send(fileResult({ channelId, success: true, metadata: r.metadata ?? {}, entries: r.entries ?? [] }));
1104
1290
  } catch (e) {
1105
1291
  const message = e.wsh ? e.message : (e.code === 'ENOENT' ? 'no such file or directory' : `${m.op} failed`);
@@ -1111,17 +1297,17 @@ export function createConnectionFactory(cfg) {
1111
1297
  // write / rename = FileOp then FileChunk frame(s) on the same channel id
1112
1298
  // (rename's payload is the UTF-8 destination path); one FileResult once
1113
1299
  // the last chunk lands (see WshClient.fileOperation).
1114
- async function startPayloadOp(m) {
1300
+ async function startPayloadOp(m, files) {
1115
1301
  const channelId = m.channel_id;
1116
1302
  const failWrite = (errorMessage) => send(fileResult({ channelId, success: false, errorMessage }));
1117
1303
  const rename = m.op === 'rename';
1118
1304
  const length = Number(m.length);
1119
1305
  if (!Number.isSafeInteger(length) || length < 0) return failWrite(`${m.op} needs a length`);
1120
- const limit = rename ? MAX_RENAME_PATH_BYTES : cfg.files.maxFileBytes;
1306
+ const limit = rename ? MAX_RENAME_PATH_BYTES : files.maxFileBytes;
1121
1307
  if (length > limit) return failWrite(`${m.op} payload of ${length} bytes exceeds the ${limit} byte limit`);
1122
1308
  if (channels.has(channelId) || fileWrites.has(channelId)) return failWrite('channel id already in use');
1123
1309
  if (fileWrites.size >= MAX_PENDING_WRITES) return failWrite('too many writes in flight');
1124
- const w = { rename, path: m.path, offset: m.offset, length, buf: new Uint8Array(length), next: 0, timer: null };
1310
+ const w = { rename, files, path: m.path, offset: m.offset, length, buf: new Uint8Array(length), next: 0, timer: null };
1125
1311
  const arm = () => {
1126
1312
  clearTimeout(w.timer);
1127
1313
  w.timer = setTimeout(() => {
@@ -1153,8 +1339,8 @@ export function createConnectionFactory(cfg) {
1153
1339
  if (w.next !== w.length) return send(fileResult({ channelId, success: false, errorMessage: 'payload ended short of the declared length' }));
1154
1340
  try {
1155
1341
  const r = w.rename
1156
- ? await cfg.files.operate('rename', w.path, { newPath: new TextDecoder('utf-8', { fatal: true }).decode(w.buf) })
1157
- : await cfg.files.operate('write', w.path, { offset: w.offset, data: w.buf });
1342
+ ? await w.files.operate('rename', w.path, { newPath: new TextDecoder('utf-8', { fatal: true }).decode(w.buf) })
1343
+ : await w.files.operate('write', w.path, { offset: w.offset, data: w.buf });
1158
1344
  return send(fileResult({ channelId, success: true, metadata: r.metadata ?? {} }));
1159
1345
  } catch (e) {
1160
1346
  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. */
@@ -14,14 +14,26 @@ export interface WshServerPrincipal {
14
14
  publicKey: Uint8Array;
15
15
  }
16
16
 
17
+ /** What `authorize()` may return instead of `true` (#122): a capability list, and/or an expiry. */
18
+ export interface WshCapabilityGrant {
19
+ /** `exec`, `pty`, `relay`, `fs:read`, `fs:write`, `gateway:tcp:<host>:<port>`, `gateway:udp:<host>:<port>`, `gateway:listen:tcp:<port>`, `unix:<path>`, `unix:listen:<path>`, `endpoint:<name>`, `mcp:<tool>`, `target:<name>`, `rpc:<protocol>`; an array, or a comma-separated string. */
20
+ capabilities?: string | string[];
21
+ expires?: string | Date | number;
22
+ }
23
+
17
24
  export interface WshServerAuthOptions {
18
25
  /**
19
26
  * Keys allowed to connect: `ssh-ed25519 AAAA... [comment]` lines (an
20
27
  * `authorized_keys` file's text works), raw 32-byte keys, or an array of either.
21
28
  */
22
29
  authorizedKeys?: string | Uint8Array | Array<string | Uint8Array>;
23
- /** Extra policy, run after the signature verifies (and after the allowlist, when given). */
24
- authorize?: (who: WshServerPrincipal) => boolean | Promise<boolean>;
30
+ /**
31
+ * Extra policy, run after the signature verifies (and after the allowlist, when given). Return `true` to admit, or a
32
+ * capability set (#122) to admit with less: the key may do only what it names, on top of what its `authorized_keys` options
33
+ * allow (it never widens them). Same grammar as `capabilities="..."` in a key line; `expires` is an RFC 3339 string, a
34
+ * `Date` or epoch milliseconds (whole seconds are used). A set that is not understood refuses the login (logged).
35
+ */
36
+ authorize?: (who: WshServerPrincipal) => boolean | WshCapabilityGrant | Promise<boolean | WshCapabilityGrant>;
25
37
  /**
26
38
  * Enable password login: return `true` to admit. Sent in the clear inside the
27
39
  * connection -- serve over `wss://` / a trusted link. Use a constant-time
@@ -60,6 +72,8 @@ export type WshClientEnv = boolean | string[] | ((name: string, value: string) =
60
72
  /** What a custom `exec` runner receives for one session. */
61
73
  export interface WshExecIo {
62
74
  user: string;
75
+ /** #121: the execution target this command runs on; undefined on the host's own. */
76
+ target?: string;
63
77
  /** Environment the client asked for (empty when `clientEnv: false`). */
64
78
  env: Record<string, string>;
65
79
  cols: number;
@@ -115,6 +129,8 @@ export interface WshGatewayEndpointDuplex {
115
129
  readable: ReadableStream<Uint8Array>;
116
130
  writable: WritableStream<Uint8Array>;
117
131
  who: WshGatewayWho;
132
+ /** #121: the execution target this endpoint belongs to; undefined for the host's own. */
133
+ target?: string;
118
134
  /** Half-close: nothing more will be sent. */
119
135
  close(reason?: string): void;
120
136
  /** Tear the connection down now. */
@@ -402,7 +418,7 @@ export interface WshServerOptions {
402
418
  /** Port (default `0` = pick a free one; read it back from `address()`). */
403
419
  port?: number;
404
420
  /** Who may connect. Omitted = every connection is refused. A function is shorthand for `{ authorize }`. */
405
- auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | Promise<boolean>);
421
+ auth?: WshServerAuthOptions | ((who: WshServerPrincipal) => boolean | WshCapabilityGrant | Promise<boolean | WshCapabilityGrant>);
406
422
  /** Enable `exec` sessions. `true`, options, or a custom runner. Off by default. */
407
423
  exec?: true | WshServerExecOptions | WshExecRunner;
408
424
  /** Enable `pty` sessions by injecting a pty implementation. Off by default. */
@@ -487,6 +503,15 @@ export interface WshServerOptions {
487
503
  onShare?: import('../host.js').WshOnShare;
488
504
  /** #163: told once per connection this host turned away (an operator, on a reverse host), with a stable reason code (`REFUSAL_REASONS`, from `@johnhenry/wsh/host`). */
489
505
  onRefused?: import('../host.js').WshOnRefused;
506
+ /**
507
+ * #121: execution targets (containers, VMs, workers, sandboxes), each with its own `exec` (`true` = a shell), `pty`, `fs`
508
+ * (`{ root }` or operations) and `endpoints`, and an `authorize(who, { target, kind })`. A client names one in `Open`,
509
+ * `FileOp` or `OpenEndpoint` and lists what it may use with `listTargets()`. Off unless given: the host then advertises no
510
+ * `targets` and refuses a request that names one. A refused target and one that does not exist look the same to the client.
511
+ */
512
+ targets?: Record<string, Omit<import('../host.js').WshTargetOptions, 'exec' | 'fs'> & { exec?: true | WshServerExecOptions | WshExecRunner; fs?: WshServerFsOptions | import('../host.js').WshFileBackend }>;
513
+ /** With `targets`: an `Open`, `FileOp` or `OpenEndpoint` that names no target is refused, so nothing runs on the host itself (`rpc` channels too). Does not cover the gateway, MCP or `Attach`. */
514
+ requireTarget?: boolean;
490
515
  onLog?: (line: string) => void;
491
516
  }
492
517
 
@@ -578,9 +603,44 @@ export interface WshServer {
578
603
 
579
604
  export function createWshServer(options?: WshServerOptions): WshServer;
580
605
 
581
- /** Parse `authorized_keys`-style text into raw 32-byte Ed25519 keys (malformed lines skipped). */
606
+ /**
607
+ * Parse `authorized_keys`-style text into the raw 32-byte Ed25519 keys of the lines that carry NO options (malformed lines
608
+ * skipped). A line with options is not returned, because its restrictions would be lost: use `auth.authorizedKeys` (which
609
+ * enforces them) or `parseAuthorizedKeyEntries`.
610
+ */
582
611
  export function parseAuthorizedKeys(text: string): Uint8Array[];
583
612
 
613
+ /** What an `authorized_keys` line's options allow (wsh #122; the same on the Rust `wsh-server`). */
614
+ export interface KeyPermissions {
615
+ /** A pty shell. */
616
+ pty: boolean;
617
+ /** `exec` channels. */
618
+ exec: boolean;
619
+ /** MCP discovery and calls. */
620
+ mcp: boolean;
621
+ /** File channels, `FileOp` and `wsh-fs`. */
622
+ fileTransfer: boolean;
623
+ /** Relay registration, listing and connecting. */
624
+ relay: boolean;
625
+ /** `command="..."`: the only command the key may run (replaces what the client asks for). */
626
+ forcedCommand: string | null;
627
+ /** `max-sessions=N`: most live pty/exec sessions the key may hold at once. */
628
+ maxSessions: number | null;
629
+ /** `capabilities="..."` (#122, step two): `null` when the line has none; else the list, default-deny (only what it names). */
630
+ capabilities: string[] | null;
631
+ /** `expires="..."`: the epoch second from which the key is refused, or `null`. */
632
+ expires: number | null;
633
+ }
634
+
635
+ /**
636
+ * Parse `authorized_keys`-style text, options included. `refused` lists the lines whose options this host does not
637
+ * understand (`code`: `unknown-option`, `bad-syntax`, `bad-value`, `duplicate-option`); those keys are not let in.
638
+ */
639
+ export function parseAuthorizedKeyEntries(text: string): {
640
+ entries: Array<{ key: Uint8Array; options: string | null; permissions: KeyPermissions; line: number }>;
641
+ refused: Array<{ line: number; code: string; reason: string; key: Uint8Array }>;
642
+ };
643
+
584
644
  /** ServerHello feature: the host discovers client-opened exec data streams itself (no primer byte). */
585
645
  export const STREAM_ANNOUNCE: 'stream-announce';
586
646