Integrate Licentry
Use the session API to activate a licence, verify signed responses and bind the session to a device.
Start with the quickstart, then use the how-to guides for individual integration tasks. The reference covers endpoints, fields and limits. The explanation sections describe the threat model and the limits of each control.
Throughout these docs, BASE is your Licentry API origin: the endpoint issued to your account, or your own hostname if you are on a dedicated server with a custom domain. Never hardcode secrets in a shipped client.
Quickstart
The steps below cover activation, response verification, heartbeat, refresh and logout. Select a language above to change the examples. Check what your client needs before choosing libraries.
Required client checks
Invalid bodies, sequence numbers and expired tokens produce visible errors. Missing client-side checks may leave an integration vulnerable even when its normal requests succeed. Implement all six checks below.
1. Pin the signing key at build time. Store every key the JWKS returns in a kid to key map. Never fetch and trust a key at runtime: the machine's owner controls its DNS and trust store and could substitute their own key.
2. Reject unsigned responses. If X-Licentry-Sig is missing, stop without reading the body. An attacker can remove the header, and some server paths also return unsigned responses. A check such as if (response.has(SIG)) { check it } accepts those responses without verification. See verifying the server for the unsigned paths.
3. Verify the signature. Decode it as raw r||s and require exactly 64 bytes, not DER. Check the timestamp in both directions and select the key by kid. Verify the canonical string "status|ts|sha256hex(body)", not the body alone. Follow the full order in verifying the server.
4. Compare the clientNonce echo. Send a fresh random value on every call and reject a missing or different echo. The signature authenticates the response; the echo ties it to your request. Without that comparison, an attacker can reuse a captured signed 200.
5. Check the status after verification. A verified 403 is still a refusal. A helper that returns only the body can make if (verify(res)) run() accept a refusal as success. Verify first, branch on the status, then read fields. No catch-all branch may run licensed functionality.
6. Keep refusals generic. Do not infer a licence state in your UI, logs or exit codes, or vary retries by a guessed reason. Activate deliberately conceals those distinctions (why); the client must preserve that behaviour.
Use a stable device hash. The same machine must produce the same hash on every run.
A changed hash revokes the session, records a device mismatch for the sharing evidence view, emits an account event and returns 403 license_suspended. An unstable hash can therefore interrupt a legitimate customer and create misleading sharing evidence.
Derive the hash from stable identifiers and send identical lowercase hex on every call. Test across a reboot and changes to docks, drivers and power sources before shipping; repeated tests under the same conditions may miss the problem.
Send x-licentry-build on every session route, and send deviceHash on heartbeat and refresh as well as activate. Request bodies are strict: {"seq":1} alone returns 400 on every heartbeat.
1 · Activate a licence
Send the licence key plus a stable 64-hex device hash. You get back a short-lived session.
IDEM=$(openssl rand -hex 16) # 16 random bytes from a cryptographic source
CN=$(openssl rand -hex 8) # fresh per request, never reused
# Send the SAME Idempotency-Key on every retry of this attempt, and forget it
# once the call succeeds. A retry under a new key burns another device slot, and
# the default cap is one, so the customer is locked out of their own product.
CODE=$(curl -sS -D act.hdr -o act.json -w '%{http_code}' \
-X POST "$BASE/v1/sess/activate" \
-H "Content-Type: application/json" \
-H "x-licentry-build: $BUILD_TOKEN" \
-H "x-licentry-protocol: 1" \
-H "Idempotency-Key: $IDEM" \
-d "$(jq -cn --arg n "$CN" '{
licenseKey: "aB3xK9m-7Qp2n-M4kL8z-Xy1Wq9r",
deviceHash: "9f2c41d8b7a6e35c0d419b8a72e6c15d3f8074ba9e2d6c1785af30b9e4c26a71",
clientNonce: $n
}')")
# Use all 64 hex characters. A shorter device hash returns 400 Invalid request
# body without naming the field. Derive it from identifiers readable without
# elevation so ordinary and administrator runs produce the same value.
# A changed hash revokes the session with 403 license_suspended and records a
# hardware mismatch against the licence.
# licentry_accepted comes from the verify sample below. It refuses an unsigned
# response, a bad signature, a stale timestamp, a non-2xx status, and an echoed
# clientNonce that is not the one this call sent.
licentry_accepted "$CODE" act.hdr act.json "$CN" || exit 1
ACCESS_TOKEN=$(jq -r .accessToken act.json)
REFRESH_TOKEN=$(jq -r .refreshToken act.json)
SEQ=1; SERVER_NONCE="" # a new session starts its own nonce chain
#include <curl/curl.h>
static size_t sink(char* p, size_t sz, size_t n, void* o) {
static_cast<std::string*>(o)->append(p, sz * n);
return sz * n;
}
// hdrSink fills this through CURLOPT_HEADERFUNCTION. Missing X-Licentry-Sig
// leaves sig empty and must fail verification. This can happen when vendor
// response signing is enabled but the server cannot load the account key.
struct SigHdr { std::vector<uint8_t> sig; std::string ts, kid; };
static size_t hdrSink(char* p, size_t sz, size_t n, void* o);
// idemKey is the caller's: 16 random bytes from a cryptographic source, made
// once per activation attempt and passed in unchanged on every retry of that
// attempt, then dropped. A retry under a new key burns another device slot, and
// the default cap is one.
bool activate(const Cfg& cfg, const std::string& deviceHash,
const std::string& idemKey, Session& out) {
const std::string clientNonce = randomHex(8); // fresh per request
std::string body = R"({"licenseKey":")" + cfg.licenseKey +
R"(","deviceHash":")" + deviceHash +
R"(","clientNonce":")" + clientNonce + R"("})";
std::string resp;
SigHdr hdr;
curl_slist* h = curl_slist_append(nullptr, "Content-Type: application/json");
h = curl_slist_append(h, ("x-licentry-build: " + cfg.buildToken).c_str());
h = curl_slist_append(h, "x-licentry-protocol: 1");
h = curl_slist_append(h, ("Idempotency-Key: " + idemKey).c_str());
CURL* c = curl_easy_init();
curl_easy_setopt(c, CURLOPT_URL, (cfg.base + "/v1/sess/activate").c_str());
curl_easy_setopt(c, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, h);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, sink);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &resp);
curl_easy_setopt(c, CURLOPT_HEADERFUNCTION, hdrSink);
curl_easy_setopt(c, CURLOPT_HEADERDATA, &hdr);
curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(h);
curl_easy_cleanup(c);
// Gate on accepted, never on verifySig: a verified 403 is still a refusal.
if (!accepted(cfg.pinned(hdr.kid), (int)code, hdr.ts, resp, hdr.sig, time(nullptr)))
return false;
auto j = json::parse(resp, nullptr, false);
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
if (j.is_discarded() || j.value("clientNonce", "") != clientNonce) return false;
out.accessToken = j["accessToken"];
out.refreshToken = j["refreshToken"];
out.seq = 1;
out.serverNonce.clear(); // a new session starts its own nonce chain
return true;
}
using System.Net.Http.Json;
using System.Text.Json;
record Session(string accessToken, string refreshToken, string expiresAt,
string refreshExpiresAt, long revocationVersion, JsonElement product,
bool idempotent, string offlineGraceJwt, string clientNonce);
// idempotencyKey is the caller's: 16 random bytes from a cryptographic source,
// made once per activation attempt and passed in unchanged on every retry of
// that attempt, then dropped. A retry under a new key burns another device slot,
// and the default cap is one.
async Task<Session> Activate(HttpClient http, string licenseKey, string deviceHash,
string buildToken, string idempotencyKey,
IReadOnlyDictionary<string, ECDsa> pinned) {
// Generate a fresh nonce for each request and compare the signed echo to
// reject replayed responses.
var clientNonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(8));
var req = new HttpRequestMessage(HttpMethod.Post, "/v1/sess/activate") {
Content = JsonContent.Create(new { licenseKey, deviceHash, clientNonce })
};
req.Headers.Add("x-licentry-build", buildToken);
req.Headers.Add("x-licentry-protocol", "1");
req.Headers.Add("Idempotency-Key", idempotencyKey);
var res = await http.SendAsync(req);
var raw = await res.Content.ReadAsByteArrayAsync();
// Verify throws on a missing or bad signature, so this path fails closed.
// Then branch on the status it hands back: a verified 403 is still a refusal.
var v = Verify(res, raw, pinned);
if (v.Status != 201) throw new InvalidOperationException("activate refused");
var session = JsonSerializer.Deserialize<Session>(v.Body)!;
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
if (session.clientNonce != clientNonce) {
throw new InvalidOperationException("nonce echo mismatch");
}
return session;
}
import secrets
import requests
# idem_key belongs to the caller: secrets.token_hex(16), made once per activation
# attempt and passed in unchanged on every retry of that attempt, then dropped.
# A retry under a new key burns another device slot, and the default cap is one,
# so the value has to outlive this function.
def activate(base, build_token, license_key, device_hash, idem_key, pinned):
client_nonce = secrets.token_hex(8) # fresh per request, never reused
r = requests.post(
f"{base}/v1/sess/activate",
headers={
"Content-Type": "application/json",
"x-licentry-build": build_token,
"x-licentry-protocol": "1",
"Idempotency-Key": idem_key,
},
json={"licenseKey": license_key, "deviceHash": device_hash,
"clientNonce": client_nonce},
timeout=10,
)
# verify raises on a missing or bad signature, so this fails closed. Branch
# on the status it hands back: a verified 403 is still a refusal.
status, session = verify(r, pinned)
if status != 201:
raise RuntimeError("activate refused")
# Check the signed clientNonce echo before accepting engineParams or the
# offline grace token. A valid signature alone does not prevent replay.
if session.get("clientNonce") != client_nonce:
raise RuntimeError("nonce echo mismatch")
return session
import { randomBytes } from "node:crypto";
// idemKey belongs to the caller: randomBytes(16).toString("hex"), made once per
// activation attempt and passed in unchanged on every retry of that attempt,
// then dropped. A retry under a new key burns another device slot, and the
// default cap is one, so the value has to outlive this call.
export async function activate({ base, buildToken, licenseKey, deviceHash,
idemKey, pinned }) {
const clientNonce = randomBytes(8).toString("hex"); // fresh per request, never reused
const res = await fetch(`${base}/v1/sess/activate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-licentry-build": buildToken,
"x-licentry-protocol": "1",
"Idempotency-Key": idemKey,
},
body: JSON.stringify({ licenseKey, deviceHash, clientNonce }),
});
// verifySigned throws on a missing or bad signature, so this fails closed.
// Branch on the status it hands back: a verified 403 is still a refusal.
const { status, body } = await verifySigned(res, pinned);
if (status !== 201) throw new Error("activate refused");
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
if (body.clientNonce !== clientNonce) throw new Error("nonce echo mismatch");
return { ...body, seq: 1, serverNonce: "" };
}
type Session struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresAt string `json:"expiresAt"`
RefreshExpiresAt string `json:"refreshExpiresAt"`
RevocationVersion int64 `json:"revocationVersion"`
ClientNonce string `json:"clientNonce"`
}
// idemKey is the caller's: 16 random bytes, hex encoded, made once per
// activation attempt and passed in unchanged on every retry of that attempt,
// then dropped. A retry under a new key burns another device slot, and the
// default cap is one.
func Activate(base, build, key, deviceHash, idemKey string,
pinned map[string]*ecdsa.PublicKey) (*Session, error) {
cn := make([]byte, 8)
rand.Read(cn)
clientNonce := hex.EncodeToString(cn) // fresh per request, never reused
body, _ := json.Marshal(map[string]string{"licenseKey": key, "deviceHash": deviceHash,
"clientNonce": clientNonce})
req, _ := http.NewRequest("POST", base+"/v1/sess/activate", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-licentry-build", build)
req.Header.Set("x-licentry-protocol", "1")
req.Header.Set("Idempotency-Key", idemKey) // same key on every retry of this call
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
raw, err := io.ReadAll(res.Body) // the signature covers these exact bytes
if err != nil {
return nil, err
}
// Gate on Accepted, never on Verify: a verified 403 is still a refusal. A
// response carrying no X-Licentry-Sig fails here rather than slipping past.
if !Accepted(res, raw, pinned) {
return nil, fmt.Errorf("activate refused: %s", res.Status)
}
var s Session
if err := json.Unmarshal(raw, &s); err != nil {
return nil, err
}
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
if s.ClientNonce != clientNonce {
return nil, errors.New("nonce echo mismatch")
}
return &s, nil
}
use serde_json::{json, Value};
// idem is the caller's: 16 random bytes, hex encoded, made once per activation
// attempt and passed in unchanged on every retry of that attempt, then dropped.
// A retry under a new key burns another device slot, and the default cap is one.
pub async fn activate(base: &str, build: &str, key: &str, device_hash: &str,
idem: &str, pinned: &HashMap<String, VerifyingKey>)
-> anyhow::Result<Value> {
// Fresh per request, never reused.
let client_nonce: String = (0..16)
.map(|_| char::from_digit(rand::random::<u32>() % 16, 16).unwrap())
.collect();
let res = reqwest::Client::new()
.post(format!("{base}/v1/sess/activate"))
.header("Content-Type", "application/json")
.header("x-licentry-build", build)
.header("x-licentry-protocol", "1")
.header("Idempotency-Key", idem) // same value on every retry of this activate
.json(&json!({ "licenseKey": key, "deviceHash": device_hash,
"clientNonce": client_nonce }))
.send()
.await?;
let status = res.status().as_u16();
let headers = res.headers().clone();
let raw = res.bytes().await?; // the signature covers these exact bytes
// Reject unsigned responses, invalid signatures, stale timestamps and
// non-2xx statuses. Propagate the error rather than treating it as success.
verify(status, &headers, &raw, pinned)?;
let body: Value = serde_json::from_slice(&raw)?;
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
if body.get("clientNonce").and_then(Value::as_str) != Some(client_nonce.as_str()) {
anyhow::bail!("nonce echo mismatch");
}
Ok(body)
}
HttpClient http = HttpClient.newHttpClient();
// idempotencyKey belongs to the caller: 16 random bytes, hex encoded, made once
// per activation attempt and sent unchanged on every retry of that attempt, then
// dropped. A retry under a new key burns another device slot, and the default
// cap is one.
byte[] nonceBytes = new byte[8];
SecureRandom.getInstanceStrong().nextBytes(nonceBytes);
String clientNonce = HexFormat.of().formatHex(nonceBytes); // fresh per request
String body = mapper.writeValueAsString(
Map.of("licenseKey", licenseKey, "deviceHash", deviceHash,
"clientNonce", clientNonce));
HttpRequest req = HttpRequest.newBuilder(URI.create(base + "/v1/sess/activate"))
.header("Content-Type", "application/json")
.header("x-licentry-build", buildToken)
.header("x-licentry-protocol", "1")
.header("Idempotency-Key", idempotencyKey) // same value on every retry
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
// The signature covers the raw bytes, so ask for bytes rather than a String.
HttpResponse<byte[]> res = http.send(req, HttpResponse.BodyHandlers.ofByteArray());
// Gate on accepted, never on verify: a verified 403 is still a refusal, and a
// response carrying no X-Licentry-Sig fails here rather than slipping past.
if (!accepted(res, PINNED)) {
throw new IllegalStateException("activate refused: " + res.statusCode());
}
Session session = mapper.readValue(res.body(), Session.class);
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
if (!clientNonce.equals(session.clientNonce())) {
throw new IllegalStateException("nonce echo mismatch");
}
int seq = 1;
String serverNonce = ""; // a new session starts its own nonce chain
<?php
// $idemKey belongs to the caller: bin2hex(random_bytes(16)), made once per
// activation attempt and sent unchanged on every retry of that attempt, then
// dropped. A retry under a new key burns another device slot, and the default
// cap is one.
// Generate a fresh $clientNonce per request. Compare its signed echo to
// reject replayed responses.
$clientNonce = bin2hex(random_bytes(8));
$body = json_encode(['licenseKey' => $licenseKey, 'deviceHash' => $deviceHash,
'clientNonce' => $clientNonce]);
$ch = curl_init($base . '/v1/sess/activate');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'x-licentry-build: ' . $buildToken,
'x-licentry-protocol: 1',
'Idempotency-Key: ' . $idemKey, // same value on every retry of this activate
],
]);
$h = [];
collectHeaders($ch, $h); // from the verify sample
$res = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
// Gate on licentryAccepted, never on licentryVerify: a verified 403 is still a
// refusal, and an answer carrying no X-Licentry-Sig is refused here.
if (!licentryAccepted($code, $h, $res, $pinned)) {
throw new RuntimeException('activate refused');
}
$session = json_decode($res, true);
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
if (($session['clientNonce'] ?? null) !== $clientNonce) {
throw new RuntimeException('nonce echo mismatch');
}
struct Session: Decodable {
let accessToken: String, refreshToken: String
let expiresAt: String, refreshExpiresAt: String
let revocationVersion: Int
let clientNonce: String?
}
// idemKey belongs to the caller: 16 random bytes, hex encoded, made once per
// activation attempt and sent unchanged on every retry of that attempt, then
// dropped. A retry under a new key burns another device slot, and the default
// cap is one.
func activate(base: URL, build: String, key: String, deviceHash: String,
idemKey: String,
pinned: [String: P256.Signing.PublicKey]) async throws -> Session {
var req = URLRequest(url: base.appending(path: "v1/sess/activate"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue(build, forHTTPHeaderField: "x-licentry-build")
req.setValue("1", forHTTPHeaderField: "x-licentry-protocol")
req.setValue(idemKey, forHTTPHeaderField: "Idempotency-Key") // reuse on retry
var nonceBytes = [UInt8](repeating: 0, count: 8)
_ = SecRandomCopyBytes(kSecRandomDefault, nonceBytes.count, &nonceBytes)
let clientNonce = nonceBytes.map { String(format: "%02x", $0) }.joined()
req.httpBody = try JSONEncoder().encode(["licenseKey": key,
"deviceHash": deviceHash,
"clientNonce": clientNonce])
let (data, res) = try await URLSession.shared.data(for: req)
// Gate on accepted, never on verify: a verified 403 is still a refusal, and
// a response carrying no X-Licentry-Sig is refused inside rather than skipped.
guard let http = res as? HTTPURLResponse,
accepted(http, body: data, pinned: pinned) else {
throw LicentryError.activation("activate refused")
}
let session = try JSONDecoder().decode(Session.self, from: data)
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
guard session.clientNonce == clientNonce else {
throw LicentryError.activation("nonce echo mismatch")
}
return session
}
val JSON = "application/json".toMediaType()
// idemKey belongs to the caller: 16 random bytes, hex encoded, made once per
// activation attempt and sent unchanged on every retry of that attempt, then
// dropped. A retry under a new key burns another device slot, and the default
// cap is one.
fun activate(base: String, build: String, key: String, deviceHash: String,
idemKey: String, pinned: Map<String, PublicKey>): Session {
val clientNonce = ByteArray(8).also { SecureRandom().nextBytes(it) }
.joinToString("") { "%02x".format(it) } // fresh per request
val body = JSONObject()
.put("licenseKey", key)
.put("deviceHash", deviceHash)
.put("clientNonce", clientNonce)
.toString()
val req = Request.Builder()
.url("$base/v1/sess/activate")
.addHeader("x-licentry-build", build)
.addHeader("x-licentry-protocol", "1")
.addHeader("Idempotency-Key", idemKey) // same value on every retry
.post(body.toRequestBody(JSON))
.build()
client.newCall(req).execute().use { res ->
val raw = res.body!!.bytes() // the signature covers these exact bytes
// Gate on accepted, never on verify: a verified 403 is still a refusal,
// and an answer carrying no X-Licentry-Sig is refused inside it.
check(accepted(res, raw, pinned)) { "activate refused" }
val session = gson.fromJson(String(raw), Session::class.java)
// Check the signed clientNonce echo before accepting engineParams or the
// offline grace token. A valid signature alone does not prevent replay.
check(session.clientNonce == clientNonce) { "nonce echo mismatch" }
return session
}
}
require "json"
require "net/http"
require "securerandom"
# idem_key belongs to the caller: SecureRandom.hex(16), made once per activation
# attempt and passed in unchanged on every retry of that attempt, then dropped.
# A retry under a new key burns another device slot, and the default cap is one,
# so the value has to outlive this method.
def activate(base, build_token, license_key, device_hash, idem_key, pinned)
client_nonce = SecureRandom.hex(8) # fresh per request, never reused
uri = URI("#{base}/v1/sess/activate")
req = Net::HTTP::Post.new(uri)
req["Content-Type"] = "application/json"
req["x-licentry-build"] = build_token
req["x-licentry-protocol"] = "1"
req["Idempotency-Key"] = idem_key
req.body = JSON.generate(licenseKey: license_key, deviceHash: device_hash,
clientNonce: client_nonce)
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }
# verify! raises on a missing or bad signature, so this fails closed. Branch on
# the status it hands back: a verified 403 is still a refusal.
status, session = verify!(res, res.body, pinned)
raise "activate refused" unless status == 201
# Check the signed clientNonce echo before accepting engineParams or the
# offline grace token. A valid signature alone does not prevent replay.
raise "nonce echo mismatch" unless session["clientNonce"] == client_nonce
session
end
{
"accessToken": "9af2c1...",
"refreshToken": "b7d3e0...",
"expiresAt": "2026-07-24T12:20:00Z",
"refreshExpiresAt": "2026-08-07T12:00:00Z",
"revocationVersion": 3,
"product": "your-product",
"idempotent": false,
"offlineGraceJwt": "eyJhbGciOiJFUzI1NiI..."
}
2 · Verify the response signature
Every response on the session routes is signed with ECDSA P-256. Verify it against a pinned public key before you read any field. This is the check that rejects a spoofed or intercepted response.
X-Licentry-Sig: MEUCIQDr4k... # base64 raw r||s, 64 bytes
X-Licentry-Sig-Ts: 1753358400 # unix seconds
X-Licentry-Sig-Kid: rs1 # which pinned key verifies this
# canonical message you verify: "${status}|${ts}|${sha256hex(body)}"
# licentry_verify checks the signature, timestamp and nonce echo.
# licentry_accepted also requires a successful status. A verified 403 is a refusal.
# Both take: <status> <header file> <body file> <the clientNonce you sent>
licentry_verify() {
_code=$1; _hd=$2; _bd=$3; _cn=$4
hdr() { grep -i "^$1:" "$_hd" | tr -d '\r' | cut -d' ' -f2-; }
SIG=$(hdr X-Licentry-Sig); TS=$(hdr X-Licentry-Sig-Ts); KID=$(hdr X-Licentry-Sig-Kid)
# Reject a missing signature. The server may omit it when vendor response
# signing is enabled but the account key cannot be loaded.
[ -n "$SIG" ] && [ -n "$TS" ] && [ -n "$KID" ] \
|| { echo "unsigned response, refusing" >&2; return 1; }
# Check absolute clock skew. A one-sided "now - ts < 300" check accepts
# negative differences after a clock rollback, allowing old signatures.
SKEW=$(( $(date +%s) - TS )); [ "$SKEW" -lt 0 ] && SKEW=$(( -SKEW ))
[ "$SKEW" -le 300 ] || { echo "signature timestamp outside tolerance" >&2; return 1; }
DIGEST=$(openssl dgst -sha256 -r "$_bd" | cut -d' ' -f1)
printf '%s|%s|%s' "$_code" "$TS" "$DIGEST" > canon.txt
# the header is raw r||s, openssl dgst only reads DER, so wrap it before verifying
printf %s "$SIG" | base64 -d | p1363-to-der > sig.der
openssl dgst -sha256 -verify "keys/$KID.pem" -signature sig.der canon.txt \
|| { echo "rejecting response" >&2; return 1; }
# The nonce echo binds this signed response to the current request.
# Without it, a captured signed 200 could be replayed.
[ "$(jq -r .clientNonce "$_bd")" = "$_cn" ] \
|| { echo "nonce echo mismatch" >&2; return 1; }
}
# Use this function to decide whether the request succeeded. The server signs
# refusals too, and the status is part of the signed message.
licentry_accepted() {
licentry_verify "$@" || return 1
case "$1" in 2??) return 0 ;; esac
echo "server refused: HTTP $1" >&2
return 1
}
#include <openssl/ecdsa.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
// pinned is the key named by X-Licentry-Sig-Kid; rs is the raw 64 byte r||s.
// A response with no X-Licentry-Sig arrives here as an empty rs and fails the
// size check below: no header is a refusal, not a skip.
bool verifySig(EVP_PKEY* pinned, int status, const std::string& ts,
const std::string& body, const std::vector<uint8_t>& rs, long now) {
// Two-sided: a rewound wall clock must not widen the replay window.
if (rs.size() != 64 || std::labs(now - std::stol(ts)) > 300) return false;
unsigned char d[32];
SHA256(reinterpret_cast<const unsigned char*>(body.data()), body.size(), d);
char hex[65];
for (int i = 0; i < 32; i++) sprintf(hex + i * 2, "%02x", d[i]);
std::string msg = std::to_string(status) + "|" + ts + "|" + std::string(hex, 64);
ECDSA_SIG* sig = ECDSA_SIG_new();
ECDSA_SIG_set0(sig, BN_bin2bn(rs.data(), 32, nullptr),
BN_bin2bn(rs.data() + 32, 32, nullptr));
unsigned char* der = nullptr; // OpenSSL verifies DER, not P1363
int derLen = i2d_ECDSA_SIG(sig, &der);
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
EVP_DigestVerifyInit(ctx, nullptr, EVP_sha256(), nullptr, pinned);
bool ok = EVP_DigestVerify(ctx, der, derLen,
reinterpret_cast<const unsigned char*>(msg.data()),
msg.size()) == 1;
EVP_MD_CTX_free(ctx); OPENSSL_free(der); ECDSA_SIG_free(sig);
return ok;
}
// Use this instead of verifySig to check success as well as authenticity.
// A signed 403 license_suspended verifies but must not enable licensed work.
bool accepted(EVP_PKEY* pinned, int status, const std::string& ts,
const std::string& body, const std::vector<uint8_t>& rs, long now) {
if (!verifySig(pinned, status, ts, body, rs, now)) return false;
return status >= 200 && status < 300;
}
using System.Security.Cryptography;
using System.Text;
// pinned holds P-256 keys by kid; VerifyData reads the raw r||s, no DER wrapping
// Returns Status with the body so callers can distinguish success from a
// signed refusal such as 403 license_suspended. Check Status after verification.
readonly record struct Verified(int Status, byte[] Body);
static Verified Verify(HttpResponseMessage res, byte[] rawBody,
IReadOnlyDictionary<string, ECDsa> pinned) {
// Reject unsigned responses, including when the server cannot load the
// account's response-signing key. Do not skip verification for a missing header.
if (!res.Headers.TryGetValues("X-Licentry-Sig", out _))
throw new CryptographicException("unsigned response");
var ts = long.Parse(res.Headers.GetValues("X-Licentry-Sig-Ts").First());
// Two-sided: a rewound wall clock must not widen the replay window.
if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts) > 300)
throw new CryptographicException("stale signature");
var kid = res.Headers.GetValues("X-Licentry-Sig-Kid").First();
if (!pinned.TryGetValue(kid, out var key))
throw new CryptographicException("unknown kid");
var sig = Convert.FromBase64String(res.Headers.GetValues("X-Licentry-Sig").First());
if (sig.Length != 64) throw new CryptographicException("expected raw r||s");
var digest = Convert.ToHexString(SHA256.HashData(rawBody)).ToLowerInvariant();
var msg = Encoding.UTF8.GetBytes($"{(int)res.StatusCode}|{ts}|{digest}");
if (!key.VerifyData(msg, sig, HashAlgorithmName.SHA256,
DSASignatureFormat.IeeeP1363FixedFieldConcatenation))
throw new CryptographicException("bad signature");
return new Verified((int)res.StatusCode, rawBody);
}
import base64
import hashlib
import time
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, utils
def verify(resp, pinned): # pinned: kid -> EllipticCurvePublicKey
# Reject unsigned responses, including when the server cannot load the
# account's response-signing key. Do not skip verification for a missing header.
if "X-Licentry-Sig" not in resp.headers:
raise InvalidSignature("unsigned response")
ts = int(resp.headers["X-Licentry-Sig-Ts"])
key = pinned.get(resp.headers["X-Licentry-Sig-Kid"])
if key is None or abs(time.time() - ts) > 300:
raise InvalidSignature("unknown kid or stale timestamp")
raw = base64.b64decode(resp.headers["X-Licentry-Sig"])
if len(raw) != 64:
raise InvalidSignature("expected raw r||s")
der = utils.encode_dss_signature(int.from_bytes(raw[:32], "big"),
int.from_bytes(raw[32:], "big"))
digest = hashlib.sha256(resp.content).hexdigest()
msg = f"{resp.status_code}|{ts}|{digest}".encode()
key.verify(der, msg, ec.ECDSA(hashes.SHA256())) # raises, so callers fail closed
# Return the status with the body. A signed 403 license_suspended can have a
# truthy body, so callers must check the status rather than the returned dict.
return resp.status_code, resp.json()
import { webcrypto as crypto } from "node:crypto";
// pinned: kid -> CryptoKey imported as ECDSA P-256; WebCrypto wants the raw r||s
export async function verifySigned(res, pinned) {
const raw = Buffer.from(await res.arrayBuffer());
// Reject unsigned responses, including when the server cannot load the
// account's response-signing key. Do not skip verification for a missing header.
if (!res.headers.get("x-licentry-sig")) throw new Error("unsigned response");
const ts = Number(res.headers.get("x-licentry-sig-ts"));
const key = pinned.get(res.headers.get("x-licentry-sig-kid"));
if (!key || Math.abs(Date.now() / 1000 - ts) > 300) {
throw new Error("unknown kid or stale timestamp");
}
const sig = Buffer.from(res.headers.get("x-licentry-sig"), "base64");
const hash = await crypto.subtle.digest("SHA-256", raw);
const digest = Buffer.from(hash).toString("hex");
const msg = new TextEncoder().encode(`${res.status}|${ts}|${digest}`);
const ok = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" },
key, sig, msg);
if (!ok) throw new Error("bad signature"); // fail closed, never use the body
// Return the STATUS too. A verified 403 license_suspended is still a refusal:
// a helper that hands back only the body invites "if (await verify(res)) run()".
return { status: res.status, body: JSON.parse(raw.toString("utf8")) };
}
// the header carries raw r||s, so split it and hand the halves to ecdsa.Verify
func Verify(res *http.Response, body []byte, pinned map[string]*ecdsa.PublicKey) bool {
ts, err := strconv.ParseInt(res.Header.Get("X-Licentry-Sig-Ts"), 10, 64)
// Two-sided: a rewound wall clock must not widen the replay window.
skew := time.Now().Unix() - ts
if err != nil || skew > 300 || skew < -300 {
return false
}
pub, ok := pinned[res.Header.Get("X-Licentry-Sig-Kid")]
if !ok {
return false
}
// Reject unsigned responses, including when the server cannot load the
// account's response-signing key. Do not skip verification for a missing header.
sigHdr := res.Header.Get("X-Licentry-Sig")
if sigHdr == "" {
return false
}
sig, err := base64.StdEncoding.DecodeString(sigHdr)
if err != nil || len(sig) != 64 {
return false
}
sum := sha256.Sum256(body)
msg := fmt.Sprintf("%d|%d|%x", res.StatusCode, ts, sum)
digest := sha256.Sum256([]byte(msg))
r := new(big.Int).SetBytes(sig[:32])
s := new(big.Int).SetBytes(sig[32:])
return ecdsa.Verify(pub, digest[:], r, s) // false means drop the response
}
// Use Accepted to check success as well as authenticity. Verify alone also
// accepts a signed 403 license_suspended. The signature covers the status.
func Accepted(res *http.Response, body []byte, pinned map[string]*ecdsa.PublicKey) bool {
if !Verify(res, body, pinned) {
return false
}
return res.StatusCode >= 200 && res.StatusCode < 300
}
use p256::ecdsa::{signature::Verifier, Signature, VerifyingKey};
use sha2::{Digest, Sha256};
// Signature::from_slice takes the raw 64 byte r||s the header carries
pub fn verify(status: u16, headers: &HeaderMap, body: &[u8],
pinned: &HashMap<String, VerifyingKey>) -> Result<(), Error> {
// Use a fallible header lookup; indexing HeaderMap panics if it is absent.
// Reject missing X-Licentry-Sig, including when the server cannot load the
// account's response-signing key.
let sig_hdr = headers.get("x-licentry-sig").ok_or(Error::Unsigned)?;
let ts: i64 = headers.get("x-licentry-sig-ts").ok_or(Error::Unsigned)?
.to_str()?.parse()?;
if (Utc::now().timestamp() - ts).abs() > 300 {
return Err(Error::Stale);
}
let kid = headers.get("x-licentry-sig-kid").ok_or(Error::Unsigned)?.to_str()?;
let key = pinned.get(kid).ok_or(Error::UnknownKid)?;
let raw = BASE64.decode(sig_hdr.as_bytes())?;
let sig = Signature::from_slice(&raw)?;
let digest = hex::encode(Sha256::digest(body));
let msg = format!("{status}|{ts}|{digest}");
key.verify(msg.as_bytes(), &sig).map_err(|_| Error::BadSignature)?;
// Return an error for authenticated refusals such as 403 license_suspended.
// Ok(()) would let callers using ? treat them as success.
if !(200..300).contains(&status) {
return Err(Error::Refused(status));
}
Ok(())
}
// plain SHA256withECDSA parses DER; the P1363 variant takes the raw r||s directly
static boolean verify(HttpResponse<byte[]> res, Map<String, PublicKey> pinned)
throws Exception {
HttpHeaders h = res.headers();
// Reject unsigned responses, including when the server cannot load the
// account's response-signing key. Do not skip verification for a missing header.
if (h.firstValue("X-Licentry-Sig").isEmpty()
|| h.firstValue("X-Licentry-Sig-Ts").isEmpty()) return false;
long ts = Long.parseLong(h.firstValue("X-Licentry-Sig-Ts").orElseThrow());
// Two-sided: a rewound wall clock must not widen the replay window.
if (Math.abs(Instant.now().getEpochSecond() - ts) > 300) return false;
PublicKey key = pinned.get(h.firstValue("X-Licentry-Sig-Kid").orElse(""));
if (key == null) return false;
byte[] rs = Base64.getDecoder()
.decode(h.firstValue("X-Licentry-Sig").orElseThrow());
if (rs.length != 64) return false;
String digest = HexFormat.of().formatHex(
MessageDigest.getInstance("SHA-256").digest(res.body()));
String msg = res.statusCode() + "|" + ts + "|" + digest;
Signature v = Signature.getInstance("SHA256withECDSAinP1363Format");
v.initVerify(key);
v.update(msg.getBytes(StandardCharsets.UTF_8));
return v.verify(rs); // a false here must reject the response
}
// Use this to check success as well as authenticity. verify() also accepts
// a signed 403 license_suspended. The signature protects the status in transit.
static boolean accepted(HttpResponse<byte[]> res, Map<String, PublicKey> pinned)
throws Exception {
if (!verify(res, pinned)) return false;
return res.statusCode() >= 200 && res.statusCode() < 300;
}
<?php
// Call this before curl_exec to capture the response headers, lowercased.
function collectHeaders($ch, array &$h): void
{
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $line) use (&$h) {
$p = explode(':', $line, 2);
if (count($p) === 2) {
$h[strtolower(trim($p[0]))] = trim($p[1]);
}
return strlen($line);
});
}
// openssl_verify parses DER, the header is raw r||s, so wrap it first
function licentryVerify(int $status, array $h, string $body, array $pinned): bool
{
// Reject unsigned responses, including when the server cannot load the
// account's response-signing key. Do not skip verification for a missing header.
if (!isset($h['x-licentry-sig'], $h['x-licentry-sig-ts'], $h['x-licentry-sig-kid'])) {
return false;
}
$ts = (int) $h['x-licentry-sig-ts'];
if (abs(time() - $ts) > 300) {
return false;
}
$pem = $pinned[$h['x-licentry-sig-kid']] ?? null;
if ($pem === null) {
return false;
}
$rs = base64_decode($h['x-licentry-sig'], true);
if ($rs === false || strlen($rs) !== 64) {
return false;
}
$der = derFromP1363($rs);
$msg = $status . '|' . $ts . '|' . hash('sha256', $body);
return openssl_verify($msg, $der, $pem, OPENSSL_ALGO_SHA256) === 1;
}
// Use this instead of licentryVerify to check success as well as authenticity.
// A signed 403 license_suspended verifies but remains a refusal.
// The signature covers the status.
function licentryAccepted(int $status, array $h, string $body, array $pinned): bool
{
if (!licentryVerify($status, $h, $body, $pinned)) {
return false;
}
return $status >= 200 && $status < 300;
}
import CryptoKit
// ECDSASignature(rawRepresentation:) is exactly the r||s the header carries
func verify(_ res: HTTPURLResponse, body: Data,
pinned: [String: P256.Signing.PublicKey]) -> Bool {
func h(_ n: String) -> String? { res.value(forHTTPHeaderField: n) }
guard let tsText = h("X-Licentry-Sig-Ts"), let ts = TimeInterval(tsText),
let kid = h("X-Licentry-Sig-Kid"), let key = pinned[kid],
let sigText = h("X-Licentry-Sig"),
let raw = Data(base64Encoded: sigText), raw.count == 64,
abs(Date().timeIntervalSince1970 - ts) <= 300,
let sig = try? P256.Signing.ECDSASignature(rawRepresentation: raw)
// A missing header returns false. The server may omit the signature when
// vendor response signing is enabled but the account key cannot be loaded.
else { return false }
let digest = SHA256.hash(data: body).map { String(format: "%02x", $0) }.joined()
let msg = Data("\(res.statusCode)|\(Int(ts))|\(digest)".utf8)
return key.isValidSignature(sig, for: msg)
}
// Use this to check success as well as authenticity. verify also accepts
// a signed 403 license_suspended. The signature covers the status.
func accepted(_ res: HTTPURLResponse, body: Data,
pinned: [String: P256.Signing.PublicKey]) -> Bool {
guard verify(res, body: body, pinned: pinned) else { return false }
return (200..<300).contains(res.statusCode)
}
// SHA256withECDSA would want DER; the P1363 name verifies the raw r||s as sent
fun verify(res: Response, body: ByteArray, pinned: Map<String, PublicKey>): Boolean {
val ts = res.header("X-Licentry-Sig-Ts")?.toLongOrNull() ?: return false
// Two-sided: a rewound wall clock must not widen the replay window.
if (abs(Instant.now().epochSecond - ts) > 300) return false
val key = pinned[res.header("X-Licentry-Sig-Kid")] ?: return false
// Reject unsigned responses, including when the server cannot load the
// account's response-signing key. Do not skip verification for a missing header.
val sigHdr = res.header("X-Licentry-Sig") ?: return false
val rs = Base64.getDecoder().decode(sigHdr)
if (rs.size != 64) return false
val digest = MessageDigest.getInstance("SHA-256").digest(body)
.joinToString("") { "%02x".format(it) }
val msg = listOf(res.code, ts, digest).joinToString("|")
val v = Signature.getInstance("SHA256withECDSAinP1363Format")
v.initVerify(key)
v.update(msg.toByteArray())
return v.verify(rs) // false means drop the response
}
// Use this to check success as well as authenticity. verify also accepts
// a signed 403 license_suspended. The signature protects the status in transit.
fun accepted(res: Response, body: ByteArray, pinned: Map<String, PublicKey>): Boolean {
if (!verify(res, body, pinned)) return false
return res.code in 200..299
}
require "openssl"
# the header is raw r||s, OpenSSL verifies DER, so rebuild the ASN.1 sequence
def verify!(res, body, pinned)
# Reject unsigned responses, including when the server cannot load the
# account's response-signing key. Do not skip verification for a missing header.
raise "unsigned response" if res["X-Licentry-Sig"].nil?
ts = res["X-Licentry-Sig-Ts"].to_i
raise "stale signature" if (Time.now.to_i - ts).abs > 300
key = pinned.fetch(res["X-Licentry-Sig-Kid"])
rs = res["X-Licentry-Sig"].unpack1("m")
raise "expected raw r||s" unless rs.bytesize == 64
r = OpenSSL::BN.new(rs[0, 32].unpack1("H*"), 16)
s = OpenSSL::BN.new(rs[32, 32].unpack1("H*"), 16)
der = OpenSSL::ASN1::Sequence.new([OpenSSL::ASN1::Integer.new(r),
OpenSSL::ASN1::Integer.new(s)]).to_der
msg = "#{res.code}|#{ts}|#{OpenSSL::Digest::SHA256.hexdigest(body)}"
raise "signature rejected" unless key.verify(OpenSSL::Digest.new("SHA256"), der, msg)
# Return the status with the body so callers can distinguish success from
# a signed refusal such as 403 license_suspended. The signature covers the
# status; check it after verification.
[res.code.to_i, JSON.parse(body)]
end
3 · Heartbeat on a timer
Before expiresAt, send a heartbeat with a strictly increasing sequence number. The first heartbeat after activate is always seq: 1, and each 200 returns the new expiresAt to schedule the next beat from.
# activate, refresh_session and stop_licensed_work are your own functions: the
# first two are the samples above, and each returns non-zero when refused.
SEQ=1 # back to 1 after activate and after every refresh
SERVER_NONCE="" # empty on the first beat, then whatever the server last sent
REACTIVATED=0
while :; do
CN=$(openssl rand -hex 8) # fresh every request, never reused
REQ=$(printf '{"seq":%d,"deviceHash":"%s","serverNonce":"%s","clientNonce":"%s"}' \
"$SEQ" "$DEVICE_HASH" "$SERVER_NONCE" "$CN")
CODE=$(curl -sS -D beat.hdr -o beat.json -w '%{http_code}' \
-X POST "$BASE/v1/sess/heartbeat" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "x-licentry-build: $BUILD_TOKEN" \
-H "x-licentry-protocol: 1" \
-d "$REQ")
# 429 and 5xx decide nothing about the licence and need not come from the app
# at all, so they are handled before verification. Back off and resend the
# IDENTICAL body: same SEQ, same SERVER_NONCE, same request.
case "$CODE" in 429|5??) sleep 30; continue ;; esac
# Everything below decides whether the product keeps running, so verify it
# before reading a single field out of the body.
licentry_verify "$CODE" beat.hdr beat.json "$CN" || exit 1
ERR=$(jq -r '.error // ""' beat.json)
case "$CODE" in
200) ;;
403|426) echo "terminal: $ERR" >&2; exit 1 ;; # killed, suspended, build retired
409) refresh_session || exit 1; SEQ=1; continue ;; # the nonce chain carries over
401)
case "$ERR" in
invalid_session) # evicted or gone. Activate ONCE, after a backoff.
[ "$REACTIVATED" = 1 ] && { echo "activation did not hold" >&2; exit 1; }
REACTIVATED=1; sleep 5
activate || exit 1; SEQ=1; SERVER_NONCE=""; continue ;;
expired) # refresh; activate only if the refresh is refused too
refresh_session || { activate || exit 1; SERVER_NONCE=""; }
SEQ=1; continue ;;
revoked) # terminal. Stop, and point the user at their seller.
echo "licence revoked" >&2; exit 1 ;;
stale_revocation) # stop the licensed work first, then honour the answer
stop_licensed_work
activate || exit 1; SEQ=1; SERVER_NONCE=""; continue ;;
nonce_mismatch) # a refresh cannot repair the chain, only a new session
activate || exit 1; SEQ=1; SERVER_NONCE=""; continue ;;
dpop_*) # dpop_required and every other dpop_ code
# Mint a FRESH proof and repeat this beat unchanged: same SEQ, same
# SERVER_NONCE. Activating again spends a device slot on something a
# new proof fixes on its own.
continue ;;
*) # a bare sentence with no code: the Authorization
# header is missing or blank. That is a bug in this script, and
# another activation will not fix it.
echo "fix the Authorization header: $ERR" >&2; exit 1 ;;
esac ;;
*) echo "permanent: HTTP $CODE $ERR" >&2; exit 1 ;; # a 400 never clears on a timer
esac
SERVER_NONCE=$(jq -r .serverNonce beat.json)
EXP=$(jq -r .expiresAt beat.json)
SEQ=$((SEQ + 1))
sleep $(( ($(date -d "$EXP" +%s) - $(date +%s)) / 2 ))
done
// Returns the HTTP status and fills out and hdr. 200 on its own is not
// permission to run: the caller verifies before it reads a field.
long heartbeat(CURL* c, const Cfg& cfg, const std::string& base,
const std::string& access, int seq, const std::string& deviceHash,
const std::string& serverNonce, const std::string& clientNonce,
std::string& out, SigHdr& hdr) {
// deviceHash is REQUIRED and the body is strict: omit it and every beat is 400.
// serverNonce is the value from the previous beat, empty string on the first.
std::string body = R"({"seq":)" + std::to_string(seq) +
R"(,"deviceHash":")" + deviceHash +
R"(","serverNonce":")" + serverNonce +
R"(","clientNonce":")" + clientNonce + R"("})";
curl_slist* h = curl_slist_append(nullptr, "Content-Type: application/json");
h = curl_slist_append(h, ("Authorization: Bearer " + access).c_str());
h = curl_slist_append(h, ("x-licentry-build: " + cfg.buildToken).c_str());
h = curl_slist_append(h, "x-licentry-protocol: 1");
// add "DPoP: <proof>" here when the session is DPoP bound
curl_easy_setopt(c, CURLOPT_URL, (base + "/v1/sess/heartbeat").c_str());
curl_easy_setopt(c, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, h);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, sink);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &out);
curl_easy_setopt(c, CURLOPT_HEADERFUNCTION, hdrSink);
curl_easy_setopt(c, CURLOPT_HEADERDATA, &hdr);
curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(h);
return code;
}
// The loop. Each refusal below wants a different answer, and re-activating on
// all of them spends the device slot on problems a refresh would have fixed.
void runSession(CURL* c, const Cfg& cfg, Session& s) {
bool reactivated = false;
// One idempotency key per activation attempt; reuse it only if THAT attempt is
// retried after a dropped response.
auto reactivate = [&] { return activate(cfg, s.deviceHash, randomHex(16), s); };
for (;;) {
const std::string cn = randomHex(8);
std::string out;
SigHdr hdr;
long code = heartbeat(c, cfg, cfg.base, s.accessToken, s.seq, s.deviceHash,
s.serverNonce, cn, out, hdr);
// Not licence decisions, and they need not come from the app at all: back
// off and resend the IDENTICAL body, same seq and same serverNonce.
if (code == 429 || code >= 500) { sleepSeconds(30); continue; }
// Verify before reading a single field. An empty hdr.sig fails here.
if (!verifySig(cfg.pinned(hdr.kid), (int)code, hdr.ts, out, hdr.sig, time(nullptr)))
return stopLicensedWork();
auto j = json::parse(out, nullptr, false);
if (j.is_discarded() || j.value("clientNonce", "") != cn) return stopLicensedWork();
const std::string err = j.value("error", "");
if (code == 403 || code == 426) return stopLicensedWork(); // killed, suspended, retired
if (code == 409) { // seq out of step
if (!refreshSession(c, cfg, cfg.base, s.refreshToken, s.deviceHash, s))
return stopLicensedWork();
continue; // next beat sends seq 1; the chain carries over
}
if (code == 401) {
if (err == "invalid_session") { // evicted or gone: activate ONCE, after a backoff
if (reactivated) return stopLicensedWork();
reactivated = true;
sleepSeconds(5);
if (!reactivate()) return stopLicensedWork();
continue;
}
if (err == "expired") { // refresh, and activate only if that is refused too
if (!refreshSession(c, cfg, cfg.base, s.refreshToken, s.deviceHash, s) &&
!reactivate()) return stopLicensedWork();
continue;
}
if (err == "revoked") return stopLicensedWork(); // terminal, do not loop
if (err == "stale_revocation") { // stop the licensed work, then honour the answer
stopLicensedWork();
if (!reactivate()) return;
continue;
}
if (err == "nonce_mismatch") { // only a new session repairs the chain
if (!reactivate()) return stopLicensedWork();
continue;
}
// dpop_required and every other dpop_ code: mint a FRESH proof and repeat
// this beat unchanged, same seq and same serverNonce.
if (err.rfind("dpop_", 0) == 0) continue;
// A bare sentence with no code: the Authorization header is missing or
// blank. That is a bug here, and another activation will not fix it.
return stopLicensedWork();
}
if (code != 200) return stopLicensedWork(); // 400 and friends never clear on a timer
s.serverNonce = j.value("serverNonce", "");
s.seq++;
sleepUntilHalfOf(j.value("expiresAt", ""));
}
}
record Beat(bool ok, string expiresAt, long revocationVersion,
string serverNonce, string clientNonce, string error);
int seq = 1; // 1 after activate and after every refresh
string serverNonce = ""; // empty on the first beat
bool reactivated = false;
while (running) {
var clientNonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(8));
var req = new HttpRequestMessage(HttpMethod.Post, "/v1/sess/heartbeat") {
Content = JsonContent.Create(new {
seq, deviceHash, serverNonce, clientNonce
})
};
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
req.Headers.Add("x-licentry-build", buildToken);
req.Headers.Add("x-licentry-protocol", "1");
var res = await http.SendAsync(req);
var raw = await res.Content.ReadAsByteArrayAsync();
var code = (int)res.StatusCode;
// Not licence decisions, and they need not come from the app at all. Back
// off and resend the IDENTICAL body: same seq, same serverNonce.
if (code == 429 || code >= 500) { await Task.Delay(30_000); continue; }
// Everything below decides whether the product keeps running, so verify
// before reading a field. Verify throws on an unsigned or forged response.
var v = Verify(res, raw, pinned);
var beat = JsonSerializer.Deserialize<Beat>(v.Body)!;
if (beat.clientNonce != clientNonce) { Shutdown(); return; }
// An operator kill, suspension or retired build is terminal. Stop licensed
// work rather than retrying or continuing under an offline policy.
if (code == 403 || code == 426) { Shutdown(); return; }
if (code == 409) { // seq out of step
if (await Refresh() is null) { Shutdown(); return; }
seq = 1; continue; // the nonce chain carries over
}
if (code == 401) {
switch (beat.error) {
case "invalid_session": // evicted or gone: activate ONCE, after a backoff
if (reactivated) { Shutdown(); return; }
reactivated = true;
await Task.Delay(5_000);
await Activate(); seq = 1; serverNonce = ""; continue;
case "expired": // refresh, and activate only if that is refused too
if (await Refresh() is null) { await Activate(); serverNonce = ""; }
seq = 1; continue;
case "revoked": // terminal. Do not loop.
Shutdown(); return;
case "stale_revocation": // stop the licensed work, then honour the answer
StopLicensedWork();
await Activate(); seq = 1; serverNonce = ""; continue;
case "nonce_mismatch": // only a new session repairs the chain
await Activate(); seq = 1; serverNonce = ""; continue;
default:
// dpop_required and every other dpop_ code: mint a FRESH proof
// and repeat this beat unchanged, same seq and same serverNonce.
if (beat.error?.StartsWith("dpop_") == true) continue;
// A bare sentence with no code: the Authorization header is
// missing or blank. A bug here, and activating cannot fix it.
Shutdown(); return;
}
}
if (code != 200) { Shutdown(); return; } // 400 and friends never clear on a timer
serverNonce = beat.serverNonce;
seq++;
await Task.Delay(HalfOf(beat.expiresAt));
}
seq = 1 # 1 after activate and after every refresh
server_nonce = "" # empty on the first beat
reactivated = False
while running:
client_nonce = secrets.token_hex(8)
r = requests.post(
f"{BASE}/v1/sess/heartbeat",
headers={"Authorization": f"Bearer {access_token}",
"x-licentry-build": BUILD_TOKEN, "x-licentry-protocol": "1"},
json={"seq": seq, "deviceHash": device_hash,
"serverNonce": server_nonce, "clientNonce": client_nonce},
timeout=10,
)
# Not licence decisions, and they need not come from the app at all. Back off
# and resend the IDENTICAL body: same seq, same server_nonce.
if r.status_code == 429 or r.status_code >= 500:
time.sleep(30); continue
# Everything below decides whether the product keeps running, so verify
# before reading a field. verify raises on an unsigned or forged response.
status, beat = verify(r, PINNED)
if beat.get("clientNonce") != client_nonce:
shutdown(); break # not an answer to this request
# Terminal: killed, suspended, or the build was retired. Do not fall through
# to a retry, and do not read the body for a value that is not there.
if status in (403, 426):
shutdown(); break
if status == 409: # seq out of step
if not refresh():
shutdown(); break
seq = 1; continue # the nonce chain carries over
if status == 401:
err = beat.get("error", "")
if err == "invalid_session": # evicted or gone: activate ONCE, after a backoff
if reactivated:
shutdown(); break
reactivated = True
time.sleep(5)
activate(); seq = 1; server_nonce = ""; continue
if err == "expired": # refresh, and activate only if that is refused too
if not refresh():
activate(); server_nonce = ""
seq = 1; continue
if err == "revoked": # terminal. Do not loop.
shutdown(); break
if err == "stale_revocation": # stop the licensed work, then honour the answer
stop_licensed_work()
activate(); seq = 1; server_nonce = ""; continue
if err == "nonce_mismatch": # only a new session repairs the chain
activate(); seq = 1; server_nonce = ""; continue
if err.startswith("dpop_"):
# dpop_required and every other dpop_ code: mint a FRESH proof and
# repeat this beat unchanged, same seq and same server_nonce.
continue
# A bare sentence with no code: the Authorization header is missing or
# blank. That is a bug here, and activating again will not fix it.
shutdown(); break
if status != 200: # 400 and friends never clear on a timer
shutdown(); break
server_nonce = beat.get("serverNonce", "")
seq += 1
time.sleep(half_of(beat["expiresAt"]))
let seq = 1; // 1 after activate and after every refresh
let serverNonce = ''; // empty on the first beat
let reactivated = false;
async function beat() {
const clientNonce = randomBytes(8).toString('hex');
const res = await fetch(`${BASE}/v1/sess/heartbeat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
'x-licentry-build': BUILD_TOKEN,
'x-licentry-protocol': '1',
},
body: JSON.stringify({ seq, deviceHash, serverNonce, clientNonce }),
});
// Not licence decisions, and they need not come from the app at all. Back off
// and resend the IDENTICAL body: same seq, same serverNonce.
if (res.status === 429 || res.status >= 500) return schedule(30_000);
// Everything below decides whether the product keeps running, so verify
// first. verifySigned throws on an unsigned or forged response.
const { status, body: b } = await verifySigned(res, pinned);
if (b.clientNonce !== clientNonce) return shutdown();
// Stop on terminal responses. Scheduling another attempt would retry a
// session that an operator deliberately ended.
if (status === 403 || status === 426) return shutdown();
if (status === 409) { // seq out of step
if (!(await refresh())) return shutdown();
seq = 1; // the nonce chain carries over
return schedule(0);
}
if (status === 401) {
const err = b.error ?? '';
if (err === 'invalid_session') { // evicted or gone: activate ONCE
if (reactivated) return shutdown();
reactivated = true;
await new Promise((r) => setTimeout(r, 5_000)); // back off first
await activate();
seq = 1; serverNonce = '';
return schedule(0);
}
if (err === 'expired') { // refresh, activate only if that fails too
if (!(await refresh())) { await activate(); serverNonce = ''; }
seq = 1;
return schedule(0);
}
if (err === 'revoked') return shutdown(); // terminal. Do not loop.
if (err === 'stale_revocation') { // stop the work, then honour the answer
stopLicensedWork();
await activate();
seq = 1; serverNonce = '';
return schedule(0);
}
if (err === 'nonce_mismatch') { // only a new session repairs the chain
await activate();
seq = 1; serverNonce = '';
return schedule(0);
}
// dpop_required and every other dpop_ code: mint a FRESH proof and repeat
// this beat unchanged, same seq and same serverNonce.
if (err.startsWith('dpop_')) return schedule(0);
// A bare sentence with no code: the Authorization header is missing or
// blank. That is a bug here, and activating again will not fix it.
return shutdown();
}
if (status !== 200) return shutdown(); // 400 and friends never clear on a timer
serverNonce = b.serverNonce ?? '';
seq += 1;
schedule(halfOf(b.expiresAt));
}
type beatResp struct {
OK bool `json:"ok"`
ExpiresAt string `json:"expiresAt"`
RevocationVersion int64 `json:"revocationVersion"`
ServerNonce string `json:"serverNonce"`
ClientNonce string `json:"clientNonce"`
Error string `json:"error"`
}
// beat classifies the answer. Each sentinel wants a different response from the
// caller, and re-activating on all of them spends the single device slot on
// problems a refresh would have fixed.
func beat(seq int, serverNonce string) (*beatResp, error) {
cn := make([]byte, 8)
rand.Read(cn)
clientNonce := hex.EncodeToString(cn)
body, _ := json.Marshal(map[string]any{
"seq": seq, "deviceHash": deviceHash,
"serverNonce": serverNonce, "clientNonce": clientNonce,
})
req, _ := http.NewRequest("POST", base+"/v1/sess/heartbeat", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("x-licentry-build", buildToken)
req.Header.Set("x-licentry-protocol", "1")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, ErrOffline // network: your offline policy, not a licence decision
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body) // the signature covers these exact bytes
// Not a licence decision, and need not come from the app at all.
if res.StatusCode == 429 || res.StatusCode >= 500 {
return nil, ErrOffline
}
// Everything below decides whether the product keeps running, so verify
// before reading a field. A missing X-Licentry-Sig fails here.
if !Verify(res, raw, pinned) {
return nil, ErrTerminal
}
var b beatResp
if err := json.Unmarshal(raw, &b); err != nil {
return nil, ErrTerminal
}
if b.ClientNonce != clientNonce {
return nil, ErrTerminal // answer to a different request, or a replay
}
switch res.StatusCode {
case 200:
return &b, nil
case 403, 426:
return nil, ErrTerminal // killed, suspended, build retired: stop
case 409:
return nil, ErrRefreshFirst // seq out of step
case 401:
break
default:
return nil, ErrPermanent // a 400 never clears on a timer
}
switch b.Error {
case "invalid_session":
return nil, ErrReactivateOnce
case "expired":
return nil, ErrRefreshFirst
case "revoked":
return nil, ErrTerminal
case "stale_revocation":
return nil, ErrStaleRevocation
case "nonce_mismatch":
return nil, ErrReactivateOnce // a refresh cannot repair the chain
}
if strings.HasPrefix(b.Error, "dpop_") {
return nil, ErrSameBeatAgain
}
return nil, ErrClientBug // a bare sentence, no code
}
// What the caller does with each of them:
// nil store ServerNonce, seq++, sleep to half of ExpiresAt
// ErrOffline back off, then resend the IDENTICAL body: same seq, same nonce
// ErrSameBeatAgain mint a FRESH DPoP proof, repeat this beat: same seq, same nonce
// ErrRefreshFirst refresh (next beat sends seq 1, chain carries over); activate only
// if the refresh is refused as well
// ErrReactivateOnce back off, activate ONCE; if the next beat refuses again, stop
// ErrStaleRevocation stop the licensed work, activate, then honour the answer
// ErrTerminal stop. Do not loop.
// ErrClientBug the Authorization header is missing or blank. Fix the
// header; another activation will not help
// ErrPermanent stop. Retrying this on a timer loops forever
#[derive(Deserialize)]
struct Beat {
#[serde(rename = "expiresAt")] expires_at: Option<String>,
#[serde(rename = "serverNonce")] server_nonce: Option<String>,
#[serde(rename = "clientNonce")] client_nonce: Option<String>,
error: Option<String>,
}
// deviceHash is REQUIRED by the strict body schema. Sending only seq is a 400
// on every beat, and the build header is required as soon as the product asks
// for one.
fn beat(seq: u32, server_nonce: &str) -> Result<Beat> {
let client_nonce: String = (0..16)
.map(|_| char::from_digit(rand::random::<u32>() % 16, 16).unwrap())
.collect();
let res = client
.post(format!("{base}/v1/sess/heartbeat"))
.bearer_auth(&access_token)
.header("x-licentry-build", &build_token)
.header("x-licentry-protocol", "1")
.json(&json!({
"seq": seq,
"deviceHash": device_hash,
"serverNonce": server_nonce,
"clientNonce": client_nonce,
}))
.send()?;
let status = res.status().as_u16();
let headers = res.headers().clone();
let raw = res.bytes()?; // the signature covers these exact bytes
// Not a licence decision, and need not come from the app at all: back off
// and resend the IDENTICAL body, same seq and same server_nonce.
if status == 429 || status >= 500 {
bail!(Offline);
}
// Everything below decides whether the product keeps running, so verify
// before reading a field. An unsigned response is refused here.
match verify(status, &headers, &raw, &pinned) {
Ok(()) => {}
Err(Error::Refused(_)) => {} // signed refusal, classified below
Err(e) => bail!(e), // unverified: drop it and stop
}
let b: Beat = serde_json::from_slice(&raw)?;
if b.client_nonce.as_deref() != Some(client_nonce.as_str()) {
bail!(Terminal);
}
match status {
200 => return Ok(b),
403 | 426 => bail!(Terminal), // killed, suspended, build retired
409 => bail!(RefreshFirst), // seq out of step
401 => {}
_ => bail!(Permanent), // a 400 never clears on a timer
}
match b.error.as_deref().unwrap_or("") {
"invalid_session" => bail!(ReactivateOnce),
"expired" => bail!(RefreshFirst),
"revoked" => bail!(Terminal),
"stale_revocation" => bail!(StaleRevocation),
"nonce_mismatch" => bail!(ReactivateOnce), // a refresh cannot repair the chain
e if e.starts_with("dpop_") => bail!(SameBeatAgain),
_ => bail!(ClientBug), // a bare sentence, no code
}
}
// What the caller does with each of them:
// Ok store server_nonce, seq += 1, sleep to half of expires_at
// Offline back off, then resend the IDENTICAL body: same seq, same nonce
// SameBeatAgain mint a FRESH DPoP proof, repeat this beat: same seq, same nonce
// RefreshFirst refresh (next beat sends seq 1, chain carries over); activate only if
// the refresh is refused as well
// ReactivateOnce back off, activate ONCE; if the next beat refuses again, stop
// StaleRevocation stop the licensed work, activate, then honour the answer
// Terminal stop. Do not loop.
// ClientBug the Authorization header is missing or blank. Fix the header;
// another activation will not help
// Permanent stop. Retrying this on a timer loops forever
record Beat(boolean ok, String expiresAt, long revocationVersion,
String serverNonce, String clientNonce, String error) {}
int seq = 1; // 1 after activate and after every refresh
String serverNonce = ""; // empty on the first beat
boolean reactivated = false;
while (running) {
byte[] n = new byte[8];
SECURE_RANDOM.nextBytes(n);
String clientNonce = HexFormat.of().formatHex(n);
var body = MAPPER.writeValueAsString(Map.of(
"seq", seq, "deviceHash", deviceHash,
"serverNonce", serverNonce, "clientNonce", clientNonce));
var req = HttpRequest.newBuilder(URI.create(base + "/v1/sess/heartbeat"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + accessToken)
.header("x-licentry-build", buildToken)
.header("x-licentry-protocol", "1")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
var res = client.send(req, HttpResponse.BodyHandlers.ofByteArray());
int code = res.statusCode();
// Not licence decisions, and they need not come from the app at all. Back
// off and resend the IDENTICAL body: same seq, same serverNonce.
if (code == 429 || code >= 500) { Thread.sleep(30_000); continue; }
// Everything below decides whether the product keeps running, so verify
// before parsing. A response with no X-Licentry-Sig fails here.
if (!verify(res, PINNED)) { shutdown(); break; }
Beat beat = MAPPER.readValue(res.body(), Beat.class);
if (!clientNonce.equals(beat.clientNonce())) { shutdown(); break; }
// Terminal. Do not retry: an error body has no expiresAt.
if (code == 403 || code == 426) { shutdown(); break; }
if (code == 409) { // seq out of step
if (refresh() == null) { shutdown(); break; }
seq = 1; continue; // the nonce chain carries over
}
if (code == 401) {
String err = beat.error() == null ? "" : beat.error();
if (err.equals("invalid_session")) { // evicted or gone: activate ONCE
if (reactivated) { shutdown(); break; }
reactivated = true;
Thread.sleep(5_000); // back off before taking the seat back
activate(); seq = 1; serverNonce = ""; continue;
}
if (err.equals("expired")) { // refresh, activate only if that fails too
if (refresh() == null) { activate(); serverNonce = ""; }
seq = 1; continue;
}
if (err.equals("revoked")) { shutdown(); break; } // terminal. Do not loop.
if (err.equals("stale_revocation")) { // stop the work, then honour the answer
stopLicensedWork();
activate(); seq = 1; serverNonce = ""; continue;
}
if (err.equals("nonce_mismatch")) { // only a new session repairs the chain
activate(); seq = 1; serverNonce = ""; continue;
}
// dpop_required and every other dpop_ code: mint a FRESH proof and
// repeat this beat unchanged, same seq and same serverNonce.
if (err.startsWith("dpop_")) { continue; }
// A bare sentence with no code: the Authorization header is missing or
// blank. That is a bug here, and activating again will not fix it.
shutdown(); break;
}
if (code != 200) { shutdown(); break; } // 400 and friends never clear on a timer
serverNonce = beat.serverNonce() == null ? "" : beat.serverNonce();
seq++;
Thread.sleep(halfOf(beat.expiresAt()));
}
$seq = 1; // 1 after activate and after every refresh
$serverNonce = ''; // empty on the first beat
$reactivated = false;
while ($running) {
$clientNonce = bin2hex(random_bytes(8));
$ch = curl_init("$base/v1/sess/heartbeat");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
"Authorization: Bearer $accessToken",
"x-licentry-build: $buildToken",
"x-licentry-protocol: 1",
],
CURLOPT_POSTFIELDS => json_encode([
'seq' => $seq, 'deviceHash' => $deviceHash,
'serverNonce' => $serverNonce, 'clientNonce' => $clientNonce,
]),
]);
$h = [];
collectHeaders($ch, $h);
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
// Not licence decisions, and they need not come from the app at all. Back
// off and resend the IDENTICAL body: same $seq, same $serverNonce.
if ($code === 429 || $code >= 500) { sleep(30); continue; }
// Everything below decides whether the product keeps running, so verify
// before reading a field. An unsigned answer is refused here.
if (!licentryVerify($code, $h, $raw, $pinned)) { shutdown(); break; }
$beat = json_decode($raw, true);
if (($beat['clientNonce'] ?? null) !== $clientNonce) { shutdown(); break; }
$err = $beat['error'] ?? '';
// Terminal: stop the licensed work. Anything that continues here would
// dereference expiresAt on an error body and loop forever.
if ($code === 403 || $code === 426) { shutdown(); break; }
if ($code === 409) { // seq out of step
if (refreshSession() === null) { shutdown(); break; }
$seq = 1; continue; // the nonce chain carries over
}
if ($code === 401) {
if ($err === 'invalid_session') { // evicted or gone: activate ONCE
if ($reactivated) { shutdown(); break; }
$reactivated = true;
sleep(5); // back off before taking the seat back
activate(); $seq = 1; $serverNonce = ''; continue;
}
if ($err === 'expired') { // refresh, activate only if that fails too
if (refreshSession() === null) { activate(); $serverNonce = ''; }
$seq = 1; continue;
}
if ($err === 'revoked') { shutdown(); break; } // terminal. Do not loop.
if ($err === 'stale_revocation') { // stop the work, then honour the answer
stopLicensedWork();
activate(); $seq = 1; $serverNonce = ''; continue;
}
if ($err === 'nonce_mismatch') { // only a new session repairs the chain
activate(); $seq = 1; $serverNonce = ''; continue;
}
// dpop_required and every other dpop_ code: mint a FRESH proof and
// repeat this beat unchanged, same $seq and same $serverNonce.
if (str_starts_with($err, 'dpop_')) { continue; }
// A bare sentence with no code: the Authorization header is missing or
// blank. That is a bug here, and activating again will not fix it.
shutdown(); break;
}
if ($code !== 200) { shutdown(); break; } // a 400 never clears on a timer
$serverNonce = $beat['serverNonce'] ?? '';
$seq++;
sleep(halfOf($beat['expiresAt']));
}
struct Beat: Decodable {
let expiresAt: String?
let serverNonce: String?
let clientNonce: String?
let error: String?
}
var seq = 1 // 1 after activate and after every refresh
var serverNonce = "" // empty on the first beat
func beat() async throws -> Beat {
var bytes = [UInt8](repeating: 0, count: 8)
_ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
let clientNonce = bytes.map { String(format: "%02x", $0) }.joined()
var req = URLRequest(url: base.appendingPathComponent("v1/sess/heartbeat"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
req.setValue(buildToken, forHTTPHeaderField: "x-licentry-build")
req.setValue("1", forHTTPHeaderField: "x-licentry-protocol")
req.httpBody = try JSONEncoder().encode([
"seq": AnyEncodable(seq), "deviceHash": AnyEncodable(deviceHash),
"serverNonce": AnyEncodable(serverNonce),
"clientNonce": AnyEncodable(clientNonce),
])
let (data, resp) = try await URLSession.shared.data(for: req)
let http = resp as! HTTPURLResponse
let code = http.statusCode
// Not a licence decision, and need not come from the app at all: back off
// and resend the IDENTICAL body, same seq and same serverNonce.
if code == 429 || code >= 500 { throw LicenceError.offline }
// Everything below decides whether the product keeps running, so verify
// before reading a field. An unsigned response is refused in there.
guard verify(http, body: data, pinned: pinned) else { throw LicenceError.terminal }
let b = try JSONDecoder().decode(Beat.self, from: data)
guard b.clientNonce == clientNonce else { throw LicenceError.terminal }
switch code {
case 200: break
case 403, 426: throw LicenceError.terminal // killed, suspended, retired
case 409: throw LicenceError.refreshFirst // seq out of step
case 401:
switch b.error ?? "" {
case "invalid_session": throw LicenceError.reactivateOnce
case "expired": throw LicenceError.refreshFirst
case "revoked": throw LicenceError.terminal
case "stale_revocation": throw LicenceError.staleRevocation
case "nonce_mismatch": throw LicenceError.reactivateOnce
case let e where e.hasPrefix("dpop_"): throw LicenceError.sameBeatAgain
default: throw LicenceError.clientBug // a bare sentence, no code
}
default: throw LicenceError.permanent // a 400 never clears on a timer
}
serverNonce = b.serverNonce ?? ""
seq += 1
return b
}
// What the caller does with each of them:
// returned Beat store serverNonce, seq += 1, sleep to half of expiresAt
// offline back off, then resend the IDENTICAL body: same seq, same nonce
// sameBeatAgain mint a FRESH DPoP proof, repeat this beat: same seq, same nonce
// refreshFirst refresh (next beat sends seq 1, chain carries over); activate only if
// the refresh is refused as well
// reactivateOnce back off, activate ONCE; if the next beat refuses again, stop
// staleRevocation stop the licensed work, activate, then honour the answer
// terminal stop. Do not loop.
// clientBug the Authorization header is missing or blank. Fix the header;
// another activation will not help
// permanent stop. Retrying this on a timer loops forever
data class Beat(val expiresAt: String, val serverNonce: String?,
val clientNonce: String?, val error: String?)
var seq = 1 // 1 after activate and after every refresh
var serverNonce = "" // empty on the first beat
var reactivated = false
while (running) {
val clientNonce = ByteArray(8).also { SecureRandom().nextBytes(it) }
.joinToString("") { "%02x".format(it) }
val body = gson.toJson(mapOf(
"seq" to seq, "deviceHash" to deviceHash,
"serverNonce" to serverNonce, "clientNonce" to clientNonce))
val req = Request.Builder()
.url("$base/v1/sess/heartbeat")
.addHeader("Authorization", "Bearer $accessToken")
.addHeader("x-licentry-build", buildToken)
.addHeader("x-licentry-protocol", "1")
.post(body.toRequestBody("application/json".toMediaType()))
.build()
client.newCall(req).execute().use { res ->
val code = res.code
// Not licence decisions, and they need not come from the app at all.
// Back off and resend the IDENTICAL body: same seq, same serverNonce.
if (code == 429 || code >= 500) { Thread.sleep(30_000); return@use }
val raw = res.body!!.bytes()
// Everything below decides whether the product keeps running, so verify
// before parsing. An unsigned response is refused inside verify.
if (!verify(res, raw, pinned)) { shutdown(); return }
val beat = gson.fromJson(String(raw), Beat::class.java)
if (beat.clientNonce != clientNonce) { shutdown(); return }
val err = beat.error ?: ""
when {
// Stop on an error status before reading expiresAt, which is absent from
// error bodies and would cause a parsing failure.
code == 403 || code == 426 -> { shutdown(); return }
code == 409 -> { // seq out of step
if (refresh() == null) { shutdown(); return }
seq = 1 // the nonce chain carries over
}
code == 401 && err == "invalid_session" -> { // evicted or gone
if (reactivated) { shutdown(); return } // activate ONCE
reactivated = true
Thread.sleep(5_000) // back off before taking the seat back
activate(); seq = 1; serverNonce = ""
}
code == 401 && err == "expired" -> { // refresh, activate only if that fails
if (refresh() == null) { activate(); serverNonce = "" }
seq = 1
}
code == 401 && err == "revoked" -> { shutdown(); return } // do not loop
code == 401 && err == "stale_revocation" -> {
stopLicensedWork() // stop first, then honour the answer
activate(); seq = 1; serverNonce = ""
}
code == 401 && err == "nonce_mismatch" -> { // only a new session repairs it
activate(); seq = 1; serverNonce = ""
}
// dpop_required and every other dpop_ code: mint a FRESH proof and
// repeat this beat unchanged, same seq and same serverNonce.
code == 401 && err.startsWith("dpop_") -> return@use
// A bare sentence with no code: the Authorization header is missing
// or blank. A bug here, and activating again will not fix it.
code == 401 -> { shutdown(); return }
code == 200 -> {
serverNonce = beat.serverNonce ?: ""
seq++
Thread.sleep(halfOf(beat.expiresAt))
}
else -> { shutdown(); return } // a 400 never clears on a timer
}
}
}
seq = 1 # 1 after activate and after every refresh
server_nonce = '' # empty on the first beat
reactivated = false
while running
client_nonce = SecureRandom.hex(8)
res = Net::HTTP.post(
URI("#{BASE}/v1/sess/heartbeat"),
{ seq: seq, deviceHash: device_hash,
serverNonce: server_nonce, clientNonce: client_nonce }.to_json,
'Content-Type' => 'application/json',
'Authorization' => "Bearer #{access_token}",
'x-licentry-build' => BUILD_TOKEN,
'x-licentry-protocol' => '1'
)
# Not licence decisions, and they need not come from the app at all. Back off
# and resend the IDENTICAL body: same seq, same server_nonce.
code = res.code.to_i
if code == 429 || code >= 500
sleep 30
next
end
# Everything below decides whether the product keeps running, so verify before
# reading a field. verify! raises on an unsigned or forged response.
status, beat = verify!(res, res.body, PINNED)
(shutdown; break) unless beat['clientNonce'] == client_nonce
err = beat['error'].to_s
# Stop on terminal responses before reading their expiry. Otherwise the loop
# can call sleep(nil) and keep running after a licence refusal.
case status
when 403, 426 then shutdown; break
when 409 # seq out of step
(shutdown; break) unless refresh
seq = 1 # the nonce chain carries over
next
when 401
case err
when 'invalid_session' # evicted or gone: activate ONCE
(shutdown; break) if reactivated
reactivated = true
sleep 5 # back off before taking the seat back
activate; seq = 1; server_nonce = ''; next
when 'expired' # refresh, activate only if that fails too
unless refresh
activate
server_nonce = ''
end
seq = 1
next
when 'revoked' then shutdown; break # terminal. Do not loop.
when 'stale_revocation' # stop the work, then honour the answer
stop_licensed_work
activate; seq = 1; server_nonce = ''; next
when 'nonce_mismatch' # only a new session repairs the chain
activate; seq = 1; server_nonce = ''; next
else
# dpop_required and every other dpop_ code: mint a FRESH proof and repeat
# this beat unchanged, same seq and same server_nonce.
next if err.start_with?('dpop_')
# A bare sentence with no code: the Authorization header is missing or
# blank. That is a bug here, and activating again will not fix it.
shutdown
break
end
when 200 then nil
else shutdown; break # a 400 never clears on a timer
end
server_nonce = beat['serverNonce'].to_s
seq += 1
sleep half_of(beat['expiresAt'])
end
4 · Refresh before expiry
Rotate tokens before refreshExpiresAt. After a refresh the sequence resets, so your next heartbeat is seq: 1 again, but the nonce chain does not: keep the last serverNonce you were issued and echo it on that beat.
CN=$(openssl rand -hex 8)
CODE=$(curl -sS -D ref.hdr -o ref.json -w '%{http_code}' \
-X POST "$BASE/v1/sess/refresh" \
-H "Content-Type: application/json" \
-H "x-licentry-build: $BUILD_TOKEN" \
-H "x-licentry-protocol: 1" \
-d "$(printf '{"refreshToken":"%s","deviceHash":"%s","clientNonce":"%s"}' \
"$REFRESH_TOKEN" "$DEVICE_HASH" "$CN")")
# Signature, freshness, echo and status, all before a token is read out of the
# body. An unsigned answer is refused here, not waved through.
# 401 refresh_token_stale or invalid_session: the pair is dead, activate again
# 403 license_suspended, 426 build retired: terminal, stop
licentry_accepted "$CODE" ref.hdr ref.json "$CN" || exit 1
ACCESS_TOKEN=$(jq -r .accessToken ref.json)
REFRESH_TOKEN=$(jq -r .refreshToken ref.json)
EXPIRES_AT=$(jq -r .expiresAt ref.json)
SEQ=1 # the heartbeat sequence starts over at 1
# The nonce chain does NOT reset: keep the last SERVER_NONCE you hold. Refresh is
# also the only thing that refills the nonce retry budget, which is three.
// Returns false when the refresh was refused. Never returns a half-filled
// session: the caller must not keep using the old tokens after a refusal.
bool refreshSession(CURL* c, const Cfg& cfg, const std::string& base,
const std::string& refreshToken,
const std::string& deviceHash, Session& out) {
// deviceHash is required: Licentry Cloud requires it on refresh, and a bound
// session demands it regardless.
std::string cn = randomHex(8);
std::string body = R"({"refreshToken":")" + refreshToken +
R"(","deviceHash":")" + deviceHash +
R"(","clientNonce":")" + cn + R"("})";
std::string resp;
SigHdr hdr;
curl_slist* h = curl_slist_append(nullptr, "Content-Type: application/json");
h = curl_slist_append(h, ("x-licentry-build: " + cfg.buildToken).c_str());
h = curl_slist_append(h, "x-licentry-protocol: 1");
curl_easy_setopt(c, CURLOPT_URL, (base + "/v1/sess/refresh").c_str());
curl_easy_setopt(c, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, h);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, sink);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &resp);
curl_easy_setopt(c, CURLOPT_HEADERFUNCTION, hdrSink);
curl_easy_setopt(c, CURLOPT_HEADERDATA, &hdr);
curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(h);
// Signature, freshness and status in one call, and an unsigned answer is
// refused here: 401 means activate again, 403 and 426 are terminal.
if (!accepted(cfg.pinned(hdr.kid), (int)code, hdr.ts, resp, hdr.sig, time(nullptr)))
return false;
auto j = json::parse(resp, nullptr, false);
if (j.is_discarded() || j.value("clientNonce", "") != cn) return false;
out.accessToken = j["accessToken"];
out.refreshToken = j["refreshToken"];
out.expiresAt = j["expiresAt"];
out.seq = 1; // the heartbeat sequence restarts; out.serverNonce does not
return true;
}
record Refreshed(string accessToken, string refreshToken,
string expiresAt, string clientNonce);
// Returns null when the refresh was refused. The caller must stop, not carry on
// with the tokens it already had.
async Task<Refreshed?> Refresh() {
var clientNonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(8));
var req = new HttpRequestMessage(HttpMethod.Post, "/v1/sess/refresh") {
Content = JsonContent.Create(new { refreshToken, deviceHash, clientNonce })
};
req.Headers.Add("x-licentry-build", buildToken);
req.Headers.Add("x-licentry-protocol", "1");
var res = await http.SendAsync(req);
var raw = await res.Content.ReadAsByteArrayAsync();
// A refusal is not a session. Filling a Session object from an error body
// leaves the old access token in place and reads as success to the caller.
// Verify first, so an unsigned answer is refused rather than waved through.
Verified v;
try { v = Verify(res, raw, pinned); }
catch (CryptographicException) { return null; }
if (v.Status != 200) return null; // 401 activate again, 403 and 426 terminal
var r = JsonSerializer.Deserialize<Refreshed>(v.Body);
if (r is null || r.clientNonce != clientNonce) return null;
return r; // seq restarts at 1; the nonce chain carries straight across
}
def refresh():
client_nonce = secrets.token_hex(8)
r = requests.post(
f"{BASE}/v1/sess/refresh",
headers={"x-licentry-build": BUILD_TOKEN, "x-licentry-protocol": "1"},
json={"refreshToken": refresh_token, "deviceHash": device_hash,
"clientNonce": client_nonce},
timeout=10,
)
# Verify first and reject unsigned responses. Check the status before reading
# token fields, which are absent from error bodies and would raise KeyError.
try:
status, s = verify(r, PINNED)
except InvalidSignature:
return None
if status != 200:
# 401 stale or invalid: activate again. 403/426: terminal.
return None
if s.get("clientNonce") != client_nonce:
return None
return {
"access_token": s["accessToken"],
"refresh_token": s["refreshToken"],
"expires_at": s["expiresAt"],
"seq": 1, # heartbeat sequence restarts; the nonce chain does not
}
async function refresh(session) {
const clientNonce = randomBytes(8).toString('hex');
const res = await fetch(`${BASE}/v1/sess/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-licentry-build': BUILD_TOKEN,
'x-licentry-protocol': '1',
},
body: JSON.stringify({
refreshToken: session.refreshToken, deviceHash, clientNonce,
}),
});
// Do not use Object.assign to merge an error body into a session: it would
// retain the old accessToken and make a failed refresh look successful.
// Verify the response first, rejecting an unsigned answer.
let status, s;
try {
({ status, body: s } = await verifySigned(res, pinned));
} catch {
return null;
}
if (status !== 200) return null; // 401 activate again, 403 and 426 terminal
if (s.clientNonce !== clientNonce) return null;
return {
accessToken: s.accessToken,
refreshToken: s.refreshToken,
expiresAt: s.expiresAt,
seq: 1, // heartbeat sequence restarts; the nonce chain does not
};
}
// refresh returns (nil, err) on any refusal. It never returns a zero-valued
// Session with a nil error, which the caller would read as success.
func refresh() (*Session, error) {
cn := make([]byte, 8)
rand.Read(cn)
clientNonce := hex.EncodeToString(cn)
body, _ := json.Marshal(map[string]any{
"refreshToken": refreshToken, "deviceHash": deviceHash,
"clientNonce": clientNonce,
})
req, _ := http.NewRequest("POST", base+"/v1/sess/refresh", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-licentry-build", buildToken)
req.Header.Set("x-licentry-protocol", "1")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body) // the signature covers these exact bytes
// Verify before the status, so an unsigned answer is refused rather than
// waved through, and gate on Verify plus the status rather than on Verify
// alone: the server signs its refusals too.
if !Verify(res, raw, pinned) {
return nil, ErrTerminal
}
switch res.StatusCode {
case 200:
case 401:
return nil, ErrReactivateOnce
case 403, 426:
return nil, ErrTerminal
default:
return nil, ErrOffline
}
var s struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresAt string `json:"expiresAt"`
ClientNonce string `json:"clientNonce"`
}
if err := json.Unmarshal(raw, &s); err != nil {
return nil, err
}
if s.ClientNonce != clientNonce {
return nil, ErrTerminal
}
return &Session{AccessToken: s.AccessToken, RefreshToken: s.RefreshToken,
ExpiresAt: s.ExpiresAt, Seq: 1}, nil
}
#[derive(Deserialize)]
struct Refreshed {
#[serde(rename = "accessToken")] access_token: String,
#[serde(rename = "refreshToken")] refresh_token: String,
#[serde(rename = "expiresAt")] expires_at: String,
#[serde(rename = "clientNonce")] client_nonce: Option<String>,
}
fn refresh() -> Result<Session> {
let client_nonce: String = (0..16)
.map(|_| char::from_digit(rand::random::<u32>() % 16, 16).unwrap())
.collect();
let res = client
.post(format!("{base}/v1/sess/refresh"))
.header("x-licentry-build", &build_token)
.header("x-licentry-protocol", "1")
.json(&json!({
"refreshToken": refresh_token,
"deviceHash": device_hash,
"clientNonce": client_nonce,
}))
.send()?;
let status = res.status().as_u16();
let headers = res.headers().clone();
let raw = res.bytes()?;
// Verify before reading the status. Reject unsigned responses;
// Err(Refused) represents an authenticated refusal.
match verify(status, &headers, &raw, &pinned) {
Ok(()) => {}
Err(Error::Refused(401)) => bail!(ReactivateOnce), // stale or invalid pair
Err(Error::Refused(403 | 426)) => bail!(Terminal),
Err(Error::Refused(_)) => bail!(Offline),
Err(_) => bail!(Unverified), // unsigned or forged
}
let s: Refreshed = serde_json::from_slice(&raw)?;
if s.client_nonce.as_deref() != Some(client_nonce.as_str()) {
bail!(Terminal);
}
Ok(Session { access_token: s.access_token, refresh_token: s.refresh_token,
expires_at: s.expires_at, seq: 1 })
}
record Refreshed(String accessToken, String refreshToken,
String expiresAt, String clientNonce) {}
// Returns null on any refusal. Do not rely on the JSON mapper to fail: with
// unknown-property handling relaxed, an error body deserializes into a record
// full of nulls and the caller carries on with a session that has no tokens.
Refreshed refresh() throws Exception {
byte[] n = new byte[8];
SECURE_RANDOM.nextBytes(n);
String clientNonce = HexFormat.of().formatHex(n);
var body = MAPPER.writeValueAsString(Map.of(
"refreshToken", refreshToken, "deviceHash", deviceHash,
"clientNonce", clientNonce));
var req = HttpRequest.newBuilder(URI.create(base + "/v1/sess/refresh"))
.header("Content-Type", "application/json")
.header("x-licentry-build", buildToken)
.header("x-licentry-protocol", "1")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
var res = client.send(req, HttpResponse.BodyHandlers.ofByteArray());
// Gate on accepted rather than on the status alone: an unsigned answer is
// refused here, and the server signs its refusals as well as its approvals.
// 401 means activate again, 403 and 426 are terminal.
if (!accepted(res, PINNED)) return null;
Refreshed r = MAPPER.readValue(res.body(), Refreshed.class);
if (r.accessToken() == null || !clientNonce.equals(r.clientNonce())) return null;
return r; // seq restarts at 1; the nonce chain carries straight across
}
function refreshSession(string $base, string $refreshToken, string $deviceHash,
string $buildToken, array $pinned): ?array {
$clientNonce = bin2hex(random_bytes(8));
$ch = curl_init("$base/v1/sess/refresh");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
"x-licentry-build: $buildToken",
"x-licentry-protocol: 1",
],
CURLOPT_POSTFIELDS => json_encode([
'refreshToken' => $refreshToken,
'deviceHash' => $deviceHash,
'clientNonce' => $clientNonce,
]),
]);
$h = [];
collectHeaders($ch, $h);
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
// null, not an array with null tokens. A caller that gets back a shape it
// recognises will use it. Gate on licentryAccepted so an unsigned answer is
// refused too: 401 means activate again, 403 and 426 are terminal.
if (!licentryAccepted($code, $h, $raw, $pinned)) return null;
$s = json_decode($raw, true);
if (($s['clientNonce'] ?? null) !== $clientNonce) return null;
return [
'accessToken' => $s['accessToken'],
'refreshToken' => $s['refreshToken'],
'expiresAt' => $s['expiresAt'],
'seq' => 1,
];
}
struct Refreshed: Decodable {
let accessToken: String
let refreshToken: String
let expiresAt: String
let clientNonce: String?
}
func refresh() async throws -> Refreshed {
var bytes = [UInt8](repeating: 0, count: 8)
_ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
let clientNonce = bytes.map { String(format: "%02x", $0) }.joined()
var req = URLRequest(url: base.appendingPathComponent("v1/sess/refresh"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue(buildToken, forHTTPHeaderField: "x-licentry-build")
req.setValue("1", forHTTPHeaderField: "x-licentry-protocol")
req.httpBody = try JSONEncoder().encode([
"refreshToken": refreshToken, "deviceHash": deviceHash,
"clientNonce": clientNonce,
])
let (data, resp) = try await URLSession.shared.data(for: req)
let http = resp as! HTTPURLResponse
// Verify before the status, so an unsigned answer is refused rather than
// waved through, and read the status only once the signature checks out.
guard verify(http, body: data, pinned: pinned) else { throw LicenceError.terminal }
switch http.statusCode {
case 200: break
case 401: throw LicenceError.reactivateOnce
case 403, 426: throw LicenceError.terminal
default: throw LicenceError.offline
}
let s = try JSONDecoder().decode(Refreshed.self, from: data)
guard s.clientNonce == clientNonce else { throw LicenceError.terminal }
return s
}
data class Refreshed(val accessToken: String?, val refreshToken: String?,
val expiresAt: String?, val clientNonce: String?)
// Returns null on a refusal. Gson fills every field with null from an error
// body without complaining, so the status check is the only real guard.
fun refresh(): Refreshed? {
val clientNonce = ByteArray(8).also { SecureRandom().nextBytes(it) }
.joinToString("") { "%02x".format(it) }
val body = gson.toJson(mapOf(
"refreshToken" to refreshToken, "deviceHash" to deviceHash,
"clientNonce" to clientNonce))
val req = Request.Builder()
.url("$base/v1/sess/refresh")
.addHeader("x-licentry-build", buildToken)
.addHeader("x-licentry-protocol", "1")
.post(body.toRequestBody("application/json".toMediaType()))
.build()
client.newCall(req).execute().use { res ->
val raw = res.body!!.bytes()
// Gate on accepted rather than on the status alone: an unsigned answer
// is refused here too. 401 means activate again, 403 and 426 terminal.
if (!accepted(res, raw, pinned)) return null
val s = gson.fromJson(String(raw), Refreshed::class.java)
if (s.accessToken == null || s.clientNonce != clientNonce) return null
return s // seq restarts at 1; the nonce chain carries straight across
}
}
def refresh
client_nonce = SecureRandom.hex(8)
res = Net::HTTP.post(
URI("#{BASE}/v1/sess/refresh"),
{ refreshToken: refresh_token, deviceHash: device_hash,
clientNonce: client_nonce }.to_json,
'Content-Type' => 'application/json',
'x-licentry-build' => BUILD_TOKEN,
'x-licentry-protocol' => '1'
)
# nil, not a Session with nil tokens. Returning a shape the caller recognises
# is how a refusal turns into a session that does nothing. Verify
# first, so an unsigned answer is refused rather than waved through.
begin
status, s = verify!(res, res.body, PINNED)
rescue StandardError
return nil
end
return nil unless status == 200 # 401 activate again, 403 and 426 are terminal
return nil unless s['clientNonce'] == client_nonce
Session.new(
access_token: s['accessToken'],
refresh_token: s['refreshToken'],
expires_at: s['expiresAt'],
seq: 1 # heartbeat sequence restarts; the nonce chain does not
)
end
5 · Logout on sign-out and on clean shutdown
Call logout when the user quits. A session that is never logged out holds its concurrency seat for days and is later counted against your customer as sharing evidence; the details are under logout. If the session is DPoP-bound, send a proof over the logout URL or the call is refused and the seat stays held.
# Call this when the user quits. maxConcurrentSessions defaults to 1, and a
# session that is never logged out holds its seat until the refresh window
# closes, which is days: the customer's own next launch is what gets evicted.
CN=$(openssl rand -hex 8)
CODE=$(curl -sS -D out.hdr -o out.json -w '%{http_code}' \
-X POST "$BASE/v1/sess/logout" \
-H "Content-Type: application/json" \
-H "x-licentry-build: $BUILD_TOKEN" \
-H "x-licentry-protocol: 1" \
-d "$(jq -cn --arg t "$ACCESS_TOKEN" --arg n "$CN" \
'{accessToken: $t, clientNonce: $n}')")
# On a DPoP bound session, add a DPoP header over this URL with ath over the
# access token. Without one a strict deployment answers 401 dpop_required, the
# logout does not happen, and the seat stays held.
# Returns 200 {"ok":true} with the nonce echo. A 204 response could not
# bind its signed empty body to this request.
licentry_accepted "$CODE" out.hdr out.json "$CN" || exit 1
// Call this when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
bool logout(CURL* c, const Cfg& cfg, const std::string& base,
const std::string& accessToken) {
const std::string cn = randomHex(8);
std::string body = R"({"accessToken":")" + accessToken +
R"(","clientNonce":")" + cn + R"("})";
std::string resp;
SigHdr hdr;
curl_slist* h = curl_slist_append(nullptr, "Content-Type: application/json");
h = curl_slist_append(h, ("x-licentry-build: " + cfg.buildToken).c_str());
h = curl_slist_append(h, "x-licentry-protocol: 1");
// On a DPoP bound session, add a DPoP header over this URL with ath over the
// access token. Without one a strict deployment answers 401 dpop_required, the
// logout does not happen, and the seat stays held.
curl_easy_setopt(c, CURLOPT_URL, (base + "/v1/sess/logout").c_str());
curl_easy_setopt(c, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, h);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, sink);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &resp);
curl_easy_setopt(c, CURLOPT_HEADERFUNCTION, hdrSink);
curl_easy_setopt(c, CURLOPT_HEADERDATA, &hdr);
curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(h);
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
if (!accepted(cfg.pinned(hdr.kid), (int)code, hdr.ts, resp, hdr.sig, time(nullptr)))
return false;
auto j = json::parse(resp, nullptr, false);
return !j.is_discarded() && j.value("clientNonce", "") == cn;
}
// Call this when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
async Task<bool> Logout(HttpClient http, string accessToken, string buildToken,
IReadOnlyDictionary<string, ECDsa> pinned) {
var clientNonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(8));
// On a DPoP bound session, add a DPoP header over this URL with ath over the
// access token. Without one a strict deployment answers 401 dpop_required,
// the logout does not happen, and the seat stays held.
var req = new HttpRequestMessage(HttpMethod.Post, "/v1/sess/logout") {
Content = JsonContent.Create(new { accessToken, clientNonce })
};
req.Headers.Add("x-licentry-build", buildToken);
req.Headers.Add("x-licentry-protocol", "1");
var res = await http.SendAsync(req);
var raw = await res.Content.ReadAsByteArrayAsync();
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
Verified v;
try { v = Verify(res, raw, pinned); }
catch (CryptographicException) { return false; }
if (v.Status != 200) return false;
var body = JsonSerializer.Deserialize<JsonElement>(v.Body);
return body.TryGetProperty("clientNonce", out var echo) &&
echo.GetString() == clientNonce;
}
# Call this when the user quits. maxConcurrentSessions defaults to 1, and a
# session that is never logged out holds its seat until the refresh window
# closes, which is days: the customer's own next launch is what gets evicted.
#
# On a DPoP bound session, add a DPoP header over this URL with ath over the
# access token. Without one a strict deployment answers 401 dpop_required, the
# logout does not happen, and the seat stays held.
def logout(base, build_token, access_token, pinned):
client_nonce = secrets.token_hex(8)
r = requests.post(
f"{base}/v1/sess/logout",
headers={"Content-Type": "application/json",
"x-licentry-build": build_token, "x-licentry-protocol": "1"},
json={"accessToken": access_token, "clientNonce": client_nonce},
timeout=10,
)
# Returns 200 {"ok":true} with the nonce echo. A 204 response could not
# bind its signed empty body to this request.
try:
status, body = verify(r, pinned)
except InvalidSignature:
return False
return status == 200 and body.get("clientNonce") == client_nonce
// Call this when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
//
// On a DPoP bound session, add a DPoP header over this URL with ath over the
// access token. Without one a strict deployment answers 401 dpop_required, the
// logout does not happen, and the seat stays held.
export async function logout({ base, buildToken, accessToken, pinned }) {
const clientNonce = randomBytes(8).toString("hex");
const res = await fetch(`${base}/v1/sess/logout`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-licentry-build": buildToken,
"x-licentry-protocol": "1",
},
body: JSON.stringify({ accessToken, clientNonce }),
});
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
const { status, body } = await verifySigned(res, pinned);
return status === 200 && body.clientNonce === clientNonce;
}
// Logout when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
func Logout(base, build, accessToken string, pinned map[string]*ecdsa.PublicKey) bool {
cn := make([]byte, 8)
rand.Read(cn)
clientNonce := hex.EncodeToString(cn)
body, _ := json.Marshal(map[string]string{
"accessToken": accessToken, "clientNonce": clientNonce,
})
// On a DPoP bound session, add a DPoP header over this URL with ath over the
// access token. Without one a strict deployment answers 401 dpop_required,
// the logout does not happen, and the seat stays held.
req, _ := http.NewRequest("POST", base+"/v1/sess/logout", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-licentry-build", build)
req.Header.Set("x-licentry-protocol", "1")
res, err := http.DefaultClient.Do(req)
if err != nil {
return false
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
if !Accepted(res, raw, pinned) {
return false
}
var b struct {
ClientNonce string `json:"clientNonce"`
}
return json.Unmarshal(raw, &b) == nil && b.ClientNonce == clientNonce
}
// Call this when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
pub fn logout(base: &str, build: &str, access_token: &str,
pinned: &HashMap<String, VerifyingKey>) -> Result<()> {
let client_nonce: String = (0..16)
.map(|_| char::from_digit(rand::random::<u32>() % 16, 16).unwrap())
.collect();
let res = client
// On a DPoP bound session, add a DPoP header over this URL with ath over
// the access token. Without one a strict deployment answers
// 401 dpop_required, the logout does not happen, and the seat stays held.
.post(format!("{base}/v1/sess/logout"))
.header("x-licentry-build", build)
.header("x-licentry-protocol", "1")
.json(&json!({ "accessToken": access_token, "clientNonce": client_nonce }))
.send()?;
let status = res.status().as_u16();
let headers = res.headers().clone();
let raw = res.bytes()?;
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
verify(status, &headers, &raw, pinned)?;
let b: Value = serde_json::from_slice(&raw)?;
if b.get("clientNonce").and_then(Value::as_str) != Some(client_nonce.as_str()) {
bail!(Terminal);
}
Ok(())
}
// Call this when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
boolean logout(String base, String accessToken, String buildToken) throws Exception {
byte[] n = new byte[8];
SECURE_RANDOM.nextBytes(n);
String clientNonce = HexFormat.of().formatHex(n);
var body = MAPPER.writeValueAsString(
Map.of("accessToken", accessToken, "clientNonce", clientNonce));
// On a DPoP bound session, add a DPoP header over this URL with ath over the
// access token. Without one a strict deployment answers 401 dpop_required,
// the logout does not happen, and the seat stays held.
var req = HttpRequest.newBuilder(URI.create(base + "/v1/sess/logout"))
.header("Content-Type", "application/json")
.header("x-licentry-build", buildToken)
.header("x-licentry-protocol", "1")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
var res = client.send(req, HttpResponse.BodyHandlers.ofByteArray());
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
if (!accepted(res, PINNED)) return false;
JsonNode echo = MAPPER.readTree(res.body()).get("clientNonce");
return echo != null && clientNonce.equals(echo.asText());
}
<?php
// Call this when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
function logoutSession(string $base, string $accessToken, string $buildToken,
array $pinned): bool {
$clientNonce = bin2hex(random_bytes(8));
// On a DPoP bound session, add a DPoP header over this URL with ath over the
// access token. Without one a strict deployment answers 401 dpop_required,
// the logout does not happen, and the seat stays held.
$ch = curl_init("$base/v1/sess/logout");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
"x-licentry-build: $buildToken",
'x-licentry-protocol: 1',
],
CURLOPT_POSTFIELDS => json_encode([
'accessToken' => $accessToken, 'clientNonce' => $clientNonce,
]),
]);
$h = [];
collectHeaders($ch, $h);
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
if (!licentryAccepted($code, $h, $raw, $pinned)) {
return false;
}
$b = json_decode($raw, true);
return ($b['clientNonce'] ?? null) === $clientNonce;
}
struct LogoutAck: Decodable { let ok: Bool?; let clientNonce: String? }
// Call this when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
func logout(base: URL, build: String, accessToken: String,
pinned: [String: P256.Signing.PublicKey]) async -> Bool {
var bytes = [UInt8](repeating: 0, count: 8)
_ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
let clientNonce = bytes.map { String(format: "%02x", $0) }.joined()
// On a DPoP bound session, add a DPoP header over this URL with ath over the
// access token. Without one a strict deployment answers 401 dpop_required,
// the logout does not happen, and the seat stays held.
var req = URLRequest(url: base.appendingPathComponent("v1/sess/logout"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue(build, forHTTPHeaderField: "x-licentry-build")
req.setValue("1", forHTTPHeaderField: "x-licentry-protocol")
req.httpBody = try? JSONEncoder().encode(["accessToken": accessToken,
"clientNonce": clientNonce])
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
guard let pair = try? await URLSession.shared.data(for: req),
let http = pair.1 as? HTTPURLResponse,
accepted(http, body: pair.0, pinned: pinned),
let ack = try? JSONDecoder().decode(LogoutAck.self, from: pair.0)
else { return false }
return ack.clientNonce == clientNonce
}
// Call this when the user quits. maxConcurrentSessions defaults to 1, and a
// session that is never logged out holds its seat until the refresh window
// closes, which is days: the customer's own next launch is what gets evicted.
fun logout(base: String, build: String, accessToken: String,
pinned: Map<String, PublicKey>): Boolean {
val clientNonce = ByteArray(8).also { SecureRandom().nextBytes(it) }
.joinToString("") { "%02x".format(it) }
val body = JSONObject()
.put("accessToken", accessToken)
.put("clientNonce", clientNonce)
.toString()
val req = Request.Builder()
// On a DPoP bound session, add a DPoP header over this URL with ath over
// the access token. Without one a strict deployment answers
// 401 dpop_required, the logout does not happen, and the seat stays held.
.url("$base/v1/sess/logout")
.addHeader("x-licentry-build", build)
.addHeader("x-licentry-protocol", "1")
.post(body.toRequestBody(JSON))
.build()
client.newCall(req).execute().use { res ->
val raw = res.body!!.bytes()
// Returns 200 {"ok":true} with the nonce echo. A 204 response could not
// bind its signed empty body to this request.
if (!accepted(res, raw, pinned)) return false
return JSONObject(String(raw)).optString("clientNonce") == clientNonce
}
}
# Call this when the user quits. maxConcurrentSessions defaults to 1, and a
# session that is never logged out holds its seat until the refresh window
# closes, which is days: the customer's own next launch is what gets evicted.
#
# On a DPoP bound session, add a DPoP header over this URL with ath over the
# access token. Without one a strict deployment answers 401 dpop_required, the
# logout does not happen, and the seat stays held.
def logout(base, build_token, access_token, pinned)
client_nonce = SecureRandom.hex(8)
res = Net::HTTP.post(
URI("#{base}/v1/sess/logout"),
{ accessToken: access_token, clientNonce: client_nonce }.to_json,
'Content-Type' => 'application/json',
'x-licentry-build' => build_token,
'x-licentry-protocol' => '1'
)
# Returns 200 {"ok":true} with the nonce echo. A 204 response could not
# bind its signed empty body to this request.
status, body = verify!(res, res.body, pinned)
status == 200 && body['clientNonce'] == client_nonce
rescue StandardError
false
end
A new product enforces nothing, so turn the protections on next. Switch the protections on lists the product settings and the client checks each one needs.
How-to guides
One task each, in roughly the order you will meet them. Each guide links to the reference for the exact fields and limits.
Verify server responses
Verify each response before accepting it. Without this check, a local proxy or another intermediary can impersonate Licentry and return 201 to every activation. See response signature verification for a shorter setup guide.
The response signature
Every response body on /v1/sess/* is signed with ECDSA P-256, successes and errors alike, so a 403 is as trustworthy as a 201. Every session route answers with a body, including logout, tamper reports and integrity events, so every response carries both a signature and your echoed clientNonce. Those three return a body rather than 204 because a signed empty body is identical for every route and a captured one could be replayed as the answer to a different call. In production the API refuses to start without a signing key, so a body with no signature header is a failure condition, not a fallback path.
| Header | Contents |
|---|---|
X-Licentry-Sig | Base64 of the raw 64-byte r||s signature. Not DER. This is exactly the form Windows BCrypt verifies. |
X-Licentry-Sig-Ts | Unix seconds at signing time. |
X-Licentry-Sig-Kid | Which pinned key verifies this response. A selector only, and deliberately not part of the signed message, so a flipped kid just fails closed. |
The signed message is "${status}|${ts}|${sha256hex(body)}", hashed with SHA-256 and signed. The body hash is over the exact bytes you received. Parse the JSON after the check, never before, and never re-serialise the body to hash it.
Reject a response when its signature is missing.
If vendorResponseSigning is on and the account key cannot be loaded, the server returns an unsigned response. It does not substitute a key the client has not pinned. An attacker can also remove the signature header, so the client must reject both cases.
A routine such as if (response.has(SIG)) { check it } skips verification when the header is absent. Test that case explicitly.
The minimum correct verification, in this order. Nothing here is optional and nothing may be reordered.
raw = response.body_bytes # keep the bytes, not the parsed object
sig = response.header("X-Licentry-Sig")
ts = response.header("X-Licentry-Sig-Ts")
kid = response.header("X-Licentry-Sig-Kid")
# 1. present, and the right shape
if sig is empty:
fail_closed() # absent is a refusal, never a skip
raw_sig = base64_decode(sig)
if len(raw_sig) != 64:
fail_closed() # raw r||s, exactly 64 bytes, NOT DER
# 2. freshness, two sided
if abs(trusted_now_seconds() - int(ts)) > 300:
fail_closed() # one sided is defeated by moving the clock back
# 3. the kid selects the key. it is NOT part of the signed material
if kid not in PINNED_KEYS:
fail_closed() # a kid you do not pin is a failure, not a skip
# 4 and 5. build the canonical string, verify over THAT
canonical = str(response.status) + "|" + ts + "|" + sha256_hex(raw)
if not ecdsa_p256_sha256_verify(PINNED_KEYS[kid], canonical, raw_sig):
fail_closed()
# 6. the echo, before the status
body = json_parse(raw)
if body.clientNonce != the_nonce_you_just_sent:
fail_closed() # a valid signature on somebody else's answer
# 7. only now branch on response.status, and only now read a field
Verify the canonical string, not the body bytes alone. The signed message includes the status, so identical bodies returned with 200 and 403 have different signatures.
If verification fails, stop licensed functionality. Do not substitute a cached verdict or retry until a response parses. A deployment fault and an attack require the same fail-closed behaviour.
Pinning the response-signing keys
Fetch GET /v1/sess/response-sig-jwks at build time and compile the keys into your client. Fetching and trusting a key at runtime relies on the customer's TLS trust store, which they can change by installing a root certificate and running a proxy. Replacing a compiled key requires modifying the binary.
Signing-key rotation
Pin every key the JWKS returns in a map indexed by kid. During rotation, the server signs the same timestamp and body hash with two keys: the primary key in X-Licentry-Sig and X-Licentry-Sig-Kid, and the incoming key in X-Licentry-Sig-Next and X-Licentry-Sig-Kid-Next. Ship a build that pins both kid values, wait for customers to update, then promote the new key on the server.
Build the candidate list with (Kid-Next, Sig-Next) first when both headers are present, followed by (Kid, Sig). Verify the first candidate whose kid is pinned. If that verification fails, reject the response without trying another candidate; also reject it if neither key is pinned. Preferring the -Next pair lets the client use the incoming key before promotion moves it to the primary header.
The overlap pair is optional.
The server computes the second signature after the primary. If that step fails under load, it logs the failure and returns the primary signature alone. Select the primary pair when -Next is absent; do not reject a response solely because it lacks an overlap signature.
A vendorResponseSigning product never receives an overlap pair. Verify its single candidate.
Activate and heartbeat also return signingPublicKey, the offline grace verification key. It is separate from the response-signing key and lets the client follow offline-key rotation without re-activating. Accept it only after verifying the response signature, never as an independent trust root. Refresh does not return it, so send at least one heartbeat after each refresh (refresh).
The offline grace token
Pin the offline grace keys by kid at build time; never fetch and trust them at runtime. Follow the three steps in offline grace to select the correct key set and check the claims. Without the dev check, a copied token works on another machine for its full TTL, and sharing fresh tokens from each heartbeat can extend that use indefinitely.
Clock skew
Every time-based check on both sides has a tolerance, and the client's wall clock belongs to the user. The server allows about 30 seconds of skew on DPoP proofs; outside that, proofs are rejected for timing reasons and the fix is to resync and build a fresh proof, never to resend the old one. On your side, keep a monotonic reference alongside wall-clock time. If the wall clock jumps backwards between two heartbeats, that is either a timezone update or someone extending an offline window by hand, and stored grace tokens should be treated as suspect until a real heartbeat succeeds.
Device binding, caps and DPoP
Choosing device-hash inputs
The API checks that your device hash contains 64 hex characters; your client is responsible for deriving a stable value. A different hash on heartbeat or refresh revokes the session, returns 403 license_suspended and records a hardware mismatch against the licence. At activation, a changed hash counts as a second device: with the default cap of 1, it returns 403 too_many_devices until an HWID reset. These responses do not identify an unstable hash recipe as the cause.
Choose inputs that are readable without elevation on every run. Do not select inputs conditionally or substitute an empty value when permissions prevent a read. Windows disk hardware serials require an administrator handle to \\.\PhysicalDriveN; Linux /sys/class/dmi/id/board_serial and product_uuid are mode 0400, readable only by root. Using them can produce different hashes for elevated and ordinary runs, interrupting legitimate sessions and recording misleading sharing evidence.
ingredients = [ i1, i2, i3, i4, i5 ] # fixed count, fixed order, per platform
each ingredient, before joining:
read as bytes, truncate at 256
strip leading and trailing 0x00 0x09 0x0a 0x0d 0x20
any remaining byte outside 0x21 to 0x7e collapses the WHOLE ingredient to ""
lowercase, ASCII only
a failed read yields "", and the slot is never dropped
canonical = "licentry-dh-v1" + US + salt + US + join(ingredients, US) # US = 0x1f
device = sha256_hex(canonical).lower() # 64 lowercase hex
Keep a fixed slot for each input. A missing ingredient becomes the empty string and keeps its slot, so a machine where one read fails hashes the same as the same machine on a run where it succeeds. The 0x1f separator cannot occur in printable ASCII inputs, so it keeps their boundaries unambiguous. Non-ASCII inputs become empty to avoid differences in how APIs and locales encode OEM serials, such as those containing trademark symbols. The licentry-dh-v1 prefix identifies the recipe version for future migrations. Compile a product-specific salt into the binary so unrelated vendors do not compute the same device identifier on one machine.
| Slot | Windows | macOS | Linux |
|---|---|---|---|
| i1 | MachineGuid under HKLM\SOFTWARE\Microsoft\Cryptography, opened with KEY_WOW64_64KEY | IOPlatformUUID from IOPlatformExpertDevice | /etc/machine-id |
| i2 | SMBIOS Type 1 system UUID via GetSystemFirmwareTable | IOPlatformSerialNumber, same node | /sys/class/dmi/id/product_name |
| i3 | SMBIOS Type 2 baseboard serial, same call | hw.model via sysctlbyname | /sys/class/dmi/id/sys_vendor |
| i4 | GetVolumeInformationW serial for the volume holding the Windows directory | machdep.cpu.brand_string, absent on Apple silicon | /sys/class/dmi/id/product_family |
| i5 | ProcessorNameString under HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0 | reserved, always empty | model name of processor : 0 in /proc/cpuinfo |
These inputs do not require elevation. On Windows, KEY_WOW64_64KEY is required for i1: without it, a 32-bit process on a 64-bit OS reads the WOW6432Node redirect and gets no value, producing different hashes in x86 and x64 builds. On Linux, i1 may fall back to /var/lib/dbus/machine-id only when /etc/machine-id does not exist. Do not fall back after a read error, which may be temporary.
Use GetSystemFirmwareTable rather than WMI for i2 and i3. Win32_ComputerSystemProduct.UUID returns the same value, but it needs the WMI service, costs 100 ms or more, initialises COM, and returns nothing against a corrupt repository.
| Refuse these | Why |
|---|---|
| Any disk hardware serial, on any platform | Requires administrator access on Windows or root on Linux, so elevated and ordinary runs can produce different values. |
board_serial, product_serial, chassis_serial, product_uuid, dmidecode | Require root on Linux. |
| Any MAC address, on any platform | A dock can change the primary network adapter. On several Mac models, Thunderbolt Ethernet becomes en0. MAC addresses can also be spoofed. |
| Hostname, username, domain | User-editable. macOS can also rename the host on some DHCP networks. |
Device instance IDs, PnP IDs, Win32_NetworkAdapter | Can change after a driver update. |
| GPU identifiers | A laptop may disable its discrete GPU on battery power. |
| Display EDID | Changes when the lid closes on a dock. |
/proc/sys/kernel/random/boot_id | Changes on every boot. Do not confuse it with machine-id. |
IORegistry boot-uuid, boot-args, /proc/self/cgroup, the root filesystem UUID | Can vary by boot, container, LVM or overlayfs configuration. |
| A random UUID your app wrote to a file on first run | Copying the file copies the identity, allowing another machine to present the same device hash. |
| Environment variables, or anything the user can type | User-editable. |
| TPM endorsement key, machine SID, OS serial number | Elevation on some Windows SKUs, and each changes on a TPM clear, a sysprep or a reactivation. |
Use the same recipe in virtual machines and containers. Preserve values such as an all-zero or all-ff firmware UUID, or an empty Apple silicon VM serial; a shared constant adds no entropy, but special-case substitutions can make the result inconsistent. Containers need a stable identity supplied by the deployment: Docker and Podman create a new /etc/machine-id unless it is bind-mounted, and Windows containers create a new MachineGuid per start. WSL2 has its own machine-id, separate from the Windows host, so Windows and Linux builds count as two devices on one physical machine at the default cap of 1.
Test device-hash stability before shipping. Compare the value before and after a reboot, docked and undocked, on mains and battery, and elevated and as an ordinary user within the same boot. Remove any input that causes a difference. A startup self-test that computes the hash 64 times and refuses to run if the results differ takes about 3 ms and can catch variation within a run; it does not replace those comparisons.
Send identical lowercase hex on every call. The API normalises the hash, but the client derives its engine parameter key from its own bytes (why casing matters).
Keep a diagnostic command that prints the composed hash and the sha256 of each input, never the raw values. Comparing its output across runs helps identify a changed input without putting hardware serials in support tickets.
Migrating a device-hash recipe
A new recipe changes the hash for every customer who installs it. At the default cap of 1, the old hash already occupies the licence's device slot, so activation with the new hash returns 403 too_many_devices. Increase capacity before releasing the new build.
- Raise the device cap to 2 on the product. An account owner or admin must do this while signed into the dashboard. API keys cannot change this runtime protection and receive
403 policy_change_forbidden. Complete this step before distributing the build. - Release the new recipe with a new version prefix. The next activation binds the new hash in the second slot. The old hash remains in the first slot until you clear it.
- After your telemetry confirms adoption, clear stale rows and return the cap to 1.
GET /v1/vendor/licenses/:id/deviceslists both hashes, andDELETE /v1/vendor/licenses/:id/devices/:deviceIdunbinds the old one. Alternatively,POST /v1/vendor/licenses/:id/hwid-resetclears both; the next activation reclaims the slot for the current hash.
For bulk resets, POST /v1/vendor/licenses/bulk accepts {"ids": [ … ], "action": "hwid-reset"} for up to 500 licences. It runs a single-licence reset for each id, including the per-licence cooldown of one hour by default. A licence reset within that hour counts as a failure. The response returns only applied, failed and outOfScope counts, not individual failed ids, so retain your list for retries. This route requires licenses.manage; a support key with only the single-reset scope, devices.reset, cannot call it.
Reset only after the customer updates. A reset clears device rows and increments the revocation version, forcing live clients to re-activate on their next call. An old build will rebind its old hash and occupy the slot you just cleared.
Both reset methods interrupt the session once. A full reset revokes it and the next call returns 401 invalid_session. A single unbind leaves it in place but increments the revocation version, so the next call returns 401 stale_revocation. In either case, the client must re-activate.
Device cap and concurrent session cap
They are easy to confuse and they fail in opposite ways. Both are set on the product, and the concurrent one is covered in full at switch the protections on.
- The device cap is per product and defaults to 1. Activating from a machine beyond the cap is refused with
403 too_many_devices, and anactivation.blockedwebhook fires. Devices cleared by an HWID reset stop counting, and re-activating on the same hardware afterwards reclaims its old slot rather than consuming a new one. - The concurrent session cap defaults to 1 and does not refuse anything. A new activation evicts the oldest session by last heartbeat. The evicted device sees
401 invalid_sessionon its next beat and re-activates, which evicts the other one. That is deliberate (why).
What sharing looks like from the server
GET /v1/vendor/licenses/:id/insights returns named indicators with severity levels and raw counts, plus a verdict of none, possible or strong. It does not write enforcement state or terminate sessions. Review the timeline before choosing to suspend, revoke or reset an HWID. The licence console in your dashboard uses the same information.
The hardening guide, available after sign-in, lists the indicators and their thresholds. Those thresholds are not published here because they could help someone keep sharing activity below the detection limits.
Device-bound sessions with DPoP
Without DPoP, anyone who obtains the access token from memory, a log or an unprotected file can use it as a bearer credential. With DPoP, requests also need a signature from the device's private key. Enable requireDpop to require this binding.
Generate a P-256 keypair in the strongest store the platform offers, such as TPM-backed CNG, Keychain, Keystore or libsecret. Register the public JWK at activate as a JSON string. A malformed or unimportable key returns 403 dpop_jwk_invalid; the server does not create an unbound session instead. Once bound, the session requires proofs on heartbeat and refresh and cannot be unbound by the client.
Per request, sign a fresh ES256 proof with the claims listed under DPoP proofs. The server remembers each jti for 150 seconds and rejects a repeat, so never reuse a proof on a retry. Build a new one.
The jti replay memory has one known limitation, described on the hardening guide. It does not change how you build the client.
Switch the protections on
Protection requires both product settings and client-side checks. Use the table for the current defaults, then follow each control's setup instructions and client requirements.
| Protection | Where | Default | Purpose |
|---|---|---|---|
requireBuildToken | Product setting | off | Retiring a leaked release. |
requireDpop | Product setting | off | Use of copied session tokens or installation folders. |
requireDpopBody | Product setting | off | Request-body changes made by a local proxy without changing the proof. |
maxConcurrentSessions | Product setting | 1 | Simultaneous use of one licence. |
engineParams | Product setting | unset | Requiring session data for correct operation. |
payloadKey | Product setting | unset | Requiring a session to obtain a file-decryption key. |
vendorResponseSigning | Product setting | off | Separating your response-signing key from the shared platform key. |
minProtocolVersion | Product setting | 0 | Excluding older clients before enabling new controls. |
| Response signature check | Your client | client implementation | Rejecting responses from a fake licensing server. |
clientNonce echo | Your client | client implementation | Rejecting replayed signed responses. |
| Heartbeat nonce chain | Your client | client implementation | Rejecting replayed heartbeat sequences. |
The product settings live in one place: Products, your product, then the Runtime protection and Engine parameters panels, which is /dashboard/products/<id>#protection. That page shows a score so you can see at a glance what a product enforces. Build tokens are registered separately under Client builds. Everything on that page is also reachable through PATCH /v1/vendor/products/:id, documented in the Vendor API reference. Changing a runtime protection is restricted to the account owner and admin seats, so a leaked developer key cannot turn the defences off.
requireBuildToken
Requires the x-licentry-build header for session calls, so a revoked release cannot keep working by omitting its token.
Register the release under Client builds, embed the returned lb_… token and then tick Require a build token on the product. The API routes are POST /v1/vendor/client-builds to mint and PATCH /v1/vendor/products/:id with { "requireBuildToken": true } to enable. Pass productId when minting to restrict the token to that product.
Send x-licentry-build: <token> on all five session routes: validate, activate, heartbeat, refresh and logout. Treat 426 upgrade_required as terminal for that binary and prompt for an update.
Register the build and release a client that sends the header before enabling enforcement. Until it is enabled, a missing header is accepted; enabling it before customers have updated can lock them out.
requireDpop
Requires sessions to be bound to a private key on the customer's machine. A copied token or installation folder alone is then insufficient to use the session.
Release a client that sends the key before ticking Require proof of possession on the product, or using PATCH /v1/vendor/products/:id with { "requireDpop": true }. Enabling this also refuses renewal of existing unbound sessions, which must re-activate.
Generate one P-256 keypair per install in the platform keystore. Send its public half as dpopPublicJwk, a JSON string, at activate, then sign a fresh ES256 proof for every heartbeat, refresh and logout. See DPoP proofs for the claims. With enforcement on, a missing key at activate returns 403 dpop_required; a malformed key returns 403 dpop_jwk_invalid.
Keep the private key in TPM-backed CNG, Keychain, Keystore or libsecret, not in a key.pem beside the binary where it can be copied with the installation. For ath, hash the access token on heartbeat and logout, and the refresh token on refresh.
requireDpopBody: request body binding
The htm, htu and ath claims bind a proof to the method, URL and token, but not the body. A local proxy could change deviceHash or seq without invalidating that proof. The bh claim binds it to the body too.
Release a client that sends bh, then use PATCH /v1/vendor/products/:id with { "requireDpopBody": true }, or tick the control on the product. The default is off for compatibility with clients that omit this claim.
Add bh, base64url(SHA-256(body bytes)), to every proof using the exact bytes you will send. With this setting on, a bound heartbeat or refresh without bh returns 401 dpop_bh_required. A mismatched bh returns 401 dpop_bh_mismatch even when the setting is off.
Serialise the body once, hash that string and send the same string. Serialising it again may change key order or spacing and invalidate the proof.
maxConcurrentSessions
Limits live sessions per licence. When a new activation exceeds the limit, the server evicts the session with the oldest last heartbeat.
Set Concurrent sessions on the product to a value from 1 to 20, or use PATCH /v1/vendor/products/:id with { "maxConcurrentSessions": 1 }. Leave it empty to inherit the deployment default of 1.
An evicted client receives 401 invalid_session. Re-activate once with backoff, as this can happen when a customer moves to another machine.
The cap evicts an existing session instead of refusing the new activation. Two clients sharing a key can repeatedly evict each other; tight re-activation loops can then trigger a rate-limit ban. The separate device cap refuses activation with 403 too_many_devices.
engineParams
Delivers encrypted values your software needs to run. The client must complete activation to obtain the decryption key, so removing a licence-check branch alone does not supply those values.
Enter a JSON object of up to 16 KB in Engine parameters on the product, or use PATCH /v1/vendor/products/:id with an engineParams object. It is sealed at rest under your account's key and cannot be read back through product management, so retain your own copy. Submit an empty box or pass null to clear it.
Read engineParams from activate, heartbeat and refresh, derive the key as follows, and pass the decrypted values to your engine:
engineKey = HKDF-SHA256(
ikm = accessToken bytes, # UTF-8, the CURRENT token
salt = deviceHash bytes, # LOWERCASE hex, what the server salts with
info = "am-engine-params-v1",
len = 32)
blob = base64_decode(response.engineParams)
iv = blob[0 .. 11] # 12 bytes
tag = blob[12 .. 27] # 16 bytes
ct = blob[28 .. ]
config = json_parse(aes_256_gcm_open(engineKey, iv, tag, ct)) # throws on tamper
The mistake. Sealing a boolean. The example below shows a parameter set that adds no protection and one that does.
# BAD. Every one of these is a value the client checks and then discards.
{
"licensed": true, # a sealed boolean is still a boolean
"tier": "pro", # one string compare to patch
"expiryCheck": true, # the program runs fine without it
"maxExports": -1 # so does this
}
# An attacker opens this ONCE on a machine with a real licence, writes the four
# values into the patched binary as constants, and never needs a session again.
# This makes the check slower to find; the program still runs without it.
# GOOD. Every one of these is a value the program cannot invent.
{
"assetKeyId": 7, # selects which shipped asset pack to decrypt
"assetKey": "b91c…", # the AES key for that pack. No key, no assets.
"tickMs": 8, # the loop rate the physics was tuned against
"curve": [0.0, 0.13, 0.41, 0.78, 1.0], # coefficients, not settings
"solverSeed": "4f2a…" # seeds a table the engine reads every frame
}
# There is no branch to invert. Without the blob the asset pack does not decrypt,
# the solver produces wrong numbers, and the product does not work.
The test: if your program still produces correct output with the blob replaced by an empty object, the parameters protect nothing. Use coefficient tables, timing curves, model or shader constants, the decryption key for an asset pack you ship encrypted, or the endpoint of a service that does the valuable work, and never a verdict about the licence.
What _session is for
When you open the blob you get your own fields exactly where you put them, plus reserved keys alongside them. Every reserved key starts with an underscore, so a client that rejects unknown fields has to skip that prefix rather than list the ones that exist today:
{
"assetKeyId": 7,
"curve": [0.0, 0.13, 0.41, 0.78, 1.0],
"_session": {
"secret": "3f9c…", # 64 hex, THIS session, THIS beat
"sessionId": "7f2e…",
"expiresAt": "2026-07-27T12:20:00Z", # end of the current access window
"epoch": 3 # increments when you edit the set
},
"_mark": "a1b2c3d4e5f6…" # 32 hex, opaque, see below
}
The product's own parameters are identical for every customer until you change them, so a buyer can decrypt and publish them. The reserved _session.secret varies by session and heartbeat sequence and is delivered only inside the blob. Its value at seq: 2 differs from its value at activate. Refresh resets the sequence, so the first value after refresh matches the first value after activation.
Read the secret from each newly decrypted blob. Caching it at activation leaves your engine using the wrong value on the second heartbeat. Rotation applies to every product on every plan and cannot be disabled; the client must handle it.
Use the secret to derive state your engine needs, such as a table, an asset decryption key or a value used in its output. The engine must depend on the current secret for an older dump to become unusable. Check expiresAt to reject stale data offline, and epoch to detect changes to the parameter set after a leak. Licentry supplies these values but cannot enforce or inspect how your engine uses them.
_mark is an opaque 32-character hex value derived from the licence that received the blob. It is not a licence id and only Licentry can resolve it, so it can remain in a debug dump sent to support. It lets the platform identify the licence behind a published parameter dump. Preserve it when re-serialising, without depending on its current length or format.
Decryption requirements
- The blob is re-sealed on heartbeat and refresh using the current access token. Re-derive the key each time; do not cache the decrypted config.
- Use the lowercase device hash bytes as the HKDF salt. The server normalises the hash before sealing: activate and heartbeat use the request value, and refresh uses the value stored at activate. Uppercase input therefore does not cause a server refusal, but deriving a client key from uppercase bytes produces the wrong key. Send lowercase hex and derive from those same bytes.
- A product without configured parameters omits
engineParamswithout returning an error. If your engine requires the blob, treat its absence as a configuration failure and stop licensed functionality.
payloadKey, the protected payload
Encrypt a file your program needs and configure Licentry to release its key only inside a live session. A copy that never activates cannot obtain the key through the API.
Use a key you generate to encrypt an asset bundle, model, level data, lookup table or required function constants. Enter it under Protected payload key on the product page. Licentry seals it under your account key and never displays it again. The session delivers it as a reserved field in the engine parameters blob:
{
"yourField": "...",
"_session": { "secret": "...", "expiresAt": "...", "epoch": 3 },
"_mark": "a1b2c3d4e5f6…",
"_payload": {
"version": 4,
"sealed": {
"alg": "ECDH-ES+A256GCM",
"epk": { "kty": "EC", "crv": "P-256", "x": "...", "y": "..." },
"ct": "base64( iv(12) | tag(16) | ciphertext )"
}
}
}Handle both payload forms, preferring sealed when present. A session with a usable DPoP key receives _payload.sealed and no _payload.key. The outer blob uses a key derived from the access token in process memory; the sealed payload also requires the DPoP private key. Store that private key on the device, using a TPM or secure enclave to prevent extraction.
To open sealed, perform ECDH with your DPoP private key and epk, then derive HKDF-SHA256(sharedSecret, salt = empty, info = "licentry:payload-ecdh:v1|" + epk.x + "." + epk.y, 32). Decrypt ct with AES-256-GCM, splitting it as iv(12) | tag(16) | ciphertext. This uses the same P-256 curve as DPoP and the same AEAD as the outer blob. If sealed is absent, read _payload.key directly. The resulting key decrypts your files and is delivered only through a session.
"_payload": { "key": "the key you configured", "version": 4 }The plaintext form is returned only when the session has no usable DPoP key, usually because the client omitted dpopPublicJwk at activation, or rarely because a stored key cannot be imported. Handle both forms even if you expect only one; the session determines the form.
To restrict delivery to bound sessions, enable Only release it to a machine-bound session (payloadRequiresDpop in the API). Release a client that sends dpopPublicJwk from the machine's keystore before enabling it, or no session will qualify. Qualifying sessions receive only the sealed form, so a client that reads _payload.key alone will fail. Copying the installation folder without its device private key does not provide access to the payload.
After a leak, save a new key to increment version, then re-encrypt and release the assets. Clients can use the version change to detect that their previous key is stale.
A missing key must not enable licensed functionality. Both an unconfigured product and an ineligible session receive a blob without _payload. The response deliberately does not distinguish them, to avoid disclosing which control prevented delivery.
A customer with a live session can still extract the decrypted key from memory and publish it. Encryption requires an attacker to extract and redistribute the key instead of bypassing one check, and rotation requires repeating that work. The version identifies the affected release; it does not prevent extraction.
vendorResponseSigning, your own signing key
Signs product responses with your account's key instead of the platform's shared key. A client that pins your key will not accept responses forged with a compromised shared key.
While vendorResponseSigning is off, pin the deployment keys from GET /v1/sess/response-sig-jwks. Once enabled, the product uses only your account's key from GET /v1/vendor/keys/<your account id>/response-sig-jwks. Pin both sets in the release that spans the change so clients can verify responses before and after it.
Enable it in this order to avoid breaking installed clients:
- Pin your account's keys from
GET /v1/vendor/keys/<your account id>/response-sig-jwks, bykid, alongside the deployment keys your client pins today. - Ship that client and wait for your customers to update.
- Tick the box on the product page, or
PATCH /v1/vendor/products/:idwith{ "vendorResponseSigning": true }. - Drop the deployment keys from your pin set on a later release, once nothing in the field still needs them.
Product responses, including refusals, carry your kid without a platform overlap signature. The platform rotation key is not used to verify your account's responses.
Register build tokens with productId. The server selects the signing key from the supplied build token and its product, not from the licence, so approvals and refusals use the same kid, including requests with unknown licence keys. If a token has no product binding and the body omits product, an unknown key receives the deployment kid, which discloses that the key was not found.
If the account key is unavailable, the server returns unsigned responses instead of using the platform key. Reject these responses just as you would any response without a valid signature from a pinned key.
minProtocolVersion: minimum client version
Refuses activation when the client's declared protocol version is below the product minimum. This lets you retire older clients before enabling controls they do not support.
Release a client that sends X-Licentry-Protocol: 1 on every call, then set the minimum to 1. Version 1 clients send clientNonce on activate and heartbeat, echo serverNonce on heartbeat and send deviceHash on refresh, as the current samples do.
The server reads this header only at activation and trusts the declared version. It does not use the version number to require those fields; they remain optional in the schema and are enforced by their individual rules. The minimum excludes older clients but cannot prevent a modified client from declaring a higher version.
Raising the minimum does not interrupt existing sessions. New activation attempts below it receive the generic 400 activation_failed response (why).
Response signature verification
Your app checks Licentry's signature before accepting a response. This lets it reject forged replies from a fake licensing server.
Signing is enabled server side on /v1/sess/* for successes and errors. Fetch GET /v1/sess/response-sig-jwks at build time and compile every returned key into the binary, indexed by kid.
Verify before parsing JSON. Check "${status}|${ts}|${sha256hex(body)}" using the exact response bytes and a two-sided timestamp window. Reject a missing signature header. Follow the complete sequence in verifying the server.
Do not fetch and trust keys at runtime, since the customer's machine controls its TLS trust store. Keep status handling separate from verification: a verified 403 remains a refusal. Avoid if (header present) { verify }, which skips unsigned responses; see the missing-signature guidance.
Nonce echo and heartbeat chain
clientNonce binds a signed response to the current request, preventing reuse of a captured signed 200. serverNonce links each heartbeat to the previous response, preventing replay of a recorded heartbeat sequence.
Neither needs a product switch. Both fields are supported by the protocol and included in the signed response body.
Send a fresh random clientNonce of at least 8 printable characters on every validate, activate, heartbeat, refresh and logout. Reject a missing or different echo before reading the status. On heartbeat, send an empty serverNonce for the first beat, then the value from the preceding response.
Sending a nonce without comparing its echo does not prevent replay: a captured signed 201 can still be reused. Once the heartbeat chain has started, omitting serverNonce counts as a mismatch. See the nonce pair for retrying a heartbeat after a lost response.
How many retries the grace allows, and what the chain looks like when two copies share one token, are covered on the hardening guide in your dashboard. Strict enforcement is a deployment setting, LICENSE_NONCE_STRICT, which is off in the code default and on for Licentry Cloud: there, a mismatch that has spent the retry grace is 401 nonce_mismatch and the beat does not land. Build for the strict behaviour whichever deployment you are on, because a client that is correct under it is correct under both.
Recovery from 401 nonce_mismatch is re-activation, not a refresh; the reason is in the failure table.
Offline grace
When configured, activate and every heartbeat return an offlineGraceJwt, a short-lived signed offline entitlement your app interprets locally while the network is gone. Key type is ES256 / P-256, so a Windows client verifies with native BCrypt.
Step 1: pin the correct key at build time
The two JWKS endpoints serve different keys. Select the one for the licences your client uses.
- Licences belonging to your account use its key from
GET /v1/vendor/keys/<your account id>/offline-grace-jwks. Pin this set. If the key is unavailable, the response omitsofflineGraceJwt; there is no fallback to the shared platform key. GET /v1/sess/offline-grace-jwksserves the deployment key for licences without a vendor account. It does not sign your account's licences.
Fetch the set at build time, compile every returned key into a kid to key map, and select the verifier using the JWT's kid. Never fetch and trust a key at runtime: the offline path must work without network access and must not trust a key supplied by the machine's owner.
Choose Rotate to publish a new key alongside the current one without using it to sign. Re-fetch the set, release a client that pins both keys and wait for customers to update. Only then choose Promote, which retires and removes the old key and starts signing with the new one. Promoting too early leaves clients that pin only the old kid unable to verify fresh grace tokens after their next heartbeat until updated.
Step 2: verify, then enforce four claims
Verify the ES256 signature against the pinned key first. Only then read the claims, and enforce all four before you honour the token:
devequals the device hash you compute locally, compared case-insensitively.exphas not passed.rvmatches the revocation version you last saw. A bumped version means the licence changed under you.prodis the product this binary is for, andtypislicentry_offline_grace.
There is no token without dev. The signer takes the device hash as a required argument and always writes the claim, so a token that lacks it did not come from us and must be refused rather than treated as an older, unbound grant.
Skip the dev check and the token becomes a bearer entitlement: copying the app-state directory to another machine keeps working offline for the full TTL. The TTL bounds how long a revoked licence runs offline; the dev check is what stops cross-machine sharing.
Step 3: account for offline limits
An issued grace token cannot be revoked before expiry, and offline expiry checks rely on a clock the customer controls. The platform-wide TTL limits this exposure; it is not a per-product setting. Do not extend it with additional client-side tolerance.
Grace token claims
| Claim | Meaning |
|---|---|
typ | "licentry_offline_grace" |
lic | Licence id (UUID). |
prod | Product slug. |
rv | Revocation version. Enforce it in app policy. |
dev | Device hash (lowercase hex). Compare before honouring. |
Live native loading
Live native loading delivers part of your program to memory after authentication instead of including it in the installed files. It is optional, off by default and enabled per product under Live native loading in the dashboard. Licentry's loading path does not write a durable decrypted copy.
Upload an artifact to a named slot, such as core. Licentry encrypts and stores it. A live session can request a short-lived, single-use grant and decryption key, fetch the ciphertext from the edge, decrypt it in memory and pass the buffer to your loader. The grant expires in about two minutes and cannot be reused. For device-bound sessions, the content key is sealed to the device keypair, so a stolen access token alone cannot decrypt the artifact.
A copied installation folder does not contain the artifact. Fetching it requires a licence that currently passes validation. Publishing a new version also changes its encryption key; recovered content from an older version does not provide the current artifact.
Decrypted artifacts can be extracted from memory. Your loader runs on the customer's machine, where someone can dump the decrypted bytes. A successful dump provides a permanent copy of that version without further licence checks or API access. Your mapping code is responsible for keeping it off disk, and that does not protect it in RAM. Describe this as making extraction harder and requiring new work for later versions, never as preventing extraction.
Watermark and trace and Rotate to expire are optional. Watermarking stamps a licence-specific copy with a marker only Licentry can resolve. It requires a binary built against the Licentry client; the dashboard refuses to enable it for an incompatible binary. Rotate to expire means publishing fresh versions on a schedule so an extracted copy does not provide later versions.
Artifacts are limited to 48 MB, the watermarking limit. Each licence may fetch 30 times per hour and 200 times per day, counted per launch rather than per download. Every fetch for the same licence and version returns identical bytes. See POST /v1/sess/artifact-grant for the request and response formats.
Failure handling
Handle each response according to the table. Keep retryable transport failures separate from terminal licence refusals.
| Response | What happened | What your client does |
|---|---|---|
403 session_killed | This session was terminated on purpose, from the dashboard, the API or the bot. Carries a reason. | Stop. Do not retry, do not re-activate. Drop to the unlicensed state or exit. Log the reason, show the user something generic. |
401, no error field | A bare string body. The Authorization: Bearer header was missing or blank, so the request was refused before any lookup and there is no code to read. | Fix the missing or blank header. Re-activation does not correct this client error. |
401 invalid_session | No session for that token, or the session was revoked for an ordinary reason, or the seat was lost to the concurrency cap because an activation elsewhere took it. | Re-activate once, with backoff. Never in a tight loop: that is how a shared key turns into a rate-limit ban. |
401 stale_revocation | The licence changed underneath the session: revoke, freeze, or an HWID reset bumped the version. | Stop the licensed path immediately, then re-activate and honour whatever comes back. Do not coast on cached state. |
401 expired, session window | The session's own access or refresh window lapsed. | Refresh. Re-activate only if the refresh is also refused. |
401 expired, licence validUntil | The licence itself ran out. Same wire code, different meaning, and the body does not tell them apart. | Terminal. Refresh fails too, and activate answers 400 activation_failed. Try the refresh once; when that also refuses, stop and direct the user to you instead of re-activating in a loop. |
401 revoked | The licence was revoked. Arrives on heartbeat and refresh. | Terminal. Re-activation cannot succeed. Stop and show a generic message. |
401 nonce_mismatch | The heartbeat nonce chain broke and the retry grace is spent. Strict deployments, which includes Licentry Cloud. | Re-activate. Refreshing does not fix it: the chain is deliberately carried across a refresh, and the retry path needs a seq that the first beat after a refresh can never have. |
401 refresh_token_stale | A rotated refresh token was presented again. Either you retried a refresh whose response you lost, or a second copy is running from the same state. | Use your newest stored pair. If that fails, re-activate. Do not loop: the two explanations look identical to us and only the count separates them. |
403 license_suspended | Frozen, flagged, or the session was cut because the device hash did not match the one it was activated with. | Stop. Direct the user to your support. Re-activating in a loop will not help and looks like abuse. |
403 too_many_devices | Every device slot on the licence is in use. | Stop and explain that the key is on another machine. Your support path is an HWID reset. |
400 activation_failed | Unknown, expired, revoked or stale key. Deliberately indistinguishable. | One generic message. Do not branch on it, do not auto-retry, do not guess in the UI. |
426 upgrade_required | The build token is unrecognised, retired, or superseded by a newer pristine build, on any session route. A missing token gives 426 only on heartbeat and refresh; on activate and validate it folds into the generic refusal (see activate). | Prompt the user to update. Retrying with the same binary cannot succeed. |
400 device_required | A refresh arrived with no deviceHash, on a deployment that requires it or for a DPoP-bound session. A 400 rather than a 401: nothing was revoked and the session is still there. | Add the field and refresh again. Send the same hash you sent at activate, lowercase and byte-identical. Retrying the same body cannot succeed. |
409 stale_seq | You sent a sequence number the server already has. | Set the next value to stored + 1 and continue. Not fatal. |
409 seq_gap | You jumped more than 8 ahead. | Refresh, then restart at seq: 1. |
409 nonce_raced | Two of your heartbeats were in flight at once. | Serialise heartbeats. Retry after the in-flight one resolves. |
401 dpop_required and every 401 dpop_* | Proof missing or rejected: timing, wrong URL, wrong token hashed, or a reused jti. | Build a fresh proof and repeat the same beat: same seq, same serverNonce. Do not re-activate, and never resend a proof. On timing errors resync the clock first. |
400 invalid_jwk_json, jwk_not_p256, jwk_import_failed | The DPoP key stored for this session is unusable. A 400 rather than a 401, because these three codes are not prefixed dpop_ and fall past the route's DPoP branch. | Generate a fresh keypair and activate again. The stored key cannot be repaired by retrying this session; a timed retry loop will continue until the refresh window expires. |
429 | Rate limited. | Honour the RateLimit-* headers and back off with jitter. |
503 | The API or its database is not ready. | Back off and retry. Fall through to your offline policy, not to an unlicensed-but-running state. |
Handle each 401 by its error field. On dpop_*, correct the proof without discarding a healthy session. On expired, try refresh first to avoid an unnecessary device registration and activation rate-limit charge. Repeated activation attempts cannot recover terminal failures and may trigger abuse controls.
Keep session_killed separate from invalid_session. The first means someone deliberately terminated the session, so stop. The second means the session is no longer usable, often after activation on another machine, so re-activate once with backoff.
Replenishing the heartbeat retry budget
After a lost heartbeat response, resend the identical body (how retries work). Only refresh replenishes this retry budget; a successful heartbeat does not. Schedule refreshes instead of waiting for an error, or lost responses across a long session can exhaust the budget. The next lost response then produces 401 nonce_mismatch and requires re-activation with a securely stored licence key or one the customer re-enters. The hardening guide lists the exact budget.
Network failures
A timeout does not establish whether a licence is valid or revoked. Handle transport failures separately from licensing responses.
- Distinguish transport failures (DNS, connect, timeout, TLS) from authenticated verdicts. Only a verified, signed response is a verdict.
- Fall through to the offline grace token if you have a valid one, with
dev,exp,rvandprodall enforced. If you do not, degrade gracefully, and be clear in the UI about what is happening and when it runs out. - Retry with exponential backoff and jitter. Do not hot-loop a dead endpoint: you will hit the rate limiter and turn a temporary outage into a longer one.
- The moment connectivity returns, heartbeat. That is what re-syncs the revocation version, delivers a fresh grace token and closes the offline window early.
Tamper resistance in your client
The server verifies the licence, but your client must enforce the result. These techniques can make licence bypass harder; none prevents a determined attacker from modifying their own copy (threat model). Start by verifying signatures and checking nonce echoes, then use session data in functionality your program requires.
1. Avoid a single licence boolean
An attacker can patch a single value that enables licensed functionality, whether it is a register, field or global. Make correct output depend on data from the session, so changing that value alone is insufficient.
# WRONG. One conditional jump stands between the attacker and your product.
if (session.valid) {
unlockFeatures();
}
# ALSO WRONG. A single variable set once and read everywhere is one byte to patch,
# or one memory write to freeze.
g_licensed = session.valid;
# WRONG IN A SUBTLER WAY. The verdict is centralised, so there is exactly
# one function to make return true.
bool IsLicensed() { return g_session != null && g_session.valid; }
# RIGHT. The data the program needs only exists if the session was real.
params = openEngineParams(session.accessToken, deviceHash) # AEAD, fails closed
engine.init(params.tickMs, params.curve, params.tables) # no params, no engine
2. Use required session data
When configured, activate, heartbeat and refresh return engineParams, an AES-256-GCM blob keyed from the live session's access token. The engine parameters guide covers setup, HKDF derivation and examples of useful and ineffective parameter sets.
Removing the licence check does not provide an access token or the key needed to decrypt the blob. GCM rejects modified ciphertext, and the response signature prevents substitution in transit.
The server re-seals the blob on every heartbeat and refresh. Re-derive its key each time so the engine uses current session data and can receive parameter changes while running.
Choose required values that cannot all be recovered from one run with a valid licence. If a single memory dump supplies every value the engine will ever need, the protection only makes the initial bypass harder. Use the test in engine parameters and make the engine depend on the current _session.secret.
3. Check throughout the session
A startup-only check can be bypassed once for the rest of that run. Use the heartbeat schedule to repeat checks, including before operations such as saving a document, exporting or invoking a licensed feature.
4. Avoid one shared licence verdict
A shared LicenseManager.IsValid() gives an attacker one function to patch. Where practical, make separate licensed operations depend on session-derived data. This adds complexity, so restrict it to the functionality that needs protection.
5. Tamper and debugger detection
Integrity checks and debugger detection can identify casual tampering and report it, but an attacker can also patch the detector. Avoid using one detection boolean to control the whole application. An immediate exit() exposes exactly when a check ran; less direct changes in behaviour are harder to associate with a particular check.
Report detections through security-event and tamper-report. Tamper reports reach your webhook endpoints as tamper.reported, without screenshot images. Images are sent only to your configured Discord log webhook on Studio; otherwise they are discarded. Capture only what you need and tell customers about the collection. Reporting while continuing to run lets you decide on a response outside the client and makes the detector harder to locate.
6. Obfuscation
Obfuscation slows analysis but is reversible. Apply it selectively to engine parameter use, signature verification and the device-hash recipe. Whole-program obfuscation can reduce performance, make debugging and crash reports harder, and trigger antivirus false positives. Packers often add little protection because unpacking is automated, while the packer itself can trigger antivirus detection.
7. Enforce server-side capabilities on the server
Where a licensed capability can run on your server, require a live session there and use the client to display its results. Modifying the binary cannot remove a check enforced by your backend. This option may not suit offline tools.
Before serving paid resources from your backend, check the licence and live session through the Vendor API. Do not trust a client's claim that it is licensed, and keep the API key on the server.
8. Account for the offline window
The offline grace TTL is one platform setting for every licence on a deployment. There is no product field or PATCH /v1/vendor/products/:id option for it. Licentry Cloud uses 72 hours to allow a single machine to keep working through a weekend outage.
A revoked licence can continue using an issued grace token until it expires, including if the customer blocks Licentry's hostname. Plan for that delay; anything that must stop sooner needs a control other than revocation. Check the token's dev claim to prevent use on another machine. Contact support if your product needs a different window.
9. Keep activation errors generic
Failed activation responses conceal the reason with a common body and padded timing (why). Preserve that in your UI, logs and support templates. Use a message such as "We could not activate this key" rather than disclosing expiry or validity details that help someone classify stolen keys.
Client-side protection has limits. Someone who controls the machine and binary can eventually bypass local checks. These measures aim to increase that effort, limit reuse as parameters change and licences are revoked, and provide evidence of key sharing.
The hardening guide explains which activity Licentry can detect, what remains invisible and how each control can be bypassed. Use it to decide where to spend development time.
Account security
Protect your vendor account as well as the client. Account access can let someone change licences or integration settings without bypassing the application.
API keys are a server-side credential
A vendor API key (lk_live_ plus 40 characters) can issue, revoke, suspend and extend licences and reset devices, according to its scopes. Keep it on your servers: never in a desktop binary, mobile app, web page, shipped config file or public repository. Your distributed client uses the session endpoints and its build token, and never needs an API key for anything. Only a hash is stored, so we cannot show you a key again after it is created, and a database leak does not expose usable keys.
- Scope every key to the minimum. A key that resets HWIDs for your support tool does not need
licenses.issue. Reserve*for something that genuinely needs everything. - Bind keys to a product when the integration only serves one. A product-bound key that touches another product's licence gets
404, not403, so it cannot even probe for what else exists. - Rotate by overlap. Create the new key, deploy it, then delete the old one. Deletion takes effect immediately, so deleting first means downtime.
- Minting is dashboard-only. No API key can create another API key, register a webhook endpoint, change a webhook URL or rotate a signing key. A leaked key therefore cannot escalate itself or redirect your event stream.
- If a key leaks: delete it first, then review what happened in the window: licences issued, licences revoked, HWID resets, sessions killed.
Webhook receivers
Your webhook endpoint is a public URL that grants entitlements.
- Verify
Licentry-Signaturebefore anything else: HMAC-SHA256 overt + "." + raw bodywith that endpoint's secret, compared in constant time. Sign the bytes exactly as they arrived, because re-serialising the JSON changes them. - Reject a timestamp more than 5 minutes from your clock. The timestamp is inside the signed material, so a captured delivery cannot be replayed later under a fresh header, but only if you actually check it.
- Deduplicate on
Licentry-Delivery. Retries reuse the delivery id, so a receiver that acknowledged late will see the same event twice. Make every handler idempotent. - Answer 2xx as soon as the signature checks out, then do the work in a queue. The request is abandoned after 10 seconds and counted as a failure.
- Events can arrive out of order. Use them as triggers, and treat the Vendor API as the source of truth for current state.
Team seats and least privilege
Role restrictions are applied centrally by path. Restricted roles are denied access to new routes unless explicitly allowed. The account owner is separate from team membership and is unrestricted.
| Role | Can | Cannot |
|---|---|---|
| Owner | Everything, including billing and the team. | Nothing. Give this to one person and put 2FA on it. |
| Admin | Day to day: products, keys, devices, API keys, webhooks, Discord. | Billing, team management, the account password and 2FA. |
| Developer | Issue and manage keys, manage products, read everything. | Mint API keys, rotate signing keys, change the integration setup. |
| Viewer | Read only. The right seat for support staff. | Change anything at all. |
What we store, and what only you can protect
| Item | Licentry holds | You hold |
|---|---|---|
| Licence keys | An HMAC under your account's own sealed pepper. Never plaintext, so nobody can read a key back out of the database. | The plaintext keys returned once at issue. If you neither store nor deliver them, they are gone. |
| Runtime tokens | Hashes only, so a database dump does not yield usable sessions. | The live tokens on the customer's machine. Platform secure storage, never a plaintext file. |
| Signing keys | Your account's private keys, sealed at rest. Public halves served from your own JWKS URLs. | The public keys and their kid values pinned inside your shipped binaries. |
| Session history | Device hashes, session and device timelines, IPs and user agents from licence traffic. This is what the sharing evidence reads. | The device hash recipe. Salt it per product so the value you send is not a global machine identifier that correlates your customers across unrelated software. |
| Integration secrets | API keys as hashes, webhook secrets sealed, delivery logs for 30 days. | The plaintext API keys and webhook secrets in your own deployment, in a secret manager rather than a repository. |
| Your binaries | Nothing. | All of it. The build pipeline, the code, and everything on this page below the network layer. |
On the client, access token, refresh token and licence key go in platform secure storage: Credential Manager, Keychain, Keystore, libsecret. Never a plaintext file next to the executable, and never a log line. Redact tokens and keys from crash reports before they leave the machine.
Launch checklist
Before you ship a licensed build to real customers:
- Base URL is configurable, no secrets compiled into the client, no vendor API key anywhere near it.
- Response-signature verification pins keys by
kid, runs before the body is parsed, and fails closed. The clock check is two sided, so setting the system clock back does not let an old signature through. The signature is decoded as rawr||sand its length is checked at 64 bytes. - A response with no
X-Licentry-Sigheader is refused. Grep your own client for a conditional around the verify call:if (header present)is the failure that never shows up in testing. Verify by stripping the header with a local proxy and confirming the product does not run. - Every
401is branched on itserrorfield, not handled by one re-activation. The 401 cases have four different correct recoveries, and three of them are terminal or made worse by re-activating. - Refresh runs on a schedule rather than only on an error, and a heartbeat follows each one.
- A fresh random
clientNoncegoes out on every validate, activate, heartbeat, refresh and logout, and the echo is compared before the status is read. - Activate persists access, refresh,
revocationVersion, product and seq state. - Idempotency key is randomly generated per activation attempt, reused only across retries of that attempt, and never derived from the device or the licence.
- Heartbeat scheduled before
expiresAt, sendsdeviceHashand theserverNoncefrom the previous beat, and handles every 401/403/409/426. 403and426are terminal on every route. No catch-all reaches the licensed path, and no error body is parsed for a field only a success carries.- The product controls are set:
requireBuildToken,requireDpop,maxConcurrentSessionsandengineParams. A product you have not configured enforces none of them, and the product page shows that as a score. - Also consider
payloadKeyif there is anything in your product worth encrypting,requireDpopBodyonce your client putsbhin its proofs,vendorResponseSigningonce your client pins your own keys, andminProtocolVersiononce every copy in the field sends its version. - Device hash is derived from real hardware, salted per product, and emitted as identical lowercase hex on every call. Tested across a reboot, because an unstable recipe revokes a paying customer's session and records a mismatch against them.
- Logout is called on user sign-out and on clean shutdown, with a DPoP proof if the session is bound, and local session state is cleared afterwards, so the concurrency seat is released instead of being evicted later and counted as churn.
session_killedstops;invalid_sessionre-activates once with backoff. Test both.- Refresh scheduled before
refreshExpiresAt; the next heartbeat after a refresh sendsseq: 1, and the storedserverNonceis carried across rather than cleared. Test by running a refresh and the beat that follows it, which is the only way this one shows up. - DPoP proofs fresh per request;
htuis the public origin you were given plus the path, with no query string, not the host your process connected to; no proof is ever resent. - Offline grace verified against your JWKS with
dev,exp,rvandprodenforced. - Nothing valuable is gated on a boolean. Something the product needs is derived from the live session, and
_session.secretis load bearing rather than ignored, read fresh out of every blob rather than cached at activation. - Checks happen at more than one moment and in more than one place.
- Tokens in platform secure storage; nothing sensitive logged or sent in crash reports; 429s backed off.
- Failure messages give no reason. Nothing in the UI helps someone sort live keys from dead ones.
The hardening guide covers detection thresholds, replay allowances and attacks that leave no server-side evidence. Review it before release. It is available to signed-in vendors on every plan, including trials.
Reference
Every endpoint, field, limit and rule, each stated once. The guides above link here.
What your client needs
There is no Licentry SDK to install. The client side is plain HTTPS and JSON, so the only question is whether your language can do the primitives below. Most can do all of them without adding a dependency.
| Primitive | Used for | Needed when |
|---|---|---|
| HTTPS client | Every call | Always. TLS verification on, certificate checks left alone. |
| JSON encode/decode | Every request and response body | Always. |
| SHA-256 | Device hash, the digest inside the response signature, the DPoP ath claim | Always. |
| Base64 and base64url | Signature header, JWT parts, ath | Always. base64url is not plain base64: - and _ replace + and /, and padding is stripped. |
| ECDSA P-256 verify | Checking X-Licentry-Sig, and the offline grace JWT (ES256) | Always. |
| ECDSA P-256 sign + keypair generation | DPoP proofs | Only if you bind sessions with DPoP. Skip it and everything else still works. |
| Secure local storage | Access and refresh tokens, and the licence key if you keep it | Always. Platform keychain or equivalent, never a plaintext file next to the binary. |
| Stable machine identifiers | Building the device hash | Always. See device binding for what makes a good one. |
Does your language need a package?
Only the P-256 verify step is ever in doubt. Everything else is standard library everywhere.
- Standard library, nothing to install: C#, Go, Python, Node.js, TypeScript, JavaScript, Java, Kotlin, Scala, Clojure, Groovy, Swift, Objective-C, PHP, Ruby, Elixir, Erlang, F#, Visual Basic, Zig, PowerShell.
- One well-known package: C and C++ (OpenSSL), Rust (
p256orring), Dart (pointycastle), Haskell (cryptonite), Perl (CryptX), Lua (luaossl), Delphi (TMS or LockBox), plus Nim, Crystal, OCaml, Julia and R through their usual bindings.
GDScript's Crypto class exposes RSA only, so a pure GDScript client can run activate, heartbeat and refresh but cannot verify the response signature without a GDExtension. That leaves the most important check undone, so treat Godot as needing native code rather than as supported out of the box.
Server-side requirements
Your backend needs no Licentry software. If it checks entitlements it calls the Vendor API over HTTPS with an API key. Webhook receivers need HMAC-SHA256, which every language has built in.
Core concepts
Licence key format
Keys are 28 characters, four mixed-case alphanumeric groups: ^[a-zA-Z0-9]{7}-[a-zA-Z0-9]{5}-[a-zA-Z0-9]{6}-[a-zA-Z0-9]{7}$. Example (illustrative): aB3xK9m-7Qp2n-M4kL8z-Xy1Wq9r. Keys are HMAC-peppered at rest, so a database leak alone reveals nothing usable.
Device hash
A 64-character hex string that identifies one machine or install, derived from stable identifiers with a fixed recipe (device binding). The server checks length and charset only, accepts either case and normalises to lowercase: the value is whatever your client computes and sends. It catches an accidentally copied token and a genuine hardware change. It does not stop a deliberate attacker who sends the first machine's hash from a second machine; requireDpop does, because the private key never leaves the machine's keystore. Send the same hash on activate, heartbeat and refresh. A refresh that leaves it out is refused with 400 device_required on Licentry Cloud and for every DPoP-bound session; the conditions are under refresh.
Build token
The x-licentry-build header identifies the exact build of your client. Register each release you ship on the Client builds page of your dashboard, or with POST /v1/vendor/client-builds, and embed the token you get back. Send it on all five session routes: validate, activate, heartbeat, refresh and logout. An unrecognised, revoked or superseded token is answered with 426 upgrade_required on every one of them. Treat that as an update prompt, and as terminal for that binary: no retry can succeed. A missing token is a different case, and it is only refused when the product sets requireBuildToken.
It binds a request to one build of one account: a token from another Licentry account cannot activate your licences, and yours cannot activate theirs. Revoking it stops every copy of that build from getting a session, which is how you cut off a leaked or bypassed release without touching a single customer's licence.
The build token is plaintext in the binary and can be extracted with strings. It identifies a release but does not authenticate the client. Do not derive other values from it or describe it as proof of a genuine binary; store it as you would a build number. Leave requireBuildToken off while developing the integration, then enable it before release. Without enforcement, a modified binary can omit a revoked token and continue.
Revocation version
Each licence carries a revocationVersion. Bump it (revoke, freeze, or reset a device) and every session bound to the old version fails on its next heartbeat with stale_revocation. Revocation therefore takes effect within one heartbeat interval, not at token expiry.
Lifecycle state machine
The client integration is a small, strict state machine. This is the order your code runs in and the transitions you must handle.
On 401 stale_revocation or refresh_token_stale, always re-activate with the licence key. If you don't store the key in secure storage, the user re-enters it, so plan your UX for that path.
These are two of eight. The diagram shows only the transitions that end in re-activation. For three of the other six, re-activating is wrong: 401 expired usually wants a refresh, 401 dpop_* wants a fresh proof on the same beat, and 401 revoked is terminal. Read the full branch table at failure handling before you write the error handler.
Endpoint reference
Every endpoint uses a strict JSON body: unknown properties are rejected with 400 Invalid request body. All bodies are Content-Type: application/json, and every response on these routes carries the signature headers from the quickstart.
All routes are rate limited. On 429, back off with jitter and honour the RateLimit-* headers when they are present. Not every limiter sends them, so their absence is normal. The exact ceilings are on the hardening guide in your dashboard; a client that beats every few minutes and backs off on 429 never meets any of them.
Read-only key check. Optionally enforces a cached revocation version. Requires the x-licentry-build header. Success is 200 with { "valid": true, "product": "…", "revocationVersion": n }, or a deliberately generic { "valid": false }.
| Field | Type | Req | Notes |
|---|---|---|---|
licenseKey | string | yes | Must match the key format. |
product | string | no | If the key belongs to another product the reply is the plain { valid:false }, with no reason, like every other refusal here (why). |
clientRevocationVersion | number | no | If sent, must equal the DB version or the key reads invalid. |
clientNonce | string | no | 8 to 128 printable characters. Echoed back inside the signed body, which is how you tell this response apart from a replay of an older one. Send a fresh random value on every call. |
deviceHash | string | no | Accepted for compatibility and not acted on. Validate is read only, so device binding happens at activate. |
realIp | string | no | What the client believes its own address is. Recorded as telemetry and never trusted as the caller address. |
These six are the whole list. The body is strict, so any other field is a 400 rather than something ignored.
Creates a runtime session: access and refresh tokens, optionally DPoP-bound. Send an Idempotency-Key (≥ 8 chars) and reuse it when retrying after a network error. How to generate it is under session timing and rules.
| Field | Type | Req | Notes |
|---|---|---|---|
licenseKey | string | yes | Same 28-character format as validate. |
deviceHash | string | yes | 64 hex chars. |
dpopPublicJwk | string | no | JSON string of a P-256 JWK. Malformed → 403 dpop_jwk_invalid (fails closed). |
clientRevocationVersion | number | no | Must match current DB version if provided. |
Activation failures are deliberately indistinguishable. Unknown, expired, revoked and canary keys all return 400 activation_failed, held to the same padded response time, so neither the body nor the clock tells them apart. The reason exists only in the server log. Do not branch on it.
Handle these outcomes separately: 403 too_many_devices, 403 license_suspended, 403 dpop_jwk_invalid, and 426 upgrade_required when the build token is present and unrecognised, retired or superseded. Everything else comes back as 400 activation_failed on a fixed delay. That includes a key that belongs to a different product, a client below the product's minProtocolVersion, and a missing build token on a product that sets requireBuildToken. Telling those cases apart would let a caller sort a stolen key list into live and dead, which is why every refusal on activate and validate looks the same. A deduplicated retry returns the same session with "idempotent": true.
A missing build token never gives 426 on activate or validate. The build token outcomes by route:
| Route | Token present but unrecognised, retired or superseded | Token missing, requireBuildToken on |
|---|---|---|
| activate | 426 upgrade_required | 400 activation_failed, padded delay |
| validate | 426 upgrade_required | 200 { "valid": false }, padded delay |
| heartbeat, refresh | 426 upgrade_required | 426 upgrade_required |
| logout | 426 upgrade_required | accepted |
The check on a present token runs before any licence is looked at, so it can say what it is; for that binary it is terminal, so prompt for an update. Whether a product requires a build token is reached through the licence, so the two routes that take a raw key fold the missing case into their generic refusal. Heartbeat and refresh are past authentication and the caller already holds a session for that licence, so naming the reason there discloses nothing. Logout checks the token itself and never the product control. Treat 426 as "this binary needs replacing" and 400 activation_failed as "this key cannot start a session".
Extends the access window. Requires Authorization: Bearer <accessToken>, plus a DPoP proof if the session is bound. Success is 200 with { "ok": true, "expiresAt": "…", "revocationVersion": n, "serverNonce": "…", "clientNonce": "…" }, plus offlineGraceJwt, signingPublicKey and engineParams where they are configured. Schedule the next beat from the returned expiresAt.
| Field | Type | Req | Notes |
|---|---|---|---|
seq | number | yes | Integer 1 or greater. Rules below. |
deviceHash | string | yes | 64 hex, byte-identical to activate. Not optional: {"seq":1} alone is 400 on every beat. |
serverNonce | string | first beat no, then yes in practice | The value from the previous response. Empty on the first beat of a session. Once the server has issued one, omitting it counts as a mismatch. |
clientNonce | string | no | Fresh random per beat, echoed in the signed body. Send it and compare the echo. |
runId | string | no, recommended | 8 to 64 characters of A-Za-z0-9_-. See below. |
Generate one runId per process start and use it on every heartbeat from that run. It is telemetry only: it never changes the response or causes a refusal, and omission supplies no signal. Several distinct values on one session can indicate a relay serving multiple clients. A relay that removes or normalises the value must rewrite request bodies, which invalidates proofs when requireDpopBody is enabled.
| Rule | Behaviour |
|---|---|
| First seq | Row starts at seq=0; first heartbeat must send seq: 1. |
| Monotonic | Next value must satisfy oldSeq < newSeq ≤ oldSeq + 8. |
| After refresh | Server resets seq to 0, so send seq: 1 again. The nonce chain does not reset: echo the last serverNonce you hold (nonce chain). |
409 stale_seq | You sent seq ≤ stored (replay). |
409 seq_gap | You skipped more than 8 (newSeq > oldSeq + 8). |
409 bad_seq | seq isn't a positive integer. |
401 stale_revocation | Licence revocation version changed → re-activate. |
Other 401 | invalid_session, expired, revoked, nonce_mismatch, dpop_* and a bodiless refusal for a missing bearer header all arrive as 401 with four different correct recoveries. Read the branch table rather than re-activating on all of them. |
Rotates the token pair before refreshExpiresAt. Body: { "refreshToken": "...", "deviceHash": "...", "clientNonce": "..." }. The refresh token is 32 to 512 characters. If DPoP-bound, send a proof whose ath hashes the refresh token. Success returns a fresh token pair with new expiries. The next heartbeat is seq: 1 and still echoes the serverNonce you were last issued (nonce chain).
| Field | Type | Req | Notes |
|---|---|---|---|
refreshToken | string | yes | 32 to 512 characters. |
deviceHash | string | optional in the schema, required in practice | 64 hex, the same value you sent at activate. Leaving it out is 400 device_required whenever the session is DPoP-bound, and on any deployment that sets LICENSE_REFRESH_REQUIRE_DEVICE, which Licentry Cloud does. A value that does not match revokes the session with 403 license_suspended. Both cases are below. |
clientNonce | string | no | 8 to 128 printable characters, echoed in the signed body. Send it and compare the echo. |
These three are the whole list. The body is strict, so any other field is a 400.
Send the device hash. It is optional in the schema so that clients built before it existed keep working, and whether omitting it is refused is a deployment setting rather than a fixed behaviour:
| Setting | Default | Licentry Cloud | What it changes |
|---|---|---|---|
LICENSE_REFRESH_REQUIRE_DEVICE | off | on | Off, deviceHash is enforced when present and not demanded. On, a refresh without it is 400 device_required and nothing rotates. |
A DPoP-bound session demands the hash whatever that setting says, because nothing older than the binding can exist. So against Licentry Cloud a client that omits the field can never refresh. Send it unconditionally and the setting stops mattering.
Send a heartbeat after each refresh. Refresh returns neither signingPublicKey nor a new offlineGraceJwt. A client that only refreshes cannot follow offline-key rotation or replace an expiring grace token. Send the seq: 1 heartbeat before relying on offline grace.
Revokes the session for an access token. Body: { "accessToken": "...", "clientNonce": "..." }. Returns 200 with { "ok": true } and your echoed nonce. It is not a 204: a response with no body cannot carry the nonce echo, and every signed empty body on these routes would otherwise be interchangeable.
Call it whenever the user quits, signs out or switches account, on the last clean shutdown path you control, and treat it as fire-and-forget rather than something a quit waits on.
Without logout, a session occupies its concurrency seat until the refresh window closes, which can take days. With the default maxConcurrentSessions of 1, the next launch evicts that abandoned session. Each eviction is recorded as superseded and contributes to sharing evidence, even when the same customer caused it.
Eviction handles sessions left by a crash. On a clean exit, call logout.
For a DPoP-bound session, send a proof over the logout URL with ath derived from the access token. Without proof enforcement, someone with a copied token could end the session, causing re-activation and misleading eviction activity. Licentry Cloud enables LICENSE_LOGOUT_DPOP_STRICT, which is off by default in code. A missing or invalid proof then returns 401 dpop_required, leaves the session active and keeps its seat occupied.
Only for live native loading, and off unless you have turned it on for the product. Asks for permission to fetch one sealed artifact, so your program can map it into memory instead of loading it from disk. Send Authorization: Bearer <accessToken>, plus a DPoP proof over this URL when the session was bound at activate, exactly as for a heartbeat.
| Field | Type | Req | Notes |
|---|---|---|---|
slot | string | yes | Your name for the artifact: lowercase, [a-z0-9][a-z0-9_-]*, up to 64 characters. |
clientNonce | string | no | Send it anyway, as on every session route. |
You ask by slot, never by version. The server resolves the slot to whichever version is live at that moment, so you can publish a new build without shipping a new client. A 200 carries the grant and what you need to verify the download:
{
"grant": "eyJhbGciOiJFUzI1NiIs...",
"url": "https://artifacts.licentry.cc",
"expiresAt": "2026-08-19T09:41:12.000Z",
"sealed": { "alg": "ECDH-ES+A256GCM", "epk": { "kty": "EC", "crv": "P-256", "x": "...", "y": "..." }, "ct": "..." },
"slot": "core",
"version": 3,
"sha256": "9f2b...",
"size": 2097152,
"kind": "pe_dll"
}
sealed carries the AES-256-GCM content key, agreed to your DPoP public key by ECDH-ES over P-256 and opened with your DPoP private key, the same mechanism as the protected payload. On a session that is not DPoP-bound, and only where you have not required binding, you get key instead, a 64-character hex string. Never both. Then, in order:
GETtheurlwith the headerX-Licentry-Grant: <grant>. The grant goes in a header because a query string lands in access logs.- The body is an envelope:
LCAR(4 bytes), version (1), iv (12), tag (16), ciphertext. Decrypt it with AES-256-GCM. - Check the sha256 of the plaintext against
sha256. Hashing the downloaded bytes would only prove the edge served the object it was pointed at. - Hand the buffer to your own loader. Mapping it is your code.
The grant is single use and lasts roughly two minutes; the edge burns it on first use. Ask for a new one per launch, and never share one between processes. Errors: 400 for a bad body, 401 for a bearer or DPoP failure, 404 artifact_unavailable, and 503 if the database is down. The 404 is deliberately one answer for an unknown slot, an archived version, live loading switched off, a licence over its fetch allowance or a server-side configuration gap, with the same delay and no rate-limit headers, so do not branch on it. If it persists, the answer is in your dashboard.
Two authenticated endpoints take detection reports from your client (when to send them). Both need Authorization: Bearer <accessToken> and an active session, and both answer 200 with { "ok": true } and your echoed clientNonce.
Body { "eventType": "...", "reason": "...", "meta": { } }. Recognised types are code_integrity_fail, anchor_seal_fail, snapshot_rollback, module_injection_detected and debugger_detected; anything else is recorded as unknown. Events land in the server-side audit log.
Body { "reason": "...", "screenshot": "..." }, both optional. screenshot is a base64 PNG of up to 5 MB.
Webhook endpoints receive tamper.reported with the reason, source address and whether a screenshot was supplied. The image is never included in a normal webhook payload. On Studio, it is attached only to the report sent to your configured Discord log webhook; otherwise it is discarded. Tell customers what you collect before enabling screenshots.
Public JWK set (P-256 / ES256) for verifying the offline-grace tokens issued against your licences: 200 with { "keys": [ … ] }, or 404 offline_grace_not_configured. The set carries two keys while a rotation is in flight, the one signing today first, and only that first one signs. Unauthenticated, because these are public keys. Your account id and the exact URL are on the Signing keys page of your dashboard and in the jwks block of GET /v1/vendor/me. This is the set to pin.
The deployment key, which signs only licences that belong to no vendor account. A licence issued from your account is never signed with it, so a client that verifies against this set alone rejects every token it receives. It carries two keys during a deployment key rotation, on the same rule: the first one signs.
DPoP proofs
DPoP (proof-of-possession, RFC 9449) binds a session to a private key the client holds. Register a P-256 public JWK at activate, then send a fresh signed proof on every heartbeat and refresh.
Registering the key (activate)
Send dpopPublicJwk as a JSON string whose parsed value is a P-256 JWK (kty:"EC", crv:"P-256", base64url x/y).
The proof JWT
- Algorithm
ES256, signed with the private key matching the registered JWK. - Claims
iatandexprequired. Proof no older than 120s; lifetimeexp - iat≤ 120s (± ~30s skew). - htm
POST; htu the public origin plus the path, with no query string (for examplehttps://licentry.cc/v1/sess/heartbeat). Build it from the origin you were given, not from the host your process happened to connect to. If your client reaches us under some other name, through a proxy that rewritesHost, a staging alias or a bare IP, the two differ and every proof comes back401 dpop_htu_mismatch, even though your JWT is correct. Either path family works, so/v1/sess/heartbeatand/api/public/license/heartbeatboth verify; only the origin is fixed. - ath base64url(SHA-256(token)): the access token on heartbeat, the refresh token on refresh.
- jti a unique string (≥ 8 chars); not reused within the 150 second replay window. Generate it from a random source rather than a counter.
- bh base64url(SHA-256(request body bytes)), the same construction as
athbut over what you are about to send. Optional, so a client built before it existed can omit it, and verified whenever it is present: abhthat does not match the bytes received is401 dpop_bh_mismatch. Hash the exact bytes you put on the wire, not a re-serialisation, because two JSON encoders disagree about key order and spacing. Making its absence a refusal is therequireDpopBodyswitch.
Generating the key and the proof
One keypair per install, generated once and kept in the platform keystore, then a fresh proof on every request. Watch the signature format: JOSE expects the raw r||s bytes, and most libraries hand you DER by default. Each example below does that conversion.
# One P-256 key per install, generated once and kept in the OS keystore.
openssl ecparam -name prime256v1 -genkey -noout -out dpop.pem
# Public JWK for activate. dpopPublicJwk is a JSON STRING, not an object.
JWK=$(openssl ec -in dpop.pem -pubout -outform DER 2>/dev/null | tail -c 64 | \
xxd -p -c 64 | awk '{ x=substr($0,1,64); y=substr($0,65,64);
cmd="printf %s " x " | xxd -r -p | basenc --base64url | tr -d =";
cmd | getline X; close(cmd);
cmd="printf %s " y " | xxd -r -p | basenc --base64url | tr -d =";
cmd | getline Y; close(cmd);
printf "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"%s\",\"y\":\"%s\"}", X, Y }')
# The build header belongs on this call like any other session route. Without it
# a product with requireBuildToken on answers a deliberately generic
# activation_failed, which looks like a bad licence key and is hard to
# diagnose from the client side.
curl -sS -X POST "$BASE/v1/sess/activate" -H "Content-Type: application/json" \
-H "x-licentry-build: $BUILD_TOKEN" \
-H "x-licentry-protocol: 1" \
-d "$(jq -cn --arg k "$LICENSE_KEY" --arg d "$DEVICE_HASH" --arg j "$JWK" \
--arg n "$(openssl rand -hex 8)" \
'{licenseKey:$k, deviceHash:$d, dpopPublicJwk:$j, clientNonce:$n}')"
# Every later heartbeat/refresh needs a fresh proof. ath binds it to the token,
# jti makes it single use, and the server refuses a lifetime over 120s.
# On /v1/sess/refresh feed ath the REFRESH token, not the access token.
ath() { printf %s "$1" | openssl dgst -binary -sha256 | basenc --base64url | tr -d =; }
# Sign with a JOSE library: ES256 needs raw r||s, and openssl emits DER.
// Windows: hold the key in CNG (BCRYPT_ECDSA_P256_ALGORITHM) so it is never
// a file on disk. BCryptSignHash already returns raw r||s, which is what JOSE
// wants, so no DER unwrapping is needed here.
std::string b64url(const uint8_t* p, size_t n); // no padding
std::string sha256B64Url(const std::string& s);
// Sent ONCE, at activate, as a JSON *string* in dpopPublicJwk.
std::string dpopPublicJwk(const std::vector<uint8_t>& x, const std::vector<uint8_t>& y) {
return "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"" +
b64url(x.data(), 32) + "\",\"y\":\"" + b64url(y.data(), 32) + "\"}";
}
// One fresh proof per request. Reusing one is a replay: the server remembers jti.
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
std::string dpopProof(BCRYPT_KEY_HANDLE key, const std::string& htm,
const std::string& htu, const std::string& accessToken) {
const long now = (long)time(nullptr);
std::string hdr = R"({"alg":"ES256","typ":"dpop+jwt"})";
std::string body = "{\"htm\":\"" + htm + "\",\"htu\":\"" + htu +
"\",\"ath\":\"" + sha256B64Url(accessToken) +
"\",\"jti\":\"" + randomHex(16) +
"\",\"iat\":" + std::to_string(now) +
",\"exp\":" + std::to_string(now + 60) + "}";
std::string signingInput = b64urlStr(hdr) + "." + b64urlStr(body);
std::vector<uint8_t> rs = signP256(key, sha256Raw(signingInput)); // 64 bytes
return signingInput + "." + b64url(rs.data(), rs.size());
}
// Send as the DPoP request header. htu is the public origin you were given plus
// this path, with no query string.
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
static string B64Url(byte[] b) => Convert.ToBase64String(b)
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
// Generate once per install and persist the key, not the JWK.
static ECDsa NewDpopKey() => ECDsa.Create(ECCurve.NamedCurves.nistP256);
// dpopPublicJwk is a JSON STRING in the activate body.
static string PublicJwk(ECDsa key) {
var p = key.ExportParameters(false);
return JsonSerializer.Serialize(new {
kty = "EC", crv = "P-256", x = B64Url(p.Q.X!), y = B64Url(p.Q.Y!)
});
}
// A fresh proof per request; jti is remembered server side, so never reuse one.
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
static string DpopProof(ECDsa key, string htm, string htu, string accessToken) {
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
string hdr = B64Url(Encoding.UTF8.GetBytes(
JsonSerializer.Serialize(new { alg = "ES256", typ = "dpop+jwt" })));
string ath = B64Url(SHA256.HashData(Encoding.UTF8.GetBytes(accessToken)));
string body = B64Url(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new {
htm, htu, ath, jti = Guid.NewGuid().ToString("N"),
iat = now, exp = now + 60 // the server refuses a window over 120s
})));
string input = hdr + "." + body;
// IeeeP1363 is raw r||s, which is what JOSE expects. The default is DER.
byte[] sig = key.SignData(Encoding.UTF8.GetBytes(input), HashAlgorithmName.SHA256,
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
return input + "." + B64Url(sig);
}
// req.Headers.Add("DPoP", DpopProof(key, "POST", url, accessToken));
import base64
import hashlib
import json
import secrets
import time
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, utils
def b64u(b: bytes) -> str:
return base64.urlsafe_b64encode(b).decode().rstrip("=")
def new_dpop_key():
return ec.generate_private_key(ec.SECP256R1()) # once per install, then stored
def public_jwk(key) -> str:
n = key.public_key().public_numbers()
# A JSON STRING is what activate expects, not a nested object.
return json.dumps({"kty": "EC", "crv": "P-256",
"x": b64u(n.x.to_bytes(32, "big")),
"y": b64u(n.y.to_bytes(32, "big"))}, separators=(",", ":"))
# On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
def dpop_proof(key, htm: str, htu: str, access_token: str) -> str:
now = int(time.time())
hdr = b64u(json.dumps({"alg": "ES256", "typ": "dpop+jwt"},
separators=(",", ":")).encode())
body = b64u(json.dumps({
"htm": htm, "htu": htu,
"ath": b64u(hashlib.sha256(access_token.encode()).digest()),
"jti": secrets.token_hex(16), # single use; the server remembers it
"iat": now, "exp": now + 60, # a window over 120s is refused
}, separators=(",", ":")).encode())
signing_input = f"{hdr}.{body}".encode()
der = key.sign(signing_input, ec.ECDSA(hashes.SHA256()))
r, s = utils.decode_dss_signature(der) # JOSE wants raw r||s, not DER
raw = r.to_bytes(32, "big") + s.to_bytes(32, "big")
return f"{hdr}.{body}.{b64u(raw)}"
# headers={"DPoP": dpop_proof(key, "POST", url, access_token)}
import { webcrypto as crypto } from "node:crypto";
const b64u = (b) => Buffer.from(b).toString("base64url");
// Generate once, then persist the key. extractable:false keeps the private half
// out of your own process memory as a serialisable value.
export async function newDpopKey() {
return crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" },
false, ["sign"]);
}
// dpopPublicJwk is a JSON STRING in the activate body, not an object.
export async function publicJwk(pair) {
const j = await crypto.subtle.exportKey("jwk", pair.publicKey);
return JSON.stringify({ kty: "EC", crv: "P-256", x: j.x, y: j.y });
}
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
export async function dpopProof(pair, htm, htu, accessToken) {
const now = Math.floor(Date.now() / 1000);
const hdr = b64u(JSON.stringify({ alg: "ES256", typ: "dpop+jwt" }));
const ath = b64u(await crypto.subtle.digest("SHA-256",
new TextEncoder().encode(accessToken)));
const body = b64u(JSON.stringify({
htm, htu, ath,
jti: crypto.randomUUID(), // single use; the server remembers it
iat: now, exp: now + 60, // the server refuses a window over 120s
}));
const input = new TextEncoder().encode(hdr + "." + body);
// WebCrypto ECDSA output is already raw r||s, which is what JOSE expects.
const sig = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" },
pair.privateKey, input);
return hdr + "." + body + "." + b64u(sig);
}
// headers: { DPoP: await dpopProof(pair, "POST", url, accessToken) }
// Generate once per install with ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
// and persist it in the OS keystore.
func b64u(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
// dpopPublicJwk is a JSON STRING in the activate body.
func PublicJWK(k *ecdsa.PrivateKey) string {
x := make([]byte, 32)
y := make([]byte, 32)
k.X.FillBytes(x)
k.Y.FillBytes(y)
return fmt.Sprintf(`{"kty":"EC","crv":"P-256","x":"%s","y":"%s"}`, b64u(x), b64u(y))
}
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
func DpopProof(k *ecdsa.PrivateKey, htm, htu, accessToken string) (string, error) {
now := time.Now().Unix()
hdr := b64u([]byte(`{"alg":"ES256","typ":"dpop+jwt"}`))
sum := sha256.Sum256([]byte(accessToken))
jti := make([]byte, 16)
rand.Read(jti)
claims, _ := json.Marshal(map[string]any{
"htm": htm, "htu": htu, "ath": b64u(sum[:]),
"jti": hex.EncodeToString(jti), // single use; the server remembers it
"iat": now, "exp": now + 60, // a window over 120s is refused
})
input := hdr + "." + b64u(claims)
digest := sha256.Sum256([]byte(input))
r, s, err := ecdsa.Sign(rand.Reader, k, digest[:])
if err != nil {
return "", err
}
// JOSE wants fixed-width raw r||s, not the ASN.1 form ecdsa.SignASN1 gives.
rs := make([]byte, 64)
r.FillBytes(rs[:32])
s.FillBytes(rs[32:])
return input + "." + b64u(rs), nil
}
// req.Header.Set("DPoP", proof)
use p256::ecdsa::{signature::Signer, Signature, SigningKey};
use sha2::{Digest, Sha256};
fn b64u(b: &[u8]) -> String { URL_SAFE_NO_PAD.encode(b) }
// SigningKey::random(&mut OsRng) once per install, then persist it.
pub fn public_jwk(key: &SigningKey) -> String {
let pt = key.verifying_key().to_encoded_point(false);
// dpopPublicJwk is a JSON STRING in the activate body.
format!(
r#"{{"kty":"EC","crv":"P-256","x":"{}","y":"{}"}}"#,
b64u(pt.x().unwrap()), b64u(pt.y().unwrap())
)
}
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
pub fn dpop_proof(key: &SigningKey, htm: &str, htu: &str, access_token: &str) -> String {
let now = Utc::now().timestamp();
let hdr = b64u(br#"{"alg":"ES256","typ":"dpop+jwt"}"#);
let ath = b64u(&Sha256::digest(access_token.as_bytes()));
let jti: [u8; 16] = rand::random();
let claims = serde_json::json!({
"htm": htm, "htu": htu, "ath": ath,
"jti": hex::encode(jti), // single use; the server remembers it
"iat": now, "exp": now + 60, // a window over 120s is refused
});
let input = format!("{hdr}.{}", b64u(claims.to_string().as_bytes()));
// p256 signs to fixed-width r||s already, which is what JOSE expects.
let sig: Signature = key.sign(input.as_bytes());
format!("{input}.{}", b64u(&sig.to_bytes()))
}
// .header("DPoP", dpop_proof(&key, "POST", url, access_token))
// KeyPairGenerator.getInstance("EC") with an ECGenParameterSpec of "secp256r1",
// generated once per install and kept in the platform KeyStore.
static String b64u(byte[] b) { return Base64.getUrlEncoder().withoutPadding().encodeToString(b); }
// dpopPublicJwk is a JSON STRING in the activate body.
static String publicJwk(ECPublicKey pub) {
byte[] x = toFixed32(pub.getW().getAffineX());
byte[] y = toFixed32(pub.getW().getAffineY());
return "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"" + b64u(x)
+ "\",\"y\":\"" + b64u(y) + "\"}";
}
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
static String dpopProof(PrivateKey key, String htm, String htu, String accessToken)
throws Exception {
long now = Instant.now().getEpochSecond();
String hdr = b64u("{\"alg\":\"ES256\",\"typ\":\"dpop+jwt\"}".getBytes(UTF_8));
String ath = b64u(MessageDigest.getInstance("SHA-256")
.digest(accessToken.getBytes(UTF_8)));
String claims = String.format(
"{\"htm\":\"%s\",\"htu\":\"%s\",\"ath\":\"%s\",\"jti\":\"%s\",\"iat\":%d,\"exp\":%d}",
htm, htu, ath, UUID.randomUUID().toString().replace("-", ""), now, now + 60);
String input = hdr + "." + b64u(claims.getBytes(UTF_8));
// The P1363 variant emits raw r||s; plain SHA256withECDSA would emit DER.
Signature s = Signature.getInstance("SHA256withECDSAinP1363Format");
s.initSign(key);
s.update(input.getBytes(UTF_8));
return input + "." + b64u(s.sign());
}
// .header("DPoP", dpopProof(key, "POST", url, accessToken))
<?php
// openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC])
// once per install, then persist the PEM outside the web root.
function b64u(string $b): string { return rtrim(strtr(base64_encode($b), '+/', '-_'), '='); }
// dpopPublicJwk is a JSON STRING in the activate body.
function publicJwk($key): string {
$d = openssl_pkey_get_details($key);
return json_encode([
'kty' => 'EC', 'crv' => 'P-256',
'x' => b64u(str_pad($d['ec']['x'], 32, "\0", STR_PAD_LEFT)),
'y' => b64u(str_pad($d['ec']['y'], 32, "\0", STR_PAD_LEFT)),
]);
}
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
function dpopProof($key, string $htm, string $htu, string $accessToken): string {
$now = time();
$hdr = b64u(json_encode(['alg' => 'ES256', 'typ' => 'dpop+jwt']));
$claims = b64u(json_encode([
'htm' => $htm, 'htu' => $htu,
'ath' => b64u(hash('sha256', $accessToken, true)),
'jti' => bin2hex(random_bytes(16)), // single use; the server remembers it
'iat' => $now, 'exp' => $now + 60, // a window over 120s is refused
]));
$input = $hdr . '.' . $claims;
openssl_sign($input, $der, $key, OPENSSL_ALGO_SHA256);
// openssl emits DER; JOSE needs raw r||s, so unwrap the ASN.1 sequence.
return $input . '.' . b64u(p1363FromDer($der));
}
// CURLOPT_HTTPHEADER => ['DPoP: ' . dpopProof($key, 'POST', $url, $accessToken)]
import CryptoKit
import Foundation
func b64u(_ d: Data) -> String {
d.base64EncodedString().replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
}
// P256.Signing.PrivateKey() once per install, stored in the Keychain.
func publicJwk(_ key: P256.Signing.PrivateKey) -> String {
let raw = key.publicKey.rawRepresentation // x || y, 32 bytes each
// dpopPublicJwk is a JSON STRING in the activate body.
return "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"\(b64u(raw.prefix(32)))\",\"y\":\"\(b64u(raw.suffix(32)))\"}"
}
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
func dpopProof(_ key: P256.Signing.PrivateKey, htm: String, htu: String,
accessToken: String) throws -> String {
let now = Int(Date().timeIntervalSince1970)
let hdr = b64u(Data(#"{"alg":"ES256","typ":"dpop+jwt"}"#.utf8))
let ath = b64u(Data(SHA256.hash(data: Data(accessToken.utf8))))
let jti = UUID().uuidString.replacingOccurrences(of: "-", with: "")
// exp - iat over 120s is refused; jti is single use.
let claims = #"{"htm":"#(htm)","htu":"#(htu)","ath":"#(ath)","jti":"#(jti)","iat":#(now),"exp":#(now + 60)}"#
let input = hdr + "." + b64u(Data(claims.utf8))
let sig = try key.signature(for: Data(input.utf8))
// rawRepresentation is r||s, which is what JOSE expects.
return input + "." + b64u(sig.rawRepresentation)
}
// req.setValue(proof, forHTTPHeaderField: "DPoP")
// KeyPairGenerator.getInstance("EC") with "secp256r1", generated once and kept
// in the Android Keystore.
fun b64u(b: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(b)
// dpopPublicJwk is a JSON STRING in the activate body.
fun publicJwk(pub: ECPublicKey): String {
val x = b64u(toFixed32(pub.w.affineX))
val y = b64u(toFixed32(pub.w.affineY))
return """{"kty":"EC","crv":"P-256","x":"$x","y":"$y"}"""
}
// On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
fun dpopProof(key: PrivateKey, htm: String, htu: String, accessToken: String): String {
val now = Instant.now().epochSecond
val hdr = b64u("""{"alg":"ES256","typ":"dpop+jwt"}""".toByteArray())
val ath = b64u(MessageDigest.getInstance("SHA-256").digest(accessToken.toByteArray()))
val jti = UUID.randomUUID().toString().replace("-", "")
// exp - iat over 120s is refused; jti is single use.
val exp = now + 60
val claims = """{"htm":"$htm","htu":"$htu","ath":"$ath","jti":"$jti","iat":$now,"exp":$exp}"""
val input = hdr + "." + b64u(claims.toByteArray())
// The P1363 name emits raw r||s; plain SHA256withECDSA would emit DER.
val s = Signature.getInstance("SHA256withECDSAinP1363Format")
s.initSign(key)
s.update(input.toByteArray())
return input + "." + b64u(s.sign())
}
// .header("DPoP", dpopProof(key, "POST", url, accessToken))
require "openssl"
require "json"
require "securerandom"
require "base64"
def b64u(b) = Base64.urlsafe_encode64(b, padding: false)
# OpenSSL::PKey::EC.generate("prime256v1") once per install, then persist it.
def public_jwk(key)
pt = key.public_key.to_bn.to_s(2) # 0x04 || x || y
# dpopPublicJwk is a JSON STRING in the activate body.
JSON.generate({ kty: "EC", crv: "P-256",
x: b64u(pt[1, 32]), y: b64u(pt[33, 32]) })
end
# On /v1/sess/refresh pass the refresh token here: ath covers the token the call presents.
def dpop_proof(key, htm, htu, access_token)
now = Time.now.to_i
hdr = b64u(JSON.generate({ alg: "ES256", typ: "dpop+jwt" }))
claims = b64u(JSON.generate({
htm: htm, htu: htu,
ath: b64u(OpenSSL::Digest::SHA256.digest(access_token)),
jti: SecureRandom.hex(16), # single use; the server remembers it
iat: now, exp: now + 60, # a window over 120s is refused
}))
input = "#{hdr}.#{claims}"
der = key.sign(OpenSSL::Digest.new("SHA256"), input)
# OpenSSL emits DER; JOSE needs raw r||s, so unwrap the ASN.1 sequence.
r, s = OpenSSL::ASN1.decode(der).value.map { _1.value }
raw = [r.to_s(16).rjust(64, "0"), s.to_s(16).rjust(64, "0")].join
"#{input}.#{b64u([raw].pack("H*"))}"
end
# req["DPoP"] = dpop_proof(key, "POST", url, access_token)
curl -sS -X POST "$BASE/v1/sess/heartbeat" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "DPoP: $DPOP_JWT" \
-d "{\"seq\":2,\"deviceHash\":\"$DEVICE_HASH\",\"serverNonce\":\"$LAST_SERVER_NONCE\"}"
Generate a new proof per request with a fresh jti, and keep the client clock within ~30s of UTC. If a proof is rejected for a timing reason, resync the clock and send a fresh proof rather than retrying the old one.
Session timing and rules
The numbers the server runs on. The default applies unless a deployment overrides it, and an override is clamped to the range shown.
| Value | Default | Range | Notes |
|---|---|---|---|
| Access window | 20 min | 5 to 120 min | Extended by every accepted heartbeat. Read expiresAt from the response, never hardcode it. |
| Refresh window | 14 days | 1 to 60 days | Reset on every successful refresh. |
| Heartbeat seq gap | 8 | fixed | oldSeq < newSeq ≤ oldSeq + 8. Tolerates dropped beats, not skipping. |
| Devices per licence | 1 | 1 to 100 | Per product, set on the product in your dashboard. |
| Concurrent sessions per licence | 1 | 1 to 20 | Not a rejection. The oldest session is evicted. See below. |
| Offline grace TTL | 72 h on Licentry Cloud | 1 to 168 h | How long a stored offline token stays valid. A platform setting, not a per-product one. The code default is 24 h; Licentry Cloud provisions 72 h. |
| DPoP proof age | 120 s | fixed | Plus 30 s skew allowance. exp - iat is bounded the same way. |
Heartbeat and refresh have credential-based limits plus an outer per-IP limit shared by clients on the same network. Send heartbeats every few minutes, not every few seconds, and back off when limited. The hardening guide lists exact ceilings and replay allowances after sign-in; publishing those thresholds would help someone avoid detection.
Activate
Send an Idempotency-Key of at least 8 characters and reuse the same value for every retry of the same activation. It is scoped to the key plus licence plus device hash, so a retry after a dropped response returns the original session with "idempotent": true instead of burning a device slot. Persist everything you get back: both tokens, both expiries, revocationVersion, product, and your own seq counter starting at 0.
Treat the idempotency key as a secret, and generate a fresh one for each new activation (its retries reuse it, as above). Use a cryptographic random source and at least 16 bytes. Do not derive it from the device hash, the licence key or a counter. For the next 24 hours, presenting that key with the same licence and device hash hands back the live tokens the original activation minted, so a predictable key is a second way into the session. Do not log it, and discard it once the activation has succeeded.
Heartbeat
The heartbeat body requires both seq and deviceHash. If the device hash differs from the hash the session was activated with, the server revokes that session on the spot, records the mismatch against the licence, and answers 403 license_suspended. That is what makes a copied access token useless on a second machine even without DPoP.
Schedule the next heartbeat at roughly one third of the remaining time to the returned expiresAt, with jitter. This leaves time for two missed beats and spreads requests from different clients.
The nonce pair
Heartbeat carries two nonce fields, both inside the signed response body.
clientNonce: a fresh random value you generate per request. The server echoes it back in the signed body. If the echo does not match what you just sent, you are looking at a replayed response, not a live one. This is stronger than a timestamp window because it is bound to this request.serverNonce: the value from the previous heartbeat response. The server chains them forward, so a recorded heartbeat sequence cannot be replayed later: the attacker's copy cannot produce the next nonce the server expects.
Send an empty serverNonce on the session's first heartbeat, then echo the value from the previous response. Once the chain starts, omission counts as a mismatch, including after refresh: the chain lasts for the session, not the token pair. Licentry Cloud returns 401 nonce_mismatch after retry grace is exhausted. Serialise heartbeats to avoid 409 nonce_raced.
After a lost response, resend the same seq and serverNonce. The server recognises the processed heartbeat, returns the missed nonce and advances nothing. Advancing seq while sending the old nonce is not a retry. The allowance is bounded because two clients sharing a token can produce the same pattern; see the hardening guide for enforcement and retry limits.
Refresh and logout
Refresh rotates both tokens and resets seq to 0, so the next heartbeat sends seq: 1. Reusing the old refresh token returns 401 refresh_token_stale and is recorded. A retry after a lost response and a second client using copied state look the same to the server, so the repeat count matters. Store the new token pair before treating refresh as complete.
Schedule refreshes to replenish the heartbeat retry budget; successful heartbeats do not reset it. Refresh does not return offline grace key material, so send a heartbeat afterwards before relying on offline grace (refresh).
Call logout on sign-out and on clean shutdown, then clear local state. What skipping it costs, and the DPoP proof a bound session must send, are under logout.
Explanation
Why the controls are built the way they are, and what they can and cannot stop.
Threat model
This model assumes someone obtains one copy of your software and tries to use or share it without a licence. For setup instructions, see switch the protections on.
Someone with control of the machine, the binary and enough time can bypass client-side checks. Protection can increase the work required, limit reuse after updates and help you detect key sharing, but it cannot make a client bypass-proof.
A single boolean check is easy to bypass. if (license.valid) { unlock(); } compiles to a comparison and conditional jump. Changing that jump or forcing valid to a constant can bypass the check regardless of the network cryptography. The tamper-resistance guidance describes how to make correct operation depend on session data.
Server and client responsibilities
Licentry manages key storage, session state, rate limits and revocation on its servers. You control enforcement in the distributed binary, which an end user can modify. Session routes use the generic /v1/sess/ prefix to avoid an obvious licensing-related search string in that binary.
| What the attacker tries | What answers it | Whose job |
|---|---|---|
| Guess or brute-force a key | Per-IP and per-key-prefix rate limits, peppered hashes, identical failure bodies on a padded response schedule | Licentry |
| Read keys out of a stolen database | Keys are stored only as HMACs under your account's own sealed pepper | Licentry |
| Replay a captured "valid" response | Signed responses, heartbeat sequence numbers, the server nonce chain | Licentry issues it, you must check it |
| Point your app at a fake server or a local proxy | Response signature verified against a key pinned in your binary | You |
| Copy an access token to a second machine | DPoP proof of possession, plus the device hash on every heartbeat | You (register the key, send the hash) |
| Copy the whole app-state folder | The dev claim on the offline grace token | You (the check is client side) |
| Patch the binary so the check never runs | Nothing on the wire. Only how your code is built | You alone |
| Share one key with forty people | Device cap, concurrent session cap, sharing evidence on the licence | Licentry surfaces it, you decide |
| Run a patched binary that never calls us | Nothing on the wire, by construction. Only values the program needs from a live session: engine parameters or the protected payload | You alone |
Choosing controls
Use engine parameters when the program needs values supplied by a live session. Use a protected payload restricted to machine-bound sessions when decryption must also require the device's private key. Where practical, enforce a capability on your own server so changing the binary cannot remove its checks. Customers can still extract data delivered to a valid session.
Protection goals
- 1
Make bypass harder. Requiring session data can force an attacker to reconstruct part of the engine instead of modifying one check.
- 2
Limit reuse. Revocation versions, short access windows and parameter updates can stop an older bypass from working if the client depends on them.
- 3
Review sharing evidence. The server can identify sharing patterns without additional client telemetry. Review those indicators before taking action.
Dedicated server
Licentry is managed by us on every plan; there is no self-operated edition. The dedicated option gives your account its own machine.
We provision, harden and patch the dedicated server. Your database and licence data live on that machine. Shell access is restricted to Licentry operators, including on dedicated plans, so we remain responsible for its configuration and maintenance.
A dedicated setup includes:
- Account isolation. Your database, keys and licence records run separately from other accounts.
- Hardware-based capacity. The machine's capacity replaces the usual plan quota as the licence limit.
- Your own Discord bot. Supply its token, client id and secret. It runs on your server with your name and branding instead of the shared Licentry bot.
- Your own API domain. Point DNS at us to use your hostname, or keep the standard endpoint with the same functionality.
- Studio features and direct priority support from the server operator.
Key custody, patching, backups, TLS, proxy hardening, replay protection and isolated per-vendor signing keys are our responsibility on every plan, dedicated or not.
Pricing depends on the machine and what you need on it, so it is quoted per setup rather than listed. Each one is maintained personally, which is why slots are limited. Write to [email protected] with your expected licence volume and whether you want a custom bot or domain.