Files
Docwell/Server/internal/directory/notify.go
T
tajniak81andClaude Opus 5.5 631b929433 Add OAuth and OIDC sign-in, two-step codes, audit log, API tokens and webhooks
Sign-in:
- Google, GitHub, Microsoft and any OpenID Connect provider, set up in the
  admin panel (secrets are write-only). PocketBase talks to the provider,
  and docwell-server keeps the state and PKCE verifier. Accounts a
  provider creates follow the sign-up switch and the domain list; refused
  ones are removed again.
- Two-step sign-in with an authenticator app (TOTP), set up under "Your
  account", with ten single-use recovery codes. After any first factor
  (password, email code, provider) the session is held behind a
  five-minute challenge: five tries, each code works once. Turning it off
  needs a code. Managers can reset it for someone who lost their phone.
  Both the web app and the admin panel ask for the code.

Integrations:
- Personal API tokens ("dw_…") that act as their owner, read-only or
  read-write, with optional expiry. Only a hash is stored, and the token is
  shown once. Tokens cannot manage tokens or two-step sign-in. Admins see
  and can revoke their organization's tokens.
- Workspace webhooks for page, comment and space events. Deliveries are
  HMAC-SHA256 signed and retried (10 s, 1 min, 5 min), with a 30-day log
  and a test button. Loopback and link-local addresses are refused
  (DOCWELL_WEBHOOKS_ALLOW_LOCAL is for development).

