| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | pub mod crypto; |
| 12 | |
| 13 | use std::sync::OnceLock; |
| 14 | use std::time::Duration; |
| 15 | |
| 16 | use serde::Serialize; |
| 17 | use tokio::sync::broadcast; |
| 18 | |
| 19 | use forge_core::store::web_push::PushSubscription; |
| 20 | use forge_core::{Error, Result}; |
| 21 | |
| 22 | use crate::i18n::{self, Lang, misc, push as text}; |
| 23 | use crate::state::AppState; |
| 24 | |
| 25 | |
| 26 | const SEND_TIMEOUT: Duration = Duration::from_secs(15); |
| 27 | |
| 28 | const BODY_CHARS: usize = 140; |
| 29 | |
| 30 | |
| 31 | |
| 32 | pub struct PushLive { |
| 33 | tx: broadcast::Sender<String>, |
| 34 | } |
| 35 | |
| 36 | impl Default for PushLive { |
| 37 | fn default() -> Self { |
| 38 | Self { |
| 39 | tx: broadcast::channel(64).0, |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | impl PushLive { |
| 45 | |
| 46 | pub fn publish(&self, user_id: &str) { |
| 47 | let _ = self.tx.send(user_id.to_owned()); |
| 48 | } |
| 49 | |
| 50 | |
| 51 | pub fn subscribe(&self) -> broadcast::Receiver<String> { |
| 52 | self.tx.subscribe() |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | |
| 57 | #[derive(Clone)] |
| 58 | pub enum Alert { |
| 59 | |
| 60 | Activity { |
| 61 | |
| 62 | repo: String, |
| 63 | number: i64, |
| 64 | title: String, |
| 65 | |
| 66 | verb: misc::K, |
| 67 | actor: Option<String>, |
| 68 | |
| 69 | url: String, |
| 70 | |
| 71 | thread: String, |
| 72 | }, |
| 73 | |
| 74 | Advisories { |
| 75 | repo: String, |
| 76 | count: u64, |
| 77 | url: String, |
| 78 | }, |
| 79 | |
| 80 | Admin { subject: String, detail: String }, |
| 81 | |
| 82 | Test, |
| 83 | } |
| 84 | |
| 85 | |
| 86 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 87 | pub struct Message { |
| 88 | pub title: String, |
| 89 | pub body: String, |
| 90 | |
| 91 | pub url: String, |
| 92 | |
| 93 | pub tag: String, |
| 94 | } |
| 95 | |
| 96 | impl Alert { |
| 97 | |
| 98 | pub fn message(&self, lang: Lang) -> Message { |
| 99 | match self { |
| 100 | Alert::Activity { |
| 101 | repo, |
| 102 | number, |
| 103 | title, |
| 104 | verb, |
| 105 | actor, |
| 106 | url, |
| 107 | thread, |
| 108 | } => { |
| 109 | let line = misc::activity_line(lang, *verb, actor.as_deref()); |
| 110 | Message { |
| 111 | title: format!("{repo}#{number}"), |
| 112 | body: clip(&format!("{line}: {title}")), |
| 113 | url: safe_url(url), |
| 114 | tag: format!("thread-{thread}"), |
| 115 | } |
| 116 | } |
| 117 | Alert::Advisories { repo, count, url } => Message { |
| 118 | title: clip(repo), |
| 119 | body: text::advisory_alerts(lang, *count), |
| 120 | url: safe_url(url), |
| 121 | tag: format!("advisories-{repo}"), |
| 122 | }, |
| 123 | Alert::Admin { subject, detail } => Message { |
| 124 | title: clip(subject), |
| 125 | body: clip(detail), |
| 126 | url: "/notifications".to_owned(), |
| 127 | tag: "admin-alert".to_owned(), |
| 128 | }, |
| 129 | Alert::Test => Message { |
| 130 | title: text::t(lang, text::K::TestTitle).to_owned(), |
| 131 | body: text::t(lang, text::K::TestBody).to_owned(), |
| 132 | url: "/settings/notifications".to_owned(), |
| 133 | tag: "test".to_owned(), |
| 134 | }, |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | |
| 140 | fn clip(text: &str) -> String { |
| 141 | let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" "); |
| 142 | if one_line.chars().count() <= BODY_CHARS { |
| 143 | return one_line; |
| 144 | } |
| 145 | let mut short: String = one_line.chars().take(BODY_CHARS - 3).collect(); |
| 146 | short.push_str("..."); |
| 147 | short |
| 148 | } |
| 149 | |
| 150 | |
| 151 | |
| 152 | pub fn safe_url(url: &str) -> String { |
| 153 | if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') { |
| 154 | url.to_owned() |
| 155 | } else { |
| 156 | "/notifications".to_owned() |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | |
| 161 | pub fn agent_label(user_agent: &str) -> String { |
| 162 | let os = if user_agent.contains("iPhone") { |
| 163 | "iPhone" |
| 164 | } else if user_agent.contains("iPad") { |
| 165 | "iPad" |
| 166 | } else if user_agent.contains("Android") { |
| 167 | "Android" |
| 168 | } else if user_agent.contains("Windows") { |
| 169 | "Windows" |
| 170 | } else if user_agent.contains("Macintosh") { |
| 171 | "Mac" |
| 172 | } else if user_agent.contains("CrOS") { |
| 173 | "ChromeOS" |
| 174 | } else if user_agent.contains("Linux") { |
| 175 | "Linux" |
| 176 | } else { |
| 177 | "Unknown system" |
| 178 | }; |
| 179 | let browser = if user_agent.contains("Edg/") { |
| 180 | "Edge" |
| 181 | } else if user_agent.contains("OPR/") { |
| 182 | "Opera" |
| 183 | } else if user_agent.contains("Firefox/") { |
| 184 | "Firefox" |
| 185 | } else if user_agent.contains("Chrome/") || user_agent.contains("Chromium/") { |
| 186 | "Chrome" |
| 187 | } else if user_agent.contains("Safari/") { |
| 188 | "Safari" |
| 189 | } else { |
| 190 | "Browser" |
| 191 | }; |
| 192 | format!("{browser} on {os}") |
| 193 | } |
| 194 | |
| 195 | |
| 196 | |
| 197 | fn client() -> &'static reqwest::Client { |
| 198 | static CLIENT: OnceLock<reqwest::Client> = OnceLock::new(); |
| 199 | CLIENT.get_or_init(|| { |
| 200 | reqwest::Client::builder() |
| 201 | .timeout(SEND_TIMEOUT) |
| 202 | .redirect(reqwest::redirect::Policy::none()) |
| 203 | .user_agent("forge-web-push") |
| 204 | .build() |
| 205 | .expect("the push client builds with the default TLS settings") |
| 206 | }) |
| 207 | } |
| 208 | |
| 209 | |
| 210 | |
| 211 | pub struct VapidKeys { |
| 212 | pub private: [u8; 32], |
| 213 | |
| 214 | pub public: String, |
| 215 | } |
| 216 | |
| 217 | |
| 218 | pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> { |
| 219 | let (public, sealed) = match state.store.web_push_keys().await? { |
| 220 | Some(pair) => pair, |
| 221 | None => { |
| 222 | let private = crypto::new_vapid_private(); |
| 223 | let public = crypto::vapid_public_key(&private)?; |
| 224 | let sealed = forge_core::secret::seal(&state.key, &private)?; |
| 225 | state.store.save_web_push_keys(&public, &sealed).await? |
| 226 | } |
| 227 | }; |
| 228 | let opened = forge_core::secret::open(&state.key, &sealed)?; |
| 229 | let private: [u8; 32] = opened |
| 230 | .try_into() |
| 231 | .map_err(|_| Error::Crypto("the stored VAPID key has the wrong length".into()))?; |
| 232 | Ok(VapidKeys { private, public }) |
| 233 | } |
| 234 | |
| 235 | |
| 236 | fn subject(base_url: &str) -> String { |
| 237 | let base = base_url.trim_end_matches('/'); |
| 238 | if base.starts_with("https://") { |
| 239 | base.to_owned() |
| 240 | } else { |
| 241 | "https://localhost".to_owned() |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | |
| 246 | #[derive(Debug, PartialEq, Eq)] |
| 247 | pub enum Outcome { |
| 248 | Delivered, |
| 249 | |
| 250 | Gone, |
| 251 | Failed(String), |
| 252 | } |
| 253 | |
| 254 | |
| 255 | pub async fn send_one( |
| 256 | keys: &VapidKeys, |
| 257 | subject: &str, |
| 258 | sub: &PushSubscription, |
| 259 | payload: &[u8], |
| 260 | ) -> Outcome { |
| 261 | let built = (|| { |
| 262 | let p256dh = crypto::decode_b64(&sub.p256dh)?; |
| 263 | let auth = crypto::decode_b64(&sub.auth)?; |
| 264 | let key_pair = crypto::vapid_key_pair(&keys.private)?; |
| 265 | crypto::push_request( |
| 266 | &sub.endpoint, |
| 267 | &p256dh, |
| 268 | &auth, |
| 269 | subject, |
| 270 | &key_pair, |
| 271 | payload.to_vec(), |
| 272 | ) |
| 273 | })(); |
| 274 | let request = match built { |
| 275 | Ok(request) => request, |
| 276 | Err(e) => return Outcome::Failed(e.to_string()), |
| 277 | }; |
| 278 | let request = match reqwest::Request::try_from(request) { |
| 279 | Ok(request) => request, |
| 280 | Err(e) => return Outcome::Failed(e.to_string()), |
| 281 | }; |
| 282 | match client().execute(request).await { |
| 283 | Ok(res) => match res.status().as_u16() { |
| 284 | 200..=299 => Outcome::Delivered, |
| 285 | 404 | 410 => Outcome::Gone, |
| 286 | status => Outcome::Failed(format!("the push service answered {status}")), |
| 287 | }, |
| 288 | Err(e) => Outcome::Failed(e.to_string()), |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | |
| 293 | pub fn queue(state: &AppState, user_id: &str, alert: Alert) { |
| 294 | let state = state.clone(); |
| 295 | let user_id = user_id.to_owned(); |
| 296 | tokio::spawn(async move { |
| 297 | if let Err(e) = deliver(&state, &user_id, &alert).await { |
| 298 | tracing::error!(error = %e, user_id, "web push: delivery failed"); |
| 299 | } |
| 300 | }); |
| 301 | } |
| 302 | |
| 303 | |
| 304 | |
| 305 | pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<usize> { |
| 306 | let devices = state.store.push_subscriptions(user_id).await?; |
| 307 | if devices.is_empty() { |
| 308 | return Ok(0); |
| 309 | } |
| 310 | let lang = match state.store.user_by_id(user_id).await? { |
| 311 | Some(user) => i18n::resolve(Some(user.language.as_str()), &http::HeaderMap::new()), |
| 312 | None => Lang::En, |
| 313 | }; |
| 314 | let payload = serde_json::to_vec(&alert.message(lang)) |
| 315 | .map_err(|e| Error::Invalid(format!("the push payload does not encode: {e}")))?; |
| 316 | let keys = vapid_keys(state).await?; |
| 317 | let subject = subject(&state.live().base_url); |
| 318 | for device in &devices { |
| 319 | match send_one(&keys, &subject, device, &payload).await { |
| 320 | Outcome::Delivered => { |
| 321 | state.store.mark_push_delivered(&device.id).await?; |
| 322 | state.push_live.publish(user_id); |
| 323 | } |
| 324 | Outcome::Gone => { |
| 325 | state.store.delete_push_endpoint(&device.endpoint).await?; |
| 326 | state.push_live.publish(user_id); |
| 327 | } |
| 328 | Outcome::Failed(reason) => { |
| 329 | tracing::warn!(reason, device = %device.id, "web push: a device was not reached"); |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | Ok(devices.len()) |
| 334 | } |
| 335 | |
| 336 | #[cfg(test)] |
| 337 | mod tests { |
| 338 | use super::*; |
| 339 | use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint; |
| 340 | |
| 341 | fn activity(actor: Option<&str>) -> Alert { |
| 342 | Alert::Activity { |
| 343 | repo: "tahinli/forge".into(), |
| 344 | number: 42, |
| 345 | title: "Crash on startup\nwhen the cache is cold".into(), |
| 346 | verb: misc::K::VerbCommented, |
| 347 | actor: actor.map(str::to_owned), |
| 348 | url: "/tahinli/forge/issues/42".into(), |
| 349 | thread: "issue-1".into(), |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn an_activity_payload_is_short_and_names_the_thread() { |
| 355 | let msg = activity(Some("tahinli")).message(Lang::En); |
| 356 | assert_eq!(msg.title, "tahinli/forge#42"); |
| 357 | assert_eq!( |
| 358 | msg.body, |
| 359 | "commented by tahinli: Crash on startup when the cache is cold" |
| 360 | ); |
| 361 | assert_eq!(msg.url, "/tahinli/forge/issues/42"); |
| 362 | assert_eq!(msg.tag, "thread-issue-1"); |
| 363 | } |
| 364 | |
| 365 | #[test] |
| 366 | fn the_body_is_clipped_to_the_limit() { |
| 367 | let long = Alert::Admin { |
| 368 | subject: "Backup".into(), |
| 369 | detail: "x".repeat(400), |
| 370 | }; |
| 371 | let msg = long.message(Lang::En); |
| 372 | assert_eq!(msg.body.chars().count(), BODY_CHARS); |
| 373 | assert!(msg.body.ends_with("...")); |
| 374 | } |
| 375 | |
| 376 | #[test] |
| 377 | fn the_payload_follows_the_recipient_language() { |
| 378 | let msg = activity(None).message(Lang::Tr); |
| 379 | assert!(msg.body.starts_with("Yorumlandı"), "{}", msg.body); |
| 380 | let advisories = Alert::Advisories { |
| 381 | repo: "tahinli/forge".into(), |
| 382 | count: 3, |
| 383 | url: "/tahinli/forge/security".into(), |
| 384 | }; |
| 385 | assert_eq!(advisories.message(Lang::En).body, "3 new security alerts"); |
| 386 | assert_eq!(advisories.message(Lang::Tr).body, "3 yeni güvenlik uyarısı"); |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn a_link_must_stay_on_this_origin() { |
| 391 | assert_eq!(safe_url("/tahinli/forge"), "/tahinli/forge"); |
| 392 | assert_eq!(safe_url("https://evil.example/x"), "/notifications"); |
| 393 | assert_eq!(safe_url("//evil.example/x"), "/notifications"); |
| 394 | assert_eq!(safe_url("/\\evil.example"), "/notifications"); |
| 395 | } |
| 396 | |
| 397 | #[test] |
| 398 | fn device_labels_name_the_browser_and_the_system() { |
| 399 | let chrome_android = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36"; |
| 400 | assert_eq!(agent_label(chrome_android), "Chrome on Android"); |
| 401 | 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"; |
| 402 | assert_eq!(agent_label(safari_iphone), "Safari on iPhone"); |
| 403 | assert_eq!(agent_label("curl/8.0"), "Browser on Unknown system"); |
| 404 | } |
| 405 | |
| 406 | #[test] |
| 407 | fn the_subject_is_https_or_the_fallback() { |
| 408 | assert_eq!( |
| 409 | subject("https://forge.example.test/"), |
| 410 | "https://forge.example.test" |
| 411 | ); |
| 412 | assert_eq!(subject("http://127.0.0.1:7660"), "https://localhost"); |
| 413 | } |
| 414 | |
| 415 | #[test] |
| 416 | fn push_live_reaches_a_listener_and_tolerates_none() { |
| 417 | let live = PushLive::default(); |
| 418 | live.publish("nobody"); |
| 419 | let mut rx = live.subscribe(); |
| 420 | live.publish("tahinli"); |
| 421 | assert_eq!(rx.try_recv().expect("event"), "tahinli"); |
| 422 | } |
| 423 | |
| 424 | |
| 425 | |
| 426 | async fn mock_push_service() -> std::net::SocketAddr { |
| 427 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 428 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 429 | .await |
| 430 | .expect("bind"); |
| 431 | let addr = listener.local_addr().expect("addr"); |
| 432 | tokio::spawn(async move { |
| 433 | loop { |
| 434 | let Ok((mut socket, _)) = listener.accept().await else { |
| 435 | return; |
| 436 | }; |
| 437 | tokio::spawn(async move { |
| 438 | let mut buf = Vec::new(); |
| 439 | let mut chunk = [0u8; 4096]; |
| 440 | let (head_end, length) = loop { |
| 441 | let n = socket.read(&mut chunk).await.unwrap_or(0); |
| 442 | if n == 0 { |
| 443 | return; |
| 444 | } |
| 445 | buf.extend_from_slice(&chunk[..n]); |
| 446 | if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { |
| 447 | let head = String::from_utf8_lossy(&buf[..end]).to_ascii_lowercase(); |
| 448 | let length = head |
| 449 | .lines() |
| 450 | .find_map(|l| l.strip_prefix("content-length:")) |
| 451 | .and_then(|v| v.trim().parse::<usize>().ok()) |
| 452 | .unwrap_or(0); |
| 453 | break (end + 4, length); |
| 454 | } |
| 455 | }; |
| 456 | while buf.len() < head_end + length { |
| 457 | let n = socket.read(&mut chunk).await.unwrap_or(0); |
| 458 | if n == 0 { |
| 459 | break; |
| 460 | } |
| 461 | buf.extend_from_slice(&chunk[..n]); |
| 462 | } |
| 463 | let request = String::from_utf8_lossy(&buf[..head_end]).into_owned(); |
| 464 | let status = if request.starts_with("POST /gone") { |
| 465 | "410 Gone" |
| 466 | } else { |
| 467 | "201 Created" |
| 468 | }; |
| 469 | let reply = format!( |
| 470 | "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" |
| 471 | ); |
| 472 | let _ = socket.write_all(reply.as_bytes()).await; |
| 473 | }); |
| 474 | } |
| 475 | }); |
| 476 | addr |
| 477 | } |
| 478 | |
| 479 | fn device(endpoint: String) -> PushSubscription { |
| 480 | let secret = web_push_native::p256::SecretKey::from_slice(&crypto::new_vapid_private()) |
| 481 | .expect("scalar"); |
| 482 | let point = secret.public_key().to_encoded_point(false); |
| 483 | PushSubscription { |
| 484 | id: endpoint.clone(), |
| 485 | user_id: String::new(), |
| 486 | endpoint, |
| 487 | p256dh: crypto::encode_b64(point.as_bytes()), |
| 488 | auth: crypto::encode_b64(&[9u8; 16]), |
| 489 | agent_label: "Chrome on Linux".into(), |
| 490 | created_at: String::new(), |
| 491 | last_success_at: None, |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | #[tokio::test] |
| 496 | async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() { |
| 497 | let dir = tempfile::tempdir().expect("tempdir"); |
| 498 | let state = crate::test_support::test_state(dir.path()).await; |
| 499 | let user = state |
| 500 | .store |
| 501 | .create_user("tahinli", None, "h", false) |
| 502 | .await |
| 503 | .expect("user"); |
| 504 | let addr = mock_push_service().await; |
| 505 | let gone = format!("http://{addr}/gone"); |
| 506 | let ok = format!("http://{addr}/ok"); |
| 507 | state |
| 508 | .store |
| 509 | .save_push_subscription( |
| 510 | &user.id, |
| 511 | &gone, |
| 512 | &device(gone.clone()).p256dh, |
| 513 | &device(gone.clone()).auth, |
| 514 | "Chrome on Linux", |
| 515 | ) |
| 516 | .await |
| 517 | .expect("save gone"); |
| 518 | state |
| 519 | .store |
| 520 | .save_push_subscription( |
| 521 | &user.id, |
| 522 | &ok, |
| 523 | &device(ok.clone()).p256dh, |
| 524 | &device(ok.clone()).auth, |
| 525 | "Chrome on Linux", |
| 526 | ) |
| 527 | .await |
| 528 | .expect("save ok"); |
| 529 | |
| 530 | let sent = deliver(&state, &user.id, &Alert::Test) |
| 531 | .await |
| 532 | .expect("deliver"); |
| 533 | assert_eq!(sent, 2); |
| 534 | let left = state |
| 535 | .store |
| 536 | .push_subscriptions(&user.id) |
| 537 | .await |
| 538 | .expect("list"); |
| 539 | assert_eq!(left.len(), 1, "the 410 device is forgotten"); |
| 540 | assert_eq!(left[0].endpoint, ok); |
| 541 | assert!( |
| 542 | left[0].last_success_at.is_some(), |
| 543 | "the delivered device is stamped" |
| 544 | ); |
| 545 | } |
| 546 | |
| 547 | #[tokio::test] |
| 548 | async fn the_payload_is_encrypted_for_the_device_and_the_status_is_read() { |
| 549 | let addr = mock_push_service().await; |
| 550 | let private = crypto::new_vapid_private(); |
| 551 | let keys = VapidKeys { |
| 552 | public: crypto::vapid_public_key(&private).expect("public"), |
| 553 | private, |
| 554 | }; |
| 555 | let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json"); |
| 556 | let ok = device(format!("http://{addr}/ok")); |
| 557 | assert_eq!( |
| 558 | send_one(&keys, "https://localhost", &ok, &payload).await, |
| 559 | Outcome::Delivered |
| 560 | ); |
| 561 | let gone = device(format!("http://{addr}/gone")); |
| 562 | assert_eq!( |
| 563 | send_one(&keys, "https://localhost", &gone, &payload).await, |
| 564 | Outcome::Gone |
| 565 | ); |
| 566 | } |
| 567 | } |