@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.
@@ -7,7 +7,7 @@ import { BetterleaksScanner } from "../../scanners/betterleaks.js";
7
7
  import { unionScanResults } from "../../scanners/union.js";
8
8
  import { CommandInterceptor } from "../../core/command-interceptor.js";
9
9
  import { AuditLogger } from "../../core/audit-logger.js";
10
- import { ConfigManager } from "../../core/config-manager.js";
10
+ import { ConfigManager, redactConfigSecrets, isSecretConfigKey, maskSecretValue } from "../../core/config-manager.js";
11
11
  import { listDocs, resolveDocSelector, fetchDoc } from "../../core/docs-loader.js";
12
12
  import { writeSuppression } from "../../core/suppression-writer.js";
13
13
  import { createRequire } from "module";
@@ -203,7 +203,12 @@ export function createServer() {
203
203
  case "get_config": {
204
204
  const manager = new ConfigManager();
205
205
  const key = args?.key;
206
- const value = key ? manager.get(key) : manager.load();
206
+ const raw = key ? manager.get(key) : manager.load();
207
+ // Never hand a stored credential (e.g. backend.apiKey) to the MCP client.
208
+ const leaf = key ? (key.split(".").pop() ?? key) : undefined;
209
+ const value = leaf && isSecretConfigKey(leaf) && typeof raw === "string"
210
+ ? maskSecretValue(raw)
211
+ : redactConfigSecrets(raw);
207
212
  return textResult(value);
208
213
  }
209
214
  case "list_docs": {
@@ -302,7 +307,7 @@ export function createServer() {
302
307
  contents: [{
303
308
  uri: "rafter://config",
304
309
  mimeType: "application/json",
305
- text: JSON.stringify(manager.load(), null, 2),
310
+ text: JSON.stringify(redactConfigSecrets(manager.load()), null, 2),
306
311
  }],
307
312
  };
308
313
  case "rafter://policy":
@@ -310,7 +315,7 @@ export function createServer() {
310
315
  contents: [{
311
316
  uri: "rafter://policy",
312
317
  mimeType: "application/json",
313
- text: JSON.stringify(manager.loadWithPolicy(), null, 2),
318
+ text: JSON.stringify(redactConfigSecrets(manager.loadWithPolicy()), null, 2),
314
319
  }],
315
320
  };
316
321
  case "rafter://docs": {
@@ -5,6 +5,7 @@ import os from "os";
5
5
  import { spawnSync } from "child_process";
6
6
  import { PatternEngine } from "../../core/pattern-engine.js";
7
7
  import { DEFAULT_SECRET_PATTERNS } from "../../scanners/secret-patterns.js";
8
+ import { SkillScanner, ensureSkillScanner, deepSeverityTier, deepActionableCount, INSTALL_HINT, } from "../../scanners/skill-scanner.js";
8
9
  import { fmt } from "../../utils/formatter.js";
9
10
  import { discoverInstalledSkills, SKILL_PLATFORMS, } from "./registry.js";
10
11
  import { isShorthand, parseShorthand, defaultCacheRoot, readResolution, writeResolution, resolutionIsFresh, contentKeyGit, contentKeyNpm, contentDir, contentWorkingTree, contentIsUsable, dropCacheEntry, defaultRemoteOps, extractNpmTarball, findSkillFiles, DEFAULT_CACHE_TTL_MS, } from "./remote.js";
@@ -705,7 +706,83 @@ function resolveNpm(input, parsed, opts) {
705
706
  cleanup,
706
707
  };
707
708
  }
708
- export function runSkillReview(input, opts) {
709
+ /** Render the deep-engine section for a single-skill text report. */
710
+ function renderDeepText(report) {
711
+ const deep = report.deepScan;
712
+ if (!deep)
713
+ return;
714
+ console.log(fmt.header("Deep engine (skill-scanner)"));
715
+ console.log(fmt.divider());
716
+ const actionable = deep.findings.filter((f) => ["critical", "high", "medium"].includes(f.severity));
717
+ if (actionable.length === 0) {
718
+ console.log(fmt.success("No critical/high/medium findings"));
719
+ }
720
+ else {
721
+ console.log(fmt.warning(`${actionable.length} finding(s) (max severity: ${deep.maxSeverity})`));
722
+ for (const f of actionable.slice(0, 10)) {
723
+ const loc = f.line ? ` (line ${f.line})` : "";
724
+ console.log(` • [${f.severity.toUpperCase()}] ${f.category}: ${f.title}${loc}`);
725
+ }
726
+ if (actionable.length > 10) {
727
+ console.log(` ... and ${actionable.length - 10} more`);
728
+ }
729
+ }
730
+ if (deep.analyzersUsed.length > 0) {
731
+ console.log(` analyzers: ${deep.analyzersUsed.join(", ")} (offline only)`);
732
+ }
733
+ console.log();
734
+ }
735
+ /**
736
+ * Run the opt-in deep engine on a single resolved skill path and fold its
737
+ * results into `report` (adds `deepScan`, escalates severity by actionable
738
+ * findings). Returns an error string when the engine failed (caller exits 2).
739
+ */
740
+ async function attachDeepScan(report, scanPath, scanner) {
741
+ const dr = await scanner.scanPath(scanPath);
742
+ if (dr.error)
743
+ return { error: dr.error };
744
+ report.deepScan = {
745
+ engine: "skill-scanner",
746
+ maxSeverity: dr.maxSeverity,
747
+ analyzersUsed: dr.analyzersUsed,
748
+ findings: dr.findings,
749
+ };
750
+ const tier = deepSeverityTier(dr);
751
+ if (_SEVERITY_ORDER_LOCAL.indexOf(tier) >
752
+ _SEVERITY_ORDER_LOCAL.indexOf(report.summary.severity)) {
753
+ report.summary.severity = tier;
754
+ }
755
+ const actionable = deepActionableCount(dr);
756
+ if (actionable > 0) {
757
+ report.summary.findings += actionable;
758
+ report.summary.reasons.push(`deep engine: ${actionable} actionable finding(s)`);
759
+ }
760
+ return {};
761
+ }
762
+ /** After deep scans escalate per-skill severities, recompute the multi summary. */
763
+ function recomputeMultiSummary(report) {
764
+ const counts = {
765
+ clean: 0,
766
+ low: 0,
767
+ medium: 0,
768
+ high: 0,
769
+ critical: 0,
770
+ };
771
+ let worst = "clean";
772
+ let findings = 0;
773
+ for (const entry of report.skills) {
774
+ counts[entry.report.summary.severity] += 1;
775
+ findings += entry.report.summary.findings;
776
+ if (_SEVERITY_ORDER_LOCAL.indexOf(entry.report.summary.severity) >
777
+ _SEVERITY_ORDER_LOCAL.indexOf(worst)) {
778
+ worst = entry.report.summary.severity;
779
+ }
780
+ }
781
+ report.summary.severityCounts = counts;
782
+ report.summary.findings = findings;
783
+ report.summary.worst = worst;
784
+ }
785
+ export async function runSkillReview(input, opts) {
709
786
  let resolved = input;
710
787
  let kind;
711
788
  let cleanup = null;
@@ -777,6 +854,33 @@ export function runSkillReview(input, opts) {
777
854
  else {
778
855
  report = buildReport(input, resolved, kind, source);
779
856
  }
857
+ // Optional DEEP engine (skill-scanner) — opt-in via --deep / --engine.
858
+ // Offline analyzers only; scans each resolved skill on disk. Availability
859
+ // is ensured by the caller (interactive install-offer); this is a safety net.
860
+ if (opts.deep) {
861
+ const scanner = new SkillScanner();
862
+ if (!scanner.isAvailable()) {
863
+ console.error(INSTALL_HINT);
864
+ return { report, exitCode: 2 };
865
+ }
866
+ if ("skills" in report) {
867
+ for (const entry of report.skills) {
868
+ const { error } = await attachDeepScan(entry.report, entry.report.target.resolvedPath, scanner);
869
+ if (error) {
870
+ console.error(fmt.error(`deep scan failed: ${error}`));
871
+ return { report, exitCode: 2 };
872
+ }
873
+ }
874
+ recomputeMultiSummary(report);
875
+ }
876
+ else {
877
+ const { error } = await attachDeepScan(report, resolved, scanner);
878
+ if (error) {
879
+ console.error(fmt.error(`deep scan failed: ${error}`));
880
+ return { report, exitCode: 2 };
881
+ }
882
+ }
883
+ }
780
884
  const format = opts.json ? "json" : opts.format ?? "text";
781
885
  if (format === "json") {
782
886
  console.log(JSON.stringify(report, null, 2));
@@ -787,6 +891,7 @@ export function runSkillReview(input, opts) {
787
891
  }
788
892
  else {
789
893
  renderText(report);
894
+ renderDeepText(report);
790
895
  }
791
896
  }
792
897
  const sev = "skills" in report ? report.summary.worst : report.summary.severity;
@@ -803,7 +908,7 @@ export function runSkillReview(input, opts) {
803
908
  }
804
909
  }
805
910
  const SEVERITY_ORDER = ["clean", "low", "medium", "high", "critical"];
806
- export function runSkillReviewInstalled(opts) {
911
+ export async function runSkillReviewInstalled(opts) {
807
912
  let filter;
808
913
  if (opts.agent) {
809
914
  const a = opts.agent;
@@ -824,8 +929,18 @@ export function runSkillReviewInstalled(opts) {
824
929
  const platformCounts = {};
825
930
  let findings = 0;
826
931
  let worst = "clean";
932
+ // Deep engine availability is ensured once by the caller; this is a safety net.
933
+ const deepScanner = opts.deep ? new SkillScanner() : null;
934
+ if (opts.deep && !deepScanner.isAvailable()) {
935
+ throw new Error(INSTALL_HINT);
936
+ }
827
937
  for (const d of discovered) {
828
938
  const report = buildReport(d.path, d.path, "file");
939
+ if (deepScanner) {
940
+ const { error } = await attachDeepScan(report, d.path, deepScanner);
941
+ if (error)
942
+ throw new Error(`deep scan failed for ${d.path}: ${error}`);
943
+ }
829
944
  installations.push({
830
945
  platform: d.platform,
831
946
  skill: d.name,
@@ -931,7 +1046,24 @@ export function createReviewCommand() {
931
1046
  .option("--summary", "Print a terse human-readable table instead of JSON (only with --installed)")
932
1047
  .option("--cache-ttl <duration>", "TTL for the persistent skill-cache resolution entries (e.g. 24h, 30m, 3600s). Default: 24h.", "24h")
933
1048
  .option("--no-cache", "Bypass the persistent skill-cache; fetch fresh and skip writes.")
934
- .action((input, opts) => {
1049
+ .option("--deep", "Also run the optional DEEP engine (Cisco AI Defense skill-scanner): prompt injection, taint/dataflow, YARA, .pyc integrity. Offline analyzers only. Offers to install the engine if missing.")
1050
+ .option("--engine <engine>", "Deep engine selector. 'skill-scanner' is equivalent to --deep.")
1051
+ .action(async (input, opts) => {
1052
+ // Resolve / validate the deep engine selector up front.
1053
+ const wantDeep = !!opts.deep || opts.engine === "skill-scanner";
1054
+ if (opts.engine != null && opts.engine !== "skill-scanner") {
1055
+ console.error(fmt.error(`unknown --engine '${opts.engine}' (supported: skill-scanner)`));
1056
+ process.exit(2);
1057
+ }
1058
+ // If --deep is requested, make it easy: ensure the engine is present,
1059
+ // offering to install it interactively. Done once for all skills.
1060
+ if (wantDeep) {
1061
+ const scanner = await ensureSkillScanner({ json: !!opts.json || opts.format === "json" });
1062
+ if (!scanner) {
1063
+ console.error(INSTALL_HINT);
1064
+ process.exit(2);
1065
+ }
1066
+ }
935
1067
  if (opts.installed) {
936
1068
  if (input) {
937
1069
  console.error(fmt.error("Cannot pass both <path-or-url> and --installed. Use one."));
@@ -939,7 +1071,7 @@ export function createReviewCommand() {
939
1071
  }
940
1072
  let result;
941
1073
  try {
942
- result = runSkillReviewInstalled({ agent: opts.agent });
1074
+ result = await runSkillReviewInstalled({ agent: opts.agent, deep: wantDeep });
943
1075
  }
944
1076
  catch (e) {
945
1077
  console.error(fmt.error(`${e instanceof Error ? e.message : String(e)}`));
@@ -965,8 +1097,9 @@ export function createReviewCommand() {
965
1097
  console.error(fmt.error(e instanceof Error ? e.message : String(e)));
966
1098
  process.exit(2);
967
1099
  }
968
- const { exitCode } = runSkillReview(input, {
1100
+ const { exitCode } = await runSkillReview(input, {
969
1101
  ...opts,
1102
+ deep: wantDeep,
970
1103
  noCache: opts.cache === false,
971
1104
  cacheTtlMs: ttlMs,
972
1105
  });
@@ -5,6 +5,38 @@ import { loadPolicy } from "./policy-loader.js";
5
5
  const VALID_RISK_LEVELS = new Set(["minimal", "moderate", "aggressive"]);
6
6
  const VALID_COMMAND_MODES = new Set(["allow-all", "approve-dangerous", "deny-list"]);
7
7
  const VALID_LOG_LEVELS = new Set(["debug", "info", "warn", "error"]);
8
+ // Config keys whose *leaf name* names a bearer credential. Values under these
9
+ // keys must be masked before the config is shown to a human or handed to an MCP
10
+ // client — never logged or echoed in cleartext.
11
+ const SECRET_CONFIG_KEY_RE = /(api_?key|token|secret|password|passwd|credential)/i;
12
+ export function isSecretConfigKey(leafKey) {
13
+ return SECRET_CONFIG_KEY_RE.test(leafKey);
14
+ }
15
+ /** Mask a credential value, keeping a 4-char prefix for recognizability. */
16
+ export function maskSecretValue(value) {
17
+ if (typeof value !== "string" || value.length === 0)
18
+ return "****";
19
+ return value.length <= 4 ? "****" : `${value.slice(0, 4)}****`;
20
+ }
21
+ /**
22
+ * Deep-clone a config value, masking any string whose KEY name looks like a
23
+ * credential. Pure — never mutates the input (so the stored config is unchanged).
24
+ */
25
+ export function redactConfigSecrets(value) {
26
+ if (Array.isArray(value)) {
27
+ return value.map((v) => redactConfigSecrets(v));
28
+ }
29
+ if (value && typeof value === "object") {
30
+ const out = {};
31
+ for (const [k, v] of Object.entries(value)) {
32
+ out[k] = isSecretConfigKey(k) && typeof v === "string"
33
+ ? maskSecretValue(v)
34
+ : redactConfigSecrets(v);
35
+ }
36
+ return out;
37
+ }
38
+ return value;
39
+ }
8
40
  /**
9
41
  * Validate a parsed config JSON object, warning and falling back to defaults for invalid fields.
10
42
  */
@@ -128,13 +160,20 @@ export class ConfigManager {
128
160
  * Save config to disk
129
161
  */
130
162
  save(config) {
131
- // Ensure directory exists
163
+ // Ensure directory exists (0700 — the dir can hold credentials/audit log).
132
164
  const dir = path.dirname(this.configPath);
133
165
  if (!fs.existsSync(dir)) {
134
- fs.mkdirSync(dir, { recursive: true });
166
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
167
+ }
168
+ // Write config 0600 — it may hold a backend API key. writeFileSync's `mode`
169
+ // only applies when the file is *created*, so chmod existing files too.
170
+ fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 0o600 });
171
+ try {
172
+ fs.chmodSync(this.configPath, 0o600);
173
+ }
174
+ catch {
175
+ // Best effort — chmod is a no-op/throws on some platforms (e.g. Windows).
135
176
  }
136
- // Write config
137
- fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), "utf-8");
138
177
  }
139
178
  /**
140
179
  * Update specific config values
@@ -0,0 +1,23 @@
1
+ import path from "path";
2
+ import { RegexScanner } from "./regex-scanner.js";
3
+ /**
4
+ * Scan only added/modified lines from a parsed git diff (+ side).
5
+ * Uses the patterns engine — git line scope is incompatible with betterleaks'
6
+ * whole-file `dir` scan (same as the PreToolUse staged hook).
7
+ */
8
+ export function scanAddedDiffLines(addedLines, repoRoot, customPatterns) {
9
+ if (addedLines.length === 0)
10
+ return [];
11
+ const scanner = new RegexScanner(customPatterns);
12
+ const byFile = new Map();
13
+ for (const { file, line, text } of addedLines) {
14
+ const absPath = path.resolve(repoRoot, file);
15
+ const matches = scanner.scanLine(text, line);
16
+ if (matches.length === 0)
17
+ continue;
18
+ const existing = byFile.get(absPath) ?? [];
19
+ existing.push(...matches);
20
+ byFile.set(absPath, existing);
21
+ }
22
+ return [...byFile.entries()].map(([file, matches]) => ({ file, matches }));
23
+ }
@@ -92,6 +92,15 @@ export class RegexScanner {
92
92
  scanText(text) {
93
93
  return this.engine.scan(text);
94
94
  }
95
+ /**
96
+ * Scan a single line at a known file line number (git diff + side).
97
+ */
98
+ scanLine(text, lineNumber) {
99
+ return this.engine.scanWithPosition(text).map((m) => ({
100
+ ...m,
101
+ line: lineNumber,
102
+ }));
103
+ }
95
104
  /**
96
105
  * Redact secrets from text
97
106
  */