@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.
@@ -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,6 +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, apiClient } from "../../utils/api.js";
14
+ import { describeSitesError, resolveMcpApiKey } from "../sites/errors.js";
13
15
  import { createRequire } from "module";
14
16
  const _require = createRequire(import.meta.url);
15
17
  const { version: CLI_VERSION } = _require("../../../package.json");
@@ -131,6 +133,56 @@ export function createServer() {
131
133
  required: ["path"],
132
134
  },
133
135
  },
136
+ {
137
+ name: "sites_create",
138
+ description: "Register a URL as a Rafter Site for live-application security monitoring (exposed backends, DNS misconfig, SEO, accessibility) and kick off its first scan. Use when asked to start monitoring a domain/site.",
139
+ inputSchema: {
140
+ type: "object",
141
+ properties: {
142
+ url: { type: "string", description: "URL of the site to monitor" },
143
+ },
144
+ required: ["url"],
145
+ },
146
+ },
147
+ {
148
+ name: "sites_scan",
149
+ description: "Trigger a re-scan of an existing Rafter Site. Identify the site by projectId OR url (exactly one required). Use when asked to re-scan or refresh a site's findings.",
150
+ inputSchema: {
151
+ type: "object",
152
+ properties: {
153
+ projectId: { type: "string", description: "The site's project id (use this or url, not both)" },
154
+ url: { type: "string", description: "The site's URL (use this or projectId, not both)" },
155
+ sections: {
156
+ type: "array",
157
+ items: { type: "string", enum: ["flight", "security", "dns"] },
158
+ description: "Subset of scan sections to run. Omit to run all.",
159
+ },
160
+ },
161
+ },
162
+ },
163
+ {
164
+ name: "sites_list",
165
+ description: "List Rafter Sites registered for monitoring, paginated. Use when asked 'what sites are being monitored?' or to browse before calling sites_get.",
166
+ inputSchema: {
167
+ type: "object",
168
+ properties: {
169
+ limit: { type: "number", description: "Results per page, 1-100 (default: 25)" },
170
+ offset: { type: "number", description: "Pagination offset (default: 0)" },
171
+ include_archived: { type: "boolean", description: "Include archived sites (default: false)" },
172
+ },
173
+ },
174
+ },
175
+ {
176
+ name: "sites_get",
177
+ description: "Get a Rafter Site's status, latest scan run, and findings summary by its project id. Use after sites_list or sites_create to check a specific site's results.",
178
+ inputSchema: {
179
+ type: "object",
180
+ properties: {
181
+ id: { type: "string", description: "The site's project id" },
182
+ },
183
+ required: ["id"],
184
+ },
185
+ },
134
186
  ],
135
187
  }));
136
188
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
@@ -271,6 +323,76 @@ export function createServer() {
271
323
  return errorResult(`Failed to write suppression: ${err.message || err}`);
272
324
  }
273
325
  }
