diff --git a/API.md b/API.md index 1918700..04e8027 100644 --- a/API.md +++ b/API.md @@ -235,6 +235,28 @@ already see. | POST | `/api/bookmarks/{id}/signals` | 201 watcher for `{type:"email",config:{from?,subject?}}`; `{checked,created}` for `{action:"check"}` | | PATCH | `/api/signal-sources/{id}` | Updated watcher for `{enabled:boolean}` | | DELETE | `/api/signal-sources/{id}` | `{ok:true}` | + +### Notifications + +Rules notify a channel when a fact appears (new signals, due bookmarks). +The engine scans every ~60s; rows dedupe on `("ruleId","dedupeKey")`. +Channel secrets are write-only: responses mask them (`••••••••`) and a +PATCH echoing the mask keeps the stored value. Channel kinds are gated by +the tenant's plan (403 `Not available on your plan`); the gate is the +entitlement catalog, never the deployment tier. + +| Method | Path | Body / Returns | +|---|---|---| +| GET | `/api/notifications/channels` | `[{id,kind,name,enabled,version,config(masked),createdAt}]` | +| POST | `/api/notifications/channels` | `{kind,name,config,enabled?}` → 201 masked projection; kinds: `email` (optional `address`, falls back to the account email; needs server SMTP), `slack` (`webhookUrl`), `matrix` (`homeserver`,`roomId`,`accessToken`), `telegram` (`botToken`,`chatId`) | +| PATCH | `/api/notifications/channels/{id}` | `{version, name?,enabled?,config?}` → 200; 409 on stale version | +| DELETE | `/api/notifications/channels/{id}` | `{ok:true}` | +| POST | `/api/notifications/channels/{id}/test` | Sends one message immediately → `{ok:true}`; 502 with the delivery error; 429 when the per-user test budget is spent | +| GET | `/api/notifications/rules` | `[{id,name,trigger,config,channelId,channelKind,channelName,cooldownMinutes,enabled,lastFiredAt,version}]` | +| POST | `/api/notifications/rules` | `{name,trigger,channelId,config?,cooldownMinutes?,enabled?}` → 201; triggers: `signal_created`, `bookmark_due` (`config.leadHours`, default 24) | +| PATCH | `/api/notifications/rules/{id}` | `{version, name?,enabled?,cooldownMinutes?,channelId?,config?}` → 200; 409 on stale version | +| DELETE | `/api/notifications/rules/{id}` | `{ok:true}` | +| GET | `/api/notifications` | Last 100 deliveries `[{id,title,body,status,attempts,ruleName,channelKind,sentAt,createdAt}]`; status ∈ pending/sent/failed/suppressed | | GET | `/api/alerts/check` | Undismissed bookmarks due within 15 minutes, soonest first | | DELETE | `/api/alerts/{bookmarkId}` | `{ok:true}`; sets `alertSent` | | GET | `/api/contacts` | Synced contacts with `_count.bookmarks` | diff --git a/RUNNING.md b/RUNNING.md index 28106df..ee208e9 100644 --- a/RUNNING.md +++ b/RUNNING.md @@ -252,6 +252,13 @@ The core app works without any external services. synced contact with a bookmark. - **Browser alerts:** Allow notifications when prompted. Alert checks run while the app is open in your browser. +- **Notifications:** In **Settings → Notifications**, add a delivery channel + (email, Slack webhook, Matrix room, Telegram bot) and rules that fire on + new mailbox signals or due bookmarks. Channel availability follows the + tenant's plan; secrets are encrypted at rest and never echoed back. + Email delivery uses the same `SMTP_*` configuration as password reset. + The engine scans every ~60 seconds; each fact notifies once per rule, + with per-rule cooldowns and delivery retries with backoff. - **Authelia:** OIDC sign-in is enabled when all three `OIDC_*` variables hold real values. The Next server validates the identity and Go provisions the local user. See [web/docs/AUTHELIA.md](web/docs/AUTHELIA.md) for client diff --git a/db/migrations/013_notifications.sql b/db/migrations/013_notifications.sql new file mode 100644 index 0000000..6d29cd0 --- /dev/null +++ b/db/migrations/013_notifications.sql @@ -0,0 +1,65 @@ +-- 013_notifications.sql — notification engine phase 1 +-- (DESIGN_NOTIFICATIONS.md): channels, rules, and fired notifications. +-- +-- Additive and idempotent; schema.sql carries identical structures so this +-- is a structural no-op on a fresh database (db-converge proves both paths +-- land the same). No existing table gains a constraint here, so the +-- converge pass-2 CASCADE-drop simulation has nothing external to repair. +-- +-- Design invariants encoded in the DDL: +-- * UNIQUE("ruleId","dedupeKey") on Notification is the exactly-once +-- ledger — the scanner inserts with ON CONFLICT DO NOTHING and re-runs +-- are free. +-- * NotificationChannel.config holds secrets encrypted with +-- internal/crypto (same format as IMAP passwords); the API never echoes +-- them back. +-- * The partial delivery index keeps the every-60s send scan cheap on +-- large histories. + +CREATE TABLE IF NOT EXISTS "NotificationChannel" ( + id text PRIMARY KEY, + "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('email','slack','matrix','telegram')), + name text NOT NULL, + config jsonb NOT NULL DEFAULT '{}', + enabled boolean NOT NULL DEFAULT true, + version integer NOT NULL DEFAULT 1, + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS "NotificationChannel_ownerId_idx" ON "NotificationChannel"("ownerId"); + +CREATE TABLE IF NOT EXISTS "NotificationRule" ( + id text PRIMARY KEY, + "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, + name text NOT NULL, + trigger text NOT NULL CHECK (trigger IN ('signal_created','bookmark_due')), + config jsonb NOT NULL DEFAULT '{}', + "channelId" text NOT NULL REFERENCES "NotificationChannel"(id) ON DELETE CASCADE, + "cooldownMinutes" integer NOT NULL DEFAULT 60, + enabled boolean NOT NULL DEFAULT true, + "lastFiredAt" timestamptz, + version integer NOT NULL DEFAULT 1, + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS "NotificationRule_ownerId_idx" ON "NotificationRule"("ownerId"); + +CREATE TABLE IF NOT EXISTS "Notification" ( + id text PRIMARY KEY, + "ruleId" text NOT NULL REFERENCES "NotificationRule"(id) ON DELETE CASCADE, + "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, + "dedupeKey" text NOT NULL, + title text NOT NULL, + body text NOT NULL, + status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','sent','failed','suppressed')), + attempts integer NOT NULL DEFAULT 0, + "lastError" text, + "nextAttemptAt" timestamptz NOT NULL DEFAULT now(), + "sentAt" timestamptz, + "createdAt" timestamptz NOT NULL DEFAULT now(), + UNIQUE ("ruleId", "dedupeKey") +); +CREATE INDEX IF NOT EXISTS "Notification_ownerId_createdAt_idx" ON "Notification"("ownerId", "createdAt" DESC); +CREATE INDEX IF NOT EXISTS "Notification_delivery_due_idx" ON "Notification"("status", "nextAttemptAt") + WHERE status IN ('pending','failed'); diff --git a/db/schema.sql b/db/schema.sql index a072776..438ec39 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -365,6 +365,59 @@ CREATE INDEX "Signal_ownerId_occurredAt_idx" ON "Signal"("ownerId", "occurredAt" ALTER TABLE "Signal" ADD CONSTRAINT "Signal_sourceId_fkey" FOREIGN KEY ("sourceId") REFERENCES "SignalSource"(id) ON DELETE SET NULL; +-- 2.15b Notifications (DESIGN_NOTIFICATIONS.md, phase 1): user-owned +-- channels (secrets encrypted at rest via internal/crypto, never echoed), +-- rules (one channel per rule in phase 1), and fired notifications whose +-- UNIQUE("ruleId","dedupeKey") is the entire exactly-once story — the +-- scanner re-runs freely and conflicting inserts are no-ops. +CREATE TABLE "NotificationChannel" ( + id text PRIMARY KEY, + "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('email','slack','matrix','telegram')), + name text NOT NULL, + config jsonb NOT NULL DEFAULT '{}', + enabled boolean NOT NULL DEFAULT true, + version integer NOT NULL DEFAULT 1, + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX "NotificationChannel_ownerId_idx" ON "NotificationChannel"("ownerId"); + +CREATE TABLE "NotificationRule" ( + id text PRIMARY KEY, + "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, + name text NOT NULL, + trigger text NOT NULL CHECK (trigger IN ('signal_created','bookmark_due')), + config jsonb NOT NULL DEFAULT '{}', + "channelId" text NOT NULL REFERENCES "NotificationChannel"(id) ON DELETE CASCADE, + "cooldownMinutes" integer NOT NULL DEFAULT 60, + enabled boolean NOT NULL DEFAULT true, + "lastFiredAt" timestamptz, + version integer NOT NULL DEFAULT 1, + "createdAt" timestamptz NOT NULL DEFAULT now(), + "updatedAt" timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX "NotificationRule_ownerId_idx" ON "NotificationRule"("ownerId"); + +CREATE TABLE "Notification" ( + id text PRIMARY KEY, + "ruleId" text NOT NULL REFERENCES "NotificationRule"(id) ON DELETE CASCADE, + "ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE, + "dedupeKey" text NOT NULL, + title text NOT NULL, + body text NOT NULL, + status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','sent','failed','suppressed')), + attempts integer NOT NULL DEFAULT 0, + "lastError" text, + "nextAttemptAt" timestamptz NOT NULL DEFAULT now(), + "sentAt" timestamptz, + "createdAt" timestamptz NOT NULL DEFAULT now(), + UNIQUE ("ruleId", "dedupeKey") +); +CREATE INDEX "Notification_ownerId_createdAt_idx" ON "Notification"("ownerId", "createdAt" DESC); +CREATE INDEX "Notification_delivery_due_idx" ON "Notification"("status", "nextAttemptAt") + WHERE status IN ('pending','failed'); + -- 2.16 AppSetting: server-owned singleton settings rows. 'adminBootstrap' -- records that initial provisioning completed (review AUTH-06), so the -- absence of a qualifying administrator never re-opens first-signup diff --git a/internal/handlers/notifications.go b/internal/handlers/notifications.go new file mode 100644 index 0000000..1a61f40 --- /dev/null +++ b/internal/handlers/notifications.go @@ -0,0 +1,562 @@ +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"], + } +} diff --git a/internal/http/integration_test.go b/internal/http/integration_test.go index 1cda8e1..3484d3f 100644 --- a/internal/http/integration_test.go +++ b/internal/http/integration_test.go @@ -6,6 +6,7 @@ import ( "github.com/andrew/superbrain/internal/auth" "github.com/andrew/superbrain/internal/config" "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/outbound" "io" "net/http" "net/http/cookiejar" @@ -29,9 +30,12 @@ func testServerDB(t *testing.T) (*httptest.Server, *db.DB) { t.Skip("set TEST_DATABASE_URL to run PostgreSQL integration tests") } // The limiter stores are process-global and login has no loopback - // exemption (review SEC-1); give every test a clean slate. + // exemption (review SEC-1); give every test a clean slate. Same for the + // outbound budgets (mailer/notify/preview share one process-wide store). auth.ResetRateLimits() + outbound.ResetBudget() t.Cleanup(auth.ResetRateLimits) + t.Cleanup(outbound.ResetBudget) t.Setenv("AUTH_SECRET", "integration-test-secret") t.Setenv("NEXTAUTH_SECRET", "integration-test-secret") t.Setenv("ADMIN_EMAILS", "") diff --git a/internal/http/notifications_test.go b/internal/http/notifications_test.go new file mode 100644 index 0000000..7ecae91 --- /dev/null +++ b/internal/http/notifications_test.go @@ -0,0 +1,287 @@ +package http + +import ( + "context" + "io" + "net" + "net/http" + "net/http/cookiejar" + "strings" + "sync" + "testing" + "time" + + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/notify" +) + +// fakeWebhook captures one Slack-style POST for the delivery tests. +type fakeWebhook struct { + t *testing.T + srv *http.Server + ln net.Listener + mu sync.Mutex + bodies []string +} + +func newFakeWebhook(t *testing.T) *fakeWebhook { + t.Helper() + ln, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + f := &fakeWebhook{t: t, ln: ln} + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + f.mu.Lock() + f.bodies = append(f.bodies, string(raw)) + f.mu.Unlock() + w.WriteHeader(200) + }) + f.srv = &http.Server{Handler: mux} + go f.srv.Serve(ln) + t.Cleanup(func() { f.srv.Close() }) + return f +} + +func (f *fakeWebhook) url() string { return "http://" + f.ln.Addr().String() + "/hook" } + +func (f *fakeWebhook) received() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.bodies...) +} + +// The full phase-1 surface: channel CRUD with write-only secrets, plan +// gating via the entitlement catalog, the version contract on rules, and +// engine behavior (dedupe, cooldown, delivery, backoff, suppression). +func TestNotificationsChannelsAndRules(t *testing.T) { + srv, d := testServerDB(t) + smtp := newFakeSMTP(t) + host, port, _ := net.SplitHostPort(smtp.ln.Addr().String()) + t.Setenv("SMTP_HOST", host) + t.Setenv("SMTP_PORT", port) + t.Setenv("SMTP_FROM", "superbrain@superbrain.test") + t.Setenv("NEXTAUTH_URL", "https://superbrain.test") + + jar, _ := cookiejar.New(nil) + alice := apiClient{t, &http.Client{Jar: jar}, srv.URL} + alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201) + alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200) + + // --- channel create: secrets are masked in every response --- + created := alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "email", "name": "My inbox", "config": map[string]any{"address": ""}, + }, 201) + emailChID := created["id"].(string) + version := int(created["version"].(float64)) + + hook := newFakeWebhook(t) + slack := alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "slack", "name": "team", "config": map[string]any{"webhookUrl": hook.url()}, + }, 201) + slackID := slack["id"].(string) + if cfg := slack["config"].(map[string]any); cfg["webhookUrl"] != notify.MaskValue { + t.Fatalf("secret leaked in create response: %v", cfg) + } + + // The stored secret decrypts to the original (encryption round-trip). + var storedCfg string + if e := d.QueryRow(`SELECT config::text FROM "NotificationChannel" WHERE id=$1`, slackID).Scan(&storedCfg); e != nil { + t.Fatal(e) + } + if strings.Contains(storedCfg, hook.url()) { + t.Fatal("webhook URL stored in plaintext") + } + dec, e := notify.DecryptConfig("slack", []byte(storedCfg), "integration-test-secret") + if e != nil || dec["webhookUrl"] != hook.url() { + t.Fatalf("decrypt round-trip failed: %v %v", dec, e) + } + + // --- PATCH contract: version required, stale rejected, mask keeps secret --- + alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{"name": "renamed"}, 400) + alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{"name": "renamed", "version": version + 5}, 409) + slackVersion := int(slack["version"].(float64)) + patched := alice.request("PATCH", "/api/notifications/channels/"+slackID, map[string]any{ + "name": "renamed", "version": slackVersion, + "config": map[string]any{"webhookUrl": notify.MaskValue}, + }, 200) + if patched["name"] != "renamed" { + t.Fatal("rename not applied") + } + dec2, e := notify.DecryptConfig("slack", []byte(mustConfigJSON(t, d, slackID)), "integration-test-secret") + if e != nil || dec2["webhookUrl"] != hook.url() { + t.Fatalf("masked PATCH clobbered the stored secret: %v %v", dec2, e) + } + + // Bad config shape is rejected. + alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "matrix", "name": "bad", "config": map[string]any{"homeserver": "notaurl", "roomId": "!x:y", "accessToken": "t"}, + }, 400) + + // --- plan gating via the entitlement catalog (never TIER directly) --- + // Default tenant is 'selfhosted' (everything allowed); force the free + // plan and telegram must be refused while email stays allowed. + if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil { + t.Fatal(e) + } + alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "telegram", "name": "tg", "config": map[string]any{"botToken": "123:abc", "chatId": "42"}, + }, 403) + alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "email", "name": "second inbox", + }, 201) + if _, e := d.Exec(`UPDATE "Tenant" SET plan='selfhosted' WHERE id=$1`, db.DefaultTenantID); e != nil { + t.Fatal(e) + } + + // --- rules: create, version contract, list projection --- + due := time.Now().UTC().Add(6 * time.Hour).Format(time.RFC3339) + bm := alice.request("POST", "/api/bookmarks", map[string]any{ + "url": "https://example.org/due-soon", "title": "Due soon", "dueDate": due, + }, 201) + _ = bm + rule := alice.request("POST", "/api/notifications/rules", map[string]any{ + "name": "Due reminders", "trigger": "bookmark_due", "channelId": emailChID, + "config": map[string]any{"leadHours": 24}, "cooldownMinutes": 60, + }, 201) + ruleID := rule["id"].(string) + if rule["channelKind"] != "email" { + t.Fatalf("rule projection missing channel join: %v", rule) + } + alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{"cooldownMinutes": float64(99999)}, 400) + alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{"enabled": false}, 400) + upd := alice.request("PATCH", "/api/notifications/rules/"+ruleID, map[string]any{ + "enabled": true, "version": int(rule["version"].(float64)), + }, 200) + _ = upd + + // --- engine: scan fires exactly once, delivers through mailer --- + ctx := context.Background() + if e := notify.RunOnce(ctx, d); e != nil { + t.Fatal(e) + } + msg := smtp.waitForMessage(t, 1) + if msg[0] != "alice@superbrain.test" || !strings.Contains(msg[1], "Bookmark due: Due soon") { + t.Fatalf("unexpected notification mail: %v", msg) + } + var status string + if e := d.QueryRow(`SELECT status FROM "Notification" WHERE "ruleId"=$1`, ruleID).Scan(&status); e != nil || status != "sent" { + t.Fatalf("notification status = %s (%v), want sent", status, e) + } + // Rescan: the dedupe key makes the second pass a no-op. + if e := notify.RunOnce(ctx, d); e != nil { + t.Fatal(e) + } + if n := smtp.messages(); len(n) != 1 { + t.Fatalf("dedupe failed: %d mails", len(n)) + } + // Cooldown: a NEW due bookmark does not fire while the rule cools. + alice.request("POST", "/api/bookmarks", map[string]any{ + "url": "https://example.org/due-too", "title": "Due too", + "dueDate": time.Now().UTC().Add(2 * time.Hour).Format(time.RFC3339), + }, 201) + if e := notify.RunOnce(ctx, d); e != nil { + t.Fatal(e) + } + if n := smtp.messages(); len(n) != 1 { + t.Fatalf("cooldown ignored: %d mails", len(n)) + } + if _, e := d.Exec(`UPDATE "NotificationRule" SET "lastFiredAt"=now()-interval '2 hours' WHERE id=$1`, ruleID); e != nil { + t.Fatal(e) + } + if e := notify.RunOnce(ctx, d); e != nil { + t.Fatal(e) + } + if n := smtp.messages(); len(n) != 2 { + t.Fatalf("after cooldown expiry: %d mails, want 2", len(n)) + } + + // --- webhook delivery through the netguarded client --- + slackRule := alice.request("POST", "/api/notifications/rules", map[string]any{ + "name": "Signals to slack", "trigger": "signal_created", "channelId": slackID, + }, 201) + _ = slackRule + if _, e := d.Exec(` + INSERT INTO "Signal"(id,"sourceType",title,summary,"bookmarkId","ownerId") + SELECT 'sig-1','email','Invoice arrived','from billing', b.id, u.id + FROM "Bookmark" b, "User" u WHERE b.url='https://example.org/due-soon' AND u.email='alice@superbrain.test' LIMIT 1`); e != nil { + t.Fatal(e) + } + if e := notify.RunOnce(ctx, d); e != nil { + t.Fatal(e) + } + got := hook.received() + if len(got) != 1 || !strings.Contains(got[0], "Invoice arrived") { + t.Fatalf("webhook delivery missing: %v", got) + } + + // --- failure path: attempts bump, backoff pushes the row out --- + deadLn, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + deadAddr := deadLn.Addr().String() + deadLn.Close() + dead := alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "slack", "name": "dead", "config": map[string]any{"webhookUrl": "http://" + deadAddr + "/hook"}, + }, 201) + deadRule := alice.request("POST", "/api/notifications/rules", map[string]any{ + "name": "dead hook", "trigger": "signal_created", "channelId": dead["id"].(string), + }, 201) + if _, e := d.Exec(`INSERT INTO "Signal"(id,"sourceType",title,"bookmarkId","ownerId") + SELECT 'sig-2','email','Second', b.id, u.id FROM "Bookmark" b, "User" u + WHERE b.url='https://example.org/due-soon' AND u.email='alice@superbrain.test' LIMIT 1`); e != nil { + t.Fatal(e) + } + if e := notify.RunOnce(ctx, d); e != nil { + t.Fatal(e) + } + var attempts int + var nextAt time.Time + var lastErr *string + if e := d.QueryRow(`SELECT attempts, "nextAttemptAt", "lastError" FROM "Notification" WHERE "ruleId"=$1`, deadRule["id"].(string)). + Scan(&attempts, &nextAt, &lastErr); e != nil { + t.Fatal(e) + } + if attempts != 1 || lastErr == nil || !nextAt.After(time.Now()) { + t.Fatalf("failure not recorded: attempts=%d nextAt=%v err=%v", attempts, nextAt, lastErr) + } + + // --- suppression: a downgraded plan stops delivery (no send attempted) --- + if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil { + t.Fatal(e) + } + if _, e := d.Exec(`UPDATE "Notification" SET status='pending', attempts=0, "nextAttemptAt"=now() WHERE "ruleId"=$1`, deadRule["id"].(string)); e != nil { + t.Fatal(e) + } + if e := notify.RunOnce(ctx, d); e != nil { + t.Fatal(e) + } + var suppressed string + if e := d.QueryRow(`SELECT status FROM "Notification" WHERE "ruleId"=$1`, deadRule["id"].(string)).Scan(&suppressed); e != nil || suppressed != "suppressed" { + t.Fatalf("downgraded plan must suppress delivery, got %q (%v)", suppressed, e) + } + + // --- history endpoint (array response: fetch raw with the session jar) --- + req, _ := http.NewRequest("GET", srv.URL+"/api/notifications", nil) + res, e := (&http.Client{Jar: jar}).Do(req) + if e != nil { + t.Fatal(e) + } + defer res.Body.Close() + rawBody, _ := io.ReadAll(res.Body) + if res.StatusCode != 200 || !strings.Contains(string(rawBody), `"status":"sent"`) { + t.Fatalf("history missing delivered rows: %d %s", res.StatusCode, rawBody) + } +} + +func mustConfigJSON(t *testing.T, d *db.DB, channelID string) string { + t.Helper() + var raw string + if e := d.QueryRow(`SELECT config::text FROM "NotificationChannel" WHERE id=$1`, channelID).Scan(&raw); e != nil { + t.Fatal(e) + } + return raw +} diff --git a/internal/http/server.go b/internal/http/server.go index ea035a5..5184ce8 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -115,6 +115,18 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server { mux.HandleFunc("PATCH /api/signal-sources/{id}", authed(handlers.HandleSignalSourcesUpdate)) mux.HandleFunc("DELETE /api/signal-sources/{id}", authed(handlers.HandleSignalSourcesDelete)) + // 4.7b Notifications (DESIGN_NOTIFICATIONS.md): channels, rules, history. + mux.HandleFunc("GET /api/notifications/channels", authed(handlers.HandleNotificationChannelsList)) + mux.HandleFunc("POST /api/notifications/channels", authed(handlers.HandleNotificationChannelsCreate)) + mux.HandleFunc("PATCH /api/notifications/channels/{id}", authed(handlers.HandleNotificationChannelsUpdate)) + mux.HandleFunc("DELETE /api/notifications/channels/{id}", authed(handlers.HandleNotificationChannelsDelete)) + mux.HandleFunc("POST /api/notifications/channels/{id}/test", authed(handlers.HandleNotificationChannelsTest)) + mux.HandleFunc("GET /api/notifications/rules", authed(handlers.HandleNotificationRulesList)) + mux.HandleFunc("POST /api/notifications/rules", authed(handlers.HandleNotificationRulesCreate)) + mux.HandleFunc("PATCH /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesUpdate)) + mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete)) + mux.HandleFunc("GET /api/notifications", authed(handlers.HandleNotificationsList)) + // 4.8 Alerts, contacts, email, dates, users mux.HandleFunc("GET /api/alerts/check", authed(handlers.HandleAlertsCheck)) mux.HandleFunc("DELETE /api/alerts/{bookmarkId}", authed(handlers.HandleAlertsDismiss)) diff --git a/internal/mailer/mailer.go b/internal/mailer/mailer.go index 8adedb5..4ecf7bd 100644 --- a/internal/mailer/mailer.go +++ b/internal/mailer/mailer.go @@ -81,10 +81,12 @@ func Send(ctx context.Context, to, subject, body string) error { if to == "" { return errors.New("mailer: missing recipient") } - // Global send budget: password resets are rare and an unreachable or - // blackholed relay must not pile up goroutines (same shape as the IMAP - // and CardDAV callers). - release, _, ok := outbound.Reserve("smtp", 5, time.Minute) + // Global send budget: transactional mail is rare per user but a hosted + // (multi-tenant) instance can legitimately send bursts — password resets + // and notification deliveries share this one key. The bound exists so an + // unreachable or blackholed relay cannot pile up goroutines (same shape + // as the IMAP and CardDAV callers), not to ration legitimate mail. + release, _, ok := outbound.Reserve("smtp", 20, time.Minute) if !ok { return errors.New("mailer: send budget exhausted") } diff --git a/internal/notify/channels.go b/internal/notify/channels.go new file mode 100644 index 0000000..0985875 --- /dev/null +++ b/internal/notify/channels.go @@ -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]))) +} diff --git a/internal/notify/engine.go b/internal/notify/engine.go new file mode 100644 index 0000000..5b6f75c --- /dev/null +++ b/internal/notify/engine.go @@ -0,0 +1,369 @@ +// Package notify is the notification engine (DESIGN_NOTIFICATIONS.md, +// phase 1): it scans for facts matching enabled rules (new signals, due +// bookmarks), records deduped Notification rows, and delivers them through +// the rule's channel. +// +// Design invariants: +// - Scanner, not hooks: producers are never instrumented; re-runs are +// free because UNIQUE("ruleId","dedupeKey") + ON CONFLICT DO NOTHING is +// the entire exactly-once story. +// - Anti-spam: per-rule cooldown, per-owner pending cap, per-row attempt +// cap with exponential backoff. +// - Plan gates: channels are validated against the owner's tenant plan at +// creation AND re-checked at delivery, so a downgraded plan stops +// sending (rows become 'suppressed', visible in history). +// - Every send is a server-initiated dial: email via internal/mailer, +// webhooks via the netguarded client in channels.go, all inside +// outbound.Reserve budgets. +package notify + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "log" + "math/rand/v2" + "strings" + "time" + + "github.com/andrew/superbrain/internal/config" + "github.com/andrew/superbrain/internal/db" + "github.com/andrew/superbrain/internal/entitlements" + "github.com/andrew/superbrain/internal/outbound" +) + +const ( + tick = 60 * time.Second + maxAttempts = 5 + maxBackoffMins = 240 + ownerPendCap = 200 // per-owner pending+failed rows before new fires are suppressed + scanBatchLimit = 50 // facts considered per rule per tick + deliverBatch = 10 // rows claimed per delivery pass (one transaction) + sendTimeout = 20 * time.Second + staleDueHours = 14 * 24 // bookmarks due longer ago than this never fire +) + +// RunLoop drives the engine until ctx is done. Mirrors signals.RunLoop: +// jittered ticks, failures logged not fatal, no work after cancellation. +func RunLoop(ctx context.Context, d *db.DB) { + // Small startup jitter so restarts don't align scans with the signals loop. + time.Sleep(time.Duration(rand.IntN(5000)) * time.Millisecond) + t := time.NewTicker(tick + time.Duration(rand.IntN(15000))*time.Millisecond) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + if err := RunOnce(ctx, d); err != nil { + log.Printf("notify: tick failed: %v", err) + } + } + } +} + +// RunOnce performs one scan+deliver pass. Exported for tests. +func RunOnce(ctx context.Context, d *db.DB) error { + if err := Scan(ctx, d); err != nil { + return fmt.Errorf("scan: %w", err) + } + return Deliver(ctx, d) +} + +// Scan inserts deduped Notification rows for every enabled rule whose +// cooldown has elapsed and whose channel the owner's plan still allows. +func Scan(ctx context.Context, d *db.DB) error { + rows, err := d.QueryContext(ctx, ` + SELECT r.id, r."ownerId", r.trigger, r.config, r."cooldownMinutes", r."lastFiredAt", + c.kind, u."tenantId" + FROM "NotificationRule" r + JOIN "NotificationChannel" c ON c.id = r."channelId" + JOIN "User" u ON u.id = r."ownerId" + WHERE r.enabled AND c.enabled`) + if err != nil { + return err + } + defer rows.Close() + type rule struct { + id, ownerID, trigger, kind string + config []byte + cooldown int + lastFired sql.NullTime + tenantID sql.NullString + } + var rules []rule + for rows.Next() { + var r rule + if err := rows.Scan(&r.id, &r.ownerID, &r.trigger, &r.config, &r.cooldown, &r.lastFired, &r.kind, &r.tenantID); err != nil { + return err + } + rules = append(rules, r) + } + if err := rows.Err(); err != nil { + return err + } + + limitsCache := map[string]entitlements.Limits{} + tenants := db.NewTenantRepo(d) + pendCache := map[string]int{} + + for _, r := range rules { + // Cooldown: skip the whole rule while it is still cooling. + if r.lastFired.Valid && time.Since(r.lastFired.Time) < time.Duration(r.cooldown)*time.Minute { + continue + } + // Plan gate at fire time (creation already checked; plans can change). + tid := r.tenantID.String + lim, ok := limitsCache[tid] + if !ok { + lim, err = tenants.Limits(ctx, tid) + if err != nil { + log.Printf("notify: limits for tenant %s: %v", tid, err) + continue + } + limitsCache[tid] = lim + } + if !lim.AllowChannel(r.kind) { + continue + } + // Per-owner pending cap: stop firing new notifications for owners + // with a stuck backlog instead of growing it without bound. + pend, ok := pendCache[r.ownerID] + if !ok { + if err := d.QueryRowContext(ctx, + `SELECT count(*) FROM "Notification" WHERE "ownerId"=$1 AND status IN ('pending','failed')`, + r.ownerID).Scan(&pend); err != nil { + return err + } + pendCache[r.ownerID] = pend + } + if pend >= ownerPendCap { + log.Printf("notify: owner %s at the pending cap (%d); rule %s skipped", r.ownerID, pend, r.id) + continue + } + + var inserted int + switch r.trigger { + case "signal_created": + inserted, err = scanSignals(ctx, d, r.id) + case "bookmark_due": + inserted, err = scanDue(ctx, d, r.id, r.config) + default: + log.Printf("notify: rule %s has unknown trigger %q", r.id, r.trigger) + continue + } + if err != nil { + log.Printf("notify: scan rule %s: %v", r.id, err) + continue + } + if inserted > 0 { + pendCache[r.ownerID] = pend + inserted + if _, err := d.ExecContext(ctx, + `UPDATE "NotificationRule" SET "lastFiredAt"=now(),"updatedAt"=now() WHERE id=$1`, r.id); err != nil { + log.Printf("notify: lastFiredAt update for %s: %v", r.id, err) + } + } + } + return nil +} + +// scanSignals fires for signals created since the rule itself was created — +// a new rule must not retro-notify the owner's whole history. Ids are +// deterministic per (rule, signal) so the conflict target is the only +// exactly-once mechanism needed. +func scanSignals(ctx context.Context, d *db.DB, ruleID string) (int, error) { + res, err := d.ExecContext(ctx, ` + INSERT INTO "Notification"(id,"ruleId","ownerId","dedupeKey",title,body) + SELECT r.id||'-'||s.id, r.id, r."ownerId", 'signal:'||s.id, + left(s.title, 200), left(COALESCE(s.summary,''), 2000) + FROM "NotificationRule" r + JOIN LATERAL ( + SELECT s.id, s.title, s.summary FROM "Signal" s + WHERE s."ownerId" = r."ownerId" AND s."createdAt" >= r."createdAt" + ORDER BY s."occurredAt" DESC LIMIT $2 + ) s ON true + WHERE r.id = $1 + ON CONFLICT ("ruleId","dedupeKey") DO NOTHING`, ruleID, scanBatchLimit) + if err != nil { + return 0, err + } + n, _ := res.RowsAffected() + return int(n), nil +} + +// scanDue fires for bookmarks due within the rule's lead window (default +// 24h) or overdue by less than staleDueHours. The dedupe key carries the +// due DATE (UTC), so moving a dueDate re-notifies and a same-day rescan +// does not. +func scanDue(ctx context.Context, d *db.DB, ruleID string, ruleConfig []byte) (int, error) { + leadHours := 24 + var cfg struct { + LeadHours *int `json:"leadHours"` + } + if len(ruleConfig) > 0 { + _ = json.Unmarshal(ruleConfig, &cfg) // tolerate junk: defaults apply + } + if cfg.LeadHours != nil && *cfg.LeadHours >= 0 && *cfg.LeadHours <= 24*30 { + leadHours = *cfg.LeadHours + } + res, err := d.ExecContext(ctx, ` + INSERT INTO "Notification"(id,"ruleId","ownerId","dedupeKey",title,body) + SELECT r.id||'-due-'||b.id||'-'||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD'), + r.id, r."ownerId", + 'due:'||b.id||':'||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD'), + left('Bookmark due: '||COALESCE(NULLIF(b.title,''), b.url), 200), + CASE WHEN b."dueDate" <= now() + THEN 'Overdue since '||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI')||' UTC.' + ELSE 'Due '||to_char(b."dueDate" AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI')||' UTC.' END + FROM "NotificationRule" r + JOIN "Bookmark" b ON b."ownerId" = r."ownerId" + WHERE r.id = $1 + AND b."dueDate" IS NOT NULL + AND b."dueDate" <= now() + make_interval(hours => $2) + AND b."dueDate" > now() - make_interval(hours => $3) + ON CONFLICT ("ruleId","dedupeKey") DO NOTHING`, + ruleID, leadHours, staleDueHours) + if err != nil { + return 0, err + } + n, _ := res.RowsAffected() + return int(n), nil +} + +// Deliver claims due rows and pushes each through its channel. The whole +// pass runs in ONE transaction with FOR UPDATE SKIP LOCKED so multiple app +// instances never double-send; the batch is small (deliverBatch) and each +// send bounded (sendTimeout) to keep the transaction short. A crash +// mid-pass rolls the claim back and the next tick retries. +func Deliver(ctx context.Context, d *db.DB) error { + return db.Transaction(ctx, d, func(tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, ` + SELECT n.id, n.title, n.body, n.attempts, + c.id, c."ownerId", c.kind, c.config, c.enabled, u."tenantId" + FROM "Notification" n + JOIN "NotificationRule" r ON r.id = n."ruleId" + JOIN "NotificationChannel" c ON c.id = r."channelId" + JOIN "User" u ON u.id = c."ownerId" + WHERE n.status IN ('pending','failed') AND n."nextAttemptAt" <= now() AND n.attempts < $1 + ORDER BY n."nextAttemptAt" + LIMIT $2 + FOR UPDATE OF n SKIP LOCKED`, maxAttempts, deliverBatch) + if err != nil { + return err + } + type item struct { + id, title, body, channelID, ownerID, kind string + attempts int + config []byte + channelEnabled bool + tenantID sql.NullString + } + var items []item + for rows.Next() { + var it item + if err := rows.Scan(&it.id, &it.title, &it.body, &it.attempts, + &it.channelID, &it.ownerID, &it.kind, &it.config, &it.channelEnabled, &it.tenantID); err != nil { + rows.Close() + return err + } + items = append(items, it) + } + rows.Close() + if err := rows.Err(); err != nil { + return err + } + + limitsCache := map[string]entitlements.Limits{} + tenants := db.NewTenantRepo(d) + secret := config.Load().EncryptionSecret() + + for _, it := range items { + status, lastErr := "sent", "" + // A disabled channel or a plan that no longer allows it suppresses + // the row permanently (history shows why nothing was sent). + tid := it.tenantID.String + lim, ok := limitsCache[tid] + if !ok { + lim, err = tenants.Limits(ctx, tid) + if err != nil { + log.Printf("notify: limits for tenant %s: %v", tid, err) + continue // stay pending; retry next tick + } + limitsCache[tid] = lim + } + if !it.channelEnabled || !lim.AllowChannel(it.kind) { + status = "suppressed" + } else { + cfg, err := DecryptConfig(it.kind, it.config, secret) + if err != nil { + status, lastErr = "failed", err.Error() + } else { + release, _, ok := outbound.Reserve("notify:"+it.kind, 10, time.Minute) + if !ok { + continue // budget exhausted: stays pending, next tick retries + } + sendCtx, cancel := context.WithTimeout(ctx, sendTimeout) + err = Send(sendCtx, d, Channel{ + ID: it.channelID, OwnerID: it.ownerID, Kind: it.kind, Config: cfg, Enabled: true, + }, it.title, it.body) + cancel() + release() + if err != nil { + status, lastErr = "failed", err.Error() + } + } + } + if err := recordDelivery(ctx, tx, it.id, status, it.attempts+1, lastErr); err != nil { + return err + } + if status == "failed" { + // Destination-level detail stays in the row; the log gets a + // classification only (never payloads or credentials). + log.Printf("notify: delivery %s failed: %s", it.id, classify(lastErr)) + } + } + return nil + }) +} + +// recordDelivery applies the outcome: sent/suppressed rows close out; +// failures bump attempts and push nextAttemptAt out exponentially +// (10m, 20m, 40m, 80m, capped). Rows at maxAttempts stay 'failed' — the +// due query's attempts filter excludes them. +func recordDelivery(ctx context.Context, tx *sql.Tx, id, status string, attempts int, lastErr string) error { + if len(lastErr) > 500 { + lastErr = lastErr[:500] + } + backoffMins := 10 * (1 << min(max(attempts-1, 0), 4)) + if backoffMins > maxBackoffMins { + backoffMins = maxBackoffMins + } + _, err := tx.ExecContext(ctx, ` + UPDATE "Notification" + SET status=$2, attempts=$3, "lastError"=NULLIF($4,''), + "nextAttemptAt"=CASE WHEN $2 IN ('sent','suppressed') THEN "nextAttemptAt" ELSE now()+make_interval(mins => $5) END, + "sentAt"=CASE WHEN $2='sent' THEN now() ELSE "sentAt" END + WHERE id=$1`, + id, status, attempts, lastErr, backoffMins) + return err +} + +// classify reduces an error to a log-safe category. +func classify(err string) string { + l := strings.ToLower(err) + switch { + case strings.Contains(l, "webhook answered"): + return err // already destination-safe (status + bounded snippet) + case strings.Contains(l, "netguard"): + return "blocked destination" + case strings.Contains(l, "no such host"), strings.Contains(l, "server misbehaving"): + return "dns failure" + case strings.Contains(l, "timeout"), strings.Contains(l, "deadline"): + return "timeout" + case strings.Contains(l, "mailer"), strings.Contains(l, "smtp"): + return "smtp failure" + default: + return "send failure" + } +} diff --git a/internal/outbound/outbound.go b/internal/outbound/outbound.go index dfc7789..80f45cf 100644 --- a/internal/outbound/outbound.go +++ b/internal/outbound/outbound.go @@ -73,3 +73,14 @@ func Reserve(key string, limit int, windowDur time.Duration) (release func(), re shared.mu.Unlock() }, 0, true } + +// ResetBudget clears all fixed-window counters. Tests only: the budget is +// process-global, and integration harnesses reset it per test server so +// sequential tests do not inherit each other's windows (same contract as +// auth.ResetRateLimits). In-flight accounting is left untouched — callers +// must have released their slots, which tests guarantee by completion. +func ResetBudget() { + shared.mu.Lock() + shared.keys = map[string]*window{} + shared.mu.Unlock() +} diff --git a/main.go b/main.go index 6b0a38f..a96e471 100644 --- a/main.go +++ b/main.go @@ -6,12 +6,14 @@ import ( "github.com/andrew/superbrain/internal/config" "github.com/andrew/superbrain/internal/db" "github.com/andrew/superbrain/internal/http" + "github.com/andrew/superbrain/internal/notify" "github.com/andrew/superbrain/internal/scripts" "github.com/andrew/superbrain/internal/signals" "log" stdhttp "net/http" "os" "os/signal" + "sync" "syscall" "time" ) @@ -65,7 +67,14 @@ func main() { workersDone := make(chan struct{}) go func() { defer close(workersDone) - signals.RunLoop(ctx, d) + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); signals.RunLoop(ctx, d) }() + // Notification engine (DESIGN_NOTIFICATIONS.md): scans rules and + // delivers through channels; shares the shutdown contract with + // signals — drain HTTP first, then both loops, then close the db. + go func() { defer wg.Done(); notify.RunLoop(ctx, d) }() + wg.Wait() }() srv := http.NewServer(cfg, d) go func() { diff --git a/web/app/(app)/settings/client.tsx b/web/app/(app)/settings/client.tsx index e1ae8c9..5049a3e 100644 --- a/web/app/(app)/settings/client.tsx +++ b/web/app/(app)/settings/client.tsx @@ -5,9 +5,10 @@ import { useSession } from 'next-auth/react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs' -import { User, Mail, Server, Cloud, Shield, Check, X, AlertTriangle } from 'lucide-react' +import { User, Mail, Server, Cloud, Shield, Bell, Check, X, AlertTriangle } from 'lucide-react' import { toast } from 'sonner' import { invalidateReference } from '@/lib/reference-data' +import { NotificationsSettings } from '@/components/notifications-settings' import type { OidcStatus } from '@/lib/oidc-config' export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) { @@ -95,6 +96,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba Profile IMAP Nextcloud + Notifications OIDC @@ -172,6 +174,10 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba + + + +

