Files
buzz/desktop/src-tauri/src/commands/pairing_generation_tests.rs
Taylor Ho 6eb65919f1 feat(identity): recover desktop identity from a signed-in phone (#4845)
**Category:** new-feature
**User Impact:** People who lose a desktop identity can securely restore
it from a signed-in Buzz phone without creating a replacement identity.

**Problem:** A fresh or identity-lost desktop could not recover its
existing full Buzz identity from an already-authorized phone.

**Solution:** Add a SAS-confirmed reverse NIP-AB transfer, durable
desktop import, a dedicated mobile recovery entry point, and clearer
desktop recovery dialogs with tested loading, drag-and-drop, and failure
states.


https://github.com/user-attachments/assets/e9215c9c-80d0-462f-9161-0fa184ca2f74

<details>
<summary>File changes</summary>

**crates/buzz-core/src/pairing/session.rs**
Adds the reverse encrypted payload and source-completion state
transitions used for phone-to-desktop recovery.

**desktop/src-tauri/src/commands/identity.rs**
Exposes the existing guarded identity commit path for recovery imports.

**desktop/src-tauri/src/commands/pairing.rs**
Adds recovery-mode pairing, durable nsec import, start serialization,
stale-task protection, and explicit rejection of unsupported recovery
payloads.

**desktop/src-tauri/src/lib.rs**
Registers the recovery pairing command.

**desktop/src/app/App.tsx**
Refreshes the recovered identity before continuing onboarding.

**desktop/src/features/onboarding/machineOnboarding.ts**
Adds recovery transitions to the onboarding state machine.

**desktop/src/features/onboarding/ui/BackupPasswordTimeline.tsx**
Adds the visual backup-to-password-to-unlock progression.

**desktop/src/features/onboarding/ui/IdentityRecoveryPairing.tsx**
Implements QR generation, copy fallback, SAS confirmation, cancellation,
expiry, and completion UI.

**desktop/src/features/onboarding/ui/MachineOnboardingFlow.tsx**
Connects private-key, phone, and backup recovery paths to the onboarding
flow.

**desktop/src/features/onboarding/ui/NostrKeyImportForm.tsx**
Polishes recovery dialogs, backup drag-and-drop, loading stability, and
security copy.

**desktop/src/shared/api/tauri.ts**
Keeps the existing pairing API surface focused on standard
desktop-to-mobile pairing.

**desktop/src/shared/api/tauriPairing.ts**
Adds the recovery pairing invoke without growing the ratcheted shared
API file.

**desktop/src/testing/e2eBridge.ts**
Mocks recovery pairing commands and lifecycle events for browser tests.

**desktop/tests/e2e/identity-lost.spec.ts**
Covers lost-identity entry, QR/copy recovery, SAS, cancellation, expiry,
success, errors, backup import, drag-and-drop, and screenshots.

**desktop/tests/e2e/onboarding.spec.ts**
Verifies recovered identities continue through harness setup without
replacement-key side effects.

**mobile/lib/features/pairing/pairing_page.dart**
Adds recovery-only scanning and explicit identity-handoff warnings.

**mobile/lib/features/pairing/pairing_provider.dart**
Recognizes recovery codes, returns the signed-in nsec after mutual SAS
approval, and waits for desktop completion.

**mobile/lib/features/settings/settings_page.dart**
Accepts the recovery route builder at the app composition boundary to
preserve feature isolation.

**mobile/lib/features/settings/settings_page/connection_section.dart**
Adds the signed-in “Send identity to desktop” settings action.

**mobile/test/features/pairing/pairing_page_test.dart**
Covers recovery-only validation and handoff messaging.

**mobile/test/features/pairing/pairing_provider_test.dart**
Covers reverse payload encryption, confirmation ordering, success,
failure, timeout, and cleanup.

</details>

## Reproduction steps

1. Launch Buzz Desktop with identity-lost state and choose **Recover
from your phone**.
2. Confirm the QR and persistent **Copy pairing code** fallback appear
without layout shift.
3. On a signed-in phone, open **Settings → Send identity to desktop**,
scan or paste the recovery code, and compare the six-digit SAS on both
devices.
4. Confirm on both sides and verify Desktop restores the identity and
continues to harness setup.
5. Repeat from identity-lost state with **Recover from a backup file**;
verify picker and drag-and-drop both advance to password entry and
restore the encrypted backup.
6. Exercise cancellation, mismatched/unsupported codes, expired
sessions, and an invalid backup; verify each returns actionable,
non-stuck UI.

## Screenshots

### Desktop phone recovery — complete flow

| Recovery entry | Pairing QR | Code match | Receiving identity |
|---|---|---|---|
| ![Desktop recovery
entry](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/desktop-phone-01-recovery-entry.png)
| ![Desktop phone recovery
QR](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/desktop-phone-02-qr.png)
| ![Desktop security-code
match](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/desktop-phone-03-sas.png)
| ![Desktop receiving
identity](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/desktop-phone-04-receiving.png)
|

### iOS Simulator — complete handoff flow

| Settings entry | Recovery scanner | Manual recovery code | Code
confirmation |
|---|---|---|---|
| ![iOS Settings entry for Send identity to
desktop](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/ios-01-settings-entry.png)
| ![iOS recovery scanner
entry](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/ios-02-recovery-entry.png)
| ![iOS manual recovery code
entry](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/ios-03-manual-code.png)
| ![iOS security-code
confirmation](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/ios-04-sas-verification.png)
|

### Encrypted backup recovery — adjusted file flow

| File picker | Drag-and-drop target | Password step |
|---|---|---|
| ![Desktop encrypted-backup file
picker](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/desktop-backup-01-file-picker-settled.png)
| ![Desktop encrypted-backup drag-and-drop
target](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/desktop-backup-02-drag-drop.png)
| ![Desktop backup password
step](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/4845/desktop-backup-03-enter-password.png)
|

## Verification

- `cargo test -p buzz-core pairing` — 71 passed
- `just mobile-test` — 1,169 passed
- `pnpm build:e2e && pnpm exec playwright test identity-lost.spec.ts
--project=smoke` — 15 passed
- Full pre-push gates — desktop checks, desktop unit tests, Rust tests,
Tauri checks, and mobile tests passed

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Co-authored-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz>
Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz>
2026-08-06 11:47:18 -07:00

130 lines
4.8 KiB
Rust

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use super::{
clear_pairing_session_if_current, commit_recovery_if_current, invalidate_pairing_generation,
recovery_result_after_completion, validate_recovery_payload_type, PairingHandle,
PairingSession, PayloadType,
};
#[tokio::test]
async fn overlapping_starts_are_serialized() {
let pairing = Arc::new(PairingHandle::new());
let first_pairing = Arc::clone(&pairing);
let (locked_tx, locked_rx) = tokio::sync::oneshot::channel();
let first = tokio::spawn(async move {
let _guard = first_pairing.start_lock.lock().await;
locked_tx.send(()).expect("signal acquired start lock");
tokio::time::sleep(Duration::from_millis(50)).await;
});
locked_rx.await.expect("first start acquired lock");
assert!(pairing.start_lock.try_lock().is_err());
first.await.expect("first start task");
assert!(pairing.start_lock.try_lock().is_ok());
}
#[test]
fn recovery_rejects_non_nsec_payloads() {
assert!(validate_recovery_payload_type(PayloadType::Nsec).is_ok());
assert_eq!(
validate_recovery_payload_type(PayloadType::Custom).unwrap_err(),
"Mobile device sent an unsupported recovery payload"
);
}
#[test]
fn superseded_recovery_cannot_commit_identity() {
let generation = AtomicU64::new(2);
let committed = std::sync::atomic::AtomicBool::new(false);
let generation_fence = std::sync::Mutex::new(());
let result = commit_recovery_if_current(&generation, &generation_fence, 1, || {
committed.store(true, Ordering::SeqCst);
Ok(())
});
assert_eq!(
result.unwrap_err(),
"Pairing session was superseded or cancelled"
);
assert!(!committed.load(Ordering::SeqCst));
}
#[test]
fn invalidation_after_check_waits_for_identity_commit() {
let generation = Arc::new(AtomicU64::new(7));
let generation_fence = Arc::new(std::sync::Mutex::new(()));
let (checked_tx, checked_rx) = std::sync::mpsc::channel();
let (finish_tx, finish_rx) = std::sync::mpsc::channel();
let committed = Arc::new(std::sync::atomic::AtomicBool::new(false));
let recovery_generation = Arc::clone(&generation);
let recovery_fence = Arc::clone(&generation_fence);
let recovery_committed = Arc::clone(&committed);
let recovery = std::thread::spawn(move || {
commit_recovery_if_current(&recovery_generation, &recovery_fence, 7, || {
checked_tx.send(()).expect("signal generation checked");
finish_rx.recv().expect("release identity commit");
recovery_committed.store(true, Ordering::SeqCst);
Ok(())
})
});
checked_rx.recv().expect("generation checked");
let invalidation_generation = Arc::clone(&generation);
let invalidation_fence = Arc::clone(&generation_fence);
let (attempted_tx, attempted_rx) = std::sync::mpsc::channel();
let (invalidated_tx, invalidated_rx) = std::sync::mpsc::channel();
let invalidation = std::thread::spawn(move || {
attempted_tx.send(()).expect("signal invalidation attempt");
let next = invalidate_pairing_generation(&invalidation_generation, &invalidation_fence)
.expect("invalidate generation");
invalidated_tx.send(next).expect("signal invalidated");
});
attempted_rx.recv().expect("invalidation attempted");
assert!(invalidated_rx
.recv_timeout(Duration::from_millis(50))
.is_err());
assert!(!committed.load(Ordering::SeqCst));
finish_tx.send(()).expect("finish identity commit");
recovery.join().expect("recovery task").unwrap();
assert!(committed.load(Ordering::SeqCst));
assert_eq!(invalidated_rx.recv().expect("invalidation completed"), 8);
invalidation.join().expect("invalidation task");
}
#[test]
fn completion_publish_failure_does_not_undo_successful_import() {
assert!(recovery_result_after_completion(Ok(()), Err("socket closed".into())).is_ok());
}
#[tokio::test]
async fn stale_task_does_not_clear_replacement_session() {
let (initial, _) = PairingSession::new_source("ws://initial.example".to_string());
let session = Arc::new(tokio::sync::Mutex::new(Some(initial)));
let generation = AtomicU64::new(1);
generation.store(2, Ordering::SeqCst);
let (replacement, _) = PairingSession::new_source("ws://replacement.example".to_string());
*session.lock().await = Some(replacement);
clear_pairing_session_if_current(&session, &generation, 1).await;
assert!(session.lock().await.is_some());
}
#[tokio::test]
async fn current_task_clears_its_session() {
let (active, _) = PairingSession::new_source("ws://active.example".to_string());
let session = Arc::new(tokio::sync::Mutex::new(Some(active)));
let generation = AtomicU64::new(3);
clear_pairing_session_if_current(&session, &generation, 3).await;
assert!(session.lock().await.is_none());
}