From 3421049d5cab485aacb0f5dd09e11230425fb1db Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 18 Feb 2026 09:00:49 -0800 Subject: [PATCH] Add remote backend connection support across server and clients - document remote architecture and setup in `REMOTE.md` and link from README - add server host override and WebSocket bearer-token auth support - enable web runtime/env remote WS config and desktop remote mode without local spawn - extend WS tests for bearer authorization path --- .plans/remote-execution.md | 103 +++++++++++++++++++++++++++++++ README.md | 2 + REMOTE.md | 93 ++++++++++++++++++++++++++++ apps/desktop/src/main.ts | 37 +++++++++++ apps/server/src/index.ts | 14 ++++- apps/server/src/wsServer.test.ts | 24 ++++++- apps/server/src/wsServer.ts | 35 ++++++++--- apps/web/src/wsTransport.ts | 59 +++++++++++++++--- apps/web/vite.config.ts | 1 + 9 files changed, 350 insertions(+), 18 deletions(-) create mode 100644 .plans/remote-execution.md create mode 100644 REMOTE.md diff --git a/.plans/remote-execution.md b/.plans/remote-execution.md new file mode 100644 index 0000000000..d56eb11247 --- /dev/null +++ b/.plans/remote-execution.md @@ -0,0 +1,103 @@ +# Plan: Remote Execution for T3 Server + Web/Desktop Frontends + +## Goal +Enable a remote `t3` backend to run on another machine while both frontend clients (browser web app and Electron desktop app) connect to it reliably. + +## Constraints From Current Codebase +- Transport is a single WebSocket RPC channel plus push events. +- Desktop currently assumes local backend process ownership. +- Browser clients cannot set arbitrary WebSocket headers. +- Existing auth support was token-in-query only (`?token=...`). + +## Core Design Choices Explored + +### 1) Network Topology +Option A: SSH tunnel to remote loopback (`ssh -L`) +- Pros: no public WS exposure, strong default security model. +- Cons: requires SSH session lifecycle and tunnel setup per user/session. + +Option B: Direct authenticated WebSocket endpoint (typically behind TLS/reverse proxy) +- Pros: simplest UX for multi-client access, no tunnel required. +- Cons: needs auth hardening and TLS termination in deployment. + +Decision: Support both operationally, but implement direct authenticated WS as the primary PoC path, with SSH as a first-class secure deployment mode. + +### 2) WS Authentication Mechanism +Option A: Query token (`wss://.../?token=...`) +- Pros: works in browser and Electron renderer immediately. +- Cons: token can leak via logs/history if mishandled. + +Option B: `Authorization: Bearer ...` header +- Pros: cleaner for non-browser clients and service integrations. +- Cons: not settable by normal browser WebSocket API. + +Option C: mTLS-only +- Pros: strongest transport auth. +- Cons: high setup complexity for a PoC. + +Decision: Keep query token as browser-compatible baseline, add bearer-header support on server for non-browser clients. + +### 3) Frontend Remote Endpoint Configuration +Option A: Build-time env only (`VITE_WS_URL`) +- Pros: simple in CI/deploy pipelines. +- Cons: rigid for ad-hoc remote switching. + +Option B: Runtime URL params (e.g. `?t3WsUrl=...&t3Token=...`) +- Pros: no rebuild needed; easy operator workflow for PoC. +- Cons: requires token hygiene. + +Option C: In-app settings UI +- Pros: best UX long-term. +- Cons: more product and persistence work. + +Decision: Implement A + B (env + runtime URL params) for web app PoC. + +### 4) Desktop Backend Ownership Model +Option A: Always spawn local backend (current) +- Pros: existing stable behavior. +- Cons: cannot target remote backend. + +Option B: Configurable remote mode (skip local spawn; renderer connects remote WS) +- Pros: minimal invasive change; preserves existing desktop UX shell. +- Cons: some desktop-only assumptions may need future guardrails. + +Decision: Implement B via env (`T3CODE_REMOTE_WS_URL`, optional `T3CODE_REMOTE_WS_TOKEN`). + +### 5) Server Bind Strategy +Option A: hardcoded mode-based bind (current desktop loopback / web default) +- Pros: simple. +- Cons: remote deployment lacks explicit operator control. + +Option B: explicit `T3CODE_HOST` override +- Pros: supports secure loopback-for-SSH and public bind use cases. + +Decision: Implement B. + +## Implemented PoC Changes +- `apps/server/src/index.ts` + - Added `T3CODE_HOST` support for explicit bind control. +- `apps/server/src/wsServer.ts` + - WS auth now accepts bearer token from `Authorization` header in addition to `?token=`. +- `apps/server/src/wsServer.test.ts` + - Added test coverage for bearer auth header path. +- `apps/web/src/wsTransport.ts` + - Added runtime remote config via URL params: `t3WsUrl`, `t3Token`. + - Added protocol normalization (`http(s)` -> `ws(s)`) and token attachment logic. + - Default same-origin fallback now respects page protocol (`wss` on https). +- `apps/web/vite.config.ts` + - Added `VITE_WS_TOKEN` injection for build/dev env usage. +- `apps/desktop/src/main.ts` + - Added remote backend mode (`T3CODE_REMOTE_WS_URL`, `T3CODE_REMOTE_WS_TOKEN`) that skips local backend spawn. + +## Chosen Architecture (for this PoC) +- Remote `t3` server is the single source of truth and execution node. +- Web and desktop renderers are pure clients over authenticated WebSocket. +- Deployment can be: + - SSH tunnel + loopback bind (`T3CODE_HOST=127.0.0.1`), or + - direct authenticated WS endpoint (prefer TLS/reverse proxy). + +## Follow-ups After PoC +- Move token auth from query param to short-lived session token bootstrap for browser UX/security. +- Add explicit origin allowlist + rate limiting for internet-exposed deployments. +- Add in-app connection settings UI for runtime endpoint switching. +- Add reconnect telemetry and health/status endpoint for remote ops. diff --git a/README.md b/README.md index ac73a42708..606901cab2 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JS └─────────────────────────────────┘ ``` +Remote deployment and frontend-to-remote connection details are documented in `REMOTE.md`. + ## Workspace layout - `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start. diff --git a/REMOTE.md b/REMOTE.md new file mode 100644 index 0000000000..78e80726b4 --- /dev/null +++ b/REMOTE.md @@ -0,0 +1,93 @@ +# Remote T3 Architecture (PoC) + +## Summary +This PoC supports running `apps/server` on a remote machine and connecting both frontend clients to it: +- Browser web app (via env or runtime URL params) +- Electron desktop app (remote mode; no local backend spawn) + +## Final Architecture +```mermaid +flowchart LR + subgraph ClientMachine[Client Machine] + Web[Web App\n(React/Vite)] + Desktop[Desktop App\n(Electron Renderer)] + end + + subgraph RemoteMachine[Remote Machine] + Server[T3 Server\n(HTTP + WS RPC)] + Codex[Codex App Server\n(JSON-RPC over stdio)] + end + + Web -- "wss/ws + token auth" --> Server + Desktop -- "wss/ws + token auth" --> Server + Server -- "stdio JSON-RPC" --> Codex +``` + +## Connection Modes + +### 1) SSH Tunnel (recommended for operator security) +Run remote server loopback-only: +```bash +T3CODE_HOST=127.0.0.1 T3CODE_PORT=3773 T3CODE_AUTH_TOKEN= bun run start +``` + +From client machine, forward port: +```bash +ssh -L 3773:127.0.0.1:3773 @ +``` + +Then connect clients to `ws://127.0.0.1:3773` with the same token. + +### 2) Direct Authenticated WS +Run remote server network-bound: +```bash +T3CODE_HOST=0.0.0.0 T3CODE_PORT=3773 T3CODE_AUTH_TOKEN= bun run start +``` + +Use TLS termination/reverse proxy in front for production internet exposure. + +## Client Configuration + +### Web App +Supported config sources: +- Build/dev env: `VITE_WS_URL`, optional `VITE_WS_TOKEN` +- Runtime URL params: `t3WsUrl`, `t3Token` + +Examples: +```text +https://web-host/?t3WsUrl=wss://api.example.com&t3Token=secret +https://api.example.com/?t3Token=secret +``` + +Notes: +- If `t3WsUrl` is `http://` or `https://`, it is normalized to `ws://` or `wss://`. +- If no URL is provided, web falls back to same-origin WS using page protocol. + +### Desktop App +Set remote mode env vars before launch: +- `T3CODE_REMOTE_WS_URL` (required for remote mode) +- `T3CODE_REMOTE_WS_TOKEN` (optional if URL already includes `?token=`) + +Example: +```bash +T3CODE_REMOTE_WS_URL=ws://127.0.0.1:3773 T3CODE_REMOTE_WS_TOKEN=secret bun run start:desktop +``` + +When `T3CODE_REMOTE_WS_URL` is set, desktop skips spawning the local server process. + +## Auth Behavior +Server WS auth now accepts either: +- Query token: `?token=...` (browser-compatible) +- `Authorization: Bearer ` header (non-browser clients) + +## New/Relevant Env Vars +- Server: + - `T3CODE_HOST` + - `T3CODE_PORT` + - `T3CODE_AUTH_TOKEN` +- Web: + - `VITE_WS_URL` + - `VITE_WS_TOKEN` +- Desktop: + - `T3CODE_REMOTE_WS_URL` + - `T3CODE_REMOTE_WS_TOKEN` diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index a1f7a9bf21..f16b9d2b34 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -31,6 +31,34 @@ let restartAttempt = 0; let restartTimer: ReturnType | null = null; let isQuitting = false; +function trimToUndefined(value: string | undefined): string | undefined { + if (!value) return undefined; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +function resolveRemoteWsUrl(rawUrl: string, rawToken: string | undefined): string { + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + throw new Error(`Invalid T3CODE_REMOTE_WS_URL: ${rawUrl}`); + } + + if (parsed.protocol === "http:") parsed.protocol = "ws:"; + if (parsed.protocol === "https:") parsed.protocol = "wss:"; + if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") { + throw new Error(`Invalid T3CODE_REMOTE_WS_URL protocol: ${parsed.protocol}`); + } + + const token = trimToUndefined(rawToken); + if (token && !parsed.searchParams.get("token")) { + parsed.searchParams.set("token", token); + } + + return parsed.toString(); +} + async function reserveLoopbackPort(): Promise { return new Promise((resolve, reject) => { const probe = net.createServer(); @@ -247,6 +275,15 @@ function createWindow(): BrowserWindow { } async function bootstrap(): Promise { + const remoteWsUrl = trimToUndefined(process.env.T3CODE_REMOTE_WS_URL); + if (remoteWsUrl) { + backendWsUrl = resolveRemoteWsUrl(remoteWsUrl, process.env.T3CODE_REMOTE_WS_TOKEN); + process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl; + registerIpcHandlers(); + mainWindow = createWindow(); + return; + } + backendPort = await reserveLoopbackPort(); backendAuthToken = randomBytes(24).toString("hex"); backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`; diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index d340657608..5ef0c2b6a7 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -34,6 +34,15 @@ function parsePort(value: string | undefined): number | undefined { return parsed; } +function parseHost(value: string | undefined): string | undefined { + if (value === undefined) return undefined; + const trimmed = value.trim(); + if (trimmed.length === 0) { + throw new Error("Invalid T3CODE_HOST: cannot be empty"); + } + return trimmed; +} + function expandHomePath(input: string): string { if (input === "~") return os.homedir(); if (input.startsWith("~/")) { @@ -99,8 +108,10 @@ function resolveStaticDir(): string | undefined { async function main() { const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web"; const requestedPort = parsePort(process.env.T3CODE_PORT); + const requestedHost = parseHost(process.env.T3CODE_HOST); const port = requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT)); + const host = requestedHost ?? (mode === "desktop" ? "127.0.0.1" : undefined); const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR); const projectRegistry = new ProjectRegistry(stateDir); const devUrl = process.env.VITE_DEV_SERVER_URL; @@ -116,7 +127,7 @@ async function main() { const server = createServer({ port, - host: mode === "desktop" ? "127.0.0.1" : undefined, + host, cwd, staticDir, devUrl, @@ -128,6 +139,7 @@ async function main() { const url = `http://localhost:${port}`; logger.info("T3 Code running", { url, + host: host ?? "0.0.0.0", cwd, mode, stateDir, diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts index 635bfbb812..8f02c51849 100644 --- a/apps/server/src/wsServer.test.ts +++ b/apps/server/src/wsServer.test.ts @@ -143,10 +143,14 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] } dispose(): void {} } -function connectWs(port: number, token?: string): Promise { +function connectWs( + port: number, + token?: string, + headers?: Record, +): Promise { return new Promise((resolve, reject) => { const query = token ? `?token=${encodeURIComponent(token)}` : ""; - const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`); + const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`, { headers }); const pending: PendingMessages = { queue: [], waiters: [] }; pendingBySocket.set(ws, pending); @@ -1057,4 +1061,20 @@ describe("WebSocket Server", () => { const welcome = (await waitForMessage(authorizedWs)) as WsPush; expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome); }); + + it("accepts bearer auth header for websocket authentication", async () => { + server = createTestServer({ cwd: "/test", authToken: "secret-token" }); + await server.start(); + const addr = server.httpServer.address(); + const port = typeof addr === "object" && addr !== null ? addr.port : 0; + + await expect( + connectWs(port, undefined, { Authorization: "Bearer wrong-token" }), + ).rejects.toThrow("WebSocket connection failed"); + + const ws = await connectWs(port, undefined, { Authorization: "Bearer secret-token" }); + connections.push(ws); + const welcome = (await waitForMessage(ws)) as WsPush; + expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome); + }); }); diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index ce9878cd46..84eb4bcc5e 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -198,6 +198,28 @@ export function createServer(options: ServerOptions) { // WebSocket server — upgrades from the HTTP server const wss = new WebSocketServer({ noServer: true }); + function parseBearerToken(authorizationHeader: string | string[] | undefined): string | null { + const raw = Array.isArray(authorizationHeader) + ? authorizationHeader[0] + : authorizationHeader; + if (!raw) return null; + const match = raw.match(/^Bearer\s+(.+)$/i); + const token = match?.[1]?.trim(); + return token && token.length > 0 ? token : null; + } + + function parseTokenFromQuery(requestUrl: string | undefined): string | null { + const url = new URL(requestUrl ?? "/", `http://localhost:${port}`); + const queryToken = url.searchParams.get("token"); + return queryToken && queryToken.length > 0 ? queryToken : null; + } + + function parseUpgradeToken(request: http.IncomingMessage): string | null { + const bearerToken = parseBearerToken(request.headers.authorization); + if (bearerToken) return bearerToken; + return parseTokenFromQuery(request.url); + } + function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void { socket.write( `HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` + @@ -212,19 +234,16 @@ export function createServer(options: ServerOptions) { httpServer.on("upgrade", (request, socket, head) => { if (authToken) { - let providedToken: string | null = null; try { - const url = new URL(request.url ?? "/", `http://localhost:${port}`); - providedToken = url.searchParams.get("token"); + const providedToken = parseUpgradeToken(request); + if (providedToken !== authToken) { + rejectUpgrade(socket, 401, "Unauthorized WebSocket connection"); + return; + } } catch { rejectUpgrade(socket, 400, "Invalid WebSocket URL"); return; } - - if (providedToken !== authToken) { - rejectUpgrade(socket, 401, "Unauthorized WebSocket connection"); - return; - } } wss.handleUpgrade(request, socket, head, (ws) => { diff --git a/apps/web/src/wsTransport.ts b/apps/web/src/wsTransport.ts index 20a40f8f05..cd0d1cf474 100644 --- a/apps/web/src/wsTransport.ts +++ b/apps/web/src/wsTransport.ts @@ -10,6 +10,49 @@ interface PendingRequest { const REQUEST_TIMEOUT_MS = 60_000; const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000]; +const RUNTIME_WS_URL_PARAM = "t3WsUrl"; +const RUNTIME_WS_TOKEN_PARAM = "t3Token"; + +function trimToUndefined(value: string | null | undefined): string | undefined { + if (!value) return undefined; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +function readRuntimeParam(name: string): string | undefined { + const fromSearch = trimToUndefined(new URLSearchParams(window.location.search).get(name)); + if (fromSearch) return fromSearch; + + const hash = window.location.hash.startsWith("#") + ? window.location.hash.slice(1) + : window.location.hash; + return trimToUndefined(new URLSearchParams(hash).get(name)); +} + +function normalizeWsUrl(raw: string): string { + try { + const parsed = new URL(raw, window.location.href); + if (parsed.protocol === "http:") parsed.protocol = "ws:"; + if (parsed.protocol === "https:") parsed.protocol = "wss:"; + return parsed.toString(); + } catch { + return raw; + } +} + +function withAuthToken(url: string, token: string | undefined): string { + if (!token) return url; + try { + const parsed = new URL(url, window.location.href); + if (!parsed.searchParams.get("token")) { + parsed.searchParams.set("token", token); + } + return parsed.toString(); + } catch { + const glue = url.includes("?") ? "&" : "?"; + return `${url}${glue}token=${encodeURIComponent(token)}`; + } +} export class WsTransport { private ws: WebSocket | null = null; @@ -23,16 +66,18 @@ export class WsTransport { constructor(url?: string) { const bridgeUrl = window.desktopBridge?.getWsUrl(); + const runtimeWsUrl = readRuntimeParam(RUNTIME_WS_URL_PARAM); + const runtimeWsToken = readRuntimeParam(RUNTIME_WS_TOKEN_PARAM); // In dev mode, VITE_WS_URL points to the server's WebSocket endpoint. // In production, the page is served by the WS server on the same host:port. const envUrl = import.meta.env.VITE_WS_URL as string | undefined; - this.url = - url ?? - (bridgeUrl && bridgeUrl.length > 0 - ? bridgeUrl - : envUrl && envUrl.length > 0 - ? envUrl - : `ws://${window.location.hostname}:${window.location.port}`); + const envToken = trimToUndefined(import.meta.env.VITE_WS_TOKEN as string | undefined); + const defaultProtocol = window.location.protocol === "https:" ? "wss" : "ws"; + const defaultUrl = `${defaultProtocol}://${window.location.host}`; + const selectedUrl = trimToUndefined( + url ?? bridgeUrl ?? runtimeWsUrl ?? trimToUndefined(envUrl) ?? defaultUrl, + ); + this.url = withAuthToken(normalizeWsUrl(selectedUrl ?? defaultUrl), runtimeWsToken ?? envToken); this.connect(); } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 5c548b5067..30ea7c22e9 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -16,6 +16,7 @@ export default defineConfig({ define: { // In dev mode, tell the web app where the WebSocket server lives "import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""), + "import.meta.env.VITE_WS_TOKEN": JSON.stringify(process.env.VITE_WS_TOKEN ?? ""), }, experimental: { enableNativePlugin: true,