@@ -0,0 +1,271 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +// Package notifications wires the S29 notification web surface: |
| 4 | +// |
| 5 | +// - GET /notifications inbox |
| 6 | +// - POST /notifications/{id}/read mark one read |
| 7 | +// - POST /notifications/{id}/unread mark one unread |
| 8 | +// - POST /notifications/mark-all-read clear unread for the viewer |
| 9 | +// - POST /threads/{kind}/{id}/subscribe subscribe (or override-ignore) |
| 10 | +// - POST /threads/{kind}/{id}/unsubscribe unsubscribe (per-thread) |
| 11 | +// - GET /notifications/unsubscribe one-click HMAC-signed unsub |
| 12 | +package notifications |
| 13 | + |
| 14 | +import ( |
| 15 | + "errors" |
| 16 | + "log/slog" |
| 17 | + "net/http" |
| 18 | + "strconv" |
| 19 | + |
| 20 | + "github.com/go-chi/chi/v5" |
| 21 | + "github.com/jackc/pgx/v5/pgxpool" |
| 22 | + |
| 23 | + "github.com/tenseleyFlow/shithub/internal/notif" |
| 24 | + notifdb "github.com/tenseleyFlow/shithub/internal/notif/sqlc" |
| 25 | + "github.com/tenseleyFlow/shithub/internal/web/middleware" |
| 26 | + "github.com/tenseleyFlow/shithub/internal/web/render" |
| 27 | +) |
| 28 | + |
| 29 | +// Deps wires the handler set. |
| 30 | +type Deps struct { |
| 31 | + Logger *slog.Logger |
| 32 | + Render *render.Renderer |
| 33 | + Pool *pgxpool.Pool |
| 34 | + UnsubscribeKey []byte |
| 35 | +} |
| 36 | + |
| 37 | +// Handlers groups the notification surface handlers. Construct via New. |
| 38 | +type Handlers struct { |
| 39 | + d Deps |
| 40 | +} |
| 41 | + |
| 42 | +// pageSize bounds inbox pagination. Same default as the search inbox. |
| 43 | +const pageSize = 25 |
| 44 | + |
| 45 | +// New constructs the handler set. |
| 46 | +func New(d Deps) (*Handlers, error) { |
| 47 | + if d.Render == nil { |
| 48 | + return nil, errors.New("notifications: nil Render") |
| 49 | + } |
| 50 | + if d.Pool == nil { |
| 51 | + return nil, errors.New("notifications: nil Pool") |
| 52 | + } |
| 53 | + return &Handlers{d: d}, nil |
| 54 | +} |
| 55 | + |
| 56 | +// MountAuthed registers the routes that REQUIRE a logged-in viewer. |
| 57 | +// Mounted from server.go inside a RequireUser-wrapped group. |
| 58 | +func (h *Handlers) MountAuthed(r chi.Router) { |
| 59 | + r.Get("/notifications", h.list) |
| 60 | + r.Post("/notifications/{id}/read", h.markRead) |
| 61 | + r.Post("/notifications/{id}/unread", h.markUnread) |
| 62 | + r.Post("/notifications/mark-all-read", h.markAllRead) |
| 63 | + r.Post("/threads/{kind}/{id}/subscribe", h.subscribe) |
| 64 | + r.Post("/threads/{kind}/{id}/unsubscribe", h.unsubscribe) |
| 65 | +} |
| 66 | + |
| 67 | +// MountPublic registers the unauthenticated one-click unsubscribe |
| 68 | +// endpoint. The HMAC-signed URL embeds the recipient ID + thread |
| 69 | +// reference + signature so we can verify without a session cookie |
| 70 | +// (RFC 8058 mailers pop links from arbitrary clients). |
| 71 | +func (h *Handlers) MountPublic(r chi.Router) { |
| 72 | + r.Get("/notifications/unsubscribe", h.unsubscribeViaToken) |
| 73 | +} |
| 74 | + |
| 75 | +// ─── handlers ────────────────────────────────────────────────────── |
| 76 | + |
| 77 | +func (h *Handlers) list(w http.ResponseWriter, r *http.Request) { |
| 78 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 79 | + if viewer.IsAnonymous() { |
| 80 | + http.Redirect(w, r, "/login?next=/notifications", http.StatusSeeOther) |
| 81 | + return |
| 82 | + } |
| 83 | + page := pageFromRequest(r) |
| 84 | + onlyUnread := r.URL.Query().Get("filter") == "unread" |
| 85 | + |
| 86 | + q := notifdb.New() |
| 87 | + rows, err := q.ListNotificationsForRecipient(r.Context(), h.d.Pool, notifdb.ListNotificationsForRecipientParams{ |
| 88 | + RecipientUserID: viewer.ID, |
| 89 | + Column2: onlyUnread, |
| 90 | + Limit: int32(pageSize), |
| 91 | + Offset: int32((page - 1) * pageSize), |
| 92 | + }) |
| 93 | + if err != nil { |
| 94 | + h.d.Logger.ErrorContext(r.Context(), "notifications: list", "error", err) |
| 95 | + h.d.Render.HTTPError(w, r, http.StatusInternalServerError, "") |
| 96 | + return |
| 97 | + } |
| 98 | + unreadCount, _ := q.CountUnreadForRecipient(r.Context(), h.d.Pool, viewer.ID) |
| 99 | + |
| 100 | + data := map[string]any{ |
| 101 | + "Title": "Notifications", |
| 102 | + "Notifications": rows, |
| 103 | + "UnreadCount": unreadCount, |
| 104 | + "Filter": r.URL.Query().Get("filter"), |
| 105 | + "Page": page, |
| 106 | + "HasPrev": page > 1, |
| 107 | + "HasNext": len(rows) == pageSize, |
| 108 | + } |
| 109 | + if err := h.d.Render.RenderPage(w, r, "notifications/inbox", data); err != nil { |
| 110 | + h.d.Logger.ErrorContext(r.Context(), "notifications: render", "error", err) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +func (h *Handlers) markRead(w http.ResponseWriter, r *http.Request) { |
| 115 | + h.setRead(w, r, true) |
| 116 | +} |
| 117 | + |
| 118 | +func (h *Handlers) markUnread(w http.ResponseWriter, r *http.Request) { |
| 119 | + h.setRead(w, r, false) |
| 120 | +} |
| 121 | + |
| 122 | +// setRead toggles the unread flag on a single inbox row. The DB path |
| 123 | +// owns the recipient_user_id check (the SET … WHERE … filters by both |
| 124 | +// id and recipient), so a forged id from another user becomes a |
| 125 | +// silent no-op rather than an authoritative 403 — matches the |
| 126 | +// existence-leak posture used elsewhere. |
| 127 | +func (h *Handlers) setRead(w http.ResponseWriter, r *http.Request, read bool) { |
| 128 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 129 | + if viewer.IsAnonymous() { |
| 130 | + h.d.Render.HTTPError(w, r, http.StatusUnauthorized, "") |
| 131 | + return |
| 132 | + } |
| 133 | + id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) |
| 134 | + if err != nil { |
| 135 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 136 | + return |
| 137 | + } |
| 138 | + q := notifdb.New() |
| 139 | + if read { |
| 140 | + err = q.SetNotificationRead(r.Context(), h.d.Pool, notifdb.SetNotificationReadParams{ |
| 141 | + ID: id, RecipientUserID: viewer.ID, |
| 142 | + }) |
| 143 | + } else { |
| 144 | + err = q.SetNotificationUnread(r.Context(), h.d.Pool, notifdb.SetNotificationUnreadParams{ |
| 145 | + ID: id, RecipientUserID: viewer.ID, |
| 146 | + }) |
| 147 | + } |
| 148 | + if err != nil { |
| 149 | + h.d.Logger.WarnContext(r.Context(), "notifications: set read", |
| 150 | + "id", id, "read", read, "error", err) |
| 151 | + } |
| 152 | + http.Redirect(w, r, "/notifications", http.StatusSeeOther) |
| 153 | +} |
| 154 | + |
| 155 | +func (h *Handlers) markAllRead(w http.ResponseWriter, r *http.Request) { |
| 156 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 157 | + if viewer.IsAnonymous() { |
| 158 | + h.d.Render.HTTPError(w, r, http.StatusUnauthorized, "") |
| 159 | + return |
| 160 | + } |
| 161 | + if err := notifdb.New().MarkAllReadForRecipient(r.Context(), h.d.Pool, viewer.ID); err != nil { |
| 162 | + h.d.Logger.WarnContext(r.Context(), "notifications: mark-all-read", "error", err) |
| 163 | + } |
| 164 | + http.Redirect(w, r, "/notifications", http.StatusSeeOther) |
| 165 | +} |
| 166 | + |
| 167 | +func (h *Handlers) subscribe(w http.ResponseWriter, r *http.Request) { |
| 168 | + h.threadAction(w, r, true) |
| 169 | +} |
| 170 | + |
| 171 | +func (h *Handlers) unsubscribe(w http.ResponseWriter, r *http.Request) { |
| 172 | + h.threadAction(w, r, false) |
| 173 | +} |
| 174 | + |
| 175 | +// threadAction toggles per-thread subscription. `subscribe=true` |
| 176 | +// inserts (or updates) a row with subscribed=true; `false` flips it |
| 177 | +// off. The fan-out worker honors the explicit row over the auto-sub |
| 178 | +// derivation. |
| 179 | +func (h *Handlers) threadAction(w http.ResponseWriter, r *http.Request, subscribed bool) { |
| 180 | + viewer := middleware.CurrentUserFromContext(r.Context()) |
| 181 | + if viewer.IsAnonymous() { |
| 182 | + h.d.Render.HTTPError(w, r, http.StatusUnauthorized, "") |
| 183 | + return |
| 184 | + } |
| 185 | + kindStr := chi.URLParam(r, "kind") |
| 186 | + if kindStr != "issue" && kindStr != "pr" { |
| 187 | + h.d.Render.HTTPError(w, r, http.StatusNotFound, "") |
| 188 | + return |
| 189 | + } |
| 190 | + id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) |
| 191 | + if err != nil { |
| 192 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 193 | + return |
| 194 | + } |
| 195 | + reason := "manual" |
| 196 | + if !subscribed { |
| 197 | + reason = "manual_unsubscribe" |
| 198 | + } |
| 199 | + if err := notifdb.New().UpsertNotificationThread(r.Context(), h.d.Pool, notifdb.UpsertNotificationThreadParams{ |
| 200 | + RecipientUserID: viewer.ID, |
| 201 | + ThreadKind: notifdb.NotificationThreadKind(kindStr), |
| 202 | + ThreadID: id, |
| 203 | + Subscribed: subscribed, |
| 204 | + Reason: reason, |
| 205 | + }); err != nil { |
| 206 | + h.d.Logger.WarnContext(r.Context(), "notifications: thread action", |
| 207 | + "kind", kindStr, "id", id, "subscribed", subscribed, "error", err) |
| 208 | + } |
| 209 | + // Bounce back to the thread the viewer was on. Best-effort: when |
| 210 | + // the Referer is missing, fall back to /notifications. |
| 211 | + dest := r.Header.Get("Referer") |
| 212 | + if dest == "" { |
| 213 | + dest = "/notifications" |
| 214 | + } |
| 215 | + http.Redirect(w, r, dest, http.StatusSeeOther) |
| 216 | +} |
| 217 | + |
| 218 | +// unsubscribeViaToken handles the email's one-click List-Unsubscribe |
| 219 | +// link. The URL embeds (recipient, thread_kind, thread_id, sig) so |
| 220 | +// no session is required. We re-derive the HMAC and compare in |
| 221 | +// constant time; a mismatch returns 400. |
| 222 | +func (h *Handlers) unsubscribeViaToken(w http.ResponseWriter, r *http.Request) { |
| 223 | + q := r.URL.Query() |
| 224 | + uStr, tk, tiStr, sig := q.Get("u"), q.Get("tk"), q.Get("ti"), q.Get("sig") |
| 225 | + uid, err := strconv.ParseInt(uStr, 10, 64) |
| 226 | + if err != nil { |
| 227 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 228 | + return |
| 229 | + } |
| 230 | + tid, err := strconv.ParseInt(tiStr, 10, 64) |
| 231 | + if err != nil { |
| 232 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 233 | + return |
| 234 | + } |
| 235 | + if !notif.VerifyUnsubscribe(h.d.UnsubscribeKey, uid, tk, tid, sig) { |
| 236 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 237 | + return |
| 238 | + } |
| 239 | + if tk != "issue" && tk != "pr" { |
| 240 | + h.d.Render.HTTPError(w, r, http.StatusBadRequest, "") |
| 241 | + return |
| 242 | + } |
| 243 | + if err := notifdb.New().UpsertNotificationThread(r.Context(), h.d.Pool, notifdb.UpsertNotificationThreadParams{ |
| 244 | + RecipientUserID: uid, |
| 245 | + ThreadKind: notifdb.NotificationThreadKind(tk), |
| 246 | + ThreadID: tid, |
| 247 | + Subscribed: false, |
| 248 | + Reason: "email_one_click", |
| 249 | + }); err != nil { |
| 250 | + h.d.Logger.WarnContext(r.Context(), "notifications: token unsubscribe", |
| 251 | + "recipient", uid, "kind", tk, "id", tid, "error", err) |
| 252 | + } |
| 253 | + if err := h.d.Render.RenderPage(w, r, "notifications/unsubscribed", map[string]any{ |
| 254 | + "Title": "Unsubscribed", |
| 255 | + }); err != nil { |
| 256 | + h.d.Logger.ErrorContext(r.Context(), "notifications: render unsub", "error", err) |
| 257 | + } |
| 258 | +} |
| 259 | + |
| 260 | +// pageFromRequest pulls ?page=N, defaulting to 1 on missing/invalid. |
| 261 | +func pageFromRequest(r *http.Request) int { |
| 262 | + p := r.URL.Query().Get("page") |
| 263 | + if p == "" { |
| 264 | + return 1 |
| 265 | + } |
| 266 | + n, err := strconv.Atoi(p) |
| 267 | + if err != nil || n < 1 || n > 10000 { |
| 268 | + return 1 |
| 269 | + } |
| 270 | + return n |
| 271 | +} |