@rafter-security/cli 0.10.1 → 0.10.3

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) {
@@ -77,6 +77,10 @@ function validateConfig(raw) {
77
77
  console.error('Warning: config "agent.commandPolicy.requireApproval" must be an array of strings — using default.');
78
78
  cp.requireApproval = [...defaults.agent.commandPolicy.requireApproval];
79
79
  }
80
+ if (cp.allowProjectOverride !== undefined && typeof cp.allowProjectOverride !== "boolean") {
81
+ console.error('Warning: config "agent.commandPolicy.allowProjectOverride" must be a boolean — ignoring (project policies cannot loosen command policy).');
82
+ delete cp.allowProjectOverride;
83
+ }
80
84
  }
81
85
  // audit
82
86
  const audit = agent.audit;
@@ -261,6 +265,18 @@ export class ConfigManager {
261
265
  this.save(config);
262
266
  }
263
267
  }
268
+ /**
269
+ * Whether the machine owner has opted out of the project-policy floor.
270
+ *
271
+ * Read from `this.load()` — the GLOBAL config file only. It must never be
272
+ * sourced from the project `.rafter.yml`, because a repo that could set this
273
+ * flag could switch the floor off and the protection would be worth nothing.
274
+ * That asymmetry is the whole point of the setting, so it is read here rather
275
+ * than off the already-merged config.
276
+ */
277
+ allowsProjectOverride() {
278
+ return this.load().agent?.commandPolicy?.allowProjectOverride === true;
279
+ }
264
280
  /**
265
281
  * Load config merged with .rafter.yml policy (policy wins)
266
282
  */
