@rafter-security/cli 0.7.7 → 0.8.0

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.
Files changed (39) hide show
  1. package/README.md +27 -681
  2. package/dist/commands/agent/baseline.js +15 -15
  3. package/dist/commands/agent/components.js +282 -138
  4. package/dist/commands/agent/index.js +2 -2
  5. package/dist/commands/agent/init.js +564 -174
  6. package/dist/commands/agent/scan.js +76 -47
  7. package/dist/commands/agent/status.js +19 -10
  8. package/dist/commands/agent/update-betterleaks.js +39 -0
  9. package/dist/commands/agent/verify.js +230 -29
  10. package/dist/commands/brief.js +13 -45
  11. package/dist/commands/completion.js +15 -15
  12. package/dist/commands/issues/from-scan.js +6 -3
  13. package/dist/commands/mcp/server.js +11 -11
  14. package/dist/core/config-manager.js +6 -0
  15. package/dist/core/custom-patterns.js +86 -4
  16. package/dist/core/policy-loader.js +60 -1
  17. package/dist/scanners/{gitleaks.js → betterleaks.js} +49 -61
  18. package/dist/scanners/regex-scanner.js +4 -5
  19. package/dist/scanners/secret-patterns.js +1 -1
  20. package/dist/utils/binary-manager.js +205 -109
  21. package/dist/utils/skill-manager.js +96 -16
  22. package/package.json +1 -1
  23. package/resources/agents/rafter.md +81 -0
  24. package/resources/continue-rules/rafter-code-review.md +15 -0
  25. package/resources/continue-rules/rafter-secure-design.md +15 -0
  26. package/resources/continue-rules/rafter-skill-review.md +15 -0
  27. package/resources/continue-rules/rafter.md +16 -0
  28. package/resources/cursor-rules/rafter-code-review.mdc +14 -0
  29. package/resources/cursor-rules/rafter-secure-design.mdc +14 -0
  30. package/resources/cursor-rules/rafter-skill-review.mdc +14 -0
  31. package/resources/cursor-rules/rafter.mdc +15 -0
  32. package/resources/rafter-security-skill.md +18 -10
  33. package/resources/skills/rafter/SKILL.md +1 -1
  34. package/resources/skills/rafter/docs/cli-reference.md +5 -5
  35. package/resources/windsurf-rules/rafter-code-review.md +14 -0
  36. package/resources/windsurf-rules/rafter-secure-design.md +14 -0
  37. package/resources/windsurf-rules/rafter-skill-review.md +14 -0
  38. package/resources/windsurf-rules/rafter.md +15 -0
  39. package/dist/commands/agent/update-gitleaks.js +0 -40
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Load custom secret patterns from ~/.rafter/patterns/
3
- * and suppression rules from .rafterignore.
3
+ * and suppression rules from .rafterignore + .rafter.yml ignore section.
4
4
  */
5
5
  import fs from "fs";
6
6
  import path from "path";
@@ -119,12 +119,13 @@ export function loadSuppressions(projectRoot = process.cwd()) {
119
119
  continue;
120
120
  const colonIdx = line.indexOf(":");
121
121
  if (colonIdx === -1) {
122
- suppressions.push({ pathGlob: line });
122
+ suppressions.push({ pathGlob: line, source: ".rafterignore" });
123
123
  }
124
124
  else {
125
125
  suppressions.push({
126
126
  pathGlob: line.slice(0, colonIdx).trim(),
127
127
  patternName: line.slice(colonIdx + 1).trim() || undefined,
128
+ source: ".rafterignore",
128
129
  });
129
130
  }
130
131
  }
@@ -134,6 +135,79 @@ export function loadSuppressions(projectRoot = process.cwd()) {
134
135
  }
135
136
  return suppressions;
136
137
  }
