@rafter-security/cli 0.10.5 → 0.11.1

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/exec.js +26 -9
  2. package/dist/commands/agent/init.js +286 -225
  3. package/dist/commands/agent/install-hook.js +19 -8
  4. package/dist/commands/agent/scan.js +270 -70
  5. package/dist/commands/agent/status.js +2 -2
  6. package/dist/commands/agent/update-skill-scanner.js +1 -1
  7. package/dist/commands/agent/verify.js +39 -15
  8. package/dist/commands/backend/get.js +6 -2
  9. package/dist/commands/backend/run.js +25 -2
  10. package/dist/commands/backend/scan-status.js +34 -4
  11. package/dist/commands/hook/pretool.js +124 -36
  12. package/dist/commands/mcp/server.js +184 -129
  13. package/dist/commands/report.js +6 -2
  14. package/dist/core/audit-logger.js +47 -17
  15. package/dist/core/config-manager.js +46 -8
  16. package/dist/core/custom-patterns.js +28 -8
  17. package/dist/core/docs-loader.js +33 -3
  18. package/dist/core/pattern-engine.js +23 -5
  19. package/dist/core/policy-loader.js +15 -4
  20. package/dist/core/risk-rules.js +391 -9
  21. package/dist/index.js +7 -1
  22. package/dist/scanners/betterleaks.js +127 -14
  23. package/dist/scanners/git-history-scan.js +75 -0
  24. package/dist/scanners/regex-scanner.js +16 -2
  25. package/dist/scanners/secret-patterns.js +5 -1
  26. package/dist/scanners/union.js +31 -19
  27. package/dist/utils/api.js +35 -1
  28. package/dist/utils/env-guard.js +14 -14
  29. package/dist/utils/git-diff.js +36 -20
  30. package/dist/utils/git.js +164 -52
  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
