---
title: Security
crumb: Security
eyebrow: Security · the rules that make it safe
h1: What your executor must do, and why.
description: The executor checklist (MUST rules), credential handling, the review UI and webhook rules, and the threat model in plain terms: what ClearedBy protects against, what it relies on you for, and what it doesn't cover.
lede: ClearedBy makes sure nothing is authorised without the merchant's rules or a person saying yes, and signs exactly what was approved. Your executor is the one place that turns an authorisation into a real change, so that is where these rules must hold. Every rule here is a MUST.
pills: Executor checklist, Threat model, Go-live
---

# 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=<hex>` (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`.