138
+ /**
139
+ * Convert .rafter.yml ignore rules into the flat Suppression list used at scan time.
140
+ * Each entry's path globs cross-product with its rule names.
141
+ */
142
+ export function policyIgnoreToSuppressions(rules) {
143
+ if (!rules || rules.length === 0)
144
+ return [];
145
+ const out = [];
146
+ for (const rule of rules) {
147
+ if (!Array.isArray(rule.paths) || rule.paths.length === 0)
148
+ continue;
149
+ const ruleNames = Array.isArray(rule.rules) && rule.rules.length > 0 ? rule.rules : [undefined];
150
+ for (const pathGlob of rule.paths) {
151
+ for (const ruleName of ruleNames) {
152
+ out.push({
153
+ pathGlob,
154
+ patternName: ruleName,
155
+ reason: rule.reason,
156
+ source: ".rafter.yml",
157
+ });
158
+ }
159
+ }
160
+ }
161
+ return out;
162
+ }
163
+ /**
164
+ * Find the first matching suppression for a finding, or null. First-match wins so
165
+ * users can put more specific entries earlier and rely on stable precedence.
166
+ */
167
+ export function findSuppression(filePath, patternName, suppressions) {
168
+ for (const s of suppressions) {
169
+ if (matchGlob(s.pathGlob, filePath)) {
170
+ if (!s.patternName || s.patternName.toLowerCase() === patternName.toLowerCase()) {
171
+ return s;
172
+ }
173
+ }
174
+ }
175
+ return null;
176
+ }
177
+ /**
178
+ * Split scan results into kept matches and structured suppressed findings.
179
+ * Used by the scan command for engine-agnostic suppression.
180
+ */
181
+ export function applySuppressions(results, suppressions) {
182
+ if (suppressions.length === 0)
183
+ return { results, suppressed: [] };
184
+ const suppressed = [];
185
+ const filtered = [];
186
+ for (const r of results) {
187
+ const kept = [];
188
+ for (const m of r.matches) {
189
+ const hit = findSuppression(r.file, m.pattern.name, suppressions);
190
+ if (hit) {
191
+ suppressed.push({
192
+ file: r.file,
193
+ line: m.line ?? null,
194
+ column: m.column ?? null,
195
+ rule: m.pattern.name,
196
+ severity: m.pattern.severity,
197
+ reason: hit.reason ?? null,
198
+ source: hit.source ?? ".rafterignore",
199
+ });
200
+ }
201
+ else {
202
+ kept.push(m);
203
+ }
204
+ }
205
+ if (kept.length > 0) {
206
+ filtered.push({ ...r, matches: kept });
207
+ }
208
+ }
209
+ return { results: filtered, suppressed };
210
+ }
137
211
  /**
138
212
  * Returns true if a finding should be suppressed.
139
213
  */
@@ -151,10 +225,18 @@ export function isSuppressed(filePath, patternName, suppressions) {
151
225
  * Match a file path against a glob pattern using minimatch.
152
226
  *
153
227
  * Uses `matchBase` so bare patterns like "*.env" match against the basename
154
- * (e.g. "config/.env"), and `dot` so dotfiles are included.
228
+ * (e.g. "config/.env"), and `dot` so dotfiles are included. Also tries
229
+ * matching the glob against any suffix of the path so that relative globs
230
+ * like `tests/fixtures/**` match absolute paths under any project root.
155
231
  */
156
232
  function matchGlob(glob, filePath) {
157
233
  const g = glob.replace(/\\/g, "/");
158
234
  const f = filePath.replace(/\\/g, "/");
159
- return minimatch(f, g, { dot: true, matchBase: true });
235
+ if (minimatch(f, g, { dot: true, matchBase: true }))
236
+ return true;
237
+ // Auto-anchor relative globs to "anywhere in the path" so that `tests/**`
238
+ // matches `/abs/project/tests/foo`. Skip if the user already anchored.
239
+ if (g.startsWith("/") || g.startsWith("**/") || g.startsWith("**"))
240
+ return false;
241
+ return minimatch(f, "**/" + g, { dot: true });
160
242
  }
@@ -76,6 +76,31 @@ function mapPolicy(raw) {
76
76
  }));
77
77
  }
78
78
  }
