@rafter-security/cli 0.8.7 → 0.8.10

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);
@@ -112,7 +112,9 @@ function claudeCodeHooks() {
112
112
  delete settings.hooks.SessionStart;
113
113
  }
114
114
  settings.hooks.PreToolUse.push({ matcher: "Bash", hooks: [pre] }, { matcher: "Write|Edit", hooks: [pre] });
115
- settings.hooks.PostToolUse.push({ matcher: ".*", hooks: [post] });
115
+ // Narrow to tools that produce scannable output (shell output + file
116
+ // writes); avoids firing posttool on every Read/MCP call (latency).
117
+ settings.hooks.PostToolUse.push({ matcher: "Bash|Write|Edit|MultiEdit", hooks: [post] });
116
118
  writeJson(settingsPath, settings);
117
119
  },
118
120
  uninstall: () => {
@@ -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):");
@@ -262,7 +268,10 @@ function installClaudeCodeHooks(root) {
262
268
  }
263
269
  // Add Rafter hooks
264
270
  settings.hooks.PreToolUse.push({ matcher: "Bash", hooks: [preHook] }, { matcher: "Write|Edit", hooks: [preHook] });
265
- settings.hooks.PostToolUse.push({ matcher: ".*", hooks: [postHook] });
271
+ // Narrow to tools that produce scannable output (shell output + file
272
+ // writes). Firing posttool on every tool — including Read and MCP calls —
273
+ // added latency to operations that never produce secrets to redact.
274
+ settings.hooks.PostToolUse.push({ matcher: "Bash|Write|Edit|MultiEdit", hooks: [postHook] });
266
275
  fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), "utf-8");
267
276
  console.log(fmt.success(`Installed PreToolUse hooks to ${settingsPath}`));
268
277
  console.log(fmt.success(`Installed PostToolUse hooks to ${settingsPath}`));
@@ -934,6 +943,7 @@ export function createInitCommand() {
934
943
  .option("--with-continue", "Install Continue.dev integration")
935
944
  .option("--with-hermes", "Install Hermes integration")
936
945
  .option("--with-betterleaks", "Download and install Betterleaks binary")
946
+ .option("--with-skill-scanner", "Install the optional skill-scanner deep engine (heavy; audit-skill --deep)")
937
947
  .option("--all", "Install all detected integrations and download Betterleaks")
938
948
  .option("-i, --interactive", "Guided setup — prompts for each detected integration")
939
949
  .option("--update", "Re-download betterleaks and reinstall integrations without resetting config")
@@ -991,6 +1001,8 @@ export function createInitCommand() {
991
1001
  // established. Excluded from --all in --local for the same reason.
992
1002
  let wantHermes = opts.withHermes || (opts.all && !opts.local);
993
1003
  let wantBetterleaks = opts.withBetterleaks || (opts.all && !opts.local);
1004
+ // skill-scanner is heavy and opt-in only — deliberately NOT folded into --all.
1005
+ const wantSkillScanner = !!opts.withSkillScanner;
994
1006
  // Interactive mode: prompt for each detected integration
995
1007
  if (opts.interactive && !opts.all) {
996
1008
  console.log();
@@ -1084,6 +1096,7 @@ export function createInitCommand() {
1084
1096
  wantAider: wantAider && (hasAider || opts.local),
1085
1097
  wantHermes: wantHermes && hasHermes,
1086
1098
  wantBetterleaks,
1099
+ wantSkillScanner,
1087
1100
  riskLevel: opts.riskLevel,
1088
1101
  });
1089
1102
  return;
@@ -1175,6 +1188,34 @@ export function createInitCommand() {
1175
1188
  }
1176
1189
  }
1177
1190
  }
