//! Psycho Key — Rust SDK (v2 AES-256-GCM protocol) //! //! Add to Cargo.toml: //! [dependencies] //! aes-gcm = "0.10" //! base64 = "0.22" //! hex = "0.4" //! hkdf = "0.12" //! hmac = "0.12" //! rand = "0.8" //! reqwest = { version = "0.12", features = ["blocking", "json"] } //! serde = { version = "1", features = ["derive"] } //! serde_json = "1" //! sha2 = "0.10" use aes_gcm::{ aead::{Aead, KeyInit, Payload}, Aes256Gcm, Nonce, }; use base64::{engine::general_purpose::STANDARD as B64, Engine as _}; use hkdf::Hkdf; use hmac::{Hmac, Mac}; use rand::RngCore; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::HashMap; use std::process::Command; use std::time::{Duration, SystemTime, UNIX_EPOCH}; type HmacSha256 = Hmac; const HKDF_SALT: &[u8] = b"psychokey-salt-v1"; #[derive(Clone, Debug)] pub struct Config { pub base_url: String, pub app: String, pub api_secret: String, pub version: String, pub require_v2: bool, } impl Config { pub fn new(app: &str, api_secret: &str) -> Self { Self { base_url: "https://psycho-key.com".to_string(), app: app.to_string(), api_secret: api_secret.to_string(), version: "1.0.0".to_string(), require_v2: true, } } } #[derive(Clone, Debug, Default, Deserialize)] pub struct License { #[serde(default)] pub id: i64, #[serde(default)] pub status: String, #[serde(default, rename = "duration")] pub duration_days: i32, #[serde(default)] pub duration_seconds: i32, #[serde(default)] pub max_hwids: i32, #[serde(default)] pub activated_at: Option, #[serde(default)] pub expires_at: Option, #[serde(default)] pub days_left: Option, #[serde(default)] pub seconds_left: Option, #[serde(default)] pub lifetime: bool, } #[derive(Clone, Debug, Default)] pub struct ClientResult { pub ok: bool, pub code: String, pub message: String, pub token: String, pub retry_after: i64, pub latest_version: String, pub download_url: String, pub variables: HashMap, pub license: License, } #[derive(Serialize)] struct InnerReq<'a> { action: &'a str, nonce: &'a str, ts: i64, hwid: &'a str, license_key: &'a str, token: &'a str, version: &'a str, sig: &'a str, } #[derive(Serialize)] struct EnvelopeReq<'a> { app: &'a str, v: u8, iv: String, ct: String, tag: String, } pub struct Client { config: Config, secret: Vec, hwid: String, token: String, vars: HashMap, http: reqwest::blocking::Client, } impl Client { pub fn new(config: Config) -> Result { let secret = hex::decode(config.api_secret.trim()) .map_err(|_| "api_secret must be 64 hex chars".to_string())?; if secret.len() != 32 { return Err("api_secret must decode to 32 bytes".to_string()); } let http = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(15)) .build() .map_err(|e| e.to_string())?; Ok(Self { config, secret, hwid: detect_hwid(), token: String::new(), vars: HashMap::new(), http, }) } pub fn hwid(&self) -> &str { &self.hwid } pub fn var(&self, key: &str) -> &str { self.vars.get(key).map(|s| s.as_str()).unwrap_or("") } pub fn init(&mut self) -> ClientResult { self.call("init", "") } pub fn auth(&mut self, license_key: &str) -> ClientResult { let res = self.call("license", license_key); if res.ok && !res.token.is_empty() { self.token = res.token.clone(); } for (k, v) in &res.variables { self.vars.insert(k.clone(), v.clone()); } res } pub fn heartbeat(&mut self) -> ClientResult { let res = self.call("heartbeat", ""); if res.ok && !res.token.is_empty() { self.token = res.token.clone(); } for (k, v) in &res.variables { self.vars.insert(k.clone(), v.clone()); } res } pub fn logout(&mut self) -> ClientResult { let res = self.call("logout", ""); self.token.clear(); res } pub fn reset_hwid(&mut self, license_key: &str) -> ClientResult { let res = self.call("reset", license_key); if res.ok && !res.token.is_empty() { self.token = res.token.clone(); } for (k, v) in &res.variables { self.vars.insert(k.clone(), v.clone()); } res } fn call(&self, action: &str, license_key: &str) -> ClientResult { let mut out = ClientResult::default(); let mut nonce_bytes = [0u8; 16]; rand::thread_rng().fill_bytes(&mut nonce_bytes); let nonce = hex::encode(nonce_bytes); let ts = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs() as i64) .unwrap_or(0); let canonical = format!( "{}|{}|{}|{}|{}|{}|{}", self.config.app, action, nonce, ts, self.hwid, license_key, self.token ); let mut mac = ::new_from_slice(&self.secret).expect("HMAC key"); mac.update(canonical.as_bytes()); let sig = hex::encode(mac.finalize().into_bytes()); let inner = serde_json::to_string(&InnerReq { action, nonce: &nonce, ts, hwid: &self.hwid, license_key, token: &self.token, version: &self.config.version, sig: &sig, }) .unwrap_or_default(); let req_key = hkdf_key(&self.secret, &format!("psychokey-req-v2|{}", self.config.app)); let cipher = Aes256Gcm::new_from_slice(&req_key).expect("AES key"); let mut iv = [0u8; 12]; rand::thread_rng().fill_bytes(&mut iv); let sealed = match cipher.encrypt( Nonce::from_slice(&iv), Payload { msg: inner.as_bytes(), aad: self.config.app.as_bytes(), }, ) { Ok(v) => v, Err(_) => { out.code = "CLIENT_CRYPTO".to_string(); return out; } }; let split = sealed.len().saturating_sub(16); let env = EnvelopeReq { app: &self.config.app, v: 2, iv: B64.encode(iv), ct: B64.encode(&sealed[..split]), tag: B64.encode(&sealed[split..]), }; let url = format!("{}/api/v1.php", self.config.base_url.trim_end_matches('/')); let resp_text = match self .http .post(&url) .header("User-Agent", format!("PsychoKey-Rust/{}", self.config.version)) .json(&env) .send() .and_then(|r| r.text()) { Ok(t) => t, Err(e) => { out.code = "NETWORK".to_string(); out.message = e.to_string(); return out; } }; let root: serde_json::Value = match serde_json::from_str(&resp_text) { Ok(v) => v, Err(_) => { out.code = "CLIENT_PARSE".to_string(); return out; } }; let mut encrypted = false; let payload: serde_json::Value = if root.get("v").and_then(|v| v.as_i64()) == Some(2) { encrypted = true; let r_iv = B64.decode(root.get("iv").and_then(|s| s.as_str()).unwrap_or("")).unwrap_or_default(); let r_ct = B64.decode(root.get("ct").and_then(|s| s.as_str()).unwrap_or("")).unwrap_or_default(); let r_tag = B64.decode(root.get("tag").and_then(|s| s.as_str()).unwrap_or("")).unwrap_or_default(); if r_iv.len() != 12 || r_tag.len() != 16 { out.code = "CLIENT_INTEGRITY".to_string(); return out; } let resp_key = hkdf_key(&self.secret, &format!("psychokey-resp-v2|{}", self.config.app)); let dec_cipher = Aes256Gcm::new_from_slice(&resp_key).expect("AES key"); let mut joined = r_ct; joined.extend_from_slice(&r_tag); let aad = format!("{}|{}|{}", self.config.app, action, nonce); let plain = match dec_cipher.decrypt( Nonce::from_slice(&r_iv), Payload { msg: &joined, aad: aad.as_bytes(), }, ) { Ok(p) => p, Err(_) => { out.code = "CLIENT_INTEGRITY".to_string(); out.message = "Response authentication failed.".to_string(); return out; } }; match serde_json::from_slice(&plain) { Ok(v) => v, Err(_) => { out.code = "CLIENT_PARSE".to_string(); return out; } } } else { if self.config.require_v2 && root.get("success").and_then(|v| v.as_bool()) == Some(true) { out.code = "CLIENT_INTEGRITY".to_string(); out.message = "Unencrypted success rejected.".to_string(); return out; } root }; if encrypted { if let Some(resp_ts) = payload.get("ts").and_then(|v| v.as_i64()) { if resp_ts > 0 && (resp_ts - ts).abs() > 300 { out.code = "CLIENT_INTEGRITY".to_string(); out.message = "Response timestamp outside allowed window.".to_string(); return out; } } } out.ok = payload.get("success").and_then(|v| v.as_bool()).unwrap_or(false); out.code = payload .get("code") .and_then(|v| v.as_str()) .unwrap_or(if out.ok { "OK" } else { "ERROR" }) .to_string(); out.message = payload.get("message").and_then(|v| v.as_str()).unwrap_or("").to_string(); out.retry_after = payload.get("retry_after").and_then(|v| v.as_i64()).unwrap_or(0); out.latest_version = payload.get("latest_version").and_then(|v| v.as_str()).unwrap_or("").to_string(); out.download_url = payload.get("download_url").and_then(|v| v.as_str()).unwrap_or("").to_string(); if let Some(obj) = payload.get("variables").and_then(|v| v.as_object()) { for (k, v) in obj { if let Some(s) = v.as_str() { out.variables.insert(k.clone(), s.to_string()); } } } if out.ok { out.token = payload.get("token").and_then(|v| v.as_str()).unwrap_or("").to_string(); if let Some(lic) = payload.get("license") { if let Ok(parsed) = serde_json::from_value::(lic.clone()) { out.license = parsed; } } } out } } fn hkdf_key(secret: &[u8], info: &str) -> [u8; 32] { let hk = Hkdf::::new(Some(HKDF_SALT), secret); let mut okm = [0u8; 32]; hk.expand(info.as_bytes(), &mut okm).expect("HKDF expand"); okm } fn valid_hwid(s: &str) -> bool { (8..=128).contains(&s.len()) && s.bytes() .all(|b| b.is_ascii_alphanumeric() || b == b':' || b == b'_' || b == b'-') } fn detect_hwid() -> String { let mut cand = String::new(); #[cfg(target_os = "windows")] if let Ok(out) = Command::new("wmic").args(["csproduct", "get", "UUID"]).output() { for line in String::from_utf8_lossy(&out.stdout).lines() { let t = line.trim(); if !t.is_empty() && t != "UUID" { cand = t.to_string(); break; } } } #[cfg(target_os = "linux")] for path in ["/etc/machine-id", "/var/lib/dbus/machine-id"] { if let Ok(text) = std::fs::read_to_string(path) { let t = text.trim(); if !t.is_empty() { cand = t.to_string(); break; } } } #[cfg(target_os = "macos")] if let Ok(out) = Command::new("ioreg").args(["-rd1", "-c", "IOPlatformExpertDevice"]).output() { for line in String::from_utf8_lossy(&out.stdout).lines() { if line.contains("IOPlatformUUID") { let parts: Vec<&str> = line.split('"').collect(); if parts.len() >= 4 { cand = parts[parts.len() - 2].to_string(); break; } } } } if valid_hwid(&cand) { return cand; } let mut h = Sha256::new(); h.update(std::env::consts::OS.as_bytes()); h.update(b"|"); h.update(std::env::consts::ARCH.as_bytes()); if let Ok(host) = std::env::var("COMPUTERNAME").or_else(|_| std::env::var("HOSTNAME")) { h.update(b"|"); h.update(host.as_bytes()); } hex::encode(&h.finalize()[..16]) }