@rafter-security/cli 0.8.10 → 0.9.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.
@@ -262,9 +262,11 @@ function codexHooks() {
262
262
  const post = { type: "command", command: "rafter hook posttool" };
263
263
  cfg.hooks.PreToolUse = filterOutRafter(cfg.hooks.PreToolUse, (e) => hookEntryMatchesRafter(e, "rafter hook pretool"));
264
264
  cfg.hooks.PostToolUse = filterOutRafter(cfg.hooks.PostToolUse, (e) => hookEntryMatchesRafter(e, "rafter hook posttool"));
265
- // Bash + apply_patch per Codex hook docs (rf-ovql verification).
265
+ // Bash + apply_patch per Codex hook docs (rf-ovql verification). PostToolUse
266
+ // mirrors that write/exec surface (narrowed from `.*` to skip Read/MCP log
267
+ // noise), matching claude-code posttool scoping (sable-h0ah).
266
268
  cfg.hooks.PreToolUse.push({ matcher: "Bash|apply_patch", hooks: [pre] });
267
- cfg.hooks.PostToolUse.push({ matcher: ".*", hooks: [post] });
269
+ cfg.hooks.PostToolUse.push({ matcher: "Bash|apply_patch", hooks: [post] });
268
270
  writeJson(hooksPath, cfg);
269
271
  },
270
272
  uninstall: () => {
@@ -853,6 +855,59 @@ function hermesMcp() {
853
855
  },
854
856
  };
855
857
  }
