What every guide does
- Activate when the customer enters a key. Store the key, the instance id and the token somewhere only your app can read.
- Validate at every launch with a short timeout. Valid or not, store the token from the answer.
- Fall back to the stored token when there is no answer, and accept it while its signature is good, it says
valid, and neitherexpnorrefresh_byhas passed. - Deactivate when the customer moves the license to another machine.
This is the launch-time flow from the quickstart. Each guide uses the token check from offline verification, and says where the code comes from. Replace the placeholders: the public key and product id are on your product page, and the host is https://clavem.io.
The Swift and Electron samples were run against the live API, apart from the activation call that succeeds. The Python sample's calls and flow were run too, but not its PyNaCl signature check. The Tauri and WordPress samples were written from the libraries' documentation and have not been run.
Swift and macOS
Uses URLSession, the Keychain for storage, and CryptoKit through the verification code. The fingerprint is a hash of the Mac's hardware UUID. Requires macOS 12 or later for kIOMainPortDefault. A sandboxed app needs the outgoing network entitlement.
import CryptoKit
import Foundation
import IOKit
import Security
// LicenseClaims, verifyToken(_:publicKey:) and isLicensed(_:productID:) are on the offline verification page.
enum LicenseState {
case unlicensed
case licensed
case invalid(String)
case needsNetwork
}
struct SavedLicense: Codable {
var key: String
var instanceID: String
var token: String
}
struct LicenseError: Error { let message: String }
final class LicenseManager {
static let shared = LicenseManager()
private let base: URL
private let service: String
private let publicKey: String
private let productID: Int
init(
base: URL = URL(string: "https://clavem.io")!,
service: String = "com.example.inkwell.license", // your bundle identifier plus ".license"
publicKey: String = "kq1…your key…9fA", // from your product page
productID: Int = 75 // from your product page
) {
self.base = base
self.service = service
self.publicKey = publicKey
self.productID = productID
}
// MARK: The three calls
/// Once per device, when the customer enters their key.
func activate(key: String) async throws {
let reply = try await post("activate", [
"license_key": key,
"instance_name": Host.current().localizedName ?? "Mac",
"fingerprint": fingerprint(),
])
guard reply.json["activated"] as? Bool == true,
let instance = reply.json["instance"] as? [String: Any],
let id = instance["id"] as? String,
let token = reply.json["token"] as? String
else { throw LicenseError(message: reply.json["error"] as? String ?? "Activation failed.") }
save(SavedLicense(key: key, instanceID: id, token: token))
}
/// At every launch.
func check() async -> LicenseState {
guard var saved = load() else { return .unlicensed }
if let reply = try? await post("validate", ["license_key": saved.key, "instance_id": saved.instanceID]) {
if reply.status == 200, let token = reply.json["token"] as? String {
// Keep the new token even when the license is not valid: offline, it then says so.
saved.token = token
save(saved)
if reply.json["valid"] as? Bool == true { return .licensed }
return .invalid(reply.json["error"] as? String ?? "This license is not valid.")
}
if reply.status == 404 {
clear() // unknown key, or this device was removed: ask for the key again
return .invalid(reply.json["error"] as? String ?? "This license was not found.")
}
}
// Offline, rate limited or the service is down: trust the stored token while it is fresh.
let claims = verifyToken(saved.token, publicKey: publicKey)
return isLicensed(claims, productID: productID) ? .licensed : .needsNetwork
}
/// When the customer moves the license to another Mac.
func deactivate() async {
guard let saved = load() else { return }
_ = try? await post("deactivate", ["license_key": saved.key, "instance_id": saved.instanceID])
clear()
}
func post(_ action: String, _ body: [String: String]) async throws -> (status: Int, json: [String: Any]) {
var request = URLRequest(url: base.appendingPathComponent("v1/licenses/" + action))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: body)
request.timeoutInterval = 8
let (data, response) = try await URLSession.shared.data(for: request)
let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
return ((response as? HTTPURLResponse)?.statusCode ?? 0, json)
}
// MARK: Storage in the Keychain
private func query() -> [String: Any] {
[kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service]
}
private func save(_ license: SavedLicense) {
guard let data = try? JSONEncoder().encode(license) else { return }
SecItemDelete(query() as CFDictionary)
SecItemAdd(query().merging([kSecValueData as String: data]) { $1 } as CFDictionary, nil)
}
private func load() -> SavedLicense? {
let request = query().merging([kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]) { $1 }
var item: CFTypeRef?
guard SecItemCopyMatching(request as CFDictionary, &item) == errSecSuccess, let data = item as? Data else { return nil }
return try? JSONDecoder().decode(SavedLicense.self, from: data)
}
private func clear() {
SecItemDelete(query() as CFDictionary)
}
/// A stable, hashed identifier for this Mac, so activating twice does not use two seats.
private func fingerprint() -> String {
let entry = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("IOPlatformExpertDevice"))
defer { IOObjectRelease(entry) }
let uuid = IORegistryEntryCreateCFProperty(entry, "IOPlatformUUID" as CFString, kCFAllocatorDefault, 0)?
.takeRetainedValue() as? String ?? UUID().uuidString
return SHA256.hash(data: Data(uuid.utf8)).map { String(format: "%02x", $0) }.joined()
}
}Call await LicenseManager.shared.check() in applicationDidFinishLaunching, or in a SwiftUI .task on your root view, and gate features on the returned LicenseState.
Electron and Node
Runs in the main process, where the key and token stay out of the renderer. safeStorage encrypts them with the operating system's keychain. Verification uses node:crypto, which handles Ed25519 in every supported Node and Electron version. The renderer reaches it through IPC, for example ipcRenderer.invoke('license:check') from your preload script.
// Main process. npm install node-machine-id
import { app, ipcMain, safeStorage } from 'electron';
import { createPublicKey, verify } from 'node:crypto';
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
import { hostname } from 'node:os';
import { join } from 'node:path';
import machineId from 'node-machine-id';
const BASE = 'https://clavem.io';
const PUBLIC_KEY = 'kq1…your key…9fA'; // from your product page
const PRODUCT_ID = 75; // from your product page
const FILE = () => join(app.getPath('userData'), 'license.bin');
// Encrypted with the operating system's keychain through safeStorage. Check safeStorage.isEncryptionAvailable() first.
const load = () => {
try {
return JSON.parse(safeStorage.decryptString(readFileSync(FILE())));
} catch {
return null;
}
};
const save = (license) => writeFileSync(FILE(), safeStorage.encryptString(JSON.stringify(license)));
const clear = () => rmSync(FILE(), { force: true });
// The same checks as the offline verification page, with node:crypto so older Electron versions work too.
function verifyToken(token) {
const [prefix, body, signature, extra] = token.split('.');
if (prefix !== 'sgt1' || !body || !signature || extra !== undefined) return null;
try {
const key = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: PUBLIC_KEY }, format: 'jwk' });
if (!verify(null, Buffer.from(prefix + '.' + body), key, Buffer.from(signature, 'base64url'))) return null;
return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
} catch {
return null;
}
}
function isLicensed(claims) {
const now = Date.now() / 1000;
return (
claims !== null &&
claims.v === 1 &&
claims.pid === PRODUCT_ID &&
claims.valid === true &&
(claims.exp === undefined || claims.exp > now) &&
claims.refresh_by > now
);
}
async function call(action, body) {
const res = await fetch(BASE + '/v1/licenses/' + action, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(8000),
});
return { status: res.status, body: await res.json() };
}
async function activate(licenseKey) {
const { body } = await call('activate', {
license_key: licenseKey,
instance_name: hostname(),
fingerprint: machineId.machineIdSync(), // already a SHA-256 hash of the machine id
});
if (!body.activated) throw new Error(body.error);
save({ licenseKey, instanceId: body.instance.id, token: body.token });
}
// Returns 'licensed', 'invalid', 'needs-network' or 'unlicensed'.
async function check() {
const saved = load();
if (!saved) return 'unlicensed';
try {
const { status, body } = await call('validate', { license_key: saved.licenseKey, instance_id: saved.instanceId });
if (status === 200) {
save({ ...saved, token: body.token }); // also when invalid: offline, the token then says so
return body.valid ? 'licensed' : 'invalid';
}
if (status === 404) {
clear(); // unknown key, or this device was removed: ask for the key again
return 'invalid';
}
} catch {
// No network.
}
// Offline, rate limited or the service is down: trust the stored token while it is fresh.
return isLicensed(verifyToken(saved.token)) ? 'licensed' : 'needs-network';
}
async function deactivate() {
const saved = load();
if (!saved) return;
await call('deactivate', { license_key: saved.licenseKey, instance_id: saved.instanceId }).catch(() => {});
clear();
}
ipcMain.handle('license:activate', (_event, key) => activate(key));
ipcMain.handle('license:check', () => check());
ipcMain.handle('license:deactivate', () => deactivate());node-machine-id supplies the fingerprint. Without it, leave fingerprint out: activation still works, but re-installing on the same machine uses another seat until the customer removes the old one.
Tauri and Rust
Uses reqwest for the calls, ed25519-dalek for verification and the keyring crate for the operating system's credential store. The commands are registered with Tauri and called from your front end.
# src-tauri/Cargo.toml
[dependencies]
base64 = "0.22"
ed25519-dalek = "2"
hostname = "0.4"
keyring = { version = "3", features = ["apple-native", "windows-native", "sync-secret-service"] }
reqwest = { version = "0.12", features = ["json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tauri = "2"// src-tauri/src/license.rs
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use ed25519_dalek::{Signature, VerifyingKey};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const BASE: &str = "https://clavem.io";
const PUBLIC_KEY: &str = "kq1…your key…9fA"; // from your product page
const PRODUCT_ID: u64 = 75; // from your product page
#[derive(Serialize, Deserialize)]
struct Saved {
key: String,
instance_id: String,
token: String,
}
#[derive(Deserialize)]
struct Claims {
v: u8,
pid: u64,
valid: bool,
exp: Option<i64>,
refresh_by: i64,
}
// The same checks as the offline verification page.
fn verify_token(token: &str) -> Option<Claims> {
let mut parts = token.split('.');
let (prefix, body, signature) = (parts.next()?, parts.next()?, parts.next()?);
if prefix != "sgt1" || parts.next().is_some() {
return None;
}
let key_bytes: [u8; 32] = URL_SAFE_NO_PAD.decode(PUBLIC_KEY).ok()?.try_into().ok()?;
let sig_bytes: [u8; 64] = URL_SAFE_NO_PAD.decode(signature).ok()?.try_into().ok()?;
let key = VerifyingKey::from_bytes(&key_bytes).ok()?;
let signed = format!("{prefix}.{body}");
key.verify_strict(signed.as_bytes(), &Signature::from_bytes(&sig_bytes)).ok()?;
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(body).ok()?).ok()
}
fn is_licensed(claims: Option<&Claims>) -> bool {
let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
claims.map_or(false, |c| {
c.v == 1 && c.pid == PRODUCT_ID && c.valid && c.exp.map_or(true, |e| e > now) && c.refresh_by > now
})
}
// Stored in the operating system's credential store.
fn entry() -> Result<keyring::Entry, String> {
keyring::Entry::new("com.example.inkwell", "license").map_err(|e| e.to_string())
}
fn load() -> Option<Saved> {
serde_json::from_str(&entry().ok()?.get_password().ok()?).ok()
}
fn save(saved: &Saved) -> Result<(), String> {
let text = serde_json::to_string(saved).map_err(|e| e.to_string())?;
entry()?.set_password(&text).map_err(|e| e.to_string())
}
fn clear() {
if let Ok(entry) = entry() {
let _ = entry.delete_credential();
}
}
async fn post(action: &str, body: Value) -> Result<(u16, Value), reqwest::Error> {
let res = reqwest::Client::new()
.post(format!("{BASE}/v1/licenses/{action}"))
.timeout(Duration::from_secs(8))
.json(&body)
.send()
.await?;
let status = res.status().as_u16();
Ok((status, res.json::<Value>().await.unwrap_or(Value::Null)))
}
/// Once per device, when the customer enters their key.
#[tauri::command]
pub async fn activate_license(key: String) -> Result<(), String> {
let name = hostname::get().map(|h| h.to_string_lossy().into_owned()).unwrap_or_else(|_| "Device".into());
let (_, reply) = post("activate", json!({ "license_key": key, "instance_name": name }))
.await
.map_err(|e| e.to_string())?;
if reply["activated"] != true {
return Err(reply["error"].as_str().unwrap_or("Activation failed.").to_string());
}
save(&Saved {
key,
instance_id: reply["instance"]["id"].as_str().unwrap_or_default().to_string(),
token: reply["token"].as_str().unwrap_or_default().to_string(),
})
}
/// At every launch. Returns "licensed", "invalid", "needs-network" or "unlicensed".
#[tauri::command]
pub async fn check_license() -> String {
let Some(mut saved) = load() else { return "unlicensed".into() };
let body = json!({ "license_key": saved.key, "instance_id": saved.instance_id });
if let Ok((status, reply)) = post("validate", body).await {
if status == 200 {
// Keep the new token even when the license is not valid: offline, it then says so.
if let Some(token) = reply["token"].as_str() {
saved.token = token.to_string();
let _ = save(&saved);
}
return if reply["valid"] == true { "licensed" } else { "invalid" }.into();
}
if status == 404 {
clear(); // unknown key, or this device was removed: ask for the key again
return "invalid".into();
}
}
// Offline, rate limited or the service is down: trust the stored token while it is fresh.
if is_licensed(verify_token(&saved.token).as_ref()) { "licensed" } else { "needs-network" }.into()
}
/// When the customer moves the license to another machine.
#[tauri::command]
pub async fn deactivate_license() {
if let Some(saved) = load() {
let _ = post("deactivate", json!({ "license_key": saved.key, "instance_id": saved.instance_id })).await;
clear();
}
}// src-tauri/src/main.rs
mod license;
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
license::activate_license,
license::check_license,
license::deactivate_license
])
.run(tauri::generate_context!())
.expect("error while running the application");
}import { invoke } from '@tauri-apps/api/core';
const state = await invoke('check_license'); // 'licensed' | 'invalid' | 'needs-network' | 'unlicensed'
await invoke('activate_license', { key: pastedKey }); // rejects with the server's messageTo use a fingerprint, add a stable device identifier such as the one the machine-uid crate provides, hash it, and send it as fingerprint.
WordPress and PHP
Licenses a plugin per site. The site's URL is the instance name, so the customer recognizes it on the device page. Validation runs at most once a day, using a transient, and the stored token covers the rest. Verification uses the sodium functions from the offline verification page, which WordPress provides on every supported PHP version.
<?php
/**
* Plugin Name: Inkwell Pro
*/
const INKWELL_BASE = 'https://clavem.io';
const INKWELL_PUBLIC_KEY = 'kq1…your key…9fA'; // from your product page
const INKWELL_PRODUCT_ID = 75; // from your product page
const INKWELL_PLUGIN = 'inkwell-pro/inkwell-pro.php';
// clavem_verify_token() and clavem_is_licensed() are on the offline verification page.
function inkwell_call(string $action, array $body): array {
$res = wp_remote_post(INKWELL_BASE . '/v1/licenses/' . $action, [
'timeout' => 8,
'headers' => ['Content-Type' => 'application/json'],
'body' => wp_json_encode($body),
]);
if (is_wp_error($res)) {
return ['status' => 0, 'body' => []];
}
return [
'status' => wp_remote_retrieve_response_code($res),
'body' => json_decode(wp_remote_retrieve_body($res), true) ?: [],
];
}
/** Call this when the customer saves their key on your settings screen. Returns true or a WP_Error. */
function inkwell_activate(string $key) {
$r = inkwell_call('activate', [
'license_key' => $key,
'instance_name' => home_url(),
'fingerprint' => hash('sha256', home_url()),
]);
if (empty($r['body']['activated'])) {
return new WP_Error('inkwell_license', $r['body']['error'] ?? 'Could not reach the license server.');
}
update_option('inkwell_license', [
'key' => $key,
'instance' => $r['body']['instance']['id'],
'token' => $r['body']['token'],
], false);
return true;
}
/** Validates online at most once a day, and falls back to the stored token when there is no answer. */
function inkwell_is_licensed(): bool {
$saved = get_option('inkwell_license');
if (!is_array($saved)) {
return false;
}
if (false === get_transient('inkwell_checked')) {
$r = inkwell_call('validate', ['license_key' => $saved['key'], 'instance_id' => $saved['instance']]);
if ($r['status'] === 200) {
// Keep the new token even when the license is not valid: offline, it then says so.
$saved['token'] = $r['body']['token'];
update_option('inkwell_license', $saved, false);
set_transient('inkwell_checked', 1, !empty($r['body']['valid']) ? DAY_IN_SECONDS : HOUR_IN_SECONDS);
} elseif ($r['status'] === 404) {
delete_option('inkwell_license'); // unknown key, or this site was removed: ask for the key again
return false;
}
// Any other result means no answer: use the stored token below.
}
$claims = clavem_verify_token($saved['token'], INKWELL_PUBLIC_KEY);
return clavem_is_licensed($claims, INKWELL_PRODUCT_ID);
}
/** Call this when the customer removes the key, so the seat is free for another site. */
function inkwell_deactivate(): void {
$saved = get_option('inkwell_license');
if (is_array($saved)) {
inkwell_call('deactivate', ['license_key' => $saved['key'], 'instance_id' => $saved['instance']]);
delete_option('inkwell_license');
}
}
function inkwell_latest_release(): ?array {
$saved = get_option('inkwell_license');
$res = wp_remote_get(
add_query_arg(['license_key' => $saved['key'] ?? '', 'platform' => 'wordpress'], INKWELL_BASE . '/v1/releases/' . INKWELL_PRODUCT_ID . '/latest'),
['timeout' => 8]
);
if (is_wp_error($res) || wp_remote_retrieve_response_code($res) !== 200) {
return null;
}
return json_decode(wp_remote_retrieve_body($res), true) ?: null;
}
// Updates. WordPress keeps update data for up to 12 hours and download links last one hour, so the
// check hands WordPress a placeholder, and the real link is requested when the customer clicks Update.
add_filter('pre_set_site_transient_update_plugins', function ($transient) {
$latest = empty($transient->checked) ? null : inkwell_latest_release();
if ($latest && version_compare($latest['version'], $transient->checked[INKWELL_PLUGIN] ?? '0', '>')) {
$transient->response[INKWELL_PLUGIN] = (object) [
'slug' => 'inkwell-pro',
'plugin' => INKWELL_PLUGIN,
'new_version' => $latest['version'],
'package' => 'inkwell:latest',
];
}
return $transient;
});
add_filter('upgrader_pre_download', function ($reply, $package) {
if ($package !== 'inkwell:latest') {
return $reply;
}
$url = (inkwell_latest_release()['files'][0]['url'] ?? null);
return $url ? download_url($url) : new WP_Error('inkwell_download', 'Your license does not allow this download.');
}, 10, 2);The update filters keep working while a license is valid. Without a valid key, the release endpoint still reports the new version, but gives no download link, so the second filter refuses the download with a message. See update checks for what the endpoint returns.
Python
Uses only the standard library for HTTP, keyring for storage and PyNaCl through the verification code, saved here as license_token.py. For a command-line tool or a desktop app on Python 3.10 or later.
# pip install keyring pynacl
import hashlib
import json
import platform
import urllib.error
import urllib.request
import keyring
# verify_token() and is_licensed() are on the offline verification page.
from license_token import is_licensed, verify_token
BASE = "https://clavem.io"
PUBLIC_KEY = "kq1…your key…9fA" # from your product page
PRODUCT_ID = 75 # from your product page
SERVICE = "com.example.inkwell"
def call(action: str, body: dict) -> tuple[int, dict]:
request = urllib.request.Request(
f"{BASE}/v1/licenses/{action}",
data=json.dumps(body).encode(),
# Send your own User-Agent: some networks block the default Python one.
headers={"Content-Type": "application/json", "User-Agent": "Inkwell/3.2"},
)
try:
with urllib.request.urlopen(request, timeout=8) as response:
return response.status, json.load(response)
except urllib.error.HTTPError as error: # 4xx and 5xx still carry a JSON body
try:
return error.code, json.load(error)
except ValueError:
return error.code, {}
# Stored in the operating system's keychain.
def load() -> dict | None:
stored = keyring.get_password(SERVICE, "license")
return json.loads(stored) if stored else None
def save(license: dict) -> None:
keyring.set_password(SERVICE, "license", json.dumps(license))
def clear() -> None:
try:
keyring.delete_password(SERVICE, "license")
except keyring.errors.PasswordDeleteError:
pass
def activate(key: str) -> None:
"""Once per device, when the customer enters their key."""
_, reply = call("activate", {"license_key": key, "instance_name": platform.node() or "Computer"})
if not reply.get("activated"):
raise RuntimeError(reply.get("error", "Activation failed."))
save({"key": key, "instance_id": reply["instance"]["id"], "token": reply["token"]})
def check() -> str:
"""At every launch. Returns 'licensed', 'invalid', 'needs-network' or 'unlicensed'."""
saved = load()
if saved is None:
return "unlicensed"
try:
status, reply = call("validate", {"license_key": saved["key"], "instance_id": saved["instance_id"]})
except (OSError, ValueError): # no network, DNS failure, timeout or a reply that is not JSON
status, reply = 0, {}
if status == 200:
# Keep the new token even when the license is not valid: offline, it then says so.
save({**saved, "token": reply["token"]})
return "licensed" if reply["valid"] else "invalid"
if status == 404:
clear() # unknown key, or this device was removed: ask for the key again
return "invalid"
# Offline, rate limited or the service is down: trust the stored token while it is fresh.
claims = verify_token(saved["token"], PUBLIC_KEY)
return "licensed" if is_licensed(claims, PRODUCT_ID) else "needs-network"
def deactivate() -> None:
"""When the customer moves the license to another machine."""
saved = load()
if saved:
try:
call("deactivate", {"license_key": saved["key"], "instance_id": saved["instance_id"]})
except (OSError, ValueError):
pass
clear()The sample sends no fingerprint. Python has no portable stable machine identifier. If you have one, hash it and add it as fingerprint to the activation call.