@rstreamlabs/webtty 1.6.5 → 1.9.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 CHANGED
@@ -3,8 +3,9 @@
3
3
  Browser-side client for the rstream WebTTY protocol.
4
4
 
5
5
  Use this package when you need to connect a web application to a WebTTY server
6
- over WebSocket. It handles the protobuf session handshake, stdin/stdout/stderr
7
- streams, remote process completion, terminal resize events, and heartbeats.
6
+ over WebSocket or WebTransport. It handles the protobuf session handshake,
7
+ stdin/stdout/stderr streams, remote process completion, terminal resize events,
8
+ and heartbeats.
8
9
 
9
10
  For a ready-made React terminal, use
10
11
  [`@rstreamlabs/react`](../react/README.md).
@@ -72,39 +73,343 @@ webtty.resize(40, 120);
72
73
  Call `closeStdin()` to send EOF, or `disconnect()` to terminate the client
73
74
  session.
74
75
 
76
+ ## Execute Commands
77
+
78
+ For non-interactive agent workflows, use `runWebTTYCommand` or
79
+ `executeWebTTYCommand`. Both open a WebTTY session, collect stdout and stderr,
80
+ and resolve when the remote command exits.
81
+
82
+ ```ts
83
+ import { runWebTTYCommand } from "@rstreamlabs/webtty";
84
+
85
+ const result = await runWebTTYCommand(
86
+ { url: "wss://host.example.t.rstream.io?rstream.token=<token>" },
87
+ "sh",
88
+ ["-lc", "docker ps --format '{{.Names}}'"],
89
+ { timeoutMs: 30_000 },
90
+ );
91
+
92
+ if (!result.success) {
93
+ throw new Error(
94
+ result.stderr || `Remote command exited with ${result.exitCode}`,
95
+ );
96
+ }
97
+
98
+ console.log(result.stdout);
99
+ ```
100
+
101
+ Use `openWebTTYCommand` when you need live control over a running command. It
102
+ returns a command object with replayable stdout/stderr, ordered log iteration,
103
+ stdin writes, EOF handling, `wait()`, and `kill()`/`terminate()` session
104
+ cleanup.
105
+
106
+ ```ts
107
+ import { openWebTTYCommand } from "@rstreamlabs/webtty";
108
+
109
+ const command = openWebTTYCommand(
110
+ { url: "wss://host.example.t.rstream.io?rstream.token=<token>" },
111
+ {
112
+ cmdArgs: ["sh", "-lc", "npm test"],
113
+ timeoutMs: 120_000,
114
+ },
115
+ );
116
+
117
+ for await (const entry of command.logs()) {
118
+ process[entry.stream === "stdout" ? "stdout" : "stderr"].write(entry.data);
119
+ }
120
+
121
+ const status = await command.wait();
122
+
123
+ if (!status.success) {
124
+ throw new Error(`Remote command exited with ${status.exitCode}`);
125
+ }
126
+ ```
127
+
128
+ Use `WebTTYRemoteExecutor` when the URL is resolved lazily, for example from a
129
+ fresh short-lived token. When the WebTTY server is discovered through
130
+ `@rstreamlabs/tunnels`, pass the advertised `exec_path` value as `execPath`
131
+ instead of assuming `/`.
132
+
133
+ ### Managed session attach
134
+
135
+ Engine-managed sessions are joined with a WebTTY `Attach` message. The attach
136
+ grant is obtained from the control-plane API, then sent as the first protobuf
137
+ message on the terminal stream. Terminal input and output stay on the WebTTY
138
+ data path. The current engine live participant stream accepts WebSocket-backed
139
+ sessions only; WebTransport attach encoding is available in the protocol/SDK,
140
+ but engines that do not expose a WebTransport participant stream reject those
141
+ sessions before issuing an attach grant.
142
+
143
+ ```ts
144
+ import { WebTTY } from "@rstreamlabs/webtty";
145
+
146
+ const session = new WebTTY({
147
+ attach: {
148
+ attachGrant,
149
+ capabilities: ["read_stream", "request_control"],
150
+ participantId,
151
+ sessionId,
152
+ },
153
+ url: participantStreamUrl,
154
+ });
155
+
156
+ session.connect();
157
+ ```
158
+
159
+ ## Recorded Session Replay
160
+
161
+ The package exposes replay helpers for product-managed WebTTY recordings. The
162
+ helpers are public so applications can inspect and audit the decrypt/transcript
163
+ path instead of relying on product UI code.
164
+
165
+ ```ts
166
+ import {
167
+ createWebTTYE2EReplayPayloadCryptoFromKeyGrant,
168
+ decryptWebTTYRecordedEvent,
169
+ decryptWebTTYRecordedTextLog,
170
+ } from "@rstreamlabs/webtty";
171
+
172
+ const payloadCrypto = await createWebTTYE2EReplayPayloadCryptoFromKeyGrant(
173
+ decryptMaterialGrant,
174
+ localWorkspaceDeviceWebTTYIdentity,
175
+ );
176
+
177
+ for (const event of recordedEvents) {
178
+ const chunk = await decryptWebTTYRecordedEvent(event, payloadCrypto);
179
+ if (chunk) {
180
+ // chunk.stream is "stdin", "stdout", or "stderr"; chunk.data is bytes.
181
+ }
182
+ }
183
+
184
+ const transcript = await decryptWebTTYRecordedTextLog(
185
+ recordedEvents,
186
+ payloadCrypto,
187
+ );
188
+ console.log(transcript.text);
189
+ ```
190
+
191
+ `decryptWebTTYRecordedTextLog` renders a readable terminal transcript from
192
+ recorded data events. It omits closed alternate-screen applications from the
193
+ transcript, matching terminal scrollback behavior. If the recording ends while
194
+ alternate screen is still active, the current alternate-screen snapshot is
195
+ included by default. Use raw decrypted events when you need full forensic data.
196
+
197
+ ## Filesystem Sidecar
198
+
199
+ When a WebTTY server is started with `--fs-root`, the optional WebDAV sidecar
200
+ advertises an `fs_path` value. Paths passed to the SDK are relative to that
201
+ configured root.
202
+
203
+ ```ts
204
+ import { WebTTYFileSystem } from "@rstreamlabs/webtty";
205
+
206
+ const fs = new WebTTYFileSystem({
207
+ url: "https://host.example.t.rstream.io?rstream.token=<token>",
208
+ });
209
+
210
+ const files = await fs.list("/");
211
+ const compose = await fs.readText("/compose.yaml");
212
+ const stream = await fs.readStream("/large.log");
213
+
214
+ await fs.writeFile("/notes/codex.txt", "checked by Codex\n");
215
+ ```
216
+
217
+ When the WebTTY server is discovered through `@rstreamlabs/tunnels`, pass the
218
+ advertised `fs_path` value as `fsPath` instead of assuming `/fs`.
219
+
220
+ `WebTTYFileSystem` also exposes fs-style aliases such as `readFile`,
221
+ `writeFile`, `readdir`, `mkdir`, `stat`, `rename`, `copyFile`, `rm`, and
222
+ `exists` for code that expects a familiar filesystem shape.
223
+
224
+ The filesystem sidecar is a WebDAV boundary, not a sandbox. It is rooted by the
225
+ server-side `--fs-root` option and runs with the WebTTY server process
226
+ permissions. It is not part of the encrypted WebTTY protobuf payload stream and
227
+ is intentionally kept separate from WebTTY E2E payload encryption.
228
+
229
+ ## Examples
230
+
231
+ Runnable examples live under `examples/`:
232
+
233
+ - `examples/remote-command` runs collected and streaming commands.
234
+ - `examples/filesystem-sidecar` reads and writes through the WebDAV sidecar.
235
+
75
236
  ## Configuration
