@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/README.md +115 -20
- package/package.json +1 -1
- package/src/client.mjs +183 -15
- package/src/features.mjs +15 -0
- package/src/gateway-client.mjs +11 -4
- package/src/host-backends.mjs +68 -3
- package/src/host.d.ts +32 -5
- package/src/index.d.ts +61 -1
- package/src/index.mjs +2 -1
- package/src/memory-host.d.ts +8 -0
- package/src/memory-host.mjs +10 -3
- package/src/messages.gen.mjs +23 -8
- package/src/reverse-host.mjs +1 -0
- package/src/server/backends.mjs +11 -6
- package/src/server/connection.mjs +107 -33
- package/src/server/gateway-core.mjs +14 -2
- package/src/server/index.d.ts +13 -0
- package/src/server/index.mjs +16 -4
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 } 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) {
|
|
@@ -183,6 +193,10 @@ function assertStdinSource(stdin) {
|
|
|
183
193
|
throw new TypeError('exec: stdin must be a string, Uint8Array, ReadableStream or (async) iterable of those');
|
|
184
194
|
}
|
|
185
195
|
|
|
196
|
+
function assertSealSession(v) {
|
|
197
|
+
if (v !== false && v !== 'auto' && v !== true) throw new TypeError("connect: sealSession must be false, 'auto' or true");
|
|
198
|
+
}
|
|
199
|
+
|
|
186
200
|
/** Write `stdin` to `session` in bounded chunks, then close the write side (EOF). */
|
|
187
201
|
async function pumpStdin(session, stdin) {
|
|
188
202
|
const send = async (chunk) => {
|
|
@@ -274,6 +288,13 @@ export class WshClient {
|
|
|
274
288
|
*/
|
|
275
289
|
#sealState = null;
|
|
276
290
|
|
|
291
|
+
/**
|
|
292
|
+
* Set from the moment this client starts sealing its whole session (#155) until the connection ends: `{ sessionId,
|
|
293
|
+
* bridge }`, `bridge` null until the key exists. A message that arrives from the host itself is then heard only
|
|
294
|
+
* as the key exchange (while pending), a frame of the session, or the keepalive.
|
|
295
|
+
*/
|
|
296
|
+
#sessionSeal = null;
|
|
297
|
+
|
|
277
298
|
/** The binding kinds the last login's signature covered (#119); empty when it was unbound. */
|
|
278
299
|
#channelBindingKinds = [];
|
|
279
300
|
|
|
@@ -558,6 +579,14 @@ export class WshClient {
|
|
|
558
579
|
return this.#hostKey;
|
|
559
580
|
}
|
|
560
581
|
|
|
582
|
+
/**
|
|
583
|
+
* Is this whole session sealed end to end (#155, `connect(url, { sealSession })`)? Every message but the keepalive,
|
|
584
|
+
* gateway and endpoint data included, then travels as an authenticated encrypted frame a relay cannot read or alter.
|
|
585
|
+
*/
|
|
586
|
+
get sessionSealed() {
|
|
587
|
+
return !!this.#sessionSeal?.bridge;
|
|
588
|
+
}
|
|
589
|
+
|
|
561
590
|
// ── Connection ──────────────────────────────────────────────────────
|
|
562
591
|
|
|
563
592
|
/**
|
|
@@ -595,15 +624,25 @@ export class WshClient {
|
|
|
595
624
|
* to this connection (#119): `true` needs at least one binding kind (`host`, `cert-hash`, `tls-exporter`) that
|
|
596
625
|
* both the host offers and this client can supply; an array names kinds that must all be bound. Not for
|
|
597
626
|
* password auth (nothing is signed). Stops an intermediary from relaying a genuine challenge to the host.
|
|
627
|
+
* @param {false | 'auto' | true} [opts.sealSession='auto'] - Seal the WHOLE session end to end (#155): after login a
|
|
628
|
+
* signed key exchange with the host (bound to its proven host key and this login key), then every message but the
|
|
629
|
+
* keepalive -- gateway and endpoint data included -- is an authenticated encrypted frame, so a relay that copies
|
|
630
|
+
* bytes can neither read nor alter it, and a frame that does not open closes the connection. `'auto'` seals only
|
|
631
|
+
* against a host that says `e2e-session-required` (a host that merely offers it is spoken to as before); `true`
|
|
632
|
+
* seals or fails -- a host that does not offer `e2e-session`, one that proved no host key, or a password login is
|
|
633
|
+
* refused BEFORE a credential is sent; `false` never seals (a host that requires it then serves nothing). Only
|
|
634
|
+
* `true` is a guarantee: `'auto'` rests on a ServerHello feature that a relay can strip before login. Pin the host
|
|
635
|
+
* (`expectHostKey` / `knownHosts`) too: the exchange authenticates the key the host proved, not whose it is.
|
|
598
636
|
* @returns {Promise<string>} The server-assigned session ID
|
|
599
637
|
*/
|
|
600
|
-
async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, requireChannelBinding = false, ...hostKeyOpts } = {}) {
|
|
638
|
+
async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, requireChannelBinding = false, sealSession = 'auto', ...hostKeyOpts } = {}) {
|
|
601
639
|
if (this.#state !== STATE_DISCONNECTED && this.#state !== STATE_CLOSED) {
|
|
602
640
|
throw new Error(`Client already ${this.#state}`);
|
|
603
641
|
}
|
|
604
642
|
if (!username) {
|
|
605
643
|
throw new Error('username is required');
|
|
606
644
|
}
|
|
645
|
+
assertSealSession(sealSession);
|
|
607
646
|
const cred = await resolveSigner({ keyPair, signer });
|
|
608
647
|
this.#signer = cred;
|
|
609
648
|
this.#loginUsername = username;
|
|
@@ -616,6 +655,7 @@ export class WshClient {
|
|
|
616
655
|
this.#channelBindingKinds = [];
|
|
617
656
|
this.#certHash = null;
|
|
618
657
|
this.#sealState = null;
|
|
658
|
+
this.#sessionSeal = null;
|
|
619
659
|
this.#peerProof = null;
|
|
620
660
|
this.#sessions.clear();
|
|
621
661
|
this.#channelCounter = 0;
|
|
@@ -651,6 +691,9 @@ export class WshClient {
|
|
|
651
691
|
}
|
|
652
692
|
|
|
653
693
|
let tempSessionId = null;
|
|
694
|
+
// Whether this session is to be sealed (#155): decided from the ServerHello and the proven host key, BEFORE a
|
|
695
|
+
// credential is sent, so a host that cannot seal is refused while nothing has been signed.
|
|
696
|
+
let seal = false;
|
|
654
697
|
|
|
655
698
|
if (firstResponse.type === MSG.SERVER_HELLO) {
|
|
656
699
|
// Server may proceed directly to auth if it accepted the hello.
|
|
@@ -665,6 +708,7 @@ export class WshClient {
|
|
|
665
708
|
: null;
|
|
666
709
|
challengeWait?.catch(() => {});
|
|
667
710
|
await this.#verifyHostKey(firstResponse, hostCtx);
|
|
711
|
+
seal = this.#planSealing(sealSession, this.#serverFeatures, !!cred);
|
|
668
712
|
|
|
669
713
|
if (authMethod === AUTH_METHOD.PUBKEY) {
|
|
670
714
|
const challengeMsg = await challengeWait;
|
|
@@ -675,6 +719,7 @@ export class WshClient {
|
|
|
675
719
|
this.#authToken = challengeMsg.token || null;
|
|
676
720
|
this.#authTtl = Number(challengeMsg.ttl) || 0;
|
|
677
721
|
this.#state = STATE_AUTHENTICATED;
|
|
722
|
+
if (seal) await this.#sealSession(timeout);
|
|
678
723
|
this.#startPing();
|
|
679
724
|
return this.#sessionId;
|
|
680
725
|
}
|
|
@@ -708,6 +753,7 @@ export class WshClient {
|
|
|
708
753
|
} else if (firstResponse.type === MSG.CHALLENGE) {
|
|
709
754
|
// Some servers skip SERVER_HELLO and go straight to CHALLENGE.
|
|
710
755
|
await this.#verifyHostKey(null, hostCtx);
|
|
756
|
+
seal = this.#planSealing(sealSession, [], !!cred);
|
|
711
757
|
if (authMethod !== AUTH_METHOD.PUBKEY || !cred) {
|
|
712
758
|
throw new Error('Server sent CHALLENGE but no key pair was provided');
|
|
713
759
|
}
|
|
@@ -751,6 +797,7 @@ export class WshClient {
|
|
|
751
797
|
this.#authToken = authResult.token || null;
|
|
752
798
|
this.#authTtl = Number(authResult.ttl) || 0;
|
|
753
799
|
this.#state = STATE_AUTHENTICATED;
|
|
800
|
+
if (seal) await this.#sealSession(timeout);
|
|
754
801
|
this.#startPing();
|
|
755
802
|
|
|
756
803
|
return this.#sessionId;
|
|
@@ -788,10 +835,13 @@ export class WshClient {
|
|
|
788
835
|
* Throws `RpcError` (`UNSUPPORTED_PROTOCOL`) before sending anything if the host does not advertise it.
|
|
789
836
|
* @param {(session: WshSession) => void} [opts.attach] - Advanced: called synchronously the moment the data
|
|
790
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.
|
|
791
840
|
* @returns {Promise<WshSession>}
|
|
792
841
|
*/
|
|
793
|
-
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 } = {}) {
|
|
794
843
|
this.#assertAuthenticated('openSession');
|
|
844
|
+
assertTargetUsable(this, target, 'openSession');
|
|
795
845
|
if (stdio !== undefined && stdio !== 'pty' && stdio !== 'pipes') {
|
|
796
846
|
throw new TypeError('openSession: stdio must be "pty" or "pipes"');
|
|
797
847
|
}
|
|
@@ -808,7 +858,7 @@ export class WshClient {
|
|
|
808
858
|
const requestedChannelId = this._nextChannelId();
|
|
809
859
|
|
|
810
860
|
await this.#transport.sendControl(
|
|
811
|
-
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 })
|
|
812
862
|
);
|
|
813
863
|
|
|
814
864
|
// Registered as a dedicated pending-open (not the generic
|
|
@@ -1151,10 +1201,11 @@ export class WshClient {
|
|
|
1151
1201
|
* when the host advertises `exec-pipes` (no echo, stderr kept apart, EOF), else the host's native
|
|
1152
1202
|
* mode; without `stdin`, the host's native mode (a PTY on the Rust server), exactly as before.
|
|
1153
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`).
|
|
1154
1205
|
* @returns {Promise<{stdout: Uint8Array, exitCode: number, stderr?: Uint8Array}>} `stderr` is present
|
|
1155
1206
|
* only when the command ran on pipes.
|
|
1156
1207
|
*/
|
|
1157
|
-
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 } = {}) {
|
|
1158
1209
|
if (stdin !== undefined) assertStdinSource(stdin);
|
|
1159
1210
|
if (stdio !== undefined && stdio !== 'pipes' && stdio !== 'pty') throw new TypeError('exec: stdio must be "pipes" or "pty"');
|
|
1160
1211
|
const client = new WshClient();
|
|
@@ -1169,7 +1220,7 @@ export class WshClient {
|
|
|
1169
1220
|
|
|
1170
1221
|
// The first stdin byte (or the EOF itself) announces the data stream to a
|
|
1171
1222
|
// legacy host, so the primer byte is only needed when there is no stdin.
|
|
1172
|
-
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 });
|
|
1173
1224
|
|
|
1174
1225
|
await new Promise((resolve, reject) => {
|
|
1175
1226
|
const timer = setTimeout(() => {
|
|
@@ -1348,6 +1399,22 @@ export class WshClient {
|
|
|
1348
1399
|
return Promise.all(peers.map(async (peer) => ({ ...peer, verified: await verifyPeerInfoRecord(peer) })));
|
|
1349
1400
|
}
|
|
1350
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
|
+
|
|
1351
1418
|
/**
|
|
1352
1419
|
* Initiate a reverse connection to a registered peer.
|
|
1353
1420
|
*
|
|
@@ -1562,7 +1629,7 @@ export class WshClient {
|
|
|
1562
1629
|
// Datagrams for UDP flows: only on a transport that has them AND a host that listed "gateway-datagram".
|
|
1563
1630
|
datagrams: () => {
|
|
1564
1631
|
const t = this.#transport;
|
|
1565
|
-
return t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
|
|
1632
|
+
return !this.#sessionSeal && t?.supportsDatagrams && this.hasFeature(GATEWAY_DATAGRAM_FEATURE) ? { send: (b) => t.sendDatagram(b), maxSize: () => t.maxDatagramSize } : null;
|
|
1566
1633
|
},
|
|
1567
1634
|
}));
|
|
1568
1635
|
}
|
|
@@ -1650,6 +1717,7 @@ export class WshClient {
|
|
|
1650
1717
|
*/
|
|
1651
1718
|
async openStream() {
|
|
1652
1719
|
this.#assertAuthenticated('openStream');
|
|
1720
|
+
if (this.#sessionSeal) throw new Error('openStream: a sealed session carries no client-opened data streams (their bytes are not frames)');
|
|
1653
1721
|
return this.#transport.openStream();
|
|
1654
1722
|
}
|
|
1655
1723
|
|
|
@@ -2380,14 +2448,18 @@ export class WshClient {
|
|
|
2380
2448
|
*
|
|
2381
2449
|
* @param {string} op - Operation: 'stat', 'list', 'read', 'write', 'mkdir', 'remove', 'rename'
|
|
2382
2450
|
* @param {string} path - File path
|
|
2383
|
-
* @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)
|
|
2384
2454
|
* @param {number} [timeout=10000]
|
|
2385
2455
|
* @returns {Promise<object>} FileResult response
|
|
2386
2456
|
*/
|
|
2387
2457
|
async fileOperation(op, path, opts = {}, timeout = DEFAULT_OPEN_TIMEOUT) {
|
|
2388
2458
|
this.#assertAuthenticated('fileOperation');
|
|
2459
|
+
assertTargetUsable(this, opts.target, 'fileOperation');
|
|
2460
|
+
const { target } = opts;
|
|
2389
2461
|
// wsh #85: a host that serves the `wsh-fs` rpc protocol is preferred over the FileOp/FileResult control path.
|
|
2390
|
-
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'))) {
|
|
2391
2463
|
let rpc = null;
|
|
2392
2464
|
try { rpc = await this.#fsChannel(); } catch { /* fall back to FileOp */ }
|
|
2393
2465
|
if (rpc) return this.#fileOperationRpc(rpc, op, path, opts, timeout);
|
|
@@ -2413,7 +2485,7 @@ export class WshClient {
|
|
|
2413
2485
|
const result = this.#waitForMessage([MSG.FILE_RESULT], timeout, `Timed out waiting for file ${op} result`, byChannel);
|
|
2414
2486
|
result.catch(() => {});
|
|
2415
2487
|
await this.#transport.sendControl(fileOpMsg({
|
|
2416
|
-
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,
|
|
2417
2489
|
}));
|
|
2418
2490
|
let off = 0;
|
|
2419
2491
|
do {
|
|
@@ -2427,7 +2499,7 @@ export class WshClient {
|
|
|
2427
2499
|
}
|
|
2428
2500
|
|
|
2429
2501
|
await this.#transport.sendControl(
|
|
2430
|
-
fileOpMsg({ channelId, op, path, offset: opts.offset, length: opts.length })
|
|
2502
|
+
fileOpMsg({ channelId, op, path, offset: opts.offset, length: opts.length, target })
|
|
2431
2503
|
);
|
|
2432
2504
|
return this.#waitForMessage(
|
|
2433
2505
|
[MSG.FILE_RESULT],
|
|
@@ -2689,10 +2761,11 @@ export class WshClient {
|
|
|
2689
2761
|
* @private
|
|
2690
2762
|
*/
|
|
2691
2763
|
#attachTransportHandlers(transport) {
|
|
2692
|
-
transport.onControl = (msg) => this.#
|
|
2764
|
+
transport.onControl = (msg) => this.#onTransportControl(msg);
|
|
2693
2765
|
transport.onClose = () => this.#handleTransportClose();
|
|
2694
2766
|
transport.onError = (err) => this.#handleTransportError(err);
|
|
2695
|
-
|
|
2767
|
+
// A datagram is not a frame: on a sealed session a relay could inject one, so none is heard (UDP uses the reliable path).
|
|
2768
|
+
transport.onDatagram = (bytes) => { if (!this.#sessionSeal) this.#gateway?.handleDatagram(bytes); };
|
|
2696
2769
|
}
|
|
2697
2770
|
|
|
2698
2771
|
/**
|
|
@@ -2853,6 +2926,90 @@ export class WshClient {
|
|
|
2853
2926
|
}
|
|
2854
2927
|
}
|
|
2855
2928
|
|
|
2929
|
+
// ── Internal: a sealed session (#155) ───────────────────────────────
|
|
2930
|
+
|
|
2931
|
+
/**
|
|
2932
|
+
* Whether this connection is to be sealed, decided from the ServerHello's features and the proven host key BEFORE
|
|
2933
|
+
* a credential is sent. `true` and a host that requires sealing (`'auto'`) fail here, with a sentence, when sealing
|
|
2934
|
+
* is not possible -- never by talking in the clear.
|
|
2935
|
+
* @param {false | 'auto' | true} mode
|
|
2936
|
+
* @param {string[]} features - the host's ServerHello features (`[]` when it sent none)
|
|
2937
|
+
* @param {boolean} haveKey - this login signs (a key login)
|
|
2938
|
+
* @returns {boolean}
|
|
2939
|
+
*/
|
|
2940
|
+
#planSealing(mode, features, haveKey) {
|
|
2941
|
+
if (mode === false) return false;
|
|
2942
|
+
if (mode === 'auto' && !features.includes(SESSION_SEAL_REQUIRED_FEATURE)) return false;
|
|
2943
|
+
const why = !features.includes(SESSION_SEAL_FEATURE)
|
|
2944
|
+
? `the host does not offer "${SESSION_SEAL_FEATURE}" (it needs a host key and a connection without client-opened data streams)`
|
|
2945
|
+
: !this.#hostKey?.publicKey
|
|
2946
|
+
? 'the host proved no host key to authenticate the exchange against'
|
|
2947
|
+
: !haveKey
|
|
2948
|
+
? 'a sealed session needs a key login (a password login has nothing to sign with)'
|
|
2949
|
+
: null;
|
|
2950
|
+
if (why) throw new Error(`sealed session: ${why} -- nothing was sent`);
|
|
2951
|
+
return true;
|
|
2952
|
+
}
|
|
2953
|
+
|
|
2954
|
+
/**
|
|
2955
|
+
* Seal this whole connection: a signed `KeyExchange` for the connection's session id (the login key signs this half,
|
|
2956
|
+
* the host's proven key the other), then every message but the keepalive leaves as an `EncryptedFrame` on channel 0,
|
|
2957
|
+
* in order. Until the key exists nothing but the key exchange may be sent, and nothing plain is heard.
|
|
2958
|
+
* @param {number} timeout
|
|
2959
|
+
*/
|
|
2960
|
+
async #sealSession(timeout) {
|
|
2961
|
+
const sessionId = this.#sessionId;
|
|
2962
|
+
const hostKey = this.#hostKey?.publicKey;
|
|
2963
|
+
if (!sessionId || !hostKey || !this.#signer) throw new Error('sealed session: no session id, host key or login key -- nothing was sent');
|
|
2964
|
+
const transport = this.#transport;
|
|
2965
|
+
const plainSend = transport.sendControl.bind(transport);
|
|
2966
|
+
let bridge = null;
|
|
2967
|
+
this.#sessionSeal = { sessionId, bridge: null };
|
|
2968
|
+
transport.sendControl = async (msg) => {
|
|
2969
|
+
if (msg.type === MSG.PING || msg.type === MSG.PONG) return plainSend(msg);
|
|
2970
|
+
if (bridge) return plainSend(await bridge.seal(msg));
|
|
2971
|
+
if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === sessionId) return plainSend(msg);
|
|
2972
|
+
throw new Error('sealed session: nothing is sent before the key exists');
|
|
2973
|
+
};
|
|
2974
|
+
const { sharedSecret } = await this.initiateE2E(sessionId, 'X25519+ML-KEM-768', timeout, {
|
|
2975
|
+
verifyPeer: hostKey, signAs: this.#signer, responderIdentity: hostKey,
|
|
2976
|
+
});
|
|
2977
|
+
bridge = new SealedBridge({ key: sharedSecret, sessionId, role: 'initiator', scope: 'session' });
|
|
2978
|
+
this.#sessionSeal = { sessionId, bridge };
|
|
2979
|
+
}
|
|
2980
|
+
|
|
2981
|
+
/**
|
|
2982
|
+
* Every message that arrives from the host itself passes here. On a sealed session only the key exchange (while the
|
|
2983
|
+
* key does not exist yet), the keepalive and frames of the session are heard: a relay in the middle can write any
|
|
2984
|
+
* plain message, so a plain one is dropped; a frame that does not open (flipped bit, replay, reorder, forged) is the
|
|
2985
|
+
* relay at work, and ends the connection.
|
|
2986
|
+
* @param {object} msg
|
|
2987
|
+
*/
|
|
2988
|
+
#onTransportControl(msg) {
|
|
2989
|
+
const seal = this.#sessionSeal;
|
|
2990
|
+
if (!seal || msg.type === MSG.PING || msg.type === MSG.PONG) { this.#handleControl(msg); return; }
|
|
2991
|
+
if (seal.bridge) {
|
|
2992
|
+
if (!seal.bridge.isFrame(msg)) {
|
|
2993
|
+
console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) on a sealed session`);
|
|
2994
|
+
return;
|
|
2995
|
+
}
|
|
2996
|
+
seal.bridge.open(msg).then(
|
|
2997
|
+
(inner) => { if (this.#sessionSeal === seal) this.#handleControl(inner); },
|
|
2998
|
+
(err) => this.#sealedFrameFailed(seal, err),
|
|
2999
|
+
);
|
|
3000
|
+
return;
|
|
3001
|
+
}
|
|
3002
|
+
if (msg.type === MSG.KEY_EXCHANGE && msg.session_id === seal.sessionId) { this.#handleControl(msg); return; }
|
|
3003
|
+
console.warn(`[wsh:client] dropping a plaintext message (type ${msg.type}) before the session is sealed`);
|
|
3004
|
+
}
|
|
3005
|
+
|
|
3006
|
+
#sealedFrameFailed(seal, err) {
|
|
3007
|
+
if (this.#sessionSeal !== seal || this.#state === STATE_CLOSED) return;
|
|
3008
|
+
this.#sessionSeal = { ...seal, failed: true };
|
|
3009
|
+
this.#emitError(new Error(`wsh: a sealed frame did not open (${err.message}); the session is closed`));
|
|
3010
|
+
this.#transport?.close().catch(() => {});
|
|
3011
|
+
}
|
|
3012
|
+
|
|
2856
3013
|
// ── Internal: auth handshake ────────────────────────────────────────
|
|
2857
3014
|
|
|
2858
3015
|
/**
|
|
@@ -2868,8 +3025,10 @@ export class WshClient {
|
|
|
2868
3025
|
* @returns {Promise<string>} Session ID
|
|
2869
3026
|
* @private
|
|
2870
3027
|
*/
|
|
2871
|
-
async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, requireChannelBinding = false, ...hostKeyOpts } = {}) {
|
|
3028
|
+
async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, requireChannelBinding = false, sealSession = 'auto', ...hostKeyOpts } = {}) {
|
|
2872
3029
|
if (!username) throw new Error('username is required');
|
|
3030
|
+
assertSealSession(sealSession);
|
|
3031
|
+
this.#sessionSeal = null;
|
|
2873
3032
|
const cred = await resolveSigner({ keyPair, signer });
|
|
2874
3033
|
this.#signer = cred;
|
|
2875
3034
|
this.#loginUsername = username;
|
|
@@ -2895,6 +3054,7 @@ export class WshClient {
|
|
|
2895
3054
|
}
|
|
2896
3055
|
|
|
2897
3056
|
let tempSessionId = null;
|
|
3057
|
+
let seal = false; // see connect()
|
|
2898
3058
|
|
|
2899
3059
|
if (firstResponse.type === MSG.SERVER_HELLO) {
|
|
2900
3060
|
tempSessionId = firstResponse.session_id;
|
|
@@ -2905,6 +3065,7 @@ export class WshClient {
|
|
|
2905
3065
|
: null;
|
|
2906
3066
|
challengeWait?.catch(() => {});
|
|
2907
3067
|
await this.#verifyHostKey(firstResponse, hostCtx);
|
|
3068
|
+
seal = this.#planSealing(sealSession, this.#serverFeatures, !!cred);
|
|
2908
3069
|
|
|
2909
3070
|
if (authMethod === AUTH_METHOD.PUBKEY) {
|
|
2910
3071
|
const challengeMsg = await challengeWait;
|
|
@@ -2914,6 +3075,7 @@ export class WshClient {
|
|
|
2914
3075
|
this.#authToken = challengeMsg.token || null;
|
|
2915
3076
|
this.#authTtl = Number(challengeMsg.ttl) || 0;
|
|
2916
3077
|
this.#state = STATE_AUTHENTICATED;
|
|
3078
|
+
if (seal) await this.#sealSession(timeout);
|
|
2917
3079
|
this.#startPing();
|
|
2918
3080
|
return this.#sessionId;
|
|
2919
3081
|
}
|
|
@@ -2934,6 +3096,7 @@ export class WshClient {
|
|
|
2934
3096
|
} else if (firstResponse.type === MSG.CHALLENGE) {
|
|
2935
3097
|
if (!cred) throw new Error('Server sent CHALLENGE but no key pair provided');
|
|
2936
3098
|
await this.#verifyHostKey(null, hostCtx);
|
|
3099
|
+
seal = this.#planSealing(sealSession, [], true);
|
|
2937
3100
|
|
|
2938
3101
|
// Challenge carries session_id directly — see connect()'s
|
|
2939
3102
|
// CHALLENGE branch for why. Keep tempSessionId as a fallback for
|
|
@@ -2964,6 +3127,7 @@ export class WshClient {
|
|
|
2964
3127
|
this.#authToken = authResult.token || null;
|
|
2965
3128
|
this.#authTtl = Number(authResult.ttl) || 0;
|
|
2966
3129
|
this.#state = STATE_AUTHENTICATED;
|
|
3130
|
+
if (seal) await this.#sealSession(timeout);
|
|
2967
3131
|
this.#startPing();
|
|
2968
3132
|
|
|
2969
3133
|
return this.#sessionId;
|
|
@@ -3053,6 +3217,10 @@ export class WshClient {
|
|
|
3053
3217
|
const serverChannelId = msg.channel_id ?? pending.requestedChannelId;
|
|
3054
3218
|
const streamIds = msg.stream_ids ?? {};
|
|
3055
3219
|
const dataMode = msg.data_mode === 'virtual' ? 'virtual' : 'stream';
|
|
3220
|
+
if (this.#sessionSeal && dataMode !== 'virtual') {
|
|
3221
|
+
pending.reject(new Error('Failed to open session: the host answered with a data stream, and a sealed session carries none'));
|
|
3222
|
+
return;
|
|
3223
|
+
}
|
|
3056
3224
|
const capabilities = Array.isArray(msg.capabilities) ? msg.capabilities : [];
|
|
3057
3225
|
|
|
3058
3226
|
const session = new WshSession(
|
package/src/features.mjs
CHANGED
|
@@ -26,3 +26,18 @@ export const MCP_CANCEL_FEATURE = 'mcp-cancel';
|
|
|
26
26
|
*/
|
|
27
27
|
export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
|
|
28
28
|
export const EXEC_PIPES_FEATURE = 'exec-pipes';
|
|
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
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Host feature (#155): this host seals the whole session end to end when asked (a signed `KeyExchange` for the
|
|
39
|
+
* connection's session id, then every message but the keepalive as an `EncryptedFrame` on channel 0).
|
|
40
|
+
*/
|
|
41
|
+
export const SESSION_SEAL_FEATURE = 'e2e-session';
|
|
42
|
+
/** Host feature (#155): this host serves nothing on a session that is not sealed. */
|
|
43
|
+
export const SESSION_SEAL_REQUIRED_FEATURE = 'e2e-session-required';
|
package/src/gateway-client.mjs
CHANGED
|
@@ -91,8 +91,10 @@ export class GatewayConnections {
|
|
|
91
91
|
onRemoteClose: datagram ? () => channel.destroy() : undefined,
|
|
92
92
|
onData,
|
|
93
93
|
sendData: (data) => this.#send(gatewayDataMsg({ gatewayId: id, data })),
|
|
94
|
-
sendCredit: (n) => this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n })),
|
|
95
|
-
|
|
94
|
+
sendCredit: (n) => Promise.resolve(this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n }))).catch(() => {}),
|
|
95
|
+
// Best effort and not awaited by the channel: on a sealed session (#155) the send finishes after the frame is
|
|
96
|
+
// sealed, so a connection that closed meanwhile must not surface as an unhandled rejection.
|
|
97
|
+
sendClose: (reason) => Promise.resolve(this.#send(gatewayCloseMsg({ gatewayId: id, reason }))).catch(() => {}),
|
|
96
98
|
onClose: () => { this.#channels.delete(id); this.#udp.delete(id); },
|
|
97
99
|
});
|
|
98
100
|
this.#channels.set(id, channel);
|
|
@@ -143,11 +145,16 @@ export class GatewayConnections {
|
|
|
143
145
|
return this.#open((id) => openUnixMsg({ gatewayId: id, path }), opts);
|
|
144
146
|
}
|
|
145
147
|
|
|
146
|
-
/** 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`). */
|
|
147
149
|
async openEndpoint(name, opts) {
|
|
148
150
|
this.#need('gateway-endpoints', 'named endpoints');
|
|
149
151
|
if (typeof name !== 'string' || !name) throw new TypeError('openEndpoint: name must be a non-empty string');
|
|
150
|
-
|
|
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);
|
|
151
158
|
}
|
|
152
159
|
|
|
153
160
|
/** Connect to host:port FROM THE HOST (the gateway's TCP egress, subject to the host's allow list). */
|
package/src/host-backends.mjs
CHANGED
|
@@ -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
|
-
*
|
|
56
|
-
*
|
|
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
|
|
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}). */
|