@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.
@@ -262,9 +262,11 @@ function codexHooks() {
262
262
  const post = { type: "command", command: "rafter hook posttool" };
263
263
  cfg.hooks.PreToolUse = filterOutRafter(cfg.hooks.PreToolUse, (e) => hookEntryMatchesRafter(e, "rafter hook pretool"));
264
264
  cfg.hooks.PostToolUse = filterOutRafter(cfg.hooks.PostToolUse, (e) => hookEntryMatchesRafter(e, "rafter hook posttool"));
265
- // Bash + apply_patch per Codex hook docs (rf-ovql verification).
265
+ // Bash + apply_patch per Codex hook docs (rf-ovql verification). PostToolUse
266
+ // mirrors that write/exec surface (narrowed from `.*` to skip Read/MCP log
267
+ // noise), matching claude-code posttool scoping (sable-h0ah).
266
268
  cfg.hooks.PreToolUse.push({ matcher: "Bash|apply_patch", hooks: [pre] });
267
- cfg.hooks.PostToolUse.push({ matcher: ".*", hooks: [post] });
269
+ cfg.hooks.PostToolUse.push({ matcher: "Bash|apply_patch", hooks: [post] });
268
270
  writeJson(hooksPath, cfg);
269
271
  },
270
272
  uninstall: () => {
@@ -82,7 +82,7 @@ function printDryRunPlan(plan) {
82
82
  if (plan.wantCodex) {
83
83
  console.log();
84
84
  console.log("Codex CLI (--with-codex):");
85
- W(path.join(plan.root, ".codex", "hooks.json"), "PreToolUse: Bash|apply_patch, PostToolUse: .*");
85
+ W(path.join(plan.root, ".codex", "hooks.json"), "PreToolUse: Bash|apply_patch, PostToolUse: Bash|apply_patch");
86
86
  for (const s of AGENT_SKILLS) {
87
87
  W(path.join(plan.root, ".agents", "skills", s.name, "SKILL.md"));
88
88
  }
@@ -314,9 +314,10 @@ function installCodexHooks(root) {
314
314
  // when an MCP server is wired up, install a separate matcher for it.
315
315
  // (rf-ovql verification 2026-05-03.)
316
316
  config.hooks.PreToolUse.push({ matcher: "Bash|apply_patch", hooks: [preHook] });
317
- // PostToolUse fires for the same tool surface; .* keeps all events in the
318
- // audit log without filtering.
319
- config.hooks.PostToolUse.push({ matcher: ".*", hooks: [postHook] });
317
+ // PostToolUse mirrors the same write/exec surface (Bash + apply_patch);
318
+ // narrowed from `.*` so posttool doesn't fire on every Read/MCP call
319
+ // (log noise + latency), matching the claude-code posttool scoping (sable-h0ah).
320
+ config.hooks.PostToolUse.push({ matcher: "Bash|apply_patch", hooks: [postHook] });
320
321
  fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2), "utf-8");
321
322
  console.log(fmt.success(`Installed hooks to ${hooksPath}`));
322
323
  }
@@ -4,18 +4,28 @@ export const RAFTER_MARKER_START = "<!-- rafter:start -->";
4
4
  export const RAFTER_MARKER_END = "<!-- rafter:end -->";
5
5
  /** Rafter security context block for agent instruction files (CLAUDE.md, AGENTS.md, etc.) */
6
6
  export const RAFTER_INSTRUCTION_BLOCK = `${RAFTER_MARKER_START}
7
- ## Security: Rafter (required review gate)
7
+ ## Security: Rafter (surface-driven review gate)
8
8
 
9
- Rafter is this project's security review gate. A security-relevant task is
10
- **not complete** until a rafter skill (or \`rafter run\`) has reviewed it.
11
- Don't mark done, don't hand off, don't open a PR without that pass.
9
+ Rafter is this project's security review gate — driven by the change's **security
10
+ surface**, not by the task label. When a diff touches a real surface (below), it is
11
+ **not complete** until a rafter skill (or \`rafter run\`) has reviewed it: don't mark
12
+ done, don't hand off, don't open a PR without that pass. When it touches **none** of
13
+ that surface — research / experimental / local-only / throwaway code (training
14
+ scripts, data analysis, plotting, model eval, notebooks, pure computation over
15
+ trusted local data) — a quick surface check is enough; proceed without the full
16
+ gate. Judge by the diff's actual surface, not the "research" label: research code
17
+ that reads a secret, shells out, hits the network, parses untrusted input, or bumps
18
+ a dependency still gets the full gate.
12
19
 
13
- **Stop and invoke before continuing:**
20
+ **Stop and invoke when the change touches that surface:**
14
21
 
15
22
  - Designing auth, payments, credentials, tokens, sessions, file upload,
16
- user data, or data deletion → **\`rafter-secure-design\`** (before writing code).
17
- - Diff touches user input, SQL, shell, auth, credentials, file paths, or
18
- serialization → **\`rafter-code-review\`** + \`rafter run\` (before declaring done).
23
+ user/untrusted data, deserialization, network endpoints, or data deletion
24
+ → **\`rafter-secure-design\`** (before writing code).
25
+ - Diff touches user/untrusted input, SQL/query building, shell/exec, auth,
26
+ credentials, file paths, (de)serialization, crypto, network endpoints/outbound
27
+ fetchers (SSRF), data deletion, or dependencies → **\`rafter-code-review\`** +
28
+ \`rafter run\` (before declaring done).
19
29
  - About to install or forward a third-party SKILL.md, MCP manifest, Cursor
20
30
  rule, or agent config → **\`rafter-skill-review\`** (before copying anywhere).
21
31
  - Security-adjacent but the angle isn't clear → **\`rafter\`** (the router skill,
@@ -26,7 +36,9 @@ Don't mark done, don't hand off, don't open a PR without that pass.
26
36
  - \`rafter run\` — remote SAST + SCA + secrets (real code analysis, needs \`RAFTER_API_KEY\`)
27
37
  - \`rafter secrets .\` — local secrets only (offline; NOT a code-security scan)
28
38
  - \`rafter run --mode plus\` — everything in default (\`--mode fast\`) plus
29
- powerful agentic deep-dives (needs \`RAFTER_API_KEY\`)
39
+ powerful agentic deep-dives (needs \`RAFTER_API_KEY\`). **Plus is a PAID tier
40
+ and consumes the user's credits — ask the user before running it.** Enforced
41
+ when \`scan.plus_requires_approval\` is set (then pass \`--yes\` to confirm).
30
42
  ${RAFTER_MARKER_END}`;
31
43
  /**
32
44
  * Write a Rafter instruction block into an instruction file.
@@ -2,12 +2,69 @@ import { Command } from "commander";
2
2
  import axios from "axios";
3
3
  import ora from "ora";
4
4
  import { detectRepo } from "../../utils/git.js";
5
- import { API, resolveKey, EXIT_GENERAL_ERROR, EXIT_QUOTA_EXHAUSTED, handle403 } from "../../utils/api.js";
5
+ import { API, resolveKey, EXIT_GENERAL_ERROR, EXIT_QUOTA_EXHAUSTED, EXIT_CONFIRMATION_REQUIRED, handle403 } from "../../utils/api.js";
6
+ import { ConfigManager } from "../../core/config-manager.js";
7
+ import { loadPolicy } from "../../core/policy-loader.js";
8
+ import { askYesNo } from "../../utils/prompt.js";
6
9
  import { handleScanStatus } from "./scan-status.js";
10
+ /**
11
+ * sable-9ddf — is the Plus-scan approval gate enabled?
12
+ *
13
+ * OR semantics across the machine-owner's global config and the project's
14
+ * `.rafter.yml`: if EITHER opts in, approval is required. A project policy can
15
+ * turn the gate ON but can NEVER turn it OFF — a hostile repo must not be able
16
+ * to silently re-open the credit-burn hole a user closed globally.
17
+ *
18
+ * Fails open (returns false) if config/policy can't be read, consistent with
19
+ * the OFF-by-default product behavior and the codebase's config-load fallback.
20
+ */
21
+ export function plusApprovalGateEnabled() {
22
+ let globalFlag = false;
23
+ try {
24
+ globalFlag = new ConfigManager().load().agent?.scan?.plusRequiresApproval === true;
25
+ }
26
+ catch { /* fail open */ }
27
+ let policyFlag = false;
28
+ try {
29
+ policyFlag = loadPolicy()?.scan?.plusRequiresApproval === true;
30
+ }
31
+ catch { /* fail open */ }
32
+ return globalFlag || policyFlag;
33
+ }
34
+ /**
35
+ * Gate a paid Plus scan behind explicit confirmation when the switch is on.
36
+ * Returns normally if the scan may proceed; calls process.exit otherwise.
37
+ * No-op for non-plus modes and when the gate is disabled (the default).
38
+ */
39
+ export async function confirmPlusScan(opts) {
40
+ if ((opts.mode ?? "fast") !== "plus")
41
+ return;
42
+ if (!plusApprovalGateEnabled())
43
+ return;
44
+ const envConfirm = process.env.RAFTER_CONFIRM;
45
+ const confirmed = opts.yes === true || envConfirm === "1" || envConfirm === "true";
46
+ if (confirmed)
47
+ return;
48
+ if (process.stdin.isTTY) {
49
+ const ok = await askYesNo("Plus is a PAID scan tier and will consume your credits. Proceed?", false);
50
+ if (ok)
51
+ return;
52
+ console.error("Plus scan cancelled.");
53
+ process.exit(EXIT_CONFIRMATION_REQUIRED);
54
+ }
55
+ console.error("Refusing to run a paid Plus scan: approval is required " +
56
+ "(scan.plus_requires_approval is enabled).\n" +
57
+ "Re-run with --yes (or set RAFTER_CONFIRM=1) to confirm the credit spend, " +
58
+ "or use the free --mode fast scan.");
59
+ process.exit(EXIT_CONFIRMATION_REQUIRED);
60
+ }
7
61
  /**
8
62
  * Shared handler for the remote backend scan (used by both `rafter run` and `rafter scan` / `rafter scan remote`).
9
63
  */
10
64
  export async function runRemoteScan(opts) {
65
+ // sable-9ddf — gate paid Plus scans before doing any work (key resolution,
66
+ // repo detection, or the billable API call).
67
+ await confirmPlusScan(opts);
11
68
  const key = resolveKey(opts.apiKey);
12
69
  const ghToken = opts.githubToken || process.env.RAFTER_GITHUB_TOKEN;
13
70
  let repo, branch;
@@ -117,6 +174,7 @@ function addRunOptions(cmd) {
117
174
  .option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
118
175
  .option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
119
176
  .option("--skip-interactive", "do not wait for scan to complete")
177
+ .option("-y, --yes", "confirm a paid Plus scan without prompting (when scan.plus_requires_approval is on)")
120
178
  .option("--quiet", "suppress status messages");
121
179
  }
122
180
  export function createRunCommand() {
@@ -10,6 +10,9 @@ 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";
14
+ import { describeSitesError, resolveMcpApiKey } from "../sites/errors.js";
15
+ import axios from "axios";
13
16
  import { createRequire } from "module";
14
17
  const _require = createRequire(import.meta.url);
15
18
  const { version: CLI_VERSION } = _require("../../../package.json");
@@ -131,6 +134,56 @@ export function createServer() {
131
134
  required: ["path"],
132
135
  },
133
136
  },
137
+ {
138
+ name: "sites_create",
139
+ 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.",
140
+ inputSchema: {
141
+ type: "object",
142
+ properties: {
143
+ url: { type: "string", description: "URL of the site to monitor" },
144
+ },
145
+ required: ["url"],
146
+ },
147
+ },
148
+ {
149
+ name: "sites_scan",
150
+ 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.",
151
+ inputSchema: {
152
+ type: "object",
153
+ properties: {
154
+ projectId: { type: "string", description: "The site's project id (use this or url, not both)" },
155
+ url: { type: "string", description: "The site's URL (use this or projectId, not both)" },
156
+ sections: {
157
+ type: "array",
158
+ items: { type: "string", enum: ["flight", "security", "dns"] },
159
+ description: "Subset of scan sections to run. Omit to run all.",
160
+ },
161
+ },
162
+ },
163
+ },
164
+ {
165
+ name: "sites_list",
166
+ description: "List Rafter Sites registered for monitoring, paginated. Use when asked 'what sites are being monitored?' or to browse before calling sites_get.",
167
+ inputSchema: {
168
+ type: "object",
169
+ properties: {
170
+ limit: { type: "number", description: "Results per page, 1-100 (default: 25)" },
171
+ offset: { type: "number", description: "Pagination offset (default: 0)" },
172
+ include_archived: { type: "boolean", description: "Include archived sites (default: false)" },
173
+ },
174
+ },
175
+ },
176
+ {
177
+ name: "sites_get",
178
+ 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.",
179
+ inputSchema: {
180
+ type: "object",
181
+ properties: {
182
+ id: { type: "string", description: "The site's project id" },
183
+ },
184
+ required: ["id"],
185
+ },
186
+ },
134
187
  ],
135
188
  }));
