Clavem

How to validate a license key in a Tauri app

Run the validate call in a Rust command with a shared reqwest client, keep the key and token in the keyring, and send the webview only a small state tag. The webview never holds the key, and the CSP does not need to allow clavem.io.

A Tauri app has two halves: a Rust process and a webview. Put the license logic in the Rust half. This page shows the commands, the state they return and the startup wiring. The plain Rust client, with ureq, is in license key validation in Rust, and the platform guide in the docs has a shorter Tauri version in the platform guides.

The state the webview sees

The webview should learn one of four things and nothing else:

use serde::Serialize;

#[derive(Serialize, Clone, Debug)]
#[serde(tag = "state", rename_all = "kebab-case")]
pub enum LicenseState {
    Licensed,
    Invalid { reason: String },
    NeedsNetwork,
    Unlicensed,
}

Serialized, that is {"state":"licensed"}, {"state":"invalid","reason":"This license key has expired."} or {"state":"needs-network"}. In JavaScript it is a discriminated union you can switch on.

The client and the commands

One reqwest::Client for the whole app keeps connections open between calls, so build it once and put it in Tauri’s managed state. The timeout is 8 seconds. This is the validate path; Verifier is the token check from offline verification in Tauri:

use serde_json::{json, Value};
use std::time::Duration;
use tauri::State;

pub struct Licensing { http: reqwest::Client, base: String }

impl Licensing {
    pub fn new() -> Self {
        let http = reqwest::Client::builder()
            .timeout(Duration::from_secs(8))
            .user_agent("Inkwell/3.2")
            .build()
            .expect("http client");
        Self { http, base: "https://clavem.io".into() }
    }

    async fn post(&self, action: &str, body: Value) -> Option<(u16, Value)> {
        let res = self.http.post(format!("{}/v1/licenses/{action}", self.base)).json(&body).send().await.ok()?;
        let status = res.status().as_u16();
        Some((status, res.json::<Value>().await.unwrap_or(Value::Null)))
    }

    pub async fn check(&self, verifier: &Verifier) -> LicenseState {
        let Some(mut saved) = load() else { return LicenseState::Unlicensed };
        let body = json!({ "license_key": saved.key, "instance_id": saved.instance_id });
        if let Some((status, reply)) = self.post("validate", body).await {
            match status {
                200 => {
                    if let Some(token) = reply["token"].as_str() { saved.token = token.into(); save(&saved); }
                    return if reply["valid"] == true { LicenseState::Licensed }
                    else { LicenseState::Invalid { reason: reply["error"].as_str().unwrap_or("This license is not valid.").into() } };
                }
                404 => { clear(); return LicenseState::Invalid { reason: reply["error"].as_str().unwrap_or("License not found.").into() }; }
                _ => {} // 429 and 5xx are not a verdict
            }
        }
        // No answer: trust the saved token while it is fresh.
        if verifier.check(&saved.token, now(), 0) == Check::Ok { LicenseState::Licensed } else { LicenseState::NeedsNetwork }
    }
}

#[tauri::command]
pub async fn check_license(licensing: State<'_, Licensing>) -> Result<LicenseState, String> {
    let verifier = Verifier::new(PUBLIC_KEY, PRODUCT_ID).ok_or("The public key in the build is not valid.")?;
    Ok(licensing.check(&verifier).await)
}

load, save and clear read and write one keyring entry that holds the key, the instance id and the token as JSON. The keyring code is on the Rust validation page. Use your tauri.conf.json identifier as the service name.

The command returns Result on purpose. Tauri documents that async commands with borrowed arguments, State<'_, T> among them, cannot be declared async as they are, and returning a Result is one of the documented workarounds.

Check at startup without blocking it

Run the first check in setup, on Tauri’s async runtime, and tell the webview with an event. The window opens at once:

use tauri::{Emitter, Manager};

tauri::Builder::default()
    .manage(Licensing::new())
    .invoke_handler(tauri::generate_handler![check_license, activate_license])
    .setup(|app| {
        let handle = app.handle().clone();
        tauri::async_runtime::spawn(async move {
            let licensing = handle.state::<Licensing>();
            let verifier = Verifier::new(PUBLIC_KEY, PRODUCT_ID).expect("public key");
            let _ = handle.emit("license-state", licensing.check(&verifier).await);
        });
        Ok(())
    })
import { listen } from '@tauri-apps/api/event';
import { invoke } from '@tauri-apps/api/core';

await listen('license-state', (event) => applyLicense(event.payload));
const state = await invoke('check_license'); // same shape: { state: 'licensed' } and so on

Real results

Example output:

before activation: Unlicensed
check online: Licensed
check with the server down: Licensed
server down, token for another product: NeedsNetwork

CSP and the HTTP plugin

Tauri’s documented example CSP sets connect-src to ipc: http://ipc.localhost. A request made from Rust is not subject to the webview’s CSP, so that setting needs no change. If you call the License API from JavaScript with @tauri-apps/plugin-http instead, you must add clavem.io to both the CSP and an allow scope on http:default in the capability file. Doing it in Rust avoids two places where the host can go out of sync.

Pitfalls specific to Tauri

  • Debug and release share the keyring. tauri dev writes to the same entry as an installed build. Use another service name when cfg!(debug_assertions) is true.
  • Changing the bundle identifier loses the saved key if you use it as the keyring service. Fix the service string once.
  • 429 and 503 are not verdicts. Retry-After is 60 and 5 seconds. Fall back to the token and retry later, not in a loop.
  • A webview reload re-runs your front end, not setup. Keep the last state in Rust so a reload can ask check_license again cheaply.

Doing this with Clavem

The License API needs no secret, so the binary holds nothing sensitive. Plan limits never block validation. See device activation for the first-run call, and the API reference for each field.

Questions

Should a Tauri app call the License API from JavaScript or from Rust?

From Rust. The key and token then stay out of the webview, the CSP stays at ipc only, and the check can run at startup before any page loads. JavaScript would need the HTTP plugin with an allowed URL in a capability.

Why does my async Tauri command fail to compile with State?

Async commands with borrowed arguments such as State need to return a Result. Tauri documents this limit. Return Result of your state type and a String, and the command compiles.

Where does a Tauri app store the license key?

In the operating system's credential store through the keyring crate, under your app identifier. The store plugin writes a plain JSON file, which is fine for settings and wrong for a key.

Sources

  1. Tauri 2, Calling Rust from the frontend (checked November 2026)
  2. Tauri 2, Content Security Policy (checked November 2026)
  3. Tauri 2, HTTP client plugin (checked November 2026)
  4. Tauri 2, Capabilities (checked November 2026)