1use hmac::{Hmac, Mac};
8use serde_json::json;
9use sha2::Sha256;
10
11use crate::webpush::MAX_PLAINTEXT;
12use crate::{Error, Result};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct Notice {
16 pub h: String,
18 pub kind: String,
20 pub msg: String,
22 pub ts: u64,
24 pub text: String,
25}
26
27const MAC_LEN: usize = 16;
29
30impl Notice {
31 pub fn mac(&self, mk: &[u8]) -> Result<String> {
32 let mut m = <Hmac<Sha256> as Mac>::new_from_slice(mk).map_err(|_| Error::Key("bad MAC key"))?;
33 m.update(self.canonical().as_bytes());
34 Ok(crate::hex(&m.finalize().into_bytes()[..MAC_LEN]))
35 }
36
37 fn canonical(&self) -> String {
38 format!("vector-push/1\n{}\n{}\n{}\n{}\n{}", self.h, self.kind, self.msg, self.ts, self.text)
39 }
40
41 pub fn message(&self, origin: &str, mk_hex: &str) -> Result<Vec<u8>> {
43 let mk = crate::unhex(mk_hex)?;
44 let mut notice = self.clone();
45 loop {
46 let out = notice.render(origin, &mk)?;
47 if out.len() <= MAX_PLAINTEXT {
48 return Ok(out);
49 }
50 let chars = notice.text.chars().count();
51 if chars == 0 {
52 return Err(Error::Format("notification does not fit".into()));
53 }
54 let over = out.len() - MAX_PLAINTEXT;
55 notice.text = notice.text.chars().take(chars.saturating_sub(over.max(chars / 8)).saturating_sub(1)).collect();
56 notice.text.push('…');
57 }
58 }
59
60 fn render(&self, origin: &str, mk: &[u8]) -> Result<Vec<u8>> {
61 let body = match self.kind.as_str() {
63 "call" | "video_call" => "Incoming call",
64 "missed_call" => "Missed call",
65 _ => "New message",
66 };
67 let msg = json!({
69 "web_push": 8030,
70 "mutable": true,
71 "notification": {
72 "title": "Vector",
73 "body": body,
74 "navigate": format!("{}/", origin.trim_end_matches('/')),
75 "mutable": true,
76 "data": {
77 "vp": 1,
78 "h": self.h,
79 "k": self.kind,
80 "m": self.msg,
81 "t": self.ts,
82 "x": self.text,
83 "a": self.mac(mk)?,
84 },
85 },
86 });
87 Ok(msg.to_string().into_bytes())
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use super::*;
94
95 fn notice(text: &str) -> Notice {
96 Notice { h: "a1b2c3d4e5f60718".into(), kind: "dm".into(), msg: "ab".repeat(32), ts: 1_790_000_000_000, text: text.into() }
97 }
98
99 #[test]
100 fn the_mac_covers_every_field() {
101 let mk = [9u8; 32];
102 let base = notice("hi").mac(&mk).unwrap();
103 assert_ne!(notice("hj").mac(&mk).unwrap(), base);
104 assert_ne!(Notice { ts: 1, ..notice("hi") }.mac(&mk).unwrap(), base);
105 assert_ne!(Notice { kind: "file".into(), ..notice("hi") }.mac(&mk).unwrap(), base);
106 assert_ne!(notice("hi").mac(&[8u8; 32]).unwrap(), base);
107 }
108
109 #[test]
110 fn the_fallback_names_a_call_and_nothing_the_sender_wrote() {
111 let mk = crate::hex(&[3u8; 32]);
112 let body = |kind: &str| {
113 let out = Notice { kind: kind.into(), ..notice("ignore this") }.message("https://web.vectorapp.io", &mk).unwrap();
114 serde_json::from_slice::<serde_json::Value>(&out).unwrap()["notification"]["body"].as_str().unwrap().to_string()
115 };
116 assert_eq!(body("call"), "Incoming call");
117 assert_eq!(body("video_call"), "Incoming call");
118 assert_eq!(body("missed_call"), "Missed call");
119 assert_eq!(body("dm"), "New message");
120 }
121
122 #[test]
123 fn long_text_is_cut_to_fit_and_still_verifies() {
124 let mk = crate::hex(&[3u8; 32]);
125 let out = notice(&"é\"".repeat(4000)).message("https://web.vectorapp.io", &mk).unwrap();
126 assert!(out.len() <= MAX_PLAINTEXT);
127 let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
128 let data = &v["notification"]["data"];
129 let cut = Notice { text: data["x"].as_str().unwrap().into(), ..notice("") };
130 assert!(cut.text.ends_with('…'));
131 assert_eq!(data["a"], cut.mac(&[3u8; 32]).unwrap());
132 assert_eq!(v["notification"]["navigate"], "https://web.vectorapp.io/");
133 }
134}