kanzo 0.4.3

Self-hosted kanban for humans and agents. One 5.0 MB binary, starts in 3 ms, zero setup.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Web Push: when an agent escalates a task, this computer's Kanzo tells each browser here that
//! turned notifications on, even with no board page open. The push carries nothing. The
//! browser's service worker wakes up and asks this Kanzo for the tasks, so nothing about them
//! goes through the push service of the browser's maker. Each request is signed with this
//! computer's VAPID key (ES256) and sent with curl, which the updater already uses.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::process::Command;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use p256::ecdsa::signature::Signer;
use p256::ecdsa::{Signature, SigningKey};
use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;

use crate::home::Home;
use crate::share::{self, Net};
use crate::store::{self, Error};

/// The key and the browsers, in the data folder. kanzo sync leaves it out, with its temporary
/// copy: another computer with these browsers would push each escalation a second time, and
/// the key is this one's.
pub const FILE: &str = "push.json";

/// Who the push services can contact about these requests: Kanzo, not the person using it.
const SUBJECT: &str = "https://github.com/emanuele-em/kanzo";

/// How often the board checks for new escalations on its own board while a browser wants them.
/// Each check reads kanzo.db's 4-byte change counter; only a change opens the board.
const WATCH_EVERY: Duration = Duration::from_secs(2);

/// Escalations kept for a browser that hasn't fetched them, as when it's asleep.
const PENDING_MAX: usize = 20;

/// Browsers kept, the latest first. Anyone the board answers could add one.
const BROWSERS_MAX: usize = 10;

/// The languages the service worker has the notification's words in.
const LANGS: [&str; 2] = ["en", "zh-cn"];

/// A token lives 12 hours and is reused until its last hour: Apple asks not to make a new one
/// more often than once an hour.
const TOKEN_LIFE: u64 = 12 * 3600;
const TOKEN_REUSE: u64 = 11 * 3600;

#[derive(Clone, Default, Serialize, Deserialize)]
struct Saved {
    /// The VAPID private key, 32 bytes in base64url, made the first time a browser asks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    key: Option<String>,
    #[serde(default)]
    browsers: Vec<Browser>,
    /// Endpoints their push service refused, the latest last. A page that signs one up again
    /// is told to make a new subscription: this one would only be refused again.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    gone: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Browser {
    /// Where its push service takes pushes for it. Only that browser can read them.
    pub endpoint: String,
    /// The board's language in it, for the notification's words.
    #[serde(default)]
    pub lang: String,
}

#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Escalation {
    pub id: i64,
    pub project: String,
    pub title: String,
    /// On the shared board this computer joined, which the board's page shows under @.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub shared: bool,
}

#[derive(Serialize)]
pub struct Pending {
    pub lang: String,
    pub tasks: Vec<Escalation>,
}

pub struct Push {
    file: PathBuf,
    saved: Mutex<Saved>,
    /// What each browser hasn't fetched yet, by endpoint.
    pending: Mutex<HashMap<String, Vec<Escalation>>>,
    /// The token for each push service, by origin, with when it expires.
    tokens: Mutex<HashMap<String, (u64, String)>>,
    /// Failures already said, so a push service that keeps refusing is said once.
    warned: Mutex<HashSet<String>>,
}

fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(PoisonError::into_inner)
}

impl Push {
    pub fn load(home: &Home) -> Self {
        let file = home.dir.join(FILE);
        let saved = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
        Self {
            file,
            saved: Mutex::new(saved),
            pending: Mutex::default(),
            tokens: Mutex::default(),
            warned: Mutex::default(),
        }
    }

    /// Readable only by this user: it holds the private key. Written beside it, then renamed.
    fn save(&self, saved: &Saved) -> store::Result<()> {
        let text = serde_json::to_vec_pretty(saved).map_err(|e| Error::Invalid(e.to_string()))?;
        let temp = self.file.with_extension("json.tmp");
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create(true).truncate(true);
        #[cfg(unix)]
        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
        let written = options.open(&temp).and_then(|mut f| std::io::Write::write_all(&mut f, &text));
        let saved = written.and_then(|()| std::fs::rename(&temp, &self.file));
        saved.map_err(|e| Error::Invalid(format!("cannot save {FILE}: {e}")))
    }

