@rafter-security/cli 0.8.6 → 0.8.9
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.
- package/dist/commands/agent/audit-skill.js +82 -6
- package/dist/commands/agent/config.js +12 -4
- package/dist/commands/agent/exec.js +16 -13
- package/dist/commands/agent/index.js +4 -0
- package/dist/commands/agent/init.js +38 -0
- package/dist/commands/agent/remove-skill-scanner.js +16 -0
- package/dist/commands/agent/scan.js +35 -71
- package/dist/commands/agent/update-skill-scanner.js +40 -0
- package/dist/commands/hook/posttool.js +23 -5
- package/dist/commands/hook/pretool.js +32 -19
- package/dist/commands/mcp/server.js +49 -4
- package/dist/commands/skill/review.js +138 -5
- package/dist/core/config-manager.js +43 -4
- package/dist/core/policy-loader.js +2 -2
- package/dist/core/suppression-writer.js +93 -0
- package/dist/scanners/git-diff-scan.js +23 -0
- package/dist/scanners/regex-scanner.js +9 -0
- package/dist/scanners/skill-scanner.js +404 -0
- package/dist/utils/api.js +14 -1
- package/dist/utils/git-diff.js +85 -0
- package/package.json +1 -1
- package/resources/rafter-security-skill.md +1 -1
- package/resources/skills/rafter/docs/finding-triage.md +3 -2
|
@@ -7,8 +7,9 @@ import { BetterleaksScanner } from "../../scanners/betterleaks.js";
|
|
|
7
7
|
import { unionScanResults } from "../../scanners/union.js";
|
|
8
8
|
import { CommandInterceptor } from "../../core/command-interceptor.js";
|
|
9
9
|
import { AuditLogger } from "../../core/audit-logger.js";
|
|
10
|
-
import { ConfigManager } from "../../core/config-manager.js";
|
|
10
|
+
import { ConfigManager, redactConfigSecrets, isSecretConfigKey, maskSecretValue } from "../../core/config-manager.js";
|
|
11
11
|
import { listDocs, resolveDocSelector, fetchDoc } from "../../core/docs-loader.js";
|
|
12
|
+
import { writeSuppression } from "../../core/suppression-writer.js";
|
|
12
13
|
import { createRequire } from "module";
|
|
13
14
|
const _require = createRequire(import.meta.url);
|
|
14
15
|
const { version: CLI_VERSION } = _require("../../../package.json");
|
|
@@ -113,6 +114,23 @@ export function createServer() {
|
|
|
113
114
|
required: ["id_or_tag"],
|
|
114
115
|
},
|
|
115
116
|
},
|
|
117
|
+
{
|
|
118
|
+
name: "suppress_finding",
|
|
119
|
+
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.",
|
|
120
|
+
inputSchema: {
|
|
121
|
+
type: "object",
|
|
122
|
+
properties: {
|
|
123
|
+
path: { type: "string", description: "File path or glob to suppress findings in (e.g. 'test/fixtures/**')" },
|
|
124
|
+
rules: {
|
|
125
|
+
type: "array",
|
|
126
|
+
items: { type: "string" },
|
|
127
|
+
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`.",
|
|
128
|
+
},
|
|
129
|
+
reason: { type: "string", description: "Why this is a false positive — persisted with the rule. Strongly recommended." },
|
|
130
|
+
},
|
|
131
|
+
required: ["path"],
|
|
132
|
+
},
|
|
133
|
+
},
|
|
116
134
|
],
|
|
117
135
|
}));
|
|
118
136
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
@@ -185,7 +203,12 @@ export function createServer() {
|
|
|
185
203
|
case "get_config": {
|
|
186
204
|
const manager = new ConfigManager();
|
|
187
205
|
const key = args?.key;
|
|
188
|
-
const
|
|
206
|
+
const raw = key ? manager.get(key) : manager.load();
|
|
207
|
+
// Never hand a stored credential (e.g. backend.apiKey) to the MCP client.
|
|
208
|
+
const leaf = key ? (key.split(".").pop() ?? key) : undefined;
|
|
209
|
+
const value = leaf && isSecretConfigKey(leaf) && typeof raw === "string"
|
|
210
|
+
? maskSecretValue(raw)
|
|
211
|
+
: redactConfigSecrets(raw);
|
|
189
212
|
return textResult(value);
|
|
190
213
|
}
|
|
191
214
|
case "list_docs": {
|
|
@@ -226,6 +249,28 @@ export function createServer() {
|
|
|
226
249
|
}
|
|
227
250
|
return textResult(results);
|
|
228
251
|
}
|
|
252
|
+
case "suppress_finding": {
|
|
253
|
+
const suppressPath = args?.path;
|
|
254
|
+
if (!suppressPath)
|
|
255
|
+
return errorResult("path is required");
|
|
256
|
+
const rules = Array.isArray(args?.rules)
|
|
257
|
+
? args.rules.map((r) => String(r))
|
|
258
|
+
: undefined;
|
|
259
|
+
const reason = args?.reason;
|
|
260
|
+
try {
|
|
261
|
+
const result = writeSuppression({ paths: [suppressPath], rules, reason });
|
|
262
|
+
return textResult({
|
|
263
|
+
ok: true,
|
|
264
|
+
file: result.file,
|
|
265
|
+
action: result.action,
|
|
266
|
+
entry: result.entry,
|
|
267
|
+
suppression_count: result.suppressionCount,
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
catch (err) {
|
|
271
|
+
return errorResult(`Failed to write suppression: ${err.message || err}`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
229
274
|
default:
|
|
230
275
|
return errorResult(`Unknown tool: ${name}`);
|
|
231
276
|
}
|
|
@@ -262,7 +307,7 @@ export function createServer() {
|
|
|
262
307
|
contents: [{
|
|
263
308
|
uri: "rafter://config",
|
|
264
309
|
mimeType: "application/json",
|
|
265
|
-
text: JSON.stringify(manager.load(), null, 2),
|
|
310
|
+
text: JSON.stringify(redactConfigSecrets(manager.load()), null, 2),
|
|
266
311
|
}],
|
|
267
312
|
};
|
|
268
313
|
case "rafter://policy":
|
|
@@ -270,7 +315,7 @@ export function createServer() {
|
|
|
270
315
|
contents: [{
|
|
271
316
|
uri: "rafter://policy",
|
|
272
317
|
mimeType: "application/json",
|
|
273
|
-
text: JSON.stringify(manager.loadWithPolicy(), null, 2),
|
|
318
|
+
text: JSON.stringify(redactConfigSecrets(manager.loadWithPolicy()), null, 2),
|
|
274
319
|
}],
|
|
275
320
|
};
|
|
276
321
|
case "rafter://docs": {
|
|
@@ -5,6 +5,7 @@ import os from "os";
|
|
|
5
5
|
import { spawnSync } from "child_process";
|
|
6
6
|
import { PatternEngine } from "../../core/pattern-engine.js";
|
|
7
7
|
import { DEFAULT_SECRET_PATTERNS } from "../../scanners/secret-patterns.js";
|
|
8
|
+
import { SkillScanner, ensureSkillScanner, deepSeverityTier, deepActionableCount, INSTALL_HINT, } from "../../scanners/skill-scanner.js";
|
|
8
9
|
import { fmt } from "../../utils/formatter.js";
|
|
9
10
|
import { discoverInstalledSkills, SKILL_PLATFORMS, } from "./registry.js";
|
|
10
11
|
import { isShorthand, parseShorthand, defaultCacheRoot, readResolution, writeResolution, resolutionIsFresh, contentKeyGit, contentKeyNpm, contentDir, contentWorkingTree, contentIsUsable, dropCacheEntry, defaultRemoteOps, extractNpmTarball, findSkillFiles, DEFAULT_CACHE_TTL_MS, } from "./remote.js";
|
|
@@ -705,7 +706,83 @@ function resolveNpm(input, parsed, opts) {
|
|
|
705
706
|
cleanup,
|
|
706
707
|
};
|
|
707
708
|
}
|
|
708
|
-
|
|
709
|
+
/** Render the deep-engine section for a single-skill text report. */
|
|
710
|
+
function renderDeepText(report) {
|
|
711
|
+
const deep = report.deepScan;
|
|
712
|
+
if (!deep)
|
|
713
|
+
return;
|
|
714
|
+
console.log(fmt.header("Deep engine (skill-scanner)"));
|
|
715
|
+
console.log(fmt.divider());
|
|
716
|
+
const actionable = deep.findings.filter((f) => ["critical", "high", "medium"].includes(f.severity));
|
|
717
|
+
if (actionable.length === 0) {
|
|
718
|
+
console.log(fmt.success("No critical/high/medium findings"));
|
|
719
|
+
}
|
|
720
|
+
else {
|
|
721
|
+
console.log(fmt.warning(`${actionable.length} finding(s) (max severity: ${deep.maxSeverity})`));
|
|
722
|
+
for (const f of actionable.slice(0, 10)) {
|
|
723
|
+
const loc = f.line ? ` (line ${f.line})` : "";
|
|
724
|
+
console.log(` • [${f.severity.toUpperCase()}] ${f.category}: ${f.title}${loc}`);
|
|
725
|
+
}
|
|
726
|
+
if (actionable.length > 10) {
|
|
727
|
+
console.log(` ... and ${actionable.length - 10} more`);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
if (deep.analyzersUsed.length > 0) {
|
|
731
|
+
console.log(` analyzers: ${deep.analyzersUsed.join(", ")} (offline only)`);
|
|
732
|
+
}
|
|
733
|
+
console.log();
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Run the opt-in deep engine on a single resolved skill path and fold its
|
|
737
|
+
* results into `report` (adds `deepScan`, escalates severity by actionable
|
|
738
|
+
* findings). Returns an error string when the engine failed (caller exits 2).
|
|
739
|
+
*/
|
|
740
|
+
async function attachDeepScan(report, scanPath, scanner) {
|
|
741
|
+
const dr = await scanner.scanPath(scanPath);
|
|
742
|
+
if (dr.error)
|
|
743
|
+
return { error: dr.error };
|
|
744
|
+
report.deepScan = {
|
|
745
|
+
engine: "skill-scanner",
|
|
746
|
+
maxSeverity: dr.maxSeverity,
|
|
747
|
+
analyzersUsed: dr.analyzersUsed,
|
|
748
|
+
findings: dr.findings,
|
|
749
|
+
};
|
|
750
|
+
const tier = deepSeverityTier(dr);
|
|
751
|
+
if (_SEVERITY_ORDER_LOCAL.indexOf(tier) >
|
|
752
|
+
_SEVERITY_ORDER_LOCAL.indexOf(report.summary.severity)) {
|
|
753
|
+
report.summary.severity = tier;
|
|
754
|
+
}
|
|
755
|
+
const actionable = deepActionableCount(dr);
|
|
756
|
+
if (actionable > 0) {
|
|
757
|
+
report.summary.findings += actionable;
|
|
758
|
+
report.summary.reasons.push(`deep engine: ${actionable} actionable finding(s)`);
|
|
759
|
+
}
|
|
760
|
+
return {};
|
|
761
|
+
}
|
|
762
|
+
/** After deep scans escalate per-skill severities, recompute the multi summary. */
|
|
763
|
+
function recomputeMultiSummary(report) {
|
|
764
|
+
const counts = {
|
|
765
|
+
clean: 0,
|
|
766
|
+
low: 0,
|
|
767
|
+
medium: 0,
|
|
768
|
+
high: 0,
|
|
769
|
+
critical: 0,
|
|
770
|
+
};
|
|
771
|
+
let worst = "clean";
|
|
772
|
+
let findings = 0;
|
|
773
|
+
for (const entry of report.skills) {
|
|
774
|
+
counts[entry.report.summary.severity] += 1;
|
|
775
|
+
findings += entry.report.summary.findings;
|
|
776
|
+
if (_SEVERITY_ORDER_LOCAL.indexOf(entry.report.summary.severity) >
|
|
777
|
+
_SEVERITY_ORDER_LOCAL.indexOf(worst)) {
|
|
778
|
+
worst = entry.report.summary.severity;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
report.summary.severityCounts = counts;
|
|
782
|
+
report.summary.findings = findings;
|
|
783
|
+
report.summary.worst = worst;
|
|
784
|
+
}
|
|
785
|
+
export async function runSkillReview(input, opts) {
|
|
709
786
|
let resolved = input;
|
|
710
787
|
let kind;
|
|
711
788
|
let cleanup = null;
|
|
@@ -777,6 +854,33 @@ export function runSkillReview(input, opts) {
|
|
|
777
854
|
else {
|
|
778
855
|
report = buildReport(input, resolved, kind, source);
|
|
779
856
|
}
|
|
857
|
+
// Optional DEEP engine (skill-scanner) — opt-in via --deep / --engine.
|
|
858
|
+
// Offline analyzers only; scans each resolved skill on disk. Availability
|
|
859
|
+
// is ensured by the caller (interactive install-offer); this is a safety net.
|
|
860
|
+
if (opts.deep) {
|
|
861
|
+
const scanner = new SkillScanner();
|
|
862
|
+
if (!scanner.isAvailable()) {
|
|
863
|
+
console.error(INSTALL_HINT);
|
|
864
|
+
return { report, exitCode: 2 };
|
|
865
|
+
}
|
|
866
|
+
if ("skills" in report) {
|
|
867
|
+
for (const entry of report.skills) {
|
|
868
|
+
const { error } = await attachDeepScan(entry.report, entry.report.target.resolvedPath, scanner);
|
|
869
|
+
if (error) {
|
|
870
|
+
console.error(fmt.error(`deep scan failed: ${error}`));
|
|
871
|
+
return { report, exitCode: 2 };
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
recomputeMultiSummary(report);
|
|
875
|
+
}
|
|
876
|
+
else {
|
|
877
|
+
const { error } = await attachDeepScan(report, resolved, scanner);
|
|
878
|
+
if (error) {
|
|
879
|
+
console.error(fmt.error(`deep scan failed: ${error}`));
|
|
880
|
+
return { report, exitCode: 2 };
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
780
884
|
const format = opts.json ? "json" : opts.format ?? "text";
|
|
781
885
|
if (format === "json") {
|
|
782
886
|
console.log(JSON.stringify(report, null, 2));
|
|
@@ -787,6 +891,7 @@ export function runSkillReview(input, opts) {
|
|
|
787
891
|
}
|
|
788
892
|
else {
|
|
789
893
|
renderText(report);
|
|
894
|
+
renderDeepText(report);
|
|
790
895
|
}
|
|
791
896
|
}
|
|
792
897
|
const sev = "skills" in report ? report.summary.worst : report.summary.severity;
|
|
@@ -803,7 +908,7 @@ export function runSkillReview(input, opts) {
|
|
|
803
908
|
}
|
|
804
909
|
}
|
|
805
910
|
const SEVERITY_ORDER = ["clean", "low", "medium", "high", "critical"];
|
|
806
|
-
export function runSkillReviewInstalled(opts) {
|
|
911
|
+
export async function runSkillReviewInstalled(opts) {
|
|
807
912
|
let filter;
|
|
808
913
|
if (opts.agent) {
|
|
809
914
|
const a = opts.agent;
|
|
@@ -824,8 +929,18 @@ export function runSkillReviewInstalled(opts) {
|
|
|
824
929
|
const platformCounts = {};
|
|
825
930
|
let findings = 0;
|
|
826
931
|
let worst = "clean";
|
|
932
|
+
// Deep engine availability is ensured once by the caller; this is a safety net.
|
|
933
|
+
const deepScanner = opts.deep ? new SkillScanner() : null;
|
|
934
|
+
if (opts.deep && !deepScanner.isAvailable()) {
|
|
935
|
+
throw new Error(INSTALL_HINT);
|
|
936
|
+
}
|
|
827
937
|
for (const d of discovered) {
|
|
828
938
|
const report = buildReport(d.path, d.path, "file");
|
|
939
|
+
if (deepScanner) {
|
|
940
|
+
const { error } = await attachDeepScan(report, d.path, deepScanner);
|
|
941
|
+
if (error)
|
|
942
|
+
throw new Error(`deep scan failed for ${d.path}: ${error}`);
|
|
943
|
+
}
|
|
829
944
|
installations.push({
|
|
830
945
|
platform: d.platform,
|
|
831
946
|
skill: d.name,
|
|
@@ -931,7 +1046,24 @@ export function createReviewCommand() {
|
|
|
931
1046
|
.option("--summary", "Print a terse human-readable table instead of JSON (only with --installed)")
|
|
932
1047
|
.option("--cache-ttl <duration>", "TTL for the persistent skill-cache resolution entries (e.g. 24h, 30m, 3600s). Default: 24h.", "24h")
|
|
933
1048
|
.option("--no-cache", "Bypass the persistent skill-cache; fetch fresh and skip writes.")
|
|
934
|
-
.
|
|
1049
|
+
.option("--deep", "Also run the optional DEEP engine (Cisco AI Defense skill-scanner): prompt injection, taint/dataflow, YARA, .pyc integrity. Offline analyzers only. Offers to install the engine if missing.")
|
|
1050
|
+
.option("--engine <engine>", "Deep engine selector. 'skill-scanner' is equivalent to --deep.")
|
|
1051
|
+
.action(async (input, opts) => {
|
|
1052
|
+
// Resolve / validate the deep engine selector up front.
|
|
1053
|
+
const wantDeep = !!opts.deep || opts.engine === "skill-scanner";
|
|
1054
|
+
if (opts.engine != null && opts.engine !== "skill-scanner") {
|
|
1055
|
+
console.error(fmt.error(`unknown --engine '${opts.engine}' (supported: skill-scanner)`));
|
|
1056
|
+
process.exit(2);
|
|
1057
|
+
}
|
|
1058
|
+
// If --deep is requested, make it easy: ensure the engine is present,
|
|
1059
|
+
// offering to install it interactively. Done once for all skills.
|
|
1060
|
+
if (wantDeep) {
|
|
1061
|
+
const scanner = await ensureSkillScanner({ json: !!opts.json || opts.format === "json" });
|
|
1062
|
+
if (!scanner) {
|
|
1063
|
+
console.error(INSTALL_HINT);
|
|
1064
|
+
process.exit(2);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
935
1067
|
if (opts.installed) {
|
|
936
1068
|
if (input) {
|
|
937
1069
|
console.error(fmt.error("Cannot pass both <path-or-url> and --installed. Use one."));
|
|
@@ -939,7 +1071,7 @@ export function createReviewCommand() {
|
|
|
939
1071
|
}
|
|
940
1072
|
let result;
|
|
941
1073
|
try {
|
|
942
|
-
result = runSkillReviewInstalled({ agent: opts.agent });
|
|
1074
|
+
result = await runSkillReviewInstalled({ agent: opts.agent, deep: wantDeep });
|
|
943
1075
|
}
|
|
944
1076
|
catch (e) {
|
|
945
1077
|
console.error(fmt.error(`${e instanceof Error ? e.message : String(e)}`));
|
|
@@ -965,8 +1097,9 @@ export function createReviewCommand() {
|
|
|
965
1097
|
console.error(fmt.error(e instanceof Error ? e.message : String(e)));
|
|
966
1098
|
process.exit(2);
|
|
967
1099
|
}
|
|
968
|
-
const { exitCode } = runSkillReview(input, {
|
|
1100
|
+
const { exitCode } = await runSkillReview(input, {
|
|
969
1101
|
...opts,
|
|
1102
|
+
deep: wantDeep,
|
|
970
1103
|
noCache: opts.cache === false,
|
|
971
1104
|
cacheTtlMs: ttlMs,
|
|
972
1105
|
});
|
|
@@ -5,6 +5,38 @@ import { loadPolicy } 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"]);
|
|
8
|
+
// Config keys whose *leaf name* names a bearer credential. Values under these
|
|
9
|
+
// keys must be masked before the config is shown to a human or handed to an MCP
|
|
10
|
+
// client — never logged or echoed in cleartext.
|
|
11
|
+
const SECRET_CONFIG_KEY_RE = /(api_?key|token|secret|password|passwd|credential)/i;
|
|
12
|
+
export function isSecretConfigKey(leafKey) {
|
|
13
|
+
return SECRET_CONFIG_KEY_RE.test(leafKey);
|
|
14
|
+
}
|
|
15
|
+
/** Mask a credential value, keeping a 4-char prefix for recognizability. */
|
|
16
|
+
export function maskSecretValue(value) {
|
|
17
|
+
if (typeof value !== "string" || value.length === 0)
|
|
18
|
+
return "****";
|
|
19
|
+
return value.length <= 4 ? "****" : `${value.slice(0, 4)}****`;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Deep-clone a config value, masking any string whose KEY name looks like a
|
|
23
|
+
* credential. Pure — never mutates the input (so the stored config is unchanged).
|
|
24
|
+
*/
|
|
25
|
+
export function redactConfigSecrets(value) {
|
|
26
|
+
if (Array.isArray(value)) {
|
|
27
|
+
return value.map((v) => redactConfigSecrets(v));
|
|
28
|
+
}
|
|
29
|
+
if (value && typeof value === "object") {
|
|
30
|
+
const out = {};
|
|
31
|
+
for (const [k, v] of Object.entries(value)) {
|
|
32
|
+
out[k] = isSecretConfigKey(k) && typeof v === "string"
|
|
33
|
+
? maskSecretValue(v)
|
|
34
|
+
: redactConfigSecrets(v);
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
8
40
|
/**
|
|
9
41
|
* Validate a parsed config JSON object, warning and falling back to defaults for invalid fields.
|
|
10
42
|
*/
|
|
@@ -128,13 +160,20 @@ export class ConfigManager {
|
|
|
128
160
|
* Save config to disk
|
|
129
161
|
*/
|
|
130
162
|
save(config) {
|
|
131
|
-
// Ensure directory exists
|
|
163
|
+
// Ensure directory exists (0700 — the dir can hold credentials/audit log).
|
|
132
164
|
const dir = path.dirname(this.configPath);
|
|
133
165
|
if (!fs.existsSync(dir)) {
|
|
134
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
166
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
167
|
+
}
|
|
168
|
+
// Write config 0600 — it may hold a backend API key. writeFileSync's `mode`
|
|
169
|
+
// only applies when the file is *created*, so chmod existing files too.
|
|
170
|
+
fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 0o600 });
|
|
171
|
+
try {
|
|
172
|
+
fs.chmodSync(this.configPath, 0o600);
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
// Best effort — chmod is a no-op/throws on some platforms (e.g. Windows).
|
|
135
176
|
}
|
|
136
|
-
// Write config
|
|
137
|
-
fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), "utf-8");
|
|
138
177
|
}
|
|
139
178
|
/**
|
|
140
179
|
* Update specific config values
|
|
@@ -27,8 +27,8 @@ const POLICY_FILE_CANDIDATES = [
|
|
|
27
27
|
* For each directory, check candidates in precedence order; the first hit
|
|
28
28
|
* wins. The walk only ascends — siblings are not considered.
|
|
29
29
|
*/
|
|
30
|
-
export function findPolicyFile() {
|
|
31
|
-
let dir =
|
|
30
|
+
export function findPolicyFile(startDir = process.cwd()) {
|
|
31
|
+
let dir = startDir;
|
|
32
32
|
const root = getGitRoot() || path.parse(dir).root;
|
|
33
33
|
while (true) {
|
|
34
34
|
for (const filename of POLICY_FILE_CANDIDATES) {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { execSync } from "child_process";
|
|
4
|
+
import yaml from "js-yaml";
|
|
5
|
+
import { findPolicyFile } from "./policy-loader.js";
|
|
6
|
+
function getGitRoot(cwd) {
|
|
7
|
+
try {
|
|
8
|
+
return execSync("git rev-parse --show-toplevel", {
|
|
9
|
+
cwd,
|
|
10
|
+
encoding: "utf-8",
|
|
11
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
12
|
+
}).trim();
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Normalize a rule for dedup comparison: an ignore rule is "the same" if it
|
|
20
|
+
* targets the same set of paths and the same set of rule names (order- and
|
|
21
|
+
* duplicate-insensitive). Reason is intentionally excluded — re-suppressing
|
|
22
|
+
* the same scope just updates the reason.
|
|
23
|
+
*/
|
|
24
|
+
function ruleKey(paths, rules) {
|
|
25
|
+
const norm = (xs) => Array.from(new Set((xs ?? []).map((x) => String(x)))).sort();
|
|
26
|
+
return JSON.stringify({ paths: norm(paths), rules: norm(rules) });
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Persist a finding suppression into the project's `.rafter.yml` `ignore`
|
|
30
|
+
* list. Resolves the policy file via the same precedence the loader uses;
|
|
31
|
+
* if none exists, creates a canonical `.rafter.yml` at the git root (or cwd).
|
|
32
|
+
*
|
|
33
|
+
* Merge semantics: if an existing ignore rule targets the same paths + rules,
|
|
34
|
+
* its reason is updated in place rather than appending a duplicate.
|
|
35
|
+
*/
|
|
36
|
+
export function writeSuppression(input) {
|
|
37
|
+
const paths = (input.paths ?? []).map((p) => String(p)).filter((p) => p.length > 0);
|
|
38
|
+
if (paths.length === 0) {
|
|
39
|
+
throw new Error('"paths" must be a non-empty array of file paths or globs.');
|
|
40
|
+
}
|
|
41
|
+
const rules = Array.isArray(input.rules)
|
|
42
|
+
? input.rules.map((r) => String(r)).filter((r) => r.length > 0)
|
|
43
|
+
: undefined;
|
|
44
|
+
const reason = typeof input.reason === "string" && input.reason.trim() ? input.reason.trim() : undefined;
|
|
45
|
+
const baseDir = input.cwd || process.cwd();
|
|
46
|
+
// Resolve target file: existing policy file wins; else canonical dotfile at git root / cwd.
|
|
47
|
+
let target = findPolicyFile(baseDir);
|
|
48
|
+
let action;
|
|
49
|
+
let raw = {};
|
|
50
|
+
if (target && fs.existsSync(target)) {
|
|
51
|
+
const content = fs.readFileSync(target, "utf-8");
|
|
52
|
+
const parsed = yaml.load(content);
|
|
53
|
+
raw = parsed && typeof parsed === "object" ? parsed : {};
|
|
54
|
+
action = "appended";
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
const root = getGitRoot(baseDir) || baseDir;
|
|
58
|
+
target = path.join(root, ".rafter.yml");
|
|
59
|
+
action = "created";
|
|
60
|
+
}
|
|
61
|
+
const ignoreList = Array.isArray(raw.ignore) ? raw.ignore : [];
|
|
62
|
+
const newEntry = { paths };
|
|
63
|
+
if (rules && rules.length > 0)
|
|
64
|
+
newEntry.rules = rules;
|
|
65
|
+
if (reason)
|
|
66
|
+
newEntry.reason = reason;
|
|
67
|
+
const key = ruleKey(paths, rules);
|
|
68
|
+
const existing = ignoreList.find((e) => e && typeof e === "object" && Array.isArray(e.paths) && ruleKey(e.paths, e.rules) === key);
|
|
69
|
+
if (existing) {
|
|
70
|
+
// Same scope already suppressed — update the reason in place.
|
|
71
|
+
if (reason)
|
|
72
|
+
existing.reason = reason;
|
|
73
|
+
else
|
|
74
|
+
delete existing.reason;
|
|
75
|
+
if (action !== "created")
|
|
76
|
+
action = "updated";
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
ignoreList.push(newEntry);
|
|
80
|
+
}
|
|
81
|
+
raw.ignore = ignoreList;
|
|
82
|
+
const dumped = yaml.dump(raw, { lineWidth: 100, noRefs: true, sortKeys: false });
|
|
83
|
+
const dir = path.dirname(target);
|
|
84
|
+
if (!fs.existsSync(dir))
|
|
85
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
86
|
+
fs.writeFileSync(target, dumped, "utf-8");
|
|
87
|
+
return {
|
|
88
|
+
file: target,
|
|
89
|
+
action,
|
|
90
|
+
entry: existing ? { ...newEntry, ...(existing.reason ? { reason: existing.reason } : {}) } : newEntry,
|
|
91
|
+
suppressionCount: ignoreList.length,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import { RegexScanner } from "./regex-scanner.js";
|
|
3
|
+
/**
|
|
4
|
+
* Scan only added/modified lines from a parsed git diff (+ side).
|
|
5
|
+
* Uses the patterns engine — git line scope is incompatible with betterleaks'
|
|
6
|
+
* whole-file `dir` scan (same as the PreToolUse staged hook).
|
|
7
|
+
*/
|
|
8
|
+
export function scanAddedDiffLines(addedLines, repoRoot, customPatterns) {
|
|
9
|
+
if (addedLines.length === 0)
|
|
10
|
+
return [];
|
|
11
|
+
const scanner = new RegexScanner(customPatterns);
|
|
12
|
+
const byFile = new Map();
|
|
13
|
+
for (const { file, line, text } of addedLines) {
|
|
14
|
+
const absPath = path.resolve(repoRoot, file);
|
|
15
|
+
const matches = scanner.scanLine(text, line);
|
|
16
|
+
if (matches.length === 0)
|
|
17
|
+
continue;
|
|
18
|
+
const existing = byFile.get(absPath) ?? [];
|
|
19
|
+
existing.push(...matches);
|
|
20
|
+
byFile.set(absPath, existing);
|
|
21
|
+
}
|
|
22
|
+
return [...byFile.entries()].map(([file, matches]) => ({ file, matches }));
|
|
23
|
+
}
|
|
@@ -92,6 +92,15 @@ export class RegexScanner {
|
|
|
92
92
|
scanText(text) {
|
|
93
93
|
return this.engine.scan(text);
|
|
94
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Scan a single line at a known file line number (git diff + side).
|
|
97
|
+
*/
|
|
98
|
+
scanLine(text, lineNumber) {
|
|
99
|
+
return this.engine.scanWithPosition(text).map((m) => ({
|
|
100
|
+
...m,
|
|
101
|
+
line: lineNumber,
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
95
104
|
/**
|
|
96
105
|
* Redact secrets from text
|
|
97
106
|
*/
|