# ClearedBy partner integration: full implementation spec > One self-contained Markdown file for AI coding agents. It covers the concepts, the exact integration steps, every `@clearedby/sdk` and `@clearedby/react` export, every HTTP endpoint a partner uses, every error code, and the security rules (MUST). Implement from this file alone. Human-readable version: https://clearedby.com/docs/partners Generated from the Markdown sources at https://clearedby.com/docs/partners/*.md (concepts, quickstart, api, ui, security), in that order. ## How to use this file (for coding agents) You are integrating ClearedBy, an approval layer for AI agents, into a platform (the "partner") that serves many merchants. Shopify is the worked example. Read the whole file before writing code. Then: 1. **Ask the user for, or find in the codebase:** the web framework (Next.js App Router, Express, other), the auth/session system (how to get the signed-in user and which merchant they are working in), the database (for keys, secrets and the executor's dedupe table), the job queue (if any), and the secret store. Never invent a ClearedBy key: the partner key (`cb_partner_...`) comes from ClearedBy and goes in a server-only environment variable, `CLEAREDBY_PARTNER_KEY`. 2. **Build in this order**, each step testable on its own: 1. Partner settings, once: `partner.updateSettings({ execution_url, notify_url?, alert_email })`. `execution_url` must be a public HTTPS URL (use a tunnel in development). 2. Merchant onboarding, in the partner's own signup/connect flow: `partner.createOrg({ external_id, name, currency, shop_domains })` (store `api_key` as the agent key), `partner.createOrgKey(orgId, { name: 'executor' })`, `partner.getSigningSecret(orgId)`, `partner.upsertReviewer(...)` for each person who approves, and `partner.createWebhook(orgId, ...)` for lifecycle events. Rotate keys later with `partner.rotateOrgKey(orgId, keyId, { graceSeconds })`. 3. The executor route (`execution_url`): raw body → `verifyDispatch` → dedupe on `work_item_id` → execute only the receipt's `params` after re-checking live state → `complete()`. Follow every MUST rule in the Security section. 4. The review UI: the partner proxy (`createPartnerProxy` with `resolveUser` from the partner's session) at `/api/clearedby/[...path]`, and `@clearedby/react` components (`ClearedByProvider`, `ApprovalQueue`, `ReviewPanel`, `RulesSummary`), themed with `partner.updateSettings({ theme })` or the CLI. 5. The agent side: `new ClearedBy({ apiKey: agentKey }).gate({ action, params, context, proof, audience, idempotencyKey })` instead of acting directly; handle `sent_back` with `resubmit`. 6. Webhook receiver: verify `X-ClearedBy-Signature`, re-read the clearance, refresh the UI (`useRevalidate`). 3. **Never**: put the partner key or any `cb_` token in browser code or an agent prompt; take `org_id` or `external_subject` from a request body; execute from a webhook or from anything other than a verified `cleared` dispatch; dedupe on the receipt nonce; give the agent store write credentials. 4. **Verify**: run a dry run (`check`) for each action shape the agent produces; propose one change that the default rules hold (a price change), approve it in the UI, and confirm the executor logged it and `delivery(id)` shows `delivered: true`. Then run the go-live checker, `npx @clearedby/sdk doctor --full`, and fix every ✗ it reports (each comes with a one-line fix). The executor must treat requests carrying `clearedby-doctor: 1` as dry runs and never act on the action `doctor.noop`. Package versions this spec describes: `@clearedby/sdk` 0.1.0, `@clearedby/react` 0.1.0, API v1. Base URL: `https://app.clearedby.com`. --- # Concepts ClearedBy is the approval layer between your AI agent and your merchant's store. The agent never writes to the store directly. It **proposes** a change. The merchant's **approval rules** decide whether a person needs to see it. A **reviewer** approves it inside **your** product. ClearedBy issues a **signed authorisation** and **dispatches** it to your **executor**, which makes exactly that change with its own store credentials and **reports** what happened. ClearedBy keeps a tamper-evident record of the whole chain. The worked example throughout is Shopify, but the flow is the same for any action. ## The life of one change {#lifecycle} 1. **Propose.** Your agent calls `POST /v1/gate` with the org's `cb_live_` key: an `action`, the exact `params`, optional `context` and a `proof` (its case for the change). 2. **Policy.** The merchant's approval rules clear small, safe changes on their own (`cleared`), refuse what is never allowed (`rejected`) and hold the rest for a person (`pending`). 3. **Human.** A reviewer opens the held change in your app and approves (`clear`), declines (`reject`), sends it back for a revision (`send_back`) or hands it to someone else (`escalate`). 4. **Authorise.** Every approval carries an Ed25519-signed **Authorisation Receipt** naming the org, the clearance, the action and the exact params. 5. **Dispatch.** ClearedBy POSTs a signed v2 envelope carrying the receipt to your `execution_url`. Retries are automatic. 6. **Execute.** Your executor verifies the dispatch (`verifyDispatch`), checks the store's current state, and makes the change. 7. **Report.** Your executor calls `POST /v1/gate/:id/complete` with per-item results. ClearedBy compares them with what was approved. Nothing reaches the store without step 4. A compromised agent can at worst propose. ## Who holds what {#credentials} | Credential | Format | Held by | Can | Can't | | --- | --- | --- | --- | --- | | Partner key | `cb_partner_` + 32 hex | Your backend only | Partner settings; create and manage orgs, keys (list, revoke, rotate), webhooks, reviewers, rules and themes; read any of your orgs' clearances (with `org_id`); read org signing secrets; attach verified evidence; mint decision tokens; revoke and withdraw; erasure | Propose (`POST /v1/gate`), approve | | Org key | `cb_live_...` | Your agent and your executor, one or more per org | Propose, dry-run, read, report completions, build undos, subscribe to webhooks, revoke its own approvals, withdraw its own requests, read the signing secret, redeliver | Approve | | Decision token | `cb_dt_...` | Your backend, for seconds | `scope: "decide"` (default): record ONE decision for ONE named reviewer (single use, 1 to 300 s, default 120). `scope: "read"`: read as that reviewer (reusable, up to 900 s, default 600) | Anything else | A partner key only sees the orgs it created: any other org id is `404 not_found`. No key can approve, and the agent that asked for a change can never approve it. The base URL for every call is `https://app.clearedby.com`. Bodies are JSON and unknown fields are rejected (`400 invalid_body`). Every error is `{"error": {"code", "message", "hint"?, "details"?}}`: branch on `code`. ## Orgs and stores {#orgs} Create **one org per merchant company** with `POST /v1/partner/orgs`, keyed by your own `external_id` (idempotent: a repeat returns `200` with the same org and no key). An org has: - `currency`: its base currency (ISO 4217). Reviewer authority is in minor units of it. Unset means GBP. - `shop_domains`: the permanent `*.myshopify.com` domains its keys may act on (up to 50). Every `shopify.*` proposal names its store in `params.store`. A store not on the list is `422 store_not_allowed`; a partner org with no stores is `422 store_not_configured`. So one merchant's key can never act on another merchant's store. - Its own `cb_live_` keys. The first is returned once by `POST /v1/partner/orgs`; mint more with `POST /v1/partner/orgs/:org_id/keys` (use one for the agent and another for the executor). - A **signing secret** (stable per org), which signs the dispatches to your executor. Read it with `GET /v1/signing-secrets?org_id=` and the partner key. - Optional per-org overrides of your partner `execution_url`, `notify_url` and `theme` (`PATCH /v1/partner/orgs/:org_id`). - Approval rules, installed and switched on at creation. `external_id` and `external_subject` are 1 to 200 characters from `A-Z a-z 0-9 . _ : @ | + = -`. ## Reviewers and authority {#reviewers} A reviewer is a person at the merchant who can approve. You identify them with your own id, the `external_subject`, and create or replace them with `PUT /v1/partner/orgs/:org_id/reviewers/:external_subject`: | Field | Required | Notes | | --- | --- | --- | | `display_name` | yes | Shown in the audit trail. | | `role` | yes | `owner`, `admin` or `reviewer`. Only owners and admins can accept looser rules. | | `authority` | yes | Action name → the largest amount (minor units of the org currency) they may approve. Replaces the whole map. | | `email` | no | Stored for the record only. Never used to sign in. | | `channels` | no | Where ClearedBy announces held items to them. Default `[]`: ClearedBy never contacts them. | Authority keys are **exact action names** or `*`. There are no prefix patterns: `shopify.*` is not a wildcard here. Actions with no `params.amount` (tags, stock, prices, product edits, discounts) count as amount `0`, so `{"*": 0}` lets someone approve all of those but no money. `{"*": 0, "shopify.refund.create": 50000}` adds refunds up to 500.00 in the org currency. `DELETE .../reviewers/:external_subject` stops their authority at once and keeps their history. Provisioned reviewers have no ClearedBy login. ## Clearances and statuses {#statuses} Each proposal becomes a **clearance** (also called a work item) with an id (a ULID). | Status | Meaning | Final? | | --- | --- | --- | | `pending` | Held, waiting for a person. | No | | `escalated` | Handed to a more senior person, or escalated because nobody decided in time. | No | | `cleared` | Approved, by a rule or a person. Carries a receipt. Your executor may act. | Yes, until revoked | | `rejected` | Refused, by a rule or a person. | Yes | | `sent_back` | Returned to the agent with a reason. The agent resubmits as a new, linked clearance (`parent_item_id`, `attempt`). | Yes, for this attempt | | `expired` | Nobody answered within `timeout_hours`. Nothing happens: a lapsed request is never approved automatically. | Yes | | `revoked` | Approved, then cancelled before it ran. | Yes | | `withdrawn` | Pulled back by the side that asked, while still open. | Yes | `POST /v1/gate` answers `200` with `cleared` or `rejected`, or `202` with `pending`. ## Receipts {#receipts} An **Authorisation Receipt** is a small JSON document signed with Ed25519 by ClearedBy alone. It names the org (`principal`), the clearance (`work_item_id`), the `action`, the exact `params` and their `params_hash`, who decided (`decided_by`), who it is for (`audience`, from the gate call) and when it expires (10 minutes after issue, 30 s clock skew allowed). Anyone can verify it offline against `https://app.clearedby.com/.well-known/clearedby-keys`. Change one character of the params and the signature breaks. Whether it has since been **revoked** is a separate, online question: `GET /v1/receipts/:receipt_id/status` (public, no key). Every dispatch attempt carries a freshly minted receipt with a new `receipt_id` and `nonce`, so dedupe execution on `work_item_id`, never on the nonce. ## Where approvals are sent {#dispatch-routing} For each decided clearance, ClearedBy POSTs the signed v2 dispatch envelope to the **first** of these that is set: 1. the gate call's own `on_decision..url`; 2. the judging policy's `on_decision..url` (hand-written policies only); 3. the org's override (`PATCH /v1/partner/orgs/:org_id` with `execution_url` / `notify_url`); 4. your partner default (`PATCH /v1/partner/settings`): `execution_url` for `cleared`, `notify_url` for `rejected`, `expired` and `sent_back`. If none is set, nothing is dispatched for that verdict. Org and partner URLs are read at send time, so a change applies at once (retries included). A revoked clearance is never dispatched. Only `cleared` authorises anything; the other verdicts are notifications. The envelope is signed `clearedby-signature: t=,v1=.")>` and carries `clearedby-event: on_decision` and `clearedby-delivery-id`. Your executor has 10 seconds to answer. Any `2xx`, or `409 {"status":"already_executed"}`, counts as delivered. Anything else is retried: 6 attempts in total (now, then about 1 min, 4 min, 16 min, 1 h, 1 h). When retries run out you get a `dispatch_gave_up` partner alert; fix the executor and `POST /v1/gate/:id/redeliver`. ## Approval rules {#approval-rules} Every new org starts with plain-English approval rules, already on. You show them as sliders and toggles; ClearedBy turns them into a policy. You can make them **stricter** yourself (on at once); making them **looser** needs an owner or admin of the merchant to accept (`202 needs_owner_approval`, then `POST .../rules/:proposal_id/accept` with that person's decision token). Amounts here are in **major units** of the org currency (`25` = £25), unlike reviewer authority. | Setting | Default | Meaning | | --- | --- | --- | | `tags_auto_max_products` | `200` | Tag changes up to this many products clear on their own. `0` = always ask. (0 to 10,000) | | `inventory_auto_max_items` | `50` | Stock updates up to this many items clear on their own. `0` = always ask. | | `price_changes` | `"always_review"` | Or `"review_drops_over_pct"`: rises, and drops up to `price_drop_review_pct`, clear on their own. | | `price_drop_review_pct` | `30` | 0 to 100. ClearedBy computes the largest drop itself. | | `discounts` | `"always_review"` | The only option for now. | | `refund_auto_max` | `25` | Refunds up to this clear on their own. `0` = every refund needs an OK. | | `refund_dual_above` | `250` | Refunds over this need two different people. `null` = never. At least `refund_auto_max`. | | `refund_daily_auto_cap` | `250` | Once this much is refunded in 24 h, every further refund needs an OK. `null` = no cap. | | `refund_per_order_cap` | `25` | Refunds on one order adding up past this in 30 days need an OK. `null` = no cap. | | `order_cancel` | `"always_review"` | The only option for now. | | `timeout_hours` | `72` | Unanswered requests lapse (never auto-approve). 1 to 720. | | `spot_checks` | `false` | Occasionally hold something that would clear on its own. | | `spot_check_pct` | `5` | How often when on: 1 to 25 (%). | Anything that isn't a Shopify catalogue action always needs a person. Until a second reviewer has refund authority, refunds over `refund_dual_above` need one OK (and the summary says so); two-person approval switches on by itself when you add the second. ## Evidence: claims vs verified facts {#evidence} Everything the agent sends in `proof` is its own word and is labelled `agent_claim` ("Agent says"), whatever it contains. Facts your backend looks up itself and attaches with the partner key (`POST /v1/gate/:id/evidence?org_id=`) are `partner_verified` ("Verified by "). Figures ClearedBy computes (batch counts, the largest price drop, the currency check, running totals a rule used) are `clearedby_computed` ("Checked by ClearedBy"). The detail view returns them split as `evidence.verified` and `evidence.claims`. Attaching evidence never re-evaluates a clearance or unlocks `clear`. Evidence card types the review UI renders: `threshold`, `entity`, `timeline`, `table`, `media`, `source`, `conversation`, `note`; any other `type` falls back to a key/value card. ## Webhooks {#webhooks} Lifecycle webhooks tell your backend something changed (for inboxes and notifications). Subscribe **per org**: `POST /v1/webhooks {url, events, filters?}` with the org's `cb_live_` key, or with your partner key and `?org_id=` (`partner.createWebhook(orgId, ...)`). The response includes the signing `secret` (`whsec_...`) once. | Event | When | Payload | | --- | --- | --- | | `decision.pending` | Held for a person (including resubmissions). Usually within 1 to 2 s of the proposal. | Light | | `decision.escalated` | Escalated by a reviewer, or on timeout. Adds `escalated_to`, `escalated_by`, `reason: "timeout"`. | Light | | `decision.sent_back` | A reviewer sent it back. Adds `decided_by`. | Light | | `decision.revoked` | An approval was cancelled before it ran. Adds `revoked_at`, `revoked_by`, `reason`, `dispatch`, `receipt_id`. | Light | | `decision.withdrawn` | An open request was withdrawn. Adds `withdrawn_at`, `withdrawn_by`, `reason`. | Light | | `decision.cleared` | Approved. | Full: `params`, `context`, `attestation`, `receipt` | | `decision.rejected` | Rejected by a rule, a person or a timeout. | Full | | `decision.expired` | Nobody answered in time. | Full | | `decision.completed` | Your executor reported. `completion_status`, `tier`, `diverged`, `item_counts`, `totals`, `after_revoke`. | Completion | | `graduation.proposed` | ClearedBy suggests loosening a hand-written policy rule that history shows is safe. Partners on the approval rules can ignore it. | `proposal_id`, `policy`, `rule_ref`, `evidence`, `proposed_change` | The envelope is `{event, org_id, occurred_at, data}`. Light payloads carry `id`, `action`, `status`, `org_id`, `mode`, `rule`, `attempt`, `parent_item_id`, `batch_id`, `expires_at` and `routed_to`, never `params`: fetch `GET /v1/gate/:id/detail` when you need them. Every webhook is signed `X-ClearedBy-Signature: sha256=` (no timestamp: treat each event as "re-read this clearance" and dedupe on `event` + `data.id`). A `2xx` within 10 s is delivered; failures retry like dispatches. After 21 consecutive failures the subscription is switched off and you get a partner alert. Every webhook and dispatch is sent right after the change it describes is saved, usually within 1 to 2 seconds: human decisions, escalations, send-backs, revokes, withdrawals, completions and automatic rule outcomes alike (the gate response already carries an automatic verdict). A handler that reads `GET /v1/gate/:id/detail` or the receipt status straight away sees the new state. A failed first attempt is retried from about a minute later. Timeouts are checked every minute. ## Partner alerts {#alerts} Operational problems in your orgs go to **you**, not the merchant: an email to `alert_email` and one POST (no retries) to `alert_webhook_url`, signed `x-clearedby-signature: sha256=` with `clearedby-event: partner.alert`. Kinds: `webhook_subscription_deactivated`, `outbound_credential_disabled`, `dispatch_gave_up`, and the usage alerts `usage_80` and `usage_100`. The last 20 are in `recent_alerts` on `GET /v1/partner/settings`. ## Usage and the soft cap {#usage} Partner orgs are unmetered: a gate call is never blocked, rejected or slowed for volume. Each org has a monthly **soft cap** of gated items (`soft_cap_per_org`, default 1,000,000; contact ClearedBy to raise it for your account). When an org reaches 80% and then 100% of it in a month, you get one `usage_80` and one `usage_100` partner alert, with `detail: { period, total_gates, soft_cap_per_org, threshold_pct }`. Each fires at most once per org per month (UTC calendar month); an org that jumps past 100% between checks gets only `usage_100`. Checks run hourly. `GET /v1/partner/settings` returns this month's volume as `usage: { period, total_gates, by_org_top, soft_cap_per_org }`, where `by_org_top` is your busiest orgs (up to 20). ## Cancel, withdraw, undo {#cancel-undo} | Where it is | Use | Who may | | --- | --- | --- | | Still open (`pending`, `escalated`) | **Withdraw**: `POST /v1/gate/:id/withdraw` | The org key, or the partner key with `org_id`. Reviewers reject instead. | | Approved, no final report | **Revoke**: `POST /v1/gate/:id/revoke`, `reason` 4 to 2,000 characters | The partner key with `org_id`; the org key; or a decision token for an owner, admin, or a reviewer whose authority covers the action. | | Done (final `done` or `partial` report) | **Undo**: `GET /v1/gate/:id/undo` builds the inverse proposal; submit it with `POST /v1/gate` | The org key. The undo goes through the rules like any change. | A revoke stops queued deliveries, mints no new receipts, and makes every receipt for the clearance answer `revoked` within about 5 seconds. If the dispatch was already `delivered` or `in_flight`, your executor must catch it with the status check. | Action | Class | Undo | | --- | --- | --- | | `shopify.product.update` | Reversible | Same action, each field's before/after swapped | | `shopify.product.tags.update` | Reversible | Same action, before/after swapped | | `shopify.price.update` | Reversible | Same action, before/after swapped | | `shopify.inventory.set` | Reversible (check sales since) | Same action, before/after swapped | | `shopify.discount.create` | Compensable | `shopify.discount.disable`; needs the discount GID as the completion's `external_ref` (else `422 needs_external_ref`) | | `shopify.discount.disable` | Compensable | Re-create it yourself (`422 unsupported`) | | `shopify.refund.create` | Irreversible | None (`422 not_reversible`) | | `shopify.order.cancel` | Irreversible | None (`422 not_reversible`) | ## Data protection {#data-protection} - **Send references, not profiles**: order ids and customer GIDs, not names, emails or addresses. Never card data, passwords, government ids or health data. - **The `subject_id` rule**: a proposal about a shopper (action under `shopify.refund.*`, `shopify.order.*` or `shopify.customer.*`, or params with a `customer_id`, `customer` or `email` key up to 4 levels deep) must name the shopper in `context.subject_id` (a string of up to 256 characters; for Shopify, `gid://shopify/Customer/`). Partner orgs refuse it otherwise: `422 subject_id_required` / `422 invalid_subject_id`. Dry runs check it too. - **Erasure**: `POST /v1/partner/orgs/:org_id/erasure` (one org) or `POST /v1/partner/erasure` (all your orgs), body `{"subject_id"}`. Synchronous and idempotent. If `complete` is `false`, retry. - **Retention**: `retention_days` (1 to 3,650) on partner settings. A daily job overwrites readable data older than that; pending items are never purged. ## Limits {#limits} | Limit | Value | | --- | --- | | Partner key rate | 600 requests a minute (read tokens share it) | | Org key rate | 60 requests a minute per key, all endpoints together | | Receipt status (public) | 300 a minute per client IP | | Redeliver | 1 per clearance per 30 s; 30 per org per minute | | Changes per proposal | 10,000 (`413 batch_too_large`); split larger jobs and share `context.batch_id` | | Items per completion report | 10,000 | | Verified evidence | 1 to 20 items and 64 KB per call; 100 per clearance | | Stores per org | 50 | | `subject_id` | up to 256 characters | | List page | 1 to 100 clearances (default 50); 1 to 500 orgs (default 100) | | Receipt validity | 10 minutes (30 s skew) | | Decision token | decide: 1 to 300 s (default 120), single use; read: up to 900 s (default 600) | | Dispatch signature tolerance | 300 s | | Your reply to a dispatch or webhook | 10 s | | Idempotency keys | 24 hours | | Long-poll `GET /v1/gate/:id/wait` | up to 55 s, then `204` | | Send-backs | 3 per lineage in the merchant rules; the next becomes a rejection | --- # Quickstart This walks through the whole integration once, with the smallest code that is still correct. Shopify is the worked example, but nothing touches a real store: the executor logs the change instead of calling Shopify. The [guide](/docs/partners/guide) explains each piece in depth; the [API reference](/docs/partners/api) has every signature. ### Before you start {#before} You need: - **A partner key** (`cb_partner_...`) from ClearedBy. Partner accounts are provisioned by ClearedBy: contact us for a partner account, or ask your ClearedBy contact for a key. It goes in your server's environment only: never in a browser bundle, an agent prompt or a log line. - **Node 18 or later** and a **Next.js 14+ app using the App Router**. Starting fresh: `npx create-next-app@latest my-app --ts --app`. - **A public HTTPS URL for your dev server.** ClearedBy refuses to send approvals to `localhost` or private addresses (`400 blocked_destination`), so run a tunnel. For example, with Cloudflare's free quick tunnel: `npx cloudflared tunnel --url http://localhost:3000`. It prints a URL like `https://quiet-river-1234.trycloudflare.com`. Keep it running. - **A Shopify store domain** to register (for example your development store, `acme-dev.myshopify.com`). Nothing is written to it in this quickstart. ## Install and configure {#install} ```bash title="terminal" npm install @clearedby/sdk @clearedby/react npm install -D tsx ``` ```bash title=".env.local" # From ClearedBy. SERVER ONLY: never prefix it with NEXT_PUBLIC_. CLEAREDBY_PARTNER_KEY=cb_partner_0123456789abcdef0123456789abcdef # Your tunnel URL from "Before you start" (no trailing slash). PUBLIC_URL=https://quiet-river-1234.trycloudflare.com ``` The setup scripts below are `.mts` files (ES modules, so top-level `await` works in any project) run with `tsx`. They read `.env.local` with Node's `--env-file` flag (Node 20.6+). On Node 18, export the variables in your shell instead. **Expected result:** `npm ls @clearedby/sdk @clearedby/react` shows both packages. ## Set your execution URL and alert email {#settings} Once per partner account, tell ClearedBy where approved changes go (your executor, which you build in step 7) and where operational alerts go. Every org you create from now on uses these; there is nothing to configure per org. ```ts title="scripts/01-settings.mts" import { ClearedByPartner } from '@clearedby/sdk' const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! }) const settings = await partner.updateSettings({ execution_url: `${process.env.PUBLIC_URL}/api/executor`, // cleared changes are POSTed here alert_email: 'platform-oncall@yourapp.example', // dispatch failures, disabled webhooks }) console.log(settings.execution_url, settings.alert_email) ``` ```bash title="terminal" npx tsx --env-file=.env.local scripts/01-settings.mts ``` **Expected result:** it prints your `https://.../api/executor` URL and the email. A `400 blocked_destination` means the URL isn't public HTTPS (check the tunnel). If your quick tunnel's URL changes later, run this script again. ## Create a company {#create-org} One ClearedBy org per merchant company, keyed by your own id for it. The call is idempotent on `external_id`: running it again returns the same org with `created: false` and no key. ```ts title="scripts/02-create-org.mts" import { ClearedByPartner } from '@clearedby/sdk' const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! }) const org = await partner.createOrg({ external_id: 'shop_demo_1', // YOUR id for this merchant name: 'Acme Outdoor (dev)', currency: 'GBP', // ISO 4217: reviewer limits are in this currency shop_domains: ['acme-dev.myshopify.com'], // permanent *.myshopify.com domains its keys may act on }) if (!org.created) throw new Error('Org already exists: its first key was shown once, when it was created') // A second key, so the executor's key can be rotated separately from the agent's. const executorKey = await partner.createOrgKey(org.org_id, { name: 'executor' }) // The org's dispatch signing secret: your executor checks every dispatch with it. const signingSecret = await partner.getSigningSecret(org.org_id) console.log(`CLEAREDBY_ORG_ID=${org.org_id}`) console.log(`CLEAREDBY_AGENT_KEY=${org.api_key}`) console.log(`CLEAREDBY_EXECUTOR_KEY=${executorKey.api_key}`) console.log(`CLEAREDBY_SIGNING_SECRET=${signingSecret}`) ``` ```bash title="terminal" npx tsx --env-file=.env.local scripts/02-create-org.mts >> .env.local ``` **Expected result:** four new lines at the end of `.env.local`: the org id (`01K...`, a ULID), two `cb_live_...` keys and the signing secret. The keys are shown **once**; in production, put them in your secret store. The org already has the default approval rules switched on: price changes always need a person, which is what the next steps rely on. ## Add a reviewer {#reviewer} A reviewer is a person at the merchant who can approve, identified by **your** id for them (`external_subject`). Their authority maps action names to the largest amount they may approve, in minor units; `"*": 0` covers every action that carries no amount (tags, stock, prices, product edits) but no money. ```ts title="scripts/03-reviewer.mts" import { ClearedByPartner } from '@clearedby/sdk' const partner = new ClearedByPartner({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY! }) const sam = await partner.upsertReviewer(process.env.CLEAREDBY_ORG_ID!, '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 }) console.log(sam.created ? 'created' : 'updated', sam.external_subject, sam.role) ``` ```bash title="terminal" npx tsx --env-file=.env.local scripts/03-reviewer.mts ``` **Expected result:** `created user_17 owner`. Running it again prints `updated`: a `PUT` replaces the whole record, so it is safe to repeat. ## Mount the partner proxy {#proxy} The browser never talks to ClearedBy. It talks to **your** server, through one catch-all route. The proxy works out who is signed in with **your** session (`resolveUser`), mints short-lived tokens for exactly that person, and calls ClearedBy with your partner key, which never leaves the server. ```ts title="lib/session.ts" import type { ProxyUser } from '@clearedby/sdk/partner-proxy' // QUICKSTART ONLY: everyone is Sam in the one dev org. In your app, read YOUR // session (cookie, JWT, NextAuth...) and return the merchant org the person is // working in and the external_subject you provisioned them with, or null. export async function currentUser(_req: Request): Promise { return { org_id: process.env.CLEAREDBY_ORG_ID!, external_subject: 'user_17' } } ``` ```ts title="app/api/clearedby/[...path]/route.ts" import { createPartnerProxy } from '@clearedby/sdk/partner-proxy' import { currentUser } from '@/lib/session' const proxy = createPartnerProxy({ partnerKey: process.env.CLEAREDBY_PARTNER_KEY!, basePath: '/api/clearedby', // must match where this file is mounted resolveUser: (req) => currentUser(req), }) export const dynamic = 'force-dynamic' export const GET = proxy.handle export const POST = proxy.handle export const PUT = proxy.handle ``` **Expected result:** after `npm run dev`, opening `http://localhost:3000/api/clearedby/items` in the browser returns `{"items":[],"next_cursor":null}`. A `403 not_a_reviewer` means the org id or `external_subject` doesn't match step 3 or 4. ## Render the approval queue {#queue} ```tsx title="app/approvals/approvals.tsx" 'use client' import { useState } from 'react' import { ClearedByProvider, ApprovalQueue, ReviewPanel } from '@clearedby/react' import '@clearedby/react/styles.css' export function Approvals() { const [id, setId] = useState(null) return (
setId(item.id)} /> {id ? :

Pick something from the list.

}
) } ``` ```tsx title="app/approvals/page.tsx" import { Approvals } from './approvals' export default function Page() { return } ``` **Expected result:** `http://localhost:3000/approvals` shows **Waiting for your OK** and "Nothing is waiting for you." ## Build the executor {#executor} ClearedBy POSTs every approved change to your `execution_url` as a signed envelope carrying an Ed25519-signed receipt. Your executor verifies it with `verifyDispatch`, dedupes on `work_item_id`, executes **only** the receipt's params, and reports what happened. Read the body as **text**: the signature is over the exact bytes. ```ts title="app/api/executor/route.ts" import { ClearedBy, type CompletionItem } from '@clearedby/sdk' import { verifyDispatch, DispatchVerificationError, ReceiptRevokedError } from '@clearedby/sdk/dispatch' export const runtime = 'nodejs' // verifyDispatch uses node:crypto export const dynamic = 'force-dynamic' const executed = new Set() // QUICKSTART ONLY: use a unique DB index in production const cb = new ClearedBy({ apiKey: process.env.CLEAREDBY_EXECUTOR_KEY! }) type PriceChange = { variant_id: string; before: { price: string }; after: { price: string } } export async function POST(req: Request) { const raw = await req.text() let v try { v = await verifyDispatch(raw, req.headers, { secret: process.env.CLEAREDBY_SIGNING_SECRET!, orgId: process.env.CLEAREDBY_ORG_ID!, // the signed body must name this org jwksUrl: 'https://app.clearedby.com/.well-known/clearedby-keys', audience: process.env.PUBLIC_URL!, // the receipt must name you checkStatus: true, // refuse an approval revoked since }) } catch (err) { if (err instanceof ReceiptRevokedError) return Response.json({ status: 'revoked' }) // 2xx: don't retry if (err instanceof DispatchVerificationError && err.code === 'status_unavailable') { return new Response(null, { status: 503 }) // fail closed: ClearedBy retries } console.error('dispatch refused:', err instanceof DispatchVerificationError ? err.code : err) return Response.json({ error: 'invalid dispatch' }, { status: 401 }) } const { envelope, params, receipt } = v if (envelope.verdict !== 'cleared') return Response.json({ status: 'noted', executed: false }) // only 'cleared' authorises if (executed.has(envelope.work_item_id)) { return Response.json({ status: 'already_executed', executed: false }, { status: 409 }) } // The go-live checker (npx @clearedby/sdk doctor): its own requests are dry runs, // and its test approvals (doctor.noop) touch nothing but are reported done. if (req.headers.get('clearedby-doctor') === '1') return Response.json({ status: 'dry_run', executed: false }) executed.add(envelope.work_item_id) // record BEFORE executing if (envelope.action === 'doctor.noop') { if (params.skip_complete !== true) { await cb.complete(envelope.work_item_id, { status: 'done', completionId: `${envelope.work_item_id}:final`, deliveryReceiptId: receipt!.receipt_id }) } return Response.json({ status: 'noop', executed: false }) } // "Execute": in production, re-read each variant's live price, write `after` only if it // still equals `before`, and report the rest as 'skipped'. Here we just log. const items: CompletionItem[] = (params.changes as PriceChange[]).map((c) => { console.log(`would set ${c.variant_id} price ${c.before.price} -> ${c.after.price} in ${params.store}`) return { key: c.variant_id, status: 'done', before: c.before, after: c.after } }) const result = await cb.complete(envelope.work_item_id, { status: 'done', completionId: `${envelope.work_item_id}:final`, // stable: a retry replays instead of duplicating items, deliveryReceiptId: receipt!.receipt_id, }) console.log('completion recorded:', result.recorded, 'diverged:', result.diverged) return Response.json({ status: 'accepted' }, { status: 202 }) } ``` **Expected result:** nothing yet. Restart `npm run dev` so the new environment variables load. A quick check: `curl -X POST $PUBLIC_URL/api/executor -d '{}'` answers `401` (no signature), which is what a forged request gets. ## Propose a change from a script {#propose} This plays your agent. It holds the org's **agent** key, which can propose but never approve. A price change always needs a person under the default rules, so it will wait in the queue. ```ts title="scripts/04-propose.mts" import { ClearedBy } from '@clearedby/sdk' const agent = new ClearedBy({ apiKey: process.env.CLEAREDBY_AGENT_KEY! }) const r = await agent.gate({ action: 'shopify.price.update', params: { store: 'acme-dev.myshopify.com', // must be one of the org's shop_domains currency: 'GBP', changes: [{ variant_id: 'gid://shopify/ProductVariant/2001', label: 'Linen shirt / M', // what the reviewer sees before: { price: '40.00', compare_at_price: null }, after: { price: '30.00', compare_at_price: '40.00' }, }], }, audience: process.env.PUBLIC_URL, // the receipt will name your executor context: { summary: 'Mark the linen shirt down for the summer sale' }, proof: { reason: 'Sell-through is 40% below plan and the summer sale starts Friday.', confidence: 0.8, evidence: [{ type: 'threshold', value: { label: 'Price drop', value: 25, limit: 30, unit: '%', status: 'ok' } }], }, idempotencyKey: 'quickstart-price-1', // a retry replays instead of proposing twice }) console.log(r.status, r.id) ``` ```bash title="terminal" npx tsx --env-file=.env.local scripts/04-propose.mts ``` **Expected result:** `pending 01K...`. Within the 15-second refresh, the queue at `/approvals` shows **Update prices** with the change in a sentence. Running the script again prints the same id (the idempotency key replays the first answer). ## Approve it in your UI {#approve} Open `http://localhost:3000/approvals`, pick the item and look at the review panel: the change as a before/after table, the agent's evidence badged **Agent says**, and only the buttons Sam may press (from ClearedBy's own permission check). Click **Approve**. Behind the button, the proxy minted a single-use decision token naming `user_17`, pinned to this item, and called `POST /v1/gate/:id/decide`. ClearedBy checked Sam's authority itself. **Expected result:** the panel shows **Approved.** and the item leaves the queue. ClearedBy dispatches straight away. ## Watch the dispatch arrive and complete {#complete} In the `npm run dev` terminal: ```text title="dev server output" would set gid://shopify/ProductVariant/2001 price 40.00 -> 30.00 in acme-dev.myshopify.com completion recorded: true diverged: false ``` Confirm from ClearedBy's side with the agent key: ```ts title="scripts/05-check.mts" import { ClearedBy } from '@clearedby/sdk' const cb = new ClearedBy({ apiKey: process.env.CLEAREDBY_AGENT_KEY! }) const [item] = (await cb.list({ status: 'cleared', limit: 1 })).items const d = await cb.delivery(item.id) console.log(item.status, item.completion?.status, 'delivered:', d.delivery?.delivered) ``` ```bash title="terminal" npx tsx --env-file=.env.local scripts/05-check.mts ``` **Expected result:** `cleared done delivered: true`. That's the full loop: proposed, held by the merchant's rules, approved by a person in your UI, authorised with a signed receipt, verified and executed by your executor, and reported back. ## Check it before go-live {#doctor} Run the go-live checker. It attacks your executor the way a forged or replayed dispatch would (a bad signature, a stale timestamp, tampered params, a `cleared` dispatch with a receipt ClearedBy never signed) and checks each is refused, then with `--full` pushes a harmless `doctor.noop` approval through for real and checks delivery, idempotency, your completion report and revocation. Each problem comes with a one-line fix. The quickstart executor knows one org's signing secret, so point the doctor at that org (`--org`). An executor that looks secrets up by `envelope.org_id` can use the doctor's own sandbox org instead: leave `--org` out. ```bash title="terminal" npx @clearedby/sdk doctor --org "$CLEAREDBY_ORG_ID" --audience "$PUBLIC_URL" --full ``` **Expected result:** every line is ✓ (or `-` for skipped) and the summary says `0 failed`. Anything marked ✗ says what to change. Add `--json` to run it in CI; the exit code is `1` when anything failed. The [API reference](/docs/partners/api#doctor) lists every check and what it can and can't prove. ## What to change for production {#production} - [ ] Replace `lib/session.ts` with your real session lookup. The org and `external_subject` must come from **your** session, never from the request. - [ ] Dedupe on `work_item_id` with a unique database index written before executing, not an in-memory `Set`. - [ ] Reply to the dispatch fast (`202`) and execute in a job. Re-check live state before every write and report per-item results, including `skipped` and `failed`. - [ ] Onboard each merchant from your own signup flow (steps 3 and 4), store the keys and signing secret in your secret store, and subscribe to lifecycle webhooks per org with `partner.createWebhook(orgId, ...)`. Rotate keys with `partner.rotateOrgKey` (a grace period lets you deploy the new key first). - [ ] Work through the [security checklist](/docs/partners/security) and the [go-live checklist](/docs/partners/guide#testing), and get `npx @clearedby/sdk doctor --full` to `0 failed` against your production executor. Next: make it look like your app in [UI components](/docs/partners/ui#theming), or read the [guide](/docs/partners/guide) for send-backs, evidence, revokes and undo. --- # 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" 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" 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" 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(input: GateInput, fn: () => T | Promise): Promise" 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" 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" 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" 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" 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" 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 `@`), `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" 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): Promise" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" const shape = await agent.describePolicy('refunds') ``` #### getPolicy {#cb-getpolicy} One stored version, YAML included. ```ts title="getPolicy(name: string, version: number): Promise" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" const item = await partner.get(orgId, id, { include: ['events'] }) ``` #### status {#p-status} ```ts title="status(orgId: string, id: string, opts?: { token?: string }): Promise" const s = await partner.status(orgId, id) ``` #### events {#p-events} ```ts title="events(orgId: string, id: string, opts?: { lineage?: boolean; token?: string }): Promise" 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" 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" 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" 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" 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" 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): Promise" 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" 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" 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" 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=,v1=`); the timestamp is within `toleranceSec` (default 300); the HMAC-SHA256 of `"."` 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" 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" 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>" 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" 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; 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" 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 ` | `CLEAREDBY_BASE_URL` | Default `https://app.clearedby.com`. | | `--org ` | | 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 ` | | Send the synthetic dispatches here instead of `execution_url` (for example a local build). | | `--audience ` | | The `audience` your executor verifies. | | `--full` | | Also run the real flow (below). | | `--wait ` | | With `--full`: how long to wait for the delivery and for your completion report. Default 120. | | `--org-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 `. **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" 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, io?: { out, err, color? }): Promise" process.exitCode = await runDoctorCli(['doctor', '--json']) ``` ## HTTP conventions {#http} | | | | --- | --- | | Base URL | `https://app.clearedby.com` | | Auth | `Authorization: Bearer ` | | 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=&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=`. 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=`, 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=,v1=.")>`; 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=` | 6 attempts; switched off after 21 consecutive failures | | Callback | The gate call's `callback_url` | `X-ClearedBy-Signature: sha256=` | Retried with backoff | | Partner alert | `alert_webhook_url` | `x-clearedby-signature: sha256=`, `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. --- # UI components ## How it fits together {#architecture} There are two halves, and the partner key never reaches the browser: - **Server:** `createPartnerProxy()` from `@clearedby/sdk/partner-proxy`, mounted at one catch-all route in your app (default `/api/clearedby`). It works out who is asking from **your** session, mints short-lived ClearedBy tokens for exactly that person, calls ClearedBy, strips anything credential-like and answers. See [the proxy](#proxy). - **Browser:** `@clearedby/react`. `` plus the components or hooks. It calls only your proxy, with same-origin cookies. ```bash title="terminal" npm install @clearedby/react @clearedby/sdk ``` ```tsx title="app/approvals.tsx" 'use client' import { useState } from 'react' import { ClearedByProvider, ApprovalQueue, ReviewPanel } from '@clearedby/react' import '@clearedby/react/styles.css' // optional: the default look (only cb-* classes, no globals) export function Approvals() { const [id, setId] = useState(null) return ( setId(item.id)} /> {id && } {/* includes DecisionBar, CancelButton and History */} ) } ``` The [quickstart](/docs/partners/quickstart#proxy) wires this up end to end. A runnable Next.js app is in [`examples/partner-approvals-next`](https://github.com/ClearedBy/clearedby-js/tree/main/examples/partner-approvals-next). Open views refresh every 15 s while the tab is visible, pause while it is hidden, refresh as soon as it is visible again and back off (up to 5 minutes) after errors. The components are keyboard-accessible (arrow keys move through the queue; Enter or Space opens an item) and announce status changes. ## ClearedByProvider {#provider} Wrap every component and hook in one provider. It holds the client, a per-provider cache, the labels, the theme and your component overrides. | Prop | Type | Default | What it does | | --- | --- | --- | --- | | `basePath` | `string` | `'/api/clearedby'` | Where your partner proxy is mounted. | | `labels` | `LabelOverrides` | | Replace any wording (see [labels](#labels)). | | `pollInterval` | `number` (ms) | `15000` | Refresh interval for open views. `0` turns polling off (drive it with `useRevalidate`). | | `locale` | `string` | the browser's | Locale for dates and money. | | `fetch` | `typeof fetch` | global `fetch` | A custom fetch (tests, extra headers). | | `theme` | `ClearedByTheme` | | Design tokens, applied on top of the stored theme, token by token. | | `fetchTheme` | `boolean` | `true` | Fetch the stored theme from `${basePath}/theme`. | | `colorScheme` | `'auto' \| 'class' \| 'light' \| 'dark'` | `'auto'` | Dark mode: the OS setting, a `.dark` ancestor (shadcn/Tailwind), or forced. | | `classNames` | `Partial` | | Extra classes per part, for every component (see [slots](#classnames)). | | `unstyled` | `boolean` | `false` | Drop every default `cb-*` class everywhere. | | `components` | `Partial` | | Your `Button`, `Input`, `Textarea`, `Select`, `Badge`, `Dialog` (see [injection](#components-injection)). | | `children` | `ReactNode` | | | ## Components {#components} Every component also accepts the **style props**: `className` (extra class on its root), `classNames` (per-part classes, merged with the provider's) and `unstyled` (overrides the provider's). Every component takes `labels` to override wording for that component only. ### ApprovalQueue {#approvalqueue} The signed-in reviewer's list of things waiting for them, newest first, with "Show more" paging. Up/Down arrows move between cards; Enter or Space opens one. | Prop | Type | Default | What it does | | --- | --- | --- | --- | | `status` | `ItemStatus \| ItemStatus[]` | `['pending', 'escalated']` | Which statuses to show. For a history tab: `['cleared', 'rejected', 'sent_back', 'expired', 'revoked']`. | | `filter` | `{ actionPrefix?: string; batchId?: string }` | | Only some actions, or one batch. | | `limit` | `number` | `25` | Page size, 1 to 100. | | `onSelect` | `(item: Approval) => void` | | A card was chosen. | | `selectedId` | `string \| null` | | Highlights that card. | | `title` | `ReactNode \| false` | "Waiting for your OK" | Heading; `false` hides it. | | `renderItem` | `(item: Approval, selected: boolean) => ReactNode` | | Render your own card instead of `ApprovalCard`. | | `labels` | `LabelOverrides` | | | ### ApprovalCard {#approvalcard} One queue entry as a button: what the assistant wants to do in a sentence, its status, and meta (two-person approval progress, sent to you, when it lapses). | Prop | Type | What it does | | --- | --- | --- | | `item` | `Approval` | The clearance (from the queue). | | `selected` | `boolean` | Selected styling (`cardSelected`). | | `onSelect` | `(item: Approval) => void` | Clicked. | | `labels` | `LabelOverrides` | | ### ReviewPanel {#reviewpanel} Everything a reviewer needs to decide one item: the change in plain English, a paged before/after table for batches, the evidence grouped by who vouches for it, the buttons they may press, "Cancel before it runs" on approved items, and the history. | Prop | Type | Default | What it does | | --- | --- | --- | --- | | `id` | `string` | required | The clearance id. | | `showDecisionBar` | `boolean` | `true` | Decision buttons on open items. | | `showCancel` | `boolean` | `true` | "Cancel before it runs" on approved, not-yet-done items. | | `showHistory` | `boolean` | `true` | The timeline. | | `escalateTo` | `string` | | Hand escalations to this `external_subject`. Default: the most senior reviewer who can cover it. | | `onDecided` | `(result: DecideResult, decision: Decision) => void` | | After a decision is recorded. | | `pageSize` | `number` | `50` | Rows per page in the changes table. | | `labels` | `LabelOverrides` | | | ### DecisionBar {#decisionbar} Only the buttons this person may press, from ClearedBy's own permission check (`can`). Decline and send back ask for a note of at least 4 characters first; escalate takes an optional note. Shows a short message after deciding ("Approved.", "Thanks. One more person needs to approve this."). | Prop | Type | What it does | | --- | --- | --- | | `id` | `string` | The clearance id. | | `escalateTo` | `string` | Hand escalations to this `external_subject`. | | `onDecided` | `(result: DecideResult, decision: Decision) => void` | After a decision is recorded. | | `labels` | `LabelOverrides` | | ### ChangesTable {#changestable} The before/after table for a batch (`params.changes[]`), paged so a 3,000-product batch stays quick, with a summary line on top. Used inside `ReviewPanel`. | Prop | Type | Default | What it does | | --- | --- | --- | --- | | `item` | `Pick` | required | The clearance. | | `pageSize` | `number` | `50` | Rows per page. | | `labels` | `LabelOverrides` | | | ### EvidenceList {#evidencelist} The evidence grouped and badged by provenance: **Verified by** your name (`partner_verified`), **Checked automatically** (`clearedby_computed`), then **Agent says** (`agent_claim`), with a warning when an item's `integrity` is `mismatch`. Used inside `ReviewPanel`. | Prop | Type | What it does | | --- | --- | --- | | `evidence` | `{ claims: EvidenceItem[]; verified: EvidenceItem[] } \| undefined` | The clearance's `evidence`. | | `currency` | `string` | The item's currency, for money figures in automatic checks. | | `labels` | `LabelOverrides` | | `groupEvidence(evidence, labels)` returns the same grouping as data (`EvidenceGroup[]`: `key`, `kind` of `'verified' | 'computed' | 'agent'`, `badge`, `items`) for your own rendering. ### RulesSummary {#rulessummary} "Your approval rules": one plain-English line per setting, **Looks good** and **Adjust**. Adjusting shows simple controls (amounts in the org currency, spot-checks with "How often"). A stricter change is saved at once. A looser change is confirmed by an owner or admin in place (in your `Dialog`, if you provide one), or shows "Your store owner needs to approve this change." A waiting proposal is shown to owners and admins with **Yes, change it**. | Prop | Type | What it does | | --- | --- | --- | | `onLooksGood` | `() => void` | The merchant tapped "Looks good" (the rules are already on; nothing is sent). | | `onChanged` | `() => void` | A change is live (saved stricter, or accepted). | | `labels` | `LabelOverrides` | | Who may edit and accept comes from the proxy: the `viewer` it adds to `GET /rules` (`role`, `can_edit`, `can_accept`), from your `canEditRules` option and the reviewer's role. ### History {#history} The item's story, oldest first, across revisions: asked, sent back and revised, approved, carried out, cancelled or undone. Technical steps are left out. | Prop | Type | What it does | | --- | --- | --- | | `id` | `string` | The clearance id. | | `title` | `string \| false` | Heading; `false` hides it. | | `labels` | `LabelOverrides` | | ### CancelButton {#cancelbutton} "Cancel before it runs" on an approved change that hasn't been reported done or failed. Renders nothing otherwise. Asks why (4+ characters) and confirms in your `Dialog` if you provide one. ClearedBy decides whether this person may (owners and admins, or anyone who could approve it). | Prop | Type | What it does | | --- | --- | --- | | `id` | `string` | The clearance id. | | `onCancelled` | `(result: RevokeResult) => void` | After the revoke. `result.dispatch` is `'delivered'` or `'in_flight'` when your executor may already have it. | | `labels` | `LabelOverrides` | | `canCancelBeforeRun(item)` is the same test as data: `true` for `cleared` items whose `completion.status` isn't `done` or `failed`. ## Hooks {#hooks} The components are built on these. Use them for a fully custom UI: they carry the same permission-aware logic. A `Resource` is `{ data: T | undefined; error: unknown; loading: boolean; revalidate: () => Promise }`; it loads on mount, shares requests between components, and polls while visible. | Hook | Signature | Returns | | --- | --- | --- | | `useApprovalQueue` | `useApprovalQueue(opts?: QueueOptions)` | `{ items: Approval[]; loading; error; hasMore; loadingMore; loadMore(): Promise; revalidate(): Promise }`. `QueueOptions` = `{ status?, filter?: { actionPrefix?, batchId? }, limit? }` (default status `['pending', 'escalated']`, limit 25). | | `useApproval` | `useApproval(id: string \| null \| undefined)` | `Resource`: the clearance in full. `null` doesn't load. | | `usePermissions` | `usePermissions(id)` | `Resource`: `{ can, cannot, reason_required, dual_review, requires_passkey, send_back_forces?, reviewer, status }`. Only show buttons in `can`. | | `useHistory` | `useHistory(id)` | `Resource`, oldest first, including earlier revisions. | | `useDecide` | `useDecide(id: string)` | `{ decide(decision: Decision, opts?: { reason?, escalateTo? }): Promise; pending; error: ApprovalsError \| null; result: DecideResult \| null; reset() }`. Refuses a decline or send-back without a 4+ character reason before sending (`reason_required`). Refreshes open views after. | | `useRevoke` | `useRevoke(id: string)` | `{ revoke(reason: string): Promise; pending; error; result; reset() }`. | | `useRules` | `useRules()` | `Resource`: `{ settings, summary[], active_version, currency, refund_approvers?, pending_proposal?, viewer?: { role, can_edit, can_accept } }`. Not polled. | | `useRulesProposal` | `useRulesProposal()` | `{ propose(settings: Partial): Promise; accept(proposalId: string): Promise<{ status: 'active' }>; proposal; pending; error; reset() }`. | | `useRevalidate` | `useRevalidate()` | `(prefix?: string) => Promise`: refresh open views now. A prefix (`'items'`, `'item:'`, `'permissions:'`, `'history:'`, `'rules'`) refreshes only those; nothing refreshes everything. | | `useClearedBy` | `useClearedBy()` | The provider's value: `{ client, store, labels, pollInterval, locale, classNames, unstyled, components }`. Throws outside a provider. | | `useLabels` | `useLabels(overrides?: LabelOverrides)` | The provider's labels with `overrides` on top. | | `useUi` | `useUi(props: StyleProps)` | `{ cls(...slots), root(...slots), C: UiComponents, pass, unstyled }`: class and component resolution for building your own parts that honour `classNames` / `unstyled` / `components`. | `Decision` is `'clear' | 'reject' | 'send_back' | 'escalate'`. `DecideResult.status` is `'cleared' | 'rejected' | 'pending' | 'escalated' | 'sent_back'` (`pending` = one of two approvals, with `approvals` and `required`). Errors from hooks are `ApprovalsError` (`message`, `status`, `code`: ClearedBy's or the proxy's error code, `network` for a failed request). Also exported: `keys` (the cache-key builders `useRevalidate` prefixes come from: `keys.queue(qs)`, `keys.item(id)`, `keys.permissions(id)`, `keys.history(id)`, `keys.rules()`), `REASON_REQUIRED` (`['reject', 'send_back']`) and `MIN_REASON_LENGTH` (`4`). ## Theming: design tokens {#theming} The components inherit your page's font and text colour by default. To match your product, give ClearedBy your design tokens **once, as data**: no CSS to write, and every component in every org picks them up. ### The ClearedByTheme schema {#theme-schema} ```ts title="ClearedByTheme" interface ClearedByTheme { colors?: { primary?: string // buttons, links, focus rings, the selected card primaryText?: string // text on primary buttons surface?: string // card / panel background (default: transparent) surfaceAlt?: string // subtle background: table headers, notes, neutral badges border?: string text?: string // body text (default: inherited) mutedText?: string success?: string warning?: string danger?: string } radius?: string // e.g. '8px' or '0.5rem' fontFamily?: string // e.g. 'Inter, system-ui, sans-serif' (default: inherited) fontSize?: string // base size, e.g. '15px' (default: inherited) spacing?: { xs?: string; sm?: string; md?: string; lg?: string } shadow?: string // card shadow, e.g. '0 1px 2px rgba(0,0,0,.08)' (default: none) dark?: { colors?: ClearedByTheme['colors']; shadow?: string } // dark-mode overrides } ``` Values must be plain CSS: colours (`#hex`, `rgb()`, `hsl()`, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`, `color()`, colour names), lengths (`px`, `rem`, `em`, `%`), a font list, or a box-shadow. `url()`, `var()`, `expression()`, `attr()`, `;`, `{`, `}`, `<`, comments and unknown keys are refused by the API with `400 invalid_body` and dropped by the components, so a theme can never inject CSS. ### Four ways to set it {#theme-ways} | Way | How | | --- | --- | | **API** (recommended) | `partner.updateSettings({ theme })` for your whole account, and optionally `partner.updateOrg(orgId, { theme })` per merchant (token by token on top; `null` clears it). `partner.getOrgTheme(orgId)` returns the merged result. The provider fetches it through the proxy (`GET /theme`, cached 5 minutes per org). | | **Importers** | `@clearedby/react/theme`: `fromShadcn(globalsCss \| cssVars \| element)`, `fromTailwind(resolvedConfig)`, `fromDesignTokens(w3cJson)` turn what you already have into a theme. | | **CLI** | `npx @clearedby/react theme --from [--push] [--org ] [--base-url ]` prints the theme; `--push` saves it with `CLEAREDBY_PARTNER_KEY` (account-wide, or one org with `--org`). | | **In code** | `` overrides the stored theme token by token. | ```bash title="terminal" # shadcn/ui: read the CSS variables in globals.css, print the theme, save it for your account npx @clearedby/react theme --from app/globals.css --push # Tailwind 3 config (resolved with tailwindcss/resolveConfig when installed), for one merchant npx @clearedby/react theme --from tailwind.config.js --push --org 01K... # W3C design tokens (DTCG), or an existing ClearedByTheme JSON npx @clearedby/react theme --from tokens.json ``` ### Importers {#importers} | Function | Reads | Mapping | | --- | --- | --- | | `fromShadcn(input)` | A `globals.css` string, a `{ '--primary': ... }` map, or (in the browser) an element whose computed style carries the variables | `--primary` → primary, `--primary-foreground` → primaryText, `--card` / `--background` → surface, `--muted` → surfaceAlt, `--border` → border, `--foreground` → text, `--muted-foreground` → mutedText, `--destructive` → danger, `--success`, `--warning`, `--radius`, `--font-sans`. The `.dark` block becomes `dark`. shadcn v3 HSL channels and v4 `oklch()` both work. | | `fromTailwind(config)` | A **resolved** Tailwind config | Semantic names first (`primary`, `background`, `card`, `muted`, `border`, `foreground`, `destructive`, `success`, `warning`), then the default palette (`blue`/`indigo` 600, `gray`/`slate` 100/200/500/900, `green` 600, `amber` 600, `red` 600); `borderRadius`, `fontFamily.sans`, `fontSize.base`, `spacing` 1/2/3/5, `boxShadow.sm`. | | `fromDesignTokens(json)` | W3C Design Tokens (DTCG) JSON | Matched by name (primary/brand/accent, surface/background, border, text/foreground, success, warning, danger/error, radius, font, spacing, shadow); `{alias}` references resolved; a top-level `dark` group becomes `dark`. | | `parseCssVariables(css)` | CSS text | `{ light, dark }` maps of the custom properties in `:root` and `.dark`. | The theme helpers are exported from both `@clearedby/react` and `@clearedby/react/theme`: `sanitizeTheme(input)` (keep only valid tokens, or `null`), `mergeTheme(base, over)` (token by token), `themeToCssVars(theme)` and `themeToDarkCssVars(theme)` (the `--cb-*` properties) and `themeCss(theme, scopeId, colorScheme)` (the stylesheet the provider injects). ### Let your AI coding agent write it {#theme-agent} ```text title="prompt" Read our design system (the Tailwind config, globals.css / CSS variables, or design-token files) and produce a JSON object matching the ClearedByTheme type from https://clearedby.com/docs/partners/ui#theme-schema, choosing the values our app actually uses for buttons, cards, borders, body text, muted text, success/warning/error states, corner radius, font and spacing. Use only literal CSS values: hex / rgb() / hsl() / oklch() colours, px / rem lengths, a font-family list and a box-shadow. No var(), no url(). Include a "dark" block if we support dark mode. Save it as clearedby-theme.json, then run: npx @clearedby/react theme --from clearedby-theme.json --push ``` ## Deeper customisation {#customisation} When tokens aren't enough there are three further levels, and you can mix them. ### Level 1: CSS variables {#css-variables} The default stylesheet (`@clearedby/react/styles.css`) reads only these variables, with neutral fallbacks that work on light and dark pages. It uses only `cb-*` classes: no element selectors, resets or globals. Set any of them in your own CSS, for one page or everywhere: | Variable | Token | | --- | --- | | `--cb-color-primary` | `colors.primary` | | `--cb-color-primary-text` | `colors.primaryText` | | `--cb-color-surface` | `colors.surface` | | `--cb-color-surface-alt` | `colors.surfaceAlt` | | `--cb-color-border` | `colors.border` | | `--cb-color-text` | `colors.text` | | `--cb-color-muted` | `colors.mutedText` | | `--cb-color-success` | `colors.success` | | `--cb-color-warning` | `colors.warning` | | `--cb-color-danger` | `colors.danger` | | `--cb-radius` | `radius` | | `--cb-font` | `fontFamily` | | `--cb-font-size` | `fontSize` | | `--cb-space-xs`, `--cb-space-sm`, `--cb-space-md`, `--cb-space-lg` | `spacing` | | `--cb-shadow` | `shadow` | ### Level 2: classNames slots {#classnames} Every styleable part has a slot. Pass any subset as `classNames` on the provider (every component) or on one component; they are added to the default `cb-*` class, or replace it with `unstyled`. `DEFAULT_CLASSES` holds the defaults (`root` → `cb-root`, `cardSelected` → `cb-card--selected`, ...). | Group | Slots | | --- | --- | | Layout and text | `root`, `heading`, `subheading`, `text`, `hint`, `status`, `success`, `error`, `warning`, `header`, `kicker`, `meta`, `section`, `note`, `callout` | | Lists and cards | `list`, `listItem`, `card`, `cardSelected`, `cardTop`, `cardTitle`, `cardSentence`, `cardMeta`, `pager` | | Badges | `badge`, `badgeWaiting`, `badgeOk`, `badgeBad`, `badgeWarn`, `badgeMuted` | | Buttons and links | `button`, `primaryButton`, `secondaryButton`, `dangerButton`, `ghostButton`, `link`, `buttonRow` | | Forms | `form`, `field`, `label`, `input`, `textarea`, `select`, `checkbox`, `checkboxLabel` | | Key/value and tables | `kv`, `kvRow`, `kvTerm`, `kvValue`, `tableWrap`, `table`, `tableHeadCell`, `tableRow`, `tableRowHeader`, `tableCell`, `diff`, `diffBefore`, `diffAfter` | | Evidence | `evidence`, `evidenceGroup`, `evidenceVerified`, `evidenceComputed`, `evidenceAgent`, `evidenceBadge`, `evidenceItem`, `evidenceLabel`, `evidenceValue`, `evidenceList` | | History and dialogs | `timeline`, `timelineItem`, `timelineRevision`, `timelineTime`, `dialog`, `dialogTitle` | ### Level 3: your own components {#components-injection} Pass your design system's primitives to the provider. Anything you leave out uses the default (plain, accessible elements; the default `Dialog` is inline and non-modal). `DEFAULT_COMPONENTS` holds the defaults. | Component | Props it receives | | --- | --- | | `Button` | `ButtonHTMLAttributes` plus `variant: 'primary' \| 'secondary' \| 'danger' \| 'ghost'` (map it to yours, e.g. shadcn `danger` → `destructive`) | | `Input` | `InputHTMLAttributes` | | `Textarea` | `TextareaHTMLAttributes` | | `Select` | `SelectHTMLAttributes` | | `Badge` | `{ tone: 'waiting' \| 'ok' \| 'bad' \| 'warn' \| 'muted'; className?; children? }` | | `Dialog` | `{ open; onClose(); title; titleId; className?; titleClassName?; children? }`. Put `titleId` on your title element. | ```tsx title="app/approvals.tsx" import { ClearedByProvider, ApprovalQueue, type UiButtonProps, type UiBadgeProps } from '@clearedby/react' import { Button } from '@/components/ui/button' // shadcn/ui import { Badge } from '@/components/ui/badge' const VARIANT = { primary: 'default', secondary: 'secondary', danger: 'destructive', ghost: 'ghost' } as const const CbButton = ({ variant, ...rest }: UiButtonProps) => ))} {q.hasMore && } ) } export function Decide({ id }: { id: string }) { const item = useApproval(id) const perms = usePermissions(id) const d = useDecide(id) if (!item.data || !perms.data) return null return (

