use hmac::{Hmac, Mac};
use sha2::Sha256;
use crate::config::ClientConfig;
use crate::error::{Error, Result};
type HmacSha256 = Hmac<Sha256>;
#[derive(Debug, Clone)]
pub struct SignParams {
pub client_key: String,
pub nonce: String,
pub timestamp: String,
}
#[derive(Debug, Clone)]
pub struct Signature {
pub signature: String,
pub nonce: String,
pub timestamp: String,
}
#[derive(Debug, Clone)]
pub struct Signer {
app_key: String,
sign_key: String,
can_sign: bool,
}
impl Signer {
pub fn new(cfg: &ClientConfig) -> Self {
Signer {
app_key: cfg.app_key.clone(),
sign_key: cfg.sign_key.clone(),
can_sign: cfg.can_sign(),
}
}
fn canonical(&self, p: &SignParams) -> String {
format!(
"share_type=pc&client_key={}&nonce_str={}×tamp={}",
p.client_key, p.nonce, p.timestamp
)
}
pub fn sign(&self, nonce: &str, timestamp: &str) -> Result<Signature> {
if !self.can_sign {
return Err(Error::Signing(
"app_key/sign_key not configured — recover them via capture (plan Steps 2–3)"
.into(),
));
}
let params = SignParams {
client_key: self.app_key.clone(),
nonce: nonce.to_string(),
timestamp: timestamp.to_string(),
};
let canonical = self.canonical(¶ms);
let mut mac = HmacSha256::new_from_slice(self.sign_key.as_bytes())
.map_err(|e| Error::Signing(format!("bad hmac key: {e}")))?;
mac.update(canonical.as_bytes());
let sig = hex::encode(mac.finalize().into_bytes());
Ok(Signature {
signature: sig,
nonce: nonce.to_string(),
timestamp: timestamp.to_string(),
})
}
pub fn is_ready(&self) -> bool {
self.can_sign
}
}
#[allow(dead_code)]
pub fn make_nonce(seed: u64) -> String {
let mut x = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^= x >> 31;
format!("{x:016x}")
}
#[cfg(test)]
mod tests {
use super::*;
fn cfg_with(app_key: &str, sign_key: &str) -> ClientConfig {
let mut c = ClientConfig::windows(crate::config::Region::Global);
c.app_key = app_key.to_string();
c.sign_key = sign_key.to_string();
c
}
#[test]
fn unconfigured_signer_refuses() {
let signer = Signer::new(&ClientConfig::windows(crate::config::Region::Global));
assert!(!signer.is_ready());
assert!(signer.sign("abc", "123").is_err());
}
#[test]
fn hmac_is_deterministic() {
let signer = Signer::new(&cfg_with("APPKEY", "secret"));
let a = signer.sign("nonce1", "1700000000").unwrap();
let b = signer.sign("nonce1", "1700000000").unwrap();
assert_eq!(a.signature, b.signature);
let c = signer.sign("nonce2", "1700000000").unwrap();
assert_ne!(a.signature, c.signature);
}
#[test]
#[ignore = "needs captured request fixture (plan Step 2)"]
fn reproduces_captured_signature() {
}
}