|
| 1 | +//! Full desktop-code wire exchange through the production relay and source state machine. |
| 2 | +use std::{sync::Arc, time::Duration}; |
| 3 | + |
| 4 | +use buzz_core::pairing::{crypto, PairingSession, PayloadType, SessionState}; |
| 5 | +use buzz_pair_relay::{run_server, Relay}; |
| 6 | +use futures_util::{SinkExt, StreamExt}; |
| 7 | +use nostr::{nips::nip44, Event, EventBuilder, Keys, Kind, PublicKey, Tag, ToBech32}; |
| 8 | +use serde_json::{json, Value}; |
| 9 | +use tokio::net::TcpListener; |
| 10 | +use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream}; |
| 11 | +use zeroize::Zeroizing; |
| 12 | + |
| 13 | +type Socket = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>; |
| 14 | + |
| 15 | +async fn receive(socket: &mut Socket) -> Value { |
| 16 | + let frame = tokio::time::timeout(Duration::from_secs(2), socket.next()) |
| 17 | + .await |
| 18 | + .expect("relay response deadline") |
| 19 | + .expect("connection open") |
| 20 | + .expect("frame"); |
| 21 | + serde_json::from_str(frame.to_text().expect("text frame")).expect("relay JSON") |
| 22 | +} |
| 23 | + |
| 24 | +async fn subscribe(socket: &mut Socket, pubkey: PublicKey) { |
| 25 | + socket |
| 26 | + .send(Message::Text( |
| 27 | + json!(["REQ", "pair", { |
| 28 | + "kinds": [24134], "#p": [pubkey.to_hex()] |
| 29 | + }]) |
| 30 | + .to_string() |
| 31 | + .into(), |
| 32 | + )) |
| 33 | + .await |
| 34 | + .unwrap(); |
| 35 | + assert_eq!(receive(socket).await[0], "EOSE"); |
| 36 | +} |
| 37 | + |
| 38 | +async fn forward(sender: &mut Socket, receiver: &mut Socket, event: Event) -> Event { |
| 39 | + sender |
| 40 | + .send(Message::Text(json!(["EVENT", event]).to_string().into())) |
| 41 | + .await |
| 42 | + .unwrap(); |
| 43 | + let ack = receive(sender).await; |
| 44 | + assert_eq!(ack[0], "OK"); |
| 45 | + assert_eq!(ack[2], true, "relay must accept each protocol event: {ack}"); |
| 46 | + let delivery = receive(receiver).await; |
| 47 | + assert_eq!(delivery[0], "EVENT"); |
| 48 | + let received: Event = serde_json::from_value(delivery[2].clone()).unwrap(); |
| 49 | + received.verify().unwrap(); |
| 50 | + received |
| 51 | +} |
| 52 | + |
| 53 | +fn target_message(keys: &Keys, source: PublicKey, message: Value) -> Event { |
| 54 | + let encrypted = nip44::encrypt( |
| 55 | + keys.secret_key(), |
| 56 | + &source, |
| 57 | + message.to_string(), |
| 58 | + nip44::Version::V2, |
| 59 | + ) |
| 60 | + .unwrap(); |
| 61 | + EventBuilder::new(Kind::Custom(24134), encrypted) |
| 62 | + .tags([Tag::public_key(source)]) |
| 63 | + .sign_with_keys(keys) |
| 64 | + .unwrap() |
| 65 | +} |
| 66 | + |
| 67 | +fn decrypt(keys: &Keys, event: &Event) -> Value { |
| 68 | + serde_json::from_str(&nip44::decrypt(keys.secret_key(), &event.pubkey, &event.content).unwrap()) |
| 69 | + .unwrap() |
| 70 | +} |
| 71 | + |
| 72 | +#[tokio::test] |
| 73 | +async fn fifth_correct_guess_delivers_identity_and_completion() { |
| 74 | + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 75 | + let url = format!("ws://{}", listener.local_addr().unwrap()); |
| 76 | + let server = tokio::spawn(run_server(listener, Arc::new(Relay::new()))); |
| 77 | + let (mut source, qr) = PairingSession::new_source(url.clone()); |
| 78 | + let target = Keys::generate(); |
| 79 | + let (mut source_socket, _) = connect_async(&url).await.unwrap(); |
| 80 | + let (mut target_socket, _) = connect_async(&url).await.unwrap(); |
| 81 | + subscribe(&mut source_socket, source.pubkey()).await; |
| 82 | + subscribe(&mut target_socket, target.public_key()).await; |
| 83 | + let session_id = crypto::derive_session_id(&qr.session_secret); |
| 84 | + let hex = |bytes: &[u8]| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>(); |
| 85 | + let offer = target_message( |
| 86 | + &target, |
| 87 | + source.pubkey(), |
| 88 | + json!({ |
| 89 | + "type": "offer", "session_id": hex(&session_id), "version": 1, |
| 90 | + "confirmation": "desktop-code-v1" |
| 91 | + }), |
| 92 | + ); |
| 93 | + let offer = forward(&mut target_socket, &mut source_socket, offer).await; |
| 94 | + assert!(source.handle_offer_with_confirmation(&offer).unwrap().1); |
| 95 | + let (code, challenge) = source.start_desktop_code().unwrap(); |
| 96 | + let challenge = forward(&mut source_socket, &mut target_socket, challenge).await; |
| 97 | + assert_eq!( |
| 98 | + decrypt(&target, &challenge), |
| 99 | + json!({"type": "desktop-code"}) |
| 100 | + ); |
| 101 | + let wrong = if code == "000000" { "000001" } else { "000000" }; |
| 102 | + for attempt in 1..=5 { |
| 103 | + let submission = target_message( |
| 104 | + &target, |
| 105 | + source.pubkey(), |
| 106 | + json!({ |
| 107 | + "type": "code-submit", "code": if attempt == 5 { &code } else { wrong }, |
| 108 | + "request_id": attempt.to_string() |
| 109 | + }), |
| 110 | + ); |
| 111 | + let submission = forward(&mut target_socket, &mut source_socket, submission).await; |
| 112 | + let (response, accepted) = source.handle_target_code(&submission).unwrap(); |
| 113 | + assert_eq!(accepted, attempt == 5); |
| 114 | + let response = forward(&mut source_socket, &mut target_socket, response).await; |
| 115 | + let message = decrypt(&target, &response); |
| 116 | + if attempt < 5 { |
| 117 | + assert_eq!( |
| 118 | + message, |
| 119 | + json!({"type":"code-rejected", "request_id":attempt.to_string(), "remaining_attempts":5-attempt}) |
| 120 | + ); |
| 121 | + } else { |
| 122 | + let ecdh = |
| 123 | + nostr::util::generate_shared_key(target.secret_key(), &source.pubkey()).unwrap(); |
| 124 | + let (_, sas_input) = crypto::derive_sas(&ecdh, &qr.session_secret); |
| 125 | + let proof = crypto::derive_transcript_hash( |
| 126 | + &session_id, |
| 127 | + &source.pubkey().to_bytes(), |
| 128 | + &target.public_key().to_bytes(), |
| 129 | + &sas_input, |
| 130 | + &qr.session_secret, |
| 131 | + ); |
| 132 | + assert_eq!( |
| 133 | + message, |
| 134 | + json!({"type":"sas-confirm", "transcript_hash":hex(&proof)}) |
| 135 | + ); |
| 136 | + } |
| 137 | + } |
| 138 | + // Source event seven must reach the target and decrypt to the identity. |
| 139 | + let identity = Keys::generate(); |
| 140 | + let secret = identity.secret_key().to_bech32().unwrap(); |
| 141 | + let payload = source |
| 142 | + .send_payload(PayloadType::Nsec, Zeroizing::new(secret.clone())) |
| 143 | + .unwrap(); |
| 144 | + let payload = forward(&mut source_socket, &mut target_socket, payload).await; |
| 145 | + let imported = decrypt(&target, &payload); |
| 146 | + assert_eq!(imported["payload"], secret); |
| 147 | + assert_eq!( |
| 148 | + Keys::parse(imported["payload"].as_str().unwrap()) |
| 149 | + .unwrap() |
| 150 | + .public_key(), |
| 151 | + identity.public_key() |
| 152 | + ); |
| 153 | + // Target event seven must reach source and finish the session. |
| 154 | + let complete = target_message( |
| 155 | + &target, |
| 156 | + source.pubkey(), |
| 157 | + json!({"type":"complete", "success":true}), |
| 158 | + ); |
| 159 | + let complete = forward(&mut target_socket, &mut source_socket, complete).await; |
| 160 | + source.handle_complete(&complete).unwrap(); |
| 161 | + assert_eq!(source.state(), SessionState::Completed); |
| 162 | + server.abort(); |
| 163 | +} |
0 commit comments