Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(static-server): HTML-escape injected runtime config and set Cache-Control: no-store on credential injection (#17175)

Mohd Quamar Tyagi28464621d879
diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.ts
index 0882d6b592..e57d21d4c0 100644
--- a/__tests__/scripts/static-server.test.ts
+++ b/__tests__/scripts/static-server.test.ts
@@ -4,7 +4,11 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { parseArgs, startStaticServer } from "../../scripts/static-server.mjs";
+import {
+ parseArgs,
+ serializeForInlineScript,
+ startStaticServer,
+} from "../../scripts/static-server.mjs";
describe("static-server.mjs", () => {
const servers: Server[] = [];
@@ -197,6 +201,31 @@ describe("static-server.mjs", () => {
});
});
+ describe("serializeForInlineScript", () => {
+ it("escapes '<' and '>' to prevent breaking out of script tags", () => {
+ const input = "</script><script>alert(1)</script>";
+ const result = serializeForInlineScript(input);
+ expect(result).not.toContain("<");
+ expect(result).not.toContain(">");
+ expect(result).toBe('"\\u003c/script\\u003e\\u003cscript\\u003ealert(1)\\u003c/script\\u003e"');
+ });
+
+ it("escapes line and paragraph separators U+2028 and U+2029", () => {
+ const input = "line1\u2028line2\u2029line3";
+ const result = serializeForInlineScript(input);
+ expect(result).toContain("\\u2028");
+ expect(result).toContain("\\u2029");
+ expect(result).not.toContain("\u2028");
+ expect(result).not.toContain("\u2029");
+ });
+
+ it("serializes complex objects properly with escaping", () => {
+ const input = { key: "<test>", count: 42 };
+ const result = serializeForInlineScript(input);
+ expect(result).toBe('{"key":"\\u003ctest\\u003e","count":42}');
+ });
+ });
+
describe("--vscode-base-path", () => {
it("parses the prefix and normalizes a trailing slash", () => {
const config = parseArgs([
@@ -655,7 +684,7 @@ describe("static-server.mjs", () => {
expect(body).not.toContain("should-not-inject");
});
- it("sets Cache-Control: no-cache for injected index.html", async () => {
+ it("sets Cache-Control: no-store when session key is injected", async () => {
const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));
tempDirs.push(buildDir);
writeFileSync(
@@ -666,9 +695,51 @@ describe("static-server.mjs", () => {
const origin = await startServerWithKey(buildDir, "cache-test-key");
const response = await fetch(`${origin}/`);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ });
+
+ it("sets Cache-Control: no-cache when session key is not present but other config is injected", 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: {},
+ authRequired: true,
+ });
+ 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}/`);
+
expect(response.headers.get("cache-control")).toBe("no-cache");
});
+ 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);
+ writeFileSync(
+ path.join(buildDir, "index.html"),
+ "<html><head></head><body>app</body></html>",
+ );
+
+ const payload = '</script><script>alert("xss")</script>';
+ const origin = await startServerWithKey(buildDir, payload);
+ const response = await fetch(`${origin}/`);
+ const body = await response.text();
+
+ expect(body).not.toContain("</script><script>");
+ expect(body).toContain("\\u003c/script\\u003e\\u003cscript\\u003e");
+ });
+
it("does not inject when sessionApiKey is null", async () => {
const buildDir = mkdtempSync(path.join(tmpdir(), "agent-canvas-build-"));
tempDirs.push(buildDir);
diff --git a/scripts/static-server.mjs b/scripts/static-server.mjs
index a0c0812c7b..b71bbb0e3b 100644
--- a/scripts/static-server.mjs
+++ b/scripts/static-server.mjs
@@ -345,6 +345,23 @@ 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")
+ .replace(/>/g, "\\u003e")
+ .replace(/\u2028/g, "\\u2028")
+ .replace(/\u2029/g, "\\u2029");
+}
+
function makeConfigInjectionScript(
sessionApiKey,
authRequired,
@@ -357,7 +374,7 @@ function makeConfigInjectionScript(
const parts = [];
if (sessionApiKey) {
- const keyLiteral = JSON.stringify(sessionApiKey);
+ const keyLiteral = serializeForInlineScript(sessionApiKey);
// Window global β€” read at module init by getBakedSessionApiKey().
// Set first so it's available even if the localStorage write throws.
parts.push(`window.__AGENT_CANVAS_SESSION_API_KEY__=${keyLiteral};`);
@@ -383,28 +400,28 @@ 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. JSON.stringify produces a safe JS
+ // VITE_RUNTIME_SERVICES_INFO env var. serializeForInlineScript produces a safe JS
// string literal for the inline <script>.
parts.push(
- `window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__=${JSON.stringify(runtimeServicesInfo)};`,
+ `window.__AGENT_CANVAS_RUNTIME_SERVICES_INFO__=${serializeForInlineScript(runtimeServicesInfo)};`,
);
}
if (lockToCloud) {
parts.push(
- `window.__AGENT_CANVAS_LOCK_TO_CLOUD__=${JSON.stringify(lockToCloud)};`,
+ `window.__AGENT_CANVAS_LOCK_TO_CLOUD__=${serializeForInlineScript(lockToCloud)};`,
);
}
if (basePath && basePath !== "/") {
parts.push(
- `window.__AGENT_CANVAS_BASE_PATH__=${JSON.stringify(basePath)};`,
+ `window.__AGENT_CANVAS_BASE_PATH__=${serializeForInlineScript(basePath)};`,
);
}
if (vscodeBasePath) {
parts.push(
- `window.__AGENT_CANVAS_VSCODE_BASE_PATH__=${JSON.stringify(vscodeBasePath)};`,
+ `window.__AGENT_CANVAS_VSCODE_BASE_PATH__=${serializeForInlineScript(vscodeBasePath)};`,
);
}
@@ -463,7 +480,7 @@ async function serveInjectedIndexHtml(
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": buf.length,
- "Cache-Control": "no-cache",
+ "Cache-Control": sessionApiKey ? "no-store" : "no-cache",
});
if (req.method === "HEAD") {
res.end();