76
237
 
77
238
  Client-level options:
78
239
 
79
- | Option | Purpose |
80
- | --- | --- |
81
- | `url` | WebSocket endpoint for the WebTTY server. |
82
- | `sendHeartbeat` | Send heartbeat messages. Defaults to `true`. |
83
- | `heartbeatIntervalMs` | Heartbeat interval in milliseconds. Defaults to `5000`. |
240
+ | Option | Purpose |
241
+ | --------------------- | ----------------------------------------------------------- |
242
+ | `url` | WebSocket or WebTransport endpoint for the WebTTY server. |
243
+ | `transport` | Optional transport override: `websocket` or `webtransport`. |
244
+ | `sendHeartbeat` | Send heartbeat messages. Defaults to `true`. |
245
+ | `heartbeatIntervalMs` | Heartbeat interval in milliseconds. Defaults to `5000`. |
84
246
 
85
247
  Execution options:
86
248
 
87
- | Option | Purpose |
88
- | --- | --- |
89
- | `cmdArgs` | Command arguments requested for the remote session. |
90
- | `envVars` | Environment variables requested for the remote session. |
91
- | `allocateTty` | Ask the server for a TTY. Defaults to `true`. |
92
- | `interactive` | Enable stdin. Defaults to `true`. |
93
- | `username` | Optional user name or numeric user ID. |
94
- | `workdir` | Optional working directory. |
249
+ | Option | Purpose |
250
+ | ------------- | ------------------------------------------------------- |
251
+ | `cmdArgs` | Command arguments requested for the remote session. |
252
+ | `envVars` | Environment variables requested for the remote session. |
253
+ | `allocateTty` | Ask the server for a TTY. Defaults to `true`. |
254
+ | `interactive` | Enable stdin. Defaults to `true`. |
255
+ | `username` | Optional user name or numeric user ID. |
256
+ | `workdir` | Optional working directory. |
95
257
 
96
258
  The remote WebTTY server decides which execution options are accepted. Treat
97
259
  these values as requests, not local privilege boundaries.
98
260
 
261
+ ## Transports
262
+
263
+ The browser client uses WebSocket by default:
264
+
265
+ ```ts
266
+ const terminal = new WebTTY({ url: "wss://terminal.example/session" });
267
+ ```
268
+
269
+ Use WebTransport when the endpoint is published over HTTP/3 WebTransport:
270
+
271
+ ```ts
272
+ const terminal = new WebTTY({
273
+ transport: "webtransport",
274
+ url: "https://terminal.example/session",
275
+ });
276
+ ```
277
+
278
+ Both transports carry the same WebTTY protobuf messages. WebTransport uses the
279
+ same length-prefixed protobuf framing as the Go WebTransport implementation.
280
+
281
+ For local WebTransport tests that use an ephemeral self-signed certificate, pass
282
+ the browser WebTransport certificate pinning options through `webTransportOptions`:
283
+
284
+ ```ts
285
+ const terminal = new WebTTY({
286
+ transport: "webtransport",
287
+ url: "https://127.0.0.1:8443/",
288
+ webTransportOptions: {
289
+ serverCertificateHashes: [
290
+ { algorithm: "sha-256", value: certificateSha256 },
291
+ ],
292
+ },
293
+ });
294
+ ```
295
+
296
+ Production endpoints should normally rely on publicly trusted TLS certificates
297
+ and leave `webTransportOptions` unset.
298
+
299
+ ## Payload Crypto Hooks
300
+
301
+ Managed WebTTY can keep the protobuf session envelope visible to the server
302
+ while carrying stdin/stdout/stderr bytes as encrypted payloads. This lets the
303
+ server route sessions, record metadata, enforce policy, and track lifecycle
304
+ events without receiving plaintext terminal bytes.
305
+
306
+ The SDK exposes payload crypto hooks through `payloadCrypto`. It also provides
307
+ `generateWebTTYE2EIdentity`, `createWebTTYE2EClientPayloadCrypto`, and
308
+ `createWebTTYE2EServerPayloadCrypto` helpers for WebCrypto-backed E2E payload
309
+ encryption.
310
+
311
+ Implemented E2E suites:
312
+
313
+ | Layer | Suite |
314
+ | ------------- | -------------------------------------------------------------------- |
315
+ | Payload bytes | AES-256-GCM with a fresh 96-bit nonce per WebTTY data message |
316
+ | Key envelope | HPKE Base mode: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-256-GCM |
317
+
318
+ Crypto helpers attach a `cryptoInfo` object to the returned `payloadCrypto`.
319
+ UI bindings can use it to display runtime security details without hard-coding
320
+ suite names. The object reports the E2E mode, payload cipher, tag and nonce
321
+ sizes, key agreement, key derivation, and key-encryption suites that are
322
+ actually configured for the session.
323
+
324
+ The WebTTY protobuf envelope remains visible for routing and policy; only the
325
+ stdin/stdout/stderr payload bytes are encrypted by these helpers.
326
+
327
+ Key identifiers and X25519 key material can be passed as raw `Uint8Array`
328
+ values or as unpadded base64url strings, matching the local WebTTY identity
329
+ files generated by the rstream CLI.
330
+
331
+ When a client needs replay/decrypt grants to point at product resources instead
332
+ of opaque public keys, pass typed recipients to
333
+ `createWebTTYE2EClientPayloadCrypto`:
334
+
335
+ ```ts
336
+ const crypto = await createWebTTYE2EClientPayloadCrypto({
337
+ recipients: [
338
+ {
339
+ id: "keyset-1",
340
+ keyId: workspaceRecipientKeyId,
341
+ kind: "workspace_keyset",
342
+ publicKey: workspaceRecipientPublicKey,
343
+ },
344
+ ],
345
+ });
346
+ ```
347
+
348
+ The helper builds the WebTTY `key_context` before HPKE wrapping, so the context
349
+ is covered by the HPKE authenticated data. `createWebTTYE2EKeyContext` is also
350
+ available when the application needs to provide the context explicitly with
351
+ workspace, project, or server identifiers.
352
+
353
+ Recorded engine events may expose both `key_context` and `key_context_raw`.
354
+ Replay and decrypt flows must prefer `key_context_raw` when it is present. It is
355
+ the unpadded base64url encoding of the exact context bytes used for HPKE/AAD;
356
+ `key_context` is a readable metadata projection and can be affected by JSON
357
+ normalization after storage.
358
+
359
+ Browser applications do not read environment variables or `.rstream` files. They
360
+ must receive either an explicit known server endpoint identity or a
361
+ workspace-managed trust grant before creating the WebTTY client. When an
362
+ endpoint identity is configured, the browser verifies the server proof before it
363
+ sends the WebTTY `Open` message. When the server requires client authentication,
364
+ the browser also needs a local client endpoint identity so it can sign a
365
+ `ClientProof`.
366
+
367
+ Node.js applications that run beside the rstream CLI can use the local trust
368
+ helper to apply the same WebTTY trust-store resolution as the CLI and native
369
+ clients:
370
+
371
+ ```ts
372
+ import { createWebTTYE2EClientPayloadCryptoFromLocalTrust } from "@rstreamlabs/webtty/node";
373
+
374
+ const payloadCrypto = await createWebTTYE2EClientPayloadCryptoFromLocalTrust({
375
+ required: true,
376
+ });
377
+ ```
378
+
379
+ The helper resolves `RSTREAM_WEBTTY_KNOWN_SERVER_KEY`,
380
+ `RSTREAM_WEBTTY_KNOWN_SERVERS_FILE`, and the default
381
+ `~/.rstream/webtty/known_servers.json` file. If no trust material exists and
382
+ `required` is not set, it returns `undefined` so plaintext WebTTY sessions remain
383
+ available for unprotected servers.
384
+
385
+ The WebDAV filesystem sidecar is a separate HTTP/WebDAV surface. It is not
386
+ covered by WebTTY payload crypto and should not be presented as protected by
387
+ WebTTY E2E encryption.
388
+
389
+ Protocol suite identifiers currently represented in the WebTTY protobuf
390
+ contract are:
391
+
392
+ | Field | Protocol identifiers |
393
+ | ------------------ | ---------------------------------------------------------------------------------- |
394
+ | `payloadSuite` | `aes-256-gcm`, `chacha20-poly1305` |
395
+ | `keyEnvelopeSuite` | `hpke-x25519-hkdf-sha256-aes-256-gcm`, `hpke-x25519-hkdf-sha256-chacha20-poly1305` |
396
+
397
+ The helpers in this package support only the AES-256-GCM payload suite and the
398
+ HPKE/X25519/HKDF-SHA256/AES-256-GCM key-envelope suite. ChaCha20-Poly1305
399
+ identifiers are reserved for forward compatibility and are rejected by the
400
+ current helpers.
401
+
402
+ Do not derive payload keys from passwords or application strings.
403
+
99
404
  ## Events
100
405
 
101
- | Event | Purpose |
102
- | --- | --- |
103
- | `onConnect` | Called after the server acknowledges the session. |
104
- | `onStdout` / `onStderr` | Called with stream chunks from the remote process. |
105
- | `onStdoutEos` / `onStderrEos` | Called when the corresponding stream reaches EOS. |
106
- | `onComplete` | Called with the remote process exit code. |
107
- | `onError` | Called for server errors, protocol errors, or connection failures. |
406
+ | Event | Purpose |
407
+ | ----------------------------- | ------------------------------------------------------------------ |
408
+ | `onConnect` | Called after the server acknowledges the session. |
409
+ | `onStdout` / `onStderr` | Called with stream chunks from the remote process. |
410
+ | `onStdoutEos` / `onStderrEos` | Called when the corresponding stream reaches EOS. |
411
+ | `onComplete` | Called with the remote process exit code. |
412
+ | `onError` | Called for server errors, protocol errors, or connection failures. |
108
413
 
109
414
  ## Security Notes
110
415