Audit log: sign-ins (including failures and second steps, filed under the
account's organization) and every successful change request, by route and
path ids, never bodies. Superadmins see everything and org admins their
organization. It is searchable and exportable as CSV in the admin panel's
new Security page, and kept for DOCWELL_AUDIT_RETENTION_DAYS (365).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:31:45 +01:00

599 lines
18 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/url"
"sort"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/mail"
"docwell/server/internal/store/pocketbase"
)
// ---- Watching pages and notifications --------------------------------------
//
// People watch a page explicitly, or automatically when they create it or
// comment on it (unless they muted it). Watchers hear about new comments;
// thread participants about replies and resolutions; people about being
// mentioned or having a page shared with them. Nobody is notified about
// their own actions, or about a page they cannot open. Unread notifications
// go out as an email digest unless the person turned that off.
// Notification types stored in notifications.type.
const (
NotifyComment = "comment"
NotifyReply = "reply"
NotifyMention = "mention"
NotifyShare = "share"
NotifyResolved = "resolved"
)
// notifyRank decides which type wins when one event reaches someone for
// several reasons (a mentioned watcher gets one "mention").
var notifyRank = map[string]int{NotifyComment: 1, NotifyResolved: 2, NotifyReply: 3, NotifyShare: 4, NotifyMention: 5}
type watchRecord struct {
ID string `json:"id"`
Page string `json:"page"`
User string `json:"user"`
Watching bool `json:"watching"`
}
func (s *Service) watchRow(ctx context.Context, pageID, userID string) (watchRecord, error) {
res, err := pocketbase.List[watchRecord](ctx, s.pb, "page_watchers", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("page = '%s' && user = '%s'", pageID, userID),
})
if err != nil || len(res.Items) == 0 {
return watchRecord{}, err
}
return res.Items[0], nil
}
// WatchState is whether the caller watches a page.
type WatchState struct {
Watching bool `json:"watching"`
}
// GetWatch reports whether the caller watches a page (viewer).
func (s *Service) GetWatch(ctx context.Context, c access.Caller, pageID string) (WatchState, error) {
p, _, err := s.pageFor(ctx, c, pageID)
if err != nil {
return WatchState{}, err
}
row, err := s.watchRow(ctx, p.ID, c.ID)
return WatchState{Watching: row.Watching}, err
}
// SetWatch starts or stops watching a page (viewer). Stopping is remembered,
// so commenting later does not start it again.
func (s *Service) SetWatch(ctx context.Context, c access.Caller, pageID string, on bool) (WatchState, error) {
p, _, err := s.pageFor(ctx, c, pageID)
if err != nil {
return WatchState{}, err
}
row, err := s.watchRow(ctx, p.ID, c.ID)
if err != nil {
return WatchState{}, err
}
switch {
case row.ID == "":
_, err = pocketbase.Create[watchRecord](ctx, s.pb, "page_watchers", map[string]any{"page": p.ID, "user": c.ID, "watching": on})
case row.Watching != on:
_, err = pocketbase.Update[watchRecord](ctx, s.pb, "page_watchers", row.ID, map[string]any{"watching": on})
}
if err != nil {
return WatchState{}, mapPB(err, "page not found")
}
return WatchState{Watching: on}, nil
}
// autoWatch starts watching for someone who took part in a page, unless they
// already decided either way (best effort).
func (s *Service) autoWatch(ctx context.Context, pageID, userID string) {
row, err := s.watchRow(ctx, pageID, userID)
if err != nil || row.ID != "" {
return
}
_, _ = pocketbase.Create[watchRecord](ctx, s.pb, "page_watchers", map[string]any{"page": pageID, "user": userID, "watching": true})
}
func (s *Service) watchers(ctx context.Context, pageID string) []string {
rows, err := listAll[watchRecord](ctx, s, "page_watchers", pocketbase.ListOptions{
Filter: fmt.Sprintf("page = '%s' && watching = true", pageID), Fields: "user",
})
if err != nil {
return nil
}
out := make([]string, len(rows))
for i, r := range rows {
out[i] = r.User
}
return out
}
// event is one thing that happened on a page, to tell people about.
type event struct {
actor string
page pageRecord
comment string
excerpt string
// to maps recipients to the notification type each gets.
to map[string]string
}
func (e *event) add(userID, kind string) {
if userID == "" || userID == e.actor {
return
}
if notifyRank[kind] > notifyRank[e.to[userID]] {
e.to[userID] = kind
}
}
func excerpt(s string) string {
s = strings.Join(strings.Fields(s), " ")
if r := []rune(s); len(r) > 200 {
return string(r[:199]) + "…"
}
return s
}
// send stores the event's notifications, for recipients who can still open
// the page (best effort: a failure only loses notifications).
func (s *Service) send(ctx context.Context, e event) {
for userID, kind := range e.to {
if !validID(userID) {
continue
}
u, err := s.getUser(ctx, userID)
if err != nil || u.Status == "disabled" {
continue
}
if _, _, _, err := s.pageAccess(ctx, u.Caller(), e.page.ID); err != nil {
continue
}
body := map[string]any{
"user": userID, "workspace": e.page.Workspace, "page": e.page.ID, "type": kind, "excerpt": excerpt(e.excerpt),
}
if e.actor != "" {
body["actor"] = e.actor
}
if e.comment != "" {
body["comment"] = e.comment
}
if _, err := pocketbase.Create[struct{}](ctx, s.pb, "notifications", body); err != nil {
slog.Default().Warn("notify: create", "user", userID, "err", err)
}
}
}
// notifyComment tells watchers about a new thread or reply, the thread's
// people about a reply, and mentioned people that they were mentioned.
func (s *Service) notifyComment(ctx context.Context, c access.Caller, p pageRecord, rec, root commentRecord, mentions []string) {
e := event{actor: c.ID, page: p, comment: rec.ID, excerpt: rec.Body, to: map[string]string{}}
for _, w := range s.watchers(ctx, p.ID) {
e.add(w, NotifyComment)
}
if root.ID != "" {
for _, uid := range s.threadPeople(ctx, root) {
e.add(uid, NotifyReply)
}
}
for i, uid := range mentions {
if i >= 50 {
break
}
e.add(uid, NotifyMention)
}
s.send(ctx, e)
}
// threadPeople are the authors in a thread.
func (s *Service) threadPeople(ctx context.Context, root commentRecord) []string {
out := []string{root.Author}
replies, err := listAll[commentRecord](ctx, s, "comments", pocketbase.ListOptions{
Filter: fmt.Sprintf("parent = '%s'", root.ID), Fields: "author",
})
if err == nil {
for _, r := range replies {
out = append(out, r.Author)
}
}
return out
}
func (s *Service) notifyResolved(ctx context.Context, c access.Caller, p pageRecord, root commentRecord) {
e := event{actor: c.ID, page: p, comment: root.ID, excerpt: root.Body, to: map[string]string{}}
for _, uid := range s.threadPeople(ctx, root) {
e.add(uid, NotifyResolved)
}
s.send(ctx, e)
}
func (s *Service) notifyShare(ctx context.Context, c access.Caller, p pageRecord, userID string) {
e := event{actor: c.ID, page: p, excerpt: p.Title, to: map[string]string{}}
e.add(userID, NotifyShare)
s.send(ctx, e)
}
// mentionIDs collects the user ids of mention nodes in a Tiptap document.
func mentionIDs(doc json.RawMessage) []string {
var root any
if json.Unmarshal(doc, &root) != nil {
return nil
}
seen := map[string]bool{}
var out []string
var walk func(n any)
walk = func(n any) {
m, ok := n.(map[string]any)
if !ok {
return
}
if m["type"] == "mention" {
if attrs, ok := m["attrs"].(map[string]any); ok {
if id, ok := attrs["id"].(string); ok && validID(id) && !seen[id] {
seen[id] = true
out = append(out, id)
}
}
}
if kids, ok := m["content"].([]any); ok {
for _, k := range kids {
walk(k)
}
}
}
walk(root)
sort.Strings(out)
return out
}
// PageSaved is called after a page's content was saved by editor (the last
// person who edited, possibly ""). It records which pages the page links to
// (for backlinks) and notifies people mentioned for the first time. A page
// that predates mention tracking (mentions still null) only records who it
// mentions, so upgrading does not notify about old mentions.
func (s *Service) PageSaved(ctx context.Context, pageID, editor string, doc json.RawMessage) {
type rec struct {
pageRecord
Mentions json.RawMessage `json:"mentions"`
Links json.RawMessage `json:"links"`
}
r, err := pocketbase.Get[rec](ctx, s.pb, "pages", pageID)
if err != nil {
return
}
if r.DeletedAt == "" {
s.emitPage(ctx, "page.updated", r.pageRecord, editor, map[string]any{"change": "content"})
}
patch := map[string]any{}
if links := linkIDs(doc, pageID); !sameIDs(r.Links, links) {
patch["links"] = links
}
now := mentionIDs(doc)
if now == nil {
now = []string{}
}
known := len(r.Mentions) > 0 && string(r.Mentions) != "null"
var before []string
if known {
_ = json.Unmarshal(r.Mentions, &before)
}
if !known || !sameIDs(r.Mentions, now) {
patch["mentions"] = now
}
if len(patch) == 0 {
return
}
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "pages", pageID, patch); err != nil {
return
}
if _, changed := patch["mentions"]; !changed || !known || r.DeletedAt != "" {
return
}
had := map[string]bool{}
for _, id := range before {
had[id] = true
}
e := event{actor: editor, page: r.pageRecord, excerpt: r.Title, to: map[string]string{}}
for _, id := range now {
if !had[id] {
e.add(id, NotifyMention)
}
}
s.send(ctx, e)
}
// sameIDs reports whether a stored id list (JSON) holds exactly ids.
func sameIDs(stored json.RawMessage, ids []string) bool {
if len(stored) == 0 || string(stored) == "null" {
return false
}
var have []string
if json.Unmarshal(stored, &have) != nil {
return false
}
return strings.Join(have, ",") == strings.Join(ids, ",")
}
// ---- Reading notifications -------------------------------------------------
type Notification struct {
ID string `json:"id"`
Type string `json:"type"`
Workspace string `json:"workspace"`
// Page is nil when the page is gone or the caller lost access to it.
Page *PageRef `json:"page"`
Comment string `json:"comment"`
Actor *MemberUser `json:"actor"`
Excerpt string `json:"excerpt"`
Created string `json:"created"`
Read bool `json:"read"`
}
type NotificationList struct {
Items []Notification `json:"items"`
Unread int `json:"unread"`
}
type notificationRecord struct {
ID string `json:"id"`
User string `json:"user"`
Workspace string `json:"workspace"`
Page string `json:"page"`
Comment string `json:"comment"`
Actor string `json:"actor"`
Type string `json:"type"`
Excerpt string `json:"excerpt"`
ReadAt string `json:"read_at"`
EmailedAt string `json:"emailed_at"`
Created string `json:"created"`
}
func (s *Service) unreadCount(ctx context.Context, userID string) (int, error) {
return s.count(ctx, "notifications", fmt.Sprintf("user = '%s' && read_at = ''", userID))
}
// ListNotifications lists the caller's newest notifications (all, or only
// unread ones) with the unread count.
func (s *Service) ListNotifications(ctx context.Context, c access.Caller, unreadOnly bool, limit int) (NotificationList, error) {
if limit <= 0 || limit > 100 {
limit = 50
}
filter := fmt.Sprintf("user = '%s'", c.ID)
if unreadOnly {
filter += " && read_at = ''"
}
res, err := pocketbase.List[notificationRecord](ctx, s.pb, "notifications", pocketbase.ListOptions{
PerPage: limit, Filter: filter, Sort: "-created,-id",
})
if err != nil {
return NotificationList{}, err
}
out := NotificationList{Items: []Notification{}}
who := s.people()
pages := map[string]*PageRef{}
for _, r := range res.Items {
n := Notification{
ID: r.ID, Type: r.Type, Workspace: r.Workspace, Comment: r.Comment, Actor: who.get(ctx, r.Actor),
Excerpt: r.Excerpt, Created: r.Created, Read: r.ReadAt != "",
}
if r.Page != "" {
ref, seen := pages[r.Page]
if !seen {
if p, _, err := s.pageFor(ctx, c, r.Page); err == nil && p.DeletedAt == "" {
ref = &PageRef{ID: p.ID, Title: p.Title, Icon: p.Icon}
}
pages[r.Page] = ref
}
if ref == nil {
// What happened on a page the caller can no longer open stays hidden.
n.Excerpt, n.Comment = "", ""
}
n.Page = ref
}
out.Items = append(out.Items, n)
}
if out.Unread, err = s.unreadCount(ctx, c.ID); err != nil {
return NotificationList{}, err
}
return out, nil
}
// MarkNotificationsRead marks the caller's notifications read: the listed
// ones, or all of them. It returns the unread count afterwards.
func (s *Service) MarkNotificationsRead(ctx context.Context, c access.Caller, ids []string, all bool) (int, error) {
now := pbTime(time.Now())
if all {
rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{
Filter: fmt.Sprintf("user = '%s' && read_at = ''", c.ID), Fields: "id",
})
if err != nil {
return 0, err
}
for _, r := range rows {
ids = append(ids, r.ID)
}
}
if len(ids) > 1000 {
return 0, apperr.Invalid("too many notifications at once")
}
for _, id := range ids {
if !validID(id) {
continue
}
rec, err := pocketbase.Get[notificationRecord](ctx, s.pb, "notifications", id)
if err != nil || rec.User != c.ID || rec.ReadAt != "" {
continue // someone else's or already read: nothing to do
}
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "notifications", id, map[string]any{"read_at": now}); err != nil {
return 0, mapPB(err, "notification not found")
}
}
return s.unreadCount(ctx, c.ID)
}
// NotificationSettings are the caller's notification preferences.
type NotificationSettings struct {
// Email is "digest" (unread notifications by email every few minutes) or "off".
Email string `json:"email"`
}
func (s *Service) GetNotificationSettings(ctx context.Context, c access.Caller) (NotificationSettings, error) {
r, err := pocketbase.Get[struct {
NotifyEmail string `json:"notify_email"`
}](ctx, s.pb, "users", c.ID)
if err != nil {
return NotificationSettings{}, mapPB(err, "user not found")
}
if r.NotifyEmail != "off" {
r.NotifyEmail = "digest"
}
return NotificationSettings{Email: r.NotifyEmail}, nil
}
func (s *Service) SetNotificationSettings(ctx context.Context, c access.Caller, in NotificationSettings) (NotificationSettings, error) {
if in.Email != "digest" && in.Email != "off" {
return NotificationSettings{}, apperr.InvalidFields(map[string]string{"email": "Choose digest or off."})
}
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "users", c.ID, map[string]any{"notify_email": in.Email}); err != nil {
return NotificationSettings{}, mapPB(err, "user not found")
}
return in, nil
}
// ---- Email digest ----------------------------------------------------------
// digestDelay leaves time to read a notification in the app before it is mailed.
const digestDelay = 10 * time.Minute
// digestItem is one line of a digest email.
type digestItem struct {
Text string
Link string
}
func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *people) (digestItem, bool) {
if n.Page == "" {
return digestItem{}, false
}
p, err := s.getPage(ctx, n.Page)
if err != nil || p.DeletedAt != "" {
return digestItem{}, false
}
actor := who.get(ctx, n.Actor).display()
if actor == "" {
actor = "Someone"
}
title := p.Title
if title == "" {
title = "Untitled"
}
verb := map[string]string{
NotifyComment: "commented on",
NotifyReply: "replied in",
NotifyMention: "mentioned you in",
NotifyShare: "shared",
NotifyResolved: "resolved a thread in",
}[n.Type]
text := fmt.Sprintf("%s %s “%s”", actor, verb, title)
if n.Excerpt != "" && n.Type != NotifyShare && n.Excerpt != p.Title {
text += ": " + n.Excerpt
}
link := strings.TrimRight(s.mailer.WebURL, "/") + "/p/" + url.PathEscape(p.ID)
if n.Comment != "" {
link += "?comment=" + url.QueryEscape(n.Comment)
}
return digestItem{Text: text, Link: link}, true
}
// SendDigests emails each person their unread notifications that were not
// mailed yet and are older than digestDelay, then marks them mailed. People
// who turned email off are marked without a mail. It is a background job.
func (s *Service) SendDigests(ctx context.Context) error {
if s.mailer.Sender == nil {
return nil
}
cutoff := pbTime(time.Now().Add(-digestDelay))
rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{
Filter: fmt.Sprintf("emailed_at = '' && read_at = '' && created <= '%s'", cutoff), Sort: "created",
})
if err != nil {
return err
}
byUser := map[string][]notificationRecord{}
for _, r := range rows {
byUser[r.User] = append(byUser[r.User], r)
}
appName := "Docwell"
if s.mailer.AppName != nil {
appName = s.mailer.AppName(ctx)
}
who := s.people()
var firstErr error
for userID, list := range byUser {
u, err := pocketbase.Get[struct {
Email string `json:"email"`
Name string `json:"name"`
Status string `json:"status"`
NotifyEmail string `json:"notify_email"`
}](ctx, s.pb, "users", userID)
if err == nil && u.NotifyEmail != "off" && u.Status != "disabled" {
var items []digestItem
for _, n := range list {
if it, ok := s.digestLine(ctx, n, who); ok {
items = append(items, it)
}
}
if len(items) > 0 {
m, err := mail.Render(u.Email, "digest", map[string]any{
"AppName": appName, "Name": u.Name, "Count": len(items), "Items": items,
"SettingsLink": strings.TrimRight(s.mailer.WebURL, "/") + "/notifications",
})
if err == nil {
err = s.mailer.Sender.Send(ctx, m)
}
if err != nil {
// Leave them unmailed; the next run tries again.
if firstErr == nil {
firstErr = err
}
continue
}
}
}
now := pbTime(time.Now())
for _, n := range list {
_, _ = pocketbase.Update[struct{}](ctx, s.pb, "notifications", n.ID, map[string]any{"emailed_at": now})
}
}
return firstErr
}
// PruneNotifications deletes read notifications older than 90 days. It is a
// background job.
func (s *Service) PruneNotifications(ctx context.Context) error {
cutoff := pbTime(time.Now().Add(-90 * 24 * time.Hour))
rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{
Filter: fmt.Sprintf("read_at != '' && created < '%s'", cutoff), Fields: "id",
})
if err != nil {
return err
}
for _, r := range rows {
if err := s.pb.Delete(ctx, "notifications", r.ID); err != nil && !pocketbase.IsNotFound(err) {
return err
}
}
return nil
}