rustify_licensing/provider/
keygen.rs1use serde_json::{json, Value};
15
16use crate::core::config::LicenseConfig;
17use crate::core::error::CheckErr;
18
19use super::LicenseProvider;
20
21pub struct KeygenProvider {
24 account_id: String,
25 api_base: String,
26}
27
28impl KeygenProvider {
29 pub fn new(account_id: impl Into<String>, api_base: impl Into<String>) -> Self {
30 Self {
31 account_id: account_id.into(),
32 api_base: api_base.into(),
33 }
34 }
35
36 pub fn from_config(config: &LicenseConfig) -> Self {
38 Self::new(config.account_id.clone(), config.api_base.clone())
39 }
40
41 fn post(&self, path: &str, auth: Option<&str>, body: &Value) -> Result<Value, CheckErr> {
44 let url = format!("{}/accounts/{}/{}", self.api_base, self.account_id, path);
45 let mut req = ureq::post(&url)
46 .set("Content-Type", "application/vnd.api+json")
47 .set("Accept", "application/vnd.api+json");
48 if let Some(key) = auth {
51 req = req.set("Authorization", &format!("License {key}"));
52 }
53 let payload = serde_json::to_string(body).map_err(|e| CheckErr::Denied(e.to_string()))?;
54 match req.send_string(&payload) {
55 Ok(resp) => resp
57 .into_json::<Value>()
58 .map_err(|e| CheckErr::Offline(format!("decode: {e}"))),
60 Err(ureq::Error::Status(code, resp)) => {
61 let detail: String = resp
62 .into_string()
63 .unwrap_or_default()
64 .chars()
65 .take(200)
66 .collect();
67 let msg = format!("HTTP {code}: {detail}");
68 if code == 408 || code == 429 || code >= 500 {
71 Err(CheckErr::Offline(msg))
72 } else {
73 Err(CheckErr::Denied(msg))
74 }
75 }
76 Err(e) => Err(CheckErr::Offline(format!("network: {e}"))),
77 }
78 }
79
80 fn validate(&self, key: &str, fingerprint: &str) -> Result<Validation, CheckErr> {
81 let body = json!({ "meta": { "key": key, "scope": { "fingerprint": fingerprint } } });
82 let v = self.post("licenses/actions/validate-key", None, &body)?;
83 Ok(Validation {
84 valid: v["meta"]["valid"].as_bool().unwrap_or(false),
85 code: v["meta"]["code"].as_str().unwrap_or("UNKNOWN").to_string(),
86 license_id: v["data"]["id"].as_str().map(str::to_string),
87 })
88 }
89
90 fn activate_machine(&self, key: &str, fingerprint: &str, license_id: &str) -> Result<(), CheckErr> {
91 let body = json!({
92 "data": {
93 "type": "machines",
94 "attributes": { "fingerprint": fingerprint },
95 "relationships": { "license": { "data": { "type": "licenses", "id": license_id } } }
96 }
97 });
98 self.post("machines", Some(key), &body).map(|_| ())
99 }
100}
101
102struct Validation {
103 valid: bool,
104 code: String,
105 license_id: Option<String>,
106}
107
108impl LicenseProvider for KeygenProvider {
109 fn check(
112 &self,
113 key: &str,
114 fingerprint: &str,
115 progress: &mut dyn FnMut(String),
116 ) -> Result<bool, CheckErr> {
117 progress("validating license…".into());
118 let r = self.validate(key, fingerprint)?;
119 if r.valid {
120 return Ok(true);
121 }
122 if matches!(
124 r.code.as_str(),
125 "NO_MACHINE" | "NO_MACHINES" | "FINGERPRINT_SCOPE_MISMATCH"
126 ) {
127 if let Some(id) = r.license_id {
128 progress("activating this device…".into());
129 let _ = self.activate_machine(key, fingerprint, &id); return Ok(self.validate(key, fingerprint)?.valid);
131 }
132 }
133 progress(format!("license not valid ({})", r.code));
134 Ok(false)
135 }
136}