Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(docker): read-only `ix docker` commands don't rewrite ~/.ix/backend/.env
KageBinaryf9c67f531849
diff --git a/ix-cli/src/cli/__tests__/docker-compose-source.test.ts b/ix-cli/src/cli/__tests__/docker-compose-source.test.tsindex 2765262f..e845d582 100644--- a/ix-cli/src/cli/__tests__/docker-compose-source.test.ts+++ b/ix-cli/src/cli/__tests__/docker-compose-source.test.ts@@ -156,6 +156,114 @@ describe("ix docker start --local-token", () => {});});+async function docker(...args: string[]): Promise<void> {+ const { registerDockerCommand } = await import("../commands/docker.js");+ const program = new Command().exitOverride();+ registerDockerCommand(program);+ await program.parseAsync(["docker", ...args], { from: "user" });+}++describe("~/.ix/backend/.env: only start writes it, and it keeps what the user set", () => {+ const backend = () => join(t, "ix-home", "backend");+ const envFile = () => join(backend(), ".env");+ const HAND_SET = "# my notes\nCOMPOSE_PROJECT_NAME=backend\n\nIX_LOCAL_TOKEN=\"hand-set-token\"\nFOO=bar\n";++ beforeEach(() => {+ process.env.IX_BUNDLED_COMPOSE = REPO_COMPOSE;+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});+ vi.spyOn(process.stdout, "write").mockImplementation(() => true);+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(JSON.stringify({ proFeaturesEnabled: false, local_auth: "bearer-v1", local_auth_enforcing: true })));+ mkdirSync(backend(), { recursive: true });+ writeFileSync(envFile(), HAND_SET, { mode: 0o600 });+ });++ it.skipIf(process.platform === "win32")("status, stop and restart read it but never rewrite it", async () => {+ writeFileSync(join(t, "up"), ""); // healthy, so status also asks compose for arangodb+ await docker("status");+ await docker("stop");+ await docker("restart");+ expect(readFileSync(envFile(), "utf8")).toBe(HAND_SET);+ // compose is still pointed at it, so ${IX_LOCAL_TOKEN} resolves the same.+ expect(log()).toContain(`compose --env-file ${envFile()} -f ${join(backend(), "docker-compose.yml")} ps`);+ expect(log()).toMatch(/ down\n/);+ expect(log()).toMatch(/ restart\n/);+ });++ it.skipIf(process.platform === "win32")("logs never rewrites it", async () => {+ const exited = new Promise<number | undefined>((resolve) => {+ vi.spyOn(process, "exit").mockImplementation(((code?: number) => { resolve(code); }) as never);+ });+ await docker("logs");+ expect(await exited).toBe(0);+ expect(readFileSync(envFile(), "utf8")).toBe(HAND_SET);+ expect(log()).toContain(`--env-file ${envFile()}`);+ });++ it.skipIf(process.platform === "win32")("read-only commands create none and pass none when it is missing", async () => {+ rmSync(envFile());+ writeFileSync(join(t, "up"), "");+ await docker("status");+ expect(existsSync(envFile())).toBe(false);+ expect(log()).not.toContain("--env-file");+ });++ it.skipIf(process.platform === "win32")("start keeps a hand-set token and the user's other lines when none is stored", async () => {+ await dockerStart();+ expect(readFileSync(envFile(), "utf8")).toBe(HAND_SET);+ expect(log()).toMatch(/up -d --pull always/);+ expect(existsSync(join(t, "ix-home", "config.yaml"))).toBe(false);+ });++ it.skipIf(process.platform === "win32")("start --local-token adopts the hand-set token instead of generating another", async () => {+ await dockerStart("--local-token");+ expect(readFileSync(join(t, "ix-home", "config.yaml"), "utf8")).toContain("local_token: hand-set-token");+ expect(readFileSync(envFile(), "utf8")).toBe(HAND_SET);+ });++ it.skipIf(process.platform === "win32")("a stored token wins over a different hand-set one, in place", async () => {+ writeFileSync(join(t, "ix-home", "config.yaml"), "auth:\n local_token: stored-token\n");+ await dockerStart();+ expect(readFileSync(envFile(), "utf8"))+ .toBe("# my notes\nCOMPOSE_PROJECT_NAME=backend\n\nIX_LOCAL_TOKEN=stored-token\nFOO=bar\n");+ });++ it.skipIf(process.platform === "win32")("start --no-local-token clears the token but keeps the other lines", async () => {+ await dockerStart("--no-local-token");+ expect(readFileSync(envFile(), "utf8"))+ .toBe("# my notes\nCOMPOSE_PROJECT_NAME=backend\n\nIX_LOCAL_TOKEN=\nFOO=bar\n");+ });+});++describe("backend .env helpers", () => {+ it("reads the token Compose would: the last assignment, unquoted, empty as none", async () => {+ const { envFileLocalToken } = await import("../backend-compose.js");+ expect(envFileLocalToken("")).toBeUndefined();+ expect(envFileLocalToken("IX_LOCAL_TOKEN=\n")).toBeUndefined();+ expect(envFileLocalToken("IX_LOCAL_TOKEN=a\r\nexport IX_LOCAL_TOKEN='b'\n")).toBe("b");+ expect(envFileLocalToken("# IX_LOCAL_TOKEN=commented\nX_IX_LOCAL_TOKEN=other\n")).toBeUndefined();+ });++ it("chooses the stored token, else the hand-set one unless clearing", async () => {+ const { backendStartToken } = await import("../backend-compose.js");+ expect(backendStartToken("s", "IX_LOCAL_TOKEN=h\n")).toBe("s");+ expect(backendStartToken(undefined, "IX_LOCAL_TOKEN=h\n")).toBe("h");+ expect(backendStartToken(undefined, "IX_LOCAL_TOKEN=h\n", true)).toBeUndefined();+ expect(backendStartToken(undefined, "")).toBeUndefined();+ });++ it("does not rewrite a file that already says the same", async () => {+ const { writeBackendEnv } = await import("../backend-compose.js");+ const env = join(t, "same.env");+ writeFileSync(env, "IX_LOCAL_TOKEN=x\n", { mode: 0o644 });+ writeBackendEnv("x", env);+ if (process.platform !== "win32") expect(statSync(env).mode & 0o777).toBe(0o644);+ writeBackendEnv("y", env);+ expect(readFileSync(env, "utf8")).toBe("IX_LOCAL_TOKEN=y\n");+ });+});+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/backend-compose.ts b/ix-cli/src/cli/backend-compose.tsindex 4f381124..8be2386a 100644--- a/ix-cli/src/cli/backend-compose.ts+++ b/ix-cli/src/cli/backend-compose.ts@@ -24,27 +24,62 @@ export function backendOverrideFile(): string {return join(ixHome(), "backend", "docker-compose.override.yml");}+const LOCAL_TOKEN_LINE = /^\s*(?:export\s+)?IX_LOCAL_TOKEN\s*=(.*)$/;+const LOCAL_TOKEN_IN_FILE = /^\s*(?:export\s+)?IX_LOCAL_TOKEN\s*=/m;++/**+ * The IX_LOCAL_TOKEN a `.env` sets, if any: the last assignment, as Compose+ * reads it, with surrounding quotes removed. An empty value is no token.+ */+export function envFileLocalToken(existing: string): string | undefined {+ let value: string | undefined;+ for (const line of existing.split(/\r?\n/)) {+ const m = LOCAL_TOKEN_LINE.exec(line);+ if (m) value = m[1].trim().replace(/^(["'])(.*)\1$/, "$2").trim();+ }+ return value ? value : undefined;+}+/*** `.env` with IX_LOCAL_TOKEN set to `token` (empty: the backend does not- * require one). Other lines a user added are kept.+ * require one). Every other line a user wrote, comments and blank lines+ * included, is kept where it was; the token line replaces the first existing+ * one, or is appended.*/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";+ const tokenLine = `IX_LOCAL_TOKEN=${token ?? ""}`;+ const lines = existing === "" ? [] : existing.replace(/\r?\n$/, "").split(/\r?\n/);+ const out: string[] = [];+ let placed = false;+ for (const line of lines) {+ if (LOCAL_TOKEN_LINE.test(line)) {+ if (!placed) out.push(tokenLine);+ placed = true;+ } else {+ out.push(line);+ }+ }+ if (!placed) out.push(tokenLine);+ return out.join("\n") + "\n";+}++function readEnvFile(envFile: string): string {+ try { return readFileSync(envFile, "utf-8"); } catch { return ""; }}/**- * Write ~/.ix/backend/.env for the stored token, atomically and at mode 0600:- * it holds the credential. Compose reads it for `${IX_LOCAL_TOKEN}`.+ * Write ~/.ix/backend/.env for `token`, atomically and at mode 0600: it holds+ * the credential. Compose reads it for `${IX_LOCAL_TOKEN}`. A file that already+ * says the same is left untouched.*/export function writeBackendEnv(token: string | undefined, envFile: string = backendEnvFile()): void {- let existing = "";- try { existing = readFileSync(envFile, "utf-8"); } catch { /* none yet */ }+ const existing = readEnvFile(envFile);+ // Already says the same (however the user quoted it): leave the file as it is.+ if (existsSync(envFile) && envFileLocalToken(existing) === (token || undefined) && LOCAL_TOKEN_IN_FILE.test(existing)) return;+ const next = backendEnvContents(existing, token);mkdirSync(dirname(envFile), { recursive: true, mode: 0o700 });const tmp = `${envFile}.${process.pid}.tmp`;- writeFileSync(tmp, backendEnvContents(existing, token), { mode: 0o600 });+ writeFileSync(tmp, next, { mode: 0o600 });try {renameSync(tmp, envFile);} catch (err) {@@ -54,15 +89,52 @@ export function writeBackendEnv(token: string | undefined, envFile: string = bactry { chmodSync(envFile, 0o600); } catch { /* the create mode is the primary guard */ }}+/**+ * The token the backend should be started with: the stored one when there is+ * one (it is what this CLI sends, so the two must agree), else whatever the+ * user set by hand in `.env`, which `ix docker start` has no reason to erase.+ * `clear` (`--no-local-token`) drops a hand-set token too: the user asked for+ * no token at all.+ */+export function backendStartToken(+ stored: string | undefined,+ existing: string,+ clear = false,+): string | undefined {+ if (stored) return stored;+ return clear ? undefined : envFileLocalToken(existing);+}++/** The IX_LOCAL_TOKEN set by hand in ~/.ix/backend/.env, if any. */+export function handSetLocalToken(envFile: string = backendEnvFile()): string | undefined {+ return envFileLocalToken(readEnvFile(envFile));+}++export interface BackendComposeOptions {+ /**+ * Rewrite `.env` from the stored token first, so a token change reaches the+ * container. Only commands that (re)create the backend (`up`) need this;+ * read-only ones (`ps`, `logs`) and `stop`/`restart` must not touch the file.+ */+ writeEnv?: boolean;+ /** With `writeEnv`: drop a hand-set token as well (`--no-local-token`). */+ clearToken?: boolean;+}+/*** 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.+ * (written first only when `writeEnv` asks; passed only when it exists, since+ * Compose refuses a missing `--env-file`) and the user's override file when+ * there is one.*/-export function backendComposeArgs(composeFile: string): string[] {+export function backendComposeArgs(composeFile: string, opts: BackendComposeOptions = {}): string[] {const envFile = backendEnvFile();- writeBackendEnv(storedLocalToken(), envFile);- const args = ["compose", "--env-file", envFile, "-f", composeFile];+ if (opts.writeEnv) {+ writeBackendEnv(backendStartToken(storedLocalToken(), readEnvFile(envFile), opts.clearToken), envFile);+ }+ const args = ["compose"];+ if (existsSync(envFile)) args.push("--env-file", envFile);+ args.push("-f", composeFile);const override = backendOverrideFile();if (existsSync(override)) args.push("-f", override);return args;diff --git a/ix-cli/src/cli/commands/docker.ts b/ix-cli/src/cli/commands/docker.tsindex 08bc6143..86e53bdc 100644--- a/ix-cli/src/cli/commands/docker.ts+++ b/ix-cli/src/cli/commands/docker.ts@@ -10,7 +10,7 @@ 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";+import { backendComposeArgs, composeSupportsLocalToken, handSetLocalToken, parseArangoHealth } from "../backend-compose.js";const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");const COMPOSE_DIR = join(IX_HOME, "backend");@@ -206,7 +206,9 @@ export function registerDockerCommand(program: Command): void {console.error(` mv ${LOCAL_COMPOSE} ${LOCAL_COMPOSE}.old`);process.exit(1);}- ensureLocalToken();+ // A token already set by hand in .env is adopted rather than replaced,+ // so whatever else was given it (IX_TOKEN, another client) keeps working.+ ensureLocalToken(handSetLocalToken());} else if (opts.localToken === false) {clearLocalToken();}@@ -231,7 +233,9 @@ export function registerDockerCommand(program: Command): void {console.log("Starting backend services...");try {- execFileSync("docker", [...backendComposeArgs(composeFile), "up", "-d", "--pull", "always"], {+ // Only `up` writes .env: it is what hands the container a changed token.+ const composeArgs = backendComposeArgs(composeFile, { writeEnv: true, clearToken: opts.localToken === false });+ execFileSync("docker", [...composeArgs, "up", "-d", "--pull", "always"], {stdio: "inherit",});} catch {diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex 83ff0ce8..a19ddbe2 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -1754,7 +1754,7 @@ export function registerUpgradeCommand(program: Command): void {"docker",// 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"],+ [...backendComposeArgs(backendComposeFile, { writeEnv: true }), "up", "-d", "--pull", "always"],{ stdio: "inherit" });console.log("[ok] Backend restarted with latest image");diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex cf788040..ad8de8be 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -418,17 +418,18 @@ export function storedLocalToken(): string | 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.+ * The stored local token, saved first if there is none: `preferred` when given+ * (a token the user already set by hand in ~/.ix/backend/.env), else a new one+ * (32 random bytes, hex). 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 {+export function ensureLocalToken(preferred?: string): string {const existing = storedLocalToken();if (existing) return existing;return updateConfig((config) => {const stored = config.auth?.local_token;if (typeof stored === "string" && stored.trim()) return { result: stored.trim() };- const token = randomBytes(32).toString("hex");+ const token = preferred?.trim() || randomBytes(32).toString("hex");return { save: { ...config, auth: { ...config.auth, local_token: token } }, result: token };});}