@rafter-security/cli 0.10.0 → 0.10.2

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,52 +1,237 @@
1
- import axios from "axios";
2
1
  import ora from "ora";
3
- import { API, writePayload, EXIT_GENERAL_ERROR, EXIT_SCAN_NOT_FOUND } from "../../utils/api.js";
2
+ import { API_TIMEOUT_SHORT_MS, writePayload, EXIT_GENERAL_ERROR, EXIT_SCAN_NOT_FOUND, apiClient, apiUrl } from "../../utils/api.js";
4
3
  import { fmt as output } from "../../utils/formatter.js";
4
+ /**
5
+ * sable-l10k — the report a scan writes is not durable the instant the scan
6
+ * flips to completed, so a poll can legitimately hit a 5xx (commonly
7
+ * "Failed to fetch report from storage: Object not found") on an otherwise
8
+ * healthy scan. Retry those instead of failing the whole run; a scan that
9
+ * would have succeeded 10 seconds later must not die on one bad read.
10
+ *
11
+ * 404 is transient only AFTER the scan is known to exist: once the first poll
12
+ * has succeeded, a missing scan is read-after-write lag rather than a wrong id.
13
+ * On the first poll a 404 is still fatal.
14
+ */
15
+ export const MAX_TRANSIENT_POLL_FAILURES = 5;
16
+ /**
17
+ * Total transient failures tolerated across one `handleScanStatus` call.
18
+ *
19
+ * The consecutive counter resets on every success, which is what we want — a
20
+ * twenty-minute scan with one blip at minute 2 and another at minute 18 should
21
+ * not die. But reset-on-success alone means a backend alternating 200/500
22
+ * forever never exhausts the budget, and the CLI has no wall-clock deadline to
23
+ * stop it. This is the backstop for that.
24
+ */
25
+ export const MAX_TOTAL_TRANSIENT_POLL_FAILURES = 20;
26
+ /** Longest single error detail we will echo back. Servers can be verbose. */
27
+ const MAX_ERROR_DETAIL_CHARS = 200;
28
+ /**
29
+ * Transient = the request never got an answer, or got one the server itself
30
+ * describes as temporary.
31
+ *
32
+ * `scanExists` gates 404: before the first successful poll a 404 means the
33
+ * scan id is wrong, and retrying it just delays a clear answer.
34
+ */
35
+ function isTransientPollError(e, scanExists) {
36
+ const status = e?.response?.status;
37
+ if (status === undefined) {
38
+ // Retry only errors that came from the HTTP layer. A TypeError thrown from
39
+ // our own code also has no `response`, and must not be mistaken for a flaky
40
+ // backend and retried five times.
41
+ return Boolean(e?.isAxiosError || e?.request);
42
+ }
43
+ if (status === 404)
44
+ return scanExists;
45
+ return status >= 500 || status === 408;
46
+ }
47
+ function truncate(value) {
48
+ // A server is free to answer {"error": {"message": "..."}}. Coerce before
49
+ // touching string methods — this used to throw, which turned a retryable
50
+ // failure into an immediate crash with a nonsense message.
51
+ const s = typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
52
+ const flat = s.replace(/[\r\n]+/g, " ").trim();
53
+ return flat.length > MAX_ERROR_DETAIL_CHARS
54
+ ? `${flat.slice(0, MAX_ERROR_DETAIL_CHARS)}…`
55
+ : flat;
56
+ }
57
+ function describeHttpError(e) {
58
+ const status = e?.response?.status;
59
+ const data = e?.response?.data;
60
+ let detail = "";
61
+ if (typeof data === "string") {
62
+ detail = data;
63
+ }
64
+ else if (data && typeof data === "object") {
65
+ detail = data.error ?? data;
66
+ }
67
+ else if (e instanceof Error) {
68
+ detail = e.message;
69
+ }
70
+ const detailText = truncate(detail);
71
+ return status
72
+ ? `HTTP ${status}${detailText ? ` — ${detailText}` : ""}`
73
+ : detailText || String(e);
74
+ }
75
+ /**
76
+ * The message a customer actually sees when the report never becomes readable.
77
+ * Storage-layer wording ("Object not found") is kept as supporting detail, not
78
+ * as the whole explanation, and the next action is spelled out.
79
+ */
80
+ export function unreadableReportMessage(scan_id, lastError, attempts = MAX_TRANSIENT_POLL_FAILURES, reachedServer = true) {
81
+ if (!reachedServer) {
82
+ return (`Rafter could not reach the API after ${attempts} attempts.\n` +
83
+ `Check your network and that https://rafter.so is reachable from here.\n` +
84
+ `Your scan id is ${scan_id} — the scan may still be running.\n` +
85
+ `Last error: ${lastError}`);
86
+ }
87
+ return (`Rafter could not read the report for scan ${scan_id} after ` +
88
+ `${attempts} attempts.\n` +
89
+ `The scan itself may have finished — retry with: rafter get ${scan_id}\n` +
90
+ `or open the scan in your dashboard at https://rafter.so/dashboard\n` +
91
+ `Last response from the server: ${lastError}`);
92
+ }
93
+ export const BASE_BACKOFF_MS = 2000;
94
+ /** 2s, 4s, 8s, 16s — the 5th failure gives up rather than sleeping again. */
95
+ export function backoffMs(consecutiveFailures) {
96
+ return BASE_BACKOFF_MS * 2 ** (consecutiveFailures - 1);
97
+ }
98
+ /**
99
+ * Thrown when polling gives up after repeated transient failures. Carries the
100
+ * customer-facing message so callers do not have to rebuild it.
101
+ */
102
+ export class PollGaveUpError extends Error {
103
+ }
104
+ /**
105
+ * A failure budget shared across every poll in one `handleScanStatus` call.
106
+ *
107
+ * Counting per-request would let a backend that alternates 200/500 forever
108
+ * reset the counter on each success and never exhaust it — the CLI has no
109
+ * wall-clock deadline, so that loop would never end.
110
+ */
111
+ class FailureBudget {
112
+ constructor() {
113
+ this.consecutive = 0;
114
+ this.total = 0;
115
+ this.last = "";
116
+ /** False once any failure carried no HTTP response at all. */
117
+ this.lastReachedServer = true;
118
+ }
119
+ record(detail, reachedServer) {
120
+ this.consecutive += 1;
121
+ this.total += 1;
122
+ this.last = detail;
123
+ this.lastReachedServer = reachedServer;
124
+ return this.consecutive;
125
+ }
126
+ /** A success clears the consecutive run, but never refunds the total. */
127
+ reset() {
128
+ this.consecutive = 0;
129
+ }
130
+ get exhausted() {
131
+ return (this.consecutive >= MAX_TRANSIENT_POLL_FAILURES ||
132
+ this.total >= MAX_TOTAL_TRANSIENT_POLL_FAILURES);
133
+ }
134
+ }
135
+ /**
136
+ * One poll, with retry/backoff over transient failures.
137
+ * Non-transient errors are rethrown for the caller to classify.
138
+ */
139
+ async function pollUntilReadable(scan_id, headers, fmt, budget, scanExists, onRetry) {
140
+ for (;;) {
141
+ try {
142
+ const res = await apiClient.get(apiUrl("static/scan"), {
143
+ params: { scan_id, format: fmt },
144
+ headers,
145
+ // Without this a hung server stalls inside a single request, and the
146
+ // retry loop can only notice between attempts.
147
+ timeout: API_TIMEOUT_SHORT_MS,
148
+ });
149
+ budget.reset();
150
+ return res;
151
+ }
152
+ catch (e) {
153
+ if (!isTransientPollError(e, scanExists))
154
+ throw e;
155
+ const attempt = budget.record(describeHttpError(e), e?.response?.status !== undefined);
156
+ if (budget.exhausted) {
157
+ throw new PollGaveUpError(unreadableReportMessage(scan_id, budget.last, budget.total, budget.lastReachedServer));
158
+ }
159
+ const waitMs = backoffMs(attempt);
160
+ onRetry?.(attempt, waitMs, budget.last);
161
+ await new Promise((r) => setTimeout(r, waitMs));
162
+ }
163
+ }
164
+ }
165
+ /**
166
+ * A single scan fetch with the same retry budget the poll loop uses.
167
+ *
168
+ * `rafter get <id>` is what the give-up message tells customers to run, so it
169
+ * must not be defeated by exactly the transient failure that produced the
170
+ * message. A 404 here is still fatal — that is a wrong id, not lag.
171
+ */
172
+ export async function fetchScanWithRetry(scan_id, headers, fmt, quiet) {
173
+ const budget = new FailureBudget();
174
+ const onRetry = quiet
175
+ ? undefined
176
+ : (attempt, waitMs, detail) => {
177
+ console.error(`Report not readable yet (${detail}); retrying in ${Math.round(waitMs / 1000)}s ` +
178
+ `(${attempt}/${MAX_TRANSIENT_POLL_FAILURES})`);
179
+ };
180
+ return pollUntilReadable(scan_id, headers, fmt, budget, false, onRetry);
181
+ }
182
+ const IN_PROGRESS = ["queued", "pending", "processing"];
5
183
  export async function handleScanStatus(scan_id, headers, fmt, quiet) {
6
- // First poll
184
+ const budget = new FailureBudget();
185
+ // Retries are printed to stderr, not just into the spinner: ora renders
186
+ // nothing on a non-TTY, and CI is exactly where this diagnostic matters.
187
+ const onRetry = quiet
188
+ ? undefined
189
+ : (attempt, waitMs, detail) => {
190
+ console.error(`Report not readable yet (${detail}); retrying in ${Math.round(waitMs / 1000)}s ` +
191
+ `(${attempt}/${MAX_TRANSIENT_POLL_FAILURES})`);
192
+ };
193
+ // First poll. A 404 here really does mean "no such scan" — do not retry it.
194
+ // Transient 5xx IS retried, so that the `rafter get <id>` this command
195
+ // recommends on failure is not itself defeated by one bad read.
7
196
  let poll;
8
197
  try {
9
- poll = await axios.get(`${API}/static/scan`, { params: { scan_id, format: fmt }, headers });
198
+ poll = await pollUntilReadable(scan_id, headers, fmt, budget, false, onRetry);
10
199
  }
11
200
  catch (e) {
12
- if (e.response?.status === 404) {
201
+ if (e?.response?.status === 404) {
13
202
  console.error(output.error(`Scan '${scan_id}' not found`));
14
203
  return EXIT_SCAN_NOT_FOUND;
15
204
  }
16
- console.error(output.error(`${e.response?.data || e.message}`));
205
+ console.error(output.error(e instanceof PollGaveUpError ? e.message : describeHttpError(e)));
17
206
  return EXIT_GENERAL_ERROR;
18
207
  }
19
208
  let status = poll.data.status;
20
- if (["queued", "pending", "processing"].includes(status)) {
21
- if (!quiet) {
22
- const spinner = ora("Waiting for scan to complete... (this could take several minutes)").start();
23
- while (["queued", "pending", "processing"].includes(status)) {
209
+ if (IN_PROGRESS.includes(status)) {
210
+ const spinner = quiet
211
+ ? undefined
212
+ : ora("Waiting for scan to complete... (this could take several minutes)").start();
213
+ try {
214
+ while (IN_PROGRESS.includes(status)) {
24
215
  await new Promise((r) => setTimeout(r, 10000));
25
- poll = await axios.get(`${API}/static/scan`, { params: { scan_id, format: fmt }, headers });
216
+ poll = await pollUntilReadable(scan_id, headers, fmt, budget, true, onRetry);
26
217
  status = poll.data.status;
27
218
  if (status === "completed") {
28
- spinner.succeed("Scan completed");
219
+ spinner?.succeed("Scan completed");
29
220
  return writePayload(poll.data, fmt, quiet);
30
221
  }
31
222
  else if (status === "failed") {
32
- spinner.fail("Scan failed");
223
+ spinner?.fail("Scan failed");
33
224
  return EXIT_GENERAL_ERROR;
34
225
  }
35
226
  }
36
- console.error(`Scan status: ${status}`);
37
227
  }
38
- else {
39
- while (["queued", "pending", "processing"].includes(status)) {
40
- await new Promise((r) => setTimeout(r, 10000));
41
- poll = await axios.get(`${API}/static/scan`, { params: { scan_id, format: fmt }, headers });
42
- status = poll.data.status;
43
- if (status === "completed") {
44
- return writePayload(poll.data, fmt, quiet);
45
- }
46
- else if (status === "failed") {
47
- return EXIT_GENERAL_ERROR;
48
- }
49
- }
228
+ catch (e) {
229
+ spinner?.fail("Could not retrieve scan report");
230
+ console.error(output.error(e instanceof PollGaveUpError ? e.message : describeHttpError(e)));
231
+ return EXIT_GENERAL_ERROR;
232
+ }
233
+ if (!quiet) {
234
+ console.error(`Scan status: ${status}`);
50
235
  }
51
236
  }
52
237
  else if (status === "completed") {
@@ -1,13 +1,12 @@
1
1
  import { Command } from "commander";
2
- import axios from "axios";
3
- import { API, resolveKey, EXIT_GENERAL_ERROR } from "../../utils/api.js";
2
+ import { resolveKey, EXIT_GENERAL_ERROR, apiClient, apiUrl } from "../../utils/api.js";
4
3
  export function createUsageCommand() {
5
4
  return new Command("usage")
6
5
  .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
7
6
  .action(async (opts) => {
8
7
  const key = resolveKey(opts.apiKey);
9
8
  try {
10
- const { data } = await axios.get(`${API}/static/usage`, { headers: { "x-api-key": key } });
9
+ const { data } = await apiClient.get(apiUrl("static/usage"), { headers: { "x-api-key": key } });
11
10
  console.log(JSON.stringify(data, null, 2));
12
11
  }
13
12
  catch (e) {
@@ -7,8 +7,7 @@
7
7
  */
8
8
  import { Command } from "commander";
9
9
  import fs from "fs";
10
- import axios from "axios";
11
- import { API, resolveKey, EXIT_GENERAL_ERROR } from "../../utils/api.js";
10
+ import { resolveKey, EXIT_GENERAL_ERROR, apiClient, apiUrl } from "../../utils/api.js";
12
11
  import { detectRepo } from "../../utils/git.js";
13
12
  import { fmt } from "../../utils/formatter.js";
14
13
  import { createIssue, listOpenIssues } from "./github-client.js";
@@ -121,16 +120,37 @@ async function runFromScan(opts) {
121
120
  console.error(fmt.success(`Created ${created.length}/${drafts.length} issue(s)`));
122
121
  }
123
122
  }
123
+ /**
124
+ * The findings list from a scan payload, or an error — never a silent [].
125
+ *
126
+ * A payload without a `vulnerabilities` array is not "no findings". It is a
127
+ * scan that has not completed, a failed scan, or a report this client cannot
128
+ * read; filing zero issues from it would report a clean codebase for work
129
+ * that was never done (sable-fgk7). An empty array IS a legitimate clean
130
+ * result and is returned as such.
131
+ */
132
+ export function vulnerabilitiesFromPayload(data, scanId) {
133
+ const payload = data;
134
+ if (payload && Array.isArray(payload.vulnerabilities)) {
135
+ return payload.vulnerabilities;
136
+ }
137
+ const status = payload && typeof payload.status === "string" ? payload.status : undefined;
138
+ if (status && status !== "completed") {
139
+ throw new Error(`Scan ${scanId} is ${status}, not completed — there are no findings to file yet. ` +
140
+ `Retry once it completes: rafter get ${scanId}`);
141
+ }
142
+ throw new Error(`Scan ${scanId} returned no 'vulnerabilities' array; refusing to treat an unreadable ` +
143
+ `report as zero findings. Check it with: rafter get ${scanId}`);
144
+ }
124
145
  async function draftsFromBackendScan(scanId, apiKey) {
125
146
  const key = resolveKey(apiKey);
126
- const { data } = await axios.get(`${API}/static/scan`, {
147
+ const { data } = await apiClient.get(apiUrl("static/scan"), {
127
148
  params: { scan_id: scanId, format: "json" },
128
149
  headers: { "x-api-key": key },
129
150
  });
130
- const vulns = data.vulnerabilities || [];
131
- return vulns.map(buildFromBackendVulnerability);
151
+ return vulnerabilitiesFromPayload(data, scanId).map(buildFromBackendVulnerability);
132
152
  }
133
- function draftsFromLocalScan(filePath) {
153
+ export function draftsFromLocalScan(filePath) {
134
154
  const raw = fs.readFileSync(filePath, "utf-8");
135
155
  const parsed = JSON.parse(raw);
136
156
  // New shape: { _note, scan_mode, triage_applied, results: [...] }
@@ -103,7 +103,7 @@ async function readInput(opts) {
103
103
  * - File paths → mentioned in body
104
104
  * - Security keywords → security label
105
105
  */
106
- function parseNaturalText(text) {
106
+ export function parseNaturalText(text) {
107
107
  const lines = text.trim().split("\n");
108
108
  const labels = [];
109
109
  // Extract title: first non-empty line, cleaned up
@@ -6,7 +6,7 @@
6
6
  * - Local scan results (secret detection)
7
7
  */
8
8
  import { fingerprint, embedFingerprint } from "./dedup.js";
9
- function severityLabel(level) {
9
+ export function severityLabel(level) {
10
10
  const map = {
11
11
  error: "critical",
12
12
  critical: "critical",
@@ -10,9 +10,8 @@ import { AuditLogger } from "../../core/audit-logger.js";
10
10
  import { ConfigManager, redactConfigSecrets, isSecretConfigKey, maskSecretValue } from "../../core/config-manager.js";
11
11
  import { listDocs, resolveDocSelector, fetchDoc } from "../../core/docs-loader.js";
12
12
  import { writeSuppression } from "../../core/suppression-writer.js";
13
- import { apiUrl } from "../../utils/api.js";
13
+ import { apiUrl, apiClient } from "../../utils/api.js";
14
14
  import { describeSitesError, resolveMcpApiKey } from "../sites/errors.js";
15
- import axios from "axios";
16
15
  import { createRequire } from "module";
17
16
  const _require = createRequire(import.meta.url);
18
17
  const { version: CLI_VERSION } = _require("../../../package.json");
@@ -332,7 +331,7 @@ export function createServer() {
332
331
  if (!key)
333
332
  return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
334
333
  try {
335
- const { data } = await axios.post(apiUrl("static/sites"), { url }, { headers: { "x-api-key": key } });
334
+ const { data } = await apiClient.post(apiUrl("static/sites"), { url }, { headers: { "x-api-key": key } });
336
335
  return textResult(data);
337
336
  }
338
337
  catch (e) {
@@ -353,7 +352,7 @@ export function createServer() {
353
352
  if (Array.isArray(args?.sections))
354
353
  body.sections = args.sections.map((s) => String(s));
355
354
  try {
356
- const { data } = await axios.post(apiUrl("static/sites/scan"), body, { headers: { "x-api-key": key } });
355
+ const { data } = await apiClient.post(apiUrl("static/sites/scan"), body, { headers: { "x-api-key": key } });
357
356
  return textResult(data);
358
357
  }
359
358
  catch (e) {
@@ -372,7 +371,7 @@ export function createServer() {
372
371
  if (args?.include_archived)
373
372
  params.include_archived = "true";
374
373
  try {
375
- const { data } = await axios.get(apiUrl("static/sites"), { params, headers: { "x-api-key": key } });
374
+ const { data } = await apiClient.get(apiUrl("static/sites"), { params, headers: { "x-api-key": key } });
376
375
  return textResult(data);
377
376
  }
378
377
  catch (e) {
@@ -387,7 +386,7 @@ export function createServer() {
387
386
  if (!key)
388
387
  return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
389
388
  try {
390
- const { data } = await axios.get(apiUrl(`static/sites/${encodeURIComponent(id)}`), { headers: { "x-api-key": key } });
389
+ const { data } = await apiClient.get(apiUrl(`static/sites/${encodeURIComponent(id)}`), { headers: { "x-api-key": key } });
391
390
  return textResult(data);
392
391
  }
393
392
  catch (e) {
@@ -1,6 +1,5 @@
1
1
  import { Command } from "commander";
2
- import axios from "axios";
3
- import { API, resolveKey, EXIT_GENERAL_ERROR, EXIT_SCAN_NOT_FOUND } from "../utils/api.js";
2
+ import { resolveKey, EXIT_GENERAL_ERROR, EXIT_SCAN_NOT_FOUND, apiClient, apiUrl } from "../utils/api.js";
4
3
  import { validateWebhookUrl } from "../core/audit-logger.js";
5
4
  import { ConfigManager } from "../core/config-manager.js";
6
5
  import { fmt } from "../utils/formatter.js";
@@ -210,7 +209,7 @@ export function createNotifyCommand() {
210
209
  if (scanId) {
211
210
  const key = resolveKey(opts?.apiKey);
212
211
  try {
213
- const { data } = await axios.get(`${API}/static/scan`, {
212
+ const { data } = await apiClient.get(apiUrl("static/scan"), {
214
213
  params: { scan_id: scanId, format: "json" },
215
214
  headers: { "x-api-key": key },
216
215
  });
@@ -1,6 +1,5 @@
1
1
  import { Command } from "commander";
2
- import axios from "axios";
3
- import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR } from "../../utils/api.js";
2
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR, apiClient } from "../../utils/api.js";
4
3
  import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
5
4
  /** Register a URL as a Site and kick off its first scan. Returns the process exit code. */
6
5
  export async function runSitesCreate(url, opts) {
@@ -8,7 +7,7 @@ export async function runSitesCreate(url, opts) {
8
7
  return EXIT_GENERAL_ERROR;
9
8
  const key = resolveKey(opts.apiKey);
10
9
  try {
11
- const { data } = await axios.post(apiUrl("static/sites"), { url }, { headers: { "x-api-key": key } });
10
+ const { data } = await apiClient.post(apiUrl("static/sites"), { url }, { headers: { "x-api-key": key } });
12
11
  return writePayload(data, opts.format, opts.quiet);
13
12
  }
14
13
  catch (e) {
@@ -1,6 +1,5 @@
1
1
  import { Command } from "commander";
2
- import axios from "axios";
3
- import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR } from "../../utils/api.js";
2
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR, apiClient } from "../../utils/api.js";
4
3
  import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
5
4
  /** Get a site's status, latest run, and findings summary. Returns the process exit code. */
6
5
  export async function runSitesGet(id, opts) {
@@ -8,7 +7,7 @@ export async function runSitesGet(id, opts) {
8
7
  return EXIT_GENERAL_ERROR;
9
8
  const key = resolveKey(opts.apiKey);
10
9
  try {
11
- const { data } = await axios.get(apiUrl(`static/sites/${encodeURIComponent(id)}`), { headers: { "x-api-key": key } });
10
+ const { data } = await apiClient.get(apiUrl(`static/sites/${encodeURIComponent(id)}`), { headers: { "x-api-key": key } });
12
11
  return writePayload(data, opts.format, opts.quiet);
13
12
  }
14
13
  catch (e) {
@@ -1,6 +1,5 @@
1
1
  import { Command } from "commander";
2
- import axios from "axios";
3
- import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR } from "../../utils/api.js";
2
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR, apiClient } from "../../utils/api.js";
4
3
  import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
5
4
  /** List registered sites, paginated. Returns the process exit code. */
6
5
  export async function runSitesList(opts) {
@@ -15,7 +14,7 @@ export async function runSitesList(opts) {
15
14
  if (opts.includeArchived)
16
15
  params.include_archived = "true";
17
16
  try {
18
- const { data } = await axios.get(apiUrl("static/sites"), { params, headers: { "x-api-key": key } });
17
+ const { data } = await apiClient.get(apiUrl("static/sites"), { params, headers: { "x-api-key": key } });
19
18
  return writePayload(data, opts.format, opts.quiet);
20
19
  }
21
20
  catch (e) {
@@ -1,6 +1,5 @@
1
1
  import { Command } from "commander";
2
- import axios from "axios";
3
- import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR } from "../../utils/api.js";
2
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR, apiClient } from "../../utils/api.js";
4
3
  import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
5
4
  const VALID_SECTIONS = new Set(["flight", "security", "dns"]);
6
5
  /** True when the argument parses as an absolute URL (has a scheme); false → treat as a project id. */
@@ -31,7 +30,7 @@ export async function runSitesScan(projectIdOrUrl, opts) {
31
30
  body.sections = sections;
32
31
  }
33
32
  try {
34
- const { data } = await axios.post(apiUrl("static/sites/scan"), body, { headers: { "x-api-key": key } });
33
+ const { data } = await apiClient.post(apiUrl("static/sites/scan"), body, { headers: { "x-api-key": key } });
35
34
  return writePayload(data, opts.format, opts.quiet);
36
35
  }
37
36
  catch (e) {
@@ -77,6 +77,10 @@ function validateConfig(raw) {
77
77
  console.error('Warning: config "agent.commandPolicy.requireApproval" must be an array of strings — using default.');
78
78
  cp.requireApproval = [...defaults.agent.commandPolicy.requireApproval];
79
79
  }
80
+ if (cp.allowProjectOverride !== undefined && typeof cp.allowProjectOverride !== "boolean") {
81
+ console.error('Warning: config "agent.commandPolicy.allowProjectOverride" must be a boolean — ignoring (project policies cannot loosen command policy).');
82
+ delete cp.allowProjectOverride;
83
+ }
80
84
  }
81
85
  // audit
82
86
  const audit = agent.audit;
@@ -261,6 +265,18 @@ export class ConfigManager {
261
265
  this.save(config);
262
266
  }
263
267
  }
268
+ /**
269
+ * Whether the machine owner has opted out of the project-policy floor.
270
+ *
271
+ * Read from `this.load()` — the GLOBAL config file only. It must never be
272
+ * sourced from the project `.rafter.yml`, because a repo that could set this
273
+ * flag could switch the floor off and the protection would be worth nothing.
274
+ * That asymmetry is the whole point of the setting, so it is read here rather
275
+ * than off the already-merged config.
276
+ */
277
+ allowsProjectOverride() {
278
+ return this.load().agent?.commandPolicy?.allowProjectOverride === true;
279
+ }
264
280
  /**
265
281
  * Load config merged with .rafter.yml policy (policy wins)
266
282
  */
@@ -278,17 +294,10 @@ export class ConfigManager {
278
294
  if (policy.riskLevel && config.agent) {
279
295
  config.agent.riskLevel = policy.riskLevel;
280
296
  }
281
- // Command policy — arrays replace, not append
297
+ // Command policy — the global config is a FLOOR the project may raise but
298
+ // never lower. See `mergeCommandPolicy` (sable-nz4y).
282
299
  if (policy.commandPolicy && config.agent) {
283
- if (policy.commandPolicy.mode) {
284
- config.agent.commandPolicy.mode = policy.commandPolicy.mode;
285
- }
286
- if (policy.commandPolicy.blockedPatterns) {
287
- config.agent.commandPolicy.blockedPatterns = policy.commandPolicy.blockedPatterns;
288
- }
289
- if (policy.commandPolicy.requireApproval) {
290
- config.agent.commandPolicy.requireApproval = policy.commandPolicy.requireApproval;
291
- }
300
+ mergeCommandPolicy(config.agent.commandPolicy, policy.commandPolicy, this.allowsProjectOverride());
292
301
  }
293
302
  // Scan settings
294
303
  if (policy.scan && config.agent) {
@@ -390,3 +399,89 @@ export class ConfigManager {
390
399
  return item && typeof item === "object" && !Array.isArray(item);
391
400
  }
392
401
  }
402
+ // ---------------------------------------------------------------------------
403
+ // Project-policy floor (sable-nz4y)
404
+ // ---------------------------------------------------------------------------
405
+ //
406
+ // Policy discovery walks up from cwd to the git root, so the `.rafter.yml` this
407
+ // merges is a file IN THE REPOSITORY BEING WORKED ON. rafter ships inside agent
408
+ // pretool hooks, so on an untrusted repo that file is attacker-controlled.
409
+ //
410
+ // It used to REPLACE the machine owner's command policy wholesale: a repo
411
+ // shipping `{ mode: allow-all, blocked_patterns: [], require_approval: [] }`
412
+ // switched off every guardrail below the unconditional critical hard-block —
413
+ // including patterns the owner had explicitly deny-listed.
414
+ //
415
+ // The rule this restores is the one the codebase already states ~20 lines below,
416
+ // for the Plus-approval gate (sable-9ddf): a project policy may turn a gate ON,
417
+ // but must never turn OFF a gate the machine owner set globally. So the global
418
+ // config is a FLOOR:
419
+ //
420
+ // * blockedPatterns / requireApproval — UNION. A project adds rules; removing
421
+ // one the owner set is not expressible.
422
+ // * mode — accepted only when at least as strict as the owner's. A project
423
+ // may tighten `allow-all` to `approve-dangerous`, never the reverse.
424
+ //
425
+ // The owner (never the repo) can opt out with
426
+ // `agent.commandPolicy.allowProjectOverride: true` in the GLOBAL config, which
427
+ // restores the old replace semantics for people who deliberately delegate policy
428
+ // to their projects.
429
+ //
430
+ // Note this does not touch the critical hard-block, which was never reachable
431
+ // from policy: CommandInterceptor.evaluate() returns on `critical` BEFORE any
432
+ // policy is loaded. That property held under every hostile policy tested; this
433
+ // change is about everything *below* critical.
434
+ /**
435
+ * Strictness rank for command-policy modes. Higher is stricter.
436
+ *
437
+ * `approve-dangerous` is the only mode that gates on assessed risk, so it is
438
+ * strictly stronger than the other two. `deny-list` and `allow-all` currently
439
+ * behave identically in the interceptor (both rely solely on the explicit
440
+ * pattern lists, which are checked regardless of mode) — they are ranked apart
441
+ * anyway so that a project moving `allow-all` -> `deny-list` is treated as a
442
+ * tightening rather than a lateral move if their behavior ever diverges.
443
+ */
444
+ const COMMAND_MODE_STRICTNESS = {
445
+ "allow-all": 0,
446
+ "deny-list": 1,
447
+ "approve-dangerous": 2,
448
+ };
449
+ /** Union preserving order: floor entries first, then project entries not already present. */
450
+ function unionPatterns(floor, project) {
451
+ const seen = new Set(floor);
452
+ return [...floor, ...project.filter((p) => !seen.has(p))];
453
+ }
454
+ /**
455
+ * Merge a project command policy over the global one under the floor rule.
456
+ *
457
+ * Mutates `target` in place, matching the surrounding merge style. When
458
+ * `allowOverride` is true the pre-sable-nz4y replace semantics are used.
459
+ */
460
+ export function mergeCommandPolicy(target, project, allowOverride) {
461
+ if (allowOverride) {
462
+ if (project.mode)
463
+ target.mode = project.mode;
464
+ if (project.blockedPatterns)
465
+ target.blockedPatterns = project.blockedPatterns;
466
+ if (project.requireApproval)
467
+ target.requireApproval = project.requireApproval;
468
+ return;
469
+ }
470
+ if (project.mode && project.mode !== target.mode) {
471
+ const projectRank = COMMAND_MODE_STRICTNESS[project.mode];
472
+ const floorRank = COMMAND_MODE_STRICTNESS[target.mode];
473
+ // An unknown mode is not demonstrably at least as strict, so it is refused.
474
+ if (projectRank !== undefined && floorRank !== undefined && projectRank >= floorRank) {
475
+ target.mode = project.mode;
476
+ }
477
+ else {
478
+ console.error(`Warning: project policy sets agent.commandPolicy.mode "${project.mode}", which is less strict than "${target.mode}" from your global config — ignoring. Set agent.commandPolicy.allowProjectOverride: true in your global config to allow project policies to loosen command policy.`);
479
+ }
480
+ }
481
+ if (project.blockedPatterns) {
482
+ target.blockedPatterns = unionPatterns(target.blockedPatterns, project.blockedPatterns);
483
+ }
484
+ if (project.requireApproval) {
485
+ target.requireApproval = unionPatterns(target.requireApproval, project.requireApproval);
486
+ }
487
+ }