@rafter-security/cli 0.9.0 → 0.10.0

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.
@@ -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
- export const CRITICAL_PATTERNS = [
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
- new RegExp(`rm\\s+(-[a-z]*r[a-z]*\\s+)*-[a-z]*f[a-z]*\\s+/(\\s|$)`),
10
- new RegExp(`rm\\s+(-[a-z]*f[a-z]*\\s+)*-[a-z]*r[a-z]*\\s+/(\\s|$)`),
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
- new RegExp(`rm\\s+(-[a-z]*r[a-z]*\\s+)*-[a-z]*f[a-z]*\\s+/(${CRITICAL_DIRS})(/|\\s|$)`),
13
- new RegExp(`rm\\s+(-[a-z]*f[a-z]*\\s+)*-[a-z]*r[a-z]*\\s+/(${CRITICAL_DIRS})(/|\\s|$)`),
14
- /:\(\)\{\s*:\|:&\s*\};:/, // fork bomb
15
- /dd\s+if=.*of=\/dev\/sd/,
16
- />\s*\/dev\/sd/,
17
- /mkfs/,
18
- /fdisk/,
19
- /parted/,
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
- export const DEFAULT_BLOCKED_PATTERNS = [
47
- "rm -rf /",
48
- ":(){ :|:& };:",
49
- "dd if=/dev/zero of=/dev/sda",
50
- "> /dev/sda",
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
- /** Read-only commands whose arguments should not trigger risk patterns. */
65
- const SAFE_PREFIX = /^(grep|egrep|fgrep|rg|ag|ack|echo|printf)\s/;
66
- /** Shell operators that chain independent commands. */
67
- const CHAIN_OPERATORS = /[;|&]|&&|\|\|/;
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
- // Safe prefix only applies to simple (non-chained) commands
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 only once a
93
- * command is already classified "critical" (safe-prefix exclusion is handled by
94
- * assessCommandRisk), to surface *which* built-in rule matched.
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;
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ import { createNotifyCommand } from "./commands/notify.js";
18
18
  import { createCompletionCommand } from "./commands/completion.js";
19
19
  import { createIssuesCommand } from "./commands/issues/index.js";
20
20
  import { createReportCommand } from "./commands/report.js";
21
+ import { createSitesCommand } from "./commands/sites/index.js";
21
22
  import { checkForUpdate } from "./utils/update-checker.js";
22
23
  import { setAgentMode } from "./utils/formatter.js";
23
24
  import { createRequire } from "module";
@@ -39,6 +40,8 @@ const program = new Command()
39
40
  program.addCommand(createRunCommand());
40
41
  program.addCommand(createGetCommand());
41
42
  program.addCommand(createUsageCommand());
43
+ // Sites — live-application security monitoring
44
+ program.addCommand(createSitesCommand());
42
45
  // Scan command group (default: remote scan; subcommands: local, remote)
43
46
  program.addCommand(createScanGroupCommand());
44
47
  // Secrets — top-level alias for local secret scanning (explicit-scope name)
@@ -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
@@ -1,11 +1,18 @@
1
1
  import { ConfigManager } from "../core/config-manager.js";
2
2
  export const API = "https://rafter.so/api/";
3
+ /** Join API with a path segment without producing a double slash, regardless of leading/trailing slashes on either side. */
4
+ export function apiUrl(path) {
5
+ return `${API.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
6
+ }
3
7
  // Exit codes
4
8
  export const EXIT_SUCCESS = 0;
5
9
  export const EXIT_GENERAL_ERROR = 1;
6
10
  export const EXIT_SCAN_NOT_FOUND = 2;
7
11
  export const EXIT_QUOTA_EXHAUSTED = 3;
8
12
  export const EXIT_INSUFFICIENT_SCOPE = 4;
13
+ // sable-9ddf — a paid Plus scan was refused because approval is required and no
14
+ // explicit confirmation (--yes / RAFTER_CONFIRM=1 / interactive yes) was given.
15
+ export const EXIT_CONFIRMATION_REQUIRED = 5;
9
16
  /**
10
17
  * Detect a 403 error from the API and print a helpful message.
11
18
  * 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.0",
3
+ "version": "0.10.0",
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.0
4
+ version: 0.10.0
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. If a task is security-relevant and no rafter skill or CLI call has been made, invoke this before handing the task off — an un-evaluated \"done\" on security-relevant work is not done."
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
- ## Picking the right tier — DO NOT stop at "local"
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
- Rafter ships three tiers. **They are not interchangeable.** The local tier is narrow; skipping remote analysis is the #1 way agents under-use rafter.
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
- 1. **Local (`rafter secrets`)** — secrets only. Regex + betterleaks for hardcoded API keys, tokens, private keys. Fast, offline, no key. **This is NOT a code security scan.** It will not find SQL injection, SSRF, auth bugs, insecure deserialization, logic flaws, or dependency vulns. If an agent's entire rafter interaction was `rafter secrets .` and it exited clean, the agent has done secret-hygiene only — not security review.
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
- **Default expectation for a security-relevant task**: run `rafter run`. Fall back to `rafter secrets` only when no API key is available or you specifically need offline secret-hygiene. If you've only run the local scanner, say so explicitly — don't claim the code was "scanned" without qualification.
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
- Stable exit codes, stable JSON shapes, deterministic findings. Safe to chain in CI and in agent loops.
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. A security-relevant task marked complete without both has been under-delivered — do not claim done."
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).