@rafter-security/cli 0.8.7 → 0.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,28 +3,48 @@ import fs from "fs";
3
3
  import path from "path";
4
4
  import { PatternEngine } from "../../core/pattern-engine.js";
5
5
  import { DEFAULT_SECRET_PATTERNS } from "../../scanners/secret-patterns.js";
6
+ import { SkillScanner, hasFindings as deepHasFindings, INSTALL_HINT, } from "../../scanners/skill-scanner.js";
6
7
  import { SkillManager } from "../../utils/skill-manager.js";
7
8
  import { fmt } from "../../utils/formatter.js";
8
9
  export function createAuditSkillCommand() {
9
10
  return new Command("audit-skill")
10
11
  .description("[deprecated] Security audit of a Claude Code skill file — use `rafter skill review` instead")
11
- .argument("<skill-path>", "Path to skill file to audit")
12
+ .argument("<skill-path>", "Path to skill file or directory to audit")
12
13
  .option("--skip-openclaw", "Skip OpenClaw integration, show manual review prompt")
13
14
  .option("--json", "Output results as JSON")
15
+ .option("--deep", "Run the optional DEEP engine (Cisco AI Defense skill-scanner) in addition to the quick scan. Offline analyzers only — no LLM/cloud/network. Requires cisco-ai-skill-scanner.")
16
+ .option("--engine <engine>", "Deep engine selector. 'skill-scanner' is equivalent to --deep.")
14
17
  .action(async (skillPath, opts) => {
15
18
  process.stderr.write("[deprecated] `rafter agent audit-skill` is deprecated; use `rafter skill review <path-or-url>` instead.\n");
16
19
  await auditSkill(skillPath, opts);
17
20
  });
18
21
  }
