Skip to content

Security Best Practices

Azizul Hakim edited this page Nov 1, 2024 · 3 revisions

Core Security Principles

Token Management

  1. Token Lifetime

    • Keep tokens short-lived (10 seconds recommended)
    • Never store tokens in localStorage or cookies
    • Generate new tokens for each request
    // Good Practice
    const token = generateXSecurityToken(secret, 10); // 10 seconds
    
    // Bad Practice - Too Long
    const token = generateXSecurityToken(secret, 3600); // 1 hour
  2. Secret Key Management

    • Use strong, random secrets
    • Minimum 32 characters length
    • Rotate secrets regularly
    // Generate secure secret
    import crypto from 'crypto';
    const secret = crypto.randomBytes(32).toString('hex');
    
    // Configure in environment
    XSECURITY_SECRET=your-very-long-and-secure-secret-key

Rate Limiting

  1. Production Settings
    XSecurityModule.register({
      rateLimit: {
        enabled: true,         // exclusively only enable/disable rate limit
        maxAttempts: 3,        // Stricter limits in production
        decayMinutes: 5,       // Longer lockout period
        cleanupInterval: 1,    // Frequent cleanup
      }
    });

Environment-Specific Configuration

Development

// development.env
XSECURITY_ENABLED=true
XSECURITY_MAX_ATTEMPTS=5
XSECURITY_DECAY_MINUTES=1

Production

// production.env
XSECURITY_ENABLED=true
XSECURITY_MAX_ATTEMPTS=3
XSECURITY_DECAY_MINUTES=5

Route Protection

  1. Exclude Public Routes

    XSecurityModule.register({
      exclude: [
        '/health',
        '/metrics',
        '/public/*',
        /^\/docs\/.*/,
      ],
    });
  2. Critical Endpoints

    // Stricter rate limiting for authentication endpoints
    XSecurityModule.register({
      rateLimit: {
        enabled: true,
        maxAttempts: 3,
        decayMinutes: 10,
      },
    });

Related Topics