Skip to content

Commit 5173fad

Browse files
authored
feat(pairing): enter desktop codes on mobile (#8085)
## Summary Enter a desktop-only, random six-digit code on mobile to pair without a desktop confirmation click. Verification uses the encrypted session, limits guesses to five, and never treats the QR-derived transcript as approval. Older clients retain desktop confirmation. Adds digit-only error shakes and native haptics, a separate biometrics choice, and a direct community-icon arrival animation. Fixes dropped early offers and resets completed pairing so reopening or signing out cannot get stuck. ### Related issue Related: #8060; no duplicate code-entry PR found. <img width="780" height="1688" alt="01-enter-code" src="https://github.com/user-attachments/assets/a99ced3e-4305-4ac6-a6cc-d598ced423e7" /> <img width="780" height="1688" alt="02-incorrect-code" src="https://github.com/user-attachments/assets/19cdb109-1f10-40a9-a661-1d7ba89c81c1" /> <img width="780" height="1688" alt="03-biometrics" src="https://github.com/user-attachments/assets/af1b2924-9ab6-4d1a-b4b1-fccfdf446404" /> <img width="780" height="1688" alt="04-community-loading" src="https://github.com/user-attachments/assets/84145d82-843a-4c25-aef7-6492fc241d4b" /> <img width="897" height="388" alt="05-desktop-code" src="https://github.com/user-attachments/assets/d8a2e469-7e42-466a-988f-bab6b1df85fc" /> ### Release order Deploy the updated pairing relay first, then desktop, then mobile. The relay now allows eight events per connection (seven for a successful fifth guess plus room for cancellation), with a corresponding bounded delivery budget. Existing clients remain supported; older client combinations keep desktop confirmation. ### Testing - 103 mobile pairing tests, 270 core tests, 51 relay integration tests, and the new real-relay fifth-guess flow passed. - The real-relay regression verifies proof, decrypted identity import, and completion after four wrong guesses. Restoring the old six-event cap makes it fail. - A paused-clock desktop regression confirms slow readiness cannot extend the visible QR beyond protocol expiry. Mobile regression covers typing before negotiation completes. - Core/pair-relay Clippy and full native desktop Clippy/workspace tests passed. Mobile analysis passed; broad mobile runs each hit an unrelated failure (a gateway-script timeout and a native-menu missing-plugin error), and both affected test files passed separately. - Repository-wide Rust testing exhausted local disk space while compiling unrelated packages. The final push omitted that resource-blocked hook and avoided repeating the desktop/mobile runs above; hosted CI remains required. --------- Signed-off-by: kenny lopez <[email protected]>
1 parent 7f6ffd5 commit 5173fad

38 files changed

Lines changed: 3094 additions & 687 deletions

‎Cargo.lock‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/buzz-core/src/pairing/session.rs‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@
2727
//! handle_complete(&event) → complete_event
2828
//! ```
2929
30+
//! # Code-entry confirmation extension
31+
//!
32+
//! A target advertises `"confirmation":"desktop-code-v1"` in its encrypted
33+
//! offer. The source generates a separate random six-digit code, never included
34+
//! in the QR or challenge. The target submits user input through NIP-44. Only a
35+
//! matching code releases the source proof and payload; five guesses abort the
36+
//! entire session. Legacy offers still require explicit source-side approval.
37+
3038
use std::collections::HashSet;
3139
use std::time::{Duration, Instant};
3240

@@ -104,6 +112,9 @@ pub struct PairingSession {
104112
created_at: Instant,
105113
/// Maximum session lifetime.
106114
timeout: Duration,
115+
desktop_code_requested: bool,
116+
desktop_code: Option<Zeroizing<String>>,
117+
code_attempts: u8,
107118
}
108119

109120
impl PairingSession {
@@ -136,6 +147,9 @@ impl PairingSession {
136147
processed_ids: HashSet::new(),
137148
created_at: Instant::now(),
138149
timeout: DEFAULT_TIMEOUT,
150+
desktop_code_requested: false,
151+
desktop_code: None,
152+
code_attempts: 0,
139153
};
140154

141155
(session, qr)
@@ -147,17 +161,33 @@ impl PairingSession {
147161
/// formatted SAS code to display. After this call the session is in
148162
/// [`SessionState::Confirming`].
149163
pub fn handle_offer(&mut self, event: &Event) -> Result<String, PairingError> {
164+
self.handle_offer_with_confirmation(event)
165+
.map(|(code, _)| code)
166+
}
167+
168+
/// Validate an offer and return its SAS and whether the target requests
169+
/// code-entry confirmation. The capability is encrypted so strict relays
170+
/// still receive only the required recipient tag.
171+
pub fn handle_offer_with_confirmation(
172+
&mut self,
173+
event: &Event,
174+
) -> Result<(String, bool), PairingError> {
150175
self.check_expired()?;
151176
self.expect_state(SessionState::Waiting)?;
152177
self.expect_role(Role::Source)?;
153178
self.validate_event_basics(event)?;
154179

155180
let msg = self.decrypt_message(event)?;
156-
let (session_id_hex, version) = match &msg {
181+
let (session_id_hex, version, code_entry) = match &msg {
157182
PairingMessage::Offer {
158183
session_id,
159184
version,
160-
} => (session_id.clone(), *version),
185+
confirmation,
186+
} => (
187+
session_id.clone(),
188+
*version,
189+
confirmation.as_deref() == Some("desktop-code-v1"),
190+
),
161191
other => return Err(unexpected("offer", other)),
162192
};
163193

@@ -192,7 +222,8 @@ impl PairingSession {
192222
self.state = SessionState::Confirming;
193223
self.record_event(event);
194224

195-
Ok(format_sas(code))
225+
self.desktop_code_requested = code_entry;
226+
Ok((format_sas(code), code_entry))
196227
}
197228

198229
/// (Source) User confirmed the SAS codes match. Build the `sas-confirm`
@@ -349,12 +380,16 @@ impl PairingSession {
349380
processed_ids: HashSet::new(),
350381
created_at: Instant::now(),
351382
timeout: DEFAULT_TIMEOUT,
383+
desktop_code_requested: false,
384+
desktop_code: None,
385+
code_attempts: 0,
352386
};
353387

354388
// Build and return the offer event.
355389
let msg = PairingMessage::Offer {
356390
session_id: hex::encode(session_id),
357391
version: 1,
392+
confirmation: None,
358393
};
359394
let event = session.build_event(&msg)?;
360395
session.state = SessionState::Confirming;
@@ -514,9 +549,15 @@ impl PairingSession {
514549
}
515550
}
516551

552+
/// Absolute protocol deadline. Transports must use this same deadline for
553+
/// UI expiry so connection setup never adds time to an expired QR.
554+
pub fn deadline(&self) -> Instant {
555+
self.created_at + self.timeout
556+
}
557+
517558
/// Check if the session has expired.
518559
pub fn is_expired(&self) -> bool {
519-
self.created_at.elapsed() > self.timeout
560+
Instant::now() >= self.deadline()
520561
}
521562

522563
/// Current protocol state.
@@ -784,6 +825,9 @@ impl Drop for PairingSession {
784825
fn unexpected(expected: &str, got: &PairingMessage) -> PairingError {
785826
let got_name = match got {
786827
PairingMessage::Offer { .. } => "offer",
828+
PairingMessage::DesktopCode {} => "desktop-code",
829+
PairingMessage::CodeSubmit { .. } => "code-submit",
830+
PairingMessage::CodeRejected { .. } => "code-rejected",
787831
PairingMessage::SasConfirm { .. } => "sas-confirm",
788832
PairingMessage::Payload { .. } => "payload",
789833
PairingMessage::Complete { .. } => "complete",
@@ -1423,3 +1467,10 @@ mod tests {
14231467
);
14241468
}
14251469
}
1470+
1471+
#[cfg(test)]
1472+
#[path = "session_code_entry_tests.rs"]
1473+
mod code_entry_tests;
1474+
1475+
#[path = "session_desktop_code.rs"]
1476+
mod desktop_code;
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
use super::*;
2+
3+
fn setup() -> (PairingSession, PairingSession, String) {
4+
let (mut source, qr) = PairingSession::new_source("wss://relay.test".into());
5+
let (target, _) = PairingSession::new_target(&qr).expect("target");
6+
let offer = target
7+
.build_event(&PairingMessage::Offer {
8+
session_id: hex::encode(target.session_id),
9+
version: 1,
10+
confirmation: Some("desktop-code-v1".into()),
11+
})
12+
.expect("offer");
13+
assert!(
14+
source
15+
.handle_offer_with_confirmation(&offer)
16+
.expect("offer")
17+
.1
18+
);
19+
let (code, challenge) = source.start_desktop_code().expect("challenge");
20+
assert_eq!(
21+
target.decrypt_message(&challenge).expect("decrypt"),
22+
PairingMessage::DesktopCode {}
23+
);
24+
assert_eq!(code.len(), 6);
25+
(source, target, code)
26+
}
27+
28+
fn submission(target: &PairingSession, code: &str, attempt: u8) -> Event {
29+
target
30+
.build_event(&PairingMessage::CodeSubmit {
31+
code: code.into(),
32+
request_id: attempt.to_string(),
33+
})
34+
.expect("submission")
35+
}
36+
37+
#[test]
38+
fn only_source_only_code_releases_identity() {
39+
let (mut source, mut target, code) = setup();
40+
assert!(source
41+
.send_payload(PayloadType::Custom, Zeroizing::new("secret".into()))
42+
.is_err());
43+
let event = submission(&target, &code, 1);
44+
let (proof, accepted) = source.handle_target_code(&event).expect("verify");
45+
assert!(accepted);
46+
assert!(source.handle_target_code(&event).is_err());
47+
target.handle_sas_confirm(&proof).expect("source proof");
48+
target.confirm_target_sas().expect("user approves import");
49+
let payload = source
50+
.send_payload(PayloadType::Custom, Zeroizing::new("secret".into()))
51+
.expect("payload");
52+
assert_eq!(
53+
&*target.handle_payload(&payload).expect("import").1,
54+
"secret"
55+
);
56+
}
57+
58+
#[test]
59+
fn qr_derived_transcript_cannot_authorize_release() {
60+
let (mut source, target, _) = setup();
61+
let hash = derive_transcript_hash(
62+
&target.session_id,
63+
&source.pubkey().to_bytes(),
64+
&target.pubkey().to_bytes(),
65+
&target.sas_input.expect("sas"),
66+
&target.session_secret,
67+
);
68+
let event = target
69+
.build_event(&PairingMessage::SasConfirm {
70+
transcript_hash: hex::encode(hash),
71+
})
72+
.expect("proof");
73+
assert!(source.handle_target_code(&event).is_err());
74+
assert_eq!(source.state(), SessionState::Confirming);
75+
assert!(source
76+
.send_payload(PayloadType::Custom, Zeroizing::new("secret".into()))
77+
.is_err());
78+
}
79+
80+
#[test]
81+
fn five_wrong_guesses_abort_without_reset_or_replay_bypass() {
82+
let (mut source, target, code) = setup();
83+
let wrong = if code == "000000" { "000001" } else { "000000" };
84+
for attempt in 1..=5 {
85+
let event = submission(&target, wrong, attempt);
86+
let (reply, accepted) = source.handle_target_code(&event).expect("reject");
87+
assert!(!accepted);
88+
assert_eq!(
89+
target.decrypt_message(&reply).expect("reply"),
90+
PairingMessage::CodeRejected {
91+
request_id: attempt.to_string(),
92+
remaining_attempts: 5 - attempt
93+
}
94+
);
95+
assert!(
96+
source.handle_target_code(&event).is_err(),
97+
"duplicate submission"
98+
);
99+
assert!(
100+
source.start_desktop_code().is_err(),
101+
"cannot regenerate code/budget"
102+
);
103+
assert!(source
104+
.send_payload(PayloadType::Custom, Zeroizing::new("secret".into()))
105+
.is_err());
106+
}
107+
assert_eq!(source.state(), SessionState::Aborted);
108+
assert!(source
109+
.handle_target_code(&submission(&target, &code, 6))
110+
.is_err());
111+
}
112+
113+
#[test]
114+
fn wrong_then_correct_code_succeeds() {
115+
let (mut source, target, code) = setup();
116+
let wrong = if code == "000000" { "000001" } else { "000000" };
117+
assert!(
118+
!source
119+
.handle_target_code(&submission(&target, wrong, 1))
120+
.expect("reject")
121+
.1
122+
);
123+
assert!(
124+
source
125+
.handle_target_code(&submission(&target, &code, 2))
126+
.expect("accept")
127+
.1
128+
);
129+
}
130+
131+
#[test]
132+
fn wrong_peer_tampering_and_expiry_cannot_authorize() {
133+
let (mut source, target, code) = setup();
134+
let (other, _) = PairingSession::new_source("wss://relay.test".into());
135+
let mut bad = submission(&target, &code, 1);
136+
bad.pubkey = other.pubkey();
137+
assert!(source.handle_target_code(&bad).is_err());
138+
let mut tampered = submission(&target, &code, 2);
139+
tampered.content.push('x');
140+
assert!(source.handle_target_code(&tampered).is_err());
141+
assert_eq!(source.code_attempts, 0);
142+
source.created_at = Instant::now() - source.timeout - Duration::from_secs(1);
143+
assert!(source
144+
.handle_target_code(&submission(&target, &code, 3))
145+
.is_err());
146+
}
147+
148+
#[test]
149+
fn legacy_capabilities_never_enable_automatic_release() {
150+
for capability in [
151+
None,
152+
Some("code-entry"),
153+
Some("unknown"),
154+
Some("desktop-code-v1"),
155+
] {
156+
let (mut source, qr) = PairingSession::new_source("wss://relay.test".into());
157+
let (target, _) = PairingSession::new_target(&qr).expect("target");
158+
let event = target
159+
.build_event(&PairingMessage::Offer {
160+
session_id: hex::encode(target.session_id),
161+
version: 1,
162+
confirmation: capability.map(str::to_string),
163+
})
164+
.expect("offer");
165+
assert_eq!(event.tags.len(), 1);
166+
let (_, enabled) = source
167+
.handle_offer_with_confirmation(&event)
168+
.expect("offer");
169+
assert_eq!(enabled, capability == Some("desktop-code-v1"));
170+
assert_eq!(source.start_desktop_code().is_ok(), enabled);
171+
}
172+
}
173+
174+
#[test]
175+
fn readiness_delay_and_late_scan_share_the_original_deadline() {
176+
let (mut source, qr) = PairingSession::new_source("wss://relay.test".into());
177+
// Simulate the maximum 35-second readiness wait without sleeping.
178+
source.created_at = Instant::now() - Duration::from_secs(35);
179+
let deadline = source.deadline();
180+
let remaining = deadline.saturating_duration_since(Instant::now());
181+
assert!(remaining <= Duration::from_secs(85));
182+
assert!(remaining > Duration::from_secs(84));
183+
// A scan 84 seconds after readiness still has one second to be accepted.
184+
source.created_at -= Duration::from_secs(84);
185+
let (_, offer) = PairingSession::new_target(&qr).unwrap();
186+
assert!(source.handle_offer(&offer).is_ok());
187+
assert!(!source.is_expired());
188+
// The transport deadline and protocol expiry both end the original window.
189+
source.created_at -= Duration::from_secs(2);
190+
assert!(source.deadline() < Instant::now());
191+
assert!(source.is_expired());
192+
assert!(matches!(
193+
source.confirm_sas(),
194+
Err(PairingError::SessionExpired)
195+
));
196+
}

0 commit comments

Comments
 (0)