Skip to content

Add 2FA, device management, and password recovery features#90

Closed
Santiago1010 wants to merge 533 commits into
mainfrom
feature/auth-verify
Closed

Add 2FA, device management, and password recovery features#90
Santiago1010 wants to merge 533 commits into
mainfrom
feature/auth-verify

Conversation

@Santiago1010
Copy link
Copy Markdown
Owner

📋 Summary

This PR implements comprehensive authentication security features including two-factor authentication (2FA), device management, password recovery, and session management. It also adds a new CI/CD workflow for code quality and security checks, along with necessary database models and service layer updates.

🎯 Type of Change

  • Bug fix (non-breaking change)
  • New feature (adds functionality)
  • Breaking change (breaks existing functionality)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Test coverage improvement
  • Build system changes
  • CI/CD changes

🔍 What Changed

Added

  • GitHub Actions workflow for CI quality & security checks (Biome linting, dependency audit, CodeQL, testing)
  • Two-factor authentication (2FA) system with SMS/WhatsApp OTP support
  • Device management endpoints (list, update, verify devices)
  • Password recovery system (forgot password, reset password, change password)
  • Session management endpoints (list sessions, revoke sessions, refresh tokens)
  • New models: geoCities, geoDialCodes, usrOtpCodes
  • New controllers: devices.controller.js, password.controller.js, two-factor.controller.js
  • New services: password.service.js, two-factor.service.js, otp-codes.service.js, accounts.services.js, SMS service
  • New email templates for password reset, password changed, unknown device alerts
  • API documentation for all new endpoints
  • Twilio SMS integration for OTP delivery
  • Environment configuration for SMS service

Changed

  • Restructured auth routes into modular files (confirmation.routes.js, device.routes.js, etc.)
  • Updated session controller to support 2FA login flow and token refresh
  • Reorganized services directory structure (moved from services/common/ to services/)
  • Updated usrAccounts model with twoFactorEnabled field and dialCodeId foreign key
  • Updated usrTokens model with secure_device purpose
  • Updated usrUsers model association from hasMany to hasOne for accounts
  • Enhanced confirmation service with device verification
  • Updated .gitignore to exclude private scripts
  • Updated .vscode/extensions.json with new extensions
  • Updated crud.helper.js boolean detection to include 'enabled' field
  • Refactored session token middleware for better user data handling

Fixed

  • Context builder middleware to handle missing x-path header gracefully
  • Page endpoint logger middleware to avoid errors when page/endpoint is missing
  • Boolean field detection in CRUD helper

Removed

  • Old scripts/backups-secrets.script.js file
  • Unused VS Code extensions from recommendations

🧪 Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing completed
  • All tests passing

Test Instructions:

  1. Test user registration and email confirmation flow
  2. Test login with and without 2FA enabled
  3. Test password recovery (forgot password, reset with token)
  4. Test device management (list devices, update trust status)
  5. Test session management (list sessions, revoke sessions)
  6. Test token refresh functionality
  7. Verify SMS OTP delivery for 2FA
  8. Test CI workflow runs successfully on push/PR

📝 Additional Notes

  • The CI workflow includes comprehensive checks: Biome linting/formatting, dependency security audit (npm audit + audit-ci), CodeQL security analysis, and test execution with coverage reporting
  • Coverage gating is commented out but ready for future implementation
  • SMS service uses Twilio and requires proper environment variable setup (TWILIO_PHONE_NUMBER)
  • Device fingerprinting is used for session and device tracking
  • Safe mode is activated for unknown/untrusted devices, requiring verification
  • All new endpoints are documented in OpenAPI format

✅ Checklist

  • Follows project style guidelines
  • Self-reviewed my code
  • Commented complex logic
  • Updated documentation
  • No new warnings
  • Existing and new tests pass locally

Santiago1010 and others added 30 commits October 5, 2025 13:41
- Add configSecurityLevels model for security tier management
- Enhance endpoints script with full database synchronization capabilities
- Implement validation schema processing with nested field support
- Add transaction-safe endpoint and schema synchronization
- Include security level mapping and field cleanup operations
…iations

- Update all console output from Spanish to English for consistency
- Comment out unused configRoles association in security levels model
- Standardize logging terminology across endpoint synchronization script
- Include array validation message in both English and Spanish locales
- Extend validation message support for array type fields
- Expand constants helper with comprehensive documentation and new DEVICES constant
- Remove obsolete middleware files (cors, error handlers, session, validation)
- Update project structure documentation to reflect current architecture
- Add temporary RSA keys for testing purposes
…templates