19
22
  async function auditSkill(skillPath, opts) {
20
- // Validate skill file exists
23
+ // Validate target exists. Accept either a skill *file* (.md) or a skill
24
+ // *directory*. The deep engine (--deep) is most thorough on a directory,
25
+ // where it can also see bundled scripts / .pyc; the quick scan reads the
26
+ // directory's SKILL.md (or the file itself).
21
27
  if (!fs.existsSync(skillPath)) {
22
- console.error(fmt.error(`Skill file not found: ${skillPath}`));
28
+ console.error(fmt.error(`Skill path not found: ${skillPath}`));
23
29
  process.exit(2);
24
30
  }
25
31
  const absolutePath = path.resolve(skillPath);
26
- const skillContent = fs.readFileSync(absolutePath, "utf-8");
32
+ const isDir = fs.statSync(absolutePath).isDirectory();
33
+ let skillContent;
34
+ if (isDir) {
35
+ const skillMd = path.join(absolutePath, "SKILL.md");
36
+ skillContent = fs.existsSync(skillMd) ? fs.readFileSync(skillMd, "utf-8") : "";
37
+ }
38
+ else {
39
+ skillContent = fs.readFileSync(absolutePath, "utf-8");
40
+ }
27
41
  const skillName = path.basename(absolutePath);
42
+ // Validate --engine early (mirrors the Python contract).
43
+ const wantDeep = !!opts.deep || opts.engine === "skill-scanner";
44
+ if (opts.engine != null && opts.engine !== "skill-scanner") {
45
+ console.error(fmt.error(`unknown --engine '${opts.engine}' (supported: skill-scanner)`));
46
+ process.exit(2);
47
+ }
28
48
  // Run deterministic analysis
29
49
  if (!opts.json) {
30
50
  console.log(fmt.header(`Auditing skill: ${skillName}`));
@@ -36,6 +56,28 @@ async function auditSkill(skillPath, opts) {
36
56
  if (!opts.json) {
37
57
  displayQuickScan(quickScan, skillName);
38
58
  }
59
+ // Optional DEEP engine (skill-scanner) — opt-in via --deep or
60
+ // --engine skill-scanner. Offline analyzers only; preserves our
61
+ // no-telemetry default (sable-7g7).
62
+ let deepResult = null;
63
+ if (wantDeep) {
64
+ const scanner = new SkillScanner();
65
+ if (!scanner.isAvailable()) {
66
+ // --deep requested but tool missing: clear hint, non-zero exit, no crash.
67
+ console.error(INSTALL_HINT);
68
+ process.exit(2);
69
+ }
70
+ deepResult = await scanner.scanPath(absolutePath);
71
+ if (deepResult.error) {
72
+ console.error(fmt.error(`deep scan failed: ${deepResult.error}`));
73
+ process.exit(2);
74
+ }
75
+ if (!opts.json) {
76
+ displayDeepScan(deepResult);
77
+ }
78
+ }
79
+ const quickHasFindings = quickScan.secrets > 0 || quickScan.highRiskCommands.length > 0;
80
+ const deepFound = deepResult ? deepHasFindings(deepResult) : false;
39
81
  // Check OpenClaw availability
40
82
  const skillManager = new SkillManager();
41
83
  const openClawAvailable = skillManager.isOpenClawInstalled();
@@ -49,8 +91,16 @@ async function auditSkill(skillPath, opts) {
49
91
  openClawAvailable,
50
92
  rafterSkillInstalled
51
93
  };
94
+ if (deepResult) {
95
+ result.deepScan = {
96
+ engine: "skill-scanner",
97
+ maxSeverity: deepResult.maxSeverity,
98
+ analyzersUsed: deepResult.analyzersUsed,
99
+ findings: deepResult.findings,
100
+ };
101
+ }
52
102
  console.log(JSON.stringify(result, null, 2));
53
- if (quickScan.secrets > 0 || quickScan.highRiskCommands.length > 0) {
103
+ if (quickHasFindings || deepFound) {
54
104
  process.exit(1);
55
105
  }
56
106
  return;
@@ -90,10 +140,36 @@ async function auditSkill(skillPath, opts) {
90
140
  console.log(fmt.divider());
91
141
  }
92
142
  console.log();
93
- if (quickScan.secrets > 0 || quickScan.highRiskCommands.length > 0) {
143
+ if (quickHasFindings || deepFound) {
94
144
  process.exit(1);
95
145
  }
96
146
  }
147
+ function displayDeepScan(deep) {
148
+ console.log(`\n🔎 Deep Scan Results (skill-scanner)`);
149
+ console.log(fmt.divider());
150
+ if (!deep.available) {
151
+ console.log(fmt.warning("skill-scanner not available"));
152
+ return;
153
+ }
154
+ const actionable = deep.findings.filter((f) => ["critical", "high", "medium"].includes(f.severity));
155
+ if (actionable.length === 0) {
156
+ console.log(fmt.success("No critical/high/medium findings"));
157
+ }
158
+ else {
159
+ console.log(fmt.warning(`${actionable.length} finding(s) (max severity: ${deep.maxSeverity})`));
160
+ actionable.slice(0, 10).forEach((f) => {
161
+ const loc = f.line ? ` (line ${f.line})` : "";
162
+ console.log(` • [${f.severity.toUpperCase()}] ${f.category}: ${f.title}${loc}`);
163
+ });
164
+ if (actionable.length > 10) {
165
+ console.log(` ... and ${actionable.length - 10} more`);
166
+ }
167
+ }
168
+ if (deep.analyzersUsed.length > 0) {
169
+ console.log(` analyzers: ${deep.analyzersUsed.join(", ")} (offline only)`);
170
+ }
171
+ console.log();
172
+ }
97
173
  async function runQuickScan(content) {
98
174
  // 1. Scan for secrets
99
175
  const patternEngine = new PatternEngine(DEFAULT_SECRET_PATTERNS);
@@ -1,5 +1,5 @@
1
1
  import { Command } from "commander";
2
- import { ConfigManager } from "../../core/config-manager.js";
2
+ import { ConfigManager, redactConfigSecrets, isSecretConfigKey, maskSecretValue } from "../../core/config-manager.js";
3
3
  import { fmt } from "../../utils/formatter.js";
4
4
  export function createConfigCommand() {
5
5
  const config = new Command("config")
@@ -11,7 +11,7 @@ export function createConfigCommand() {
11
11
  .action(() => {
12
12
  const manager = new ConfigManager();
13
13
  const cfg = manager.load();
14
- console.log(JSON.stringify(cfg, null, 2));
14
+ console.log(JSON.stringify(redactConfigSecrets(cfg), null, 2));
15
15
  });
16
16
  // Get specific value
17
17
  config
@@ -25,8 +25,12 @@ export function createConfigCommand() {
25
25
  console.error(`Key not found: ${key}`);
26
26
  process.exit(1);
27
27
  }
28
+ const leaf = key.split(".").pop() ?? key;
28
29
  if (typeof value === "object") {
29
- console.log(JSON.stringify(value, null, 2));
30
+ console.log(JSON.stringify(redactConfigSecrets(value), null, 2));
31
+ }
32
+ else if (isSecretConfigKey(leaf) && typeof value === "string") {
33
+ console.log(maskSecretValue(value));
30
34
  }
31
35
  else {
32
36
  console.log(value);
@@ -49,7 +53,11 @@ export function createConfigCommand() {
49
53
  // Use as string
50
54
  }
51
55
  manager.set(key, parsedValue);
52
- console.log(fmt.success(`Set ${key} = ${JSON.stringify(parsedValue)}`));
56
+ const leaf = key.split(".").pop() ?? key;
57
+ const echo = isSecretConfigKey(leaf) && typeof parsedValue === "string"
58
+ ? JSON.stringify(maskSecretValue(parsedValue))
59
+ : JSON.stringify(parsedValue);
60
+ console.log(fmt.success(`Set ${key} = ${echo}`));
53
61
  });
54
62
  return config;
55
63
  }
@@ -1,6 +1,7 @@
1
1
  import { Command } from "commander";
2
2
  import { CommandInterceptor } from "../../core/command-interceptor.js";
3
- import { RegexScanner } from "../../scanners/regex-scanner.js";
3
+ import { scanAddedDiffLines } from "../../scanners/git-diff-scan.js";
4
+ import { parseUnifiedDiffAddedLines } from "../../utils/git-diff.js";
4
5
  import { execSync } from "child_process";
5
6
  import readline from "readline";
6
7
  import { fmt } from "../../utils/formatter.js";
@@ -80,25 +81,27 @@ function isGitCommand(command) {
80
81
  }
81
82
  async function scanStagedFiles() {
82
83
  try {
83
- // Get staged files
84
- const stagedFiles = execSync("git diff --cached --name-only", {
84
+ const patch = execSync("git diff -U0 --no-color --cached --diff-filter=ACM", {
85
85
  encoding: "utf-8",
86
- stdio: ["pipe", "pipe", "ignore"]
87
- })
88
- .trim()
89
- .split("\n")
90
- .filter(f => f);
91
- if (stagedFiles.length === 0) {
86
+ stdio: ["pipe", "pipe", "ignore"],
87
+ }).trim();
88
+ if (!patch) {
92
89
  return { secretsFound: false, count: 0, files: 0 };
93
90
  }
94
- // Scan staged files
95
- const scanner = new RegexScanner();
96
- const results = scanner.scanFiles(stagedFiles);
91
+ const repoRoot = execSync("git rev-parse --show-toplevel", {
92
+ encoding: "utf-8",
93
+ stdio: ["pipe", "pipe", "ignore"],
94
+ }).trim();
95
+ const addedLines = parseUnifiedDiffAddedLines(patch);
96
+ if (addedLines.length === 0) {
97
+ return { secretsFound: false, count: 0, files: 0 };
98
+ }
99
+ const results = scanAddedDiffLines(addedLines, repoRoot);
97
100
  const totalMatches = results.reduce((sum, r) => sum + r.matches.length, 0);
98
101
  return {
99
102
  secretsFound: results.length > 0,
100
103
  count: totalMatches,
101
- files: results.length
104
+ files: results.length,
102
105
  };
103
106
  }
104
107
  catch {
@@ -10,6 +10,8 @@ import { createInstallHookCommand } from "./install-hook.js";
10
10
  import { createVerifyCommand } from "./verify.js";
11
11
  import { createStatusCommand } from "./status.js";
12
12
  import { createUpdateBetterleaksCommand } from "./update-betterleaks.js";
13
+ import { createUpdateSkillScannerCommand } from "./update-skill-scanner.js";
14
+ import { createRemoveSkillScannerCommand } from "./remove-skill-scanner.js";
13
15
  import { createBaselineCommand } from "./baseline.js";
14
16
  import { createListCommand } from "./list.js";
15
17
  import { createEnableCommand } from "./enable.js";
@@ -29,6 +31,8 @@ export function createAgentCommand() {
29
31
  agent.addCommand(createVerifyCommand());
30
32
  agent.addCommand(createStatusCommand());
31
33
  agent.addCommand(createUpdateBetterleaksCommand());
34
+ agent.addCommand(createUpdateSkillScannerCommand());
35
+ agent.addCommand(createRemoveSkillScannerCommand());
32
36
  agent.addCommand(createBaselineCommand());
33
37
  agent.addCommand(createListCommand());
34
38
  agent.addCommand(createEnableCommand());
@@ -1,6 +1,7 @@
1
1
  import { Command } from "commander";
2
2
  import { ConfigManager } from "../../core/config-manager.js";
3
3
  import { BinaryManager } from "../../utils/binary-manager.js";
4
+ import { SkillScannerInstaller, SKILL_SCANNER_VERSION } from "../../scanners/skill-scanner.js";
4
5
  import { SkillManager } from "../../utils/skill-manager.js";
5
6
  import fs from "fs";
6
7
  import path from "path";
@@ -62,6 +63,11 @@ function printDryRunPlan(plan) {
62
63
  console.log("Betterleaks (--with-betterleaks / --all):");
63
64
  D(path.join(home, ".rafter", "bin", "betterleaks"), "binary, ~12MB from GitHub releases");
64
65
  }
66
+ if (plan.wantSkillScanner) {
67
+ console.log();
68
+ console.log("skill-scanner deep engine (--with-skill-scanner):");
69
+ D("skill-scanner", "heavy PyPI package, isolated install via uv tool / pip --user");
70
+ }
65
71
  if (plan.wantClaudeCode) {
66
72
  console.log();
67
73
  console.log("Claude Code (--with-claude-code):");
@@ -934,6 +940,7 @@ export function createInitCommand() {
934
940
  .option("--with-continue", "Install Continue.dev integration")
935
941
  .option("--with-hermes", "Install Hermes integration")
936
942
  .option("--with-betterleaks", "Download and install Betterleaks binary")
943
+ .option("--with-skill-scanner", "Install the optional skill-scanner deep engine (heavy; audit-skill --deep)")
937
944
  .option("--all", "Install all detected integrations and download Betterleaks")
938
945
  .option("-i, --interactive", "Guided setup — prompts for each detected integration")
939
946
  .option("--update", "Re-download betterleaks and reinstall integrations without resetting config")
@@ -991,6 +998,8 @@ export function createInitCommand() {
991
998
  // established. Excluded from --all in --local for the same reason.
992
999
  let wantHermes = opts.withHermes || (opts.all && !opts.local);
993
1000
  let wantBetterleaks = opts.withBetterleaks || (opts.all && !opts.local);
1001
+ // skill-scanner is heavy and opt-in only — deliberately NOT folded into --all.
1002
+ const wantSkillScanner = !!opts.withSkillScanner;
994
1003
  // Interactive mode: prompt for each detected integration
995
1004
  if (opts.interactive && !opts.all) {
996
1005
  console.log();
@@ -1084,6 +1093,7 @@ export function createInitCommand() {
1084
1093
  wantAider: wantAider && (hasAider || opts.local),
1085
1094
  wantHermes: wantHermes && hasHermes,
1086
1095
  wantBetterleaks,
1096
+ wantSkillScanner,
1087
1097
  riskLevel: opts.riskLevel,
1088
1098
  });
1089
1099
  return;
@@ -1175,6 +1185,34 @@ export function createInitCommand() {
1175
1185
  }
1176
1186
  }
1177
1187
  }
1188
+ // Install the optional skill-scanner deep engine (opt-in via
1189
+ // --with-skill-scanner only — never via --all, as it's heavy).
1190
+ if (wantSkillScanner) {
1191
+ const onPath = opts.update ? null : (() => {
1192
+ try {
1193
+ const cmd = process.platform === "win32" ? "where skill-scanner" : "which skill-scanner";
1194
+ return execSync(cmd, { timeout: 5000, encoding: "utf-8" }).trim().split("\n")[0].trim() || null;
1195
+ }
1196
+ catch {
1197
+ return null;
1198
+ }
1199
+ })();
1200
+ if (onPath) {
1201
+ console.log(fmt.success(`skill-scanner available on PATH (${onPath})`));
1202
+ }
1203
+ else {
1204
+ console.log();
1205
+ console.log(fmt.info("Installing optional skill-scanner deep engine (heavy third-party package; isolated install)..."));
1206
+ const result = await new SkillScannerInstaller().install(SKILL_SCANNER_VERSION, (msg) => console.log(` ${msg}`));
1207
+ if (result.ok) {
1208
+ console.log(fmt.success(`skill-scanner installed (via ${result.via}): ${result.message}`));
1209
+ }
1210
+ else {
1211
+ console.log(fmt.warning(`skill-scanner install failed: ${result.message}`));
1212
+ console.log(fmt.info("To fix: run 'rafter agent update-skill-scanner' or install manually with 'uv tool install cisco-ai-skill-scanner'."));
1213
+ }
1214
+ }
1215
+ }
1178
1216
  // Install OpenClaw skill if opted in
1179
1217
  let openclawOk = false;
1180
1218
  if (hasOpenClaw && wantOpenClaw) {
@@ -0,0 +1,16 @@
1
+ import { Command } from "commander";
2
+ import { SkillScannerInstaller } from "../../scanners/skill-scanner.js";
3
+ import { fmt } from "../../utils/formatter.js";
4
+ export function createRemoveSkillScannerCommand() {
5
+ return new Command("remove-skill-scanner")
6
+ .description("Uninstall the optional skill-scanner deep engine (inverse of update-skill-scanner)")
7
+ .action(async () => {
8
+ const result = await new SkillScannerInstaller().uninstall((msg) => console.log(` ${msg}`));
9
+ console.log();
10
+ if (!result.ok) {
11
+ console.error(fmt.error(`Uninstall failed: ${result.message}`));
12
+ process.exit(1);
13
+ }
14
+ console.log(fmt.success(`skill-scanner removed: ${result.message}`));
15
+ });
16
+ }
@@ -1,5 +1,7 @@
1
1
  import { Command } from "commander";
2
2
  import { RegexScanner } from "../../scanners/regex-scanner.js";
3
+ import { scanAddedDiffLines } from "../../scanners/git-diff-scan.js";
4
+ import { parseUnifiedDiffAddedLines } from "../../utils/git-diff.js";
3
5
  import { BetterleaksScanner } from "../../scanners/betterleaks.js";
4
6
  import { unionScanResults } from "../../scanners/union.js";
5
7
  import { BinaryManager, BETTERLEAKS_VERSION } from "../../utils/binary-manager.js";
@@ -344,98 +346,60 @@ function outputScanResults(results, opts, context, exitOnFindings = true, suppre
344
346
  process.exit(1);
345
347
  }
346
348
  /**
347
- * Scan files changed since a git ref
349
+ * Scan files changed since a git ref (+ lines only in the unified diff).
348
350
  */
349
351
  async function scanDiffFiles(ref, opts, scanCfg, baselineEntries = [], scanPath, suppressions = []) {
350
- const cwd = scanPath && fs.existsSync(scanPath) && fs.statSync(scanPath).isDirectory() ? scanPath : undefined;
351
- try {
352
- const diffOutput = execFileSync("git", ["diff", "--name-only", "--diff-filter=ACM", ref], {
353
- encoding: "utf-8",
354
- cwd,
355
- stdio: ["pipe", "pipe", "ignore"],
356
- }).trim();
357
- if (!diffOutput) {
358
- outputScanResults([], opts, `files changed since ${ref}`, true, suppressions);
359
- return;
360
- }
361
- const changedFiles = diffOutput.split("\n").map(f => f.trim()).filter(f => f);
362
- if (!opts.quiet) {
363
- console.error(`Scanning ${changedFiles.length} file(s) changed since ${ref}...`);
364
- }
365
- const repoRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], {
366
- encoding: "utf-8",
367
- cwd,
368
- stdio: ["pipe", "pipe", "ignore"],
369
- }).trim();
370
- const engine = await selectEngine(opts.engine || "auto", opts.quiet || false, autoUpdateEnabled(opts, scanCfg));
371
- const allResults = [];
372
- for (const file of changedFiles) {
373
- const filePath = path.resolve(repoRoot, file);
374
- if (!fs.existsSync(filePath))
375
- continue;
376
- const stats = fs.statSync(filePath);
377
- if (!stats.isFile())
378
- continue;
379
- const results = await scanFile(filePath, engine, scanCfg);
380
- allResults.push(...results);
381
- }
382
- // sable-yz0 — honor scan.exclude_paths in --diff mode too (was previously
383
- // dropped). Use the repo root as scanRoot so user-relative paths in
384
- // .rafter.yml resolve consistently with the directory-scan behavior.
385
- const filteredDiff = applyExcludePaths(allResults, scanCfg?.excludePaths, repoRoot);
386
- outputScanResults(applyBaseline(filteredDiff, baselineEntries), opts, `files changed since ${ref}`, true, suppressions);
387
- }
388
- catch (error) {
389
- if (error.status === 128) {
390
- console.error("Error: Not in a git repository or invalid ref");
391
- process.exit(2);
392
- }
393
- throw error;
394
- }
352
+ await runGitAddedLineScan(["diff", "-U0", "--no-color", "--diff-filter=ACM", ref], opts, scanCfg, baselineEntries, scanPath, suppressions, `files changed since ${ref}`, `No files changed since ${ref}`);
395
353
  }
396
354
  /**
397
- * Scan git staged files for secrets
355
+ * Scan git staged files for secrets (+ lines only in the staged diff).
398
356
  */
399
357
  async function scanStagedFiles(opts, scanCfg, baselineEntries = [], scanPath, suppressions = []) {
358
+ await runGitAddedLineScan(["diff", "-U0", "--no-color", "--cached", "--diff-filter=ACM"], opts, scanCfg, baselineEntries, scanPath, suppressions, "staged files", "No files staged for commit", { notRepoMessage: "Error: Not in a git repository" });
359
+ }
360
+ /**
361
+ * Shared handler for --diff / --staged: parse unified diff for + lines, scan
362
+ * with the patterns engine, then apply exclude_paths / baseline / suppressions.
363
+ */
364
+ async function runGitAddedLineScan(gitArgs, opts, scanCfg, baselineEntries, scanPath, suppressions, contextLabel, emptyMessage, errorOpts) {
400
365
  const cwd = scanPath && fs.existsSync(scanPath) && fs.statSync(scanPath).isDirectory() ? scanPath : undefined;
401
366
  try {
402
- const stagedFilesOutput = execFileSync("git", ["diff", "--cached", "--name-only", "--diff-filter=ACM"], {
367
+ const patch = execFileSync("git", gitArgs, {
403
368
  encoding: "utf-8",
404
369
  cwd,
405
- stdio: ["pipe", "pipe", "ignore"]
406
- }).trim();
407
- if (!stagedFilesOutput) {
408
- outputScanResults([], opts, "staged files", true, suppressions);
370
+ stdio: ["pipe", "pipe", "ignore"],
371
+ });
372
+ if (!patch.trim()) {
373
+ if (!opts.quiet) {
374
+ console.log(`\n${fmt.success(emptyMessage)}\n`);
375
+ }
376
+ outputScanResults([], opts, contextLabel, true, suppressions);
409
377
  return;
410
378
  }
411
- const stagedFiles = stagedFilesOutput.split("\n").map(f => f.trim()).filter(f => f);
412
- if (!opts.quiet) {
413
- console.error(`Scanning ${stagedFiles.length} staged file(s)...`);
379
+ const addedLines = parseUnifiedDiffAddedLines(patch);
380
+ if (addedLines.length === 0) {
381
+ if (!opts.quiet) {
382
+ console.log(`\n${fmt.success(emptyMessage)}\n`);
383
+ }
384
+ outputScanResults([], opts, contextLabel, true, suppressions);
385
+ return;
414
386
  }
415
387
  const repoRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], {
416
388
  encoding: "utf-8",
417
389
  cwd,
418
390
  stdio: ["pipe", "pipe", "ignore"],
419
391
  }).trim();
420
- const engine = await selectEngine(opts.engine || "auto", opts.quiet || false, autoUpdateEnabled(opts, scanCfg));
421
- const allResults = [];
422
- for (const file of stagedFiles) {
423
- const filePath = path.resolve(repoRoot, file);
424
- if (!fs.existsSync(filePath))
425
- continue;
426
- const stats = fs.statSync(filePath);
427
- if (!stats.isFile())
428
- continue;
429
- const results = await scanFile(filePath, engine, scanCfg);
430
- allResults.push(...results);
431
- }
432
- // sable-yz0 — honor scan.exclude_paths in --staged mode too.
433
- const filteredStaged = applyExcludePaths(allResults, scanCfg?.excludePaths, repoRoot);
434
- outputScanResults(applyBaseline(filteredStaged, baselineEntries), opts, "staged files", true, suppressions);
392
+ const fileCount = new Set(addedLines.map((l) => l.file)).size;
393
+ if (!opts.quiet) {
394
+ console.error(`Scanning ${addedLines.length} added line(s) in ${fileCount} file(s) (${contextLabel})...`);
395
+ }
396
+ const allResults = scanAddedDiffLines(addedLines, repoRoot, scanCfg?.customPatterns);
397
+ const filtered = applyExcludePaths(allResults, scanCfg?.excludePaths, repoRoot);
398
+ outputScanResults(applyBaseline(filtered, baselineEntries), opts, contextLabel, true, suppressions);
435
399
  }
436
400
  catch (error) {
437
401
  if (error.status === 128) {
438
- console.error("Error: Not in a git repository");
402
+ console.error(errorOpts?.notRepoMessage ?? "Error: Not in a git repository or invalid ref");
439
403
  process.exit(2);
440
404
  }
441
405
  throw error;
@@ -0,0 +1,40 @@
1
+ import { Command } from "commander";
2
+ import { execSync } from "child_process";
3
+ import { SkillScannerInstaller, SKILL_SCANNER_VERSION, } from "../../scanners/skill-scanner.js";
4
+ import { fmt } from "../../utils/formatter.js";
5
+ export function createUpdateSkillScannerCommand() {
6
+ return new Command("update-skill-scanner")
7
+ .description("Install or update the optional skill-scanner deep engine (audit-skill --deep)")
8
+ .option("--version <version>", "skill-scanner version to install", SKILL_SCANNER_VERSION)
9
+ .action(async (opts) => {
10
+ const checkCmd = process.platform === "win32" ? "where skill-scanner" : "which skill-scanner";
11
+ let existing = null;
12
+ try {
13
+ existing = execSync(checkCmd, { timeout: 5000, encoding: "utf-8" }).trim().split("\n")[0].trim() || null;
14
+ }
15
+ catch {
16
+ existing = null;
17
+ }
18
+ if (existing) {
19
+ console.log(fmt.info(`Current skill-scanner: ${existing}`));
20
+ }
21
+ else {
22
+ console.log(fmt.info("skill-scanner not currently on PATH"));
23
+ }
24
+ console.log(fmt.warning("skill-scanner is a heavy third-party package (pulls litellm, fastapi, " +
25
+ "yara-x, …). Installing it in an isolated environment."));
26
+ console.log(fmt.info(`Installing skill-scanner v${opts.version}...`));
27
+ console.log();
28
+ const result = await new SkillScannerInstaller().install(opts.version, (msg) => console.log(` ${msg}`));
29
+ console.log();
30
+ if (!result.ok) {
31
+ console.error(fmt.error(`Install failed: ${result.message}`));
32
+ console.log(fmt.info("To fix: install manually with `uv tool install cisco-ai-skill-scanner` " +
33
+ "(or `pip install --user cisco-ai-skill-scanner`) and ensure " +
34
+ "`skill-scanner` is on PATH."));
35
+ process.exit(1);
36
+ }
37
+ console.log(fmt.success(`skill-scanner installed (via ${result.via}): ${result.message}`));
38
+ console.log(fmt.info("Run `rafter agent audit-skill <path> --deep` to use it."));
39
+ });
40
+ }
@@ -110,15 +110,33 @@ function countMatches(scanner, tool_response) {
110
110
  }
111
111
  return count;
112
112
  }
113
- const STDIN_TIMEOUT_MS = 5000;
113
+ // Bound the stdin read so a hung/never-closing stdin can't wedge the hook.
114
+ // Overridable via env (milliseconds) as an operator safety valve / for tests.
115
+ function stdinTimeoutMs() {
116
+ const n = Number(process.env.RAFTER_HOOK_STDIN_TIMEOUT_MS);
117
+ return Number.isFinite(n) && n > 0 ? n : 5000;
118
+ }
114
119
  function readStdin() {
115
120
  return new Promise((resolve) => {
116
121
  let data = "";
117
- const timeout = setTimeout(() => { resolve(data); }, STDIN_TIMEOUT_MS);
122
+ const onData = (chunk) => { data += chunk; };
123
+ const finish = () => {
124
+ clearTimeout(timeout);
125
+ process.stdin.removeListener("data", onData);
126
+ process.stdin.removeListener("end", finish);
127
+ process.stdin.removeListener("error", finish);
128
+ // A piped stdin with no EOF stays in flowing mode and keeps the Node
129
+ // event loop alive indefinitely — even after we resolve. Pause it so the
130
+ // process can exit once the output is written (was a hard hang on the
131
+ // timeout path: output emitted at 5s but the process never exited).
132
+ process.stdin.pause();
133
+ resolve(data);
134
+ };
135
+ const timeout = setTimeout(finish, stdinTimeoutMs());
118
136
  process.stdin.setEncoding("utf-8");
119
- process.stdin.on("data", (chunk) => { data += chunk; });
120
- process.stdin.on("end", () => { clearTimeout(timeout); resolve(data); });
121
- process.stdin.on("error", () => { clearTimeout(timeout); resolve(data); });
137
+ process.stdin.on("data", onData);
138
+ process.stdin.on("end", finish);
139
+ process.stdin.on("error", finish);
122
140
  process.stdin.resume();
123
141
  });
124
142
  }
@@ -6,8 +6,9 @@ import { ConfigManager } from "../../core/config-manager.js";
6
6
  import { applySuppressions } from "../../core/custom-patterns.js";
7
7
  import { resolveHookControl } from "../../core/hook-control.js";
8
8
  import { collectSuppressions, applyExcludePaths } from "../agent/scan.js";
9
+ import { scanAddedDiffLines } from "../../scanners/git-diff-scan.js";
10
+ import { parseUnifiedDiffAddedLines } from "../../utils/git-diff.js";
9
11
  import { execSync } from "child_process";
10
- import fs from "fs";
11
12
  import path from "path";
12
13
  /**
13
14
  * Load the policy-merged scan config + suppression list the same way scan.ts
@@ -256,22 +257,16 @@ export function scanStagedFiles(cwd = process.cwd()) {
256
257
  };
257
258
  try {
258
259
  const repoRoot = execSync("git rev-parse --show-toplevel", gitOpts).trim() || cwd;
259
- const stagedOutput = execSync("git diff --cached --name-only --diff-filter=ACM", gitOpts).trim();
260
- if (!stagedOutput) {
260
+ const patch = execSync("git diff -U0 --no-color --cached --diff-filter=ACM", gitOpts).trim();
261
+ if (!patch) {
261
262
  return { ...empty, repoRoot };
262
263
  }
263
- const stagedFiles = stagedOutput.split("\n").filter((f) => f.trim());
264
- const { scanCfg, suppressions } = loadScanConfig(cwd);
265
- const scanner = new RegexScanner(scanCfg?.customPatterns);
266
- const raw = [];
267
- for (const file of stagedFiles) {
268
- const filePath = path.resolve(repoRoot, file);
269
- if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile())
270
- continue;
271
- const r = scanner.scanFile(filePath);
272
- if (r.matches.length > 0)
273
- raw.push(r);
264
+ const addedLines = parseUnifiedDiffAddedLines(patch);
265
+ if (addedLines.length === 0) {
266
+ return { ...empty, repoRoot };
274
267
  }
268
+ const { scanCfg, suppressions } = loadScanConfig(cwd);
269
+ const raw = scanAddedDiffLines(addedLines, repoRoot, scanCfg?.customPatterns);
275
270
  const afterExclude = applyExcludePaths(raw, scanCfg?.excludePaths, repoRoot);
276
271
  const { results: kept } = applySuppressions(afterExclude, suppressions);
277
272
  const count = kept.reduce((sum, r) => sum + r.matches.length, 0);
@@ -316,15 +311,33 @@ export function formatStagedSecretReason(scan) {
316
311
  "Run 'rafter secrets --staged' for full detail, or add an exclude_paths/ignore rule to .rafter.yml if this is a false positive.",
317
312
  ].join("\n");
318
313
  }
319
- const STDIN_TIMEOUT_MS = 5000;
314
+ // Bound the stdin read so a hung/never-closing stdin can't wedge the hook.
315
+ // Overridable via env (milliseconds) as an operator safety valve / for tests.
316
+ function stdinTimeoutMs() {
317
+ const n = Number(process.env.RAFTER_HOOK_STDIN_TIMEOUT_MS);
318
+ return Number.isFinite(n) && n > 0 ? n : 5000;
319
+ }
320
320
  function readStdin() {
321
321
  return new Promise((resolve) => {
322
322
  let data = "";
323
- const timeout = setTimeout(() => { resolve(data); }, STDIN_TIMEOUT_MS);
323
+ const onData = (chunk) => { data += chunk; };
324
+ const finish = () => {
325
+ clearTimeout(timeout);
326
+ process.stdin.removeListener("data", onData);
327
+ process.stdin.removeListener("end", finish);
328
+ process.stdin.removeListener("error", finish);
329
+ // A piped stdin with no EOF stays in flowing mode and keeps the Node
330
+ // event loop alive indefinitely — even after we resolve. Pause it so the
331
+ // process can exit once the decision is written (was a hard hang on the
332
+ // timeout path: output emitted at 5s but the process never exited).
333
+ process.stdin.pause();
334
+ resolve(data);
335
+ };
336
+ const timeout = setTimeout(finish, stdinTimeoutMs());
324
337
  process.stdin.setEncoding("utf-8");
325
- process.stdin.on("data", (chunk) => { data += chunk; });
326
- process.stdin.on("end", () => { clearTimeout(timeout); resolve(data); });
327
- process.stdin.on("error", () => { clearTimeout(timeout); resolve(data); });
338
+ process.stdin.on("data", onData);
339
+ process.stdin.on("end", finish);
340
+ process.stdin.on("error", finish);
328
341
  process.stdin.resume();
329
342
  });
330
343
  }