Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: auto-generate random API keys for dev server authentication (#203)

Rohit Malhotra9098d9e6dfbe
diff --git a/AGENTS.md b/AGENTS.md
index 66614413ad..3f41c41c89 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -86,16 +86,22 @@
- `OH_AGENT_SERVER_LOCAL_PATH` β€” absolute path to a local `software-agent-sdk` checkout. Runs the local checkout via `uvx` with `--with-editable` for `openhands-sdk`/`openhands-tools`/`openhands-workspace` and `--reinstall` for `openhands-agent-server`, so SDK edits are picked up on restart. Highest precedence.
- `OH_AGENT_SERVER_GIT_REF` β€” git commit SHA or branch name (takes precedence over version)
- `OH_AGENT_SERVER_VERSION` β€” specific PyPI version (e.g., "1.21.1")
- - `OH_SECRET_KEY` β€” secret key for settings encryption; uses a default value for local dev, override for production
+ - `OH_SECRET_KEY` β€” secret key for settings encryption; uses a static default for local dev since it's needed for reading persisted encrypted values across restarts
+ - `SESSION_API_KEY` / `OH_SESSION_API_KEYS_0` / `VITE_SESSION_API_KEY` β€” session API key for agent-server authentication; auto-generated using `crypto.randomBytes(32)` if not set, passed to both agent-server (`OH_SESSION_API_KEYS_0`) and frontend (`VITE_SESSION_API_KEY`)
- Default: released PyPI version `1.21.1` for agent-server SDK libraries
+- Security: Both `scripts/dev-safe.mjs` and `scripts/dev-with-automation.mjs` auto-generate random API keys on each startup for better security isolation:
+ - `SESSION_API_KEY` β€” 64-character hex (256-bit) for agent-server API authentication; auto-generated per session unless overridden via env var
+ - `AUTOMATION_LOCAL_API_KEY` β€” 64-character hex for automation backend auth; auto-generated per session unless overridden
+ - `OH_SECRET_KEY` β€” kept as a static default because it's used for encrypting/decrypting persisted settings values and needs consistency across restarts
- `scripts/dev-safe.mjs` should fail fast if `uvx` cannot be spawned (for example missing PATH entries).
- `npm run dev` now runs the full stack with automation by default (via `dev:automation`). Use `npm run dev:minimal` for agent-server + Vite only.
- `scripts/dev-with-automation.mjs` runs the full stack: agent-server, automation backend (both via uvx), Vite dev server, and ingress proxy. Uses a standalone ingress proxy (`scripts/ingress.mjs`) to route traffic:
- `/api/automation/*` β†’ automation backend (:18001)
- `/api/*`, `/sockets`, etc. β†’ agent server (:18000)
- `/*` (default) β†’ Vite dev server (:3001)
- - Environment variables: `PORT` (ingress port, default: 8000), `OH_AUTOMATION_GIT_REF` (git ref, overrides default version), `OH_AUTOMATION_VERSION` (default: `1.0.0a1`)
+ - Environment variables: `PORT` (ingress port, default: 8000), `OH_AUTOMATION_GIT_REF` (git ref, overrides default version), `OH_AUTOMATION_VERSION` (default: `1.0.0a1`), `AUTOMATION_LOCAL_API_KEY` (optional, use a fixed key; default: auto-generated random key per session)
- Access points: `http://localhost:8000/` (main UI), `http://localhost:8000/api/automation/docs` (API docs)
+ - Security: `AUTOMATION_LOCAL_API_KEY` is auto-generated using `crypto.randomBytes(32)` on each startup for better security isolation. Set the env var explicitly to use a consistent key across restarts. The cipher key (`OH_SECRET_KEY`) keeps a static default for local dev since it's used for encrypting/decrypting persisted settings values.
- `scripts/ingress.mjs` is a standalone HTTP reverse proxy that can be used independently to route traffic to multiple backends based on URL path prefix.
- `scripts/dev-safe.mjs` (now `npm run dev:minimal`) runs just agent-server + Vite without automation.
- Vite dev mode can black-screen on first load with `504 Outdated Optimize Dep` if core client-entry deps are not prebundled; keep `react`, `react/jsx-runtime`, `react-dom/client`, and `react-router/dom` in `optimizeDeps.include`.
diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.ts
index ecc7c9ccaa..f47f70af0a 100644
--- a/__tests__/scripts/dev-with-automation.test.ts
+++ b/__tests__/scripts/dev-with-automation.test.ts
@@ -168,10 +168,11 @@ describe("buildConfig", () => {
expect(config.verbose).toBe(true);
});
- it("uses default local API key", () => {
+ it("auto-generates random local API key by default", () => {
const config = buildConfig({}, {});
- expect(config.localApiKey).toBe("openhands-local-api-key");
+ // Default is a 64-char hex string (256-bit random key)
+ expect(config.localApiKey).toMatch(/^[0-9a-f]{64}$/);
});
it("respects custom AUTOMATION_LOCAL_API_KEY from env", () => {
@@ -180,14 +181,15 @@ describe("buildConfig", () => {
expect(config.localApiKey).toBe("my-custom-key");
});
- it("sets sessionApiKey to null by default", () => {
+ it("auto-generates random session API key by default", () => {
const config = buildConfig({}, {});
- expect(config.sessionApiKey).toBeNull();
+ // Default is a 64-char hex string (256-bit random key)
+ expect(config.sessionApiKey).toMatch(/^[0-9a-f]{64}$/);
});
- it("reads sessionApiKey from OH_SESSION_API_KEY", () => {
- const config = buildConfig({}, { OH_SESSION_API_KEY: "my-session-key" });
+ it("reads sessionApiKey from SESSION_API_KEY", () => {
+ const config = buildConfig({}, { SESSION_API_KEY: "my-session-key" });
expect(config.sessionApiKey).toBe("my-session-key");
});
@@ -198,19 +200,13 @@ describe("buildConfig", () => {
expect(config.sessionApiKey).toBe("vite-session-key");
});
- it("OH_SESSION_API_KEY takes precedence over VITE_SESSION_API_KEY", () => {
+ it("SESSION_API_KEY takes precedence over VITE_SESSION_API_KEY", () => {
const config = buildConfig({}, {
- OH_SESSION_API_KEY: "oh-key",
+ SESSION_API_KEY: "session-key",
VITE_SESSION_API_KEY: "vite-key",
});
- expect(config.sessionApiKey).toBe("oh-key");
- });
-
- it("reads sessionApiKey from SESSION_API_KEY (agent-server V0 env)", () => {
- const config = buildConfig({}, { SESSION_API_KEY: "v0-session-key" });
-
- expect(config.sessionApiKey).toBe("v0-session-key");
+ expect(config.sessionApiKey).toBe("session-key");
});
it("reads sessionApiKey from OH_SESSION_API_KEYS_0 (agent-server V1 env)", () => {
@@ -232,7 +228,6 @@ describe("buildConfig", () => {
const config = buildConfig({}, {
SESSION_API_KEY: "v0-key",
OH_SESSION_API_KEYS_0: "v1-key",
- OH_SESSION_API_KEY: "oh-key",
VITE_SESSION_API_KEY: "vite-key",
});
diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjs
index 109f266f93..c326b99a1c 100644
--- a/scripts/dev-safe.mjs
+++ b/scripts/dev-safe.mjs
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
+import { randomBytes } from "node:crypto";
import {
existsSync,
mkdirSync,
@@ -24,11 +25,25 @@ const LOCAL_AGENT_SERVER_SUBDIRS = [
"openhands-workspace",
];
// Default secret key for local development (DO NOT use in production)
+// This is kept static because it's used for encrypting/decrypting persisted settings
const DEFAULT_SECRET_KEY = "openhands-dev-secret-key-change-in-prod";
// Default agent-server version (released PyPI version)
// Set OH_AGENT_SERVER_GIT_REF to use a git branch/SHA instead
const DEFAULT_AGENT_SERVER_VERSION = "1.21.1";
+/**
+ * Generate a cryptographically secure random API key.
+ * Returns a 64-character hex string (256-bit).
+ */
+export function generateRandomApiKey() {
+ return randomBytes(32).toString("hex");
+}
+
+// Auto-generate a random session API key for this dev session.
+// This ensures the agent-server API is authenticated even in local dev.
+// Set SESSION_API_KEY env var to use a consistent key across restarts.
+const DEFAULT_SESSION_API_KEY = generateRandomApiKey();
+
function isEnoentError(error) {
return Boolean(
(error &&
@@ -189,6 +204,16 @@ export function buildSafeDevConfig(cwd = process.cwd(), env = process.env) {
const workspacesPath = path.join(stateDir, "workspaces");
// Use provided secret key or default for local development
const secretKey = env.OH_SECRET_KEY || DEFAULT_SECRET_KEY;
+ // Use provided session API key or auto-generated random key for this session
+ // Check multiple env vars that may be used:
+ // - SESSION_API_KEY: Common name
+ // - OH_SESSION_API_KEYS_0: Used by agent-server V1 config
+ // - VITE_SESSION_API_KEY: Used by frontend config
+ const sessionApiKey =
+ env.SESSION_API_KEY ||
+ env.OH_SESSION_API_KEYS_0 ||
+ env.VITE_SESSION_API_KEY ||
+ DEFAULT_SESSION_API_KEY;
return {
cwd,
@@ -203,6 +228,7 @@ export function buildSafeDevConfig(cwd = process.cwd(), env = process.env) {
backendHost: `127.0.0.1:${backendPort}`,
workingDir: env.VITE_WORKING_DIR || workspacesPath,
secretKey,
+ sessionApiKey,
};
}
@@ -222,6 +248,8 @@ export function buildAgentServerEnv(config) {
OH_BASH_EVENTS_DIR: config.bashEventsDir,
OH_VSCODE_PORT: String(config.vscodePort),
OH_SECRET_KEY: config.secretKey,
+ // Use OH_SESSION_API_KEYS_0 for agent-server V1 config format
+ OH_SESSION_API_KEYS_0: config.sessionApiKey,
};
}
@@ -332,6 +360,13 @@ async function main() {
? "custom (from OH_SECRET_KEY)"
: "default (for local development)";
+ const sessionKeySource =
+ process.env.SESSION_API_KEY ||
+ process.env.OH_SESSION_API_KEYS_0 ||
+ process.env.VITE_SESSION_API_KEY
+ ? "custom (from env)"
+ : "auto-generated (random)";
+
console.log("Starting isolated agent-server + frontend dev stack...");
console.log(`- agent-server: ${agentServerCmd.source}`);
console.log(`- backend: ${config.backendBaseUrl}`);
@@ -339,6 +374,7 @@ async function main() {
console.log(`- working dir: ${config.workingDir}`);
console.log(`- isolated state dir: ${config.stateDir}`);
console.log(`- secret key: ${secretKeySource}`);
+ console.log(`- session API key: ${sessionKeySource}`);
console.log("");
const backend = spawnProcess(
@@ -409,6 +445,8 @@ 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,
},
});
diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjs
index 698fa113e9..c1238f320d 100644
--- a/scripts/dev-with-automation.mjs
+++ b/scripts/dev-with-automation.mjs
@@ -51,6 +51,7 @@ import {
buildAgentServerEnv,
buildNpmScriptCommand,
formatMissingUvxGuidance,
+ generateRandomApiKey,
} from "./dev-safe.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -63,8 +64,12 @@ const DEFAULT_AUTOMATION_PACKAGE = "openhands-automation";
const DEFAULT_AUTOMATION_VERSION = "1.0.0a1";
const DEFAULT_BACKEND_PORT = 18000;
const DEFAULT_AUTOMATION_PORT = 18001;
-// Default local API key for automation backend auth (matches agent-server pattern)
-const DEFAULT_LOCAL_API_KEY = "openhands-local-api-key";
+
+// Auto-generate a random API key for this dev session.
+// This ensures services share the same key during a single invocation,
+// but each restart gets a fresh key for better security isolation.
+// Set AUTOMATION_LOCAL_API_KEY env var to use a consistent key across restarts.
+const DEFAULT_LOCAL_API_KEY = generateRandomApiKey();
// ═══════════════════════════════════════════════════════════════════════════
// Terminal Styling
@@ -233,13 +238,17 @@ function buildConfig(args, env = process.env) {
// Local API key for automation backend auth
const localApiKey = env.AUTOMATION_LOCAL_API_KEY || DEFAULT_LOCAL_API_KEY;
- // Session API key for agent-server auth (optional)
- // Check multiple env vars that the agent-server may use:
- // - SESSION_API_KEY: Used by agent-server default config (V0)
- // - OH_SESSION_API_KEYS_0: Used by agent-server V1 config
- // - OH_SESSION_API_KEY: Common alias
- // - VITE_SESSION_API_KEY: Used by frontend config
- const sessionApiKey = env.SESSION_API_KEY || env.OH_SESSION_API_KEYS_0 || env.OH_SESSION_API_KEY || env.VITE_SESSION_API_KEY || null;
+ // Session API key for agent-server auth
+ // Build a preliminary safe config to get the auto-generated session key
+ // This ensures both agent-server and frontend use the same key
+ const stateDir = join(homedir(), ".openhands", "agent-canvas");
+ const safeConfig = buildSafeDevConfig(projectRoot, {
+ ...env,
+ OH_CANVAS_SAFE_STATE_DIR: stateDir,
+ OH_CANVAS_SAFE_BACKEND_PORT: backendPort.toString(),
+ OH_CANVAS_SAFE_VSCODE_PORT: vscodePort.toString(),
+ });
+ const sessionApiKey = safeConfig.sessionApiKey;
return {
// Ingress port (main entry point)
@@ -255,7 +264,7 @@ function buildConfig(args, env = process.env) {
canvasPath: projectRoot,
// Data directories (same as dev-safe.mjs)
- stateDir: join(homedir(), ".openhands", "agent-canvas"),
+ stateDir,
// Auth
localApiKey,
@@ -523,6 +532,8 @@ function startVite(config) {
VITE_BACKEND_BASE_URL: `http://127.0.0.1:${config.ingressPort}`,
VITE_WORKING_DIR: join(config.stateDir, "workspaces"),
VITE_FRONTEND_PORT: config.vitePort.toString(),
+ // Session API key for frontend to authenticate with agent-server
+ VITE_SESSION_API_KEY: config.sessionApiKey,
// Automation API key for frontend to authenticate with automation backend
VITE_AUTOMATION_API_KEY: config.localApiKey,
},
@@ -704,6 +715,7 @@ async function main() {
export {
buildAutomationCommand,
buildConfig,
+ generateRandomApiKey,
DEFAULT_AUTOMATION_REPO,
DEFAULT_AUTOMATION_PACKAGE,
DEFAULT_AUTOMATION_VERSION,