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(security): resolve all 12 CodeQL alerts + Scorecard quick wins (#284)
Joseph Mikhail143adb5fa8d2
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex f19cb4fb..40f8b051 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -13,6 +13,13 @@ updates:schedule:interval: weeklyopen-pull-requests-limit: 5+ ignore:+ # Toolchain majors need a deliberate, tested migration, not an auto-bump:+ # TypeScript 6.0 broke typescript-eslint 8.x here (#278). Minor/patch still flow.+ - dependency-name: "typescript"+ update-types: ["version-update:semver-major"]+ - dependency-name: "@types/node"+ update-types: ["version-update:semver-major"]groups:dev-dependencies:dependency-type: developmentdiff --git a/.github/workflows/security.yml b/.github/workflows/security.ymlindex c59fce7a..cfd2d6c8 100644--- a/.github/workflows/security.yml+++ b/.github/workflows/security.yml@@ -6,14 +6,17 @@ on:pull_request:branches: [main]+# Least privilege at the top; the scanning job elevates to upload SARIF.permissions:contents: read- security-events: writejobs:trivy-repo:name: Trivy (repo)runs-on: ubuntu-latest+ permissions:+ contents: read+ security-events: write # upload SARIF to code scanningsteps:- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2with:diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 00000000..8092d70b--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,25 @@+# Security Policy++## Reporting a vulnerability++Please report security issues privately, **not** as a public issue.++- Preferred: open a private report via GitHub Security Advisories+ (the repository's **Security → Report a vulnerability** tab), or+- Email the maintainers at [email protected].++Please include a description, reproduction steps, affected version, and impact.+We aim to acknowledge reports within 3 business days and to provide a remediation+timeline after triage. Please give us a reasonable window to ship a fix before+any public disclosure.++## Supported versions++Security fixes target the latest released version of the `ix` CLI. Older+versions are not maintained; please upgrade (`ix upgrade`) before reporting.++## Scope++This policy covers the `ix` CLI and the artifacts published from this+repository. The memory-layer backend is released from a separate repository and+has its own reporting channel.diff --git a/ix-cli/src/cli/__tests__/diff-content.test.ts b/ix-cli/src/cli/__tests__/diff-content.test.tsindex 128cf813..ecfc9430 100644--- a/ix-cli/src/cli/__tests__/diff-content.test.ts+++ b/ix-cli/src/cli/__tests__/diff-content.test.ts@@ -174,9 +174,12 @@ describe("diff.ts textual diff model", () => {expect(diffContent).toContain("computeTextualDiff(beforeSource, afterSource)");});- it("writes temp files to os.tmpdir for git diff --no-index", () => {+ it("uses a private temp dir under os.tmpdir for git diff --no-index and cleans it up", () => {expect(diffContent).toContain("os.tmpdir()");- expect(diffContent).toContain("unlinkSync");+ // Atomic private temp dir (mkdtempSync) + recursive cleanup, not predictably+ // named files in the shared tmpdir (CodeQL js/insecure-temporary-file).+ expect(diffContent).toContain("mkdtempSync");+ expect(diffContent).toContain("rmSync");});});diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.tsindex 6bff6c6d..0f3da14f 100644--- a/ix-cli/src/cli/bootstrap.ts+++ b/ix-cli/src/cli/bootstrap.ts@@ -1,4 +1,4 @@-import { mkdirSync, existsSync, writeFileSync } from "node:fs";+import { mkdirSync, writeFileSync } from "node:fs";import { join, basename, resolve } from "node:path";import { homedir } from "node:os";import { execFileSync } from "node:child_process";@@ -20,10 +20,16 @@ export interface BootstrapResult {export function ensureLocalConfig(): boolean {const configDir = join(homedir(), ".ix");const configPath = join(configDir, "config.yaml");- if (existsSync(configPath)) return false;mkdirSync(configDir, { recursive: true });- writeFileSync(configPath, `endpoint: ${getEndpoint()}\nformat: text\n`);- return true;+ try {+ // 'wx' creates the file atomically and throws EEXIST if it already exists,+ // avoiding the existsSync-then-write TOCTOU (CodeQL js/file-system-race).+ writeFileSync(configPath, `endpoint: ${getEndpoint()}\nformat: text\n`, { flag: "wx" });+ return true;+ } catch (err: any) {+ if (err?.code === "EEXIST") return false;+ throw err;+ }}// Roots whose workspace_id was re-keyed to the path-based id during THIS process,diff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.tsindex fbfeb3c9..8598224b 100644--- a/ix-cli/src/cli/commands/diff.ts+++ b/ix-cli/src/cli/commands/diff.ts@@ -162,10 +162,12 @@ export async function computeTextualDiff(before: string,after: string,): Promise<string[]> {- const tmpDir = os.tmpdir();- const ts = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;- const beforePath = path.join(tmpDir, `ix-diff-a-${ts}`);- const afterPath = path.join(tmpDir, `ix-diff-b-${ts}`);+ // Create a private temp directory atomically (0700, unique name) rather than+ // writing predictably-named files into the shared tmpdir, which is a symlink/+ // race vector (CodeQL js/insecure-temporary-file).+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ix-diff-"));+ const beforePath = path.join(tmpRoot, "a");+ const afterPath = path.join(tmpRoot, "b");fs.writeFileSync(beforePath, before);fs.writeFileSync(afterPath, after);@@ -182,8 +184,7 @@ export async function computeTextualDiff(if (!stdout) return [];return parseDiffOutput(stdout);} finally {- try { fs.unlinkSync(beforePath); } catch {}- try { fs.unlinkSync(afterPath); } catch {}+ try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch {}}}diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex 0e08fabc..da3eb863 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -1209,10 +1209,18 @@ export async function ingestFiles(// error messages still point at the file on disk.const readAndDispatch = chunk.map(async (absFilePath, idx) => {try {- const st = await fs.promises.stat(absFilePath);- if (st.size === 0) { filesSkipped++; return; }- if (st.size > MAX_FILE_BYTES) { tooLarge++; return; }- const bytes = await fs.promises.readFile(absFilePath);+ // Open once and fstat the same handle so the size check and the read+ // observe the same inode (no stat→read TOCTOU; CodeQL js/file-system-race).+ const fh = await fs.promises.open(absFilePath, 'r');+ let bytes!: Buffer;+ try {+ const st = await fh.stat();+ if (st.size === 0) { filesSkipped++; return; }+ if (st.size > MAX_FILE_BYTES) { tooLarge++; return; }+ bytes = await fh.readFile();+ } finally {+ await fh.close();+ }const hash = sha256(bytes);if (!opts.force && knownHashes.get(absFilePath) === hash) { filesSkipped++; return; }const previousHash = knownHashes.get(absFilePath);diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex 6c546f3a..913c7fa6 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -38,6 +38,13 @@ function getCurrentVersion(): string {}}+// Strict semver (X.Y.Z with optional -prerelease/+build). The release tag comes+// from the network and later flows into file paths, the install shim, and+// download URLs, so it is validated here at the source: anything that isn't a+// plain version is rejected (CodeQL js/http-to-file-access barrier + general+// hardening against a tampered/unexpected tag).+const VERSION_RE = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;+async function fetchLatestRelease(repo: string): Promise<string | null> {try {const resp = await fetch(@@ -45,7 +52,9 @@ async function fetchLatestRelease(repo: string): Promise<string | null> {);if (!resp.ok) return null;const data = (await resp.json()) as { tag_name?: string };- return data.tag_name?.replace(/^v/, "") ?? null;+ const version = data.tag_name?.replace(/^v/, "") ?? null;+ if (version === null || !VERSION_RE.test(version)) return null;+ return version;} catch {return null;}@@ -255,9 +264,13 @@ export function registerUpgradeCommand(program: Command): void {try {jsPath = execFileSync("cygpath", ["-u", jsPathWin], { encoding: "utf-8" }).trim();} catch { /* use windows path */ }- if (existsSync(shimPath)) {+ // Write the shim directly (creating ~/.local/bin if needed) rather than+ // existsSync-then-write, which is a TOCTOU (CodeQL js/file-system-race).+ // jsPath derives only from the validated-semver `latest` + install dir.+ try {+ mkdirSync(dirname(shimPath), { recursive: true });writeFileSync(shimPath, `#!/usr/bin/env bash\nexec node "${jsPath}" "$@"\n`);- }+ } catch { /* shim refresh is best-effort */ }}console.log(`[ok] Upgraded ix: ${current} → ${latest}`);diff --git a/ix-cli/src/cli/commands/view.ts b/ix-cli/src/cli/commands/view.tsindex 1c930584..749099bc 100644--- a/ix-cli/src/cli/commands/view.ts+++ b/ix-cli/src/cli/commands/view.ts@@ -222,6 +222,13 @@ export function registerViewCommand(program: Command): void {// workspace scoping (single-repo behavior is unaffected).}}+ // The system id (from a local marker or the backend) is embedded in the+ // generated, then-executed compass server script and the scope file, so+ // constrain it to the known id charset before use (CodeQL+ // js/http-to-file-access barrier; serverScript also JSON-encodes it).+ if (systemId !== null && !/^[A-Za-z0-9_.:-]+$/.test(systemId)) {+ systemId = null;+ }}const workspaceName = workspaceId? (findWorkspaceForCwd(process.cwd())?.workspace_name ?? workspaceId)diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex dfd0d7b2..add6c237 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -1,4 +1,4 @@-import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync } from "node:fs";+import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync, renameSync } from "node:fs";import { join, resolve as resolvePath } from "node:path";import { homedir } from "node:os";import { createHash } from "node:crypto";@@ -88,15 +88,25 @@ export function saveConfig(config: IxConfig): void {if (!OSS_OWNED_KEYS.has(k as keyof IxConfig)) preserved[k] = v;}const merged: Record<string, unknown> = { ...preserved, ...(config as unknown as Record<string, unknown>) };- // 0600 — the config holds credentials (Pro's instances carry a tunnel JWT and- // a long-lived IdP refresh token). `mode` on writeFileSync only applies when- // CREATING the file, so chmodSync enforces it on an already-existing file too- // (a pre-existing config written before this fix may be group/world-readable).- writeFileSync(configPath, stringify(merged), { mode: 0o600 });+ // Atomic write: serialize to a private (0600) temp file in the SAME directory,+ // then rename it over the target. The config holds credentials (Pro's instances+ // carry a tunnel JWT and a long-lived IdP refresh token), so this avoids both a+ // partially-written/looser-mode window and the read-modify-write race (CodeQL+ // js/file-system-race). Same-dir keeps the rename atomic; rename replaces on+ // POSIX and Windows alike, and inherits the temp's 0600 mode (tightening any+ // pre-existing group/world-readable config).+ const tmpPath = `${configPath}.${process.pid}.tmp`;+ writeFileSync(tmpPath, stringify(merged), { mode: 0o600 });try {- chmodSync(configPath, 0o600);+ renameSync(tmpPath, configPath);+ } catch (err) {+ try { rmSync(tmpPath, { force: true }); } catch { /* best effort */ }+ throw err;+ }+ try {+ chmodSync(configPath, 0o600); // belt-and-suspenders if umask altered the temp mode} catch {- // chmod can fail on exotic filesystems; the create-mode above is the primary guard.+ // chmod can fail on exotic filesystems; the temp's create-mode is the primary guard.}}