Files
superbrain/internal/handlers/notifications.go
T
Andrew S Erwin 3b11ac83fc Notifications phase 2 (Gitea #10): share triggers, targeted people, Signal, managed-by footer
- share_received trigger: scanner fires when a bookmark, tag or collection
  is shared with the rule owner (same dedupe discipline; sharer name and
  item title in the message)
- config.targetUserIds on rules: same-tenant targets (<=20, validated at
  write time); each targeted Notification row carries recipientId and is
  delivered through the RECIPIENT's own enabled channel of the rule's kind,
  gated by the recipient's tenant plan (no channel => suppressed, visible
  in history); history lists rows you own or were targeted on
- signal channel kind: signal-cli REST bridge (POST {restUrl}/v2/send with
  account query param and recipients array); account encrypted + masked
  like every other credential; netguard-dialed like every webhook
- 'Managed by David's Superbrain.' footer is plan DATA: entitlements
  ManagedFooter (free hosted plan only; managed_footer override key),
  appended at delivery time - paying plans, core and self-hosted never
  carry it
- catalog: signal joins standard/premium/core/selfhosted channel lists
- migration 019 + schema.sql (trigger/kind CHECKs, Notification.recipientId)
- UI: trigger option, same-tenant target picker via /api/users/search,
  signal channel fields, targeted-count badge on rules
- tests: share/target/footer/signal legs against fake webhook, fake SMTP
  and a fake signal-cli bridge; entitlements footer assertions
2026-11-09 17:42:38 -06:00

655 lines
19 KiB
Go

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"}
case "signal":
return []string{"restUrl", "account", "recipient"}
}
return nil
}
// cleanRuleTargets validates configured notification targets: existing
// users in the caller's tenant, deduped, capped at 20. Cross-tenant
// targeting is refused so a rule can never dial another organization's
// channels; delivery uses each target's OWN enabled channel of the rule's
// kind (a target without one is suppressed, visible in history).
func cleanRuleTargets(r *http.Request, b object) ([]string, error) {
c, ok := b["config"].(map[string]any)
if !ok {
return nil, nil
}
raw, present := c["targetUserIds"]
if !present || raw == nil {
return nil, nil
}
list, ok := raw.([]any)
if !ok {
return nil, bad("config.targetUserIds must be an array")
}
seen := map[string]bool{}
out := []string{}
for _, v := range list {
id, _ := v.(string)
if id == "" || seen[id] {
return nil, bad("config.targetUserIds must be unique non-empty ids")
}
seen[id] = true
out = append(out, id)
}
if len(out) > 20 {
return nil, bad("config.targetUserIds may contain at most 20 users")
}
if len(out) == 0 {
return nil, nil
}
var tenantID *string
if e := database(r).QueryRowContext(r.Context(),
`SELECT "tenantId" FROM "User" WHERE id=$1`, user(r)).Scan(&tenantID); e != nil {
return nil, e
}
tid := ""
if tenantID != nil {
tid = *tenantID
}
var n int
if e := database(r).QueryRowContext(r.Context(),
`SELECT count(*) FROM "User" WHERE id = ANY($1) AND COALESCE("tenantId",'') = $2`,
out, tid).Scan(&n); e != nil {
return nil, e
}
if n != len(out) {
return nil, bad("config.targetUserIds must be users in your organization")
}
return out, 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" && trigger != "share_received" {
respond(w, 0, nil, bad("Trigger must be signal_created, bookmark_due or share_received"))
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
}
targets, e := cleanRuleTargets(r, b)
if e != nil {
respond(w, 0, nil, e)
return
}
if targets != nil {
cfg["targetUserIds"] = targets
}
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 {
// Start from the stored config so untouched keys survive a patch.
cfg := object{}
switch c := existing["config"].(type) {
case map[string]any:
for k, v := range c {
cfg[k] = v
}
case string:
if c != "" {
_ = json.Unmarshal([]byte(c), &cfg)
}
}
if str(existing, "trigger") == "bookmark_due" {
lead := 24
if v, ok := cfg["leadHours"].(float64); ok && v >= 0 && v <= 24*30 {
lead = int(v)
}
if c, ok := b["config"].(map[string]any); ok {
if lv, ok := c["leadHours"].(float64); ok && lv >= 0 && lv <= 24*30 {
lead = int(lv)
}
}
cfg["leadHours"] = lead
}
targets, e := cleanRuleTargets(r, b)
if e != nil {
respond(w, 0, nil, e)
return
}
if targets != nil {
cfg["targetUserIds"] = targets
}
raw, _ := json.Marshal(cfg)
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 OR n."recipientId"=$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"],
"recipientId": row["recipientId"],
"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"],
}
}