    /// This computer's VAPID public key, which a browser subscribes with. Made the first time,
    /// and used only once it's saved, so a restart never brings a different one.
    pub fn public_key(&self) -> store::Result<String> {
        let mut saved = lock(&self.saved);
        if signing_key(&saved).is_none() {
            let mut secret = [0; 32];
            // Almost every 32 bytes is a valid key; the rest are tried again.
            while SigningKey::from_slice(&secret).is_err() {
                getrandom::fill(&mut secret).map_err(|e| Error::Invalid(format!("cannot make a key: {e}")))?;
            }
            let next = Saved { key: Some(B64.encode(secret)), ..saved.clone() };
            self.save(&next)?;
            *saved = next;
        }
        let key = signing_key(&saved).expect("made above");
        Ok(B64.encode(key.verifying_key().to_sec1_point(false).as_bytes()))
    }

    /// Adds a browser, or updates its language. A page says it on every load: unchanged, the
    /// file isn't written. False, adding nothing, for an endpoint its push service refused.
    pub fn add(&self, mut browser: Browser) -> store::Result<bool> {
        if !browser.endpoint.starts_with("https://") || browser.endpoint.len() > 2048 {
            return Err(Error::Invalid("a push endpoint is an https URL".into()));
        }
        if !LANGS.contains(&browser.lang.as_str()) {
            browser.lang = LANGS[0].into();
        }
        let mut saved = lock(&self.saved);
        if saved.gone.contains(&browser.endpoint) {
            return Ok(false);
        }
        if saved.browsers.last() == Some(&browser) {
            return Ok(true);
        }
        let mut next = saved.clone();
        next.browsers.retain(|b| b.endpoint != browser.endpoint);
        next.browsers.push(browser);
        let extra = next.browsers.len().saturating_sub(BROWSERS_MAX);
        next.browsers.drain(..extra);
        self.save(&next)?;
        *saved = next;
        Ok(true)
    }

    /// The browser turned notifications off.
    pub fn remove(&self, endpoint: &str) -> store::Result<()> {
        self.discard(endpoint, false)
    }

    /// Its push service no longer knows the browser, so the browser must subscribe again.
    fn refused(&self, endpoint: &str) -> store::Result<()> {
        self.discard(endpoint, true)
    }

    fn discard(&self, endpoint: &str, refused: bool) -> store::Result<()> {
        lock(&self.pending).remove(endpoint);
        let mut saved = lock(&self.saved);
        if !saved.browsers.iter().any(|b| b.endpoint == endpoint) {
            return Ok(());
        }
        let mut next = saved.clone();
        next.browsers.retain(|b| b.endpoint != endpoint);
        if refused {
            next.gone.push(endpoint.into());
            let extra = next.gone.len().saturating_sub(BROWSERS_MAX);
            next.gone.drain(..extra);
        }
        self.save(&next)?;
        *saved = next;
        Ok(())
    }

    pub fn is_empty(&self) -> bool {
        lock(&self.saved).browsers.is_empty()
    }

    /// What a browser's service worker shows: its escalations since it last asked.
    pub fn take(&self, endpoint: &str) -> Pending {
        let lang = lock(&self.saved).browsers.iter().find(|b| b.endpoint == endpoint).map(|b| b.lang.clone());
        let tasks = lock(&self.pending).remove(endpoint).unwrap_or_default();
        Pending { lang: lang.unwrap_or_default(), tasks }
    }

    /// Keeps the escalations for each browser and wakes it. A browser its push service no
    /// longer knows, as after it unsubscribed or was reset, is forgotten.
    pub fn notify(self: &Arc<Self>, fresh: &[Escalation]) {
        let (key, browsers) = {
            let saved = lock(&self.saved);
            (signing_key(&saved), saved.browsers.clone())
        };
        let Some(key) = key else { return };
        let mut pending = lock(&self.pending);
        for b in &browsers {
            let queue = pending.entry(b.endpoint.clone()).or_default();
            queue.extend(fresh.iter().cloned());
            let extra = queue.len().saturating_sub(PENDING_MAX);
            queue.drain(..extra);
        }
        drop(pending);
        let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs());
        for b in browsers {
            let Some(auth) = self.authorization(&key, &b.endpoint, now) else { continue };
            let push = self.clone();
            std::thread::spawn(move || match send(&curl_args(&b.endpoint, &auth)) {
                Ok(code) if forget(code) => {
                    push.warn(&b.endpoint, &format!("HTTP {code}; it subscribes again when it next opens the board"));
                    let _ = push.refused(&b.endpoint);
                }
                Ok(code) if !(200..300).contains(&code) => push.warn(&b.endpoint, &format!("HTTP {code}")),
                Ok(_) => {}
                Err(why) => push.warn(&b.endpoint, &why),
            });
        }
    }

    /// The Authorization header for the push service at `endpoint`, its token reused for 11 hours.
    fn authorization(&self, key: &SigningKey, endpoint: &str, now: u64) -> Option<String> {
        let origin = origin(endpoint)?;
        let mut tokens = lock(&self.tokens);
        let token = match tokens.get(&origin) {
            Some((expires, token)) if *expires > now + (TOKEN_LIFE - TOKEN_REUSE) => token.clone(),
            _ => {
                let token = token(key, &origin, now + TOKEN_LIFE);
                tokens.insert(origin, (now + TOKEN_LIFE, token.clone()));
                token
            }
        };
        let public = B64.encode(key.verifying_key().to_sec1_point(false).as_bytes());
        Some(format!("Authorization: vapid t={token}, k={public}"))
    }

    fn warn(&self, endpoint: &str, why: &str) {
        let service = origin(endpoint).unwrap_or_default();
        if lock(&self.warned).insert(format!("{service} {why}")) {
            eprintln!("kanzo: cannot notify a browser through {service}: {why}");
        }
    }
}

fn signing_key(saved: &Saved) -> Option<SigningKey> {
    SigningKey::from_slice(&B64.decode(saved.key.as_deref()?).ok()?).ok()
}

/// The scheme and host of an https endpoint, port included: a token's audience.
fn origin(endpoint: &str) -> Option<String> {
    let rest = endpoint.strip_prefix("https://")?;
    Some(format!("https://{}", rest.split('/').next()?))
}

