# Security model

AIPAY is a non-custodial payment gateway. This page states what protects the money,
what a compromise can and cannot do, and which duties stay with the merchant. It is
written for the person who has to answer "is it safe to route our payments through
this?" — not marketing.

## What AIPAY never holds

- No private key, seed phrase or signing device of any merchant, payer or agent.
- No card data, no bank credential, no provider (Alipay / WeChat Pay / UnionPay /
  Stripe) credential. Off-chain money never reaches AIPAY.
- Payments go from the payer's wallet straight to the merchant's own address. AIPAY
  watches the chain; it cannot move, freeze or redirect funds that already arrived.

## The credential that matters: the merchant API key

Everything an attacker would want sits behind one bearer token. Be precise about it.

| If someone steals a merchant API key, they can… | …and cannot |
| --- | --- |
| Create orders (and burn the merchant's daily quota) | Move funds out of the merchant's wallet |
| Read that merchant's orders (already public on-chain, plus shop/description) | Sign a transaction or a wallet operation |
| Confirm **off-chain** orders (declare "the money arrived") | Confirm an **on-chain** order without a matching transaction: the server re-reads the receipt, the transfer event, the recipient, the amount and the depth |
| **Change the receiving address**, so future payments go to them | Rewrite past orders: each order stores the recipient it was created with |
| Change the webhook URL / rotate its secret | Read or recover the key itself: only its SHA-256 is stored, the plaintext is shown once |
| Rotate or delete the merchant | Access another merchant, or the wallet app |

So the honest answer to "can a breach cost a merchant money?" is: **not from the
wallet, and not retroactively — but yes, a stolen key can redirect future payments
and can fake an off-chain receipt.** Both are addressed below.

## Controls in place

- **Keys**: 43 URL-safe CSPRNG characters, stored as SHA-256 only, returned once;
  rotation keeps the old key valid for 1–72 hours (default 24) so a live integration
  can roll without downtime, and `revokeOldImmediately` exists for a leak.
- **On-chain verification**: receipt status, `Transfer` log (token, recipient,
  amount ≥ order amount), confirmation depth per chain (Tron: 19 blocks; Solana:
  commitment level). Unknown transaction, reverted transaction and mismatch are
  distinct refusals — never a silent confirmation.
- **Off-chain separation**: a chain hash cannot confirm an off-chain order and a
  receipt cannot confirm an on-chain one (`409 channel_mismatch`). Every confirmed
  off-chain order records `confirmedSource` (`merchant_manual`, `merchant_webhook`,
  `statement`) and is labelled as a receipt, never as chain evidence.
- **Webhook integrity**: `sha256=HMAC-SHA256(secret, "<timestamp>.<raw body>")`,
  ±5 minutes, constant-time comparison, retries with a claim/lease so two sweeps
  cannot double-send.
- **Channel secrets**: per-channel HMAC secret, rotated/revoked independently; the
  signature is verified **before** any order lookup, so an unsigned request cannot
  enumerate references.
- **References**: `ap_` + 20 characters from a 32-character alphabet (100 bits,
  CSPRNG) — not guessable, not sequential.
- **Request handling**: 16 KiB body cap, strict validation, parameterised SQL,
  CORS limited to `aipay.im`, `no-store` responses, per-merchant daily order quota
  and per-IP signup quota.
- **Browser surface**: static export, no session cookie, no third-party script on
  the payer page, CSP with `object-src 'none'` and `frame-ancestors 'none'`,
  `X-Frame-Options: DENY`, `nosniff`.
- **Data minimisation**: the API key is hashed; the client IP is stored only as a
  per-day hash for the signup counter; email is optional; orders are kept 90 days.

## Residual risks, and what the merchant must do

1. **Key theft → recipient redirect.** *Highest-impact gap.* Mitigations today:
   rotate the key, keep it server-side, never paste it into chat or a repo. There is
   no second factor on a recipient change yet, and no alert. Treat the key as the
   bank credential it is; if it may have leaked, rotate immediately and check
   `GET /v1/merchants/me` for an address you do not recognise.
2. **Fake off-chain confirmation.** Only your own system or your key can mark an
   off-chain order paid, and AIPAY cannot verify it. If your backend consumes
   `order.confirmed` for off-chain orders, read `confirmedSource` and treat it as
   bookkeeping, not as settlement proof.
3. **Webhook forgery.** Verify the HMAC over the raw body and reject timestamps
   outside ±5 minutes. Never trust an unsigned POST to your webhook URL.
4. **RPC trust.** AIPAY verifies against allow-listed RPC endpoints per chain with
   failover. A lying RPC could misreport a payment; confirmation depth reduces, but
   does not remove, that risk. For very large amounts, reconcile against a second
   source (your own node or the explorer) before shipping.
5. **Chain reorganisations.** Depth thresholds are per chain; on cheap/fast chains a
   deep reorg is unlikely but not impossible. The order keeps the depth it was
   confirmed at.
6. **Availability.** Free-tier quotas are finite (see
   [merchant-order-service.md](merchant-order-service.md) §7). A flood of requests
   can exhaust them; refusals are explicit (`429 rate_limited`), and nothing is
   silently dropped.
7. **Your own systems.** The keys to your webhook handler, your order database and
   your staff devices are outside AIPAY's control. Most real-world losses in payment
   integrations happen there.
8. **A capability is signed, but the machine around it is not.** The agent's
   spending policy now stores each capability with the human's **signature** over
   every field (the same `aipay-grant-v1` envelope used to move one), and the
   engine refuses a capability with no signature, one signed by a key this
   machine does not trust, or one edited after it was signed. A delegated
   capability is checked against its parent on every payment as well: the
   parent's signature, the parent's life, and every bound (scope, budgets,
   window length, approval mode, timelock, stream ceiling) must still hold, and
   a delegation shares the parent's allowance rather than copying it. So a
   capability is a checkable consent, not a claim.

   What is still outside that guarantee: the **trust anchor** lives in a file on
   the agent's machine (`~/.aipay/agent/approval.json`), and the agent process
   runs as you — someone who can rewrite your home directory can move that
   anchor, and can edit the local spend ledger. Keep the approval key's
   passphrase **different** from the wallet keystore's
   (`AIPAY_AGENT_APPROVAL_PASSPHRASE`), keep the agent on a machine you
   control, and treat the local store as untrusted. When you need consent that
   anyone can check, issue a **mandate** (`aipay-mandate-v1`, the user's key,
   covering scope and every cap) as well. See [Automatic payments, spending
   limits and mandates](automation.md).
9. **What is still not signed.** The **local spend ledger** (who spent what) and
   the state file itself are plain local state: a machine owner can delete a
   recorded spend, and the guard marker only stops the accident. The **approval
   token** (the human's key, for one escalated payment) and the **mandate** are
   signed; a capability is signed as well.

## What AIPAY will never claim

- That a confirmed payment means goods were delivered: `delivery` is `not_tracked`.
- That an off-chain confirmation is chain evidence.
- That funds are held, insured or reversible.
- That a local agent policy is enforced on-chain.

If you find a way to contradict any of the above, that is a security report: contact
the operator before publishing it.

See also: [integration guide](integration.md), [API reference](merchant-order-service.md),
and [llms.txt](../llms.txt) for the whole surface in one file.
