diff --git a/Cargo.lock b/Cargo.lock index d59a5a2..38ddeb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2173,7 +2173,6 @@ dependencies = [ name = "forge-web-app" version = "0.1.0" dependencies = [ - "aes-gcm 0.11.1", "async-compression", "base64 0.23.1", "bytes", @@ -2187,7 +2186,6 @@ dependencies = [ "futures-util", "grass", "hex", - "hkdf 0.13.0", "hmac 0.13.0", "http", "http-body", @@ -2197,8 +2195,6 @@ dependencies = [ "jiff 1.0.3", "lettre", "nix 0.31.4", - "p256", - "rand 0.10.4", "reqwest", "serde", "serde_json", @@ -2293,7 +2289,6 @@ dependencies = [ "jiff 1.0.3", "multer", "nix 0.31.4", - "p256", "reqwest", "scraper", "serde", diff --git a/Cargo.toml b/Cargo.toml index 5e08f6f..e875f55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,10 +76,6 @@ base64 = "0.23.1" getrandom = "0.4.3" rpassword = "7.5.5" chacha20poly1305 = "0.11.0" -# Web Push (forge-web): RFC 8291 encryption and RFC 8292 VAPID -p256 = { version = "0.14.0", features = ["ecdh", "ecdsa"] } -hkdf = "0.13.0" -aes-gcm = "0.11.1" # storage turso = { version = "0.9.0-pre.6", default-features = false, features = ["mimalloc"] } diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 2280dcc..c8885cd 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -48,7 +48,6 @@ pub mod transfers; pub mod ui_prefs; pub mod user_delete; pub mod user_prefs; -pub mod web_push; pub mod webhooks; pub mod wiki; diff --git a/crates/forge-core/src/store/web_push.rs b/crates/forge-core/src/store/web_push.rs deleted file mode 100644 index e38c6ad..0000000 --- a/crates/forge-core/src/store/web_push.rs +++ /dev/null @@ -1,186 +0,0 @@ -use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; -use crate::error::{Error, Result}; -use crate::time::now_stamp; - -pub const MAX_DEVICES: i64 = 20; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PushSubscription { - pub id: String, - pub user_id: String, - pub endpoint: String, - pub p256dh: String, - pub auth: String, - pub agent_label: String, - pub created_at: String, - pub last_success_at: Option, -} - -const COLS: &str = "id, user_id, endpoint, p256dh, auth, agent_label, created_at, last_success_at"; - -fn map_row(row: &turso::Row) -> Result { - Ok(PushSubscription { - id: col_text(row, 0)?, - user_id: col_text(row, 1)?, - endpoint: col_text(row, 2)?, - p256dh: col_text(row, 3)?, - auth: col_text(row, 4)?, - agent_label: col_text(row, 5)?, - created_at: col_text(row, 6)?, - last_success_at: col_opt_text(row, 7)?, - }) -} - -impl Store { - pub async fn web_push_keys(&self) -> Result> { - let conn = self.read_conn().await; - fetch_opt( - &conn, - "SELECT public_key, private_key FROM web_push_keys WHERE id = 1", - (), - |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), - ) - .await - } - - pub async fn save_web_push_keys( - &self, - public_key: &str, - sealed_private: &str, - ) -> Result<(String, String)> { - let conn = self.inner.conn.lock().await; - conn.execute( - "INSERT INTO web_push_keys (id, public_key, private_key, created_at) \ - VALUES (1, ?1, ?2, ?3) ON CONFLICT (id) DO NOTHING", - ( - public_key.to_string(), - sealed_private.to_string(), - now_stamp(), - ), - ) - .await - .map_err(db_err)?; - fetch_opt( - &conn, - "SELECT public_key, private_key FROM web_push_keys WHERE id = 1", - (), - |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), - ) - .await? - .ok_or_else(|| Error::Database("the VAPID key was not stored".into())) - } - - pub async fn push_subscriptions(&self, user_id: &str) -> Result> { - let conn = self.read_conn().await; - fetch_all( - &conn, - &format!( - "SELECT {COLS} FROM push_subscriptions WHERE user_id = ?1 ORDER BY created_at, id" - ), - (user_id.to_string(),), - map_row, - ) - .await - } - - pub async fn save_push_subscription( - &self, - user_id: &str, - endpoint: &str, - p256dh: &str, - auth: &str, - agent_label: &str, - ) -> Result { - let conn = self.inner.conn.lock().await; - let held = fetch_opt( - &conn, - "SELECT COUNT(*) FROM push_subscriptions WHERE user_id = ?1 AND endpoint != ?2", - (user_id.to_string(), endpoint.to_string()), - |row| crate::store::col_int(row, 0), - ) - .await? - .unwrap_or(0); - if held >= MAX_DEVICES { - return Err(Error::Invalid(format!( - "an account can enable push on at most {MAX_DEVICES} devices" - ))); - } - conn.execute( - "INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth, agent_label, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \ - ON CONFLICT (endpoint) DO UPDATE SET user_id = excluded.user_id, \ - p256dh = excluded.p256dh, auth = excluded.auth, \ - agent_label = excluded.agent_label, created_at = excluded.created_at", - ( - new_id(), - user_id.to_string(), - endpoint.to_string(), - p256dh.to_string(), - auth.to_string(), - agent_label.to_string(), - now_stamp(), - ), - ) - .await - .map_err(db_err)?; - fetch_opt( - &conn, - &format!("SELECT {COLS} FROM push_subscriptions WHERE endpoint = ?1"), - (endpoint.to_string(),), - map_row, - ) - .await? - .ok_or_else(|| Error::Database("the push subscription was not stored".into())) - } - - pub async fn delete_push_subscription(&self, user_id: &str, id: &str) -> Result { - let conn = self.inner.conn.lock().await; - let n = conn - .execute( - "DELETE FROM push_subscriptions WHERE id = ?1 AND user_id = ?2", - (id.to_string(), user_id.to_string()), - ) - .await - .map_err(db_err)?; - Ok(n > 0) - } - - pub async fn delete_push_subscription_by_endpoint( - &self, - user_id: &str, - endpoint: &str, - ) -> Result { - let conn = self.inner.conn.lock().await; - let n = conn - .execute( - "DELETE FROM push_subscriptions WHERE endpoint = ?1 AND user_id = ?2", - (endpoint.to_string(), user_id.to_string()), - ) - .await - .map_err(db_err)?; - Ok(n > 0) - } - - pub async fn delete_push_endpoint(&self, endpoint: &str) -> Result { - let conn = self.inner.conn.lock().await; - let n = conn - .execute( - "DELETE FROM push_subscriptions WHERE endpoint = ?1", - (endpoint.to_string(),), - ) - .await - .map_err(db_err)?; - Ok(n > 0) - } - - pub async fn mark_push_delivered(&self, id: &str) -> Result<()> { - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE push_subscriptions SET last_success_at = ?2 WHERE id = ?1", - (id.to_string(), now_stamp()), - ) - .await - .map_err(db_err)?; - Ok(()) - } -} diff --git a/crates/forge-web-account/src/lib.rs b/crates/forge-web-account/src/lib.rs index c3f38d8..cb23053 100644 --- a/crates/forge-web-account/src/lib.rs +++ b/crates/forge-web-account/src/lib.rs @@ -5,7 +5,7 @@ pub(crate) use forge_web_app::test_support; pub(crate) use forge_web_app::{ accent, alerts, api, audit, auth, backup, client_ip, custom_colour, exporter, i18n, importer, live, mail, mirrors, raw, render, self_update, signatures, state, theme, throttle, views, - web_push, webhooks, + webhooks, }; #[cfg(test)] pub(crate) use forge_web_app::{blobs, release_ops, replication}; diff --git a/crates/forge-web-account/src/pages/admin_server.rs b/crates/forge-web-account/src/pages/admin_server.rs index c4270d5..595cb4d 100644 --- a/crates/forge-web-account/src/pages/admin_server.rs +++ b/crates/forge-web-account/src/pages/admin_server.rs @@ -176,10 +176,7 @@ pub(crate) const PAGES: &[SrvPage] = &[ group: Group::Integrations, en: "Integrations", tr: "Entegrasyonlar", - keys: &[ - "webhooks.allow_http", - "webhooks.allowed_hosts", - ], + keys: &["webhooks.allow_http", "webhooks.allowed_hosts"], }, SrvPage { slug: "self-update", diff --git a/crates/forge-web-account/src/pages/assets.rs b/crates/forge-web-account/src/pages/assets.rs index 99162b8..ed2eefc 100644 --- a/crates/forge-web-account/src/pages/assets.rs +++ b/crates/forge-web-account/src/pages/assets.rs @@ -89,27 +89,6 @@ async fn custom_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> { )) } -const OFFLINE_HTML: &str = include_str!("../../../forge-web/assets/offline.html"); -const OFFLINE_JS: &str = include_str!("../../../forge-web/assets/offline.js"); - -#[route(GET "/assets/offline.html")] -async fn offline_html(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> { - Ok(respond( - "text/html; charset=utf-8", - "no-cache", - OFFLINE_HTML, - )) -} - -#[route(GET "/assets/offline.js")] -async fn offline_js(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> { - Ok(respond( - "text/javascript; charset=utf-8", - "no-cache", - OFFLINE_JS, - )) -} - #[route(GET "/-/alive")] async fn alive(cx: &Cx) -> Result { crate::pages::settings_live::alive_response(cx).await @@ -372,33 +351,6 @@ mod tests { ); } - #[tokio::test] - async fn offline_page_and_script_are_served_without_caching() { - let router: Router = Router::builder() - .discover() - .layer(CookieLayer::new()) - .build(); - for (uri, kind) in [ - ("/assets/offline.html", "text/html"), - ("/assets/offline.js", "text/javascript"), - ] { - let req = Request::builder() - .method("GET") - .uri(uri) - .body(Body::empty()) - .unwrap(); - let res = router.handle(req).await; - assert_eq!(res.status(), 200, "{uri}"); - assert!( - res.headers()["content-type"] - .to_str() - .unwrap() - .starts_with(kind) - ); - assert_eq!(res.headers()["cache-control"], "no-cache", "{uri}"); - } - } - #[tokio::test] async fn custom_css_keys_the_hue_choices_and_is_empty_without_one() { let router: Router = Router::builder() diff --git a/crates/forge-web-account/src/pages/settings_notifications.rs b/crates/forge-web-account/src/pages/settings_notifications.rs index 4d0772d..532360a 100644 --- a/crates/forge-web-account/src/pages/settings_notifications.rs +++ b/crates/forge-web-account/src/pages/settings_notifications.rs @@ -1,4 +1,3 @@ -use forge_core::store::web_push::PushSubscription; use forge_core::{Session, Store, User}; use serde::Deserialize; use topcoat::Result; @@ -9,18 +8,15 @@ use topcoat::router::{page, query_params, route}; use topcoat::view::{View, component, view}; use crate::auth::{require_csrf, require_user}; -use crate::i18n::push as push_text; use crate::i18n::s; use crate::i18n::{self, Key, Lang, t}; use crate::state::AppState; -use crate::views::parts::{SubPart, confirm_act, head}; -use crate::views::{csrf_field, rel_time, shell}; +use crate::views::parts::{SubPart, head}; +use crate::views::shell; #[query_params(error = bad_request)] struct NotificationsQuery { saved: Option, - test: Option, - removed: Option, } #[derive(Deserialize)] @@ -38,8 +34,6 @@ struct NotificationsPage { unverified_note: Option<&'static str>, server_note: Option<&'static str>, notice: Option, - devices: Vec, - can_test: bool, } #[component] @@ -51,8 +45,6 @@ async fn notifications_body(cx: &Cx, page: NotificationsPage) -> Result Result -
-

(push_text::t(lang, push_text::K::DeviceHeading))

- - - - - - - -
- - -
- csrf_field(token: csrf.as_str()) - -
-
- if !can_test { -

(push_text::t(lang, push_text::K::TestNoDevices))

- } -
-
-

(push_text::t(lang, push_text::K::DevicesHeading))

- if devices.is_empty() { -

(push_text::t(lang, push_text::K::DevicesEmpty))

- } - for device in devices.into_iter() { -
- (device.agent_label.as_str()) - (push_text::added_label(lang)) " " rel_time(lang: lang, stamp: device.created_at.as_str()) " · " - if let Some(stamp) = device.last_success_at.as_deref() { - (push_text::last_delivered_label(lang)) " " rel_time(lang: lang, stamp: stamp) - } else { - (push_text::t(lang, push_text::K::NeverDelivered)) - } - - confirm_act(lang: lang, label: push_text::t(lang, push_text::K::RemoveDevice), action: "/settings/notifications/push/remove", csrf: csrf.as_str(), fields: vec![("id".to_owned(), device.id.clone())]) -
- } -
}) } @@ -134,7 +86,6 @@ async fn page_for( ) -> forge_core::Result { let server_on = store.mail_settings().await?.enabled; let verified = store.email_is_verified(&viewer.0.id).await?; - let devices = store.push_subscriptions(&viewer.0.id).await?; Ok(NotificationsPage { lang, csrf: viewer.1.csrf_token.clone(), @@ -142,8 +93,6 @@ async fn page_for( unverified_note: (!verified).then(|| t(lang, Key::EmailNotifyUnverified)), server_note: (!server_on).then(|| t(lang, Key::EmailNotifyServerOff)), notice, - can_test: !devices.is_empty(), - devices, }) } @@ -153,19 +102,8 @@ async fn notifications_page(cx: &Cx) -> Result { let store: &Store = &context::(cx).store; let lang = i18n::lang(cx, Some(&viewer.0)); let query = query_params::(cx)?; - let notice = if query.saved.as_deref() == Some("1") { - Some(t(lang, Key::EmailNotifySaved).to_owned()) - } else if let Some(sent) = query.test.as_deref() { - match sent.parse::() { - Ok(0) => Some(push_text::t(lang, push_text::K::TestNoDevices).to_owned()), - Ok(n) => Some(push_text::test_sent(lang, n)), - Err(_) => None, - } - } else if query.removed.as_deref() == Some("1") { - Some(push_text::t(lang, push_text::K::DeviceRemoved).to_owned()) - } else { - None - }; + let notice = + (query.saved.as_deref() == Some("1")).then(|| t(lang, Key::EmailNotifySaved).to_owned()); let page = page_for(store, &viewer, lang, notice).await?; Ok(view! { shell(title: t(lang, Key::Notifications), viewer: Some(&viewer), notifications_body(page: page)) diff --git a/crates/forge-web-account/src/pages/settings_sessions.rs b/crates/forge-web-account/src/pages/settings_sessions.rs index da19999..ebee95e 100644 --- a/crates/forge-web-account/src/pages/settings_sessions.rs +++ b/crates/forge-web-account/src/pages/settings_sessions.rs @@ -10,7 +10,6 @@ use crate::audit::{self, Actor, Target}; use crate::auth::{CsrfForm, logout, require_csrf, require_user}; use crate::i18n::{Key, Lang, t}; use crate::state::AppState; -use crate::web_push::agent_label_in; #[derive(Deserialize)] struct RevokeForm { @@ -23,10 +22,55 @@ struct RevokeForm { pub(crate) fn session_label(lang: Lang, session: &Session) -> String { session.user_agent.as_deref().map_or_else( || t(lang, Key::UnknownBrowser).to_owned(), - |agent| agent_label_in(lang, agent), + |agent| agent_label(lang, agent), ) } +fn agent_label(lang: Lang, 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 if lang == Lang::Tr { + "bilinmeyen sistem" + } 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/") + || user_agent.contains("CriOS/") + { + "Chrome" + } else if user_agent.contains("Safari/") { + "Safari" + } else if lang == Lang::Tr { + "Tarayıcı" + } else { + "Browser" + }; + match lang { + Lang::Tr if os == "bilinmeyen sistem" => format!("{browser}, {os}"), + Lang::Tr => format!("{os} üzerinde {browser}"), + Lang::En => format!("{browser} on {os}"), + } +} + #[route(GET "/settings/sessions")] async fn sessions_page(cx: &Cx) -> Result { require_user(cx).await?; @@ -115,10 +159,24 @@ mod tests { use topcoat::router::request::Request; use topcoat::router::{Body, to_bytes}; + use super::agent_label; use crate::auth::SESSION_COOKIE; + use crate::i18n::Lang; const CSRF: &str = "sessions-test-csrf"; + #[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(Lang::En, 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(Lang::En, safari_iphone), "Safari on iPhone"); + assert_eq!( + agent_label(Lang::En, "curl/8.0"), + "Browser on Unknown system" + ); + } + #[tokio::test] async fn sessions_list_moves_to_the_security_sessions_topic() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/crates/forge-web-app/Cargo.toml b/crates/forge-web-app/Cargo.toml index c7baaba..db1aef7 100644 --- a/crates/forge-web-app/Cargo.toml +++ b/crates/forge-web-app/Cargo.toml @@ -31,7 +31,6 @@ base64.workspace = true tracing.workspace = true tokio-util = { workspace = true, features = ["io"] } http-body.workspace = true -rand.workspace = true hex.workspace = true nix = { workspace = true } sha2.workspace = true @@ -43,9 +42,6 @@ ulid.workspace = true lettre.workspace = true tar.workspace = true flate2.workspace = true -p256.workspace = true -hkdf.workspace = true -aes-gcm.workspace = true tempfile = { workspace = true, optional = true } diff --git a/crates/forge-web-app/src/alerts.rs b/crates/forge-web-app/src/alerts.rs index 4f8314f..8e0b43a 100644 --- a/crates/forge-web-app/src/alerts.rs +++ b/crates/forge-web-app/src/alerts.rs @@ -96,14 +96,6 @@ async fn deliver( continue; } publish_unread(state, &admin.id).await; - crate::web_push::queue( - state, - &admin.id, - crate::web_push::Alert::Admin { - subject: subject.to_owned(), - detail: detail.to_owned(), - }, - ); if !live.alerts.email { continue; } diff --git a/crates/forge-web-app/src/layers.rs b/crates/forge-web-app/src/layers.rs index 0ab8390..84564a4 100644 --- a/crates/forge-web-app/src/layers.rs +++ b/crates/forge-web-app/src/layers.rs @@ -457,9 +457,7 @@ mod repo_settings_write { fn written(cx: &Cx) -> Option<(String, String)> { let parts = post_segments(cx)?; match parts.as_slice() { - [owner, name, "settings", ..] => { - Some(((*owner).to_owned(), (*name).to_owned())) - } + [owner, name, "settings", ..] => Some(((*owner).to_owned(), (*name).to_owned())), _ => None, } } diff --git a/crates/forge-web-app/src/lib.rs b/crates/forge-web-app/src/lib.rs index 4b8b4f9..a363f63 100644 --- a/crates/forge-web-app/src/lib.rs +++ b/crates/forge-web-app/src/lib.rs @@ -47,7 +47,6 @@ pub mod state; #[cfg(any(test, feature = "test-support"))] pub mod test_support; pub mod views; -pub mod web_push; pub mod webhooks; pub mod build_info { diff --git a/crates/forge-web-app/src/notify.rs b/crates/forge-web-app/src/notify.rs index 7bb055e..cbbb5ff 100644 --- a/crates/forge-web-app/src/notify.rs +++ b/crates/forge-web-app/src/notify.rs @@ -6,7 +6,7 @@ use forge_core::store::orgs::OrgMemberRole; use forge_core::{Action, Issue, Repo, Result, User, authorize}; use http::HeaderMap; -use crate::i18n::{self, misc}; +use crate::i18n; use crate::mail::{ self, templates::{self, Verb, Why}, @@ -14,7 +14,6 @@ use crate::mail::{ use crate::notify_hub::publish_unread; use crate::render::markdown::mentioned_usernames; use crate::state::AppState; -use crate::web_push::{self, Alert}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Activity { @@ -289,18 +288,6 @@ async fn run( } } - let push = if recipients.is_empty() { - None - } else { - match push_alert(state, repo, issue, actor_id, activity).await { - Ok(alert) => Some(alert), - Err(e) => { - tracing::error!(error = %e, issue_id, "notify: push text failed"); - None - } - } - }; - if let Some(actor_id) = actor { match activity { Activity::Opened => { @@ -352,9 +339,6 @@ async fn run( { Ok(()) => { publish_unread(state, &user_id).await; - if let Some(alert) = &push { - web_push::queue(state, &user_id, alert.clone()); - } } Err(e) => tracing::error!(error = %e, user_id, issue_id, "notify: inbox write failed"), } @@ -428,56 +412,6 @@ async fn mail_plan( })) } -async fn push_alert( - state: &AppState, - repo: &Repo, - issue: &Issue, - actor_id: &str, - activity: &Activity, -) -> Result { - let actor = match actor_id { - "" => None, - id => state.store.user_by_id(id).await?.map(|u| u.username), - }; - let section = if state - .store - .pull_by_number(&repo.id, issue.number) - .await? - .is_some() - { - "pulls" - } else { - "issues" - }; - Ok(Alert::Activity { - repo: format!("{}/{}", repo.owner_name, repo.name), - number: issue.number, - title: issue.title.clone(), - verb: push_verb_for(activity), - actor, - url: format!( - "/{}/{}/{section}/{}", - repo.owner_name, repo.name, issue.number - ), - thread: issue.id.clone(), - }) -} - -fn push_verb_for(activity: &Activity) -> misc::K { - match activity { - Activity::Opened => misc::K::VerbOpened, - Activity::Comment => misc::K::VerbCommented, - Activity::Closed => misc::K::VerbClosed, - Activity::Reopened => misc::K::VerbReopened, - Activity::Merged => misc::K::VerbMerged, - Activity::Review => misc::K::VerbReviewed, - Activity::Assigned { .. } => misc::K::VerbAssigned, - Activity::ReviewRequested { .. } => misc::K::VerbReviewRequested, - Activity::Pushed => misc::K::VerbPushedTo, - Activity::Edited => misc::K::VerbMentionedYou, - } -} - fn verb_for(activity: &Activity) -> Verb { match activity { Activity::Opened => Verb::Opened, diff --git a/crates/forge-web-app/src/state.rs b/crates/forge-web-app/src/state.rs index c0032e8..dad6dfd 100644 --- a/crates/forge-web-app/src/state.rs +++ b/crates/forge-web-app/src/state.rs @@ -31,7 +31,6 @@ pub struct AppState { pub runner_logs: Arc, pub runner_metrics: Arc, pub live: Arc, - pub push_live: Arc, pub packages_live: Arc, } diff --git a/crates/forge-web-app/src/test_support/mod.rs b/crates/forge-web-app/src/test_support/mod.rs index 8922a97..c6d2ed7 100644 --- a/crates/forge-web-app/src/test_support/mod.rs +++ b/crates/forge-web-app/src/test_support/mod.rs @@ -86,7 +86,6 @@ pub async fn test_state(dir: &Path) -> AppState { runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()), runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()), live: Arc::new(crate::live::LiveHub::default()), - push_live: Arc::new(crate::web_push::PushLive::default()), packages_live: Arc::new(crate::packages_live::PackagesLive::default()), } } diff --git a/crates/forge-web-app/src/views/mod.rs b/crates/forge-web-app/src/views/mod.rs index 419c5b9..aae2f87 100644 --- a/crates/forge-web-app/src/views/mod.rs +++ b/crates/forge-web-app/src/views/mod.rs @@ -649,9 +649,6 @@ pub async fn shell( - - - (full_title) diff --git a/crates/forge-web-app/src/web_push/crypto.rs b/crates/forge-web-app/src/web_push/crypto.rs deleted file mode 100644 index 3712428..0000000 --- a/crates/forge-web-app/src/web_push/crypto.rs +++ /dev/null @@ -1,296 +0,0 @@ -use std::time::{SystemTime, UNIX_EPOCH}; - -use aes_gcm::Aes128Gcm; -use aes_gcm::KeyInit; -use aes_gcm::aead::Aead; -use base64::Engine; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use hkdf::Hkdf; -use p256::ecdsa::signature::Signer; -use p256::ecdsa::{Signature, SigningKey}; -use p256::elliptic_curve::sec1::ToSec1Point; -use sha2::Sha256; - -use forge_core::{Error, Result}; - -const POINT_LEN: usize = 65; -const RECORD_SIZE: u32 = 4096; -const VAPID_TTL: u64 = 12 * 60 * 60; -const PUSH_TTL: &str = "43200"; - -pub fn decode_b64(text: &str) -> Result> { - URL_SAFE_NO_PAD - .decode(text.trim_end_matches('=')) - .map_err(|_| Error::Invalid("not base64url".into())) -} - -pub fn encode_b64(bytes: &[u8]) -> String { - URL_SAFE_NO_PAD.encode(bytes) -} - -fn random_secret() -> p256::SecretKey { - loop { - let mut bytes = [0u8; 32]; - rand::fill(&mut bytes); - if let Ok(secret) = p256::SecretKey::from_slice(&bytes) { - return secret; - } - } -} - -pub fn new_vapid_private() -> [u8; 32] { - random_secret().to_bytes().into() -} - -pub fn vapid_key_pair(private: &[u8; 32]) -> Result { - SigningKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into())) -} - -pub fn vapid_public_key(private: &[u8; 32]) -> Result { - Ok(encode_b64( - vapid_key_pair(private)? - .verifying_key() - .to_sec1_point(false) - .as_bytes(), - )) -} - -fn encrypt_body( - ua_public: &p256::PublicKey, - auth: &[u8], - as_secret: &p256::SecretKey, - salt: &[u8; 16], - payload: &[u8], -) -> Result> { - let encryption_error = - |e: &dyn std::fmt::Display| Error::Crypto(format!("web push encryption failed: {e}")); - let as_public = as_secret.public_key().to_sec1_point(false); - let ua_point = ua_public.to_sec1_point(false); - let shared = p256::ecdh::diffie_hellman(as_secret.to_nonzero_scalar(), ua_public.as_affine()); - - let mut key_info = b"WebPush: info\0".to_vec(); - key_info.extend_from_slice(ua_point.as_bytes()); - key_info.extend_from_slice(as_public.as_bytes()); - let mut ikm = [0u8; 32]; - Hkdf::::new(Some(auth), &shared.raw_secret_bytes()[..]) - .expand(&key_info, &mut ikm) - .map_err(|e| encryption_error(&e))?; - - let mut cek = [0u8; 16]; - let mut nonce = [0u8; 12]; - let prk = Hkdf::::new(Some(salt), &ikm); - prk.expand(b"Content-Encoding: aes128gcm\0", &mut cek) - .map_err(|e| encryption_error(&e))?; - prk.expand(b"Content-Encoding: nonce\0", &mut nonce) - .map_err(|e| encryption_error(&e))?; - - if payload.len() + 1 + 16 > RECORD_SIZE as usize { - return Err(Error::Invalid("the push message is too large".into())); - } - let mut plaintext = payload.to_vec(); - plaintext.push(0x02); - let ciphertext = Aes128Gcm::new(&cek.into()) - .encrypt(&nonce.into(), plaintext.as_slice()) - .map_err(|e| encryption_error(&e))?; - - let mut body = Vec::with_capacity(salt.len() + 4 + 1 + POINT_LEN + ciphertext.len()); - body.extend_from_slice(salt); - body.extend_from_slice(&RECORD_SIZE.to_be_bytes()); - body.push(POINT_LEN as u8); - body.extend_from_slice(as_public.as_bytes()); - body.extend_from_slice(&ciphertext); - Ok(body) -} - -fn vapid_token(uri: &http::Uri, subject: &str, key_pair: &SigningKey) -> Result { - let bad_endpoint = || Error::Invalid("bad push endpoint".into()); - let scheme = uri.scheme_str().ok_or_else(bad_endpoint)?; - let authority = uri.authority().ok_or_else(bad_endpoint)?; - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|_| Error::Crypto("the system clock is before 1970".into()))? - .as_secs(); - let header = URL_SAFE_NO_PAD.encode(r#"{"typ":"JWT","alg":"ES256"}"#); - let claims = serde_json::json!({ - "aud": format!("{scheme}://{authority}"), - "exp": now + VAPID_TTL, - "sub": subject, - }); - let input = format!("{header}.{}", URL_SAFE_NO_PAD.encode(claims.to_string())); - let signature: Signature = key_pair - .try_sign(input.as_bytes()) - .map_err(|e| Error::Crypto(format!("VAPID signing failed: {e}")))?; - Ok(format!( - "{input}.{}", - URL_SAFE_NO_PAD.encode(signature.to_bytes()) - )) -} - -pub fn push_request( - endpoint: &str, - p256dh: &[u8], - auth: &[u8], - subject: &str, - key_pair: &SigningKey, - payload: Vec, -) -> Result>> { - if p256dh.len() != POINT_LEN { - return Err(Error::Invalid( - "the browser key is not a P-256 point".into(), - )); - } - let ua_public = p256::PublicKey::from_sec1_bytes(p256dh) - .map_err(|_| Error::Invalid("the browser key is not on the curve".into()))?; - if auth.len() != 16 { - return Err(Error::Invalid( - "the browser auth secret is not 16 bytes".into(), - )); - } - let uri: http::Uri = endpoint - .parse() - .map_err(|_| Error::Invalid("bad push endpoint".into()))?; - - let mut salt = [0u8; 16]; - rand::fill(&mut salt); - let body = encrypt_body(&ua_public, auth, &random_secret(), &salt, &payload)?; - - let token = vapid_token(&uri, subject, key_pair)?; - let public = key_pair.verifying_key().to_sec1_point(false); - http::Request::builder() - .method(http::Method::POST) - .uri(uri) - .header("content-encoding", "aes128gcm") - .header("content-type", "application/octet-stream") - .header("ttl", PUSH_TTL) - .header( - "authorization", - format!("vapid t={token}, k={}", encode_b64(public.as_bytes())), - ) - .body(body) - .map_err(|e| Error::Crypto(format!("web push request failed: {e}"))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_browser_key_that_is_not_a_point_is_refused() { - let key_pair = vapid_key_pair(&new_vapid_private()).expect("key"); - let auth = [7u8; 16]; - let not_a_point = [4u8; 65]; - assert!( - push_request( - "https://push.example.test/x", - ¬_a_point, - &auth, - "mailto:tahinli@example.test", - &key_pair, - b"hi".to_vec() - ) - .is_err() - ); - assert!( - push_request( - "https://push.example.test/x", - &[0x04; 10], - &auth, - "mailto:tahinli@example.test", - &key_pair, - b"hi".to_vec() - ) - .is_err() - ); - } - - #[test] - fn the_request_is_an_encrypted_vapid_post_to_the_endpoint() { - let private = new_vapid_private(); - let key_pair = vapid_key_pair(&private).expect("key"); - let browser = p256::SecretKey::from_slice(&new_vapid_private()).expect("scalar"); - let point = browser - .public_key() - .to_sec1_point(false) - .as_bytes() - .to_vec(); - let auth = [9u8; 16]; - let endpoint = "https://push.example.test/send/abc"; - let payload = br#"{"title":"tahinli/forge#1"}"#.to_vec(); - let request = push_request( - endpoint, - &point, - &auth, - "mailto:tahinli@example.test", - &key_pair, - payload.clone(), - ) - .expect("request"); - - assert_eq!(request.method(), http::Method::POST); - assert_eq!(request.uri().to_string(), endpoint); - assert_eq!(request.headers()["content-encoding"], "aes128gcm"); - assert_eq!(request.headers()["ttl"], "43200"); - - let auth_header = request.headers()["authorization"] - .to_str() - .expect("ascii") - .to_owned(); - assert!(auth_header.starts_with("vapid "), "{auth_header}"); - assert!(auth_header.contains(&format!( - "k={}", - vapid_public_key(&private).expect("public") - ))); - let token = auth_header - .split("t=") - .nth(1) - .and_then(|rest| rest.split(',').next()) - .expect("token"); - let claims = token.split('.').nth(1).expect("claims"); - let claims = decode_b64(claims).expect("base64"); - let claims: serde_json::Value = serde_json::from_slice(&claims).expect("json"); - assert_eq!(claims["aud"], "https://push.example.test"); - assert_eq!(claims["sub"], "mailto:tahinli@example.test"); - - let body = request.body(); - assert!(body.len() > payload.len()); - assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice())); - } - - #[test] - fn the_public_key_is_the_uncompressed_point() { - let public = vapid_public_key(&new_vapid_private()).expect("public"); - assert_eq!(decode_b64(&public).expect("b64").len(), POINT_LEN); - } - - #[test] - fn the_rfc_8291_appendix_a_vector_encrypts_to_the_published_body() { - let as_secret = p256::SecretKey::from_slice( - &decode_b64("yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw").expect("b64"), - ) - .expect("key"); - let ua_public = p256::PublicKey::from_sec1_bytes( - &decode_b64( - "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4", - ) - .expect("b64"), - ) - .expect("point"); - let auth = decode_b64("BTBZMqHH6r4Tts7J_aSIgg").expect("b64"); - let salt: [u8; 16] = decode_b64("DGv6ra1nlYgDCS1FRnbzlw") - .expect("b64") - .try_into() - .expect("16 bytes"); - let body = encrypt_body( - &ua_public, - &auth, - &as_secret, - &salt, - b"When I grow up, I want to be a watermelon", - ) - .expect("body"); - assert_eq!( - encode_b64(&body), - "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPTpK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN" - ); - } -} diff --git a/crates/forge-web-app/src/web_push/mod.rs b/crates/forge-web-app/src/web_push/mod.rs deleted file mode 100644 index 33410c9..0000000 --- a/crates/forge-web-app/src/web_push/mod.rs +++ /dev/null @@ -1,574 +0,0 @@ -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; -use crate::webhooks::client::{WebhookPolicy, policy_client, validate_url}; - -const SEND_TIMEOUT: Duration = Duration::from_secs(15); -const BODY_CHARS: usize = 140; - -pub struct PushLive { - tx: broadcast::Sender, -} - -impl Default for PushLive { - fn default() -> Self { - Self { - tx: broadcast::channel(64).0, - } - } -} - -impl PushLive { - pub fn publish(&self, user_id: &str) { - let _ = self.tx.send(user_id.to_owned()); - } - - pub fn subscribe(&self) -> broadcast::Receiver { - self.tx.subscribe() - } -} - -#[derive(Clone)] -pub enum Alert { - Activity { - repo: String, - number: i64, - title: String, - verb: misc::K, - actor: Option, - url: String, - thread: String, - }, - Admin { - subject: String, - detail: String, - }, - Test, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -pub struct Message { - pub title: String, - pub body: String, - pub url: String, - pub tag: String, -} - -impl Alert { - 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::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(), - }, - } - } -} - -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 -} - -fn safe_url(url: &str) -> String { - if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') { - url.to_owned() - } else { - "/notifications".to_owned() - } -} - -pub fn agent_label(user_agent: &str) -> String { - agent_label_in(Lang::En, user_agent) -} - -pub fn agent_label_in(lang: Lang, 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 if lang == Lang::Tr { - "bilinmeyen sistem" - } 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/") - || user_agent.contains("CriOS/") - { - "Chrome" - } else if user_agent.contains("Safari/") { - "Safari" - } else if lang == Lang::Tr { - "Tarayıcı" - } else { - "Browser" - }; - match lang { - Lang::Tr if os == "bilinmeyen sistem" => format!("{browser}, {os}"), - Lang::Tr => format!("{os} üzerinde {browser}"), - Lang::En => format!("{browser} on {os}"), - } -} - -fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> { - static CLIENT: OnceLock> = OnceLock::new(); - CLIENT - .get_or_init( - || match policy_client(policy.clone(), SEND_TIMEOUT, "forge-web-push") { - Ok(client) => Some(client), - Err(e) => { - tracing::error!(error = %e, "web push: the client does not build"); - None - } - }, - ) - .as_ref() -} - -pub struct VapidKeys { - pub private: [u8; 32], - pub public: String, -} - -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 }) -} - -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() - } -} - -#[derive(Debug, PartialEq, Eq)] -enum Outcome { - Delivered, - Gone, - Failed(String), -} - -async fn send_one( - client: &reqwest::Client, - policy: &WebhookPolicy, - keys: &VapidKeys, - subject: &str, - sub: &PushSubscription, - payload: &[u8], -) -> Outcome { - if let Err(e) = validate_url(&sub.endpoint, policy) { - return Outcome::Failed(e.to_string()); - } - 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()), - } -} - -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"); - } - }); -} - -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(()); - } - 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); - let policy = crate::mirrors::policy(state); - let Some(client) = client(&policy) else { - return Err(Error::Invalid("the web push client does not build".into())); - }; - for device in &devices { - match send_one(client, &policy, &keys, &subject, device, &payload).await { - Outcome::Delivered => { - if let Err(e) = state.store.mark_push_delivered(&device.id).await { - tracing::warn!( - error = %e, - device = %device.id, - "web push: the delivery stamp was not saved" - ); - } - state.push_live.publish(user_id); - } - Outcome::Gone => { - if let Err(e) = state.store.delete_push_endpoint(&device.endpoint).await { - tracing::warn!( - error = %e, - device = %device.id, - "web push: the gone device was not removed" - ); - } - state.push_live.publish(user_id); - } - Outcome::Failed(reason) => { - tracing::warn!(reason, device = %device.id, "web push: a device was not reached"); - } - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use p256::elliptic_curve::sec1::ToSec1Point; - - 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); - } - - #[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"); - } - - 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 = p256::SecretKey::from_slice(&crypto::new_vapid_private()).expect("scalar"); - let point = secret.public_key().to_sec1_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 mut state = crate::test_support::test_state(dir.path()).await; - let mut config = crate::test_support::test_config(dir.path()); - config.webhooks = forge_core::config::WebhookConfig { - allow_http: true, - allowed_hosts: vec!["127.0.0.1".into()], - }; - state.config = std::sync::Arc::new(config); - 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"); - let gone_device = device(gone.clone()); - let ok_device = device(ok.clone()); - state - .store - .save_push_subscription( - &user.id, - &gone, - &gone_device.p256dh, - &gone_device.auth, - "Chrome on Linux", - ) - .await - .expect("save gone"); - state - .store - .save_push_subscription( - &user.id, - &ok, - &ok_device.p256dh, - &ok_device.auth, - "Chrome on Linux", - ) - .await - .expect("save ok"); - - deliver(&state, &user.id, &Alert::Test) - .await - .expect("deliver"); - 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 open = WebhookPolicy::from_config(&forge_core::config::WebhookConfig { - allow_http: true, - allowed_hosts: vec!["127.0.0.1".into()], - }) - .expect("policy"); - let client = reqwest::Client::new(); - let send = |endpoint: String, policy: WebhookPolicy| { - let (client, keys, payload) = (&client, &keys, &payload); - async move { - send_one( - client, - &policy, - keys, - "https://localhost", - &device(endpoint), - payload, - ) - .await - } - }; - assert_eq!( - send(format!("http://{addr}/ok"), open.clone()).await, - Outcome::Delivered - ); - assert_eq!( - send(format!("http://{addr}/gone"), open).await, - Outcome::Gone - ); - let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default()) - .expect("policy"); - assert!(matches!( - send(format!("http://{addr}/ok"), strict).await, - Outcome::Failed(_) - )); - } -} diff --git a/crates/forge-web-base/src/i18n/mod.rs b/crates/forge-web-base/src/i18n/mod.rs index b75f240..8425a42 100644 --- a/crates/forge-web-base/src/i18n/mod.rs +++ b/crates/forge-web-base/src/i18n/mod.rs @@ -47,7 +47,6 @@ pub mod orgs; pub mod packages; pub mod pulls; pub mod pulls_review; -pub mod push; pub mod releases_ci; pub mod repo_admin; pub mod server_settings; diff --git a/crates/forge-web-base/src/i18n/push.rs b/crates/forge-web-base/src/i18n/push.rs deleted file mode 100644 index 72149f9..0000000 --- a/crates/forge-web-base/src/i18n/push.rs +++ /dev/null @@ -1,46 +0,0 @@ -use super::Lang; - -strings! { - K; - DeviceHeading => "Push notifications on this device", "Bu cihazda anlık bildirimler"; - DeviceUnsupported => "This browser does not support push notifications.", "Bu tarayıcı anlık bildirimleri desteklemiyor."; - DeviceNeedsHttps => "Push notifications need an HTTPS connection.", "Anlık bildirimler için HTTPS bağlantısı gerekir."; - DeviceIosHint => "On iPhone and iPad, add Forge to your Home Screen, open it from there, then turn push on.", "iPhone ve iPad'de önce Forge'u Ana Ekrana ekleyin, oradan açın, sonra anlık bildirimleri açın."; - DeviceDenied => "Notifications are blocked for this site. Allow them in the browser's site settings, then try again.", "Bu site için bildirimler engellenmiş. Tarayıcının site ayarlarından izin verip yeniden deneyin."; - DeviceOn => "Push is on for this device.", "Bu cihazda anlık bildirimler açık."; - DeviceOff => "Push is off for this device.", "Bu cihazda anlık bildirimler kapalı."; - DeviceError => "Push could not be turned on. Try again.", "Anlık bildirimler açılamadı. Yeniden deneyin."; - TurnOn => "Turn on for this device", "Bu cihazda aç"; - TurnOff => "Turn off for this device", "Bu cihazda kapat"; - SendTest => "Send test notification", "Test bildirimi gönder"; - TestNoDevices => "No device has push on yet. Turn it on first.", "Henüz anlık bildirimi açık bir cihaz yok. Önce bunu açın."; - DevicesHeading => "Devices", "Cihazlar"; - DevicesEmpty => "No device has push on.", "Anlık bildirimi açık cihaz yok."; - RemoveDevice => "Remove", "Kaldır"; - DeviceRemoved => "Device removed.", "Cihaz kaldırıldı."; - NeverDelivered => "Nothing delivered yet", "Henüz teslim edilmedi"; - TestTitle => "Forge test notification", "Forge test bildirimi"; - TestBody => "Push notifications work on this device.", "Anlık bildirimler bu cihazda çalışıyor."; -} - -pub fn test_sent(lang: Lang, devices: usize) -> String { - match lang { - Lang::En => format!("Test sent to {devices} device(s)."), - Lang::Tr => format!("Test {devices} cihaza gönderildi."), - } -} - -pub fn added_label(lang: Lang) -> &'static str { - match lang { - Lang::En => "Added", - Lang::Tr => "Eklendi", - } -} - -pub fn last_delivered_label(lang: Lang) -> &'static str { - match lang { - Lang::En => "Last delivered", - Lang::Tr => "Son teslim", - } -} - diff --git a/crates/forge-web-repo/Cargo.toml b/crates/forge-web-repo/Cargo.toml index 154fa57..3324c6a 100644 --- a/crates/forge-web-repo/Cargo.toml +++ b/crates/forge-web-repo/Cargo.toml @@ -34,7 +34,6 @@ multer.workspace = true ulid.workspace = true zip = { workspace = true } tar.workspace = true -p256.workspace = true [dev-dependencies] diff --git a/crates/forge-web-repo/src/lib.rs b/crates/forge-web-repo/src/lib.rs index 3f13899..f1d873a 100644 --- a/crates/forge-web-repo/src/lib.rs +++ b/crates/forge-web-repo/src/lib.rs @@ -4,8 +4,7 @@ pub(crate) use forge_web_app::test_support; pub(crate) use forge_web_app::{ api, audit, auth, automerge, blobs, ci, i18n, internal, layers, lfs, lfs_pointer, live, merge, - merge_queue, mirrors, notify, post_update, raw, render, signatures, state, templates, views, - web_push, webhooks, + merge_queue, notify, post_update, raw, render, signatures, state, templates, views, webhooks, }; pub mod pages; diff --git a/crates/forge-web-repo/src/pages/mod.rs b/crates/forge-web-repo/src/pages/mod.rs index 8b34ce2..be6d7da 100644 --- a/crates/forge-web-repo/src/pages/mod.rs +++ b/crates/forge-web-repo/src/pages/mod.rs @@ -39,7 +39,6 @@ pub mod pull_flow; pub mod pull_view; pub mod pulls_list; pub mod pulls_merge; -pub mod push; pub mod reactions; #[cfg(test)] mod reactions_tests; diff --git a/crates/forge-web-repo/src/pages/push.rs b/crates/forge-web-repo/src/pages/push.rs deleted file mode 100644 index cd5576b..0000000 --- a/crates/forge-web-repo/src/pages/push.rs +++ /dev/null @@ -1,533 +0,0 @@ -use futures_util::stream; -use http::header::USER_AGENT; -use serde::Deserialize; -use serde_json::json; -use tokio::sync::broadcast::error::RecvError; -use topcoat::Result; -use topcoat::context::{Cx, context}; -use topcoat::router::content::Form; -use topcoat::router::content::sse::Event; -use topcoat::router::error::{SeeOther, see_other}; -use topcoat::router::request::headers; -use topcoat::router::response::Response; -use topcoat::router::{Body, HeaderMap, StatusCode, header, route}; - -use crate::api::{self, json}; -use crate::auth::{CsrfForm, current_user, require_csrf, require_user}; -use crate::live::events_response; -use crate::state::AppState; -use crate::web_push::{self, Alert, crypto}; -use crate::webhooks::client::{WebhookPolicy, validate_url}; - -const MAX_ENDPOINT: usize = 2048; - -#[derive(Deserialize)] -struct SubscribeForm { - #[serde(default)] - csrf: String, - #[serde(default)] - endpoint: String, - #[serde(default)] - p256dh: String, - #[serde(default)] - auth: String, -} - -#[derive(Deserialize)] -struct EndpointForm { - #[serde(default)] - csrf: String, - #[serde(default)] - endpoint: String, -} - -#[derive(Deserialize)] -struct DeviceForm { - #[serde(default)] - csrf: String, - #[serde(default)] - id: String, -} - -fn check_endpoint(endpoint: &str, policy: &WebhookPolicy) -> forge_core::Result<()> { - if endpoint.len() > MAX_ENDPOINT { - return Err(forge_core::Error::Invalid( - "the push endpoint is too long".into(), - )); - } - let url = reqwest::Url::parse(endpoint) - .map_err(|_| forge_core::Error::Invalid("the push endpoint is not a URL".into()))?; - if url.scheme() != "https" || url.host_str().is_none() || url.port().is_some() { - return Err(forge_core::Error::Invalid( - "the push endpoint must be an https URL on the default port".into(), - )); - } - validate_url(endpoint, policy).map_err(|e| forge_core::Error::Invalid(e.to_string()))?; - Ok(()) -} - -fn check_keys(p256dh: &str, auth: &str) -> forge_core::Result<()> { - let point = crypto::decode_b64(p256dh)?; - if point.len() != 65 || point[0] != 0x04 || p256::PublicKey::from_sec1_bytes(&point).is_err() { - return Err(forge_core::Error::Invalid( - "the browser key is not a P-256 public key".into(), - )); - } - if crypto::decode_b64(auth)?.len() != 16 { - return Err(forge_core::Error::Invalid( - "the browser auth secret is not 16 bytes".into(), - )); - } - Ok(()) -} - -fn no_content() -> Response { - let mut res = Response::new(Body::empty()); - *res.status_mut() = StatusCode::NO_CONTENT; - res -} - -#[route(GET "/push/vapid-key")] -async fn vapid_key(cx: &Cx) -> Result { - require_user(cx).await?; - let state = context::(cx); - let keys = web_push::vapid_keys(state).await?; - Ok(json(StatusCode::OK, &json!({ "public_key": keys.public }))) -} - -#[route(POST "/push/subscribe")] -async fn subscribe(cx: &Cx, Form(form): Form) -> Result { - let (user, _) = require_csrf(cx, &form.csrf).await?; - let state = context::(cx); - let policy = crate::mirrors::policy(state); - if let Err(e) = - check_endpoint(&form.endpoint, &policy).and_then(|()| check_keys(&form.p256dh, &form.auth)) - { - return Ok(api::error(StatusCode::BAD_REQUEST, &e.to_string())); - } - let agent = headers(cx) - .get(USER_AGENT) - .and_then(|value| value.to_str().ok()) - .unwrap_or_default() - .to_owned(); - state - .store - .save_push_subscription( - &user.id, - &form.endpoint, - &form.p256dh, - &form.auth, - &web_push::agent_label(&agent), - ) - .await?; - state.push_live.publish(&user.id); - Ok(no_content()) -} - -#[route(POST "/push/unsubscribe")] -async fn unsubscribe(cx: &Cx, Form(form): Form) -> Result { - let (user, _) = require_csrf(cx, &form.csrf).await?; - let state = context::(cx); - if state - .store - .delete_push_subscription_by_endpoint(&user.id, &form.endpoint) - .await? - { - state.push_live.publish(&user.id); - } - Ok(no_content()) -} - -#[route(POST "/settings/notifications/push/remove")] -async fn remove_device(cx: &Cx, Form(form): Form) -> Result { - let (user, _) = require_csrf(cx, &form.csrf).await?; - let state = context::(cx); - if state - .store - .delete_push_subscription(&user.id, &form.id) - .await? - { - state.push_live.publish(&user.id); - } - Ok(see_other("/settings/notifications?removed=1")) -} - -#[route(POST "/settings/notifications/push/test")] -async fn send_test(cx: &Cx, Form(form): Form) -> Result { - let (user, _) = require_csrf(cx, &form.csrf).await?; - let state = context::(cx); - let devices = state.store.push_subscriptions(&user.id).await?.len(); - if devices > 0 { - web_push::queue(state, &user.id, Alert::Test); - } - Ok(see_other(format!("/settings/notifications?test={devices}"))) -} - -#[route(GET "/settings/notifications/push/events")] -async fn push_events(cx: &Cx) -> Result { - let Some((user, _)) = current_user(cx).await? else { - let mut res = Response::new(Body::empty()); - *res.status_mut() = StatusCode::UNAUTHORIZED; - return Ok(res); - }; - let state = context::(cx); - let rx = state.push_live.subscribe(); - let changes = stream::unfold((rx, user.id), |(mut rx, user_id)| async move { - loop { - match rx.recv().await { - Ok(changed) if changed == user_id => { - return Some((changed_event(), (rx, user_id))); - } - Ok(_) => continue, - Err(RecvError::Lagged(_)) => return Some((changed_event(), (rx, user_id))), - Err(RecvError::Closed) => return None, - } - } - }); - events_response(cx, changes) -} - -fn changed_event() -> Result { - Ok(Event::new().event("changed").data("1")) -} - -const SW_JS: &str = include_str!("../../../forge-web/assets/sw.js"); -const ICON_192: &[u8] = include_bytes!("../../../forge-web/assets/icons/icon-192.png"); -const ICON_512: &[u8] = include_bytes!("../../../forge-web/assets/icons/icon-512.png"); -const APPLE_TOUCH_ICON: &[u8] = - include_bytes!("../../../forge-web/assets/icons/apple-touch-icon.png"); - -const MANIFEST: &str = r##"{ - "name": "Forge", - "short_name": "Forge", - "start_url": "/", - "scope": "/", - "display": "standalone", - "background_color": "#f6f4ec", - "theme_color": "#5f7f67", - "icons": [ - { "src": "/assets/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, - { "src": "/assets/icons/icon-512.png", "sizes": "512x512", "type": "image/png" } - ] -} -"##; - -fn static_headers(content_type: &'static str, cache: &'static str) -> HeaderMap { - let mut headers = HeaderMap::new(); - headers.insert( - header::CONTENT_TYPE, - content_type.parse().expect("static header value"), - ); - headers.insert( - header::CACHE_CONTROL, - cache.parse().expect("static header value"), - ); - headers -} - -#[route(GET "/sw.js")] -async fn service_worker(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> { - let headers = static_headers("text/javascript; charset=utf-8", "no-cache"); - Ok((StatusCode::OK, headers, SW_JS)) -} - -#[route(GET "/manifest.webmanifest")] -async fn manifest(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> { - let headers = static_headers("application/manifest+json", "public, max-age=3600"); - Ok((StatusCode::OK, headers, MANIFEST)) -} - -#[route(GET "/assets/icons/icon-192.png")] -async fn icon_192(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> { - let headers = static_headers("image/png", "public, max-age=604800"); - Ok((StatusCode::OK, headers, ICON_192)) -} - -#[route(GET "/assets/icons/icon-512.png")] -async fn icon_512(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> { - let headers = static_headers("image/png", "public, max-age=604800"); - Ok((StatusCode::OK, headers, ICON_512)) -} - -#[route(GET "/assets/icons/apple-touch-icon.png")] -async fn apple_touch_icon(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> { - let headers = static_headers("image/png", "public, max-age=604800"); - Ok((StatusCode::OK, headers, APPLE_TOUCH_ICON)) -} - -#[cfg(test)] -mod tests { - use forge_core::Store; - use p256::elliptic_curve::sec1::ToSec1Point; - use topcoat::router::request::Request; - use topcoat::router::{Body, Router, to_bytes}; - - use crate::auth::SESSION_COOKIE; - use crate::test_support::{app_router, create_session, test_state}; - use crate::web_push::crypto; - - const TOKEN: &str = "push-session"; - const CSRF: &str = "push-csrf"; - const UA: &str = - "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36"; - - struct Fixture { - _dir: tempfile::TempDir, - router: Router, - store: Store, - user_id: String, - } - - async fn fixture() -> Fixture { - let dir = tempfile::tempdir().expect("tempdir"); - let data_dir = dir.path().join("data"); - std::fs::create_dir_all(&data_dir).expect("data dir"); - let state = test_state(&data_dir).await; - let user = state - .store - .create_user("tahinli", None, "h", false) - .await - .expect("user"); - create_session(&state.store, &user.id, TOKEN, CSRF).await; - Fixture { - _dir: dir, - router: app_router(state.clone()), - store: state.store.clone(), - user_id: user.id, - } - } - - fn browser_keys() -> (String, String) { - let secret = p256::SecretKey::from_slice(&crypto::new_vapid_private()).expect("scalar"); - let point = secret.public_key().to_sec1_point(false); - ( - crypto::encode_b64(point.as_bytes()), - crypto::encode_b64(&[7u8; 16]), - ) - } - - async fn send( - router: &Router, - method: &str, - uri: &str, - token: Option<&str>, - form: Option, - ) -> (u16, String) { - let mut builder = Request::builder() - .method(method) - .uri(uri) - .header("user-agent", UA); - if let Some(token) = token { - builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); - } - let body = match form { - Some(form) => { - builder = builder.header("content-type", "application/x-www-form-urlencoded"); - Body::from(form) - } - None => Body::empty(), - }; - let res = router.handle(builder.body(body).expect("request")).await; - let status = res.status().as_u16(); - let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); - (status, String::from_utf8_lossy(&bytes).into_owned()) - } - - fn subscribe_form(csrf: &str, endpoint: &str, p256dh: &str, auth: &str) -> String { - let enc = |s: &str| form_urlencoded::byte_serialize(s.as_bytes()).collect::(); - format!( - "csrf={}&endpoint={}&p256dh={}&auth={}", - enc(csrf), - enc(endpoint), - enc(p256dh), - enc(auth) - ) - } - - #[tokio::test] - async fn the_vapid_key_is_created_once_and_served() { - let fx = fixture().await; - let (status, first) = send(&fx.router, "GET", "/push/vapid-key", Some(TOKEN), None).await; - assert_eq!(status, 200, "{first}"); - let (_, second) = send(&fx.router, "GET", "/push/vapid-key", Some(TOKEN), None).await; - assert_eq!(first, second, "the same key on every request"); - let key: serde_json::Value = serde_json::from_str(&first).expect("json"); - let public = key["public_key"].as_str().expect("public key"); - assert_eq!(crypto::decode_b64(public).expect("b64").len(), 65); - - let (status, _) = send(&fx.router, "GET", "/push/vapid-key", None, None).await; - assert_ne!(status, 200, "case anonymous"); - } - - #[tokio::test] - async fn subscribe_then_unsubscribe_round_trip() { - let fx = fixture().await; - let (p256dh, auth) = browser_keys(); - let endpoint = "https://push.example.test/send/tahinli-1"; - let form = subscribe_form(CSRF, endpoint, &p256dh, &auth); - - let (status, body) = send( - &fx.router, - "POST", - "/push/subscribe", - Some(TOKEN), - Some(form), - ) - .await; - assert_eq!(status, 204, "{body}"); - let devices = fx - .store - .push_subscriptions(&fx.user_id) - .await - .expect("list"); - assert_eq!(devices.len(), 1); - assert_eq!(devices[0].endpoint, endpoint); - assert_eq!(devices[0].agent_label, "Chrome on Android"); - - let remove = format!("csrf={CSRF}&endpoint={endpoint}"); - let (status, body) = send( - &fx.router, - "POST", - "/push/unsubscribe", - Some(TOKEN), - Some(remove), - ) - .await; - assert_eq!(status, 204, "{body}"); - assert!( - fx.store - .push_subscriptions(&fx.user_id) - .await - .expect("list") - .is_empty() - ); - } - - #[tokio::test] - async fn refused_subscriptions_store_nothing() { - let fx = fixture().await; - let (p256dh, auth) = browser_keys(); - - let form = subscribe_form("wrong", "https://push.example.test/x", &p256dh, &auth); - let (status, _) = send( - &fx.router, - "POST", - "/push/subscribe", - Some(TOKEN), - Some(form), - ) - .await; - assert_eq!(status, 403, "case csrf"); - - let http_endpoint = subscribe_form(CSRF, "http://push.example.test/x", &p256dh, &auth); - let (status, _) = send( - &fx.router, - "POST", - "/push/subscribe", - Some(TOKEN), - Some(http_endpoint), - ) - .await; - assert_eq!(status, 400, "case http endpoint: an endpoint must be https"); - let short_auth = subscribe_form( - CSRF, - "https://push.example.test/x", - &p256dh, - &crypto::encode_b64(&[1u8; 8]), - ); - let (status, _) = send( - &fx.router, - "POST", - "/push/subscribe", - Some(TOKEN), - Some(short_auth), - ) - .await; - assert_eq!(status, 400, "case short auth: the auth secret is 16 bytes"); - let not_a_point = subscribe_form( - CSRF, - "https://push.example.test/x", - &crypto::encode_b64(&[4u8; 65]), - &auth, - ); - let (status, _) = send( - &fx.router, - "POST", - "/push/subscribe", - Some(TOKEN), - Some(not_a_point), - ) - .await; - assert_eq!(status, 400, "case not a point: the browser key is a point"); - assert!( - fx.store - .push_subscriptions(&fx.user_id) - .await - .expect("list") - .is_empty() - ); - } - - #[tokio::test] - async fn a_viewer_removes_only_their_own_device() { - let fx = fixture().await; - let other = fx - .store - .create_user("nina", None, "h", false) - .await - .expect("other user"); - let theirs = fx - .store - .save_push_subscription( - &other.id, - "https://push.example.test/nina", - "BA", - "AA", - "Chrome on Linux", - ) - .await - .expect("save"); - let form = format!("csrf={CSRF}&id={}", theirs.id); - let (status, _) = send( - &fx.router, - "POST", - "/settings/notifications/push/remove", - Some(TOKEN), - Some(form), - ) - .await; - assert_eq!(status, 303); - assert_eq!( - fx.store - .push_subscriptions(&other.id) - .await - .expect("list") - .len(), - 1 - ); - } - - #[tokio::test] - async fn worker_and_manifest_are_public_and_events_need_a_session() { - let fx = fixture().await; - let (status, _) = send( - &fx.router, - "GET", - "/settings/notifications/push/events", - None, - None, - ) - .await; - assert_eq!(status, 401, "case events without a session"); - - let (status, sw) = send(&fx.router, "GET", "/sw.js", None, None).await; - assert_eq!(status, 200); - assert!(sw.contains("notificationclick"), "{sw}"); - let (status, manifest) = send(&fx.router, "GET", "/manifest.webmanifest", None, None).await; - assert_eq!(status, 200); - assert!( - manifest.contains("\"display\": \"standalone\""), - "{manifest}" - ); - } -} diff --git a/crates/forge-web/assets/icons/apple-touch-icon.png b/crates/forge-web/assets/icons/apple-touch-icon.png deleted file mode 100644 index 870fd784806e8d31da441dcc779ddc7b7c58cbee..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 729 zcmeAS@N?(olHy`uVBq!ia0y~yVAuk}9Bd2>47O+4j2IZ07I?ZihE&{oduOkoR-j1R z!>#3e*o1}O_fBGpPEO=mXkd0LOJk?&;6*RHOaK7rx=oj$8d)h>I58&1}IrIlvn`nFB&J8$mXmz7I( zO)AB2SzZ3^6`fI}x206=uvc`(x##Mw7g8^rR&lSbD)m zaO}^$zAn-F$fKVJn>XMvvgQ7^$Hz-GOz-8%tN(m+^t3b2;Ro*>+CYwKVslhRHM!;f zHtzr1WySEj5$aq)6R;t0H=T{t+WfTUwPC_S+}=ag+VVn7VZ0bBUAB7;J$5}uWb?eta0DDdsbMI-H#^)O&7dQxN}C`@cFy`ci?%}#Nt=R sUsJxX-{D%*b$;fTR=+2YWN(WrXdiO@eCU4}0|Nttr>mdKI;Vst0GU)W(*OVf diff --git a/crates/forge-web/assets/icons/icon-192.png b/crates/forge-web/assets/icons/icon-192.png deleted file mode 100644 index 11457d577a3b9e07463d23fc2b659b295d318339..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 810 zcmeAS@N?(olHy`uVBq!ia0y~yU^oE69Bd2>3_*8t*clj@K6<)1hE&{oduOj#wxdYH z#hH!))s7#YHicSsH}onfvPhpcnPud!ku-5h*Vfi2PyU~IvvuBq>O1$}SQ_4$QK%IDcme|vwkH!gij(p5^wC-B-$bUwj0|Ab;nv;Px;O$XJBIF5b@o}7F>!t963 zJ+`ACge#>*4*Ngh=z6GL#B%h5uw_%yk4_m!!#^&43nc24+yi**Cn{^S%|9V1(%*Ta z>+<{)(O~fhTrJuYF3(>PeSqx%Tfr~kQtlfJHyHft7v(WZGe{qJ>3>BxfjNQM;RQoX zeMc4VCdLhn4h#wm9jeug$JiJc8yG-50R|2R76v8^uEYP>N|t)tJ9n2~KfYY;f3E)g z_b*>RzpZ~0tP`uQlh+r%OxPK>^kU8{#~V0}Zg}$g!qlC6_j$^n&lmqI>9#pDYF&7p zq#48=4h(XP=#ByDQ2B4Yg%^u6@p}RxyX#c*$AZU(3Csu~Y`#XwR*4))GCD8EEU2sY zIfwZH7Yh>uqr(A)JsiRxS#Pi%VEe!!(2y;_xZd83!R$bNs>AE$`*|C9H>?%N`1)l# z;|9iE)0o!I{RfgRvzjeNQsS+;+z^BDv$Jo@mygjI-fE${zx z?-`U9EPZ(YwQ2;*7NbAa^;{}UQ4;@}?bt*axAOl#SkErNXv+UT@SlJhQ78Znnta&GRqZ)f|uVv^LBPW?*1o@O1TaS?83{1ORyF5+?uv diff --git a/crates/forge-web/assets/icons/icon-512.png b/crates/forge-web/assets/icons/icon-512.png deleted file mode 100644 index c800844ea012ef2d3bbb476635d2828284d6c891..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2514 zcmb_eZBSHI7=F&Z%kB+#;WAi4XuCR1U{WkH!YCS-B*ke0YM3d(aBC790oNKO5L%8x zNE0opl1L1imgasq%aSHGxZ}zoARoKUy$h@;9c(fPu1eBfw+()?}pTmN`5Z6F29+%-5bh z`n6q2NX7eC6u<3A;_BjyGK6;)n^)~LEUvRFBO>~QXO0z;%uMR}*XdunNc6;>zi@u2 zd|~ZY(}(Z%&Zg0GhjyJE&0(b$ zi8`oFsG*aDTP1KDsj~lZamvKJ($%HTa`i6{QOw82o z?w_1ON^Z4$Js(Isy)-kGE0}fGre4la@w~BV)0?lWq`Ke6J#taF2Pt{5h7)Jl>Rig$ z8b3%_pITEfc&WGK*mi$=y40oq{}559B0PvC=Gzt@4Zo&JuStu*q?A61WinI;Q}}vYdtR$`RjTd3@&snMcN*()gC* zbS44kYWk|=7r`0=TH_2j*%%1NJ>BwCP)wlf88pgI!6CrBW%PD0|BzBpKpd=XjRoSe zB?UiS(cLF2lBX-G%o@sp-q=`V{6`y#TECkBxu;Vk1M8=29r@$CSlW~3jg(b|2aJHF zk~Pc%c6a-<+gKd~!~V7QW}g9u;qU?3?9boZvu>pm(W`a)8J-}@cc9^;FGi|ap-W7X>6giCw=!cV1aEM@U zVvo$LeO~aAe9sMqdo9r1rWBKb>h<6V)V`|{`BhqEg?0`DWh;0li-_(ycpF$5keG;0 z3H?9_je>Y)ieR9wBsvayZwQTp{#pb$g-CnT$C>J7@f#ywSoJpmta&Lbqv=J%&i??2 CavF*N diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 2381083..acac588 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -210,7 +210,6 @@ restoreJobs(jobs); restoreLogs(logs); syncLive(); - syncPush(); syncTick(); syncRel(); syncBannerExpiry(); @@ -810,7 +809,6 @@ closeLive(); }); } - if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); } // The form to send a queued change on: the form itself, or after a swap the one with the same action. function resend(form) { @@ -2611,143 +2609,6 @@ area.setSelectionRange(start + block.length, start + block.length); }); - // Web Push on this device (the notification settings card, [data-push]). The server renders every - // state message with a data-push-state attribute, hidden; this picks which ones show from the - // browser's own state: secure context, support, iOS install, permission and the subscription. The - // service worker (/sw.js, served at the origin root) is registered only when the user turns push on. - function pushSet(el, on) { - el.hidden = !on; - el.style.display = on ? '' : 'none'; - } - - function pushCard() { return document.querySelector('[data-push]'); } - - function pushShow(card, name, on) { - card.querySelectorAll('[data-push-state="' + name + '"]').forEach(function (el) { pushSet(el, on); }); - } - - function pushActions(card, enable, disable) { - card.querySelectorAll('[data-push-action="enable"]').forEach(function (el) { pushSet(el, enable); }); - card.querySelectorAll('[data-push-action="disable"]').forEach(function (el) { pushSet(el, disable); }); - } - - function pushBase64ToBytes(text) { - var pad = '==='.slice((text.length + 3) % 4); - var raw = atob((text + pad).replace(/-/g, '+').replace(/_/g, '/')); - var out = new Uint8Array(raw.length); - for (var i = 0; i < raw.length; i++) { out[i] = raw.charCodeAt(i); } - return out; - } - - function pushBytesToBase64(buffer) { - var bytes = new Uint8Array(buffer); - var text = ''; - for (var i = 0; i < bytes.length; i++) { text += String.fromCharCode(bytes[i]); } - return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); - } - - function pushCsrf(card) { - var input = card.querySelector('input[name="csrf"]'); - return input ? input.value : ''; - } - - function pushIos() { - var standalone = window.navigator.standalone === true || (window.matchMedia && matchMedia('(display-mode: standalone)').matches); - return /iPhone|iPad|iPod/.test(navigator.userAgent) && !standalone; - } - - function syncPush() { - var card = pushCard(); - if (!card) { return; } - ['unsupported', 'https', 'ios', 'denied', 'error', 'on', 'off'].forEach(function (name) { pushShow(card, name, false); }); - pushActions(card, false, false); - if (!window.isSecureContext) { pushShow(card, 'https', true); return; } - if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) { - pushShow(card, 'unsupported', true); - return; - } - if (pushIos()) { pushShow(card, 'ios', true); return; } - if (Notification.permission === 'denied') { pushShow(card, 'denied', true); return; } - navigator.serviceWorker.getRegistration('/sw.js').then(function (reg) { - return reg ? reg.pushManager.getSubscription() : null; - }).then(function (sub) { - if (!pushCard() || pushCard() !== card) { return; } - pushShow(card, sub ? 'on' : 'off', true); - pushActions(card, !sub, !!sub); - }).catch(function () { - pushShow(card, 'error', true); - }); - } - - // Turns push on for this browser: permission, service worker, subscription, then the server - // records the device. The device list refreshes through the page's event stream. - async function pushEnable(card) { - try { - if ((await Notification.requestPermission()) !== 'granted') { return syncPush(); } - var reg = await navigator.serviceWorker.register('/sw.js'); - await navigator.serviceWorker.ready; - var keyRes = await fetch('/push/vapid-key', { credentials: 'same-origin', headers: { accept: 'application/json' } }); - if (!keyRes.ok) { throw new Error('vapid key ' + keyRes.status); } - var key = (await keyRes.json()).public_key; - // A subscription made with another key cannot be reused: drop it on the server and in the browser. - var old = await reg.pushManager.getSubscription(); - if (old) { await pushPost(card, '/push/unsubscribe', { endpoint: old.endpoint }); await old.unsubscribe(); } - var sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: pushBase64ToBytes(key) }); - var saved = await pushPost(card, '/push/subscribe', { - endpoint: sub.endpoint, - p256dh: pushBytesToBase64(sub.getKey('p256dh')), - auth: pushBytesToBase64(sub.getKey('auth')) - }); - if (!saved.ok) { throw new Error('subscribe ' + saved.status); } - syncPush(); - } catch (e) { - syncPush(); - var error = card.querySelector('[data-push-state="error"]'); - if (error) { pushSet(error, true); } - } - } - - async function pushDisable(card) { - try { - var reg = await navigator.serviceWorker.getRegistration('/sw.js'); - var sub = reg ? await reg.pushManager.getSubscription() : null; - if (sub) { - await pushPost(card, '/push/unsubscribe', { endpoint: sub.endpoint }); - await sub.unsubscribe(); - } - } catch (e) { - // Nothing to undo in the browser; the page below shows the state as it is now. - } - syncPush(); - } - - function pushPost(card, url, fields) { - var body = new URLSearchParams(); - body.set('csrf', pushCsrf(card)); - Object.keys(fields).forEach(function (k) { body.set(k, fields[k]); }); - return fetch(url, { method: 'POST', body: body, credentials: 'same-origin' }); - } - - document.addEventListener('click', function (e) { - var button = e.target && e.target.closest ? e.target.closest('[data-push-action]') : null; - if (!button) { return; } - var card = pushCard(); - if (!card || !card.contains(button)) { return; } - e.preventDefault(); - if (button.getAttribute('data-push-action') === 'enable') { pushEnable(card); } - else { pushDisable(card); } - }); - - // The service worker asks an open tab to show a notification's link in place. - if ('serviceWorker' in navigator) { - navigator.serviceWorker.addEventListener('message', function (e) { - var data = e.data; - if (data && data.type === 'forge-navigate' && typeof data.url === 'string' && data.url.charAt(0) === '/' && data.url.charAt(1) !== '/') { - go(data.url); - } - }); - } - // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose @@ -3214,7 +3075,6 @@ syncLog(); followTail(); syncLive(); - syncPush(); syncTick(); syncRel(); syncBannerExpiry(); diff --git a/crates/forge-web/assets/offline.html b/crates/forge-web/assets/offline.html deleted file mode 100644 index e43bbf7..0000000 --- a/crates/forge-web/assets/offline.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - -Forge - - - - -
- - - - - -
- - diff --git a/crates/forge-web/assets/offline.js b/crates/forge-web/assets/offline.js deleted file mode 100644 index 81f523c..0000000 --- a/crates/forge-web/assets/offline.js +++ /dev/null @@ -1,28 +0,0 @@ -// Offline page (served by the service worker when a page load finds the server down). Shows the -// line in the browser's language, then reloads once the server answers again. Nothing else runs here. -(function () { - 'use strict'; - var want = /^tr\b/i.test(navigator.language || '') ? 'tr' : 'en'; - document.querySelectorAll('.link-offline [lang]').forEach(function (el) { - if (el.getAttribute('lang') !== want) { el.hidden = true; } - }); - - if (!window.EventSource) { return; } - // Opens the stream again after a drop. The browser retries by itself, except when a proxy answers - // with an error (EventSource then closes for good): that case is retried here, 1, 2, then 3 s. - function keepOpen(url, onOpen) { - var delay = 1000; - function connect() { - var es = new EventSource(url); - es.onopen = function () { delay = 1000; onOpen(); }; - es.onerror = function () { - if (es.readyState !== EventSource.CLOSED) { return; } - es.close(); - setTimeout(connect, delay); - delay = Math.min(delay + 1000, 3000); - }; - } - connect(); - } - keepOpen('/-/alive', function () { location.reload(); }); -})(); diff --git a/crates/forge-web/assets/sw.js b/crates/forge-web/assets/sw.js deleted file mode 100644 index 9dbcb14..0000000 --- a/crates/forge-web/assets/sw.js +++ /dev/null @@ -1,100 +0,0 @@ -// Forge service worker. Served at /sw.js, so its scope is the whole origin. It shows Web Push -// notifications while no tab is open and opens the link of a clicked one. No inline code. The only -// thing it caches is the offline page: app pages are always fetched fresh. A full page load that -// finds the server down (or a proxy answering 502, 503 or 504 while forge restarts) gets that page -// instead of the browser's error page. Everything else passes straight through to the network. - -// Bump the version when the offline page changes, so the new one is precached on install. -var OFFLINE_CACHE = 'forge-offline-v2'; -var OFFLINE_URL = '/assets/offline.html'; -// The offline page and the two files it loads. They are precached: while the server is down the -// browser could not fetch them for the offline page otherwise. -var OFFLINE_FILES = [OFFLINE_URL, '/assets/offline.js', '/assets/main.css']; -var RESTART_STATUS = [502, 503, 504]; - -self.addEventListener('install', function (event) { - event.waitUntil( - caches.open(OFFLINE_CACHE) - .then(function (cache) { return cache.addAll(OFFLINE_FILES.map(function (u) { return new Request(u, { cache: 'reload' }); })); }) - .catch(function () { /* the server is down: the page is fetched again on the next install */ }) - .then(function () { return self.skipWaiting(); }) - ); -}); - -self.addEventListener('activate', function (event) { - event.waitUntil((async function () { - var names = await caches.keys(); - await Promise.all(names.filter(function (n) { return n.indexOf('forge-offline-') === 0 && n !== OFFLINE_CACHE; }) - .map(function (n) { return caches.delete(n); })); - await self.clients.claim(); - })()); -}); - -// Navigations only, and only GET: the response is the network's, unless the network failed or the -// server is restarting. Subresources, the event stream and form posts are not touched, except the -// three offline-page files above (bare URLs, no query): network first, the precache when it fails. -self.addEventListener('fetch', function (event) { - var req = event.request; - var asset = new URL(req.url); - if (req.method === 'GET' && req.mode !== 'navigate' && asset.origin === self.location.origin && - asset.search === '' && OFFLINE_FILES.indexOf(asset.pathname) >= 0) { - event.respondWith((async function () { - var res = null; - try { res = await fetch(req); } catch (e) { res = null; } - if (res && RESTART_STATUS.indexOf(res.status) < 0) { return res; } - var cached = await caches.match(asset.pathname); - return cached || res || Response.error(); - })()); - return; - } - if (req.mode !== 'navigate' || req.method !== 'GET') { return; } - event.respondWith((async function () { - var res = null; - try { - res = await fetch(req); - } catch (e) { - res = null; - } - if (res && RESTART_STATUS.indexOf(res.status) < 0) { return res; } - var offline = await caches.match(OFFLINE_URL); - return offline || res || Response.error(); - })()); -}); - -self.addEventListener('push', function (event) { - var data = {}; - try { - data = event.data ? event.data.json() : {}; - } catch (e) { - data = {}; - } - var title = typeof data.title === 'string' && data.title ? data.title : 'Forge'; - var options = { - body: typeof data.body === 'string' ? data.body : '', - tag: typeof data.tag === 'string' ? data.tag : undefined, - icon: '/assets/icons/icon-192.png', - badge: '/assets/icons/icon-192.png', - data: { url: typeof data.url === 'string' ? data.url : '/notifications' } - }; - event.waitUntil(self.registration.showNotification(title, options)); -}); - -// Focuses an open Forge tab and asks it to soft-navigate to the link, or opens a new window. -self.addEventListener('notificationclick', function (event) { - event.notification.close(); - var raw = event.notification.data && event.notification.data.url; - var target = typeof raw === 'string' && raw.charAt(0) === '/' && raw.charAt(1) !== '/' ? raw : '/notifications'; - var url = new URL(target, self.location.origin).href; - event.waitUntil((async function () { - var windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); - for (var i = 0; i < windows.length; i++) { - var client = windows[i]; - if (new URL(client.url).origin === self.location.origin) { - await client.focus(); - client.postMessage({ type: 'forge-navigate', url: target }); - return; - } - } - await self.clients.openWindow(url); - })()); -}); diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 6cf74aa..019803a 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -126,7 +126,6 @@ pub async fn serve( runner_logs: Arc::new(forge_web_app::ci::runner_log::RunnerLogs::default()), runner_metrics: Arc::new(forge_web_app::ci::runner_metrics::RunnerMetrics::default()), live: Arc::new(forge_web_app::live::LiveHub::default()), - push_live: Arc::new(forge_web_app::web_push::PushLive::default()), packages_live: Arc::new(forge_web_app::packages_live::PackagesLive::default()), }; if let Err(e) = forge_web_app::signatures::rebuild_allowed_signers(&state).await { diff --git a/crates/forge-web/src/routes.snap b/crates/forge-web/src/routes.snap index 170b76d..6c0ee0a 100644 --- a/crates/forge-web/src/routes.snap +++ b/crates/forge-web/src/routes.snap @@ -285,13 +285,8 @@ route /assets/fonts/ibm-plex-mono-2.5.0-400.woff2 Only([GET]) route /assets/fonts/ibm-plex-mono-2.5.0-500.woff2 Only([GET]) route /assets/fonts/ibm-plex-mono-2.5.0-600.woff2 Only([GET]) route /assets/highlight.css Only([GET]) -route /assets/icons/apple-touch-icon.png Only([GET]) -route /assets/icons/icon-192.png Only([GET]) -route /assets/icons/icon-512.png Only([GET]) route /assets/main.css Only([GET]) route /assets/nav.js Only([GET]) -route /assets/offline.html Only([GET]) -route /assets/offline.js Only([GET]) route /attachments/{id}/{name} Only([GET]) route /avatars/{username} Only([GET]) route /explore/events Only([GET]) @@ -303,7 +298,6 @@ route /import/{job_id}/retry Only([POST]) route /login/passkey/begin Only([POST]) route /login/passkey/finish Only([POST]) route /logout Only([POST]) -route /manifest.webmanifest Only([GET]) route /needs-you/events Only([GET]) route /needs-you/runs/dismiss Only([POST]) route /notifications/admin/{admin_note}/open Only([GET]) @@ -335,9 +329,6 @@ route /org/{org}/teams/{team}/members/remove Only([POST]) route /org/{org}/teams/{team}/repos/add Only([POST]) route /org/{org}/teams/{team}/repos/remove Only([POST]) route /org/{org}/teams/{team}/update Only([POST]) -route /push/subscribe Only([POST]) -route /push/unsubscribe Only([POST]) -route /push/vapid-key Only([GET]) route /review-requests/events Only([GET]) route /settings/appearance Only([POST]) route /settings/events Only([GET]) @@ -348,9 +339,6 @@ route /settings/export/{export_id}/download Only([GET]) route /settings/gpg/delete Only([POST]) route /settings/keys/delete Only([POST]) route /settings/notifications Only([POST]) -route /settings/notifications/push/events Only([GET]) -route /settings/notifications/push/remove Only([POST]) -route /settings/notifications/push/test Only([POST]) route /settings/pins Only([GET]) route /settings/pins Only([POST]) route /settings/profile/avatar/delete Only([POST]) @@ -368,7 +356,6 @@ route /settings/tokens/delete Only([POST]) route /snippets/events Only([GET]) route /snippets/{id}/delete Only([POST]) route /snippets/{id}/events Only([GET]) -route /sw.js Only([GET]) route /theme/custom.css Only([GET]) route /users/{username}/events Only([GET]) route /v2/ Only([GET]) diff --git a/docs/architecture.md b/docs/architecture.md index 90f5f2f..0260330 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -296,8 +296,7 @@ The release list and release pages follow `RepoReleases` (`/{owner}/{repo}/relea A page survives a server restart without a reload by hand. Every page holds one stream to `GET /-/alive` (no login, no data). The stream sends `retry: 1000` first, and every event stream sent through `events_response` does the same, so the browser reconnects about once a second. When the stream fails, `nav.js` shows a bar ("Server restarting… your page is kept"). When it opens again, the bar goes and the page refreshes once (`refreshLive`). - A soft navigation that finds the server down (no answer, or a 502, 503 or 504 from the proxy) stays on the page and is made again when the server is back. A form post is never sent again: the form keeps its values and the bar asks the reader to submit it again. -- A full load while the server is down gets the offline page. `sw.js` (scope `/`) answers failed or 502/503/504 navigations with `/assets/offline.html`, precached on install with its script and stylesheet. The offline page reloads itself when `/-/alive` opens. The service worker caches nothing else: app pages and API responses always come from the network. -- EventSource closes for good when a proxy answers with an error, so `nav.js` and the offline page open the stream again themselves after 1, 2, then 3 seconds. +- EventSource closes for good when a proxy answers with an error, so `nav.js` opens the stream again themselves after 1, 2, then 3 seconds. ## 6. Authorization model diff --git a/docs/notifications.md b/docs/notifications.md index f5e856e..6d9818f 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -1,65 +1,4 @@ # Notifications Forge keeps an inbox of notifications for each user (the bell in the top bar). The same -notifications can also reach you by email, and by Web Push on your devices. - -## Web Push - -Web Push delivers a notification to a device even when no Forge tab is open. It works in -Chromium-based browsers, Firefox and Safari, on desktop and on Android. On iPhone and iPad it works -only for an app installed to the Home Screen. - -### Requirements - -- **HTTPS.** Browsers only offer push on a secure origin. Serve Forge over HTTPS (the usual - reverse-proxy setup). `localhost` also counts as secure for testing. -- **iOS and iPadOS.** Open Forge in Safari, use Share, then Add to Home Screen, and open Forge from - that icon. Then turn push on in the notification settings. Safari in a normal tab cannot receive - push. iOS 16.4 or later is needed. -- **Permission.** The browser asks for permission the first time you turn push on. If you refused, - allow notifications for the site in the browser's site settings and try again. - -### Turning it on - -1. Open **Settings, Notifications**. -2. Under **Push notifications on this device**, choose **Turn on for this device**, then allow - notifications when the browser asks. -3. Choose **Send test notification** to check that the device gets one. - -Each browser profile, and each installed app, is a separate device. The **Devices** list shows -every device with push on, when it was added and when it last received a notification. Remove a -device there to stop its notifications; **Turn off for this device** does the same for the device -you are using. - -### What is sent - -A notification carries a short title (for example `owner/repo#12`), a one-line body (the activity -and the start of the title, at most 140 characters) and the link it opens. Nothing else is sent: no -token, no email address and no body text. The push service sees that a message was delivered to -your device, as with any push service. - -Only notifications that reach your inbox are pushed. The same rules apply: you hear about activity -on threads you follow, when you are mentioned, assigned or asked to review, and so on. Watching a -repo or ignoring a thread changes what reaches your inbox, and so what is pushed. Site admin alerts -are pushed the same way. - -Notifications on a lock screen can show the title of a private repository. Turn push off for a -device you share. - -### Devices that stop working - -A push service answers `404` or `410` for a subscription that no longer exists, for example after -the browser was reset or the app was uninstalled. Forge removes such a device by itself. A device -that keeps failing is kept, so a temporary outage does not drop it. - -### Operator notes - -- Forge creates one VAPID key pair the first time push is used and stores it in the database. The - private key is sealed with the instance key (`data_dir/forge.key`). Keep both in your backups: a - restore that loses the VAPID key makes every device subscribe again. -- The VAPID contact is the `base_url` of the instance when it is an `https` URL. Behind plain HTTP - the contact falls back to `https://localhost`. -- Pushes go out from a background task and never delay the request that caused them. The server - makes outgoing requests to the push services, so it needs outbound HTTPS. -- Each account can turn push on for at most 20 devices. -- The service worker is served at `/sw.js`, the web app manifest at `/manifest.webmanifest`. +notifications can also reach you by email.