src/windows/verify.rs

367 lines · 14692 bytes

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