Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,24 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/).

## [Unreleased]

## [1.4.0] - 2026-06-17

### Added
- **`kit context check` — per-project CLI context lock.** Declare each tool's exact account + project in `.kit.toml` `[context]` (gcloud account/project, vercel team/project, github org/remote, git email, npm registry). `kit context check` reads the LIVE tool state and verifies it matches, and **never infers a pairing from whatever happens to be logged in or selected**: a right account with the wrong project is a mismatch, not a pass. Read-only; exits non-zero on a mismatch so it can gate a git hook or an agent before an outward or destructive command. Context pointers are non-secret and live in config; the credentials they authenticate with stay in the vault. (Catches the class of incident where a repo carries a stale deploy connection from a previous purpose, or a CLI is pointed at the wrong org.)
- **`kit hooks add context-check`** — installs a `pre-push` git hook that runs `kit context check` and blocks the push on a mismatch. This is the enforcement: a push to the wrong org/project is stopped before it leaves the machine.
- **`kit context use`** — activates the declared context (gcloud config + repo git identity) so every CLI points at the right account/project atomically. Touches only local config, never an account or a deploy; vercel/npm get guidance rather than an auto-switch.
- **`kit context --prompt`** — a fast, read-only indicator of the active gcloud context (e.g. `[gcp:my-project]`) for your shell prompt, read from gcloud's config files (no subprocess per prompt), so the context you are in is always visible.
- **Rule citations on security checks.** Each `kit check` security finding now carries the rule it enforces (CWE / OWASP Top 10) in the `--json` output and as a `[CWE-…]` tag in the text table, via a local, deterministic rules catalog (`src/rules/catalog.ts`). It cites kit's own checks (gitignore, secrets, dep-pinning, lockfiles, service exposure); a check without a defensible anchor carries no rule rather than a forced one. Foundation for consolidating + citing findings across kit and the scanners it wraps.

### Changed
- **`kit memory pal add` verify flags:** use `--verify-http <url> [--expect <code>]` or `--verify-file <path>` instead of `--verify "<shell>"`. 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.

### Fixed
- **A `--help`/`-h` flag never executes a side-effectful subcommand.** `kit memory <subcommand> --help` (e.g. `kit memory install --help`) previously ran the subcommand instead of printing help, so `kit memory install --help` would actually install the hooks. It now shows help and does nothing else.

### 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.

## [1.3.1] - 2026-06-17

### Security
Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ Complete reference: [`docs/COMMANDS.md`](./docs/COMMANDS.md). The shortlist:
- `kit auth {elevate,setup-totp,status,revoke}`: Elevation gate + TOTP
- `kit mcp {list,auth,set-token,clear}`: MCP-server orchestrator
- `kit env {list,switch,current,diff}`: Environment routing + drift detection
- `kit context {check,use,--prompt}`: Lock each CLI to its declared account + project (no wrong-org pushes)
- `kit triage {npm,pip,docker,repo,skill}`: Pre-install security check
- `kit security {scan-build,scan-staged,verify-pull,costs,policy}`: Security ops
- `kit hooks {install,add,sync}`: Git hooks + bypass detector
Expand Down Expand Up @@ -249,6 +250,7 @@ migration, to deploy-platform propagation, to destructive history cleanup.

- `secret-scan` (pre-commit): Block commits that introduce known credential patterns
- `post-pull-audit` (post-merge): Run `verify-pull` after every `git pull` / merge
- `context-check` (pre-push): Block a push when the live CLI context does not match `.kit.toml [context]` (see Context lock)

### Environments + elevation

Expand All @@ -262,6 +264,26 @@ Production credentials are gated behind explicit env-switching and short-lived e
- `kit auth revoke`: Drop the elevation marker early
- `kit audit secrets [--since-days N] [--key <name>]`: Forensics: who touched which key, when

### Context lock

When you work across several accounts and projects (gcloud, Vercel, GitHub, npm) it is easy to be in the wrong one without noticing, and a logged-in account plus a selected project are not assumed to belong together. Declare the exact pair per repo and kit verifies the live tools against it:

```toml
[context]
gcloud = { account = "ops@acme.com", project = "acme-prod", config = "acme", region = "europe-west4" }
vercel = { team = "team_…", project = "prj_…" } # the ids in .vercel/project.json
github = { org = "acme", remote = "github.com/acme/app" }
git = { email = "you@acme.com" }
npm = { registry = "https://registry.npmjs.org" }
```

- `kit context check`: verify the live account+project of each CLI matches the declaration. A right account with the wrong project is a mismatch, not a pass. Read-only; exits non-zero so it can gate.
- `kit context use`: activate the declared context (gcloud config + repo git identity). Touches only local config, never an account or a deploy.
- `kit context --prompt`: a fast, read-only indicator (e.g. `[gcp:acme-prod]`) for your shell prompt, so the context you are in is always visible.
- `kit hooks add context-check`: install a pre-push hook so a push to the wrong org/project is blocked before it leaves the machine.

Context pointers are non-secret and live in config; the credentials they authenticate with stay in the vault.

### Quality gates (baseline-aware)

- `kit check --enforce-tests`: Fail when net-new source files lack a sibling `.test.ts`
Expand Down
25 changes: 18 additions & 7 deletions docs/MEMORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <id> | snooze <id> <days>
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 <url> [--expect <code>]` (kit makes the
request and compares the status) and `--verify-file <path>` (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
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
10 changes: 9 additions & 1 deletion src/check-security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { promisify } from "node:util";
import { readFile, access } from "node:fs/promises";
import { resolve } from "node:path";
import { execFileNoThrow } from "./utils/execFileNoThrow.js";
import { ruleForCheck, type RuleRef } from "./rules/catalog.js";
import {
ensureBumblebee,
runScan,
Expand Down Expand Up @@ -51,6 +52,7 @@ export interface SecurityCheckResult {
severity?: "critical" | "high" | "medium" | "low";
files?: string[]; // Files with issues (for secrets scan)
suggestion?: string; // Installation or remediation instructions
rule?: RuleRef; // citation for the rule this check enforces (CWE/OWASP), if mapped
}

/**
Expand Down Expand Up @@ -1005,7 +1007,13 @@ export async function checkSecurity(): Promise<SecurityCheckResult[]> {
const exposureResults = await checkServiceExposure();
results.push(...exposureResults);

return results;
// Attach a rule citation (CWE/OWASP) to each finding whose check is mapped in
// the local rules catalog. Deterministic lookup, no network. Unmapped checks
// pass through unchanged.
return results.map((r) => {
const rule = ruleForCheck(r.name);
return rule ? { ...r, rule } : r;
});
}

/**
Expand Down
85 changes: 85 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ import { promptConfirm } from "./utils/prompt.js";
import { c } from "./utils/colors.js";
import { gatherStatus } from "./status.js";
import { KIT_FILE, resolveConfigPath } from "./cli-shared.js";
import { checkContext, applyContext, contextPrompt } from "./context-lock.js";
import { cmdEnv } from "./commands/env.js";
import { cmdAuth } from "./commands/auth.js";
import { cmdAudit } from "./commands/audit.js";
Expand Down Expand Up @@ -3367,7 +3368,88 @@ async function cmdOpen(): Promise<boolean> {
}
}

async function cmdContextCheck(): Promise<boolean> {
const jsonMode = hasFlag(process.argv, "--json");
const config = await loadConfig(resolveConfigPath());
const findings = await checkContext(config.context);

if (jsonMode) {
console.log(JSON.stringify(findings, null, 2));
return findings.every((f) => f.status !== "mismatch");
}
if (!config.context) {
console.log(
`${c.dim}No [context] declared in .kit.toml. Add one to lock each CLI to its account + project.${c.reset}`,
);
return true;
}
console.log(`${c.bold}Context lock${c.reset}\n`);
for (const f of findings) {
const icon =
f.status === "ok"
? `${c.green}✓${c.reset}`
: f.status === "mismatch"
? `${c.red}✗${c.reset}`
: `${c.yellow}!${c.reset}`;
const actual = f.actual ?? `${c.dim}(unreadable)${c.reset}`;
const detail =
f.status === "ok"
? `${c.dim}${f.expected}${c.reset}`
: `expected ${c.bold}${f.expected}${c.reset}, live ${c.bold}${actual}${c.reset}`;
console.log(` ${icon} ${f.tool}.${f.field} ${detail}`);
}
const mismatches = findings.filter((f) => f.status === "mismatch");
if (mismatches.length > 0) {
console.log(
`\n${c.red}${mismatches.length} mismatch(es) — you are NOT locked to the declared account/project. Do not run outward/destructive commands until this is green.${c.reset}`,
);
}
// Mismatch = non-zero exit so this can gate a hook / agent before acting.
// Unknown (tool absent / unreadable) does not block.
return mismatches.length === 0;
}

async function cmdContextUse(): Promise<boolean> {
const config = await loadConfig(resolveConfigPath());
if (!config.context) {
console.log(
`${c.dim}No [context] declared in .kit.toml. Add one to lock each CLI to its account + project.${c.reset}`,
);
return true;
}
console.log(`${c.bold}Context use${c.reset}\n`);
const results = await applyContext(config.context, process.cwd());
for (const r of results) {
const icon = r.ok ? `${c.green}✓${c.reset}` : `${c.red}✗${c.reset}`;
console.log(` ${icon} ${r.step.tool} ${c.dim}${r.step.describe}${c.reset}`);
}
// vercel/npm have no clean per-repo "active" state to switch — guide instead.
if (config.context.vercel) {
console.log(
` ${c.dim}vercel: pass --scope per command or run \`vercel link\`; kit does not switch the dashboard link.${c.reset}`,
);
}
if (config.context.npm) {
console.log(
` ${c.dim}npm: registry is global — set with \`npm config set registry <url>\` if it differs.${c.reset}`,
);
}
const failed = results.filter((r) => !r.ok).length;
if (failed > 0) {
console.log(`\n${c.yellow}${failed} step(s) failed (tool not installed?). Run kit context check to verify.${c.reset}`);
}
return failed === 0;
}

async function cmdContext(): Promise<boolean> {
if (process.argv[3] === "check") return cmdContextCheck();
if (process.argv[3] === "use") return cmdContextUse();
// Fast, read-only PS1 indicator: `kit context --prompt` -> "[gcp:<project>]".
if (hasFlag(process.argv, "--prompt")) {
console.log(contextPrompt());
return true;
}

const jsonMode = hasFlag(process.argv, "--json");

try {
Expand Down Expand Up @@ -3612,6 +3694,9 @@ const COMMAND_HELP: Record<string, string> = {
run: "Execute a command with project env vars loaded",
open: "Open service dashboard in browser (stripe, vercel, railway, etc.)",
context: "Show project context: tools, services, secrets, environment",
"context check": "Verify each CLI's live account+project matches .kit.toml [context] (exits non-zero on mismatch)",
"context use": "Activate the declared context: gcloud config + repo git identity",
"context --prompt": "Print a compact active-gcloud indicator for your shell prompt (PS1)",
mcp: "MCP server over stdio (Claude Code/Cursor/Codex); 'kit mcp list|auth|set-token|clear' manages declared servers",
whoami: "Show current agent / user identity",
version: "Print kit version",
Expand Down
6 changes: 6 additions & 0 deletions src/commands/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ const BUILTIN_HOOKS: Record<string, { hookName: string; commands: string[]; desc
commands: ["kit security verify-pull"],
description: "After git pull/merge, audit new deps, gitignore drops, and introduced secrets.",
},
"context-check": {
hookName: "pre-push",
commands: ["kit context check"],
description:
"Block a push when the live CLI context (account/project) does not match .kit.toml [context]. Stops pushes to the wrong org/project.",
},
};

export async function cmdHooks(): Promise<boolean> {
Expand Down
20 changes: 17 additions & 3 deletions src/commands/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
palSnooze,
palAutoVerify,
importLegacyLedger,
type VerifyCheck,
} from "../memory/pal.js";
import {
saveThread,
Expand All @@ -43,6 +44,9 @@ import {
export async function cmdMemory(): Promise<boolean> {
const subcommand = process.argv[3];
if (!subcommand || subcommand === "--help" || subcommand === "-h") return memHelp();
// A --help/-h flag after a subcommand means "show help", never run a
// side-effectful subcommand (e.g. `kit memory install --help` must not install).
if (hasFlag(process.argv, "--help") || hasFlag(process.argv, "-h")) return memHelp();

// One handler per subcommand — keeps this dispatcher flat (was a complexity-132
// if-chain). Each handler reads process.argv itself, so no args thread through.
Expand Down Expand Up @@ -109,13 +113,23 @@ async function memPal(): Promise<boolean> {
const title = process.argv.slice(5).filter((a) => !a.startsWith("--")).join(" ").trim();
if (!title) {
console.error(
`${c.red}usage: kit memory pal add <title> [--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}`);
Expand Down Expand Up @@ -149,7 +163,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}`,
);
Expand Down
Loading
Loading