@rafter-security/cli 0.8.3 → 0.8.5

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,21 +3,28 @@ import fs from "fs";
3
3
  import path from "path";
4
4
  import os from "os";
5
5
  import { execSync } from "child_process";
6
+ import { fileURLToPath } from "url";
6
7
  import { getRafterDir, getAuditLogPath, getBinDir } from "../../core/config-defaults.js";
7
8
  import { AuditLogger } from "../../core/audit-logger.js";
8
9
  import { ConfigManager } from "../../core/config-manager.js";
9
10
  import { BinaryManager } from "../../utils/binary-manager.js";
11
+ import { SkillManager } from "../../utils/skill-manager.js";
10
12
  export function createStatusCommand() {
11
13
  return new Command("status")
12
14
  .description("Show agent security status dashboard")
13
- .action(async () => {
15
+ .option("--json", "Output status as JSON")
16
+ .action(async (opts) => {
14
17
  const rafterDir = getRafterDir();
15
18
  const auditPath = getAuditLogPath();
16
19
  const home = os.homedir();
20
+ const configPath = path.join(rafterDir, "config.json");
21
+ if (opts.json) {
22
+ console.log(JSON.stringify(buildStatusJson(home, configPath, auditPath), null, 2));
23
+ return;
24
+ }
17
25
  console.log("Rafter Agent Status");
18
26
  console.log("=".repeat(50));
19
27
  // --- Config ---
20
- const configPath = path.join(rafterDir, "config.json");
21
28
  if (fs.existsSync(configPath)) {
22
29
  try {
23
30
  const cfg = new ConfigManager().load();
@@ -86,13 +93,21 @@ export function createStatusCommand() {
86
93
  console.log(`PreToolUse: ${pretoolOk ? "installed" : "not installed — run: rafter agent init --with-claude-code"}`);
87
94
  console.log(`PostToolUse: ${posttoolOk ? "installed" : "not installed — run: rafter agent init --with-claude-code"}`);
88
95
  // --- OpenClaw skill ---
89
- const skillPath = path.join(home, ".openclaw", "skills", "rafter-security.md");
90
- const openclawDir = path.join(home, ".openclaw");
91
- if (fs.existsSync(skillPath)) {
92
- console.log(`OpenClaw: skill installed (${skillPath})`);
96
+ // rf-zgwj moved the skill to the canonical ClawHub workspace path
97
+ // (~/.openclaw/workspace/skills/rafter-security/SKILL.md) and strips the
98
+ // legacy flat file. Detect via SkillManager so this matches `agent verify`
99
+ // and the installer — checking the legacy path here is a false negative.
100
+ const skillManager = new SkillManager();
101
+ if (skillManager.isRafterSkillInstalled()) {
102
+ console.log(`OpenClaw: skill installed (${skillManager.getRafterSkillPath()})`);
93
103
  }
94
- else if (fs.existsSync(openclawDir)) {
95
- console.log("OpenClaw: detected but skill missing — run: rafter agent init --with-openclaw");
104
+ else if (skillManager.isOpenClawInstalled()) {
105
+ if (skillManager.hasLegacyRafterSkill()) {
106
+ console.log(`OpenClaw: legacy skill at ${skillManager.getLegacyRafterSkillPath()} (not loaded) — run: rafter agent init --with-openclaw to migrate`);
107
+ }
108
+ else {
109
+ console.log("OpenClaw: detected but skill missing — run: rafter agent init --with-openclaw");
110
+ }
96
111
  }
97
112
  else {
98
113
  console.log("OpenClaw: not detected (optional)");
@@ -115,6 +130,7 @@ export function createStatusCommand() {
115
130
  { name: "Cursor", flag: "--with-cursor", configDir: path.join(home, ".cursor"), configFile: path.join(home, ".cursor", "mcp.json"), needle: "rafter" },
116
131
  { name: "Windsurf", flag: "--with-windsurf", configDir: path.join(home, ".codeium", "windsurf"), configFile: path.join(home, ".codeium", "windsurf", "mcp_config.json"), needle: "rafter" },
117
132
  { name: "Continue.dev", flag: "--with-continue", configDir: path.join(home, ".continue"), configFile: path.join(home, ".continue", "config.json"), needle: "rafter" },
133
+ { name: "Hermes", flag: "--with-hermes", configDir: path.join(home, ".hermes"), configFile: path.join(home, ".hermes", "config.yaml"), needle: "rafter" },
118
134
  ];
119
135
  for (const agent of mcpAgents) {
120
136
  const label = `${agent.name}:`.padEnd(14);
@@ -183,3 +199,109 @@ export function createStatusCommand() {
183
199
  console.log();
184
200
  });
185
201
  }
202
+ function buildStatusJson(home, configPath, auditPath) {
203
+ return {
204
+ installed: fs.existsSync(configPath),
205
+ version: getPkgVersion(),
206
+ agents_detected: detectAgents(home),
207
+ hooks_installed: detectGitHooks(home),
208
+ betterleaks_available: isBetterleaksAvailable(),
209
+ config_path: formatHomePath(configPath, home),
210
+ audit_log_path: formatHomePath(auditPath, home),
211
+ };
212
+ }
213
+ function detectAgents(home) {
214
+ const candidates = [
215
+ ["claude-code", path.join(home, ".claude")],
216
+ ["openclaw", path.join(home, ".openclaw")],
217
+ ["codex", path.join(home, ".codex")],
218
+ ["gemini", path.join(home, ".gemini")],
219
+ ["cursor", path.join(home, ".cursor")],
220
+ ["windsurf", path.join(home, ".codeium", "windsurf")],
221
+ ["continue", path.join(home, ".continue")],
222
+ ["aider", path.join(home, ".aider.conf.yml")],
223
+ ["hermes", path.join(home, ".hermes")],
224
+ ];
225
+ return candidates
226
+ .filter(([, p]) => fs.existsSync(p))
227
+ .map(([name]) => name);
228
+ }
229
+ function detectGitHooks(home) {
230
+ const hooks = new Set();
231
+ const specs = [
232
+ ["pre-commit", "Rafter Security Pre-Commit Hook"],
233
+ ["pre-push", "Rafter Security Pre-Push Hook"],
234
+ ];
235
+ for (const [hookName, marker] of specs) {
236
+ const globalHook = path.join(home, ".rafter", "git-hooks", hookName);
237
+ if (fileContains(globalHook, marker))
238
+ hooks.add(hookName);
239
+ }
240
+ try {
241
+ const gitDir = execSync("git rev-parse --git-dir", {
242
+ encoding: "utf-8",
243
+ stdio: ["pipe", "pipe", "ignore"],
244
+ timeout: 5000,
245
+ }).trim();
246
+ const hooksDir = path.resolve(gitDir, "hooks");
247
+ for (const [hookName, marker] of specs) {
248
+ if (fileContains(path.join(hooksDir, hookName), marker))
249
+ hooks.add(hookName);
250
+ }
251
+ }
252
+ catch {
253
+ // Not in a git repository, or git unavailable.
254
+ }
255
+ return [...hooks].sort();
256
+ }
257
+ function isBetterleaksAvailable() {
258
+ const exeExt = process.platform === "win32" ? ".exe" : "";
259
+ const localBetterleaks = path.join(getBinDir(), `betterleaks${exeExt}`);
260
+ try {
261
+ execSync("betterleaks version", {
262
+ timeout: 5000,
263
+ encoding: "utf-8",
264
+ stdio: ["pipe", "pipe", "ignore"],
265
+ });
266
+ return true;
267
+ }
268
+ catch {
269
+ if (fs.existsSync(localBetterleaks))
270
+ return true;
271
+ return Boolean(new BinaryManager().findLegacyGitleaks());
272
+ }
273
+ }
274
+ function fileContains(filePath, needle) {
275
+ try {
276
+ return fs.readFileSync(filePath, "utf-8").includes(needle);
277
+ }
278
+ catch {
279
+ return false;
280
+ }
281
+ }
282
+ function formatHomePath(filePath, home) {
283
+ const relative = path.relative(home, filePath);
284
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) {
285
+ return path.join("~", relative).replace(/\\/g, "/");
286
+ }
287
+ return filePath;
288
+ }
289
+ function getPkgVersion() {
290
+ try {
291
+ const __filename = fileURLToPath(import.meta.url);
292
+ let dir = path.dirname(__filename);
293
+ for (let i = 0; i < 6; i++) {
294
+ const candidate = path.join(dir, "package.json");
295
+ if (fs.existsSync(candidate)) {
296
+ const pkg = JSON.parse(fs.readFileSync(candidate, "utf-8"));
297
+ if (pkg.version)
298
+ return pkg.version;
299
+ }
300
+ dir = path.dirname(dir);
301
+ }
302
+ }
303
+ catch {
304
+ // fall through
305
+ }
306
+ return "unknown";
307
+ }
@@ -259,6 +259,34 @@ function checkAider() {
259
259
  }
260
260
  return { name, passed: true, detail: `RAFTER.md + read: entry in ${conf}` };
261
261
  }
262
+ function checkHermes() {
263
+ // Hermes uses ~/.hermes/config.yaml with a snake_case `mcp_servers:` block
264
+ // (MCP-only v0 — no hook surface confirmed yet; sable-gyw).
265
+ const name = "Hermes";
266
+ const homeDir = os.homedir();
267
+ const hermesDir = path.join(homeDir, ".hermes");
268
+ if (!fs.existsSync(hermesDir)) {
269
+ return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-hermes' to enable` };
270
+ }
271
+ const configPath = path.join(hermesDir, "config.yaml");
272
+ if (!fs.existsSync(configPath)) {
273
+ return { name, passed: false, optional: true, detail: `Config not found: ${configPath} — run 'rafter agent init --with-hermes'` };
274
+ }
275
+ try {
276
+ const loaded = yaml.load(fs.readFileSync(configPath, "utf-8"));
277
+ const servers = (loaded && typeof loaded === "object" && !Array.isArray(loaded))
278
+ ? loaded.mcp_servers
279
+ : undefined;
280
+ const hasRafterMcp = servers && typeof servers === "object" && servers.rafter != null;
281
+ if (!hasRafterMcp) {
282
+ return { name, passed: false, optional: true, detail: "Rafter MCP server not configured — run 'rafter agent init --with-hermes'" };
283
+ }
284
+ return { name, passed: true, detail: "MCP server configured" };
285
+ }
286
+ catch (e) {
287
+ return { name, passed: false, optional: true, detail: `Cannot read config: ${e}` };
288
+ }
289
+ }
262
290
  /**
263
291
  * Probe the Claude Code hook integration end-to-end (rf-65zg).
264
292
  *
@@ -349,6 +377,7 @@ export function createVerifyCommand() {
349
377
  checkWindsurf(),
350
378
  checkContinueDev(),
351
379
  checkAider(),
380
+ checkHermes(),
352
381
  ];
353
382
  if (opts.probe) {
354
383
  // Only Claude Code has a probe today (rf-65zg). Codex/Cursor/Gemini
@@ -2,7 +2,41 @@ import { Command } from "commander";
2
2
  import { CommandInterceptor } from "../../core/command-interceptor.js";
3
3
  import { RegexScanner } from "../../scanners/regex-scanner.js";
4
4
  import { AuditLogger } from "../../core/audit-logger.js";
5
+ import { ConfigManager } from "../../core/config-manager.js";
6
+ import { applySuppressions } from "../../core/custom-patterns.js";
7
+ import { collectSuppressions, applyExcludePaths } from "../agent/scan.js";
5
8
  import { execSync } from "child_process";
9
+ import fs from "fs";
10
+ import path from "path";
11
+ /**
12
+ * Load the policy-merged scan config + suppression list the same way scan.ts
13
+ * does, so hook decisions match `rafter secrets`. Policy discovery and
14
+ * `.rafterignore` loading key off `process.cwd()`; `cwd` lets tests point the
15
+ * lookup at a temp repo without a process-wide chdir leaking across tests.
16
+ */
17
+ function loadScanConfig(cwd = process.cwd()) {
18
+ const prev = process.cwd();
19
+ const restore = path.resolve(cwd) !== path.resolve(prev);
20
+ if (restore) {
21
+ try {
22
+ process.chdir(cwd);
23
+ }
24
+ catch { /* ignore — fall back to current cwd */ }
25
+ }
26
+ try {
27
+ const cfg = new ConfigManager().loadWithPolicy();
28
+ const scanCfg = cfg.agent?.scan;
29
+ return { scanCfg, suppressions: collectSuppressions(scanCfg?.ignore) };
30
+ }
31
+ finally {
32
+ if (restore) {
33
+ try {
34
+ process.chdir(prev);
35
+ }
36
+ catch { /* ignore */ }
37
+ }
38
+ }
39
+ }
6
40
  const RISK_LABELS = {
7
41
  critical: "CRITICAL", high: "HIGH", medium: "MEDIUM", low: "LOW",
8
42
  };
@@ -139,10 +173,15 @@ function evaluateBash(command) {
139
173
  if (trimmed.startsWith("git commit") || trimmed.startsWith("git push")) {
140
174
  const scanResult = scanStagedFiles();
141
175
  if (scanResult.secretsFound) {
142
- audit.logSecretDetected("staged files", `${scanResult.count} secret(s)`, "blocked");
176
+ // Audit per file so the log records WHICH file + pattern, not a bare count.
177
+ for (const r of scanResult.findings) {
178
+ const rel = path.relative(scanResult.repoRoot, r.file) || path.basename(r.file);
179
+ const names = [...new Set(r.matches.map((m) => m.pattern.name))];
180
+ audit.logSecretDetected(rel, names.join(", "), "blocked");
181
+ }
143
182
  return {
144
183
  decision: "deny",
145
- reason: `${scanResult.count} secret(s) detected in ${scanResult.files} staged file(s). Run 'rafter secrets --staged' for details.`,
184
+ reason: formatStagedSecretReason(scanResult),
146
185
  };
147
186
  }
148
187
  }
@@ -155,41 +194,112 @@ function evaluateWrite(toolInput) {
155
194
  if (!content) {
156
195
  return { decision: "allow" };
157
196
  }
158
- const scanner = new RegexScanner();
159
- if (scanner.hasSecrets(content)) {
160
- const matches = scanner.scanText(content);
161
- const names = [...new Set(matches.map(m => m.pattern.name))];
162
- const audit = new AuditLogger();
163
- audit.logSecretDetected(toolInput.file_path || "file content", names.join(", "), "blocked");
164
- return {
165
- decision: "deny",
166
- reason: `Secret detected in file content: ${names.join(", ")}`,
167
- };
197
+ // Route through the same config pipeline as scan.ts so the hook honors
198
+ // custom patterns, exclude_paths, and ignore rules from .rafter.yml.
199
+ const { scanCfg, suppressions } = loadScanConfig();
200
+ const scanner = new RegexScanner(scanCfg?.customPatterns);
201
+ const matches = scanner.scanText(content);
202
+ if (matches.length === 0) {
203
+ return { decision: "allow" };
168
204
  }
169
- return { decision: "allow" };
205
+ const filePath = toolInput.file_path || "file content";
206
+ // Apply exclude_paths + suppressions keyed on the target file path, so a
207
+ // write to a policy-excluded path is allowed (matching `rafter secrets`).
208
+ const afterExclude = applyExcludePaths([{ file: filePath, matches }], scanCfg?.excludePaths, process.cwd());
209
+ const { results: kept } = applySuppressions(afterExclude, suppressions);
210
+ const keptMatches = kept[0]?.matches ?? [];
211
+ if (keptMatches.length === 0) {
212
+ return { decision: "allow" };
213
+ }
214
+ const names = [...new Set(keptMatches.map((m) => m.pattern.name))];
215
+ const audit = new AuditLogger();
216
+ audit.logSecretDetected(filePath, names.join(", "), "blocked");
217
+ return {
218
+ decision: "deny",
219
+ reason: `Secret detected in ${filePath}: ${names.join(", ")}`,
220
+ };
170
221
  }
171
- function scanStagedFiles() {
222
+ /**
223
+ * Scan the git staged files for secrets, routed through the SAME config-aware
224
+ * pipeline as `rafter secrets --staged` (sable-55u). The hook previously ran
225
+ * RegexScanner directly on the raw staged list with no config — no custom
226
+ * patterns, no exclude_paths, no suppressions — so it phantom-blocked commits
227
+ * on findings the CLI would suppress. Now it loads `.rafter.yml`, applies
228
+ * exclude_paths and ignore rules, and reports which file + pattern matched.
229
+ *
230
+ * Still patterns-only (no betterleaks): the hook is on the hot path and must
231
+ * stay fast, and betterleaks version skew therefore cannot affect it.
232
+ *
233
+ * `cwd` exists for tests; production callers use the inherited process cwd.
234
+ */
235
+ export function scanStagedFiles(cwd = process.cwd()) {
236
+ const gitOpts = {
237
+ cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "ignore"],
238
+ };
239
+ const empty = {
240
+ secretsFound: false, count: 0, files: 0, findings: [], repoRoot: cwd,
241
+ };
172
242
  try {
173
- const stagedOutput = execSync("git diff --cached --name-only --diff-filter=ACM", {
174
- encoding: "utf-8",
175
- stdio: ["pipe", "pipe", "ignore"],
176
- }).trim();
243
+ const repoRoot = execSync("git rev-parse --show-toplevel", gitOpts).trim() || cwd;
244
+ const stagedOutput = execSync("git diff --cached --name-only --diff-filter=ACM", gitOpts).trim();
177
245
  if (!stagedOutput) {
178
- return { secretsFound: false, count: 0, files: 0 };
246
+ return { ...empty, repoRoot };
247
+ }
248
+ const stagedFiles = stagedOutput.split("\n").filter((f) => f.trim());
249
+ const { scanCfg, suppressions } = loadScanConfig(cwd);
250
+ const scanner = new RegexScanner(scanCfg?.customPatterns);
251
+ const raw = [];
252
+ for (const file of stagedFiles) {
253
+ const filePath = path.resolve(repoRoot, file);
254
+ if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile())
255
+ continue;
256
+ const r = scanner.scanFile(filePath);
257
+ if (r.matches.length > 0)
258
+ raw.push(r);
179
259
  }
180
- const stagedFiles = stagedOutput.split("\n").filter(f => f.trim());
181
- const scanner = new RegexScanner();
182
- const results = scanner.scanFiles(stagedFiles);
183
- const totalMatches = results.reduce((sum, r) => sum + r.matches.length, 0);
260
+ const afterExclude = applyExcludePaths(raw, scanCfg?.excludePaths, repoRoot);
261
+ const { results: kept } = applySuppressions(afterExclude, suppressions);
262
+ const count = kept.reduce((sum, r) => sum + r.matches.length, 0);
184
263
  return {
185
- secretsFound: results.length > 0,
186
- count: totalMatches,
187
- files: results.length,
264
+ secretsFound: kept.length > 0,
265
+ count,
266
+ files: kept.length,
267
+ findings: kept,
268
+ repoRoot,
188
269
  };
189
270
  }
190
271
  catch {
191
- return { secretsFound: false, count: 0, files: 0 };
272
+ return empty;
273
+ }
274
+ }
275
+ /** Cap on individual findings listed in a deny reason before truncating. */
276
+ const MAX_REASON_FINDINGS = 10;
277
+ /**
278
+ * Render a deny reason that names each offending file + pattern (+ line when
279
+ * known) instead of a bare count, so the agent knows what to fix without a
280
+ * second `rafter secrets` run. Truncates long lists.
281
+ */
282
+ export function formatStagedSecretReason(scan) {
283
+ const lines = [];
284
+ let shown = 0;
285
+ outer: for (const r of scan.findings) {
286
+ const rel = path.relative(scan.repoRoot, r.file) || path.basename(r.file);
287
+ for (const m of r.matches) {
288
+ if (shown >= MAX_REASON_FINDINGS) {
289
+ lines.push(` …and ${scan.count - shown} more`);
290
+ break outer;
291
+ }
292
+ const loc = m.line ? `:${m.line}` : "";
293
+ lines.push(` ${rel}${loc} — ${m.pattern.name}`);
294
+ shown++;
295
+ }
192
296
  }
297
+ return [
298
+ `${scan.count} secret(s) detected in ${scan.files} staged file(s):`,
299
+ ...lines,
300
+ "Hook scan is pattern-only (betterleaks version is irrelevant). " +
301
+ "Run 'rafter secrets --staged' for full detail, or add an exclude_paths/ignore rule to .rafter.yml if this is a false positive.",
302
+ ].join("\n");
193
303
  }
194
304
  const STDIN_TIMEOUT_MS = 5000;
195
305
  function readStdin() {
@@ -4,6 +4,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
4
4
  import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
5
5
  import { RegexScanner } from "../../scanners/regex-scanner.js";
6
6
  import { BetterleaksScanner } from "../../scanners/betterleaks.js";
7
+ import { unionScanResults } from "../../scanners/union.js";
7
8
  import { CommandInterceptor } from "../../core/command-interceptor.js";
8
9
  import { AuditLogger } from "../../core/audit-logger.js";
9
10
  import { ConfigManager } from "../../core/config-manager.js";
@@ -19,6 +20,8 @@ function formatScanResults(results) {
19
20
  severity: m.pattern.severity,
20
21
  line: m.line,
21
22
  redacted: m.redacted || m.match.slice(0, 4) + "****",
23
+ // sable-j85 — engine attribution, set only for both-engine (auto) scans.
24
+ ...(m.engines ? { engines: m.engines } : {}),
22
25
  })),
23
26
  }));
24
27
  }
@@ -118,31 +121,44 @@ export function createServer() {
118
121
  case "scan_secrets": {
119
122
  const scanPath = args?.path;
120
123
  const engine = args?.engine || "auto";
121
- if (engine === "betterleaks" || engine === "auto") {
124
+ const runPatterns = () => {
125
+ const scanner = new RegexScanner();
126
+ try {
127
+ return scanner.scanDirectory(scanPath);
128
+ }
129
+ catch {
130
+ return [scanner.scanFile(scanPath)];
131
+ }
132
+ };
133
+ if (engine === "betterleaks") {
134
+ const bl = new BetterleaksScanner();
135
+ if (!(await bl.isAvailable()))
136
+ return errorResult("Betterleaks not installed");
137
+ try {
138
+ return textResult(formatScanResults(await bl.scanDirectory(scanPath)));
139
+ }
140
+ catch {
141
+ return errorResult("Betterleaks scan failed");
142
+ }
143
+ }
144
+ if (engine === "auto") {
145
+ // sable-j85 — run BOTH engines and union, so a betterleaks miss
146
+ // (e.g. AWS access keys) is still caught by patterns. Degrades to
147
+ // patterns-only when betterleaks is unavailable or errors.
122
148
  const bl = new BetterleaksScanner();
123
149
  if (await bl.isAvailable()) {
124
150
  try {
125
- const results = await bl.scanDirectory(scanPath);
126
- return textResult(formatScanResults(results));
151
+ const blResults = await bl.scanDirectory(scanPath);
152
+ return textResult(formatScanResults(unionScanResults(blResults, runPatterns())));
127
153
  }
128
154
  catch {
129
- if (engine === "betterleaks")
130
- return errorResult("Betterleaks scan failed");
155
+ // betterleaks failed — fall through to patterns-only.
131
156
  }
132
157
  }
133
- else if (engine === "betterleaks") {
134
- return errorResult("Betterleaks not installed");
135
- }
136
- }
137
- const scanner = new RegexScanner();
138
- let results;
139
- try {
140
- results = scanner.scanDirectory(scanPath);
141
- }
142
- catch {
143
- results = [scanner.scanFile(scanPath)];
158
+ return textResult(formatScanResults(runPatterns()));
144
159
  }
145
- return textResult(formatScanResults(results));
160
+ // patterns (and any unrecognized value — the tool schema enums this).
161
+ return textResult(formatScanResults(runPatterns()));
146
162
  }
147
163
  case "evaluate_command": {
148
164
  const command = args?.command;
@@ -93,6 +93,10 @@ function validateConfig(raw) {
93
93
  return true;
94
94
  });
95
95
  }
96
+ if (scan.autoUpdateBetterleaks !== undefined && typeof scan.autoUpdateBetterleaks !== "boolean") {
97
+ console.error('Warning: config "agent.scan.autoUpdateBetterleaks" must be a boolean — using default.');
98
+ delete scan.autoUpdateBetterleaks;
99
+ }
96
100
  }
97
101
  }
98
102
  return raw;
@@ -253,6 +257,9 @@ export class ConfigManager {
253
257
  if (policy.scan.customPatterns) {
254
258
  config.agent.scan.customPatterns = policy.scan.customPatterns;
255
259
  }
260
+ if (policy.scan.autoUpdateBetterleaks !== undefined) {
261
+ config.agent.scan.autoUpdateBetterleaks = policy.scan.autoUpdateBetterleaks;
262
+ }
256
263
  }
257
264
  // Ignore rules — top-level policy key, applied per finding at scan time
258
265
  if (policy.ignore && config.agent) {
@@ -2,15 +2,36 @@ import fs from "fs";
2
2
  import path from "path";
3
3
  import { execSync } from "child_process";
4
4
  import yaml from "js-yaml";
5
- const POLICY_FILENAMES = [".rafter.yml", ".rafter.yaml"];
6
5
  /**
7
- * Find a policy file by walking from cwd up to git root
6
+ * Policy file candidates, in precedence order.
7
+ *
8
+ * sable-c1c — the cloud scanner (rafter-backend) reads `.rafter/config.yml`
9
+ * (subdir + `config.yml`), while the CLI canonical is `.rafter.yml`. To
10
+ * unbreak customers writing either shape, the CLI now reads both
11
+ * indefinitely. Precedence: canonical dotfile first; backend file is the
12
+ * fallback. If both are present, the dotfile wins (canonical).
13
+ *
14
+ * Schema compatibility is handled separately in `mapPolicy` — top-level
15
+ * `exclude_paths` / `custom_patterns` (backend flat shape) is accepted
16
+ * alongside `scan.exclude_paths` / `scan.custom_patterns` (CLI nested).
17
+ */
18
+ const POLICY_FILE_CANDIDATES = [
19
+ ".rafter.yml",
20
+ ".rafter.yaml",
21
+ path.join(".rafter", "config.yml"),
22
+ path.join(".rafter", "config.yaml"),
23
+ ];
24
+ /**
25
+ * Find a policy file by walking from cwd up to git root.
26
+ *
27
+ * For each directory, check candidates in precedence order; the first hit
28
+ * wins. The walk only ascends — siblings are not considered.
8
29
  */
9
30
  export function findPolicyFile() {
10
31
  let dir = process.cwd();
11
32
  const root = getGitRoot() || path.parse(dir).root;
12
33
  while (true) {
13
- for (const filename of POLICY_FILENAMES) {
34
+ for (const filename of POLICY_FILE_CANDIDATES) {
14
35
  const candidate = path.join(dir, filename);
15
36
  if (fs.existsSync(candidate)) {
16
37
  return candidate;
@@ -75,6 +96,25 @@ function mapPolicy(raw) {
75
96
  severity: p.severity || "high",
76
97
  }));
77
98
  }
99
+ if (typeof raw.scan.auto_update_betterleaks === "boolean") {
100
+ policy.scan.autoUpdateBetterleaks = raw.scan.auto_update_betterleaks;
101
+ }
102
+ }
103
+ // sable-c1c — backend flat-shape compat. rafter-backend reads
104
+ // exclude_paths / custom_patterns at the top level (no `scan:` nesting),
105
+ // so customers writing the backend shape get the same behavior locally.
106
+ // Nested form takes precedence if both are present in the same file.
107
+ if (!policy.scan?.excludePaths && Array.isArray(raw.exclude_paths)) {
108
+ policy.scan = policy.scan || {};
109
+ policy.scan.excludePaths = raw.exclude_paths;
110
+ }
111
+ if (!policy.scan?.customPatterns && Array.isArray(raw.custom_patterns)) {
112
+ policy.scan = policy.scan || {};
113
+ policy.scan.customPatterns = raw.custom_patterns.map((p) => ({
114
+ name: p.name,
115
+ regex: p.regex,
116
+ severity: p.severity || "high",
117
+ }));
78
118
  }
79
119
  if (Array.isArray(raw.ignore)) {
80
120
  const rules = [];
@@ -178,7 +218,11 @@ function deriveDocId(source, kind) {
178
218
  const crypto = require("crypto");
179
219
  return crypto.createHash("sha256").update(source).digest("hex").slice(0, 8);
180
220
  }
181
- const VALID_TOP_LEVEL_KEYS = new Set(["version", "risk_level", "command_policy", "scan", "ignore", "audit", "docs"]);
221
+ const VALID_TOP_LEVEL_KEYS = new Set([
222
+ "version", "risk_level", "command_policy", "scan", "ignore", "audit", "docs",
223
+ // sable-c1c — backend flat-shape compat keys.
224
+ "exclude_paths", "custom_patterns",
225
+ ]);
182
226
  const VALID_RISK_LEVELS = new Set(["minimal", "moderate", "aggressive"]);
183
227
  const VALID_COMMAND_MODES = new Set(["allow-all", "approve-dangerous", "deny-list"]);
184
228
  const VALID_LOG_LEVELS = new Set(["debug", "info", "warn", "error"]);
@@ -256,6 +300,13 @@ function validatePolicy(policy, raw) {
256
300
  }
257
301
  }
258
302
  }
303
+ // sable-o4k — only a boolean reaches policy.scan (mapping guards the type),
304
+ // so warn directly off the raw value when it's present but malformed.
305
+ if (raw.scan && typeof raw.scan === "object" &&
306
+ raw.scan.auto_update_betterleaks !== undefined &&
307
+ typeof raw.scan.auto_update_betterleaks !== "boolean") {
308
+ console.error(`Warning: "scan.auto_update_betterleaks" must be a boolean — ignoring.`);
309
+ }
259
310
  }
260
311
  if (policy.ignore !== undefined) {
261
312
  if (!Array.isArray(policy.ignore)) {
@@ -133,7 +133,11 @@ export class BetterleaksScanner {
133
133
  }
134
134
  const parsed = JSON.parse(content);
135
135
  if (!Array.isArray(parsed)) {
136
- console.error("[rafter] Warning: Betterleaks output is not an array — possible version mismatch");
136
+ // sable-o4k — a stale/incompatible binary emits a non-array shape and
137
+ // would otherwise silently yield zero findings. The managed binary is
138
+ // auto-updated upstream; this covers a stale binary on PATH, which we
139
+ // can't safely overwrite — so point the user at the fix.
140
+ console.error("[rafter] Warning: Betterleaks output is not an array — possible version mismatch. Run: rafter agent update-betterleaks");
137
141
  return [];
138
142
  }
139
143
  return parsed;
@@ -87,6 +87,13 @@ export const DEFAULT_SECRET_PATTERNS = [
87
87
  severity: "critical",
88
88
  description: "Twilio API Key detected"
89
89
  },
90
+ // HashiCorp Vault
91
+ {
92
+ name: "HashiCorp Vault Token",
93
+ regex: "hvs\\.[a-zA-Z0-9_-]{90,}",
94
+ severity: "critical",
95
+ description: "HashiCorp Vault service token detected"
96
+ },
90
97
  // Generic patterns
91
98
  {
92
99
  name: "Generic API Key",