- Remove auth-related files (controllers, services, routes) for platform separation
- Restore error handling middlewares with comprehensive documentation
- Consolidate CRUD templates into unified crud directory
- Add endpoints template for route generation
- Update project structure documentation to reflect current organization
- Create generateCrudEndpoints script for automatic route generation
- Add ROUTES_COMMON path constant for common route organization
- Update crud helper to use centralized string utilities
- Rename crud template to docs template for better clarity
- Register new script as executable in package.json
- Create empty route index files for all platforms (app, bot, desktop, wearable, web)
- Remove 'unknown' device type from DEVICES constant for cleaner device classification
- Standardize route structure across all platform modules
- Update endpoints template to use dynamic method names from CrudHelper
- Change ROUTES_COMMON to ROUTES_DEFAULT for better path semantics
- Improve endpoint generator to include singular name parameter
- Update project structure documentation with new route files
- Standardize file naming from .endpoints to .routes extension
- Add platform-specific routers for app, bot, desktop, wearable, and web
- Restore comprehensive logging service in common services directory
- Update gitignore to allow common log service files
- Implement user agent detection for platform routing
- Support multiple API version endpoints for different platforms
- Add CORS middleware with security configuration and error handling
- Remove unused common context directory from project structure
- Add sync-endpoints script to package.json for endpoint synchronization
- Update structure documentation to reflect middleware changes
- Move all CRUD templates to unified crud directory
- Update template paths in controllers, services, and validations generators
- Reorganize generated file locations with common/ prefix for controllers and services
- Add users service directory to project structure
- Sort package.json scripts alphabetically for better maintainability
- Fix test paths to reflect new template organization
  Auto-generated by GitHub Actions workflow
  PR: #42
  Workflow: Auto Version & Changelog
  Run ID: 18264208001
Refactor Project Structure and Enhance CRUD Generation
- Move constants.helper.js to utils/constants.util.js
- Move encrypt.helper.js to utils/encrypt.util.js
- Move numbers.helper.js to utils/numbers.util.js
- Move strings.helper.js to utils/strings.util.js
- Move utilities.helper.js to utils/utilities.util.js
- Update all import paths to reflect new module locations
- Maintain all existing functionality and exports
…tion

- Move encryption test files from helpers/encrypt to utils/encrypt
- Move numbers test files from helpers/numbers to utils/numbers
- Move strings test files from helpers/strings to utils/strings
- Move utilities test files from helpers/utilities to utils/utilities
- Update import paths in test files to reflect new module locations
- Update documentation references to point to utils modules
- Update script imports to use new utils paths
  Auto-generated by GitHub Actions workflow
  PR: #49
  Workflow: Auto Version & Changelog
  Run ID: 18361854861
…-from-utils

Refactor helper modules to utils directory
- Move utility helpers from helpers/ to utils/ directory
- Remove redundant helper files (constants, encrypt, numbers, strings, utilities)
- Add comprehensive tests for CRUD helper methods including:
  - Constructor validation with database connection check
  - Database operations with referenced table lookup
  - Field requirement validation and type checking
  - Method name generation for CRUD templates
- Reorganize test structure to align with new helper organization
…verage

- Change #executeQuery, #searchColumns, #formatColumns, #ensureDirectoryExists, and #writeFileIfNotExists to public
- Improve boolean detection in shouldBeTinyInt to include '_has_' pattern
- Add comprehensive test cases for error handling and edge cases
- Enhance test coverage for filesystem operations and database queries
- Remove .debug configuration file
- Clear module cache before mocking dependencies
- Mock fs and util modules before requiring CrudHelper
- Use jest.doMock for proper module isolation
- Restore original modules after test execution
- Replace util.promisify mock with direct fs/promises mock
- Remove complex module mocking setup
- Improve error assertion with message validation
- Clean up test structure and comments
- Make messagePath parameter optional in success response helper
- Improve documentation with JSDoc comments
- Add comprehensive test suite covering all parameter combinations
- Handle edge cases for empty messages and data-only responses
- Delete performance.helper.js and all associated test files
- Remove constructor validation from crud helper
- Update project structure documentation
  Auto-generated by GitHub Actions workflow
  PR: #53
  Workflow: Auto Version & Changelog
  Run ID: 18388599336
…t-coverage-for-helpershelperjs-top-level-helpers

Refactor project structure and enhance CRUD helper
- Create CONTRIBUTING.md with contribution guidelines and commit standards
- Create DEVELOPER_SETUP.md with detailed development environment setup
- Include Docker and local setup instructions
- Document code quality and testing procedures
  Auto-generated by GitHub Actions workflow
  PR: #54
  Workflow: Auto Version & Changelog
  Run ID: 18388925399
…-developer_setupmd

Add Project Documentation
…p test structure

