diff --git a/CHANGELOG.md b/CHANGELOG.md index 54a5ae8a..025609c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,38 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). command configured, a non-zero exit, non-JSON output, or a missing `token` all hard-error rather than silently degrading to HMAC-only. +### Fixed + +- **PAL finding sync no longer device-blind — a real security blocker can't be + silently cleared across devices.** The adversarial pass on the 3.0 surface + found that `palSyncFindings` auto-closed findings purely by source-tag + scope, + with **no `origin_device` predicate** — and because the finding id was derived + only from `sourceTag + dedupKey` (repo-independent), the id was *identical* + across machines on a shared/synced store. So a `kit check` on device B that + didn't see device A's open finding would **permanently close A's blocker** (and + two different repos that merely shared a directory *basename* reconciled into + each other's findings). The reconcile now (a) folds the scope into the id so + different repos get distinct rows, (b) scopes findings by the **absolute** + project root rather than its basename, and (c) **device-fences** the auto-close + (`origin_device = thisDevice OR NULL`), so a scan only clears findings this + device owns (legacy NULL-origin rows stay reconcilable by any device). A + genuinely-cleared finding now lingers until the owning device re-scans — + fail-safe (a stale reminder, never a dropped blocker). + +### Security + +- **Device identity is now an unguessable persisted token, not a hostname hash.** + `deviceId()` previously derived the per-device id from `sha256(hostname+user)` + — guessable by any peer on a shared store (enabling cross-device + surface/suppression of PAL items) and unstable across hostname churn (a DHCP + lease or machine rename would silently orphan a device's own items). It now + prefers a random id persisted once to `/device-id` (0600), and + validates the `KIT_DEVICE_ID` override against `[A-Za-z0-9_-]{1,64}` (a + malformed value is ignored rather than trusted). The hostname hash remains only + as a last-resort fallback when the id file can't be written. + +## [3.0.0] - 2026-06-30 + kit 3.0 — from a provable local floor to an org-governed control plane: machine **identity** (Ed25519) + **signable, distributable policy-as-code**, **governed cross-device memory** (encrypted sync + device-coupled action items), diff --git a/src/findings-track.ts b/src/findings-track.ts index e1130d82..64a363c2 100644 --- a/src/findings-track.ts +++ b/src/findings-track.ts @@ -41,8 +41,10 @@ export async function syncSecurityFindings( const { openMemoryDb } = await import("./memory/db.js"); const { palSyncFindings } = await import("./memory/pal.js"); const { getCurrentProjectRoot } = await import("./memory/project.js"); - const { basename } = await import("node:path"); - const scope = basename(getCurrentProjectRoot()); + // Scope by the ABSOLUTE project root, not its basename: two different repos + // that happen to share a directory name (e.g. ~/work/api and ~/scratch/api) + // must not reconcile into each other's findings. + const scope = getCurrentProjectRoot(); const db = openMemoryDb(); try { return palSyncFindings(db, "sec", actionableFindings(results).map(securityFindingToSync), { diff --git a/src/health-track.ts b/src/health-track.ts index 8da9729f..16eb84ee 100644 --- a/src/health-track.ts +++ b/src/health-track.ts @@ -21,8 +21,9 @@ export async function syncHealthFindings( const { openMemoryDb } = await import("./memory/db.js"); const { palSyncFindings } = await import("./memory/pal.js"); const { getCurrentProjectRoot } = await import("./memory/project.js"); - const { basename } = await import("node:path"); - const scope = basename(getCurrentProjectRoot()); + // Absolute root, not basename — same-named repos in different paths must not + // reconcile into each other's findings (see findings-track.ts). + const scope = getCurrentProjectRoot(); const db = openMemoryDb(); try { return palSyncFindings(db, "health", actionableHealth(findings).map(healthFindingToSync), { diff --git a/src/memory/pal.test.ts b/src/memory/pal.test.ts index f4e7d160..bebf1147 100644 --- a/src/memory/pal.test.ts +++ b/src/memory/pal.test.ts @@ -254,6 +254,57 @@ describe("palSyncFindings — findings → ledger (track layer)", () => { assert.ok(open[0]?.id.startsWith("sec-")); db.close(); }); + + // Regression: the adversarial pass found that the auto-close was device-blind. + // Because the finding id is identical across machines on a shared store, a scan + // on device B that doesn't see device A's finding would permanently close A's + // open security blocker. + const withDevice = (id: string, fn: () => T): T => { + const prev = process.env.KIT_DEVICE_ID; + process.env.KIT_DEVICE_ID = id; + try { + return fn(); + } finally { + if (prev === undefined) delete process.env.KIT_DEVICE_ID; + else process.env.KIT_DEVICE_ID = prev; + } + }; + + it("a scan on device B does NOT auto-close device A's open finding (shared store)", () => { + const db = fresh(); + withDevice("dev-A", () => palSyncFindings(db, "sec", [f("leak")], { scope: "repo" })); + // device B runs a scan of something else (empty for this source+scope) + const r = withDevice("dev-B", () => palSyncFindings(db, "sec", [], { scope: "repo" })); + assert.equal(r.closed.length, 0, "B must not close A's finding"); + const all = palList(db, { scope: "repo", allDevices: true }); + assert.equal(all.length, 1, "A's finding is still open"); + assert.equal(all[0]?.origin_device, "dev-A"); + // and A's own re-scan that no longer sees it CAN close it + const ra = withDevice("dev-A", () => palSyncFindings(db, "sec", [], { scope: "repo" })); + assert.equal(ra.closed.length, 1, "the owning device reconciles its own finding"); + db.close(); + }); + + it("the same finding in two different repos maps to two distinct rows", () => { + const db = fresh(); + palSyncFindings(db, "sec", [f("leak")], { scope: "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/abs/repo-x" }); + palSyncFindings(db, "sec", [f("leak")], { scope: "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/abs/repo-y" }); + const all = palList(db, { allDevices: true }); + assert.equal(all.length, 2, "scope is folded into the id — no cross-repo collision"); + assert.notEqual(all[0]?.id, all[1]?.id); + }); + + it("legacy NULL-origin findings are reconcilable by any device", () => { + const db = fresh(); + // simulate a pre-v5 open finding row (no origin_device) at this scope+id + const legacyId = findingPalId("sec", "repo\x1fold"); + db.prepare( + "INSERT INTO pending_actions (id, status, title, scope, kind, origin_device) VALUES (?, 'open', 'old', 'repo', 'finding', NULL)", + ).run(legacyId); + const r = withDevice("whoever", () => palSyncFindings(db, "sec", [], { scope: "repo" })); + assert.equal(r.closed.length, 1, "a NULL-origin legacy finding can be cleared by any device"); + db.close(); + }); }); describe("PAL — device coupling (don't nag about ephemeral-session items)", () => { diff --git a/src/memory/pal.ts b/src/memory/pal.ts index 5bfaa324..ec746f4c 100644 --- a/src/memory/pal.ts +++ b/src/memory/pal.ts @@ -16,28 +16,69 @@ * no-info aware. */ import { randomBytes, createHash } from "node:crypto"; -import { readFileSync, existsSync } from "node:fs"; +import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs"; import { homedir, hostname, userInfo } from "node:os"; -import { join } from "node:path"; +import { join, dirname } from "node:path"; import type { DatabaseSync } from "node:sqlite"; +/** A device id is an opaque, filesystem- and SQL-safe token. We validate any + * externally-supplied value against this before trusting it. */ +const DEVICE_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; + +/** Where the persisted per-device id lives. Mirrors `getMemoryDir()` (db.ts) but + * is inlined to avoid a circular import. */ +function deviceIdPath(): string { + const dir = process.env.KIT_MEMORY_DIR ?? join(homedir(), ".kit"); + return join(dir, "device-id"); +} + +/** Hostname+user-derived id. Deterministic, but DRIFTS when the hostname changes + * (DHCP lease, machine rename, a sudo/login shell with a different hostname), + * which would silently orphan this device's own items. Used only as a last + * resort when a persisted id can neither be read nor written. */ +function hostnameDeviceId(): string { + try { + return createHash("sha256") + .update(`${hostname()}\x1f${userInfo().username}`) + .digest("hex") + .slice(0, 16); + } catch { + return "unknown"; + } +} + /** * A stable identifier for THIS device. Used to device-couple PAL items so an item * created in an ephemeral session/container (which gets its own throwaway id) - * never nags on your durable device. Derived from hostname + user (no network, no - * identity required); overridable via KIT_DEVICE_ID. An ephemeral container's - * random hostname yields a different id, which is exactly what we want. + * never nags on your durable device. + * + * Resolution order: + * 1. `KIT_DEVICE_ID` IF well-formed (`[A-Za-z0-9_-]{1,64}`). A malformed value is + * ignored, not trusted. SECURITY: on a SHARED store this override is + * trust-bearing — setting it to another device's id lets you surface or + * suppress that device's items. Set it only on trusted hosts. + * 2. A random id persisted once to `/device-id` (0600). Unguessable + * and stable across hostname churn — unlike the host-derived hash, which a + * peer on a shared store can also guess from `sha256(hostname+user)`. + * 3. Hostname-derived hash, only if the id file can't be read or written. */ export function deviceId(): string { const override = (process.env.KIT_DEVICE_ID ?? "").trim(); - if (override) return override; + if (override && DEVICE_ID_RE.test(override)) return override; + // (a malformed override falls through to the persisted id rather than being trusted) try { - return createHash("sha256") - .update(`${hostname()}\x1f${userInfo().username}`) - .digest("hex") - .slice(0, 16); + const path = deviceIdPath(); + if (existsSync(path)) { + const saved = readFileSync(path, "utf8").trim(); + if (DEVICE_ID_RE.test(saved)) return saved; + } + const fresh = randomBytes(8).toString("hex"); // 16 hex chars, unguessable + const dir = dirname(path); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 }); + writeFileSync(path, fresh + "\n", { mode: 0o600 }); + return fresh; } catch { - return "unknown"; + return hostnameDeviceId(); } } @@ -209,8 +250,17 @@ export function findingPalId(sourceTag: string, dedupKey: string): string { * re-scan is idempotent). An item that had cleared (closed) and now recurs is * REOPENED; an open item whose finding the scan no longer reports is auto-CLOSED. * Finding-presence IS the verify, so this needs no shell and no stored command — - * same security posture as the rest of PAL. Reconciliation is per source-tag and - * per scope, so a partial sync never touches another source's or repo's items. + * same security posture as the rest of PAL. + * + * Reconciliation is fenced three ways so a sync never clears someone else's + * blocker: by source-tag, by scope (and the scope is folded INTO the id, so two + * repos sharing a finding category never collide on one row), and by + * origin_device. The device fence is the important one: on a SHARED store the + * finding id is identical across machines, so without it a scan on device B that + * doesn't see device A's finding would auto-close A's open security item. A scan + * now only auto-closes findings this device owns (or legacy NULL-origin rows); a + * genuinely-cleared finding lingers until the OWNING device re-scans — fail-safe + * (a stale reminder, never a silently-dropped blocker). */ export function palSyncFindings( db: DatabaseSync, @@ -219,12 +269,16 @@ export function palSyncFindings( opts: { scope?: string } = {}, ): SyncFindingsResult { const scope = opts.scope ?? null; + // Fold scope into the id so the same finding in two different repos maps to two + // distinct ledger rows (findingPalId alone is repo-independent). + const idFor = (dedupKey: string) => + findingPalId(sourceTag, scope ? `${scope}\x1f${dedupKey}` : dedupKey); const currentIds = new Set(); let added = 0; let reopened = 0; for (const f of findings) { - const id = findingPalId(sourceTag, f.dedupKey); + const id = idFor(f.dedupKey); currentIds.add(id); const existing = db.prepare("SELECT status FROM pending_actions WHERE id = ?").get(id) as | { status: string } @@ -236,9 +290,11 @@ export function palSyncFindings( ).run(id, f.title, f.detail ?? null, scope, deviceId(), process.cwd()); added++; } else if (existing.status === "closed") { + // Re-attribute on reopen: the device observing the recurrence is the one + // that should be reminded (and able to auto-close it once it clears). db.prepare( - "UPDATE pending_actions SET status='open', closed_at=NULL, title=?, detail=? WHERE id=?", - ).run(f.title, f.detail ?? null, id); + "UPDATE pending_actions SET status='open', closed_at=NULL, title=?, detail=?, origin_device=?, origin_root=? WHERE id=?", + ).run(f.title, f.detail ?? null, deviceId(), process.cwd(), id); reopened++; } else { // already open/snoozed — refresh the text so the reminder stays accurate @@ -250,12 +306,15 @@ export function palSyncFindings( } } - // Auto-close findings of THIS source + scope that the scan no longer reports. + // Auto-close findings of THIS source + scope + device that the scan no longer + // reports. The origin_device fence stops a scan on one machine from clearing a + // finding another machine is blocked on (shared store → identical ids); legacy + // NULL-origin rows predate device coupling and are reconcilable by any device. const open = db .prepare( - "SELECT id FROM pending_actions WHERE kind='finding' AND status='open' AND id LIKE ? AND scope IS ?", + "SELECT id FROM pending_actions WHERE kind='finding' AND status='open' AND id LIKE ? AND scope IS ? AND (origin_device = ? OR origin_device IS NULL)", ) - .all(`${sourceTag}-%`, scope) as { id: string }[]; + .all(`${sourceTag}-%`, scope, deviceId()) as { id: string }[]; const closed: string[] = []; for (const row of open) { if (!currentIds.has(row.id) && palDone(db, row.id)) closed.push(row.id);