This PR implements a comprehensive refresh token strategy for the Callora Backend, addressing issue #232. The implementation enhances security by supporting long-lived refresh tokens with short-lived access tokens, enabling secure token rotation and immediate revocation capabilities.
- RefreshTokenService: Secure token generation, validation, and management
- RefreshTokenRepository: Database operations for token storage and retrieval
- AuthController: REST endpoints for token refresh, revocation, and management
- Auth Routes: Express routes with proper validation and middleware
- Added
refresh_tokenstable with proper indexing and constraints - Includes fields for token hashing, expiration tracking, and revocation status
- Optimized for performance with composite indexes
- Comprehensive documentation in
docs/auth-refresh-strategy.md - Security considerations and best practices
- Migration strategy and configuration guidelines
- Unit tests for RefreshTokenService covering all scenarios
- Integration tests for API endpoints with mock repository
- Security tests for edge cases and attack vectors
- SHA-256 Hashing: Refresh tokens stored as secure hashes
- Token Validation: Multiple layers of verification (signature, type, claims)
- Hash Verification: Prevents token substitution attacks
- Timing-Safe Comparison: Prevents timing attacks
- Token Expiration: Configurable expiry times (15m access, 7d refresh)
- Revocation Support: Individual and bulk token revocation
- Rate Limiting: Token usage tracking and cleanup
- Maximum Tokens: Limit of 5 active refresh tokens per user
- Comprehensive logging for security events
- Token usage tracking with timestamps
- Failed attempt monitoring
- Security violation alerts
Refresh an access token using a valid refresh token
Request: { "refreshToken": "eyJhbGciOiJIUzI1NiJ9..." }
Response: { "accessToken": "eyJhbGciOiJIUzI1NiJ9...", "tokenType": "Bearer" }Revoke a specific refresh token
Request: { "refreshToken": "eyJhbGciOiJIUzI1NiJ9..." }
Response: { "message": "Token revoked successfully" }Revoke all refresh tokens for authenticated user
Response: { "message": "All tokens revoked successfully" }Get token information for authenticated user
Response: { "activeRefreshTokens": 2, "maxAllowedTokens": 5 }JWT_SECRET=your-super-secret-key
ACCESS_TOKEN_EXPIRY=15m
REFRESH_TOKEN_EXPIRY=7d
MAX_REFRESH_TOKENS_PER_USER=5- Deploy database migration
- Update backend services
- Maintain backward compatibility
- Update clients to handle token pairs
- Implement automatic token refresh
- Add token revocation handling
- Enable refresh token flow for all clients
- Monitor for issues and performance
- Cleanup legacy authentication
- Token creation and validation
- Refresh token flow
- Security validations
- Error handling
- API endpoint functionality
- Database operations
- Security scenarios
- Edge cases
- Token substitution attacks
- Token enumeration prevention
- Revoked token rejection
- Expired token handling
- Minimal overhead with proper indexing
- Efficient token lookup and cleanup
- Optimized for concurrent access
- Efficient token hashing and validation
- Minimal memory footprint
- Proper cleanup of expired tokens
- Reduced authentication frequency
- Smaller access tokens for API calls
- Efficient token refresh mechanism
- Existing 24-hour JWT tokens continue to work
- Gradual migration path available
- No breaking changes to current API
- Optional refresh token usage
- JWT secret is properly secured and rotated
- Database access is properly restricted
- Client-side token storage follows security best practices
- Network communication uses HTTPS
- All tokens are cryptographically signed
- Token hashes prevent tampering
- Database constraints ensure data consistency
- Audit trail for token operations
- Token revocation for compromised tokens
- Rate limiting prevents abuse
- Comprehensive logging for monitoring
- Security testing for attack vectors
- Token Rotation: Implement refresh token rotation
- Device Management: Track tokens by device/browser
- Anomaly Detection: AI-powered usage analysis
- Multi-factor Refresh: Additional verification for sensitive ops
- Token Scoping: Different permissions for different tokens
src/types/auth.ts- Added refresh token interfaces (updated withfamilyId)src/services/refreshTokenService.ts- Core token service (updated with family propagation andmssupport in parseExpiry)src/repositories/refreshTokenRepository.ts- Database operations (updated with reuse detection and family revocation)src/controllers/authController.ts- API endpointssrc/routes/authRoutes.ts- Express routessrc/services/refreshTokenService.test.ts- Unit teststests/integration/refreshToken.test.ts- Integration tests (added reuse and family revocation scenarios)docs/auth-refresh-strategy.md- Documentationmigrations/add_refresh_tokens.sql- Database schemamigrations/add_refresh_token_family.sql- Added family_id tracking column and index
# Run unit tests
npm test src/services/refreshTokenService.test.ts
# Run integration tests
npm test tests/integration/refreshToken.test.ts
# Run all auth-related tests
npm test -- --testNamePattern="refresh|auth"
# Type checking
npm run typecheck
# Linting
npm run lint- Comprehensive refresh token implementation
- Security best practices followed
- Full test coverage
- Database migration provided
- Documentation complete
- Backward compatibility maintained
- Performance considerations addressed
- Security testing completed
- Error handling robust
- Logging and monitoring included
Security Note: This implementation follows OWASP JWT security guidelines and industry best practices for token-based authentication systems.