feat(notifications): event bus architecture with Telegram and SMTP subscribers (#5326)

* feat(notifications): event bus architecture with Telegram and SMTP subscribers

- Event bus core with buffered channel, fan-out, panic recovery
- Telegram subscriber with HTML formatting and rate limiting
- Email subscriber with SMTP/TLS/STARTTLS support and stage diagnostics
- 5 event types: outbound.down/up, xray.crash, cpu.high, login.attempt
- CPU threshold checks per subscriber (tgCpu for TG, smtpCpu for Email)
- SystemMetricData struct for raw metric values in events
- i18n keys for en-US, ru-RU, and English defaults for other locales

* fix

* fix(notifications): repair crash/CPU alerts, harden secrets, add node alerts

Bug fixes:
- Xray crash notifications were permanently suppressed after the first crash:
  XrayStateTracker latched state="down" with no reset and no recovery event,
  so only the first crash per process lifetime ever notified. Removed the
  tracker; the existing 1/min rate limiter already dedupes crash-loop spam.
- Email CPU alerts could never fire unless Telegram was also enabled, because
  the CPU job was registered only inside the tgbot block. Register it whenever
  either Telegram or SMTP wants cpu.high (new cpuAlarmWanted gate) and relax
  the cadence to @every 1m (cpu.Percent already samples over a full minute).
- SMTP password (and, pre-existing, all other secrets) were shipped to the
  browser in plaintext: GetAllSettingView was dead code and /setting/all
  returned the raw model. Wire getAllSetting -> GetAllSettingView, redact
  smtpPassword with a hasSmtpPassword presence flag, and preserve it on blank
  save. Closes the leak for tgBotToken/ldapPassword/2FA token too.

Polish:
- email Send: use nil SMTP auth when no credentials (Go refuses PlainAuth over
  the unencrypted "none" transport).
- Remove unused EventClientDepleted; fix inaccurate bus.go doc comments; drop
  stale tgBotLoginNotify from the frontend schema; gofmt alignment.

Feature - node online/offline alerts:
- Emit node.down/node.up from the heartbeat job on a real status transition
  (with a startup-spam guard), reusing NodeHealthData. Formatted by both the
  Telegram and email subscribers and selectable in the settings UI.

Regenerated frontend types (hasSmtpPassword). New i18n keys added to en-US;
other locales fall back to English (bundle default) until translated.

* fix(settings): use antd Space orientation instead of deprecated direction

Ant Design 6 deprecated Space's `direction` prop in favor of `orientation`,
which logged a console warning from the Telegram/Email notification tabs. Brings
these two tabs in line with the rest of the codebase, which already uses
`orientation`.

* i18n(notifications): translate the notification feature into all locales

The notifications PR shipped ~99 new strings (SMTP settings, event labels,
Telegram/email message templates) as English placeholders in every non-English
locale. Translate them — plus the node-alert keys added during this review —
into all 12 locales: Arabic, Spanish, Persian, Indonesian, Japanese,
Portuguese-BR, Russian, Turkish, Ukrainian, Vietnamese, and Simplified/
Traditional Chinese.

Go-template placeholders ({{ .Tag }}, {{ .Name }}, etc.) are preserved exactly;
tgbot message values carry no leading status emoji (the bot/email code adds
those, so an emoji in the value would duplicate it); product/protocol names
(SMTP, STARTTLS, TLS, CPU, Xray, Telegram) are kept as-is.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
Sentiago
2026-06-15 22:03:41 +03:00
committed by GitHub
parent 7fe082a7f1
commit eec030f86f
48 changed files with 3854 additions and 141 deletions
+127 -2
View File
@@ -1200,7 +1200,69 @@
"userPassMustBeNotEmpty": "Нове ім'я користувача та пароль порожні",
"getOutboundTrafficError": "Помилка отримання вихідного трафіку",
"resetOutboundTrafficError": "Помилка скидання вихідного трафіку"
}
},
"emailNotifications": "Сповіщення",
"emailSettings": "Електронна пошта",
"eventCPUHigh": "Високе навантаження на CPU (%)",
"eventGroupOutbound": "Вихідні з'єднання",
"eventGroupSecurity": "Безпека",
"eventGroupSystem": "Система",
"eventGroupXray": "Ядро Xray",
"eventLoginAttempt": "Спроба входу",
"eventOutboundDown": "Недоступне",
"eventOutboundUp": "Доступне",
"eventXrayCrash": "Збій",
"requestFailed": "Запит не вдалося виконати",
"smtpEnable": "Увімкнути сповіщення електронною поштою",
"smtpEnableDesc": "Увімкнути сповіщення електронною поштою через SMTP",
"smtpEncryption": "Шифрування",
"smtpEncryptionDesc": "Метод шифрування з'єднання SMTP",
"smtpEncryptionNone": "Немає (відкритий текст)",
"smtpEncryptionStartTLS": "STARTTLS",
"smtpEncryptionTLS": "TLS (неявне)",
"smtpEventBusNotify": "Сповіщення про події електронною поштою",
"smtpEventBusNotifyDesc": "Виберіть, які події спричиняють сповіщення електронною поштою",
"smtpHost": "Хост SMTP",
"smtpHostDesc": "Ім'я хоста сервера SMTP (наприклад, smtp.gmail.com)",
"smtpHostNotConfigured": "Хост SMTP не налаштовано",
"smtpNoRecipients": "Отримувачів не налаштовано",
"smtpNotInitialized": "SMTP не ініціалізовано",
"smtpPassword": "Пароль SMTP",
"smtpPasswordDesc": "Пароль для автентифікації SMTP",
"smtpPort": "Порт SMTP",
"smtpPortDesc": "Порт сервера SMTP (типово: 587)",
"smtpSettings": "Налаштування SMTP",
"smtpStageAuth": "Автентифікація",
"smtpStageConnect": "З'єднання",
"smtpStageSend": "Надсилання",
"smtpTestSuccess": "Тестовий лист успішно надіслано",
"smtpTo": "Отримувачі",
"smtpToDesc": "Адреси електронної пошти отримувачів, розділені комами",
"smtpUsername": "Ім'я користувача SMTP",
"smtpUsernameDesc": "Ім'я користувача для автентифікації SMTP",
"telegramTokenConfigured": "Налаштовано; залиште порожнім, щоб зберегти поточний токен.",
"telegramTokenPlaceholder": "Налаштовано — введіть новий токен для заміни",
"testSmtp": "Надіслати тестовий лист",
"testTgBot": "Надіслати тестове повідомлення",
"tgBotNotEnabled": "Бот Telegram не увімкнено",
"tgBotNotRunning": "Бот Telegram не запущено",
"tgEventBusNotify": "Сповіщення про події в Telegram",
"tgEventBusNotifyDesc": "Виберіть, які події спричиняють сповіщення в Telegram",
"tgTestFailed": "Тест Telegram не вдався",
"tgTestSuccess": "Тестове повідомлення надіслано в Telegram",
"smtpErrorAuth": "Помилка автентифікації — перевірте ім'я користувача та пароль",
"smtpErrorStarttls": "Сервер вимагає STARTTLS — змініть тип шифрування",
"smtpErrorTls": "Сервер вимагає TLS — змініть тип шифрування",
"smtpErrorRefused": "У з'єднанні відмовлено — перевірте хост і порт",
"smtpErrorTimeout": "Час очікування з'єднання вичерпано — хост недоступний",
"smtpErrorRelay": "Сервер відхиляє надсилання з цієї адреси",
"smtpErrorEof": "З'єднання закрито сервером",
"smtpErrorUnknown": "Помилка SMTP: {{ .Error }}",
"eventGroupNode": "Вузли",
"eventNodeDown": "Недоступний",
"eventNodeUp": "Доступний",
"smtpPasswordConfigured": "Налаштовано; залиште порожнім, щоб зберегти поточний пароль.",
"smtpPasswordPlaceholder": "Налаштовано — введіть новий пароль для заміни"
},
"xray": {
"title": "Xray конфігурації",
@@ -1703,7 +1765,18 @@
"AreYouSure": "Ви впевнені? 🤔",
"SuccessResetTraffic": "📧 Електронна пошта: {{ .ClientEmail }}\n🏁 Результат: ✅ Успішно",
"FailedResetTraffic": "📧 Електронна пошта: {{ .ClientEmail }}\n🏁 Результат: ❌ Невдача \n\n🛠️ Помилка: [ {{ .ErrorMessage }} ]",
"FinishProcess": "🔚 Процес скидання трафіку завершено для всіх клієнтів."
"FinishProcess": "🔚 Процес скидання трафіку завершено для всіх клієнтів.",
"eventCPUHigh": "Високе навантаження на CPU",
"eventCPUHighDetail": "CPU: {{ .Detail }}",
"eventDelayDetail": "Затримка: {{ .Delay }} мс",
"eventErrorDetail": "Помилка: {{ .Error }}",
"eventLoginFallback": "Невдала спроба входу з {{ .Source }}",
"eventOutboundDown": "Вихідне з'єднання {{ .Tag }} НЕДОСТУПНЕ",
"eventOutboundUp": "Вихідне з'єднання {{ .Tag }} ДОСТУПНЕ",
"eventXrayCrash": "Стався збій Xray",
"eventXrayCrashError": "Помилка: {{ .Error }}",
"eventNodeDown": "Вузол {{ .Name }} НЕДОСТУПНИЙ",
"eventNodeUp": "Вузол {{ .Name }} ДОСТУПНИЙ"
},
"buttons": {
"closeKeyboard": "❌ Закрити клавіатуру",
@@ -1773,5 +1846,57 @@
"chooseClient": "Виберіть клієнта для Вхідного {{ .Inbound }}",
"chooseInbound": "Виберіть Вхідний"
}
},
"email": {
"labelDelay": "Затримка",
"labelDetail": "Деталі",
"labelError": "Помилка",
"labelIP": "IP",
"labelOutbound": "Вихідне з'єднання",
"labelReason": "Причина",
"labelSource": "Джерело",
"labelStatus": "Статус",
"labelTime": "Час",
"labelUsername": "Ім'я користувача",
"statusBanned": "BANNED",
"statusCrashed": "ЗБІЙ",
"statusDown": "НЕДОСТУПНО",
"statusFailed": "НЕВДАЛО",
"statusFull": "FULL",
"statusHigh": "ВИСОКЕ",
"statusOffline": "OFFLINE",
"statusOnline": "ONLINE",
"statusRunning": "Працює",
"statusSuccess": "УСПІШНО",
"statusUp": "ДОСТУПНО",
"statusXrayDown": "Xray DOWN",
"statusXrayUp": "Xray UP",
"subjectCPUHigh": "Високе навантаження на CPU",
"subjectDiskFull": "Disk full",
"subjectIPBanned": "IP banned: {{ .IP }}",
"subjectLoginFailed": "Невдалий вхід",
"subjectLoginSuccess": "Успішний вхід",
"subjectNodeOffline": "Node {{ .Node }} is OFFLINE",
"subjectNodeOnline": "Node {{ .Node }} is ONLINE",
"subjectNodeXrayDown": "Node {{ .Node }} Xray is DOWN",
"subjectNodeXrayUp": "Node {{ .Node }} Xray is UP",
"subjectOutboundDown": "Вихідне з'єднання {{ .Tag }} НЕДОСТУПНЕ",
"subjectOutboundUp": "Вихідне з'єднання {{ .Tag }} ДОСТУПНЕ",
"subjectXrayCrash": "Стався збій Xray",
"subjectXrayUp": "Xray is UP",
"titleCPUHigh": "Високе навантаження на CPU",
"titleDiskFull": "Disk full",
"titleIPBanned": "IP banned",
"titleLoginFailed": "Невдалий вхід",
"titleLoginSuccess": "Успішний вхід",
"titleNodeOffline": "Node OFFLINE",
"titleNodeOnline": "Node ONLINE",
"titleNodeXrayDown": "Node Xray DOWN",
"titleNodeXrayUp": "Node Xray UP",
"titleOutboundDown": "Вихідне з'єднання НЕДОСТУПНЕ",
"titleOutboundUp": "Вихідне з'єднання ДОСТУПНЕ",
"titleXrayCrash": "Стався збій Xray",
"titleXrayUp": "Xray UP",
"labelNode": "Вузол"
}
}