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(upgrade): verify release archives against their published checksum
KageBinarydac529c35189
diff --git a/docs-site/src/content/docs/community/security.md b/docs-site/src/content/docs/community/security.mdindex 5db104f4..9911eeff 100644--- a/docs-site/src/content/docs/community/security.md+++ b/docs-site/src/content/docs/community/security.md@@ -25,6 +25,22 @@ This policy covers the `ix` CLI and the artifacts published from the[Ix repository](https://github.com/ix-infrastructure/Ix). The memory-layer backend is released separately and has itsown reporting channel.+## Verifying downloads++Every release archive is published with a `<archive>.sha256` file. `ix upgrade` downloads both and checks the+archive before it extracts or runs anything. It refuses to install if the checksum does not match or is missing,+and leaves your current install as it was. This covers the CLI and the Compass bundle.++When the [GitHub CLI](https://cli.github.com/) is installed, `ix upgrade` also checks the CLI archive's build+provenance with `gh attestation verify`. It reports the result, but the checksum is what decides. To check an archive+yourself:++```sh+sha256sum -c ix-<version>-<platform>.tar.gz.sha256+gh attestation verify ix-<version>-<platform>.tar.gz -R ix-infrastructure/Ix \+ --signer-workflow ix-infrastructure/Ix/.github/workflows/release.yml+```+## Your code stays localThe default backend runs in Docker on your machine and binds to `127.0.0.1` only, so your code and graph stay ondiff --git a/ix-cli/src/cli/__tests__/integrity.test.ts b/ix-cli/src/cli/__tests__/integrity.test.tsnew file mode 100644index 00000000..21ea8808--- /dev/null+++ b/ix-cli/src/cli/__tests__/integrity.test.ts@@ -0,0 +1,160 @@+// Copyright 2026 Ix Infrastructure Inc.++import { createHash } from "node:crypto";+import { spawn, type ChildProcess } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import {+ ChecksumError,+ attestationCommand,+ downloadVerified,+ parseSha256Sidecar,+ verifySha256,+} from "../integrity.js";++const ARCHIVE = Buffer.from("pretend this is ix-9.9.9-linux-amd64.tar.gz\n".repeat(200));+const NAME = "ix-9.9.9-linux-amd64.tar.gz";+const sha = (b: Buffer) => createHash("sha256").update(b).digest("hex");++/**+ * A release host serving `www/` from a separate process: downloadVerified runs+ * curl synchronously, which would block a server living in this event loop.+ */+let host: ChildProcess;+let base = "";+let dir = "";+let www = "";++const HOST_SCRIPT = `+const http = require("http"), fs = require("fs"), path = require("path");+const root = process.argv[1];+http.createServer((req, res) => {+ const file = path.join(root, decodeURIComponent(req.url.split("?")[0]));+ fs.readFile(file, (err, body) => { if (err) { res.writeHead(404).end(); } else { res.writeHead(200).end(body); } });+}).listen(0, "127.0.0.1", function () { process.stdout.write(String(this.address().port) + "\\n"); });+`;++/** Replace what the host serves: URL path -> body. */+function serve(files: Record<string, Buffer | string>): void {+ rmSync(www, { recursive: true, force: true });+ for (const [path, body] of Object.entries(files)) {+ mkdirSync(join(www, dirname(path)), { recursive: true });+ writeFileSync(join(www, path), body);+ }+}++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), "ix-integrity-"));+ www = join(dir, "www");+ host = spawn(process.execPath, ["-e", HOST_SCRIPT, www], { stdio: ["ignore", "pipe", "inherit"] });+ const port = await new Promise<string>((resolve, reject) => {+ host.once("error", reject);+ host.stdout!.once("data", (chunk) => resolve(String(chunk).trim()));+ });+ base = `http://127.0.0.1:${port}`;+});++afterAll(() => {+ host.kill();+ rmSync(dir, { recursive: true, force: true });+});++describe("downloadVerified", () => {+ it("accepts an archive that matches its published checksum", () => {+ serve({ [`/v9.9.9/${NAME}`]: ARCHIVE, [`/v9.9.9/${NAME}.sha256`]: `${sha(ARCHIVE)} ${NAME}\n` });+ const dest = join(dir, "good.tar.gz");+ downloadVerified(`${base}/v9.9.9/${NAME}`, dest, { timeoutMs: 10_000 });+ expect(readFileSync(dest).equals(ARCHIVE)).toBe(true);+ });++ it("refuses an archive with one byte flipped", () => {+ const tampered = Buffer.from(ARCHIVE);+ tampered[100] ^= 0x01;+ serve({ [`/v9.9.9/${NAME}`]: tampered, [`/v9.9.9/${NAME}.sha256`]: `${sha(ARCHIVE)} ${NAME}\n` });+ expect(() => downloadVerified(`${base}/v9.9.9/${NAME}`, join(dir, "bad.tar.gz"), { timeoutMs: 10_000 })).toThrow(+ /checksum mismatch/,+ );+ });++ it("fails closed when the release publishes no checksum", () => {+ serve({ [`/v9.9.9/${NAME}`]: ARCHIVE });+ let err: unknown;+ try {+ downloadVerified(`${base}/v9.9.9/${NAME}`, join(dir, "nosum.tar.gz"), { timeoutMs: 10_000 });+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(ChecksumError);+ expect(String(err)).toMatch(/no published checksum/);+ });++ it("refuses a checksum file that vouches for a different asset", () => {+ serve({+ [`/v9.9.9/${NAME}`]: ARCHIVE,+ [`/v9.9.9/${NAME}.sha256`]: `${sha(ARCHIVE)} ix-9.9.9-darwin-arm64.tar.gz\n`,+ });+ expect(() => downloadVerified(`${base}/v9.9.9/${NAME}`, join(dir, "other.tar.gz"), { timeoutMs: 10_000 })).toThrow(+ ChecksumError,+ );+ });++ it("reports a failed archive download as a download error, not a checksum error", () => {+ serve({});+ const dest = join(dir, "missing.tar.gz");+ let err: unknown;+ try {+ downloadVerified(`${base}/v9.9.9/${NAME}`, dest, { timeoutMs: 10_000 });+ } catch (e) {+ err = e;+ }+ expect(err).toBeDefined();+ expect(err).not.toBeInstanceOf(ChecksumError);+ expect(existsSync(dest)).toBe(false);+ });+});++describe("parseSha256Sidecar", () => {+ const hex = "a".repeat(64);++ it("reads sha256sum output in text and binary mode, with or without a name", () => {+ expect(parseSha256Sidecar(`${hex} ${NAME}\n`, NAME)).toBe(hex);+ expect(parseSha256Sidecar(`${hex} *${NAME}\r\n`, NAME)).toBe(hex);+ expect(parseSha256Sidecar(`${hex.toUpperCase()}\n`, NAME)).toBe(hex);+ });++ it("rejects anything that is not a sha256 digest", () => {+ expect(() => parseSha256Sidecar("<html>Not Found</html>", NAME)).toThrow(ChecksumError);+ expect(() => parseSha256Sidecar(`${"a".repeat(63)} ${NAME}`, NAME)).toThrow(ChecksumError);+ expect(() => parseSha256Sidecar("", NAME)).toThrow(ChecksumError);+ });+});++describe("verifySha256", () => {+ it("names the expected and actual digests on a mismatch", () => {+ serve({});+ const dest = join(dir, "local.bin");+ writeFileSync(dest, ARCHIVE);+ expect(() => verifySha256(dest, sha(ARCHIVE))).not.toThrow();+ expect(() => verifySha256(dest, "b".repeat(64))).toThrow(new RegExp(`expected ${"b".repeat(64)}, got ${sha(ARCHIVE)}`));+ });+});++describe("attestationCommand", () => {+ it("verifies against this repository's release workflow", () => {+ expect(attestationCommand("ix.tar.gz", "ix-infrastructure/Ix")).toEqual([+ "gh",+ [+ "attestation",+ "verify",+ "ix.tar.gz",+ "-R",+ "ix-infrastructure/Ix",+ "--signer-workflow",+ "ix-infrastructure/Ix/.github/workflows/release.yml",+ ],+ ]);+ });+});diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex b0f95b1b..c93512bf 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -9,6 +9,7 @@ import { homedir } from "os";import chalk from "chalk";import { BACKEND_IMAGE, checkBackendImage, isNonStandardBackend } from "../backend-status.js";import { canRenderProgress } from "../stderr.js";+import { ChecksumError, attestationCommand, downloadVerified, verifyAttestation } from "../integrity.js";import type { IxClient } from "../../client/api.js";import {BACKEND_VERSION_FILE,@@ -1477,12 +1478,16 @@ export function registerUpgradeCommand(program: Command): void {console.log(`Downloading ix ${latest} for ${platform}...`);try {- execFileSync(- "curl",- ["-fsSL", "--progress-bar", url, "-o", tmpFile],- { stdio: ["ignore", "inherit", "inherit"], timeout: 300000 }- );- } catch {+ // Checked against the release's published .sha256 before anything+ // extracts or runs it; a missing checksum fails closed.+ downloadVerified(url, tmpFile, { timeoutMs: 300000, progress: true });+ } catch (err) {+ if (err instanceof ChecksumError) {+ console.error(`[error] ${err.message}`);+ console.error(" The download was not installed. Your existing install is untouched.");+ rmQuiet(tmpDirRaw);+ process.exit(1);+ }console.error(`[error] Failed to download ${url}`);console.error(" You can also upgrade manually:");console.error(@@ -1496,6 +1501,20 @@ export function registerUpgradeCommand(program: Command): void {process.exit(1);}+ // Provenance, when the GitHub CLI is there to check it. Reported, not+ // enforced: the checksum above is the gate (see verifyAttestation).+ const attestation = verifyAttestation(tmpFile, `${GITHUB_ORG}/${GITHUB_REPO}`);+ if (attestation.status === "verified") {+ console.log("[ok] Checksum and build provenance verified");+ } else {+ console.log("[ok] Checksum verified");+ const [ghCmd, ghArgs] = attestationCommand(archiveName, `${GITHUB_ORG}/${GITHUB_REPO}`);+ if (attestation.status === "failed") {+ console.error(`[!!] Build provenance could not be verified: ${attestation.detail}`);+ }+ console.log(chalk.dim(` To check build provenance yourself: ${ghCmd} ${ghArgs.join(" ")}`));+ }+console.log("Installing...");// Extract into a staging directory beside the install, verify the@@ -1807,10 +1826,12 @@ export function registerUpgradeCommand(program: Command): void {const compassBackup = join(IX_HOME, `.compass-backup-${process.pid}`);let stage = "download";try {- execFileSync("curl", ["-fsSL", compassUrl, "-o", compassTar], {- stdio: ["ignore", "inherit", "inherit"],- timeout: 60000,- });+ try {+ downloadVerified(compassUrl, compassTar, { timeoutMs: 60000 });+ } catch (err) {+ if (err instanceof ChecksumError) stage = "checksum";+ throw err;+ }stage = "extract";installCompassBundle(compassTar, COMPASS_DIR, compassStaging, compassBackup);// Its own stage: a failure here is a bundle that installed fine anddiff --git a/ix-cli/src/cli/integrity.ts b/ix-cli/src/cli/integrity.tsnew file mode 100644index 00000000..5355dad5--- /dev/null+++ b/ix-cli/src/cli/integrity.ts@@ -0,0 +1,104 @@+// Copyright 2026 Ix Infrastructure Inc.++import { execFileSync } from "node:child_process";+import { createHash, timingSafeEqual } from "node:crypto";+import { readFileSync } from "node:fs";+import { basename } from "node:path";++/** A release archive that does not match its published checksum, or has none. */+export class ChecksumError extends Error {+ override name = "ChecksumError";+}++/**+ * The digest from a `<asset>.sha256` sidecar: `sha256sum` output, one line of+ * `<64 hex> <file name>` (the name may carry a leading `*` in binary mode).+ * When the line names a file it must be `expectedName`, so a sidecar for a+ * different asset cannot vouch for this one.+ */+export function parseSha256Sidecar(text: string, expectedName: string): string {+ const line = text.split(/\r?\n/).find((l) => l.trim() !== "") ?? "";+ const match = /^([0-9a-fA-F]{64})(?:\s+\*?(.+?))?\s*$/.exec(line.trim());+ if (!match) throw new ChecksumError(`checksum file for ${expectedName} is not in sha256sum format`);+ const named = match[2];+ if (named !== undefined && basename(named) !== expectedName) {+ throw new ChecksumError(`checksum file names ${named}, not ${expectedName}`);+ }+ return match[1].toLowerCase();+}++export function sha256File(file: string): string {+ return createHash("sha256").update(readFileSync(file)).digest("hex");+}++/** Throws ChecksumError unless `file` hashes to `expectedHex`. */+export function verifySha256(file: string, expectedHex: string): void {+ const actual = Buffer.from(sha256File(file), "hex");+ const expected = Buffer.from(expectedHex, "hex");+ if (expected.length !== actual.length || !timingSafeEqual(actual, expected)) {+ throw new ChecksumError(+ `checksum mismatch for ${basename(file)}: expected ${expectedHex}, got ${actual.toString("hex")}`,+ );+ }+}++/**+ * Downloads `url` to `dest` and checks it against `url + ".sha256"` before+ * anything reads it. Fails closed: a missing or unreadable checksum is an+ * error, not a skip. Both requests go through curl, like the rest of+ * `ix upgrade`, so proxies and certificates behave the same for each.+ *+ * Throws ChecksumError for a bad or missing checksum; any other error is the+ * download itself failing.+ */+export function downloadVerified(+ url: string,+ dest: string,+ opts: { timeoutMs: number; progress?: boolean },+): void {+ execFileSync("curl", ["-fsSL", ...(opts.progress ? ["--progress-bar"] : []), url, "-o", dest], {+ stdio: ["ignore", "inherit", "inherit"],+ timeout: opts.timeoutMs,+ });+ let sidecar: string;+ try {+ sidecar = execFileSync("curl", ["-fsSL", `${url}.sha256`], {+ stdio: ["ignore", "pipe", "pipe"],+ timeout: 60_000,+ encoding: "utf8",+ });+ } catch {+ throw new ChecksumError(`no published checksum at ${url}.sha256; refusing to install an unverified archive`);+ }+ verifySha256(dest, parseSha256Sidecar(sidecar, basename(new URL(url).pathname)));+}++/**+ * Build provenance for a CLI release archive, checked with the GitHub CLI when+ * it is installed: `gh attestation verify` against the release workflow. The+ * checksum is the gate; this is a second, independent check whose failure is+ * reported but does not block, because it also fails for reasons that say+ * nothing about the archive (gh not logged in, no network to the API).+ */+export function attestationCommand(file: string, repo: string): [string, string[]] {+ return [+ "gh",+ ["attestation", "verify", file, "-R", repo, "--signer-workflow", `${repo}/.github/workflows/release.yml`],+ ];+}++/** `unavailable`: no gh on PATH, or one too old to have `gh attestation`. */+export type AttestationResult = { status: "verified" } | { status: "failed"; detail: string } | { status: "unavailable" };++export function verifyAttestation(file: string, repo: string): AttestationResult {+ const [cmd, args] = attestationCommand(file, repo);+ try {+ execFileSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"], timeout: 60_000 });+ return { status: "verified" };+ } catch (err) {+ const e = err as NodeJS.ErrnoException & { stderr?: Buffer | string };+ const detail = String(e.stderr || e.message).trim();+ if (e.code === "ENOENT" || /unknown command "attestation"/.test(detail)) return { status: "unavailable" };+ return { status: "failed", detail: detail.split("\n")[0] ?? "" };+ }+}