@@ -278,17 +294,10 @@ export class ConfigManager {
278
294
  if (policy.riskLevel && config.agent) {
279
295
  config.agent.riskLevel = policy.riskLevel;
280
296
  }
281
- // Command policy — arrays replace, not append
297
+ // Command policy — the global config is a FLOOR the project may raise but
298
+ // never lower. See `mergeCommandPolicy` (sable-nz4y).
282
299
  if (policy.commandPolicy && config.agent) {
283
- if (policy.commandPolicy.mode) {
284
- config.agent.commandPolicy.mode = policy.commandPolicy.mode;
285
- }
286
- if (policy.commandPolicy.blockedPatterns) {
287
- config.agent.commandPolicy.blockedPatterns = policy.commandPolicy.blockedPatterns;
288
- }
289
- if (policy.commandPolicy.requireApproval) {
290
- config.agent.commandPolicy.requireApproval = policy.commandPolicy.requireApproval;
291
- }
300
+ mergeCommandPolicy(config.agent.commandPolicy, policy.commandPolicy, this.allowsProjectOverride());
292
301
  }
293
302
  // Scan settings
294
303
  if (policy.scan && config.agent) {
@@ -390,3 +399,89 @@ export class ConfigManager {
390
399
  return item && typeof item === "object" && !Array.isArray(item);
391
400
  }
392
401
  }
402
+ // ---------------------------------------------------------------------------
403
+ // Project-policy floor (sable-nz4y)
404
+ // ---------------------------------------------------------------------------
405
+ //
406
+ // Policy discovery walks up from cwd to the git root, so the `.rafter.yml` this
407
+ // merges is a file IN THE REPOSITORY BEING WORKED ON. rafter ships inside agent
408
+ // pretool hooks, so on an untrusted repo that file is attacker-controlled.
409
+ //
410
+ // It used to REPLACE the machine owner's command policy wholesale: a repo
411
+ // shipping `{ mode: allow-all, blocked_patterns: [], require_approval: [] }`
412
+ // switched off every guardrail below the unconditional critical hard-block —
413
+ // including patterns the owner had explicitly deny-listed.
414
+ //
415
+ // The rule this restores is the one the codebase already states ~20 lines below,
416
+ // for the Plus-approval gate (sable-9ddf): a project policy may turn a gate ON,
417
+ // but must never turn OFF a gate the machine owner set globally. So the global
418
+ // config is a FLOOR:
419
+ //
420
+ // * blockedPatterns / requireApproval — UNION. A project adds rules; removing
421
+ // one the owner set is not expressible.
422
+ // * mode — accepted only when at least as strict as the owner's. A project
423
+ // may tighten `allow-all` to `approve-dangerous`, never the reverse.
424
+ //
425
+ // The owner (never the repo) can opt out with
426
+ // `agent.commandPolicy.allowProjectOverride: true` in the GLOBAL config, which
427
+ // restores the old replace semantics for people who deliberately delegate policy
428
+ // to their projects.
429
+ //
430
+ // Note this does not touch the critical hard-block, which was never reachable
431
+ // from policy: CommandInterceptor.evaluate() returns on `critical` BEFORE any
432
+ // policy is loaded. That property held under every hostile policy tested; this
433
+ // change is about everything *below* critical.
434
+ /**
435
+ * Strictness rank for command-policy modes. Higher is stricter.
436
+ *
437
+ * `approve-dangerous` is the only mode that gates on assessed risk, so it is
438
+ * strictly stronger than the other two. `deny-list` and `allow-all` currently
439
+ * behave identically in the interceptor (both rely solely on the explicit
440
+ * pattern lists, which are checked regardless of mode) — they are ranked apart
441
+ * anyway so that a project moving `allow-all` -> `deny-list` is treated as a
442
+ * tightening rather than a lateral move if their behavior ever diverges.
443
+ */
444
+ const COMMAND_MODE_STRICTNESS = {
445
+ "allow-all": 0,
446
+ "deny-list": 1,
447
+ "approve-dangerous": 2,
448
+ };
449
+ /** Union preserving order: floor entries first, then project entries not already present. */
450
+ function unionPatterns(floor, project) {
451
+ const seen = new Set(floor);
452
+ return [...floor, ...project.filter((p) => !seen.has(p))];
453
+ }
454
+ /**
455
+ * Merge a project command policy over the global one under the floor rule.
456
+ *
457
+ * Mutates `target` in place, matching the surrounding merge style. When
458
+ * `allowOverride` is true the pre-sable-nz4y replace semantics are used.
459
+ */
460
+ export function mergeCommandPolicy(target, project, allowOverride) {
461
+ if (allowOverride) {
462
+ if (project.mode)
463
+ target.mode = project.mode;
464
+ if (project.blockedPatterns)
465
+ target.blockedPatterns = project.blockedPatterns;
466
+ if (project.requireApproval)
467
+ target.requireApproval = project.requireApproval;
468
+ return;
469
+ }
470
+ if (project.mode && project.mode !== target.mode) {
471
+ const projectRank = COMMAND_MODE_STRICTNESS[project.mode];
472
+ const floorRank = COMMAND_MODE_STRICTNESS[target.mode];
473
+ // An unknown mode is not demonstrably at least as strict, so it is refused.
474
+ if (projectRank !== undefined && floorRank !== undefined && projectRank >= floorRank) {
475
+ target.mode = project.mode;
476
+ }
477
+ else {
478
+ console.error(`Warning: project policy sets agent.commandPolicy.mode "${project.mode}", which is less strict than "${target.mode}" from your global config — ignoring. Set agent.commandPolicy.allowProjectOverride: true in your global config to allow project policies to loosen command policy.`);
479
+ }
480
+ }
481
+ if (project.blockedPatterns) {
482
+ target.blockedPatterns = unionPatterns(target.blockedPatterns, project.blockedPatterns);
483
+ }
484
+ if (project.requireApproval) {
485
+ target.requireApproval = unionPatterns(target.requireApproval, project.requireApproval);
486
+ }
487
+ }
@@ -752,7 +752,119 @@ export function sanitizeCommandForMatching(command) {
752
752
  /**
753
753
  * Assess risk level of a command string.
754
754
  */
755
+ /**
756
+ * rf-vnxs — reconfiguring rafter's OWN security controls is a PROTECTED CLASS.
757
+ *
758
+ * The gate must never approve its own disarming. On 0.10.1 it did: the hook
759
+ * rated `rafter agent config set agent.hooks.enabled false` as `low`, allowed
760
+ * it, and every later command — including the CRITICAL tier that no policy,
761
+ * mode or deny-list can override — was then permitted. Three steps, no
762
+ * malformed command, and it persists to config.json.
763
+ *
764
+ * This is matched STRUCTURALLY — resolved exec plus an argv walk — and not by
765
+ * string, because the spellings are unbounded and were all observed allowed on
766
+ * the published artifact: extra whitespace, `FALSE`, `npx @rafter-security/cli
767
+ * …`, `sudo -E rafter …`, the `agent disable` component route, and three
768
+ * different self-disabling keys (hooks.enabled, hooks.secretScan,
769
+ * hooks.commandPolicy). A blacklist of one string is one alias away from being
770
+ * a no-op — the same shape as the CHAIN_OPS one-liner that was proven inert
771
+ * only by running the shipped module.
772
+ */
773
+ const RAFTER_EXECS = new Set(["rafter", "rafter-cli"]);
774
+ const PACKAGE_RUNNERS = new Set(["npx", "bunx", "pnpx", "dlx", "pnpm", "yarn", "bun"]);
775
+ const RAFTER_PACKAGE = /^(?:@rafter-security\/cli|rafter-cli|rafter)(?:@[\w.^~*-]+)?$/;
776
+ /** Config keys that gate the hook. Namespace, not a leaf — see hook-control. */
777
+ const PROTECTED_CONFIG_KEY = /^(?:agent\.)?(?:hooks|commandpolicy)\b|^agent\.risklevel$/;
778
+ /**
779
+ * True if this statement's argv reconfigures or removes a rafter security
780
+ * control.
781
+ *
782
+ * The rafter invocation is looked for at ANY position, not just as the
783
+ * statement's own exec, because a shell that carries a command string puts it
784
+ * in the operand: `bash -c "rafter agent config set agent.hooks.enabled false"`
785
+ * and `bash -c "$(echo rafter …)"` both sanitize to a statement whose exec is
786
+ * `bash`, and an exec-only walk reads them — wrongly — as not-rafter. A quoted
787
+ * word is skipped on the raw pass so that `echo 'rafter agent config set …'`
788
+ * stays prose; the sanitized pass is where an actually-executed operand has
789
+ * already been unwrapped for us.
790
+ */
791
+ function statementDisarmsRafter(words) {
792
+ for (let j = 0; j < words.length; j++) {
793
+ if (words[j].quoted)
794
+ continue;
795
+ let k = j;
796
+ let exec = execName(words[k].text);
797
+ k++;
798
+ // `npx [-y] @rafter-security/cli …`, `pnpm dlx rafter-cli …`, `bunx rafter …`
799
+ if (PACKAGE_RUNNERS.has(exec)) {
800
+ while (k < words.length && (words[k].text.startsWith("-") || ["dlx", "exec"].includes(words[k].text.toLowerCase())))
801
+ k++;
802
+ if (k >= words.length || !RAFTER_PACKAGE.test(words[k].text.toLowerCase()))
803
+ continue;
804
+ k++;
805
+ exec = "rafter";
806
+ }
807
+ if (!RAFTER_EXECS.has(exec))
808
+ continue;
809
+ const args = words.slice(k).map((w) => w.text.toLowerCase()).filter((a) => !a.startsWith("-"));
810
+ for (let n = 0; n + 1 < args.length; n++) {
811
+ // `… config set <protected key>` — the key is the next non-flag operand.
812
+ if (args[n] === "config" && args[n + 1] === "set") {
813
+ const key = args[n + 2];
814
+ if (key && PROTECTED_CONFIG_KEY.test(key))
815
+ return true;
816
+ }
817
+ // `… agent disable <component>` — uninstalls a control outright.
818
+ if (args[n] === "agent" && args[n + 1] === "disable")
819
+ return true;
820
+ }
821
+ }
822
+ return false;
823
+ }
824
+ /**
825
+ * True if the command disarms rafter, checked on BOTH the raw text and the
826
+ * sanitized text. Raw catches the ordinary invocation; sanitized catches the
827
+ * case where a shell runs the OUTPUT of something else — `bash -c "$(echo
828
+ * rafter agent config set …)"`, whose own exec is `echo` and which a walk over
829
+ * the raw argv therefore reads, correctly, as a print. That is the same
830
+ * executes-output distinction sable-c6an turned on.
831
+ */
832
+ export function modifiesRafterSecurityConfig(command) {
833
+ if (disarmsRafter(command, 0))
834
+ return true;
835
+ const sanitized = sanitizeCommandForMatching(command);
836
+ return sanitized !== command && disarmsRafter(sanitized, 0);
837
+ }
838
+ /** True if any statement (or any command substitution) disarms rafter. */
839
+ function disarmsRafter(command, depth = 0) {
840
+ if (depth > MAX_SANITIZE_DEPTH)
841
+ return false;
842
+ const { pieces } = tokenize(command);
843
+ let stmt = [];
844
+ const statements = [];
845
+ for (const p of pieces) {
846
+ if (p.op !== null) {
847
+ if (CHAIN_OPS.has(p.op) || p.op === "\n" || p.op === "\r") {
848
+ statements.push(stmt);
849
+ stmt = [];
850
+ }
851
+ continue;
852
+ }
853
+ stmt.push(p);
854
+ for (const sub of p.substs ?? []) {
855
+ if (disarmsRafter(sub, depth + 1))
856
+ return true;
857
+ }
858
+ }
859
+ statements.push(stmt);
860
+ return statements.some(statementDisarmsRafter);
861
+ }
755
862
  export function assessCommandRisk(command) {
863
+ // rf-vnxs: checked on the RAW command, before sanitization, because the
864
+ // disarm is an ordinary well-formed invocation — there is nothing malformed
865
+ // for the sanitizer to normalise, and redaction could hide the operand.
866
+ if (modifiesRafterSecurityConfig(command))
867
+ return "critical";
756
868
  const cmd = sanitizeCommandForMatching(command).toLowerCase().trim();
757
869
  if (!cmd)
758
870
  return "low";
@@ -777,6 +889,9 @@ export function assessCommandRisk(command) {
777
889
  * built-in rule matched.
778
890
  */
779
891
  export function matchedCriticalPattern(command) {
892
+ if (modifiesRafterSecurityConfig(command)) {
893
+ return "rafter security configuration is protected (rf-vnxs)";
894
+ }
780
895
  const cmd = sanitizeCommandForMatching(command).toLowerCase().trim();
781
896
  for (const pattern of CRITICAL_PATTERNS) {
782
897
  if (pattern.test(cmd))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rafter-security/cli",
3
- "version": "0.10.1",
3
+ "version": "0.10.3",
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.1
4
+ version: 0.10.3
5
5
  homepage: https://rafter.so
6
6
  metadata:
7
7
  openclaw: