git clone https://garage44.eu/jeroen/midas.git.. /src/push.rs
//! Telling a person's phone that something needs them: Web Push, from the hub.
//!
//! The page is followed on a phone, and what needs the person — a session's
//! question or permission request, a decision put to them (`midas ask`) — sat
//! there until they happened to look. A browser that subscribed (More ▸ Notify
//! this device) gets a push when a new one appears; its service worker
//! (`web/src/sw.js`) then asks the hub what waits (`GET /v1/push/needs`), with
//! the person's own login, and shows that.
//!
//! The push itself carries nothing. Web Push encrypts a payload for each
//! subscription (ECDH, HKDF, AES-GCM: RFC 8291), and an empty one needs none of
//! that — only the hub's VAPID signature (RFC 8292), an ES256 token over the
//! push service's origin. So the whole cryptography here is one P-256 signing
//! key, made on first use from the kernel's randomness and kept beside the
//! state, readable by the hub's user only; and what a push service sees is
//! that this hub woke this browser, never what for.
use std::collections::BTreeSet;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Mutex;
use anyhow::{anyhow, bail, Context, Result};
use data_encoding::BASE64URL_NOPAD;
use p256::ecdsa::signature::Signer;
use p256::ecdsa::{Signature, SigningKey};
use serde_json::{json, Value};
use crate::events;
use crate::registry;
fn key_file() -> PathBuf {
registry::root().join("push-vapid.key")
}
fn subs_file() -> PathBuf {
registry::root().join("push-subscriptions.json")
}
/// The hub's signing key: made the first time, from /dev/urandom, mode 0600.
fn key() -> Result<SigningKey> {
if let Ok(b) = std::fs::read(key_file()) {
return SigningKey::from_slice(&b).map_err(|_| anyhow!("{} is not a P-256 key", key_file().display()));
}
let mut f = std::fs::File::open("/dev/urandom")?;
loop {
let mut b = [0u8; 32];
f.read_exact(&mut b)?;
// Nearly every 32 bytes is a valid scalar; the rest is drawn again.
if let Ok(k) = SigningKey::from_slice(&b) {
use std::os::unix::fs::OpenOptionsExt;
let mut out = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(key_file())
.with_context(|| format!("writing {}", key_file().display()))?;
std::io::Write::write_all(&mut out, &b)?;
return Ok(k);
}
}
}
/// The public key a browser subscribes with (`applicationServerKey`): the
/// uncompressed point, base64url.
pub fn public_key() -> Result<String> {
Ok(BASE64URL_NOPAD.encode(key()?.verifying_key().to_encoded_point(false).as_bytes()))
}
fn read_subs() -> Vec<Value> {
std::fs::read_to_string(subs_file()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}
/// Change the subscriptions under their lock. Read, changed and written back by hand, two at once
/// (a subscribe while a push cleans up) lost one's change, and shared one temporary file.
fn update_subs<R>(f: impl FnOnce(&mut Vec<Value>) -> Result<R>) -> Result<R> {
let mut s = crate::store::Store::<Vec<Value>>::open(subs_file())?.private();
let r = f(&mut s.data)?;
s.save()?;
Ok(r)
}
/// A browser's subscription, for an account: its push service's address. The
/// keys it also sends are for encrypting a payload, which these pushes have none of.
pub fn subscribe(account: &str, endpoint: &str) -> Result<()> {
if !endpoint.starts_with("https://") || endpoint.len() > 1000 || endpoint.contains(char::is_whitespace) {
bail!("a push subscription's endpoint is an https address");
}
update_subs(|subs| {
subs.retain(|s| s["endpoint"] != endpoint);
subs.push(json!({"account": account, "endpoint": endpoint, "at": registry::now()}));
Ok(())
})?;
events::emit("push_subscribed", json!({"actor": format!("web:{account}")}));
Ok(())
}
pub fn unsubscribe(endpoint: &str) -> Result<bool> {
update_subs(|subs| {
let before = subs.len();
subs.retain(|s| s["endpoint"] != endpoint);
Ok(subs.len() < before)
})
}
/// An account's ntfy topic, for a phone Web Push cannot reach: Firefox on an
/// Android without Google's services subscribes to nothing. The ntfy app
/// carries its own connection, so the hub posts to the topic instead, with the
/// page's address to open. Unlike a Web Push it is read by the ntfy server, so
/// it says only how many things wait, never what they are. `None` removes it.
/// A bare name is a topic on ntfy.sh, as the ntfy app takes it; the address
/// kept is returned, so the page shows what the hub will post to.
pub fn set_ntfy(account: &str, topic: Option<&str>, page: &str) -> Result<Option<String>> {
let topic = topic.map(ntfy_address).transpose()?;
let topic = topic.as_deref();
update_subs(|subs| {
subs.retain(|s| !(s["ntfy"].is_string() && s["account"] == account));
if let Some(topic) = topic {
let page = if valid_https(page) { page } else { "" };
subs.push(json!({"account": account, "ntfy": topic, "page": page, "at": registry::now()}));
}
Ok(())
})?;
if topic.is_some() {
events::emit("push_subscribed", json!({"actor": format!("web:{account}"), "via": "ntfy"}));
}
Ok(topic.map(str::to_string))
}
/// What the person typed as a topic, as the address to post to: a bare name
/// (ntfy's own rule: letters, digits, `-` and `_`, at most 64) on ntfy.sh, or
/// an https address with a topic after the host, for a server of their own.
fn ntfy_address(t: &str) -> Result<String> {
if !t.is_empty() && t.len() <= 64 && t.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
return Ok(format!("https://ntfy.sh/{t}"));
}
if ntfy_topic(t) {
return Ok(t.to_string());
}
bail!("an ntfy topic is a name of letters, digits, - and _ (a topic on ntfy.sh), or an https address ending in the topic, as https://ntfy.example.org/my-topic")
}
/// The account's ntfy topic, if it set one.
pub fn ntfy_of(account: &str) -> Option<String> {
read_subs().iter().filter(|s| s["account"] == account).find_map(|s| s["ntfy"].as_str().map(str::to_string))
}
/// An https address with a topic after the host.
fn ntfy_topic(u: &str) -> bool {
let path = u.strip_prefix("https://").and_then(|r| r.split_once('/')).map(|(_, p)| p.trim_matches('/')).unwrap_or("");
valid_https(u) && !path.is_empty()
}
fn valid_https(u: &str) -> bool {
u.starts_with("https://") && u.len() <= 1000 && !u.contains(char::is_whitespace) && audience(u).is_some()
}
/// One message to an ntfy topic: `waiting` things wait (0 for a test).
fn ntfy_send(topic: &str, page: &str, waiting: usize) -> Result<()> {
let text = match waiting {
0 => "Notifications from midas reach this topic.".to_string(),
1 => "Something waits for you on midas.".to_string(),
n => format!("{n} things wait for you on midas."),
};
let mut headers = vec!["Title: midas".to_string(), "Tags: bell".into()];
if waiting > 0 {
headers.push("Priority: high".into());
}
if !page.is_empty() {
headers.push(format!("Click: {page}"));
}
let out = crate::util::curl(&headers, &["-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "15", "--data-binary", &text, topic])?;
let code = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !code.starts_with('2') {
bail!("{} answered {code:?}", audience(topic).unwrap_or_default());
}
Ok(())
}
/// A test message to the account's topic, so the person sees it arrive.
pub fn ntfy_test(account: &str) -> Result<()> {
let subs = read_subs();
let s = subs.iter().find(|s| s["account"] == account && s["ntfy"].is_string()).ok_or_else(|| anyhow!("no ntfy topic is set"))?;
ntfy_send(s["ntfy"].as_str().unwrap_or_default(), s["page"].as_str().unwrap_or_default(), 0)
}
/// The push service's origin, which the token is for: `https://host[:port]`.
fn audience(endpoint: &str) -> Option<String> {
let rest = endpoint.strip_prefix("https://")?;
let host = rest.split('/').next().filter(|h| !h.is_empty())?;
Some(format!("https://{host}"))
}
/// A VAPID token (RFC 8292): ES256 over `{aud, exp, sub}`, good for twelve hours.
pub fn token(key: &SigningKey, aud: &str, sub: &str, now: i64) -> String {
let head = BASE64URL_NOPAD.encode(br#"{"typ":"JWT","alg":"ES256"}"#);
let claims = BASE64URL_NOPAD.encode(json!({"aud": aud, "exp": now + 12 * 3600, "sub": sub}).to_string().as_bytes());
let signed = format!("{head}.{claims}");
let sig: Signature = key.sign(signed.as_bytes());
format!("{signed}.{}", BASE64URL_NOPAD.encode(&sig.to_bytes()))
}
/// Wake every browser subscribed for one of `to`'s accounts, and tell their
/// ntfy topics that `waiting` things wait. A subscription its push service no
/// longer knows (404, 410) is dropped.
fn send_all(waiting: usize, to: &BTreeSet<String>) {
let ours = |s: &Value| to.contains(s["account"].as_str().unwrap_or(""));
for s in read_subs().iter().filter(|s| s["ntfy"].is_string() && ours(s)) {
if let Err(e) = ntfy_send(s["ntfy"].as_str().unwrap_or_default(), s["page"].as_str().unwrap_or_default(), waiting) {
events::emit("error", json!({"what": format!("a push to ntfy: {e}")}));
}
}
let Ok(k) = key() else { return };
let Ok(public) = public_key() else { return };
// Push services want a way to reach the sender: the owner's address, else a placeholder.
let sub = format!("mailto:{}", crate::conf::hub().contact.unwrap_or_else(|| "midas@localhost".into()));
let mut gone: Vec<String> = Vec::new();
let subs = read_subs();
for s in subs.iter().filter(|s| ours(s)) {
let Some(endpoint) = s["endpoint"].as_str() else { continue };
let Some(aud) = audience(endpoint) else { continue };
let jwt = token(&k, &aud, &sub, registry::now());
let headers = [format!("Authorization: vapid t={jwt}, k={public}"), "TTL: 3600".into(), "Urgency: high".into()];
let out = crate::util::curl(&headers, &["-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "15", "-X", "POST", "-H", "Content-Length: 0", endpoint]);
let code = out.ok().map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_default();
match code.as_str() {
"200" | "201" | "202" => {}
"404" | "410" => gone.push(endpoint.to_string()),
other => events::emit("error", json!({"what": format!("a push to {aud} answered {other:?}")})),
}
}
if !gone.is_empty() {
// Read again: a browser may have subscribed while the pushes went out.
let _ = update_subs(|subs| {
subs.retain(|s| !gone.iter().any(|g| s["endpoint"] == g.as_str()));
Ok(())
});
}
}
/// How long news of a landing stays among what [`needs`] lists: long enough
/// for the phone to fetch it after the push, short enough not to pile up.
const NEWS_S: i64 = 15 * 60;
/// What happened to a landing that the person follows from a phone: a session
/// that went live and finished, a landing that failed or was given up, a
/// deploy that failed. Each once, as a push: nothing told them before, and
/// they could not tell when a session would land (2026-10-31).
fn news(sessions: &Value) -> Vec<Value> {
let evs = events::read(&events::Filter {
since: chrono::Duration::seconds(NEWS_S),
kinds: ["hosted_finished", "landing_done", "deploy_failed"].map(String::from).to_vec(),
node: None, actor: None,
});
let of = |k: &str, v: &str| sessions.as_array().into_iter().flatten().find(|h| h[k] == v).cloned();
let mut out = Vec::new();
for e in evs.iter().rev() {
let at = e["ts"].as_str().unwrap_or("");
match e["kind"].as_str() {
Some("hosted_finished") if e["outcome"] == "landed" => {
let id = e["session"].as_str().unwrap_or("");
let Some(h) = of("id", id) else { continue };
out.push(json!({"key": format!("live:{id}"), "title": h["title"],
"body": "is live, and finished", "url": format!("/sessions/{id}")}));
}
Some("landing_done") if matches!(e["outcome"].as_str(), Some("failed" | "abandoned" | "conflict")) => {
let Some(h) = e["actor"].as_str().and_then(|o| of("owner", o)) else { continue };
let id = h["id"].as_str().unwrap_or("");
let why = match e["outcome"].as_str() {
Some("failed") => "did not land: the gate or the pre-land check refused it",
Some("conflict") => "did not land: the rebase onto main conflicts",
_ => "did not land: it gave up its turn",
};
out.push(json!({"key": format!("landing:{id}:{at}"), "title": h["title"], "body": why, "url": format!("/sessions/{id}")}));
}
Some("deploy_failed") => {
let target = e["target"].as_str().unwrap_or("a target");
out.push(json!({"key": format!("deploy:{}", e["deploy"].as_str().unwrap_or(at)),
"title": format!("The deploy of {target} failed"),
"body": crate::util::short(e["what"].as_str().unwrap_or("see the Workspace page"), 120), "url": "/"}));
}
_ => {}
}
}
out
}
/// What waits for the person now, each with a title, a line and where to go:
/// what the service worker shows, and what [`watch`] compares. News of
/// landings ([`news`]) first, so one alone shows as itself.
///
/// Each says whether it is `urgent`: what cannot wait for the person's next
/// decision block (focus.rs) — a session waiting for the phone, and what the
/// autopilot left them as needing them now. The rest can wait while they hold.
pub fn needs() -> Vec<Value> {
let sessions = crate::sessions::list();
// A session waiting for the phone first: it waits half a minute, not hours.
let mut out = crate::device::wanted();
for n in &mut out {
n["urgent"] = json!(true);
}
out.extend(news(&sessions));
let names = crate::collab::names();
// A session asking for root (admin.rs) waits on the person's passkey for its work.
for r in crate::admin::status()["requests"].as_array().into_iter().flatten().filter(|r| r["state"] == "asked") {
let by = r["session"].as_str().unwrap_or("a session");
let who = names[by]["label"].as_str().unwrap_or(by);
out.push(json!({
"key": format!("admin:{}", r["id"].as_str().unwrap_or("")),
"title": format!("{} asks for root", crate::util::short(who, 60)),
"body": format!("{} min: {}", r["minutes"], r["reason"].as_str().unwrap_or("")), "url": "/", "urgent": true,
}));
}
for d in crate::collab::decisions().as_array().into_iter().flatten().filter(|d| d["answer"].is_null()) {
let by = d["by"].as_str().unwrap_or("a session");
let who = names[by.strip_prefix("gate-").unwrap_or(by)]["label"].as_str().unwrap_or(by);
out.push(json!({
"key": format!("decision:{}", d["id"].as_str().unwrap_or("")),
"title": format!("{} asks you", crate::util::short(who, 60)),
"body": d["question"], "url": "/",
}));
}
for h in sessions.as_array().into_iter().flatten() {
// Something only they can do (sessions.rs, `awaits`), autopilot or not; put off, news again when
// its time comes, which is in the key.
let a = &h["awaits"];
if a.is_object() && h["archived"] != true && a["snooze"].as_i64().is_none_or(|t| t <= crate::registry::now()) {
let id = h["id"].as_str().unwrap_or("");
out.push(json!({
"key": format!("awaits:{id}:{}", a["snooze"].as_i64().unwrap_or(0)), "title": h["title"],
"body": format!("waits on you: {}", a["text"].as_str().unwrap_or("")), "url": format!("/sessions/{id}"),
}));
}
// On autopilot, it answers for them: only what it leaves to them is news.
let pilot = &h["autopilot"];
if pilot["on"] == true {
if pilot["state"] == "left" && h["archived"] != true && !matches!(h["status"].as_str(), Some("stopped" | "failed")) {
let id = h["id"].as_str().unwrap_or("");
out.push(json!({
"key": format!("autopilot:{id}"), "title": h["title"],
"body": format!("the autopilot leaves this to you: {}", pilot["left_why"].as_str().unwrap_or("it was not sure")),
"url": format!("/sessions/{id}"), "urgent": pilot["left_urgent"] != false,
}));
}
continue;
}
if h["status"] == "needs_permission" && h["archived"] != true {
let id = h["id"].as_str().unwrap_or("");
out.push(json!({
"key": format!("permission:{id}"), "title": h["title"],
"body": "waits for your answer", "url": format!("/sessions/{id}"),
}));
}
}
out
}
/// The hub's watch, every ten seconds: a push when something new waits. What
/// waited when the hub started is its baseline, not news.
pub fn watch() {
loop {
std::thread::sleep(std::time::Duration::from_secs(10));
tick();
}
}
/// Push now rather than at the watch's next tick, on a thread of its own: a
/// call is waiting for the phone the push is to bring back.
pub fn nudge() {
let _ = std::thread::Builder::new().name("push-nudge".into()).spawn(tick);
}
/// One look at what waits, and a push if something is new. One at a time, so
/// the watch and a nudge do not both push the same news.
fn tick() {
static SEEN: Mutex<Option<BTreeSet<String>>> = Mutex::new(None);
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
// Nobody to tell: no listing every session (and the names, under the registry lock)
// for nothing. The baseline goes too, so what waits when someone subscribes is not news.
if read_subs().is_empty() {
*seen = None;
return;
}
let list = needs();
let now: BTreeSet<String> = list.iter().filter_map(|n| n["key"].as_str().map(str::to_string)).collect();
let waiting = now.len();
let fresh: Vec<&Value> = match seen.as_ref() {
Some(s) => list.iter().filter(|n| n["key"].as_str().is_some_and(|k| !s.contains(k))).collect(),
None => Vec::new(),
};
*seen = Some(now);
drop(seen);
// Each person as they asked (focus.rs): while they hold, only what cannot wait; and once
// at a decision block's start, when anything waits.
let t = registry::now();
let accounts: BTreeSet<String> = read_subs().iter().map(|s| s["account"].as_str().unwrap_or("").to_string()).collect();
let to: BTreeSet<String> = accounts.into_iter().filter(|a| {
let opened = crate::focus::block_opened(a, t).is_some() && waiting > 0;
let new = if crate::focus::holding(a, t) { fresh.iter().any(|n| n["urgent"] == true) } else { !fresh.is_empty() };
opened || new
}).collect();
if !to.is_empty() {
send_all(waiting, &to);
}
}
#[cfg(test)]
mod tests {
use super::*;
use p256::ecdsa::signature::Verifier;
use p256::ecdsa::VerifyingKey;
#[test]
fn a_vapid_token_is_es256_over_the_push_services_origin() {
let key = SigningKey::from_slice(&[7u8; 32]).unwrap();
let t = token(&key, "https://fcm.googleapis.com", "mailto:a@b.c", 1000);
let parts: Vec<&str> = t.split('.').collect();
assert_eq!(parts.len(), 3);
let claims: Value = serde_json::from_slice(&BASE64URL_NOPAD.decode(parts[1].as_bytes()).unwrap()).unwrap();
assert_eq!(claims, json!({"aud": "https://fcm.googleapis.com", "exp": 1000 + 12 * 3600, "sub": "mailto:a@b.c"}));
let sig = Signature::from_slice(&BASE64URL_NOPAD.decode(parts[2].as_bytes()).unwrap()).unwrap();
let vk = VerifyingKey::from(&key);
assert!(vk.verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &sig).is_ok());
assert_eq!(audience("https://updates.push.services.mozilla.com/wpush/v2/abc").as_deref(), Some("https://updates.push.services.mozilla.com"));
assert_eq!(audience("http://x/y"), None);
}
#[test]
fn an_ntfy_topic_is_an_https_address_with_a_topic() {
assert!(ntfy_topic("https://ntfy.sh/midas-abc"));
assert!(ntfy_topic("https://ntfy.example.org:8443/a/"));
assert!(!ntfy_topic("https://ntfy.sh"));
assert!(!ntfy_topic("https://ntfy.sh/"));
assert!(!ntfy_topic("http://ntfy.sh/midas"));
assert!(!ntfy_topic("https://ntfy.sh/a b"));
}
#[test]
fn a_bare_ntfy_name_is_a_topic_on_ntfy_sh() {
assert_eq!(ntfy_address("midas_x-7").unwrap(), "https://ntfy.sh/midas_x-7");
assert_eq!(ntfy_address("https://ntfy.example.org/a").unwrap(), "https://ntfy.example.org/a");
assert!(ntfy_address("ntfy.sh/a").is_err());
assert!(ntfy_address("a b").is_err());
assert!(ntfy_address(&"a".repeat(65)).is_err());
}
}