1use std::collections::HashMap;
6use std::sync::Arc;
7
8use nostr_sdk::prelude::*;
9use serde::de::DeserializeOwned;
10use serde::{Deserialize, Serialize};
11pub use vector_push::ticket::TicketList;
12pub use vector_push::{Notice, Ticket};
13
14use crate::db::settings::{get_sql_setting, remove_setting, set_sql_setting};
15use crate::event_ext::FinalizeUnsignedWithId;
16use crate::tags::TagsExt;
17use crate::ClientRelayExt;
18use crate::state::{my_public_key, nostr_client, STATE};
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct Device {
23 pub id: String,
25 pub endpoint: String,
26 pub p256dh: String,
27 pub auth: String,
28 pub vapid: String,
30 pub origin: String,
31}
32
33pub async fn adopt(dev: Device) -> Result<(), String> {
36 let fresh = device().as_ref() != Some(&dev);
37 set_device(dev).await?;
38 if fresh {
39 let recent = recent_contacts().await;
40 prepare(&recent).await?;
41 crate::db::spawn_bound(async move {
42 for npub in recent {
43 match share_with(&npub).await {
44 Ok(true) => crate::rt::time::sleep(std::time::Duration::from_millis(1500)).await,
45 Ok(false) => {}
46 Err(e) => crate::log_warn!("[Push] ticket to {}: {}", npub, e),
47 }
48 }
49 });
50 }
51 controls_changed();
53 Ok(())
54}
55
56async fn recent_contacts() -> Vec<String> {
57 let state = STATE.lock().await;
58 let mut chats: Vec<(u64, String)> = state
59 .chats
60 .iter()
61 .filter(|c| matches!(c.chat_type(), crate::ChatType::DirectMessage))
62 .filter(|c| !state.get_profile(c.id()).is_some_and(|p| p.flags.is_blocked()))
63 .map(|c| (c.last_message_time().unwrap_or(0), c.id().clone()))
64 .collect();
65 chats.sort_by(|a, b| b.0.cmp(&a.0));
66 chats.into_iter().take(RECENT_CONTACTS).map(|(_, id)| id).collect()
67}
68
69pub fn receive(message: &[u8]) -> Option<(String, Notice)> {
72 let v: serde_json::Value = serde_json::from_slice(message).ok()?;
73 let d = &v["notification"]["data"];
74 let notice = Notice {
75 h: d["h"].as_str()?.to_string(),
76 kind: d["k"].as_str()?.to_string(),
77 msg: d["m"].as_str()?.to_string(),
78 ts: d["t"].as_u64()?,
79 text: d["x"].as_str().unwrap_or_default().to_string(),
80 };
81 let mac = d["a"].as_str()?;
82 let issued: HashMap<String, Issued> = load(ISSUED_KEY);
83 let (npub, i) = issued.iter().find(|(_, i)| i.h == notice.h)?;
84 let mk = crate::simd::hex::hex_to_bytes_32_checked(&i.mk)?;
85 (notice.mac(&mk).ok()? == mac).then(|| (npub.clone(), notice))
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
90struct Issued {
91 cap: String,
92 h: String,
93 mk: String,
94 #[serde(default)]
96 sent: String,
97 #[serde(default)]
99 held: u64,
100}
101
102const DEVICE_KEY: &str = "push_device";
103const ISSUED_KEY: &str = "push_issued";
104const HELD_KEY: &str = "push_held";
105const MAX_TICKETS_PER_CONTACT: usize = 8;
107const SEND_JITTER_MS: u64 = 4000;
109const TTL: u32 = 2 * 24 * 3600;
111#[cfg(feature = "calls")]
113const CALL_TTL: u32 = 60;
114
115const RECENT_CONTACTS: usize = 30;
118
119struct PushLock;
121fn lock() -> Arc<tokio::sync::Mutex<()>> {
122 crate::db::current_session().scoped::<PushLock, _>()
123}
124
125fn load<T: DeserializeOwned + Default>(key: &str) -> T {
126 get_sql_setting(key.into()).ok().flatten().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
127}
128
129fn save<T: Serialize>(key: &str, value: &T) -> Result<(), String> {
130 set_sql_setting(key.into(), serde_json::to_string(value).map_err(|e| e.to_string())?)
131}
132
133fn random_hex<const N: usize>() -> String {
134 use rand::RngCore;
135 let mut b = [0u8; N];
136 rand::thread_rng().fill_bytes(&mut b);
137 crate::simd::hex::bytes_to_hex_string(&b)
138}
139
140pub fn device() -> Option<Device> {
145 load::<Option<Device>>(DEVICE_KEY)
146}
147
148pub async fn set_device(device: Device) -> Result<(), String> {
151 let _g = lock().lock_owned().await;
152 save(DEVICE_KEY, &Some(device))
153}
154
155pub async fn disable() -> Result<(), String> {
157 let (old, issued) = {
158 let _g = lock().lock_owned().await;
159 let old = device();
160 let issued: HashMap<String, Issued> = load(ISSUED_KEY);
161 remove_setting(DEVICE_KEY)?;
162 remove_setting(ISSUED_KEY)?;
163 (old, issued)
164 };
165 let Some(old) = old else { return Ok(()) };
166 let holders: Vec<String> = issued.into_iter().filter(|(_, i)| i.sent.starts_with(&old.id)).map(|(npub, _)| npub).collect();
167 crate::db::spawn_bound(async move {
168 let list = TicketList { v: 1, tickets: vec![], revoked: vec![old.id] };
169 for npub in holders {
170 if let Err(e) = send_list(&npub, &list).await {
171 crate::log_warn!("[Push] revoking at {}: {}", npub, e);
172 }
173 }
174 });
175 Ok(())
176}
177
178pub async fn share_with(npub: &str) -> Result<bool, String> {
181 let Some(device) = device() else { return Ok(false) };
182 if my_public_key().and_then(|pk| pk.to_bech32().ok()).as_deref() == Some(npub) || is_blocked(npub).await {
183 return Ok(false);
184 }
185 let ticket = {
186 let _g = lock().lock_owned().await;
187 let mut issued: HashMap<String, Issued> = load(ISSUED_KEY);
188 let version = ticket_version(&device);
189 if issued.get(npub).is_some_and(|i| i.sent == version) {
190 return Ok(false);
191 }
192 let fresh = !issued.contains_key(npub);
193 let entry = issued.entry(npub.to_string()).or_insert_with(new_issued);
194 let ticket = mint(&device, entry)?;
195 save(ISSUED_KEY, &issued)?;
196 if fresh {
197 crate::emit_event("push_contacts_changed", &serde_json::json!({}));
198 controls_changed();
200 }
201 ticket
202 };
203 send_list(npub, &TicketList { v: 1, tickets: vec![ticket], revoked: vec![] }).await?;
204 let _g = lock().lock_owned().await;
205 let mut issued: HashMap<String, Issued> = load(ISSUED_KEY);
206 if let Some(i) = issued.get_mut(npub) {
207 i.sent = ticket_version(&device);
208 }
209 save(ISSUED_KEY, &issued)?;
210 Ok(true)
211}
212
213fn new_issued() -> Issued {
214 Issued { cap: random_hex::<16>(), h: random_hex::<8>(), mk: random_hex::<32>(), sent: String::new(), held: 0 }
215}
216
217pub async fn prepare(npubs: &[String]) -> Result<(), String> {
220 let _g = lock().lock_owned().await;
221 let mut issued: HashMap<String, Issued> = load(ISSUED_KEY);
222 for npub in npubs {
223 issued.entry(npub.clone()).or_insert_with(new_issued);
224 }
225 save(ISSUED_KEY, &issued)
226}
227
228fn ticket_version(device: &Device) -> String {
231 let (key, relays) = pusher();
232 format!("{}|{}|{}", device.id, &key[..16], relays.join(","))
233}
234
235fn pusher() -> (&'static str, Vec<String>) {
238 let key = option_env!("VECTOR_PUSHER").unwrap_or(vector_push::DEFAULT_PUSHER);
239 let relays = match option_env!("VECTOR_PUSHER_RELAYS") {
240 Some(r) => r.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),
241 None => vector_push::DEFAULT_PUSHER_RELAYS.iter().map(|r| r.to_string()).collect(),
242 };
243 (key, relays)
244}
245
246fn mint(device: &Device, issued: &Issued) -> Result<Ticket, String> {
247 let (key, relays) = pusher();
248 let pusher = PublicKey::from_hex(key).map_err(|e| e.to_string())?;
249 let cap = vector_push::Capability { endpoint: device.endpoint.clone(), vapid: device.vapid.clone(), cap: issued.cap.clone() };
250 Ok(Ticket {
251 id: device.id.clone(),
252 pusher: key.to_string(),
253 relays,
254 sealed: vector_push::ticket::seal(&pusher, &cap).map_err(|e| e.to_string())?,
255 p256dh: device.p256dh.clone(),
256 auth: device.auth.clone(),
257 origin: device.origin.clone(),
258 h: issued.h.clone(),
259 mk: issued.mk.clone(),
260 })
261}
262
263async fn send_list(npub: &str, list: &TicketList) -> Result<(), String> {
264 let client = nostr_client().ok_or("Not connected")?;
265 let me = my_public_key().ok_or("Not logged in")?;
266 let to = PublicKey::from_bech32(npub).map_err(|e| e.to_string())?;
267 let rumor = EventBuilder::new(Kind::ApplicationSpecificData, serde_json::to_string(list).map_err(|e| e.to_string())?)
268 .tag(Tag::public_key(to))
269 .tag(Tag::identifier(vector_push::TICKET_RUMOR_D))
270 .finalize_unsigned_with_id(me);
271 let out = crate::inbox_relays::send_gift_wrap(&client, &to, rumor, []).await?;
272 if out.success.is_empty() {
273 return Err("no relay took the ticket".into());
274 }
275 Ok(())
276}
277
278pub async fn worker_contacts() -> serde_json::Value {
281 let issued: HashMap<String, Issued> = {
282 let _g = lock().lock_owned().await;
283 load(ISSUED_KEY)
284 };
285 let gate = crate::notify::StreamGate::load();
286 let state = STATE.lock().await;
287 let mut out = serde_json::Map::new();
288 for (npub, i) in issued {
289 let fallback = format!("{}…", &npub[..npub.len().min(12)]);
290 let name = crate::notify::sender(&state, &gate, &npub, &fallback).name;
291 out.insert(i.h, serde_json::json!({ "npub": npub, "name": name, "mk": i.mk }));
292 }
293 serde_json::Value::Object(out)
294}
295
296const VIEWING_LEASE: u64 = 45;
303
304struct Viewing;
306fn viewing_slot() -> Arc<std::sync::Mutex<Option<(String, u64)>>> {
307 crate::db::current_session().scoped::<Viewing, _>()
308}
309
310fn now_secs() -> u64 {
311 crate::clock::now_secs()
312}
313
314async fn is_blocked(npub: &str) -> bool {
315 STATE.lock().await.get_profile(npub).is_some_and(|p| p.flags.is_blocked())
316}
317
318pub async fn viewing(npub: Option<String>) -> Result<(), String> {
320 *viewing_slot().lock().unwrap() = npub.map(|n| (n, now_secs() + VIEWING_LEASE));
321 reconcile_holds().await
322}
323
324async fn wanted_hold(npub: &str, now: u64) -> u64 {
327 if is_blocked(npub).await {
328 return vector_push::HOLD_FOREVER;
329 }
330 let mute = crate::notify::prefs(npub).mute_until;
331 let muted = match mute {
332 -1 => vector_push::HOLD_FOREVER,
333 ms if ms > 0 && (ms / 1000) as u64 > now => (ms / 1000) as u64,
334 _ => 0,
335 };
336 let seen = viewing_slot().lock().unwrap().as_ref().filter(|(n, until)| n == npub && *until > now).map_or(0, |(_, until)| *until);
337 muted.max(seen)
338}
339
340pub fn controls_changed() {
342 if device().is_none() {
343 return;
344 }
345 crate::db::spawn_bound(async {
346 if let Err(e) = reconcile_holds().await {
347 crate::log_warn!("[Push] holds not updated: {}", e);
348 }
349 });
350}
351
352pub async fn reconcile_holds() -> Result<(), String> {
355 if device().is_none() {
356 return Ok(());
357 }
358 let now = now_secs();
359 let issued: HashMap<String, Issued> = {
360 let _g = lock().lock_owned().await;
361 load(ISSUED_KEY)
362 };
363 let mut changes: Vec<(String, vector_push::Hold)> = Vec::new();
364 for (npub, i) in &issued {
365 let want = wanted_hold(npub, now).await;
366 let have = if i.held != vector_push::HOLD_FOREVER && i.held <= now { 0 } else { i.held };
367 if want != have {
368 changes.push((npub.clone(), vector_push::Hold { c: i.cap.clone(), until: want }));
369 }
370 }
371 if changes.is_empty() {
372 return Ok(());
373 }
374 let (key, relays) = pusher();
375 let pusher_pk = PublicKey::from_hex(key).map_err(|e| e.to_string())?;
376 let event = vector_push::Control::new(changes.iter().map(|(_, h)| h.clone()).collect())
377 .event(&pusher_pk)
378 .map_err(|e| e.to_string())?;
379 let client = nostr_client().ok_or("Not connected")?;
380 publish(&client, &relays, &event).await?;
381 let _g = lock().lock_owned().await;
382 let mut issued: HashMap<String, Issued> = load(ISSUED_KEY);
383 for (npub, hold) in changes {
384 if let Some(i) = issued.get_mut(&npub).filter(|i| i.cap == hold.c) {
385 i.held = hold.until;
386 }
387 }
388 save(ISSUED_KEY, &issued)
389}
390
391pub(crate) async fn store_tickets(from_npub: &str, content: &str) {
397 let Ok(list) = serde_json::from_str::<TicketList>(content) else { return };
398 let _g = lock().lock_owned().await;
399 let mut held: HashMap<String, Vec<Ticket>> = load(HELD_KEY);
400 let entry = held.entry(from_npub.to_string()).or_default();
401 entry.retain(|t| !list.revoked.contains(&t.id) && !list.tickets.iter().any(|n| n.id == t.id));
402 for t in list.tickets {
403 match t.validate() {
404 Ok(()) => entry.push(t),
405 Err(e) => crate::log_warn!("[Push] ticket from {} refused: {}", from_npub, e),
406 }
407 }
408 if entry.len() > MAX_TICKETS_PER_CONTACT {
409 let excess = entry.len() - MAX_TICKETS_PER_CONTACT;
410 entry.drain(..excess);
411 }
412 if entry.is_empty() {
413 held.remove(from_npub);
414 }
415 if let Err(e) = save(HELD_KEY, &held) {
416 crate::log_warn!("[Push] saving tickets: {}", e);
417 }
418}
419
420pub(crate) fn after_delivery(receiver_npub: &str, rumor: &UnsignedEvent) {
423 let receiver = receiver_npub.to_string();
424 let notice = notice_for(rumor);
425 crate::db::spawn_bound(async move {
426 if let Some(notice) = notice {
427 let jitter = rand::Rng::gen_range(&mut rand::thread_rng(), 0..SEND_JITTER_MS);
430 crate::rt::time::sleep(std::time::Duration::from_millis(jitter)).await;
431 notify(&receiver, ¬ice, TTL).await;
432 }
433 if let Err(e) = share_with(&receiver).await {
434 crate::log_warn!("[Push] sharing ticket with {}: {}", receiver, e);
435 }
436 });
437}
438
439#[cfg(feature = "calls")]
442pub(crate) fn call_ringing(receiver_npub: &str, call_id: &str, video: bool) {
443 let notice = call_notice(if video { "video_call" } else { "call" }, call_id);
444 let receiver = receiver_npub.to_string();
445 crate::db::spawn_bound(async move { notify(&receiver, ¬ice, CALL_TTL).await });
446}
447
448#[cfg(feature = "calls")]
450pub(crate) fn call_missed(receiver_npub: &str, call_id: &str) {
451 let notice = call_notice("missed_call", call_id);
452 let receiver = receiver_npub.to_string();
453 crate::db::spawn_bound(async move { notify(&receiver, ¬ice, TTL).await });
454}
455
456#[cfg(feature = "calls")]
457fn call_notice(kind: &str, call_id: &str) -> Notice {
458 Notice { h: String::new(), kind: kind.into(), msg: call_id.into(), ts: now_secs() * 1000, text: String::new() }
459}
460
461fn notice_for(rumor: &UnsignedEvent) -> Option<Notice> {
462 let (kind, text) = match rumor.kind {
463 Kind::PrivateDirectMessage => ("dm", preview_text(&rumor.content)),
464 k if k.as_u16() == 15 => {
465 let mime = rumor.tags.find_kind("file-type").and_then(|t| t.content()).unwrap_or("");
466 ("file", format!("Sent {}", file_label(mime)))
467 }
468 _ => return None,
469 };
470 Some(Notice {
471 h: String::new(),
472 kind: kind.into(),
473 msg: rumor.id?.to_hex(),
474 ts: rumor.created_at.as_secs() * 1000,
475 text,
476 })
477}
478
479fn preview_text(content: &str) -> String {
482 let flat: String = crate::notify::strip_ansi(content).split_whitespace().collect::<Vec<_>>().join(" ");
483 flat.chars().take(600).collect()
484}
485
486fn file_label(mime: &str) -> &'static str {
487 match mime {
488 "image/gif" => "a GIF",
489 m if m.starts_with("image/") => "a Picture",
490 m if m.starts_with("video/") => "a Video",
491 "audio/wav" | "audio/x-wav" => "a Voice Message",
492 m if m.starts_with("audio/") => "an Audio Clip",
493 _ => "a File",
494 }
495}
496
497async fn notify(receiver: &str, notice: &Notice, ttl: u32) {
498 let tickets: Vec<Ticket> = {
499 let _g = lock().lock_owned().await;
500 let held: HashMap<String, Vec<Ticket>> = load(HELD_KEY);
501 held.get(receiver).cloned().unwrap_or_default()
502 };
503 if tickets.is_empty() {
504 return;
505 }
506 let Some(client) = nostr_client() else { return };
507 for t in tickets {
508 let event = match t.request(notice, ttl) {
509 Ok(e) => e,
510 Err(e) => {
511 crate::log_warn!("[Push] building request: {}", e);
512 continue;
513 }
514 };
515 if let Err(e) = publish(&client, &t.relays, &event).await {
516 crate::log_warn!("[Push] request not published: {}", e);
517 }
518 }
519}
520
521async fn publish(client: &Client, relays: &[String], event: &Event) -> Result<(), String> {
524 use crate::inbox_relays::normalize_relay_url;
525 crate::event_size::check(event)?;
526 let pool = client.relays().all().await;
527 let wanted: Vec<String> = relays.iter().map(|r| normalize_relay_url(r)).collect();
528 let mut targets: Vec<Relay> = pool
529 .iter()
530 .filter(|(u, r)| wanted.contains(&normalize_relay_url(&u.to_string())) && r.status() == RelayStatus::Connected)
531 .map(|(_, r)| r.clone())
532 .collect();
533 let mut transient: Vec<RelayUrl> = Vec::new();
534 if targets.is_empty() {
535 for r in relays {
536 let norm = normalize_relay_url(r);
537 if let Some((_, relay)) = pool.iter().find(|(u, _)| normalize_relay_url(&u.to_string()) == norm) {
538 let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(6))).await;
539 targets.push(relay.clone());
540 continue;
541 }
542 if client.add_managed_relay(r.as_str()).await.is_ok() {
543 if let Ok(Some(relay)) = client.relay(r.as_str()).await {
544 let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(6))).await;
545 transient.push(relay.url().clone());
546 targets.push(relay);
547 }
548 }
549 }
550 }
551 let results = futures_util::future::join_all(targets.iter().map(|r| async move { r.send_event(event).await })).await;
552 for url in transient {
553 let _ = client.remove_relay(&url).await;
554 }
555 if results.iter().any(|r| r.is_ok()) {
556 Ok(())
557 } else {
558 Err(results.into_iter().filter_map(|r| r.err()).map(|e| e.to_string()).next().unwrap_or_else(|| "no relays".into()))
559 }
560}
561
562#[cfg(test)]
563mod tests {
564 use super::*;
565
566 fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
567 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
568 crate::db::close_database();
569 crate::db::clear_id_caches();
570 let tmp = tempfile::tempdir().unwrap();
571 let account = Keys::generate().public_key().to_bech32().unwrap();
572 std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
573 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
574 crate::db::set_current_account(account.clone()).unwrap();
575 crate::db::init_database(&account).unwrap();
576 (tmp, guard)
577 }
578
579 #[tokio::test]
580 async fn a_push_reads_only_against_the_ticket_this_device_issued() {
581 let (_tmp, _guard) = init_test_db();
582 let alice = Keys::generate().public_key().to_bech32().unwrap();
583 prepare(std::slice::from_ref(&alice)).await.unwrap();
584 let issued: HashMap<String, Issued> = load(ISSUED_KEY);
585 let i = &issued[&alice];
586 let notice = Notice { h: i.h.clone(), kind: "call".into(), msg: "c1".into(), ts: 5, text: String::new() };
587 let message = notice.message("https://vectorapp.io", &i.mk).unwrap();
588
589 let (from, got) = receive(&message).expect("a push sealed by our own ticket");
590 assert_eq!((from.as_str(), got.kind.as_str(), got.msg.as_str()), (alice.as_str(), "call", "c1"));
591 let forged = String::from_utf8(message.clone()).unwrap().replace("\"c1\"", "\"c2\"");
592 assert!(receive(forged.as_bytes()).is_none(), "an altered field fails the MAC");
593 let stranger = Notice { h: "00".repeat(8), ..notice }.message("https://vectorapp.io", &i.mk).unwrap();
594 assert!(receive(&stranger).is_none(), "a handle no contact here holds");
595 }
596
597 #[test]
598 fn previews_flatten_and_files_get_a_label() {
599 assert_eq!(preview_text("hi\n\nthere you"), "hi there you");
600 assert_eq!(preview_text(&"x".repeat(900)).len(), 600);
601 assert_eq!(file_label("image/png"), "a Picture");
602 assert_eq!(file_label("image/gif"), "a GIF");
603 assert_eq!(file_label("audio/wav"), "a Voice Message");
604 assert_eq!(file_label("application/zip"), "a File");
605 }
606}