OIDC Configuration

diff --git a/web/components/notifications-settings.tsx b/web/components/notifications-settings.tsx new file mode 100644 index 0000000..101b508 --- /dev/null +++ b/web/components/notifications-settings.tsx @@ -0,0 +1,322 @@ +'use client' + +// Notifications settings (DESIGN_NOTIFICATIONS.md phase 1): channels with +// write-only secrets, rules with the house version contract (every mutating +// PATCH sends the expected version; a 409 reloads instead of clobbering), +// and a recent-delivery strip. Plan gating surfaces as the server's 403 +// "Not available on your plan" toast — the UI never guesses entitlements. + +import { useCallback, useEffect, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Switch } from '@/components/ui/switch' +import { Badge } from '@/components/ui/badge' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { Bell, Mail, Slack, MessageSquare, Send, Trash2, Loader2 } from 'lucide-react' +import { toast } from 'sonner' + +type Channel = { + id: string; kind: string; name: string; enabled: boolean; version: number + config: Record; createdAt: string +} +type Rule = { + id: string; name: string; trigger: string; config: { leadHours?: number } + channelId: string; channelKind: string; channelName: string + cooldownMinutes: number; enabled: boolean; lastFiredAt: string | null; version: number +} +type NotificationRow = { + id: string; title: string; status: string; attempts: number + ruleName: string; channelKind: string; sentAt: string | null; createdAt: string +} + +const MASK = '••••••••' + +const KIND_META: Record = { + email: { label: 'Email', icon: Mail, fields: [{ key: 'address', label: 'Address (blank = account email)', placeholder: 'you@example.com' }] }, + slack: { label: 'Slack', icon: Slack, fields: [{ key: 'webhookUrl', label: 'Incoming webhook URL', secret: true, placeholder: 'https://hooks.slack.com/services/…' }] }, + matrix: { + label: 'Matrix', icon: MessageSquare, fields: [ + { key: 'homeserver', label: 'Homeserver URL', placeholder: 'https://matrix.example.org' }, + { key: 'roomId', label: 'Room ID', placeholder: '!room:example.org' }, + { key: 'accessToken', label: 'Access token', secret: true }, + ], + }, + telegram: { + label: 'Telegram', icon: Send, fields: [ + { key: 'botToken', label: 'Bot token', secret: true }, + { key: 'chatId', label: 'Chat ID' }, + ], + }, +} + +const TRIGGER_LABELS: Record = { + signal_created: 'New signal matches a mailbox watcher', + bookmark_due: 'A bookmark is due soon or overdue', +} + +async function api(path: string, init?: RequestInit): Promise { + return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) +} + +export function NotificationsSettings() { + const [channels, setChannels] = useState([]) + const [rules, setRules] = useState([]) + const [history, setHistory] = useState([]) + const [loading, setLoading] = useState(true) + + // Channel form + const [chKind, setChKind] = useState('email') + const [chName, setChName] = useState('') + const [chConfig, setChConfig] = useState>({}) + const [savingCh, setSavingCh] = useState(false) + // Rule form + const [rName, setRName] = useState('') + const [rTrigger, setRTrigger] = useState('bookmark_due') + const [rChannel, setRChannel] = useState('') + const [rLead, setRLead] = useState(24) + const [savingR, setSavingR] = useState(false) + const [testingId, setTestingId] = useState(null) + + // Promise-chain shape (house pattern, see admin/client.tsx): setState + // lives only inside async callbacks — the SSR lint refuses effects that + // can reach a synchronous setState. + const reload = useCallback(() => + Promise.all([ + api('/api/notifications/channels').then(r => r.json()), + api('/api/notifications/rules').then(r => r.json()), + api('/api/notifications').then(r => r.json()), + ]) + .then(([ch, ru, hi]) => { + if (Array.isArray(ch)) setChannels(ch) + if (Array.isArray(ru)) setRules(ru) + if (Array.isArray(hi)) setHistory(hi.slice(0, 10)) + }) + .catch(() => { toast.error('Could not load notification settings') }) + .finally(() => { setLoading(false) }), []) + + useEffect(() => { reload() }, [reload]) + + const reportError = async (res: Response, fallback: string) => { + let msg = fallback + try { + const data = await res.json() + if (data?.error) msg = data.error + } catch { /* body was not JSON */ } + toast.error(msg) + } + + const addChannel = async () => { + if (!chName.trim()) { toast.error('Give the channel a name'); return } + setSavingCh(true) + try { + const res = await api('/api/notifications/channels', { + method: 'POST', + body: JSON.stringify({ kind: chKind, name: chName.trim(), config: chConfig }), + }) + if (res.ok) { + toast.success('Channel added') + setChName(''); setChConfig({}) + await reload() + } else await reportError(res, 'Could not add the channel') + } finally { setSavingCh(false) } + } + + const toggleChannel = async (c: Channel, enabled: boolean) => { + const res = await api(`/api/notifications/channels/${c.id}`, { + method: 'PATCH', body: JSON.stringify({ enabled, version: c.version }), + }) + if (res.ok) await reload() + else await reportError(res, 'Could not update the channel') + } + + const removeChannel = async (c: Channel) => { + const res = await api(`/api/notifications/channels/${c.id}`, { method: 'DELETE' }) + if (res.ok) { toast.success('Channel removed'); await reload() } + else await reportError(res, 'Could not remove the channel') + } + + const testChannel = async (c: Channel) => { + setTestingId(c.id) + try { + const res = await api(`/api/notifications/channels/${c.id}/test`, { method: 'POST' }) + if (res.ok) toast.success('Test message sent') + else await reportError(res, 'Test delivery failed') + } finally { setTestingId(null) } + } + + const addRule = async () => { + if (!rName.trim()) { toast.error('Give the rule a name'); return } + if (!rChannel) { toast.error('Pick a channel'); return } + setSavingR(true) + try { + const res = await api('/api/notifications/rules', { + method: 'POST', + body: JSON.stringify({ + name: rName.trim(), trigger: rTrigger, channelId: rChannel, + config: rTrigger === 'bookmark_due' ? { leadHours: rLead } : {}, + }), + }) + if (res.ok) { + toast.success('Rule created') + setRName('') + await reload() + } else await reportError(res, 'Could not create the rule') + } finally { setSavingR(false) } + } + + const toggleRule = async (rule: Rule, enabled: boolean) => { + const res = await api(`/api/notifications/rules/${rule.id}`, { + method: 'PATCH', body: JSON.stringify({ enabled, version: rule.version }), + }) + if (res.ok) await reload() + else await reportError(res, 'Could not update the rule') + } + + const removeRule = async (rule: Rule) => { + const res = await api(`/api/notifications/rules/${rule.id}`, { method: 'DELETE' }) + if (res.ok) { toast.success('Rule removed'); await reload() } + else await reportError(res, 'Could not remove the rule') + } + + const kindIcon = (kind: string) => { + const Icon = KIND_META[kind]?.icon ?? Bell + return + } + + if (loading) { + return
Loading notifications…
+ } + + return ( +
+ {/* Channels */} +
+

Channels

+

+ Where notifications are delivered. Secrets are stored encrypted and never shown again after saving. + Which channel kinds are available depends on your plan. +

+ + {channels.length === 0 && ( +

No channels yet — add one below.

+ )} + {channels.map(c => ( +
+ {kindIcon(c.kind)} +
+

{c.name}

+

+ {KIND_META[c.kind]?.label ?? c.kind} + {c.config?.address ? ` · ${c.config.address}` : ''} + {c.config?.homeserver ? ` · ${c.config.homeserver}` : ''} +

+
+ + toggleChannel(c, v)} aria-label="Enable channel" /> + +
+ ))} + +
+
+ + ) => setChName(e.target.value)} /> +
+ {KIND_META[chKind]?.fields.map(f => ( + ) => setChConfig(p => ({ ...p, [f.key]: e.target.value }))} /> + ))} + +
+
+ + {/* Rules */} +
+

Rules

+

+ When something happens in your brain, notify a channel. Each rule fires at most once per + fact and respects its cooldown. +

+ + {rules.length === 0 &&

No rules yet.

} + {rules.map(rule => ( +
+
+

{rule.name}

+

+ {TRIGGER_LABELS[rule.trigger] ?? rule.trigger} + {rule.trigger === 'bookmark_due' && rule.config?.leadHours != null ? ` (within ${rule.config.leadHours}h)` : ''} + {' → '} + {kindIcon(rule.channelKind)}{rule.channelName} +

+
+ toggleRule(rule, v)} aria-label="Enable rule" /> + +
+ ))} + +
+ ) => setRName(e.target.value)} /> +
+ + +
+ {rTrigger === 'bookmark_due' && ( + + )} + +
+
+ + {/* Recent deliveries */} +
+

Recent notifications

+ {history.length === 0 &&

Nothing sent yet.

} + {history.map(n => ( +
+ + {n.status} + + {n.title} + {n.ruleName} +
+ ))} +
+
+ ) +}