/// A VAPID token for the push service at `audience`, until `expires`.
fn token(key: &SigningKey, audience: &str, expires: u64) -> String {
    let claims = serde_json::json!({ "aud": audience, "exp": expires, "sub": SUBJECT });
    let unsigned = format!("{}.{}", B64.encode(r#"{"typ":"JWT","alg":"ES256"}"#), B64.encode(claims.to_string()));
    let signature: Signature = key.sign(unsigned.as_bytes());
    format!("{unsigned}.{}", B64.encode(signature.to_bytes()))
}

/// curl's arguments for an empty push to `endpoint`.
fn curl_args(endpoint: &str, auth: &str) -> Vec<String> {
    let null = if cfg!(windows) { "NUL" } else { "/dev/null" };
    let args = [
        // An endpoint comes from a browser: taken as it is, never as a pattern, and only over https.
        "-g",
        "--proto",
        "=https",
        "-sS",
        "--max-time",
        "20",
        "-o",
        null,
        "-w",
        "%{http_code}",
        "-X",
        "POST",
        // A day to reach a browser that's closed, high so a sleeping device doesn't hold it back,
        // and one topic, so a newer push replaces one it hasn't delivered yet.
        "-H",
        "TTL: 86400",
        "-H",
        "Urgency: high",
        "-H",
        "Topic: kanzo",
        "-H",
        "Content-Type:",
        "-H",
        auth,
        "--data-binary",
        "",
        endpoint,
    ];
    args.iter().map(|a| a.to_string()).collect()
}

/// The push service's answer, or why there was none.
fn send(args: &[String]) -> Result<u16, String> {
    let out = Command::new("curl").args(args).output().map_err(|e| format!("cannot run curl: {e}"))?;
    let code = String::from_utf8_lossy(&out.stdout).trim().parse().unwrap_or(0);
    if code == 0 {
        return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
    }
    Ok(code)
}

/// The push service no longer knows the browser, as after it unsubscribed.
fn forget(code: u16) -> bool {
    matches!(code, 404 | 410)
}

/// The tasks escalated now on the board this computer follows: the shared one it joined, or
/// else its own. None if they couldn't be read.
pub async fn escalated_now(home: &Home) -> Option<Vec<Escalation>> {
    if let Net::Joined(host) = Net::load(home) {
        let tasks = share::escalated(&host).await.ok()?;
        return Some(
            tasks.into_iter().map(|(id, project, title)| Escalation { id, project, title, shared: true }).collect(),
        );
    }
    let h = home.clone();
    let tasks = tokio::task::spawn_blocking(move || h.store().ok()?.escalated().ok()).await.ok()??;
    Some(tasks.into_iter().map(|(id, project, title)| Escalation { id, project, title, shared: false }).collect())
}

/// The escalations among `now` that weren't there before. The first look only learns them.
fn news(known: &mut Option<HashSet<(bool, i64)>>, now: Vec<Escalation>) -> Vec<Escalation> {
    let ids = now.iter().map(|e| (e.shared, e.id)).collect();
    let fresh = match known.as_ref() {
        Some(k) => now.into_iter().filter(|e| !k.contains(&(e.shared, e.id))).collect(),
        None => Vec::new(),
    };
    *known = Some(ids);
    fresh
}

/// What the watcher follows: its own board's file, or the events of the shared board it joined.
#[derive(PartialEq)]
enum Follow {
    Own(Option<(u64, Option<[u8; 4]>)>),
    Shared(String, Option<String>),
}

/// Waits `d`, or until the board stops: true if it stopped.
async fn pause(shutdown: &CancellationToken, d: Duration) -> bool {
    tokio::select! {
        _ = tokio::time::sleep(d) => false,
        _ = shutdown.cancelled() => true,
    }
}

/// While a browser wants them, looks for new escalations and pushes them. On its own board it
/// checks every 2 seconds; on a shared board it joined, it waits on that board's /api/events,
/// which answers as soon as the board changes. With no browser subscribed it reads nothing, and
/// the next one to subscribe starts from what is escalated then.
pub async fn watch(push: Arc<Push>, home: Home, shutdown: CancellationToken) {
    let (mut known, mut follow) = (None, Follow::Own(None));
    loop {
        if push.is_empty() {
            (known, follow) = (None, Follow::Own(None));
            if pause(&shutdown, WATCH_EVERY).await {
                return;
            }
            continue;
        }
        // Joining or leaving a board starts over on the other one.
        let net = Net::load(&home);
        let wanted = match &net {
            Net::Joined(host) => matches!(&follow, Follow::Shared(h, _) if h == host),
            _ => matches!(follow, Follow::Own(_)),
        };
        if !wanted {
            known = None;
            follow = match net {
                Net::Joined(host) => Follow::Shared(host, None),
                _ => Follow::Own(None),
            };
        }
        let mut seen = None;
        let changed = match &mut follow {
            Follow::Own(stamp) => {
                if pause(&shutdown, WATCH_EVERY).await {
                    return;
                }
                let now = home.db_stamp();
                seen = Some(now);
                *stamp != Some(now)
            }
            Follow::Shared(host, cursor) => {
                let path = cursor.as_ref().map_or("/api/events".into(), |c| format!("/api/events?since={c}&wait=25"));
                let reply = tokio::select! {
                    r = share::get_json(host, &path) => r,
                    _ = shutdown.cancelled() => return,
                };
                match reply {
                    Ok(reply) => {
                        let first = cursor.is_none();
                        *cursor = reply["last"].as_str().map(String::from);
                        // After a comment there's nothing to look at: only a move or an edit escalates.
                        let kinds = reply["events"].as_array().into_iter().flatten().filter_map(|e| e["kind"].as_str());
                        first
                            || reply["reset"] == true
                            || kinds.into_iter().any(|k| k == "task.moved" || k == "task.updated")
                    }
                    Err(_) => {
                        // The shared board is away: try again in a while, from where it was.
                        if pause(&shutdown, WATCH_EVERY * 5).await {
                            return;
                        }
                        false
                    }
                }
            }
        };
        if !changed {
            continue;
        }
        // A read that fails, as while kanzo sync holds the board, is tried again next time.
        let Some(now) = escalated_now(&home).await else { continue };
        if let (Follow::Own(stamp), Some(s)) = (&mut follow, seen) {
            *stamp = Some(s);
        }
        let fresh = news(&mut known, now);
        if !fresh.is_empty() {
            push.notify(&fresh);
        }
    }
}

#[cfg(test)]
mod tests {
    use p256::ecdsa::VerifyingKey;
    use p256::ecdsa::signature::Verifier;

    use super::*;

    fn push() -> (tempfile::TempDir, Push) {
        let tmp = tempfile::tempdir().unwrap();
        let home = Home::open(tmp.path().to_path_buf()).unwrap();
        let push = Push::load(&home);
        (tmp, push)
    }

    fn browser(endpoint: &str) -> Browser {
        Browser { endpoint: endpoint.into(), lang: "en".into() }
    }

    fn escalation(id: i64) -> Escalation {
        Escalation { id, project: "api".into(), title: format!("Task {id}"), shared: false }
    }

    #[test]
    fn a_token_is_es256_for_the_push_services_origin_and_lasts_hours() {
        let (_tmp, push) = push();
        let public = push.public_key().unwrap();
        let key = signing_key(&lock(&push.saved)).unwrap();
        let header = push.authorization(&key, "https://fcm.googleapis.com/fcm/send/abc:def", 1_000).unwrap();
        let jwt = header.strip_prefix("Authorization: vapid t=").unwrap().split(',').next().unwrap();
        assert!(header.ends_with(&format!(", k={public}")), "{header}");
        let parts: Vec<&str> = jwt.split('.').collect();
        let claims: serde_json::Value = serde_json::from_slice(&B64.decode(parts[1]).unwrap()).unwrap();
        assert_eq!(claims["aud"], "https://fcm.googleapis.com");
        assert_eq!((claims["exp"].as_u64(), claims["sub"].as_str()), (Some(1_000 + TOKEN_LIFE), Some(SUBJECT)));
        let verifying = VerifyingKey::from_sec1_bytes(&B64.decode(&public).unwrap()).unwrap();
        let signature = Signature::from_slice(&B64.decode(parts[2]).unwrap()).unwrap();
        assert!(verifying.verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature).is_ok());

        let again = |at| push.authorization(&key, "https://fcm.googleapis.com/fcm/send/other", at).unwrap();
        assert_eq!(again(1_000 + 3_600), header, "reused for the same push service");
        assert_ne!(again(1_000 + TOKEN_REUSE + 1), header, "a new one in its last hour");
        assert_eq!(push.authorization(&key, "http://push.example/x", 1), None, "only https");
        assert_eq!(origin("https://push.example:8443/a/b").as_deref(), Some("https://push.example:8443"));
    }

    #[test]
    fn a_push_is_empty_with_a_topic_and_never_a_curl_pattern() {
        let args = curl_args("https://push.example/[1-1000]", "Authorization: vapid t=x, k=y");
        let has = |pair: [&str; 2]| args.windows(2).any(|w| w[0] == pair[0] && w[1] == pair[1]);
        assert!(args.contains(&"-g".to_string()), "{args:?}");
        assert!(has(["--proto", "=https"]) && has(["--data-binary", ""]));
        for header in ["TTL: 86400", "Urgency: high", "Topic: kanzo", "Content-Type:", "Authorization: vapid t=x, k=y"]
        {
            assert!(has(["-H", header]), "{header}");
        }
        assert_eq!(args.last().unwrap(), "https://push.example/[1-1000]");
        assert!(forget(404) && forget(410) && !forget(201) && !forget(429));
    }

    #[test]
    fn the_key_and_browsers_last_and_only_this_user_reads_them() {
        let (tmp, push) = push();
        let public = push.public_key().unwrap();
        assert_eq!(public.len(), 87, "65 bytes, uncompressed");
        push.add(browser("https://push.example/a")).unwrap();
        push.add(Browser { endpoint: "https://push.example/a".into(), lang: "zh-cn".into() }).unwrap();
        push.add(Browser { endpoint: "https://push.example/b".into(), lang: "fr".into() }).unwrap();
        assert!(push.add(browser("http://push.example/c")).is_err());

        let home = Home::open(tmp.path().to_path_buf()).unwrap();
        let again = Push::load(&home);
        assert_eq!(again.public_key().unwrap(), public, "the same key after a restart");
        assert_eq!(lock(&again.saved).browsers.len(), 2);
        assert_eq!(again.take("https://push.example/a").lang, "zh-cn");
        assert_eq!(again.take("https://push.example/b").lang, "en", "a language it has no words in");
        again.remove("https://push.example/a").unwrap();
        assert!(Push::load(&home).take("https://push.example/a").lang.is_empty());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(tmp.path().join(FILE)).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }

        // The same browser again writes nothing; only the latest ten are kept.
        let written = std::fs::metadata(tmp.path().join(FILE)).unwrap().modified().unwrap();
        std::thread::sleep(Duration::from_millis(20));
        again.add(browser("https://push.example/b")).unwrap();
        assert_eq!(std::fs::metadata(tmp.path().join(FILE)).unwrap().modified().unwrap(), written);
        for i in 0..15 {
            again.add(browser(&format!("https://push.example/{i}"))).unwrap();
        }
        let kept: Vec<String> = lock(&again.saved).browsers.iter().map(|b| b.endpoint.clone()).collect();
        assert_eq!((kept.len(), kept[0].as_str()), (BROWSERS_MAX, "https://push.example/5"));
    }

    #[test]
    fn a_subscription_its_push_service_refused_is_renewed() {
        let (tmp, push) = push();
        assert!(push.add(browser("https://push.example/a")).unwrap());
        push.refused("https://push.example/a").unwrap();
        assert!(push.is_empty());

        // Even after a restart, the page that sends it again is told to make a new one.
        let again = Push::load(&Home::open(tmp.path().to_path_buf()).unwrap());
        assert!(!again.add(browser("https://push.example/a")).unwrap());
        assert!(again.is_empty());
        assert!(again.add(browser("https://push.example/b")).unwrap(), "its new one");
        again.remove("https://push.example/b").unwrap();
        assert!(again.add(browser("https://push.example/b")).unwrap(), "turned off is not refused");

        for i in 0..15 {
            again.add(browser(&format!("https://push.example/{i}"))).unwrap();
            again.refused(&format!("https://push.example/{i}")).unwrap();
        }
        let gone = lock(&again.saved).gone.clone();
        assert_eq!((gone.len(), gone[0].as_str()), (BROWSERS_MAX, "https://push.example/5"), "the latest ten");
    }

    #[test]
    fn a_browser_gets_each_escalation_once_and_at_most_twenty() {
        let (_tmp, push) = push();
        let push = Arc::new(push);
        // No key yet, so nothing is queued or sent.
        lock(&push.saved).browsers.push(browser("https://127.0.0.1:9/never"));
        push.notify(&[escalation(1)]);
        assert!(push.take("https://127.0.0.1:9/never").tasks.is_empty());

        push.public_key().unwrap();
        push.notify(&(1..=25).map(escalation).collect::<Vec<_>>());
        let kept = push.take("https://127.0.0.1:9/never").tasks;
        assert_eq!((kept.len(), kept[0].id), (PENDING_MAX, 6), "the latest twenty");
        assert!(push.take("https://127.0.0.1:9/never").tasks.is_empty(), "taken once");
    }

    #[test]
    fn only_new_escalations_count_and_the_first_look_learns() {
        let tmp = tempfile::tempdir().unwrap();
        let home = Home::open(tmp.path().to_path_buf()).unwrap();
        let s = home.store().unwrap();
        let p = s.create_project("api", "", None).unwrap();
        let escalate = |id: i64| {
            let patch = store::TaskPatch { escalated: Some(true), ..Default::default() };
            s.update_task(id, patch).unwrap();
        };
        let now = || {
            let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
            rt.block_on(escalated_now(&home)).unwrap()
        };
        let old = s.create_task(p.id, "Old", "").unwrap().id;
        escalate(old);
        let mut known = None;
        assert!(news(&mut known, now()).is_empty(), "learns what is there");
        let new = s.create_task(p.id, "New", "").unwrap().id;
        escalate(new);
        let fresh = news(&mut known, now());
        assert_eq!(fresh, [Escalation { id: new, project: "api".into(), title: "New".into(), shared: false }]);
        assert!(news(&mut known, now()).is_empty());
        s.move_task(old, "doing", None).unwrap();
        assert!(news(&mut known, now()).is_empty(), "a move ends it");
        escalate(old);
        assert_eq!(news(&mut known, now()).len(), 1, "escalated again is new again");
        let mut shared = now();
        shared.iter_mut().for_each(|e| e.shared = true);
        assert_eq!(news(&mut known, shared).len(), 2, "the shared board's tasks are others");
    }
}