@rafter-security/cli 0.11.2 → 0.11.4

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.
@@ -111,7 +111,7 @@ function claudeCodeHooks() {
111
111
  if (settings.hooks.SessionStart.length === 0)
112
112
  delete settings.hooks.SessionStart;
113
113
  }
114
- settings.hooks.PreToolUse.push({ matcher: "Bash", hooks: [pre] }, { matcher: "Write|Edit", hooks: [pre] });
114
+ settings.hooks.PreToolUse.push({ matcher: "Bash", hooks: [pre] }, { matcher: "Write|Edit|MultiEdit", hooks: [pre] });
115
115
  // Narrow to tools that produce scannable output (shell output + file
116
116
  // writes); avoids firing posttool on every Read/MCP call (latency).
117
117
  settings.hooks.PostToolUse.push({ matcher: "Bash|Write|Edit|MultiEdit", hooks: [post] });
@@ -549,8 +549,9 @@ function geminiHooks() {
549
549
  s.hooks.AfterTool = filterOutRafter(s.hooks.AfterTool, (e) => hookEntryMatchesRafter(e, "rafter hook posttool"));
550
550
  // Explicit Gemini built-in tool names per geminicli.com/docs/hooks/reference
551
551
  // (rf-044o verification).
552
+ // No tool is named `edit`: Gemini's edit tool is `replace`.
552
553
  s.hooks.BeforeTool.push({
553
- matcher: "run_shell_command|write_file|replace|edit",
554
+ matcher: "run_shell_command|write_file|replace",
554
555
  hooks: [{ type: "command", command: "rafter hook pretool --format gemini", timeout: 5000 }],
555
556
  });
556
557
  s.hooks.AfterTool.push({
@@ -374,7 +374,7 @@ function installClaudeCodeHooks(root, out) {
374
374
  delete settings.hooks.SessionStart;
375
375
  }
376
376
  // Add Rafter hooks
377
- settings.hooks.PreToolUse.push({ matcher: "Bash", hooks: [preHook] }, { matcher: "Write|Edit", hooks: [preHook] });
377
+ settings.hooks.PreToolUse.push({ matcher: "Bash", hooks: [preHook] }, { matcher: "Write|Edit|MultiEdit", hooks: [preHook] });
378
378
  // Narrow to tools that produce scannable output (shell output + file
379
379
  // writes). Firing posttool on every tool — including Read and MCP calls —
380
380
  // added latency to operations that never produce secrets to redact.
@@ -590,10 +590,12 @@ function installGeminiHooks(root, out) {
590
590
  settings.hooks.AfterTool = settings.hooks.AfterTool.filter((entry) => !(entry.hooks || []).some((h) => String(h.command ?? "").includes("hook posttool")));
591
591
  // Gemini matchers are regexes against built-in tool names per
592
592
  // geminicli.com/docs/hooks/reference. Match the mutating tools by name
593
- // explicitly: run_shell_command, write_file, replace, edit. (rf-044o
594
- // verification 2026-05-03 — schema confirmed against current Gemini docs.)
593
+ // explicitly: run_shell_command, write_file, replace. (rf-044o
594
+ // verification 2026-05-03 — schema confirmed against current Gemini docs.
595
+ // Gemini has no tool named `edit`; its edit tool is `replace` per
596
+ // geminicli.com/docs/reference/tools.)
595
597
  settings.hooks.BeforeTool.push({
596
- matcher: "run_shell_command|write_file|replace|edit",
598
+ matcher: "run_shell_command|write_file|replace",
597
599
  hooks: [{ type: "command", command: absoluteHookCommand("pretool --format gemini"), timeout: 5000 }],
598
600
  });
599
601
  settings.hooks.AfterTool.push({
@@ -211,7 +211,8 @@ const WRITE_TOOLS = new Set(["Write", "Edit", "MultiEdit", "write_file", "replac
211
211
  * Map each write tool's input onto the { file_path, content } shape that
212
212
  * evaluateWrite reads: Continue's Write names its path `filepath`; MultiEdit
213
213
  * and Windsurf's pre_write_code carry `edits[].new_string`; Codex's
214
- * apply_patch carries the whole patch in `command`.
214
+ * apply_patch carries the whole patch in `command`, with its target paths
215
+ * in the patch headers (`patch_paths`).
215
216
  */
216
217
  function normalizeWriteInput(toolName, input) {
217
218
  const out = { ...input };
@@ -225,8 +226,28 @@ function normalizeWriteInput(toolName, input) {
225
226
  out.content = input.command;
226
227
  }
227
228
  }
229
+ if (toolName === "apply_patch" && typeof input.command === "string") {
230
+ out.patch_paths = applyPatchPaths(input.command);
231
+ }
228
232
  return out;
229
233
  }
234
+ /**
235
+ * Every path an apply_patch names. The patch format carries its targets only
236
+ * in hunk headers, which Codex matches on the trimmed line:
237
+ * `*** Add File: <path>`, `*** Update File: <path>`, `*** Delete File: <path>`
238
+ * and `*** Move to: <path>` (codex-rs/apply-patch, apply_patch.lark).
239
+ */
240
+ const APPLY_PATCH_HEADERS = ["*** Add File: ", "*** Update File: ", "*** Delete File: ", "*** Move to: "];
241
+ function applyPatchPaths(patch) {
242
+ const paths = [];
243
+ for (const raw of patch.split("\n")) {
244
+ const line = raw.trim();
245
+ const header = APPLY_PATCH_HEADERS.find((h) => line.startsWith(h));
246
+ if (header)
247
+ paths.push(line.slice(header.length).trim());
248
+ }
249
+ return paths;
250
+ }
230
251
  function evaluateBash(command, control) {
231
252
  const audit = new AuditLogger();
232
253
  // Command-risk interception — gated by commandPolicy. When disabled, skip the
@@ -308,8 +329,9 @@ function writesRafterSecurityConfig(filePath) {
308
329
  function evaluateWrite(toolInput) {
309
330
  // rf-vnxs: checked FIRST, and before the no-content early return, because a
310
331
  // truncating write with empty content disables the hook just as well as one
311
- // carrying JSON.
312
- if (writesRafterSecurityConfig(toolInput.file_path ?? "")) {
332
+ // carrying JSON. apply_patch names its targets only in the patch headers.
333
+ const targets = [toolInput.file_path ?? "", ...(toolInput.patch_paths ?? [])];
334
+ if (targets.some(writesRafterSecurityConfig)) {
313
335
  return {
314
336
  decision: "deny",
315
337
  reason: "\u2717 Rafter blocked: write to rafter's own configuration\n" +
@@ -29,24 +29,30 @@ function severityEmoji(level) {
29
29
  return emojis[sev] || "🟡";
30
30
  }
31
31
  export function buildFromBackendVulnerability(vuln) {
32
- const sev = severityLabel(vuln.level);
33
- const emoji = severityEmoji(vuln.level);
34
- const fp = fingerprint(vuln.file, vuln.ruleId);
35
- const title = `${emoji} [${sev.toUpperCase()}] ${vuln.ruleId}: ${truncate(vuln.message, 80)}`;
32
+ const ruleId = vuln.rule_id ?? vuln.ruleId ?? "unknown-rule";
33
+ const level = vuln.severity ?? vuln.level ?? "note";
34
+ const summary = vuln.title ?? vuln.message ?? "Security finding";
35
+ const details = vuln.description ?? vuln.message ?? summary;
36
+ const file = vuln.file_path ?? vuln.file ?? "unknown file";
37
+ const line = vuln.line_start ?? vuln.line;
38
+ const sev = severityLabel(level);
39
+ const emoji = severityEmoji(level);
40
+ const fp = fingerprint(file, ruleId);
41
+ const title = `${emoji} [${sev.toUpperCase()}] ${ruleId}: ${truncate(summary, 80)}`;
36
42
  let body = `## Security Finding\n\n`;
37
- body += `**Rule:** \`${vuln.ruleId}\`\n`;
43
+ body += `**Rule:** \`${ruleId}\`\n`;
38
44
  body += `**Severity:** ${sev}\n`;
39
- body += `**File:** \`${vuln.file}\``;
40
- if (vuln.line)
41
- body += ` (line ${vuln.line})`;
45
+ body += `**File:** \`${file}\``;
46
+ if (line)
47
+ body += ` (line ${line})`;
42
48
  body += `\n\n`;
43
- body += `### Description\n\n${vuln.message}\n\n`;
44
- body += `### Remediation\n\nReview and fix the finding in \`${vuln.file}\`.\n`;
49
+ body += `### Description\n\n${details}\n\n`;
50
+ body += `### Remediation\n\nReview and fix the finding in \`${file}\`.\n`;
45
51
  body += `\n---\n*Created by [Rafter CLI](https://rafter.so) — security for AI builders*\n`;
46
52
  const labels = [
47
53
  "security",
48
54
  `severity:${sev}`,
49
- `rule:${vuln.ruleId}`,
55
+ `rule:${ruleId}`,
50
56
  ];
51
57
  return {
52
58
  title,
@@ -3,6 +3,62 @@ import { resolveKey, EXIT_GENERAL_ERROR, EXIT_SCAN_NOT_FOUND, apiClient, apiUrl
3
3
  import { validateWebhookUrl } from "../core/audit-logger.js";
4
4
  import { ConfigManager } from "../core/config-manager.js";
5
5
  import { fmt } from "../utils/formatter.js";
6
+ // Map a raw severity/level to a display tier, using the same rules as the
7
+ // GitHub Action (github-action/action.yml) and `rafter get`, so notify agrees
8
+ // with both. A value outside the known set is kept verbatim so a finding is
9
+ // never silently dropped.
10
+ function severityTier(raw) {
11
+ switch ((raw ?? "").toLowerCase()) {
12
+ case "critical":
13
+ return "critical";
14
+ case "error":
15
+ case "high":
16
+ return "high";
17
+ case "warning":
18
+ case "medium":
19
+ return "medium";
20
+ case "note":
21
+ case "low":
22
+ return "low";
23
+ default:
24
+ return (raw ?? "unknown").toLowerCase();
25
+ }
26
+ }
27
+ // Read findings from the real scan shape (`vulnerabilities[]`), falling back to
28
+ // the legacy `findings[]` for old cached payloads. Counts are derived from each
29
+ // finding's own severity — never from `summary` — so a finding cannot be lost
30
+ // to a summary field this code does not read. "Clean" is therefore reported
31
+ // only when there are genuinely zero findings.
32
+ function normalizeScan(scan) {
33
+ const raw = Array.isArray(scan.vulnerabilities)
34
+ ? scan.vulnerabilities
35
+ : Array.isArray(scan.findings)
36
+ ? scan.findings
37
+ : [];
38
+ let critical = 0;
39
+ let high = 0;
40
+ let medium = 0;
41
+ let low = 0;
42
+ const findings = raw.map((v) => {
43
+ const tier = severityTier(v.severity ?? v.level);
44
+ if (tier === "critical")
45
+ critical++;
46
+ else if (tier === "high")
47
+ high++;
48
+ else if (tier === "medium")
49
+ medium++;
50
+ else if (tier === "low")
51
+ low++;
52
+ const title = v.title ?? v.rule_id ?? v.ruleId ?? v.message ?? "Unknown";
53
+ const file = v.file_path ?? v.file;
54
+ const line = v.line_start ?? v.line;
55
+ let location = v.location ?? file ?? "";
56
+ if (!v.location && file && line != null)
57
+ location = `${file}:${line}`;
58
+ return { severity: tier, title, location };
59
+ });
60
+ return { findings, critical, high, medium, low, total: findings.length };
61
+ }
6
62
  function resolveWebhook(cliOpt) {
7
63
  if (cliOpt)
8
64
  return cliOpt;
@@ -29,17 +85,11 @@ function detectPlatform(url) {
29
85
  return "discord";
30
86
  return "generic";
31
87
  }
32
- function formatSlackPayload(scan) {
88
+ export function formatSlackPayload(scan) {
33
89
  const status = scan.status ?? "unknown";
34
90
  const repo = scan.repository_name ?? "unknown";
35
91
  const scanId = scan.scan_id ?? "";
36
- const findings = scan.findings ?? [];
37
- const summary = scan.summary ?? {};
38
- const critical = summary.critical ?? 0;
39
- const high = summary.high ?? 0;
40
- const medium = summary.medium ?? 0;
41
- const low = summary.low ?? 0;
42
- const total = critical + high + medium + low;
92
+ const { findings, critical, high, medium, low, total } = normalizeScan(scan);
43
93
  let statusIcon;
44
94
  let statusText;
45
95
  if (status === "completed" && total === 0) {
@@ -88,12 +138,9 @@ function formatSlackPayload(scan) {
88
138
  }
89
139
  if (findings.length > 0) {
90
140
  const lines = findings.slice(0, 5).map((f) => {
91
- const sev = (f.severity ?? "unknown").toUpperCase();
92
- const title = f.title ?? f.rule_id ?? "Unknown";
93
- const loc = f.location ?? f.file ?? "";
94
- let line = `• \`[${sev}]\` ${title}`;
95
- if (loc)
96
- line += ` — ${loc}`;
141
+ let line = `• \`[${f.severity.toUpperCase()}]\` ${f.title}`;
142
+ if (f.location)
143
+ line += ` — ${f.location}`;
97
144
  return line;
98
145
  });
99
146
  if (findings.length > 5)
@@ -107,17 +154,11 @@ function formatSlackPayload(scan) {
107
154
  });
108
155
  return { text: `[rafter] ${repo}: ${statusText}`, blocks };
109
156
  }
110
- function formatDiscordPayload(scan) {
157
+ export function formatDiscordPayload(scan) {
111
158
  const status = scan.status ?? "unknown";
112
159
  const repo = scan.repository_name ?? "unknown";
113
160
  const scanId = scan.scan_id ?? "";
114
- const findings = scan.findings ?? [];
115
- const summary = scan.summary ?? {};
116
- const critical = summary.critical ?? 0;
117
- const high = summary.high ?? 0;
118
- const medium = summary.medium ?? 0;
119
- const low = summary.low ?? 0;
120
- const total = critical + high + medium + low;
161
+ const { findings, critical, high, medium, low, total } = normalizeScan(scan);
121
162
  let color;
122
163
  let statusText;
123
164
  if (status === "completed" && total === 0) {
@@ -162,12 +203,9 @@ function formatDiscordPayload(scan) {
162
203
  }
163
204
  if (findings.length > 0) {
164
205
  const lines = findings.slice(0, 5).map((f) => {
165
- const sev = (f.severity ?? "unknown").toUpperCase();
166
- const title = f.title ?? f.rule_id ?? "Unknown";
167
- const loc = f.location ?? f.file ?? "";
168
- let line = `• \`[${sev}]\` ${title}`;
169
- if (loc)
170
- line += ` — ${loc}`;
206
+ let line = `• \`[${f.severity.toUpperCase()}]\` ${f.title}`;
207
+ if (f.location)
208
+ line += ` — ${f.location}`;
171
209
  return line;
172
210
  });
173
211
  if (findings.length > 5)
@@ -179,11 +217,10 @@ function formatDiscordPayload(scan) {
179
217
  embeds: [{ title: "\u{1f6e1}\ufe0f Rafter Security Scan", color, fields, footer: { text: "rafter-bot | rafter.so" } }],
180
218
  };
181
219
  }
182
- function formatGenericPayload(scan) {
220
+ export function formatGenericPayload(scan) {
183
221
  const status = scan.status ?? "unknown";
184
222
  const repo = scan.repository_name ?? "unknown";
185
- const summary = scan.summary ?? {};
186
- const total = (summary.critical ?? 0) + (summary.high ?? 0) + (summary.medium ?? 0) + (summary.low ?? 0);
223
+ const { total } = normalizeScan(scan);
187
224
  let statusText;
188
225
  if (status === "completed" && total === 0)
189
226
  statusText = "Clean — no issues found";
@@ -40,7 +40,7 @@ function generateClaudeConfig() {
40
40
  hooks: [{ type: "command", command: "rafter hook pretool" }],
41
41
  },
42
42
  {
43
- matcher: "Write|Edit",
43
+ matcher: "Write|Edit|MultiEdit",
44
44
  hooks: [{ type: "command", command: "rafter hook pretool" }],
45
45
  },
46
46
  ],
@@ -969,9 +969,226 @@ function statementDisarmsRafter(words) {
969
969
  export function modifiesRafterSecurityConfig(command) {
970
970
  if (disarmsRafter(command, 0))
971
971
  return true;
972
+ if (writesRafterDir(command))
973
+ return true;
972
974
  const sanitized = sanitizeCommandForMatching(command);
973
975
  return sanitized !== command && disarmsRafter(sanitized, 0);
974
976
  }
977
+ /**
978
+ * sable-36oe: the SHELL route to rafter's own directory (`~/.rafter`), which
979
+ * the Write/Edit route already refuses (rf-vnxs, `writesRafterSecurityConfig`
980
+ * in hook/pretool). `rm ~/.rafter/config.json` disarms the gate exactly as
981
+ * `rafter agent config set agent.hooks.enabled false` does.
982
+ *
983
+ * Deny-by-default scoped to the path, NOT a blocklist of write verbs: the
984
+ * verbs are unbounded (`>`, sed -i, cp, tee, dd, install, rsync, perl -i,
985
+ * python -c …). A command is protected when a statement that NAMES the
986
+ * rafter dir is not a known read-only command without an output redirect.
987
+ * Statements that do not name it are not constrained, so
988
+ * `cat ~/.rafter/x && npm test` stays allowed; a cd INTO the dir is itself
989
+ * not read-only, which keeps `cd ~/.rafter && echo x > config.json` blocked.
990
+ *
991
+ * Checked on the raw text (a reference inside quotes counts — python -c
992
+ * code, heredoc bodies) and on the normalized view, which expands brace
993
+ * lists and ANSI-C quotes (`~/.{rafter,x}`, `$'\x2erafter'`).
994
+ */
995
+ function writesRafterDir(command) {
996
+ if (rafterDirScan(command))
997
+ return true;
998
+ const normalized = normalizeForMatching(command);
999
+ return normalized !== command && rafterDirScan(normalized);
1000
+ }
1001
+ const RAFTER_DIR_NAME = ".rafter";
1002
+ /** Characters that continue a file name: `.rafter.yml` and `.rafterignore` are not `.rafter`. */
1003
+ function isNameChar(c) {
1004
+ return /[a-z0-9_.-]/i.test(c);
1005
+ }
1006
+ /**
1007
+ * True if `text` names the rafter dir: `.rafter` as a whole path component
1008
+ * (so `~/.rafter`, `$HOME/.rafter`, `${HOME}/.rafter`, `/home/u/.rafter`,
1009
+ * `./.rafter/x`, `'.rafter'` inside code), case-insensitively because macOS
1010
+ * file systems are. An unquoted glob component that could expand to it
1011
+ * (`~/.raf*`, `.r?fter`, `.*`) counts too. Linear: one indexOf walk plus one
1012
+ * pass over components.
1013
+ */
1014
+ function namesRafterDir(text, globs) {
1015
+ const t = text.toLowerCase();
1016
+ for (let i = t.indexOf(RAFTER_DIR_NAME); i !== -1; i = t.indexOf(RAFTER_DIR_NAME, i + 1)) {
1017
+ const before = i === 0 ? "" : t[i - 1];
1018
+ const after = t[i + RAFTER_DIR_NAME.length] ?? "";
1019
+ if ((before === "" || !isNameChar(before)) && (after === "" || !isNameChar(after)))
1020
+ return true;
1021
+ }
1022
+ if (!globs)
1023
+ return false;
1024
+ // Bash never lets a wildcard match a leading dot, so only a component that
1025
+ // starts with a literal "." can glob to ".rafter". Over-approximate the
1026
+ // match: the literal characters outside brackets must appear in order in
1027
+ // "rafter"; `*`, `?` and a whole `[...]` are free.
1028
+ for (const comp of t.split("/")) {
1029
+ if (comp[0] !== "." || !/[*?[]/.test(comp))
1030
+ continue;
1031
+ const want = "rafter";
1032
+ let k = 0;
1033
+ let inBracket = false;
1034
+ let ok = true;
1035
+ for (let j = 1; j < comp.length; j++) {
1036
+ const c = comp[j];
1037
+ if (inBracket) {
1038
+ if (c === "]")
1039
+ inBracket = false;
1040
+ continue;
1041
+ }
1042
+ if (c === "[") {
1043
+ inBracket = true;
1044
+ continue;
1045
+ }
1046
+ if (c === "*" || c === "?")
1047
+ continue;
1048
+ while (k < want.length && want[k] !== c)
1049
+ k++;
1050
+ if (k === want.length) {
1051
+ ok = false;
1052
+ break;
1053
+ }
1054
+ k++;
1055
+ }
1056
+ if (ok)
1057
+ return true;
1058
+ }
1059
+ return false;
1060
+ }
1061
+ /**
1062
+ * Read-only commands: they can neither write a file nor run another program
1063
+ * when given no output redirect. Deliberately narrow. NOT here: sed (its `w`
1064
+ * and `e` commands write and execute without -i), less (`-o` writes a log),
1065
+ * tee/cp/mv/rm/ln/chmod/touch/truncate/dd, and anything that runs a program.
1066
+ */
1067
+ const READ_ONLY_EXECS = new Set([
1068
+ "cat", "more", "head", "tail", "ls", "stat", "file", "wc",
1069
+ "grep", "egrep", "fgrep", "rg", "jq", "diff", "cmp",
1070
+ "md5sum", "sha1sum", "sha224sum", "sha256sum", "sha384sum", "sha512sum",
1071
+ "shasum", "b2sum", "cksum",
1072
+ "find", "test", "[", "realpath", "readlink", "du",
1073
+ "cd", "pushd", "popd",
1074
+ ]);
1075
+ /** find actions that delete, run a program, or write a file. */
1076
+ const FIND_WRITE_ACTIONS = new Set([
1077
+ "-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls",
1078
+ ]);
1079
+ /** Only a bare name or a system bin dir: `./cat` is whatever the agent wrote there. */
1080
+ const SYSTEM_BIN = /^(?:\/usr(?:\/local)?|\/opt\/homebrew)?\/s?bin\/[^/]+$/;
1081
+ const WRITE_REDIRECTS = new Set([">", ">>"]);
1082
+ /** True if some statement names the rafter dir and is not read-only. */
1083
+ function rafterDirScan(command) {
1084
+ const acc = { protected: false };
1085
+ scanRafterDirStatements(command, 0, acc);
1086
+ return acc.protected;
1087
+ }
1088
+ function scanRafterDirStatements(command, depth, acc) {
1089
+ // Past the recursion cap, or on a desynchronized parse, the structure is
1090
+ // unknown: FAIL CLOSED — a reference anywhere in the text protects it.
1091
+ if (depth > MAX_SANITIZE_DEPTH) {
1092
+ if (namesRafterDir(command, false))
1093
+ acc.protected = true;
1094
+ return;
1095
+ }
1096
+ const { pieces, unterminated } = tokenize(command);
1097
+ if (unterminated && namesRafterDir(command, false))
1098
+ acc.protected = true;
1099
+ let stmt = [];
1100
+ const flush = () => { scanRafterDirStatement(stmt, acc); stmt = []; };
1101
+ for (let i = 0; i < pieces.length; i++) {
1102
+ const p = pieces[i];
1103
+ for (const sub of p.substs)
1104
+ scanRafterDirStatements(sub, depth + 1, acc);
1105
+ if (p.op !== null && CHAIN_OPS.has(p.op)) {
1106
+ // `>|`, `>&`, `&>`, `&>>` are redirects spelled with a chain character;
1107
+ // splitting on them would orphan the target from its `>`.
1108
+ const prev = pieces[i - 1];
1109
+ const next = pieces[i + 1];
1110
+ const afterRedirect = p.op !== "&&" && p.op !== "||" && !!prev && prev.end === p.start && WRITE_REDIRECTS.has(prev.op ?? "");
1111
+ const beforeRedirect = p.op === "&" && !!next && next.start === p.end && WRITE_REDIRECTS.has(next.op ?? "");
1112
+ if (!afterRedirect && !beforeRedirect) {
1113
+ flush();
1114
+ continue;
1115
+ }
1116
+ }
1117
+ stmt.push(p);
1118
+ }
1119
+ flush();
1120
+ }
1121
+ function scanRafterDirStatement(stmt, acc) {
1122
+ let argv0 = -1;
1123
+ let redirect = false;
1124
+ let names = false;
1125
+ for (let i = 0; i < stmt.length; i++) {
1126
+ const p = stmt[i];
1127
+ if (p.op !== null) {
1128
+ if (WRITE_REDIRECTS.has(p.op) && !discardsOutput(stmt, i))
1129
+ redirect = true;
1130
+ continue;
1131
+ }
1132
+ const prevOp = i > 0 ? stmt[i - 1].op : null;
1133
+ const isRedirectTarget = prevOp !== null && REDIRECT_OPS.has(prevOp);
1134
+ // Executing a binary that lives in the dir (`~/.rafter/bin/betterleaks
1135
+ // version`) is not a reference; its arguments still are. Only an UNQUOTED
1136
+ // argv0 is a path the shell runs: a quoted one is a heredoc body line or
1137
+ // other code (`open('/home/u/.rafter/config.json','w')`), never a binary.
1138
+ if (argv0 === -1 && !isRedirectTarget) {
1139
+ argv0 = i;
1140
+ if (!p.quoted && !ENV_ASSIGNMENT.test(p.text))
1141
+ continue;
1142
+ }
1143
+ if (namesRafterDir(p.text, !p.quoted))
1144
+ names = true;
1145
+ }
1146
+ if (names && (redirect || !statementReadOnly(stmt, argv0)))
1147
+ acc.protected = true;
1148
+ }
1149
+ /** `2>/dev/null`, `2>&1`, `>&-`: an output redirect that writes no file. */
1150
+ function discardsOutput(stmt, i) {
1151
+ let j = i + 1;
1152
+ let dup = false;
1153
+ if (stmt[j]?.op === "&" && stmt[j].start === stmt[i].end) {
1154
+ dup = true;
1155
+ j++;
1156
+ }
1157
+ const target = stmt[j];
1158
+ if (!target || target.op !== null || target.substs.length > 0)
1159
+ return false;
1160
+ return dup ? /^(?:\d+|-)$/.test(target.text) : target.text === "/dev/null";
1161
+ }
1162
+ function statementReadOnly(stmt, argv0) {
1163
+ if (argv0 === -1)
1164
+ return true; // empty, or only an input redirect
1165
+ const head = stmt[argv0];
1166
+ if (!head.quoted && ENV_ASSIGNMENT.test(head.text))
1167
+ return false;
1168
+ if (head.text.includes("/") && !SYSTEM_BIN.test(head.text))
1169
+ return false;
1170
+ const exec = head.text.slice(head.text.lastIndexOf("/") + 1);
1171
+ if (!READ_ONLY_EXECS.has(exec))
1172
+ return false;
1173
+ const args = stmt.slice(argv0 + 1).filter((p) => p.op === null);
1174
+ switch (exec) {
1175
+ case "find":
1176
+ return !args.some((a) => FIND_WRITE_ACTIONS.has(a.text));
1177
+ case "rg": // --pre runs a program on every file searched
1178
+ return !args.some((a) => a.text.startsWith("--pre"));
1179
+ case "file": // -C compiles a magic file, writing it
1180
+ return !args.some((a) => a.text === "--compile" || /^-[A-Za-z]*C/.test(a.text));
1181
+ case "cd":
1182
+ case "pushd":
1183
+ case "popd":
1184
+ // Claude Code's Bash tool keeps its cwd between calls, so a cd INTO the
1185
+ // dir would make the next call's bare `config.json` a write there with
1186
+ // no reference left to catch. cd elsewhere stays read-only.
1187
+ return !args.some((a) => a.substs.length > 0 || namesRafterDir(a.text, !a.quoted));
1188
+ default:
1189
+ return true;
1190
+ }
1191
+ }
975
1192
  /** True if any statement (or any command substitution) disarms rafter. */
976
1193
  function disarmsRafter(command, depth = 0) {
977
1194
  if (depth > MAX_SANITIZE_DEPTH)
@@ -7,76 +7,97 @@ import path from "path";
7
7
  const execFileAsync = promisify(execFile);
8
8
  /** Per-invocation timeout for the betterleaks subprocess. */
9
9
  const SCAN_TIMEOUT_MS = 60000;
10
+ /** Config env vars betterleaks consults before the target's own .toml, in its order. */
11
+ const CONFIG_PATH_ENV_VARS = ["BETTERLEAKS_CONFIG", "GITLEAKS_CONFIG"];
12
+ const CONFIG_TOML_ENV_VARS = ["BETTERLEAKS_CONFIG_TOML", "GITLEAKS_CONFIG_TOML"];
10
13
  /**
11
- * Budget for the path arguments of one `betterleaks dir` call. Windows caps a
12
- * whole command line at 32,767 characters; elsewhere the limit is far larger.
14
+ * Paths under `dirPath` that a git-aware scan must skip, relative to it: what
15
+ * git ignores (a wholly ignored directory as one `dir/` entry), submodules (a
16
+ * gitlink, mode 160000, in the index) and untracked nested repositories (which
17
+ * `ls-files --others` lists as one `dir/` entry). Git lists no files inside
18
+ * either kind, so the file-list scan this replaced never scanned them. A
19
+ * tracked path that is now a directory on disk is NOT skipped: its files are
20
+ * untracked and get scanned. Returns null when `dirPath` is not inside a git
21
+ * work tree or git is unavailable, so the caller scans the directory whole.
13
22
  */
14
- const ARG_CHARS_PER_CALL = process.platform === "win32" ? 24000 : 500000;
23
+ export function gitSkippedPaths(dirPath) {
24
+ const ls = (...args) => {
25
+ const r = spawnSync("git", ["-C", dirPath, "ls-files", "-z", ...args, "--", "."], {
26
+ encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 30000, maxBuffer: 256 * 1024 * 1024,
27
+ });
28
+ if (r.status !== 0 || typeof r.stdout !== "string")
29
+ return null;
30
+ return r.stdout.split("\0").filter(Boolean);
31
+ };
32
+ const ignored = ls("--others", "--ignored", "--exclude-standard", "--directory");
33
+ const staged = ls("--cached", "--stage");
34
+ const untracked = ls("--others", "--exclude-standard");
35
+ if (ignored === null || staged === null || untracked === null)
36
+ return null;
37
+ // `--stage` lines read "<mode> <object> <stage>\t<path>".
38
+ const submodules = staged.filter((l) => l.startsWith("160000 ")).map((l) => l.slice(l.indexOf("\t") + 1));
39
+ const nestedRepos = untracked.filter((rel) => rel.endsWith("/"));
40
+ return [...ignored, ...submodules, ...nestedRepos];
41
+ }
15
42
  /**
16
- * Maximum number of file paths handed to one `betterleaks dir` invocation.
17
- *
18
- * sable-jiqb — betterleaks' run time scales with the length of the explicit
19
- * file list it is given (measured ~0.2s/file: 50 files ~10s, 300 files ~60s),
20
- * not with the size of the files. A whole git-tracked list on a few-hundred-file
21
- * repo therefore exceeds SCAN_TIMEOUT_MS in a single call and the engine falls
22
- * back to patterns. Capping each call at this many files keeps every invocation
23
- * well under the timeout (~0.2s * 64 ~= 13s, roughly a fifth of the 60s floor,
24
- * leaving headroom on a loaded box); the full tree is covered across as many
25
- * sequential calls as it takes, and their findings are unioned by file.
43
+ * Write `s` as a TOML basic string. JSON escapes every control character
44
+ * TOML forbids raw except DEL (U+007F), which would make the whole config
45
+ * unreadable and drop the scan to the patterns engine.
26
46
  */
27
- export const MAX_FILES_PER_CALL = 64;
28
- /** Config env vars betterleaks consults before the target's own .toml. */
29
- const CONFIG_ENV_VARS = [
30
- "BETTERLEAKS_CONFIG", "GITLEAKS_CONFIG", "BETTERLEAKS_CONFIG_TOML", "GITLEAKS_CONFIG_TOML",
31
- ];
47
+ function tomlString(s) {
48
+ return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
49
+ }
32
50
  /**
33
- * Files under `dirPath` that git does not ignore (tracked, plus untracked and
34
- * not ignored), as absolute paths. Returns null when `dirPath` is not inside a
35
- * git work tree or git is unavailable, so the caller scans the directory whole.
51
+ * A regex (RE2, JS and Python read it alike) matching `p` and everything below
52
+ * it. Only on Windows is `\\` a separator; on POSIX it is an ordinary filename
53
+ * character and stays literal, or an ignored `a\\b` would also skip `a/b`.
36
54
  */
37
- export function gitVisibleFiles(dirPath) {
38
- const r = spawnSync("git", ["-C", dirPath, "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "."], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 30000, maxBuffer: 256 * 1024 * 1024 });
39
- if (r.status !== 0 || typeof r.stdout !== "string")
40
- return null;
41
- const files = new Set();
42
- for (const rel of r.stdout.split("\0")) {
43
- if (!rel)
44
- continue;
45
- const abs = path.join(dirPath, rel);
46
- try {
47
- // Skip deleted-but-tracked paths, submodule dirs and symlinks (betterleaks
48
- // does not follow symlinks by default either).
49
- if (fs.lstatSync(abs).isFile())
50
- files.add(abs);
51
- }
52
- catch {
53
- // deleted from the work tree
54
- }
55
- }
56
- return [...files];
55
+ function pathPrefixPattern(p) {
56
+ const slashed = (process.platform === "win32" ? p.replace(/\\/g, "/") : p).replace(/\/+$/, "");
57
+ return "^" + slashed.replace(/[\\.+*?()|[\]{}^$]/g, "\\$&") + "(?:/.*)?$";
57
58
  }
58
59
  /**
59
- * Split `paths` into groups that stay within both bounds: at most `maxCount`
60
- * paths per group (sable-jiqb — betterleaks' cost scales with the file count,
61
- * so this is what keeps each invocation under the timeout) and a joined length
62
- * under `budget` chars (the OS command-line cap, the original #262 constraint).
60
+ * The betterleaks config for one git-aware directory scan: the config the scan
61
+ * would otherwise use (`baseToml`, its text; betterleaks' default rules when
62
+ * null) plus a global path allowlist for `skipped`, so one
63
+ * `betterleaks dir <root>` walk passes over those paths without reading them.
64
+ *
65
+ * The base config is copied in, not extended: betterleaks 1.1.x stops
66
+ * following `[extend]` two levels down, so wrapping a repo config that itself
67
+ * extends a shared config (which extends the defaults) silently dropped the
68
+ * default rules. A relative `extend.path` in the copy still resolves as it
69
+ * did, against the working directory. The deprecated `[allowlist]` table is
70
+ * renamed to `[[allowlists]]`, its equivalent, since betterleaks rejects a
71
+ * config that has both.
72
+ *
73
+ * #262 — rafter used to hand betterleaks the git-visible files as path
74
+ * arguments, 64 per call. betterleaks 1.1.x rebuilds its config and detector
75
+ * for every path argument (~0.2s each with the default rules), and its
76
+ * `extend` depth counter is a process global it never resets, so with a config
77
+ * that extends another (`[extend] useDefault = true`) only the first two path
78
+ * arguments of a call got the extended rules: every later file was scanned
79
+ * with the repo's own rules alone. A single walk builds one detector and
80
+ * applies the full rule set to every file.
63
81
  */
64
- function chunkFiles(paths, budget, maxCount) {
65
- const chunks = [];
66
- let cur = [];
67
- let len = 0;
68
- for (const p of paths) {
69
- if (cur.length > 0 && (cur.length >= maxCount || len + p.length + 1 > budget)) {
70
- chunks.push(cur);
71
- cur = [];
72
- len = 0;
73
- }
74
- cur.push(p);
75
- len += p.length + 1;
76
- }
77
- if (cur.length > 0)
78
- chunks.push(cur);
79
- return chunks;
82
+ export function scanConfigToml(dirPath, skipped, baseToml) {
83
+ const patterns = [
84
+ "(?:^|/)\\.git(?:/.*)?$",
85
+ ...skipped.map((rel) => pathPrefixPattern(path.join(dirPath, rel))),
86
+ ];
87
+ const base = baseToml === null
88
+ ? ["[extend]", "useDefault = true"]
89
+ : [baseToml.replace(/^[ \t]*\[[ \t]*allowlist[ \t]*\][ \t]*(#.*)?$/gm, "[[allowlists]]")];
90
+ return [
91
+ "# Generated by rafter for one scan (scanConfigToml, rafter's betterleaks scanner).",
92
+ ...base,
93
+ "",
94
+ "[[allowlists]]",
95
+ 'description = "rafter: paths git ignores"',
96
+ "paths = [",
97
+ ...patterns.map((p) => ` ${tomlString(p)},`),
98
+ "]",
99
+ "",
100
+ ].join("\n");
80
101
  }
81
102
  /** Name why a betterleaks subprocess failed: a timeout reads differently from a crash. */
82
103
  function describeFailure(e) {
@@ -190,8 +211,8 @@ export class BetterleaksScanner {
190
211
  * walks node_modules, build output and local secret stores (.env) alike:
191
212
  * slow enough to hit the timeout on an ordinary checkout, and noisy (#262).
192
213
  * With respectGitignore (the default, matching the patterns engine) and a
193
- * target inside a git work tree, it is handed git's own list of non-ignored
194
- * files instead.
214
+ * target inside a git work tree, it walks the tree once under a generated
215
+ * config that skips what git ignores (see scanConfigToml).
195
216
  */
196
217
  async scanDirectory(dirPath, opts) {
197
218
  const blPath = await this.resolveBinary();
@@ -201,26 +222,36 @@ export class BetterleaksScanner {
201
222
  if (opts?.useGit) {
202
223
  return this.groupByFile(await this.runDir(blPath, "git", [dirPath], []));
203
224
  }
204
- const files = opts?.respectGitignore === false ? null : gitVisibleFiles(dirPath);
205
- if (files === null) {
225
+ const skipped = opts?.respectGitignore === false ? null : gitSkippedPaths(dirPath);
226
+ if (skipped === null) {
206
227
  return this.groupByFile(await this.runDir(blPath, "dir", [dirPath], []));
207
228
  }
208
- // Given file paths instead of a directory, betterleaks no longer finds the
209
- // target's own .betterleaks.toml / .gitleaks.toml, so pass it explicitly
210
- // unless an env var already chooses the config (it outranks the file).
211
- const configArgs = [];
212
- if (!CONFIG_ENV_VARS.some((v) => process.env[v])) {
213
- const cfg = [".betterleaks.toml", ".gitleaks.toml"]
229
+ // Private 0700 dir, atomically created — see scanFile for the TOCTOU rationale (CWE-367).
230
+ const cfgDir = fs.mkdtempSync(path.join(os.tmpdir(), "betterleaks-cfg-"));
231
+ try {
232
+ // The generated config is passed as -c, which outranks every other
233
+ // source, so it carries whichever config betterleaks would have chosen,
234
+ // in betterleaks' own order: env path, env content, the target's file.
235
+ const envPath = CONFIG_PATH_ENV_VARS.map((v) => process.env[v]).find(Boolean);
236
+ const envToml = CONFIG_TOML_ENV_VARS.map((v) => process.env[v]).find(Boolean);
237
+ const repoPath = [".betterleaks.toml", ".gitleaks.toml"]
214
238
  .map((n) => path.join(dirPath, n))
215
239
  .find((p) => fs.existsSync(p));
216
- if (cfg)
217
- configArgs.push("-c", cfg);
240
+ const baseToml = envPath
241
+ ? fs.readFileSync(envPath, "utf-8")
242
+ : envToml ?? (repoPath ? fs.readFileSync(repoPath, "utf-8") : null);
243
+ const cfg = path.join(cfgDir, "scan.toml");
244
+ fs.writeFileSync(cfg, scanConfigToml(dirPath, skipped, baseToml));
245
+ return this.groupByFile(await this.runDir(blPath, "dir", [dirPath], ["-c", cfg]));
218
246
  }
219
- const findings = [];
220
- for (const chunk of chunkFiles(files, ARG_CHARS_PER_CALL, MAX_FILES_PER_CALL)) {
221
- findings.push(...(await this.runDir(blPath, "dir", chunk, configArgs)));
247
+ finally {
248
+ try {
249
+ fs.rmSync(cfgDir, { recursive: true, force: true });
250
+ }
251
+ catch {
252
+ // ignore
253
+ }
222
254
  }
223
- return this.groupByFile(findings);
224
255
  }
225
256
  /** One betterleaks invocation; returns its findings or throws with the cause. */
226
257
  async runDir(blPath, subcommand, targets, extraArgs) {
@@ -82,7 +82,8 @@ export class RegexScanner {
82
82
  ".ruff_cache",
83
83
  "results",
84
84
  ".terraform",
85
- "bower_components"
85
+ "bower_components",
86
+ ".trigger", // Trigger.dev build output (bundled JS + source maps)
86
87
  ];
87
88
  // Merge policy excludePaths into the exclude list
88
89
  if (options?.excludePaths) {
package/dist/utils/api.js CHANGED
@@ -106,7 +106,11 @@ export function handle403(e) {
106
106
  if (typeof body === "object" && body?.scan_mode) {
107
107
  const mode = body.scan_mode;
108
108
  const limit = body.limit ?? "?";
109
- const used = body.used ?? limit;
109
+ // The API sends `remaining`, not `used`; `used` is kept for older servers.
110
+ const used = body.used ??
111
+ (typeof body.limit === "number" && typeof body.remaining === "number"
112
+ ? body.limit - body.remaining
113
+ : limit);
110
114
  console.error(`Error: ${mode.charAt(0).toUpperCase() + mode.slice(1)} scan limit reached (${used}/${limit} used this billing period).\nUpgrade your plan or wait for your quota to reset.`);
111
115
  return EXIT_QUOTA_EXHAUSTED;
112
116
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rafter-security/cli",
3
- "version": "0.11.2",
3
+ "version": "0.11.4",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: rafter-security
3
3
  description: Security toolkit for AI workflows. Use when scanning code or repos for vulnerabilities, auditing third-party skills/MCPs/agent configs before installing, evaluating shell commands before running them, or generating secure design questions for new features. Provides `rafter run` (remote SAST + SCA, needs RAFTER_API_KEY), `rafter secrets` (offline secrets-only), `rafter agent exec --dry-run` (command-risk classification), and `rafter skill review`.
4
- version: 0.11.2
4
+ version: 0.11.4
5
5
  homepage: https://rafter.so
6
6
  metadata:
7
7
  openclaw:
@@ -113,6 +113,7 @@ rafter usage # check API quota
113
113
 
114
114
  Full CLI tree: **Read `docs/cli-reference.md`**. Full digest: `rafter brief commands`.
115
115
 
116
+ **Scan budget:** Remote scans spend the user's quota. `rafter run` scans the **pushed** branch, so re-running without a new push repeats it — run it once per task or before a PR and reuse `rafter get <scan-id>`; while iterating scan only changes (`rafter secrets --staged` / `--diff <ref>`); never loop, retry, or `--watch` from an agent session — exit `3` means quota exhausted, so stop, tell the user, and check `rafter usage`.
116
117
  ## Configuration
117
118
 
118
119
  `rafter run` (the full code scan) needs an API key: