UNPKG

@vigilbase/cli

Version:

Vigilbase CLI — security scanners, agent tools, and Vigilbase One from the terminal.

481 lines (475 loc) • 26.3 kB
import { z } from 'zod'; import { shouldUseColor } from '../lib/banner.js'; import { checkupReportLines, readCheckupReport, styleGrade } from '../lib/checkup-report.js'; import { sanitizeTerminal, singleLine } from '../lib/format.js'; import { ASCII_SYMBOLS, UNICODE_SYMBOLS, createStyles, stripAnsi, supportsUnicode } from '../lib/tui.js'; import { CloudflareClient, accountResourceSchema, cloudflareScopeSchema, workspaceSectionSchema, } from '../lib/cloudflare-client.js'; import { assertCommandFlags, asArray, asRecord, ok, outputJson, requireOneClient, withSpinner, } from './helpers.js'; import { InvalidArgumentError, inRange, limitValue, oneOf, textValue, unknownSubcommand } from './legacy-validation.js'; import { flagArgs, listV1, moreCommand } from '../lib/one-v1.js'; import { VigilbaseApiError } from '../lib/client.js'; import { getCloudflareCheckupStatus, getToolRun, listCloudflareDnsRecords } from '../vendor/api-contract/one/v1/support-services.js'; const checkupUsage = 'Usage: vigilbase cf checkup [status|start|progress <run-id>|result <run-id>] [--customer-id …] [--account-id …] [--json]'; export const CLOUDFLARE_HELP = `Usage: vigilbase cf <command> [options] Alias: vigilbase cloudflare Inventory and workspace: zones List zones (default) --customer-id --account-id --zone-id zone <zone-id> Zone detail; --customer-id for live details, optional --account-id accounts List accessible accounts --customer-id --account-id account <account-id> Stored account detail; --customer-id workspace [section] Workspace bootstrap or one section --customer-id --account-id --zone-id Sections: overview, reports, zones, rule-analyzer, accounts, checkups, settings Zone reads (--customer-id <uuid> required; IDs can use --zone-id): dns <zone-id> DNS records, TTL and proxy state; every page unless --limit 1..1000 or --cursor waf <zone-id> WAF rules, expressions, analytics and suggestions speed-settings <zone-id> Performance settings (internal users only) Account reads (optional --customer-id; IDs can use --account-id): audit-logs <account-id> Latest provider audit events (up to 100) Needs service-read permission. zero-trust <account-id> Users, Access applications, tunnels and authentication analytics developer-platform <account-id> Workers, Pages and 24-hour usage; --customer-id required; service-read magic-transit <account-id> Prefixes, routes and traffic analytics Zero Trust and Magic Transit require deployment-read permission. Analytics and checkups: analytics --customer-id <uuid> [--account-id <id> | --zone-id <id>] [--days 1..30] Default 7 days; live zone analytics uses the most recent 23 hours. checkup [status] Latest completed checkup --customer-id --account-id checkup start Start and persist a scan --customer-id --account-id checkup progress <run-uuid> Read saved progress once checkup result <run-uuid> Read the stored Cloudflare checkup result checkups aliases checkup; list/show alias status; run aliases start. Common options: --json, --one-url <origin>, --one-api-url <url>, --timeout <milliseconds>, --help dns, checkup status and checkup result call One's v1 API (https://api.vigilbase.com/one/v1); the rest call One (--one-url). Customer IDs are UUIDs; account and zone IDs are 32 hexadecimal characters. One login, tenant bindings and permissions apply to every command. Checkup start creates a scan run. These commands do not edit provider configuration. See CLOUDFLARE.md for full grammar, API mapping, data limits and examples.`; function validate(schema, input) { const result = schema.safeParse(input); if (!result.success) throw new InvalidArgumentError(result.error.issues.map((issue) => issue.message).join(' ')); return result.data; } function dataOf(payload) { return asRecord(payload.data) ?? payload; } function writeLine(ctx, value) { // DNS contents, rule expressions, and evidence can contain terminal controls. ctx.writer.stdout(value.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')); } function fields(ctx, data) { for (const [key, value] of Object.entries(data)) { if (value === undefined || value === null) continue; writeLine(ctx, `${key.padEnd(20)} ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`); } } /** * Text output of the checkup commands. On a terminal with colour (stdout a * TTY, TERM not dumb, NO_COLOR and FORCE_COLOR=0 unset, not CI), lines carry * the palette's SGR styles and are written to stdout directly; everywhere * else they go through the writer as plain text. Every payload string in a * line was sanitised when it was read, so the only escape sequences a line * can hold are the palette's own styles; a line with anything else is * written plain. */ function checkupOutput(ctx) { const stream = ctx.stdoutStream; const terminal = ctx.mode === 'text' && stream?.isTTY === true && (ctx.env.TERM ?? '').toLowerCase() !== 'dumb'; const color = terminal && shouldUseColor(stream, ctx.env); const width = Math.floor(Number(stream?.columns) || 0); const palette = { style: createStyles(color), // Plain output keeps the Unicode symbols, like the CLI's other plain lines; legacy consoles get ASCII. symbols: terminal && !supportsUnicode(ctx.env) ? ASCII_SYMBOLS : UNICODE_SYMBOLS, color, columns: terminal ? (width > 0 ? Math.max(40, width) : 80) : null, }; return { palette, line: (text = '') => { const visible = stripAnsi(text); const styledOnly = !/\u001b(?!\[[0-9;]*m)/.test(text) && sanitizeTerminal(visible) === visible; if (color && stream && styledOnly) stream.write(`${text}\n`); else writeLine(ctx, visible); }, }; } /** `grade D 47`, the server's grade in its band's colour. */ function gradeLine(palette, grade, score) { const scoreText = typeof score === 'number' || typeof score === 'string' ? singleLine(String(score), 10) : ''; return `grade ${styleGrade(palette.style, singleLine(String(grade), 3))}${scoreText ? ` ${scoreText}` : ''}`; } const FULL_DATA_HINT = 'For every check and field, add --json.'; function zones(ctx, values) { const items = asArray(values).map(asRecord).filter((item) => item !== null); if (!items.length) writeLine(ctx, 'No Cloudflare zones.'); for (const zone of items) { const plan = zone.planName ?? zone.plan_name ?? asRecord(zone.plan)?.name; writeLine(ctx, `${String(zone.id ?? zone.zone_id)} ${String(zone.name ?? zone.zone_name).padEnd(28)} ${String(zone.status ?? '-')}${plan ? ` ${String(plan)}` : ''}`); } } export const handleCloudflare = async (ctx) => { assertCommandFlags(ctx, ['customer-id', 'account-id', 'zone-id', 'days', 'limit', 'cursor']); const subcommand = (ctx.rest[0] ?? 'zones').toLowerCase(); for (const name of ['limit', 'cursor']) { if (ctx.values[name] !== undefined && subcommand !== 'dns') throw new Error(`--${name} is not supported for this cf command; only cf dns takes --limit and --cursor.`); } const scope = validate(cloudflareScopeSchema, { customerId: ctx.values['customer-id'], accountId: ctx.values['account-id'], zoneId: ctx.values['zone-id'], }); if (ctx.values.days !== undefined && subcommand !== 'analytics') throw new Error('--days is supported only by cf analytics.'); if (scope.accountId && ['dns', 'waf', 'speed-settings'].includes(subcommand)) throw new Error(`cf ${subcommand} accepts a zone ID and --customer-id; --account-id is not supported.`); if (scope.zoneId && ['accounts', 'account', ...accountResourceSchema.options, 'checkup', 'checkups'].includes(subcommand)) throw new Error(`cf ${subcommand} does not support --zone-id.`); const args = ctx.rest.slice(1); const noExtraArgs = (count, message = `Unexpected arguments. Run \`vigilbase ${ctx.command} --help\` for usage.`) => { if (args.length > count) throw new Error(message); }; const emit = (payload, render) => { if (payload.success === false) throw new Error('Cloudflare request failed.'); if (ctx.mode === 'json') outputJson(ctx, payload); else render(dataOf(payload)); return ok(); }; // Validate commands before requesting credentials or making API calls. if (!['zones', 'zone', 'accounts', 'workspace', 'dns', 'waf', 'speed-settings', 'account', ...accountResourceSchema.options, 'analytics', 'checkup', 'checkups'].includes(subcommand)) { throw unknownSubcommand(ctx.command, ctx.rest[0] ?? ''); } let zoneId; let accountId; const accountResource = accountResourceSchema.safeParse(subcommand); if (accountResource.success || subcommand === 'account') { noExtraArgs(1); if (args[0] && scope.accountId && args[0] !== scope.accountId) throw new Error('The positional account ID and --account-id must match.'); accountId = args[0] ?? scope.accountId; if (!accountId) throw new Error(`Missing <account-id>. Usage: vigilbase cf ${subcommand} <account-id> [--customer-id <uuid>] [--json]`); validate(cloudflareScopeSchema, { accountId }); if (subcommand === 'developer-platform' && !scope.customerId) throw new Error('cf developer-platform requires --customer-id <uuid>. Find it with `vigilbase cf accounts --json`.'); } else if (['dns', 'waf', 'zone', 'speed-settings'].includes(subcommand)) { noExtraArgs(1); if (args[0] && scope.zoneId && args[0] !== scope.zoneId) throw new Error('The positional zone ID and --zone-id must match.'); zoneId = args[0] ?? scope.zoneId; // Preserve the historical `cf zone` alias for the zone inventory. if (subcommand !== 'zone' && !zoneId) throw new Error(`Missing <zone-id>. Usage: vigilbase cf ${subcommand} <zone-id> --customer-id <uuid> [--json]`); if (zoneId) validate(cloudflareScopeSchema, { zoneId }); // One answers 400 to every caller that leaves the customer out of a zone read. if (subcommand !== 'zone' && !scope.customerId) throw new Error(`cf ${subcommand} requires --customer-id <uuid>. Find it with \`vigilbase cf accounts --json\`.`); } else if (!['workspace', 'checkup', 'checkups'].includes(subcommand)) { noExtraArgs(0); } const section = subcommand === 'workspace' ? (noExtraArgs(1), oneOf('Workspace section', workspaceSectionSchema.options, args[0])) : undefined; let days = 7; if (subcommand === 'analytics') { if (!scope.customerId) throw new Error('Cloudflare analytics requires --customer-id <uuid>. Find it with `vigilbase cf accounts --json`.'); if (scope.zoneId && scope.accountId) throw new Error('Choose either --zone-id or --account-id for analytics.'); const raw = ctx.values.days ?? '7'; if (!/^\d+$/.test(raw)) throw new InvalidArgumentError('--days must be an integer.'); days = inRange('--days', Number(raw), 1, 30); } const action = (args[0] ?? 'status').toLowerCase(); let runId; if (subcommand === 'checkup' || subcommand === 'checkups') { if (['progress', 'result'].includes(action)) { noExtraArgs(2, checkupUsage); if (args[1] === undefined) throw new Error(`Missing <run-uuid>. Usage: vigilbase cf checkup ${action} <run-uuid> [--json]`); runId = validate(z.string().uuid('A checkup run UUID is required.'), args[1]); if (scope.customerId || scope.accountId) throw new Error(`cf checkup ${action} is scoped by run ID and does not accept --customer-id or --account-id.`); } else if (['status', 'list', 'show', 'start', 'run'].includes(action)) { noExtraArgs(1, checkupUsage); } else throw new Error(checkupUsage); } const one = await requireOneClient(ctx); const cloudflare = new CloudflareClient(one); if (subcommand === 'speed-settings') { const payload = await withSpinner(ctx, 'Loading Cloudflare speed settings', () => cloudflare.speedSettings(zoneId, scope.customerId)); return emit(payload, (data) => { if (!Object.keys(data).length) writeLine(ctx, 'No speed settings returned; provider availability or permissions may limit this view.'); else fields(ctx, data); }); } if (accountResource.success) { const payload = await withSpinner(ctx, `Loading Cloudflare ${subcommand}`, () => cloudflare.accountResource(accountResource.data, accountId, scope.customerId)); return emit(payload, (data) => { if (subcommand === 'audit-logs') { const logs = asArray(data.logs); if (!logs.length) writeLine(ctx, 'No audit logs returned; provider availability or permissions may limit this view.'); for (const raw of logs) { const log = asRecord(raw); if (!log) continue; const action = asRecord(log.action); const actor = asRecord(log.actor); const resource = asRecord(log.resource); writeLine(ctx, `${String(log.id ?? '-')} ${String(log.when ?? '-')} ${String(action?.type ?? '-')} ${action?.result === true ? 'success' : action?.result === false ? 'failed' : '-'} ${String(actor?.email ?? actor?.id ?? '-')} ${String(resource?.type ?? '-')} ${String(resource?.id ?? '-')}`); } } else fields(ctx, data); }); } if (subcommand === 'account') { const payload = await withSpinner(ctx, 'Loading Cloudflare account', () => cloudflare.workspace({ ...scope, accountId })); if (payload.success === false) return emit(payload, () => { }); const matches = asArray(dataOf(payload).accounts).map(asRecord).filter((item) => item?.id === accountId); if (!matches.length) throw new Error('Cloudflare account not found in the selected workspace.'); const customerIds = new Set(matches.map((item) => item?.customerId)); if (customerIds.size > 1) throw new Error('This Cloudflare account is linked to multiple customers. Specify --customer-id.'); const account = matches.find((item) => item?.status === 'active' || item?.status === 'trialing') ?? matches[0]; return emit({ success: true, data: account }, (data) => fields(ctx, data)); } if (subcommand === 'zones' || subcommand === 'zone') { if (zoneId && scope.customerId) { const payload = await withSpinner(ctx, 'Loading live Cloudflare zone', () => cloudflare.zoneDetail(scope.customerId, zoneId)); if (payload.success === false) return emit(payload, () => { }); const zone = dataOf(payload); if (zone.id !== zoneId) throw new Error('The server returned a different Cloudflare zone.'); if (scope.accountId && asRecord(zone.account)?.id !== scope.accountId) throw new Error('Cloudflare zone does not belong to the selected account.'); return emit(payload, (data) => fields(ctx, data)); } let payload = await withSpinner(ctx, 'Loading Cloudflare zones', () => scope.customerId || scope.accountId || scope.zoneId || zoneId ? cloudflare.workspace({ ...scope, zoneId: zoneId ?? scope.zoneId }, 'zones') : one.getCloudflareZones()); if (payload.success === false) return emit(payload, () => { }); if (scope.accountId || scope.zoneId) { const data = dataOf(payload); const selectedZones = asArray(data.zones).filter((raw) => { const zone = asRecord(raw); return zone && (!scope.accountId || (zone.accountId ?? zone.account_id ?? zone.cloudflare_account_id) === scope.accountId) && (!scope.zoneId || (zone.id ?? zone.zone_id) === scope.zoneId); }); payload = payload.data ? { ...payload, data: { ...data, zones: selectedZones } } : { ...payload, zones: selectedZones }; } if (zoneId) { const zone = asArray(dataOf(payload).zones).map(asRecord).find((item) => (item?.id ?? item?.zone_id) === zoneId); if (!zone) throw new Error('Cloudflare zone not found in the selected workspace.'); return emit({ success: true, data: zone }, (data) => fields(ctx, data)); } return emit(payload, (data) => zones(ctx, data.zones)); } if (subcommand === 'accounts' || subcommand === 'workspace') { let payload = await withSpinner(ctx, 'Loading Cloudflare workspace', () => cloudflare.workspace(scope, section)); if (subcommand === 'accounts' && scope.accountId) { const data = dataOf(payload); const accounts = asArray(data.accounts).filter((raw) => asRecord(raw)?.id === scope.accountId); payload = { ...payload, data: { ...data, accounts } }; } return emit(payload, (data) => { if (subcommand === 'accounts') { const accounts = asArray(data.accounts); if (!accounts.length) writeLine(ctx, 'No Cloudflare accounts.'); for (const raw of accounts) { const account = asRecord(raw); if (account) writeLine(ctx, `${String(account.id)} ${String(account.name).padEnd(28)} ${String(account.status)} ${String(account.zoneCount ?? 0)} zones${account.customerId ? ` customer ${String(account.customerId)}` : ''}`); } } else fields(ctx, data); }); } if (subcommand === 'dns') { // One v1 one.cloudflareDnsRecords.list; Cloudflare IDs are lower-case hex there. const limit = ctx.values.limit === undefined ? undefined : limitValue(ctx.values.limit, 50, 1000); const cursor = textValue('--cursor', ctx.values.cursor, 512); const page = await withSpinner(ctx, 'Loading Cloudflare DNS', () => listV1(one, listCloudflareDnsRecords, { params: { zoneId: zoneId.toLowerCase() }, query: { customerId: scope.customerId }, }, { limit, cursor, defaultScope: 'all' })); if (ctx.mode === 'json') { outputJson(ctx, page); return ok(); } if (!page.items.length) writeLine(ctx, 'No DNS records.'); for (const record of page.items) { writeLine(ctx, `${record.id} ${record.type.padEnd(6)} ${record.name.padEnd(28)} ${record.content} TTL ${record.ttl === 1 ? 'auto' : record.ttl} ${record.proxied ? 'proxied' : 'DNS only'}`); } // The cursor is bound to the zone and the customer. if (page.nextCursor) writeLine(ctx, moreCommand(['cf', 'dns', zoneId, '--customer-id', scope.customerId, ...flagArgs('--limit', limit)], page.nextCursor)); return ok(); } if (subcommand === 'waf') { const payload = await withSpinner(ctx, 'Loading Cloudflare WAF', () => cloudflare.zoneRecords('waf', zoneId, scope.customerId)); return emit(payload, (data) => { const records = asArray(data.rules); if (!records.length) writeLine(ctx, 'No WAF rules.'); for (const raw of records) { const record = asRecord(raw); if (!record) continue; writeLine(ctx, `${String(record.id)} ${String(record.action).padEnd(18)} ${record.paused ? 'paused' : 'active'} ${String(record.description ?? '')}`); const expression = asRecord(record.filter)?.expression; if (expression) writeLine(ctx, ` ${String(expression)}`); } writeLine(ctx, `Rule analytics: ${data.analyticsAvailable ? 'available' : 'unavailable'}`); for (const raw of asArray(data.suggestions)) { const suggestion = asRecord(raw); if (suggestion) writeLine(ctx, `[${String(suggestion.severity)}] ${String(suggestion.title)}: ${String(suggestion.recommendation)}`); } }); } if (subcommand === 'analytics') { const payload = await withSpinner(ctx, 'Loading Cloudflare analytics', () => cloudflare.analytics(scope, days)); return emit(payload, (data) => { if (scope.zoneId) writeLine(ctx, 'Live zone analytics use the most recent 23 hours; stored usage may cover less.'); fields(ctx, asRecord(data.analytics) ?? data); }); } if (action === 'progress') { const payload = await withSpinner(ctx, 'Loading Cloudflare checkup progress', () => cloudflare.checkupProgress(runId)); return emit(payload, (data) => { writeLine(ctx, `checkup ${String(data.status)} ${String(data.progressPct ?? 0)}%`); for (const raw of asArray(data.events)) { const event = asRecord(raw); if (event) writeLine(ctx, `${String(event.createdAt ?? '')} ${String(event.message ?? '')}`); } if (data.errorMessage) writeLine(ctx, `error ${String(data.errorMessage)}`); }); } if (action === 'result') { // One v1 one.toolRuns.get. const { body: run } = await withSpinner(ctx, 'Loading Cloudflare checkup result', () => one.callV1(getToolRun, { params: { runId: runId }, query: {} })); if (run.toolName !== 'cloudflare-checkup') throw new Error('This run is not a Cloudflare checkup.'); if (ctx.mode === 'json') { outputJson(ctx, run); return ok(); } const out = checkupOutput(ctx); out.line(`checkup ${singleLine(run.status, 40)}`); if (run.grade) out.line(gradeLine(out.palette, run.grade, run.gradeScore)); const view = readCheckupReport(run.results); if (!view) { if (run.errorMessage) out.line(`error ${singleLine(run.errorMessage)}`); out.line('No result is available yet.'); return ok(); } for (const line of checkupReportLines(out.palette, view)) out.line(line); out.line(); out.line(out.palette.style.dim(FULL_DATA_HINT)); return ok(); } const isStart = action === 'start' || action === 'run'; if (isStart) { const payload = await withSpinner(ctx, 'Starting Cloudflare checkup', () => cloudflare.checkup(scope, true)); return emit(payload, (data) => { writeLine(ctx, `started ${String(data.toolRunId ?? data.id ?? 'ok')} ${String(data.status ?? 'running')}`); }); } // One v1 one.cloudflareCheckups.get: the account, the latest completed run and any run in progress. const { body: status } = await withSpinner(ctx, 'Loading Cloudflare checkup', () => one.callV1(getCloudflareCheckupStatus, { query: { customerId: scope.customerId, accountId: scope.accountId?.toLowerCase() }, })); if (ctx.mode === 'json') { outputJson(ctx, status); return ok(); } const run = status.latestRun; // The status carries no results; the text report reads them from the run (one.toolRuns.get). // Reading the run can be refused when the status was not (staff naming a customer need admin:full for // one.toolRuns.get); the status is still shown, with one line saying the details are unavailable. let detail = null; let detailError = null; if (run) { try { detail = (await withSpinner(ctx, 'Loading Cloudflare checkup result', () => one.callV1(getToolRun, { params: { runId: run.id }, query: { customerId: scope.customerId } }))).body; } catch (error) { if (!(error instanceof VigilbaseApiError)) throw error; detailError = error; } } const out = checkupOutput(ctx); out.line(`checkup ${status.requiresSetup ? 'setup required' : singleLine(run?.status ?? 'no completed runs', 40)}`); const latestId = run ? singleLine(run.id, 80) : null; if (latestId) out.line(`run ${latestId}`); if (run?.grade) out.line(gradeLine(out.palette, run.grade, run.gradeScore)); const view = readCheckupReport(detail?.results); if (!view && status.account) out.line(`account ${singleLine(status.account.name ?? status.account.id, 80)}`); if (status.activeRun) out.line(`running ${singleLine(status.activeRun.id, 80)} ${singleLine(status.activeRun.status, 40)}`); if (detailError) out.line(`details unavailable (HTTP ${detailError.status}${detailError.code ? ` ${singleLine(detailError.code, 40)}` : ''}); the status above is complete`); const lines = view ? checkupReportLines(out.palette, view) : []; for (const line of lines) out.line(line); if (latestId || lines.length) out.line(); if (latestId) out.line(out.palette.style.dim(`Details: vigilbase cf checkup result ${latestId}`)); if (lines.length) out.line(out.palette.style.dim(FULL_DATA_HINT)); return ok(); };