//! Web Push: a notification for the inbox also reaches the user's devices when no tab is open. A //! browser (or an installed app) subscribes through the service worker, the server keeps the //! subscription, and [`queue`] sends the message to every device of a user. //! //! Delivery never blocks the caller: [`queue`] spawns the work, which looks up the user's devices, //! encrypts the message per device (RFC 8291), signs the request with the instance's VAPID key //! (RFC 8292) and posts it to the push service. A device the service reports gone (404 or 410) is //! removed. Every change to a user's devices is announced on [`PushLive`], so an open settings page //! refreshes through its event stream. pub mod crypto; use std::sync::OnceLock; use std::time::Duration; use serde::Serialize; use tokio::sync::broadcast; use forge_core::store::web_push::PushSubscription; use forge_core::{Error, Result}; use crate::i18n::{self, Lang, misc, push as text}; use crate::state::AppState; /// How long one push request may take before it counts as failed. const SEND_TIMEOUT: Duration = Duration::from_secs(15); /// Longest body text in a notification, in characters. const BODY_CHARS: usize = 140; /// Announces changes to a user's devices to the settings pages that show them. Only the event /// stream reads it; nothing here is stored, and a second server process would not see it. pub struct PushLive { tx: broadcast::Sender, } impl Default for PushLive { fn default() -> Self { Self { tx: broadcast::channel(64).0, } } } impl PushLive { /// Says that the devices of `user_id` changed. Nobody listening is fine. pub fn publish(&self, user_id: &str) { let _ = self.tx.send(user_id.to_owned()); } /// A receiver for every change, from every user. A stream filters for its own user. pub fn subscribe(&self) -> broadcast::Receiver { self.tx.subscribe() } } /// What a notification says. Built per recipient, in the recipient's language. #[derive(Clone)] pub enum Alert { /// Activity on an issue or pull request the user hears about. Activity { /// `owner/repo`. repo: String, number: i64, title: String, /// The verb of the activity (`misc::K::VerbOpened` and so on). verb: misc::K, actor: Option, /// The relative link the notification opens. url: String, /// The thread id. A newer notification for the same thread replaces the older one. thread: String, }, /// New security advisory alerts on a repo. Advisories { repo: String, count: u64, url: String, }, /// A site admin alert. Admin { subject: String, detail: String }, /// The test button. Test, } /// The JSON the service worker reads. Small, and nothing in it is a secret. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Message { pub title: String, pub body: String, /// A relative link on this origin. pub url: String, /// Notifications with the same tag replace each other on the device. pub tag: String, } impl Alert { /// The message for a recipient who reads `lang`. pub fn message(&self, lang: Lang) -> Message { match self { Alert::Activity { repo, number, title, verb, actor, url, thread, } => { let line = misc::activity_line(lang, *verb, actor.as_deref()); Message { title: format!("{repo}#{number}"), body: clip(&format!("{line}: {title}")), url: safe_url(url), tag: format!("thread-{thread}"), } } Alert::Advisories { repo, count, url } => Message { title: clip(repo), body: text::advisory_alerts(lang, *count), url: safe_url(url), tag: format!("advisories-{repo}"), }, Alert::Admin { subject, detail } => Message { title: clip(subject), body: clip(detail), url: "/notifications".to_owned(), tag: "admin-alert".to_owned(), }, Alert::Test => Message { title: text::t(lang, text::K::TestTitle).to_owned(), body: text::t(lang, text::K::TestBody).to_owned(), url: "/settings/notifications".to_owned(), tag: "test".to_owned(), }, } } } /// Shortens text to the body limit, in characters, one line. fn clip(text: &str) -> String { let one_line: String = text.split_whitespace().collect::>().join(" "); if one_line.chars().count() <= BODY_CHARS { return one_line; } let mut short: String = one_line.chars().take(BODY_CHARS - 3).collect(); short.push_str("..."); short } /// A relative link only. The service worker opens it on this origin, so anything that could leave /// the origin (a scheme, a protocol-relative `//host`) falls back to the notifications page. pub fn safe_url(url: &str) -> String { if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') { url.to_owned() } else { "/notifications".to_owned() } } /// A short label for a device, from its User-Agent: "Chrome on Android", "Safari on iPhone". pub fn agent_label(user_agent: &str) -> String { let os = if user_agent.contains("iPhone") { "iPhone" } else if user_agent.contains("iPad") { "iPad" } else if user_agent.contains("Android") { "Android" } else if user_agent.contains("Windows") { "Windows" } else if user_agent.contains("Macintosh") { "Mac" } else if user_agent.contains("CrOS") { "ChromeOS" } else if user_agent.contains("Linux") { "Linux" } else { "Unknown system" }; let browser = if user_agent.contains("Edg/") { "Edge" } else if user_agent.contains("OPR/") { "Opera" } else if user_agent.contains("Firefox/") { "Firefox" } else if user_agent.contains("Chrome/") || user_agent.contains("Chromium/") { "Chrome" } else if user_agent.contains("Safari/") { "Safari" } else { "Browser" }; format!("{browser} on {os}") } /// The shared HTTP client for push requests. Built once; redirects are not followed, since a push /// service answers on the endpoint itself. fn client() -> &'static reqwest::Client { static CLIENT: OnceLock = OnceLock::new(); CLIENT.get_or_init(|| { reqwest::Client::builder() .timeout(SEND_TIMEOUT) .redirect(reqwest::redirect::Policy::none()) .user_agent("forge-web-push") .build() .expect("the push client builds with the default TLS settings") }) } /// The instance's VAPID key pair. The private key is stored sealed with the instance key; the /// first call creates the pair. pub struct VapidKeys { pub private: [u8; 32], /// The public key, base64url. The browser subscribes with it. pub public: String, } /// The VAPID keys of this instance, creating and storing them on first use. pub async fn vapid_keys(state: &AppState) -> Result { let (public, sealed) = match state.store.web_push_keys().await? { Some(pair) => pair, None => { let private = crypto::new_vapid_private(); let public = crypto::vapid_public_key(&private)?; let sealed = forge_core::secret::seal(&state.key, &private)?; state.store.save_web_push_keys(&public, &sealed).await? } }; let opened = forge_core::secret::open(&state.key, &sealed)?; let private: [u8; 32] = opened .try_into() .map_err(|_| Error::Crypto("the stored VAPID key has the wrong length".into()))?; Ok(VapidKeys { private, public }) } /// The contact the push service may use about this instance: the base URL when it is https. fn subject(base_url: &str) -> String { let base = base_url.trim_end_matches('/'); if base.starts_with("https://") { base.to_owned() } else { "https://localhost".to_owned() } } /// What the push service answered for one device. #[derive(Debug, PartialEq, Eq)] pub enum Outcome { Delivered, /// 404 or 410: the subscription is gone and the device must be forgotten. Gone, Failed(String), } /// Encrypts `payload` for one device and posts it to the device's push service. pub async fn send_one( keys: &VapidKeys, subject: &str, sub: &PushSubscription, payload: &[u8], ) -> Outcome { let built = (|| { let p256dh = crypto::decode_b64(&sub.p256dh)?; let auth = crypto::decode_b64(&sub.auth)?; let key_pair = crypto::vapid_key_pair(&keys.private)?; crypto::push_request( &sub.endpoint, &p256dh, &auth, subject, &key_pair, payload.to_vec(), ) })(); let request = match built { Ok(request) => request, Err(e) => return Outcome::Failed(e.to_string()), }; let request = match reqwest::Request::try_from(request) { Ok(request) => request, Err(e) => return Outcome::Failed(e.to_string()), }; match client().execute(request).await { Ok(res) => match res.status().as_u16() { 200..=299 => Outcome::Delivered, 404 | 410 => Outcome::Gone, status => Outcome::Failed(format!("the push service answered {status}")), }, Err(e) => Outcome::Failed(e.to_string()), } } /// Queues `alert` for every device of `user_id`. Returns at once: the work runs on a spawned task. pub fn queue(state: &AppState, user_id: &str, alert: Alert) { let state = state.clone(); let user_id = user_id.to_owned(); tokio::spawn(async move { if let Err(e) = deliver(&state, &user_id, &alert).await { tracing::error!(error = %e, user_id, "web push: delivery failed"); } }); } /// Sends `alert` to every device of `user_id` now and returns how many devices there are. Devices /// the push service reports gone are removed. [`queue`] is the caller's entry point. pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result { let devices = state.store.push_subscriptions(user_id).await?; if devices.is_empty() { return Ok(0); } let lang = match state.store.user_by_id(user_id).await? { Some(user) => i18n::resolve(Some(user.language.as_str()), &http::HeaderMap::new()), None => Lang::En, }; let payload = serde_json::to_vec(&alert.message(lang)) .map_err(|e| Error::Invalid(format!("the push payload does not encode: {e}")))?; let keys = vapid_keys(state).await?; let subject = subject(&state.live().base_url); for device in &devices { match send_one(&keys, &subject, device, &payload).await { Outcome::Delivered => { state.store.mark_push_delivered(&device.id).await?; state.push_live.publish(user_id); } Outcome::Gone => { state.store.delete_push_endpoint(&device.endpoint).await?; state.push_live.publish(user_id); } Outcome::Failed(reason) => { tracing::warn!(reason, device = %device.id, "web push: a device was not reached"); } } } Ok(devices.len()) } #[cfg(test)] mod tests { use super::*; use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint; fn activity(actor: Option<&str>) -> Alert { Alert::Activity { repo: "tahinli/forge".into(), number: 42, title: "Crash on startup\nwhen the cache is cold".into(), verb: misc::K::VerbCommented, actor: actor.map(str::to_owned), url: "/tahinli/forge/issues/42".into(), thread: "issue-1".into(), } } #[test] fn an_activity_payload_is_short_and_names_the_thread() { let msg = activity(Some("tahinli")).message(Lang::En); assert_eq!(msg.title, "tahinli/forge#42"); assert_eq!( msg.body, "commented by tahinli: Crash on startup when the cache is cold" ); assert_eq!(msg.url, "/tahinli/forge/issues/42"); assert_eq!(msg.tag, "thread-issue-1"); } #[test] fn the_body_is_clipped_to_the_limit() { let long = Alert::Admin { subject: "Backup".into(), detail: "x".repeat(400), }; let msg = long.message(Lang::En); assert_eq!(msg.body.chars().count(), BODY_CHARS); assert!(msg.body.ends_with("...")); } #[test] fn the_payload_follows_the_recipient_language() { let msg = activity(None).message(Lang::Tr); assert!(msg.body.starts_with("Yorumlandı"), "{}", msg.body); let advisories = Alert::Advisories { repo: "tahinli/forge".into(), count: 3, url: "/tahinli/forge/security".into(), }; assert_eq!(advisories.message(Lang::En).body, "3 new security alerts"); assert_eq!(advisories.message(Lang::Tr).body, "3 yeni güvenlik uyarısı"); } #[test] fn a_link_must_stay_on_this_origin() { assert_eq!(safe_url("/tahinli/forge"), "/tahinli/forge"); assert_eq!(safe_url("https://evil.example/x"), "/notifications"); assert_eq!(safe_url("//evil.example/x"), "/notifications"); assert_eq!(safe_url("/\\evil.example"), "/notifications"); } #[test] fn device_labels_name_the_browser_and_the_system() { let chrome_android = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36"; assert_eq!(agent_label(chrome_android), "Chrome on Android"); let safari_iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1"; assert_eq!(agent_label(safari_iphone), "Safari on iPhone"); assert_eq!(agent_label("curl/8.0"), "Browser on Unknown system"); } #[test] fn the_subject_is_https_or_the_fallback() { assert_eq!( subject("https://forge.example.test/"), "https://forge.example.test" ); assert_eq!(subject("http://127.0.0.1:7660"), "https://localhost"); } #[test] fn push_live_reaches_a_listener_and_tolerates_none() { let live = PushLive::default(); live.publish("nobody"); let mut rx = live.subscribe(); live.publish("tahinli"); assert_eq!(rx.try_recv().expect("event"), "tahinli"); } /// A local stand-in for a push service: `/gone` answers 410, `/ok` answers 201, and each /// request is read in full (headers and body) before it is answered. async fn mock_push_service() -> std::net::SocketAddr { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind"); let addr = listener.local_addr().expect("addr"); tokio::spawn(async move { loop { let Ok((mut socket, _)) = listener.accept().await else { return; }; tokio::spawn(async move { let mut buf = Vec::new(); let mut chunk = [0u8; 4096]; let (head_end, length) = loop { let n = socket.read(&mut chunk).await.unwrap_or(0); if n == 0 { return; } buf.extend_from_slice(&chunk[..n]); if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { let head = String::from_utf8_lossy(&buf[..end]).to_ascii_lowercase(); let length = head .lines() .find_map(|l| l.strip_prefix("content-length:")) .and_then(|v| v.trim().parse::().ok()) .unwrap_or(0); break (end + 4, length); } }; while buf.len() < head_end + length { let n = socket.read(&mut chunk).await.unwrap_or(0); if n == 0 { break; } buf.extend_from_slice(&chunk[..n]); } let request = String::from_utf8_lossy(&buf[..head_end]).into_owned(); let status = if request.starts_with("POST /gone") { "410 Gone" } else { "201 Created" }; let reply = format!( "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ); let _ = socket.write_all(reply.as_bytes()).await; }); } }); addr } fn device(endpoint: String) -> PushSubscription { let secret = web_push_native::p256::SecretKey::from_slice(&crypto::new_vapid_private()) .expect("scalar"); let point = secret.public_key().to_encoded_point(false); PushSubscription { id: endpoint.clone(), user_id: String::new(), endpoint, p256dh: crypto::encode_b64(point.as_bytes()), auth: crypto::encode_b64(&[9u8; 16]), agent_label: "Chrome on Linux".into(), created_at: String::new(), last_success_at: None, } } #[tokio::test] async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() { let dir = tempfile::tempdir().expect("tempdir"); let state = crate::test_support::test_state(dir.path()).await; let user = state .store .create_user("tahinli", None, "h", false) .await .expect("user"); let addr = mock_push_service().await; let gone = format!("http://{addr}/gone"); let ok = format!("http://{addr}/ok"); state .store .save_push_subscription( &user.id, &gone, &device(gone.clone()).p256dh, &device(gone.clone()).auth, "Chrome on Linux", ) .await .expect("save gone"); state .store .save_push_subscription( &user.id, &ok, &device(ok.clone()).p256dh, &device(ok.clone()).auth, "Chrome on Linux", ) .await .expect("save ok"); let sent = deliver(&state, &user.id, &Alert::Test) .await .expect("deliver"); assert_eq!(sent, 2); let left = state .store .push_subscriptions(&user.id) .await .expect("list"); assert_eq!(left.len(), 1, "the 410 device is forgotten"); assert_eq!(left[0].endpoint, ok); assert!( left[0].last_success_at.is_some(), "the delivered device is stamped" ); } #[tokio::test] async fn the_payload_is_encrypted_for_the_device_and_the_status_is_read() { let addr = mock_push_service().await; let private = crypto::new_vapid_private(); let keys = VapidKeys { public: crypto::vapid_public_key(&private).expect("public"), private, }; let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json"); let ok = device(format!("http://{addr}/ok")); assert_eq!( send_one(&keys, "https://localhost", &ok, &payload).await, Outcome::Delivered ); let gone = device(format!("http://{addr}/gone")); assert_eq!( send_one(&keys, "https://localhost", &gone, &payload).await, Outcome::Gone ); } }