@rafter-security/cli 0.10.6 → 0.11.2

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 (41) hide show
  1. package/dist/commands/agent/baseline.js +9 -50
  2. package/dist/commands/agent/components.js +7 -2
  3. package/dist/commands/agent/exec.js +26 -9
  4. package/dist/commands/agent/init.js +275 -220
  5. package/dist/commands/agent/install-hook.js +17 -6
  6. package/dist/commands/agent/scan.js +309 -71
  7. package/dist/commands/agent/update-skill-scanner.js +1 -1
  8. package/dist/commands/agent/verify.js +39 -15
  9. package/dist/commands/backend/get.js +6 -2
  10. package/dist/commands/backend/scan-status.js +34 -4
  11. package/dist/commands/ci/init.js +4 -1
  12. package/dist/commands/hook/posttool.js +11 -0
  13. package/dist/commands/hook/pretool.js +124 -36
  14. package/dist/commands/mcp/server.js +184 -129
  15. package/dist/commands/report.js +6 -2
  16. package/dist/core/audit-logger.js +47 -17
  17. package/dist/core/config-manager.js +46 -8
  18. package/dist/core/custom-patterns.js +28 -8
  19. package/dist/core/docs-loader.js +33 -3
  20. package/dist/core/pattern-engine.js +23 -5
  21. package/dist/core/policy-loader.js +15 -4
  22. package/dist/core/risk-rules.js +391 -9
  23. package/dist/index.js +6 -0
  24. package/dist/scanners/betterleaks.js +127 -14
  25. package/dist/scanners/git-history-scan.js +75 -0
  26. package/dist/scanners/regex-scanner.js +16 -2
  27. package/dist/scanners/secret-patterns.js +11 -2
  28. package/dist/scanners/union.js +31 -19
  29. package/dist/utils/api.js +35 -1
  30. package/dist/utils/git-diff.js +36 -20
  31. package/dist/utils/skill-manager.js +4 -3
  32. package/package.json +16 -15
  33. package/resources/continue-rules/rafter.md +1 -1
  34. package/resources/cursor-rules/rafter.mdc +1 -1
  35. package/resources/rafter-security-skill.md +3 -1
  36. package/resources/skills/rafter/SKILL.md +1 -2
  37. package/resources/skills/rafter/docs/guardrails.md +1 -1
  38. package/resources/skills/rafter-code-review/SKILL.md +0 -1
  39. package/resources/skills/rafter-secure-design/SKILL.md +0 -1
  40. package/resources/skills/rafter-skill-review/SKILL.md +0 -1
  41. package/resources/windsurf-rules/rafter.md +1 -1
@@ -1,4 +1,6 @@
1
1
  import { Command } from "commander";
2
+ import fs from "fs";
3
+ import path from "path";
2
4
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
6
  import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
@@ -10,6 +12,8 @@ import { AuditLogger } from "../../core/audit-logger.js";
10
12
  import { ConfigManager, redactConfigSecrets, isSecretConfigKey, maskSecretValue } from "../../core/config-manager.js";
11
13
  import { listDocs, resolveDocSelector, fetchDoc } from "../../core/docs-loader.js";
12
14
  import { writeSuppression } from "../../core/suppression-writer.js";
15
+ import { applySuppressions } from "../../core/custom-patterns.js";
16
+ import { collectSuppressions } from "../agent/scan.js";
13
17
  import { apiUrl, apiClient } from "../../utils/api.js";
14
18
  import { describeSitesError, resolveMcpApiKey } from "../sites/errors.js";
15
19
  import { createRequire } from "module";
