The POWERBACK authentication system uses JWT (JSON Web Tokens) with HTTP-only cookies for secure token management. The system implements token rotation, secure cookie handling, and comprehensive session management.
auth/authbase.js- Base authentication class with JWT token managementauth/tokenizer.js- Concrete implementation extending AuthBaseauth/tokenStore.js- In-memory token store for refresh tokensroutes/api/users.js- User authentication endpointscontroller/users/password/change.js- Password change with token invalidation
- Access Tokens - Short-lived tokens for API authorization (configurable expiration)
- Refresh Tokens - Long-lived tokens (18 days) stored in HTTP-only cookies for session persistence
- User submits credentials via
/api/users/login - Server validates credentials directly (no Passport.js)
- JWT access token generated for immediate use
- JWT refresh token generated and stored in HTTP-only cookie
- Refresh token saved to in-memory token store
- User data and access token returned to frontend
- Frontend calls
/api/users/refreshwith HTTP-only cookie - Server validates refresh token from cookie
- Checks token exists in token store and is not expired
- Validates token version matches user's current version
- Generates new access token and refresh token
- Invalidates old refresh token (single-use security)
- Sets new refresh token in HTTP-only cookie
- Returns new access token and user data
- User changes password via
/api/users/change/:userId - Password hashed and stored in database
- Token version incremented to invalidate all existing tokens
- All existing refresh tokens removed from token store
- New JWT tokens generated with updated token version
- All other user sessions destroyed for security
- New refresh token set in HTTP-only cookie
- HTTP-only Cookies: Refresh tokens stored in HTTP-only cookies to prevent XSS attacks
- Secure Cookies: Production cookies marked as secure for HTTPS-only transmission
- SameSite Protection: Cookies set with appropriate SameSite attributes
- Token Rotation: Refresh tokens are single-use and rotated on each refresh
- Token Versioning: Tokens invalidated when password changes
- In-Memory Store: Refresh tokens stored in memory with expiration timestamps
- Automatic Cleanup: Expired tokens removed hourly to prevent memory bloat
- Session Invalidation: Password changes destroy all user sessions
- Token Validation: Comprehensive token validation including timing checks
- Token Rejection: Invalid tokens trigger logout and cookie clearing
- Graceful Degradation: Authentication failures handled with appropriate HTTP status codes
- Logging: Comprehensive logging for security monitoring and debugging
- Purpose: User authentication and session creation
- Input:
{ username, password } - Output: User data and access token
- Cookies: Sets HTTP-only refresh token cookie
- Purpose: Token refresh using HTTP-only cookie
- Input: Refresh token from HTTP-only cookie
- Output: New access token and user data
- Cookies: Updates refresh token cookie with new token
- Purpose: Session termination and cleanup
- Input: None (uses existing session)
- Output: Success confirmation
- Cookies: Clears refresh token cookie
- Purpose: Password change with token invalidation
- Input:
{ newPassword } - Output: Success message and new access token
- Security: Invalidates all existing tokens, destroys other sessions
// Token store maps refresh tokens to expiration timestamps
const store = new Map(); // token → expiresAt (timestamp in ms)- Creation: Token saved with 18-day expiration
- Validation: Token checked against store and expiration
- Rotation: Old token deleted, new token created
- Cleanup: Expired tokens removed hourly
- Automatic Cleanup: Hourly cleanup of expired tokens
- Memory Monitoring: Logging of cleanup operations
- Test Environment: Cleanup disabled in test environment
{
expires: new Date(Date.now() + SERVER.REFRESH_EXPY * 1000),
sameSite: 'strict',
path: '/api/users/refresh',
secure: true,
httpOnly: true
}{
expires: new Date(Date.now() + SERVER.REFRESH_EXPY * 1000),
sameSite: 'strict',
path: '/api/users/refresh',
secure: false,
httpOnly: true
}- Invalid Token: Returns 401 Unauthorized
- Expired Token: Clears cookies and logs out user
- Missing Token: Returns 401 Unauthorized
- Token Version Mismatch: Returns 401 Unauthorized
- Invalid Password: Returns 422 Unprocessable Entity
- User Not Found: Returns 404 Not Found
- Session Errors: Logged and handled gracefully
- Refresh tokens are single-use and rotated on each refresh
- Tokens include token version for password change invalidation
- HTTP-only cookies prevent XSS attacks
- Secure cookies prevent transmission over HTTP in production
- Password changes invalidate all existing tokens
- Other user sessions destroyed on password change
- Token timing validation prevents replay attacks
- Comprehensive logging for security monitoring
- No sensitive information leaked in error messages
- Proper HTTP status codes for different error types
- Graceful handling of authentication failures
- Security events logged for monitoring
- Frontend auth flows (e.g.
AuthContext, login/reset/activation pages) use the client logging helper (logError/logWarnfrom@Utils) so that browser consoles in production only see high-level messages; full error objects, responses, and stack traces are limited to development.
- AuthContext: Manages authentication state and token refresh
- API Calls: Automatic token refresh on 401 errors
- Session Persistence: HTTP-only cookies maintain sessions across page refreshes
- Route Protection:
tokenizer.guard()middleware protects routes - User Context: Authenticated user available in
req.jwt.payload.sub - Token Validation: Automatic token validation on protected routes
- JWT-only System: No session-based authentication, pure JWT tokens
- Authentication attempts and failures
- Token validation and rejection events
- Password change events and session destruction
- Security events and error conditions
- Token store size and cleanup operations
- Authentication request timing
- Memory usage and cleanup effectiveness
- Error rates and failure patterns
- Token Not Found: Check token store and expiration
- Cookie Not Set: Verify cookie configuration and domain settings
- Session Expired: Check token version and password change history
- Authentication Failed: Verify token signature and audience
- Token store state and size
- Cookie configuration and values
- Token validation results
- Error messages and stack traces
- JWT-only Authentication: Pure JWT token-based authentication system
- HTTP-only Cookies: Secure token storage with automatic refresh
- Session Management: In-memory token store with automatic cleanup
- Account Security: Automatic logout when accounts are locked due to failed password resets
- API Documentation - API endpoints and authentication
- Development Guide - Development setup
- FEC Compliance Guide - Compliance system
- User Management - User model and management
- Client Utils - Client logging (e.g.
logError/logWarnfrom@Utils)
- Code:
auth/,routes/api/users.js,controller/users/password/change.js - Related:
docs/API.md,specs/backend-compliance.md,specs/jwt-authentication-system.md - Documentation: See
README.mdfor complete documentation index