@rafter-security/cli 0.9.1 → 0.10.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.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * rafter sites — live-application security monitoring ("Sites").
3
+ *
4
+ * Subcommands:
5
+ * rafter sites create <url> Register a site, kick off its first scan
6
+ * rafter sites scan <projectId-or-url> Trigger a re-scan of an existing site
7
+ * rafter sites list List registered sites
8
+ * rafter sites get <id> Get a site's status + latest run + findings summary
9
+ */
10
+ import { Command } from "commander";
11
+ import { createSitesCreateCommand } from "./create.js";
12
+ import { createSitesScanCommand } from "./scan.js";
13
+ import { createSitesListCommand } from "./list.js";
14
+ import { createSitesGetCommand } from "./get.js";
15
+ export function createSitesCommand() {
16
+ const sitesGroup = new Command("sites")
17
+ .description("Manage Rafter Sites — live-application security monitoring");
18
+ sitesGroup.addCommand(createSitesCreateCommand());
19
+ sitesGroup.addCommand(createSitesScanCommand());
20
+ sitesGroup.addCommand(createSitesListCommand());
21
+ sitesGroup.addCommand(createSitesGetCommand());
22
+ // Default action for `rafter sites` with no subcommand — show help.
23
+ sitesGroup.action(() => {
24
+ sitesGroup.help();
25
+ });
26
+ return sitesGroup;
27
+ }
@@ -0,0 +1,38 @@
1
+ import { Command } from "commander";
2
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR, apiClient } from "../../utils/api.js";
3
+ import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
4
+ /** List registered sites, paginated. Returns the process exit code. */
5
+ export async function runSitesList(opts) {
6
+ if (rejectUnsupportedFormat(opts.format))
7
+ return EXIT_GENERAL_ERROR;
8
+ const key = resolveKey(opts.apiKey);
9
+ const params = {};
10
+ if (opts.limit !== undefined)
11
+ params.limit = String(opts.limit);
12
+ if (opts.offset !== undefined)
13
+ params.offset = String(opts.offset);
14
+ if (opts.includeArchived)
15
+ params.include_archived = "true";
16
+ try {
17
+ const { data } = await apiClient.get(apiUrl("static/sites"), { params, headers: { "x-api-key": key } });
18
+ return writePayload(data, opts.format, opts.quiet);
19
+ }
20
+ catch (e) {
21
+ const { message, exitCode } = describeSitesError(e);
22
+ console.error(`Error: ${message}`);
23
+ return exitCode;
24
+ }
25
+ }
26
+ export function createSitesListCommand() {
27
+ return new Command("list")
28
+ .description("List registered sites")
29
+ .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
30
+ .option("-f, --format <format>", "json | md", "json")
31
+ .option("--limit <limit>", "results per page, 1-100 (default: 25)")
32
+ .option("--offset <offset>", "pagination offset (default: 0)")
33
+ .option("--include-archived", "include archived sites")
34
+ .option("--quiet", "suppress status messages")
35
+ .action(async (opts) => {
36
+ process.exit(await runSitesList(opts));
37
+ });
38
+ }
@@ -0,0 +1,53 @@
1
+ import { Command } from "commander";
2
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR, apiClient } from "../../utils/api.js";
3
+ import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
4
+ const VALID_SECTIONS = new Set(["flight", "security", "dns"]);
5
+ /** True when the argument parses as an absolute URL (has a scheme); false → treat as a project id. */
6
+ function looksLikeUrl(value) {
7
+ try {
8
+ new URL(value);
9
+ return true;
10
+ }
11
+ catch {
12
+ return false;
13
+ }
14
+ }
15
+ /** Trigger a re-scan of an existing site, identified by project id or URL. Returns the process exit code. */
16
+ export async function runSitesScan(projectIdOrUrl, opts) {
17
+ if (rejectUnsupportedFormat(opts.format))
18
+ return EXIT_GENERAL_ERROR;
19
+ const key = resolveKey(opts.apiKey);
20
+ const body = looksLikeUrl(projectIdOrUrl)
21
+ ? { url: projectIdOrUrl }
22
+ : { projectId: projectIdOrUrl };
23
+ if (opts.sections) {
24
+ const sections = String(opts.sections).split(",").map((s) => s.trim()).filter(Boolean);
25
+ const invalid = sections.filter((s) => !VALID_SECTIONS.has(s));
26
+ if (invalid.length > 0) {
27
+ console.error(`Error: invalid --sections value(s): ${invalid.join(", ")} (expected: flight, security, dns)`);
28
+ return 1;
29
+ }
30
+ body.sections = sections;
31
+ }
32
+ try {
33
+ const { data } = await apiClient.post(apiUrl("static/sites/scan"), body, { headers: { "x-api-key": key } });
34
+ return writePayload(data, opts.format, opts.quiet);
35
+ }
36
+ catch (e) {
37
+ const { message, exitCode } = describeSitesError(e);
38
+ console.error(`Error: ${message}`);
39
+ return exitCode;
40
+ }
41
+ }
42
+ export function createSitesScanCommand() {
43
+ return new Command("scan")
44
+ .description("Trigger a re-scan of an existing site")
45
+ .argument("<projectIdOrUrl>", "site's project id, or its URL")
46
+ .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
47
+ .option("-f, --format <format>", "json | md", "json")
48
+ .option("--sections <sections>", "comma-separated subset of flight,security,dns (default: all)")
49
+ .option("--quiet", "suppress status messages")
50
+ .action(async (projectIdOrUrl, opts) => {
51
+ process.exit(await runSitesScan(projectIdOrUrl, opts));
52
+ });
53
+ }
@@ -128,7 +128,9 @@ const REDIRECT_OPS = new Set([">", ">>", "<", "<<"]);
128
128
  /** Bound on recursion through nested shell wrappers / substitutions. */
