Add notification engine phase 1: channels, rules, plan-gated delivery
release gate / check (push) Failing after 6m54s

When something happens in the brain, tell the user (PLAN_PRICING_TIERS
step 3). The engine is a SCANNER, not a hook system: producers are never
instrumented; exactly-once comes solely from UNIQUE(ruleId,dedupeKey) +
ON CONFLICT DO NOTHING, so rescans are free and restarts are safe.

Schema (migration 013 + schema.sql, converge-verified):
NotificationChannel (secrets encrypted at rest via internal/crypto, the
IMAP-password format), NotificationRule (one channel per rule in phase 1,
cooldown, version column), Notification (dedupe ledger + delivery state:
pending/sent/failed/suppressed, attempts, backoff timestamp).

internal/notify: two triggers — signal_created (fires only for signals
newer than the rule, never retro-notifying history) and bookmark_due
(lead-hours window, dedupe key carries the UTC due date so moving a
dueDate re-notifies and same-day rescans do not). Delivery claims rows in
one short transaction (FOR UPDATE SKIP LOCKED, batch 10) so multiple app
instances never double-send; exponential backoff to 5 attempts; per-rule
cooldown; per-owner pending cap. Channels: email (internal/mailer,
falls back to the account email), Slack webhook, Matrix room, Telegram
bot — webhooks dial through netguard inside outbound.Reserve budgets.
The plan gate re-checks at delivery: a downgraded tenant's rows become
'suppressed' instead of sending. Signal-app delivery deliberately absent
(needs a daemon; see plan doc hard truths).

API: channel/rule CRUD with the house version contract (409 on stale
base), write-only secrets (masked in every response; a PATCH echoing the
mask keeps the stored value), test-send endpoint with its own budget,
owner-scoped delivery history. Channel kinds gate on the ENTITLEMENT
CATALOG (403 'Not available on your plan') — never on TIER, per the
tenancy invariant.

Web: Settings -> Notifications tab (channels with per-kind forms and
Test button, rule builder, recent-delivery strip). Data loading uses the
house promise-chain shape; setState only in async callbacks (SSR lint).

Fixes along the way: mailer send budget raised 5->20/min (shared by
resets and notifications; 5/min would throttle a hosted instance) and
outbound gains ResetBudget() wired into the test harness — the global
'smtp' window made password-reset and notification tests collide when
the package ran as a whole.

Tests: full channel/rule/engine integration pass (masking + encryption
round-trip, masked-PATCH preservation, version contract, plan gating via
a forced 'free' tenant, dedupe across rescans, cooldown, real SMTP and
webhook delivery via loopback fakes, backoff recording, downgrade
suppression, history). Full suite green with -race; web lint/SSR-eslint/
build clean. Docs: API.md endpoint table, RUNNING.md, AGENTS.md
invariants, DESIGN_NOTIFICATIONS.md (local).
This commit is contained in:
Andrew S Erwin
2026-10-26 14:43:15 -05:00
parent 1f38c4d56c
commit 451312c3cf
15 changed files with 2034 additions and 7 deletions
+296
View File
@@ -0,0 +1,296 @@
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"}
// 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"},
}
// 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")
}
}
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
}
return mailer.Send(ctx, to, title, text)
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})
}
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])))
}