Commit 362a323a5b

362a323a5bd36ece37de7218bf5092807fcc0fda

parent: 992459575f

Unregistered key

vaw <git@nlih.de> · 2026-09-04 22:27 UTC
committer: <noreply@github.com>

Improve verifications (#605)

Layout: unified · split

Cargo.lock +20
@@ -3457,6 +3457,7 @@ dependencies = [
34573457 "itertools 0.14.0",
34583458 "js_option",
34593459 "matrix-sdk-common",
3460 "matrix-sdk-qrcode",
34603461 "pbkdf2",
34613462 "rand 0.10.1",
34623463 "rmp-serde",
@@ -3508,6 +3509,19 @@ dependencies = [
35083509 "zeroize",
35093510]
35103511
3512[[package]]
3513name = "matrix-sdk-qrcode"
3514version = "0.18.0"
3515source = "registry+https://github.com/rust-lang/crates.io-index"
3516checksum = "fc199f424cd31ad8a63717965779f6ecc877b3ecebe31db8030ef3be8200b0cd"
3517dependencies = [
3518 "byteorder",
3519 "qrcode",
3520 "ruma",
3521 "thiserror 2.0.18",
3522 "vodozemac",
3523]
3524
35113525[[package]]
35123526name = "matrix-sdk-sqlite"
35133527version = "0.18.0"
@@ -4566,6 +4580,12 @@ dependencies = [
45664580 "bytemuck",
45674581]
45684582
4583[[package]]
4584name = "qrcode"
4585version = "0.14.1"
4586source = "registry+https://github.com/rust-lang/crates.io-index"
4587checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
4588
45694589[[package]]
45704590name = "quantette"
45714591version = "0.6.0"
Cargo.toml +1 −1
@@ -97,7 +97,7 @@ version = "0.18.0"
9797[dependencies.matrix-sdk]
9898version = "0.18.0"
9999default-features = false
100features = ["e2e-encryption", "socks", "sqlite", "sso-login"]
100features = ["e2e-encryption", "socks", "sqlite", "sso-login", "qrcode"]
101101
102102[dependencies.matrix-sdk-crypto]
103103version = "0.18.0"
docs/iamb.1 +2
@@ -84,6 +84,8 @@ Import and decrypt keys from
8484View a list of ongoing E2EE verifications.
8585.It Sy ":verify accept [key]"
8686Accept a verification request.
87.It Sy ":verify emoji [key]"
88Transition a request to use interactive emoji verification.
8789.It Sy ":verify cancel [key]"
8890Cancel an in-progress verification.
8991.It Sy ":verify confirm [key]"
src/base.rs +6 −9
@@ -12,6 +12,7 @@ use std::time::{Duration, Instant};
1212
1313use emojis::Emoji;
1414
15use matrix_sdk::encryption::verification::VerificationRequest;
1516use ratatui::{
1617 buffer::Buffer,
1718 layout::{Alignment, Rect},
@@ -31,7 +32,6 @@ use url::Url;
3132
3233use matrix_sdk::{
3334 RoomState as MatrixRoomState,
34 encryption::verification::SasVerification,
3535 room::Room as MatrixRoom,
3636 ruma::{
3737 EventId,
@@ -141,6 +141,9 @@ pub enum VerifyAction {
141141
142142 /// Reject an in-progress verification due to mismatched Emoji.
143143 Mismatch,
144
145 /// Start an interactive (SAS) emoji verification
146 Emoji,
144147}
145148
146149/// An action taken against the currently selected message.
@@ -1847,7 +1850,8 @@ pub struct ChatStore {
18471850 pub presences: CompletionMap<OwnedUserId, PresenceState>,
18481851
18491852 /// In-progress and completed verifications.
1850 pub verifications: CompletionMap<String, SasVerification>,
1853 /// The map key is the `flow_id`.
1854 pub verifications: CompletionMap<String, VerificationRequest>,
18511855
18521856 /// Settings for the current profile loaded from config file.
18531857 pub settings: ApplicationSettings,
@@ -1940,13 +1944,6 @@ impl ChatStore {
19401944 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
19411945 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
19421946 }
1943
1944 /// Insert a new E2EE verification.
1945 pub fn insert_sas(&mut self, sas: SasVerification) {
1946 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1947
1948 self.verifications.insert(key, sas);
1949 }
19501947}
19511948
19521949impl ApplicationStore for ChatStore {}
src/commands.rs +1
@@ -213,6 +213,7 @@ fn iamb_verify(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
213213 "cancel" => VerifyAction::Cancel,
214214 "confirm" => VerifyAction::Confirm,
215215 "mismatch" => VerifyAction::Mismatch,
216 "emoji" => VerifyAction::Emoji,
216217 "request" => {
217218 let iact = IambAction::VerifyRequest(args.remove(1));
218219 let step = CommandStep::Continue(iact.into(), ctx.context.clone());
src/completions.rs +8 −1
@@ -373,7 +373,14 @@ fn complete_iamb_keys(
373373
374374/// Tab completion for `:verify`
375375fn complete_iamb_verify(args: Vec<String>, store: &ChatStore) -> Vec<String> {
376 let subcmds = ["request", "accept", "confirm", "cancel", "missmatch"];
376 let subcmds = [
377 "request",
378 "accept",
379 "confirm",
380 "cancel",
381 "missmatch",
382 "emoji",
383 ];
377384 match args.len() {
378385 1 => complete_choices(&args[0], &subcmds),
379386 2 if args[0] == "request" => complete_users(&args[1], store),
src/main.rs +8 −11
@@ -28,7 +28,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
2828use std::time::{Duration, Instant};
2929
3030use clap::{CommandFactory, Parser};
31use matrix_sdk::ruma::OwnedUserId;
31use matrix_sdk::ruma::UserId;
3232use matrix_sdk::ruma::api::error::ErrorKind;
3333use matrix_sdk::ruma::profile::{ProfileFieldName, ProfileFieldValue};
3434use matrix_sdk_crypto::encrypt_room_key_export;
@@ -87,6 +87,7 @@ mod worker;
8787
8888#[cfg(test)]
8989mod tests;
90mod verifications;
9091
9192use crate::{
9293 base::{
@@ -621,19 +622,15 @@ impl Application {
621622 None
622623 },
623624
624 IambAction::Verify(act, user_dev) => {
625 if let Some(sas) = store.application.verifications.get(&user_dev) {
626 self.worker.verify(act, sas.clone())?
627 } else {
628 return Err(IambError::InvalidVerificationId(user_dev).into());
629 }
625 IambAction::Verify(act, flow_id) => {
626 return verifications::iamb_verify(act, flow_id, store).await;
630627 },
631628 IambAction::VerifyRequest(user_id) => {
632 if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
633 self.worker.verify_request(user_id)?
634 } else {
629 let Ok(user_id) = <&UserId>::try_from(user_id.as_str()) else {
635630 return Err(IambError::InvalidUserId(user_id).into());
636 }
631 };
632
633 return verifications::iamb_verify_request(user_id, store).await;
637634 },
638635 };
639636
src/verifications.rs added +226
@@ -0,0 +1,226 @@
1use matrix_sdk::Client;
2use matrix_sdk::encryption::verification::{
3 Verification,
4 VerificationRequest,
5 VerificationRequestState,
6};
7use matrix_sdk::ruma::events::key::verification::VerificationMethod;
8use matrix_sdk::ruma::{OwnedDeviceId, OwnedUserId, UserId};
9use modalkit::errors::UIError;
10use modalkit::prelude::{EditInfo, InfoMessage};
11
12use crate::base::{AsyncProgramStore, IambError, IambResult, ProgramStore, VerifyAction};
13
14const SUPPORTED_METHODS: [VerificationMethod; 3] = [
15 // Emoji verification
16 VerificationMethod::SasV1,
17 // QR Code verification
18 VerificationMethod::ReciprocateV1,
19 VerificationMethod::QrCodeShowV1,
20];
21
22async fn maybe_autostart(request: &VerificationRequest) -> Result<(), matrix_sdk::Error> {
23 if let Some(theirs) = request.their_supported_methods() {
24 if theirs.contains(&VerificationMethod::QrCodeScanV1) &&
25 theirs.contains(&VerificationMethod::ReciprocateV1)
26 {
27 // Generate a QR code to show. This doesn't actually mean we select
28 // this flow.
29 request.generate_qr_code().await?;
30 } else if theirs.contains(&VerificationMethod::SasV1) {
31 // We only have one method in common and don't need to query the
32 // user.
33 request.start_sas().await?;
34 }
35 }
36
37 Ok(())
38}
39
40pub async fn handle_request(
41 flow_id: String,
42 other_user_id: OwnedUserId,
43 other_device_id: OwnedDeviceId,
44 client: Client,
45 store: AsyncProgramStore,
46) {
47 let own_user_id = client.user_id().unwrap();
48 let own_device_id = client.device_id().unwrap();
49 if other_user_id == own_user_id && other_device_id == own_device_id {
50 tracing::debug!("ignoring the verification request we sent");
51 return;
52 }
53
54 let Some(request) = client
55 .encryption()
56 .get_verification_request(&other_user_id, &flow_id)
57 .await
58 else {
59 tracing::warn!("couldn't find verification request in crypto store");
60 return;
61 };
62
63 tracing::debug!("received a verification request");
64
65 store.lock().await.application.verifications.insert(flow_id, request);
66}
67
68pub async fn handle_ready(
69 flow_id: String,
70 other_user_id: OwnedUserId,
71 client: Client,
72 store: AsyncProgramStore,
73) {
74 let Some(request) = client
75 .encryption()
76 .get_verification_request(&other_user_id, &flow_id)
77 .await
78 else {
79 tracing::warn!("couldn't find verification request in crypto store");
80 return;
81 };
82
83 if let Err(err) = maybe_autostart(&request).await {
84 tracing::warn!("unable to start verification process: {err}");
85 }
86
87 // Insert the request in case we missed it. Not sure if this is needed.
88 // Might happen with room verification requests if the client is restarted.
89 store.lock().await.application.verifications.insert(flow_id, request);
90}
91
92pub async fn handle_start(flow_id: String, other_user_id: OwnedUserId, client: Client) {
93 match client.encryption().get_verification(&other_user_id, &flow_id).await {
94 Some(Verification::SasV1(sas)) => {
95 tracing::debug!("accepting SAS verification flow");
96 if let Err(err) = sas.accept().await {
97 tracing::warn!("unable to accept SAS verification flow: {err}");
98 }
99 },
100 Some(_) => {
101 tracing::info!("ignoring verification start with unsupported method");
102 },
103 None => {
104 tracing::warn!("couldn't find verification request in crypto store");
105 },
106 }
107}
108
109pub async fn iamb_verify(
110 act: VerifyAction,
111 flow_id: String,
112 store: &ProgramStore,
113) -> IambResult<EditInfo> {
114 let Some(request) = store.application.verifications.get(&flow_id) else {
115 return Err(IambError::InvalidVerificationId(flow_id).into());
116 };
117
118 match act {
119 VerifyAction::Accept => {
120 if request.their_supported_methods().is_none_or(|theirs| {
121 !(theirs.contains(&VerificationMethod::SasV1) ||
122 theirs.contains(&VerificationMethod::QrCodeScanV1) &&
123 theirs.contains(&VerificationMethod::ReciprocateV1))
124 }) {
125 let msg = "We don't have any verification methods in common.";
126 let err = UIError::Failure(msg.into());
127 return Err(err);
128 }
129
130 request
131 .accept_with_methods(SUPPORTED_METHODS.into())
132 .await
133 .map_err(IambError::from)?;
134
135 maybe_autostart(request).await.map_err(IambError::from)?;
136
137 Ok(Some(InfoMessage::from("Accepted verification request")))
138 },
139 VerifyAction::Emoji => {
140 if request
141 .their_supported_methods()
142 .is_none_or(|theirs| !theirs.contains(&VerificationMethod::SasV1))
143 {
144 let msg = "The other party doesn't support emoji verification.";
145 let err = UIError::Failure(msg.into());
146 return Err(err);
147 }
148
149 if request.start_sas().await.map_err(IambError::from)?.is_some() {
150 Ok(Some(InfoMessage::from("Verification started")))
151 } else {
152 let msg = "Can't start interactive verification at this point.";
153 let err = UIError::Failure(msg.into());
154 Err(err)
155 }
156 },
157 VerifyAction::Cancel => {
158 request.cancel().await.map_err(IambError::from)?;
159 Ok(Some(InfoMessage::from("Cancelled verification")))
160 },
161 VerifyAction::Confirm => {
162 match request.state() {
163 VerificationRequestState::Transitioned {
164 verification: Verification::SasV1(sas),
165 } if sas.can_be_presented() => {
166 sas.confirm().await.map_err(IambError::from)?;
167 },
168 VerificationRequestState::Transitioned { verification: Verification::QrV1(qr) }
169 if qr.has_been_scanned() =>
170 {
171 qr.confirm().await.map_err(IambError::from)?;
172 },
173 _ => {
174 let msg = "Can only confirm in-progress verifications!";
175 let err = UIError::Failure(msg.into());
176 return Err(err);
177 },
178 }
179
180 Ok(Some(InfoMessage::from("Confirmed verification")))
181 },
182 VerifyAction::Mismatch => {
183 match request.state() {
184 VerificationRequestState::Transitioned {
185 verification: Verification::SasV1(sas),
186 } if sas.can_be_presented() => {
187 sas.mismatch().await.map_err(IambError::from)?;
188 },
189 VerificationRequestState::Transitioned { verification: Verification::QrV1(qr) }
190 if qr.has_been_scanned() =>
191 {
192 qr.cancel().await.map_err(IambError::from)?;
193 },
194 _ => {
195 let msg = "Can only reject in-progress verifications!";
196 let err = UIError::Failure(msg.into());
197 return Err(err);
198 },
199 }
200
201 Ok(Some(InfoMessage::from("Rejected verification")))
202 },
203 }
204}
205
206pub async fn iamb_verify_request(
207 user_id: &UserId,
208 store: &mut ProgramStore,
209) -> IambResult<EditInfo> {
210 let enc = store.application.worker.client.encryption();
211
212 let Some(identity) = enc.get_user_identity(user_id).await.map_err(IambError::from)? else {
213 let msg = format!("Could not find identity information for {user_id}");
214 let err = UIError::Failure(msg);
215 return Err(err);
216 };
217
218 let request = identity.request_verification_with_methods(SUPPORTED_METHODS.into());
219 let request = request.await.map_err(IambError::from)?;
220
221 let flow_id = request.flow_id().to_owned();
222 store.application.verifications.insert(flow_id, request);
223
224 let info = format!("Sent verification request to {user_id}");
225 Ok(Some(InfoMessage::from(info)))
226}
src/windows/mod.rs +16 −208
@@ -6,7 +6,7 @@
66//! Additionally, some of the iamb commands delegate behaviour to the current UI element. For
77//! example, [sending messages][crate::base::SendAction] delegate to the [room window][RoomState],
88//! where we have the message bar and room ID easily accessible and resettable.
9use std::cmp::{Ord, Ordering, PartialOrd};
9use std::cmp::{Ord, Ordering};
1010use std::fmt::{self, Display};
1111use std::ops::Deref;
1212use std::sync::Arc;
@@ -14,7 +14,6 @@ use std::time::{Duration, Instant};
1414
1515use matrix_sdk::{
1616 RoomState as MatrixRoomState,
17 encryption::verification::{SasVerification, format_emojis},
1817 room::{Room as MatrixRoom, RoomMember},
1918 ruma::{
2019 OwnedRoomAliasId,
@@ -80,11 +79,14 @@ use crate::base::{
8079};
8180use crate::windows::room::room_command;
8281
83use self::{room::RoomState, welcome::WelcomeState};
82use self::room::RoomState;
83use self::verify::VerifyItem;
84use self::welcome::WelcomeState;
8485use crate::message::MessageTimeStamp;
8586use feruca::Collator;
8687
8788pub mod room;
89pub mod verify;
8890pub mod welcome;
8991
9092type MatrixRoomInfo = Arc<(MatrixRoom, Option<Tags>)>;
@@ -107,7 +109,7 @@ fn bold_spans(s: &str) -> Line<'_> {
107109}
108110
109111#[inline]
110fn selected_style(selected: bool) -> Style {
112pub fn selected_style(selected: bool) -> Style {
111113 if selected {
112114 Style::default().add_modifier(StyleModifier::REVERSED)
113115 } else {
@@ -765,12 +767,20 @@ impl WindowOps<IambInfo> for IambWindow {
765767 .render(area, buf, state);
766768 },
767769 IambWindow::VerifyList(state) => {
768 let verifications = &store.application.verifications;
769 let mut items = verifications.iter().map(VerifyItem::from).collect::<Vec<_>>();
770 let mut items = store
771 .application
772 .verifications
773 .iter()
774 .map(|(_, req)| VerifyItem::new(req.to_owned()))
775 .collect::<Vec<_>>();
770776
771777 // Sort the active verifications towards the top.
772778 items.sort();
773779
780 if let Some(item) = items.first_mut() {
781 item.show_help();
782 }
783
774784 state.set(items);
775785 state.set_ignorecase(store.application.settings.tunables.ignorecase);
776786
@@ -1430,208 +1440,6 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
14301440 }
14311441}
14321442
1433#[derive(Clone)]
1434pub struct VerifyItem {
1435 user_dev: String,
1436 sasv1: SasVerification,
1437}
1438
1439impl VerifyItem {
1440 fn new(user_dev: String, sasv1: SasVerification) -> Self {
1441 VerifyItem { user_dev, sasv1 }
1442 }
1443
1444 fn show_item(&self) -> String {
1445 let state = if self.sasv1.is_done() {
1446 "done"
1447 } else if self.sasv1.is_cancelled() {
1448 "cancelled"
1449 } else if self.sasv1.emoji().is_some() {
1450 "accepted"
1451 } else {
1452 "not accepted"
1453 };
1454
1455 if self.sasv1.is_self_verification() {
1456 let device = self.sasv1.other_device();
1457
1458 if let Some(display_name) = device.display_name() {
1459 format!("Device verification with {display_name} ({state})")
1460 } else {
1461 format!("Device verification with device {} ({})", device.device_id(), state)
1462 }
1463 } else {
1464 format!("User Verification with {} ({})", self.sasv1.other_user_id(), state)
1465 }
1466 }
1467}
1468
1469impl PartialEq for VerifyItem {
1470 fn eq(&self, other: &Self) -> bool {
1471 self.user_dev == other.user_dev
1472 }
1473}
1474
1475impl Eq for VerifyItem {}
1476
1477impl Ord for VerifyItem {
1478 fn cmp(&self, other: &Self) -> Ordering {
1479 fn state_val(sas: &SasVerification) -> usize {
1480 if sas.is_done() {
1481 return 3;
1482 } else if sas.is_cancelled() {
1483 return 2;
1484 } else {
1485 return 1;
1486 }
1487 }
1488
1489 fn device_val(sas: &SasVerification) -> usize {
1490 if sas.is_self_verification() {
1491 return 1;
1492 } else {
1493 return 2;
1494 }
1495 }
1496
1497 let state1 = state_val(&self.sasv1);
1498 let state2 = state_val(&other.sasv1);
1499
1500 let dev1 = device_val(&self.sasv1);
1501 let dev2 = device_val(&other.sasv1);
1502
1503 let scmp = state1.cmp(&state2);
1504 let dcmp = dev1.cmp(&dev2);
1505
1506 scmp.then(dcmp).then_with(|| {
1507 let did1 = self.sasv1.other_device().device_id();
1508 let did2 = other.sasv1.other_device().device_id();
1509
1510 did1.cmp(did2)
1511 })
1512 }
1513}
1514
1515impl PartialOrd for VerifyItem {
1516 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1517 Some(self.cmp(other))
1518 }
1519}
1520
1521impl From<(&String, &SasVerification)> for VerifyItem {
1522 fn from((user_dev, sasv1): (&String, &SasVerification)) -> Self {
1523 VerifyItem::new(user_dev.clone(), sasv1.clone())
1524 }
1525}
1526
1527impl Display for VerifyItem {
1528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1529 if self.sasv1.is_done() {
1530 return Ok(());
1531 }
1532
1533 if self.sasv1.is_cancelled() {
1534 write!(f, ":verify request {}", self.sasv1.other_user_id())
1535 } else if self.sasv1.emoji().is_some() {
1536 write!(f, ":verify confirm {}", self.user_dev)
1537 } else {
1538 write!(f, ":verify accept {}", self.user_dev)
1539 }
1540 }
1541}
1542
1543impl ListItem<IambInfo> for VerifyItem {
1544 fn show(
1545 &self,
1546 selected: bool,
1547 _: &ViewportContext<ListCursor>,
1548 _: &mut ProgramStore,
1549 ) -> Text<'_> {
1550 let mut lines = vec![];
1551
1552 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1553 let item = Span::styled(self.show_item(), selected_style(selected));
1554 lines.push(Line::from(item));
1555
1556 if self.sasv1.is_done() {
1557 // Print nothing.
1558 } else if self.sasv1.is_cancelled() {
1559 if let Some(info) = self.sasv1.cancel_info() {
1560 lines.push(Line::from(format!(" Cancelled: {}", info.reason())));
1561 lines.push(Line::from(""));
1562 }
1563
1564 lines.push(Line::from(" You can start a new verification request with:"));
1565 } else if let Some(emoji) = self.sasv1.emoji() {
1566 lines.push(Line::from(
1567 " Both devices should see the following Emoji sequence:".to_string(),
1568 ));
1569 lines.push(Line::from(""));
1570
1571 for line in format_emojis(emoji).lines() {
1572 lines.push(Line::from(format!(" {line}")));
1573 }
1574
1575 lines.push(Line::from(""));
1576 lines.push(Line::from(" If they don't match, run:"));
1577 lines.push(Line::from(""));
1578 lines.push(Line::from(Span::styled(
1579 format!(":verify mismatch {}", self.user_dev),
1580 bold,
1581 )));
1582 lines.push(Line::from(""));
1583 lines.push(Line::from(" If everything looks right, you can confirm with:"));
1584 } else {
1585 lines.push(Line::from(" To accept this request, run:"));
1586 }
1587
1588 let cmd = self.to_string();
1589
1590 if !cmd.is_empty() {
1591 lines.push(Line::from(""));
1592 lines.push(Line::from(vec![Span::from(" "), Span::styled(cmd, bold)]));
1593 lines.push(Line::from(""));
1594 lines.push(Line::from(vec![
1595 Span::from("You can copy the above command with "),
1596 Span::styled("yy", bold),
1597 Span::from(" and then execute it with "),
1598 Span::styled("@\"", bold),
1599 ]));
1600 }
1601
1602 Text::from(lines)
1603 }
1604
1605 fn get_word(&self) -> Option<String> {
1606 None
1607 }
1608}
1609
1610impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
1611 fn prompt(
1612 &mut self,
1613 act: &PromptAction,
1614 _: &ProgramContext,
1615 _: &mut ProgramStore,
1616 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1617 match act {
1618 PromptAction::Submit => Ok(vec![]),
1619 PromptAction::Abort(_) => {
1620 let msg = "Cannot abort entry inside a list";
1621 let err = EditError::Failure(msg.into());
1622
1623 Err(err)
1624 },
1625 PromptAction::Recall(..) => {
1626 let msg = "Cannot recall history inside a list";
1627 let err = EditError::Failure(msg.into());
1628
1629 Err(err)
1630 },
1631 }
1632 }
1633}
1634
16351443#[derive(Clone)]
16361444pub struct MemberItem {
16371445 member: RoomMember,
src/windows/verify.rs added +366
@@ -0,0 +1,366 @@
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}
src/worker.rs +81 −209
@@ -13,12 +13,16 @@ use std::time::{Duration, Instant};
1313
1414use futures::{StreamExt, stream::FuturesUnordered};
1515use gethostname::gethostname;
16use matrix_sdk::ruma::events::key::verification::ready::{
17 OriginalSyncKeyVerificationReadyEvent,
18 ToDeviceKeyVerificationReadyEvent,
19};
1620use matrix_sdk_base::RoomStateFilter;
1721use ratatui_image::picker::Picker;
1822use tokio::sync::Semaphore;
1923use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
2024use tokio::task::JoinHandle;
21use tracing::{error, warn};
25use tracing::{Instrument as _, error, warn};
2226use url::Url;
2327
2428use matrix_sdk::{
@@ -29,11 +33,7 @@ use matrix_sdk::{
2933 RoomMemberships,
3034 authentication::matrix::MatrixSession,
3135 config::{RequestConfig, SyncSettings},
32 encryption::{
33 BackupDownloadStrategy,
34 EncryptionSettings,
35 verification::{SasVerification, Verification},
36 },
36 encryption::{BackupDownloadStrategy, EncryptionSettings},
3737 event_handler::Ctx,
3838 reqwest,
3939 room::{Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
@@ -63,9 +63,6 @@ use matrix_sdk::{
6363 SyncMessageLikeEvent,
6464 SyncStateEvent,
6565 key::verification::{
66 VerificationMethod,
67 done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent},
68 key::{OriginalSyncKeyVerificationKeyEvent, ToDeviceKeyVerificationKeyEvent},
6966 request::ToDeviceKeyVerificationRequestEvent,
7067 start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
7168 },
@@ -99,6 +96,7 @@ use crate::config::{ImagePreviewSize, ProxyUrl};
9996use crate::message::{Message, MessageEvent, MessageId, MessageKey};
10097use crate::notifications::register_notifications;
10198use crate::preview::PreviewKind;
99use crate::verifications;
102100use crate::{
103101 ApplicationSettings,
104102 base::{
@@ -111,7 +109,6 @@ use crate::{
111109 ProgramStore,
112110 RoomFetchStatus,
113111 RoomInfo,
114 VerifyAction,
115112 },
116113};
117114
@@ -739,8 +736,6 @@ pub enum WorkerTask {
739736 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
740737 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
741738 TypingNotice(OwnedRoomId),
742 Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>),
743 VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>),
744739 LoadImage(MediaSource, PreviewKind, ImagePreviewSize, Arc<Picker>, Arc<Semaphore>),
745740}
746741
@@ -792,19 +787,6 @@ impl Debug for WorkerTask {
792787 WorkerTask::TypingNotice(room_id) => {
793788 f.debug_tuple("WorkerTask::TypingNotice").field(room_id).finish()
794789 },
795 WorkerTask::Verify(act, sasv1, _) => {
796 f.debug_tuple("WorkerTask::Verify")
797 .field(act)
798 .field(sasv1)
799 .field(&format_args!("_"))
800 .finish()
801 },
802 WorkerTask::VerifyRequest(user_id, _) => {
803 f.debug_tuple("WorkerTask::VerifyRequest")
804 .field(user_id)
805 .field(&format_args!("_"))
806 .finish()
807 },
808790 WorkerTask::LoadImage(source, kind, size, _, _) => {
809791 f.debug_tuple("WorkerTask::RenderImage")
810792 .field(source)
@@ -984,22 +966,6 @@ impl Requester {
984966 self.tx.send(WorkerTask::TypingNotice(room_id)).unwrap();
985967 }
986968
987 pub fn verify(&self, act: VerifyAction, sas: SasVerification) -> IambResult<EditInfo> {
988 let (reply, response) = oneshot();
989
990 self.tx.send(WorkerTask::Verify(act, sas, reply)).unwrap();
991
992 return response.recv();
993 }
994
995 pub fn verify_request(&self, user_id: OwnedUserId) -> IambResult<EditInfo> {
996 let (reply, response) = oneshot();
997
998 self.tx.send(WorkerTask::VerifyRequest(user_id, reply)).unwrap();
999
1000 return response.recv();
1001 }
1002
1003969 pub fn load_image(
1004970 &self,
1005971 source: MediaSource,
@@ -1101,14 +1067,6 @@ impl ClientWorker {
11011067 assert!(self.initialized);
11021068 self.typing_notice(room_id).await;
11031069 },
1104 WorkerTask::Verify(act, sas, reply) => {
1105 assert!(self.initialized);
1106 reply.send(self.verify(act, sas).await);
1107 },
1108 WorkerTask::VerifyRequest(user_id, reply) => {
1109 assert!(self.initialized);
1110 reply.send(self.verify_request(user_id).await);
1111 },
11121070 WorkerTask::LoadImage(source, kind, size, picker, permits) => {
11131071 assert!(self.initialized);
11141072 tokio::spawn(crate::preview::load_image(
@@ -1179,13 +1137,16 @@ impl ClientWorker {
11791137 let room_id = room.room_id();
11801138
11811139 if let Some(msg) = ev.as_original() &&
1182 let MessageType::VerificationRequest(_) = msg.content.msgtype &&
1183 let Some(request) = client
1184 .encryption()
1185 .get_verification_request(ev.sender(), ev.event_id())
1186 .await
1140 let MessageType::VerificationRequest(content) = &msg.content.msgtype
11871141 {
1188 request.accept().await.expect("Failed to accept request");
1142 verifications::handle_request(
1143 ev.event_id().into(),
1144 ev.sender().into(),
1145 content.from_device.clone(),
1146 client.clone(),
1147 Arc::clone(&store.0),
1148 )
1149 .await
11891150 }
11901151
11911152 let mut locked = store.lock().await;
@@ -1326,115 +1287,93 @@ impl ClientWorker {
13261287 );
13271288
13281289 let _ = self.client.add_event_handler(
1329 |ev: OriginalSyncKeyVerificationStartEvent,
1330 client: Client,
1331 store: Ctx<AsyncProgramStore>| {
1332 async move {
1333 let tx_id = ev.content.relates_to.event_id.as_ref();
1334
1335 if let Some(Verification::SasV1(sas)) =
1336 client.encryption().get_verification(&ev.sender, tx_id).await
1337 {
1338 sas.accept().await.unwrap();
1339
1340 store.lock().await.application.insert_sas(sas)
1341 }
1342 }
1343 },
1344 );
1345
1346 let _ = self.client.add_event_handler(
1347 |ev: OriginalSyncKeyVerificationKeyEvent,
1290 |ev: ToDeviceKeyVerificationRequestEvent,
13481291 client: Client,
13491292 store: Ctx<AsyncProgramStore>| {
1350 async move {
1351 let tx_id = ev.content.relates_to.event_id.as_ref();
1352
1353 if let Some(Verification::SasV1(sas)) =
1354 client.encryption().get_verification(&ev.sender, tx_id).await
1355 {
1356 store.lock().await.application.insert_sas(sas);
1357 }
1358 }
1293 let span = tracing::info_span!(
1294 "to_device_verify_request",
1295 other_user_id = ?ev.sender,
1296 other_device_id = ?ev.content.from_device,
1297 flow_id = ?ev.content.transaction_id,
1298 );
1299 verifications::handle_request(
1300 ev.content.transaction_id.into(),
1301 ev.sender,
1302 ev.content.from_device,
1303 client,
1304 store.0,
1305 )
1306 .instrument(span)
13591307 },
13601308 );
13611309
13621310 let _ = self.client.add_event_handler(
1363 |ev: OriginalSyncKeyVerificationDoneEvent,
1311 |ev: ToDeviceKeyVerificationReadyEvent,
13641312 client: Client,
13651313 store: Ctx<AsyncProgramStore>| {
1366 async move {
1367 let tx_id = ev.content.relates_to.event_id.as_ref();
1368
1369 if let Some(Verification::SasV1(sas)) =
1370 client.encryption().get_verification(&ev.sender, tx_id).await
1371 {
1372 store.lock().await.application.insert_sas(sas);
1373 }
1374 }
1375 },
1376 );
1377
1378 let _ = self.client.add_event_handler(
1379 |ev: ToDeviceKeyVerificationRequestEvent, client: Client| {
1380 async move {
1381 let request = client
1382 .encryption()
1383 .get_verification_request(&ev.sender, &ev.content.transaction_id)
1384 .await;
1385
1386 if let Some(request) = request {
1387 request.accept().await.unwrap();
1388 }
1389 }
1314 let span = tracing::info_span!(
1315 "to_device_verify_ready",
1316 other_user_id = ?ev.sender,
1317 other_device_id = ?ev.content.from_device,
1318 flow_id = ?ev.content.transaction_id,
1319 );
1320 verifications::handle_ready(
1321 ev.content.transaction_id.into(),
1322 ev.sender,
1323 client,
1324 store.0,
1325 )
1326 .instrument(span)
13901327 },
13911328 );
13921329
13931330 let _ = self.client.add_event_handler(
1394 |ev: ToDeviceKeyVerificationStartEvent,
1331 |ev: OriginalSyncKeyVerificationReadyEvent,
13951332 client: Client,
13961333 store: Ctx<AsyncProgramStore>| {
1397 async move {
1398 let tx_id = ev.content.transaction_id;
1399
1400 if let Some(Verification::SasV1(sas)) =
1401 client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
1402 {
1403 sas.accept().await.unwrap();
1404
1405 store.lock().await.application.insert_sas(sas);
1406 }
1407 }
1334 let span = tracing::info_span!(
1335 "room_verify_ready",
1336 other_user_id = ?ev.sender,
1337 other_device_id = ?ev.content.from_device,
1338 flow_id = ?ev.content.relates_to.event_id,
1339 );
1340 verifications::handle_ready(
1341 ev.content.relates_to.event_id.into(),
1342 ev.sender,
1343 client,
1344 store.0,
1345 )
1346 .instrument(span)
14081347 },
14091348 );
14101349
14111350 let _ = self.client.add_event_handler(
1412 |ev: ToDeviceKeyVerificationKeyEvent, client: Client, store: Ctx<AsyncProgramStore>| {
1413 async move {
1414 let tx_id = ev.content.transaction_id;
1415
1416 if let Some(Verification::SasV1(sas)) =
1417 client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
1418 {
1419 store.lock().await.application.insert_sas(sas);
1420 }
1421 }
1351 |ev: ToDeviceKeyVerificationStartEvent, client: Client| {
1352 let span = tracing::info_span!(
1353 "to_device_verify_start",
1354 other_user_id = ?ev.sender,
1355 other_device_id = ?ev.content.from_device,
1356 flow_id = ?ev.content.transaction_id,
1357 );
1358 verifications::handle_start(ev.content.transaction_id.into(), ev.sender, client)
1359 .instrument(span)
14221360 },
14231361 );
14241362
14251363 let _ = self.client.add_event_handler(
1426 |ev: ToDeviceKeyVerificationDoneEvent,
1427 client: Client,
1428 store: Ctx<AsyncProgramStore>| {
1429 async move {
1430 let tx_id = ev.content.transaction_id;
1431
1432 if let Some(Verification::SasV1(sas)) =
1433 client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
1434 {
1435 store.lock().await.application.insert_sas(sas);
1436 }
1437 }
1364 |ev: OriginalSyncKeyVerificationStartEvent, client: Client| {
1365 let span = tracing::info_span!(
1366 "room_verify_start",
1367 other_user_id = ?ev.sender,
1368 other_device_id = ?ev.content.from_device,
1369 flow_id = ?ev.content.relates_to.event_id
1370 );
1371 verifications::handle_start(
1372 ev.content.relates_to.event_id.into(),
1373 ev.sender,
1374 client,
1375 )
1376 .instrument(span)
14381377 },
14391378 );
14401379
@@ -1628,71 +1567,4 @@ impl ClientWorker {
16281567 let _ = room.typing_notice(true).await;
16291568 }
16301569 }
1631
1632 async fn verify(&self, action: VerifyAction, sas: SasVerification) -> IambResult<EditInfo> {
1633 match action {
1634 VerifyAction::Accept => {
1635 sas.accept().await.map_err(IambError::from)?;
1636
1637 Ok(Some(InfoMessage::from("Accepted verification request")))
1638 },
1639 VerifyAction::Confirm => {
1640 if sas.is_done() || sas.is_cancelled() {
1641 let msg = "Can only confirm in-progress verifications!";
1642 let err = UIError::Failure(msg.into());
1643
1644 return Err(err);
1645 }
1646
1647 sas.confirm().await.map_err(IambError::from)?;
1648
1649 Ok(Some(InfoMessage::from("Confirmed verification")))
1650 },
1651 VerifyAction::Cancel => {
1652 if sas.is_done() || sas.is_cancelled() {
1653 let msg = "Can only cancel in-progress verifications!";
1654 let err = UIError::Failure(msg.into());
1655
1656 return Err(err);
1657 }
1658
1659 sas.cancel().await.map_err(IambError::from)?;
1660
1661 Ok(Some(InfoMessage::from("Cancelled verification")))
1662 },
1663 VerifyAction::Mismatch => {
1664 if sas.is_done() || sas.is_cancelled() {
1665 let msg = "Can only cancel in-progress verifications!";
1666 let err = UIError::Failure(msg.into());
1667
1668 return Err(err);
1669 }
1670
1671 sas.mismatch().await.map_err(IambError::from)?;
1672
1673 Ok(Some(InfoMessage::from("Cancelled verification")))
1674 },
1675 }
1676 }
1677
1678 async fn verify_request(&self, user_id: OwnedUserId) -> IambResult<EditInfo> {
1679 let enc = self.client.encryption();
1680
1681 match enc.get_user_identity(user_id.as_ref()).await.map_err(IambError::from)? {
1682 Some(identity) => {
1683 let methods = vec![VerificationMethod::SasV1];
1684 let request = identity.request_verification_with_methods(methods);
1685 let _req = request.await.map_err(IambError::from)?;
1686 let info = format!("Sent verification request to {user_id}");
1687
1688 Ok(Some(InfoMessage::from(info)))
1689 },
1690 None => {
1691 let msg = format!("Could not find identity information for {user_id}");
1692 let err = UIError::Failure(msg);
1693
1694 Err(err)
1695 },
1696 }
1697 }
16981570}