PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (notifiers): Let a Telegram notifier send through a self-hosted Bot API server or reverse proxy set in its advanced settings, so networks without access to api.telegram.org can still get notifications
Rostislav Dugincb37d67af34a
diff --git a/backend/internal/features/notifiers/controller_test.go b/backend/internal/features/notifiers/controller_test.goindex 5f93f850..b5795d1f 100644--- a/backend/internal/features/notifiers/controller_test.go+++ b/backend/internal/features/notifiers/controller_test.go@@ -2,7 +2,12 @@ package notifiersimport ("fmt"+ "io""net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync""testing""github.com/gin-gonic/gin"@@ -1625,3 +1630,307 @@ func createEmailNotifier(workspaceID uuid.UUID) *Notifier {},}}++func Test_SaveTelegramNotifier_WithBotAPIURL_ReturnedInClearAndClearedByUpdate(t *testing.T) {+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ router := createRouter()+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)++ notifier := createTelegramNotifier(workspace.ID, "https://gateway.example.com/telegram")+ notifier.TelegramNotifier.IsProxyEnabled = true+ notifier.TelegramNotifier.ProxyURL = "socks5://user:[email protected]:1080"++ var savedNotifier Notifier+ test_utils.MakePostRequestAndUnmarshal(+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, *notifier, http.StatusOK, &savedNotifier,+ )++ retrievedNotifier := getNotifier(t, router, savedNotifier.ID, owner.Token)+ assert.Equal(t, "https://gateway.example.com/telegram", retrievedNotifier.TelegramNotifier.BotAPIURL)+ assert.Equal(t, "", retrievedNotifier.TelegramNotifier.BotToken)+ assert.Equal(t, "", retrievedNotifier.TelegramNotifier.ProxyURL)++ retrievedNotifier.TelegramNotifier.BotAPIURL = ""+ test_utils.MakePostRequest(+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, *retrievedNotifier, http.StatusOK,+ )++ updatedNotifier := getNotifier(t, router, savedNotifier.ID, owner.Token)+ assert.Equal(t, "", updatedNotifier.TelegramNotifier.BotAPIURL)++ deleteNotifier(t, router, savedNotifier.ID, workspace.ID, owner.Token)+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)+}++func createTelegramNotifier(workspaceID uuid.UUID, botAPIURL string) *Notifier {+ return &Notifier{+ WorkspaceID: workspaceID,+ Name: "Test Telegram Notifier " + uuid.New().String(),+ NotifierType: NotifierTypeTelegram,+ TelegramNotifier: &telegram_notifier.TelegramNotifier{+ BotToken: testTelegramBotToken,+ TargetChatID: "-1001234567890",+ BotAPIURL: botAPIURL,+ },+ }+}++func getNotifier(t *testing.T, router *gin.Engine, notifierID uuid.UUID, token string) *Notifier {+ var retrievedNotifier Notifier+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ fmt.Sprintf("/api/v1/notifiers/%s", notifierID.String()),+ "Bearer "+token,+ http.StatusOK,+ &retrievedNotifier,+ )++ return &retrievedNotifier+}++const (+ testTelegramBotToken = "123456:AAH-TESTBOTTOKEN"+ testTelegramBotTokenSecret = "AAH-TESTBOTTOKEN"+)++func Test_SaveTelegramNotifier_WithUnusableBotAPIURL_RefusedAndStoredNotifierUnchanged(t *testing.T) {+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ router := createRouter()+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)++ var savedNotifier Notifier+ test_utils.MakePostRequestAndUnmarshal(+ t,+ router,+ "/api/v1/notifiers",+ "Bearer "+owner.Token,+ *createTelegramNotifier(workspace.ID, "https://gateway.example.com/telegram"),+ http.StatusOK,+ &savedNotifier,+ )++ for _, unusableBotAPIURL := range []string{+ "ftp://telegram.example.com",+ "https://user:[email protected]",+ "https://gateway.example.com/telegram?key=1",+ } {+ t.Run(unusableBotAPIURL, func(t *testing.T) {+ newNotifier := createTelegramNotifier(workspace.ID, unusableBotAPIURL)+ test_utils.MakePostRequest(+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, *newNotifier, http.StatusBadRequest,+ )++ updatedNotifier := getNotifier(t, router, savedNotifier.ID, owner.Token)+ updatedNotifier.TelegramNotifier.BotAPIURL = unusableBotAPIURL+ test_utils.MakePostRequest(+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, *updatedNotifier, http.StatusBadRequest,+ )++ storedNotifier := getNotifier(t, router, savedNotifier.ID, owner.Token)+ assert.Equal(t, "https://gateway.example.com/telegram", storedNotifier.TelegramNotifier.BotAPIURL)+ })+ }++ var notifiers []Notifier+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ fmt.Sprintf("/api/v1/notifiers?workspace_id=%s", workspace.ID.String()),+ "Bearer "+owner.Token,+ http.StatusOK,+ ¬ifiers,+ )+ assert.Len(t, notifiers, 1)++ deleteNotifier(t, router, savedNotifier.ID, workspace.ID, owner.Token)+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)+}++func Test_SendTestNotificationExisting_TelegramWithBotAPIURL_DeliveredUnderPathPrefix(t *testing.T) {+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ router := createRouter()+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)++ botAPIServer := startTelegramBotAPIStub(t, http.StatusOK, `{"ok":true}`)++ var savedNotifier Notifier+ test_utils.MakePostRequestAndUnmarshal(+ t,+ router,+ "/api/v1/notifiers",+ "Bearer "+owner.Token,+ *createTelegramNotifier(workspace.ID, botAPIServer.URL+"/telegram/"),+ http.StatusOK,+ &savedNotifier,+ )++ test_utils.MakePostRequest(+ t,+ router,+ fmt.Sprintf("/api/v1/notifiers/%s/test", savedNotifier.ID.String()),+ "Bearer "+owner.Token,+ nil,+ http.StatusOK,+ )++ receivedRequests := botAPIServer.GetReceivedRequests()+ assert.Len(t, receivedRequests, 1)+ assert.Equal(t, "/telegram/bot"+testTelegramBotToken+"/sendMessage", receivedRequests[0].Path)+ assert.Equal(t, "-1001234567890", receivedRequests[0].ChatID)++ deleteNotifier(t, router, savedNotifier.ID, workspace.ID, owner.Token)+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)+}++func Test_SendTestNotificationDirect_TelegramWithBotAPIURL_DeliveredUnderPathPrefix(t *testing.T) {+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ router := createRouter()+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ defer workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)++ botAPIServer := startTelegramBotAPIStub(t, http.StatusOK, `{"ok":true}`)+ notifier := createTelegramNotifier(workspace.ID, botAPIServer.URL+"/telegram")++ test_utils.MakePostRequest(+ t, router, "/api/v1/notifiers/direct-test", "Bearer "+owner.Token, *notifier, http.StatusOK,+ )++ receivedRequests := botAPIServer.GetReceivedRequests()+ assert.Len(t, receivedRequests, 1)+ assert.Equal(t, "/telegram/bot"+testTelegramBotToken+"/sendMessage", receivedRequests[0].Path)+ assert.Equal(t, "-1001234567890", receivedRequests[0].ChatID)+}++func Test_SendTestNotificationDirect_TelegramWithUnusableBotAPIURL_RefusedWithoutRequest(t *testing.T) {+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ router := createRouter()+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ defer workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)++ botAPIServer := startTelegramBotAPIStub(t, http.StatusOK, `{"ok":true}`)+ botAPIHost := strings.TrimPrefix(botAPIServer.URL, "http://")++ for _, unusableBotAPIURL := range []string{+ "ftp://" + botAPIHost + "/telegram",+ "http://user:password@" + botAPIHost + "/telegram",+ } {+ t.Run(unusableBotAPIURL, func(t *testing.T) {+ notifier := createTelegramNotifier(workspace.ID, unusableBotAPIURL)++ test_utils.MakePostRequest(+ t, router, "/api/v1/notifiers/direct-test", "Bearer "+owner.Token, *notifier, http.StatusBadRequest,+ )+ })+ }++ assert.Empty(t, botAPIServer.GetReceivedRequests())+}++func Test_SendTestNotificationDirect_TelegramWithBotAPIURLAndProxy_SentThroughProxy(t *testing.T) {+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ router := createRouter()+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ defer workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)++ proxyServer := startTelegramBotAPIStub(t, http.StatusOK, `{"ok":true}`)++ notifier := createTelegramNotifier(workspace.ID, "http://telegram-bot-api.invalid:8081/telegram")+ notifier.TelegramNotifier.IsProxyEnabled = true+ notifier.TelegramNotifier.ProxyURL = proxyServer.URL++ test_utils.MakePostRequest(+ t, router, "/api/v1/notifiers/direct-test", "Bearer "+owner.Token, *notifier, http.StatusOK,+ )++ receivedRequests := proxyServer.GetReceivedRequests()+ assert.Len(t, receivedRequests, 1)+ assert.Equal(+ t,+ "http://telegram-bot-api.invalid:8081/telegram/bot"+testTelegramBotToken+"/sendMessage",+ receivedRequests[0].RequestURI,+ )+}++func Test_SendTestNotificationDirect_TelegramBotAPIUnreachable_ErrorNamesHostWithoutBotToken(t *testing.T) {+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ router := createRouter()+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ defer workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)++ closedServer := httptest.NewServer(http.NotFoundHandler())+ closedServer.Close()++ notifier := createTelegramNotifier(workspace.ID, closedServer.URL+"/telegram")++ response := test_utils.MakePostRequest(+ t, router, "/api/v1/notifiers/direct-test", "Bearer "+owner.Token, *notifier, http.StatusBadRequest,+ )++ assert.Contains(t, string(response.Body), strings.TrimPrefix(closedServer.URL, "http://"))+ assert.NotContains(t, string(response.Body), testTelegramBotTokenSecret)+}++type telegramBotAPIRequest struct {+ Path string+ RequestURI string+ ChatID string+}++type telegramBotAPIStub struct {+ URL string++ mu sync.Mutex+ receivedRequests []telegramBotAPIRequest+}++func (s *telegramBotAPIStub) GetReceivedRequests() []telegramBotAPIRequest {+ s.mu.Lock()+ defer s.mu.Unlock()++ return append([]telegramBotAPIRequest(nil), s.receivedRequests...)+}++// Also serves as a forward proxy: a proxied request arrives with the target's absolute URL as its+// RequestURI.+func startTelegramBotAPIStub(t *testing.T, statusCode int, responseBody string) *telegramBotAPIStub {+ stub := &telegramBotAPIStub{}++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requestBody, _ := io.ReadAll(r.Body)+ formValues, _ := url.ParseQuery(string(requestBody))++ stub.mu.Lock()+ stub.receivedRequests = append(stub.receivedRequests, telegramBotAPIRequest{+ Path: r.URL.Path,+ RequestURI: r.RequestURI,+ ChatID: formValues.Get("chat_id"),+ })+ stub.mu.Unlock()++ w.WriteHeader(statusCode)+ _, _ = io.WriteString(w, strings.ReplaceAll(responseBody, "{path}", r.URL.Path))+ }))+ t.Cleanup(server.Close)++ stub.URL = server.URL++ return stub+}++func Test_SendTestNotificationDirect_TelegramBotAPIEchoesRequestPath_ErrorKeepsBodyWithoutBotToken(t *testing.T) {+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ router := createRouter()+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ defer workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)++ botAPIServer := startTelegramBotAPIStub(t, http.StatusNotFound, "Cannot POST {path}")+ notifier := createTelegramNotifier(workspace.ID, botAPIServer.URL+"/telegram")++ response := test_utils.MakePostRequest(+ t, router, "/api/v1/notifiers/direct-test", "Bearer "+owner.Token, *notifier, http.StatusBadRequest,+ )++ assert.Contains(t, string(response.Body), "Cannot POST /telegram/botredacted/sendMessage")+ assert.NotContains(t, string(response.Body), testTelegramBotTokenSecret)+}diff --git a/backend/internal/features/notifiers/models/telegram/bot_api_url.go b/backend/internal/features/notifiers/models/telegram/bot_api_url.gonew file mode 100644index 00000000..fa323042--- /dev/null+++ b/backend/internal/features/notifiers/models/telegram/bot_api_url.go@@ -0,0 +1,49 @@+package telegram_notifier++import (+ "errors"+ "fmt"+ "net/url"+ "strings"+)++const officialBotAPIURL = "https://api.telegram.org"++// Send validates again because a direct test send of an unsaved notifier never reaches Validate.+// Concatenation rather than url.JoinPath keeps "./" and "../" in the prefix exactly as validated.+func (t *TelegramNotifier) getSendMessageURL(botToken string) (string, error) {+ botAPIURL := officialBotAPIURL++ if t.BotAPIURL != "" {+ if err := validateBotAPIURL(t.BotAPIURL); err != nil {+ return "", err+ }++ botAPIURL = t.BotAPIURL+ }++ return fmt.Sprintf("%s/bot%s/sendMessage", strings.TrimRight(botAPIURL, "/"), botToken), nil+}++// The URL is stored and returned in clear, so it must not be able to carry a secret of its own.+// A query or fragment would also break the path the bot token is appended to.+func validateBotAPIURL(rawBotAPIURL string) error {+ parsedBotAPIURL, err := url.Parse(rawBotAPIURL)+ if err != nil ||+ (parsedBotAPIURL.Scheme != "http" && parsedBotAPIURL.Scheme != "https") ||+ parsedBotAPIURL.Host == "" {+ return errors.New("bot API URL must be a valid http/https URL with a host")+ }++ if parsedBotAPIURL.User != nil {+ return errors.New("bot API URL must not contain a username or password")+ }++ // An empty query or fragment ("/telegram?") parses to empty fields, so the delimiters are checked+ // in the raw string. Outside user info, rejected above, they can only be those delimiters.+ if strings.ContainsAny(rawBotAPIURL, "?#") {+ return errors.New("bot API URL must not contain a query or fragment")+ }++ return nil+}diff --git a/backend/internal/features/notifiers/models/telegram/model.go b/backend/internal/features/notifiers/models/telegram/model.goindex 6ee86d1b..3fa61164 100644--- a/backend/internal/features/notifiers/models/telegram/model.go+++ b/backend/internal/features/notifiers/models/telegram/model.go@@ -24,6 +24,7 @@ type TelegramNotifier struct {ThreadID *int64 `json:"threadId" gorm:"column:thread_id"`IsProxyEnabled bool `json:"isProxyEnabled" gorm:"column:is_proxy_enabled;type:boolean;not null;default:false"`ProxyURL string `json:"proxyUrl" gorm:"column:proxy_url;type:text"`+ BotAPIURL string `json:"botApiUrl" gorm:"column:bot_api_url;type:text"`}func (t *TelegramNotifier) TableName() string {@@ -54,6 +55,12 @@ func (t *TelegramNotifier) Validate(encryptor encryption.FieldEncryptor) error {}}+ if t.BotAPIURL != "" {+ if err := validateBotAPIURL(t.BotAPIURL); err != nil {+ return err+ }+ }+return nil}@@ -72,7 +79,10 @@ func (t *TelegramNotifier) Send(fullMessage = fmt.Sprintf("%s\n\n%s", notification.Heading, notification.Message)}- apiURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)+ sendMessageURL, err := t.getSendMessageURL(botToken)+ if err != nil {+ return err+ }data := url.Values{}data.Set("chat_id", t.TargetChatID)@@ -83,7 +93,12 @@ func (t *TelegramNotifier) Send(data.Set("message_thread_id", strconv.FormatInt(*t.ThreadID, 10))}- req, err := http.NewRequestWithContext(context.Background(), "POST", apiURL, strings.NewReader(data.Encode()))+ req, err := http.NewRequestWithContext(+ context.Background(),+ "POST",+ sendMessageURL,+ strings.NewReader(data.Encode()),+ )if err != nil {return fmt.Errorf("failed to create request: %w", err)}@@ -108,7 +123,7 @@ func (t *TelegramNotifier) Send(return fmt.Errorf("telegram API returned non-OK status: %s. Error: %s",resp.Status,- string(bodyBytes),+ notifier_models.RedactSecretInText(string(bodyBytes), botToken),)}@@ -124,6 +139,7 @@ func (t *TelegramNotifier) Update(incoming *TelegramNotifier) {t.TargetChatID = incoming.TargetChatIDt.ThreadID = incoming.ThreadIDt.IsProxyEnabled = incoming.IsProxyEnabled+ t.BotAPIURL = incoming.BotAPIURLif !incoming.IsProxyEnabled {t.ProxyURL = ""diff --git a/backend/internal/features/notifiers/models/telegram/model_test.go b/backend/internal/features/notifiers/models/telegram/model_test.goindex c89671ac..98f7c537 100644--- a/backend/internal/features/notifiers/models/telegram/model_test.go+++ b/backend/internal/features/notifiers/models/telegram/model_test.go@@ -48,3 +48,55 @@ func Test_Validate_WhenProxyURLIsSocks5_ReturnsNoError(t *testing.T) {require.NoError(t, err)}++func Test_Validate_WithBotAPIURL_AcceptsPlainHTTPAddressesOnly(t *testing.T) {+ testCases := []struct {+ botAPIURL string+ expectedError string+ }{+ {botAPIURL: ""},+ {botAPIURL: "http://localhost:8081"},+ {botAPIURL: "http://telegram-bot-api:8081"},+ {botAPIURL: "https://gateway.example.com"},+ {botAPIURL: "https://gateway.example.com/telegram/"},+ {botAPIURL: "ftp://telegram.example.com", expectedError: "valid http/https URL with a host"},+ {botAPIURL: "telegram-bot-api:8081", expectedError: "valid http/https URL with a host"},+ {botAPIURL: "https://", expectedError: "valid http/https URL with a host"},+ {botAPIURL: "gateway.example.com/telegram", expectedError: "valid http/https URL with a host"},+ {botAPIURL: "https://user:[email protected]", expectedError: "username or password"},+ {botAPIURL: "https://[email protected]", expectedError: "username or password"},+ {botAPIURL: "https://gateway.example.com/telegram?key=1", expectedError: "query or fragment"},+ {botAPIURL: "https://gateway.example.com/telegram?", expectedError: "query or fragment"},+ {botAPIURL: "https://gateway.example.com/#bot", expectedError: "query or fragment"},+ {botAPIURL: "https://gateway.example.com/#", expectedError: "query or fragment"},+ }++ for _, testCase := range testCases {+ t.Run(testCase.botAPIURL, func(t *testing.T) {+ notifier := &TelegramNotifier{+ BotToken: "token",+ TargetChatID: "123456",+ BotAPIURL: testCase.botAPIURL,+ }++ err := notifier.Validate(notifier_models.PassthroughEncryptor{})++ if testCase.expectedError == "" {+ require.NoError(t, err)+ return+ }++ require.Error(t, err)+ assert.Contains(t, err.Error(), testCase.expectedError)+ })+ }+}++func Test_GetSendMessageURL_WithoutBotAPIURL_UsesOfficialTelegramAPI(t *testing.T) {+ notifier := &TelegramNotifier{}++ sendMessageURL, err := notifier.getSendMessageURL("123456:AAH-TOKEN")++ require.NoError(t, err)+ assert.Equal(t, "https://api.telegram.org/bot123456:AAH-TOKEN/sendMessage", sendMessageURL)+}diff --git a/backend/internal/features/notifiers/models/url_credentials.go b/backend/internal/features/notifiers/models/url_credentials.goindex 7858dabb..414134c8 100644--- a/backend/internal/features/notifiers/models/url_credentials.go+++ b/backend/internal/features/notifiers/models/url_credentials.go@@ -45,6 +45,15 @@ func ErrorWithoutWebhookURLCredentials(err error) error {}}+// A server's error response can echo the request it got, and with it a secret the request carried.+func RedactSecretInText(text, secret string) string {+ if secret == "" {+ return text+ }++ return strings.ReplaceAll(text, secret, redactedURLSegment)+}+// Which segment holds the secret varies per provider. The first one usually names the endpoint and// is what makes a failure diagnosable, so it survives.func redactPathSecrets(path string) string {diff --git a/backend/internal/features/notifiers/models/url_credentials_test.go b/backend/internal/features/notifiers/models/url_credentials_test.goindex 545d7ec3..ed87e97d 100644--- a/backend/internal/features/notifiers/models/url_credentials_test.go+++ b/backend/internal/features/notifiers/models/url_credentials_test.go@@ -98,3 +98,16 @@ func Test_ErrorWithoutWebhookURLCredentials_WithNonTransportError_ReturnsItUnchaassert.Equal(t, plainError, ErrorWithoutWebhookURLCredentials(plainError))}++func Test_RedactSecretInText_WithEchoedSecret_ReplacesEveryOccurrence(t *testing.T) {+ redactedText := RedactSecretInText(+ "Cannot POST /bot123456:AAH-SECRET/sendMessage (123456:AAH-SECRET)",+ "123456:AAH-SECRET",+ )++ assert.Equal(t, "Cannot POST /botredacted/sendMessage (redacted)", redactedText)+}++func Test_RedactSecretInText_WithEmptySecret_ReturnsTextUnchanged(t *testing.T) {+ assert.Equal(t, "chat not found", RedactSecretInText("chat not found", ""))+}diff --git a/backend/migrations/20261010171734_add_telegram_bot_api_url.sql b/backend/migrations/20261010171734_add_telegram_bot_api_url.sqlnew file mode 100644index 00000000..a8a252ad--- /dev/null+++ b/backend/migrations/20261010171734_add_telegram_bot_api_url.sql@@ -0,0 +1,15 @@+-- +goose Up+-- +goose StatementBegin++ALTER TABLE telegram_notifiers+ ADD COLUMN bot_api_url TEXT;++-- +goose StatementEnd++-- +goose Down+-- +goose StatementBegin++ALTER TABLE telegram_notifiers+ DROP COLUMN IF EXISTS bot_api_url;++-- +goose StatementEnddiff --git a/frontend/src/entity/notifiers/models/telegram/TelegramNotifier.ts b/frontend/src/entity/notifiers/models/telegram/TelegramNotifier.tsindex 35bd0631..ac05b56a 100644--- a/frontend/src/entity/notifiers/models/telegram/TelegramNotifier.ts+++ b/frontend/src/entity/notifiers/models/telegram/TelegramNotifier.ts@@ -4,6 +4,7 @@ export interface TelegramNotifier {threadId?: number;isProxyEnabled?: boolean;proxyUrl?: string;+ botApiUrl?: string;// temp fieldisSendToThreadEnabled?: boolean;diff --git a/frontend/src/entity/notifiers/models/telegram/validateTelegramNotifier.test.ts b/frontend/src/entity/notifiers/models/telegram/validateTelegramNotifier.test.tsindex d5c79c7b..a106fd25 100644--- a/frontend/src/entity/notifiers/models/telegram/validateTelegramNotifier.test.ts+++ b/frontend/src/entity/notifiers/models/telegram/validateTelegramNotifier.test.ts@@ -51,4 +51,38 @@ describe('validateTelegramNotifier', () => {).toBe(true);}});++ it('accepts an empty Bot API URL and plain http or https addresses', () => {+ for (const botApiUrl of [+ undefined,+ '',+ 'http://localhost:8081',+ 'http://telegram-bot-api:8081',+ 'https://gateway.example.com',+ 'https://gateway.example.com/telegram/',+ ]) {+ expect(+ validateTelegramNotifier(true, { botToken: 'token', targetChatId: '123456', botApiUrl }),+ ).toBe(true);+ }+ });++ it('rejects Bot API URLs with another scheme, no host, credentials, a query or a fragment', () => {+ for (const botApiUrl of [+ 'ftp://telegram.example.com',+ 'telegram-bot-api:8081',+ 'https://',+ 'gateway.example.com/telegram',+ 'https://user:[email protected]',+ 'https://[email protected]',+ 'https://gateway.example.com/telegram?key=1',+ 'https://gateway.example.com/telegram?',+ 'https://gateway.example.com/#bot',+ 'https://gateway.example.com/#',+ ]) {+ expect(+ validateTelegramNotifier(true, { botToken: 'token', targetChatId: '123456', botApiUrl }),+ ).toBe(false);+ }+ });});diff --git a/frontend/src/entity/notifiers/models/telegram/validateTelegramNotifier.ts b/frontend/src/entity/notifiers/models/telegram/validateTelegramNotifier.tsindex 5647d7c7..4f193b5e 100644--- a/frontend/src/entity/notifiers/models/telegram/validateTelegramNotifier.ts+++ b/frontend/src/entity/notifiers/models/telegram/validateTelegramNotifier.ts@@ -12,6 +12,26 @@ const isValidProxyUrl = (rawProxyUrl: string): boolean => {}};+// eslint-disable-next-line i18next/no-literal-string -- URL protocols, not copy+const allowedBotApiProtocols = ['http:', 'https:'];++// Outside user info, which is rejected, "?" and "#" can only start a query or a fragment, and an+// empty one ("/telegram?") leaves search and hash empty.+const isValidBotApiUrl = (rawBotApiUrl: string): boolean => {+ try {+ const botApiUrl = new URL(rawBotApiUrl);+ return (+ allowedBotApiProtocols.includes(botApiUrl.protocol) &&+ !!botApiUrl.host &&+ !botApiUrl.username &&+ !botApiUrl.password &&+ !/[?#]/.test(rawBotApiUrl)+ );+ } catch {+ return false;+ }+};+export const validateTelegramNotifier = (isCreate: boolean,notifier: TelegramNotifier,@@ -39,5 +59,9 @@ export const validateTelegramNotifier = (}}+ if (notifier.botApiUrl && !isValidBotApiUrl(notifier.botApiUrl)) {+ return false;+ }+return true;};diff --git a/frontend/src/features/databases/ui/edit/AdvancedSettingsToggleComponent.tsx b/frontend/src/features/databases/ui/edit/AdvancedSettingsToggleComponent.tsxdeleted file mode 100644index f482f2c6..00000000--- a/frontend/src/features/databases/ui/edit/AdvancedSettingsToggleComponent.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { DownOutlined, UpOutlined } from '@ant-design/icons';-import { useTranslation } from 'react-i18next';--interface Props {- isShowAdvanced: boolean;- onToggle: () => void;-}--export const AdvancedSettingsToggleComponent = ({ isShowAdvanced, onToggle }: Props) => {- const { t } = useTranslation();-- return (- <div className="mt-4 mb-1 flex items-center">- <div- className="flex cursor-pointer items-center text-sm text-blue-600 hover:text-blue-800"- onClick={onToggle}- >- <span className="mr-2">{t('databases.edit.advancedSettings')}</span>-- {isShowAdvanced ? (- <UpOutlined style={{ fontSize: '12px' }} />- ) : (- <DownOutlined style={{ fontSize: '12px' }} />- )}- </div>- </div>- );-};diff --git a/frontend/src/features/databases/ui/edit/EditMariaDbSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditMariaDbSpecificDataComponent.tsxindex a87f6d6e..6bf2692a 100644--- a/frontend/src/features/databases/ui/edit/EditMariaDbSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditMariaDbSpecificDataComponent.tsx@@ -21,8 +21,10 @@ import {import { NAME_LIST_TOKEN_SEPARATORS, normalizeNameList } from '../../../../shared/lib';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';-import { ClipboardPasteModalComponent } from '../../../../shared/ui';-import { AdvancedSettingsToggleComponent } from './AdvancedSettingsToggleComponent';+import {+ AdvancedSettingsToggleComponent,+ ClipboardPasteModalComponent,+} from '../../../../shared/ui';import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {@@ -372,6 +374,7 @@ export const EditMariaDbSpecificDataComponent = ({</div><AdvancedSettingsToggleComponent+ label={t('databases.edit.advancedSettings')}isShowAdvanced={isShowAdvanced}onToggle={() => setShowAdvanced(!isShowAdvanced)}/>diff --git a/frontend/src/features/databases/ui/edit/EditMongoDbSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditMongoDbSpecificDataComponent.tsxindex 149a9fa5..4df1d73f 100644--- a/frontend/src/features/databases/ui/edit/EditMongoDbSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditMongoDbSpecificDataComponent.tsx@@ -22,8 +22,10 @@ import {import { NAME_LIST_TOKEN_SEPARATORS, normalizeNameList } from '../../../../shared/lib';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';-import { ClipboardPasteModalComponent } from '../../../../shared/ui';-import { AdvancedSettingsToggleComponent } from './AdvancedSettingsToggleComponent';+import {+ AdvancedSettingsToggleComponent,+ ClipboardPasteModalComponent,+} from '../../../../shared/ui';import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {@@ -417,6 +419,7 @@ export const EditMongoDbSpecificDataComponent = ({</div><AdvancedSettingsToggleComponent+ label={t('databases.edit.advancedSettings')}isShowAdvanced={isShowAdvanced}onToggle={() => setShowAdvanced(!isShowAdvanced)}/>diff --git a/frontend/src/features/databases/ui/edit/EditMySqlSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditMySqlSpecificDataComponent.tsxindex 2cbe0374..c42e055b 100644--- a/frontend/src/features/databases/ui/edit/EditMySqlSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditMySqlSpecificDataComponent.tsx@@ -21,8 +21,10 @@ import {import { NAME_LIST_TOKEN_SEPARATORS, normalizeNameList } from '../../../../shared/lib';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';-import { ClipboardPasteModalComponent } from '../../../../shared/ui';-import { AdvancedSettingsToggleComponent } from './AdvancedSettingsToggleComponent';+import {+ AdvancedSettingsToggleComponent,+ ClipboardPasteModalComponent,+} from '../../../../shared/ui';import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {@@ -368,6 +370,7 @@ export const EditMySqlSpecificDataComponent = ({</div><AdvancedSettingsToggleComponent+ label={t('databases.edit.advancedSettings')}isShowAdvanced={isShowAdvanced}onToggle={() => setShowAdvanced(!isShowAdvanced)}/>diff --git a/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsxindex ed3ab0bf..b4699fa3 100644--- a/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditPostgreSqlLogicalSpecificDataComponent.tsx@@ -23,8 +23,10 @@ import {import { NAME_LIST_TOKEN_SEPARATORS, normalizeNameList } from '../../../../shared/lib';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';-import { ClipboardPasteModalComponent } from '../../../../shared/ui';-import { AdvancedSettingsToggleComponent } from './AdvancedSettingsToggleComponent';+import {+ AdvancedSettingsToggleComponent,+ ClipboardPasteModalComponent,+} from '../../../../shared/ui';import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {@@ -651,6 +653,7 @@ export const EditPostgreSqlLogicalSpecificDataComponent = ({)}<AdvancedSettingsToggleComponent+ label={t('databases.edit.advancedSettings')}isShowAdvanced={isShowAdvanced}onToggle={() => setShowAdvanced(!isShowAdvanced)}/>diff --git a/frontend/src/features/databases/ui/edit/EditPostgreSqlPhysicalSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditPostgreSqlPhysicalSpecificDataComponent.tsxindex b2f47e0c..b7f636a8 100644--- a/frontend/src/features/databases/ui/edit/EditPostgreSqlPhysicalSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditPostgreSqlPhysicalSpecificDataComponent.tsx@@ -27,8 +27,10 @@ import {} from '../../../../shared/i18n';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';-import { ClipboardPasteModalComponent } from '../../../../shared/ui';-import { AdvancedSettingsToggleComponent } from './AdvancedSettingsToggleComponent';+import {+ AdvancedSettingsToggleComponent,+ ClipboardPasteModalComponent,+} from '../../../../shared/ui';import { EditSshTunnelComponent } from './EditSshTunnelComponent';interface Props {@@ -624,6 +626,7 @@ export const EditPostgreSqlPhysicalSpecificDataComponent = ({{renderSslCertSection()}<AdvancedSettingsToggleComponent+ label={t('databases.edit.advancedSettings')}isShowAdvanced={isShowAdvanced}onToggle={() => setShowAdvanced(!isShowAdvanced)}/>diff --git a/frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsx b/frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsxindex 6a184ec1..1fd44da9 100644--- a/frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsx+++ b/frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsx@@ -1,6 +1,6 @@-import { DownOutlined, InfoCircleOutlined, UpOutlined } from '@ant-design/icons';+import { InfoCircleOutlined } from '@ant-design/icons';import { Checkbox, Input, Select, Tooltip } from 'antd';-import { type ReactNode, useState } from 'react';+import { useState } from 'react';import { useTranslation } from 'react-i18next';import {@@ -10,6 +10,10 @@ import {getDefaultEmailNotifierSecurity,getSecurityAfterPortChange,} from '../../../../../entity/notifiers';+import {+ AdvancedFieldRowComponent,+ AdvancedSettingsToggleComponent,+} from '../../../../../shared/ui';interface Props {notifier: Notifier;@@ -185,20 +189,11 @@ export function EditEmailNotifierComponent({ notifier, setNotifier, setUnsaved }</div></div>- <div className="mt-4 mb-3 flex items-center">- <div- className="flex cursor-pointer items-center text-sm text-blue-600 hover:text-blue-800"- onClick={() => setShowAdvanced(!showAdvanced)}- >- <span className="mr-2">{t('notifiers.email.advancedSettings')}</span>-- {showAdvanced ? (- <UpOutlined style={{ fontSize: '12px' }} />- ) : (- <DownOutlined style={{ fontSize: '12px' }} />- )}- </div>- </div>+ <AdvancedSettingsToggleComponent+ label={t('notifiers.advancedSettings')}+ isShowAdvanced={showAdvanced}+ onToggle={() => setShowAdvanced(!showAdvanced)}+ />{showAdvanced && (<>@@ -274,24 +269,3 @@ export function EditEmailNotifierComponent({ notifier, setNotifier, setUnsaved }</>);}--interface AdvancedFieldRowProps {- label: string;- tooltip: string;- children: ReactNode;-}--function AdvancedFieldRowComponent({ label, tooltip, children }: AdvancedFieldRowProps) {- return (- <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">- <div className="mb-1 min-w-[150px] sm:mb-0 sm:pr-2">{label}</div>- <div className="flex items-center">- {children}-- <Tooltip className="cursor-pointer" title={tooltip}>- <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />- </Tooltip>- </div>- </div>- );-}diff --git a/frontend/src/features/notifiers/ui/edit/notifiers/EditTelegramNotifierComponent.test.tsx b/frontend/src/features/notifiers/ui/edit/notifiers/EditTelegramNotifierComponent.test.tsxnew file mode 100644index 00000000..b4df89e9--- /dev/null+++ b/frontend/src/features/notifiers/ui/edit/notifiers/EditTelegramNotifierComponent.test.tsx@@ -0,0 +1,72 @@+import { renderToStaticMarkup } from 'react-dom/server';+import { describe, expect, it, vi } from 'vitest';++import {+ type Notifier,+ NotifierType,+ type TelegramNotifier,+} from '../../../../../entity/notifiers';+import { LocaleProvider } from '../../../../../shared/i18n';+import { EditTelegramNotifierComponent } from './EditTelegramNotifierComponent';++// The entity's public API imports its API client, and the client's config+// module reads window at import time. The tests run in node, so they supply+// window. LocaleProvider then reads localStorage, which here reports no saved+// language.+vi.hoisted(() => {+ vi.stubGlobal('window', {});+ vi.stubGlobal('localStorage', { getItem: () => null });+ vi.stubGlobal('navigator', { language: 'en-US', languages: ['en-US'] });+});++const createTelegramNotifier = (change: Partial<TelegramNotifier>): Notifier => ({+ id: 'notifier-id',+ name: 'Telegram',+ notifierType: NotifierType.TELEGRAM,+ workspaceId: 'workspace-id',+ telegramNotifier: {+ botToken: '',+ targetChatId: '-1001234567890',+ ...change,+ },+});++const renderTelegramForm = (notifier: Notifier) =>+ renderToStaticMarkup(+ <LocaleProvider>+ <EditTelegramNotifierComponent+ notifier={notifier}+ setNotifier={() => {}}+ setUnsaved={() => {}}+ />+ </LocaleProvider>,+ );++describe('EditTelegramNotifierComponent', () => {+ it('starts with the advanced settings collapsed for a new notifier', () => {+ const markup = renderTelegramForm(createTelegramNotifier({}));++ expect(markup).toContain('Advanced settings');+ expect(markup).toContain('Target chat ID');+ expect(markup).not.toContain('Bot API URL');+ expect(markup).not.toContain('Use proxy');+ });++ it('starts with the advanced settings expanded when a proxy is enabled', () => {+ const markup = renderTelegramForm(createTelegramNotifier({ isProxyEnabled: true }));++ expect(markup).toContain('Bot API URL');+ expect(markup).toContain('Use proxy');+ expect(markup).toContain('Proxy URL');+ });++ it('starts with the advanced settings expanded when a Bot API URL is set', () => {+ const markup = renderTelegramForm(+ createTelegramNotifier({ botApiUrl: 'https://gateway.example.com/telegram' }),+ );++ expect(markup).toContain('https://gateway.example.com/telegram');+ expect(markup).toContain('Use proxy');+ expect(markup).not.toContain('Proxy URL');+ });+});diff --git a/frontend/src/features/notifiers/ui/edit/notifiers/EditTelegramNotifierComponent.tsx b/frontend/src/features/notifiers/ui/edit/notifiers/EditTelegramNotifierComponent.tsxindex 2a30ef42..6ef11606 100644--- a/frontend/src/features/notifiers/ui/edit/notifiers/EditTelegramNotifierComponent.tsx+++ b/frontend/src/features/notifiers/ui/edit/notifiers/EditTelegramNotifierComponent.tsx@@ -4,6 +4,10 @@ import { useEffect, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import type { Notifier } from '../../../../../entity/notifiers';+import {+ AdvancedFieldRowComponent,+ AdvancedSettingsToggleComponent,+} from '../../../../../shared/ui';interface Props {notifier: Notifier;@@ -16,6 +20,9 @@ const chatIdBotLink = <a href="https://t.me/getmyid_bot" target="_blank" rel="noexport function EditTelegramNotifierComponent({ notifier, setNotifier, setUnsaved }: Props) {const { t } = useTranslation();const [isShowHowToGetChatId, setIsShowHowToGetChatId] = useState(false);+ const [isShowAdvanced, setIsShowAdvanced] = useState(+ !!notifier.telegramNotifier?.botApiUrl || !!notifier.telegramNotifier?.isProxyEnabled,+ );useEffect(() => {if (notifier.telegramNotifier?.threadId && !notifier.telegramNotifier.isSendToThreadEnabled) {@@ -118,66 +125,6 @@ export function EditTelegramNotifierComponent({ notifier, setNotifier, setUnsave)}</div>- <div className="mt-4 mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">- <div className="mb-1 min-w-[150px] sm:mb-0 sm:pr-2">{t('notifiers.telegram.useProxy')}</div>- <div className="flex items-center">- <Switch- checked={notifier?.telegramNotifier?.isProxyEnabled || false}- onChange={(checked) => {- if (!notifier?.telegramNotifier) return;-- setNotifier({- ...notifier,- telegramNotifier: {- ...notifier.telegramNotifier,- isProxyEnabled: checked,- proxyUrl: checked ? notifier.telegramNotifier.proxyUrl : undefined,- },- });- setUnsaved();- }}- size="small"- />-- <Tooltip className="cursor-pointer" title={t('notifiers.telegram.useProxyTooltip')}>- <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />- </Tooltip>- </div>- </div>-- {notifier?.telegramNotifier?.isProxyEnabled && (- <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">- <div className="mb-1 min-w-[150px] sm:mb-0 sm:pr-2">- {t('notifiers.telegram.proxyUrl')}- </div>- <div className="flex items-center">- <Input- value={notifier?.telegramNotifier?.proxyUrl || ''}- onChange={(e) => {- if (!notifier?.telegramNotifier) return;-- setNotifier({- ...notifier,- telegramNotifier: {- ...notifier.telegramNotifier,- proxyUrl: e.target.value.trim(),- },- });- setUnsaved();- }}- size="small"- className="w-full max-w-[250px]"- // eslint-disable-next-line i18next/no-literal-string -- example proxy URL- placeholder="socks5://user:pass@host:1080"- />-- <Tooltip className="cursor-pointer" title={t('notifiers.telegram.proxyUrlTooltip')}>- <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />- </Tooltip>- </div>- </div>- )}-<div className="mt-4 mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center"><div className="mb-1 min-w-[150px] sm:mb-0 sm:pr-2">{t('notifiers.telegram.sendToGroupTopic')}@@ -270,6 +217,91 @@ export function EditTelegramNotifierComponent({ notifier, setNotifier, setUnsave</div></>)}++ <AdvancedSettingsToggleComponent+ label={t('notifiers.advancedSettings')}+ isShowAdvanced={isShowAdvanced}+ onToggle={() => setIsShowAdvanced(!isShowAdvanced)}+ />++ {isShowAdvanced && (+ <>+ <AdvancedFieldRowComponent+ label={t('notifiers.telegram.botApiUrl')}+ tooltip={t('notifiers.telegram.botApiUrlTooltip')}+ >+ <Input+ value={notifier?.telegramNotifier?.botApiUrl || ''}+ onChange={(e) => {+ if (!notifier?.telegramNotifier) return;++ setNotifier({+ ...notifier,+ telegramNotifier: {+ ...notifier.telegramNotifier,+ botApiUrl: e.target.value.trim(),+ },+ });+ setUnsaved();+ }}+ size="small"+ className="w-full max-w-[250px]"+ // eslint-disable-next-line i18next/no-literal-string -- example URL, not copy+ placeholder="https://api.telegram.org"+ />+ </AdvancedFieldRowComponent>++ <AdvancedFieldRowComponent+ label={t('notifiers.telegram.useProxy')}+ tooltip={t('notifiers.telegram.useProxyTooltip')}+ >+ <Switch+ checked={notifier?.telegramNotifier?.isProxyEnabled || false}+ onChange={(checked) => {+ if (!notifier?.telegramNotifier) return;++ setNotifier({+ ...notifier,+ telegramNotifier: {+ ...notifier.telegramNotifier,+ isProxyEnabled: checked,+ proxyUrl: checked ? notifier.telegramNotifier.proxyUrl : undefined,+ },+ });+ setUnsaved();+ }}+ size="small"+ />+ </AdvancedFieldRowComponent>++ {notifier?.telegramNotifier?.isProxyEnabled && (+ <AdvancedFieldRowComponent+ label={t('notifiers.telegram.proxyUrl')}+ tooltip={t('notifiers.telegram.proxyUrlTooltip')}+ >+ <Input+ value={notifier?.telegramNotifier?.proxyUrl || ''}+ onChange={(e) => {+ if (!notifier?.telegramNotifier) return;++ setNotifier({+ ...notifier,+ telegramNotifier: {+ ...notifier.telegramNotifier,+ proxyUrl: e.target.value.trim(),+ },+ });+ setUnsaved();+ }}+ size="small"+ className="w-full max-w-[250px]"+ // eslint-disable-next-line i18next/no-literal-string -- example proxy URL+ placeholder="socks5://user:pass@host:1080"+ />+ </AdvancedFieldRowComponent>+ )}+ </>+ )}</>);}diff --git a/frontend/src/features/notifiers/ui/show/notifier/ShowTelegramNotifierComponent.test.tsx b/frontend/src/features/notifiers/ui/show/notifier/ShowTelegramNotifierComponent.test.tsxnew file mode 100644index 00000000..9177fa67--- /dev/null+++ b/frontend/src/features/notifiers/ui/show/notifier/ShowTelegramNotifierComponent.test.tsx@@ -0,0 +1,56 @@+import { renderToStaticMarkup } from 'react-dom/server';+import { describe, expect, it, vi } from 'vitest';++import {+ type Notifier,+ NotifierType,+ type TelegramNotifier,+} from '../../../../../entity/notifiers';+import { LocaleProvider } from '../../../../../shared/i18n';+import { ShowTelegramNotifierComponent } from './ShowTelegramNotifierComponent';++// The entity's public API imports its API client, and the client's config+// module reads window at import time. The tests run in node, so they supply+// window. LocaleProvider then reads localStorage, which here reports no saved+// language.+vi.hoisted(() => {+ vi.stubGlobal('window', {});+ vi.stubGlobal('localStorage', { getItem: () => null });+ vi.stubGlobal('navigator', { language: 'en-US', languages: ['en-US'] });+});++const createTelegramNotifier = (change: Partial<TelegramNotifier>): Notifier => ({+ id: 'notifier-id',+ name: 'Telegram',+ notifierType: NotifierType.TELEGRAM,+ workspaceId: 'workspace-id',+ telegramNotifier: {+ botToken: '',+ targetChatId: '-1001234567890',+ ...change,+ },+});++const renderTelegramView = (notifier: Notifier) =>+ renderToStaticMarkup(+ <LocaleProvider>+ <ShowTelegramNotifierComponent notifier={notifier} />+ </LocaleProvider>,+ );++describe('ShowTelegramNotifierComponent', () => {+ it('shows the Bot API URL when it is set', () => {+ const markup = renderTelegramView(+ createTelegramNotifier({ botApiUrl: 'https://gateway.example.com/telegram' }),+ );++ expect(markup).toContain('Bot API URL');+ expect(markup).toContain('https://gateway.example.com/telegram');+ });++ it('omits the Bot API URL when the official API is used', () => {+ const markup = renderTelegramView(createTelegramNotifier({}));++ expect(markup).not.toContain('Bot API URL');+ });+});diff --git a/frontend/src/features/notifiers/ui/show/notifier/ShowTelegramNotifierComponent.tsx b/frontend/src/features/notifiers/ui/show/notifier/ShowTelegramNotifierComponent.tsxindex 2a70e0a5..0e5dee9e 100644--- a/frontend/src/features/notifiers/ui/show/notifier/ShowTelegramNotifierComponent.tsx+++ b/frontend/src/features/notifiers/ui/show/notifier/ShowTelegramNotifierComponent.tsx@@ -29,6 +29,13 @@ export function ShowTelegramNotifierComponent({ notifier }: Props) {</div>)}+ {notifier?.telegramNotifier?.botApiUrl && (+ <div className="mb-1 flex items-center">+ <div className="min-w-[110px] pr-2">{t('notifiers.telegram.botApiUrl')}</div>+ {notifier.telegramNotifier.botApiUrl}+ </div>+ )}+{notifier?.telegramNotifier?.isProxyEnabled && (<div className="mb-1 flex items-center"><div className="min-w-[110px] pr-2">{t('notifiers.telegram.proxy')}</div>diff --git a/frontend/src/shared/i18n/locales/en.ts b/frontend/src/shared/i18n/locales/en.tsindex 762921c4..0e908cb8 100644--- a/frontend/src/shared/i18n/locales/en.ts+++ b/frontend/src/shared/i18n/locales/en.ts@@ -1113,6 +1113,7 @@ export const en = {},},notifiers: {+ advancedSettings: 'Advanced settings',types: {email: 'Email',telegram: 'Telegram',@@ -1211,7 +1212,6 @@ export const en = {fromTooltip:'Optional. Sender address, with or without a name: Acme Backups <[email protected]>. If empty, the SMTP user is used when it is an email address, otherwise noreply@ and the SMTP host',fromAuto: '(auto)',- advancedSettings: 'Advanced settings',skipTlsTooltip:'Skip TLS certificate verification. Enable this if your SMTP server uses a self-signed certificate. Warning: this reduces security.',security: 'Connection security',@@ -1238,6 +1238,9 @@ export const en = {group:'If you want to get chat ID of a group, add your bot with <botLink>@getmyid_bot</botLink> to the group and write /start (you will see chat ID)',},+ botApiUrl: 'Bot API URL',+ botApiUrlTooltip:+ 'Optional. A self-hosted Telegram Bot API server or a reverse proxy in front of the Telegram API. If empty, the official Telegram API is used. This server receives the bot token. A bot has to log out of the official API before it works with a self-hosted server',useProxy: 'Use proxy',useProxyTooltip: 'Use a proxy for Telegram API requests',proxy: 'Proxy',diff --git a/frontend/src/shared/i18n/locales/es.ts b/frontend/src/shared/i18n/locales/es.tsindex e11fc514..e9fd21eb 100644--- a/frontend/src/shared/i18n/locales/es.ts+++ b/frontend/src/shared/i18n/locales/es.ts@@ -1139,6 +1139,7 @@ export const es: typeof en = {},},notifiers: {+ advancedSettings: 'Ajustes avanzados',types: {email: 'Correo electrónico',telegram: 'Telegram',@@ -1238,7 +1239,6 @@ export const es: typeof en = {fromTooltip:'Opcional. Dirección del remitente, con o sin nombre: Acme Backups <[email protected]>. Si se deja vacía, se usa el usuario SMTP cuando es una dirección de correo y, si no, noreply@ con el host SMTP',fromAuto: '(automático)',- advancedSettings: 'Ajustes avanzados',skipTlsTooltip:'No verifica el certificado TLS. Active esta opción si su servidor SMTP usa un certificado autofirmado. Advertencia: esto reduce la seguridad.',security: 'Seguridad de la conexión',@@ -1265,6 +1265,9 @@ export const es: typeof en = {group:'Para obtener el ID de un chat de grupo, añada al grupo su bot y <botLink>@getmyid_bot</botLink> y escriba /start (verá el ID del chat)',},+ botApiUrl: 'URL de Bot API',+ botApiUrlTooltip:+ 'Opcional. Un servidor propio de Telegram Bot API o un proxy inverso delante de la API de Telegram. Si lo deja vacío, se usa la API oficial de Telegram. Este servidor recibe el token del bot. Antes de usar un servidor propio, cierre la sesión del bot en la API oficial con el método logOut',useProxy: 'Usar proxy',useProxyTooltip: 'Usa un proxy para las solicitudes a la API de Telegram',proxy: 'Proxy',diff --git a/frontend/src/shared/i18n/locales/fr.ts b/frontend/src/shared/i18n/locales/fr.tsindex f0f1a21b..b2f0b745 100644--- a/frontend/src/shared/i18n/locales/fr.ts+++ b/frontend/src/shared/i18n/locales/fr.ts@@ -1147,6 +1147,7 @@ export const fr: typeof en = {},},notifiers: {+ advancedSettings: 'Paramètres avancés',types: {email: 'E-mail',telegram: 'Telegram',@@ -1246,7 +1247,6 @@ export const fr: typeof en = {fromTooltip:"Facultatif. Adresse de l'expéditeur, avec ou sans nom : Acme Backups <[email protected]>. Si le champ est vide, l'utilisateur SMTP est utilisé s'il s'agit d'une adresse e-mail, sinon noreply@ suivi de l'hôte SMTP",fromAuto: '(automatique)',- advancedSettings: 'Paramètres avancés',skipTlsTooltip:'Ne pas vérifier le certificat TLS. Activez cette option si votre serveur SMTP utilise un certificat auto-signé. Attention : cela réduit la sécurité.',security: 'Sécurité de la connexion',@@ -1273,6 +1273,9 @@ export const fr: typeof en = {group:"Pour obtenir l'ID d'un groupe, ajoutez votre bot et <botLink>@getmyid_bot</botLink> au groupe, puis écrivez /start (l'ID du chat s'affichera)",},+ botApiUrl: 'URL de la Bot API',+ botApiUrlTooltip:+ "Facultatif. Un serveur Telegram Bot API auto-hébergé ou un proxy inverse placé devant l'API Telegram. S'il est vide, l'API officielle de Telegram est utilisée. Ce serveur reçoit le jeton du bot. Avant de passer à un serveur auto-hébergé, déconnectez le bot de l'API officielle avec la méthode logOut",useProxy: 'Utiliser un proxy',useProxyTooltip: "Passer par un proxy pour les requêtes vers l'API Telegram",proxy: 'Proxy',diff --git a/frontend/src/shared/i18n/locales/pt.ts b/frontend/src/shared/i18n/locales/pt.tsindex 6bce1ee3..f4850e40 100644--- a/frontend/src/shared/i18n/locales/pt.ts+++ b/frontend/src/shared/i18n/locales/pt.ts@@ -1133,6 +1133,7 @@ export const pt: typeof en = {},},notifiers: {+ advancedSettings: 'Configurações avançadas',types: {email: 'E-mail',telegram: 'Telegram',@@ -1230,7 +1231,6 @@ export const pt: typeof en = {fromTooltip:'Opcional. Endereço do remetente, com ou sem nome: Acme Backups <[email protected]>. Se ficar vazio, será usado o usuário SMTP quando ele for um endereço de e-mail; caso contrário, noreply@ com o host SMTP',fromAuto: '(automático)',- advancedSettings: 'Configurações avançadas',skipTlsTooltip:'Não verifica o certificado TLS. Ative se o seu servidor SMTP usa um certificado autoassinado. Atenção: isso reduz a segurança.',security: 'Segurança da conexão',@@ -1257,6 +1257,9 @@ export const pt: typeof en = {group:'Para obter o ID do chat de um grupo, adicione ao grupo o seu bot e o <botLink>@getmyid_bot</botLink> e envie /start (o ID do chat vai aparecer)',},+ botApiUrl: 'URL da Bot API',+ botApiUrlTooltip:+ 'Opcional. Um servidor próprio do Telegram Bot API ou um proxy reverso na frente da API do Telegram. Se ficar vazio, é usada a API oficial do Telegram. Esse servidor recebe o token do bot. Antes de usar um servidor próprio, encerre a sessão do bot na API oficial com o método logOut',useProxy: 'Usar proxy',useProxyTooltip: 'Usa um proxy para as requisições à API do Telegram',proxy: 'Proxy',diff --git a/frontend/src/shared/i18n/locales/ru.ts b/frontend/src/shared/i18n/locales/ru.tsindex b475b4fe..2ef3e63c 100644--- a/frontend/src/shared/i18n/locales/ru.ts+++ b/frontend/src/shared/i18n/locales/ru.ts@@ -1118,6 +1118,7 @@ export const ru: typeof en = {},},notifiers: {+ advancedSettings: 'Дополнительные настройки',types: {email: 'Email',telegram: 'Telegram',@@ -1215,7 +1216,6 @@ export const ru: typeof en = {fromTooltip:'Необязательно. Адрес отправителя, можно с именем: Acme Backups <[email protected]>. Если поле пустое, используется пользователь SMTP, когда это адрес почты, а иначе noreply@ и хост SMTP',fromAuto: '(автоматически)',- advancedSettings: 'Дополнительные настройки',skipTlsTooltip:'Не проверять TLS-сертификат. Включите, если SMTP-сервер использует самоподписанный сертификат. Внимание: это снижает безопасность.',security: 'Защита соединения',@@ -1241,6 +1241,9 @@ export const ru: typeof en = {group:'Чтобы узнать ID группы, добавьте в нее своего бота и <botLink>@getmyid_bot</botLink>, затем напишите /start — появится ID чата',},+ botApiUrl: 'URL Bot API',+ botApiUrlTooltip:+ 'Необязательно. Адрес своего сервера Telegram Bot API или reverse proxy перед Telegram API. Если поле пустое, используется официальный Telegram API. Этот сервер получает токен бота. Чтобы бот заработал через свой сервер, сначала выведите его из официального API методом logOut',useProxy: 'Использовать прокси',useProxyTooltip: 'Отправлять запросы к Telegram API через прокси',proxy: 'Прокси',diff --git a/frontend/src/shared/i18n/locales/zh.ts b/frontend/src/shared/i18n/locales/zh.tsindex f935664a..603006b2 100644--- a/frontend/src/shared/i18n/locales/zh.ts+++ b/frontend/src/shared/i18n/locales/zh.ts@@ -1074,6 +1074,7 @@ export const zh: typeof en = {},},notifiers: {+ advancedSettings: '高级设置',types: {email: '邮件',telegram: 'Telegram',@@ -1167,7 +1168,6 @@ export const zh: typeof en = {fromTooltip:'可选。发件人地址,可以带名称:Acme Backups <[email protected]>。留空时,如果 SMTP 用户是邮箱地址就使用它,否则使用 noreply@ 加 SMTP 主机',fromAuto: '(自动)',- advancedSettings: '高级设置',skipTlsTooltip:'跳过 TLS 证书验证。如果 SMTP 服务器使用自签名证书,请开启此项。警告:这会降低安全性。',security: '连接安全',@@ -1193,6 +1193,9 @@ export const zh: typeof en = {group:'要获取群组的聊天 ID,请把你的机器人和 <botLink>@getmyid_bot</botLink> 一起加入群组,然后发送 /start(你会看到聊天 ID)',},+ botApiUrl: 'Bot API URL',+ botApiUrlTooltip:+ '可选。自建的 Telegram Bot API 服务器,或 Telegram API 前面的反向代理。留空时使用官方 Telegram API。该服务器会收到机器人令牌。切换到自建服务器之前,需要先用 logOut 方法让机器人从官方 API 登出',useProxy: '使用代理',useProxyTooltip: '通过代理发送 Telegram API 请求',proxy: '代理',diff --git a/frontend/src/shared/ui/AdvancedFieldRowComponent.tsx b/frontend/src/shared/ui/AdvancedFieldRowComponent.tsxnew file mode 100644index 00000000..fb30d9f2--- /dev/null+++ b/frontend/src/shared/ui/AdvancedFieldRowComponent.tsx@@ -0,0 +1,22 @@+import { InfoCircleOutlined } from '@ant-design/icons';+import { Tooltip } from 'antd';+import type { ReactNode } from 'react';++interface Props {+ label: string;+ tooltip: string;+ children: ReactNode;+}++export const AdvancedFieldRowComponent = ({ label, tooltip, children }: Props) => (+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">+ <div className="mb-1 min-w-[150px] sm:mb-0 sm:pr-2">{label}</div>+ <div className="flex items-center">+ {children}++ <Tooltip className="cursor-pointer" title={tooltip}>+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ </div>+);diff --git a/frontend/src/shared/ui/AdvancedSettingsToggleComponent.tsx b/frontend/src/shared/ui/AdvancedSettingsToggleComponent.tsxnew file mode 100644index 00000000..d42191dd--- /dev/null+++ b/frontend/src/shared/ui/AdvancedSettingsToggleComponent.tsx@@ -0,0 +1,24 @@+import { DownOutlined, UpOutlined } from '@ant-design/icons';++interface Props {+ label: string;+ isShowAdvanced: boolean;+ onToggle: () => void;+}++export const AdvancedSettingsToggleComponent = ({ label, isShowAdvanced, onToggle }: Props) => (+ <div className="mt-4 mb-1 flex items-center">+ <div+ className="flex cursor-pointer items-center text-sm text-blue-600 hover:text-blue-800"+ onClick={onToggle}+ >+ <span className="mr-2">{label}</span>++ {isShowAdvanced ? (+ <UpOutlined style={{ fontSize: '12px' }} />+ ) : (+ <DownOutlined style={{ fontSize: '12px' }} />+ )}+ </div>+ </div>+);diff --git a/frontend/src/shared/ui/index.ts b/frontend/src/shared/ui/index.tsindex 1f1286c3..26f2bb6c 100644--- a/frontend/src/shared/ui/index.ts+++ b/frontend/src/shared/ui/index.ts@@ -1,3 +1,5 @@+export { AdvancedFieldRowComponent } from './AdvancedFieldRowComponent';+export { AdvancedSettingsToggleComponent } from './AdvancedSettingsToggleComponent';export { ClipboardPasteModalComponent } from './ClipboardPasteModalComponent';export { CloudflareTurnstileWidget } from './CloudflareTurnstileWidget';export { ConfirmationComponent } from './ConfirmationComponent';diff --git a/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/.openspec.yaml b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/.openspec.yamlnew file mode 100644index 00000000..53f62d70--- /dev/null+++ b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/.openspec.yaml@@ -0,0 +1,2 @@+schema: spec-driven+created: 2026-10-10diff --git a/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/design.md b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/design.mdnew file mode 100644index 00000000..a3a33c7a--- /dev/null+++ b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/design.md@@ -0,0 +1,115 @@+## Context++See proposal.md - Why for the motivation and specs/telegram-notifier-endpoint/spec.md for the required behavior.++The Telegram notifier builds its request address from a constant host: `backend/internal/features/notifiers/models/telegram/model.go:75` formats `https://api.telegram.org/bot%s/sendMessage`. Everything else the change needs already exists and only has to accept a second host:++- The notifier's HTTP client comes from `buildHTTPClient` in `backend/internal/features/notifiers/models/telegram/proxies.go:22`. Without a proxy it leaves `Transport` nil, so the default transport applies the proxy environment variables to whatever host the request names.+- Save, update and a direct test send for a saved notifier merge the incoming notifier, encrypt it and call `Validate` before anything is stored or sent (`backend/internal/features/notifiers/service.go:59-67`, `:97-101`, `:264-270`). A direct test send for a notifier that has not been saved yet only encrypts it and sends (`service.go:276-285`), so `Validate` alone does not guard that path.+- A transport error passes through `notifier_models.ErrorWithoutWebhookURLCredentials` (`model.go:100`) before it becomes the notifier's `LastSendError` (`backend/internal/features/notifiers/model.go:60-64`). `redactPathSecrets` in `backend/internal/features/notifiers/models/url_credentials.go:49` keeps only the first path segment and strips the token from a fused `bot<token>` segment, so a prefixed path such as `/telegram/bot<token>/sendMessage` is already redacted.+- A non-200 response is reported with its body verbatim (`model.go:107-111`). That body comes from whatever server the URL names.+- The email notifier's form already has a collapsible advanced section. Its row layout, `AdvancedFieldRowComponent`, is a private function at the bottom of `frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsx:284`, and the toggle header is inline markup at `:188-201`.+- The proxy columns were added by `backend/migrations/20260622120000_add_telegram_proxy.sql` as `is_proxy_enabled BOOLEAN NOT NULL DEFAULT FALSE` and a nullable `proxy_url TEXT` mapped to a Go `string`.++## Goals / Non-Goals++**Goals:**++- One optional field on the Telegram notifier decides the server; empty keeps today's behavior byte for byte.+- The same validation rules in the backend and in the form, so the form never offers a save the API rejects.+- No path through which the bot token reaches `LastSendError`, the logs or a test-send response, whichever server answers.++**Non-Goals:**++- Changing the request itself: method, form encoding, `parse_mode`, topic handling and timeout stay as they are.+- A shared "custom API base URL" abstraction for other notifiers.++## Decisions++### 1. A per-notifier field, not an environment variable++The URL is a column on `telegram_notifiers`, edited in the Telegram form.++- *Rejected: `TELEGRAM_API_URL` in the process environment*, as the issue proposed. It needs a container restart to change, cannot be seen or tested from the form, applies to every notifier in every workspace at once, and would be the only notifier setting that lives outside the notifier. The proxy, the closest existing setting, is already per notifier.++### 2. Empty means the official API; no separate switch++The field `BotAPIURL string` (`json:"botApiUrl"`, column `bot_api_url`) is empty by default, and an empty value sends to `https://api.telegram.org`.++- *Rejected: an `IsCustomBotAPIEnabled` switch plus a URL, like the proxy.* The proxy needs the switch because its URL is encrypted and hidden, so the form cannot tell "unchanged" from "cleared" by the field alone. The Bot API URL is returned in clear (decision 3), so the field itself is the state, and a switch would be a second source of truth.+- *Rejected: prefilling `https://api.telegram.org` into the field.* Every existing row would need a data migration, and a stored default would stop following the code if the default ever changed.++### 3. Stored and returned in clear, credentials rejected++The URL is not encrypted, `HideSensitiveData` leaves it alone, and `Validate` rejects a URL whose user info is set.++- *Rejected: encrypting it like the proxy URL.* That would allow basic auth for a reverse proxy, but the URL could no longer be shown, the form would need the proxy's "unchanged vs cleared" dance, and the user explicitly chose the simpler form. Rejecting user info is what makes storing in clear safe: the only secret on the request is the bot token, which stays encrypted in its own column.++### 4. Validation in a dedicated parser next to the proxy parser++A new `validateBotAPIURL` in `backend/internal/features/notifiers/models/telegram/bot_api_url.go` accepts `http`/`https`, requires a host, and rejects user info, a raw query and a fragment. `Validate` calls it when the field is set, and `Send` calls it again before building the request address, the way `buildHTTPClient` re-parses the proxy URL. The second call is what covers the direct test send of an unsaved notifier, which skips `Validate`: an invalid URL fails the send with the same error instead of reaching the network. The frontend mirrors the rules in `validateTelegramNotifier.ts` with `new URL()`.++- *Rejected: adding `Validate` to the unsaved direct test send.* It would change that path for every notifier type, which is outside this change.++- *Rejected: reusing `parseProxyURL`.* Its scheme list includes `socks5` and `socks5h`, and it allows user info, both wrong for an API endpoint.+- *Rejected: also blocking private and loopback addresses.* A self-hosted Bot API server is normally on the same Docker network or on `localhost`, which is the main use case. The webhook notifier already sends to any address, so a block here would add friction without closing anything.++### 5. Build the address by trimming the trailing slash at send time++`Send` joins `strings.TrimRight(baseURL, "/")` with `/bot<token>/sendMessage`. The value is stored exactly as entered (after the form trims whitespace).++- *Rejected: normalizing on save.* It would mutate user input in `Update` and `EncryptSensitiveData`, and `Send` would still need to be safe for rows written before or around the normalization. One place that builds the address is simpler.+- *Rejected: `url.JoinPath`.* It removes `./` and `../` elements from the joined path, so the request could go to a different path than the one the user entered and validation accepted. Concatenation sends exactly the validated prefix.++### 6. Strip the bot token from a non-OK response body++Before the response body goes into the returned error, every occurrence of the decrypted bot token is replaced with the `redacted` marker. The marker is the unexported `redactedURLSegment` in `backend/internal/features/notifiers/models/url_credentials.go:10`, which the `telegram_notifier` package cannot reach, so `notifier_models` gets a small exported `RedactSecretInText(text, secret string) string` beside it. Every redaction then uses the same marker, and the constant stays private.++The redaction happens inside `TelegramNotifier.Send`, which both the test sends and the scheduled sends call, so the test-send response and `LastSendError` carry the same redacted text.++- *Rejected: keeping the body verbatim.* The official API never echoes the request path, but an arbitrary reverse proxy can: an Express-style "Cannot POST /bot<token>/sendMessage" page, or a gateway that echoes the upstream URL, would put the token into `LastSendError` and the test-send response. The spec forbids that.+- *Rejected: dropping the body.* It holds Telegram's own explanation, such as "chat not found", which users need to fix their settings.++### 7. Nullable `TEXT` column, matching `proxy_url`++The migration adds `bot_api_url TEXT` with no default, through a stub created by `goose -dir backend/migrations create add_telegram_bot_api_url sql`.++- *Rejected: `TEXT NOT NULL DEFAULT ''`.* Either works with a Go `string`; the nullable form matches the sibling `proxy_url` column, so the table reads consistently.++### 8. Advanced-section components move to `shared/ui`++`frontend/src/features/databases/ui/edit/AdvancedSettingsToggleComponent.tsx` already renders the toggle header the email form repeats inline, but it hard-codes the `databases.edit.advancedSettings` key. It moves to `frontend/src/shared/ui/AdvancedSettingsToggleComponent.tsx` and takes the label as a prop. `AdvancedFieldRowComponent` moves out of the email form into `frontend/src/shared/ui/AdvancedFieldRowComponent.tsx`. Both are exported from `shared/ui/index.ts`. The five database forms, the email form and the Telegram form use them, and the inline header in the email form is deleted.++The Telegram toggle label comes from a new `notifiers.advancedSettings` key, which replaces `notifiers.email.advancedSettings`, so both notifier forms read one key. The Telegram form's section starts open when `botApiUrl` is set or `isProxyEnabled` is true. The proxy switch and proxy URL move into the section unchanged.++The shared header uses the database forms' spacing (`mb-1`), so the gap under the email form's header shrinks from `mb-3` to `mb-1`. That is the only visible change to existing forms.++- *Rejected: a notifier-only copy under `features/notifiers`.* It would be the third copy of the same header, beside the database one and the inline email one.+- *Rejected: importing the component from `features/databases`.* The frontend FSD rules forbid cross-imports between slices of the same layer; `shared/ui` is the layer both can import.+- *Rejected: also replacing the inline headers in the storage and logical backup forms.* They are outside the code this task touches; the shared component makes that a mechanical follow-up.++### 9. Testing through the controller with a local server++Controller tests in `backend/internal/features/notifiers/controller_test.go` use `httptest` servers as the Bot API server and as a proxy:++- A saved notifier whose Bot API URL is the server with a path prefix and a trailing slash, sent through `POST /notifiers/:id/test`, delivers `/<prefix>/bot<token>/sendMessage` with the notifier's `chat_id`.+- An unsaved notifier sent through `POST /notifiers/direct-test` reaches the server the same way. With an invalid URL or a URL with user info, the direct test returns an error and the server records no request.+- A notifier with both a Bot API URL and a proxy pointing at an `httptest` proxy makes the proxy receive the request for the Bot API URL.+- A server that answers 404 with a body echoing the request path yields an error that keeps the body with `redacted` in place of the token.+- A Bot API URL with a prefix pointing at a closed server yields an error that names the host and not the token.+- Saving an invalid or credential-bearing URL is rejected and the stored notifier is unchanged; reading a notifier returns `botApiUrl` in clear while the token and proxy URL stay empty.++Unit tests in `model_test.go` cover the rules of `Validate` as table tests beside the existing proxy `Validate` tests, and the address an empty Bot API URL produces (`https://api.telegram.org/bot<token>/sendMessage`), which no controller test can reach without calling Telegram. `url_credentials_test.go` covers `RedactSecretInText`. On the frontend, `validateTelegramNotifier.test.ts` covers the URL rules, and render tests with `renderToStaticMarkup`, the pattern `PhysicalBackupTypeCellComponent.test.tsx` uses, check that the Telegram form starts with the advanced section collapsed for a new notifier and expanded with a proxy or a Bot API URL, and that the read-only view shows the Bot API URL.++- *Rejected: unit-testing only the address builder.* The controller test covers merge, encryption, validation and sending in one pass, which is the contract the user relies on, and `backend/AGENTS.md` prefers controller tests.++## Risks / Trade-offs++- [The bot token goes to whatever server the URL names, over plain `http` if the user chooses it] → This is the feature: the user points their own bot at their own server. The tooltip says the URL receives the bot token, and the user decided against a further warning.+- [A user with edit rights on notifiers can make the backend send POST requests to an internal address] → The webhook notifier already allows the same, so no new exposure is added; recorded so a later SSRF policy covers both.+- [A self-hosted Bot API server rejects a bot still logged in to the official API] → The tooltip mentions that a bot must be moved to the self-hosted server first; Telegram's error reaches the user through the response body.+- [Moving the proxy into a collapsed section hides it from users who look for it] → The section opens on its own whenever a proxy is enabled, so existing users see it in the same place they configure it.++## Migration Plan++The migration only adds a nullable column, so it runs online and existing rows keep sending to the official API. Rolling back drops the column; a notifier that relied on a custom server then sends to the official API again, which matches the code being rolled back.diff --git a/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/proposal.md b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/proposal.mdnew file mode 100644index 00000000..16c6fab8--- /dev/null+++ b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/proposal.md@@ -0,0 +1,44 @@+## Why++A Telegram notifier always sends to `https://api.telegram.org`. People who run their own Telegram Bot API server, or who reach Telegram through a reverse proxy because the official address is blocked or filtered in their network, cannot use the Telegram notifier at all. The per-notifier proxy setting does not help them: it routes traffic through a forward proxy but still targets the official host.++The issue that raised this asks for a process-wide environment variable. A per-notifier setting fits better. It is edited in the same form as the bot token and the proxy, it takes effect without restarting the container, and two notifiers can point at different servers.++## What Changes++- A Telegram notifier gets an optional Bot API URL. When it is empty, the notifier sends to the official Telegram API as today. When it is set, the notifier sends `sendMessage` to that server instead, keeping the standard `/bot<token>/sendMessage` path under it.+- The URL is validated on save and on test send, in the backend and in the form: `http` or `https` only, a host is required, a path prefix is allowed, and a username or password, a query string or a fragment is rejected. A trailing slash is accepted and does not produce a double slash in the request.+- The URL is not a secret. It is stored as entered, returned by the API and shown on the notifier's page. Because credentials are rejected, nothing secret can end up in it.+- The Telegram form gets a collapsible "Advanced settings" section, like the email notifier's. The new Bot API URL field and the existing proxy switch and proxy URL move into it. The section opens on its own when the notifier already has a Bot API URL or a proxy.+- The advanced-settings toggle that the database forms already use moves to the shared UI layer and serves the database, email and Telegram forms, instead of a third copy.+- The new label and tooltip are added to all six interface dictionaries.++Nothing here is BREAKING. Existing notifiers get an empty Bot API URL and keep sending to the official API, and the API only gains an optional field.++## Capabilities++### New Capabilities++- `telegram-notifier-endpoint`: where a Telegram notifier sends its messages, which Bot API URLs it accepts, and how the URL is stored and shown.++### Modified Capabilities++None. The `outbound-http-proxy` requirements keep holding as written: a notifier with its own proxy still uses it, and a notifier without one still follows the proxy environment variables, now for whichever host its Bot API URL names.++## Out of scope++- A process-wide `TELEGRAM_API_URL` environment variable, as the issue proposed. The per-notifier field replaces it.+- Credentials in the Bot API URL, such as basic auth for a reverse proxy. Supporting them would mean encrypting the URL and hiding it like the proxy URL.+- A warning or a restriction for plain `http` URLs. A self-hosted server on the same Docker network is usually reached over `http`, and the user chose not to add a warning.+- Blocking private or internal addresses. The webhook notifier already lets a user send requests to any address, so this field adds no new kind of exposure.+- Guiding the user through moving a bot from the official API to a self-hosted server (the `logOut` call), beyond a mention in the tooltip.+- Other Telegram methods or features, and custom API URLs for other notifiers.+- The website's advanced configuration page, which documents environment variables and gains none here.++## Impact++- **Module rules this change answers to:** the root `AGENTS.md`, `backend/AGENTS.md` and `frontend/AGENTS.md`.+- **Database:** one migration adds a nullable `bot_api_url` column to `telegram_notifiers`.+- **Backend:** the Telegram notifier model in `backend/internal/features/notifiers/models/telegram/` (field, validation, update, sending), its unit tests and the notifier controller tests.+- **API:** create, update, read and test-send of a Telegram notifier carry an optional `botApiUrl`.+- **Frontend:** the Telegram notifier type, its validation and tests, the edit form and the read-only view, plus the six dictionaries under `frontend/src/shared/i18n/locales/`. The advanced-settings toggle and field row move to `frontend/src/shared/ui/`, so the five database forms and the email form switch to the shared components; the email form's header gets the database forms' slightly smaller bottom spacing.diff --git a/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/specs/telegram-notifier-endpoint/spec.md b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/specs/telegram-notifier-endpoint/spec.mdnew file mode 100644index 00000000..c7616e85--- /dev/null+++ b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/specs/telegram-notifier-endpoint/spec.md@@ -0,0 +1,106 @@+## Purpose++Lets a Telegram notifier deliver messages through a self-hosted Telegram Bot API server or a reverse proxy instead of the official Telegram API, and defines which addresses it accepts and how the address is shown.++## ADDED Requirements++### Requirement: A Telegram notifier sends to its Bot API URL or to the official API++A Telegram notifier SHALL have an optional Bot API URL. When the URL is empty, the notifier SHALL send its messages to the official Telegram Bot API at `https://api.telegram.org`. When the URL is set, the notifier SHALL send its messages to that server instead, with the standard Bot API path for sending a message appended to the URL, including any path prefix the URL has. A trailing slash in the URL SHALL NOT change the address the request is sent to. This SHALL hold for scheduled notifications and for test notifications alike, and a notifier with a proxy enabled SHALL reach the Bot API URL through that proxy.++#### Scenario: Notifier without a Bot API URL++- **WHEN** a Telegram notifier has no Bot API URL and sends a notification+- **THEN** the message is sent to the official Telegram Bot API, as before this change++#### Scenario: Notifier with a self-hosted server++- **WHEN** a Telegram notifier has the Bot API URL `http://telegram-bot-api:8081` and sends a notification+- **THEN** the message is sent to `http://telegram-bot-api:8081/bot<token>/sendMessage` with the notifier's chat, topic and text++#### Scenario: Bot API URL with a path prefix and a trailing slash++- **WHEN** a Telegram notifier has the Bot API URL `https://gateway.example.com/telegram/` and sends a notification+- **THEN** the message is sent to `https://gateway.example.com/telegram/bot<token>/sendMessage`++#### Scenario: Test notification uses the Bot API URL from the form++- **WHEN** the user enters a Bot API URL in the Telegram form and sends a test notification before saving+- **THEN** the test message is sent to the entered server++#### Scenario: Bot API URL together with a proxy++- **WHEN** a Telegram notifier has both a Bot API URL and a proxy enabled+- **THEN** the message is sent to the Bot API URL through the configured proxy++#### Scenario: Existing notifiers after the upgrade++- **WHEN** Databasus is upgraded and a Telegram notifier created before the upgrade sends a notification+- **THEN** the notifier has no Bot API URL and the message is sent to the official Telegram Bot API++### Requirement: Only a plain HTTP or HTTPS address is accepted as a Bot API URL++Saving a Telegram notifier and sending a test notification SHALL be rejected with an error when the Bot API URL is set and does not satisfy all of these: the scheme is `http` or `https`, the URL has a host, and it has no query string and no fragment. A path prefix SHALL be accepted. The form SHALL refuse to save or test the notifier under the same conditions. An empty Bot API URL SHALL always be accepted.++#### Scenario: Unsupported scheme++- **WHEN** the user saves a Telegram notifier with the Bot API URL `ftp://telegram.example.com`+- **THEN** the save is rejected and the notifier keeps its previous settings++#### Scenario: Address without a host++- **WHEN** the user saves a Telegram notifier with the Bot API URL `telegram-bot-api:8081` or `https://`+- **THEN** the save is rejected++#### Scenario: Query string or fragment++- **WHEN** the user saves a Telegram notifier with the Bot API URL `https://gateway.example.com/telegram?key=1` or `https://gateway.example.com/#bot`+- **THEN** the save is rejected++#### Scenario: Test send of an unsaved notifier with an invalid address++- **WHEN** the user sends a test notification from the form for a Telegram notifier that has not been saved yet and whose Bot API URL is `ftp://telegram.example.com` or `https://user:[email protected]`+- **THEN** the test send returns an error and no request leaves the backend++#### Scenario: Valid addresses++- **WHEN** the user saves a Telegram notifier with the Bot API URL `http://localhost:8081`, `https://gateway.example.com` or `https://gateway.example.com/telegram/`+- **THEN** the notifier is saved with that URL++### Requirement: The Bot API URL holds no credentials and stays visible++A Bot API URL that contains a username or a password SHALL be rejected, on save and on test send, in the API and in the form. Because the URL then holds no secret, it SHALL be stored as entered, returned when the notifier is read and shown on the notifier's page, unlike the bot token and the proxy URL, which stay hidden. Errors from a failed send, whether stored as the notifier's last error, written to logs or returned by a test send, SHALL NOT contain the bot token when the notifier uses a Bot API URL, including one with a path prefix.++#### Scenario: Credentials in the URL++- **WHEN** the user saves a Telegram notifier with the Bot API URL `https://user:[email protected]`+- **THEN** the save is rejected++#### Scenario: Reading a notifier with a Bot API URL++- **WHEN** the user opens a Telegram notifier whose Bot API URL is `https://gateway.example.com/telegram`+- **THEN** the page shows that URL, while the bot token and the proxy URL stay hidden++#### Scenario: Send fails against a custom server++- **WHEN** a Telegram notifier with the Bot API URL `https://gateway.example.com/telegram` fails to connect to that server+- **THEN** the reported error names the host but does not contain the bot token++#### Scenario: Custom server echoes the request path in an error response++- **WHEN** the server at the Bot API URL answers with a non-OK status and a body such as `Cannot POST /telegram/bot<token>/sendMessage`+- **THEN** the reported error, whether returned by a test send or stored as the notifier's last error, keeps the body with `redacted` in place of the bot token++### Requirement: Bot API URL and proxy live in the advanced settings of the Telegram form++The Telegram notifier form SHALL show the Bot API URL field, the proxy switch and the proxy URL in a collapsible advanced settings section. The section SHALL start expanded when the notifier being edited has a Bot API URL or a proxy enabled, and collapsed otherwise. The bot token, the chat ID and the topic settings SHALL stay outside the section.++#### Scenario: New notifier++- **WHEN** the user creates a Telegram notifier+- **THEN** the advanced settings section is collapsed and the bot token, chat ID and topic settings are visible++#### Scenario: Editing a notifier with a proxy++- **WHEN** the user edits a Telegram notifier that has a proxy enabled or a Bot API URL set+- **THEN** the advanced settings section is expanded and shows those valuesdiff --git a/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/tasks.md b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/tasks.mdnew file mode 100644index 00000000..44a42ed4--- /dev/null+++ b/openspec/changes/archive/2026-10-10-add-telegram-bot-api-url/tasks.md@@ -0,0 +1,18 @@+## 1. Backend++- [x] 1.1 Create the migration stub with `goose -dir backend/migrations create add_telegram_bot_api_url sql` and fill it to add a nullable `bot_api_url TEXT` column to `telegram_notifiers` in Up and drop it in Down, matching `20260622120000_add_telegram_proxy.sql`. Add `BotAPIURL string` (`json:"botApiUrl"`, column `bot_api_url`) to `TelegramNotifier` and copy it unconditionally in `Update`, leaving `HideSensitiveData` and `EncryptSensitiveData` untouched. Add a controller test that saves a Telegram notifier with a Bot API URL, reads it back with `botApiUrl` in clear and the bot token and proxy URL empty, then updates it with an empty URL and reads it back empty; verify with `just test-package ./internal/features/notifiers/...` in `backend/`+- [x] 1.2 Add `validateBotAPIURL` in `backend/internal/features/notifiers/models/telegram/bot_api_url.go` that accepts `http`/`https` with a host and rejects user info, a query and a fragment, and call it from `Validate` when the field is set. Add table tests on `Validate` in `model_test.go` beside the proxy tests for every valid and rejected URL in the spec, and a controller test that saving an invalid or credential-bearing URL is rejected and leaves the stored notifier unchanged; verify with `just test-package ./internal/features/notifiers/...` in `backend/`+- [x] 1.3 Make `Send` build the address from the validated Bot API URL with the trailing slash trimmed, or from `https://api.telegram.org` when the field is empty. Add a unit test in `model_test.go` that an empty Bot API URL yields `https://api.telegram.org/bot<token>/sendMessage`, and controller tests with `httptest` servers: a saved notifier with a prefixed, slash-terminated URL sent through `POST /notifiers/:id/test` delivers `/<prefix>/bot<token>/sendMessage` with its `chat_id`; an unsaved notifier sent through `POST /notifiers/direct-test` reaches the server the same way; a direct test with an invalid URL and with a URL holding user info returns an error while the server records no request; a notifier with a Bot API URL and a proxy pointing at an `httptest` proxy makes the proxy receive the request for the Bot API URL; a prefixed URL pointing at a closed server yields an error that names the host and not the token; verify with `just test-package ./internal/features/notifiers/...` in `backend/`+- [x] 1.4 Add `RedactSecretInText(text, secret string) string` to `backend/internal/features/notifiers/models/url_credentials.go`, replacing every occurrence of the secret with the existing `redactedURLSegment` marker, with a unit test in `url_credentials_test.go`, and apply it to the non-OK response body in the Telegram `Send`. Add a controller test where the Bot API server answers 404 with a body echoing the request path and the test-send error keeps the body with `redacted` in place of the token; verify with `just test-package ./internal/features/notifiers/...` in `backend/`++## 2. Frontend++- [x] 2.1 Add `botApiUrl?: string` to `TelegramNotifier.ts`, mirror the backend rules in `validateTelegramNotifier.ts`, and add the valid and rejected spec URLs to `validateTelegramNotifier.test.ts`; verify with `pnpm test` and `pnpm typecheck` in `frontend/`+- [x] 2.2 Move `AdvancedSettingsToggleComponent` from `features/databases/ui/edit/` to `shared/ui/` with the label as a prop, move `AdvancedFieldRowComponent` from `EditEmailNotifierComponent.tsx` to `shared/ui/`, export both from `shared/ui/index.ts`, switch the five database forms and the email form to them, delete the email form's inline header, and rename `notifiers.email.advancedSettings` to `notifiers.advancedSettings` in all six dictionaries; verify with `pnpm lint`, `pnpm typecheck` and `pnpm test` in `frontend/`+- [x] 2.3 Add the Bot API URL label, placeholder and tooltip (official API when empty, the URL receives the bot token, a bot must be moved to a self-hosted server first) to all six dictionaries, written in each language per the translation rules; verify with `pnpm test` (the dictionary placeholder test) and `pnpm typecheck` in `frontend/`+- [x] 2.4 Add the collapsible advanced settings section to `EditTelegramNotifierComponent.tsx`, holding the new Bot API URL field and the existing proxy switch and proxy URL, starting open when `botApiUrl` is set or `isProxyEnabled` is true. Add `EditTelegramNotifierComponent.test.tsx` rendering with `renderToStaticMarkup`: a new notifier renders without the proxy and Bot API URL labels, a notifier with a proxy and one with a Bot API URL render with them; verify with `pnpm test` in `frontend/`+- [x] 2.5 Show the Bot API URL in `ShowTelegramNotifierComponent.tsx` when it is set, with `ShowTelegramNotifierComponent.test.tsx` checking that the URL is rendered when set and absent otherwise; verify with `pnpm test` in `frontend/`++## 3. Final checks++- [x] 3.1 Run `just format` and `just lint` at the repository root and `pnpm build` in `frontend/`, and fix every finding in the touched files; verify all three exit cleanlydiff --git a/openspec/specs/telegram-notifier-endpoint/spec.md b/openspec/specs/telegram-notifier-endpoint/spec.mdnew file mode 100644index 00000000..2cccf1aa--- /dev/null+++ b/openspec/specs/telegram-notifier-endpoint/spec.md@@ -0,0 +1,108 @@+# Telegram Notifier Endpoint Specification++## Purpose++Lets a Telegram notifier deliver messages through a self-hosted Telegram Bot API server or a reverse proxy instead of the official Telegram API, and defines which addresses it accepts and how the address is shown.++## Requirements++### Requirement: A Telegram notifier sends to its Bot API URL or to the official API++A Telegram notifier SHALL have an optional Bot API URL. When the URL is empty, the notifier SHALL send its messages to the official Telegram Bot API at `https://api.telegram.org`. When the URL is set, the notifier SHALL send its messages to that server instead, with the standard Bot API path for sending a message appended to the URL, including any path prefix the URL has. A trailing slash in the URL SHALL NOT change the address the request is sent to. This SHALL hold for scheduled notifications and for test notifications alike, and a notifier with a proxy enabled SHALL reach the Bot API URL through that proxy.++#### Scenario: Notifier without a Bot API URL++- **WHEN** a Telegram notifier has no Bot API URL and sends a notification+- **THEN** the message is sent to the official Telegram Bot API, as before this change++#### Scenario: Notifier with a self-hosted server++- **WHEN** a Telegram notifier has the Bot API URL `http://telegram-bot-api:8081` and sends a notification+- **THEN** the message is sent to `http://telegram-bot-api:8081/bot<token>/sendMessage` with the notifier's chat, topic and text++#### Scenario: Bot API URL with a path prefix and a trailing slash++- **WHEN** a Telegram notifier has the Bot API URL `https://gateway.example.com/telegram/` and sends a notification+- **THEN** the message is sent to `https://gateway.example.com/telegram/bot<token>/sendMessage`++#### Scenario: Test notification uses the Bot API URL from the form++- **WHEN** the user enters a Bot API URL in the Telegram form and sends a test notification before saving+- **THEN** the test message is sent to the entered server++#### Scenario: Bot API URL together with a proxy++- **WHEN** a Telegram notifier has both a Bot API URL and a proxy enabled+- **THEN** the message is sent to the Bot API URL through the configured proxy++#### Scenario: Existing notifiers after the upgrade++- **WHEN** Databasus is upgraded and a Telegram notifier created before the upgrade sends a notification+- **THEN** the notifier has no Bot API URL and the message is sent to the official Telegram Bot API++### Requirement: Only a plain HTTP or HTTPS address is accepted as a Bot API URL++Saving a Telegram notifier and sending a test notification SHALL be rejected with an error when the Bot API URL is set and does not satisfy all of these: the scheme is `http` or `https`, the URL has a host, and it has no query string and no fragment. A path prefix SHALL be accepted. The form SHALL refuse to save or test the notifier under the same conditions. An empty Bot API URL SHALL always be accepted.++#### Scenario: Unsupported scheme++- **WHEN** the user saves a Telegram notifier with the Bot API URL `ftp://telegram.example.com`+- **THEN** the save is rejected and the notifier keeps its previous settings++#### Scenario: Address without a host++- **WHEN** the user saves a Telegram notifier with the Bot API URL `telegram-bot-api:8081` or `https://`+- **THEN** the save is rejected++#### Scenario: Query string or fragment++- **WHEN** the user saves a Telegram notifier with the Bot API URL `https://gateway.example.com/telegram?key=1` or `https://gateway.example.com/#bot`+- **THEN** the save is rejected++#### Scenario: Test send of an unsaved notifier with an invalid address++- **WHEN** the user sends a test notification from the form for a Telegram notifier that has not been saved yet and whose Bot API URL is `ftp://telegram.example.com` or `https://user:[email protected]`+- **THEN** the test send returns an error and no request leaves the backend++#### Scenario: Valid addresses++- **WHEN** the user saves a Telegram notifier with the Bot API URL `http://localhost:8081`, `https://gateway.example.com` or `https://gateway.example.com/telegram/`+- **THEN** the notifier is saved with that URL++### Requirement: The Bot API URL holds no credentials and stays visible++A Bot API URL that contains a username or a password SHALL be rejected, on save and on test send, in the API and in the form. Because the URL then holds no secret, it SHALL be stored as entered, returned when the notifier is read and shown on the notifier's page, unlike the bot token and the proxy URL, which stay hidden. Errors from a failed send, whether stored as the notifier's last error, written to logs or returned by a test send, SHALL NOT contain the bot token when the notifier uses a Bot API URL, including one with a path prefix.++#### Scenario: Credentials in the URL++- **WHEN** the user saves a Telegram notifier with the Bot API URL `https://user:[email protected]`+- **THEN** the save is rejected++#### Scenario: Reading a notifier with a Bot API URL++- **WHEN** the user opens a Telegram notifier whose Bot API URL is `https://gateway.example.com/telegram`+- **THEN** the page shows that URL, while the bot token and the proxy URL stay hidden++#### Scenario: Send fails against a custom server++- **WHEN** a Telegram notifier with the Bot API URL `https://gateway.example.com/telegram` fails to connect to that server+- **THEN** the reported error names the host but does not contain the bot token++#### Scenario: Custom server echoes the request path in an error response++- **WHEN** the server at the Bot API URL answers with a non-OK status and a body such as `Cannot POST /telegram/bot<token>/sendMessage`+- **THEN** the reported error, whether returned by a test send or stored as the notifier's last error, keeps the body with `redacted` in place of the bot token++### Requirement: Bot API URL and proxy live in the advanced settings of the Telegram form++The Telegram notifier form SHALL show the Bot API URL field, the proxy switch and the proxy URL in a collapsible advanced settings section. The section SHALL start expanded when the notifier being edited has a Bot API URL or a proxy enabled, and collapsed otherwise. The bot token, the chat ID and the topic settings SHALL stay outside the section.++#### Scenario: New notifier++- **WHEN** the user creates a Telegram notifier+- **THEN** the advanced settings section is collapsed and the bot token, chat ID and topic settings are visible++#### Scenario: Editing a notifier with a proxy++- **WHEN** the user edits a Telegram notifier that has a proxy enabled or a Bot API URL set+- **THEN** the advanced settings section is expanded and shows those values