forge
Explore
Log in

Don't you dare go Hollow

Web push notifications with a service worker and per-device settings

Browse files at this commit

8a4b8e735e86f1bc40997b3c9572d005a4aefa01Ahmet Kaan GümüşParent: ca21cba
  • feat
    • web push notifications with a service worker and per-device settings
Show full message
✨ feat: web push notifications with a service worker and per-device settings

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.lockmodified+533 -73
@@ -90,6 +90,16 @@ dependencies = [
90 "zeroize",90 "zeroize",
91 ]91 ]
92 92
93+[[package]]
94+name = "aes-keywrap"
95+version = "0.9.1"
96+source = "registry+https://github.com/rust-lang/crates.io-index"
97+checksum = "cf71a903b87eeef4903e7077cc9689f0c8449e093395db09dc48d1a39934e770"
98+dependencies = [
99+ "aes 0.9.3",
100+ "byteorder",
101+]
102+
93 [[package]]103 [[package]]
94 name = "ahash"104 name = "ahash"
95 version = "0.8.12"105 version = "0.8.12"
@@ -410,6 +420,12 @@ dependencies = [
410 "pkg-config",420 "pkg-config",
411 ]421 ]
412 422
423+[[package]]
424+name = "base16ct"
425+version = "0.2.0"
426+source = "registry+https://github.com/rust-lang/crates.io-index"
427+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
428+
413 [[package]]429 [[package]]
414 name = "base16ct"430 name = "base16ct"
415 version = "1.0.0"431 version = "1.0.0"
@@ -507,6 +523,12 @@ dependencies = [
507 "which",523 "which",
508 ]524 ]
509 525
526+[[package]]
527+name = "binstring"
528+version = "0.1.8"
529+source = "registry+https://github.com/rust-lang/crates.io-index"
530+checksum = "3cff57e3fb66fb8077cb7f5de37442fff99b4ee99d71e6b946ad9b6b7246c27c"
531+
510 [[package]]532 [[package]]
511 name = "bit-set"533 name = "bit-set"
512 version = "0.8.0"534 version = "0.8.0"
@@ -564,6 +586,16 @@ dependencies = [
564 "digest 0.11.3",586 "digest 0.11.3",
565 ]587 ]
566 588
589+[[package]]
590+name = "blake2b_simd"
591+version = "1.0.5"
592+source = "registry+https://github.com/rust-lang/crates.io-index"
593+checksum = "3560a7b1951efe814fcd721938313adc56753ca39f4b23847d7e9a2402f5dbff"
594+dependencies = [
595+ "arrayvec",
596+ "constant_time_eq",
597+]
598+
567 [[package]]599 [[package]]
568 name = "block-buffer"600 name = "block-buffer"
569 version = "0.10.4"601 version = "0.10.4"
@@ -919,6 +951,17 @@ version = "0.5.4"
919 source = "registry+https://github.com/rust-lang/crates.io-index"951 source = "registry+https://github.com/rust-lang/crates.io-index"
920 checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"952 checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
921 953
954+[[package]]
955+name = "coarsetime"
956+version = "0.1.38"
957+source = "registry+https://github.com/rust-lang/crates.io-index"
958+checksum = "eae63702c5627c75addbfb1ea9d1b3842205a6ffd43e4cce884a2a9eb1828fd7"
959+dependencies = [
960+ "libc",
961+ "wasix",
962+ "wasm-bindgen",
963+]
964+
922 [[package]]965 [[package]]
923 name = "codemap"966 name = "codemap"
924 version = "0.1.3"967 version = "0.1.3"
@@ -998,6 +1041,12 @@ dependencies = [
998 "crossbeam-utils",1041 "crossbeam-utils",
999 ]1042 ]
1000 1043
1044+[[package]]
1045+name = "const-oid"
1046+version = "0.9.6"
1047+source = "registry+https://github.com/rust-lang/crates.io-index"
1048+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
1049+
1001 [[package]]1050 [[package]]
1002 name = "const-oid"1051 name = "const-oid"
1003 version = "0.10.2"1052 version = "0.10.2"
@@ -1025,6 +1074,12 @@ dependencies = [
1025 "unicode-xid",1074 "unicode-xid",
1026 ]1075 ]
1027 1076
1077+[[package]]
1078+name = "constant_time_eq"
1079+version = "0.4.2"
1080+source = "registry+https://github.com/rust-lang/crates.io-index"
1081+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
1082+
1028 [[package]]1083 [[package]]
1029 name = "cookie"1084 name = "cookie"
1030 version = "0.18.2"1085 version = "0.18.2"
@@ -1168,6 +1223,18 @@ version = "0.2.4"
1168 source = "registry+https://github.com/rust-lang/crates.io-index"1223 source = "registry+https://github.com/rust-lang/crates.io-index"
1169 checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"1224 checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
1170 1225
1226+[[package]]
1227+name = "crypto-bigint"
1228+version = "0.5.5"
1229+source = "registry+https://github.com/rust-lang/crates.io-index"
1230+checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
1231+dependencies = [
1232+ "generic-array 0.14.7",
1233+ "rand_core 0.6.4",
1234+ "subtle",
1235+ "zeroize",
1236+]
1237+
1171 [[package]]1238 [[package]]
1172 name = "crypto-bigint"1239 name = "crypto-bigint"
1173 version = "0.7.5"1240 version = "0.7.5"
@@ -1213,7 +1280,7 @@ version = "0.7.2"
1213 source = "registry+https://github.com/rust-lang/crates.io-index"1280 source = "registry+https://github.com/rust-lang/crates.io-index"
1214 checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f"1281 checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f"
1215 dependencies = [1282 dependencies = [
1216- "crypto-bigint",1283+ "crypto-bigint 0.7.5",
1217 "rand_core 0.10.1",1284 "rand_core 0.10.1",
1218 ]1285 ]
1219 1286
@@ -1251,6 +1318,12 @@ dependencies = [
1251 "syn 3.0.9",1318 "syn 3.0.9",
1252 ]1319 ]
1253 1320
1321+[[package]]
1322+name = "ct-codecs"
1323+version = "1.1.8"
1324+source = "registry+https://github.com/rust-lang/crates.io-index"
1325+checksum = "8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd"
1326+
1254 [[package]]1327 [[package]]
1255 name = "ctr"1328 name = "ctr"
1256 version = "0.9.2"1329 version = "0.9.2"
@@ -1453,14 +1526,25 @@ dependencies = [
1453 "syn 2.0.119",1526 "syn 2.0.119",
1454 ]1527 ]
1455 1528
1529+[[package]]
1530+name = "der"
1531+version = "0.7.10"
1532+source = "registry+https://github.com/rust-lang/crates.io-index"
1533+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
1534+dependencies = [
1535+ "const-oid 0.9.6",
1536+ "pem-rfc7468 0.7.0",
1537+ "zeroize",
1538+]
1539+
1456 [[package]]1540 [[package]]
1457 name = "der"1541 name = "der"
1458 version = "0.8.2"1542 version = "0.8.2"
1459 source = "registry+https://github.com/rust-lang/crates.io-index"1543 source = "registry+https://github.com/rust-lang/crates.io-index"
1460 checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"1544 checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"
1461 dependencies = [1545 dependencies = [
1462- "const-oid",1546+ "const-oid 0.10.2",
1463- "pem-rfc7468",1547+ "pem-rfc7468 1.0.0",
1464 "zeroize",1548 "zeroize",
1465 ]1549 ]
1466 1550
@@ -1555,6 +1639,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1555 checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"1639 checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
1556 dependencies = [1640 dependencies = [
1557 "block-buffer 0.10.4",1641 "block-buffer 0.10.4",
1642+ "const-oid 0.9.6",
1558 "crypto-common 0.1.7",1643 "crypto-common 0.1.7",
1559 "subtle",1644 "subtle",
1560 ]1645 ]
@@ -1566,7 +1651,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1566 checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"1651 checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
1567 dependencies = [1652 dependencies = [
1568 "block-buffer 0.12.1",1653 "block-buffer 0.12.1",
1569- "const-oid",1654+ "const-oid 0.10.2",
1570 "crypto-common 0.2.2",1655 "crypto-common 0.2.2",
1571 "ctutils",1656 "ctutils",
1572 ]1657 ]
@@ -1609,29 +1694,64 @@ version = "1.0.5"
1609 source = "registry+https://github.com/rust-lang/crates.io-index"1694 source = "registry+https://github.com/rust-lang/crates.io-index"
1610 checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"1695 checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
1611 1696
1697+[[package]]
1698+name = "ecdsa"
1699+version = "0.16.9"
1700+source = "registry+https://github.com/rust-lang/crates.io-index"
1701+checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
1702+dependencies = [
1703+ "der 0.7.10",
1704+ "digest 0.10.7",
1705+ "elliptic-curve 0.13.8",
1706+ "rfc6979 0.4.0",
1707+ "signature 2.2.0",
1708+ "spki 0.7.3",
1709+]
1710+
1612 [[package]]1711 [[package]]
1613 name = "ecdsa"1712 name = "ecdsa"
1614 version = "0.17.0"1713 version = "0.17.0"
1615 source = "registry+https://github.com/rust-lang/crates.io-index"1714 source = "registry+https://github.com/rust-lang/crates.io-index"
1616 checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0"1715 checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0"
1617 dependencies = [1716 dependencies = [
1618- "der",1717+ "der 0.8.2",
1619 "digest 0.11.3",1718 "digest 0.11.3",
1620- "elliptic-curve",1719+ "elliptic-curve 0.14.1",
1621- "rfc6979",1720+ "rfc6979 0.6.0",
1622- "signature",1721+ "signature 3.0.0",
1623- "spki",1722+ "spki 0.8.1",
1624 "zeroize",1723 "zeroize",
1625 ]1724 ]
1626 1725
1726+[[package]]
1727+name = "ece-native"
1728+version = "0.5.0"
1729+source = "registry+https://github.com/rust-lang/crates.io-index"
1730+checksum = "6911cc97c62febd8cbcb2cb49ed21c58ccd418a80c43f20df4973ee08484e65d"
1731+dependencies = [
1732+ "aes-gcm 0.10.3",
1733+ "hkdf 0.12.4",
1734+ "sha2 0.10.9",
1735+]
1736+
1627 [[package]]1737 [[package]]
1628 name = "ed25519"1738 name = "ed25519"
1629 version = "3.0.0"1739 version = "3.0.0"
1630 source = "registry+https://github.com/rust-lang/crates.io-index"1740 source = "registry+https://github.com/rust-lang/crates.io-index"
1631 checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"1741 checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
1632 dependencies = [1742 dependencies = [
1633- "pkcs8",1743+ "pkcs8 0.11.0",
1634- "signature",1744+ "signature 3.0.0",
1745+]
1746+
1747+[[package]]
1748+name = "ed25519-compact"
1749+version = "2.6.0"
1750+source = "registry+https://github.com/rust-lang/crates.io-index"
1751+checksum = "1454db4f2edb7f0e8fe0c5b375b0c978fc63244cc9f010d160e417eb10139aa8"
1752+dependencies = [
1753+ "ct-codecs",
1754+ "getrandom 0.4.3",
1635 ]1755 ]
1636 1756
1637 [[package]]1757 [[package]]
@@ -1645,7 +1765,7 @@ dependencies = [
1645 "rand_core 0.10.1",1765 "rand_core 0.10.1",
1646 "serde",1766 "serde",
1647 "sha2 0.11.1",1767 "sha2 0.11.1",
1648- "signature",1768+ "signature 3.0.0",
1649 "subtle",1769 "subtle",
1650 "zeroize",1770 "zeroize",
1651 ]1771 ]
@@ -1662,24 +1782,45 @@ version = "1.19.0"
1662 source = "registry+https://github.com/rust-lang/crates.io-index"1782 source = "registry+https://github.com/rust-lang/crates.io-index"
1663 checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"1783 checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
1664 1784
1785+[[package]]
1786+name = "elliptic-curve"
1787+version = "0.13.8"
1788+source = "registry+https://github.com/rust-lang/crates.io-index"
1789+checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
1790+dependencies = [
1791+ "base16ct 0.2.0",
1792+ "crypto-bigint 0.5.5",
1793+ "digest 0.10.7",
1794+ "ff 0.13.1",
1795+ "generic-array 0.14.7",
1796+ "group 0.13.0",
1797+ "hkdf 0.12.4",
1798+ "pem-rfc7468 0.7.0",
1799+ "pkcs8 0.10.2",
1800+ "rand_core 0.6.4",
1801+ "sec1 0.7.3",
1802+ "subtle",
1803+ "zeroize",
1804+]
1805+
1665 [[package]]1806 [[package]]
1666 name = "elliptic-curve"1807 name = "elliptic-curve"
1667 version = "0.14.1"1808 version = "0.14.1"
1668 source = "registry+https://github.com/rust-lang/crates.io-index"1809 source = "registry+https://github.com/rust-lang/crates.io-index"
1669 checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65"1810 checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65"
1670 dependencies = [1811 dependencies = [
1671- "base16ct",1812+ "base16ct 1.0.0",
1672- "crypto-bigint",1813+ "crypto-bigint 0.7.5",
1673 "crypto-common 0.2.2",1814 "crypto-common 0.2.2",
1674 "digest 0.11.3",1815 "digest 0.11.3",
1675- "ff",1816+ "ff 0.14.0",
1676- "group",1817+ "group 0.14.0",
1677 "hkdf 0.13.0",1818 "hkdf 0.13.0",
1678 "hybrid-array",1819 "hybrid-array",
1679- "pem-rfc7468",1820+ "pem-rfc7468 1.0.0",
1680- "pkcs8",1821+ "pkcs8 0.11.0",
1681 "rand_core 0.10.1",1822 "rand_core 0.10.1",
1682- "sec1",1823+ "sec1 0.8.1",
1683 "subtle",1824 "subtle",
1684 "zeroize",1825 "zeroize",
1685 ]1826 ]
@@ -1875,6 +2016,16 @@ dependencies = [
1875 "syn 3.0.9",2016 "syn 3.0.9",
1876 ]2017 ]
1877 2018
2019+[[package]]
2020+name = "ff"
2021+version = "0.13.1"
2022+source = "registry+https://github.com/rust-lang/crates.io-index"
2023+checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
2024+dependencies = [
2025+ "rand_core 0.6.4",
2026+ "subtle",
2027+]
2028+
1878 [[package]]2029 [[package]]
1879 name = "ff"2030 name = "ff"
1880 version = "0.14.0"2031 version = "0.14.0"
@@ -2126,6 +2277,7 @@ dependencies = [
2126 "tracing",2277 "tracing",
2127 "tracing-subscriber",2278 "tracing-subscriber",
2128 "ulid",2279 "ulid",
2280+ "web-push-native",
2129 "webauthn-authenticator-rs",2281 "webauthn-authenticator-rs",
2130 "webauthn-rs",2282 "webauthn-rs",
2131 "webauthn-rs-proto",2283 "webauthn-rs-proto",
@@ -2289,6 +2441,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
2289 dependencies = [2441 dependencies = [
2290 "typenum",2442 "typenum",
2291 "version_check",2443 "version_check",
2444+ "zeroize",
2292 ]2445 ]
2293 2446
2294 [[package]]2447 [[package]]
@@ -3211,13 +3364,24 @@ dependencies = [
3211 "rand 0.8.8",3364 "rand 0.8.8",
3212 ]3365 ]
3213 3366
3367+[[package]]
3368+name = "group"
3369+version = "0.13.0"
3370+source = "registry+https://github.com/rust-lang/crates.io-index"
3371+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
3372+dependencies = [
3373+ "ff 0.13.1",
3374+ "rand_core 0.6.4",
3375+ "subtle",
3376+]
3377+
3214 [[package]]3378 [[package]]
3215 name = "group"3379 name = "group"
3216 version = "0.14.0"3380 version = "0.14.0"
3217 source = "registry+https://github.com/rust-lang/crates.io-index"3381 source = "registry+https://github.com/rust-lang/crates.io-index"
3218 checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4"3382 checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4"
3219 dependencies = [3383 dependencies = [
3220- "ff",3384+ "ff 0.14.0",
3221 "rand_core 0.10.1",3385 "rand_core 0.10.1",
3222 "subtle",3386 "subtle",
3223 ]3387 ]
@@ -3363,6 +3527,33 @@ dependencies = [
3363 "digest 0.11.3",3527 "digest 0.11.3",
3364 ]3528 ]
3365 3529
3530+[[package]]
3531+name = "hmac-sha1-compact"
3532+version = "1.1.8"
3533+source = "registry+https://github.com/rust-lang/crates.io-index"
3534+checksum = "7ed9b23855291da44e7e84616e19dc0d969c3580e14ffa6b759f28775e26afc1"
3535+dependencies = [
3536+ "digest 0.10.7",
3537+]
3538+
3539+[[package]]
3540+name = "hmac-sha256"
3541+version = "1.1.15"
3542+source = "registry+https://github.com/rust-lang/crates.io-index"
3543+checksum = "1ad320b3b96fb2a455a0726d16efe0a5afdbd34b71dea5bc53b05ea057714d4e"
3544+dependencies = [
3545+ "digest 0.10.7",
3546+]
3547+
3548+[[package]]
3549+name = "hmac-sha512"
3550+version = "1.1.13"
3551+source = "registry+https://github.com/rust-lang/crates.io-index"
3552+checksum = "66de62217b456dfbbba2bed965a134a4df57c48f0eac4c772018aee528e72244"
3553+dependencies = [
3554+ "digest 0.10.7",
3555+]
3556+
3366 [[package]]3557 [[package]]
3367 name = "home"3558 name = "home"
3368 version = "0.5.12"3559 version = "0.5.12"
@@ -4005,6 +4196,46 @@ dependencies = [
4005 "wasm-bindgen",4196 "wasm-bindgen",
4006 ]4197 ]
4007 4198
4199+[[package]]
4200+name = "jwt-simple"
4201+version = "0.12.17"
4202+source = "registry+https://github.com/rust-lang/crates.io-index"
4203+checksum = "06a4207b9d1f423858853fb9ee8b34aebc2b661f3b446ca4efda46c4b3700a2f"
4204+dependencies = [
4205+ "anyhow",
4206+ "binstring",
4207+ "blake2b_simd",
4208+ "coarsetime",
4209+ "ct-codecs",
4210+ "ed25519-compact",
4211+ "hmac-sha1-compact",
4212+ "hmac-sha256",
4213+ "hmac-sha512",
4214+ "k256",
4215+ "p256 0.13.2",
4216+ "p384 0.13.1",
4217+ "rand 0.8.8",
4218+ "serde",
4219+ "serde_json",
4220+ "superboring",
4221+ "thiserror 2.0.21",
4222+ "zeroize",
4223+]
4224+
4225+[[package]]
4226+name = "k256"
4227+version = "0.13.4"
4228+source = "registry+https://github.com/rust-lang/crates.io-index"
4229+checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b"
4230+dependencies = [
4231+ "cfg-if",
4232+ "ecdsa 0.16.9",
4233+ "elliptic-curve 0.13.8",
4234+ "once_cell",
4235+ "sha2 0.10.9",
4236+ "signature 2.2.0",
4237+]
4238+
4008 [[package]]4239 [[package]]
4009 name = "keccak"4240 name = "keccak"
4010 version = "0.2.2"4241 version = "0.2.2"
@@ -4054,6 +4285,9 @@ name = "lazy_static"
4054 version = "1.5.1"4285 version = "1.5.1"
4055 source = "registry+https://github.com/rust-lang/crates.io-index"4286 source = "registry+https://github.com/rust-lang/crates.io-index"
4056 checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"4287 checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
4288+dependencies = [
4289+ "spin 0.9.9",
4290+]
4057 4291
4058 [[package]]4292 [[package]]
4059 name = "lazycell"4293 name = "lazycell"
@@ -4440,6 +4674,22 @@ dependencies = [
4440 "windows-sys 0.61.2",4674 "windows-sys 0.61.2",
4441 ]4675 ]
4442 4676
4677+[[package]]
4678+name = "ml-dsa"
4679+version = "0.1.1"
4680+source = "registry+https://github.com/rust-lang/crates.io-index"
4681+checksum = "add6b9d92e496f16f4526d68ff29da1483aba4b119baeab8bed3b9e3544a6f3d"
4682+dependencies = [
4683+ "const-oid 0.10.2",
4684+ "crypto-common 0.2.2",
4685+ "ctutils",
4686+ "hybrid-array",
4687+ "module-lattice",
4688+ "pkcs8 0.11.0",
4689+ "shake",
4690+ "signature 3.0.0",
4691+]
4692+
4443 [[package]]4693 [[package]]
4444 name = "ml-kem"4694 name = "ml-kem"
4445 version = "0.3.2"4695 version = "0.3.2"
@@ -4449,7 +4699,7 @@ dependencies = [
4449 "hybrid-array",4699 "hybrid-array",
4450 "kem",4700 "kem",
4451 "module-lattice",4701 "module-lattice",
4452- "pkcs8",4702+ "pkcs8 0.11.0",
4453 "rand_core 0.10.1",4703 "rand_core 0.10.1",
4454 "sha3 0.11.0",4704 "sha3 0.11.0",
4455 ]4705 ]
@@ -4632,6 +4882,22 @@ dependencies = [
4632 "rand_core 0.10.1",4882 "rand_core 0.10.1",
4633 ]4883 ]
4634 4884
4885+[[package]]
4886+name = "num-bigint-dig"
4887+version = "0.8.6"
4888+source = "registry+https://github.com/rust-lang/crates.io-index"
4889+checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
4890+dependencies = [
4891+ "lazy_static",
4892+ "libm",
4893+ "num-integer",
4894+ "num-iter",
4895+ "num-traits",
4896+ "rand 0.8.8",
4897+ "smallvec",
4898+ "zeroize",
4899+]
4900+
4635 [[package]]4901 [[package]]
4636 name = "num-conv"4902 name = "num-conv"
4637 version = "0.2.2"4903 version = "0.2.2"
@@ -4658,6 +4924,16 @@ dependencies = [
4658 "num-traits",4924 "num-traits",
4659 ]4925 ]
4660 4926
4927+[[package]]
4928+name = "num-iter"
4929+version = "0.1.46"
4930+source = "registry+https://github.com/rust-lang/crates.io-index"
4931+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
4932+dependencies = [
4933+ "num-integer",
4934+ "num-traits",
4935+]
4936+
4661 [[package]]4937 [[package]]
4662 name = "num-traits"4938 name = "num-traits"
4663 version = "0.2.19"4939 version = "0.2.19"
@@ -4665,6 +4941,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
4665 checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"4941 checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
4666 dependencies = [4942 dependencies = [
4667 "autocfg",4943 "autocfg",
4944+ "libm",
4668 ]4945 ]
4669 4946
4670 [[package]]4947 [[package]]
@@ -4885,30 +5162,54 @@ version = "3.5.0"
4885 source = "registry+https://github.com/rust-lang/crates.io-index"5162 source = "registry+https://github.com/rust-lang/crates.io-index"
4886 checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"5163 checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"
4887 5164
5165+[[package]]
5166+name = "p256"
5167+version = "0.13.2"
5168+source = "registry+https://github.com/rust-lang/crates.io-index"
5169+checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
5170+dependencies = [
5171+ "ecdsa 0.16.9",
5172+ "elliptic-curve 0.13.8",
5173+ "primeorder 0.13.6",
5174+ "sha2 0.10.9",
5175+]
5176+
4888 [[package]]5177 [[package]]
4889 name = "p256"5178 name = "p256"
4890 version = "0.14.0"5179 version = "0.14.0"
4891 source = "registry+https://github.com/rust-lang/crates.io-index"5180 source = "registry+https://github.com/rust-lang/crates.io-index"
4892 checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a"5181 checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a"
4893 dependencies = [5182 dependencies = [
4894- "ecdsa",5183+ "ecdsa 0.17.0",
4895- "elliptic-curve",5184+ "elliptic-curve 0.14.1",
4896 "primefield",5185 "primefield",
4897- "primeorder",5186+ "primeorder 0.14.0",
4898 "sha2 0.11.1",5187 "sha2 0.11.1",
4899 ]5188 ]
4900 5189
5190+[[package]]
5191+name = "p384"
5192+version = "0.13.1"
5193+source = "registry+https://github.com/rust-lang/crates.io-index"
5194+checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"
5195+dependencies = [
5196+ "ecdsa 0.16.9",
5197+ "elliptic-curve 0.13.8",
5198+ "primeorder 0.13.6",
5199+ "sha2 0.10.9",
5200+]
5201+
4901 [[package]]5202 [[package]]
4902 name = "p384"5203 name = "p384"
4903 version = "0.14.0"5204 version = "0.14.0"
4904 source = "registry+https://github.com/rust-lang/crates.io-index"5205 source = "registry+https://github.com/rust-lang/crates.io-index"
4905 checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f"5206 checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f"
4906 dependencies = [5207 dependencies = [
4907- "ecdsa",5208+ "ecdsa 0.17.0",
4908- "elliptic-curve",5209+ "elliptic-curve 0.14.1",
4909 "fiat-crypto",5210 "fiat-crypto",
4910 "primefield",5211 "primefield",
4911- "primeorder",5212+ "primeorder 0.14.0",
4912 "sha2 0.11.1",5213 "sha2 0.11.1",
4913 ]5214 ]
4914 5215
@@ -4918,11 +5219,11 @@ version = "0.14.0"
4918 source = "registry+https://github.com/rust-lang/crates.io-index"5219 source = "registry+https://github.com/rust-lang/crates.io-index"
4919 checksum = "4ad64cc32c2dc466317c12ee5853e61f159f9eab1fe7efade0395dc2e7b43449"5220 checksum = "4ad64cc32c2dc466317c12ee5853e61f159f9eab1fe7efade0395dc2e7b43449"
4920 dependencies = [5221 dependencies = [
4921- "base16ct",5222+ "base16ct 1.0.0",
4922- "ecdsa",5223+ "ecdsa 0.17.0",
4923- "elliptic-curve",5224+ "elliptic-curve 0.14.1",
4924 "primefield",5225 "primefield",
4925- "primeorder",5226+ "primeorder 0.14.0",
4926 "sha2 0.11.1",5227 "sha2 0.11.1",
4927 ]5228 ]
4928 5229
@@ -4941,7 +5242,7 @@ version = "0.2.4"
4941 source = "registry+https://github.com/rust-lang/crates.io-index"5242 source = "registry+https://github.com/rust-lang/crates.io-index"
4942 checksum = "f0786409b5aaa884655c9b4065681db0835db0cc185a6fb19fb17a5d38656866"5243 checksum = "f0786409b5aaa884655c9b4065681db0835db0cc185a6fb19fb17a5d38656866"
4943 dependencies = [5244 dependencies = [
4944- "base16ct",5245+ "base16ct 1.0.0",
4945 "byteorder",5246 "byteorder",
4946 "bytes",5247 "bytes",
4947 "delegate",5248 "delegate",
@@ -5034,6 +5335,15 @@ dependencies = [
5034 "hmac 0.13.0",5335 "hmac 0.13.0",
5035 ]5336 ]
5036 5337
5338+[[package]]
5339+name = "pem-rfc7468"
5340+version = "0.7.0"
5341+source = "registry+https://github.com/rust-lang/crates.io-index"
5342+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
5343+dependencies = [
5344+ "base64ct",
5345+]
5346+
5037 [[package]]5347 [[package]]
5038 name = "pem-rfc7468"5348 name = "pem-rfc7468"
5039 version = "1.0.0"5349 version = "1.0.0"
@@ -5200,14 +5510,25 @@ version = "0.2.17"
5200 source = "registry+https://github.com/rust-lang/crates.io-index"5510 source = "registry+https://github.com/rust-lang/crates.io-index"
5201 checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"5511 checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
5202 5512
5513+[[package]]
5514+name = "pkcs1"
5515+version = "0.7.5"
5516+source = "registry+https://github.com/rust-lang/crates.io-index"
5517+checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
5518+dependencies = [
5519+ "der 0.7.10",
5520+ "pkcs8 0.10.2",
5521+ "spki 0.7.3",
5522+]
5523+
5203 [[package]]5524 [[package]]
5204 name = "pkcs1"5525 name = "pkcs1"
5205 version = "0.8.0-rc.4"5526 version = "0.8.0-rc.4"
5206 source = "registry+https://github.com/rust-lang/crates.io-index"5527 source = "registry+https://github.com/rust-lang/crates.io-index"
5207 checksum = "986d2e952779af96ea048f160fd9194e1751b4faea78bcf3ceb456efe008088e"5528 checksum = "986d2e952779af96ea048f160fd9194e1751b4faea78bcf3ceb456efe008088e"
5208 dependencies = [5529 dependencies = [
5209- "der",5530+ "der 0.8.2",
5210- "spki",5531+ "spki 0.8.1",
5211 ]5532 ]
5212 5533
5213 [[package]]5534 [[package]]
@@ -5219,12 +5540,22 @@ dependencies = [
5219 "aes 0.9.3",5540 "aes 0.9.3",
5220 "aes-gcm 0.11.1",5541 "aes-gcm 0.11.1",
5221 "cbc",5542 "cbc",
5222- "der",5543+ "der 0.8.2",
5223 "pbkdf2",5544 "pbkdf2",
5224 "rand_core 0.10.1",5545 "rand_core 0.10.1",
5225 "scrypt",5546 "scrypt",
5226 "sha2 0.11.1",5547 "sha2 0.11.1",
5227- "spki",5548+ "spki 0.8.1",
5549+]
5550+
5551+[[package]]
5552+name = "pkcs8"
5553+version = "0.10.2"
5554+source = "registry+https://github.com/rust-lang/crates.io-index"
5555+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
5556+dependencies = [
5557+ "der 0.7.10",
5558+ "spki 0.7.3",
5228 ]5559 ]
5229 5560
5230 [[package]]5561 [[package]]
@@ -5233,10 +5564,10 @@ version = "0.11.0"
5233 source = "registry+https://github.com/rust-lang/crates.io-index"5564 source = "registry+https://github.com/rust-lang/crates.io-index"
5234 checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"5565 checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
5235 dependencies = [5566 dependencies = [
5236- "der",5567+ "der 0.8.2",
5237 "pkcs5",5568 "pkcs5",
5238 "rand_core 0.10.1",5569 "rand_core 0.10.1",
5239- "spki",5570+ "spki 0.8.1",
5240 ]5571 ]
5241 5572
5242 [[package]]5573 [[package]]
@@ -5403,21 +5734,30 @@ version = "0.14.0"
5403 source = "registry+https://github.com/rust-lang/crates.io-index"5734 source = "registry+https://github.com/rust-lang/crates.io-index"
5404 checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4"5735 checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4"
5405 dependencies = [5736 dependencies = [
5406- "crypto-bigint",5737+ "crypto-bigint 0.7.5",
5407 "crypto-common 0.2.2",5738 "crypto-common 0.2.2",
5408- "ff",5739+ "ff 0.14.0",
5409 "rand_core 0.10.1",5740 "rand_core 0.10.1",
5410 "subtle",5741 "subtle",
5411 "zeroize",5742 "zeroize",
5412 ]5743 ]
5413 5744
5745+[[package]]
5746+name = "primeorder"
5747+version = "0.13.6"
5748+source = "registry+https://github.com/rust-lang/crates.io-index"
5749+checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
5750+dependencies = [
5751+ "elliptic-curve 0.13.8",
5752+]
5753+
5414 [[package]]5754 [[package]]
5415 name = "primeorder"5755 name = "primeorder"
5416 version = "0.14.0"5756 version = "0.14.0"
5417 source = "registry+https://github.com/rust-lang/crates.io-index"5757 source = "registry+https://github.com/rust-lang/crates.io-index"
5418 checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06"5758 checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06"
5419 dependencies = [5759 dependencies = [
5420- "elliptic-curve",5760+ "elliptic-curve 0.14.1",
5421 "once_cell",5761 "once_cell",
5422 "primefield",5762 "primefield",
5423 "serdect",5763 "serdect",
@@ -5893,13 +6233,23 @@ dependencies = [
5893 "web-sys",6233 "web-sys",
5894 ]6234 ]
5895 6235
6236+[[package]]
6237+name = "rfc6979"
6238+version = "0.4.0"
6239+source = "registry+https://github.com/rust-lang/crates.io-index"
6240+checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
6241+dependencies = [
6242+ "hmac 0.12.1",
6243+ "subtle",
6244+]
6245+
5896 [[package]]6246 [[package]]
5897 name = "rfc6979"6247 name = "rfc6979"
5898 version = "0.6.0"6248 version = "0.6.0"
5899 source = "registry+https://github.com/rust-lang/crates.io-index"6249 source = "registry+https://github.com/rust-lang/crates.io-index"
5900 checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b"6250 checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b"
5901 dependencies = [6251 dependencies = [
5902- "crypto-bigint",6252+ "crypto-bigint 0.7.5",
5903 "hmac 0.13.0",6253 "hmac 0.13.0",
5904 ]6254 ]
5905 6255
@@ -5938,22 +6288,43 @@ dependencies = [
5938 "windows-sys 0.61.2",6288 "windows-sys 0.61.2",
5939 ]6289 ]
5940 6290
6291+[[package]]
6292+name = "rsa"
6293+version = "0.9.10"
6294+source = "registry+https://github.com/rust-lang/crates.io-index"
6295+checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
6296+dependencies = [
6297+ "const-oid 0.9.6",
6298+ "digest 0.10.7",
6299+ "num-bigint-dig",
6300+ "num-integer",
6301+ "num-traits",
6302+ "pkcs1 0.7.5",
6303+ "pkcs8 0.10.2",
6304+ "rand_core 0.6.4",
6305+ "sha2 0.10.9",
6306+ "signature 2.2.0",
6307+ "spki 0.7.3",
6308+ "subtle",
6309+ "zeroize",
6310+]
6311+
5941 [[package]]6312 [[package]]
5942 name = "rsa"6313 name = "rsa"
5943 version = "0.10.0-rc.18"6314 version = "0.10.0-rc.18"
5944 source = "registry+https://github.com/rust-lang/crates.io-index"6315 source = "registry+https://github.com/rust-lang/crates.io-index"
5945 checksum = "30b2aa4ba0d89f73d1e332df05be0eeab8840351c36ca5654341dfdb57bb3caf"6316 checksum = "30b2aa4ba0d89f73d1e332df05be0eeab8840351c36ca5654341dfdb57bb3caf"
5946 dependencies = [6317 dependencies = [
5947- "const-oid",6318+ "const-oid 0.10.2",
5948- "crypto-bigint",6319+ "crypto-bigint 0.7.5",
5949 "crypto-primes",6320 "crypto-primes",
5950 "digest 0.11.3",6321 "digest 0.11.3",
5951- "pkcs1",6322+ "pkcs1 0.8.0-rc.4",
5952- "pkcs8",6323+ "pkcs8 0.11.0",
5953 "rand_core 0.10.1",6324 "rand_core 0.10.1",
5954 "sha2 0.11.1",6325 "sha2 0.11.1",
5955- "signature",6326+ "signature 3.0.0",
5956- "spki",6327+ "spki 0.8.1",
5957 "zeroize",6328 "zeroize",
5958 ]6329 ]
5959 6330
@@ -5981,16 +6352,16 @@ dependencies = [
5981 "bytes",6352 "bytes",
5982 "cbc",6353 "cbc",
5983 "cipher 0.5.2",6354 "cipher 0.5.2",
5984- "crypto-bigint",6355+ "crypto-bigint 0.7.5",
5985 "ctr 0.10.1",6356 "ctr 0.10.1",
5986 "curve25519-dalek",6357 "curve25519-dalek",
5987 "data-encoding",6358 "data-encoding",
5988 "delegate",6359 "delegate",
5989- "der",6360+ "der 0.8.2",
5990 "digest 0.11.3",6361 "digest 0.11.3",
5991- "ecdsa",6362+ "ecdsa 0.17.0",
5992 "ed25519-dalek",6363 "ed25519-dalek",
5993- "elliptic-curve",6364+ "elliptic-curve 0.14.1",
5994 "enum_dispatch",6365 "enum_dispatch",
5995 "flate2",6366 "flate2",
5996 "futures",6367 "futures",
@@ -6006,28 +6377,28 @@ dependencies = [
6006 "ml-kem",6377 "ml-kem",
6007 "module-lattice",6378 "module-lattice",
6008 "num-bigint 0.5.1",6379 "num-bigint 0.5.1",
6009- "p256",6380+ "p256 0.14.0",
6010- "p384",6381+ "p384 0.14.0",
6011 "p521",6382 "p521",
6012 "pageant",6383 "pageant",
6013 "pbkdf2",6384 "pbkdf2",
6014- "pkcs1",6385+ "pkcs1 0.8.0-rc.4",
6015 "pkcs5",6386 "pkcs5",
6016- "pkcs8",6387+ "pkcs8 0.11.0",
6017 "polyval 0.7.3",6388 "polyval 0.7.3",
6018 "rand 0.10.3",6389 "rand 0.10.3",
6019 "rand_core 0.10.1",6390 "rand_core 0.10.1",
6020- "rsa",6391+ "rsa 0.10.0-rc.18",
6021 "russh-cryptovec",6392 "russh-cryptovec",
6022 "russh-util",6393 "russh-util",
6023 "salsa20",6394 "salsa20",
6024 "scrypt",6395 "scrypt",
6025- "sec1",6396+ "sec1 0.8.1",
6026 "sha1 0.11.0",6397 "sha1 0.11.0",
6027 "sha2 0.11.1",6398 "sha2 0.11.1",
6028 "sha3 0.12.0",6399 "sha3 0.12.0",
6029- "signature",6400+ "signature 3.0.0",
6030- "spki",6401+ "spki 0.8.1",
6031 "ssh-encoding",6402 "ssh-encoding",
6032 "ssh-key",6403 "ssh-key",
6033 "subtle",6404 "subtle",
@@ -6315,15 +6686,29 @@ dependencies = [
6315 "sha2 0.11.1",6686 "sha2 0.11.1",
6316 ]6687 ]
6317 6688
6689+[[package]]
6690+name = "sec1"
6691+version = "0.7.3"
6692+source = "registry+https://github.com/rust-lang/crates.io-index"
6693+checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
6694+dependencies = [
6695+ "base16ct 0.2.0",
6696+ "der 0.7.10",
6697+ "generic-array 0.14.7",
6698+ "pkcs8 0.10.2",
6699+ "subtle",
6700+ "zeroize",
6701+]
6702+
6318 [[package]]6703 [[package]]
6319 name = "sec1"6704 name = "sec1"
6320 version = "0.8.1"6705 version = "0.8.1"
6321 source = "registry+https://github.com/rust-lang/crates.io-index"6706 source = "registry+https://github.com/rust-lang/crates.io-index"
6322 checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"6707 checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"
6323 dependencies = [6708 dependencies = [
6324- "base16ct",6709+ "base16ct 1.0.0",
6325 "ctutils",6710 "ctutils",
6326- "der",6711+ "der 0.8.2",
6327 "hybrid-array",6712 "hybrid-array",
6328 "subtle",6713 "subtle",
6329 "zeroize",6714 "zeroize",
@@ -6499,7 +6884,7 @@ version = "0.4.3"
6499 source = "registry+https://github.com/rust-lang/crates.io-index"6884 source = "registry+https://github.com/rust-lang/crates.io-index"
6500 checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e"6885 checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e"
6501 dependencies = [6886 dependencies = [
6502- "base16ct",6887+ "base16ct 1.0.0",
6503 "serde",6888 "serde",
6504 ]6889 ]
6505 6890
@@ -6589,6 +6974,17 @@ dependencies = [
6589 "sponge-cursor",6974 "sponge-cursor",
6590 ]6975 ]
6591 6976
6977+[[package]]
6978+name = "shake"
6979+version = "0.1.0"
6980+source = "registry+https://github.com/rust-lang/crates.io-index"
6981+checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"
6982+dependencies = [
6983+ "digest 0.11.3",
6984+ "keccak",
6985+ "sponge-cursor",
6986+]
6987+
6592 [[package]]6988 [[package]]
6593 name = "sharded-slab"6989 name = "sharded-slab"
6594 version = "0.1.7"6990 version = "0.1.7"
@@ -6656,6 +7052,16 @@ dependencies = [
6656 "libc",7052 "libc",
6657 ]7053 ]
6658 7054
7055+[[package]]
7056+name = "signature"
7057+version = "2.2.0"
7058+source = "registry+https://github.com/rust-lang/crates.io-index"
7059+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
7060+dependencies = [
7061+ "digest 0.10.7",
7062+ "rand_core 0.6.4",
7063+]
7064+
6659 [[package]]7065 [[package]]
6660 name = "signature"7066 name = "signature"
6661 version = "3.0.0"7067 version = "3.0.0"
@@ -6761,6 +7167,16 @@ version = "0.10.1"
6761 source = "registry+https://github.com/rust-lang/crates.io-index"7167 source = "registry+https://github.com/rust-lang/crates.io-index"
6762 checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3"7168 checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3"
6763 7169
7170+[[package]]
7171+name = "spki"
7172+version = "0.7.3"
7173+source = "registry+https://github.com/rust-lang/crates.io-index"
7174+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
7175+dependencies = [
7176+ "base64ct",
7177+ "der 0.7.10",
7178+]
7179+
6764 [[package]]7180 [[package]]
6765 name = "spki"7181 name = "spki"
6766 version = "0.8.1"7182 version = "0.8.1"
@@ -6768,7 +7184,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
6768 checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"7184 checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
6769 dependencies = [7185 dependencies = [
6770 "base64ct",7186 "base64ct",
6771- "der",7187+ "der 0.8.2",
6772 ]7188 ]
6773 7189
6774 [[package]]7190 [[package]]
@@ -6803,10 +7219,10 @@ checksum = "7b54d0ed0498daf3f78d82e00e28c8eec9d75a067c4cfbcc7a0f7d0f4077749e"
6803 dependencies = [7219 dependencies = [
6804 "base64ct",7220 "base64ct",
6805 "bytes",7221 "bytes",
6806- "crypto-bigint",7222+ "crypto-bigint 0.7.5",
6807 "ctutils",7223 "ctutils",
6808 "digest 0.11.3",7224 "digest 0.11.3",
6809- "pem-rfc7468",7225+ "pem-rfc7468 1.0.0",
6810 "zeroize",7226 "zeroize",
6811 ]7227 ]
6812 7228
@@ -6822,15 +7238,15 @@ dependencies = [
6822 "ed25519-dalek",7238 "ed25519-dalek",
6823 "hex",7239 "hex",
6824 "hmac 0.13.0",7240 "hmac 0.13.0",
6825- "p256",7241+ "p256 0.14.0",
6826- "p384",7242+ "p384 0.14.0",
6827 "p521",7243 "p521",
6828 "rand_core 0.10.1",7244 "rand_core 0.10.1",
6829- "rsa",7245+ "rsa 0.10.0-rc.18",
6830- "sec1",7246+ "sec1 0.8.1",
6831 "sha1 0.11.0",7247 "sha1 0.11.0",
6832 "sha2 0.11.1",7248 "sha2 0.11.1",
6833- "signature",7249+ "signature 3.0.0",
6834 "ssh-cipher",7250 "ssh-cipher",
6835 "ssh-encoding",7251 "ssh-encoding",
6836 "zeroize",7252 "zeroize",
@@ -6951,6 +7367,24 @@ version = "2.6.1"
6951 source = "registry+https://github.com/rust-lang/crates.io-index"7367 source = "registry+https://github.com/rust-lang/crates.io-index"
6952 checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"7368 checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
6953 7369
7370+[[package]]
7371+name = "superboring"
7372+version = "0.1.17"
7373+source = "registry+https://github.com/rust-lang/crates.io-index"
7374+checksum = "19706eb9c165c3c27117e8795678015277188647b03db4f7cbf9df98048e09a6"
7375+dependencies = [
7376+ "aes-gcm 0.11.1",
7377+ "aes-keywrap",
7378+ "getrandom 0.2.17",
7379+ "getrandom 0.4.3",
7380+ "hmac-sha1-compact",
7381+ "hmac-sha256",
7382+ "hmac-sha512",
7383+ "ml-dsa",
7384+ "rand 0.8.8",
7385+ "rsa 0.9.10",
7386+]
7387+
6954 [[package]]7388 [[package]]
6955 name = "symlink"7389 name = "symlink"
6956 version = "0.1.0"7390 version = "0.1.0"
@@ -8393,6 +8827,15 @@ dependencies = [
8393 "wit-bindgen",8827 "wit-bindgen",
8394 ]8828 ]
8395 8829
8830+[[package]]
8831+name = "wasix"
8832+version = "0.13.2"
8833+source = "registry+https://github.com/rust-lang/crates.io-index"
8834+checksum = "ae86f02046da16a333a9129d31451423e1657737ecdafed4193838a5f54c5cfe"
8835+dependencies = [
8836+ "wasi",
8837+]
8838+
8396 [[package]]8839 [[package]]
8397 name = "wasm-bindgen"8840 name = "wasm-bindgen"
8398 version = "0.2.129"8841 version = "0.2.129"
@@ -8462,6 +8905,23 @@ dependencies = [
8462 "web-sys",8905 "web-sys",
8463 ]8906 ]
8464 8907
8908+[[package]]
8909+name = "web-push-native"
8910+version = "0.5.0"
8911+source = "registry+https://github.com/rust-lang/crates.io-index"
8912+checksum = "7628c93e39aeee4c0bca50ae333052b4f174c653e8fca1d0a8e34f9bc4879c0c"
8913+dependencies = [
8914+ "aes-gcm 0.10.3",
8915+ "base64ct",
8916+ "ece-native",
8917+ "hkdf 0.13.0",
8918+ "http",
8919+ "jwt-simple",
8920+ "p256 0.13.2",
8921+ "serde",
8922+ "sha2 0.11.1",
8923+]
8924+
8465 [[package]]8925 [[package]]
8466 name = "web-sys"8926 name = "web-sys"
8467 version = "0.3.106"8927 version = "0.3.106"
@@ -8896,8 +9356,8 @@ version = "0.14.1"
8896 source = "registry+https://github.com/rust-lang/crates.io-index"9356 source = "registry+https://github.com/rust-lang/crates.io-index"
8897 checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa"9357 checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa"
8898 dependencies = [9358 dependencies = [
8899- "ff",9359+ "ff 0.14.0",
8900- "group",9360+ "group 0.14.0",
8901 "hybrid-array",9361 "hybrid-array",
8902 "primefield",9362 "primefield",
8903 ]9363 ]
Cargo.tomlmodified+2 -0
@@ -65,6 +65,8 @@ base64 = "0.23.1"
65 getrandom = "0.4.3"65 getrandom = "0.4.3"
66 rpassword = "7.5.4"66 rpassword = "7.5.4"
67 chacha20poly1305 = "0.11.0"67 chacha20poly1305 = "0.11.0"
68+# Web Push (forge-web): RFC 8291 encryption and RFC 8292 VAPID, RustCrypto based, pure Rust
69+web-push-native = "0.5.0"
68 70
69 # storage71 # storage
70 turso = "0.8.3"72 turso = "0.8.3"
crates/forge-core/migrations/0061_web_push.sqladded+24 -0
@@ -0,0 +1,24 @@
1+-- Web Push. `web_push_keys` holds the one VAPID key pair of the instance: the public key as
2+-- base64url (the browser's applicationServerKey) and the private key sealed with the instance key.
3+-- `push_subscriptions` has one row per browser or installed PWA a user enabled push on. The
4+-- endpoint is the push service URL, unique across accounts, so a shared browser that signs in as
5+-- someone else moves the row to that account. Applied by store/migrate.rs.
6+
7+CREATE TABLE web_push_keys (
8+ id INTEGER PRIMARY KEY CHECK (id = 1),
9+ public_key TEXT NOT NULL,
10+ private_key TEXT NOT NULL,
11+ created_at TEXT NOT NULL
12+);
13+
14+CREATE TABLE push_subscriptions (
15+ id TEXT PRIMARY KEY,
16+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
17+ endpoint TEXT NOT NULL UNIQUE,
18+ p256dh TEXT NOT NULL,
19+ auth TEXT NOT NULL,
20+ agent_label TEXT NOT NULL,
21+ created_at TEXT NOT NULL,
22+ last_success_at TEXT NULL
23+);
24+CREATE INDEX idx_push_subscriptions_user ON push_subscriptions(user_id);
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -100,6 +100,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
100 (58, include_str!("../../migrations/0058_passkeys.sql")),100 (58, include_str!("../../migrations/0058_passkeys.sql")),
101 (59, include_str!("../../migrations/0059_admin_alerts.sql")),101 (59, include_str!("../../migrations/0059_admin_alerts.sql")),
102 (60, include_str!("../../migrations/0060_runner_memory.sql")),102 (60, include_str!("../../migrations/0060_runner_memory.sql")),
103+ (61, include_str!("../../migrations/0061_web_push.sql")),
103 ];104 ];
104 105
105 /// The highest migration version this binary knows about.106 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+1 -0
@@ -44,6 +44,7 @@ pub mod suspension;
44 pub mod transfers;44 pub mod transfers;
45 pub mod ui_prefs;45 pub mod ui_prefs;
46 pub mod user_delete;46 pub mod user_delete;
47+pub mod web_push;
47 pub mod webhooks;48 pub mod webhooks;
48 pub mod wiki;49 pub mod wiki;
49 50
crates/forge-core/src/store/web_push.rsadded+209 -0
@@ -0,0 +1,209 @@
1+//! Web Push (migration 0061): the instance's VAPID key pair and each user's push subscriptions.
2+//! The store keeps the private key sealed; the web crate seals and opens it with the instance key.
3+
4+use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
5+use crate::error::{Error, Result};
6+use crate::time::now_stamp;
7+
8+/// Most devices one account may hold. A subscription past this is refused, so a client cannot
9+/// grow the table without bound.
10+pub const MAX_DEVICES: usize = 20;
11+
12+/// One browser or installed app that receives pushes for `user_id`.
13+#[derive(Debug, Clone, PartialEq, Eq)]
14+pub struct PushSubscription {
15+ pub id: String,
16+ pub user_id: String,
17+ /// The push service URL. Unique across accounts.
18+ pub endpoint: String,
19+ /// The browser's public key, base64url.
20+ pub p256dh: String,
21+ /// The browser's auth secret, base64url.
22+ pub auth: String,
23+ /// A short device label such as "Chrome on Android", derived from the User-Agent.
24+ pub agent_label: String,
25+ pub created_at: String,
26+ pub last_success_at: Option<String>,
27+}
28+
29+const COLS: &str = "id, user_id, endpoint, p256dh, auth, agent_label, created_at, last_success_at";
30+
31+fn map_row(row: &turso::Row) -> Result<PushSubscription> {
32+ Ok(PushSubscription {
33+ id: col_text(row, 0)?,
34+ user_id: col_text(row, 1)?,
35+ endpoint: col_text(row, 2)?,
36+ p256dh: col_text(row, 3)?,
37+ auth: col_text(row, 4)?,
38+ agent_label: col_text(row, 5)?,
39+ created_at: col_text(row, 6)?,
40+ last_success_at: col_opt_text(row, 7)?,
41+ })
42+}
43+
44+impl Store {
45+ /// The instance's VAPID key pair as `(public key, sealed private key)`, or `None` before the
46+ /// first one is generated.
47+ pub async fn web_push_keys(&self) -> Result<Option<(String, String)>> {
48+ let conn = self.read_conn().await;
49+ fetch_opt(
50+ &conn,
51+ "SELECT public_key, private_key FROM web_push_keys WHERE id = 1",
52+ (),
53+ |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
54+ )
55+ .await
56+ }
57+
58+ /// Stores the VAPID key pair unless one is already stored, and returns the stored pair. Two
59+ /// requests that race to create the first key both end up with the same one.
60+ pub async fn save_web_push_keys(
61+ &self,
62+ public_key: &str,
63+ sealed_private: &str,
64+ ) -> Result<(String, String)> {
65+ let conn = self.inner.conn.lock().await;
66+ conn.execute(
67+ "INSERT INTO web_push_keys (id, public_key, private_key, created_at) \
68+ VALUES (1, ?1, ?2, ?3) ON CONFLICT (id) DO NOTHING",
69+ (
70+ public_key.to_string(),
71+ sealed_private.to_string(),
72+ now_stamp(),
73+ ),
74+ )
75+ .await
76+ .map_err(db_err)?;
77+ fetch_opt(
78+ &conn,
79+ "SELECT public_key, private_key FROM web_push_keys WHERE id = 1",
80+ (),
81+ |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
82+ )
83+ .await?
84+ .ok_or_else(|| Error::Database("the VAPID key was not stored".into()))
85+ }
86+
87+ /// The devices of `user_id`, oldest first.
88+ pub async fn push_subscriptions(&self, user_id: &str) -> Result<Vec<PushSubscription>> {
89+ let conn = self.read_conn().await;
90+ fetch_all(
91+ &conn,
92+ &format!(
93+ "SELECT {COLS} FROM push_subscriptions WHERE user_id = ?1 ORDER BY created_at, id"
94+ ),
95+ (user_id.to_string(),),
96+ map_row,
97+ )
98+ .await
99+ }
100+
101+ /// Adds a device for `user_id`, or refreshes the keys of the device with this endpoint. The
102+ /// endpoint moves to `user_id` when another account held it. Refused past `MAX_DEVICES` for
103+ /// a new endpoint.
104+ pub async fn save_push_subscription(
105+ &self,
106+ user_id: &str,
107+ endpoint: &str,
108+ p256dh: &str,
109+ auth: &str,
110+ agent_label: &str,
111+ ) -> Result<PushSubscription> {
112+ let conn = self.inner.conn.lock().await;
113+ let held = fetch_opt(
114+ &conn,
115+ "SELECT COUNT(*) FROM push_subscriptions WHERE user_id = ?1 AND endpoint != ?2",
116+ (user_id.to_string(), endpoint.to_string()),
117+ |row| crate::store::col_int(row, 0),
118+ )
119+ .await?
120+ .unwrap_or(0);
121+ if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_DEVICES {
122+ return Err(Error::Invalid(format!(
123+ "an account can enable push on at most {MAX_DEVICES} devices"
124+ )));
125+ }
126+ conn.execute(
127+ "INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth, agent_label, created_at) \
128+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \
129+ ON CONFLICT (endpoint) DO UPDATE SET user_id = excluded.user_id, \
130+ p256dh = excluded.p256dh, auth = excluded.auth, \
131+ agent_label = excluded.agent_label, created_at = excluded.created_at",
132+ (
133+ new_id(),
134+ user_id.to_string(),
135+ endpoint.to_string(),
136+ p256dh.to_string(),
137+ auth.to_string(),
138+ agent_label.to_string(),
139+ now_stamp(),
140+ ),
141+ )
142+ .await
143+ .map_err(db_err)?;
144+ fetch_opt(
145+ &conn,
146+ &format!("SELECT {COLS} FROM push_subscriptions WHERE endpoint = ?1"),
147+ (endpoint.to_string(),),
148+ map_row,
149+ )
150+ .await?
151+ .ok_or_else(|| Error::Database("the push subscription was not stored".into()))
152+ }
153+
154+ /// Removes the device with this id when it belongs to `user_id`.
155+ pub async fn delete_push_subscription(&self, user_id: &str, id: &str) -> Result<bool> {
156+ let conn = self.inner.conn.lock().await;
157+ let n = conn
158+ .execute(
159+ "DELETE FROM push_subscriptions WHERE id = ?1 AND user_id = ?2",
160+ (id.to_string(), user_id.to_string()),
161+ )
162+ .await
163+ .map_err(db_err)?;
164+ Ok(n > 0)
165+ }
166+
167+ /// Removes the device with this endpoint when it belongs to `user_id`.
168+ pub async fn delete_push_subscription_by_endpoint(
169+ &self,
170+ user_id: &str,
171+ endpoint: &str,
172+ ) -> Result<bool> {
173+ let conn = self.inner.conn.lock().await;
174+ let n = conn
175+ .execute(
176+ "DELETE FROM push_subscriptions WHERE endpoint = ?1 AND user_id = ?2",
177+ (endpoint.to_string(), user_id.to_string()),
178+ )
179+ .await
180+ .map_err(db_err)?;
181+ Ok(n > 0)
182+ }
183+
184+ /// Removes the device with this endpoint whoever owns it. Used when the push service says
185+ /// the subscription is gone (404 or 410).
186+ pub async fn delete_push_endpoint(&self, endpoint: &str) -> Result<bool> {
187+ let conn = self.inner.conn.lock().await;
188+ let n = conn
189+ .execute(
190+ "DELETE FROM push_subscriptions WHERE endpoint = ?1",
191+ (endpoint.to_string(),),
192+ )
193+ .await
194+ .map_err(db_err)?;
195+ Ok(n > 0)
196+ }
197+
198+ /// Records a delivery the push service accepted.
199+ pub async fn mark_push_delivered(&self, id: &str) -> Result<()> {
200+ let conn = self.inner.conn.lock().await;
201+ conn.execute(
202+ "UPDATE push_subscriptions SET last_success_at = ?2 WHERE id = ?1",
203+ (id.to_string(), now_stamp()),
204+ )
205+ .await
206+ .map_err(db_err)?;
207+ Ok(())
208+ }
209+}
crates/forge-web/Cargo.tomlmodified+1 -0
@@ -58,6 +58,7 @@ tar.workspace = true
58 flate2.workspace = true58 flate2.workspace = true
59 webauthn-rs = { version = "0.5.5", features = ["danger-allow-state-serialisation", "conditional-ui"] }59 webauthn-rs = { version = "0.5.5", features = ["danger-allow-state-serialisation", "conditional-ui"] }
60 webauthn-rs-proto = "0.5.5"60 webauthn-rs-proto = "0.5.5"
61+web-push-native.workspace = true
61 62
62 [build-dependencies]63 [build-dependencies]
63 grass.workspace = true64 grass.workspace = true
crates/forge-web/assets/icons/apple-touch-icon.pngadded+0 -0

