Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(security): opt-in local token, no ArangoDB host port (SEC-02)

KageBinary21b1ab993908
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c1b1d09f..d3c5f0a0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -182,8 +182,8 @@ clone.
**You do not need the backend source to work on this repository.** Everything in
the `ix` CLI is developed against the published backend image, which is public and
pullable anonymously. `./scripts/backend.sh up` in [Local Setup](#local-setup)
-starts it (`ghcr.io/ix-infrastructure/ix-memory-layer:latest` plus ArangoDB, on
-`127.0.0.1:8090` and `:8529`). It installs nothing itself — it runs
+starts it (`ghcr.io/ix-infrastructure/ix-memory-layer:latest` on
+`127.0.0.1:8090`, plus ArangoDB with no host port). It installs nothing itself — it runs
`docker compose -f docker-compose.standalone.yml` against an already-installed
Docker. What the `curl | sh` *installer* puts on the machine is a separate list:
[docs/prerequisites.md](docs/prerequisites.md).
diff --git a/docker-compose.standalone.yml b/docker-compose.standalone.yml
index 5f55c7be..281ea4e2 100644
--- a/docker-compose.standalone.yml
+++ b/docker-compose.standalone.yml
@@ -19,8 +19,11 @@ services:
image: arangodb:3.12.11
networks:
- backend
- ports:
- - "127.0.0.1:8529:8529"
+ # No host port. ArangoDB runs without authentication, so a published port
+ # let any local process read or wipe the graph without going through the
+ # memory layer. Only memory-layer reaches it, over the compose network.
+ # For the web UI, publish it yourself in docker-compose.override.yml next
+ # to this file (`ix docker` applies that file); see docs/prerequisites.md.
environment:
ARANGO_NO_AUTH: "1"
# `--vector-index` is the current name; it was `--experimental-vector-index`
@@ -51,6 +54,9 @@ services:
ARANGO_USER: root
ARANGO_PASSWORD: ""
PORT: "8090"
+ # Empty: the backend requires no token. `ix docker start --local-token`
+ # writes one into .env next to this file and the CLI sends it.
+ IX_LOCAL_TOKEN: ${IX_LOCAL_TOKEN:-}
depends_on:
arangodb:
condition: service_healthy
diff --git a/docs-site/src/content/docs/concepts/how-it-works.md b/docs-site/src/content/docs/concepts/how-it-works.md
index c8a84c68..adc5b680 100644
--- a/docs-site/src/content/docs/concepts/how-it-works.md
+++ b/docs-site/src/content/docs/concepts/how-it-works.md
@@ -21,9 +21,9 @@ The graph is stored in a backend that runs in Docker on your machine:
| Service | Port | Role |
|---|---|---|
| **Ix Memory Layer** | `127.0.0.1:8090` | The HTTP API every client talks to |
-| **ArangoDB 3.12** | `127.0.0.1:8529` | The graph database behind it |
+| **ArangoDB 3.12** | none (Compose network only) | The graph database behind it |
-Both bind to localhost only, so with the default local backend your code and graph stay on your machine. The backend ships as a released Docker image
+The memory layer binds to localhost only and ArangoDB publishes no port at all, so with the default local backend your code and graph stay on your machine. The backend ships as a released Docker image
(`ghcr.io/ix-infrastructure/ix-memory-layer`). Start it with `ix docker start` and check it with `ix status`.
## Three clients, one graph
diff --git a/docs-site/src/content/docs/reference/commands.md b/docs-site/src/content/docs/reference/commands.md
index b309b5ad..23ccc152 100644
--- a/docs-site/src/content/docs/reference/commands.md
+++ b/docs-site/src/content/docs/reference/commands.md
@@ -86,6 +86,7 @@ before it exits: `ix map` re-ingests the workspace, and so does `ix ingest` when
| `ix status` | Checks the backend is reachable |
| `ix doctor` | Checks server, database and graph integrity |
| `ix docker start` / `stop` / `restart` | Starts, stops or restarts the local backend containers |
+| `ix docker start --local-token` | Makes the local backend require a bearer token, which the CLI stores and sends (`--no-local-token` turns it off). See [Local token](/reference/configuration/#local-token) |
| `ix docker status` / `logs` | Shows container health, or tails the backend's logs |
| `ix view` | Opens the [Compass](/guides/compass/) visualizer |
| `ix mcp` | Runs the [MCP server](/integrations/mcp/). `ix mcp install` registers it with your clients |
diff --git a/docs-site/src/content/docs/reference/configuration.md b/docs-site/src/content/docs/reference/configuration.md
index 5ec387c6..329c8eb8 100644
--- a/docs-site/src/content/docs/reference/configuration.md
+++ b/docs-site/src/content/docs/reference/configuration.md
@@ -19,6 +19,7 @@ ix config set format llm # set a value
|---|---|
| `IX_HOME` | Relocates everything under `~/.ix`, configuration included. Useful for giving a CI job or a second install its own state. It's read at use, not at install, so move `~/.ix` there rather than expecting the old configuration to be found |
| `IX_FORMAT` | Default output format: `text`, `json` or `llm`. Overrides the config file. `--format` overrides it |
+| `IX_TOKEN=<token>` | Bearer token sent to the backend on every request, to any endpoint. Overrides the stored local token (see [Local token](#local-token)) |
| `IX_DEBUG=1` | Prints full stack traces on errors |
| `IX_MCP_SUBPROCESS=1` | Runs each MCP tool call in its own `ix` process |
| `IX_COMMIT_FAILURE_LIMIT=<n>` | Consecutive failed commits before `ix map` stops (default 5). `0` never stops |
@@ -43,7 +44,7 @@ These apply to the agent skill's `bootstrap.sh`:
| Path | Contents |
|---|---|
| `~/.ix/config.yaml` | CLI configuration |
-| `~/.ix/backend/` | Docker Compose file for the local backend |
+| `~/.ix/backend/` | Docker Compose file for the local backend, its `.env` (the local token, mode 0600) and an optional `docker-compose.override.yml` |
| `~/.ix/cli/` | The installed CLI |
| `~/.ix/cli/compass/` | Compass assets, fetched by `ix upgrade` |
@@ -54,5 +55,25 @@ All services bind to `127.0.0.1` only.
| Port | Service |
|---|---|
| `8090` | Ix Memory Layer (the HTTP API) |
-| `8529` | ArangoDB |
| `8080` | Compass (`ix view`), configurable with `--port` |
+
+ArangoDB has no host port: it runs without authentication, so only the memory layer reaches it, over the Compose network. To use its web UI, publish the port yourself in `~/.ix/backend/docker-compose.override.yml`, which `ix docker` applies, then run `ix docker start`:
+
+```yaml
+services:
+ arangodb:
+ ports:
+ - "127.0.0.1:8529:8529"
+```
+
+## Local token
+
+The backend refuses requests from other hosts, from web pages and with non-JSON bodies. It can also require a bearer token, so that another local process cannot use it without the token in `~/.ix`. This is opt-in for now:
+
+```bash
+ix docker start --local-token # generate a token, store it, restart the backend requiring it
+ix docker start --no-local-token # stop requiring it and forget it
+ix doctor # "Backend token" says whether it is required and accepted
+```
+
+The token is stored as `auth.local_token` in `~/.ix/config.yaml` and written to `~/.ix/backend/.env` for Compose. The CLI and `ix view` send it only to a local endpoint; set `IX_TOKEN` to send a token to any other backend.
diff --git a/docs/prerequisites.md b/docs/prerequisites.md
index a213e617..f71747e3 100644
--- a/docs/prerequisites.md
+++ b/docs/prerequisites.md
@@ -88,7 +88,9 @@ docker-compose>=2.0
# STEP 3: Backend services (managed by Docker, no manual install)
# ============================================================================
-# ArangoDB 3.12 — graph database (Docker container on 127.0.0.1:8529)
+# ArangoDB 3.12 — graph database (Docker container, no host port; only the
+# memory layer reaches it. Publish 8529 in ~/.ix/backend/docker-compose.override.yml
+# if you want its web UI: services: { arangodb: { ports: ["127.0.0.1:8529:8529"] } })
arangodb==3.12
# Ix Memory Layer — Scala/JVM HTTP API (Docker container on 127.0.0.1:8090)
@@ -146,5 +148,5 @@ ripgrep>=13
# expecting the old configuration to be found.
#
# Wrapper: /usr/local/bin/ix (if writable) or ~/.local/bin/ix (fallback)
-# Ports: 8090 (Memory Layer), 8529 (ArangoDB) — localhost only
+# Ports: 8090 (Memory Layer) — localhost only. ArangoDB publishes none.
```
diff --git a/ix-cli/src/cli/__tests__/docker-compose-source.test.ts b/ix-cli/src/cli/__tests__/docker-compose-source.test.ts
index 4cf19d92..2765262f 100644
--- a/ix-cli/src/cli/__tests__/docker-compose-source.test.ts
+++ b/ix-cli/src/cli/__tests__/docker-compose-source.test.ts
@@ -1,7 +1,7 @@
// Copyright 2026 Ix Infrastructure Inc.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -53,11 +53,11 @@ afterEach(() => {
rmSync(t, { recursive: true, force: true });
});
-async function dockerStart(): Promise<void> {
+async function dockerStart(...flags: string[]): Promise<void> {
const { registerDockerCommand } = await import("../commands/docker.js");
const program = new Command().exitOverride();
registerDockerCommand(program);
- await program.parseAsync(["docker", "start"], { from: "user" });
+ await program.parseAsync(["docker", "start", ...flags], { from: "user" });
}
const log = () => (existsSync(join(t, "docker.log")) ? readFileSync(join(t, "docker.log"), "utf8") : "");
@@ -72,7 +72,7 @@ describe("ix docker start: where the compose file comes from", () => {
const local = join(t, "ix-home", "backend", "docker-compose.yml");
expect(readFileSync(local, "utf8")).toBe(readFileSync(REPO_COMPOSE, "utf8"));
- expect(log()).toContain(`compose -f ${local} up -d --pull always`);
+ expect(log()).toContain(`compose --env-file ${join(t, "ix-home", "backend", ".env")} -f ${local} up -d --pull always`);
expect(log()).not.toContain(join(t, "repo"));
});
@@ -91,6 +91,71 @@ describe("ix docker start: where the compose file comes from", () => {
});
});
+describe("ix docker start --local-token", () => {
+ const envFile = () => join(t, "ix-home", "backend", ".env");
+ const config = () => readFileSync(join(t, "ix-home", "config.yaml"), "utf8");
+
+ beforeEach(() => {
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(process.stdout, "write").mockImplementation(() => true);
+ // The capabilities read after start: a backend that now enforces.
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify({ proFeaturesEnabled: false, local_auth: "bearer-v1", local_auth_enforcing: true })));
+ });
+
+ it.skipIf(process.platform === "win32")("is off by default: no token stored, an empty one passed to compose", async () => {
+ process.env.IX_BUNDLED_COMPOSE = REPO_COMPOSE;
+ await dockerStart();
+ expect(readFileSync(envFile(), "utf8")).toBe("IX_LOCAL_TOKEN=\n");
+ expect(existsSync(join(t, "ix-home", "config.yaml"))).toBe(false);
+ });
+
+ it.skipIf(process.platform === "win32")("stores a token, writes it to a 0600 .env and recreates the backend even when healthy", async () => {
+ process.env.IX_BUNDLED_COMPOSE = REPO_COMPOSE;
+ writeFileSync(join(t, "up"), ""); // already healthy
+ await dockerStart("--local-token");
+
+ const token = /local_token: (\w+)/.exec(config())?.[1];
+ expect(token).toMatch(/^[0-9a-f]{64}$/);
+ expect(readFileSync(envFile(), "utf8")).toBe(`IX_LOCAL_TOKEN=${token}\n`);
+ expect(statSync(envFile()).mode & 0o777).toBe(0o600);
+ expect(log()).toMatch(/compose --env-file \S+ -f \S+ up -d --pull always/);
+
+ // Running it again keeps the same token.
+ await dockerStart("--local-token");
+ expect(config()).toContain(`local_token: ${token}`);
+
+ // --no-local-token forgets it and passes an empty one.
+ await dockerStart("--no-local-token");
+ expect(config()).not.toContain("local_token");
+ expect(readFileSync(envFile(), "utf8")).toBe("IX_LOCAL_TOKEN=\n");
+ });
+
+ it.skipIf(process.platform === "win32")("refuses, running nothing, when the installed compose predates the token", async () => {
+ mkdirSync(join(t, "ix-home", "backend"), { recursive: true });
+ writeFileSync(join(t, "ix-home", "backend", "docker-compose.yml"), "services:\n memory-layer:\n image: x\n");
+ const errors: string[] = [];
+ vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { errors.push(a.join(" ")); });
+ vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
+ throw new Error(`exit ${code}`);
+ }) as never);
+
+ await expect(dockerStart("--local-token")).rejects.toThrow("exit 1");
+ expect(errors.join("\n")).toMatch(/does not pass IX_LOCAL_TOKEN/);
+ expect(log()).toBe("");
+ expect(existsSync(join(t, "ix-home", "config.yaml"))).toBe(false);
+ });
+
+ it.skipIf(process.platform === "win32")("applies the user's override file", async () => {
+ process.env.IX_BUNDLED_COMPOSE = REPO_COMPOSE;
+ mkdirSync(join(t, "ix-home", "backend"), { recursive: true });
+ const override = join(t, "ix-home", "backend", "docker-compose.override.yml");
+ writeFileSync(override, "services:\n arangodb:\n ports: [\"127.0.0.1:8529:8529\"]\n");
+ await dockerStart();
+ expect(log()).toContain(`-f ${override} up -d`);
+ });
+});
+
describe("isIxArangoVolume", () => {
const labels = (project: string, volume: string) =>
new Map([["com.docker.compose.project", project], ["com.docker.compose.volume", volume]]);
diff --git a/ix-cli/src/cli/__tests__/local-token.test.ts b/ix-cli/src/cli/__tests__/local-token.test.ts
new file mode 100644
index 00000000..01071010
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/local-token.test.ts
@@ -0,0 +1,252 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { createServer, type IncomingHttpHeaders, type Server } from "node:http";
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { parse } from "yaml";
+
+/**
+ * SEC-02: the backend can require a bearer token (IX_LOCAL_TOKEN, local-auth
+ * v1). The CLI sends one through a single header builder whenever it has one,
+ * stores it opt-in, sends the stored one only to a loopback endpoint, and says
+ * how to fix a 401 instead of printing the raw body.
+ */
+
+const TOKEN = "a".repeat(64);
+const REPO_COMPOSE = resolve(fileURLToPath(new URL("../../../../docker-compose.standalone.yml", import.meta.url)));
+
+// A strict backend: every request without `Authorization: Bearer TOKEN` gets
+// the guard's 401, exactly as LocalRequestGuard answers it.
+let server: Server;
+let endpoint: string;
+const seen: Array<{ method?: string; url?: string; headers: IncomingHttpHeaders }> = [];
+
+beforeAll(async () => {
+ server = createServer((req, res) => {
+ seen.push({ method: req.method, url: req.url, headers: req.headers });
+ req.resume();
+ req.on("end", () => {
+ if (req.headers.authorization !== `Bearer ${TOKEN}`) {
+ res.writeHead(401, { "content-type": "application/json", "www-authenticate": 'Bearer realm="ix-memory"' });
+ res.end(JSON.stringify({ error: "unauthorized", code: "local_token_required" }));
+ return;
+ }
+ res.writeHead(200, { "content-type": "application/json" });
+ if (req.url?.startsWith("/v1/capabilities")) {
+ res.end(JSON.stringify({ proFeaturesEnabled: false, local_auth: "bearer-v1", local_auth_enforcing: true }));
+ } else if (req.url?.startsWith("/v1/reset")) {
+ res.end(JSON.stringify({ ok: true, message: "reset" }));
+ } else {
+ res.end(JSON.stringify({ status: "ok", exists: true, nodes: [], results: [] }));
+ }
+ });
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ const addr = server.address();
+ endpoint = `http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : 0}`;
+});
+
+afterAll(async () => {
+ await new Promise<void>((r) => server.close(() => r()));
+});
+
+let home: string;
+let saved: Record<string, string | undefined>;
+
+beforeEach(() => {
+ vi.resetModules();
+ seen.length = 0;
+ home = mkdtempSync(join(tmpdir(), "ix-token-"));
+ saved = { IX_HOME: process.env.IX_HOME, IX_TOKEN: process.env.IX_TOKEN, IX_ENDPOINT: process.env.IX_ENDPOINT };
+ process.env.IX_HOME = home;
+ delete process.env.IX_TOKEN;
+ delete process.env.IX_ENDPOINT;
+});
+
+afterEach(() => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ vi.restoreAllMocks();
+ rmSync(home, { recursive: true, force: true });
+});
+
+function storeToken(token: string): void {
+ writeFileSync(join(home, "config.yaml"), `endpoint: ${endpoint}\nformat: text\nauth:\n local_token: ${token}\n`);
+}
+
+describe("the client sends the token on every request", () => {
+ it("every transport path carries Authorization when the client has a token", async () => {
+ const { IxClient } = await import("../../client/api.js");
+ const client = new IxClient(endpoint, undefined, { token: TOKEN });
+ await client.search("x"); // post()
+ await client.hasIngestBaseline(); // get()
+ await client.ingest("/tmp/x"); // own fetch
+ await client.map(); // own fetch
+ await client.commitPatchBulk([]); // own fetch
+ await client.commitPatch({} as never); // own fetch
+ await client.savingsReset(); // DELETE, no body
+ await client.reset(); // local: synchronous reset route
+ expect(seen.length).toBe(8);
+ for (const r of seen) expect(r.headers.authorization, `${r.method} ${r.url}`).toBe(`Bearer ${TOKEN}`);
+ });
+
+ it("sends no Authorization header without a token, and a 401 becomes LocalTokenRequiredError", async () => {
+ const { IxClient, LocalTokenRequiredError } = await import("../../client/api.js");
+ const client = new IxClient(endpoint);
+ const err = await client.search("x").catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(LocalTokenRequiredError);
+ // The `<status>: <body>` shape callers read codes out of is kept.
+ expect((err as Error).message).toMatch(/^401: .*local_token_required/);
+ expect(seen[0].headers.authorization).toBeUndefined();
+ await expect(client.ingest("/tmp/x")).rejects.toBeInstanceOf(LocalTokenRequiredError);
+ });
+
+ it("a plain 401 without the guard's code stays an ordinary error", async () => {
+ const { httpError, LocalTokenRequiredError } = await import("../../client/api.js");
+ expect(httpError(401, "nope")).not.toBeInstanceOf(LocalTokenRequiredError);
+ expect(httpError(401, "nope").message).toBe("401: nope");
+ expect(httpError(500, '{"code":"local_token_required"}')).not.toBeInstanceOf(LocalTokenRequiredError);
+ });
+
+ it("createClient sends the stored token, and the strict backend answers", async () => {
+ storeToken(TOKEN);
+ const { createClient } = await import("../../client/factory.js");
+ const client = createClient();
+ expect(client.sendsToken).toBe(true);
+ await expect(client.search("x")).resolves.toBeDefined();
+ expect(seen[0].headers.authorization).toBe(`Bearer ${TOKEN}`);
+ });
+
+ it("capabilities() reports a refused token instead of falling back to {}", async () => {
+ const { IxClient, LocalTokenRequiredError } = await import("../../client/api.js");
+ await expect(new IxClient(endpoint).capabilities()).rejects.toBeInstanceOf(LocalTokenRequiredError);
+ // Anything else still falls back, as before.
+ await expect(new IxClient("http://127.0.0.1:1").capabilities()).resolves.toEqual({});
+ });
+});
+
+describe("which token goes where", () => {
+ it("IX_TOKEN wins, and goes to any endpoint", async () => {
+ storeToken("b".repeat(64));
+ process.env.IX_TOKEN = TOKEN;
+ const { getLocalToken } = await import("../config.js");
+ expect(getLocalToken("http://localhost:8090")).toBe(TOKEN);
+ expect(getLocalToken("https://ix.example.com")).toBe(TOKEN);
+ });
+
+ it("the stored token goes only to a loopback endpoint", async () => {
+ storeToken(TOKEN);
+ const { getLocalToken } = await import("../config.js");
+ expect(getLocalToken("http://localhost:8090")).toBe(TOKEN);
+ expect(getLocalToken("http://127.0.0.1:8090")).toBe(TOKEN);
+ expect(getLocalToken("http://[::1]:8090")).toBe(TOKEN);
+ expect(getLocalToken("https://ix.example.com")).toBeUndefined();
+ expect(getLocalToken("http://127.0.0.1.evil.com:8090")).toBeUndefined();
+ });
+
+ it("there is no token until one is asked for", async () => {
+ const { getLocalToken, loadConfig } = await import("../config.js");
+ expect(getLocalToken("http://localhost:8090")).toBeUndefined();
+ expect(loadConfig().auth).toBeUndefined();
+ });
+
+ it("ensureLocalToken generates once, keeps the config private and other keys intact; clearLocalToken forgets it", async () => {
+ writeFileSync(join(home, "config.yaml"), "endpoint: http://localhost:8090\nformat: text\ninstances:\n - name: pro\n");
+ const { ensureLocalToken, clearLocalToken, storedLocalToken } = await import("../config.js");
+ const token = ensureLocalToken();
+ expect(token).toMatch(/^[0-9a-f]{64}$/);
+ expect(ensureLocalToken()).toBe(token);
+ const onDisk = parse(readFileSync(join(home, "config.yaml"), "utf8"));
+ expect(onDisk.auth.local_token).toBe(token);
+ expect(onDisk.instances).toEqual([{ name: "pro" }]);
+ if (process.platform !== "win32") expect(statSync(join(home, "config.yaml")).mode & 0o777).toBe(0o600);
+ clearLocalToken();
+ expect(storedLocalToken()).toBeUndefined();
+ expect(parse(readFileSync(join(home, "config.yaml"), "utf8")).auth).toBeUndefined();
+ });
+});
+
+describe("errors and doctor", () => {
+ it("renders local_token_required with the fix for a local and a remote backend", async () => {
+ const { localTokenRequiredError } = await import("../errors.js");
+ expect(localTokenRequiredError("http://localhost:8090")).toMatchObject({
+ error: "local_token_required",
+ next: expect.stringContaining("ix docker start --local-token"),
+ });
+ expect(localTokenRequiredError("https://ix.example.com").next).toMatch(/IX_TOKEN/);
+ expect(localTokenRequiredError("https://ix.example.com").next).not.toMatch(/ix docker/);
+ });
+
+ it("renderCliError prints the code, not the raw 401 body", async () => {
+ const { LocalTokenRequiredError } = await import("../../client/api.js");
+ const { renderCliError } = await import("../errors.js");
+ const lines: string[] = [];
+ vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { lines.push(a.join(" ")); });
+ vi.spyOn(process.stderr, "write").mockImplementation((s: string | Uint8Array) => { lines.push(String(s)); return true; });
+ vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`exit ${code}`); }) as never);
+ expect(() => renderCliError(new LocalTokenRequiredError('{"error":"unauthorized","code":"local_token_required"}'),
+ false, "http://localhost:8090")).toThrow("exit 1");
+ const out = lines.join("\n");
+ expect(out).toMatch(/requires a token/);
+ expect(out).toMatch(/ix docker start --local-token/);
+ expect(out).not.toMatch(/^Error: 401/m);
+ });
+
+ it("doctor's Backend token check", async () => {
+ const { assessLocalAuth } = await import("../commands/doctor.js");
+ const { LocalTokenRequiredError } = await import("../../client/api.js");
+ const refused = new LocalTokenRequiredError("{}");
+ expect(assessLocalAuth(refused, false, true)).toMatchObject({ ok: false, detail: expect.stringMatching(/has none/) });
+ expect(assessLocalAuth(refused, true, true)).toMatchObject({ ok: false, detail: expect.stringMatching(/refused/) });
+ expect(assessLocalAuth(new Error("fetch failed"), false, true)).toMatchObject({ ok: true, detail: expect.stringMatching(/unreachable/) });
+ expect(assessLocalAuth({ proFeaturesEnabled: false }, false, true)).toMatchObject({ ok: true, detail: expect.stringMatching(/predates/) });
+ expect(assessLocalAuth({ local_auth: "bearer-v1", local_auth_enforcing: true }, true, true)).toMatchObject({ ok: true });
+ expect(assessLocalAuth({ local_auth: "bearer-v1", local_auth_enforcing: false }, true, true)).toMatchObject({ ok: false, warn: true });
+ expect(assessLocalAuth({ local_auth: "bearer-v1", local_auth_enforcing: false }, false, true)).toMatchObject({
+ ok: true, detail: expect.stringMatching(/not required/),
+ });
+ });
+});
+
+describe("the backend compose file", () => {
+ const compose = parse(readFileSync(REPO_COMPOSE, "utf8"));
+
+ it("publishes no ArangoDB port", () => {
+ expect(compose.services.arangodb.ports).toBeUndefined();
+ // The memory layer is still reachable, on loopback only.
+ expect(compose.services["memory-layer"].ports).toEqual(["127.0.0.1:8090:8090"]);
+ });
+
+ it("passes IX_LOCAL_TOKEN to the memory layer, empty by default", async () => {
+ expect(compose.services["memory-layer"].environment.IX_LOCAL_TOKEN).toBe("${IX_LOCAL_TOKEN:-}");
+ const { composeSupportsLocalToken } = await import("../backend-compose.js");
+ expect(composeSupportsLocalToken(readFileSync(REPO_COMPOSE, "utf8"))).toBe(true);
+ expect(composeSupportsLocalToken("services:\n memory-layer:\n image: x\n")).toBe(false);
+ });
+
+ it(".env keeps the user's other lines and replaces only IX_LOCAL_TOKEN", async () => {
+ const { backendEnvContents, writeBackendEnv } = await import("../backend-compose.js");
+ expect(backendEnvContents("", undefined)).toBe("IX_LOCAL_TOKEN=\n");
+ expect(backendEnvContents("FOO=1\nIX_LOCAL_TOKEN=old\nexport IX_LOCAL_TOKEN=older\n", TOKEN))
+ .toBe(`FOO=1\nIX_LOCAL_TOKEN=${TOKEN}\n`);
+ const env = join(home, "backend", ".env");
+ writeBackendEnv(TOKEN, env);
+ expect(readFileSync(env, "utf8")).toBe(`IX_LOCAL_TOKEN=${TOKEN}\n`);
+ if (process.platform !== "win32") expect(statSync(env).mode & 0o777).toBe(0o600);
+ });
+
+ it("reads the arangodb container's health from compose ps, in either output shape", async () => {
+ const { parseArangoHealth } = await import("../backend-compose.js");
+ const row = (service: string, health: string) => JSON.stringify({ Service: service, Health: health, State: "running" });
+ expect(parseArangoHealth("")).toBe("absent");
+ expect(parseArangoHealth(row("arangodb", "healthy"))).toBe("healthy");
+ expect(parseArangoHealth(`${row("memory-layer", "healthy")}\n${row("arangodb", "unhealthy")}`)).toBe("unhealthy");
+ expect(parseArangoHealth(`[${row("arangodb", "starting")}]`)).toBe("starting");
+ expect(parseArangoHealth(row("memory-layer", "healthy"))).toBe("absent");
+ });
+});
diff --git a/ix-cli/src/cli/backend-compose.ts b/ix-cli/src/cli/backend-compose.ts
new file mode 100644
index 00000000..4f381124
--- /dev/null
+++ b/ix-cli/src/cli/backend-compose.ts
@@ -0,0 +1,98 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { storedLocalToken } from "./config.js";
+import { ixHome } from "./ix-home.js";
+
+/**
+ * The files `docker compose` is given for the backend in ~/.ix/backend, shared
+ * by `ix docker` and `ix upgrade` so both start the same stack.
+ */
+
+/** Compose variables for the backend (IX_LOCAL_TOKEN). Mode 0600: it holds the credential. */
+export function backendEnvFile(): string {
+ return join(ixHome(), "backend", ".env");
+}
+
+/**
+ * The user's own additions to the backend compose, applied when present. The
+ * shipped compose does not publish ArangoDB's port; a user who wants its web
+ * UI publishes it here (see docs/prerequisites.md).
+ */
+export function backendOverrideFile(): string {
+ return join(ixHome(), "backend", "docker-compose.override.yml");
+}
+
+/**
+ * `.env` with IX_LOCAL_TOKEN set to `token` (empty: the backend does not
+ * require one). Other lines a user added are kept.
+ */
+export function backendEnvContents(existing: string, token: string | undefined): string {
+ const kept = existing
+ .split(/\r?\n/)
+ .filter((line) => line.trim() !== "" && !/^\s*(export\s+)?IX_LOCAL_TOKEN\s*=/.test(line));
+ return [...kept, `IX_LOCAL_TOKEN=${token ?? ""}`].join("\n") + "\n";
+}
+
+/**
+ * Write ~/.ix/backend/.env for the stored token, atomically and at mode 0600:
+ * it holds the credential. Compose reads it for `${IX_LOCAL_TOKEN}`.
+ */
+export function writeBackendEnv(token: string | undefined, envFile: string = backendEnvFile()): void {
+ let existing = "";
+ try { existing = readFileSync(envFile, "utf-8"); } catch { /* none yet */ }
+ mkdirSync(dirname(envFile), { recursive: true, mode: 0o700 });
+ const tmp = `${envFile}.${process.pid}.tmp`;
+ writeFileSync(tmp, backendEnvContents(existing, token), { mode: 0o600 });
+ try {
+ renameSync(tmp, envFile);
+ } catch (err) {
+ try { rmSync(tmp, { force: true }); } catch { /* best effort */ }
+ throw err;
+ }
+ try { chmodSync(envFile, 0o600); } catch { /* the create mode is the primary guard */ }
+}
+
+/**
+ * The `docker compose` arguments that name the backend's files: the env file
+ * (rewritten from the stored token first, so a token change reaches the next
+ * `up`) and the user's override file when there is one.
+ */
+export function backendComposeArgs(composeFile: string): string[] {
+ const envFile = backendEnvFile();
+ writeBackendEnv(storedLocalToken(), envFile);
+ const args = ["compose", "--env-file", envFile, "-f", composeFile];
+ const override = backendOverrideFile();
+ if (existsSync(override)) args.push("-f", override);
+ return args;
+}
+
+/** Whether a compose file passes IX_LOCAL_TOKEN to the backend (older ones do not). */
+export function composeSupportsLocalToken(composeText: string): boolean {
+ return /\$\{IX_LOCAL_TOKEN\b/.test(composeText);
+}
+
+/**
+ * The arangodb service's health from `docker compose ps --format json`, which
+ * prints one JSON object per line on current Compose and a JSON array on older
+ * releases. "absent" when this compose project runs no arangodb container.
+ */
+export function parseArangoHealth(psOutput: string): "healthy" | "unhealthy" | "starting" | "absent" {
+ const text = psOutput.trim();
+ if (!text) return "absent";
+ let rows: Array<{ Service?: string; Health?: string; State?: string }>;
+ try {
+ const parsed = JSON.parse(text);
+ rows = Array.isArray(parsed) ? parsed : [parsed];
+ } catch {
+ rows = text.split("\n").flatMap((line) => {
+ try { return [JSON.parse(line)]; } catch { return []; }
+ });
+ }
+ const arango = rows.find((r) => r.Service === "arangodb");
+ if (!arango) return "absent";
+ if (arango.Health === "healthy") return "healthy";
+ if (arango.Health === "starting") return "starting";
+ return "unhealthy";
+}
diff --git a/ix-cli/src/cli/commands/docker.ts b/ix-cli/src/cli/commands/docker.ts
index 0f18478d..08bc6143 100644
--- a/ix-cli/src/cli/commands/docker.ts
+++ b/ix-cli/src/cli/commands/docker.ts
@@ -3,17 +3,19 @@
import { Command } from "commander";
import { execFileSync, spawn } from "child_process";
import { createInterface } from "readline";
-import { copyFileSync, existsSync, mkdirSync } from "fs";
+import { copyFileSync, existsSync, mkdirSync, readFileSync } from "fs";
import { dirname, join } from "path";
import { homedir } from "os";
import { fileURLToPath } from "url";
import { stampBackendVersionAfterPull } from "./upgrade.js";
+import { clearLocalToken, ensureLocalToken } from "../config.js";
+import { createClient } from "../../client/factory.js";
+import { backendComposeArgs, composeSupportsLocalToken, parseArangoHealth } from "../backend-compose.js";
const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");
const COMPOSE_DIR = join(IX_HOME, "backend");
const LOCAL_COMPOSE = join(COMPOSE_DIR, "docker-compose.yml");
const HEALTH_URL = "http://localhost:8090/v1/health";
-const ARANGO_URL = "http://localhost:8529/_api/version";
/**
* The compose file this CLI release ships. `npm run build` copies the repo's
@@ -58,6 +60,18 @@ function findComposeFile(): string | null {
}
}
+function arangoHealth(composeFile: string | null): ReturnType<typeof parseArangoHealth> | "unknown" {
+ if (!composeFile) return "unknown";
+ try {
+ const out = execFileSync("docker", [...backendComposeArgs(composeFile), "ps", "--format", "json", "arangodb"], {
+ encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000,
+ });
+ return parseArangoHealth(out);
+ } catch {
+ return "unknown";
+ }
+}
+
function reportMissingCompose(): void {
console.error(`[error] No backend compose file at ${LOCAL_COMPOSE}, and this CLI install does not ship one.`);
console.error(" Reinstall or run 'ix upgrade' to restore it.");
@@ -116,16 +130,44 @@ function askConfirmation(prompt: string): Promise<boolean> {
});
}
-function isHealthy(): boolean {
+function memoryLayerResponds(timeout = 5000): boolean {
try {
- execFileSync("curl", ["-sf", HEALTH_URL], { stdio: "ignore", timeout: 5000 });
- execFileSync("curl", ["-sf", ARANGO_URL], { stdio: "ignore", timeout: 5000 });
+ execFileSync("curl", ["-sf", HEALTH_URL], { stdio: "ignore", timeout });
return true;
} catch {
return false;
}
}
+/**
+ * The memory layer answers its health route (which reports 503 while it cannot
+ * reach ArangoDB), and this project's arangodb container, if it runs one, is
+ * not unhealthy. ArangoDB is no longer probed on a host port: the compose file
+ * does not publish one. A backend served by some other stack ("absent",
+ * "unknown") is judged by the memory layer alone, as before.
+ */
+function isHealthy(composeFile: string | null): boolean {
+ if (!memoryLayerResponds()) return false;
+ const arango = arangoHealth(composeFile);
+ return arango !== "unhealthy" && arango !== "starting";
+}
+
+/** One line on whether the running backend requires the local token. Best-effort. */
+async function reportLocalAuth(): Promise<void> {
+ try {
+ const caps = await createClient({ endpoint: "http://localhost:8090" }).fetchCapabilities();
+ if (caps.local_auth === undefined) {
+ console.log(" Local token: not supported by this backend image (run 'ix upgrade')");
+ } else {
+ console.log(` Local token: ${caps.local_auth_enforcing ? "required" : "off"}`);
+ }
+ } catch (err) {
+ if ((err as Error)?.name === "LocalTokenRequiredError") {
+ console.log(" Local token: required, and this CLI's token was refused (run 'ix docker start --local-token')");
+ }
+ }
+}
+
function dockerAvailable(): boolean {
try {
execFileSync("docker", ["info"], { stdio: "ignore", timeout: 10000 });
@@ -144,14 +186,35 @@ export function registerDockerCommand(program: Command): void {
.command("start")
.alias("up")
.description("Start the IX backend (ArangoDB + Memory Layer)")
- .action(async () => {
+ .option("--local-token", "Require a bearer token on the backend; the CLI stores and sends it")
+ .option("--no-local-token", "Stop requiring the token and forget the stored one")
+ .action(async (opts: { localToken?: boolean }) => {
// Written before anything else, so stop/restart/logs work from any directory.
const composeFile = findComposeFile();
- if (isHealthy()) {
+ // Opt-in until a release turns the token on by default. Changing it means
+ // recreating memory-layer with the new environment, so a healthy backend
+ // is not left as it is.
+ const changeToken = opts.localToken !== undefined;
+ if (opts.localToken === true) {
+ let composeText = "";
+ try { composeText = composeFile ? readFileSync(composeFile, "utf-8") : ""; } catch { /* reported below */ }
+ if (!composeSupportsLocalToken(composeText)) {
+ console.error(`[error] ${composeFile ?? LOCAL_COMPOSE} does not pass IX_LOCAL_TOKEN to the backend.`);
+ console.error(" It predates token support, and 'ix upgrade' does not replace it. Move it aside and");
+ console.error(" run this again: 'ix docker start' then writes the compose file this CLI ships.");
+ console.error(` mv ${LOCAL_COMPOSE} ${LOCAL_COMPOSE}.old`);
+ process.exit(1);
+ }
+ ensureLocalToken();
+ } else if (opts.localToken === false) {
+ clearLocalToken();
+ }
+
+ if (!changeToken && isHealthy(composeFile)) {
console.log("[ok] Backend is already running and healthy");
console.log(" Memory Layer: http://localhost:8090");
- console.log(" ArangoDB: http://localhost:8529");
+ await reportLocalAuth();
return;
}
@@ -168,7 +231,7 @@ export function registerDockerCommand(program: Command): void {
console.log("Starting backend services...");
try {
- execFileSync("docker", ["compose", "-f", composeFile, "up", "-d", "--pull", "always"], {
+ execFileSync("docker", [...backendComposeArgs(composeFile), "up", "-d", "--pull", "always"], {
stdio: "inherit",
});
} catch {
@@ -190,11 +253,11 @@ export function registerDockerCommand(program: Command): void {
console.log("Waiting for services to become healthy...");
for (let i = 0; i < 30; i++) {
- if (isHealthy()) {
+ if (isHealthy(composeFile)) {
console.log("");
console.log("[ok] Backend is ready!");
console.log(" Memory Layer: http://localhost:8090");
- console.log(" ArangoDB: http://localhost:8529");
+ if (changeToken) await reportLocalAuth();
return;
}
process.stdout.write(".");
@@ -221,7 +284,7 @@ export function registerDockerCommand(program: Command): void {
}
const removeLocal = opts.removeData || opts.removeAllData;
- const args = ["compose", "-f", composeFile, "down"];
+ const args = [...backendComposeArgs(composeFile), "down"];
if (removeLocal) args.push("-v");
try {
@@ -288,11 +351,11 @@ export function registerDockerCommand(program: Command): void {
docker
.command("status")
.description("Show backend container and health status")
- .action(() => {
+ .action(async () => {
const composeFile = findComposeFile();
if (composeFile) {
try {
- execFileSync("docker", ["compose", "-f", composeFile, "ps"], {
+ execFileSync("docker", [...backendComposeArgs(composeFile), "ps"], {
stdio: "inherit",
});
} catch {
@@ -300,24 +363,15 @@ export function registerDockerCommand(program: Command): void {
}
}
console.log("");
- if (isHealthy()) {
+ if (isHealthy(composeFile)) {
console.log("[ok] Backend is healthy");
console.log(" Memory Layer: http://localhost:8090");
- console.log(" ArangoDB: http://localhost:8529");
+ await reportLocalAuth();
} else {
console.log("[!!] Backend is not healthy");
- try {
- execFileSync("curl", ["-sf", HEALTH_URL], { stdio: "ignore", timeout: 3000 });
- console.log(" Memory Layer: responding");
- } catch {
- console.log(" Memory Layer: not responding");
- }
- try {
- execFileSync("curl", ["-sf", ARANGO_URL], { stdio: "ignore", timeout: 3000 });
- console.log(" ArangoDB: responding");
- } catch {
- console.log(" ArangoDB: not responding");
- }
+ console.log(` Memory Layer: ${memoryLayerResponds(3000) ? "responding" : "not responding"}`);
+ const arango = arangoHealth(composeFile);
+ console.log(` ArangoDB: ${arango === "absent" ? "no container" : arango === "unknown" ? "container state unknown" : arango}`);
}
});
@@ -332,7 +386,7 @@ export function registerDockerCommand(program: Command): void {
process.exit(1);
}
- const args = ["compose", "-f", composeFile, "logs"];
+ const args = [...backendComposeArgs(composeFile), "logs"];
if (opts.follow) args.push("-f");
const child = spawn("docker", args, { stdio: "inherit" });
child.on("exit", (code) => process.exit(code || 0));
@@ -349,7 +403,7 @@ export function registerDockerCommand(program: Command): void {
}
try {
- execFileSync("docker", ["compose", "-f", composeFile, "restart"], {
+ execFileSync("docker", [...backendComposeArgs(composeFile), "restart"], {
stdio: "inherit",
});
console.log("[ok] Backend restarted.");
diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.ts
index a8c7413c..a68adba7 100644
--- a/ix-cli/src/cli/commands/doctor.ts
+++ b/ix-cli/src/cli/commands/doctor.ts
@@ -15,6 +15,7 @@ import {
type WorkspaceConfig,
} from "../config.js";
import { ixHome } from "../ix-home.js";
+import { isLocalEndpoint } from "../backend-version.js";
import { resolveReadSystemId } from "../resolve.js";
import { assessGraphStats } from "../graph-health.js";
import { llmLine, printLlmLines } from "../llm.js";
@@ -34,6 +35,7 @@ import { loadIngestBaseline } from "../ingest-baseline.js";
import { isCloudReady } from "../remote.js";
import { hasCompletedMapBaseline } from "../stale.js";
import { printJson } from "../format.js";
+import type { CapabilitiesResponse } from "../../client/types.js";
interface CheckResult {
ok: boolean;
@@ -200,6 +202,43 @@ export function checkNestedWorkspaces(
};
}
+/**
+ * Does the backend require the local bearer token, and does this CLI have the
+ * one it accepts? `caps` is the `/v1/capabilities` answer, or the error asking
+ * for it threw. A refused token fails the run, because every command fails the
+ * same way; a token the backend ignores is only a warning.
+ */
+export function assessLocalAuth(
+ caps: CapabilitiesResponse | Error,
+ sendsToken: boolean,
+ local: boolean,
+): CheckResult {
+ if (caps instanceof Error && caps.name === "LocalTokenRequiredError") {
+ return {
+ ok: false,
+ detail: sendsToken
+ ? "the backend refused this CLI's token — " +
+ (local ? "run 'ix docker start --local-token' to give the backend the stored one" : "check IX_TOKEN")
+ : "the backend requires a token and this CLI has none — " +
+ (local ? "run 'ix docker start --local-token', or set IX_TOKEN" : "set IX_TOKEN"),
+ };
+ }
+ if (caps instanceof Error) return { ok: true, detail: "backend unreachable (skipped)" };
+ if (caps.local_auth === undefined) return { ok: true, detail: "backend predates the token guard (skipped)" };
+ if (caps.local_auth_enforcing) return { ok: true, detail: "required, and this CLI's token is accepted" };
+ if (sendsToken) {
+ return {
+ ok: false, warn: true,
+ detail: "this CLI has a token but the backend does not require it — " +
+ (local ? "run 'ix docker start --local-token' to apply it" : "the backend ignores it"),
+ };
+ }
+ return {
+ ok: true,
+ detail: local ? "not required (opt in with 'ix docker start --local-token')" : "not required",
+ };
+}
+
export function registerDoctorCommand(program: Command): void {
program
.command("doctor")
@@ -280,6 +319,18 @@ export function registerDoctorCommand(program: Command): void {
}
},
},
+ {
+ name: "Backend token",
+ run: async () => {
+ let caps: CapabilitiesResponse | Error;
+ try {
+ caps = await client.fetchCapabilities();
+ } catch (e) {
+ caps = e instanceof Error ? e : new Error(String(e));
+ }
+ return assessLocalAuth(caps, client.sendsToken === true, isLocalEndpoint(endpoint));
+ },
+ },
{
name: "Workspace for this directory",
run: async () => {
diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.ts
index a9f2d8c8..83ff0ce8 100644
--- a/ix-cli/src/cli/commands/upgrade.ts
+++ b/ix-cli/src/cli/commands/upgrade.ts
@@ -18,6 +18,7 @@ import {
getTrackedVersion,
writeVersionStamp,
} from "../backend-version.js";
+import { backendComposeArgs } from "../backend-compose.js";
// Re-exported for the existing importers of this module (tests and call sites
// that predate backend-version.ts). recordBackendRelease is deliberately NOT
@@ -1751,7 +1752,9 @@ export function registerUpgradeCommand(program: Command): void {
try {
execFileSync(
"docker",
- ["compose", "-f", backendComposeFile, "up", "-d", "--pull", "always"],
+ // The same env and override files `ix docker start` uses, or the
+ // restart would drop the local token and a published Arango port.
+ [...backendComposeArgs(backendComposeFile), "up", "-d", "--pull", "always"],
{ stdio: "inherit" }
);
console.log("[ok] Backend restarted with latest image");
diff --git a/ix-cli/src/cli/commands/view.ts b/ix-cli/src/cli/commands/view.ts
index 5c3b6ab1..845314f7 100644
--- a/ix-cli/src/cli/commands/view.ts
+++ b/ix-cli/src/cli/commands/view.ts
@@ -14,7 +14,7 @@ import { homedir, platform } from "os";
import { fileURLToPath } from "url";
import { createConnection } from "net";
import { resolveWorkspaceId } from "../bootstrap.js";
-import { findWorkspaceForCwd, getDefaultWorkspace, loadWorkspaces } from "../config.js";
+import { findWorkspaceForCwd, getDefaultWorkspace, getLocalToken, loadWorkspaces } from "../config.js";
import { detectSystem } from "../system.js";
import { createClient } from "../../client/factory.js";
@@ -667,12 +667,12 @@ function openBrowser(url: string): void {
}
/**
- * 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.
+ * The token the visualizer's /v1 proxy sends to the backend: IX_TOKEN, else
+ * the stored local token (the proxy only ever talks to the local backend).
+ * Handed to the server through its environment, never argv.
*/
function viewBackendToken(): string {
- return process.env.IX_TOKEN ?? "";
+ return getLocalToken(BACKEND_URL) ?? "";
}
export function registerViewCommand(program: Command): void {
diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.ts
index 047aa9ea..05ad1604 100644
--- a/ix-cli/src/cli/config.ts
+++ b/ix-cli/src/cli/config.ts
@@ -2,11 +2,12 @@
import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync, renameSync, realpathSync, mkdirSync } from "node:fs";
import { dirname, isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";
-import { createHash } from "node:crypto";
+import { createHash, randomBytes } from "node:crypto";
import { execFileSync } from "node:child_process";
import { parse, stringify } from "yaml";
import { IxClient } from "../client/api.js";
import { ixHome } from "./ix-home.js";
+import { isLocalEndpoint } from "./backend-version.js";
/**
* The key of a project root's per-root state files. Canonical first: `ix
@@ -146,6 +147,8 @@ export interface IxConfig {
format: string;
workspace?: string;
workspaces?: WorkspaceConfig[];
+ /** Credentials for the local backend. See `getLocalToken`. */
+ auth?: { local_token?: string };
}
const defaultConfig: IxConfig = {
@@ -190,6 +193,7 @@ const OSS_OWNED_KEYS = new Set<keyof IxConfig>([
"format",
"workspace",
"workspaces",
+ "auth",
]);
export function saveConfig(config: IxConfig): void {
@@ -254,6 +258,52 @@ export function getEndpoint(): string {
return process.env.IX_ENDPOINT || loadConfig().endpoint;
}
+/**
+ * The bearer token the client sends to `endpoint`, if any.
+ *
+ * IX_TOKEN is the user's explicit choice and goes to whatever endpoint is
+ * configured. The stored `auth.local_token` belongs to the backend `ix docker`
+ * runs on this machine, so it is sent only to a loopback endpoint: pointing
+ * IX_ENDPOINT at another host must not hand that host the local credential.
+ */
+export function getLocalToken(endpoint: string = getEndpoint()): string | undefined {
+ const explicit = process.env.IX_TOKEN?.trim();
+ if (explicit) return explicit;
+ if (!isLocalEndpoint(endpoint)) return undefined;
+ return storedLocalToken();
+}
+
+/** The token in config.yaml's `auth.local_token`, if one is stored. */
+export function storedLocalToken(): string | undefined {
+ const stored = loadConfig().auth?.local_token;
+ return typeof stored === "string" && stored.trim() ? stored.trim() : undefined;
+}
+
+/**
+ * The stored local token, generated (32 random bytes, hex) and saved first if
+ * there is none. Only `ix docker start --local-token` calls this: the token is
+ * opt-in until a release turns it on by default.
+ */
+export function ensureLocalToken(): string {
+ const existing = storedLocalToken();
+ if (existing) return existing;
+ const config = loadConfig();
+ const token = randomBytes(32).toString("hex");
+ saveConfig({ ...config, auth: { ...config.auth, local_token: token } });
+ return token;
+}
+
+/** Forget the stored local token. */
+export function clearLocalToken(): void {
+ const config = loadConfig();
+ if (!config.auth?.local_token) return;
+ const { local_token: _dropped, ...rest } = config.auth;
+ const next: IxConfig = { ...config };
+ if (Object.keys(rest).length > 0) next.auth = rest;
+ else delete next.auth;
+ saveConfig(next);
+}
+
// Kept for @ix/pro, which imports it. The factory itself is the synchronous
// `createClient` in client/factory.ts; this wrapper loads it lazily because
// that module imports `getEndpoint` from this one.
diff --git a/ix-cli/src/cli/errors.ts b/ix-cli/src/cli/errors.ts
index 6b1b6c29..c7885179 100644
--- a/ix-cli/src/cli/errors.ts
+++ b/ix-cli/src/cli/errors.ts
@@ -325,6 +325,20 @@ export function backendUnreachableError(endpoint?: string): StructuredError {
};
}
+/**
+ * The backend answered 401 `local_token_required`: it was started with
+ * IX_LOCAL_TOKEN and this CLI sent no token, or a different one.
+ */
+export function localTokenRequiredError(endpoint?: string): StructuredError {
+ return {
+ error: "local_token_required",
+ message: `The Ix backend${endpoint ? ` at ${endpoint}` : ""} requires a token this CLI did not send or that it refused.`,
+ next: isLocalEndpoint(endpoint)
+ ? "Run `ix docker start --local-token` to give the backend this CLI's stored token, or set IX_TOKEN to the backend's token."
+ : "Set IX_TOKEN to the token that backend was started with.",
+ };
+}
+
export function renderCliError(err: unknown, debug = false, endpoint?: string): void {
if (err instanceof CliUsageError || err instanceof CliResolutionError) {
const code = err instanceof CliUsageError ? "usage_error" : "resolution_failed";
@@ -360,6 +374,15 @@ export function renderCliError(err: unknown, debug = false, endpoint?: string):
process.exit(1);
}
+ if (e?.name === "LocalTokenRequiredError") {
+ const refused = localTokenRequiredError(endpoint);
+ if (!emitLlmError(refused.error, refused.message, refused.next)) {
+ renderStructuredError(refused);
+ }
+ if (debug) writeDebugDetail(err);
+ process.exit(1);
+ }
+
const structured = typeof e?.message === "string" ? parseBackendError(e.message) : null;
if (structured) {
if (!emitLlmError(structured.error, structured.message, structured.next)) {
diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.ts
index 6f8bfed0..9d0b3a6d 100644
--- a/ix-cli/src/client/api.ts
+++ b/ix-cli/src/client/api.ts
@@ -35,6 +35,8 @@ export interface IxClientOptions {
shareReads?: boolean;
/** At most this many requests in flight at once. */
maxInFlight?: number;
+ /** Sent as `Authorization: Bearer <token>` on every request (see `getLocalToken`). */
+ token?: string;
}
/**
@@ -53,6 +55,7 @@ function isSharedRead(path: string): boolean {
export class IxClient {
private readonly memo?: RequestMemo<SuccessBody>;
private readonly limiter?: Limiter;
+ private readonly token?: string;
// An optional deadline signal shared across every request this client makes.
// `ix map` sets it to a hard wall-clock budget so that, even when the backend
@@ -68,6 +71,19 @@ export class IxClient {
) {
if (options.shareReads) this.memo = new RequestMemo();
if (options.maxInFlight !== undefined) this.limiter = new Limiter(options.maxInFlight);
+ if (options.token) this.token = options.token;
+ }
+
+ /**
+ * The headers of every request: the JSON content type when there is a body,
+ * and the bearer token when the client has one. The one place either is set,
+ * so no request can go out without the token.
+ */
+ private headers(json: boolean): Record<string, string> {
+ const headers: Record<string, string> = {};
+ if (json) headers["Content-Type"] = "application/json";
+ if (this.token) headers.Authorization = `Bearer ${this.token}`;
+ return headers;
}
/** Reads answered from `shareReads` instead of the backend, for diagnostics and tests. */
@@ -120,13 +136,13 @@ export class IxClient {
async ingest(path: string, recursive?: boolean, force?: boolean): Promise<IngestResult> {
const resp = await fetch(`${this.endpoint}/v1/ingest`, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: this.headers(true),
body: JSON.stringify({ path, recursive, force: force || undefined }),
signal: this.signalFor(30 * 60 * 1000), // 30 minute timeout for large repos
});
if (!resp.ok) {
const text = await resp.text();
- throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);
+ throw httpError(resp.status, text);
}
return resp.json() as Promise<IngestResult>;
}
@@ -313,13 +329,13 @@ export class IxClient {
async commitPatch(patch: GraphPatchPayload): Promise<PatchCommitResult> {
const resp = await fetch(`${this.endpoint}/v1/patch`, {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: this.headers(true),
body: JSON.stringify(patch),
signal: this.signalFor(5 * 60 * 1000), // 5 min — matches commitPatchBulk
});
if (!resp.ok) {
const text = await resp.text();
- throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);
+ throw httpError(resp.status, text);
}
return resp.json() as Promise<PatchCommitResult>;
}
@@ -381,13 +397,13 @@ export class IxClient {
if (opts?.systemId) body.system_id = opts.systemId;
const resp = await fetch(`${this.endpoint}/v1/map`, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: this.headers(true),
body: JSON.stringify(body),
signal: this.signalFor(30 * 60 * 1000), // 30 minute timeout
});
if (!resp.ok) {
const text = await resp.text();
- throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);
+ throw httpError(resp.status, text);
}
return resp.json();
}
@@ -395,13 +411,13 @@ export class IxClient {
async commitPatchBulk(patches: GraphPatchPayload[]): Promise<PatchCommitResult> {
const resp = await fetch(`${this.endpoint}/v1/patches/bulk`, {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: this.headers(true),
body: JSON.stringify({ patches }),
signal: this.signalFor(5 * 60 * 1000), // 5 min — prevents hang when k8s ingress closes idle connections
});
if (!resp.ok) {
const text = await resp.text();
- throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);
+ throw httpError(resp.status, text);
}
return resp.json() as Promise<PatchCommitResult>;
}
@@ -527,7 +543,7 @@ export class IxClient {
// A redirect can replay a destructive POST or hide an accepted reset
// behind a later connection failure/404. Inspect the first response.
redirect: "manual",
- headers: { "Content-Type": "application/json" },
+ headers: this.headers(true),
body: JSON.stringify({}),
signal: AbortSignal.timeout(30 * 1000),
});
@@ -550,7 +566,7 @@ export class IxClient {
}
if (!beginResp.ok) {
const text = await beginResp.text();
- throw new Error(`${beginResp.status}: ${errorBodyForMessage(text)}`);
+ throw httpError(beginResp.status, text);
}
if (beginResp.status !== 202) {
@@ -573,6 +589,7 @@ export class IxClient {
statusResp = await fetch(`${this.endpoint}/v1/reset/status/${opId}`, {
method: "GET",
redirect: "manual",
+ headers: this.headers(false),
signal: AbortSignal.timeout(30 * 1000),
});
} catch (error) {
@@ -649,7 +666,7 @@ export class IxClient {
const resp = await fetch(`${this.endpoint}${syncPath}`, {
method: "POST",
redirect: "manual",
- headers: { "Content-Type": "application/json" },
+ headers: this.headers(true),
body: JSON.stringify({}),
signal: AbortSignal.timeout(10 * 60 * 1000),
});
@@ -659,7 +676,7 @@ export class IxClient {
}
if (!resp.ok) {
const text = await resp.text();
- throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);
+ throw httpError(resp.status, text);
}
return resp.json() as Promise<{ ok: boolean; message: string }>;
}
@@ -670,10 +687,13 @@ export class IxClient {
}
async savingsReset(): Promise<any> {
- const resp = await fetch(`${this.endpoint}/v1/savings`, { method: "DELETE" });
+ const resp = await fetch(`${this.endpoint}/v1/savings`, {
+ method: "DELETE",
+ headers: this.headers(false),
+ });
if (!resp.ok) {
const text = await resp.text();
- throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);
+ throw httpError(resp.status, text);
}
return resp.json();
}
@@ -695,19 +715,31 @@ export class IxClient {
async capabilities(): Promise<CapabilitiesResponse> {
try {
- return await this.get<CapabilitiesResponse>("/v1/capabilities");
- } catch {
+ return await this.fetchCapabilities();
+ } catch (err) {
+ // A refused token is not "an older backend": say so rather than guess.
+ if (err instanceof LocalTokenRequiredError) throw err;
// Backend doesn't support capabilities yet — fall back to local mode.
return {};
}
}
+ /** `/v1/capabilities`, with every failure thrown (for `ix doctor`). */
+ async fetchCapabilities(): Promise<CapabilitiesResponse> {
+ return this.get<CapabilitiesResponse>("/v1/capabilities");
+ }
+
+ /** Whether this client sends a bearer token. */
+ get sendsToken(): boolean {
+ return this.token !== undefined;
+ }
+
private async post<T>(path: string, body: unknown): Promise<T> {
const payload = JSON.stringify(body);
return this.read<T>("POST", path, payload, () =>
fetch(`${this.endpoint}${path}`, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: this.headers(true),
body: payload,
// These small reads/writes (source-hashes, stitch, list, ...) had no
// timeout, so a stalled connection could hang the process indefinitely.
@@ -719,6 +751,7 @@ export class IxClient {
private async get<T>(path: string, timeoutMs = 2 * 60 * 1000): Promise<T> {
return this.read<T>("GET", path, "", () =>
fetch(`${this.endpoint}${path}`, {
+ headers: this.headers(false),
signal: this.signalFor(timeoutMs),
}));
}
@@ -733,7 +766,7 @@ export class IxClient {
const run = async (): Promise<SuccessBody> => {
const resp = await send();
const text = await resp.text();
- if (!resp.ok) throw new Error(`${resp.status}: ${errorBodyForMessage(text)}`);
+ if (!resp.ok) throw httpError(resp.status, text);
return { status: resp.status, text };
};
return this.limiter ? this.limiter.run(run) : run();
@@ -745,6 +778,32 @@ export class IxClient {
}
}
+/**
+ * The backend refused a request for want of its local bearer token (a 401
+ * with code `local_token_required`, from the loopback guard). The message keeps
+ * the `401: <body>` shape every other HTTP failure has, so code that reads an
+ * error code back out of a message still sees it; `renderCliError` recognises
+ * the class and says how to fix it.
+ */
+export class LocalTokenRequiredError extends Error {
+ readonly code = "local_token_required";
+ constructor(body: string) {
+ super(`401: ${errorBodyForMessage(body)}`);
+ this.name = "LocalTokenRequiredError";
+ }
+}
+
+/** The error for a non-2xx response: `<status>: <body>`, or a typed one we can explain. */
+export function httpError(status: number, body: string): Error {
+ if (status === 401) {
+ try {
+ const parsed = JSON.parse(body) as { code?: unknown } | null;
+ if (parsed?.code === "local_token_required") return new LocalTokenRequiredError(body);
+ } catch { /* not the guard's JSON: a plain 401 */ }
+ }
+ return new Error(`${status}: ${errorBodyForMessage(body)}`);
+}
+
/**
* An error response body as it goes into an Error message. A JSON body is kept
* whole: callers read its error code back out of the message. Anything else,
diff --git a/ix-cli/src/client/factory.ts b/ix-cli/src/client/factory.ts
index f06da157..28d43c4e 100644
--- a/ix-cli/src/client/factory.ts
+++ b/ix-cli/src/client/factory.ts
@@ -1,6 +1,6 @@
// Copyright 2026 Ix Infrastructure Inc.
-import { getEndpoint } from "../cli/config.js";
+import { getEndpoint, getLocalToken } from "../cli/config.js";
import { IxClient } from "./api.js";
import { QUERY_CLIENT_OPTIONS } from "./request-memo.js";
@@ -23,9 +23,11 @@ export interface CreateClientOptions {
* outside `src/client/` and tests.
*/
export function createClient(opts: CreateClientOptions = {}): IxClient {
+ const endpoint = opts.endpoint ?? getEndpoint();
+ const token = getLocalToken(endpoint);
return new IxClient(
- opts.endpoint ?? getEndpoint(),
+ endpoint,
opts.deadlineSignal,
- opts.query ? QUERY_CLIENT_OPTIONS : {},
+ { ...(opts.query ? QUERY_CLIENT_OPTIONS : {}), ...(token ? { token } : {}) },
);
}
diff --git a/ix-cli/src/client/types.ts b/ix-cli/src/client/types.ts
index 46277405..21890c45 100644
--- a/ix-cli/src/client/types.ts
+++ b/ix-cli/src/client/types.ts
@@ -232,4 +232,8 @@ export interface CapabilitiesResponse {
// treat absence as "unknown" rather than "false" to stay compatible with
// older deployments.
proFeaturesEnabled?: boolean;
+ /** The local-auth contract the backend speaks ("bearer-v1"); absent before the guard. */
+ local_auth?: string;
+ /** Whether the backend requires the bearer token (IX_LOCAL_TOKEN is set on it). */
+ local_auth_enforcing?: boolean;
}
diff --git a/scripts/backend.sh b/scripts/backend.sh
index dc13c5e0..5d0ac863 100755
--- a/scripts/backend.sh
+++ b/scripts/backend.sh
@@ -34,7 +34,6 @@ fi
COMPOSE_FILE="docker-compose.standalone.yml"
HEALTH_URL="http://localhost:8090/v1/health"
-ARANGO_URL="http://localhost:8529/_api/version"
# ── Helpers ──────────────────────────────────────────────────────────────────
@@ -102,7 +101,6 @@ wait_for_health() {
echo ""
echo "[ok] Backend is ready!"
echo " Memory Layer: http://localhost:8090"
- echo " ArangoDB: http://localhost:8529"
return 0
fi
printf "."
@@ -114,8 +112,15 @@ wait_for_health() {
return 1
}
+# ArangoDB publishes no host port: its health comes from Compose.
+arango_ok() {
+ local health
+ health=$(dc ps --format '{{.Health}}' arangodb 2>/dev/null) || return 0
+ [ -z "$health" ] || [ "$health" = "healthy" ]
+}
+
is_healthy() {
- curl -sf "$HEALTH_URL" > /dev/null 2>&1 && curl -sf "$ARANGO_URL" > /dev/null 2>&1
+ curl -sf "$HEALTH_URL" > /dev/null 2>&1 && arango_ok
}
containers_running() {
@@ -132,7 +137,6 @@ case "${1:-up}" in
if is_healthy; then
echo "[ok] Backend is already running and healthy"
echo " Memory Layer: http://localhost:8090"
- echo " ArangoDB: http://localhost:8529"
exit 0
fi
diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1
index 35a4dbef..35d295ff 100644
--- a/scripts/install/install.ps1
+++ b/scripts/install/install.ps1
@@ -22,7 +22,6 @@ $IxHome = if ($env:IX_HOME) { $env:IX_HOME } else { "$env:USERPROFILE\.ix" }
$IxBin = "$IxHome\bin"
$ComposeDir = "$IxHome\backend"
$HealthUrl = "http://localhost:8090/v1/health"
-$ArangoUrl = "http://localhost:8529/_api/version"
$NodeMinMajor = 22
# Installer scratch files live under $IxHome, never under $env:TEMP.
@@ -155,12 +154,25 @@ function Test-Healthy {
# prompt that defaults to No. It only fires once a backend is actually
# up and returning a body — a first install has nothing listening, the
# request fails outright, and the parse never happens. So this bites on
- # re-runs and upgrades, never on the machine you first tested. Both
- # endpoints return JSON that nothing here reads; only the status matters.
+ # re-runs and upgrades, never on the machine you first tested. The
+ # response is JSON that nothing here reads; only the status matters.
$null = Invoke-WebRequest -Uri $HealthUrl -TimeoutSec 3 -UseBasicParsing -ErrorAction Stop
- $null = Invoke-WebRequest -Uri $ArangoUrl -TimeoutSec 3 -UseBasicParsing -ErrorAction Stop
- return $true
} catch { return $false }
+ return (Test-ArangoHealthy)
+}
+
+# ArangoDB publishes no host port, so ask Compose for its container's health.
+# No compose file, or no arangodb container, means some other stack serves the
+# backend: the memory layer's health (503 while it cannot reach its database)
+# is then the whole answer.
+function Test-ArangoHealthy {
+ $composeFile = "$ComposeDir\docker-compose.yml"
+ if (-not (Test-Path $composeFile)) { return $true }
+ try {
+ $health = (docker compose -f "$composeFile" ps --format '{{.Health}}' arangodb 2>$null | Out-String).Trim()
+ } catch { return $true }
+ if ($LASTEXITCODE -ne 0) { return $true }
+ return ([string]::IsNullOrEmpty($health) -or $health -eq "healthy")
}
function Get-LatestVersion {
diff --git a/scripts/install/install.sh b/scripts/install/install.sh
index c6353951..10629f34 100755
--- a/scripts/install/install.sh
+++ b/scripts/install/install.sh
@@ -28,7 +28,6 @@ IX_HOME="${IX_HOME:-$HOME/.ix}"
COMPOSE_DIR="$IX_HOME/backend"
HEALTH_URL="http://localhost:8090/v1/health"
-ARANGO_URL="http://localhost:8529/_api/version"
NODE_MIN_MAJOR=22
@@ -785,10 +784,20 @@ fi
step "3. Backend (ArangoDB + Memory Layer)"
+# ArangoDB publishes no host port, so ask Compose for its container's health.
+# No compose file or no arangodb container means some other stack serves the
+# backend: judge it by the memory layer's health alone, which reports 503
+# while it cannot reach its database.
+arango_ok() {
+ [ -f "$COMPOSE_DIR/docker-compose.yml" ] || return 0
+ _arango_health=$(dc -f "$COMPOSE_DIR/docker-compose.yml" ps --format '{{.Health}}' arangodb < /dev/null 2>/dev/null) || return 0
+ [ -z "$_arango_health" ] || [ "$_arango_health" = "healthy" ]
+}
+
if [ "${IX_SKIP_BACKEND:-}" = "1" ]; then
echo " (skipped via IX_SKIP_BACKEND=1)"
else
- if _fetch "$HEALTH_URL" >/dev/null 2>&1 && _fetch "$ARANGO_URL" >/dev/null 2>&1; then
+ if _fetch "$HEALTH_URL" >/dev/null 2>&1 && arango_ok; then
info "Backend is already running and healthy"
else
if command -v lsof >/dev/null 2>&1; then
@@ -881,7 +890,7 @@ else
printf " Waiting for services to become healthy..."
i=0
while [ "$i" -lt 45 ]; do
- if _fetch "$HEALTH_URL" >/dev/null 2>&1 && _fetch "$ARANGO_URL" >/dev/null 2>&1; then
+ if _fetch "$HEALTH_URL" >/dev/null 2>&1 && arango_ok; then
break
fi
printf "."
@@ -898,7 +907,6 @@ else
fi
echo " Memory Layer: http://localhost:8090"
- echo " ArangoDB: http://localhost:8529"
fi
# -- Step 4: Install ix CLI --
@@ -1209,7 +1217,6 @@ echo "║ Ix is ready! ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo " Backend: http://localhost:8090"
-echo " ArangoDB: http://localhost:8529"
echo ""
# Verify CLI works
diff --git a/skills/ix/references/troubleshooting.md b/skills/ix/references/troubleshooting.md
index f6fc19aa..198990f7 100644
--- a/skills/ix/references/troubleshooting.md
+++ b/skills/ix/references/troubleshooting.md
@@ -4,8 +4,8 @@
- **Node.js >= 22** — required by the `ix` CLI.
- **git** — used for workspace detection.
-- **Docker + Docker Compose** — runs the local backend (ArangoDB on
- 127.0.0.1:8529 and the Ix Memory Layer on 127.0.0.1:8090). Docker Desktop
+- **Docker + Docker Compose** — runs the local backend (the Ix Memory Layer on
+ 127.0.0.1:8090, and ArangoDB behind it with no host port). Docker Desktop
must be running on macOS/Windows.
- **ripgrep** — powers `ix text`; optional but recommended (non-fatal if
missing).
@@ -31,6 +31,7 @@ again.
| Symptom | Fix |
|---|---|
| `Ix backend not reachable` | `ix docker start`, wait, then `ix doctor` |
+| `error code=local_token_required` | The backend requires a token this CLI did not send. On the local backend run `ix docker start --local-token` (gives it the CLI's stored token); for another backend set `IX_TOKEN`. `ix doctor` reports it under "Backend token" |
| Docker daemon not running | Start Docker Desktop / the Docker service, then re-run bootstrap |
| `ix: command not found` | Re-run bootstrap (installs the CLI), or restart the shell so PATH picks up the wrapper |
| `The '<name>' command requires Ix Pro.` | Not installed — skip the step, do not retry or mention it again this session |