UNPKG

@vigilbase/cli

Version:

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

237 lines (236 loc) • 11 kB
import { z } from 'zod'; import { SCAN_FAILED_MESSAGE, singleLine } from './format.js'; import { parseJsonResponse, requestText } from './network.js'; import { fetchSkillText } from './skill-fetch.js'; import { ApiCallError, callOperation, operationUrl } from '../vendor/api-contract/client/index.js'; import { executeAgentTool, getSecurityBadge, listAgentTools } from '../vendor/api-contract/tools/v1/operations.js'; import { getDocsPage, searchDocs } from '../vendor/api-contract/docs/v1/operations.js'; import { AGENT_API_ERROR_CODES, } from '../types.js'; import { docsApiUrl, toolsApiUrl } from './config.js'; export class VigilbaseApiError extends Error { status; body; retryAfterSec; code; /** The server's sanitised explanation, set only for known vigilbase.com problem errors. */ reason; /** CLI-authored remediation, never server text (see one-error-hints.ts). */ hint; /** * The message is the CLI's own text, never the server's, so formatError prints it although the * error carries a body. Unmarked errors with a body print only a generic `Request failed`. */ isCliAuthored; /** The One tool run a failed scan recorded. */ toolRunId; /** The `X-Request-Id` of a One v1 answer, for support. */ requestId; constructor(message, options) { super(message); this.name = 'VigilbaseApiError'; this.status = options.status; this.body = options.body; this.retryAfterSec = options.retryAfterSec; this.code = options.code; this.reason = options.reason; this.hint = options.hint; this.isCliAuthored = options.isCliAuthored ?? false; this.toolRunId = options.toolRunId; this.requestId = options.requestId; } } export function retryAfterSeconds(response, body) { const header = response.headers.get('retry-after'); if (header) { const parsed = Number.parseInt(header, 10); if (Number.isFinite(parsed) && parsed >= 0) return parsed; } if (body && typeof body === 'object' && 'retryAfterSec' in body && typeof body.retryAfterSec === 'number') { return body.retryAfterSec; } return undefined; } /** Longer messages are withheld rather than cut. */ const MAX_REASON_SOURCE_LENGTH = 1000; const problemSchema = z.object({ error: z.object({ code: z.unknown(), message: z.string().max(MAX_REASON_SOURCE_LENGTH) }), code: z.unknown(), }); /** * The reason a vigilbase.com problem+json error gives, when its code is one com sends. * Anything else stays redacted: other media types, unknown codes, odd messages. */ function problemReason(response, body) { const mediaType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase(); if (mediaType !== 'application/problem+json') return undefined; const problem = problemSchema.safeParse(body); if (!problem.success) return undefined; const code = z.enum(AGENT_API_ERROR_CODES).safeParse(problem.data.error.code ?? problem.data.code); if (!code.success) return undefined; const message = singleLine(problem.data.error.message); return message ? { code: code.data, message } : undefined; } /** `fallback` is the CLI's own message, used when com gave no reason it accepts. */ function publicApiError(fallback, response, body) { const reason = problemReason(response, body); return new VigilbaseApiError(reason?.message ?? fallback, { status: response.status, body, retryAfterSec: retryAfterSeconds(response, body), code: reason?.code, reason: reason?.message, isCliAuthored: !reason, }); } /** * A failed contract call as the CLI's error: the body as sent (only known * problem reasons are shown, see problemReason) and the response for Retry-After. */ function callError(fallback, error, response) { const body = error.body ?? undefined; if (response) return publicApiError(fallback, response, body); return new VigilbaseApiError(fallback, { status: error.status, body, isCliAuthored: true }); } const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** com's 422 for a scan the scanner could not assess (apps/com/lib/agent/handlers.ts): it still carries the result. */ const unassessedScanSchema = z.object({ success: z.literal(false), toolName: z.string(), target: z.string(), result: z.object({ status: z.literal('error') }).passthrough(), }); /** The Tools API catalog path, relative to `toolsApiUrl` (`servers[0]` of the Tools document). */ export const PUBLIC_TOOLS_PATH = listAgentTools.path; /** * The public Tools API client: typed calls of the operations declared in * `@vigilbase/api-contract` (vendored in src/vendor/api-contract), on * https://api.vigilbase.com/tools/v1 by default. * Vigilbase One authenticated calls use a separate client + device-auth tokens. */ export class VigilbaseClient { config; constructor(config) { this.config = config; } get baseUrl() { return toolsApiUrl(this.config); } /** * `fetch` for callOperation through the CLI's transport (timeouts, no * redirects, network errors). `last` keeps the response for Retry-After. */ transport(last) { return async (input, init) => { const headers = new Headers(init?.headers); headers.set('User-Agent', this.config.userAgent); const { response, text } = await requestText(this.config, String(input), { ...init, headers, option: '--base-url' }); last.response = response; // A body that is not JSON (an edge challenge page) must not reach the typed client as JSON. parseJsonResponse(response, text); return new Response(response.status === 204 || response.status === 304 ? null : text, { status: response.status, headers: response.headers }); }; } async listTools() { const last = {}; try { const { body } = await callOperation(listAgentTools, {}, { baseUrl: this.baseUrl, fetch: this.transport(last) }); return body; } catch (error) { if (!(error instanceof ApiCallError)) throw error; if (error.status < 400) throw new VigilbaseApiError('Invalid tool catalog response. Check the API URL or retry later.', { status: error.status }); throw callError(`Failed to list tools (HTTP ${error.status})`, error, last.response); } } async executeTool(toolName, target) { const last = {}; try { const { body } = await callOperation(executeAgentTool, { params: { toolName }, body: { target } }, { baseUrl: this.baseUrl, fetch: this.transport(last) }); return body; } catch (error) { if (error instanceof z.ZodError) throw new VigilbaseApiError('Invalid tool name or target.', { status: 400, isCliAuthored: true }); if (!(error instanceof ApiCallError)) throw error; if (error.status < 400) throw new VigilbaseApiError('Invalid tool execution response. Check the API URL or retry later.', { status: error.status }); if (error.status === 429) throw callError('Rate limit exceeded. Retry after the indicated delay.', error, last.response); if (error.status !== 422) throw callError(`Tool execution failed (HTTP ${error.status})`, error, last.response); const unassessed = unassessedScanSchema.safeParse(error.body); if (!unassessed.success) throw callError(SCAN_FAILED_MESSAGE, error, last.response); // A scan the scanner could not assess keeps its result, as One's route does. const { toolName: name, target: scanned, result } = unassessed.data; const toolRunId = typeof result.toolRunId === 'string' && UUID.test(result.toolRunId) ? result.toolRunId : undefined; return { success: false, toolName: name, target: scanned, grade: null, gradeScore: null, result, error: null, status: 422, code: 'scan_unassessed', ...(toolRunId ? { toolRunId } : {}), }; } } async fetchSkillMarkdown(skillUrl) { return fetchSkillText(this.config, skillUrl); } /** The Docs API base, or a CLI-authored error when `--base-url` names an origin that does not serve it. */ get docsBaseUrl() { const base = docsApiUrl(this.config); if (!base) { throw new VigilbaseApiError('The Docs API is served only on api.vigilbase.com. Run docs commands without --base-url.', { status: 400, isCliAuthored: true }); } return base; } /** Docs search (docs.search.query): anonymous, no credential or developer key is sent. */ async searchDocs(q, limit) { const base = this.docsBaseUrl; const last = {}; try { const { body } = await callOperation(searchDocs, { query: { q, limit } }, { baseUrl: base, fetch: this.transport(last) }); return body; } catch (error) { if (!(error instanceof ApiCallError)) throw error; if (error.status < 400) throw new VigilbaseApiError('Invalid docs search response. Retry later.', { status: error.status }); if (error.status === 429) throw callError('Docs rate limit exceeded. Retry after the indicated delay.', error, last.response); throw callError(`Docs search failed (HTTP ${error.status})`, error, last.response); } } /** One docs page as Markdown (docs.pages.get): anonymous. */ async getDocsPage(path) { const base = this.docsBaseUrl; const last = {}; try { const { body } = await callOperation(getDocsPage, { query: { path } }, { baseUrl: base, fetch: this.transport(last) }); return body; } catch (error) { if (!(error instanceof ApiCallError)) throw error; if (error.status < 400) throw new VigilbaseApiError('Invalid docs page response. Retry later.', { status: error.status }); if (error.status === 404) throw callError(`No docs page at "${path}". Find one with \`vigilbase docs search <words>\`.`, error, last.response); if (error.status === 429) throw callError('Docs rate limit exceeded. Retry after the indicated delay.', error, last.response); throw callError(`Docs page request failed (HTTP ${error.status})`, error, last.response); } } badgeUrl(domain, style = 'default') { return operationUrl(getSecurityBadge, { params: { domain }, query: style === 'default' ? {} : { style } }, this.baseUrl); } }