My App
Api

Security Considerations

Security best practices and considerations for the HMS API

Authentication Security

Token Management

Access Tokens

  • Short lifetime (15 minutes) to minimize exposure window
  • Stored in HTTP-only cookies to prevent XSS attacks
  • Automatically cleared on logout

Refresh Tokens

  • Longer lifetime (7 days) for user convenience
  • Stored in HTTP-only cookies
  • Should be rotated on use (recommended enhancement)

Token Validation

  • All tokens are cryptographically signed with JWT
  • Tokens include user ID, user type, and email
  • Expired tokens are automatically rejected

Password Security

Hashing

  • Passwords are hashed using bcrypt with salt rounds
  • Never stored in plain text
  • Salt is automatically generated per password

Password Reset

  • Reset tokens are cryptographically secure random strings
  • Tokens expire after 1 hour
  • Tokens are single-use only
  • Tokens are marked as used immediately after password reset

Password Requirements

  • Minimum length: 8 characters (enforced on frontend)
  • Should include uppercase, lowercase, numbers, and special characters
  • Common passwords should be rejected

HTTP-Only Flag

  • Prevents JavaScript access to cookies
  • Protects against XSS attacks

Secure Flag

  • Enabled in production (HTTPS only)
  • Prevents transmission over unencrypted connections

SameSite Flag

  • Set to Lax to prevent CSRF attacks
  • Allows cookies to be sent with top-level navigations

Cookie Expiration

  • Access tokens: 15 minutes
  • Refresh tokens: 7 days
  • Automatically cleared on logout

Input Validation

Zod Schemas

  • All request bodies are validated using Zod schemas
  • Invalid input is rejected before processing
  • Prevents injection attacks and malformed data

Email Validation

  • Email format is validated
  • Email normalization (lowercase) prevents duplicate accounts

Password Validation

  • Password strength requirements enforced
  • Password confirmation required for registration/reset

Rate Limiting

Recommended Implementation

  • Authentication endpoints: 5 attempts per 15 minutes per IP
  • Password reset endpoints: 3 attempts per hour per IP
  • Profile update endpoints: 10 requests per minute per user

Current Status

  • ⚠️ Rate limiting not yet implemented
  • Should be added before production deployment

Email Enumeration Prevention

Password Reset

  • Always returns 200 OK, regardless of email existence
  • Prevents attackers from discovering valid email addresses
  • Email is only sent if account exists

Login

  • Generic error message: "Invalid credentials"
  • Does not distinguish between invalid email and invalid password

CORS Configuration

Allowed Origins

  • Only configured frontend origins are allowed
  • Credentials are required for cookie-based authentication
  • Prevents unauthorized cross-origin requests

Current Configuration

cors({
  origin: process.env.FRONTEND_URL || 'http://localhost:3000',
  credentials: true,
})

SQL Injection Prevention

Prisma ORM

  • All database queries use Prisma ORM
  • Parameterized queries prevent SQL injection
  • Type-safe queries prevent malformed queries

XSS Prevention

HTTP-Only Cookies

  • Tokens stored in HTTP-only cookies cannot be accessed by JavaScript
  • Prevents XSS attacks from stealing tokens

Input Sanitization

  • User input is validated and sanitized
  • No raw HTML is stored or displayed

CSRF Protection

SameSite Cookies

  • Cookies use SameSite=Lax to prevent CSRF attacks
  • Cookies are not sent with cross-site requests

Token Validation

  • All protected routes validate JWT tokens
  • Tokens cannot be forged without secret key

Security Best Practices

Implemented ✅

  • ✅ HTTP-only cookies for token storage
  • ✅ Secure cookie flags in production
  • ✅ Password hashing with bcrypt
  • ✅ JWT token expiration
  • ✅ Single-use password reset tokens
  • ✅ Email enumeration prevention
  • ✅ CORS configuration
  • ✅ Input validation with Zod
  • ✅ SQL injection prevention (Prisma)
  • ✅ XSS prevention (HTTP-only cookies)
  • ✅ CSRF protection (SameSite cookies)
  • ⚠️ Rate Limiting: Implement on all authentication endpoints
  • ⚠️ Refresh Token Rotation: Rotate refresh tokens on use
  • ⚠️ Account Lockout: Lock accounts after failed login attempts
  • ⚠️ 2FA: Add two-factor authentication for admin accounts
  • ⚠️ Session Management: Track active sessions and allow revocation
  • ⚠️ Audit Logging: Log all authentication events
  • ⚠️ IP Whitelisting: Optional IP whitelisting for admin accounts
  • ⚠️ Password History: Prevent reuse of recent passwords
  • ⚠️ Security Headers: Add security headers (HSTS, CSP, etc.)

Environment Variables

Required for Security

# JWT Secrets (must be strong, random strings)
JWT_SECRET=your-access-token-secret
JWT_REFRESH_SECRET=your-refresh-token-secret

# Database (use connection pooling in production)
DATABASE_URL=postgresql://user:password@localhost:5432/hms

# Frontend URL (for CORS)
FRONTEND_URL=http://localhost:3000

# Node Environment
NODE_ENV=production

Security Notes

  • Never commit secrets to version control
  • Use environment variables or secret management services
  • Rotate secrets periodically
  • Use different secrets for development and production

Incident Response

If a Security Breach is Detected

  1. Immediate Actions

    • Revoke all active tokens
    • Force password reset for affected users
    • Review audit logs
  2. Investigation

    • Identify affected accounts
    • Determine attack vector
    • Assess data exposure
  3. Remediation

    • Patch security vulnerabilities
    • Implement additional security measures
    • Notify affected users (if required by law)
  4. Prevention

    • Update security practices
    • Conduct security audit
    • Implement monitoring and alerting

Compliance Considerations

GDPR

  • User data is stored securely
  • Users can request data deletion
  • Password reset tokens are time-limited
  • Email addresses are protected from enumeration

PCI DSS (if processing payments)

  • Authentication tokens are separate from payment data
  • Secure transmission (HTTPS) required
  • Access controls in place

Security Testing

Automated Testing

  • Unit tests for security utilities
  • Integration tests for authentication flows
  • E2E tests for complete user journeys

Manual Testing

  • Penetration testing recommended before production
  • Security code review
  • Dependency vulnerability scanning

Tools

  • npm audit for dependency vulnerabilities
  • OWASP ZAP for security testing
  • Snyk for continuous security monitoring

References

On this page