@rafter-security/cli 0.9.0 → 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.
- package/dist/commands/agent/components.js +4 -2
- package/dist/commands/agent/init.js +5 -4
- package/dist/commands/agent/instruction-block.js +21 -9
- package/dist/commands/backend/run.js +59 -1
- package/dist/commands/scan/index.js +2 -0
- package/dist/core/command-interceptor.js +28 -41
- package/dist/core/config-manager.js +9 -0
- package/dist/core/pattern-engine.js +33 -2
- package/dist/core/policy-loader.js +9 -0
- package/dist/core/risk-rules.js +408 -28
- package/dist/scanners/secret-patterns.js +14 -0
- package/dist/utils/api.js +3 -0
- package/package.json +6 -2
- package/resources/rafter-security-skill.md +1 -1
- package/resources/skills/rafter/SKILL.md +18 -8
- package/resources/skills/rafter-code-review/SKILL.md +7 -1
- package/resources/skills/rafter-secure-design/SKILL.md +7 -1
|
@@ -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: "
|
|
269
|
+
cfg.hooks.PostToolUse.push({ matcher: "Bash|apply_patch", hooks: [post] });
|
|
268
270
|
writeJson(hooksPath, cfg);
|
|
269
271
|
},
|
|
270
272
|
uninstall: () => {
|
|
@@ -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
|
}
|
|
@@ -314,9 +314,10 @@ function installCodexHooks(root) {
|
|
|
314
314
|
// when an MCP server is wired up, install a separate matcher for it.
|
|
315
315
|
// (rf-ovql verification 2026-05-03.)
|
|
316
316
|
config.hooks.PreToolUse.push({ matcher: "Bash|apply_patch", hooks: [preHook] });
|
|
317
|
-
// PostToolUse
|
|
318
|
-
//
|
|
319
|
-
|
|
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] });
|
|
320
321
|
fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2), "utf-8");
|
|
321
322
|
console.log(fmt.success(`Installed hooks to ${hooksPath}`));
|
|
322
323
|
}
|
|
@@ -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 (
|
|
7
|
+
## Security: Rafter (surface-driven review gate)
|
|
8
8
|
|
|
9
|
-
Rafter is this project's security review gate
|
|
10
|
-
|
|
11
|
-
|
|
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
|
|
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
|
|
17
|
-
-
|
|
18
|
-
|
|
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.
|
|
@@ -2,12 +2,69 @@ 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;
|
|
@@ -117,6 +174,7 @@ function addRunOptions(cmd) {
|
|
|
117
174
|
.option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
|
|
118
175
|
.option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
|
|
119
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)")
|
|
120
178
|
.option("--quiet", "suppress status messages");
|
|
121
179
|
}
|
|
122
180
|
export function createRunCommand() {
|
|
@@ -26,6 +26,7 @@ export function createScanGroupCommand() {
|
|
|
26
26
|
.option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
|
|
27
27
|
.option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
|
|
28
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)")
|
|
29
30
|
.option("--quiet", "suppress status messages")
|
|
30
31
|
.action(async (opts) => {
|
|
31
32
|
await runRemoteScan(opts);
|
|
@@ -43,6 +44,7 @@ export function createScanGroupCommand() {
|
|
|
43
44
|
.option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
|
|
44
45
|
.option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
|
|
45
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)")
|
|
46
48
|
.option("--quiet", "suppress status messages");
|
|
47
49
|
scanGroup.addCommand(localCmd, { hidden: true });
|
|
48
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
|
|
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
|
-
|
|
79
|
-
|
|
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:
|
|
103
|
-
requiresApproval:
|
|
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
|
-
//
|
|
94
|
+
// deny-list / allow-all / unknown mode: not blocked, not approval-gated.
|
|
115
95
|
return {
|
|
116
96
|
command,
|
|
117
|
-
riskLevel
|
|
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(
|
|
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
|
|
125
|
+
return target.toLowerCase().includes(pattern.toLowerCase());
|
|
139
126
|
}
|
|
140
127
|
}
|
|
141
128
|
/**
|
|
@@ -129,6 +129,10 @@ function validateConfig(raw) {
|
|
|
129
129
|
console.error('Warning: config "agent.scan.autoUpdateBetterleaks" must be a boolean — using default.');
|
|
130
130
|
delete scan.autoUpdateBetterleaks;
|
|
131
131
|
}
|
|
132
|
+
if (scan.plusRequiresApproval !== undefined && typeof scan.plusRequiresApproval !== "boolean") {
|
|
133
|
+
console.error('Warning: config "agent.scan.plusRequiresApproval" must be a boolean — using default.');
|
|
134
|
+
delete scan.plusRequiresApproval;
|
|
135
|
+
}
|
|
132
136
|
}
|
|
133
137
|
}
|
|
134
138
|
return raw;
|
|
@@ -299,6 +303,11 @@ export class ConfigManager {
|
|
|
299
303
|
if (policy.scan.autoUpdateBetterleaks !== undefined) {
|
|
300
304
|
config.agent.scan.autoUpdateBetterleaks = policy.scan.autoUpdateBetterleaks;
|
|
301
305
|
}
|
|
306
|
+
// sable-9ddf — OR merge: a project policy may turn the Plus-approval gate
|
|
307
|
+
// ON, but must never turn OFF a gate the machine owner set globally.
|
|
308
|
+
if (policy.scan.plusRequiresApproval === true) {
|
|
309
|
+
config.agent.scan.plusRequiresApproval = true;
|
|
310
|
+
}
|
|
302
311
|
}
|
|
303
312
|
// Ignore rules — top-level policy key, applied per finding at scan time
|
|
304
313
|
if (policy.ignore && config.agent) {
|
|
@@ -2,6 +2,22 @@ const GENERIC_PATTERN_NAMES = new Set(["Generic API Key", "Generic Secret"]);
|
|
|
2
2
|
const VARIABLE_NAME_RE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
|
|
3
3
|
const LOWERCASE_IDENT_RE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/;
|
|
4
4
|
const QUOTED_VALUE_RE = /['"]([^'"]+)['"]/;
|
|
5
|
+
/**
|
|
6
|
+
* Matches an environment-assignment prefix in a command line: an identifier
|
|
7
|
+
* followed immediately by `=` and a run of non-whitespace (the value). Used to
|
|
8
|
+
* find `NAME=VALUE` tokens like `RAFTER_API_KEY=<secret> rafter ...` so their
|
|
9
|
+
* value can be redacted before the command is written to the audit log.
|
|
10
|
+
*/
|
|
11
|
+
const ENV_ASSIGN_RE = /(^|\s)([A-Za-z_][A-Za-z0-9_]*)=(\S+)/g;
|
|
12
|
+
/**
|
|
13
|
+
* A `NAME` in a `NAME=VALUE` assignment is treated as secret-bearing when it
|
|
14
|
+
* ends in a credential-suggesting word (e.g. RAFTER_API_KEY, GITHUB_TOKEN,
|
|
15
|
+
* DB_PASSWORD, AUTH). Values behind such names are redacted even when they
|
|
16
|
+
* don't match any known secret pattern (that's the whole point — the value of
|
|
17
|
+
* a bespoke API key won't match a built-in pattern, but it's still a secret).
|
|
18
|
+
* Plain names like FOO or NODE_ENV do not match, so `FOO=bar` is left intact.
|
|
19
|
+
*/
|
|
20
|
+
const SECRET_ENV_NAME_RE = /(?:^|_)(KEY|TOKEN|SECRET|SECRETS|PASSWORD|PASSWD|PWD|API[_-]?KEY|ACCESS[_-]?KEY|CREDENTIALS?|AUTH)$/i;
|
|
5
21
|
export class PatternEngine {
|
|
6
22
|
constructor(patterns) {
|
|
7
23
|
this.patterns = patterns;
|
|
@@ -53,16 +69,31 @@ export class PatternEngine {
|
|
|
53
69
|
return matches;
|
|
54
70
|
}
|
|
55
71
|
/**
|
|
56
|
-
* Redact text by replacing sensitive patterns
|
|
72
|
+
* Redact text by replacing sensitive patterns.
|
|
73
|
+
*
|
|
74
|
+
* Two layers, both additive:
|
|
75
|
+
* 1. Env-assignment redaction: any `NAME=VALUE` whose NAME looks
|
|
76
|
+
* secret-bearing has its VALUE masked, even if the VALUE matches no
|
|
77
|
+
* known pattern. This catches leaks like `RAFTER_API_KEY=<key> rafter …`
|
|
78
|
+
* in a logged command line, where the key's shape is unknown.
|
|
79
|
+
* 2. Pattern-based redaction: values that match a built-in secret pattern
|
|
80
|
+
* are masked wherever they appear.
|
|
57
81
|
*/
|
|
58
82
|
redactText(text) {
|
|
59
|
-
let redacted = text;
|
|
83
|
+
let redacted = this.redactEnvAssignments(text);
|
|
60
84
|
for (const pattern of this.patterns) {
|
|
61
85
|
const regex = this.createRegex(pattern.regex);
|
|
62
86
|
redacted = redacted.replace(regex, (match) => this.isFalsePositive(pattern, match) ? match : this.redact(match));
|
|
63
87
|
}
|
|
64
88
|
return redacted;
|
|
65
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Mask the VALUE of every `NAME=VALUE` token whose NAME looks
|
|
92
|
+
* secret-bearing. Non-secret names (FOO, NODE_ENV, …) are left untouched.
|
|
93
|
+
*/
|
|
94
|
+
redactEnvAssignments(text) {
|
|
95
|
+
return text.replace(ENV_ASSIGN_RE, (full, prefix, name, value) => SECRET_ENV_NAME_RE.test(name) ? `${prefix}${name}=${this.redact(value)}` : full);
|
|
96
|
+
}
|
|
66
97
|
/**
|
|
67
98
|
* Check if text contains any sensitive patterns
|
|
68
99
|
*/
|
|
@@ -99,6 +99,9 @@ function mapPolicy(raw) {
|
|
|
99
99
|
if (typeof raw.scan.auto_update_betterleaks === "boolean") {
|
|
100
100
|
policy.scan.autoUpdateBetterleaks = raw.scan.auto_update_betterleaks;
|
|
101
101
|
}
|
|
102
|
+
if (typeof raw.scan.plus_requires_approval === "boolean") {
|
|
103
|
+
policy.scan.plusRequiresApproval = raw.scan.plus_requires_approval;
|
|
104
|
+
}
|
|
102
105
|
}
|
|
103
106
|
// sable-c1c — backend flat-shape compat. rafter-backend reads
|
|
104
107
|
// exclude_paths / custom_patterns at the top level (no `scan:` nesting),
|
|
@@ -307,6 +310,12 @@ function validatePolicy(policy, raw) {
|
|
|
307
310
|
typeof raw.scan.auto_update_betterleaks !== "boolean") {
|
|
308
311
|
console.error(`Warning: "scan.auto_update_betterleaks" must be a boolean — ignoring.`);
|
|
309
312
|
}
|
|
313
|
+
// sable-9ddf — only a boolean reaches policy.scan (mapping guards the type).
|
|
314
|
+
if (raw.scan && typeof raw.scan === "object" &&
|
|
315
|
+
raw.scan.plus_requires_approval !== undefined &&
|
|
316
|
+
typeof raw.scan.plus_requires_approval !== "boolean") {
|
|
317
|
+
console.error(`Warning: "scan.plus_requires_approval" must be a boolean — ignoring.`);
|
|
318
|
+
}
|
|
310
319
|
}
|
|
311
320
|
if (policy.ignore !== undefined) {
|
|
312
321
|
if (!Array.isArray(policy.ignore)) {
|
package/dist/core/risk-rules.js
CHANGED
|
@@ -1,23 +1,36 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Centralized risk assessment rules.
|
|
3
3
|
* Single source of truth — imported by command-interceptor, audit-logger, and config-defaults.
|
|
4
|
+
*
|
|
5
|
+
* Risk patterns are matched against a *sanitized* view of the command line
|
|
6
|
+
* (see `sanitizeCommandForMatching`), not the raw string: quoted text that a
|
|
7
|
+
* command consumes as DATA (a commit message, a PR body, an `echo` argument)
|
|
8
|
+
* must not be mistaken for a command, while quoted text that a shell or eval
|
|
9
|
+
* wrapper EXECUTES (`bash -c "…"`, `eval "…"`) must still be scanned.
|
|
4
10
|
*/
|
|
5
11
|
/** Directories where `rm -rf /<dir>` is catastrophic (data loss / unbootable). */
|
|
6
12
|
const CRITICAL_DIRS = "home|etc|usr|boot|root|sys|proc|lib|lib64|bin|sbin|opt";
|
|
7
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Catastrophic, irreversible commands. These are hard-blocked unconditionally —
|
|
15
|
+
* no policy, mode, or deny-list can opt out of them. Kept as pattern *sources*
|
|
16
|
+
* so the default policy deny-list (`DEFAULT_BLOCKED_PATTERNS`) is exactly this
|
|
17
|
+
* set, byte for byte, and can never drift from it.
|
|
18
|
+
*/
|
|
19
|
+
const CRITICAL_PATTERN_SOURCES = [
|
|
8
20
|
// rm -rf / (root only, any flag order)
|
|
9
|
-
|
|
10
|
-
|
|
21
|
+
`rm\\s+(-[a-z]*r[a-z]*\\s+)*-[a-z]*f[a-z]*\\s+/(\\s|$)`,
|
|
22
|
+
`rm\\s+(-[a-z]*f[a-z]*\\s+)*-[a-z]*r[a-z]*\\s+/(\\s|$)`,
|
|
11
23
|
// rm -rf on critical top-level directories
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
24
|
+
`rm\\s+(-[a-z]*r[a-z]*\\s+)*-[a-z]*f[a-z]*\\s+/(${CRITICAL_DIRS})(/|\\s|$)`,
|
|
25
|
+
`rm\\s+(-[a-z]*f[a-z]*\\s+)*-[a-z]*r[a-z]*\\s+/(${CRITICAL_DIRS})(/|\\s|$)`,
|
|
26
|
+
`:\\(\\)\\{\\s*:\\|:&\\s*\\};:`, // fork bomb
|
|
27
|
+
`dd\\s+if=.*of=/dev/sd`,
|
|
28
|
+
`>\\s*/dev/sd`,
|
|
29
|
+
`mkfs`,
|
|
30
|
+
`fdisk`,
|
|
31
|
+
`parted`,
|
|
20
32
|
];
|
|
33
|
+
export const CRITICAL_PATTERNS = CRITICAL_PATTERN_SOURCES.map((s) => new RegExp(s));
|
|
21
34
|
export const HIGH_PATTERNS = [
|
|
22
35
|
/rm\s+(-[a-z]*r[a-z]*\s+)*-[a-z]*f[a-z]*/, // rm -rf, -fr, -r -f, -f -r (any path)
|
|
23
36
|
/rm\s+(-[a-z]*f[a-z]*\s+)*-[a-z]*r[a-z]*/, // rm -fr, reversed
|
|
@@ -43,12 +56,14 @@ export const MEDIUM_PATTERNS = [
|
|
|
43
56
|
/pkill/,
|
|
44
57
|
/killall/,
|
|
45
58
|
];
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
59
|
+
/**
|
|
60
|
+
* Default policy deny-list. Identical to the built-in unconditional hard-block
|
|
61
|
+
* set: a deny-list entry hard-denies, so the *defaults* must never match a
|
|
62
|
+
* merely approval-grade command. (The old literals — e.g. the substring
|
|
63
|
+
* "rm -rf /" — hard-denied `rm -rf /tmp/build`, which is HIGH and belongs in
|
|
64
|
+
* DEFAULT_REQUIRE_APPROVAL, not in a deny-list.)
|
|
65
|
+
*/
|
|
66
|
+
export const DEFAULT_BLOCKED_PATTERNS = [...CRITICAL_PATTERN_SOURCES];
|
|
52
67
|
export const DEFAULT_REQUIRE_APPROVAL = [
|
|
53
68
|
"rm -rf",
|
|
54
69
|
"sudo rm",
|
|
@@ -61,17 +76,382 @@ export const DEFAULT_REQUIRE_APPROVAL = [
|
|
|
61
76
|
"git push --force-if-includes",
|
|
62
77
|
"git push .* \\+",
|
|
63
78
|
];
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
// Argument-aware command sanitizer
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
//
|
|
83
|
+
// The risk patterns above describe *shell commands*. Matching them against the
|
|
84
|
+
// raw command line treats quoted argument text as if it were a command, so
|
|
85
|
+
//
|
|
86
|
+
// gh pr create --body "…don't git push --force…"
|
|
87
|
+
// git commit -m "don't git push --force"
|
|
88
|
+
//
|
|
89
|
+
// were flagged as force-pushes. Simply ignoring quoted text is NOT a fix: a
|
|
90
|
+
// shell or eval wrapper *executes* its quoted argument, so `bash -c "rm -rf /"`
|
|
91
|
+
// must still hard-block. The sanitizer is therefore argument-aware:
|
|
92
|
+
//
|
|
93
|
+
// * tokenize respecting quotes, escapes, command substitution and redirects;
|
|
94
|
+
// * split on chain operators (`;` `&&` `||` `|` `&`), keeping them in place so
|
|
95
|
+
// pipeline rules (`curl … | bash`) still match;
|
|
96
|
+
// * a shell's `-c` argument IS a command → recursively sanitize and inline it;
|
|
97
|
+
// * `$(…)` / backticks (outside single quotes) ARE commands → same;
|
|
98
|
+
// * arguments a command consumes as text (`echo`/`grep` operands, `-m`,
|
|
99
|
+
// `--body`, …) and prose-shaped quoted arguments are DATA → redacted;
|
|
100
|
+
// * everything else is preserved byte for byte.
|
|
101
|
+
//
|
|
102
|
+
// Known limitation: an *unrecognized* evaluator that takes a bare quoted command
|
|
103
|
+
// string with no `-c`/`-e`-style flag (e.g. a bespoke `myrunner "rm -rf /"`) has
|
|
104
|
+
// its argument treated as data. Anything reached through a real shell, an eval
|
|
105
|
+
// flag, a substitution, or an unquoted argument is still scanned.
|
|
106
|
+
/** Shells whose `-c` argument is a command string to execute. */
|
|
107
|
+
const SHELL_EXECS = new Set(["bash", "sh", "zsh", "dash", "ksh", "ash", "fish", "su"]);
|
|
108
|
+
/** Execs whose arguments are executable text (a remote command, a script). */
|
|
109
|
+
const EVAL_EXECS = new Set(["eval", "exec", "ssh", "sshpass", "xargs"]);
|
|
110
|
+
/** Flags carrying an executable string (`bash -c`, `python -c`, `mysql -e`, `find -exec`). */
|
|
111
|
+
const EVAL_FLAGS = new Set(["-c", "-e", "--command", "--execute", "--eval", "-exec", "--exec"]);
|
|
112
|
+
/** Prefix wrappers that delegate to the command that follows them. */
|
|
113
|
+
const TAIL_WRAPPERS = new Set([
|
|
114
|
+
"sudo", "doas", "env", "nohup", "timeout", "nice", "ionice",
|
|
115
|
+
"time", "watch", "setsid", "stdbuf", "chrt", "command",
|
|
116
|
+
]);
|
|
117
|
+
/** Commands whose operands are pure text data — searching or printing, never executing. */
|
|
118
|
+
const TEXT_EXECS = new Set(["echo", "printf", "grep", "egrep", "fgrep", "rg", "ag", "ack"]);
|
|
119
|
+
/** Flags whose value is human prose (a message, a body, a title) — never a command. */
|
|
120
|
+
const TEXT_FLAGS = new Set([
|
|
121
|
+
"-m", "--message", "--body", "--body-text", "--title", "--description",
|
|
122
|
+
"--reason", "--notes", "--subject", "--comment", "--annotation",
|
|
123
|
+
]);
|
|
124
|
+
/** Operators that chain independent commands. */
|
|
125
|
+
const CHAIN_OPS = new Set([";", "&&", "||", "|", "&"]);
|
|
126
|
+
/** Operators whose following token is a redirect target (a path — never data). */
|
|
127
|
+
const REDIRECT_OPS = new Set([">", ">>", "<", "<<"]);
|
|
128
|
+
/** Bound on recursion through nested shell wrappers / substitutions. */
|
|
129
|
+
const MAX_SANITIZE_DEPTH = 8;
|
|
130
|
+
function isOpChar(c) {
|
|
131
|
+
return c === ";" || c === "&" || c === "|" || c === ">" || c === "<";
|
|
132
|
+
}
|
|
133
|
+
/** Read a `$(…)` substitution starting at `i`; returns its contents and the next index. */
|
|
134
|
+
function readSubst(s, i) {
|
|
135
|
+
let j = i + 2;
|
|
136
|
+
let depth = 1;
|
|
137
|
+
let inner = "";
|
|
138
|
+
while (j < s.length && depth > 0) {
|
|
139
|
+
const ch = s[j];
|
|
140
|
+
if (ch === "(")
|
|
141
|
+
depth++;
|
|
142
|
+
else if (ch === ")") {
|
|
143
|
+
depth--;
|
|
144
|
+
if (depth === 0) {
|
|
145
|
+
j++;
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
inner += ch;
|
|
150
|
+
j++;
|
|
151
|
+
}
|
|
152
|
+
return { inner, next: j };
|
|
153
|
+
}
|
|
154
|
+
/** Read a backtick substitution starting at `i`. */
|
|
155
|
+
function readBacktick(s, i) {
|
|
156
|
+
let j = i + 1;
|
|
157
|
+
let inner = "";
|
|
158
|
+
while (j < s.length && s[j] !== "`") {
|
|
159
|
+
inner += s[j];
|
|
160
|
+
j++;
|
|
161
|
+
}
|
|
162
|
+
return { inner, next: Math.min(j + 1, s.length) };
|
|
163
|
+
}
|
|
164
|
+
/** Split a command line into words and operators, respecting quotes and substitutions. */
|
|
165
|
+
function tokenize(s) {
|
|
166
|
+
const pieces = [];
|
|
167
|
+
let i = 0;
|
|
168
|
+
while (i < s.length) {
|
|
169
|
+
const c = s[i];
|
|
170
|
+
if (/\s/.test(c)) {
|
|
171
|
+
i++;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (isOpChar(c)) {
|
|
175
|
+
const start = i;
|
|
176
|
+
const two = s.slice(i, i + 2);
|
|
177
|
+
const op = (two === "&&" || two === "||" || two === ">>" || two === "<<") ? two : c;
|
|
178
|
+
i += op.length;
|
|
179
|
+
pieces.push({ start, end: i, op, text: op, quoted: false, substs: [] });
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
const start = i;
|
|
183
|
+
let text = "";
|
|
184
|
+
let quoted = false;
|
|
185
|
+
const substs = [];
|
|
186
|
+
while (i < s.length) {
|
|
187
|
+
const ch = s[i];
|
|
188
|
+
if (/\s/.test(ch) || isOpChar(ch))
|
|
189
|
+
break;
|
|
190
|
+
if (ch === "\\") {
|
|
191
|
+
i++;
|
|
192
|
+
if (i < s.length) {
|
|
193
|
+
text += s[i];
|
|
194
|
+
i++;
|
|
195
|
+
}
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
// Single quotes are inert: no expansion, no substitution.
|
|
199
|
+
if (ch === "'") {
|
|
200
|
+
i++;
|
|
201
|
+
quoted = true;
|
|
202
|
+
while (i < s.length && s[i] !== "'") {
|
|
203
|
+
text += s[i];
|
|
204
|
+
i++;
|
|
205
|
+
}
|
|
206
|
+
i++;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
// Double quotes are data, but `$( )` / backticks inside them DO execute.
|
|
210
|
+
if (ch === '"') {
|
|
211
|
+
i++;
|
|
212
|
+
quoted = true;
|
|
213
|
+
while (i < s.length && s[i] !== '"') {
|
|
214
|
+
if (s[i] === "\\") {
|
|
215
|
+
i++;
|
|
216
|
+
if (i < s.length) {
|
|
217
|
+
text += s[i];
|
|
218
|
+
i++;
|
|
219
|
+
}
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (s[i] === "$" && s[i + 1] === "(") {
|
|
223
|
+
const r = readSubst(s, i);
|
|
224
|
+
substs.push(r.inner);
|
|
225
|
+
i = r.next;
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (s[i] === "`") {
|
|
229
|
+
const r = readBacktick(s, i);
|
|
230
|
+
substs.push(r.inner);
|
|
231
|
+
i = r.next;
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
text += s[i];
|
|
235
|
+
i++;
|
|
236
|
+
}
|
|
237
|
+
i++;
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (ch === "$" && s[i + 1] === "(") {
|
|
241
|
+
const r = readSubst(s, i);
|
|
242
|
+
substs.push(r.inner);
|
|
243
|
+
i = r.next;
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (ch === "`") {
|
|
247
|
+
const r = readBacktick(s, i);
|
|
248
|
+
substs.push(r.inner);
|
|
249
|
+
i = r.next;
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
text += ch;
|
|
253
|
+
i++;
|
|
254
|
+
}
|
|
255
|
+
pieces.push({ start, end: i, op: null, text, quoted, substs });
|
|
256
|
+
}
|
|
257
|
+
return pieces;
|
|
258
|
+
}
|
|
259
|
+
/** `/usr/bin/rm` → `rm`; used to classify the executable of a segment. */
|
|
260
|
+
function execName(text) {
|
|
261
|
+
const base = text.slice(text.lastIndexOf("/") + 1);
|
|
262
|
+
return base.toLowerCase();
|
|
263
|
+
}
|
|
264
|
+
const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
265
|
+
const SHELL_C_FLAG = /^-[a-z]*c$/;
|
|
266
|
+
const LONG_FLAG_WITH_VALUE = /^(--[a-z][a-z-]*)=/;
|
|
267
|
+
/**
|
|
268
|
+
* Decide, for one segment (a single command in a chain), which spans are DATA
|
|
269
|
+
* and which are code, appending the resulting replacements.
|
|
270
|
+
*/
|
|
271
|
+
function processSegment(pieces, depth, out) {
|
|
272
|
+
// A word is a redirect target when the piece before it is `>`/`>>`/`<`.
|
|
273
|
+
const isRedirectTarget = new Array(pieces.length).fill(false);
|
|
274
|
+
for (let i = 1; i < pieces.length; i++) {
|
|
275
|
+
const prev = pieces[i - 1];
|
|
276
|
+
if (prev.op && REDIRECT_OPS.has(prev.op) && !pieces[i].op)
|
|
277
|
+
isRedirectTarget[i] = true;
|
|
278
|
+
}
|
|
279
|
+
// Effective executable: skip env assignments and prefix wrappers (`sudo`,
|
|
280
|
+
// `env`, `timeout 5`, `nice -n 15`, …) to reach the command they delegate to.
|
|
281
|
+
let execIdx = -1;
|
|
282
|
+
for (let i = 0; i < pieces.length; i++) {
|
|
283
|
+
const p = pieces[i];
|
|
284
|
+
if (p.op || isRedirectTarget[i])
|
|
285
|
+
continue;
|
|
286
|
+
if (!p.quoted && ENV_ASSIGNMENT.test(p.text))
|
|
287
|
+
continue;
|
|
288
|
+
if (execIdx === -1 && !p.quoted && TAIL_WRAPPERS.has(execName(p.text))) {
|
|
289
|
+
// Skip the wrapper's own flags and their numeric/duration values.
|
|
290
|
+
let j = i + 1;
|
|
291
|
+
while (j < pieces.length) {
|
|
292
|
+
const q = pieces[j];
|
|
293
|
+
if (q.op || isRedirectTarget[j]) {
|
|
294
|
+
j++;
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (q.text.startsWith("-") || /^\d+[a-z]*$/i.test(q.text)) {
|
|
298
|
+
j++;
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
i = j - 1;
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
execIdx = i;
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
const exec = execIdx === -1 ? "" : execName(pieces[execIdx].text);
|
|
310
|
+
const isTextExec = TEXT_EXECS.has(exec);
|
|
311
|
+
// A segment is code-carrying when some part of it is a command string the
|
|
312
|
+
// segment will execute: a shell, an eval-style flag, or an eval-style exec.
|
|
313
|
+
// Its quoted arguments are NOT prose and must stay visible to the patterns.
|
|
314
|
+
let hasShellExec = false;
|
|
315
|
+
let hasEvalFlag = false;
|
|
316
|
+
for (let i = 0; i < pieces.length; i++) {
|
|
317
|
+
const p = pieces[i];
|
|
318
|
+
if (p.op || isRedirectTarget[i])
|
|
319
|
+
continue;
|
|
320
|
+
if (!p.quoted && SHELL_EXECS.has(execName(p.text)))
|
|
321
|
+
hasShellExec = true;
|
|
322
|
+
if (!p.quoted && EVAL_FLAGS.has(p.text.toLowerCase()))
|
|
323
|
+
hasEvalFlag = true;
|
|
324
|
+
}
|
|
325
|
+
const codeCarrying = hasShellExec || hasEvalFlag || EVAL_EXECS.has(exec);
|
|
326
|
+
let seenShell = false;
|
|
327
|
+
let pendingScript = false;
|
|
328
|
+
let prevTextFlag = false;
|
|
329
|
+
for (let i = 0; i < pieces.length; i++) {
|
|
330
|
+
const p = pieces[i];
|
|
331
|
+
if (p.op) {
|
|
332
|
+
prevTextFlag = false;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
const isExecTok = i === execIdx;
|
|
336
|
+
const flagName = p.text.toLowerCase();
|
|
337
|
+
if (!p.quoted && SHELL_EXECS.has(execName(p.text)))
|
|
338
|
+
seenShell = true;
|
|
339
|
+
// `bash -c <script>` — the next word is a command string, not data.
|
|
340
|
+
if (pendingScript && !p.text.startsWith("-")) {
|
|
341
|
+
out.push({ start: p.start, end: p.end, with: sanitize(p.text, depth + 1) });
|
|
342
|
+
pendingScript = false;
|
|
343
|
+
prevTextFlag = false;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (seenShell && !p.quoted && SHELL_C_FLAG.test(flagName)) {
|
|
347
|
+
pendingScript = true;
|
|
348
|
+
prevTextFlag = false;
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
// `$(…)` / backticks execute — scan their contents, drop the literal wrapper.
|
|
352
|
+
if (p.substs.length > 0) {
|
|
353
|
+
const inner = p.substs.map((s) => sanitize(s, depth + 1)).join(" ");
|
|
354
|
+
out.push({ start: p.start, end: p.end, with: inner });
|
|
355
|
+
prevTextFlag = false;
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (isRedirectTarget[i]) {
|
|
359
|
+
prevTextFlag = false;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
if (isExecTok) {
|
|
363
|
+
// Unquote a quoted executable so quoting the *command name* cannot break
|
|
364
|
+
// the pattern anchors (`"rm" -rf /`, `r"m" -rf /`, `watch "rm -rf /"`).
|
|
365
|
+
// Unquoting only ever exposes more to the patterns — the safe direction.
|
|
366
|
+
if (p.quoted)
|
|
367
|
+
out.push({ start: p.start, end: p.end, with: p.text });
|
|
368
|
+
prevTextFlag = false;
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
// Value of a prose flag (`-m "…"`, `--body "…"`) — always data, even inside
|
|
372
|
+
// a code-carrying segment (`git commit -e -m "don't git push --force"`).
|
|
373
|
+
if (prevTextFlag) {
|
|
374
|
+
out.push({ start: p.start, end: p.end, with: " " });
|
|
375
|
+
prevTextFlag = false;
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const longFlag = LONG_FLAG_WITH_VALUE.exec(p.text);
|
|
379
|
+
if (!p.quoted && longFlag && TEXT_FLAGS.has(longFlag[1])) {
|
|
380
|
+
out.push({ start: p.start, end: p.end, with: longFlag[1] });
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
if (TEXT_FLAGS.has(flagName)) {
|
|
384
|
+
prevTextFlag = true;
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
prevTextFlag = false;
|
|
388
|
+
// Operands of a text command (`echo`, `grep`, `printf`) are never executed.
|
|
389
|
+
if (isTextExec && i > execIdx) {
|
|
390
|
+
out.push({ start: p.start, end: p.end, with: " " });
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
if (p.quoted) {
|
|
394
|
+
const isProse = /\s/.test(p.text);
|
|
395
|
+
if (!isProse) {
|
|
396
|
+
// Single-word quoted operand: unquote it so quoting cannot be used to
|
|
397
|
+
// hide a flag or a path from the patterns (`rm "-rf" "/"`).
|
|
398
|
+
out.push({ start: p.start, end: p.end, with: p.text });
|
|
399
|
+
}
|
|
400
|
+
else if (codeCarrying) {
|
|
401
|
+
// This segment executes a command string (`ssh host "…"`, `mysql -e "…"`).
|
|
402
|
+
// The quoted argument is code — unquote and scan it, recursively.
|
|
403
|
+
out.push({ start: p.start, end: p.end, with: sanitize(p.text, depth + 1) });
|
|
404
|
+
}
|
|
405
|
+
else {
|
|
406
|
+
// A quoted, multi-word argument to an ordinary command is prose data.
|
|
407
|
+
out.push({ start: p.start, end: p.end, with: " " });
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
function sanitize(command, depth) {
|
|
413
|
+
if (!command || depth > MAX_SANITIZE_DEPTH)
|
|
414
|
+
return command;
|
|
415
|
+
const pieces = tokenize(command);
|
|
416
|
+
const replacements = [];
|
|
417
|
+
let segment = [];
|
|
418
|
+
for (const p of pieces) {
|
|
419
|
+
if (p.op && CHAIN_OPS.has(p.op)) {
|
|
420
|
+
processSegment(segment, depth, replacements);
|
|
421
|
+
segment = [];
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
segment.push(p);
|
|
425
|
+
}
|
|
426
|
+
processSegment(segment, depth, replacements);
|
|
427
|
+
if (replacements.length === 0)
|
|
428
|
+
return command;
|
|
429
|
+
replacements.sort((a, b) => a.start - b.start);
|
|
430
|
+
let out = "";
|
|
431
|
+
let cursor = 0;
|
|
432
|
+
for (const r of replacements) {
|
|
433
|
+
if (r.start < cursor)
|
|
434
|
+
continue;
|
|
435
|
+
out += command.slice(cursor, r.start) + r.with;
|
|
436
|
+
cursor = r.end;
|
|
437
|
+
}
|
|
438
|
+
out += command.slice(cursor);
|
|
439
|
+
return out;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Normalize a command line for risk/policy pattern matching: quoted text the
|
|
443
|
+
* command consumes as DATA is redacted; text a shell or eval wrapper EXECUTES
|
|
444
|
+
* is preserved (and recursively sanitized). Everything else is untouched.
|
|
445
|
+
*/
|
|
446
|
+
export function sanitizeCommandForMatching(command) {
|
|
447
|
+
return sanitize(command, 0);
|
|
448
|
+
}
|
|
68
449
|
/**
|
|
69
450
|
* Assess risk level of a command string.
|
|
70
451
|
*/
|
|
71
452
|
export function assessCommandRisk(command) {
|
|
72
|
-
const cmd = command.toLowerCase().trim();
|
|
73
|
-
|
|
74
|
-
if (SAFE_PREFIX.test(cmd) && !CHAIN_OPERATORS.test(cmd))
|
|
453
|
+
const cmd = sanitizeCommandForMatching(command).toLowerCase().trim();
|
|
454
|
+
if (!cmd)
|
|
75
455
|
return "low";
|
|
76
456
|
for (const pattern of CRITICAL_PATTERNS) {
|
|
77
457
|
if (pattern.test(cmd))
|
|
@@ -89,12 +469,12 @@ export function assessCommandRisk(command) {
|
|
|
89
469
|
}
|
|
90
470
|
/**
|
|
91
471
|
* Return the source of the first CRITICAL pattern matching the command, or null.
|
|
92
|
-
* Mirrors assessCommandRisk's lowercasing. Intended to be called
|
|
93
|
-
* command is already classified "critical"
|
|
94
|
-
*
|
|
472
|
+
* Mirrors assessCommandRisk's sanitization + lowercasing. Intended to be called
|
|
473
|
+
* only once a command is already classified "critical", to surface *which*
|
|
474
|
+
* built-in rule matched.
|
|
95
475
|
*/
|
|
96
476
|
export function matchedCriticalPattern(command) {
|
|
97
|
-
const cmd = command.toLowerCase().trim();
|
|
477
|
+
const cmd = sanitizeCommandForMatching(command).toLowerCase().trim();
|
|
98
478
|
for (const pattern of CRITICAL_PATTERNS) {
|
|
99
479
|
if (pattern.test(cmd))
|
|
100
480
|
return pattern.source;
|
|
@@ -153,6 +153,20 @@ export const DEFAULT_SECRET_PATTERNS = [
|
|
|
153
153
|
regex: "dop_v1_[a-f0-9]{64}",
|
|
154
154
|
severity: "critical",
|
|
155
155
|
description: "DigitalOcean Personal Access Token detected"
|
|
156
|
+
},
|
|
157
|
+
// Mailchimp
|
|
158
|
+
{
|
|
159
|
+
name: "Mailchimp API Key",
|
|
160
|
+
regex: "[a-f0-9]{32}-us\\d{1,2}",
|
|
161
|
+
severity: "critical",
|
|
162
|
+
description: "Mailchimp API Key detected"
|
|
163
|
+
},
|
|
164
|
+
// SendGrid
|
|
165
|
+
{
|
|
166
|
+
name: "SendGrid API Key",
|
|
167
|
+
regex: "SG\\.[a-zA-Z0-9_-]{22}\\.[a-zA-Z0-9_-]{43}",
|
|
168
|
+
severity: "critical",
|
|
169
|
+
description: "SendGrid API Key detected"
|
|
156
170
|
}
|
|
157
171
|
];
|
|
158
172
|
/**
|
package/dist/utils/api.js
CHANGED
|
@@ -6,6 +6,9 @@ export const EXIT_GENERAL_ERROR = 1;
|
|
|
6
6
|
export const EXIT_SCAN_NOT_FOUND = 2;
|
|
7
7
|
export const EXIT_QUOTA_EXHAUSTED = 3;
|
|
8
8
|
export const EXIT_INSUFFICIENT_SCOPE = 4;
|
|
9
|
+
// sable-9ddf — a paid Plus scan was refused because approval is required and no
|
|
10
|
+
// explicit confirmation (--yes / RAFTER_CONFIRM=1 / interactive yes) was given.
|
|
11
|
+
export const EXIT_CONFIRMATION_REQUIRED = 5;
|
|
9
12
|
/**
|
|
10
13
|
* Detect a 403 error from the API and print a helpful message.
|
|
11
14
|
* Returns the appropriate exit code, or -1 if not a 403.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rafter-security/cli",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -24,7 +24,10 @@
|
|
|
24
24
|
"build": "tsc -p tsconfig.json",
|
|
25
25
|
"prepublishOnly": "pnpm run build",
|
|
26
26
|
"postinstall": "echo '\n Run: rafter agent init --all\n Sets up secret scanning for Claude Code, Codex CLI, and git hooks.\n'",
|
|
27
|
-
"test": "vitest"
|
|
27
|
+
"test": "vitest run",
|
|
28
|
+
"test:watch": "vitest",
|
|
29
|
+
"test:coverage": "vitest run --coverage",
|
|
30
|
+
"clean": "rm -rf dist/ node_modules/.cache/"
|
|
28
31
|
},
|
|
29
32
|
"engines": {
|
|
30
33
|
"node": ">=18"
|
|
@@ -44,6 +47,7 @@
|
|
|
44
47
|
"devDependencies": {
|
|
45
48
|
"@types/js-yaml": "^4.0.9",
|
|
46
49
|
"@types/node": "^20.11.30",
|
|
50
|
+
"@vitest/coverage-v8": "4.1.0",
|
|
47
51
|
"tsx": "^4.7.0",
|
|
48
52
|
"typescript": "^5.4.5",
|
|
49
53
|
"vitest": "^4.1.0"
|
|
@@ -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.9.
|
|
4
|
+
version: 0.9.1
|
|
5
5
|
homepage: https://rafter.so
|
|
6
6
|
metadata:
|
|
7
7
|
openclaw:
|
|
@@ -1,23 +1,33 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: rafter
|
|
3
|
-
description: "Entry point for rafter. Invoke when a sub-skill is unclear, or when the task needs `rafter run` (remote SAST+SCA), `rafter secrets` (local secrets-only), `rafter audit`, policy checks, or command-risk evaluation.
|
|
3
|
+
description: "Entry point for rafter. Invoke when a sub-skill is unclear, or when the task needs `rafter run` (remote SAST+SCA), `rafter secrets` (local secrets-only), `rafter audit`, policy checks, or command-risk evaluation. Scope by security surface, not task label: engage when the diff touches auth, credentials/secrets/tokens, untrusted input, SQL, shell/exec, file paths, deserialization, crypto, network endpoints, data deletion, or dependencies; for research/experimental/local-only code with none of that, a quick surface check is enough. When such surface IS present and no rafter skill or CLI call has been made, invoke this before handing the task off — an un-evaluated \"done\" on genuine security surface is not done."
|
|
4
4
|
version: 0.7.0
|
|
5
5
|
allowed-tools: [Bash, Read]
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
# Rafter — Security Toolkit for AI Workflows
|
|
9
9
|
|
|
10
|
-
##
|
|
10
|
+
## When Rafter applies (and when it doesn't)
|
|
11
|
+
|
|
12
|
+
Rafter is a **surface-driven** gate, not a task-label gate. Read the diff's actual security surface first; let that — not whether the work is called "research" — pick the branch.
|
|
13
|
+
|
|
14
|
+
**Engage fully** (walk the review + run `rafter run`) when the change touches any of: auth / sessions / access control · credentials, secrets, tokens, keys · user-supplied or otherwise untrusted input · SQL or any other query / command construction · shell, `exec`, or subprocess invocation · file paths (read, write, upload, traversal) · deserialization or parsing of untrusted data · crypto primitives · network-facing endpoints or outbound fetchers (SSRF surface) · data deletion or other destructive mutations · dependency, lockfile, or manifest changes.
|
|
15
|
+
|
|
16
|
+
**Back off** when the change touches **none** of those — research / experimental / exploratory / local-only / throwaway code: training scripts, data analysis, plotting, model eval, notebooks, pure computation over trusted local data. A quick surface check is enough; with no security surface, proceed **without** the full `rafter-code-review` + `rafter run`.
|
|
11
17
|
|
|
12
|
-
|
|
18
|
+
**The rule that decides it:** the "research" label buys nothing. Research code that reads a secret, shells out, hits the network, parses untrusted input, or bumps a dependency is on the engage list and gets the full gate. Judge by the surface of the diff, not by what the task is called.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Picking the right tier — DO NOT stop at "local"
|
|
13
23
|
|
|
14
|
-
|
|
15
|
-
2. **Remote fast (`rafter run`, default mode)** — SAST + SCA + secrets via the Rafter API. This is the real code-analysis pass: dataflow, taint, known-vulnerable dependencies, crypto misuse, injection sinks. Needs `RAFTER_API_KEY`.
|
|
16
|
-
3. **Remote plus (`rafter run --mode plus`)** — agentic deep-dive: LLM-guided investigation of suspicious patterns the rules engine flags. Slower, higher signal. Code is deleted server-side after the run.
|
|
24
|
+
Three tiers, **not interchangeable**. The local tier is narrow; skipping remote analysis is the #1 way agents under-use rafter.
|
|
17
25
|
|
|
18
|
-
|
|
26
|
+
1. **`rafter secrets`** — hardcoded credentials only (regex + betterleaks). Fast, offline, no key. **NOT a code security scan** — it finds no SQL injection, SSRF, auth bugs, insecure deserialization, logic flaws, or dependency vulns. A clean `rafter secrets .` is secret-hygiene, not security review.
|
|
27
|
+
2. **`rafter run`** (default mode) — the real code-analysis pass: SAST + SCA + secrets (dataflow, taint, known-vulnerable deps, crypto misuse, injection sinks). Needs `RAFTER_API_KEY`.
|
|
28
|
+
3. **`rafter run --mode plus`** — agentic deep-dive: LLM-guided investigation of what the rules engine flags. Slower, higher signal; code is deleted server-side after the run. **PAID tier — consumes the user's credits; ask before running it.** If `scan.plus_requires_approval` is set, Plus refuses without `--yes` / `RAFTER_CONFIRM=1`.
|
|
19
29
|
|
|
20
|
-
|
|
30
|
+
**Default for a security-relevant task: `rafter run`.** Fall back to `rafter secrets` only when no API key is available — and say so explicitly; don't claim the code was "scanned" without qualification. Deterministic findings, stable exit codes and JSON shapes — safe to chain in CI and in agent loops.
|
|
21
31
|
|
|
22
32
|
---
|
|
23
33
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: rafter-code-review
|
|
3
|
-
description: "REQUIRED before declaring a task done when the diff touches user input, SQL, shell, auth, credentials, file paths, serialization, or dependency surface. Walks OWASP/ASVS/MITRE questions the compiler and the test suite won't catch. Pair with `rafter run` on the same diff.
|
|
3
|
+
description: "REQUIRED before declaring a task done when the diff touches user input, SQL, shell, auth, credentials, file paths, serialization, crypto, network endpoints, data deletion, or dependency surface. Judge by that surface, not the task label — research/experimental/local-only code with none of it can skip this. Walks OWASP/ASVS/MITRE questions the compiler and the test suite won't catch. Pair with `rafter run` on the same diff. When the diff has that surface, marking it complete without both has been under-delivered — do not claim done."
|
|
4
4
|
version: 0.7.0
|
|
5
5
|
allowed-tools: [Bash, Read, Glob, Grep]
|
|
6
6
|
---
|
|
@@ -11,6 +11,12 @@ A reviewer's skill, not an audit generator. Each sub-doc is a set of **questions
|
|
|
11
11
|
|
|
12
12
|
> Pair with the `rafter` skill (detection: `rafter scan`, `rafter run`) and `rafter-secure-design` (prevention: design-phase walks). This skill is the middle stage — review before merge.
|
|
13
13
|
|
|
14
|
+
## When this applies (and when it doesn't)
|
|
15
|
+
|
|
16
|
+
Scoped to the **security surface of the diff**, not the task's label. Walk it fully when the change touches: user / untrusted input, SQL or query building, shell / `exec` / subprocess, auth or access control, credentials / secrets / tokens, file paths or uploads, (de)serialization, crypto, network-facing endpoints or outbound fetchers, data deletion, or dependency / manifest changes.
|
|
17
|
+
|
|
18
|
+
If **none** of those are present — research / experimental / exploratory / local-only / throwaway code such as training scripts, data analysis, plotting, model eval, notebooks, or pure computation over trusted local data — a quick surface check is enough; you don't need to walk the full review or pair `rafter run`. But the check is the surface, not the label: research code that reads a secret, shells out, hits the network, or parses untrusted bytes is back on the engage list and gets the full walk.
|
|
19
|
+
|
|
14
20
|
## How to use this skill
|
|
15
21
|
|
|
16
22
|
1. Identify the category of code in front of you (below).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: rafter-secure-design
|
|
3
|
-
description: "REQUIRED before writing code for any feature touching auth, payments, credentials, tokens, sessions, file upload, user data, or data deletion. Invoke it, record answers inline in the design doc or PR description, then write the code. Skipping this is how auth bypass, token leakage, and delete-the-wrong-record bugs ship. If the feature touches any of those surfaces and this hasn't run, the design is incomplete — do not proceed to implementation."
|
|
3
|
+
description: "REQUIRED before writing code for any feature touching auth, payments, credentials, tokens, sessions, file upload, user data, untrusted input, deserialization, network endpoints, or data deletion. Scope by that surface, not the task label — a research/experimental/local-only feature with none of it doesn't need this. Invoke it, record answers inline in the design doc or PR description, then write the code. Skipping this is how auth bypass, token leakage, and delete-the-wrong-record bugs ship. If the feature touches any of those surfaces and this hasn't run, the design is incomplete — do not proceed to implementation."
|
|
4
4
|
version: 0.1.0
|
|
5
5
|
allowed-tools: [Read, Glob, Grep]
|
|
6
6
|
---
|
|
@@ -11,6 +11,12 @@ A designer's skill, not a scanner. The goal is to catch the flaw in the whiteboa
|
|
|
11
11
|
|
|
12
12
|
> Pair with `rafter-code-review` (structured review *during* PR) and the `rafter` skill (automated detection of what slipped through). This skill is the earliest stage — prevention before the code exists.
|
|
13
13
|
|
|
14
|
+
## When this applies (and when it doesn't)
|
|
15
|
+
|
|
16
|
+
Engage this design walk when the feature you're about to build touches a real security surface: auth or access control, credentials / secrets / tokens / sessions, user or untrusted input, SQL or query construction, shell / `exec`, file paths or uploads, (de)serialization, crypto, network-facing endpoints or outbound fetchers, data deletion, or new dependencies.
|
|
17
|
+
|
|
18
|
+
If the thing you're designing has **none** of that — a research / experimental / local-only / throwaway piece such as a training script, analysis pipeline, plot, model-eval harness, notebook, or pure computation over trusted local data — a quick surface check is enough and you can proceed to implementation without the full walk. Judge by the surface, not by whether the work is called "research": a research feature that stores user data, handles a token, or opens a network endpoint is back on the engage list.
|
|
19
|
+
|
|
14
20
|
## How to use this skill
|
|
15
21
|
|
|
16
22
|
1. Identify what's being designed (below). If multiple apply, walk them in the order listed — `threat-modeling` last, as a capstone.
|