Files
Claw3D/src/lib/gateway/openclaw/GatewayBrowserClient.ts
T
GordoCursor AgentLuke The DevElias PfefferClaude Sonnet 4.6copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>Greg Clarkiamlukethedev
4e552967d9 [PRIORITY][FEAT] merge runtime profiles, office systems, doctor, and vera lane convergence (#109)
* fix: include kanbanImmersive in immersiveOverlayActive calculation

When Kanban board is open, HUD elements (camera preset buttons, edit toolbar, overlays) should be suppressed. The kanbanImmersive flag was defined but not included in the immersiveOverlayActive condition, causing HUD elements to remain visible.

This fix adds kanbanImmersive to the immersiveOverlayActive calculation so HUD elements are properly hidden when the Kanban board is open.

Co-authored-by: Luke The Dev <iamlukethedev@users.noreply.github.com>

* Fix: Hide mini status bar when Kanban immersive overlay is open

Wraps the bottom-left mini status bar (showing agent stats, vibe score, and
control hints) with !immersiveOverlayActive check to match the behavior of
other HUD elements like camera controls and toolbar.

This ensures the status bar is properly hidden when the Kanban board or any
other immersive overlay is active, maintaining a clean immersive experience.

Co-authored-by: Luke The Dev <iamlukethedev@users.noreply.github.com>

* chore: drop unrelated package-lock line from branch

Co-authored-by: Luke The Dev <iamlukethedev@users.noreply.github.com>

* universal-backend-plan

* backend-neutral runtime seam

* package.json update

* feat: add Hermes gateway adapter as alternative to OpenClaw

Adds a WebSocket adapter that lets Claw3D connect to a Hermes AI agent
runtime without any changes to the frontend. The adapter implements the
full Claw3D gateway protocol and bridges it to the Hermes HTTP API.

Changes:
- server/hermes-gateway-adapter.js: WebSocket bridge implementing the
  Claw3D gateway protocol against the Hermes HTTP API. Supports all
  core methods (agents, sessions, chat streaming, cron, config, files,
  approvals) and multi-agent orchestration via spawn_agent/delegate_task
  tools. Persists conversation history to ~/.hermes/clawd3d-history.json.
- scripts/clawd3d-start.sh: All-in-one startup script that launches
  Hermes, the adapter, and the Next.js dev server with auto port
  conflict resolution. Alias as `claw3d` for convenience.
- src/features/office/hooks/useCronAgents.ts: Hook that polls the
  gateway for cron-scheduled agents and surfaces them in the 3D office.
- package.json: adds `hermes-adapter` npm script
- .env.example: documents Hermes config vars
- docs/hermes-gateway.md: setup guide and protocol reference

Usage:
  npm run hermes-adapter   # start adapter (connect to http://localhost:8642)
  npm run dev              # start Claw3D, point browser at localhost:3000
  # or: bash scripts/clawd3d-start.sh  (starts everything automatically)

Both OpenClaw and Hermes are supported simultaneously — the gateway URL
in NEXT_PUBLIC_GATEWAY_URL determines which backend Claw3D connects to.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: add read_agent_context tool for cross-agent coordination

Agents can now read each other's conversation history via the
read_agent_context tool, enabling the orchestrator to check what
a sub-agent has done before re-delegating work.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: wire Hermes office UX and role-aware runtime updates

* feature update - demomode & hermes adapter

* fix lint blockers

* lintfix #2

* fix: stabilize retro office camera preset callbacks

* Initial plan

* fix: stabilize retro office overview preset hooks

Agent-Logs-Url: https://github.com/gsknnft/Claw3D/sessions/9cc71555-591e-44cf-aec4-25affbdcb405

Co-authored-by: gsknnft <123185582+gsknnft@users.noreply.github.com>

* feat: add truthful backend selection, Hermes adapter hardening, and demo gateway mode

* fix: address bugbot review and finalize backend selection

* fixed - onboarding and hermes calls

* office systems roadmap

* feat specs in docs

* specs ready

* feat: continue custom runtime seam and gateway alignment

* custom lane wired

* feat: add custom runtime provider path and office runtime alignment

* office_sys prep

* tighten multi-floor runtime spec

* multi-floor v1 implementation

* moved floor nav

* runtime architecture specs

* claw3doctor specs

* feat: add first pass claw3doctor diagnostics

* docs: align roadmap with runtime profiles and office systems priorities

* feat: expand claw3doctor provider diagnostics and json output

* feat: improve claw3doctor formatting and multi-runtime diagnostics

* feat: formalize runtime profile resolution

* feat: expand claw3doctor profile health diagnostics

* feat: polish claw3doctor output and tunnel remediation

* feat: add claw3doctor profile scoping and failure classification

* docs: define claw3doctor v1 boundary and v2 backlog

* test: fix stale claw3doctor branch expectations

* test: fix stale expectations on claw3doctor branch

* fix(claw3doctor): scope provider-specific checks to --profile / --all-profiles flags

PR #101 finding:
- Medium: --profile <adapter> and --all-profiles only scoped the profile health
  probe loop; OpenClaw/Hermes/Demo/Custom check blocks still ran based on the
  selected adapter type in runtimeContext, making CLI output misleading.

Fix: introduce adapterInScope(adapterType, defaultBehavior) helper in main().
  - --profile <adapter>  -> only that adapter's checks run
  - --all-profiles       -> all adapter checks run
  - no flag              -> falls back to existing shouldRun* predicate (unchanged)

Also:
- Export parseDoctorArgs from claw3doctor-core.mjs (removed duplicate in script)
- Add test suites: parseDoctorArgs flag parsing (6 cases) and
  adapterInScope scoping semantics (4 cases) — 10 new tests, all green

* fix(office): persist per-floor selectedAgentId on focusLocalAgent + wire officeFloors runtime state

PR #96 findings:
- Medium #1: focusLocalAgent now writes selectedAgentId back to floorRosterCache
  so handleSelectFloor restores the agent the user last picked on each floor
  rather than snapping back to the hydration-time suggestion.
- Medium #2: Add useEffect that calls settingsCoordinator.schedulePatch with
  officeFloors[activeFloorId] patch on every status/gatewayUrl change, writing
  status, gatewayUrl, lastKnownGoodAt, lastErrorCode, and lastErrorMessage so
  the persisted floor runtime state actually tracks live connection transitions.

* fix unkept changes

* fix audit findings - cross-floor misattribution & officefloors silent drops

* pushed changes

* multi-agentic runtime & chat bubble fix

* partial parity with office-sys-next

* claw3doctor parity

* partial parity with v_lane

* merged feat/office-systems-next -> merge_sys

* parity across PR branches

* rm *.orig postmerge

* full parity across unmerged PRs & main

* fix lukes findings

* fix findings - bigger chatbox

* real local upload path

* fixed file upload, MIME integgration

* minor fix

* fix lukess findings

* deleted *.orig

* three bugs fixed - gatewayclient, coord, claw3doctor

* address findings

* fix lukes findings

* fix findings #2

* fix: ignore temporary skill-agent names during identity recovery

* fix: preserve stable identity names during temp-name recovery

* fix(gateway): correct disconnect race and token-blanking on adapter switch

- disconnect() now checks actual connection status rather than selectedAdapterType,
  which may already reflect the target adapter when the effect fires. Prevents stale
  WebSocket clients from persisting after switching to local/claw3d/custom backends.
- setSelectedAdapterType() falls back to loadedGatewaySettings.current.profiles token
  when the in-memory adapterProfiles entry has an empty token (sanitized API form).
  Prevents saved tokens from being cleared when switching between backends.

Closes Luke findings: High (stale gateway on floor switch), Medium (token blanking).

Authored-By: GSKNNFT

* feat(gateway): loopback bypass, control-ui remap, operator.read scope, 75ms connect

Cherry-picked clean additions from pr/gsknnft-2 (fix/reduce-gateway-connect-delay):

- proxy-url.ts: resolveStudioProxyGatewayUrl() now accepts optional upstreamGatewayUrl;
  loopback hosts (localhost/127.0.0.1/::1) bypass the Studio proxy and connect directly
- gateway-proxy.js: remap unauthenticated openclaw-control-ui connections to webchat-ui
  client ID so OpenClaw doesn't reject them as unknown clients
- GatewayBrowserClient.ts + nodeGatewayClient.ts: add operator.read scope to both
  browser and Node gateway clients for expanded access control
- GatewayBrowserClient.ts: reduce socket open→connect delay from 750ms to 75ms

GatewayClient.ts rewrites from that PR were intentionally excluded — they would
regress our disconnect-race fix, token-blanking fix, broken-regex fix, local/claw3d
adapter support, adapterProfiles type export, and private envelope path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(floor-nav): show only available floors per active adapter; block hang on unconfigured runtime

- floors.ts: add paperclip to FloorProvider; add listAvailableFloorsForAdapter() —
  lobby always visible, runtime floors only shown when their provider matches the
  active adapter, so demo-only users only see Lobby
- OfficeFloorNav: accept activeAdapterType prop, filter floor list via
  listAvailableFloorsForAdapter(); fall back displayActiveFloorId to lobby if current
  floor is no longer in the available set
- OfficeScreen: pass selectedAdapterType to OfficeFloorNav; add guard in
  handleSelectFloor — bail back to lobby immediately when a runtime floor has no
  gateway URL configured, preventing the connect-hang limbo state

Authored-By: GSKNNFT

* hardening: drop unsafe-eval in production CSP; add TRUSTED_PROXY IP resolution

next.config.ts:
- unsafe-eval removed from production script-src (Next.js dev/HMR needs it, but
  production build does not; React and Three.js make no use of eval)
- connect-src intentionally kept broad with note: gateway URLs are user-configured
  at runtime, cannot be enumerated at build time

server/access-gate.js:
- Add resolveClientIp() helper: when TRUSTED_PROXY=1 env var is set, prefer the
  first value of X-Forwarded-For for rate-limiter keying (correct behavior behind
  nginx/Caddy/Vercel edge). Without the flag, remoteAddress is used (safe default
  for direct exposure — prevents X-Forwarded-For spoofing by untrusted clients).

Authored-By: GSKNNFT

* fix(security): remove upstream tokens from browser API; propagate abort to custom runtime

HIGH — /api/studio: strip gatewayPrivate and localGatewayDefaultsPrivate from GET and
PUT responses. Upstream tokens must not cross the browser API boundary. The Studio
proxy (server/gateway-proxy.js) already injects the server-side token into connect
frames when the browser sends an empty token, so the browser never needed raw tokens.
GatewayClient.ts and OfficeScreen.tsx updated to work from sanitized public settings only.

MEDIUM — /api/runtime/custom route: pass request.signal to the upstream fetch() call.
Client abort (e.g. hitting Stop) now cancels the upstream runtime request instead of
leaving it running after the browser fetch resolves.

Authored By: GSKNNFT

* fix(security): preserve stored token through empty-token UI state; handle non-JSON health responses

GatewayClient.ts — autosave effects no longer overwrite persisted gateway tokens with
empty strings. When the in-memory token is empty (proxy handles auth server-side),
the patch omits the token field (undefined) so mergeGatewaySettings/mergeGatewayProfiles
treats it as "leave unchanged". adapterProfiles updater also preserves the existing
stored token when the new token is empty, preventing floor-switch from erasing tokens.

runtime/custom/http.ts — requestCustomRuntime() checks the response Content-Type before
calling response.json(). Non-JSON responses (e.g. plain-text /health "OK") are returned
as-is instead of throwing a JSON parse error, making the custom/local/claw3d health
probe path reliable for runtimes that return plain text.

Authored By: GSKNNFT

* fix(bug): avoid overwriting stored tokens with an empty UI value

GatewayClient.ts:944 → token: "" || undefined = undefined → omitted from patch
mergeGatewayConnectionState: patch.token === undefined → patchedToken = undefined → nextToken = undefined || current?.token ?? "" = "abc123" ✓

scenarionn- user explicitly clears token (empty string patch):

mergeGatewayConnectionState: patchedToken = "" → nextToken = "" || current?.token ?? "" = falls back to existing stored token

Authored By: GSKNNFT

* fix ongoing findings issue

* test: update gateway connection persistence expectations

Co-authored-by: Luke The Dev <iamlukethedev@users.noreply.github.com>

* fix: tighten ts.net hostname matching in doctor

Co-authored-by: Luke The Dev <iamlukethedev@users.noreply.github.com>

* chore(release): prepare v0.1.4

Pin in-repo app version to 0.1.4 to match the planned GitHub release
tag, and document the convergence release in CHANGELOG.md with verified
0.1.3 and 0.1.4 entries covering runtime profiles, multi-floor offices,
remote messaging/handoffs, file uploads, security hardening, and the
claw3doctor diagnostics CLI.

Made-with: Cursor

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Luke The Dev <iamlukethedev@users.noreply.github.com>
Co-authored-by: Elias Pfeffer <eliaspfeffer@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Greg Clark <greg.clark@gmail.com>
Co-authored-by: iamlukethedev <lucas.guilherme@smartwayslfl.com>
2026-04-23 18:29:20 -05:00

713 lines
21 KiB
TypeScript

// Adapted from `openclaw/openclaw` `ui/src/ui/gateway.ts`.
// Source license: MIT. Last verified against OpenClaw 2026.2.12
// (`f9e444dd56ccfc2271e8ae1729b7a14a55e1c11e`).
// Update this file via `npm run sync:gateway-client -- /path/to/gateway.ts` and record
// provenance changes in `THIRD_PARTY_CODE.md` whenever the upstream source changes.
import { getPublicKeyAsync, signAsync, utils } from "@noble/ed25519";
import { GatewayResponseError } from "@/lib/gateway/errors";
const gatewayBrowserDebugEnabled =
process.env.NODE_ENV !== "production";
const gatewayBrowserDebugLog = (
message: string,
details?: Record<string, unknown>
) => {
if (!gatewayBrowserDebugEnabled) return;
if (details) {
console.info("[gateway-browser]", message, details);
return;
}
console.info("[gateway-browser]", message);
};
const GATEWAY_CLIENT_NAMES = {
CONTROL_UI: "openclaw-control-ui",
} as const;
const GATEWAY_CLIENT_MODES = {
WEBCHAT: "webchat",
} as const;
type CryptoLike = {
randomUUID?: (() => string) | undefined;
getRandomValues?: ((array: Uint8Array) => Uint8Array) | undefined;
};
let warnedWeakCrypto = false;
function uuidFromBytes(bytes: Uint8Array): string {
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += bytes[i]!.toString(16).padStart(2, "0");
}
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(
16,
20
)}-${hex.slice(20)}`;
}
function weakRandomBytes(): Uint8Array {
const bytes = new Uint8Array(16);
const now = Date.now();
for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
bytes[0] ^= now & 0xff;
bytes[1] ^= (now >>> 8) & 0xff;
bytes[2] ^= (now >>> 16) & 0xff;
bytes[3] ^= (now >>> 24) & 0xff;
return bytes;
}
function warnWeakCryptoOnce() {
if (warnedWeakCrypto) return;
warnedWeakCrypto = true;
console.warn("[uuid] crypto API missing; falling back to weak randomness");
}
function generateUUID(cryptoLike: CryptoLike | null = globalThis.crypto): string {
if (cryptoLike && typeof cryptoLike.randomUUID === "function") return cryptoLike.randomUUID();
if (cryptoLike && typeof cryptoLike.getRandomValues === "function") {
const bytes = new Uint8Array(16);
cryptoLike.getRandomValues(bytes);
return uuidFromBytes(bytes);
}
warnWeakCryptoOnce();
return uuidFromBytes(weakRandomBytes());
}
type DeviceAuthPayloadParams = {
deviceId: string;
clientId: string;
clientMode: string;
role: string;
scopes: string[];
signedAtMs: number;
token?: string | null;
nonce?: string | null;
version?: "v1" | "v2";
};
function buildDeviceAuthPayload(params: DeviceAuthPayloadParams): string {
const version = params.version ?? (params.nonce ? "v2" : "v1");
const scopes = params.scopes.join(",");
const token = params.token ?? "";
const base = [
version,
params.deviceId,
params.clientId,
params.clientMode,
params.role,
scopes,
String(params.signedAtMs),
token,
];
if (version === "v2") {
base.push(params.nonce ?? "");
}
return base.join("|");
}
type DeviceAuthEntry = {
token: string;
role: string;
scopes: string[];
updatedAtMs: number;
};
type DeviceAuthStore = {
version: 1;
deviceId: string;
tokens: Record<string, DeviceAuthEntry>;
};
const DEVICE_AUTH_STORAGE_KEY = "openclaw.device.auth.v1";
function normalizeAuthScope(scope: string | undefined): string {
const trimmed = scope?.trim();
if (!trimmed) return "default";
return trimmed.toLowerCase();
}
function buildScopedTokenKey(scope: string, role: string): string {
return `${scope}::${role}`;
}
function normalizeRole(role: string): string {
return role.trim();
}
function normalizeScopes(scopes: string[] | undefined): string[] {
if (!Array.isArray(scopes)) return [];
const out = new Set<string>();
for (const scope of scopes) {
const trimmed = scope.trim();
if (trimmed) out.add(trimmed);
}
return [...out].sort();
}
function readDeviceAuthStore(): DeviceAuthStore | null {
try {
const raw = window.localStorage.getItem(DEVICE_AUTH_STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as DeviceAuthStore;
if (!parsed || parsed.version !== 1) return null;
if (!parsed.deviceId || typeof parsed.deviceId !== "string") return null;
if (!parsed.tokens || typeof parsed.tokens !== "object") return null;
return parsed;
} catch {
return null;
}
}
function writeDeviceAuthStore(store: DeviceAuthStore) {
try {
window.localStorage.setItem(DEVICE_AUTH_STORAGE_KEY, JSON.stringify(store));
} catch {
// best-effort
}
}
function loadDeviceAuthToken(params: { deviceId: string; role: string; scope: string }): DeviceAuthEntry | null {
const store = readDeviceAuthStore();
if (!store || store.deviceId !== params.deviceId) return null;
const role = normalizeRole(params.role);
const scope = normalizeAuthScope(params.scope);
const key = buildScopedTokenKey(scope, role);
const entry = store.tokens[key];
if (!entry || typeof entry.token !== "string") return null;
return entry;
}
function storeDeviceAuthToken(params: {
deviceId: string;
role: string;
scope: string;
token: string;
scopes?: string[];
}): DeviceAuthEntry {
const role = normalizeRole(params.role);
const scope = normalizeAuthScope(params.scope);
const key = buildScopedTokenKey(scope, role);
const next: DeviceAuthStore = {
version: 1,
deviceId: params.deviceId,
tokens: {},
};
const existing = readDeviceAuthStore();
if (existing && existing.deviceId === params.deviceId) {
next.tokens = { ...existing.tokens };
}
const entry: DeviceAuthEntry = {
token: params.token,
role,
scopes: normalizeScopes(params.scopes),
updatedAtMs: Date.now(),
};
next.tokens[key] = entry;
writeDeviceAuthStore(next);
return entry;
}
function clearDeviceAuthToken(params: { deviceId: string; role: string; scope: string }) {
const store = readDeviceAuthStore();
if (!store || store.deviceId !== params.deviceId) return;
const role = normalizeRole(params.role);
const scope = normalizeAuthScope(params.scope);
const key = buildScopedTokenKey(scope, role);
const hasScoped = Boolean(store.tokens[key]);
const hasLegacy = Boolean(store.tokens[role]);
if (!hasScoped && !hasLegacy) return;
const next = { ...store, tokens: { ...store.tokens } };
delete next.tokens[key];
delete next.tokens[role];
writeDeviceAuthStore(next);
}
type StoredIdentity = {
version: 1;
deviceId: string;
publicKey: string;
privateKey: string;
createdAtMs: number;
};
type DeviceIdentity = {
deviceId: string;
publicKey: string;
privateKey: string;
};
const DEVICE_IDENTITY_STORAGE_KEY = "openclaw-device-identity-v1";
export function clearGatewayBrowserSessionStorage() {
try {
localStorage.removeItem(DEVICE_AUTH_STORAGE_KEY);
localStorage.removeItem(DEVICE_IDENTITY_STORAGE_KEY);
} catch {
// best-effort
}
}
function base64UrlEncode(bytes: Uint8Array): string {
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/g, "");
}
function base64UrlDecode(input: string): Uint8Array {
const normalized = input.replaceAll("-", "+").replaceAll("_", "/");
const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
const binary = atob(padded);
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
return out;
}
function bytesToHex(bytes: Uint8Array): string {
return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
async function fingerprintPublicKey(publicKey: Uint8Array): Promise<string> {
const hash = await crypto.subtle.digest("SHA-256", new Uint8Array(publicKey));
return bytesToHex(new Uint8Array(hash));
}
async function generateIdentity(): Promise<DeviceIdentity> {
const privateKey = utils.randomSecretKey();
const publicKey = await getPublicKeyAsync(privateKey);
const deviceId = await fingerprintPublicKey(publicKey);
return {
deviceId,
publicKey: base64UrlEncode(publicKey),
privateKey: base64UrlEncode(privateKey),
};
}
async function loadOrCreateDeviceIdentity(): Promise<DeviceIdentity> {
try {
const raw = localStorage.getItem(DEVICE_IDENTITY_STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw) as StoredIdentity;
if (
parsed?.version === 1 &&
typeof parsed.deviceId === "string" &&
typeof parsed.publicKey === "string" &&
typeof parsed.privateKey === "string"
) {
const derivedId = await fingerprintPublicKey(base64UrlDecode(parsed.publicKey));
if (derivedId !== parsed.deviceId) {
const updated: StoredIdentity = {
...parsed,
deviceId: derivedId,
};
localStorage.setItem(DEVICE_IDENTITY_STORAGE_KEY, JSON.stringify(updated));
return {
deviceId: derivedId,
publicKey: parsed.publicKey,
privateKey: parsed.privateKey,
};
}
return {
deviceId: parsed.deviceId,
publicKey: parsed.publicKey,
privateKey: parsed.privateKey,
};
}
}
} catch {
// fall through to regenerate
}
const identity = await generateIdentity();
const stored: StoredIdentity = {
version: 1,
deviceId: identity.deviceId,
publicKey: identity.publicKey,
privateKey: identity.privateKey,
createdAtMs: Date.now(),
};
localStorage.setItem(DEVICE_IDENTITY_STORAGE_KEY, JSON.stringify(stored));
return identity;
}
async function signDevicePayload(privateKeyBase64Url: string, payload: string) {
const key = base64UrlDecode(privateKeyBase64Url);
const data = new TextEncoder().encode(payload);
const sig = await signAsync(data, key);
return base64UrlEncode(sig);
}
export type GatewayEventFrame = {
type: "event";
event: string;
payload?: unknown;
seq?: number;
stateVersion?: { presence: number; health: number };
};
export type GatewayResponseFrame = {
type: "res";
id: string;
ok: boolean;
payload?: unknown;
error?: { code: string; message: string; details?: unknown };
};
export type GatewayHelloOk = {
type: "hello-ok";
protocol: number;
adapterType?: "openclaw" | "hermes" | "demo" | "custom";
features?: { methods?: string[]; events?: string[] };
snapshot?: unknown;
auth?: {
deviceToken?: string;
role?: string;
scopes?: string[];
issuedAtMs?: number;
};
policy?: { tickIntervalMs?: number };
};
type Pending = {
resolve: (value: unknown) => void;
reject: (err: unknown) => void;
};
export type GatewayBrowserClientOptions = {
url: string;
token?: string;
password?: string;
authScopeKey?: string;
disableDeviceAuth?: boolean;
clientName?: string;
clientVersion?: string;
platform?: string;
mode?: string;
instanceId?: string;
onHello?: (hello: GatewayHelloOk) => void;
onEvent?: (evt: GatewayEventFrame) => void;
onClose?: (info: { code: number; reason: string }) => void;
onGap?: (info: { expected: number; received: number }) => void;
};
const CONNECT_FAILED_CLOSE_CODE = 4008;
const WS_CLOSE_REASON_MAX_BYTES = 123;
function truncateWsCloseReason(reason: string, maxBytes = WS_CLOSE_REASON_MAX_BYTES): string {
const trimmed = reason.trim();
if (!trimmed) return "connect failed";
const encoder = new TextEncoder();
if (encoder.encode(trimmed).byteLength <= maxBytes) return trimmed;
let out = "";
for (const char of trimmed) {
const next = out + char;
if (encoder.encode(next).byteLength > maxBytes) break;
out = next;
}
return out.trimEnd() || "connect failed";
}
export class GatewayBrowserClient {
private ws: WebSocket | null = null;
private pending = new Map<string, Pending>();
private closed = false;
private lastSeq: number | null = null;
private connectNonce: string | null = null;
private connectSent = false;
private connectTimer: number | null = null;
private backoffMs = 800;
constructor(private opts: GatewayBrowserClientOptions) {}
start() {
this.closed = false;
gatewayBrowserDebugLog("start", {
url: this.opts.url,
authScopeKey: this.opts.authScopeKey ?? null,
disableDeviceAuth: Boolean(this.opts.disableDeviceAuth),
clientName: this.opts.clientName ?? null,
mode: this.opts.mode ?? null,
});
this.connect();
}
stop() {
this.closed = true;
gatewayBrowserDebugLog("stop");
this.ws?.close();
this.ws = null;
this.flushPending(new Error("gateway client stopped"));
}
get connected() {
return this.ws?.readyState === WebSocket.OPEN;
}
private connect() {
if (this.closed) return;
gatewayBrowserDebugLog("connect:open-socket", { url: this.opts.url });
this.ws = new WebSocket(this.opts.url);
this.ws.onopen = () => {
gatewayBrowserDebugLog("socket:open");
this.queueConnect();
};
this.ws.onmessage = (ev) => this.handleMessage(String(ev.data ?? ""));
this.ws.onclose = (ev) => {
const reason = String(ev.reason ?? "");
gatewayBrowserDebugLog("socket:close", { code: ev.code, reason });
this.ws = null;
this.flushPending(new Error(`gateway closed (${ev.code}): ${reason}`));
this.opts.onClose?.({ code: ev.code, reason });
this.scheduleReconnect();
};
this.ws.onerror = () => {
gatewayBrowserDebugLog("socket:error");
};
}
private scheduleReconnect() {
if (this.closed) return;
const delay = this.backoffMs;
this.backoffMs = Math.min(this.backoffMs * 1.7, 15_000);
gatewayBrowserDebugLog("schedule-reconnect", { delay });
window.setTimeout(() => this.connect(), delay);
}
private flushPending(err: Error) {
for (const [, p] of this.pending) p.reject(err);
this.pending.clear();
}
private async sendConnect() {
if (this.connectSent) return;
this.connectSent = true;
if (this.connectTimer !== null) {
window.clearTimeout(this.connectTimer);
this.connectTimer = null;
}
const isSecureContext =
!this.opts.disableDeviceAuth && typeof crypto !== "undefined" && !!crypto.subtle;
gatewayBrowserDebugLog("send-connect", {
url: this.opts.url,
disableDeviceAuth: Boolean(this.opts.disableDeviceAuth),
hasNonce: Boolean(this.connectNonce),
isSecureContext,
});
const scopes = ["operator.read", "operator.admin", "operator.approvals", "operator.pairing"];
const role = "operator";
const authScopeKey = normalizeAuthScope(this.opts.authScopeKey ?? this.opts.url);
let deviceIdentity: Awaited<ReturnType<typeof loadOrCreateDeviceIdentity>> | null = null;
let canFallbackToShared = false;
let authToken = this.opts.token;
if (isSecureContext) {
deviceIdentity = await loadOrCreateDeviceIdentity();
const storedToken = loadDeviceAuthToken({
deviceId: deviceIdentity.deviceId,
role,
scope: authScopeKey,
})?.token;
authToken = storedToken ?? this.opts.token;
canFallbackToShared = Boolean(storedToken && this.opts.token);
}
const auth =
authToken || this.opts.password
? {
token: authToken,
password: this.opts.password,
}
: undefined;
let device:
| {
id: string;
publicKey: string;
signature: string;
signedAt: number;
nonce: string | undefined;
}
| undefined;
if (isSecureContext && deviceIdentity) {
const signedAtMs = Date.now();
const nonce = this.connectNonce ?? undefined;
const payload = buildDeviceAuthPayload({
deviceId: deviceIdentity.deviceId,
clientId: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.CONTROL_UI,
clientMode: this.opts.mode ?? GATEWAY_CLIENT_MODES.WEBCHAT,
role,
scopes,
signedAtMs,
token: authToken ?? null,
nonce,
});
const signature = await signDevicePayload(deviceIdentity.privateKey, payload);
device = {
id: deviceIdentity.deviceId,
publicKey: deviceIdentity.publicKey,
signature,
signedAt: signedAtMs,
nonce,
};
}
const params = {
minProtocol: 3,
maxProtocol: 3,
client: {
id: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.CONTROL_UI,
version: this.opts.clientVersion ?? "dev",
platform: this.opts.platform ?? navigator.platform ?? "web",
mode: this.opts.mode ?? GATEWAY_CLIENT_MODES.WEBCHAT,
instanceId: this.opts.instanceId,
},
role,
scopes,
device,
caps: [],
auth,
userAgent: navigator.userAgent,
locale: navigator.language,
};
gatewayBrowserDebugLog("connect-params", {
clientId: params.client.id,
clientMode: params.client.mode,
disableDeviceAuth: this.opts.disableDeviceAuth,
isSecureContext,
hasToken: Boolean(authToken),
hasDeviceIdentity: Boolean(deviceIdentity),
});
void this.request<GatewayHelloOk>("connect", params)
.then((hello) => {
gatewayBrowserDebugLog("hello-ok", {
protocol: hello?.protocol ?? null,
hasAuthToken: Boolean(hello?.auth?.deviceToken),
});
if (hello?.auth?.deviceToken && deviceIdentity) {
storeDeviceAuthToken({
deviceId: deviceIdentity.deviceId,
role: hello.auth.role ?? role,
scope: authScopeKey,
token: hello.auth.deviceToken,
scopes: hello.auth.scopes ?? [],
});
}
this.backoffMs = 800;
this.opts.onHello?.(hello);
})
.catch((err) => {
gatewayBrowserDebugLog("connect-failed", {
message: err instanceof Error ? err.message : String(err),
});
if (canFallbackToShared && deviceIdentity) {
clearDeviceAuthToken({ deviceId: deviceIdentity.deviceId, role, scope: authScopeKey });
}
const rawReason =
err instanceof GatewayResponseError
? `connect failed: ${err.code} ${err.message}`
: "connect failed";
const reason = truncateWsCloseReason(rawReason);
if (reason !== rawReason) {
console.warn("[gateway] connect close reason truncated to 123 UTF-8 bytes");
}
this.ws?.close(CONNECT_FAILED_CLOSE_CODE, reason);
});
}
private handleMessage(raw: string) {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return;
}
const frame = parsed as { type?: unknown };
if (frame.type === "event") {
const evt = parsed as GatewayEventFrame;
if (evt.event === "connect.challenge") {
gatewayBrowserDebugLog("connect-challenge");
const payload = evt.payload as { nonce?: unknown } | undefined;
const nonce = payload && typeof payload.nonce === "string" ? payload.nonce : null;
if (nonce) {
this.connectNonce = nonce;
void this.sendConnect();
}
return;
}
const seq = typeof evt.seq === "number" ? evt.seq : null;
if (seq !== null) {
if (this.lastSeq !== null && seq > this.lastSeq + 1) {
this.opts.onGap?.({ expected: this.lastSeq + 1, received: seq });
}
this.lastSeq = seq;
}
try {
this.opts.onEvent?.(evt);
} catch (err) {
console.error("[gateway] event handler error:", err);
}
return;
}
if (frame.type === "res") {
const res = parsed as GatewayResponseFrame;
const pending = this.pending.get(res.id);
if (!pending) return;
this.pending.delete(res.id);
if (res.ok) pending.resolve(res.payload);
else {
if (res.error && typeof res.error.code === "string") {
pending.reject(
new GatewayResponseError({
code: res.error.code,
message: res.error.message ?? "request failed",
details: res.error.details,
})
);
return;
}
pending.reject(new Error(res.error?.message ?? "request failed"));
}
return;
}
}
request<T = unknown>(method: string, params?: unknown): Promise<T> {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
return Promise.reject(new Error("gateway not connected"));
}
const id = generateUUID();
const frame = { type: "req", id, method, params };
const p = new Promise<T>((resolve, reject) => {
this.pending.set(id, { resolve: (v) => resolve(v as T), reject });
});
this.ws.send(JSON.stringify(frame));
return p;
}
private queueConnect() {
this.connectNonce = null;
this.connectSent = false;
if (this.connectTimer !== null) window.clearTimeout(this.connectTimer);
const SOCKET_OPEN_CONNECT_DELAY_MS = 75;
gatewayBrowserDebugLog("queue-connect", { delayMs: SOCKET_OPEN_CONNECT_DELAY_MS });
this.connectTimer = window.setTimeout(() => {
void this.sendConnect();
}, SOCKET_OPEN_CONNECT_DELAY_MS);
}
}