01The executor checklist
Your executor is the only thing that changes the store. Each rule below closes a specific attack; the threat model says which.
- Verify every dispatch with
verifyDispatchbefore doing anything, over the raw body bytes (read the body as text; never re-serialise parsed JSON). Passsecret(the org signing secret),orgId,jwksUrl(orkeys) andaudience. Reject on any error (401). - Execute only
cleared, and only the receipt's params: theparamsthatverifyDispatchreturns. Neverenvelope.data, never anything from the agent, a header or a query string.rejected,expiredandsent_backauthorise nothing: answer2xxand don't act. - 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, answer2xx.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. - Dedupe on
work_item_idwith a unique index, and record "executing" before calling the store. Never dedupe on the receipt'snonceorreceipt_id: every delivery attempt carries new ones. - Answer
409 {"status":"already_executed"}to a repeat. ClearedBy records it as delivered and stops retrying. - Re-check the live state of every item before writing. Write only when the live value still equals the approved
before; report the rest asskipped. For an undo, the same check protects changes people made by hand since. - 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
partialorfailed. Send an idempotency key derived fromwork_item_idwith the store's own mutation. - 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 owncb_live_key (createOrgKey), and keep the partner key out of both. - Report what happened with
complete()(POST /v1/gate/:id/complete): a stablecompletionId, per-item results and thedeliveryReceiptIdyou verified. A2xxto the dispatch only proves you received it. - 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. - Treat the go-live checker's traffic as a test. A request with the header
clearedby-doctor: 1was sent bynpx @clearedby/sdk doctor, not ClearedBy: verify and dedupe it as usual and answer as you would, but never execute or record it. The actiondoctor.noopis never real: touch nothing, and report it done withcomplete()unlessparams.skip_completeistrue.
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; a production-shaped one (Express, a job queue, per-item state checks and partial reports) is in the guide. 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.
02Credentials
| 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.
03Your review UI
- Take the person from your session, never from the request. The org and
external_subjectyou pass tocreateDecisionToken(or return from the proxy'sresolveUser) must come from your own authenticated session. A browser that could name its ownexternal_subjectcould 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 whenintegrityismismatch. - Send looser rule changes to an owner or admin. Show
summary_diffand let only an owner or admin accept (ClearedBy enforces it; your UI should make it obvious).
04Webhooks and alerts
- Verify
X-ClearedBy-Signature: sha256=<hex>(HMAC-SHA256 of the raw body with the subscription'swhsec_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_upespecially: an approved change is not being executed).
05Proposals and data
- Send an
Idempotency-Keyon every proposal, so a retried network call can't create a second clearance. - Send an
audiencenaming your executor on every proposal, and verify it. - Name the shopper in
context.subject_idfor 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 calleraseSubjectEverywherefrom your own erasure flow.
06Threat 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
proofis 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).
07Go-live checklist
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). Then tick off the rest.
npx @clearedby/sdk doctor --fullreports0 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 owncb_live_key. - Every org has
currencyandshop_domainsset, 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-Keyand anaudiencenaming your executor. - The executor uses
verifyDispatchwithorgId,jwksUrl,audience, andcheckStatus: truefor refunds and cancellations. - The executor dedupes on
work_item_idwith a unique index written before execution, and answers409 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_subjectfrom your session, shows onlypermissions.can, and badges evidence by provenance. execution_urlis set and one small auto-cleared change has reached it (delivery()showsdelivered: true).alert_emailand/oralert_webhook_urlare set and someone is paged bypartner.alert.retention_daysis set and your erasure flow callseraseSubjectEverywhere.
Something here doesn't match what you see? Tell your ClearedBy contact, with the clearance id.