From 8a4b8e735e86f1bc40997b3c9572d005a4aefa01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 21 Oct 2026 21:53:15 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20web=20push=20notifications?= =?UTF-8?q?=20with=20a=20service=20worker=20and=20per-device=20settings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each inbox notification also goes to the user's devices that turned push on. Pushes are encrypted with web-push-native (RFC 8291, RFC 8292), sent from a spawned task, and carry only a short title, body and link. Devices are managed on the notifications settings page, which updates live. Adds a service worker at /sw.js, a web app manifest and icons. --- Cargo.lock | 606 +++++++++++++++--- Cargo.toml | 2 + .../forge-core/migrations/0061_web_push.sql | 24 + crates/forge-core/src/store/migrate.rs | 1 + crates/forge-core/src/store/mod.rs | 1 + crates/forge-core/src/store/web_push.rs | 209 ++++++ crates/forge-web/Cargo.toml | 1 + .../assets/icons/apple-touch-icon.png | Bin 0 -> 729 bytes crates/forge-web/assets/icons/icon-192.png | Bin 0 -> 810 bytes crates/forge-web/assets/icons/icon-512.png | Bin 0 -> 2514 bytes crates/forge-web/assets/nav.js | 139 ++++ crates/forge-web/assets/sw.js | 49 ++ crates/forge-web/src/alerts.rs | 8 + crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/i18n/mod.rs | 1 + crates/forge-web/src/i18n/push.rs | 122 ++++ crates/forge-web/src/main.rs | 1 + crates/forge-web/src/notify.rs | 84 ++- crates/forge-web/src/pages/mod.rs | 1 + crates/forge-web/src/pages/push.rs | 601 +++++++++++++++++ .../src/pages/settings_notifications.rs | 94 ++- .../forge-web/src/pages/settings_security.rs | 1 + crates/forge-web/src/state.rs | 2 + crates/forge-web/src/test_support.rs | 1 + crates/forge-web/src/views/mod.rs | 4 + crates/forge-web/src/web_push/crypto.rs | 177 +++++ crates/forge-web/src/web_push/mod.rs | 567 ++++++++++++++++ docs/notifications.md | 65 ++ style/main.scss | 49 ++ 29 files changed, 2730 insertions(+), 81 deletions(-) create mode 100644 crates/forge-core/migrations/0061_web_push.sql create mode 100644 crates/forge-core/src/store/web_push.rs create mode 100644 crates/forge-web/assets/icons/apple-touch-icon.png create mode 100644 crates/forge-web/assets/icons/icon-192.png create mode 100644 crates/forge-web/assets/icons/icon-512.png create mode 100644 crates/forge-web/assets/sw.js create mode 100644 crates/forge-web/src/i18n/push.rs create mode 100644 crates/forge-web/src/pages/push.rs create mode 100644 crates/forge-web/src/web_push/crypto.rs create mode 100644 crates/forge-web/src/web_push/mod.rs create mode 100644 docs/notifications.md diff --git a/Cargo.lock b/Cargo.lock index 05df56d..0328713 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,6 +90,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "aes-keywrap" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf71a903b87eeef4903e7077cc9689f0c8449e093395db09dc48d1a39934e770" +dependencies = [ + "aes 0.9.3", + "byteorder", +] + [[package]] name = "ahash" version = "0.8.12" @@ -410,6 +420,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base16ct" version = "1.0.0" @@ -507,6 +523,12 @@ dependencies = [ "which", ] +[[package]] +name = "binstring" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cff57e3fb66fb8077cb7f5de37442fff99b4ee99d71e6b946ad9b6b7246c27c" + [[package]] name = "bit-set" version = "0.8.0" @@ -564,6 +586,16 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "blake2b_simd" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3560a7b1951efe814fcd721938313adc56753ca39f4b23847d7e9a2402f5dbff" +dependencies = [ + "arrayvec", + "constant_time_eq", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -919,6 +951,17 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "coarsetime" +version = "0.1.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae63702c5627c75addbfb1ea9d1b3842205a6ffd43e4cce884a2a9eb1828fd7" +dependencies = [ + "libc", + "wasix", + "wasm-bindgen", +] + [[package]] name = "codemap" version = "0.1.3" @@ -998,6 +1041,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" @@ -1025,6 +1074,12 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "cookie" version = "0.18.2" @@ -1168,6 +1223,18 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array 0.14.7", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-bigint" version = "0.7.5" @@ -1213,7 +1280,7 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f" dependencies = [ - "crypto-bigint", + "crypto-bigint 0.7.5", "rand_core 0.10.1", ] @@ -1251,6 +1318,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "ct-codecs" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd" + [[package]] name = "ctr" version = "0.9.2" @@ -1453,14 +1526,25 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468 0.7.0", + "zeroize", +] + [[package]] name = "der" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" dependencies = [ - "const-oid", - "pem-rfc7468", + "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] @@ -1555,6 +1639,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -1566,7 +1651,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", ] @@ -1609,29 +1694,64 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der 0.7.10", + "digest 0.10.7", + "elliptic-curve 0.13.8", + "rfc6979 0.4.0", + "signature 2.2.0", + "spki 0.7.3", +] + [[package]] name = "ecdsa" version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" dependencies = [ - "der", + "der 0.8.2", "digest 0.11.3", - "elliptic-curve", - "rfc6979", - "signature", - "spki", + "elliptic-curve 0.14.1", + "rfc6979 0.6.0", + "signature 3.0.0", + "spki 0.8.1", "zeroize", ] +[[package]] +name = "ece-native" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6911cc97c62febd8cbcb2cb49ed21c58ccd418a80c43f20df4973ee08484e65d" +dependencies = [ + "aes-gcm 0.10.3", + "hkdf 0.12.4", + "sha2 0.10.9", +] + [[package]] name = "ed25519" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" dependencies = [ - "pkcs8", - "signature", + "pkcs8 0.11.0", + "signature 3.0.0", +] + +[[package]] +name = "ed25519-compact" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1454db4f2edb7f0e8fe0c5b375b0c978fc63244cc9f010d160e417eb10139aa8" +dependencies = [ + "ct-codecs", + "getrandom 0.4.3", ] [[package]] @@ -1645,7 +1765,7 @@ dependencies = [ "rand_core 0.10.1", "serde", "sha2 0.11.1", - "signature", + "signature 3.0.0", "subtle", "zeroize", ] @@ -1662,24 +1782,45 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct 0.2.0", + "crypto-bigint 0.5.5", + "digest 0.10.7", + "ff 0.13.1", + "generic-array 0.14.7", + "group 0.13.0", + "hkdf 0.12.4", + "pem-rfc7468 0.7.0", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sec1 0.7.3", + "subtle", + "zeroize", +] + [[package]] name = "elliptic-curve" version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" dependencies = [ - "base16ct", - "crypto-bigint", + "base16ct 1.0.0", + "crypto-bigint 0.7.5", "crypto-common 0.2.2", "digest 0.11.3", - "ff", - "group", + "ff 0.14.0", + "group 0.14.0", "hkdf 0.13.0", "hybrid-array", - "pem-rfc7468", - "pkcs8", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", "rand_core 0.10.1", - "sec1", + "sec1 0.8.1", "subtle", "zeroize", ] @@ -1875,6 +2016,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "ff" version = "0.14.0" @@ -2126,6 +2277,7 @@ dependencies = [ "tracing", "tracing-subscriber", "ulid", + "web-push-native", "webauthn-authenticator-rs", "webauthn-rs", "webauthn-rs-proto", @@ -2289,6 +2441,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -3211,13 +3364,24 @@ dependencies = [ "rand 0.8.8", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff 0.13.1", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "group" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" dependencies = [ - "ff", + "ff 0.14.0", "rand_core 0.10.1", "subtle", ] @@ -3363,6 +3527,33 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "hmac-sha1-compact" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ed9b23855291da44e7e84616e19dc0d969c3580e14ffa6b759f28775e26afc1" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac-sha256" +version = "1.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad320b3b96fb2a455a0726d16efe0a5afdbd34b71dea5bc53b05ea057714d4e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac-sha512" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66de62217b456dfbbba2bed965a134a4df57c48f0eac4c772018aee528e72244" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "home" version = "0.5.12" @@ -4005,6 +4196,46 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jwt-simple" +version = "0.12.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06a4207b9d1f423858853fb9ee8b34aebc2b661f3b446ca4efda46c4b3700a2f" +dependencies = [ + "anyhow", + "binstring", + "blake2b_simd", + "coarsetime", + "ct-codecs", + "ed25519-compact", + "hmac-sha1-compact", + "hmac-sha256", + "hmac-sha512", + "k256", + "p256 0.13.2", + "p384 0.13.1", + "rand 0.8.8", + "serde", + "serde_json", + "superboring", + "thiserror 2.0.21", + "zeroize", +] + +[[package]] +name = "k256" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "once_cell", + "sha2 0.10.9", + "signature 2.2.0", +] + [[package]] name = "keccak" version = "0.2.2" @@ -4054,6 +4285,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin 0.9.9", +] [[package]] name = "lazycell" @@ -4440,6 +4674,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ml-dsa" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "add6b9d92e496f16f4526d68ff29da1483aba4b119baeab8bed3b9e3544a6f3d" +dependencies = [ + "const-oid 0.10.2", + "crypto-common 0.2.2", + "ctutils", + "hybrid-array", + "module-lattice", + "pkcs8 0.11.0", + "shake", + "signature 3.0.0", +] + [[package]] name = "ml-kem" version = "0.3.2" @@ -4449,7 +4699,7 @@ dependencies = [ "hybrid-array", "kem", "module-lattice", - "pkcs8", + "pkcs8 0.11.0", "rand_core 0.10.1", "sha3 0.11.0", ] @@ -4632,6 +4882,22 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -4658,6 +4924,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -4665,6 +4941,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -4885,30 +5162,54 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", + "sha2 0.10.9", +] + [[package]] name = "p256" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ - "ecdsa", - "elliptic-curve", + "ecdsa 0.17.0", + "elliptic-curve 0.14.1", "primefield", - "primeorder", + "primeorder 0.14.0", "sha2 0.11.1", ] +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", + "sha2 0.10.9", +] + [[package]] name = "p384" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" dependencies = [ - "ecdsa", - "elliptic-curve", + "ecdsa 0.17.0", + "elliptic-curve 0.14.1", "fiat-crypto", "primefield", - "primeorder", + "primeorder 0.14.0", "sha2 0.11.1", ] @@ -4918,11 +5219,11 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ad64cc32c2dc466317c12ee5853e61f159f9eab1fe7efade0395dc2e7b43449" dependencies = [ - "base16ct", - "ecdsa", - "elliptic-curve", + "base16ct 1.0.0", + "ecdsa 0.17.0", + "elliptic-curve 0.14.1", "primefield", - "primeorder", + "primeorder 0.14.0", "sha2 0.11.1", ] @@ -4941,7 +5242,7 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0786409b5aaa884655c9b4065681db0835db0cc185a6fb19fb17a5d38656866" dependencies = [ - "base16ct", + "base16ct 1.0.0", "byteorder", "bytes", "delegate", @@ -5034,6 +5335,15 @@ dependencies = [ "hmac 0.13.0", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "pem-rfc7468" version = "1.0.0" @@ -5200,14 +5510,25 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der 0.7.10", + "pkcs8 0.10.2", + "spki 0.7.3", +] + [[package]] name = "pkcs1" version = "0.8.0-rc.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "986d2e952779af96ea048f160fd9194e1751b4faea78bcf3ceb456efe008088e" dependencies = [ - "der", - "spki", + "der 0.8.2", + "spki 0.8.1", ] [[package]] @@ -5219,12 +5540,22 @@ dependencies = [ "aes 0.9.3", "aes-gcm 0.11.1", "cbc", - "der", + "der 0.8.2", "pbkdf2", "rand_core 0.10.1", "scrypt", "sha2 0.11.1", - "spki", + "spki 0.8.1", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der 0.7.10", + "spki 0.7.3", ] [[package]] @@ -5233,10 +5564,10 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" dependencies = [ - "der", + "der 0.8.2", "pkcs5", "rand_core 0.10.1", - "spki", + "spki 0.8.1", ] [[package]] @@ -5403,21 +5734,30 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" dependencies = [ - "crypto-bigint", + "crypto-bigint 0.7.5", "crypto-common 0.2.2", - "ff", + "ff 0.14.0", "rand_core 0.10.1", "subtle", "zeroize", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve 0.13.8", +] + [[package]] name = "primeorder" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" dependencies = [ - "elliptic-curve", + "elliptic-curve 0.14.1", "once_cell", "primefield", "serdect", @@ -5893,13 +6233,23 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + [[package]] name = "rfc6979" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" dependencies = [ - "crypto-bigint", + "crypto-bigint 0.7.5", "hmac 0.13.0", ] @@ -5938,22 +6288,43 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1 0.7.5", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sha2 0.10.9", + "signature 2.2.0", + "spki 0.7.3", + "subtle", + "zeroize", +] + [[package]] name = "rsa" version = "0.10.0-rc.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30b2aa4ba0d89f73d1e332df05be0eeab8840351c36ca5654341dfdb57bb3caf" dependencies = [ - "const-oid", - "crypto-bigint", + "const-oid 0.10.2", + "crypto-bigint 0.7.5", "crypto-primes", "digest 0.11.3", - "pkcs1", - "pkcs8", + "pkcs1 0.8.0-rc.4", + "pkcs8 0.11.0", "rand_core 0.10.1", "sha2 0.11.1", - "signature", - "spki", + "signature 3.0.0", + "spki 0.8.1", "zeroize", ] @@ -5981,16 +6352,16 @@ dependencies = [ "bytes", "cbc", "cipher 0.5.2", - "crypto-bigint", + "crypto-bigint 0.7.5", "ctr 0.10.1", "curve25519-dalek", "data-encoding", "delegate", - "der", + "der 0.8.2", "digest 0.11.3", - "ecdsa", + "ecdsa 0.17.0", "ed25519-dalek", - "elliptic-curve", + "elliptic-curve 0.14.1", "enum_dispatch", "flate2", "futures", @@ -6006,28 +6377,28 @@ dependencies = [ "ml-kem", "module-lattice", "num-bigint 0.5.1", - "p256", - "p384", + "p256 0.14.0", + "p384 0.14.0", "p521", "pageant", "pbkdf2", - "pkcs1", + "pkcs1 0.8.0-rc.4", "pkcs5", - "pkcs8", + "pkcs8 0.11.0", "polyval 0.7.3", "rand 0.10.3", "rand_core 0.10.1", - "rsa", + "rsa 0.10.0-rc.18", "russh-cryptovec", "russh-util", "salsa20", "scrypt", - "sec1", + "sec1 0.8.1", "sha1 0.11.0", "sha2 0.11.1", "sha3 0.12.0", - "signature", - "spki", + "signature 3.0.0", + "spki 0.8.1", "ssh-encoding", "ssh-key", "subtle", @@ -6315,15 +6686,29 @@ dependencies = [ "sha2 0.11.1", ] +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct 0.2.0", + "der 0.7.10", + "generic-array 0.14.7", + "pkcs8 0.10.2", + "subtle", + "zeroize", +] + [[package]] name = "sec1" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" dependencies = [ - "base16ct", + "base16ct 1.0.0", "ctutils", - "der", + "der 0.8.2", "hybrid-array", "subtle", "zeroize", @@ -6499,7 +6884,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" dependencies = [ - "base16ct", + "base16ct 1.0.0", "serde", ] @@ -6589,6 +6974,17 @@ dependencies = [ "sponge-cursor", ] +[[package]] +name = "shake" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a" +dependencies = [ + "digest 0.11.3", + "keccak", + "sponge-cursor", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -6656,6 +7052,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "signature" version = "3.0.0" @@ -6761,6 +7167,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der 0.7.10", +] + [[package]] name = "spki" version = "0.8.1" @@ -6768,7 +7184,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" dependencies = [ "base64ct", - "der", + "der 0.8.2", ] [[package]] @@ -6803,10 +7219,10 @@ checksum = "7b54d0ed0498daf3f78d82e00e28c8eec9d75a067c4cfbcc7a0f7d0f4077749e" dependencies = [ "base64ct", "bytes", - "crypto-bigint", + "crypto-bigint 0.7.5", "ctutils", "digest 0.11.3", - "pem-rfc7468", + "pem-rfc7468 1.0.0", "zeroize", ] @@ -6822,15 +7238,15 @@ dependencies = [ "ed25519-dalek", "hex", "hmac 0.13.0", - "p256", - "p384", + "p256 0.14.0", + "p384 0.14.0", "p521", "rand_core 0.10.1", - "rsa", - "sec1", + "rsa 0.10.0-rc.18", + "sec1 0.8.1", "sha1 0.11.0", "sha2 0.11.1", - "signature", + "signature 3.0.0", "ssh-cipher", "ssh-encoding", "zeroize", @@ -6951,6 +7367,24 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "superboring" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19706eb9c165c3c27117e8795678015277188647b03db4f7cbf9df98048e09a6" +dependencies = [ + "aes-gcm 0.11.1", + "aes-keywrap", + "getrandom 0.2.17", + "getrandom 0.4.3", + "hmac-sha1-compact", + "hmac-sha256", + "hmac-sha512", + "ml-dsa", + "rand 0.8.8", + "rsa 0.9.10", +] + [[package]] name = "symlink" version = "0.1.0" @@ -8393,6 +8827,15 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasix" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae86f02046da16a333a9129d31451423e1657737ecdafed4193838a5f54c5cfe" +dependencies = [ + "wasi", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -8462,6 +8905,23 @@ dependencies = [ "web-sys", ] +[[package]] +name = "web-push-native" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7628c93e39aeee4c0bca50ae333052b4f174c653e8fca1d0a8e34f9bc4879c0c" +dependencies = [ + "aes-gcm 0.10.3", + "base64ct", + "ece-native", + "hkdf 0.13.0", + "http", + "jwt-simple", + "p256 0.13.2", + "serde", + "sha2 0.11.1", +] + [[package]] name = "web-sys" version = "0.3.106" @@ -8896,8 +9356,8 @@ version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" dependencies = [ - "ff", - "group", + "ff 0.14.0", + "group 0.14.0", "hybrid-array", "primefield", ] diff --git a/Cargo.toml b/Cargo.toml index 6890635..d18fd27 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,6 +65,8 @@ base64 = "0.23.1" getrandom = "0.4.3" rpassword = "7.5.4" chacha20poly1305 = "0.11.0" +# Web Push (forge-web): RFC 8291 encryption and RFC 8292 VAPID, RustCrypto based, pure Rust +web-push-native = "0.5.0" # storage turso = "0.8.3" diff --git a/crates/forge-core/migrations/0061_web_push.sql b/crates/forge-core/migrations/0061_web_push.sql new file mode 100644 index 0000000..1468862 --- /dev/null +++ b/crates/forge-core/migrations/0061_web_push.sql @@ -0,0 +1,24 @@ +-- Web Push. `web_push_keys` holds the one VAPID key pair of the instance: the public key as +-- base64url (the browser's applicationServerKey) and the private key sealed with the instance key. +-- `push_subscriptions` has one row per browser or installed PWA a user enabled push on. The +-- endpoint is the push service URL, unique across accounts, so a shared browser that signs in as +-- someone else moves the row to that account. Applied by store/migrate.rs. + +CREATE TABLE web_push_keys ( + id INTEGER PRIMARY KEY CHECK (id = 1), + public_key TEXT NOT NULL, + private_key TEXT NOT NULL, + created_at TEXT NOT NULL +); + +CREATE TABLE push_subscriptions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + endpoint TEXT NOT NULL UNIQUE, + p256dh TEXT NOT NULL, + auth TEXT NOT NULL, + agent_label TEXT NOT NULL, + created_at TEXT NOT NULL, + last_success_at TEXT NULL +); +CREATE INDEX idx_push_subscriptions_user ON push_subscriptions(user_id); diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index bb2471f..b2e4f13 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -100,6 +100,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (58, include_str!("../../migrations/0058_passkeys.sql")), (59, include_str!("../../migrations/0059_admin_alerts.sql")), (60, include_str!("../../migrations/0060_runner_memory.sql")), + (61, include_str!("../../migrations/0061_web_push.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 12af619..d9ffe54 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -44,6 +44,7 @@ pub mod suspension; pub mod transfers; pub mod ui_prefs; pub mod user_delete; +pub mod web_push; pub mod webhooks; pub mod wiki; diff --git a/crates/forge-core/src/store/web_push.rs b/crates/forge-core/src/store/web_push.rs new file mode 100644 index 0000000..f6fd89d --- /dev/null +++ b/crates/forge-core/src/store/web_push.rs @@ -0,0 +1,209 @@ +//! Web Push (migration 0061): the instance's VAPID key pair and each user's push subscriptions. +//! The store keeps the private key sealed; the web crate seals and opens it with the instance key. + +use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::error::{Error, Result}; +use crate::time::now_stamp; + +/// Most devices one account may hold. A subscription past this is refused, so a client cannot +/// grow the table without bound. +pub const MAX_DEVICES: usize = 20; + +/// One browser or installed app that receives pushes for `user_id`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PushSubscription { + pub id: String, + pub user_id: String, + /// The push service URL. Unique across accounts. + pub endpoint: String, + /// The browser's public key, base64url. + pub p256dh: String, + /// The browser's auth secret, base64url. + pub auth: String, + /// A short device label such as "Chrome on Android", derived from the User-Agent. + pub agent_label: String, + pub created_at: String, + pub last_success_at: Option, +} + +const COLS: &str = "id, user_id, endpoint, p256dh, auth, agent_label, created_at, last_success_at"; + +fn map_row(row: &turso::Row) -> Result { + Ok(PushSubscription { + id: col_text(row, 0)?, + user_id: col_text(row, 1)?, + endpoint: col_text(row, 2)?, + p256dh: col_text(row, 3)?, + auth: col_text(row, 4)?, + agent_label: col_text(row, 5)?, + created_at: col_text(row, 6)?, + last_success_at: col_opt_text(row, 7)?, + }) +} + +impl Store { + /// The instance's VAPID key pair as `(public key, sealed private key)`, or `None` before the + /// first one is generated. + pub async fn web_push_keys(&self) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT public_key, private_key FROM web_push_keys WHERE id = 1", + (), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await + } + + /// Stores the VAPID key pair unless one is already stored, and returns the stored pair. Two + /// requests that race to create the first key both end up with the same one. + pub async fn save_web_push_keys( + &self, + public_key: &str, + sealed_private: &str, + ) -> Result<(String, String)> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO web_push_keys (id, public_key, private_key, created_at) \ + VALUES (1, ?1, ?2, ?3) ON CONFLICT (id) DO NOTHING", + ( + public_key.to_string(), + sealed_private.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + fetch_opt( + &conn, + "SELECT public_key, private_key FROM web_push_keys WHERE id = 1", + (), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await? + .ok_or_else(|| Error::Database("the VAPID key was not stored".into())) + } + + /// The devices of `user_id`, oldest first. + pub async fn push_subscriptions(&self, user_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {COLS} FROM push_subscriptions WHERE user_id = ?1 ORDER BY created_at, id" + ), + (user_id.to_string(),), + map_row, + ) + .await + } + + /// Adds a device for `user_id`, or refreshes the keys of the device with this endpoint. The + /// endpoint moves to `user_id` when another account held it. Refused past `MAX_DEVICES` for + /// a new endpoint. + pub async fn save_push_subscription( + &self, + user_id: &str, + endpoint: &str, + p256dh: &str, + auth: &str, + agent_label: &str, + ) -> Result { + let conn = self.inner.conn.lock().await; + let held = fetch_opt( + &conn, + "SELECT COUNT(*) FROM push_subscriptions WHERE user_id = ?1 AND endpoint != ?2", + (user_id.to_string(), endpoint.to_string()), + |row| crate::store::col_int(row, 0), + ) + .await? + .unwrap_or(0); + if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_DEVICES { + return Err(Error::Invalid(format!( + "an account can enable push on at most {MAX_DEVICES} devices" + ))); + } + conn.execute( + "INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth, agent_label, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \ + ON CONFLICT (endpoint) DO UPDATE SET user_id = excluded.user_id, \ + p256dh = excluded.p256dh, auth = excluded.auth, \ + agent_label = excluded.agent_label, created_at = excluded.created_at", + ( + new_id(), + user_id.to_string(), + endpoint.to_string(), + p256dh.to_string(), + auth.to_string(), + agent_label.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + fetch_opt( + &conn, + &format!("SELECT {COLS} FROM push_subscriptions WHERE endpoint = ?1"), + (endpoint.to_string(),), + map_row, + ) + .await? + .ok_or_else(|| Error::Database("the push subscription was not stored".into())) + } + + /// Removes the device with this id when it belongs to `user_id`. + pub async fn delete_push_subscription(&self, user_id: &str, id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "DELETE FROM push_subscriptions WHERE id = ?1 AND user_id = ?2", + (id.to_string(), user_id.to_string()), + ) + .await + .map_err(db_err)?; + Ok(n > 0) + } + + /// Removes the device with this endpoint when it belongs to `user_id`. + pub async fn delete_push_subscription_by_endpoint( + &self, + user_id: &str, + endpoint: &str, + ) -> Result { + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "DELETE FROM push_subscriptions WHERE endpoint = ?1 AND user_id = ?2", + (endpoint.to_string(), user_id.to_string()), + ) + .await + .map_err(db_err)?; + Ok(n > 0) + } + + /// Removes the device with this endpoint whoever owns it. Used when the push service says + /// the subscription is gone (404 or 410). + pub async fn delete_push_endpoint(&self, endpoint: &str) -> Result { + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "DELETE FROM push_subscriptions WHERE endpoint = ?1", + (endpoint.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(n > 0) + } + + /// Records a delivery the push service accepted. + pub async fn mark_push_delivered(&self, id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE push_subscriptions SET last_success_at = ?2 WHERE id = ?1", + (id.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} diff --git a/crates/forge-web/Cargo.toml b/crates/forge-web/Cargo.toml index bd3a02d..449edb6 100644 --- a/crates/forge-web/Cargo.toml +++ b/crates/forge-web/Cargo.toml @@ -58,6 +58,7 @@ tar.workspace = true flate2.workspace = true webauthn-rs = { version = "0.5.5", features = ["danger-allow-state-serialisation", "conditional-ui"] } webauthn-rs-proto = "0.5.5" +web-push-native.workspace = true [build-dependencies] grass.workspace = true diff --git a/crates/forge-web/assets/icons/apple-touch-icon.png b/crates/forge-web/assets/icons/apple-touch-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..870fd784806e8d31da441dcc779ddc7b7c58cbee GIT binary patch literal 729 zcmeAS@N?(olHy`uVBq!ia0y~yVAuk}9Bd2>47O+4j2IZ07I?ZihE&{oduOkoR-j1R z!>#3e*o1}O_fBGpPEO=mXkd0LOJk?&;6*RHOaK7rx=oj$8d)h>I58&1}IrIlvn`nFB&J8$mXmz7I( zO)AB2SzZ3^6`fI}x206=uvc`(x##Mw7g8^rR&lSbD)m zaO}^$zAn-F$fKVJn>XMvvgQ7^$Hz-GOz-8%tN(m+^t3b2;Ro*>+CYwKVslhRHM!;f zHtzr1WySEj5$aq)6R;t0H=T{t+WfTUwPC_S+}=ag+VVn7VZ0bBUAB7;J$5}uWb?eta0DDdsbMI-H#^)O&7dQxN}C`@cFy`ci?%}#Nt=R sUsJxX-{D%*b$;fTR=+2YWN(WrXdiO@eCU4}0|Nttr>mdKI;Vst0GU)W(*OVf literal 0 HcmV?d00001 diff --git a/crates/forge-web/assets/icons/icon-192.png b/crates/forge-web/assets/icons/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..11457d577a3b9e07463d23fc2b659b295d318339 GIT binary patch literal 810 zcmeAS@N?(olHy`uVBq!ia0y~yU^oE69Bd2>3_*8t*clj@K6<)1hE&{oduOj#wxdYH z#hH!))s7#YHicSsH}onfvPhpcnPud!ku-5h*Vfi2PyU~IvvuBq>O1$}SQ_4$QK%IDcme|vwkH!gij(p5^wC-B-$bUwj0|Ab;nv;Px;O$XJBIF5b@o}7F>!t963 zJ+`ACge#>*4*Ngh=z6GL#B%h5uw_%yk4_m!!#^&43nc24+yi**Cn{^S%|9V1(%*Ta z>+<{)(O~fhTrJuYF3(>PeSqx%Tfr~kQtlfJHyHft7v(WZGe{qJ>3>BxfjNQM;RQoX zeMc4VCdLhn4h#wm9jeug$JiJc8yG-50R|2R76v8^uEYP>N|t)tJ9n2~KfYY;f3E)g z_b*>RzpZ~0tP`uQlh+r%OxPK>^kU8{#~V0}Zg}$g!qlC6_j$^n&lmqI>9#pDYF&7p zq#48=4h(XP=#ByDQ2B4Yg%^u6@p}RxyX#c*$AZU(3Csu~Y`#XwR*4))GCD8EEU2sY zIfwZH7Yh>uqr(A)JsiRxS#Pi%VEe!!(2y;_xZd83!R$bNs>AE$`*|C9H>?%N`1)l# z;|9iE)0o!I{RfgRvzjeNQsS+;+z^BDv$Jo@mygjI-fE${zx z?-`U9EPZ(YwQ2;*7NbAa^;{}UQ4;@}?bt*axAOl#SkErNXv+UT@SlJhQ78Znnta&GRqZ)f|uVv^LBPW?*1o@O1TaS?83{1ORyF5+?uv literal 0 HcmV?d00001 diff --git a/crates/forge-web/assets/icons/icon-512.png b/crates/forge-web/assets/icons/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..c800844ea012ef2d3bbb476635d2828284d6c891 GIT binary patch literal 2514 zcmb_eZBSHI7=F&Z%kB+#;WAi4XuCR1U{WkH!YCS-B*ke0YM3d(aBC790oNKO5L%8x zNE0opl1L1imgasq%aSHGxZ}zoARoKUy$h@;9c(fPu1eBfw+()?}pTmN`5Z6F29+%-5bh z`n6q2NX7eC6u<3A;_BjyGK6;)n^)~LEUvRFBO>~QXO0z;%uMR}*XdunNc6;>zi@u2 zd|~ZY(}(Z%&Zg0GhjyJE&0(b$ zi8`oFsG*aDTP1KDsj~lZamvKJ($%HTa`i6{QOw82o z?w_1ON^Z4$Js(Isy)-kGE0}fGre4la@w~BV)0?lWq`Ke6J#taF2Pt{5h7)Jl>Rig$ z8b3%_pITEfc&WGK*mi$=y40oq{}559B0PvC=Gzt@4Zo&JuStu*q?A61WinI;Q}}vYdtR$`RjTd3@&snMcN*()gC* zbS44kYWk|=7r`0=TH_2j*%%1NJ>BwCP)wlf88pgI!6CrBW%PD0|BzBpKpd=XjRoSe zB?UiS(cLF2lBX-G%o@sp-q=`V{6`y#TECkBxu;Vk1M8=29r@$CSlW~3jg(b|2aJHF zk~Pc%c6a-<+gKd~!~V7QW}g9u;qU?3?9boZvu>pm(W`a)8J-}@cc9^;FGi|ap-W7X>6giCw=!cV1aEM@U zVvo$LeO~aAe9sMqdo9r1rWBKb>h<6V)V`|{`BhqEg?0`DWh;0li-_(ycpF$5keG;0 z3H?9_je>Y)ieR9wBsvayZwQTp{#pb$g-CnT$C>J7@f#ywSoJpmta&Lbqv=J%&i??2 CavF*N literal 0 HcmV?d00001 diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 77f2cca..c9b7d02 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -169,6 +169,7 @@ restoreJobs(jobs); syncUnread(); syncLive(); + syncPush(); syncTick(); } @@ -1013,6 +1014,143 @@ area.setSelectionRange(start + block.length, start + block.length); }); + // Web Push on this device (the notification settings card, [data-push]). The server renders every + // state message with a data-push-state attribute, hidden; this picks which ones show from the + // browser's own state: secure context, support, iOS install, permission and the subscription. The + // service worker (/sw.js, served at the origin root) is registered only when the user turns push on. + function pushSet(el, on) { + el.hidden = !on; + el.style.display = on ? '' : 'none'; + } + + function pushCard() { return document.querySelector('[data-push]'); } + + function pushShow(card, name, on) { + card.querySelectorAll('[data-push-state="' + name + '"]').forEach(function (el) { pushSet(el, on); }); + } + + function pushActions(card, enable, disable) { + card.querySelectorAll('[data-push-action="enable"]').forEach(function (el) { pushSet(el, enable); }); + card.querySelectorAll('[data-push-action="disable"]').forEach(function (el) { pushSet(el, disable); }); + } + + function pushBase64ToBytes(text) { + var pad = '==='.slice((text.length + 3) % 4); + var raw = atob((text + pad).replace(/-/g, '+').replace(/_/g, '/')); + var out = new Uint8Array(raw.length); + for (var i = 0; i < raw.length; i++) { out[i] = raw.charCodeAt(i); } + return out; + } + + function pushBytesToBase64(buffer) { + var bytes = new Uint8Array(buffer); + var text = ''; + for (var i = 0; i < bytes.length; i++) { text += String.fromCharCode(bytes[i]); } + return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); + } + + function pushCsrf(card) { + var input = card.querySelector('input[name="csrf"]'); + return input ? input.value : ''; + } + + function pushIos() { + var standalone = window.navigator.standalone === true || (window.matchMedia && matchMedia('(display-mode: standalone)').matches); + return /iPhone|iPad|iPod/.test(navigator.userAgent) && !standalone; + } + + function syncPush() { + var card = pushCard(); + if (!card) { return; } + ['unsupported', 'https', 'ios', 'denied', 'error', 'on', 'off'].forEach(function (name) { pushShow(card, name, false); }); + pushActions(card, false, false); + if (!window.isSecureContext) { pushShow(card, 'https', true); return; } + if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) { + pushShow(card, 'unsupported', true); + return; + } + if (pushIos()) { pushShow(card, 'ios', true); return; } + if (Notification.permission === 'denied') { pushShow(card, 'denied', true); return; } + navigator.serviceWorker.getRegistration('/sw.js').then(function (reg) { + return reg ? reg.pushManager.getSubscription() : null; + }).then(function (sub) { + if (!pushCard() || pushCard() !== card) { return; } + pushShow(card, sub ? 'on' : 'off', true); + pushActions(card, !sub, !!sub); + }).catch(function () { + pushShow(card, 'error', true); + }); + } + + // Turns push on for this browser: permission, service worker, subscription, then the server + // records the device. The device list refreshes through the page's event stream. + async function pushEnable(card) { + try { + if ((await Notification.requestPermission()) !== 'granted') { return syncPush(); } + var reg = await navigator.serviceWorker.register('/sw.js'); + await navigator.serviceWorker.ready; + var keyRes = await fetch('/push/vapid-key', { credentials: 'same-origin', headers: { accept: 'application/json' } }); + if (!keyRes.ok) { throw new Error('vapid key ' + keyRes.status); } + var key = (await keyRes.json()).public_key; + // A subscription made with another key cannot be reused: drop it on the server and in the browser. + var old = await reg.pushManager.getSubscription(); + if (old) { await pushPost(card, '/push/unsubscribe', { endpoint: old.endpoint }); await old.unsubscribe(); } + var sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: pushBase64ToBytes(key) }); + var saved = await pushPost(card, '/push/subscribe', { + endpoint: sub.endpoint, + p256dh: pushBytesToBase64(sub.getKey('p256dh')), + auth: pushBytesToBase64(sub.getKey('auth')) + }); + if (!saved.ok) { throw new Error('subscribe ' + saved.status); } + syncPush(); + } catch (e) { + syncPush(); + var error = card.querySelector('[data-push-state="error"]'); + if (error) { pushSet(error, true); } + } + } + + async function pushDisable(card) { + try { + var reg = await navigator.serviceWorker.getRegistration('/sw.js'); + var sub = reg ? await reg.pushManager.getSubscription() : null; + if (sub) { + await pushPost(card, '/push/unsubscribe', { endpoint: sub.endpoint }); + await sub.unsubscribe(); + } + } catch (e) { + // Nothing to undo in the browser; the page below shows the state as it is now. + } + syncPush(); + } + + function pushPost(card, url, fields) { + var body = new URLSearchParams(); + body.set('csrf', pushCsrf(card)); + Object.keys(fields).forEach(function (k) { body.set(k, fields[k]); }); + return fetch(url, { method: 'POST', body: body, credentials: 'same-origin' }); + } + + document.addEventListener('click', function (e) { + var button = e.target && e.target.closest ? e.target.closest('[data-push-action]') : null; + if (!button) { return; } + var card = pushCard(); + if (!card || !card.contains(button)) { return; } + e.preventDefault(); + if (button.getAttribute('data-push-action') === 'enable') { pushEnable(card); } + else { pushDisable(card); } + }); + + // The service worker asks an open tab to show a notification's link in place. + if ('serviceWorker' in navigator) { + navigator.serviceWorker.addEventListener('message', function (e) { + var data = e.data; + if (data && data.type === 'forge-navigate' && typeof data.url === 'string' && data.url.charAt(0) === '/' && data.url.charAt(1) !== '/') { + go(data.url); + } + }); + } + // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose @@ -1178,6 +1316,7 @@ syncLog(); followTail(); syncLive(); + syncPush(); syncTick(); window.__forgeQuery = function (href) { diff --git a/crates/forge-web/assets/sw.js b/crates/forge-web/assets/sw.js new file mode 100644 index 0000000..38ea13b --- /dev/null +++ b/crates/forge-web/assets/sw.js @@ -0,0 +1,49 @@ +// Forge service worker. Served at /sw.js, so its scope is the whole origin. It shows Web Push +// notifications while no tab is open and opens the link of a clicked one. No inline code, no +// network caching: the page is always fetched fresh. + +self.addEventListener('install', function () { + self.skipWaiting(); +}); + +self.addEventListener('activate', function (event) { + event.waitUntil(self.clients.claim()); +}); + +self.addEventListener('push', function (event) { + var data = {}; + try { + data = event.data ? event.data.json() : {}; + } catch (e) { + data = {}; + } + var title = typeof data.title === 'string' && data.title ? data.title : 'Forge'; + var options = { + body: typeof data.body === 'string' ? data.body : '', + tag: typeof data.tag === 'string' ? data.tag : undefined, + icon: '/assets/icons/icon-192.png', + badge: '/assets/icons/icon-192.png', + data: { url: typeof data.url === 'string' ? data.url : '/notifications' } + }; + event.waitUntil(self.registration.showNotification(title, options)); +}); + +// Focuses an open Forge tab and asks it to soft-navigate to the link, or opens a new window. +self.addEventListener('notificationclick', function (event) { + event.notification.close(); + var raw = event.notification.data && event.notification.data.url; + var target = typeof raw === 'string' && raw.charAt(0) === '/' && raw.charAt(1) !== '/' ? raw : '/notifications'; + var url = new URL(target, self.location.origin).href; + event.waitUntil((async function () { + var windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); + for (var i = 0; i < windows.length; i++) { + var client = windows[i]; + if (new URL(client.url).origin === self.location.origin) { + await client.focus(); + client.postMessage({ type: 'forge-navigate', url: target }); + return; + } + } + await self.clients.openWindow(url); + })()); +}); diff --git a/crates/forge-web/src/alerts.rs b/crates/forge-web/src/alerts.rs index 0cb6153..0284bf1 100644 --- a/crates/forge-web/src/alerts.rs +++ b/crates/forge-web/src/alerts.rs @@ -125,6 +125,14 @@ async fn deliver( continue; } publish_unread(state, &admin.id).await; + crate::web_push::queue( + state, + &admin.id, + crate::web_push::Alert::Admin { + subject: subject.to_owned(), + detail: detail.to_owned(), + }, + ); if !live.alerts.email { continue; } diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 759eec5..5aa0fdc 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -135,6 +135,7 @@ pub async fn serve( notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), ci_live: Arc::new(crate::ci::CiLive::default()), live: Arc::new(crate::live::LiveHub::default()), + push_live: Arc::new(crate::web_push::PushLive::default()), }; if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await { tracing::error!(error = %e, "building the SSH allowed-signers file failed"); diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index b37407f..d7835b9 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -32,6 +32,7 @@ pub mod misc; pub mod orgs; pub mod pulls; pub mod pulls_review; +pub mod push; pub mod releases_ci; pub mod repo_admin; diff --git a/crates/forge-web/src/i18n/push.rs b/crates/forge-web/src/i18n/push.rs new file mode 100644 index 0000000..4258d77 --- /dev/null +++ b/crates/forge-web/src/i18n/push.rs @@ -0,0 +1,122 @@ +//! Strings for Web Push: the device card in notification settings, the push notification text and +//! the test message. Shared strings (Notifications, Save) come from `super::Key`. + +use super::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + // Settings card: this device. + DeviceHeading, + DeviceHelp, + DeviceUnsupported, + DeviceNeedsHttps, + DeviceIosHint, + DeviceDenied, + DeviceOn, + DeviceOff, + DeviceError, + TurnOn, + TurnOff, + SendTest, + TestNoDevices, + // Settings card: the devices list. + DevicesHeading, + DevicesEmpty, + RemoveDevice, + DeviceRemoved, + NeverDelivered, + // The notification the device shows. + TestTitle, + TestBody, +} + +/// The phrase for `key`. +pub fn t(lang: Lang, key: K) -> &'static str { + use K::*; + match (key, lang) { + (DeviceHeading, Lang::En) => "Push notifications on this device", + (DeviceHeading, Lang::Tr) => "Bu cihazda anlık bildirimler", + (DeviceHelp, Lang::En) => { + "Get a notification on this device even when Forge is closed. Each browser or installed app is a separate device." + } + (DeviceHelp, Lang::Tr) => { + "Forge kapalıyken bile bu cihazda bildirim alın. Her tarayıcı veya yüklü uygulama ayrı bir cihazdır." + } + (DeviceUnsupported, Lang::En) => "This browser does not support push notifications.", + (DeviceUnsupported, Lang::Tr) => "Bu tarayıcı anlık bildirimleri desteklemiyor.", + (DeviceNeedsHttps, Lang::En) => "Push notifications need an HTTPS connection.", + (DeviceNeedsHttps, Lang::Tr) => "Anlık bildirimler için HTTPS bağlantısı gerekir.", + (DeviceIosHint, Lang::En) => { + "On iPhone and iPad, add Forge to your Home Screen, open it from there, then turn push on." + } + (DeviceIosHint, Lang::Tr) => { + "iPhone ve iPad'de önce Forge'u Ana Ekrana ekleyin, oradan açın, sonra anlık bildirimleri açın." + } + (DeviceDenied, Lang::En) => { + "Notifications are blocked for this site. Allow them in the browser's site settings, then try again." + } + (DeviceDenied, Lang::Tr) => { + "Bu site için bildirimler engellenmiş. Tarayıcının site ayarlarından izin verip yeniden deneyin." + } + (DeviceOn, Lang::En) => "Push is on for this device.", + (DeviceOn, Lang::Tr) => "Bu cihazda anlık bildirimler açık.", + (DeviceOff, Lang::En) => "Push is off for this device.", + (DeviceOff, Lang::Tr) => "Bu cihazda anlık bildirimler kapalı.", + (DeviceError, Lang::En) => "Push could not be turned on. Try again.", + (DeviceError, Lang::Tr) => "Anlık bildirimler açılamadı. Yeniden deneyin.", + (TurnOn, Lang::En) => "Turn on for this device", + (TurnOn, Lang::Tr) => "Bu cihazda aç", + (TurnOff, Lang::En) => "Turn off for this device", + (TurnOff, Lang::Tr) => "Bu cihazda kapat", + (SendTest, Lang::En) => "Send test notification", + (SendTest, Lang::Tr) => "Test bildirimi gönder", + (TestNoDevices, Lang::En) => "No device has push on yet. Turn it on first.", + (TestNoDevices, Lang::Tr) => "Henüz anlık bildirimi açık bir cihaz yok. Önce bunu açın.", + (DevicesHeading, Lang::En) => "Devices", + (DevicesHeading, Lang::Tr) => "Cihazlar", + (DevicesEmpty, Lang::En) => "No device has push on.", + (DevicesEmpty, Lang::Tr) => "Anlık bildirimi açık cihaz yok.", + (RemoveDevice, Lang::En) => "Remove", + (RemoveDevice, Lang::Tr) => "Kaldır", + (DeviceRemoved, Lang::En) => "Device removed.", + (DeviceRemoved, Lang::Tr) => "Cihaz kaldırıldı.", + (NeverDelivered, Lang::En) => "Nothing delivered yet", + (NeverDelivered, Lang::Tr) => "Henüz teslim edilmedi", + (TestTitle, Lang::En) => "Forge test notification", + (TestTitle, Lang::Tr) => "Forge test bildirimi", + (TestBody, Lang::En) => "Push notifications work on this device.", + (TestBody, Lang::Tr) => "Anlık bildirimler bu cihazda çalışıyor.", + } +} + +/// "Test sent to 2 devices." for the settings notice. +pub fn test_sent(lang: Lang, devices: usize) -> String { + match lang { + Lang::En => format!("Test sent to {devices} device(s)."), + Lang::Tr => format!("Test {devices} cihaza gönderildi."), + } +} + +/// "Added 2026-10-02" and the matching delivery line. +pub fn added_on(lang: Lang, date: &str) -> String { + match lang { + Lang::En => format!("Added {date}"), + Lang::Tr => format!("Eklendi {date}"), + } +} + +/// "Last delivered 2026-10-02". +pub fn last_delivered(lang: Lang, date: &str) -> String { + match lang { + Lang::En => format!("Last delivered {date}"), + Lang::Tr => format!("Son teslim {date}"), + } +} + +/// "3 new security alerts" for the push about advisories. +pub fn advisory_alerts(lang: Lang, count: u64) -> String { + match lang { + Lang::En => format!("{count} new security alerts"), + Lang::Tr => format!("{count} yeni güvenlik uyarısı"), + } +} diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 34021bb..62b5d34 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -55,6 +55,7 @@ mod test_support; mod theme; mod throttle; mod views; +mod web_push; mod webhooks; use std::path::PathBuf; diff --git a/crates/forge-web/src/notify.rs b/crates/forge-web/src/notify.rs index a90fd66..b7e8648 100644 --- a/crates/forge-web/src/notify.rs +++ b/crates/forge-web/src/notify.rs @@ -12,7 +12,7 @@ use forge_core::store::orgs::OrgMemberRole; use forge_core::{Action, Issue, Repo, Result, User, authorize}; use http::HeaderMap; -use crate::i18n; +use crate::i18n::{self, misc}; use crate::mail::{ self, templates::{self, Verb, Why}, @@ -20,6 +20,7 @@ use crate::mail::{ use crate::notify_hub::publish_unread; use crate::render::markdown::mentioned_usernames; use crate::state::AppState; +use crate::web_push::{self, Alert}; /// Something that happened on an issue or pull request, as far as notifications care. #[derive(Debug, Clone, PartialEq, Eq)] @@ -202,6 +203,15 @@ async fn notify_advisory_admins(state: &AppState, repo: &Repo, opened: usize) -> .notify_new_alerts(&admin, &repo.id, count) .await?; publish_unread(state, &admin).await; + web_push::queue( + state, + &admin, + Alert::Advisories { + repo: format!("{}/{}", repo.owner_name, repo.name), + count, + url: format!("/{}/{}/security", repo.owner_name, repo.name), + }, + ); } Ok(()) } @@ -368,6 +378,20 @@ async fn run( } } + // The same activity as a push for each device of a recipient. Built once, in the recipient's + // language when it is sent. + let push = if recipients.is_empty() { + None + } else { + match push_alert(state, repo, issue, actor_id, activity).await { + Ok(alert) => Some(alert), + Err(e) => { + tracing::error!(error = %e, issue_id, "notify: push text failed"); + None + } + } + }; + // Auto-subscribe. Existing rows, including explicit ignores, are left alone. if let Some(actor_id) = actor { match activity { @@ -418,7 +442,12 @@ async fn run( ) .await { - Ok(()) => publish_unread(state, &user_id).await, + Ok(()) => { + publish_unread(state, &user_id).await; + if let Some(alert) = &push { + web_push::queue(state, &user_id, alert.clone()); + } + } Err(e) => tracing::error!(error = %e, user_id, issue_id, "notify: inbox write failed"), } if let Some(plan) = &plan @@ -500,6 +529,57 @@ async fn mail_plan( })) } +/// The push text for this activity: the repo, the number, the issue title and what happened. +async fn push_alert( + state: &AppState, + repo: &Repo, + issue: &Issue, + actor_id: &str, + activity: &Activity, +) -> Result { + let actor = match actor_id { + "" => None, + id => state.store.user_by_id(id).await?.map(|u| u.username), + }; + let section = if state + .store + .pull_by_number(&repo.id, issue.number) + .await? + .is_some() + { + "pulls" + } else { + "issues" + }; + Ok(Alert::Activity { + repo: format!("{}/{}", repo.owner_name, repo.name), + number: issue.number, + title: issue.title.clone(), + verb: push_verb_for(activity), + actor, + url: format!( + "/{}/{}/{section}/{}", + repo.owner_name, repo.name, issue.number + ), + thread: issue.id.clone(), + }) +} + +fn push_verb_for(activity: &Activity) -> misc::K { + match activity { + Activity::Opened => misc::K::VerbOpened, + Activity::Comment => misc::K::VerbCommented, + Activity::Closed => misc::K::VerbClosed, + Activity::Reopened => misc::K::VerbReopened, + Activity::Merged => misc::K::VerbMerged, + Activity::Review => misc::K::VerbReviewed, + Activity::Assigned { .. } => misc::K::VerbAssigned, + Activity::ReviewRequested { .. } => misc::K::VerbReviewRequested, + Activity::Pushed => misc::K::VerbPushedTo, + Activity::Edited => misc::K::VerbMentionedYou, + } +} + fn verb_for(activity: &Activity) -> Verb { match activity { Activity::Opened => Verb::Opened, diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 8efc4ae..560238a 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -83,6 +83,7 @@ pub mod pull_reviews; pub mod pull_view; pub mod pulls_list; pub mod pulls_merge; +pub mod push; pub mod reactions; #[cfg(test)] mod reactions_tests; diff --git a/crates/forge-web/src/pages/push.rs b/crates/forge-web/src/pages/push.rs new file mode 100644 index 0000000..22c77d2 --- /dev/null +++ b/crates/forge-web/src/pages/push.rs @@ -0,0 +1,601 @@ +//! Web Push routes. The browser calls the `/push` routes from `assets/nav.js`; the settings page +//! posts its device actions as forms (soft-navigation swaps the result in place). +//! +//! - `GET /push/vapid-key`: the public key the browser subscribes with (JSON). +//! - `POST /push/subscribe`: adds this browser for the viewer. Fields: `csrf`, `endpoint`, +//! `p256dh`, `auth`. The device label comes from the request's User-Agent. +//! - `POST /push/unsubscribe`: removes this browser for the viewer. Fields: `csrf`, `endpoint`. +//! - `POST /settings/notifications/push/remove`: removes one of the viewer's devices. Fields: +//! `csrf`, `id`. +//! - `POST /settings/notifications/push/test`: sends a test notification to the viewer's devices. +//! - `GET /settings/notifications/push/events`: an event stream that sends `changed` whenever the +//! viewer's devices change, so the settings page re-renders without a reload. + +use futures_util::stream; +use http::header::USER_AGENT; +use serde::Deserialize; +use serde_json::json; +use tokio::sync::broadcast::error::RecvError; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::content::sse::{Event, KeepAlive, Sse}; +use topcoat::router::error::{SeeOther, see_other}; +use topcoat::router::request::headers; +use topcoat::router::response::{IntoResponse, Response}; +use topcoat::router::{Body, HeaderMap, HeaderValue, StatusCode, header, route}; + +use crate::api::{self, json}; +use crate::auth::{current_user, require_csrf, require_user}; +use crate::state::AppState; +use crate::web_push::{self, Alert, crypto}; + +/// How often an idle event stream sends a comment so proxies keep it open. +const STREAM_KEEP_ALIVE: std::time::Duration = std::time::Duration::from_secs(30); + +/// Longest push endpoint accepted, in bytes. +const MAX_ENDPOINT: usize = 2048; + +#[derive(Deserialize)] +struct SubscribeForm { + #[serde(default)] + csrf: String, + #[serde(default)] + endpoint: String, + #[serde(default)] + p256dh: String, + #[serde(default)] + auth: String, +} + +#[derive(Deserialize)] +struct EndpointForm { + #[serde(default)] + csrf: String, + #[serde(default)] + endpoint: String, +} + +#[derive(Deserialize)] +struct DeviceForm { + #[serde(default)] + csrf: String, + #[serde(default)] + id: String, +} + +#[derive(Deserialize)] +struct CsrfForm { + #[serde(default)] + csrf: String, +} + +/// A push endpoint must be an https URL of sane length. The service worker never opens it, but +/// the server posts to it, so only the push service's own kind of URL is accepted. +fn check_endpoint(endpoint: &str) -> forge_core::Result<()> { + if endpoint.len() > MAX_ENDPOINT { + return Err(forge_core::Error::Invalid( + "the push endpoint is too long".into(), + )); + } + let url = reqwest::Url::parse(endpoint) + .map_err(|_| forge_core::Error::Invalid("the push endpoint is not a URL".into()))?; + // The VAPID audience is the origin without a port (web-push-native builds it that way), so a + // non-default port would not match what the push service checks. Push services use 443. + if url.scheme() != "https" || url.host_str().is_none() || url.port().is_some() { + return Err(forge_core::Error::Invalid( + "the push endpoint must be an https URL on the default port".into(), + )); + } + Ok(()) +} + +/// The browser's P-256 public key must be an uncompressed point, and its auth secret 16 bytes. +fn check_keys(p256dh: &str, auth: &str) -> forge_core::Result<()> { + let point = crypto::decode_b64(p256dh)?; + if point.len() != 65 + || point[0] != 0x04 + || web_push_native::p256::PublicKey::from_sec1_bytes(&point).is_err() + { + return Err(forge_core::Error::Invalid( + "the browser key is not a P-256 public key".into(), + )); + } + if crypto::decode_b64(auth)?.len() != 16 { + return Err(forge_core::Error::Invalid( + "the browser auth secret is not 16 bytes".into(), + )); + } + Ok(()) +} + +fn no_content() -> Response { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::NO_CONTENT; + res +} + +/// The public key the browser subscribes with. Creates the instance's key pair on first use. +#[route(GET "/push/vapid-key")] +async fn vapid_key(cx: &Cx) -> Result { + require_user(cx).await?; + let state = app_context::(cx); + let keys = web_push::vapid_keys(state).await?; + Ok(json(StatusCode::OK, &json!({ "public_key": keys.public }))) +} + +/// Adds this browser as a device of the viewer. +#[route(POST "/push/subscribe")] +async fn subscribe(cx: &Cx, Form(form): Form) -> Result { + let (user, _) = require_csrf(cx, &form.csrf).await?; + if let Err(e) = + check_endpoint(&form.endpoint).and_then(|()| check_keys(&form.p256dh, &form.auth)) + { + return Ok(api::error(StatusCode::BAD_REQUEST, &e.to_string())); + } + let state = app_context::(cx); + let agent = headers(cx) + .get(USER_AGENT) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default() + .to_owned(); + state + .store + .save_push_subscription( + &user.id, + &form.endpoint, + &form.p256dh, + &form.auth, + &web_push::agent_label(&agent), + ) + .await?; + state.push_live.publish(&user.id); + Ok(no_content()) +} + +/// Removes this browser from the viewer's devices. Nothing to remove is not an error. +#[route(POST "/push/unsubscribe")] +async fn unsubscribe(cx: &Cx, Form(form): Form) -> Result { + let (user, _) = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + if state + .store + .delete_push_subscription_by_endpoint(&user.id, &form.endpoint) + .await? + { + state.push_live.publish(&user.id); + } + Ok(no_content()) +} + +/// Removes one of the viewer's devices from the settings list. +#[route(POST "/settings/notifications/push/remove")] +async fn remove_device(cx: &Cx, Form(form): Form) -> Result { + let (user, _) = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + if state + .store + .delete_push_subscription(&user.id, &form.id) + .await? + { + state.push_live.publish(&user.id); + } + Ok(see_other("/settings/notifications?removed=1")) +} + +/// Sends the test notification to every device of the viewer. The count goes back in the URL so +/// the settings page can say how many devices were tried. +#[route(POST "/settings/notifications/push/test")] +async fn send_test(cx: &Cx, Form(form): Form) -> Result { + let (user, _) = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let devices = state.store.push_subscriptions(&user.id).await?.len(); + if devices > 0 { + web_push::queue(state, &user.id, Alert::Test); + } + Ok(see_other(format!("/settings/notifications?test={devices}"))) +} + +/// One `changed` event each time the viewer's devices change, until the viewer disconnects or the +/// server shuts down. Other users' changes are skipped. An anonymous viewer gets a bare 401. +#[route(GET "/settings/notifications/push/events")] +async fn push_events(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(res); + }; + let state = app_context::(cx); + let rx = state.push_live.subscribe(); + let changes = stream::unfold((rx, user.id), |(mut rx, user_id)| async move { + loop { + match rx.recv().await { + Ok(changed) if changed == user_id => { + return Some((changed_event(), (rx, user_id))); + } + Ok(_) => continue, + // Missed some changes: say so, so the page re-reads its devices. + Err(RecvError::Lagged(_)) => return Some((changed_event(), (rx, user_id))), + Err(RecvError::Closed) => return None, + } + } + }); + let events = Sse::new(changes).keep_alive( + KeepAlive::new() + .interval(STREAM_KEEP_ALIVE) + .text("keepalive"), + ); + let mut res = events.into_response(cx)?; + // Nginx buffers a proxied response unless told not to, which would hold the events back. + res.headers_mut() + .insert("x-accel-buffering", HeaderValue::from_static("no")); + Ok(res) +} + +fn changed_event() -> Result { + Ok(Event::new().event("changed").data("1")) +} + +/// The service worker. It must sit at the origin root to control every page, so it has its own +/// route rather than the immutable `/assets` ones. Revalidated on each load. +const SW_JS: &str = include_str!("../../assets/sw.js"); +const ICON_192: &[u8] = include_bytes!("../../assets/icons/icon-192.png"); +const ICON_512: &[u8] = include_bytes!("../../assets/icons/icon-512.png"); +const APPLE_TOUCH_ICON: &[u8] = include_bytes!("../../assets/icons/apple-touch-icon.png"); + +/// The web app manifest: installing Forge from the browser gives a standalone app with these icons. +const MANIFEST: &str = r##"{ + "name": "Forge", + "short_name": "Forge", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#f6f4ec", + "theme_color": "#5f7f67", + "icons": [ + { "src": "/assets/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "/assets/icons/icon-512.png", "sizes": "512x512", "type": "image/png" } + ] +} +"##; + +fn static_headers(content_type: &'static str, cache: &'static str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + header::CONTENT_TYPE, + content_type.parse().expect("static header value"), + ); + headers.insert( + header::CACHE_CONTROL, + cache.parse().expect("static header value"), + ); + headers +} + +#[route(GET "/sw.js")] +async fn service_worker() -> Result<(StatusCode, HeaderMap, &'static str)> { + let headers = static_headers("text/javascript; charset=utf-8", "no-cache"); + Ok((StatusCode::OK, headers, SW_JS)) +} + +#[route(GET "/manifest.webmanifest")] +async fn manifest() -> Result<(StatusCode, HeaderMap, &'static str)> { + let headers = static_headers("application/manifest+json", "public, max-age=3600"); + Ok((StatusCode::OK, headers, MANIFEST)) +} + +#[route(GET "/assets/icons/icon-192.png")] +async fn icon_192() -> Result<(StatusCode, HeaderMap, &'static [u8])> { + let headers = static_headers("image/png", "public, max-age=604800"); + Ok((StatusCode::OK, headers, ICON_192)) +} + +#[route(GET "/assets/icons/icon-512.png")] +async fn icon_512() -> Result<(StatusCode, HeaderMap, &'static [u8])> { + let headers = static_headers("image/png", "public, max-age=604800"); + Ok((StatusCode::OK, headers, ICON_512)) +} + +#[route(GET "/assets/icons/apple-touch-icon.png")] +async fn apple_touch_icon() -> Result<(StatusCode, HeaderMap, &'static [u8])> { + let headers = static_headers("image/png", "public, max-age=604800"); + Ok((StatusCode::OK, headers, APPLE_TOUCH_ICON)) +} + +#[cfg(test)] +mod tests { + use forge_core::Store; + use topcoat::router::request::Request; + use topcoat::router::{Body, Router, to_bytes}; + use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint; + + use crate::auth::SESSION_COOKIE; + use crate::test_support::{app_router, create_session, test_state}; + use crate::web_push::crypto; + + const TOKEN: &str = "push-session"; + const CSRF: &str = "push-csrf"; + const UA: &str = + "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36"; + + struct Fixture { + _dir: tempfile::TempDir, + router: Router, + store: Store, + user_id: String, + } + + async fn fixture() -> Fixture { + let dir = tempfile::tempdir().expect("tempdir"); + let data_dir = dir.path().join("data"); + std::fs::create_dir_all(&data_dir).expect("data dir"); + let state = test_state(&data_dir).await; + let user = state + .store + .create_user("tahinli", None, "h", false) + .await + .expect("user"); + create_session(&state.store, &user.id, TOKEN, CSRF).await; + Fixture { + _dir: dir, + router: app_router(state.clone()), + store: state.store.clone(), + user_id: user.id, + } + } + + /// A browser key and auth secret as a browser would send them: base64url, uncompressed point. + fn browser_keys() -> (String, String) { + let secret = web_push_native::p256::SecretKey::from_slice(&crypto::new_vapid_private()) + .expect("scalar"); + let point = secret.public_key().to_encoded_point(false); + ( + crypto::encode_b64(point.as_bytes()), + crypto::encode_b64(&[7u8; 16]), + ) + } + + async fn send( + router: &Router, + method: &str, + uri: &str, + token: Option<&str>, + form: Option, + ) -> (u16, String) { + let mut builder = Request::builder() + .method(method) + .uri(uri) + .header("user-agent", UA); + if let Some(token) = token { + builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); + } + let body = match form { + Some(form) => { + builder = builder.header("content-type", "application/x-www-form-urlencoded"); + Body::from(form) + } + None => Body::empty(), + }; + let res = router.handle(builder.body(body).expect("request")).await; + let status = res.status().as_u16(); + let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); + (status, String::from_utf8_lossy(&bytes).into_owned()) + } + + fn subscribe_form(csrf: &str, endpoint: &str, p256dh: &str, auth: &str) -> String { + let enc = |s: &str| form_urlencoded::byte_serialize(s.as_bytes()).collect::(); + format!( + "csrf={}&endpoint={}&p256dh={}&auth={}", + enc(csrf), + enc(endpoint), + enc(p256dh), + enc(auth) + ) + } + + #[tokio::test] + async fn the_vapid_key_is_created_once_and_served() { + let fx = fixture().await; + let (status, first) = send(&fx.router, "GET", "/push/vapid-key", Some(TOKEN), None).await; + assert_eq!(status, 200, "{first}"); + let (_, second) = send(&fx.router, "GET", "/push/vapid-key", Some(TOKEN), None).await; + assert_eq!(first, second, "the same key on every request"); + let key: serde_json::Value = serde_json::from_str(&first).expect("json"); + let public = key["public_key"].as_str().expect("public key"); + assert_eq!(crypto::decode_b64(public).expect("b64").len(), 65); + } + + #[tokio::test] + async fn the_vapid_key_needs_a_session() { + let fx = fixture().await; + let (status, _) = send(&fx.router, "GET", "/push/vapid-key", None, None).await; + assert_ne!(status, 200); + } + + #[tokio::test] + async fn subscribe_then_unsubscribe_round_trip() { + let fx = fixture().await; + let (p256dh, auth) = browser_keys(); + let endpoint = "https://push.example.test/send/tahinli-1"; + let form = subscribe_form(CSRF, endpoint, &p256dh, &auth); + + let (status, body) = send( + &fx.router, + "POST", + "/push/subscribe", + Some(TOKEN), + Some(form), + ) + .await; + assert_eq!(status, 204, "{body}"); + let devices = fx + .store + .push_subscriptions(&fx.user_id) + .await + .expect("list"); + assert_eq!(devices.len(), 1); + assert_eq!(devices[0].endpoint, endpoint); + assert_eq!(devices[0].agent_label, "Chrome on Android"); + + let remove = format!("csrf={CSRF}&endpoint={endpoint}"); + let (status, body) = send( + &fx.router, + "POST", + "/push/unsubscribe", + Some(TOKEN), + Some(remove), + ) + .await; + assert_eq!(status, 204, "{body}"); + assert!( + fx.store + .push_subscriptions(&fx.user_id) + .await + .expect("list") + .is_empty() + ); + } + + #[tokio::test] + async fn a_subscription_needs_the_csrf_token() { + let fx = fixture().await; + let (p256dh, auth) = browser_keys(); + let form = subscribe_form("wrong", "https://push.example.test/x", &p256dh, &auth); + let (status, _) = send( + &fx.router, + "POST", + "/push/subscribe", + Some(TOKEN), + Some(form), + ) + .await; + assert_eq!(status, 403); + assert!( + fx.store + .push_subscriptions(&fx.user_id) + .await + .expect("list") + .is_empty() + ); + } + + #[tokio::test] + async fn a_subscription_with_bad_fields_is_refused() { + let fx = fixture().await; + let (p256dh, auth) = browser_keys(); + let http_endpoint = subscribe_form(CSRF, "http://push.example.test/x", &p256dh, &auth); + let (status, _) = send( + &fx.router, + "POST", + "/push/subscribe", + Some(TOKEN), + Some(http_endpoint), + ) + .await; + assert_eq!(status, 400, "an endpoint must be https"); + let short_auth = subscribe_form( + CSRF, + "https://push.example.test/x", + &p256dh, + &crypto::encode_b64(&[1u8; 8]), + ); + let (status, _) = send( + &fx.router, + "POST", + "/push/subscribe", + Some(TOKEN), + Some(short_auth), + ) + .await; + assert_eq!(status, 400, "the auth secret is 16 bytes"); + let not_a_point = subscribe_form( + CSRF, + "https://push.example.test/x", + &crypto::encode_b64(&[4u8; 65]), + &auth, + ); + let (status, _) = send( + &fx.router, + "POST", + "/push/subscribe", + Some(TOKEN), + Some(not_a_point), + ) + .await; + assert_eq!(status, 400, "the browser key is a point"); + assert!( + fx.store + .push_subscriptions(&fx.user_id) + .await + .expect("list") + .is_empty() + ); + } + + #[tokio::test] + async fn a_viewer_removes_only_their_own_device() { + let fx = fixture().await; + let other = fx + .store + .create_user("nina", None, "h", false) + .await + .expect("other user"); + let theirs = fx + .store + .save_push_subscription( + &other.id, + "https://push.example.test/nina", + "BA", + "AA", + "Chrome on Linux", + ) + .await + .expect("save"); + let form = format!("csrf={CSRF}&id={}", theirs.id); + let (status, _) = send( + &fx.router, + "POST", + "/settings/notifications/push/remove", + Some(TOKEN), + Some(form), + ) + .await; + assert_eq!(status, 303); + assert_eq!( + fx.store + .push_subscriptions(&other.id) + .await + .expect("list") + .len(), + 1 + ); + } + + #[tokio::test] + async fn the_events_stream_needs_a_session() { + let fx = fixture().await; + let (status, _) = send( + &fx.router, + "GET", + "/settings/notifications/push/events", + None, + None, + ) + .await; + assert_eq!(status, 401); + } + + #[tokio::test] + async fn the_service_worker_and_manifest_are_served() { + let fx = fixture().await; + let (status, sw) = send(&fx.router, "GET", "/sw.js", None, None).await; + assert_eq!(status, 200); + assert!(sw.contains("notificationclick"), "{sw}"); + let (status, manifest) = send(&fx.router, "GET", "/manifest.webmanifest", None, None).await; + assert_eq!(status, 200); + assert!( + manifest.contains("\"display\": \"standalone\""), + "{manifest}" + ); + } +} diff --git a/crates/forge-web/src/pages/settings_notifications.rs b/crates/forge-web/src/pages/settings_notifications.rs index afce1d7..06cfd90 100644 --- a/crates/forge-web/src/pages/settings_notifications.rs +++ b/crates/forge-web/src/pages/settings_notifications.rs @@ -4,6 +4,7 @@ //! itself on change (soft-nav POST, no reload); the Save button only shows without JavaScript. //! Every POST checks the CSRF token first. +use forge_core::store::web_push::PushSubscription; use forge_core::{Session, Store, User}; use serde::Deserialize; use topcoat::Result; @@ -14,13 +15,18 @@ use topcoat::router::{page, query_params, route}; use topcoat::view::{View, component, view}; use crate::auth::{require_csrf, require_user}; +use crate::i18n::push as push_text; use crate::i18n::{self, Key, Lang, t}; use crate::state::AppState; -use crate::views::shell; +use crate::views::{csrf_field, shell}; #[query_params(error = bad_request)] struct NotificationsQuery { saved: Option, + /// Set by the test button: how many devices the test was sent to. + test: Option, + /// Set after a device is removed. + removed: Option, } #[derive(Deserialize)] @@ -40,7 +46,16 @@ struct NotificationsPage { unverified_note: Option<&'static str>, /// A note when instance mail is off, `None` when it is on. server_note: Option<&'static str>, - notice: Option<&'static str>, + notice: Option, + /// The viewer's devices with push on. + devices: Vec, + /// Whether the test button has a device to send to. + can_test: bool, +} + +/// A device's date for the list: the `YYYY-MM-DD` part of its stamp. +fn day_of(stamp: &str) -> &str { + stamp.get(..10).unwrap_or(stamp) } #[component] @@ -52,6 +67,8 @@ async fn notifications_body(page: NotificationsPage) -> Result { unverified_note, server_note, notice, + devices, + can_test, } = page; // Nothing can be sent while instance mail is off or the address is unverified, so the box is // locked and the notes below say why. @@ -63,7 +80,7 @@ async fn notifications_body(page: NotificationsPage) -> Result { if let Some(message) = notice {
-

(message)

+

(message.as_str())

}
@@ -89,6 +106,56 @@ async fn notifications_body(page: NotificationsPage) -> Result {
+
+

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

+ (push_text::t(lang, push_text::K::DeviceHelp)) + + + + + + + +
+ + +
+
+ csrf_field(token: csrf.as_str()) + + if !can_test { + (push_text::t(lang, push_text::K::TestNoDevices)) + } +
+
+
+

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

+ if devices.is_empty() { +

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

+ } +
    + for device in devices.into_iter() { +
  • +
    + (device.agent_label.as_str()) + (push_text::added_on(lang, day_of(&device.created_at))) + + if let Some(stamp) = device.last_success_at.as_deref() { + (push_text::last_delivered(lang, day_of(stamp))) + } else { + (push_text::t(lang, push_text::K::NeverDelivered)) + } + +
    +
    + csrf_field(token: csrf.as_str()) + + +
    +
  • + } +
+
}) } @@ -98,10 +165,11 @@ async fn page_for( store: &Store, viewer: &(User, Session), lang: Lang, - notice: Option<&'static str>, + notice: Option, ) -> forge_core::Result { let server_on = store.mail_settings().await?.enabled; let verified = store.email_is_verified(&viewer.0.id).await?; + let devices = store.push_subscriptions(&viewer.0.id).await?; Ok(NotificationsPage { lang, csrf: viewer.1.csrf_token.clone(), @@ -109,6 +177,8 @@ async fn page_for( unverified_note: (!verified).then(|| t(lang, Key::EmailNotifyUnverified)), server_note: (!server_on).then(|| t(lang, Key::EmailNotifyServerOff)), notice, + can_test: !devices.is_empty(), + devices, }) } @@ -117,8 +187,20 @@ async fn notifications_page(cx: &Cx) -> Result { let viewer = require_user(cx).await?; let store: &Store = &app_context::(cx).store; let lang = i18n::lang(cx, Some(&viewer.0)); - let saved = query_params::(cx)?.saved.clone(); - let notice = (saved.as_deref() == Some("1")).then(|| t(lang, Key::EmailNotifySaved)); + let query = query_params::(cx)?; + let notice = if query.saved.as_deref() == Some("1") { + Some(t(lang, Key::EmailNotifySaved).to_owned()) + } else if let Some(sent) = query.test.as_deref() { + match sent.parse::() { + Ok(0) => Some(push_text::t(lang, push_text::K::TestNoDevices).to_owned()), + Ok(n) => Some(push_text::test_sent(lang, n)), + Err(_) => None, + } + } else if query.removed.as_deref() == Some("1") { + Some(push_text::t(lang, push_text::K::DeviceRemoved).to_owned()) + } else { + None + }; let page = page_for(store, &viewer, lang, notice).await?; Ok(view! { shell(title: t(lang, Key::Notifications), viewer: Some(&viewer), notifications_body(page: page)) diff --git a/crates/forge-web/src/pages/settings_security.rs b/crates/forge-web/src/pages/settings_security.rs index c1b36a5..55a931a 100644 --- a/crates/forge-web/src/pages/settings_security.rs +++ b/crates/forge-web/src/pages/settings_security.rs @@ -1101,6 +1101,7 @@ mod tests { notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), ci_live: Arc::new(crate::ci::CiLive::default()), live: Arc::new(crate::live::LiveHub::default()), + push_live: Arc::new(crate::web_push::PushLive::default()), }; let hash = hash_password_async(PASSWORD.into()).await.unwrap(); let user = store diff --git a/crates/forge-web/src/state.rs b/crates/forge-web/src/state.rs index f26ea0b..7d18551 100644 --- a/crates/forge-web/src/state.rs +++ b/crates/forge-web/src/state.rs @@ -51,6 +51,8 @@ pub struct AppState { pub ci_live: Arc, /// Change signals of live pages, keyed by topic. See `live`. pub live: Arc, + /// Device changes per user. The settings pages showing a user's push devices listen to it. + pub push_live: Arc, } /// A settings handle over `config` with no stored overrides and no file keys. For tests. diff --git a/crates/forge-web/src/test_support.rs b/crates/forge-web/src/test_support.rs index 1accc7d..a533951 100644 --- a/crates/forge-web/src/test_support.rs +++ b/crates/forge-web/src/test_support.rs @@ -87,6 +87,7 @@ pub async fn test_state(dir: &Path) -> AppState { notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), ci_live: Arc::new(crate::ci::CiLive::default()), live: Arc::new(crate::live::LiveHub::default()), + push_live: Arc::new(crate::web_push::PushLive::default()), } } diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index 791bd78..546c329 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -253,6 +253,10 @@ pub async fn shell( + + + + (full_title) diff --git a/crates/forge-web/src/web_push/crypto.rs b/crates/forge-web/src/web_push/crypto.rs new file mode 100644 index 0000000..487d353 --- /dev/null +++ b/crates/forge-web/src/web_push/crypto.rs @@ -0,0 +1,177 @@ +//! Thin glue over `web-push-native`, which does the cryptography: the RFC 8291 message encryption +//! (aes128gcm content coding, RFC 8188) and the RFC 8292 VAPID authorization (an ES256 JWT). The +//! crate is RustCrypto based and pure Rust. This module only converts the base64url values that +//! browsers and the database hold into the types the crate takes, and builds the request. + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use p256::elliptic_curve::sec1::ToEncodedPoint; +use web_push_native::jwt_simple::algorithms::ES256KeyPair; +use web_push_native::{Auth, WebPushBuilder, p256}; + +use forge_core::{Error, Result}; + +/// The uncompressed P-256 point length: 0x04 followed by X and Y. +const POINT_LEN: usize = 65; + +/// Decodes base64url, with or without padding. +pub fn decode_b64(text: &str) -> Result> { + URL_SAFE_NO_PAD + .decode(text.trim_end_matches('=')) + .map_err(|_| Error::Invalid("not base64url".into())) +} + +/// Encodes base64url without padding, the form push services and browsers use. +pub fn encode_b64(bytes: &[u8]) -> String { + URL_SAFE_NO_PAD.encode(bytes) +} + +/// A new VAPID private key (32 bytes) from the system RNG. +pub fn new_vapid_private() -> [u8; 32] { + let mut out = [0u8; 32]; + out.copy_from_slice(&ES256KeyPair::generate().to_bytes()); + out +} + +/// The key pair the VAPID signature is made with, from its 32-byte private scalar. +pub fn vapid_key_pair(private: &[u8; 32]) -> Result { + ES256KeyPair::from_bytes(private).map_err(|_| Error::Crypto("bad VAPID key".into())) +} + +/// The public key of a VAPID private key, as the uncompressed point in base64url. This is the +/// `applicationServerKey` the browser subscribes with. +pub fn vapid_public_key(private: &[u8; 32]) -> Result { + let secret = + p256::SecretKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))?; + let point = secret.public_key().to_encoded_point(false); + Ok(encode_b64(point.as_bytes())) +} + +/// Builds the POST for one push: the body is encrypted for the browser's key and auth secret, +/// and the request carries the VAPID `Authorization` for `endpoint`'s origin. `subject` is the +/// contact URL (`mailto:` or `https:`). +pub fn push_request( + endpoint: &str, + p256dh: &[u8], + auth: &[u8], + subject: &str, + key_pair: &ES256KeyPair, + payload: Vec, +) -> Result>> { + if p256dh.len() != POINT_LEN { + return Err(Error::Invalid( + "the browser key is not a P-256 point".into(), + )); + } + let ua_public = p256::PublicKey::from_sec1_bytes(p256dh) + .map_err(|_| Error::Invalid("the browser key is not on the curve".into()))?; + if auth.len() != 16 { + return Err(Error::Invalid( + "the browser auth secret is not 16 bytes".into(), + )); + } + let ua_auth = Auth::clone_from_slice(auth); + let uri: http::Uri = endpoint + .parse() + .map_err(|_| Error::Invalid("bad push endpoint".into()))?; + WebPushBuilder::new(uri, ua_public, ua_auth) + .with_vapid(key_pair, subject) + .build(payload) + .map_err(|e| Error::Crypto(format!("web push encryption failed: {e}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + use p256::elliptic_curve::sec1::ToEncodedPoint; + + #[test] + fn a_browser_key_that_is_not_a_point_is_refused() { + let key_pair = vapid_key_pair(&new_vapid_private()).expect("key"); + let auth = [7u8; 16]; + let not_a_point = [4u8; 65]; + assert!( + push_request( + "https://push.example.test/x", + ¬_a_point, + &auth, + "mailto:tahinli@example.test", + &key_pair, + b"hi".to_vec() + ) + .is_err() + ); + assert!( + push_request( + "https://push.example.test/x", + &[0x04; 10], + &auth, + "mailto:tahinli@example.test", + &key_pair, + b"hi".to_vec() + ) + .is_err() + ); + } + + #[test] + fn the_request_is_an_encrypted_vapid_post_to_the_endpoint() { + let private = new_vapid_private(); + let key_pair = vapid_key_pair(&private).expect("key"); + let browser = p256::SecretKey::from_slice(&new_vapid_private()).expect("scalar"); + let point = browser + .public_key() + .to_encoded_point(false) + .as_bytes() + .to_vec(); + let auth = [9u8; 16]; + let endpoint = "https://push.example.test/send/abc"; + let payload = br#"{"title":"tahinli/forge#1"}"#.to_vec(); + let request = push_request( + endpoint, + &point, + &auth, + "mailto:tahinli@example.test", + &key_pair, + payload.clone(), + ) + .expect("request"); + + assert_eq!(request.method(), http::Method::POST); + assert_eq!(request.uri().to_string(), endpoint); + assert_eq!(request.headers()["content-encoding"], "aes128gcm"); + assert_eq!(request.headers()["ttl"], "43200"); + + // The VAPID header names the push service's origin and carries the instance's public key. + let auth_header = request.headers()["authorization"] + .to_str() + .expect("ascii") + .to_owned(); + assert!(auth_header.starts_with("vapid "), "{auth_header}"); + assert!(auth_header.contains(&format!( + "k={}", + vapid_public_key(&private).expect("public") + ))); + let token = auth_header + .split("t=") + .nth(1) + .and_then(|rest| rest.split(',').next()) + .expect("token"); + let claims = token.split('.').nth(1).expect("claims"); + let claims = decode_b64(claims).expect("base64"); + let claims: serde_json::Value = serde_json::from_slice(&claims).expect("json"); + assert_eq!(claims["aud"], "https://push.example.test"); + assert_eq!(claims["sub"], "mailto:tahinli@example.test"); + + // The body is encrypted: it is longer than the plaintext and does not contain it. + let body = request.body(); + assert!(body.len() > payload.len()); + assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice())); + } + + #[test] + fn the_public_key_is_the_uncompressed_point() { + let public = vapid_public_key(&new_vapid_private()).expect("public"); + assert_eq!(decode_b64(&public).expect("b64").len(), POINT_LEN); + } +} diff --git a/crates/forge-web/src/web_push/mod.rs b/crates/forge-web/src/web_push/mod.rs new file mode 100644 index 0000000..aa33a61 --- /dev/null +++ b/crates/forge-web/src/web_push/mod.rs @@ -0,0 +1,567 @@ +//! Web Push: a notification for the inbox also reaches the user's devices when no tab is open. A +//! browser (or an installed app) subscribes through the service worker, the server keeps the +//! subscription, and [`queue`] sends the message to every device of a user. +//! +//! Delivery never blocks the caller: [`queue`] spawns the work, which looks up the user's devices, +//! encrypts the message per device (RFC 8291), signs the request with the instance's VAPID key +//! (RFC 8292) and posts it to the push service. A device the service reports gone (404 or 410) is +//! removed. Every change to a user's devices is announced on [`PushLive`], so an open settings page +//! refreshes through its event stream. + +pub mod crypto; + +use std::sync::OnceLock; +use std::time::Duration; + +use serde::Serialize; +use tokio::sync::broadcast; + +use forge_core::store::web_push::PushSubscription; +use forge_core::{Error, Result}; + +use crate::i18n::{self, Lang, misc, push as text}; +use crate::state::AppState; + +/// How long one push request may take before it counts as failed. +const SEND_TIMEOUT: Duration = Duration::from_secs(15); +/// Longest body text in a notification, in characters. +const BODY_CHARS: usize = 140; + +/// Announces changes to a user's devices to the settings pages that show them. Only the event +/// stream reads it; nothing here is stored, and a second server process would not see it. +pub struct PushLive { + tx: broadcast::Sender, +} + +impl Default for PushLive { + fn default() -> Self { + Self { + tx: broadcast::channel(64).0, + } + } +} + +impl PushLive { + /// Says that the devices of `user_id` changed. Nobody listening is fine. + pub fn publish(&self, user_id: &str) { + let _ = self.tx.send(user_id.to_owned()); + } + + /// A receiver for every change, from every user. A stream filters for its own user. + pub fn subscribe(&self) -> broadcast::Receiver { + self.tx.subscribe() + } +} + +/// What a notification says. Built per recipient, in the recipient's language. +#[derive(Clone)] +pub enum Alert { + /// Activity on an issue or pull request the user hears about. + Activity { + /// `owner/repo`. + repo: String, + number: i64, + title: String, + /// The verb of the activity (`misc::K::VerbOpened` and so on). + verb: misc::K, + actor: Option, + /// The relative link the notification opens. + url: String, + /// The thread id. A newer notification for the same thread replaces the older one. + thread: String, + }, + /// New security advisory alerts on a repo. + Advisories { + repo: String, + count: u64, + url: String, + }, + /// A site admin alert. + Admin { subject: String, detail: String }, + /// The test button. + Test, +} + +/// The JSON the service worker reads. Small, and nothing in it is a secret. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Message { + pub title: String, + pub body: String, + /// A relative link on this origin. + pub url: String, + /// Notifications with the same tag replace each other on the device. + pub tag: String, +} + +impl Alert { + /// The message for a recipient who reads `lang`. + pub fn message(&self, lang: Lang) -> Message { + match self { + Alert::Activity { + repo, + number, + title, + verb, + actor, + url, + thread, + } => { + let line = misc::activity_line(lang, *verb, actor.as_deref()); + Message { + title: format!("{repo}#{number}"), + body: clip(&format!("{line}: {title}")), + url: safe_url(url), + tag: format!("thread-{thread}"), + } + } + Alert::Advisories { repo, count, url } => Message { + title: clip(repo), + body: text::advisory_alerts(lang, *count), + url: safe_url(url), + tag: format!("advisories-{repo}"), + }, + Alert::Admin { subject, detail } => Message { + title: clip(subject), + body: clip(detail), + url: "/notifications".to_owned(), + tag: "admin-alert".to_owned(), + }, + Alert::Test => Message { + title: text::t(lang, text::K::TestTitle).to_owned(), + body: text::t(lang, text::K::TestBody).to_owned(), + url: "/settings/notifications".to_owned(), + tag: "test".to_owned(), + }, + } + } +} + +/// Shortens text to the body limit, in characters, one line. +fn clip(text: &str) -> String { + let one_line: String = text.split_whitespace().collect::>().join(" "); + if one_line.chars().count() <= BODY_CHARS { + return one_line; + } + let mut short: String = one_line.chars().take(BODY_CHARS - 3).collect(); + short.push_str("..."); + short +} + +/// A relative link only. The service worker opens it on this origin, so anything that could leave +/// the origin (a scheme, a protocol-relative `//host`) falls back to the notifications page. +pub fn safe_url(url: &str) -> String { + if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') { + url.to_owned() + } else { + "/notifications".to_owned() + } +} + +/// A short label for a device, from its User-Agent: "Chrome on Android", "Safari on iPhone". +pub fn agent_label(user_agent: &str) -> String { + let os = if user_agent.contains("iPhone") { + "iPhone" + } else if user_agent.contains("iPad") { + "iPad" + } else if user_agent.contains("Android") { + "Android" + } else if user_agent.contains("Windows") { + "Windows" + } else if user_agent.contains("Macintosh") { + "Mac" + } else if user_agent.contains("CrOS") { + "ChromeOS" + } else if user_agent.contains("Linux") { + "Linux" + } else { + "Unknown system" + }; + let browser = if user_agent.contains("Edg/") { + "Edge" + } else if user_agent.contains("OPR/") { + "Opera" + } else if user_agent.contains("Firefox/") { + "Firefox" + } else if user_agent.contains("Chrome/") || user_agent.contains("Chromium/") { + "Chrome" + } else if user_agent.contains("Safari/") { + "Safari" + } else { + "Browser" + }; + format!("{browser} on {os}") +} + +/// The shared HTTP client for push requests. Built once; redirects are not followed, since a push +/// service answers on the endpoint itself. +fn client() -> &'static reqwest::Client { + static CLIENT: OnceLock = OnceLock::new(); + CLIENT.get_or_init(|| { + reqwest::Client::builder() + .timeout(SEND_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .user_agent("forge-web-push") + .build() + .expect("the push client builds with the default TLS settings") + }) +} + +/// The instance's VAPID key pair. The private key is stored sealed with the instance key; the +/// first call creates the pair. +pub struct VapidKeys { + pub private: [u8; 32], + /// The public key, base64url. The browser subscribes with it. + pub public: String, +} + +/// The VAPID keys of this instance, creating and storing them on first use. +pub async fn vapid_keys(state: &AppState) -> Result { + let (public, sealed) = match state.store.web_push_keys().await? { + Some(pair) => pair, + None => { + let private = crypto::new_vapid_private(); + let public = crypto::vapid_public_key(&private)?; + let sealed = forge_core::secret::seal(&state.key, &private)?; + state.store.save_web_push_keys(&public, &sealed).await? + } + }; + let opened = forge_core::secret::open(&state.key, &sealed)?; + let private: [u8; 32] = opened + .try_into() + .map_err(|_| Error::Crypto("the stored VAPID key has the wrong length".into()))?; + Ok(VapidKeys { private, public }) +} + +/// The contact the push service may use about this instance: the base URL when it is https. +fn subject(base_url: &str) -> String { + let base = base_url.trim_end_matches('/'); + if base.starts_with("https://") { + base.to_owned() + } else { + "https://localhost".to_owned() + } +} + +/// What the push service answered for one device. +#[derive(Debug, PartialEq, Eq)] +pub enum Outcome { + Delivered, + /// 404 or 410: the subscription is gone and the device must be forgotten. + Gone, + Failed(String), +} + +/// Encrypts `payload` for one device and posts it to the device's push service. +pub async fn send_one( + keys: &VapidKeys, + subject: &str, + sub: &PushSubscription, + payload: &[u8], +) -> Outcome { + let built = (|| { + let p256dh = crypto::decode_b64(&sub.p256dh)?; + let auth = crypto::decode_b64(&sub.auth)?; + let key_pair = crypto::vapid_key_pair(&keys.private)?; + crypto::push_request( + &sub.endpoint, + &p256dh, + &auth, + subject, + &key_pair, + payload.to_vec(), + ) + })(); + let request = match built { + Ok(request) => request, + Err(e) => return Outcome::Failed(e.to_string()), + }; + let request = match reqwest::Request::try_from(request) { + Ok(request) => request, + Err(e) => return Outcome::Failed(e.to_string()), + }; + match client().execute(request).await { + Ok(res) => match res.status().as_u16() { + 200..=299 => Outcome::Delivered, + 404 | 410 => Outcome::Gone, + status => Outcome::Failed(format!("the push service answered {status}")), + }, + Err(e) => Outcome::Failed(e.to_string()), + } +} + +/// Queues `alert` for every device of `user_id`. Returns at once: the work runs on a spawned task. +pub fn queue(state: &AppState, user_id: &str, alert: Alert) { + let state = state.clone(); + let user_id = user_id.to_owned(); + tokio::spawn(async move { + if let Err(e) = deliver(&state, &user_id, &alert).await { + tracing::error!(error = %e, user_id, "web push: delivery failed"); + } + }); +} + +/// Sends `alert` to every device of `user_id` now and returns how many devices there are. Devices +/// the push service reports gone are removed. [`queue`] is the caller's entry point. +pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result { + let devices = state.store.push_subscriptions(user_id).await?; + if devices.is_empty() { + return Ok(0); + } + let lang = match state.store.user_by_id(user_id).await? { + Some(user) => i18n::resolve(Some(user.language.as_str()), &http::HeaderMap::new()), + None => Lang::En, + }; + let payload = serde_json::to_vec(&alert.message(lang)) + .map_err(|e| Error::Invalid(format!("the push payload does not encode: {e}")))?; + let keys = vapid_keys(state).await?; + let subject = subject(&state.live().base_url); + for device in &devices { + match send_one(&keys, &subject, device, &payload).await { + Outcome::Delivered => { + state.store.mark_push_delivered(&device.id).await?; + state.push_live.publish(user_id); + } + Outcome::Gone => { + state.store.delete_push_endpoint(&device.endpoint).await?; + state.push_live.publish(user_id); + } + Outcome::Failed(reason) => { + tracing::warn!(reason, device = %device.id, "web push: a device was not reached"); + } + } + } + Ok(devices.len()) +} + +#[cfg(test)] +mod tests { + use super::*; + use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint; + + fn activity(actor: Option<&str>) -> Alert { + Alert::Activity { + repo: "tahinli/forge".into(), + number: 42, + title: "Crash on startup\nwhen the cache is cold".into(), + verb: misc::K::VerbCommented, + actor: actor.map(str::to_owned), + url: "/tahinli/forge/issues/42".into(), + thread: "issue-1".into(), + } + } + + #[test] + fn an_activity_payload_is_short_and_names_the_thread() { + let msg = activity(Some("tahinli")).message(Lang::En); + assert_eq!(msg.title, "tahinli/forge#42"); + assert_eq!( + msg.body, + "commented by tahinli: Crash on startup when the cache is cold" + ); + assert_eq!(msg.url, "/tahinli/forge/issues/42"); + assert_eq!(msg.tag, "thread-issue-1"); + } + + #[test] + fn the_body_is_clipped_to_the_limit() { + let long = Alert::Admin { + subject: "Backup".into(), + detail: "x".repeat(400), + }; + let msg = long.message(Lang::En); + assert_eq!(msg.body.chars().count(), BODY_CHARS); + assert!(msg.body.ends_with("...")); + } + + #[test] + fn the_payload_follows_the_recipient_language() { + let msg = activity(None).message(Lang::Tr); + assert!(msg.body.starts_with("Yorumlandı"), "{}", msg.body); + let advisories = Alert::Advisories { + repo: "tahinli/forge".into(), + count: 3, + url: "/tahinli/forge/security".into(), + }; + assert_eq!(advisories.message(Lang::En).body, "3 new security alerts"); + assert_eq!(advisories.message(Lang::Tr).body, "3 yeni güvenlik uyarısı"); + } + + #[test] + fn a_link_must_stay_on_this_origin() { + assert_eq!(safe_url("/tahinli/forge"), "/tahinli/forge"); + assert_eq!(safe_url("https://evil.example/x"), "/notifications"); + assert_eq!(safe_url("//evil.example/x"), "/notifications"); + assert_eq!(safe_url("/\\evil.example"), "/notifications"); + } + + #[test] + fn device_labels_name_the_browser_and_the_system() { + let chrome_android = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36"; + assert_eq!(agent_label(chrome_android), "Chrome on Android"); + let safari_iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1"; + assert_eq!(agent_label(safari_iphone), "Safari on iPhone"); + assert_eq!(agent_label("curl/8.0"), "Browser on Unknown system"); + } + + #[test] + fn the_subject_is_https_or_the_fallback() { + assert_eq!( + subject("https://forge.example.test/"), + "https://forge.example.test" + ); + assert_eq!(subject("http://127.0.0.1:7660"), "https://localhost"); + } + + #[test] + fn push_live_reaches_a_listener_and_tolerates_none() { + let live = PushLive::default(); + live.publish("nobody"); + let mut rx = live.subscribe(); + live.publish("tahinli"); + assert_eq!(rx.try_recv().expect("event"), "tahinli"); + } + + /// A local stand-in for a push service: `/gone` answers 410, `/ok` answers 201, and each + /// request is read in full (headers and body) before it is answered. + async fn mock_push_service() -> std::net::SocketAddr { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let addr = listener.local_addr().expect("addr"); + tokio::spawn(async move { + loop { + let Ok((mut socket, _)) = listener.accept().await else { + return; + }; + tokio::spawn(async move { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let (head_end, length) = loop { + let n = socket.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + return; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..end]).to_ascii_lowercase(); + let length = head + .lines() + .find_map(|l| l.strip_prefix("content-length:")) + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0); + break (end + 4, length); + } + }; + while buf.len() < head_end + length { + let n = socket.read(&mut chunk).await.unwrap_or(0); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + } + let request = String::from_utf8_lossy(&buf[..head_end]).into_owned(); + let status = if request.starts_with("POST /gone") { + "410 Gone" + } else { + "201 Created" + }; + let reply = format!( + "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + let _ = socket.write_all(reply.as_bytes()).await; + }); + } + }); + addr + } + + fn device(endpoint: String) -> PushSubscription { + let secret = web_push_native::p256::SecretKey::from_slice(&crypto::new_vapid_private()) + .expect("scalar"); + let point = secret.public_key().to_encoded_point(false); + PushSubscription { + id: endpoint.clone(), + user_id: String::new(), + endpoint, + p256dh: crypto::encode_b64(point.as_bytes()), + auth: crypto::encode_b64(&[9u8; 16]), + agent_label: "Chrome on Linux".into(), + created_at: String::new(), + last_success_at: None, + } + } + + #[tokio::test] + async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let user = state + .store + .create_user("tahinli", None, "h", false) + .await + .expect("user"); + let addr = mock_push_service().await; + let gone = format!("http://{addr}/gone"); + let ok = format!("http://{addr}/ok"); + state + .store + .save_push_subscription( + &user.id, + &gone, + &device(gone.clone()).p256dh, + &device(gone.clone()).auth, + "Chrome on Linux", + ) + .await + .expect("save gone"); + state + .store + .save_push_subscription( + &user.id, + &ok, + &device(ok.clone()).p256dh, + &device(ok.clone()).auth, + "Chrome on Linux", + ) + .await + .expect("save ok"); + + let sent = deliver(&state, &user.id, &Alert::Test) + .await + .expect("deliver"); + assert_eq!(sent, 2); + let left = state + .store + .push_subscriptions(&user.id) + .await + .expect("list"); + assert_eq!(left.len(), 1, "the 410 device is forgotten"); + assert_eq!(left[0].endpoint, ok); + assert!( + left[0].last_success_at.is_some(), + "the delivered device is stamped" + ); + } + + #[tokio::test] + async fn the_payload_is_encrypted_for_the_device_and_the_status_is_read() { + let addr = mock_push_service().await; + let private = crypto::new_vapid_private(); + let keys = VapidKeys { + public: crypto::vapid_public_key(&private).expect("public"), + private, + }; + let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json"); + let ok = device(format!("http://{addr}/ok")); + assert_eq!( + send_one(&keys, "https://localhost", &ok, &payload).await, + Outcome::Delivered + ); + let gone = device(format!("http://{addr}/gone")); + assert_eq!( + send_one(&keys, "https://localhost", &gone, &payload).await, + Outcome::Gone + ); + } +} diff --git a/docs/notifications.md b/docs/notifications.md new file mode 100644 index 0000000..d7d5d71 --- /dev/null +++ b/docs/notifications.md @@ -0,0 +1,65 @@ +# Notifications + +Forge keeps an inbox of notifications for each user (the bell in the top bar). The same +notifications can also reach you by email, and by Web Push on your devices. + +## Web Push + +Web Push delivers a notification to a device even when no Forge tab is open. It works in +Chromium-based browsers, Firefox and Safari, on desktop and on Android. On iPhone and iPad it works +only for an app installed to the Home Screen. + +### Requirements + +- **HTTPS.** Browsers only offer push on a secure origin. Serve Forge over HTTPS (the usual + reverse-proxy setup). `localhost` also counts as secure for testing. +- **iOS and iPadOS.** Open Forge in Safari, use Share, then Add to Home Screen, and open Forge from + that icon. Then turn push on in the notification settings. Safari in a normal tab cannot receive + push. iOS 16.4 or later is needed. +- **Permission.** The browser asks for permission the first time you turn push on. If you refused, + allow notifications for the site in the browser's site settings and try again. + +### Turning it on + +1. Open **Settings, Notifications**. +2. Under **Push notifications on this device**, choose **Turn on for this device**, then allow + notifications when the browser asks. +3. Choose **Send test notification** to check that the device gets one. + +Each browser profile, and each installed app, is a separate device. The **Devices** list shows +every device with push on, when it was added and when it last received a notification. Remove a +device there to stop its notifications; **Turn off for this device** does the same for the device +you are using. + +### What is sent + +A notification carries a short title (for example `owner/repo#12`), a one-line body (the activity +and the start of the title, at most 140 characters) and the link it opens. Nothing else is sent: no +token, no email address and no body text. The push service sees that a message was delivered to +your device, as with any push service. + +Only notifications that reach your inbox are pushed. The same rules apply: you hear about activity +on threads you follow, when you are mentioned, assigned or asked to review, and so on. Watching a +repo or ignoring a thread changes what reaches your inbox, and so what is pushed. Security alerts +and site admin alerts are pushed the same way. + +Notifications on a lock screen can show the title of a private repository. Turn push off for a +device you share. + +### Devices that stop working + +A push service answers `404` or `410` for a subscription that no longer exists, for example after +the browser was reset or the app was uninstalled. Forge removes such a device by itself. A device +that keeps failing is kept, so a temporary outage does not drop it. + +### Operator notes + +- Forge creates one VAPID key pair the first time push is used and stores it in the database. The + private key is sealed with the instance key (`data_dir/forge.key`). Keep both in your backups: a + restore that loses the VAPID key makes every device subscribe again. +- The VAPID contact is the `base_url` of the instance when it is an `https` URL. Behind plain HTTP + the contact falls back to `https://localhost`. +- Pushes go out from a background task and never delay the request that caused them. The server + makes outgoing requests to the push services, so it needs outbound HTTPS. +- Each account can turn push on for at most 20 devices. +- The service worker is served at `/sw.js`, the web app manifest at `/manifest.webmanifest`. diff --git a/style/main.scss b/style/main.scss index 64a8ddd..933e425 100644 --- a/style/main.scss +++ b/style/main.scss @@ -1630,6 +1630,55 @@ code { } } +// Settings > Notifications: the Web Push card. Devices are a plain list, one row per device, that +// stacks on a phone and keeps the remove button at the row's end on wider screens. +.push-card { + display: flex; + flex-direction: column; + gap: 12px; + + h2 { + margin: 0; + } + + .actions { + margin-top: 0; + } +} + +.push-devices { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 8px; +} + +.push-device { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px 12px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: var(--radius-lg); + min-width: 0; + + > div { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + overflow-wrap: anywhere; + } +} + +.push-remove { + margin: 0; +} + // Settings > Notifications: the checkbox with its helper, then the notes saying why it is locked. // One 12px rhythm between the field, each note and the no-JS actions; helper text and notes share // one size.