use serde_json::{json, Value};
use crate::core::config::LicenseConfig;
use crate::core::error::CheckErr;
use super::LicenseProvider;
pub struct KeygenProvider {
account_id: String,
api_base: String,
}
impl KeygenProvider {
pub fn new(account_id: impl Into<String>, api_base: impl Into<String>) -> Self {
Self {
account_id: account_id.into(),
api_base: api_base.into(),
}
}
pub fn from_config(config: &LicenseConfig) -> Self {
Self::new(config.account_id.clone(), config.api_base.clone())
}
fn post(&self, path: &str, auth: Option<&str>, body: &Value) -> Result<Value, CheckErr> {
let url = format!("{}/accounts/{}/{}", self.api_base, self.account_id, path);
let mut req = ureq::post(&url)
.set("Content-Type", "application/vnd.api+json")
.set("Accept", "application/vnd.api+json");
if let Some(key) = auth {
req = req.set("Authorization", &format!("License {key}"));
}
let payload = serde_json::to_string(body).map_err(|e| CheckErr::Denied(e.to_string()))?;
match req.send_string(&payload) {
Ok(resp) => resp
.into_json::<Value>()
.map_err(|e| CheckErr::Offline(format!("decode: {e}"))),
Err(ureq::Error::Status(code, resp)) => {
let detail: String = resp
.into_string()
.unwrap_or_default()
.chars()
.take(200)
.collect();
let msg = format!("HTTP {code}: {detail}");
if code == 408 || code == 429 || code >= 500 {
Err(CheckErr::Offline(msg))
} else {
Err(CheckErr::Denied(msg))
}
}
Err(e) => Err(CheckErr::Offline(format!("network: {e}"))),
}
}
fn validate(&self, key: &str, fingerprint: &str) -> Result<Validation, CheckErr> {
let body = json!({ "meta": { "key": key, "scope": { "fingerprint": fingerprint } } });
let v = self.post("licenses/actions/validate-key", None, &body)?;
Ok(Validation {
valid: v["meta"]["valid"].as_bool().unwrap_or(false),
code: v["meta"]["code"].as_str().unwrap_or("UNKNOWN").to_string(),
license_id: v["data"]["id"].as_str().map(str::to_string),
})
}
fn activate_machine(&self, key: &str, fingerprint: &str, license_id: &str) -> Result<(), CheckErr> {
let body = json!({
"data": {
"type": "machines",
"attributes": { "fingerprint": fingerprint },
"relationships": { "license": { "data": { "type": "licenses", "id": license_id } } }
}
});
self.post("machines", Some(key), &body).map(|_| ())
}
}
struct Validation {
valid: bool,
code: String,
license_id: Option<String>,
}
impl LicenseProvider for KeygenProvider {
fn check(
&self,
key: &str,
fingerprint: &str,
progress: &mut dyn FnMut(String),
) -> Result<bool, CheckErr> {
progress("validating license…".into());
let r = self.validate(key, fingerprint)?;
if r.valid {
return Ok(true);
}
if matches!(
r.code.as_str(),
"NO_MACHINE" | "NO_MACHINES" | "FINGERPRINT_SCOPE_MISMATCH"
) {
if let Some(id) = r.license_id {
progress("activating this device…".into());
let _ = self.activate_machine(key, fingerprint, &id); return Ok(self.validate(key, fingerprint)?.valid);
}
}
progress(format!("license not valid ({})", r.code));
Ok(false)
}
}