Skip to content

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.

Add notification webhooks support (Discord, Slack, etc.)

Juan Denis7833d78fc557
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index bda381ff..0df6c97e 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -97,6 +97,10 @@ def create_app(config_name=None):
from app.api.monitoring import monitoring_bp
app.register_blueprint(monitoring_bp, url_prefix='/api/v1/monitoring')
+ # Register blueprints - Notifications
+ from app.api.notifications import notifications_bp
+ app.register_blueprint(notifications_bp, url_prefix='/api/v1/notifications')
+
# Register blueprints - Backups
from app.api.backups import backups_bp
app.register_blueprint(backups_bp, url_prefix='/api/v1/backups')
diff --git a/backend/app/api/notifications.py b/backend/app/api/notifications.py
new file mode 100644
index 00000000..6d484c01
--- /dev/null
+++ b/backend/app/api/notifications.py
@@ -0,0 +1,145 @@
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required, get_jwt_identity
+from app.models import User
+from app.services.notification_service import NotificationService
+
+notifications_bp = Blueprint('notifications', __name__)
+
+
+def admin_required(fn):
+ """Decorator to require admin role."""
+ from functools import wraps
+
+ @wraps(fn)
+ def wrapper(*args, **kwargs):
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ if not user or user.role != 'admin':
+ return jsonify({'error': 'Admin access required'}), 403
+ return fn(*args, **kwargs)
+ return wrapper
+
+
+@notifications_bp.route('/status', methods=['GET'])
+@jwt_required()
+def get_status():
+ """Get notification channels status."""
+ status = NotificationService.get_status()
+ return jsonify(status), 200
+
+
+@notifications_bp.route('/config', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_config():
+ """Get notification configuration."""
+ config = NotificationService.get_config()
+
+ # Mask sensitive data
+ if 'discord' in config and config['discord'].get('webhook_url'):
+ url = config['discord']['webhook_url']
+ config['discord']['webhook_url'] = url[:30] + '...' if len(url) > 30 else url
+
+ if 'slack' in config and config['slack'].get('webhook_url'):
+ url = config['slack']['webhook_url']
+ config['slack']['webhook_url'] = url[:30] + '...' if len(url) > 30 else url
+
+ if 'telegram' in config and config['telegram'].get('bot_token'):
+ config['telegram']['bot_token'] = '***'
+
+ if 'generic_webhook' in config and config['generic_webhook'].get('url'):
+ url = config['generic_webhook']['url']
+ config['generic_webhook']['url'] = url[:30] + '...' if len(url) > 30 else url
+
+ return jsonify(config), 200
+
+
+@notifications_bp.route('/config/<channel>', methods=['PUT'])
+@jwt_required()
+@admin_required
+def update_channel_config(channel):
+ """Update configuration for a specific notification channel."""
+ data = request.get_json()
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ valid_channels = ['discord', 'slack', 'telegram', 'generic_webhook']
+ if channel not in valid_channels:
+ return jsonify({'error': f'Invalid channel. Valid options: {valid_channels}'}), 400
+
+ # Get current config to preserve masked values
+ current_config = NotificationService.get_config()
+
+ # Handle masked sensitive values
+ if channel == 'discord':
+ if data.get('webhook_url') and '...' in data.get('webhook_url', ''):
+ data['webhook_url'] = current_config.get('discord', {}).get('webhook_url', '')
+
+ elif channel == 'slack':
+ if data.get('webhook_url') and '...' in data.get('webhook_url', ''):
+ data['webhook_url'] = current_config.get('slack', {}).get('webhook_url', '')
+
+ elif channel == 'telegram':
+ if data.get('bot_token') == '***':
+ data['bot_token'] = current_config.get('telegram', {}).get('bot_token', '')
+
+ elif channel == 'generic_webhook':
+ if data.get('url') and '...' in data.get('url', ''):
+ data['url'] = current_config.get('generic_webhook', {}).get('url', '')
+
+ result = NotificationService.update_channel_config(channel, data)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@notifications_bp.route('/test/<channel>', methods=['POST'])
+@jwt_required()
+@admin_required
+def test_channel(channel):
+ """Send a test notification to a specific channel."""
+ valid_channels = ['discord', 'slack', 'telegram', 'generic_webhook']
+ if channel not in valid_channels:
+ return jsonify({'error': f'Invalid channel. Valid options: {valid_channels}'}), 400
+
+ result = NotificationService.send_test(channel)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@notifications_bp.route('/test', methods=['POST'])
+@jwt_required()
+@admin_required
+def test_all_channels():
+ """Send a test notification to all enabled channels."""
+ test_alerts = [{
+ 'type': 'test',
+ 'severity': 'test',
+ 'message': 'This is a test notification from ServerKit. All channels are working correctly!',
+ 'value': 'N/A',
+ 'threshold': 'N/A'
+ }]
+
+ # Temporarily enable test severity for all channels
+ config = NotificationService.get_config()
+ results = {}
+
+ for channel in ['discord', 'slack', 'telegram', 'generic_webhook']:
+ channel_config = config.get(channel, {})
+ if channel_config.get('enabled'):
+ test_config = {**channel_config, 'notify_on': ['test']}
+
+ if channel == 'discord':
+ results[channel] = NotificationService.send_discord(test_alerts, test_config)
+ elif channel == 'slack':
+ results[channel] = NotificationService.send_slack(test_alerts, test_config)
+ elif channel == 'telegram':
+ results[channel] = NotificationService.send_telegram(test_alerts, test_config)
+ elif channel == 'generic_webhook':
+ results[channel] = NotificationService.send_generic_webhook(test_alerts, test_config)
+
+ if not results:
+ return jsonify({'success': False, 'error': 'No channels enabled'}), 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 207 # 207 Multi-Status for partial success
diff --git a/backend/app/services/monitoring_service.py b/backend/app/services/monitoring_service.py
index b08b9cbd..207841ea 100644
--- a/backend/app/services/monitoring_service.py
+++ b/backend/app/services/monitoring_service.py
@@ -10,6 +10,8 @@ from pathlib import Path
import threading
import time
+from .notification_service import NotificationService
+
class MonitoringService:
"""Service for system monitoring and alerts."""
@@ -266,13 +268,17 @@ class MonitoringService:
# Log alerts
cls.log_alert(alerts_to_send)
- # Send notifications
+ # Send email notifications
if config.get('email', {}).get('enabled'):
cls.send_email_alert(alerts_to_send)
+ # Send legacy webhook (for backwards compatibility)
if config.get('webhook', {}).get('enabled'):
cls.send_webhook_alert(alerts_to_send)
+ # Send to all configured notification channels (Discord, Slack, Telegram, etc.)
+ NotificationService.send_all(alerts_to_send)
+
@classmethod
def log_alert(cls, alerts: List[Dict]) -> None:
"""Log alerts to file."""
@@ -374,6 +380,7 @@ class MonitoringService:
config = cls.get_config()
metrics = cls.get_current_metrics()
alerts = cls.check_thresholds()
+ notification_status = NotificationService.get_status()
return {
'enabled': config.get('enabled', False),
@@ -381,6 +388,7 @@ class MonitoringService:
'check_interval': config.get('check_interval', 60),
'email_enabled': config.get('email', {}).get('enabled', False),
'webhook_enabled': config.get('webhook', {}).get('enabled', False),
+ 'notifications': notification_status,
'current_metrics': metrics,
'active_alerts': alerts
}
diff --git a/backend/app/services/notification_service.py b/backend/app/services/notification_service.py
new file mode 100644
index 00000000..bf05c3c6
--- /dev/null
+++ b/backend/app/services/notification_service.py
@@ -0,0 +1,526 @@
+"""
+Notification Service
+
+Handles sending notifications to various channels:
+- Discord webhooks
+- Slack webhooks
+- Telegram bots
+- Generic webhooks
+- Email (via existing SMTP config)
+"""
+
+import os
+import json
+import requests
+from datetime import datetime
+from typing import Dict, List, Optional
+from pathlib import Path
+
+
+class NotificationService:
+ """Service for sending notifications to various channels."""
+
+ CONFIG_DIR = '/etc/serverkit'
+ NOTIFICATIONS_CONFIG = os.path.join(CONFIG_DIR, 'notifications.json')
+
+ # Severity colors (hex for Discord, named for Slack)
+ SEVERITY_COLORS = {
+ 'critical': {'hex': 0xFF0000, 'slack': 'danger', 'emoji': 'πŸ”΄'},
+ 'warning': {'hex': 0xFFA500, 'slack': 'warning', 'emoji': '🟠'},
+ 'info': {'hex': 0x00BFFF, 'slack': '#00BFFF', 'emoji': 'πŸ”΅'},
+ 'success': {'hex': 0x00FF00, 'slack': 'good', 'emoji': '🟒'},
+ 'test': {'hex': 0x808080, 'slack': '#808080', 'emoji': 'βšͺ'}
+ }
+
+ @classmethod
+ def get_config(cls) -> Dict:
+ """Get notification configuration."""
+ if os.path.exists(cls.NOTIFICATIONS_CONFIG):
+ try:
+ with open(cls.NOTIFICATIONS_CONFIG, 'r') as f:
+ return json.load(f)
+ except Exception:
+ pass
+
+ return {
+ 'discord': {
+ 'enabled': False,
+ 'webhook_url': '',
+ 'username': 'ServerKit',
+ 'avatar_url': '',
+ 'notify_on': ['critical', 'warning']
+ },
+ 'slack': {
+ 'enabled': False,
+ 'webhook_url': '',
+ 'channel': '', # Optional override
+ 'username': 'ServerKit',
+ 'icon_emoji': ':robot_face:',
+ 'notify_on': ['critical', 'warning']
+ },
+ 'telegram': {
+ 'enabled': False,
+ 'bot_token': '',
+ 'chat_id': '',
+ 'notify_on': ['critical', 'warning']
+ },
+ 'generic_webhook': {
+ 'enabled': False,
+ 'url': '',
+ 'headers': {},
+ 'notify_on': ['critical', 'warning']
+ }
+ }
+
+ @classmethod
+ def save_config(cls, config: Dict) -> Dict:
+ """Save notification configuration."""
+ try:
+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)
+ with open(cls.NOTIFICATIONS_CONFIG, 'w') as f:
+ json.dump(config, f, indent=2)
+ return {'success': True, 'message': 'Configuration saved'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def update_channel_config(cls, channel: str, settings: Dict) -> Dict:
+ """Update configuration for a specific channel."""
+ config = cls.get_config()
+
+ if channel not in config:
+ return {'success': False, 'error': f'Unknown channel: {channel}'}
+
+ # Merge settings
+ config[channel] = {**config[channel], **settings}
+
+ return cls.save_config(config)
+
+ @classmethod
+ def get_hostname(cls) -> str:
+ """Get the server hostname."""
+ try:
+ if hasattr(os, 'uname'):
+ return os.uname().nodename
+ import socket
+ return socket.gethostname()
+ except Exception:
+ return 'unknown'
+
+ # ==========================================
+ # DISCORD
+ # ==========================================
+ @classmethod
+ def send_discord(cls, alerts: List[Dict], config: Dict = None) -> Dict:
+ """
+ Send notification to Discord webhook.
+
+ Discord webhook format uses embeds for rich formatting.
+ """
+ if config is None:
+ config = cls.get_config().get('discord', {})
+
+ if not config.get('enabled') or not config.get('webhook_url'):
+ return {'success': False, 'error': 'Discord not configured'}
+
+ webhook_url = config['webhook_url']
+
+ # 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:
+ # Build embeds for each alert
+ embeds = []
+ for alert in alerts[:10]: # Discord limit: 10 embeds per message
+ severity = alert.get('severity', 'info')
+ color_info = cls.SEVERITY_COLORS.get(severity, cls.SEVERITY_COLORS['info'])
+
+ embed = {
+ 'title': f"{color_info['emoji']} {severity.upper()}: {alert.get('type', 'Alert').upper()}",
+ 'description': alert.get('message', 'No message'),
+ 'color': color_info['hex'],
+ 'timestamp': datetime.utcnow().isoformat() + 'Z',
+ 'footer': {
+ 'text': f"ServerKit β€’ {cls.get_hostname()}"
+ }
+ }
+
+ # Add fields if available
+ fields = []
+ if 'value' in alert:
+ fields.append({
+ 'name': 'Current Value',
+ 'value': str(alert['value']),
+ 'inline': True
+ })
+ if 'threshold' in alert:
+ fields.append({
+ 'name': 'Threshold',
+ 'value': str(alert['threshold']),
+ 'inline': True
+ })
+
+ if fields:
+ embed['fields'] = fields
+
+ embeds.append(embed)
+
+ payload = {
+ 'username': config.get('username', 'ServerKit'),
+ 'embeds': embeds
+ }
+
+ if config.get('avatar_url'):
+ payload['avatar_url'] = config['avatar_url']
+
+ response = requests.post(
+ webhook_url,
+ json=payload,
+ timeout=10
+ )
+
+ if response.status_code in [200, 204]:
+ return {'success': True, 'message': 'Discord notification sent'}
+
+ return {
+ 'success': False,
+ 'error': f'Discord returned {response.status_code}: {response.text[:200]}'
+ }
+
+ except requests.exceptions.Timeout:
+ return {'success': False, 'error': 'Discord webhook timeout'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # ==========================================
+ # SLACK
+ # ==========================================
+ @classmethod
+ def send_slack(cls, alerts: List[Dict], config: Dict = None) -> Dict:
+ """
+ Send notification to Slack webhook.
+
+ Slack uses Block Kit for rich formatting.
+ """
+ if config is None:
+ config = cls.get_config().get('slack', {})
+
+ if not config.get('enabled') or not config.get('webhook_url'):
+ return {'success': False, 'error': 'Slack not configured'}
+
+ webhook_url = config['webhook_url']
+
+ # 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:
+ # Build attachments for each alert
+ attachments = []
+ for alert in alerts[:20]: # Slack limit
+ severity = alert.get('severity', 'info')
+ color_info = cls.SEVERITY_COLORS.get(severity, cls.SEVERITY_COLORS['info'])
+
+ attachment = {
+ 'color': color_info['slack'],
+ 'blocks': [
+ {
+ 'type': 'section',
+ 'text': {
+ 'type': 'mrkdwn',
+ 'text': f"*{color_info['emoji']} {severity.upper()}: {alert.get('type', 'Alert').upper()}*\n{alert.get('message', 'No message')}"
+ }
+ }
+ ]
+ }
+
+ # Add fields if available
+ fields = []
+ if 'value' in alert:
+ fields.append({
+ 'type': 'mrkdwn',
+ 'text': f"*Current:* {alert['value']}"
+ })
+ if 'threshold' in alert:
+ fields.append({
+ 'type': 'mrkdwn',
+ 'text': f"*Threshold:* {alert['threshold']}"
+ })
+
+ if fields:
+ attachment['blocks'].append({
+ 'type': 'section',
+ 'fields': fields
+ })
+
+ # Add timestamp
+ attachment['blocks'].append({
+ 'type': 'context',
+ 'elements': [
+ {
+ 'type': 'mrkdwn',
+ 'text': f"ServerKit β€’ {cls.get_hostname()} β€’ <!date^{int(datetime.now().timestamp())}^{{date_short}} {{time}}|{datetime.now().isoformat()}>"
+ }
+ ]
+ })
+
+ attachments.append(attachment)
+
+ payload = {
+ 'username': config.get('username', 'ServerKit'),
+ 'icon_emoji': config.get('icon_emoji', ':robot_face:'),
+ 'attachments': attachments
+ }
+
+ if config.get('channel'):
+ payload['channel'] = config['channel']
+
+ response = requests.post(
+ webhook_url,
+ json=payload,
+ timeout=10
+ )
+
+ if response.status_code == 200 and response.text == 'ok':
+ return {'success': True, 'message': 'Slack notification sent'}
+
+ return {
+ 'success': False,
+ 'error': f'Slack returned: {response.text[:200]}'
+ }
+
+ except requests.exceptions.Timeout:
+ return {'success': False, 'error': 'Slack webhook timeout'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # ==========================================
+ # TELEGRAM
+ # ==========================================
+ @classmethod
+ def send_telegram(cls, alerts: List[Dict], config: Dict = None) -> Dict:
+ """
+ Send notification to Telegram bot.
+
+ Uses Telegram Bot API with HTML formatting.
+ """
+ if config is None:
+ config = cls.get_config().get('telegram', {})
+
+ if not config.get('enabled') or not config.get('bot_token') or not config.get('chat_id'):
+ return {'success': False, 'error': 'Telegram not configured'}
+
+ bot_token = config['bot_token']
+ chat_id = config['chat_id']
+
+ # 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:
+ # Build message
+ lines = [f"<b>πŸ”” ServerKit Alert</b>", f"<i>Host: {cls.get_hostname()}</i>", ""]
+
+ for alert in alerts:
+ severity = alert.get('severity', 'info')
+ color_info = cls.SEVERITY_COLORS.get(severity, cls.SEVERITY_COLORS['info'])
+
+ lines.append(f"{color_info['emoji']} <b>{severity.upper()}: {alert.get('type', 'Alert').upper()}</b>")
+ lines.append(alert.get('message', 'No message'))
+
+ if 'value' in alert or 'threshold' in alert:
+ details = []
+ if 'value' in alert:
+ details.append(f"Current: {alert['value']}")
+ if 'threshold' in alert:
+ details.append(f"Threshold: {alert['threshold']}")
+ lines.append(f"<code>{' | '.join(details)}</code>")
+
+ lines.append("")
+
+ lines.append(f"<i>{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</i>")
+
+ message = "\n".join(lines)
+
+ url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
+ payload = {
+ 'chat_id': chat_id,
+ 'text': message,
+ 'parse_mode': 'HTML',
+ 'disable_web_page_preview': True
+ }
+
+ response = requests.post(url, json=payload, timeout=10)
+ result = response.json()
+
+ if result.get('ok'):
+ return {'success': True, 'message': 'Telegram notification sent'}
+
+ return {
+ 'success': False,
+ 'error': result.get('description', 'Unknown error')
+ }
+
+ except requests.exceptions.Timeout:
+ return {'success': False, 'error': 'Telegram API timeout'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # ==========================================
+ # GENERIC WEBHOOK
+ # ==========================================
+ @classmethod
+ def send_generic_webhook(cls, alerts: List[Dict], config: Dict = None) -> Dict:
+ """
+ Send notification to a generic webhook URL.
+
+ Sends a JSON payload with alert data.
+ """
+ if config is None:
+ config = cls.get_config().get('generic_webhook', {})
+
+ if not config.get('enabled') or not config.get('url'):
+ return {'success': False, 'error': 'Generic webhook not configured'}
+
+ webhook_url = config['url']
+
+ # 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:
+ payload = {
+ 'source': 'serverkit',
+ 'hostname': cls.get_hostname(),
+ 'timestamp': datetime.utcnow().isoformat() + 'Z',
+ 'alerts': alerts
+ }
+
+ headers = {'Content-Type': 'application/json'}
+ headers.update(config.get('headers', {}))
+
+ response = requests.post(
+ webhook_url,
+ json=payload,
+ headers=headers,
+ timeout=10
+ )
+
+ if response.ok:
+ return {'success': True, 'message': 'Webhook notification sent'}
+
+ return {
+ 'success': False,
+ 'error': f'Webhook returned {response.status_code}'
+ }
+
+ except requests.exceptions.Timeout:
+ return {'success': False, 'error': 'Webhook timeout'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # ==========================================
+ # SEND TO ALL CONFIGURED CHANNELS
+ # ==========================================
+ @classmethod
+ def send_all(cls, alerts: List[Dict]) -> Dict:
+ """
+ Send alerts to all configured notification channels.
+
+ Returns results for each channel.
+ """
+ config = cls.get_config()
+ results = {}
+
+ if config.get('discord', {}).get('enabled'):
+ results['discord'] = cls.send_discord(alerts, config['discord'])
+
+ if config.get('slack', {}).get('enabled'):
+ results['slack'] = cls.send_slack(alerts, config['slack'])
+
+ if config.get('telegram', {}).get('enabled'):
+ results['telegram'] = cls.send_telegram(alerts, config['telegram'])
+
+ if config.get('generic_webhook', {}).get('enabled'):
+ results['generic_webhook'] = cls.send_generic_webhook(alerts, config['generic_webhook'])
+
+ return {
+ 'success': all(r.get('success', False) for r in results.values()) if results else True,
+ 'results': results
+ }
+
+ # ==========================================
+ # TEST NOTIFICATIONS
+ # ==========================================
+ @classmethod
+ def send_test(cls, channel: str) -> Dict:
+ """Send a test notification to a specific channel."""
+ test_alerts = [{
+ 'type': 'test',
+ 'severity': 'test',
+ 'message': 'This is a test notification from ServerKit. If you received this, your notifications are working correctly!',
+ 'value': 'N/A',
+ 'threshold': 'N/A'
+ }]
+
+ # For tests, include all severities temporarily
+ config = cls.get_config()
+
+ if channel == 'discord':
+ test_config = {**config.get('discord', {}), 'notify_on': ['test']}
+ return cls.send_discord(test_alerts, test_config)
+ elif channel == 'slack':
+ test_config = {**config.get('slack', {}), 'notify_on': ['test']}
+ return cls.send_slack(test_alerts, test_config)
+ elif channel == 'telegram':
+ test_config = {**config.get('telegram', {}), 'notify_on': ['test']}
+ return cls.send_telegram(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)
+ else:
+ return {'success': False, 'error': f'Unknown channel: {channel}'}
+
+ # ==========================================
+ # STATUS
+ # ==========================================
+ @classmethod
+ def get_status(cls) -> Dict:
+ """Get notification configuration status."""
+ config = cls.get_config()
+
+ return {
+ 'discord': {
+ 'enabled': config.get('discord', {}).get('enabled', False),
+ 'configured': bool(config.get('discord', {}).get('webhook_url')),
+ 'notify_on': config.get('discord', {}).get('notify_on', [])
+ },
+ 'slack': {
+ 'enabled': config.get('slack', {}).get('enabled', False),
+ 'configured': bool(config.get('slack', {}).get('webhook_url')),
+ 'notify_on': config.get('slack', {}).get('notify_on', [])
+ },
+ 'telegram': {
+ 'enabled': config.get('telegram', {}).get('enabled', False),
+ 'configured': bool(config.get('telegram', {}).get('bot_token') and config.get('telegram', {}).get('chat_id')),
+ 'notify_on': config.get('telegram', {}).get('notify_on', [])
+ },
+ 'generic_webhook': {
+ 'enabled': config.get('generic_webhook', {}).get('enabled', False),
+ 'configured': bool(config.get('generic_webhook', {}).get('url')),
+ 'notify_on': config.get('generic_webhook', {}).get('notify_on', [])
+ }
+ }
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 9303f359..70fc4d49 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -47,4 +47,7 @@ cryptography==42.0.0
# Two-Factor Authentication
pyotp==2.9.0
-qrcode[pil]==7.4.2
\ No newline at end of file
+qrcode[pil]==7.4.2
+
+# HTTP Requests (for webhooks & notifications)
+requests==2.31.0
\ No newline at end of file
diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsx
index 6510c687..c1a7d55d 100644
--- a/frontend/src/pages/Settings.jsx
+++ b/frontend/src/pages/Settings.jsx
@@ -782,88 +782,322 @@ const AppearanceSettings = () => {
};
const NotificationSettings = () => {
- const [settings, setSettings] = useState({
- emailAlerts: true,
- serverAlerts: true,
- securityAlerts: true,
- backupAlerts: false,
- deployAlerts: true
+ const { isAdmin } = useAuth();
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [testing, setTesting] = useState(null);
+ const [message, setMessage] = useState(null);
+ 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'] },
+ generic_webhook: { enabled: false, url: '', headers: {}, notify_on: ['critical', 'warning'] }
});
+ const [expandedChannel, setExpandedChannel] = useState(null);
+
+ const severityOptions = ['critical', 'warning', 'info', 'success'];
+
+ useEffect(() => {
+ if (isAdmin) loadConfig();
+ }, [isAdmin]);
+
+ async function loadConfig() {
+ try {
+ const data = await api.getNotificationsConfig();
+ setConfig(prev => ({
+ discord: { ...prev.discord, ...data.discord },
+ slack: { ...prev.slack, ...data.slack },
+ telegram: { ...prev.telegram, ...data.telegram },
+ generic_webhook: { ...prev.generic_webhook, ...data.generic_webhook }
+ }));
+ } catch (err) {
+ console.error('Failed to load notification config:', err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function handleSaveChannel(channel) {
+ setSaving(true);
+ setMessage(null);
+ try {
+ await api.updateNotificationChannel(channel, config[channel]);
+ setMessage({ type: 'success', text: `${channel.charAt(0).toUpperCase() + channel.slice(1).replace('_', ' ')} settings saved` });
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message });
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function handleTestChannel(channel) {
+ setTesting(channel);
+ setMessage(null);
+ try {
+ const result = await api.testNotificationChannel(channel);
+ setMessage({ type: result.success ? 'success' : 'error', text: result.message || result.error || 'Test completed' });
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message });
+ } finally {
+ setTesting(null);
+ }
+ }
- function handleToggle(key) {
- setSettings({ ...settings, [key]: !settings[key] });
+ function updateChannelConfig(channel, key, value) {
+ setConfig(prev => ({
+ ...prev,
+ [channel]: { ...prev[channel], [key]: value }
+ }));
}
+ function toggleSeverity(channel, severity) {
+ const current = config[channel].notify_on || [];
+ const updated = current.includes(severity)
+ ? current.filter(s => s !== severity)
+ : [...current, severity];
+ 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 channels = [
+ { id: 'discord', name: 'Discord', icon: (
+ <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
+ <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/>
+ </svg>
+ ), description: 'Send rich notifications to Discord channels via webhooks' },
+ { id: 'slack', name: 'Slack', icon: (
+ <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
+ <path d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zM18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312zM15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z"/>
+ </svg>
+ ), description: 'Send notifications to Slack channels via incoming webhooks' },
+ { id: 'telegram', name: 'Telegram', icon: (
+ <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
+ <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: '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"/>
+ <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
+ </svg>
+ ), description: 'Send JSON payloads to any webhook endpoint' }
+ ];
+
return (
<div className="settings-section">
<div className="section-header">
- <h2>Notification Settings</h2>
- <p>Choose what notifications you want to receive</p>
+ <h2>Notification Webhooks</h2>
+ <p>Configure notification channels for server alerts</p>
</div>
- <div className="settings-card">
- <h3>Email Notifications</h3>
- <div className="notification-options">
- <div className="notification-item">
- <div className="notification-info">
- <span className="notification-title">Server Alerts</span>
- <span className="notification-desc">Get notified when server metrics exceed thresholds</span>
- </div>
- <label className="toggle-switch">
- <input
- type="checkbox"
- checked={settings.serverAlerts}
- onChange={() => handleToggle('serverAlerts')}
- />
- <span className="toggle-slider"></span>
- </label>
- </div>
+ {message && (
+ <div className={`alert alert-${message.type === 'success' ? 'success' : 'danger'}`}>
+ {message.text}
+ </div>
+ )}
- <div className="notification-item">
- <div className="notification-info">
- <span className="notification-title">Security Alerts</span>
- <span className="notification-desc">Get notified about security events and login attempts</span>
+ <div className="notification-channels">
+ {channels.map(channel => (
+ <div key={channel.id} className={`notification-channel-card ${config[channel.id]?.enabled ? 'enabled' : ''}`}>
+ <div
+ className="channel-header"
+ onClick={() => setExpandedChannel(expandedChannel === channel.id ? null : channel.id)}
+ >
+ <div className="channel-icon">{channel.icon}</div>
+ <div className="channel-info">
+ <h3>{channel.name}</h3>
+ <p>{channel.description}</p>
+ </div>
+ <div className="channel-status">
+ <span className={`badge ${config[channel.id]?.enabled ? 'badge-success' : 'badge-secondary'}`}>
+ {config[channel.id]?.enabled ? 'Enabled' : 'Disabled'}
+ </span>
+ <svg
+ viewBox="0 0 24 24"
+ width="20"
+ height="20"
+ className={`expand-icon ${expandedChannel === channel.id ? 'expanded' : ''}`}
+ >
+ <polyline points="6 9 12 15 18 9" stroke="currentColor" fill="none" strokeWidth="2"/>
+ </svg>
+ </div>
</div>
- <label className="toggle-switch">
- <input
- type="checkbox"
- checked={settings.securityAlerts}
- onChange={() => handleToggle('securityAlerts')}
- />
- <span className="toggle-slider"></span>
- </label>
- </div>
- <div className="notification-item">
- <div className="notification-info">
- <span className="notification-title">Backup Notifications</span>
- <span className="notification-desc">Get notified when backups complete or fail</span>
- </div>
- <label className="toggle-switch">
- <input
- type="checkbox"
- checked={settings.backupAlerts}
- onChange={() => handleToggle('backupAlerts')}
- />
- <span className="toggle-slider"></span>
- </label>
- </div>
+ {expandedChannel === channel.id && (
+ <div className="channel-config">
+ <div className="form-group">
+ <label className="toggle-switch-label">
+ <span>Enable {channel.name}</span>
+ <label className="toggle-switch">
+ <input
+ type="checkbox"
+ checked={config[channel.id]?.enabled || false}
+ onChange={(e) => updateChannelConfig(channel.id, 'enabled', e.target.checked)}
+ />
+ <span className="toggle-slider"></span>
+ </label>
+ </label>
+ </div>
- <div className="notification-item">
- <div className="notification-info">
- <span className="notification-title">Deployment Notifications</span>
- <span className="notification-desc">Get notified when deployments complete or fail</span>
- </div>
- <label className="toggle-switch">
- <input
- type="checkbox"
- checked={settings.deployAlerts}
- onChange={() => handleToggle('deployAlerts')}
- />
- <span className="toggle-slider"></span>
- </label>
+ {channel.id === 'discord' && (
+ <>
+ <div className="form-group">
+ <label>Webhook URL</label>
+ <input
+ type="text"
+ value={config.discord.webhook_url || ''}
+ onChange={(e) => updateChannelConfig('discord', 'webhook_url', e.target.value)}
+ placeholder="https://discord.com/api/webhooks/..."
+ />
+ <span className="form-help">Create a webhook in Discord: Server Settings β†’ Integrations β†’ Webhooks</span>
+ </div>
+ <div className="form-row">
+ <div className="form-group">
+ <label>Bot Username</label>
+ <input
+ type="text"
+ value={config.discord.username || 'ServerKit'}
+ onChange={(e) => updateChannelConfig('discord', 'username', e.target.value)}
+ placeholder="ServerKit"
+ />
+ </div>
+ <div className="form-group">
+ <label>Avatar URL (optional)</label>
+ <input
+ type="text"
+ value={config.discord.avatar_url || ''}
+ onChange={(e) => updateChannelConfig('discord', 'avatar_url', e.target.value)}
+ placeholder="https://example.com/avatar.png"
+ />
+ </div>
+ </div>
+ </>
+ )}
+
+ {channel.id === 'slack' && (
+ <>
+ <div className="form-group">
+ <label>Webhook URL</label>
+ <input
+ type="text"
+ value={config.slack.webhook_url || ''}
+ onChange={(e) => updateChannelConfig('slack', 'webhook_url', e.target.value)}
+ placeholder="https://hooks.slack.com/services/..."
+ />
+ <span className="form-help">Create an incoming webhook in Slack: Apps β†’ Incoming Webhooks</span>
+ </div>
+ <div className="form-row">
+ <div className="form-group">
+ <label>Channel (optional)</label>
+ <input
+ type="text"
+ value={config.slack.channel || ''}
+ onChange={(e) => updateChannelConfig('slack', 'channel', e.target.value)}
+ placeholder="#alerts"
+ />
+ </div>
+ <div className="form-group">
+ <label>Username</label>
+ <input
+ type="text"
+ value={config.slack.username || 'ServerKit'}
+ onChange={(e) => updateChannelConfig('slack', 'username', e.target.value)}
+ placeholder="ServerKit"
+ />
+ </div>
+ </div>
+ </>
+ )}
+
+ {channel.id === 'telegram' && (
+ <>
+ <div className="form-group">
+ <label>Bot Token</label>
+ <input
+ type="password"
+ value={config.telegram.bot_token || ''}
+ onChange={(e) => updateChannelConfig('telegram', 'bot_token', e.target.value)}
+ placeholder="123456:ABC-DEF..."
+ />
+ <span className="form-help">Get a bot token from @BotFather on Telegram</span>
+ </div>
+ <div className="form-group">
+ <label>Chat ID</label>
+ <input
+ type="text"
+ value={config.telegram.chat_id || ''}
+ onChange={(e) => updateChannelConfig('telegram', 'chat_id', e.target.value)}
+ placeholder="-1001234567890"
+ />
+ <span className="form-help">Use @userinfobot or @getidsbot to find your chat ID</span>
+ </div>
+ </>
+ )}
+
+ {channel.id === 'generic_webhook' && (
+ <div className="form-group">
+ <label>Webhook URL</label>
+ <input
+ type="text"
+ value={config.generic_webhook.url || ''}
+ onChange={(e) => updateChannelConfig('generic_webhook', 'url', e.target.value)}
+ placeholder="https://your-endpoint.com/webhook"
+ />
+ <span className="form-help">Receives JSON payload with alert data</span>
+ </div>
+ )}
+
+ <div className="form-group">
+ <label>Alert Severities</label>
+ <div className="severity-toggles">
+ {severityOptions.map(severity => (
+ <label key={severity} className={`severity-toggle ${severity}`}>
+ <input
+ type="checkbox"
+ checked={config[channel.id]?.notify_on?.includes(severity) || false}
+ onChange={() => toggleSeverity(channel.id, severity)}
+ />
+ <span>{severity.charAt(0).toUpperCase() + severity.slice(1)}</span>
+ </label>
+ ))}
+ </div>
+ </div>
+
+ <div className="channel-actions">
+ <button
+ className="btn btn-secondary"
+ onClick={() => handleTestChannel(channel.id)}
+ disabled={testing === channel.id || !config[channel.id]?.enabled}
+ >
+ {testing === channel.id ? 'Testing...' : 'Send Test'}
+ </button>
+ <button
+ className="btn btn-primary"
+ onClick={() => handleSaveChannel(channel.id)}
+ disabled={saving}
+ >
+ {saving ? 'Saving...' : 'Save'}
+ </button>
+ </div>
+ </div>
+ )}
</div>
- </div>
+ ))}
</div>
</div>
);
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index d5e234c6..dd841642 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -1624,6 +1624,36 @@ class ApiService {
body: { temp_token: tempToken, code }
});
}
+
+ // ========================================
+ // Notification Webhooks endpoints
+ // ========================================
+ async getNotificationsStatus() {
+ return this.request('/notifications/status');
+ }
+
+ async getNotificationsConfig() {
+ return this.request('/notifications/config');
+ }
+
+ async updateNotificationChannel(channel, settings) {
+ return this.request(`/notifications/config/${channel}`, {
+ method: 'PUT',
+ body: settings
+ });
+ }
+
+ async testNotificationChannel(channel) {
+ return this.request(`/notifications/test/${channel}`, {
+ method: 'POST'
+ });
+ }
+
+ async testAllNotifications() {
+ return this.request('/notifications/test', {
+ method: 'POST'
+ });
+ }
}
export const api = new ApiService();
diff --git a/frontend/src/styles/components/_notifications.less b/frontend/src/styles/components/_notifications.less
new file mode 100644
index 00000000..7fbe8efe
--- /dev/null
+++ b/frontend/src/styles/components/_notifications.less
@@ -0,0 +1,178 @@
+// ============================================
+// NOTIFICATION SETTINGS STYLES
+// ============================================
+
+.notification-channels {
+ display: flex;
+ flex-direction: column;
+ gap: @spacing-md;
+}
+
+.notification-channel-card {
+ border: 1px solid @border-color;
+ border-radius: @radius-lg;
+ background: @surface-secondary;
+ overflow: hidden;
+ transition: border-color 0.2s;
+
+ &.enabled {
+ border-color: fade(@success, 40%);
+ }
+}
+
+.channel-header {
+ display: flex;
+ align-items: center;
+ gap: @spacing-md;
+ padding: @spacing-md @spacing-lg;
+ cursor: pointer;
+ transition: background 0.2s;
+
+ &:hover {
+ background: @surface-tertiary;
+ }
+}
+
+.channel-icon {
+ width: 48px;
+ height: 48px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: @surface-tertiary;
+ border-radius: @radius-md;
+ flex-shrink: 0;
+
+ svg {
+ color: @text-secondary;
+ }
+
+ .notification-channel-card.enabled & svg {
+ color: @primary;
+ }
+}
+
+.channel-info {
+ flex: 1;
+ min-width: 0;
+
+ h3 {
+ margin: 0 0 @spacing-xs 0;
+ font-size: @font-size-md;
+ }
+
+ p {
+ margin: 0;
+ color: @text-secondary;
+ font-size: @font-size-sm;
+ }
+}
+
+.channel-status {
+ display: flex;
+ align-items: center;
+ gap: @spacing-md;
+}
+
+.expand-icon {
+ color: @text-tertiary;
+ transition: transform 0.2s;
+
+ &.expanded {
+ transform: rotate(180deg);
+ }
+}
+
+.channel-config {
+ padding: @spacing-lg;
+ border-top: 1px solid @border-color;
+ background: @surface-primary;
+}
+
+.toggle-switch-label {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+
+ span {
+ font-weight: 500;
+ }
+}
+
+.form-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: @spacing-md;
+
+ @media (max-width: 600px) {
+ grid-template-columns: 1fr;
+ }
+}
+
+.severity-toggles {
+ display: flex;
+ flex-wrap: wrap;
+ gap: @spacing-sm;
+}
+
+.severity-toggle {
+ display: flex;
+ align-items: center;
+ gap: @spacing-xs;
+ padding: @spacing-xs @spacing-sm;
+ border-radius: @radius-sm;
+ background: @surface-tertiary;
+ cursor: pointer;
+ transition: all 0.2s;
+ font-size: @font-size-sm;
+
+ input {
+ display: none;
+ }
+
+ span {
+ padding: 2px @spacing-xs;
+ border-radius: @radius-xs;
+ }
+
+ &.critical span {
+ background: fade(@danger, 20%);
+ color: @danger;
+ }
+
+ &.warning span {
+ background: fade(@warning, 20%);
+ color: @warning;
+ }
+
+ &.info span {
+ background: fade(@info, 20%);
+ color: @info;
+ }
+
+ &.success span {
+ background: fade(@success, 20%);
+ color: @success;
+ }
+
+ input:checked + span {
+ font-weight: 600;
+ }
+
+ &:has(input:not(:checked)) {
+ opacity: 0.5;
+ }
+
+ &:hover {
+ opacity: 1;
+ }
+}
+
+.channel-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: @spacing-sm;
+ margin-top: @spacing-lg;
+ padding-top: @spacing-md;
+ border-top: 1px solid @border-color;
+}
diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.less
index d72fe5ac..74f2c172 100644
--- a/frontend/src/styles/main.less
+++ b/frontend/src/styles/main.less
@@ -42,6 +42,7 @@
@import 'components/_uptime';
@import 'components/_env-vars';
@import 'components/_two-factor';
+@import 'components/_notifications';
// --------------------------------------------
// 5. PAGE-SPECIFIC STYLES