@rstreamlabs/webtty 1.12.1 → 1.12.3

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
@@ -1,591 +1,32 @@
1
1
  # `@rstreamlabs/webtty`
2
2
 
3
- Browser-side client for the rstream WebTTY protocol.
4
-
5
- Use this package when you need to connect a web application to a WebTTY server
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.
9
-
10
- For a ready-made React terminal, use
11
- [`@rstreamlabs/react`](../react/README.md).
12
-
13
- ## Install
3
+ WebTTY connects an authorized client to a terminal or command on a
4
+ remote machine. This package handles session input, output, resizing
5
+ and completion over WebSocket or WebTransport. An application backend
6
+ decides who can reach each server and supplies a scoped connection.
14
7
 
15
8
  ```sh
16
9
  npm install @rstreamlabs/webtty
17
10
  ```
18
11
 
19
- ## Connect to a WebTTY Session
20
-
21
- ```ts
22
- import { WebTTY } from "@rstreamlabs/webtty";
23
-
24
- const decoder = new TextDecoder();
25
-
26
- const webtty = new WebTTY(
27
- {
28
- url: "wss://host.example.t.rstream.io?rstream.token=<token>",
29
- },
30
- {
31
- cmdArgs: ["uname", "-a"],
32
- interactive: false,
33
- },
34
- {
35
- onConnect: () => {
36
- console.log("connected");
37
- },
38
- onStdout: (chunk) => {
39
- console.log(decoder.decode(chunk));
40
- },
41
- onComplete: (exitCode) => {
42
- console.log("completed", exitCode);
43
- },
44
- onError: (message) => {
45
- console.error(message);
46
- },
47
- },
48
- );
49
-
50
- webtty.connect();
51
- ```
52
-
53
- ## Interactive Sessions
54
-
55
- Connection failures are delivered once through `onError`, including normal
56
- WebTransport closure before the stream opens. Disconnecting also releases a
57
- stream that becomes available after the opening was cancelled. A normal close
58
- after opening still drains buffered output before reporting the session result.
59
-
60
- Error messages redact values from the configured endpoint's query parameters,
61
- userinfo and fragment, including their common URL-encoded forms. Avoid logging
62
- the endpoint separately. An identifiable browser `SecurityError` points to
63
- browser policy and `connect-src`; an empty browser error reports that diagnostic
64
- details are unavailable. Such an error does not establish that CSP is the cause.
65
- Invalid endpoint configuration still throws synchronously without echoing the URL.
66
-
67
- For an interactive terminal, write encoded input to stdin and forward terminal
68
- resize events.
69
-
70
- ```ts
71
- const encoder = new TextEncoder();
72
-
73
- const webtty = new WebTTY(
74
- { url: "wss://host.example.t.rstream.io?rstream.token=<token>" },
75
- { allocateTty: true, interactive: true },
76
- );
77
-
78
- webtty.connect();
79
-
80
- // After onConnect fires:
81
- webtty.writeStdin(encoder.encode("whoami\n"));
82
- webtty.resize(40, 120);
83
- ```
84
-
85
- Call `closeStdin()` to send EOF, or `disconnect()` to release the reader.
86
- For an Engine-managed detached execution, releasing the reader leaves the
87
- command running within its original execution budget.
88
-
89
- ## Execute Commands
90
-
91
- For non-interactive agent workflows, use `runWebTTYCommand` or
92
- `executeWebTTYCommand`. Both open a WebTTY session, collect stdout and stderr,
93
- and resolve when the remote command exits.
94
-
95
- ```ts
96
- import { runWebTTYCommand } from "@rstreamlabs/webtty";
97
-
98
- const result = await runWebTTYCommand(
99
- { url: "wss://host.example.t.rstream.io?rstream.token=<token>" },
100
- "sh",
101
- ["-lc", "docker ps --format '{{.Names}}'"],
102
- { timeoutMs: 30_000 },
103
- );
104
-
105
- if (!result.success) {
106
- throw new Error(
107
- result.stderr || `Remote command exited with ${result.exitCode}`,
108
- );
109
- }
110
-
111
- console.log(result.stdout);
112
- ```
113
-
114
- Use `openWebTTYCommand` when you need live control over a running command. It
115
- returns a command object with replayable stdout/stderr, ordered log iteration,
116
- stdin writes, EOF handling, `wait()`, and explicit `kill()`/`terminate()`.
117
-
118
- `terminate({ signal?, timeoutMs? })` sends a protocol termination request and
119
- waits for the native process result, including final stdout/stderr. `kill()` is
120
- an alias with the same semantics. The default confirmation wait is 65 seconds.
121
- `wait()` and `exitCode` retain the native result, including a natural exit that
122
- races with termination. Repeated requests do not restart termination.
123
-
124
- Missing native support rejects the operation without disconnecting. An aborted
125
- or timed-out confirmation wait leaves the remote result unknown and the reader
126
- connected; `wait()` can still observe a later native result. Use `disconnect()`
127
- when the application is finished with that reader. No local failure invents an
128
- exit code. Managed clients must also check the Engine's `explicit_termination`
129
- capability; an older relay can ignore a request even if a new native server
130
- advertises support, in which case confirmation times out.
131
-
132
- Low-level `WebTTY.canTerminate()` exposes native support after `onConnect`.
133
- `WebTTY.requestTermination()` queues the request; only `onComplete` confirms its
134
- outcome. Managed control permissions still apply independently of support.
135
-
136
- Command output capture is bounded to 8 MiB by default (`maxOutputBytes` can set
137
- another positive byte limit), and at most 32,768 nonempty chunks. Exceeding either
138
- limit raises `WebTTYCommandOutputLimitError` on output readers and requests
139
- termination. Further output is discarded while the bounded confirmation wait
140
- continues; `wait()` still reports a native result if one arrives. If termination
141
- cannot be confirmed, the command reader is disconnected with an unknown result.
142
- Use the low-level `WebTTY` output callbacks for continuous streaming without
143
- retaining a replayable command output buffer.
144
-
145
- ```ts
146
- import { openWebTTYCommand } from "@rstreamlabs/webtty";
147
-
148
- const command = openWebTTYCommand(
149
- { url: "wss://host.example.t.rstream.io?rstream.token=<token>" },
150
- {
151
- cmdArgs: ["sh", "-lc", "npm test"],
152
- timeoutMs: 120_000,
153
- },
154
- );
155
-
156
- for await (const entry of command.logs()) {
157
- process[entry.stream === "stdout" ? "stdout" : "stderr"].write(entry.data);
158
- }
159
-
160
- const status = await command.wait();
161
-
162
- if (!status.success) {
163
- throw new Error(`Remote command exited with ${status.exitCode}`);
164
- }
165
- ```
166
-
167
- Use `WebTTYRemoteExecutor` when the URL is resolved lazily, for example from a
168
- fresh short-lived token. When the WebTTY server is discovered through
169
- `@rstreamlabs/tunnels`, pass the advertised `exec_path` value as `execPath`
170
- instead of assuming `/`.
171
-
172
- ### Bounded detached execution
173
-
174
- Fetch WebTTY capabilities from the same Engine that provides the authenticated
175
- terminal URL, then pass them as `managed.capabilities`. The object returned by
176
- `@rstreamlabs/tunnels`' WebTTY capabilities API is directly compatible.
177
-
178
- ```ts
179
- const command = openWebTTYCommand(
180
- {
181
- url: authenticatedTerminalUrl,
182
- managed: { capabilities, executionSeconds: 300 },
183
- },
184
- { cmdArgs: ["sh", "-c", "run-job"], interactive: false, allocateTty: false },
185
- );
186
- await command.ready();
187
- const executionId = command.managedSessionId;
188
- // Save executionId before releasing the reader.
189
- command.disconnect();
190
- ```
191
-
192
- The SDK checks the advertised transport and maximum duration before connecting.
193
- `ready()` waits for the relay's confirmation; `managedSessionId` then identifies
194
- the same execution for later session API calls. `ready({ signal })` cancels only
195
- that wait. A missing or zero budget preserves the ordinary connection-bound
196
- lifetime. Detaching does not establish an exit result, and losing the opening
197
- response does not make retrying the command safe.
198
-
199
- Use the saved ID to inspect the session or obtain an authorized participant and
200
- Attach grant. No new Open is needed to recover a running command. The original
201
- deadline remains unchanged. This does not add restart survival or an output
202
- cursor; historical output still depends on recording and retention permissions.
203
-
204
- For any managed connection, including Attach, `managed.capabilities` also gates
205
- explicit termination: both Engine and native server support are required. An
206
- Attach without this capability snapshot cannot send Terminate. Current control
207
- authority is still checked by the Engine for every request.
208
-
209
- Omitting `executionSeconds` or setting it to zero keeps the ordinary connection
210
- lifetime, including when the Engine reports `managed_protocol: false`. Supplying
211
- that capability snapshot still prevents unsupported termination requests.
212
-
213
- ### Managed session attach
214
-
215
- Engine-managed sessions are joined with a WebTTY `Attach` message. The attach
216
- grant is obtained from the control-plane API, then sent as the first protobuf
217
- message on the terminal stream. Terminal input and output stay on the WebTTY
218
- data path. The Engine participant stream uses WebSocket, including when the
219
- original execution used WebTransport. Check the session's `live.attachable`
220
- state before requesting an Attach grant; older Engines can support fewer
221
- combinations. WebTransport Attach encoding in the SDK alone does not establish
222
- Engine participant-stream support.
223
-
224
- ```ts
225
- import { WebTTY } from "@rstreamlabs/webtty";
226
-
227
- const session = new WebTTY({
228
- managed: { capabilities },
229
- attach: {
230
- attachGrant,
231
- capabilities: ["read_stream", "request_control"],
232
- participantId,
233
- sessionId,
234
- },
235
- url: participantStreamUrl,
236
- });
237
-
238
- session.connect();
239
- ```
240
-
241
- ## Recorded Session Replay
242
-
243
- The package exposes replay helpers for product-managed WebTTY recordings. The
244
- helpers are public so applications can inspect and audit the decrypt/transcript
245
- path instead of relying on product UI code.
246
-
247
- ```ts
248
- import {
249
- createWebTTYE2EReplayPayloadCryptoFromKeyGrant,
250
- decryptWebTTYRecordedEvent,
251
- decryptWebTTYRecordedTextLog,
252
- } from "@rstreamlabs/webtty";
253
-
254
- const payloadCrypto = await createWebTTYE2EReplayPayloadCryptoFromKeyGrant(
255
- decryptMaterialGrant,
256
- localWorkspaceDeviceWebTTYIdentity,
257
- );
258
-
259
- for (const event of recordedEvents) {
260
- const chunk = await decryptWebTTYRecordedEvent(event, payloadCrypto);
261
- if (chunk) {
262
- // chunk.stream is "stdin", "stdout", or "stderr"; chunk.data is bytes.
263
- }
264
- }
265
-
266
- const transcript = await decryptWebTTYRecordedTextLog(
267
- recordedEvents,
268
- payloadCrypto,
269
- );
270
- console.log(transcript.text);
271
- ```
272
-
273
- `decryptWebTTYRecordedTextLog` renders a readable terminal transcript from
274
- recorded data events. It omits closed alternate-screen applications from the
275
- transcript, matching terminal scrollback behavior. If the recording ends while
276
- alternate screen is still active, the current alternate-screen snapshot is
277
- included by default. Use raw decrypted events when you need full forensic data.
278
-
279
- ## Filesystem Sidecar
280
-
281
- When a WebTTY server is started with `--fs-root`, the optional WebDAV sidecar
282
- advertises an `fs_path` value. Paths passed to the SDK are relative to that
283
- configured root.
284
-
285
- ```ts
286
- import { WebTTYFileSystem } from "@rstreamlabs/webtty";
287
-
288
- const fs = new WebTTYFileSystem({
289
- url: "https://host.example.t.rstream.io?rstream.token=<token>",
290
- });
291
-
292
- const files = await fs.list("/");
293
- const compose = await fs.readText("/compose.yaml");
294
- const stream = await fs.readStream("/large.log");
295
-
296
- await fs.writeFile("/notes/codex.txt", "checked by Codex\n");
297
- ```
298
-
299
- When the WebTTY server is discovered through `@rstreamlabs/tunnels`, pass the
300
- advertised `fs_path` value as `fsPath` instead of assuming `/fs`.
301
-
302
- `WebTTYFileSystem` also exposes fs-style aliases such as `readFile`,
303
- `writeFile`, `readdir`, `mkdir`, `stat`, `rename`, `copyFile`, `rm`, and
304
- `exists` for code that expects a familiar filesystem shape.
12
+ | I need to | Start with |
13
+ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
14
+ | Authorize and open a terminal from a browser | [WebTTY browser setup](https://rstream.io/docs/webtty/sdk-browser). |
15
+ | Handle input, output, errors and disconnect in my own UI | [Interactive sessions](https://github.com/rstreamlabs/rstream-js/blob/main/packages/webtty/docs/001-interactive-sessions.md). |
16
+ | Run a command or follow a managed execution | [Commands](https://github.com/rstreamlabs/rstream-js/blob/main/packages/webtty/docs/002-commands.md). |
17
+ | Replay a recording or work with files | [Recordings and files](https://github.com/rstreamlabs/rstream-js/blob/main/packages/webtty/docs/003-recordings-and-files.md). |
18
+ | Select transport and verify the remote endpoint | [Transports and endpoint trust](https://github.com/rstreamlabs/rstream-js/blob/main/packages/webtty/docs/004-transports-and-crypto.md). |
305
19
 
306
- The filesystem sidecar is a WebDAV boundary, not a sandbox. It is rooted by the
307
- server-side `--fs-root` option and runs with the WebTTY server process
308
- permissions. It is not part of the encrypted WebTTY protobuf payload stream and
309
- is intentionally kept separate from WebTTY E2E payload encryption.
20
+ For an existing React UI, use [React](https://github.com/rstreamlabs/rstream-js/blob/main/packages/react/README.md) for a single
21
+ terminal or [Terminal UI](https://github.com/rstreamlabs/rstream-js/blob/main/packages/terminal-ui/README.md) for a workspace.
310
22
 
311
23
  ## Examples
312
24
 
313
- Runnable examples live under `examples/`:
314
-
315
- - `examples/remote-command` runs collected and streaming commands.
316
- - `examples/filesystem-sidecar` reads and writes through the WebDAV sidecar.
317
-
318
- ## Configuration
319
-
320
- Client-level options:
321
-
322
- | Option | Purpose |
323
- | --------------------- | ----------------------------------------------------------- |
324
- | `url` | WebSocket or WebTransport endpoint for the WebTTY server. |
325
- | `transport` | Optional transport override: `websocket` or `webtransport`. |
326
- | `sendHeartbeat` | Send heartbeat messages. Defaults to `true`. |
327
- | `heartbeatIntervalMs` | Heartbeat interval in milliseconds. Defaults to `5000`. |
328
-
329
- Execution options:
330
-
331
- | Option | Purpose |
332
- | ------------- | ------------------------------------------------------- |
333
- | `cmdArgs` | Command arguments requested for the remote session. |
334
- | `envVars` | Environment variables requested for the remote session. |
335
- | `allocateTty` | Ask the server for a TTY. Defaults to `true`. |
336
- | `interactive` | Enable stdin. Defaults to `true`. |
337
- | `username` | Optional user name or numeric user ID. |
338
- | `workdir` | Optional working directory. |
339
-
340
- The remote WebTTY server decides which execution options are accepted. Treat
341
- these values as requests, not local privilege boundaries.
342
-
343
- ## Transports
344
-
345
- The browser client uses WebSocket by default:
346
-
347
- ```ts
348
- const terminal = new WebTTY({ url: "wss://terminal.example/session" });
349
- ```
350
-
351
- In Node.js, supply the Node transport to each client configuration:
352
-
353
- ```ts
354
- import { nodeWebSocketFactory } from "@rstreamlabs/webtty/node";
355
- import { runWebTTYCommand } from "@rstreamlabs/webtty/node";
356
-
357
- const result = await runWebTTYCommand(
358
- {
359
- url: "wss://terminal.example/session",
360
- webSocketFactory: nodeWebSocketFactory,
361
- },
362
- "whoami",
363
- );
364
- ```
365
-
366
- This uses HTTP/1.1 WebSocket with normal TLS verification, a 10-second handshake
367
- deadline, a 1-second close deadline and the configured `maxMessageSize` limit.
368
- It works independently of the global WebSocket implementation and does not
369
- modify other clients or browser bundles. The same option applies to `WebTTY`,
370
- `openWebTTYCommand` and `WebTTYRemoteExecutor`. WebTransport still requires a
371
- runtime that provides it; selecting it never falls back silently to WebSocket.
372
- Node 26.7's experimental HTTP/2 WebSocket handshake rejects a conforming
373
- [RFC 8441 endpoint](https://www.rfc-editor.org/rfc/rfc8441.html#section-5);
374
- the Node factory avoids that runtime-specific failure.
375
-
376
- Use WebTransport when the endpoint is published over HTTP/3 WebTransport:
377
-
378
- ```ts
379
- const terminal = new WebTTY({
380
- transport: "webtransport",
381
- url: "https://terminal.example/session",
382
- });
383
- ```
384
-
385
- Both transports carry the same WebTTY protobuf messages. WebTransport uses the
386
- same length-prefixed protobuf framing as the Go WebTransport implementation.
387
-
388
- For local WebTransport tests that use an ephemeral self-signed certificate, pass
389
- the browser WebTransport certificate pinning options through `webTransportOptions`:
390
-
391
- ```ts
392
- const terminal = new WebTTY({
393
- transport: "webtransport",
394
- url: "https://127.0.0.1:8443/",
395
- webTransportOptions: {
396
- serverCertificateHashes: [
397
- { algorithm: "sha-256", value: certificateSha256 },
398
- ],
399
- },
400
- });
401
- ```
402
-
403
- Production endpoints should normally rely on publicly trusted TLS certificates
404
- and leave `webTransportOptions` unset.
405
-
406
- ## Payload Crypto Hooks
407
-
408
- Managed WebTTY can keep the protobuf session envelope visible to the server
409
- while carrying stdin/stdout/stderr bytes as encrypted payloads. This lets the
410
- server route sessions, record metadata, enforce policy, and track lifecycle
411
- events without receiving plaintext terminal bytes.
412
-
413
- The SDK exposes payload crypto hooks through `payloadCrypto`. It also provides
414
- `generateWebTTYE2EIdentity`, `createWebTTYE2EClientPayloadCrypto`, and
415
- `createWebTTYE2EServerPayloadCrypto` helpers for WebCrypto-backed E2E payload
416
- encryption.
417
-
418
- Implemented E2E suites:
419
-
420
- | Layer | Suite |
421
- | ------------- | -------------------------------------------------------------------- |
422
- | Payload bytes | AES-256-GCM with a fresh 96-bit nonce per WebTTY data message |
423
- | Key envelope | HPKE Base mode: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-256-GCM |
424
-
425
- Crypto helpers attach a `cryptoInfo` object to the returned `payloadCrypto`.
426
- UI bindings can use it to display runtime security details without hard-coding
427
- suite names. The object reports the E2E mode, payload cipher, tag and nonce
428
- sizes, key agreement, key derivation, and key-encryption suites that are
429
- actually configured for the session.
430
-
431
- The WebTTY protobuf envelope remains visible for routing and policy; only the
432
- stdin/stdout/stderr payload bytes are encrypted by these helpers.
433
-
434
- Key identifiers and X25519 key material can be passed as raw `Uint8Array`
435
- values or as unpadded base64url strings, matching the local WebTTY identity
436
- files generated by the rstream CLI.
437
-
438
- When a client needs replay/decrypt grants to point at product resources instead
439
- of opaque public keys, pass typed recipients to
440
- `createWebTTYE2EClientPayloadCrypto`:
441
-
442
- ```ts
443
- const crypto = await createWebTTYE2EClientPayloadCrypto({
444
- recipients: [
445
- {
446
- id: "keyset-1",
447
- keyId: workspaceRecipientKeyId,
448
- kind: "workspace_keyset",
449
- publicKey: workspaceRecipientPublicKey,
450
- },
451
- ],
452
- });
453
- ```
454
-
455
- The helper builds the WebTTY `key_context` before HPKE wrapping, so the context
456
- is covered by the HPKE authenticated data. `createWebTTYE2EKeyContext` is also
457
- available when the application needs to provide the context explicitly with
458
- workspace, project, or server identifiers.
459
-
460
- Recorded engine events may expose both `key_context` and `key_context_raw`.
461
- Replay and decrypt flows must prefer `key_context_raw` when it is present. It is
462
- the unpadded base64url encoding of the exact context bytes used for HPKE/AAD;
463
- `key_context` is a readable metadata projection and can be affected by JSON
464
- normalization after storage.
465
-
466
- Browser applications do not read environment variables or `.rstream` files. They
467
- must receive either an explicit known server endpoint identity or a
468
- workspace-managed trust grant before creating the WebTTY client. When an
469
- endpoint identity is configured, the browser verifies the server proof before it
470
- sends the WebTTY `Open` message. When the server requires client authentication,
471
- the browser also needs a local client endpoint identity so it can sign a
472
- `ClientProof`.
473
-
474
- Node.js applications that run beside the rstream CLI can use the local trust
475
- helper to apply the same WebTTY trust-store resolution as the CLI and native
476
- clients:
477
-
478
- ```ts
479
- import { createWebTTYE2EClientPayloadCryptoFromLocalTrust } from "@rstreamlabs/webtty/node";
480
-
481
- const payloadCrypto = await createWebTTYE2EClientPayloadCryptoFromLocalTrust({
482
- required: true,
483
- });
484
- ```
485
-
486
- The helper resolves `RSTREAM_WEBTTY_KNOWN_SERVER_KEY`,
487
- `RSTREAM_WEBTTY_KNOWN_SERVERS_FILE`, and the default
488
- `~/.rstream/webtty/known_servers.json` file. If no trust material exists and
489
- `required` is not set, it returns `undefined` so plaintext WebTTY sessions remain
490
- available for unprotected servers.
491
-
492
- The WebDAV filesystem sidecar is a separate HTTP/WebDAV surface. It is not
493
- covered by WebTTY payload crypto and should not be presented as protected by
494
- WebTTY E2E encryption.
495
-
496
- Protocol suite identifiers currently represented in the WebTTY protobuf
497
- contract are:
498
-
499
- | Field | Protocol identifiers |
500
- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
501
- | `payloadSuite` | `aes-256-gcm`, `aes-256-gcm-random-nonce`, `chacha20-poly1305` |
502
- | `keyEnvelopeSuite` | `hpke-x25519-hkdf-sha256-aes-256-gcm`, `p256-hkdf-sha256-aes-256-gcm-random-nonce`, `hpke-x25519-hkdf-sha256-chacha20-poly1305` |
503
-
504
- The helpers support two complete E2E profiles. Existing applications keep using
505
- the default HPKE/X25519/HKDF-SHA256/AES-256-GCM profile. Applications that use
506
- E2E with a FIPS build of the Go client or engine must select the
507
- P-256/HKDF-SHA256/AES-256-GCM random-nonce profile and use WebTransport:
508
-
509
- ```ts
510
- import { createWebTTYE2EClientPayloadCrypto } from "@rstreamlabs/webtty";
511
- import { WebTTY } from "@rstreamlabs/webtty";
512
- import { webTTYFIPSCompatibleKeyEnvelopeSuite } from "@rstreamlabs/webtty";
513
-
514
- const payloadCrypto = await createWebTTYE2EClientPayloadCrypto({
515
- keyEnvelopeSuite: webTTYFIPSCompatibleKeyEnvelopeSuite,
516
- recipients: [
517
- {
518
- keyEnvelopeSuite: webTTYFIPSCompatibleKeyEnvelopeSuite,
519
- keyId: serverKeyId,
520
- publicKey: serverPublicKey,
521
- },
522
- ],
523
- });
524
-
525
- const client = new WebTTY(
526
- { transport: "webtransport", url },
527
- { payloadCrypto },
528
- );
529
- ```
530
-
531
- Standard rstream endpoints accept both profiles. FIPS Go builds accept only the
532
- P-256 random-nonce profile for E2E and require WebTransport. Application E2E
533
- is optional unless server or workspace policy requires it; a transport-only
534
- connection does not protect terminal content from an Engine that terminates
535
- transport encryption. ChaCha20-Poly1305 identifiers remain
536
- reserved for forward compatibility and are rejected by the current helpers.
537
-
538
- This JavaScript implementation provides protocol interoperability with the
539
- FIPS Go artifacts. Browser WebCrypto does not embed the validated Go
540
- Cryptographic Module, so this package does not carry the Go module's FIPS
541
- 140-3 Inside status.
542
-
543
- Do not derive payload keys from passwords or application strings.
544
-
545
- ## Events
546
-
547
- | Event | Purpose |
548
- | ----------------------------- | ------------------------------------------------------------------ |
549
- | `onConnect` | Called after the server acknowledges the session. |
550
- | `onStdout` / `onStderr` | Called with stream chunks from the remote process. |
551
- | `onStdoutEos` / `onStderrEos` | Called when the corresponding stream reaches EOS. |
552
- | `onComplete` | Called with the remote process exit code. |
553
- | `onError` | Called for server errors, protocol errors, or connection failures. |
554
-
555
- ## Security Notes
556
-
557
- Browser WebTTY sessions should use short-lived tokens scoped to the specific
558
- tunnel and path. Do not embed personal access tokens or application credentials
559
- in frontend code.
560
-
561
- ## Development
562
-
563
- ```sh
564
- npm --workspace @rstreamlabs/webtty run test
565
- npm --workspace @rstreamlabs/webtty run type-check
566
- npm --workspace @rstreamlabs/webtty run lint
567
- npm --workspace @rstreamlabs/webtty run build
568
- ```
569
-
570
- # Transport resource limits
571
-
572
- `WebTTYClientConfig.maxMessageSize` limits encoded messages in both directions
573
- and defaults to 1 MiB. WebTransport validates a frame length before allocating
574
- its body and buffers at most one partial frame. It pauses reads while an async
575
- message handler (including E2E decryption) is pending. Incoming WebSocket data
576
- and outgoing transport queues are bounded to four times the message limit;
577
- SDK queues also have a 1,024 message limit. Exceeding a limit closes the session
578
- with an explicit error. Applications should split large stdin writes into
579
- chunks below the message limit, allowing for protobuf and encryption overhead.
580
-
581
- Disconnect cancels pending transport setup and reads, aborts writes and drops
582
- queued terminal data. Late decryption results are not delivered after a local
583
- disconnect. A runtime without WebTransport reports that capability limitation.
584
-
585
- For Node local trust helpers, `RSTREAM_DATA_DIR` selects an absolute state root
586
- instead of the default `~/.rstream`. This matches the Go and C++ CLI state layout
587
- and is independent of the engine connection configuration.
588
-
589
- ## Shared filesystem backend
25
+ | Example | What it shows |
26
+ | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
27
+ | [Remote command](https://github.com/rstreamlabs/rstream-js/tree/main/packages/webtty/examples/remote-command) | Run and observe a permitted command against an authorized WebTTY endpoint. |
28
+ | [Filesystem sidecar](https://github.com/rstreamlabs/rstream-js/tree/main/packages/webtty/examples/filesystem-sidecar) | List and read files through the authorized sidecar. |
590
29
 
591
- `WebTTYFileSystem` and its existing exports remain available. The implementation now lives in `@rstreamlabs/filesystem`, which also exports `WebDAVFileSystem` and the transport-independent `FileSystemBackend` interface. Existing WebTTY write helpers and configuration are preserved. New read clients can use `readStream` to avoid buffering large downloads; native `downloadURL` is available only when authentication does not require custom headers. This filesystem protocol is independent from the temporary encrypted file-sharing utility and from WebTTY E2E payload encryption.
30
+ For workspace checks and package maintenance, follow
31
+ [Contributing](https://github.com/rstreamlabs/rstream-js/blob/main/CONTRIBUTING.md)
32
+ and the [Node transport dependency baseline](https://github.com/rstreamlabs/rstream-js/blob/main/packages/webtty/docs/000-dependencies.md).
@@ -11169,6 +11169,7 @@ async function resolveURL(url) {
11169
11169
  }
11170
11170
  function clientConfig(config, url, execPath) {
11171
11171
  return {
11172
+ webSocketFactory: config.webSocketFactory,
11172
11173
  heartbeatIntervalMs: config.heartbeatIntervalMs,
11173
11174
  managed: config.managed,
11174
11175
  sendHeartbeat: config.sendHeartbeat,
package/dist/index.d.mts CHANGED
@@ -4995,8 +4995,8 @@ interface WebTTYClientConfig {
4995
4995
  webTransportOptions?: WebTTYWebTransportOptions;
4996
4996
  /**
4997
4997
  * Attach to an existing engine-managed WebTTY session instead of opening a
4998
- * new remote process. The attach grant is issued by the control-plane API;
4999
- * terminal bytes still flow through the WebTTY protobuf stream.
4998
+ * new remote process. The Engine API issues the attach grant.
4999
+ * Terminal bytes flow through the WebTTY protobuf stream.
5000
5000
  */
5001
5001
  attach?: WebTTYAttachConfig;
5002
5002
  /** Engine capabilities and optional detached execution budget. */
@@ -5452,6 +5452,7 @@ type WebTTYURLProvider = string | URL | (() => Promise<string | URL> | string |
5452
5452
  type WebTTYCommandOutput = "both" | "stderr" | "stdout";
5453
5453
  type WebTTYCommandStream = "stderr" | "stdout";
5454
5454
  interface WebTTYRemoteExecutorConfig {
5455
+ webSocketFactory?: WebTTYWebSocketFactory;
5455
5456
  execPath?: string;
5456
5457
  managed?: WebTTYManagedSessionConfig;
5457
5458
  heartbeatIntervalMs?: number;
package/dist/index.d.ts CHANGED
@@ -4995,8 +4995,8 @@ interface WebTTYClientConfig {
4995
4995
  webTransportOptions?: WebTTYWebTransportOptions;
4996
4996
  /**
4997
4997
  * Attach to an existing engine-managed WebTTY session instead of opening a
4998
- * new remote process. The attach grant is issued by the control-plane API;
4999
- * terminal bytes still flow through the WebTTY protobuf stream.
4998
+ * new remote process. The Engine API issues the attach grant.
4999
+ * Terminal bytes flow through the WebTTY protobuf stream.
5000
5000
  */
5001
5001
  attach?: WebTTYAttachConfig;
5002
5002
  /** Engine capabilities and optional detached execution budget. */
@@ -5452,6 +5452,7 @@ type WebTTYURLProvider = string | URL | (() => Promise<string | URL> | string |
5452
5452
  type WebTTYCommandOutput = "both" | "stderr" | "stdout";
5453
5453
  type WebTTYCommandStream = "stderr" | "stdout";
5454
5454
  interface WebTTYRemoteExecutorConfig {
5455
+ webSocketFactory?: WebTTYWebSocketFactory;
5455
5456
  execPath?: string;
5456
5457
  managed?: WebTTYManagedSessionConfig;
5457
5458
  heartbeatIntervalMs?: number;
package/dist/index.js CHANGED
@@ -11245,6 +11245,7 @@ async function resolveURL(url) {
11245
11245
  }
11246
11246
  function clientConfig(config, url, execPath) {
11247
11247
  return {
11248
+ webSocketFactory: config.webSocketFactory,
11248
11249
  heartbeatIntervalMs: config.heartbeatIntervalMs,
11249
11250
  managed: config.managed,
11250
11251
  sendHeartbeat: config.sendHeartbeat,
package/dist/index.mjs CHANGED
@@ -40,7 +40,7 @@ import {
40
40
  webTTYRecordedEventEncryptedPayload,
41
41
  webTTYServerProofTranscriptBytes,
42
42
  webTTYSigningKeyID
43
- } from "./chunk-V7EU2JPX.mjs";
43
+ } from "./chunk-BSMXY5EO.mjs";
44
44
  export {
45
45
  WebTTY,
46
46
  WebTTYCommand,
package/dist/node.js CHANGED
@@ -11251,6 +11251,7 @@ async function resolveURL(url) {
11251
11251
  }
11252
11252
  function clientConfig(config, url, execPath) {
11253
11253
  return {
11254
+ webSocketFactory: config.webSocketFactory,
11254
11255
  heartbeatIntervalMs: config.heartbeatIntervalMs,
11255
11256
  managed: config.managed,
11256
11257
  sendHeartbeat: config.sendHeartbeat,
package/dist/node.mjs CHANGED
@@ -40,7 +40,7 @@ import {
40
40
  webTTYRecordedEventEncryptedPayload,
41
41
  webTTYServerProofTranscriptBytes,
42
42
  webTTYSigningKeyID
43
- } from "./chunk-V7EU2JPX.mjs";
43
+ } from "./chunk-BSMXY5EO.mjs";
44
44
 
45
45
  // src/local-e2e.ts
46
46
  var localKeyFileVersion = 1;
@@ -1,11 +1,26 @@
1
- # `rstream-webtty-filesystem-sidecar-example`
1
+ # Write and read a file through a WebTTY sidecar
2
2
 
3
- Example of using `@rstreamlabs/webtty` to read and write files through the optional WebDAV filesystem sidecar.
3
+ This Node.js example writes `codex-note.txt` at the root of a WebTTY WebDAV
4
+ sidecar, lists the directory and reads the file through both text and streaming
5
+ methods. Use a disposable writable export. The write overwrites an existing
6
+ file of the same name.
4
7
 
5
- The sample only needs the WebTTY URL. If you build an inventory-driven integration, pass the advertised `fs_path` from `rstream webtty list -o json` as the SDK `fsPath` option.
8
+ [Build the checkout](../../../../docs/000-building-from-source.md) so this
9
+ sample can load its local SDK dependency. Use an authorized HTTPS endpoint
10
+ with a writable WebDAV sidecar at `/fs`. The
11
+ [sidecar guide](https://rstream.io/docs/webtty/quickstart#add-a-filesystem-sidecar)
12
+ explains server setup. If your endpoint advertises another `fs_path`, pass
13
+ it as `fsPath` in the sample.
14
+
15
+ From this directory, copy the example environment file and set
16
+ `RSTREAM_WEBTTY_URL` to the authorized URL in `.env.local`.
6
17
 
7
18
  ```sh
8
19
  cp .env.local.example .env.local
9
20
  npm install
10
21
  npm start
11
22
  ```
23
+
24
+ Expect the listing to contain `codex-note.txt` and both reads to print
25
+ `written through rstream WebTTY`. The process exits after the reads. Delete
26
+ the sample file from the export and remove the local credential file.
@@ -6,15 +6,15 @@
6
6
  "type": "module",
7
7
  "dependencies": {
8
8
  "@rstreamlabs/webtty": "file:../..",
9
- "dotenv": "^17.4.2"
9
+ "dotenv": "^18.0.10"
10
10
  },
11
11
  "scripts": {
12
12
  "start": "tsx src/main.ts",
13
13
  "type-check": "tsc --noEmit"
14
14
  },
15
15
  "devDependencies": {
16
- "@types/node": "^26",
17
- "tsx": "^4.23.1",
16
+ "@types/node": "^26.6.6",
17
+ "tsx": "^4.23.15",
18
18
  "typescript": "7.0.2"
19
19
  }
20
20
  }
@@ -2,10 +2,27 @@
2
2
 
3
3
  Example of using `@rstreamlabs/webtty` to run collected and streaming commands through a WebTTY server.
4
4
 
5
- The sample only needs the WebTTY URL. If you build an inventory-driven integration, pass the advertised `exec_path` from `rstream webtty list -o json` as the SDK `execPath` option.
5
+ [Build the checkout](../../../../docs/000-building-from-source.md), then use
6
+ this directory. Set `RSTREAM_WEBTTY_URL` in the copied `.env.local` file to an
7
+ authorized URL. For an inventory-driven integration, pass the advertised
8
+ `exec_path` from `rstream webtty list -o json` as the SDK `execPath` option.
6
9
 
7
10
  ```sh
8
11
  cp .env.local.example .env.local
9
12
  npm install
10
13
  npm start
11
14
  ```
15
+
16
+ The Node entry point supplies `nodeWebSocketFactory`, so it uses the qualified HTTP/1.1
17
+ WebSocket transport with certificate verification. Set `NODE_EXTRA_CA_CERTS`
18
+ before starting the process when the endpoint uses a private CA. The two commands
19
+ print collected output and then three streamed ticks. The remote server must
20
+ permit these commands and satisfy any endpoint/E2E trust policy; the sample does
21
+ not create a server or mint its URL grant.
22
+
23
+ After installation, run `npm run type-check` to check the sample against the
24
+ package types. From the monorepo root after building,
25
+ `node --test packages/webtty/test/remote-command-example.test.cjs` runs this
26
+ entrypoint against a synthetic TLS/WebSocket server without relying on a global
27
+ WebSocket. It verifies both commands and the selected HTTP/1.1 transport; it does
28
+ not execute a shell on a real host.
@@ -6,15 +6,15 @@
6
6
  "type": "module",
7
7
  "dependencies": {
8
8
  "@rstreamlabs/webtty": "file:../..",
9
- "dotenv": "^17.4.2"
9
+ "dotenv": "^18.0.10"
10
10
  },
11
11
  "scripts": {
12
12
  "start": "tsx src/main.ts",
13
13
  "type-check": "tsc --noEmit"
14
14
  },
15
15
  "devDependencies": {
16
- "@types/node": "^26",
17
- "tsx": "^4.23.1",
16
+ "@types/node": "^26.6.6",
17
+ "tsx": "^4.23.15",
18
18
  "typescript": "7.0.2"
19
19
  }
20
20
  }
@@ -1,7 +1,8 @@
1
1
  // See LICENSE file in the project root for license information.
2
2
 
3
3
  import dotenv from "dotenv";
4
- import { WebTTYRemoteExecutor } from "@rstreamlabs/webtty";
4
+ import { WebTTYRemoteExecutor } from "@rstreamlabs/webtty/node";
5
+ import { nodeWebSocketFactory } from "@rstreamlabs/webtty/node";
5
6
 
6
7
  dotenv.config({ path: ".env.local" });
7
8
 
@@ -14,6 +15,7 @@ function env(name: string): string {
14
15
  async function main(): Promise<void> {
15
16
  const executor = new WebTTYRemoteExecutor({
16
17
  url: env("RSTREAM_WEBTTY_URL"),
18
+ webSocketFactory: nodeWebSocketFactory,
17
19
  });
18
20
  const result = await executor.runCommand("sh", ["-lc", "uname -a && pwd"], {
19
21
  timeoutMs: 30_000,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rstreamlabs/webtty",
3
- "version": "1.12.1",
3
+ "version": "1.12.3",
4
4
  "description": "Client-side implementation of the rstream WebTTY protocol.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -41,20 +41,20 @@
41
41
  "type-check": "tsc --noEmit"
42
42
  },
43
43
  "devDependencies": {
44
- "@turbo/gen": "^2.10.11",
45
- "@types/node": "^26",
46
- "@types/ws": "^8.18.1",
44
+ "@turbo/gen": "^2.11.11",
45
+ "@types/node": "^26.6.6",
46
+ "@types/ws": "^8.18.2",
47
47
  "eslint": "9.39.5",
48
48
  "eslint-config": "*",
49
- "protobufjs-cli": "^2.6.2",
49
+ "protobufjs-cli": "^2.7.1",
50
50
  "tsup": "^8.5.1",
51
51
  "typescript": "6.0.3",
52
52
  "typescript-config": "*"
53
53
  },
54
54
  "dependencies": {
55
- "protobufjs": "^8.7.2",
56
- "ws": "^8.21.3",
57
- "@rstreamlabs/filesystem": "^0.3.0"
55
+ "protobufjs": "^8.8.1",
56
+ "ws": "^8.23.0",
57
+ "@rstreamlabs/filesystem": "^0.3.3"
58
58
  },
59
59
  "publishConfig": {
60
60
  "access": "public"