@robota-sdk/agent-transport-ws 3.0.0-beta.78 → 3.0.0-beta.81

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.
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Connection-admission guards for the WS transport (SEC-001 / GUI-002).
3
+ *
4
+ * Pure, socket-free predicates over the HTTP upgrade request — token minting/comparison plus the
5
+ * `Host` and `Origin` allow-lists. Split out of `ws-transport-configurable.ts` so the transport file
6
+ * carries lifecycle and frame routing only; the admission policy is independently readable and the
7
+ * transport module stays within the file-size ratchet.
8
+ */
9
+
10
+ import { timingSafeEqual } from 'node:crypto';
11
+
12
+ import { resolveAdmission } from '@robota-sdk/agent-transport/node';
13
+
14
+ import type { ITransportAdmission } from '@robota-sdk/agent-interface-transport';
15
+ import type { IncomingMessage } from 'node:http';
16
+
17
+ /**
18
+ * Host names that are always loopback (port stripped by the caller). IPv4 bind only, so `[::1]`
19
+ * inbound is moot, but accepting it is harmless.
20
+ */
21
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
22
+
23
+ /** Strip the `:port` suffix from a Host/authority (port-agnostic — `bindWithRetry` can walk the port). */
24
+ function hostname(hostHeader: string | undefined): string | null {
25
+ if (!hostHeader) return null;
26
+ if (hostHeader.startsWith('[')) return hostHeader.slice(0, hostHeader.indexOf(']') + 1) || null;
27
+ const colon = hostHeader.lastIndexOf(':');
28
+ return colon === -1 ? hostHeader : hostHeader.slice(0, colon);
29
+ }
30
+
31
+ /**
32
+ * The upgrade `Host` must be a loopback name (port-agnostic) or an explicitly allowed host — closes
33
+ * DNS rebinding. A missing `Host` is rejected (a well-formed HTTP/1.1 client always sends one).
34
+ */
35
+ export function hostAllowed(req: IncomingMessage, allowedHosts: ReadonlySet<string>): boolean {
36
+ const host = hostname(req.headers.host);
37
+ if (host === null) return false;
38
+ return LOOPBACK_HOSTS.has(host) || allowedHosts.has(host);
39
+ }
40
+
41
+ /**
42
+ * A browser sends an unforgeable `Origin`; require it to be loopback or explicitly allowed. A
43
+ * non-browser client omits `Origin` (allowed here — the token is its gate). Closes the browser
44
+ * drive-by hole.
45
+ */
46
+ export function originAllowed(req: IncomingMessage, allowedOrigins: ReadonlySet<string>): boolean {
47
+ const origin = req.headers.origin;
48
+ if (origin === undefined) return true; // non-browser client; token still required
49
+ if (allowedOrigins.has(origin)) return true;
50
+ try {
51
+ return LOOPBACK_HOSTS.has(new URL(origin).hostname);
52
+ } catch {
53
+ return false; // malformed Origin → reject
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Constant-time token comparison. Returns false on any length mismatch (never throws), so an
59
+ * absent/short/long presented token is a plain reject, not an error.
60
+ */
61
+ export function tokenMatches(expected: string, presented: string | null | undefined): boolean {
62
+ if (!presented) return false;
63
+ const a = Buffer.from(expected);
64
+ const b = Buffer.from(presented);
65
+ if (a.length !== b.length) return false;
66
+ return timingSafeEqual(a, b);
67
+ }
68
+
69
+ /** Read the presented token from the upgrade request: `?token=` query param, else the WS subprotocol. */
70
+ export function presentedToken(req: IncomingMessage): string | null {
71
+ try {
72
+ const url = new URL(req.url ?? '', 'ws://127.0.0.1');
73
+ const q = url.searchParams.get('token');
74
+ if (q) return q;
75
+ } catch {
76
+ // malformed URL → fall through to the subprotocol header
77
+ }
78
+ const proto = req.headers['sec-websocket-protocol'];
79
+ return typeof proto === 'string' ? proto.split(',')[0]?.trim() || null : null;
80
+ }
81
+
82
+ /**
83
+ * This transport's admission decision, asked of the shared seam.
84
+ *
85
+ * Lives here rather than in the transport file because this module already owns the admission
86
+ * policy — token comparison and the Host/Origin allow-lists — and the transport file carries
87
+ * lifecycle and frame routing. The split is also what keeps that file inside its size ratchet.
88
+ */
89
+ export function resolveWsAdmission(config: {
90
+ token?: string;
91
+ open?: boolean;
92
+ openReason?: string;
93
+ }): ITransportAdmission {
94
+ // No fabricated reason. The first version filled one in for any caller that omitted it, which made
95
+ // WS the one transport where `{ open: true }` alone was accepted — HTTP and WebRTC both refuse it.
96
+ // Review found that: a reason invented on the caller's behalf reads, to the next person, as a
97
+ // decision somebody made. The whole point of requiring it is that nobody can produce one by
98
+ // accident, so the seam is asked the question exactly as it was given.
99
+ return resolveAdmission({
100
+ ...(config.token !== undefined ? { token: config.token } : {}),
101
+ ...(config.open === true ? { open: true } : {}),
102
+ ...(config.openReason !== undefined ? { openReason: config.openReason } : {}),
103
+ });
104
+ }
@@ -0,0 +1,8 @@
1
+ import type { RawData } from 'ws';
2
+
3
+ /** Normalize the `ws` inbound payload variants to one binary view. */
4
+ export function toBytes(data: RawData): Uint8Array {
5
+ if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data));
6
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
7
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
8
+ }
@@ -0,0 +1,109 @@
1
+ import {
2
+ createOutboundDelivery,
3
+ createPendingStallClock,
4
+ DEFAULT_MAX_PENDING_BYTES,
5
+ isOverPendingBudget,
6
+ } from '@robota-sdk/agent-transport';
7
+ import { WebSocket } from 'ws';
8
+
9
+ import type {
10
+ IPendingStallClock,
11
+ TOutboundDeliver,
12
+ TServerMessage,
13
+ } from '@robota-sdk/agent-transport';
14
+
15
+ /**
16
+ * Connection-scoped session delivery lifecycle shared by sync and async WebSocket failures.
17
+ *
18
+ * ARCH-030: {@link deliver} is the ONLY way out of this class. The raw sink — the `readyState` check
19
+ * plus `socket.send` — is private, so no caller can put a frame on this socket outside the connection's
20
+ * one outbound boundary. That is not stylistic: the previous shape exposed a public `send` that threw
21
+ * on a closed socket, and every reply the protocol handler produced went through it unguarded.
22
+ */
23
+ export class WsSessionDelivery {
24
+ private cleanupProtocol = (): void => undefined;
25
+ private detachSink = (): void => undefined;
26
+ private closed = false;
27
+ /**
28
+ * Issue #2306: ONE drain clock for the socket. `bufferedAmount` does not distinguish text from
29
+ * binary, so both halves observe the same clock — a slow reader of payload frames is caught when a
30
+ * JSON reply is attempted, and the reverse.
31
+ */
32
+ private readonly stallClock: IPendingStallClock = createPendingStallClock();
33
+
34
+ /**
35
+ * The connection's outbound boundary. Built here, from this class's own sink and its own `close`
36
+ * policy, and passed DOWN into `createSessionMessageHandler` — the carrier owns both halves, so it builds the
37
+ * boundary rather than handing the protocol layer a raw sink to wrap.
38
+ */
39
+ readonly deliver: TOutboundDeliver;
40
+
41
+ constructor(private readonly socket: WebSocket) {
42
+ this.deliver = createOutboundDelivery(
43
+ (message) => this.rawSend(message),
44
+ () => this.close(),
45
+ // ARCH-030 / issue #1734: the socket's own count of what it has accepted and not yet written.
46
+ // Read at call time — it changes underneath.
47
+ () => this.socket.bufferedAmount,
48
+ DEFAULT_MAX_PENDING_BYTES,
49
+ this.stallClock,
50
+ );
51
+ }
52
+
53
+ /**
54
+ * Put a TRANS-001 payload frame on this socket, under the SAME budget and the same close policy as
55
+ * the text protocol (ARCH-030 / issue #1734).
56
+ *
57
+ * A WebSocket carries two kinds of outbound frame over one socket, and until this existed the
58
+ * binary half went straight to `socket.send` — outside the boundary, with no budget, and with a
59
+ * failure that could only surface as a throw inside a listener. `bufferedAmount` does not
60
+ * distinguish the two, so a non-reading peer accumulating payload frames was invisible to a budget
61
+ * that only guarded the other half.
62
+ *
63
+ * It is not `deliver`: that boundary is typed for `TServerMessage` and its brand is what makes a
64
+ * raw send unusable where a protocol frame is required. Widening it to accept bytes would remove
65
+ * the property the brand exists for.
66
+ */
67
+ readonly deliverBinary = (frame: Uint8Array): void => {
68
+ if (this.closed) return;
69
+ if (this.socket.readyState !== WebSocket.OPEN) return;
70
+ if (
71
+ isOverPendingBudget(this.socket.bufferedAmount) ||
72
+ this.stallClock.observe(this.socket.bufferedAmount) !== undefined
73
+ ) {
74
+ this.close();
75
+ return;
76
+ }
77
+ this.socket.send(frame, { binary: true }, (error) => {
78
+ if (error) this.close();
79
+ });
80
+ };
81
+
82
+ private rawSend(message: TServerMessage): void {
83
+ if (this.socket.readyState !== WebSocket.OPEN) throw new Error('WebSocket is not open');
84
+ this.socket.send(JSON.stringify(message), (error) => {
85
+ if (error) this.close();
86
+ });
87
+ }
88
+
89
+ bindProtocolCleanup(cleanup: () => void): void {
90
+ this.cleanupProtocol = cleanup;
91
+ }
92
+
93
+ bindSinkDetach(detach: () => void): void {
94
+ this.detachSink = detach;
95
+ }
96
+
97
+ readonly close = (): void => {
98
+ if (this.closed) return;
99
+ this.closed = true;
100
+ this.detachSink();
101
+ this.cleanupProtocol();
102
+ if (
103
+ this.socket.readyState === WebSocket.OPEN ||
104
+ this.socket.readyState === WebSocket.CONNECTING
105
+ ) {
106
+ this.socket.close(1011, 'session event delivery failed');
107
+ }
108
+ };
109
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The construction contract for `WsTransport` — what a caller decides before the server exists.
3
+ *
4
+ * Split from `ws-transport-configurable.ts` under the file-size ceiling, and the seam is the
5
+ * honest one: everything here is a decision the CALLER makes (port, retries, admission — SEC-008's
6
+ * `token`/`open`/`openReason` contract lives in these doc comments), while the class next door is
7
+ * what the transport DOES with those decisions.
8
+ */
9
+
10
+ import type { TUsageSurface } from '@robota-sdk/agent-interface-analytics';
11
+ import type { TDriverId } from '@robota-sdk/agent-interface-session';
12
+ import type { ITransportLifecycleError } from '@robota-sdk/agent-interface-transport';
13
+ import type { ISessionMessageHandlerOptions } from '@robota-sdk/agent-transport';
14
+
15
+ export const DEFAULT_PORT = 7070;
16
+ export const DEFAULT_MAX_RETRIES = 20;
17
+
18
+ export interface IWsTransportConfig {
19
+ /** Trusted server-assigned identity for turns submitted over this product surface. */
20
+ driverId?: TDriverId;
21
+ /** Trusted product surface, independent from the connection's driver identity. */
22
+ surface?: TUsageSurface;
23
+ /** Host-owned cross-session usage read model, forwarded unchanged to the protocol handler. */
24
+ personalUsageReporter?: ISessionMessageHandlerOptions['personalUsageReporter'];
25
+ /** Host-owned current-session trace/cost producer, forwarded unchanged to the protocol handler. */
26
+ usageReporter?: ISessionMessageHandlerOptions['usageReporter'];
27
+ /** Host-owned stored-session trace/cost producer for personal-usage drill-down. */
28
+ storedSessionUsageReporter?: ISessionMessageHandlerOptions['storedSessionUsageReporter'];
29
+ port?: number;
30
+ maxRetries?: number;
31
+ /**
32
+ * OPTIONAL explicit loopback auth token. When set, every connection MUST present a matching token
33
+ * (query param `?token=` or the `Sec-WebSocket-Protocol` subprotocol) or the socket is closed BEFORE any
34
+ * session data is emitted (GUI-002; the GUI sidecar sets `ROBOTA_WS_TOKEN`). SEC-001: when this is unset
35
+ * AND `open` is not `true`, the transport AUTO-MINTS a random per-launch token (secure by default) —
36
+ * `resolvedToken` exposes it so the surface can deliver it to the co-located client (a `0600` connection
37
+ * file / the served monitor's injected `ws-url`). An explicit token here wins over the auto-mint — but NOT
38
+ * over `open`: SEC-008 makes a token together with `open: true` a contradiction that throws, rather
39
+ * than a precedence one side quietly wins.
40
+ */
41
+ token?: string;
42
+ /**
43
+ * SEC-001 discouraged opt-out: when `true`, run WITHOUT auth (no token, no auto-mint) — the pre-SEC-001
44
+ * open loopback behavior. NOT RECOMMENDED (any local process or browser page can then drive+authorize the
45
+ * session); mirrors Jupyter's `c.ServerApp.token = ''`.
46
+ *
47
+ * SEC-008: `open: true` together with a non-empty `token` is REJECTED, not resolved by precedence. The
48
+ * two ask for opposite things, and picking a winner silently is how a caller ends up with the admission
49
+ * it did not choose. `resolveAdmission` decides that for every transport, so they cannot differ.
50
+ */
51
+ open?: boolean;
52
+ /** SEC-008: why running with no credential is correct here. Required when `open` is true. */
53
+ openReason?: string;
54
+ /**
55
+ * SEC-001 defense-in-depth: extra host names (beyond `localhost`/`127.0.0.1`/`::1`) accepted in the
56
+ * upgrade `Host` header. The `Host` allow-list closes DNS-rebinding independently of the token.
57
+ */
58
+ allowedHosts?: readonly string[];
59
+ /**
60
+ * SEC-001 defense-in-depth: extra browser `Origin`s (beyond loopback) accepted on the upgrade — e.g. the
61
+ * `apps/agent-web` app origin. A browser sends an unforgeable `Origin`; a non-browser client omits it (and
62
+ * is gated by the token instead). Closes the "any web page in any browser" hole before history is emitted.
63
+ */
64
+ allowedOrigins?: readonly string[];
65
+ }
66
+
67
+ type TUsageReporters = Pick<
68
+ ISessionMessageHandlerOptions,
69
+ 'personalUsageReporter' | 'usageReporter' | 'storedSessionUsageReporter'
70
+ >;
71
+
72
+ /** Remove absent reporters so exact-optional handler options remain truthful. */
73
+ function configuredUsageReporters(config: IWsTransportConfig): TUsageReporters {
74
+ return {
75
+ ...(config.personalUsageReporter
76
+ ? { personalUsageReporter: config.personalUsageReporter }
77
+ : {}),
78
+ ...(config.usageReporter ? { usageReporter: config.usageReporter } : {}),
79
+ ...(config.storedSessionUsageReporter
80
+ ? { storedSessionUsageReporter: config.storedSessionUsageReporter }
81
+ : {}),
82
+ };
83
+ }
84
+
85
+ type TConfiguredHandlerOptions = Pick<
86
+ ISessionMessageHandlerOptions,
87
+ 'driverId' | 'surface' | 'personalUsageReporter' | 'usageReporter' | 'storedSessionUsageReporter'
88
+ >;
89
+
90
+ /** Project immutable transport attribution/reporters into each protocol handler. */
91
+ export function configuredWsHandlerOptions(config: IWsTransportConfig): TConfiguredHandlerOptions {
92
+ return {
93
+ ...(config.driverId ? { driverId: config.driverId } : {}),
94
+ ...(config.surface ? { surface: config.surface } : {}),
95
+ ...configuredUsageReporters(config),
96
+ };
97
+ }
98
+
99
+ export function validTransportOptions(options: Readonly<Record<string, unknown>>): boolean {
100
+ const { port, maxRetries } = options;
101
+ if (port !== undefined && (typeof port !== 'number' || port < 1 || port > 65535)) return false;
102
+ return maxRetries === undefined || (typeof maxRetries === 'number' && maxRetries >= 0);
103
+ }
104
+
105
+ export function transportLifecycleError(
106
+ transportName: string,
107
+ code: ITransportLifecycleError['code'],
108
+ ): ITransportLifecycleError {
109
+ return Object.assign(new Error(`${transportName} ${code}.`), {
110
+ name: 'TransportLifecycleError' as const,
111
+ code,
112
+ transportName,
113
+ });
114
+ }
@@ -3,29 +3,59 @@
3
3
  * Owns the WebSocket server lifecycle (ws package), started/stopped via the transport registry.
4
4
  */
5
5
 
6
- import { createServer, type Server } from 'node:http';
6
+ import { createServer, type IncomingMessage, type Server } from 'node:http';
7
7
 
8
- import { WebSocketServer, WebSocket } from 'ws';
8
+ import { createSessionMessageHandler } from '@robota-sdk/agent-transport';
9
+ import { WebSocketServer } from 'ws';
9
10
 
10
- import { createWsHandler } from './ws-handler.js';
11
+ import { PayloadChannelRegistry } from './payload-channels.js';
12
+ import {
13
+ hostAllowed,
14
+ originAllowed,
15
+ presentedToken,
16
+ resolveWsAdmission,
17
+ tokenMatches,
18
+ } from './ws-connection-guards.js';
19
+ import { toBytes } from './ws-message-data.js';
20
+ import { WsSessionDelivery } from './ws-session-delivery.js';
21
+ import {
22
+ DEFAULT_MAX_RETRIES,
23
+ DEFAULT_PORT,
24
+ configuredWsHandlerOptions,
25
+ transportLifecycleError,
26
+ validTransportOptions,
27
+ } from './ws-transport-config.js';
11
28
 
12
- import type { TServerMessage } from './ws-protocol.js';
29
+ import type { IWsTransportConfig } from './ws-transport-config.js';
13
30
  import type { TUniversalValue } from '@robota-sdk/agent-core';
14
31
  import type {
32
+ IChannelDescriptor,
15
33
  IConfigurableTransport,
16
- IInteractiveSession,
34
+ IPayloadChannel,
35
+ IPayloadChannelHost,
36
+ TChannelEventMap,
17
37
  } from '@robota-sdk/agent-interface-transport';
38
+ import type { IProtocolSession } from '@robota-sdk/agent-transport';
39
+ import type { RawData, WebSocket } from 'ws';
18
40
 
19
- const DEFAULT_PORT = 7070;
20
- const DEFAULT_MAX_RETRIES = 20;
21
-
22
- export interface IWsTransportConfig {
23
- port?: number;
24
- maxRetries?: number;
25
- }
41
+ /**
42
+ * RUNTIME-13: forced-terminate deadline for `stop()`. `WebSocketServer.close()` fires its callback only after
43
+ * every client socket is gone, so a still-connected client would hang `stop()` forever. We send a close frame
44
+ * (1001 "going away") to each client, then `terminate()` any socket still open at this deadline — the RFC 6455
45
+ * + `ws` + drain-then-force convention (a WS close handshake completes in well under a second; 5s is generous).
46
+ */
47
+ const WS_STOP_TERMINATE_DEADLINE_MS = 5000;
26
48
 
27
- export class WsTransport implements IConfigurableTransport<IInteractiveSession> {
49
+ /**
50
+ * TRANS-001: the WS transport is a payload-agnostic CARRIER that routes by WebSocket frame opcode —
51
+ * TEXT frames go to the text-agent protocol profile (`createSessionMessageHandler`), BINARY frames go to the
52
+ * consumer-declared channels. The two profiles share one connection and never constrain each other.
53
+ */
54
+ export class WsTransport
55
+ implements IConfigurableTransport<IProtocolSession>, IPayloadChannelHost
56
+ {
28
57
  readonly name = 'ws';
58
+ readonly lifecycle = Object.freeze({ kind: 'service' as const });
29
59
  readonly defaultEnabled = true;
30
60
  readonly optionsSchema = {
31
61
  port: { type: 'number', description: 'WebSocket server port', default: DEFAULT_PORT },
@@ -36,44 +66,132 @@ export class WsTransport implements IConfigurableTransport<IInteractiveSession>
36
66
  },
37
67
  };
38
68
 
39
- private session: IInteractiveSession | null = null;
69
+ private session: IProtocolSession | null = null;
40
70
  private stopFn: (() => Promise<void>) | null = null;
41
- private readonly port: number;
42
- private readonly maxRetries: number;
71
+ private state: 'detached' | 'attached' | 'starting' | 'ready' | 'stopping' = 'detached';
72
+ private startOperation: Promise<{ stop: () => Promise<void>; port: number }> | undefined;
73
+ private startCancelled = false;
74
+ private port: number;
75
+ private maxRetries: number;
76
+ private readonly token?: string;
77
+ private readonly allowedHosts: ReadonlySet<string>;
78
+ private readonly allowedOrigins: ReadonlySet<string>;
79
+ private readonly handlerOptions: ReturnType<typeof configuredWsHandlerOptions>;
80
+ private readonly channels = new PayloadChannelRegistry();
81
+ private resolvedPort?: number;
43
82
 
44
83
  constructor(config: IWsTransportConfig = {}) {
45
84
  this.port = config.port ?? DEFAULT_PORT;
46
85
  this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
86
+ // SEC-001/SEC-008: secure by default, decided by the shared seam rather than a copy here — see
87
+ // SPEC § Transport Admission. A failed mint throws out of the constructor (fail-closed).
88
+ const admission = resolveWsAdmission(config);
89
+ if (admission.token !== null) this.token = admission.token;
90
+ this.allowedHosts = new Set(config.allowedHosts ?? []);
91
+ this.allowedOrigins = new Set(config.allowedOrigins ?? []);
92
+ this.handlerOptions = configuredWsHandlerOptions(config);
47
93
  }
48
94
 
49
- attach(session: IInteractiveSession): void {
95
+ attach(session: IProtocolSession): void {
50
96
  this.session = session;
97
+ this.state = 'attached';
98
+ }
99
+
100
+ /**
101
+ * TRANS-001: declare an app-level channel carried on this transport's connections. The channel's
102
+ * events and opaque binary frames ride alongside the text-agent protocol on the SAME socket — the
103
+ * transport never inspects the payloads. Register before or after `start()`; a channel opened
104
+ * later is served by every already-connected client.
105
+ */
106
+ registerChannel<TEvents extends TChannelEventMap>(
107
+ descriptor: IChannelDescriptor<TEvents>,
108
+ ): IPayloadChannel<TEvents> {
109
+ return this.channels.registerChannel(descriptor);
110
+ }
111
+
112
+ /** Actually-bound port after start; undefined before start. */
113
+ get boundPort(): number | undefined {
114
+ return this.resolvedPort;
115
+ }
116
+
117
+ /**
118
+ * SEC-001: the resolved auth token (explicit or auto-minted), or `undefined` in the discouraged `open`
119
+ * mode. The surface reads this to deliver the token to the co-located client (a `0600` connection file /
120
+ * the served monitor's injected `ws-url`). Never logged by the transport itself.
121
+ */
122
+ get resolvedToken(): string | undefined {
123
+ return this.token;
51
124
  }
52
125
 
53
126
  async start(): Promise<void> {
54
- if (!this.session) throw new Error('WsTransport: attach() must be called before start()');
55
- const handle = await this.bindWithRetry(this.session, this.port, this.maxRetries);
127
+ if (!this.session) throw transportLifecycleError(this.name, 'not-attached');
128
+ if (this.state === 'starting' || this.state === 'ready' || this.state === 'stopping') {
129
+ throw transportLifecycleError(this.name, 'already-started');
130
+ }
131
+ this.state = 'starting';
132
+ this.startCancelled = false;
133
+ const operation = this.bindWithRetry(this.session, this.port, this.maxRetries);
134
+ this.startOperation = operation;
135
+ let handle: Awaited<typeof operation>;
136
+ try {
137
+ handle = await operation;
138
+ } catch (error) {
139
+ if (this.state === 'starting' && this.startOperation === operation) {
140
+ this.startOperation = undefined;
141
+ this.state = this.session ? 'attached' : 'detached';
142
+ }
143
+ throw error;
144
+ }
145
+ if (this.startCancelled || this.startOperation !== operation) {
146
+ await handle.stop();
147
+ this.state = this.session ? 'attached' : 'detached';
148
+ throw new Error('WsTransport startup was stopped.');
149
+ }
56
150
  this.stopFn = handle.stop;
151
+ this.resolvedPort = handle.port;
152
+ this.startOperation = undefined;
153
+ this.state = 'ready';
57
154
  }
58
155
 
59
156
  async stop(): Promise<void> {
157
+ if (this.state === 'starting') {
158
+ this.state = 'stopping';
159
+ this.startCancelled = true;
160
+ try {
161
+ await this.startOperation;
162
+ } catch {
163
+ // The start caller owns bind failure; stop still clears lifecycle state.
164
+ }
165
+ }
60
166
  await this.stopFn?.();
61
167
  this.stopFn = null;
168
+ this.startOperation = undefined;
169
+ this.resolvedPort = undefined;
170
+ this.session = null;
171
+ this.state = 'detached';
172
+ }
173
+
174
+ /** TRANS-002 (issue #2480): persisted `port`/`maxRetries` reach the server through here, before start. */
175
+ configure(options: Record<string, TUniversalValue>): void {
176
+ if (this.state !== 'detached' && this.state !== 'attached') {
177
+ throw transportLifecycleError(this.name, 'already-started');
178
+ }
179
+ if (!this.validateOptions(options)) {
180
+ throw new TypeError('WsTransport options are invalid (port 1-65535, maxRetries >= 0).');
181
+ }
182
+ if (typeof options['port'] === 'number') this.port = options['port'];
183
+ if (typeof options['maxRetries'] === 'number') this.maxRetries = options['maxRetries'];
62
184
  }
63
185
 
64
186
  validateOptions(options: Record<string, TUniversalValue>): boolean {
65
- const { port, maxRetries } = options;
66
- if (port !== undefined && (typeof port !== 'number' || port < 1 || port > 65535)) return false;
67
- if (maxRetries !== undefined && (typeof maxRetries !== 'number' || maxRetries < 0))
68
- return false;
69
- return true;
187
+ return validTransportOptions(options);
70
188
  }
71
189
 
72
190
  private bindWithRetry(
73
- session: IInteractiveSession,
191
+ session: IProtocolSession,
74
192
  port: number,
75
193
  retriesLeft: number,
76
- ): Promise<{ stop: () => Promise<void> }> {
194
+ ): Promise<{ stop: () => Promise<void>; port: number }> {
77
195
  return this.tryBind(session, port).catch((err: NodeJS.ErrnoException) => {
78
196
  if (err.code === 'EADDRINUSE' && retriesLeft > 0)
79
197
  return this.bindWithRetry(session, port + 1, retriesLeft - 1);
@@ -82,9 +200,9 @@ export class WsTransport implements IConfigurableTransport<IInteractiveSession>
82
200
  }
83
201
 
84
202
  private tryBind(
85
- session: IInteractiveSession,
203
+ session: IProtocolSession,
86
204
  port: number,
87
- ): Promise<{ stop: () => Promise<void> }> {
205
+ ): Promise<{ stop: () => Promise<void>; port: number }> {
88
206
  return new Promise((resolve, reject) => {
89
207
  const httpServer: Server = createServer((_, res) => {
90
208
  res.writeHead(400).end('WebSocket endpoint');
@@ -95,31 +213,90 @@ export class WsTransport implements IConfigurableTransport<IInteractiveSession>
95
213
  reject(err);
96
214
  });
97
215
 
216
+ const expectedToken = this.token;
217
+ const allowedHosts = this.allowedHosts;
218
+ const allowedOrigins = this.allowedOrigins;
219
+ const channels = this.channels;
98
220
  httpServer.listen(port, '127.0.0.1', () => {
99
- const wss = new WebSocketServer({ server: httpServer });
221
+ const wss = new WebSocketServer({
222
+ server: httpServer,
223
+ // Reject disallowed Host/Origin before the protocol upgrade or any session data.
224
+ verifyClient: (
225
+ info: { origin: string; secure: boolean; req: IncomingMessage },
226
+ cb: (res: boolean, code?: number, message?: string) => void,
227
+ ) => {
228
+ if (!hostAllowed(info.req, allowedHosts)) {
229
+ cb(false, 403, 'Forbidden host');
230
+ return;
231
+ }
232
+ if (!originAllowed(info.req, allowedOrigins)) {
233
+ cb(false, 403, 'Forbidden origin');
234
+ return;
235
+ }
236
+ cb(true);
237
+ },
238
+ });
239
+
240
+ wss.on('connection', (ws: WebSocket, req: IncomingMessage) => {
241
+ // Reject unauthenticated peers before sending history or accepting prompt responses.
242
+ if (expectedToken !== undefined && !tokenMatches(expectedToken, presentedToken(req))) {
243
+ ws.close(1008, 'unauthorized');
244
+ return;
245
+ }
100
246
 
101
- wss.on('connection', (ws: WebSocket) => {
102
- const send = (message: TServerMessage): void => {
103
- if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
104
- };
247
+ const delivery = new WsSessionDelivery(ws);
248
+ const handler = createSessionMessageHandler({
249
+ session,
250
+ deliver: delivery.deliver,
251
+ ...this.handlerOptions,
252
+ });
253
+ delivery.bindProtocolCleanup(handler.cleanup);
105
254
 
106
- const { onMessage, cleanup } = createWsHandler({ session, send });
255
+ delivery.bindSinkDetach(
256
+ // ARCH-030: through the connection's own delivery, so payload frames share the text
257
+ // protocol's backpressure budget and its close policy. The bare `readyState` check plus
258
+ // `ws.send` that stood here was the last outbound path on this socket outside the
259
+ // boundary.
260
+ channels.addSink((frame: Uint8Array) => delivery.deliverBinary(frame)),
261
+ );
107
262
 
108
- ws.on('message', (data) => onMessage(String(data)));
109
- ws.on('close', cleanup);
110
- ws.on('error', cleanup);
263
+ // Route by frame opcode: TEXT → the text-agent protocol profile, BINARY → the
264
+ // payload-agnostic channels. An unroutable channel frame is answered with an explicit
265
+ // `protocol_error` rather than silently dropped.
266
+ ws.on('message', (data: RawData, isBinary: boolean) => {
267
+ if (!isBinary) {
268
+ handler.onMessage(String(data));
269
+ return;
270
+ }
271
+ const result = channels.receive(toBytes(data));
272
+ if (!result.ok) delivery.deliver({ type: 'protocol_error', message: result.error });
273
+ });
274
+ ws.on('close', delivery.close);
275
+ ws.on('error', delivery.close);
111
276
 
112
- send({ type: 'messages', messages: session.getMessages() });
113
- send({
277
+ delivery.deliver({ type: 'messages', messages: session.getMessages() });
278
+ delivery.deliver({
114
279
  type: 'execution_workspace_event',
115
280
  snapshot: session.getExecutionWorkspaceSnapshot(),
116
281
  });
117
282
  });
118
283
 
119
284
  resolve({
285
+ port,
120
286
  stop: () =>
121
287
  new Promise<void>((res) => {
122
- wss.close(() => httpServer.close(() => res()));
288
+ // RUNTIME-13: graceful-then-forced shutdown. Send a close frame to each client so well-behaved
289
+ // peers close cleanly; terminate any socket still open at the deadline so `wss.close()`'s
290
+ // all-clients-gone callback can never hang. `verifyClient`/token gates are connection-time and
291
+ // untouched here (SEC-001 preserved).
292
+ for (const client of wss.clients) client.close(1001, 'server shutting down');
293
+ const deadline = setTimeout(() => {
294
+ for (const client of wss.clients) client.terminate();
295
+ }, WS_STOP_TERMINATE_DEADLINE_MS);
296
+ wss.close(() => {
297
+ clearTimeout(deadline);
298
+ httpServer.close(() => res());
299
+ });
123
300
  }),
124
301
  });
125
302
  });