Skip to content
These docs describe staging.zkao.io and the @zksecurity/zkao-cli@next release. For production, see docs.zkao.io.

TypeScript SDK

View .md

@zksecurity/zkao-sdk is a typed client for the zkao API. Its types are generated from the OpenAPI spec, so every request and response is checked at compile time. It runs on Node 18 or later and in any runtime with fetch.

Terminal window
npm install @zksecurity/zkao-sdk
import { ZkaoClient } from "@zksecurity/zkao-sdk";
const zkao = new ZkaoClient({
token: process.env.ZKAO_API_TOKEN!,
projectId: process.env.ZKAO_PROJECT_ID!,
});

A client is bound to one project. Every call is scoped to it.

Option Type Meaning
token string Project API token, zkao_proj_<keyId>_<secret>, or an organization token, zkao_org_<keyId>_<secret>. Required.
projectId string Id of the project to work on. A project token reaches only its own. Required.
baseUrl string API base URL, used exactly as given. Optional.
fetch typeof fetch Custom fetch, for tests or proxies. Optional.

The client picks its base URL in this order:

  1. The baseUrl option, used verbatim.
  2. The ZKAO_URL environment variable, normalized.
  3. Production, https://zkao.io/api/v1 (exported as DEFAULT_BASE_URL).

ZKAO_URL accepts a bare host, an origin, or a full API URL. A bare host gets https://, except localhost, which gets http://. /api/v1 is appended unless the value already ends in /api/v<n>. So staging.zkao.io becomes https://staging.zkao.io/api/v1. A plain http:// URL to a non-local host logs a warning, since the token would travel unencrypted.

Two helpers expose this logic:

Function Meaning
normalizeBaseUrl(value: string): string Turn a host, origin, or URL into a full API base URL. Throws on an empty or invalid value.
resolveBaseUrlFromEnv(env?): string | undefined Read and normalize ZKAO_URL, from env or process.env. Returns undefined when unset.

Every method returns a promise. A non-2xx response rejects with ZkaoApiError. The required token scope is noted where a method needs more than read. Each method links to its endpoint in the API reference.

Method Returns Meaning
getTokenInfo() TokenInfo The token’s kind, scopes, repository allowlist, expiry, spend limit, and its project and organization. API

The standalone getTokenInfo({ token, baseUrl?, fetch? }) does the same without a project id. Use it to find which project or organization a token belongs to. kind is "project" or "organization". For an organization token, project is null and organization names what it reaches.

ZkaoOrganizationClient is for an organization token. It takes organizationId instead of projectId, and the same baseUrl and fetch options.

import { ZkaoOrganizationClient, getTokenInfo } from "@zksecurity/zkao-sdk";
const token = process.env.ZKAO_API_TOKEN!;
const { organization } = await getTokenInfo({ token });
const org = new ZkaoOrganizationClient({ token, organizationId: organization.id });
const project = await org.createProject("widgets");
const repository = await org.connectRepository(project.id, { owner: "acme", name: "widget" });
const zkao = org.project(project.id);
await zkao.waitForRepositoryReady(repository.id);
Method Returns Meaning
listProjects(opts?) Paginated<Project> The organization’s projects. opts takes page and limit. API
createProject(name, description?) Project Create a project. Needs projects:write. API
updateProject(projectId, changes) Project Change name, description, or both. The slug does not change. Needs projects:write. API
connectRepository(projectId, { owner, name }) Repository Connect a GitHub repository to a project. Needs repositories:write. API
moveRepository(repositoryId, projectId) MoveRepositoryResult Move a repository to another project, with its scans and findings. Needs repositories:write. API
project(projectId) ZkaoClient A client for one project of the organization, with the same token.

A project token on these methods fails with 403. moveRepository fails with 409 while the repository has running scans, credits still to settle, or is still being analyzed. No token can manage members, create tokens, archive or delete projects, or buy credits.

