Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Web Push: notify the installed app when it's closed
Lin (kwant bot)e3ec91b76e89
diff --git a/README.md b/README.mdindex d06bcecd..db38bf03 100644--- a/README.md+++ b/README.md@@ -94,6 +94,8 @@ The app is signed ad hoc, not notarized by Apple, so macOS stops it the first tiIn Chrome or Edge, click **Install app** in the sidebar; in Safari on a Mac, **File → Add to Dock**; on a phone, kwant shows how. Browsers only install pages served over https or from `127.0.0.1`.+To get notifications on your phone with kwant closed, install it (on an iPhone, add it to the Home Screen first) and turn on **Settings → Notifications → Notify me on this device**. kwant then sends a Web Push notification for each kind you've ticked there, such as an approval or a question. It goes through your browser's push service (Google's for Chrome on Android, Apple's on an iPhone), encrypted so that service can't read it. Signing a browser out under **Signed-in devices** stops its notifications.+More in the [quickstart](https://kwant.si/docs/quickstart) and [install](https://kwant.si/docs/install) docs.---diff --git a/site-src/docs-routines.html b/site-src/docs-routines.htmlindex efd8bf20..dea10b8a 100644--- a/site-src/docs-routines.html+++ b/site-src/docs-routines.html@@ -69,4 +69,4 @@ card_art: avatar:devops<figure><div class="frame">{{shot:v2-away|While you were away, with a question waiting for an answer, two finished items and two failed or stuck ones.|(max-width: 860px) 100vw, 760px}}</div></figure>-<p>For a ping when something needs you, turn on browser notifications or add an HTTPS webhook such as ntfy in settings. Webhook messages carry only a title and one line.</p>+<p>For a ping when something needs you, turn on <strong>Notify me on this device</strong> in settings, or add an HTTPS webhook such as ntfy. On a phone, install kwant first (on an iPhone, add it to the Home Screen); notifications then arrive even with the app closed. They go through your browser's push service (Google's or Apple's), encrypted so it can't read them. Webhook messages carry only a title and one line.</p>diff --git a/site-src/privacy.html b/site-src/privacy.htmlindex 40c21e7f..070f3977 100644--- a/site-src/privacy.html+++ b/site-src/privacy.html@@ -39,7 +39,7 @@ card: No cookies, no analytics, no telemetry. Your kwant data stays on your mach<li><strong>MCP servers and connectors</strong> you add, such as <a href="https://composio.dev/privacy" rel="noopener">Composio</a>, Notion, Linear or GitHub. Bots can also search the public <a href="https://registry.modelcontextprotocol.io" rel="noopener">MCP Registry</a> by name to suggest a server; nothing is installed without you.</li><li><strong>Loose ends sources</strong> you turn on: your email server (IMAP, read-only) and the GitHub API.</li><li><strong>Passwords:</strong> <a href="https://bitwarden.com/privacy/" rel="noopener">Bitwarden</a>, if you connect a vault.</li>- <li><strong>Phone notifications:</strong> <a href="https://docs.ntfy.sh/privacy/" rel="noopener">ntfy</a> or the server you set, if you turn them on.</li>+ <li><strong>Phone notifications:</strong> <a href="https://docs.ntfy.sh/privacy/" rel="noopener">ntfy</a> or the server you set, if you add a webhook; and your browser's push service (Google, Apple or Mozilla), if you turn on notifications on a device. The push service relays them encrypted and can't read them.</li><li><strong>Websites your bots visit</strong> with the bot browser or web search. Those sites see a normal browser visit from your computer or server.</li></ul>diff --git a/site/docs/routines.html b/site/docs/routines.htmlindex 7f71970d..3fcc4bf5 100644--- a/site/docs/routines.html+++ b/site/docs/routines.html@@ -20,7 +20,7 @@<meta property="og:image:height" content="630"><meta property="og:image:alt" content="Routines & bot actions: Schedule work, let bots set things up with an Undo, and decide who hires."><meta property="article:published_time" content="2026-10-22">-<meta property="article:modified_time" content="2026-10-24">+<meta property="article:modified_time" content="2026-10-25"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Scheduled AI agents: routines & cron · kwant"><meta name="twitter:description" content="Schedule bot work with routines, cron rules and follow-ups that run on your own machine, with an Undo on every change bots make.">@@ -118,7 +118,7 @@<figure><div class="frame"><a class="zoom" href="../assets/media/v2-away-2880.webp?v=a14d8f3178" data-caption="While you were away, with a question waiting for an answer, two finished items and two failed or stuck ones."><img src="../assets/media/v2-away-1440.webp?v=fce9c3cdb1" srcset="../assets/media/v2-away-1440.webp?v=fce9c3cdb1 1440w, ../assets/media/v2-away-2880.webp?v=a14d8f3178 2880w" sizes="(max-width: 860px) 100vw, 760px" width="1440" height="900" loading="lazy" decoding="async" alt="While you were away, with a question waiting for an answer, two finished items and two failed or stuck ones."></a></div></figure>-<p>For a ping when something needs you, turn on browser notifications or add an HTTPS webhook such as ntfy in settings. Webhook messages carry only a title and one line.</p>+<p>For a ping when something needs you, turn on <strong>Notify me on this device</strong> in settings, or add an HTTPS webhook such as ntfy. On a phone, install kwant first (on an iPhone, add it to the Home Screen); notifications then arrive even with the app closed. They go through your browser's push service (Google's or Apple's), encrypted so it can't read them. Webhook messages carry only a title and one line.</p><nav class="pager" aria-label="Docs pages"><a class="prev" href="../docs/approvals.html"><small>Previous</small>Approvals & passwords</a><a class="next" href="../docs/memory-skills.html"><small>Next</small>Memory, skills & search</a></nav></article>@@ -161,6 +161,6 @@</footer><script src="../assets/js/site.js?v=c490c973ba" defer></script><script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>-<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/routines#article","headline":"Scheduled AI agents: routines & cron","description":"Schedule bot work with routines, cron rules and follow-ups that run on your own machine, with an Undo on every change bots make.","url":"https://kwant.si/docs/routines","mainEntityOfPage":"https://kwant.si/docs/routines","image":"https://kwant.si/assets/og/docs-routines.png?v=7be758aed4","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-10-24","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Routines & bot actions","item":"https://kwant.si/docs/routines"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>+<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/routines#article","headline":"Scheduled AI agents: routines & cron","description":"Schedule bot work with routines, cron rules and follow-ups that run on your own machine, with an Undo on every change bots make.","url":"https://kwant.si/docs/routines","mainEntityOfPage":"https://kwant.si/docs/routines","image":"https://kwant.si/assets/og/docs-routines.png?v=7be758aed4","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-10-25","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Routines & bot actions","item":"https://kwant.si/docs/routines"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script></body></html>diff --git a/site/privacy.html b/site/privacy.htmlindex 0a2c74d5..20aa68b3 100644--- a/site/privacy.html+++ b/site/privacy.html@@ -79,7 +79,7 @@<li><strong>MCP servers and connectors</strong> you add, such as <a href="https://composio.dev/privacy" rel="noopener">Composio</a>, Notion, Linear or GitHub. Bots can also search the public <a href="https://registry.modelcontextprotocol.io" rel="noopener">MCP Registry</a> by name to suggest a server; nothing is installed without you.</li><li><strong>Loose ends sources</strong> you turn on: your email server (IMAP, read-only) and the GitHub API.</li><li><strong>Passwords:</strong> <a href="https://bitwarden.com/privacy/" rel="noopener">Bitwarden</a>, if you connect a vault.</li>- <li><strong>Phone notifications:</strong> <a href="https://docs.ntfy.sh/privacy/" rel="noopener">ntfy</a> or the server you set, if you turn them on.</li>+ <li><strong>Phone notifications:</strong> <a href="https://docs.ntfy.sh/privacy/" rel="noopener">ntfy</a> or the server you set, if you add a webhook; and your browser's push service (Google, Apple or Mozilla), if you turn on notifications on a device. The push service relays them encrypted and can't read them.</li><li><strong>Websites your bots visit</strong> with the bot browser or web search. Those sites see a normal browser visit from your computer or server.</li></ul>diff --git a/site/sitemap.xml b/site/sitemap.xmlindex 0006f5b0..2a048d50 100644--- a/site/sitemap.xml+++ b/site/sitemap.xml@@ -11,7 +11,7 @@<url><loc>https://kwant.si/docs/models</loc><lastmod>2026-10-24</lastmod></url><url><loc>https://kwant.si/docs/parallel-universe</loc><lastmod>2026-10-22</lastmod></url><url><loc>https://kwant.si/docs/quickstart</loc><lastmod>2026-10-22</lastmod></url>- <url><loc>https://kwant.si/docs/routines</loc><lastmod>2026-10-24</lastmod></url>+ <url><loc>https://kwant.si/docs/routines</loc><lastmod>2026-10-25</lastmod></url><url><loc>https://kwant.si/docs/spaces</loc><lastmod>2026-10-24</lastmod></url><url><loc>https://kwant.si/features</loc><lastmod>2026-10-25</lastmod></url><url><loc>https://kwant.si/</loc><lastmod>2026-10-25</lastmod></url>diff --git a/src/server/auth.rs b/src/server/auth.rsindex d8ca3df2..289e6577 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -328,6 +328,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {["", "api", "setup", ..] => true,// Sign-in links, device approvals and sessions: who else may sign in as the person["", "api", "signin", ..] => true,+ // Web Push: where the person's notifications go+ ["", "api", "push", ..] => true,["", "api", "approvals", _, "resolve"] => *method == Method::POST,["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,["", "api", "kwants" | "teams", _] => *method == Method::DELETE,@@ -582,6 +584,9 @@ pub async fn create_session(/// `DELETE /api/auth/session`: ends this browser's session and clears the cookie.pub async fn delete_session(State(state): State<AppState>, headers: HeaderMap) -> Response {if let Some(secret) = cookie_token(&headers) {+ if let Some(id) = state.api_token.signin.session_id(secret) {+ state.push.drop_session(&id);+ }state.api_token.signin.revoke_secret(secret);}let mut resp = StatusCode::NO_CONTENT.into_response();@@ -726,6 +731,8 @@ pub async fn sessions(State(state): State<AppState>, headers: HeaderMap) -> Resp/// `DELETE /api/signin/sessions/:id` (person only): signs that browser out. 404 when unknown.pub async fn revoke_session(State(state): State<AppState>, axum::extract::Path(id): axum::extract::Path<String>) -> Response {+ // A signed-out phone stops getting notifications too+ state.push.drop_session(&id);if state.api_token.signin.revoke(&id) {StatusCode::NO_CONTENT.into_response()} else {@@ -822,6 +829,9 @@ mod tests {assert!(person_only(&get, "/api/setup/status"));assert!(person_only(&post, "/api/setup/install"));assert!(person_only(&get, "/api/setup/jobs/setup-1"));+ assert!(person_only(&get, "/api/push/key"));+ assert!(person_only(&post, "/api/push/subscribe"));+ assert!(person_only(&post, "/api/push/unsubscribe"));assert!(person_only(&post, "/api/connections/composio"));assert!(person_only(&get, "/api/parallel/prices"));assert!(person_only(&post, "/api/parallel/scenarios"));diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 98f61648..c8979e84 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -1234,7 +1234,7 @@ pub struct Notification {pub body: String,}-/// Sends `n` to the UI and the webhook, if the user wants this kind. The body never holds chat+/// Sends `n` to the UI, the webhook and push subscriptions, if the user wants this kind. The body never holds chat/// text, tool arguments or settings, so nothing secret reaches the phone service.pub async fn notify(state: &AppState, n: Notification) {if !notify_on(state).await.iter().any(|k| k == n.kind) {@@ -1251,6 +1251,11 @@ pub async fn notify(state: &AppState, n: Notification) {Some((id, name, _)) => (Some(id), Some(name)),None => (None, None),};+ if !state.push.subscriptions().is_empty() {+ let payload = super::push::Payload::new(n.kind, &title, &body, space_id.clone(), n.channel_id.clone(), n.kwant_id.clone());+ let push = state.push.clone();+ tokio::spawn(async move { push.send_all(&payload).await });+ }let _ = state.event_sender.send(RuntimeEvent::Notify {kind: n.kind.into(),kwant_id: n.kwant_id,diff --git a/src/server/mod.rs b/src/server/mod.rsindex feb9f016..526f2dce 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -37,6 +37,7 @@ pub mod parallel_routes;pub mod document_routes;pub mod connections;pub mod setup_routes;+pub mod push;use crate::broker::PermissionBroker;use crate::config::Config;@@ -101,6 +102,8 @@ pub struct AppState {pub documents: Arc<crate::documents::extract::Desk>,/// The Setup checklist's install jobs (one at a time).pub setup: Arc<setup_routes::SetupJobs>,+ /// Web Push to the person's installed app: the VAPID key and subscriptions.+ pub push: Arc<push::Push>,}impl AppState {@@ -147,6 +150,7 @@ impl AppState {parallel: Default::default(),documents: Default::default(),setup: Default::default(),+ push: Arc::new(push::Push::load(&config_data_dir)),}}@@ -172,6 +176,9 @@ pub fn create_router(state: AppState) -> Router {.route("/api/signin/requests/deny", post(auth::device_deny)).route("/api/signin/sessions", get(auth::sessions)).route("/api/signin/sessions/:id", delete(auth::revoke_session))+ .route("/api/push/key", get(push::key))+ .route("/api/push/subscribe", post(push::subscribe))+ .route("/api/push/unsubscribe", post(push::unsubscribe)).route("/api/profiles", get(profile_routes::list).post(profile_routes::create)).route("/api/profiles/:id", axum::routing::patch(profile_routes::update).delete(profile_routes::remove)).route("/api/profiles/:id/key", put(profile_routes::set_key).delete(profile_routes::delete_key))diff --git a/src/server/push.rs b/src/server/push.rsnew file mode 100644index 00000000..fe4fd5c9--- /dev/null+++ b/src/server/push.rs@@ -0,0 +1,877 @@+//! Web Push (RFC 8030) to the person's installed app, so a bot that needs them reaches their+//! phone with kwant closed. The browser subscribes with our VAPID public key (RFC 8292) and hands+//! us its push service endpoint; every notification is encrypted for that browser (RFC 8291,+//! aes128gcm), so the push service (Google's, Apple's, Mozilla's) only relays ciphertext.+//!+//! The VAPID key is made on first use and kept in `<data_dir>/vapid_key` (0600, PKCS#8); only+//! its public half ever leaves this machine. Subscriptions live in `<data_dir>/push.json` (0600):+//! an endpoint is a capability URL, so it is never logged beyond its host.+//!+//! Endpoints must be https and resolve to public addresses only, checked again on every send+//! through our own resolver (no proxy), so a subscription can't make kwnt call into its own+//! network. A 404 or 410 from the push service drops the subscription; nothing is retried.++use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;+use base64::Engine;+use chrono::{DateTime, Utc};+use ring::{aead, agreement, hmac, rand::SecureRandom, signature};+use serde::{Deserialize, Serialize};+use std::net::{IpAddr, SocketAddr};+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};+use std::time::Duration;++const KEY_FILE: &str = "vapid_key";+const SUBS_FILE: &str = "push.json";+/// The VAPID `sub` claim: who the push service can write to about our traffic.+const VAPID_SUBJECT: &str = "mailto:[email protected]";+/// VAPID tokens are good for this long (RFC 8292 allows up to 24 hours).+const JWT_SECS: i64 = 12 * 60 * 60;+/// Subscriptions kept at once; a new one past this drops the oldest.+pub const MAX_SUBSCRIPTIONS: usize = 20;+const MAX_ENDPOINT_LEN: usize = 2048;+const MAX_LABEL_CHARS: usize = 200;+/// Longest notification body in a push.+pub const PUSH_BODY_CHARS: usize = 160;+/// Pushes we send stay well under the 4 KB push services accept.+pub const MAX_PAYLOAD_BYTES: usize = 3 * 1024;+/// Record size in the aes128gcm header; one record always holds our payload.+const RECORD_SIZE: u32 = 4096;+const SEND_TIMEOUT: Duration = Duration::from_secs(10);+const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);++const QUERY_VALUE: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.');++/// A browser that asked for pushes.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct Subscription {+ pub endpoint: String,+ /// The browser's P-256 public key, base64url (65 bytes uncompressed).+ pub p256dh: String,+ /// The browser's auth secret, base64url (16 bytes).+ pub auth: String,+ #[serde(default)]+ pub label: String,+ /// The sign-in session that subscribed, so signing that browser out stops its pushes.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub session_id: Option<String>,+ pub created_at: DateTime<Utc>,+}++/// What a push carries, as the service worker reads it.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct Payload {+ pub title: String,+ pub body: String,+ pub kind: String,+ pub space_id: Option<String>,+ pub channel_id: Option<String>,+ pub kwant_id: String,+ /// Relative: `/?space=<id>&channel=<id>`, or `&kwant=<id>` without a channel.+ pub url: String,+ pub tag: String,+}++impl Payload {+ pub fn new(+ kind: &str,+ title: &str,+ body: &str,+ space_id: Option<String>,+ channel_id: Option<String>,+ kwant_id: String,+ ) -> Self {+ let enc = |s: &str| percent_encoding::utf8_percent_encode(s, QUERY_VALUE).to_string();+ let mut query = Vec::new();+ if let Some(s) = &space_id {+ query.push(format!("space={}", enc(s)));+ }+ match &channel_id {+ Some(c) => query.push(format!("channel={}", enc(c))),+ None => query.push(format!("kwant={}", enc(&kwant_id))),+ }+ let tag = format!(+ "kwnt-{}-{kind}-{}",+ space_id.as_deref().unwrap_or("none"),+ channel_id.as_deref().unwrap_or(&kwant_id)+ );+ Self {+ title: clip(title, 120),+ body: clip(body, PUSH_BODY_CHARS),+ kind: kind.into(),+ space_id,+ channel_id,+ kwant_id,+ url: format!("/?{}", query.join("&")),+ tag,+ }+ }++ /// The person is waiting on these: kept a day and sent at high urgency.+ pub fn needs_person(&self) -> bool {+ matches!(self.kind.as_str(), "approval_needed" | "question_asked" | "human_step")+ }++ pub fn ttl(&self) -> u32 {+ if self.needs_person() {+ 86_400+ } else {+ 3_600+ }+ }++ pub fn urgency(&self) -> &'static str {+ if self.needs_person() {+ "high"+ } else {+ "normal"+ }+ }++ /// The JSON the browser gets, shortened to fit `MAX_PAYLOAD_BYTES`.+ fn to_bytes(&self) -> Vec<u8> {+ let mut p = self.clone();+ loop {+ let bytes = serde_json::to_vec(&p).unwrap_or_default();+ if bytes.len() <= MAX_PAYLOAD_BYTES || (p.body.is_empty() && p.title.chars().count() <= 40) {+ return bytes;+ }+ if !p.body.is_empty() {+ p.body.clear();+ } else {+ p.title = clip(&p.title, 40);+ }+ }+ }+}++fn clip(text: &str, max: usize) -> String {+ let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");+ if flat.chars().count() <= max {+ return flat;+ }+ let mut out: String = flat.chars().take(max.saturating_sub(1)).collect();+ out.push('…');+ out+}++/// Why a subscription was refused (400).+#[derive(Debug, PartialEq, Eq)]+pub struct Invalid(pub &'static str);++fn decode(s: &str) -> Option<Vec<u8>> {+ // Browsers send base64url without padding; tolerate padding and plain base64 too+ let s = s.trim().trim_end_matches('=').replace('+', "-").replace('/', "_");+ B64.decode(s).ok()+}++/// Addresses on the public internet; everything else is this machine or its network.+pub fn is_public_ip(ip: IpAddr) -> bool {+ match ip {+ IpAddr::V4(v4) => {+ let [a, b, ..] = v4.octets();+ !(v4.is_private()+ || v4.is_loopback()+ || v4.is_link_local()+ || v4.is_broadcast()+ || v4.is_documentation()+ || v4.is_unspecified()+ || v4.is_multicast()+ || a == 0+ || a >= 240+ || (a == 100 && (64..128).contains(&b)) // shared (CGNAT), 100.64/10+ || (a == 192 && b == 0 && v4.octets()[2] == 0) // IETF protocol assignments+ || (a == 198 && (b == 18 || b == 19))) // benchmarking+ }+ IpAddr::V6(v6) => {+ if let Some(v4) = v6.to_ipv4_mapped() {+ return is_public_ip(IpAddr::V4(v4));+ }+ let seg = v6.segments();+ !(v6.is_loopback()+ || v6.is_unspecified()+ || v6.is_multicast()+ || (seg[0] & 0xfe00) == 0xfc00 // unique local+ || (seg[0] & 0xffc0) == 0xfe80 // link local+ || (seg[0] == 0x2001 && seg[1] == 0x0db8) // documentation+ || (seg[0] == 0x0064 && seg[1] == 0xff9b) // NAT64 to anything, incl. private v4+ || (seg[0] == 0 && seg[1] == 0 && seg[2] == 0 && seg[3] == 0 && seg[4] == 0 && seg[5] == 0)) // v4-compatible+ }+ }+}++/// Checks an endpoint before it is stored: https, a host name or public address, no user info.+/// Names are resolved (and checked) again on each send.+pub fn check_endpoint(raw: &str) -> Result<reqwest::Url, Invalid> {+ if raw.len() > MAX_ENDPOINT_LEN {+ return Err(Invalid("endpoint is too long"));+ }+ let url = reqwest::Url::parse(raw).map_err(|_| Invalid("endpoint is not a valid URL"))?;+ if url.scheme() != "https" {+ return Err(Invalid("endpoint must be an https:// URL"));+ }+ if !url.username().is_empty() || url.password().is_some() {+ return Err(Invalid("endpoint must not contain a user name or password"));+ }+ match url.host() {+ None => Err(Invalid("endpoint has no host")),+ Some(url::Host::Ipv4(ip)) if !is_public_ip(IpAddr::V4(ip)) => Err(Invalid("endpoint must be on the public internet")),+ Some(url::Host::Ipv6(ip)) if !is_public_ip(IpAddr::V6(ip)) => Err(Invalid("endpoint must be on the public internet")),+ Some(url::Host::Domain(d)) => {+ let d = d.trim_end_matches('.').to_ascii_lowercase();+ if d == "localhost" || d.ends_with(".localhost") || !d.contains('.') {+ Err(Invalid("endpoint must be on the public internet"))+ } else {+ Ok(url)+ }+ }+ Some(_) => Ok(url),+ }+}++/// Checks the browser's keys: a 65-byte uncompressed P-256 point and a 16-byte auth secret.+pub fn check_keys(p256dh: &str, auth: &str) -> Result<(), Invalid> {+ match decode(p256dh) {+ Some(k) if k.len() == 65 && k[0] == 4 => {}+ _ => return Err(Invalid("keys.p256dh must be a base64url P-256 public key")),+ }+ match decode(auth) {+ Some(a) if a.len() == 16 => Ok(()),+ _ => Err(Invalid("keys.auth must be a base64url 16-byte secret")),+ }+}++fn hmac_sha256(key: &[u8], parts: &[&[u8]]) -> [u8; 32] {+ let key = hmac::Key::new(hmac::HMAC_SHA256, key);+ let mut ctx = hmac::Context::with_key(&key);+ for p in parts {+ ctx.update(p);+ }+ let mut out = [0u8; 32];+ out.copy_from_slice(ctx.sign().as_ref());+ out+}++/// RFC 8291 section 3.4 and RFC 8188: one aes128gcm record for `plaintext`, given the ECDH+/// secret already agreed. Split out so the RFC's test vector can be checked without its private key.+pub fn encrypt_with_secret(+ ecdh_secret: &[u8],+ auth_secret: &[u8],+ ua_public: &[u8],+ as_public: &[u8],+ salt: &[u8; 16],+ plaintext: &[u8],+) -> Result<Vec<u8>, &'static str> {+ if as_public.len() != 65 {+ return Err("bad server key");+ }+ if plaintext.len() + 1 + 16 > RECORD_SIZE as usize - 86 {+ return Err("payload too large");+ }+ // PRK_key = HMAC(auth_secret, ecdh_secret); IKM = HKDF-Expand(PRK_key, key_info, 32)+ let prk_key = hmac_sha256(auth_secret, &[ecdh_secret]);+ let ikm = hmac_sha256(&prk_key, &[b"WebPush: info\0", ua_public, as_public, &[1]]);+ let prk = hmac_sha256(salt, &[&ikm]);+ let cek = hmac_sha256(&prk, &[b"Content-Encoding: aes128gcm\0", &[1]]);+ let nonce = hmac_sha256(&prk, &[b"Content-Encoding: nonce\0", &[1]]);++ let key = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_128_GCM, &cek[..16]).map_err(|_| "bad key")?);+ let nonce = aead::Nonce::try_assume_unique_for_key(&nonce[..12]).map_err(|_| "bad nonce")?;+ // The last (and only) record ends with the 0x02 delimiter and no padding+ let mut record = Vec::with_capacity(plaintext.len() + 17);+ record.extend_from_slice(plaintext);+ record.push(2);+ key.seal_in_place_append_tag(nonce, aead::Aad::empty(), &mut record)+ .map_err(|_| "encryption failed")?;++ let mut out = Vec::with_capacity(86 + record.len());+ out.extend_from_slice(salt);+ out.extend_from_slice(&RECORD_SIZE.to_be_bytes());+ out.push(as_public.len() as u8);+ out.extend_from_slice(as_public);+ out.extend_from_slice(&record);+ Ok(out)+}++/// The browser's side of `encrypt_with_secret` (one record), for tests and the fake push+/// service: the plaintext, or `None` when the body doesn't open.+pub fn decrypt_with_secret(ecdh_secret: &[u8], auth_secret: &[u8], ua_public: &[u8], body: &[u8]) -> Option<Vec<u8>> {+ if body.len() < 86 + 17 || u32::from_be_bytes(body[16..20].try_into().ok()?) != RECORD_SIZE || body[20] != 65 {+ return None;+ }+ let (salt, as_public) = (&body[..16], &body[21..86]);+ let prk_key = hmac_sha256(auth_secret, &[ecdh_secret]);+ let ikm = hmac_sha256(&prk_key, &[b"WebPush: info\0", ua_public, as_public, &[1]]);+ let prk = hmac_sha256(salt, &[&ikm]);+ let cek = hmac_sha256(&prk, &[b"Content-Encoding: aes128gcm\0", &[1]]);+ let nonce = hmac_sha256(&prk, &[b"Content-Encoding: nonce\0", &[1]]);+ let key = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_128_GCM, &cek[..16]).ok()?);+ let nonce = aead::Nonce::try_assume_unique_for_key(&nonce[..12]).ok()?;+ let mut record = body[86..].to_vec();+ let plain = key.open_in_place(nonce, aead::Aad::empty(), &mut record).ok()?;+ match plain.split_last() {+ Some((2, rest)) => Some(rest.to_vec()),+ _ => None,+ }+}++/// Encrypts `plaintext` for one browser with a fresh server key pair and salt.+pub fn encrypt(ua_public: &[u8], auth_secret: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, &'static str> {+ let rng = ring::rand::SystemRandom::new();+ let private = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).map_err(|_| "rng")?;+ let as_public = private.compute_public_key().map_err(|_| "rng")?;+ let mut salt = [0u8; 16];+ rng.fill(&mut salt).map_err(|_| "rng")?;+ let peer = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, ua_public);+ let secret = agreement::agree_ephemeral(private, &peer, |s| s.to_vec()).map_err(|_| "bad browser key")?;+ encrypt_with_secret(&secret, auth_secret, ua_public, as_public.as_ref(), &salt, plaintext)+}++/// The VAPID key pair (ECDSA P-256).+pub struct Vapid {+ pair: signature::EcdsaKeyPair,+}++impl Vapid {+ fn from_pkcs8(der: &[u8]) -> Option<Self> {+ let rng = ring::rand::SystemRandom::new();+ signature::EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P256_SHA256_FIXED_SIGNING, der, &rng)+ .ok()+ .map(|pair| Self { pair })+ }++ fn generate() -> Option<(Self, Vec<u8>)> {+ let rng = ring::rand::SystemRandom::new();+ let der = signature::EcdsaKeyPair::generate_pkcs8(&signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng).ok()?;+ let der = der.as_ref().to_vec();+ Some((Self::from_pkcs8(&der)?, der))+ }++ /// The uncompressed public key, base64url: the browser's `applicationServerKey`.+ pub fn public_key(&self) -> String {+ use signature::KeyPair;+ B64.encode(self.pair.public_key().as_ref())+ }++ /// `Authorization: vapid t=<jwt>, k=<public key>` for `endpoint`'s push service.+ pub fn authorization(&self, endpoint: &reqwest::Url, now: DateTime<Utc>) -> Option<String> {+ let aud = endpoint.origin().ascii_serialization();+ let header = B64.encode(br#"{"typ":"JWT","alg":"ES256"}"#);+ let claims = serde_json::json!({ "aud": aud, "exp": now.timestamp() + JWT_SECS, "sub": VAPID_SUBJECT });+ let claims = B64.encode(serde_json::to_vec(&claims).ok()?);+ let signing_input = format!("{header}.{claims}");+ let rng = ring::rand::SystemRandom::new();+ let sig = self.pair.sign(&rng, signing_input.as_bytes()).ok()?;+ Some(format!("vapid t={signing_input}.{}, k={}", B64.encode(sig.as_ref()), self.public_key()))+ }+}++/// Resolves push service names and keeps only public addresses, so a name pointing into this+/// network (or re-pointed after subscribing) is never connected to.+struct PublicOnly;++impl reqwest::dns::Resolve for PublicOnly {+ fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {+ let host = name.as_str().to_string();+ Box::pin(async move {+ let addrs: Vec<SocketAddr> = tokio::net::lookup_host((host.as_str(), 0))+ .await?+ .filter(|a| is_public_ip(a.ip()))+ .collect();+ if addrs.is_empty() {+ return Err("push endpoint does not resolve to a public address".into());+ }+ Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs)+ })+ }+}++/// What one send found.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Sent {+ Ok,+ /// 404 or 410: the browser unsubscribed; drop it.+ Gone,+ Failed,+}++pub struct Push {+ dir: Option<PathBuf>,+ vapid: Mutex<Option<Arc<Vapid>>>,+ subs: Mutex<Vec<Subscription>>,+ client: reqwest::Client,+ /// Tests send to a local http endpoint.+ allow_local: bool,+}++impl std::fmt::Debug for Push {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Push").finish_non_exhaustive()+ }+}++impl Push {+ /// Subscriptions from `<data_dir>/push.json`; the key is read or made on first use.+ pub fn load(data_dir: &Path) -> Self {+ let subs = match std::fs::read_to_string(data_dir.join(SUBS_FILE)) {+ Ok(s) => serde_json::from_str(&s).unwrap_or_else(|e| {+ tracing::warn!(error = %e, "push.json is unreadable; devices have to turn notifications on again");+ Vec::new()+ }),+ Err(_) => Vec::new(),+ };+ Self::build(Some(data_dir.to_path_buf()), subs, false)+ }++ /// Sends to `http://127.0.0.1` too, for tests with a fake push service. Never used by `serve`.+ pub fn for_tests_allowing_local(data_dir: &Path) -> Self {+ Self::build(Some(data_dir.to_path_buf()), Vec::new(), true)+ }++ fn build(dir: Option<PathBuf>, subs: Vec<Subscription>, allow_local: bool) -> Self {+ let mut builder = reqwest::Client::builder()+ .timeout(SEND_TIMEOUT)+ .connect_timeout(CONNECT_TIMEOUT)+ .redirect(reqwest::redirect::Policy::none())+ // A proxy would resolve the name itself, past our check+ .no_proxy();+ if !allow_local {+ builder = builder.dns_resolver(Arc::new(PublicOnly));+ }+ Self {+ dir,+ vapid: Mutex::new(None),+ subs: Mutex::new(subs),+ client: builder.build().unwrap_or_default(),+ allow_local,+ }+ }++ /// The VAPID key, read from the data dir or made (and saved) the first time.+ pub fn vapid(&self) -> Option<Arc<Vapid>> {+ let mut slot = self.vapid.lock().unwrap_or_else(|e| e.into_inner());+ if let Some(v) = slot.as_ref() {+ return Some(v.clone());+ }+ let path = self.dir.as_ref().map(|d| d.join(KEY_FILE));+ let existing = path+ .as_ref()+ .and_then(|p| std::fs::read_to_string(p).ok())+ .and_then(|s| decode(&s))+ .and_then(|der| Vapid::from_pkcs8(&der));+ let vapid = match existing {+ Some(v) => v,+ None => {+ let (v, der) = Vapid::generate()?;+ if let Some(p) = &path {+ if let Some(d) = p.parent() {+ let _ = std::fs::create_dir_all(d);+ }+ if let Err(e) = super::auth::write_private(p, &B64.encode(&der)) {+ // Without the file every restart makes a new key and old subscriptions stop working+ tracing::warn!(error = %e, "could not save the push key");+ }+ }+ v+ }+ };+ let v = Arc::new(vapid);+ *slot = Some(v.clone());+ Some(v)+ }++ fn check(&self, endpoint: &str) -> Result<(), Invalid> {+ if self.allow_local && endpoint.starts_with("http://127.0.0.1:") {+ return Ok(());+ }+ check_endpoint(endpoint).map(|_| ())+ }++ fn save(&self, subs: &[Subscription]) {+ let Some(dir) = &self.dir else { return };+ let Ok(json) = serde_json::to_string_pretty(subs) else { return };+ let path = dir.join(SUBS_FILE);+ let tmp = path.with_extension("json.tmp");+ let res = super::auth::write_private(&tmp, &json).and_then(|_| std::fs::rename(&tmp, &path));+ if let Err(e) = res {+ tracing::warn!(error = %e, "could not save push subscriptions");+ }+ }++ /// Adds or refreshes a subscription (by endpoint). Past the cap the oldest is dropped.+ pub fn subscribe(+ &self,+ endpoint: &str,+ p256dh: &str,+ auth: &str,+ label: &str,+ session_id: Option<String>,+ ) -> Result<(), Invalid> {+ self.check(endpoint)?;+ check_keys(p256dh, auth)?;+ let sub = Subscription {+ endpoint: endpoint.to_string(),+ p256dh: p256dh.trim().to_string(),+ auth: auth.trim().to_string(),+ label: clip(label, MAX_LABEL_CHARS),+ session_id,+ created_at: Utc::now(),+ };+ let mut subs = self.subs.lock().unwrap_or_else(|e| e.into_inner());+ subs.retain(|s| s.endpoint != sub.endpoint);+ subs.push(sub);+ subs.sort_by_key(|s| s.created_at);+ while subs.len() > MAX_SUBSCRIPTIONS {+ subs.remove(0);+ }+ self.save(&subs);+ Ok(())+ }++ /// Removes one subscription; false when there was none.+ pub fn unsubscribe(&self, endpoint: &str) -> bool {+ self.remove(|s| s.endpoint == endpoint)+ }++ /// Stops pushes to the browsers a signed-out session subscribed.+ pub fn drop_session(&self, session_id: &str) -> bool {+ self.remove(|s| s.session_id.as_deref() == Some(session_id))+ }++ fn remove(&self, f: impl Fn(&Subscription) -> bool) -> bool {+ let mut subs = self.subs.lock().unwrap_or_else(|e| e.into_inner());+ let before = subs.len();+ subs.retain(|s| !f(s));+ let removed = subs.len() != before;+ if removed {+ self.save(&subs);+ }+ removed+ }++ pub fn subscriptions(&self) -> Vec<Subscription> {+ self.subs.lock().unwrap_or_else(|e| e.into_inner()).clone()+ }++ /// Sends `payload` to every subscription at once and drops the ones that are gone. Each+ /// send has its own timeout; failures are logged (host only) and not retried.+ pub async fn send_all(&self, payload: &Payload) {+ let subs = self.subscriptions();+ if subs.is_empty() {+ return;+ }+ let Some(vapid) = self.vapid() else {+ return tracing::warn!("push key unavailable; notification not pushed");+ };+ let bytes = payload.to_bytes();+ let topic = topic(&payload.tag);+ let sends = subs.iter().map(|s| self.send_one(&vapid, s, &bytes, payload, &topic));+ let results = futures::future::join_all(sends).await;+ let gone: Vec<&str> = subs+ .iter()+ .zip(results)+ .filter(|(_, r)| *r == Sent::Gone)+ .map(|(s, _)| s.endpoint.as_str())+ .collect();+ if !gone.is_empty() {+ self.remove(|s| gone.contains(&s.endpoint.as_str()));+ }+ }++ async fn send_one(&self, vapid: &Vapid, sub: &Subscription, bytes: &[u8], payload: &Payload, topic: &str) -> Sent {+ let host = super::continuity::loggable_url(&sub.endpoint);+ if self.check(&sub.endpoint).is_err() {+ tracing::warn!(endpoint = %host, "push endpoint is no longer allowed; skipped");+ return Sent::Failed;+ }+ let Ok(url) = reqwest::Url::parse(&sub.endpoint) else { return Sent::Failed };+ let (Some(ua_public), Some(auth)) = (decode(&sub.p256dh), decode(&sub.auth)) else { return Sent::Failed };+ let body = match encrypt(&ua_public, &auth, bytes) {+ Ok(b) => b,+ Err(e) => {+ tracing::warn!(endpoint = %host, error = e, "could not encrypt a push");+ return Sent::Failed;+ }+ };+ let Some(authorization) = vapid.authorization(&url, Utc::now()) else { return Sent::Failed };+ let res = self+ .client+ .post(url)+ .header(reqwest::header::AUTHORIZATION, authorization)+ .header(reqwest::header::CONTENT_ENCODING, "aes128gcm")+ .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")+ .header("TTL", payload.ttl().to_string())+ .header("Urgency", payload.urgency())+ .header("Topic", topic)+ .body(body)+ .send()+ .await;+ match res {+ Ok(r) if r.status().is_success() => Sent::Ok,+ Ok(r) if r.status() == reqwest::StatusCode::NOT_FOUND || r.status() == reqwest::StatusCode::GONE => {+ tracing::info!(endpoint = %host, status = %r.status(), "push subscription expired; removed");+ Sent::Gone+ }+ Ok(r) => {+ tracing::warn!(endpoint = %host, status = %r.status(), "push service refused the notification");+ Sent::Failed+ }+ // reqwest errors can print the full URL, so only the kind is logged+ Err(e) => {+ tracing::warn!(endpoint = %host, timeout = e.is_timeout(), connect = e.is_connect(), "push service could not be reached");+ Sent::Failed+ }+ }+ }+}++/// RFC 8030 `Topic`: a newer push with the same topic replaces one still waiting on the push+/// service. At most 32 base64url characters, so the tag is hashed.+fn topic(tag: &str) -> String {+ use sha2::Digest;+ B64.encode(sha2::Sha256::digest(tag.as_bytes()))[..32].to_string()+}++// Routes (all person-only, see `auth::person_only`)++#[derive(Debug, Deserialize)]+pub struct SubscribeKeys {+ pub p256dh: String,+ pub auth: String,+}++/// `PushSubscription.toJSON()` plus an optional label; `expirationTime` is ignored.+#[derive(Debug, Deserialize)]+pub struct SubscribeBody {+ pub endpoint: String,+ pub keys: SubscribeKeys,+ #[serde(default)]+ pub label: Option<String>,+}++#[derive(Debug, Deserialize)]+pub struct UnsubscribeBody {+ pub endpoint: String,+}++fn bad_request(msg: &str) -> axum::response::Response {+ use axum::response::IntoResponse;+ (axum::http::StatusCode::BAD_REQUEST, axum::Json(serde_json::json!({ "error": msg }))).into_response()+}++/// `GET /api/push/key`: `{public_key}`, the browser's `applicationServerKey`.+pub async fn key(axum::extract::State(state): axum::extract::State<super::AppState>) -> axum::response::Response {+ use axum::response::IntoResponse;+ match state.push.vapid() {+ Some(v) => axum::Json(serde_json::json!({ "public_key": v.public_key() })).into_response(),+ None => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(serde_json::json!({ "error": "push key unavailable" }))).into_response(),+ }+}++/// `POST /api/push/subscribe`: stores (or refreshes) this browser's subscription, linked to its+/// sign-in session when it has one. 204; 400 with `{error}` for a bad endpoint or keys.+pub async fn subscribe(+ axum::extract::State(state): axum::extract::State<super::AppState>,+ headers: axum::http::HeaderMap,+ body: Result<axum::Json<SubscribeBody>, axum::extract::rejection::JsonRejection>,+) -> axum::response::Response {+ use axum::response::IntoResponse;+ let Ok(axum::Json(body)) = body else {+ return bad_request("expected {endpoint, keys: {p256dh, auth}}");+ };+ let session = super::auth::cookie_token(&headers).and_then(|c| state.api_token.signin.session_id(c));+ let label = body+ .label+ .or_else(|| headers.get(axum::http::header::USER_AGENT).and_then(|v| v.to_str().ok()).map(super::signin::browser_label))+ .unwrap_or_default();+ match state.push.subscribe(&body.endpoint, &body.keys.p256dh, &body.keys.auth, &label, session) {+ Ok(()) => axum::http::StatusCode::NO_CONTENT.into_response(),+ Err(Invalid(msg)) => bad_request(msg),+ }+}++/// `POST /api/push/unsubscribe` `{endpoint}`: 204, also when it wasn't subscribed.+pub async fn unsubscribe(+ axum::extract::State(state): axum::extract::State<super::AppState>,+ body: Result<axum::Json<UnsubscribeBody>, axum::extract::rejection::JsonRejection>,+) -> axum::response::Response {+ use axum::response::IntoResponse;+ let Ok(axum::Json(body)) = body else {+ return bad_request("expected {endpoint}");+ };+ state.push.unsubscribe(&body.endpoint);+ axum::http::StatusCode::NO_CONTENT.into_response()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn b64(s: &str) -> Vec<u8> {+ B64.decode(s.split_whitespace().collect::<String>()).unwrap()+ }++ /// RFC 8291 section 5 and appendix A.+ #[test]+ fn encrypts_the_rfc_8291_example() {+ let ecdh = b64("kyrL1jIIOHEzg3sM2ZWRHDRB62YACZhhSlknJ672kSs");+ let auth = b64("BTBZMqHH6r4Tts7J_aSIgg");+ let ua_public = b64("BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcx aOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4");+ let as_public = b64("BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIg Dll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8");+ let salt: [u8; 16] = b64("DGv6ra1nlYgDCS1FRnbzlw").try_into().unwrap();+ let plaintext = b"When I grow up, I want to be a watermelon";+ let out = encrypt_with_secret(&ecdh, &auth, &ua_public, &as_public, &salt, plaintext).unwrap();+ let header = b64("DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z 9KsN6nGRTbVYI_c7VJSPQTBtkgcy27ml mlMoZIIgDll6e3vCYLocInmYWAmS6Tlz AC8wEqKK6PBru3jl7A8");+ let ciphertext = b64("8pfeW0KbunFT06SuDKoJH9Ql87S1QUrd irN6GcG7sFz1y1sqLgVi1VhjVkHsUoEs bI_0LpXMuGvnzQ");+ assert_eq!(&out[..86], &header[..]);+ assert_eq!(&out[86..], &ciphertext[..]);+ }++ /// A fresh key pair and salt, decrypted the way a browser does it.+ #[test]+ fn a_browser_can_decrypt_a_push() {+ let rng = ring::rand::SystemRandom::new();+ let ua_private = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).unwrap();+ let ua_public = ua_private.compute_public_key().unwrap().as_ref().to_vec();+ let auth = [7u8; 16];+ let out = encrypt(&ua_public, &auth, b"{\"title\":\"hi\"}").unwrap();+ assert_eq!(decrypt_for_tests(ua_private, &ua_public, &auth, &out), b"{\"title\":\"hi\"}");+ }++ fn decrypt_for_tests(ua_private: agreement::EphemeralPrivateKey, ua_public: &[u8], auth: &[u8], body: &[u8]) -> Vec<u8> {+ let peer = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, &body[21..86]);+ let ecdh = agreement::agree_ephemeral(ua_private, &peer, |s| s.to_vec()).unwrap();+ decrypt_with_secret(&ecdh, auth, ua_public, body).unwrap()+ }++ #[test]+ fn vapid_token_is_an_es256_jwt_for_the_push_origin() {+ let (v, _) = Vapid::generate().unwrap();+ let url = reqwest::Url::parse("https://fcm.googleapis.com/fcm/send/abc").unwrap();+ let now = Utc::now();+ let h = v.authorization(&url, now).unwrap();+ let (t, k) = h.strip_prefix("vapid t=").unwrap().split_once(", k=").unwrap();+ assert_eq!(k, v.public_key());+ assert_eq!(b64(k).len(), 65);+ let parts: Vec<&str> = t.split('.').collect();+ assert_eq!(parts.len(), 3);+ let claims: serde_json::Value = serde_json::from_slice(&b64(parts[1])).unwrap();+ assert_eq!(claims["aud"], "https://fcm.googleapis.com");+ assert_eq!(claims["sub"], VAPID_SUBJECT);+ assert_eq!(claims["exp"], now.timestamp() + JWT_SECS);+ let public = signature::UnparsedPublicKey::new(&signature::ECDSA_P256_SHA256_FIXED, b64(k));+ public+ .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &b64(parts[2]))+ .expect("signature verifies");+ }++ #[test]+ fn endpoints_must_be_public_https() {+ assert!(check_endpoint("https://fcm.googleapis.com/fcm/send/abc").is_ok());+ assert!(check_endpoint("https://web.push.apple.com/QX").is_ok());+ for bad in [+ "http://fcm.googleapis.com/x",+ "https://localhost/x",+ "https://foo.localhost/x",+ "https://intranet/x",+ "https://127.0.0.1/x",+ "https://10.0.0.5/x",+ "https://192.168.1.1/x",+ "https://169.254.169.254/latest",+ "https://100.64.0.1/x",+ "https://[::1]/x",+ "https://[fd00::1]/x",+ "https://[::ffff:10.0.0.1]/x",+ "https://user:[email protected]/x",+ "file:///etc/passwd",+ "not a url",+ ] {+ assert!(check_endpoint(bad).is_err(), "{bad} should be refused");+ }+ assert!(check_endpoint(&format!("https://fcm.googleapis.com/{}", "a".repeat(3000))).is_err());+ assert!(is_public_ip("8.8.8.8".parse().unwrap()));+ assert!(is_public_ip("2607:f8b0::1".parse().unwrap()));+ assert!(!is_public_ip("0.1.2.3".parse().unwrap()));+ assert!(!is_public_ip("64:ff9b::a00:1".parse().unwrap()));+ }++ /// A name that resolves into this machine or its network is never connected to.+ #[tokio::test]+ async fn the_resolver_drops_private_addresses() {+ use reqwest::dns::Resolve;+ let err = PublicOnly.resolve("localhost".parse().unwrap()).await.err().expect("refused");+ assert!(err.to_string().contains("public address"));+ // And the real client fails before sending anything+ let push = Push::build(None, Vec::new(), false);+ let res = push.client.post("https://localhost:9/x").send().await;+ assert!(res.is_err());+ }++ #[test]+ fn keys_are_checked() {+ let p = B64.encode([4u8; 65]);+ let a = B64.encode([1u8; 16]);+ assert!(check_keys(&p, &a).is_ok());+ assert!(check_keys(&format!("{p}="), &format!("{a}==")).is_ok());+ assert!(check_keys(&B64.encode([4u8; 33]), &a).is_err());+ assert!(check_keys(&p, &B64.encode([1u8; 8])).is_err());+ assert!(check_keys("!!", &a).is_err());+ }++ #[test]+ fn subscriptions_upsert_cap_and_persist_privately() {+ let dir = tempfile::tempdir().unwrap();+ let push = Push::load(dir.path());+ let p = B64.encode([4u8; 65]);+ let a = B64.encode([1u8; 16]);+ for i in 0..MAX_SUBSCRIPTIONS + 3 {+ push.subscribe(&format!("https://fcm.googleapis.com/fcm/send/{i}"), &p, &a, "Chrome", None).unwrap();+ }+ assert_eq!(push.subscriptions().len(), MAX_SUBSCRIPTIONS);+ assert!(!push.subscriptions().iter().any(|s| s.endpoint.ends_with("/send/0")));+ // Same endpoint again replaces, with the new session+ push.subscribe("https://fcm.googleapis.com/fcm/send/5", &p, &a, "Pixel", Some("s1".into())).unwrap();+ assert_eq!(push.subscriptions().len(), MAX_SUBSCRIPTIONS);+ assert_eq!(Push::load(dir.path()).subscriptions().len(), MAX_SUBSCRIPTIONS);+ assert!(push.drop_session("s1"));+ assert!(!push.unsubscribe("https://fcm.googleapis.com/fcm/send/5"));+ assert!(push.unsubscribe("https://fcm.googleapis.com/fcm/send/6"));+ assert_eq!(Push::load(dir.path()).subscriptions().len(), MAX_SUBSCRIPTIONS - 2);+ assert_eq!(push.subscribe("https://10.0.0.1/x", &p, &a, "", None), Err(Invalid("endpoint must be on the public internet")));+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = std::fs::metadata(dir.path().join(SUBS_FILE)).unwrap().permissions().mode();+ assert_eq!(mode & 0o777, 0o600);+ }+ }++ #[test]+ fn vapid_key_is_made_once_and_kept() {+ let dir = tempfile::tempdir().unwrap();+ let key = Push::load(dir.path()).vapid().unwrap().public_key();+ assert_eq!(Push::load(dir.path()).vapid().unwrap().public_key(), key);+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = std::fs::metadata(dir.path().join(KEY_FILE)).unwrap().permissions().mode();+ assert_eq!(mode & 0o777, 0o600);+ }+ }++ #[test]+ fn payload_shape_ttl_and_urgency() {+ let p = Payload::new("approval_needed", "Ada needs approval", &"x".repeat(400), Some("sp 1".into()), Some("c1".into()), "k1".into());+ assert_eq!(p.url, "/?space=sp%201&channel=c1");+ assert_eq!(p.tag, "kwnt-sp 1-approval_needed-c1");+ assert_eq!(p.body.chars().count(), PUSH_BODY_CHARS);+ assert_eq!((p.ttl(), p.urgency()), (86_400, "high"));+ let p = Payload::new("turn_finished", "Laya finished", "done", None, None, "k1".into());+ assert_eq!(p.url, "/?kwant=k1");+ assert_eq!(p.tag, "kwnt-none-turn_finished-k1");+ assert_eq!((p.ttl(), p.urgency()), (3_600, "normal"));+ let huge = Payload { title: "t".repeat(5000), ..p };+ assert!(huge.to_bytes().len() <= MAX_PAYLOAD_BYTES);+ assert_eq!(topic("kwnt-x").len(), 32);+ }+}diff --git a/tests/push_test.rs b/tests/push_test.rsnew file mode 100644index 00000000..5a8106ab--- /dev/null+++ b/tests/push_test.rs@@ -0,0 +1,280 @@+//! Web Push to the installed app (2026-10-25): a browser subscribes with our VAPID key, and a+//! notification reaches a (fake, local) push service as an RFC 8291 aes128gcm body with an+//! RFC 8292 VAPID token, TTL and Urgency. A 410 from the push service drops the subscription,+//! `notify_on` is honoured, the routes are person-only, and signing a session out stops its pushes.++use axum::{+ body::{to_bytes, Body, Bytes},+ extract::{ConnectInfo, State},+ http::{HeaderMap, Request, StatusCode},+ routing::post,+ Router,+};+use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;+use base64::Engine;+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ router::LayaRouter,+ server::{+ auth::{ApiToken, Require},+ continuity::{self, Notification},+ create_router,+ push::{self, Push},+ signin, AppState,+ },+ tools::ToolRunner,+};+use ring::agreement;+use serde_json::{json, Value};+use std::net::SocketAddr;+use std::sync::atomic::{AtomicU16, Ordering};+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++const TOKEN: &str = "test-api-token-0123456789";+const REMOTE: &str = "203.0.113.9:40000";++async fn setup() -> (Router, AppState, TempDir) {+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };+ let mut state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ state.api_token = Arc::new(ApiToken::for_tests(TOKEN, Require::Auto, config.port));+ state.push = Arc::new(Push::for_tests_allowing_local(&data));+ (create_router(state.clone()), state, tmp)+}++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>, bearer: Option<&str>, cookie: Option<&str>) -> (StatusCode, Value) {+ let mut req = Request::builder()+ .method(method)+ .uri(uri)+ .header("host", "kwnt.example.com")+ .header("user-agent", "Mozilla/5.0 (Linux; Android 14; Pixel) Chrome/129.0 Mobile Safari/537.36");+ if let Some(t) = bearer {+ req = req.header("authorization", format!("Bearer {t}"));+ }+ if let Some(c) = cookie {+ req = req.header("cookie", format!("kwnt_token={c}"));+ }+ let body = match body {+ Some(b) => {+ req = req.header("content-type", "application/json");+ Body::from(b.to_string())+ }+ None => Body::empty(),+ };+ let mut req = req.body(body).unwrap();+ req.extensions_mut().insert(ConnectInfo(REMOTE.parse::<SocketAddr>().unwrap()));+ let res = app.clone().oneshot(req).await.unwrap();+ let status = res.status();+ let bytes = to_bytes(res.into_body(), 1 << 20).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++#[derive(Clone, Default)]+struct Fake {+ seen: Arc<Mutex<Vec<(HeaderMap, Bytes)>>>,+ status: Arc<AtomicU16>,+}++async fn fake_push(State(f): State<Fake>, headers: HeaderMap, body: Bytes) -> StatusCode {+ f.seen.lock().unwrap().push((headers, body));+ StatusCode::from_u16(f.status.load(Ordering::SeqCst)).unwrap()+}++/// A push service on 127.0.0.1 that records requests and answers with `status`.+async fn start_fake() -> (Fake, String) {+ let fake = Fake { status: Arc::new(AtomicU16::new(201)), ..Default::default() };+ let app = Router::new().route("/push/:id", post(fake_push)).with_state(fake.clone());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ (fake, format!("http://{addr}"))+}++async fn wait_for(fake: &Fake, n: usize) {+ for _ in 0..100 {+ if fake.seen.lock().unwrap().len() >= n {+ return;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("push service got {} requests, wanted {n}", fake.seen.lock().unwrap().len());+}++/// A browser's push keys: (private key, p256dh, auth).+fn browser_keys() -> (agreement::EphemeralPrivateKey, Vec<u8>, [u8; 16]) {+ let rng = ring::rand::SystemRandom::new();+ let private = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).unwrap();+ let public = private.compute_public_key().unwrap().as_ref().to_vec();+ (private, public, [9u8; 16])+}++fn note(kind: &'static str) -> Notification {+ Notification {+ kind,+ kwant_id: "k-ada".into(),+ kwant_name: "Ada".into(),+ channel_id: Some("ch-1".into()),+ title: "Ada needs your approval".into(),+ body: "Run `cargo test`?".into(),+ }+}++fn header<'a>(h: &'a HeaderMap, name: &str) -> &'a str {+ h.get(name).and_then(|v| v.to_str().ok()).unwrap_or("")+}++#[tokio::test]+async fn a_notification_reaches_the_push_service_encrypted_and_a_410_drops_it() {+ let (app, state, _tmp) = setup().await;+ let (fake, base) = start_fake().await;++ let (status, key) = call(&app, "GET", "/api/push/key", None, Some(TOKEN), None).await;+ assert_eq!(status, StatusCode::OK);+ let public_key = key["public_key"].as_str().unwrap().to_string();+ assert_eq!(B64.decode(&public_key).unwrap().len(), 65);++ let (ua_private, ua_public, auth) = browser_keys();+ let endpoint = format!("{base}/push/phone-1");+ let sub = json!({+ "endpoint": endpoint,+ "expirationTime": null,+ "keys": { "p256dh": B64.encode(&ua_public), "auth": B64.encode(auth) },+ });+ let (status, _) = call(&app, "POST", "/api/push/subscribe", Some(sub), Some(TOKEN), None).await;+ assert_eq!(status, StatusCode::NO_CONTENT);+ assert_eq!(state.push.subscriptions()[0].label, "Chrome on Android");++ continuity::notify(&state, note("approval_needed")).await;+ wait_for(&fake, 1).await;+ let (headers, body) = fake.seen.lock().unwrap()[0].clone();+ assert_eq!(header(&headers, "content-encoding"), "aes128gcm");+ assert_eq!(header(&headers, "ttl"), "86400");+ assert_eq!(header(&headers, "urgency"), "high");+ assert_eq!(header(&headers, "topic").len(), 32);+ let auth_header = header(&headers, "authorization");+ let (jwt, k) = auth_header.strip_prefix("vapid t=").unwrap().split_once(", k=").unwrap();+ assert_eq!(k, public_key);+ let claims: Value = serde_json::from_slice(&B64.decode(jwt.split('.').nth(1).unwrap()).unwrap()).unwrap();+ assert_eq!(claims["aud"], base);+ assert_eq!(claims["sub"], "mailto:[email protected]");++ // The browser opens it with its private key+ let peer = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, body[21..86].to_vec());+ let ecdh = agreement::agree_ephemeral(ua_private, &peer, |s| s.to_vec()).unwrap();+ let plain = push::decrypt_with_secret(&ecdh, &auth, &ua_public, &body).expect("decrypts");+ let payload: Value = serde_json::from_slice(&plain).unwrap();+ assert_eq!(payload["title"], "Ada needs your approval");+ assert_eq!(payload["body"], "Run `cargo test`?");+ assert_eq!(payload["kind"], "approval_needed");+ assert_eq!(payload["kwant_id"], "k-ada");+ assert_eq!(payload["channel_id"], "ch-1");+ assert_eq!(payload["url"], "/?channel=ch-1");+ assert_eq!(payload["tag"], "kwnt-none-approval_needed-ch-1");+ assert!(plain.len() <= push::MAX_PAYLOAD_BYTES);++ // The browser unsubscribed on its side: the push service says 410 and we forget it+ fake.status.store(410, Ordering::SeqCst);+ continuity::notify(&state, note("turn_finished")).await;+ wait_for(&fake, 2).await;+ let (headers, _) = fake.seen.lock().unwrap()[1].clone();+ assert_eq!(header(&headers, "ttl"), "3600");+ assert_eq!(header(&headers, "urgency"), "normal");+ for _ in 0..50 {+ if state.push.subscriptions().is_empty() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ assert!(state.push.subscriptions().is_empty(), "a 410 drops the subscription");+}++#[tokio::test]+async fn kinds_the_person_turned_off_are_not_pushed() {+ let (app, state, _tmp) = setup().await;+ let (fake, base) = start_fake().await;+ let (_, ua_public, auth) = browser_keys();+ let sub = json!({ "endpoint": format!("{base}/push/p"), "keys": { "p256dh": B64.encode(&ua_public), "auth": B64.encode(auth) } });+ assert_eq!(call(&app, "POST", "/api/push/subscribe", Some(sub), Some(TOKEN), None).await.0, StatusCode::NO_CONTENT);+ continuity::save_notify_settings(&state, None, Some(vec!["approval_needed".into()])).await.unwrap();+ continuity::notify(&state, note("turn_finished")).await;+ tokio::time::sleep(Duration::from_millis(400)).await;+ assert!(fake.seen.lock().unwrap().is_empty());+ continuity::notify(&state, note("approval_needed")).await;+ wait_for(&fake, 1).await;+}++#[tokio::test]+async fn push_routes_are_person_only_and_check_what_they_store() {+ let (app, state, _tmp) = setup().await;+ let (_, ua_public, auth) = browser_keys();+ let keys = json!({ "p256dh": B64.encode(&ua_public), "auth": B64.encode(auth) });++ // From another machine without a sign-in+ assert_eq!(call(&app, "GET", "/api/push/key", None, None, None).await.0, StatusCode::UNAUTHORIZED);+ let sub = json!({ "endpoint": "https://fcm.googleapis.com/fcm/send/x", "keys": keys });+ assert_eq!(call(&app, "POST", "/api/push/subscribe", Some(sub.clone()), None, None).await.0, StatusCode::UNAUTHORIZED);+ // A bearer that isn't the API token (a bot's turn token) is refused+ assert_eq!(call(&app, "POST", "/api/push/subscribe", Some(sub.clone()), Some("kt1.some-turn-token"), None).await.0.as_u16() / 100, 4);+ assert!(state.push.subscriptions().is_empty());++ for (endpoint, why) in [+ ("http://fcm.googleapis.com/x", "https"),+ ("https://169.254.169.254/latest/meta-data", "public"),+ ("https://localhost/x", "public"),+ ("https://[::1]/x", "public"),+ ] {+ let (status, body) = call(&app, "POST", "/api/push/subscribe", Some(json!({ "endpoint": endpoint, "keys": keys })), Some(TOKEN), None).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{endpoint}");+ assert!(body["error"].as_str().unwrap().contains(why), "{endpoint}: {body}");+ }+ let bad_keys = json!({ "endpoint": "https://fcm.googleapis.com/fcm/send/x", "keys": { "p256dh": "abc", "auth": B64.encode(auth) } });+ assert_eq!(call(&app, "POST", "/api/push/subscribe", Some(bad_keys), Some(TOKEN), None).await.0, StatusCode::BAD_REQUEST);+ assert_eq!(call(&app, "POST", "/api/push/subscribe", Some(json!({ "nope": 1 })), Some(TOKEN), None).await.0, StatusCode::BAD_REQUEST);+ assert!(state.push.subscriptions().is_empty());++ assert_eq!(call(&app, "POST", "/api/push/subscribe", Some(sub), Some(TOKEN), None).await.0, StatusCode::NO_CONTENT);+ let gone = json!({ "endpoint": "https://fcm.googleapis.com/fcm/send/x" });+ assert_eq!(call(&app, "POST", "/api/push/unsubscribe", Some(gone.clone()), Some(TOKEN), None).await.0, StatusCode::NO_CONTENT);+ assert!(state.push.subscriptions().is_empty());+ // Unsubscribing twice is fine+ assert_eq!(call(&app, "POST", "/api/push/unsubscribe", Some(gone), Some(TOKEN), None).await.0, StatusCode::NO_CONTENT);+}++#[tokio::test]+async fn signing_a_browser_out_stops_its_pushes() {+ let (app, state, _tmp) = setup().await;+ let (_, ua_public, auth) = browser_keys();+ let keys = json!({ "p256dh": B64.encode(&ua_public), "auth": B64.encode(auth) });+ let client = signin::Client { browser: "Chrome on Android".into(), ip: "203.0.113.9".into() };+ let phone = state.api_token.signin.create_session(signin::Via::Device, &client);+ let laptop = state.api_token.signin.create_session(signin::Via::Link, &client);++ let sub = |e: &str| json!({ "endpoint": format!("https://fcm.googleapis.com/fcm/send/{e}"), "keys": keys, "label": "Pixel 11 Pro" });+ assert_eq!(call(&app, "POST", "/api/push/subscribe", Some(sub("phone")), None, Some(&phone)).await.0, StatusCode::NO_CONTENT);+ assert_eq!(call(&app, "POST", "/api/push/subscribe", Some(sub("laptop")), None, Some(&laptop)).await.0, StatusCode::NO_CONTENT);+ assert_eq!(state.push.subscriptions().len(), 2);+ assert_eq!(state.push.subscriptions()[0].label, "Pixel 11 Pro");++ // Signed out from the Signed-in devices list+ let phone_id = state.api_token.signin.session_id(&phone).unwrap();+ assert_eq!(call(&app, "DELETE", &format!("/api/signin/sessions/{phone_id}"), None, None, Some(&laptop)).await.0, StatusCode::NO_CONTENT);+ let left: Vec<String> = state.push.subscriptions().into_iter().map(|s| s.endpoint).collect();+ assert_eq!(left, vec!["https://fcm.googleapis.com/fcm/send/laptop".to_string()]);++ // Signing itself out+ assert_eq!(call(&app, "DELETE", "/api/auth/session", None, None, Some(&laptop)).await.0, StatusCode::NO_CONTENT);+ assert!(state.push.subscriptions().is_empty());+}