Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.iqlabs.agentnet

import android.util.Log
import android.content.Context
import java.net.HttpURLConnection
import java.net.URL

Expand All @@ -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 {
Expand All @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
53 changes: 53 additions & 0 deletions surfaces/desktop/src-tauri/src/local_session.rs
Original file line number Diff line number Diff line change
@@ -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<String> {
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())
}
14 changes: 9 additions & 5 deletions surfaces/desktop/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -154,7 +157,7 @@ fn port_answering() -> bool {
}

fn spawn_server(node: &str, server: &str) -> std::io::Result<Child> {
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
Expand Down Expand Up @@ -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)
Expand Down
33 changes: 33 additions & 0 deletions surfaces/localhost/README.md
Original file line number Diff line number Diff line change
@@ -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/<port>.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.
3 changes: 2 additions & 1 deletion surfaces/localhost/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
63 changes: 63 additions & 0 deletions surfaces/localhost/src/httpAuth.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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 };
}
19 changes: 15 additions & 4 deletions surfaces/localhost/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1322,8 +1324,11 @@ function readBody(req: import("node:http").IncomingMessage): Promise<string> {
}

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=<id>&cursor=<seq>,
Expand All @@ -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",
});
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading