diff --git a/CHANGELOG.md b/CHANGELOG.md index 39fc4654..63eaebbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### 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. + ## [1.3.1] - 2026-06-17 ### Security diff --git a/README.md b/README.md index 9be95dc2..59ae9764 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 @@ -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 ]`: 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` diff --git a/src/cli.ts b/src/cli.ts index f5a76945..a970588d 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -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"; @@ -3367,7 +3368,88 @@ async function cmdOpen(): Promise { } } +async function cmdContextCheck(): Promise { + 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 { + 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 \` 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 { + if (process.argv[3] === "check") return cmdContextCheck(); + if (process.argv[3] === "use") return cmdContextUse(); + // Fast, read-only PS1 indicator: `kit context --prompt` -> "[gcp:]". + if (hasFlag(process.argv, "--prompt")) { + console.log(contextPrompt()); + return true; + } + const jsonMode = hasFlag(process.argv, "--json"); try { @@ -3612,6 +3694,9 @@ const COMMAND_HELP: Record = { 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", diff --git a/src/commands/hooks.ts b/src/commands/hooks.ts index c9473017..a5106e0d 100644 --- a/src/commands/hooks.ts +++ b/src/commands/hooks.ts @@ -18,6 +18,12 @@ const BUILTIN_HOOKS: Record { diff --git a/src/config.ts b/src/config.ts index 6f047a03..ce04b378 100644 --- a/src/config.ts +++ b/src/config.ts @@ -248,6 +248,22 @@ export interface EnvOverride { governance?: GovernanceConfig; } +/** + * Per-project CLI context lock. Each tool declares the EXACT (account, project) + * pair this repo must use. kit verifies the live tool state against these + * declarations and never infers a pairing from whatever happens to be logged in + * or selected (a logged-in account + a selected project are not assumed to belong + * together). These are non-secret pointers; the credentials they authenticate + * with stay in the vault (`[secrets]`). + */ +export interface ContextConfig { + gcloud?: { account?: string; project?: string; config?: string; region?: string }; + vercel?: { team?: string; project?: string }; + github?: { org?: string; remote?: string }; + git?: { email?: string }; + npm?: { registry?: string }; +} + export interface kitConfig { tools?: ToolConfig; services?: Record; @@ -255,6 +271,8 @@ export interface kitConfig { skills?: SkillsConfig; governance?: GovernanceConfig; hooks?: HooksConfig; + /** Per-project CLI context lock (account+project per tool). */ + context?: ContextConfig; web?: { search?: WebSearchConfig; }; @@ -444,6 +462,30 @@ const kitConfigSchema = z skills: SkillsConfigSchema.optional(), governance: GovernanceConfigSchema.optional(), hooks: HooksConfigSchema, + context: z + .object({ + gcloud: z + .object({ + account: z.string().optional(), + project: z.string().optional(), + config: z.string().optional(), + region: z.string().optional(), + }) + .passthrough() + .optional(), + vercel: z + .object({ team: z.string().optional(), project: z.string().optional() }) + .passthrough() + .optional(), + github: z + .object({ org: z.string().optional(), remote: z.string().optional() }) + .passthrough() + .optional(), + git: z.object({ email: z.string().optional() }).passthrough().optional(), + npm: z.object({ registry: z.string().optional() }).passthrough().optional(), + }) + .passthrough() + .optional(), web: WebConfigSchema, setup: z .object({ diff --git a/src/context-lock.test.ts b/src/context-lock.test.ts new file mode 100644 index 00000000..f6b266c9 --- /dev/null +++ b/src/context-lock.test.ts @@ -0,0 +1,93 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + compareContext, + parseGithubRemote, + planContext, + parseGcloudProject, + type LiveContext, +} from "./context-lock.js"; + +describe("context lock", () => { + it("passes only when the exact declared pair matches", () => { + const declared = { gcloud: { account: "ops@example.com", project: "prod-project" } }; + const live: LiveContext = { gcloud: { account: "ops@example.com", project: "prod-project" } }; + const f = compareContext(declared, live); + assert.equal(f.filter((x) => x.status !== "ok").length, 0); + }); + + it("flags right account + WRONG project as a mismatch (never trust the ambient pair)", () => { + const declared = { gcloud: { account: "ops@example.com", project: "prod-project" } }; + const live: LiveContext = { gcloud: { account: "ops@example.com", project: "other-project" } }; + const proj = compareContext(declared, live).find( + (x) => x.tool === "gcloud" && x.field === "project", + ); + assert.equal(proj?.status, "mismatch"); + assert.equal(proj?.expected, "prod-project"); + assert.equal(proj?.actual, "other-project"); + }); + + it("marks unreadable live state as unknown (does not block)", () => { + const declared = { npm: { registry: "https://registry.npmjs.org" } }; + const live: LiveContext = { npm: { registry: null } }; + assert.equal(compareContext(declared, live)[0]?.status, "unknown"); + }); + + it("only checks declared fields", () => { + const declared = { git: { email: "dev@example.com" } }; + const live: LiveContext = { + gcloud: { account: "x", project: "y" }, + git: { email: "dev@example.com" }, + }; + const f = compareContext(declared, live); + assert.equal(f.length, 1); + assert.equal(f[0]?.tool, "git"); + assert.equal(f[0]?.status, "ok"); + }); + + it("flags a vercel link to the wrong project", () => { + const declared = { vercel: { team: "team_example", project: "prj_canonical" } }; + const live: LiveContext = { vercel: { orgId: "team_example", projectId: "prj_stale" } }; + const proj = compareContext(declared, live).find((x) => x.field === "project(projectId)"); + assert.equal(proj?.status, "mismatch"); + }); + + it("parses github org + remote from ssh and https urls", () => { + assert.deepEqual(parseGithubRemote("git@github.com:example-org/example-repo.git"), { + org: "example-org", + remote: "github.com/example-org/example-repo", + }); + assert.deepEqual(parseGithubRemote("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/example-org/example-repo"), { + org: "example-org", + remote: "github.com/example-org/example-repo", + }); + assert.deepEqual(parseGithubRemote(null), { org: null, remote: null }); + assert.deepEqual(parseGithubRemote("https://gitlab.com/x/y"), { org: null, remote: null }); + }); + + it("plans gcloud + git activation from the declared context (local config only)", () => { + const steps = planContext({ + gcloud: { config: "prod-cfg", account: "ops@example.com", project: "prod-project", region: "europe-west4" }, + git: { email: "dev@example.com" }, + }); + const describes = steps.map((s) => s.describe); + assert.ok(describes.some((d) => d.includes("activate config prod-cfg"))); + assert.ok(describes.some((d) => d.includes("project=prod-project"))); + assert.ok(describes.some((d) => d.includes("account=ops@example.com"))); + // git identity is repo-local, not global + const gitStep = steps.find((s) => s.tool === "git"); + assert.equal(gitStep?.local, true); + assert.deepEqual(gitStep?.argv, ["config", "user.email", "dev@example.com"]); + // nothing planned for vercel/npm (no clean per-repo activation) + assert.equal(steps.some((s) => s.tool === "vercel" || s.tool === "npm"), false); + }); + + it("plans nothing when no activatable context is declared", () => { + assert.deepEqual(planContext({ npm: { registry: "https://registry.npmjs.org" } }), []); + }); + + it("parses the gcloud project from a config INI", () => { + assert.equal(parseGcloudProject("[core]\naccount = a@b.com\nproject = prod-project\n"), "prod-project"); + assert.equal(parseGcloudProject("[core]\naccount = a@b.com\n"), null); + }); +}); diff --git a/src/context-lock.ts b/src/context-lock.ts new file mode 100644 index 00000000..96aa98e9 --- /dev/null +++ b/src/context-lock.ts @@ -0,0 +1,224 @@ +/** + * Per-project CLI context lock. + * + * Verifies that each tool's LIVE (account, project) pair matches what `.kit.toml` + * `[context]` declares. The core rule: a logged-in account and a selected project + * are NEVER assumed to belong together. Only the declared pair is trusted; the + * ambient CLI state is data to be checked against it. A right account paired with + * the wrong project (or vice versa) is a mismatch, not a pass. + * + * Read-only: this never changes any tool's state (that is `kit context use`). + */ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { readFile } from "node:fs/promises"; +import { readFileSync } from "node:fs"; +import { resolve, join } from "node:path"; +import { homedir } from "node:os"; +import type { ContextConfig } from "./config.js"; + +const exec = promisify(execFile); + +export interface ContextFinding { + tool: string; // gcloud | git | github | npm | vercel + field: string; // account | project | email | org | remote | registry | ... + status: "ok" | "mismatch" | "unknown"; // unknown = live state could not be read + expected: string; + actual: string | null; +} + +/** A snapshot of the live context read from each tool (null = unreadable). */ +export interface LiveContext { + gcloud?: { account: string | null; project: string | null }; + git?: { email: string | null }; + github?: { org: string | null; remote: string | null }; + npm?: { registry: string | null }; + vercel?: { orgId: string | null; projectId: string | null }; +} + +function field( + tool: string, + name: string, + expected: string | undefined, + actual: string | null, +): ContextFinding | null { + if (expected === undefined) return null; // not declared -> not checked + if (actual === null) return { tool, field: name, status: "unknown", expected, actual: null }; + return { tool, field: name, status: actual === expected ? "ok" : "mismatch", expected, actual }; +} + +// One row per checkable (tool, field). Adding a CLI to the lock is one row. +// `declared` returns the expected value (undefined = not declared = not checked); +// `live` returns the read value (null = unreadable). vercel context = the ids in +// .vercel/project.json (deterministic + local): team -> orgId, project -> projectId. +const FIELD_SPECS: { + tool: string; + field: string; + declared: (d: ContextConfig) => string | undefined; + live: (l: LiveContext) => string | null; +}[] = [ + { tool: "gcloud", field: "account", declared: (d) => d.gcloud?.account, live: (l) => l.gcloud?.account ?? null }, + { tool: "gcloud", field: "project", declared: (d) => d.gcloud?.project, live: (l) => l.gcloud?.project ?? null }, + { tool: "git", field: "email", declared: (d) => d.git?.email, live: (l) => l.git?.email ?? null }, + { tool: "github", field: "org", declared: (d) => d.github?.org, live: (l) => l.github?.org ?? null }, + { tool: "github", field: "remote", declared: (d) => d.github?.remote, live: (l) => l.github?.remote ?? null }, + { tool: "npm", field: "registry", declared: (d) => d.npm?.registry, live: (l) => l.npm?.registry ?? null }, + { tool: "vercel", field: "team(orgId)", declared: (d) => d.vercel?.team, live: (l) => l.vercel?.orgId ?? null }, + { tool: "vercel", field: "project(projectId)", declared: (d) => d.vercel?.project, live: (l) => l.vercel?.projectId ?? null }, +]; + +/** + * Compare a declared context against a live snapshot. PURE (no I/O) so the + * principle is unit-testable: only the exact declared pair passes. + */ +export function compareContext(declared: ContextConfig, live: LiveContext): ContextFinding[] { + return FIELD_SPECS.map((s) => field(s.tool, s.field, s.declared(declared), s.live(live))).filter( + (f): f is ContextFinding => f !== null, + ); +} + +async function run(cmd: string, args: string[]): Promise { + try { + const { stdout } = await exec(cmd, args, { timeout: 8_000 }); + return stdout.trim() || null; + } catch { + return null; + } +} + +/** github.com[:/]org/repo(.git) -> { org, "github.com/org/repo" }. */ +export function parseGithubRemote(url: string | null): { org: string | null; remote: string | null } { + if (!url) return { org: null, remote: null }; + const m = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?$/); + if (!m) return { org: null, remote: null }; + return { org: m[1], remote: `github.com/${m[1]}/${m[2]}` }; +} + +/** Read the live context from each tool. Every read fails soft to null. */ +export async function gatherLive(cwd: string = process.cwd()): Promise { + const live: LiveContext = {}; + + const gcloudJson = await run("gcloud", ["config", "list", "--format=json"]); + if (gcloudJson !== null) { + try { + const c = JSON.parse(gcloudJson) as { core?: { account?: string; project?: string } }; + live.gcloud = { account: c.core?.account ?? null, project: c.core?.project ?? null }; + } catch { + live.gcloud = { account: null, project: null }; + } + } else { + live.gcloud = { account: null, project: null }; + } + + live.git = { email: await run("git", ["config", "user.email"]) }; + + const remote = await run("git", ["remote", "get-url", "origin"]); + live.github = parseGithubRemote(remote); + + const registry = await run("npm", ["config", "get", "registry"]); + live.npm = { registry: registry ? registry.replace(/\/+$/, "") : null }; + + try { + const raw = await readFile(resolve(cwd, ".vercel", "project.json"), "utf8"); + const j = JSON.parse(raw) as { orgId?: string; projectId?: string }; + live.vercel = { orgId: j.orgId ?? null, projectId: j.projectId ?? null }; + } catch { + live.vercel = { orgId: null, projectId: null }; + } + + return live; +} + +/** Verify the declared context against live tool state. Empty if nothing declared. */ +export async function checkContext( + ctx: ContextConfig | undefined, + cwd: string = process.cwd(), +): Promise { + if (!ctx) return []; + // Normalize a declared npm registry the same way the live read is normalized. + const declared: ContextConfig = ctx.npm?.registry + ? { ...ctx, npm: { ...ctx.npm, registry: ctx.npm.registry.replace(/\/+$/, "") } } + : ctx; + return compareContext(declared, await gatherLive(cwd)); +} + +// ── kit context use — activate the declared context ────────────────────────── + +export interface ContextStep { + tool: string; + argv: string[]; + /** Run in the repo (cwd) rather than affecting global state — e.g. git config. */ + local?: boolean; + describe: string; +} + +/** + * Plan the commands that would activate the declared context. PURE (no I/O) so + * the mapping is unit-testable. Only LOCAL CLI config is ever touched (gcloud + * config, repo git identity) — never an account or a deploy. vercel/npm are not + * auto-activated (no clean per-repo "active" state); `use` prints guidance. + */ +export function planContext(ctx: ContextConfig): ContextStep[] { + const steps: ContextStep[] = []; + const g = ctx.gcloud; + if (g?.config) + steps.push({ tool: "gcloud", argv: ["config", "configurations", "activate", g.config], describe: `activate config ${g.config}` }); + if (g?.account) + steps.push({ tool: "gcloud", argv: ["config", "set", "account", g.account], describe: `account=${g.account}` }); + if (g?.project) + steps.push({ tool: "gcloud", argv: ["config", "set", "project", g.project], describe: `project=${g.project}` }); + if (g?.region) + steps.push({ tool: "gcloud", argv: ["config", "set", "run/region", g.region], describe: `run/region=${g.region}` }); + if (ctx.git?.email) + steps.push({ tool: "git", argv: ["config", "user.email", ctx.git.email], local: true, describe: `git user.email=${ctx.git.email}` }); + return steps; +} + +export interface ApplyResult { + step: ContextStep; + ok: boolean; +} + +/** Execute the activation plan. Each step runs via execFile (no shell). */ +export async function applyContext( + ctx: ContextConfig, + cwd: string = process.cwd(), +): Promise { + const results: ApplyResult[] = []; + for (const step of planContext(ctx)) { + let ok = false; + try { + await exec(step.tool, step.argv, { timeout: 8_000, cwd: step.local ? cwd : undefined }); + ok = true; + } catch { + ok = false; + } + results.push({ step, ok }); + } + return results; +} + +// ── kit context --prompt — a fast, read-only PS1 indicator ─────────────────── + +/** Extract `project = ` from a gcloud configuration INI. PURE. */ +export function parseGcloudProject(ini: string): string | null { + const m = ini.match(/^\s*project\s*=\s*(.+?)\s*$/m); + return m ? m[1].trim() : null; +} + +/** + * A compact indicator of the ACTIVE gcloud context for a shell prompt, read from + * gcloud's config files (no subprocess, so it is cheap to call per prompt). + * Returns "" if gcloud config cannot be read. Example: "[gcp:cbd-platform]". + */ +export function contextPrompt(): string { + try { + const dir = process.env.CLOUDSDK_CONFIG || join(homedir(), ".config", "gcloud"); + const active = readFileSync(join(dir, "active_config"), "utf8").trim(); + const ini = readFileSync(join(dir, "configurations", `config_${active}`), "utf8"); + const project = parseGcloudProject(ini); + return project ? `[gcp:${project}]` : active ? `[gcp:${active}]` : ""; + } catch { + return ""; + } +}