src/windows/verify.rs

366 lines · 14489 bytes

  1use std::cmp::Ordering;
  2use std::fmt;
  3
  4use matrix_sdk::encryption::verification::{
  5    Verification,
  6    VerificationRequest,
  7    VerificationRequestState,
  8};
  9use matrix_sdk::ruma::events::key::verification::VerificationMethod;
 10use matrix_sdk_crypto::matrix_sdk_qrcode::qrcode::render::unicode::Dense1x2;
 11use matrix_sdk_crypto::{QrVerificationState, SasState, format_emojis};
 12
 13use modalkit::actions::{PromptAction, Promptable};
 14use modalkit::errors::{EditError, EditResult};
 15use modalkit::prelude::ViewportContext;
 16use modalkit_ratatui::list::{ListCursor, ListItem};
 17use ratatui::style::{Color, Modifier as StyleModifier, Style};
 18use ratatui::text::{Line, Span, Text};
 19
 20use crate::base::{IambInfo, ProgramAction, ProgramContext, ProgramStore};
 21
 22const BLACK_ON_WHITE: Style = Style::new().fg(Color::Black).bg(Color::White);
 23
 24#[derive(Clone)]
 25pub struct VerifyItem {
 26    request: VerificationRequest,
 27    show_help: bool,
 28}
 29
 30impl VerifyItem {
 31    pub fn new(request: VerificationRequest) -> Self {
 32        Self { request, show_help: false }
 33    }
 34
 35    pub fn show_help(&mut self) {
 36        self.show_help = true;
 37    }
 38}
 39
 40impl PartialEq for VerifyItem {
 41    fn eq(&self, other: &Self) -> bool {
 42        self.request.flow_id() == other.request.flow_id()
 43    }
 44}
 45
 46impl Eq for VerifyItem {}
 47
 48impl Ord for VerifyItem {
 49    fn cmp(&self, other: &Self) -> Ordering {
 50        fn state_val(req: &VerificationRequest) -> usize {
 51            // 0: running
 52            // 1: ready
 53            // 2: requests for this session
 54            // 3: all others
 55            // 4: canceled
 56            // 5: done
 57            match req.state() {
 58                VerificationRequestState::Requested { .. } => 2,
 59                VerificationRequestState::Ready { .. } => 1,
 60                VerificationRequestState::Transitioned {
 61                    verification: Verification::SasV1(sas),
 62                } => {
 63                    match sas.state() {
 64                        SasState::KeysExchanged { emojis: Some(_), .. } => 0,
 65                        SasState::Done { .. } => 5,
 66                        SasState::Cancelled(_) => 4,
 67                        _ => 3,
 68                    }
 69                },
 70                VerificationRequestState::Transitioned { verification: Verification::QrV1(qr) } => {
 71                    match qr.state() {
 72                        QrVerificationState::Started => 1,
 73                        QrVerificationState::Scanned => 0,
 74                        QrVerificationState::Done { .. } => 5,
 75                        QrVerificationState::Cancelled(_) => 4,
 76                        _ => 3,
 77                    }
 78                },
 79                VerificationRequestState::Done => 5,
 80                VerificationRequestState::Cancelled(_) => 4,
 81                _ => 3,
 82            }
 83        }
 84
 85        fn device_val(req: &VerificationRequest) -> usize {
 86            if req.is_self_verification() { 1 } else { 2 }
 87        }
 88
 89        let state1 = state_val(&self.request);
 90        let state2 = state_val(&other.request);
 91
 92        let dev1 = device_val(&self.request);
 93        let dev2 = device_val(&other.request);
 94
 95        let scmp = state1.cmp(&state2);
 96        let dcmp = dev1.cmp(&dev2);
 97
 98        scmp.then(dcmp).then_with(|| {
 99            let did1 = self.request.flow_id();
100            let did2 = other.request.flow_id();
101
102            did1.cmp(did2)
103        })
104    }
105}
106
107impl PartialOrd for VerifyItem {
108    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
109        Some(self.cmp(other))
110    }
111}
112
113impl fmt::Display for VerifyItem {
114    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115        match self.request.state() {
116            VerificationRequestState::Requested { .. } => {
117                write!(f, ":verify accept {}", self.request.flow_id())
118            },
119            VerificationRequestState::Ready { their_methods, .. }
120                if their_methods.contains(&VerificationMethod::SasV1) =>
121            {
122                write!(f, ":verify emoji {}", self.request.flow_id())
123            },
124            VerificationRequestState::Transitioned { verification: Verification::SasV1(sas) } => {
125                match sas.state() {
126                    SasState::KeysExchanged { emojis: Some(_), .. } => {
127                        write!(f, ":verify confirm {}", self.request.flow_id())
128                    },
129                    _ => Ok(()),
130                }
131            },
132            VerificationRequestState::Transitioned { verification: Verification::QrV1(qr) } => {
133                match qr.state() {
134                    QrVerificationState::Started => {
135                        write!(f, ":verify emoji {}", self.request.flow_id())
136                    },
137                    QrVerificationState::Scanned => {
138                        write!(f, ":verify confirm {}", self.request.flow_id())
139                    },
140                    _ => Ok(()),
141                }
142            },
143            _ => Ok(()),
144        }
145    }
146}
147
148impl ListItem<IambInfo> for VerifyItem {
149    fn show(
150        &self,
151        selected: bool,
152        _: &ViewportContext<ListCursor>,
153        store: &mut ProgramStore,
154    ) -> Text<'_> {
155        let mut lines = vec![];
156        let bold = Style::default().add_modifier(StyleModifier::BOLD);
157        let selected_bold = super::selected_style(selected).add_modifier(StyleModifier::BOLD);
158        let selected = super::selected_style(selected);
159
160        let mut other_device = None;
161        let state = match self.request.state() {
162            _ if self.request.is_passive() => "completed with other device",
163            VerificationRequestState::Created { .. } => "request sent",
164            VerificationRequestState::Requested { their_methods, other_device_data } => {
165                other_device = Some(other_device_data);
166
167                if their_methods.contains(&VerificationMethod::SasV1) {
168                    lines.push(Line::from("    To accept this request, run:"));
169                    "requested"
170                } else {
171                    "no methods in common"
172                }
173            },
174            VerificationRequestState::Ready { other_device_data, their_methods, .. } => {
175                // This state should only be temporary since we either generate a qr code or
176                // directly start SAS verification.
177
178                other_device = Some(other_device_data);
179
180                if their_methods.contains(&VerificationMethod::SasV1) {
181                    lines.push(Line::from("    To start interactive verification, run:"));
182                }
183
184                "ready"
185            },
186            VerificationRequestState::Transitioned { verification: Verification::SasV1(sas) } => {
187                other_device = Some(sas.other_device().to_owned());
188
189                match sas.state() {
190                    SasState::Created { .. } |
191                    SasState::Started { .. } |
192                    SasState::Accepted { .. } => "starting",
193                    SasState::KeysExchanged { emojis: Some(emojis), .. } => {
194                        lines.push(Line::from(
195                            "    Both devices should see the following Emoji sequence:".to_string(),
196                        ));
197                        lines.push(Line::from(""));
198
199                        for line in format_emojis(emojis.emojis).lines() {
200                            lines.push(Line::from(format!("    {line}")));
201                        }
202
203                        lines.push(Line::from(""));
204                        lines.push(Line::from("    If they don't match, run:"));
205                        lines.push(Line::from(""));
206                        lines.push(Line::from(Span::styled(
207                            format!("        :verify mismatch {}", self.request.flow_id()),
208                            bold,
209                        )));
210                        lines.push(Line::from(""));
211                        lines.push(Line::from(
212                            "    If everything looks right, you can confirm with:",
213                        ));
214                        "running"
215                    },
216                    SasState::KeysExchanged { emojis: None, .. } => "unsupported method",
217                    SasState::Confirmed => "waiting for response",
218                    SasState::Done { .. } => "done",
219                    SasState::Cancelled(info) => {
220                        lines.push(Line::from(format!("    Cancelled: {}", info.reason())));
221                        "cancelled"
222                    },
223                }
224            },
225            VerificationRequestState::Transitioned { verification: Verification::QrV1(qr) } => {
226                other_device = Some(qr.other_device().to_owned());
227
228                match qr.state() {
229                    QrVerificationState::Started => {
230                        if let Ok(qrcode) = qr.to_qr_code() {
231                            let rendered = qrcode.render::<Dense1x2>().build();
232                            lines.extend(
233                                rendered
234                                    .lines()
235                                    .map(|line| Line::styled(line.to_owned(), BLACK_ON_WHITE)),
236                            );
237
238                            lines.push(Line::from("    Scan this QR code with the other device."));
239                            lines.push(Line::from(
240                                "    To alternativly start interactive verification, run:",
241                            ));
242                        } else {
243                            lines.push(Line::from("    To start interactive verification, run:"));
244                        }
245
246                        "ready"
247                    },
248                    QrVerificationState::Scanned => {
249                        lines.push(Line::from(
250                            "    Check whether the other device shows a successful verification."
251                                .to_string(),
252                        ));
253                        lines.push(Line::from(""));
254                        lines.push(Line::from("    If it shows an error, run:"));
255                        lines.push(Line::from(""));
256                        lines.push(Line::from(Span::styled(
257                            format!("        :verify mismatch {}", self.request.flow_id()),
258                            bold,
259                        )));
260                        lines.push(Line::from(""));
261                        lines.push(Line::from(
262                            "    If everything looks right, you can confirm with:",
263                        ));
264                        "running"
265                    },
266                    QrVerificationState::Confirmed => "waiting for response",
267                    QrVerificationState::Reciprocated => {
268                        tracing::error!(
269                            "reached unreachable state of having scanned a verification QR code"
270                        );
271                        "inconsistent state"
272                    },
273                    QrVerificationState::Done { .. } => "done",
274                    QrVerificationState::Cancelled(info) => {
275                        lines.push(Line::from(format!("    Cancelled: {}", info.reason())));
276                        "cancelled"
277                    },
278                }
279            },
280            VerificationRequestState::Transitioned { .. } => "unsupported method",
281            VerificationRequestState::Done => "done",
282            VerificationRequestState::Cancelled(info) => {
283                lines.push(Line::from(format!("    Cancelled: {}", info.reason())));
284                "cancelled"
285            },
286        };
287
288        let line = if self.request.is_self_verification() {
289            if let Some(device) = other_device {
290                if let Some(display_name) = device.display_name() {
291                    vec![
292                        Span::styled("Device verification with ", selected),
293                        Span::styled(display_name.to_owned(), selected_bold),
294                        Span::styled(format!(" ({state})"), selected),
295                    ]
296                } else {
297                    vec![
298                        Span::styled("Device verification with ", selected),
299                        Span::styled(device.device_id().to_string(), selected_bold),
300                        Span::styled(format!(" ({state})"), selected),
301                    ]
302                }
303            } else {
304                vec![Span::styled(
305                    format!("Device verification with any own device ({state})"),
306                    selected,
307                )]
308            }
309        } else {
310            let color = store.application.settings.get_user_color(self.request.other_user_id());
311            vec![
312                Span::styled("User verification with ", selected),
313                Span::styled(self.request.other_user_id().as_str(), selected_bold.patch(color)),
314                Span::styled(format!(" ({state})"), selected),
315            ]
316        };
317        lines.insert(0, line.into());
318
319        let cmd = self.to_string();
320
321        if !cmd.is_empty() {
322            lines.push(Line::from(""));
323            lines.push(Line::from(vec![Span::from("        "), Span::styled(cmd, bold)]));
324            if self.show_help {
325                lines.push(Line::from(""));
326                lines.push(Line::from(vec![
327                    Span::from("You can copy the above command with "),
328                    Span::styled("yy", bold),
329                    Span::from(" and then execute it with "),
330                    Span::styled("@\"", bold),
331                ]));
332            }
333        }
334
335        Text::from(lines)
336    }
337
338    fn get_word(&self) -> Option<String> {
339        None
340    }
341}
342
343impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
344    fn prompt(
345        &mut self,
346        act: &PromptAction,
347        _: &ProgramContext,
348        _: &mut ProgramStore,
349    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
350        match act {
351            PromptAction::Submit => Ok(vec![]),
352            PromptAction::Abort(_) => {
353                let msg = "Cannot abort entry inside a list";
354                let err = EditError::Failure(msg.into());
355
356                Err(err)
357            },
358            PromptAction::Recall(..) => {
359                let msg = "Cannot recall history inside a list";
360                let err = EditError::Failure(msg.into());
361
362                Err(err)
363            },
364        }
365    }
366}