326
+ case "sites_create": {
327
+ const url = args?.url;
328
+ if (!url)
329
+ return errorResult("url is required");
330
+ const key = resolveMcpApiKey();
331
+ if (!key)
332
+ return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
333
+ try {
334
+ const { data } = await apiClient.post(apiUrl("static/sites"), { url }, { headers: { "x-api-key": key } });
335
+ return textResult(data);
336
+ }
337
+ catch (e) {
338
+ return errorResult(describeSitesError(e).message);
339
+ }
340
+ }
341
+ case "sites_scan": {
342
+ const projectId = args?.projectId;
343
+ const url = args?.url;
344
+ if (!projectId && !url)
345
+ return errorResult("Provide exactly one of projectId or url");
346
+ if (projectId && url)
347
+ return errorResult("Provide exactly one of projectId or url, not both");
348
+ const key = resolveMcpApiKey();
349
+ if (!key)
350
+ return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
351
+ const body = projectId ? { projectId } : { url };
352
+ if (Array.isArray(args?.sections))
353
+ body.sections = args.sections.map((s) => String(s));
354
+ try {
355
+ const { data } = await apiClient.post(apiUrl("static/sites/scan"), body, { headers: { "x-api-key": key } });
356
+ return textResult(data);
357
+ }
358
+ catch (e) {
359
+ return errorResult(describeSitesError(e).message);
360
+ }
361
+ }
362
+ case "sites_list": {
363
+ const key = resolveMcpApiKey();
364
+ if (!key)
365
+ return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
366
+ const params = {};
367
+ if (args?.limit !== undefined)
368
+ params.limit = String(args.limit);
369
+ if (args?.offset !== undefined)
370
+ params.offset = String(args.offset);
371
+ if (args?.include_archived)
372
+ params.include_archived = "true";
373
+ try {
374
+ const { data } = await apiClient.get(apiUrl("static/sites"), { params, headers: { "x-api-key": key } });
375
+ return textResult(data);
376
+ }
377
+ catch (e) {
378
+ return errorResult(describeSitesError(e).message);
379
+ }
380
+ }
381
+ case "sites_get": {
382
+ const id = args?.id;
383
+ if (!id)
384
+ return errorResult("id is required");
385
+ const key = resolveMcpApiKey();
386
+ if (!key)
387
+ return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
388
+ try {
389
+ const { data } = await apiClient.get(apiUrl(`static/sites/${encodeURIComponent(id)}`), { headers: { "x-api-key": key } });
390
+ return textResult(data);
391
+ }
392
+ catch (e) {
393
+ return errorResult(describeSitesError(e).message);
394
+ }
395
+ }
274
396
  default:
275
397
  return errorResult(`Unknown tool: ${name}`);
276
398
  }
@@ -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
  });