{describeAction(item.data, f).title}

{perms.data.can.includes('clear') && } {perms.data.can.includes('reject') && ( )} {d.error &&

{d.error.code === 'reason_required' ? 'Please add a note.' : d.error.message}

}
) } ``` ### Webhook-driven refresh {#recipe-revalidate} Turn polling down (or off) and refresh the moment something changes: your backend receives ClearedBy's `decision.*` webhooks (see the [API reference](/docs/partners/api#cb-createwebhook)), tells the browsers of that merchant over whatever push channel you already have, and the browser calls `useRevalidate()`. ```ts title="app/api/clearedby-events/route.ts (server)" import { verifyWebhook } from '@/lib/verify-webhook' // HMAC check from the API reference import { pusher } from '@/lib/pusher' // or SSE, a WebSocket, Ably... export async function POST(req: Request) { const raw = await req.text() const evt = JSON.parse(raw) const secret = await secrets.get(`cb:${evt.org_id}:whsec`) if (!verifyWebhook(raw, req.headers.get('x-clearedby-signature'), secret)) return new Response(null, { status: 401 }) await pusher.trigger(`approvals-${evt.org_id}`, 'changed', { id: evt.data.id }) // no payload data needed return new Response(null, { status: 200 }) } ``` ```tsx title="components/live-approvals.tsx (browser)" 'use client' import { useEffect } from 'react' import { ClearedByProvider, ApprovalQueue, useRevalidate } from '@clearedby/react' function LiveRefresh({ channel }: { channel: string }) { const revalidate = useRevalidate() useEffect(() => { const sub = pusherClient.subscribe(channel) sub.bind('changed', ({ id }: { id: string }) => { void revalidate('items') // the queue void revalidate(`item:${id}`) // that item, if open void revalidate(`permissions:${id}`) }) return () => pusherClient.unsubscribe(channel) }, [channel, revalidate]) return null } export function LiveApprovals({ orgId }: { orgId: string }) { return ( ) } ``` --- # Security ## The executor checklist {#executor-rules} Your executor is the only thing that changes the store. Each rule below closes a specific attack; the [threat model](#threat-model) says which. 1. **Verify every dispatch with `verifyDispatch`** before doing anything, over the **raw body bytes** (read the body as text; never re-serialise parsed JSON). Pass `secret` (the org signing secret), `orgId`, `jwksUrl` (or `keys`) and `audience`. Reject on any error (`401`). 2. **Execute only `cleared`, and only the receipt's params**: the `params` that `verifyDispatch` returns. Never `envelope.data`, never anything from the agent, a header or a query string. `rejected`, `expired` and `sent_back` authorise nothing: answer `2xx` and don't act. 3. **Check the status right before anything irreversible** (refunds, cancellations, payouts): `checkStatus: true`. An approval can be revoked after the dispatch left ClearedBy. `ReceiptRevokedError`: don't execute, answer `2xx`. `status_unavailable`: fail closed, answer non-2xx (`503`) so ClearedBy retries. If your job starts long after the dispatch arrived, check again (`checkReceiptStatus`) when it starts. 4. **Dedupe on `work_item_id`** with a unique index, and record "executing" **before** calling the store. Never dedupe on the receipt's `nonce` or `receipt_id`: every delivery attempt carries new ones. 5. **Answer `409 {"status":"already_executed"}`** to a repeat. ClearedBy records it as delivered and stops retrying. 6. **Re-check the live state** of every item before writing. Write only when the live value still equals the approved `before`; report the rest as `skipped`. For an undo, the same check protects changes people made by hand since. 7. **Never exceed the approved amount.** A receipt authorises *up to* what was approved, at decision time. Re-check the refundable amount on the order: if less is refundable now, refund less (or stop) and report `partial` or `failed`. Send an idempotency key derived from `work_item_id` with the store's own mutation. 8. **Keep store write credentials away from agents.** The agent gets read-only store access at most, and an org `cb_live_` key that can only propose. Only the executor holds store write access. Give the executor its own `cb_live_` key (`createOrgKey`), and keep the partner key out of both. 9. **Report what happened** with `complete()` (`POST /v1/gate/:id/complete`): a stable `completionId`, per-item results and the `deliveryReceiptId` you verified. A `2xx` to the dispatch only proves you received it. 10. **Answer within 10 seconds.** Verify, dedupe, enqueue, reply `202`; do the work in a job. A slow reply counts as a failed attempt and is retried. 11. **Treat the go-live checker's traffic as a test.** A request with the header `clearedby-doctor: 1` was sent by `npx @clearedby/sdk doctor`, not ClearedBy: verify and dedupe it as usual and answer as you would, but never execute or record it. The action `doctor.noop` is never real: touch nothing, and report it done with `complete()` unless `params.skip_complete` is `true`. > **Must:** Why the receipt, not just the signature. > Dispatches are HMAC-signed with the org's signing secret, which any holder of one of that org's API keys can read, **including your agent's key**. So the HMAC alone proves "someone with an org key sent this", not "a person approved this". The Ed25519 receipt is signed by ClearedBy alone, and no API key can produce one. That is why `verifyDispatch` refuses a `cleared` dispatch without a valid receipt bound to the envelope, and why you pass `audience`: a receipt minted for another service can't be replayed at yours. A minimal compliant handler is in the [quickstart](/docs/partners/quickstart#executor); a production-shaped one (Express, a job queue, per-item state checks and partial reports) is in the [guide](/docs/partners/guide#we-dispatch). [`examples/dispatch-receiver`](https://github.com/ClearedBy/clearedby-js/tree/main/examples/dispatch-receiver) runs offline and shows a first delivery, a retry answered `409 already_executed`, and a forged amount refused with `receipt_mismatch`, and it passes the doctor. ## Credentials {#credentials} | Credential | Where it may live | Never | | --- | --- | --- | | Partner key `cb_partner_...` | Your backend's secret store | In a browser bundle (`NEXT_PUBLIC_`), an agent prompt or tool, a log line, the executor, a client-side env | | Org key `cb_live_...` (agent) | The agent's runtime, one org only | Given to an agent of a different merchant; used by the executor | | Org key `cb_live_...` (executor) | The executor | Given to the agent | | Decision token `cb_dt_...` | Your backend, for the seconds between the click and the decision | Sent to the browser; minted with an `external_subject` from the request body | | Org signing secret | The executor (to verify dispatches) | Treated as proof of approval (see the receipt callout above) | | Webhook secret `whsec_...` | The service that receives webhooks | Shared across orgs | | Alert webhook secret | The service that receives partner alerts | | **Rotate keys** with `partner.rotateOrgKey(orgId, keyId, { graceSeconds })`: it mints a replacement with the same name and agent binding and revokes the old key, at once or when the grace period (up to 24 hours) ends, so you can deploy the new key first. If an org key leaks, `partner.revokeOrgKey(orgId, keyId)` stops it on its next request; `partner.listOrgKeys(orgId)` shows every key with `last_used_at`, so you can spot one that shouldn't be in use. If a partner key leaks, ask ClearedBy to revoke it: every decision token it minted stops working too. ## Your review UI {#review-ui} - **Take the person from your session, never from the request.** The org and `external_subject` you pass to `createDecisionToken` (or return from the proxy's `resolveUser`) must come from your own authenticated session. A browser that could name its own `external_subject` could approve as anyone. - **Keep ClearedBy's permission check in charge.** Show only the buttons in `permissions.can`. ClearedBy re-checks authority, two-person rules and requester-is-not-approver on every decision, so a button you show wrongly is refused, never honoured. - **Use the partner proxy, or copy its rules.** It serves a fixed route list, refuses cross-site writes, never returns keys, tokens or receipts, and caps body sizes. A hand-built proxy must do the same. - **Badge evidence by provenance.** Never style an agent claim as verified, even if its value says `verified: true`. Warn when `integrity` is `mismatch`. - **Send looser rule changes to an owner or admin.** Show `summary_diff` and let only an owner or admin accept (ClearedBy enforces it; your UI should make it obvious). ## Webhooks and alerts {#webhooks} - Verify `X-ClearedBy-Signature: sha256=` (HMAC-SHA256 of the raw body with the subscription's `whsec_` secret) with a constant-time comparison before trusting anything. - There is no timestamp in the webhook signature, so treat every event as "this clearance changed": re-read it from the API (the source of truth) and dedupe on `event` + `data.id`. Never execute from a webhook: only a verified dispatch authorises execution. - Acknowledge within 10 seconds, then process. - Page someone on `partner.alert` (`dispatch_gave_up` especially: an approved change is not being executed). ## Proposals and data {#proposals} - Send an `Idempotency-Key` on every proposal, so a retried network call can't create a second clearance. - Send an `audience` naming your executor on every proposal, and verify it. - Name the shopper in `context.subject_id` for anything about a shopper, so their data can be erased. Send references (order and customer GIDs), not names, emails or addresses. Never card data, passwords, government ids or health data. - Set `retention_days`, and call `eraseSubjectEverywhere` from your own erasure flow. ## Threat model {#threat-model} In plain terms: who might try what, and what stops them. | If... | What stops it | Rule | | --- | --- | --- | | **The agent is compromised or prompt-injected** and tries to change the store directly | It holds no store write credentials and its `cb_live_` key can only propose. The worst it can do is propose, which the merchant's rules and a person then judge. | 8 | | **The agent tries to approve its own proposal** | No key can approve. Only a decision token naming a real reviewer can, ClearedBy checks that reviewer's authority, and the agent that asked is never an approver. | | | **The agent forges a dispatch** to your executor (it can read the org signing secret with its key) | The HMAC would pass, but it can't produce an Ed25519 receipt: `verifyDispatch` refuses a `cleared` dispatch without one (`missing_signature`, `missing_receipt`, `receipt_invalid`). | 1 | | **Someone alters the approved parameters in transit** (a bigger refund, another product) | The receipt signs the exact params and their hash; any change breaks it (`params_hash_mismatch`, `receipt_mismatch`). Executing only the receipt's params closes the rest. | 1, 2 | | **An old dispatch is replayed** | The signed timestamp must be within 5 minutes and the receipt within its 10-minute window; dedupe on `work_item_id` catches replays inside the window. | 1, 4 | | **A receipt meant for another service is replayed at yours** | The receipt names its `audience`; `verifyDispatch` with your `audience` refuses anything else. | 1 | | **An approval is revoked after it was dispatched** | The online status check sees the revocation (`ReceiptRevokedError`). | 3 | | **ClearedBy retries a delivery you already executed** | Dedupe on `work_item_id`; answer `409 already_executed`. | 4, 5 | | **The store changed between approval and execution** (someone edited the product, the order was part-refunded) | Compare live state with the approved `before`, skip what moved, never exceed the approved amount. | 6, 7 | | **A merchant's key is used against another merchant's store** | Each org lists its stores (`shop_domains`); a proposal for any other store is refused before it is recorded (`store_not_allowed`). | | | **A browser tries to decide as someone else, or for another merchant** | The proxy takes the org and person only from `resolveUser`; tokens are minted server-side for that person, and a token only works in its own org. | UI | | **A cross-site page tries to post a decision** as a signed-in reviewer | The proxy refuses non-same-origin writes (`403 cross_site`) and non-JSON bodies. | UI | | **Someone edits history** | Every proposal, decision, cancellation, evidence attachment and result is on a hash-chained, signed record per org; `verifyLedger()` re-walks it. | | | **A webhook is forged** | Verify its HMAC; and a webhook never authorises execution anyway. | Webhooks | What ClearedBy does **not** do, by design: - **It doesn't execute.** It is the control plane: it decides and signs; your executor acts. A bug in your executor (skipping rule 6 or 7) can still do damage within what was approved. - **It doesn't verify the agent's claims.** Evidence in `proof` is presented as "Agent says". Only facts your backend attaches (`attachEvidence`) or ClearedBy computes are marked verified. - **It can't see a person's intent.** A reviewer who approves carelessly has approved. Rules, two-person approval for large amounts, spot-checks and clear evidence are how you reduce that. - **It doesn't reach copies.** Erasure and retention cover what ClearedBy stores, not what you or your merchants copied out (logs, webhook receivers). ## Go-live checklist {#go-live} Run `npx @clearedby/sdk doctor --full` against your production executor first: it tests the executor rules above with real and forged dispatches and prints a fix for anything that fails ([what it checks](/docs/partners/api#doctor)). Then tick off the rest. - [ ] `npx @clearedby/sdk doctor --full` reports `0 failed`, and you have read every ⚠. - [ ] The partner key is only on your servers: not in a browser bundle, an agent prompt or a log line. - [ ] Agents hold only their org's `cb_live_` key and read-only store access. Only the executor holds store write access, with its own `cb_live_` key. - [ ] Every org has `currency` and `shop_domains` set, and a dry run (`check`) passes for each action you use. - [ ] Reviewer authority keys are exact action names (`shopify.refund.create`), in minor units. - [ ] Shopper-related proposals carry `context.subject_id`. - [ ] Proposals carry an `Idempotency-Key` and an `audience` naming your executor. - [ ] The executor uses `verifyDispatch` with `orgId`, `jwksUrl`, `audience`, and `checkStatus: true` for refunds and cancellations. - [ ] The executor dedupes on `work_item_id` with a unique index written before execution, and answers `409 already_executed`. - [ ] The executor checks live state before every write, never exceeds an approved amount, and reports per-item results with a stable completion id. - [ ] Webhook handlers verify signatures, ack within 10 seconds, and re-read clearances rather than trusting payloads. - [ ] The review UI takes `external_subject` from your session, shows only `permissions.can`, and badges evidence by provenance. - [ ] `execution_url` is set and one small auto-cleared change has reached it (`delivery()` shows `delivered: true`). - [ ] `alert_email` and/or `alert_webhook_url` are set and someone is paged by `partner.alert`. - [ ] `retention_days` is set and your erasure flow calls `eraseSubjectEverywhere`.