1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use dioxus::prelude::*;
use futures_util::StreamExt;
use matrix_sdk::encryption::verification::{
QrVerification, QrVerificationData, QrVerificationState, VerificationRequest,
VerificationRequestState,
};
use matrix_sdk::ruma::events::key::verification::VerificationMethod;
use qrcode::render::unicode::Dense1x2;
use crate::components::modal::Modal;
use crate::platform::file_dialog::{FileFilter, pick_file};
use crate::state::app_state::AppState;
fn render_qr_code(verification: &QrVerification) -> Result<String, String> {
let qr = verification
.to_qr_code()
.map_err(|e| format!("Failed to render verification QR code: {e}"))?;
Ok(qr
.render::<Dense1x2>()
.quiet_zone(false)
.module_dimensions(1, 1)
.build())
}
fn decode_qr_payload(bytes: &[u8]) -> Result<Vec<u8>, String> {
let image = image::load_from_memory(bytes)
.map_err(|e| format!("Failed to open QR image: {e}"))?
.to_luma8();
let mut decoder = quircs::Quirc::default();
for code in decoder.identify(image.width() as usize, image.height() as usize, &image) {
let code = code.map_err(|e| format!("Failed to read QR image: {e}"))?;
let decoded = code
.decode()
.map_err(|e| format!("Failed to decode QR code: {e}"))?;
return Ok(decoded.payload);
}
Err("No QR code was found in the selected image".to_string())
}
fn update_qr_progress(
qr_state: QrVerificationState,
mut status: Signal<String>,
mut awaiting_confirmation: Signal<bool>,
mut verified: Signal<bool>,
mut error: Signal<Option<String>>,
) -> bool {
match qr_state {
QrVerificationState::Started => {
status.set("Verification request is ready. Show or scan the QR code.".to_string());
false
}
QrVerificationState::Reciprocated => {
status.set("QR code scanned. Waiting for the other device to continue.".to_string());
false
}
QrVerificationState::Scanned => {
awaiting_confirmation.set(true);
status.set("QR code scanned. Confirm on this device to finish verification.".to_string());
false
}
QrVerificationState::Confirmed => {
awaiting_confirmation.set(false);
status.set("Confirmation sent. Waiting for verification to complete.".to_string());
false
}
QrVerificationState::Done { .. } => {
awaiting_confirmation.set(false);
verified.set(true);
status.set("Device verification completed successfully.".to_string());
true
}
QrVerificationState::Cancelled(cancel_info) => {
awaiting_confirmation.set(false);
error.set(Some(format!("Verification cancelled: {cancel_info:?}")));
true
}
}
}
async fn watch_qr_changes(
qr: QrVerification,
status: Signal<String>,
awaiting_confirmation: Signal<bool>,
verified: Signal<bool>,
error: Signal<Option<String>>,
) {
if update_qr_progress(
qr.state(),
status,
awaiting_confirmation,
verified,
error,
) {
return;
}
let mut changes = qr.changes();
while let Some(qr_state) = changes.next().await {
if update_qr_progress(qr_state, status, awaiting_confirmation, verified, error) {
break;
}
}
}
async fn watch_request_changes(
request: VerificationRequest,
mut active_qr: Signal<Option<QrVerification>>,
mut qr_display: Signal<Option<String>>,
mut status: Signal<String>,
awaiting_confirmation: Signal<bool>,
mut verified: Signal<bool>,
mut error: Signal<Option<String>>,
) {
let mut changes = request.changes();
while let Some(request_state) = changes.next().await {
match request_state {
VerificationRequestState::Created { .. } => {
status.set("Verification request created. Waiting for the other device.".to_string());
}
VerificationRequestState::Requested { .. } => {
status.set("Open another logged-in device and accept the verification request.".to_string());
}
VerificationRequestState::Ready { .. } => {
status.set("Verification accepted. QR code is ready.".to_string());
let has_qr = active_qr.read().is_some();
if has_qr {
continue;
}
match request.generate_qr_code().await {
Ok(Some(qr)) => match render_qr_code(&qr) {
Ok(rendered) => {
qr_display.set(Some(rendered));
active_qr.set(Some(qr.clone()));
spawn(watch_qr_changes(
qr,
status,
awaiting_confirmation,
verified,
error,
));
}
Err(err) => error.set(Some(err)),
},
Ok(None) => {
status.set("The other device is not ready for QR verification yet.".to_string());
}
Err(err) => {
error.set(Some(format!("Failed to generate QR verification: {err}")));
}
}
}
VerificationRequestState::Transitioned { .. } => {
status.set(
"This verification switched to a different method. Use emoji verification on the other device if needed."
.to_string(),
);
}
VerificationRequestState::Done => {
verified.set(true);
status.set("Device verification completed successfully.".to_string());
break;
}
VerificationRequestState::Cancelled(cancel_info) => {
error.set(Some(format!("Verification cancelled: {cancel_info:?}")));
break;
}
}
}
}
/// QR code verification dialog.
#[component]
pub fn QrVerificationDialog(on_close: EventHandler<()>) -> Element {
let state = use_context::<Signal<AppState>>();
let mut active_qr = use_signal(|| Option::<QrVerification>::None);
let mut error = use_signal(|| Option::<String>::None);
let mut flow_id = use_signal(String::new);
let mut loading = use_signal(|| true);
let mut loaded = use_signal(|| false);
let mut mode = use_signal(|| QrMode::ShowCode);
let qr_display = use_signal(|| Option::<String>::None);
let mut request_status = use_signal(|| "Starting verification request...".to_string());
let mut verification_request = use_signal(|| Option::<VerificationRequest>::None);
let awaiting_confirmation = use_signal(|| false);
let verified = use_signal(|| false);
let mut scan_busy = use_signal(|| false);
if !*loaded.read() {
loaded.set(true);
spawn(async move {
let client = { state.read().client.clone() };
let Some(client) = client else {
error.set(Some("Not logged in".to_string()));
loading.set(false);
return;
};
let Some(user_id) = client.user_id().map(ToOwned::to_owned) else {
error.set(Some("Unable to determine the current user".to_string()));
loading.set(false);
return;
};
let methods = vec![
VerificationMethod::SasV1,
VerificationMethod::QrCodeScanV1,
VerificationMethod::QrCodeShowV1,
VerificationMethod::ReciprocateV1,
];
match client.encryption().get_user_identity(&user_id).await {
Ok(Some(identity)) => match identity.request_verification_with_methods(methods).await {
Ok(request) => {
flow_id.set(request.flow_id().to_string());
verification_request.set(Some(request.clone()));
request_status.set(
"Verification request sent. Accept it on your other device to continue."
.to_string(),
);
spawn(watch_request_changes(
request,
active_qr,
qr_display,
request_status,
awaiting_confirmation,
verified,
error,
));
}
Err(err) => {
error.set(Some(format!("Failed to create verification request: {err}")));
}
},
Ok(None) => {
error.set(Some(
"Your account identity is not available yet. Wait for sync and try again."
.to_string(),
));
}
Err(err) => {
error.set(Some(format!("Failed to load your identity: {err}")));
}
}
loading.set(false);
});
}
rsx! {
Modal {
title: "Verify with QR Code".to_string(),
on_close: move |_| on_close.call(()),
div {
class: "qr-verification",
div {
class: "qr-verification__tabs",
button {
class: if *mode.read() == QrMode::ShowCode {
"qr-verification__tab qr-verification__tab--active"
} else {
"qr-verification__tab"
},
onclick: move |_| mode.set(QrMode::ShowCode),
"Show QR Code"
}
button {
class: if *mode.read() == QrMode::ScanCode {
"qr-verification__tab qr-verification__tab--active"
} else {
"qr-verification__tab"
},
onclick: move |_| mode.set(QrMode::ScanCode),
"Scan QR Code"
}
}
if *loading.read() {
div {
class: "qr-verification__loading",
div { class: "spinner" }
span { "Preparing verification request..." }
}
} else {
p {
class: "qr-verification__instructions",
"{request_status}"
}
if !flow_id.read().is_empty() {
p {
class: "qr-verification__hint",
"Flow ID: {flow_id}"
}
}
if let Some(ref err) = *error.read() {
div { class: "qr-verification__error", "{err}" }
}
if *verified.read() {
div {
class: "security-status",
span { class: "security-status__icon security-status__icon--ok", "✅" }
div {
class: "security-status__info",
span { class: "security-status__label", "Verification complete" }
span {
class: "security-status__description",
"This device is now verified."
}
}
}
} else if *mode.read() == QrMode::ShowCode {
div {
class: "qr-verification__show",
if let Some(ref rendered) = *qr_display.read() {
pre {
class: "qr-verification__grid",
"{rendered}"
}
p {
class: "qr-verification__instructions",
"Scan this code from your other Matrix client."
}
} else {
p {
class: "qr-verification__hint",
"The QR code will appear here once the other device accepts the verification request."
}
}
}
} else {
div {
class: "qr-verification__scan",
p { "Choose an image containing the QR code shown by your other device." }
button {
class: "btn btn--primary",
disabled: *scan_busy.read(),
onclick: move |_| {
error.set(None);
scan_busy.set(true);
let request = verification_request.read().as_ref().cloned();
spawn(async move {
let Some(request) = request else {
error.set(Some("Verification request is not available yet.".to_string()));
scan_busy.set(false);
return;
};
let file = match pick_file(
"Choose a QR code image",
&[FileFilter {
name: "Images",
extensions: &["png", "jpg", "jpeg", "bmp", "gif", "webp"],
}],
)
.await
{
Ok(Some(file)) => file,
Ok(None) => {
scan_busy.set(false);
return;
}
Err(err) => {
error.set(Some(err));
scan_busy.set(false);
return;
}
};
let image_bytes = file.bytes;
let payload = match decode_qr_payload(&image_bytes) {
Ok(payload) => payload,
Err(err) => {
error.set(Some(err));
scan_busy.set(false);
return;
}
};
let qr_data = match QrVerificationData::from_bytes(payload) {
Ok(data) => data,
Err(err) => {
error.set(Some(format!("The selected QR code is not a Matrix verification code: {err}")));
scan_busy.set(false);
return;
}
};
match request.scan_qr_code(qr_data).await {
Ok(Some(qr)) => {
request_status.set(
"QR code imported. Waiting for the verification exchange to continue."
.to_string(),
);
active_qr.set(Some(qr.clone()));
spawn(watch_qr_changes(
qr,
request_status,
awaiting_confirmation,
verified,
error,
));
}
Ok(None) => {
error.set(Some(
"This verification flow is not ready to scan a QR code yet. Accept it on the other device first."
.to_string(),
));
}
Err(err) => {
error.set(Some(format!("Failed to scan QR code: {err}")));
}
}
scan_busy.set(false);
});
},
if *scan_busy.read() { "Scanning..." } else { "Choose QR Image" }
}
p {
class: "qr-verification__hint",
"Desktop builds use image import instead of a live camera feed."
}
}
}
div {
class: "qr-verification__actions",
if *awaiting_confirmation.read() {
button {
class: "btn btn--primary",
onclick: move |_| {
if let Some(qr) = active_qr.read().as_ref().cloned() {
error.set(None);
spawn(async move {
if let Err(err) = qr.confirm().await {
error.set(Some(format!("Failed to confirm QR verification: {err}")));
}
});
}
},
"Confirm Scan"
}
}
button {
class: "btn btn--secondary",
onclick: move |_| {
let qr = active_qr.read().as_ref().cloned();
let request = verification_request.read().as_ref().cloned();
spawn(async move {
if let Some(qr) = qr {
let _ = qr.cancel().await;
} else if let Some(request) = request {
let _ = request.cancel().await;
}
});
on_close.call(());
},
"Close"
}
}
}
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum QrMode {
ShowCode,
ScanCode,
}