Guide
How to Add License Keys to a Tauri / Rust App
Keyfern does not ship an official Rust crate yet; use the 4-endpoint public REST API alongside standard Rust crates (reqwest, ed25519-dalek, base64, serde_json).
This guide builds a small license.rs module for the Rust side of a Tauri app (or any Rust desktop app): node-locked activation, local Ed25519 verification, an offline cache with clock rollback checks, and a Tauri command your frontend can call. The code was compiled and run against the live Keyfern API. For the full API reference see the Keyfern documentation.
Why Signed Payloads Beat Plain JSON Checks
The quickest license check is a plain request that trusts a JSON field:
// INSECURE PATTERN - DO NOT USE
let body: serde_json::Value = reqwest::get(format!("https://api.myapp.com/verify?key={key}"))
.await?
.json()
.await?;
if body["valid"] == true {
launch_app();
}
Anyone can add your API host to their hosts file, point it to 127.0.0.1 and run a tiny local server that answers {"valid": true}. Your app unlocks forever, and it locks out paying customers the moment they are offline.
Keyfern answers every license call with a payload signed by the product's Ed25519 private key, which never leaves the server. Your app embeds only the public key. A fake server cannot produce a valid signature, and a verified answer can be cached for offline use. Every answer has this shape:
{ "ok": true, "payload": "eyJ2IjoxLCJwcm9kdWN0Ijoi...", "sig": "q1Xc...", "license": { ... } }
payloadis the license as UTF-8 JSON, encoded as base64url without padding (RFC 4648 §5).sigis the 64-byte Ed25519 signature, also base64url without padding. It is computed over the exact decoded bytes ofpayload: not over the base64 text and not over re-serialized JSON. Verify first, then parse those same bytes.- The public key is the raw 32-byte Ed25519 key, base64url without padding. Copy it from the product's Integrate tab in the dashboard (
GET /v1/products/{product}/public-keyreturns it too, with a PEM copy). licenseis an unsigned copy for debugging. Never make decisions on it.
The signed payload contains v, product, key, machine, nonce, iat (issue time, Unix seconds), status (active, expired or blocked), expires, lease_until, features, max_machines, machines_used, customer, meta, usage and op.
Step 1: Call POST /v1/activate from Rust
Add the crates to src-tauri/Cargo.toml. getrandom makes the nonce; machine-uid and sha2 build a hashed machine ID. Tauri already runs a Tokio runtime, so the async reqwest client needs nothing else.
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
ed25519-dalek = "2"
base64 = "0.22"
serde_json = "1"
getrandom = "0.3"
machine-uid = "0.5"
sha2 = "0.10"
Send the key, a stable machine code and a fresh random nonce. The server copies the nonce into the signed payload, so a recorded old answer cannot be replayed later. Refusals come back as HTTP 4xx with {"error": "...", "message": "..."} (machine_limit, expired, blocked, invalid_key); 5xx and 429 are treated like a network failure so the app can fall back to its cache.
// src-tauri/src/license.rs
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use serde_json::{json, Value};
use std::{fmt, fs, path::Path, time::{SystemTime, UNIX_EPOCH}};
const API: &str = "https://keyfern.com";
const PRODUCT: &str = "prod_your_product_id"; // dashboard > product > Integrate
const PUBLIC_KEY: &str = "YOUR_ED25519_PUBLIC_KEY_BASE64URL"; // 32 raw bytes, base64url, no padding
#[derive(Debug)]
pub enum LicenseError {
Network(String), // no answer: fall back to the cached lease
Server(String), // signed refusal codes such as machine_limit, expired, blocked, invalid_key
Invalid(&'static str), // bad_signature, replay, wrong_machine, clock_rollback, lease_expired ...
}
impl fmt::Display for LicenseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Network(m) => write!(f, "network: {m}"),
Self::Server(c) => f.write_str(c),
Self::Invalid(c) => f.write_str(c),
}
}
}
fn now() -> i64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64
}
fn b64(s: &str) -> Result<Vec<u8>, LicenseError> {
URL_SAFE_NO_PAD.decode(s.trim_end_matches('=')).map_err(|_| LicenseError::Invalid("bad_signature"))
}
/// Fresh random nonce per request: the server signs it back, so an old answer cannot be replayed.
pub fn new_nonce() -> String {
let mut buf = [0u8; 16];
getrandom::fill(&mut buf).expect("OS random generator");
URL_SAFE_NO_PAD.encode(buf)
}
/// Stable per-PC id, hashed so the raw OS id never leaves the machine.
pub fn machine_code() -> String {
use sha2::{Digest, Sha256};
let raw = machine_uid::get().unwrap_or_default();
Sha256::digest(format!("my-app|{raw}")).iter().take(16).map(|b| format!("{b:02x}")).collect()
}
/// POST /v1/activate. Returns the raw answer { ok, payload, sig, license }.
pub async fn activate(key: &str, machine: &str, nonce: &str) -> Result<Value, LicenseError> {
let res = reqwest::Client::new()
.post(format!("{API}/v1/activate"))
.json(&json!({ "product": PRODUCT, "key": key, "machine": machine, "nonce": nonce, "name": "My Tauri app" }))
.send()
.await
.map_err(|e| LicenseError::Network(e.to_string()))?;
let status = res.status();
let body: Value = res.json().await.map_err(|e| LicenseError::Network(e.to_string()))?;
if status.is_server_error() || status.as_u16() == 429 {
return Err(LicenseError::Network(format!("HTTP {status}")));
}
if !status.is_success() {
return Err(LicenseError::Server(body["error"].as_str().unwrap_or("error").to_string()));
}
Ok(body)
}
Step 2: Verify the Ed25519 Signature Locally
With ed25519-dalek, decode the public key, the payload and the signature, verify, and only then parse the JSON. Then check that the answer is for your product, carries the nonce you sent and names this machine.
/// Checks the Ed25519 signature over the exact payload bytes, then product, nonce and machine.
/// Never read answer["license"]: it is an unsigned copy for debugging.
pub fn verify(answer: &Value, nonce: Option<&str>, machine: &str) -> Result<Value, LicenseError> {
let bad = LicenseError::Invalid("bad_signature");
let pk: [u8; 32] = b64(PUBLIC_KEY)?.try_into().map_err(|_| LicenseError::Invalid("bad_signature"))?;
let vk = VerifyingKey::from_bytes(&pk).map_err(|_| LicenseError::Invalid("bad_signature"))?;
let payload = b64(answer["payload"].as_str().ok_or(LicenseError::Invalid("bad_signature"))?)?;
let sig = Signature::from_slice(&b64(answer["sig"].as_str().ok_or(LicenseError::Invalid("bad_signature"))?)?)
.map_err(|_| LicenseError::Invalid("bad_signature"))?;
vk.verify(&payload, &sig).map_err(|_| bad)?;
// only now parse the bytes that were signed
let lic: Value = serde_json::from_slice(&payload).map_err(|_| LicenseError::Invalid("bad_signature"))?;
if lic["product"] != PRODUCT {
return Err(LicenseError::Invalid("bad_signature"));
}
if let Some(n) = nonce {
if lic["nonce"] != n {
return Err(LicenseError::Invalid("replay"));
}
}
if lic["machine"] != machine {
return Err(LicenseError::Invalid("wrong_machine"));
}
Ok(lic)
}
Try it on the public demo product. Set PRODUCT to prod_demo and PUBLIC_KEY to H2r9o0JnaRK19BX97GYWXnlx6coRoeo-cSW3wAOebXo, then activate the key DEMO-KEYFERN-TRY-IT with the machine demo-browser. The demo key has one seat, so any other machine gets machine_limit. It is the same product the live demo on the home page uses.
Step 3: Caching Offline Leases & Clock Rollback Checks
Save the signed answer and re-verify it at every start. The cache holds only payload, sig and the latest time the app has seen: editing the license inside it breaks the signature, and setting the PC clock back more than one hour is refused as clock_rollback.
/// Keep the signed answer (payload + sig) and the latest time we have seen.
pub fn save(path: &Path, answer: &Value) -> std::io::Result<()> {
let cache = json!({ "payload": answer["payload"], "sig": answer["sig"], "last_seen": now() });
fs::write(path, cache.to_string())
}
/// Offline start-up check: signature, machine, clock rollback, status, expiry and lease.
pub fn cached(path: &Path, machine: &str) -> Result<Value, LicenseError> {
let raw = fs::read(path).map_err(|_| LicenseError::Invalid("no_cache"))?;
let mut cache: Value = serde_json::from_slice(&raw).map_err(|_| LicenseError::Invalid("no_cache"))?;
let lic = verify(&cache, None, machine)?;
let t = now();
let last_seen = cache["last_seen"].as_i64().unwrap_or(0).max(lic["iat"].as_i64().unwrap_or(0));
if t < last_seen - 3600 {
return Err(LicenseError::Invalid("clock_rollback")); // clock set back by more than 1 hour
}
if lic["status"] != "active" {
return Err(LicenseError::Invalid("not_active"));
}
if lic["expires"].as_i64().is_some_and(|e| e <= t) {
return Err(LicenseError::Invalid("expired"));
}
if lic["lease_until"].as_i64().is_some_and(|l| l <= t) {
return Err(LicenseError::Invalid("lease_expired")); // connect once to renew the lease
}
cache["last_seen"] = json!(t);
let _ = fs::write(path, cache.to_string());
Ok(lic)
}
/// Normal start-up call: online when possible, verified cache when offline.
pub async fn activate_or_cached(key: &str, cache_path: &Path) -> Result<Value, LicenseError> {
let machine = machine_code();
let nonce = new_nonce();
match activate(key, &machine, &nonce).await {
Ok(answer) => {
let lic = verify(&answer, Some(&nonce), &machine)?;
let _ = save(cache_path, &answer);
Ok(lic)
}
Err(LicenseError::Network(_)) => cached(cache_path, &machine),
Err(LicenseError::Server(code)) => {
if ["blocked", "expired", "invalid_key", "machine_limit"].contains(&code.as_str()) {
let _ = fs::remove_file(cache_path);
}
Err(LicenseError::Server(code))
}
Err(e) => Err(e),
}
}
Offline leases are off by default. A new product has lease_days = 0: lease_until equals iat, so cached() refuses at once with lease_expired and the app must be online to start. To let paying users launch offline, set Offline use (days) on the product in the dashboard to any value from 1 to 3,650 days. After that period without a successful online check, the app asks the user to connect once.
Expose the check to your frontend as a Tauri command and register it in the builder with .invoke_handler(tauri::generate_handler![check_license]):
// src-tauri/src/lib.rs
mod license;
use tauri::Manager;
#[tauri::command]
async fn check_license(app: tauri::AppHandle, key: String) -> Result<serde_json::Value, String> {
let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
license::activate_or_cached(&key, &dir.join("license.cache"))
.await
.map_err(|e| e.to_string())
}
From JavaScript, call await invoke('check_license', { key }) (from @tauri-apps/api/core) at every launch with the key the user entered, and open the app when it resolves. The returned object is the verified payload: read features, expires and lease_until from it.
Pricing & Quickstart
- Free: 1 product and 50 keys, no credit card.
- Starter $10/month: 1,000 keys, plus sales through your own Stripe account: Keyfern creates and emails the key at checkout and extends it on renewal, with 0% Keyfern commission. See Sell license keys with Stripe.
- Business $30/month (10,000 keys) and Enterprise $79/month (100,000 keys). No per-call fees.
Watch a real signed activation in your browser with the live demo, then create a free account, add a product and paste its ID and public key into license.rs. Building with Electron instead? Read the Electron licensing guide.