@rafter-security/cli 0.8.7 → 0.8.10
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/components.js +3 -1
- 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 +42 -1
- 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 +28 -5
- package/dist/commands/hook/pretool.js +37 -19
- package/dist/commands/mcp/server.js +9 -4
- package/dist/commands/skill/review.js +138 -5
- package/dist/core/command-interceptor.js +29 -3
- package/dist/core/config-manager.js +43 -4
- package/dist/core/risk-rules.js +14 -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 +4 -4
- package/resources/rafter-security-skill.md +1 -1
|
@@ -6,8 +6,9 @@ import { ConfigManager } from "../../core/config-manager.js";
|
|
|
6
6
|
import { applySuppressions } from "../../core/custom-patterns.js";
|
|
7
7
|
import { resolveHookControl } from "../../core/hook-control.js";
|
|
8
8
|
import { collectSuppressions, applyExcludePaths } from "../agent/scan.js";
|
|
9
|
+
import { scanAddedDiffLines } from "../../scanners/git-diff-scan.js";
|
|
10
|
+
import { parseUnifiedDiffAddedLines } from "../../utils/git-diff.js";
|
|
9
11
|
import { execSync } from "child_process";
|
|
10
|
-
import fs from "fs";
|
|
11
12
|
import path from "path";
|
|
12
13
|
/**
|
|
13
14
|
* Load the policy-merged scan config + suppression list the same way scan.ts
|
|
@@ -64,6 +65,11 @@ function formatApprovalMessage(command, evaluation) {
|
|
|
64
65
|
export function createHookPretoolCommand() {
|
|
65
66
|
return new Command("pretool")
|
|
66
67
|
.description("PreToolUse hook handler (reads stdin, writes JSON decision to stdout)")
|
|
68
|
+
// Tolerate extra flags/args the host harness appends to the hook command
|
|
69
|
+
// (e.g. Claude Code adds `--hook-json <data>`). Hook input comes from stdin,
|
|
70
|
+
// so anything else is unused — discard it instead of erroring out.
|
|
71
|
+
.allowUnknownOption()
|
|
72
|
+
.allowExcessArguments()
|
|
67
73
|
.option("--format <format>", "Output format: claude (default, also Codex/Continue), cursor, gemini, windsurf", "claude")
|
|
68
74
|
.action(async (opts) => {
|
|
69
75
|
const format = (opts.format || "claude");
|
|
@@ -256,22 +262,16 @@ export function scanStagedFiles(cwd = process.cwd()) {
|
|
|
256
262
|
};
|
|
257
263
|
try {
|
|
258
264
|
const repoRoot = execSync("git rev-parse --show-toplevel", gitOpts).trim() || cwd;
|
|
259
|
-
const
|
|
260
|
-
if (!
|
|
265
|
+
const patch = execSync("git diff -U0 --no-color --cached --diff-filter=ACM", gitOpts).trim();
|
|
266
|
+
if (!patch) {
|
|
261
267
|
return { ...empty, repoRoot };
|
|
262
268
|
}
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
const raw = [];
|
|
267
|
-
for (const file of stagedFiles) {
|
|
268
|
-
const filePath = path.resolve(repoRoot, file);
|
|
269
|
-
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile())
|
|
270
|
-
continue;
|
|
271
|
-
const r = scanner.scanFile(filePath);
|
|
272
|
-
if (r.matches.length > 0)
|
|
273
|
-
raw.push(r);
|
|
269
|
+
const addedLines = parseUnifiedDiffAddedLines(patch);
|
|
270
|
+
if (addedLines.length === 0) {
|
|
271
|
+
return { ...empty, repoRoot };
|
|
274
272
|
}
|
|
273
|
+
const { scanCfg, suppressions } = loadScanConfig(cwd);
|
|
274
|
+
const raw = scanAddedDiffLines(addedLines, repoRoot, scanCfg?.customPatterns);
|
|
275
275
|
const afterExclude = applyExcludePaths(raw, scanCfg?.excludePaths, repoRoot);
|
|
276
276
|
const { results: kept } = applySuppressions(afterExclude, suppressions);
|
|
277
277
|
const count = kept.reduce((sum, r) => sum + r.matches.length, 0);
|
|
@@ -316,15 +316,33 @@ export function formatStagedSecretReason(scan) {
|
|
|
316
316
|
"Run 'rafter secrets --staged' for full detail, or add an exclude_paths/ignore rule to .rafter.yml if this is a false positive.",
|
|
317
317
|
].join("\n");
|
|
318
318
|
}
|
|
319
|
-
|
|
319
|
+
// Bound the stdin read so a hung/never-closing stdin can't wedge the hook.
|
|
320
|
+
// Overridable via env (milliseconds) as an operator safety valve / for tests.
|
|
321
|
+
function stdinTimeoutMs() {
|
|
322
|
+
const n = Number(process.env.RAFTER_HOOK_STDIN_TIMEOUT_MS);
|
|
323
|
+
return Number.isFinite(n) && n > 0 ? n : 5000;
|
|
324
|
+
}
|
|
320
325
|
function readStdin() {
|
|
321
326
|
return new Promise((resolve) => {
|
|
322
327
|
let data = "";
|
|
323
|
-
const
|
|
328
|
+
const onData = (chunk) => { data += chunk; };
|
|
329
|
+
const finish = () => {
|
|
330
|
+
clearTimeout(timeout);
|
|
331
|
+
process.stdin.removeListener("data", onData);
|
|
332
|
+
process.stdin.removeListener("end", finish);
|
|
333
|
+
process.stdin.removeListener("error", finish);
|
|
334
|
+
// A piped stdin with no EOF stays in flowing mode and keeps the Node
|
|
335
|
+
// event loop alive indefinitely — even after we resolve. Pause it so the
|
|
336
|
+
// process can exit once the decision is written (was a hard hang on the
|
|
337
|
+
// timeout path: output emitted at 5s but the process never exited).
|
|
338
|
+
process.stdin.pause();
|
|
339
|
+
resolve(data);
|
|
340
|
+
};
|
|
341
|
+
const timeout = setTimeout(finish, stdinTimeoutMs());
|
|
324
342
|
process.stdin.setEncoding("utf-8");
|
|
325
|
-
process.stdin.on("data",
|
|
326
|
-
process.stdin.on("end",
|
|
327
|
-
process.stdin.on("error",
|
|
343
|
+
process.stdin.on("data", onData);
|
|
344
|
+
process.stdin.on("end", finish);
|
|
345
|
+
process.stdin.on("error", finish);
|
|
328
346
|
process.stdin.resume();
|
|
329
347
|
});
|
|
330
348
|
}
|
|
@@ -7,7 +7,7 @@ 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
12
|
import { writeSuppression } from "../../core/suppression-writer.js";
|
|
13
13
|
import { createRequire } from "module";
|
|
@@ -203,7 +203,12 @@ export function createServer() {
|
|
|
203
203
|
case "get_config": {
|
|
204
204
|
const manager = new ConfigManager();
|
|
205
205
|
const key = args?.key;
|
|
206
|
-
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);
|
|
207
212
|
return textResult(value);
|
|
208
213
|
}
|
|
209
214
|
case "list_docs": {
|
|
@@ -302,7 +307,7 @@ export function createServer() {
|
|
|
302
307
|
contents: [{
|
|
303
308
|
uri: "rafter://config",
|
|
304
309
|
mimeType: "application/json",
|
|
305
|
-
text: JSON.stringify(manager.load(), null, 2),
|
|
310
|
+
text: JSON.stringify(redactConfigSecrets(manager.load()), null, 2),
|
|
306
311
|
}],
|
|
307
312
|
};
|
|
308
313
|
case "rafter://policy":
|
|
@@ -310,7 +315,7 @@ export function createServer() {
|
|
|
310
315
|
contents: [{
|
|
311
316
|
uri: "rafter://policy",
|
|
312
317
|
mimeType: "application/json",
|
|
313
|
-
text: JSON.stringify(manager.loadWithPolicy(), null, 2),
|
|
318
|
+
text: JSON.stringify(redactConfigSecrets(manager.loadWithPolicy()), null, 2),
|
|
314
319
|
}],
|
|
315
320
|
};
|
|
316
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
|
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ConfigManager } from "./config-manager.js";
|
|
2
2
|
import { AuditLogger } from "./audit-logger.js";
|
|
3
|
-
import { assessCommandRisk } from "./risk-rules.js";
|
|
3
|
+
import { assessCommandRisk, matchedCriticalPattern } from "./risk-rules.js";
|
|
4
4
|
export class CommandInterceptor {
|
|
5
5
|
constructor() {
|
|
6
6
|
this.config = new ConfigManager();
|
|
@@ -10,13 +10,39 @@ export class CommandInterceptor {
|
|
|
10
10
|
* Evaluate if a command should be allowed
|
|
11
11
|
*/
|
|
12
12
|
evaluate(command) {
|
|
13
|
+
const riskLevel = this.assessRisk(command);
|
|
14
|
+
// Unconditional hard-block: catastrophic destructive commands (rm -rf /,
|
|
15
|
+
// fork bombs, disk wipes, mkfs, …) are NEVER allowed, regardless of the
|
|
16
|
+
// configured policy — or its absence. Security must not depend on a policy
|
|
17
|
+
// being present (the default config may be missing one) or on the chosen
|
|
18
|
+
// mode (even allow-all / a custom deny-list cannot opt out of these).
|
|
19
|
+
if (riskLevel === "critical") {
|
|
20
|
+
return {
|
|
21
|
+
command,
|
|
22
|
+
riskLevel,
|
|
23
|
+
allowed: false,
|
|
24
|
+
requiresApproval: false,
|
|
25
|
+
reason: "Matches built-in blocked pattern (critical destructive command)",
|
|
26
|
+
matchedPattern: matchedCriticalPattern(command) ?? "builtin:critical-destructive"
|
|
27
|
+
};
|
|
28
|
+
}
|
|
13
29
|
const cfg = this.config.loadWithPolicy();
|
|
14
30
|
const policy = cfg.agent?.commandPolicy;
|
|
15
31
|
if (!policy) {
|
|
16
|
-
// No policy configured
|
|
32
|
+
// No policy configured — fall back to safe built-in defaults rather than
|
|
33
|
+
// allow-all: high-risk commands still require approval.
|
|
34
|
+
if (riskLevel === "high") {
|
|
35
|
+
return {
|
|
36
|
+
command,
|
|
37
|
+
riskLevel,
|
|
38
|
+
allowed: false,
|
|
39
|
+
requiresApproval: true,
|
|
40
|
+
reason: "High risk command requires approval"
|
|
41
|
+
};
|
|
42
|
+
}
|
|
17
43
|
return {
|
|
18
44
|
command,
|
|
19
|
-
riskLevel
|
|
45
|
+
riskLevel,
|
|
20
46
|
allowed: true,
|
|
21
47
|
requiresApproval: false
|
|
22
48
|
};
|
|
@@ -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
|
package/dist/core/risk-rules.js
CHANGED
|
@@ -87,3 +87,17 @@ export function assessCommandRisk(command) {
|
|
|
87
87
|
}
|
|
88
88
|
return "low";
|
|
89
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Return the source of the first CRITICAL pattern matching the command, or null.
|
|
92
|
+
* Mirrors assessCommandRisk's lowercasing. Intended to be called only once a
|
|
93
|
+
* command is already classified "critical" (safe-prefix exclusion is handled by
|
|
94
|
+
* assessCommandRisk), to surface *which* built-in rule matched.
|
|
95
|
+
*/
|
|
96
|
+
export function matchedCriticalPattern(command) {
|
|
97
|
+
const cmd = command.toLowerCase().trim();
|
|
98
|
+
for (const pattern of CRITICAL_PATTERNS) {
|
|
99
|
+
if (pattern.test(cmd))
|
|
100
|
+
return pattern.source;
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
@@ -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
|
*/
|