# SECURITY &  PRIVACY

Operational security baseline for WDK + USDT0 integrations in production. Covers key management, nonce hygiene, signing security, logging practices, and incident response.

## Threat Model

WDK settlement involves three security-critical assets: the private key that signs authorizations, the nonces that prevent replay, and the API key that authenticates to P402. Compromise of any one of these can result in fund loss.

| Threat               | Impact                                                      | Mitigation                                                                                           |
|---------------------|------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
| Private key leak    | Attacker can sign unlimited transfers.                     | Use hardware wallets or HSMs. Never log or transmit private keys. Rotate immediately if suspected. |
| Nonce replay        | Attacker replays a valid signature to settle again.       | P402 tracks all nonces in the replay protection DB. Each nonce can only be settled once.          |
| API key leak        | Attacker can call settlement on your behalf.              | SHA-256 hashed at rest. Rotate immediately via Dashboard → Settings → API Keys. Use scoped keys per environment. |
| Man-in-the-middle    | Attacker intercepts and modifies settlement requests.     | All P402 endpoints enforce HTTPS/TLS 1.3. EIP-712 signatures bind to exact authorization fields — modification breaks verification. |
| Expired authorization| User signs but settlement is delayed past validBefore.    | Set validBefore to at least 1 hour from signing time. Always handle P402_SETTLEMENT_TIMEOUT errors. |
| Amount manipulation  | Service charges more than declared.                       | P402 enforces amount matching at the facilitator layer. Requests where value ≠ maxAmountRequired are rejected. |

## Key Management

### For user-facing flows

When users sign their own authorizations (e.g. paying from their MetaMask wallet), the private key never leaves the browser. The WDK adapter calls the wallet's `eth_signTypedData_v4` method. The signature is the only thing your backend receives.

#### Do / Don't

✓ Receive the signature from the frontend and forward it directly to P402.

✓ Validate the returned receipt on your backend to confirm settlement.

✗ Ask users to send you their private key or seed phrase.

✗ Store the signature in a database — it has no value after settlement.

✗ Log the full authorization object in plaintext application logs.

### For server-side / agent flows

When your server or an autonomous agent signs authorizations, the private key lives in your infrastructure. Apply these practices:

- **Use environment variables**  
  Store the private key in an environment variable, never in code or config files that could be committed to version control.

- **Prefer HSMs or TEEs for production**  
  P402 supports CDP Server Wallets (TEE-backed). The private key never leaves the hardware. Signing happens inside the secure enclave.

- **Separate keys per environment**  
  Use different signing keys for development, staging, and production. A dev key leak cannot drain production funds.

- **Implement key rotation before go-live**  
  Build a rotation procedure before you go to production. Rotation must be zero-downtime: generate new key, update P402 wallet record, retire old key.

## Nonce Hygiene

A nonce is a 32-byte random value embedded in every EIP-3009 authorization. P402 records every used nonce and rejects any settlement that reuses one — this is the replay protection mechanism.

### Critical rule

Never reuse a nonce. Never generate nonces from sequential IDs, timestamps, or deterministic inputs. Always generate 32 cryptographically random bytes.

```typescript
// Correct: 32 cryptographically random bytes
const nonce = '0x' + crypto.getRandomValues(new Uint8Array(32))
  .reduce((hex, b) => hex + b.toString(16).padStart(2, '0'), '');

// Wrong: predictable, not 32 bytes of entropy
// const nonce = `0x${Date.now().toString(16)}`;            // Too short
// const nonce = `0x${invoiceId.replace(/-/g, '')}`;        // Deterministic
// const nonce = `0x${counter++}`;                          // Sequential
```

## Logging Practices

Settlement flows involve sensitive data. Log enough to debug incidents without creating a liability for your users.

| Data                       | Log it?       | Why                                                        |
|---------------------------|---------------|------------------------------------------------------------|
| receipt_id                | Yes — always  | Essential for support and reconciliation.                   |
| txHash                    | Yes — always  | Needed to verify settlement on-chain.                       |
| walletAddress (from)      | Yes — masked  | Log first 6 + last 4 chars: 0xABCD...1234                 |
| amount + asset            | Yes — always  | Needed for spend auditing.                                   |
| signature                 | No            | No value after settlement; storing creates unnecessary risk. |
| private key / nonce       | Never         | Catastrophic if leaked.                                     |
| full authorization object  | Dev/staging only | OK for debugging; never in production.                      |
| P402 API key             | Never         | Store only the last 4 chars for identification.            |

## Privacy Considerations

Settlement transactions are recorded on-chain and are permanently public. Communicate this clearly to your users.

### On-chain data is public

Every settled transaction is visible on Base or Arbitrum block explorers. The from address, to address, amount, and timestamp are public permanently.

### Wallet addresses are pseudonymous, not anonymous

A wallet address does not directly identify a person, but on-chain activity can be linked to real identities through other data. Do not assume on-chain payments are anonymous.

### P402 processes personal data

P402 logs wallet addresses, API keys, and transaction metadata for fraud prevention and support. Review the P402 Privacy Policy before processing payments on behalf of EU/UK users (GDPR implications).

### Minimize stored payment metadata

Store only what you need: receipt_id, txHash, amount, and masked wallet address. Never persist raw private keys, seed phrases, or full authorization objects.

### Implement retention policies

Document how long you retain receipts, audit logs, and payment events. Follow applicable regulations for your jurisdiction and user base.

## Incident Response

If you suspect a key compromise or unauthorized settlement, act immediately:

1. **Rotate the compromised key**  
   For P402 API keys: Dashboard → Settings → API Keys → Revoke. Generate a new key immediately. For signing keys: generate a new wallet, update all references, and drain the old wallet to the new one.

2. **Review recent settlements**  
   Pull settlement history from Dashboard → Transactions. Look for unexpected wallet addresses in the "from" field or amounts you did not authorize.

3. **Enable emergency pause**  
   If you have admin access, use POST /api/v1/admin/security with action: "pause" to halt all settlements for your account while you investigate.

4. **Contact P402 support**  
   Email security@p402.io with incident details. Include the compromised key's last 4 chars, time range of suspected activity, and any txHashes you believe are unauthorized.