129
129
  const MAX_SANITIZE_DEPTH = 8;
130
130
  function isOpChar(c) {
131
- return c === ";" || c === "&" || c === "|" || c === ">" || c === "<";
131
+ // \n and \r are statement separators (rf-6pqx): a newline ends a command
132
+ // exactly as ";" does, so a payload on a later line is classified on its own.
133
+ return c === ";" || c === "&" || c === "|" || c === ">" || c === "<" || c === "\n" || c === "\r";
132
134
  }
133
135
  /** Read a `$(…)` substitution starting at `i`; returns its contents and the next index. */
134
136
  function readSubst(s, i) {
@@ -161,18 +163,32 @@ function readBacktick(s, i) {
161
163
  }
162
164
  return { inner, next: Math.min(j + 1, s.length) };
163
165
  }
164
- /** Split a command line into words and operators, respecting quotes and substitutions. */
166
+ /**
167
+ * Split a command line into words and operators, respecting quotes and substitutions.
168
+ * `unterminated` is set when a quote is never closed — the parse is then unreliable
169
+ * and the caller must FAIL CLOSED (match the raw string) rather than trust a
170
+ * desynchronized sanitization (se-y6vo: `$'a\'b'` swallows a trailing payload).
171
+ */
165
172
  function tokenize(s) {
166
173
  const pieces = [];
174
+ let unterminated = false;
167
175
  let i = 0;
168
176
  while (i < s.length) {
169
177
  const c = s[i];
170
- if (/\s/.test(c)) {
178
+ // Whitespace EXCEPT newlines is skipped; a newline falls through to the
179
+ // operator branch below so it becomes a statement separator (rf-6pqx).
180
+ if (/\s/.test(c) && c !== "\n" && c !== "\r") {
171
181
  i++;
172
182
  continue;
173
183
  }
174
184
  if (isOpChar(c)) {
175
185
  const start = i;
186
+ if (c === "\n" || c === "\r") {
187
+ // Normalize a line break (incl. CRLF) to a ";" separator piece.
188
+ i += 1;
189
+ pieces.push({ start, end: i, op: ";", text: ";", quoted: false, substs: [] });
190
+ continue;
191
+ }
176
192
  const two = s.slice(i, i + 2);
177
193
  const op = (two === "&&" || two === "||" || two === ">>" || two === "<<") ? two : c;
178
194
  i += op.length;
@@ -188,6 +204,20 @@ function tokenize(s) {
188
204
  if (/\s/.test(ch) || isOpChar(ch))
189
205
  break;
190
206
  if (ch === "\\") {
207
+ // Line continuation: `\` immediately before a newline (incl. CRLF) is
208
+ // deleted by the shell — `r\<NL>m` is `rm`, so the newline must not be
209
+ // absorbed into the word (rf-6pqx/se-y6vo).
210
+ const nxt = s[i + 1] ?? "";
211
+ if (nxt === "\n") {
212
+ i += 2;
213
+ continue;
214
+ }
215
+ if (nxt === "\r") {
216
+ i += 2;
217
+ if (s[i] === "\n")
218
+ i++;
219
+ continue;
220
+ }
191
221
  i++;
192
222
  if (i < s.length) {
193
223
  text += s[i];
@@ -199,19 +229,43 @@ function tokenize(s) {
199
229
  if (ch === "'") {
200
230
  i++;
201
231
  quoted = true;
202
- while (i < s.length && s[i] !== "'") {
232
+ let closed = false;
233
+ while (i < s.length) {
234
+ if (s[i] === "'") {
235
+ closed = true;
236
+ i++;
237
+ break;
238
+ }
203
239
  text += s[i];
204
240
  i++;
205
241
  }
206
- i++;
242
+ if (!closed)
243
+ unterminated = true;
207
244
  continue;
208
245
  }
209
246
  // Double quotes are data, but `$( )` / backticks inside them DO execute.
210
247
  if (ch === '"') {
211
248
  i++;
212
249
  quoted = true;
213
- while (i < s.length && s[i] !== '"') {
250
+ let closed = false;
251
+ while (i < s.length) {
252
+ if (s[i] === '"') {
253
+ closed = true;
254
+ i++;
255
+ break;
256
+ }
214
257
  if (s[i] === "\\") {
258
+ const nxt = s[i + 1] ?? "";
259
+ if (nxt === "\n") {
260
+ i += 2;
261
+ continue;
262
+ }
263
+ if (nxt === "\r") {
264
+ i += 2;
265
+ if (s[i] === "\n")
266
+ i++;
267
+ continue;
268
+ }
215
269
  i++;
216
270
  if (i < s.length) {
217
271
  text += s[i];
@@ -234,7 +288,8 @@ function tokenize(s) {
234
288
  text += s[i];
235
289
  i++;
236
290
  }
237
- i++;
291
+ if (!closed)
292
+ unterminated = true;
238
293
  continue;
239
294
  }
240
295
  if (ch === "$" && s[i + 1] === "(") {
@@ -254,7 +309,7 @@ function tokenize(s) {
254
309
  }
255
310
  pieces.push({ start, end: i, op: null, text, quoted, substs });
256
311
  }
257
- return pieces;
312
+ return { pieces, unterminated };
258
313
  }
259
314
  /** `/usr/bin/rm` → `rm`; used to classify the executable of a segment. */
260
315
  function execName(text) {
@@ -264,11 +319,58 @@ function execName(text) {
264
319
  const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
265
320
  const SHELL_C_FLAG = /^-[a-z]*c$/;
266
321
  const LONG_FLAG_WITH_VALUE = /^(--[a-z][a-z-]*)=/;
322
+ const NUMERIC_ARG = /^\d+[a-z]*$/i;
323
+ /**
324
+ * A heredoc introducer: `<<`, optional `-`/`~` (indented-terminator forms), an
325
+ * optional quote around the delimiter, and the delimiter word. Group 1 is the
326
+ * dash/tilde, group 3 is the delimiter name. `g` so we can find all on a line.
327
+ */
328
+ const HEREDOC_START = /(?<!<)<<(?!<)([-~]?)\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2/g;
329
+ /** Chain/pipe operators, used to find the statement that owns a heredoc. */
330
+ const CHAIN_SPLIT = /\|\||&&|[;|&]/;
267
331
  /**
268
332
  * Decide, for one segment (a single command in a chain), which spans are DATA
269
333
  * and which are code, appending the resulting replacements.
270
334
  */
271
- function processSegment(pieces, depth, out) {
335
+ /**
336
+ * The effective executable of a segment (`sudo rm -rf /` -> `rm`), used to ask
337
+ * what the NEXT stage of a pipeline does with this stage's output.
338
+ */
339
+ function segmentExec(pieces) {
340
+ const isRedirectTarget = new Array(pieces.length).fill(false);
341
+ for (let i = 1; i < pieces.length; i++) {
342
+ const prev = pieces[i - 1];
343
+ if (prev.op && REDIRECT_OPS.has(prev.op) && !pieces[i].op)
344
+ isRedirectTarget[i] = true;
345
+ }
346
+ for (let i = 0; i < pieces.length; i++) {
347
+ const p = pieces[i];
348
+ if (p.op || isRedirectTarget[i])
349
+ continue;
350
+ if (!p.quoted && ENV_ASSIGNMENT.test(p.text))
351
+ continue;
352
+ if (!p.quoted && TAIL_WRAPPERS.has(execName(p.text))) {
353
+ let j = i + 1;
354
+ while (j < pieces.length) {
355
+ const q = pieces[j];
356
+ if (q.op || isRedirectTarget[j]) {
357
+ j++;
358
+ continue;
359
+ }
360
+ if (q.text.startsWith("-") || /^\d+[a-z]*$/i.test(q.text)) {
361
+ j++;
362
+ continue;
363
+ }
364
+ break;
365
+ }
366
+ i = j - 1;
367
+ continue;
368
+ }
369
+ return execName(p.text);
370
+ }
371
+ return "";
372
+ }
373
+ function processSegment(pieces, depth, out, pipedIntoShell = false, outputExecuted = false) {
272
374
  // A word is a redirect target when the piece before it is `>`/`>>`/`<`.
273
375
  const isRedirectTarget = new Array(pieces.length).fill(false);
274
376
  for (let i = 1; i < pieces.length; i++) {
@@ -323,6 +425,14 @@ function processSegment(pieces, depth, out) {
323
425
  hasEvalFlag = true;
324
426
  }
325
427
  const codeCarrying = hasShellExec || hasEvalFlag || EVAL_EXECS.has(exec);
428
+ // sable-c6an. Two questions the code conflated, and conflating them gets one
429
+ // of them wrong:
430
+ // codeCarrying — this segment RUNS a command string it was handed
431
+ // executesOutput — this segment's STDOUT becomes code somewhere else
432
+ // (`… | bash`, or a substitution used as a -c script)
433
+ // `bash -c "echo 'rm -rf /'"` is the first and not the second, so its operand
434
+ // stays data; `bash -c "$(echo rm -rf /)"` is the second, so it is code.
435
+ const executesOutput = pipedIntoShell || outputExecuted;
326
436
  let seenShell = false;
327
437
  let pendingScript = false;
328
438
  let prevTextFlag = false;
@@ -338,7 +448,17 @@ function processSegment(pieces, depth, out) {
338
448
  seenShell = true;
339
449
  // `bash -c <script>` — the next word is a command string, not data.
340
450
  if (pendingScript && !p.text.startsWith("-")) {
341
- out.push({ start: p.start, end: p.end, with: sanitize(p.text, depth + 1) });
451
+ // The script can be entirely a substitution — `bash -c "$(…)"` — where
452
+ // `text` is EMPTY and the substitution IS the script. Reading only `text`
453
+ // dropped it, so `bash -c "$(echo rm -rf /)"` classified low: a bypass of
454
+ // the hard block needing no policy file (sable-c6an). The substitution's
455
+ // OUTPUT is the script, so it sanitizes as output-executed.
456
+ const parts = [];
457
+ if (p.text !== "")
458
+ parts.push(sanitize(p.text, depth + 1));
459
+ for (const sub of p.substs)
460
+ parts.push(sanitize(sub, depth + 1, true));
461
+ out.push({ start: p.start, end: p.end, with: parts.join(" ") });
342
462
  pendingScript = false;
343
463
  prevTextFlag = false;
344
464
  continue;
@@ -350,7 +470,9 @@ function processSegment(pieces, depth, out) {
350
470
  }
351
471
  // `$(…)` / backticks execute — scan their contents, drop the literal wrapper.
352
472
  if (p.substs.length > 0) {
353
- const inner = p.substs.map((s) => sanitize(s, depth + 1)).join(" ");
473
+ const inner = p.substs
474
+ .map((s) => sanitize(s, depth + 1, codeCarrying || executesOutput))
475
+ .join(" ");
354
476
  out.push({ start: p.start, end: p.end, with: inner });
355
477
  prevTextFlag = false;
356
478
  continue;
@@ -386,7 +508,7 @@ function processSegment(pieces, depth, out) {
386
508
  }
387
509
  prevTextFlag = false;
388
510
  // Operands of a text command (`echo`, `grep`, `printf`) are never executed.
389
- if (isTextExec && i > execIdx) {
511
+ if (isTextExec && i > execIdx && !executesOutput) {
390
512
  out.push({ start: p.start, end: p.end, with: " " });
391
513
  continue;
392
514
  }
@@ -397,7 +519,7 @@ function processSegment(pieces, depth, out) {
397
519
  // hide a flag or a path from the patterns (`rm "-rf" "/"`).
398
520
  out.push({ start: p.start, end: p.end, with: p.text });
399
521
  }
400
- else if (codeCarrying) {
522
+ else if (codeCarrying || executesOutput) {
401
523
  // This segment executes a command string (`ssh host "…"`, `mysql -e "…"`).
402
524
  // The quoted argument is code — unquote and scan it, recursively.
403
525
  out.push({ start: p.start, end: p.end, with: sanitize(p.text, depth + 1) });
@@ -409,21 +531,93 @@ function processSegment(pieces, depth, out) {
409
531
  }
410
532
  }
411
533
  }
412
- function sanitize(command, depth) {
534
+ /**
535
+ * Remove `\<newline>` line continuations the way a shell does BEFORE parsing.
536
+ * `r\<NL>m -rf /` is `rm -rf /` to bash, so the backslash-newline must be deleted
537
+ * or the token `rm` never forms and the pattern misses it (se-y6vo). Removed when
538
+ * unquoted or inside double quotes; PRESERVED inside single quotes.
539
+ */
540
+ function stripLineContinuations(s) {
541
+ if (!s.includes("\\"))
542
+ return s;
543
+ let out = "";
544
+ let i = 0;
545
+ let inSingle = false;
546
+ let inDouble = false;
547
+ while (i < s.length) {
548
+ const c = s[i];
549
+ if (c === "'" && !inDouble) {
550
+ inSingle = !inSingle;
551
+ out += c;
552
+ i++;
553
+ continue;
554
+ }
555
+ if (c === '"' && !inSingle) {
556
+ inDouble = !inDouble;
557
+ out += c;
558
+ i++;
559
+ continue;
560
+ }
561
+ if (c === "\\" && !inSingle) {
562
+ const nxt = s[i + 1] ?? "";
563
+ if (nxt === "\n") {
564
+ i += 2;
565
+ continue;
566
+ }
567
+ if (nxt === "\r") {
568
+ i += 2;
569
+ if (s[i] === "\n")
570
+ i++;
571
+ continue;
572
+ }
573
+ // Normal escape (`\"`, `\$`, …): keep both chars so an escaped quote does
574
+ // not flip the quote state above.
575
+ out += c;
576
+ if (i + 1 < s.length) {
577
+ out += s[i + 1];
578
+ i += 2;
579
+ }
580
+ else {
581
+ i++;
582
+ }
583
+ continue;
584
+ }
585
+ out += c;
586
+ i++;
587
+ }
588
+ return out;
589
+ }
590
+ function sanitize(command, depth, outputExecuted = false) {
413
591
  if (!command || depth > MAX_SANITIZE_DEPTH)
414
592
  return command;
415
- const pieces = tokenize(command);
593
+ command = stripLineContinuations(command);
594
+ const { pieces, unterminated } = tokenize(command);
595
+ // Fail closed: an unterminated quote means the parse desynchronized from the
596
+ // shell, so a sanitized view could hide an executable payload. Match the raw
597
+ // command instead (se-y6vo).
598
+ if (unterminated)
599
+ return command;
416
600
  const replacements = [];
601
+ // Segments keep the operator that ends them, so a segment can be asked
602
+ // whether its output feeds a shell (`echo "rm -rf /" | bash`).
603
+ const segments = [];
417
604
  let segment = [];
418
605
  for (const p of pieces) {
419
606
  if (p.op && CHAIN_OPS.has(p.op)) {
420
- processSegment(segment, depth, replacements);
607
+ segments.push({ pieces: segment, endOp: p.op });
421
608
  segment = [];
422
609
  continue;
423
610
  }
424
611
  segment.push(p);
425
612
  }
426
- processSegment(segment, depth, replacements);
613
+ segments.push({ pieces: segment, endOp: null });
614
+ for (let k = 0; k < segments.length; k++) {
615
+ const next = segments[k + 1];
616
+ const pipedIntoShell = segments[k].endOp === "|" &&
617
+ next !== undefined &&
618
+ SHELL_EXECS.has(segmentExec(next.pieces));
619
+ processSegment(segments[k].pieces, depth, replacements, pipedIntoShell, outputExecuted);
620
+ }
427
621
  if (replacements.length === 0)
428
622
  return command;
429
623
  replacements.sort((a, b) => a.start - b.start);
@@ -443,8 +637,117 @@ function sanitize(command, depth) {
443
637
  * command consumes as DATA is redacted; text a shell or eval wrapper EXECUTES
444
638
  * is preserved (and recursively sanitized). Everything else is untouched.
445
639
  */
640
+ /**
641
+ * Does the command that owns a heredoc EXECUTE its body? `cat > f <<EOF` /
642
+ * `grep -q x <<EOF` consume the body as DATA; `bash <<EOF` / `sh <<'EOF'` /
643
+ * `ssh host <<EOF` EXECUTE it. Only a data body may be stripped; an executed
644
+ * body must stay visible to the patterns (else the newline fix opens a fresh
645
+ * bypass — se-y6vo).
646
+ */
647
+ function heredocOwnerExecutes(line, ltPos) {
648
+ const head = line.slice(0, ltPos);
649
+ const segments = head.split(CHAIN_SPLIT);
650
+ const seg = segments.length ? segments[segments.length - 1] : head;
651
+ const tokens = seg.split(/\s+/).filter((t) => t.length > 0);
652
+ let idx = 0;
653
+ while (idx < tokens.length) {
654
+ const tok = tokens[idx];
655
+ if (ENV_ASSIGNMENT.test(tok)) {
656
+ idx++;
657
+ continue;
658
+ }
659
+ const name = execName(tok);
660
+ if (TAIL_WRAPPERS.has(name)) {
661
+ idx++;
662
+ while (idx < tokens.length && (tokens[idx].startsWith("-") || NUMERIC_ARG.test(tokens[idx])))
663
+ idx++;
664
+ continue;
665
+ }
666
+ return SHELL_EXECS.has(name) || EVAL_EXECS.has(name);
667
+ }
668
+ return false;
669
+ }
670
+ /**
671
+ * Blank heredoc BODIES that a command consumes as DATA, before tokenizing.
672
+ * A body written to a file (`cat > doc.md <<EOF … EOF`) or searched
673
+ * (`grep <<EOF … EOF`) is data, never executed. Leaving it in place makes the
674
+ * newline-as-separator fix (rf-6pqx) classify ordinary documentation writes as
675
+ * CRITICAL (rf-3rsj) — the same over-block public #230 reported. Stripping it
676
+ * fixes both. A body EXECUTED by a shell/eval owner is KEPT so it is still
677
+ * scanned. Co-designed with kerckhoffs (se-ijzs) and achebe (#230).
678
+ */
679
+ /**
680
+ * `cat <<EOF | bash` — the body is data to `cat`, but `cat`'s OUTPUT is the
681
+ * script, so the body is executed after all. The owner check above only reads
682
+ * the text BEFORE the introducer and never sees the pipe, so without this a
683
+ * heredoc piped into a shell is stripped and the hard block is silently lost.
684
+ * Keeping a body is the safe direction: it can only over-block, and only for a
685
+ * shape that should block anyway.
686
+ */
687
+ function heredocOutputPipedToShell(line, ltPos) {
688
+ const stages = line.slice(ltPos).split("|").slice(1);
689
+ for (const stage of stages) {
690
+ const tokens = stage.trim().split(/\s+/).filter((t) => t.length > 0);
691
+ let idx = 0;
692
+ while (idx < tokens.length) {
693
+ const tok = tokens[idx];
694
+ if (ENV_ASSIGNMENT.test(tok)) {
695
+ idx++;
696
+ continue;
697
+ }
698
+ const name = execName(tok);
699
+ if (TAIL_WRAPPERS.has(name)) {
700
+ idx++;
701
+ while (idx < tokens.length && (tokens[idx].startsWith("-") || NUMERIC_ARG.test(tokens[idx])))
702
+ idx++;
703
+ continue;
704
+ }
705
+ if (SHELL_EXECS.has(name) || EVAL_EXECS.has(name))
706
+ return true;
707
+ break;
708
+ }
709
+ }
710
+ return false;
711
+ }
712
+ function stripHeredocBodies(command) {
713
+ if (!command.includes("<<"))
714
+ return command;
715
+ const lines = command.split("\n");
716
+ const out = [];
717
+ let k = 0;
718
+ while (k < lines.length) {
719
+ const line = lines[k];
720
+ out.push(line);
721
+ HEREDOC_START.lastIndex = 0;
722
+ const matches = [...line.matchAll(HEREDOC_START)];
723
+ k += 1;
724
+ if (matches.length === 0)
725
+ continue;
726
+ const ltPos = matches[0].index ?? 0;
727
+ const keep = heredocOwnerExecutes(line, ltPos) || heredocOutputPipedToShell(line, ltPos);
728
+ for (const m of matches) {
729
+ const delim = m[3];
730
+ const dash = m[1]; // '-'/'~': a tab-indented terminator is allowed
731
+ while (k < lines.length) {
732
+ // bash terminates only on a line EXACTLY equal to the delimiter — for
733
+ // plain `<<` an indented delimiter is body; `<<-` strips leading TABS.
734
+ let cand = lines[k].replace(/\r$/, "");
735
+ if (dash)
736
+ cand = cand.replace(/^\t+/, "");
737
+ if (cand === delim) {
738
+ k += 1;
739
+ break;
740
+ }
741
+ if (keep)
742
+ out.push(lines[k]);
743
+ k += 1;
744
+ }
745
+ }
746
+ }
747
+ return out.join("\n");
748
+ }
446
749
  export function sanitizeCommandForMatching(command) {
447
- return sanitize(command, 0);
750
+ return sanitize(stripHeredocBodies(command), 0);
448
751
  }
449
752
  /**
450
753
  * Assess risk level of a command string.
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from "commander";
3
3
  import * as dotenv from "dotenv";
4
+ import { guardSecurityEnvFromDotenv } from "./utils/env-guard.js";
4
5
  import { createRunCommand } from "./commands/backend/run.js";
5
6
  import { createGetCommand } from "./commands/backend/get.js";
6
7
  import { createUsageCommand } from "./commands/backend/usage.js";
@@ -18,10 +19,12 @@ import { createNotifyCommand } from "./commands/notify.js";
18
19
  import { createCompletionCommand } from "./commands/completion.js";
19
20
  import { createIssuesCommand } from "./commands/issues/index.js";
20
21
  import { createReportCommand } from "./commands/report.js";
22
+ import { createSitesCommand } from "./commands/sites/index.js";
21
23
  import { checkForUpdate } from "./utils/update-checker.js";
22
24
  import { setAgentMode } from "./utils/formatter.js";
23
25
  import { createRequire } from "module";
24
- dotenv.config();
26
+ // rf-7dda: a repo `.env` must not be able to disable the hook or its timeouts.
27
+ guardSecurityEnvFromDotenv(() => dotenv.config());
25
28
  const require = createRequire(import.meta.url);
26
29
  const { version: VERSION } = require("../package.json");
27
30
  // Set agent mode early from argv — preAction hooks may not propagate to nested
@@ -39,6 +42,8 @@ const program = new Command()
39
42
  program.addCommand(createRunCommand());
40
43
  program.addCommand(createGetCommand());
41
44
  program.addCommand(createUsageCommand());
45
+ // Sites — live-application security monitoring
46
+ program.addCommand(createSitesCommand());
42
47
  // Scan command group (default: remote scan; subcommands: local, remote)
43
48
  program.addCommand(createScanGroupCommand());
44
49
  // Secrets — top-level alias for local secret scanning (explicit-scope name)
@@ -150,6 +150,13 @@ export class BetterleaksScanner {
150
150
  return [];
151
151
  }
152
152
  const parsed = JSON.parse(content);
153
+ // #217 — betterleaks >=1.1.2 writes the literal `null` (not `[]`) for a
154
+ // clean scan via the `dir`/`git` subcommands we invoke. That is a valid
155
+ // empty result, not a version mismatch, so it must not reach the warning
156
+ // branch below — otherwise every clean file scanned emits warning noise.
157
+ if (parsed === null) {
158
+ return [];
159
+ }
153
160
  if (!Array.isArray(parsed)) {
154
161
  // sable-o4k — a stale/incompatible binary emits a non-array shape and
155
162
  // would otherwise silently yield zero findings. The managed binary is