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 database query runner and notification preferences
Juan Denisf7f8e18852b9
diff --git a/backend/app/api/databases.py b/backend/app/api/databases.pyindex 8c2166fb..35e2c71e 100644--- a/backend/app/api/databases.py+++ b/backend/app/api/databases.py@@ -429,6 +429,183 @@ def delete_backup(filename):return jsonify(result), 200 if result['success'] else 400+# ==================== QUERY EXECUTION ====================++@databases_bp.route('/mysql/<name>/query', methods=['POST'])+@jwt_required()+def execute_mysql_query(name):+ """Execute a query on a MySQL database.++ Request body:+ query: SQL query to execute+ readonly: If true, only allow SELECT/SHOW/DESCRIBE/EXPLAIN (default: true)++ Security: Readonly mode is enforced by default. Admin role required to disable.+ """+ data = request.get_json()++ if not data or 'query' not in data:+ return jsonify({'error': 'query is required'}), 400++ query = data['query']+ readonly = data.get('readonly', True)+ root_password = request.headers.get('X-DB-Password')++ # Only admins can disable readonly mode+ if not readonly:+ current_user_id = get_jwt_identity()+ from app.models import User+ user = User.query.get(current_user_id)+ if not user or user.role != 'admin':+ return jsonify({'error': 'Admin access required to execute write queries'}), 403++ result = DatabaseService.mysql_execute_query(+ database=name,+ query=query,+ readonly=readonly,+ root_password=root_password,+ timeout=30,+ max_rows=1000+ )++ return jsonify(result), 200 if result['success'] else 400+++@databases_bp.route('/postgresql/<name>/query', methods=['POST'])+@jwt_required()+def execute_pg_query(name):+ """Execute a query on a PostgreSQL database.++ Request body:+ query: SQL query to execute+ readonly: If true, only allow SELECT/SHOW/DESCRIBE/EXPLAIN (default: true)++ Security: Readonly mode is enforced by default. Admin role required to disable.+ """+ data = request.get_json()++ if not data or 'query' not in data:+ return jsonify({'error': 'query is required'}), 400++ query = data['query']+ readonly = data.get('readonly', True)++ # Only admins can disable readonly mode+ if not readonly:+ current_user_id = get_jwt_identity()+ from app.models import User+ user = User.query.get(current_user_id)+ if not user or user.role != 'admin':+ return jsonify({'error': 'Admin access required to execute write queries'}), 403++ result = DatabaseService.pg_execute_query(+ database=name,+ query=query,+ readonly=readonly,+ timeout=30,+ max_rows=1000+ )++ return jsonify(result), 200 if result['success'] else 400+++@databases_bp.route('/sqlite/query', methods=['POST'])+@jwt_required()+def execute_sqlite_query():+ """Execute a query on a SQLite database file.++ Request body:+ path: Path to the SQLite database file+ query: SQL query to execute+ readonly: If true, only allow SELECT queries (default: true)++ Security: Readonly mode is enforced by default. Admin role required to disable.+ """+ data = request.get_json()++ if not data or 'path' not in data or 'query' not in data:+ return jsonify({'error': 'path and query are required'}), 400++ db_path = data['path']+ query = data['query']+ readonly = data.get('readonly', True)++ # Only admins can disable readonly mode+ if not readonly:+ current_user_id = get_jwt_identity()+ from app.models import User+ user = User.query.get(current_user_id)+ if not user or user.role != 'admin':+ return jsonify({'error': 'Admin access required to execute write queries'}), 403++ result = DatabaseService.sqlite_execute_query(+ db_path=db_path,+ query=query,+ readonly=readonly,+ timeout=30,+ max_rows=1000+ )++ return jsonify(result), 200 if result['success'] else 400+++@databases_bp.route('/mysql/<name>/tables/<table>/structure', methods=['GET'])+@jwt_required()+def get_mysql_table_structure(name, table):+ """Get the structure/schema of a MySQL table."""+ root_password = request.headers.get('X-DB-Password')+ result = DatabaseService.mysql_get_table_structure(name, table, root_password)+ return jsonify(result), 200 if result['success'] else 400+++@databases_bp.route('/postgresql/<name>/tables/<table>/structure', methods=['GET'])+@jwt_required()+def get_pg_table_structure(name, table):+ """Get the structure/schema of a PostgreSQL table."""+ result = DatabaseService.pg_get_table_structure(name, table)+ return jsonify(result), 200 if result['success'] else 400+++@databases_bp.route('/sqlite/tables/<table>/structure', methods=['GET'])+@jwt_required()+def get_sqlite_table_structure(table):+ """Get the structure/schema of a SQLite table.++ Query params:+ path: Path to the SQLite database file+ """+ db_path = request.args.get('path')+ if not db_path:+ return jsonify({'error': 'path query parameter is required'}), 400++ result = DatabaseService.sqlite_get_table_structure(db_path, table)+ return jsonify(result), 200 if result['success'] else 400+++@databases_bp.route('/sqlite', methods=['GET'])+@jwt_required()+def list_sqlite_databases():+ """List SQLite database files found in common locations."""+ databases = DatabaseService.sqlite_list_databases()+ return jsonify({'databases': databases}), 200+++@databases_bp.route('/sqlite/tables', methods=['GET'])+@jwt_required()+def get_sqlite_tables():+ """Get tables in a SQLite database.++ Query params:+ path: Path to the SQLite database file+ """+ db_path = request.args.get('path')+ if not db_path:+ return jsonify({'error': 'path query parameter is required'}), 400++ tables = DatabaseService.sqlite_get_tables(db_path)+ return jsonify({'tables': tables}), 200++# ==================== UTILITY ====================@databases_bp.route('/generate-password', methods=['GET'])diff --git a/backend/app/api/notifications.py b/backend/app/api/notifications.pyindex 6d484c01..7428be32 100644--- a/backend/app/api/notifications.py+++ b/backend/app/api/notifications.py@@ -1,6 +1,7 @@from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identity-from app.models import User+from app.models import User, NotificationPreferences+from app import dbfrom app.services.notification_service import NotificationServicenotifications_bp = Blueprint('notifications', __name__)@@ -51,6 +52,10 @@ def get_config():url = config['generic_webhook']['url']config['generic_webhook']['url'] = url[:30] + '...' if len(url) > 30 else url+ if 'email' in config:+ if config['email'].get('smtp_password'):+ config['email']['smtp_password'] = '***'+return jsonify(config), 200@@ -63,7 +68,7 @@ def update_channel_config(channel):if not data:return jsonify({'error': 'No data provided'}), 400- valid_channels = ['discord', 'slack', 'telegram', 'generic_webhook']+ valid_channels = ['discord', 'slack', 'telegram', 'email', 'generic_webhook']if channel not in valid_channels:return jsonify({'error': f'Invalid channel. Valid options: {valid_channels}'}), 400@@ -83,6 +88,10 @@ def update_channel_config(channel):if data.get('bot_token') == '***':data['bot_token'] = current_config.get('telegram', {}).get('bot_token', '')+ elif channel == 'email':+ if data.get('smtp_password') == '***':+ data['smtp_password'] = current_config.get('email', {}).get('smtp_password', '')+elif channel == 'generic_webhook':if data.get('url') and '...' in data.get('url', ''):data['url'] = current_config.get('generic_webhook', {}).get('url', '')@@ -96,7 +105,7 @@ def update_channel_config(channel):@admin_requireddef test_channel(channel):"""Send a test notification to a specific channel."""- valid_channels = ['discord', 'slack', 'telegram', 'generic_webhook']+ valid_channels = ['discord', 'slack', 'telegram', 'email', 'generic_webhook']if channel not in valid_channels:return jsonify({'error': f'Invalid channel. Valid options: {valid_channels}'}), 400@@ -121,7 +130,7 @@ def test_all_channels():config = NotificationService.get_config()results = {}- for channel in ['discord', 'slack', 'telegram', 'generic_webhook']:+ for channel in ['discord', 'slack', 'telegram', 'email', 'generic_webhook']:channel_config = config.get(channel, {})if channel_config.get('enabled'):test_config = {**channel_config, 'notify_on': ['test']}@@ -132,6 +141,8 @@ def test_all_channels():results[channel] = NotificationService.send_slack(test_alerts, test_config)elif channel == 'telegram':results[channel] = NotificationService.send_telegram(test_alerts, test_config)+ elif channel == 'email':+ results[channel] = NotificationService.send_email(test_alerts, test_config)elif channel == 'generic_webhook':results[channel] = NotificationService.send_generic_webhook(test_alerts, test_config)@@ -143,3 +154,142 @@ def test_all_channels():'success': all_success,'results': results}), 200 if all_success else 207 # 207 Multi-Status for partial success+++# ==========================================+# USER NOTIFICATION PREFERENCES+# ==========================================++@notifications_bp.route('/preferences', methods=['GET'])+@jwt_required()+def get_user_preferences():+ """Get current user's notification preferences."""+ current_user_id = get_jwt_identity()+ prefs = NotificationPreferences.get_or_create(current_user_id)+ return jsonify(prefs.to_dict()), 200+++@notifications_bp.route('/preferences', methods=['PUT'])+@jwt_required()+def update_user_preferences():+ """Update current user's notification preferences."""+ current_user_id = get_jwt_identity()+ data = request.get_json()++ if not data:+ return jsonify({'error': 'No data provided'}), 400++ prefs = NotificationPreferences.get_or_create(current_user_id)++ # Update fields+ if 'enabled' in data:+ prefs.enabled = data['enabled']++ if 'channels' in data:+ valid_channels = ['email', 'discord', 'slack', 'telegram']+ channels = [c for c in data['channels'] if c in valid_channels]+ prefs.set_channels(channels)++ if 'severities' in data:+ valid_severities = ['critical', 'warning', 'info', 'success']+ severities = [s for s in data['severities'] if s in valid_severities]+ prefs.set_severities(severities)++ if 'email' in data:+ prefs.email = data['email'] if data['email'] else None++ if 'discord_webhook' in data:+ # Don't update if it's the masked version+ if data['discord_webhook'] and '...' not in data['discord_webhook']:+ prefs.discord_webhook = data['discord_webhook']+ elif not data['discord_webhook']:+ prefs.discord_webhook = None++ if 'telegram_chat_id' in data:+ prefs.telegram_chat_id = data['telegram_chat_id'] if data['telegram_chat_id'] else None++ if 'categories' in data:+ prefs.set_categories(data['categories'])++ if 'quiet_hours' in data:+ qh = data['quiet_hours']+ if 'enabled' in qh:+ prefs.quiet_hours_enabled = qh['enabled']+ if 'start' in qh:+ prefs.quiet_hours_start = qh['start']+ if 'end' in qh:+ prefs.quiet_hours_end = qh['end']++ try:+ db.session.commit()+ return jsonify({'success': True, 'preferences': prefs.to_dict()}), 200+ except Exception as e:+ db.session.rollback()+ return jsonify({'error': str(e)}), 500+++@notifications_bp.route('/preferences/test', methods=['POST'])+@jwt_required()+def test_user_notification():+ """Send a test notification to the current user's configured channels."""+ current_user_id = get_jwt_identity()+ prefs = NotificationPreferences.get_or_create(current_user_id)+ user = User.query.get(current_user_id)++ if not prefs.enabled:+ return jsonify({'error': 'Notifications are disabled for your account'}), 400++ test_alert = {+ 'type': 'test',+ 'severity': 'test',+ 'message': f'This is a test notification for {user.username}. Your personal notification settings are working correctly!',+ 'value': 'N/A',+ 'threshold': 'N/A'+ }++ results = {}+ channels = prefs.get_channels()+ config = NotificationService.get_config()++ # Send to each enabled channel+ if 'email' in channels:+ email_to_use = prefs.email or user.email+ if email_to_use:+ email_config = {+ **config.get('email', {}),+ 'to_emails': [email_to_use],+ 'notify_on': ['test']+ }+ results['email'] = NotificationService.send_email([test_alert], email_config)++ if 'discord' in channels and prefs.discord_webhook:+ discord_config = {+ 'enabled': True,+ 'webhook_url': prefs.discord_webhook,+ 'username': 'ServerKit',+ 'notify_on': ['test']+ }+ results['discord'] = NotificationService.send_discord([test_alert], discord_config)++ if 'telegram' in channels and prefs.telegram_chat_id:+ telegram_config = {+ **config.get('telegram', {}),+ 'chat_id': prefs.telegram_chat_id,+ 'notify_on': ['test']+ }+ results['telegram'] = NotificationService.send_telegram([test_alert], telegram_config)++ if 'slack' in channels:+ # Use global slack config for user notifications+ slack_config = {**config.get('slack', {}), 'notify_on': ['test']}+ if slack_config.get('enabled') and slack_config.get('webhook_url'):+ results['slack'] = NotificationService.send_slack([test_alert], slack_config)++ if not results:+ return jsonify({'error': 'No channels configured for notifications'}), 400++ all_success = all(r.get('success', False) for r in results.values())+ return jsonify({+ 'success': all_success,+ 'results': results+ }), 200 if all_success else 207diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 7f8794a1..ca62af82 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -2,5 +2,6 @@ from app.models.user import Userfrom app.models.application import Applicationfrom app.models.domain import Domainfrom app.models.env_variable import EnvironmentVariable, EnvironmentVariableHistory+from app.models.notification_preferences import NotificationPreferences-__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory']+__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory', 'NotificationPreferences']diff --git a/backend/app/models/notification_preferences.py b/backend/app/models/notification_preferences.pynew file mode 100644index 00000000..6efb7473--- /dev/null+++ b/backend/app/models/notification_preferences.py@@ -0,0 +1,122 @@+"""+User Notification Preferences Model++Stores per-user notification preferences for receiving alerts.+"""++from datetime import datetime+from app import db+import json+++class NotificationPreferences(db.Model):+ __tablename__ = 'notification_preferences'++ id = db.Column(db.Integer, primary_key=True)+ user_id = db.Column(db.Integer, db.ForeignKey('users.id'), unique=True, nullable=False)++ # Global toggle - whether to receive any notifications+ enabled = db.Column(db.Boolean, default=True)++ # Which channels this user wants to receive notifications on+ # JSON array of channel names: ['email', 'discord', 'slack', 'telegram']+ channels = db.Column(db.Text, default='["email"]')++ # Severity levels this user wants to be notified about+ # JSON array: ['critical', 'warning', 'info', 'success']+ severities = db.Column(db.Text, default='["critical", "warning"]')++ # Personal email for notifications (overrides global email list if set)+ email = db.Column(db.String(255), nullable=True)++ # Personal Discord webhook (for DMs or personal server)+ discord_webhook = db.Column(db.String(512), nullable=True)++ # Personal Telegram chat ID (for personal notifications)+ telegram_chat_id = db.Column(db.String(64), nullable=True)++ # Notification categories the user wants+ # JSON object with category: boolean+ categories = db.Column(db.Text, default='{"system": true, "security": true, "backups": true, "apps": true}')++ # Quiet hours (don't send non-critical notifications during these hours)+ quiet_hours_enabled = db.Column(db.Boolean, default=False)+ quiet_hours_start = db.Column(db.String(5), default='22:00') # HH:MM format+ quiet_hours_end = db.Column(db.String(5), default='08:00')++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ # Relationship+ user = db.relationship('User', backref=db.backref('notification_preferences', uselist=False))++ def get_channels(self):+ """Get the list of enabled channels."""+ try:+ return json.loads(self.channels) if self.channels else ['email']+ except (json.JSONDecodeError, TypeError):+ return ['email']++ def set_channels(self, channels_list):+ """Set the list of enabled channels."""+ self.channels = json.dumps(channels_list)++ def get_severities(self):+ """Get the list of enabled severity levels."""+ try:+ return json.loads(self.severities) if self.severities else ['critical', 'warning']+ except (json.JSONDecodeError, TypeError):+ return ['critical', 'warning']++ def set_severities(self, severities_list):+ """Set the list of enabled severity levels."""+ self.severities = json.dumps(severities_list)++ def get_categories(self):+ """Get notification category preferences."""+ try:+ return json.loads(self.categories) if self.categories else {+ 'system': True,+ 'security': True,+ 'backups': True,+ 'apps': True+ }+ except (json.JSONDecodeError, TypeError):+ return {'system': True, 'security': True, 'backups': True, 'apps': True}++ def set_categories(self, categories_dict):+ """Set notification category preferences."""+ self.categories = json.dumps(categories_dict)++ def to_dict(self):+ """Convert to dictionary for API response."""+ return {+ 'id': self.id,+ 'user_id': self.user_id,+ 'enabled': self.enabled,+ 'channels': self.get_channels(),+ 'severities': self.get_severities(),+ 'email': self.email,+ 'discord_webhook': self.discord_webhook[:30] + '...' if self.discord_webhook and len(self.discord_webhook) > 30 else self.discord_webhook,+ 'telegram_chat_id': self.telegram_chat_id,+ 'categories': self.get_categories(),+ 'quiet_hours': {+ 'enabled': self.quiet_hours_enabled,+ 'start': self.quiet_hours_start,+ 'end': self.quiet_hours_end+ },+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None+ }++ @classmethod+ def get_or_create(cls, user_id):+ """Get existing preferences or create default ones."""+ prefs = cls.query.filter_by(user_id=user_id).first()+ if not prefs:+ prefs = cls(user_id=user_id)+ db.session.add(prefs)+ db.session.commit()+ return prefs++ def __repr__(self):+ return f'<NotificationPreferences user_id={self.user_id}>'diff --git a/backend/app/services/database_service.py b/backend/app/services/database_service.pyindex e309e377..adcc8d69 100644--- a/backend/app/services/database_service.py+++ b/backend/app/services/database_service.py@@ -509,6 +509,429 @@ class DatabaseService:})return tables+ # ==================== QUERY EXECUTION ====================++ # Allowed readonly commands for security+ READONLY_COMMANDS = {'SELECT', 'SHOW', 'DESCRIBE', 'DESC', 'EXPLAIN'}++ @staticmethod+ def _is_readonly_query(query):+ """Check if a query is readonly (SELECT, SHOW, DESCRIBE, EXPLAIN)."""+ # Remove leading whitespace and get first word+ normalized = query.strip().upper()+ first_word = normalized.split()[0] if normalized.split() else ''+ return first_word in DatabaseService.READONLY_COMMANDS++ @staticmethod+ def mysql_execute_query(database, query, readonly=True, root_password=None, timeout=30, max_rows=1000):+ """Execute a MySQL query and return structured results.++ Args:+ database: Database name to query+ query: SQL query to execute+ readonly: If True, only allow SELECT/SHOW/DESCRIBE/EXPLAIN+ root_password: MySQL root password+ timeout: Query timeout in seconds+ max_rows: Maximum rows to return++ Returns:+ dict with columns, rows, row_count, and execution info+ """+ import json+ import time++ # Security check for readonly mode+ if readonly and not DatabaseService._is_readonly_query(query):+ return {+ 'success': False,+ 'error': 'Only SELECT, SHOW, DESCRIBE, and EXPLAIN queries are allowed in readonly mode'+ }++ try:+ start_time = time.time()++ # Build mysql command with JSON output format+ cmd = ['mysql', '-u', 'root']+ if root_password:+ cmd.extend([f'-p{root_password}'])+ cmd.extend([+ '-D', database,+ '-e', query,+ '--batch', # Tab-separated output+ '-N' if query.strip().upper().startswith(('SHOW', 'DESCRIBE', 'DESC')) else ''+ ])+ # Remove empty strings from cmd+ cmd = [c for c in cmd if c]++ result = subprocess.run(+ cmd,+ capture_output=True,+ text=True,+ timeout=timeout+ )++ execution_time = time.time() - start_time++ if result.returncode != 0:+ return {+ 'success': False,+ 'error': result.stderr.strip() if result.stderr else 'Query execution failed'+ }++ # Parse the output+ lines = result.stdout.strip().split('\n') if result.stdout.strip() else []++ if not lines:+ return {+ 'success': True,+ 'columns': [],+ 'rows': [],+ 'row_count': 0,+ 'execution_time': execution_time,+ 'truncated': False+ }++ # First line is headers (unless -N was used)+ if query.strip().upper().startswith(('SHOW', 'DESCRIBE', 'DESC')):+ # For SHOW/DESCRIBE, we need to add generic column names+ columns = [f'Column_{i}' for i in range(len(lines[0].split('\t')))] if lines else []+ data_lines = lines+ else:+ columns = lines[0].split('\t') if lines else []+ data_lines = lines[1:]++ # Parse rows+ rows = []+ for i, line in enumerate(data_lines):+ if i >= max_rows:+ break+ values = line.split('\t')+ # Convert NULL strings to None+ values = [None if v == 'NULL' else v for v in values]+ rows.append(values)++ return {+ 'success': True,+ 'columns': columns,+ 'rows': rows,+ 'row_count': len(rows),+ 'total_rows': len(data_lines),+ 'execution_time': round(execution_time, 4),+ 'truncated': len(data_lines) > max_rows+ }++ except subprocess.TimeoutExpired:+ return {+ 'success': False,+ 'error': f'Query timed out after {timeout} seconds'+ }+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @staticmethod+ def pg_execute_query(database, query, readonly=True, timeout=30, max_rows=1000):+ """Execute a PostgreSQL query and return structured results.++ Args:+ database: Database name to query+ query: SQL query to execute+ readonly: If True, only allow SELECT/SHOW/DESCRIBE/EXPLAIN+ timeout: Query timeout in seconds+ max_rows: Maximum rows to return++ Returns:+ dict with columns, rows, row_count, and execution info+ """+ import time++ # Security check for readonly mode+ if readonly and not DatabaseService._is_readonly_query(query):+ return {+ 'success': False,+ 'error': 'Only SELECT, SHOW, DESCRIBE, and EXPLAIN queries are allowed in readonly mode'+ }++ try:+ start_time = time.time()++ # For PostgreSQL, we use psql with specific formatting+ # -F sets field separator, -A for unaligned output+ cmd = [+ 'sudo', '-u', 'postgres', 'psql',+ '-d', database,+ '-c', query,+ '-F', '\t', # Tab separator+ '-A', # Unaligned output+ '--pset', 'footer=off' # No row count footer+ ]++ result = subprocess.run(+ cmd,+ capture_output=True,+ text=True,+ timeout=timeout+ )++ execution_time = time.time() - start_time++ if result.returncode != 0:+ error_msg = result.stderr.strip() if result.stderr else 'Query execution failed'+ return {+ 'success': False,+ 'error': error_msg+ }++ # Parse the output+ lines = result.stdout.strip().split('\n') if result.stdout.strip() else []++ if not lines:+ return {+ 'success': True,+ 'columns': [],+ 'rows': [],+ 'row_count': 0,+ 'execution_time': execution_time,+ 'truncated': False+ }++ # First line is headers+ columns = lines[0].split('\t') if lines else []+ data_lines = lines[1:] if len(lines) > 1 else []++ # Parse rows+ rows = []+ for i, line in enumerate(data_lines):+ if i >= max_rows:+ break+ if line.strip(): # Skip empty lines+ values = line.split('\t')+ # Convert empty strings and special values+ values = [None if v == '' else v for v in values]+ rows.append(values)++ return {+ 'success': True,+ 'columns': columns,+ 'rows': rows,+ 'row_count': len(rows),+ 'total_rows': len(data_lines),+ 'execution_time': round(execution_time, 4),+ 'truncated': len(data_lines) > max_rows+ }++ except subprocess.TimeoutExpired:+ return {+ 'success': False,+ 'error': f'Query timed out after {timeout} seconds'+ }+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @staticmethod+ def sqlite_execute_query(db_path, query, readonly=True, timeout=30, max_rows=1000):+ """Execute a SQLite query and return structured results.++ Args:+ db_path: Path to SQLite database file+ query: SQL query to execute+ readonly: If True, only allow SELECT/SHOW/DESCRIBE/EXPLAIN+ timeout: Query timeout in seconds+ max_rows: Maximum rows to return++ Returns:+ dict with columns, rows, row_count, and execution info+ """+ import sqlite3+ import time++ # Security check for readonly mode+ if readonly and not DatabaseService._is_readonly_query(query):+ return {+ 'success': False,+ 'error': 'Only SELECT queries are allowed in readonly mode'+ }++ # Validate path exists+ if not os.path.exists(db_path):+ return {'success': False, 'error': f'Database file not found: {db_path}'}++ try:+ start_time = time.time()++ # Open in readonly mode if readonly is True+ uri = f'file:{db_path}?mode=ro' if readonly else db_path+ conn = sqlite3.connect(uri, uri=readonly, timeout=timeout)+ conn.row_factory = sqlite3.Row+ cursor = conn.cursor()++ cursor.execute(query)++ # Get column names+ columns = [description[0] for description in cursor.description] if cursor.description else []++ # Fetch rows with limit+ rows = []+ total_fetched = 0+ for row in cursor:+ total_fetched += 1+ if len(rows) < max_rows:+ rows.append(list(row))++ execution_time = time.time() - start_time+ conn.close()++ return {+ 'success': True,+ 'columns': columns,+ 'rows': rows,+ 'row_count': len(rows),+ 'total_rows': total_fetched,+ 'execution_time': round(execution_time, 4),+ 'truncated': total_fetched > max_rows+ }++ except sqlite3.OperationalError as e:+ return {'success': False, 'error': str(e)}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @staticmethod+ def mysql_get_table_structure(database, table, root_password=None):+ """Get the structure/schema of a MySQL table."""+ query = f"DESCRIBE `{table}`;"+ result = DatabaseService.mysql_execute(query, database=database, root_password=root_password)++ if not result['success']:+ return result++ columns = []+ for line in result['output'].strip().split('\n')[1:]:+ parts = line.split('\t')+ if len(parts) >= 6:+ columns.append({+ 'name': parts[0],+ 'type': parts[1],+ 'nullable': parts[2] == 'YES',+ 'key': parts[3],+ 'default': parts[4] if parts[4] != 'NULL' else None,+ 'extra': parts[5]+ })++ return {'success': True, 'columns': columns, 'table': table}++ @staticmethod+ def pg_get_table_structure(database, table):+ """Get the structure/schema of a PostgreSQL table."""+ query = f"""+ SELECT column_name, data_type, is_nullable, column_default+ FROM information_schema.columns+ WHERE table_name = '{table}' AND table_schema = 'public'+ ORDER BY ordinal_position;+ """+ result = DatabaseService.pg_execute(query, database=database)++ if not result['success']:+ return result++ columns = []+ for line in result['output'].strip().split('\n'):+ parts = line.split('|')+ if len(parts) >= 4:+ columns.append({+ 'name': parts[0].strip(),+ 'type': parts[1].strip(),+ 'nullable': parts[2].strip() == 'YES',+ 'default': parts[3].strip() if parts[3].strip() else None+ })++ return {'success': True, 'columns': columns, 'table': table}++ @staticmethod+ def sqlite_get_table_structure(db_path, table):+ """Get the structure/schema of a SQLite table."""+ import sqlite3++ if not os.path.exists(db_path):+ return {'success': False, 'error': f'Database file not found: {db_path}'}++ try:+ conn = sqlite3.connect(f'file:{db_path}?mode=ro', uri=True)+ cursor = conn.cursor()+ cursor.execute(f"PRAGMA table_info(`{table}`);")+ rows = cursor.fetchall()+ conn.close()++ columns = []+ for row in rows:+ columns.append({+ 'name': row[1],+ 'type': row[2],+ 'nullable': row[3] == 0,+ 'default': row[4],+ 'primary_key': row[5] == 1+ })++ return {'success': True, 'columns': columns, 'table': table}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @staticmethod+ def sqlite_list_databases(search_paths=None):+ """Find SQLite database files in common locations."""+ if search_paths is None:+ search_paths = ['/var/www', '/home', '/opt']++ databases = []+ for base_path in search_paths:+ if not os.path.exists(base_path):+ continue+ try:+ for root, dirs, files in os.walk(base_path):+ # Skip hidden directories and common non-app directories+ dirs[:] = [d for d in dirs if not d.startswith('.') and d not in ['node_modules', 'vendor', '__pycache__']]++ for file in files:+ if file.endswith(('.db', '.sqlite', '.sqlite3')):+ filepath = os.path.join(root, file)+ try:+ size = os.path.getsize(filepath)+ databases.append({+ 'name': file,+ 'path': filepath,+ 'size': size,+ 'type': 'sqlite'+ })+ except OSError:+ continue+ except PermissionError:+ continue++ return databases++ @staticmethod+ def sqlite_get_tables(db_path):+ """Get tables in a SQLite database."""+ import sqlite3++ if not os.path.exists(db_path):+ return []++ try:+ conn = sqlite3.connect(f'file:{db_path}?mode=ro', uri=True)+ cursor = conn.cursor()+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';")+ tables = []+ for row in cursor.fetchall():+ table_name = row[0]+ # Get row count+ cursor.execute(f"SELECT COUNT(*) FROM `{table_name}`;")+ count = cursor.fetchone()[0]+ tables.append({'name': table_name, 'rows': count})+ conn.close()+ return tables+ except Exception:+ return []+# ==================== UTILITY ====================@staticmethoddiff --git a/backend/app/services/notification_service.py b/backend/app/services/notification_service.pyindex bf05c3c6..2085e97c 100644--- a/backend/app/services/notification_service.py+++ b/backend/app/services/notification_service.py@@ -6,12 +6,15 @@ Handles sending notifications to various channels:- Slack webhooks- Telegram bots- Generic webhooks-- Email (via existing SMTP config)+- Email (with HTML templates)"""import osimport jsonimport requests+import smtplib+from email.mime.text import MIMEText+from email.mime.multipart import MIMEMultipartfrom datetime import datetimefrom typing import Dict, List, Optionalfrom pathlib import Path@@ -64,6 +67,18 @@ class NotificationService:'chat_id': '','notify_on': ['critical', 'warning']},+ 'email': {+ 'enabled': False,+ 'smtp_host': '',+ 'smtp_port': 587,+ 'smtp_user': '',+ 'smtp_password': '',+ 'smtp_tls': True,+ 'from_email': '',+ 'from_name': 'ServerKit',+ 'to_emails': [],+ 'notify_on': ['critical', 'warning']+ },'generic_webhook': {'enabled': False,'url': '',@@ -376,6 +391,201 @@ class NotificationService:except Exception as e:return {'success': False, 'error': str(e)}+ # ==========================================+ # ==========================================+ @classmethod+ def _get_email_template(cls, alerts: List[Dict]) -> str:+ """Generate HTML email template for alerts."""+ hostname = cls.get_hostname()+ timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')++ # Color mapping for severity+ severity_styles = {+ 'critical': {'bg': '#fef2f2', 'border': '#ef4444', 'text': '#dc2626'},+ 'warning': {'bg': '#fffbeb', 'border': '#f59e0b', 'text': '#d97706'},+ 'info': {'bg': '#eff6ff', 'border': '#3b82f6', 'text': '#2563eb'},+ 'success': {'bg': '#f0fdf4', 'border': '#22c55e', 'text': '#16a34a'},+ 'test': {'bg': '#f9fafb', 'border': '#6b7280', 'text': '#4b5563'}+ }++ alerts_html = ""+ for alert in alerts:+ severity = alert.get('severity', 'info')+ style = severity_styles.get(severity, severity_styles['info'])++ alert_html = f"""+ <div style="margin-bottom: 16px; padding: 16px; background-color: {style['bg']};+ border-left: 4px solid {style['border']}; border-radius: 4px;">+ <div style="color: {style['text']}; font-weight: 600; font-size: 14px;+ text-transform: uppercase; margin-bottom: 8px;">+ {severity}: {alert.get('type', 'Alert').upper()}+ </div>+ <div style="color: #374151; font-size: 14px;">+ {alert.get('message', 'No message')}+ </div>+ """++ if 'value' in alert or 'threshold' in alert:+ alert_html += '<div style="margin-top: 12px; font-size: 13px; color: #6b7280;">'+ if 'value' in alert:+ alert_html += f'<span style="margin-right: 16px;">Current: <strong>{alert["value"]}</strong></span>'+ if 'threshold' in alert:+ alert_html += f'<span>Threshold: <strong>{alert["threshold"]}</strong></span>'+ alert_html += '</div>'++ alert_html += '</div>'+ alerts_html += alert_html++ template = f"""+ <!DOCTYPE html>+ <html>+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ </head>+ <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;+ line-height: 1.6; color: #374151; max-width: 600px; margin: 0 auto; padding: 20px;">++ <!-- Header -->+ <div style="text-align: center; padding: 24px 0; border-bottom: 1px solid #e5e7eb;">+ <h1 style="margin: 0; color: #111827; font-size: 24px;">+ ServerKit Alert+ </h1>+ <p style="margin: 8px 0 0 0; color: #6b7280; font-size: 14px;">+ {len(alerts)} alert(s) triggered on {hostname}+ </p>+ </div>++ <!-- Alerts -->+ <div style="padding: 24px 0;">+ {alerts_html}+ </div>++ <!-- Footer -->+ <div style="text-align: center; padding: 24px 0; border-top: 1px solid #e5e7eb;+ font-size: 12px; color: #9ca3af;">+ <p style="margin: 0;">+ Sent by ServerKit at {timestamp}+ </p>+ <p style="margin: 8px 0 0 0;">+ <a href="#" style="color: #6366f1; text-decoration: none;">Manage notification settings</a>+ </p>+ </div>+ </body>+ </html>+ """+ return template++ @classmethod+ def _get_plain_text_template(cls, alerts: List[Dict]) -> str:+ """Generate plain text email for alerts."""+ hostname = cls.get_hostname()+ timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')++ lines = [+ "ServerKit Alert",+ "=" * 40,+ f"{len(alerts)} alert(s) triggered on {hostname}",+ ""+ ]++ for alert in alerts:+ severity = alert.get('severity', 'info').upper()+ alert_type = alert.get('type', 'Alert').upper()+ lines.append(f"[{severity}] {alert_type}")+ lines.append(alert.get('message', 'No message'))+ if 'value' in alert:+ lines.append(f" Current: {alert['value']}")+ if 'threshold' in alert:+ lines.append(f" Threshold: {alert['threshold']}")+ lines.append("")++ lines.append("-" * 40)+ lines.append(f"Sent by ServerKit at {timestamp}")++ return "\n".join(lines)++ @classmethod+ def send_email(cls, alerts: List[Dict], config: Dict = None) -> Dict:+ """+ Send notification via email with HTML template.++ Args:+ alerts: List of alert dictionaries+ config: Email configuration (optional, uses saved config if not provided)++ Returns:+ dict with success status and message+ """+ if config is None:+ config = cls.get_config().get('email', {})++ if not config.get('enabled'):+ return {'success': False, 'error': 'Email notifications not enabled'}++ if not config.get('smtp_host') or not config.get('from_email') or not config.get('to_emails'):+ return {'success': False, 'error': 'Email not configured (missing SMTP host, from email, or recipients)'}++ # Filter alerts by severity+ notify_on = config.get('notify_on', ['critical', 'warning'])+ alerts = [a for a in alerts if a.get('severity', 'info') in notify_on]++ if not alerts:+ return {'success': True, 'message': 'No alerts to send'}++ try:+ # Determine subject based on severity+ severities = [a.get('severity', 'info') for a in alerts]+ if 'critical' in severities:+ priority = 'CRITICAL'+ elif 'warning' in severities:+ priority = 'WARNING'+ else:+ priority = 'INFO'++ subject = f"[{priority}] ServerKit: {len(alerts)} alert(s) on {cls.get_hostname()}"++ # Create message+ msg = MIMEMultipart('alternative')+ msg['Subject'] = subject+ msg['From'] = f"{config.get('from_name', 'ServerKit')} <{config['from_email']}>"+ msg['To'] = ', '.join(config['to_emails'])++ # Add plain text and HTML versions+ plain_text = cls._get_plain_text_template(alerts)+ html_content = cls._get_email_template(alerts)++ msg.attach(MIMEText(plain_text, 'plain'))+ msg.attach(MIMEText(html_content, 'html'))++ # Send email+ smtp_port = config.get('smtp_port', 587)+ use_tls = config.get('smtp_tls', True)++ if use_tls:+ server = smtplib.SMTP(config['smtp_host'], smtp_port)+ server.starttls()+ else:+ server = smtplib.SMTP_SSL(config['smtp_host'], smtp_port)++ if config.get('smtp_user') and config.get('smtp_password'):+ server.login(config['smtp_user'], config['smtp_password'])++ server.send_message(msg)+ server.quit()++ return {'success': True, 'message': 'Email notification sent'}++ except smtplib.SMTPAuthenticationError:+ return {'success': False, 'error': 'SMTP authentication failed'}+ except smtplib.SMTPConnectError:+ return {'success': False, 'error': 'Failed to connect to SMTP server'}+ except smtplib.SMTPException as e:+ return {'success': False, 'error': f'SMTP error: {str(e)}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}+# ==========================================# GENERIC WEBHOOK# ==========================================@@ -454,6 +664,9 @@ class NotificationService:if config.get('telegram', {}).get('enabled'):results['telegram'] = cls.send_telegram(alerts, config['telegram'])+ if config.get('email', {}).get('enabled'):+ results['email'] = cls.send_email(alerts, config['email'])+if config.get('generic_webhook', {}).get('enabled'):results['generic_webhook'] = cls.send_generic_webhook(alerts, config['generic_webhook'])@@ -488,6 +701,9 @@ class NotificationService:elif channel == 'telegram':test_config = {**config.get('telegram', {}), 'notify_on': ['test']}return cls.send_telegram(test_alerts, test_config)+ elif channel == 'email':+ test_config = {**config.get('email', {}), 'notify_on': ['test']}+ return cls.send_email(test_alerts, test_config)elif channel == 'generic_webhook':test_config = {**config.get('generic_webhook', {}), 'notify_on': ['test']}return cls.send_generic_webhook(test_alerts, test_config)@@ -518,6 +734,15 @@ class NotificationService:'configured': bool(config.get('telegram', {}).get('bot_token') and config.get('telegram', {}).get('chat_id')),'notify_on': config.get('telegram', {}).get('notify_on', [])},+ 'email': {+ 'enabled': config.get('email', {}).get('enabled', False),+ 'configured': bool(+ config.get('email', {}).get('smtp_host') and+ config.get('email', {}).get('from_email') and+ config.get('email', {}).get('to_emails')+ ),+ 'notify_on': config.get('email', {}).get('notify_on', [])+ },'generic_webhook': {'enabled': config.get('generic_webhook', {}).get('enabled', False),'configured': bool(config.get('generic_webhook', {}).get('url')),diff --git a/frontend/src/components/QueryRunner.jsx b/frontend/src/components/QueryRunner.jsxnew file mode 100644index 00000000..c2fe8b63--- /dev/null+++ b/frontend/src/components/QueryRunner.jsx@@ -0,0 +1,469 @@+import React, { useState, useEffect, useRef, useCallback } from 'react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++const HISTORY_KEY = 'serverkit_query_history';+const MAX_HISTORY = 50;++const QueryRunner = ({ database, dbType, onClose }) => {+ const toast = useToast();+ const textareaRef = useRef(null);++ const [query, setQuery] = useState('');+ const [results, setResults] = useState(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState('');+ const [readonly, setReadonly] = useState(true);+ const [tables, setTables] = useState([]);+ const [selectedTable, setSelectedTable] = useState(null);+ const [tableStructure, setTableStructure] = useState(null);+ const [history, setHistory] = useState([]);+ const [showHistory, setShowHistory] = useState(false);+ const [sortConfig, setSortConfig] = useState({ column: null, direction: 'asc' });+ const [isAdmin, setIsAdmin] = useState(false);++ useEffect(() => {+ loadTables();+ loadHistory();+ checkAdminStatus();++ // Focus textarea on mount+ if (textareaRef.current) {+ textareaRef.current.focus();+ }+ }, []);++ async function checkAdminStatus() {+ try {+ const user = await api.getCurrentUser();+ setIsAdmin(user.role === 'admin');+ } catch (err) {+ console.error('Failed to check admin status:', err);+ }+ }++ async function loadTables() {+ try {+ let data;+ if (dbType === 'mysql') {+ data = await api.getMySQLTables(database.name);+ } else if (dbType === 'postgresql') {+ data = await api.getPostgreSQLTables(database.name);+ } else if (dbType === 'sqlite') {+ data = await api.getSQLiteTables(database.path);+ }+ setTables(data.tables || []);+ } catch (err) {+ console.error('Failed to load tables:', err);+ }+ }++ function loadHistory() {+ try {+ const stored = localStorage.getItem(HISTORY_KEY);+ if (stored) {+ const allHistory = JSON.parse(stored);+ const dbKey = dbType === 'sqlite' ? database.path : database.name;+ setHistory(allHistory[dbKey] || []);+ }+ } catch (err) {+ console.error('Failed to load query history:', err);+ }+ }++ function saveToHistory(sql) {+ try {+ const stored = localStorage.getItem(HISTORY_KEY);+ const allHistory = stored ? JSON.parse(stored) : {};+ const dbKey = dbType === 'sqlite' ? database.path : database.name;++ const dbHistory = allHistory[dbKey] || [];+ // Remove duplicate if exists+ const filtered = dbHistory.filter(h => h.query !== sql);+ // Add to front+ filtered.unshift({+ query: sql,+ timestamp: new Date().toISOString()+ });+ // Limit size+ allHistory[dbKey] = filtered.slice(0, MAX_HISTORY);++ localStorage.setItem(HISTORY_KEY, JSON.stringify(allHistory));+ setHistory(allHistory[dbKey]);+ } catch (err) {+ console.error('Failed to save query history:', err);+ }+ }++ async function executeQuery() {+ if (!query.trim()) {+ setError('Please enter a query');+ return;+ }++ setLoading(true);+ setError('');+ setResults(null);++ try {+ let result;+ if (dbType === 'mysql') {+ result = await api.executeMySQLQuery(database.name, query, readonly);+ } else if (dbType === 'postgresql') {+ result = await api.executePostgreSQLQuery(database.name, query, readonly);+ } else if (dbType === 'sqlite') {+ result = await api.executeSQLiteQuery(database.path, query, readonly);+ }++ if (result.success) {+ setResults(result);+ saveToHistory(query);+ toast.success(`Query executed in ${result.execution_time}s (${result.row_count} rows)`);+ } else {+ setError(result.error || 'Query execution failed');+ }+ } catch (err) {+ setError(err.message || 'Failed to execute query');+ } finally {+ setLoading(false);+ }+ }++ async function loadTableStructure(table) {+ setSelectedTable(table);+ try {+ let result;+ if (dbType === 'mysql') {+ result = await api.getMySQLTableStructure(database.name, table.name);+ } else if (dbType === 'postgresql') {+ result = await api.getPostgreSQLTableStructure(database.name, table.name);+ } else if (dbType === 'sqlite') {+ result = await api.getSQLiteTableStructure(database.path, table.name);+ }+ if (result.success) {+ setTableStructure(result.columns);+ }+ } catch (err) {+ console.error('Failed to load table structure:', err);+ }+ }++ function insertTableName(tableName) {+ const textarea = textareaRef.current;+ if (!textarea) return;++ const start = textarea.selectionStart;+ const end = textarea.selectionEnd;+ const newQuery = query.substring(0, start) + tableName + query.substring(end);+ setQuery(newQuery);++ // Restore focus and position cursor after table name+ setTimeout(() => {+ textarea.focus();+ textarea.setSelectionRange(start + tableName.length, start + tableName.length);+ }, 0);+ }++ function insertSelectAll(tableName) {+ setQuery(`SELECT * FROM ${tableName} LIMIT 100;`);+ if (textareaRef.current) {+ textareaRef.current.focus();+ }+ }++ function handleKeyDown(e) {+ // Ctrl+Enter or Cmd+Enter to execute+ if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {+ e.preventDefault();+ executeQuery();+ }+ }++ function handleSort(columnIndex) {+ setSortConfig(prev => ({+ column: columnIndex,+ direction: prev.column === columnIndex && prev.direction === 'asc' ? 'desc' : 'asc'+ }));+ }++ function getSortedRows() {+ if (!results?.rows || sortConfig.column === null) {+ return results?.rows || [];+ }++ return [...results.rows].sort((a, b) => {+ const aVal = a[sortConfig.column];+ const bVal = b[sortConfig.column];++ // Handle nulls+ if (aVal === null && bVal === null) return 0;+ if (aVal === null) return 1;+ if (bVal === null) return -1;++ // Try numeric comparison+ const aNum = Number(aVal);+ const bNum = Number(bVal);+ if (!isNaN(aNum) && !isNaN(bNum)) {+ return sortConfig.direction === 'asc' ? aNum - bNum : bNum - aNum;+ }++ // String comparison+ const comparison = String(aVal).localeCompare(String(bVal));+ return sortConfig.direction === 'asc' ? comparison : -comparison;+ });+ }++ function exportToCSV() {+ if (!results?.columns || !results?.rows) return;++ const escape = (val) => {+ if (val === null) return '';+ const str = String(val);+ if (str.includes(',') || str.includes('"') || str.includes('\n')) {+ return `"${str.replace(/"/g, '""')}"`;+ }+ return str;+ };++ const header = results.columns.map(escape).join(',');+ const rows = results.rows.map(row => row.map(escape).join(','));+ const csv = [header, ...rows].join('\n');++ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `query_results_${new Date().toISOString().slice(0, 10)}.csv`;+ a.click();+ URL.revokeObjectURL(url);++ toast.success('Results exported to CSV');+ }++ const dbName = dbType === 'sqlite' ? database.name : database.name;++ return (+ <div className="modal-overlay query-runner-overlay" onClick={onClose}>+ <div className="query-runner-modal" onClick={e => e.stopPropagation()}>+ <div className="query-runner-header">+ <div className="query-runner-title">+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">+ <polyline points="16 18 22 12 16 6"/>+ <polyline points="8 6 2 12 8 18"/>+ </svg>+ <span>Query Runner - {dbName}</span>+ <span className={`db-type-badge ${dbType}`}>+ {dbType === 'mysql' ? 'MySQL' : dbType === 'postgresql' ? 'PostgreSQL' : 'SQLite'}+ </span>+ </div>+ <div className="query-runner-actions">+ {isAdmin && (+ <label className="readonly-toggle">+ <input+ type="checkbox"+ checked={!readonly}+ onChange={(e) => setReadonly(!e.target.checked)}+ />+ <span>Allow write queries</span>+ </label>+ )}+ <button className="btn btn-secondary btn-sm" onClick={() => setShowHistory(!showHistory)}>+ History+ </button>+ <button className="modal-close" onClick={onClose}>×</button>+ </div>+ </div>++ <div className="query-runner-body">+ <div className="query-runner-sidebar">+ <div className="sidebar-section">+ <h4>Tables ({tables.length})</h4>+ <div className="tables-list">+ {tables.map(table => (+ <div+ key={table.name}+ className={`table-item ${selectedTable?.name === table.name ? 'selected' : ''}`}+ onClick={() => loadTableStructure(table)}+ >+ <span className="table-name" title={table.name}>{table.name}</span>+ <span className="table-rows">{table.rows}</span>+ </div>+ ))}+ {tables.length === 0 && (+ <p className="hint">No tables found</p>+ )}+ </div>+ </div>++ {selectedTable && tableStructure && (+ <div className="sidebar-section">+ <h4>+ {selectedTable.name}+ <button+ className="btn-icon"+ title="SELECT * FROM table"+ onClick={() => insertSelectAll(selectedTable.name)}+ >+ <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" strokeWidth="2">+ <polyline points="9 11 12 14 22 4"/>+ <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/>+ </svg>+ </button>+ </h4>+ <div className="columns-list">+ {tableStructure.map(col => (+ <div+ key={col.name}+ className="column-item"+ onClick={() => insertTableName(col.name)}+ title={`${col.type}${col.nullable ? '' : ' NOT NULL'}${col.key === 'PRI' || col.primary_key ? ' PRIMARY KEY' : ''}`}+ >+ <span className="column-name">{col.name}</span>+ <span className="column-type">{col.type}</span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>++ <div className="query-runner-main">+ <div className="query-editor">+ <textarea+ ref={textareaRef}+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder="Enter your SQL query here... (Ctrl+Enter to execute)"+ spellCheck={false}+ />+ <div className="query-actions">+ <div className="query-hints">+ {readonly && (+ <span className="hint">+ <svg viewBox="0 0 24 24" width="14" height="14" 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>+ Readonly mode - only SELECT, SHOW, DESCRIBE allowed+ </span>+ )}+ </div>+ <button+ className="btn btn-primary"+ onClick={executeQuery}+ disabled={loading || !query.trim()}+ >+ {loading ? 'Executing...' : 'Execute (Ctrl+Enter)'}+ </button>+ </div>+ </div>++ {error && (+ <div className="query-error">+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ <line x1="15" y1="9" x2="9" y2="15"/>+ <line x1="9" y1="9" x2="15" y2="15"/>+ </svg>+ {error}+ </div>+ )}++ {results && (+ <div className="query-results">+ <div className="results-header">+ <span className="results-info">+ {results.row_count} row{results.row_count !== 1 ? 's' : ''}+ {results.truncated && ` (truncated from ${results.total_rows})`}+ {' - '}{results.execution_time}s+ </span>+ <button+ className="btn btn-secondary btn-sm"+ onClick={exportToCSV}+ disabled={!results.rows?.length}+ >+ Export CSV+ </button>+ </div>++ {results.columns?.length > 0 ? (+ <div className="results-table-container">+ <table className="results-table">+ <thead>+ <tr>+ {results.columns.map((col, idx) => (+ <th+ key={idx}+ onClick={() => handleSort(idx)}+ className={sortConfig.column === idx ? `sorted-${sortConfig.direction}` : ''}+ >+ {col}+ {sortConfig.column === idx && (+ <span className="sort-indicator">+ {sortConfig.direction === 'asc' ? ' ▲' : ' ▼'}+ </span>+ )}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {getSortedRows().map((row, rowIdx) => (+ <tr key={rowIdx}>+ {row.map((cell, cellIdx) => (+ <td key={cellIdx} className={cell === null ? 'null-value' : ''}>+ {cell === null ? 'NULL' : String(cell)}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <p className="hint">Query executed successfully. No results to display.</p>+ )}+ </div>+ )}+ </div>+ </div>++ {showHistory && (+ <div className="query-history-panel">+ <div className="history-header">+ <h4>Query History</h4>+ <button className="modal-close" onClick={() => setShowHistory(false)}>×</button>+ </div>+ <div className="history-list">+ {history.length === 0 ? (+ <p className="hint">No query history</p>+ ) : (+ history.map((item, idx) => (+ <div+ key={idx}+ className="history-item"+ onClick={() => {+ setQuery(item.query);+ setShowHistory(false);+ if (textareaRef.current) {+ textareaRef.current.focus();+ }+ }}+ >+ <code>{item.query}</code>+ <span className="history-time">+ {new Date(item.timestamp).toLocaleString()}+ </span>+ </div>+ ))+ )}+ </div>+ </div>+ )}+ </div>+ </div>+ );+};++export default QueryRunner;diff --git a/frontend/src/pages/Databases.jsx b/frontend/src/pages/Databases.jsxindex ba5fab94..7306589f 100644--- a/frontend/src/pages/Databases.jsx+++ b/frontend/src/pages/Databases.jsx@@ -1,6 +1,7 @@import React, { useState, useEffect } from 'react';import api from '../services/api';import { useToast } from '../contexts/ToastContext';+import QueryRunner from '../components/QueryRunner';const Databases = () => {const [activeTab, setActiveTab] = useState('mysql');@@ -73,12 +74,19 @@ const Databases = () => {>Backups</button>+ <button+ className={`tab ${activeTab === 'sqlite' ? 'active' : ''}`}+ onClick={() => setActiveTab('sqlite')}+ >+ SQLite+ </button></div><div className="tab-content">{activeTab === 'mysql' && <MySQLTab status={status?.mysql} />}{activeTab === 'postgresql' && <PostgreSQLTab status={status?.postgresql} />}{activeTab === 'backups' && <BackupsTab />}+ {activeTab === 'sqlite' && <SQLiteTab />}</div></div>);@@ -93,6 +101,7 @@ const MySQLTab = ({ status }) => {const [showCreateDbModal, setShowCreateDbModal] = useState(false);const [showCreateUserModal, setShowCreateUserModal] = useState(false);const [selectedDb, setSelectedDb] = useState(null);+ const [queryDb, setQueryDb] = useState(null);useEffect(() => {if (status?.running) {@@ -224,6 +233,12 @@ const MySQLTab = ({ status }) => {</div></div><div className="db-item-actions">+ <button+ className="btn btn-primary btn-sm"+ onClick={() => setQueryDb(db)}+ >+ Query+ </button><buttonclassName="btn btn-secondary btn-sm"onClick={() => setSelectedDb(db)}@@ -307,6 +322,14 @@ const MySQLTab = ({ status }) => {onClose={() => setSelectedDb(null)}/>)}++ {queryDb && (+ <QueryRunner+ database={queryDb}+ dbType="mysql"+ onClose={() => setQueryDb(null)}+ />+ )}</div>);};@@ -320,6 +343,7 @@ const PostgreSQLTab = ({ status }) => {const [showCreateDbModal, setShowCreateDbModal] = useState(false);const [showCreateUserModal, setShowCreateUserModal] = useState(false);const [selectedDb, setSelectedDb] = useState(null);+ const [queryDb, setQueryDb] = useState(null);useEffect(() => {if (status?.running) {@@ -451,6 +475,12 @@ const PostgreSQLTab = ({ status }) => {</div></div><div className="db-item-actions">+ <button+ className="btn btn-primary btn-sm"+ onClick={() => setQueryDb(db)}+ >+ Query+ </button><buttonclassName="btn btn-secondary btn-sm"onClick={() => setSelectedDb(db)}@@ -534,6 +564,14 @@ const PostgreSQLTab = ({ status }) => {onClose={() => setSelectedDb(null)}/>)}++ {queryDb && (+ <QueryRunner+ database={queryDb}+ dbType="postgresql"+ onClose={() => setQueryDb(null)}+ />+ )}</div>);};@@ -1263,6 +1301,155 @@ const TablesModal = ({ database, dbType, onClose }) => {);};+const SQLiteTab = () => {+ const [databases, setDatabases] = useState([]);+ const [loading, setLoading] = useState(true);+ const [queryDb, setQueryDb] = useState(null);+ const [selectedDb, setSelectedDb] = useState(null);++ useEffect(() => {+ loadDatabases();+ }, []);++ async function loadDatabases() {+ setLoading(true);+ try {+ const data = await api.getSQLiteDatabases();+ setDatabases(data.databases || []);+ } catch (err) {+ console.error('Failed to load SQLite databases:', err);+ } finally {+ setLoading(false);+ }+ }++ if (loading) {+ return <div className="loading">Scanning for SQLite databases...</div>;+ }++ return (+ <div>+ <div className="section-header">+ <div className="hint">+ Showing .db, .sqlite, and .sqlite3 files found in /var/www, /home, and /opt+ </div>+ <button className="btn btn-secondary" onClick={loadDatabases}>+ Refresh+ </button>+ </div>++ {databases.length === 0 ? (+ <div className="empty-state">+ <h3>No SQLite databases found</h3>+ <p>No .db, .sqlite, or .sqlite3 files were found in the scanned directories.</p>+ </div>+ ) : (+ <div className="db-list">+ {databases.map(db => (+ <div key={db.path} className="db-item">+ <div className="db-item-info">+ <div className="db-item-icon sqlite">+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <ellipse cx="12" cy="5" rx="9" ry="3"/>+ <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/>+ <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>+ </svg>+ </div>+ <div className="db-item-details">+ <h3>{db.name}</h3>+ <div className="db-item-meta">+ <span className="mono">{db.path}</span>+ <span>{formatBytes(db.size)}</span>+ </div>+ </div>+ </div>+ <div className="db-item-actions">+ <button+ className="btn btn-primary btn-sm"+ onClick={() => setQueryDb(db)}+ >+ Query+ </button>+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => setSelectedDb(db)}+ >+ Tables+ </button>+ </div>+ </div>+ ))}+ </div>+ )}++ {selectedDb && (+ <SQLiteTablesModal+ database={selectedDb}+ onClose={() => setSelectedDb(null)}+ />+ )}++ {queryDb && (+ <QueryRunner+ database={queryDb}+ dbType="sqlite"+ onClose={() => setQueryDb(null)}+ />+ )}+ </div>+ );+};++const SQLiteTablesModal = ({ database, onClose }) => {+ const [tables, setTables] = useState([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ loadTables();+ }, [database]);++ async function loadTables() {+ try {+ const data = await api.getSQLiteTables(database.path);+ setTables(data.tables || []);+ } catch (err) {+ console.error('Failed to load tables:', err);+ } finally {+ setLoading(false);+ }+ }++ return (+ <div className="modal-overlay" onClick={onClose}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Tables in {database.name}</h2>+ <button className="modal-close" onClick={onClose}>×</button>+ </div>+ <div className="modal-body">+ {loading ? (+ <div className="loading">Loading tables...</div>+ ) : tables.length === 0 ? (+ <p className="hint">No tables in this database.</p>+ ) : (+ <div className="tables-list">+ {tables.map(table => (+ <div key={table.name} className="table-item">+ <span className="table-name">{table.name}</span>+ <span className="table-rows">{table.rows.toLocaleString()} rows</span>+ </div>+ ))}+ </div>+ )}+ </div>+ <div className="modal-actions">+ <button className="btn btn-primary" onClick={onClose}>Close</button>+ </div>+ </div>+ </div>+ );+};+function formatBytes(bytes) {if (!bytes || bytes === 0) return '0 B';const k = 1024;diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxindex c1a7d55d..d9412ab3 100644--- a/frontend/src/pages/Settings.jsx+++ b/frontend/src/pages/Settings.jsx@@ -782,22 +782,35 @@ const AppearanceSettings = () => {};const NotificationSettings = () => {- const { isAdmin } = useAuth();+ const { isAdmin, user } = useAuth();const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);const [testing, setTesting] = useState(null);const [message, setMessage] = useState(null);+ const [activeSection, setActiveSection] = useState('personal');const [config, setConfig] = useState({discord: { enabled: false, webhook_url: '', username: 'ServerKit', avatar_url: '', notify_on: ['critical', 'warning'] },slack: { enabled: false, webhook_url: '', channel: '', username: 'ServerKit', icon_emoji: ':robot_face:', notify_on: ['critical', 'warning'] },telegram: { enabled: false, bot_token: '', chat_id: '', notify_on: ['critical', 'warning'] },+ email: { enabled: false, smtp_host: '', smtp_port: 587, smtp_user: '', smtp_password: '', smtp_tls: true, from_email: '', from_name: 'ServerKit', to_emails: [], notify_on: ['critical', 'warning'] },generic_webhook: { enabled: false, url: '', headers: {}, notify_on: ['critical', 'warning'] }});const [expandedChannel, setExpandedChannel] = useState(null);+ const [userPrefs, setUserPrefs] = useState({+ enabled: true,+ channels: ['email'],+ severities: ['critical', 'warning'],+ email: '',+ discord_webhook: '',+ telegram_chat_id: '',+ categories: { system: true, security: true, backups: true, apps: true },+ quiet_hours: { enabled: false, start: '22:00', end: '08:00' }+ });const severityOptions = ['critical', 'warning', 'info', 'success'];useEffect(() => {+ loadUserPrefs();if (isAdmin) loadConfig();}, [isAdmin]);@@ -808,6 +821,7 @@ const NotificationSettings = () => {discord: { ...prev.discord, ...data.discord },slack: { ...prev.slack, ...data.slack },telegram: { ...prev.telegram, ...data.telegram },+ email: { ...prev.email, ...data.email },generic_webhook: { ...prev.generic_webhook, ...data.generic_webhook }}));} catch (err) {@@ -817,6 +831,43 @@ const NotificationSettings = () => {}}+ async function loadUserPrefs() {+ try {+ const data = await api.getUserNotificationPreferences();+ setUserPrefs(prev => ({ ...prev, ...data }));+ } catch (err) {+ console.error('Failed to load user notification preferences:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleSaveUserPrefs() {+ setSaving(true);+ setMessage(null);+ try {+ await api.updateUserNotificationPreferences(userPrefs);+ setMessage({ type: 'success', text: 'Your notification preferences have been saved' });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setSaving(false);+ }+ }++ async function handleTestUserNotification() {+ setTesting('user');+ setMessage(null);+ try {+ const result = await api.testUserNotification();+ setMessage({ type: result.success ? 'success' : 'error', text: result.success ? 'Test notification sent!' : (result.error || 'Test failed') });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setTesting(null);+ }+ }+async function handleSaveChannel(channel) {setSaving(true);setMessage(null);@@ -858,22 +909,211 @@ const NotificationSettings = () => {updateChannelConfig(channel, 'notify_on', updated);}- if (!isAdmin) {- return (- <div className="settings-section">- <div className="section-header">- <h2>Notification Settings</h2>- <p>Configure notification webhooks for alerts</p>- </div>- <div className="alert alert-warning">Admin access required to configure notifications.</div>- </div>- );- }-if (loading) {return <div className="loading">Loading notification settings...</div>;}+ const userPrefsUI = (+ <div className="user-notification-prefs">+ <div className="settings-card">+ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Enable notifications for my account</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={userPrefs.enabled}+ onChange={(e) => setUserPrefs({...userPrefs, enabled: e.target.checked})}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>+ </div>++ <div className="settings-card">+ <h3>Notification Channels</h3>+ <p>Choose how you want to receive notifications</p>+ <div className="channel-toggles">+ {['email', 'discord', 'slack', 'telegram'].map(ch => (+ <label key={ch} className="channel-toggle">+ <input+ type="checkbox"+ checked={userPrefs.channels?.includes(ch)}+ onChange={(e) => {+ const channels = e.target.checked+ ? [...(userPrefs.channels || []), ch]+ : (userPrefs.channels || []).filter(c => c !== ch);+ setUserPrefs({...userPrefs, channels});+ }}+ />+ <span>{ch.charAt(0).toUpperCase() + ch.slice(1)}</span>+ </label>+ ))}+ </div>+ </div>++ {userPrefs.channels?.includes('email') && (+ <div className="settings-card">+ <h3>Email Settings</h3>+ <div className="form-group">+ <label>Notification Email (optional)</label>+ <input+ type="email"+ value={userPrefs.email || ''}+ onChange={(e) => setUserPrefs({...userPrefs, email: e.target.value})}+ placeholder={user?.email || 'Uses your account email'}+ />+ <span className="form-help">Leave empty to use your account email</span>+ </div>+ </div>+ )}++ {userPrefs.channels?.includes('discord') && (+ <div className="settings-card">+ <h3>Personal Discord Webhook</h3>+ <div className="form-group">+ <label>Webhook URL</label>+ <input+ type="text"+ value={userPrefs.discord_webhook || ''}+ onChange={(e) => setUserPrefs({...userPrefs, discord_webhook: e.target.value})}+ placeholder="https://discord.com/api/webhooks/..."+ />+ <span className="form-help">Create a webhook in your personal server or DM channel</span>+ </div>+ </div>+ )}++ {userPrefs.channels?.includes('telegram') && (+ <div className="settings-card">+ <h3>Personal Telegram</h3>+ <div className="form-group">+ <label>Your Chat ID</label>+ <input+ type="text"+ value={userPrefs.telegram_chat_id || ''}+ onChange={(e) => setUserPrefs({...userPrefs, telegram_chat_id: e.target.value})}+ placeholder="Your personal chat ID"+ />+ <span className="form-help">Use @userinfobot to get your personal chat ID</span>+ </div>+ </div>+ )}++ <div className="settings-card">+ <h3>Severity Levels</h3>+ <p>Which alert types do you want to receive?</p>+ <div className="severity-toggles">+ {severityOptions.map(severity => (+ <label key={severity} className={`severity-toggle ${severity}`}>+ <input+ type="checkbox"+ checked={userPrefs.severities?.includes(severity)}+ onChange={(e) => {+ const severities = e.target.checked+ ? [...(userPrefs.severities || []), severity]+ : (userPrefs.severities || []).filter(s => s !== severity);+ setUserPrefs({...userPrefs, severities});+ }}+ />+ <span>{severity.charAt(0).toUpperCase() + severity.slice(1)}</span>+ </label>+ ))}+ </div>+ </div>++ <div className="settings-card">+ <h3>Notification Categories</h3>+ <p>What types of events should trigger notifications?</p>+ <div className="category-toggles">+ {Object.entries({+ system: 'System Alerts (CPU, Memory, Disk)',+ security: 'Security Events',+ backups: 'Backup Status',+ apps: 'Application Events'+ }).map(([key, label]) => (+ <label key={key} className="category-toggle">+ <input+ type="checkbox"+ checked={userPrefs.categories?.[key] !== false}+ onChange={(e) => setUserPrefs({+ ...userPrefs,+ categories: { ...userPrefs.categories, [key]: e.target.checked }+ })}+ />+ <span>{label}</span>+ </label>+ ))}+ </div>+ </div>++ <div className="settings-card">+ <h3>Quiet Hours</h3>+ <p>Pause non-critical notifications during these hours</p>+ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Enable quiet hours</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={userPrefs.quiet_hours?.enabled}+ onChange={(e) => setUserPrefs({+ ...userPrefs,+ quiet_hours: { ...userPrefs.quiet_hours, enabled: e.target.checked }+ })}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>+ {userPrefs.quiet_hours?.enabled && (+ <div className="form-row">+ <div className="form-group">+ <label>Start Time</label>+ <input+ type="time"+ value={userPrefs.quiet_hours?.start || '22:00'}+ onChange={(e) => setUserPrefs({+ ...userPrefs,+ quiet_hours: { ...userPrefs.quiet_hours, start: e.target.value }+ })}+ />+ </div>+ <div className="form-group">+ <label>End Time</label>+ <input+ type="time"+ value={userPrefs.quiet_hours?.end || '08:00'}+ onChange={(e) => setUserPrefs({+ ...userPrefs,+ quiet_hours: { ...userPrefs.quiet_hours, end: e.target.value }+ })}+ />+ </div>+ </div>+ )}+ </div>++ <div className="form-actions">+ <button+ className="btn btn-secondary"+ onClick={handleTestUserNotification}+ disabled={testing === 'user' || !userPrefs.enabled}+ >+ {testing === 'user' ? 'Sending...' : 'Send Test Notification'}+ </button>+ <button+ className="btn btn-primary"+ onClick={handleSaveUserPrefs}+ disabled={saving}+ >+ {saving ? 'Saving...' : 'Save Preferences'}+ </button>+ </div>+ </div>+ );+const channels = [{ id: 'discord', name: 'Discord', icon: (<svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">@@ -890,6 +1130,12 @@ const NotificationSettings = () => {<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>), description: 'Send notifications to Telegram chats via bot API' },+ { id: 'email', name: 'Email', icon: (+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>+ <polyline points="22,6 12,13 2,6"/>+ </svg>+ ), description: 'Send email notifications with HTML templates via SMTP' },{ id: 'generic_webhook', name: 'Generic Webhook', icon: (<svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>@@ -901,8 +1147,8 @@ const NotificationSettings = () => {return (<div className="settings-section"><div className="section-header">- <h2>Notification Webhooks</h2>- <p>Configure notification channels for server alerts</p>+ <h2>Notification Settings</h2>+ <p>Configure how you receive alerts and notifications</p></div>{message && (@@ -911,6 +1157,34 @@ const NotificationSettings = () => {</div>)}+ <div className="notification-tabs">+ <button+ className={`notification-tab ${activeSection === 'personal' ? 'active' : ''}`}+ onClick={() => setActiveSection('personal')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>+ <circle cx="12" cy="7" r="4"/>+ </svg>+ My Preferences+ </button>+ {isAdmin && (+ <button+ className={`notification-tab ${activeSection === 'admin' ? 'active' : ''}`}+ onClick={() => setActiveSection('admin')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="3"/>+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>+ </svg>+ System Webhooks+ </button>+ )}+ </div>++ {activeSection === 'personal' && userPrefsUI}++ {activeSection === 'admin' && isAdmin && (<div className="notification-channels">{channels.map(channel => (<div key={channel.id} className={`notification-channel-card ${config[channel.id]?.enabled ? 'enabled' : ''}`}>@@ -1049,6 +1323,93 @@ const NotificationSettings = () => {</>)}+ {channel.id === 'email' && (+ <>+ <div className="form-row">+ <div className="form-group">+ <label>SMTP Host</label>+ <input+ type="text"+ value={config.email.smtp_host || ''}+ onChange={(e) => updateChannelConfig('email', 'smtp_host', e.target.value)}+ placeholder="smtp.example.com"+ />+ </div>+ <div className="form-group">+ <label>SMTP Port</label>+ <input+ type="number"+ value={config.email.smtp_port || 587}+ onChange={(e) => updateChannelConfig('email', 'smtp_port', parseInt(e.target.value))}+ placeholder="587"+ />+ </div>+ </div>+ <div className="form-row">+ <div className="form-group">+ <label>SMTP Username</label>+ <input+ type="text"+ value={config.email.smtp_user || ''}+ onChange={(e) => updateChannelConfig('email', 'smtp_user', e.target.value)}+ placeholder="[email protected]"+ />+ </div>+ <div className="form-group">+ <label>SMTP Password</label>+ <input+ type="password"+ value={config.email.smtp_password || ''}+ onChange={(e) => updateChannelConfig('email', 'smtp_password', e.target.value)}+ placeholder="••••••••"+ />+ </div>+ </div>+ <div className="form-row">+ <div className="form-group">+ <label>From Email</label>+ <input+ type="email"+ value={config.email.from_email || ''}+ onChange={(e) => updateChannelConfig('email', 'from_email', e.target.value)}+ placeholder="[email protected]"+ />+ </div>+ <div className="form-group">+ <label>From Name</label>+ <input+ type="text"+ value={config.email.from_name || 'ServerKit'}+ onChange={(e) => updateChannelConfig('email', 'from_name', e.target.value)}+ placeholder="ServerKit"+ />+ </div>+ </div>+ <div className="form-group">+ <label>Recipient Emails (comma-separated)</label>+ <input+ type="text"+ value={(config.email.to_emails || []).join(', ')}+ onChange={(e) => updateChannelConfig('email', 'to_emails', e.target.value.split(',').map(s => s.trim()).filter(Boolean))}+ placeholder="[email protected], [email protected]"+ />+ </div>+ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Use TLS</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={config.email.smtp_tls !== false}+ onChange={(e) => updateChannelConfig('email', 'smtp_tls', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>+ </>+ )}+{channel.id === 'generic_webhook' && (<div className="form-group"><label>Webhook URL</label>@@ -1099,6 +1460,7 @@ const NotificationSettings = () => {</div>))}</div>+ )}</div>);};diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 7f9388a3..3c5fefaa 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -960,6 +960,48 @@ class ApiService {return this.request(`/databases/generate-password?length=${length}`);}+ // Query Execution+ async executeMySQLQuery(database, query, readonly = true) {+ return this.request(`/databases/mysql/${database}/query`, {+ method: 'POST',+ body: { query, readonly }+ });+ }++ async executePostgreSQLQuery(database, query, readonly = true) {+ return this.request(`/databases/postgresql/${database}/query`, {+ method: 'POST',+ body: { query, readonly }+ });+ }++ async executeSQLiteQuery(path, query, readonly = true) {+ return this.request('/databases/sqlite/query', {+ method: 'POST',+ body: { path, query, readonly }+ });+ }++ async getMySQLTableStructure(database, table) {+ return this.request(`/databases/mysql/${database}/tables/${table}/structure`);+ }++ async getPostgreSQLTableStructure(database, table) {+ return this.request(`/databases/postgresql/${database}/tables/${table}/structure`);+ }++ async getSQLiteTableStructure(path, table) {+ return this.request(`/databases/sqlite/tables/${table}/structure?path=${encodeURIComponent(path)}`);+ }++ async getSQLiteDatabases() {+ return this.request('/databases/sqlite');+ }++ async getSQLiteTables(path) {+ return this.request(`/databases/sqlite/tables?path=${encodeURIComponent(path)}`);+ }+// ========================================// Monitoring & Alerts endpoints// ========================================@@ -1655,6 +1697,24 @@ class ApiService {});}+ // User notification preferences+ async getUserNotificationPreferences() {+ return this.request('/notifications/preferences');+ }++ async updateUserNotificationPreferences(preferences) {+ return this.request('/notifications/preferences', {+ method: 'PUT',+ body: preferences+ });+ }++ async testUserNotification() {+ return this.request('/notifications/preferences/test', {+ method: 'POST'+ });+ }+// ========================================// Security (ClamAV, File Integrity) endpoints// ========================================diff --git a/frontend/src/styles/components/_notifications.less b/frontend/src/styles/components/_notifications.lessindex 645ffa16..9362fed9 100644--- a/frontend/src/styles/components/_notifications.less+++ b/frontend/src/styles/components/_notifications.less@@ -2,6 +2,100 @@// NOTIFICATION SETTINGS STYLES// ============================================+// Notification Tabs+.notification-tabs {+ display: flex;+ gap: @space-2;+ margin-bottom: @space-6;+ padding-bottom: @space-4;+ border-bottom: 1px solid @border-subtle;+}++.notification-tab {+ display: flex;+ align-items: center;+ gap: @space-2;+ padding: @space-3 @space-4;+ background: transparent;+ border: 1px solid @border-subtle;+ border-radius: @radius-md;+ color: @text-secondary;+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ cursor: pointer;+ transition: all @transition-fast;++ svg {+ stroke-width: 2;+ }++ &:hover {+ background: @bg-hover;+ border-color: @border-default;+ color: @text-primary;+ }++ &.active {+ background: @accent-glow;+ border-color: @accent-primary;+ color: @accent-primary;++ svg {+ stroke: @accent-primary;+ }+ }+}++// User Notification Preferences+.user-notification-prefs {+ display: flex;+ flex-direction: column;+ gap: @space-4;+}++.channel-toggles,+.category-toggles {+ display: flex;+ flex-wrap: wrap;+ gap: @space-3;+}++.channel-toggle,+.category-toggle {+ display: flex;+ align-items: center;+ gap: @space-2;+ padding: @space-2 @space-3;+ background: @bg-card;+ border: 1px solid @border-subtle;+ border-radius: @radius-md;+ cursor: pointer;+ transition: all @transition-fast;++ input[type="checkbox"] {+ accent-color: @accent-primary;+ }++ span {+ font-size: @font-size-sm;+ color: @text-secondary;+ }++ &:hover {+ background: @bg-hover;+ border-color: @border-default;+ }++ &:has(input:checked) {+ background: @accent-glow;+ border-color: fade(@accent-primary, 40%);++ span {+ color: @text-primary;+ }+ }+}+.notification-channels {display: flex;flex-direction: column;diff --git a/frontend/src/styles/components/_query-runner.less b/frontend/src/styles/components/_query-runner.lessnew file mode 100644index 00000000..85619f19--- /dev/null+++ b/frontend/src/styles/components/_query-runner.less@@ -0,0 +1,483 @@+// ============================================+// QUERY RUNNER COMPONENT STYLES+// ============================================++// Overlay - full screen modal+.query-runner-overlay {+ &.modal-overlay {+ padding: 0;+ background: rgba(0, 0, 0, 0.8);+ }+}++// Main modal container+.query-runner-modal {+ width: 100%;+ height: 100%;+ max-width: 100%;+ max-height: 100%;+ display: flex;+ flex-direction: column;+ background: @bg-body;+ border-radius: 0;+ overflow: hidden;+}++// Header+.query-runner-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @space-3 @space-4;+ background: @bg-sidebar;+ border-bottom: 1px solid @border-subtle;+ flex-shrink: 0;+}++.query-runner-title {+ display: flex;+ align-items: center;+ gap: @space-3;+ font-size: @font-size-md;+ font-weight: @font-weight-semibold;+ color: @text-primary;++ svg {+ color: @accent-primary;+ }++ .db-type-badge {+ font-size: @font-size-xs;+ padding: @space-1 @space-2;+ border-radius: @radius-sm;+ font-weight: @font-weight-medium;++ &.mysql {+ background: fade(@color-mysql, 15%);+ color: @color-mysql;+ }++ &.postgresql {+ background: fade(@color-postgresql, 15%);+ color: @color-postgresql-secondary;+ }++ &.sqlite {+ background: fade(@accent-primary, 15%);+ color: @accent-primary;+ }+ }+}++.query-runner-actions {+ display: flex;+ align-items: center;+ gap: @space-3;++ .readonly-toggle {+ display: flex;+ align-items: center;+ gap: @space-2;+ font-size: @font-size-sm;+ color: @text-secondary;+ cursor: pointer;++ input[type="checkbox"] {+ accent-color: @warning;+ }+ }++ .modal-close {+ width: 32px;+ height: 32px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: none;+ color: @text-secondary;+ font-size: 24px;+ cursor: pointer;+ border-radius: @radius-md;+ transition: all @transition-fast;++ &:hover {+ background: @bg-hover;+ color: @text-primary;+ }+ }+}++// Body layout+.query-runner-body {+ flex: 1;+ display: flex;+ overflow: hidden;+}++// Sidebar+.query-runner-sidebar {+ width: 260px;+ flex-shrink: 0;+ background: @bg-sidebar;+ border-right: 1px solid @border-subtle;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++.sidebar-section {+ display: flex;+ flex-direction: column;+ overflow: hidden;++ &:first-child {+ flex: 1;+ min-height: 150px;+ }++ &:last-child {+ border-top: 1px solid @border-subtle;+ max-height: 40%;+ }++ h4 {+ padding: @space-3 @space-4;+ margin: 0;+ font-size: @font-size-sm;+ font-weight: @font-weight-semibold;+ color: @text-secondary;+ background: @bg-card;+ border-bottom: 1px solid @border-subtle;+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-shrink: 0;++ .btn-icon {+ width: 24px;+ height: 24px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: none;+ color: @text-secondary;+ cursor: pointer;+ border-radius: @radius-sm;+ transition: all @transition-fast;++ &:hover {+ background: @bg-hover;+ color: @accent-primary;+ }+ }+ }+}++.tables-list,+.columns-list {+ flex: 1;+ overflow-y: auto;+ padding: @space-2;+}++.table-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: @space-2 @space-3;+ border-radius: @radius-md;+ cursor: pointer;+ transition: all @transition-fast;++ &:hover {+ background: @bg-hover;+ }++ &.selected {+ background: @accent-glow;+ border: 1px solid fade(@accent-primary, 30%);+ }++ .table-name {+ font-size: @font-size-sm;+ color: @text-primary;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .table-rows {+ font-size: @font-size-xs;+ color: @text-tertiary;+ flex-shrink: 0;+ margin-left: @space-2;+ }+}++.column-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: @space-1 @space-3;+ border-radius: @radius-sm;+ cursor: pointer;+ transition: all @transition-fast;++ &:hover {+ background: @bg-hover;+ }++ .column-name {+ font-size: @font-size-sm;+ font-family: @font-mono;+ color: @text-primary;+ }++ .column-type {+ font-size: @font-size-xs;+ font-family: @font-mono;+ color: @text-tertiary;+ }+}++// Main query area+.query-runner-main {+ flex: 1;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ background: @bg-body;+}++// Query editor+.query-editor {+ flex-shrink: 0;+ padding: @space-4;+ border-bottom: 1px solid @border-subtle;++ textarea {+ width: 100%;+ height: 150px;+ padding: @space-3;+ font-family: @font-mono;+ font-size: @font-size-sm;+ line-height: @line-height-relaxed;+ background: @bg-card;+ border: 1px solid @border-subtle;+ border-radius: @radius-md;+ color: @text-primary;+ resize: vertical;+ transition: border-color @transition-fast;++ &:focus {+ outline: none;+ border-color: @accent-primary;+ box-shadow: 0 0 0 3px @accent-glow;+ }++ &::placeholder {+ color: @text-tertiary;+ }+ }+}++.query-actions {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-top: @space-3;+}++.query-hints {+ display: flex;+ align-items: center;+ gap: @space-2;++ .hint {+ display: flex;+ align-items: center;+ gap: @space-1;+ font-size: @font-size-sm;+ color: @text-tertiary;++ svg {+ color: @warning;+ }+ }+}++// Error display+.query-error {+ display: flex;+ align-items: flex-start;+ gap: @space-2;+ padding: @space-3 @space-4;+ background: @danger-bg;+ border-bottom: 1px solid @danger-border;+ color: @danger;+ font-size: @font-size-sm;++ svg {+ flex-shrink: 0;+ margin-top: 2px;+ }+}++// Results area+.query-results {+ flex: 1;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}++.results-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @space-2 @space-4;+ background: @bg-card;+ border-bottom: 1px solid @border-subtle;+ flex-shrink: 0;++ .results-info {+ font-size: @font-size-sm;+ color: @text-secondary;+ }+}++// Results table+.results-table-container {+ flex: 1;+ overflow: auto;+}++.results-table {+ width: 100%;+ border-collapse: collapse;+ font-size: @font-size-sm;++ th, td {+ padding: @space-2 @space-3;+ text-align: left;+ border-bottom: 1px solid @border-subtle;+ white-space: nowrap;+ max-width: 300px;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ th {+ position: sticky;+ top: 0;+ background: @bg-card;+ font-weight: @font-weight-medium;+ color: @text-secondary;+ cursor: pointer;+ user-select: none;+ transition: background @transition-fast;++ &:hover {+ background: @bg-hover;+ }++ &.sorted-asc,+ &.sorted-desc {+ color: @accent-primary;+ }++ .sort-indicator {+ font-size: @font-size-xs;+ margin-left: @space-1;+ }+ }++ td {+ font-family: @font-mono;+ color: @text-primary;++ &.null-value {+ color: @text-tertiary;+ font-style: italic;+ }+ }++ tbody tr {+ &:hover {+ background: fade(@bg-hover, 50%);+ }+ }+}++// History panel+.query-history-panel {+ position: absolute;+ top: 60px;+ right: 0;+ width: 400px;+ max-height: calc(100% - 80px);+ background: @bg-card;+ border: 1px solid @border-subtle;+ border-radius: @radius-lg;+ box-shadow: @shadow-lg;+ display: flex;+ flex-direction: column;+ z-index: @z-modal;+ margin: @space-4;+ overflow: hidden;+}++.history-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @space-3 @space-4;+ border-bottom: 1px solid @border-subtle;++ h4 {+ margin: 0;+ font-size: @font-size-base;+ font-weight: @font-weight-semibold;+ color: @text-primary;+ }+}++.history-list {+ flex: 1;+ overflow-y: auto;+ padding: @space-2;+}++.history-item {+ padding: @space-3;+ border-radius: @radius-md;+ cursor: pointer;+ transition: all @transition-fast;++ &:hover {+ background: @bg-hover;+ }++ code {+ display: block;+ font-family: @font-mono;+ font-size: @font-size-sm;+ color: @text-primary;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ margin-bottom: @space-1;+ }++ .history-time {+ font-size: @font-size-xs;+ color: @text-tertiary;+ }+}++// SQLite icon color+.db-item-icon.sqlite {+ color: @accent-primary;+}diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex 2e9e78c9..9726d4aa 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -43,6 +43,7 @@@import 'components/_env-vars';@import 'components/_two-factor';@import 'components/_notifications';+@import 'components/_query-runner';// --------------------------------------------// 5. PAGE-SPECIFIC STYLES