Clavem

How to validate a license key in a C++ app

POST the key and the saved instance id to /v1/licenses/validate with libcurl, keep the response body on 4xx and 5xx by leaving CURLOPT_FAILONERROR off, and map the answer to an enum. Store the key in the platform's secret store and set timeouts so a launch cannot hang.

C++ has no standard HTTP, JSON or secret-store library, so every project picks its own. This page uses the common choices: libcurl for HTTP, nlohmann/json for JSON, and the Keychain or DPAPI for storage. It covers the online validate call. The token check for the offline path is in offline verification in C++, and the first-run call is in device activation in C++.

The call

post returns nothing when there is no HTTP answer at all, and a Reply with the status, the parsed body and any Retry-After for everything else. libcurl handles are wrapped in unique_ptr, so every path frees them:

#include <curl/curl.h>
#include <nlohmann/json.hpp>
#include <algorithm>
#include <memory>
#include <optional>
#include <string>

using json = nlohmann::json;

struct Reply { long status = 0; json body; std::optional<int> retry_after; };

struct CurlDeleter { void operator()(CURL* h) const { curl_easy_cleanup(h); } };
struct SlistDeleter { void operator()(curl_slist* l) const { curl_slist_free_all(l); } };

static size_t append(char* d, size_t s, size_t n, void* out) { static_cast<std::string*>(out)->append(d, s * n); return s * n; }
static size_t on_header(char* d, size_t s, size_t n, void* out) {
  std::string line(d, s * n);
  auto colon = line.find(':');
  if (colon != std::string::npos) {
    std::string name = line.substr(0, colon);
    std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return std::tolower(c); });
    if (name == "retry-after") { try { *static_cast<std::optional<int>*>(out) = std::stoi(line.substr(colon + 1)); } catch (...) {} }
  }
  return s * n;
}

std::optional<Reply> post(const std::string& base, const std::string& action, const json& body) {
  std::unique_ptr<CURL, CurlDeleter> curl(curl_easy_init());
  if (!curl) return std::nullopt;
  std::string payload = body.dump(), raw;
  Reply reply;
  std::unique_ptr<curl_slist, SlistDeleter> headers(
      curl_slist_append(curl_slist_append(nullptr, "Content-Type: application/json"), "User-Agent: Inkwell/3.2"));

  curl_easy_setopt(curl.get(), CURLOPT_URL, (base + "/v1/licenses/" + action).c_str());
  curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers.get());
  curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, payload.c_str());
  curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDSIZE, static_cast<long>(payload.size()));
  curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, 8L);
  curl_easy_setopt(curl.get(), CURLOPT_CONNECTTIMEOUT, 5L);
  curl_easy_setopt(curl.get(), CURLOPT_NOSIGNAL, 1L);                // needed for timeouts in threaded programs
  curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, append);
  curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &raw);
  curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, on_header);
  curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &reply.retry_after);
  // Do not set CURLOPT_FAILONERROR: it discards the body of 4xx and 5xx replies.

  if (curl_easy_perform(curl.get()) != CURLE_OK) return std::nullopt;   // offline, DNS failure, timeout
  curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &reply.status);
  reply.body = json::parse(raw, nullptr, /*allow_exceptions=*/false);
  if (!reply.body.is_object()) reply.body = json();
  return reply;
}

Call curl_global_init once at startup, before any thread uses libcurl, and curl_global_cleanup at exit. A small RAII struct in main does both.

Map the answer

enum class Kind { Valid, NotValid, Unknown, NoAnswer };
struct Outcome { Kind kind; std::string token, reason; std::optional<int> retry_after; };

// body.value("error", "...") throws when "error" exists and is null, which it is on every success.
std::string text(const json& body, const char* key, const std::string& fallback = "") {
  auto it = body.find(key);
  return it != body.end() && it->is_string() ? it->get<std::string>() : fallback;
}

Outcome validate(const std::string& base, const std::string& key, const std::string& instance_id = "") {
  json body = {{"license_key", key}};
  if (!instance_id.empty()) body["instance_id"] = instance_id;
  auto reply = post(base, "validate", body);
  if (!reply) return {Kind::NoAnswer, "", "", std::nullopt};

  std::string message = text(reply->body, "error", "This license is not valid.");
  switch (reply->status) {
    case 200:
      if (!reply->body.contains("valid") || !reply->body["valid"].is_boolean()) return {Kind::NoAnswer, "", "", std::nullopt};
      return {reply->body["valid"].get<bool>() ? Kind::Valid : Kind::NotValid, text(reply->body, "token"), message, std::nullopt};
    case 404: return {Kind::Unknown, "", message, std::nullopt};
    case 429:
    case 503: return {Kind::NoAnswer, "", "", reply->retry_after};
    default:  return {Kind::NoAnswer, "", "", std::nullopt};   // 400 is a bug in the app; other 5xx is on the server
  }
}
Reply Kind What the app does
200, valid: true Valid Store the new token. This restarts the 14-day window.
200, valid: false NotValid Expired or disabled. Store the token, show the reason, keep the key.
404 Unknown Unknown key or instance_id not found. Clear the license, ask for the key.
429, 503 NoAnswer No verdict. Use the stored token and retry later.

Real output

The code above, built with clang++ and Homebrew’s libcurl, against the live API with the demo key and a local stub for the rest:

