Skip to content

πŸ™Œ OpenHands: AI-Driven Development

refactor(mars): mount the web bridge by default; drop the MARS_WEB=1 opt-in (#18349)

sk09-dev0cb2fa70d76d
diff --git a/.env.sample b/.env.sample
index 87917b496f..2978a11d8b 100644
--- a/.env.sample
+++ b/.env.sample
@@ -23,11 +23,12 @@ VITE_INSECURE_SKIP_VERIFY="false" # Skip TLS certificate verification for proxie
# VITE_POSTHOG_API_KEY="phc_..."
# VITE_DO_NOT_TRACK="1" # Disable all telemetry, including anonymous install counts
-# DigitalOcean Managed Agents: the Electron desktop app, and the web build when
-# its server runs with MARS_WEB=1. `npm run desktop` does not read this file β€”
+# DigitalOcean Managed Agents: the Electron desktop app and the web build (its
+# server hosts the bridge by default). `npm run desktop` does not read this file β€”
# export these in the shell that launches it; `npm run dev` does. Defaults come
# from the `mars` block in config/defaults.json.
-# MARS_WEB="1" # Web build: host the DigitalOcean bridge in the dev/static server
+# MARS_WEB_KEY="" # Web build: key the /mars/* routes require; defaults to the server's --session-api-key. Required on a non-loopback bind.
+# MARS_WEB="0" # Web build: turn the DigitalOcean bridge off for a server that must not host it (on by default)
# MARS_TOKEN="" # Web build: personal access token to sign in with at server start (credentials are otherwise in-memory and lost on restart)
# DO_OAUTH_CLIENT_ID="" # Desktop only: public client ID of a DigitalOcean OAuth app with redirect URI http://127.0.0.1:53682/callback. Unset = personal access tokens only.
# MARS_API_BASE_URL="https://api.digitalocean.com" # Point at a staging harness API
diff --git a/__tests__/scripts/dev-static.test.ts b/__tests__/scripts/dev-static.test.ts
index 2968bfbcff..d5b08ed9d2 100644
--- a/__tests__/scripts/dev-static.test.ts
+++ b/__tests__/scripts/dev-static.test.ts
@@ -4,6 +4,7 @@ import {
buildAutomationBackendEnv,
buildLocalServiceRouteArgs,
parseArgs,
+ buildMarsWebEnv,
} from "../../scripts/dev-static.mjs";
import { buildFrontendEnv } from "../../scripts/static-build.mjs";
@@ -62,3 +63,17 @@ describe("dev-static", () => {
expect(args.filter((arg: string) => arg.includes("localhost"))).toEqual([]);
});
});
+
+describe("dev-static MARS web bridge env", () => {
+ it("puts the bridge on the ingress behind the session key, and off the static child", () => {
+ const config = { sessionApiKey: "stack-key" } as never;
+ expect(buildMarsWebEnv("ingress", config)).toEqual({
+ MARS_WEB_KEY: "stack-key",
+ });
+ expect(buildMarsWebEnv("static", config)).toEqual({ MARS_WEB: "0" });
+ });
+
+ it("mounts nothing when the stack has no session key", () => {
+ expect(buildMarsWebEnv("ingress", {} as never)).toEqual({ MARS_WEB: "0" });
+ });
+});
diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.ts
index 3c7a9e2dfd..d51044ef5b 100644
--- a/__tests__/scripts/dev-with-automation.test.ts
+++ b/__tests__/scripts/dev-with-automation.test.ts
@@ -33,6 +33,7 @@ import {
DEFAULT_AUTOMATION_REPO,
DEFAULT_AUTOMATION_PACKAGE,
DEFAULT_AUTOMATION_VERSION,
+ buildMarsWebEnv,
} from "../../scripts/dev-with-automation.mjs";
import {
buildAgentServerEnv,
@@ -1179,3 +1180,28 @@ describe("dev-with-automation CLI", () => {
expect(output).toContain("uvx");
});
});
+
+describe("buildMarsWebEnv", () => {
+ it("puts the bridge on the ingress behind the session key, off the static child", () => {
+ const config = { sessionApiKey: "stack-key", marsWebBridge: true } as never;
+ expect(buildMarsWebEnv("ingress", config)).toEqual({
+ MARS_WEB_KEY: "stack-key",
+ });
+ expect(buildMarsWebEnv("static", config)).toEqual({ MARS_WEB: "0" });
+ });
+
+ it("mounts nothing without a session key", () => {
+ expect(
+ buildMarsWebEnv("ingress", { marsWebBridge: true } as never),
+ ).toEqual({ MARS_WEB: "0" });
+ });
+
+ it("mounts nothing under Electron (marsWebBridge: false), even with a key", () => {
+ expect(
+ buildMarsWebEnv("ingress", {
+ sessionApiKey: "k",
+ marsWebBridge: false,
+ } as never),
+ ).toEqual({ MARS_WEB: "0" });
+ });
+});
diff --git a/__tests__/scripts/mars-web-bridge.test.ts b/__tests__/scripts/mars-web-bridge.test.ts
index 4fbaf77e09..b26b5e15ca 100644
--- a/__tests__/scripts/mars-web-bridge.test.ts
+++ b/__tests__/scripts/mars-web-bridge.test.ts
@@ -24,7 +24,7 @@ import { MARS_TUNNEL_IPC } from "../../scripts/mars-tunnel-bridge.mjs";
import {
RPC_METHODS,
createMarsWebBridge,
- isMarsWebEnabled,
+ isMarsWebDisabled,
mountMarsWebBridge,
rewriteAgentServerUrls,
} from "../../scripts/mars-web-bridge.mjs";
@@ -661,28 +661,104 @@ describe("createMarsWebBridge with a session key", () => {
});
describe("mountMarsWebBridge", () => {
- it("is off unless MARS_WEB=1", () => {
- expect(isMarsWebEnabled({})).toBe(false);
- expect(isMarsWebEnabled({ MARS_WEB: "0" })).toBe(false);
- expect(isMarsWebEnabled({ MARS_WEB: "1" })).toBe(true);
+ it("mounts by default on a loopback bind, even without a key", async () => {
+ const warnings: string[] = [];
+ const debugs: string[] = [];
+ const mounted = mountMarsWebBridge({
+ env: {},
+ host: "127.0.0.1",
+ log: (m) => warnings.push(m),
+ debug: (m) => debugs.push(m),
+ });
+ expect(mounted).not.toBeNull();
+ expect(warnings).toEqual([]);
+ expect(debugs[0]).toMatch(/local callers only/);
+ await mounted!.dispose();
+ });
+
+ it("is off with MARS_WEB=0 and its synonyms, silently", () => {
+ for (const value of ["0", "false", "off", "no", "OFF", " 0 "]) {
+ const logs: string[] = [];
+ expect(
+ mountMarsWebBridge({
+ env: { MARS_WEB: value, MARS_WEB_KEY: "k" },
+ host: "127.0.0.1",
+ log: (m) => logs.push(m),
+ debug: (m) => logs.push(m),
+ }),
+ ).toBeNull();
+ expect(logs).toEqual([]);
+ }
+ });
+
+ it("stays on for the old MARS_WEB=1 opt-in, and warns once about a typo", async () => {
+ for (const value of ["1", "true", "on", "yes"]) {
+ const logs: string[] = [];
+ expect(isMarsWebDisabled({ MARS_WEB: value }, (m) => logs.push(m))).toBe(
+ false,
+ );
+ expect(logs).toEqual([]);
+ }
+ const logs: string[] = [];
+ expect(isMarsWebDisabled({ MARS_WEB: "nope" }, (m) => logs.push(m))).toBe(
+ false,
+ );
+ expect(logs[0]).toMatch(/not recognised/);
+ const mounted = mountMarsWebBridge({
+ env: { MARS_WEB: "nope" },
+ host: "127.0.0.1",
+ log: () => {},
+ debug: () => {},
+ });
+ expect(mounted).not.toBeNull();
+ await mounted!.dispose();
+ });
+
+ it("only warns about an unmountable LAN bind when someone opted in", () => {
+ const warnings: string[] = [];
+ const debugs: string[] = [];
+ // Nobody asked for DigitalOcean: a Docker public-mode instance must not
+ // see a warning on every start.
expect(
- mountMarsWebBridge({ env: {}, host: "127.0.0.1", log: () => {} }),
+ mountMarsWebBridge({
+ env: {},
+ host: "::",
+ log: (m) => warnings.push(m),
+ debug: (m) => debugs.push(m),
+ }),
).toBeNull();
+ expect(warnings).toEqual([]);
+ expect(debugs[0]).toMatch(/not loopback/);
+ // MARS_TOKEN, or the old MARS_WEB=1 opt-in, says they meant to use it, so
+ // the refusal is worth a warning.
+ for (const env of [{ MARS_TOKEN: "dop_v1_x" }, { MARS_WEB: "1" }]) {
+ const warned: string[] = [];
+ expect(
+ mountMarsWebBridge({
+ env,
+ host: "::",
+ log: (m) => warned.push(m),
+ debug: () => {},
+ }),
+ ).toBeNull();
+ expect(warned[0]).toMatch(/not loopback/);
+ }
});
it("refuses a non-loopback bind without a key, and mounts with one", async () => {
const logs: string[] = [];
expect(
mountMarsWebBridge({
- env: { MARS_WEB: "1" },
+ env: {},
host: "0.0.0.0",
log: (m) => logs.push(m),
+ debug: (m) => logs.push(m),
}),
).toBeNull();
expect(logs[0]).toMatch(/not loopback/);
const mounted = mountMarsWebBridge({
- env: { MARS_WEB: "1", MARS_WEB_KEY: "k" },
+ env: { MARS_WEB_KEY: "k" },
host: "0.0.0.0",
log: () => {},
});
diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.ts
index c05386782d..78104e9d90 100644
--- a/__tests__/scripts/static-server.test.ts
+++ b/__tests__/scripts/static-server.test.ts
@@ -1037,3 +1037,82 @@ describe("static-server.mjs", () => {
expect(server.listening).toBe(true);
});
});
+
+describe("static-server.mjs MARS web bridge (Docker arguments)", () => {
+ const servers: Server[] = [];
+ const tempDirs: string[] = [];
+
+ afterEach(async () => {
+ await Promise.all(
+ servers.splice(0).map(
+ (server) =>
+ new Promise<void>((resolve) => {
+ server.close(() => resolve());
+ }),
+ ),
+ );
+ for (const dir of tempDirs.splice(0)) {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ function makeBuildDir() {
+ 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>",
+ );
+ return buildDir;
+ }
+
+ async function start(
+ overrides: Partial<Parameters<typeof startStaticServer>[0]>,
+ ) {
+ const server = await startStaticServer({
+ port: 0,
+ dir: makeBuildDir(),
+ routes: {},
+ ...overrides,
+ });
+ 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}`;
+ }
+
+ // docker/entrypoint.sh runs `--host :: --session-api-key <key>` with no
+ // `--allow-lan-session-key`: the key is stripped from the HTML, but the
+ // bridge must still mount behind it.
+ it("mounts with the entrypoint's `--host :: --session-api-key` arguments", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const origin = await start({ host: "::", sessionApiKey: "docker-key" });
+ expect(await (await fetch(`${origin}/mars/health`)).json()).toEqual({
+ ok: true,
+ authRequired: true,
+ });
+ const page = await (await fetch(`${origin}/`)).text();
+ expect(page).not.toContain("docker-key");
+ expect(
+ warn.mock.calls.some((c) => String(c[0]).includes("[mars-web]")),
+ ).toBe(false);
+ });
+
+ it("does not mount on a LAN bind with no key (public mode)", async () => {
+ vi.spyOn(console, "debug").mockImplementation(() => {});
+ const origin = await start({ host: "::", authRequired: true });
+ const response = await fetch(`${origin}/mars/health`);
+ expect(response.headers.get("content-type")).toMatch(/text\/html/);
+ });
+
+ it("honours MARS_WEB=0", async () => {
+ vi.stubEnv("MARS_WEB", "0");
+ const origin = await start({ host: "127.0.0.1", sessionApiKey: "k" });
+ const response = await fetch(`${origin}/mars/health`);
+ expect(response.headers.get("content-type")).toMatch(/text\/html/);
+ });
+});
diff --git a/config/defaults.json b/config/defaults.json
index 07b81b9da2..c6a20570b7 100644
--- a/config/defaults.json
+++ b/config/defaults.json
@@ -35,7 +35,7 @@
"workspace": "openhands-workspace"
},
"mars": {
- "_comment": "DigitalOcean Managed Agents: the Electron desktop app, and the web build when its server runs with MARS_WEB=1. apiBaseUrl is the harness API both use. oauthClientId (desktop only; the web build offers personal access tokens only) is the public client ID of the DigitalOcean OAuth app registered with redirect URI http://127.0.0.1:53682/callback; implicit grant needs no secret. Leave empty to offer personal access tokens only. Overridden at runtime by DO_OAUTH_CLIENT_ID / MARS_API_BASE_URL. Read by scripts/mars-tunnel-bridge.mjs.",
+ "_comment": "DigitalOcean Managed Agents: the Electron desktop app and the web build (its server hosts the bridge by default). apiBaseUrl is the harness API both use. oauthClientId (desktop only; the web build offers personal access tokens only) is the public client ID of the DigitalOcean OAuth app registered with redirect URI http://127.0.0.1:53682/callback; implicit grant needs no secret. Leave empty to offer personal access tokens only. Overridden at runtime by DO_OAUTH_CLIENT_ID / MARS_API_BASE_URL. Read by scripts/mars-tunnel-bridge.mjs.",
"apiBaseUrl": "https://api.digitalocean.com",
"oauthClientId": ""
},
diff --git a/electron/main.mjs b/electron/main.mjs
index 0d93dd9e80..b632dee9a7 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -684,6 +684,9 @@ async function startStack() {
staticDir: buildDir,
mode: "agent-canvas",
isPublic: false,
+ // The preload provides window.marsBridge; the stack's ingress must not
+ // host a second, separate one.
+ marsWebBridge: false,
skipNpmCheck: true,
agentServerReadyTimeoutMs: 10 * 60_000,
onServiceLog: handleServiceLog,
diff --git a/playwright.mock-llm.config.ts b/playwright.mock-llm.config.ts
index 008cf48bba..5396aa524a 100644
--- a/playwright.mock-llm.config.ts
+++ b/playwright.mock-llm.config.ts
@@ -181,7 +181,11 @@ export default defineConfig({
// for agent-server, 18001 for automation).
{
command: [
- "exec node scripts/static-server.mjs",
+ // No DigitalOcean bridge on the e2e public-mode server: nothing here
+ // uses it, and the Providers entry must not appear in these specs.
+ "exec env",
+ envAssignment("MARS_WEB", "0"),
+ "node scripts/static-server.mjs",
"--dir build",
`--port ${PUBLIC_MODE_PORT}`,
"--host 127.0.0.1",
diff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjs
index cf9163a9d5..4294572ebf 100644
--- a/scripts/dev-static.mjs
+++ b/scripts/dev-static.mjs
@@ -408,6 +408,22 @@ function startAutomationBackend(config) {
);
}
+/**
+ * One MARS web bridge per stack, on the server the browser reaches: the
+ * ingress, guarded by the stack's session key (the same one the page holds).
+ * The static child behind it gets `MARS_WEB=0`: a second bridge there would
+ * answer /mars/* with its own, separate sign-in state for anyone who opens
+ * that port directly. Without the key the ingress bridge would take
+ * destroySession and savePat from any local process, the agent's shell
+ * included, so a stack with no session key mounts nothing.
+ */
+export function buildMarsWebEnv(role, config) {
+ if (role === "static") return { MARS_WEB: "0" };
+ return config.sessionApiKey
+ ? { MARS_WEB_KEY: config.sessionApiKey }
+ : { MARS_WEB: "0" };
+}
+
function startStaticServer(config) {
// Reuse `vitePort` as the upstream port name so the ingress route table
// below stays identical to dev-with-automation.mjs.
@@ -464,6 +480,7 @@ function startStaticServer(config) {
{
cwd: config.canvasPath,
color: c.magenta,
+ env: buildMarsWebEnv("static", config),
},
);
}
@@ -497,6 +514,7 @@ function startIngress(config) {
{
cwd: projectRoot,
color: c.yellow,
+ env: buildMarsWebEnv("ingress", config),
},
);
}
diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjs
index 90ec8cdb8e..be842e6dd6 100644
--- a/scripts/dev-with-automation.mjs
+++ b/scripts/dev-with-automation.mjs
@@ -1126,6 +1126,25 @@ process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
process.on("SIGHUP", shutdown);
+/**
+ * One MARS web bridge per stack, on the server the browser reaches: the
+ * ingress, guarded by the stack's session key (the same one the page holds).
+ * The static child behind it gets `MARS_WEB=0`: a second bridge there would
+ * answer /mars/* with its own, separate sign-in state for anyone who opens
+ * that port directly. Without a key the ingress bridge would take
+ * destroySession and savePat from any local process, the agent's shell
+ * included, so a stack with no session key mounts nothing. Electron turns it
+ * off altogether (`config.marsWebBridge`), its preload provides the bridge.
+ */
+export function buildMarsWebEnv(role, config) {
+ if (role === "static" || config.marsWebBridge === false) {
+ return { MARS_WEB: "0" };
+ }
+ return config.sessionApiKey
+ ? { MARS_WEB_KEY: config.sessionApiKey }
+ : { MARS_WEB: "0" };
+}
+
function startIngress(config) {
logService("ingress", `Starting on port ${config.ingressPort}...`, c.yellow);
@@ -1153,9 +1172,7 @@ function startIngress(config) {
{
cwd: projectRoot,
color: c.yellow,
- // The MARS web bridge (opt-in, MARS_WEB=1) guards /mars/* with the
- // stack's session key, the same one the page already holds.
- env: config.sessionApiKey ? { MARS_WEB_KEY: config.sessionApiKey } : {},
+ env: buildMarsWebEnv("ingress", config),
},
);
}
@@ -1459,6 +1476,11 @@ async function main(options = {}) {
// AUTOMATION_AGENT_SERVER_URL.
sandboxAgentServerUrl,
staticMode: staticModeOverride,
+ // Whether the ingress hosts the MARS web bridge (DigitalOcean Managed
+ // Agents for the browser). Electron passes false: its preload already
+ // provides the bridge, and a second one would hold its own sign-in state
+ // and, with MARS_TOKEN set, validate the token against DO at every start.
+ marsWebBridge = true,
defaultStaticMode = false,
buildStaticFrontend,
staticDir: staticDirOverride,
@@ -1575,6 +1597,7 @@ async function main(options = {}) {
// so downstream helpers (Vite spawn, static build) can produce a
// runtime-services info object describing what the agent can reach.
config.mode = mode;
+ config.marsWebBridge = marsWebBridge;
config.agentHostAlias = agentHostAlias;
config.frontendKind = useStaticMode ? "static" : "vite";
ensureDirectories(config);
@@ -1718,6 +1741,7 @@ function startStaticFrontend(config, staticDir) {
? ["--runtime-services-info", runtimeServicesInfo]
: []),
// Proxy routes only to services that this launch mode started.
+ // (MARS web bridge: see the env below β€” the ingress hosts it.)
...buildRouteArgs(getLocalServiceRoutes(config)),
// Only the static server injects into the document, so only it can tell
// the frontend this origin serves the editor. The ingress routes the same
@@ -1731,6 +1755,7 @@ function startStaticFrontend(config, staticDir) {
{
cwd: config.canvasPath,
color: c.magenta,
+ env: buildMarsWebEnv("static", config),
},
);
}
diff --git a/scripts/ingress.mjs b/scripts/ingress.mjs
index 9ab45dee92..c3d9066fa1 100644
--- a/scripts/ingress.mjs
+++ b/scripts/ingress.mjs
@@ -175,9 +175,9 @@ export function startIngress(config) {
const route = createRouter(config.routes, config.defaultBackend);
const proxy = createProxyHandlers({ label: `ingress:${config.port}` });
const uninstallDiagnostics = proxy.installDiagnostics();
- // DigitalOcean Managed Agents for the browser: with MARS_WEB=1 this server
- // hosts the MARS bridge and proxies to sessions' tunnel listeners, behind
- // the session key (MARS_WEB_KEY; dev-with-automation passes the stack's key).
+ // DigitalOcean Managed Agents for the browser: this server hosts the MARS
+ // bridge and proxies to sessions' tunnel listeners, behind the session key
+ // (MARS_WEB_KEY; dev-with-automation passes the stack's key).
const marsWeb = mountMarsWebBridge({ host: config.host });
const noReferrerPrefixes = config.noReferrerPrefixes ?? [];
diff --git a/scripts/mars-web-bridge.mjs b/scripts/mars-web-bridge.mjs
index b35243437e..b7efb9e9a3 100644
--- a/scripts/mars-web-bridge.mjs
+++ b/scripts/mars-web-bridge.mjs
@@ -28,17 +28,16 @@
* the event WebSocket, so proxied JSON has those URLs rewritten to the prefix.
*
* Trust model. These routes hold the DigitalOcean token and can destroy
- * sessions, so they are off unless `MARS_WEB=1`, and when on they want the
- * server's session key on every request: the renderer sends it as
- * `X-Session-API-Key` on `/mars/rpc/*` (the same key it already sends the
- * agent-server), and a request that presents it gets an `HttpOnly;
- * SameSite=Strict; Path=/mars` cookie back, which the browser then attaches
- * on its own to the proxied REST calls and to the WebSocket upgrade β€” the
- * one request a browser cannot put a header on. The key is `MARS_WEB_KEY`,
- * else the server's `--session-api-key`; with neither, the bridge mounts
- * only on a loopback bind (dev), where a `Host` check keeps a DNS-rebound
- * page from reaching it (cookies are host-scoped, so with a key in play
- * rebinding cannot carry one). Cross-origin requests are refused outright;
+ * sessions, so they want the server's session key on every request: the
+ * renderer sends it as `X-Session-API-Key` on `/mars/rpc/*` (the same key it
+ * already sends the agent-server), and a request that presents it gets an
+ * `HttpOnly; SameSite=Strict; Path=/mars` cookie back, which the browser then
+ * attaches on its own to the proxied REST calls and to the WebSocket upgrade
+ * β€” the one request a browser cannot put a header on. The key is
+ * `MARS_WEB_KEY`, else the server's `--session-api-key`; with neither, the
+ * bridge mounts only on a loopback bind (dev), where a `Host` check keeps a
+ * DNS-rebound page from reaching it (cookies are host-scoped, so with a key in
+ * play rebinding cannot carry one). Cross-origin requests are refused outright;
* JSON POSTs preflight and this server sends no CORS headers. Credentials
* are in-memory only (no OS keychain here, nothing written to disk);
* `MARS_TOKEN` seeds one at startup.
@@ -98,11 +97,6 @@ export const RPC_METHODS = new Set([
/** Request headers that belong to the canvas origin, never to the session host. */
const CANVAS_ONLY_HEADERS = ["cookie", AUTH_HEADER, "origin", "referer"];
-/** Off unless asked for: these routes hold the DO token and can destroy sessions. */
-export function isMarsWebEnabled(env = process.env) {
- return env.MARS_WEB === "1";
-}
-
/**
* The key `/mars/*` requires, or null when none is configured. Explicit
* `MARS_WEB_KEY` wins so a deployment can decouple it from the agent-server
@@ -120,28 +114,65 @@ export function resolveMarsWebKey({
}
/**
- * Mount the bridge for a server, or return null when it must not be: not
- * opted in, or no key on a non-loopback bind (the routes would be open to
- * the LAN with the DO token behind them).
+ * Mount the bridge for a server, or return null when it must not be. On by
+ * default; off when:
+ *
+ * - `MARS_WEB=0`. The explicit opt-out, for a server that fronts nothing a
+ * browser reaches directly (dev-with-automation's static child behind the
+ * ingress) or runs under Electron, where the preload already provides the
+ * bridge and a second one would only hold its own sign-in state.
+ * - No key on a non-loopback bind: the routes would be open to the LAN with
+ * the DO token behind them.
+ *
+ * The refusal is a warning only when someone asked for the bridge (the old
+ * `MARS_WEB=1` opt-in, or `MARS_TOKEN` set); a Docker public-mode instance
+ * that never uses DigitalOcean gets a debug line, not a warning on every
+ * start. `MARS_WEB_KEY` is not a signal here: with it set there is a key and
+ * this branch is never reached.
*/
export function mountMarsWebBridge({
env = process.env,
host = DEFAULT_BIND_HOST,
sessionApiKey = null,
log = (message) => console.warn(`[mars-web] ${message}`),
+ debug = (message) => console.debug(`[mars-web] ${message}`),
} = {}) {
- if (!isMarsWebEnabled(env)) return null;
+ if (isMarsWebDisabled(env, log)) return null;
const key = resolveMarsWebKey({ env, sessionApiKey });
if (!key && !isLoopbackBind(host)) {
- log(
- `MARS_WEB=1 but no key and bind host ${host} is not loopback; refusing to mount /mars/* (set MARS_WEB_KEY or --session-api-key).`,
+ const optedIn = env.MARS_WEB === "1" || Boolean(env.MARS_TOKEN?.trim());
+ (optedIn ? log : debug)(
+ `no key and bind host ${host} is not loopback; not mounting /mars/* (set MARS_WEB_KEY or --session-api-key).`,
);
return null;
}
- if (!key) log("no key configured; /mars/* is open to local callers only");
+ if (!key) debug("no key configured; /mars/* is open to local callers only");
return createMarsWebBridge({ env, host, key });
}
+const MARS_WEB_OFF = new Set(["0", "false", "off", "no"]);
+const MARS_WEB_ON = new Set(["", "1", "true", "on", "yes"]);
+
+/**
+ * `MARS_WEB=0` (also `false`, `off`, `no`) turns the bridge off for a server
+ * that must not host it. The old `MARS_WEB=1` opt-in and its synonyms mean
+ * on, which is the default anyway. Anything else is a typo in the off switch:
+ * say so once, and stay on, since on is what no value means.
+ */
+export function isMarsWebDisabled(
+ env = process.env,
+ log = (message) => console.warn(`[mars-web] ${message}`),
+) {
+ const value = (env.MARS_WEB ?? "").trim().toLowerCase();
+ if (MARS_WEB_OFF.has(value)) return true;
+ if (!MARS_WEB_ON.has(value)) {
+ log(
+ `MARS_WEB=${JSON.stringify(env.MARS_WEB)} is not recognised (use 0/false/off/no to turn the bridge off); leaving it on.`,
+ );
+ }
+ return false;
+}
+
function safeEqual(a, b) {
const x = Buffer.from(a);
const y = Buffer.from(b);
diff --git a/scripts/static-server.mjs b/scripts/static-server.mjs
index 3cb21ab929..51836365b0 100644
--- a/scripts/static-server.mjs
+++ b/scripts/static-server.mjs
@@ -680,13 +680,16 @@ export function startStaticServer(config) {
const staticMiddleware = createStaticMiddleware(dirAbs);
const uninstallDiagnostics = proxy.installDiagnostics();
- // DigitalOcean Managed Agents for the browser: with MARS_WEB=1 this server
- // hosts the MARS bridge and proxies to sessions' tunnel listeners, behind
- // the session key (see mars-web-bridge.mjs). The key is the one this server
- // already injects; a LAN bind with no key refuses to mount.
+ // DigitalOcean Managed Agents for the browser: this server hosts the MARS
+ // bridge and proxies to sessions' tunnel listeners, behind the session key
+ // (see mars-web-bridge.mjs). Deliberately `config.sessionApiKey`, not
+ // `policy.sessionApiKey`: the policy decides whether the key may be baked
+ // into the HTML on a LAN bind (Docker binds `::` and strips it), while the
+ // bridge only ever checks a key the client sends β€” the one the user types
+ // on the API key screen. A LAN bind with no key at all refuses to mount.
const marsWeb = mountMarsWebBridge({
host: config.host,
- sessionApiKey: policy.sessionApiKey,
+ sessionApiKey: config.sessionApiKey || null,
});
const server = createServer((req, res) => {
diff --git a/src/api/mars/AGENTS.md b/src/api/mars/AGENTS.md
index 65f16165b8..c133dae693 100644
--- a/src/api/mars/AGENTS.md
+++ b/src/api/mars/AGENTS.md
@@ -1,6 +1,6 @@
# DigitalOcean Managed Agents (MARS)
-Available in the Electron desktop app, and in the web build when its server runs with `MARS_WEB=1`. A DigitalOcean *agent* is an immutable Agent Config (DigitalOcean's console calls it an environment); a *session* is a microVM launched from one, running an OpenHands agent-server with its own disk and conversations.
+Available in the Electron desktop app and in the web build (the server hosts the bridge; see "Web build" below). A DigitalOcean *agent* is an immutable Agent Config (DigitalOcean's console calls it an environment); a *session* is a microVM launched from one, running an OpenHands agent-server with its own disk and conversations.
- **Surfaces**: the "Choose how you want to connect" chooser (`AddBackendChooser` in `backend-form-modal.tsx`) gains a third **DigitalOcean** tab, `DigitalOceanConnectPanel`: sign in (OAuth or token), then pick an OpenHands agent β€” opening it resumes the agent's latest live session or launches its first, and closes the modal. Each agent row expands to list its sessions as children (any connectable one opens directly), and **New Agent** (`DigitalOceanNewAgentForm`) creates an OpenHands Agent Config and launches its first session. While a MARS backend is active, `MarsSessionPanel` (`src/components/features/sidebar/mars-session-panel.tsx`) replaces the sidebar conversation list: the agent's sessions read like thread folders (the current one expands to its conversations, others open with a click), the header "+" launches a new session, and the agent menu switches agent or opens `ManageBackendsModal initialView="managed-agents"` β€” the full management view in `src/components/features/backends/managed-agents/`. Everything is gated on `getMarsBridge()`: Electron's preload provides it, and the web build gets a fetch-backed one from the Agent Canvas server when that server hosts the MARS web bridge (below); a page with neither never shows it.
- **OpenHands only**: agent configs are shown only when their manifest's `agent` is `openhands` (flat `agent:` or `spec.agent`). The list endpoint omits manifests, so `listAgentConfigs` in `scripts/mars-tunnel-bridge.mjs` fetches each config once (configs are immutable) and adds `agent`. The match is strict: a manifest without `agent: openhands` (older specs that no longer launch) or one that could not be read (`agent: null`, retried on the next list) is hidden. Sessions are shown only when their `config_id` names a matching config; `agent_kind` is not used, since OpenHands sessions report `AGENT_KIND_UNSPECIFIED`.
@@ -8,7 +8,7 @@ Available in the Electron desktop app, and in the web build when its server runs
- **Sandbox size**: the New Agent form's "Sandbox size" picker lists `GET /v2/agents/sessions/sandbox/sizes` (`listSandboxSizes`, `useMarsSandboxSizes`; static, so `staleTime: Infinity`) and defaults to DigitalOcean's choice. The chosen slug goes into the manifest as a top-level `size:` line (slug-validated in `buildOpenHandsManifest`), because sessions created from a config cannot carry a size; it therefore applies to every session of that agent. A failed or pending catalog leaves only the default and never blocks create.
- **Shared hooks**: `useLaunchMarsSession()` (open / launch / create agent / "open agent", with create-vs-connect error copy) and `useMarsSignIn()` (sign-in, switch connection, sign-out) back the chooser tab, the Managed Agents view and the sidebar; reuse them instead of calling `createSession` + connect directly.
- **Port-forward tunnel**: `openTunnel` opens the port-forward tunnel and, on desktop, returns `{transport: "tunnel", host: http://127.0.0.1:<port>}`; the renderer registers that host as an ordinary local backend. The public ingress URL path (direct connection to `GET /v2/agents/sessions/{id}/ingress`) was built and tested here and then removed from this branch on 2026-10-08 β€” REST worked over it but its WebSocket is reset inside the platform (microVM LB β†’ activator, fix in microvm#1920) β€” and will come back once that is deployed.
-- **Web build (browser)**: the server that fronts the web build (`scripts/ingress.mjs` for `npm run dev`, `scripts/static-server.mjs` for `dev:static` and Docker) hosts the same bridge via `scripts/mars-web-bridge.mjs` and exposes it same-origin: `POST /mars/rpc/<method>` (an explicit allow-list of the `MarsBridge` surface, `RPC_METHODS`; `src/api/mars/mars-web-bridge.ts` installs a fetch-backed `window.marsBridge` from `entry.client.tsx` after probing `GET /mars/health`), and `/mars/sessions/<id>/…` as an HTTP + WebSocket reverse proxy to the tunnel listener the server holds for that session (through the bridge's own `createProxyHandlers` instance: no idle/response timeout, since agent-server calls can stay silent for minutes, no `X-Forwarded-*`, and upstream failures answer a JSON 502 `{error:{message}}`; the tunnel client itself pings the harness socket every 30 s). `openTunnel` therefore answers `host: <origin>/mars/sessions/<id>`, a path-prefixed backend; proxied JSON has agent-server URLs (`conversation_url` and friends) rewritten to that prefix so the event WebSocket lands on the proxy. This is what makes the browser work at all: harness-api has no CORS, the tunnel needs a Node process, and the token must stay off the page. The routes are **off unless `MARS_WEB=1`** and, when on, want the server's session key on every request: the renderer sends it as `X-Session-API-Key` on `/mars/rpc/*` and gets an `HttpOnly; SameSite=Strict; Path=/mars` cookie back, which the browser attaches on its own to the proxied REST calls and the WebSocket upgrade (the one request a browser cannot put a header on). The key is `MARS_WEB_KEY`, else the server's `--session-api-key` (`dev-with-automation` hands the stack's key to `ingress.mjs`); with neither, `mountMarsWebBridge` mounts only on a loopback bind, where a `Host` check stops DNS rebinding. Only `conversation_url` fields are rewritten (a URL inside a message is content), JSON past 8 MB streams through untouched, `Cookie` and the key header never reach the session host, a malformed session path is a 400, an upstream WebSocket the browser abandoned mid-handshake is terminated, and `dispose()` closes both ends of every proxied WebSocket. Credentials are in-memory (no keychain; `MARS_TOKEN` seeds one at startup), OAuth is not offered (`canUseOAuth: false`), and cross-origin requests are refused.
+- **Web build (browser)**: the server that fronts the web build (`scripts/ingress.mjs` for `npm run dev`, `scripts/static-server.mjs` for `dev:static` and Docker) hosts the same bridge via `scripts/mars-web-bridge.mjs` and exposes it same-origin: `POST /mars/rpc/<method>` (an explicit allow-list of the `MarsBridge` surface, `RPC_METHODS`; `src/api/mars/mars-web-bridge.ts` installs a fetch-backed `window.marsBridge` from `entry.client.tsx` after probing `GET /mars/health`), and `/mars/sessions/<id>/…` as an HTTP + WebSocket reverse proxy to the tunnel listener the server holds for that session (through the bridge's own `createProxyHandlers` instance: no idle/response timeout, since agent-server calls can stay silent for minutes, no `X-Forwarded-*`, and upstream failures answer a JSON 502 `{error:{message}}`; the tunnel client itself pings the harness socket every 30 s). `openTunnel` therefore answers `host: <origin>/mars/sessions/<id>`, a path-prefixed backend; proxied JSON has agent-server URLs (`conversation_url` and friends) rewritten to that prefix so the event WebSocket lands on the proxy. This is what makes the browser work at all: harness-api has no CORS, the tunnel needs a Node process, and the token must stay off the page. The routes are **mounted by default when a key is configured, or on a loopback bind** (`MARS_WEB=0` turns them off; both dev launchers set it on the static child so only the browser-facing ingress hosts a bridge, and Electron passes `marsWebBridge: false` so none runs there) and want the server's session key on every request: the renderer sends it as `X-Session-API-Key` on `/mars/rpc/*` and gets an `HttpOnly; SameSite=Strict; Path=/mars` cookie back, which the browser attaches on its own to the proxied REST calls and the WebSocket upgrade (the one request a browser cannot put a header on). The key is `MARS_WEB_KEY`, else the server's `--session-api-key` (`dev-with-automation` hands the stack's key to `ingress.mjs`); with neither, `mountMarsWebBridge` mounts only on a loopback bind, where a `Host` check stops DNS rebinding. Only `conversation_url` fields are rewritten (a URL inside a message is content), JSON past 8 MB streams through untouched, `Cookie` and the key header never reach the session host, a malformed session path is a 400, an upstream WebSocket the browser abandoned mid-handshake is terminated, and `dispose()` closes both ends of every proxied WebSocket. Credentials are in-memory (no keychain; `MARS_TOKEN` seeds one at startup), OAuth is not offered (`canUseOAuth: false`), and cross-origin requests are refused.
- **Stop and delete are confirmed, destructive, and gated**: Stop (`destroySession`) ends the session and its sandbox through `DELETE /v2/agents/sessions/{id}`, detaching any live connection first; Delete agent (`deleteAgentConfig`) soft-deletes the config through `DELETE /v2/agents/configs/{id}`. harness-api does not refuse a delete while sessions run, so the renderer only enables it once none of the agent's sessions is live (paused counts as live). Both sit behind `ConfirmationModal` and ride the same IPC / web-RPC surface as pause. In a session row the main action (Connect / Resume and connect / Open) is rightmost with Stop directly left of it. Removing a MARS backend in Manage Backends opens `MarsBackendRemovalModal` instead of the generic confirmation: "Disconnect only" (the session keeps running and billing) or "Stop session" (destroy first, then remove; a refused destroy keeps the backend and shows the error), and Manage Backends ignores Escape / outside clicks while it is open.
- **One backend per session**: connecting registers an ordinary `kind: "local"` backend named after the session (`buildMarsBackendName`) whose `host` is the loopback tunnel (in the web build, the server's `/mars/sessions/<id>` proxy), carrying `marsSessionId` / `marsConfigId`. The backend record persists while tunnels and (in the web build) credentials do not, so `useRestoreMarsTunnels` reconnects the active MARS backend once a usable DigitalOcean connection exists β€” after sign-in, not before β€” and Manage Backends keeps a MARS backend selectable while its health is red, since selecting it is what reconnects it. The far end is a real agent-server, so conversations, files, and the terminal work unmodified. Connect logic is shared through `useConnectMarsSession()` (`src/hooks/use-connect-mars-session.ts`), which lands the user in the session's most recent conversation (or a new chat) with the URL pinned to the new backend.
- **Server-side ownership**: tunnels, the harness-api REST client, OAuth, and credentials live in a Node process β€” the Electron main process on desktop, the web server in the web build (`scripts/mars-tunnel-bridge.mjs`, `tunnel-client.mjs`, `tunnel-registry.mjs`, `mars-api.mjs`, `mars-oauth.mjs`, `mars-credentials.mjs`) β€” and reach the renderer only via `window.marsBridge` (`electron/preload-main.cjs`, or `/mars/rpc/*`). harness-api sends no CORS headers and tokens must never reach the page, so do not move these calls into the renderer.