1191
+ // Install the optional skill-scanner deep engine (opt-in via
1192
+ // --with-skill-scanner only — never via --all, as it's heavy).
1193
+ if (wantSkillScanner) {
1194
+ const onPath = opts.update ? null : (() => {
1195
+ try {
1196
+ const cmd = process.platform === "win32" ? "where skill-scanner" : "which skill-scanner";
1197
+ return execSync(cmd, { timeout: 5000, encoding: "utf-8" }).trim().split("\n")[0].trim() || null;
1198
+ }
1199
+ catch {
1200
+ return null;
1201
+ }
1202
+ })();
1203
+ if (onPath) {
1204
+ console.log(fmt.success(`skill-scanner available on PATH (${onPath})`));
1205
+ }
1206
+ else {
1207
+ console.log();
1208
+ console.log(fmt.info("Installing optional skill-scanner deep engine (heavy third-party package; isolated install)..."));
1209
+ const result = await new SkillScannerInstaller().install(SKILL_SCANNER_VERSION, (msg) => console.log(` ${msg}`));
1210
+ if (result.ok) {
1211
+ console.log(fmt.success(`skill-scanner installed (via ${result.via}): ${result.message}`));
1212
+ }
1213
+ else {
1214
+ console.log(fmt.warning(`skill-scanner install failed: ${result.message}`));
1215
+ console.log(fmt.info("To fix: run 'rafter agent update-skill-scanner' or install manually with 'uv tool install cisco-ai-skill-scanner'."));
1216
+ }
1217
+ }
1218
+ }
1178
1219
  // Install OpenClaw skill if opted in
1179
1220
  let openclawOk = false;
1180
1221
  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
+ }
@@ -4,6 +4,11 @@ import { AuditLogger } from "../../core/audit-logger.js";
4
4
  export function createHookPosttoolCommand() {
5
5
  return new Command("posttool")
6
6
  .description("PostToolUse hook handler (reads stdin, redacts secrets in output, writes JSON to stdout)")
7
+ // Tolerate extra flags/args the host harness appends to the hook command
8
+ // (e.g. Claude Code adds `--hook-json <data>`). Hook input comes from stdin,
9
+ // so anything else is unused — discard it instead of erroring out.
10
+ .allowUnknownOption()
11
+ .allowExcessArguments()
7
12
  .option("--format <format>", "Output format: claude (default, also Codex/Continue), cursor, gemini, windsurf", "claude")
8
13
  .action(async (opts) => {
9
14
  const format = (opts.format || "claude");
@@ -110,15 +115,33 @@ function countMatches(scanner, tool_response) {
110
115
  }
111
116
  return count;
112
117
  }
113
- const STDIN_TIMEOUT_MS = 5000;
118
+ // Bound the stdin read so a hung/never-closing stdin can't wedge the hook.
119
+ // Overridable via env (milliseconds) as an operator safety valve / for tests.
120
+ function stdinTimeoutMs() {
121
+ const n = Number(process.env.RAFTER_HOOK_STDIN_TIMEOUT_MS);
122
+ return Number.isFinite(n) && n > 0 ? n : 5000;
123
+ }
114
124
  function readStdin() {
115
125
  return new Promise((resolve) => {
116
126
  let data = "";
117
- const timeout = setTimeout(() => { resolve(data); }, STDIN_TIMEOUT_MS);
127
+ const onData = (chunk) => { data += chunk; };
128
+ const finish = () => {
129
+ clearTimeout(timeout);
130
+ process.stdin.removeListener("data", onData);
131
+ process.stdin.removeListener("end", finish);
132
+ process.stdin.removeListener("error", finish);
133
+ // A piped stdin with no EOF stays in flowing mode and keeps the Node
134
+ // event loop alive indefinitely — even after we resolve. Pause it so the
135
+ // process can exit once the output is written (was a hard hang on the
136
+ // timeout path: output emitted at 5s but the process never exited).
137
+ process.stdin.pause();
138
+ resolve(data);
139
+ };
140
+ const timeout = setTimeout(finish, stdinTimeoutMs());
118
141
  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); });
142
+ process.stdin.on("data", onData);
143
+ process.stdin.on("end", finish);
144
+ process.stdin.on("error", finish);
122
145
  process.stdin.resume();
123
146
  });
124
147
  }