Method Returns Meaning
listRepositories() Repository[] The project’s repositories, or the token’s allowlisted subset. API
waitForRepositoryReady(repositoryId, opts?) Repository Block until the repository’s readiness is ready. See Polling helpers.
Method Returns Meaning
getRepositoryGuidance(repositoryId) RepositoryGuidance Read a repository’s guidance. API
setRepositoryGuidance(repositoryId, content, opts?) SetGuidanceResult Set guidance, or clear it with null. Needs guidance:write. API

setRepositoryGuidance takes { expectedContent?: string | null }. Pass the content you last read, or null if it was cleared. The write then fails with 409 conflict if someone changed it in between. Writing the content already stored is a no-op that returns unchanged: true.

const current = await zkao.getRepositoryGuidance(repoId);
await zkao.setRepositoryGuidance(repoId, `${current.content ?? ""}\nNew note.`, {
expectedContent: current.content,
});
Method Returns Meaning
listAuditAreas(repositoryId, opts?) AuditAreaList A repository’s audit areas. opts.branch picks the branch whose map gives sizes. API
createAuditArea(repositoryId, name, description?) AuditArea Add a custom area. The key is derived from the name. Needs guidance:write. API
deleteAuditArea(repositoryId, areaKey) DeleteAuditAreaResult Delete a custom area. An area a scan’s map named is refused with 409. Needs guidance:write. API

A branch defaults to the repository’s default branch.

Method Returns Meaning
getContinuousTesting(repositoryId, opts?) ContinuousTesting A branch’s available and enabled analyses, schedule, spend and monthly budget bounds. opts.branch picks the branch. API
setContinuousTesting(repositoryId, body) ContinuousTesting Turn automatic analysis on or off, select analyses, or change the monthly budget or audit areas. Needs automations:write. API
removeContinuousTesting(repositoryId, opts?) RemoveContinuousTestingResult Remove a branch’s schedule. Scans it already ran are kept. Needs automations:write. API
prepareContinuousTesting(repositoryId, branch) { preparing: true } Plan the branch’s next analysis without running it, as Prepare next analysis does in the app. Spends no credits. Needs automations:write. API
listAgentQuestions() { questions: AgentQuestion[] } The open questions Continuous Security analyses asked the project’s members, oldest first. API
answerAgentQuestion(questionId, answer) { questionId, status } Answer with selectedOption, a note, or both. Needs guidance:write. API

availableFeatures lists the branch’s analysis IDs. Use enableFeatures to add analyses or enabledFeatures to replace the selection. Omitting both keeps the current selection. This example enables formal verification (FV) alongside the branch’s other analyses.

const schedule = await zkao.setContinuousTesting(repositoryId, {
branch: "main",
enabled: true,
monthlyBudgetCredits,
enableFeatures: ["formal-verification"],
});
console.log(schedule.enabled, schedule.enabledFeatures);

For FV alone, pass enabledFeatures: ["formal-verification"]. An existing schedule accepts a feature change at its current budget. areaKeys selects the audit areas that analyses rotate through. An empty areaKeys scans the whole repository every run.

selectedOption is the label of one of the question’s options. The analysis reads the answer in its next session. The answer counts as that of the member who created the token, who needs a project role of their own. A question that was already answered or dismissed fails with 409.

const { questions } = await zkao.listAgentQuestions();
for (const q of questions) console.log(q.id, q.text, q.options.map((o) => o.label));
await zkao.answerAgentQuestion(questionId, {
selectedOption: "<one of the labels>",
note: "Only the operator can call this.",
});
Method Returns Meaning
listScans(opts?) Paginated<Scan> Scans, most recent first. opts takes page and limit (max 100). API
getScan(scanId) ScanDetail One scan’s status and detail. API
launchScan(body) LaunchScanResult Launch a scan. Needs scans:launch. API
waitForScan(scanId, opts?) ScanDetail Block until the scan is COMPLETED, FAILED, or CANCELLED. See Polling helpers.
cancelScan(scanId) CancelScanResult Cancel a running or queued scan and release its unspent credits. Needs scans:launch. API
resumeTriage(scanId, body, opts) ResumeTriageResult Resume budget-stopped triage. Needs scans:launch. API
getTriageRun(scanId, runId) TriageRun Read a resumed triage run. API
waitForTriageRun(scanId, runId, opts?) TriageRun Wait for that run to reach a terminal status. Honors Retry-After.
publishScan(scanId, opts?) PublishArtifactResult Publish a completed scan as a public page. opts.withPassword adds a generated password. Needs publish. API

