package handlers // Notification channels, rules and history (DESIGN_NOTIFICATIONS.md). // Owner-scoped like every user resource; mutating PATCHes carry the // expected version (409 on stale base, the house mutation contract). // Channel secrets are write-only: responses carry the masked projection, // and a PATCH echoing the mask keeps the stored secret. import ( "context" "encoding/json" "errors" "fmt" "math" "net/http" "sort" "strconv" "strings" "time" "github.com/andrew/superbrain/internal/config" "github.com/andrew/superbrain/internal/db" "github.com/andrew/superbrain/internal/notify" "github.com/andrew/superbrain/internal/outbound" ) // errPlanGate answers 403 for features the tenant's plan does not include. // The entitlement catalog (not TIER) is the gate — see AGENTS.md invariant. func planGate(w http.ResponseWriter) { respond(w, 403, Error{Error: "Not available on your plan"}, nil) } // userTenantAllows resolves the caller's plan via their tenant and reports // whether a channel kind is included. func userTenantAllows(r *http.Request, kind string) (bool, error) { var tenantID *string if e := database(r).QueryRowContext(r.Context(), `SELECT "tenantId" FROM "User" WHERE id=$1`, user(r)).Scan(&tenantID); e != nil { return false, e } tid := "" if tenantID != nil { tid = *tenantID } lim, e := db.NewTenantRepo(database(r)).Limits(r.Context(), tid) if e != nil { return false, e } return lim.AllowChannel(kind), nil } // channelConfigFields is the per-kind key allowlist: unknown submitted keys // are dropped so stored configs stay auditable. func channelConfigFields(kind string) []string { switch kind { case "email": return []string{"address"} case "slack": return []string{"webhookUrl"} case "matrix": return []string{"homeserver", "roomId", "accessToken"} case "telegram": return []string{"botToken", "chatId"} } return nil } func cleanChannelConfig(kind string, raw any) (map[string]string, error) { cfg := map[string]string{} if raw == nil { return cfg, nil } m, ok := raw.(map[string]any) if !ok { return nil, bad("Config must be an object") } for _, key := range channelConfigFields(kind) { if v, ok := m[key]; ok { s, ok := v.(string) if !ok { return nil, bad("Config values must be text") } s = strings.TrimSpace(s) if len(s) > 2000 { return nil, bad("Config value too long") } cfg[key] = s } } return cfg, nil } // storedConfigJSON normalizes the jsonb config column (to_jsonb yields a // map; direct reads may yield a string) into JSON text for the notify // package's decrypt path. func storedConfigJSON(row object) []byte { switch c := row["config"].(type) { case string: if c == "" { return []byte("{}") } return []byte(c) case map[string]any: raw, _ := json.Marshal(c) return raw } return []byte("{}") } // channelProjection is the only shape channel data ever leaves the server // in: plaintext non-secret config plus the mask over secret fields. func channelProjection(row object) object { kind := str(row, "kind") cfg := map[string]string{} if dec, err := notify.DecryptConfig(kind, storedConfigJSON(row), config.Load().EncryptionSecret()); err == nil { cfg = notify.MaskConfig(kind, dec) } return object{ "id": row["id"], "kind": kind, "name": row["name"], "enabled": row["enabled"], "version": row["version"], "config": cfg, "createdAt": row["createdAt"], } } // requiredVersion enforces the house mutation contract: every mutating // PATCH sends the base version it edited from. func requiredVersion(b object) (int, error) { v, present := b["version"] if !present { return 0, bad("version is required; refetch the record and retry") } f, ok := v.(float64) if !ok || f < 0 || f != math.Trunc(f) { return 0, bad("version must be a non-negative integer") } return int(f), nil } // patchVersioned applies server-owned updates with the optimistic version // guard and bumps version+updatedAt. Keys come from handler allowlists, // never from request data; values are bind parameters. A row that moved on // since the caller's read is a 409 (rows-affected 0 -> ErrNotFound from // the RETURNING scan). func patchVersioned(r *http.Request, table, id string, baseVersion int, updates object) (object, error) { keys := make([]string, 0, len(updates)) for k := range updates { keys = append(keys, k) } sort.Strings(keys) sets := make([]string, 0, len(keys)+2) args := make([]any, 0, len(keys)+3) for _, k := range keys { args = append(args, updates[k]) sets = append(sets, db.Quote(k)+fmt.Sprintf("=$%d", len(args))) } sets = append(sets, `version=version+1`, `"updatedAt"=now()`) args = append(args, id, user(r), baseVersion) q := `UPDATE ` + db.Quote(table) + ` SET ` + strings.Join(sets, ",") + fmt.Sprintf(` WHERE id=$%d AND "ownerId"=$%d AND version=$%d RETURNING to_jsonb(`, len(args)-2, len(args)-1, len(args)) + db.Quote(table) + `)` row, err := db.One(r.Context(), database(r), q, args...) if errors.Is(err, db.ErrNotFound) { return nil, conflict("Modified elsewhere; reload to see the latest version") } return row, err } func truncate(s string, n int) string { rs := []rune(s) if len(rs) <= n { return s } return string(rs[:n]) } func HandleNotificationChannelsList(w http.ResponseWriter, r *http.Request) { rows, e := db.Many(r.Context(), database(r), `SELECT to_jsonb(t) FROM "NotificationChannel" t WHERE "ownerId"=$1 ORDER BY "createdAt"`, user(r)) if e != nil { respond(w, 0, nil, e) return } out := []object{} for _, row := range rows { out = append(out, channelProjection(row)) } respond(w, 200, out, nil) } func HandleNotificationChannelsCreate(w http.ResponseWriter, r *http.Request) { b, ok := read(w, r) if !ok { return } kind := str(b, "kind") if !notify.ValidKind(kind) { respond(w, 0, nil, bad("Unknown channel kind")) return } name := strings.TrimSpace(str(b, "name")) if name == "" || len([]rune(name)) > 120 { respond(w, 0, nil, bad("Name is required (max 120 characters)")) return } allow, e := userTenantAllows(r, kind) if e != nil { respond(w, 0, nil, e) return } if !allow { planGate(w) return } cfg, e := cleanChannelConfig(kind, b["config"]) if e != nil { respond(w, 0, nil, e) return } if e := notify.ValidateConfig(kind, cfg); e != nil { respond(w, 0, nil, bad(e.Error())) return } enc, e := notify.EncryptConfig(kind, cfg, config.Load().EncryptionSecret()) if e != nil { respond(w, 0, nil, e) return } enabled := true if v, ok := b["enabled"].(bool); ok { enabled = v } row, e := db.Insert(r.Context(), database(r), "NotificationChannel", object{ "id": db.NewID(), "ownerId": user(r), "kind": kind, "name": name, "config": enc, "enabled": enabled, }) if e != nil { respond(w, 0, nil, e) return } respond(w, 201, channelProjection(row), nil) } func HandleNotificationChannelsUpdate(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") existing, e := owned(r, database(r), "NotificationChannel", id, "ownerId") if e != nil { respond(w, 0, nil, e) return } b, ok := read(w, r) if !ok { return } baseVersion, e := requiredVersion(b) if e != nil { respond(w, 0, nil, e) return } if stored, _ := existing["version"].(float64); int(stored) != baseVersion { respond(w, 0, nil, conflict("Channel was modified elsewhere; reload to see the latest version")) return } kind := str(existing, "kind") updates := object{} if _, present := b["name"]; present { s := strings.TrimSpace(str(b, "name")) if s == "" || len([]rune(s)) > 120 { respond(w, 0, nil, bad("Name must be 1-120 characters")) return } updates["name"] = s } if v, present := b["enabled"]; present { ev, ok := v.(bool) if !ok { respond(w, 0, nil, bad("Enabled must be boolean")) return } updates["enabled"] = ev } if _, present := b["config"]; present { submitted, e := cleanChannelConfig(kind, b["config"]) if e != nil { respond(w, 0, nil, e) return } storedCfg, _ := notify.DecryptConfig(kind, storedConfigJSON(existing), config.Load().EncryptionSecret()) if storedCfg == nil { storedCfg = map[string]string{} } merged := notify.MergeMasked(submitted, storedCfg, kind) if e := notify.ValidateConfig(kind, merged); e != nil { respond(w, 0, nil, bad(e.Error())) return } enc, e := notify.EncryptConfig(kind, merged, config.Load().EncryptionSecret()) if e != nil { respond(w, 0, nil, e) return } updates["config"] = enc } if len(updates) == 0 { respond(w, 0, nil, bad("Nothing to update")) return } row, e := patchVersioned(r, "NotificationChannel", id, baseVersion, updates) if e != nil { respond(w, 0, nil, e) return } respond(w, 200, channelProjection(row), nil) } func HandleNotificationChannelsDelete(w http.ResponseWriter, r *http.Request) { respond(w, 200, object{"ok": true}, remove(r, "NotificationChannel", r.PathValue("id"), "ownerId")) } // HandleNotificationChannelsTest sends one message through the stored // config right now (same path as the engine, budget included) so a bad // webhook/token fails at setup time, not at 3am. func HandleNotificationChannelsTest(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") row, e := owned(r, database(r), "NotificationChannel", id, "ownerId") if e != nil { respond(w, 0, nil, e) return } kind := str(row, "kind") cfg, e := notify.DecryptConfig(kind, storedConfigJSON(row), config.Load().EncryptionSecret()) if e != nil { respond(w, 0, nil, bad("Stored credentials cannot be decrypted; re-enter them")) return } release, retry, ok := outbound.Reserve("notify-test:"+kind+":"+user(r), 10, time.Minute) if !ok { w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds()))) respond(w, 429, Error{Error: "Too many test sends, slow down"}, nil) return } defer release() ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() ch := notify.Channel{ID: id, OwnerID: user(r), Kind: kind, Config: cfg, Enabled: true} if e := notify.Send(ctx, database(r), ch, "Superbrain test notification", "Your "+kind+" channel is set up correctly."); e != nil { respond(w, 502, Error{Error: "Test delivery failed: " + truncate(e.Error(), 200)}, nil) return } respond(w, 200, object{"ok": true}, nil) } func HandleNotificationRulesList(w http.ResponseWriter, r *http.Request) { rows, e := db.Many(r.Context(), database(r), ` SELECT to_jsonb(r) || jsonb_build_object('channelKind', c.kind, 'channelName', c.name) FROM "NotificationRule" r JOIN "NotificationChannel" c ON c.id=r."channelId" WHERE r."ownerId"=$1 ORDER BY r."createdAt"`, user(r)) if e != nil { respond(w, 0, nil, e) return } out := []object{} for _, row := range rows { out = append(out, ruleProjection(row, str(row, "channelKind"), str(row, "channelName"))) } respond(w, 200, out, nil) } func HandleNotificationRulesCreate(w http.ResponseWriter, r *http.Request) { b, ok := read(w, r) if !ok { return } name := strings.TrimSpace(str(b, "name")) if name == "" || len([]rune(name)) > 120 { respond(w, 0, nil, bad("Name is required (max 120 characters)")) return } trigger := str(b, "trigger") if trigger != "signal_created" && trigger != "bookmark_due" { respond(w, 0, nil, bad("Trigger must be signal_created or bookmark_due")) return } channel, e := owned(r, database(r), "NotificationChannel", str(b, "channelId"), "ownerId") if e != nil { respond(w, 0, nil, bad("Channel not found")) return } allow, e := userTenantAllows(r, str(channel, "kind")) if e != nil { respond(w, 0, nil, e) return } if !allow { planGate(w) return } cfg := object{} if trigger == "bookmark_due" { lead := 24 if c, ok := b["config"].(map[string]any); ok { if v, ok := c["leadHours"].(float64); ok && v >= 0 && v <= 24*30 { lead = int(v) } } cfg["leadHours"] = lead } raw, _ := json.Marshal(cfg) cooldown := 60 if v, ok := b["cooldownMinutes"].(float64); ok && v >= 1 && v <= 7*24*60 { cooldown = int(v) } enabled := true if v, ok := b["enabled"].(bool); ok { enabled = v } row, e := db.Insert(r.Context(), database(r), "NotificationRule", object{ "id": db.NewID(), "ownerId": user(r), "name": name, "trigger": trigger, "config": string(raw), "channelId": str(b, "channelId"), "cooldownMinutes": cooldown, "enabled": enabled, }) if e != nil { respond(w, 0, nil, e) return } respond(w, 201, ruleProjection(row, str(channel, "kind"), str(channel, "name")), nil) } func HandleNotificationRulesUpdate(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") existing, e := owned(r, database(r), "NotificationRule", id, "ownerId") if e != nil { respond(w, 0, nil, e) return } b, ok := read(w, r) if !ok { return } baseVersion, e := requiredVersion(b) if e != nil { respond(w, 0, nil, e) return } if stored, _ := existing["version"].(float64); int(stored) != baseVersion { respond(w, 0, nil, conflict("Rule was modified elsewhere; reload to see the latest version")) return } updates := object{} if _, present := b["name"]; present { s := strings.TrimSpace(str(b, "name")) if s == "" || len([]rune(s)) > 120 { respond(w, 0, nil, bad("Name must be 1-120 characters")) return } updates["name"] = s } if v, present := b["enabled"]; present { ev, ok := v.(bool) if !ok { respond(w, 0, nil, bad("Enabled must be boolean")) return } updates["enabled"] = ev } if v, present := b["cooldownMinutes"]; present { cv, ok := v.(float64) if !ok || cv < 1 || cv > 7*24*60 { respond(w, 0, nil, bad("cooldownMinutes must be 1..10080")) return } updates["cooldownMinutes"] = int(cv) } if _, present := b["channelId"]; present { channel, e := owned(r, database(r), "NotificationChannel", str(b, "channelId"), "ownerId") if e != nil { respond(w, 0, nil, bad("Channel not found")) return } allow, e := userTenantAllows(r, str(channel, "kind")) if e != nil { respond(w, 0, nil, e) return } if !allow { planGate(w) return } updates["channelId"] = str(b, "channelId") } if _, present := b["config"]; present && str(existing, "trigger") == "bookmark_due" { lead := 24 if c, ok := b["config"].(map[string]any); ok { if lv, ok := c["leadHours"].(float64); ok && lv >= 0 && lv <= 24*30 { lead = int(lv) } } raw, _ := json.Marshal(object{"leadHours": lead}) updates["config"] = string(raw) } if len(updates) == 0 { respond(w, 0, nil, bad("Nothing to update")) return } row, e := patchVersioned(r, "NotificationRule", id, baseVersion, updates) if e != nil { respond(w, 0, nil, e) return } kind, name := "", "" if ch, e := owned(r, database(r), "NotificationChannel", str(row, "channelId"), "ownerId"); e == nil { kind, name = str(ch, "kind"), str(ch, "name") } respond(w, 200, ruleProjection(row, kind, name), nil) } func HandleNotificationRulesDelete(w http.ResponseWriter, r *http.Request) { respond(w, 200, object{"ok": true}, remove(r, "NotificationRule", r.PathValue("id"), "ownerId")) } // HandleNotificationsList is the owner's recent delivery history. func HandleNotificationsList(w http.ResponseWriter, r *http.Request) { rows, e := db.Many(r.Context(), database(r), ` SELECT to_jsonb(n) || jsonb_build_object('ruleName', r.name, 'channelKind', c.kind) FROM "Notification" n JOIN "NotificationRule" r ON r.id = n."ruleId" JOIN "NotificationChannel" c ON c.id = r."channelId" WHERE n."ownerId"=$1 ORDER BY n."createdAt" DESC LIMIT 100`, user(r)) if e != nil { respond(w, 0, nil, e) return } out := []object{} for _, row := range rows { out = append(out, object{ "id": row["id"], "title": row["title"], "body": row["body"], "status": row["status"], "attempts": row["attempts"], "ruleName": row["ruleName"], "channelKind": row["channelKind"], "sentAt": row["sentAt"], "createdAt": row["createdAt"], }) } respond(w, 200, out, nil) } func ruleProjection(row object, channelKind, channelName string) object { cfg := object{} switch c := row["config"].(type) { case map[string]any: cfg = c case string: if c != "" { _ = json.Unmarshal([]byte(c), &cfg) } } return object{ "id": row["id"], "name": row["name"], "trigger": row["trigger"], "config": cfg, "channelId": row["channelId"], "channelKind": channelKind, "channelName": channelName, "cooldownMinutes": row["cooldownMinutes"], "enabled": row["enabled"], "lastFiredAt": row["lastFiredAt"], "version": row["version"], "createdAt": row["createdAt"], } }