π OpenHands: AI-Driven Development
fix: inject runtime session key into index.html for published binary (#795)
chuckbutkuscbeeee002e19
diff --git a/AGENTS.md b/AGENTS.mdindex 805cc8e525..643341b305 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -144,6 +144,8 @@ you are running inside of β NOT the automation backend.## Additional Notes+- **Published binary auth fix**: When users install the npm package globally (`npm install -g @openhands/agent-canvas`) and run `agent-canvas`, the pre-built static frontend has a `VITE_SESSION_API_KEY` baked in at publish time that differs from the user's persisted runtime key (`~/.openhands/agent-canvas/session-api-key.txt`). The fix is to inject the runtime session key into `index.html` responses at serve time (not build time). `scripts/static-server.mjs` accepts a `--session-api-key <key>` flag and injects a tiny inline `<script>` before `</head>` that seeds the key into `localStorage['openhands-agent-server-config'].sessionApiKey` β only if no key is already stored (preserving user-set overrides). `scripts/dev-with-automation.mjs` and `scripts/dev-static.mjs` both pass `--session-api-key ${config.sessionApiKey}` when starting the static server.+- Direct `dependencies` and `devDependencies` in `package.json` are exact-pinned (no caret ranges); reproducible installs should use the committed `package-lock.json` plus `npm ci`, and targeted transitive fixes still belong in `overrides`.- `package-lock.json` must also retain the optional peer entry for `node_modules/vite-tsconfig-paths/node_modules/[email protected]`; without that nested lock entry, clean `npm ci` installs on CI fail with `Missing: [email protected] from lock file`.- `npm test` now runs `npm run make-i18n` first so clean environments generate `src/i18n/declaration.ts` before Vitest loads aliased imports.diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.tsindex 9569b2dd19..324177b096 100644--- a/__tests__/scripts/static-server.test.ts+++ b/__tests__/scripts/static-server.test.ts@@ -4,7 +4,10 @@ import { tmpdir } from "node:os";import path from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { startStaticServer } from "../../scripts/static-server.mjs";+import {+ parseArgs,+ startStaticServer,+} from "../../scripts/static-server.mjs";describe("static-server.mjs", () => {const servers: Server[] = [];@@ -42,6 +45,155 @@ describe("static-server.mjs", () => {return `http://127.0.0.1:${address.port}`;}+ describe("parseArgs", () => {+ it("defaults sessionApiKey to null", () => {+ const config = parseArgs([]);+ expect(config.sessionApiKey).toBeNull();+ });++ it("parses --session-api-key", () => {+ const config = parseArgs(["--session-api-key", "my-test-key"]);+ expect(config.sessionApiKey).toBe("my-test-key");+ });++ it("treats empty string as null for session key", () => {+ const config = parseArgs(["--session-api-key", ""]);+ expect(config.sessionApiKey).toBeNull();+ });+ });++ describe("session key injection", () => {+ async function startServerWithKey(dir: string, sessionApiKey: string) {+ const server = await startStaticServer({+ port: 0,+ host: "127.0.0.1",+ dir,+ routes: {},+ sessionApiKey,+ });+ servers.push(server);+ 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}`;+ }++ it("injects session key script into index.html", 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 origin = await startServerWithKey(buildDir, "test-session-key");+ const response = await fetch(`${origin}/`);++ expect(response.status).toBe(200);+ const body = await response.text();+ expect(body).toContain("openhands-agent-server-config");+ expect(body).toContain("test-session-key");+ expect(body).toContain("sessionApiKey");+ });++ it("injects session key into SPA fallback index.html", 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 origin = await startServerWithKey(buildDir, "fallback-key");+ const response = await fetch(`${origin}/some/deep/route`);++ expect(response.status).toBe(200);+ const body = await response.text();+ expect(body).toContain("fallback-key");+ });++ it("does not inject into non-html asset responses", async () => {+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));+ tempDirs.push(buildDir);+ mkdirSync(path.join(buildDir, "assets"));+ writeFileSync(+ path.join(buildDir, "index.html"),+ "<html><head></head><body>app</body></html>",+ );+ writeFileSync(+ path.join(buildDir, "assets", "app.js"),+ "console.log('app');",+ );++ const origin = await startServerWithKey(buildDir, "should-not-inject");+ const response = await fetch(`${origin}/assets/app.js`);++ expect(response.status).toBe(200);+ const body = await response.text();+ expect(body).not.toContain("should-not-inject");+ });++ it("sets Cache-Control: no-cache for injected index.html", 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 origin = await startServerWithKey(buildDir, "cache-test-key");+ const response = await fetch(`${origin}/`);++ expect(response.headers.get("cache-control")).toBe("no-cache");+ });++ it("does not inject when sessionApiKey is null", 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: "127.0.0.1",+ dir: buildDir,+ routes: {},+ sessionApiKey: null,+ });+ servers.push(server);+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("No port");+ const origin = `http://127.0.0.1:${(address as { port: number }).port}`;++ const response = await fetch(`${origin}/`);+ const body = await response.text();+ expect(body).not.toContain("openhands-agent-server-config");+ });++ it("injects session key into HTML without </head> tag (falls back to </body>)", async () => {+ const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));+ tempDirs.push(buildDir);+ writeFileSync(+ path.join(buildDir, "index.html"),+ "<html><body>no-head</body></html>",+ );++ const origin = await startServerWithKey(buildDir, "no-head-key");+ const response = await fetch(`${origin}/`);++ expect(response.status).toBe(200);+ const body = await response.text();+ expect(body).toContain("no-head-key");+ expect(body).toContain("openhands-agent-server-config");+ // Script should appear before </body>, not at the very front of the document+ expect(body.indexOf("no-head-key")).toBeLessThan(body.indexOf("</body>"));+ expect(body.indexOf("no-head-key")).toBeGreaterThan(0);+ });+ });+it("serves nested build assets on all platforms", async () => {const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));tempDirs.push(buildDir);diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 91bb63d4ea..7bb7d7615a 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -180,10 +180,12 @@ wait "$WAIT_PID1" "$WAIT_PID2"# ββ 4. Start static server (frontend + proxy) ββββββββββββββββββββββββββββββββlog "Starting frontend + proxy on port $PORT..."+# EFFECTIVE_SESSION_KEY is set above from ~/.openhands/agent-canvas/session-api-key.txt (or $SESSION_API_KEY)node /opt/agent-canvas/static-server.mjs \--port "$PORT" \--host 0.0.0.0 \--dir /opt/agent-canvas/frontend \+ --session-api-key "$EFFECTIVE_SESSION_KEY" \--route "/api/automation=http://127.0.0.1:${AUTOMATION_PORT}" \--route "/api=http://127.0.0.1:${AGENT_SERVER_PORT}" \--route "/server_info=http://127.0.0.1:${AGENT_SERVER_PORT}" \diff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjsindex 5a19c04ab7..5abfe9fcb0 100644--- a/scripts/dev-static.mjs+++ b/scripts/dev-static.mjs@@ -388,6 +388,12 @@ function startStaticServer(config) {"0.0.0.0","--port",String(config.vitePort),+ // Inject the runtime session key so the pre-built frontend can+ // authenticate to agent-server without VITE_SESSION_API_KEY being baked+ // into the bundle at publish time.+ ...(config.sessionApiKey+ ? ["--session-api-key", config.sessionApiKey]+ : []),"--route",`/api/automation=http://localhost:${config.autoBackendPort}`,"--route",diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjsindex f07f9e50e7..915445250e 100644--- a/scripts/dev-with-automation.mjs+++ b/scripts/dev-with-automation.mjs@@ -1061,6 +1061,12 @@ function startStaticFrontend(config, staticDir) {"0.0.0.0","--port",String(config.vitePort),+ // Inject the runtime session key so the pre-built frontend can+ // authenticate to agent-server without VITE_SESSION_API_KEY being baked+ // into the bundle at publish time.+ ...(config.sessionApiKey+ ? ["--session-api-key", config.sessionApiKey]+ : []),// Proxy routes to backends (same as ingress but for direct access to vitePort)"--route",`/api/automation=http://localhost:${config.autoBackendPort}`,diff --git a/scripts/static-server.mjs b/scripts/static-server.mjsindex e0eb61efc3..238196c04c 100644--- a/scripts/static-server.mjs+++ b/scripts/static-server.mjs@@ -29,7 +29,7 @@import { createServer, request as httpRequest } from "node:http";import { createReadStream } from "node:fs";-import { stat } from "node:fs/promises";+import { readFile, stat } from "node:fs/promises";import { extname, isAbsolute, normalize, relative, resolve } from "node:path";import process from "node:process";import { pathToFileURL } from "node:url";@@ -72,6 +72,7 @@ export function parseArgs(argv = process.argv.slice(2)) {host: "0.0.0.0",dir: "build",routes: {},+ sessionApiKey: null,};for (let i = 0; i < argv.length; i++) {@@ -104,6 +105,9 @@ export function parseArgs(argv = process.argv.slice(2)) {config.routes[prefix] = url;break;}+ case "--session-api-key":+ config.sessionApiKey = argv[++i] || null;+ break;case "-h":case "--help":showHelp();@@ -129,6 +133,9 @@ OPTIONS:-d, --dir <dir> Directory to serve (default: build)-r, --route <prefix=url> Proxy <prefix> (and subpaths) to <url>;may be repeated. WebSockets supported.+ --session-api-key <key> Inject session API key into index.html so the+ pre-built frontend authenticates to agent-server+ without needing VITE_SESSION_API_KEY baked in.-h, --help Show this helpROUTING:@@ -140,6 +147,70 @@ ROUTING:`);}+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+// Runtime config injection+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/**+ * Build a tiny inline script that seeds the session API key into the+ * `openhands-agent-server-config` localStorage entry the first time the page+ * loads. Only writes if no key is already stored β explicit user overrides+ * (set via Settings > Agent Server in the UI) are always preserved.+ *+ * This lets the pre-built static binary work without needing VITE_SESSION_API_KEY+ * baked into the bundle at publish time: the runtime key is injected here instead.+ */+function makeConfigInjectionScript(sessionApiKey) {+ if (!sessionApiKey) return "";+ // JSON.stringify produces a properly escaped JS string literal.+ const keyLiteral = JSON.stringify(sessionApiKey);+ return (+ `<script>` ++ `(function(){` ++ `try{` ++ `var _k='openhands-agent-server-config',` ++ `_c=JSON.parse(localStorage.getItem(_k)||'{}');` ++ `if(!_c.sessionApiKey){` ++ `_c.sessionApiKey=${keyLiteral};` ++ `localStorage.setItem(_k,JSON.stringify(_c));` ++ `}` ++ `}catch(e){}` ++ `}());` ++ `</script>`+ );+}++/**+ * Serve index.html with the runtime session key injected into <head>.+ * Returns true if the response was written, false if the file was not found.+ */+async function serveInjectedIndexHtml(req, res, indexPath, sessionApiKey) {+ let content;+ try {+ content = await readFile(indexPath, "utf8");+ } catch {+ return false;+ }++ const script = makeConfigInjectionScript(sessionApiKey);+ // Inject right before </head> so the key is available before any app code runs.+ // replace() targets the first (and only) </head> in well-formed HTML.+ const injected = content.includes("</head>")+ ? content.replace("</head>", `${script}\n</head>`)+ : content.includes("</body>")+ ? content.replace("</body>", `${script}\n</body>`)+ : script + content;++ const buf = Buffer.from(injected, "utf8");+ res.writeHead(200, {+ "Content-Type": "text/html; charset=utf-8",+ "Content-Length": buf.length,+ "Cache-Control": "no-cache",+ });+ if (req.method !== "HEAD") res.end(buf);+ return true;+}+// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// Router (kept structurally identical to scripts/ingress.mjs)// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -322,7 +393,7 @@ async function serveFile(req, res, filePath, urlPath) {return true;}-async function handleStatic(req, res, dirAbs) {+async function handleStatic(req, res, dirAbs, sessionApiKey = null) {const rawPath = req.url.split("?")[0];let urlPath;try {@@ -346,6 +417,12 @@ async function handleStatic(req, res, dirAbs) {filePath = resolve(filePath, "index.html");}+ // Serve index.html with runtime key injection when a session key is configured.+ if (sessionApiKey && filePath.endsWith("index.html")) {+ if (await serveInjectedIndexHtml(req, res, filePath, sessionApiKey)) return;+ // Fall through to regular serveFile (handles 404 path correctly).+ }+if (await serveFile(req, res, filePath, urlPath)) return;// SPA fallback: only for non-asset requests, and not for non-GET/HEAD.@@ -354,7 +431,10 @@ async function handleStatic(req, res, dirAbs) {!looksLikeAssetRequest(urlPath)) {const indexPath = resolve(dirAbs, "index.html");- if (await serveFile(req, res, indexPath, "/")) return;+ if (sessionApiKey) {+ if (await serveInjectedIndexHtml(req, res, indexPath, sessionApiKey))+ return;+ } else if (await serveFile(req, res, indexPath, "/")) return;}res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });@@ -368,6 +448,7 @@ async function handleStatic(req, res, dirAbs) {export function startStaticServer(config) {const route = createRouter(config.routes);const dirAbs = resolve(config.dir);+ const sessionApiKey = config.sessionApiKey || null;const server = createServer((req, res) => {const backend = route(req.url);@@ -375,7 +456,7 @@ export function startStaticServer(config) {proxyRequest(req, res, backend);return;}- handleStatic(req, res, dirAbs).catch((err) => {+ handleStatic(req, res, dirAbs, sessionApiKey).catch((err) => {console.error(`Static handler error for ${req.url}:`, err);if (!res.headersSent) {res.writeHead(500);