|
| 1 | +import chalk from "chalk"; |
| 2 | +import { readFile } from "fs/promises"; |
| 3 | +import { join } from "path"; |
| 4 | + |
| 5 | +import { resolveRepo, type RepoSource } from "../repo-resolver.js"; |
| 6 | +import { |
| 7 | + analyzeSecurityPatterns, |
| 8 | + getSecurityGrade, |
| 9 | + type SecurityAnalysis, |
| 10 | + type Severity, |
| 11 | +} from "../security.js"; |
| 12 | +import { scanRepositoryFiles } from "../services/clone-service.js"; |
| 13 | + |
| 14 | +/** Options accepted by the `bootcamp security` command. */ |
| 15 | +export interface SecurityCommandOptions { |
| 16 | + branch?: string; |
| 17 | + /** Emit the report as JSON for machine consumption. */ |
| 18 | + json?: boolean; |
| 19 | + /** Exit non-zero when the security score is below `minScore` (CI gate). */ |
| 20 | + check?: boolean; |
| 21 | + /** Minimum passing score for `--check` (0-100). Defaults to 70. */ |
| 22 | + minScore?: number; |
| 23 | + /** Maximum files to scan. Defaults to 500. */ |
| 24 | + maxFiles?: number; |
| 25 | + /** Keep the temporary clone (remote repos only). */ |
| 26 | + keepTemp?: boolean; |
| 27 | + verbose?: boolean; |
| 28 | +} |
| 29 | + |
| 30 | +const SEVERITY_ICON: Record<Severity, string> = { |
| 31 | + critical: "🔴", |
| 32 | + high: "🟠", |
| 33 | + medium: "🟡", |
| 34 | + low: "🔵", |
| 35 | + info: "⚪", |
| 36 | +}; |
| 37 | + |
| 38 | +const SEVERITY_ORDER: Severity[] = ["critical", "high", "medium", "low", "info"]; |
| 39 | + |
| 40 | +function scoreColor(score: number): typeof chalk.green { |
| 41 | + if (score >= 80) return chalk.green; |
| 42 | + if (score >= 60) return chalk.yellow; |
| 43 | + return chalk.red; |
| 44 | +} |
| 45 | + |
| 46 | +function checkmark(value: boolean): string { |
| 47 | + return value ? chalk.green("✓") : chalk.dim("·"); |
| 48 | +} |
| 49 | + |
| 50 | +function printReport(analysis: SecurityAnalysis, repoName: string, filesScanned: number): void { |
| 51 | + const grade = getSecurityGrade(analysis.score); |
| 52 | + const emoji = analysis.score >= 80 ? "🟢" : analysis.score >= 60 ? "🟡" : "🔴"; |
| 53 | + const color = scoreColor(analysis.score); |
| 54 | + |
| 55 | + console.log(chalk.bold("\n🔒 Security Analysis")); |
| 56 | + console.log(chalk.dim(`Repository: ${repoName}`)); |
| 57 | + console.log(chalk.dim(`Scanned ${filesScanned} files\n`)); |
| 58 | + |
| 59 | + console.log(`${emoji} ` + color.bold(`${analysis.score}/100 (Grade: ${grade})`)); |
| 60 | + |
| 61 | + const counts = SEVERITY_ORDER.map( |
| 62 | + (sev) => [sev, analysis.findings.filter((f) => f.severity === sev).length] as const |
| 63 | + ).filter(([, n]) => n > 0); |
| 64 | + if (counts.length > 0) { |
| 65 | + console.log( |
| 66 | + chalk.dim("Findings: ") + |
| 67 | + counts.map(([sev, n]) => `${SEVERITY_ICON[sev]} ${n} ${sev}`).join(chalk.dim(" · ")) |
| 68 | + ); |
| 69 | + } else { |
| 70 | + console.log(chalk.green("No pattern-based findings detected.")); |
| 71 | + } |
| 72 | + console.log(); |
| 73 | + |
| 74 | + console.log(chalk.bold("Protections")); |
| 75 | + console.log( |
| 76 | + ` ${checkmark(analysis.headers.hasHelmet)} security headers (helmet)` + |
| 77 | + ` ${checkmark(analysis.headers.hasCors)} CORS` + |
| 78 | + ` ${checkmark(analysis.headers.hasCSP)} CSP` |
| 79 | + ); |
| 80 | + console.log( |
| 81 | + ` ${checkmark(analysis.hasRateLimiting)} rate limiting` + |
| 82 | + ` ${checkmark(analysis.hasInputValidation)} input validation` + |
| 83 | + ` ${checkmark(analysis.hasSqlInjectionPrevention)} SQL-injection prevention` |
| 84 | + ); |
| 85 | + console.log( |
| 86 | + ` ${checkmark(analysis.secretsHandling.gitignoreSecrets)} secrets git-ignored` + |
| 87 | + ` ${checkmark(analysis.secretsHandling.hasEnvExample)} .env.example present` |
| 88 | + ); |
| 89 | + console.log(); |
| 90 | + |
| 91 | + if (analysis.securityDeps.length > 0) { |
| 92 | + console.log(chalk.bold("Security dependencies")); |
| 93 | + for (const dep of analysis.securityDeps) { |
| 94 | + console.log(` ${chalk.cyan(dep.name)}` + (dep.purpose ? chalk.dim(` — ${dep.purpose}`) : "")); |
| 95 | + } |
| 96 | + console.log(); |
| 97 | + } |
| 98 | + |
| 99 | + if (analysis.findings.length > 0) { |
| 100 | + console.log(chalk.bold("Findings") + chalk.dim(" (most severe first)")); |
| 101 | + const sorted = [...analysis.findings].sort( |
| 102 | + (a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) |
| 103 | + ); |
| 104 | + for (const finding of sorted) { |
| 105 | + const where = finding.file ? chalk.dim(` (${finding.file}${finding.line ? `:${finding.line}` : ""})`) : ""; |
| 106 | + console.log(` ${SEVERITY_ICON[finding.severity]} ` + chalk.cyan(finding.title) + where); |
| 107 | + if (finding.recommendation) { |
| 108 | + console.log(chalk.dim(` → ${finding.recommendation}`)); |
| 109 | + } |
| 110 | + } |
| 111 | + console.log(); |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +/** |
| 116 | + * Run the standalone `bootcamp security` command: clone/resolve the target |
| 117 | + * repo, scan it, run the deterministic security pattern analysis, and report |
| 118 | + * it (human or JSON). With `--check`, exits non-zero when the score is below |
| 119 | + * `--min-score`. Reuses the same `analyzeSecurityPatterns` engine that powers |
| 120 | + * `SECURITY.md` — mirroring `bootcamp health` and `bootcamp metrics`. |
| 121 | + */ |
| 122 | +export async function runSecurityCommand(repoUrl: string, opts: SecurityCommandOptions): Promise<void> { |
| 123 | + const minScore = typeof opts.minScore === "number" && Number.isFinite(opts.minScore) ? opts.minScore : 70; |
| 124 | + |
| 125 | + let repoSource: RepoSource; |
| 126 | + try { |
| 127 | + repoSource = await resolveRepo(repoUrl, process.cwd(), opts.branch || undefined); |
| 128 | + } catch (error: unknown) { |
| 129 | + console.error( |
| 130 | + chalk.red(`Failed to resolve repository: ${error instanceof Error ? error.message : String(error)}`) |
| 131 | + ); |
| 132 | + process.exit(1); |
| 133 | + return; |
| 134 | + } |
| 135 | + |
| 136 | + let exitCode = 0; |
| 137 | + try { |
| 138 | + const scan = await scanRepositoryFiles(repoSource.path, opts.maxFiles ?? 500); |
| 139 | + const packageJson = await readFile(join(repoSource.path, "package.json"), "utf-8") |
| 140 | + .then((content) => JSON.parse(content) as Record<string, unknown>) |
| 141 | + .catch(() => undefined); |
| 142 | + const analysis = await analyzeSecurityPatterns(repoSource.path, scan.files, packageJson); |
| 143 | + const filesScanned = scan.files.length; |
| 144 | + |
| 145 | + if (opts.json) { |
| 146 | + console.log( |
| 147 | + JSON.stringify( |
| 148 | + { |
| 149 | + repo: repoSource.repoInfo.fullName, |
| 150 | + filesScanned, |
| 151 | + grade: getSecurityGrade(analysis.score), |
| 152 | + ...analysis, |
| 153 | + }, |
| 154 | + null, |
| 155 | + 2 |
| 156 | + ) |
| 157 | + ); |
| 158 | + } else { |
| 159 | + printReport(analysis, repoSource.repoInfo.fullName, filesScanned); |
| 160 | + } |
| 161 | + |
| 162 | + if (opts.check && analysis.score < minScore) { |
| 163 | + if (!opts.json) { |
| 164 | + console.error( |
| 165 | + chalk.red(`❌ Security score ${analysis.score}/100 is below the required minimum of ${minScore}.`) |
| 166 | + ); |
| 167 | + } |
| 168 | + exitCode = 1; |
| 169 | + } |
| 170 | + } catch (error: unknown) { |
| 171 | + console.error( |
| 172 | + chalk.red(`Security analysis failed: ${error instanceof Error ? error.message : String(error)}`) |
| 173 | + ); |
| 174 | + exitCode = 1; |
| 175 | + } finally { |
| 176 | + if (opts.keepTemp && !repoSource.isLocal) { |
| 177 | + console.log(chalk.gray(`Temporary clone kept at: ${repoSource.path}`)); |
| 178 | + } else { |
| 179 | + await repoSource.cleanup(); |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + if (exitCode !== 0) { |
| 184 | + process.exit(exitCode); |
| 185 | + } |
| 186 | +} |
0 commit comments