Token format
A token is three parts joined by dots: sgt1, the payload and the signature. The payload is a JSON object encoded as base64url without padding. The signature is an Ed25519 signature over the ASCII text sgt1.<payload>, that is, the first two parts exactly as received, joined by the dot. The signature is also base64url without padding and is 64 bytes long.
sgt1.eyJ2IjoxLCJsaWQiOjMwNSwicGlkIjo3NSwi….HPo9sIcspSAVQsysSy42PrJY…
sgt1 prefix and format version
eyJ2IjoxLCJsaWQiOjMwNSwi… payload: base64url of a JSON object
HPo9sIcspSAVQsysSy42PrJY… signature: base64url of 64 bytesEach product has its own Ed25519 key pair. Clavem signs with the private half and never shares it. You verify with the public half: 32 raw bytes, base64url encoded. Find it on the product page in the dashboard, or as public_key in GET /v1/admin/products. It is not a secret, and shipping it in your app is the intended use.
A token signed for one product does not verify against the public key of another. Check pid as well, so a token from your other product cannot unlock this one.
An example from the demo license
This is the payload of a real token, returned by the demo license that backs the homepage. Fetch your own with the command below and decode the middle part.
curl https://clavem.io/v1/licenses/validate \
-d license_key="S1GNE-TDEM0-7K4QX-9WZ2P-H5RB8"{
"v": 1,
"lid": 305,
"pid": 75,
"kh": "7e0e4148136b6dae",
"status": "active",
"valid": true,
"email": "ada@example.com",
"iat": 1795043490,
"refresh_by": 1796253090
}Payload fields
The payload is signed, not encrypted. Anyone who holds the token can read it, including the buyer's email address. Do not send tokens to third parties.
| Field | Type | Meaning |
|---|---|---|
v | number | Token format version. Always 1 today. Reject any other value. |
lid | number | Clavem's id for the license. For an imported license this is not the Lemon Squeezy id. |
pid | number | Clavem's id for the product. The same number the releases endpoint takes and the products list returns. |
kh | string | The first 16 hex characters of the SHA-256 of the normalized license key. Lets your app confirm a token belongs to the key the customer typed. See the JavaScript example. |
status | string | active, inactive, expired or disabled, as of the moment the token was issued. See the status model. |
valid | boolean | true when status is active or inactive. Tokens are also issued for expired and disabled licenses, with valid set to false. |
iid | string, optional | The activation instance id, when the request named one. Present on every activate response, and on validate when you send instance_id. |
fp | string, optional | The device fingerprint given at activation. Absent when the activation had none. |
email | string, optional | The buyer's email address. |
iat | number | When the token was issued, in seconds since the Unix epoch. |
exp | number, optional | When the license expires, in seconds since the Unix epoch. Absent for perpetual licenses. For subscriptions this includes the three days of grace after the paid period. |
refresh_by | number | The time after which your app should validate online again: iat plus 14 days. |
How to verify
- Split the token on dots. There must be exactly three parts and the first must be
sgt1. - Decode the public key and the signature from base64url.
- Verify the signature over the bytes of
parts[0] + "." + parts[1]. If it fails, the token is not from Clavem or was changed. Stop. - Decode the payload and parse the JSON.
- Check
vis1,pidis your product, andvalidistrue. - If
expis present, check it is in the future. - Compare
refresh_bywith the current time. Before it, trust the token. After it, ask the server again (see the launch-time flow).
The examples below do steps 1 to 6 and leave step 7 to the caller through refresh_by. The JavaScript and Swift examples were run against tokens signed by Clavem's own signing code. The Rust, PHP and Python examples were written from the libraries' documentation and have not been run.
JavaScript
Ed25519 is part of Web Crypto in current browsers, Electron 37 and later, Node 20 and later, Deno, Bun and Cloudflare Workers. In older Electron or Node versions, use the node:crypto variant in the Electron guide.
// Web Crypto: browsers, Electron, Node 20 and later, Deno, Bun and Cloudflare Workers.
// publicKey is the product's public key from your dashboard. It is safe to ship in your app.
const bytes = (b64url) =>
Uint8Array.from(atob(b64url.replaceAll('-', '+').replaceAll('_', '/')), (c) => c.charCodeAt(0));
export async function verifyToken(token, publicKey) {
const parts = token.split('.');
if (parts.length !== 3 || parts[0] !== 'sgt1') return null;
try {
const key = await crypto.subtle.importKey('raw', bytes(publicKey), { name: 'Ed25519' }, false, ['verify']);
const signed = new TextEncoder().encode(parts[0] + '.' + parts[1]);
const ok = await crypto.subtle.verify({ name: 'Ed25519' }, key, bytes(parts[2]), signed);
if (!ok) return null;
return JSON.parse(new TextDecoder().decode(bytes(parts[1])));
} catch {
return null; // malformed token or key
}
}
// The checks your app should make on a verified token.
export function isLicensed(claims, productId, now = Date.now() / 1000) {
return (
claims !== null &&
claims.v === 1 &&
claims.pid === productId &&
claims.valid === true &&
(claims.exp === undefined || claims.exp > now) &&
claims.refresh_by > now
);
}
// Optional: confirm the token was issued for the key the customer typed.
export async function matchesKey(claims, licenseKey) {
const trimmed = licenseKey.trim();
const native = /^[0-9A-Za-z]{5}(?:-[0-9A-Za-z]{5}){4}$/.test(trimmed);
const normalized = native
? trimmed.toUpperCase().replace(/[IL]/g, '1').replace(/O/g, '0').replace(/U/g, 'V')
: trimmed.toLowerCase();
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(normalized));
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
return hex.slice(0, 16) === claims.kh;
}Swift
CryptoKit has verified Ed25519 signatures since macOS 10.15 and iOS 13.
import CryptoKit
import Foundation
struct LicenseClaims: Decodable {
let v: Int
let lid: Int
let pid: Int
let kh: String
let status: String
let valid: Bool
let iid: String?
let fp: String?
let email: String?
let iat: Int
let exp: Int?
let refresh_by: Int
}
extension Data {
/// Decodes unpadded base64url, the encoding Clavem uses everywhere.
init?(base64URLEncoded string: String) {
var s = string.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
s += String(repeating: "=", count: (4 - s.count % 4) % 4)
self.init(base64Encoded: s)
}
}
/// Returns the claims when the signature is valid, otherwise nil.
func verifyToken(_ token: String, publicKey: String) -> LicenseClaims? {
let parts = token.split(separator: ".", omittingEmptySubsequences: false)
guard parts.count == 3, parts[0] == "sgt1",
let keyBytes = Data(base64URLEncoded: publicKey),
let key = try? Curve25519.Signing.PublicKey(rawRepresentation: keyBytes),
let signature = Data(base64URLEncoded: String(parts[2])),
let body = Data(base64URLEncoded: String(parts[1]))
else { return nil }
let signed = Data((String(parts[0]) + "." + String(parts[1])).utf8)
guard key.isValidSignature(signature, for: signed) else { return nil }
return try? JSONDecoder().decode(LicenseClaims.self, from: body)
}
/// The checks your app should make on a verified token.
func isLicensed(_ claims: LicenseClaims?, productID: Int, now: Date = Date()) -> Bool {
guard let c = claims else { return false }
let t = Int(now.timeIntervalSince1970)
return c.v == 1 && c.pid == productID && c.valid && (c.exp ?? Int.max) > t && c.refresh_by > t
}Rust
verify_strict rejects some malleable signatures that plain verify accepts. Signatures from standard Ed25519 signers, Clavem's included, pass it, so the stricter check costs nothing.
// Cargo.toml
// ed25519-dalek = "2"
// base64 = "0.22"
// serde = { version = "1", features = ["derive"] }
// serde_json = "1"
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use ed25519_dalek::{Signature, VerifyingKey};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Claims {
pub v: u8,
pub lid: u64,
pub pid: u64,
pub kh: String,
pub status: String,
pub valid: bool,
pub iid: Option<String>,
pub fp: Option<String>,
pub email: Option<String>,
pub iat: i64,
pub exp: Option<i64>,
pub refresh_by: i64,
}
/// Returns the claims when the signature is valid, otherwise None.
pub fn verify_token(token: &str, public_key: &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()
}
/// The checks your app should make on a verified token. `now` is Unix seconds.
pub fn is_licensed(claims: Option<&Claims>, product_id: u64, now: i64) -> bool {
match claims {
Some(c) => {
c.v == 1
&& c.pid == product_id
&& c.valid
&& c.exp.map_or(true, |exp| exp > now)
&& c.refresh_by > now
}
None => false,
}
}PHP
<?php
// PHP 7.4 or later. The sodium extension ships with PHP, and WordPress provides it through sodium_compat.
/** Returns the decoded bytes, or false when the input is not valid base64url. */
function clavem_b64url_decode(string $value) {
$b64 = strtr($value, '-_', '+/');
return base64_decode($b64 . str_repeat('=', (4 - strlen($b64) % 4) % 4), true);
}
/** Returns the claims as an array when the signature is valid, otherwise null. */
function clavem_verify_token(string $token, string $publicKey): ?array {
$parts = explode('.', $token);
if (count($parts) !== 3 || $parts[0] !== 'sgt1') {
return null;
}
$key = clavem_b64url_decode($publicKey);
$signature = clavem_b64url_decode($parts[2]);
$body = clavem_b64url_decode($parts[1]);
if ($key === false || $signature === false || $body === false
|| strlen($key) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES
|| strlen($signature) !== SODIUM_CRYPTO_SIGN_BYTES) {
return null;
}
if (!sodium_crypto_sign_verify_detached($signature, $parts[0] . '.' . $parts[1], $key)) {
return null;
}
$claims = json_decode($body, true);
return is_array($claims) ? $claims : null;
}
/** The checks your app should make on a verified token. */
function clavem_is_licensed(?array $claims, int $productId, ?int $now = null): bool {
$now ??= time();
return $claims !== null
&& ($claims['v'] ?? null) === 1
&& ($claims['pid'] ?? null) === $productId
&& ($claims['valid'] ?? false) === true
&& (!isset($claims['exp']) || $claims['exp'] > $now)
&& ($claims['refresh_by'] ?? 0) > $now;
}Python
PyNaCl wraps libsodium. If you already depend on cryptography, replace the verify call with Ed25519PublicKey.from_public_bytes(...).verify(signature, message).
# pip install pynacl
from __future__ import annotations
import base64
import json
import time
from nacl.exceptions import BadSignatureError
from nacl.signing import VerifyKey
def _b64url_decode(value: str) -> bytes:
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
def verify_token(token: str, public_key: str) -> dict | None:
"""Returns the claims when the signature is valid, otherwise None."""
parts = token.split(".")
if len(parts) != 3 or parts[0] != "sgt1":
return None
try:
key = VerifyKey(_b64url_decode(public_key))
key.verify(f"{parts[0]}.{parts[1]}".encode(), _b64url_decode(parts[2]))
claims = json.loads(_b64url_decode(parts[1]))
except (BadSignatureError, ValueError):
return None # bad signature, malformed token or malformed key
return claims if isinstance(claims, dict) else None
def is_licensed(claims: dict | None, product_id: int, now: float | None = None) -> bool:
"""The checks your app should make on a verified token."""
now = time.time() if now is None else now
return (
claims is not None
and claims.get("v") == 1
and claims.get("pid") == product_id
and claims.get("valid") is True
and claims.get("exp", float("inf")) > now
and claims.get("refresh_by", 0) > now
)What a token cannot tell you
- Revocation after issue. A token says what the license looked like when it was signed. If you disable the license tomorrow, a token issued today still verifies until
refresh_by. That is the trade: the shorter you require re-validation, the sooner a revocation reaches a device that is offline, and the sooner an honest customer on a plane is asked to connect. Clavem sets the window to 14 days. - A clock set back. A customer can move the system clock back to keep a token fresh. If that matters, store the highest
iatyou have seen and treat a clock earlier than it as stale. - Who is holding it. A token is not bound to a device. If you want it to be, compare
iidorfpwith what your app stored at activation.
If Clavem were to disappear, tokens already on customers' machines stay valid until their refresh_by, and your app can keep trusting an expired window if you choose to. Export your licenses as CSV from the dashboard at any time.