- Move getDeviceInfo helper from helpers/ to utils/ directory
- Remove performance helper and related test files
- Add CONTRIBUTING.md and DEVELOPER_SETUP.md documentation files
- Reorganize test directory structure by removing performance tests
- Add OpenAPI components documentation for JWT authentication schemes
- Create basicInfo.js with API metadata and version
- Add main index.js to combine all documentation modules
- Implement server.js with web and mobile API endpoints
- Add tags.js with organized API categories for documentation
- Implement getSessions endpoint to retrieve user sessions
- Add pagination support with limit and page parameters
- Include i18n translations for success messages
- Create UML documentation files for session listing flow
- Add validation schemas for pagination parameters
- Extend fields translations for pagination parameters
- Implement revokeAllSessionExceptCurrent endpoint for bulk session management
- Add exceptJti filter to accesses service to exclude current session
- Include i18n translations for success messages in both languages
- Create UML documentation files for session revocation flow
- Update getSessions to support active filter parameter
- Add validation schema for the new endpoint
…ntries

- Create seeder for 6 base continents with multilingual names
- Create seeder for 25 regions linked to continents
- Create seeder for 247 countries with detailed attributes
- Includes multilingual names, ISO codes, surface area, and TLDs
- Uses batched inserts for performance on large country dataset
- Create TwoFactorController with disable2FA endpoint
- Implement TwoFactorService with account validation and 2FA disabling
- Add TODO for email notification on 2FA disable
- Create PlantUML diagrams for disable 2FA endpoint (activity, communication, component, dataflow, sequence, usecase)
- Add disable2FA route to two-factor routes with session validation middleware
- Add 2FA status checking, enable, disable, verify, and code sending functionalities
- Integrate OTP service and credential management for phone verification
- Implement rate limiting and security validations for OTP requests
- Update structure documentation to reflect new 2FA-related files and models
- Implement get2FAStatus, enable2FA, sendVerifyCode, verifyOTP, and disable2FA controller methods
- Connect controller endpoints to corresponding service layer functionality
- Clean up TODO comments for 2FA notification emails (moved to email service responsibility)
- Add full 2FA route endpoints with validation schemas
- Extend localization files with 2FA field and validation messages
- Update two-factor routes to include all endpoints (get status, enable, send code, verify, disable)
- Implement comprehensive validation schemas for 2FA operations
- Add security configuration constants for OTP and 2FA settings
- Remove debug flag file and update structure
- Add readAllDevices and updateDevice endpoints to OpenAPI documentation
- Include device management endpoints in auth paths index
- Re-add debug flag file for development configuration
…troller

- Move confirmDevice method from ConfirmationController to new DeviceController
- Add readAllDevices endpoint to DeviceController for device listing
- Update device routes to use DeviceController instead of ConfirmationController
- Implement updateDevice controller method for device trust, block, and active status
- Add deviceId field to localization files for validation messages
- Include updateDevice route with validation schema
- Extend device service to handle active status updates
- Update project structure documentation
- Add GitHub Actions workflow for CI quality checks on develop/main branches
- Include jobs for code quality (Biome linting/formatting), dependency security audit, CodeQL analysis, and testing
- Implement concurrency control and final status aggregation with PR failure comments
- Configure branch protection prerequisites with detailed job summaries
@Santiago1010 Santiago1010 requested a review from Sleon4 January 23, 2026 13:14
@Santiago1010 Santiago1010 self-assigned this Jan 23, 2026
@Santiago1010 Santiago1010 added enhancement New feature or request refactor Code refactorings to improve flow. labels Jan 23, 2026
@github-advanced-security
Copy link
Copy Markdown

This pull request sets up GitHub code scanning for this repository. Once the scans have completed and the checks have passed, the analysis results for this pull request branch will appear on this overview. Once you merge this pull request, the 'Security' tab will show more code scanning analysis results (for example, for the default branch). Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results. For more information about GitHub code scanning, check out the documentation.

Copy link
Copy Markdown

@github-advanced-security github-advanced-security AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeQL found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.

Change from complex array syntax with multiple commands to a single Biome command using the `--write` flag. Removes the separate format step and explicit `git add`.
- Consolidate Biome lint and format checks into single `check` command
- Strengthen dependency audit to check only high/critical vulnerabilities in production dependencies
- Add detailed success/failure PR comments with actionable next steps
- Update job summaries with clearer formatting and language specification
- Add success comment to indicate PR readiness for review
Sleon4
Sleon4 previously approved these changes Jan 23, 2026
  Auto-generated by GitHub Actions workflow
  PR: #90
  Workflow: Auto Version & Changelog
  Run ID: 21294376548
@github-actions
Copy link
Copy Markdown

🚀 Auto-versioning complete!

📦 New version: 1.19.0
📋 CHANGELOG.md and package.json updated
👤 Author: Santiago1010
✅ Approved by: Sleon4

This PR is ready for merging.

@Santiago1010 Santiago1010 requested a review from leiderp January 23, 2026 17:29
Copy link
Copy Markdown

@leiderp leiderp left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To SAntiago

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request refactor Code refactorings to improve flow.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants