Skip to main content

wellfare_core/
companion_pairing.rs

1//! JSON wire protocol for companion WebSocket pairing (Ed25519 challenge-response).
2
3use serde::{Deserialize, Serialize};
4
5pub const MSG_CHALLENGE: &str = "CHALLENGE";
6pub const MSG_PAIRING_RESPONSE: &str = "PAIRING_RESPONSE";
7pub const MSG_AUTH_SUCCESS: &str = "AUTH_SUCCESS";
8pub const MSG_AUTH_DENIED: &str = "AUTH_DENIED";
9pub const COMPANION_PAIRING_CONTEXT: &str = "wellfair:companion";
10
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12pub struct CompanionChallenge {
13    #[serde(rename = "type")]
14    pub msg_type: String,
15    pub nonce_hex: String,
16    pub context: String,
17}
18
19impl CompanionChallenge {
20    /// Creates a new instance.
21    pub fn new(nonce_hex: impl Into<String>) -> Self {
22        Self {
23            msg_type: MSG_CHALLENGE.into(),
24            nonce_hex: nonce_hex.into(),
25            context: COMPANION_PAIRING_CONTEXT.into(),
26        }
27    }
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
31pub struct CompanionPairingResponse {
32    #[serde(rename = "type")]
33    pub msg_type: String,
34    pub device_id: String,
35    pub public_key_hex: String,
36    pub signature_hex: String,
37}
38
39impl CompanionPairingResponse {
40    /// Creates a new instance.
41    pub fn new(
42        device_id: impl Into<String>,
43        public_key_hex: impl Into<String>,
44        signature_hex: impl Into<String>,
45    ) -> Self {
46        Self {
47            msg_type: MSG_PAIRING_RESPONSE.into(),
48            device_id: device_id.into(),
49            public_key_hex: public_key_hex.into(),
50            signature_hex: signature_hex.into(),
51        }
52    }
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
56pub struct CompanionAuthResult {
57    #[serde(rename = "type")]
58    pub msg_type: String,
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub reason: Option<String>,
61}
62
63impl CompanionAuthResult {
64    /// Success result.
65    pub fn success() -> Self {
66        Self {
67            msg_type: MSG_AUTH_SUCCESS.into(),
68            reason: None,
69        }
70    }
71
72    /// Denied result.
73    pub fn denied(reason: impl Into<String>) -> Self {
74        Self {
75            msg_type: MSG_AUTH_DENIED.into(),
76            reason: Some(reason.into()),
77        }
78    }
79}