@rafter-security/cli 0.10.2 → 0.10.4

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.
@@ -2,7 +2,10 @@ import { Command } from "commander";
2
2
  import { CommandInterceptor } from "../../core/command-interceptor.js";
3
3
  import { RegexScanner } from "../../scanners/regex-scanner.js";
4
4
  import { AuditLogger } from "../../core/audit-logger.js";
5
+ import os from "node:os";
6
+ import { modifiesRafterSecurityConfig } from "../../core/risk-rules.js";
5
7
  import { ConfigManager } from "../../core/config-manager.js";
8
+ import { getRafterDir } from "../../core/config-defaults.js";
6
9
  import { applySuppressions } from "../../core/custom-patterns.js";
7
10
  import { resolveHookControl } from "../../core/hook-control.js";
8
11
  import { collectSuppressions, applyExcludePaths } from "../agent/scan.js";
@@ -50,6 +53,16 @@ const RISK_DESCRIPTIONS = {
50
53
  };
51
54
  function formatBlockedMessage(command, evaluation) {
52
55
  const cmdDisplay = command.length > 60 ? command.slice(0, 60) + "..." : command;
56
+ // rf-vnxs: say what actually happened. "irreversible system damage" is the
57
+ // wrong sentence for a config write, and a wrong reason teaches the agent to
58
+ // hunt for a way around a rule whose shape it was never told.
59
+ if (modifiesRafterSecurityConfig(command)) {
60
+ return (`\u2717 Rafter blocked: ${cmdDisplay}\n` +
61
+ ` Rule: rafter security configuration is protected (rf-vnxs)\n` +
62
+ ` Risk: CRITICAL\u2014this command reconfigures or removes rafter's own\n` +
63
+ ` guardrail. The gate cannot approve its own disarming. A person\n` +
64
+ ` must make this change outside an agent session.`);
65
+ }
53
66
  const rule = evaluation.matchedPattern ?? "policy violation";
54
67
  const label = RISK_LABELS[evaluation.riskLevel] ?? evaluation.riskLevel.toUpperCase();
55
68
  const desc = RISK_DESCRIPTIONS[evaluation.riskLevel] ?? "";
@@ -60,7 +73,7 @@ function formatApprovalMessage(command, evaluation) {
60
73
  const rule = evaluation.matchedPattern ?? "policy match";
61
74
  const label = RISK_LABELS[evaluation.riskLevel] ?? evaluation.riskLevel.toUpperCase();
62
75
  const desc = RISK_DESCRIPTIONS[evaluation.riskLevel] ?? "";
63
- return `\u26a0 Rafter: approval required\n Command: ${cmdDisplay}\n Rule: ${rule}\n Risk: ${label}\u2014${desc}\n\nTo approve: rafter agent exec --approve "${command}"\nTo configure: rafter agent config set agent.riskLevel minimal`;
76
+ return `\u26a0 Rafter: approval required\n Command: ${cmdDisplay}\n Rule: ${rule}\n Risk: ${label}\u2014${desc}\n\nTo approve: a person must run \`rafter agent exec "${command}"\` at an\n interactive terminal and confirm. There is no flag that\n skips the prompt.`;
64
77
  }
65
78
  export function createHookPretoolCommand() {
66
79
  return new Command("pretool")
@@ -209,7 +222,44 @@ function evaluateBash(command, control) {
209
222
  audit.logCommandIntercepted(command, true, "allowed");
210
223
  return { decision: "allow" };
211
224
  }
225
+ /**
226
+ * True if this write targets rafter's own configuration directory.
227
+ *
228
+ * rf-vnxs, fourth route. Blocking the CLI invocation is not enough: the config
229
+ * is a FILE, and an agent holding a Write/Edit tool does not need the CLI to
230
+ * disable the hook — it can write `~/.rafter/config.json` directly. Three
231
+ * independent routes to the unblockable tier had already been found one at a
232
+ * time in this codebase; this is the one that would have been the fourth.
233
+ */
234
+ function writesRafterSecurityConfig(filePath) {
235
+ if (!filePath)
236
+ return false;
237
+ try {
238
+ const expanded = filePath.startsWith("~")
239
+ ? path.join(os.homedir(), filePath.slice(1))
240
+ : filePath;
241
+ const target = path.resolve(expanded);
242
+ const rafterDir = path.resolve(getRafterDir());
243
+ return target === rafterDir || target.startsWith(rafterDir + path.sep);
244
+ }
245
+ catch {
246
+ return false;
247
+ }
248
+ }
212
249
  function evaluateWrite(toolInput) {
250
+ // rf-vnxs: checked FIRST, and before the no-content early return, because a
251
+ // truncating write with empty content disables the hook just as well as one
252
+ // carrying JSON.
253
+ if (writesRafterSecurityConfig(toolInput.file_path ?? "")) {
254
+ return {
255
+ decision: "deny",
256
+ reason: "\u2717 Rafter blocked: write to rafter's own configuration\n" +
257
+ " Rule: rafter security configuration is protected (rf-vnxs)\n" +
258
+ " Risk: CRITICAL\u2014editing this file reconfigures or removes the\n" +
259
+ " guardrail. The gate cannot approve its own disarming. A\n" +
260
+ " person must make this change outside an agent session.",
261
+ };
262
+ }
213
263
  // Write uses "content", Edit uses "new_string"
214
264
  const content = toolInput.content || toolInput.new_string || "";
215
265
  if (!content) {
@@ -1,6 +1,6 @@
1
1
  import { ConfigManager } from "./config-manager.js";
2
2
  import { AuditLogger } from "./audit-logger.js";
3
- import { assessCommandRisk, matchedCriticalPattern, sanitizeCommandForMatching, } from "./risk-rules.js";
3
+ import { assessCommandRisk, matchedCriticalPattern, sanitizeCommandForMatching, isChainedCommand, } from "./risk-rules.js";
4
4
  export class CommandInterceptor {
5
5
  constructor() {
6
6
  this.config = new ConfigManager();
@@ -67,6 +67,48 @@ export class CommandInterceptor {
67
67
  };
68
68
  }
69
69
  }
70
+ // Check the positive allowlist. Deliberately AFTER blockedPatterns and
71
+ // BEFORE requireApproval: a deny rule always wins, and an allow rule's
72
+ // whole job is to suppress the approval prompt for a known-safe command.
73
+ //
74
+ // Two guards keep an allowlist from becoming a hole in the guard rail:
75
+ //
76
+ // - A `critical` command is never allowlistable. NOTE: this guard is
77
+ // currently UNREACHABLE — evaluate() hard-blocks critical at the top of
78
+ // the method, before this loop — and a mutation sweep proved it:
79
+ // deleting the guard leaves every test green, in both runtimes. Kept as
80
+ // defence in depth, because it becomes the only protection the day that
81
+ // early block is narrowed. Do not write a test claiming to exercise it;
82
+ // such a test passes with the guard deleted.
83
+ // - A match does not apply when the command holds more than one
84
+ // statement. Patterns are unanchored by request, so without this
85
+ // "^git push" would wave through `rm -rf / && git push` — or, via the
86
+ // newline the original regex missed, anything on a second line.
87
+ // Defence in depth behind the config validator: a non-array here is not
88
+ // merely wrong, it is dangerous. A bare string iterates as CHARACTERS, and
89
+ // the first one of `"^git status"` is `^`, which matches every command —
90
+ // the allowlist would allow everything. The validator catches the shape
91
+ // `config set` writes; this catches every other way it could arrive.
92
+ const allowedPatterns = Array.isArray(policy.allowedPatterns) ? policy.allowedPatterns : [];
93
+ for (const pattern of allowedPatterns) {
94
+ if (!this.matchesPattern(command, pattern))
95
+ continue;
96
+ if (isChainedCommand(command)) {
97
+ // Fall through to normal classification rather than allowing.
98
+ break;
99
+ }
100
+ if (this.assessRisk(command) === "critical") {
101
+ break;
102
+ }
103
+ return {
104
+ command,
105
+ riskLevel: "low",
106
+ allowed: true,
107
+ requiresApproval: false,
108
+ reason: `Matches allowed pattern: ${pattern}`,
109
+ matchedPattern: pattern
110
+ };
111
+ }
70
112
  // Check approval patterns
71
113
  for (const pattern of policy.requireApproval) {
72
114
  if (this.matchesPattern(command, pattern)) {
@@ -54,6 +54,8 @@ export function getDefaultConfig() {
54
54
  mode: "approve-dangerous",
55
55
  blockedPatterns: [...DEFAULT_BLOCKED_PATTERNS],
56
56
  requireApproval: [...DEFAULT_REQUIRE_APPROVAL],
57
+ // Empty by default: an allowlist is opt-in, per project.
58
+ allowedPatterns: [],
57
59
  },
58
60
  outputFiltering: {
59
61
  redactSecrets: true,
@@ -73,6 +73,10 @@ function validateConfig(raw) {
73
73
  console.error('Warning: config "agent.commandPolicy.blockedPatterns" must be an array of strings — using default.');
74
74
  cp.blockedPatterns = [...defaults.agent.commandPolicy.blockedPatterns];
75
75
  }
76
+ if (cp.allowedPatterns !== undefined && (!Array.isArray(cp.allowedPatterns) || !cp.allowedPatterns.every((v) => typeof v === "string"))) {
77
+ console.error('Warning: config "agent.commandPolicy.allowedPatterns" must be an array of strings — using default.');
78
+ cp.allowedPatterns = [...(defaults.agent.commandPolicy.allowedPatterns ?? [])];
79
+ }
76
80
  if (cp.requireApproval !== undefined && (!Array.isArray(cp.requireApproval) || !cp.requireApproval.every((v) => typeof v === "string"))) {
77
81
  console.error('Warning: config "agent.commandPolicy.requireApproval" must be an array of strings — using default.');
78
82
  cp.requireApproval = [...defaults.agent.commandPolicy.requireApproval];
@@ -285,10 +289,22 @@ export class ConfigManager {
285
289
  const policy = loadPolicy();
286
290
  if (!policy)
287
291
  return config;
288
- // Ensure agent block exists
292
+ // Ensure agent block exists, AND that commandPolicy inside it does.
293
+ //
294
+ // Checking only for `agent` was not enough. A config file that carries an
295
+ // `agent` block without a `commandPolicy` key — a partial or hand-edited
296
+ // ~/.rafter/config.json, which is a normal thing to have — reaches the
297
+ // assignments below and throws
298
+ // TypeError: Cannot set properties of undefined (setting 'mode')
299
+ // the moment the repo also has a .rafter.yml with a command_policy block.
300
+ // Found 2026-09-10 by an end-to-end test that loads a real config instead
301
+ // of a stub; the stubbed unit tests could not see it.
302
+ const agentDefaults = getDefaultConfig().agent;
289
303
  if (!config.agent) {
290
- const defaults = getDefaultConfig();
291
- config.agent = defaults.agent;
304
+ config.agent = agentDefaults;
305
+ }
306
+ if (!config.agent.commandPolicy) {
307
+ config.agent.commandPolicy = { ...agentDefaults.commandPolicy };
292
308
  }
293
309
  // Risk level
294
310
  if (policy.riskLevel && config.agent) {
@@ -465,6 +481,8 @@ export function mergeCommandPolicy(target, project, allowOverride) {
465
481
  target.blockedPatterns = project.blockedPatterns;
466
482
  if (project.requireApproval)
467
483
  target.requireApproval = project.requireApproval;
484
+ if (project.allowedPatterns)
485
+ target.allowedPatterns = project.allowedPatterns;
468
486
  return;
469
487
  }
470
488
  if (project.mode && project.mode !== target.mode) {
@@ -484,4 +502,16 @@ export function mergeCommandPolicy(target, project, allowOverride) {
484
502
  if (project.requireApproval) {
485
503
  target.requireApproval = unionPatterns(target.requireApproval, project.requireApproval);
486
504
  }
505
+ // allowedPatterns is NOT unioned, and that asymmetry is the whole point.
506
+ // Unioning blockedPatterns or requireApproval can only ever ADD restriction,
507
+ // so a project contributing to them is safe. An allowlist is the opposite:
508
+ // it is a grant. Union it and a cloned repo ships
509
+ // command_policy: { allowed_patterns: [".*"] }
510
+ // and waves every non-critical command through — which is precisely the
511
+ // bypass the floor exists to prevent (sable-nz4y / rf-adth). So the owner's
512
+ // allowlist stands and the project's is refused unless the owner has
513
+ // explicitly opted into project override.
514
+ if (project.allowedPatterns) {
515
+ console.error(`Warning: project policy sets agent.commandPolicy.allowed_patterns, which can only loosen command policy — ignoring. Set agent.commandPolicy.allowProjectOverride: true in your global config to allow project policies to loosen command policy.`);
516
+ }
487
517
  }
@@ -83,6 +83,9 @@ function mapPolicy(raw) {
83
83
  if (Array.isArray(raw.command_policy.require_approval)) {
84
84
  policy.commandPolicy.requireApproval = raw.command_policy.require_approval;
85
85
  }
86
+ if (Array.isArray(raw.command_policy.allowed_patterns)) {
87
+ policy.commandPolicy.allowedPatterns = raw.command_policy.allowed_patterns;
88
+ }
86
89
  }
87
90
  if (raw.scan && typeof raw.scan === "object") {
88
91
  policy.scan = {};
@@ -266,6 +269,12 @@ function validatePolicy(policy, raw) {
266
269
  delete policy.commandPolicy.requireApproval;
267
270
  }
268
271
  }
272
+ if (policy.commandPolicy.allowedPatterns !== undefined) {
273
+ if (!Array.isArray(policy.commandPolicy.allowedPatterns) || !policy.commandPolicy.allowedPatterns.every((v) => typeof v === "string")) {
274
+ console.error(`Warning: "command_policy.allowed_patterns" must be an array of strings — ignoring.`);
275
+ delete policy.commandPolicy.allowedPatterns;
276
+ }
277
+ }
269
278
  }
270
279
  if (policy.scan) {
271
280
  if (policy.scan.excludePaths !== undefined) {
@@ -749,10 +749,145 @@ function stripHeredocBodies(command) {
749
749
  export function sanitizeCommandForMatching(command) {
750
750
  return sanitize(stripHeredocBodies(command), 0);
751
751
  }
752
+ /**
753
+ * True if the command contains more than one statement.
754
+ *
755
+ * Asked of the TOKENIZER rather than a regex, deliberately. The first version
756
+ * of this was `/[;|&]|&&|\|\|/`, which omits the newline — and a newline has
757
+ * been a statement separator in this file since rf-6pqx, six lines from where
758
+ * that regex sat. The gap was reachable in one step: with `^git push origin
759
+ * feature/` allowlisted,
760
+ *
761
+ * git push origin feature/x
762
+ * git push --force origin main
763
+ *
764
+ * classified `allow`, because the chain check saw no operator. The agent being
765
+ * gated writes the whole string, so prefixing an allowlisted line is free.
766
+ *
767
+ * The tokenizer already normalises `\n` to `;`, so routing the question through
768
+ * it removes the second, narrower definition instead of widening it. One source
769
+ * of truth for "what separates two commands".
770
+ */
771
+ export function isChainedCommand(command) {
772
+ const { pieces } = tokenize(command);
773
+ return pieces.some((p) => p.op !== null && CHAIN_OPS.has(p.op));
774
+ }
752
775
  /**
753
776
  * Assess risk level of a command string.
754
777
  */
778
+ /**
779
+ * rf-vnxs — reconfiguring rafter's OWN security controls is a PROTECTED CLASS.
780
+ *
781
+ * The gate must never approve its own disarming. On 0.10.1 it did: the hook
782
+ * rated `rafter agent config set agent.hooks.enabled false` as `low`, allowed
783
+ * it, and every later command — including the CRITICAL tier that no policy,
784
+ * mode or deny-list can override — was then permitted. Three steps, no
785
+ * malformed command, and it persists to config.json.
786
+ *
787
+ * This is matched STRUCTURALLY — resolved exec plus an argv walk — and not by
788
+ * string, because the spellings are unbounded and were all observed allowed on
789
+ * the published artifact: extra whitespace, `FALSE`, `npx @rafter-security/cli
790
+ * …`, `sudo -E rafter …`, the `agent disable` component route, and three
791
+ * different self-disabling keys (hooks.enabled, hooks.secretScan,
792
+ * hooks.commandPolicy). A blacklist of one string is one alias away from being
793
+ * a no-op — the same shape as the CHAIN_OPS one-liner that was proven inert
794
+ * only by running the shipped module.
795
+ */
796
+ const RAFTER_EXECS = new Set(["rafter", "rafter-cli"]);
797
+ const PACKAGE_RUNNERS = new Set(["npx", "bunx", "pnpx", "dlx", "pnpm", "yarn", "bun"]);
798
+ const RAFTER_PACKAGE = /^(?:@rafter-security\/cli|rafter-cli|rafter)(?:@[\w.^~*-]+)?$/;
799
+ /** Config keys that gate the hook. Namespace, not a leaf — see hook-control. */
800
+ const PROTECTED_CONFIG_KEY = /^(?:agent\.)?(?:hooks|commandpolicy)\b|^agent\.risklevel$/;
801
+ /**
802
+ * True if this statement's argv reconfigures or removes a rafter security
803
+ * control.
804
+ *
805
+ * The rafter invocation is looked for at ANY position, not just as the
806
+ * statement's own exec, because a shell that carries a command string puts it
807
+ * in the operand: `bash -c "rafter agent config set agent.hooks.enabled false"`
808
+ * and `bash -c "$(echo rafter …)"` both sanitize to a statement whose exec is
809
+ * `bash`, and an exec-only walk reads them — wrongly — as not-rafter. A quoted
810
+ * word is skipped on the raw pass so that `echo 'rafter agent config set …'`
811
+ * stays prose; the sanitized pass is where an actually-executed operand has
812
+ * already been unwrapped for us.
813
+ */
814
+ function statementDisarmsRafter(words) {
815
+ for (let j = 0; j < words.length; j++) {
816
+ if (words[j].quoted)
817
+ continue;
818
+ let k = j;
819
+ let exec = execName(words[k].text);
820
+ k++;
821
+ // `npx [-y] @rafter-security/cli …`, `pnpm dlx rafter-cli …`, `bunx rafter …`
822
+ if (PACKAGE_RUNNERS.has(exec)) {
823
+ while (k < words.length && (words[k].text.startsWith("-") || ["dlx", "exec"].includes(words[k].text.toLowerCase())))
824
+ k++;
825
+ if (k >= words.length || !RAFTER_PACKAGE.test(words[k].text.toLowerCase()))
826
+ continue;
827
+ k++;
828
+ exec = "rafter";
829
+ }
830
+ if (!RAFTER_EXECS.has(exec))
831
+ continue;
832
+ const args = words.slice(k).map((w) => w.text.toLowerCase()).filter((a) => !a.startsWith("-"));
833
+ for (let n = 0; n + 1 < args.length; n++) {
834
+ // `… config set <protected key>` — the key is the next non-flag operand.
835
+ if (args[n] === "config" && args[n + 1] === "set") {
836
+ const key = args[n + 2];
837
+ if (key && PROTECTED_CONFIG_KEY.test(key))
838
+ return true;
839
+ }
840
+ // `… agent disable <component>` — uninstalls a control outright.
841
+ if (args[n] === "agent" && args[n + 1] === "disable")
842
+ return true;
843
+ }
844
+ }
845
+ return false;
846
+ }
847
+ /**
848
+ * True if the command disarms rafter, checked on BOTH the raw text and the
849
+ * sanitized text. Raw catches the ordinary invocation; sanitized catches the
850
+ * case where a shell runs the OUTPUT of something else — `bash -c "$(echo
851
+ * rafter agent config set …)"`, whose own exec is `echo` and which a walk over
852
+ * the raw argv therefore reads, correctly, as a print. That is the same
853
+ * executes-output distinction sable-c6an turned on.
854
+ */
855
+ export function modifiesRafterSecurityConfig(command) {
856
+ if (disarmsRafter(command, 0))
857
+ return true;
858
+ const sanitized = sanitizeCommandForMatching(command);
859
+ return sanitized !== command && disarmsRafter(sanitized, 0);
860
+ }
861
+ /** True if any statement (or any command substitution) disarms rafter. */
862
+ function disarmsRafter(command, depth = 0) {
863
+ if (depth > MAX_SANITIZE_DEPTH)
864
+ return false;
865
+ const { pieces } = tokenize(command);
866
+ let stmt = [];
867
+ const statements = [];
868
+ for (const p of pieces) {
869
+ if (p.op !== null) {
870
+ if (CHAIN_OPS.has(p.op) || p.op === "\n" || p.op === "\r") {
871
+ statements.push(stmt);
872
+ stmt = [];
873
+ }
874
+ continue;
875
+ }
876
+ stmt.push(p);
877
+ for (const sub of p.substs ?? []) {
878
+ if (disarmsRafter(sub, depth + 1))
879
+ return true;
880
+ }
881
+ }
882
+ statements.push(stmt);
883
+ return statements.some(statementDisarmsRafter);
884
+ }
755
885
  export function assessCommandRisk(command) {
886
+ // rf-vnxs: checked on the RAW command, before sanitization, because the
887
+ // disarm is an ordinary well-formed invocation — there is nothing malformed
888
+ // for the sanitizer to normalise, and redaction could hide the operand.
889
+ if (modifiesRafterSecurityConfig(command))
890
+ return "critical";
756
891
  const cmd = sanitizeCommandForMatching(command).toLowerCase().trim();
757
892
  if (!cmd)
758
893
  return "low";
@@ -777,6 +912,9 @@ export function assessCommandRisk(command) {
777
912
  * built-in rule matched.
778
913
  */
779
914
  export function matchedCriticalPattern(command) {
915
+ if (modifiesRafterSecurityConfig(command)) {
916
+ return "rafter security configuration is protected (rf-vnxs)";
917
+ }
780
918
  const cmd = sanitizeCommandForMatching(command).toLowerCase().trim();
781
919
  for (const pattern of CRITICAL_PATTERNS) {
782
920
  if (pattern.test(cmd))
@@ -80,6 +80,34 @@ export const DEFAULT_SECRET_PATTERNS = [
80
80
  severity: "critical",
81
81
  description: "Stripe Restricted API Key detected"
82
82
  },
83
+ // OpenAI (rf-f5is / se-wagv, external report). The hook's Write gate is
84
+ // regex-only, and this file had NO OpenAI rule at all — so `sk-proj-` and
85
+ // legacy keys were ALLOWED through the gate at any length, while
86
+ // `rafter secrets` caught them via betterleaks. The two engines disagreed,
87
+ // and the one guarding writes was the blind one.
88
+ //
89
+ // No `(?i)`: these prefixes and their base62 bodies are case-sensitive, and
90
+ // the convention here is that prefixed vendor tokens (ghp_, AKIA, AIza, xox)
91
+ // match case-sensitively. Lower-casing them would only add false positives.
92
+ {
93
+ name: "OpenAI API Key",
94
+ regex: "sk-(proj|svcacct|admin)-[A-Za-z0-9_-]{40,}",
95
+ severity: "critical",
96
+ description: "OpenAI project/service/admin API key detected"
97
+ },
98
+ {
99
+ name: "OpenAI API Key (legacy)",
100
+ regex: "sk-[A-Za-z0-9]{20}T3BlbkFJ[A-Za-z0-9]{20}",
101
+ severity: "critical",
102
+ description: "OpenAI legacy API key detected"
103
+ },
104
+ // Supabase (rf-f5is / se-wagv). Detected by NEITHER engine at any length.
105
+ {
106
+ name: "Supabase Secret Key",
107
+ regex: "sb_secret_[A-Za-z0-9_-]{20,}",
108
+ severity: "critical",
109
+ description: "Supabase secret key detected"
110
+ },
83
111
  // Twilio
84
112
  {
85
113
  name: "Twilio API Key",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rafter-security/cli",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
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.10.2
4
+ version: 0.10.4
5
5
  homepage: https://rafter.so
6
6
  metadata:
7
7
  openclaw:
@@ -24,23 +24,46 @@ Every command (Bash-like tool call) gets classified into one of four tiers by `s
24
24
  | `high` | Destructive or privileged (force push, `sudo`, broad file deletion, curl | sh) | **prompt** the agent / user for approval |
25
25
  | `critical` | Likely irreversible damage (`rm -rf /`, DB drop, wiping .git, repo-wide chmod) | **block** hard |
26
26
 
27
- Tiers are derived from regex patterns in `risk-rules.ts` (`CRITICAL_PATTERNS`, `HIGH_PATTERNS`, `MEDIUM_PATTERNS`) plus a `SAFE_PREFIX` allowlist. Presence of chain operators (`&&`, `||`, `;`, `|`) disqualifies the safe-prefix shortcut.
27
+ Tiers are derived from regex patterns in `risk-rules.ts` (`CRITICAL_PATTERNS`, `HIGH_PATTERNS`, `MEDIUM_PATTERNS`) plus a `SAFE_PREFIX` allowlist. A command holding more than one statement disqualifies the safe-prefix shortcut. Statement separators are whatever the tokenizer treats as one — `&&`, `||`, `;`, `|`, `&`, and a NEWLINE — rather than a hand-kept list; the newline was missing from an earlier hand-kept copy and that was a live bypass.
28
28
 
29
29
  ## Policy Overrides
30
30
 
31
31
  `.rafter.yml` (project) and `~/.rafter/config.yml` (global) can override defaults:
32
32
 
33
33
  ```yaml
34
- risk:
34
+ command_policy:
35
35
  blocked_patterns:
36
36
  - "terraform destroy"
37
37
  require_approval:
38
38
  - "^npm publish"
39
- allow:
40
- - "^pnpm run test" # force low regardless of content
39
+ allowed_patterns:
40
+ - "^pnpm run test" # force low, skipping the approval prompt
41
+ - "git push --force-with-lease"
41
42
  ```
42
43
 
43
- Merge order (most specific wins): project `.rafter.yml` > global config > built-in defaults. Dump the effective merged policy with `rafter policy export`.
44
+ **On `allowed_patterns`.** Until 2026-09-07 this section documented a
45
+ `risk.allow` key that was never implemented — a customer went looking for it
46
+ and found nothing. The real key is `command_policy.allowed_patterns`, and it
47
+ now exists.
48
+
49
+ It is a positive allowlist for the known-safe command that trips a broad tier:
50
+ the motivating case is `git push --force-with-lease` to a feature branch on a
51
+ repo whose `main` is protected server-side, which classifies `high` and prompts
52
+ on every push even though the dangerous version cannot land. Dropping
53
+ `risk_level` to silence that is too blunt — it would also stop prompting for
54
+ `sudo` and `curl | sh`.
55
+
56
+ Three properties keep an allowlist from becoming a hole in the guard rail:
57
+
58
+ 1. **`blocked_patterns` always wins.** An allow rule never re-opens what a deny
59
+ rule closed.
60
+ 2. **`critical` is never allowlistable.** `rm -rf /`, a DB drop and wiping
61
+ `.git` stay blocked whatever the config says.
62
+ 3. **Chain operators disqualify a match.** Patterns are unanchored, so without
63
+ this `"git push"` would wave through `rm -rf / && git push`. A chained
64
+ command is classified exactly as it would be with no allowlist configured.
65
+
66
+ Merge order: project `.rafter.yml` > global config > built-in defaults for most keys — but NOT for `command_policy`, which is a floor. A project policy may tighten command policy and never loosen it: `mode` is accepted only if at least as strict, `blocked_patterns` and `require_approval` are unioned, and `allowed_patterns` — being a grant rather than a restriction — is refused outright unless the machine owner sets `agent.commandPolicy.allowProjectOverride: true` in their global config. Dump the effective merged policy with `rafter policy export`.
44
67
 
45
68
  ## How to Interpret a Block
46
69