Skip to main content

Security Guide

Security is paramount when handling cryptocurrency payments. This guide covers best practices and security measures to protect your integration and users.

API Security

Authentication

Always use secure authentication methods:

// ✅ Good - Use environment variables
const apiKey = process.env.CRYPTOPAY_API_KEY;

// ❌ Bad - Never hardcode API keys
const apiKey = 'cp_live_abc123def456';

API Key Management

  • Environment Variables: Store API keys in environment variables
  • Key Rotation: Rotate API keys regularly (every 90 days)
  • Separate Keys: Use different keys for development, staging, and production
  • Least Privilege: Use keys with minimal required permissions
# .env file
CRYPTOPAY_API_KEY=cp_live_abc123def456
CRYPTOPAY_WEBHOOK_SECRET=whsec_def456ghi789

Webhook Security

HMAC Signature Verification

Always verify webhook signatures to prevent spoofing:

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload, 'utf8')
.digest('hex');

// Use constant-time comparison to prevent timing attacks
return crypto.timingSafeEqual(
Buffer.from(signature, 'hex'),
Buffer.from(expectedSignature, 'hex')
);
}

IP Whitelisting

Restrict webhook access to our IP addresses:

# Nginx configuration
location /webhooks/cryptopay {
allow 52.89.214.238;
allow 54.218.53.128;
allow 52.32.178.7;
deny all;

proxy_pass http://your-app;
}

HTTPS Only

Always use HTTPS for webhook endpoints:

// ✅ Good
const webhookUrl = 'https://your-site.com/webhooks/cryptopay';

// ❌ Bad - Never use HTTP for production
const webhookUrl = 'http://your-site.com/webhooks/cryptopay';

Payment Security

Amount Validation

Always validate payment amounts match your expectations:

function validatePayment(webhookData) {
const { order_id, amount, currency } = webhookData.data;

// Get expected amount from your database
const expectedOrder = await getOrderFromDatabase(order_id);

if (expectedOrder.amount !== amount) {
throw new Error(`Amount mismatch: expected ${expectedOrder.amount}, got ${amount}`);
}

if (expectedOrder.currency !== currency) {
throw new Error(`Currency mismatch: expected ${expectedOrder.currency}, got ${currency}`);
}

return true;
}

Confirmation Requirements

Set appropriate confirmation thresholds based on payment value:

Payment ValueRecommended Confirmations
< $1001-3 confirmations
$100 - $1,0006-12 confirmations
> $1,00012+ confirmations
function getRequiredConfirmations(amount) {
const value = parseFloat(amount);

if (value < 100) return 3;
if (value < 1000) return 12;
return 24; // High-value transactions
}

Double-Spend Protection

Our system includes built-in double-spend protection:

  • Nonce Validation: Each payment order has a unique nonce
  • Transaction Monitoring: We monitor for conflicting transactions
  • Confirmation Tracking: Payments aren't confirmed until reaching threshold
  • Reorg Handling: We handle blockchain reorganizations automatically

Data Protection

PII Handling

Minimize collection and storage of personally identifiable information:

// ✅ Good - Minimal data collection
const orderInfo = {
product_id: 'premium_plan',
quantity: 1,
customer_reference: 'user_123' // Use internal ID, not email
};

// ❌ Bad - Storing sensitive PII
const orderInfo = {
customer_email: 'user@example.com',
customer_name: 'John Doe',
customer_address: '123 Main St'
};

Data Encryption

Encrypt sensitive data at rest and in transit:

const crypto = require('crypto');

// Encrypt sensitive order data
function encryptOrderData(data, key) {
const cipher = crypto.createCipher('aes-256-cbc', key);
let encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}

Infrastructure Security

Network Security

  • Firewall Rules: Restrict access to necessary ports only
  • VPN Access: Use VPN for administrative access
  • DDoS Protection: Implement DDoS protection for public endpoints
  • Rate Limiting: Implement rate limiting on API endpoints

Server Security

# Example security headers
server {
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
add_header Content-Security-Policy "default-src 'self'";
}

Database Security

  • Connection Encryption: Use SSL/TLS for database connections
  • Access Control: Implement proper database user permissions
  • Backup Encryption: Encrypt database backups
  • Audit Logging: Enable database audit logging

Monitoring and Alerting

Security Monitoring

Implement monitoring for security events:

// Monitor for suspicious activity
function monitorPaymentActivity(webhookData) {
const { amount, from_address, order_id } = webhookData.data;

// Alert on high-value transactions
if (parseFloat(amount) > 10000) {
sendAlert(`High-value payment: ${amount} for order ${order_id}`);
}

// Monitor for unusual patterns
checkForUnusualActivity(from_address, amount);
}

function sendAlert(message) {
// Send to monitoring service (Slack, PagerDuty, etc.)
console.log(`SECURITY ALERT: ${message}`);
}

Failed Payment Monitoring

Monitor for failed payments that might indicate attacks:

function monitorFailedPayments(failureData) {
const { reason, order_id, from_address } = failureData;

// Track failed attempts by address
const failureCount = incrementFailureCount(from_address);

if (failureCount > 5) {
blockAddress(from_address);
sendAlert(`Address ${from_address} blocked after ${failureCount} failed attempts`);
}
}

Compliance

AML/KYC Considerations

While CryptoPay doesn't require KYC, consider your local regulations:

  • Transaction Limits: Implement limits based on local requirements
  • Suspicious Activity: Monitor and report suspicious transactions
  • Record Keeping: Maintain transaction records as required by law

GDPR Compliance

If serving EU customers:

  • Data Minimization: Collect only necessary data
  • Right to Deletion: Implement data deletion capabilities
  • Privacy Policy: Clearly explain data usage
  • Consent Management: Implement proper consent mechanisms

Incident Response

Security Incident Plan

  1. Detection: Monitor for security events
  2. Assessment: Evaluate the scope and impact
  3. Containment: Isolate affected systems
  4. Investigation: Determine root cause
  5. Recovery: Restore normal operations
  6. Lessons Learned: Update security measures

Emergency Contacts

Maintain emergency contact information:

const emergencyContacts = {
security_team: 'security@yourcompany.com',
cryptopay_support: 'security@cryptopay.com',
incident_response: '+1-555-SECURITY'
};

Security Checklist

Pre-Production

  • API keys stored in environment variables
  • Webhook signature verification implemented
  • HTTPS enforced for all endpoints
  • Input validation on all user data
  • Rate limiting implemented
  • Security headers configured
  • Database connections encrypted
  • Monitoring and alerting configured

Production

  • Regular security audits
  • API key rotation schedule
  • Backup and recovery procedures
  • Incident response plan
  • Staff security training
  • Compliance requirements met
  • Third-party security assessments

Best Practices Summary

  1. Never trust user input - Validate everything
  2. Use HTTPS everywhere - No exceptions
  3. Verify webhook signatures - Prevent spoofing
  4. Monitor everything - Log and alert on anomalies
  5. Principle of least privilege - Minimal required permissions
  6. Defense in depth - Multiple security layers
  7. Regular updates - Keep dependencies current
  8. Incident preparedness - Have a response plan

Getting Help

If you discover a security vulnerability:

  • Email: security@cryptopay.com
  • PGP Key: Available on our website
  • Bug Bounty: We offer rewards for valid security reports

For security questions or concerns:

  • Support: support@cryptopay.com
  • Documentation: This security guide
  • Community: Join our Discord for discussions

Remember: Security is an ongoing process, not a one-time setup. Regularly review and update your security measures as your application grows and evolves.