demo key (live): valid token=sgt1.eyJ2Ijo...
unknown key (live): unknown reason="license_key not found."
unknown instance (live): unknown reason="instance_id not found."
empty body (live): 400 {"error":"license_key: Invalid input: expected string, received undefined","valid":false}
stub 429: no-answer retry_after=60
stub 503: no-answer retry_after=5
slow server: no-answer, after 8 s

The first run crashed on the very first call, with type must be string, but is null: value("error", ...) on a reply whose error is null. That is why text exists. A 503 asks for 5 seconds and a 429 for 60. Retry the 503 once on a worker thread, and use the stored token for both.

Where to keep the key

C++ has no portable secret store, so write a small interface and implement it per platform. On macOS, the Keychain through the Security framework works with SecItemUpdate, falling back to SecItemAdd. The wrapper below releases every CoreFoundation object with RAII. Its roundtrip was tested: set, read back, update, remove.

// macOS: link -framework Security -framework CoreFoundation
#include <Security/Security.h>

template <class T>
struct Cf {  // releases a CoreFoundation object when it goes out of scope
  T ref;
  explicit Cf(T r = nullptr) : ref(r) {}
  ~Cf() { if (ref) CFRelease(ref); }
  Cf(const Cf&) = delete;
  Cf(Cf&& o) noexcept : ref(o.ref) { o.ref = nullptr; }
};

Cf<CFMutableDictionaryRef> query(const std::string& service, const std::string& account) {
  Cf<CFMutableDictionaryRef> q(CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
  Cf<CFStringRef> s(CFStringCreateWithCString(nullptr, service.c_str(), kCFStringEncodingUTF8));
  Cf<CFStringRef> a(CFStringCreateWithCString(nullptr, account.c_str(), kCFStringEncodingUTF8));
  CFDictionarySetValue(q.ref, kSecClass, kSecClassGenericPassword);
  CFDictionarySetValue(q.ref, kSecAttrService, s.ref);
  CFDictionarySetValue(q.ref, kSecAttrAccount, a.ref);
  return q;
}

bool keychain_set(const std::string& service, const std::string& account, const std::string& value) {
  Cf<CFDataRef> data(CFDataCreate(nullptr, reinterpret_cast<const UInt8*>(value.data()), value.size()));
  auto q = query(service, account);
  Cf<CFMutableDictionaryRef> update(CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
  CFDictionarySetValue(update.ref, kSecValueData, data.ref);
  OSStatus status = SecItemUpdate(q.ref, update.ref);
  if (status == errSecItemNotFound) {
    CFDictionarySetValue(q.ref, kSecValueData, data.ref);
    CFDictionarySetValue(q.ref, kSecAttrAccessible, kSecAttrAccessibleAfterFirstUnlock);
    status = SecItemAdd(q.ref, nullptr);
  }
  return status == errSecSuccess;
}

keychain_get and keychain_remove follow the same pattern with SecItemCopyMatching and SecItemDelete. On Windows, DPAPI protects a value for the current user. Example output:

// Windows: link crypt32.lib
#include <windows.h>
#include <dpapi.h>
#include <vector>

std::vector<BYTE> protect(const std::string& text) {
  DATA_BLOB in{static_cast<DWORD>(text.size()), reinterpret_cast<BYTE*>(const_cast<char*>(text.data()))}, out{};
  if (!CryptProtectData(&in, L"Inkwell license", nullptr, nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &out)) return {};
  std::vector<BYTE> blob(out.pbData, out.pbData + out.cbData);
  LocalFree(out.pbData);
  return blob;   // write this to a file under %LOCALAPPDATA%
}

On Linux, libsecret is the usual choice, and it needs a running Secret Service. Without one, fall back to a file with 0600 permissions and say so.

Pitfalls specific to C++

  • CURLOPT_FAILONERROR hides the answer. Without the body you cannot show error, and without the headers you cannot see Retry-After.
  • CA certificates. A libcurl built with OpenSSL on Linux or Windows needs to find a CA bundle. If HTTPS works on your machine and fails on a customer’s, set CURLOPT_CAINFO, or build with the platform’s TLS backend.
  • Never call it on the UI thread. Even an 8-second timeout freezes a window. Run the check on a worker and post the result back.
  • curl_global_init is not thread safe. Call it once, early.

Doing this with Clavem

The License API needs no secret, so the binary holds nothing sensitive. Plan limits never block validation. See the API reference for every field.

Questions

Why does libcurl give me no body for a 404 from the License API?

You probably set CURLOPT_FAILONERROR. It makes libcurl fail on status 400 and above and discard the body, so you lose the error message and the Retry-After header. Leave it off and read the status with CURLINFO_RESPONSE_CODE.

Why does nlohmann json throw on the error field of a valid response?

A successful reply has an error field set to null. json::value with a string default throws a type error when the key exists but is null. Check that the field is a string before you read it.

Do I need CURLOPT_NOSIGNAL?

Yes, in any program with more than one thread. libcurl's timeout handling can otherwise use signals, which is unsafe in threads. Set it on every handle that uses a timeout.

Sources

  1. libcurl, CURLOPT_FAILONERROR (checked November 2026)
  2. libcurl, CURLOPT_NOSIGNAL (checked November 2026)