Skip to main content

bsv_rs/auth/
types.rs

1//! Core types for BRC-31 authentication protocol.
2//!
3//! This module defines the fundamental types used in peer-to-peer authentication:
4//! - `MessageType` - Authentication message types
5//! - `AuthMessage` - Full authentication message structure
6//! - `PeerSession` - Session state between peers
7//! - `RequestedCertificateSet` - Certificate request specification
8
9use crate::primitives::PublicKey;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12
13/// Protocol version for BRC-31 authentication.
14pub const AUTH_VERSION: &str = "0.1";
15
16/// Protocol ID used for signing auth messages.
17/// This is used with security level 2 for BRC-42 key derivation.
18pub const AUTH_PROTOCOL_ID: &str = "auth message signature";
19
20/// Message types in the BRC-31 authentication protocol.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub enum MessageType {
24    /// Initial authentication request from initiator.
25    InitialRequest,
26    /// Response to initial request with session nonce.
27    InitialResponse,
28    /// Request for certificates from peer.
29    CertificateRequest,
30    /// Response with certificates.
31    CertificateResponse,
32    /// General authenticated message.
33    General,
34}
35
36impl MessageType {
37    /// Returns the string representation of the message type.
38    pub fn as_str(&self) -> &'static str {
39        match self {
40            Self::InitialRequest => "initialRequest",
41            Self::InitialResponse => "initialResponse",
42            Self::CertificateRequest => "certificateRequest",
43            Self::CertificateResponse => "certificateResponse",
44            Self::General => "general",
45        }
46    }
47
48    /// Parses a message type from its string representation.
49    #[allow(clippy::should_implement_trait)]
50    pub fn from_str(s: &str) -> Option<Self> {
51        match s {
52            "initialRequest" => Some(Self::InitialRequest),
53            "initialResponse" => Some(Self::InitialResponse),
54            "certificateRequest" => Some(Self::CertificateRequest),
55            "certificateResponse" => Some(Self::CertificateResponse),
56            "general" => Some(Self::General),
57            _ => None,
58        }
59    }
60
61    /// Returns true if this is an initial handshake message type.
62    pub fn is_handshake(&self) -> bool {
63        matches!(self, Self::InitialRequest | Self::InitialResponse)
64    }
65
66    /// Returns true if this is a certificate-related message type.
67    pub fn is_certificate(&self) -> bool {
68        matches!(self, Self::CertificateRequest | Self::CertificateResponse)
69    }
70}
71
72impl std::fmt::Display for MessageType {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        write!(f, "{}", self.as_str())
75    }
76}
77
78/// Authentication message structure (BRC-31).
79///
80/// This structure represents all message types in the authentication protocol.
81/// Different fields are used depending on the message type.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase")]
84pub struct AuthMessage {
85    /// Protocol version (e.g., "0.1").
86    pub version: String,
87
88    /// Type of message.
89    pub message_type: MessageType,
90
91    /// Sender's identity key (33-byte compressed public key).
92    pub identity_key: PublicKey,
93
94    /// Sender's nonce for this message (base64, 32 bytes: 16 random + 16 HMAC).
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub nonce: Option<String>,
97
98    /// Session nonce from initial handshake (for InitialResponse).
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub initial_nonce: Option<String>,
101
102    /// Recipient's nonce from previous message.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub your_nonce: Option<String>,
105
106    /// Attached certificates (for CertificateResponse).
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub certificates: Option<Vec<crate::auth::certificates::VerifiableCertificate>>,
109
110    /// Requested certificate specifications (for InitialRequest, CertificateRequest).
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub requested_certificates: Option<RequestedCertificateSet>,
113
114    /// Message payload (for General messages).
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub payload: Option<Vec<u8>>,
117
118    /// DER-encoded signature over message contents.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub signature: Option<Vec<u8>>,
121}
122
123impl AuthMessage {
124    /// Creates a new message with required fields.
125    pub fn new(message_type: MessageType, identity_key: PublicKey) -> Self {
126        Self {
127            version: AUTH_VERSION.to_string(),
128            message_type,
129            identity_key,
130            nonce: None,
131            initial_nonce: None,
132            your_nonce: None,
133            certificates: None,
134            requested_certificates: None,
135            payload: None,
136            signature: None,
137        }
138    }
139
140    /// Returns the bytes to sign for this message.
141    ///
142    /// The signing data varies by message type:
143    /// - InitialResponse: yourNonce || initialNonce (initiator's nonce || responder's session nonce, decoded from base64)
144    /// - General/CertificateRequest/CertificateResponse: payload or serialized requested_certificates
145    pub fn signing_data(&self) -> Vec<u8> {
146        match self.message_type {
147            MessageType::InitialResponse => {
148                // For InitialResponse, sign: yourNonce (initiator's nonce) || initialNonce (responder's session nonce)
149                // This matches Go/TS SDKs: initiator_nonce_bytes || responder_nonce_bytes
150                let mut data = Vec::new();
151                if let Some(ref your_nonce) = self.your_nonce {
152                    if let Ok(decoded) = crate::primitives::from_base64(your_nonce) {
153                        data.extend_from_slice(&decoded);
154                    }
155                }
156                if let Some(ref initial_nonce) = self.initial_nonce {
157                    if let Ok(decoded) = crate::primitives::from_base64(initial_nonce) {
158                        data.extend_from_slice(&decoded);
159                    }
160                }
161                data
162            }
163            MessageType::General => {
164                // For General messages, sign the payload
165                self.payload.clone().unwrap_or_default()
166            }
167            MessageType::CertificateRequest => {
168                // For CertificateRequest, sign the serialized requested_certificates
169                if let Some(ref req) = self.requested_certificates {
170                    serde_json::to_vec(req).unwrap_or_default()
171                } else {
172                    Vec::new()
173                }
174            }
175            MessageType::CertificateResponse => {
176                // For CertificateResponse, sign serialized certificates
177                if let Some(ref certs) = self.certificates {
178                    serde_json::to_vec(certs).unwrap_or_default()
179                } else {
180                    Vec::new()
181                }
182            }
183            MessageType::InitialRequest => {
184                // Initial request is not signed (starts handshake)
185                Vec::new()
186            }
187        }
188    }
189
190    /// Returns the key ID to use for signing/verification.
191    ///
192    /// Format: "{nonce} {peer_nonce}" for most messages.
193    pub fn get_key_id(&self, peer_session_nonce: Option<&str>) -> String {
194        let nonce = self.nonce.as_deref().unwrap_or("");
195        let peer_nonce = peer_session_nonce.unwrap_or("");
196
197        match self.message_type {
198            MessageType::InitialResponse => {
199                // For InitialResponse: "{yourNonce} {initialNonce}" = "{initiator_nonce} {responder_nonce}"
200                // Matches Go: keyID(message.InitialNonce, session.SessionNonce) on responder
201                //             keyID(session.SessionNonce, message.InitialNonce) on initiator
202                let your = self.your_nonce.as_deref().unwrap_or("");
203                let initial = self.initial_nonce.as_deref().unwrap_or("");
204                format!("{} {}", your, initial)
205            }
206            _ => {
207                // For other messages: "{nonce} {peer_session_nonce}"
208                format!("{} {}", nonce, peer_nonce)
209            }
210        }
211    }
212
213    /// Validates the message structure.
214    pub fn validate(&self) -> crate::Result<()> {
215        // Check version
216        if self.version != AUTH_VERSION {
217            return Err(crate::Error::AuthError(format!(
218                "Invalid auth version: expected {}, got {}",
219                AUTH_VERSION, self.version
220            )));
221        }
222
223        // Validate based on message type
224        match self.message_type {
225            MessageType::InitialRequest => {
226                // InitialRequest must have an initial_nonce (session nonce)
227                if self.initial_nonce.is_none() {
228                    return Err(crate::Error::AuthError(
229                        "InitialRequest must have an initial_nonce".into(),
230                    ));
231                }
232            }
233            MessageType::InitialResponse => {
234                // InitialResponse must have at least one of nonce/initial_nonce (the
235                // responder's session nonce), plus your_nonce and signature.
236                // The Go SDK sends both nonce and initial_nonce; the TS SDK only sends
237                // initialNonce (no nonce field). Accept either for cross-SDK compat.
238                if self.nonce.is_none() && self.initial_nonce.is_none() {
239                    return Err(crate::Error::AuthError(
240                        "InitialResponse must have nonce or initial_nonce".into(),
241                    ));
242                }
243                if self.your_nonce.is_none() {
244                    return Err(crate::Error::AuthError(
245                        "InitialResponse must have your_nonce".into(),
246                    ));
247                }
248                if self.signature.is_none() {
249                    return Err(crate::Error::AuthError(
250                        "InitialResponse must have signature".into(),
251                    ));
252                }
253            }
254            MessageType::CertificateRequest => {
255                // CertificateRequest must have requested_certificates
256                if self.requested_certificates.is_none() {
257                    return Err(crate::Error::AuthError(
258                        "CertificateRequest must have requested_certificates".into(),
259                    ));
260                }
261            }
262            MessageType::CertificateResponse => {
263                // CertificateResponse must have certificates
264                if self.certificates.is_none() {
265                    return Err(crate::Error::AuthError(
266                        "CertificateResponse must have certificates".into(),
267                    ));
268                }
269            }
270            MessageType::General => {
271                // General messages should have nonce, your_nonce, and signature
272                if self.signature.is_none() {
273                    return Err(crate::Error::AuthError(
274                        "General message must have signature".into(),
275                    ));
276                }
277            }
278        }
279
280        Ok(())
281    }
282}
283
284/// Peer session state.
285///
286/// Tracks the authentication state between two peers, including
287/// nonces, identity keys, and certificate validation status.
288#[derive(Debug, Clone, Default, Serialize, Deserialize)]
289#[serde(rename_all = "camelCase")]
290pub struct PeerSession {
291    /// Whether the session has completed mutual authentication.
292    pub is_authenticated: bool,
293
294    /// This session's unique nonce (session identifier).
295    pub session_nonce: Option<String>,
296
297    /// Peer's nonce from their last message.
298    pub peer_nonce: Option<String>,
299
300    /// Peer's identity public key.
301    pub peer_identity_key: Option<PublicKey>,
302
303    /// Last update timestamp (milliseconds since epoch).
304    pub last_update: u64,
305
306    /// Whether certificates are required for this session.
307    pub certificates_required: bool,
308
309    /// Whether certificates have been validated.
310    pub certificates_validated: bool,
311}
312
313impl PeerSession {
314    /// Creates a new empty session.
315    pub fn new() -> Self {
316        Self::default()
317    }
318
319    /// Creates a new session with the given session nonce.
320    pub fn with_nonce(session_nonce: String) -> Self {
321        Self {
322            session_nonce: Some(session_nonce),
323            last_update: current_time_ms(),
324            ..Default::default()
325        }
326    }
327
328    /// Updates the last update timestamp to now.
329    pub fn touch(&mut self) {
330        self.last_update = current_time_ms();
331    }
332
333    /// Returns true if this session is ready for general messages.
334    pub fn is_ready(&self) -> bool {
335        self.is_authenticated && (!self.certificates_required || self.certificates_validated)
336    }
337}
338
339/// Certificate request specification.
340///
341/// Specifies which certificates are required from a peer, including
342/// trusted certifiers and the certificate types with fields to reveal.
343#[derive(Debug, Clone, Default, Serialize, Deserialize)]
344#[serde(rename_all = "camelCase")]
345pub struct RequestedCertificateSet {
346    /// List of trusted certifier public keys (hex encoded).
347    #[serde(default)]
348    pub certifiers: Vec<String>,
349
350    /// Map of certificate type ID (base64) -> list of field names to reveal.
351    #[serde(default)]
352    pub types: HashMap<String, Vec<String>>,
353}
354
355impl RequestedCertificateSet {
356    /// Creates a new empty certificate request set.
357    pub fn new() -> Self {
358        Self::default()
359    }
360
361    /// Returns true if no certificates are requested.
362    pub fn is_empty(&self) -> bool {
363        self.certifiers.is_empty() && self.types.is_empty()
364    }
365
366    /// Adds a trusted certifier by public key hex.
367    pub fn add_certifier(&mut self, certifier_hex: impl Into<String>) {
368        self.certifiers.push(certifier_hex.into());
369    }
370
371    /// Adds a certificate type with fields to reveal.
372    pub fn add_type(&mut self, type_id: impl Into<String>, fields: Vec<String>) {
373        self.types.insert(type_id.into(), fields);
374    }
375
376    /// Checks if a certifier is trusted.
377    pub fn is_certifier_trusted(&self, certifier_hex: &str) -> bool {
378        self.certifiers.is_empty() || self.certifiers.contains(&certifier_hex.to_string())
379    }
380
381    /// Checks if a certificate type is requested.
382    pub fn is_type_requested(&self, type_id: &str) -> bool {
383        self.types.is_empty() || self.types.contains_key(type_id)
384    }
385
386    /// Gets the fields to reveal for a certificate type.
387    pub fn get_fields_for_type(&self, type_id: &str) -> Option<&Vec<String>> {
388        self.types.get(type_id)
389    }
390}
391
392/// Returns current time in milliseconds since Unix epoch.
393///
394/// On `wasm32-unknown-unknown` (e.g. Cloudflare Workers) this uses
395/// `js_sys::Date::now()` because `std::time::SystemTime::now()` is
396/// unimplemented and panics there. On all other targets the behavior is
397/// unchanged. See `crate::util::time` for the cfg-gated implementation.
398pub fn current_time_ms() -> u64 {
399    crate::util::time::current_time_ms()
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405    use crate::primitives::PrivateKey;
406
407    #[test]
408    fn test_message_type_conversion() {
409        assert_eq!(MessageType::InitialRequest.as_str(), "initialRequest");
410        assert_eq!(
411            MessageType::from_str("initialRequest"),
412            Some(MessageType::InitialRequest)
413        );
414        assert_eq!(MessageType::from_str("invalid"), None);
415    }
416
417    #[test]
418    fn test_auth_message_creation() {
419        let key = PrivateKey::random().public_key();
420        let msg = AuthMessage::new(MessageType::InitialRequest, key.clone());
421
422        assert_eq!(msg.version, AUTH_VERSION);
423        assert_eq!(msg.message_type, MessageType::InitialRequest);
424        assert_eq!(msg.identity_key, key);
425        assert!(msg.nonce.is_none());
426    }
427
428    #[test]
429    fn test_peer_session() {
430        let mut session = PeerSession::with_nonce("test-nonce".to_string());
431        assert_eq!(session.session_nonce.as_deref(), Some("test-nonce"));
432        assert!(!session.is_authenticated);
433        assert!(!session.is_ready());
434
435        session.is_authenticated = true;
436        assert!(session.is_ready());
437
438        session.certificates_required = true;
439        assert!(!session.is_ready());
440
441        session.certificates_validated = true;
442        assert!(session.is_ready());
443    }
444
445    #[test]
446    fn test_requested_certificate_set() {
447        let mut req = RequestedCertificateSet::new();
448        assert!(req.is_empty());
449
450        req.add_certifier("02abc123");
451        req.add_type("type1", vec!["name".to_string(), "email".to_string()]);
452
453        assert!(!req.is_empty());
454        assert!(req.is_certifier_trusted("02abc123"));
455        assert!(!req.is_certifier_trusted("02def456"));
456        assert!(req.is_type_requested("type1"));
457        assert!(!req.is_type_requested("type2"));
458    }
459}