ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add two-factor authentication (2FA) support
Juan Denis3f5746cfe4fa
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 62144120..bda381ff 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -129,6 +129,10 @@ def create_app(config_name=None):from app.api.env_vars import env_vars_bpapp.register_blueprint(env_vars_bp, url_prefix='/api/v1/apps')+ # Register blueprints - Two-Factor Authentication+ from app.api.two_factor import two_factor_bp+ app.register_blueprint(two_factor_bp, url_prefix='/api/v1/auth/2fa')+# Create database tableswith app.app_context():db.create_all()diff --git a/backend/app/api/auth.py b/backend/app/api/auth.pyindex 4503be0a..14c338ae 100644--- a/backend/app/api/auth.py+++ b/backend/app/api/auth.py@@ -94,7 +94,23 @@ def login():if not user.is_active:return jsonify({'error': 'Account is deactivated'}), 403- # Reset failed login count on successful login+ # Check if 2FA is enabled+ if user.totp_enabled:+ # Create a short-lived temporary token for 2FA verification+ # This token can only be used to complete 2FA, not to access resources+ temp_token = create_access_token(+ identity=user.id,+ additional_claims={'2fa_pending': True},+ expires_delta=False # Use default (short) expiry+ )++ return jsonify({+ 'requires_2fa': True,+ 'temp_token': temp_token,+ 'message': 'Two-factor authentication required'+ }), 200++ # No 2FA - proceed with normal loginuser.reset_failed_login()db.session.commit()diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.pynew file mode 100644index 00000000..2cd5f6a0--- /dev/null+++ b/backend/app/api/two_factor.py@@ -0,0 +1,241 @@+"""+Two-Factor Authentication API++Provides endpoints for enabling, disabling, and managing 2FA.+"""++from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity+from app.models import User+from app.services.totp_service import TOTPService, TwoFactorSetup++two_factor_bp = Blueprint('two_factor', __name__)+++@two_factor_bp.route('/status', methods=['GET'])+@jwt_required()+def get_2fa_status():+ """Get the current 2FA status for the user."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)++ if not user:+ return jsonify({'error': 'User not found'}), 404++ setup = TwoFactorSetup(user)++ return jsonify({+ 'enabled': user.totp_enabled,+ 'confirmed_at': user.totp_confirmed_at.isoformat() if user.totp_confirmed_at else None,+ 'backup_codes_remaining': setup.get_remaining_backup_codes_count() if user.totp_enabled else 0+ }), 200+++@two_factor_bp.route('/setup', methods=['POST'])+@jwt_required()+def initiate_2fa_setup():+ """+ Initiate 2FA setup. Generates a new secret and returns QR code.+ User must verify with a code to complete setup.+ """+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)++ if not user:+ return jsonify({'error': 'User not found'}), 404++ if user.totp_enabled:+ return jsonify({'error': '2FA is already enabled'}), 400++ setup = TwoFactorSetup(user)+ setup_data = setup.initiate_setup()++ return jsonify({+ 'message': '2FA setup initiated. Scan the QR code and enter a verification code.',+ 'secret': setup_data['secret'],+ 'qr_code': setup_data['qr_code'],+ 'uri': setup_data['uri'],+ 'issuer': setup_data['issuer']+ }), 200+++@two_factor_bp.route('/setup/confirm', methods=['POST'])+@jwt_required()+def confirm_2fa_setup():+ """+ Confirm 2FA setup by verifying a code.+ Returns backup codes on success (one-time display).+ """+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)++ if not user:+ return jsonify({'error': 'User not found'}), 404++ if user.totp_enabled:+ return jsonify({'error': '2FA is already enabled'}), 400++ data = request.get_json()+ if not data or 'code' not in data:+ return jsonify({'error': 'Verification code is required'}), 400++ setup = TwoFactorSetup(user)+ success, result = setup.confirm_setup(data['code'])++ if not success:+ return jsonify({'error': result}), 400++ return jsonify({+ 'message': '2FA has been enabled successfully',+ 'backup_codes': result, # One-time display+ 'backup_codes_warning': 'Save these backup codes in a secure location. They will not be shown again.'+ }), 200+++@two_factor_bp.route('/disable', methods=['POST'])+@jwt_required()+def disable_2fa():+ """+ Disable 2FA. Requires a valid TOTP code or backup code.+ """+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)++ if not user:+ return jsonify({'error': 'User not found'}), 404++ if not user.totp_enabled:+ return jsonify({'error': '2FA is not enabled'}), 400++ data = request.get_json()+ if not data or 'code' not in data:+ return jsonify({'error': 'Verification code is required'}), 400++ setup = TwoFactorSetup(user)+ success, error = setup.disable(data['code'])++ if not success:+ return jsonify({'error': error}), 400++ return jsonify({+ 'message': '2FA has been disabled successfully'+ }), 200+++@two_factor_bp.route('/backup-codes/regenerate', methods=['POST'])+@jwt_required()+def regenerate_backup_codes():+ """+ Regenerate backup codes. Requires a valid TOTP code.+ Old backup codes become invalid.+ """+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)++ if not user:+ return jsonify({'error': 'User not found'}), 404++ if not user.totp_enabled:+ return jsonify({'error': '2FA is not enabled'}), 400++ data = request.get_json()+ if not data or 'code' not in data:+ return jsonify({'error': 'TOTP code is required'}), 400++ setup = TwoFactorSetup(user)+ success, result = setup.regenerate_backup_codes(data['code'])++ if not success:+ return jsonify({'error': result}), 400++ return jsonify({+ 'message': 'Backup codes have been regenerated',+ 'backup_codes': result,+ 'backup_codes_warning': 'Save these backup codes in a secure location. They will not be shown again.'+ }), 200+++@two_factor_bp.route('/verify', methods=['POST'])+def verify_2fa_code():+ """+ Verify a 2FA code during login.+ This endpoint is used when login returns requires_2fa=true.+ Expects a temporary token from the login response.+ """+ from flask_jwt_extended import create_access_token, create_refresh_token, decode_token+ from app import db++ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ temp_token = data.get('temp_token')+ code = data.get('code')++ if not temp_token or not code:+ return jsonify({'error': 'Temporary token and code are required'}), 400++ # Decode the temporary token to get user ID+ try:+ token_data = decode_token(temp_token)+ user_id = token_data['sub']++ # Check if this is a 2FA pending token+ if not token_data.get('2fa_pending'):+ return jsonify({'error': 'Invalid token type'}), 400++ except Exception as e:+ return jsonify({'error': 'Invalid or expired token'}), 401++ user = User.query.get(user_id)+ if not user:+ return jsonify({'error': 'User not found'}), 404++ if not user.totp_enabled:+ return jsonify({'error': '2FA is not enabled for this account'}), 400++ # Try TOTP code first+ if TOTPService.verify_code(user.totp_secret, code):+ # Success - issue real tokens+ user.reset_failed_login()+ db.session.commit()++ access_token = create_access_token(identity=user.id)+ refresh_token = create_refresh_token(identity=user.id)++ return jsonify({+ 'user': user.to_dict(),+ 'access_token': access_token,+ 'refresh_token': refresh_token+ }), 200++ # Try backup code+ backup_codes = user.get_backup_codes()+ matched_hash = TOTPService.verify_backup_code(code, backup_codes)++ if matched_hash:+ # Valid backup code - remove it (one-time use)+ user.use_backup_code(matched_hash)+ user.reset_failed_login()+ db.session.commit()++ access_token = create_access_token(identity=user.id)+ refresh_token = create_refresh_token(identity=user.id)++ # Warn about remaining backup codes+ remaining = len(user.get_backup_codes())++ return jsonify({+ 'user': user.to_dict(),+ 'access_token': access_token,+ 'refresh_token': refresh_token,+ 'backup_code_used': True,+ 'backup_codes_remaining': remaining,+ 'warning': f'Backup code used. {remaining} codes remaining.' if remaining <= 3 else None+ }), 200++ # Invalid code+ user.record_failed_login()+ db.session.commit()++ return jsonify({'error': 'Invalid verification code'}), 401diff --git a/backend/app/models/user.py b/backend/app/models/user.pyindex 75d5fd52..6fd096df 100644--- a/backend/app/models/user.py+++ b/backend/app/models/user.py@@ -1,6 +1,7 @@from datetime import datetime, timedeltafrom werkzeug.security import generate_password_hash, check_password_hashfrom app import db+import jsonclass User(db.Model):@@ -19,6 +20,12 @@ class User(db.Model):failed_login_count = db.Column(db.Integer, default=0)locked_until = db.Column(db.DateTime, nullable=True)+ # Two-Factor Authentication fields+ totp_secret = db.Column(db.String(32), nullable=True) # Base32 encoded secret+ totp_enabled = db.Column(db.Boolean, default=False)+ backup_codes = db.Column(db.Text, nullable=True) # JSON array of hashed backup codes+ totp_confirmed_at = db.Column(db.DateTime, nullable=True) # When 2FA was enabled+# Relationshipsapplications = db.relationship('Application', backref='owner', lazy='dynamic')@@ -63,9 +70,32 @@ class User(db.Model):'username': self.username,'role': self.role,'is_active': self.is_active,+ 'totp_enabled': self.totp_enabled,'created_at': self.created_at.isoformat(),'updated_at': self.updated_at.isoformat()}+ def get_backup_codes(self):+ """Get the list of backup code hashes."""+ if not self.backup_codes:+ return []+ try:+ return json.loads(self.backup_codes)+ except (json.JSONDecodeError, TypeError):+ return []++ def set_backup_codes(self, codes_hashes):+ """Store backup code hashes."""+ self.backup_codes = json.dumps(codes_hashes)++ def use_backup_code(self, code_hash):+ """Remove a used backup code."""+ codes = self.get_backup_codes()+ if code_hash in codes:+ codes.remove(code_hash)+ self.set_backup_codes(codes)+ return True+ return False+def __repr__(self):return f'<User {self.username}>'diff --git a/backend/app/services/totp_service.py b/backend/app/services/totp_service.pynew file mode 100644index 00000000..28f9afbf--- /dev/null+++ b/backend/app/services/totp_service.py@@ -0,0 +1,317 @@+"""+Two-Factor Authentication (2FA) Service++Handles TOTP generation, verification, backup codes, and QR code provisioning.+Uses pyotp for TOTP implementation (RFC 6238 compliant).+"""++import pyotp+import secrets+import hashlib+import base64+from io import BytesIO+from datetime import datetime++# QR code generation+try:+ import qrcode+ HAS_QRCODE = True+except ImportError:+ HAS_QRCODE = False+++class TOTPService:+ """Service for managing TOTP-based two-factor authentication."""++ # App name for authenticator apps+ ISSUER_NAME = "ServerKit"++ # TOTP settings+ DIGITS = 6+ INTERVAL = 30 # seconds++ # Backup codes settings+ BACKUP_CODE_LENGTH = 8+ BACKUP_CODE_COUNT = 10++ @staticmethod+ def generate_secret():+ """Generate a new TOTP secret key."""+ return pyotp.random_base32()++ @staticmethod+ def get_totp(secret):+ """Get a TOTP instance for the given secret."""+ return pyotp.TOTP(secret, digits=TOTPService.DIGITS, interval=TOTPService.INTERVAL)++ @staticmethod+ def verify_code(secret, code, valid_window=1):+ """+ Verify a TOTP code.++ Args:+ secret: The user's TOTP secret+ code: The 6-digit code to verify+ valid_window: Number of time periods to check before/after current++ Returns:+ bool: True if code is valid+ """+ if not secret or not code:+ return False++ # Clean the code (remove spaces, dashes)+ code = code.replace(' ', '').replace('-', '')++ # Must be digits only+ if not code.isdigit():+ return False++ totp = TOTPService.get_totp(secret)+ return totp.verify(code, valid_window=valid_window)++ @staticmethod+ def get_current_code(secret):+ """Get the current TOTP code (for testing)."""+ totp = TOTPService.get_totp(secret)+ return totp.now()++ @staticmethod+ def get_provisioning_uri(secret, email):+ """+ Get the provisioning URI for authenticator apps.++ This URI is used to generate QR codes that can be scanned+ by Google Authenticator, Authy, 1Password, etc.+ """+ totp = TOTPService.get_totp(secret)+ return totp.provisioning_uri(+ name=email,+ issuer_name=TOTPService.ISSUER_NAME+ )++ @staticmethod+ def generate_qr_code_base64(secret, email):+ """+ Generate a QR code as base64 encoded PNG.++ Returns:+ str: Base64 encoded PNG image, or None if qrcode not available+ """+ if not HAS_QRCODE:+ return None++ uri = TOTPService.get_provisioning_uri(secret, email)++ # Generate QR code+ qr = qrcode.QRCode(+ version=1,+ error_correction=qrcode.constants.ERROR_CORRECT_L,+ box_size=10,+ border=4,+ )+ qr.add_data(uri)+ qr.make(fit=True)++ # Create image+ img = qr.make_image(fill_color="black", back_color="white")++ # Convert to base64+ buffer = BytesIO()+ img.save(buffer, format='PNG')+ buffer.seek(0)+ img_base64 = base64.b64encode(buffer.getvalue()).decode()++ return f"data:image/png;base64,{img_base64}"++ @staticmethod+ def generate_backup_codes():+ """+ Generate a set of backup codes.++ Returns:+ tuple: (plain_codes, hashed_codes)+ - plain_codes: List of codes to show to user (one-time only)+ - hashed_codes: List of SHA256 hashes to store in database+ """+ plain_codes = []+ hashed_codes = []++ for _ in range(TOTPService.BACKUP_CODE_COUNT):+ # Generate random code (e.g., "a1b2c3d4")+ code = secrets.token_hex(TOTPService.BACKUP_CODE_LENGTH // 2)+ plain_codes.append(code)++ # Hash for storage+ code_hash = hashlib.sha256(code.encode()).hexdigest()+ hashed_codes.append(code_hash)++ return plain_codes, hashed_codes++ @staticmethod+ def verify_backup_code(code, hashed_codes):+ """+ Verify a backup code against stored hashes.++ Args:+ code: The backup code entered by user+ hashed_codes: List of valid backup code hashes++ Returns:+ str or None: The matching hash if valid, None otherwise+ """+ if not code or not hashed_codes:+ return None++ # Clean the code+ code = code.lower().replace(' ', '').replace('-', '')++ # Hash the input+ code_hash = hashlib.sha256(code.encode()).hexdigest()++ if code_hash in hashed_codes:+ return code_hash++ return None++ @staticmethod+ def format_backup_codes(codes):+ """Format backup codes for display (add dashes for readability)."""+ formatted = []+ for code in codes:+ # Format as "a1b2-c3d4" for 8-char codes+ mid = len(code) // 2+ formatted.append(f"{code[:mid]}-{code[mid:]}")+ return formatted+++class TwoFactorSetup:+ """Helper class for managing 2FA setup flow."""++ def __init__(self, user):+ self.user = user++ def initiate_setup(self):+ """+ Start 2FA setup by generating a new secret.++ Returns:+ dict: Setup data including secret and QR code+ """+ from app import db++ # Generate new secret (don't enable yet)+ secret = TOTPService.generate_secret()+ self.user.totp_secret = secret++ # Don't enable until verified+ db.session.commit()++ # Generate QR code+ qr_code = TOTPService.generate_qr_code_base64(secret, self.user.email)+ uri = TOTPService.get_provisioning_uri(secret, self.user.email)++ return {+ 'secret': secret, # For manual entry+ 'qr_code': qr_code, # Base64 PNG+ 'uri': uri, # For advanced users+ 'issuer': TOTPService.ISSUER_NAME+ }++ def confirm_setup(self, code):+ """+ Confirm 2FA setup by verifying the first code.++ Returns:+ tuple: (success, backup_codes or error_message)+ """+ from app import db++ if not self.user.totp_secret:+ return False, "2FA setup not initiated"++ # Verify the code+ if not TOTPService.verify_code(self.user.totp_secret, code):+ return False, "Invalid verification code"++ # Generate backup codes+ plain_codes, hashed_codes = TOTPService.generate_backup_codes()++ # Enable 2FA+ self.user.totp_enabled = True+ self.user.totp_confirmed_at = datetime.utcnow()+ self.user.set_backup_codes(hashed_codes)++ db.session.commit()++ # Return formatted backup codes (one-time display)+ formatted_codes = TOTPService.format_backup_codes(plain_codes)++ return True, formatted_codes++ def disable(self, code_or_backup):+ """+ Disable 2FA for the user.++ Args:+ code_or_backup: Either a TOTP code or backup code++ Returns:+ tuple: (success, error_message or None)+ """+ from app import db++ if not self.user.totp_enabled:+ return False, "2FA is not enabled"++ # Try TOTP code first+ if TOTPService.verify_code(self.user.totp_secret, code_or_backup):+ self._clear_totp()+ db.session.commit()+ return True, None++ # Try backup code+ backup_codes = self.user.get_backup_codes()+ matched_hash = TOTPService.verify_backup_code(code_or_backup, backup_codes)+ if matched_hash:+ self._clear_totp()+ db.session.commit()+ return True, None++ return False, "Invalid verification code"++ def _clear_totp(self):+ """Clear all 2FA data from user."""+ self.user.totp_secret = None+ self.user.totp_enabled = False+ self.user.backup_codes = None+ self.user.totp_confirmed_at = None++ def regenerate_backup_codes(self, totp_code):+ """+ Regenerate backup codes (requires valid TOTP code).++ Returns:+ tuple: (success, new_codes or error_message)+ """+ from app import db++ if not self.user.totp_enabled:+ return False, "2FA is not enabled"++ if not TOTPService.verify_code(self.user.totp_secret, totp_code):+ return False, "Invalid verification code"++ # Generate new backup codes+ plain_codes, hashed_codes = TOTPService.generate_backup_codes()+ self.user.set_backup_codes(hashed_codes)++ db.session.commit()++ formatted_codes = TOTPService.format_backup_codes(plain_codes)+ return True, formatted_codes++ def get_remaining_backup_codes_count(self):+ """Get the number of remaining backup codes."""+ codes = self.user.get_backup_codes()+ return len(codes)diff --git a/backend/requirements.txt b/backend/requirements.txtindex 7fdda93b..9303f359 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -43,4 +43,8 @@ passlibbcrypt# Encryption for env vars-cryptography==42.0.0\ No newline at end of file+cryptography==42.0.0++# Two-Factor Authentication+pyotp==2.9.0+qrcode[pil]==7.4.2\ No newline at end of filediff --git a/frontend/src/pages/Login.jsx b/frontend/src/pages/Login.jsxindex 116a7a18..bebae3c9 100644--- a/frontend/src/pages/Login.jsx+++ b/frontend/src/pages/Login.jsx@@ -1,22 +1,45 @@-import React, { useState } from 'react';+import React, { useState, useRef, useEffect } from 'react';import { useNavigate, Link } from 'react-router-dom';import { useAuth } from '../contexts/AuthContext';+import api from '../services/api';const Login = () => {const [email, setEmail] = useState('');const [password, setPassword] = useState('');const [error, setError] = useState('');const [loading, setLoading] = useState(false);- const { login } = useAuth();++ // 2FA state+ const [requires2FA, setRequires2FA] = useState(false);+ const [tempToken, setTempToken] = useState('');+ const [totpCode, setTotpCode] = useState(['', '', '', '', '', '']);+ const [useBackupCode, setUseBackupCode] = useState(false);+ const [backupCode, setBackupCode] = useState('');++ const { login, setUser, setTokens } = useAuth();const navigate = useNavigate();+ // Refs for TOTP input fields+ const inputRefs = useRef([]);+async function handleSubmit(e) {e.preventDefault();setError('');setLoading(true);try {- await login(email, password);+ const response = await api.login(email, password);++ // Check if 2FA is required+ if (response.requires_2fa) {+ setRequires2FA(true);+ setTempToken(response.temp_token);+ setLoading(false);+ return;+ }++ // No 2FA - complete login+ setUser(response.user);navigate('/');} catch (err) {setError(err.message || 'Failed to login');@@ -25,6 +48,175 @@ const Login = () => {}}+ async function handle2FASubmit(e) {+ e.preventDefault();+ setError('');+ setLoading(true);++ const code = useBackupCode ? backupCode : totpCode.join('');++ try {+ const response = await api.verify2FA(tempToken, code);++ // Store tokens+ api.setTokens(response.access_token, response.refresh_token);+ setUser(response.user);++ // Show warning if backup code used and running low+ if (response.warning) {+ // Could show a toast here+ console.warn(response.warning);+ }++ navigate('/');+ } catch (err) {+ setError(err.message || 'Invalid verification code');+ // Clear the code inputs on error+ if (!useBackupCode) {+ setTotpCode(['', '', '', '', '', '']);+ inputRefs.current[0]?.focus();+ }+ } finally {+ setLoading(false);+ }+ }++ function handleTotpChange(index, value) {+ // Only allow digits+ if (value && !/^\d$/.test(value)) return;++ const newCode = [...totpCode];+ newCode[index] = value;+ setTotpCode(newCode);++ // Auto-focus next input+ if (value && index < 5) {+ inputRefs.current[index + 1]?.focus();+ }+ }++ function handleTotpKeyDown(index, e) {+ // Handle backspace+ if (e.key === 'Backspace' && !totpCode[index] && index > 0) {+ inputRefs.current[index - 1]?.focus();+ }+ }++ function handleTotpPaste(e) {+ e.preventDefault();+ const pastedData = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 6);++ if (pastedData) {+ const newCode = [...totpCode];+ for (let i = 0; i < pastedData.length && i < 6; i++) {+ newCode[i] = pastedData[i];+ }+ setTotpCode(newCode);++ // Focus the next empty input or the last one+ const nextEmptyIndex = newCode.findIndex(c => !c);+ if (nextEmptyIndex !== -1) {+ inputRefs.current[nextEmptyIndex]?.focus();+ } else {+ inputRefs.current[5]?.focus();+ }+ }+ }++ function handleBack() {+ setRequires2FA(false);+ setTempToken('');+ setTotpCode(['', '', '', '', '', '']);+ setBackupCode('');+ setUseBackupCode(false);+ setError('');+ }++ // Auto-submit when all 6 digits are entered+ useEffect(() => {+ if (!useBackupCode && totpCode.every(c => c) && !loading) {+ handle2FASubmit({ preventDefault: () => {} });+ }+ }, [totpCode, useBackupCode]);++ // Render 2FA verification form+ if (requires2FA) {+ return (+ <div className="auth-container">+ <div className="auth-card">+ <div className="auth-header">+ <div className="brand-logo">+ <svg viewBox="0 0 24 24" width="32" height="32" stroke="currentColor" fill="none" strokeWidth="2">+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>+ <path d="M7 11V7a5 5 0 0 1 10 0v4"/>+ </svg>+ </div>+ <h1>Two-Factor Authentication</h1>+ <p>{useBackupCode ? 'Enter a backup code' : 'Enter the 6-digit code from your authenticator app'}</p>+ </div>++ {error && <div className="error-message">{error}</div>}++ <form onSubmit={handle2FASubmit}>+ {!useBackupCode ? (+ <div className="totp-inputs">+ {totpCode.map((digit, index) => (+ <input+ key={index}+ ref={el => inputRefs.current[index] = el}+ type="text"+ inputMode="numeric"+ maxLength={1}+ value={digit}+ onChange={(e) => handleTotpChange(index, e.target.value)}+ onKeyDown={(e) => handleTotpKeyDown(index, e)}+ onPaste={index === 0 ? handleTotpPaste : undefined}+ autoFocus={index === 0}+ className="totp-input"+ />+ ))}+ </div>+ ) : (+ <div className="form-group">+ <label htmlFor="backupCode">Backup Code</label>+ <input+ type="text"+ id="backupCode"+ value={backupCode}+ onChange={(e) => setBackupCode(e.target.value.toLowerCase())}+ placeholder="xxxx-xxxx"+ autoFocus+ />+ </div>+ )}++ <button type="submit" className="btn btn-primary btn-full" disabled={loading}>+ {loading ? 'Verifying...' : 'Verify'}+ </button>+ </form>++ <div className="auth-footer-links">+ <button+ type="button"+ className="link-button"+ onClick={() => setUseBackupCode(!useBackupCode)}+ >+ {useBackupCode ? 'Use authenticator app instead' : 'Use a backup code instead'}+ </button>+ <button+ type="button"+ className="link-button"+ onClick={handleBack}+ >+ Back to login+ </button>+ </div>+ </div>+ </div>+ );+ }++ // Render normal login formreturn (<div className="auth-container"><div className="auth-card">diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxindex 8f59dc0f..6510c687 100644--- a/frontend/src/pages/Settings.jsx+++ b/frontend/src/pages/Settings.jsx@@ -194,7 +194,7 @@ const ProfileSettings = () => {};const SecuritySettings = () => {- const { updateUser } = useAuth();+ const { updateUser, user } = useAuth();const [formData, setFormData] = useState({currentPassword: '',newPassword: '',@@ -203,6 +203,32 @@ const SecuritySettings = () => {const [loading, setLoading] = useState(false);const [message, setMessage] = useState(null);+ // 2FA state+ const [twoFAStatus, setTwoFAStatus] = useState(null);+ const [twoFALoading, setTwoFALoading] = useState(true);+ const [showSetupModal, setShowSetupModal] = useState(false);+ const [showDisableModal, setShowDisableModal] = useState(false);+ const [showBackupCodesModal, setShowBackupCodesModal] = useState(false);+ const [setupData, setSetupData] = useState(null);+ const [verificationCode, setVerificationCode] = useState('');+ const [backupCodes, setBackupCodes] = useState([]);+ const [twoFAError, setTwoFAError] = useState('');++ useEffect(() => {+ load2FAStatus();+ }, []);++ async function load2FAStatus() {+ try {+ const status = await api.get2FAStatus();+ setTwoFAStatus(status);+ } catch (err) {+ console.error('Failed to load 2FA status:', err);+ } finally {+ setTwoFALoading(false);+ }+ }+async function handleSubmit(e) {e.preventDefault();setMessage(null);@@ -230,6 +256,109 @@ const SecuritySettings = () => {}}+ async function handleInitiate2FA() {+ setTwoFAError('');+ setTwoFALoading(true);+ try {+ const data = await api.initiate2FASetup();+ setSetupData(data);+ setShowSetupModal(true);+ } catch (err) {+ setTwoFAError(err.message);+ } finally {+ setTwoFALoading(false);+ }+ }++ async function handleConfirm2FA() {+ if (!verificationCode || verificationCode.length !== 6) {+ setTwoFAError('Please enter a 6-digit code');+ return;+ }++ setTwoFALoading(true);+ setTwoFAError('');+ try {+ const result = await api.confirm2FASetup(verificationCode);+ setBackupCodes(result.backup_codes);+ setShowSetupModal(false);+ setShowBackupCodesModal(true);+ setVerificationCode('');+ load2FAStatus();+ } catch (err) {+ setTwoFAError(err.message || 'Invalid verification code');+ } finally {+ setTwoFALoading(false);+ }+ }++ async function handleDisable2FA() {+ if (!verificationCode) {+ setTwoFAError('Please enter a verification code');+ return;+ }++ setTwoFALoading(true);+ setTwoFAError('');+ try {+ await api.disable2FA(verificationCode);+ setShowDisableModal(false);+ setVerificationCode('');+ load2FAStatus();+ } catch (err) {+ setTwoFAError(err.message || 'Invalid verification code');+ } finally {+ setTwoFALoading(false);+ }+ }++ async function handleRegenerateBackupCodes() {+ if (!verificationCode || verificationCode.length !== 6) {+ setTwoFAError('Please enter a 6-digit code');+ return;+ }++ setTwoFALoading(true);+ setTwoFAError('');+ try {+ const result = await api.regenerateBackupCodes(verificationCode);+ setBackupCodes(result.backup_codes);+ setShowBackupCodesModal(true);+ setVerificationCode('');+ load2FAStatus();+ } catch (err) {+ setTwoFAError(err.message || 'Invalid verification code');+ } finally {+ setTwoFALoading(false);+ }+ }++ function downloadBackupCodes() {+ const content = `ServerKit Backup Codes+Generated: ${new Date().toLocaleString()}++These codes can be used to access your account if you lose your authenticator device.+Each code can only be used once.++${backupCodes.join('\n')}++Keep these codes in a safe place.`;++ const blob = new Blob([content], { type: 'text/plain' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = 'serverkit-backup-codes.txt';+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+ }++ function copyBackupCodes() {+ navigator.clipboard.writeText(backupCodes.join('\n'));+ }+return (<div className="settings-section"><div className="section-header">@@ -243,6 +372,77 @@ const SecuritySettings = () => {</div>)}+ {/* Two-Factor Authentication Section */}+ <div className="settings-card two-fa-card">+ <div className="two-fa-header">+ <div className="two-fa-icon">+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>+ <path d="M7 11V7a5 5 0 0 1 10 0v4"/>+ </svg>+ </div>+ <div>+ <h3>Two-Factor Authentication (2FA)</h3>+ <p>Add an extra layer of security to your account</p>+ </div>+ </div>++ {twoFALoading && !twoFAStatus ? (+ <div className="loading-sm">Loading...</div>+ ) : twoFAStatus?.enabled ? (+ <div className="two-fa-enabled">+ <div className="two-fa-status">+ <span className="badge badge-success">Enabled</span>+ <span className="two-fa-info">+ Enabled on {new Date(twoFAStatus.confirmed_at).toLocaleDateString()}+ </span>+ </div>+ <div className="two-fa-backup-info">+ <span>Backup codes remaining: <strong>{twoFAStatus.backup_codes_remaining}</strong></span>+ {twoFAStatus.backup_codes_remaining <= 3 && (+ <span className="warning-text">Consider regenerating your backup codes</span>+ )}+ </div>+ <div className="two-fa-actions">+ <button+ className="btn btn-secondary"+ onClick={() => {+ setVerificationCode('');+ setTwoFAError('');+ setShowBackupCodesModal(true);+ }}+ >+ Regenerate Backup Codes+ </button>+ <button+ className="btn btn-danger"+ onClick={() => {+ setVerificationCode('');+ setTwoFAError('');+ setShowDisableModal(true);+ }}+ >+ Disable 2FA+ </button>+ </div>+ </div>+ ) : (+ <div className="two-fa-disabled">+ <p className="two-fa-description">+ Two-factor authentication adds an additional layer of security to your account+ by requiring a code from your authenticator app in addition to your password.+ </p>+ <button+ className="btn btn-primary"+ onClick={handleInitiate2FA}+ disabled={twoFALoading}+ >+ Enable Two-Factor Authentication+ </button>+ </div>+ )}+ </div>+<form onSubmit={handleSubmit} className="settings-form"><h3>Change Password</h3>@@ -304,6 +504,197 @@ const SecuritySettings = () => {<span className="badge badge-success">Current</span></div></div>++ {/* 2FA Setup Modal */}+ {showSetupModal && setupData && (+ <div className="modal-overlay" onClick={() => setShowSetupModal(false)}>+ <div className="modal modal-md" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Set Up Two-Factor Authentication</h2>+ <button className="modal-close" onClick={() => setShowSetupModal(false)}>×</button>+ </div>+ <div className="modal-body">+ <div className="setup-steps">+ <div className="setup-step">+ <span className="step-number">1</span>+ <div className="step-content">+ <h4>Scan the QR Code</h4>+ <p>Use your authenticator app (Google Authenticator, Authy, 1Password, etc.) to scan this QR code.</p>+ {setupData.qr_code ? (+ <div className="qr-code-container">+ <img src={setupData.qr_code} alt="2FA QR Code" className="qr-code" />+ </div>+ ) : (+ <div className="qr-fallback">+ <p>QR code unavailable. Enter this secret manually:</p>+ <code className="secret-key">{setupData.secret}</code>+ </div>+ )}+ <details className="manual-entry">+ <summary>Can't scan? Enter manually</summary>+ <p>Account: {user?.email}</p>+ <p>Secret: <code>{setupData.secret}</code></p>+ </details>+ </div>+ </div>++ <div className="setup-step">+ <span className="step-number">2</span>+ <div className="step-content">+ <h4>Enter Verification Code</h4>+ <p>Enter the 6-digit code from your authenticator app to verify setup.</p>+ <input+ type="text"+ value={verificationCode}+ onChange={(e) => setVerificationCode(e.target.value.replace(/\D/g, '').slice(0, 6))}+ placeholder="000000"+ className="verification-input"+ autoFocus+ />+ {twoFAError && <p className="error-text">{twoFAError}</p>}+ </div>+ </div>+ </div>+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => setShowSetupModal(false)}>+ Cancel+ </button>+ <button+ className="btn btn-primary"+ onClick={handleConfirm2FA}+ disabled={twoFALoading || verificationCode.length !== 6}+ >+ {twoFALoading ? 'Verifying...' : 'Enable 2FA'}+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Disable 2FA Modal */}+ {showDisableModal && (+ <div className="modal-overlay" onClick={() => setShowDisableModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Disable Two-Factor Authentication</h2>+ <button className="modal-close" onClick={() => setShowDisableModal(false)}>×</button>+ </div>+ <div className="modal-body">+ <div className="warning-box">+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>+ <line x1="12" y1="9" x2="12" y2="13"/>+ <line x1="12" y1="17" x2="12.01" y2="17"/>+ </svg>+ <p>Disabling 2FA will make your account less secure. You will only need your password to log in.</p>+ </div>+ <div className="form-group">+ <label>Enter a verification code or backup code to disable 2FA:</label>+ <input+ type="text"+ value={verificationCode}+ onChange={(e) => setVerificationCode(e.target.value)}+ placeholder="Code from authenticator or backup code"+ autoFocus+ />+ {twoFAError && <p className="error-text">{twoFAError}</p>}+ </div>+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => setShowDisableModal(false)}>+ Cancel+ </button>+ <button+ className="btn btn-danger"+ onClick={handleDisable2FA}+ disabled={twoFALoading || !verificationCode}+ >+ {twoFALoading ? 'Disabling...' : 'Disable 2FA'}+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Backup Codes Modal */}+ {showBackupCodesModal && (+ <div className="modal-overlay" onClick={() => setShowBackupCodesModal(false)}>+ <div className="modal modal-md" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>{backupCodes.length > 0 ? 'Your Backup Codes' : 'Regenerate Backup Codes'}</h2>+ <button className="modal-close" onClick={() => setShowBackupCodesModal(false)}>×</button>+ </div>+ <div className="modal-body">+ {backupCodes.length > 0 ? (+ <>+ <div className="warning-box">+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ <line x1="12" y1="8" x2="12" y2="12"/>+ <line x1="12" y1="16" x2="12.01" y2="16"/>+ </svg>+ <p>Save these backup codes in a secure location. They will not be shown again. Each code can only be used once.</p>+ </div>+ <div className="backup-codes-grid">+ {backupCodes.map((code, index) => (+ <code key={index} className="backup-code">{code}</code>+ ))}+ </div>+ <div className="backup-codes-actions">+ <button className="btn btn-secondary" onClick={downloadBackupCodes}>+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/>+ </svg>+ Download+ </button>+ <button className="btn btn-secondary" onClick={copyBackupCodes}>+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>+ </svg>+ Copy+ </button>+ </div>+ </>+ ) : (+ <>+ <p>Enter a code from your authenticator app to generate new backup codes. This will invalidate all existing backup codes.</p>+ <div className="form-group">+ <label>Verification Code</label>+ <input+ type="text"+ value={verificationCode}+ onChange={(e) => setVerificationCode(e.target.value.replace(/\D/g, '').slice(0, 6))}+ placeholder="000000"+ autoFocus+ />+ {twoFAError && <p className="error-text">{twoFAError}</p>}+ </div>+ </>+ )}+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => {+ setShowBackupCodesModal(false);+ setBackupCodes([]);+ setVerificationCode('');+ }}>+ {backupCodes.length > 0 ? 'Done' : 'Cancel'}+ </button>+ {backupCodes.length === 0 && (+ <button+ className="btn btn-primary"+ onClick={handleRegenerateBackupCodes}+ disabled={twoFALoading || verificationCode.length !== 6}+ >+ {twoFALoading ? 'Generating...' : 'Generate New Codes'}+ </button>+ )}+ </div>+ </div>+ </div>+ )}</div>);};diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 5eb55214..d5e234c6 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -1585,6 +1585,45 @@ class ApiService {method: 'DELETE'});}++ // ========================================+ // Two-Factor Authentication endpoints+ // ========================================+ async get2FAStatus() {+ return this.request('/auth/2fa/status');+ }++ async initiate2FASetup() {+ return this.request('/auth/2fa/setup', { method: 'POST' });+ }++ async confirm2FASetup(code) {+ return this.request('/auth/2fa/setup/confirm', {+ method: 'POST',+ body: { code }+ });+ }++ async disable2FA(code) {+ return this.request('/auth/2fa/disable', {+ method: 'POST',+ body: { code }+ });+ }++ async regenerateBackupCodes(code) {+ return this.request('/auth/2fa/backup-codes/regenerate', {+ method: 'POST',+ body: { code }+ });+ }++ async verify2FA(tempToken, code) {+ return this.request('/auth/2fa/verify', {+ method: 'POST',+ body: { temp_token: tempToken, code }+ });+ }}export const api = new ApiService();diff --git a/frontend/src/styles/components/_two-factor.less b/frontend/src/styles/components/_two-factor.lessnew file mode 100644index 00000000..779a6f87--- /dev/null+++ b/frontend/src/styles/components/_two-factor.less@@ -0,0 +1,306 @@+// ============================================+// TWO-FACTOR AUTHENTICATION STYLES+// ============================================++// TOTP Code Input (Login page)+.totp-inputs {+ display: flex;+ justify-content: center;+ gap: @spacing-sm;+ margin: @spacing-lg 0;+}++.totp-input {+ width: 48px;+ height: 56px;+ font-size: 24px;+ font-weight: 600;+ text-align: center;+ border: 2px solid @border-color;+ border-radius: @radius-md;+ background: @surface-secondary;+ color: @text-primary;+ transition: all 0.2s;++ &:focus {+ border-color: @primary;+ outline: none;+ box-shadow: 0 0 0 3px fade(@primary, 20%);+ }++ &::placeholder {+ color: @text-tertiary;+ }+}++// Auth footer links+.auth-footer-links {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: @spacing-sm;+ margin-top: @spacing-lg;+}++.link-button {+ background: none;+ border: none;+ color: @primary;+ cursor: pointer;+ font-size: @font-size-sm;+ padding: 0;++ &:hover {+ text-decoration: underline;+ }+}++// 2FA Card in Settings+.two-fa-card {+ border: 1px solid @border-color;+ border-radius: @radius-lg;+ padding: @spacing-lg;+ margin-bottom: @spacing-lg;+}++.two-fa-header {+ display: flex;+ gap: @spacing-md;+ margin-bottom: @spacing-lg;++ .two-fa-icon {+ width: 48px;+ height: 48px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: fade(@primary, 15%);+ border-radius: @radius-md;+ color: @primary;+ flex-shrink: 0;+ }++ h3 {+ margin: 0 0 @spacing-xs 0;+ }++ p {+ margin: 0;+ color: @text-secondary;+ font-size: @font-size-sm;+ }+}++.two-fa-disabled {+ .two-fa-description {+ color: @text-secondary;+ margin-bottom: @spacing-md;+ }+}++.two-fa-enabled {+ .two-fa-status {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ margin-bottom: @spacing-md;+ }++ .two-fa-info {+ color: @text-secondary;+ font-size: @font-size-sm;+ }++ .two-fa-backup-info {+ background: @surface-tertiary;+ padding: @spacing-sm @spacing-md;+ border-radius: @radius-sm;+ margin-bottom: @spacing-md;+ display: flex;+ flex-direction: column;+ gap: @spacing-xs;++ .warning-text {+ color: @warning;+ font-size: @font-size-sm;+ }+ }++ .two-fa-actions {+ display: flex;+ gap: @spacing-sm;+ }+}++// Setup Modal+.setup-steps {+ display: flex;+ flex-direction: column;+ gap: @spacing-lg;+}++.setup-step {+ display: flex;+ gap: @spacing-md;++ .step-number {+ width: 28px;+ height: 28px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: @primary;+ color: white;+ border-radius: 50%;+ font-weight: 600;+ font-size: @font-size-sm;+ flex-shrink: 0;+ }++ .step-content {+ flex: 1;++ h4 {+ margin: 0 0 @spacing-xs 0;+ }++ p {+ color: @text-secondary;+ margin: 0 0 @spacing-md 0;+ font-size: @font-size-sm;+ }+ }+}++.qr-code-container {+ display: flex;+ justify-content: center;+ padding: @spacing-md;+ background: white;+ border-radius: @radius-md;+ margin-bottom: @spacing-md;+}++.qr-code {+ width: 200px;+ height: 200px;+}++.qr-fallback {+ background: @surface-tertiary;+ padding: @spacing-md;+ border-radius: @radius-md;+ text-align: center;++ .secret-key {+ display: block;+ font-size: @font-size-lg;+ padding: @spacing-sm;+ margin-top: @spacing-sm;+ background: @surface-primary;+ border-radius: @radius-sm;+ word-break: break-all;+ }+}++.manual-entry {+ margin-top: @spacing-md;+ font-size: @font-size-sm;+ color: @text-secondary;++ summary {+ cursor: pointer;+ color: @primary;++ &:hover {+ text-decoration: underline;+ }+ }++ p {+ margin: @spacing-xs 0;+ }++ code {+ background: @surface-tertiary;+ padding: 2px 6px;+ border-radius: @radius-sm;+ }+}++.verification-input {+ font-size: 24px;+ font-weight: 600;+ text-align: center;+ letter-spacing: 0.5em;+ padding: @spacing-md;+ width: 100%;+ max-width: 200px;+}++// Warning Box+.warning-box {+ display: flex;+ gap: @spacing-md;+ padding: @spacing-md;+ background: fade(@warning, 10%);+ border: 1px solid fade(@warning, 30%);+ border-radius: @radius-md;+ margin-bottom: @spacing-lg;++ svg {+ flex-shrink: 0;+ color: @warning;+ }++ p {+ margin: 0;+ color: @text-primary;+ font-size: @font-size-sm;+ }+}++.error-text {+ color: @danger;+ font-size: @font-size-sm;+ margin-top: @spacing-xs;+}++// Backup Codes Grid+.backup-codes-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: @spacing-sm;+ margin-bottom: @spacing-lg;+}++.backup-code {+ display: block;+ padding: @spacing-sm @spacing-md;+ background: @surface-tertiary;+ border-radius: @radius-sm;+ text-align: center;+ font-size: @font-size-md;+ font-family: @font-mono;+}++.backup-codes-actions {+ display: flex;+ justify-content: center;+ gap: @spacing-sm;++ .btn svg {+ margin-right: @spacing-xs;+ }+}++// Modal medium size+.modal-md {+ max-width: 500px;+}++// Loading small+.loading-sm {+ color: @text-tertiary;+ font-size: @font-size-sm;+}diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex d24b3203..d72fe5ac 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -41,6 +41,7 @@@import 'components/_spinner';@import 'components/_uptime';@import 'components/_env-vars';+@import 'components/_two-factor';// --------------------------------------------// 5. PAGE-SPECIFIC STYLES