package main import ( "encoding/json" "errors" "fmt" "io" "log" "net" "net/http" "net/url" "os" "sync" "sync/atomic" "time" webpush "github.com/SherClockHolmes/webpush-go" ) // pushClient sends Web Push POSTs. The endpoint is attacker-controlled data (any // member registers one at subscribe time), so — like ogClient — its dialer // validates the resolved IP of every connection to stop the server being pointed // at its own network (SSRF), and re-validates each redirect hop (defeating DNS // rebinding). webpush-go otherwise uses http.DefaultClient, which has no guard. var pushClient = &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ DialContext: (&net.Dialer{ Timeout: 10 * time.Second, Control: guardDialControl, }).DialContext, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 20 * time.Second, DisableKeepAlives: true, }, CheckRedirect: func(req *http.Request, via []*http.Request) error { if len(via) >= 5 { return errors.New("too many redirects") } if req.URL.Scheme != "https" { return errors.New("non-https redirect") } return nil }, } // validatePushEndpoint is the first line of the SSRF guard: it rejects anything // that isn't a plain https URL with a host before we ever store it. Real Web Push // services (FCM, Mozilla, Apple, Windows) are always https. The resolved-IP check // that actually blocks internal targets lives in pushClient's dialer above, so a // stale stored endpoint is still guarded when we send. func validatePushEndpoint(endpoint string) error { if len(endpoint) > 2048 { return errors.New("endpoint too long") } u, err := url.Parse(endpoint) if err != nil { return err } if u.Scheme != "https" { return errors.New("endpoint must be https") } if u.Hostname() == "" { return errors.New("endpoint has no host") } return nil } // PushSub is a stored Web Push subscription, tied to the session token that made // it. Only a hash of that token is persisted (it's a live credential); Token is // the raw value on the way in, TokenHash is what comes back out and is matched on. type PushSub struct { Endpoint string Token string // raw session token — input to addSubscription only, never stored TokenHash string // hashToken(Token); the persisted, matched-on value P256dh string Auth string UserID string // who this belongs to (so removing a user drops their subs) } func (db *DB) addSubscription(s PushSub) error { var uid any if s.UserID != "" { uid = s.UserID } // Persist only the token hash; the plaintext `token` column stays empty. _, err := db.sql.Exec( `INSERT INTO push_subscriptions(endpoint, token, token_hash, p256dh, auth, user_id, created_at) VALUES(?, '', ?, ?, ?, ?, ?) ON CONFLICT(endpoint) DO UPDATE SET token='', token_hash=excluded.token_hash, p256dh=excluded.p256dh, auth=excluded.auth, user_id=excluded.user_id`, s.Endpoint, hashToken(s.Token), s.P256dh, s.Auth, uid, time.Now().Unix(), ) return err } func (db *DB) listSubscriptions() ([]PushSub, error) { rows, err := db.sql.Query("SELECT endpoint, COALESCE(token_hash, ''), p256dh, auth FROM push_subscriptions") if err != nil { return nil, err } defer rows.Close() out := []PushSub{} for rows.Next() { var s PushSub if err := rows.Scan(&s.Endpoint, &s.TokenHash, &s.P256dh, &s.Auth); err != nil { return nil, err } out = append(out, s) } return out, rows.Err() } func (db *DB) deleteSubscription(endpoint string) error { _, err := db.sql.Exec("DELETE FROM push_subscriptions WHERE endpoint = ?", endpoint) return err } // deleteOwnSubscription removes a subscription only if it belongs to the given // token, so knowing someone else's endpoint isn't enough to silence their device. func (db *DB) deleteOwnSubscription(endpoint, token string) error { _, err := db.sql.Exec( "DELETE FROM push_subscriptions WHERE endpoint = ? AND token_hash = ?", endpoint, hashToken(token), ) return err } func (db *DB) deleteSubscriptionsForToken(token string) error { _, err := db.sql.Exec("DELETE FROM push_subscriptions WHERE token_hash = ?", hashToken(token)) return err } // ensureVAPID returns the server's VAPID keypair, generating and persisting one on // first use. VAPID lets the server authenticate itself to the browser push services // with no third-party account — it is unrelated to message encryption. // // The pair lives in a 0600 sidecar file next to the DB (.vapid, like the // -blobs dir), deliberately NOT in the config table: hibernation replicates // lchat.db to S3, and a bucket leak must not hand out private keys of any kind // (docs/no-plaintext.md § 2). The pair used to live in config — those legacy // rows are moved into the file and deleted on first boot, so existing push // subscriptions keep working across the change. func (db *DB) ensureVAPID() (pub, priv string, err error) { // The file is authoritative once it exists. A restored/older DB snapshot may // still carry the legacy config rows — clear them so the DB (and its S3 // replica) never re-grows a private key. b, readErr := os.ReadFile(db.vapidPath) if readErr == nil { var k struct{ Public, Private string } if err := json.Unmarshal(b, &k); err != nil || k.Public == "" || k.Private == "" { // Fail loud rather than silently minting a new pair: regenerating // breaks every existing push subscription, so a corrupt file is an // operator problem (restore or delete it), not something to paper over. return "", "", fmt.Errorf("vapid keyfile %s is malformed; restore it or delete it to re-mint (breaks existing push subscriptions)", db.vapidPath) } db.deleteVAPIDConfig() return k.Public, k.Private, nil } if !os.IsNotExist(readErr) { // EACCES/EIO etc. must NOT fall through to the mint path — that would // rename a fresh pair over a file that exists but couldn't be read // (e.g. an operator's root-owned copy after a migration) and silently // break every subscription. Only a genuinely absent file mints. return "", "", fmt.Errorf("vapid keyfile %s: %w", db.vapidPath, readErr) } // Legacy: the pair is still in the DB — move it into the file. Fresh // instance: mint one. Either way the file is written before the config // rows are deleted, so a crash in between leaves both copies (file wins // next boot), never neither. pub, okPub, errPub := db.getConfig("vapid_public") priv, okPriv, errPriv := db.getConfig("vapid_private") if errPub != nil || errPriv != nil { // A transient DB error here must not mint a fresh pair (the delete // below would then destroy the intact legacy rows) — retry next boot. return "", "", fmt.Errorf("vapid config read: %v / %v", errPub, errPriv) } if !okPub || !okPriv { priv, pub, err = webpush.GenerateVAPIDKeys() if err != nil { return "", "", err } // A fresh mint with existing subscriptions means the old pair is gone // (a DB restored onto a new box) — say so, since those subscriptions // are now dead until members revisit (docs/secrets.md). if subs, _ := db.listSubscriptions(); len(subs) > 0 { log.Printf("vapid: minted a NEW keypair with %d existing push subscriptions — they break until members re-subscribe on next visit", len(subs)) } } blob, err := json.Marshal(struct{ Public, Private string }{pub, priv}) if err != nil { return "", "", err } // Write-temp-then-rename so a crash mid-write can't leave a torn keyfile. tmp := db.vapidPath + ".tmp" if err = os.WriteFile(tmp, blob, 0o600); err != nil { return "", "", err } if err = os.Rename(tmp, db.vapidPath); err != nil { return "", "", err } db.deleteVAPIDConfig() return pub, priv, nil } // deleteVAPIDConfig scrubs the legacy config-table copy of the VAPID pair. // Best-effort: a failed delete just means the next boot retries. func (db *DB) deleteVAPIDConfig() { db.sql.Exec("DELETE FROM config WHERE key IN ('vapid_public', 'vapid_private')") } // pushNewMessage delivers the ciphertext blob to every subscription. The server // never sees plaintext: the payload IS the same ciphertext stored in the DB, and // the service worker decrypts it locally with the group key. Expired subscriptions // (404/410) are pruned. Best-effort; runs in its own goroutine. // pushNewMessage notifies everyone except the sender — you don't want a push on // any of your own devices for a message you just sent. The sender's device token // (from their WebSocket) identifies both that device and, via its owning user, // all their other devices, which selectRecipients excludes. func (s *Server) pushNewMessage(blob, threadID, senderToken string, id, at int64) { // The space thread (spacethread.go) never pushes: its traffic is app // machinery (install registry + space-app events) that must not buzz every // phone in the space, and clients that don't know the thread (native, old) // couldn't render the notification. Live WS delivery still applies. if s.db.threadKind(threadID) == "space" { return } members, err := s.db.memberUserIDs(threadID) if err != nil { log.Println("push: thread members:", err) return } set := make(map[string]bool, len(members)) for _, u := range members { set[u] = true } s.dropMutedRecipients(threadID, set) // And members who BLOCK the sender (issue #578): a blocked member's group // messages must never buzz the blocker (the client folds them away too). if senderUser, ok := s.db.deviceTokenUser(senderToken); ok { s.dropBlockingRecipients(senderUser, set) } // id/at ride along so the service worker can file the row straight into // the page's local message store (#457 phase 2) — opening from a // notification then paints with the message already in place. Additive: // an older SW just ignores them. Both are values the recipient could read // from /api/messages anyway; nothing new is disclosed. payload, _ := json.Marshal(map[string]any{"blob": blob, "thread": threadID, "id": id, "at": at}) // skipActive=true: don't notify people currently reading on another device. // recipients=set: only this thread's members, never non-members. s.sendToRecipients(payload, "msg", senderToken, true, set) // Same message, same rules, over APNs to the native iOS apps (no-op unless // LCHAT_APNS_* is configured). s.apnsFanOut(threadID, blob, id, at, senderToken, true, set) } // dropMutedRecipients removes members who muted the thread from a push // recipient set — a mute means no buzz on any device, over either transport. // The messages themselves still flow; only notifications stop. func (s *Server) dropMutedRecipients(threadID string, set map[string]bool) { muted, err := s.db.mutedUserIDs(threadID) if err != nil { log.Println("push: muted members:", err) return // best-effort: on error, prefer a spurious buzz over a lost one } for u := range muted { delete(set, u) } } // dropBlockingRecipients removes members who have blocked the author from a // push recipient set — block implies never hearing from them again. func (s *Server) dropBlockingRecipients(authorID string, set map[string]bool) { blockers, err := s.db.blockersOf(authorID) if err != nil { log.Println("push: blockers:", err) return } for u := range blockers { delete(set, u) } } // sendTestPush delivers a generic "it works" notification to every subscriber, // bypassing the message flow (and ignoring active state, so it always lands). // It covers BOTH transports: Web Push (browsers) and APNs (native iOS, via the // relay when configured). The APNs side carries a dummy thread/blob the NSE // can't decrypt, so the phone shows the placeholder "New message" banner (see // ios/LChatNSE) — which is exactly the "push reached this device" signal a test // wants. No exclusions (exceptToken="", recipients=nil) and skipActive=false, so // it always lands, on every registered device including the admin's own. func (s *Server) sendTestPush() int { payload, _ := json.Marshal(map[string]bool{"test": true}) sent := s.sendToRecipients(payload, "test", "", false, nil) sent += s.apnsFanOut("test", "test", 0, 0, "", false, nil) // no-op unless APNs/relay configured return sent } // maxPushConcurrency bounds simultaneous sends so a large group doesn't open // thousands of sockets at once. Each webpush send is a blocking HTTPS round-trip, // so fanning out turns O(N) sequential latency into ~O(N/concurrency). const maxPushConcurrency = 32 // selectRecipients decides which subscriptions should receive a payload. It // excludes the sender — by exact device token AND by owning user, so none of the // sender's *other* devices buzz for a message they sent (each device carries its // own token now, so an exact-token match alone would miss the sibling devices). // When skipActive it also drops ALL of a recipient's devices if they're reading on // any one of them (per-user, mirroring the sender exclusion — a per-device check // would still buzz your phone while you read on your laptop), and when recipients is // non-nil it keeps only devices whose owner is in that set (thread membership). func (s *Server) selectRecipients(subs []PushSub, exceptToken string, skipActive bool, recipients map[string]bool) []PushSub { senderUser := "" exceptHash := "" if exceptToken != "" { exceptHash = hashToken(exceptToken) senderUser, _ = s.db.deviceTokenUser(exceptToken) } out := make([]PushSub, 0, len(subs)) for _, sub := range subs { if exceptHash != "" && sub.TokenHash == exceptHash { continue // the exact device that sent it } // Resolve the owner once — needed for sender-user exclusion, the per-user // active check, and membership. Resolved from the stored token hash. var uid string var known bool if senderUser != "" || recipients != nil || skipActive { uid, known = s.db.deviceTokenUserByHash(sub.TokenHash) } if senderUser != "" && known && uid == senderUser { continue // another of the sender's own devices — don't notify yourself } if skipActive && s.isUserActive(uid) { continue // this person is reading on one of their devices right now } if recipients != nil && (!known || !recipients[uid]) { continue // not a member of this thread } out = append(out, sub) } return out } // sendToRecipients delivers a payload to the subscriptions selectRecipients // picks. Prunes dead subs (404/410). Sends run concurrently, bounded by // maxPushConcurrency. Returns the number of successful sends. func (s *Server) sendToRecipients(payload []byte, kind, exceptToken string, skipActive bool, recipients map[string]bool) int { subs, err := s.db.listSubscriptions() if err != nil { log.Println("push: list subs:", err) return 0 } targets := s.selectRecipients(subs, exceptToken, skipActive, recipients) log.Printf("push[%s]: %d subscription(s), %d after exclusions", kind, len(subs), len(targets)) sem := make(chan struct{}, maxPushConcurrency) var wg sync.WaitGroup var sent atomic.Int64 for _, sub := range targets { wg.Add(1) sem <- struct{}{} go func(sub PushSub) { defer wg.Done() defer func() { <-sem }() if s.sendOne(payload, kind, sub) { sent.Add(1) } }(sub) } wg.Wait() return int(sent.Load()) } // sendOne delivers a payload to a single subscription, pruning it if the push // service reports it gone (404/410). Returns true on a 2xx. func (s *Server) sendOne(payload []byte, kind string, sub PushSub) bool { resp, err := webpush.SendNotification(payload, &webpush.Subscription{ Endpoint: sub.Endpoint, Keys: webpush.Keys{P256dh: sub.P256dh, Auth: sub.Auth}, }, &webpush.Options{ // Route through the SSRF-guarded client, not webpush-go's default // http.DefaultClient — the endpoint is attacker-controlled. HTTPClient: pushClient, // Pass the bare e-mail: webpush-go prepends "mailto:" itself. Passing // "mailto:…" yields "mailto:mailto:…", which Apple rejects (BadJwtToken). Subscriber: "admin@elevenmessenger.com", VAPIDPublicKey: s.vapidPub, VAPIDPrivateKey: s.vapidPriv, TTL: 60, Urgency: webpush.UrgencyHigh, }) if err != nil { log.Printf("push[%s]: send error: %v", kind, err) return false } defer resp.Body.Close() if resp.StatusCode >= 200 && resp.StatusCode < 300 { log.Printf("push[%s]: status %d (%.45s…)", kind, resp.StatusCode, sub.Endpoint) return true } body, _ := io.ReadAll(io.LimitReader(resp.Body, 400)) log.Printf("push[%s]: status %d body=%q (%.45s…)", kind, resp.StatusCode, string(body), sub.Endpoint) if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone { _ = s.db.deleteSubscription(sub.Endpoint) } return false }