@@ -0,0 +1,29 @@
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
+ /** Register a URL as a Site and kick off its first scan. Returns the process exit code. */
5
+ export async function runSitesCreate(url, opts) {
6
+ if (rejectUnsupportedFormat(opts.format))
7
+ return EXIT_GENERAL_ERROR;
8
+ const key = resolveKey(opts.apiKey);
9
+ try {
10
+ const { data } = await apiClient.post(apiUrl("static/sites"), { url }, { headers: { "x-api-key": key } });
11
+ return writePayload(data, opts.format, opts.quiet);
12
+ }
13
+ catch (e) {
14
+ const { message, exitCode } = describeSitesError(e);
15
+ console.error(`Error: ${message}`);
16
+ return exitCode;
17
+ }
18
+ }
19
+ export function createSitesCreateCommand() {
20
+ return new Command("create")
21
+ .description("Register a site for live monitoring and kick off its first scan")
22
+ .argument("<url>", "URL of the site to monitor")
23
+ .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
24
+ .option("-f, --format <format>", "json | md", "json")
25
+ .option("--quiet", "suppress status messages")
26
+ .action(async (url, opts) => {
27
+ process.exit(await runSitesCreate(url, opts));
28
+ });
29
+ }
@@ -0,0 +1,78 @@
1
+ import { EXIT_GENERAL_ERROR, EXIT_QUOTA_EXHAUSTED, EXIT_INSUFFICIENT_SCOPE, EXIT_SCAN_NOT_FOUND, } from "../../utils/api.js";
2
+ import { ConfigManager } from "../../core/config-manager.js";
3
+ /**
4
+ * Resolve the Rafter API key for a context with no CLI flag (e.g. an MCP tool
5
+ * call). Same precedence as resolveKey() in utils/api.ts (env > stored config)
6
+ * minus the --api-key flag, but returns undefined instead of calling
7
+ * process.exit — killing the whole MCP server over one tool's missing key
8
+ * would take every other tool down with it.
9
+ */
10
+ export function resolveMcpApiKey() {
11
+ if (process.env.RAFTER_API_KEY)
12
+ return process.env.RAFTER_API_KEY;
13
+ try {
14
+ const stored = new ConfigManager().get("backend.apiKey");
15
+ if (typeof stored === "string" && stored.trim())
16
+ return stored.trim();
17
+ }
18
+ catch {
19
+ // Config unreadable — fall through.
20
+ }
21
+ return undefined;
22
+ }
23
+ /** Extract a human-readable message from a Sites API error response body. */
24
+ function errorBodyMessage(e) {
25
+ const body = e?.response?.data;
26
+ if (typeof body === "string" && body.trim())
27
+ return body;
28
+ if (body && typeof body === "object") {
29
+ if (typeof body.error === "string" && body.error)
30
+ return body.error;
31
+ if (typeof body.message === "string" && body.message)
32
+ return body.message;
33
+ }
34
+ // Deliberately no non-empty fallback here — an unconditional default (e.g.
35
+ // "Unknown error") would make every `msg || "<status-specific default>"`
36
+ // check in describeSitesError() below unreachable, since msg would never
37
+ // be falsy. Let describeSitesError()'s own per-status defaults apply.
38
+ return e?.message || "";
39
+ }
40
+ /**
41
+ * The Sites API never returns a `markdown` field, so `--format md` has nothing
42
+ * to render. Rather than silently falling back to JSON (which looks like
43
+ * success but produces the wrong format), reject up front with a clear error.
44
+ * Returns true (and prints the error) when `fmt` is unsupported.
45
+ */
46
+ export function rejectUnsupportedFormat(fmt) {
47
+ if (fmt !== "md")
48
+ return false;
49
+ console.error("Error: Sites does not support --format md yet, use --format json");
50
+ return true;
51
+ }
52
+ /**
53
+ * Map a Sites API (/api/static/sites*) error to a CLI-friendly message + exit code.
54
+ *
55
+ * Unlike the remote-scan API (see handle403 in utils/api.ts, which infers "quota"
56
+ * from a `scan_mode` field), the Sites API returns 403 for BOTH wrong API-key
57
+ * scope and plan/site limits — the only signal is the free-text `error` string.
58
+ * Never assume 403 == quota here. 404 means "not found or not owned by this
59
+ * account" — the Sites API deliberately does not distinguish the two.
60
+ */
61
+ export function describeSitesError(e) {
62
+ const status = e?.response?.status;
63
+ const msg = errorBodyMessage(e);
64
+ switch (status) {
65
+ case 400:
66
+ return { message: `Bad request — ${msg}`, exitCode: EXIT_GENERAL_ERROR };
67
+ case 401:
68
+ return { message: `Unauthorized — ${msg || "invalid or missing API key"}`, exitCode: EXIT_GENERAL_ERROR };
69
+ case 403:
70
+ return { message: `Forbidden — ${msg || "access denied"}`, exitCode: EXIT_INSUFFICIENT_SCOPE };
71
+ case 404:
72
+ return { message: `Not found — ${msg || "site not found, or not owned by this account"}`, exitCode: EXIT_SCAN_NOT_FOUND };
73
+ case 429:
74
+ return { message: `Rate limited — ${msg || "too many requests, try again later"}`, exitCode: EXIT_QUOTA_EXHAUSTED };
75
+ default:
76
+ return { message: msg || "Request failed", exitCode: EXIT_GENERAL_ERROR };
77
+ }
78
+ }
@@ -0,0 +1,29 @@
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
+ /** Get a site's status, latest run, and findings summary. Returns the process exit code. */
5
+ export async function runSitesGet(id, opts) {
6
+ if (rejectUnsupportedFormat(opts.format))
7
+ return EXIT_GENERAL_ERROR;
8
+ const key = resolveKey(opts.apiKey);
9
+ try {
10
+ const { data } = await apiClient.get(apiUrl(`static/sites/${encodeURIComponent(id)}`), { headers: { "x-api-key": key } });
11
+ return writePayload(data, opts.format, opts.quiet);
12
+ }
13
+ catch (e) {
14
+ const { message, exitCode } = describeSitesError(e);
15
+ console.error(`Error: ${message}`);
16
+ return exitCode;
17
+ }
18
+ }
19
+ export function createSitesGetCommand() {
20
+ return new Command("get")
21
+ .description("Get a site's status, latest run, and findings summary")
22
+ .argument("<id>", "site's project id")
23
+ .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
24
+ .option("-f, --format <format>", "json | md", "json")
25
+ .option("--quiet", "suppress status messages")
26
+ .action(async (id, opts) => {
27
+ process.exit(await runSitesGet(id, opts));
28
+ });
29
+ }