@rafter-security/cli 0.8.5 → 0.8.6

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.
@@ -7,6 +7,7 @@ import { fileURLToPath } from "url";
7
7
  import { getRafterDir, getAuditLogPath, getBinDir } from "../../core/config-defaults.js";
8
8
  import { AuditLogger } from "../../core/audit-logger.js";
9
9
  import { ConfigManager } from "../../core/config-manager.js";
10
+ import { resolveHookControl } from "../../core/hook-control.js";
10
11
  import { BinaryManager } from "../../utils/binary-manager.js";
11
12
  import { SkillManager } from "../../utils/skill-manager.js";
12
13
  export function createStatusCommand() {
@@ -38,6 +39,22 @@ export function createStatusCommand() {
38
39
  else {
39
40
  console.log(`\nConfig: not found — run: rafter agent init`);
40
41
  }
42
+ // --- Hook off-switch (trusted-source only: env / global config) ---
43
+ {
44
+ const c = resolveHookControl();
45
+ const describe = (on, src) => on ? "active" : `DISABLED (via ${src === "env" ? "RAFTER_DISABLE_* env" : "global config"})`;
46
+ if (!c.hookEnabled) {
47
+ console.log(`Hooks: ${describe(false, c.source.hook)}`);
48
+ }
49
+ else if (!c.secretScanEnabled || !c.commandPolicyEnabled) {
50
+ console.log(`Hooks: active (partial)`);
51
+ console.log(` secret scan: ${describe(c.secretScanEnabled, c.source.secretScan)}`);
52
+ console.log(` command policy: ${describe(c.commandPolicyEnabled, c.source.commandPolicy)}`);
53
+ }
54
+ else {
55
+ console.log(`Hooks: active`);
56
+ }
57
+ }
41
58
  // --- Betterleaks ---
42
59
  const exeExt = process.platform === "win32" ? ".exe" : "";
43
60
  const localBetterleaks = path.join(getBinDir(), `betterleaks${exeExt}`);
@@ -208,6 +225,19 @@ function buildStatusJson(home, configPath, auditPath) {
208
225
  betterleaks_available: isBetterleaksAvailable(),
209
226
  config_path: formatHomePath(configPath, home),
210
227
  audit_log_path: formatHomePath(auditPath, home),
228
+ hook_control: (() => {
229
+ const c = resolveHookControl();
230
+ return {
231
+ hook_enabled: c.hookEnabled,
232
+ secret_scan_enabled: c.secretScanEnabled,
233
+ command_policy_enabled: c.commandPolicyEnabled,
234
+ source: {
235
+ hook: c.source.hook,
236
+ secret_scan: c.source.secretScan,
237
+ command_policy: c.source.commandPolicy,
238
+ },
239
+ };
240
+ })(),
211
241
  };
212
242
  }
213
243
  function detectAgents(home) {
@@ -4,6 +4,7 @@ import { RegexScanner } from "../../scanners/regex-scanner.js";
4
4
  import { AuditLogger } from "../../core/audit-logger.js";
5
5
  import { ConfigManager } from "../../core/config-manager.js";
6
6
  import { applySuppressions } from "../../core/custom-patterns.js";
7
+ import { resolveHookControl } from "../../core/hook-control.js";
7
8
  import { collectSuppressions, applyExcludePaths } from "../agent/scan.js";
8
9
  import { execSync } from "child_process";
9
10
  import fs from "fs";
@@ -140,37 +141,51 @@ function normalizeInput(raw, format) {
140
141
  }
141
142
  function evaluateToolCall(payload) {
142
143
  const { tool_name, tool_input } = payload;
144
+ // Honor the (trusted-source-only) hook off-switch before doing any work.
145
+ // Master switch off → allow everything; otherwise the two concerns are gated
146
+ // independently inside evaluateBash (command policy + git-commit secret scan).
147
+ const control = resolveHookControl();
148
+ if (!control.hookEnabled)
149
+ return { decision: "allow" };
143
150
  if (tool_name === "Bash") {
144
- return evaluateBash(tool_input?.command || "");
151
+ return evaluateBash(tool_input?.command || "", control);
145
152
  }
146
153
  if (tool_name === "Write" || tool_name === "Edit") {
154
+ if (!control.secretScanEnabled)
155
+ return { decision: "allow" };
147
156
  return evaluateWrite(tool_input || {});
148
157
  }
149
158
  return { decision: "allow" };
150
159
  }
151
- function evaluateBash(command) {
152
- const interceptor = new CommandInterceptor();
160
+ function evaluateBash(command, control) {
153
161
  const audit = new AuditLogger();
154
- const evaluation = interceptor.evaluate(command);
155
- // Blocked — hard deny
156
- if (!evaluation.allowed && !evaluation.requiresApproval) {
157
- audit.logCommandIntercepted(command, false, "blocked", evaluation.reason);
158
- return {
159
- decision: "deny",
160
- reason: formatBlockedMessage(command, evaluation),
161
- };
162
- }
163
- // Requires approval — deny (agent can't provide interactive approval)
164
- if (evaluation.requiresApproval) {
165
- audit.logCommandIntercepted(command, false, "blocked", evaluation.reason);
166
- return {
167
- decision: "deny",
168
- reason: formatApprovalMessage(command, evaluation),
169
- };
162
+ // Command-risk interception — gated by commandPolicy. When disabled, skip the
163
+ // block/approval logic but still fall through to the staged-secret scan below
164
+ // (a user may keep secret scanning while silencing command prompts).
165
+ if (control.commandPolicyEnabled) {
166
+ const interceptor = new CommandInterceptor();
167
+ const evaluation = interceptor.evaluate(command);
168
+ // Blocked — hard deny
169
+ if (!evaluation.allowed && !evaluation.requiresApproval) {
170
+ audit.logCommandIntercepted(command, false, "blocked", evaluation.reason);
171
+ return {
172
+ decision: "deny",
173
+ reason: formatBlockedMessage(command, evaluation),
174
+ };
175
+ }
176
+ // Requires approval — deny (agent can't provide interactive approval)
177
+ if (evaluation.requiresApproval) {
178
+ audit.logCommandIntercepted(command, false, "blocked", evaluation.reason);
179
+ return {
180
+ decision: "deny",
181
+ reason: formatApprovalMessage(command, evaluation),
182
+ };
183
+ }
170
184
  }
171
- // Git commit/push — scan staged files for secrets
185
+ // Git commit/push — scan staged files for secrets. Gated by secretScan so the
186
+ // git-commit secret check survives `commandPolicy` being disabled on its own.
172
187
  const trimmed = command.trim();
173
- if (trimmed.startsWith("git commit") || trimmed.startsWith("git push")) {
188
+ if (control.secretScanEnabled && (trimmed.startsWith("git commit") || trimmed.startsWith("git push"))) {
174
189
  const scanResult = scanStagedFiles();
175
190
  if (scanResult.secretsFound) {
176
191
  // Audit per file so the log records WHICH file + pattern, not a bare count.
@@ -0,0 +1,75 @@
1
+ import { ConfigManager } from "./config-manager.js";
2
+ /**
3
+ * Parse a tri-state from an env var. Returns true (disable), false (force-enable),
4
+ * or undefined (unset / unrecognized → defer to config). Deliberately strict:
5
+ * only explicit, well-known tokens count, so a stray value fails safe to "defer"
6
+ * rather than silently disabling a security control (secure-design D2).
7
+ */
8
+ function envTriState(raw) {
9
+ if (raw == null)
10
+ return undefined;
11
+ const v = raw.trim().toLowerCase();
12
+ if (v === "1" || v === "true" || v === "yes" || v === "on")
13
+ return true; // disable
14
+ if (v === "0" || v === "false" || v === "no" || v === "off")
15
+ return false; // force-enable
16
+ return undefined;
17
+ }
18
+ /**
19
+ * Resolve whether the hook (and its sub-parts) should act.
20
+ *
21
+ * SECURITY (secure-design D1): the disable signal is honored ONLY from trusted,
22
+ * machine-owner-owned sources — the global `~/.rafter/config.json` and the
23
+ * `RAFTER_DISABLE_*` env vars. It is NEVER read from project-local `.rafter.yml`,
24
+ * so cloning a hostile repo cannot silently disable a victim's secret scanning or
25
+ * command interception. That is enforced structurally: this function calls
26
+ * `ConfigManager.load()` (global config only), NOT `loadWithPolicy()` (which
27
+ * merges `.rafter.yml`), and `hooks` is absent from the PolicyFile schema.
28
+ *
29
+ * Precedence (D5): env var overrides global config. Default (D2): enabled; an
30
+ * unreadable config or unrecognized value fails safe to enabled.
31
+ */
32
+ export function resolveHookControl(opts) {
33
+ const env = opts?.env ?? process.env;
34
+ let cfg = opts?.config;
35
+ if (!cfg) {
36
+ try {
37
+ cfg = new ConfigManager().load();
38
+ }
39
+ catch {
40
+ // Unreadable/corrupt global config must not disable the hook — fail safe.
41
+ cfg = undefined;
42
+ }
43
+ }
44
+ const h = cfg?.agent?.hooks;
45
+ // Resolve one axis: env wins over global; absent → default `true` (enabled).
46
+ // `globalDisabled` is the config saying `<key>: false` (disabled) or
47
+ // `hooks.<sub>: true` meaning "disable this sub-part".
48
+ const resolve = (envVal, globalDisabled) => {
49
+ if (envVal !== undefined)
50
+ return { enabled: !envVal, source: "env" };
51
+ if (globalDisabled === true)
52
+ return { enabled: false, source: "global-config" };
53
+ return { enabled: true, source: "default" };
54
+ };
55
+ // Master switch. Global form: `agent.hooks.enabled === false` disables.
56
+ const hook = resolve(envTriState(env.RAFTER_DISABLE_HOOKS), h?.enabled === false ? true : undefined);
57
+ // Sub-parts. Global form: `agent.hooks.secretScan === false` disables that part.
58
+ // A disabled master switch forces every sub-part off regardless of its own setting.
59
+ const secretScan = hook.enabled
60
+ ? resolve(envTriState(env.RAFTER_DISABLE_SECRET_SCAN), h?.secretScan === false ? true : undefined)
61
+ : { enabled: false, source: hook.source };
62
+ const commandPolicy = hook.enabled
63
+ ? resolve(envTriState(env.RAFTER_DISABLE_COMMAND_POLICY), h?.commandPolicy === false ? true : undefined)
64
+ : { enabled: false, source: hook.source };
65
+ return {
66
+ hookEnabled: hook.enabled,
67
+ secretScanEnabled: secretScan.enabled,
68
+ commandPolicyEnabled: commandPolicy.enabled,
69
+ source: {
70
+ hook: hook.source,
71
+ secretScan: secretScan.source,
72
+ commandPolicy: commandPolicy.source,
73
+ },
74
+ };
75
+ }
@@ -1,6 +1,5 @@
1
1
  import { execFile } from "child_process";
2
2
  import { promisify } from "util";
3
- import { randomBytes } from "crypto";
4
3
  import { BinaryManager } from "../utils/binary-manager.js";
5
4
  import fs from "fs";
6
5
  import os from "os";
@@ -48,7 +47,11 @@ export class BetterleaksScanner {
48
47
  if (!blPath) {
49
48
  throw new Error("Betterleaks not available");
50
49
  }
51
- const tmpReport = path.join(os.tmpdir(), `betterleaks-${Date.now()}-${randomBytes(6).toString("hex")}.json`);
50
+ // mkdtempSync atomically creates a private 0700 dir, so the report path
51
+ // can't be pre-created/symlinked by another user on the shared tmpdir —
52
+ // avoids the TOCTOU race a predictable Date.now() filename allowed (CWE-367).
53
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "betterleaks-"));
54
+ const tmpReport = path.join(tmpDir, "report.json");
52
55
  try {
53
56
  // `--` ensures a target path beginning with `-` isn't parsed as a flag by betterleaks.
54
57
  await execFileAsync(blPath, ["dir", "-f", "json", "--report-path", tmpReport, "--", filePath], { timeout: 60000 });
@@ -56,7 +59,6 @@ export class BetterleaksScanner {
56
59
  return { file: filePath, matches: [] };
57
60
  }
58
61
  const results = this.parseResults(tmpReport);
59
- fs.unlinkSync(tmpReport);
60
62
  return {
61
63
  file: filePath,
62
64
  matches: results.map(r => this.convertToPatternMatch(r))
@@ -66,17 +68,23 @@ export class BetterleaksScanner {
66
68
  // Betterleaks exits with --exit-code (default 1) when leaks found — read report before cleanup
67
69
  if (e.code === 1 && fs.existsSync(tmpReport)) {
68
70
  const results = this.parseResults(tmpReport);
69
- fs.unlinkSync(tmpReport);
70
71
  return {
71
72
  file: filePath,
72
73
  matches: results.map(r => this.convertToPatternMatch(r))
73
74
  };
74
75
  }
75
- if (fs.existsSync(tmpReport)) {
76
- fs.unlinkSync(tmpReport);
77
- }
78
76
  throw new Error(`Betterleaks scan failed: ${e.message}`);
79
77
  }
78
+ finally {
79
+ // Best-effort cleanup — a cleanup failure must never mask the scan's
80
+ // real result or its original error.
81
+ try {
82
+ fs.rmSync(tmpDir, { recursive: true, force: true });
83
+ }
84
+ catch {
85
+ // ignore
86
+ }
87
+ }
80
88
  }
81
89
  async scanFiles(filePaths) {
82
90
  const results = [];
@@ -102,7 +110,9 @@ export class BetterleaksScanner {
102
110
  if (!blPath) {
103
111
  throw new Error("Betterleaks not available");
104
112
  }
105
- const tmpReport = path.join(os.tmpdir(), `betterleaks-${Date.now()}-${randomBytes(6).toString("hex")}.json`);
113
+ // Private 0700 dir, atomically created — see scanFile for the TOCTOU rationale (CWE-367).
114
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "betterleaks-"));
115
+ const tmpReport = path.join(tmpDir, "report.json");
106
116
  const subcommand = opts?.useGit ? "git" : "dir";
107
117
  try {
108
118
  // `--` ensures a target path beginning with `-` isn't parsed as a flag by betterleaks.
@@ -111,19 +121,27 @@ export class BetterleaksScanner {
111
121
  return [];
112
122
  }
113
123
  const results = this.parseResults(tmpReport);
114
- fs.unlinkSync(tmpReport);
115
124
  return this.groupByFile(results);
116
125
  }
117
126
  catch (e) {
118
127
  if (fs.existsSync(tmpReport)) {
119
128
  const results = this.parseResults(tmpReport);
120
- fs.unlinkSync(tmpReport);
121
129
  if (e.code === 1) {
122
130
  return this.groupByFile(results);
123
131
  }
124
132
  }
125
133
  throw new Error(`Betterleaks scan failed: ${e.message}`);
126
134
  }
135
+ finally {
136
+ // Best-effort cleanup — a cleanup failure must never mask the scan's
137
+ // real result or its original error.
138
+ try {
139
+ fs.rmSync(tmpDir, { recursive: true, force: true });
140
+ }
141
+ catch {
142
+ // ignore
143
+ }
144
+ }
127
145
  }
128
146
  parseResults(reportPath) {
129
147
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rafter-security/cli",
3
- "version": "0.8.5",
3
+ "version": "0.8.6",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: rafter-security
3
3
  description: Security toolkit for AI workflows. Use when scanning code or repos for vulnerabilities, auditing third-party skills/MCPs/agent configs before installing, evaluating shell commands before running them, or generating secure design questions for new features. Provides `rafter run` (remote SAST + SCA, needs RAFTER_API_KEY), `rafter secrets` (offline secrets-only), `rafter agent exec --dry-run` (command-risk classification), and `rafter skill review`.
4
- version: 0.8.5
4
+ version: 0.8.6
5
5
  homepage: https://rafter.so
6
6
  metadata:
7
7
  openclaw: