diff --git a/README.md b/README.md index da3efb04eb..1f53425c83 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ Optional environment variables: ## Runtime boundary model - `t3` starts a localhost-only WebSocket server. +- Launch URLs include an ephemeral WebSocket token so only the opened browser session can attach. - Browser renderer talks through a typed `NativeApi` adapter over that WebSocket. - Runtime validates request payloads with shared Zod contracts. - Codex execution sandbox policy (`read-only`, `workspace-write`, `danger-full-access`) is still selected per session startup options. diff --git a/apps/t3/scripts/smoke-test.mjs b/apps/t3/scripts/smoke-test.mjs index e995211e22..2efcdc3682 100644 --- a/apps/t3/scripts/smoke-test.mjs +++ b/apps/t3/scripts/smoke-test.mjs @@ -2,7 +2,6 @@ import { spawn } from "node:child_process"; import fs from "node:fs"; import { createServer } from "node:net"; import path from "node:path"; -import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; function getFreePort() { @@ -33,6 +32,26 @@ function waitForProcessExit(processRef) { }); } +function waitForStartupUrl(readOutput, timeoutMs = 20_000) { + return new Promise((resolve, reject) => { + const startedAt = Date.now(); + const timer = setInterval(() => { + const output = readOutput(); + const match = output.match(/CodeThing is running at (http:\/\/[^\s]+)/); + if (match?.[1]) { + clearInterval(timer); + resolve(match[1]); + return; + } + + if (Date.now() - startedAt >= timeoutMs) { + clearInterval(timer); + reject(new Error("Smoke test failed: did not observe startup URL in CLI output.")); + } + }, 100); + }); +} + async function main() { const [backendPort, webPort] = await Promise.all([getFreePort(), getFreePort()]); const scriptDir = path.dirname(fileURLToPath(import.meta.url)); @@ -68,14 +87,20 @@ async function main() { }); try { - await delay(2_000); + const appUrl = await waitForStartupUrl(() => output); + const parsedAppUrl = new URL(appUrl); - const page = await fetch(`http://127.0.0.1:${webPort}`); + const page = await fetch(parsedAppUrl); if (page.status !== 200) { throw new Error(`Smoke test failed: expected web status 200, received ${page.status}.`); } - const ws = new WebSocket(`ws://127.0.0.1:${backendPort}`); + const wsUrl = parsedAppUrl.searchParams.get("ws"); + if (!wsUrl) { + throw new Error("Smoke test failed: launch URL did not include ws runtime parameter."); + } + + const ws = new WebSocket(wsUrl); await new Promise((resolve, reject) => { const timer = setTimeout( () => reject(new Error("Smoke test failed: websocket did not respond in time.")), diff --git a/apps/t3/src/cli.ts b/apps/t3/src/cli.ts index 49465f89a7..ad7e718ef3 100644 --- a/apps/t3/src/cli.ts +++ b/apps/t3/src/cli.ts @@ -1,5 +1,6 @@ #!/usr/bin/env node import { spawn, spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; import fs from "node:fs"; import { createServer } from "node:http"; import path from "node:path"; @@ -256,9 +257,11 @@ export function readCliVersion( } async function runCli(options: CliOptions): Promise { + const authToken = randomUUID(); const runtimeServer = await startRuntimeApiServer({ port: options.backendPort, launchCwd: options.launchCwd, + authToken, }); const __dirname = path.dirname(fileURLToPath(import.meta.url)); diff --git a/apps/t3/src/runtimeApiServer.test.ts b/apps/t3/src/runtimeApiServer.test.ts index 34a22b7b06..20a16d45c6 100644 --- a/apps/t3/src/runtimeApiServer.test.ts +++ b/apps/t3/src/runtimeApiServer.test.ts @@ -160,6 +160,31 @@ describe("runtimeApiServer", () => { secondClient.socket.close(); }); + it("requires auth token when runtime is configured with one", async () => { + const server = await startRuntimeApiServer({ + port: 0, + launchCwd: process.cwd(), + authToken: "secret-token", + }); + servers.push(server); + + const authorizedUrl = new URL(server.wsUrl); + const unauthorizedUrl = `${authorizedUrl.origin}${authorizedUrl.pathname}`; + const unauthorizedClient = new WebSocket(unauthorizedUrl); + const unauthorizedClose = await withTimeout( + new Promise<{ code: number }>((resolve, reject) => { + unauthorizedClient.once("close", (code) => resolve({ code })); + unauthorizedClient.once("error", (error) => reject(error)); + }), + ); + expect(unauthorizedClose.code).toBe(4001); + + const authorizedClient = await connectClient(server.wsUrl); + const hello = await authorizedClient.nextMessage(); + expect(hello.type).toBe("hello"); + authorizedClient.socket.close(); + }); + it("returns a bootstrap payload even when codex cannot initialize", async () => { const originalPath = process.env.PATH; process.env.PATH = ""; diff --git a/apps/t3/src/runtimeApiServer.ts b/apps/t3/src/runtimeApiServer.ts index f3bfb28b7c..779bd444aa 100644 --- a/apps/t3/src/runtimeApiServer.ts +++ b/apps/t3/src/runtimeApiServer.ts @@ -75,6 +75,7 @@ interface RuntimeApiServerOptions { port: number; launchCwd: string; bootstrapSessionTimeoutMs?: number; + authToken?: string; } interface RuntimeApiServer { @@ -257,6 +258,7 @@ export async function startRuntimeApiServer( options: RuntimeApiServerOptions, ): Promise { const launchCwd = path.resolve(options.launchCwd); + const authToken = options.authToken; const bootstrapSessionTimeoutMs = options.bootstrapSessionTimeoutMs ?? BOOTSTRAP_SESSION_TIMEOUT_MS; const providerManager = new ProviderManager(); @@ -385,6 +387,23 @@ export async function startRuntimeApiServer( port: options.port, }); + const isAuthorizedConnection = (requestUrl: string | undefined) => { + if (!authToken) { + return true; + } + + if (!requestUrl) { + return false; + } + + try { + const request = new URL(requestUrl, "ws://127.0.0.1"); + return request.searchParams.get("token") === authToken; + } catch { + return false; + } + }; + const resolveMethod = async (method: string, params: unknown) => { if (method === "app.bootstrap") { const bootstrap = await ensureLaunchSession(); @@ -486,7 +505,12 @@ export async function startRuntimeApiServer( throw new Error(`Unknown API method: ${method}`); }; - wss.on("connection", (socket) => { + wss.on("connection", (socket, request) => { + if (!isAuthorizedConnection(request.url)) { + socket.close(4001, "unauthorized"); + return; + } + if (activeClient && activeClient !== socket) { activeClient.close(4000, "replaced-by-new-client"); } @@ -560,9 +584,13 @@ export async function startRuntimeApiServer( const address = wss.address(); const resolvedPort = typeof address === "object" && address !== null ? address.port : options.port; + const wsBaseUrl = `ws://127.0.0.1:${resolvedPort}`; + const wsUrl = authToken + ? `${wsBaseUrl}?token=${encodeURIComponent(authToken)}` + : wsBaseUrl; return { - wsUrl: `ws://127.0.0.1:${resolvedPort}`, + wsUrl, async close() { processManager.killAll(); providerManager.stopAll();