@@ -110,6 +110,9 @@ export function loadSuppressions(projectRoot = process.cwd()) {
110
110
  const file = path.join(projectRoot, ".rafterignore");
111
111
  if (!fs.existsSync(file))
112
112
  return [];
113
+ // `.rafterignore` globs are relative to the file's own directory, so anchor
114
+ // them there (sable-lu0j).
115
+ const baseDir = path.resolve(projectRoot);
113
116
  const suppressions = [];
114
117
  try {
115
118
  const lines = fs.readFileSync(file, "utf-8").split("\n");
@@ -119,13 +122,14 @@ export function loadSuppressions(projectRoot = process.cwd()) {
119
122
  continue;
120
123
  const colonIdx = line.indexOf(":");
121
124
  if (colonIdx === -1) {
122
- suppressions.push({ pathGlob: line, source: ".rafterignore" });
125
+ suppressions.push({ pathGlob: line, source: ".rafterignore", baseDir });
123
126
  }
124
127
  else {
125
128
  suppressions.push({
126
129
  pathGlob: line.slice(0, colonIdx).trim(),
127
130
  patternName: line.slice(colonIdx + 1).trim() || undefined,
128
131
  source: ".rafterignore",
132
+ baseDir,
129
133
  });
130
134
  }
131
135
  }
@@ -139,9 +143,12 @@ export function loadSuppressions(projectRoot = process.cwd()) {
139
143
  * Convert .rafter.yml ignore rules into the flat Suppression list used at scan time.
140
144
  * Each entry's path globs cross-product with its rule names.
141
145
  */
142
- export function policyIgnoreToSuppressions(rules) {
146
+ export function policyIgnoreToSuppressions(rules, baseDir) {
143
147
  if (!rules || rules.length === 0)
144
148
  return [];
149
+ // The globs are relative to the `.rafter.yml`'s own directory, so anchor
150
+ // them there (sable-lu0j) — a rule cannot match files outside that tree.
151
+ const anchor = baseDir ? path.resolve(baseDir) : undefined;
145
152
  const out = [];
146
153
  for (const rule of rules) {
147
154
  if (!Array.isArray(rule.paths) || rule.paths.length === 0)
@@ -154,6 +161,7 @@ export function policyIgnoreToSuppressions(rules) {
154
161
  patternName: ruleName,
155
162
  reason: rule.reason,
156
163
  source: ".rafter.yml",
164
+ baseDir: anchor,
157
165
  });
158
166
  }
159
167
  }
@@ -166,7 +174,7 @@ export function policyIgnoreToSuppressions(rules) {
166
174
  */
167
175
  export function findSuppression(filePath, patternName, suppressions) {
168
176
  for (const s of suppressions) {
169
- if (matchGlob(s.pathGlob, filePath)) {
177
+ if (matchGlob(s.pathGlob, filePath, s.baseDir)) {
170
178
  if (!s.patternName || s.patternName.toLowerCase() === patternName.toLowerCase()) {
171
179
  return s;
172
180
  }
@@ -186,7 +194,9 @@ export function applySuppressions(results, suppressions) {
186
194
  for (const r of results) {
187
195
  const kept = [];
188
196
  for (const m of r.matches) {
189
- const hit = findSuppression(r.file, m.pattern.name, suppressions);
197
+ // A merged finding is suppressed only when every engine's rule is.
198
+ const hits = (m.ruleNames ?? [m.pattern.name]).map((n) => findSuppression(r.file, n, suppressions));
199
+ const hit = hits.every(Boolean) ? hits[0] : null;
190
200
  if (hit) {
191
201
  suppressed.push({
192
202
  file: r.file,
@@ -213,7 +223,7 @@ export function applySuppressions(results, suppressions) {
213
223
  */
214
224
  export function isSuppressed(filePath, patternName, suppressions) {
215
225
  for (const s of suppressions) {
216
- if (matchGlob(s.pathGlob, filePath)) {
226
+ if (matchGlob(s.pathGlob, filePath, s.baseDir)) {
217
227
  if (!s.patternName || s.patternName.toLowerCase() === patternName.toLowerCase()) {
218
228
  return true;
219
229
  }
@@ -229,13 +239,23 @@ export function isSuppressed(filePath, patternName, suppressions) {
229
239
  * matching the glob against any suffix of the path so that relative globs
230
240
  * like `tests/fixtures/**` match absolute paths under any project root.
231
241
  */
232
- function matchGlob(glob, filePath) {
242
+ function matchGlob(glob, filePath, baseDir) {
233
243
  const g = glob.replace(/\\/g, "/");
234
- const f = filePath.replace(/\\/g, "/");
244
+ let f = filePath.replace(/\\/g, "/");
245
+ // When the rule has a base directory (sable-lu0j), the glob is relative to
246
+ // that tree: a file outside it never matches, and the glob is tested against
247
+ // the file's path relative to the base. This stops a relative rule in one
248
+ // tree's `.rafter.yml` from suppressing findings in another tree.
249
+ if (baseDir) {
250
+ const rel = path.relative(path.resolve(baseDir), path.resolve(filePath));
251
+ if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel))
252
+ return false;
253
+ f = rel.replace(/\\/g, "/");
254
+ }
235
255
  if (minimatch(f, g, { dot: true, matchBase: true }))
236
256
  return true;
237
257
  // Auto-anchor relative globs to "anywhere in the path" so that `tests/**`
238
- // matches `/abs/project/tests/foo`. Skip if the user already anchored.
258
+ // matches `project/tests/foo`. Skip if the user already anchored.
239
259
  if (g.startsWith("/") || g.startsWith("**/") || g.startsWith("**"))
240
260
  return false;
241
261
  return minimatch(f, "**/" + g, { dot: true });
@@ -50,9 +50,21 @@ function writeCache(url, body, contentType) {
50
50
  function isExpired(fetchedAt, ttlSeconds) {
51
51
  return Date.now() - fetchedAt > ttlSeconds * 1000;
52
52
  }
53
+ /**
54
+ * Resolve a policy `docs: path:` entry to an absolute file path, confined to
55
+ * the project root (sable-fwup).
56
+ *
57
+ * A path entry comes from a project `.rafter.yml`, so it is attacker-controlled
58
+ * for anyone who can land a file in the repo. Without containment, an absolute
59
+ * path or a `../` escape read any file on disk through `docs show` / the MCP
60
+ * `get_doc` tool. The path is confined to the git root (cwd when there is no
61
+ * repo): absolute paths are rejected, and the resolved path — after following
62
+ * symlinks — must stay inside the root.
63
+ */
53
64
  function resolvePolicyPath(relative) {
54
- if (path.isAbsolute(relative))
55
- return relative;
65
+ if (path.isAbsolute(relative)) {
66
+ throw new Error(`docs path must be relative to the project root: ${relative}`);
67
+ }
56
68
  let root;
57
69
  try {
58
70
  root = execSync("git rev-parse --show-toplevel", {
@@ -63,7 +75,25 @@ function resolvePolicyPath(relative) {
63
75
  catch {
64
76
  root = process.cwd();
65
77
  }
66
- return path.resolve(root, relative);
78
+ const realRoot = fs.realpathSync(root);
79
+ const abs = path.resolve(realRoot, relative);
80
+ // Lexical containment first, so a `../` escape is rejected before any file
81
+ // access.
82
+ const rel = path.relative(realRoot, abs);
83
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
84
+ throw new Error(`docs path escapes the project root: ${relative}`);
85
+ }
86
+ // Symlink containment: resolve the real path when the target exists and
87
+ // re-check, so an in-repo symlink cannot point outside the root.
88
+ if (fs.existsSync(abs)) {
89
+ const real = fs.realpathSync(abs);
90
+ const realRel = path.relative(realRoot, real);
91
+ if (realRel.startsWith("..") || path.isAbsolute(realRel)) {
92
+ throw new Error(`docs path resolves outside the project root: ${relative}`);
93
+ }
94
+ return real;
95
+ }
96
+ return abs;
67
97
  }
68
98
  /**
69
99
  * List docs from the active policy with resolution metadata.
@@ -7,8 +7,14 @@ const QUOTED_VALUE_RE = /['"]([^'"]+)['"]/;
7
7
  * followed immediately by `=` and a run of non-whitespace (the value). Used to
8
8
  * find `NAME=VALUE` tokens like `RAFTER_API_KEY=<secret> rafter ...` so their
9
9
  * value can be redacted before the command is written to the audit log.
10
+ *
11
+ * The prefix also accepts a leading quote (sable-fqrr): `agent exec`
12
+ * shell-quotes a token containing special characters, so a logged command can
13
+ * read `env 'SECRET_TOKEN=<secret>' ...` — a quote, not whitespace, sits
14
+ * before NAME=. Without this the value escaped redaction and reached the audit
15
+ * log in the clear.
10
16
  */
11
- const ENV_ASSIGN_RE = /(^|\s)([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g;
17
+ const ENV_ASSIGN_RE = /(^|[\s'"])([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g;
12
18
  /**
13
19
  * A `NAME` in a `NAME=VALUE` assignment is treated as secret-bearing when it
14
20
  * ends in a credential-suggesting word (e.g. RAFTER_API_KEY, GITHUB_TOKEN,
@@ -21,6 +27,17 @@ const SECRET_ENV_NAME_RE = /(?:^|_)(KEY|TOKEN|SECRET|SECRETS|PASSWORD|PASSWD|PWD
21
27
  export class PatternEngine {
22
28
  constructor(patterns) {
23
29
  this.patterns = patterns;
30
+ this.regexes = new Map(patterns.map((p) => [p, this.createRegex(p.regex)]));
31
+ }
32
+ /** The pattern's compiled regex, rewound for a fresh search. */
33
+ regexFor(pattern) {
34
+ let regex = this.regexes.get(pattern);
35
+ if (!regex) {
36
+ regex = this.createRegex(pattern.regex);
37
+ this.regexes.set(pattern, regex);
38
+ }
39
+ regex.lastIndex = 0;
40
+ return regex;
24
41
  }
25
42
  /**
26
43
  * Scan text for pattern matches
@@ -28,7 +45,7 @@ export class PatternEngine {
28
45
  scan(text) {
29
46
  const matches = [];
30
47
  for (const pattern of this.patterns) {
31
- const regex = this.createRegex(pattern.regex);
48
+ const regex = this.regexFor(pattern);
32
49
  let match;
33
50
  while ((match = regex.exec(text)) !== null) {
34
51
  if (this.isFalsePositive(pattern, match[0]))
@@ -51,7 +68,7 @@ export class PatternEngine {
51
68
  for (let lineNum = 0; lineNum < lines.length; lineNum++) {
52
69
  const line = lines[lineNum];
53
70
  for (const pattern of this.patterns) {
54
- const regex = this.createRegex(pattern.regex);
71
+ const regex = this.regexFor(pattern);
55
72
  let match;
56
73
  while ((match = regex.exec(line)) !== null) {
57
74
  if (this.isFalsePositive(pattern, match[0]))
@@ -82,7 +99,7 @@ export class PatternEngine {
82
99
  redactText(text) {
83
100
  let redacted = this.redactEnvAssignments(text);
84
101
  for (const pattern of this.patterns) {
85
- const regex = this.createRegex(pattern.regex);
102
+ const regex = this.regexFor(pattern);
86
103
  redacted = redacted.replace(regex, (match) => this.isFalsePositive(pattern, match) ? match : this.redact(match));
87
104
  }
88
105
  return redacted;
@@ -155,7 +172,8 @@ export class PatternEngine {
155
172
  const visibleChars = 4;
156
173
  const start = match.substring(0, visibleChars);
157
174
  const end = match.substring(match.length - visibleChars);
158
- const middle = "*".repeat(match.length - (visibleChars * 2));
175
+ // Cap the mask so a long token (a JWT) does not print a line of asterisks.
176
+ const middle = "*".repeat(Math.min(match.length - (visibleChars * 2), 16));
159
177
  return start + middle + end;
160
178
  }
161
179
  }
@@ -29,7 +29,10 @@ const POLICY_FILE_CANDIDATES = [
29
29
  */
30
30
  export function findPolicyFile(startDir = process.cwd()) {
31
31
  let dir = startDir;
32
- const root = getGitRoot() || path.parse(dir).root;
32
+ // Bound the walk by the git root of the START dir, not of the process cwd
33
+ // (sable-lu0j) — otherwise discovering a policy for a scan target in another
34
+ // tree stops at the wrong root.
35
+ const root = getGitRoot(startDir) || path.parse(dir).root;
33
36
  while (true) {
34
37
  for (const filename of POLICY_FILE_CANDIDATES) {
35
38
  const candidate = path.join(dir, filename);
@@ -48,8 +51,10 @@ export function findPolicyFile(startDir = process.cwd()) {
48
51
  /**
49
52
  * Load and parse the policy file, returning null if not found
50
53
  */
51
- export function loadPolicy() {
52
- const policyPath = findPolicyFile();
54
+ export function loadPolicy(baseDir) {
55
+ // Discover the policy from the scan target, not the process cwd (sable-lu0j):
56
+ // an ambient `.rafter.yml` in cwd must not govern a scan of a different tree.
57
+ const policyPath = findPolicyFile(baseDir ?? process.cwd());
53
58
  if (!policyPath)
54
59
  return null;
55
60
  try {
@@ -134,6 +139,11 @@ function mapPolicy(raw) {
134
139
  console.error(`Warning: skipping ignore entry — "paths" must be a non-empty array of strings.`);
135
140
  continue;
136
141
  }
142
+ // Dropping a non-list `rules` would widen the entry to every pattern.
143
+ if ("rules" in entry && !Array.isArray(entry.rules)) {
144
+ console.error(`Warning: skipping ignore entry — "rules" must be an array of strings.`);
145
+ continue;
146
+ }
137
147
  const rule = { paths: paths.map((p) => String(p)) };
138
148
  if (Array.isArray(entry.rules)) {
139
149
  rule.rules = entry.rules.map((r) => String(r));
@@ -376,10 +386,11 @@ function validatePolicy(policy, raw) {
376
386
  }
377
387
  return policy;
378
388
  }
379
- function getGitRoot() {
389
+ function getGitRoot(cwd) {
380
390
  try {
381
391
  return execSync("git rev-parse --show-toplevel", {
382
392
  encoding: "utf-8",
393
+ cwd: cwd && fs.existsSync(cwd) && fs.statSync(cwd).isDirectory() ? cwd : undefined,
383
394
  stdio: ["pipe", "pipe", "ignore"],
384
395
  }).trim();
385
396
  }