/** * JSON `/edge` WebSocket client for the TypeScript edge-client. * * Mirrors `edge-client/src/network/ws_client.rs` for wire shapes, URL auth, * registration, heartbeat metadata, ACK correlation, and reconnect backoff. The * binary `/shell-edge` channel is deliberately out of scope for this module. */ import { EventEmitter } from 'node:events'; import { type Settings } from '../config/settings.js'; export declare const SUBPROTOCOL_V2 = "edgeai-v2"; export declare const DEFAULT_HEARTBEAT_INTERVAL_MS = 30000; export declare const DEFAULT_MAX_PAYLOAD_BYTES: number; export type JsonPrimitive = string | number | boolean | null; export type JsonValue = JsonPrimitive | JsonObject | JsonValue[]; export interface JsonObject { [key: string]: JsonValue; } export interface RegisterMessage { type: 'register'; machine_id: string; agent_id: string; } export interface StreamMessage { msg_id: string; machine_id: string; agent_id: string; type: string; payload: JsonValue; timestamp: number; } export interface AckMessage { action: string; msg_id: string; } export interface SystemMetrics { cpu_cores: number | null; cpu_speed_mhz: number | null; load_avg_1m: number | null; load_avg_5m: number | null; cpu_usage_pct: number | null; mem_total_mb: number | null; mem_available_mb: number | null; disk_total_gb: number | null; disk_free_gb: number | null; process_count: number | null; } export interface HeartbeatMessage { type: 'heartbeat'; machine_id: string; platform?: string; hostname?: string; agent_version?: string; system?: SystemMetrics; operator_id?: string; } export interface BufferDrainable { enqueue(frame: StreamMessage): Promise; drain(): AsyncIterable; } export interface ReconnectOptions { initialDelayMs: number; maxDelayMs: number; multiplier: number; } export interface EdgeWsClientOptions { settings: Settings; edgeToken?: string; deviceSecret?: string; pinnedFingerprint?: string; networkMode?: string; buffer?: BufferDrainable; heartbeatIntervalMs?: number; requestTimeoutMs?: number; reconnect?: Partial; packageVersion?: string; } export interface EdgeWsClientEventMap { registered: [message: JsonObject]; inbound: [message: JsonObject]; online: []; offline: []; error: [error: Error]; agent_list: [message: JsonObject]; audit_event: [message: JsonObject]; heartbeat: [message: JsonObject]; config: [config: JsonObject | null]; info: [message: string]; event: [message: JsonObject]; } export type EdgeAuthDecision = { kind: 'Connect'; url: string; } | { kind: 'ConnectUnauthenticated'; url: string; } | { kind: 'Refuse'; }; export interface StreamMessageInput { machine_id: string; agent_id: string; type: string; payload: JsonValue; timestamp?: number; } export declare function createRegisterMessage(machineId: string, agentId: string): RegisterMessage; export declare function createStreamMessage(input: StreamMessageInput): StreamMessage; export declare function createAckMessage(msgId: string): AckMessage; export declare function encodeStreamMessage(message: StreamMessage): string; export declare function decodeStreamMessage(text: string): StreamMessage; export declare function isRegisterMessage(value: unknown): value is RegisterMessage; export declare function isStreamMessage(value: unknown): value is StreamMessage; export declare function isAckMessage(value: unknown): value is AckMessage; export declare function isHeartbeatMessage(value: unknown): value is HeartbeatMessage; export declare function selectRelayUrl(mode: string | undefined, lanUrl: string | undefined, wanUrl: string | undefined, defaultUrl: string): string; export declare function percentEncodeToken(token: string): string; export declare function appendEdgeToken(url: string, token: string | undefined): string; export declare function appendDeviceSecret(url: string, secret: string | undefined): string; /** * Build the AUTH-TOKEN half of the `Sec-WebSocket-Protocol` header. Caller * passes this to `ws` as a separate element in the `protocols` array * alongside SUBPROTOCOL_V2 — the resulting HTTP header reads * `Sec-WebSocket-Protocol: edgeai-v2, `. * * Edge-2-edge: the `deviceSecret` historically travelled INSIDE the * subprotocol header (so reverse-proxy logs could never see it), but for * v2 we omit it — we send only the opaque edge_token. Returns `undefined` * when there is no token to send, OR when the token is NOT a v2 opaque * token (a raw edge_token would trigger `malformed_opaque` 401 on the * server's subprotocol channel; raw tokens should travel via the URL * query string instead — which `decideEdgeAuth` already wires up). */ export declare function buildEdgeSubprotocolHeader(edgeToken: string | undefined, deviceSecret: string | undefined): string | undefined; /** True iff the token LOOKS like a v2 opaque token (`o...`). */ declare function isOpaqueToken(token: string): boolean; export { isOpaqueToken as _isOpaqueTokenForTests }; export declare function decideEdgeAuth(baseUrl: string, token: string | undefined, escapeActive: boolean): EdgeAuthDecision; /** * FIX 2026-07-12 (3.5 + 3.6 from review): wrap any Error before emitting * it from EdgeWsClient so the URL (and other sensitive tokens) can never * leak to listeners that log the raw error. EventEmitter's `emit('error', err)` * propagates the error verbatim — if `err.message` contains a URL with * `?edge_token=...&device_secret=...`, a single missed redaction in a * listener leaks credentials to the log. * * This helper produces a NEW Error whose `.message` has `redactUrl()` * applied. The original `.stack` is preserved (so debugging still works) * but we strip the message portion of the stack (the first line) so the * URL isn't in the stack either. Listeners that destructure * `{ message, code }` are safe; listeners that log `err.toString()` are * also safe (toString uses message). */ export declare function redactErrorUrl(err: Error): Error; export { redactUrl } from './redact-url.js'; export declare function buildHeartbeatMessage(settings: Settings, packageVersion?: string): HeartbeatMessage; export declare class EdgeWsClient extends EventEmitter { private readonly settings; private readonly edgeToken; private deviceSecret; private readonly pinnedFingerprint; private readonly buffer; private readonly heartbeatIntervalMs; private readonly requestTimeoutMs; private readonly reconnect; private readonly packageVersion; private readonly localQueue; private readonly pending; private ws; private started; private stopping; private registered; private online; private flushing; private networkMode; private reconnectAttempts; private heartbeatTimer; private reconnectTimer; private lastRelayHeartbeatMs; constructor(options: EdgeWsClientOptions); on(event: K, listener: (...args: EdgeWsClientEventMap[K]) => void): this; once(event: K, listener: (...args: EdgeWsClientEventMap[K]) => void): this; off(event: K, listener: (...args: EdgeWsClientEventMap[K]) => void): this; emit(event: K, ...args: EdgeWsClientEventMap[K]): boolean; start(): Promise; stop(): Promise; send(message: StreamMessage): Promise; request(message: StreamMessage, timeoutMs?: number): Promise; sendHeartbeat(): Promise; isOnline(): boolean; isRegistered(): boolean; lastRelayHeartbeat(): number | undefined; currentUrl(): string; private connect; private buildWebSocketOptions; private createPinnedTlsConnection; private resolveCurrentUrl; private inboundTokenBucket; private inboundLastRefillMs; private inboundLastWarnMs; private static readonly RATE_LIMIT_CAPACITY; private static readonly RATE_LIMIT_REFILL_PER_SEC; private static readonly RATE_LIMIT_WARN_INTERVAL_MS; private handleRawMessage; private dispatchAction; private dispatchAckOrType; private handleRegistered; private applyConfigMessage; private handleNetworkModeChange; private ackConfigMessage; private requestConfigSnapshot; private replyWithConfigSnapshot; private resolvePending; private canSendNow; private sendStreamNow; private sendJsonObject; private sendText; private enqueueOffline; private flushOutbound; private startHeartbeat; private restartHeartbeat; private stopHeartbeat; private handleClose; private markOffline; private forceReconnect; private scheduleReconnect; private clearReconnectTimer; private rejectAllPending; } export declare function reconnectDelayMs(attempt: number, options: ReconnectOptions): number;