package notify // Channel configuration: validation, at-rest encryption, API masking and // the per-kind send adapters (DESIGN_NOTIFICATIONS.md). // // Secrets (webhook URLs, tokens) are encrypted with internal/crypto under // the same EncryptionSecret as IMAP passwords — the version-byte format and // legacy fallback live there; this package never sniffs ciphertext itself. // GET responses only ever carry masked config; a PATCH that echoes the mask // back keeps the stored secret (write-only fields). // // All HTTP sends dial through netguard (443/80 only, private ranges // blocked unless the operator pinned the host via NETGUARD_TRUSTED_HOSTS — // e.g. a LAN Matrix homeserver) inside outbound.Reserve budgets owned by // the engine, never per-adapter. import ( "bytes" "context" "encoding/json" "errors" "fmt" "net" "net/http" "net/mail" "net/url" "strings" "time" crypt "github.com/andrew/superbrain/internal/crypto" "github.com/andrew/superbrain/internal/db" "github.com/andrew/superbrain/internal/mailer" "github.com/andrew/superbrain/internal/netguard" ) // Kinds is the phase-1 channel set (mirrors the NotificationChannel CHECK). var Kinds = []string{"email", "slack", "matrix", "telegram", "signal"} // ValidKind reports whether kind is a known channel kind. func ValidKind(kind string) bool { for _, k := range Kinds { if k == kind { return true } } return false } // secretFields are encrypted at rest and masked in every API response. var secretFields = map[string][]string{ "email": {}, "slack": {"webhookUrl"}, "matrix": {"accessToken"}, "telegram": {"botToken"}, // The signal-cli REST bridge authenticates by sender account on the // query string; treat the account identifier as a secret (masked, // encrypted at rest) like every other credential. "signal": {"account"}, } // MaskValue replaces a secret in API output. A PATCH carrying this exact // value for a secret field means "keep what is stored". const MaskValue = "••••••••" // Channel is a decrypted, in-memory channel. Config values are plaintext; // this struct must never be serialized to an API response directly. type Channel struct { ID string OwnerID string Kind string Name string Config map[string]string Enabled bool } // ValidateConfig enforces per-kind shape. It runs on create AND update so a // stored config can never drift into an undeliverable shape. func ValidateConfig(kind string, cfg map[string]string) error { if !ValidKind(kind) { return errors.New("unknown channel kind") } req := func(key string) string { return strings.TrimSpace(cfg[key]) } absURL := func(key, v string) error { u, err := url.Parse(v) if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { return fmt.Errorf("%s must be an absolute http(s) URL", key) } return nil } switch kind { case "email": if a := req("address"); a != "" { if parsed, err := mail.ParseAddress(a); err != nil || parsed.Address != a { return errors.New("address must be a valid email") } } case "slack": if err := absURL("webhookUrl", req("webhookUrl")); err != nil { return err } case "matrix": if err := absURL("homeserver", req("homeserver")); err != nil { return err } if req("roomId") == "" { return errors.New("roomId is required") } if req("accessToken") == "" { return errors.New("accessToken is required") } case "telegram": if req("botToken") == "" { return errors.New("botToken is required") } if req("chatId") == "" { return errors.New("chatId is required") } case "signal": if err := absURL("restUrl", req("restUrl")); err != nil { return err } if req("account") == "" { return errors.New("account is required") } if req("recipient") == "" { return errors.New("recipient is required") } } return nil } // EncryptConfig returns the jsonb text to store: plaintext fields as-is, // secret fields encrypted. Empty secrets stay empty (nothing to protect). func EncryptConfig(kind string, cfg map[string]string, secret string) (string, error) { out := map[string]any{} for k, v := range cfg { if isSecret(kind, k) && v != "" && v != MaskValue { enc, err := crypt.Encrypt(v, secret) if err != nil { return "", err } out[k] = enc continue } out[k] = v } raw, err := json.Marshal(out) return string(raw), err } // DecryptConfig reverses EncryptConfig. A secret that fails to decrypt // (e.g. after key loss) is surfaced as an error — delivery must fail loudly // rather than send an empty credential. func DecryptConfig(kind string, stored []byte, secret string) (map[string]string, error) { var raw map[string]any if err := json.Unmarshal(stored, &raw); err != nil { return nil, err } out := make(map[string]string, len(raw)) for k, v := range raw { s, _ := v.(string) if isSecret(kind, k) && s != "" { dec, err := crypt.Decrypt(s, secret) if err != nil { return nil, fmt.Errorf("channel secret %q cannot be decrypted: %w", k, err) } s = dec } out[k] = s } return out, nil } // MaskConfig produces the API-safe projection: secrets replaced by // MaskValue, everything else as stored (decrypted plaintext for // non-secret fields). func MaskConfig(kind string, cfg map[string]string) map[string]string { out := make(map[string]string, len(cfg)) for k, v := range cfg { if isSecret(kind, k) && v != "" { out[k] = MaskValue continue } out[k] = v } return out } func isSecret(kind, key string) bool { for _, f := range secretFields[kind] { if f == key { return true } } return false } // MergeMasked implements the write-only-secret PATCH rule: a submitted // config whose secret field carries MaskValue keeps the stored value. func MergeMasked(submitted, stored map[string]string, kind string) map[string]string { out := make(map[string]string, len(submitted)) for k, v := range submitted { if isSecret(kind, k) && v == MaskValue { out[k] = stored[k] continue } out[k] = v } return out } // notifyClient mirrors the preview client: netguard dial, bounded // redirects, shared idle-connection pool. One client for all webhook kinds. var notifyClient = &http.Client{ Timeout: 20 * time.Second, Transport: &http.Transport{ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { if netguard.AllowPrivate() { return netguard.DialContext(ctx, network, address) } return netguard.DialContextPorts(ctx, network, address, 80, 443) }, IdleConnTimeout: 30 * time.Second, MaxIdleConns: 16, MaxIdleConnsPerHost: 4, }, CheckRedirect: func(r *http.Request, via []*http.Request) error { if len(via) > 3 { return errors.New("too many redirects") } return nil }, } // Send delivers one notification through the channel. The plaintext title // and body are identical across kinds; only the payload envelope differs. // Errors are returned for the engine to record (attempts, backoff) — this // layer never retries on its own. func Send(ctx context.Context, d *db.DB, ch Channel, title, body string) error { text := title if body != "" { text += "\n" + body } switch ch.Kind { case "email": to := strings.TrimSpace(ch.Config["address"]) if to == "" { // Default to the owner's account email. var email *string if err := d.QueryRowContext(ctx, `SELECT email FROM "User" WHERE id=$1`, ch.OwnerID).Scan(&email); err != nil { return fmt.Errorf("owner email lookup: %w", err) } if email == nil || *email == "" { return errors.New("channel has no address and the owner has no email") } to = *email } c := FooterLinks(ctx, d, ch.OwnerID, to) c.Headline, c.Body = title, body return mailer.SendTemplate(ctx, to, title, text, c) case "slack": return postJSON(ctx, ch.Config["webhookUrl"], nil, map[string]any{"text": text}, []int{200}) case "matrix": base := strings.TrimRight(ch.Config["homeserver"], "/") room := url.PathEscape(ch.Config["roomId"]) txn := url.PathEscape(fmt.Sprintf("sb%d", time.Now().UnixNano())) endpoint := fmt.Sprintf("%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s", base, room, txn) headers := http.Header{"Authorization": []string{"Bearer " + ch.Config["accessToken"]}} return postJSON(ctx, endpoint, headers, map[string]any{"msgtype": "m.text", "body": text}, []int{200}) case "telegram": endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", url.PathEscape(ch.Config["botToken"])) return postJSON(ctx, endpoint, nil, map[string]any{"chat_id": ch.Config["chatId"], "text": text}, []int{200}) case "signal": // signal-cli REST bridge contract: POST {restUrl}/v2/send?account=... // with {"message":..., "recipients":[...]}. The bridge is a // house-style LAN/service dependency, so the dial is netguarded // like every other webhook (private ranges need the test escape // hatch or an operator pin, exactly as SMTP relays do). endpoint := strings.TrimRight(ch.Config["restUrl"], "/") + "/v2/send?account=" + url.QueryEscape(ch.Config["account"]) return postJSON(ctx, endpoint, nil, map[string]any{ "message": text, "recipients": []string{ch.Config["recipient"]}, }, []int{200, 201, 204}) } return fmt.Errorf("unknown channel kind %q", ch.Kind) } // postJSON sends one webhook payload. want lists accepted status codes; // anything else is an error carrying the status (and a bounded body snippet // for logs — never full bodies, which may echo secrets). func postJSON(ctx context.Context, endpoint string, headers http.Header, payload any, want []int) error { raw, err := json.Marshal(payload) if err != nil { return err } method := http.MethodPost if headers != nil && headers.Get("Authorization") != "" && strings.Contains(endpoint, "/_matrix/") { method = http.MethodPut // Matrix's send endpoint is a PUT keyed by txn id } req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(raw)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") for k, vs := range headers { for _, v := range vs { req.Header.Add(k, v) } } res, err := notifyClient.Do(req) if err != nil { return err } defer res.Body.Close() for _, w := range want { if res.StatusCode == w { return nil } } snippet := make([]byte, 200) n, _ := res.Body.Read(snippet) return fmt.Errorf("webhook answered %d: %s", res.StatusCode, strings.TrimSpace(string(snippet[:n]))) }