diff --git a/src/cli.test.ts b/src/cli.test.ts index c4171887..66a3a600 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -582,3 +582,63 @@ describe("kit init — auto-generate", () => { assert.equal(result.exitCode, 1, "should exit 1 when confidence too low"); }); }); + +// --------------------------------------------------------------------------- +// Wired commands that were previously documented but unrouted +// --------------------------------------------------------------------------- + +describe("kit env diff", () => { + let tempDir: string; + + before(async () => { + tempDir = await mkdtemp(join(tmpdir(), "kit-integ-envdiff-")); + await writeFile(join(tempDir, ".env.local"), "A=1\nB=2\nC=3\n", "utf-8"); + await writeFile(join(tempDir, ".env.staging"), "A=1\nB=changed\nD=4\n", "utf-8"); + }); + + after(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + it("routes and reports drift between .env.local and the target", async () => { + const result = await runCli(["env", "diff", "--compare", "staging"], tempDir); + assert.equal(result.exitCode, 0); + assert.ok(!result.stderr.includes("Unknown subcommand"), "must be routed"); + // C only local, D only staging, B changed; values never printed + assert.ok(result.stdout.includes("C"), "key only in local"); + assert.ok(result.stdout.includes("D"), "key only in staging"); + assert.ok(!result.stdout.includes("changed"), "raw values must not leak"); + }); + + it("exits 1 with usage when --compare is missing", async () => { + const result = await runCli(["env", "diff"], tempDir); + assert.equal(result.exitCode, 1); + }); +}); + +describe("kit secrets validate", () => { + let tempDir: string; + + before(async () => { + tempDir = await mkdtemp(join(tmpdir(), "kit-integ-secval-")); + await writeFile(join(tempDir, ".gitignore"), GITIGNORE_CONTENT, "utf-8"); + await writeFile( + join(tempDir, ".kit.toml"), + `[secrets]\nstore = "env"\n\n[secrets.keys]\n_KIT_VAL_PRESENT = { source = "env" }\n_KIT_VAL_ABSENT = { source = "env" }\n`, + "utf-8", + ); + }); + + after(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + it("exits non-zero and flags the missing key", async () => { + const result = await runCli(["secrets", "validate"], tempDir, { + _KIT_VAL_PRESENT: "set", + }); + assert.equal(result.exitCode, 1, "missing key → non-zero"); + assert.ok(!result.stderr.includes("Unknown subcommand"), "must be routed"); + assert.ok(result.stdout.includes("_KIT_VAL_ABSENT"), "names the missing key"); + }); +}); diff --git a/src/cli.ts b/src/cli.ts index 9501bdb1..b07d67b3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4,7 +4,9 @@ import { readFileSync, writeFileSync, existsSync } from "node:fs"; import { writeFile, access, mkdir } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import { resolve, dirname, join } from "node:path"; -import { loadConfig, type kitConfig } from "./config.js"; +import { loadConfig, type kitConfig, type SecretKeyConfig } from "./config.js"; +import { createInterface } from "node:readline/promises"; +import { validateSecrets, summarizeValidation } from "./secrets-validate.js"; import { checkTools } from "./check-tools.js"; import { checkServices } from "./check-services.js"; import { checkSecrets } from "./check-secrets.js"; @@ -115,7 +117,7 @@ import { runDoctor } from "./doctor.js"; import { detectStack } from "./stack-detector.js"; import { generateToml, parseEnvTemplateKeys } from "./toml-generator.js"; import { vaultMeta, detectSecretStore } from "./vault-meta.js"; -import { vaultCliInstalled } from "./secret-backends.js"; +import { vaultCliInstalled, resolveViaBackend } from "./secret-backends.js"; import { createPlugin } from "./create-plugin.js"; import { cmdPlugin } from "./plugins-cli.js"; import { cloneRepository } from "./clone.js"; @@ -802,11 +804,78 @@ async function cmdLogin(): Promise { ); } +/** + * `kit secrets validate [--fix] [--auto]` — verify every declared key resolves + * to a non-empty value in the configured backend. Read-only by default; exits + * non-zero when keys are missing/unfixable. `--fix` prompts interactively, + * `--auto` pulls from .env.template. Writes go through the gated backend writer. + */ +async function cmdSecretsValidate(): Promise { + const config = await loadConfig(resolveConfigPath()); + if (!config.secrets) { + console.log(`${c.dim}No secrets configured in ${KIT_FILE}${c.reset}`); + return true; + } + const fix = hasFlag(process.argv, "--fix"); + const auto = hasFlag(process.argv, "--auto"); + + // Real availability check: env vars locally, everything else via its backend. + const checkAvailability = async ( + key: string, + source: SecretKeyConfig["source"], + cfg: SecretKeyConfig, + ): Promise => { + if (source === "env") return Boolean(process.env[key]); + if (source === "config") return Boolean(cfg.value); + const r = await resolveViaBackend(key, cfg, config.secrets?.infisical); + return r.resolved && Boolean(r.value); + }; + + const rl = fix ? createInterface({ input: process.stdin, output: process.stdout }) : null; + const prompt = rl + ? async (key: string): Promise => { + const answer = (await rl.question(` ${c.cyan}${key}${c.reset} value (blank to skip): `)).trim(); + return answer.length > 0 ? answer : null; + } + : undefined; + + console.log(`${c.bold}${c.cyan}kit secrets validate${c.reset}`); + try { + const results = await validateSecrets(config, { fix, auto, prompt }, checkAvailability); + for (const r of results) { + const icon = + r.status === "present" || r.status === "fixed" + ? `${c.green}✓${c.reset}` + : r.status === "missing" + ? `${c.red}✗${c.reset}` + : `${c.yellow}⚠${c.reset}`; + console.log(` ${icon} ${r.key} ${c.dim}(${r.source})${c.reset}${r.detail ? ` — ${r.detail}` : ""}`); + } + const s = summarizeValidation(results); + const tail = [ + s.missing ? `${s.missing} missing` : "", + s.unfixable ? `${s.unfixable} unfixable` : "", + s.fixed ? `${s.fixed} fixed` : "", + ] + .filter(Boolean) + .join(", "); + console.log( + `\n${s.ok ? c.green : c.red}${s.present + s.fixed}/${s.total} resolvable${c.reset}${tail ? ` ${c.dim}(${tail})${c.reset}` : ""}`, + ); + return s.ok; + } finally { + rl?.close(); + } +} + async function cmdSecrets(): Promise { // Route subcommand: kit secrets sync [--target=...] [--dry-run] if (process.argv[3] === "sync") { return cmdSecretsSync(); } + if (process.argv[3] === "validate") { + return cmdSecretsValidate(); + } if (process.argv[3] === "migrate") { return cmdSecretsMigrate(); } diff --git a/src/commands/env.ts b/src/commands/env.ts index f38394cb..c7d73f50 100644 --- a/src/commands/env.ts +++ b/src/commands/env.ts @@ -5,8 +5,9 @@ import { promptConfirm } from "../utils/prompt.js"; import { inspectEnv } from "../env-inspect.js"; import { isNonInteractive } from "../environment.js"; import { c } from "../utils/colors.js"; -import { hasFlag } from "../utils/flags.js"; +import { hasFlag, flagValue } from "../utils/flags.js"; import { resolveConfigPath } from "../cli-shared.js"; +import { diffEnvFiles } from "../env-diff.js"; async function cmdEnvList(): Promise { let config: kitConfig; @@ -121,12 +122,42 @@ async function cmdEnvCurrent(): Promise { return true; } +/** + * `kit env diff --compare ` — surface drift between the local .env.local + * and a target env file (.env.). Values are never printed — only key + * presence and short value hashes — so it is safe to run anywhere. + */ +async function cmdEnvDiff(): Promise { + const args = process.argv.slice(2); + const target = flagValue(args, "--compare"); + if (!target) { + console.error(`${c.red}Usage: kit env diff --compare <${KNOWN_ENVS.join("|")}|name>${c.reset}`); + return false; + } + const a = ".env.local"; + const b = `.env.${target}`; + const res = await diffEnvFiles(a, b); + console.log(`${c.bold}${c.cyan}kit env diff${c.reset} ${c.dim}(${a} vs ${b})${c.reset}`); + for (const k of res.onlyInA) console.log(` ${c.yellow}- ${k}${c.reset} ${c.dim}only in ${a}${c.reset}`); + for (const k of res.onlyInB) console.log(` ${c.green}+ ${k}${c.reset} ${c.dim}only in ${b}${c.reset}`); + for (const ch of res.changed) + console.log(` ${c.yellow}~ ${ch.key}${c.reset} ${c.dim}(${ch.aHash} → ${ch.bHash})${c.reset}`); + const drift = res.onlyInA.length + res.onlyInB.length + res.changed.length; + console.log( + drift === 0 + ? ` ${c.green}✓ no drift${c.reset} ${c.dim}(${res.identicalCount} identical)${c.reset}` + : `\n ${c.dim}${drift} differing, ${res.identicalCount} identical${c.reset}`, + ); + return true; +} + export async function cmdEnv(): Promise { const args = process.argv.slice(2); // includes "env" - // Route subcommand: kit env list / switch / current / validate + // Route subcommand: kit env list / switch / current / diff if (args[1] === "list") return cmdEnvList(); if (args[1] === "switch") return cmdEnvSwitch(); if (args[1] === "current") return cmdEnvCurrent(); + if (args[1] === "diff") return cmdEnvDiff(); const showValues = hasFlag(args, "--show-values"); const missingOnly = hasFlag(args, "--missing");