Skip to main content

weirdnet_push/
handle.rs

1//! Wake handles and control secrets.
2//!
3//! A wake handle is 32 random bytes (base64url): what a sender needs to wake a device, and
4//! all it learns. The device shares it, sealed, only with its home relay and trusted peers.
5//! The control secret, also 32 random bytes, stays on the device; it is needed to rotate or
6//! revoke the handle. The server keeps only SHA-256 hashes of both.
7
8use crate::error::{Error, Result};
9use base64::Engine;
10use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13
14fn random32() -> String {
15    B64.encode(weirdnet_keys::random_bytes::<32>().expect("system randomness"))
16}
17
18fn check32(s: &str) -> Result<()> {
19    match B64.decode(s) {
20        Ok(b) if b.len() == 32 => Ok(()),
21        _ => Err(Error::Invalid("expected 32 bytes, base64url".into())),
22    }
23}
24
25/// An opaque wake handle.
26#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[serde(try_from = "String", into = "String")]
28pub struct WakeHandle(String);
29
30impl std::fmt::Debug for WakeHandle {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        write!(f, "WakeHandle({}…)", &self.0[..6])
33    }
34}
35
36impl WakeHandle {
37    /// A new random handle.
38    pub fn generate() -> Self {
39        Self(random32())
40    }
41
42    /// Parses a handle.
43    pub fn parse(s: &str) -> Result<Self> {
44        check32(s)?;
45        Ok(Self(s.to_string()))
46    }
47
48    /// The handle text.
49    pub fn as_str(&self) -> &str {
50        &self.0
51    }
52
53    /// The server's key for it: hex SHA-256.
54    pub fn digest(&self) -> String {
55        hex::encode(Sha256::digest(self.0.as_bytes()))
56    }
57}
58
59impl TryFrom<String> for WakeHandle {
60    type Error = Error;
61    fn try_from(s: String) -> Result<Self> {
62        check32(&s)?;
63        Ok(Self(s))
64    }
65}
66
67impl From<WakeHandle> for String {
68    fn from(h: WakeHandle) -> String {
69        h.0
70    }
71}
72
73/// The secret that controls a handle (rotate, revoke).
74#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(try_from = "String", into = "String")]
76pub struct ControlSecret(String);
77
78impl std::fmt::Debug for ControlSecret {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.write_str("ControlSecret(<redacted>)")
81    }
82}
83
84impl ControlSecret {
85    /// A new random secret.
86    pub fn generate() -> Self {
87        Self(random32())
88    }
89
90    /// The secret text (store it on the device).
91    pub fn expose(&self) -> &str {
92        &self.0
93    }
94
95    /// Hex SHA-256, as the server keeps it.
96    pub fn digest(&self) -> String {
97        hex::encode(Sha256::digest(self.0.as_bytes()))
98    }
99
100    /// Constant-time check against a stored digest.
101    pub fn matches(&self, digest: &str) -> bool {
102        use subtle::ConstantTimeEq;
103        self.digest().as_bytes().ct_eq(digest.as_bytes()).into()
104    }
105}
106
107impl TryFrom<String> for ControlSecret {
108    type Error = Error;
109    fn try_from(s: String) -> Result<Self> {
110        check32(&s)?;
111        Ok(Self(s))
112    }
113}
114
115impl From<ControlSecret> for String {
116    fn from(h: ControlSecret) -> String {
117        h.0
118    }
119}
120
121/// What a device gives its home relay and trusted peers (sealed) so they can wake it.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct WakeCard {
124    /// The push service base URL (`https://push.weirdbrains.com`).
125    pub service: String,
126    /// The handle.
127    pub handle: WakeHandle,
128    /// The device's push public key, hex.
129    pub key: String,
130}
131
132impl WakeCard {
133    /// The push public key.
134    pub fn public_key(&self) -> Result<[u8; 32]> {
135        let b = hex::decode(&self.key).map_err(|_| Error::Invalid("bad push key".into()))?;
136        b.try_into().map_err(|_| Error::Invalid("bad push key".into()))
137    }
138
139    /// Seals a wake for this card.
140    pub fn seal(&self, reason: crate::wake::Reason) -> Result<crate::wake::Payload96> {
141        crate::wake::seal(&self.public_key()?, &self.handle, reason)
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn handles_and_secrets() {
151        let h = WakeHandle::generate();
152        assert_eq!(h.as_str().len(), 43);
153        assert_eq!(WakeHandle::parse(h.as_str()).unwrap(), h);
154        assert!(WakeHandle::parse("short").is_err());
155        assert!(serde_json::from_str::<WakeHandle>("\"nope\"").is_err());
156        assert_eq!(h.digest().len(), 64);
157        let c = ControlSecret::generate();
158        assert!(c.matches(&c.digest()));
159        assert!(!ControlSecret::generate().matches(&c.digest()));
160        assert!(!format!("{c:?}").contains(c.expose()));
161    }
162}