UNPKG

@vigilbase/cli

Version:

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

292 lines (291 loc) • 17.1 kB
import { z } from 'zod'; import { executeOneOperation, formatOnePayload } from '../lib/one-operations.js'; import { listV1 } from '../lib/one-v1.js'; import { getCustomer, listCustomers } from '../vendor/api-contract/one/v1/customers.js'; import { getCustomerOrganization, listCustomerContacts, listCustomerEndpoints, listCustomerServices } from '../vendor/api-contract/one/v1/customer-records.js'; import { getMonitoringHistory, getMonitoringMetrics, getMonitoringStatus, listMonitoringTargets, listWatchdogScans, listWatchdogTargets } from '../vendor/api-contract/one/v1/monitoring.js'; import { getCustomerBilling, getReconReport, listContracts, listInvoices, listReconReports, listSubscriptions } from '../vendor/api-contract/one/v1/reports-billing.js'; import { listSupportTickets } from '../vendor/api-contract/one/v1/support-services.js'; import { assertCommandFlags, ok, outputJson, requireOneClient, withSpinner } from './helpers.js'; import { InvalidArgumentError, inRange, isoDateTime, missingArguments, oneOf, textValue, unknownSubcommand } from './legacy-validation.js'; const regions = ['ams', 'nyc', 'lon', 'sgp', 'iad', 'sfo', 'fra', 'dub', 'tok', 'syd', 'cpt', 'gru', 'dxb', 'ewr', 'lhr', 'jnb', 'atl', 'blr', 'bom', 'cdg', 'del', 'dfw', 'hnl', 'icn', 'itm', 'lax', 'mad', 'man', 'mel', 'mex', 'mia', 'mxp', 'nrt', 'ord', 'sao', 'scl', 'sea', 'sjc', 'sto', 'tlv', 'waw', 'yto']; function flag(ctx, name, max = 2048) { const value = ctx.values[name]; return value === undefined ? undefined : textValue(`--${name}`, String(value), max); } function integer(ctx, name, min, max) { const value = flag(ctx, name); if (value === undefined) return undefined; if (!/^\d+$/.test(value)) throw new InvalidArgumentError(`--${name} must be an integer.`); return inRange(`--${name}`, Number(value), min, max); } function uuid(value) { const result = z.string().uuid().safeParse(value); if (!result.success) throw new Error('A valid UUID is required. Copy the full customer, target, or report ID from its list command.'); return result.data; } function identifier(value) { const result = z.string().trim().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/).safeParse(value); if (!result.success) throw new Error('An ID containing only letters, numbers, underscores, or hyphens is required.'); return result.data; } const customerSubcommands = ['show', 'summary', 'services', 'endpoints', 'contacts', 'organization', 'watchdog-targets', 'watchdog-scans', 'reports', 'investigations', 'contracts', 'billing', 'invoices', 'subscriptions', 'projects']; /** Positional placeholders of each subcommand (as in ONE_HELP), so a missing argument is named. */ const POSITIONALS = { customers: { ...Object.fromEntries(customerSubcommands.map((command) => [command, '<customer-id>'])), report: '<customer-id> <report-id>', investigation: '<customer-id> <investigation-id>', }, orgs: { show: '<organization-id>' }, monitoring: { metrics: '<target-id>...', targets: '<customer-id>', status: '<customer-id>', history: '<customer-id>' }, }; function positionalUsage(ctx) { const [command] = ctx.rest; const placeholders = POSITIONALS[ctx.command]; if (command === undefined || !placeholders || !Object.hasOwn(placeholders, command)) return undefined; return `vigilbase ${ctx.command} ${command} ${placeholders[command]}`; } function check(ctx, arity, flags = []) { if (ctx.rest.length < arity) throw new Error(missingArguments(ctx.command, arity - ctx.rest.length, positionalUsage(ctx))); if (ctx.rest.length > arity) throw new Error(`Unexpected arguments. Run \`vigilbase ${ctx.command} --help\` for usage.`); assertCommandFlags(ctx, flags); } /** --limit for v1 lists: items across pages (each page asks for at most what the operation allows). */ const MAX_LIMIT = 1000; const PAGE_FLAGS = ['limit', 'cursor']; function pageSelection(ctx, defaultScope) { return { limit: integer(ctx, 'limit', 1, MAX_LIMIT), cursor: flag(ctx, 'cursor', 512), defaultScope }; } const optionalUuid = (ctx, name) => ctx.values[name] === undefined ? undefined : uuid(ctx.values[name]); export function buildOneOperation(ctx) { const command = ctx.rest[0] ?? (ctx.command === 'monitoring' ? 'health' : ctx.command === 'support' ? 'tickets' : 'list'); const label = `${ctx.command} ${command}`; const operation = (path, query) => ({ kind: 'legacy', label, operation: { path, query, label } }); const v1 = (op, run) => ({ kind: 'v1', label, operationId: op.id, run }); if (ctx.command === 'customers') { if (command === 'list' || command === 'ls') { check(ctx, ctx.rest.length === 0 ? 0 : 1, PAGE_FLAGS); const page = pageSelection(ctx, 'all'); return v1(listCustomers, (client) => listV1(client, listCustomers, { query: {} }, page)); } if (command === 'show' || command === 'summary') { check(ctx, 2); const customerId = uuid(ctx.rest[1]); return v1(getCustomer, async (client) => (await client.callV1(getCustomer, { params: { customerId } })).body); } if (command === 'organization' || command === 'billing') { check(ctx, 2); const customerId = uuid(ctx.rest[1]); const op = command === 'organization' ? getCustomerOrganization : getCustomerBilling; return v1(op, async (client) => (await client.callV1(op, { params: { customerId } })).body); } // Lists that used to answer every row follow nextCursor to the end unless --limit or --cursor is given. const allLists = { services: listCustomerServices, endpoints: listCustomerEndpoints, contacts: listCustomerContacts, 'watchdog-targets': listWatchdogTargets, subscriptions: listSubscriptions, }; if (Object.hasOwn(allLists, command)) { check(ctx, 2, PAGE_FLAGS); const customerId = uuid(ctx.rest[1]); const page = pageSelection(ctx, 'all'); const op = allLists[command]; return v1(op, (client) => listV1(client, op, { params: { customerId }, query: {} }, page)); } if (command === 'projects') { check(ctx, 2); return operation(`/api/customers/${uuid(ctx.rest[1])}/projects`); } if (command === 'watchdog-scans') { check(ctx, 2, [...PAGE_FLAGS, 'target-id']); const customerId = uuid(ctx.rest[1]); const page = pageSelection(ctx, 'page'); const targetId = optionalUuid(ctx, 'target-id'); return v1(listWatchdogScans, (client) => listV1(client, listWatchdogScans, { params: { customerId }, query: { targetId } }, page)); } if (command === 'reports') { check(ctx, 2, PAGE_FLAGS); const customerId = uuid(ctx.rest[1]); const page = pageSelection(ctx, 'page'); return v1(listReconReports, (client) => listV1(client, listReconReports, { params: { customerId }, query: {} }, page)); } if (command === 'report') { check(ctx, 3); const customerId = uuid(ctx.rest[1]), reportId = uuid(ctx.rest[2]); return v1(getReconReport, async (client) => (await client.callV1(getReconReport, { params: { customerId, reportId } })).body); } if (command === 'investigations') { check(ctx, 2, ['limit', 'cursor', 'before', 'issue-id']); const before = flag(ctx, 'before'); const cursor = flag(ctx, 'cursor', 512); if (before && cursor) throw new Error('--before and --cursor are mutually exclusive.'); if (before) isoDateTime('--before', before); return operation(`/api/customers/${uuid(ctx.rest[1])}/vigil/investigations`, { limit: integer(ctx, 'limit', 1, 100), cursor, before, issueId: flag(ctx, 'issue-id', 256), }); } if (command === 'investigation') { check(ctx, 3, ['revision']); return operation(`/api/customers/${uuid(ctx.rest[1])}/vigil/investigations/${uuid(ctx.rest[2])}`, { revision: integer(ctx, 'revision', 1, 2_147_483_647) }); } if (command === 'contracts') { check(ctx, 2, [...PAGE_FLAGS, 'status']); const customerId = uuid(ctx.rest[1]); const status = oneOf('--status', ['draft', 'pending', 'active', 'expired', 'terminated'], flag(ctx, 'status')); const page = pageSelection(ctx, 'all'); return v1(listContracts, (client) => listV1(client, listContracts, { params: { customerId }, query: { status } }, page)); } if (command === 'invoices') { check(ctx, 2, [...PAGE_FLAGS, 'status']); const customerId = uuid(ctx.rest[1]); const status = oneOf('--status', ['draft', 'open', 'paid', 'uncollectible', 'void'], flag(ctx, 'status')); const page = pageSelection(ctx, 'page'); return v1(listInvoices, (client) => listV1(client, listInvoices, { params: { customerId }, query: { status } }, page)); } } if (ctx.command === 'orgs') { if (command === 'list' || command === 'ls') { check(ctx, ctx.rest.length === 0 ? 0 : 1); return operation('/api/user/organizations'); } if (command === 'show') { check(ctx, 2); return operation(`/api/organizations/${identifier(ctx.rest[1])}`); } if (command === 'roles') { check(ctx, 1); return operation('/api/auth/orgs/permission-roles'); } if (command === 'members') { check(ctx, ctx.rest[1] === undefined ? 1 : 2); return operation(ctx.rest[1] === undefined ? '/api/auth/orgs/members' : `/api/organizations/${identifier(ctx.rest[1])}/members`); } } if (ctx.command === 'monitoring') { const fleetRoutes = { health: '/api/monitoring/health', probes: '/api/monitoring/probes', 'probe-health': '/api/monitoring/probes/health' }; if (Object.hasOwn(fleetRoutes, command)) { check(ctx, ctx.rest.length === 0 ? 0 : 1); return operation(fleetRoutes[command]); } if (command === 'metrics') { check(ctx, Math.max(ctx.rest.length, 2)); const ids = ctx.rest.slice(1).map(uuid); if (ids.length > 50) throw new Error('monitoring metrics accepts at most 50 target IDs.'); const targetIds = [...new Set(ids)]; return v1(getMonitoringMetrics, async (client) => (await client.callV1(getMonitoringMetrics, { query: { targetIds } })).body); } if (command === 'targets') { check(ctx, 2, PAGE_FLAGS); const customerId = uuid(ctx.rest[1]); const page = pageSelection(ctx, 'all'); return v1(listMonitoringTargets, (client) => listV1(client, listMonitoringTargets, { params: { customerId }, query: {} }, page)); } if (command === 'status') { check(ctx, 2, ['isLight']); const customerId = uuid(ctx.rest[1]); const light = ctx.values.isLight ? 'true' : undefined; return v1(getMonitoringStatus, async (client) => (await client.callV1(getMonitoringStatus, { params: { customerId }, query: { light } })).body); } if (command === 'history') { check(ctx, 2, ['range', 'region', 'target-id']); const customerId = uuid(ctx.rest[1]); const query = { range: oneOf('--range', ['24h', '7d', '30d'], flag(ctx, 'range')), region: oneOf('--region', regions, flag(ctx, 'region')), targetId: optionalUuid(ctx, 'target-id'), }; return v1(getMonitoringHistory, async (client) => (await client.callV1(getMonitoringHistory, { params: { customerId }, query })).body); } } if (ctx.command === 'support' && command === 'tickets') { check(ctx, ctx.rest.length === 0 ? 0 : 1, ['isAll', ...PAGE_FLAGS, 'customer-id']); const query = { includeClosed: ctx.values.isAll ? 'true' : undefined, customerId: optionalUuid(ctx, 'customer-id') }; const page = pageSelection(ctx, 'page'); return v1(listSupportTickets, (client) => listV1(client, listSupportTickets, { query }, page)); } throw unknownSubcommand(ctx.command, command); } export const handleOne = async (ctx) => { const built = buildOneOperation(ctx); const client = await requireOneClient(ctx); const payload = await withSpinner(ctx, `Loading ${built.label}`, () => built.kind === 'v1' ? built.run(client) : executeOneOperation(client, built.operation)); if (ctx.mode === 'json') outputJson(ctx, payload); else { ctx.writer.stdout(built.label); for (const line of formatOnePayload(payload)) ctx.writer.stdout(line); } return ok(); }; export const ONE_HELP = { customers: `Usage: vigilbase customers <command> [--json] list List visible customers (also the default) show <customer-id> Customer details and service counts summary <customer-id> Alias of show services <customer-id> Service records endpoints <customer-id> Endpoint inventory contacts <customer-id> Customer contacts organization <customer-id> Organization linkage watchdog-targets <customer-id> Security/uptime targets watchdog-scans <customer-id> --target-id UUID; one page unless --limit reports <customer-id> Recon reports; one page unless --limit report <customer-id> <report-id> Recon report detail investigations <customer-id> --limit 1..100 --issue-id TEXT --cursor TEXT or --before ISO investigation <customer-id> <id> --revision 1..2147483647 contracts <customer-id> --status <status>, one of draft, pending, active, expired, terminated billing <customer-id> Billing overview invoices <customer-id> --status <status>, one of draft, open, paid, uncollectible, void; one page unless --limit subscriptions <customer-id> Stripe subscriptions projects <customer-id> Linked projects (internal operators) Lists answer { items, nextCursor }. --limit 1..1000 reads pages until it has that many items; --cursor <cursor> reads one page from a nextCursor. Without either, list, services, endpoints, contacts, watchdog-targets, contracts and subscriptions read every page. Customer, target, report, and investigation IDs must be UUIDs. Investigations require internal Vigil access. Every command but investigations and projects calls One's v1 API (https://api.vigilbase.com/one/v1, or --one-api-url); those two call One. All operations use your One login and the API's customer/partner permissions. See ONE.md for API mappings and examples.`, orgs: `Usage: vigilbase orgs <command> [--json] list Your organizations (also the default) show <organization-id> Organization details (internal read:admin) members Current organization's members members <org-id> Another organization's members (internal read:admin) roles Current organization's assignable role templates Roles require organization management access. Organization IDs may be opaque IDs. These commands read organization context; they do not switch the active organization.`, monitoring: `Usage: vigilbase monitoring <command> [--json] health Metrics backend and alerting readiness (also the default) probes Registered probe heartbeats (internal operators) probe-health Live probe health, with database fallback metrics <target-id>... Metrics for 1..50 target UUIDs targets <customer-id> Customer's monitoring targets (every page unless --limit 1..1000 or --cursor) status <customer-id> Current status; --light skips latency/SSL provider reads history <customer-id> --range 24h|7d|30d --region CODE --target-id UUID All operations require read:monitoring and the API's tenant access checks. History defaults to 7d. Health metadata preserves unknown, partial, and unavailable states. metrics, targets, status and history call One's v1 API; health, probes and probe-health call One.`, support: `Usage: vigilbase support tickets [--all] [--limit 1..1000] [--cursor <cursor>] [--customer-id <uuid>] [--json] Lists current organization's open tickets; --all includes closed tickets. Vigilbase staff must choose the customer with --customer-id. One page of 50 by default (at most the newest 100 tickets). Requires support:access and a linked Pylon account. Calls One's v1 API (one.supportTickets.list).`, };