From 5afa49b6bc334ae7ed9f4e461b527083073dfddd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20Sandstr=C3=B6m?= Date: Wed, 17 Jun 2026 13:00:50 +0200 Subject: [PATCH] feat(pal)!: declarative typed verify checks, no shell execution (1.4.0) palAutoVerify no longer runs a stored shell string via execSync. A verify is now a typed check (http-status via fetch, file-exists via fs) executed natively, never through a shell and never by interpolating a stored value into a command. A defensive parser rejects any unknown/injected shape, so a planted or imported verify is inert. Why: kit is agent-native. The old verify_cmd was a persistence/deferred-exec primitive: a prompt-injected low-trust session could store a command that later detonated when a more-trusted session ran `kit memory pal verify`. The typed model removes the sink at the root while staying autonomy-friendly (auto-verify needs no human gate, so autonomous agent jobs do not break). CLI: --verify-http [--expect ] / --verify-file replace --verify "". DB: new pending_actions.verify_check (JSON); legacy verify_cmd kept for kit memory scan but never auto-executed. Tests: declarative pass/fail/regress + two SECURITY regressions (imported and injected shapes never execute). 2219 green. Co-Authored-By: Claude Opus 4.8 --- CHANGELOG.md | 8 +++ docs/MEMORY.md | 25 +++++++--- package.json | 2 +- src/commands/memory.ts | 17 +++++-- src/memory/db.ts | 5 ++ src/memory/pal.test.ts | 55 ++++++++++++++++----- src/memory/pal.ts | 107 ++++++++++++++++++++++++++++++----------- 7 files changed, 169 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39fc4654..591a8903 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.4.0] - 2026-06-17 + +### Security +- **PAL verify is now a declarative, typed check instead of a raw shell command.** `palAutoVerify` no longer runs a stored shell string through `execSync`; it runs a typed check natively (`http-status` via fetch, `file-exists` via fs), never through a shell and never by interpolating a stored value into a command. There is no longer an arbitrary-command-execution sink. This removes a persistence/deferred-execution risk that mattered for kit's agent-native use: a prompt-injected agent could previously store a `verify_cmd` in one (low-trust) session that detonated later when a more-trusted session ran `kit memory pal verify`. The typed model is also deliberately autonomy-friendly: auto-verify needs no human gate, yet a planted or injected value is inert (a defensive parser rejects any unknown shape). Closes the residual `memory/pal.js` finding (Socket AI) at the root rather than by adding a human-in-the-loop gate that would break autonomous agent jobs. + +### Changed +- **`kit memory pal add` verify flags:** use `--verify-http [--expect ]` or `--verify-file ` instead of `--verify ""`. For checks these types do not cover, run the check yourself and close the item manually (pal stays a ledger). Raw shell `verify_cmd` from pre-1.4 stores is retained so `kit memory scan` can still find secrets in old rows, but is never auto-executed. + ## [1.3.1] - 2026-06-17 ### Security diff --git a/docs/MEMORY.md b/docs/MEMORY.md index 0ffb5674..e83cda4a 100644 --- a/docs/MEMORY.md +++ b/docs/MEMORY.md @@ -92,16 +92,25 @@ source-verifiable: see the table in the repo notes.) ### Pending actions (PAL) A structured "blocked-on-you" ledger on top of the raw log — items that survive -across sessions and **auto-close when their verify command starts passing**. +across sessions and **auto-close when their declarative verify check starts +passing**. A verify is a typed, native check (no shell), so it is safe to +auto-run unattended and a planted value can never execute code: ```bash -kit memory pal # list open items -kit memory pal add "ship the release" --verify "curl -fsS https://… | grep -q 200" +kit memory pal # list open items +kit memory pal add "ship the release" --verify-http https://example.com --expect 200 +kit memory pal add "build artifact exists" --verify-file ./dist/cli.js kit memory pal done | snooze -kit memory pal verify # run verifies: N=2 consecutive passes closes; a regression reopens -kit memory pal import # migrate a legacy ~/.claude/pal/ledger.jsonl +kit memory pal verify # run checks: N=2 consecutive passes closes; a regression reopens +kit memory pal import # migrate a legacy ~/.claude/pal/ledger.jsonl (verifies become manual) ``` +Supported verify checks: `--verify-http [--expect ]` (kit makes the +request and compares the status) and `--verify-file ` (file exists). kit +never runs a shell verify. For a check these types do not cover, run it yourself +and close the item manually. Raw shell `verify_cmd` from pre-1.4 stores is never +auto-executed. + Open items surface in the `UserPromptSubmit` reminder so handed-off tasks stop getting forgotten. Verify commands run in your shell — they are **operator-authored and live in the personal store only**; never put an executable verify on an item @@ -183,8 +192,10 @@ Shared memory is **treated like code**: cell contents. It reports masked findings and exits non-zero if any are found, so you can use it as a gate. - Backups are encrypted (AES-256-GCM, scrypt). The passphrase is never stored. -- Shared writes are secret-scanned fail-closed; executable verify commands never - cross the sharing boundary. +- Shared writes are secret-scanned fail-closed. Verify checks are declarative + and typed (no shell), and a verify imported or merged from another store is + demoted to a manual item, so no executable ever crosses a file, DB, or sharing + boundary and auto-runs. ## Where it sits diff --git a/package.json b/package.json index 45f046d2..fc9cd9f1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.3.1", + "version": "1.4.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "type": "module", diff --git a/src/commands/memory.ts b/src/commands/memory.ts index e7db8382..3dc17ec9 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -31,6 +31,7 @@ import { palSnooze, palAutoVerify, importLegacyLedger, + type VerifyCheck, } from "../memory/pal.js"; import { saveThread, @@ -109,13 +110,23 @@ async function memPal(): Promise { const title = process.argv.slice(5).filter((a) => !a.startsWith("--")).join(" ").trim(); if (!title) { console.error( - `${c.red}usage: kit memory pal add [--verify=<cmd>] [--scope=<s>]${c.reset}`, + `${c.red}usage: kit memory pal add <title> [--verify-http <url> [--expect <code>]] [--verify-file <path>] [--scope=<s>]${c.reset}`, ); return false; } + // Declarative verify only (no shell). http-status or file-exists. + const httpUrl = flagValue(process.argv, "--verify-http"); + const filePath = flagValue(process.argv, "--verify-file"); + let check: VerifyCheck | undefined; + if (httpUrl) { + const expect = Number(flagValue(process.argv, "--expect") ?? "200"); + check = { type: "http-status", url: httpUrl, expect: Number.isFinite(expect) ? expect : 200 }; + } else if (filePath) { + check = { type: "file-exists", path: filePath }; + } const id = palAdd(db, { title, - verifyCmd: flagValue(process.argv, "--verify"), + check, scope: flagValue(process.argv, "--scope") ?? basename(getCurrentProjectRoot()), }); console.log(`${c.green}✓${c.reset} added ${c.bold}${id}${c.reset}`); @@ -149,7 +160,7 @@ async function memPal(): Promise<boolean> { return true; } if (action === "verify") { - const r = palAutoVerify(db); + const r = await palAutoVerify(db); console.log( `${c.dim}checked ${r.checked} · closed ${r.closed.length} · reopened ${r.reopened.length}${c.reset}`, ); diff --git a/src/memory/db.ts b/src/memory/db.ts index 0ddef293..e8afec4f 100644 --- a/src/memory/db.ts +++ b/src/memory/db.ts @@ -93,6 +93,7 @@ CREATE TABLE IF NOT EXISTS pending_actions ( scope TEXT, kind TEXT NOT NULL DEFAULT 'manual', verify_cmd TEXT, + verify_check TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP, next_check TEXT, snooze_until TEXT, @@ -149,6 +150,10 @@ function migrate(db: DatabaseSync): void { // v2: pending_actions.verify_passes (N=2 auto-verify confirmation). Add to // tables created before this column existed. ensureColumn(db, "pending_actions", "verify_passes", "INTEGER NOT NULL DEFAULT 0"); + // v3: pending_actions.verify_check (declarative typed verify replacing raw + // shell verify_cmd). Legacy verify_cmd rows have a NULL verify_check and are + // never auto-executed. + ensureColumn(db, "pending_actions", "verify_check", "TEXT"); const row = db.prepare("SELECT version FROM schema_meta LIMIT 1").get() as | { version: number } | undefined; diff --git a/src/memory/pal.test.ts b/src/memory/pal.test.ts index 4a637202..e23f9f2b 100644 --- a/src/memory/pal.test.ts +++ b/src/memory/pal.test.ts @@ -16,10 +16,13 @@ import { describe("PAL — pending actions", () => { const fresh = () => openMemoryDb(":memory:"); - it("adds + lists; kind inferred from verifyCmd", () => { + it("adds + lists; kind inferred from a verify check", () => { const db = fresh(); const manual = palAdd(db, { title: "ship the harvest branch" }); - const auto = palAdd(db, { title: "endpoint returns 200", verifyCmd: "true" }); + const auto = palAdd(db, { + title: "endpoint returns 200", + check: { type: "http-status", url: "https://example.com", expect: 200 }, + }); assert.match(manual, /^[0-9a-f]{4}$/); const open = palList(db); assert.equal(open.length, 2); @@ -47,29 +50,39 @@ describe("PAL — pending actions", () => { db.close(); }); - it("auto-verify closes after N=2 passes; a failing verify stays open", () => { + it("auto-verify closes after N=2 passes; a failing check stays open", async () => { const db = fresh(); - const passes = palAdd(db, { title: "passing check", verifyCmd: "true" }); - const fails = palAdd(db, { title: "failing check", verifyCmd: "false" }); - let r = palAutoVerify(db); + const tmp = mkdtempSync(join(tmpdir(), "kit-pal-")); + const present = join(tmp, "present"); + writeFileSync(present, "x"); + const missing = join(tmp, "missing"); + const passes = palAdd(db, { title: "passing check", check: { type: "file-exists", path: present } }); + const fails = palAdd(db, { title: "failing check", check: { type: "file-exists", path: missing } }); + let r = await palAutoVerify(db); assert.deepEqual(r.closed, []); // first pass: streak = 1 assert.equal(palList(db).length, 2); - r = palAutoVerify(db); + r = await palAutoVerify(db); assert.deepEqual(r.closed, [passes]); // second consecutive pass closes it const open = palList(db); assert.equal(open.length, 1); assert.equal(open[0]?.id, fails); + rmSync(tmp, { recursive: true, force: true }); db.close(); }); - it("reopens a closed auto item when its verify regresses", () => { + it("reopens a closed auto item when its check regresses", async () => { const db = fresh(); - const id = palAdd(db, { title: "regressing check", verifyCmd: "false" }); + const tmp = mkdtempSync(join(tmpdir(), "kit-pal-")); + const artifact = join(tmp, "artifact"); + writeFileSync(artifact, "x"); + const id = palAdd(db, { title: "regressing check", check: { type: "file-exists", path: artifact } }); palDone(db, id); // force-close assert.equal(palList(db, { status: "closed" }).length, 1); - const r = palAutoVerify(db); // verify 'false' on a closed auto item → reopen + rmSync(artifact); // artifact gone -> the check now fails + const r = await palAutoVerify(db); // fail on a closed auto item -> reopen assert.deepEqual(r.reopened, [id]); assert.equal(palList(db).length, 1); + rmSync(tmp, { recursive: true, force: true }); db.close(); }); @@ -113,7 +126,7 @@ describe("PAL — pending actions", () => { db.close(); }); - it("SECURITY: a verify command imported from a legacy ledger is never auto-executed", () => { + it("SECURITY: a verify command imported from a legacy ledger is never auto-executed", async () => { const db = fresh(); const tmp = mkdtempSync(join(tmpdir(), "kit-pal-sec-")); const led = join(tmp, "ledger.jsonl"); @@ -132,12 +145,30 @@ describe("PAL — pending actions", () => { const item = palList(db).find((p) => p.id === "evil"); assert.equal(item?.kind, "manual"); // demoted: not an auto item assert.equal(item?.verify_cmd ?? null, null); // executable command dropped on import - palAutoVerify(db); // must NOT run `touch ${marker}` + await palAutoVerify(db); // must NOT run `touch ${marker}` assert.equal(existsSync(marker), false, "imported verify_cmd must never execute"); rmSync(tmp, { recursive: true, force: true }); db.close(); }); + it("SECURITY: an unknown/injected verify_check shape is never executed", async () => { + const db = fresh(); + const tmp = mkdtempSync(join(tmpdir(), "kit-pal-sec2-")); + const marker = join(tmp, "PWNED"); + // Simulate DB tampering: inject a row with a bogus verify_check that a naive + // executor might run as a command. parseCheck must reject the unknown shape; + // nothing executes. + db.prepare( + `INSERT INTO pending_actions (id, status, title, kind, verify_check) + VALUES ('evil', 'open', 'injected', 'auto', ?)`, + ).run(JSON.stringify({ type: "shell", cmd: `touch ${marker}` })); + const r = await palAutoVerify(db); + assert.equal(r.checked, 0); // unknown shape -> not even run + assert.equal(existsSync(marker), false, "injected verify_check must never execute"); + rmSync(tmp, { recursive: true, force: true }); + db.close(); + }); + it("scopes the open list to a project (plus globally-scoped items)", () => { const db = fresh(); palAdd(db, { title: "kit item", scope: "kit" }); diff --git a/src/memory/pal.ts b/src/memory/pal.ts index ddc91f35..4fae7c68 100644 --- a/src/memory/pal.ts +++ b/src/memory/pal.ts @@ -3,17 +3,33 @@ * * PAL is the STRUCTURED, actionable layer on top of raw conversation memory: * "blocked-on-you" items that survive sessions and auto-close when their verify - * command starts passing. It lives in the `pending_actions` table of the same - * SQLite store. Deterministic; the only side effect is running operator-defined - * verify commands (local shell, with a timeout). Fail-open / no-info aware. + * check starts passing. It lives in the `pending_actions` table of the same + * SQLite store. + * + * SECURITY: a verify is a DECLARATIVE, typed check (see `VerifyCheck`), executed + * natively (fetch / fs) with a timeout. kit NEVER runs a shell, and never + * interpolates a stored string into a command, so there is no arbitrary-command- + * execution sink: a planted or imported value can only ever do what the fixed + * check types allow (nothing). This is deliberately compatible with autonomous + * agents: auto-verify needs no human gate, yet a prompt-injected agent cannot + * plant a command that detonates later in a more-trusted session. Fail-open / + * no-info aware. */ import { randomBytes } from "node:crypto"; -import { execSync } from "node:child_process"; import { readFileSync, existsSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import type { DatabaseSync } from "node:sqlite"; +/** + * A declarative verify check. Fixed shapes only, executed natively by kit (no + * shell, no arbitrary binary). Add a new shape here only if it can be run as a + * pure data operation that cannot be coerced into command execution. + */ +export type VerifyCheck = + | { type: "http-status"; url: string; expect: number } + | { type: "file-exists"; path: string }; + export interface PendingAction { id: string; status: string; @@ -21,7 +37,11 @@ export interface PendingAction { detail: string | null; scope: string | null; kind: string; + /** Legacy raw shell command from pre-1.4 stores. NEVER executed; kept only so + * `kit memory scan` can still find secrets leaked into old rows. */ verify_cmd: string | null; + /** JSON-encoded VerifyCheck. The only field auto-verify ever executes. */ + verify_check: string | null; created_at: string | null; next_check: string | null; snooze_until: string | null; @@ -34,7 +54,7 @@ export interface PalAddInput { detail?: string; scope?: string; kind?: "manual" | "auto"; - verifyCmd?: string; + check?: VerifyCheck; } function newId(db: DatabaseSync): string { @@ -47,11 +67,12 @@ function newId(db: DatabaseSync): string { export function palAdd(db: DatabaseSync, input: PalAddInput): string { const id = newId(db); - const kind = input.kind ?? (input.verifyCmd ? "auto" : "manual"); + const kind = input.kind ?? (input.check ? "auto" : "manual"); + const verifyCheck = input.check ? JSON.stringify(input.check) : null; db.prepare( - `INSERT INTO pending_actions (id, status, title, detail, scope, kind, verify_cmd) + `INSERT INTO pending_actions (id, status, title, detail, scope, kind, verify_check) VALUES (?, 'open', ?, ?, ?, ?, ?)`, - ).run(id, input.title, input.detail ?? null, input.scope ?? null, kind, input.verifyCmd ?? null); + ).run(id, input.title, input.detail ?? null, input.scope ?? null, kind, verifyCheck); return id; } @@ -95,24 +116,51 @@ export function palSnooze(db: DatabaseSync, id: string, days: number): boolean { } /** - * Run a verify command. true = pass (exit 0), false = ran but failed, null = no-info. - * - * SECURITY: this runs `cmd` through a shell on purpose — verify commands routinely - * need pipes / `&&` (e.g. `curl -fsS … | grep 200`). The trust boundary: `verify_cmd` - * is OPERATOR-AUTHORED and lives only in the PERSONAL store (~/.kit/memory.db); running - * it is equivalent to the operator running their own command — no untrusted data is - * interpolated, so this is not a command-injection sink. INVARIANT for Track D (shared - * memory): shared/synced items must NEVER carry an executable `verify_cmd` that runs - * unreviewed — only manual items or review-gated verifies cross the sharing boundary. + * Parse the stored JSON into a VerifyCheck, defensively. Only known shapes are + * accepted; anything malformed, unknown, or legacy returns null and is never + * executed. This is the gate that makes a planted/imported value inert. */ -function runVerify(cmd: string): boolean | null { +function parseCheck(json: string | null): VerifyCheck | null { + if (!json) return null; + let raw: unknown; try { - execSync(cmd, { stdio: "ignore", timeout: 15_000 }); - return true; - } catch (err) { - const status = (err as { status?: number | null }).status; - if (typeof status === "number") return false; // ran, non-zero exit - return null; // spawn error / timeout → no-info, leave state unchanged + raw = JSON.parse(json); + } catch { + return null; + } + if (!raw || typeof raw !== "object") return null; + const o = raw as Record<string, unknown>; + if (o.type === "file-exists" && typeof o.path === "string") { + return { type: "file-exists", path: o.path }; + } + if (o.type === "http-status" && typeof o.url === "string" && typeof o.expect === "number") { + return { type: "http-status", url: o.url, expect: o.expect }; + } + return null; +} + +/** + * Run a declarative verify check. true = pass, false = ran but failed, null = + * no-info (leave state unchanged). Executed NATIVELY (fetch / fs), never through + * a shell and never by interpolating a stored string into a command, so there is + * no command-execution sink: a check can only do what its fixed type allows. + */ +async function runCheck(check: VerifyCheck): Promise<boolean | null> { + try { + if (check.type === "file-exists") { + return existsSync(check.path); + } + // http-status: kit makes the request itself; the URL is data, not a command. + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 15_000); + try { + const res = await fetch(check.url, { signal: controller.signal, redirect: "manual" }); + return res.status === check.expect; + } finally { + clearTimeout(timer); + } + } catch { + return null; // network/fs error or timeout → no-info } } @@ -127,15 +175,20 @@ export interface AutoVerifyResult { * times is closed (a pass increments the streak, a fail resets it). A CLOSED item * whose verify now FAILS is reopened (reopen-on-regress). No-info leaves it alone. */ -export function palAutoVerify(db: DatabaseSync, confirmPasses = 2): AutoVerifyResult { +export async function palAutoVerify( + db: DatabaseSync, + confirmPasses = 2, +): Promise<AutoVerifyResult> { const out: AutoVerifyResult = { checked: 0, closed: [], reopened: [] }; const rows = db .prepare( - "SELECT * FROM pending_actions WHERE kind='auto' AND verify_cmd IS NOT NULL AND status IN ('open','closed')", + "SELECT * FROM pending_actions WHERE kind='auto' AND verify_check IS NOT NULL AND status IN ('open','closed')", ) .all() as unknown as PendingAction[]; for (const r of rows) { - const result = runVerify(r.verify_cmd as string); + const check = parseCheck(r.verify_check); + if (!check) continue; // malformed/unknown/legacy shape -> never executed + const result = await runCheck(check); if (result === null) continue; // no-info out.checked++; if (r.status === "open") {