136
189
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
@@ -271,6 +324,76 @@ export function createServer() {
271
324
  return errorResult(`Failed to write suppression: ${err.message || err}`);
272
325
  }
273
326
  }
327
+ case "sites_create": {
328
+ const url = args?.url;
329
+ if (!url)
330
+ return errorResult("url is required");
331
+ const key = resolveMcpApiKey();
332
+ if (!key)
333
+ return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
334
+ try {
335
+ const { data } = await axios.post(apiUrl("static/sites"), { url }, { headers: { "x-api-key": key } });
336
+ return textResult(data);
337
+ }
338
+ catch (e) {
339
+ return errorResult(describeSitesError(e).message);
340
+ }
341
+ }
342
+ case "sites_scan": {
343
+ const projectId = args?.projectId;
344
+ const url = args?.url;
345
+ if (!projectId && !url)
346
+ return errorResult("Provide exactly one of projectId or url");
347
+ if (projectId && url)
348
+ return errorResult("Provide exactly one of projectId or url, not both");
349
+ const key = resolveMcpApiKey();
350
+ if (!key)
351
+ return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
352
+ const body = projectId ? { projectId } : { url };
353
+ if (Array.isArray(args?.sections))
354
+ body.sections = args.sections.map((s) => String(s));
355
+ try {
356
+ const { data } = await axios.post(apiUrl("static/sites/scan"), body, { headers: { "x-api-key": key } });
357
+ return textResult(data);
358
+ }
359
+ catch (e) {
360
+ return errorResult(describeSitesError(e).message);
361
+ }
362
+ }
363
+ case "sites_list": {
364
+ const key = resolveMcpApiKey();
365
+ if (!key)
366
+ return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
367
+ const params = {};
368
+ if (args?.limit !== undefined)
369
+ params.limit = String(args.limit);
370
+ if (args?.offset !== undefined)
371
+ params.offset = String(args.offset);
372
+ if (args?.include_archived)
373
+ params.include_archived = "true";
374
+ try {
375
+ const { data } = await axios.get(apiUrl("static/sites"), { params, headers: { "x-api-key": key } });
376
+ return textResult(data);
377
+ }
378
+ catch (e) {
379
+ return errorResult(describeSitesError(e).message);
380
+ }
381
+ }
382
+ case "sites_get": {
383
+ const id = args?.id;
384
+ if (!id)
385
+ return errorResult("id is required");
386
+ const key = resolveMcpApiKey();
387
+ if (!key)
388
+ return errorResult("No API key configured. Set RAFTER_API_KEY or run 'rafter agent config set backend.apiKey <key>'.");
389
+ try {
390
+ const { data } = await axios.get(apiUrl(`static/sites/${encodeURIComponent(id)}`), { headers: { "x-api-key": key } });
391
+ return textResult(data);
392
+ }
393
+ catch (e) {
394
+ return errorResult(describeSitesError(e).message);
395
+ }
396
+ }
274
397
  default:
275
398
  return errorResult(`Unknown tool: ${name}`);
276
399
  }
@@ -26,6 +26,7 @@ export function createScanGroupCommand() {
26
26
  .option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
27
27
  .option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
28
28
  .option("--skip-interactive", "do not wait for scan to complete")
29
+ .option("-y, --yes", "confirm a paid Plus scan without prompting (when scan.plus_requires_approval is on)")
29
30
  .option("--quiet", "suppress status messages")
30
31
  .action(async (opts) => {
31
32
  await runRemoteScan(opts);
@@ -43,6 +44,7 @@ export function createScanGroupCommand() {
43
44
  .option("--provider <provider>", "git provider: gitlab | gitea | bitbucket (default: auto-detected; github requires nothing)")
44
45
  .option("--repo-url <url>", "full https clone URL for non-github remotes (default: auto-detected)")
45
46
  .option("--skip-interactive", "do not wait for scan to complete")
47
+ .option("-y, --yes", "confirm a paid Plus scan without prompting (when scan.plus_requires_approval is on)")
46
48
  .option("--quiet", "suppress status messages");
47
49
  scanGroup.addCommand(localCmd, { hidden: true });
48
50
  scanGroup.addCommand(remoteCmd);
@@ -0,0 +1,30 @@
1
+ import { Command } from "commander";
2
+ import axios from "axios";
3
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR } from "../../utils/api.js";
4
+ import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
5
+ /** Register a URL as a Site and kick off its first scan. Returns the process exit code. */
6
+ export async function runSitesCreate(url, opts) {
7
+ if (rejectUnsupportedFormat(opts.format))
8
+ return EXIT_GENERAL_ERROR;
9
+ const key = resolveKey(opts.apiKey);
10
+ try {
11
+ const { data } = await axios.post(apiUrl("static/sites"), { url }, { headers: { "x-api-key": key } });
12
+ return writePayload(data, opts.format, opts.quiet);
13
+ }
14
+ catch (e) {
15
+ const { message, exitCode } = describeSitesError(e);
16
+ console.error(`Error: ${message}`);
17
+ return exitCode;
18
+ }
19
+ }
20
+ export function createSitesCreateCommand() {
21
+ return new Command("create")
22
+ .description("Register a site for live monitoring and kick off its first scan")
23
+ .argument("<url>", "URL of the site to monitor")
24
+ .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
25
+ .option("-f, --format <format>", "json | md", "json")
26
+ .option("--quiet", "suppress status messages")
27
+ .action(async (url, opts) => {
28
+ process.exit(await runSitesCreate(url, opts));
29
+ });
30
+ }
@@ -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,30 @@
1
+ import { Command } from "commander";
2
+ import axios from "axios";
3
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR } from "../../utils/api.js";
4
+ import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
5
+ /** Get a site's status, latest run, and findings summary. Returns the process exit code. */
6
+ export async function runSitesGet(id, opts) {
7
+ if (rejectUnsupportedFormat(opts.format))
8
+ return EXIT_GENERAL_ERROR;
9
+ const key = resolveKey(opts.apiKey);
10
+ try {
11
+ const { data } = await axios.get(apiUrl(`static/sites/${encodeURIComponent(id)}`), { headers: { "x-api-key": key } });
12
+ return writePayload(data, opts.format, opts.quiet);
13
+ }
14
+ catch (e) {
15
+ const { message, exitCode } = describeSitesError(e);
16
+ console.error(`Error: ${message}`);
17
+ return exitCode;
18
+ }
19
+ }
20
+ export function createSitesGetCommand() {
21
+ return new Command("get")
22
+ .description("Get a site's status, latest run, and findings summary")
23
+ .argument("<id>", "site's project id")
24
+ .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
25
+ .option("-f, --format <format>", "json | md", "json")
26
+ .option("--quiet", "suppress status messages")
27
+ .action(async (id, opts) => {
28
+ process.exit(await runSitesGet(id, opts));
29
+ });
30
+ }
@@ -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,39 @@
1
+ import { Command } from "commander";
2
+ import axios from "axios";
3
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR } from "../../utils/api.js";
4
+ import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
5
+ /** List registered sites, paginated. Returns the process exit code. */
6
+ export async function runSitesList(opts) {
7
+ if (rejectUnsupportedFormat(opts.format))
8
+ return EXIT_GENERAL_ERROR;
9
+ const key = resolveKey(opts.apiKey);
10
+ const params = {};
11
+ if (opts.limit !== undefined)
12
+ params.limit = String(opts.limit);
13
+ if (opts.offset !== undefined)
14
+ params.offset = String(opts.offset);
15
+ if (opts.includeArchived)
16
+ params.include_archived = "true";
17
+ try {
18
+ const { data } = await axios.get(apiUrl("static/sites"), { params, headers: { "x-api-key": key } });
19
+ return writePayload(data, opts.format, opts.quiet);
20
+ }
21
+ catch (e) {
22
+ const { message, exitCode } = describeSitesError(e);
23
+ console.error(`Error: ${message}`);
24
+ return exitCode;
25
+ }
26
+ }
27
+ export function createSitesListCommand() {
28
+ return new Command("list")
29
+ .description("List registered sites")
30
+ .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
31
+ .option("-f, --format <format>", "json | md", "json")
32
+ .option("--limit <limit>", "results per page, 1-100 (default: 25)")
33
+ .option("--offset <offset>", "pagination offset (default: 0)")
34
+ .option("--include-archived", "include archived sites")
35
+ .option("--quiet", "suppress status messages")
36
+ .action(async (opts) => {
37
+ process.exit(await runSitesList(opts));
38
+ });
39
+ }
@@ -0,0 +1,54 @@
1
+ import { Command } from "commander";
2
+ import axios from "axios";
3
+ import { apiUrl, resolveKey, writePayload, EXIT_GENERAL_ERROR } from "../../utils/api.js";
4
+ import { describeSitesError, rejectUnsupportedFormat } from "./errors.js";
5
+ const VALID_SECTIONS = new Set(["flight", "security", "dns"]);
6
+ /** True when the argument parses as an absolute URL (has a scheme); false → treat as a project id. */
7
+ function looksLikeUrl(value) {
8
+ try {
9
+ new URL(value);
10
+ return true;
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
16
+ /** Trigger a re-scan of an existing site, identified by project id or URL. Returns the process exit code. */
17
+ export async function runSitesScan(projectIdOrUrl, opts) {
18
+ if (rejectUnsupportedFormat(opts.format))
19
+ return EXIT_GENERAL_ERROR;
20
+ const key = resolveKey(opts.apiKey);
21
+ const body = looksLikeUrl(projectIdOrUrl)
22
+ ? { url: projectIdOrUrl }
23
+ : { projectId: projectIdOrUrl };
24
+ if (opts.sections) {
25
+ const sections = String(opts.sections).split(",").map((s) => s.trim()).filter(Boolean);
26
+ const invalid = sections.filter((s) => !VALID_SECTIONS.has(s));
27
+ if (invalid.length > 0) {
28
+ console.error(`Error: invalid --sections value(s): ${invalid.join(", ")} (expected: flight, security, dns)`);
29
+ return 1;
30
+ }
31
+ body.sections = sections;
32
+ }
33
+ try {
34
+ const { data } = await axios.post(apiUrl("static/sites/scan"), body, { headers: { "x-api-key": key } });
35
+ return writePayload(data, opts.format, opts.quiet);
36
+ }
37
+ catch (e) {
38
+ const { message, exitCode } = describeSitesError(e);
39
+ console.error(`Error: ${message}`);
40
+ return exitCode;
41
+ }
42
+ }
43
+ export function createSitesScanCommand() {
44
+ return new Command("scan")
45
+ .description("Trigger a re-scan of an existing site")
46
+ .argument("<projectIdOrUrl>", "site's project id, or its URL")
47
+ .option("-k, --api-key <key>", "API key or RAFTER_API_KEY env var")
48
+ .option("-f, --format <format>", "json | md", "json")
49
+ .option("--sections <sections>", "comma-separated subset of flight,security,dns (default: all)")
50
+ .option("--quiet", "suppress status messages")
51
+ .action(async (projectIdOrUrl, opts) => {
52
+ process.exit(await runSitesScan(projectIdOrUrl, opts));
53
+ });
54
+ }