858
+ /**
859
+ * OpenCode MCP server entry (~/.config/opencode/opencode.json).
860
+ *
861
+ * OpenCode's schema differs from Cursor/Windsurf: the block is `mcp` (not
862
+ * `mcpServers`), each local server carries `type: "local"`, and command + args
863
+ * are a single `command` array. Verified against
864
+ * https://opencode.ai/docs/mcp-servers/ (sable-l8e5).
865
+ */
866
+ function openCodeMcp() {
867
+ const home = os.homedir();
868
+ const configPath = path.join(home, ".config", "opencode", "opencode.json");
869
+ const entry = {
870
+ type: "local",
871
+ command: [RAFTER_MCP_ENTRY.command, ...RAFTER_MCP_ENTRY.args],
872
+ enabled: true,
873
+ };
874
+ return {
875
+ id: "opencode.mcp",
876
+ platform: "opencode",
877
+ kind: "mcp",
878
+ description: "OpenCode MCP server entry (~/.config/opencode/opencode.json)",
879
+ detectDir: path.join(home, ".config", "opencode"),
880
+ path: configPath,
881
+ isInstalled: () => {
882
+ if (!fs.existsSync(configPath))
883
+ return false;
884
+ const cfg = readJson(configPath);
885
+ return !!cfg.mcp?.rafter;
886
+ },
887
+ install: () => {
888
+ const dir = path.join(home, ".config", "opencode");
889
+ if (!fs.existsSync(dir))
890
+ fs.mkdirSync(dir, { recursive: true });
891
+ let cfg = fs.existsSync(configPath) ? readJson(configPath) : {};
892
+ // Guard against valid-but-non-object top-level JSON (array/string/number).
893
+ if (!cfg || typeof cfg !== "object" || Array.isArray(cfg))
894
+ cfg = {};
895
+ if (!cfg.$schema)
896
+ cfg.$schema = "https://opencode.ai/config.json";
897
+ if (!cfg.mcp || typeof cfg.mcp !== "object" || Array.isArray(cfg.mcp))
898
+ cfg.mcp = {};
899
+ cfg.mcp.rafter = { ...entry };
900
+ writeJson(configPath, cfg);
901
+ },
902
+ uninstall: () => {
903
+ if (!fs.existsSync(configPath))
904
+ return;
905
+ const cfg = readJson(configPath);
906
+ if (removeKey(cfg.mcp, "rafter"))
907
+ writeJson(configPath, cfg);
908
+ },
909
+ };
910
+ }
856
911
  /**
857
912
  * Aider read-only context: writes RAFTER.md and adds it to .aider.conf.yml `read:`.
858
913
  *
@@ -1001,6 +1056,7 @@ export function getComponentRegistry() {
1001
1056
  continueMcp(),
1002
1057
  aiderRead(),
1003
1058
  hermesMcp(),
1059
+ openCodeMcp(),
1004
1060
  openclawSkill(),
1005
1061
  ];
1006
1062
  }
@@ -82,7 +82,7 @@ function printDryRunPlan(plan) {
82
82
  if (plan.wantCodex) {
83
83
  console.log();
84
84
  console.log("Codex CLI (--with-codex):");
85
- W(path.join(plan.root, ".codex", "hooks.json"), "PreToolUse: Bash|apply_patch, PostToolUse: .*");
85
+ W(path.join(plan.root, ".codex", "hooks.json"), "PreToolUse: Bash|apply_patch, PostToolUse: Bash|apply_patch");
86
86
  for (const s of AGENT_SKILLS) {
87
87
  W(path.join(plan.root, ".agents", "skills", s.name, "SKILL.md"));
88
88
  }
@@ -144,6 +144,11 @@ function printDryRunPlan(plan) {
144
144
  console.log("Hermes (--with-hermes):");
145
145
  W(path.join(plan.root, ".hermes", "config.yaml"), "mcp_servers.rafter entry merged into existing YAML");
146
146
  }
147
+ if (plan.wantOpenCode) {
148
+ console.log();
149
+ console.log("OpenCode (--with-opencode):");
150
+ W(path.join(plan.root, ".config", "opencode", "opencode.json"), "mcp.rafter local/stdio entry merged into existing JSON");
151
+ }
147
152
  if (plan.wantOpenClaw) {
148
153
  console.log();
149
154
  console.log("OpenClaw (--with-openclaw):");
@@ -309,9 +314,10 @@ function installCodexHooks(root) {
309
314
  // when an MCP server is wired up, install a separate matcher for it.
310
315
  // (rf-ovql verification 2026-05-03.)
311
316
  config.hooks.PreToolUse.push({ matcher: "Bash|apply_patch", hooks: [preHook] });
312
- // PostToolUse fires for the same tool surface; .* keeps all events in the
313
- // audit log without filtering.
314
- config.hooks.PostToolUse.push({ matcher: ".*", hooks: [postHook] });
317
+ // PostToolUse mirrors the same write/exec surface (Bash + apply_patch);
318
+ // narrowed from `.*` so posttool doesn't fire on every Read/MCP call
319
+ // (log noise + latency), matching the claude-code posttool scoping (sable-h0ah).
320
+ config.hooks.PostToolUse.push({ matcher: "Bash|apply_patch", hooks: [postHook] });
315
321
  fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2), "utf-8");
316
322
  console.log(fmt.success(`Installed hooks to ${hooksPath}`));
317
323
  }
@@ -772,6 +778,60 @@ function installHermesMcp(root) {
772
778
  console.log(fmt.success(`Installed Rafter MCP server to ${configPath}`));
773
779
  return true;
774
780
  }
781
+ /**
782
+ * OpenCode MCP server entry. OpenCode's schema differs from Cursor/Windsurf:
783
+ * the block is `mcp` (not `mcpServers`), each local server has `type: "local"`,
784
+ * and the command + args are a single `command` array (not split). Verified
785
+ * against https://opencode.ai/docs/mcp-servers/ (rf-opencode).
786
+ */
787
+ const RAFTER_OPENCODE_MCP_ENTRY = {
788
+ type: "local",
789
+ command: [RAFTER_MCP_ENTRY.command, ...RAFTER_MCP_ENTRY.args],
790
+ enabled: true,
791
+ };
792
+ /**
793
+ * Install MCP server config for OpenCode (~/.config/opencode/opencode.json).
794
+ *
795
+ * OpenCode reads a global config at ~/.config/opencode/opencode.json and a
796
+ * project-level opencode.json (project takes precedence). We register the
797
+ * local stdio server `rafter mcp serve` under the `mcp` block. The `$schema`
798
+ * pointer is seeded on first write so editors get completion. Any existing
799
+ * keys / other MCP servers are preserved.
800
+ */
801
+ function installOpenCodeMcp(root) {
802
+ const openCodeDir = path.join(root, ".config", "opencode");
803
+ const configPath = path.join(openCodeDir, "opencode.json");
804
+ if (!fs.existsSync(openCodeDir)) {
805
+ fs.mkdirSync(openCodeDir, { recursive: true });
806
+ }
807
+ let config = {};
808
+ if (fs.existsSync(configPath)) {
809
+ try {
810
+ const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8"));
811
+ // Guard against valid-but-non-object top-level JSON (array/string/number).
812
+ // Mirrors the Python `isinstance(loaded, dict)` check so a wrong-shaped
813
+ // file is replaced rather than silently mangled by property assignment.
814
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
815
+ config = parsed;
816
+ }
817
+ else {
818
+ console.log(fmt.warning("Existing OpenCode opencode.json was not a JSON object, creating new one"));
819
+ }
820
+ }
821
+ catch {
822
+ console.log(fmt.warning("Existing OpenCode opencode.json was unreadable, creating new one"));
823
+ }
824
+ }
825
+ if (!config.$schema)
826
+ config.$schema = "https://opencode.ai/config.json";
827
+ if (!config.mcp || typeof config.mcp !== "object" || Array.isArray(config.mcp)) {
828
+ config.mcp = {};
829
+ }
830
+ config.mcp.rafter = { ...RAFTER_OPENCODE_MCP_ENTRY };
831
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
832
+ console.log(fmt.success(`Installed Rafter MCP server to ${configPath}`));
833
+ return true;
834
+ }
775
835
  function installAiderRead(root) {
776
836
  const rafterMdPath = path.join(root, "RAFTER.md");
777
837
  const configPath = path.join(root, ".aider.conf.yml");
@@ -942,6 +1002,7 @@ export function createInitCommand() {
942
1002
  .option("--with-windsurf", "Install Windsurf integration")
943
1003
  .option("--with-continue", "Install Continue.dev integration")
944
1004
  .option("--with-hermes", "Install Hermes integration")
1005
+ .option("--with-opencode", "Install OpenCode integration")
945
1006
  .option("--with-betterleaks", "Download and install Betterleaks binary")
946
1007
  .option("--with-skill-scanner", "Install the optional skill-scanner deep engine (heavy; audit-skill --deep)")
947
1008
  .option("--all", "Install all detected integrations and download Betterleaks")
@@ -974,6 +1035,7 @@ export function createInitCommand() {
974
1035
  const hasContinueDev = scope === "user" && fs.existsSync(path.join(os.homedir(), ".continue"));
975
1036
  const hasAider = scope === "user" && fs.existsSync(path.join(os.homedir(), ".aider.conf.yml"));
976
1037
  const hasHermes = scope === "user" && fs.existsSync(path.join(os.homedir(), ".hermes"));
1038
+ const hasOpenCode = scope === "user" && fs.existsSync(path.join(os.homedir(), ".config", "opencode"));
977
1039
  // Resolve opt-in flags (--all enables all detected, --interactive prompts).
978
1040
  // In --local scope, --all is restricted to platforms that have a project-local
979
1041
  // config story (claudeCode, codex, gemini, cursor). The rest require user scope.
@@ -1000,6 +1062,12 @@ export function createInitCommand() {
1000
1062
  // reads ~/.hermes/config.yaml; the project-local install story isn't
1001
1063
  // established. Excluded from --all in --local for the same reason.
1002
1064
  let wantHermes = opts.withHermes || (opts.all && !opts.local);
1065
+ // OpenCode: MCP-based, user scope only. OpenCode reads a global config at
1066
+ // ~/.config/opencode/opencode.json; a project-local install story via
1067
+ // --local isn't wired here, so (like Hermes) it's excluded from --all in
1068
+ // --local scope. It supports MCP local/stdio servers and AGENTS.md
1069
+ // natively (https://opencode.ai/docs/mcp-servers/, sable-l8e5).
1070
+ let wantOpenCode = opts.withOpencode || (opts.all && !opts.local);
1003
1071
  let wantBetterleaks = opts.withBetterleaks || (opts.all && !opts.local);
1004
1072
  // skill-scanner is heavy and opt-in only — deliberately NOT folded into --all.
1005
1073
  const wantSkillScanner = !!opts.withSkillScanner;
@@ -1026,6 +1094,8 @@ export function createInitCommand() {
1026
1094
  wantAider = await askYesNo("Install Aider MCP server?");
1027
1095
  if (hasHermes && !wantHermes)
1028
1096
  wantHermes = await askYesNo("Install Hermes MCP server?");
1097
+ if (hasOpenCode && !wantOpenCode)
1098
+ wantOpenCode = await askYesNo("Install OpenCode MCP server?");
1029
1099
  if (!wantBetterleaks)
1030
1100
  wantBetterleaks = await askYesNo("Download Betterleaks binary (enhanced scanning)?");
1031
1101
  console.log();
@@ -1050,6 +1120,8 @@ export function createInitCommand() {
1050
1120
  detected.push("Aider");
1051
1121
  if (hasHermes)
1052
1122
  detected.push("Hermes");
1123
+ if (hasOpenCode)
1124
+ detected.push("OpenCode");
1053
1125
  if (detected.length > 0) {
1054
1126
  console.log(fmt.info(`Detected environments: ${detected.join(", ")}`));
1055
1127
  }
@@ -1077,6 +1149,8 @@ export function createInitCommand() {
1077
1149
  console.log(fmt.warning("Aider requested but not detected (~/.aider.conf.yml not found)"));
1078
1150
  if (wantHermes && !hasHermes)
1079
1151
  console.log(fmt.warning("Hermes requested but not detected (~/.hermes not found)"));
1152
+ if (wantOpenCode && !hasOpenCode)
1153
+ console.log(fmt.warning("OpenCode requested but not detected (~/.config/opencode not found)"));
1080
1154
  }
1081
1155
  // --dry-run: print every file path the command would touch, then
1082
1156
  // exit before any filesystem write happens (rf-hrtd). The plan is
@@ -1095,6 +1169,7 @@ export function createInitCommand() {
1095
1169
  wantContinue: wantContinue && (hasContinueDev || opts.local),
1096
1170
  wantAider: wantAider && (hasAider || opts.local),
1097
1171
  wantHermes: wantHermes && hasHermes,
1172
+ wantOpenCode: wantOpenCode && hasOpenCode,
1098
1173
  wantBetterleaks,
1099
1174
  wantSkillScanner,
1100
1175
  riskLevel: opts.riskLevel,
@@ -1389,6 +1464,21 @@ export function createInitCommand() {
1389
1464
  console.error(fmt.error(`Failed to install Hermes integration: ${e}`));
1390
1465
  }
1391
1466
  }
1467
+ // Install OpenCode integration if opted in (sable-l8e5).
1468
+ // User scope only — OpenCode reads a global config at
1469
+ // ~/.config/opencode/opencode.json. MCP-based: we register the local
1470
+ // stdio server `rafter mcp serve` under the `mcp` block.
1471
+ let openCodeOk = false;
1472
+ if (wantOpenCode && hasOpenCode) {
1473
+ try {
1474
+ openCodeOk = installOpenCodeMcp(root);
1475
+ if (openCodeOk)
1476
+ manager.set("agent.environments.opencode.enabled", true);
1477
+ }
1478
+ catch (e) {
1479
+ console.error(fmt.error(`Failed to install OpenCode integration: ${e}`));
1480
+ }
1481
+ }
1392
1482
  // Install global instruction files for platforms that support them.
1393
1483
  // Cursor is intentionally absent — Cursor uses per-skill rules + the
1394
1484
  // rafter sub-agent installed in the Cursor branch above (rf-svn3).
@@ -1401,7 +1491,7 @@ export function createInitCommand() {
1401
1491
  console.log();
1402
1492
  console.log(fmt.success("Agent security initialized!"));
1403
1493
  console.log();
1404
- const anyIntegration = openclawOk || claudeCodeOk || codexOk || geminiOk || cursorOk || windsurfOk || continueOk || aiderOk;
1494
+ const anyIntegration = openclawOk || claudeCodeOk || codexOk || geminiOk || cursorOk || windsurfOk || continueOk || aiderOk || hermesOk || openCodeOk;
1405
1495
  if (anyIntegration) {
1406
1496
  console.log("Next steps:");
1407
1497
  if (openclawOk)
@@ -1420,6 +1510,10 @@ export function createInitCommand() {
1420
1510
  console.log(" - Restart Continue.dev to load MCP server");
1421
1511
  if (aiderOk)
1422
1512
  console.log(" - Restart Aider to load RAFTER.md from .aider.conf.yml read:");
1513
+ if (hermesOk)
1514
+ console.log(" - Restart Hermes to load MCP server");
1515
+ if (openCodeOk)
1516
+ console.log(" - Restart OpenCode to load MCP server");
1423
1517
  }
1424
1518
  else if (scope === "project") {
1425
1519
  console.log("No integrations were installed. In --local mode, pass one or more opt-in flags:");
@@ -1449,6 +1543,8 @@ export function createInitCommand() {
1449
1543
  console.log(" rafter agent init --with-aider # Aider only");
1450
1544
  if (hasHermes)
1451
1545
  console.log(" rafter agent init --with-hermes # Hermes only");
1546
+ if (hasOpenCode)
1547
+ console.log(" rafter agent init --with-opencode # OpenCode only");
1452
1548
  }
1453
1549
  else {
1454
1550
  console.log("No agent environments detected. Install an agent tool and re-run with --with-<tool>.");
@@ -4,18 +4,28 @@ export const RAFTER_MARKER_START = "<!-- rafter:start -->";
4
4
  export const RAFTER_MARKER_END = "<!-- rafter:end -->";
5
5
  /** Rafter security context block for agent instruction files (CLAUDE.md, AGENTS.md, etc.) */
6
6
  export const RAFTER_INSTRUCTION_BLOCK = `${RAFTER_MARKER_START}
7
- ## Security: Rafter (required review gate)
7
+ ## Security: Rafter (surface-driven review gate)
8
8
 
9
- Rafter is this project's security review gate. A security-relevant task is
10
- **not complete** until a rafter skill (or \`rafter run\`) has reviewed it.
11
- Don't mark done, don't hand off, don't open a PR without that pass.
9
+ Rafter is this project's security review gate — driven by the change's **security
10
+ surface**, not by the task label. When a diff touches a real surface (below), it is
11
+ **not complete** until a rafter skill (or \`rafter run\`) has reviewed it: don't mark
12
+ done, don't hand off, don't open a PR without that pass. When it touches **none** of
13
+ that surface — research / experimental / local-only / throwaway code (training
14
+ scripts, data analysis, plotting, model eval, notebooks, pure computation over
15
+ trusted local data) — a quick surface check is enough; proceed without the full
16
+ gate. Judge by the diff's actual surface, not the "research" label: research code
17
+ that reads a secret, shells out, hits the network, parses untrusted input, or bumps
18
+ a dependency still gets the full gate.
12
19
 
13
- **Stop and invoke before continuing:**
20
+ **Stop and invoke when the change touches that surface:**
14
21
 
15
22
  - Designing auth, payments, credentials, tokens, sessions, file upload,
16
- user data, or data deletion → **\`rafter-secure-design\`** (before writing code).
17
- - Diff touches user input, SQL, shell, auth, credentials, file paths, or
18
- serialization → **\`rafter-code-review\`** + \`rafter run\` (before declaring done).
23
+ user/untrusted data, deserialization, network endpoints, or data deletion
24
+ → **\`rafter-secure-design\`** (before writing code).
25
+ - Diff touches user/untrusted input, SQL/query building, shell/exec, auth,
26
+ credentials, file paths, (de)serialization, crypto, network endpoints/outbound
27
+ fetchers (SSRF), data deletion, or dependencies → **\`rafter-code-review\`** +
28
+ \`rafter run\` (before declaring done).
19
29
  - About to install or forward a third-party SKILL.md, MCP manifest, Cursor
20
30
  rule, or agent config → **\`rafter-skill-review\`** (before copying anywhere).
21
31
  - Security-adjacent but the angle isn't clear → **\`rafter\`** (the router skill,
@@ -26,7 +36,9 @@ Don't mark done, don't hand off, don't open a PR without that pass.
26
36
  - \`rafter run\` — remote SAST + SCA + secrets (real code analysis, needs \`RAFTER_API_KEY\`)
27
37
  - \`rafter secrets .\` — local secrets only (offline; NOT a code-security scan)
28
38
  - \`rafter run --mode plus\` — everything in default (\`--mode fast\`) plus
29
- powerful agentic deep-dives (needs \`RAFTER_API_KEY\`)
39
+ powerful agentic deep-dives (needs \`RAFTER_API_KEY\`). **Plus is a PAID tier
40
+ and consumes the user's credits — ask the user before running it.** Enforced
41
+ when \`scan.plus_requires_approval\` is set (then pass \`--yes\` to confirm).
30
42
  ${RAFTER_MARKER_END}`;
31
43
  /**
32
44
  * Write a Rafter instruction block into an instruction file.
@@ -148,6 +148,7 @@ export function createStatusCommand() {
148
148
  { name: "Windsurf", flag: "--with-windsurf", configDir: path.join(home, ".codeium", "windsurf"), configFile: path.join(home, ".codeium", "windsurf", "mcp_config.json"), needle: "rafter" },
149
149
  { name: "Continue.dev", flag: "--with-continue", configDir: path.join(home, ".continue"), configFile: path.join(home, ".continue", "config.json"), needle: "rafter" },
150
150
  { name: "Hermes", flag: "--with-hermes", configDir: path.join(home, ".hermes"), configFile: path.join(home, ".hermes", "config.yaml"), needle: "rafter" },
151
+ { name: "OpenCode", flag: "--with-opencode", configDir: path.join(home, ".config", "opencode"), configFile: path.join(home, ".config", "opencode", "opencode.json"), needle: "rafter" },
151
152
  ];
152
153
  for (const agent of mcpAgents) {
153
154
  const label = `${agent.name}:`.padEnd(14);
@@ -251,6 +252,7 @@ function detectAgents(home) {
251
252
  ["continue", path.join(home, ".continue")],
252
253
  ["aider", path.join(home, ".aider.conf.yml")],
253
254
  ["hermes", path.join(home, ".hermes")],
255
+ ["opencode", path.join(home, ".config", "opencode")],
254
256
  ];
255
257
  return candidates
256
258
  .filter(([, p]) => fs.existsSync(p))
@@ -287,6 +287,34 @@ function checkHermes() {
287
287
  return { name, passed: false, optional: true, detail: `Cannot read config: ${e}` };
288
288
  }
289
289
  }
290
+ function checkOpenCode() {
291
+ // OpenCode uses ~/.config/opencode/opencode.json with an `mcp` block
292
+ // (local/stdio servers carry type: "local"; sable-l8e5).
293
+ const name = "OpenCode";
294
+ const homeDir = os.homedir();
295
+ const openCodeDir = path.join(homeDir, ".config", "opencode");
296
+ if (!fs.existsSync(openCodeDir)) {
297
+ return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-opencode' to enable` };
298
+ }
299
+ const configPath = path.join(openCodeDir, "opencode.json");
300
+ if (!fs.existsSync(configPath)) {
301
+ return { name, passed: false, optional: true, detail: `Config not found: ${configPath} — run 'rafter agent init --with-opencode'` };
302
+ }
303
+ try {
304
+ const loaded = JSON.parse(fs.readFileSync(configPath, "utf-8"));
305
+ const servers = (loaded && typeof loaded === "object" && !Array.isArray(loaded))
306
+ ? loaded.mcp
307
+ : undefined;
308
+ const hasRafterMcp = servers && typeof servers === "object" && servers.rafter != null;
309
+ if (!hasRafterMcp) {
310
+ return { name, passed: false, optional: true, detail: "Rafter MCP server not configured — run 'rafter agent init --with-opencode'" };
311
+ }
312
+ return { name, passed: true, detail: "MCP server configured" };
313
+ }
314
+ catch (e) {
315
+ return { name, passed: false, optional: true, detail: `Cannot read config: ${e}` };
316
+ }
317
+ }
290
318
  /**
291
319
  * Probe the Claude Code hook integration end-to-end (rf-65zg).
292
320
  *
@@ -378,6 +406,7 @@ export function createVerifyCommand() {
378
406
  checkContinueDev(),
379
407
  checkAider(),
380
408
  checkHermes(),
409
+ checkOpenCode(),
381
410
  ];
382
411
  if (opts.probe) {
383
412
  // Only Claude Code has a probe today (rf-65zg). Codex/Cursor/Gemini
@@ -2,17 +2,79 @@ import { Command } from "commander";
2
2
  import axios from "axios";
3
3
  import ora from "ora";
4
4
  import { detectRepo } from "../../utils/git.js";
5
- import { API, resolveKey, EXIT_GENERAL_ERROR, EXIT_QUOTA_EXHAUSTED, handle403 } from "../../utils/api.js";
5
+ import { API, resolveKey, EXIT_GENERAL_ERROR, EXIT_QUOTA_EXHAUSTED, EXIT_CONFIRMATION_REQUIRED, handle403 } from "../../utils/api.js";
6
+ import { ConfigManager } from "../../core/config-manager.js";
7
+ import { loadPolicy } from "../../core/policy-loader.js";
8
+ import { askYesNo } from "../../utils/prompt.js";
6
9
  import { handleScanStatus } from "./scan-status.js";
10
+ /**
11
+ * sable-9ddf — is the Plus-scan approval gate enabled?
12
+ *
13
+ * OR semantics across the machine-owner's global config and the project's
14
+ * `.rafter.yml`: if EITHER opts in, approval is required. A project policy can
15
+ * turn the gate ON but can NEVER turn it OFF — a hostile repo must not be able
16
+ * to silently re-open the credit-burn hole a user closed globally.
17
+ *
18
+ * Fails open (returns false) if config/policy can't be read, consistent with
19
+ * the OFF-by-default product behavior and the codebase's config-load fallback.
20
+ */
21
+ export function plusApprovalGateEnabled() {
22
+ let globalFlag = false;
23
+ try {
24
+ globalFlag = new ConfigManager().load().agent?.scan?.plusRequiresApproval === true;
25
+ }
26
+ catch { /* fail open */ }
27
+ let policyFlag = false;
28
+ try {
29
+ policyFlag = loadPolicy()?.scan?.plusRequiresApproval === true;
30
+ }
31
+ catch { /* fail open */ }
32
+ return globalFlag || policyFlag;
33
+ }
34
+ /**
35
+ * Gate a paid Plus scan behind explicit confirmation when the switch is on.
36
+ * Returns normally if the scan may proceed; calls process.exit otherwise.
37
+ * No-op for non-plus modes and when the gate is disabled (the default).
38
+ */
39
+ export async function confirmPlusScan(opts) {
40
+ if ((opts.mode ?? "fast") !== "plus")
41
+ return;
42
+ if (!plusApprovalGateEnabled())
43
+ return;
44
+ const envConfirm = process.env.RAFTER_CONFIRM;
45
+ const confirmed = opts.yes === true || envConfirm === "1" || envConfirm === "true";
46
+ if (confirmed)
47
+ return;
48
+ if (process.stdin.isTTY) {
49
+ const ok = await askYesNo("Plus is a PAID scan tier and will consume your credits. Proceed?", false);
50
+ if (ok)
51
+ return;
52
+ console.error("Plus scan cancelled.");
53
+ process.exit(EXIT_CONFIRMATION_REQUIRED);
54
+ }
55
+ console.error("Refusing to run a paid Plus scan: approval is required " +
56
+ "(scan.plus_requires_approval is enabled).\n" +
57
+ "Re-run with --yes (or set RAFTER_CONFIRM=1) to confirm the credit spend, " +
58
+ "or use the free --mode fast scan.");
59
+ process.exit(EXIT_CONFIRMATION_REQUIRED);
60
+ }
7
61
  /**
8
62
  * Shared handler for the remote backend scan (used by both `rafter run` and `rafter scan` / `rafter scan remote`).
9
63
  */
10
64
  export async function runRemoteScan(opts) {
65
+ // sable-9ddf — gate paid Plus scans before doing any work (key resolution,
66
+ // repo detection, or the billable API call).
67
+ await confirmPlusScan(opts);
11
68
  const key = resolveKey(opts.apiKey);
12
69
  const ghToken = opts.githubToken || process.env.RAFTER_GITHUB_TOKEN;
13
70
  let repo, branch;
71
+ let detectedProvider, detectedRepoUrl;
14
72
  try {
15
- ({ repo, branch } = detectRepo({ repo: opts.repo, branch: opts.branch, quiet: opts.quiet }));
73
+ ({ repo, branch, provider: detectedProvider, repo_url: detectedRepoUrl } = detectRepo({
74
+ repo: opts.repo,
75
+ branch: opts.branch,
76
+ quiet: opts.quiet,
77
+ }));
16
78
  }
17
79
  catch (e) {
18
80
  if (e instanceof Error) {
@@ -23,6 +85,9 @@ export async function runRemoteScan(opts) {
23
85
  }
24
86
  process.exit(EXIT_GENERAL_ERROR);
25
87
  }
88
+ // Explicit flags override inferred values.
89
+ const provider = opts.provider ?? detectedProvider;
90
+ const repoUrl = opts.repoUrl ?? detectedRepoUrl;
26
91
  const body = {
27
92
  repository_name: repo,
28
93
  branch_name: branch,
@@ -30,6 +95,13 @@ export async function runRemoteScan(opts) {
30
95
  };
31
96
  if (ghToken)
32
97
  body.github_token = ghToken;
98
+ // Additive, backward-compatible: only send provider + repo_url for non-github
99
+ // remotes. For github (or an unknown host that defaulted to github), omit both
100
+ // so the request body is byte-identical to the legacy github-only behavior.
101
+ if (provider && provider !== "github" && repoUrl) {
102
+ body.provider = provider;
103
+ body.repo_url = repoUrl;
104
+ }
33
105
  if (!opts.quiet) {
34
106
  const spinner = ora("Submitting scan").start();
35
107
  try {
@@ -99,7 +171,10 @@ function addRunOptions(cmd) {
99
171
  .option("-f, --format <format>", "json | md", "md")
100
172
  .option("-m, --mode <mode>", "scan mode: fast | plus", "fast")
101
173
  .option("--github-token <token>", "GitHub PAT for private repos (or RAFTER_GITHUB_TOKEN env var)")
174
+ .option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
175
+ .option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
102
176
  .option("--skip-interactive", "do not wait for scan to complete")
177
+ .option("-y, --yes", "confirm a paid Plus scan without prompting (when scan.plus_requires_approval is on)")
103
178
  .option("--quiet", "suppress status messages");
104
179
  }
105
180
  export function createRunCommand() {
@@ -23,7 +23,10 @@ export function createScanGroupCommand() {
23
23
  .option("-f, --format <format>", "json | md", "md")
24
24
  .option("-m, --mode <mode>", "scan mode: fast | plus", "fast")
25
25
  .option("--github-token <token>", "GitHub PAT for private repos (or RAFTER_GITHUB_TOKEN env var)")
26
+ .option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
27
+ .option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
26
28
  .option("--skip-interactive", "do not wait for scan to complete")
29
+ .option("-y, --yes", "confirm a paid Plus scan without prompting (when scan.plus_requires_approval is on)")
27
30
  .option("--quiet", "suppress status messages")
28
31
  .action(async (opts) => {
29
32
  await runRemoteScan(opts);
@@ -38,7 +41,10 @@ export function createScanGroupCommand() {
38
41
  .option("-f, --format <format>", "json | md", "md")
39
42
  .option("-m, --mode <mode>", "scan mode: fast | plus", "fast")
40
43
  .option("--github-token <token>", "GitHub PAT for private repos (or RAFTER_GITHUB_TOKEN env var)")
44
+ .option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
45
+ .option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
41
46
  .option("--skip-interactive", "do not wait for scan to complete")
47
+ .option("-y, --yes", "confirm a paid Plus scan without prompting (when scan.plus_requires_approval is on)")
42
48
  .option("--quiet", "suppress status messages");
43
49
  scanGroup.addCommand(localCmd, { hidden: true });
44
50
  scanGroup.addCommand(remoteCmd);
@@ -1,6 +1,6 @@
1
1
  import { ConfigManager } from "./config-manager.js";
2
2
  import { AuditLogger } from "./audit-logger.js";
3
- import { assessCommandRisk, matchedCriticalPattern } from "./risk-rules.js";
3
+ import { assessCommandRisk, matchedCriticalPattern, sanitizeCommandForMatching, } from "./risk-rules.js";
4
4
  export class CommandInterceptor {
5
5
  constructor() {
6
6
  this.config = new ConfigManager();
@@ -47,12 +47,19 @@ export class CommandInterceptor {
47
47
  requiresApproval: false
48
48
  };
49
49
  }
50
- // Check blocked patterns (always block)
50
+ // Check blocked patterns (always block).
51
+ //
52
+ // A deny-list match denies — that is what a deny-list is for — but it must
53
+ // NOT rewrite the command's risk. Reporting every deny-list hit as
54
+ // "critical" made the hook tell users a `gh pr create` was an irreversible
55
+ // system-damage command. The assessed risk is reported as assessed; the
56
+ // genuinely unconditional hard-blocks are the CRITICAL_PATTERNS handled
57
+ // above, and the default deny-list is exactly that set.
51
58
  for (const pattern of policy.blockedPatterns) {
52
59
  if (this.matchesPattern(command, pattern)) {
53
60
  return {
54
61
  command,
55
- riskLevel: "critical",
62
+ riskLevel,
56
63
  allowed: false,
57
64
  requiresApproval: false,
58
65
  reason: `Matches blocked pattern: ${pattern}`,
@@ -63,7 +70,6 @@ export class CommandInterceptor {
63
70
  // Check approval patterns
64
71
  for (const pattern of policy.requireApproval) {
65
72
  if (this.matchesPattern(command, pattern)) {
66
- const riskLevel = this.assessRisk(command);
67
73
  return {
68
74
  command,
69
75
  riskLevel,
@@ -74,47 +80,21 @@ export class CommandInterceptor {
74
80
  };
75
81
  }
76
82
  }
77
- // Check policy mode
78
- if (policy.mode === "deny-list") {
79
- // If not in blocked or approval lists, allow
80
- return {
81
- command,
82
- riskLevel: this.assessRisk(command),
83
- allowed: true,
84
- requiresApproval: false
85
- };
86
- }
87
- else if (policy.mode === "approve-dangerous") {
88
- // Assess risk and require approval for high/critical
89
- const riskLevel = this.assessRisk(command);
90
- if (riskLevel === "high" || riskLevel === "critical") {
91
- return {
92
- command,
93
- riskLevel,
94
- allowed: false,
95
- requiresApproval: true,
96
- reason: `High risk command requires approval`
97
- };
98
- }
83
+ // Check policy mode. `riskLevel` is the assessment made at the top of
84
+ // evaluate() — critical already returned, so it is high/medium/low here.
85
+ if (policy.mode === "approve-dangerous" && riskLevel === "high") {
99
86
  return {
100
87
  command,
101
88
  riskLevel,
102
- allowed: true,
103
- requiresApproval: false
104
- };
105
- }
106
- else if (policy.mode === "allow-all") {
107
- return {
108
- command,
109
- riskLevel: this.assessRisk(command),
110
- allowed: true,
111
- requiresApproval: false
89
+ allowed: false,
90
+ requiresApproval: true,
91
+ reason: `High risk command requires approval`
112
92
  };
113
93
  }
114
- // Default: allow
94
+ // deny-list / allow-all / unknown mode: not blocked, not approval-gated.
115
95
  return {
116
96
  command,
117
- riskLevel: this.assessRisk(command),
97
+ riskLevel,
118
98
  allowed: true,
119
99
  requiresApproval: false
120
100
  };
@@ -126,16 +106,23 @@ export class CommandInterceptor {
126
106
  this.audit.logCommandIntercepted(evaluation.command, evaluation.allowed, actionTaken, evaluation.reason);
127
107
  }
128
108
  /**
129
- * Match command against pattern
109
+ * Match a command against a policy pattern.
110
+ *
111
+ * Matching runs against the SANITIZED command line, not the raw string: the
112
+ * policy patterns describe commands, so quoted text a command merely consumes
113
+ * as data (a commit message, a PR body) must not match them, while text a
114
+ * shell or eval wrapper executes (`bash -c "…"`) must. See
115
+ * `sanitizeCommandForMatching`.
130
116
  */
131
117
  matchesPattern(command, pattern) {
118
+ const target = sanitizeCommandForMatching(command);
132
119
  try {
133
120
  const regex = new RegExp(pattern, "i");
134
- return regex.test(command);
121
+ return regex.test(target);
135
122
  }
136
123
  catch {
137
124
  // If pattern is not valid regex, try case-insensitive substring match
138
- return command.toLowerCase().includes(pattern.toLowerCase());
125
+ return target.toLowerCase().includes(pattern.toLowerCase());
139
126
  }
140
127
  }
141
128
  /**