79
+ if (Array.isArray(raw.ignore)) {
80
+ const rules = [];
81
+ for (const entry of raw.ignore) {
82
+ if (!entry || typeof entry !== "object") {
83
+ console.error(`Warning: skipping malformed ignore entry — must be an object with paths.`);
84
+ continue;
85
+ }
86
+ const paths = entry.paths;
87
+ if (!Array.isArray(paths) || paths.length === 0) {
88
+ console.error(`Warning: skipping ignore entry — "paths" must be a non-empty array of strings.`);
89
+ continue;
90
+ }
91
+ const rule = { paths: paths.map((p) => String(p)) };
92
+ if (Array.isArray(entry.rules)) {
93
+ rule.rules = entry.rules.map((r) => String(r));
94
+ }
95
+ if (typeof entry.reason === "string" && entry.reason) {
96
+ rule.reason = entry.reason;
97
+ }
98
+ rules.push(rule);
99
+ }
100
+ if (rules.length > 0) {
101
+ policy.ignore = rules;
102
+ }
103
+ }
79
104
  if (raw.audit && typeof raw.audit === "object") {
80
105
  policy.audit = {};
81
106
  if (raw.audit.retention_days != null) {
@@ -153,7 +178,7 @@ function deriveDocId(source, kind) {
153
178
  const crypto = require("crypto");
154
179
  return crypto.createHash("sha256").update(source).digest("hex").slice(0, 8);
155
180
  }
156
- const VALID_TOP_LEVEL_KEYS = new Set(["version", "risk_level", "command_policy", "scan", "audit", "docs"]);
181
+ const VALID_TOP_LEVEL_KEYS = new Set(["version", "risk_level", "command_policy", "scan", "ignore", "audit", "docs"]);
157
182
  const VALID_RISK_LEVELS = new Set(["minimal", "moderate", "aggressive"]);
158
183
  const VALID_COMMAND_MODES = new Set(["allow-all", "approve-dangerous", "deny-list"]);
159
184
  const VALID_LOG_LEVELS = new Set(["debug", "info", "warn", "error"]);
@@ -232,6 +257,40 @@ function validatePolicy(policy, raw) {
232
257
  }
233
258
  }
234
259
  }
260
+ if (policy.ignore !== undefined) {
261
+ if (!Array.isArray(policy.ignore)) {
262
+ console.error(`Warning: "ignore" must be an array — ignoring.`);
263
+ delete policy.ignore;
264
+ }
265
+ else {
266
+ const valid = [];
267
+ for (const entry of policy.ignore) {
268
+ if (!entry || typeof entry !== "object") {
269
+ console.error(`Warning: skipping malformed ignore entry — must be an object with paths.`);
270
+ continue;
271
+ }
272
+ if (!Array.isArray(entry.paths) || entry.paths.length === 0 || !entry.paths.every((p) => typeof p === "string" && p)) {
273
+ console.error(`Warning: skipping ignore entry — "paths" must be a non-empty array of strings.`);
274
+ continue;
275
+ }
276
+ if (entry.rules !== undefined && (!Array.isArray(entry.rules) || !entry.rules.every((r) => typeof r === "string"))) {
277
+ console.error(`Warning: skipping ignore entry — "rules" must be an array of strings.`);
278
+ continue;
279
+ }
280
+ if (entry.reason !== undefined && typeof entry.reason !== "string") {
281
+ console.error(`Warning: ignore entry "reason" must be a string — dropping reason.`);
282
+ delete entry.reason;
283
+ }
284
+ valid.push(entry);
285
+ }
286
+ if (valid.length > 0) {
287
+ policy.ignore = valid;
288
+ }
289
+ else {
290
+ delete policy.ignore;
291
+ }
292
+ }
293
+ }
235
294
  if (policy.audit) {
236
295
  if (policy.audit.retentionDays !== undefined && (typeof policy.audit.retentionDays !== "number" || isNaN(policy.audit.retentionDays))) {
237
296
  console.error(`Warning: "audit.retention_days" must be a number — ignoring.`);
@@ -6,46 +6,64 @@ import fs from "fs";
6
6
  import os from "os";
7
7
  import path from "path";
8
8
  const execFileAsync = promisify(execFile);
9
- export class GitleaksScanner {
9
+ export class BetterleaksScanner {
10
10
  constructor() {
11
+ this.resolvedPath = null;
11
12
  this.binaryManager = new BinaryManager();
12
13
  }
13
14
  /**
14
- * Check if Gitleaks is available
15
+ * Resolve the betterleaks binary to use. Prefer the rafter-managed binary at
16
+ * ~/.rafter/bin/betterleaks; otherwise fall back to one on PATH (e.g. Homebrew).
17
+ * Cached after first lookup.
15
18
  */
16
- async isAvailable() {
17
- if (!this.binaryManager.isGitleaksInstalled()) {
18
- return false;
19
+ async resolveBinary() {
20
+ if (this.resolvedPath !== null)
21
+ return this.resolvedPath || null;
22
+ if (this.binaryManager.isBetterleaksInstalled()) {
23
+ const managed = this.binaryManager.getBetterleaksPath();
24
+ if (await this.binaryManager.verifyBetterleaks()) {
25
+ this.resolvedPath = managed;
26
+ return managed;
27
+ }
19
28
  }
20
- return await this.binaryManager.verifyGitleaks();
29
+ const onPath = this.binaryManager.findBetterleaksOnPath();
30
+ if (onPath) {
31
+ const ok = await this.binaryManager.verifyBetterleaksVerbose(onPath);
32
+ if (ok.ok) {
33
+ this.resolvedPath = onPath;
34
+ return onPath;
35
+ }
36
+ }
37
+ this.resolvedPath = "";
38
+ return null;
39
+ }
40
+ async isAvailable() {
41
+ return (await this.resolveBinary()) !== null;
21
42
  }
22
43
  /**
23
- * Scan a file with Gitleaks
44
+ * Scan a single file with Betterleaks (uses `dir` subcommand on a single path).
24
45
  */
25
46
  async scanFile(filePath) {
26
- if (!await this.isAvailable()) {
27
- throw new Error("Gitleaks not available");
47
+ const blPath = await this.resolveBinary();
48
+ if (!blPath) {
49
+ throw new Error("Betterleaks not available");
28
50
  }
29
- const gitleaksPath = this.binaryManager.getGitleaksPath();
30
- const tmpReport = path.join(os.tmpdir(), `gitleaks-${Date.now()}-${randomBytes(6).toString("hex")}.json`);
51
+ const tmpReport = path.join(os.tmpdir(), `betterleaks-${Date.now()}-${randomBytes(6).toString("hex")}.json`);
31
52
  try {
32
- // Run gitleaks detect on file
33
- await execFileAsync(gitleaksPath, ["detect", "--no-git", "-f", "json", "-r", tmpReport, "-s", filePath], { timeout: 30000 });
34
- // If no leaks found, gitleaks exits 0 with empty report
53
+ // `--` ensures a target path beginning with `-` isn't parsed as a flag by betterleaks.
54
+ await execFileAsync(blPath, ["dir", "-f", "json", "--report-path", tmpReport, "--", filePath], { timeout: 60000 });
35
55
  if (!fs.existsSync(tmpReport)) {
36
56
  return { file: filePath, matches: [] };
37
57
  }
38
58
  const results = this.parseResults(tmpReport);
39
- // Clean up report
40
59
  fs.unlinkSync(tmpReport);
41
- // Convert to our format
42
60
  return {
43
61
  file: filePath,
44
62
  matches: results.map(r => this.convertToPatternMatch(r))
45
63
  };
46
64
  }
47
65
  catch (e) {
48
- // Gitleaks exits with code 1 when leaks found — read report before cleanup
66
+ // Betterleaks exits with --exit-code (default 1) when leaks found — read report before cleanup
49
67
  if (e.code === 1 && fs.existsSync(tmpReport)) {
50
68
  const results = this.parseResults(tmpReport);
51
69
  fs.unlinkSync(tmpReport);
@@ -54,16 +72,12 @@ export class GitleaksScanner {
54
72
  matches: results.map(r => this.convertToPatternMatch(r))
55
73
  };
56
74
  }
57
- // Clean up report for non-leak errors
58
75
  if (fs.existsSync(tmpReport)) {
59
76
  fs.unlinkSync(tmpReport);
60
77
  }
61
- throw new Error(`Gitleaks scan failed: ${e.message}`);
78
+ throw new Error(`Betterleaks scan failed: ${e.message}`);
62
79
  }
63
80
  }
64
- /**
65
- * Scan multiple files
66
- */
67
81
  async scanFiles(filePaths) {
68
82
  const results = [];
69
83
  for (const filePath of filePaths) {
@@ -80,46 +94,37 @@ export class GitleaksScanner {
80
94
  return results;
81
95
  }
82
96
  /**
83
- * Scan a directory
97
+ * Scan a directory. With useGit=true, scans git history (`betterleaks git`);
98
+ * otherwise scans the filesystem (`betterleaks dir`).
84
99
  */
85
100
  async scanDirectory(dirPath, opts) {
86
- if (!await this.isAvailable()) {
87
- throw new Error("Gitleaks not available");
101
+ const blPath = await this.resolveBinary();
102
+ if (!blPath) {
103
+ throw new Error("Betterleaks not available");
88
104
  }
89
- const gitleaksPath = this.binaryManager.getGitleaksPath();
90
- const tmpReport = path.join(os.tmpdir(), `gitleaks-${Date.now()}-${randomBytes(6).toString("hex")}.json`);
105
+ const tmpReport = path.join(os.tmpdir(), `betterleaks-${Date.now()}-${randomBytes(6).toString("hex")}.json`);
106
+ const subcommand = opts?.useGit ? "git" : "dir";
91
107
  try {
92
- const args = ["detect", "-f", "json", "-r", tmpReport, "-s", dirPath];
93
- if (!opts?.useGit) {
94
- args.splice(1, 0, "--no-git");
95
- }
96
- // Run gitleaks detect on directory
97
- await execFileAsync(gitleaksPath, args, { timeout: 60000 });
98
- // No leaks found
108
+ // `--` ensures a target path beginning with `-` isn't parsed as a flag by betterleaks.
109
+ await execFileAsync(blPath, [subcommand, "-f", "json", "--report-path", tmpReport, "--", dirPath], { timeout: 60000 });
99
110
  if (!fs.existsSync(tmpReport)) {
100
111
  return [];
101
112
  }
102
113
  const results = this.parseResults(tmpReport);
103
114
  fs.unlinkSync(tmpReport);
104
- // Group by file
105
115
  return this.groupByFile(results);
106
116
  }
107
117
  catch (e) {
108
- // Clean up report
109
118
  if (fs.existsSync(tmpReport)) {
110
119
  const results = this.parseResults(tmpReport);
111
120
  fs.unlinkSync(tmpReport);
112
- // Gitleaks exits 1 when leaks found
113
121
  if (e.code === 1) {
114
122
  return this.groupByFile(results);
115
123
  }
116
124
  }
117
- throw new Error(`Gitleaks scan failed: ${e.message}`);
125
+ throw new Error(`Betterleaks scan failed: ${e.message}`);
118
126
  }
119
127
  }
120
- /**
121
- * Parse Gitleaks JSON report
122
- */
123
128
  parseResults(reportPath) {
124
129
  try {
125
130
  const content = fs.readFileSync(reportPath, "utf-8");
@@ -128,26 +133,22 @@ export class GitleaksScanner {
128
133
  }
129
134
  const parsed = JSON.parse(content);
130
135
  if (!Array.isArray(parsed)) {
131
- console.error("[rafter] Warning: Gitleaks output is not an array — possible version mismatch");
136
+ console.error("[rafter] Warning: Betterleaks output is not an array — possible version mismatch");
132
137
  return [];
133
138
  }
134
139
  return parsed;
135
140
  }
136
141
  catch (e) {
137
- console.error(`[rafter] Warning: Failed to parse Gitleaks report: ${e instanceof Error ? e.message : e}`);
142
+ console.error(`[rafter] Warning: Failed to parse Betterleaks report: ${e instanceof Error ? e.message : e}`);
138
143
  return [];
139
144
  }
140
145
  }
141
- /**
142
- * Convert Gitleaks result to our PatternMatch format
143
- */
144
146
  convertToPatternMatch(result) {
145
- // Map Gitleaks severity to our levels
146
147
  const severity = this.getSeverity(result.RuleID, result.Tags);
147
148
  return {
148
149
  pattern: {
149
150
  name: result.RuleID || result.Description,
150
- regex: "", // Gitleaks doesn't expose the regex
151
+ regex: "",
151
152
  severity,
152
153
  description: result.Description
153
154
  },
@@ -157,12 +158,8 @@ export class GitleaksScanner {
157
158
  redacted: this.redact(result.Secret || result.Match)
158
159
  };
159
160
  }
160
- /**
161
- * Determine severity from Gitleaks rule ID and tags
162
- */
163
161
  getSeverity(ruleID, tags) {
164
162
  const lowerID = ruleID.toLowerCase();
165
- // Critical: Private keys, passwords, database credentials, access tokens
166
163
  if (lowerID.includes("private-key") ||
167
164
  lowerID.includes("password") ||
168
165
  lowerID.includes("database") ||
@@ -172,24 +169,18 @@ export class GitleaksScanner {
172
169
  (tags.includes("key") && tags.includes("secret"))) {
173
170
  return "critical";
174
171
  }
175
- // High: API keys, generic tokens
176
172
  if (lowerID.includes("api-key") ||
177
173
  lowerID.includes("-token") ||
178
174
  lowerID.startsWith("token-") ||
179
175
  tags.includes("api")) {
180
176
  return "high";
181
177
  }
182
- // Medium: Generic secrets
183
178
  if (lowerID.includes("generic") ||
184
179
  tags.includes("generic")) {
185
180
  return "medium";
186
181
  }
187
- // Default to high for safety
188
182
  return "high";
189
183
  }
190
- /**
191
- * Redact a secret
192
- */
193
184
  redact(match) {
194
185
  if (match.length <= 8) {
195
186
  return "*".repeat(match.length);
@@ -200,9 +191,6 @@ export class GitleaksScanner {
200
191
  const middle = "*".repeat(match.length - (visibleChars * 2));
201
192
  return start + middle + end;
202
193
  }
203
- /**
204
- * Group results by file
205
- */
206
194
  groupByFile(results) {
207
195
  const grouped = new Map();
208
196
  for (const result of results) {
@@ -2,7 +2,7 @@ import fs from "fs";
2
2
  import path from "path";
3
3
  import { PatternEngine } from "../core/pattern-engine.js";
4
4
  import { DEFAULT_SECRET_PATTERNS } from "./secret-patterns.js";
5
- import { loadCustomPatterns, loadSuppressions, isSuppressed } from "../core/custom-patterns.js";
5
+ import { loadCustomPatterns } from "../core/custom-patterns.js";
6
6
  export class RegexScanner {
7
7
  constructor(customPatterns) {
8
8
  const patterns = [...DEFAULT_SECRET_PATTERNS, ...loadCustomPatterns()];
@@ -16,16 +16,15 @@ export class RegexScanner {
16
16
  }
17
17
  }
18
18
  this.engine = new PatternEngine(patterns);
19
- this.suppressions = loadSuppressions();
20
19
  }
21
20
  /**
22
- * Scan a single file for secrets
21
+ * Scan a single file for secrets. Suppression is applied at the scan
22
+ * command boundary (engine-agnostic), not here.
23
23
  */
24
24
  scanFile(filePath) {
25
25
  try {
26
26
  const content = fs.readFileSync(filePath, "utf-8");
27
- const raw = this.engine.scanWithPosition(content);
28
- const matches = raw.filter((m) => !isSuppressed(filePath, m.pattern.name, this.suppressions));
27
+ const matches = this.engine.scanWithPosition(content);
29
28
  return { file: filePath, matches };
30
29
  }
31
30
  catch (e) {
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Default secret detection patterns
3
- * Based on common secret formats and Gitleaks rules
3
+ * Based on common secret formats and Betterleaks rules
4
4
  */
5
5
  export const DEFAULT_SECRET_PATTERNS = [
6
6
  // AWS