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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
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
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
42 changes: 42 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,13 +248,31 @@ 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<string, ServiceConfig>;
secrets?: SecretsConfig;
skills?: SkillsConfig;
governance?: GovernanceConfig;
hooks?: HooksConfig;
/** Per-project CLI context lock (account+project per tool). */
context?: ContextConfig;
web?: {
search?: WebSearchConfig;
};
Expand Down Expand Up @@ -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({
Expand Down
93 changes: 93 additions & 0 deletions src/context-lock.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading