@johnhenry/wsh 0.30.0 → 0.32.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 +93 -15
- package/package.json +5 -1
- package/src/auth.mjs +59 -0
- package/src/client.mjs +83 -30
- package/src/index.d.ts +57 -3
- package/src/index.mjs +1 -0
- package/src/memory-host.d.ts +48 -0
- package/src/memory-host.mjs +175 -0
- package/src/recording.mjs +18 -10
- package/src/server/connection.mjs +3 -4
- package/src/server/constants.mjs +10 -0
- package/src/server/fs.mjs +2 -1
- package/src/server/gateway.mjs +11 -4
- package/src/server/index.d.ts +23 -0
- package/src/server/index.mjs +56 -17
- package/src/server/pty.mjs +1 -1
- package/src/server/sessions.mjs +2 -1
- package/src/server/socket.mjs +73 -0
- package/src/session.mjs +36 -1
- package/src/transport-ws.mjs +18 -2
package/README.md
CHANGED
|
@@ -61,22 +61,39 @@ Or via CDN:
|
|
|
61
61
|
- **Reverse mode** -- register as a peer (via a signed peer record) and accept incoming connections through a relay
|
|
62
62
|
- **File transfer** -- scp-like upload/download as `FileChunk` control messages in 64KB chunks
|
|
63
63
|
- **MCP bridge** -- discover and invoke remote MCP tools through the control channel
|
|
64
|
-
- **Session recording** -- own JSON schema (not asciicast
|
|
64
|
+
- **Session recording** -- own JSON schema (asciicast-v2-shaped, not a playable asciicast file -- see note below) recording and playback with seek/pause/resume
|
|
65
65
|
- **Key management** -- IndexedDB storage with OPFS encrypted backup (PBKDF2 + AES-256-GCM)
|
|
66
66
|
- **98 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
|
|
67
67
|
|
|
68
|
-
> **Session recording is not asciicast
|
|
69
|
-
>
|
|
70
|
-
>
|
|
71
|
-
>
|
|
72
|
-
>
|
|
73
|
-
>
|
|
74
|
-
>
|
|
75
|
-
>
|
|
76
|
-
>
|
|
77
|
-
>
|
|
78
|
-
>
|
|
79
|
-
> (
|
|
68
|
+
> **Session recording is asciicast-v2-shaped, but not an asciicast file.**
|
|
69
|
+
> The JS `SessionRecorder.toJSON()` export borrows asciicast v2's vocabulary --
|
|
70
|
+
> `version: 2`, `width`, `height`, `timestamp`, `env`, and events as
|
|
71
|
+
> `[seconds, "o" | "i" | "r", data]` -- so it is easy to convert, but it is not
|
|
72
|
+
> something `asciinema play` can read as-is:
|
|
73
|
+
>
|
|
74
|
+
> - it is **one JSON document** with an `events` array; asciicast v2 is
|
|
75
|
+
> newline-delimited JSON (a header line, then one event per line);
|
|
76
|
+
> - the header carries wsh's own `sessionId`, and `width`/`height` follow the
|
|
77
|
+
> latest resize rather than the size at the start;
|
|
78
|
+
> - session lifecycle events (`open`, `exit`) use codes asciicast v2 does not
|
|
79
|
+
> define (the Rust recorder also has `Start`/`Exit`/`Snapshot`, and uses a
|
|
80
|
+
> different, incompatible schema from the JS one);
|
|
81
|
+
> - `RecordingExport`'s `format: "asciicast"` option is accepted on the wire but
|
|
82
|
+
> not implemented server-side -- it returns the same custom JSONL as
|
|
83
|
+
> `format: "jsonl"`.
|
|
84
|
+
>
|
|
85
|
+
> To play a JS recording in asciinema, write the header and the `o`/`i`/`r`
|
|
86
|
+
> events out as lines (lossy: lifecycle events are dropped):
|
|
87
|
+
>
|
|
88
|
+
> ```js
|
|
89
|
+
> const { version, width, height, timestamp, env, events } = recorder.toJSON();
|
|
90
|
+
> const cast = [JSON.stringify({ version, width, height, timestamp, env }),
|
|
91
|
+
> ...events.filter((e) => 'oir'.includes(e[1])).map((e) => JSON.stringify(e))].join('\n') + '\n';
|
|
92
|
+
> // write `cast` to session.cast, then: asciinema play session.cast
|
|
93
|
+
> ```
|
|
94
|
+
>
|
|
95
|
+
> A first-class `.cast` exporter is not provided; the conversion above is the
|
|
96
|
+
> supported path (it is covered by `test/recording-format.test.mjs`).
|
|
80
97
|
|
|
81
98
|
## Wire Protocol: QMux
|
|
82
99
|
|
|
@@ -153,6 +170,23 @@ arrives on it, so against a host that does not advertise `stream-announce`
|
|
|
153
170
|
the client writes a one-byte primer for you (a host that strips it, as those
|
|
154
171
|
hosts do). Pass `primer: false` to never send it.
|
|
155
172
|
|
|
173
|
+
### Stdin and EOF
|
|
174
|
+
|
|
175
|
+
`stdin` feeds the command and then closes its write side, so `cat`, `wc -c` and `sh -s` finish:
|
|
176
|
+
|
|
177
|
+
```js
|
|
178
|
+
const { stdout } = await WshClient.exec(url, 'wc -c', { username, keyPair, stdin: new Uint8Array(1000) });
|
|
179
|
+
// stdin: a string, a Uint8Array, a ReadableStream, or an (async) iterable of strings / bytes
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
On an open exec session, `await session.write(data); await session.closeStdin()` sends EOF without closing the
|
|
183
|
+
session: output keeps arriving and `onExit` / `onClose` fire as usual. Without `stdin`, `exec` never touches stdin.
|
|
184
|
+
|
|
185
|
+
EOF is the end of the session's stdin data stream, so it needs a **stream-mode** host: `@johnhenry/wsh/server` (any
|
|
186
|
+
version, nothing to upgrade server-side). The Rust `wsh-server` runs exec on a PTY with stdin carried as control
|
|
187
|
+
messages (`data_mode: virtual`) and has no EOF message; `closeStdin()` throws there and `exec({ stdin })` rejects
|
|
188
|
+
rather than silently hanging (tracked in #105).
|
|
189
|
+
|
|
156
190
|
## Node Server
|
|
157
191
|
|
|
158
192
|
`@johnhenry/wsh/server` is a Node host for the same protocol, over WebSocket
|
|
@@ -201,6 +235,50 @@ messages whose `type` is a string, from authenticated connections only. On a rel
|
|
|
201
235
|
`relay: { onUnreachable(from, targetFingerprint, request) }` is told when an operator asked for a peer that is not
|
|
202
236
|
registered (the operator still gets `no such peer`), so the host can reach that peer another way, such as a Web Push.
|
|
203
237
|
|
|
238
|
+
### Pre-upgraded transports: `accept()`
|
|
239
|
+
|
|
240
|
+
`createWshServer()` normally opens its own listener. If your application already owns the HTTP server (or Worker, or
|
|
241
|
+
test harness) and has upgraded the connection itself, hand the socket over instead of bridging it to a per-session
|
|
242
|
+
loopback listener (which any local process could also connect to):
|
|
243
|
+
|
|
244
|
+
```js
|
|
245
|
+
const wsh = createWshServer({ auth: { authorizedKeys }, exec: true }); // no listen()
|
|
246
|
+
wss.on('connection', (ws, req) => wsh.accept(ws, { remote: { address: req.socket.remoteAddress } }));
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
`accept(socket, { remote })` takes any WebSocket-like duplex (`send`, `close`, `readyState`, and `on` or
|
|
250
|
+
`addEventListener`): a `ws` socket, a browser/Worker `WebSocket`, a test double. It applies the same auth, features,
|
|
251
|
+
rate limit and session registry as `listen()`'s connections, may be mixed with `listen()`, and resolves to
|
|
252
|
+
`{ close() }`. `remote.address` keys the password-failure throttle (sockets without one share a key). `server.close()`
|
|
253
|
+
drops every accepted socket.
|
|
254
|
+
|
|
255
|
+
### In-memory host (`@johnhenry/wsh/memory`)
|
|
256
|
+
|
|
257
|
+
A browser-safe host for demos and tests: no sockets, no ports, no Node (nothing in its import graph is `node:*` or `ws`).
|
|
258
|
+
|
|
259
|
+
```js
|
|
260
|
+
import { createMemoryHost } from '@johnhenry/wsh/memory';
|
|
261
|
+
|
|
262
|
+
const host = createMemoryHost({
|
|
263
|
+
auth: { authorizedKeys: [rawPublicKey] }, // same shapes as createWshServer
|
|
264
|
+
exec: async (command, io) => { await io.write(`ran ${command}\n`); return 0; },
|
|
265
|
+
});
|
|
266
|
+
const client = await host.connect({ username: 'demo', keyPair }); // or { signer } / { password }
|
|
267
|
+
const session = await client.openSession({ type: 'exec', command: 'hi' });
|
|
268
|
+
session.onData = (d) => console.log(new TextDecoder().decode(d)); // "ran hi"
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
It is the real connection handler speaking QMux over an in-memory socket pair, so the client code you test is the code
|
|
272
|
+
you ship. `host.createClient()` / `host.WebSocket` / `host.accept(socket)` / `createSocketPair()` are the lower-level pieces.
|
|
273
|
+
Supported: `auth`, `exec` (a function; there is no shell), `mcp`, `extensions`. Not available in memory: `pty`, `fs`,
|
|
274
|
+
`gateway`, `relay`, `sessions`, `rpc`, `hostKey` and WebTransport (use `@johnhenry/wsh/server`).
|
|
275
|
+
|
|
276
|
+
### Signing with a page-held signer
|
|
277
|
+
|
|
278
|
+
`connect()`, `WshClient.exec()` and `connectReverse()` take `signer: { publicKey, sign(data) }` instead of `keyPair`
|
|
279
|
+
(not both): `publicKey` is the raw 32-byte Ed25519 key or a public `CryptoKey`, `sign` returns the 64-byte signature
|
|
280
|
+
(sync or async). For keys that live in a wallet, a hardware token or another realm and are not a `CryptoKeyPair`.
|
|
281
|
+
|
|
204
282
|
### WebTransport listener
|
|
205
283
|
|
|
206
284
|
The client's ladder prefers WebTransport (`https://`) and falls back to `wss://`;
|
|
@@ -936,7 +1014,7 @@ so options the platform gains later need no change here.
|
|
|
936
1014
|
| `WshMcpBridge` | Remote MCP tool discovery and invocation |
|
|
937
1015
|
| `RpcChannel` / `RpcError` | Typed RPC channel (JSON-RPC 2.0 over a CBOR sequence): `client.openRpc(protocol)`; `RPC_FEATURE`, `rpcProtocolFeature(name)`, `RPC_ERROR`, `CborSequenceDecoder` |
|
|
938
1016
|
| `mcpClientTransport()` / `mcpServerAdapter()` (`/server`) | MCP SDK `Transport` over an `rpc` channel |
|
|
939
|
-
| `SessionRecorder` | Record PTY I/O with timestamps (
|
|
1017
|
+
| `SessionRecorder` | Record PTY I/O with timestamps (asciicast-v2-shaped JSON; convert to play in asciinema, see the note under Session recording) |
|
|
940
1018
|
| `SessionPlayer` | Replay recordings with original timing |
|
|
941
1019
|
| `generateKeyPair()` | Create Ed25519 key pair via Web Crypto |
|
|
942
1020
|
| `sign(privateKey, message)` / `verify(publicKey, signature, message)` | Raw Ed25519 sign / verify. This positional order (WebCrypto's) is the one canonical form across wsh, raijin and browsermesh |
|
|
@@ -1003,7 +1081,7 @@ than left to be found.
|
|
|
1003
1081
|
| Attach / resume | `attachSession()`, `resumeSession()`, `WshSession.seq` | `attach_session()`, `resume_session()` | **Wire-unified** (`Attach`/`Resume`/`Presence`); `seq` = cumulative output bytes. `@johnhenry/wsh/server` honours `last_seq` (bounded ring, gap errors) and answers Presence with `channel_id`/`seq`; the Rust `wsh-server` does the same (`rust-v0.2.0`+; fixed 256 KiB ring) |
|
|
1004
1082
|
| Reverse-connect / relay peer | `connectReverse()`, `trustRelayPeer()`; `@johnhenry/wsh/server`: `relay` option and `createReverseHost()` | `wsh reverse`, `wsh agent` (persistent, with startup-unit install) | **Wire-unified** (registration, discovery, signed peer records); **daemonization is CLI-only** -- a browser tab cannot be a background OS service. The Node relay is default-deny and bridges one operator per peer unless `maxOperatorsPerPeer` is raised (`busy:` reasons say so); E2E and bridged feature gates need `rust-v0.3.0`+ on the Rust side; several operators per peer and the signed `KeyExchange` are JS-relay only for now |
|
|
1005
1083
|
| Post-quantum E2E (experimental) | `initiateE2E()` (WebCrypto ML-KEM-768 or `@noble/post-quantum` fallback) | `E2eKeyExchange` (`ml-kem` crate) | **Wire-unified** algorithm and transcript; key material backends differ by platform necessity |
|
|
1006
|
-
| Session recording/replay | `SessionRecorder`/`SessionPlayer` (asciicast
|
|
1084
|
+
| Session recording/replay | `SessionRecorder`/`SessionPlayer` (asciicast-v2-shaped JSON) | none | **JS-only** -- no current Rust consumer needs playback; the vocabulary is asciicast v2's, so a Rust port could share it |
|
|
1007
1085
|
| Self-signed cert pinning | `serverCertificateHashes` (WebTransport option) | N/A -- Rust dials a cert its own TLS stack already trusts, or `--generate-cert`'s self-signed cert out of band | **Deliberately not unified** -- this is a browser-specific WebTransport API shape, not a wire-protocol concept |
|
|
1008
1086
|
|
|
1009
1087
|
### Build and test
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/wsh",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.0",
|
|
4
4
|
"description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
"./server": {
|
|
13
13
|
"types": "./src/server/index.d.ts",
|
|
14
14
|
"import": "./src/server/index.mjs"
|
|
15
|
+
},
|
|
16
|
+
"./memory": {
|
|
17
|
+
"types": "./src/memory-host.d.ts",
|
|
18
|
+
"import": "./src/memory-host.mjs"
|
|
15
19
|
}
|
|
16
20
|
},
|
|
17
21
|
"types": "./src/index.d.ts",
|
package/src/auth.mjs
CHANGED
|
@@ -159,6 +159,65 @@ export async function sign(privateKey, data) {
|
|
|
159
159
|
return new Uint8Array(sig);
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
+
/**
|
|
163
|
+
* A page-held signer: an object that can sign but need not expose a private key.
|
|
164
|
+
* `publicKey` is the raw 32-byte Ed25519 key (or a `CryptoKey`); `sign(data)` returns the
|
|
165
|
+
* 64-byte signature, synchronously or not. For keys held by a wallet, a hardware token, a
|
|
166
|
+
* Worker, or anything else that is not a `CryptoKeyPair`.
|
|
167
|
+
*
|
|
168
|
+
* @typedef {{ publicKey: Uint8Array | CryptoKey, sign: (data: Uint8Array) => Uint8Array | Promise<Uint8Array> }} WshSigner
|
|
169
|
+
*/
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Turn `{ keyPair }` or `{ signer }` into one `{ publicKeyRaw, sign }` pair, or `null` when neither is given.
|
|
173
|
+
* Throws a TypeError for both together or for a malformed signer.
|
|
174
|
+
*
|
|
175
|
+
* @param {{ keyPair?: CryptoKeyPair, signer?: WshSigner }} credentials
|
|
176
|
+
* @returns {Promise<{ publicKeyRaw: Uint8Array, sign: (data: Uint8Array) => Promise<Uint8Array> } | null>}
|
|
177
|
+
*/
|
|
178
|
+
export async function resolveSigner({ keyPair, signer } = {}) {
|
|
179
|
+
if (keyPair && signer) throw new TypeError('pass either keyPair or signer, not both');
|
|
180
|
+
if (keyPair) {
|
|
181
|
+
return { publicKeyRaw: await exportPublicKeyRaw(keyPair.publicKey), sign: (data) => sign(keyPair.privateKey, data) };
|
|
182
|
+
}
|
|
183
|
+
if (!signer) return null;
|
|
184
|
+
if (typeof signer !== 'object' || typeof signer.sign !== 'function') {
|
|
185
|
+
throw new TypeError('signer must be { publicKey, sign(data) }');
|
|
186
|
+
}
|
|
187
|
+
let publicKeyRaw;
|
|
188
|
+
if (signer.publicKey instanceof Uint8Array) publicKeyRaw = signer.publicKey;
|
|
189
|
+
else if (signer.publicKey && typeof signer.publicKey === 'object' && signer.publicKey.type === 'public') publicKeyRaw = await exportPublicKeyRaw(signer.publicKey);
|
|
190
|
+
if (!publicKeyRaw || publicKeyRaw.byteLength !== 32) {
|
|
191
|
+
throw new TypeError('signer.publicKey must be a raw 32-byte Ed25519 key or a public CryptoKey');
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
publicKeyRaw,
|
|
195
|
+
sign: async (data) => {
|
|
196
|
+
const sig = await signer.sign(data);
|
|
197
|
+
if (!(sig instanceof Uint8Array) || sig.byteLength !== 64) throw new TypeError('signer.sign() must return a 64-byte Ed25519 signature');
|
|
198
|
+
return sig;
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* `signChallenge` for a resolved signer (see `resolveSigner`).
|
|
205
|
+
* @returns {Promise<{ signature: Uint8Array, publicKeyRaw: Uint8Array }>}
|
|
206
|
+
*/
|
|
207
|
+
export async function signChallengeWith(signer, sessionId, nonce, opts) {
|
|
208
|
+
const transcript = await buildTranscript(sessionId, nonce, opts);
|
|
209
|
+
return { signature: await signer.sign(transcript), publicKeyRaw: signer.publicKeyRaw };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* `signPeerRecord` for a resolved signer (see `resolveSigner`).
|
|
214
|
+
* @returns {Promise<{ signature: Uint8Array, publicKeyRaw: Uint8Array }>}
|
|
215
|
+
*/
|
|
216
|
+
export async function signPeerRecordWith(signer, record) {
|
|
217
|
+
const transcript = await buildPeerRecordTranscript(record);
|
|
218
|
+
return { signature: await signer.sign(transcript), publicKeyRaw: signer.publicKeyRaw };
|
|
219
|
+
}
|
|
220
|
+
|
|
162
221
|
/**
|
|
163
222
|
* Verify an Ed25519 signature.
|
|
164
223
|
* @param {CryptoKey} publicKey
|
package/src/client.mjs
CHANGED
|
@@ -37,7 +37,7 @@ import {
|
|
|
37
37
|
sessionGrant as sessionGrantMsg, sessionRevoke as sessionRevokeMsg,
|
|
38
38
|
isRelayForwardable,
|
|
39
39
|
} from './messages.mjs';
|
|
40
|
-
import {
|
|
40
|
+
import { resolveSigner, signChallengeWith, signPeerRecordWith, verifyPeerRecord, importPublicKeyRaw, fingerprint as computeFingerprint } from './auth.mjs';
|
|
41
41
|
import { generateMlKemKeyPair, mlKemEncapsulate, mlKemDecapsulate } from './mlkem.mjs';
|
|
42
42
|
import { compareBytes, combineHybridSecret, verifyKeyExchangeSignature } from './e2e-exchange.mjs';
|
|
43
43
|
import { WshSession } from './session.mjs';
|
|
@@ -173,6 +173,42 @@ async function normalizeExpectedHostKey(v) {
|
|
|
173
173
|
|
|
174
174
|
// ── Client class ──────────────────────────────────────────────────────
|
|
175
175
|
|
|
176
|
+
const STDIN_CHUNK = 64 * 1024;
|
|
177
|
+
|
|
178
|
+
function assertStdinSource(stdin) {
|
|
179
|
+
if (typeof stdin === 'string' || stdin instanceof Uint8Array) return;
|
|
180
|
+
if (stdin && (typeof stdin.getReader === 'function' || typeof stdin[Symbol.asyncIterator] === 'function' || typeof stdin[Symbol.iterator] === 'function')) return;
|
|
181
|
+
throw new TypeError('exec: stdin must be a string, Uint8Array, ReadableStream or (async) iterable of those');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Write `stdin` to `session` in bounded chunks, then close the write side (EOF). */
|
|
185
|
+
async function pumpStdin(session, stdin) {
|
|
186
|
+
const send = async (chunk) => {
|
|
187
|
+
if (typeof chunk === 'string') chunk = new TextEncoder().encode(chunk);
|
|
188
|
+
if (!(chunk instanceof Uint8Array)) throw new TypeError('exec: stdin chunks must be strings or Uint8Arrays');
|
|
189
|
+
for (let i = 0; i < chunk.byteLength; i += STDIN_CHUNK) {
|
|
190
|
+
await session.write(chunk.subarray(i, i + STDIN_CHUNK));
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
if (typeof stdin === 'string' || stdin instanceof Uint8Array) {
|
|
194
|
+
await send(stdin);
|
|
195
|
+
} else if (typeof stdin.getReader === 'function') {
|
|
196
|
+
const reader = stdin.getReader();
|
|
197
|
+
try {
|
|
198
|
+
for (;;) {
|
|
199
|
+
const { value, done } = await reader.read();
|
|
200
|
+
if (done) break;
|
|
201
|
+
await send(value);
|
|
202
|
+
}
|
|
203
|
+
} finally {
|
|
204
|
+
reader.releaseLock?.();
|
|
205
|
+
}
|
|
206
|
+
} else {
|
|
207
|
+
for await (const chunk of stdin) await send(chunk);
|
|
208
|
+
}
|
|
209
|
+
await session.closeStdin();
|
|
210
|
+
}
|
|
211
|
+
|
|
176
212
|
export class WshClient {
|
|
177
213
|
|
|
178
214
|
/** @type {'disconnected'|'connecting'|'connected'|'authenticated'|'closed'} */
|
|
@@ -467,7 +503,8 @@ export class WshClient {
|
|
|
467
503
|
* @param {string} url - Server URL (https:// for WebTransport, wss:// or ws:// for WebSocket)
|
|
468
504
|
* @param {object} opts
|
|
469
505
|
* @param {string} opts.username - Username for authentication
|
|
470
|
-
* @param {CryptoKeyPair} [opts.keyPair]
|
|
506
|
+
* @param {CryptoKeyPair} [opts.keyPair]
|
|
507
|
+
* @param {import('./auth.mjs').WshSigner} [opts.signer] - Page-held signer `{ publicKey, sign(data) }` instead of `keyPair`.
|
|
471
508
|
* @param {string} [opts.password] - Password for password auth
|
|
472
509
|
* @param {'wt'|'ws'|'auto'} [opts.transport] - Force a specific transport
|
|
473
510
|
* @param {object} [opts.webTransport] - Options forwarded to the
|
|
@@ -493,15 +530,16 @@ export class WshClient {
|
|
|
493
530
|
* @param {Function} [opts.onHostKey] - Per-connect `onHostKey`.
|
|
494
531
|
* @returns {Promise<string>} The server-assigned session ID
|
|
495
532
|
*/
|
|
496
|
-
async connect(url, { username, keyPair, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, ...hostKeyOpts } = {}) {
|
|
533
|
+
async connect(url, { username, keyPair, signer, password, transport: transportHint, webTransport, timeout = DEFAULT_AUTH_TIMEOUT, ...hostKeyOpts } = {}) {
|
|
497
534
|
if (this.#state !== STATE_DISCONNECTED && this.#state !== STATE_CLOSED) {
|
|
498
535
|
throw new Error(`Client already ${this.#state}`);
|
|
499
536
|
}
|
|
500
537
|
if (!username) {
|
|
501
538
|
throw new Error('username is required');
|
|
502
539
|
}
|
|
503
|
-
|
|
504
|
-
|
|
540
|
+
const cred = await resolveSigner({ keyPair, signer });
|
|
541
|
+
if (!cred && !password) {
|
|
542
|
+
throw new Error('Either keyPair, signer or password is required for authentication');
|
|
505
543
|
}
|
|
506
544
|
|
|
507
545
|
this.#state = STATE_CONNECTING;
|
|
@@ -519,7 +557,7 @@ export class WshClient {
|
|
|
519
557
|
this.#state = STATE_CONNECTED;
|
|
520
558
|
|
|
521
559
|
// ── Auth handshake ────────────────────────────────────────────
|
|
522
|
-
const authMethod =
|
|
560
|
+
const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
|
|
523
561
|
const hostKeyNonce = newHostKeyNonce();
|
|
524
562
|
await transport.sendControl(
|
|
525
563
|
hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce] })
|
|
@@ -568,9 +606,8 @@ export class WshClient {
|
|
|
568
606
|
// Sign the challenge. Challenge.session_id (not the one from
|
|
569
607
|
// ServerHello) is authoritative for the transcript — see the
|
|
570
608
|
// comment in the CHALLENGE-first branch below for why.
|
|
571
|
-
const { signature, publicKeyRaw } = await
|
|
572
|
-
|
|
573
|
-
keyPair.publicKey,
|
|
609
|
+
const { signature, publicKeyRaw } = await signChallengeWith(
|
|
610
|
+
cred,
|
|
574
611
|
challengeMsg.session_id,
|
|
575
612
|
challengeMsg.nonce,
|
|
576
613
|
{ username }
|
|
@@ -595,7 +632,7 @@ export class WshClient {
|
|
|
595
632
|
} else if (firstResponse.type === MSG.CHALLENGE) {
|
|
596
633
|
// Some servers skip SERVER_HELLO and go straight to CHALLENGE.
|
|
597
634
|
await this.#verifyHostKey(null, hostCtx);
|
|
598
|
-
if (authMethod !== AUTH_METHOD.PUBKEY || !
|
|
635
|
+
if (authMethod !== AUTH_METHOD.PUBKEY || !cred) {
|
|
599
636
|
throw new Error('Server sent CHALLENGE but no key pair was provided');
|
|
600
637
|
}
|
|
601
638
|
|
|
@@ -607,9 +644,8 @@ export class WshClient {
|
|
|
607
644
|
// tempSessionId as a fallback for this.#sessionId below in case
|
|
608
645
|
// AUTH_OK's own session_id is ever absent.
|
|
609
646
|
tempSessionId = firstResponse.session_id;
|
|
610
|
-
const { signature, publicKeyRaw } = await
|
|
611
|
-
|
|
612
|
-
keyPair.publicKey,
|
|
647
|
+
const { signature, publicKeyRaw } = await signChallengeWith(
|
|
648
|
+
cred,
|
|
613
649
|
firstResponse.session_id,
|
|
614
650
|
firstResponse.nonce,
|
|
615
651
|
{ username }
|
|
@@ -996,20 +1032,27 @@ export class WshClient {
|
|
|
996
1032
|
* @param {object} opts
|
|
997
1033
|
* @param {string} opts.username
|
|
998
1034
|
* @param {CryptoKeyPair} [opts.keyPair]
|
|
1035
|
+
* @param {import('./auth.mjs').WshSigner} [opts.signer] - Page-held signer `{ publicKey, sign(data) }` instead of `keyPair`.
|
|
999
1036
|
* @param {string} [opts.password]
|
|
1000
1037
|
* @param {number} [opts.timeout=60000] - Overall timeout in ms
|
|
1001
1038
|
* @param {boolean} [opts.primer=true] - See `openSession({ primer })`
|
|
1039
|
+
* @param {string|Uint8Array|ReadableStream|AsyncIterable|Iterable} [opts.stdin] - Input for the
|
|
1040
|
+
* command. It is written, then stdin is closed (EOF), so `cat`, `wc -c` and `sh -s` finish.
|
|
1041
|
+
* Omitted: stdin is never touched (unchanged behaviour). Needs a stream-mode host.
|
|
1002
1042
|
* @returns {Promise<{stdout: Uint8Array, exitCode: number}>}
|
|
1003
1043
|
*/
|
|
1004
|
-
static async exec(url, command, { username, keyPair, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, ...hostKeyOpts } = {}) {
|
|
1044
|
+
static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, ...hostKeyOpts } = {}) {
|
|
1045
|
+
if (stdin !== undefined) assertStdinSource(stdin);
|
|
1005
1046
|
const client = new WshClient();
|
|
1006
1047
|
const chunks = [];
|
|
1007
1048
|
let exitCode = -1;
|
|
1008
1049
|
|
|
1009
1050
|
try {
|
|
1010
|
-
await client.connect(url, { username, keyPair, password, ...hostKeyOpts });
|
|
1051
|
+
await client.connect(url, { username, keyPair, signer, password, ...hostKeyOpts });
|
|
1011
1052
|
|
|
1012
|
-
|
|
1053
|
+
// The first stdin byte (or the EOF itself) announces the data stream to a
|
|
1054
|
+
// legacy host, so the primer byte is only needed when there is no stdin.
|
|
1055
|
+
const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false });
|
|
1013
1056
|
|
|
1014
1057
|
await new Promise((resolve, reject) => {
|
|
1015
1058
|
const timer = setTimeout(() => {
|
|
@@ -1028,6 +1071,13 @@ export class WshClient {
|
|
|
1028
1071
|
clearTimeout(timer);
|
|
1029
1072
|
resolve();
|
|
1030
1073
|
};
|
|
1074
|
+
|
|
1075
|
+
if (stdin !== undefined) {
|
|
1076
|
+
pumpStdin(session, stdin).catch((err) => {
|
|
1077
|
+
clearTimeout(timer);
|
|
1078
|
+
reject(err);
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1031
1081
|
});
|
|
1032
1082
|
|
|
1033
1083
|
} finally {
|
|
@@ -1056,6 +1106,7 @@ export class WshClient {
|
|
|
1056
1106
|
* @param {object} opts
|
|
1057
1107
|
* @param {string} opts.username
|
|
1058
1108
|
* @param {CryptoKeyPair} [opts.keyPair]
|
|
1109
|
+
* @param {import('./auth.mjs').WshSigner} [opts.signer] - Page-held signer `{ publicKey, sign(data) }` instead of `keyPair`.
|
|
1059
1110
|
* @param {string} [opts.password]
|
|
1060
1111
|
* @param {object} [opts.expose] - Capabilities to expose { shell, exec, fs, tools }
|
|
1061
1112
|
* @param {string} [opts.peerType]
|
|
@@ -1069,6 +1120,7 @@ export class WshClient {
|
|
|
1069
1120
|
async connectReverse(url, {
|
|
1070
1121
|
username,
|
|
1071
1122
|
keyPair,
|
|
1123
|
+
signer,
|
|
1072
1124
|
password,
|
|
1073
1125
|
webTransport,
|
|
1074
1126
|
expose = {},
|
|
@@ -1081,7 +1133,7 @@ export class WshClient {
|
|
|
1081
1133
|
...hostKeyOpts
|
|
1082
1134
|
} = {}) {
|
|
1083
1135
|
// Authenticate normally first.
|
|
1084
|
-
const sessionId = await this.connect(url, { username, keyPair, password, webTransport, ...hostKeyOpts });
|
|
1136
|
+
const sessionId = await this.connect(url, { username, keyPair, signer, password, webTransport, ...hostKeyOpts });
|
|
1085
1137
|
|
|
1086
1138
|
// Build capabilities list from expose options.
|
|
1087
1139
|
const capabilities = [];
|
|
@@ -1091,10 +1143,9 @@ export class WshClient {
|
|
|
1091
1143
|
if (expose.tools) capabilities.push('tools');
|
|
1092
1144
|
|
|
1093
1145
|
// Export public key for peer identification.
|
|
1146
|
+
const cred = await resolveSigner({ keyPair, signer });
|
|
1094
1147
|
let publicKey = null;
|
|
1095
|
-
if (
|
|
1096
|
-
publicKey = await exportPublicKeyRaw(keyPair.publicKey);
|
|
1097
|
-
}
|
|
1148
|
+
if (cred) publicKey = cred.publicKeyRaw;
|
|
1098
1149
|
|
|
1099
1150
|
const effectiveShellBackend = shellBackend || (expose.shell ? 'virtual-shell' : 'exec-only');
|
|
1100
1151
|
const record = {
|
|
@@ -1118,8 +1169,8 @@ export class WshClient {
|
|
|
1118
1169
|
// (see auth.mjs's "Signed peer records" section). Only possible with
|
|
1119
1170
|
// a real identity key, same precondition `publicKey` already had.
|
|
1120
1171
|
let recordSignature;
|
|
1121
|
-
if (
|
|
1122
|
-
({ signature: recordSignature } = await
|
|
1172
|
+
if (cred) {
|
|
1173
|
+
({ signature: recordSignature } = await signPeerRecordWith(cred, record));
|
|
1123
1174
|
}
|
|
1124
1175
|
|
|
1125
1176
|
// Register as a reverse peer.
|
|
@@ -2360,18 +2411,20 @@ export class WshClient {
|
|
|
2360
2411
|
* @param {object} opts
|
|
2361
2412
|
* @param {string} opts.username
|
|
2362
2413
|
* @param {CryptoKeyPair} [opts.keyPair]
|
|
2414
|
+
* @param {import('./auth.mjs').WshSigner} [opts.signer] - Page-held signer `{ publicKey, sign(data) }` instead of `keyPair`.
|
|
2363
2415
|
* @param {string} [opts.password]
|
|
2364
2416
|
* @param {number} [opts.timeout]
|
|
2365
2417
|
* @returns {Promise<string>} Session ID
|
|
2366
2418
|
* @private
|
|
2367
2419
|
*/
|
|
2368
|
-
async #performAuth({ username, keyPair, password, timeout = DEFAULT_AUTH_TIMEOUT, url, ...hostKeyOpts } = {}) {
|
|
2420
|
+
async #performAuth({ username, keyPair, signer, password, timeout = DEFAULT_AUTH_TIMEOUT, url, ...hostKeyOpts } = {}) {
|
|
2369
2421
|
if (!username) throw new Error('username is required');
|
|
2370
|
-
|
|
2422
|
+
const cred = await resolveSigner({ keyPair, signer });
|
|
2423
|
+
if (!cred && !password) throw new Error('Either keyPair, signer or password is required');
|
|
2371
2424
|
|
|
2372
2425
|
this.#hostKey = null;
|
|
2373
2426
|
try {
|
|
2374
|
-
const authMethod =
|
|
2427
|
+
const authMethod = cred ? AUTH_METHOD.PUBKEY : AUTH_METHOD.PASSWORD;
|
|
2375
2428
|
const hostKeyNonce = newHostKeyNonce();
|
|
2376
2429
|
await this.#transport.sendControl(hello({ username, authMethod, features: [HOST_KEY_NONCE_PREFIX + hostKeyNonce] }));
|
|
2377
2430
|
const hostCtx = { ...hostKeyOpts, url, username, nonce: hostKeyNonce };
|
|
@@ -2409,8 +2462,8 @@ export class WshClient {
|
|
|
2409
2462
|
return this.#sessionId;
|
|
2410
2463
|
}
|
|
2411
2464
|
|
|
2412
|
-
const { signature, publicKeyRaw } = await
|
|
2413
|
-
|
|
2465
|
+
const { signature, publicKeyRaw } = await signChallengeWith(
|
|
2466
|
+
cred, challengeMsg.session_id, challengeMsg.nonce, { username }
|
|
2414
2467
|
);
|
|
2415
2468
|
|
|
2416
2469
|
await this.#transport.sendControl(authMsg({
|
|
@@ -2422,7 +2475,7 @@ export class WshClient {
|
|
|
2422
2475
|
}));
|
|
2423
2476
|
}
|
|
2424
2477
|
} else if (firstResponse.type === MSG.CHALLENGE) {
|
|
2425
|
-
if (!
|
|
2478
|
+
if (!cred) throw new Error('Server sent CHALLENGE but no key pair provided');
|
|
2426
2479
|
await this.#verifyHostKey(null, hostCtx);
|
|
2427
2480
|
|
|
2428
2481
|
// Challenge carries session_id directly — see connect()'s
|
|
@@ -2430,8 +2483,8 @@ export class WshClient {
|
|
|
2430
2483
|
// this.#sessionId below in case AUTH_OK's own session_id is ever
|
|
2431
2484
|
// absent.
|
|
2432
2485
|
tempSessionId = firstResponse.session_id;
|
|
2433
|
-
const { signature, publicKeyRaw } = await
|
|
2434
|
-
|
|
2486
|
+
const { signature, publicKeyRaw } = await signChallengeWith(
|
|
2487
|
+
cred, firstResponse.session_id, firstResponse.nonce, { username }
|
|
2435
2488
|
);
|
|
2436
2489
|
|
|
2437
2490
|
await this.#transport.sendControl(authMsg({
|
package/src/index.d.ts
CHANGED
|
@@ -1108,6 +1108,38 @@ export function signChallenge(
|
|
|
1108
1108
|
opts?: WshTranscriptOptions,
|
|
1109
1109
|
): Promise<{ signature: Uint8Array; publicKeyRaw: Uint8Array }>;
|
|
1110
1110
|
|
|
1111
|
+
/**
|
|
1112
|
+
* A signer that need not expose a private key: a wallet, a hardware token, a Worker.
|
|
1113
|
+
* `publicKey` is the raw 32-byte Ed25519 key or a public `CryptoKey`; `sign` returns the 64-byte signature.
|
|
1114
|
+
*/
|
|
1115
|
+
export interface WshSigner {
|
|
1116
|
+
publicKey: Uint8Array | CryptoKey;
|
|
1117
|
+
sign(data: Uint8Array): Uint8Array | Promise<Uint8Array>;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/** A `keyPair` or `signer` normalized to a raw public key and an async `sign`; `null` when neither is given. */
|
|
1121
|
+
export interface WshResolvedSigner {
|
|
1122
|
+
publicKeyRaw: Uint8Array;
|
|
1123
|
+
sign(data: Uint8Array): Promise<Uint8Array>;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/** Normalize `{ keyPair }` or `{ signer }`. Throws a TypeError for both together or a malformed signer. */
|
|
1127
|
+
export function resolveSigner(credentials?: { keyPair?: CryptoKeyPair; signer?: WshSigner }): Promise<WshResolvedSigner | null>;
|
|
1128
|
+
|
|
1129
|
+
/** `signChallenge` for a signer resolved by `resolveSigner`. */
|
|
1130
|
+
export function signChallengeWith(
|
|
1131
|
+
signer: WshResolvedSigner,
|
|
1132
|
+
sessionId: string,
|
|
1133
|
+
nonce: Uint8Array,
|
|
1134
|
+
opts?: WshTranscriptOptions,
|
|
1135
|
+
): Promise<{ signature: Uint8Array; publicKeyRaw: Uint8Array }>;
|
|
1136
|
+
|
|
1137
|
+
/** `signPeerRecord` for a signer resolved by `resolveSigner`. */
|
|
1138
|
+
export function signPeerRecordWith(
|
|
1139
|
+
signer: WshResolvedSigner,
|
|
1140
|
+
record: WshPeerRecord,
|
|
1141
|
+
): Promise<{ signature: Uint8Array; publicKeyRaw: Uint8Array }>;
|
|
1142
|
+
|
|
1111
1143
|
/**
|
|
1112
1144
|
* Server-side: verify a client's challenge response.
|
|
1113
1145
|
*/
|
|
@@ -1385,7 +1417,10 @@ export class SerialQueue<T = unknown> {
|
|
|
1385
1417
|
* Provides the same interface as WebTransportTransport so that upper
|
|
1386
1418
|
* layers (session, client) work identically over either transport.
|
|
1387
1419
|
*/
|
|
1388
|
-
export class WebSocketTransport extends WshTransport {
|
|
1420
|
+
export class WebSocketTransport extends WshTransport {
|
|
1421
|
+
/** `WebSocket`: a constructor to dial with instead of the global one (a test double, `createMemoryHost().WebSocket`). */
|
|
1422
|
+
constructor(options?: { WebSocket?: new (url: string) => any });
|
|
1423
|
+
}
|
|
1389
1424
|
|
|
1390
1425
|
/**
|
|
1391
1426
|
* @deprecated The old hand-rolled 5-byte mux's frame-type byte values.
|
|
@@ -1665,6 +1700,13 @@ export class WshSession {
|
|
|
1665
1700
|
*/
|
|
1666
1701
|
write(data: Uint8Array | string): Promise<void>;
|
|
1667
1702
|
|
|
1703
|
+
/**
|
|
1704
|
+
* Send EOF on stdin without closing the session: output keeps arriving and
|
|
1705
|
+
* `onExit`/`onClose` fire as usual. Idempotent; `write()` rejects afterwards.
|
|
1706
|
+
* Stream-mode sessions only (throws on a virtual-mode session).
|
|
1707
|
+
*/
|
|
1708
|
+
closeStdin(): Promise<void>;
|
|
1709
|
+
|
|
1668
1710
|
/**
|
|
1669
1711
|
* Opt in to end-to-end encryption for this session's data plane
|
|
1670
1712
|
* (virtual-mode sessions only). `sharedSecret` must come from a fresh
|
|
@@ -1772,6 +1814,8 @@ export interface WshHostKeyOptions {
|
|
|
1772
1814
|
export interface WshConnectOptions extends WshHostKeyOptions {
|
|
1773
1815
|
username: string;
|
|
1774
1816
|
keyPair?: CryptoKeyPair;
|
|
1817
|
+
/** A page-held signer instead of `keyPair` (not both). */
|
|
1818
|
+
signer?: WshSigner;
|
|
1775
1819
|
password?: string;
|
|
1776
1820
|
transport?: 'wt' | 'ws';
|
|
1777
1821
|
/**
|
|
@@ -1845,6 +1889,8 @@ export interface WshResumeSessionOptions {
|
|
|
1845
1889
|
export interface WshConnectReverseOptions {
|
|
1846
1890
|
username: string;
|
|
1847
1891
|
keyPair?: CryptoKeyPair;
|
|
1892
|
+
/** A page-held signer instead of `keyPair` (not both). */
|
|
1893
|
+
signer?: WshSigner;
|
|
1848
1894
|
password?: string;
|
|
1849
1895
|
/** Forwarded to the underlying `connect()` -- see `WshConnectOptions`. */
|
|
1850
1896
|
webTransport?: WshWebTransportOptions;
|
|
@@ -1871,10 +1917,18 @@ export interface WshConnectReverseOptions {
|
|
|
1871
1917
|
export interface WshExecOptions extends WshHostKeyOptions {
|
|
1872
1918
|
username: string;
|
|
1873
1919
|
keyPair?: CryptoKeyPair;
|
|
1920
|
+
/** A page-held signer instead of `keyPair` (not both). */
|
|
1921
|
+
signer?: WshSigner;
|
|
1874
1922
|
password?: string;
|
|
1875
1923
|
timeout?: number;
|
|
1876
1924
|
/** See {@link WshOpenSessionOptions.primer}. */
|
|
1877
1925
|
primer?: boolean;
|
|
1926
|
+
/**
|
|
1927
|
+
* Input for the command: written, then stdin is closed (EOF), so `cat`,
|
|
1928
|
+
* `wc -c` and `sh -s` finish. Omitted: stdin is not touched. Needs a
|
|
1929
|
+
* stream-mode host (`@johnhenry/wsh/server`).
|
|
1930
|
+
*/
|
|
1931
|
+
stdin?: string | Uint8Array | ReadableStream<Uint8Array | string> | AsyncIterable<Uint8Array | string> | Iterable<Uint8Array | string>;
|
|
1878
1932
|
}
|
|
1879
1933
|
|
|
1880
1934
|
/** Result from WshClient.exec(). */
|
|
@@ -2542,7 +2596,7 @@ export interface SessionRecordingEntry {
|
|
|
2542
2596
|
data: unknown;
|
|
2543
2597
|
}
|
|
2544
2598
|
|
|
2545
|
-
/**
|
|
2599
|
+
/** The `toJSON()` export: asciicast-v2-shaped (not a playable asciicast file -- one JSON document, plus `sessionId` and `open`/`exit` events). */
|
|
2546
2600
|
export interface SessionRecordingJSON {
|
|
2547
2601
|
version: 2;
|
|
2548
2602
|
width: number;
|
|
@@ -2580,7 +2634,7 @@ export class SessionRecorder {
|
|
|
2580
2634
|
record(type: SessionRecordingEventType | string, data: unknown): void;
|
|
2581
2635
|
|
|
2582
2636
|
/**
|
|
2583
|
-
* Export the recording as a JSON-serializable object (asciicast
|
|
2637
|
+
* Export the recording as a JSON-serializable object (asciicast-v2-shaped; see the README for converting it to a `.cast` file).
|
|
2584
2638
|
*/
|
|
2585
2639
|
toJSON(): SessionRecordingJSON;
|
|
2586
2640
|
|
package/src/index.mjs
CHANGED
|
@@ -47,6 +47,7 @@ export {
|
|
|
47
47
|
generateKeyPair, exportPublicKeyRaw, exportPublicKeySSH,
|
|
48
48
|
importPublicKeyRaw, exportPrivateKeyPKCS8, importPrivateKeyPKCS8,
|
|
49
49
|
sign, verify, buildTranscript, signChallenge, verifyChallenge,
|
|
50
|
+
resolveSigner, signChallengeWith, signPeerRecordWith,
|
|
50
51
|
buildPeerRecordTranscript, signPeerRecord, verifyPeerRecord,
|
|
51
52
|
fingerprint, shortFingerprint, generateNonce,
|
|
52
53
|
podId, fingerprintToPodId, podIdToFingerprint,
|