---
title: API reference
crumb: API reference
eyebrow: Reference · @clearedby/sdk and HTTP
h1: Every SDK method and every endpoint a partner uses.
description: The @clearedby/sdk reference (ClearedBy, ClearedByPartner, the /dispatch, /receipt, /partner-proxy and /doctor subpaths) with signatures and examples, plus the HTTP reference with auth, request and response examples and error codes.
lede: The SDK first (`ClearedBy`, `ClearedByPartner` and the `/dispatch`, `/receipt`, `/partner-proxy` and `/doctor` subpaths), each method with its signature, what it does and an example. Then the HTTP API underneath it, endpoint by endpoint, and every error code.
pills: API v1, @clearedby/sdk 0.1.1, Node 18+
---

# API reference

## Install and choose a client {#clients}

```bash title="terminal"
npm install @clearedby/sdk
```

The package has no dependencies and works wherever `fetch` exists (Node 18+, edge runtimes, Bun, Deno). The `/dispatch`, `/receipt` and `/doctor` subpaths need Node's `node:crypto`. Before go-live, run the [doctor](#doctor): `npx @clearedby/sdk doctor --full`. There are two clients, one per kind of key:

| Client | Key | Use it for |
| --- | --- | --- |
| `new ClearedBy({ apiKey })` | the org's `cb_live_` key | Your **agent** (propose, follow, resubmit, undo) and your **executor** (complete, delivery). Also webhooks, catalogue, policies. |
| `new ClearedByPartner({ partnerKey })` | your `cb_partner_` key | Your **backend**: settings, orgs, keys (list, revoke, rotate), webhooks, reviewers, tokens, decisions, reads for your review UI, evidence, rules, erasure. |

```ts title="clients.ts"
import { ClearedBy, ClearedByPartner } from '@clearedby/sdk'

// Server-side only. Never ship either key to a browser or put it in an agent's prompt.
const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! })
const agent = new ClearedBy({ apiKey: await secrets.get(`cb:${orgId}:agent`) })
```

Both constructors take `{ baseUrl?: string, fetch?: typeof fetch }` too: `baseUrl` defaults to `https://app.clearedby.com`; `fetch` lets you inject an implementation (tests, instrumentation). Every method returns a promise and throws `ClearedByApiError` for any non-2xx answer (see [Errors](#sdk-errors)).

## ClearedBy: the org client {#clearedby}

Authenticate with one org's `cb_live_` key. The read methods (`status`, `list`, `get`, `events`, `permissions`, `signingSecrets`) also accept a partner key with an `orgId` option, but `ClearedByPartner` has the same reads with the org first.

### Propose {#cb-propose}

#### gate {#cb-gate}

Propose an action. The merchant's rules answer at once: `cleared` (with a signed `receipt`), `rejected`, or `pending` (held for a person). A `shopify.*` action must name a store from the org's `shop_domains` in `params.store`; a shopper-related action must carry `context.subject_id`.

```ts title="gate(input: GateInput): Promise<GateResult>"
const r = await agent.gate({
  action: 'shopify.refund.create',
  params: { store: 'acme.myshopify.com', order_id: 'gid://shopify/Order/5512', amount: 40, currency: 'GBP' },
  context: { subject_id: 'gid://shopify/Customer/7208314339542', summary: 'Refund a damaged jacket' },
  proof: { reason: 'Photos show a torn seam', confidence: 0.9, evidence: [{ type: 'note', value: 'Order delivered 3 days ago' }] },
  audience: 'https://exec.yourapp.example',        // the receipt will name your executor
  idempotencyKey: `refund:${ticketId}`,            // a retry replays the first answer
})
// r.status: 'cleared' | 'rejected' | 'pending'; r.id is the clearance id
```

`GateInput` fields: `action` (required), `params`, `context`, `proof` (`reason`, `confidence` 0 to 1, `recommended_outcome`, `risk_flags`, `evidence[]`), `policy` (a named policy; default the org's), `audience`, `mode` (`'enforce'` default, or `'shadow'`), `callbackUrl` (alias `callback_url`), `onDecision` (alias `on_decision`: per-call `{ cleared?, rejected?, expired?, sent_back?: { url } }` dispatch overrides), `timeout` (seconds or `"1h"`), `parentItemId`, `reverts`, `idempotencyKey` (sent as the `Idempotency-Key` header, kept 24 h).

`GateResult`: `id`, `status`, `rule`, `sampled`, `decided_by`, `expires_at`, `routed_to`, `attestation`, `receipt` (cleared in enforce mode), `resume`, `reason`, `attempt`, `parent_item_id`, `shadow` / `would` (shadow mode), `revoked_at`, `withdrawn_at`, `test`.

#### resubmit {#cb-resubmit}

Resubmit a `sent_back` clearance with revised params, as a new clearance linked to the original (`parent_item_id`, `attempt + 1`). Each sent-back clearance accepts exactly one resubmission for the same action.

```ts title="resubmit(parentItemId: string, input: GateInput): Promise<GateResult>"
const r2 = await agent.resubmit(r.id, { ...input, params: revisedParams, idempotencyKey: `${jobId}:v2` })
// r2.attempt === 2, r2.parent_item_id === r.id
```

#### check {#cb-check}

Dry run (`POST /v1/gate?dry=1`): every check a real proposal runs (catalogue schema, store list, `subject_id`) and the rules, but nothing is recorded, no webhook and no dispatch.

```ts title="check(input: GateInput): Promise<CheckResult>"
const dry = await agent.check({ action: 'shopify.product.tags.update', params })
// { dry: true, verdict: 'review', rule: 'rules[1]: shopify.product.tags.update', sampled: false, policy, currency, trace }
```

#### guard {#cb-guard}

Gate, then run `fn` only if it clears (now, or after a person approves; it waits up to an hour). Throws `RejectedError` (rejected, expired, revoked, withdrawn), `SentBackError` (catch it and `resubmit`), `TestItemError` for a dashboard test item, or `ClearedByApiError` on timeout. In shadow mode `fn` always runs. For partner integrations prefer dispatch to your executor: `guard` is for agents that act themselves.

```ts title="guard<T>(input: GateInput, fn: () => T | Promise<T>): Promise<T>"
await agent.guard({ action: 'email.send', params: { to_count: 1200 } }, () => mailer.sendCampaign(id))
```

### Follow {#cb-follow}

#### status {#cb-status}

The lightweight status shape of one clearance (`GET /v1/gate/:id`).

```ts title="status(id: string, opts?: { orgId?: string }): Promise<GateResult>"
const s = await agent.status(r.id)
if (s.status === 'sent_back') console.log('revise:', s.reason)
```

#### wait {#cb-wait}

Wait until the clearance leaves `pending` / `escalated` (default: 5 minutes), then return it. A `sent_back` comes back rather than hanging. It long-polls `GET /v1/gate/:id/wait` (each request is held up to 55 s and answers as soon as the clearance settles, or `204` to ask again), so a decision arrives within a second or two. Only against a server without `/wait` does it poll `GET /v1/gate/:id` every `pollMs` (default 2 s). Throws `ClearedByApiError` with status `408`, code `timeout`. For servers, prefer the `decision.*` webhooks.

```ts title="wait(id: string, opts?: { timeoutMs?: number; pollMs?: number }): Promise<GateResult>"
const settled = await agent.wait(r.id, { timeoutMs: 10 * 60_000 })
```

#### revoke {#cb-revoke}

Cancel an approved change before it runs. `reason` is 4 to 2,000 characters. `409 already_executed` once a final `done`/`failed` report exists; `409 not_cleared` if it isn't approved. `dispatch` says whether your executor may already have it.

```ts title="revoke(id: string, reason: string): Promise<RevokeResult>"
const rv = await agent.revoke(r.id, 'customer cancelled the order')
// rv.dispatch: 'cancelled' | 'in_flight' | 'delivered' | 'gave_up' | 'none'; rv.stopped_partial
```

#### withdraw {#cb-withdraw}

Pull back a request that is still `pending` or `escalated`. `409 not_pending` once decided.

```ts title="withdraw(id: string, reason?: string): Promise<WithdrawResult>"
await agent.withdraw(r.id, 'the customer resolved it themselves')
```

### Execute and prove {#cb-execute}

#### complete {#cb-complete}

Report what your executor did. Only a `cleared` clearance can be completed. `done` and `failed` are final; report progress on a big batch with `partial`. Pass a stable `completionId` (sent as `Idempotency-Key`) so a retry replays. Per-item `items` are compared with what was approved: writing anything else sets `diverged: true` for good. An `externalRef` (a Shopify object id) earns the Tier 3 label.

```ts title="complete(id: string, input: CompleteInput): Promise<CompleteResult>"
const res = await executor.complete(workItemId, {
  status: 'done',                                   // 'done' | 'failed' | 'partial'
  completionId: `${workItemId}:final`,
  items: [{ key: 'gid://shopify/ProductVariant/2001', status: 'done', before: { price: '40.00' }, after: { price: '30.00' } }],
  deliveryReceiptId: receipt.receipt_id,            // the receipt you verified
  externalRef: 'gid://shopify/BulkOperation/991',   // optional
})
// { recorded, status, tier, diverged, completion_id, idempotent_replay, receipt_id, items, totals, ... }
```

`CompletionItem`: `key` (the change's `product_id` / `variant_id` GID, or `<inventory_item_id>@<location_id>`), `status` (`done`, `failed`, `skipped`), `before`, `after`, `external_ref`, `error`. Up to 10,000 per call.

#### buildUndo {#cb-buildundo}

Build the inverse proposal for an executed clearance from the record: the inverse action, only the items reported `done`, before and after swapped, and `reverts` set. Nothing is proposed until you submit it.

```ts title="buildUndo(id: string): Promise<UndoInput>"
const u = await agent.buildUndo(r2.id)       // { action, params, reverts, keys }
await agent.gate({ ...u, audience: 'https://exec.yourapp.example', idempotencyKey: `undo:${r2.id}` })
```

#### undo {#cb-undo}

`buildUndo` and `gate` in one call. `extra` adds anything else the gate takes; `action`, `params` and `reverts` always come from the record.

```ts title="undo(id: string, extra?: Omit<GateInput, 'action' | 'params' | 'reverts'>): Promise<GateResult>"
const u = await agent.undo(r2.id, { audience: 'https://exec.yourapp.example', context: { summary: 'Put the tags back' } })
```

#### delivery {#cb-delivery}

The dispatch state for a clearance (`GET /v1/gate/:id/delivery`): attempts, last status, whether it was delivered or ClearedBy gave up.

```ts title="delivery(id: string): Promise<DeliveryState>"
const d = await executor.delivery(id)
// d.delivery: { delivery_id, verdict, attempts, delivered, already_executed, last_status, last_error,
//               next_retry_at, in_flight, gave_up, needs_attention, receipt_id, cancelled, ... } | null
```

#### redeliver {#cb-redeliver}

Send the dispatch again now, as the next attempt under the same `delivery_id`, with a fresh receipt. 1 per clearance per 30 s. `409 revoked`, `409 in_flight`, `409 not_decided`, `404 no_dispatch`.

```ts title="redeliver(id: string): Promise<{ id: string; delivery: DeliveryView }>"
await executor.redeliver(id)     // after fixing the executor that caused a dispatch_gave_up alert
```

#### receipt {#cb-receipt}

The stored Authorisation Receipt for a cleared clearance. `404 no_receipt` if there is none; `410 receipt_redacted` after erasure.

```ts title="receipt(id: string): Promise<AuthorizationReceipt>"
const rec = await agent.receipt(r.id)
```

#### receiptStatus {#cb-receiptstatus}

Is a receipt still good (`GET /v1/receipts/:receipt_id/status`, public)? `status` is `valid`, `expired`, `superseded`, `revoked`, `redacted` or `unknown`. Only `revoked` means "don't execute".

```ts title="receiptStatus(receiptId: string): Promise<ReceiptStatusView>"
const st = await executor.receiptStatus(receipt.receipt_id)
if (st.status === 'revoked') return
```

### Read {#cb-read}

#### list {#cb-list}

Clearances, newest first, paged with `next_cursor`. `ListOptions`: `status` (one or an array), `reviewer` (an `external_subject`: items their authority covers or that were escalated to them), `reviewerUserId`, `actionPrefix`, `batchId`, `include` (`params`, `proof`, `context`, `lineage`), `limit` (1 to 100, default 50), `cursor`, `orgId` (with a partner key).

```ts title="list(opts?: ListOptions): Promise<{ items: Clearance[]; next_cursor: string | null }>"
const page = await agent.list({ status: ['pending', 'escalated'], batchId: 'bf-2026-tags', include: ['params'] })
```

#### get {#cb-get}

One clearance in full (`GET /v1/gate/:id/detail`): params, proof, the evidence split into `claims` and `verified`, context, routing, escalation, dual review, decider, completion, dispatch state and lineage. `include: ['events']` adds the history.

```ts title="get(id: string, opts?: { include?: IncludeOption[]; orgId?: string }): Promise<Clearance>"
const item = await agent.get(r.id, { include: ['events'] })
```

#### events {#cb-events}

The clearance's history, oldest first. `lineage: true` merges every attempt of a send-back chain.

```ts title="events(id: string, opts?: { lineage?: boolean; orgId?: string }): Promise<ClearanceEvent[]>"
const history = await agent.events(r2.id, { lineage: true })
```

#### permissions {#cb-permissions}

Which decisions a reviewer may make on this clearance right now, and why not the others: the same checks the decision runs, in the same order. Show only the buttons in `can`.

```ts title="permissions(id: string, reviewer: string, opts?: { orgId?: string }): Promise<Permissions>"
const p = await agent.permissions(r.id, 'user_17')
// { can: ['clear', 'reject', 'send_back', 'escalate'], cannot: [], reason_required: ['reject', 'send_back'], dual_review: null, ... }
```

### Ledger {#cb-ledger}

#### ledger {#cb-ledger-page}

The org's tamper-evident record, newest first. Page older with `cursor: page.next_cursor`.

```ts title="ledger(opts?: { limit?: number; cursor?: number }): Promise<LedgerPage>"
const { rows, next_cursor } = await agent.ledger({ limit: 50 })
```

#### verifyLedger {#cb-verifyledger}

Re-walk the org's chain from the start and report the first broken row, if any.

```ts title="verifyLedger(): Promise<LedgerVerifyResult>"
const v = await agent.verifyLedger()   // { intact: true, through, rows } | { intact: false, broken_at, reason, rows }
```

### Catalogue and policies {#cb-policies}

Partner orgs normally use the approval rules (`ClearedByPartner.getRules` / `setRules`). These are for hand-written policies.

#### catalogue {#cb-catalogue}

Every `shopify.*` action with its params JSON schema, reversibility, inverse action, recommended evidence cards and an example. The gate enforces the same schemas.

```ts title="catalogue(): Promise<{ shopify: ActionCatalogue }>"
const { shopify } = await agent.catalogue()
const tags = shopify.actions.find((a) => a.action === 'shopify.product.tags.update')
```

#### listPolicies {#cb-listpolicies}

Every policy name with its active and latest version. Never the rules themselves.

```ts title="listPolicies(): Promise<PolicyListEntry[]>"
const policies = await agent.listPolicies()
```

#### describePolicy {#cb-describepolicy}

What the active version of a policy reads: the actions, field names and currency, never the thresholds. Useful for an agent to know what to send.

```ts title="describePolicy(name: string): Promise<PolicyShape>"
const shape = await agent.describePolicy('refunds')
```

#### getPolicy {#cb-getpolicy}

One stored version, YAML included.

```ts title="getPolicy(name: string, version: number): Promise<PolicyVersion>"
const v3 = await agent.getPolicy('refunds', 3)
```

#### savePolicyDraft {#cb-savepolicydraft}

Save a new draft version from YAML. Compile and lint run first; when they block, you get `{ saved: false, lint, compile_errors }` rather than an exception. A key can never activate a policy (see `ClearedByPartner.activatePolicy`).

```ts title="savePolicyDraft(name: string, yaml: string): Promise<SavePolicyDraftResult>"
const draft = await agent.savePolicyDraft('refunds', yamlText)
if (!draft.saved) console.log(draft.lint, draft.compile_errors)
```

#### simulatePolicy {#cb-simulatepolicy}

Replay a stored version over the last `days` (1 to 90, default 30) of history: what it would have loosened and tightened.

```ts title="simulatePolicy(name: string, version: number, opts?: { days?: number }): Promise<SimulateResult>"
const sim = await agent.simulatePolicy('refunds', draft.version!, { days: 30 })
```

### Webhooks {#cb-webhooks}

Lifecycle webhooks are per org. With the org's `cb_live_` key use these; with your partner key use [`partner.createWebhook(orgId, ...)`](#p-webhooks) and friends.

#### createWebhook {#cb-createwebhook}

Subscribe to events. `url` must be public HTTPS. The response carries the signing `secret` once.

```ts title="createWebhook(input: CreateWebhookInput): Promise<Webhook & { secret: string }>"
const hook = await agent.createWebhook({
  url: 'https://api.yourapp.example/clearedby/events',
  events: ['decision.pending', 'decision.escalated', 'decision.sent_back', 'decision.cleared',
           'decision.rejected', 'decision.expired', 'decision.completed', 'decision.revoked', 'decision.withdrawn'],
  filters: { action_prefix: 'shopify.' },          // optional; also policy, mode
})
await secrets.put(`cb:${orgId}:whsec`, hook.secret)   // shown once
```

#### listWebhooks {#cb-listwebhooks}

This org's subscriptions, newest first, with `active` and `failed_count`. Secrets are never returned.

```ts title="listWebhooks(): Promise<Webhook[]>"
const hooks = await agent.listWebhooks()
```

#### deleteWebhook {#cb-deletewebhook}

Unsubscribe.

```ts title="deleteWebhook(id: string): Promise<{ deleted: true; id: string }>"
await agent.deleteWebhook(hook.id)
```

### Org settings and reporting {#cb-org}

#### signingSecrets {#cb-signingsecrets}

The org's signing secrets: `on_decision.secret` verifies dispatches (pass it to `verifyDispatch`), `callback.secret` verifies per-item `callbackUrl` deliveries. Stable per org.

```ts title="signingSecrets(opts?: { orgId?: string }): Promise<SigningSecrets>"
const { on_decision } = await executor.signingSecrets()
```

#### stats {#cb-stats}

Throughput over the last `days` (1 to 365, default 30), for the org and per reviewer.

```ts title="stats(opts?: { days?: number }): Promise<OrgStats>"
const s = await agent.stats({ days: 7 })   // s.org.auto_clear_rate, s.reviewers[].median_minutes
```

#### usage {#cb-usage}

The current billing period's usage. `over_quota` never blocks a gate call.

```ts title="usage(): Promise<Usage>"
const u = await agent.usage()
```

#### graduations {#cb-graduations}

Suggestions to loosen a rule that history shows is safe. Ratifying is a dashboard action.

```ts title="graduations(opts?: { status?: 'open' | 'ratified' | 'dismissed' | 'all' }): Promise<GraduationProposal[]>"
const open = await agent.graduations()
```

## ClearedByPartner: the partner client {#partner}

Authenticate with your `cb_partner_` key, on your servers only. Every org-scoped method takes the org id first. A partner key only sees the orgs it created; any other id is `404 not_found`.

### Settings and secrets {#p-settings}

#### getSettings {#p-getsettings}

Your account-wide settings: `execution_url`, `notify_url`, `alert_email`, `alert_webhook_url`, `alert_webhook_configured`, `retention_days`, `theme`, and `recent_alerts` (the last 20). Never the alert secret. It also returns `usage` (a `PartnerUsage`): this month's `period` (`YYYY-MM`, UTC), `total_gates` across your orgs, `by_org_top` (your busiest orgs, up to 20, each `{ org_id, external_id, name, total_gates }`), and `soft_cap_per_org`. The soft cap never blocks a gate call: it only triggers one `usage_80` and one `usage_100` alert per org per month (see [Partner alerts](/docs/partners/guide#partner-alerts)).

```ts title="getSettings(): Promise<PartnerSettings>"
const s = await partner.getSettings()
for (const o of s.usage.by_org_top) {
  if (o.total_gates >= s.usage.soft_cap_per_org * 0.8) console.warn(`${o.external_id} is near its soft cap`)
}
```

#### updateSettings {#p-updatesettings}

Change any subset; `null` clears a field. URLs must be public HTTPS (`400 blocked_destination` otherwise). The first time you set `alert_webhook_url`, or with `rotate_alert_webhook_secret: true`, the response carries `alert_webhook_secret` once.

```ts title="updateSettings(input: UpdatePartnerSettingsInput): Promise<PartnerSettings & { alert_webhook_secret?: string }>"
const s = await partner.updateSettings({
  execution_url: 'https://exec.yourapp.example/clearedby/on-decision',   // cleared
  notify_url: 'https://exec.yourapp.example/clearedby/on-verdict',       // rejected, expired, sent_back
  alert_email: 'platform-oncall@yourapp.example',
  alert_webhook_url: 'https://ops.yourapp.example/clearedby/alerts',
  retention_days: 90,
  theme: { colors: { primary: '#6b3fd4' }, radius: '10px' },
})
if (s.alert_webhook_secret) await secrets.put('cb:alert-secret', s.alert_webhook_secret)
```

#### getSigningSecret {#p-getsigningsecret}

The org's dispatch signing secret: what your executor passes to `verifyDispatch` as `secret`. Stable per org, so fetch it once when you onboard the org.

```ts title="getSigningSecret(orgId: string): Promise<string>"
await secrets.put(`cb:${orgId}:signing`, await partner.getSigningSecret(orgId))
```

#### getSigningSecrets {#p-getsigningsecrets}

The full signing-secret view for an org (dispatch and callback secrets, and their header formats).

```ts title="getSigningSecrets(orgId: string): Promise<SigningSecrets>"
const view = await partner.getSigningSecrets(orgId)
```

### Orgs and keys {#p-orgs}

#### createOrg {#p-createorg}

Create one org per merchant company. Idempotent on `external_id`: the first call returns `created: true` and a one-time `api_key`; repeats return the existing org, `created: false`, no key. The org starts with the default approval rules switched on.

```ts title="createOrg(input: CreateOrgInput): Promise<CreateOrgResult>"
const org = await partner.createOrg({
  external_id: 'shop_8841',                          // your id for the merchant
  name: 'Acme Outdoor',
  currency: 'GBP',                                   // ISO 4217
  shop_domains: ['acme-outdoor.myshopify.com'],      // permanent *.myshopify.com domains, up to 50
})
if (org.created) await secrets.put(`cb:${org.org_id}:agent`, org.api_key!)
```

#### getOrg {#p-getorg}

One of your orgs: `org_id`, `external_id`, `name`, `shop_domains`, `currency`, `execution_url` / `notify_url` / `theme` overrides (`null` = your default), `plan`, `created_at`.

```ts title="getOrg(orgId: string): Promise<PartnerOrg>"
const org = await partner.getOrg(orgId)
```

#### listOrgs {#p-listorgs}

Your orgs, oldest first. `limit` 1 to 500 (default 100); page with `after: page.next_after`; `externalId` filters to one.

```ts title="listOrgs(opts?: ListOrgsOptions): Promise<{ orgs: PartnerOrg[]; next_after: string | null }>"
const page = await partner.listOrgs({ limit: 200 })
```

#### iterateOrgs {#p-iterateorgs}

Every org, page by page, as an async iterator.

```ts title="iterateOrgs(opts?: { pageSize?: number }): AsyncGenerator<PartnerOrg>"
for await (const org of partner.iterateOrgs()) console.log(org.external_id, org.shop_domains)
```

#### findOrg {#p-findorg}

The org with this `external_id`, or `null`.

```ts title="findOrg(externalId: string): Promise<PartnerOrg | null>"
const org = await partner.findOrg('shop_8841')
```

#### updateOrg {#p-updateorg}

Change an org: `name`, `currency` (doesn't convert anything), `shop_domains` (replaces the list), `execution_url` / `notify_url` (per-org dispatch overrides) and `theme`. `null` clears an override. Send at least one field.

```ts title="updateOrg(orgId: string, input: UpdateOrgInput): Promise<PartnerOrg>"
await partner.updateOrg(orgId, { shop_domains: ['acme-outdoor.myshopify.com', 'acme-outdoor-eu.myshopify.com'] })
```

#### getOrgTheme {#p-getorgtheme}

The effective theme for one merchant's embedded UI: your account theme with the org's override on top, or `null`.

```ts title="getOrgTheme(orgId: string): Promise<ClearedByTheme | null>"
const theme = await partner.getOrgTheme(orgId)
```

#### createOrgKey {#p-createorgkey}

Mint another `cb_live_` key for an org, for example a separate executor key. `api_key` is shown once. To replace a key, use [`rotateOrgKey`](#p-rotateorgkey).

```ts title="createOrgKey(orgId: string, opts?: { name?: string }): Promise<OrgKey>"
const exec = await partner.createOrgKey(orgId, { name: 'executor' })   // { org_id, key_id, api_key, prefix, name }
```

#### listOrgKeys {#p-listorgkeys}

Every `cb_live_` key the org has had, newest first, revoked ones included. Each `OrgKeyInfo` has `key_id`, `name`, `prefix`, `agent_id`, `created_at`, `last_used_at`, `revoked_at`, `revokes_at` (a rotated-out key still in its grace period), `revoked_by` and `active`. Never the secret.

```ts title="listOrgKeys(orgId: string): Promise<OrgKeyInfo[]>"
const keys = await partner.listOrgKeys(orgId)
const stale = keys.filter((k) => k.active && k.last_used_at === null)
```

#### revokeOrgKey {#p-revokeorgkey}

Revoke one key. It takes effect on the key's next request, which gets `401 unauthorized`. Revoking a revoked key returns it unchanged; a key still in a rotation grace period is cut off now. `404` for a key that isn't the org's.

```ts title="revokeOrgKey(orgId: string, keyId: string): Promise<OrgKeyInfo & { org_id: string }>"
await partner.revokeOrgKey(orgId, leakedKeyId)
```

#### rotateOrgKey {#p-rotateorgkey}

Replace a key: a new `cb_live_` key with the same name and the same agent binding, returned once as `api_key`, and the old key revoked. With `graceSeconds` (up to 86400) the old key keeps working until `replaced.revokes_at`, so you can roll the new one out first; without it the old key stops at once. A key that is already revoked or already rotated is `409 key_revoked`: rotate its replacement.

```ts title="rotateOrgKey(orgId: string, keyId: string, opts?: { graceSeconds?: number }): Promise<RotatedOrgKey>"
const next = await partner.rotateOrgKey(orgId, agentKeyId, { graceSeconds: 3600 })
await secrets.put(`cb:${orgId}:agent`, next.api_key)     // shown once; redeploy within the hour
// next.replaced → { key_id: agentKeyId, active: true, revokes_at: '...' }
```

### Webhooks {#p-webhooks}

The same lifecycle subscriptions as the [org client's](#cb-webhooks), managed with your partner key for any of your orgs. Another partner's org is `404`.

#### createWebhook {#p-createwebhook}

Subscribe one org to events. `url` must be public HTTPS. The response carries the signing `secret` once.

```ts title="createWebhook(orgId: string, input: CreateWebhookInput): Promise<Webhook & { secret: string }>"
const hook = await partner.createWebhook(orgId, {
  url: 'https://api.yourapp.example/clearedby/events',
  events: ['decision.pending', 'decision.cleared', 'decision.rejected', 'decision.sent_back', 'decision.revoked'],
})
await secrets.put(`cb:${orgId}:whsec`, hook.secret)   // shown once
```

#### listWebhooks {#p-listwebhooks}

The org's subscriptions, newest first, with `active` and `failed_count`. Secrets are never returned.

```ts title="listWebhooks(orgId: string): Promise<Webhook[]>"
const hooks = await partner.listWebhooks(orgId)
```

#### deleteWebhook {#p-deletewebhook}

Unsubscribe. `404` for an id that isn't that org's.

```ts title="deleteWebhook(orgId: string, id: string): Promise<{ deleted: true; id: string }>"
await partner.deleteWebhook(orgId, hook.id)
```

### Reviewers {#p-reviewers}

#### upsertReviewer {#p-upsertreviewer}

Create or replace a reviewer (`PUT`: the whole record, so it is safe to repeat). `authority` is exact action names or `*`, each mapped to the largest amount in minor units of the org currency. `created` is `true` on first creation.

```ts title="upsertReviewer(orgId: string, externalSubject: string, input: ReviewerInput): Promise<PartnerReviewer & { created: boolean }>"
await partner.upsertReviewer(orgId, 'user_17', {
  display_name: 'Sam R.',
  role: 'owner',                                               // owner | admin | reviewer
  authority: { '*': 0, 'shopify.refund.create': 50000 },       // no-amount actions + refunds up to 500.00
  // email: optional, record only; channels: [] (default) = ClearedBy never contacts them
})
```

#### removeReviewer {#p-removereviewer}

Stop a reviewer's authority and routing at once; their history stays. Idempotent; an unknown subject is `404`.

```ts title="removeReviewer(orgId: string, externalSubject: string): Promise<PartnerReviewer>"
await partner.removeReviewer(orgId, 'user_22')   // → { ..., active: false }
```

#### listReviewers {#p-listreviewers}

The org's reviewers, removed ones included (`active: false`).

```ts title="listReviewers(orgId: string): Promise<PartnerReviewer[]>"
const people = await partner.listReviewers(orgId)
```

### Decisions and tokens {#p-decisions}

#### createDecisionToken {#p-createdecisiontoken}

Mint a short-lived token naming one reviewer. The default `scope: 'decide'` token records one decision (single use; `ttlSeconds` 1 to 300, default 120; if the decision is refused, the token isn't used up). Pass `workItemId` to pin it to one clearance. `externalSubject` must come from **your** session.

```ts title="createDecisionToken(input: { orgId, externalSubject, workItemId?, ttlSeconds?, scope? }): Promise<DecisionToken>"
const { token } = await partner.createDecisionToken({ orgId, externalSubject: session.userId, workItemId: id })
```

#### createReadToken {#p-createreadtoken}

A reusable read-only token for one reviewer (up to 900 s, default 600): reads as that person, never decides (`403 token_scope`). The partner proxy caches one per person.

```ts title="createReadToken(input: { orgId, externalSubject, workItemId?, ttlSeconds? }): Promise<DecisionToken>"
const { token } = await partner.createReadToken({ orgId, externalSubject: session.userId })
const inbox = await partner.list(orgId, { status: ['pending', 'escalated'], token })   // as that reviewer
```

#### decide {#p-decide}

Record the reviewer's decision with their decision token. `reason` (4+ characters) is required for `reject` and `send_back`. `escalateTo` (an `external_subject`) only with `escalate`; leave it out and ClearedBy picks the most senior reviewer who can cover it. `status` comes back as `cleared`, `rejected`, `sent_back`, `escalated`, or `pending` (the first of two approvals, with `approvals` and `required`).

```ts title="decide(id: string, input: { decision, reason?, escalateTo? }, auth: { token: string }): Promise<PartnerDecideResult>"
const { token } = await partner.createDecisionToken({ orgId, externalSubject: 'user_17', workItemId: id })
const res = await partner.decide(id, { decision: 'send_back', reason: 'Leave out the Clearance collection' }, { token })
```

### Reading clearances {#p-read}

The same reads as `ClearedBy`, with the org first. Pass `token` (from `createReadToken` or an unused decide token) to read **as** that reviewer: `list` then defaults to their queue. Without it, the partner key reads (600 requests a minute).

#### list {#p-list}

```ts title="list(orgId: string, opts?: ListOptions & { token?: string }): Promise<{ items: Clearance[]; next_cursor: string | null }>"
const inbox = await partner.list(orgId, { status: ['pending', 'escalated'], reviewer: 'user_17', include: ['params', 'proof'] })
```

#### get {#p-get}

```ts title="get(orgId: string, id: string, opts?: { include?: IncludeOption[]; token?: string }): Promise<Clearance>"
const item = await partner.get(orgId, id, { include: ['events'] })
```

#### status {#p-status}

```ts title="status(orgId: string, id: string, opts?: { token?: string }): Promise<GateResult>"
const s = await partner.status(orgId, id)
```

#### events {#p-events}

```ts title="events(orgId: string, id: string, opts?: { lineage?: boolean; token?: string }): Promise<ClearanceEvent[]>"
const history = await partner.events(orgId, id, { lineage: true })
```

#### permissions {#p-permissions}

```ts title="permissions(orgId: string, id: string, reviewer: string, opts?: { token?: string }): Promise<Permissions>"
const { can, reason_required } = await partner.permissions(orgId, id, session.userId)
```

### Evidence, revoke and withdraw {#p-items}

#### attachEvidence {#p-attachevidence}

Attach facts your backend looked up itself to a `pending` or `escalated` clearance, as `partner_verified` evidence ("Verified by" your name). 1 to 20 items and 64 KB per call, 100 per clearance. Their hashes go on the signed record. Nothing is re-evaluated.

```ts title="attachEvidence(orgId: string, itemId: string, items: AttachEvidenceItem[]): Promise<AttachEvidenceResult>"
await partner.attachEvidence(orgId, id, [{
  type: 'order_lookup',                               // 1 to 64 chars; what a rule's requires_verified names
  label: 'Shopify order',
  value: { order: '#5512', total: 40, refunded: 0 },
  source_ref: 'gid://shopify/Order/5512',
}])
```

#### revoke {#p-revoke}

Cancel an approved change in one of your orgs before it runs. Without `auth` the partner key does it; with `{ token }` it is done as that reviewer (an owner, admin, or someone whose authority covers the action).

```ts title="revoke(orgId: string, id: string, reason: string, auth?: { token: string }): Promise<RevokeResult>"
const rv = await partner.revoke(orgId, id, 'customer cancelled the order')
```

#### withdraw {#p-withdraw}

Withdraw a still-open request in one of your orgs.

```ts title="withdraw(orgId: string, id: string, reason?: string): Promise<WithdrawResult>"
await partner.withdraw(orgId, id, 'no longer needed')
```

### Approval rules and policies {#p-rules}

#### getRules {#p-getrules}

The merchant's approval rules: `settings`, a plain-English `summary` (one sentence per setting, amounts formatted in the org currency), `active_version`, `currency`, `refund_approvers`, and any `pending_proposal` waiting for an owner.

```ts title="getRules(orgId: string): Promise<ApprovalRules>"
const rules = await partner.getRules(orgId)
for (const line of rules.summary) console.log(line.sentence)   // "Refunds over £25 need your OK"
```

#### setRules {#p-setrules}

Change any subset of settings. Stricter or equal: on at once, `{ status: 'active' }`. Looser or mixed: saved as a proposal, `{ status: 'needs_owner_approval', proposal_id, summary_diff }`.

```ts title="setRules(orgId: string, settings: Partial<ApprovalRulesSettings>): Promise<SetRulesResult>"
const res = await partner.setRules(orgId, { refund_auto_max: 50, spot_checks: true, spot_check_pct: 5 })
```

#### acceptRules {#p-acceptrules}

An owner or admin of the merchant accepts a looser proposal, with their decision token (not pinned to an item).

```ts title="acceptRules(orgId: string, proposalId: string, auth: { token: string }): Promise<{ status: 'active'; active_version; attestation; summary }>"
if (res.status === 'needs_owner_approval') {
  const { token } = await partner.createDecisionToken({ orgId, externalSubject: 'user_17' })
  await partner.acceptRules(orgId, res.proposal_id, { token })
}
```

#### activatePolicy {#p-activatepolicy}

Switch on a stored hand-written policy version in one of your orgs. With the partner key it's allowed only when the version isn't looser than the active one (else `403 owner_approval_required`); pass an owner/admin `{ token }` to activate as the merchant.

```ts title="activatePolicy(orgId: string, name: string, version: number, auth?: { token: string }): Promise<PolicyActivation>"
await partner.activatePolicy(orgId, 'refunds', 3)
```

### Data protection {#p-erasure}

#### eraseSubject {#p-erasesubject}

Erase one shopper's readable data in one org: params, context, notes, receipts and the webhook and replay copies. `subjectId` is the `context.subject_id` you proposed with. Synchronous; safe to retry.

```ts title="eraseSubject(orgId: string, subjectId: string): Promise<OrgErasureResult>"
const r = await partner.eraseSubject(orgId, 'gid://shopify/Customer/7208314339542')   // { items_redacted, attestation_seq, ... }
```

#### eraseSubjectEverywhere {#p-erasesubjecteverywhere}

The same across every org you own. If `complete` is `false`, call it again.

```ts title="eraseSubjectEverywhere(subjectId: string): Promise<PartnerErasureResult>"
const all = await partner.eraseSubjectEverywhere('gid://shopify/Customer/7208314339542')
if (!all.complete) await partner.eraseSubjectEverywhere('gid://shopify/Customer/7208314339542')
```

## Errors in the SDK {#sdk-errors}

| Class | Thrown when | Useful fields |
| --- | --- | --- |
| `ClearedByApiError` | Any non-2xx answer; `wait()` timing out (`408`, `timeout`) | `status`, `code` (the API's stable `error.code`), `message`, `hint`, `details`, `body` |
| `ClearedByError` | The older name of `ClearedByApiError`: the same class, so `instanceof` works with either | as above |
| `RejectedError` | `guard()`: rejected, expired, revoked or withdrawn | `result` |
| `SentBackError` | `guard()`: a reviewer sent it back | `result`, `reason` |
| `TestItemError` | `guard()`: a dashboard test item (never executable) | `result` |

```ts title="errors.ts"
import { ClearedByApiError } from '@clearedby/sdk'

try {
  await partner.decide(id, { decision: 'clear' }, { token })
} catch (e) {
  if (e instanceof ClearedByApiError && e.code === 'not_pending') return { status: 'already_decided' }
  if (e instanceof ClearedByApiError && e.code === 'no_authority') return { status: 'over_limit' }
  throw e
}
```

## @clearedby/sdk/dispatch {#dispatch}

Verify a dispatch before your executor acts on it. Node 18+ (`node:crypto`).

### verifyDispatch {#verifydispatch}

Checks, in order: the `clearedby-signature` header (`t=<unix>,v1=<hex>`); the timestamp is within `toleranceSec` (default 300); the HMAC-SHA256 of `"<t>.<raw body>"` with your secret (constant-time); the body is a v2 envelope and `params_hash` matches its params; the `clearedby-delivery-id` header matches; for `cleared`, the Ed25519 receipt verifies offline (signature, freshness, `audience`) and is bound to this envelope (same clearance, org, action and params hash); optionally (`checkStatus`) the receipt hasn't been revoked. Throws `DispatchVerificationError` with a stable `code`.

```ts title="verifyDispatch(rawBody: string, headers: HeadersLike, opts: VerifyDispatchOptions): Promise<VerifiedDispatch>"
import { verifyDispatch } from '@clearedby/sdk/dispatch'

const { envelope, params, receipt, status } = await verifyDispatch(rawBody, req.headers, {
  secret: signingSecret,             // string, or string[] during your own rotation
  orgId,                             // the signed body must name this org
  jwksUrl: 'https://app.clearedby.com/.well-known/clearedby-keys',   // or keys: { key_id: publicHex }
  audience: 'https://exec.yourapp.example',                          // the receipt must name exactly this
  checkStatus: true,                 // also ask whether it was revoked (fails closed)
  // toleranceSec?: 300, now?: Date, fetch?: typeof fetch
})
// execute ONLY `params` (for cleared: the receipt's signed params); dedupe on envelope.work_item_id
```

`HeadersLike` is a `Headers` object or a plain object (Node's `IncomingHttpHeaders`). `checkStatus: true` asks the origin of `jwksUrl` (default `https://app.clearedby.com`); pass `{ statusUrl }` or `{ baseUrl }` to override.

The envelope (`VerifiedDispatch.envelope`, `DispatchEnvelope`):

```json title="dispatch envelope (v2)"
{
  "v": 2,
  "delivery_id": "01K...:cleared",
  "attempt": 1,
  "event": "on_decision",
  "verdict": "cleared",
  "org_id": "01K...",
  "work_item_id": "01K...",
  "parent_item_id": null,
  "action": "shopify.price.update",
  "params": { "store": "acme.myshopify.com", "currency": "GBP", "count": 1, "changes": [ "..." ] },
  "params_hash": "5e1c...",
  "decided_by": "user:01K...",
  "rule": "rules[3]: shopify.price.update",
  "reason": "Looks right",
  "attestation": { "seq": 42, "hash": "..." },
  "receipt": { "v": 1, "receipt_id": "01K...", "work_item_id": "01K...", "principal": "01K...", "action": "shopify.price.update", "params": { "...": "..." }, "params_hash": "5e1c...", "audience": "https://exec.yourapp.example", "expires_at": "...", "nonce": "...", "key_id": "...", "alg": "ed25519", "sig": "..." },
  "issued_at": "2026-11-20T10:00:05.000Z"
}
```

### DispatchVerificationError {#dispatchverificationerror}

`code` is one of: `missing_signature`, `malformed_signature`, `timestamp_out_of_tolerance`, `bad_signature`, `malformed_envelope`, `unsupported_version`, `params_hash_mismatch`, `delivery_id_mismatch`, `org_mismatch`, `missing_receipt` (a `cleared` dispatch without a receipt), `no_keys`, `receipt_invalid` (see `receiptReason`), `receipt_mismatch`, and with `checkStatus`: `receipt_revoked`, `status_unavailable`. Answer `401` for all of them except `status_unavailable` (answer `503` so ClearedBy retries) and `receipt_revoked` (see below).

```ts title="class DispatchVerificationError extends Error { code: DispatchErrorCode; receiptReason? }"
if (err instanceof DispatchVerificationError) console.warn('refused dispatch:', err.code, err.receiptReason)
```

### ReceiptRevokedError {#receiptrevokederror}

A subclass of `DispatchVerificationError` (code `receipt_revoked`) thrown with `checkStatus` when the approval was revoked after it was sent. Don't execute; answer `2xx` so it isn't retried.

```ts title="class ReceiptRevokedError extends DispatchVerificationError { status: ReceiptStatusView; revokedAt: string | null }"
if (err instanceof ReceiptRevokedError) return res.status(200).json({ status: 'revoked' })
```

### signDispatchPayload and parseSignatureHeader {#signdispatchpayload}

`signDispatchPayload` produces a valid `clearedby-signature` value, so your tests can sign fake dispatches for your receiver. `parseSignatureHeader` splits a header into its timestamp and `v1` signatures. `DISPATCH_ENVELOPE_VERSION` is `2`.

```ts title="signDispatchPayload(secret: string, t: number, rawBody: string): string"
import { signDispatchPayload, parseSignatureHeader } from '@clearedby/sdk/dispatch'

const t = Math.floor(Date.now() / 1000)
const header = signDispatchPayload('test-secret', t, body)   // 't=1790000000,v1=ab12...'
parseSignatureHeader(header)                                 // { t: 1790000000, v1: ['ab12...'] }
```

## @clearedby/sdk/receipt {#receipt}

Verify Authorisation Receipts offline, for any service that is handed one (an executor, an MCP server, a partner API). Node 18+.

### verifyReceipt {#verifyreceipt}

Offline: signature, freshness (`clockSkewSeconds` default 30), `audience` and `action`. Returns a result rather than throwing. Pass `audience` for anything consequential: without it, a receipt addressed to someone else also passes.

```ts title="verifyReceipt(receipt: unknown, opts: VerifyReceiptOptions): VerifyReceiptResult"
import { verifyReceipt, fetchClearedByKeys } from '@clearedby/sdk/receipt'

const keys = await fetchClearedByKeys()           // cache it; refetch on 'unknown_key'
const v = verifyReceipt(receipt, { keys, audience: 'https://exec.yourapp.example', action: 'shopify.refund.create' })
if (!v.valid) throw new Error(v.reason)           // malformed | unsupported_version | unsupported_alg | bad_decision
                                                  // | unknown_key | bad_signature | not_yet_valid | expired
                                                  // | audience_mismatch | action_mismatch
```

### verifyReceiptOnline {#verifyreceiptonline}

`verifyReceipt`, then (with `checkStatus`) the online revocation check. Adds the reasons `revoked` and `status_unavailable`.

```ts title="verifyReceiptOnline(receipt: unknown, opts: VerifyReceiptOptions & { checkStatus?: boolean | ReceiptStatusOptions }): Promise<VerifyReceiptOnlineResult>"
const v = await verifyReceiptOnline(receipt, { keys, audience, checkStatus: true })
```

### fetchClearedByKeys {#fetchclearedbykeys}

Fetch ClearedBy's published verification keys (`/.well-known/clearedby-keys`) as `{ key_id: publicHex }`.

```ts title="fetchClearedByKeys(opts?: { baseUrl?: string; fetch?: typeof fetch }): Promise<Record<string, string>>"
const keys = await fetchClearedByKeys()
```

### checkReceiptStatus and receiptStatusUrl {#checkreceiptstatus}

Ask whether a receipt is still valid. Throws `ReceiptStatusUnavailableError` (code `status_unavailable`) on a network error or non-200. `receiptStatusUrl` builds the URL.

```ts title="checkReceiptStatus(receiptId: string, opts?: ReceiptStatusOptions): Promise<ReceiptStatusView>"
const st = await checkReceiptStatus(receipt.receipt_id)   // { receipt_id, work_item_id, status, expires_at?, revoked_at?, superseded_by? }
receiptStatusUrl(receipt.receipt_id)                      // 'https://app.clearedby.com/v1/receipts/01K.../status'
```

### canonicalJSON and receiptSigningHash {#canonicaljson}

`canonicalJSON` is the key-sorted JSON that `params_hash` and evidence `sha256` are computed over (`sha256(canonicalJSON(params))`). `receiptSigningHash` is the exact hash the receipt signature covers (the receipt without `sig`).

```ts title="canonicalJSON(value: unknown): string"
import { createHash } from 'node:crypto'
const ok = createHash('sha256').update(canonicalJSON(receipt.params)).digest('hex') === receipt.params_hash
```

## @clearedby/sdk/partner-proxy {#partner-proxy}

The server half of the embedded approval UI. Full options, routes and recipes are on the [UI components page](/docs/partners/ui#proxy).

### createPartnerProxy {#createpartnerproxy}

Returns a Web Fetch handler for a fixed set of routes. The org and the person come **only** from `resolveUser`.

```ts title="createPartnerProxy(opts: PartnerProxyOptions): PartnerProxy"
import { createPartnerProxy } from '@clearedby/sdk/partner-proxy'

const proxy = createPartnerProxy({
  partnerKey: process.env.CLEAREDBY_PARTNER_KEY!,
  resolveUser: async (req) => {
    const s = await getSession(req)
    return s ? { org_id: s.clearedbyOrgId, external_subject: s.userId } : null
  },
})
// proxy.handle(req: Request): Promise<Response>; proxy.clearTokenCache(user?)
```

### expressHandler {#expresshandler}

Adapt a proxy to Express (or any Node framework with `status` / `setHeader` / `send`). Mount it on the same path as `basePath`.

```ts title="expressHandler(proxy: PartnerProxy): (req, res, next?) => Promise<void>"
app.use('/api/clearedby', expressHandler(proxy))
```

## @clearedby/sdk/doctor {#doctor}

The go-live checker. It checks your integration end to end and prints a pass/fail report, with a one-line fix and a docs link for every problem. Run it as a command (`npx @clearedby/sdk doctor`) or call `runDoctor` from a script or CI. Node 18+. It writes only to its own **sandbox org** (`external_id` `__doctor__`, named "Doctor sandbox (safe to delete)"), which it creates on the first run and reuses after that, or to the org you pass with `--org`. Any org key it creates during a run is revoked before it exits, so none pile up.

```bash title="terminal"
CLEAREDBY_PARTNER_KEY=cb_partner_... npx @clearedby/sdk doctor                  # settings + your endpoint
CLEAREDBY_PARTNER_KEY=cb_partner_... npx @clearedby/sdk doctor --full --wait 120 # + a real approval end to end
npx @clearedby/sdk doctor --json > doctor.json                                   # for CI: exit 1 on any ✗
```

| Option | Env | Meaning |
| --- | --- | --- |
| | `CLEAREDBY_PARTNER_KEY` | Your partner key (required). |
| `--base-url <url>` | `CLEAREDBY_BASE_URL` | Default `https://app.clearedby.com`. |
| `--org <id>` | | Use this org instead of the sandbox org. Only a test org: the doctor adds a reviewer `__doctor_reviewer__` (authority over `doctor.noop` only) and, with `--full`, `doctor.noop` clearances. |
| `--url <url>` | | Send the synthetic dispatches here instead of `execution_url` (for example a local build). |
| `--audience <aud>` | | The `audience` your executor verifies. |
| `--full` | | Also run the real flow (below). |
| `--wait <seconds>` | | With `--full`: how long to wait for the delivery and for your completion report. Default 120. |
| `--org-key <key>` | `CLEAREDBY_ORG_KEY` | A `cb_live_` key for the sandbox org. Without it, `--full` uses a key it creates (`name: clearedby-doctor`) and revokes it with `revokeOrgKey` before it exits. |
| `--json` | | Print the report as JSON. |

Exit code: `0` when nothing failed (warnings allowed), `1` when any check failed, `2` for a usage error.

**What it checks, and what each check can and can't prove:**

| Check | Passes when | Can't prove |
| --- | --- | --- |
| Credentials | The partner key reads your settings. | |
| `execution_url` | Set (for the sandbox org, its override or your default) and `https`. `http://localhost` is a warning. | |
| Alerts, retention | `alert_email` or `alert_webhook_url` is set; `retention_days` is set. Warnings only. | |
| a. Signed dispatch accepted | A synthetic dispatch the doctor signs with the sandbox org's signing secret gets `2xx`. It is a `rejected` verdict for `doctor.noop`: it needs no receipt and authorises nothing. | That you execute a genuine `cleared` dispatch (the real flow does). |
| b. Bad signature refused | Signed with the wrong secret: `4xx`. | |
| c. Stale timestamp refused | Correctly signed, 10 minutes old: `4xx`. | |
| d. Tampered params refused | Params changed after signing, `params_hash` recomputed: `4xx`. | |
| e. Redelivery acknowledged | The same work item again, attempt 2: `2xx` or `409`. | Idempotency: a rejected verdict executes nothing either way. `--full` tests it with a genuine receipt. |
| f. Forged receipt refused | A correctly HMAC-signed `cleared` dispatch whose receipt is signed by a key ClearedBy never published: `4xx`. This is what an agent holding an org key could forge. | |
| Real dispatch delivered (`--full`) | A `doctor.noop` proposal, approved by the sandbox reviewer, is delivered by ClearedBy (`GET /v1/gate/:id/delivery` shows `delivered: true`). | |
| Not executed twice (`--full`) | Replaying that genuine, already-delivered approval gets `409`, or `2xx` with `executed: false` / `status: "already_executed"`. `executed: true` fails. | Side effects you don't report: the doctor only sees your answers. A bare `2xx` is a warning. |
| Completion reported (`--full`) | Your executor called `complete()` for the `doctor.noop` within `--wait` seconds. Warning otherwise. | |
| Revoked approval not executed (`--full`) | A second `doctor.noop` (with `params.skip_complete: true`) is approved, delivered, then revoked; replaying its genuine receipt gets `2xx` with `status: "revoked"` or `executed: false`, or a `4xx`. A `409` is a warning: dedupe answered before any `checkStatus`. | That you check status before irreversible *real* actions. |
| Webhooks | The sandbox org's subscriptions (read with the partner key, `listWebhooks(orgId)`) are active with no failed deliveries. Skipped when there are none. | |

The synthetic dispatches can't carry a receipt ClearedBy signed (only ClearedBy can mint one), so every check that needs a genuine receipt runs only with `--full`, where ClearedBy mints the receipts for real.

**What your executor must do with doctor traffic:**

- Requests the doctor sends itself carry the header `clearedby-doctor: 1`. Treat them as a **dry run**: verify and dedupe exactly as usual and answer exactly as you would, but never execute or record anything. ClearedBy's own dispatches never carry this header.
- The action `doctor.noop` is never real. Verify and dedupe it like any dispatch, touch nothing, and report it done with `complete()` (unless `params.skip_complete` is `true`).
- Look the signing secret up by `envelope.org_id` (`getSigningSecret`) if you serve many orgs, so the sandbox org verifies too. An executor that knows only one org's secret fails check a; run the doctor with `--org <that org>`.

**Optional response contract.** Answer your dispatches with JSON `{ "status": "executed" | "already_executed" | "noted" | "revoked" | "dry_run", "executed": true | false, "execution_id": "..." }`. It is optional and ClearedBy ignores it, but it lets the doctor prove double execution (`executed: true` on a repeat) instead of warning that it can't tell.

### runDoctor {#rundoctor}

Runs every check and returns the report. Never throws for a failed check: each problem is a `fail` or `warn` entry with `fix` and `docs`. `report.ok` is `false` when anything failed.

```ts title="runDoctor(opts: DoctorOptions): Promise<DoctorReport>"
import { runDoctor, formatDoctorReport } from '@clearedby/sdk/doctor'

const report = await runDoctor({
  partnerKey: process.env.CLEAREDBY_PARTNER_KEY!,
  full: true,                                  // also run the real flow
  waitSeconds: 120,
  audience: 'https://exec.yourapp.example',
  // baseUrl?, orgId?, executionUrl?, orgKey?, requestTimeoutMs? (10000), pollIntervalMs? (2000),
  // onCheck?(check) for progress, fetch? / executorFetch? for tests
})
if (!report.ok) throw new Error(formatDoctorReport(report))
// report.checks: { id, group, title, status: 'pass' | 'warn' | 'fail' | 'skip', detail?, fix?, note?, docs? }[]
```

Check ids are stable: `credentials.partner_key`, `credentials.sandbox_org`, `settings.execution_url`, `settings.alerts`, `settings.retention`, `endpoint.signed`, `endpoint.bad_signature`, `endpoint.stale_timestamp`, `endpoint.tampered_params`, `endpoint.redelivery`, `endpoint.forged_receipt`, `full.flow`, `full.delivery`, `full.idempotency`, `full.completion`, `full.revoked`, `webhooks`, and `cleanup.org_key` (a warning, only if a key it created could not be revoked). The module also exports the constants `DOCTOR_ACTION` (`'doctor.noop'`), `DOCTOR_HEADER` (`'clearedby-doctor'`), `DOCTOR_EXTERNAL_ID`, `DOCTOR_ORG_NAME` and `DOCTOR_REVIEWER`.

### formatDoctorReport {#formatdoctorreport}

The human-readable report: one line per check (✓ / ⚠ / ✗ / -), then the detail, the fix and the docs link for each problem, and a summary line.

```ts title="formatDoctorReport(report: DoctorReport, opts?: { color?: boolean }): string"
console.log(formatDoctorReport(report, { color: process.stdout.isTTY }))
```

```text title="sample output (abridged)"
Execution endpoint (synthetic dispatches signed by the doctor)
  ✓ a. A correctly signed dispatch is accepted
      A signed, non-cleared doctor.noop dispatch got 200 noted in 11 ms.
  ✗ b. A bad signature is refused
      Your endpoint answered 200 noted in 5 ms to a dispatch signed with the wrong secret.
      Fix: Verify every POST with verifyDispatch(rawBody, headers, { secret, orgId, jwksUrl, audience }) over the raw body bytes, and answer 401 on any DispatchVerificationError.
      Docs: https://www.clearedby.com/docs/partners/security#executor-rules

6 passed, 1 warning, 4 failed, 2 skipped. Not ready for go-live: fix the ✗ items and run it again.
```

### runDoctorCli {#rundoctorcli}

The command line itself (what the `clearedby` bin runs). `argv` excludes `node` and the script. Returns the exit code.

```ts title="runDoctorCli(argv: string[], env?: Record<string, string | undefined>, io?: { out, err, color? }): Promise<number>"
process.exitCode = await runDoctorCli(['doctor', '--json'])
```

## HTTP conventions {#http}

| | |
| --- | --- |
| Base URL | `https://app.clearedby.com` |
| Auth | `Authorization: Bearer <cb_partner_... \| cb_live_... \| cb_dt_...>` |
| Bodies | JSON. Unknown fields are refused with `400 invalid_body`. |
| Errors | `{"error": {"code": "...", "message": "...", "hint": "...", "details": {...}}}` (`hint` and `details` optional). Branch on `code`. |
| Idempotency | `Idempotency-Key` on `POST /v1/gate` (24 h; the same key with a different body is `422 idempotency_key_reused`; a replay answers with header `idempotent-replay: true`) and on `POST /v1/gate/:id/complete` (or `completion_id` in the body). |
| Pagination | Clearances: `limit` + `cursor` / `next_cursor`. Orgs: `limit` + `after` / `next_after`. |
| Partner reads | Read endpoints accept the partner key plus `?org_id=`. Leaving out `org_id` is `400`; another partner's org is `404`. |
| Money | Reviewer authority: integer minor units of the org currency. Approval-rule settings: major units. Params: whatever the action's schema says (Shopify prices are decimal strings, refund `amount` a number). |

## Partner endpoints {#http-partner}

All under `/v1/partner`, with the partner key. Any org that isn't yours is `404 not_found`.

### GET, PATCH /v1/partner/settings {#http-settings}

Account-wide settings. `PATCH` takes any subset; `null` clears a field. Errors: `400 invalid_body`, `400 blocked_destination` (a URL that isn't public HTTPS, DNS included).

```http title="PATCH /v1/partner/settings"
PATCH /v1/partner/settings
Authorization: Bearer cb_partner_...

{ "execution_url": "https://exec.yourapp.example/clearedby/on-decision",
  "notify_url": "https://exec.yourapp.example/clearedby/on-verdict",
  "alert_email": "platform-oncall@yourapp.example",
  "alert_webhook_url": "https://ops.yourapp.example/clearedby/alerts",
  "retention_days": 90 }

200 OK
{ "partner_id": "01K...", "retention_days": 90,
  "execution_url": "https://exec.yourapp.example/clearedby/on-decision",
  "notify_url": "https://exec.yourapp.example/clearedby/on-verdict",
  "alert_email": "platform-oncall@yourapp.example",
  "alert_webhook_url": "https://ops.yourapp.example/clearedby/alerts",
  "alert_webhook_configured": true, "alert_webhook_secret": "...(first time only)",
  "recent_alerts": [], "theme": null,
  "usage": { "period": "2026-09", "total_gates": 48210,
    "by_org_top": [{ "org_id": "01K...", "external_id": "shop_8841", "name": "Acme Outdoor", "total_gates": 31002 }],
    "soft_cap_per_org": 1000000 } }
```

Other fields: `rotate_alert_webhook_secret: true`, `theme` (see [UI theming](/docs/partners/ui#theming)). `usage` is read-only (`GET` and every `PATCH` response): this month's volume and the per-org soft cap, which only triggers the `usage_80` / `usage_100` alerts and never blocks a gate call. Partner accounts, extra partner keys and a higher soft cap are provisioned by ClearedBy: contact us.

### POST /v1/partner/orgs {#http-create-org}

Create an org. `201` with a one-time `api_key` on first creation; `200` with the existing org and no key on a repeat. Errors: `400 invalid_body` (unknown currency, a domain that isn't `*.myshopify.com`, a bad `external_id`).

```http title="POST /v1/partner/orgs"
POST /v1/partner/orgs
Authorization: Bearer cb_partner_...

{ "external_id": "shop_8841", "name": "Acme Outdoor", "currency": "GBP",
  "shop_domains": ["acme-outdoor.myshopify.com"] }

201 Created
{ "org_id": "01K...", "external_id": "shop_8841", "name": "Acme Outdoor",
  "shop_domain": "acme-outdoor.myshopify.com", "shop_domains": ["acme-outdoor.myshopify.com"],
  "currency": "GBP", "execution_url": null, "notify_url": null, "theme": null,
  "plan": "partner", "created_at": "2026-09-24T10:00:00.000Z",
  "created": true, "api_key": "cb_live_..." }
```

### GET /v1/partner/orgs, GET /v1/partner/orgs/:org_id {#http-get-orgs}

List (`?limit=1..500&after=<next_after>&external_id=`) or fetch one. The list answers `{ "orgs": [ ... ], "next_after": "01K..." | null }`; one org has the fields above without `created` / `api_key`.

### PATCH /v1/partner/orgs/:org_id {#http-update-org}

Any of `name`, `currency`, `shop_domains` (replaces the list), `execution_url`, `notify_url`, `theme` (`null` clears an override). At least one. Errors: `400 invalid_body`, `400 blocked_destination`, `404 not_found`.

```http title="PATCH /v1/partner/orgs/:org_id"
PATCH /v1/partner/orgs/01K...
{ "shop_domains": ["acme-outdoor.myshopify.com", "acme-outdoor-eu.myshopify.com"], "notify_url": null }

200 OK
{ "org_id": "01K...", "shop_domains": ["acme-outdoor.myshopify.com", "acme-outdoor-eu.myshopify.com"], "...": "..." }
```

### POST /v1/partner/orgs/:org_id/keys {#http-keys}

Mint another `cb_live_` key. Body optional: `{ "name": "executor" }`.

```http title="POST /v1/partner/orgs/:org_id/keys"
201 Created
{ "org_id": "01K...", "key_id": "01K...", "api_key": "cb_live_...", "prefix": "cb_live_3f2a", "name": "executor" }
```

### GET /v1/partner/orgs/:org_id/keys, DELETE .../keys/:key_id {#http-keys-manage}

`GET` lists the org's keys, newest first, revoked ones included, never the secret. `DELETE` revokes one at once (its next request is `401`) and answers the same shape for that key; it is idempotent. A key id that isn't the org's is `404 not_found`.

```http title="GET /v1/partner/orgs/:org_id/keys"
200 OK
{ "org_id": "01K...", "keys": [
  { "key_id": "01K...", "name": "executor", "prefix": "cb_live_3f2a", "agent_id": null,
    "created_at": "2026-09-01T09:00:00.000Z", "last_used_at": "2026-09-24T10:00:00.000Z",
    "revoked_at": null, "revokes_at": null, "revoked_by": null, "active": true }
] }
```

### POST /v1/partner/orgs/:org_id/keys/:key_id/rotate {#http-keys-rotate}

Body optional: `{ "grace_seconds": 3600 }` (0 to 86400, default 0). Mints a replacement with the same `name` and agent binding and revokes the old key: at once, or once the grace period has passed (`replaced.revokes_at`). The new secret is returned once. Errors: `400 invalid_body` (a bad `grace_seconds`), `404 not_found`, `409 key_revoked` (already revoked or rotated).

```http title="POST /v1/partner/orgs/:org_id/keys/:key_id/rotate"
201 Created
{ "org_id": "01K...", "key_id": "01K...", "api_key": "cb_live_...", "prefix": "cb_live_9c1d", "name": "executor", "agent_id": null,
  "replaced": { "key_id": "01K...", "active": true, "revoked_at": null, "revokes_at": "2026-09-24T11:00:00.000Z",
                "revoked_by": "partner:01K...", "...": "..." } }
```

### PUT, DELETE /v1/partner/orgs/:org_id/reviewers/:external_subject {#http-reviewers}

`PUT` creates (`201`) or replaces (`200`) a reviewer; `DELETE` removes one (`200`, `active: false`; idempotent). `GET /v1/partner/orgs/:org_id/reviewers` lists them (`{ "org_id", "reviewers": [...] }`). Errors: `400 invalid_body`, `400 invalid_subject`, `404 not_found`, `409 email_taken`.

```http title="PUT /v1/partner/orgs/:org_id/reviewers/user_17"
PUT /v1/partner/orgs/01K.../reviewers/user_17
{ "display_name": "Sam R.", "role": "owner", "authority": { "*": 0, "shopify.refund.create": 50000 } }

201 Created
{ "external_subject": "user_17", "user_id": "01K...", "display_name": "Sam R.", "email": null,
  "role": "owner", "authority": { "*": 0, "shopify.refund.create": 50000 }, "channels": [], "active": true }
```

### GET, PUT /v1/partner/orgs/:org_id/rules and POST .../rules/:proposal_id/accept {#http-rules}

`GET` returns `{ settings, summary[], active_version, currency, refund_approvers, pending_proposal? }`. `PUT { "settings": {...} }` answers `200 {"status": "active", ...}` or `202 {"status": "needs_owner_approval", "proposal_id", "summary_diff", ...}`. Accept needs an **owner or admin decision token** (not the partner key). Errors: `400 invalid_body`, `403 forbidden` (not an owner/admin), `409 proposal_superseded`, `409 already_active`.

```http title="PUT /v1/partner/orgs/:org_id/rules"
PUT /v1/partner/orgs/01K.../rules
{ "settings": { "refund_auto_max": 50 } }

202 Accepted
{ "status": "needs_owner_approval", "proposal_id": "01K...", "proposal_version": 3, "strictness": "looser",
  "summary_diff": [ { "key": "refund_auto_max", "action_label": "Refunds",
                      "before": "Refunds over £25 need your OK", "after": "Refunds over £50 need your OK" } ],
  "summary": [ "..." ] }
```

### GET /v1/partner/orgs/:org_id/theme {#http-theme}

The effective theme for one merchant: `{ "org_id": "01K...", "theme": { ... } | null }`.

### POST /v1/partner/orgs/:org_id/erasure, POST /v1/partner/erasure {#http-erasure}

Body `{ "subject_id": "gid://shopify/Customer/7208314339542" }` (never in the URL). Synchronous and idempotent.

```http title="POST /v1/partner/erasure"
200 OK
{ "subject_hash": "9f2c...", "orgs_scanned": 214, "items_redacted": 5,
  "orgs": [ { "org_id": "01K...", "external_id": "shop_8841", "items_redacted": 3, "attestation_seq": 118 } ],
  "failed": [], "complete": true }
```

The per-org call answers `{ "org_id", "external_id", "items_redacted", "attestation_seq" }`.

## Token and decision endpoints {#http-decisions}

### POST /v1/auth/decision-token {#http-decision-token}

Partner key. Body: `org_id`, `external_subject`, optional `work_item_id` (pins it), `ttl_seconds`, `scope` (`decide` default, or `read`). Errors: `404 not_found` (unknown org or person), `403 user_deprovisioned`, `400 invalid_body`.

```http title="POST /v1/auth/decision-token"
{ "org_id": "01K...", "external_subject": "user_17", "work_item_id": "01K...", "ttl_seconds": 120 }

201 Created
{ "token": "cb_dt_...", "token_id": "01K...", "expires_at": "2026-09-24T10:02:00.000Z", "org_id": "01K...",
  "user_id": "01K...", "external_subject": "user_17", "work_item_id": "01K...", "scope": "decide" }
```

### POST /v1/gate/:id/decide {#http-decide}

`Authorization: Bearer cb_dt_...` (a decide token). Body: `decision` (`clear`, `reject`, `send_back`, `escalate`), `reason` (4+ characters for `reject` and `send_back`), `escalate_to` (with `escalate` only). Errors: see [decisions](#err-decisions).

```http title="POST /v1/gate/:id/decide"
{ "decision": "clear" }

200 OK
{ "status": "cleared", "attestation": { "seq": 42, "hash": "..." }, "receipt": { "...": "..." } }
```

## Proposal endpoints {#http-gate}

### POST /v1/gate {#http-propose}

Org key. Body: `action`, `params`, `context`, `proof`, `policy`, `audience`, `mode`, `callback_url`, `timeout`, `parent_item_id`, `reverts`, `on_decision`. Header `Idempotency-Key` recommended. `200` for `cleared`/`rejected`, `202` for `pending`. `?dry=1` evaluates without recording (`200 {"dry": true, "verdict", "rule", ...}`). Errors: see [proposals](#err-proposals).

```http title="POST /v1/gate"
POST /v1/gate
Authorization: Bearer cb_live_...
Idempotency-Key: bf-2026-tags:job-77:v1

{ "action": "shopify.product.tags.update",
  "params": { "store": "acme-outdoor.myshopify.com",
              "changes": [ { "product_id": "gid://shopify/Product/1001", "label": "Trail jacket",
                             "before": ["bf-2025"], "after": ["black-friday"] } ] },
  "audience": "https://exec.yourapp.example",
  "context": { "batch_id": "bf-2026-tags", "summary": "Swap bf-2025 for black-friday" },
  "proof": { "reason": "Preparing Black Friday tags", "confidence": 0.95 } }

200 OK
{ "id": "01K...", "status": "cleared", "decided_by": "policy:auto", "rule": "rules[0]: shopify.product.tags.update",
  "sampled": false, "attestation": { "seq": 17, "hash": "..." }, "receipt": { "...": "..." } }

202 Accepted   (when held)
{ "id": "01K...", "status": "pending", "rule": "...", "sampled": false, "attempt": 1,
  "expires_at": "2026-09-27T10:00:00.000Z", "routed_to": ["..."], "resume": { "mode": "poll", "...": "..." } }
```

### GET /v1/gate, GET /v1/gate/:id, /detail, /events, /permissions {#http-read}

Org key, partner key + `org_id`, or a reviewer token (reads as that person). List query: `status`, `reviewer`, `action_prefix`, `batch_id`, `include` (`params,proof,context,lineage`), `limit`, `cursor`. `/detail?include=events`, `/events?include=lineage`, `/permissions?reviewer=<external_subject>`. Errors: `400 invalid_query`, `404 not_found`, `404 reviewer_not_found`, `403 token_scope`.

```http title="GET /v1/gate/:id/permissions?org_id=...&reviewer=user_22"
200 OK
{ "id": "01K...", "status": "pending",
  "reviewer": { "user_id": "01K...", "external_subject": "user_22", "name": "Priya K." },
  "can": ["reject", "send_back", "escalate"],
  "cannot": [ { "decision": "clear", "status": 403, "code": "no_authority",
                "message": "your authority does not cover 'shopify.refund.create' at this amount" } ],
  "requires_passkey": false, "reason_required": ["reject", "send_back"], "dual_review": null }
```

### POST /v1/gate/:id/evidence {#http-evidence}

Partner key + `?org_id=`. Body `{ "items": [ { "type", "value", "label"?, "source_ref"? } ] }`. `201` with `{ work_item_id, items, attestation }`. Errors: `403 partner_key_required` (an org key), `409 not_pending`, `409 evidence_limit`, `413 evidence_too_large`.

### POST /v1/gate/:id/revoke, POST /v1/gate/:id/withdraw {#http-cancel}

Revoke: `{ "reason": "..." }` (4 to 2,000 characters) with the org key, the partner key + `?org_id=`, or a decision token. Withdraw: `{ "reason"?: "..." }` with the org key or the partner key + `?org_id=`. Errors: see [cancel](#err-cancel).

```http title="POST /v1/gate/:id/revoke?org_id=..."
{ "reason": "customer cancelled the order" }

200 OK
{ "id": "01K...", "status": "revoked", "revoked_at": "...", "revoked_by": "partner:01K...",
  "dispatch": "cancelled", "stopped_partial": false, "attestation": { "seq": 51, "hash": "..." } }
```

### POST /v1/gate/:id/complete, GET /v1/gate/:id/undo {#http-complete}

Org key. Complete body: `status` (`done`, `failed`, `partial`), `completion_id` (or the `Idempotency-Key` header), `items[]`, `delivery_receipt_id`, `executed_params`, `external_ref`, `evidence`, `result`. Undo answers `{ "action", "params", "reverts", "keys" }` for you to submit with `POST /v1/gate`. Errors: see [completion](#err-completion).

```http title="POST /v1/gate/:id/complete"
Idempotency-Key: 01K...:final

{ "status": "done", "delivery_receipt_id": "01K...",
  "items": [ { "key": "gid://shopify/Product/1001", "status": "done", "before": ["bf-2025"], "after": ["black-friday"] } ] }

200 OK
{ "recorded": true, "status": "done", "tier": 1, "diverged": false, "completion_id": "01K...:final",
  "idempotent_replay": false, "receipt_id": "01K...", "delivery_receipt_id": "01K...",
  "items": { "reported": 1, "done": 1, "failed": 0, "skipped": 0, "unknown": 0 },
  "totals": { "approved": 1, "done": 1, "failed": 0, "skipped": 0, "unreported": 0 } }
```

### GET /v1/gate/:id/delivery, POST /v1/gate/:id/redeliver, GET /v1/gate/:id/receipt, GET /v1/gate/:id/wait {#http-delivery}

Org key. Delivery answers `{ "id", "status", "delivery": {...} | null, "deliveries": [...] }`; redeliver `{ "id", "delivery" }`. Receipt answers the stored receipt (`404 no_receipt`, `410 receipt_redacted`). Wait long-polls up to 55 s (`?timeout=<seconds>`, 1 to 55, waits less) and answers the status shape once the clearance leaves `pending` / `escalated`, or `204` (ask again). Wait takes the same credentials as `GET /v1/gate/:id`, so the partner key with `?org_id=` works too.

## Public endpoints {#http-public}

### GET /v1/receipts/:receipt_id/status {#http-receipt-status}

No key. 300 a minute per IP. Errors: `400 invalid_receipt_id`.

```http title="GET /v1/receipts/:receipt_id/status"
200 OK
{ "receipt_id": "01K...", "work_item_id": "01K...", "status": "revoked", "revoked_at": "2026-09-24T10:03:00.000Z" }
```

### GET /.well-known/clearedby-keys {#http-keys-doc}

No key. ClearedBy's Ed25519 public keys: `{ "keys": [ { "kid": "...", "publicKeyHex": "...", "x": "..." } ] }`. `fetchClearedByKeys()` reads it.

## Other org-key endpoints {#http-org}

| Endpoint | Purpose | SDK |
| --- | --- | --- |
| `GET /v1/signing-secrets` (org key, or partner key + `org_id`) | Signing secrets for dispatches and callbacks | `signingSecrets()`, `partner.getSigningSecrets()` |
| `POST /v1/webhooks`, `GET /v1/webhooks`, `DELETE /v1/webhooks/:id` (org key, or partner key + `org_id`) | Lifecycle webhook subscriptions | `createWebhook()`, `listWebhooks()`, `deleteWebhook()`; `partner.createWebhook(orgId, ...)`, `partner.listWebhooks(orgId)`, `partner.deleteWebhook(orgId, id)` |
| `GET /v1/catalogue` | The Shopify action catalogue | `catalogue()` |
| `GET /v1/ledger`, `GET /v1/ledger/verify` | The tamper-evident record | `ledger()`, `verifyLedger()` |
| `GET /v1/policies`, `GET /v1/policies/:name`, `GET /v1/policies/:name/:version`, `POST /v1/policies/:name`, `POST /v1/policies/:name/:version/simulate` | Hand-written policies | `listPolicies()`, `describePolicy()`, `getPolicy()`, `savePolicyDraft()`, `simulatePolicy()` |
| `POST /v1/policies/:name/:version/activate` | Switch a policy on (partner key + `{org_id}`, or an owner/admin decision token) | `partner.activatePolicy()` |
| `GET /v1/stats`, `GET /v1/usage`, `GET /v1/graduation` | Reporting | `stats()`, `usage()`, `graduations()` |

## Outbound messages {#outbound}

| Message | Sent to | Signature | Retries |
| --- | --- | --- | --- |
| Dispatch (v2 envelope) | `execution_url` (cleared) / `notify_url` (others), or an override | `clearedby-signature: t=<unix>,v1=<hex HMAC-SHA256(org signing secret, "<t>.<raw body>")>`; also `clearedby-event: on_decision`, `clearedby-delivery-id` | 6 attempts; `2xx` or `409 already_executed` = delivered |
| Lifecycle webhook | Your `POST /v1/webhooks` URL | `X-ClearedBy-Signature: sha256=<hex HMAC-SHA256(whsec secret, raw body)>` | 6 attempts; switched off after 21 consecutive failures |
| Callback | The gate call's `callback_url` | `X-ClearedBy-Signature: sha256=<hex HMAC-SHA256(org signing secret, raw body)>` | Retried with backoff |
| Partner alert | `alert_webhook_url` | `x-clearedby-signature: sha256=<hex HMAC-SHA256(alert_webhook_secret, raw body)>`, `clearedby-event: partner.alert` | None (also emailed, and listed in `recent_alerts`) |

```ts title="verify-webhook.ts"
import { createHmac, timingSafeEqual } from 'node:crypto'

export function verifyWebhook(rawBody: string, header: string | null | undefined, secret: string): boolean {
  if (!header || !header.startsWith('sha256=')) return false
  const got = Buffer.from(header.slice(7), 'hex')
  const want = createHmac('sha256', secret).update(rawBody).digest()
  return got.length === want.length && timingSafeEqual(got, want)
}
```

```json title="a lifecycle webhook (decision.pending)"
{ "event": "decision.pending", "org_id": "01K...", "occurred_at": "2026-11-20T10:00:01.000Z",
  "data": { "id": "01K...", "action": "shopify.product.tags.update", "status": "pending", "org_id": "01K...",
            "mode": "enforce", "rule": "rules[1]: shopify.product.tags.update", "attempt": 1, "parent_item_id": null,
            "batch_id": "bf-2026-tags", "expires_at": "2026-11-23T10:00:00.000Z",
            "routed_to": [ { "user_id": "01K...", "external_subject": "user_17" } ] } }
```

## Error codes {#errors}

Every error is `{"error": {"code", "message", "hint"?, "details"?}}` with the status below.

### Credentials (any endpoint) {#err-credentials}

| Status | Code | When, and what to do |
| --- | --- | --- |
| 401 | `unauthorized` | The key is missing, malformed, unknown or revoked. |
| 401 | `invalid_token` | The decision token is malformed, unknown, expired or already used. Mint a new one. |
| 403 | `forbidden` | The right kind of credential for a different job: a key trying to decide, a non-owner token accepting rules, a reviewer trying to withdraw. |
| 403 | `token_scope` | A token pinned to another clearance, or a read token trying to write. |
| 403 | `user_deprovisioned` | That reviewer was removed. |
| 403 | `partner_key_required` | Evidence attach with an org key. |
| 403 | `agent_inactive`, `agent_mismatch` | The key is bound to a registered agent that is inactive, or `context.agent_id` names another agent. |
| 429 | `rate_limited` | Slow down and retry after a few seconds. |

### Proposals: POST /v1/gate {#err-proposals}

| Status | Code | When, and what to do |
| --- | --- | --- |
| 400 | `invalid_body` | Not JSON, an unknown field, or a wrong type. The message names the field. |
| 422 | `reserved_context_key` | `context` set a key ClearedBy owns (`on_decision`, `on_decision_override`, `on_decision_attestation`, `agent_verified`, `test`, anything starting `cb_`). Use the top-level fields. |
| 422 | `unknown_action` | A `shopify.*` action not in the catalogue (`details.valid_actions`). |
| 422 | `invalid_params` | Params fail the action's schema (`details.issues`). |
| 422 | `count_mismatch` | `count` isn't `changes.length`. Leave `count` out. |
| 413 | `batch_too_large` | More than 10,000 changes. Split and share `context.batch_id`. |
| 422 | `store_not_allowed` | `params.store` isn't one of the org's `shop_domains`. |
| 422 | `store_not_configured` | A partner org with no stores. `updateOrg` first. |
| 422 | `subject_id_required`, `invalid_subject_id` | A shopper-related proposal without a valid `context.subject_id`. |
| 422 | `idempotency_key_reused` | The same `Idempotency-Key` with a different body within 24 h. |
| 409 | `idempotency_in_progress` | A request with this key is still running. Retry shortly. |
| 422 | `no_active_policy` | The named `policy` isn't active, or the org has none. |
| 404 | `parent_not_found` | Resubmit: no such parent. |
| 409 | `parent_not_sent_back`, `parent_already_resubmitted` | Resubmit: the parent wasn't sent back, or already has its one resubmission. |
| 422 | `resubmit_action_mismatch` | A resubmission must keep the parent's action. |
| 404 | `reverts_not_found` | Undo: the target isn't in this org. |
| 409 | `reverts_not_cleared`, `reverts_not_completed` | Undo: the target wasn't approved, or has no usable `done`/`partial` report. |
| 422 | `not_reversible`, `wrong_inverse` | Undo: refunds and cancellations can't be undone; or the action isn't the target's inverse. |

### Decisions {#err-decisions}

| Status | Code | When, and what to do |
| --- | --- | --- |
| 400 | `invalid_body` | Unknown decision, a missing or short reason, or `escalate_to` without `escalate`. |
| 404 | `not_found` | The reviewer or clearance isn't in that org. |
| 409 | `not_pending`, `already_decided` | Already decided (possibly at the same moment). Refresh. |
| 403 | `no_authority` | Their authority doesn't cover this action at this amount. They can still escalate. |
| 403 | `self_approval` | `context.agent_user` names this person. |
| 403 | `requester_cannot_approve` | Two-person rule: the person who asked (`requested_by_subject`) can't approve. |
| 409 | `already_approved` | Two-person rule: this person already approved. |
| 401 | `passkey_required_not_supported_for_partner` | The rule needs a passkey approval. Don't use `attest: passkey` in partner orgs. |
| 422 | `escalate_target_not_found`, `escalate_target_lacks_authority` | `escalate_to` isn't an active reviewer, or can't cover it. |
| (in `cannot`) | `revision_cap_reached` | Permissions only: a send-back would be recorded as `send_back_forces`. |

### Evidence {#err-evidence}

| Status | Code | When |
| --- | --- | --- |
| 409 | `not_pending` | Evidence only attaches while a clearance is waiting. |
| 409 | `evidence_limit` | 100 items already attached. |
| 413 | `evidence_too_large` | Over 64 KB in one call. |

### Cancel {#err-cancel}

| Status | Code | When |
| --- | --- | --- |
| 400 | `reason_required` | Revoke needs a reason of at least 4 characters. |
| 409 | `not_cleared` | Revoke: not approved, or already revoked. |
| 409 | `already_executed` | Revoke: a final report exists. Propose the undo. |
| 409 | `not_pending` | Withdraw: already decided. |

### Completion and undo {#err-completion}

| Status | Code | When |
| --- | --- | --- |
| 409 | `not_cleared` | Only an approved change can have been executed. |
| 409 | `completion_conflict` | The same completion id with a different body. |
| 409 | `already_completed` | A `done` or `failed` report already closed it. |
| 409 | `item_already_done` | An item key already reported `done` earlier. |
| 400 | `invalid_body` | A duplicate item key, or `Idempotency-Key` and `completion_id` differ. |
| 409 | `nothing_to_undo`, `reverts_not_completed` | Nothing was reported `done`, or a `partial` report has no items. |
| 422 | `needs_external_ref`, `unsupported`, `not_reversible` | See the reversibility table in the [guide](/docs/partners/guide#cancel-undo). |
| 410 | `redacted` | The clearance was erased. |

### Dispatch and receipts {#err-dispatch}

| Status | Code | When |
| --- | --- | --- |
| 409 | `not_decided` | Redeliver: still waiting. |
| 409 | `revoked` | Redeliver: revoked; never delivered again. |
| 409 | `in_flight` | Redeliver: a send is in progress. |
| 404 | `no_dispatch` | Redeliver: no dispatch applies to this verdict. |
| 429 | `rate_limited` | Redeliver: 1 per clearance per 30 s, 30 per org per minute. |
| 404 | `no_receipt` | Receipt: not approved in enforce mode. |
| 410 | `receipt_redacted` | Receipt: erased. |
| 400 | `invalid_receipt_id` | Receipt status: not a valid id. |

### Partner administration {#err-partner}

| Status | Code | When |
| --- | --- | --- |
| 400 | `invalid_body`, `invalid_query`, `invalid_subject` | Validation failed (unknown currency, a custom storefront domain, a bad `external_subject`, a missing `org_id` with the partner key). |
| 400 | `blocked_destination` | A URL that isn't public HTTPS (private, loopback, link-local or metadata IP, or unresolvable). |
| 404 | `not_found` | The org isn't yours, or the reviewer, key or webhook doesn't exist in it. |
| 404 | `reviewer_not_found` | The `reviewer` query names nobody in the org. |
| 409 | `email_taken` | Another reviewer in the org has that email. |
| 409 | `key_revoked` | Rotate: that key is already revoked or already rotated. Rotate its replacement (`listOrgKeys`). |
| 409 | `proposal_superseded` | A newer rules change replaced this proposal. |
| 409 | `already_active` | That rules proposal or policy version is already on. |
| 403 | `owner_approval_required` | Your partner key tried to switch on a looser (or incomparable) policy. Use an owner/admin token. |
| 500 | `internal_error` | Our side. Safe to retry with the same idempotency key. |

### Partner proxy (to the browser) {#err-proxy}

The partner proxy answers its own errors in the same envelope: `401 unauthenticated` (`resolveUser` returned null), `403 not_a_reviewer` (the person isn't a reviewer in that org), `403 cross_site` (a write from another origin), `404 not_found` (a route outside the fixed list), `405 method_not_allowed`, `400 invalid_body` / `invalid_query` / `reason_required`, `413 body_too_large`, `415 unsupported_media_type`, `502 upstream_auth` (ClearedBy refused the partner key) and `502 upstream_unavailable`. Everything else is ClearedBy's own `code` and `message`, passed through.
