diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index e1343366..acd1bef1 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -17,9 +17,15 @@ | ---------------------------- | ------------------------------------------------------------------------------------------ | | `--read-only` / `--readonly` | Activate session-wide refusal of every mutating op. Also honored as `KIT_READ_ONLY=1` env. | | `--non-interactive` | Skip all confirmation prompts. Required in CI / agent contexts. | +| `--env=` | Select the environment overlay (`[env.]` in `.kit.toml`). Also honored as `KIT_ENV`. | | `--version` / `-v` | Print kit version + exit. | | `--help` / `-h` | Print top-level help + exit. | +`--read-only`, `--readonly`, `--non-interactive` and `--env=` may be +written before or after the command word — `kit --read-only check` and +`kit check --read-only` are equivalent. Every command accepts them; a command +that rejects unknown flags allows these on top of its own. + ## Core lifecycle | Command | Purpose | diff --git a/src/cli.test.ts b/src/cli.test.ts index 651e950c..2608a3af 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -1049,3 +1049,91 @@ describe("mcpExposedToolNames", () => { assert.deepEqual(mcpExposedToolNames(), EXPECTED_MCP_TOOLS); }); }); + +// --------------------------------------------------------------------------- +// Global flags: dispatch position + typo rejection +// --------------------------------------------------------------------------- + +describe("global flags before the command word", () => { + let tempDir: string; + + before(async () => { + tempDir = await mkdtemp(join(tmpdir(), "kit-globalflags-")); + await writeFile(join(tempDir, ".kit.toml"), FIXTURE_EMPTY, "utf-8"); + }); + + after(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + it("`kit --read-only check` runs the check instead of 'Unknown command'", async () => { + // README.md and docs/THREAT_MODEL.md both document this exact form. It used to + // activate read-only mode and then refuse to dispatch, because `--read-only` + // WAS args[0] — kit rejected its own documented security-control invocation. + const result = await runCli(["--read-only", "check"], tempDir); + const output = `${result.stdout}${result.stderr}`; + assert.ok(!output.includes("Unknown command"), `kit refused to dispatch:\n${output}`); + assert.ok(output.includes("read-only mode active"), "read-only mode should still activate"); + }); + + it("`kit check --read-only` is not rejected as an unknown flag", async () => { + const result = await runCli(["check", "--read-only"], tempDir); + const output = `${result.stdout}${result.stderr}`; + assert.ok(!output.includes("unknown flag"), `global flag rejected:\n${output}`); + }); + + it("`kit check --non-interactive` is not rejected as an unknown flag", async () => { + const result = await runCli(["check", "--non-interactive"], tempDir); + const output = `${result.stdout}${result.stderr}`; + assert.ok(!output.includes("unknown flag"), `global flag rejected:\n${output}`); + }); + + it("a genuinely unknown flag is still rejected", async () => { + const result = await runCli(["check", "--not-a-real-flag"], tempDir); + const output = `${result.stdout}${result.stderr}`; + assert.equal(result.exitCode, 1); + assert.ok(output.includes("unknown flag"), "the rejection must survive the widened allowlist"); + }); +}); + +describe("kit upgrade rejects a typo'd flag instead of doing something else", () => { + let tempDir: string; + const LOCK = `{ + "tools": { + "node": { "version": "22", "source": "mise", "installedAt": "2020-01-01T00:00:00.000Z" } + } +} +`; + + beforeEach(async () => { + tempDir = await mkdtemp(join(tmpdir(), "kit-upgradeflag-")); + await writeFile(join(tempDir, ".kit.toml"), '[tools]\nnode = "22"\n', "utf-8"); + await mkdir(join(tempDir, ".kit"), { recursive: true }); + await writeFile(join(tempDir, ".kit", "cli-lock.json"), LOCK, "utf-8"); + }); + + afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + it("`--self.` exits 1 and never touches the lock file", async () => { + // The reported failure: a trailing period missed hasFlag's exact match, so the + // self-upgrade silently became the lock-file path — it rewrote every + // installedAt to "now", installed nothing, and printed a success line. + const result = await runCli(["upgrade", "--self."], tempDir); + const output = `${result.stdout}${result.stderr}`; + assert.equal(result.exitCode, 1, `expected rejection, got:\n${output}`); + assert.ok(output.includes("unknown flag"), `no rejection printed:\n${output}`); + const lock = await readFile(join(tempDir, ".kit", "cli-lock.json"), "utf-8"); + assert.ok( + lock.includes("2020-01-01T00:00:00.000Z"), + "a rejected invocation must not rewrite installedAt", + ); + }); + + it("plain `kit upgrade` still updates the lock files", async () => { + const result = await runCli(["upgrade"], tempDir); + const output = `${result.stdout}${result.stderr}`; + assert.ok(output.includes("Updated lock files"), `the happy path regressed:\n${output}`); + }); +}); diff --git a/src/cli.ts b/src/cli.ts index d3cec2ad..598c84f7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4,7 +4,7 @@ import { readFileSync, realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; import { loadConfig } from "./config.js"; -import { hasFlag } from "./utils/flags.js"; +import { hasFlag, splitLeadingGlobalFlags } from "./utils/flags.js"; import { generateCompletions } from "./completions.js"; import { checkForUpdate, printUpdateNotice } from "./update-check.js"; import { SKIPPED_COMMITS_LOG } from "./hooks.js"; @@ -280,8 +280,19 @@ async function showSkippedCommitBanner(): Promise { */ async function main(): Promise { - const args = process.argv.slice(2); - const command = args[0]; + // Global flags may precede the command word (`kit --read-only check`, the form + // README.md:299 and docs/THREAT_MODEL.md:98 document). Move them behind the + // positionals — and rewrite process.argv to match — so command modules that + // read subcommands off raw indices (`process.argv[3]`) see the same shape they + // would for `kit check ...`. Without this the flag WAS the command and kit + // answered "Unknown command: --read-only". + const rawArgs = process.argv.slice(2); + const { leading: leadingGlobals, rest: positional } = splitLeadingGlobalFlags(rawArgs); + const args = leadingGlobals.length > 0 ? [...positional, ...leadingGlobals] : rawArgs; + if (leadingGlobals.length > 0) { + process.argv = [...process.argv.slice(0, 2), ...args]; + } + const command = positional[0]; const nonInteractive = hasFlag(args, "--non-interactive") || process.env.CI === "true" || @@ -326,12 +337,12 @@ async function main(): Promise { let ok: boolean; // --version / --help flags before the switch - if (args[0] === "--version" || args[0] === "-v") { + if (positional[0] === "--version" || positional[0] === "-v") { ok = cmdVersion(); process.exitCode = ok ? 0 : 1; return; } - if (args[0] === "--help" || args[0] === "-h") { + if (positional[0] === "--help" || positional[0] === "-h") { ok = cmdHelp(); process.exitCode = 0; return; @@ -352,9 +363,9 @@ async function main(): Promise { if (command === "version") { ok = cmdVersion(); } else if (command === "help") { - ok = cmdHelp(args[1]); + ok = cmdHelp(positional[1]); } else if (command === "completions") { - const shell = args[1]; + const shell = positional[1]; const script = generateCompletions(shell); if (!script) { console.error(`Unknown shell: ${shell}. Use: bash, zsh, fish`); diff --git a/src/commands/check-flags.test.ts b/src/commands/check-flags.test.ts index 4aa79b6c..4f3322e1 100644 --- a/src/commands/check-flags.test.ts +++ b/src/commands/check-flags.test.ts @@ -4,6 +4,7 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { CHECK_FLAGS } from "./check.js"; +import { GLOBAL_FLAGS } from "../utils/flags.js"; /** * The allowlist behind `kit check`'s unknown-flag rejection must cover every flag the check path @@ -73,3 +74,18 @@ describe("kit check flag allowlist", () => { for (const f of CHECK_FLAGS) assert.match(f, /^--[a-z][a-z0-9-]*$/, f); }); }); + +describe("kit check accepts the documented global flags", () => { + /** + * `--read-only` and `--non-interactive` are honored by cli.ts for every command + * and are in docs/COMMANDS.md's global table, but CHECK_FLAGS was built from the + * check path's own literals — so `kit check --read-only` exited 1 with "unknown + * flag" and the security check never ran. Same class as the `--attest` break + * above: a gate that refuses to run is a false red. + */ + it("CHECK_FLAGS is a superset of GLOBAL_FLAGS", () => { + const allowed = new Set(CHECK_FLAGS); + const missing = (GLOBAL_FLAGS as readonly string[]).filter((f) => !allowed.has(f)); + assert.deepEqual(missing, [], `globals kit check would reject: ${missing.join(", ")}`); + }); +}); diff --git a/src/commands/check.ts b/src/commands/check.ts index 8b213b09..dbd922d8 100644 --- a/src/commands/check.ts +++ b/src/commands/check.ts @@ -8,7 +8,7 @@ */ import { resolve } from "node:path"; import { c } from "../utils/colors.js"; -import { hasFlag, flagValue, envTruthy, unknownFlags } from "../utils/flags.js"; +import { hasFlag, flagValue, envTruthy, unknownFlags, GLOBAL_FLAGS } from "../utils/flags.js"; import { loadConfig } from "../config.js"; import { resolveConfigPath } from "../cli-shared.js"; import { withGovernance } from "../governance-middleware.js"; @@ -70,9 +70,14 @@ export const CHECK_FLAGS = [ "--key", "--attest", // cli-checks-shared.ts:emitAttestation "--no-auto-install", // cli-checks-shared.ts:autoInstallScanners + // Honored for every command by cli.ts / config.ts, not by the check path itself. + // Omitting them made `kit check --read-only` and `kit check --non-interactive` + // — both in the "Global flags" table of docs/COMMANDS.md — exit 1 without + // running the check: the same false-red as the `--attest` regression above. + ...GLOBAL_FLAGS, ] as const; -const COMPARE_FLAGS = ["--json", "--fail-on-worse"] as const; -const VERIFY_FLAGS = ["--json", "--key"] as const; +const COMPARE_FLAGS = ["--json", "--fail-on-worse", ...GLOBAL_FLAGS] as const; +const VERIFY_FLAGS = ["--json", "--key", ...GLOBAL_FLAGS] as const; /** Print the rejection and return false, so every caller fails the same way. */ function rejectUnknownFlags(form: string, allowed: readonly string[]): boolean { diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts index dd26bd78..97487402 100644 --- a/src/commands/upgrade.ts +++ b/src/commands/upgrade.ts @@ -8,7 +8,7 @@ * four are exported. Imports only sibling core modules, never cli.ts. */ import { c } from "../utils/colors.js"; -import { hasFlag } from "../utils/flags.js"; +import { hasFlag, unknownFlags, GLOBAL_FLAGS } from "../utils/flags.js"; import { loadConfig } from "../config.js"; import { resolveConfigPath } from "../cli-shared.js"; import { readkitMeta, updateSkillsLock, updateCliLock } from "../lock.js"; @@ -98,10 +98,28 @@ export async function selfUpgrade(): Promise { } } +/** + * Every flag `kit upgrade` honors. `--self` is the only one the command reads; + * the globals are honored by cli.ts / config.ts for every command. + */ +export const UPGRADE_FLAGS = ["--self", ...GLOBAL_FLAGS] as const; + export async function cmdUpgrade(): Promise { console.log(`${c.bold}${c.cyan}kit upgrade${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); + // A typo'd flag must not silently become a DIFFERENT operation. `kit upgrade + // --self.` (trailing period) missed the exact-match in hasFlag, fell through + // to the lock-file path, and rewrote every `installedAt` in .kit/cli-lock.json + // to "now" while installing nothing — reported as a successful upgrade. + const bad = unknownFlags(process.argv, UPGRADE_FLAGS); + if (bad.length > 0) { + const plural = bad.length > 1 ? "s" : ""; + console.error(`${c.red}unknown flag${plural} for kit upgrade: ${bad.join(", ")}${c.reset}`); + console.error(`${c.dim}accepted: ${UPGRADE_FLAGS.join(" ")}${c.reset}`); + return false; + } + if (hasFlag(process.argv, "--self")) { return await selfUpgrade(); } diff --git a/src/utils/flags.test.ts b/src/utils/flags.test.ts index 59b63bcf..a5765b9b 100644 --- a/src/utils/flags.test.ts +++ b/src/utils/flags.test.ts @@ -1,6 +1,15 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { hasFlag, flagValue, flagInt, unknownFlags } from "./flags.js"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { + hasFlag, + flagValue, + flagInt, + unknownFlags, + GLOBAL_FLAGS, + splitLeadingGlobalFlags, +} from "./flags.js"; describe("flag helpers", () => { describe("hasFlag", () => { @@ -154,3 +163,81 @@ describe("flagInt — boundaries and malformed input", () => { assert.equal(flagInt(["--", "--ttl-minutes", "30"], "--ttl-minutes", 5), 30); }); }); + +describe("GLOBAL_FLAGS", () => { + /** + * The ORACLE is docs/COMMANDS.md's "Global flags" table, not a second copy of + * the list: `kit check --read-only` shipped broken precisely because the only + * thing asserting the allowlist was the allowlist. If a global is documented, + * a command allowlist must accept it. + */ + function documentedGlobals(): string[] { + const root = resolve(import.meta.dirname, "..", ".."); + const doc = readFileSync(resolve(root, "docs", "COMMANDS.md"), "utf-8"); + const start = doc.indexOf("## Global flags"); + assert.ok(start >= 0, "docs/COMMANDS.md no longer has a '## Global flags' section"); + const section = doc.slice(start, doc.indexOf("\n## ", start + 1)); + const flags = new Set(); + for (const m of section.matchAll(/`(--[a-z][a-z0-9-]*)`/g)) flags.add(m[1]); + return [...flags]; + } + + it("the oracle itself finds something (a regex that matches nothing reads as full coverage)", () => { + const found = documentedGlobals(); + assert.ok(found.length >= 4, `the docs scan found only ${found.length} global flags`); + assert.ok(found.includes("--read-only"), "expected the scan to see --read-only"); + }); + + it("every flag documented as global is in GLOBAL_FLAGS", () => { + const allowed = new Set(GLOBAL_FLAGS); + const missing = documentedGlobals().filter((f) => !allowed.has(f)); + assert.deepEqual(missing, [], `documented as global but rejectable by a command: ${missing}`); + }); + + it("includes --env, which config.ts honors globally off raw argv", () => { + // resolveActiveEnvironment() reads `--env=` from process.argv for every + // command, so a command allowlist that omits it rejects a working flag. + assert.ok((GLOBAL_FLAGS as readonly string[]).includes("--env")); + }); +}); + +describe("splitLeadingGlobalFlags", () => { + it("moves a leading global off the front so the command word is positional 0", () => { + const { leading, rest } = splitLeadingGlobalFlags(["--read-only", "check"]); + assert.deepEqual(leading, ["--read-only"]); + assert.deepEqual(rest, ["check"]); + }); + + it("preserves subcommand positions (the reason raw argv indices break)", () => { + const { rest } = splitLeadingGlobalFlags(["--read-only", "check", "verify-attestation"]); + // commands/check.ts reads process.argv[3] === "verify-attestation" + assert.equal(rest[1], "verify-attestation"); + }); + + it("takes several leading globals, including --env=", () => { + const { leading, rest } = splitLeadingGlobalFlags([ + "--non-interactive", + "--env=prod", + "secrets", + ]); + assert.deepEqual(leading, ["--non-interactive", "--env=prod"]); + assert.deepEqual(rest, ["secrets"]); + }); + + it("stops at the command word — a global AFTER it is the command's to see", () => { + const { leading, rest } = splitLeadingGlobalFlags(["check", "--read-only"]); + assert.deepEqual(leading, []); + assert.deepEqual(rest, ["check", "--read-only"]); + }); + + it("leaves --version / --help alone: as token 0 they ARE the command", () => { + assert.deepEqual(splitLeadingGlobalFlags(["--version"]).rest, ["--version"]); + assert.deepEqual(splitLeadingGlobalFlags(["--help"]).rest, ["--help"]); + }); + + it("does not eat a command-specific flag it has never heard of", () => { + const { leading, rest } = splitLeadingGlobalFlags(["--nope", "check"]); + assert.deepEqual(leading, []); + assert.deepEqual(rest, ["--nope", "check"]); + }); +}); diff --git a/src/utils/flags.ts b/src/utils/flags.ts index 30ee224b..85894d3b 100644 --- a/src/utils/flags.ts +++ b/src/utils/flags.ts @@ -64,3 +64,62 @@ export function flagInt(argv: readonly string[], name: string, fallback: number) const n = Number.parseInt(raw, 10); return Number.isNaN(n) ? fallback : n; } + +/** + * Flags kit honors for EVERY command, wherever they appear in argv. + * + * A command's own allowlist must accept these on top of its own flags, or the + * unknown-flag rejection turns a documented global into a hard failure. That is + * not hypothetical: `kit check --read-only` and `kit check --non-interactive` + * — both listed in the "Global flags" table of docs/COMMANDS.md — exited 1 with + * "unknown flag for kit check" and the check never ran, because CHECK_FLAGS was + * built from the check path's own flag literals only. + * + * `--env` is honored globally too (config.ts:resolveActiveEnvironment reads + * `--env=` straight off process.argv) even though the COMMANDS.md table + * predates it. `--help` is intercepted in cli.ts before dispatch, but it is + * listed so a command allowlist never rejects what the user can legally type. + */ +export const GLOBAL_FLAGS = [ + "--read-only", + "--readonly", + "--non-interactive", + "--env", + "--help", + "--version", +] as const; + +/** + * The globals that may legally appear BEFORE the command word + * (`kit --read-only check`, the form README.md and docs/THREAT_MODEL.md + * document). `--version` / `--help` are excluded: as the first token they mean + * the top-level version/help command, and cli.ts dispatches them as such. + */ +const GLOBAL_PREFIX_FLAGS = ["--read-only", "--readonly", "--non-interactive"] as const; + +function isGlobalPrefixFlag(token: string): boolean { + return (GLOBAL_PREFIX_FLAGS as readonly string[]).includes(token) || token.startsWith("--env="); +} + +/** + * Split leading global flags off the front of argv. + * + * `kit --read-only check verify-attestation` must reach cmdCheck with the same + * POSITIONAL shape as `kit check verify-attestation` — command modules read + * subcommands off raw indices (`process.argv[3] === "verify-attestation"`), so a + * flag sitting in front of the command word shifts every one of them. Before + * this split, `command = args[0]` was `--read-only` and kit answered "Unknown + * command: --read-only" (exit 1) for the exact invocation its own README + * documents. + * + * The flags are not dropped — callers re-append them after the positionals, so + * `hasFlag(process.argv, "--read-only")` and every allowlist still see them. + */ +export function splitLeadingGlobalFlags(args: readonly string[]): { + leading: string[]; + rest: string[]; +} { + let i = 0; + while (i < args.length && isGlobalPrefixFlag(args[i])) i++; + return { leading: args.slice(0, i), rest: args.slice(i) }; +}