@@ -37,175 +41,226 @@ function errorResult(message) {
37
41
  export function createServer() {
38
42
  const server = new Server({ name: "rafter", version: CLI_VERSION }, { capabilities: { tools: {}, resources: {} } });
39
43
  // ── Tools ───────────────────────────────────────────────────────────
40
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
41
- tools: [
42
- {
43
- name: "scan_secrets",
44
- description: "Scan files or directories for leaked secrets, API keys, tokens, passwords, and credentials. Use before pushing code, when handling config files, or when asked 'is this safe to commit?' or 'check for leaked keys'.",
45
- inputSchema: {
46
- type: "object",
47
- properties: {
48
- path: { type: "string", description: "File or directory path to scan" },
49
- engine: {
50
- type: "string",
51
- enum: ["auto", "betterleaks", "patterns"],
52
- description: "Scan engine: auto (default), betterleaks, or patterns.",
53
- },
44
+ const tools = [
45
+ {
46
+ name: "scan_secrets",
47
+ description: "Scan files or directories for leaked secrets, API keys, tokens, passwords, and credentials. Use before pushing code, when handling config files, or when asked 'is this safe to commit?' or 'check for leaked keys'. Findings hidden by the project's .rafter.yml ignore rules or .rafterignore are dropped from the results; when any were, a second content block lists them as {suppressed_count, _suppressed: [{file, line, column, rule, severity, reason, source}]} (no secret text), so a blanket ignore rule cannot silently empty a scan.",
48
+ inputSchema: {
49
+ type: "object",
50
+ properties: {
51
+ path: { type: "string", description: "File or directory path to scan" },
52
+ engine: {
53
+ type: "string",
54
+ enum: ["auto", "betterleaks", "patterns"],
55
+ description: "Scan engine: auto (default), betterleaks, or patterns.",
54
56
  },
55
- required: ["path"],
56
57
  },
58
+ required: ["path"],
57
59
  },
58
- {
59
- name: "evaluate_command",
60
- description: "Check if a shell command is safe to run per security policy. Use when asked 'is this command safe?' or before running destructive or privileged operations.",
61
- inputSchema: {
62
- type: "object",
63
- properties: {
64
- command: { type: "string", description: "Shell command to evaluate" },
65
- },
66
- required: ["command"],
60
+ },
61
+ {
62
+ name: "evaluate_command",
63
+ description: "Check if a shell command is safe to run per security policy. Use when asked 'is this command safe?' or before running destructive or privileged operations.",
64
+ inputSchema: {
65
+ type: "object",
66
+ properties: {
67
+ command: { type: "string", description: "Shell command to evaluate" },
67
68
  },
69
+ required: ["command"],
68
70
  },
69
- {
70
- name: "read_audit_log",
71
- description: "Read security event history — blocked commands, detected secrets, policy overrides. Use when asked 'what happened?' or 'show security events'.",
72
- inputSchema: {
73
- type: "object",
74
- properties: {
75
- limit: { type: "number", description: "Maximum entries to return (default: 20)" },
76
- event_type: {
77
- type: "string",
78
- description: "Filter by event type (e.g. command_intercepted, secret_detected)",
79
- },
80
- since: { type: "string", description: "ISO 8601 timestamp — only return entries after this time" },
71
+ },
72
+ {
73
+ name: "read_audit_log",
74
+ description: "Read security event history — blocked commands, detected secrets, policy overrides. Use when asked 'what happened?' or 'show security events'.",
75
+ inputSchema: {
76
+ type: "object",
77
+ properties: {
78
+ limit: { type: "number", description: "Maximum entries to return (default: 20)" },
79
+ event_type: {
80
+ type: "string",
81
+ description: "Filter by event type (e.g. command_intercepted, secret_detected)",
81
82
  },
83
+ since: { type: "string", description: "ISO 8601 timestamp — only return entries after this time" },
82
84
  },
83
85
  },
84
- {
85
- name: "get_config",
86
- description: "Read Rafter security policy and configuration. Use to understand what protections are active and what risk level is configured.",
87
- inputSchema: {
88
- type: "object",
89
- properties: {
90
- key: {
91
- type: "string",
92
- description: "Dot-path config key (e.g. agent.commandPolicy). Omit for full config.",
93
- },
86
+ },
87
+ {
88
+ name: "get_config",
89
+ description: "Read Rafter security policy and configuration. Use to understand what protections are active and what risk level is configured.",
90
+ inputSchema: {
91
+ type: "object",
92
+ properties: {
93
+ key: {
94
+ type: "string",
95
+ description: "Dot-path config key (e.g. agent.commandPolicy). Omit for full config.",
94
96
  },
95
97
  },
96
98
  },
97
- {
98
- name: "list_docs",
99
- description: "List repo-specific security docs declared in .rafter.yml. Call this early in any security-relevant task to discover project-specific rules, threat models, or compliance policies the user expects agents to follow.",
100
- inputSchema: {
101
- type: "object",
102
- properties: {
103
- tag: { type: "string", description: "Filter to docs whose tags include this value" },
104
- },
99
+ },
100
+ {
101
+ name: "list_docs",
102
+ description: "List repo-specific security docs declared in .rafter.yml. Call this early in any security-relevant task to discover project-specific rules, threat models, or compliance policies the user expects agents to follow.",
103
+ inputSchema: {
104
+ type: "object",
105
+ properties: {
106
+ tag: { type: "string", description: "Filter to docs whose tags include this value" },
105
107
  },
106
108
  },
107
- {
108
- name: "get_doc",
109
- description: "Return the content of a repo-specific security doc by id or tag. Use after list_docs to read a specific document.",
110
- inputSchema: {
111
- type: "object",
112
- properties: {
113
- id_or_tag: { type: "string", description: "Doc id or tag selector" },
114
- refresh: { type: "boolean", description: "Force re-fetch for URL-backed docs (bypass cache)" },
115
- },
116
- required: ["id_or_tag"],
109
+ },
110
+ {
111
+ name: "get_doc",
112
+ description: "Return the content of a repo-specific security doc by id or tag. Use after list_docs to read a specific document.",
113
+ inputSchema: {
114
+ type: "object",
115
+ properties: {
116
+ id_or_tag: { type: "string", description: "Doc id or tag selector" },
117
+ refresh: { type: "boolean", description: "Force re-fetch for URL-backed docs (bypass cache)" },
117
118
  },
119
+ required: ["id_or_tag"],
118
120
  },
119
- {
120
- name: "suppress_finding",
121
- description: "Triage a false positive by persisting a suppression rule into the project's .rafter.yml. Use when a scan_secrets finding (or a remote scan finding) is a confirmed false positive — e.g. a test fixture or sample credential. Suppressed findings still surface under '_suppressed' in scan output, so the decision is reviewable and version-controlled. Always include a reason.",
122
- inputSchema: {
123
- type: "object",
124
- properties: {
125
- path: { type: "string", description: "File path or glob to suppress findings in (e.g. 'test/fixtures/**')" },
126
- rules: {
127
- type: "array",
128
- items: { type: "string" },
129
- description: "Specific rules to suppress, matched case-insensitively against a finding's rule name OR rule id — e.g. 'AWS Access Key' (local pattern name) or 'R-6D5E2' (remote SAST/SCA rule id). Omit to suppress all rules for the path. Honored by both local scans and remote `rafter run`.",
130
- },
131
- reason: { type: "string", description: "Why this is a false positive — persisted with the rule. Strongly recommended." },
121
+ },
122
+ {
123
+ name: "suppress_finding",
124
+ description: "Triage a false positive by persisting a suppression rule into the project's .rafter.yml. Use when a scan_secrets finding (or a remote scan finding) is a confirmed false positive — e.g. a test fixture or sample credential. scan_secrets stops reporting suppressed findings; `rafter secrets --json` lists them under '_suppressed', so the decision is reviewable and version-controlled. Always include a reason.",
125
+ inputSchema: {
126
+ type: "object",
127
+ properties: {
128
+ path: { type: "string", description: "File path or glob to suppress findings in (e.g. 'test/fixtures/**')" },
129
+ rules: {
130
+ type: "array",
131
+ items: { type: "string" },
132
+ description: "Specific rules to suppress, matched case-insensitively against a finding's rule name OR rule id — e.g. 'AWS Access Key' (local pattern name) or 'R-6D5E2' (remote SAST/SCA rule id). Omit to suppress all rules for the path. Honored by both local scans and remote `rafter run`.",
132
133
  },
133
- required: ["path"],
134
+ reason: { type: "string", description: "Why this is a false positive — persisted with the rule. Strongly recommended." },
134
135
  },
136
+ required: ["path"],
135
137
  },
136
- {
137
- name: "sites_create",
138
- description: "Register a URL as a Rafter Site for live-application security monitoring (exposed backends, DNS misconfig, SEO, accessibility) and kick off its first scan. Use when asked to start monitoring a domain/site.",
139
- inputSchema: {
140
- type: "object",
141
- properties: {
142
- url: { type: "string", description: "URL of the site to monitor" },
143
- },
144
- required: ["url"],
138
+ },
139
+ {
140
+ name: "sites_create",
141
+ description: "Register a URL as a Rafter Site for live-application security monitoring (exposed backends, DNS misconfig, SEO, accessibility) and kick off its first scan. Use when asked to start monitoring a domain/site.",
142
+ inputSchema: {
143
+ type: "object",
144
+ properties: {
145
+ url: { type: "string", description: "URL of the site to monitor" },
145
146
  },
147
+ required: ["url"],
146
148
  },
147
- {
148
- name: "sites_scan",
149
- description: "Trigger a re-scan of an existing Rafter Site. Identify the site by projectId OR url (exactly one required). Use when asked to re-scan or refresh a site's findings.",
150
- inputSchema: {
151
- type: "object",
152
- properties: {
153
- projectId: { type: "string", description: "The site's project id (use this or url, not both)" },
154
- url: { type: "string", description: "The site's URL (use this or projectId, not both)" },
155
- sections: {
156
- type: "array",
157
- items: { type: "string", enum: ["flight", "security", "dns"] },
158
- description: "Subset of scan sections to run. Omit to run all.",
159
- },
149
+ },
150
+ {
151
+ name: "sites_scan",
152
+ description: "Trigger a re-scan of an existing Rafter Site. Identify the site by projectId OR url (exactly one required). Use when asked to re-scan or refresh a site's findings.",
153
+ inputSchema: {
154
+ type: "object",
155
+ properties: {
156
+ projectId: { type: "string", description: "The site's project id (use this or url, not both)" },
157
+ url: { type: "string", description: "The site's URL (use this or projectId, not both)" },
158
+ sections: {
159
+ type: "array",
160
+ items: { type: "string", enum: ["flight", "security", "dns"] },
161
+ description: "Subset of scan sections to run. Omit to run all.",
160
162
  },
161
163
  },
162
164
  },
163
- {
164
- name: "sites_list",
165
- description: "List Rafter Sites registered for monitoring, paginated. Use when asked 'what sites are being monitored?' or to browse before calling sites_get.",
166
- inputSchema: {
167
- type: "object",
168
- properties: {
169
- limit: { type: "number", description: "Results per page, 1-100 (default: 25)" },
170
- offset: { type: "number", description: "Pagination offset (default: 0)" },
171
- include_archived: { type: "boolean", description: "Include archived sites (default: false)" },
172
- },
165
+ },
166
+ {
167
+ name: "sites_list",
168
+ description: "List Rafter Sites registered for monitoring, paginated. Use when asked 'what sites are being monitored?' or to browse before calling sites_get.",
169
+ inputSchema: {
170
+ type: "object",
171
+ properties: {
172
+ limit: { type: "number", description: "Results per page, 1-100 (default: 25)" },
173
+ offset: { type: "number", description: "Pagination offset (default: 0)" },
174
+ include_archived: { type: "boolean", description: "Include archived sites (default: false)" },
173
175
  },
174
176
  },
175
- {
176
- name: "sites_get",
177
- description: "Get a Rafter Site's status, latest scan run, and findings summary by its project id. Use after sites_list or sites_create to check a specific site's results.",
178
- inputSchema: {
179
- type: "object",
180
- properties: {
181
- id: { type: "string", description: "The site's project id" },
182
- },
183
- required: ["id"],
177
+ },
178
+ {
179
+ name: "sites_get",
180
+ description: "Get a Rafter Site's status, latest scan run, and findings summary by its project id. Use after sites_list or sites_create to check a specific site's results.",
181
+ inputSchema: {
182
+ type: "object",
183
+ properties: {
184
+ id: { type: "string", description: "The site's project id" },
184
185
  },
186
+ required: ["id"],
185
187
  },
186
- ],
187
- }));
188
+ },
189
+ ];
190
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
188
191
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
189
192
  const { name, arguments: args } = request.params;
193
+ // sable-ykuh — validate required inputSchema fields up front, so a missing
194
+ // argument comes back as a clean tool error instead of reaching the handler
195
+ // and crashing it with a raw TypeError (surfaced to the client as a -32603
196
+ // internal error). Mirrors the Python server, where FastMCP rejects the
197
+ // call against the tool signature before the handler runs.
198
+ const tool = tools.find((t) => t.name === name);
199
+ if (!tool)
200
+ return errorResult(`Unknown tool: ${name}`);
201
+ const required = (tool.inputSchema.required) ?? [];
202
+ for (const field of required) {
203
+ const value = args?.[field];
204
+ if (value === undefined || value === null) {
205
+ return errorResult(`Invalid arguments for "${name}": missing required field "${field}"`);
206
+ }
207
+ }
190
208
  switch (name) {
191
209
  case "scan_secrets": {
192
210
  const scanPath = args?.path;
193
211
  const engine = args?.engine || "auto";
194
212
  const runPatterns = () => {
195
213
  const scanner = new RegexScanner();
196
- try {
197
- return scanner.scanDirectory(scanPath);
214
+ // scanDirectory() on a file returns [] rather than throwing, so pick by type.
215
+ return fs.statSync(scanPath).isFile()
216
+ ? [scanner.scanFile(scanPath)]
217
+ : scanner.scanDirectory(scanPath);
218
+ };
219
+ // Honor the project's suppressions, as `rafter secrets` does, so a
220
+ // finding triaged with suppress_finding is not reported again.
221
+ const report = (results) => {
222
+ // Partition off files that could not be read (sable-ilbx), so an
223
+ // unreadable file is not reported as a clean, empty entry.
224
+ const readErrors = results
225
+ .filter((r) => r.readError)
226
+ .map((r) => ({ file: r.file, error: r.readError }));
227
+ const scanResults = results.filter((r) => !r.readError);
228
+ // Discover and anchor the policy from the scan TARGET, not the MCP
229
+ // server's cwd (sable-lu0j).
230
+ const scanBase = path.resolve(scanPath);
231
+ const rafterignoreDir = fs.existsSync(scanBase) && fs.statSync(scanBase).isDirectory()
232
+ ? scanBase
233
+ : path.dirname(scanBase);
234
+ const policyCfg = new ConfigManager().loadWithPolicy(scanBase).agent?.scan;
235
+ const suppressions = collectSuppressions(policyCfg?.ignore, policyCfg?.ignoreBaseDir, rafterignoreDir);
236
+ const applied = applySuppressions(scanResults, suppressions);
237
+ // Drop only what was suppressed; a clean file keeps its empty entry.
238
+ const kept = new Map(applied.results.map((r) => [r.file, r]));
239
+ const out = textResult(formatScanResults(scanResults.filter((r) => r.matches.length === 0 || kept.has(r.file)).map((r) => kept.get(r.file) ?? r)));
240
+ // Say what was dropped (metadata only, no secret text), as
241
+ // `rafter secrets --json` does under `_suppressed`.
242
+ if (applied.suppressed.length > 0) {
243
+ out.content.push(textResult({
244
+ suppressed_count: applied.suppressed.length,
245
+ _suppressed: applied.suppressed,
246
+ }).content[0]);
198
247
  }
199
- catch {
200
- return [scanner.scanFile(scanPath)];
248
+ // Say what could not be read (metadata only, no secret text), so a
249
+ // caller can tell an empty result from an incomplete scan.
250
+ if (readErrors.length > 0) {
251
+ out.content.push(textResult({
252
+ unreadable_count: readErrors.length,
253
+ unreadable: readErrors,
254
+ }).content[0]);
201
255
  }
256
+ return out;
202
257
  };
203
258
  if (engine === "betterleaks") {
204
259
  const bl = new BetterleaksScanner();
205
260
  if (!(await bl.isAvailable()))
206
261
  return errorResult("Betterleaks not installed");
207
262
  try {
208
- return textResult(formatScanResults(await bl.scanDirectory(scanPath)));
263
+ return report(await bl.scanDirectory(scanPath));
209
264
  }
210
265
  catch {
211
266
  return errorResult("Betterleaks scan failed");
@@ -219,16 +274,16 @@ export function createServer() {
219
274
  if (await bl.isAvailable()) {
220
275
  try {
221
276
  const blResults = await bl.scanDirectory(scanPath);
222
- return textResult(formatScanResults(unionScanResults(blResults, runPatterns())));
277
+ return report(unionScanResults(blResults, runPatterns()));
223
278
  }
224
279
  catch {
225
280
  // betterleaks failed — fall through to patterns-only.
226
281
  }
227
282
  }
228
- return textResult(formatScanResults(runPatterns()));
283
+ return report(runPatterns());
229
284
  }
230
285
  // patterns (and any unrecognized value — the tool schema enums this).
231
- return textResult(formatScanResults(runPatterns()));
286
+ return report(runPatterns());
232
287
  }
233
288
  case "evaluate_command": {
234
289
  const command = args?.command;
@@ -32,9 +32,13 @@ export function createReportCommand() {
32
32
  }
33
33
  let results;
34
34
  try {
35
- results = JSON.parse(jsonData);
35
+ const parsed = JSON.parse(jsonData);
36
+ // `rafter secrets --json` wraps its results in an object.
37
+ results = Array.isArray(parsed) ? parsed : parsed?.results;
36
38
  if (!Array.isArray(results)) {
37
- throw new Error("Expected a JSON array of scan results");
39
+ throw new Error(Array.isArray(parsed?.vulnerabilities)
40
+ ? "this is a remote scan result; render it with `rafter get <scan_id> --format md`"
41
+ : "Expected the JSON output of `rafter secrets --json`");
38
42
  }
39
43
  }
40
44
  catch (e) {
@@ -103,26 +103,34 @@ function isPrivateIp(ip) {
103
103
  /**
104
104
  * Return sha256 hex of the last non-empty line of the file (including its
105
105
  * trailing newline), or null if the file is empty / does not exist.
106
- * Reads only the tail of the file so this is cheap even for large logs.
106
+ * Reads backwards from the end in chunks, so this stays cheap for large logs
107
+ * while still hashing the whole line when one entry is longer than a chunk
108
+ * (a long intercepted command can be).
107
109
  */
108
110
  export function readLastLineHash(filePath) {
109
111
  if (!fs.existsSync(filePath))
110
112
  return null;
111
- const stat = fs.statSync(filePath);
112
- if (stat.size === 0)
113
+ const size = fs.statSync(filePath).size;
114
+ if (size === 0)
113
115
  return null;
114
- // Read the last 64KB — an audit line tops out well under this.
115
- const readBytes = Math.min(stat.size, 65536);
116
116
  const fd = fs.openSync(filePath, "r");
117
117
  try {
118
- const buf = Buffer.alloc(readBytes);
119
- fs.readSync(fd, buf, 0, readBytes, stat.size - readBytes);
120
- const text = buf.toString("utf-8");
121
- // Find last non-empty line
122
- const lines = text.split("\n");
123
- for (let i = lines.length - 1; i >= 0; i--) {
124
- if (lines[i].trim()) {
125
- return createHash("sha256").update(lines[i] + "\n").digest("hex");
118
+ let buf = Buffer.alloc(0);
119
+ let pos = size;
120
+ while (pos > 0) {
121
+ const n = Math.min(65536, pos);
122
+ pos -= n;
123
+ const chunk = Buffer.alloc(n);
124
+ fs.readSync(fd, chunk, 0, n, pos);
125
+ buf = Buffer.concat([chunk, buf]);
126
+ const text = buf.toString("utf-8");
127
+ const lines = text.split("\n");
128
+ // lines[0] may be cut off by the chunk boundary; trust it only at file start.
129
+ const first = pos === 0 ? 0 : 1;
130
+ for (let i = lines.length - 1; i >= first; i--) {
131
+ if (lines[i].trim()) {
132
+ return createHash("sha256").update(lines[i] + "\n").digest("hex");
133
+ }
126
134
  }
127
135
  }
128
136
  return null;
@@ -197,6 +205,14 @@ export const RISK_SEVERITY = {
197
205
  high: 2,
198
206
  critical: 3,
199
207
  };
208
+ let warnedAuditFailure = false;
209
+ function warnAuditFailure(logPath, e) {
210
+ if (warnedAuditFailure)
211
+ return;
212
+ warnedAuditFailure = true;
213
+ const msg = e instanceof Error ? e.message : String(e);
214
+ console.error(`rafter: could not write audit log ${logPath}: ${msg}`);
215
+ }
200
216
  export class AuditLogger {
201
217
  constructor(logPath) {
202
218
  this.configManager = new ConfigManager();
@@ -206,7 +222,7 @@ export class AuditLogger {
206
222
  this.logPath = logPath;
207
223
  }
208
224
  else {
209
- // Project-local override from .rafter.yml (via loadWithPolicy) beats global
225
+ // Global config only: loadWithPolicy drops a project-level audit.log_path.
210
226
  let policyPath;
211
227
  try {
212
228
  policyPath = this.configManager.loadWithPolicy()?.agent?.audit?.logPath;
@@ -220,14 +236,28 @@ export class AuditLogger {
220
236
  }
221
237
  // Ensure log directory exists
222
238
  const dir = path.dirname(this.logPath);
223
- if (!fs.existsSync(dir)) {
224
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
239
+ try {
240
+ if (!fs.existsSync(dir)) {
241
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
242
+ }
243
+ }
244
+ catch (e) {
245
+ warnAuditFailure(this.logPath, e);
225
246
  }
226
247
  }
227
248
  /**
228
- * Log an audit event
249
+ * Log an audit event. Never throws: an audit failure must not change the
250
+ * decision of the caller.
229
251
  */
230
252
  log(entry) {
253
+ try {
254
+ this.writeEntry(entry);
255
+ }
256
+ catch (e) {
257
+ warnAuditFailure(this.logPath, e);
258
+ }
259
+ }
260
+ writeEntry(entry) {
231
261
  const config = this.configManager.load();
232
262
  // Check if logging is enabled
233
263
  if (!config.agent?.audit.logAllActions) {
@@ -1,7 +1,7 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
3
  import { getDefaultConfig, getConfigPath, getRafterDir, CONFIG_VERSION } from "./config-defaults.js";
4
- import { loadPolicy } from "./policy-loader.js";
4
+ import { loadPolicy, findPolicyFile } 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"]);
@@ -40,6 +40,27 @@ export function redactConfigSecrets(value) {
40
40
  /**
41
41
  * Validate a parsed config JSON object, warning and falling back to defaults for invalid fields.
42
42
  */
43
+ /**
44
+ * The Python CLI writes the shared config file with snake_case keys
45
+ * (`backend.api_key`, `agent.risk_level`). Rename them to camelCase so a config
46
+ * written by either CLI reads the same here. Component IDs under
47
+ * `agent.components` are data, not field names, and keep their spelling.
48
+ * Where both spellings exist, the camelCase one (Node's own) wins.
49
+ */
50
+ function camelizeKeys(value, keepKeys = false) {
51
+ if (Array.isArray(value))
52
+ return value.map((v) => camelizeKeys(v));
53
+ if (!value || typeof value !== "object")
54
+ return value;
55
+ const out = {};
56
+ for (const [key, v] of Object.entries(value)) {
57
+ const camel = keepKeys ? key : key.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
58
+ if (camel !== key && camel in value)
59
+ continue;
60
+ out[camel] = camelizeKeys(v, !keepKeys && camel === "components");
61
+ }
62
+ return out;
63
+ }
43
64
  function validateConfig(raw) {
44
65
  if (!raw || typeof raw !== "object") {
45
66
  console.error("Warning: config file is not a JSON object — using defaults.");
@@ -145,6 +166,7 @@ function validateConfig(raw) {
145
166
  }
146
167
  return raw;
147
168
  }
169
+ let warnedProjectLogPath = false;
148
170
  export class ConfigManager {
149
171
  constructor(configPath) {
150
172
  this.configPath = configPath || getConfigPath();
@@ -159,7 +181,7 @@ export class ConfigManager {
159
181
  try {
160
182
  const content = fs.readFileSync(this.configPath, "utf-8");
161
183
  const parsed = JSON.parse(content);
162
- const config = validateConfig(parsed);
184
+ const config = validateConfig(camelizeKeys(parsed));
163
185
  // Migrate config if needed
164
186
  return this.migrate(config);
165
187
  }
@@ -282,11 +304,17 @@ export class ConfigManager {
282
304
  return this.load().agent?.commandPolicy?.allowProjectOverride === true;
283
305
  }
284
306
  /**
285
- * Load config merged with .rafter.yml policy (policy wins)
307
+ * Load config merged with .rafter.yml policy (policy wins).
308
+ *
309
+ * `baseDir` is the scan target: the policy and its ignore globs are
310
+ * discovered and anchored from there, not the process cwd (sable-lu0j), so
311
+ * an ambient `.rafter.yml` in cwd cannot govern a scan of a different tree.
312
+ * Defaults to cwd, which is correct for `--staged`/hook runs that scan the
313
+ * repo the command runs in.
286
314
  */
287
- loadWithPolicy() {
315
+ loadWithPolicy(baseDir) {
288
316
  const config = this.load();
289
- const policy = loadPolicy();
317
+ const policy = loadPolicy(baseDir);
290
318
  if (!policy)
291
319
  return config;
292
320
  // Ensure agent block exists, AND that commandPolicy inside it does.
@@ -334,11 +362,17 @@ export class ConfigManager {
334
362
  config.agent.scan.plusRequiresApproval = true;
335
363
  }
336
364
  }
337
- // Ignore rules — top-level policy key, applied per finding at scan time
365
+ // Ignore rules — top-level policy key, applied per finding at scan time.
366
+ // Record the directory the globs are relative to (the `.rafter.yml`'s own
367
+ // directory) so they anchor to the policy's tree, not an absolute path
368
+ // anywhere on disk (sable-lu0j).
338
369
  if (policy.ignore && config.agent) {
339
370
  if (!config.agent.scan)
340
371
  config.agent.scan = {};
341
372
  config.agent.scan.ignore = policy.ignore;
373
+ const policyPath = findPolicyFile(baseDir);
374
+ if (policyPath)
375
+ config.agent.scan.ignoreBaseDir = path.dirname(policyPath);
342
376
  }
343
377
  // Audit settings
344
378
  if (policy.audit && config.agent) {
@@ -348,8 +382,12 @@ export class ConfigManager {
348
382
  if (policy.audit.logLevel) {
349
383
  config.agent.audit.logLevel = policy.audit.logLevel;
350
384
  }
351
- if (policy.audit.logPath) {
352
- config.agent.audit.logPath = policy.audit.logPath;
385
+ // audit.log_path is honored only from the global config; a project
386
+ // value is ignored, with a warning, logged once per process.
387
+ if (policy.audit.logPath && !warnedProjectLogPath) {
388
+ warnedProjectLogPath = true;
389
+ console.error('rafter: ignoring "audit.log_path" in the project policy file — the audit log location ' +
390
+ "can only be set in ~/.rafter/config.json (agent.audit.logPath).");
353
391
  }
354
392
  }
355
393
  return config;