Binary file changed

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

Binary file changed

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

Binary file changed

crates/forge-web/assets/nav.jsmodified+139 -0
@@ -169,6 +169,7 @@
169 restoreJobs(jobs);169 restoreJobs(jobs);
170 syncUnread();170 syncUnread();
171 syncLive();171 syncLive();
172+ syncPush();
172 syncTick();173 syncTick();
173 }174 }
174 175
@@ -1013,6 +1014,143 @@
1013 area.setSelectionRange(start + block.length, start + block.length);1014 area.setSelectionRange(start + block.length, start + block.length);
1014 });1015 });
1015 1016
1017+ // Web Push on this device (the notification settings card, [data-push]). The server renders every
1018+ // state message with a data-push-state attribute, hidden; this picks which ones show from the
1019+ // browser's own state: secure context, support, iOS install, permission and the subscription. The
1020+ // service worker (/sw.js, served at the origin root) is registered only when the user turns push on.
1021+ function pushSet(el, on) {
1022+ el.hidden = !on;
1023+ el.style.display = on ? '' : 'none';
1024+ }
1025+
1026+ function pushCard() { return document.querySelector('[data-push]'); }
1027+
1028+ function pushShow(card, name, on) {
1029+ card.querySelectorAll('[data-push-state="' + name + '"]').forEach(function (el) { pushSet(el, on); });
1030+ }
1031+
1032+ function pushActions(card, enable, disable) {
1033+ card.querySelectorAll('[data-push-action="enable"]').forEach(function (el) { pushSet(el, enable); });
1034+ card.querySelectorAll('[data-push-action="disable"]').forEach(function (el) { pushSet(el, disable); });
1035+ }
1036+
1037+ function pushBase64ToBytes(text) {
1038+ var pad = '==='.slice((text.length + 3) % 4);
1039+ var raw = atob((text + pad).replace(/-/g, '+').replace(/_/g, '/'));
1040+ var out = new Uint8Array(raw.length);
1041+ for (var i = 0; i < raw.length; i++) { out[i] = raw.charCodeAt(i); }
1042+ return out;
1043+ }
1044+
1045+ function pushBytesToBase64(buffer) {
1046+ var bytes = new Uint8Array(buffer);
1047+ var text = '';
1048+ for (var i = 0; i < bytes.length; i++) { text += String.fromCharCode(bytes[i]); }
1049+ return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
1050+ }
1051+
1052+ function pushCsrf(card) {
1053+ var input = card.querySelector('input[name="csrf"]');
1054+ return input ? input.value : '';
1055+ }
1056+
1057+ function pushIos() {
1058+ var standalone = window.navigator.standalone === true || (window.matchMedia && matchMedia('(display-mode: standalone)').matches);
1059+ return /iPhone|iPad|iPod/.test(navigator.userAgent) && !standalone;
1060+ }
1061+
1062+ function syncPush() {
1063+ var card = pushCard();
1064+ if (!card) { return; }
1065+ ['unsupported', 'https', 'ios', 'denied', 'error', 'on', 'off'].forEach(function (name) { pushShow(card, name, false); });
1066+ pushActions(card, false, false);
1067+ if (!window.isSecureContext) { pushShow(card, 'https', true); return; }
1068+ if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) {
1069+ pushShow(card, 'unsupported', true);
1070+ return;
1071+ }
1072+ if (pushIos()) { pushShow(card, 'ios', true); return; }
1073+ if (Notification.permission === 'denied') { pushShow(card, 'denied', true); return; }
1074+ navigator.serviceWorker.getRegistration('/sw.js').then(function (reg) {
1075+ return reg ? reg.pushManager.getSubscription() : null;
1076+ }).then(function (sub) {
1077+ if (!pushCard() || pushCard() !== card) { return; }
1078+ pushShow(card, sub ? 'on' : 'off', true);
1079+ pushActions(card, !sub, !!sub);
1080+ }).catch(function () {
1081+ pushShow(card, 'error', true);
1082+ });
1083+ }
1084+
1085+ // Turns push on for this browser: permission, service worker, subscription, then the server
1086+ // records the device. The device list refreshes through the page's event stream.
1087+ async function pushEnable(card) {
1088+ try {
1089+ if ((await Notification.requestPermission()) !== 'granted') { return syncPush(); }
1090+ var reg = await navigator.serviceWorker.register('/sw.js');
1091+ await navigator.serviceWorker.ready;
1092+ var keyRes = await fetch('/push/vapid-key', { credentials: 'same-origin', headers: { accept: 'application/json' } });
1093+ if (!keyRes.ok) { throw new Error('vapid key ' + keyRes.status); }
1094+ var key = (await keyRes.json()).public_key;
1095+ // A subscription made with another key cannot be reused: drop it on the server and in the browser.
1096+ var old = await reg.pushManager.getSubscription();
1097+ if (old) { await pushPost(card, '/push/unsubscribe', { endpoint: old.endpoint }); await old.unsubscribe(); }
1098+ var sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: pushBase64ToBytes(key) });
1099+ var saved = await pushPost(card, '/push/subscribe', {
1100+ endpoint: sub.endpoint,
1101+ p256dh: pushBytesToBase64(sub.getKey('p256dh')),
1102+ auth: pushBytesToBase64(sub.getKey('auth'))
1103+ });
1104+ if (!saved.ok) { throw new Error('subscribe ' + saved.status); }
1105+ syncPush();
1106+ } catch (e) {
1107+ syncPush();
1108+ var error = card.querySelector('[data-push-state="error"]');
1109+ if (error) { pushSet(error, true); }
1110+ }
1111+ }
1112+
1113+ async function pushDisable(card) {
1114+ try {
1115+ var reg = await navigator.serviceWorker.getRegistration('/sw.js');
1116+ var sub = reg ? await reg.pushManager.getSubscription() : null;
1117+ if (sub) {
1118+ await pushPost(card, '/push/unsubscribe', { endpoint: sub.endpoint });
1119+ await sub.unsubscribe();
1120+ }
1121+ } catch (e) {
1122+ // Nothing to undo in the browser; the page below shows the state as it is now.
1123+ }
1124+ syncPush();
1125+ }
1126+
1127+ function pushPost(card, url, fields) {
1128+ var body = new URLSearchParams();
1129+ body.set('csrf', pushCsrf(card));
1130+ Object.keys(fields).forEach(function (k) { body.set(k, fields[k]); });
1131+ return fetch(url, { method: 'POST', body: body, credentials: 'same-origin' });
1132+ }
1133+
1134+ document.addEventListener('click', function (e) {
1135+ var button = e.target && e.target.closest ? e.target.closest('[data-push-action]') : null;
1136+ if (!button) { return; }
1137+ var card = pushCard();
1138+ if (!card || !card.contains(button)) { return; }
1139+ e.preventDefault();
1140+ if (button.getAttribute('data-push-action') === 'enable') { pushEnable(card); }
1141+ else { pushDisable(card); }
1142+ });
1143+
1144+ // The service worker asks an open tab to show a notification's link in place.
1145+ if ('serviceWorker' in navigator) {
1146+ navigator.serviceWorker.addEventListener('message', function (e) {
1147+ var data = e.data;
1148+ if (data && data.type === 'forge-navigate' && typeof data.url === 'string' && data.url.charAt(0) === '/' && data.url.charAt(1) !== '/') {
1149+ go(data.url);
1150+ }
1151+ });
1152+ }
1153+
1016 // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of1154 // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of
1017 // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in1155 // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in
1018 // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose1156 // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose
@@ -1178,6 +1316,7 @@
1178 syncLog();1316 syncLog();
1179 followTail();1317 followTail();
1180 syncLive();1318 syncLive();
1319+ syncPush();
1181 syncTick();1320 syncTick();
1182 1321
1183 window.__forgeQuery = function (href) {1322 window.__forgeQuery = function (href) {
crates/forge-web/assets/sw.jsadded+49 -0
@@ -0,0 +1,49 @@
1+// Forge service worker. Served at /sw.js, so its scope is the whole origin. It shows Web Push
2+// notifications while no tab is open and opens the link of a clicked one. No inline code, no
3+// network caching: the page is always fetched fresh.
4+
5+self.addEventListener('install', function () {
6+ self.skipWaiting();
7+});
8+
9+self.addEventListener('activate', function (event) {
10+ event.waitUntil(self.clients.claim());
11+});
12+
13+self.addEventListener('push', function (event) {
14+ var data = {};
15+ try {
16+ data = event.data ? event.data.json() : {};
17+ } catch (e) {
18+ data = {};
19+ }
20+ var title = typeof data.title === 'string' && data.title ? data.title : 'Forge';
21+ var options = {
22+ body: typeof data.body === 'string' ? data.body : '',
23+ tag: typeof data.tag === 'string' ? data.tag : undefined,
24+ icon: '/assets/icons/icon-192.png',
25+ badge: '/assets/icons/icon-192.png',
26+ data: { url: typeof data.url === 'string' ? data.url : '/notifications' }
27+ };
28+ event.waitUntil(self.registration.showNotification(title, options));
29+});
30+
31+// Focuses an open Forge tab and asks it to soft-navigate to the link, or opens a new window.
32+self.addEventListener('notificationclick', function (event) {
33+ event.notification.close();
34+ var raw = event.notification.data && event.notification.data.url;
35+ var target = typeof raw === 'string' && raw.charAt(0) === '/' && raw.charAt(1) !== '/' ? raw : '/notifications';
36+ var url = new URL(target, self.location.origin).href;
37+ event.waitUntil((async function () {
38+ var windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
39+ for (var i = 0; i < windows.length; i++) {
40+ var client = windows[i];
41+ if (new URL(client.url).origin === self.location.origin) {
42+ await client.focus();
43+ client.postMessage({ type: 'forge-navigate', url: target });
44+ return;
45+ }
46+ }
47+ await self.clients.openWindow(url);
48+ })());
49+});
crates/forge-web/src/alerts.rsmodified+8 -0
@@ -125,6 +125,14 @@ async fn deliver(
125 continue;125 continue;
126 }126 }
127 publish_unread(state, &admin.id).await;127 publish_unread(state, &admin.id).await;
128+ crate::web_push::queue(
129+ state,
130+ &admin.id,
131+ crate::web_push::Alert::Admin {
132+ subject: subject.to_owned(),
133+ detail: detail.to_owned(),
134+ },
135+ );
128 if !live.alerts.email {136 if !live.alerts.email {
129 continue;137 continue;
130 }138 }
crates/forge-web/src/boot.rsmodified+1 -0
@@ -135,6 +135,7 @@ pub async fn serve(
135 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),135 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
136 ci_live: Arc::new(crate::ci::CiLive::default()),136 ci_live: Arc::new(crate::ci::CiLive::default()),
137 live: Arc::new(crate::live::LiveHub::default()),137 live: Arc::new(crate::live::LiveHub::default()),
138+ push_live: Arc::new(crate::web_push::PushLive::default()),
138 };139 };
139 if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await {140 if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await {
140 tracing::error!(error = %e, "building the SSH allowed-signers file failed");141 tracing::error!(error = %e, "building the SSH allowed-signers file failed");
crates/forge-web/src/i18n/mod.rsmodified+1 -0
@@ -32,6 +32,7 @@ pub mod misc;
32 pub mod orgs;32 pub mod orgs;
33 pub mod pulls;33 pub mod pulls;
34 pub mod pulls_review;34 pub mod pulls_review;
35+pub mod push;
35 pub mod releases_ci;36 pub mod releases_ci;
36 pub mod repo_admin;37 pub mod repo_admin;
37 38
crates/forge-web/src/i18n/push.rsadded+122 -0
@@ -0,0 +1,122 @@
1+//! Strings for Web Push: the device card in notification settings, the push notification text and
2+//! the test message. Shared strings (Notifications, Save) come from `super::Key`.
3+
4+use super::Lang;
5+
6+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7+pub enum K {
8+ // Settings card: this device.
9+ DeviceHeading,
10+ DeviceHelp,
11+ DeviceUnsupported,
12+ DeviceNeedsHttps,
13+ DeviceIosHint,
14+ DeviceDenied,
15+ DeviceOn,
16+ DeviceOff,
17+ DeviceError,
18+ TurnOn,
19+ TurnOff,
20+ SendTest,
21+ TestNoDevices,
22+ // Settings card: the devices list.
23+ DevicesHeading,
24+ DevicesEmpty,
25+ RemoveDevice,
26+ DeviceRemoved,
27+ NeverDelivered,
28+ // The notification the device shows.
29+ TestTitle,
30+ TestBody,
31+}
32+
33+/// The phrase for `key`.
34+pub fn t(lang: Lang, key: K) -> &'static str {
35+ use K::*;
36+ match (key, lang) {
37+ (DeviceHeading, Lang::En) => "Push notifications on this device",
38+ (DeviceHeading, Lang::Tr) => "Bu cihazda anlık bildirimler",
39+ (DeviceHelp, Lang::En) => {
40+ "Get a notification on this device even when Forge is closed. Each browser or installed app is a separate device."
41+ }
42+ (DeviceHelp, Lang::Tr) => {
43+ "Forge kapalıyken bile bu cihazda bildirim alın. Her tarayıcı veya yüklü uygulama ayrı bir cihazdır."
44+ }
45+ (DeviceUnsupported, Lang::En) => "This browser does not support push notifications.",
46+ (DeviceUnsupported, Lang::Tr) => "Bu tarayıcı anlık bildirimleri desteklemiyor.",
47+ (DeviceNeedsHttps, Lang::En) => "Push notifications need an HTTPS connection.",
48+ (DeviceNeedsHttps, Lang::Tr) => "Anlık bildirimler için HTTPS bağlantısı gerekir.",
49+ (DeviceIosHint, Lang::En) => {
50+ "On iPhone and iPad, add Forge to your Home Screen, open it from there, then turn push on."
51+ }
52+ (DeviceIosHint, Lang::Tr) => {
53+ "iPhone ve iPad'de önce Forge'u Ana Ekrana ekleyin, oradan açın, sonra anlık bildirimleri açın."
54+ }
55+ (DeviceDenied, Lang::En) => {
56+ "Notifications are blocked for this site. Allow them in the browser's site settings, then try again."
57+ }
58+ (DeviceDenied, Lang::Tr) => {
59+ "Bu site için bildirimler engellenmiş. Tarayıcının site ayarlarından izin verip yeniden deneyin."
60+ }
61+ (DeviceOn, Lang::En) => "Push is on for this device.",
62+ (DeviceOn, Lang::Tr) => "Bu cihazda anlık bildirimler açık.",
63+ (DeviceOff, Lang::En) => "Push is off for this device.",
64+ (DeviceOff, Lang::Tr) => "Bu cihazda anlık bildirimler kapalı.",
65+ (DeviceError, Lang::En) => "Push could not be turned on. Try again.",
66+ (DeviceError, Lang::Tr) => "Anlık bildirimler açılamadı. Yeniden deneyin.",
67+ (TurnOn, Lang::En) => "Turn on for this device",
68+ (TurnOn, Lang::Tr) => "Bu cihazda aç",
69+ (TurnOff, Lang::En) => "Turn off for this device",
70+ (TurnOff, Lang::Tr) => "Bu cihazda kapat",
71+ (SendTest, Lang::En) => "Send test notification",
72+ (SendTest, Lang::Tr) => "Test bildirimi gönder",
73+ (TestNoDevices, Lang::En) => "No device has push on yet. Turn it on first.",
74+ (TestNoDevices, Lang::Tr) => "Henüz anlık bildirimi açık bir cihaz yok. Önce bunu açın.",
75+ (DevicesHeading, Lang::En) => "Devices",
76+ (DevicesHeading, Lang::Tr) => "Cihazlar",
77+ (DevicesEmpty, Lang::En) => "No device has push on.",
78+ (DevicesEmpty, Lang::Tr) => "Anlık bildirimi açık cihaz yok.",
79+ (RemoveDevice, Lang::En) => "Remove",
80+ (RemoveDevice, Lang::Tr) => "Kaldır",
81+ (DeviceRemoved, Lang::En) => "Device removed.",
82+ (DeviceRemoved, Lang::Tr) => "Cihaz kaldırıldı.",
83+ (NeverDelivered, Lang::En) => "Nothing delivered yet",
84+ (NeverDelivered, Lang::Tr) => "Henüz teslim edilmedi",
85+ (TestTitle, Lang::En) => "Forge test notification",
86+ (TestTitle, Lang::Tr) => "Forge test bildirimi",
87+ (TestBody, Lang::En) => "Push notifications work on this device.",
88+ (TestBody, Lang::Tr) => "Anlık bildirimler bu cihazda çalışıyor.",
89+ }
90+}
91+
92+/// "Test sent to 2 devices." for the settings notice.
93+pub fn test_sent(lang: Lang, devices: usize) -> String {
94+ match lang {
95+ Lang::En => format!("Test sent to {devices} device(s)."),
96+ Lang::Tr => format!("Test {devices} cihaza gönderildi."),
97+ }
98+}
99+
100+/// "Added 2026-10-02" and the matching delivery line.
101+pub fn added_on(lang: Lang, date: &str) -> String {
102+ match lang {
103+ Lang::En => format!("Added {date}"),
104+ Lang::Tr => format!("Eklendi {date}"),
105+ }
106+}
107+
108+/// "Last delivered 2026-10-02".
109+pub fn last_delivered(lang: Lang, date: &str) -> String {
110+ match lang {
111+ Lang::En => format!("Last delivered {date}"),
112+ Lang::Tr => format!("Son teslim {date}"),
113+ }
114+}
115+
116+/// "3 new security alerts" for the push about advisories.
117+pub fn advisory_alerts(lang: Lang, count: u64) -> String {
118+ match lang {
119+ Lang::En => format!("{count} new security alerts"),
120+ Lang::Tr => format!("{count} yeni güvenlik uyarısı"),
121+ }
122+}
crates/forge-web/src/main.rsmodified+1 -0
@@ -55,6 +55,7 @@ mod test_support;
55 mod theme;55 mod theme;
56 mod throttle;56 mod throttle;
57 mod views;57 mod views;
58+mod web_push;
58 mod webhooks;59 mod webhooks;
59 60
60 use std::path::PathBuf;61 use std::path::PathBuf;
crates/forge-web/src/notify.rsmodified+82 -2
@@ -12,7 +12,7 @@ use forge_core::store::orgs::OrgMemberRole;
12 use forge_core::{Action, Issue, Repo, Result, User, authorize};12 use forge_core::{Action, Issue, Repo, Result, User, authorize};
13 use http::HeaderMap;13 use http::HeaderMap;
14 14
15-use crate::i18n;15+use crate::i18n::{self, misc};
16 use crate::mail::{16 use crate::mail::{
17 self,17 self,
18 templates::{self, Verb, Why},18 templates::{self, Verb, Why},
@@ -20,6 +20,7 @@ use crate::mail::{
20 use crate::notify_hub::publish_unread;20 use crate::notify_hub::publish_unread;
21 use crate::render::markdown::mentioned_usernames;21 use crate::render::markdown::mentioned_usernames;
22 use crate::state::AppState;22 use crate::state::AppState;
23+use crate::web_push::{self, Alert};
23 24
24 /// Something that happened on an issue or pull request, as far as notifications care.25 /// Something that happened on an issue or pull request, as far as notifications care.
25 #[derive(Debug, Clone, PartialEq, Eq)]26 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -202,6 +203,15 @@ async fn notify_advisory_admins(state: &AppState, repo: &Repo, opened: usize) ->
202 .notify_new_alerts(&admin, &repo.id, count)203 .notify_new_alerts(&admin, &repo.id, count)
203 .await?;204 .await?;
204 publish_unread(state, &admin).await;205 publish_unread(state, &admin).await;
206+ web_push::queue(
207+ state,
208+ &admin,
209+ Alert::Advisories {
210+ repo: format!("{}/{}", repo.owner_name, repo.name),
211+ count,
212+ url: format!("/{}/{}/security", repo.owner_name, repo.name),
213+ },
214+ );
205 }215 }
206 Ok(())216 Ok(())
207 }217 }
@@ -368,6 +378,20 @@ async fn run(
368 }378 }
369 }379 }
370 380
381+ // The same activity as a push for each device of a recipient. Built once, in the recipient's
382+ // language when it is sent.
383+ let push = if recipients.is_empty() {
384+ None
385+ } else {
386+ match push_alert(state, repo, issue, actor_id, activity).await {
387+ Ok(alert) => Some(alert),
388+ Err(e) => {
389+ tracing::error!(error = %e, issue_id, "notify: push text failed");
390+ None
391+ }
392+ }
393+ };
394+
371 // Auto-subscribe. Existing rows, including explicit ignores, are left alone.395 // Auto-subscribe. Existing rows, including explicit ignores, are left alone.
372 if let Some(actor_id) = actor {396 if let Some(actor_id) = actor {
373 match activity {397 match activity {
@@ -418,7 +442,12 @@ async fn run(
418 )442 )
419 .await443 .await
420 {444 {
421- Ok(()) => publish_unread(state, &user_id).await,445+ Ok(()) => {
446+ publish_unread(state, &user_id).await;
447+ if let Some(alert) = &push {
448+ web_push::queue(state, &user_id, alert.clone());
449+ }
450+ }
422 Err(e) => tracing::error!(error = %e, user_id, issue_id, "notify: inbox write failed"),451 Err(e) => tracing::error!(error = %e, user_id, issue_id, "notify: inbox write failed"),
423 }452 }
424 if let Some(plan) = &plan453 if let Some(plan) = &plan
@@ -500,6 +529,57 @@ async fn mail_plan(
500 }))529 }))
501 }530 }
502 531
532+/// The push text for this activity: the repo, the number, the issue title and what happened.
533+async fn push_alert(
534+ state: &AppState,
535+ repo: &Repo,
536+ issue: &Issue,
537+ actor_id: &str,
538+ activity: &Activity,
539+) -> Result<Alert> {
540+ let actor = match actor_id {
541+ "" => None,
542+ id => state.store.user_by_id(id).await?.map(|u| u.username),
543+ };
544+ let section = if state
545+ .store
546+ .pull_by_number(&repo.id, issue.number)
547+ .await?
548+ .is_some()
549+ {
550+ "pulls"
551+ } else {
552+ "issues"
553+ };
554+ Ok(Alert::Activity {
555+ repo: format!("{}/{}", repo.owner_name, repo.name),
556+ number: issue.number,
557+ title: issue.title.clone(),
558+ verb: push_verb_for(activity),
559+ actor,
560+ url: format!(
561+ "/{}/{}/{section}/{}",
562+ repo.owner_name, repo.name, issue.number
563+ ),
564+ thread: issue.id.clone(),
565+ })
566+}
567+
568+fn push_verb_for(activity: &Activity) -> misc::K {
569+ match activity {
570+ Activity::Opened => misc::K::VerbOpened,
571+ Activity::Comment => misc::K::VerbCommented,
572+ Activity::Closed => misc::K::VerbClosed,
573+ Activity::Reopened => misc::K::VerbReopened,
574+ Activity::Merged => misc::K::VerbMerged,
575+ Activity::Review => misc::K::VerbReviewed,
576+ Activity::Assigned { .. } => misc::K::VerbAssigned,
577+ Activity::ReviewRequested { .. } => misc::K::VerbReviewRequested,
578+ Activity::Pushed => misc::K::VerbPushedTo,
579+ Activity::Edited => misc::K::VerbMentionedYou,
580+ }
581+}
582+
503 fn verb_for(activity: &Activity) -> Verb {583 fn verb_for(activity: &Activity) -> Verb {
504 match activity {584 match activity {
505 Activity::Opened => Verb::Opened,585 Activity::Opened => Verb::Opened,
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -83,6 +83,7 @@ pub mod pull_reviews;
83 pub mod pull_view;83 pub mod pull_view;
84 pub mod pulls_list;84 pub mod pulls_list;
85 pub mod pulls_merge;85 pub mod pulls_merge;
86+pub mod push;
86 pub mod reactions;87 pub mod reactions;
87 #[cfg(test)]88 #[cfg(test)]
88 mod reactions_tests;89 mod reactions_tests;
crates/forge-web/src/pages/push.rsadded+601 -0
@@ -0,0 +1,601 @@
1+//! Web Push routes. The browser calls the `/push` routes from `assets/nav.js`; the settings page
2+//! posts its device actions as forms (soft-navigation swaps the result in place).
3+//!
4+//! - `GET /push/vapid-key`: the public key the browser subscribes with (JSON).
5+//! - `POST /push/subscribe`: adds this browser for the viewer. Fields: `csrf`, `endpoint`,
6+//! `p256dh`, `auth`. The device label comes from the request's User-Agent.
7+//! - `POST /push/unsubscribe`: removes this browser for the viewer. Fields: `csrf`, `endpoint`.
8+//! - `POST /settings/notifications/push/remove`: removes one of the viewer's devices. Fields:
9+//! `csrf`, `id`.
10+//! - `POST /settings/notifications/push/test`: sends a test notification to the viewer's devices.
11+//! - `GET /settings/notifications/push/events`: an event stream that sends `changed` whenever the
12+//! viewer's devices change, so the settings page re-renders without a reload.
13+
14+use futures_util::stream;
15+use http::header::USER_AGENT;
16+use serde::Deserialize;
17+use serde_json::json;
18+use tokio::sync::broadcast::error::RecvError;
19+use topcoat::Result;
20+use topcoat::context::{Cx, app_context};
21+use topcoat::router::content::Form;
22+use topcoat::router::content::sse::{Event, KeepAlive, Sse};
23+use topcoat::router::error::{SeeOther, see_other};
24+use topcoat::router::request::headers;
25+use topcoat::router::response::{IntoResponse, Response};
26+use topcoat::router::{Body, HeaderMap, HeaderValue, StatusCode, header, route};
27+
28+use crate::api::{self, json};
29+use crate::auth::{current_user, require_csrf, require_user};
30+use crate::state::AppState;
31+use crate::web_push::{self, Alert, crypto};
32+
33+/// How often an idle event stream sends a comment so proxies keep it open.
34+const STREAM_KEEP_ALIVE: std::time::Duration = std::time::Duration::from_secs(30);
35+
36+/// Longest push endpoint accepted, in bytes.
37+const MAX_ENDPOINT: usize = 2048;
38+
39+#[derive(Deserialize)]
40+struct SubscribeForm {
41+ #[serde(default)]
42+ csrf: String,
43+ #[serde(default)]
44+ endpoint: String,
45+ #[serde(default)]
46+ p256dh: String,
47+ #[serde(default)]
48+ auth: String,
49+}
50+
51+#[derive(Deserialize)]
52+struct EndpointForm {
53+ #[serde(default)]
54+ csrf: String,
55+ #[serde(default)]
56+ endpoint: String,
57+}
58+
59+#[derive(Deserialize)]
60+struct DeviceForm {
61+ #[serde(default)]
62+ csrf: String,
63+ #[serde(default)]
64+ id: String,
65+}
66+
67+#[derive(Deserialize)]
68+struct CsrfForm {
69+ #[serde(default)]
70+ csrf: String,
71+}
72+
73+/// A push endpoint must be an https URL of sane length. The service worker never opens it, but
74+/// the server posts to it, so only the push service's own kind of URL is accepted.
75+fn check_endpoint(endpoint: &str) -> forge_core::Result<()> {
76+ if endpoint.len() > MAX_ENDPOINT {
77+ return Err(forge_core::Error::Invalid(
78+ "the push endpoint is too long".into(),
79+ ));
80+ }
81+ let url = reqwest::Url::parse(endpoint)
82+ .map_err(|_| forge_core::Error::Invalid("the push endpoint is not a URL".into()))?;
83+ // The VAPID audience is the origin without a port (web-push-native builds it that way), so a
84+ // non-default port would not match what the push service checks. Push services use 443.
85+ if url.scheme() != "https" || url.host_str().is_none() || url.port().is_some() {
86+ return Err(forge_core::Error::Invalid(
87+ "the push endpoint must be an https URL on the default port".into(),
88+ ));
89+ }
90+ Ok(())
91+}
92+
93+/// The browser's P-256 public key must be an uncompressed point, and its auth secret 16 bytes.
94+fn check_keys(p256dh: &str, auth: &str) -> forge_core::Result<()> {
95+ let point = crypto::decode_b64(p256dh)?;
96+ if point.len() != 65
97+ || point[0] != 0x04
98+ || web_push_native::p256::PublicKey::from_sec1_bytes(&point).is_err()
99+ {
100+ return Err(forge_core::Error::Invalid(
101+ "the browser key is not a P-256 public key".into(),
102+ ));
103+ }
104+ if crypto::decode_b64(auth)?.len() != 16 {
105+ return Err(forge_core::Error::Invalid(
106+ "the browser auth secret is not 16 bytes".into(),
107+ ));
108+ }
109+ Ok(())
110+}
111+
112+fn no_content() -> Response {
113+ let mut res = Response::new(Body::empty());
114+ *res.status_mut() = StatusCode::NO_CONTENT;
115+ res
116+}
117+
118+/// The public key the browser subscribes with. Creates the instance's key pair on first use.
119+#[route(GET "/push/vapid-key")]
120+async fn vapid_key(cx: &Cx) -> Result<Response> {
121+ require_user(cx).await?;
122+ let state = app_context::<AppState>(cx);
123+ let keys = web_push::vapid_keys(state).await?;
124+ Ok(json(StatusCode::OK, &json!({ "public_key": keys.public })))
125+}
126+
127+/// Adds this browser as a device of the viewer.
128+#[route(POST "/push/subscribe")]
129+async fn subscribe(cx: &Cx, Form(form): Form<SubscribeForm>) -> Result<Response> {
130+ let (user, _) = require_csrf(cx, &form.csrf).await?;
131+ if let Err(e) =
132+ check_endpoint(&form.endpoint).and_then(|()| check_keys(&form.p256dh, &form.auth))
133+ {
134+ return Ok(api::error(StatusCode::BAD_REQUEST, &e.to_string()));
135+ }
136+ let state = app_context::<AppState>(cx);
137+ let agent = headers(cx)
138+ .get(USER_AGENT)
139+ .and_then(|value| value.to_str().ok())
140+ .unwrap_or_default()
141+ .to_owned();
142+ state
143+ .store
144+ .save_push_subscription(
145+ &user.id,
146+ &form.endpoint,
147+ &form.p256dh,
148+ &form.auth,
149+ &web_push::agent_label(&agent),
150+ )
151+ .await?;
152+ state.push_live.publish(&user.id);
153+ Ok(no_content())
154+}
155+
156+/// Removes this browser from the viewer's devices. Nothing to remove is not an error.
157+#[route(POST "/push/unsubscribe")]
158+async fn unsubscribe(cx: &Cx, Form(form): Form<EndpointForm>) -> Result<Response> {
159+ let (user, _) = require_csrf(cx, &form.csrf).await?;
160+ let state = app_context::<AppState>(cx);
161+ if state
162+ .store
163+ .delete_push_subscription_by_endpoint(&user.id, &form.endpoint)
164+ .await?
165+ {
166+ state.push_live.publish(&user.id);
167+ }
168+ Ok(no_content())
169+}
170+
171+/// Removes one of the viewer's devices from the settings list.
172+#[route(POST "/settings/notifications/push/remove")]
173+async fn remove_device(cx: &Cx, Form(form): Form<DeviceForm>) -> Result<SeeOther> {
174+ let (user, _) = require_csrf(cx, &form.csrf).await?;
175+ let state = app_context::<AppState>(cx);
176+ if state
177+ .store
178+ .delete_push_subscription(&user.id, &form.id)
179+ .await?
180+ {
181+ state.push_live.publish(&user.id);
182+ }
183+ Ok(see_other("/settings/notifications?removed=1"))
184+}
185+
186+/// Sends the test notification to every device of the viewer. The count goes back in the URL so
187+/// the settings page can say how many devices were tried.
188+#[route(POST "/settings/notifications/push/test")]
189+async fn send_test(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
190+ let (user, _) = require_csrf(cx, &form.csrf).await?;
191+ let state = app_context::<AppState>(cx);
192+ let devices = state.store.push_subscriptions(&user.id).await?.len();
193+ if devices > 0 {
194+ web_push::queue(state, &user.id, Alert::Test);
195+ }
196+ Ok(see_other(format!("/settings/notifications?test={devices}")))
197+}
198+
199+/// One `changed` event each time the viewer's devices change, until the viewer disconnects or the
200+/// server shuts down. Other users' changes are skipped. An anonymous viewer gets a bare 401.
201+#[route(GET "/settings/notifications/push/events")]
202+async fn push_events(cx: &Cx) -> Result<Response> {
203+ let Some((user, _)) = current_user(cx).await? else {
204+ let mut res = Response::new(Body::empty());
205+ *res.status_mut() = StatusCode::UNAUTHORIZED;
206+ return Ok(res);
207+ };
208+ let state = app_context::<AppState>(cx);
209+ let rx = state.push_live.subscribe();
210+ let changes = stream::unfold((rx, user.id), |(mut rx, user_id)| async move {
211+ loop {
212+ match rx.recv().await {
213+ Ok(changed) if changed == user_id => {
214+ return Some((changed_event(), (rx, user_id)));
215+ }
216+ Ok(_) => continue,
217+ // Missed some changes: say so, so the page re-reads its devices.
218+ Err(RecvError::Lagged(_)) => return Some((changed_event(), (rx, user_id))),
219+ Err(RecvError::Closed) => return None,
220+ }
221+ }
222+ });
223+ let events = Sse::new(changes).keep_alive(
224+ KeepAlive::new()
225+ .interval(STREAM_KEEP_ALIVE)
226+ .text("keepalive"),
227+ );
228+ let mut res = events.into_response(cx)?;
229+ // Nginx buffers a proxied response unless told not to, which would hold the events back.
230+ res.headers_mut()
231+ .insert("x-accel-buffering", HeaderValue::from_static("no"));
232+ Ok(res)
233+}
234+
235+fn changed_event() -> Result<Event> {
236+ Ok(Event::new().event("changed").data("1"))
237+}
238+
239+/// The service worker. It must sit at the origin root to control every page, so it has its own
240+/// route rather than the immutable `/assets` ones. Revalidated on each load.
241+const SW_JS: &str = include_str!("../../assets/sw.js");
242+const ICON_192: &[u8] = include_bytes!("../../assets/icons/icon-192.png");
243+const ICON_512: &[u8] = include_bytes!("../../assets/icons/icon-512.png");
244+const APPLE_TOUCH_ICON: &[u8] = include_bytes!("../../assets/icons/apple-touch-icon.png");
245+
246+/// The web app manifest: installing Forge from the browser gives a standalone app with these icons.
247+const MANIFEST: &str = r##"{
248+ "name": "Forge",
249+ "short_name": "Forge",
250+ "start_url": "/",
251+ "scope": "/",
252+ "display": "standalone",
253+ "background_color": "#f6f4ec",
254+ "theme_color": "#5f7f67",
255+ "icons": [
256+ { "src": "/assets/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
257+ { "src": "/assets/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }
258+ ]
259+}
260+"##;
261+
262+fn static_headers(content_type: &'static str, cache: &'static str) -> HeaderMap {
263+ let mut headers = HeaderMap::new();
264+ headers.insert(
265+ header::CONTENT_TYPE,
266+ content_type.parse().expect("static header value"),
267+ );
268+ headers.insert(
269+ header::CACHE_CONTROL,
270+ cache.parse().expect("static header value"),
271+ );
272+ headers
273+}
274+
275+#[route(GET "/sw.js")]
276+async fn service_worker() -> Result<(StatusCode, HeaderMap, &'static str)> {
277+ let headers = static_headers("text/javascript; charset=utf-8", "no-cache");
278+ Ok((StatusCode::OK, headers, SW_JS))
279+}
280+
281+#[route(GET "/manifest.webmanifest")]
282+async fn manifest() -> Result<(StatusCode, HeaderMap, &'static str)> {
283+ let headers = static_headers("application/manifest+json", "public, max-age=3600");
284+ Ok((StatusCode::OK, headers, MANIFEST))
285+}
286+
287+#[route(GET "/assets/icons/icon-192.png")]
288+async fn icon_192() -> Result<(StatusCode, HeaderMap, &'static [u8])> {
289+ let headers = static_headers("image/png", "public, max-age=604800");
290+ Ok((StatusCode::OK, headers, ICON_192))
291+}
292+
293+#[route(GET "/assets/icons/icon-512.png")]
294+async fn icon_512() -> Result<(StatusCode, HeaderMap, &'static [u8])> {
295+ let headers = static_headers("image/png", "public, max-age=604800");
296+ Ok((StatusCode::OK, headers, ICON_512))
297+}
298+
299+#[route(GET "/assets/icons/apple-touch-icon.png")]
300+async fn apple_touch_icon() -> Result<(StatusCode, HeaderMap, &'static [u8])> {
301+ let headers = static_headers("image/png", "public, max-age=604800");
302+ Ok((StatusCode::OK, headers, APPLE_TOUCH_ICON))
303+}
304+
305+#[cfg(test)]
306+mod tests {
307+ use forge_core::Store;
308+ use topcoat::router::request::Request;
309+ use topcoat::router::{Body, Router, to_bytes};
310+ use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint;
311+
312+ use crate::auth::SESSION_COOKIE;
313+ use crate::test_support::{app_router, create_session, test_state};
314+ use crate::web_push::crypto;
315+
316+ const TOKEN: &str = "push-session";
317+ const CSRF: &str = "push-csrf";
318+ const UA: &str =
319+ "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36";
320+
321+ struct Fixture {
322+ _dir: tempfile::TempDir,
323+ router: Router,
324+ store: Store,
325+ user_id: String,
326+ }
327+
328+ async fn fixture() -> Fixture {
329+ let dir = tempfile::tempdir().expect("tempdir");
330+ let data_dir = dir.path().join("data");
331+ std::fs::create_dir_all(&data_dir).expect("data dir");
332+ let state = test_state(&data_dir).await;
333+ let user = state
334+ .store
335+ .create_user("tahinli", None, "h", false)
336+ .await
337+ .expect("user");
338+ create_session(&state.store, &user.id, TOKEN, CSRF).await;
339+ Fixture {
340+ _dir: dir,
341+ router: app_router(state.clone()),
342+ store: state.store.clone(),
343+ user_id: user.id,
344+ }
345+ }
346+
347+ /// A browser key and auth secret as a browser would send them: base64url, uncompressed point.
348+ fn browser_keys() -> (String, String) {
349+ let secret = web_push_native::p256::SecretKey::from_slice(&crypto::new_vapid_private())
350+ .expect("scalar");
351+ let point = secret.public_key().to_encoded_point(false);
352+ (
353+ crypto::encode_b64(point.as_bytes()),
354+ crypto::encode_b64(&[7u8; 16]),
355+ )
356+ }
357+
358+ async fn send(
359+ router: &Router,
360+ method: &str,
361+ uri: &str,
362+ token: Option<&str>,
363+ form: Option<String>,
364+ ) -> (u16, String) {
365+ let mut builder = Request::builder()
366+ .method(method)
367+ .uri(uri)
368+ .header("user-agent", UA);
369+ if let Some(token) = token {
370+ builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
371+ }
372+ let body = match form {
373+ Some(form) => {
374+ builder = builder.header("content-type", "application/x-www-form-urlencoded");
375+ Body::from(form)
376+ }
377+ None => Body::empty(),
378+ };
379+ let res = router.handle(builder.body(body).expect("request")).await;
380+ let status = res.status().as_u16();
381+ let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
382+ (status, String::from_utf8_lossy(&bytes).into_owned())
383+ }
384+
385+ fn subscribe_form(csrf: &str, endpoint: &str, p256dh: &str, auth: &str) -> String {
386+ let enc = |s: &str| form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>();
387+ format!(
388+ "csrf={}&endpoint={}&p256dh={}&auth={}",
389+ enc(csrf),
390+ enc(endpoint),
391+ enc(p256dh),
392+ enc(auth)
393+ )
394+ }
395+
396+ #[tokio::test]
397+ async fn the_vapid_key_is_created_once_and_served() {
398+ let fx = fixture().await;
399+ let (status, first) = send(&fx.router, "GET", "/push/vapid-key", Some(TOKEN), None).await;
400+ assert_eq!(status, 200, "{first}");
401+ let (_, second) = send(&fx.router, "GET", "/push/vapid-key", Some(TOKEN), None).await;
402+ assert_eq!(first, second, "the same key on every request");
403+ let key: serde_json::Value = serde_json::from_str(&first).expect("json");
404+ let public = key["public_key"].as_str().expect("public key");
405+ assert_eq!(crypto::decode_b64(public).expect("b64").len(), 65);
406+ }
407+
408+ #[tokio::test]
409+ async fn the_vapid_key_needs_a_session() {
410+ let fx = fixture().await;
411+ let (status, _) = send(&fx.router, "GET", "/push/vapid-key", None, None).await;
412+ assert_ne!(status, 200);
413+ }
414+
415+ #[tokio::test]
416+ async fn subscribe_then_unsubscribe_round_trip() {
417+ let fx = fixture().await;
418+ let (p256dh, auth) = browser_keys();
419+ let endpoint = "https://push.example.test/send/tahinli-1";
420+ let form = subscribe_form(CSRF, endpoint, &p256dh, &auth);
421+
422+ let (status, body) = send(
423+ &fx.router,
424+ "POST",
425+ "/push/subscribe",
426+ Some(TOKEN),
427+ Some(form),
428+ )
429+ .await;
430+ assert_eq!(status, 204, "{body}");
431+ let devices = fx
432+ .store
433+ .push_subscriptions(&fx.user_id)
434+ .await
435+ .expect("list");
436+ assert_eq!(devices.len(), 1);
437+ assert_eq!(devices[0].endpoint, endpoint);
438+ assert_eq!(devices[0].agent_label, "Chrome on Android");
439+
440+ let remove = format!("csrf={CSRF}&endpoint={endpoint}");
441+ let (status, body) = send(
442+ &fx.router,
443+ "POST",
444+ "/push/unsubscribe",
445+ Some(TOKEN),
446+ Some(remove),
447+ )
448+ .await;
449+ assert_eq!(status, 204, "{body}");
450+ assert!(
451+ fx.store
452+ .push_subscriptions(&fx.user_id)
453+ .await
454+ .expect("list")
455+ .is_empty()
456+ );
457+ }
458+
459+ #[tokio::test]
460+ async fn a_subscription_needs_the_csrf_token() {
461+ let fx = fixture().await;
462+ let (p256dh, auth) = browser_keys();
463+ let form = subscribe_form("wrong", "https://push.example.test/x", &p256dh, &auth);
464+ let (status, _) = send(
465+ &fx.router,
466+ "POST",
467+ "/push/subscribe",
468+ Some(TOKEN),
469+ Some(form),
470+ )
471+ .await;
472+ assert_eq!(status, 403);
473+ assert!(
474+ fx.store
475+ .push_subscriptions(&fx.user_id)
476+ .await
477+ .expect("list")
478+ .is_empty()
479+ );
480+ }
481+
482+ #[tokio::test]
483+ async fn a_subscription_with_bad_fields_is_refused() {
484+ let fx = fixture().await;
485+ let (p256dh, auth) = browser_keys();
486+ let http_endpoint = subscribe_form(CSRF, "http://push.example.test/x", &p256dh, &auth);
487+ let (status, _) = send(
488+ &fx.router,
489+ "POST",
490+ "/push/subscribe",
491+ Some(TOKEN),
492+ Some(http_endpoint),
493+ )
494+ .await;
495+ assert_eq!(status, 400, "an endpoint must be https");
496+ let short_auth = subscribe_form(
497+ CSRF,
498+ "https://push.example.test/x",
499+ &p256dh,
500+ &crypto::encode_b64(&[1u8; 8]),
501+ );
502+ let (status, _) = send(
503+ &fx.router,
504+ "POST",
505+ "/push/subscribe",
506+ Some(TOKEN),
507+ Some(short_auth),
508+ )
509+ .await;
510+ assert_eq!(status, 400, "the auth secret is 16 bytes");
511+ let not_a_point = subscribe_form(
512+ CSRF,
513+ "https://push.example.test/x",
514+ &crypto::encode_b64(&[4u8; 65]),
515+ &auth,
516+ );
517+ let (status, _) = send(
518+ &fx.router,
519+ "POST",
520+ "/push/subscribe",
521+ Some(TOKEN),
522+ Some(not_a_point),
523+ )
524+ .await;
525+ assert_eq!(status, 400, "the browser key is a point");
526+ assert!(
527+ fx.store
528+ .push_subscriptions(&fx.user_id)
529+ .await
530+ .expect("list")
531+ .is_empty()
532+ );
533+ }
534+
535+ #[tokio::test]
536+ async fn a_viewer_removes_only_their_own_device() {
537+ let fx = fixture().await;
538+ let other = fx
539+ .store
540+ .create_user("nina", None, "h", false)
541+ .await
542+ .expect("other user");
543+ let theirs = fx
544+ .store
545+ .save_push_subscription(
546+ &other.id,
547+ "https://push.example.test/nina",
548+ "BA",
549+ "AA",
550+ "Chrome on Linux",
551+ )
552+ .await
553+ .expect("save");
554+ let form = format!("csrf={CSRF}&id={}", theirs.id);
555+ let (status, _) = send(
556+ &fx.router,
557+ "POST",
558+ "/settings/notifications/push/remove",
559+ Some(TOKEN),
560+ Some(form),
561+ )
562+ .await;
563+ assert_eq!(status, 303);
564+ assert_eq!(
565+ fx.store
566+ .push_subscriptions(&other.id)
567+ .await
568+ .expect("list")
569+ .len(),
570+ 1
571+ );
572+ }
573+
574+ #[tokio::test]
575+ async fn the_events_stream_needs_a_session() {
576+ let fx = fixture().await;
577+ let (status, _) = send(
578+ &fx.router,
579+ "GET",
580+ "/settings/notifications/push/events",
581+ None,
582+ None,
583+ )
584+ .await;
585+ assert_eq!(status, 401);
586+ }
587+
588+ #[tokio::test]
589+ async fn the_service_worker_and_manifest_are_served() {
590+ let fx = fixture().await;
591+ let (status, sw) = send(&fx.router, "GET", "/sw.js", None, None).await;
592+ assert_eq!(status, 200);
593+ assert!(sw.contains("notificationclick"), "{sw}");
594+ let (status, manifest) = send(&fx.router, "GET", "/manifest.webmanifest", None, None).await;
595+ assert_eq!(status, 200);
596+ assert!(
597+ manifest.contains("\"display\": \"standalone\""),
598+ "{manifest}"
599+ );
600+ }
601+}
crates/forge-web/src/pages/settings_notifications.rsmodified+88 -6
@@ -4,6 +4,7 @@
4 //! itself on change (soft-nav POST, no reload); the Save button only shows without JavaScript.4 //! itself on change (soft-nav POST, no reload); the Save button only shows without JavaScript.
5 //! Every POST checks the CSRF token first.5 //! Every POST checks the CSRF token first.
6 6
7+use forge_core::store::web_push::PushSubscription;
7 use forge_core::{Session, Store, User};8 use forge_core::{Session, Store, User};
8 use serde::Deserialize;9 use serde::Deserialize;
9 use topcoat::Result;10 use topcoat::Result;
@@ -14,13 +15,18 @@ use topcoat::router::{page, query_params, route};
14 use topcoat::view::{View, component, view};15 use topcoat::view::{View, component, view};
15 16
16 use crate::auth::{require_csrf, require_user};17 use crate::auth::{require_csrf, require_user};
18+use crate::i18n::push as push_text;
17 use crate::i18n::{self, Key, Lang, t};19 use crate::i18n::{self, Key, Lang, t};
18 use crate::state::AppState;20 use crate::state::AppState;
19-use crate::views::shell;21+use crate::views::{csrf_field, shell};
20 22
21 #[query_params(error = bad_request)]23 #[query_params(error = bad_request)]
22 struct NotificationsQuery {24 struct NotificationsQuery {
23 saved: Option<String>,25 saved: Option<String>,
26+ /// Set by the test button: how many devices the test was sent to.
27+ test: Option<String>,
28+ /// Set after a device is removed.
29+ removed: Option<String>,
24 }30 }
25 31
26 #[derive(Deserialize)]32 #[derive(Deserialize)]
@@ -40,7 +46,16 @@ struct NotificationsPage {
40 unverified_note: Option<&'static str>,46 unverified_note: Option<&'static str>,
41 /// A note when instance mail is off, `None` when it is on.47 /// A note when instance mail is off, `None` when it is on.
42 server_note: Option<&'static str>,48 server_note: Option<&'static str>,
43- notice: Option<&'static str>,49+ notice: Option<String>,
50+ /// The viewer's devices with push on.
51+ devices: Vec<PushSubscription>,
52+ /// Whether the test button has a device to send to.
53+ can_test: bool,
54+}
55+
56+/// A device's date for the list: the `YYYY-MM-DD` part of its stamp.
57+fn day_of(stamp: &str) -> &str {
58+ stamp.get(..10).unwrap_or(stamp)
44 }59 }
45 60
46 #[component]61 #[component]
@@ -52,6 +67,8 @@ async fn notifications_body(page: NotificationsPage) -> Result<impl View> {
52 unverified_note,67 unverified_note,
53 server_note,68 server_note,
54 notice,69 notice,
70+ devices,
71+ can_test,
55 } = page;72 } = page;
56 // Nothing can be sent while instance mail is off or the address is unverified, so the box is73 // Nothing can be sent while instance mail is off or the address is unverified, so the box is
57 // locked and the notes below say why.74 // locked and the notes below say why.
@@ -63,7 +80,7 @@ async fn notifications_body(page: NotificationsPage) -> Result<impl View> {
63 </section>80 </section>
64 if let Some(message) = notice {81 if let Some(message) = notice {
65 <section class="card notice" role="status">82 <section class="card notice" role="status">
66- <p>(message)</p>83+ <p>(message.as_str())</p>
67 </section>84 </section>
68 }85 }
69 <section class="card">86 <section class="card">
@@ -89,6 +106,56 @@ async fn notifications_body(page: NotificationsPage) -> Result<impl View> {
89 </noscript>106 </noscript>
90 </form>107 </form>
91 </section>108 </section>
109+ <section class="card push-card" data-push="true" data-live="/settings/notifications/push/events">
110+ <h2>(push_text::t(lang, push_text::K::DeviceHeading))</h2>
111+ <small class="muted">(push_text::t(lang, push_text::K::DeviceHelp))</small>
112+ <p class="notice" role="note" data-push-state="unsupported" hidden=(true)>(push_text::t(lang, push_text::K::DeviceUnsupported))</p>
113+ <p class="notice" role="note" data-push-state="https" hidden=(true)>(push_text::t(lang, push_text::K::DeviceNeedsHttps))</p>
114+ <p class="notice" role="note" data-push-state="ios" hidden=(true)>(push_text::t(lang, push_text::K::DeviceIosHint))</p>
115+ <p class="notice" role="note" data-push-state="denied" hidden=(true)>(push_text::t(lang, push_text::K::DeviceDenied))</p>
116+ <p class="notice" role="alert" data-push-state="error" hidden=(true)>(push_text::t(lang, push_text::K::DeviceError))</p>
117+ <p class="muted" data-push-state="on" hidden=(true)>(push_text::t(lang, push_text::K::DeviceOn))</p>
118+ <p class="muted" data-push-state="off" hidden=(true)>(push_text::t(lang, push_text::K::DeviceOff))</p>
119+ <div class="actions">
120+ <button type="button" class="primary" data-push-action="enable" hidden=(true)>(push_text::t(lang, push_text::K::TurnOn))</button>
121+ <button type="button" data-push-action="disable" hidden=(true)>(push_text::t(lang, push_text::K::TurnOff))</button>
122+ </div>
123+ <form method="post" action="/settings/notifications/push/test" class="actions">
124+ csrf_field(token: csrf.as_str())
125+ <button type="submit" data-push-test="true" disabled=(!can_test)>(push_text::t(lang, push_text::K::SendTest))</button>
126+ if !can_test {
127+ <small class="muted">(push_text::t(lang, push_text::K::TestNoDevices))</small>
128+ }
129+ </form>
130+ </section>
131+ <section class="card">
132+ <h2>(push_text::t(lang, push_text::K::DevicesHeading))</h2>
133+ if devices.is_empty() {
134+ <p class="muted">(push_text::t(lang, push_text::K::DevicesEmpty))</p>
135+ }
136+ <ul class="push-devices">
137+ for device in devices.into_iter() {
138+ <li class="push-device">
139+ <div>
140+ <strong>(device.agent_label.as_str())</strong>
141+ <small class="muted">(push_text::added_on(lang, day_of(&device.created_at)))</small>
142+ <small class="muted">
143+ if let Some(stamp) = device.last_success_at.as_deref() {
144+ (push_text::last_delivered(lang, day_of(stamp)))
145+ } else {
146+ (push_text::t(lang, push_text::K::NeverDelivered))
147+ }
148+ </small>
149+ </div>
150+ <form method="post" action="/settings/notifications/push/remove" class="push-remove">
151+ csrf_field(token: csrf.as_str())
152+ <input type="hidden" name="id" value=(device.id.as_str())>
153+ <button type="submit" class="link-button">(push_text::t(lang, push_text::K::RemoveDevice))</button>
154+ </form>
155+ </li>
156+ }
157+ </ul>
158+ </section>
92 </div>159 </div>
93 })160 })
94 }161 }
@@ -98,10 +165,11 @@ async fn page_for(
98 store: &Store,165 store: &Store,
99 viewer: &(User, Session),166 viewer: &(User, Session),
100 lang: Lang,167 lang: Lang,
101- notice: Option<&'static str>,168+ notice: Option<String>,
102 ) -> forge_core::Result<NotificationsPage> {169 ) -> forge_core::Result<NotificationsPage> {
103 let server_on = store.mail_settings().await?.enabled;170 let server_on = store.mail_settings().await?.enabled;
104 let verified = store.email_is_verified(&viewer.0.id).await?;171 let verified = store.email_is_verified(&viewer.0.id).await?;
172+ let devices = store.push_subscriptions(&viewer.0.id).await?;
105 Ok(NotificationsPage {173 Ok(NotificationsPage {
106 lang,174 lang,
107 csrf: viewer.1.csrf_token.clone(),175 csrf: viewer.1.csrf_token.clone(),
@@ -109,6 +177,8 @@ async fn page_for(
109 unverified_note: (!verified).then(|| t(lang, Key::EmailNotifyUnverified)),177 unverified_note: (!verified).then(|| t(lang, Key::EmailNotifyUnverified)),
110 server_note: (!server_on).then(|| t(lang, Key::EmailNotifyServerOff)),178 server_note: (!server_on).then(|| t(lang, Key::EmailNotifyServerOff)),
111 notice,179 notice,
180+ can_test: !devices.is_empty(),
181+ devices,
112 })182 })
113 }183 }
114 184
@@ -117,8 +187,20 @@ async fn notifications_page(cx: &Cx) -> Result<impl View> {
117 let viewer = require_user(cx).await?;187 let viewer = require_user(cx).await?;
118 let store: &Store = &app_context::<AppState>(cx).store;188 let store: &Store = &app_context::<AppState>(cx).store;
119 let lang = i18n::lang(cx, Some(&viewer.0));189 let lang = i18n::lang(cx, Some(&viewer.0));
120- let saved = query_params::<NotificationsQuery>(cx)?.saved.clone();190+ let query = query_params::<NotificationsQuery>(cx)?;
121- let notice = (saved.as_deref() == Some("1")).then(|| t(lang, Key::EmailNotifySaved));191+ let notice = if query.saved.as_deref() == Some("1") {
192+ Some(t(lang, Key::EmailNotifySaved).to_owned())
193+ } else if let Some(sent) = query.test.as_deref() {
194+ match sent.parse::<usize>() {
195+ Ok(0) => Some(push_text::t(lang, push_text::K::TestNoDevices).to_owned()),
196+ Ok(n) => Some(push_text::test_sent(lang, n)),
197+ Err(_) => None,
198+ }
199+ } else if query.removed.as_deref() == Some("1") {
200+ Some(push_text::t(lang, push_text::K::DeviceRemoved).to_owned())
201+ } else {
202+ None
203+ };
122 let page = page_for(store, &viewer, lang, notice).await?;204 let page = page_for(store, &viewer, lang, notice).await?;
123 Ok(view! {205 Ok(view! {
124 shell(title: t(lang, Key::Notifications), viewer: Some(&viewer), notifications_body(page: page))206 shell(title: t(lang, Key::Notifications), viewer: Some(&viewer), notifications_body(page: page))
crates/forge-web/src/pages/settings_security.rsmodified+1 -0
@@ -1101,6 +1101,7 @@ mod tests {
1101 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),1101 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
1102 ci_live: Arc::new(crate::ci::CiLive::default()),1102 ci_live: Arc::new(crate::ci::CiLive::default()),
1103 live: Arc::new(crate::live::LiveHub::default()),1103 live: Arc::new(crate::live::LiveHub::default()),
1104+ push_live: Arc::new(crate::web_push::PushLive::default()),
1104 };1105 };
1105 let hash = hash_password_async(PASSWORD.into()).await.unwrap();1106 let hash = hash_password_async(PASSWORD.into()).await.unwrap();
1106 let user = store1107 let user = store
crates/forge-web/src/state.rsmodified+2 -0
@@ -51,6 +51,8 @@ pub struct AppState {
51 pub ci_live: Arc<crate::ci::CiLive>,51 pub ci_live: Arc<crate::ci::CiLive>,
52 /// Change signals of live pages, keyed by topic. See `live`.52 /// Change signals of live pages, keyed by topic. See `live`.
53 pub live: Arc<crate::live::LiveHub>,53 pub live: Arc<crate::live::LiveHub>,
54+ /// Device changes per user. The settings pages showing a user's push devices listen to it.
55+ pub push_live: Arc<crate::web_push::PushLive>,
54 }56 }
55 57
56 /// A settings handle over `config` with no stored overrides and no file keys. For tests.58 /// A settings handle over `config` with no stored overrides and no file keys. For tests.
crates/forge-web/src/test_support.rsmodified+1 -0
@@ -87,6 +87,7 @@ pub async fn test_state(dir: &Path) -> AppState {
87 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),87 notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()),
88 ci_live: Arc::new(crate::ci::CiLive::default()),88 ci_live: Arc::new(crate::ci::CiLive::default()),
89 live: Arc::new(crate::live::LiveHub::default()),89 live: Arc::new(crate::live::LiveHub::default()),
90+ push_live: Arc::new(crate::web_push::PushLive::default()),
90 }91 }
91 }92 }
92 93
crates/forge-web/src/views/mod.rsmodified+4 -0
@@ -253,6 +253,10 @@ pub async fn shell(
253 <meta charset="utf-8">253 <meta charset="utf-8">
254 <meta name="viewport" content="width=device-width, initial-scale=1">254 <meta name="viewport" content="width=device-width, initial-scale=1">
255 <meta name="referrer" content="same-origin">255 <meta name="referrer" content="same-origin">
256+ <meta name="theme-color" content="#5f7f67">
257+ <meta name="apple-mobile-web-app-capable" content="yes">
258+ <link rel="manifest" href="/manifest.webmanifest">
259+ <link rel="apple-touch-icon" href="/assets/icons/apple-touch-icon.png">
256 <title>(full_title)</title>260 <title>(full_title)</title>
257 <link rel="preload" as="font" type="font/woff2" crossorigin="anonymous" href=(FIGTREE_PRELOAD_HREF)>261 <link rel="preload" as="font" type="font/woff2" crossorigin="anonymous" href=(FIGTREE_PRELOAD_HREF)>
258 <link rel="stylesheet" href=(STYLESHEET_HREF)>262 <link rel="stylesheet" href=(STYLESHEET_HREF)>
crates/forge-web/src/web_push/crypto.rsadded+177 -0
@@ -0,0 +1,177 @@
1+//! Thin glue over `web-push-native`, which does the cryptography: the RFC 8291 message encryption
2+//! (aes128gcm content coding, RFC 8188) and the RFC 8292 VAPID authorization (an ES256 JWT). The
3+//! crate is RustCrypto based and pure Rust. This module only converts the base64url values that
4+//! browsers and the database hold into the types the crate takes, and builds the request.
5+
6+use base64::Engine;
7+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
8+use p256::elliptic_curve::sec1::ToEncodedPoint;
9+use web_push_native::jwt_simple::algorithms::ES256KeyPair;
10+use web_push_native::{Auth, WebPushBuilder, p256};
11+
12+use forge_core::{Error, Result};
13+
14+/// The uncompressed P-256 point length: 0x04 followed by X and Y.
15+const POINT_LEN: usize = 65;
16+
17+/// Decodes base64url, with or without padding.
18+pub fn decode_b64(text: &str) -> Result<Vec<u8>> {
19+ URL_SAFE_NO_PAD
20+ .decode(text.trim_end_matches('='))
21+ .map_err(|_| Error::Invalid("not base64url".into()))
22+}
23+
24+/// Encodes base64url without padding, the form push services and browsers use.
25+pub fn encode_b64(bytes: &[u8]) -> String {
26+ URL_SAFE_NO_PAD.encode(bytes)
27+}
28+
29+/// A new VAPID private key (32 bytes) from the system RNG.
30+pub fn new_vapid_private() -> [u8; 32] {
31+ let mut out = [0u8; 32];
32+ out.copy_from_slice(&ES256KeyPair::generate().to_bytes());
33+ out
34+}
35+
36+/// The key pair the VAPID signature is made with, from its 32-byte private scalar.
37+pub fn vapid_key_pair(private: &[u8; 32]) -> Result<ES256KeyPair> {
38+ ES256KeyPair::from_bytes(private).map_err(|_| Error::Crypto("bad VAPID key".into()))
39+}
40+
41+/// The public key of a VAPID private key, as the uncompressed point in base64url. This is the
42+/// `applicationServerKey` the browser subscribes with.
43+pub fn vapid_public_key(private: &[u8; 32]) -> Result<String> {
44+ let secret =
45+ p256::SecretKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))?;
46+ let point = secret.public_key().to_encoded_point(false);
47+ Ok(encode_b64(point.as_bytes()))
48+}
49+
50+/// Builds the POST for one push: the body is encrypted for the browser's key and auth secret,
51+/// and the request carries the VAPID `Authorization` for `endpoint`'s origin. `subject` is the
52+/// contact URL (`mailto:` or `https:`).
53+pub fn push_request(
54+ endpoint: &str,
55+ p256dh: &[u8],
56+ auth: &[u8],
57+ subject: &str,
58+ key_pair: &ES256KeyPair,
59+ payload: Vec<u8>,
60+) -> Result<http::Request<Vec<u8>>> {
61+ if p256dh.len() != POINT_LEN {
62+ return Err(Error::Invalid(
63+ "the browser key is not a P-256 point".into(),
64+ ));
65+ }
66+ let ua_public = p256::PublicKey::from_sec1_bytes(p256dh)
67+ .map_err(|_| Error::Invalid("the browser key is not on the curve".into()))?;
68+ if auth.len() != 16 {
69+ return Err(Error::Invalid(
70+ "the browser auth secret is not 16 bytes".into(),
71+ ));
72+ }
73+ let ua_auth = Auth::clone_from_slice(auth);
74+ let uri: http::Uri = endpoint
75+ .parse()
76+ .map_err(|_| Error::Invalid("bad push endpoint".into()))?;
77+ WebPushBuilder::new(uri, ua_public, ua_auth)
78+ .with_vapid(key_pair, subject)
79+ .build(payload)
80+ .map_err(|e| Error::Crypto(format!("web push encryption failed: {e}")))
81+}
82+
83+#[cfg(test)]
84+mod tests {
85+ use super::*;
86+ use p256::elliptic_curve::sec1::ToEncodedPoint;
87+
88+ #[test]
89+ fn a_browser_key_that_is_not_a_point_is_refused() {
90+ let key_pair = vapid_key_pair(&new_vapid_private()).expect("key");
91+ let auth = [7u8; 16];
92+ let not_a_point = [4u8; 65];
93+ assert!(
94+ push_request(
95+ "https://push.example.test/x",
96+ &not_a_point,
97+ &auth,
98+ "mailto:tahinli@example.test",
99+ &key_pair,
100+ b"hi".to_vec()
101+ )
102+ .is_err()
103+ );
104+ assert!(
105+ push_request(
106+ "https://push.example.test/x",
107+ &[0x04; 10],
108+ &auth,
109+ "mailto:tahinli@example.test",
110+ &key_pair,
111+ b"hi".to_vec()
112+ )
113+ .is_err()
114+ );
115+ }
116+
117+ #[test]
118+ fn the_request_is_an_encrypted_vapid_post_to_the_endpoint() {
119+ let private = new_vapid_private();
120+ let key_pair = vapid_key_pair(&private).expect("key");
121+ let browser = p256::SecretKey::from_slice(&new_vapid_private()).expect("scalar");
122+ let point = browser
123+ .public_key()
124+ .to_encoded_point(false)
125+ .as_bytes()
126+ .to_vec();
127+ let auth = [9u8; 16];
128+ let endpoint = "https://push.example.test/send/abc";
129+ let payload = br#"{"title":"tahinli/forge#1"}"#.to_vec();
130+ let request = push_request(
131+ endpoint,
132+ &point,
133+ &auth,
134+ "mailto:tahinli@example.test",
135+ &key_pair,
136+ payload.clone(),
137+ )
138+ .expect("request");
139+
140+ assert_eq!(request.method(), http::Method::POST);
141+ assert_eq!(request.uri().to_string(), endpoint);
142+ assert_eq!(request.headers()["content-encoding"], "aes128gcm");
143+ assert_eq!(request.headers()["ttl"], "43200");
144+
145+ // The VAPID header names the push service's origin and carries the instance's public key.
146+ let auth_header = request.headers()["authorization"]
147+ .to_str()
148+ .expect("ascii")
149+ .to_owned();
150+ assert!(auth_header.starts_with("vapid "), "{auth_header}");
151+ assert!(auth_header.contains(&format!(
152+ "k={}",
153+ vapid_public_key(&private).expect("public")
154+ )));
155+ let token = auth_header
156+ .split("t=")
157+ .nth(1)
158+ .and_then(|rest| rest.split(',').next())
159+ .expect("token");
160+ let claims = token.split('.').nth(1).expect("claims");
161+ let claims = decode_b64(claims).expect("base64");
162+ let claims: serde_json::Value = serde_json::from_slice(&claims).expect("json");
163+ assert_eq!(claims["aud"], "https://push.example.test");
164+ assert_eq!(claims["sub"], "mailto:tahinli@example.test");
165+
166+ // The body is encrypted: it is longer than the plaintext and does not contain it.
167+ let body = request.body();
168+ assert!(body.len() > payload.len());
169+ assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice()));
170+ }
171+
172+ #[test]
173+ fn the_public_key_is_the_uncompressed_point() {
174+ let public = vapid_public_key(&new_vapid_private()).expect("public");
175+ assert_eq!(decode_b64(&public).expect("b64").len(), POINT_LEN);
176+ }
177+}
crates/forge-web/src/web_push/mod.rsadded+567 -0
@@ -0,0 +1,567 @@
1+//! Web Push: a notification for the inbox also reaches the user's devices when no tab is open. A
2+//! browser (or an installed app) subscribes through the service worker, the server keeps the
3+//! subscription, and [`queue`] sends the message to every device of a user.
4+//!
5+//! Delivery never blocks the caller: [`queue`] spawns the work, which looks up the user's devices,
6+//! encrypts the message per device (RFC 8291), signs the request with the instance's VAPID key
7+//! (RFC 8292) and posts it to the push service. A device the service reports gone (404 or 410) is
8+//! removed. Every change to a user's devices is announced on [`PushLive`], so an open settings page
9+//! refreshes through its event stream.
10+
11+pub mod crypto;
12+
13+use std::sync::OnceLock;
14+use std::time::Duration;
15+
16+use serde::Serialize;
17+use tokio::sync::broadcast;
18+
19+use forge_core::store::web_push::PushSubscription;
20+use forge_core::{Error, Result};
21+
22+use crate::i18n::{self, Lang, misc, push as text};
23+use crate::state::AppState;
24+
25+/// How long one push request may take before it counts as failed.
26+const SEND_TIMEOUT: Duration = Duration::from_secs(15);
27+/// Longest body text in a notification, in characters.
28+const BODY_CHARS: usize = 140;
29+
30+/// Announces changes to a user's devices to the settings pages that show them. Only the event
31+/// stream reads it; nothing here is stored, and a second server process would not see it.
32+pub struct PushLive {
33+ tx: broadcast::Sender<String>,
34+}
35+
36+impl Default for PushLive {
37+ fn default() -> Self {
38+ Self {
39+ tx: broadcast::channel(64).0,
40+ }
41+ }
42+}
43+
44+impl PushLive {
45+ /// Says that the devices of `user_id` changed. Nobody listening is fine.
46+ pub fn publish(&self, user_id: &str) {
47+ let _ = self.tx.send(user_id.to_owned());
48+ }
49+
50+ /// A receiver for every change, from every user. A stream filters for its own user.
51+ pub fn subscribe(&self) -> broadcast::Receiver<String> {
52+ self.tx.subscribe()
53+ }
54+}
55+
56+/// What a notification says. Built per recipient, in the recipient's language.
57+#[derive(Clone)]
58+pub enum Alert {
59+ /// Activity on an issue or pull request the user hears about.
60+ Activity {
61+ /// `owner/repo`.
62+ repo: String,
63+ number: i64,
64+ title: String,
65+ /// The verb of the activity (`misc::K::VerbOpened` and so on).
66+ verb: misc::K,
67+ actor: Option<String>,
68+ /// The relative link the notification opens.
69+ url: String,
70+ /// The thread id. A newer notification for the same thread replaces the older one.
71+ thread: String,
72+ },
73+ /// New security advisory alerts on a repo.
74+ Advisories {
75+ repo: String,
76+ count: u64,
77+ url: String,
78+ },
79+ /// A site admin alert.
80+ Admin { subject: String, detail: String },
81+ /// The test button.
82+ Test,
83+}
84+
85+/// The JSON the service worker reads. Small, and nothing in it is a secret.
86+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
87+pub struct Message {
88+ pub title: String,
89+ pub body: String,
90+ /// A relative link on this origin.
91+ pub url: String,
92+ /// Notifications with the same tag replace each other on the device.
93+ pub tag: String,
94+}
95+
96+impl Alert {
97+ /// The message for a recipient who reads `lang`.
98+ pub fn message(&self, lang: Lang) -> Message {
99+ match self {
100+ Alert::Activity {
101+ repo,
102+ number,
103+ title,
104+ verb,
105+ actor,
106+ url,
107+ thread,
108+ } => {
109+ let line = misc::activity_line(lang, *verb, actor.as_deref());
110+ Message {
111+ title: format!("{repo}#{number}"),
112+ body: clip(&format!("{line}: {title}")),
113+ url: safe_url(url),
114+ tag: format!("thread-{thread}"),
115+ }
116+ }
117+ Alert::Advisories { repo, count, url } => Message {
118+ title: clip(repo),
119+ body: text::advisory_alerts(lang, *count),
120+ url: safe_url(url),
121+ tag: format!("advisories-{repo}"),
122+ },
123+ Alert::Admin { subject, detail } => Message {
124+ title: clip(subject),
125+ body: clip(detail),
126+ url: "/notifications".to_owned(),
127+ tag: "admin-alert".to_owned(),
128+ },
129+ Alert::Test => Message {
130+ title: text::t(lang, text::K::TestTitle).to_owned(),
131+ body: text::t(lang, text::K::TestBody).to_owned(),
132+ url: "/settings/notifications".to_owned(),
133+ tag: "test".to_owned(),
134+ },
135+ }
136+ }
137+}
138+
139+/// Shortens text to the body limit, in characters, one line.
140+fn clip(text: &str) -> String {
141+ let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
142+ if one_line.chars().count() <= BODY_CHARS {
143+ return one_line;
144+ }
145+ let mut short: String = one_line.chars().take(BODY_CHARS - 3).collect();
146+ short.push_str("...");
147+ short
148+}
149+
150+/// A relative link only. The service worker opens it on this origin, so anything that could leave
151+/// the origin (a scheme, a protocol-relative `//host`) falls back to the notifications page.
152+pub fn safe_url(url: &str) -> String {
153+ if url.starts_with('/') && !url.starts_with("//") && !url.contains('\\') {
154+ url.to_owned()
155+ } else {
156+ "/notifications".to_owned()
157+ }
158+}
159+
160+/// A short label for a device, from its User-Agent: "Chrome on Android", "Safari on iPhone".
161+pub fn agent_label(user_agent: &str) -> String {
162+ let os = if user_agent.contains("iPhone") {
163+ "iPhone"
164+ } else if user_agent.contains("iPad") {
165+ "iPad"
166+ } else if user_agent.contains("Android") {
167+ "Android"
168+ } else if user_agent.contains("Windows") {
169+ "Windows"
170+ } else if user_agent.contains("Macintosh") {
171+ "Mac"
172+ } else if user_agent.contains("CrOS") {
173+ "ChromeOS"
174+ } else if user_agent.contains("Linux") {
175+ "Linux"
176+ } else {
177+ "Unknown system"
178+ };
179+ let browser = if user_agent.contains("Edg/") {
180+ "Edge"
181+ } else if user_agent.contains("OPR/") {
182+ "Opera"
183+ } else if user_agent.contains("Firefox/") {
184+ "Firefox"
185+ } else if user_agent.contains("Chrome/") || user_agent.contains("Chromium/") {
186+ "Chrome"
187+ } else if user_agent.contains("Safari/") {
188+ "Safari"
189+ } else {
190+ "Browser"
191+ };
192+ format!("{browser} on {os}")
193+}
194+
195+/// The shared HTTP client for push requests. Built once; redirects are not followed, since a push
196+/// service answers on the endpoint itself.
197+fn client() -> &'static reqwest::Client {
198+ static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
199+ CLIENT.get_or_init(|| {
200+ reqwest::Client::builder()
201+ .timeout(SEND_TIMEOUT)
202+ .redirect(reqwest::redirect::Policy::none())
203+ .user_agent("forge-web-push")
204+ .build()
205+ .expect("the push client builds with the default TLS settings")
206+ })
207+}
208+
209+/// The instance's VAPID key pair. The private key is stored sealed with the instance key; the
210+/// first call creates the pair.
211+pub struct VapidKeys {
212+ pub private: [u8; 32],
213+ /// The public key, base64url. The browser subscribes with it.
214+ pub public: String,
215+}
216+
217+/// The VAPID keys of this instance, creating and storing them on first use.
218+pub async fn vapid_keys(state: &AppState) -> Result<VapidKeys> {
219+ let (public, sealed) = match state.store.web_push_keys().await? {
220+ Some(pair) => pair,
221+ None => {
222+ let private = crypto::new_vapid_private();
223+ let public = crypto::vapid_public_key(&private)?;
224+ let sealed = forge_core::secret::seal(&state.key, &private)?;
225+ state.store.save_web_push_keys(&public, &sealed).await?
226+ }
227+ };
228+ let opened = forge_core::secret::open(&state.key, &sealed)?;
229+ let private: [u8; 32] = opened
230+ .try_into()
231+ .map_err(|_| Error::Crypto("the stored VAPID key has the wrong length".into()))?;
232+ Ok(VapidKeys { private, public })
233+}
234+
235+/// The contact the push service may use about this instance: the base URL when it is https.
236+fn subject(base_url: &str) -> String {
237+ let base = base_url.trim_end_matches('/');
238+ if base.starts_with("https://") {
239+ base.to_owned()
240+ } else {
241+ "https://localhost".to_owned()
242+ }
243+}
244+
245+/// What the push service answered for one device.
246+#[derive(Debug, PartialEq, Eq)]
247+pub enum Outcome {
248+ Delivered,
249+ /// 404 or 410: the subscription is gone and the device must be forgotten.
250+ Gone,
251+ Failed(String),
252+}
253+
254+/// Encrypts `payload` for one device and posts it to the device's push service.
255+pub async fn send_one(
256+ keys: &VapidKeys,
257+ subject: &str,
258+ sub: &PushSubscription,
259+ payload: &[u8],
260+) -> Outcome {
261+ let built = (|| {
262+ let p256dh = crypto::decode_b64(&sub.p256dh)?;
263+ let auth = crypto::decode_b64(&sub.auth)?;
264+ let key_pair = crypto::vapid_key_pair(&keys.private)?;
265+ crypto::push_request(
266+ &sub.endpoint,
267+ &p256dh,
268+ &auth,
269+ subject,
270+ &key_pair,
271+ payload.to_vec(),
272+ )
273+ })();
274+ let request = match built {
275+ Ok(request) => request,
276+ Err(e) => return Outcome::Failed(e.to_string()),
277+ };
278+ let request = match reqwest::Request::try_from(request) {
279+ Ok(request) => request,
280+ Err(e) => return Outcome::Failed(e.to_string()),
281+ };
282+ match client().execute(request).await {
283+ Ok(res) => match res.status().as_u16() {
284+ 200..=299 => Outcome::Delivered,
285+ 404 | 410 => Outcome::Gone,
286+ status => Outcome::Failed(format!("the push service answered {status}")),
287+ },
288+ Err(e) => Outcome::Failed(e.to_string()),
289+ }
290+}
291+
292+/// Queues `alert` for every device of `user_id`. Returns at once: the work runs on a spawned task.
293+pub fn queue(state: &AppState, user_id: &str, alert: Alert) {
294+ let state = state.clone();
295+ let user_id = user_id.to_owned();
296+ tokio::spawn(async move {
297+ if let Err(e) = deliver(&state, &user_id, &alert).await {
298+ tracing::error!(error = %e, user_id, "web push: delivery failed");
299+ }
300+ });
301+}
302+
303+/// Sends `alert` to every device of `user_id` now and returns how many devices there are. Devices
304+/// the push service reports gone are removed. [`queue`] is the caller's entry point.
305+pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<usize> {
306+ let devices = state.store.push_subscriptions(user_id).await?;
307+ if devices.is_empty() {
308+ return Ok(0);
309+ }
310+ let lang = match state.store.user_by_id(user_id).await? {
311+ Some(user) => i18n::resolve(Some(user.language.as_str()), &http::HeaderMap::new()),
312+ None => Lang::En,
313+ };
314+ let payload = serde_json::to_vec(&alert.message(lang))
315+ .map_err(|e| Error::Invalid(format!("the push payload does not encode: {e}")))?;
316+ let keys = vapid_keys(state).await?;
317+ let subject = subject(&state.live().base_url);
318+ for device in &devices {
319+ match send_one(&keys, &subject, device, &payload).await {
320+ Outcome::Delivered => {
321+ state.store.mark_push_delivered(&device.id).await?;
322+ state.push_live.publish(user_id);
323+ }
324+ Outcome::Gone => {
325+ state.store.delete_push_endpoint(&device.endpoint).await?;
326+ state.push_live.publish(user_id);
327+ }
328+ Outcome::Failed(reason) => {
329+ tracing::warn!(reason, device = %device.id, "web push: a device was not reached");
330+ }
331+ }
332+ }
333+ Ok(devices.len())
334+}
335+
336+#[cfg(test)]
337+mod tests {
338+ use super::*;
339+ use web_push_native::p256::elliptic_curve::sec1::ToEncodedPoint;
340+
341+ fn activity(actor: Option<&str>) -> Alert {
342+ Alert::Activity {
343+ repo: "tahinli/forge".into(),
344+ number: 42,
345+ title: "Crash on startup\nwhen the cache is cold".into(),
346+ verb: misc::K::VerbCommented,
347+ actor: actor.map(str::to_owned),
348+ url: "/tahinli/forge/issues/42".into(),
349+ thread: "issue-1".into(),
350+ }
351+ }
352+
353+ #[test]
354+ fn an_activity_payload_is_short_and_names_the_thread() {
355+ let msg = activity(Some("tahinli")).message(Lang::En);
356+ assert_eq!(msg.title, "tahinli/forge#42");
357+ assert_eq!(
358+ msg.body,
359+ "commented by tahinli: Crash on startup when the cache is cold"
360+ );
361+ assert_eq!(msg.url, "/tahinli/forge/issues/42");
362+ assert_eq!(msg.tag, "thread-issue-1");
363+ }
364+
365+ #[test]
366+ fn the_body_is_clipped_to_the_limit() {
367+ let long = Alert::Admin {
368+ subject: "Backup".into(),
369+ detail: "x".repeat(400),
370+ };
371+ let msg = long.message(Lang::En);
372+ assert_eq!(msg.body.chars().count(), BODY_CHARS);
373+ assert!(msg.body.ends_with("..."));
374+ }
375+
376+ #[test]
377+ fn the_payload_follows_the_recipient_language() {
378+ let msg = activity(None).message(Lang::Tr);
379+ assert!(msg.body.starts_with("Yorumlandı"), "{}", msg.body);
380+ let advisories = Alert::Advisories {
381+ repo: "tahinli/forge".into(),
382+ count: 3,
383+ url: "/tahinli/forge/security".into(),
384+ };
385+ assert_eq!(advisories.message(Lang::En).body, "3 new security alerts");
386+ assert_eq!(advisories.message(Lang::Tr).body, "3 yeni güvenlik uyarısı");
387+ }
388+
389+ #[test]
390+ fn a_link_must_stay_on_this_origin() {
391+ assert_eq!(safe_url("/tahinli/forge"), "/tahinli/forge");
392+ assert_eq!(safe_url("https://evil.example/x"), "/notifications");
393+ assert_eq!(safe_url("//evil.example/x"), "/notifications");
394+ assert_eq!(safe_url("/\\evil.example"), "/notifications");
395+ }
396+
397+ #[test]
398+ fn device_labels_name_the_browser_and_the_system() {
399+ let chrome_android = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36";
400+ assert_eq!(agent_label(chrome_android), "Chrome on Android");
401+ let safari_iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1";
402+ assert_eq!(agent_label(safari_iphone), "Safari on iPhone");
403+ assert_eq!(agent_label("curl/8.0"), "Browser on Unknown system");
404+ }
405+
406+ #[test]
407+ fn the_subject_is_https_or_the_fallback() {
408+ assert_eq!(
409+ subject("https://forge.example.test/"),
410+ "https://forge.example.test"
411+ );
412+ assert_eq!(subject("http://127.0.0.1:7660"), "https://localhost");
413+ }
414+
415+ #[test]
416+ fn push_live_reaches_a_listener_and_tolerates_none() {
417+ let live = PushLive::default();
418+ live.publish("nobody");
419+ let mut rx = live.subscribe();
420+ live.publish("tahinli");
421+ assert_eq!(rx.try_recv().expect("event"), "tahinli");
422+ }
423+
424+ /// A local stand-in for a push service: `/gone` answers 410, `/ok` answers 201, and each
425+ /// request is read in full (headers and body) before it is answered.
426+ async fn mock_push_service() -> std::net::SocketAddr {
427+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
428+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
429+ .await
430+ .expect("bind");
431+ let addr = listener.local_addr().expect("addr");
432+ tokio::spawn(async move {
433+ loop {
434+ let Ok((mut socket, _)) = listener.accept().await else {
435+ return;
436+ };
437+ tokio::spawn(async move {
438+ let mut buf = Vec::new();
439+ let mut chunk = [0u8; 4096];
440+ let (head_end, length) = loop {
441+ let n = socket.read(&mut chunk).await.unwrap_or(0);
442+ if n == 0 {
443+ return;
444+ }
445+ buf.extend_from_slice(&chunk[..n]);
446+ if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
447+ let head = String::from_utf8_lossy(&buf[..end]).to_ascii_lowercase();
448+ let length = head
449+ .lines()
450+ .find_map(|l| l.strip_prefix("content-length:"))
451+ .and_then(|v| v.trim().parse::<usize>().ok())
452+ .unwrap_or(0);
453+ break (end + 4, length);
454+ }
455+ };
456+ while buf.len() < head_end + length {
457+ let n = socket.read(&mut chunk).await.unwrap_or(0);
458+ if n == 0 {
459+ break;
460+ }
461+ buf.extend_from_slice(&chunk[..n]);
462+ }
463+ let request = String::from_utf8_lossy(&buf[..head_end]).into_owned();
464+ let status = if request.starts_with("POST /gone") {
465+ "410 Gone"
466+ } else {
467+ "201 Created"
468+ };
469+ let reply = format!(
470+ "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
471+ );
472+ let _ = socket.write_all(reply.as_bytes()).await;
473+ });
474+ }
475+ });
476+ addr
477+ }
478+
479+ fn device(endpoint: String) -> PushSubscription {
480+ let secret = web_push_native::p256::SecretKey::from_slice(&crypto::new_vapid_private())
481+ .expect("scalar");
482+ let point = secret.public_key().to_encoded_point(false);
483+ PushSubscription {
484+ id: endpoint.clone(),
485+ user_id: String::new(),
486+ endpoint,
487+ p256dh: crypto::encode_b64(point.as_bytes()),
488+ auth: crypto::encode_b64(&[9u8; 16]),
489+ agent_label: "Chrome on Linux".into(),
490+ created_at: String::new(),
491+ last_success_at: None,
492+ }
493+ }
494+
495+ #[tokio::test]
496+ async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() {
497+ let dir = tempfile::tempdir().expect("tempdir");
498+ let state = crate::test_support::test_state(dir.path()).await;
499+ let user = state
500+ .store
501+ .create_user("tahinli", None, "h", false)
502+ .await
503+ .expect("user");
504+ let addr = mock_push_service().await;
505+ let gone = format!("http://{addr}/gone");
506+ let ok = format!("http://{addr}/ok");
507+ state
508+ .store
509+ .save_push_subscription(
510+ &user.id,
511+ &gone,
512+ &device(gone.clone()).p256dh,
513+ &device(gone.clone()).auth,
514+ "Chrome on Linux",
515+ )
516+ .await
517+ .expect("save gone");
518+ state
519+ .store
520+ .save_push_subscription(
521+ &user.id,
522+ &ok,
523+ &device(ok.clone()).p256dh,
524+ &device(ok.clone()).auth,
525+ "Chrome on Linux",
526+ )
527+ .await
528+ .expect("save ok");
529+
530+ let sent = deliver(&state, &user.id, &Alert::Test)
531+ .await
532+ .expect("deliver");
533+ assert_eq!(sent, 2);
534+ let left = state
535+ .store
536+ .push_subscriptions(&user.id)
537+ .await
538+ .expect("list");
539+ assert_eq!(left.len(), 1, "the 410 device is forgotten");
540+ assert_eq!(left[0].endpoint, ok);
541+ assert!(
542+ left[0].last_success_at.is_some(),
543+ "the delivered device is stamped"
544+ );
545+ }
546+
547+ #[tokio::test]
548+ async fn the_payload_is_encrypted_for_the_device_and_the_status_is_read() {
549+ let addr = mock_push_service().await;
550+ let private = crypto::new_vapid_private();
551+ let keys = VapidKeys {
552+ public: crypto::vapid_public_key(&private).expect("public"),
553+ private,
554+ };
555+ let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json");
556+ let ok = device(format!("http://{addr}/ok"));
557+ assert_eq!(
558+ send_one(&keys, "https://localhost", &ok, &payload).await,
559+ Outcome::Delivered
560+ );
561+ let gone = device(format!("http://{addr}/gone"));
562+ assert_eq!(
563+ send_one(&keys, "https://localhost", &gone, &payload).await,
564+ Outcome::Gone
565+ );
566+ }
567+}
docs/notifications.mdadded+65 -0
@@ -0,0 +1,65 @@
1+# Notifications
2+
3+Forge keeps an inbox of notifications for each user (the bell in the top bar). The same
4+notifications can also reach you by email, and by Web Push on your devices.
5+
6+## Web Push
7+
8+Web Push delivers a notification to a device even when no Forge tab is open. It works in
9+Chromium-based browsers, Firefox and Safari, on desktop and on Android. On iPhone and iPad it works
10+only for an app installed to the Home Screen.
11+
12+### Requirements
13+
14+- **HTTPS.** Browsers only offer push on a secure origin. Serve Forge over HTTPS (the usual
15+ reverse-proxy setup). `localhost` also counts as secure for testing.
16+- **iOS and iPadOS.** Open Forge in Safari, use Share, then Add to Home Screen, and open Forge from
17+ that icon. Then turn push on in the notification settings. Safari in a normal tab cannot receive
18+ push. iOS 16.4 or later is needed.
19+- **Permission.** The browser asks for permission the first time you turn push on. If you refused,
20+ allow notifications for the site in the browser's site settings and try again.
21+
22+### Turning it on
23+
24+1. Open **Settings, Notifications**.
25+2. Under **Push notifications on this device**, choose **Turn on for this device**, then allow
26+ notifications when the browser asks.
27+3. Choose **Send test notification** to check that the device gets one.
28+
29+Each browser profile, and each installed app, is a separate device. The **Devices** list shows
30+every device with push on, when it was added and when it last received a notification. Remove a
31+device there to stop its notifications; **Turn off for this device** does the same for the device
32+you are using.
33+
34+### What is sent
35+
36+A notification carries a short title (for example `owner/repo#12`), a one-line body (the activity
37+and the start of the title, at most 140 characters) and the link it opens. Nothing else is sent: no
38+token, no email address and no body text. The push service sees that a message was delivered to
39+your device, as with any push service.
40+
41+Only notifications that reach your inbox are pushed. The same rules apply: you hear about activity
42+on threads you follow, when you are mentioned, assigned or asked to review, and so on. Watching a
43+repo or ignoring a thread changes what reaches your inbox, and so what is pushed. Security alerts
44+and site admin alerts are pushed the same way.
45+
46+Notifications on a lock screen can show the title of a private repository. Turn push off for a
47+device you share.
48+
49+### Devices that stop working
50+
51+A push service answers `404` or `410` for a subscription that no longer exists, for example after
52+the browser was reset or the app was uninstalled. Forge removes such a device by itself. A device
53+that keeps failing is kept, so a temporary outage does not drop it.
54+
55+### Operator notes
56+
57+- Forge creates one VAPID key pair the first time push is used and stores it in the database. The
58+ private key is sealed with the instance key (`data_dir/forge.key`). Keep both in your backups: a
59+ restore that loses the VAPID key makes every device subscribe again.
60+- The VAPID contact is the `base_url` of the instance when it is an `https` URL. Behind plain HTTP
61+ the contact falls back to `https://localhost`.
62+- Pushes go out from a background task and never delay the request that caused them. The server
63+ makes outgoing requests to the push services, so it needs outbound HTTPS.
64+- Each account can turn push on for at most 20 devices.
65+- The service worker is served at `/sw.js`, the web app manifest at `/manifest.webmanifest`.
style/main.scssmodified+49 -0
@@ -1630,6 +1630,55 @@ code {
1630 }1630 }
1631 }1631 }
1632 1632
1633+// Settings > Notifications: the Web Push card. Devices are a plain list, one row per device, that
1634+// stacks on a phone and keeps the remove button at the row's end on wider screens.
1635+.push-card {
1636+ display: flex;
1637+ flex-direction: column;
1638+ gap: 12px;
1639+
1640+ h2 {
1641+ margin: 0;
1642+ }
1643+
1644+ .actions {
1645+ margin-top: 0;
1646+ }
1647+}
1648+
1649+.push-devices {
1650+ list-style: none;
1651+ margin: 0;
1652+ padding: 0;
1653+ display: flex;
1654+ flex-direction: column;
1655+ gap: 8px;
1656+}
1657+
1658+.push-device {
1659+ display: flex;
1660+ flex-wrap: wrap;
1661+ align-items: center;
1662+ justify-content: space-between;
1663+ gap: 8px 12px;
1664+ padding: 10px 12px;
1665+ border: 1px solid var(--border);
1666+ border-radius: var(--radius-lg);
1667+ min-width: 0;
1668+
1669+ > div {
1670+ display: flex;
1671+ flex-direction: column;
1672+ gap: 2px;
1673+ min-width: 0;
1674+ overflow-wrap: anywhere;
1675+ }
1676+}
1677+
1678+.push-remove {
1679+ margin: 0;
1680+}
1681+
1633 // Settings > Notifications: the checkbox with its helper, then the notes saying why it is locked.1682 // Settings > Notifications: the checkbox with its helper, then the notes saying why it is locked.
1634 // One 12px rhythm between the field, each note and the no-JS actions; helper text and notes share1683 // One 12px rhythm between the field, each note and the no-JS actions; helper text and notes share
1635 // one size.1684 // one size.