src/windows/verify.rs

353 lines · 14122 bytes

  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    fn show(
137        &self,
138        selected: bool,
139        _: &ViewportContext<ListCursor>,
140        store: &mut ProgramStore,
141    ) -> Text<'_> {
142        let mut lines = vec![];
143        let bold = Style::default().add_modifier(StyleModifier::BOLD);
144        let selected_bold = super::selected_style(selected).add_modifier(StyleModifier::BOLD);
145        let selected = super::selected_style(selected);
146
147        let mut other_device = None;
148        let state = match self.request.state() {
149            _ if self.request.is_passive() => "completed with other device",
150            VerificationRequestState::Created { .. } => "request sent",
151            VerificationRequestState::Requested { their_methods, other_device_data } => {
152                other_device = Some(other_device_data);
153
154                if their_methods.contains(&VerificationMethod::SasV1) {
155                    lines.push(Line::from("    To accept this request, run:"));
156                    "requested"
157                } else {
158                    "no methods in common"
159                }
160            },
161            VerificationRequestState::Ready { other_device_data, their_methods, .. } => {
162                // This state should only be temporary since we either generate a qr code or
163                // directly start SAS verification.
164
165                other_device = Some(other_device_data);
166
167                if their_methods.contains(&VerificationMethod::SasV1) {
168                    lines.push(Line::from("    To start interactive verification, run:"));
169                }
170
171                "ready"
172            },
173            VerificationRequestState::Transitioned { verification: Verification::SasV1(sas) } => {
174                other_device = Some(sas.other_device().to_owned());
175
176                match sas.state() {
177                    SasState::Created { .. } |
178                    SasState::Started { .. } |
179                    SasState::Accepted { .. } => "starting",
180                    SasState::KeysExchanged { emojis: Some(emojis), .. } => {
181                        lines.push(Line::from(
182                            "    Both devices should see the following Emoji sequence:".to_string(),
183                        ));
184                        lines.push(Line::from(""));
185
186                        for line in format_emojis(emojis.emojis).lines() {
187                            lines.push(Line::from(format!("    {line}")));
188                        }
189
190                        lines.push(Line::from(""));
191                        lines.push(Line::from("    If they don't match, run:"));
192                        lines.push(Line::from(""));
193                        lines.push(Line::from(Span::styled(
194                            format!("        :verify mismatch {}", self.request.flow_id()),
195                            bold,
196                        )));
197                        lines.push(Line::from(""));
198                        lines.push(Line::from(
199                            "    If everything looks right, you can confirm with:",
200                        ));
201                        "running"
202                    },
203                    SasState::KeysExchanged { emojis: None, .. } => "unsupported method",
204                    SasState::Confirmed => "waiting for response",
205                    SasState::Done { .. } => "done",
206                    SasState::Cancelled(info) => {
207                        lines.push(Line::from(format!("    Cancelled: {}", info.reason())));
208                        "cancelled"
209                    },
210                }
211            },
212            VerificationRequestState::Transitioned { verification: Verification::QrV1(qr) } => {
213                other_device = Some(qr.other_device().to_owned());
214
215                match qr.state() {
216                    QrVerificationState::Started => {
217                        if let Ok(qrcode) = qr.to_qr_code() {
218                            let rendered = qrcode.render::<Dense1x2>().build();
219                            lines.extend(
220                                rendered
221                                    .lines()
222                                    .map(|line| Line::styled(line.to_owned(), BLACK_ON_WHITE)),
223                            );
224
225                            lines.push(Line::from("    Scan this QR code with the other device."));
226                            lines.push(Line::from(
227                                "    To alternativly start interactive verification, run:",
228                            ));
229                        } else {
230                            lines.push(Line::from("    To start interactive verification, run:"));
231                        }
232
233                        "ready"
234                    },
235                    QrVerificationState::Scanned => {
236                        lines.push(Line::from(
237                            "    Check whether the other device shows a successful verification."
238                                .to_string(),
239                        ));
240                        lines.push(Line::from(""));
241                        lines.push(Line::from("    If it shows an error, run:"));
242                        lines.push(Line::from(""));
243                        lines.push(Line::from(Span::styled(
244                            format!("        :verify mismatch {}", self.request.flow_id()),
245                            bold,
246                        )));
247                        lines.push(Line::from(""));
248                        lines.push(Line::from(
249                            "    If everything looks right, you can confirm with:",
250                        ));
251                        "running"
252                    },
253                    QrVerificationState::Confirmed => "waiting for response",
254                    QrVerificationState::Reciprocated => {
255                        tracing::error!(
256                            "reached unreachable state of having scanned a verification QR code"
257                        );
258                        "inconsistent state"
259                    },
260                    QrVerificationState::Done { .. } => "done",
261                    QrVerificationState::Cancelled(info) => {
262                        lines.push(Line::from(format!("    Cancelled: {}", info.reason())));
263                        "cancelled"
264                    },
265                }
266            },
267            VerificationRequestState::Transitioned { .. } => "unsupported method",
268            VerificationRequestState::Done => "done",
269            VerificationRequestState::Cancelled(info) => {
270                lines.push(Line::from(format!("    Cancelled: {}", info.reason())));
271                "cancelled"
272            },
273        };
274
275        let line = if self.request.is_self_verification() {
276            if let Some(device) = other_device {
277                if let Some(display_name) = device.display_name() {
278                    vec![
279                        Span::styled("Device verification with ", selected),
280                        Span::styled(display_name.to_owned(), selected_bold),
281                        Span::styled(format!(" ({state})"), selected),
282                    ]
283                } else {
284                    vec![
285                        Span::styled("Device verification with ", selected),
286                        Span::styled(device.device_id().to_string(), selected_bold),
287                        Span::styled(format!(" ({state})"), selected),
288                    ]
289                }
290            } else {
291                vec![Span::styled(
292                    format!("Device verification with any own device ({state})"),
293                    selected,
294                )]
295            }
296        } else {
297            let color = store.application.settings.get_user_color(self.request.other_user_id());
298            vec![
299                Span::styled("User verification with ", selected),
300                Span::styled(self.request.other_user_id().as_str(), selected_bold.patch(color)),
301                Span::styled(format!(" ({state})"), selected),
302            ]
303        };
304        lines.insert(0, line.into());
305
306        let cmd = self.to_string();
307
308        if !cmd.is_empty() {
309            lines.push(Line::from(""));
310            lines.push(Line::from(vec![Span::from("        "), Span::styled(cmd, bold)]));
311            if self.show_help {
312                lines.push(Line::from(""));
313                lines.push(Line::from(vec![
314                    Span::from("You can copy the above command with "),
315                    Span::styled("yy", bold),
316                    Span::from(" and then execute it with "),
317                    Span::styled("@\"", bold),
318                ]));
319            }
320        }
321
322        Text::from(lines)
323    }
324
325    fn get_word(&self) -> Option<String> {
326        None
327    }
328}
329
330impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
331    fn prompt(
332        &mut self,
333        act: &PromptAction,
334        _: &ProgramContext,
335        _: &mut ProgramStore,
336    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
337        match act {
338            PromptAction::Submit => Ok(vec![]),
339            PromptAction::Abort(_) => {
340                let msg = "Cannot abort entry inside a list";
341                let err = EditError::Failure(msg.into());
342
343                Err(err)
344            },
345            PromptAction::Recall(..) => {
346                let msg = "Cannot recall history inside a list";
347                let err = EditError::Failure(msg.into());
348
349                Err(err)
350            },
351        }
352    }
353}