Skip to main content

hyprstream_rpc/
signer.rs

1//! Signer implementations for Ed25519 envelope signing.
2//!
3//! - `LocalSigner`: Native — owns the `SigningKey`, signs synchronously.
4//! - `IdentitySigner`: Wraps a `SigningIdentity` from an `IdentityProvider`.
5//! - `JsSigner`: WASM — delegates to a JS callback (aegis-vault), awaits the result.
6
7use anyhow::Result;
8use async_trait::async_trait;
9
10use crate::crypto::SigningKey;
11use crate::identity::SigningIdentity;
12use crate::transport_traits::Signer;
13
14/// Native signer that owns an Ed25519 signing key.
15///
16/// Signs synchronously — the async wrapper resolves immediately.
17/// Used for server-to-server RPC where the signing key is local.
18///
19/// `SigningKey` derives `ZeroizeOnDrop` from ed25519-dalek ≥ 2.0, so the
20/// Ed25519 key bytes are zeroed when the `LocalSigner` is dropped. The ML-DSA
21/// key is an opaque byte buffer (`ml_dsa` crate) without `ZeroizeOnDrop`; we
22/// zero it explicitly in our `Drop` impl.
23pub struct LocalSigner {
24    signing_key: SigningKey,
25    pq_signing_key: Option<crate::crypto::pq::MlDsaSigningKey>,
26}
27
28impl std::fmt::Debug for LocalSigner {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("LocalSigner")
31            .field(
32                "pubkey",
33                &hex::encode(self.signing_key.verifying_key().to_bytes()),
34            )
35            .field(
36                "pq_pubkey",
37                &self.pq_signing_key.as_ref().map(|_| "<ml-dsa-65>"),
38            )
39            .finish()
40    }
41}
42
43impl LocalSigner {
44    /// Create a native signer.
45    ///
46    /// The post-quantum half is the node's **persistent** mesh ML-DSA-65 key,
47    /// derived deterministically from `signing_key` via
48    /// [`crate::node_identity::derive_mesh_mldsa_key`] (#157). This replaces the
49    /// previous ephemeral keygen so the signer's ML-DSA public key is stable
50    /// across restarts and equals the `#mesh-pq` key peers anchor in their PQ
51    /// trust store. Use [`Self::with_pq_key`] only to override with an
52    /// externally supplied key (e.g. tests).
53    pub fn new(signing_key: SigningKey) -> Self {
54        let pq_signing_key = Some(crate::node_identity::derive_mesh_mldsa_key(&signing_key));
55        Self {
56            signing_key,
57            pq_signing_key,
58        }
59    }
60
61    pub fn with_pq_key(mut self, key: crate::crypto::pq::MlDsaSigningKey) -> Self {
62        self.pq_signing_key = Some(key);
63        self
64    }
65
66    pub fn signing_key(&self) -> &SigningKey {
67        &self.signing_key
68    }
69}
70
71#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
72#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
73impl Signer for LocalSigner {
74    fn pubkey(&self) -> [u8; 32] {
75        self.signing_key.verifying_key().to_bytes()
76    }
77
78    async fn sign(&self, canonical_bytes: &[u8]) -> Result<[u8; 64]> {
79        use ed25519_dalek::Signer as _;
80        Ok(self.signing_key.sign(canonical_bytes).to_bytes())
81    }
82
83    fn pq_pubkey(&self) -> Option<Vec<u8>> {
84        self.pq_signing_key.as_ref().map(|sk| {
85            let vk = ml_dsa::Keypair::verifying_key(sk);
86            crate::crypto::pq::ml_dsa_vk_bytes(&vk)
87        })
88    }
89
90    async fn pq_sign(&self, canonical_bytes: &[u8]) -> Result<Option<Vec<u8>>> {
91        match &self.pq_signing_key {
92            Some(sk) => Ok(Some(crate::crypto::pq::ml_dsa_sign(sk, canonical_bytes))),
93            None => Ok(None),
94        }
95    }
96}
97
98/// Signer backed by an `IdentityProvider`-derived `SigningIdentity`.
99///
100/// Bridges the `IdentityProvider` abstraction to the `Signer` trait
101/// used by `RpcClientImpl`. Created via `IdentityProvider::identity_open()`.
102pub struct IdentitySigner {
103    identity_handle: Box<dyn SigningIdentity>,
104}
105
106impl IdentitySigner {
107    pub fn new(identity_handle: Box<dyn SigningIdentity>) -> Self {
108        Self { identity_handle }
109    }
110}
111
112#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
113#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
114impl Signer for IdentitySigner {
115    fn pubkey(&self) -> [u8; 32] {
116        self.identity_handle.pubkey()
117    }
118
119    async fn sign(&self, canonical_bytes: &[u8]) -> Result<[u8; 64]> {
120        self.identity_handle.sign(canonical_bytes).await
121    }
122}
123
124// ============================================================================
125// WASM signer — delegates to JS callback (aegis-vault)
126// ============================================================================
127
128#[cfg(target_arch = "wasm32")]
129mod wasm {
130    use anyhow::{anyhow, Result};
131    use async_trait::async_trait;
132    use js_sys::Function;
133    use wasm_bindgen::prelude::*;
134    use wasm_bindgen_futures::JsFuture;
135
136    use crate::transport_traits::Signer;
137
138    /// WASM signer that delegates to a JavaScript async callback.
139    ///
140    /// The callback signature is `(canonicalBytes: Uint8Array) => Promise<Uint8Array>`.
141    /// The signing key never enters this WASM module — it lives in aegis-vault,
142    /// a cross-origin iframe, or a hardware token.
143    pub struct JsSigner {
144        pubkey: [u8; 32],
145        sign_fn: Function,
146        pq_pubkey: Option<Vec<u8>>,
147        pq_sign_fn: Option<Function>,
148    }
149
150    // SAFETY: wasm32 is single-threaded. js_sys::Function is !Send only because
151    // the JS spec doesn't define cross-thread semantics, but there are no threads.
152    unsafe impl Send for JsSigner {}
153    unsafe impl Sync for JsSigner {}
154
155    impl JsSigner {
156        pub fn new(pubkey: &[u8], sign_fn: Function) -> Result<Self> {
157            if pubkey.len() != 32 {
158                return Err(anyhow!(
159                    "signer_pubkey must be 32 bytes, got {}",
160                    pubkey.len()
161                ));
162            }
163            let mut pk = [0u8; 32];
164            pk.copy_from_slice(pubkey);
165            Ok(Self {
166                pubkey: pk,
167                sign_fn,
168                pq_pubkey: None,
169                pq_sign_fn: None,
170            })
171        }
172
173        /// Construct a browser signer whose Ed25519 and ML-DSA-65 private
174        /// material remains behind separate JS callbacks.
175        pub fn new_hybrid(
176            pubkey: &[u8],
177            sign_fn: Function,
178            pq_pubkey: &[u8],
179            pq_sign_fn: Function,
180        ) -> Result<Self> {
181            crate::crypto::pq::ml_dsa_vk_from_bytes(pq_pubkey)
182                .map_err(|error| anyhow!("invalid signer ML-DSA-65 public key: {error}"))?;
183            let mut signer = Self::new(pubkey, sign_fn)?;
184            signer.pq_pubkey = Some(pq_pubkey.to_vec());
185            signer.pq_sign_fn = Some(pq_sign_fn);
186            Ok(signer)
187        }
188    }
189
190    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
191    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
192    impl Signer for JsSigner {
193        fn pubkey(&self) -> [u8; 32] {
194            self.pubkey
195        }
196
197        async fn sign(&self, canonical_bytes: &[u8]) -> Result<[u8; 64]> {
198            let canonical_js = js_sys::Uint8Array::from(canonical_bytes);
199            let promise_jsvalue = self
200                .sign_fn
201                .call1(&JsValue::NULL, &canonical_js)
202                .map_err(|e| anyhow!("sign callback threw: {:?}", e))?;
203            let promise: js_sys::Promise = promise_jsvalue
204                .dyn_into()
205                .map_err(|_| anyhow!("sign callback must return a Promise<Uint8Array>"))?;
206            let signature_jsvalue = JsFuture::from(promise)
207                .await
208                .map_err(|e| anyhow!("sign callback rejected: {:?}", e))?;
209            let signature_js: js_sys::Uint8Array = signature_jsvalue
210                .dyn_into()
211                .map_err(|_| anyhow!("sign callback must resolve to a Uint8Array"))?;
212            let signature_vec = signature_js.to_vec();
213            if signature_vec.len() != 64 {
214                return Err(anyhow!(
215                    "signature must be 64 bytes, got {}",
216                    signature_vec.len()
217                ));
218            }
219            let mut signature = [0u8; 64];
220            signature.copy_from_slice(&signature_vec);
221            Ok(signature)
222        }
223
224        fn pq_pubkey(&self) -> Option<Vec<u8>> {
225            self.pq_pubkey.clone()
226        }
227
228        async fn pq_sign(&self, canonical_bytes: &[u8]) -> Result<Option<Vec<u8>>> {
229            const ML_DSA65_SIGNATURE_LEN: usize = 3309;
230            let Some(sign_fn) = &self.pq_sign_fn else {
231                return Ok(None);
232            };
233            let canonical_js = js_sys::Uint8Array::from(canonical_bytes);
234            let promise_jsvalue = sign_fn
235                .call1(&JsValue::NULL, &canonical_js)
236                .map_err(|error| anyhow!("PQ sign callback threw: {error:?}"))?;
237            let promise: js_sys::Promise = promise_jsvalue
238                .dyn_into()
239                .map_err(|_| anyhow!("PQ sign callback must return a Promise<Uint8Array>"))?;
240            let signature_jsvalue = JsFuture::from(promise)
241                .await
242                .map_err(|error| anyhow!("PQ sign callback rejected: {error:?}"))?;
243            let signature_js: js_sys::Uint8Array = signature_jsvalue
244                .dyn_into()
245                .map_err(|_| anyhow!("PQ sign callback must resolve to a Uint8Array"))?;
246            let signature = signature_js.to_vec();
247            anyhow::ensure!(
248                signature.len() == ML_DSA65_SIGNATURE_LEN,
249                "ML-DSA-65 signature must be {ML_DSA65_SIGNATURE_LEN} bytes"
250            );
251            Ok(Some(signature))
252        }
253    }
254}
255
256#[cfg(target_arch = "wasm32")]
257pub use wasm::JsSigner;