keygen_rs/
lib.rs

1use client::Client;
2use errors::Error;
3use license::{License, LicenseResponse, SchemeCode};
4use serde::{Deserialize, Serialize};
5
6pub(crate) mod certificate;
7pub(crate) mod client;
8pub(crate) mod decryptor;
9pub(crate) mod verifier;
10
11pub mod component;
12pub mod config;
13pub mod entitlement;
14pub mod errors;
15pub mod group;
16pub mod license;
17pub mod license_file;
18pub mod machine;
19pub mod machine_file;
20pub mod service;
21
22// Management features only available with "token" feature flag
23#[cfg(feature = "token")]
24pub mod policy;
25#[cfg(feature = "token")]
26pub mod product;
27#[cfg(feature = "token")]
28pub mod token;
29#[cfg(feature = "token")]
30pub mod user;
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub(crate) struct KeygenRelationshipData {
34    pub r#type: String,
35    pub id: String,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub(crate) struct KeygenRelationship {
40    #[serde(default)]
41    pub data: Option<KeygenRelationshipData>,
42    #[serde(default)]
43    pub links: Option<serde_json::Value>,
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize, Default)]
47pub(crate) struct KeygenRelationships {
48    #[serde(default)]
49    pub policy: Option<KeygenRelationship>,
50    #[serde(default)]
51    pub account: Option<KeygenRelationship>,
52    #[serde(default)]
53    pub product: Option<KeygenRelationship>,
54    #[serde(default)]
55    pub group: Option<KeygenRelationship>,
56    #[serde(default)]
57    pub owner: Option<KeygenRelationship>,
58    #[serde(default)]
59    pub users: Option<KeygenRelationship>,
60    #[serde(default)]
61    pub machines: Option<KeygenRelationship>,
62    #[serde(default)]
63    pub environment: Option<KeygenRelationship>,
64    #[serde(default)]
65    pub license: Option<KeygenRelationship>,
66    // Use flatten to capture any other relationship fields we don't explicitly handle
67    #[serde(flatten)]
68    pub other: std::collections::HashMap<String, serde_json::Value>,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize)]
72pub(crate) struct KeygenResponseData<T> {
73    pub id: String,
74    pub r#type: String,
75    pub attributes: T,
76    pub relationships: KeygenRelationships,
77}
78
79/// Validates a license key
80///
81/// # Example
82/// ```
83/// #[tokio::main]
84/// async fn main() -> Result<(), Error> {
85///     dotenv().ok();
86///     config::set_config(KeygenConfig {
87///         api_url: env::var("KEYGEN_API_URL").expect("KEYGEN_API_URL must be set"),
88///         account: env::var("KEYGEN_ACCOUNT").expect("KEYGEN_ACCOUNT must be set"),
89///         product: env::var("KEYGEN_PRODUCT").expect("KEYGEN_PRODUCT must be set"),
90///         license_key: Some(env::var("KEYGEN_LICENSE_KEY").expect("KEYGEN_LICENSE_KEY must be set")),
91///         public_key: Some(env::var("KEYGEN_PUBLIC_KEY").expect("KEYGEN_PUBLIC_KEY must be set")),
92///         ..KeygenConfig::default()
93///     });
94///
95///     let fingerprint = machine_uid::get().unwrap_or("".into());
96///     let license = keygen_rs::validate(&[fingerprint]).await?;
97///     println!("License validated successfully: {:?}", license);
98///     Ok(())
99/// }
100/// ```
101pub async fn validate(fingerprints: &[String], entitlements: &[String]) -> Result<License, Error> {
102    let client = Client::default()?;
103    let response = client.get("me", None::<&()>).await?;
104    let profile: LicenseResponse<()> = serde_json::from_value(response.body)?;
105    let license = License::from(profile.data);
106    license.validate_key(fingerprints, entitlements).await
107}
108
109/// Verifies a signed key based on a given scheme
110///
111/// Supported schemes are:
112/// - Ed25519Sign
113///
114/// # Example
115/// ```
116/// #[tokio::main]
117/// async fn main() {
118///     dotenv().ok();
119///     let (public_key, signed_key) =
120///         generate_signed_license_key("4F5D3B-0FB8B2-6871BC-5D3EB3-4885B7-V3".to_string());
121///     config::set_config(KeygenConfig {
122///         api_url: env::var("KEYGEN_API_URL").expect("KEYGEN_API_URL must be set"),
123///         account: env::var("KEYGEN_ACCOUNT").expect("KEYGEN_ACCOUNT must be set"),
124///         product: env::var("KEYGEN_PRODUCT").expect("KEYGEN_PRODUCT must be set"),
125///         license_key: Some(env::var("KEYGEN_LICENSE_KEY").expect("KEYGEN_LICENSE_KEY must be set")),
126///         public_key: Some(public_key.clone()),
127///         ..KeygenConfig::default()
128///     });
129///
130///     println!("Signed key: {:?}", signed_key);
131///     if let Ok(data) = keygen_rs::verify(SchemeCode::Ed25519Sign, &signed_key) {
132///       println!("License verified: {:?}", String::from_utf8_lossy(&data));
133///     } else {
134///       println!("License verification failed");
135///     }
136/// }
137pub fn verify(scheme: SchemeCode, signed_key: &str) -> Result<Vec<u8>, Error> {
138    let license = License::from_signed_key(scheme, signed_key);
139    license.verify()
140}