package server import ( "context" "crypto/ecdh" "database/sql" "encoding/base64" "encoding/json" "errors" "fmt" "net/http" "net/url" "strings" "time" webpush "github.com/SherClockHolmes/webpush-go" "pageswiki/internal/store" ) type browserPushInput struct { Subscription webpush.Subscription `json:"subscription"` Focused bool `json:"focused"` Seen []string `json:"seen"` } type storedBrowserPush struct { webpush.Subscription Origin string `json:"origin"` } // Only browser push vendors are destinations, never arbitrary user-provided URLs. // DNS pinning/public-address checks at dial time provide a second SSRF boundary. func validPushSubscription(sub webpush.Subscription) bool { u, e := url.Parse(sub.Endpoint) if e != nil || u.Scheme != "https" || u.User != nil || u.Fragment != "" || u.Port() != "" || len(sub.Endpoint) > 4096 { return false } host := u.Hostname() if host != "fcm.googleapis.com" && host != "updates.push.services.mozilla.com" && host != "web.push.apple.com" && !strings.HasSuffix(host, ".push.services.mozilla.com") { return false } auth, e := base64.RawURLEncoding.DecodeString(sub.Keys.Auth) if e != nil || len(auth) != 16 { return false } key, e := base64.RawURLEncoding.DecodeString(sub.Keys.P256dh) if e != nil { return false } _, e = ecdh.P256().NewPublicKey(key) return e == nil } func (s *Server) notificationPushKeys(ctx context.Context) (private, public string, err error) { err = s.store.DB.QueryRowContext(ctx, `SELECT private_key,public_key FROM notification_push_keys WHERE id=1`).Scan(&private, &public) if !errors.Is(err, sql.ErrNoRows) { return } private, public, err = webpush.GenerateVAPIDKeys() if err != nil { return } _, err = s.store.DB.ExecContext(ctx, `INSERT OR IGNORE INTO notification_push_keys(id,private_key,public_key) VALUES(1,?,?)`, private, public) if err != nil { return } err = s.store.DB.QueryRowContext(ctx, `SELECT private_key,public_key FROM notification_push_keys WHERE id=1`).Scan(&private, &public) return } func (s *Server) handleNotificationPush(w http.ResponseWriter, r *http.Request, domain, owner string) { ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() switch r.Method { case "GET": _, pub, err := s.notificationPushKeys(ctx) if err != nil { writeEventJSON(w, 503, map[string]string{"error": "push unavailable"}) return } writeEventJSON(w, 200, map[string]string{"public_key": pub}) return case "POST", "DELETE": if !validBrowserMutationOrigin(r) { http.Error(w, "invalid origin", 403) return } var input browserPushInput if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8192)).Decode(&input); err != nil || !validPushSubscription(input.Subscription) || len(input.Seen) > 30 { writeEventJSON(w, 400, map[string]string{"error": "invalid push subscription"}) return } var err error if r.Method == "DELETE" { err = s.store.DeleteNotificationPush(ctx, domain, owner, input.Subscription.Endpoint) } else { raw, _ := json.Marshal(storedBrowserPush{input.Subscription, s.socialOrigin(r)}) err = s.store.SaveNotificationPush(ctx, domain, owner, s.authTokenFromRequest(r), input.Subscription.Endpoint, string(raw), input.Focused) if err == nil && input.Focused { err = s.store.AcknowledgeNotificationPush(ctx, domain, owner, input.Subscription.Endpoint, input.Seen) } } if err != nil { writeEventJSON(w, 409, map[string]string{"error": "unable to save subscription (maximum 8 devices)"}) return } writeEventJSON(w, 200, map[string]bool{"ok": true}) return } w.Header().Set("Allow", "GET, POST, DELETE") http.Error(w, "method not allowed", 405) } func (s *Server) deliverNotificationPush(job *store.EventJob) error { ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) defer cancel() // Bounded retention even for abandoned devices. Inbox is not affected. _, err := s.store.DB.ExecContext(ctx, `DELETE FROM notification_push_subscriptions WHERE id IN (SELECT id FROM notification_push_subscriptions WHERE expires_at_ms 0 { _ = s.store.AddEventLog(job.UUID, job.EventUUID, "info", fmt.Sprintf("push sent=%d failed=%d (no payload or endpoint logged)", sent, failed)) } return nil } func (s *Server) sendNotificationPush(ctx context.Context, d *store.NotificationPushDelivery, sub storedBrowserPush, client webpush.HTTPClient) (success, retry, expired bool) { if !validPushSubscription(sub.Subscription) { return false, false, true } private, public, e := s.notificationPushKeys(ctx) if e != nil { return false, true, false } // No task titles, body text or credentials leave the server in a push payload. payload, _ := json.Marshal(map[string]string{"uuid": d.Notification, "owner": d.Owner, "domain": d.Domain}) resp, e := webpush.SendNotificationWithContext(ctx, payload, &sub.Subscription, &webpush.Options{HTTPClient: client, Subscriber: sub.Origin, VAPIDPrivateKey: private, VAPIDPublicKey: public, TTL: 300, Urgency: webpush.UrgencyNormal, Topic: "pageswiki-inbox"}) if e != nil { return false, true, false } defer resp.Body.Close() return resp.StatusCode >= 200 && resp.StatusCode < 300, resp.StatusCode == 429 || resp.StatusCode >= 500, resp.StatusCode == 404 || resp.StatusCode == 410 }