// SPDX-License-Identifier: AGPL-3.0-or-later // Package push sends notifications to people's phones through UnifiedPush: // the Docwell app registers the endpoint its distributor (ntfy, NextPush, …) // gave it, and the server POSTs a small JSON message there. No Google or // Apple account is involved, which suits self-hosting. package push import ( "bytes" "context" "encoding/json" "fmt" "io" "log/slog" "net" "net/http" "net/url" "regexp" "strings" "time" "docwell/server/internal/apperr" "docwell/server/internal/store/pocketbase" "docwell/server/internal/webhooks" ) // maxDevices caps the phones one person registers. const maxDevices = 10 // Message is what a phone receives. UnifiedPush caps messages at 4 KB. type Message struct { Title string `json:"title"` Body string `json:"body"` // Route is the app route to open, e.g. "/p/?comment=". Route string `json:"route"` } // Device is one registered phone. type Device struct { ID string `json:"id"` Name string `json:"name"` Created string `json:"created"` } type deviceRecord struct { ID string `json:"id"` User string `json:"user"` Endpoint string `json:"endpoint"` P256dh string `json:"p256dh"` Auth string `json:"auth"` Name string `json:"name"` Created string `json:"created"` } func (r deviceRecord) view() Device { return Device{ID: r.ID, Name: r.Name, Created: r.Created} } type job struct { user string msg Message } type Options struct { // AllowLocal lets endpoints be on loopback and link-local addresses // (development). Private networks are always allowed: a self-hosted // distributor usually lives there. AllowLocal bool } type Service struct { pb *pocketbase.Client log *slog.Logger client *http.Client queue chan job } func New(pb *pocketbase.Client, log *slog.Logger, opts Options) *Service { dialer := &net.Dialer{Timeout: 10 * time.Second, Control: webhooks.Guard(opts.AllowLocal)} return &Service{ pb: pb, log: log, queue: make(chan job, 1000), client: &http.Client{ Timeout: 10 * time.Second, Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: nil}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, }, } } // Run delivers queued messages until ctx ends. func (s *Service) Run(ctx context.Context) { for { select { case <-ctx.Done(): return case j := <-s.queue: s.deliver(ctx, j) } } } // Notify queues a message for every phone of user. It never blocks: when the // queue is full the message is dropped (the notification is still in the inbox). func (s *Service) Notify(user string, m Message) { select { case s.queue <- job{user: user, msg: m}: default: s.log.Warn("push: queue full, message dropped", "user", user) } } func (s *Service) devices(ctx context.Context, user string) ([]deviceRecord, error) { res, err := pocketbase.List[deviceRecord](ctx, s.pb, "push_devices", pocketbase.ListOptions{ PerPage: maxDevices * 2, Filter: fmt.Sprintf("user = '%s'", user), Sort: "-created", }) return res.Items, err } func (s *Service) deliver(ctx context.Context, j job) { devices, err := s.devices(ctx, j.user) if err != nil { s.log.Warn("push: list devices", "user", j.user, "err", err) return } plain, _ := json.Marshal(j.msg) for _, d := range devices { body, err := encrypt(plain, d.P256dh, d.Auth) if err != nil { s.log.Warn("push: encrypt", "device", d.ID, "err", err) continue } code, err := s.post(ctx, d.Endpoint, body) switch { case err != nil: s.log.Warn("push: send", "device", d.ID, "err", err) case code == http.StatusNotFound || code == http.StatusGone: // The app was uninstalled or the distributor dropped the endpoint. _ = s.pb.Delete(ctx, "push_devices", d.ID) case code >= 300: s.log.Warn("push: endpoint refused", "device", d.ID, "status", code) } } } func (s *Service) post(ctx context.Context, endpoint string, body []byte) (int, error) { ctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) if err != nil { return 0, err } req.Header.Set("Content-Type", "application/octet-stream") req.Header.Set("Content-Encoding", "aes128gcm") // RFC 8030 urgency and lifetime, which ntfy and other distributors honour. req.Header.Set("Urgency", "normal") req.Header.Set("TTL", "86400") res, err := s.client.Do(req) if err != nil { return 0, err } _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 64<<10)) _ = res.Body.Close() return res.StatusCode, nil } // cleanEndpoint validates a distributor's endpoint. func cleanEndpoint(raw string) (string, error) { raw = strings.TrimSpace(raw) u, err := url.Parse(raw) if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || len(raw) > 1000 || u.User != nil { return "", apperr.InvalidFields(map[string]string{"endpoint": "Endpoint must be an http(s) address."}) } return u.String(), nil } // Register saves a phone's endpoint and Web Push keys for user. // Registering an endpoint again (the app does on every start) updates it // instead of adding a copy. func (s *Service) Register(ctx context.Context, user, endpoint, p256dh, auth, name string) (Device, error) { endpoint, err := cleanEndpoint(endpoint) if err != nil { return Device{}, err } if err := checkKeys(p256dh, auth); err != nil { return Device{}, apperr.InvalidFields(map[string]string{"p256dh": "Send the endpoint's Web Push keys (" + err.Error() + ")."}) } name = strings.TrimSpace(name) if r := []rune(name); len(r) > 100 { name = string(r[:100]) } keys := map[string]any{"user": user, "name": name, "p256dh": p256dh, "auth": auth} res, err := pocketbase.List[deviceRecord](ctx, s.pb, "push_devices", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("endpoint = '%s'", strings.ReplaceAll(endpoint, "'", "")), }) if err != nil { return Device{}, err } if len(res.Items) > 0 { // Endpoints are secret to the phone; one moving to another account // means the same phone signed in as someone else. rec, err := pocketbase.Update[deviceRecord](ctx, s.pb, "push_devices", res.Items[0].ID, keys) return rec.view(), err } existing, err := s.devices(ctx, user) if err != nil { return Device{}, err } if len(existing) >= maxDevices { // The oldest phone makes room; people replace phones more than they add them. _ = s.pb.Delete(ctx, "push_devices", existing[len(existing)-1].ID) } keys["endpoint"] = endpoint rec, err := pocketbase.Create[deviceRecord](ctx, s.pb, "push_devices", keys) return rec.view(), err } // List returns user's phones, newest first. func (s *Service) List(ctx context.Context, user string) ([]Device, error) { recs, err := s.devices(ctx, user) out := make([]Device, 0, len(recs)) for _, r := range recs { out = append(out, r.view()) } return out, err } var deviceID = regexp.MustCompile(`^[A-Za-z0-9]{1,32}$`) // Remove forgets one of user's phones (signing out on it). func (s *Service) Remove(ctx context.Context, user, id string) error { if !deviceID.MatchString(id) { return apperr.NotFound("device not found") } rec, err := pocketbase.Get[deviceRecord](ctx, s.pb, "push_devices", id) if err != nil || rec.User != user { return apperr.NotFound("device not found") } return s.pb.Delete(ctx, "push_devices", id) }