diff --git a/.changeset/init-blank-husky-choice-1758.md b/.changeset/init-blank-husky-choice-1758.md new file mode 100644 index 00000000..8b0f06bf --- /dev/null +++ b/.changeset/init-blank-husky-choice-1758.md @@ -0,0 +1,5 @@ +--- +"secureflow-cli": minor +--- + +feat(cli): [NSoC_2026] allow choosing between Blank and Husky in secureflow --init (#1758) diff --git a/cli/src/index.test.ts b/cli/src/index.test.ts index 575abd47..3f2afe31 100644 --- a/cli/src/index.test.ts +++ b/cli/src/index.test.ts @@ -67,6 +67,14 @@ vi.mock("./lib/output-args.js", () => ({ vi.mock("./lib/audio-player.js", () => ({ playVoiceDebrief: m.playVoiceDebrief })); vi.mock("./mcp/index.js", () => ({ startMcpServer: m.startMcpServer })); +vi.mock("./lib/tui.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + initSecureFlow: vi.fn(actual.initSecureFlow), + }; +}); + const violation = { line: 3, text: "console.log(secret)", reason: "secret" }; const scanResult = (path: string, violations: unknown[] = []) => ({ path, @@ -384,3 +392,32 @@ describe("voice debrief", () => { expect(m.playVoiceDebrief).not.toHaveBeenCalled(); }); }); + +describe("--init flag & initialization modes (#1758)", () => { + it("initializes secureflow and prints greeting with exit code 0 on success", async () => { + const { initSecureFlow } = await import("./lib/tui.js"); + vi.mocked(initSecureFlow).mockResolvedValueOnce({ + success: true, + message: "Successfully added npx secureflow to package.json prepare script", + hookPath: "package.json", + }); + + const code = await runCli("--init", "blank"); + expect(code).toBe(0); + expect(initSecureFlow).toHaveBeenCalled(); + expect(output(logSpy)).toContain("[SecureFlow Init]"); + }); + + it("exits with code 1 when initialization fails", async () => { + const { initSecureFlow } = await import("./lib/tui.js"); + vi.mocked(initSecureFlow).mockResolvedValueOnce({ + success: false, + message: "Failed to write package.json", + hookPath: "", + }); + + const code = await runCli("--init", "--blank"); + expect(code).toBe(1); + expect(output(errorSpy)).toContain("Failed to write package.json"); + }); +}); diff --git a/cli/src/index.ts b/cli/src/index.ts index 99ccf613..6eb93254 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -38,6 +38,8 @@ import { TerminalSpinner, formatTuiScanSummary, initHuskyPreCommitHook, + initBlankPrepareScript, + initSecureFlow, formatInitGreeting, colors, } from "./lib/tui.js"; @@ -89,7 +91,9 @@ Commands: explain --web3 Generate AI security analysis and remediation for Web3 / Smart Contract findings Options: - --init Initialize local .husky/pre-commit hook configured with SecureFlow + --init Initialize SecureFlow (choose between Blank and Husky) + --husky Initialize using Husky pre-commit hook (.husky/pre-commit) + --blank Initialize using Blank mode (package.json prepare script) --verbose Enable verbose logging --format Output format: text, json, sarif, csv, html, markdown (default: text) -o, --output Write output to specified file path @@ -195,8 +199,12 @@ async function runAiScanIfAvailable(stagedForAi: StagedFileForAiScan[]): Promise } async function main(): Promise { - if (process.argv.includes("--init")) { - const result = initHuskyPreCommitHook(); + if ( + process.argv.some( + (arg) => arg === "--init" || arg.startsWith("--init=") || arg === "--husky" || arg === "--blank", + ) + ) { + const result = await initSecureFlow(); const greeting = formatInitGreeting(result); if (result.success) { console.log(greeting); diff --git a/cli/src/lib/tui.test.ts b/cli/src/lib/tui.test.ts index 320e72bd..41f99a9d 100644 --- a/cli/src/lib/tui.test.ts +++ b/cli/src/lib/tui.test.ts @@ -15,6 +15,10 @@ import { renderWarningTable, formatTuiScanSummary, initHuskyPreCommitHook, + initBlankPrepareScript, + detectInitMode, + promptInitChoice, + initSecureFlow, formatInitGreeting, type TableRow, } from "./tui.js"; @@ -344,4 +348,204 @@ describe("cli/src/lib/tui (#1712)", () => { expect(greeting).toContain("https://custom-repo.example.com/docs"); }); }); + describe("initBlankPrepareScript (#1758)", () => { + let tempDir: string; + + beforeEach(() => { + execSyncMock.mockReset(); + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "secureflow-blank-test-")); + }); + + afterEach(() => { + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it("runs npm init --y when package.json does not exist and adds prepare script", () => { + const commandsExecuted: string[] = []; + const mockExec = vi.fn((cmd: string) => { + commandsExecuted.push(cmd); + if (cmd === "npm init --y") { + fs.writeFileSync( + path.join(tempDir, "package.json"), + JSON.stringify({ name: "new-pkg", version: "1.0.0" }, null, 2), + ); + } + }); + + const res = initBlankPrepareScript(tempDir, mockExec); + + expect(res.success).toBe(true); + expect(mockExec).toHaveBeenCalledWith( + "npm init --y", + expect.objectContaining({ cwd: tempDir }), + ); + expect(commandsExecuted).toEqual(["npm init --y"]); + + const pkg = JSON.parse(fs.readFileSync(path.join(tempDir, "package.json"), "utf-8")); + expect(pkg.scripts.prepare).toBe("npx secureflow"); + expect(res.message).toContain("Successfully added npx secureflow"); + }); + + it("skips npm init --y when package.json already exists and adds prepare script", () => { + const pkgPath = path.join(tempDir, "package.json"); + fs.writeFileSync( + pkgPath, + JSON.stringify({ name: "existing-pkg", version: "1.0.0", scripts: { test: "vitest" } }, null, 2), + ); + + const mockExec = vi.fn(); + const res = initBlankPrepareScript(tempDir, mockExec); + + expect(res.success).toBe(true); + expect(mockExec).not.toHaveBeenCalled(); + + const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + expect(pkg.scripts.test).toBe("vitest"); + expect(pkg.scripts.prepare).toBe("npx secureflow"); + }); + + it("appends npx secureflow with && when a prepare script already exists (e.g. xyz && npx secureflow)", () => { + const pkgPath = path.join(tempDir, "package.json"); + fs.writeFileSync( + pkgPath, + JSON.stringify({ name: "existing-pkg", scripts: { prepare: "xyz" } }, null, 2), + ); + + const res = initBlankPrepareScript(tempDir); + + expect(res.success).toBe(true); + const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + expect(pkg.scripts.prepare).toBe("xyz && npx secureflow"); + expect(res.message).toContain("Appended npx secureflow to existing prepare script"); + }); + + it("recognizes when secureflow is already present in prepare script and avoids duplication", () => { + const pkgPath = path.join(tempDir, "package.json"); + fs.writeFileSync( + pkgPath, + JSON.stringify({ name: "existing-pkg", scripts: { prepare: "npm run build && npx secureflow" } }, null, 2), + ); + + const res = initBlankPrepareScript(tempDir); + + expect(res.success).toBe(true); + expect(res.message).toContain("already configured"); + const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + expect(pkg.scripts.prepare).toBe("npm run build && npx secureflow"); + }); + + it("handles invalid package.json JSON syntax gracefully", () => { + const pkgPath = path.join(tempDir, "package.json"); + fs.writeFileSync(pkgPath, "{ invalid json ... "); + + const res = initBlankPrepareScript(tempDir); + + expect(res.success).toBe(false); + expect(res.message).toContain("Failed to parse package.json"); + }); + }); + + describe("detectInitMode & promptInitChoice (#1758)", () => { + it("detects blank mode from command line arguments", () => { + expect(detectInitMode(["node", "cli", "--init", "blank"])).toBe("blank"); + expect(detectInitMode(["node", "cli", "--init=blank"])).toBe("blank"); + expect(detectInitMode(["node", "cli", "--blank"])).toBe("blank"); + expect(detectInitMode(["node", "cli", "-b"])).toBe("blank"); + expect(detectInitMode(["node", "cli", "--init", "2"])).toBe("blank"); + }); + + it("detects husky mode from command line arguments", () => { + expect(detectInitMode(["node", "cli", "--init", "husky"])).toBe("husky"); + expect(detectInitMode(["node", "cli", "--init=husky"])).toBe("husky"); + expect(detectInitMode(["node", "cli", "--husky"])).toBe("husky"); + expect(detectInitMode(["node", "cli", "--init", "1"])).toBe("husky"); + }); + + it("returns null when no mode argument is provided with --init", () => { + expect(detectInitMode(["node", "cli", "--init"])).toBeNull(); + expect(detectInitMode(["node", "cli"])).toBeNull(); + }); + + it("promptInitChoice resolves to blank when user selects 2 or blank", async () => { + const mockRl = { + question: vi.fn((_prompt: string, cb: (ans: string) => void) => cb("2")), + close: vi.fn(), + on: vi.fn(), + } as any; + + const choice = await promptInitChoice(mockRl, process.stdin, { write: vi.fn() } as any); + expect(choice).toBe("blank"); + }); + + it("promptInitChoice resolves to husky when user selects 1, husky, or presses Enter", async () => { + const mockRl1 = { + question: vi.fn((_prompt: string, cb: (ans: string) => void) => cb("husky")), + close: vi.fn(), + on: vi.fn(), + } as any; + + const choice1 = await promptInitChoice(mockRl1, process.stdin, { write: vi.fn() } as any); + expect(choice1).toBe("husky"); + + const mockRl2 = { + question: vi.fn((_prompt: string, cb: (ans: string) => void) => cb("")), + close: vi.fn(), + on: vi.fn(), + } as any; + + const choice2 = await promptInitChoice(mockRl2, process.stdin, { write: vi.fn() } as any); + expect(choice2).toBe("husky"); + }); + }); + + describe("initSecureFlow orchestrator (#1758)", () => { + let tempDir: string; + + beforeEach(() => { + execSyncMock.mockReset(); + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "secureflow-init-orch-")); + }); + + afterEach(() => { + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it("routes to Blank mode when mode is specified as blank", async () => { + const pkgPath = path.join(tempDir, "package.json"); + fs.writeFileSync(pkgPath, JSON.stringify({ name: "orch-test", scripts: {} })); + + const res = await initSecureFlow({ + mode: "blank", + targetDir: tempDir, + }); + + expect(res.success).toBe(true); + expect(res.hookPath).toBe(pkgPath); + const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + expect(pkg.scripts.prepare).toBe("npx secureflow"); + }); + + it("routes to Husky mode when mode is specified as husky", async () => { + const res = await initSecureFlow({ + mode: "husky", + targetDir: tempDir, + }); + + expect(res.success).toBe(true); + expect(res.hookPath).toBe(path.join(tempDir, ".husky", "pre-commit")); + expect(fs.existsSync(res.hookPath)).toBe(true); + }); + + it("formats greeting with package.json prepare script details in blank mode", () => { + const greeting = formatInitGreeting({ + success: true, + message: "Successfully added npx secureflow to package.json prepare script", + hookPath: path.join(tempDir, "package.json"), + }); + + expect(greeting).toContain("Hook Location:"); + expect(greeting).toContain("package.json"); + expect(greeting).toContain("npm run prepare"); + }); + }); }); diff --git a/cli/src/lib/tui.ts b/cli/src/lib/tui.ts index f3f9e281..23532a53 100644 --- a/cli/src/lib/tui.ts +++ b/cli/src/lib/tui.ts @@ -10,6 +10,7 @@ import fs from "node:fs"; import path from "node:path"; import { execSync } from "node:child_process"; +import readline from "node:readline"; import type { FileScanResult, Violation } from "../scanner.js"; import type { AiFinding } from "./api-client.js"; @@ -221,7 +222,23 @@ export interface InitGreetingOptions { } export interface InitHuskyOptions { - execFn?: CommandExecutor; + execFn?: CommandExecutor | undefined; +} + +export type InitMode = "husky" | "blank"; + +export interface InitBlankOptions { + execFn?: CommandExecutor | undefined; +} + +export interface InitSecureFlowOptions { + mode?: InitMode | undefined; + targetDir?: string | undefined; + execFn?: CommandExecutor | undefined; + rl?: readline.Interface; + stdin?: NodeJS.ReadableStream; + stdout?: NodeJS.WritableStream; + argv?: string[]; } /** @@ -315,6 +332,198 @@ export function initHuskyPreCommitHook( } } +/** + * Initializes repository with `npm init --y` (if needed) and configures + * `npx secureflow` in package.json's `prepare` script (#1758). + * If a `prepare` script already exists, appends ` && npx secureflow`. + */ +export function initBlankPrepareScript( + targetDir: string = process.cwd(), + optionsOrExecFn?: CommandExecutor | InitBlankOptions, +): InitHookResult { + try { + const execFn: CommandExecutor = + typeof optionsOrExecFn === "function" + ? optionsOrExecFn + : (optionsOrExecFn?.execFn ?? execSync); + + const pkgJsonPath = path.join(targetDir, "package.json"); + + // 1. Run npm init --y if not already exist (#1758) + if (!fs.existsSync(pkgJsonPath)) { + try { + execFn("npm init --y", { cwd: targetDir, stdio: "ignore" }); + } catch (err) { + // Continue if npm init --y encountered an issue + } + } + + let pkg: any; + if (fs.existsSync(pkgJsonPath)) { + try { + const raw = fs.readFileSync(pkgJsonPath, "utf-8"); + pkg = JSON.parse(raw); + } catch (parseErr) { + return { + success: false, + message: `Failed to parse package.json: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`, + hookPath: pkgJsonPath, + }; + } + } else { + pkg = { + name: path.basename(targetDir) || "project", + version: "1.0.0", + scripts: {}, + }; + } + + if (!pkg.scripts || typeof pkg.scripts !== "object") { + pkg.scripts = {}; + } + + const secureflowCmd = "npx secureflow"; + const existingPrepare = + typeof pkg.scripts.prepare === "string" ? pkg.scripts.prepare.trim() : undefined; + + let message = ""; + if (!existingPrepare) { + pkg.scripts.prepare = secureflowCmd; + message = "Successfully added npx secureflow to package.json prepare script"; + } else if (existingPrepare.includes("secureflow")) { + return { + success: true, + message: "SecureFlow is already configured in package.json prepare script", + hookPath: pkgJsonPath, + }; + } else { + pkg.scripts.prepare = `${existingPrepare} && ${secureflowCmd}`; + message = `Appended npx secureflow to existing prepare script ("${pkg.scripts.prepare}")`; + } + + fs.writeFileSync(pkgJsonPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8"); + + return { + success: true, + message, + hookPath: pkgJsonPath, + }; + } catch (error) { + return { + success: false, + message: `Failed to configure package.json prepare script: ${error instanceof Error ? error.message : String(error)}`, + hookPath: path.join(targetDir, "package.json"), + }; + } +} + +/** + * Detects whether the user explicitly selected Blank or Husky mode via CLI arguments (#1758). + */ +export function detectInitMode(argv: string[] = process.argv): InitMode | null { + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (!arg) continue; + if (arg === "--blank" || arg === "-b") return "blank"; + if (arg === "--husky") return "husky"; + if (arg.startsWith("--init=")) { + const val = arg.slice("--init=".length).trim().toLowerCase(); + if (val === "blank" || val === "b" || val === "2") return "blank"; + if (val === "husky" || val === "h" || val === "1") return "husky"; + } + if (arg === "--init" && i + 1 < argv.length) { + const next = argv[i + 1]?.trim().toLowerCase(); + if (next === "blank" || next === "b" || next === "2") return "blank"; + if (next === "husky" || next === "h" || next === "1") return "husky"; + } + } + return null; +} + +/** + * Prompts user to select between Blank and Husky initialization mode interactively (#1758). + */ +export async function promptInitChoice( + rl?: readline.Interface, + input: NodeJS.ReadableStream = process.stdin, + output: NodeJS.WritableStream = process.stdout, +): Promise { + const readlineInterface = + rl || + readline.createInterface({ + input, + output, + }); + + const shouldClose = !rl; + + return new Promise((resolve) => { + let answered = false; + + readlineInterface.on("close", () => { + if (!answered) { + answered = true; + resolve("husky"); + } + }); + + output.write(`\n${colors.bold(colors.cyan("Select initialization mode:"))}\n`); + output.write( + ` ${colors.bold("1)")} ${colors.green("Husky")} - Git pre-commit hook via .husky/pre-commit (${colors.cyan("Recommended")})\n`, + ); + output.write( + ` ${colors.bold("2)")} ${colors.yellow("Blank")} - Add npx secureflow to package.json prepare script\n\n`, + ); + + readlineInterface.question( + colors.bold("Choose [1/2 or Husky/Blank] (default: 1): "), + (answer) => { + if (answered) return; + answered = true; + if (shouldClose) readlineInterface.close(); + const trimmed = answer.trim().toLowerCase(); + if (trimmed === "2" || trimmed === "blank" || trimmed === "b") { + resolve("blank"); + } else { + resolve("husky"); + } + }, + ); + }); +} + +/** + * Main initialization entry point allowing users to choose between Blank and Husky (#1758). + */ +export async function initSecureFlow( + options: InitSecureFlowOptions = {}, +): Promise { + const targetDir = options.targetDir || process.cwd(); + const argv = options.argv || process.argv; + let mode = options.mode; + + if (!mode) { + mode = detectInitMode(argv) ?? undefined; + } + + if (!mode) { + const isInteractive = + (options.stdin as any)?.isTTY ?? (process.stdin.isTTY && !process.env.CI); + if (isInteractive) { + mode = await promptInitChoice(options.rl, options.stdin, options.stdout); + } else { + mode = "husky"; + } + } + + const execOpts = options.execFn ? { execFn: options.execFn } : undefined; + if (mode === "blank") { + return initBlankPrepareScript(targetDir, execOpts); + } else { + return initHuskyPreCommitHook(targetDir, execOpts); + } +} + /** * Formats a terminal greeting banner and onboarding guide for `secureflow --init` (#1732). */ @@ -395,13 +604,22 @@ export function formatInitGreeting( "└───────────────────────────────────────────────────────────────────────┘", ); - const nextStepsSection = [ - colors.bold(colors.yellow("🚀 Next Steps:")), - ` ${colors.cyan("1.")} Stage changes: ${colors.gray("git add ")}`, - ` ${colors.cyan("2.")} Commit files: ${colors.gray('git commit -m "feat: new feature"')}\n ${colors.dim("⤷ SecureFlow will automatically scan staged files before committing.")}`, - ` ${colors.cyan("3.")} Manual audit: ${colors.gray("npx secureflow")} ${colors.dim("(run anytime on pending changes)")}`, - ` ${colors.cyan("4.")} Explore all options: ${colors.gray("npx secureflow --help")}`, - ].join("\n"); + const isBlankMode = Boolean(result.hookPath && result.hookPath.endsWith("package.json")); + + const nextStepsSection = isBlankMode + ? [ + colors.bold(colors.yellow("🚀 Next Steps:")), + ` ${colors.cyan("1.")} Run prepare script: ${colors.gray("npm run prepare")}\n ${colors.dim("⤷ SecureFlow will execute automatically during package lifecycle preparation.")}`, + ` ${colors.cyan("2.")} Manual audit: ${colors.gray("npx secureflow")} ${colors.dim("(run anytime on pending changes)")}`, + ` ${colors.cyan("3.")} Explore all options: ${colors.gray("npx secureflow --help")}`, + ].join("\n") + : [ + colors.bold(colors.yellow("🚀 Next Steps:")), + ` ${colors.cyan("1.")} Stage changes: ${colors.gray("git add ")}`, + ` ${colors.cyan("2.")} Commit files: ${colors.gray('git commit -m "feat: new feature"')}\n ${colors.dim("⤷ SecureFlow will automatically scan staged files before committing.")}`, + ` ${colors.cyan("3.")} Manual audit: ${colors.gray("npx secureflow")} ${colors.dim("(run anytime on pending changes)")}`, + ` ${colors.cyan("4.")} Explore all options: ${colors.gray("npx secureflow --help")}`, + ].join("\n"); const footer = [ divider,