Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(view): guard every visualizer route, not just /__ix/remap

KageBinary4aef8f29b49a
diff --git a/ix-cli/src/cli/__tests__/view-server.test.ts b/ix-cli/src/cli/__tests__/view-server.test.ts
index 26304dfc..300d9510 100644
--- a/ix-cli/src/cli/__tests__/view-server.test.ts
+++ b/ix-cli/src/cli/__tests__/view-server.test.ts
@@ -8,7 +8,7 @@ import { join } from "node:path";
import { createServer } from "node:net";
import { Script } from "node:vm";
import * as http from "node:http";
-import { browserUrl, runningInstanceLines, serverRuntimeArgs, serverScript } from "../commands/view.js";
+import { browserOpener, browserUrl, runningInstanceLines, serverRuntimeArgs, serverScript } from "../commands/view.js";
interface StartServerOptions {
workspaceId?: string;
@@ -289,6 +289,108 @@ describe("view server (/__ix/remap)", () => {
}
});
+ /**
+ * Run `body` against a server proxying to a recording fake backend, then put
+ * the default server back. `env` reaches the server process.
+ */
+ async function withBackend(
+ env: Record<string, string>,
+ body: (seen: http.IncomingHttpHeaders[]) => Promise<void>,
+ ): Promise<void> {
+ const seen: http.IncomingHttpHeaders[] = [];
+ const backend = http.createServer((req, res) => {
+ seen.push(req.headers);
+ req.resume();
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end('{"ok":true}');
+ });
+ await new Promise<void>((resolve, reject) => {
+ backend.once("error", reject);
+ backend.listen(0, "127.0.0.1", resolve);
+ });
+ const address = backend.address();
+ if (!address || typeof address === "string") throw new Error("backend did not bind a TCP port");
+ try {
+ await startServer(env, mapRoot, { backendUrl: `http://127.0.0.1:${address.port}` });
+ await body(seen);
+ } finally {
+ await stopServer();
+ await new Promise<void>((resolve, reject) => backend.close((err) => (err ? reject(err) : resolve())));
+ await startServer({ STUB_EXIT: "0" });
+ }
+ }
+
+ /** A request with headers fetch will not send (Host), answered with its status. */
+ const rawStatus = (method: string, path: string, headers: Record<string, string>) =>
+ new Promise<number>((resolve, reject) => {
+ const req = http.request({ host: "127.0.0.1", port, path, method, headers }, (res) => {
+ res.resume();
+ res.on("end", () => resolve(res.statusCode ?? 0));
+ });
+ req.on("error", reject);
+ req.end();
+ });
+
+ it("refuses a cross-origin POST to the /v1 proxy without reaching the backend", async () => {
+ await withBackend({}, async (seen) => {
+ const res = await post("/v1/reset", { origin: "https://evil.example" });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ ok: false, error: "forbidden: loopback only" });
+ expect(seen).toHaveLength(0);
+ });
+ });
+
+ it("refuses a foreign Host on the /v1 proxy and on static files (DNS rebinding)", async () => {
+ await withBackend({}, async (seen) => {
+ expect(await rawStatus("GET", "/v1/health", { host: "attacker.example" })).toBe(403);
+ expect(await rawStatus("POST", "/v1/reset", { host: `attacker.example:${port}` })).toBe(403);
+ expect(await rawStatus("GET", "/", { host: "attacker.example" })).toBe(403);
+ expect(seen).toHaveLength(0);
+ });
+ });
+
+ it("refuses a request the browser marks cross-site, even with no Origin", async () => {
+ await withBackend({}, async (seen) => {
+ const res = await fetch(`http://127.0.0.1:${port}/v1/health`, { headers: { "sec-fetch-site": "cross-site" } });
+ expect(res.status).toBe(403);
+ expect(seen).toHaveLength(0);
+ });
+ });
+
+ it("still serves the visualizer and proxies its same-origin reads", async () => {
+ await withBackend({}, async (seen) => {
+ const page = await fetch(`http://127.0.0.1:${port}/`, { headers: { "sec-fetch-site": "none" } });
+ expect(page.status).toBe(200);
+ expect(await page.text()).toContain("fake compass");
+ const res = await fetch(`http://127.0.0.1:${port}/v1/health`, {
+ headers: { origin: `http://localhost:${port}`, "sec-fetch-site": "same-origin" },
+ });
+ expect(res.status).toBe(200);
+ expect(seen).toHaveLength(1);
+ });
+ });
+
+ it("sends the backend token and never the caller's own credentials or origin", async () => {
+ await withBackend({ IX_VIEW_BACKEND_TOKEN: "tok-123" }, async (seen) => {
+ const res = await fetch(`http://127.0.0.1:${port}/v1/search`, {
+ method: "POST",
+ headers: { authorization: "Bearer caller", origin: `http://127.0.0.1:${port}`, "content-type": "application/json" },
+ body: "{}",
+ });
+ expect(res.status).toBe(200);
+ expect(seen[0].authorization).toBe("Bearer tok-123");
+ expect(seen[0].origin).toBeUndefined();
+ });
+ });
+
+ it("forwards no Authorization at all while there is no token", async () => {
+ await withBackend({ IX_VIEW_BACKEND_TOKEN: "" }, async (seen) => {
+ const res = await fetch(`http://127.0.0.1:${port}/v1/health`, { headers: { authorization: "Bearer caller" } });
+ expect(res.status).toBe(200);
+ expect(seen[0].authorization).toBeUndefined();
+ });
+ });
+
it("accepts a same-origin loopback Origin", async () => {
const res = await post("/__ix/remap", { origin: `http://localhost:${port}`, host: `127.0.0.1:${port}` });
expect(res.status).toBe(200);
@@ -547,3 +649,13 @@ describe("generated server script", () => {
expect(script).not.toContain("\\");
});
});
+
+describe("browserOpener", () => {
+ // The URL is one argument to a program, never part of a shell command line.
+ it("passes the URL as a single argument on every platform", () => {
+ const url = "http://localhost:4173/?ix=abc;rm -rf ~";
+ expect(browserOpener(url, "darwin")).toEqual(["open", [url]]);
+ expect(browserOpener(url, "linux")).toEqual(["xdg-open", [url]]);
+ expect(browserOpener(url, "win32")).toEqual(["explorer.exe", [url]]);
+ });
+});
diff --git a/ix-cli/src/cli/commands/view.ts b/ix-cli/src/cli/commands/view.ts
index 6ada996f..8e8e3875 100644
--- a/ix-cli/src/cli/commands/view.ts
+++ b/ix-cli/src/cli/commands/view.ts
@@ -1,7 +1,7 @@
// Copyright 2026 Ix Infrastructure Inc.
import { Command } from "commander";
-import { execSync, spawn } from "child_process";
+import { execFile, spawn } from "child_process";
import {
existsSync,
readFileSync,
@@ -364,14 +364,62 @@ const cacheControl = (f) =>
? "public, max-age=31536000, immutable"
: "no-store";
+// The backend token, passed in the environment rather than argv so other local
+// users cannot read it from the process list. Empty until the CLI has one.
+const BACKEND_TOKEN = process.env.IX_VIEW_BACKEND_TOKEN || "";
+
+const isLoopbackName = (h) => h === "localhost" || h === "127.0.0.1" || h === "[::1]";
+
+// Loopback-only, for every request: the /v1 proxy forwards to a backend that
+// can reset the graph, /__ix/remap shells out with the user's privileges, and
+// static files are the user's. Rejects a foreign Host (DNS rebinding), an
+// Origin other than this server's own (CSRF from any other site, including
+// another localhost port: a simple POST needs no preflight) and a request the
+// browser marks cross-site. Browsers send Origin on cross-site POSTs; curl and
+// same-origin reads either omit it or send this server's own. The Origin is
+// parsed with the URL API rather than a regex because this snippet lives
+// inside a template literal and regex backslashes would be consumed every time
+// the server is regenerated by ix view start.
+function forbiddenReason(req) {
+ // Strip the port, keeping a bracketed IPv6 literal intact ([::1]:8080 -> [::1]).
+ let host = (req.headers.host || "").toLowerCase();
+ host = host.startsWith("[") ? host.slice(0, host.indexOf("]") + 1) : host.split(":")[0];
+ if (!isLoopbackName(host)) return "host";
+ const origin = req.headers.origin;
+ if (origin) {
+ try {
+ const u = new URL(origin);
+ const own = (u.protocol === "http:" || u.protocol === "https:") &&
+ isLoopbackName(u.hostname) && u.port === String(PORT);
+ if (!own) return "origin";
+ } catch {
+ return "origin";
+ }
+ }
+ if (String(req.headers["sec-fetch-site"] || "").toLowerCase() === "cross-site") return "cross-site";
+ return null;
+}
+
const server = http.createServer((req, res) => {
const parsed = url.parse(req.url);
const pathname = parsed.pathname || "/";
+ if (forbiddenReason(req)) {
+ req.resume();
+ res.writeHead(403, { "Content-Type": "application/json", "Cache-Control": "no-store" });
+ res.end(JSON.stringify({ ok: false, error: "forbidden: loopback only" }));
+ return;
+ }
+
// Proxy /v1 requests to backend
if (pathname.startsWith("/v1")) {
const backendUrl = BACKEND + pathname + (parsed.search || "");
const proxyHeaders = { ...req.headers, host: "localhost:8090" };
+ // The backend authenticates this server, not the browser: never forward a
+ // caller's own credentials or origin, and add the token when there is one.
+ delete proxyHeaders.authorization;
+ delete proxyHeaders.origin;
+ if (BACKEND_TOKEN) proxyHeaders.authorization = "Bearer " + BACKEND_TOKEN;
// Scope every proxied read to the workspace ix view was launched in, so the
// System Compass visualiser isolates by workspace without the browser app
// knowing anything about workspaces. The backend reads X-Ix-Workspace as a
@@ -418,41 +466,9 @@ const server = http.createServer((req, res) => {
// Real /__ix/remap - rebuild the code map for the workspace this visualizer
// was launched from (its cwd), by running the CLI's map command against it. The
- // stock endpoint was a stub that returned the SPA HTML.
- //
- // Loopback-only: this endpoint shells out with the user's privileges, so
- // reject cross-site requests (CSRF / DNS-rebinding). Browsers send Origin on
- // cross-site POSTs; curl and same-origin fetches either omit it or send a
- // loopback origin. The Origin is parsed with the URL API rather than a regex
- // because this snippet lives inside a template literal and regex backslashes
- // would be consumed every time the server is regenerated by ix view start.
+ // stock endpoint was a stub that returned the SPA HTML. Loopback-only, like
+ // every route: forbiddenReason has already run.
if (pathname === "/__ix/remap" && req.method === "POST") {
- const origin = req.headers.origin || "";
- // Strip the port, keeping a bracketed IPv6 literal intact ([::1]:8080 -> [::1]).
- let host = (req.headers.host || "").toLowerCase();
- host = host.startsWith("[") ? host.slice(0, host.indexOf("]") + 1) : host.split(":")[0];
- const loopbackHost = host === "localhost" || host === "127.0.0.1" || host === "[::1]";
- let loopbackOrigin = !origin;
- if (origin) {
- try {
- const u = new URL(origin);
- loopbackOrigin =
- (u.protocol === "http:" || u.protocol === "https:") &&
- (u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]") &&
- // Our own port, not merely some loopback one. Any page served on any
- // other localhost port — a dev server, a local docs site — can send a
- // simple POST with no preflight, and accepting the whole loopback
- // interface as one origin let it trigger a remap.
- u.port === String(PORT);
- } catch {
- loopbackOrigin = false;
- }
- }
- if (!loopbackHost || !loopbackOrigin) {
- res.writeHead(403, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ ok: false, error: "forbidden: loopback only" }));
- return;
- }
// Nothing reads the request body, but leaving it unconsumed holds the
// stream open for the whole map.
req.resume();
@@ -605,19 +621,30 @@ export function browserUrl(serverUrl: string, token: string = CACHE_BUST): strin
return `${serverUrl}/?ix=${token}`;
}
+/**
+ * The opener command for this platform, as a program and its arguments: no
+ * shell ever parses the URL. Windows uses explorer.exe rather than cmd's
+ * `start`, which would hand the URL to cmd's parser again.
+ */
+export function browserOpener(url: string, plat: NodeJS.Platform = platform()): [string, string[]] {
+ if (plat === "darwin") return ["open", [url]];
+ if (plat === "win32") return ["explorer.exe", [url]];
+ return ["xdg-open", [url]];
+}
+
function openBrowser(url: string): void {
- try {
- const plat = platform();
- if (plat === "darwin") {
- execSync(`open ${url}`, { stdio: "ignore" });
- } else if (plat === "win32") {
- execSync(`start ${url}`, { stdio: "ignore" });
- } else {
- execSync(`xdg-open ${url}`, { stdio: "ignore" });
- }
- } catch {
- // Non-critical
- }
+ const [cmd, args] = browserOpener(url);
+ // Non-critical: a missing opener just leaves the printed URL.
+ execFile(cmd, args, { windowsHide: true }, () => {});
+}
+
+/**
+ * The token the visualizer's /v1 proxy sends to the backend. For now only an
+ * explicit IX_TOKEN; once the CLI stores a local token (SEC-02) it comes from
+ * there. Handed to the server through its environment, never argv.
+ */
+function viewBackendToken(): string {
+ return process.env.IX_TOKEN ?? "";
}
export function registerViewCommand(program: Command): void {
@@ -751,6 +778,7 @@ export function registerViewCommand(program: Command): void {
], {
detached: true,
stdio: "ignore",
+ env: { ...process.env, IX_VIEW_BACKEND_TOKEN: viewBackendToken() },
});
child.unref();