launchScan takes a LaunchScanRequest:

Field Meaning
repositoryId Repository to scan. Required.
creditBudget Maximum budget in credits. Omit it to use the budget zkao recommends.
presetRef Preset ref from listScanPresets(). Defaults to the first active preset.
branch Branch to scan. Ignored when commitHash is set.
commitHash Commit to scan.
commitMessage Commit message to record.
baseCommit Base commit, branch, or tag of a diff scan. Required by a diff preset, refused by others.
auditAreaKeys Area keys to scope the scan to. Omit to scan the whole repository.
guidance Guidance for this scan only, replacing the repository’s.

It resolves to { scanId, queued, creditBudget, buildsOverview }. buildsOverview is true when a diff scan also builds the repository’s overview, which raises its budget. See Scans and Diff scans.

getScan and waitForScan return a triage object. Check its status, untriagedCount, and resume before relying on results. Resumption takes body: { creditBudget } and opts: { idempotencyKey }. Reuse that key and budget when retrying the same request. The result is { run, replayed }.

waitForTriageRun accepts the same polling options as waitForScan. Its onPoll receives the triage run. The run reports budgetExhausted separately from status. The parent scan stays COMPLETED while resumed triage runs. Read the scan’s triage again afterward to check remaining work.

findingId accepts the full id or the ZK- label shown on the finding page.

Method Returns Meaning
listFindings(opts?) Paginated<Finding> Findings across the project. opts takes scanId, page, and limit. API
getFinding(findingId) FindingDetail Full finding text and notes. API
addFindingNote(findingId, content) { noteId, findingId } Add a comment. Needs findings:write. API
pinFindingNote(findingId, noteId, kind?) { findingId, noteId } Pin a note as the finding’s resolution note. kind is "resolution". Needs findings:write. API
setFindingSeverity(findingId, severity) { findingId, userSeverity, effectiveSeverity } Override severity, or clear the override with null. Needs findings:write. API
setFindingResolution(findingId, status, opts?) { findingId, resolutionStatus } Change the resolution status. Needs findings:write. API
overrideFindingTriage(findingId, triageStatus, opts?) FindingTriageResult Replace the AI triage verdict with CONFIRMED or FALSE_POSITIVE. Setting the AI’s own verdict again clears the override. opts.note is added as a comment. Needs findings:write. API
listFindingDetails(opts?) FindingDetailsPage Full text of many findings in one call. opts takes scanId, ids, page, and limit. API
publishFinding(findingId, opts?) PublishArtifactResult Publish a finding as a public page. opts takes noteId and withPassword. Needs publish. API

setFindingResolution takes { note?: ChangeNote; reason?: ResolutionReason }. note is { content } for a new comment or { existingNoteId } to reuse one. reason is a catalog code valid for the status. note wins when both are given. Both are ignored for NOT_STARTED and IN_PROGRESS. See Triage findings for the codes.

await zkao.setFindingResolution(findingId, "WONT_FIX", { reason: "risk_accepted" });
Method Returns Meaning
getRegressionTestReadiness(findingId) RegressionTestReadiness Check GitHub installation, permissions, and requester access. API
createRegressionTest(findingId, body, opts) CreateRegressionTestResult Request one paid attempt. body takes creditBudget and optional targetBranch. opts requires idempotencyKey. Needs regression-tests:write. API
listRegressionTests(findingId) RegressionTestRun[] List the latest attempts. API
getRegressionTest(findingId, runId) RegressionTestRun Follow one attempt and read its draft PR URL. API
retryRegressionTestPublication(findingId, runId) RegressionTestRun Retry opening the saved test’s PR without another generation budget. Needs regression-tests:write. API

