Files
silo-server/internal/notifications/webpush_sender.go
T
cf0db385f3 Add Apple push notifications support (#255)
* Add push notifications support

* fix(notifications): address push notification review findings

- Gate the capability endpoint's apple_push availability on the admin
  delivery toggle, matching web push: Available now means setup will
  actually deliver.
- Reject direct admin writes to push_relay_deployment_id/api_key; the
  relay issues them as a pair during registration and a lone write
  desyncs them (and poisons the next rotation request).
- Purge a device's registrations under other profiles when it
  re-registers, so a profile switch on a shared device stops the old
  profile's pushes (attempts cascade); adds a DB-backed test.
- Extract the shared channelDispatcher core + retry sweep and rebuild
  the webhook/web push/Apple push dispatchers on it instead of keeping
  three copies of the worker-pool/retry loop.
- Deduplicate relay URL validation (admin setting + register flow) and
  the push outbox attempt-building loops behind shared helpers.
- Cap free-text decline reasons in notification display bodies.
- Fix TestHandleApplePushDisplayDB expectations to match the shared
  display copy (test previously failed under SILO_TEST_DATABASE_URL).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(notifications): route push relay URL writes through registration only

Direct writes to notifications.push_relay_url via the admin settings
endpoint bypassed the relay registration flow, letting the stored URL
drift out of sync with the deployment id / API key pair the relay
minted for it. Reject the URL alongside the deployment id and API key
in the settings handler; POST /admin/notifications/push/relay/register
remains the only path that persists all three together.

The admin UI's Relay URL field now edits local draft state and is
applied by the Register/Rotate action instead of the settings save.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-01 17:25:16 -04:00

264 lines
8.6 KiB
Go

package notifications
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"time"
webpush "github.com/SherClockHolmes/webpush-go"
)
// webPushRetrySchedule is deliberately shorter than the webhook schedule:
// vendor push services queue undeliverable messages themselves (the TTL
// covers offline devices), so server-side retries only need to ride out
// transient push-service errors.
var webPushRetrySchedule = []time.Duration{
0,
30 * time.Second,
2 * time.Minute,
10 * time.Minute,
30 * time.Minute,
}
const (
webPushMaxAttempts = 5
webPushTTLSeconds = 12 * 60 * 60 // push-service queue TTL for offline devices
)
func webPushRetryDelay(completedAttempt int) (time.Duration, bool) {
if completedAttempt < 1 || completedAttempt >= webPushMaxAttempts {
return 0, false
}
return webPushRetrySchedule[completedAttempt] - webPushRetrySchedule[completedAttempt-1], true
}
// webPushPayload is the JSON the service worker receives. It is encrypted
// end-to-end (RFC 8291): only the subscribed browser can read it, never the
// vendor push service, so full display content is safe to include.
type webPushPayload struct {
Title string `json:"title"`
Body string `json:"body,omitempty"`
URL string `json:"url"`
Icon string `json:"icon,omitempty"`
Tag string `json:"tag,omitempty"`
DeliveryID string `json:"delivery_id"`
}
// buildWebPushPayload renders a delivery for the service worker.
func buildWebPushPayload(row DeliveryRow, posterURL string) ([]byte, error) {
display := BuildNotificationDisplay(row)
payload := webPushPayload{
Title: display.Title,
Body: display.Body,
URL: display.URL,
Tag: row.ID,
DeliveryID: row.ID,
}
switch row.Type {
case DeliveryTypeEpisodeAvailable:
payload.Icon = posterURL
case DeliveryTypeRequestFulfilled:
payload.Icon = posterURL
}
return json.Marshal(payload)
}
// webPushSender delivers claimed web push attempts. Shared by the
// post-commit dispatcher and the retry worker.
type webPushSender struct {
subscriptions *WebPushRepository
deliveries *DeliveryRepository
service *WebPushService
settings *Settings
client *http.Client
payload func(ctx context.Context, row DeliveryRow) DeliveryRowPayload
logger *slog.Logger
}
func newWebPushSender(
subscriptions *WebPushRepository,
deliveries *DeliveryRepository,
service *WebPushService,
settings *Settings,
) *webPushSender {
return &webPushSender{
subscriptions: subscriptions,
deliveries: deliveries,
service: service,
settings: settings,
// Subscription endpoints are client-supplied URLs the server POSTs
// to: the SSRF-guarded client applies (vendor push services are
// public hosts, so legitimate endpoints always pass).
client: newWebhookHTTPClient(nil),
logger: slog.Default().With("component", "notifications.webpush"),
}
}
// processAttempt sends one claimed attempt and records the outcome. Expired
// or revoked subscriptions (404/410 from the push service) are deleted —
// that is the protocol's unsubscribe signal, not a failure to retry.
func (s *webPushSender) processAttempt(ctx context.Context, attempt DeliveryAttempt) {
sub, err := s.subscriptions.getByIDUnscoped(ctx, attempt.TargetID)
if err != nil || sub == nil {
if err == nil {
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeFailed,
attempt.AttemptNumber+1, nil, "subscription deleted", nil)
}
return
}
if !sub.Enabled || !s.settings.WebPushEnabled(ctx) {
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeFailed,
attempt.AttemptNumber+1, nil, "subscription disabled", nil)
return
}
row, err := s.deliveries.GetRowByID(ctx, attempt.NotificationDeliveryID)
if err != nil {
// Transient lookup failure: let the claim lease expire and the retry
// worker reclaim, instead of permanently failing the delivery.
if ctx.Err() == nil {
s.logger.Warn("web push delivery lookup failed",
"attempt_id", attempt.ID,
"delivery_id", attempt.NotificationDeliveryID,
"error", err)
}
return
}
if row == nil {
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeFailed,
attempt.AttemptNumber+1, nil, "delivery row missing", nil)
return
}
if row.ProfileID != sub.ProfileID {
// The endpoint was reassigned to a different profile between enqueue
// and dispatch; this delivery belongs to the previous owner.
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeFailed,
attempt.AttemptNumber+1, nil, "subscription reassigned", nil)
return
}
publicKey, privateKey, err := s.service.vapidKeys(ctx)
if err != nil {
s.logger.Error("VAPID keys unavailable", "error", err)
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeFailed,
attempt.AttemptNumber+1, nil, "VAPID keys unavailable", nil)
return
}
posterURL := ""
if s.payload != nil {
posterURL = s.payload(ctx, *row).PosterURL
}
message, err := buildWebPushPayload(*row, posterURL)
if err != nil {
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeFailed,
attempt.AttemptNumber+1, nil, "payload build failed", nil)
return
}
status, retryAfter, sendErr := s.send(ctx, sub, message, publicKey, privateKey)
attemptNumber := attempt.AttemptNumber + 1
if sendErr == nil && status >= 200 && status < 300 {
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeDelivered,
attemptNumber, &status, "", nil)
_ = s.subscriptions.RecordSuccess(ctx, sub.ID)
return
}
if status == http.StatusNotFound || status == http.StatusGone {
// The browser unsubscribed or the registration expired: remove the
// subscription entirely (attempts cascade with it).
s.logger.Info("web push subscription gone; removing",
"subscription_id", sub.ID, "status", status)
_ = s.subscriptions.deleteGone(ctx, sub.ID)
return
}
var statusPtr *int
if status > 0 {
statusPtr = &status
}
_ = s.subscriptions.RecordFailure(ctx, sub.ID, statusPtr)
message_ := "push service error"
if sendErr != nil {
message_ = classifyWebhookError(sendErr)
} else if status > 0 {
message_ = fmt.Sprintf("HTTP %d", status)
}
delay, more := webPushRetryDelay(attemptNumber)
if retryAfter > 0 {
delay = retryAfter
}
if more && (sendErr != nil || retryableHTTPStatus(status)) {
nextRetry := time.Now().Add(delay)
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeRetrying,
attemptNumber, statusPtr, message_, &nextRetry)
return
}
_ = s.subscriptions.FinalizeAttempt(ctx, attempt.ID, WebhookOutcomeFailed,
attemptNumber, statusPtr, message_, nil)
}
func (s *webPushSender) send(ctx context.Context, sub *WebPushSubscription, message []byte, publicKey, privateKey string) (status int, retryAfter time.Duration, err error) {
resp, err := webpush.SendNotificationWithContext(ctx, message, &webpush.Subscription{
Endpoint: sub.Endpoint,
Keys: webpush.Keys{P256dh: sub.P256dh, Auth: sub.Auth},
}, &webpush.Options{
HTTPClient: s.client,
Subscriber: "https://github.com/Silo-Server/silo-server",
TTL: webPushTTLSeconds,
Urgency: webpush.UrgencyNormal,
VAPIDPublicKey: publicKey,
VAPIDPrivateKey: privateKey,
})
if err != nil {
return 0, 0, err
}
defer func() { _ = resp.Body.Close() }()
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 16<<10))
if resp.StatusCode == http.StatusTooManyRequests {
retryAfter = parseRetryAfter(resp.Header.Get("Retry-After"), time.Now())
}
return resp.StatusCode, retryAfter, nil
}
// WebPushDispatcher implements the channel Dispatcher interface on top of the
// shared channelDispatcher core, with the retry/recovery sweep integrated.
type WebPushDispatcher struct {
core channelDispatcher[DeliveryAttempt]
}
func newWebPushDispatcher(sender *webPushSender) *WebPushDispatcher {
return &WebPushDispatcher{core: channelDispatcher[DeliveryAttempt]{
channel: "web push",
queue: make(chan string, webhookDispatchQueue),
logger: slog.Default().With("component", "notifications.webpush.dispatch"),
claimPending: sender.subscriptions.ClaimPendingForDelivery,
process: sender.processAttempt,
enabled: sender.settings.WebPushEnabled,
claimDue: sender.subscriptions.ClaimDue,
claimLimit: webhookRetryClaimLimit,
}}
}
// Dispatch queues the delivery's web push attempts for immediate send.
func (d *WebPushDispatcher) Dispatch(_ context.Context, delivery DeliveryRow) error {
if d == nil {
return nil
}
d.core.dispatch(delivery.ID)
return nil
}
// Run consumes the dispatch queue and the retry/recovery sweep until ctx is
// canceled.
func (d *WebPushDispatcher) Run(ctx context.Context) {
d.core.run(ctx)
}