Clavem

License activation and deactivation in a Tauri app

Run activate in a Rust command, hash the machine id with your app identifier, and return a small tagged state to the webview. When every seat is taken, the state carries the used and allowed counts, so the page can send the customer to the device page.

This page is the Tauri side of activation: a command that returns something the webview can render, a salt that comes from your own configuration, and a button to free the seat. The machine id and the plain Rust client are in device activation in Rust, and the check at each launch is in license key validation in Tauri.

A state for the webview

An activation attempt has four outcomes worth different screens. Return a tagged enum and the front end gets a discriminated union:

use serde::Serialize;
use serde_json::{json, Value};

#[derive(Serialize, Clone, Debug)]
#[serde(tag = "state", rename_all = "kebab-case")]
pub enum ActivationState {
    Activated,
    LimitReached { used: u64, limit: u64 },
    Refused { reason: String },   // expired, disabled, unknown key
    Offline,                      // no answer: offline, 429 or 5xx
}

/// Turns the reply into a state, plus the instance id and token to save when it worked.
pub fn interpret(status: u16, reply: &Value) -> (ActivationState, Option<(String, String)>) {
    let message = reply["error"].as_str().unwrap_or("Activation failed.").to_string();
    match status {
        200 => match (reply["instance"]["id"].as_str(), reply["token"].as_str()) {
            (Some(id), Some(token)) => (ActivationState::Activated, Some((id.into(), token.into()))),
            _ => (ActivationState::Offline, None),
        },
        400 | 404 => {
            let lic = &reply["license_key"];
            match (lic["activation_usage"].as_u64(), lic["activation_limit"].as_u64()) {
                (Some(used), Some(limit)) if used >= limit && message.contains("activation limit")
                    => (ActivationState::LimitReached { used, limit }, None),
                _ => (ActivationState::Refused { reason: message }, None),
            }
        }
        _ => (ActivationState::Offline, None),
    }
}

interpret takes plain values, so it can be tested without a window. Against a local stub that returns the documented responses, with no live activation, it produced the JSON the webview would receive:

TEST-ACTIVE   200 {"state":"activated"} saved=true
TEST-ACTIVE   200 {"state":"activated"} saved=true
TEST-LIMIT    400 {"state":"limit-reached","used":3,"limit":3} saved=false
TEST-EXPIRED  400 {"state":"refused","reason":"This license key has expired."} saved=false
NOPE          404 {"state":"refused","reason":"license_key not found."} saved=false
TEST-429      429 {"state":"offline"} saved=false

The second line is the same machine activating twice. The fingerprint made the stub return the same seat, so the device count did not move.

The command, with a salt from your own config

Hash the machine id with your app identifier, so the fingerprint is specific to this app. Read the identifier from the Tauri config at run time. It is the same string as identifier in tauri.conf.json, so there is no second copy to forget:

use sha2::{Digest, Sha256};
use tauri::{AppHandle, State};

fn fingerprint(salt: &str) -> Option<String> {
    let id = machine_uid::get().ok()?;
    Some(Sha256::digest(format!("{salt}:{id}")).iter().map(|b| format!("{b:02x}")).collect())
}

#[tauri::command]
pub async fn activate_license(app: AppHandle, licensing: State<'_, Licensing>, key: String) -> Result<ActivationState, String> {
    let name = hostname::get().map(|h| h.to_string_lossy().into_owned()).unwrap_or_else(|_| "Computer".into());
    let mut body = json!({ "license_key": key, "instance_name": name });
    if let Some(fp) = fingerprint(&app.config().identifier) { body["fingerprint"] = json!(fp); }

    let Some((status, reply)) = licensing.post("activate", body).await else { return Ok(ActivationState::Offline) };
    let (state, saved) = interpret(status, &reply);
    if let Some((instance_id, token)) = saved { save(&Saved { key, instance_id, token }); }
    Ok(state)
}

Licensing, post, save and Saved are from the validation page. The machine_uid crate is explained on the Rust activation page. The pure functions above were.

What the front end does

import { invoke } from '@tauri-apps/api/core';
import { openUrl } from '@tauri-apps/plugin-opener';

const result = await invoke('activate_license', { key });
switch (result.state) {
  case 'activated':
    showApp();
    break;
  case 'limit-reached':
    showMessage(`This key is already active on ${result.used} of ${result.limit} computers.`);
    showButton('Manage computers', () => openUrl('https://clavem.io/licenses/manage'));
    break;
  case 'refused':
    showMessage(result.reason);
    break;
  case 'offline':
    showMessage('Could not reach the license server. Check your connection and try again.');
    break;
}

The device page at /licenses/manage takes the customer’s key, lists their computers and removes one, with no account. Do not add a retry button to the limit message: no retry can succeed until a seat is free.

Deactivate on request

#[tauri::command]
pub async fn deactivate_license(licensing: State<'_, Licensing>) -> Result<bool, String> {
    let Some(saved) = load() else { return Ok(true) };
    let reply = licensing.post("deactivate", json!({ "license_key": saved.key, "instance_id": saved.instance_id })).await;
    let freed = matches!(reply, Some((200 | 404, _)));   // 404: the seat was already gone
    if freed { clear(); }
    Ok(freed)
}

Tie it to a button that says what it does, such as “Move this license to another computer”. When it returns false, keep the saved ids and say that the seat is still taken and can be removed from the device page. Never call it from an exit handler. Quitting is not moving.

Things specific to Tauri

  • Keep the instance id out of webview storage. localStorage and IndexedDB belong to the webview, can be cleared with its data, and are readable from page scripts. The Rust-side keyring is where the id and token go.
  • The fingerprint is the safety net. If the saved ids are lost, a fresh activation with the same fingerprint gets the same seat back, with the name updated.
  • Debug builds activate too. tauri dev on your own machine uses a seat unless you point it at a test license with a higher limit.
  • A new bundle identifier changes the salt, and so every customer’s fingerprint. Set it once, before release.

Doing this with Clavem

The device limit is set on the product, three by default, and PATCH /v1/admin/licenses/:id can change it for one license. See the API reference for activation errors and the response fields.

Questions

What happens to the seat if a Tauri user clears the app's data?

The seat stays used on the server, but activating again with the same fingerprint returns that seat instead of a new one. That is why the fingerprint matters. It makes lost local state harmless.

How do I open the customer's device page from a Tauri app?

Use the opener plugin and call openUrl with the device page address. Tauri documents openUrl in the JavaScript and Rust APIs of the plugin.

Should I deactivate when the app quits?

No. Quitting does not move the license to another computer. Deactivate only on an explicit user action such as a Move license button, or the next launch needs a fresh activation.

Sources

  1. Tauri 2, Opener plugin (checked November 2026)
  2. Tauri 2, Configuration reference (identifier) (checked November 2026)