Eventos e SDK
SDK JavaScript
Um cliente tipado e leve para Node.js 18+, Deno e Bun. Sem dependências: usa o fetch nativo e o Web Crypto.
@scanverra/sdk está em prévia e a interface ainda pode mudar. Cada chamada é uma requisição HTTP comum, então as páginas da API mostram como fazer sem ele.Instalação
Crie um cliente e reutilize.
npm install @scanverra/sdk
import { Scanverra } from "@scanverra/sdk";
const scanverra = new Scanverra({
apiKey: process.env.SCANVERRA_API_KEY,
// baseUrl: "https://www.scanverra.com", // optional
// timeoutMs: 300_000, // optional, per request
});Rodar verificações
scans.audit() e scans.repo() respondem com o relatório pronto. As outras respondem na hora com um id; wait() consulta até o relatório ficar pronto e lança um erro se a verificação falhou.
// Answers with the finished report
const audit = await scanverra.scans.audit({ url: "https://example.com" });
// Answer with an id; wait() polls until the report is ready
const { scanId } = await scanverra.scans.security({ url: "https://example.com" });
const security = await scanverra.wait("security", scanId);
const { testId } = await scanverra.scans.browser({ url: "https://example.com" });
const browser = await scanverra.wait("browser", testId, { intervalMs: 5000 });
// Repo scans: owner and repo of a connected account
const repo = await scanverra.scans.repo({ owner: "acme", repo: "storefront", async: true });
const repoReport = await scanverra.wait("repo", repo.scanId);Ler propriedades
Pontuações, problemas unificados e próximos passos de cada produto.
const { properties } = await scanverra.properties.list();
for (const p of properties) console.log(p.name, p.score, p.openTasks);
const detail = await scanverra.properties.get(properties[0].id);
const critical = detail.issues.filter((i) => i.severity === "critical");Assinar eventos
Crie um REST hook para qualquer evento e confira a assinatura de cada entrega com verifyWebhook. Entregas com mais de cinco minutos são recusadas.
const hook = await scanverra.hooks.create({
event: "remediation.task_created",
url: "https://hooks.example.com/scanverra",
});
// Store hook.secret: it is shown only once.
// In your receiver, with the raw request body:
import { verifyWebhook } from "@scanverra/sdk";
const ok = await verifyWebhook({
secret: process.env.SCANVERRA_HOOK_SECRET,
body: rawBody,
timestamp: req.headers["x-scanverra-timestamp"],
signature: req.headers["x-scanverra-signature"],
});
if (!ok) return res.status(401).end();Erros
Qualquer falha lança ScanverraError com status, code, uma message legível e o body da resposta. Quando nenhuma resposta chega, status é 0 e code é network_error ou timeout.
import { ScanverraError } from "@scanverra/sdk";
try {
await scanverra.scans.audit({ url: "https://example.com" });
} catch (err) {
if (!(err instanceof ScanverraError)) throw err;
if (err.code === "SCAN_COOLDOWN") console.log("Try again later:", err.message);
else if (err.status === 0 || err.status >= 500) console.log("Retry with backoff:", err.code ?? err.status);
else throw err; // 4xx: fix the request (see /docs/errors)
}Referência
| Campo | Descrição |
|---|---|
scans.audit(body)Promise<report>Opcional | Roda uma auditoria de site e retorna o relatório. Com async: true você recebe reportId na hora. |
scans.security(body)Promise<{ scanId }>Opcional | Inicia uma verificação de segurança. |
scans.browser(body)Promise<{ testId }>Opcional | Inicia uma auditoria de navegador. Com credentialId você testa páginas com login. |
scans.seo(body)Promise<{ scanId }>Opcional | Inicia uma análise de SEO. |
scans.repo(body)Promise<{ scanId }>Opcional | Verifica um repositório conectado. |
results.<tool>(id)Promise<ScanResult>Opcional | Lê uma verificação pelo id: audit, security, browser, seo ou repo. |
wait(tool, id, options?)Promise<ScanResult>Opcional | Consulta o método results da ferramenta até a verificação terminar. Opções: intervalMs (4000), timeoutMs (600000). |
properties.list() / get(id)Promise<...>Opcional | Lista as propriedades ou lê uma com os problemas e próximos passos. |
hooks.list() / create() / delete(id) / sample(event)Promise<...>Opcional | Gerencia os REST hooks. create() retorna o segredo de assinatura uma única vez. |
verifyWebhook(input)Promise<boolean>Opcional | Confere X-Scanverra-Signature com o corpo bruto e o carimbo de data e hora. |