forge
Explore
Log in

Don't you dare go Hollow

🔥 remove: web push notifications (VAPID, push subscriptions, service worker, offline page, PWA manifest and icons); admin alerts go by mail

Browse files at this commit

a953f4729ac0180cff8faec4625ba6e9d69321ffAhmet Kaan GümüşParent: 1537db2
Cargo.lockmodified+0 -5
@@ -2173,7 +2173,6 @@ dependencies = [
21732173 name = "forge-web-app"
21742174 version = "0.1.0"
21752175 dependencies = [
2176- "aes-gcm 0.11.1",
21772176 "async-compression",
21782177 "base64 0.23.1",
21792178 "bytes",
@@ -2187,7 +2186,6 @@ dependencies = [
21872186 "futures-util",
21882187 "grass",
21892188 "hex",
2190- "hkdf 0.13.0",
21912189 "hmac 0.13.0",
21922190 "http",
21932191 "http-body",
@@ -2197,8 +2195,6 @@ dependencies = [
21972195 "jiff 1.0.3",
21982196 "lettre",
21992197 "nix 0.31.4",
2200- "p256",
2201- "rand 0.10.4",
22022198 "reqwest",
22032199 "serde",
22042200 "serde_json",
@@ -2293,7 +2289,6 @@ dependencies = [
22932289 "jiff 1.0.3",
22942290 "multer",
22952291 "nix 0.31.4",
2296- "p256",
22972292 "reqwest",
22982293 "scraper",
22992294 "serde",
Cargo.tomlmodified+0 -4
@@ -76,10 +76,6 @@ base64 = "0.23.1"
7676 getrandom = "0.4.3"
7777 rpassword = "7.5.5"
7878 chacha20poly1305 = "0.11.0"
79-# Web Push (forge-web): RFC 8291 encryption and RFC 8292 VAPID
80-p256 = { version = "0.14.0", features = ["ecdh", "ecdsa"] }
81-hkdf = "0.13.0"
82-aes-gcm = "0.11.1"
8379
8480 # storage
8581 turso = { version = "0.9.0-pre.6", default-features = false, features = ["mimalloc"] }
crates/forge-core/src/store/mod.rsmodified+0 -1
@@ -48,7 +48,6 @@ pub mod transfers;
4848 pub mod ui_prefs;
4949 pub mod user_delete;
5050 pub mod user_prefs;
51-pub mod web_push;
5251 pub mod webhooks;
5352 pub mod wiki;
5453
crates/forge-core/src/store/web_push.rsdeleted+0 -186
@@ -1,186 +0,0 @@
1-use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
2-use crate::error::{Error, Result};
3-use crate::time::now_stamp;
4-
5-pub const MAX_DEVICES: i64 = 20;
6-
7-#[derive(Debug, Clone, PartialEq, Eq)]
8-pub struct PushSubscription {
9- pub id: String,
10- pub user_id: String,
11- pub endpoint: String,
12- pub p256dh: String,
13- pub auth: String,
14- pub agent_label: String,
15- pub created_at: String,
16- pub last_success_at: Option<String>,
17-}
18-
19-const COLS: &str = "id, user_id, endpoint, p256dh, auth, agent_label, created_at, last_success_at";
20-
21-fn map_row(row: &turso::Row) -> Result<PushSubscription> {
22- Ok(PushSubscription {
23- id: col_text(row, 0)?,
24- user_id: col_text(row, 1)?,
25- endpoint: col_text(row, 2)?,
26- p256dh: col_text(row, 3)?,
27- auth: col_text(row, 4)?,
28- agent_label: col_text(row, 5)?,
29- created_at: col_text(row, 6)?,
30- last_success_at: col_opt_text(row, 7)?,
31- })
32-}
33-
34-impl Store {
35- pub async fn web_push_keys(&self) -> Result<Option<(String, String)>> {
36- let conn = self.read_conn().await;
37- fetch_opt(
38- &conn,
39- "SELECT public_key, private_key FROM web_push_keys WHERE id = 1",
40- (),
41- |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
42- )
43- .await
44- }
45-
46- pub async fn save_web_push_keys(
47- &self,
48- public_key: &str,
49- sealed_private: &str,
50- ) -> Result<(String, String)> {
51- let conn = self.inner.conn.lock().await;
52- conn.execute(
53- "INSERT INTO web_push_keys (id, public_key, private_key, created_at) \
54- VALUES (1, ?1, ?2, ?3) ON CONFLICT (id) DO NOTHING",
55- (
56- public_key.to_string(),
57- sealed_private.to_string(),
58- now_stamp(),
59- ),
60- )
61- .await
62- .map_err(db_err)?;
63- fetch_opt(
64- &conn,
65- "SELECT public_key, private_key FROM web_push_keys WHERE id = 1",
66- (),
67- |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
68- )
69- .await?
70- .ok_or_else(|| Error::Database("the VAPID key was not stored".into()))
71- }
72-
73- pub async fn push_subscriptions(&self, user_id: &str) -> Result<Vec<PushSubscription>> {
74- let conn = self.read_conn().await;
75- fetch_all(
76- &conn,
77- &format!(
78- "SELECT {COLS} FROM push_subscriptions WHERE user_id = ?1 ORDER BY created_at, id"
79- ),
80- (user_id.to_string(),),
81- map_row,
82- )
83- .await
84- }
85-
86- pub async fn save_push_subscription(
87- &self,
88- user_id: &str,
89- endpoint: &str,
90- p256dh: &str,
91- auth: &str,
92- agent_label: &str,
93- ) -> Result<PushSubscription> {
94- let conn = self.inner.conn.lock().await;
95- let held = fetch_opt(
96- &conn,
97- "SELECT COUNT(*) FROM push_subscriptions WHERE user_id = ?1 AND endpoint != ?2",
98- (user_id.to_string(), endpoint.to_string()),
99- |row| crate::store::col_int(row, 0),
100- )
101- .await?
102- .unwrap_or(0);
103- if held >= MAX_DEVICES {
104- return Err(Error::Invalid(format!(
105- "an account can enable push on at most {MAX_DEVICES} devices"
106- )));
107- }
108- conn.execute(
109- "INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth, agent_label, created_at) \
110- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \
111- ON CONFLICT (endpoint) DO UPDATE SET user_id = excluded.user_id, \
112- p256dh = excluded.p256dh, auth = excluded.auth, \
113- agent_label = excluded.agent_label, created_at = excluded.created_at",
114- (
115- new_id(),
116- user_id.to_string(),
117- endpoint.to_string(),
118- p256dh.to_string(),
119- auth.to_string(),
120- agent_label.to_string(),
121- now_stamp(),
122- ),
123- )
124- .await
125- .map_err(db_err)?;
126- fetch_opt(
127- &conn,
128- &format!("SELECT {COLS} FROM push_subscriptions WHERE endpoint = ?1"),
129- (endpoint.to_string(),),
130- map_row,
131- )
132- .await?
133- .ok_or_else(|| Error::Database("the push subscription was not stored".into()))
134- }
135-
136- pub async fn delete_push_subscription(&self, user_id: &str, id: &str) -> Result<bool> {
137- let conn = self.inner.conn.lock().await;
138- let n = conn
139- .execute(
140- "DELETE FROM push_subscriptions WHERE id = ?1 AND user_id = ?2",
141- (id.to_string(), user_id.to_string()),
142- )
143- .await
144- .map_err(db_err)?;
145- Ok(n > 0)
146- }
147-
148- pub async fn delete_push_subscription_by_endpoint(
149- &self,
150- user_id: &str,
151- endpoint: &str,
152- ) -> Result<bool> {
153- let conn = self.inner.conn.lock().await;
154- let n = conn
155- .execute(
156- "DELETE FROM push_subscriptions WHERE endpoint = ?1 AND user_id = ?2",
157- (endpoint.to_string(), user_id.to_string()),
158- )
159- .await
160- .map_err(db_err)?;
161- Ok(n > 0)
162- }
163-
164- pub async fn delete_push_endpoint(&self, endpoint: &str) -> Result<bool> {
165- let conn = self.inner.conn.lock().await;
166- let n = conn
167- .execute(
168- "DELETE FROM push_subscriptions WHERE endpoint = ?1",
169- (endpoint.to_string(),),
170- )
171- .await
172- .map_err(db_err)?;
173- Ok(n > 0)
174- }
175-
176- pub async fn mark_push_delivered(&self, id: &str) -> Result<()> {
177- let conn = self.inner.conn.lock().await;
178- conn.execute(
179- "UPDATE push_subscriptions SET last_success_at = ?2 WHERE id = ?1",
180- (id.to_string(), now_stamp()),
181- )
182- .await
183- .map_err(db_err)?;
184- Ok(())
185- }
186-}
crates/forge-web-account/src/lib.rsmodified+1 -1
@@ -5,7 +5,7 @@ pub(crate) use forge_web_app::test_support;
55 pub(crate) use forge_web_app::{
66 accent, alerts, api, audit, auth, backup, client_ip, custom_colour, exporter, i18n, importer,
77 live, mail, mirrors, raw, render, self_update, signatures, state, theme, throttle, views,
8- web_push, webhooks,
8+ webhooks,
99 };
1010 #[cfg(test)]
1111 pub(crate) use forge_web_app::{blobs, release_ops, replication};
crates/forge-web-account/src/pages/admin_server.rsmodified+1 -4
@@ -176,10 +176,7 @@ pub(crate) const PAGES: &[SrvPage] = &[
176176 group: Group::Integrations,
177177 en: "Integrations",
178178 tr: "Entegrasyonlar",
179- keys: &[
180- "webhooks.allow_http",
181- "webhooks.allowed_hosts",
182- ],
179+ keys: &["webhooks.allow_http", "webhooks.allowed_hosts"],
183180 },
184181 SrvPage {
185182 slug: "self-update",
crates/forge-web-account/src/pages/assets.rsmodified+0 -48
@@ -89,27 +89,6 @@ async fn custom_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> {
8989 ))
9090 }
9191
92-const OFFLINE_HTML: &str = include_str!("../../../forge-web/assets/offline.html");
93-const OFFLINE_JS: &str = include_str!("../../../forge-web/assets/offline.js");
94-
95-#[route(GET "/assets/offline.html")]
96-async fn offline_html(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
97- Ok(respond(
98- "text/html; charset=utf-8",
99- "no-cache",
100- OFFLINE_HTML,
101- ))
102-}
103-
104-#[route(GET "/assets/offline.js")]
105-async fn offline_js(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
106- Ok(respond(
107- "text/javascript; charset=utf-8",
108- "no-cache",
109- OFFLINE_JS,
110- ))
111-}
112-
11392 #[route(GET "/-/alive")]
11493 async fn alive(cx: &Cx) -> Result<Response> {
11594 crate::pages::settings_live::alive_response(cx).await
@@ -372,33 +351,6 @@ mod tests {
372351 );
373352 }
374353
375- #[tokio::test]
376- async fn offline_page_and_script_are_served_without_caching() {
377- let router: Router = Router::builder()
378- .discover()
379- .layer(CookieLayer::new())
380- .build();
381- for (uri, kind) in [
382- ("/assets/offline.html", "text/html"),
383- ("/assets/offline.js", "text/javascript"),
384- ] {
385- let req = Request::builder()
386- .method("GET")
387- .uri(uri)
388- .body(Body::empty())
389- .unwrap();
390- let res = router.handle(req).await;
391- assert_eq!(res.status(), 200, "{uri}");
392- assert!(
393- res.headers()["content-type"]
394- .to_str()
395- .unwrap()
396- .starts_with(kind)
397- );
398- assert_eq!(res.headers()["cache-control"], "no-cache", "{uri}");
399- }
400- }
401-
402354 #[tokio::test]
403355 async fn custom_css_keys_the_hue_choices_and_is_empty_without_one() {
404356 let router: Router = Router::builder()
crates/forge-web-account/src/pages/settings_notifications.rsmodified+4 -66
@@ -1,4 +1,3 @@
1-use forge_core::store::web_push::PushSubscription;
21 use forge_core::{Session, Store, User};
32 use serde::Deserialize;
43 use topcoat::Result;
@@ -9,18 +8,15 @@ use topcoat::router::{page, query_params, route};
98 use topcoat::view::{View, component, view};
109
1110 use crate::auth::{require_csrf, require_user};
12-use crate::i18n::push as push_text;
1311 use crate::i18n::s;
1412 use crate::i18n::{self, Key, Lang, t};
1513 use crate::state::AppState;
16-use crate::views::parts::{SubPart, confirm_act, head};
17-use crate::views::{csrf_field, rel_time, shell};
14+use crate::views::parts::{SubPart, head};
15+use crate::views::shell;
1816
1917 #[query_params(error = bad_request)]
2018 struct NotificationsQuery {
2119 saved: Option<String>,
22- test: Option<String>,
23- removed: Option<String>,
2420 }
2521
2622 #[derive(Deserialize)]
@@ -38,8 +34,6 @@ struct NotificationsPage {
3834 unverified_note: Option<&'static str>,
3935 server_note: Option<&'static str>,
4036 notice: Option<String>,
41- devices: Vec<PushSubscription>,
42- can_test: bool,
4337 }
4438
4539 #[component]
@@ -51,8 +45,6 @@ async fn notifications_body(cx: &Cx, page: NotificationsPage) -> Result<impl Vie
5145 unverified_note,
5246 server_note,
5347 notice,
54- devices,
55- can_test,
5648 } = page;
5749 let blocked = unverified_note.is_some() || server_note.is_some();
5850 Ok(view! {
@@ -82,46 +74,6 @@ async fn notifications_body(cx: &Cx, page: NotificationsPage) -> Result<impl Vie
8274 </div>
8375 </noscript>
8476 </section>
85- <section class="sec" id="device" data-push="true" data-live="/settings/notifications/push/events">
86- <h2>(push_text::t(lang, push_text::K::DeviceHeading))</h2>
87- <p class="state" data-push-state="on" hidden=(true)>(push_text::t(lang, push_text::K::DeviceOn))</p>
88- <p class="state" data-push-state="off" hidden=(true)>(push_text::t(lang, push_text::K::DeviceOff))</p>
89- <p class="hint" role="note" data-push-state="unsupported" hidden=(true)>(push_text::t(lang, push_text::K::DeviceUnsupported))</p>
90- <p class="hint" role="note" data-push-state="https" hidden=(true)>(push_text::t(lang, push_text::K::DeviceNeedsHttps))</p>
91- <p class="hint" role="note" data-push-state="ios" hidden=(true)>(push_text::t(lang, push_text::K::DeviceIosHint))</p>
92- <p class="hint" role="note" data-push-state="denied" hidden=(true)>(push_text::t(lang, push_text::K::DeviceDenied))</p>
93- <p class="hint warn" role="alert" data-push-state="error" hidden=(true)>(push_text::t(lang, push_text::K::DeviceError))</p>
94- <div class="acts">
95- <button type="button" class="act" data-push-action="enable" hidden=(true)>(push_text::t(lang, push_text::K::TurnOn))</button>
96- <button type="button" class="act quiet" data-push-action="disable" hidden=(true)>(push_text::t(lang, push_text::K::TurnOff))</button>
97- <form method="post" action="/settings/notifications/push/test">
98- csrf_field(token: csrf.as_str())
99- <button type="submit" class="act" data-push-test="true" disabled=(!can_test)>(push_text::t(lang, push_text::K::SendTest))</button>
100- </form>
101- </div>
102- if !can_test {
103- <p class="hint">(push_text::t(lang, push_text::K::TestNoDevices))</p>
104- }
105- </section>
106- <section class="sec" id="devices">
107- <h2>(push_text::t(lang, push_text::K::DevicesHeading))</h2>
108- if devices.is_empty() {
109- <p class="state">(push_text::t(lang, push_text::K::DevicesEmpty))</p>
110- }
111- for device in devices.into_iter() {
112- <div class="line">
113- <span class="name">(device.agent_label.as_str())</span>
114- <span class="val">(push_text::added_label(lang)) " " rel_time(lang: lang, stamp: device.created_at.as_str()) " · "
115- if let Some(stamp) = device.last_success_at.as_deref() {
116- (push_text::last_delivered_label(lang)) " " rel_time(lang: lang, stamp: stamp)
117- } else {
118- (push_text::t(lang, push_text::K::NeverDelivered))
119- }
120- </span>
121- 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())])
122- </div>
123- }
124- </section>
12577 </div>
12678 })
12779 }
@@ -134,7 +86,6 @@ async fn page_for(
13486 ) -> forge_core::Result<NotificationsPage> {
13587 let server_on = store.mail_settings().await?.enabled;
13688 let verified = store.email_is_verified(&viewer.0.id).await?;
137- let devices = store.push_subscriptions(&viewer.0.id).await?;
13889 Ok(NotificationsPage {
13990 lang,
14091 csrf: viewer.1.csrf_token.clone(),
@@ -142,8 +93,6 @@ async fn page_for(
14293 unverified_note: (!verified).then(|| t(lang, Key::EmailNotifyUnverified)),
14394 server_note: (!server_on).then(|| t(lang, Key::EmailNotifyServerOff)),
14495 notice,
145- can_test: !devices.is_empty(),
146- devices,
14796 })
14897 }
14998
@@ -153,19 +102,8 @@ async fn notifications_page(cx: &Cx) -> Result<impl View> {
153102 let store: &Store = &context::<AppState>(cx).store;
154103 let lang = i18n::lang(cx, Some(&viewer.0));
155104 let query = query_params::<NotificationsQuery>(cx)?;
156- let notice = if query.saved.as_deref() == Some("1") {
157- Some(t(lang, Key::EmailNotifySaved).to_owned())
158- } else if let Some(sent) = query.test.as_deref() {
159- match sent.parse::<usize>() {
160- Ok(0) => Some(push_text::t(lang, push_text::K::TestNoDevices).to_owned()),
161- Ok(n) => Some(push_text::test_sent(lang, n)),
162- Err(_) => None,
163- }
164- } else if query.removed.as_deref() == Some("1") {
165- Some(push_text::t(lang, push_text::K::DeviceRemoved).to_owned())
166- } else {
167- None
168- };
105+ let notice =
106+ (query.saved.as_deref() == Some("1")).then(|| t(lang, Key::EmailNotifySaved).to_owned());
169107 let page = page_for(store, &viewer, lang, notice).await?;
170108 Ok(view! {
171109 shell(title: t(lang, Key::Notifications), viewer: Some(&viewer), notifications_body(page: page))
crates/forge-web-account/src/pages/settings_sessions.rsmodified+60 -2
@@ -10,7 +10,6 @@ use crate::audit::{self, Actor, Target};
1010 use crate::auth::{CsrfForm, logout, require_csrf, require_user};
1111 use crate::i18n::{Key, Lang, t};
1212 use crate::state::AppState;
13-use crate::web_push::agent_label_in;
1413
1514 #[derive(Deserialize)]
1615 struct RevokeForm {
@@ -23,10 +22,55 @@ struct RevokeForm {
2322 pub(crate) fn session_label(lang: Lang, session: &Session) -> String {
2423 session.user_agent.as_deref().map_or_else(
2524 || t(lang, Key::UnknownBrowser).to_owned(),
26- |agent| agent_label_in(lang, agent),
25+ |agent| agent_label(lang, agent),
2726 )
2827 }
2928
29+fn agent_label(lang: Lang, user_agent: &str) -> String {
30+ let os = if user_agent.contains("iPhone") {
31+ "iPhone"
32+ } else if user_agent.contains("iPad") {
33+ "iPad"
34+ } else if user_agent.contains("Android") {
35+ "Android"
36+ } else if user_agent.contains("Windows") {
37+ "Windows"
38+ } else if user_agent.contains("Macintosh") {
39+ "Mac"
40+ } else if user_agent.contains("CrOS") {
41+ "ChromeOS"
42+ } else if user_agent.contains("Linux") {
43+ "Linux"
44+ } else if lang == Lang::Tr {
45+ "bilinmeyen sistem"
46+ } else {
47+ "Unknown system"
48+ };
49+ let browser = if user_agent.contains("Edg/") {
50+ "Edge"
51+ } else if user_agent.contains("OPR/") {
52+ "Opera"
53+ } else if user_agent.contains("Firefox/") {
54+ "Firefox"
55+ } else if user_agent.contains("Chrome/")
56+ || user_agent.contains("Chromium/")
57+ || user_agent.contains("CriOS/")
58+ {
59+ "Chrome"
60+ } else if user_agent.contains("Safari/") {
61+ "Safari"
62+ } else if lang == Lang::Tr {
63+ "Tarayıcı"
64+ } else {
65+ "Browser"
66+ };
67+ match lang {
68+ Lang::Tr if os == "bilinmeyen sistem" => format!("{browser}, {os}"),
69+ Lang::Tr => format!("{os} üzerinde {browser}"),
70+ Lang::En => format!("{browser} on {os}"),
71+ }
72+}
73+
3074 #[route(GET "/settings/sessions")]
3175 async fn sessions_page(cx: &Cx) -> Result<SeeOther> {
3276 require_user(cx).await?;
@@ -115,10 +159,24 @@ mod tests {
115159 use topcoat::router::request::Request;
116160 use topcoat::router::{Body, to_bytes};
117161
162+ use super::agent_label;
118163 use crate::auth::SESSION_COOKIE;
164+ use crate::i18n::Lang;
119165
120166 const CSRF: &str = "sessions-test-csrf";
121167
168+ #[test]
169+ fn device_labels_name_the_browser_and_the_system() {
170+ let chrome_android = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36";
171+ assert_eq!(agent_label(Lang::En, chrome_android), "Chrome on Android");
172+ 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";
173+ assert_eq!(agent_label(Lang::En, safari_iphone), "Safari on iPhone");
174+ assert_eq!(
175+ agent_label(Lang::En, "curl/8.0"),
176+ "Browser on Unknown system"
177+ );
178+ }
179+
122180 #[tokio::test]
123181 async fn sessions_list_moves_to_the_security_sessions_topic() {
124182 let dir = tempfile::tempdir().expect("tempdir");
crates/forge-web-app/Cargo.tomlmodified+0 -4
@@ -31,7 +31,6 @@ base64.workspace = true
3131 tracing.workspace = true
3232 tokio-util = { workspace = true, features = ["io"] }
3333 http-body.workspace = true
34-rand.workspace = true
3534 hex.workspace = true
3635 nix = { workspace = true }
3736 sha2.workspace = true
@@ -43,9 +42,6 @@ ulid.workspace = true
4342 lettre.workspace = true
4443 tar.workspace = true
4544 flate2.workspace = true
46-p256.workspace = true
47-hkdf.workspace = true
48-aes-gcm.workspace = true
4945
5046 tempfile = { workspace = true, optional = true }
5147
crates/forge-web-app/src/alerts.rsmodified+0 -8
@@ -96,14 +96,6 @@ async fn deliver(
9696 continue;
9797 }
9898 publish_unread(state, &admin.id).await;
99- crate::web_push::queue(
100- state,
101- &admin.id,
102- crate::web_push::Alert::Admin {
103- subject: subject.to_owned(),
104- detail: detail.to_owned(),
105- },
106- );
10799 if !live.alerts.email {
108100 continue;
109101 }
crates/forge-web-app/src/layers.rsmodified+1 -3
@@ -457,9 +457,7 @@ mod repo_settings_write {
457457 fn written(cx: &Cx) -> Option<(String, String)> {
458458 let parts = post_segments(cx)?;
459459 match parts.as_slice() {
460- [owner, name, "settings", ..] => {
461- Some(((*owner).to_owned(), (*name).to_owned()))
462- }
460+ [owner, name, "settings", ..] => Some(((*owner).to_owned(), (*name).to_owned())),
463461 _ => None,
464462 }
465463 }
crates/forge-web-app/src/lib.rsmodified+0 -1
@@ -47,7 +47,6 @@ pub mod state;
4747 #[cfg(any(test, feature = "test-support"))]
4848 pub mod test_support;
4949 pub mod views;
50-pub mod web_push;
5150 pub mod webhooks;
5251
5352 pub mod build_info {
crates/forge-web-app/src/notify.rsmodified+1 -67
@@ -6,7 +6,7 @@ use forge_core::store::orgs::OrgMemberRole;
66 use forge_core::{Action, Issue, Repo, Result, User, authorize};
77 use http::HeaderMap;
88
9-use crate::i18n::{self, misc};
9+use crate::i18n;
1010 use crate::mail::{
1111 self,
1212 templates::{self, Verb, Why},
@@ -14,7 +14,6 @@ use crate::mail::{
1414 use crate::notify_hub::publish_unread;
1515 use crate::render::markdown::mentioned_usernames;
1616 use crate::state::AppState;
17-use crate::web_push::{self, Alert};
1817
1918 #[derive(Debug, Clone, PartialEq, Eq)]
2019 pub enum Activity {
@@ -289,18 +288,6 @@ async fn run(
289288 }
290289 }
291290
292- let push = if recipients.is_empty() {
293- None
294- } else {
295- match push_alert(state, repo, issue, actor_id, activity).await {
296- Ok(alert) => Some(alert),
297- Err(e) => {
298- tracing::error!(error = %e, issue_id, "notify: push text failed");
299- None
300- }
301- }
302- };
303-
304291 if let Some(actor_id) = actor {
305292 match activity {
306293 Activity::Opened => {
@@ -352,9 +339,6 @@ async fn run(
352339 {
353340 Ok(()) => {
354341 publish_unread(state, &user_id).await;
355- if let Some(alert) = &push {
356- web_push::queue(state, &user_id, alert.clone());
357- }
358342 }
359343 Err(e) => tracing::error!(error = %e, user_id, issue_id, "notify: inbox write failed"),
360344 }
@@ -428,56 +412,6 @@ async fn mail_plan(
428412 }))
429413 }
430414
431-async fn push_alert(
432- state: &AppState,
433- repo: &Repo,
434- issue: &Issue,
435- actor_id: &str,
436- activity: &Activity,
437-) -> Result<Alert> {
438- let actor = match actor_id {
439- "" => None,
440- id => state.store.user_by_id(id).await?.map(|u| u.username),
441- };
442- let section = if state
443- .store
444- .pull_by_number(&repo.id, issue.number)
445- .await?
446- .is_some()
447- {
448- "pulls"
449- } else {
450- "issues"
451- };
452- Ok(Alert::Activity {
453- repo: format!("{}/{}", repo.owner_name, repo.name),
454- number: issue.number,
455- title: issue.title.clone(),
456- verb: push_verb_for(activity),
457- actor,
458- url: format!(
459- "/{}/{}/{section}/{}",
460- repo.owner_name, repo.name, issue.number
461- ),
462- thread: issue.id.clone(),
463- })
464-}
465-
466-fn push_verb_for(activity: &Activity) -> misc::K {
467- match activity {
468- Activity::Opened => misc::K::VerbOpened,
469- Activity::Comment => misc::K::VerbCommented,
470- Activity::Closed => misc::K::VerbClosed,
471- Activity::Reopened => misc::K::VerbReopened,
472- Activity::Merged => misc::K::VerbMerged,
473- Activity::Review => misc::K::VerbReviewed,
474- Activity::Assigned { .. } => misc::K::VerbAssigned,
475- Activity::ReviewRequested { .. } => misc::K::VerbReviewRequested,
476- Activity::Pushed => misc::K::VerbPushedTo,
477- Activity::Edited => misc::K::VerbMentionedYou,
478- }
479-}
480-
481415 fn verb_for(activity: &Activity) -> Verb {
482416 match activity {
483417 Activity::Opened => Verb::Opened,
crates/forge-web-app/src/state.rsmodified+0 -1
@@ -31,7 +31,6 @@ pub struct AppState {
3131 pub runner_logs: Arc<crate::ci::runner_log::RunnerLogs>,
3232 pub runner_metrics: Arc<crate::ci::runner_metrics::RunnerMetrics>,
3333 pub live: Arc<crate::live::LiveHub>,
34- pub push_live: Arc<crate::web_push::PushLive>,
3534 pub packages_live: Arc<crate::packages_live::PackagesLive>,
3635 }
3736
crates/forge-web-app/src/test_support/mod.rsmodified+0 -1
@@ -86,7 +86,6 @@ pub async fn test_state(dir: &Path) -> AppState {
8686 runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()),
8787 runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()),
8888 live: Arc::new(crate::live::LiveHub::default()),
89- push_live: Arc::new(crate::web_push::PushLive::default()),
9089 packages_live: Arc::new(crate::packages_live::PackagesLive::default()),
9190 }
9291 }
crates/forge-web-app/src/views/mod.rsmodified+0 -3
@@ -649,9 +649,6 @@ pub async fn shell(
649649 <meta name="viewport" content="width=device-width, initial-scale=1">
650650 <meta name="referrer" content="same-origin">
651651 <meta name="theme-color" content="#b44d1a">
652- <meta name="apple-mobile-web-app-capable" content="yes">
653- <link rel="manifest" href="/manifest.webmanifest">
654- <link rel="apple-touch-icon" href="/assets/icons/apple-touch-icon.png">
655652 <title>(full_title)</title>
656653 <link rel="preload" as="font" type="font/woff2" crossorigin="anonymous" href=(FIGTREE_PRELOAD_HREF)>
657654 <link rel="stylesheet" href=(STYLESHEET_HREF)>
crates/forge-web-app/src/web_push/crypto.rsdeleted+0 -296
@@ -1,296 +0,0 @@
1-use std::time::{SystemTime, UNIX_EPOCH};
2-
3-use aes_gcm::Aes128Gcm;
4-use aes_gcm::KeyInit;
5-use aes_gcm::aead::Aead;
6-use base64::Engine;
7-use base64::engine::general_purpose::URL_SAFE_NO_PAD;
8-use hkdf::Hkdf;
9-use p256::ecdsa::signature::Signer;
10-use p256::ecdsa::{Signature, SigningKey};
11-use p256::elliptic_curve::sec1::ToSec1Point;
12-use sha2::Sha256;
13-
14-use forge_core::{Error, Result};
15-
16-const POINT_LEN: usize = 65;
17-const RECORD_SIZE: u32 = 4096;
18-const VAPID_TTL: u64 = 12 * 60 * 60;
19-const PUSH_TTL: &str = "43200";
20-
21-pub fn decode_b64(text: &str) -> Result<Vec<u8>> {
22- URL_SAFE_NO_PAD
23- .decode(text.trim_end_matches('='))
24- .map_err(|_| Error::Invalid("not base64url".into()))
25-}
26-
27-pub fn encode_b64(bytes: &[u8]) -> String {
28- URL_SAFE_NO_PAD.encode(bytes)
29-}
30-
31-fn random_secret() -> p256::SecretKey {
32- loop {
33- let mut bytes = [0u8; 32];
34- rand::fill(&mut bytes);
35- if let Ok(secret) = p256::SecretKey::from_slice(&bytes) {
36- return secret;
37- }
38- }
39-}
40-
41-pub fn new_vapid_private() -> [u8; 32] {
42- random_secret().to_bytes().into()
43-}
44-
45-pub fn vapid_key_pair(private: &[u8; 32]) -> Result<SigningKey> {
46- SigningKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))
47-}
48-
49-pub fn vapid_public_key(private: &[u8; 32]) -> Result<String> {
50- Ok(encode_b64(
51- vapid_key_pair(private)?
52- .verifying_key()
53- .to_sec1_point(false)
54- .as_bytes(),
55- ))
56-}
57-
58-fn encrypt_body(
59- ua_public: &p256::PublicKey,
60- auth: &[u8],
61- as_secret: &p256::SecretKey,
62- salt: &[u8; 16],
63- payload: &[u8],
64-) -> Result<Vec<u8>> {
65- let encryption_error =
66- |e: &dyn std::fmt::Display| Error::Crypto(format!("web push encryption failed: {e}"));
67- let as_public = as_secret.public_key().to_sec1_point(false);
68- let ua_point = ua_public.to_sec1_point(false);
69- let shared = p256::ecdh::diffie_hellman(as_secret.to_nonzero_scalar(), ua_public.as_affine());
70-
71- let mut key_info = b"WebPush: info\0".to_vec();
72- key_info.extend_from_slice(ua_point.as_bytes());
73- key_info.extend_from_slice(as_public.as_bytes());
74- let mut ikm = [0u8; 32];
75- Hkdf::<Sha256>::new(Some(auth), &shared.raw_secret_bytes()[..])
76- .expand(&key_info, &mut ikm)
77- .map_err(|e| encryption_error(&e))?;
78-
79- let mut cek = [0u8; 16];
80- let mut nonce = [0u8; 12];
81- let prk = Hkdf::<Sha256>::new(Some(salt), &ikm);
82- prk.expand(b"Content-Encoding: aes128gcm\0", &mut cek)
83- .map_err(|e| encryption_error(&e))?;
84- prk.expand(b"Content-Encoding: nonce\0", &mut nonce)
85- .map_err(|e| encryption_error(&e))?;
86-
87- if payload.len() + 1 + 16 > RECORD_SIZE as usize {
88- return Err(Error::Invalid("the push message is too large".into()));
89- }
90- let mut plaintext = payload.to_vec();
91- plaintext.push(0x02);
92- let ciphertext = Aes128Gcm::new(&cek.into())
93- .encrypt(&nonce.into(), plaintext.as_slice())
94- .map_err(|e| encryption_error(&e))?;
95-
96- let mut body = Vec::with_capacity(salt.len() + 4 + 1 + POINT_LEN + ciphertext.len());
97- body.extend_from_slice(salt);
98- body.extend_from_slice(&RECORD_SIZE.to_be_bytes());
99- body.push(POINT_LEN as u8);
100- body.extend_from_slice(as_public.as_bytes());
101- body.extend_from_slice(&ciphertext);
102- Ok(body)
103-}
104-
105-fn vapid_token(uri: &http::Uri, subject: &str, key_pair: &SigningKey) -> Result<String> {
106- let bad_endpoint = || Error::Invalid("bad push endpoint".into());
107- let scheme = uri.scheme_str().ok_or_else(bad_endpoint)?;
108- let authority = uri.authority().ok_or_else(bad_endpoint)?;
109- let now = SystemTime::now()
110- .duration_since(UNIX_EPOCH)
111- .map_err(|_| Error::Crypto("the system clock is before 1970".into()))?
112- .as_secs();
113- let header = URL_SAFE_NO_PAD.encode(r#"{"typ":"JWT","alg":"ES256"}"#);
114- let claims = serde_json::json!({
115- "aud": format!("{scheme}://{authority}"),
116- "exp": now + VAPID_TTL,
117- "sub": subject,
118- });
119- let input = format!("{header}.{}", URL_SAFE_NO_PAD.encode(claims.to_string()));
120- let signature: Signature = key_pair
121- .try_sign(input.as_bytes())
122- .map_err(|e| Error::Crypto(format!("VAPID signing failed: {e}")))?;
123- Ok(format!(
124- "{input}.{}",
125- URL_SAFE_NO_PAD.encode(signature.to_bytes())
126- ))
127-}
128-
129-pub fn push_request(
130- endpoint: &str,
131- p256dh: &[u8],
132- auth: &[u8],
133- subject: &str,
134- key_pair: &SigningKey,
135- payload: Vec<u8>,
136-) -> Result<http::Request<Vec<u8>>> {
137- if p256dh.len() != POINT_LEN {
138- return Err(Error::Invalid(
139- "the browser key is not a P-256 point".into(),
140- ));
141- }
142- let ua_public = p256::PublicKey::from_sec1_bytes(p256dh)
143- .map_err(|_| Error::Invalid("the browser key is not on the curve".into()))?;
144- if auth.len() != 16 {
145- return Err(Error::Invalid(
146- "the browser auth secret is not 16 bytes".into(),
147- ));
148- }
149- let uri: http::Uri = endpoint
150- .parse()
151- .map_err(|_| Error::Invalid("bad push endpoint".into()))?;
152-
153- let mut salt = [0u8; 16];
154- rand::fill(&mut salt);
155- let body = encrypt_body(&ua_public, auth, &random_secret(), &salt, &payload)?;
156-
157- let token = vapid_token(&uri, subject, key_pair)?;
158- let public = key_pair.verifying_key().to_sec1_point(false);
159- http::Request::builder()
160- .method(http::Method::POST)
161- .uri(uri)
162- .header("content-encoding", "aes128gcm")
163- .header("content-type", "application/octet-stream")
164- .header("ttl", PUSH_TTL)
165- .header(
166- "authorization",
167- format!("vapid t={token}, k={}", encode_b64(public.as_bytes())),
168- )
169- .body(body)
170- .map_err(|e| Error::Crypto(format!("web push request failed: {e}")))
171-}
172-
173-#[cfg(test)]
174-mod tests {
175- use super::*;
176-
177- #[test]
178- fn a_browser_key_that_is_not_a_point_is_refused() {
179- let key_pair = vapid_key_pair(&new_vapid_private()).expect("key");
180- let auth = [7u8; 16];
181- let not_a_point = [4u8; 65];
182- assert!(
183- push_request(
184- "https://push.example.test/x",
185- &not_a_point,
186- &auth,
187- "mailto:tahinli@example.test",
188- &key_pair,
189- b"hi".to_vec()
190- )
191- .is_err()
192- );
193- assert!(
194- push_request(
195- "https://push.example.test/x",
196- &[0x04; 10],
197- &auth,
198- "mailto:tahinli@example.test",
199- &key_pair,
200- b"hi".to_vec()
201- )
202- .is_err()
203- );
204- }
205-
206- #[test]
207- fn the_request_is_an_encrypted_vapid_post_to_the_endpoint() {
208- let private = new_vapid_private();
209- let key_pair = vapid_key_pair(&private).expect("key");
210- let browser = p256::SecretKey::from_slice(&new_vapid_private()).expect("scalar");
211- let point = browser
212- .public_key()
213- .to_sec1_point(false)
214- .as_bytes()
215- .to_vec();
216- let auth = [9u8; 16];
217- let endpoint = "https://push.example.test/send/abc";
218- let payload = br#"{"title":"tahinli/forge#1"}"#.to_vec();
219- let request = push_request(
220- endpoint,
221- &point,
222- &auth,
223- "mailto:tahinli@example.test",
224- &key_pair,
225- payload.clone(),
226- )
227- .expect("request");
228-
229- assert_eq!(request.method(), http::Method::POST);
230- assert_eq!(request.uri().to_string(), endpoint);
231- assert_eq!(request.headers()["content-encoding"], "aes128gcm");
232- assert_eq!(request.headers()["ttl"], "43200");
233-
234- let auth_header = request.headers()["authorization"]
235- .to_str()
236- .expect("ascii")
237- .to_owned();
238- assert!(auth_header.starts_with("vapid "), "{auth_header}");
239- assert!(auth_header.contains(&format!(
240- "k={}",
241- vapid_public_key(&private).expect("public")
242- )));
243- let token = auth_header
244- .split("t=")
245- .nth(1)
246- .and_then(|rest| rest.split(',').next())
247- .expect("token");
248- let claims = token.split('.').nth(1).expect("claims");
249- let claims = decode_b64(claims).expect("base64");
250- let claims: serde_json::Value = serde_json::from_slice(&claims).expect("json");
251- assert_eq!(claims["aud"], "https://push.example.test");
252- assert_eq!(claims["sub"], "mailto:tahinli@example.test");
253-
254- let body = request.body();
255- assert!(body.len() > payload.len());
256- assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice()));
257- }
258-
259- #[test]
260- fn the_public_key_is_the_uncompressed_point() {
261- let public = vapid_public_key(&new_vapid_private()).expect("public");
262- assert_eq!(decode_b64(&public).expect("b64").len(), POINT_LEN);
263- }
264-
265- #[test]
266- fn the_rfc_8291_appendix_a_vector_encrypts_to_the_published_body() {
267- let as_secret = p256::SecretKey::from_slice(
268- &decode_b64("yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw").expect("b64"),
269- )
270- .expect("key");
271- let ua_public = p256::PublicKey::from_sec1_bytes(
272- &decode_b64(
273- "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4",
274- )
275- .expect("b64"),
276- )
277- .expect("point");
278- let auth = decode_b64("BTBZMqHH6r4Tts7J_aSIgg").expect("b64");
279- let salt: [u8; 16] = decode_b64("DGv6ra1nlYgDCS1FRnbzlw")
280- .expect("b64")
281- .try_into()
282- .expect("16 bytes");
283- let body = encrypt_body(
284- &ua_public,
285- &auth,
286- &as_secret,
287- &salt,
288- b"When I grow up, I want to be a watermelon",
289- )
290- .expect("body");
291- assert_eq!(
292- encode_b64(&body),
293- "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPTpK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN"
294- );
295- }
296-}
crates/forge-web-app/src/web_push/mod.rsdeleted+0 -574
@@ -1,574 +0,0 @@
1-pub mod crypto;
2-
3-use std::sync::OnceLock;
4-use std::time::Duration;
5-
6-use serde::Serialize;
7-use tokio::sync::broadcast;
8-
9-use forge_core::store::web_push::PushSubscription;
10-use forge_core::{Error, Result};
11-
12-use crate::i18n::{self, Lang, misc, push as text};
13-use crate::state::AppState;
14-use crate::webhooks::client::{WebhookPolicy, policy_client, validate_url};
15-
16-const SEND_TIMEOUT: Duration = Duration::from_secs(15);
17-const BODY_CHARS: usize = 140;
18-
19-pub struct PushLive {
20- tx: broadcast::Sender<String>,
21-}
22-
23-impl Default for PushLive {
24- fn default() -> Self {
25- Self {
26- tx: broadcast::channel(64).0,
27- }
28- }
29-}
30-
31-impl PushLive {
32- pub fn publish(&self, user_id: &str) {
33- let _ = self.tx.send(user_id.to_owned());
34- }
35-
36- pub fn subscribe(&self) -> broadcast::Receiver<String> {
37- self.tx.subscribe()
38- }
39-}
40-
41-#[derive(Clone)]
42-pub enum Alert {
43- Activity {
44- repo: String,
45- number: i64,
46- title: String,
47- verb: misc::K,
48- actor: Option<String>,
49- url: String,
50- thread: String,
51- },
52- Admin {
53- subject: String,
54- detail: String,
55- },
56- Test,
57-}
58-
59-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
60-pub struct Message {
61- pub title: String,
62- pub body: String,
63- pub url: String,
64- pub tag: String,
65-}
66-
67-impl Alert {
68- pub fn message(&self, lang: Lang) -> Message {
69- match self {
70- Alert::Activity {
71- repo,
72- number,
73- title,
74- verb,
75- actor,
76- url,
77- thread,
78- } => {
79- let line = misc::activity_line(lang, *verb, actor.as_deref());
80- Message {
81- title: format!("{repo}#{number}"),
82- body: clip(&format!("{line}: {title}")),
83- url: safe_url(url),
84- tag: format!("thread-{thread}"),
85- }
86- }
87- Alert::Admin { subject, detail } => Message {
88- title: clip(subject),
89- body: clip(detail),
90- url: "/notifications".to_owned(),
91- tag: "admin-alert".to_owned(),
92- },
93- Alert::Test => Message {
94- title: text::t(lang, text::K::TestTitle).to_owned(),
95- body: text::t(lang, text::K::TestBody).to_owned(),
96- url: "/settings/notifications".to_owned(),
97- tag: "test".to_owned(),
98- },
99- }
100- }
101-}
102-
103-fn clip(text: &str) -> String {
104- let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
105- if one_line.chars().count() <= BODY_CHARS {
106- return one_line;
107- }
108- let mut short: String = one_line.chars().take(BODY_CHARS - 3).collect();
109- short.push_str("...");
110- short
111-}
112-
113-fn safe_url(url: &str) -> String {
114- if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') {
115- url.to_owned()
116- } else {
117- "/notifications".to_owned()
118- }
119-}
120-
121-pub fn agent_label(user_agent: &str) -> String {
122- agent_label_in(Lang::En, user_agent)
123-}
124-
125-pub fn agent_label_in(lang: Lang, user_agent: &str) -> String {
126- let os = if user_agent.contains("iPhone") {
127- "iPhone"
128- } else if user_agent.contains("iPad") {
129- "iPad"
130- } else if user_agent.contains("Android") {
131- "Android"
132- } else if user_agent.contains("Windows") {
133- "Windows"
134- } else if user_agent.contains("Macintosh") {
135- "Mac"
136- } else if user_agent.contains("CrOS") {
137- "ChromeOS"
138- } else if user_agent.contains("Linux") {
139- "Linux"
140- } else if lang == Lang::Tr {
141- "bilinmeyen sistem"
142- } else {
143- "Unknown system"
144- };
145- let browser = if user_agent.contains("Edg/") {
146- "Edge"
147- } else if user_agent.contains("OPR/") {
148- "Opera"
149- } else if user_agent.contains("Firefox/") {
150- "Firefox"
151- } else if user_agent.contains("Chrome/")
152- || user_agent.contains("Chromium/")
153- || user_agent.contains("CriOS/")
154- {
155- "Chrome"
156- } else if user_agent.contains("Safari/") {
157- "Safari"
158- } else if lang == Lang::Tr {
159- "Tarayıcı"
160- } else {
161- "Browser"
162- };
163- match lang {
164- Lang::Tr if os == "bilinmeyen sistem" => format!("{browser}, {os}"),
165- Lang::Tr => format!("{os} üzerinde {browser}"),
166- Lang::En => format!("{browser} on {os}"),
167- }
168-}
169-
170-fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> {
171- static CLIENT: OnceLock<Option<reqwest::Client>> = OnceLock::new();
172- CLIENT
173- .get_or_init(
174- || match policy_client(policy.clone(), SEND_TIMEOUT, "forge-web-push") {
175- Ok(client) => Some(client),
176- Err(e) => {
177- tracing::error!(error = %e, "web push: the client does not build");
178- None
179- }
180- },
181- )
182- .as_ref()
183-}
184-
185-pub struct VapidKeys {
186- pub private: [u8; 32],
187- pub public: String,
188-}
189-
190-pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> {
191- let (public, sealed) = match state.store.web_push_keys().await? {
192- Some(pair) => pair,
193- None => {
194- let private = crypto::new_vapid_private();
195- let public = crypto::vapid_public_key(&private)?;
196- let sealed = forge_core::secret::seal(&state.key, &private)?;
197- state.store.save_web_push_keys(&public, &sealed).await?
198- }
199- };
200- let opened = forge_core::secret::open(&state.key, &sealed)?;
201- let private: [u8; 32] = opened
202- .try_into()
203- .map_err(|_| Error::Crypto("the stored VAPID key has the wrong length".into()))?;
204- Ok(VapidKeys { private, public })
205-}
206-
207-fn subject(base_url: &str) -> String {
208- let base = base_url.trim_end_matches('/');
209- if base.starts_with("https://") {
210- base.to_owned()
211- } else {
212- "https://localhost".to_owned()
213- }
214-}
215-
216-#[derive(Debug, PartialEq, Eq)]
217-enum Outcome {
218- Delivered,
219- Gone,
220- Failed(String),
221-}
222-
223-async fn send_one(
224- client: &reqwest::Client,
225- policy: &WebhookPolicy,
226- keys: &VapidKeys,
227- subject: &str,
228- sub: &PushSubscription,
229- payload: &[u8],
230-) -> Outcome {
231- if let Err(e) = validate_url(&sub.endpoint, policy) {
232- return Outcome::Failed(e.to_string());
233- }
234- let built = (|| {
235- let p256dh = crypto::decode_b64(&sub.p256dh)?;
236- let auth = crypto::decode_b64(&sub.auth)?;
237- let key_pair = crypto::vapid_key_pair(&keys.private)?;
238- crypto::push_request(
239- &sub.endpoint,
240- &p256dh,
241- &auth,
242- subject,
243- &key_pair,
244- payload.to_vec(),
245- )
246- })();
247- let request = match built {
248- Ok(request) => request,
249- Err(e) => return Outcome::Failed(e.to_string()),
250- };
251- let request = match reqwest::Request::try_from(request) {
252- Ok(request) => request,
253- Err(e) => return Outcome::Failed(e.to_string()),
254- };
255- match client.execute(request).await {
256- Ok(res) => match res.status().as_u16() {
257- 200..=299 => Outcome::Delivered,
258- 404 | 410 => Outcome::Gone,
259- status => Outcome::Failed(format!("the push service answered {status}")),
260- },
261- Err(e) => Outcome::Failed(e.to_string()),
262- }
263-}
264-
265-pub fn queue(state: &AppState, user_id: &str, alert: Alert) {
266- let state = state.clone();
267- let user_id = user_id.to_owned();
268- tokio::spawn(async move {
269- if let Err(e) = deliver(&state, &user_id, &alert).await {
270- tracing::error!(error = %e, user_id, "web push: delivery failed");
271- }
272- });
273-}
274-
275-async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<()> {
276- let devices = state.store.push_subscriptions(user_id).await?;
277- if devices.is_empty() {
278- return Ok(());
279- }
280- let lang = match state.store.user_by_id(user_id).await? {
281- Some(user) => i18n::resolve(Some(user.language.as_str()), &http::HeaderMap::new()),
282- None => Lang::En,
283- };
284- let payload = serde_json::to_vec(&alert.message(lang))
285- .map_err(|e| Error::Invalid(format!("the push payload does not encode: {e}")))?;
286- let keys = vapid_keys(state).await?;
287- let subject = subject(&state.live().base_url);
288- let policy = crate::mirrors::policy(state);
289- let Some(client) = client(&policy) else {
290- return Err(Error::Invalid("the web push client does not build".into()));
291- };
292- for device in &devices {
293- match send_one(client, &policy, &keys, &subject, device, &payload).await {
294- Outcome::Delivered => {
295- if let Err(e) = state.store.mark_push_delivered(&device.id).await {
296- tracing::warn!(
297- error = %e,
298- device = %device.id,
299- "web push: the delivery stamp was not saved"
300- );
301- }
302- state.push_live.publish(user_id);
303- }
304- Outcome::Gone => {
305- if let Err(e) = state.store.delete_push_endpoint(&device.endpoint).await {
306- tracing::warn!(
307- error = %e,
308- device = %device.id,
309- "web push: the gone device was not removed"
310- );
311- }
312- state.push_live.publish(user_id);
313- }
314- Outcome::Failed(reason) => {
315- tracing::warn!(reason, device = %device.id, "web push: a device was not reached");
316- }
317- }
318- }
319- Ok(())
320-}
321-
322-#[cfg(test)]
323-mod tests {
324- use super::*;
325- use p256::elliptic_curve::sec1::ToSec1Point;
326-
327- fn activity(actor: Option<&str>) -> Alert {
328- Alert::Activity {
329- repo: "tahinli/forge".into(),
330- number: 42,
331- title: "Crash on startup\nwhen the cache is cold".into(),
332- verb: misc::K::VerbCommented,
333- actor: actor.map(str::to_owned),
334- url: "/tahinli/forge/issues/42".into(),
335- thread: "issue-1".into(),
336- }
337- }
338-
339- #[test]
340- fn an_activity_payload_is_short_and_names_the_thread() {
341- let msg = activity(Some("tahinli")).message(Lang::En);
342- assert_eq!(msg.title, "tahinli/forge#42");
343- assert_eq!(
344- msg.body,
345- "commented by tahinli: Crash on startup when the cache is cold"
346- );
347- assert_eq!(msg.url, "/tahinli/forge/issues/42");
348- assert_eq!(msg.tag, "thread-issue-1");
349- }
350-
351- #[test]
352- fn the_body_is_clipped_to_the_limit() {
353- let long = Alert::Admin {
354- subject: "Backup".into(),
355- detail: "x".repeat(400),
356- };
357- let msg = long.message(Lang::En);
358- assert_eq!(msg.body.chars().count(), BODY_CHARS);
359- assert!(msg.body.ends_with("..."));
360- }
361-
362- #[test]
363- fn the_payload_follows_the_recipient_language() {
364- let msg = activity(None).message(Lang::Tr);
365- assert!(msg.body.starts_with("Yorumlandı"), "{}", msg.body);
366- }
367-
368- #[test]
369- fn a_link_must_stay_on_this_origin() {
370- assert_eq!(safe_url("/tahinli/forge"), "/tahinli/forge");
371- assert_eq!(safe_url("https://evil.example/x"), "/notifications");
372- assert_eq!(safe_url("//evil.example/x"), "/notifications");
373- assert_eq!(safe_url("/\\evil.example"), "/notifications");
374- }
375-
376- #[test]
377- fn device_labels_name_the_browser_and_the_system() {
378- let chrome_android = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36";
379- assert_eq!(agent_label(chrome_android), "Chrome on Android");
380- 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";
381- assert_eq!(agent_label(safari_iphone), "Safari on iPhone");
382- assert_eq!(agent_label("curl/8.0"), "Browser on Unknown system");
383- }
384-
385- #[test]
386- fn the_subject_is_https_or_the_fallback() {
387- assert_eq!(
388- subject("https://forge.example.test/"),
389- "https://forge.example.test"
390- );
391- assert_eq!(subject("http://127.0.0.1:7660"), "https://localhost");
392- }
393-
394- #[test]
395- fn push_live_reaches_a_listener_and_tolerates_none() {
396- let live = PushLive::default();
397- live.publish("nobody");
398- let mut rx = live.subscribe();
399- live.publish("tahinli");
400- assert_eq!(rx.try_recv().expect("event"), "tahinli");
401- }
402-
403- async fn mock_push_service() -> std::net::SocketAddr {
404- use tokio::io::{AsyncReadExt, AsyncWriteExt};
405- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
406- .await
407- .expect("bind");
408- let addr = listener.local_addr().expect("addr");
409- tokio::spawn(async move {
410- loop {
411- let Ok((mut socket, _)) = listener.accept().await else {
412- return;
413- };
414- tokio::spawn(async move {
415- let mut buf = Vec::new();
416- let mut chunk = [0u8; 4096];
417- let (head_end, length) = loop {
418- let n = socket.read(&mut chunk).await.unwrap_or(0);
419- if n == 0 {
420- return;
421- }
422- buf.extend_from_slice(&chunk[..n]);
423- if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
424- let head = String::from_utf8_lossy(&buf[..end]).to_ascii_lowercase();
425- let length = head
426- .lines()
427- .find_map(|l| l.strip_prefix("content-length:"))
428- .and_then(|v| v.trim().parse::<usize>().ok())
429- .unwrap_or(0);
430- break (end + 4, length);
431- }
432- };
433- while buf.len() < head_end + length {
434- let n = socket.read(&mut chunk).await.unwrap_or(0);
435- if n == 0 {
436- break;
437- }
438- buf.extend_from_slice(&chunk[..n]);
439- }
440- let request = String::from_utf8_lossy(&buf[..head_end]).into_owned();
441- let status = if request.starts_with("POST /gone") {
442- "410 Gone"
443- } else {
444- "201 Created"
445- };
446- let reply = format!(
447- "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
448- );
449- let _ = socket.write_all(reply.as_bytes()).await;
450- });
451- }
452- });
453- addr
454- }
455-
456- fn device(endpoint: String) -> PushSubscription {
457- let secret = p256::SecretKey::from_slice(&crypto::new_vapid_private()).expect("scalar");
458- let point = secret.public_key().to_sec1_point(false);
459- PushSubscription {
460- id: endpoint.clone(),
461- user_id: String::new(),
462- endpoint,
463- p256dh: crypto::encode_b64(point.as_bytes()),
464- auth: crypto::encode_b64(&[9u8; 16]),
465- agent_label: "Chrome on Linux".into(),
466- created_at: String::new(),
467- last_success_at: None,
468- }
469- }
470-
471- #[tokio::test]
472- async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() {
473- let dir = tempfile::tempdir().expect("tempdir");
474- let mut state = crate::test_support::test_state(dir.path()).await;
475- let mut config = crate::test_support::test_config(dir.path());
476- config.webhooks = forge_core::config::WebhookConfig {
477- allow_http: true,
478- allowed_hosts: vec!["127.0.0.1".into()],
479- };
480- state.config = std::sync::Arc::new(config);
481- let user = state
482- .store
483- .create_user("tahinli", None, "h", false)
484- .await
485- .expect("user");
486- let addr = mock_push_service().await;
487- let gone = format!("http://{addr}/gone");
488- let ok = format!("http://{addr}/ok");
489- let gone_device = device(gone.clone());
490- let ok_device = device(ok.clone());
491- state
492- .store
493- .save_push_subscription(
494- &user.id,
495- &gone,
496- &gone_device.p256dh,
497- &gone_device.auth,
498- "Chrome on Linux",
499- )
500- .await
501- .expect("save gone");
502- state
503- .store
504- .save_push_subscription(
505- &user.id,
506- &ok,
507- &ok_device.p256dh,
508- &ok_device.auth,
509- "Chrome on Linux",
510- )
511- .await
512- .expect("save ok");
513-
514- deliver(&state, &user.id, &Alert::Test)
515- .await
516- .expect("deliver");
517- let left = state
518- .store
519- .push_subscriptions(&user.id)
520- .await
521- .expect("list");
522- assert_eq!(left.len(), 1, "the 410 device is forgotten");
523- assert_eq!(left[0].endpoint, ok);
524- assert!(
525- left[0].last_success_at.is_some(),
526- "the delivered device is stamped"
527- );
528- }
529-
530- #[tokio::test]
531- async fn the_payload_is_encrypted_for_the_device_and_the_status_is_read() {
532- let addr = mock_push_service().await;
533- let private = crypto::new_vapid_private();
534- let keys = VapidKeys {
535- public: crypto::vapid_public_key(&private).expect("public"),
536- private,
537- };
538- let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json");
539- let open = WebhookPolicy::from_config(&forge_core::config::WebhookConfig {
540- allow_http: true,
541- allowed_hosts: vec!["127.0.0.1".into()],
542- })
543- .expect("policy");
544- let client = reqwest::Client::new();
545- let send = |endpoint: String, policy: WebhookPolicy| {
546- let (client, keys, payload) = (&client, &keys, &payload);
547- async move {
548- send_one(
549- client,
550- &policy,
551- keys,
552- "https://localhost",
553- &device(endpoint),
554- payload,
555- )
556- .await
557- }
558- };
559- assert_eq!(
560- send(format!("http://{addr}/ok"), open.clone()).await,
561- Outcome::Delivered
562- );
563- assert_eq!(
564- send(format!("http://{addr}/gone"), open).await,
565- Outcome::Gone
566- );
567- let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default())
568- .expect("policy");
569- assert!(matches!(
570- send(format!("http://{addr}/ok"), strict).await,
571- Outcome::Failed(_)
572- ));
573- }
574-}
crates/forge-web-base/src/i18n/mod.rsmodified+0 -1
@@ -47,7 +47,6 @@ pub mod orgs;
4747 pub mod packages;
4848 pub mod pulls;
4949 pub mod pulls_review;
50-pub mod push;
5150 pub mod releases_ci;
5251 pub mod repo_admin;
5352 pub mod server_settings;
crates/forge-web-base/src/i18n/push.rsdeleted+0 -46
@@ -1,46 +0,0 @@
1-use super::Lang;
2-
3-strings! {
4- K;
5- DeviceHeading => "Push notifications on this device", "Bu cihazda anlık bildirimler";
6- DeviceUnsupported => "This browser does not support push notifications.", "Bu tarayıcı anlık bildirimleri desteklemiyor.";
7- DeviceNeedsHttps => "Push notifications need an HTTPS connection.", "Anlık bildirimler için HTTPS bağlantısı gerekir.";
8- 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.";
9- 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.";
10- DeviceOn => "Push is on for this device.", "Bu cihazda anlık bildirimler açık.";
11- DeviceOff => "Push is off for this device.", "Bu cihazda anlık bildirimler kapalı.";
12- DeviceError => "Push could not be turned on. Try again.", "Anlık bildirimler açılamadı. Yeniden deneyin.";
13- TurnOn => "Turn on for this device", "Bu cihazda aç";
14- TurnOff => "Turn off for this device", "Bu cihazda kapat";
15- SendTest => "Send test notification", "Test bildirimi gönder";
16- 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.";
17- DevicesHeading => "Devices", "Cihazlar";
18- DevicesEmpty => "No device has push on.", "Anlık bildirimi açık cihaz yok.";
19- RemoveDevice => "Remove", "Kaldır";
20- DeviceRemoved => "Device removed.", "Cihaz kaldırıldı.";
21- NeverDelivered => "Nothing delivered yet", "Henüz teslim edilmedi";
22- TestTitle => "Forge test notification", "Forge test bildirimi";
23- TestBody => "Push notifications work on this device.", "Anlık bildirimler bu cihazda çalışıyor.";
24-}
25-
26-pub fn test_sent(lang: Lang, devices: usize) -> String {
27- match lang {
28- Lang::En => format!("Test sent to {devices} device(s)."),
29- Lang::Tr => format!("Test {devices} cihaza gönderildi."),
30- }
31-}
32-
33-pub fn added_label(lang: Lang) -> &'static str {
34- match lang {
35- Lang::En => "Added",
36- Lang::Tr => "Eklendi",
37- }
38-}
39-
40-pub fn last_delivered_label(lang: Lang) -> &'static str {
41- match lang {
42- Lang::En => "Last delivered",
43- Lang::Tr => "Son teslim",
44- }
45-}
46-
crates/forge-web-repo/Cargo.tomlmodified+0 -1
@@ -34,7 +34,6 @@ multer.workspace = true
3434 ulid.workspace = true
3535 zip = { workspace = true }
3636 tar.workspace = true
37-p256.workspace = true
3837
3938
4039 [dev-dependencies]
crates/forge-web-repo/src/lib.rsmodified+1 -2
@@ -4,8 +4,7 @@
44 pub(crate) use forge_web_app::test_support;
55 pub(crate) use forge_web_app::{
66 api, audit, auth, automerge, blobs, ci, i18n, internal, layers, lfs, lfs_pointer, live, merge,
7- merge_queue, mirrors, notify, post_update, raw, render, signatures, state, templates, views,
8- web_push, webhooks,
7+ merge_queue, notify, post_update, raw, render, signatures, state, templates, views, webhooks,
98 };
109
1110 pub mod pages;
crates/forge-web-repo/src/pages/mod.rsmodified+0 -1
@@ -39,7 +39,6 @@ pub mod pull_flow;
3939 pub mod pull_view;
4040 pub mod pulls_list;
4141 pub mod pulls_merge;
42-pub mod push;
4342 pub mod reactions;
4443 #[cfg(test)]
4544 mod reactions_tests;
crates/forge-web-repo/src/pages/push.rsdeleted+0 -533
@@ -1,533 +0,0 @@
1-use futures_util::stream;
2-use http::header::USER_AGENT;
3-use serde::Deserialize;
4-use serde_json::json;
5-use tokio::sync::broadcast::error::RecvError;
6-use topcoat::Result;
7-use topcoat::context::{Cx, context};
8-use topcoat::router::content::Form;
9-use topcoat::router::content::sse::Event;
10-use topcoat::router::error::{SeeOther, see_other};
11-use topcoat::router::request::headers;
12-use topcoat::router::response::Response;
13-use topcoat::router::{Body, HeaderMap, StatusCode, header, route};
14-
15-use crate::api::{self, json};
16-use crate::auth::{CsrfForm, current_user, require_csrf, require_user};
17-use crate::live::events_response;
18-use crate::state::AppState;
19-use crate::web_push::{self, Alert, crypto};
20-use crate::webhooks::client::{WebhookPolicy, validate_url};
21-
22-const MAX_ENDPOINT: usize = 2048;
23-
24-#[derive(Deserialize)]
25-struct SubscribeForm {
26- #[serde(default)]
27- csrf: String,
28- #[serde(default)]
29- endpoint: String,
30- #[serde(default)]
31- p256dh: String,
32- #[serde(default)]
33- auth: String,
34-}
35-
36-#[derive(Deserialize)]
37-struct EndpointForm {
38- #[serde(default)]
39- csrf: String,
40- #[serde(default)]
41- endpoint: String,
42-}
43-
44-#[derive(Deserialize)]
45-struct DeviceForm {
46- #[serde(default)]
47- csrf: String,
48- #[serde(default)]
49- id: String,
50-}
51-
52-fn check_endpoint(endpoint: &str, policy: &WebhookPolicy) -> forge_core::Result<()> {
53- if endpoint.len() > MAX_ENDPOINT {
54- return Err(forge_core::Error::Invalid(
55- "the push endpoint is too long".into(),
56- ));
57- }
58- let url = reqwest::Url::parse(endpoint)
59- .map_err(|_| forge_core::Error::Invalid("the push endpoint is not a URL".into()))?;
60- if url.scheme() != "https" || url.host_str().is_none() || url.port().is_some() {
61- return Err(forge_core::Error::Invalid(
62- "the push endpoint must be an https URL on the default port".into(),
63- ));
64- }
65- validate_url(endpoint, policy).map_err(|e| forge_core::Error::Invalid(e.to_string()))?;
66- Ok(())
67-}
68-
69-fn check_keys(p256dh: &str, auth: &str) -> forge_core::Result<()> {
70- let point = crypto::decode_b64(p256dh)?;
71- if point.len() != 65 || point[0] != 0x04 || p256::PublicKey::from_sec1_bytes(&point).is_err() {
72- return Err(forge_core::Error::Invalid(
73- "the browser key is not a P-256 public key".into(),
74- ));
75- }
76- if crypto::decode_b64(auth)?.len() != 16 {
77- return Err(forge_core::Error::Invalid(
78- "the browser auth secret is not 16 bytes".into(),
79- ));
80- }
81- Ok(())
82-}
83-
84-fn no_content() -> Response {
85- let mut res = Response::new(Body::empty());
86- *res.status_mut() = StatusCode::NO_CONTENT;
87- res
88-}
89-
90-#[route(GET "/push/vapid-key")]
91-async fn vapid_key(cx: &Cx) -> Result<Response> {
92- require_user(cx).await?;
93- let state = context::<AppState>(cx);
94- let keys = web_push::vapid_keys(state).await?;
95- Ok(json(StatusCode::OK, &json!({ "public_key": keys.public })))
96-}
97-
98-#[route(POST "/push/subscribe")]
99-async fn subscribe(cx: &Cx, Form(form): Form<SubscribeForm>) -> Result<Response> {
100- let (user, _) = require_csrf(cx, &form.csrf).await?;
101- let state = context::<AppState>(cx);
102- let policy = crate::mirrors::policy(state);
103- if let Err(e) =
104- check_endpoint(&form.endpoint, &policy).and_then(|()| check_keys(&form.p256dh, &form.auth))
105- {
106- return Ok(api::error(StatusCode::BAD_REQUEST, &e.to_string()));
107- }
108- let agent = headers(cx)
109- .get(USER_AGENT)
110- .and_then(|value| value.to_str().ok())
111- .unwrap_or_default()
112- .to_owned();
113- state
114- .store
115- .save_push_subscription(
116- &user.id,
117- &form.endpoint,
118- &form.p256dh,
119- &form.auth,
120- &web_push::agent_label(&agent),
121- )
122- .await?;
123- state.push_live.publish(&user.id);
124- Ok(no_content())
125-}
126-
127-#[route(POST "/push/unsubscribe")]
128-async fn unsubscribe(cx: &Cx, Form(form): Form<EndpointForm>) -> Result<Response> {
129- let (user, _) = require_csrf(cx, &form.csrf).await?;
130- let state = context::<AppState>(cx);
131- if state
132- .store
133- .delete_push_subscription_by_endpoint(&user.id, &form.endpoint)
134- .await?
135- {
136- state.push_live.publish(&user.id);
137- }
138- Ok(no_content())
139-}
140-
141-#[route(POST "/settings/notifications/push/remove")]
142-async fn remove_device(cx: &Cx, Form(form): Form<DeviceForm>) -> Result<SeeOther> {
143- let (user, _) = require_csrf(cx, &form.csrf).await?;
144- let state = context::<AppState>(cx);
145- if state
146- .store
147- .delete_push_subscription(&user.id, &form.id)
148- .await?
149- {
150- state.push_live.publish(&user.id);
151- }
152- Ok(see_other("/settings/notifications?removed=1"))
153-}
154-
155-#[route(POST "/settings/notifications/push/test")]
156-async fn send_test(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
157- let (user, _) = require_csrf(cx, &form.csrf).await?;
158- let state = context::<AppState>(cx);
159- let devices = state.store.push_subscriptions(&user.id).await?.len();
160- if devices > 0 {
161- web_push::queue(state, &user.id, Alert::Test);
162- }
163- Ok(see_other(format!("/settings/notifications?test={devices}")))
164-}
165-
166-#[route(GET "/settings/notifications/push/events")]
167-async fn push_events(cx: &Cx) -> Result<Response> {
168- let Some((user, _)) = current_user(cx).await? else {
169- let mut res = Response::new(Body::empty());
170- *res.status_mut() = StatusCode::UNAUTHORIZED;
171- return Ok(res);
172- };
173- let state = context::<AppState>(cx);
174- let rx = state.push_live.subscribe();
175- let changes = stream::unfold((rx, user.id), |(mut rx, user_id)| async move {
176- loop {
177- match rx.recv().await {
178- Ok(changed) if changed == user_id => {
179- return Some((changed_event(), (rx, user_id)));
180- }
181- Ok(_) => continue,
182- Err(RecvError::Lagged(_)) => return Some((changed_event(), (rx, user_id))),
183- Err(RecvError::Closed) => return None,
184- }
185- }
186- });
187- events_response(cx, changes)
188-}
189-
190-fn changed_event() -> Result<Event> {
191- Ok(Event::new().event("changed").data("1"))
192-}
193-
194-const SW_JS: &str = include_str!("../../../forge-web/assets/sw.js");
195-const ICON_192: &[u8] = include_bytes!("../../../forge-web/assets/icons/icon-192.png");
196-const ICON_512: &[u8] = include_bytes!("../../../forge-web/assets/icons/icon-512.png");
197-const APPLE_TOUCH_ICON: &[u8] =
198- include_bytes!("../../../forge-web/assets/icons/apple-touch-icon.png");
199-
200-const MANIFEST: &str = r##"{
201- "name": "Forge",
202- "short_name": "Forge",
203- "start_url": "/",
204- "scope": "/",
205- "display": "standalone",
206- "background_color": "#f6f4ec",
207- "theme_color": "#5f7f67",
208- "icons": [
209- { "src": "/assets/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
210- { "src": "/assets/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }
211- ]
212-}
213-"##;
214-
215-fn static_headers(content_type: &'static str, cache: &'static str) -> HeaderMap {
216- let mut headers = HeaderMap::new();
217- headers.insert(
218- header::CONTENT_TYPE,
219- content_type.parse().expect("static header value"),
220- );
221- headers.insert(
222- header::CACHE_CONTROL,
223- cache.parse().expect("static header value"),
224- );
225- headers
226-}
227-
228-#[route(GET "/sw.js")]
229-async fn service_worker(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
230- let headers = static_headers("text/javascript; charset=utf-8", "no-cache");
231- Ok((StatusCode::OK, headers, SW_JS))
232-}
233-
234-#[route(GET "/manifest.webmanifest")]
235-async fn manifest(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
236- let headers = static_headers("application/manifest+json", "public, max-age=3600");
237- Ok((StatusCode::OK, headers, MANIFEST))
238-}
239-
240-#[route(GET "/assets/icons/icon-192.png")]
241-async fn icon_192(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
242- let headers = static_headers("image/png", "public, max-age=604800");
243- Ok((StatusCode::OK, headers, ICON_192))
244-}
245-
246-#[route(GET "/assets/icons/icon-512.png")]
247-async fn icon_512(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
248- let headers = static_headers("image/png", "public, max-age=604800");
249- Ok((StatusCode::OK, headers, ICON_512))
250-}
251-
252-#[route(GET "/assets/icons/apple-touch-icon.png")]
253-async fn apple_touch_icon(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
254- let headers = static_headers("image/png", "public, max-age=604800");
255- Ok((StatusCode::OK, headers, APPLE_TOUCH_ICON))
256-}
257-
258-#[cfg(test)]
259-mod tests {
260- use forge_core::Store;
261- use p256::elliptic_curve::sec1::ToSec1Point;
262- use topcoat::router::request::Request;
263- use topcoat::router::{Body, Router, to_bytes};
264-
265- use crate::auth::SESSION_COOKIE;
266- use crate::test_support::{app_router, create_session, test_state};
267- use crate::web_push::crypto;
268-
269- const TOKEN: &str = "push-session";
270- const CSRF: &str = "push-csrf";
271- const UA: &str =
272- "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36";
273-
274- struct Fixture {
275- _dir: tempfile::TempDir,
276- router: Router,
277- store: Store,
278- user_id: String,
279- }
280-
281- async fn fixture() -> Fixture {
282- let dir = tempfile::tempdir().expect("tempdir");
283- let data_dir = dir.path().join("data");
284- std::fs::create_dir_all(&data_dir).expect("data dir");
285- let state = test_state(&data_dir).await;
286- let user = state
287- .store
288- .create_user("tahinli", None, "h", false)
289- .await
290- .expect("user");
291- create_session(&state.store, &user.id, TOKEN, CSRF).await;
292- Fixture {
293- _dir: dir,
294- router: app_router(state.clone()),
295- store: state.store.clone(),
296- user_id: user.id,
297- }
298- }
299-
300- fn browser_keys() -> (String, String) {
301- let secret = p256::SecretKey::from_slice(&crypto::new_vapid_private()).expect("scalar");
302- let point = secret.public_key().to_sec1_point(false);
303- (
304- crypto::encode_b64(point.as_bytes()),
305- crypto::encode_b64(&[7u8; 16]),
306- )
307- }
308-
309- async fn send(
310- router: &Router,
311- method: &str,
312- uri: &str,
313- token: Option<&str>,
314- form: Option<String>,
315- ) -> (u16, String) {
316- let mut builder = Request::builder()
317- .method(method)
318- .uri(uri)
319- .header("user-agent", UA);
320- if let Some(token) = token {
321- builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
322- }
323- let body = match form {
324- Some(form) => {
325- builder = builder.header("content-type", "application/x-www-form-urlencoded");
326- Body::from(form)
327- }
328- None => Body::empty(),
329- };
330- let res = router.handle(builder.body(body).expect("request")).await;
331- let status = res.status().as_u16();
332- let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
333- (status, String::from_utf8_lossy(&bytes).into_owned())
334- }
335-
336- fn subscribe_form(csrf: &str, endpoint: &str, p256dh: &str, auth: &str) -> String {
337- let enc = |s: &str| form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>();
338- format!(
339- "csrf={}&endpoint={}&p256dh={}&auth={}",
340- enc(csrf),
341- enc(endpoint),
342- enc(p256dh),
343- enc(auth)
344- )
345- }
346-
347- #[tokio::test]
348- async fn the_vapid_key_is_created_once_and_served() {
349- let fx = fixture().await;
350- let (status, first) = send(&fx.router, "GET", "/push/vapid-key", Some(TOKEN), None).await;
351- assert_eq!(status, 200, "{first}");
352- let (_, second) = send(&fx.router, "GET", "/push/vapid-key", Some(TOKEN), None).await;
353- assert_eq!(first, second, "the same key on every request");
354- let key: serde_json::Value = serde_json::from_str(&first).expect("json");
355- let public = key["public_key"].as_str().expect("public key");
356- assert_eq!(crypto::decode_b64(public).expect("b64").len(), 65);
357-
358- let (status, _) = send(&fx.router, "GET", "/push/vapid-key", None, None).await;
359- assert_ne!(status, 200, "case anonymous");
360- }
361-
362- #[tokio::test]
363- async fn subscribe_then_unsubscribe_round_trip() {
364- let fx = fixture().await;
365- let (p256dh, auth) = browser_keys();
366- let endpoint = "https://push.example.test/send/tahinli-1";
367- let form = subscribe_form(CSRF, endpoint, &p256dh, &auth);
368-
369- let (status, body) = send(
370- &fx.router,
371- "POST",
372- "/push/subscribe",
373- Some(TOKEN),
374- Some(form),
375- )
376- .await;
377- assert_eq!(status, 204, "{body}");
378- let devices = fx
379- .store
380- .push_subscriptions(&fx.user_id)
381- .await
382- .expect("list");
383- assert_eq!(devices.len(), 1);
384- assert_eq!(devices[0].endpoint, endpoint);
385- assert_eq!(devices[0].agent_label, "Chrome on Android");
386-
387- let remove = format!("csrf={CSRF}&endpoint={endpoint}");
388- let (status, body) = send(
389- &fx.router,
390- "POST",
391- "/push/unsubscribe",
392- Some(TOKEN),
393- Some(remove),
394- )
395- .await;
396- assert_eq!(status, 204, "{body}");
397- assert!(
398- fx.store
399- .push_subscriptions(&fx.user_id)
400- .await
401- .expect("list")
402- .is_empty()
403- );
404- }
405-
406- #[tokio::test]
407- async fn refused_subscriptions_store_nothing() {
408- let fx = fixture().await;
409- let (p256dh, auth) = browser_keys();
410-
411- let form = subscribe_form("wrong", "https://push.example.test/x", &p256dh, &auth);
412- let (status, _) = send(
413- &fx.router,
414- "POST",
415- "/push/subscribe",
416- Some(TOKEN),
417- Some(form),
418- )
419- .await;
420- assert_eq!(status, 403, "case csrf");
421-
422- let http_endpoint = subscribe_form(CSRF, "http://push.example.test/x", &p256dh, &auth);
423- let (status, _) = send(
424- &fx.router,
425- "POST",
426- "/push/subscribe",
427- Some(TOKEN),
428- Some(http_endpoint),
429- )
430- .await;
431- assert_eq!(status, 400, "case http endpoint: an endpoint must be https");
432- let short_auth = subscribe_form(
433- CSRF,
434- "https://push.example.test/x",
435- &p256dh,
436- &crypto::encode_b64(&[1u8; 8]),
437- );
438- let (status, _) = send(
439- &fx.router,
440- "POST",
441- "/push/subscribe",
442- Some(TOKEN),
443- Some(short_auth),
444- )
445- .await;
446- assert_eq!(status, 400, "case short auth: the auth secret is 16 bytes");
447- let not_a_point = subscribe_form(
448- CSRF,
449- "https://push.example.test/x",
450- &crypto::encode_b64(&[4u8; 65]),
451- &auth,
452- );
453- let (status, _) = send(
454- &fx.router,
455- "POST",
456- "/push/subscribe",
457- Some(TOKEN),
458- Some(not_a_point),
459- )
460- .await;
461- assert_eq!(status, 400, "case not a point: the browser key is a point");
462- assert!(
463- fx.store
464- .push_subscriptions(&fx.user_id)
465- .await
466- .expect("list")
467- .is_empty()
468- );
469- }
470-
471- #[tokio::test]
472- async fn a_viewer_removes_only_their_own_device() {
473- let fx = fixture().await;
474- let other = fx
475- .store
476- .create_user("nina", None, "h", false)
477- .await
478- .expect("other user");
479- let theirs = fx
480- .store
481- .save_push_subscription(
482- &other.id,
483- "https://push.example.test/nina",
484- "BA",
485- "AA",
486- "Chrome on Linux",
487- )
488- .await
489- .expect("save");
490- let form = format!("csrf={CSRF}&id={}", theirs.id);
491- let (status, _) = send(
492- &fx.router,
493- "POST",
494- "/settings/notifications/push/remove",
495- Some(TOKEN),
496- Some(form),
497- )
498- .await;
499- assert_eq!(status, 303);
500- assert_eq!(
501- fx.store
502- .push_subscriptions(&other.id)
503- .await
504- .expect("list")
505- .len(),
506- 1
507- );
508- }
509-
510- #[tokio::test]
511- async fn worker_and_manifest_are_public_and_events_need_a_session() {
512- let fx = fixture().await;
513- let (status, _) = send(
514- &fx.router,
515- "GET",
516- "/settings/notifications/push/events",
517- None,
518- None,
519- )
520- .await;
521- assert_eq!(status, 401, "case events without a session");
522-
523- let (status, sw) = send(&fx.router, "GET", "/sw.js", None, None).await;
524- assert_eq!(status, 200);
525- assert!(sw.contains("notificationclick"), "{sw}");
526- let (status, manifest) = send(&fx.router, "GET", "/manifest.webmanifest", None, None).await;
527- assert_eq!(status, 200);
528- assert!(
529- manifest.contains("\"display\": \"standalone\""),
530- "{manifest}"
531- );
532- }
533-}
crates/forge-web/assets/icons/apple-touch-icon.pngdeleted+0 -0

Binary file changed

crates/forge-web/assets/icons/icon-192.pngdeleted+0 -0

Binary file changed

crates/forge-web/assets/icons/icon-512.pngdeleted+0 -0

Binary file changed

crates/forge-web/assets/nav.jsmodified+0 -140
@@ -210,7 +210,6 @@
210210 restoreJobs(jobs);
211211 restoreLogs(logs);
212212 syncLive();
213- syncPush();
214213 syncTick();
215214 syncRel();
216215 syncBannerExpiry();
@@ -810,7 +809,6 @@
810809 closeLive();
811810 });
812811 }
813- if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); }
814812
815813 // The form to send a queued change on: the form itself, or after a swap the one with the same action.
816814 function resend(form) {
@@ -2611,143 +2609,6 @@
26112609 area.setSelectionRange(start + block.length, start + block.length);
26122610 });
26132611
2614- // Web Push on this device (the notification settings card, [data-push]). The server renders every
2615- // state message with a data-push-state attribute, hidden; this picks which ones show from the
2616- // browser's own state: secure context, support, iOS install, permission and the subscription. The
2617- // service worker (/sw.js, served at the origin root) is registered only when the user turns push on.
2618- function pushSet(el, on) {
2619- el.hidden = !on;
2620- el.style.display = on ? '' : 'none';
2621- }
2622-
2623- function pushCard() { return document.querySelector('[data-push]'); }
2624-
2625- function pushShow(card, name, on) {
2626- card.querySelectorAll('[data-push-state="' + name + '"]').forEach(function (el) { pushSet(el, on); });
2627- }
2628-
2629- function pushActions(card, enable, disable) {
2630- card.querySelectorAll('[data-push-action="enable"]').forEach(function (el) { pushSet(el, enable); });
2631- card.querySelectorAll('[data-push-action="disable"]').forEach(function (el) { pushSet(el, disable); });
2632- }
2633-
2634- function pushBase64ToBytes(text) {
2635- var pad = '==='.slice((text.length + 3) % 4);
2636- var raw = atob((text + pad).replace(/-/g, '+').replace(/_/g, '/'));
2637- var out = new Uint8Array(raw.length);
2638- for (var i = 0; i < raw.length; i++) { out[i] = raw.charCodeAt(i); }
2639- return out;
2640- }
2641-
2642- function pushBytesToBase64(buffer) {
2643- var bytes = new Uint8Array(buffer);
2644- var text = '';
2645- for (var i = 0; i < bytes.length; i++) { text += String.fromCharCode(bytes[i]); }
2646- return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
2647- }
2648-
2649- function pushCsrf(card) {
2650- var input = card.querySelector('input[name="csrf"]');
2651- return input ? input.value : '';
2652- }
2653-
2654- function pushIos() {
2655- var standalone = window.navigator.standalone === true || (window.matchMedia && matchMedia('(display-mode: standalone)').matches);
2656- return /iPhone|iPad|iPod/.test(navigator.userAgent) && !standalone;
2657- }
2658-
2659- function syncPush() {
2660- var card = pushCard();
2661- if (!card) { return; }
2662- ['unsupported', 'https', 'ios', 'denied', 'error', 'on', 'off'].forEach(function (name) { pushShow(card, name, false); });
2663- pushActions(card, false, false);
2664- if (!window.isSecureContext) { pushShow(card, 'https', true); return; }
2665- if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) {
2666- pushShow(card, 'unsupported', true);
2667- return;
2668- }
2669- if (pushIos()) { pushShow(card, 'ios', true); return; }
2670- if (Notification.permission === 'denied') { pushShow(card, 'denied', true); return; }
2671- navigator.serviceWorker.getRegistration('/sw.js').then(function (reg) {
2672- return reg ? reg.pushManager.getSubscription() : null;
2673- }).then(function (sub) {
2674- if (!pushCard() || pushCard() !== card) { return; }
2675- pushShow(card, sub ? 'on' : 'off', true);
2676- pushActions(card, !sub, !!sub);
2677- }).catch(function () {
2678- pushShow(card, 'error', true);
2679- });
2680- }
2681-
2682- // Turns push on for this browser: permission, service worker, subscription, then the server
2683- // records the device. The device list refreshes through the page's event stream.
2684- async function pushEnable(card) {
2685- try {
2686- if ((await Notification.requestPermission()) !== 'granted') { return syncPush(); }
2687- var reg = await navigator.serviceWorker.register('/sw.js');
2688- await navigator.serviceWorker.ready;
2689- var keyRes = await fetch('/push/vapid-key', { credentials: 'same-origin', headers: { accept: 'application/json' } });
2690- if (!keyRes.ok) { throw new Error('vapid key ' + keyRes.status); }
2691- var key = (await keyRes.json()).public_key;
2692- // A subscription made with another key cannot be reused: drop it on the server and in the browser.
2693- var old = await reg.pushManager.getSubscription();
2694- if (old) { await pushPost(card, '/push/unsubscribe', { endpoint: old.endpoint }); await old.unsubscribe(); }
2695- var sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: pushBase64ToBytes(key) });
2696- var saved = await pushPost(card, '/push/subscribe', {
2697- endpoint: sub.endpoint,
2698- p256dh: pushBytesToBase64(sub.getKey('p256dh')),
2699- auth: pushBytesToBase64(sub.getKey('auth'))
2700- });
2701- if (!saved.ok) { throw new Error('subscribe ' + saved.status); }
2702- syncPush();
2703- } catch (e) {
2704- syncPush();
2705- var error = card.querySelector('[data-push-state="error"]');
2706- if (error) { pushSet(error, true); }
2707- }
2708- }
2709-
2710- async function pushDisable(card) {
2711- try {
2712- var reg = await navigator.serviceWorker.getRegistration('/sw.js');
2713- var sub = reg ? await reg.pushManager.getSubscription() : null;
2714- if (sub) {
2715- await pushPost(card, '/push/unsubscribe', { endpoint: sub.endpoint });
2716- await sub.unsubscribe();
2717- }
2718- } catch (e) {
2719- // Nothing to undo in the browser; the page below shows the state as it is now.
2720- }
2721- syncPush();
2722- }
2723-
2724- function pushPost(card, url, fields) {
2725- var body = new URLSearchParams();
2726- body.set('csrf', pushCsrf(card));
2727- Object.keys(fields).forEach(function (k) { body.set(k, fields[k]); });
2728- return fetch(url, { method: 'POST', body: body, credentials: 'same-origin' });
2729- }
2730-
2731- document.addEventListener('click', function (e) {
2732- var button = e.target && e.target.closest ? e.target.closest('[data-push-action]') : null;
2733- if (!button) { return; }
2734- var card = pushCard();
2735- if (!card || !card.contains(button)) { return; }
2736- e.preventDefault();
2737- if (button.getAttribute('data-push-action') === 'enable') { pushEnable(card); }
2738- else { pushDisable(card); }
2739- });
2740-
2741- // The service worker asks an open tab to show a notification's link in place.
2742- if ('serviceWorker' in navigator) {
2743- navigator.serviceWorker.addEventListener('message', function (e) {
2744- var data = e.data;
2745- if (data && data.type === 'forge-navigate' && typeof data.url === 'string' && data.url.charAt(0) === '/' && data.url.charAt(1) !== '/') {
2746- go(data.url);
2747- }
2748- });
2749- }
2750-
27512612 // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of
27522613 // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in
27532614 // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose
@@ -3214,7 +3075,6 @@
32143075 syncLog();
32153076 followTail();
32163077 syncLive();
3217- syncPush();
32183078 syncTick();
32193079 syncRel();
32203080 syncBannerExpiry();
crates/forge-web/assets/offline.htmldeleted+0 -21
@@ -1,21 +0,0 @@
1-<!doctype html>
2-<html lang="en">
3-<head>
4-<meta charset="utf-8">
5-<meta name="viewport" content="width=device-width, initial-scale=1">
6-<meta name="referrer" content="same-origin">
7-<meta name="robots" content="noindex">
8-<title>Forge</title>
9-<link rel="stylesheet" href="/assets/main.css">
10-<script src="/assets/offline.js" defer="defer"></script>
11-</head>
12-<body>
13-<main class="link-offline" role="status" aria-live="polite">
14-<p class="link-offline-mark">Forge</p>
15-<p class="link-offline-text" lang="en">Server restarting&hellip;</p>
16-<p class="link-offline-text" lang="tr">Sunucu yeniden başlıyor&hellip;</p>
17-<p class="link-offline-sub" lang="en">This page loads again by itself when the server is back.</p>
18-<p class="link-offline-sub" lang="tr">Sunucu geri gelince bu sayfa kendiliğinden yeniden yüklenir.</p>
19-</main>
20-</body>
21-</html>
crates/forge-web/assets/offline.jsdeleted+0 -28
@@ -1,28 +0,0 @@
1-// Offline page (served by the service worker when a page load finds the server down). Shows the
2-// line in the browser's language, then reloads once the server answers again. Nothing else runs here.
3-(function () {
4- 'use strict';
5- var want = /^tr\b/i.test(navigator.language || '') ? 'tr' : 'en';
6- document.querySelectorAll('.link-offline [lang]').forEach(function (el) {
7- if (el.getAttribute('lang') !== want) { el.hidden = true; }
8- });
9-
10- if (!window.EventSource) { return; }
11- // Opens the stream again after a drop. The browser retries by itself, except when a proxy answers
12- // with an error (EventSource then closes for good): that case is retried here, 1, 2, then 3 s.
13- function keepOpen(url, onOpen) {
14- var delay = 1000;
15- function connect() {
16- var es = new EventSource(url);
17- es.onopen = function () { delay = 1000; onOpen(); };
18- es.onerror = function () {
19- if (es.readyState !== EventSource.CLOSED) { return; }
20- es.close();
21- setTimeout(connect, delay);
22- delay = Math.min(delay + 1000, 3000);
23- };
24- }
25- connect();
26- }
27- keepOpen('/-/alive', function () { location.reload(); });
28-})();
crates/forge-web/assets/sw.jsdeleted+0 -100
@@ -1,100 +0,0 @@
1-// Forge service worker. Served at /sw.js, so its scope is the whole origin. It shows Web Push
2-// notifications while no tab is open and opens the link of a clicked one. No inline code. The only
3-// thing it caches is the offline page: app pages are always fetched fresh. A full page load that
4-// finds the server down (or a proxy answering 502, 503 or 504 while forge restarts) gets that page
5-// instead of the browser's error page. Everything else passes straight through to the network.
6-
7-// Bump the version when the offline page changes, so the new one is precached on install.
8-var OFFLINE_CACHE = 'forge-offline-v2';
9-var OFFLINE_URL = '/assets/offline.html';
10-// The offline page and the two files it loads. They are precached: while the server is down the
11-// browser could not fetch them for the offline page otherwise.
12-var OFFLINE_FILES = [OFFLINE_URL, '/assets/offline.js', '/assets/main.css'];
13-var RESTART_STATUS = [502, 503, 504];
14-
15-self.addEventListener('install', function (event) {
16- event.waitUntil(
17- caches.open(OFFLINE_CACHE)
18- .then(function (cache) { return cache.addAll(OFFLINE_FILES.map(function (u) { return new Request(u, { cache: 'reload' }); })); })
19- .catch(function () { /* the server is down: the page is fetched again on the next install */ })
20- .then(function () { return self.skipWaiting(); })
21- );
22-});
23-
24-self.addEventListener('activate', function (event) {
25- event.waitUntil((async function () {
26- var names = await caches.keys();
27- await Promise.all(names.filter(function (n) { return n.indexOf('forge-offline-') === 0 && n !== OFFLINE_CACHE; })
28- .map(function (n) { return caches.delete(n); }));
29- await self.clients.claim();
30- })());
31-});
32-
33-// Navigations only, and only GET: the response is the network's, unless the network failed or the
34-// server is restarting. Subresources, the event stream and form posts are not touched, except the
35-// three offline-page files above (bare URLs, no query): network first, the precache when it fails.
36-self.addEventListener('fetch', function (event) {
37- var req = event.request;
38- var asset = new URL(req.url);
39- if (req.method === 'GET' && req.mode !== 'navigate' && asset.origin === self.location.origin &&
40- asset.search === '' && OFFLINE_FILES.indexOf(asset.pathname) >= 0) {
41- event.respondWith((async function () {
42- var res = null;
43- try { res = await fetch(req); } catch (e) { res = null; }
44- if (res && RESTART_STATUS.indexOf(res.status) < 0) { return res; }
45- var cached = await caches.match(asset.pathname);
46- return cached || res || Response.error();
47- })());
48- return;
49- }
50- if (req.mode !== 'navigate' || req.method !== 'GET') { return; }
51- event.respondWith((async function () {
52- var res = null;
53- try {
54- res = await fetch(req);
55- } catch (e) {
56- res = null;
57- }
58- if (res && RESTART_STATUS.indexOf(res.status) < 0) { return res; }
59- var offline = await caches.match(OFFLINE_URL);
60- return offline || res || Response.error();
61- })());
62-});
63-
64-self.addEventListener('push', function (event) {
65- var data = {};
66- try {
67- data = event.data ? event.data.json() : {};
68- } catch (e) {
69- data = {};
70- }
71- var title = typeof data.title === 'string' && data.title ? data.title : 'Forge';
72- var options = {
73- body: typeof data.body === 'string' ? data.body : '',
74- tag: typeof data.tag === 'string' ? data.tag : undefined,
75- icon: '/assets/icons/icon-192.png',
76- badge: '/assets/icons/icon-192.png',
77- data: { url: typeof data.url === 'string' ? data.url : '/notifications' }
78- };
79- event.waitUntil(self.registration.showNotification(title, options));
80-});
81-
82-// Focuses an open Forge tab and asks it to soft-navigate to the link, or opens a new window.
83-self.addEventListener('notificationclick', function (event) {
84- event.notification.close();
85- var raw = event.notification.data && event.notification.data.url;
86- var target = typeof raw === 'string' && raw.charAt(0) === '/' && raw.charAt(1) !== '/' ? raw : '/notifications';
87- var url = new URL(target, self.location.origin).href;
88- event.waitUntil((async function () {
89- var windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
90- for (var i = 0; i < windows.length; i++) {
91- var client = windows[i];
92- if (new URL(client.url).origin === self.location.origin) {
93- await client.focus();
94- client.postMessage({ type: 'forge-navigate', url: target });
95- return;
96- }
97- }
98- await self.clients.openWindow(url);
99- })());
100-});
crates/forge-web/src/boot.rsmodified+0 -1
@@ -126,7 +126,6 @@ pub async fn serve(
126126 runner_logs: Arc::new(forge_web_app::ci::runner_log::RunnerLogs::default()),
127127 runner_metrics: Arc::new(forge_web_app::ci::runner_metrics::RunnerMetrics::default()),
128128 live: Arc::new(forge_web_app::live::LiveHub::default()),
129- push_live: Arc::new(forge_web_app::web_push::PushLive::default()),
130129 packages_live: Arc::new(forge_web_app::packages_live::PackagesLive::default()),
131130 };
132131 if let Err(e) = forge_web_app::signatures::rebuild_allowed_signers(&state).await {
crates/forge-web/src/routes.snapmodified+0 -13
@@ -285,13 +285,8 @@ route /assets/fonts/ibm-plex-mono-2.5.0-400.woff2 Only([GET])
285285 route /assets/fonts/ibm-plex-mono-2.5.0-500.woff2 Only([GET])
286286 route /assets/fonts/ibm-plex-mono-2.5.0-600.woff2 Only([GET])
287287 route /assets/highlight.css Only([GET])
288-route /assets/icons/apple-touch-icon.png Only([GET])
289-route /assets/icons/icon-192.png Only([GET])
290-route /assets/icons/icon-512.png Only([GET])
291288 route /assets/main.css Only([GET])
292289 route /assets/nav.js Only([GET])
293-route /assets/offline.html Only([GET])
294-route /assets/offline.js Only([GET])
295290 route /attachments/{id}/{name} Only([GET])
296291 route /avatars/{username} Only([GET])
297292 route /explore/events Only([GET])
@@ -303,7 +298,6 @@ route /import/{job_id}/retry Only([POST])
303298 route /login/passkey/begin Only([POST])
304299 route /login/passkey/finish Only([POST])
305300 route /logout Only([POST])
306-route /manifest.webmanifest Only([GET])
307301 route /needs-you/events Only([GET])
308302 route /needs-you/runs/dismiss Only([POST])
309303 route /notifications/admin/{admin_note}/open Only([GET])
@@ -335,9 +329,6 @@ route /org/{org}/teams/{team}/members/remove Only([POST])
335329 route /org/{org}/teams/{team}/repos/add Only([POST])
336330 route /org/{org}/teams/{team}/repos/remove Only([POST])
337331 route /org/{org}/teams/{team}/update Only([POST])
338-route /push/subscribe Only([POST])
339-route /push/unsubscribe Only([POST])
340-route /push/vapid-key Only([GET])
341332 route /review-requests/events Only([GET])
342333 route /settings/appearance Only([POST])
343334 route /settings/events Only([GET])
@@ -348,9 +339,6 @@ route /settings/export/{export_id}/download Only([GET])
348339 route /settings/gpg/delete Only([POST])
349340 route /settings/keys/delete Only([POST])
350341 route /settings/notifications Only([POST])
351-route /settings/notifications/push/events Only([GET])
352-route /settings/notifications/push/remove Only([POST])
353-route /settings/notifications/push/test Only([POST])
354342 route /settings/pins Only([GET])
355343 route /settings/pins Only([POST])
356344 route /settings/profile/avatar/delete Only([POST])
@@ -368,7 +356,6 @@ route /settings/tokens/delete Only([POST])
368356 route /snippets/events Only([GET])
369357 route /snippets/{id}/delete Only([POST])
370358 route /snippets/{id}/events Only([GET])
371-route /sw.js Only([GET])
372359 route /theme/custom.css Only([GET])
373360 route /users/{username}/events Only([GET])
374361 route /v2/ Only([GET])
docs/architecture.mdmodified+1 -2
@@ -296,8 +296,7 @@ The release list and release pages follow `RepoReleases` (`/{owner}/{repo}/relea
296296 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`).
297297
298298 - 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.
299-- 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.
300-- 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.
299+- 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.
301300
302301 ## 6. Authorization model
303302
docs/notifications.mdmodified+1 -62
@@ -1,65 +1,4 @@
11 # Notifications
22
33 Forge keeps an inbox of notifications for each user (the bell in the top bar). The same
4-notifications can also reach you by email, and by Web Push on your devices.
5-
6-## Web Push
7-
8-Web Push delivers a notification to a device even when no Forge tab is open. It works in
9-Chromium-based browsers, Firefox and Safari, on desktop and on Android. On iPhone and iPad it works
10-only for an app installed to the Home Screen.
11-
12-### Requirements
13-
14-- **HTTPS.** Browsers only offer push on a secure origin. Serve Forge over HTTPS (the usual
15- reverse-proxy setup). `localhost` also counts as secure for testing.
16-- **iOS and iPadOS.** Open Forge in Safari, use Share, then Add to Home Screen, and open Forge from
17- that icon. Then turn push on in the notification settings. Safari in a normal tab cannot receive
18- push. iOS 16.4 or later is needed.
19-- **Permission.** The browser asks for permission the first time you turn push on. If you refused,
20- allow notifications for the site in the browser's site settings and try again.
21-
22-### Turning it on
23-
24-1. Open **Settings, Notifications**.
25-2. Under **Push notifications on this device**, choose **Turn on for this device**, then allow
26- notifications when the browser asks.
27-3. Choose **Send test notification** to check that the device gets one.
28-
29-Each browser profile, and each installed app, is a separate device. The **Devices** list shows
30-every device with push on, when it was added and when it last received a notification. Remove a
31-device there to stop its notifications; **Turn off for this device** does the same for the device
32-you are using.
33-
34-### What is sent
35-
36-A notification carries a short title (for example `owner/repo#12`), a one-line body (the activity
37-and the start of the title, at most 140 characters) and the link it opens. Nothing else is sent: no
38-token, no email address and no body text. The push service sees that a message was delivered to
39-your device, as with any push service.
40-
41-Only notifications that reach your inbox are pushed. The same rules apply: you hear about activity
42-on threads you follow, when you are mentioned, assigned or asked to review, and so on. Watching a
43-repo or ignoring a thread changes what reaches your inbox, and so what is pushed. Site admin alerts
44-are pushed the same way.
45-
46-Notifications on a lock screen can show the title of a private repository. Turn push off for a
47-device you share.
48-
49-### Devices that stop working
50-
51-A push service answers `404` or `410` for a subscription that no longer exists, for example after
52-the browser was reset or the app was uninstalled. Forge removes such a device by itself. A device
53-that keeps failing is kept, so a temporary outage does not drop it.
54-
55-### Operator notes
56-
57-- Forge creates one VAPID key pair the first time push is used and stores it in the database. The
58- private key is sealed with the instance key (`data_dir/forge.key`). Keep both in your backups: a
59- restore that loses the VAPID key makes every device subscribe again.
60-- The VAPID contact is the `base_url` of the instance when it is an `https` URL. Behind plain HTTP
61- the contact falls back to `https://localhost`.
62-- Pushes go out from a background task and never delay the request that caused them. The server
63- makes outgoing requests to the push services, so it needs outbound HTTPS.
64-- Each account can turn push on for at most 20 devices.
65-- The service worker is served at `/sw.js`, the web app manifest at `/manifest.webmanifest`.
4+notifications can also reach you by email.