diff --git a/surfaces/android/app/src/main/java/com/iqlabs/agentnet/MainActivity.kt b/surfaces/android/app/src/main/java/com/iqlabs/agentnet/MainActivity.kt index df319115..d63b042e 100644 --- a/surfaces/android/app/src/main/java/com/iqlabs/agentnet/MainActivity.kt +++ b/surfaces/android/app/src/main/java/com/iqlabs/agentnet/MainActivity.kt @@ -41,7 +41,6 @@ import kotlin.concurrent.thread class MainActivity : AppCompatActivity() { companion object { private const val TAG = "AgentNet/Main" - private const val URL = "http://127.0.0.1:${Paths.PORT}/" // dApp identity shown in the wallet's approval sheet. Must be a live domain we // control: wallets display it and may fetch the icon to verify who is asking. private const val IDENTITY_NAME = "AgentNet" @@ -551,7 +550,11 @@ class MainActivity : AppCompatActivity() { private fun showWebView() = runOnUiThread { bootBox.visibility = android.view.View.GONE webView.visibility = android.view.View.VISIBLE - webView.loadUrl(URL) + val session = ServerManager.readSession(this) ?: run { + setStatus("Local session unavailable\nRestart the app to reconnect safely.") + return@runOnUiThread + } + webView.loadUrl(session.launchUrl) } // Everything heavy runs off the UI thread; the UI shows progress until the server diff --git a/surfaces/android/app/src/main/java/com/iqlabs/agentnet/NotifActionReceiver.kt b/surfaces/android/app/src/main/java/com/iqlabs/agentnet/NotifActionReceiver.kt index a699fc80..8ba7aa34 100644 --- a/surfaces/android/app/src/main/java/com/iqlabs/agentnet/NotifActionReceiver.kt +++ b/surfaces/android/app/src/main/java/com/iqlabs/agentnet/NotifActionReceiver.kt @@ -42,7 +42,7 @@ class NotifActionReceiver : BroadcastReceiver() { val pending = goAsync() Thread { try { - RpcClient.post(client, body) + RpcClient.post(context, client, body) // Stop also demotes the foreground service (no more active work to hold it). if (kind == "stop") context.stopService(Intent(context, ServerService::class.java)) } finally { diff --git a/surfaces/android/app/src/main/java/com/iqlabs/agentnet/RpcClient.kt b/surfaces/android/app/src/main/java/com/iqlabs/agentnet/RpcClient.kt index e2a0c09e..261bb76e 100644 --- a/surfaces/android/app/src/main/java/com/iqlabs/agentnet/RpcClient.kt +++ b/surfaces/android/app/src/main/java/com/iqlabs/agentnet/RpcClient.kt @@ -1,6 +1,7 @@ package com.iqlabs.agentnet import android.util.Log +import android.content.Context import java.net.HttpURLConnection import java.net.URL @@ -15,8 +16,9 @@ object RpcClient { // `jsonBody` is a ready-made JSON object string, e.g. {"type":"interrupt"} or // {"type":"approvalDecision","id":"…","outcome":"deny"}. Runs on the caller's thread; // callers (a BroadcastReceiver via goAsync) are already off the main thread. - fun post(clientId: String, jsonBody: String): Boolean { + fun post(ctx: Context, clientId: String, jsonBody: String): Boolean { if (clientId.isBlank()) { Log.w(TAG, "no client id; dropping $jsonBody"); return false } + val session = ServerManager.readSession(ctx) ?: return false return try { val url = URL("http://127.0.0.1:${Paths.PORT}/rpc?client=" + java.net.URLEncoder.encode(clientId, "UTF-8")) (url.openConnection() as HttpURLConnection).run { @@ -25,6 +27,7 @@ object RpcClient { readTimeout = 3000 doOutput = true setRequestProperty("content-type", "application/json") + setRequestProperty("Authorization", "Bearer ${session.token}") outputStream.use { it.write(jsonBody.toByteArray()) } val code = responseCode disconnect() diff --git a/surfaces/android/app/src/main/java/com/iqlabs/agentnet/ServerManager.kt b/surfaces/android/app/src/main/java/com/iqlabs/agentnet/ServerManager.kt index e49fd117..56769ff7 100644 --- a/surfaces/android/app/src/main/java/com/iqlabs/agentnet/ServerManager.kt +++ b/surfaces/android/app/src/main/java/com/iqlabs/agentnet/ServerManager.kt @@ -22,6 +22,17 @@ import java.net.URL class ServerManager(private val ctx: Context) { companion object { private const val TAG = "AgentNet/Server" + + class LocalSession(val launchUrl: String, val token: String) + + // Written by the successfully bound server inside app-private storage. + // Never obtain this capability from an unauthenticated HTTP endpoint. + fun readSession(ctx: Context): LocalSession? = runCatching { + val value = File(Paths.layout(ctx).home, ".agentnet/localhost-auth/${Paths.PORT}.url").readText().trim() + val match = Regex("^http://127\\.0\\.0\\.1:${Paths.PORT}/#agentnet_session=([a-f0-9]{64})$").matchEntire(value) + ?: return@runCatching null + LocalSession(value, match.groupValues[1]) + }.getOrNull() } @Volatile private var process: Process? = null @@ -145,20 +156,23 @@ class ServerManager(private val ctx: Context) { return out } - // Poll http://127.0.0.1:PORT/onboarding until it answers (server up) or we time out. + // Validate the private launch capability against /session before opening the UI. // HTTP polling, not a fixed sleep, so we show the WebView the instant it's ready. fun waitForServer(timeoutMs: Long = 120_000): Boolean { val deadline = System.currentTimeMillis() + timeoutMs - val url = URL("http://127.0.0.1:${Paths.PORT}/onboarding") + val url = URL("http://127.0.0.1:${Paths.PORT}/session") while (System.currentTimeMillis() < deadline) { try { + val session = readSession(ctx) + if (session == null) { Thread.sleep(100); continue } val conn = url.openConnection() as HttpURLConnection conn.connectTimeout = 2000 conn.readTimeout = 2000 conn.requestMethod = "GET" + conn.setRequestProperty("Authorization", "Bearer ${session.token}") val code = conn.responseCode conn.disconnect() - if (code in 200..399) { + if (code == 204) { Log.i(TAG, "server ready (HTTP $code)") return true } diff --git a/surfaces/desktop/src-tauri/src/local_session.rs b/surfaces/desktop/src-tauri/src/local_session.rs new file mode 100644 index 00000000..094c4789 --- /dev/null +++ b/surfaces/desktop/src-tauri/src/local_session.rs @@ -0,0 +1,53 @@ +use crate::PORT; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpStream; +use std::path::PathBuf; +use std::time::Duration; + +// A listening port alone is not evidence that it is our authenticated server. +pub fn authenticated_launch_url() -> Option { + let state_dir = std::env::var("AGENTNET_HOME") + .ok() + .filter(|value| !value.is_empty()) + .map(PathBuf::from) + .or_else(|| { + std::env::var("HOME") + .or_else(|_| std::env::var("USERPROFILE")) + .ok() + .map(|home| PathBuf::from(home).join(".agentnet")) + })?; + let value = + std::fs::read_to_string(state_dir.join("localhost-auth").join(format!("{PORT}.url"))) + .ok()?; + let value = value.trim(); + let prefix = format!("http://127.0.0.1:{PORT}/#agentnet_session="); + let token = value.strip_prefix(&prefix)?; + if token.len() != 64 + || !token + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return None; + } + let mut connection = TcpStream::connect_timeout( + &(std::net::Ipv4Addr::LOCALHOST, PORT).into(), + Duration::from_millis(250), + ) + .ok()?; + connection + .set_read_timeout(Some(Duration::from_millis(500))) + .ok()?; + connection + .set_write_timeout(Some(Duration::from_millis(500))) + .ok()?; + write!(connection, "GET /session HTTP/1.1\r\nHost: 127.0.0.1:{PORT}\r\nAuthorization: Bearer {token}\r\nConnection: close\r\n\r\n").ok()?; + let mut status = String::new(); + BufReader::new(connection) + .take(128) + .read_line(&mut status) + .ok()?; + if !status.starts_with("HTTP/1.1 204 ") { + return None; + } + Some(value.to_string()) +} diff --git a/surfaces/desktop/src-tauri/src/main.rs b/surfaces/desktop/src-tauri/src/main.rs index fdaa2822..e2426f26 100644 --- a/surfaces/desktop/src-tauri/src/main.rs +++ b/surfaces/desktop/src-tauri/src/main.rs @@ -19,6 +19,9 @@ use tauri::menu::{MenuBuilder, MenuItemBuilder}; use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}; use tauri::{Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent}; +mod local_session; +use local_session::authenticated_launch_url; + const PORT: u16 = 4317; /// The .app's Contents/Resources dir, when running from inside a macOS @@ -154,7 +157,7 @@ fn port_answering() -> bool { } fn spawn_server(node: &str, server: &str) -> std::io::Result { - let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string()); + let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_else(|_| ".".to_string()); // Agents run from the user's HOME. A Finder/Dock launch would otherwise cwd // the child into the .app bundle (read-only under Gatekeeper translocation), // where files an agent writes fail or pollute the bundle. The server resolves @@ -235,21 +238,22 @@ fn main() { // (b) Wait until the server answers, up to ~30s. let deadline = Instant::now() + Duration::from_secs(30); - while !port_answering() { + let launch_url = loop { + if let Some(url) = authenticated_launch_url() { break url; } if Instant::now() >= deadline { // Tauri panics on a setup Err without firing Exit, so reap the // child we spawned here rather than leaking a server on 4317. kill_server(&app.handle()); - return Err("AgentNet server did not answer on port 4317 within 30s".into()); + return Err("Authenticated AgentNet server was not ready within 30s; close any older server and restart".into()); } std::thread::sleep(Duration::from_millis(200)); - } + }; // (c) Only now create the window, pointed at the same-origin SPA. let window = WebviewWindowBuilder::new( app, "main", - WebviewUrl::External(format!("http://localhost:{PORT}").parse().unwrap()), + WebviewUrl::External(launch_url.parse()?), ) .title("AgentNet") .inner_size(1240.0, 840.0) diff --git a/surfaces/localhost/README.md b/surfaces/localhost/README.md new file mode 100644 index 00000000..6b648624 --- /dev/null +++ b/surfaces/localhost/README.md @@ -0,0 +1,33 @@ +# Local HTTP authentication + +The server binds to `127.0.0.1`. After binding, it writes an owner-only launch URL to +`$AGENTNET_HOME/localhost-auth/.url` (default home: `~/.agentnet`). Open that +link to authorize the browser. The capability is in its fragment, is removed from +browser history on startup, and is sent only in Authorization headers. It is not +returned by a public HTTP endpoint, stored in cookies, or printed in server logs. + +For a manual macOS browser launch after starting the server: + +```sh +open "$(cat "${AGENTNET_HOME:-$HOME/.agentnet}/localhost-auth/${AGENTNET_PORT:-4317}.url")" +``` + +The browser keeps the capability in origin-scoped sessionStorage. Desktop and +Android wrappers read the private launch file and validate `/session` before +opening the UI; native notification RPCs authenticate as well. Reusing an older, +unauthenticated server fails closed. OAuth redirect callbacks retain their +existing flow. + +For Vite hot reload, preserve the private link's fragment when opening the dev +server URL. Its API proxy forwards the capability and rejects foreign UI origins. +`AGENTNET_HOME` changes application storage, not the CLI wallet path: disposable +wallet tests must also use an isolated `HOME`, as the reproduction does. + +`/session`, `/events`, and `/rpc` reject missing or stale capabilities. Host and +Origin checks additionally reject cross-origin requests and DNS-rebinding hosts. +This protects the HTTP boundary. It cannot protect a plaintext wallet key against +malware already running as its owner or against compromised application code. + +Run `pnpm --filter agentnet-localhost test` for the HTTP and transport regressions. +The security reproduction uses a disposable wallet and a sandbox with no access +to personal wallet files or external RPC networks; no transaction is needed. diff --git a/surfaces/localhost/package.json b/surfaces/localhost/package.json index e8f1488a..208d6405 100644 --- a/surfaces/localhost/package.json +++ b/surfaces/localhost/package.json @@ -7,7 +7,8 @@ "scripts": { "build": "tsup", "dev": "tsx src/index.ts", - "start": "node dist/index.js" + "start": "node dist/index.js", + "test": "node --import tsx --test test/*.test.ts" }, "dependencies": { "@iqlabs-official/agent-sdk": "workspace:*", diff --git a/surfaces/localhost/src/httpAuth.ts b/surfaces/localhost/src/httpAuth.ts new file mode 100644 index 00000000..f5902b11 --- /dev/null +++ b/surfaces/localhost/src/httpAuth.ts @@ -0,0 +1,63 @@ +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { chmod, lstat, mkdir, rename, writeFile } from "node:fs/promises"; +import type { IncomingMessage, ServerResponse } from "node:http"; +import { join } from "node:path"; + +// The launch capability is delivered through a private file, never through an +// unauthenticated HTTP response. A client id selects a stream; it is not auth. +export function createLocalHttpAuth(port: number, stateDir: string) { + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid localhost port"); + const token = randomBytes(32).toString("hex"); + const directory = join(stateDir, "localhost-auth"); + const launchFile = join(directory, `${port}.url`); + let ready = false; + + function handle(req: IncomingMessage, res: ServerResponse, path: string): boolean { + res.setHeader("referrer-policy", "no-referrer"); + res.setHeader("x-frame-options", "DENY"); + const host = req.headers.host; + if (host !== `127.0.0.1:${port}` && host !== `localhost:${port}`) { + res.writeHead(403).end("Untrusted host"); + return true; + } + if (req.headers.origin !== undefined && req.headers.origin !== `http://${host}`) { + res.writeHead(403).end("Untrusted origin"); + return true; + } + if (!ready) { res.writeHead(503).end("Starting localhost session"); return true; } + if (path !== "/session" && path !== "/events" && path !== "/rpc") return false; + res.setHeader("cache-control", "no-store"); + const bearer = req.headers.authorization?.match(/^Bearer ([a-f0-9]{64})$/)?.[1]; + // Cookies are shared across ports. Require the capability explicitly so it + // cannot be sent to an unrelated local app through a browser cookie. + if (!bearer || !timingSafeEqual(Buffer.from(bearer), Buffer.from(token))) { + res.writeHead(401).end("Open the app using its private launch link"); + return true; + } + if (req.headers["sec-fetch-site"] === "cross-site") { + res.writeHead(403).end("Cross-site requests are not allowed"); + return true; + } + if (path === "/session") { + if (req.method !== "GET") { + res.writeHead(405, { allow: "GET" }).end(); + } else { + res.writeHead(204).end(); + } + return true; + } + return false; + } + + async function publishLaunchUrl(): Promise { + await mkdir(directory, { recursive: true, mode: 0o700 }); + if ((await lstat(directory)).isSymbolicLink()) throw new Error("Local auth directory must not be a symlink"); + await chmod(directory, 0o700); + const temporary = join(directory, `${port}.${randomBytes(8).toString("hex")}.tmp`); + await writeFile(temporary, `http://127.0.0.1:${port}/#agentnet_session=${token}\n`, { mode: 0o600, flag: "wx" }); + await rename(temporary, launchFile); + ready = true; + } + + return { handle, publishLaunchUrl, launchFile }; +} diff --git a/surfaces/localhost/src/index.ts b/surfaces/localhost/src/index.ts index 576ec329..719305c3 100644 --- a/surfaces/localhost/src/index.ts +++ b/surfaces/localhost/src/index.ts @@ -86,8 +86,10 @@ import { import { SessionStore } from "@iqlabs-official/agent-sdk/account/store"; import { migrateSessions } from "@iqlabs-official/agent-sdk/account/migrate"; import { exportKeypair, importKeypair, solanaDefaultKeypairPath } from "@iqlabs-official/agent-sdk/account/localWallet"; +import { createLocalHttpAuth } from "./httpAuth.js"; const PORT = Number(process.env.AGENTNET_PORT ?? 4317); +const localAuth = createLocalHttpAuth(PORT, process.env.AGENTNET_HOME || join(homedir(), ".agentnet")); // This surface serves the app to a user with a system browser (desktop web + the Android // shell), so a http://localhost:PORT link the agent hands back actually opens. Declare that // to the runtime, which then gives the agent the "serve web apps + hand back a link" memory @@ -1322,8 +1324,11 @@ function readBody(req: import("node:http").IncomingMessage): Promise { } const http = createServer(async (req, res) => { - const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`); + let url: URL; + try { url = new URL(req.url ?? "/", `http://127.0.0.1:${PORT}`); } + catch { res.writeHead(400).end("Invalid request URL"); return; } const path = url.pathname; + if (localAuth.handle(req, res, path)) return; // ── SSE: open this UI's event stream (server→UI). A fresh connection gets a new // client id + chat attachment. A RECONNECT (?client=&cursor=, @@ -1333,7 +1338,7 @@ const http = createServer(async (req, res) => { if (req.method === "GET" && path === "/events") { res.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", - "cache-control": "no-cache, no-transform", + "cache-control": "no-store, no-transform", connection: "keep-alive", "x-accel-buffering": "no", }); @@ -1442,8 +1447,14 @@ const http = createServer(async (req, res) => { res.writeHead(404).end("not found"); }); -http.listen(PORT, () => { - console.log(`AgentNet localhost → http://localhost:${PORT}/ (guest chat ready)`); +http.listen(PORT, "127.0.0.1", () => { + void localAuth.publishLaunchUrl().then(() => { + console.log(`AgentNet localhost → http://127.0.0.1:${PORT}/\nOpen the private launch link in ${localAuth.launchFile}`); + }).catch((error) => { + console.error("Could not initialize localhost authentication:", error); + http.close(); + process.exitCode = 1; + }); }); // Boot reconnect: if the user's last choice was the device-local wallet, re-adopt it now. diff --git a/surfaces/localhost/test/http-security.test.ts b/surfaces/localhost/test/http-security.test.ts new file mode 100644 index 00000000..279950fb --- /dev/null +++ b/surfaces/localhost/test/http-security.test.ts @@ -0,0 +1,183 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer, request } from "node:http"; +import { mkdtemp, readFile, stat, symlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createLocalHttpAuth } from "../src/httpAuth.js"; +import { Transport } from "../../webview/src/transport/client.js"; + +const port = 46317; + +function http(path: string, headers: Record = {}, method = "GET") { + return new Promise<{ status: number; headers: Record; body: string }>((resolve, reject) => { + const req = request({ host: "127.0.0.1", port, path, method, headers }, res => { + let body = ""; + res.on("data", b => { body += b; }); + res.on("end", () => resolve({ status: res.statusCode!, headers: res.headers, body })); + }); + req.on("error", reject); + req.end(); + }); +} + +test("HTTP gate rejects anonymous, spoofed and stale capabilities; preserves authorized RPC and callback", async () => { + const dir = await mkdtemp(join(tmpdir(), "agentnet-auth-")); + let auth = createLocalHttpAuth(port, dir); + let exports = 0; + const server = createServer((req, res) => { + const path = new URL(req.url!, `http://127.0.0.1:${port}`).pathname; + if (auth.handle(req, res, path)) return; + if (path === "/rpc") { exports++; res.writeHead(204).end(); } + else if (path === "/events") res.end("event: client\ndata: {\"client\":\"c1\"}\n\n"); + else res.end("public UI or OAuth callback"); + }); + await new Promise(resolve => server.listen(port, "127.0.0.1", resolve)); + try { + assert.equal((await http("/events")).status, 503); + await auth.publishLaunchUrl(); + const firstUrl = (await readFile(auth.launchFile, "utf8")).trim(); + const token = new URLSearchParams(new URL(firstUrl).hash.slice(1)).get("agentnet_session")!; + const authorized = { authorization: `Bearer ${token}` }; + assert.equal((await stat(auth.launchFile)).mode & 0o777, 0o600); + assert.equal((await stat(join(dir, "localhost-auth"))).mode & 0o777, 0o700); + for (const path of ["/events", "/rpc?client=c1", "/session"]) { + assert.equal((await http(path)).status, 401); + assert.equal((await http(`${path}${path.includes("?") ? "&" : "?"}token=${token}`)).status, 401); + assert.equal((await http(path, { cookie: `agentnet_local_${port}=${token}` })).status, 401); + assert.equal((await http(path, { authorization: `Bearer ${"0".repeat(64)}` })).status, 401); + assert.equal((await http(path, { ...authorized, origin: "https://untrusted.example" })).status, 403); + assert.equal((await http(path, { ...authorized, host: `rebind.example:${port}` })).status, 403); + assert.equal((await http(path, { ...authorized, "sec-fetch-site": "cross-site" })).status, 403); + } + assert.equal(exports, 0); + assert.equal((await http("/session", authorized)).status, 204); + assert.equal((await http("/session", authorized, "POST")).status, 405); + const rpc = await http("/rpc?client=c1", { ...authorized, origin: `http://127.0.0.1:${port}` }, "POST"); + assert.equal(rpc.status, 204); + assert.equal(rpc.headers["cache-control"], "no-store"); + assert.equal(rpc.headers["set-cookie"], undefined); + assert.equal(exports, 1); + assert.equal((await http("/events", authorized)).status, 200); + assert.equal((await http("/oauth/google/callback?state=existing-state")).status, 200); + assert.equal((await http("/")).body.includes(token), false); + auth = createLocalHttpAuth(port, dir); + await auth.publishLaunchUrl(); + assert.equal((await http("/session", authorized)).status, 401); + assert.notEqual((await readFile(auth.launchFile, "utf8")).trim(), firstUrl); + } finally { + server.closeAllConnections(); + await new Promise(resolve => server.close(() => resolve())); + } +}); + +test("authentication refuses a symlinked private directory", async () => { + const dir = await mkdtemp(join(tmpdir(), "agentnet-auth-link-")); + const other = await mkdtemp(join(tmpdir(), "agentnet-auth-target-")); + await symlink(other, join(dir, "localhost-auth")); + await assert.rejects(createLocalHttpAuth(port, dir).publishLaunchUrl(), /symlink/); +}); + +async function until(predicate: () => boolean, timeout = 2200) { + const end = Date.now() + timeout; + while (!predicate()) { + if (Date.now() > end) throw new Error("Expected transport result did not arrive"); + await new Promise(resolve => setTimeout(resolve, 5)); + } +} + +test("browser transport authenticates streams/RPC, decodes split UTF-8, replays cursor and cancels on close", async () => { + const originalFetch = globalThis.fetch; + const originalWindow = globalThis.window; + const token = "a".repeat(64); + const storage = new Map(); + let currentUrl = new URL(`http://127.0.0.1:${port}/#agentnet_session=${token}`); + const calls: { url: string; options: RequestInit }[] = []; + const streams: ReadableStreamDefaultController[] = []; + const events: unknown[] = []; + Object.assign(globalThis, { window: { + get location() { return currentUrl; }, + history: { replaceState(_a: unknown, _b: string, url: URL) { currentUrl = new URL(url); } }, + sessionStorage: { getItem: (key: string) => storage.get(key) ?? null, setItem: (key: string, value: string) => storage.set(key, value) }, + } }); + globalThis.fetch = (async (url: string, options: RequestInit = {}) => { + calls.push({ url, options }); + assert.equal(new Headers(options.headers).get("authorization"), `Bearer ${token}`); + assert.equal(options.credentials, "omit"); + assert.equal(currentUrl.hash, ""); + assert.equal(url.includes(token), false); + if (url === "/session" || url.startsWith("/rpc")) return new Response(null, { status: 204 }); + return new Response(new ReadableStream({ + start(controller) { + streams.push(controller); + options.signal?.addEventListener("abort", () => controller.error(new DOMException("closed", "AbortError")), { once: true }); + controller.enqueue(new TextEncoder().encode("event: client\r\ndata: {\"client\":\"c1\"}\r\n\r\n")); + }, + })); + }) as typeof fetch; + const transport = new Transport(); + transport.onEvent(event => events.push(event)); + try { + transport.open(); transport.open(); + await until(() => transport.getClientId() === "c1"); + assert.equal(calls.filter(c => c.url === "/session").length, 1); + const data = new TextEncoder().encode("id: 7\ndata: {\"type\":\"toast\",\"text\":\"안녕\"}\n\n"); + for (const byte of data) streams[0].enqueue(new Uint8Array([byte])); + await until(() => events.some((e: any) => e.text === "안녕")); + await transport.post({ type: "wallet" }); + assert.equal(calls.at(-1)?.url, "/rpc?client=c1"); + streams[0].close(); + await until(() => calls.some(c => c.url === "/events?client=c1&cursor=7")); + transport.reopen(); + await until(() => streams.length === 3); + assert.equal(calls.at(-1)?.url, "/events"); + transport.close(); + const count = calls.length; + await transport.post({ type: "wallet" }); + assert.equal(calls.length, count); + } finally { + transport.close(); globalThis.fetch = originalFetch; Object.assign(globalThis, { window: originalWindow }); + } +}); + +test("missing capability fails closed without requests", async () => { + const originalFetch = globalThis.fetch, originalWindow = globalThis.window; + let calls = 0; + Object.assign(globalThis, { window: { location: new URL(`http://127.0.0.1:${port}/`), sessionStorage: { getItem: () => null } } }); + globalThis.fetch = (async () => { calls++; throw new Error("Unexpected request"); }) as typeof fetch; + const events: any[] = [], transport = new Transport(); + transport.onEvent(event => events.push(event)); + try { + transport.open(); + await until(() => events.some(e => e.type === "localAuthRequired")); + assert.equal(calls, 0); + } finally { + transport.close(); globalThis.fetch = originalFetch; Object.assign(globalThis, { window: originalWindow }); + } +}); + +test("closing during bootstrap prevents a late response from opening a stream", async () => { + const originalFetch = globalThis.fetch, originalWindow = globalThis.window; + let finish!: (response: Response) => void; + let calls = 0; + Object.assign(globalThis, { window: { + location: new URL(`http://127.0.0.1:${port}/`), + sessionStorage: { getItem: () => "a".repeat(64) }, + } }); + globalThis.fetch = (() => { + calls++; + return new Promise(resolve => { finish = resolve; }); + }) as typeof fetch; + const transport = new Transport(); + try { + transport.open(); + assert.equal(calls, 1); + transport.close(); + finish(new Response(null, { status: 204 })); + await new Promise(resolve => setTimeout(resolve, 10)); + assert.equal(calls, 1); + assert.equal(transport.getClientId(), null); + } finally { + transport.close(); globalThis.fetch = originalFetch; Object.assign(globalThis, { window: originalWindow }); + } +}); diff --git a/surfaces/webview/src/App.tsx b/surfaces/webview/src/App.tsx index e3e15775..84f525e6 100644 --- a/surfaces/webview/src/App.tsx +++ b/surfaces/webview/src/App.tsx @@ -138,6 +138,15 @@ export function App() { return ( <>
+ {state.phase === "localAuth" && ( +
+

Reopen AgentNet

+

+ This window needs a private launch link. Reopen the desktop or Android app. + If you started AgentNet in a terminal, use the launch link file shown there. +

+
+ )} {(state.phase === "connecting" || state.phase === "restoring") && } {state.phase === "claudeAuth" && } {state.phase === "codexAuth" && } diff --git a/surfaces/webview/src/state/store.spec.tsx b/surfaces/webview/src/state/store.spec.tsx index 3b84d55e..7ba05f00 100644 --- a/surfaces/webview/src/state/store.spec.tsx +++ b/surfaces/webview/src/state/store.spec.tsx @@ -1,6 +1,20 @@ import { describe, expect, it } from "vitest"; import { initialState, reducer } from "./store"; +describe("local session authorization", () => { + it("locks the window and clears revealed secrets and funding UI when authorization expires", () => { + const state = reducer({ ...initialState, phase: "chat", walletAddress: "disposable-wallet", + secretKey: "synthetic-secret", secretKeyError: "old error", fundOpen: true, marketOpen: true, + }, { type: "localAuthRequired" }); + expect(state.phase).toBe("localAuth"); + expect(state.walletAddress).toBeNull(); + expect(state.secretKey).toBeNull(); + expect(state.secretKeyError).toBeNull(); + expect(state.fundOpen).toBe(false); + expect(state.marketOpen).toBe(false); + }); +}); + describe("chat selection restoration", () => { it("restores each engine's settings on a fresh load and retains them across a repaint", () => { let state = reducer(initialState, { type: "settings", cli: "claude", model: "sonnet", effort: "high", mode: "plan" }); diff --git a/surfaces/webview/src/state/store.tsx b/surfaces/webview/src/state/store.tsx index d38f3e4b..f942a0b8 100644 --- a/surfaces/webview/src/state/store.tsx +++ b/surfaces/webview/src/state/store.tsx @@ -55,6 +55,7 @@ export interface State { phase: | "connecting" | "restoring" // Android cold boot: attempting a silent Keystore reconnect (shows Splash, not the signup screen) + | "localAuth" | "claudeAuth" | "codexAuth" | "customAuth" // custom engine picked with no saved endpoint: the AI Connections form, not a login @@ -352,6 +353,8 @@ type Action = ServerMessage | LocalAction; export function reducer(state: State, ev: Action): State { switch (ev.type) { + case "localAuthRequired": + return { ...state, phase: "localAuth", walletAddress: null, secretKey: null, secretKeyError: null, fundOpen: false, marketOpen: false }; case "__typing": return { ...state, typing: true }; case "__removeApproval": diff --git a/surfaces/webview/src/transport/client.ts b/surfaces/webview/src/transport/client.ts index 026256bb..1667f0d6 100644 --- a/surfaces/webview/src/transport/client.ts +++ b/surfaces/webview/src/transport/client.ts @@ -1,13 +1,5 @@ -// The single seam between this UI and core. Talks surfaces/localhost's transport: -// server→UI : SSE on GET /events (first frame is `event: client {client:id}`) -// UI→server : POST /rpc?client= (body = a ClientMessage) -// -// surfaces/localhost numbers every data frame (`id: N`) and keeps a per-client replay -// buffer, so after a dropped stream we reopen /events?client=&cursor= and -// it re-emits what we missed — no lost events across a brief WebView/network blip. The -// EventSource auto-reconnects on its own, but it would open a FRESH client; we want the -// SAME one, so we manage reconnection manually with the cursor. - +// Authenticated HTTP-RPC + SSE. The private launch capability stays in this +// origin's sessionStorage and Authorization headers, never cookies or API URLs. import type { ClientMessage, ServerMessage } from "./protocol"; type Listener = (msg: ServerMessage) => void; @@ -15,118 +7,147 @@ type Listener = (msg: ServerMessage) => void; export class Transport { private clientId: string | null = null; private lastEventId = 0; - private es: EventSource | null = null; + private stream: AbortController | null = null; + private capability: string | null = null; private listeners = new Set(); - private closed = false; - private retryDelay = 1000; // reconnect backoff (ms); grows on repeat failures, resets on connect + private closed = true; + private lifecycle = 0; + private retryDelay = 1000; - /** The SSE client id (null until the handshake lands). Native notification actions POST - * to /rpc?client= with it, so the Android shell needs to read it. */ - getClientId(): string | null { - return this.clientId; - } + getClientId(): string | null { return this.clientId; } - /** Subscribe to server→UI events. Returns an unsubscribe fn. */ onEvent(cb: Listener): () => void { this.listeners.add(cb); return () => this.listeners.delete(cb); } - /** Open the SSE stream (idempotent). Call once on app start. */ open(): void { + if (!this.closed) return; this.closed = false; - this.connect(); + this.lifecycle++; + void this.bootstrap(); } - /** Drop the current client and open a brand-new SSE stream. Used after onboarding: - * the first stream attached the ONBOARDING handler (no runtime yet); once the wallet - * is connected the runtime exists, so a fresh stream attaches the CHAT dispatcher. - * (The server keys chat-vs-onboarding on "did a runtime exist when /events opened".) - * A React SPA never navigates, so without this the onboarding client would keep - * handling chat messages — i.e. silently drop every `send`. */ + private async bootstrap(): Promise { + const lifecycle = this.lifecycle; + const fragment = new URLSearchParams(window.location.hash.slice(1)); + const capability = fragment.get("agentnet_session"); + if (capability) { + fragment.delete("agentnet_session"); + const url = new URL(window.location.href); + url.hash = fragment.toString(); + window.history.replaceState(null, "", url); + } + try { + this.capability = capability; + try { + if (capability) window.sessionStorage.setItem("agentnet.localSession", capability); + else this.capability = window.sessionStorage.getItem("agentnet.localSession"); + } catch { /* a private launch link still works when storage is unavailable */ } + if (!this.capability) { this.unauthorized(); return; } + const response = await fetch("/session", { + headers: { authorization: `Bearer ${this.capability}` }, credentials: "omit", + }); + if (lifecycle !== this.lifecycle) return; + if (response.status !== 204) { this.unauthorized(); return; } + if (!this.closed) void this.connect(); + } catch { + if (lifecycle === this.lifecycle) this.unauthorized(); + } + } + + // Connecting a wallet reopens the same transport with a fresh chat dispatcher. reopen(): void { - this.es?.close(); - this.es = null; + this.stream?.abort(); + this.stream = null; this.clientId = null; this.lastEventId = 0; this.retryDelay = 1000; - this.connect(); + void this.connect(); } - /** Send one UI→server command. No-op until the client id handshake completes. */ async post(msg: ClientMessage): Promise { - if (!this.clientId) { - // Shouldn't happen in normal flow (UI actions come after the stream is up), but - // guard so an early click doesn't 409 — or hang forever if the handshake never - // lands (server down). Wait briefly; bail rather than POST with a null client. - const ready = await this.waitForId(); - if (!ready || !this.clientId) return; - } - await fetch(`/rpc?client=${encodeURIComponent(this.clientId)}`, { - method: "POST", - headers: { "content-type": "application/json" }, + if (this.closed) return; + if (!this.clientId && !await this.waitForId()) return; + if (!this.clientId || this.closed) return; + const response = await fetch(`/rpc?client=${encodeURIComponent(this.clientId)}`, { + method: "POST", credentials: "omit", + headers: { "content-type": "application/json", authorization: `Bearer ${this.capability}` }, body: JSON.stringify(msg), }); + if (response.status === 401 || response.status === 403) this.unauthorized(); } close(): void { this.closed = true; - this.es?.close(); - this.es = null; + this.lifecycle++; + this.stream?.abort(); + this.stream = null; } - // ── internals ── + private unauthorized(): void { + this.close(); + this.clientId = null; + for (const cb of this.listeners) cb({ type: "localAuthRequired" }); + } - private connect(): void { + private async connect(): Promise { + if (this.closed || !this.capability) return; const q = this.clientId - ? `?client=${encodeURIComponent(this.clientId)}&cursor=${this.lastEventId}` - : ""; - const es = new EventSource(`/events${q}`); - this.es = es; - - // The handshake frame (`event: client`) carries our id. On a reconnect the server - // echoes the same id back; on a fresh open it mints a new one. - es.addEventListener("client", (e) => { - try { - this.clientId = JSON.parse((e as MessageEvent).data).client; - this.retryDelay = 1000; // stream is up — reset the reconnect backoff - } catch { - /* ignore malformed handshake */ - } - }); - - // Every numbered data frame is a ServerMessage. Track its id for replay-on-reconnect. - es.onmessage = (e) => { - if (e.lastEventId) this.lastEventId = Number(e.lastEventId) || this.lastEventId; - let msg: ServerMessage; - try { - msg = JSON.parse(e.data); - } catch { - return; // skip garbage, keep the stream alive + ? `?client=${encodeURIComponent(this.clientId)}&cursor=${this.lastEventId}` : ""; + const controller = new AbortController(); + this.stream = controller; + try { + const response = await fetch(`/events${q}`, { + headers: { authorization: `Bearer ${this.capability}` }, + credentials: "omit", signal: controller.signal, + }); + if (response.status === 401 || response.status === 403) { this.unauthorized(); return; } + if (!response.ok || !response.body) throw new Error("Local event stream unavailable"); + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let pending = ""; + while (true) { + const { value, done } = await reader.read(); + if (done) break; + pending += decoder.decode(value, { stream: true }); + let boundary: RegExpExecArray | null; + while ((boundary = /\r?\n\r?\n/.exec(pending))) { + const frame = pending.slice(0, boundary.index); + pending = pending.slice(boundary.index + boundary[0].length); + this.receiveFrame(frame); + } } - for (const cb of this.listeners) cb(msg); - }; - - // EventSource retries internally, but to preserve our client id + cursor we close it - // and reopen with the query params ourselves. - es.onerror = () => { - es.close(); - this.es = null; - if (this.closed) return; + } catch { + // Transient drops use the same bounded backoff as the previous EventSource. + } finally { + if (this.stream !== controller || this.closed) return; + this.stream = null; const delay = this.retryDelay; - // Exponential backoff, capped at 30s: a down server used to get hammered with a - // fresh reconnect every second. Reset to 1s once a stream reconnects (see above). this.retryDelay = Math.min(this.retryDelay * 2, 30_000); - setTimeout(() => { - if (!this.closed) this.connect(); - }, delay); - }; + setTimeout(() => { if (!this.closed) void this.connect(); }, delay); + } + } + + private receiveFrame(frame: string): void { + const lines = frame.split(/\r?\n/); + const data = lines.filter(line => line.startsWith("data:")) + .map(line => line.slice(5).replace(/^ /, "")).join("\n"); + if (!data) return; + let msg: ServerMessage; + try { msg = JSON.parse(data); } catch { return; } + if (lines.some(line => line === "event: client")) { + this.clientId = (msg as unknown as { client: string }).client; + this.retryDelay = 1000; + return; + } + const id = lines.find(line => line.startsWith("id:")); + if (id) this.lastEventId = Number(id.slice(3).trim()) || this.lastEventId; + for (const cb of this.listeners) cb(msg); } - // Resolve true once the handshake id lands; false if the transport closes or we give up. - // Capped so a never-completing handshake (server down) can't hang post() forever. private waitForId(): Promise { - return new Promise((resolve) => { + return new Promise(resolve => { let waited = 0; const tick = () => { if (this.clientId) resolve(true); diff --git a/surfaces/webview/src/transport/protocol.ts b/surfaces/webview/src/transport/protocol.ts index 6b9ee107..1d68678b 100644 --- a/surfaces/webview/src/transport/protocol.ts +++ b/surfaces/webview/src/transport/protocol.ts @@ -253,6 +253,7 @@ export type ServerMessage = | { type: "approvalsSnapshot"; reqs: ApprovalRequest[] } // setup/auth: | { type: "init"; defaultPath: string | null; cloudKind: string | null; hasWallet?: boolean } + | { type: "localAuthRequired" } | { type: "walletConnected"; address: string | null; storageOptions: unknown; storageConfigured?: boolean } // answers to exportSecretKey / importSecretKey; `error` carries the host's reason | { type: "secretKey"; secretKey: string | null; error?: string } diff --git a/surfaces/webview/vite.config.ts b/surfaces/webview/vite.config.ts index d5410d51..b76ec65c 100644 --- a/surfaces/webview/vite.config.ts +++ b/surfaces/webview/vite.config.ts @@ -1,4 +1,4 @@ -import { defineConfig } from "vite"; +import { defineConfig, type ProxyOptions } from "vite"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; @@ -8,14 +8,31 @@ import tailwindcss from "@tailwindcss/vite"; // relative so the bundle works under the WebView's origin (127.0.0.1/file) unchanged. // The dev server proxies /events + /rpc to a running surfaces/localhost (port 4317) so // `vite dev` can drive a real core in a desktop browser while building the UI. +const appProxy: ProxyOptions = { + target: "http://127.0.0.1:4317", + changeOrigin: true, + configure(proxy) { + proxy.on("proxyReq", (outgoing, incoming) => { + if (incoming.headers.origin && incoming.headers.origin !== `http://${incoming.headers.host}`) { + outgoing.destroy(new Error("Cross-origin local API request")); + return; + } + // The development proxy is same-origin to its UI. Authenticate to the + // backend with the capability; do not forward a different port's Origin. + outgoing.removeHeader("origin"); + }); + }, +}; + export default defineConfig({ base: "./", plugins: [react(), tailwindcss()], build: { outDir: "dist", emptyOutDir: true }, server: { proxy: { - "/events": { target: "http://localhost:4317", changeOrigin: true }, - "/rpc": { target: "http://localhost:4317", changeOrigin: true }, + "/session": appProxy, + "/events": appProxy, + "/rpc": appProxy, }, }, });