@rafter-security/cli 0.10.0 → 0.10.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.
- package/dist/commands/agent/exec.js +63 -11
- package/dist/commands/agent/init.js +94 -19
- package/dist/commands/agent/scan.js +6 -2
- package/dist/commands/agent/verify.js +128 -6
- package/dist/commands/backend/get.js +9 -4
- package/dist/commands/backend/run.js +3 -4
- package/dist/commands/backend/scan-status.js +211 -26
- package/dist/commands/backend/usage.js +2 -3
- package/dist/commands/issues/from-scan.js +26 -6
- package/dist/commands/issues/from-text.js +1 -1
- package/dist/commands/issues/issue-builder.js +1 -1
- package/dist/commands/mcp/server.js +5 -6
- package/dist/commands/notify.js +2 -3
- package/dist/commands/sites/create.js +2 -3
- package/dist/commands/sites/get.js +2 -3
- package/dist/commands/sites/list.js +2 -3
- package/dist/commands/sites/scan.js +2 -3
- package/dist/core/risk-rules.js +321 -18
- package/dist/index.js +3 -1
- package/dist/scanners/betterleaks.js +7 -0
- package/dist/utils/api.js +48 -0
- package/dist/utils/env-guard.js +32 -0
- package/package.json +1 -1
- package/resources/rafter-security-skill.md +1 -1
- package/resources/skills/rafter/docs/cli-reference.md +1 -1
- package/resources/skills/rafter/docs/guardrails.md +2 -2
|
@@ -1,20 +1,49 @@
|
|
|
1
|
-
import { Command } from "commander";
|
|
1
|
+
import { Command, Option } from "commander";
|
|
2
2
|
import { CommandInterceptor } from "../../core/command-interceptor.js";
|
|
3
3
|
import { scanAddedDiffLines } from "../../scanners/git-diff-scan.js";
|
|
4
4
|
import { parseUnifiedDiffAddedLines } from "../../utils/git-diff.js";
|
|
5
5
|
import { execSync } from "child_process";
|
|
6
6
|
import readline from "readline";
|
|
7
7
|
import { fmt } from "../../utils/formatter.js";
|
|
8
|
+
// Approval model (rf-ss67): the only party who can approve a command that the
|
|
9
|
+
// policy says needs approval is a person at an interactive terminal. There is
|
|
10
|
+
// no flag, env var or stdin trick that stands in for that, because every one
|
|
11
|
+
// of those can be produced by the agent whose command is being gated:
|
|
12
|
+
// * `--force` used to skip the prompt. Combined with the PreToolUse hook
|
|
13
|
+
// treating a quoted argument as prose, `rafter agent exec --force "<cmd>"`
|
|
14
|
+
// ran any HIGH-tier command unprompted with the hook blind. The flag is
|
|
15
|
+
// kept only so old invocations parse; it changes nothing.
|
|
16
|
+
// * A piped "yes" is not a person. Approval is offered only when stdin is a
|
|
17
|
+
// TTY; otherwise the command is denied and says why.
|
|
18
|
+
// The machine owner widens policy in ~/.rafter/config.json, not per call.
|
|
19
|
+
const DRY_RUN_EXIT = { allowed: 0, blocked: 1, approval: 2 };
|
|
8
20
|
export function createExecCommand() {
|
|
9
21
|
return new Command("exec")
|
|
10
22
|
.description("Execute command with security validation")
|
|
11
|
-
.argument("<command
|
|
23
|
+
.argument("<command...>", "Command to execute (quote it, or pass it after --)")
|
|
12
24
|
.option("--skip-scan", "Skip pre-execution file scanning")
|
|
13
|
-
.option("--
|
|
14
|
-
.
|
|
25
|
+
.option("--dry-run", "Classify the command and exit without running it (exit 0 allowed, 1 blocked, 2 needs approval)")
|
|
26
|
+
.addOption(new Option("--force", "Deprecated: no longer skips approval (rf-ss67)").hideHelp())
|
|
27
|
+
.action(async (parts, opts) => {
|
|
28
|
+
const command = joinCommandParts(parts);
|
|
15
29
|
const interceptor = new CommandInterceptor();
|
|
16
30
|
// Step 1: Evaluate command
|
|
17
31
|
const evaluation = interceptor.evaluate(command);
|
|
32
|
+
// Step 1b: --dry-run reports the classification and stops. Nothing runs,
|
|
33
|
+
// nothing is scanned, nothing is logged as executed.
|
|
34
|
+
if (opts.dryRun) {
|
|
35
|
+
const blocked = !evaluation.allowed && !evaluation.requiresApproval;
|
|
36
|
+
const verdict = blocked ? "BLOCKED" : evaluation.requiresApproval ? "REQUIRES APPROVAL" : "ALLOWED";
|
|
37
|
+
console.log(`Dry run: ${verdict}`);
|
|
38
|
+
console.log(`Risk Level: ${evaluation.riskLevel.toUpperCase()}`);
|
|
39
|
+
console.log(`Requires approval: ${evaluation.requiresApproval ? "yes" : "no"}`);
|
|
40
|
+
if (evaluation.reason) {
|
|
41
|
+
console.log(`Reason: ${evaluation.reason}`);
|
|
42
|
+
}
|
|
43
|
+
console.log(`Command: ${command}`);
|
|
44
|
+
console.log("Not executed (--dry-run).");
|
|
45
|
+
process.exit(blocked ? DRY_RUN_EXIT.blocked : evaluation.requiresApproval ? DRY_RUN_EXIT.approval : DRY_RUN_EXIT.allowed);
|
|
46
|
+
}
|
|
18
47
|
// Step 2: Handle blocked commands
|
|
19
48
|
if (!evaluation.allowed && !evaluation.requiresApproval) {
|
|
20
49
|
console.error(`\n${fmt.error("Command BLOCKED")}\n`);
|
|
@@ -35,8 +64,11 @@ export function createExecCommand() {
|
|
|
35
64
|
process.exit(1);
|
|
36
65
|
}
|
|
37
66
|
}
|
|
38
|
-
// Step 4: Handle approval required
|
|
39
|
-
if (evaluation.requiresApproval
|
|
67
|
+
// Step 4: Handle approval required — only a person at a terminal can.
|
|
68
|
+
if (evaluation.requiresApproval) {
|
|
69
|
+
if (opts.force) {
|
|
70
|
+
console.log(`\n${fmt.warning("--force no longer skips approval (rf-ss67); approval needs a person at an interactive terminal")}\n`);
|
|
71
|
+
}
|
|
40
72
|
console.log(`\n${fmt.warning("Command requires approval")}\n`);
|
|
41
73
|
console.log(`Risk Level: ${evaluation.riskLevel.toUpperCase()}`);
|
|
42
74
|
console.log(`Command: ${command}`);
|
|
@@ -44,6 +76,13 @@ export function createExecCommand() {
|
|
|
44
76
|
console.log(`Reason: ${evaluation.reason}`);
|
|
45
77
|
}
|
|
46
78
|
console.log();
|
|
79
|
+
if (!process.stdin.isTTY) {
|
|
80
|
+
console.log(`${fmt.error("Command denied: approval needs an interactive terminal, and stdin is not one")}`);
|
|
81
|
+
console.log("Run the command yourself at a terminal, or have the machine owner adjust " +
|
|
82
|
+
"commandPolicy in ~/.rafter/config.json.\n");
|
|
83
|
+
interceptor.logEvaluation(evaluation, "blocked");
|
|
84
|
+
process.exit(1);
|
|
85
|
+
}
|
|
47
86
|
const approved = await promptApproval();
|
|
48
87
|
if (!approved) {
|
|
49
88
|
console.log(`\n${fmt.error("Command cancelled")}\n`);
|
|
@@ -53,16 +92,12 @@ export function createExecCommand() {
|
|
|
53
92
|
console.log(`\n${fmt.success("Command approved by user")}\n`);
|
|
54
93
|
interceptor.logEvaluation(evaluation, "overridden");
|
|
55
94
|
}
|
|
56
|
-
else if (opts.force && evaluation.requiresApproval) {
|
|
57
|
-
console.log(`\n${fmt.warning("Forcing execution (--force flag)")}\n`);
|
|
58
|
-
interceptor.logEvaluation(evaluation, "overridden");
|
|
59
|
-
}
|
|
60
95
|
else {
|
|
61
96
|
interceptor.logEvaluation(evaluation, "allowed");
|
|
62
97
|
}
|
|
63
98
|
// Step 5: Execute command
|
|
64
99
|
try {
|
|
65
|
-
|
|
100
|
+
execSync(command, {
|
|
66
101
|
stdio: "inherit",
|
|
67
102
|
encoding: "utf-8"
|
|
68
103
|
});
|
|
@@ -75,6 +110,23 @@ export function createExecCommand() {
|
|
|
75
110
|
}
|
|
76
111
|
});
|
|
77
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* One quoted argument is the command verbatim. Several (the `-- rm -rf x` form
|
|
115
|
+
* the docs show) are re-joined with shell quoting, so what the classifier sees
|
|
116
|
+
* is what the shell will run — `-- echo "a b"` becomes `echo 'a b'`, not `echo a b`.
|
|
117
|
+
*/
|
|
118
|
+
export function joinCommandParts(parts) {
|
|
119
|
+
if (parts.length === 1)
|
|
120
|
+
return parts[0];
|
|
121
|
+
return parts.map(shellQuote).join(" ");
|
|
122
|
+
}
|
|
123
|
+
function shellQuote(token) {
|
|
124
|
+
if (token === "")
|
|
125
|
+
return "''";
|
|
126
|
+
if (/^[A-Za-z0-9_\/:=@.,+%-]+$/.test(token))
|
|
127
|
+
return token;
|
|
128
|
+
return `'${token.replace(/'/g, `'\\''`)}'`;
|
|
129
|
+
}
|
|
78
130
|
function isGitCommand(command) {
|
|
79
131
|
return command.trim().startsWith("git commit") ||
|
|
80
132
|
command.trim().startsWith("git push");
|
|
@@ -6,7 +6,7 @@ import { SkillManager } from "../../utils/skill-manager.js";
|
|
|
6
6
|
import fs from "fs";
|
|
7
7
|
import path from "path";
|
|
8
8
|
import os from "os";
|
|
9
|
-
import { execSync } from "child_process";
|
|
9
|
+
import { execSync, spawnSync } from "child_process";
|
|
10
10
|
import { fileURLToPath } from "url";
|
|
11
11
|
import { createRequire } from "module";
|
|
12
12
|
import { askYesNo } from "../../utils/prompt.js";
|
|
@@ -15,6 +15,70 @@ import { injectInstructionFile } from "./instruction-block.js";
|
|
|
15
15
|
import yaml from "js-yaml";
|
|
16
16
|
const __filename = fileURLToPath(import.meta.url);
|
|
17
17
|
const __dirname = path.dirname(__filename);
|
|
18
|
+
/**
|
|
19
|
+
* Resolve an ABSOLUTE, self-contained hook command (rf-er8a). Agents run a hook
|
|
20
|
+
* through `sh -c "<command>"` in a minimal environment that need not have
|
|
21
|
+
* `rafter` — or even `node` — on PATH; a bare `rafter hook pretool` then exits
|
|
22
|
+
* 127, which those tools treat as a silent allow, so the gate is inert while
|
|
23
|
+
* settings.json says it is installed. Pinning BOTH the node interpreter and the
|
|
24
|
+
* CLI entrypoint makes the command resolvable regardless of PATH. (dist/index.js
|
|
25
|
+
* carries `#!/usr/bin/env node`, so an absolute entrypoint ALONE still fails
|
|
26
|
+
* where node is off PATH — the interpreter must be pinned too.)
|
|
27
|
+
*/
|
|
28
|
+
function hookEntrypoint() {
|
|
29
|
+
let entrypoint = process.argv[1] || "";
|
|
30
|
+
try {
|
|
31
|
+
entrypoint = fs.realpathSync(entrypoint);
|
|
32
|
+
}
|
|
33
|
+
catch { /* keep as-is */ }
|
|
34
|
+
return entrypoint;
|
|
35
|
+
}
|
|
36
|
+
export function absoluteHookCommand(args) {
|
|
37
|
+
return `${process.execPath} ${hookEntrypoint()} hook ${args}`;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* After writing the hooks, confirm the exact command we wrote actually runs and
|
|
41
|
+
* enforces — and refuse to report a clean success if it does not (rf-er8a /
|
|
42
|
+
* rf-fuwy). Returns human-readable warnings; empty means the gate is live.
|
|
43
|
+
*/
|
|
44
|
+
function installedHookWarnings() {
|
|
45
|
+
const warnings = [];
|
|
46
|
+
const entrypoint = hookEntrypoint();
|
|
47
|
+
if (entrypoint.includes("/_npx/") || entrypoint.includes("\\_npx\\")) {
|
|
48
|
+
warnings.push(`The rafter entrypoint is inside an npx cache (${entrypoint}), which is ephemeral: the ` +
|
|
49
|
+
`installed hook will stop resolving when the cache is cleared. Install globally ` +
|
|
50
|
+
`(npm install -g @rafter-security/cli) and re-run 'rafter agent init'.`);
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
const cmd = absoluteHookCommand("pretool");
|
|
54
|
+
const res = spawnSync("sh", ["-c", cmd], {
|
|
55
|
+
input: JSON.stringify({
|
|
56
|
+
hook_event_name: "PreToolUse",
|
|
57
|
+
tool_name: "Bash",
|
|
58
|
+
tool_input: { command: "rm -rf / --no-preserve-root" },
|
|
59
|
+
permission_mode: "default",
|
|
60
|
+
cwd: process.cwd(),
|
|
61
|
+
}),
|
|
62
|
+
encoding: "utf-8",
|
|
63
|
+
timeout: 10000,
|
|
64
|
+
});
|
|
65
|
+
let decision = null;
|
|
66
|
+
try {
|
|
67
|
+
decision = JSON.parse(res.stdout || "")?.hookSpecificOutput?.permissionDecision ?? null;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
decision = null;
|
|
71
|
+
}
|
|
72
|
+
if (res.error || res.status === 127) {
|
|
73
|
+
warnings.push(`The installed PreToolUse hook did not execute (exit ${res.status ?? "spawn error"}) — the gate is inert. Command: ${cmd}`);
|
|
74
|
+
}
|
|
75
|
+
else if (decision !== "deny") {
|
|
76
|
+
warnings.push(`The installed PreToolUse hook ran but did not block a synthetic critical command (decision=${decision ?? "none"}).`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch { /* best-effort confirmation */ }
|
|
80
|
+
return warnings;
|
|
81
|
+
}
|
|
18
82
|
/**
|
|
19
83
|
* Skills installed by `rafter agent init` for Claude Code / Codex.
|
|
20
84
|
*
|
|
@@ -251,22 +315,22 @@ function installClaudeCodeHooks(root) {
|
|
|
251
315
|
settings.hooks.PreToolUse = [];
|
|
252
316
|
if (!settings.hooks.PostToolUse)
|
|
253
317
|
settings.hooks.PostToolUse = [];
|
|
254
|
-
const preHook = { type: "command", command: "
|
|
255
|
-
const postHook = { type: "command", command: "
|
|
318
|
+
const preHook = { type: "command", command: absoluteHookCommand("pretool") };
|
|
319
|
+
const postHook = { type: "command", command: absoluteHookCommand("posttool") };
|
|
256
320
|
// Remove any existing Rafter hooks to avoid duplicates
|
|
257
321
|
settings.hooks.PreToolUse = settings.hooks.PreToolUse.filter((entry) => {
|
|
258
322
|
const hooks = entry.hooks || [];
|
|
259
|
-
return !hooks.some((h) => h.command
|
|
323
|
+
return !hooks.some((h) => String(h.command ?? "").includes("hook pretool"));
|
|
260
324
|
});
|
|
261
325
|
settings.hooks.PostToolUse = settings.hooks.PostToolUse.filter((entry) => {
|
|
262
326
|
const hooks = entry.hooks || [];
|
|
263
|
-
return !hooks.some((h) => h.command
|
|
327
|
+
return !hooks.some((h) => String(h.command ?? "").includes("hook posttool"));
|
|
264
328
|
});
|
|
265
329
|
// Strip legacy SessionStart entry left over from <=0.7.4 installs.
|
|
266
330
|
if (Array.isArray(settings.hooks.SessionStart)) {
|
|
267
331
|
settings.hooks.SessionStart = settings.hooks.SessionStart.filter((entry) => {
|
|
268
332
|
const hooks = entry.hooks || [];
|
|
269
|
-
return !hooks.some((h) => h.command
|
|
333
|
+
return !hooks.some((h) => String(h.command ?? "").includes("hook session-start"));
|
|
270
334
|
});
|
|
271
335
|
if (settings.hooks.SessionStart.length === 0)
|
|
272
336
|
delete settings.hooks.SessionStart;
|
|
@@ -303,11 +367,11 @@ function installCodexHooks(root) {
|
|
|
303
367
|
if (!config.hooks.PostToolUse)
|
|
304
368
|
config.hooks.PostToolUse = [];
|
|
305
369
|
// Codex uses the same hookSpecificOutput protocol as Claude Code (format=claude)
|
|
306
|
-
const preHook = { type: "command", command: "
|
|
307
|
-
const postHook = { type: "command", command: "
|
|
370
|
+
const preHook = { type: "command", command: absoluteHookCommand("pretool") };
|
|
371
|
+
const postHook = { type: "command", command: absoluteHookCommand("posttool") };
|
|
308
372
|
// Remove existing rafter hooks
|
|
309
|
-
config.hooks.PreToolUse = config.hooks.PreToolUse.filter((entry) => !(entry.hooks || []).some((h) => h.command
|
|
310
|
-
config.hooks.PostToolUse = config.hooks.PostToolUse.filter((entry) => !(entry.hooks || []).some((h) => h.command
|
|
373
|
+
config.hooks.PreToolUse = config.hooks.PreToolUse.filter((entry) => !(entry.hooks || []).some((h) => String(h.command ?? "").includes("hook pretool")));
|
|
374
|
+
config.hooks.PostToolUse = config.hooks.PostToolUse.filter((entry) => !(entry.hooks || []).some((h) => String(h.command ?? "").includes("hook posttool")));
|
|
311
375
|
// PreToolUse intercepts the tools Codex documents support for: Bash and
|
|
312
376
|
// apply_patch (file edits). Per developers.openai.com/codex/hooks PreToolUse
|
|
313
377
|
// also covers MCP tool calls via patterns like `mcp__<server>__<tool>` —
|
|
@@ -353,14 +417,14 @@ function installCursorHooks(root) {
|
|
|
353
417
|
if (!config.hooks)
|
|
354
418
|
config.hooks = {};
|
|
355
419
|
const events = [
|
|
356
|
-
{ event: "preToolUse", command: "
|
|
357
|
-
{ event: "postToolUse", command: "
|
|
358
|
-
{ event: "beforeShellExecution", command: "
|
|
420
|
+
{ event: "preToolUse", command: absoluteHookCommand("pretool --format cursor") },
|
|
421
|
+
{ event: "postToolUse", command: absoluteHookCommand("posttool --format cursor") },
|
|
422
|
+
{ event: "beforeShellExecution", command: absoluteHookCommand("pretool --format cursor") },
|
|
359
423
|
];
|
|
360
424
|
for (const { event, command } of events) {
|
|
361
425
|
if (!Array.isArray(config.hooks[event]))
|
|
362
426
|
config.hooks[event] = [];
|
|
363
|
-
config.hooks[event] = config.hooks[event].filter((entry) => !entry?.command?.includes("
|
|
427
|
+
config.hooks[event] = config.hooks[event].filter((entry) => !(String(entry?.command ?? "").includes("hook pretool") || String(entry?.command ?? "").includes("hook posttool")));
|
|
364
428
|
config.hooks[event].push({ command, type: "command", timeout: 5000 });
|
|
365
429
|
}
|
|
366
430
|
fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2), "utf-8");
|
|
@@ -484,19 +548,19 @@ function installGeminiHooks(root) {
|
|
|
484
548
|
if (!settings.hooks.AfterTool)
|
|
485
549
|
settings.hooks.AfterTool = [];
|
|
486
550
|
// Remove existing rafter hooks
|
|
487
|
-
settings.hooks.BeforeTool = settings.hooks.BeforeTool.filter((entry) => !(entry.hooks || []).some((h) => h.command
|
|
488
|
-
settings.hooks.AfterTool = settings.hooks.AfterTool.filter((entry) => !(entry.hooks || []).some((h) => h.command
|
|
551
|
+
settings.hooks.BeforeTool = settings.hooks.BeforeTool.filter((entry) => !(entry.hooks || []).some((h) => String(h.command ?? "").includes("hook pretool")));
|
|
552
|
+
settings.hooks.AfterTool = settings.hooks.AfterTool.filter((entry) => !(entry.hooks || []).some((h) => String(h.command ?? "").includes("hook posttool")));
|
|
489
553
|
// Gemini matchers are regexes against built-in tool names per
|
|
490
554
|
// geminicli.com/docs/hooks/reference. Match the mutating tools by name
|
|
491
555
|
// explicitly: run_shell_command, write_file, replace, edit. (rf-044o
|
|
492
556
|
// verification 2026-05-03 — schema confirmed against current Gemini docs.)
|
|
493
557
|
settings.hooks.BeforeTool.push({
|
|
494
558
|
matcher: "run_shell_command|write_file|replace|edit",
|
|
495
|
-
hooks: [{ type: "command", command: "
|
|
559
|
+
hooks: [{ type: "command", command: absoluteHookCommand("pretool --format gemini"), timeout: 5000 }],
|
|
496
560
|
});
|
|
497
561
|
settings.hooks.AfterTool.push({
|
|
498
562
|
matcher: ".*",
|
|
499
|
-
hooks: [{ type: "command", command: "
|
|
563
|
+
hooks: [{ type: "command", command: absoluteHookCommand("posttool --format gemini"), timeout: 5000 }],
|
|
500
564
|
});
|
|
501
565
|
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), "utf-8");
|
|
502
566
|
console.log(fmt.success(`Installed hooks to ${settingsPath}`));
|
|
@@ -1489,7 +1553,18 @@ export function createInitCommand() {
|
|
|
1489
1553
|
windsurf: windsurfOk,
|
|
1490
1554
|
}, root, scope);
|
|
1491
1555
|
console.log();
|
|
1492
|
-
|
|
1556
|
+
// rf-er8a: do not report a clean success if the hook we just wrote cannot
|
|
1557
|
+
// execute and enforce. A silent 127 (or an npx-cache entrypoint) means the
|
|
1558
|
+
// gate is inert even though settings.json looks configured.
|
|
1559
|
+
const hookWarnings = claudeCodeOk ? installedHookWarnings() : [];
|
|
1560
|
+
if (hookWarnings.length > 0) {
|
|
1561
|
+
for (const w of hookWarnings)
|
|
1562
|
+
console.log(fmt.warning(w));
|
|
1563
|
+
console.log(fmt.warning("Agent security initialized WITH WARNINGS — the command gate may NOT be active (see above). Run 'rafter agent verify' to confirm."));
|
|
1564
|
+
}
|
|
1565
|
+
else {
|
|
1566
|
+
console.log(fmt.success("Agent security initialized!"));
|
|
1567
|
+
}
|
|
1493
1568
|
console.log();
|
|
1494
1569
|
const anyIntegration = openclawOk || claudeCodeOk || codexOk || geminiOk || cursorOk || windsurfOk || continueOk || aiderOk || hermesOk || openCodeOk;
|
|
1495
1570
|
if (anyIntegration) {
|
|
@@ -371,7 +371,9 @@ async function runGitAddedLineScan(gitArgs, opts, scanCfg, baselineEntries, scan
|
|
|
371
371
|
});
|
|
372
372
|
if (!patch.trim()) {
|
|
373
373
|
if (!opts.quiet) {
|
|
374
|
-
|
|
374
|
+
// Status line, so stderr — stdout must stay parseable as JSON under
|
|
375
|
+
// --json, and outputScanResults owns the single stdout success line.
|
|
376
|
+
console.error(fmt.success(emptyMessage));
|
|
375
377
|
}
|
|
376
378
|
outputScanResults([], opts, contextLabel, true, suppressions);
|
|
377
379
|
return;
|
|
@@ -379,7 +381,9 @@ async function runGitAddedLineScan(gitArgs, opts, scanCfg, baselineEntries, scan
|
|
|
379
381
|
const addedLines = parseUnifiedDiffAddedLines(patch);
|
|
380
382
|
if (addedLines.length === 0) {
|
|
381
383
|
if (!opts.quiet) {
|
|
382
|
-
|
|
384
|
+
// Status line, so stderr — stdout must stay parseable as JSON under
|
|
385
|
+
// --json, and outputScanResults owns the single stdout success line.
|
|
386
|
+
console.error(fmt.success(emptyMessage));
|
|
383
387
|
}
|
|
384
388
|
outputScanResults([], opts, contextLabel, true, suppressions);
|
|
385
389
|
return;
|
|
@@ -1,12 +1,62 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
2
|
import { BinaryManager } from "../../utils/binary-manager.js";
|
|
3
3
|
import { SkillManager } from "../../utils/skill-manager.js";
|
|
4
|
+
import { resolveHookControl } from "../../core/hook-control.js";
|
|
4
5
|
import { spawnSync } from "child_process";
|
|
5
6
|
import fs from "fs";
|
|
6
7
|
import path from "path";
|
|
7
8
|
import os from "os";
|
|
8
9
|
import yaml from "js-yaml";
|
|
9
10
|
import { fmt } from "../../utils/formatter.js";
|
|
11
|
+
/**
|
|
12
|
+
* Run a configured PreToolUse hook command EXACTLY as Claude Code would — through
|
|
13
|
+
* `sh -c "<command as written in settings.json>"`, with a synthetic payload on
|
|
14
|
+
* stdin — and return its exit status and the permissionDecision it emitted.
|
|
15
|
+
*
|
|
16
|
+
* This is the whole point of rf-fuwy: `agent verify` used to confirm only that
|
|
17
|
+
* the hook was CONFIGURED (a substring match) and reported a completely inert
|
|
18
|
+
* gate as healthy, byte-identical to a working one. A command that does not
|
|
19
|
+
* resolve exits 127; Claude Code blocks only on exit 2, so 127 is a silent
|
|
20
|
+
* allow. Executing the command is the only check that cannot be fooled by that.
|
|
21
|
+
*/
|
|
22
|
+
export function runConfiguredHook(command, toolCommand) {
|
|
23
|
+
const payload = JSON.stringify({
|
|
24
|
+
session_id: `rafter-verify-${process.pid}-${Date.now()}`,
|
|
25
|
+
transcript_path: "",
|
|
26
|
+
cwd: process.cwd(),
|
|
27
|
+
permission_mode: "default",
|
|
28
|
+
hook_event_name: "PreToolUse",
|
|
29
|
+
tool_name: "Bash",
|
|
30
|
+
tool_input: { command: toolCommand },
|
|
31
|
+
});
|
|
32
|
+
// `sh -c` reproduces exactly how Claude Code invokes a shell-form hook, so a
|
|
33
|
+
// command that resolves in this terminal but not in the editor (or vice versa)
|
|
34
|
+
// is exercised the same way the editor would exercise it. Retry a transient
|
|
35
|
+
// spawn failure (e.g. EAGAIN under process pressure) so a resource hiccup does
|
|
36
|
+
// not get reported as an inert gate — a false alarm is worse than a slow check.
|
|
37
|
+
let result = spawnSync("sh", ["-c", command], { input: payload, encoding: "utf-8", timeout: 10000 });
|
|
38
|
+
// Retry a spawn-level error OR a signal kill: under the same process pressure
|
|
39
|
+
// that produces EAGAIN, the OOM killer sends SIGKILL, which sets `signal` (not
|
|
40
|
+
// `error`) with a null status — the identical false-alarm scenario by another
|
|
41
|
+
// route (measured by achebe). A persistent failure still returns decision:null,
|
|
42
|
+
// so a genuinely inert hook is still reported inert — no fail-open.
|
|
43
|
+
for (let attempt = 0; attempt < 2 && (result.error || result.signal); attempt++) {
|
|
44
|
+
result = spawnSync("sh", ["-c", command], { input: payload, encoding: "utf-8", timeout: 10000 });
|
|
45
|
+
}
|
|
46
|
+
if (result.error) {
|
|
47
|
+
return { status: null, decision: null, error: result.error.message, stdout: "" };
|
|
48
|
+
}
|
|
49
|
+
const stdout = result.stdout ?? "";
|
|
50
|
+
let decision = null;
|
|
51
|
+
try {
|
|
52
|
+
const parsed = JSON.parse(stdout);
|
|
53
|
+
decision = parsed?.hookSpecificOutput?.permissionDecision ?? null;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
decision = null;
|
|
57
|
+
}
|
|
58
|
+
return { status: result.status, decision, stdout };
|
|
59
|
+
}
|
|
10
60
|
async function checkBetterleaks() {
|
|
11
61
|
const binaryManager = new BinaryManager();
|
|
12
62
|
const name = "Betterleaks";
|
|
@@ -67,11 +117,64 @@ function checkClaudeCode() {
|
|
|
67
117
|
// Substring match — Python install writes an absolute path
|
|
68
118
|
// (/home/foo/bin/rafter hook pretool), Node writes the bare command.
|
|
69
119
|
const hooks = settings?.hooks?.PreToolUse || [];
|
|
70
|
-
const
|
|
71
|
-
|
|
120
|
+
const commands = [];
|
|
121
|
+
for (const entry of hooks) {
|
|
122
|
+
for (const h of entry.hooks || []) {
|
|
123
|
+
const cmd = String(h?.command ?? "");
|
|
124
|
+
if (cmd.includes("hook pretool"))
|
|
125
|
+
commands.push(cmd);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (commands.length === 0) {
|
|
72
129
|
return { name, passed: false, optional: true, detail: "Rafter hooks not installed — run 'rafter agent init --with-claude-code'" };
|
|
73
130
|
}
|
|
74
|
-
|
|
131
|
+
// A configured hook that has been deliberately switched off is a valid
|
|
132
|
+
// state, not a failure: expecting a "deny" from a disabled hook would fail a
|
|
133
|
+
// machine whose owner turned it off on purpose (rf-fuwy amendment).
|
|
134
|
+
const control = resolveHookControl();
|
|
135
|
+
if (!control.commandPolicyEnabled) {
|
|
136
|
+
return {
|
|
137
|
+
name,
|
|
138
|
+
passed: false,
|
|
139
|
+
optional: true,
|
|
140
|
+
detail: `Hook installed but command interception is DISABLED (${control.source.commandPolicy}) — no command is blocked. Re-enable to enforce.`,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
// rf-fuwy: EXECUTE the configured command, do not just read it. A gate that
|
|
144
|
+
// cannot run (exit 127) is inert but was reported "installed"; a gate that
|
|
145
|
+
// runs but does not block a CRITICAL command is misconfigured. Assert both
|
|
146
|
+
// directions with synthetic payloads.
|
|
147
|
+
const hookCmd = commands[0];
|
|
148
|
+
const danger = runConfiguredHook(hookCmd, "rm -rf / --no-preserve-root");
|
|
149
|
+
if (danger.error || danger.status === 127) {
|
|
150
|
+
return {
|
|
151
|
+
name,
|
|
152
|
+
passed: false,
|
|
153
|
+
detail: `Hook is CONFIGURED but NOT EXECUTABLE (${danger.error ? danger.error : "exit 127"}): "${hookCmd}" does not resolve, so the gate is INERT ` +
|
|
154
|
+
`(Claude Code blocks only on exit 2; anything else is allowed). Reinstall with 'rafter agent init --with-claude-code', which writes an absolute path.`,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
if (danger.decision !== "deny") {
|
|
158
|
+
return {
|
|
159
|
+
name,
|
|
160
|
+
passed: false,
|
|
161
|
+
detail: `Hook executes (exit ${danger.status}) but did NOT block a synthetic CRITICAL command (decision=${danger.decision ?? "none/unparseable"}). ` +
|
|
162
|
+
`The gate is not enforcing.`,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
const benign = runConfiguredHook(hookCmd, "echo hello");
|
|
166
|
+
if (benign.decision === "deny") {
|
|
167
|
+
return {
|
|
168
|
+
name,
|
|
169
|
+
passed: false,
|
|
170
|
+
detail: `Hook blocks even a benign command (echo) — over-blocking; check policy/config.`,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
// Note the caveat honestly: verify runs in the terminal's environment, which
|
|
174
|
+
// may differ from the editor's — a pass proves the command runs and enforces
|
|
175
|
+
// HERE, and a failure proves it is broken; it is not proof the editor's PATH
|
|
176
|
+
// resolves it too.
|
|
177
|
+
return { name, passed: true, detail: `Hooks installed and enforcing (blocked a synthetic 'rm -rf /'; verify runs in this shell's env)` };
|
|
75
178
|
}
|
|
76
179
|
catch (e) {
|
|
77
180
|
return { name, passed: false, optional: true, detail: `Cannot read settings: ${e}` };
|
|
@@ -348,9 +451,28 @@ function probeClaudeCode() {
|
|
|
348
451
|
});
|
|
349
452
|
const auditPath = path.join(home, ".rafter", "audit.jsonl");
|
|
350
453
|
const sizeBefore = fs.existsSync(auditPath) ? fs.statSync(auditPath).size : 0;
|
|
351
|
-
//
|
|
352
|
-
//
|
|
353
|
-
|
|
454
|
+
// Run the command EXACTLY as configured in settings.json, through `sh -c`, the
|
|
455
|
+
// way Claude Code would. (Earlier this spawned verify's own node + argv[1],
|
|
456
|
+
// which always resolves and therefore passed even when the CONFIGURED command
|
|
457
|
+
// did not exist — the rf-fuwy defect. Reading and running the real command is
|
|
458
|
+
// the only faithful probe.)
|
|
459
|
+
let configuredCmd = "rafter hook pretool";
|
|
460
|
+
try {
|
|
461
|
+
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
|
|
462
|
+
for (const entry of settings?.hooks?.PreToolUse || []) {
|
|
463
|
+
for (const h of entry.hooks || []) {
|
|
464
|
+
const cmd = String(h?.command ?? "");
|
|
465
|
+
if (cmd.includes("hook pretool")) {
|
|
466
|
+
configuredCmd = cmd;
|
|
467
|
+
break;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
catch {
|
|
473
|
+
// fall back to the bare command below
|
|
474
|
+
}
|
|
475
|
+
const result = spawnSync("sh", ["-c", configuredCmd], {
|
|
354
476
|
input: stdinPayload,
|
|
355
477
|
encoding: "utf-8",
|
|
356
478
|
timeout: 10000,
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
4
|
-
import { handleScanStatus } from "./scan-status.js";
|
|
2
|
+
import { resolveKey, writePayload, EXIT_GENERAL_ERROR, EXIT_SCAN_NOT_FOUND } from "../../utils/api.js";
|
|
3
|
+
import { handleScanStatus, fetchScanWithRetry, PollGaveUpError } from "./scan-status.js";
|
|
5
4
|
export function createGetCommand() {
|
|
6
5
|
return new Command("get")
|
|
7
6
|
.argument("<scan_id>")
|
|
@@ -13,7 +12,10 @@ export function createGetCommand() {
|
|
|
13
12
|
const key = resolveKey(opts.apiKey);
|
|
14
13
|
if (!opts.interactive) {
|
|
15
14
|
try {
|
|
16
|
-
|
|
15
|
+
// sable-l10k — retried, because this is the command the poll loop's
|
|
16
|
+
// give-up message recommends. A remedy defeated by the same transient
|
|
17
|
+
// failure it is recommended for is not a remedy.
|
|
18
|
+
const { data } = await fetchScanWithRetry(scan_id, { "x-api-key": key }, opts.format, opts.quiet);
|
|
17
19
|
const exitCode = writePayload(data, opts.format, opts.quiet);
|
|
18
20
|
process.exit(exitCode);
|
|
19
21
|
}
|
|
@@ -22,6 +24,9 @@ export function createGetCommand() {
|
|
|
22
24
|
console.error(`Scan '${scan_id}' not found`);
|
|
23
25
|
process.exit(EXIT_SCAN_NOT_FOUND);
|
|
24
26
|
}
|
|
27
|
+
else if (e instanceof PollGaveUpError) {
|
|
28
|
+
console.error(e.message);
|
|
29
|
+
}
|
|
25
30
|
else if (e.response?.data) {
|
|
26
31
|
console.error(e.response.data);
|
|
27
32
|
}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
|
-
import axios from "axios";
|
|
3
2
|
import ora from "ora";
|
|
4
3
|
import { detectRepo } from "../../utils/git.js";
|
|
5
|
-
import {
|
|
4
|
+
import { resolveKey, EXIT_GENERAL_ERROR, EXIT_QUOTA_EXHAUSTED, EXIT_CONFIRMATION_REQUIRED, handle403, apiClient, apiUrl } from "../../utils/api.js";
|
|
6
5
|
import { ConfigManager } from "../../core/config-manager.js";
|
|
7
6
|
import { loadPolicy } from "../../core/policy-loader.js";
|
|
8
7
|
import { askYesNo } from "../../utils/prompt.js";
|
|
@@ -105,7 +104,7 @@ export async function runRemoteScan(opts) {
|
|
|
105
104
|
if (!opts.quiet) {
|
|
106
105
|
const spinner = ora("Submitting scan").start();
|
|
107
106
|
try {
|
|
108
|
-
const { data } = await
|
|
107
|
+
const { data } = await apiClient.post(apiUrl("static/scan"), body, { headers: { "x-api-key": key } });
|
|
109
108
|
spinner.succeed(`Scan ID: ${data.scan_id}`);
|
|
110
109
|
if (opts.skipInteractive)
|
|
111
110
|
return;
|
|
@@ -136,7 +135,7 @@ export async function runRemoteScan(opts) {
|
|
|
136
135
|
}
|
|
137
136
|
else {
|
|
138
137
|
try {
|
|
139
|
-
const { data } = await
|
|
138
|
+
const { data } = await apiClient.post(apiUrl("static/scan"), body, { headers: { "x-api-key": key } });
|
|
140
139
|
if (opts.skipInteractive)
|
|
141
140
|
return;
|
|
142
141
|
const exitCode = await handleScanStatus(data.scan_id, { "x-api-key": key }, opts.format ?? "md", opts.quiet);
|