Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: custom payload generic webhooks and google chat notifications (#3417)
Khanh Chau20d0f33abb09
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 4059bb6f6..e97e0a091 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -93,6 +93,7 @@ var (ErrEnvironmentConnectionTestFailed = Classify(ErrBadRequest, errors.Sentinel("Environment connection test failed"))ErrUnsafeRemoteURL = Classify(ErrBadRequest, errors.Sentinel("Remote URL is not allowed"))ErrImageScanInProgress = Classify(ErrConflict, errors.Sentinel("an image update check is already in progress"))+ ErrInvalidNotificationPayloadTemplate = Classify(ErrValidation, errors.Sentinel("invalid generic webhook payload template"))ErrRedeployAfterSyncFailed = errors.Sentinel("redeploy failed")ErrGitOpsSyncProjectBindingBroken = errors.Sentinel("GitOps sync project binding broken"))diff --git a/backend/internal/models/notification.go b/backend/internal/models/notification.goindex 964f55b25..8175d3739 100644--- a/backend/internal/models/notification.go+++ b/backend/internal/models/notification.go@@ -7,29 +7,31 @@ import (type NotificationProvider stringconst (- NotificationProviderDiscord NotificationProvider = "discord"- NotificationProviderEmail NotificationProvider = "email"- NotificationProviderTelegram NotificationProvider = "telegram"- NotificationProviderSignal NotificationProvider = "signal"- NotificationProviderSlack NotificationProvider = "slack"- NotificationProviderNtfy NotificationProvider = "ntfy"- NotificationProviderPushover NotificationProvider = "pushover"- NotificationProviderGotify NotificationProvider = "gotify"- NotificationProviderMatrix NotificationProvider = "matrix"- NotificationProviderGeneric NotificationProvider = "generic"+ NotificationProviderDiscord NotificationProvider = "discord"+ NotificationProviderEmail NotificationProvider = "email"+ NotificationProviderTelegram NotificationProvider = "telegram"+ NotificationProviderSignal NotificationProvider = "signal"+ NotificationProviderSlack NotificationProvider = "slack"+ NotificationProviderNtfy NotificationProvider = "ntfy"+ NotificationProviderPushover NotificationProvider = "pushover"+ NotificationProviderGotify NotificationProvider = "gotify"+ NotificationProviderMatrix NotificationProvider = "matrix"+ NotificationProviderGoogleChat NotificationProvider = "googlechat"+ NotificationProviderGeneric NotificationProvider = "generic")var validNotificationProviders = map[NotificationProvider]struct{}{- NotificationProviderDiscord: {},- NotificationProviderEmail: {},- NotificationProviderTelegram: {},- NotificationProviderSignal: {},- NotificationProviderSlack: {},- NotificationProviderNtfy: {},- NotificationProviderPushover: {},- NotificationProviderGotify: {},- NotificationProviderMatrix: {},- NotificationProviderGeneric: {},+ NotificationProviderDiscord: {},+ NotificationProviderEmail: {},+ NotificationProviderTelegram: {},+ NotificationProviderSignal: {},+ NotificationProviderSlack: {},+ NotificationProviderNtfy: {},+ NotificationProviderPushover: {},+ NotificationProviderGotify: {},+ NotificationProviderMatrix: {},+ NotificationProviderGoogleChat: {},+ NotificationProviderGeneric: {},}func IsValidNotificationProvider(provider NotificationProvider) bool {@@ -170,6 +172,13 @@ type GotifyConfig struct {Events map[NotificationEventType]bool `json:"events,omitempty"`}+type GoogleChatConfig struct {+ // WebhookURL is the full incoming webhook URL copied from Google Chat,+ // e.g. https://chat.googleapis.com/v1/spaces/SPACE/messages?key=KEY&token=TOKEN.+ WebhookURL string `json:"webhookUrl"`+ Events map[NotificationEventType]bool `json:"events,omitempty"`+}+type MatrixConfig struct {Host string `json:"host"`Port int `json:"port,omitempty"`@@ -196,4 +205,13 @@ type GenericConfig struct {// {"code":900,...} on failure). When empty, only the HTTP status code is// checked (existing behaviour).SuccessBodyContains string `json:"successBodyContains,omitempty"`+ // PayloadTemplate is an optional Go text/template rendered into the request+ // body, letting users target endpoints that require a nested or+ // provider-specific payload shape rather than the flat+ // {"title":...,"message":...} object. The template receives the title and+ // message (under the configured TitleKey/MessageKey) plus event variables+ // (environment, environmentId, event, timestamp), all pre-escaped for JSON+ // string contexts. When empty, the flat JSON payload is used (existing+ // behaviour).+ PayloadTemplate string `json:"payloadTemplate,omitempty"`}diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.goindex cb18f98e8..5c0e900f8 100644--- a/backend/internal/services/notification_service.go+++ b/backend/internal/services/notification_service.go@@ -17,6 +17,7 @@ import ("emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -39,6 +40,9 @@ var notificationCredentialFieldsByProviderInternal = map[models.NotificationProvmodels.NotificationProviderPushover: {"token"},models.NotificationProviderGotify: {"token"},models.NotificationProviderMatrix: {"password"},+ // The Google Chat incoming webhook URL embeds the key and token query+ // parameters, so the whole URL is treated as a credential.+ models.NotificationProviderGoogleChat: {"webhookUrl"},}var notificationTargetFieldByProviderInternal = map[models.NotificationProvider]string{@@ -265,6 +269,19 @@ func (s *NotificationService) GetSettingsByProvider(ctx context.Context, provide}func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provider models.NotificationProvider, enabled bool, config models.JSON) (*models.NotificationSettings, error) {+ if provider == models.NotificationProviderGeneric {+ genericConfig, decodeErr := notifications.DecodeConfig[models.GenericConfig](config, "Generic")+ if decodeErr != nil {+ return nil, decodeErr+ }+ // Shoutrrr renders the payload template internally at send time, so a+ // broken template is validated here where the error surfaces against+ // the user's own configuration instead of as an opaque send failure.+ if validateErr := notifications.ValidateGenericPayloadTemplate(genericConfig); validateErr != nil {+ return nil, common.Classify(common.ErrInvalidNotificationPayloadTemplate, validateErr)+ }+ }+var setting models.NotificationSettingserr := s.db.WithContext(ctx).Where("provider = ?", provider).First(&setting).Error@@ -737,6 +754,7 @@ func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx c"eventType": string(eventType),}content := s.imageUpdateNotificationContentInternal(target.EnvironmentName, imageRef, updateInfo)+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, eventType)return s.notifyEnabledProvidersInternal(ctx, target, eventType, imageRef, metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})@@ -772,6 +790,7 @@ func (s *NotificationService) sendContainerUpdateNotificationForTargetInternal(c"eventType": string(models.NotificationEventContainerUpdate),}content := s.containerUpdateNotificationContentInternal(target.EnvironmentName, containerName, imageRef, oldDigest, newDigest)+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventContainerUpdate)_, err := s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventContainerUpdate, imageRef, metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})@@ -822,6 +841,7 @@ func (s *NotificationService) sendVulnerabilityNotificationForTargetInternal(ctx"eventType": string(models.NotificationEventVulnerabilityFound),}content := s.vulnerabilityNotificationContentInternal(target.EnvironmentName, payload)+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventVulnerabilityFound)_, err := s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventVulnerabilityFound, payload.ImageName, metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})@@ -886,6 +906,7 @@ func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal("batch": true,}content := s.batchImageUpdateNotificationContentInternal(target.EnvironmentName, updatesWithChanges)+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventImageUpdate)return s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventImageUpdate, strings.Join(imageRefs, ", "), metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})@@ -931,6 +952,7 @@ func (s *NotificationService) sendPruneReportNotificationForTargetInternal(ctx c"eventType": string(models.NotificationEventPruneReport),}content := s.pruneReportNotificationContentInternal(target.EnvironmentName, result)+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventPruneReport)_, err := s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventPruneReport, "System Prune Report", metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})@@ -986,6 +1008,7 @@ func (s *NotificationService) sendAutoHealNotificationForTargetInternal(ctx cont"eventType": string(models.NotificationEventAutoHeal),}content := s.autoHealNotificationContentInternal(target.EnvironmentName, containerName)+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventAutoHeal)_, err := s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventAutoHeal, containerName, metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})@@ -1120,6 +1143,14 @@ func (s *NotificationService) TestNotification(ctx context.Context, environmentI}content := s.testNotificationContentInternal(target.EnvironmentName, testType)+ // Stamp the event vars so the Test button exercises a configured generic+ // payload template. The simple test renders image-update content, so it+ // reports that event type.+ testEventType := notificationEventTypeForTestTypeInternal(testType)+ if testEventType == "" {+ testEventType = models.NotificationEventImageUpdate+ }+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, testEventType)handled, sendErr := notifications.Deliver(ctx, provider, setting.Config, content)if !handled {return "", errors.Errorf("unknown provider: %s", provider)diff --git a/backend/pkg/utils/notifications/deliver.go b/backend/pkg/utils/notifications/deliver.goindex 45653db13..6d85d6203 100644--- a/backend/pkg/utils/notifications/deliver.go+++ b/backend/pkg/utils/notifications/deliver.go@@ -28,6 +28,12 @@ type Content struct {// this package. Nil means the provider map's email deliverer errors.RenderEmail func() (subject, html string, err error)+ // Vars carries per-event variables (environment, environmentId, event,+ // timestamp) for the generic webhook's payload template. They are only+ // injected into the outgoing request when a payload template is configured,+ // so existing template-less generic webhooks keep their exact payload.+ Vars map[string]string+// RequireNtfyTopic preserves the per-event ntfy topic validation.RequireNtfyTopic bool@@ -38,16 +44,17 @@ type Content struct {type delivererFunc func(ctx context.Context, config models.JSON, c Content) errorvar providerDeliverers = map[models.NotificationProvider]delivererFunc{- models.NotificationProviderDiscord: deliverDiscord,- models.NotificationProviderEmail: deliverEmail,- models.NotificationProviderTelegram: deliverTelegram,- models.NotificationProviderSignal: deliverSignal,- models.NotificationProviderSlack: deliverSlack,- models.NotificationProviderNtfy: deliverNtfy,- models.NotificationProviderPushover: deliverPushover,- models.NotificationProviderGotify: deliverGotify,- models.NotificationProviderMatrix: deliverMatrix,- models.NotificationProviderGeneric: deliverGeneric,+ models.NotificationProviderDiscord: deliverDiscord,+ models.NotificationProviderEmail: deliverEmail,+ models.NotificationProviderTelegram: deliverTelegram,+ models.NotificationProviderSignal: deliverSignal,+ models.NotificationProviderSlack: deliverSlack,+ models.NotificationProviderNtfy: deliverNtfy,+ models.NotificationProviderPushover: deliverPushover,+ models.NotificationProviderGotify: deliverGotify,+ models.NotificationProviderMatrix: deliverMatrix,+ models.NotificationProviderGoogleChat: deliverGoogleChat,+ models.NotificationProviderGeneric: deliverGeneric,}// Deliver sends c to a single provider. handled is false for unknown providers.@@ -231,6 +238,23 @@ func deliverMatrix(ctx context.Context, config models.JSON, c Content) error {return nil}+func deliverGoogleChat(ctx context.Context, config models.JSON, c Content) error {+ googleChatConfig, err := DecodeConfig[models.GoogleChatConfig](config, "Google Chat")+ if err != nil {+ return err+ }+ if googleChatConfig.WebhookURL == "" {+ return errors.New("google chat webhook URL not configured")+ }+ if err := DecryptStringCredential(&googleChatConfig.WebhookURL); err != nil {+ return err+ }+ if err := SendGoogleChat(ctx, googleChatConfig, c.Text[MessageFormatPlain]); err != nil {+ return errors.WrapIf(err, "failed to send Google Chat notification")+ }+ return nil+}+func deliverGeneric(ctx context.Context, config models.JSON, c Content) error {genericConfig, err := DecodeConfig[models.GenericConfig](config, "Generic")if err != nil {@@ -239,7 +263,7 @@ func deliverGeneric(ctx context.Context, config models.JSON, c Content) error {if genericConfig.WebhookURL == "" {return errors.New("webhook URL not configured")}- if err := SendGenericWithTitle(ctx, genericConfig, c.Title, c.Text[MessageFormatPlain]); err != nil {+ if err := SendGenericWithTitle(ctx, genericConfig, c.Title, c.Text[MessageFormatPlain], c.Vars); err != nil {return errors.WrapIf(err, "failed to send Generic webhook notification")}return nildiff --git a/backend/pkg/utils/notifications/generic_sender.go b/backend/pkg/utils/notifications/generic_sender.goindex 8b986347a..a440631ed 100644--- a/backend/pkg/utils/notifications/generic_sender.go+++ b/backend/pkg/utils/notifications/generic_sender.go@@ -3,12 +3,15 @@ package notificationsimport ("bytes""context"+ "encoding/json/jsontext""encoding/json/v2""fmt""io""net/http""net/url""strings"+ "text/template"+ "time""emperror.dev/errors"@@ -17,6 +20,16 @@ import (shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")+// genericPayloadTemplateID is the Shoutrrr template ID under which a user's+// payload template is registered on the generic service instance.+const genericPayloadTemplateID = "arcane"++// genericHTTPClient bounds every generic webhook request. Shoutrrr's generic+// service falls back to a client with no timeout when none is injected, and+// the payload-template path sends through the located service directly,+// bypassing the router's own per-send timeout.+var genericHTTPClient = &http.Client{Timeout: 15 * time.Second}+// resolveWebhookURLInternal parses and normalises the configured webhook URL,// adding a default scheme when the user omitted one. It is the single source// of truth for scheme normalisation and host validation used by both@@ -90,9 +103,19 @@ func BuildGenericURL(config models.GenericConfig) (string, error) {// Default to the JSON template — Shoutrrr's JSON template marshals the// notification params as a flat JSON object at the root level, which is// the format most providers (PushPlus, custom APIs, Home Assistant, etc.)- // expect.- setDefault("template", "json")+ // expect. When the user configured a payload template, point Shoutrrr at+ // the named template registered at send time instead, and default the+ // content type to JSON since that is what payload templates target.+ hasPayloadTemplate := strings.TrimSpace(config.PayloadTemplate) != ""+ if hasPayloadTemplate {+ setDefault("template", genericPayloadTemplateID)+ } else {+ setDefault("template", "json")+ }setDefault("contenttype", config.ContentType)+ if hasPayloadTemplate {+ setDefault("contenttype", "application/json")+ }setDefault("method", config.Method)setDefault("titlekey", config.TitleKey)setDefault("messagekey", config.MessageKey)@@ -124,11 +147,110 @@ func BuildGenericURL(config models.GenericConfig) (string, error) {return shoutrrrURL.String(), nil}+// EventVars builds the per-event variables exposed to a generic webhook+// payload template. The names must stay clear of Shoutrrr generic config keys+// (title, template, contenttype, method, messagekey, titlekey, disabletls) —+// a colliding param would mutate the per-send service config.+func EventVars(environmentName, environmentID string, event models.NotificationEventType) map[string]string {+ return map[string]string{+ "environment": environmentName,+ "environmentId": environmentID,+ "event": string(event),+ "timestamp": time.Now().UTC().Format(time.RFC3339),+ }+}++// jsonEscapeString escapes value for embedding inside a JSON string literal:+// json.Marshal yields a quoted string, and the surrounding quotes are trimmed+// so the template author keeps control of the quoting. Applied only on the+// payload-template path — the default template=json path is escaped by+// Shoutrrr's own json.Marshal.+func jsonEscapeString(value string) string {+ encoded, err := json.Marshal(value)+ if err != nil {+ return value+ }+ return strings.TrimSuffix(strings.TrimPrefix(string(encoded), `"`), `"`)+}++// genericTemplateDataInternal builds the variable map a payload template is+// rendered with on the direct-HTTP path: the JSON-escaped title and message+// under the configured titlekey/messagekey — mirroring how Shoutrrr's+// createSendParams keys the send params — plus the escaped per-event vars.+func genericTemplateDataInternal(config models.GenericConfig, title, message string, vars map[string]string) map[string]string {+ titleKey := config.TitleKey+ if titleKey == "" {+ titleKey = "title"+ }+ messageKey := config.MessageKey+ if messageKey == "" {+ messageKey = "message"+ }++ data := make(map[string]string, len(vars)+2)+ for key, value := range vars {+ data[key] = jsonEscapeString(value)+ }+ data[titleKey] = jsonEscapeString(title)+ data[messageKey] = jsonEscapeString(message)+ return data+}++// RenderGenericPayloadTemplate renders the configured payload template with+// the same variables the Shoutrrr send path exposes. Used by the direct-HTTP+// path (SuccessBodyContains) and by save-time validation.+func RenderGenericPayloadTemplate(config models.GenericConfig, title, message string, vars map[string]string) (string, error) {+ tmpl, err := template.New(genericPayloadTemplateID).Parse(config.PayloadTemplate)+ if err != nil {+ return "", errors.WrapIf(err, "invalid webhook payload template")+ }++ var rendered bytes.Buffer+ if err := tmpl.Execute(&rendered, genericTemplateDataInternal(config, title, message, vars)); err != nil {+ return "", errors.WrapIf(err, "failed to render webhook payload template")+ }+ return rendered.String(), nil+}++// isJSONContentType reports whether the configured content type denotes JSON.+// An empty content type counts as JSON because that is the default applied to+// outgoing generic webhook requests.+func isJSONContentType(contentType string) bool {+ if contentType == "" {+ return true+ }+ // Ignore any parameters such as "; charset=utf-8".+ mediaType := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))+ return mediaType == "application/json" || strings.HasSuffix(mediaType, "+json")+}++// ValidateGenericPayloadTemplate checks a configured payload template at save+// time: it must parse, execute against sample variables, and — when the+// content type is JSON (the default) — render valid JSON. Shoutrrr renders+// the template internally at send time, so validating here surfaces mistakes+// against the user's own configuration instead of as an opaque send failure.+func ValidateGenericPayloadTemplate(config models.GenericConfig) error {+ if strings.TrimSpace(config.PayloadTemplate) == "" {+ return nil+ }++ sampleVars := EventVars("Local Docker", "0", models.NotificationEventImageUpdate)+ rendered, err := RenderGenericPayloadTemplate(config, "Sample Title", "sample \"message\"\nwith a newline", sampleVars)+ if err != nil {+ return err+ }++ if isJSONContentType(config.ContentType) && !jsontext.Value(rendered).IsValid() {+ return errors.New("webhook payload template did not render valid JSON")+ }+ return nil+}+// SendGenericWithTitle sends a message with title via Shoutrrr Generic webhook.// When config.SuccessBodyContains is set the response body is also inspected —// this is necessary for providers (e.g. PushPlus) that always return HTTP 200// but embed a success/failure indicator inside the JSON body.-func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, title, message string) error {+func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, title, message string, vars map[string]string) error {if config.WebhookURL == "" {return errors.New("webhook URL is empty")}@@ -138,7 +260,7 @@ func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, titl// shoutrrr, which preserves the existing behaviour for everyone who does// not set SuccessBodyContains.if config.SuccessBodyContains != "" {- return sendGenericDirectInternal(ctx, config, title, message)+ return sendGenericDirectInternal(ctx, config, title, message, vars)}shoutrrrURL, err := BuildGenericURL(config)@@ -146,7 +268,20 @@ func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, titlreturn errors.WrapIf(err, "failed to build shoutrrr Generic URL")}- sender, err := shoutrrr.CreateSenderWithOptions(shoutrrrTypes.SenderOptions{}, shoutrrrURL)+ senderOptions := shoutrrrTypes.SenderOptions{HTTPClient: genericHTTPClient}++ // A user-supplied inline `?template=<id>` in the webhook URL wins over the+ // default "arcane" ID, so the payload template must be registered under the+ // effective ID for Shoutrrr to resolve it. An inline `template=json`+ // selects Shoutrrr's built-in JSON template instead, which does its own+ // escaping — send through the plain path so params are not double-escaped.+ if strings.TrimSpace(config.PayloadTemplate) != "" {+ if templateID := effectiveGenericTemplateIDInternal(shoutrrrURL); templateID != "json" && templateID != "JSON" {+ return sendGenericTemplatedInternal(config, shoutrrrURL, templateID, senderOptions, title, message, vars)+ }+ }++ sender, err := shoutrrr.CreateSenderWithOptions(senderOptions, shoutrrrURL)if err != nil {return errors.WrapIf(err, "failed to create shoutrrr Generic sender")}@@ -167,33 +302,95 @@ func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, titlreturn nil}-// sendGenericDirectInternal makes the webhook HTTP call directly, giving access-// to the response body so that provider-level success/failure can be detected-// even when the HTTP status is always 200.-func sendGenericDirectInternal(ctx context.Context, config models.GenericConfig, title, message string) error {- webhookURL, err := resolveWebhookURLInternal(config)+// effectiveGenericTemplateIDInternal returns the template ID the built+// Shoutrrr URL selects for payload rendering. BuildGenericURL always sets a+// template query key, so an empty result only happens on an unparseable URL;+// fall back to the default ID in that case.+func effectiveGenericTemplateIDInternal(shoutrrrURL string) string {+ parsed, err := url.Parse(shoutrrrURL)if err != nil {- return err+ return genericPayloadTemplateID+ }+ if id := parsed.Query().Get("template"); id != "" {+ return id}+ return genericPayloadTemplateID+}- // Build JSON payload using the configured message/title keys.- msgKey := config.MessageKey- if msgKey == "" {- msgKey = "message"+// sendGenericTemplatedInternal sends through Shoutrrr's generic service with+// the user's payload template registered on the service instance under+// templateID — the ID the URL's template key selects. Templates are resolved+// per service instance, which router.Send does not expose, so the service is+// obtained via Locate — the full initService path (scheme extraction, config+// parse, HTTP client injection) — and sent on directly.+func sendGenericTemplatedInternal(config models.GenericConfig, shoutrrrURL, templateID string, opts shoutrrrTypes.SenderOptions, title, message string, vars map[string]string) error {+ sender, err := shoutrrr.CreateSenderWithOptions(opts)+ if err != nil {+ return errors.WrapIf(err, "failed to create shoutrrr Generic sender")}- titleKey := config.TitleKey- if titleKey == "" {- titleKey = "title"++ service, err := sender.Locate(shoutrrrURL)+ if err != nil {+ return errors.WrapIf(err, "failed to initialize shoutrrr Generic service")}- payload := map[string]string{msgKey: message}- if title != "" {- payload[titleKey] = title+ if err := service.SetTemplateString(templateID, config.PayloadTemplate); err != nil {+ return errors.WrapIf(err, "invalid webhook payload template")}- body, err := json.Marshal(payload)+ // Shoutrrr renders the registered template over the send params, remapping+ // the "title" param to the configured titlekey and adding the message under+ // the configured messagekey. Every value is JSON-escaped here, so+ // {"text": "{{.message}}"} stays valid JSON for hostile message content —+ // text/template itself does no escaping.+ params := shoutrrrTypes.Params{"title": jsonEscapeString(title)}+ for key, value := range vars {+ params[key] = jsonEscapeString(value)+ }++ if err := service.Send(jsonEscapeString(message), ¶ms); err != nil {+ return errors.WrapIf(err, "failed to send Generic webhook message via shoutrrr")+ }+ return nil+}++// sendGenericDirectInternal makes the webhook HTTP call directly, giving access+// to the response body so that provider-level success/failure can be detected+// even when the HTTP status is always 200. It renders the payload template when+// one is configured so the two features compose.+func sendGenericDirectInternal(ctx context.Context, config models.GenericConfig, title, message string, vars map[string]string) error {+ webhookURL, err := resolveWebhookURLInternal(config)if err != nil {- return errors.WrapIf(err, "failed to marshal webhook payload")+ return err+ }++ var body []byte+ if strings.TrimSpace(config.PayloadTemplate) != "" {+ rendered, renderErr := RenderGenericPayloadTemplate(config, title, message, vars)+ if renderErr != nil {+ return renderErr+ }+ body = []byte(rendered)+ } else {+ // Build JSON payload using the configured message/title keys.+ msgKey := config.MessageKey+ if msgKey == "" {+ msgKey = "message"+ }+ titleKey := config.TitleKey+ if titleKey == "" {+ titleKey = "title"+ }++ payload := map[string]string{msgKey: message}+ if title != "" {+ payload[titleKey] = title+ }++ body, err = json.Marshal(payload)+ if err != nil {+ return errors.WrapIf(err, "failed to marshal webhook payload")+ }}method := strings.ToUpper(config.Method)@@ -216,7 +413,7 @@ func sendGenericDirectInternal(ctx context.Context, config models.GenericConfig,req.Header.Set(k, v)}- resp, err := http.DefaultClient.Do(req)+ resp, err := genericHTTPClient.Do(req)if err != nil {return errors.WrapIf(err, "failed to send webhook request")}diff --git a/backend/pkg/utils/notifications/generic_sender_test.go b/backend/pkg/utils/notifications/generic_sender_test.goindex aa47e20dd..00b76d3f4 100644--- a/backend/pkg/utils/notifications/generic_sender_test.go+++ b/backend/pkg/utils/notifications/generic_sender_test.go@@ -1,6 +1,10 @@package notificationsimport (+ "encoding/json/v2"+ "io"+ "net/http"+ "net/http/httptest""testing""github.com/getarcaneapp/arcane/backend/v2/internal/models"@@ -414,3 +418,174 @@ func TestBuildGenericURL_PreservesUserShoutrrrConfigKeys(t *testing.T) {})}}++// TestBuildGenericURL_PayloadTemplate verifies that a configured payload+// template switches the Shoutrrr template to the named "arcane" template and+// defaults the content type to JSON, while a user-supplied inline template+// query key still wins.+func TestBuildGenericURL_PayloadTemplate(t *testing.T) {+ gotURL, err := BuildGenericURL(models.GenericConfig{+ WebhookURL: "https://webhook.example.com/notify",+ PayloadTemplate: `{"text": "{{.message}}"}`,+ })+ require.NoError(t, err)+ assert.Contains(t, gotURL, "template=arcane")+ assert.Contains(t, gotURL, "contenttype=application%2Fjson")+ assert.NotContains(t, gotURL, "template=json")++ gotURL, err = BuildGenericURL(models.GenericConfig{+ WebhookURL: "https://webhook.example.com/notify?template=custom",+ PayloadTemplate: `{"text": "{{.message}}"}`,+ })+ require.NoError(t, err)+ assert.Contains(t, gotURL, "template=custom")+ assert.NotContains(t, gotURL, "template=arcane")+}++// TestRenderGenericPayloadTemplate_EscapesJSON guards the escaping contract: a+// template embedding values inside JSON string literals must render valid JSON+// for hostile message content, and the event vars must be available.+func TestRenderGenericPayloadTemplate_EscapesJSON(t *testing.T) {+ config := models.GenericConfig{+ PayloadTemplate: `{"text": "{{.title}}: {{.message}}", "env": "{{.environment}}", "event": "{{.event}}"}`,+ }+ vars := map[string]string{"environment": "Local Docker", "environmentId": "0", "event": "image_update", "timestamp": "2026-07-28T00:00:00Z"}++ body, err := RenderGenericPayloadTemplate(config, "Image \"Update\"", "he said \"stop\"\nnew line \\ end", vars)+ require.NoError(t, err)++ var decoded map[string]string+ require.NoError(t, json.Unmarshal([]byte(body), &decoded), "rendered body must be valid JSON: %s", body)+ assert.Equal(t, "Image \"Update\": he said \"stop\"\nnew line \\ end", decoded["text"])+ assert.Equal(t, "Local Docker", decoded["env"])+ assert.Equal(t, "image_update", decoded["event"])+}++// TestSendGenericWithTitle_PayloadTemplate exercises the Shoutrrr send path+// end to end: the payload template registered on the located service must+// reach the endpoint as the rendered request body, with the configured custom+// headers and JSON content type applied.+func TestSendGenericWithTitle_PayloadTemplate(t *testing.T) {+ var gotBody []byte+ var gotContentType, gotMethod, gotAuth string++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotBody, _ = io.ReadAll(r.Body)+ gotContentType = r.Header.Get("Content-Type")+ gotMethod = r.Method+ gotAuth = r.Header.Get("Authorization")+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()++ config := models.GenericConfig{+ WebhookURL: server.URL + "/v1/spaces/FOO/messages",+ PayloadTemplate: `{"text": "{{.title}}\n{{.message}} ({{.environment}})"}`,+ CustomHeaders: map[string]string{"Authorization": "Bearer t0ken"},+ }+ vars := map[string]string{"environment": "Local Docker", "environmentId": "0", "event": "image_update", "timestamp": "2026-07-28T00:00:00Z"}++ require.NoError(t, SendGenericWithTitle(t.Context(), config, "Image Update", "nginx:latest updated", vars))++ assert.JSONEq(t, `{"text": "Image Update\nnginx:latest updated (Local Docker)"}`, string(gotBody))+ assert.Equal(t, http.MethodPost, gotMethod)+ assert.Equal(t, "application/json", gotContentType)+ assert.Equal(t, "Bearer t0ken", gotAuth)+}++// TestSendGenericWithTitle_TemplateWithSuccessBodyContains verifies the two+// direct-send features compose: template rendering plus response validation.+func TestSendGenericWithTitle_TemplateWithSuccessBodyContains(t *testing.T) {+ var gotBody []byte+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotBody, _ = io.ReadAll(r.Body)+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"code":900,"msg":"failed"}`))+ }))+ defer server.Close()++ config := models.GenericConfig{+ WebhookURL: server.URL,+ PayloadTemplate: `{"text": "{{.message}}"}`,+ SuccessBodyContains: `"code":200`,+ }++ err := SendGenericWithTitle(t.Context(), config, "", "hello", nil)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "did not contain expected success indicator")+ assert.JSONEq(t, `{"text": "hello"}`, string(gotBody))+}++func TestValidateGenericPayloadTemplate(t *testing.T) {+ tests := []struct {+ name string+ config models.GenericConfig+ wantErr string+ }{+ {+ name: "no template is always valid",+ config: models.GenericConfig{},+ },+ {+ name: "valid JSON template",+ config: models.GenericConfig{+ PayloadTemplate: `{"text": "{{.message}}", "when": "{{.timestamp}}"}`,+ },+ },+ {+ name: "invalid template syntax is reported",+ config: models.GenericConfig{+ PayloadTemplate: `{"text": "{{.message}`,+ },+ wantErr: "invalid webhook payload template",+ },+ {+ name: "template rendering malformed JSON is rejected",+ config: models.GenericConfig{+ PayloadTemplate: `{"text": "{{.message}}"`,+ },+ wantErr: "did not render valid JSON",+ },+ {+ name: "malformed JSON is allowed for non-JSON content types",+ config: models.GenericConfig{+ ContentType: "text/plain",+ PayloadTemplate: `event={{.event}} message={{.message}}`,+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := ValidateGenericPayloadTemplate(tt.config)++ if tt.wantErr != "" {+ require.Error(t, err)+ assert.Contains(t, err.Error(), tt.wantErr)+ return+ }+ require.NoError(t, err)+ })+ }+}++// TestSendGenericWithTitle_PayloadTemplateWithInlineTemplateID guards against+// the configured payload being registered under an ID the URL does not select:+// a user-supplied inline `?template=custom` must still resolve to the+// configured payload template instead of failing template resolution.+func TestSendGenericWithTitle_PayloadTemplateWithInlineTemplateID(t *testing.T) {+ var gotBody []byte+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotBody, _ = io.ReadAll(r.Body)+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()++ config := models.GenericConfig{+ WebhookURL: server.URL + "/notify?template=custom",+ PayloadTemplate: `{"text": "{{.message}}"}`,+ }++ require.NoError(t, SendGenericWithTitle(t.Context(), config, "", "hello", nil))+ assert.JSONEq(t, `{"text": "hello"}`, string(gotBody))+}diff --git a/backend/pkg/utils/notifications/googlechat_sender.go b/backend/pkg/utils/notifications/googlechat_sender.gonew file mode 100644index 000000000..8a64b652f--- /dev/null+++ b/backend/pkg/utils/notifications/googlechat_sender.go@@ -0,0 +1,79 @@+package notifications++import (+ "context"+ "net/url"+ "strings"++ "emperror.dev/errors"++ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/nicholas-fedor/shoutrrr"+ shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"+)++// BuildGoogleChatURL converts GoogleChatConfig to Shoutrrr URL format by+// swapping the incoming webhook URL's scheme to googlechat while preserving+// the host, path and the key/token query parameters.+func BuildGoogleChatURL(config models.GoogleChatConfig) (string, error) {+ if config.WebhookURL == "" {+ return "", errors.New("google chat webhook URL is empty")+ }++ parsed, err := url.Parse(config.WebhookURL)+ if err != nil {+ return "", errors.WrapIf(err, "invalid google chat webhook URL")+ }++ // Accept a bare host without scheme, mirroring the generic webhook's URL+ // normalisation.+ if parsed.Host == "" && !strings.Contains(config.WebhookURL, "://") {+ normalized := strings.TrimPrefix(config.WebhookURL, "//")+ parsed, err = url.Parse("https://" + normalized)+ if err != nil {+ return "", errors.WrapIf(err, "invalid google chat webhook URL")+ }+ }++ if parsed.Host == "" {+ return "", errors.New("invalid google chat webhook URL: missing host")+ }++ switch strings.ToLower(parsed.Scheme) {+ case "http", "https":+ default:+ return "", errors.Errorf("invalid google chat webhook URL scheme: %s", parsed.Scheme)+ }++ shoutrrrURL := &url.URL{+ Scheme: "googlechat",+ Host: parsed.Host,+ Path: parsed.Path,+ RawQuery: parsed.Query().Encode(),+ }++ return shoutrrrURL.String(), nil+}++// SendGoogleChat sends a message via Shoutrrr's Google Chat service. The+// service posts plain text only ({"text": ...}) and ignores params, so the+// title is expected to already be part of the message body.+func SendGoogleChat(ctx context.Context, config models.GoogleChatConfig, message string) error {+ shoutrrrURL, err := BuildGoogleChatURL(config)+ if err != nil {+ return errors.WrapIf(err, "failed to build shoutrrr Google Chat URL")+ }++ sender, err := shoutrrr.CreateSenderWithOptions(shoutrrrTypes.SenderOptions{}, shoutrrrURL)+ if err != nil {+ return errors.WrapIf(err, "failed to create shoutrrr Google Chat sender")+ }++ errs := sender.Send(message, &shoutrrrTypes.Params{})+ for _, err := range errs {+ if err != nil {+ return errors.WrapIf(err, "failed to send Google Chat message via shoutrrr")+ }+ }+ return nil+}diff --git a/backend/pkg/utils/notifications/googlechat_sender_test.go b/backend/pkg/utils/notifications/googlechat_sender_test.gonew file mode 100644index 000000000..64114015f--- /dev/null+++ b/backend/pkg/utils/notifications/googlechat_sender_test.go@@ -0,0 +1,17 @@+package notifications++import (+ "testing"++ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestBuildGoogleChatURL(t *testing.T) {+ gotURL, err := BuildGoogleChatURL(models.GoogleChatConfig{+ WebhookURL: "https://chat.googleapis.com/v1/spaces/FOO/messages?key=bar&token=baz",+ })+ require.NoError(t, err)+ assert.Equal(t, "googlechat://chat.googleapis.com/v1/spaces/FOO/messages?key=bar&token=baz", gotURL)+}diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex f78f4369f..1d8fd8723 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -2419,6 +2419,15 @@"notifications_generic_custom_headers_label": "Custom Headers (Optional)","notifications_generic_custom_headers_placeholder": "Authorization:Bearer token, X-Custom:value","notifications_generic_custom_headers_help": "Comma-separated list of custom headers in format 'Key:Value' (e.g., Authorization:Bearer token)",+ "notifications_generic_payload_template_label": "Payload Template (Optional)",+ "notifications_generic_payload_template_help": "Custom request body for endpoints that require a specific payload shape, such as a nested JSON object. Leave empty to send the default flat JSON payload. Available variables:",+ "notifications_generic_success_body_label": "Success Body Contains (Optional)",+ "notifications_generic_success_body_placeholder": "\"code\":200",+ "notifications_generic_success_body_help": "Text that must appear in the response body for the notification to count as delivered. Useful for providers that always return HTTP 200 but report failures inside the response body.",+ "notifications_googlechat_title": "Google Chat",+ "notifications_googlechat_description": "Send notifications to a Google Chat space via an incoming webhook",+ "notifications_googlechat_webhook_url_placeholder": "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN",+ "notifications_googlechat_webhook_url_help": "The incoming webhook URL from your Google Chat space (Apps & integrations > Webhooks)","notifications_test_notification": "Test Provider","notifications_unsaved_changes_title": "Unsaved Changes","notifications_unsaved_changes_description": "You have unsaved changes. Would you like to save them before testing?",diff --git a/frontend/src/lib/types/notifications.ts b/frontend/src/lib/types/notifications.tsindex 85c519a46..d4bf6751d 100644--- a/frontend/src/lib/types/notifications.ts+++ b/frontend/src/lib/types/notifications.ts@@ -10,6 +10,7 @@ export type NotificationProvider =| 'pushover'| 'gotify'| 'matrix'+ | 'googlechat'| 'generic';export type EmailTLSMode = 'none' | 'starttls' | 'ssl';export type EmailAuthMode = 'none' | 'auto' | 'plain' | 'login' | 'crammd5';@@ -36,6 +37,7 @@ export const NOTIFICATION_PROVIDER_KEYS = ['discord','email','generic',+ 'googlechat','gotify','matrix','ntfy',@@ -140,6 +142,10 @@ export interface GotifyFormValues extends BaseProviderFormValues {useHeader: boolean;}+export interface GoogleChatFormValues extends BaseProviderFormValues {+ webhookUrl: string;+}+export interface MatrixFormValues extends BaseProviderFormValues {host: string;port: number;@@ -156,6 +162,8 @@ export interface GenericFormValues extends BaseProviderFormValues {titleKey: string;messageKey: string;customHeaders: string;+ payloadTemplate: string;+ successBodyContains: string;}export type ProviderFormValuesMap = {@@ -168,6 +176,7 @@ export type ProviderFormValuesMap = {pushover: PushoverFormValues;gotify: GotifyFormValues;matrix: MatrixFormValues;+ googlechat: GoogleChatFormValues;generic: GenericFormValues;};@@ -496,6 +505,16 @@ export function matrixSettingsToFormValues(settings?: NotificationSettings): Mat};}+export function googleChatSettingsToFormValues(settings?: NotificationSettings): GoogleChatFormValues {+ const cfg = getConfig(settings);+ const events = getEvents(cfg);+ return {+ enabled: settings?.enabled ?? false,+ webhookUrl: getString(cfg, 'webhookUrl'),+ ...eventFlagsToFormValues(events)+ };+}+export function genericSettingsToFormValues(settings?: NotificationSettings): GenericFormValues {const cfg = getConfig(settings);const events = getEvents(cfg);@@ -513,6 +532,8 @@ export function genericSettingsToFormValues(settings?: NotificationSettings): GetitleKey: getString(cfg, 'titleKey', 'title'),messageKey: getString(cfg, 'messageKey', 'message'),customHeaders: customHeadersStr,+ payloadTemplate: getString(cfg, 'payloadTemplate'),+ successBodyContains: getString(cfg, 'successBodyContains'),...eventFlagsToFormValues(events)};}@@ -620,6 +641,23 @@ export function matrixFormValuesToSettings(values: MatrixFormValues): Notificati};}+export function googleChatFormValuesToSettings(values: GoogleChatFormValues): NotificationSettings {+ return {+ provider: 'googlechat',+ enabled: values.enabled,+ config: {+ webhookUrl: values.webhookUrl,+ events: {+ image_update: values.eventImageUpdate,+ container_update: values.eventContainerUpdate,+ vulnerability_found: values.eventVulnerabilityFound,+ prune_report: values.eventPruneReport,+ auto_heal: values.eventAutoHeal+ }+ }+ };+}+export function genericFormValuesToSettings(values: GenericFormValues): NotificationSettings {const customHeaders: Record<string, string> = {};if (values.customHeaders) {@@ -645,6 +683,8 @@ export function genericFormValuesToSettings(values: GenericFormValues): NotificatitleKey: values.titleKey,messageKey: values.messageKey,customHeaders: customHeaders,+ payloadTemplate: values.payloadTemplate,+ successBodyContains: values.successBodyContains,events: {image_update: values.eventImageUpdate,container_update: values.eventContainerUpdate,diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelteindex 3f51945bb..e03c0fd36 100644--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte@@ -20,6 +20,7 @@type PushoverFormValues,type GotifyFormValues,type MatrixFormValues,+ type GoogleChatFormValues,type GenericFormValues,type NotificationProviderKey,NOTIFICATION_PROVIDER_KEYS,@@ -32,6 +33,7 @@pushoverSettingsToFormValues,gotifySettingsToFormValues,matrixSettingsToFormValues,+ googleChatSettingsToFormValues,genericSettingsToFormValues,discordFormValuesToSettings,emailFormValuesToSettings,@@ -42,6 +44,7 @@pushoverFormValuesToSettings,gotifyFormValuesToSettings,matrixFormValuesToSettings,+ googleChatFormValuesToSettings,genericFormValuesToSettings} from '#lib/types/notifications';import { NotificationsIcon } from '#lib/icons';@@ -60,11 +63,15 @@defaultTab: () => 'email'});const providerTab = $derived(urlTab.value);+ // Providers whose display name is not just a capitalised key.+ const providerTabLabels: Partial<Record<NotificationProviderKey, string>> = {+ googlechat: 'Google Chat'+ };const providerTabItems = NOTIFICATION_PROVIDER_KEYS.map((provider) =>({value: provider,- label: provider.charAt(0).toUpperCase() + provider.slice(1)+ label: providerTabLabels[provider] ?? provider.charAt(0).toUpperCase() + provider.slice(1)}) satisfies TabItem);@@ -88,6 +95,7 @@let pushoverFormRef: ReturnType<typeof BuiltInProviderForm>;let gotifyFormRef: ReturnType<typeof BuiltInProviderForm>;let matrixFormRef: ReturnType<typeof BuiltInProviderForm>;+ let googlechatFormRef: ReturnType<typeof BuiltInProviderForm>;let genericFormRef: ReturnType<typeof BuiltInProviderForm>;// Saved settings from server (used to detect if settings exist)@@ -101,6 +109,7 @@pushover: null,gotify: null,matrix: null,+ googlechat: null,generic: null});@@ -114,6 +123,7 @@let pushoverValues = $state<PushoverFormValues>(pushoverSettingsToFormValues());let gotifyValues = $state<GotifyFormValues>(gotifySettingsToFormValues());let matrixValues = $state<MatrixFormValues>(matrixSettingsToFormValues());+ let googlechatValues = $state<GoogleChatFormValues>(googleChatSettingsToFormValues());let genericValues = $state<GenericFormValues>(genericSettingsToFormValues());// Baseline values - what was last saved (for change detection)@@ -126,6 +136,7 @@let pushoverBaseline = $state<PushoverFormValues>(pushoverSettingsToFormValues());let gotifyBaseline = $state<GotifyFormValues>(gotifySettingsToFormValues());let matrixBaseline = $state<MatrixFormValues>(matrixSettingsToFormValues());+ let googlechatBaseline = $state<GoogleChatFormValues>(googleChatSettingsToFormValues());let genericBaseline = $state<GenericFormValues>(genericSettingsToFormValues());// Change detection@@ -138,6 +149,7 @@const pushoverHasChanges = $derived(JSON.stringify(pushoverValues) !== JSON.stringify(pushoverBaseline));const gotifyHasChanges = $derived(JSON.stringify(gotifyValues) !== JSON.stringify(gotifyBaseline));const matrixHasChanges = $derived(JSON.stringify(matrixValues) !== JSON.stringify(matrixBaseline));+ const googlechatHasChanges = $derived(JSON.stringify(googlechatValues) !== JSON.stringify(googlechatBaseline));const genericHasChanges = $derived(JSON.stringify(genericValues) !== JSON.stringify(genericBaseline));const hasChanges = $derived(emailHasChanges ||@@ -149,6 +161,7 @@pushoverHasChanges ||gotifyHasChanges ||matrixHasChanges ||+ googlechatHasChanges ||genericHasChanges);@@ -202,6 +215,9 @@matrixValues = matrixSettingsToFormValues(savedSettings.matrix ?? undefined);matrixBaseline = { ...matrixValues };+ googlechatValues = googleChatSettingsToFormValues(savedSettings.googlechat ?? undefined);+ googlechatBaseline = { ...googlechatValues };+genericValues = genericSettingsToFormValues(savedSettings.generic ?? undefined);genericBaseline = { ...genericValues };});@@ -217,6 +233,7 @@const pushoverValid = pushoverFormRef?.isValid() ?? true;const gotifyValid = gotifyFormRef?.isValid() ?? true;const matrixValid = matrixFormRef?.isValid() ?? true;+ const googlechatValid = googlechatFormRef?.isValid() ?? true;const genericValid = genericFormRef?.isValid() ?? true;if (@@ -230,6 +247,7 @@pushoverValid &&gotifyValid &&matrixValid &&+ googlechatValid &&genericValid)) {@@ -358,6 +376,19 @@}}+ // Save Google Chat settings if changed+ if (googlechatHasChanges) {+ try {+ const settings = googleChatFormValuesToSettings(googlechatValues);+ await notificationService.updateSettings('googlechat', settings);+ savedSettings.googlechat = settings;+ googlechatBaseline = { ...googlechatValues };+ } catch (error: any) {+ const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';+ errors.push(m.notifications_saved_failed({ provider: 'Google Chat', error: errorMsg }));+ }+ }+// Save Generic settings if changedif (genericHasChanges) {try {@@ -394,6 +425,7 @@pushoverValues = { ...pushoverBaseline };gotifyValues = { ...gotifyBaseline };matrixValues = { ...matrixBaseline };+ googlechatValues = { ...googlechatBaseline };genericValues = { ...genericBaseline };}@@ -555,6 +587,18 @@/></Tabs.Content>+ <Tabs.Content value="googlechat" class="mt-4 space-y-4">+ <BuiltInProviderForm+ bind:this={googlechatFormRef}+ provider="googlechat"+ bind:values={googlechatValues}+ disabled={isReadOnly}+ {isTesting}+ hasExistingCredentials={savedSettings.googlechat !== null}+ onTest={(testType) => testNotification('googlechat', testType)}+ />+ </Tabs.Content>+<Tabs.Content value="generic" class="mt-4 space-y-4"><BuiltInProviderFormbind:this={genericFormRef}diff --git a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelteindex 8cf0d2f19..0cb8da8eb 100644--- a/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte+++ b/frontend/src/routes/(app)/settings/notifications/providers/BuiltInProviderForm.svelte@@ -14,6 +14,13 @@type AnyBuiltInValues = ProviderFormValuesMap[NotificationProviderKey];+ // Go template syntax is deliberately kept out of the translatable messages:+ // the `{{ }}` delimiters collide with the message compiler's own placeholder+ // syntax, and the variable names are code rather than prose to translate.+ const GENERIC_PAYLOAD_TEMPLATE_PLACEHOLDER = '{"text": "{{.message}}"}';+ const GENERIC_PAYLOAD_TEMPLATE_VARS =+ '{{.title}}, {{.message}}, {{.environment}}, {{.environmentId}}, {{.event}}, {{.timestamp}}';+interface Props {provider: NotificationProviderKey;values: AnyBuiltInValues;@@ -73,6 +80,10 @@title: m.notifications_matrix_title(),description: m.notifications_matrix_description()},+ googlechat: {+ title: m.notifications_googlechat_title(),+ description: m.notifications_googlechat_description()+ },generic: {title: m.notifications_generic_title(),description: m.notifications_generic_description()@@ -339,6 +350,16 @@if (!d.enabled) return;addRequiredTrimmedFieldIssue(ctx, d.host, 'host', m.common_required());}),+ googlechat: z+ .object({+ enabled: z.boolean(),+ webhookUrl: z.string(),+ ...eventSubscriptionSchemaFields+ })+ .superRefine((d, ctx) => {+ if (!d.enabled) return;+ addRequiredTrimmedFieldIssue(ctx, d.webhookUrl, 'webhookUrl', 'Webhook URL is required when Google Chat is enabled');+ }),generic: z.object({enabled: z.boolean(),@@ -348,6 +369,8 @@titleKey: z.string(),messageKey: z.string(),customHeaders: z.string(),+ payloadTemplate: z.string(),+ successBodyContains: z.string(),...eventSubscriptionSchemaFields}).superRefine((d, ctx) => {@@ -1016,6 +1039,16 @@description: m.use_http_instead_of_https_not_recommended_for_production()}],+ googlechat: [+ {+ kind: 'input',+ key: 'webhookUrl',+ id: 'googlechat-webhook-url',+ label: m.webhook_url(),+ placeholder: m.notifications_googlechat_webhook_url_placeholder(),+ helpText: m.notifications_googlechat_webhook_url_help()+ }+ ],generic: [{kind: 'input',@@ -1064,6 +1097,23 @@label: m.notifications_generic_custom_headers_label(),placeholder: m.notifications_generic_custom_headers_placeholder(),helpText: m.notifications_generic_custom_headers_help()+ },+ {+ kind: 'textarea',+ key: 'payloadTemplate',+ id: 'generic-payload-template',+ label: m.notifications_generic_payload_template_label(),+ placeholder: GENERIC_PAYLOAD_TEMPLATE_PLACEHOLDER,+ helpText: `${m.notifications_generic_payload_template_help()} ${GENERIC_PAYLOAD_TEMPLATE_VARS}`,+ rows: 4+ },+ {+ kind: 'input',+ key: 'successBodyContains',+ id: 'generic-success-body-contains',+ label: m.notifications_generic_success_body_label(),+ placeholder: m.notifications_generic_success_body_placeholder(),+ helpText: m.notifications_generic_success_body_help()}]};diff --git a/tests/spec/settings-notifications.spec.ts b/tests/spec/settings-notifications.spec.tsindex 290cb098c..ae6db0a05 100644--- a/tests/spec/settings-notifications.spec.ts+++ b/tests/spec/settings-notifications.spec.ts@@ -40,6 +40,9 @@ test.describe('Notification settings', () => {let saveEndpointCalled = false;let testEndpointCalled = false;+ // Saved settings are kept in memory and served back on GET so that a+ // reload round-trips them through the form like the real backend would.+ const persistedSettings: Array<Record<string, unknown>> = [];await page.route('**/api/environments/*/notifications/settings', async (route) => {const req = route.request();@@ -47,17 +50,24 @@ test.describe('Notification settings', () => {await route.fulfill({status: 200,contentType: 'application/json',- body: JSON.stringify([])+ body: JSON.stringify(persistedSettings)});return;}if (req.method() === 'POST') {saveEndpointCalled = true;+ const saved = req.postDataJSON() as Record<string, unknown>;+ const index = persistedSettings.findIndex((s) => s.provider === saved.provider);+ if (index >= 0) {+ persistedSettings[index] = saved;+ } else {+ persistedSettings.push(saved);+ }await route.fulfill({status: 200,contentType: 'application/json',- body: JSON.stringify({ success: true })+ body: JSON.stringify(saved)});return;}@@ -223,6 +233,35 @@ test.describe('Notification settings', () => {getErrorCheck();});+ test('should allow configuring a custom generic webhook payload template', async ({ page }) => {+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'generic');++ await openProviderTab(page, 'Generic');+ await enableCurrentProvider(page);++ await page.getByPlaceholder('https://example.com/webhook').fill('https://example.com/webhook');++ const template = '{"receiveIdType":"chat_id","msgType":"text","text":"{{.message}}"}';+ await page.locator('#generic-payload-template').fill(template);++ await openTestMenu(page);+ await page.getByRole('menuitem', { name: 'Simple Test Notification', exact: true }).click();++ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });+ if (await saveAndTestButton.isVisible().catch(() => false)) {+ await saveAndTestButton.click();+ }++ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);+ getErrorCheck();++ // The template must survive a reload, proving it round-trips through the+ // save path and back into the form.+ await page.reload();+ await openProviderTab(page, 'Generic');+ await expect(page.locator('#generic-payload-template')).toHaveValue(template);+ });+test('should allow testing signal notifications', async ({ page }) => {const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'signal');diff --git a/types/notification/notification.go b/types/notification/notification.goindex d44ceab5f..1e7c20438 100644--- a/types/notification/notification.go+++ b/types/notification/notification.go@@ -31,9 +31,15 @@ const (// NotificationProviderPushover is the builtin Pushover notification provider.NotificationProviderPushover Provider = "pushover"+ // NotificationProviderGotify is the builtin Gotify notification provider.+ NotificationProviderGotify Provider = "gotify"+// NotificationProviderMatrix is the builtin Matrix webhook notification provider.NotificationProviderMatrix Provider = "matrix"+ // NotificationProviderGoogleChat is the builtin Google Chat notification provider.+ NotificationProviderGoogleChat Provider = "googlechat"+// NotificationProviderGeneric is the builtin Generic webhook notification provider.NotificationProviderGeneric Provider = "generic")