Reuse the same request key, budget, and target branch after an uncertain launch response. The result’s replayed flag identifies an existing attempt. See Regression tests for permissions and validation outcomes.

Method Returns Meaning
listScanPresets() ScanPreset[] Presets the project can launch. Pass a ref as presetRef. API

Vulnerability reports researchers filed through GitHub’s private vulnerability reporting. intakeState says whether a report has been read and split into claims yet; an investigation waits for COMPLETE.

Method Returns Meaning
listReports(opts?) Paginated<Report> Reports, newest first. opts takes status, page, and limit. API
investigateReport(publicId) InvestigateReportResult Check a report’s claims against the code. Needs scans:launch. API

investigateReport checks each claim against the repository, deduplicates it against the findings already confirmed there, and writes a proof of concept where one can be written. It returns at once with the scan doing the work, so poll getScan and then read that scan’s findings.

It is idempotent: a report already under investigation comes back with the existing scan and claimsQueued: null, so a retry costs nothing.

const { scanId } = await zkao.investigateReport("REPORT-2026-0012");
await zkao.waitForScan(scanId);

A coordinated-disclosure advisory. publicId is the readable identifier, like ADVISORY-ADV-2026-0045.

An advisory makes two separate statements, and the difference matters. software is which repositories it is about, and it is what every notice is matched on: a contact is told only if they run something on that list. affected is the version ranges that carry the bug, and it is often empty because when a report arrives nobody yet knows which releases are involved.

Method Returns Meaning
listAdvisories(opts?) Paginated<Advisory> Advisories, newest first. opts takes status, page, and limit. API
getAdvisory(publicId) AdvisoryDetail The advisory, its software, its affected versions, and every planned notice. API
replaceAdvisoryAffected(publicId, affected) AdvisoryDetail Replace the affected version ranges. Needs advisories:write. API

replaceAdvisoryAffected is the one write worth putting in a release pipeline. A patch notice is held back until some range names the version that fixed the bug, and nothing but whatever cut the release knows it:

await zkao.replaceAdvisoryAffected("ADVISORY-ADV-2026-0045", [
{ repository: { owner: "acme", name: "libfoo" }, introducedIn: "1.0.0", fixedIn: "2.0.3" },
]);

It replaces the whole set, so send what is affected now rather than a patch. It records versions and nothing else: a range may name only software already on the advisory’s software, and anything else is a 400. Which software an advisory concerns decides who hears about it, so it is changed in the app, not from a token that records versions.

Reading an advisory also reports why a notice is held back. notices[].status is BLOCKED with a blockedReason when the plan is withholding one.

The teams running your software. Each contact records which of your repositories they run, which is what notices are matched on, and a tier saying how early they hear: EMBARGO first and alone, DOWNSTREAM once a patch exists, ANNOUNCE at public disclosure.

Method Returns Meaning
listAdvisoryContacts(opts?) Paginated<AdvisoryContact> The contact list, oldest first. opts takes tier, status, page, and limit. Needs contacts:read. API
addAdvisoryContact(contact) AdvisoryContact Put one address on the list. Needs contacts:write. API

software is required when adding one. A contact who runs nothing is told nothing, so an empty list is a 400 rather than a contact that sits silent.

await zkao.addAdvisoryContact({
organization: "Downstream Inc",
tier: "DOWNSTREAM",
software: [{ owner: "acme", name: "libfoo" }],
});

A new contact starts PENDING_VERIFICATION, and an unconfirmed address receives nothing embargoed. Nothing is emailed by this call: the confirmation mail is sent from the app.

The two contact scopes are separate from the rest on purpose. This list is who learns about a vulnerability before the public does, so read does not reach it and advisories:write cannot add to it.

