Security Model
Overview
Security is foundational to the x402 Protocol. We've designed a multi-layered security model that protects users, providers, and the network from fraud, attacks, and system failures.
Security Principles
Core Tenets
- Defense in Depth: Multiple security layers, no single point of failure
- Least Privilege: Minimal permissions for all components
- Transparency: Open-source contracts, public audits
- Privacy First: No unnecessary data collection
- Fail Secure: Systems default to safe state on error
Security First
Every architectural decision prioritizes security over convenience. We never compromise on safety.
Threat Model
Potential Threats
User Threats:
- Phishing attacks
- Wallet compromise
- Man-in-the-middle attacks
- Transaction replay
Provider Threats:
- Payment fraud
- DDoS attacks
- Data breaches
- API abuse
Network Threats:
- Smart contract exploits
- Consensus attacks
- Front-running
- MEV extraction
Cryptographic Security
Payment Signing
ECDSA Signatures:
import { signPayment } from '402x-sdk';
const signature = await signPayment({
invoiceId: 'inv_123',
amount: 0.05,
recipient: '0x742d35Cc...',
nonce: Date.now(),
privateKey: userPrivateKey
});Verification:
import { verifySignature } from '402x-sdk';
const isValid = verifySignature({
message: paymentMessage,
signature: signature,
publicKey: userPublicKey
});Nonce Management
Preventing Replay Attacks:
const nonce = {
timestamp: Date.now(),
random: crypto.randomBytes(16).toString('hex'),
counter: incrementCounter()
};
// Nonce is valid for 60 seconds
const NONCE_EXPIRY = 60000;
function validateNonce(nonce) {
const age = Date.now() - nonce.timestamp;
if (age > NONCE_EXPIRY) {
throw new Error('Nonce expired');
}
if (usedNonces.has(nonce.toString())) {
throw new Error('Nonce already used');
}
usedNonces.add(nonce.toString());
return true;
}Smart Contract Security
Audit & Verification
Security Measures:
- ✅ Multiple independent audits (Trail of Bits, OpenZeppelin)
- ✅ Formal verification of critical functions
- ✅ Bug bounty program ($100k+ rewards)
- ✅ Continuous monitoring
- ✅ Emergency pause mechanism
Audited Contracts:
// X402Payment.sol - Audited by Trail of Bits
contract X402Payment is Pausable, ReentrancyGuard {
using SafeMath for uint256;
// All state-changing functions are protected
function pay(...)
external
payable
whenNotPaused
nonReentrant
{
// Payment logic
}
}Upgrade Mechanism
Safe Upgrades:
// Using OpenZeppelin's TransparentUpgradeableProxy
contract X402PaymentV2 is X402Payment {
// New features added here
// Existing storage layout preserved
function newFeature() external {
// New functionality
}
}Upgrade Process:
- Develop new version
- Third-party audit
- Testnet deployment
- 7-day timelock
- Multi-sig approval
- Mainnet upgrade
- Monitoring period
API Security
Authentication & Authorization
API Key Authentication:
// Provider API key
const apiKey = process.env.X402_API_KEY;
const response = await fetch('https://api.402x.io/payments', {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});Request Signing:
import { createHmac } from 'crypto';
const signature = createHmac('sha256', secretKey)
.update(JSON.stringify(requestBody))
.digest('hex');
const headers = {
'X-402-Signature': signature,
'X-402-Timestamp': Date.now()
};Rate Limiting
Multi-Tier Rate Limits:
const rateLimits = {
perSecond: 10,
perMinute: 100,
perHour: 1000,
perDay: 10000
};
// Adaptive rate limiting based on trust score
const limit = calculateLimit({
baseLimt: rateLimits.perSecond,
trustScore: user.trustScore,
historyFactor: user.reliabilityScore
});DDoS Protection:
- Cloudflare WAF
- Request validation
- IP reputation checking
- Automatic blacklisting
- Challenge-response for suspicious traffic
Payment Security
Fraud Detection
Real-Time Analysis:
const fraudScore = calculateFraudScore({
// Velocity checks
paymentsLast5Min: userHistory.recent,
// Pattern analysis
typicalAmount: userHistory.avgAmount,
typicalTime: userHistory.avgTime,
// Device fingerprinting
deviceId: request.deviceId,
ipAddress: request.ip,
// Behavioral analysis
mouseMovements: request.biometrics,
typingPattern: request.typingBiometrics
});
if (fraudScore > 0.8) {
await requireAdditionalVerification();
} else if (fraudScore > 0.5) {
await delayPayment(30); // 30 second delay
}Fraud Indicators:
- 🚩 Unusual payment velocity
- 🚩 Geographic inconsistencies
- 🚩 Device fingerprint mismatch
- 🚩 Behavioral anomalies
- 🚩 Known fraud patterns
Refund Protection
Provider Protection:
const refundPolicy = {
// Refund window (configurable by provider)
windowSeconds: 600, // 10 minutes default
// Maximum refund percentage
maxRefundRate: 0.05, // 5% of payments
// Automatic fraud detection
autoRejectSuspicious: true,
// Manual review threshold
manualReviewAmount: 100 // $100+
};User Protection:
- Escrow for high-value transactions
- Dispute resolution system
- Automatic refunds for failed delivery
- Transparent refund policies
Data Security
Encryption
Data at Rest:
// AES-256-GCM encryption
const encrypted = encrypt({
data: sensitiveData,
key: deriveKey(masterKey, salt),
algorithm: 'aes-256-gcm'
});Data in Transit:
- TLS 1.3 minimum
- Perfect forward secrecy
- Certificate pinning
- HSTS headers
Privacy & Compliance
Data Minimization:
// Only store essential data
const paymentRecord = {
invoiceId: invoice.id,
amount: invoice.amount,
timestamp: Date.now(),
status: 'confirmed',
// No PII stored
// No wallet addresses (hashed only)
// No IP addresses (aggregated only)
};GDPR Compliance:
- Right to erasure
- Data portability
- Consent management
- Privacy by design
- Data processing agreements
PCI Compliance:
- No credit card data stored
- Crypto payments only
- Regular security audits
- Incident response plan
Network Security
Node Security
Provider Node Hardening:
# Firewall configuration
ufw allow 443/tcp
ufw allow 80/tcp
ufw deny 22/tcp from any
ufw enable
# Automatic security updates
apt-get install unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades
# Fail2ban for intrusion prevention
apt-get install fail2ban
systemctl enable fail2banMonitoring:
// Real-time threat monitoring
monitor.on('suspicious-activity', async (event) => {
await notifySecurityTeam(event);
if (event.severity === 'critical') {
await automaticMitigation(event);
}
});Consensus Security
Payment Verification:
// Wait for multiple confirmations for high-value
const requiredConfirmations = amount > 1000 ? 12 : 1;
const receipt = await waitForConfirmations({
txHash: transaction.hash,
confirmations: requiredConfirmations
});Incident Response
Security Incident Protocol
1. Detection:
- Automated monitoring alerts
- User reports
- Security research disclosures
- Bug bounty submissions
2. Assessment:
const incidentSeverity = assessIncident({
scope: 'How many users affected?',
impact: 'What is at risk?',
exploitability: 'How easy to exploit?',
publicKnowledge: 'Is it public?'
});
// Critical: Immediate response, all hands
// High: 4-hour response time
// Medium: 24-hour response time
// Low: Next sprint3. Containment:
- Pause affected systems
- Isolate compromised components
- Prevent further damage
4. Recovery:
- Deploy fixes
- Restore services
- Verify integrity
5. Post-Mortem:
- Root cause analysis
- Lessons learned
- Process improvements
- Public disclosure (if applicable)
Emergency Procedures
Smart Contract Pause:
// Emergency pause (multi-sig only)
function emergencyPause() external onlyMultiSig {
_pause();
emit EmergencyPaused(msg.sender, block.timestamp);
}
function emergencyUnpause() external onlyMultiSig {
require(pausedFor() >= MIN_PAUSE_DURATION, "Too soon");
_unpause();
emit EmergencyUnpaused(msg.sender, block.timestamp);
}Multi-Sig Security:
- 3-of-5 multi-signature requirement
- Time-delayed execution
- Geographic distribution of signers
- Hardware wallet storage
Bug Bounty Program
Rewards
| Severity | Reward | Examples |
|---|---|---|
| Critical | $50,000+ | Smart contract exploits, authentication bypass |
| High | $10,000 - $50,000 | Payment fraud, data breaches |
| Medium | $2,000 - $10,000 | DoS vectors, information disclosure |
| Low | $500 - $2,000 | Minor bugs, configuration issues |
Scope
In Scope:
- ✅ Smart contracts
- ✅ API endpoints
- ✅ SDK libraries
- ✅ Payment flows
- ✅ Authentication systems
Out of Scope:
- ❌ Social engineering
- ❌ Physical attacks
- ❌ Third-party services
- ❌ Known issues
- ❌ Spam/DoS
Submission Process
- Report: [email protected] (PGP encrypted)
- Acknowledgment: Within 24 hours
- Validation: Within 7 days
- Fix: Timeline based on severity
- Reward: Within 30 days of fix
- Disclosure: Coordinated public disclosure
Security Best Practices
For Providers
✅ Do:
- Use environment variables for secrets
- Implement rate limiting
- Validate all inputs
- Use HTTPS everywhere
- Keep dependencies updated
- Monitor for suspicious activity
- Implement proper error handling
❌ Don't:
- Store private keys in code
- Trust client-side data
- Use weak passwords
- Disable security features
- Ignore security warnings
- Skip updates
For Users
✅ Do:
- Use hardware wallets for large amounts
- Verify URLs before connecting wallet
- Check transaction details carefully
- Keep software updated
- Use strong passwords
- Enable 2FA where available
❌ Don't:
- Share private keys
- Click suspicious links
- Use public WiFi for payments
- Ignore wallet warnings
- Rush transactions
For Integrators
// Good: Proper error handling and validation
try {
const payment = await verifyPayment(invoice);
if (payment.amount !== expectedAmount) {
throw new Error('Amount mismatch');
}
if (payment.status !== 'confirmed') {
throw new Error('Payment not confirmed');
}
await deliverContent(payment);
} catch (error) {
logger.error('Payment verification failed', error);
await handlePaymentFailure(invoice);
}
// Bad: Trusting without verification
const payment = await getPayment(invoice);
await deliverContent(payment); // ❌ No validation!Security Audits
Audit History
2024 Q4 - Trail of Bits
- Smart contracts
- Critical infrastructure
- Findings: 0 critical, 2 medium (fixed)
2025 Q1 - OpenZeppelin
- Payment flows
- API security
- Findings: 0 critical, 1 medium (fixed), 3 low (acknowledged)
2025 Q2 - Certora (Formal Verification)
- Core payment logic
- State machine verification
- Findings: 0 issues
Continuous Security
- Weekly dependency updates
- Monthly penetration testing
- Quarterly security reviews
- Annual comprehensive audits
- 24/7 security monitoring
Compliance
Regulatory Compliance
AML/KYC:
- Transaction monitoring
- Risk-based approach
- Suspicious activity reporting
- Record keeping
Data Protection:
- GDPR (Europe)
- CCPA (California)
- Privacy Shield
- Data localization
Financial Regulations:
- FinCEN guidance
- SEC compliance
- State money transmitter licenses
- International regulations
Resources
Report Security Issues
If you discover a security vulnerability, please email [email protected] immediately. Do not open a public issue.
PGP Key: Download