Yaltopia-Ticket-Admin/dev-docs/SECURITY.md

8.0 KiB

Security Guide

Current Security Implementation

Authentication

  • JWT tokens stored in localStorage
  • Automatic token attachment to API requests via Axios interceptor
  • Automatic redirect to login on 401 (Unauthorized) responses
  • Token removal on logout

API Security

  • HTTPS enforcement (production requirement)
  • CORS configuration on backend
  • Error handling for common HTTP status codes (401, 403, 404, 500)
  • Network error handling

Client-Side Protection

  • Error boundary for graceful error handling
  • Input validation on forms
  • XSS protection via React's built-in escaping

Security Improvements for Production

1. Token Storage (High Priority)

Current Issue: Tokens in localStorage are vulnerable to XSS attacks.

Recommended Solution: Use httpOnly cookies

Backend changes needed:

// Set cookie on login
res.cookie('access_token', token, {
  httpOnly: true,
  secure: true, // HTTPS only
  sameSite: 'strict',
  maxAge: 24 * 60 * 60 * 1000 // 24 hours
});

Frontend changes:

// Remove localStorage token handling
// Cookies are automatically sent with requests
// Update api-client.ts to remove token interceptor

2. Content Security Policy (CSP)

Add to your hosting platform or nginx configuration:

Content-Security-Policy: 
  default-src 'self';
  script-src 'self' 'unsafe-inline' 'unsafe-eval';
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  font-src 'self' data:;
  connect-src 'self' https://api.yourdomain.com;
  frame-ancestors 'none';

Note: Adjust unsafe-inline and unsafe-eval as you refine your CSP.

3. HTTPS Enforcement

Required for production!

  • Obtain SSL/TLS certificate (Let's Encrypt, Cloudflare, etc.)
  • Configure your hosting platform to enforce HTTPS
  • Add HSTS header:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

4. Input Validation & Sanitization

Always validate and sanitize user inputs:

// Example: Email validation
const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// Example: Sanitize HTML (if displaying user content)
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(dirty);

5. Rate Limiting

Implement on backend:

  • Login attempts: 5 per 15 minutes per IP
  • API calls: 100 per minute per user
  • Password reset: 3 per hour per email

Consider using:

  • express-rate-limit (Node.js)
  • Cloudflare rate limiting
  • API Gateway rate limiting (AWS, Azure, GCP)

6. Dependency Security

Regular security audits:

# Check for vulnerabilities
npm audit

# Fix automatically (if possible)
npm audit fix

# Update dependencies
npm update

# Check for outdated packages
npm outdated

Set up automated dependency updates:

  • Dependabot (GitHub)
  • Renovate Bot
  • Snyk

7. Error Handling

Don't expose sensitive information in errors:

// Bad
catch (error) {
  toast.error(error.message); // May expose stack traces
}

// Good
catch (error) {
  console.error('Error details:', error); // Log for debugging
  toast.error('An error occurred. Please try again.'); // Generic message
}

8. Secrets Management

Never commit secrets to git:

  • Use environment variables
  • Use secret management services (AWS Secrets Manager, Azure Key Vault, etc.)
  • Add .env* to .gitignore
  • Use different secrets for dev/staging/production

9. API Key Protection

If using third-party APIs:

// Bad - API key in client code
const API_KEY = 'sk_live_123456789';

// Good - Proxy through your backend
const response = await fetch('/api/proxy/third-party-service', {
  method: 'POST',
  body: JSON.stringify(data)
});

10. Session Management

Implement proper session handling:

  • Session timeout after inactivity (15-30 minutes)
  • Logout on browser close (optional)
  • Single session per user (optional)
  • Session invalidation on password change
// Example: Auto-logout on inactivity
let inactivityTimer: NodeJS.Timeout;

const resetInactivityTimer = () => {
  clearTimeout(inactivityTimer);
  inactivityTimer = setTimeout(() => {
    // Logout user
    localStorage.removeItem('access_token');
    window.location.href = '/login';
  }, 30 * 60 * 1000); // 30 minutes
};

// Reset timer on user activity
document.addEventListener('mousemove', resetInactivityTimer);
document.addEventListener('keypress', resetInactivityTimer);

Security Headers Checklist

Configure these headers on your server/hosting platform:

  • X-Frame-Options: SAMEORIGIN
  • X-Content-Type-Options: nosniff
  • X-XSS-Protection: 1; mode=block
  • Referrer-Policy: strict-origin-when-cross-origin
  • Strict-Transport-Security: max-age=31536000; includeSubDomains
  • Content-Security-Policy: ...
  • Permissions-Policy: geolocation=(), microphone=(), camera=()

Monitoring & Incident Response

1. Error Tracking

Implement error tracking service:

// Example: Sentry integration
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: import.meta.env.VITE_SENTRY_DSN,
  environment: import.meta.env.VITE_ENV,
  tracesSampleRate: 1.0,
});

2. Security Monitoring

Monitor for:

  • Failed login attempts
  • Unusual API usage patterns
  • Error rate spikes
  • Slow response times
  • Unauthorized access attempts

3. Incident Response Plan

  1. Detection: Monitor logs and alerts
  2. Assessment: Determine severity and impact
  3. Containment: Isolate affected systems
  4. Eradication: Remove threat
  5. Recovery: Restore normal operations
  6. Lessons Learned: Document and improve

Compliance Considerations

GDPR (if applicable)

  • User data encryption
  • Right to be forgotten
  • Data export functionality
  • Privacy policy
  • Cookie consent

HIPAA (if handling health data)

  • Additional encryption requirements
  • Audit logging
  • Access controls
  • Business Associate Agreements

PCI DSS (if handling payments)

  • Never store credit card data in frontend
  • Use payment gateway (Stripe, PayPal, etc.)
  • Secure transmission (HTTPS)

Security Testing

Manual Testing

  • Test authentication flows
  • Test authorization (role-based access)
  • Test input validation
  • Test error handling
  • Test session management

Automated Testing

Penetration Testing

Consider hiring security professionals for:

  • Vulnerability assessment
  • Penetration testing
  • Security code review

Security Checklist for Production

  • HTTPS enabled with valid certificate
  • All security headers configured
  • CSP implemented
  • Tokens stored securely (httpOnly cookies)
  • Input validation on all forms
  • Rate limiting configured
  • Error tracking service active
  • Regular security audits scheduled
  • Dependency updates automated
  • Secrets properly managed
  • Backup and recovery plan in place
  • Incident response plan documented
  • Team trained on security best practices

Resources

Reporting Security Issues

If you discover a security vulnerability:

  1. Do not open a public issue
  2. Email security@yourdomain.com
  3. Include detailed description and steps to reproduce
  4. Allow reasonable time for fix before disclosure

Regular Security Tasks

Daily

  • Monitor error logs
  • Check failed login attempts

Weekly

  • Review security alerts
  • Check for dependency updates

Monthly

  • Run security audit: npm audit
  • Update dependencies
  • Review access logs

Quarterly

  • Security training for team
  • Review and update security policies
  • Penetration testing (if budget allows)

Annually

  • Comprehensive security audit
  • Update incident response plan
  • Review compliance requirements