The balance belongs to the project’s organization and is shared by all its projects. Usage and the monthly summary count only movements attributed to this project. See Credits.

Method Returns Meaning
getBillingBalance() BillingBalance balanceCredits, reservedCredits held by active scans, and availableCredits for new scans. API
getBillingUsage(opts?) BillingUsage Ledger movements with signed credits. opts takes from, to, and limit. Defaults to the last 30 days. API
getBillingSummary(opts?) UsageMonthSummary[] Credits spent and purchased per UTC month, newest first. opts.months sets how many. API

Scans take minutes, and a tight polling loop is rejected with 429. The helpers back off exponentially with jitter, honor the server’s Retry-After, and treat a 429 as a signal to slow down.

const { scanId } = await zkao.launchScan({ repositoryId, presetRef });
const scan = await zkao.waitForScan(scanId, {
onPoll: (s) => console.log(s.status),
});
if (scan.status !== "COMPLETED") throw new Error(`Scan ended ${scan.status}`);

waitForScan(scanId, opts) resolves with the final detail whatever the final status is.

Option Default Meaning
intervalMs 5000 First delay between polls. Grows by 1.5x each poll.
maxIntervalMs 30000 Cap on the delay.
timeoutMs 1 hour Give up and throw after this long.
signal none AbortSignal that stops the wait. Rejects with the abort reason.
onPoll none Called with the latest ScanDetail on each poll that is not final.

waitForRepositoryReady(repositoryId, opts) takes the same options except onPoll, with a default timeout of 30 minutes. It throws if the repository is not in the project or the token’s allowlist. Call it between adding a repository and launching its first scan.

isTerminalScanStatus(status) and TERMINAL_SCAN_STATUSES tell whether a status is final, for your own loops.

Every non-2xx response throws ZkaoApiError.

Property Meaning
status HTTP status.
code Machine-readable error code from the response, such as insufficient_credits.
message Human-readable message.
minimumCredits Set with budget_below_minimum: the smallest budget the launch accepts, in credits.

Branch on code, not on the message.

import { ZkaoApiError } from "@zksecurity/zkao-sdk";
try {
await zkao.launchScan({ repositoryId, presetRef });
} catch (err) {
if (err instanceof ZkaoApiError && err.code === "repository_initializing") {
await zkao.waitForRepositoryReady(repositoryId);
} else if (err instanceof ZkaoApiError && err.code === "insufficient_credits") {
console.error("Not enough credits for this budget.");
} else {
throw err;
}
}

The full list of codes is in API conventions. Timeouts and aborts in the polling helpers throw a plain Error, not ZkaoApiError.

The package exports a named type for each API object.

Type Meaning
Repository, RepositoryGuidance, SetGuidanceResult Repositories and their guidance.
Scan, ScanDetail, ScanStatus, ScanPreset Scans, their status, and presets.
LaunchScanRequest, LaunchScanResult, CancelScanResult Launch and cancel bodies and results.
Finding, FindingDetail, FindingNote, ChangeNote, FindingTriageResult Findings, their notes, and a triage override’s result.
ContinuousFeatureId, ContinuousTesting, SetContinuousTestingRequest, RemoveContinuousTestingResult, AgentQuestion Continuous Security analyses, schedules and questions.
Severity, ResolutionStatus, ResolutionReason, TriageStatus Finding enums.
PublishArtifactResult Result of publishing a scan or finding.
TokenInfo The calling token, with its project and organization.
Organization, Project, MoveRepositoryResult An organization, one of its projects, and the result of moving a repository.
BillingBalance, BillingUsage, UsageEvent, UsageEventType, BillingSummary, UsageMonthSummary Credit balance and ledger.
Paginated<T> { items, page, limit, total } for list endpoints.
ZkaoClientOptions, ZkaoOrganizationClientOptions, WaitForScanOptions, WaitForRepositoryReadyOptions Option objects.

The raw generated types are exported as components and paths. Any schema without a named export is available as components["schemas"]["<Name>"], for example components["schemas"]["AuditArea"].