Clavem

License activation and deactivation in a C++ app

Call /v1/licenses/activate once per computer with the key, a device name and a salted SHA-256 of the machine id, then store the instance id. The machine id comes from IOKit on macOS, the registry on Windows and /etc/machine-id on Linux.

Activation ties a license key to one computer and returns an instance.id. Validation then sends it at each launch. This page covers the C++ specifics: reading the machine id on three platforms, hashing it, and handling every reply without exceptions. The post, text and json helpers are the ones from the validation page.

The machine id

The API accepts an optional fingerprint, up to 200 characters. With one, activating again from the same computer returns the same seat and updates its name. Without one, each reinstall takes another seat. Read the operating system’s id, then hash it with a string that belongs to your app, so the value you send cannot be matched to anything outside it:

#include <openssl/evp.h>
#include <fstream>
#if defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>      // link -framework IOKit -framework CoreFoundation
#elif defined(_WIN32)
#include <windows.h>
#endif

std::string sha256_hex(const std::string& text) {
  unsigned char digest[EVP_MAX_MD_SIZE];
  unsigned int len = 0;
  EVP_Digest(text.data(), text.size(), digest, &len, EVP_sha256(), nullptr);
  static const char* hex = "0123456789abcdef";
  std::string out;
  for (unsigned int i = 0; i < len; ++i) { out += hex[digest[i] >> 4]; out += hex[digest[i] & 15]; }
  return out;
}

std::optional<std::string> machine_id() {
#if defined(__APPLE__)
  io_registry_entry_t entry = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
  if (!entry) return std::nullopt;
  CFTypeRef value = IORegistryEntryCreateCFProperty(entry, CFSTR("IOPlatformUUID"), kCFAllocatorDefault, 0);
  IOObjectRelease(entry);
  if (!value) return std::nullopt;
  char buffer[128];
  bool ok = CFGetTypeID(value) == CFStringGetTypeID() &&
            CFStringGetCString(static_cast<CFStringRef>(value), buffer, sizeof buffer, kCFStringEncodingUTF8);
  CFRelease(value);
  return ok ? std::optional<std::string>(buffer) : std::nullopt;
#elif defined(_WIN32)
  char buffer[128];
  DWORD size = sizeof buffer;
  if (RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", "MachineGuid",
                   RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY, nullptr, buffer, &size) == ERROR_SUCCESS)
    return std::string(buffer);
  return std::nullopt;
#else
  for (const char* path : {"/etc/machine-id", "/var/lib/dbus/machine-id"}) {
    std::ifstream in(path);
    std::string id;
    if (in && std::getline(in, id) && !id.empty()) return id;
  }
  return std::nullopt;
#endif
}

std::optional<std::string> fingerprint(const std::string& salt) {
  auto id = machine_id();
  return id ? std::optional<std::string>(sha256_hex(salt + ":" + *id)) : std::nullopt;
}

The macOS branch was compiled and run, and returned 64 hex characters. CFStringGetCString can fail on a short buffer, and the code checks it. If machine_id returns nothing, send no fingerprint. Activation still works, at the cost of an extra seat per reinstall.

Activate

enum class ActivationKind { Activated, LimitReached, Refused, Unavailable };

struct Activation {
  ActivationKind kind;
  std::string instance_id, token, reason;
  int used = 0, limit = 0;
  std::optional<int> retry_after;
};

/// A number field, or -1 when it is missing or null. activation_limit is null for an unlimited license.
int whole(const json& o, const char* key) {
  auto it = o.find(key);
  return it != o.end() && it->is_number_integer() ? it->get<int>() : -1;
}

Activation activate(const std::string& base, const std::string& key, const std::string& device_name) {
  json body = {{"license_key", key}, {"instance_name", device_name}};
  if (auto fp = fingerprint("com.example.inkwell")) body["fingerprint"] = *fp;

  auto r = post(base, "activate", body);
  if (!r) return {ActivationKind::Unavailable, "", "", "", 0, 0, std::nullopt};
  std::string message = text(r->body, "error", "Activation failed.");

  if (r->status == 200 && r->body.contains("instance") && r->body["instance"].is_object())
    return {ActivationKind::Activated, text(r->body["instance"], "id"), text(r->body, "token"), "", 0, 0, std::nullopt};
  if (r->status == 400 || r->status == 404) {
    if (r->body.contains("license_key") && r->body["license_key"].is_object()) {
      const auto& lic = r->body["license_key"];
      int used = whole(lic, "activation_usage"), limit = whole(lic, "activation_limit");
      if (used >= 0 && limit >= 0 && used >= limit && message.find("activation limit") != std::string::npos)
        return {ActivationKind::LimitReached, "", "", message, used, limit, std::nullopt};
    }
    return {ActivationKind::Refused, "", "", message, 0, 0, std::nullopt};   // expired, disabled, unknown key
  }
  return {ActivationKind::Unavailable, "", "", "", 0, 0, r->retry_after};     // 429 or 5xx
}

The helper whole exists because activation_limit is null for an unlimited license, and nlohmann’s value throws on a null field. An expired license with no limit would otherwise crash the activation screen. Run against a local stub that returns the documented responses, with no live activation:

fingerprint length: 64
activated twice, same seat: 1
limit: 1 3/3
expired: This license key has expired.
unknown: license_key not found.
429: unavailable=1 retry_after=60
offline: unavailable=1

When every seat is taken

The 400 body carries the license with activation_usage and activation_limit, so the UI can say “3 of 3 computers are in use”. Point the customer to the device page at /licenses/manage, where they enter their key, see each computer and remove one, with no account. Do not offer a retry. It cannot succeed until a seat is free.

Deactivate

/// True when the seat is free: the server said so, or said it was already gone (404).
bool deactivate(const std::string& base, const std::string& key, const std::string& instance_id) {
  auto r = post(base, "deactivate", {{"license_key", key}, {"instance_id", instance_id}});
  return r && (r->status == 200 || r->status == 404);
}

Offline it returned false. Keep the saved ids in that case and tell the customer that the seat is still taken and can be removed from the device page. After a true, delete the stored license. A second deactivate returned true too, because a 404 means the seat is already gone. Wire it to a menu item, not to a destructor or atexit.

What differs in C++ builds

  • Static and dynamic builds report the same id. The id comes from the operating system, not from your binary, so changing how you link does not change seats.
  • Cloned images share ids. A machine-id file baked into a VM or container image is copied with it, so clones share one seat. Reset it when you build images.
  • Windows service versus user. HKEY_LOCAL_MACHINE is readable without elevation, so the same code works in a service and in a user app.
  • Unicode device names. instance_name is a JSON string. Convert Windows wide strings to UTF-8 before you put them in the body, or nlohmann throws on invalid UTF-8 when it dumps.

Doing this with Clavem

The device limit comes from the product, three by default, and PATCH /v1/admin/licenses/:id can change it for one license. Activation moves a license from inactive to active, and the last deactivation moves it back. See the API reference for the fields and errors.

Questions

How do I get a stable machine id in C++?

Read the operating system's own id. That is IOPlatformUUID through IOKit on macOS, the MachineGuid registry value on Windows and the machine-id file on Linux. Hash it with a salt that belongs to your app before you send it.

Why use RRF_SUBKEY_WOW6464KEY on Windows?

A 32-bit process on 64-bit Windows can be redirected to a different registry view. The flag makes RegGetValue read the 64-bit view, so 32-bit and 64-bit builds of your app report the same MachineGuid.

Should the app deactivate on exit?

No. Quitting does not move a license to another computer. Deactivate on an explicit action such as Move this license, and keep the saved ids if the call cannot reach the server.