Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: keep local session keys off externally reachable listeners (#17007)

Graham Neubigc5efa3ae415d
diff --git a/.agents/skills/e2e-testing/references/guide.md b/.agents/skills/e2e-testing/references/guide.md
index 97038a4020..8078fb2215 100644
--- a/.agents/skills/e2e-testing/references/guide.md
+++ b/.agents/skills/e2e-testing/references/guide.md
@@ -57,7 +57,7 @@
- The same test specs and helpers are reused to validate the Docker image via `playwright.mock-llm-docker.config.ts`. Run locally with `npm run test:e2e:mock-llm:docker` (requires Docker daemon and a built image).
- **Architecture**: The Docker config replaces the npm path's `bin/agent-canvas.mjs` webServer with a `docker run --network host` command. The mock LLM server still runs on the host. On Linux (including CI), `--network host` lets the container share the host's network stack so all `127.0.0.1` URLs work identically. On macOS/Windows Docker Desktop (bridge networking), set `MOCK_LLM_AGENT_URL=http://host.docker.internal:<port>` so the agent-server inside Docker can reach the host-side mock LLM server.
-- **Dual-stack binding**: Both `scripts/static-server.mjs` and `scripts/ingress.mjs` default to `::` (dual-stack, accepting IPv4 and IPv6 connections). The Docker entrypoint passes `--host ::` explicitly. This means `localhost` is safe in both the Docker and npm Playwright configs β€” whether it resolves to `127.0.0.1` (IPv4) or `::1` (IPv6), the server accepts the connection. The mock LLM server URL (`MOCK_LLM_URL`) still uses `127.0.0.1` because the Python mock server is a separate process whose bind behavior we don't control.
+- **Dual-stack binding**: `scripts/static-server.mjs` and `scripts/ingress.mjs` default to `127.0.0.1` (loopback) so a local session key is not exposed on the LAN. The Docker entrypoint passes `--host ::` (dual-stack, all interfaces inside the container) so published ports work, but only passes `--allow-lan-session-key` when `AGENT_CANVAS_ALLOW_LAN_SESSION_KEY=true`; the documented opt-in pairs that setting with a host-loopback-only port publish. Playwright npm configs should use `http://127.0.0.1` for the canvas origin when talking to the default bind. The mock LLM server URL (`MOCK_LLM_URL`) still uses `127.0.0.1` because the Python mock server is a separate process whose bind behavior we don't control.
- **Entrypoint crash resilience**: `docker/entrypoint.sh` uses a `while kill -0 "$STATIC_PID"; do sleep 10 & wait $!; done` loop instead of `wait -n "${PIDS[@]}"` (any child). If the agent-server or automation backend exits mid-test, the static-server proxy stays up and returns 502s for backend routes β€” the container doesn't disappear with `ECONNREFUSED`. The container exits only when the static-server (ingress) dies or on SIGTERM/SIGINT. The `sleep & wait $!` pattern ensures `wait` (a bash builtin) is the foreground op, so trapped signals fire immediately. `cleanup()` includes `exit 0` so the script terminates after a signal-triggered trap return.
- **URL split**: `mock-llm-helpers.ts` exports two mock LLM URL constants:
- `MOCK_LLM_BASE_URL` β€” always `http://127.0.0.1:<port>`, used by tests for the mock LLM admin API (register/activate/reset trajectories).
diff --git a/.github/pr-assets/pr-16975-agent-canvas-loopback.png b/.github/pr-assets/pr-16975-agent-canvas-loopback.png
new file mode 100644
index 0000000000..5812cfd226
Binary files /dev/null and b/.github/pr-assets/pr-16975-agent-canvas-loopback.png differ
diff --git a/.github/pr-assets/pr-16975-bind-policy.png b/.github/pr-assets/pr-16975-bind-policy.png
new file mode 100644
index 0000000000..c025fd6bf5
Binary files /dev/null and b/.github/pr-assets/pr-16975-bind-policy.png differ
diff --git a/README.md b/README.md
index 22abe4db44..d0759960a6 100644
--- a/README.md
+++ b/README.md
@@ -93,7 +93,8 @@ export PROJECTS_PATH="$HOME/projects" # directory containing your project folde
mkdir -p "$PROJECTS_PATH" "$HOME/.openhands"
docker run -it --rm \
- -p 8000:8000 \
+ -p 127.0.0.1:8000:8000 \
+ -e AGENT_CANVAS_ALLOW_LAN_SESSION_KEY=true \
-v "$HOME/.openhands:/home/openhands/.openhands" \
-v "${PROJECTS_PATH}:/projects" \
ghcr.io/openhands/agent-canvas:1.24.0 # x-release-please-version
@@ -121,6 +122,10 @@ npm run dev
Access the UI at [http://localhost:8000](http://localhost:8000) for the npm/source launchers, or [http://localhost:8000/canvas](http://localhost:8000/canvas) for the Docker image. You can add additional backends directly from the UI.
+Local (`npx` / `npm run dev`) listeners bind **loopback only** (`127.0.0.1`) so the auto-injected session key is not reachable from other machines on the network. To listen on all interfaces, pass `--host 0.0.0.0` (or set `OH_BIND_HOST`); the session key is then **not** injected and the UI uses the same API-key entry screen as `--public`.
+
+Docker listens on all container interfaces so port publishing works, but does not inject its session key into HTML by default. The quickstart above explicitly enables injection while publishing the host port on `127.0.0.1` only. If you publish Docker on a LAN or public interface, omit `AGENT_CANVAS_ALLOW_LAN_SESSION_KEY` and enter the API key in the UI. Set `LOCAL_BACKEND_API_KEY` to a strong value, or retrieve the generated value with `docker exec <container> sh -c 'cat "$STATE_DIR/api-key.txt"'`. For internet-facing installs, follow [self-hosting](./docs/SELF_HOSTING.md).
+
# Architecture
Agent Canvas is powered by the [OpenHands Agent Server](https://github.com/OpenHands/software-agent-sdk/tree/main/openhands-agent-server/openhands/agent_server), a REST API for running multiple agents on a single machine. Each Agent Server runs on a single host/port; the Agent Canvas can connect to multiple Agent Servers and easily flip between them.
@@ -140,16 +145,15 @@ The Agent Server is often paired with an [Automation Server](https://github.com/
Agent Canvas is part of a multi-repository OpenHands system. Changes should go to the repository that owns the behavior:
-| Repository | Responsibility |
-|---|---|
-| [`OpenHands/OpenHands`](https://github.com/OpenHands/OpenHands) | Agent Canvas frontend, user-facing control center, backend selection, and local-stack orchestration. |
+| Repository | Responsibility |
+| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
+| [`OpenHands/OpenHands`](https://github.com/OpenHands/OpenHands) | Agent Canvas frontend, user-facing control center, backend selection, and local-stack orchestration. |
| [`OpenHands/software-agent-sdk`](https://github.com/OpenHands/software-agent-sdk) | Python SDK, Agent Server, agents, tools, conversations, workspaces, events, and the canonical server API. |
-| [`OpenHands/typescript-client`](https://github.com/OpenHands/typescript-client) | Browser-compatible TypeScript client for the Agent Server API. |
-| [`OpenHands/automation`](https://github.com/OpenHands/automation) | Automation definitions, scheduling, webhooks, run history, and dispatching. |
+| [`OpenHands/typescript-client`](https://github.com/OpenHands/typescript-client) | Browser-compatible TypeScript client for the Agent Server API. |
+| [`OpenHands/automation`](https://github.com/OpenHands/automation) | Automation definitions, scheduling, webhooks, run history, and dispatching. |
The Agent Server API is implemented by the SDK and consumed through the TypeScript client by Agent Canvas. The automation service decides when work runs and dispatches conversations to the Agent Server/SDK, which decides what runs. See [`AGENTS.md`](./AGENTS.md) for contributor-specific boundaries and the required custom code-review guide.
-
## More documentation
- [Documentation index](./docs/README.md)
diff --git a/README.windows.md b/README.windows.md
index 49151c055c..23a4c76a0a 100644
--- a/README.windows.md
+++ b/README.windows.md
@@ -18,7 +18,8 @@ $env:PROJECTS_PATH = Join-Path $HOME "projects" # directory containing your pro
New-Item -ItemType Directory -Force -Path $env:PROJECTS_PATH, (Join-Path $env:USERPROFILE ".openhands") | Out-Null
docker run -it --rm `
- -p 8000:8000 `
+ -p 127.0.0.1:8000:8000 `
+ -e AGENT_CANVAS_ALLOW_LAN_SESSION_KEY=true `
-v "$($env:USERPROFILE)\.openhands:/home/openhands/.openhands" `
-v "$($env:PROJECTS_PATH):/projects" `
ghcr.io/openhands/agent-canvas:1.24.0 # x-release-please-version
@@ -27,3 +28,5 @@ docker run -it --rm `
Open [http://localhost:8000/canvas](http://localhost:8000/canvas) in your browser.
The agent will be able to access any project under `PROJECTS_PATH`.
+
+The quickstart restricts the published port to host loopback before explicitly enabling session-key injection. If you publish the port on a LAN or public interface, omit `AGENT_CANVAS_ALLOW_LAN_SESSION_KEY`, set `LOCAL_BACKEND_API_KEY` to a strong value, and enter that value in the UI.
diff --git a/__tests__/scripts/bind-host.test.ts b/__tests__/scripts/bind-host.test.ts
new file mode 100644
index 0000000000..e58356d74b
--- /dev/null
+++ b/__tests__/scripts/bind-host.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ DEFAULT_BIND_HOST,
+ applySessionKeyPolicy,
+ bindHostArgs,
+ isLoopbackBind,
+ resolveBindHost,
+} from "../../scripts/bind-host.mjs";
+
+describe("bind-host", () => {
+ it("defaults to IPv4 loopback", () => {
+ expect(DEFAULT_BIND_HOST).toBe("127.0.0.1");
+ expect(resolveBindHost({})).toBe("127.0.0.1");
+ });
+
+ it("prefers --host over OH_BIND_HOST", () => {
+ expect(
+ resolveBindHost({ flag: "0.0.0.0", env: "::" }),
+ ).toBe("0.0.0.0");
+ });
+
+ it("treats :: and 0.0.0.0 as non-loopback", () => {
+ expect(isLoopbackBind("::")).toBe(false);
+ expect(isLoopbackBind("0.0.0.0")).toBe(false);
+ expect(isLoopbackBind("127.0.0.1")).toBe(true);
+ expect(isLoopbackBind("::1")).toBe(true);
+ expect(isLoopbackBind("[::1]")).toBe(true);
+ expect(isLoopbackBind("localhost")).toBe(true);
+ });
+
+ it("recognizes the full 127.0.0.0/8 loopback range (RFC 3330)", () => {
+ expect(isLoopbackBind("127.0.0.2")).toBe(true);
+ expect(isLoopbackBind("127.0.0.3")).toBe(true);
+ expect(isLoopbackBind("127.1.2.3")).toBe(true);
+ expect(isLoopbackBind("127.255.255.255")).toBe(true);
+ });
+
+ it("strips the session key when bound off-loopback", () => {
+ const warn = vi.fn();
+ const policy = applySessionKeyPolicy({
+ host: "::",
+ sessionApiKey: "secret-key",
+ warn,
+ });
+ expect(policy.sessionApiKey).toBeNull();
+ expect(policy.authRequired).toBe(true);
+ expect(policy.strippedSessionKey).toBe(true);
+ expect(warn).toHaveBeenCalled();
+ });
+
+ it("keeps the session key on loopback", () => {
+ const policy = applySessionKeyPolicy({
+ host: "127.0.0.1",
+ sessionApiKey: "secret-key",
+ warn: () => {},
+ });
+ expect(policy.sessionApiKey).toBe("secret-key");
+ expect(policy.authRequired).toBe(false);
+ expect(policy.strippedSessionKey).toBe(false);
+ });
+
+ it("keeps the session key on non-loopback when explicitly allowed", () => {
+ const policy = applySessionKeyPolicy({
+ host: "::",
+ sessionApiKey: "secret-key",
+ allowLanSessionKey: true,
+ warn: () => {},
+ });
+ expect(policy.sessionApiKey).toBe("secret-key");
+ expect(policy.strippedSessionKey).toBe(false);
+ });
+
+ it("emits --host for child processes", () => {
+ expect(bindHostArgs("127.0.0.1")).toEqual(["--host", "127.0.0.1"]);
+ });
+});
diff --git a/__tests__/scripts/dev-safe.test.ts b/__tests__/scripts/dev-safe.test.ts
index b2ab67c0a2..801e8e1a31 100644
--- a/__tests__/scripts/dev-safe.test.ts
+++ b/__tests__/scripts/dev-safe.test.ts
@@ -26,6 +26,7 @@ import {
formatMissingUvxGuidance,
formatMissingFrontendDependenciesGuidance,
getMissingFrontendDependencyBins,
+ getViteSessionApiKey,
validateFrontendDependencies,
validateLocalAgentServerPath,
findFreePort,
@@ -710,6 +711,20 @@ describe("validateLocalAgentServerPath", () => {
});
});
+describe("getViteSessionApiKey", () => {
+ it("only injects the key on loopback listeners", () => {
+ const config = { sessionApiKey: "local-secret" };
+
+ expect(getViteSessionApiKey(config, {})).toBe("local-secret");
+ expect(getViteSessionApiKey(config, { VITE_BIND_HOST: "127.0.0.1" })).toBe(
+ "local-secret",
+ );
+ expect(getViteSessionApiKey(config, { VITE_BIND_HOST: "0.0.0.0" })).toBe(
+ "",
+ );
+ });
+});
+
describe("buildSafeDevConfig", () => {
let keyTmp: string | null = null;
diff --git a/__tests__/scripts/dev-static.test.ts b/__tests__/scripts/dev-static.test.ts
index c1000ed404..2968bfbcff 100644
--- a/__tests__/scripts/dev-static.test.ts
+++ b/__tests__/scripts/dev-static.test.ts
@@ -3,7 +3,18 @@ import { describe, expect, it } from "vitest";
import {
buildAutomationBackendEnv,
buildLocalServiceRouteArgs,
+ parseArgs,
} from "../../scripts/dev-static.mjs";
+import { buildFrontendEnv } from "../../scripts/static-build.mjs";
+
+describe("dev-static CLI", () => {
+ it.each([
+ [["--host", "0.0.0.0"], "0.0.0.0"],
+ [["-H", "::"], "::"],
+ ])("parses an explicit bind host", (argv, expected) => {
+ expect(parseArgs(argv).host).toBe(expected);
+ });
+});
describe("dev-static", () => {
it("uses the same session key for both agent-server and automation backend auth", () => {
@@ -28,6 +39,16 @@ describe("dev-static", () => {
});
});
+ it("keeps reusable frontend builds free of session credentials", () => {
+ const env = buildFrontendEnv(
+ { viteWorkingDir: "/tmp/workspace" },
+ { VITE_SESSION_API_KEY: "inherited-secret" },
+ );
+
+ expect(env.VITE_SESSION_API_KEY).toBe("");
+ expect(env.VITE_WORKING_DIR).toBe("/tmp/workspace");
+ });
+
it("points every local proxy route at the IPv4 loopback", () => {
// Both backends bind to `0.0.0.0`, which only accepts IPv4, so a
// `localhost` target strands the proxy on ::1 on Windows.
diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.ts
index d8b5cc93ee..63ec9a355b 100644
--- a/__tests__/scripts/dev-with-automation.test.ts
+++ b/__tests__/scripts/dev-with-automation.test.ts
@@ -22,6 +22,7 @@ import {
buildConfig,
buildRouteArgs,
buildViteBackendEnv,
+ buildViteFrontendEnv,
getAgentServerBaseUrl,
getFrontendBackend,
getLocalServiceRoutes,
@@ -601,6 +602,66 @@ describe("stack mode routing", () => {
});
});
+ it("binds Vite to loopback and injects the key by default", async () => {
+ const config = await buildConfig({}, envWithIsolatedKeyPath());
+
+ expect(buildViteFrontendEnv(config)).toMatchObject({
+ VITE_BIND_HOST: "127.0.0.1",
+ VITE_SESSION_API_KEY: config.sessionApiKey,
+ });
+ expect(buildViteFrontendEnv(config)).not.toHaveProperty(
+ "VITE_AUTH_REQUIRED",
+ );
+ });
+
+ it("keeps the session key out of an off-loopback Vite origin", async () => {
+ const config = await buildConfig(
+ { host: "0.0.0.0" },
+ envWithIsolatedKeyPath(),
+ );
+
+ const viteEnv = buildViteFrontendEnv(config);
+ expect(viteEnv.VITE_BIND_HOST).toBe("0.0.0.0");
+ expect(viteEnv).not.toHaveProperty("VITE_SESSION_API_KEY");
+ expect(viteEnv.VITE_AUTH_REQUIRED).toBe("true");
+ });
+
+ it("makes the key-free ingress reachable to Docker conversations", async () => {
+ const config = await buildConfig(
+ {},
+ envWithIsolatedKeyPath({ OH_CONVERSATION_RUNTIME: "docker" }),
+ );
+
+ expect(config.bindHost).toBe("0.0.0.0");
+ expect(buildViteFrontendEnv(config)).not.toHaveProperty(
+ "VITE_SESSION_API_KEY",
+ );
+ });
+
+ it("honors an explicit loopback override in Docker conversation mode", async () => {
+ const config = await buildConfig(
+ {},
+ envWithIsolatedKeyPath({
+ OH_CONVERSATION_RUNTIME: "docker",
+ OH_BIND_HOST: "127.0.0.1",
+ }),
+ );
+
+ expect(config.bindHost).toBe("127.0.0.1");
+ });
+
+ it("keeps the session key out of public-mode Vite on loopback", async () => {
+ const config = await buildConfig(
+ { public: true },
+ envWithIsolatedKeyPath({ LOCAL_BACKEND_API_KEY: "public-key" }),
+ );
+
+ const viteEnv = buildViteFrontendEnv(config);
+ expect(viteEnv.VITE_BIND_HOST).toBe("127.0.0.1");
+ expect(viteEnv).not.toHaveProperty("VITE_SESSION_API_KEY");
+ expect(viteEnv.VITE_AUTH_REQUIRED).toBe("true");
+ });
+
it("allows frontend-only Vite to target an explicit backend URL", async () => {
const config = await buildConfig(
{ frontendOnly: true },
diff --git a/__tests__/scripts/docker-session-key-policy.test.ts b/__tests__/scripts/docker-session-key-policy.test.ts
new file mode 100644
index 0000000000..4398e1f03f
--- /dev/null
+++ b/__tests__/scripts/docker-session-key-policy.test.ts
@@ -0,0 +1,68 @@
+// @vitest-environment node
+
+import { spawnSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const repoRoot = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ "../..",
+);
+const entrypoint = readFileSync(
+ path.join(repoRoot, "docker/entrypoint.sh"),
+ "utf-8",
+);
+const blockStart = "# >>> docker-session-key-policy";
+const blockEnd = "# <<< docker-session-key-policy";
+
+function sessionKeyPolicyBlock(): string {
+ const start = entrypoint.indexOf(blockStart);
+ const end = entrypoint.indexOf(blockEnd);
+ if (start === -1 || end === -1) {
+ throw new Error("Docker session-key policy markers are missing");
+ }
+ return entrypoint.slice(start, end);
+}
+
+function resolveStaticServerArgs(allowLanSessionKey: string | undefined): {
+ args: string[];
+ stderr: string;
+} {
+ const script = [
+ "set -uo pipefail",
+ "PORT=8000",
+ "log() { printf '%s\\n' \"$*\" >&2; }",
+ sessionKeyPolicyBlock(),
+ "printf '%s\\n' \"${STATIC_SERVER_SESSION_KEY_ARGS[@]}\"",
+ ].join("\n");
+ const env: Record<string, string> = { PATH: process.env.PATH ?? "" };
+ if (allowLanSessionKey !== undefined) {
+ env.AGENT_CANVAS_ALLOW_LAN_SESSION_KEY = allowLanSessionKey;
+ }
+ const result = spawnSync("bash", ["-c", script], {
+ encoding: "utf-8",
+ env,
+ });
+ expect(result.status).toBe(0);
+ return {
+ args: result.stdout.trim() ? result.stdout.trim().split("\n") : [],
+ stderr: result.stderr,
+ };
+}
+
+describe("Docker session-key injection policy", () => {
+ it("does not inject the key by default", () => {
+ expect(resolveStaticServerArgs(undefined).args).toEqual([]);
+ });
+
+ it("requires an explicit true value and warns when enabled", () => {
+ expect(resolveStaticServerArgs("1").args).toEqual([]);
+
+ const enabled = resolveStaticServerArgs("true");
+ expect(enabled.args).toEqual(["--allow-lan-session-key"]);
+ expect(enabled.stderr).toContain("WARNING");
+ expect(enabled.stderr).toContain("host loopback only");
+ });
+});
diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.ts
index 50d29e553a..f8e9d001a9 100644
--- a/__tests__/scripts/static-server.test.ts
+++ b/__tests__/scripts/static-server.test.ts
@@ -111,6 +111,10 @@ describe("static-server.mjs", () => {
}
describe("parseArgs", () => {
+ it("defaults host to IPv4 loopback", () => {
+ expect(parseArgs([]).host).toBe("127.0.0.1");
+ });
+
it("defaults sessionApiKey to null", () => {
const config = parseArgs([]);
expect(config.sessionApiKey).toBeNull();
@@ -207,7 +211,9 @@ describe("static-server.mjs", () => {
const result = serializeForInlineScript(input);
expect(result).not.toContain("<");
expect(result).not.toContain(">");
- expect(result).toBe('"\\u003c/script\\u003e\\u003cscript\\u003ealert(1)\\u003c/script\\u003e"');
+ expect(result).toBe(
+ '"\\u003c/script\\u003e\\u003cscript\\u003ealert(1)\\u003c/script\\u003e"',
+ );
});
it("escapes line and paragraph separators U+2028 and U+2029", () => {
@@ -723,6 +729,68 @@ describe("static-server.mjs", () => {
expect(response.headers.get("cache-control")).toBe("no-cache");
});
+ it("does not inject the session key when bound off-loopback", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));
+ tempDirs.push(buildDir);
+ writeFileSync(
+ path.join(buildDir, "index.html"),
+ "<html><head></head><body>app</body></html>",
+ );
+
+ try {
+ const server = await startStaticServer({
+ port: 0,
+ host: "0.0.0.0",
+ dir: buildDir,
+ routes: {},
+ sessionApiKey: "lan-secret",
+ });
+ servers.push(server);
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ throw new Error("Static server did not bind to a TCP port");
+ }
+ const origin = `http://127.0.0.1:${address.port}`;
+ const body = await (await fetch(`${origin}/`)).text();
+
+ expect(body).not.toContain("lan-secret");
+ expect(body).not.toContain("__AGENT_CANVAS_SESSION_API_KEY__");
+ expect(body).toContain("__AGENT_CANVAS_AUTH_REQUIRED__");
+ expect(warn).toHaveBeenCalled();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("injects the session key off-loopback only with --allow-lan-session-key", async () => {
+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));
+ tempDirs.push(buildDir);
+ writeFileSync(
+ path.join(buildDir, "index.html"),
+ "<html><head></head><body>app</body></html>",
+ );
+
+ const server = await startStaticServer({
+ port: 0,
+ host: "0.0.0.0",
+ dir: buildDir,
+ routes: {},
+ sessionApiKey: "container-key",
+ allowLanSessionKey: true,
+ });
+ servers.push(server);
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ throw new Error("Static server did not bind to a TCP port");
+ }
+ const origin = `http://127.0.0.1:${address.port}`;
+ const body = await (await fetch(`${origin}/`)).text();
+
+ expect(body).toContain("container-key");
+ expect(body).toContain("__AGENT_CANVAS_SESSION_API_KEY__");
+ });
+
it("escapes HTML special characters and script closing tags in injected values", async () => {
const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));
tempDirs.push(buildDir);
diff --git a/bin/agent-canvas.mjs b/bin/agent-canvas.mjs
index 06732aad26..f399534872 100755
--- a/bin/agent-canvas.mjs
+++ b/bin/agent-canvas.mjs
@@ -75,6 +75,9 @@ AUTH MODES:
OPTIONS:
-p, --port <port> Ingress port (default: 8000)
+ -H, --host <host> Bind address (default: 127.0.0.1). Use 0.0.0.0
+ or :: to listen on all interfaces; the session
+ key is then not injected into HTML.
--public Enable public mode (see above)
--frontend-only Start only the static frontend behind ingress
--backend-only Start only agent-server + automation behind ingress
@@ -86,6 +89,7 @@ ENVIRONMENT VARIABLES:
LOCAL_BACKEND_API_KEY API key for the server. Required in --public
mode; optional otherwise (auto-generated if
omitted, persisted across restarts).
+ OH_BIND_HOST Bind address for ingress/static (default: 127.0.0.1)
OH_SECRET_KEY Secret key for encrypting settings
OH_AGENT_SERVER_GIT_REF Git ref for agent-server
OH_AGENT_SERVER_LOCAL_PATH Path to local SDK checkout (for development)
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 9e36e44f62..07c9a2eeea 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -142,6 +142,7 @@ COPY --from=frontend-build /build/build /opt/agent-canvas/frontend
# Copy the static-server scripts and their production runtime deps.
COPY scripts/static-server.mjs /opt/agent-canvas/static-server.mjs
+COPY scripts/bind-host.mjs /opt/agent-canvas/bind-host.mjs
COPY scripts/proxy-utils.mjs /opt/agent-canvas/proxy-utils.mjs
COPY --from=frontend-build /build/node_modules/httpxy /opt/agent-canvas/node_modules/httpxy
COPY --from=frontend-build /build/node_modules/sirv /opt/agent-canvas/node_modules/sirv
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index b96fa4d0fc..d0beb09fe7 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -32,6 +32,9 @@
# the proxy route.
# PUBLIC_MODE_PORT – If set, starts a second static server on this port
# with --auth-required (no session key injected)
+# AGENT_CANVAS_ALLOW_LAN_SESSION_KEY – Set to true only when the published
+# host port is restricted to loopback and you accept
+# embedding the session key in the served HTML
# OH_SECRET_KEY – Secret key for settings encryption (auto-generated
# and persisted if not provided)
# OPENHANDS_AUTOMATION_API_KEY – Override automation backend auth key
@@ -389,10 +392,22 @@ RUNTIME_SERVICES_INFO="$(node /opt/agent-canvas/runtime-services-info.mjs \
--agent-server-url "$AGENT_SERVER_URL" \
--automation-url "$AUTOMATION_BASE_URL")"
-# EFFECTIVE_SESSION_KEY is set above from LOCAL_BACKEND_API_KEY or the persisted api-key.txt
+# EFFECTIVE_SESSION_KEY is set above from LOCAL_BACKEND_API_KEY or the persisted api-key.txt.
+# --host :: is required so Docker published ports can reach the process. Because
+# the container cannot tell whether the host published that port on loopback or
+# every interface, session-key injection stays disabled unless the operator
+# explicitly opts in.
+# >>> docker-session-key-policy: extracted by the regression test below.
+STATIC_SERVER_SESSION_KEY_ARGS=()
+if [ "${AGENT_CANVAS_ALLOW_LAN_SESSION_KEY:-false}" = "true" ]; then
+ log "WARNING: Embedding the session API key in frontend HTML; publish port $PORT on host loopback only."
+ STATIC_SERVER_SESSION_KEY_ARGS+=(--allow-lan-session-key)
+fi
+# <<< docker-session-key-policy
node /opt/agent-canvas/static-server.mjs \
--port "$PORT" \
--host :: \
+ "${STATIC_SERVER_SESSION_KEY_ARGS[@]}" \
--dir /opt/agent-canvas/frontend \
--base-path "$AGENT_CANVAS_BASE_PATH" \
--session-api-key "$EFFECTIVE_SESSION_KEY" \
diff --git a/package.json b/package.json
index ea42f75a5f..5e8bdb706f 100644
--- a/package.json
+++ b/package.json
@@ -86,6 +86,7 @@
"test:e2e:live": "node --env-file-if-exists=.env tests/e2e/live/scripts/run-live-e2e.mjs",
"test:e2e:mock-llm": "playwright test --config=playwright.mock-llm.config.ts",
"test:e2e:mock-llm:docker": "playwright test --config=playwright.mock-llm-docker.config.ts",
+ "test:e2e:bind-policy": "playwright test --config=playwright.bind-policy.config.ts",
"test:coverage": "npm run make-i18n && vitest run --coverage",
"test:mutation": "npm run make-i18n && stryker run",
"test:mutation:diff": "npm run make-i18n && node scripts/stryker-diff.mjs",
diff --git a/playwright.bind-policy.config.ts b/playwright.bind-policy.config.ts
new file mode 100644
index 0000000000..d1973583dc
--- /dev/null
+++ b/playwright.bind-policy.config.ts
@@ -0,0 +1,32 @@
+import { defineConfig, devices } from "@playwright/test";
+
+/**
+ * Bind-policy E2E: static-server session-key injection + optional live
+ * ingress at http://127.0.0.1:8000 (set OH_INGRESS_URL to override).
+ *
+ * Does not start Vite. Chromium only.
+ *
+ * npx playwright test --config=playwright.bind-policy.config.ts
+ */
+export default defineConfig({
+ testDir: "./tests/e2e/bind-policy",
+ testMatch: /.*\.spec\.ts/,
+ fullyParallel: false,
+ forbidOnly: !!process.env.CI,
+ retries: 0,
+ workers: 1,
+ timeout: 60_000,
+ reporter: [["list"]],
+ use: {
+ ...devices["Desktop Chrome"],
+ ignoreHTTPSErrors: true,
+ trace: "off",
+ video: "off",
+ },
+ projects: [
+ {
+ name: "chromium",
+ use: { ...devices["Desktop Chrome"] },
+ },
+ ],
+});
diff --git a/playwright.config.ts b/playwright.config.ts
index 129af0a55f..b1dfb82ea7 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -13,7 +13,7 @@ import { defineConfig, devices } from "@playwright/test";
*/
export default defineConfig({
testDir: "./tests/e2e",
- testIgnore: ["**/e2e/live/**", "**/e2e/mock-llm/**"],
+ testIgnore: ["**/e2e/live/**", "**/e2e/mock-llm/**", "**/e2e/bind-policy/**"],
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
diff --git a/playwright.mock-llm-docker.config.ts b/playwright.mock-llm-docker.config.ts
index d0b9791612..8e80c7760a 100644
--- a/playwright.mock-llm-docker.config.ts
+++ b/playwright.mock-llm-docker.config.ts
@@ -77,6 +77,7 @@ const MOCK_LLM_PYTHON = process.env.MOCK_LLM_PYTHON ?? "python3";
process.env.MOCK_LLM_BACKEND_URL = `http://localhost:${INGRESS_PORT}`;
process.env.MOCK_LLM_PORT = MOCK_LLM_PORT;
process.env.MOCK_LLM_PUBLIC_MODE_URL = `http://localhost:${PUBLIC_MODE_PORT}`;
+process.env.MOCK_LLM_DOCKER_MODE = "true";
process.env.VITE_SESSION_API_KEY = sessionApiKey;
// MOCK_LLM_AGENT_URL β€” the URL the agent-server inside Docker uses to
@@ -150,10 +151,7 @@ export default defineConfig({
globalTimeout: process.env.CI ? ciGlobalTimeoutMs : 0, // 20 min hard cap in CI
reporter: [
["line"],
- [
- "json",
- { outputFile: "test-results-mock-llm-docker/results.json" },
- ],
+ ["json", { outputFile: "test-results-mock-llm-docker/results.json" }],
[
"html",
{
diff --git a/playwright.mock-llm.config.ts b/playwright.mock-llm.config.ts
index cc1e499ef8..008cf48bba 100644
--- a/playwright.mock-llm.config.ts
+++ b/playwright.mock-llm.config.ts
@@ -53,7 +53,7 @@ const STATE_DIR = resolve(".tmp/mock-llm-state");
const AUTOMATION_DB_DIR = join(dirname(STATE_DIR), "automation");
// ── URLs ───────────────────────────────────────────────────────────────
-const INGRESS_URL = `http://localhost:${INGRESS_PORT}/`;
+const INGRESS_URL = `http://127.0.0.1:${INGRESS_PORT}/`;
const MOCK_LLM_URL = `http://127.0.0.1:${MOCK_LLM_PORT}`;
// Python binary for the mock server β€” defaults to "python3" but CI can
@@ -63,9 +63,9 @@ const MOCK_LLM_PYTHON = process.env.MOCK_LLM_PYTHON ?? "python3";
// Export for the test helpers β€” BACKEND_URL points to the ingress (API
// calls are proxied to the agent-server, so no direct backend port needed).
-process.env.MOCK_LLM_BACKEND_URL = `http://localhost:${INGRESS_PORT}`;
+process.env.MOCK_LLM_BACKEND_URL = `http://127.0.0.1:${INGRESS_PORT}`;
process.env.MOCK_LLM_PORT = MOCK_LLM_PORT;
-process.env.MOCK_LLM_PUBLIC_MODE_URL = `http://localhost:${PUBLIC_MODE_PORT}`;
+process.env.MOCK_LLM_PUBLIC_MODE_URL = `http://127.0.0.1:${PUBLIC_MODE_PORT}`;
function shellQuote(value: string) {
return `'${value.replaceAll("'", "'\\''")}'`;
@@ -161,7 +161,7 @@ export default defineConfig({
// GET /api/automation/v1 returns 200 (empty list) without auth
// because the dev automation backend does not enforce session-key
// auth on the list endpoint (confirmed in CI).
- url: `http://localhost:${INGRESS_PORT}/api/automation/v1`,
+ url: `http://127.0.0.1:${INGRESS_PORT}/api/automation/v1`,
timeout: 180_000, // allow extra time for build + agent-server + automation startup
reuseExistingServer: !process.env.CI,
// Without this, Playwright tears the webServer down with
@@ -184,13 +184,14 @@ export default defineConfig({
"exec node scripts/static-server.mjs",
"--dir build",
`--port ${PUBLIC_MODE_PORT}`,
+ "--host 127.0.0.1",
"--auth-required",
"--route /api/automation=http://localhost:18001",
"--route /api=http://localhost:18000",
"--route /server_info=http://localhost:18000",
"--route /sockets=http://localhost:18000",
].join(" "),
- url: `http://localhost:${PUBLIC_MODE_PORT}/`,
+ url: `http://127.0.0.1:${PUBLIC_MODE_PORT}/`,
timeout: 15_000,
reuseExistingServer: !process.env.CI,
},
diff --git a/scripts/bind-host.mjs b/scripts/bind-host.mjs
new file mode 100644
index 0000000000..0b1915265f
--- /dev/null
+++ b/scripts/bind-host.mjs
@@ -0,0 +1,78 @@
+/**
+ * Bind-address helpers for the local Agent Canvas stack.
+ *
+ * Default is IPv4 loopback. Binding `::` / `0.0.0.0` exposes the UI (and any
+ * session key injected into index.html) to every peer on the network.
+ */
+
+export const DEFAULT_BIND_HOST = "127.0.0.1";
+
+const STATIC_LOOPBACK_HOSTS = new Set(["::1", "localhost"]);
+const IPV4_LOOPBACK_RE = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
+
+export function isLoopbackBind(host) {
+ if (host == null || host === "") return false;
+ const normalized = String(host)
+ .trim()
+ .replace(/^\[|\]$/g, "")
+ .toLowerCase();
+ return STATIC_LOOPBACK_HOSTS.has(normalized) || IPV4_LOOPBACK_RE.test(normalized);
+}
+
+/**
+ * Resolve the listen address.
+ * CLI `--host` wins, then `OH_BIND_HOST`, then loopback.
+ */
+export function resolveBindHost({ flag, env } = {}) {
+ const fromFlag =
+ flag != null && String(flag).trim() !== "" ? String(flag).trim() : null;
+ const fromEnv =
+ env != null && String(env).trim() !== "" ? String(env).trim() : null;
+ return fromFlag || fromEnv || DEFAULT_BIND_HOST;
+}
+
+export function bindHostArgs(host) {
+ return ["--host", host || DEFAULT_BIND_HOST];
+}
+
+/**
+ * Session keys must not be written into unauthenticated HTML when the
+ * listener is reachable off-loopback. Convert to public-mode (`authRequired`)
+ * unless the caller explicitly opts back in (container entrypoints).
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.host]
+ * @param {string | null} [opts.sessionApiKey]
+ * @param {boolean} [opts.authRequired]
+ * @param {boolean} [opts.allowLanSessionKey]
+ * @param {(msg: string) => void} [opts.warn]
+ */
+export function applySessionKeyPolicy(opts = {}) {
+ const {
+ host,
+ sessionApiKey = null,
+ authRequired = false,
+ allowLanSessionKey = false,
+ warn = console.warn,
+ } = opts;
+ const loopback = isLoopbackBind(host);
+ if (loopback || allowLanSessionKey || !sessionApiKey) {
+ return {
+ sessionApiKey: sessionApiKey || null,
+ authRequired: Boolean(authRequired),
+ strippedSessionKey: false,
+ };
+ }
+
+ warn(
+ `WARNING: bind host ${host} is not loopback; refusing to inject the session API key into HTML.\n` +
+ " The UI will use the API key entry screen (same as --public).\n" +
+ " Pass --host 127.0.0.1 (default) for local mode, or --allow-lan-session-key only if you accept LAN exposure.",
+ );
+
+ return {
+ sessionApiKey: null,
+ authRequired: true,
+ strippedSessionKey: true,
+ };
+}
diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjs
index 3de19bf361..6dab2cdd1d 100644
--- a/scripts/dev-safe.mjs
+++ b/scripts/dev-safe.mjs
@@ -16,6 +16,7 @@ import process from "node:process";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath, pathToFileURL } from "node:url";
+import { applySessionKeyPolicy } from "./bind-host.mjs";
import {
getProcessTreeSpawnOptions,
isProcessRunning,
@@ -565,6 +566,15 @@ export function buildSafeDevConfig(cwd = process.cwd(), env = process.env) {
return buildConfigFromPorts({ backendPort, vscodePort }, cwd, env);
}
+export function getViteSessionApiKey(config, env = process.env) {
+ return (
+ applySessionKeyPolicy({
+ host: env.VITE_BIND_HOST || "127.0.0.1",
+ sessionApiKey: config.sessionApiKey,
+ }).sessionApiKey || ""
+ );
+}
+
/**
* Build safe dev configuration with dynamic port allocation.
*
@@ -1090,8 +1100,7 @@ async function main() {
VITE_BACKEND_HOST: config.backendHost,
VITE_BACKEND_BASE_URL: config.backendBaseUrl,
VITE_WORKING_DIR: config.workingDir,
- // Pass session API key so frontend can authenticate with agent-server
- VITE_SESSION_API_KEY: config.sessionApiKey,
+ VITE_SESSION_API_KEY: getViteSessionApiKey(config),
// This mode has no static server or ingress in front of Vite, so Vite's
// own proxy is the only thing that can serve the editor prefix on the
// frontend origin. The editor is a separate process on a port of its
diff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjs
index 80f5728a0e..cf9163a9d5 100644
--- a/scripts/dev-static.mjs
+++ b/scripts/dev-static.mjs
@@ -69,6 +69,7 @@ import {
getNoReferrerPrefixArgs,
getVSCodeAdvertiseArgs,
} from "./dev-with-automation.mjs";
+import { applySessionKeyPolicy, bindHostArgs } from "./bind-host.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const projectRoot = resolve(__dirname, "..");
@@ -117,6 +118,7 @@ export function parseArgs(argv = process.argv.slice(2)) {
automationRepo: null,
skipBuild: false,
verbose: false,
+ host: null,
};
for (let i = 0; i < argv.length; i++) {
@@ -125,6 +127,10 @@ export function parseArgs(argv = process.argv.slice(2)) {
case "--port":
config.port = parseInt(argv[++i], 10);
break;
+ case "-H":
+ case "--host":
+ config.host = argv[++i];
+ break;
case "--automation-ref":
config.automationGitRef = argv[++i];
break;
@@ -161,6 +167,7 @@ USAGE:
OPTIONS:
-p, --port <port> Ingress port (default: 8000)
+ -H, --host <host> Bind address for ingress/static (default: 127.0.0.1)
--automation-ref <ref> Git ref for automation backend (default: main)
--automation-repo <url> Git repo URL for automation
--skip-build Reuse existing build/ directory (faster restart)
@@ -426,14 +433,25 @@ function startStaticServer(config) {
join(config.canvasPath, "build"),
"--port",
String(config.vitePort),
+ ...bindHostArgs(config.bindHost),
...(process.env.VITE_BASE_PATH
? ["--base-path", process.env.VITE_BASE_PATH]
: []),
- // Inject the API key so the pre-built frontend can authenticate
- // to the agent-server without a baked-in VITE_SESSION_API_KEY.
- ...(config.sessionApiKey
- ? ["--session-api-key", config.sessionApiKey]
- : []),
+ ...(() => {
+ const policy = applySessionKeyPolicy({
+ host: config.bindHost,
+ sessionApiKey: config.sessionApiKey,
+ warn: (msg) => logService("static", msg, c.yellow),
+ });
+ const flags = [];
+ if (policy.sessionApiKey) {
+ flags.push("--session-api-key", policy.sessionApiKey);
+ }
+ if (policy.authRequired) {
+ flags.push("--auth-required");
+ }
+ return flags;
+ })(),
"--runtime-services-info",
runtimeServicesInfo,
...buildLocalServiceRouteArgs(config),
@@ -468,6 +486,7 @@ function startIngress(config) {
ingressScript,
"--port",
config.ingressPort.toString(),
+ ...bindHostArgs(config.bindHost),
"--runtime-services-info",
runtimeServicesInfo,
...buildLocalServiceRouteArgs(config),
diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjs
index 717dd540a6..d927eb02d5 100644
--- a/scripts/dev-with-automation.mjs
+++ b/scripts/dev-with-automation.mjs
@@ -71,6 +71,12 @@ import {
signalProcessTree,
} from "./dev-process-utils.mjs";
import { fileLog, stripAnsi } from "./logger.mjs";
+import {
+ applySessionKeyPolicy,
+ bindHostArgs,
+ isLoopbackBind,
+ resolveBindHost,
+} from "./bind-host.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const projectRoot = resolve(__dirname, "..");
@@ -176,6 +182,7 @@ function parseArgs() {
public: false,
frontendOnly: false,
backendOnly: false,
+ host: null,
};
for (let i = 0; i < args.length; i++) {
@@ -215,6 +222,10 @@ function parseArgs() {
case "--backend-only":
config.backendOnly = true;
break;
+ case "-H":
+ case "--host":
+ config.host = args[++i];
+ break;
case "-h":
case "--help":
showHelp();
@@ -237,6 +248,9 @@ USAGE:
OPTIONS:
-p, --port <port> Ingress port (default: 8000)
+ -H, --host <host> Bind address for ingress/static (default: 127.0.0.1).
+ Use 0.0.0.0 or :: to listen on all interfaces; the
+ session key will not be injected into HTML.
--automation-ref <ref> Git ref for automation (branch/tag/SHA)
--automation-repo <url> Git repo URL (default: ${DEFAULT_AUTOMATION_REPO})
--static Serve an existing production build instead of Vite
@@ -250,6 +264,7 @@ OPTIONS:
ENVIRONMENT VARIABLES:
PORT Alternative to --port
+ OH_BIND_HOST Alternative to --host (default: 127.0.0.1)
OH_AUTOMATION_GIT_REF Git ref for automation (overrides default version)
OH_AUTOMATION_VERSION Specific PyPI version for automation (default: ${DEFAULT_AUTOMATION_VERSION})
OH_AUTOMATION_LOCAL_PATH Absolute path to a local automation checkout (overridden only by --automation-git-ref)
@@ -476,6 +491,20 @@ async function buildConfig(args, env = process.env) {
);
}
+ const bindHost = resolveBindHost({
+ flag: args.host,
+ env:
+ env.OH_BIND_HOST ||
+ (env.OH_CONVERSATION_RUNTIME === "docker" ? "0.0.0.0" : undefined),
+ });
+ if (!isLoopbackBind(bindHost) && !isPublic) {
+ logService(
+ "auth",
+ `Bind host ${bindHost} is not loopback β€” session key will not be injected into HTML`,
+ c.yellow,
+ );
+ }
+
return {
// Ingress port (main entry point)
ingressPort: preferredIngressPort,
@@ -516,6 +545,7 @@ async function buildConfig(args, env = process.env) {
launchAutomation,
verbose: args.verbose,
+ bindHost,
};
}
@@ -1112,6 +1142,7 @@ function startIngress(config) {
ingressScript,
"--port",
config.ingressPort.toString(),
+ ...bindHostArgs(config.bindHost),
...(runtimeServicesInfo
? ["--runtime-services-info", runtimeServicesInfo]
: []),
@@ -1159,16 +1190,14 @@ export function getAgentHostAlias(env = process.env) {
: "localhost";
}
-function startVite(config) {
- logService("vite", `Starting on port ${config.vitePort}...`, c.magenta);
-
- const frontendCommand = buildNpmScriptCommand("dev:frontend");
-
+function buildViteFrontendEnv(config) {
+ /** @type {Record<string, string>} */
const viteEnv = {
// Full-stack mode points Vite at this launcher's ingress. Frontend-only
// mode uses the separately running backend ingress instead.
...buildViteBackendEnv(config),
VITE_FRONTEND_PORT: config.vitePort.toString(),
+ VITE_BIND_HOST: config.bindHost,
};
if (config.viteWorkingDir) {
viteEnv.VITE_WORKING_DIR = config.viteWorkingDir;
@@ -1191,15 +1220,34 @@ function startVite(config) {
viteEnv.VITE_VSCODE_TARGET = `http://127.0.0.1:${config.vscodePort}`;
}
- // In local mode, bake the session key into the frontend so the user
- // never has to paste it. In public mode, omit the key and set
- // VITE_AUTH_REQUIRED so the frontend shows the API key entry screen
- // immediately (no network round-trip needed).
- if (config.launchAgentServer && config.isPublic) {
+ // The Vite origin is directly reachable on its own port, so it must use the
+ // same bind/key policy as ingress and the static server. Local loopback mode
+ // keeps transparent auth; public or off-loopback mode serves no credential
+ // and shows the API-key entry screen.
+ const policy = applySessionKeyPolicy({
+ host: config.bindHost,
+ sessionApiKey:
+ config.launchAgentServer && !config.isPublic
+ ? config.sessionApiKey
+ : null,
+ authRequired: Boolean(config.launchAgentServer && config.isPublic),
+ warn: (msg) => logService("vite", msg, c.yellow),
+ });
+ if (policy.authRequired) {
viteEnv.VITE_AUTH_REQUIRED = "true";
- } else if (config.launchAgentServer) {
- viteEnv.VITE_SESSION_API_KEY = config.sessionApiKey;
}
+ if (policy.sessionApiKey) {
+ viteEnv.VITE_SESSION_API_KEY = policy.sessionApiKey;
+ }
+
+ return viteEnv;
+}
+
+function startVite(config) {
+ logService("vite", `Starting on port ${config.vitePort}...`, c.magenta);
+
+ const frontendCommand = buildNpmScriptCommand("dev:frontend");
+ const viteEnv = buildViteFrontendEnv(config);
spawnService("vite", frontendCommand.command, frontendCommand.args, {
cwd: config.canvasPath,
@@ -1636,18 +1684,32 @@ function startStaticFrontend(config, staticDir) {
staticDir,
"--port",
String(config.vitePort),
+ ...bindHostArgs(config.bindHost),
...(process.env.VITE_BASE_PATH
? ["--base-path", process.env.VITE_BASE_PATH]
: []),
- // In local mode, inject the API key so the pre-built frontend can
- // authenticate transparently. In public mode, pass --auth-required
- // so the frontend shows the API key entry screen instead.
- ...(config.launchAgentServer && !config.isPublic && config.sessionApiKey
- ? ["--session-api-key", config.sessionApiKey]
- : []),
- ...(config.launchAgentServer && config.isPublic
- ? ["--auth-required"]
- : []),
+ // In local mode on loopback, inject the API key so the pre-built
+ // frontend can authenticate transparently. Off-loopback binds (and
+ // public mode) use the API key entry screen instead.
+ ...(() => {
+ const policy = applySessionKeyPolicy({
+ host: config.bindHost,
+ sessionApiKey:
+ config.launchAgentServer && !config.isPublic
+ ? config.sessionApiKey
+ : null,
+ authRequired: Boolean(config.launchAgentServer && config.isPublic),
+ warn: (msg) => logService("static", msg, c.yellow),
+ });
+ const flags = [];
+ if (policy.sessionApiKey) {
+ flags.push("--session-api-key", policy.sessionApiKey);
+ }
+ if (policy.authRequired) {
+ flags.push("--auth-required");
+ }
+ return flags;
+ })(),
// Inject runtime-services info so the agent knows what's reachable.
...(runtimeServicesInfo
? ["--runtime-services-info", runtimeServicesInfo]
@@ -1681,6 +1743,7 @@ export {
buildConfig,
buildRouteArgs,
buildViteBackendEnv,
+ buildViteFrontendEnv,
getAgentServerBaseUrl,
getFrontendBackend,
getLocalServiceRoutes,
diff --git a/scripts/ingress.mjs b/scripts/ingress.mjs
index 1cf9a6c6d6..0924c5f581 100644
--- a/scripts/ingress.mjs
+++ b/scripts/ingress.mjs
@@ -25,6 +25,7 @@ import { createServer } from "node:http";
import process from "node:process";
import { pathToFileURL } from "node:url";
+import { DEFAULT_BIND_HOST, resolveBindHost } from "./bind-host.mjs";
import {
createProxyHandlers,
createRouter,
@@ -42,6 +43,7 @@ function parseArgs() {
const args = process.argv.slice(2);
const config = {
port: 8000,
+ host: null,
routes: {},
defaultBackend: null,
noReferrerPrefixes: [],
@@ -54,6 +56,10 @@ function parseArgs() {
case "--port":
config.port = parseInt(args[++i], 10);
break;
+ case "-H":
+ case "--host":
+ config.host = args[++i];
+ break;
case "-r":
case "--route":
// Format: "/path=http://host:port"
@@ -98,6 +104,7 @@ USAGE:
OPTIONS:
-p, --port <port> Port to listen on (default: 8000)
+ -H, --host <host> Address to bind (default: 127.0.0.1 loopback)
-r, --route <path=url> Add a route (can be repeated)
-d, --default <url> Default backend for unmatched routes
--no-referrer-prefix <p> Send "Referrer-Policy: no-referrer" on proxied
@@ -108,6 +115,7 @@ OPTIONS:
ENVIRONMENT VARIABLES:
INGRESS_PORT Port to listen on
+ INGRESS_HOST Bind address (default: 127.0.0.1)
INGRESS_ROUTES JSON object: {"path": "url", ...}
INGRESS_DEFAULT Default backend URL
INGRESS_RUNTIME_SERVICES_INFO
@@ -149,6 +157,7 @@ function buildConfig(args, env = process.env) {
return {
port: args.port || parseInt(env.INGRESS_PORT, 10) || 8000,
+ host: resolveBindHost({ flag: args.host, env: env.INGRESS_HOST }),
routes,
defaultBackend: args.defaultBackend || env.INGRESS_DEFAULT || null,
noReferrerPrefixes: args.noReferrerPrefixes ?? [],
@@ -223,7 +232,7 @@ export function startIngress(config) {
});
server.on("close", uninstallDiagnostics);
- server.listen(config.port, () => {
+ server.listen(config.port, config.host || DEFAULT_BIND_HOST, () => {
console.log("");
console.log(
"╔═══════════════════════════════════════════════════════════════╗",
diff --git a/scripts/static-build.mjs b/scripts/static-build.mjs
index 23bb529a85..58a9cb579d 100644
--- a/scripts/static-build.mjs
+++ b/scripts/static-build.mjs
@@ -11,6 +11,16 @@ import {
} from "./dev-with-automation.mjs";
import { buildNpmScriptCommand } from "./dev-safe.mjs";
+export function buildFrontendEnv(config, env = process.env) {
+ return {
+ ...env,
+ VITE_SESSION_API_KEY: "",
+ ...(config.viteWorkingDir
+ ? { VITE_WORKING_DIR: config.viteWorkingDir }
+ : {}),
+ };
+}
+
export function buildFrontend(config, args = {}) {
const buildDir = join(config.canvasPath, "build");
@@ -39,18 +49,9 @@ export function buildFrontend(config, args = {}) {
);
const cmd = buildNpmScriptCommand("build:app");
- const buildEnv = {
- ...process.env,
- // Bake the session API key β€” used by the frontend for both agent-server
- // and automation auth via the `X-Session-API-Key` header.
- VITE_SESSION_API_KEY: config.sessionApiKey,
- // Intentionally do NOT set VITE_BACKEND_BASE_URL: leaving it unset makes
- // the runtime fall back to window.location.origin, which keeps the build
- // portable across localhost, LAN hosts, and tunnels such as ngrok.
- };
- if (config.viteWorkingDir) {
- buildEnv.VITE_WORKING_DIR = config.viteWorkingDir;
- }
+ // The static server injects runtime configuration after applying the
+ // bind-host policy, so the reusable build itself must remain key-free.
+ const buildEnv = buildFrontendEnv(config);
const result = spawnSync(cmd.command, cmd.args, {
cwd: config.canvasPath,
diff --git a/scripts/static-server.mjs b/scripts/static-server.mjs
index 5f507b6756..289047c790 100644
--- a/scripts/static-server.mjs
+++ b/scripts/static-server.mjs
@@ -34,6 +34,7 @@ import process from "node:process";
import { pathToFileURL } from "node:url";
import sirv from "sirv";
+import { applySessionKeyPolicy, DEFAULT_BIND_HOST } from "./bind-host.mjs";
import {
createProxyHandlers,
createRouter,
@@ -86,13 +87,14 @@ function isEnvFlagEnabled(value) {
export function parseArgs(argv = process.argv.slice(2), env = process.env) {
const config = {
port: 3001,
- host: "::",
+ host: DEFAULT_BIND_HOST,
dir: "build",
routes: {},
rejectPrefixes: [],
noReferrerPrefixes: [],
sessionApiKey: null,
authRequired: false,
+ allowLanSessionKey: false,
runtimeServicesInfo: null,
lockToCloud: null,
basePath: "/",
@@ -160,6 +162,9 @@ export function parseArgs(argv = process.argv.slice(2), env = process.env) {
case "--disable-telemetry":
config.disableTelemetry = true;
break;
+ case "--allow-lan-session-key":
+ config.allowLanSessionKey = true;
+ break;
case "--reject-prefix": {
const prefix = argv[++i];
if (!prefix || !prefix.startsWith("/")) {
@@ -236,7 +241,10 @@ USAGE:
OPTIONS:
-p, --port <port> Port to bind (default: 3001)
- -H, --host <host> Hostname to bind (default: :: dual-stack)
+ -H, --host <host> Hostname to bind (default: 127.0.0.1 loopback).
+ Use 0.0.0.0 or :: to expose on the LAN; the
+ session key is then not injected unless you also
+ pass --allow-lan-session-key.
-d, --dir <dir> Directory to serve (default: build)
-r, --route <prefix=url> Proxy <prefix> (and subpaths) to <url>;
may be repeated. WebSockets supported.
@@ -246,6 +254,8 @@ OPTIONS:
--auth-required Inject authRequired flag into index.html so the
pre-built frontend shows the API key entry screen
(public mode) without VITE_AUTH_REQUIRED baked in.
+ --allow-lan-session-key Permit --session-api-key when --host is not
+ loopback (Docker/container entrypoints only).
--runtime-services-info <json>
Inject a JSON description of the local runtime
services into index.html so the pre-built
@@ -345,15 +355,6 @@ ROUTING:
* `isDoNotTrackEnabled()` in `#/services/telemetry`. Enabled by
* AGENT_CANVAS_DISABLE_TELEMETRY=1 or the --disable-telemetry flag.
*/
-
-/**
- * Serialize a value into a safe JavaScript literal for inclusion in an inline <script> tag.
- * Escapes characters that could terminate or manipulate the surrounding HTML context:
- * - '<' -> \u003c (prevents </script> breakout)
- * - '>' -> \u003e (prevents premature tag closing in some contexts)
- * - '\u2028' -> \u2028 (prevents syntax errors in JS parsers)
- * - '\u2029' -> \u2029 (prevents syntax errors in JS parsers)
- */
export function serializeForInlineScript(value) {
return JSON.stringify(value)
.replace(/</g, "\\u003c")
@@ -400,7 +401,7 @@ function makeConfigInjectionScript(
if (runtimeServicesInfo) {
// Stored as the raw JSON string so the browser-side parser
// (parseRuntimeServicesInfo) can JSON.parse it exactly like the
- // VITE_RUNTIME_SERVICES_INFO env var. serializeForInlineScript produces a safe JS
+ // VITE_RUNTIME_SERVICES_INFO env var. JSON.stringify produces a safe JS
// string literal for the inline <script>.
parts.push(
`window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__=${serializeForInlineScript(runtimeServicesInfo)};`,
@@ -657,9 +658,15 @@ export function startStaticServer(config) {
const route = createRouter(config.routes);
const proxy = createProxyHandlers({ label: `static:${config.port}` });
const dirAbs = resolve(config.dir);
- const injectionOpts = {
+ const policy = applySessionKeyPolicy({
+ host: config.host,
sessionApiKey: config.sessionApiKey || null,
authRequired: config.authRequired || false,
+ allowLanSessionKey: config.allowLanSessionKey || false,
+ });
+ const injectionOpts = {
+ sessionApiKey: policy.sessionApiKey,
+ authRequired: policy.authRequired,
runtimeServicesInfo: config.runtimeServicesInfo || null,
lockToCloud: config.lockToCloud || null,
basePath: normalizeBasePath(config.basePath),
diff --git a/src/root.tsx b/src/root.tsx
index 4ad349dcd4..72e0075489 100644
--- a/src/root.tsx
+++ b/src/root.tsx
@@ -242,10 +242,15 @@ export default function App() {
// reload the baked key is still null, but the registry has the key.
// So: skip the instant gate when a registered backend already carries
// an API key β€” let the normal /server_info probe validate it instead.
+ const { active } = useActiveBackendContext();
const bakedKeyMissing = isAuthRequiredAndMissing();
const hasRegisteredKey = Boolean(getEffectiveLocalBackend()?.apiKey);
- const authMissing = bakedKeyMissing && !hasRegisteredKey;
- const { active } = useActiveBackendContext();
+ // When the active backend is cloud, local session-key auth is irrelevant β€”
+ // the cloud backend uses its own bearer token. Skip the API-key entry screen
+ // in that case so Docker/public mode doesn't block cloud-only sessions.
+ const isActiveCloudBackend = active.backend.kind === "cloud";
+ const authMissing =
+ bakedKeyMissing && !hasRegisteredKey && !isActiveCloudBackend;
const queryClient = useQueryClient();
// In locked-to-Cloud mode the only valid backend is a Cloud backend whose
// host matches the configured locked Cloud host. A missing backend, a stale
diff --git a/tests/e2e/bind-policy/loopback-bind.spec.ts b/tests/e2e/bind-policy/loopback-bind.spec.ts
new file mode 100644
index 0000000000..acf87978ff
--- /dev/null
+++ b/tests/e2e/bind-policy/loopback-bind.spec.ts
@@ -0,0 +1,162 @@
+import { expect, test } from "@playwright/test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import type { Server } from "node:http";
+import net from "node:net";
+import { networkInterfaces, tmpdir } from "node:os";
+import path from "node:path";
+
+import { startStaticServer } from "../../../scripts/static-server.mjs";
+
+const ASSET_DIR = path.join(process.cwd(), ".github", "pr-assets");
+
+function originOf(server: Server): string {
+ const address = server.address();
+ if (!address || typeof address === "string") {
+ throw new Error("Static server did not bind to a TCP port");
+ }
+ return `http://127.0.0.1:${address.port}`;
+}
+
+function closeServer(server: Server): Promise<void> {
+ return new Promise((resolve) => {
+ server.close(() => resolve());
+ });
+}
+
+function firstLanIpv4(): string | null {
+ for (const addrs of Object.values(networkInterfaces())) {
+ for (const addr of addrs ?? []) {
+ if (addr.family === "IPv4" && !addr.internal) {
+ return addr.address;
+ }
+ }
+ }
+ return null;
+}
+
+function canConnect(host: string, port: number, ms = 1500): Promise<boolean> {
+ return new Promise((resolve) => {
+ const socket = net.connect({ host, port }, () => {
+ socket.destroy();
+ resolve(true);
+ });
+ socket.setTimeout(ms, () => {
+ socket.destroy();
+ resolve(false);
+ });
+ socket.on("error", () => resolve(false));
+ });
+}
+
+function escapeHtml(text: string): string {
+ return text
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;");
+}
+
+test("LAN bind strips the session key from GET / and writes a PNG", async ({
+ page,
+}) => {
+ const dir = mkdtempSync(path.join(tmpdir(), "oh-bind-"));
+ writeFileSync(
+ path.join(dir, "index.html"),
+ "<html><head></head><body>app</body></html>",
+ );
+ const servers: Server[] = [];
+
+ try {
+ const loopback = await startStaticServer({
+ port: 0,
+ host: "127.0.0.1",
+ dir,
+ routes: {},
+ sessionApiKey: "loopback-fixture-key",
+ });
+ servers.push(loopback);
+
+ const lan = await startStaticServer({
+ port: 0,
+ host: "0.0.0.0",
+ dir,
+ routes: {},
+ sessionApiKey: "lan-secret",
+ });
+ servers.push(lan);
+
+ const loopbackHtml = await (await fetch(`${originOf(loopback)}/`)).text();
+ const lanHtml = await (await fetch(`${originOf(lan)}/`)).text();
+
+ expect(loopbackHtml).toContain("__AGENT_CANVAS_SESSION_API_KEY__");
+ expect(loopbackHtml).toContain("loopback-fixture-key");
+ expect(lanHtml).not.toContain("lan-secret");
+ expect(lanHtml).not.toContain("__AGENT_CANVAS_SESSION_API_KEY__");
+ expect(lanHtml).toContain("__AGENT_CANVAS_AUTH_REQUIRED__");
+
+ mkdirSync(ASSET_DIR, { recursive: true });
+ await page.setContent(`<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <title>OpenHands #16879 bind policy</title>
+ <style>
+ body { margin: 0; background: #0d1117; color: #c9d1d9; font: 14px/1.45 ui-monospace, Consolas, monospace; padding: 24px; }
+ h1 { font-size: 16px; color: #8b949e; font-weight: 600; }
+ h2 { font-size: 15px; margin: 20px 0 8px; }
+ .before { color: #f85149; }
+ .after { color: #3fb950; }
+ pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 12px 16px; white-space: pre-wrap; word-break: break-all; }
+ </style>
+</head>
+<body>
+ <h1>OpenHands #16879 β€” GET / index.html (Playwright)</h1>
+ <h2 class="before">BEFORE pattern: host 0.0.0.0 + session key (would leak on LAN)</h2>
+ <pre>window.__AGENT_CANVAS_SESSION_API_KEY__="&lt;redacted&gt;"</pre>
+ <h2 class="after">AFTER this branch: host 0.0.0.0 without --allow-lan-session-key</h2>
+ <pre>${escapeHtml(lanHtml.replaceAll("lan-secret", "<redacted>"))}</pre>
+ <h2>LOOPBACK still injects for local use</h2>
+ <pre>${escapeHtml(loopbackHtml.replaceAll("loopback-fixture-key", "<redacted>"))}</pre>
+</body>
+</html>`);
+ await page.screenshot({
+ path: path.join(ASSET_DIR, "pr-16975-bind-policy.png"),
+ fullPage: true,
+ });
+ } finally {
+ await Promise.all(servers.map(closeServer));
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("live ingress is loopback-only when the stack is already up", async ({
+ page,
+}) => {
+ const ingressUrl = process.env.OH_INGRESS_URL ?? "http://127.0.0.1:8000/";
+ let reachable = false;
+ try {
+ const response = await fetch(ingressUrl, { signal: AbortSignal.timeout(3000) });
+ reachable = response.ok;
+ } catch {
+ reachable = false;
+ }
+ test.skip(!reachable, `Start the stack first: node scripts/dev-with-automation.mjs --port 8000`);
+
+ const loopbackOpen = await canConnect("127.0.0.1", 8000);
+ expect(loopbackOpen).toBe(true);
+
+ const lan = firstLanIpv4();
+ if (lan) {
+ const lanOpen = await canConnect(lan, 8000);
+ expect(lanOpen, `ingress should refuse ${lan}:8000`).toBe(false);
+ }
+
+ await page.goto(ingressUrl, { waitUntil: "domcontentloaded" });
+ await expect(page.getByRole("heading", { name: "Choose your agent" })).toBeVisible({
+ timeout: 30_000,
+ });
+ mkdirSync(ASSET_DIR, { recursive: true });
+ await page.screenshot({
+ path: path.join(ASSET_DIR, "pr-16975-agent-canvas-loopback.png"),
+ fullPage: false,
+ });
+});
diff --git a/tests/e2e/mock-llm/backends/mock-llm-auth-modes.spec.ts b/tests/e2e/mock-llm/backends/mock-llm-auth-modes.spec.ts
index 38eb85f85c..afd550d52c 100644
--- a/tests/e2e/mock-llm/backends/mock-llm-auth-modes.spec.ts
+++ b/tests/e2e/mock-llm/backends/mock-llm-auth-modes.spec.ts
@@ -99,13 +99,16 @@ test.describe("auth mode: fresh install with runtime-injected key", () => {
});
expect(settingsResp.ok()).toBe(true);
- // Sanity check: the runtime key landed on the window global.
+ // Docker's externally reachable listener must not expose the key. The
+ // loopback-only npm launcher injects it for the local first-run path.
const injected = await page.evaluate(
() =>
(window as unknown as Record<string, unknown>)
.__AGENT_CANVAS_SESSION_API_KEY__,
);
- expect(injected).toBe(SESSION_API_KEY);
+ expect(injected).toBe(
+ process.env.MOCK_LLM_DOCKER_MODE ? undefined : SESSION_API_KEY,
+ );
});
});
@@ -158,11 +161,9 @@ test.describe("auth mode: non-public key rotation", () => {
{ staleKey: STALE_KEY },
);
- // The runtime session key (injected by static-server) should be the
- // CORRECT key. `syncLauncherDefaultLocalBackend()` overwrites the
- // stale apiKey on the registry's default-local entry on boot, and the
- // static-server's localStorage write overwrites the legacy stored
- // sessionApiKey so the next read produces the live key.
+ // The loopback launcher replaces stale browser state with its injected
+ // key. Docker stays key-free, so route test traffic with the known key
+ // without exposing or persisting it in the browser.
await routeSessionApiKey(page);
await page.goto("/", { waitUntil: "domcontentloaded" });
await dismissAnalyticsModal(page);
@@ -182,13 +183,15 @@ test.describe("auth mode: non-public key rotation", () => {
`GET /api/settings should succeed but returned ${settingsResp.status()}`,
).toBe(true);
- // Verify localStorage was updated: the stale key should have been
- // replaced by the baked key.
const storedConfig = await page.evaluate(() => {
const raw = window.localStorage.getItem("openhands-agent-server-config");
return raw ? JSON.parse(raw) : null;
});
- expect(storedConfig?.sessionApiKey).not.toBe(STALE_KEY);
+ if (process.env.MOCK_LLM_DOCKER_MODE) {
+ expect(storedConfig?.sessionApiKey).toBe(STALE_KEY);
+ } else {
+ expect(storedConfig?.sessionApiKey).not.toBe(STALE_KEY);
+ }
});
});
diff --git a/vite.config.ts b/vite.config.ts
index 00f0ae9022..7a27e8cac0 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -105,6 +105,7 @@ export default defineConfig(({ mode }) => {
VITE_BACKEND_HOST = "127.0.0.1:8000",
VITE_USE_TLS = "false",
VITE_FRONTEND_PORT = "3001",
+ VITE_BIND_HOST = "127.0.0.1",
VITE_INSECURE_SKIP_VERIFY = "false",
VITE_BASE_PATH,
VITE_VSCODE_BASE_PATH,
@@ -402,7 +403,7 @@ export default defineConfig(({ mode }) => {
server: {
port: FE_PORT,
strictPort: true, // Fail if port is busy (dynamic allocation handles fallback)
- host: true,
+ host: VITE_BIND_HOST,
allowedHosts: true,
proxy: {
"/api": {