Skip to content

About

Official C++ SDK for AuthForge — license key authentication with HMAC-verified heartbeats

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

51 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AuthForge C++ SDK

Official C++ SDK for AuthForge: credit-based license key authentication with Ed25519-verified responses.

CMake library. One public header (authforge_sdk.h) and two implementation files (authforge_sdk.cpp, authforge_offline.cpp) packaged as authforge_sdk, linking libsodium (Ed25519), OpenSSL (SHA and helpers), and libcurl (HTTP). Targets C++17. Works on Windows (MSVC), Linux (GCC/Clang), and macOS (Clang).

How licensing works

  1. Activate: the SDK validates the license key online via POST /auth/validate. The server checks revocation, expiry, HWID binding, and credits, then returns an Ed25519-signed session with a TTL.
  2. Grace period: by default the app keeps running on that signed session for the length of the session TTL (default 24h, server clamps 1h to 7d). A background loop re-verifies the signed session locally. With session renewal (on by default) it also refreshes the session with one check-in once at most a fifth of it is left and renews it once it has run out, so a running app is not cut off at the end of the TTL (see Session renewal and the clocks).
  3. Online check-ins (optional): opt in with authforge::OnlineHeartbeat::On to have the SDK call POST /auth/heartbeat every heartbeatInterval seconds. Check-ins pick up a revocation, an expiry or a device reset; they do not detect two copies on one device ID.

Features

Everything in this list ships in authforge_sdk.h / authforge_sdk.cpp today:

  • License activation via POST /auth/validate, returning a signed ValidateLicenseResult.
  • Ed25519 signature verification (libsodium) on every /auth/validate, /auth/heartbeat and /auth/renew response; tampered or unsigned responses are rejected.
  • Key rotation: a single-key constructor (also accepts a comma-separated string) and a std::vector<std::string> rotation-set constructor. The SDK trusts a signature that matches any key, so you can roll the server-side signing key without breaking deployed clients.
  • Nonce anti-replay: every request attempt, a retry included, carries a fresh 128-bit nonce, and the nonce echoed in the signed payload must be that attempt's.
  • Response binding: a validate, renewal or check-in response is accepted only when the HWID and license key signed into it (when it carries them) are exactly this client's, so a response issued for one device and license is rejected on another (signature_mismatch).
  • HWID v2: sha256("authforge-hwid-v2|" + appId + "|" + machineId) from the OS machine id (macOS IOPlatformUUID, Linux /etc/machine-id, Windows MachineGuid). Stable across network changes and identical across all AuthForge SDKs for the same app and machine; falls back to the legacy MAC + CPU + disk serial fingerprint only when no OS id can be read, and then writes the reason to stderr. GetHwidSource() says which (machine-id, legacy or override). Cloned VM images and containers share the OS machine id, and so the HWID: regenerate the machine id on each clone, or pass a per-instance hwidOverride.
  • hwidOverride: bind to any identity instead of the machine (for example tg:<id>, discord:<id>).
  • Seat enforcement: the server binds each HWID into a license's free slots up to maxHwidSlots; maxHwidSlots / hwidCount are surfaced on the validate result. A shared (unlimited-seat) key skips per-device binding.
  • Grace period by default, online check-ins on demand (see Grace period and online check-ins).
  • Session renewal (on by default; SetAutoRenew(false) turns it off): a running app's session is refreshed and renewed instead of ending at the end of its TTL. Expiry is measured on a monotonic clock and the wall clock, so setting the clock back does not extend a session.
  • Offline license files (.authforge): LoginFromFile() / VerifyLicenseFile() verify a cloud-minted, Ed25519-signed file with zero network access for air-gapped machines.
  • Self-serve offline activation: ActivateOffline(key, path) turns a license key into a lifetime, HWID-bound .authforge file with one online call, verifies it locally and writes it atomically (see Self-serve offline activation).
  • Self-ban (SelfBan(...)) for anti-tamper response, both pre-session and post-session. It blocks the caller's IP address only when asked (blacklistIp is false by default, as on the server).
  • Grace period duration control (ttlSeconds) with server-side clamping to [3600, 604800].
  • App variables / license variables for feature flags and tiered licensing, readable for the whole session (online check-ins keep them).
  • Automatic retries for rate-limited requests and for requests that got no HTTP answer, each attempt with a fresh nonce.
  • Typed failures: authforge::AuthForgeError carries the server code plus a transient/definitive classification (see Failure Handling). Nothing exits the process unless you call SetExitOnFailure(true), and GetLastFailure() says why Login() returned false.
  • HTTPS only: an http:// base URL is refused unless it points at this machine (127.0.0.1, ::1, localhost); an answer over 1 MiB is not read.

There is no C++ package registry for this SDK. Ship source via GitHub Releases (tag v*, source archive) or by cloning the repository, then build with CMake as below.

Quick Start

Add authforge_sdk.h, authforge_sdk.cpp and authforge_offline.cpp to your project (or link the CMake package, see Building), then:

#include "authforge_sdk.h"
#include <iostream>
#include <string>

int main() {
    authforge::AuthForgeClient client(
        "YOUR_APP_ID",           // from your AuthForge dashboard
        "YOUR_APP_SECRET",       // from your AuthForge dashboard
        "YOUR_PUBLIC_KEY"        // base64 Ed25519 public key from dashboard
    );
    // Default policy: activate online once, then run through the grace
    // period (no network). Pass authforge::OnlineHeartbeat::On as the 4th
    // argument to enable online check-ins.

    std::string key;
    std::cout << "Enter license key: ";
    std::getline(std::cin, key);

    if (client.Login(key)) {
        std::cout << "Authenticated!" << std::endl;
        // Your app logic here; the background session check runs automatically.
        // Check client.IsAuthenticated() (or set onFailure) to learn that the
        // license was revoked or the session ended.
    } else {
        // invalid_key, expired, network_error, ... (see Failure Handling)
        const auto failure = client.GetLastFailure();
        std::cout << "Login failed: " << (failure ? failure->code : "unknown") << std::endl;
        return 1;
    }

    return 0;
}

By default nothing in the SDK exits the process. Without onFailure, a session that ends in the background (revoked, expired, ...) writes AuthForge: session ended (<code>) to stderr and IsAuthenticated() turns false; the app keeps running unless it checks. 2.0.1 called std::exit(1) instead; client.SetExitOnFailure(true) restores that.

Building

CMake

cmake -S . -B build
cmake --build build
cmake --install build --prefix /your/prefix

CMake must be able to find libsodium, OpenSSL, and libcurl (headers and libraries). libsodium is taken from its CMake package (vcpkg's unofficial-sodium), else from pkg-config (libsodium.pc), else from a search for sodium.h and the library; the installed AuthForgeConfig.cmake finds it again the same way. Examples:

  • Linux (Debian/Ubuntu): sudo apt install libsodium-dev libssl-dev libcurl4-openssl-dev
  • macOS (Homebrew): brew install libsodium openssl curl. If CMake does not pick up Homebrew paths automatically, set CMAKE_PREFIX_PATH to your prefix (often /opt/homebrew on Apple Silicon, /usr/local on Intel).
  • Windows: Install dependencies with vcpkg, then configure with its toolchain file, for example:
    vcpkg install libsodium:x64-windows openssl:x64-windows curl:x64-windows
    cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=%VCPKG_ROOT%\scripts\buildsystems\vcpkg.cmake
    (Adjust triplet and VCPKG_ROOT to match your setup.)

Using from another CMake project

find_package(AuthForge CONFIG REQUIRED)
target_link_libraries(yourapp PRIVATE AuthForge::authforge_sdk)

Configuration

Parameter Type Default Description
appId string required Your application ID from the AuthForge dashboard
appSecret string required for online APIs; "" for LoginFromFile only Your application secret from the AuthForge dashboard. Do not ship it in air-gapped binaries.
publicKey std::string / std::vector<std::string> required App Ed25519 public key(s) (base64) from dashboard. The single-string overload accepts a comma-separated trust list; the std::vector<std::string> overload takes a rotation set. The SDK trusts a signature matching any key (see Key rotation).
onlineHeartbeat authforge::OnlineHeartbeat OnlineHeartbeat::Off Off (default): run through the grace period on the signed session, no network after activation. On: enable online check-ins via /auth/heartbeat (see below).
heartbeatInterval int 900 Seconds between background checks (minimum 10; default 15 min). With online check-ins enabled, this is the check-in cadence. An interval of at least half the session TTL writes AuthForge: heartbeatInterval <n>s is at least half the session TTL <ttl>s; sessions may lapse between background checks to stderr at construction.
apiBaseUrl string https://auth.authforge.cc API endpoint. Must be https://; http:// is accepted only for 127.0.0.1, ::1 or localhost (a test server or a local proxy). Any other http:// URL throws std::invalid_argument, because the app secret and license key would cross the network in clear text.
onFailure std::function nullptr Callback (const string&, const exception*) for Login and background check failures. Optional: nothing exits the process either way (see Failure Handling).
requestTimeout int 15 HTTP request timeout in seconds; the connection itself must open within the smaller of this and 10 s
ttlSeconds int 0 (server default: 86400) Requested grace period duration in seconds (the session token lifetime). 0 means "server default" (24h). Server clamps to [3600, 604800] (1h to 7d); preserved across heartbeat refreshes.
hwidOverride string "" Optional custom hardware/subject identifier. When non-empty, the SDK uses this value instead of the HWID derived from the OS machine id.

Setters and accessors

Member Default Description
SetAutoRenew(bool) true Session renewal. Call before Login(). See Session renewal and the clocks.
SetExitOnFailure(bool) false true restores 2.0.1: std::exit(1) when Login() fails without onFailure, when a definitive background failure has no onFailure, and when onFailure throws. From the background thread the exit is std::quick_exit(1) (std::_Exit(1) on macOS, which has no quick_exit): static destructors do not run while main() is still using them, and buffered output (std::cout redirected to a file, for example) is not flushed. LoginFromFile() never exits.
GetLastFailure() none std::optional<authforge::AuthForgeFailure> with reason (login_failed, heartbeat_failed, offline_login_failed), code and message (the exception's what()). Recorded before onFailure runs, with or without a callback. A successful Login(), LoginFromFile() or ActivateOffline() clears it; Logout() does not. A default-mode refresh or renewal that fails transiently is not reported, so it is not recorded either.
GetHwidSource() "machine-id", "legacy" or "override": where GetHwid() comes from.

Identity-based binding example (Telegram/Discord)

authforge::AuthForgeClient client(
    "YOUR_APP_ID",
    "YOUR_APP_SECRET",
    "YOUR_PUBLIC_KEY",
    authforge::OnlineHeartbeat::On,
    900,
    authforge::AuthForgeClient::kDefaultApiBaseUrl,
    onFailure,
    15,
    0,
    "tg:" + std::to_string(telegramUserId) // or "discord:" + std::to_string(discordUserId)
);

Key rotation

To rotate the server-side signing key without a flag-day, construct the client with the new and previous keys via the std::vector<std::string> overload; the SDK accepts a signature matching any entry:

authforge::AuthForgeClient client(
    "YOUR_APP_ID",
    "YOUR_APP_SECRET",
    std::vector<std::string>{ "NEW_PUBLIC_KEY", "PREVIOUS_PUBLIC_KEY" }
);

client.GetPublicKeys() returns the full trust list. A comma-separated single string ("NEW,PREVIOUS") works too, for env-var convenience.

Billing

  • One Login() or ValidateLicense() call = 1 credit (one /auth/validate debit each).
  • 10 online check-ins = 1 credit, counted per license (debited on every 10th successful check-in of the license, whichever session sent it).
  • One renewal (/auth/renew) = 1 credit, like a login (it never takes a new seat).
  • The default grace period mode with renewal on (the default) sends one check-in each time a session nears its end (once at most a fifth of its lifetime is left), billed like any check-in, so a process that runs for days pays about a tenth of a credit per session lifetime. It pays a renewal only when it could not refresh in time: offline for the last fifth of the session, asleep past its end, or a check-in answered session_expired (for example after an app secret rotation). With SetAutoRenew(false) it makes no network call after activation and the session ends at the end of its TTL, as in 2.0.1.
  • 1 new offline activation (ActivateOffline()) = 2 credits, charged to the app owner. Re-activating the same machine is free.

A desktop app with online check-ins running 6h/day at a 15-minute interval burns ~3-4 credits/day. /auth/heartbeat is limited to 6 requests/minute per license key, so keep intervals at 10 seconds or higher and choose cadence based on revocation speed needs (revocations always land on the next check-in).

Methods

Method Returns Description
Login(const std::string&) bool Activates the key online and stores the signed session (sessionToken, expiresIn, appVariables, licenseVariables). false on failure: GetLastFailure() (or onFailure) says why
ValidateLicense(const std::string&) ValidateLicenseResult Same /auth/validate + signatures as Login; does not persist session or start background checks; never calls onFailure or std::exit; inspect valid / errorCode
SelfBan(licenseKey = "", sessionToken = "", revokeLicense = true, blacklistHwid = true, blacklistIp = false) bool Requests /auth/selfban to blacklist the HWID (and the IP when blacklistIp is true) and optionally revoke (session-authenticated only). Returns true; throws authforge::AuthForgeError when refused or unreachable and std::invalid_argument before any request (offline_session, missing_license_key, no app secret); never calls onFailure
LoginFromFile(const std::string&) bool Authorizes from an offline .authforge file (path or text) with no network; never starts background checks; failures go to onFailure("offline_login_failed", …) and GetLastFailure(); never exits
ActivateOffline(const std::string& licenseKey, const std::string& path = "") OfflineActivationResult Self-serve offline activation: one call to /auth/offline/activate, verifies the returned .authforge file, writes it atomically to path (when given) and starts an offline session as LoginFromFile does. Needs the app secret. Throws authforge::AuthForgeError on failure; never calls onFailure or std::exit
VerifyLicenseFile(const std::string&, long long nowEpochMs = 0) VerifyLicenseFileResult Verifies a .authforge file with this client's app id / keys / HWID without changing state
GetOfflineLicense() std::optional<OfflineLicense> Metadata of the offline file in use (jti, expiresAt, hwidPolicy, …)
GetSessionKind() SessionKind SessionKind::Online, SessionKind::Offline, or SessionKind::None when logged out
GetHwid() const std::string& The HWID this client sends (or hwidOverride); customers share it to receive a bound file
CreateActivationRequest(const ActivationRequestOptions& = {}) std::string Unsigned .authforge-request for this machine. No network, no secret. Hostname omitted unless includeMachineName
Logout() void Stops background checks and clears all session/auth state
IsAuthenticated() bool True while a session is running: an online session with lifetime left by the clock rule (false as soon as it runs out, before any background check), or an offline file whose expiresAt, if any, is still ahead. A pure query: it never ends the session or calls onFailure
SetAutoRenew(bool), SetExitOnFailure(bool), GetLastFailure(), GetHwidSource() See Setters and accessors
GetSessionDataJson() std::optional<std::string> Full decoded payload JSON
GetAppVariablesJson() std::optional<std::string> App variables JSON from the last Login() or offline file (if present); kept across online check-ins
GetLicenseVariablesJson() std::optional<std::string> License variables JSON from the last Login() or offline file (if present); kept across online check-ins

Grace period and online check-ins

Grace period (default). After a successful online activation, the app keeps running on the Ed25519-signed session. The background loop re-verifies the signed session locally every heartbeatInterval. With session renewal on (the default) it also sends one check-in once at most max(lifetime / 5, 2 × heartbeatInterval) of the session is left (one that fails transiently is not reported and the next interval tries again; a definitive answer such as revoked ends the session) and renews a session that has run out. With SetAutoRenew(false) it makes no request and ends the session with session_expired at the end of the TTL, as in 2.0.1. The TTL defaults to 24h, and the server clamps requested values (ttlSeconds) to 1h to 7d. This is session continuation after one successful online activation, not persistent offline licensing: a revocation takes effect at the next online validate, check-in or renewal.

Online check-ins (opt-in). Construct the client with authforge::OnlineHeartbeat::On and the SDK calls /auth/heartbeat every heartbeatInterval seconds with a fresh nonce, verifies signature + nonce, and triggers failure on invalid session state. A check-in refreshes the session but carries no variables: the app and license variables from Login() stay available, and a change made in the dashboard is picked up at the next Login() or renewal. A check-in answered session_expired renews the session in the same tick (renewal on). Definitive failures clear the session and stop check-ins; transient ones (network, server errors, no_credits, ...) are reported and check-ins continue (see Failure Handling). Choose this to pick up a revocation, an expiry or a device reset within one interval; check-ins do not detect two copies running on one device ID.

Session renewal and the clocks

Session renewal is on by default; client.SetAutoRenew(false) before Login() turns it off. A session is renewed when it has run out or when a check-in is answered session_expired: POST /auth/renew sends the app id and secret, the license key, the HWID, a fresh nonce (and ttlSeconds when set), and the answer is checked like a login answer (signature, nonce, the HWID and license key signed into it, lifetime). It replaces the session token, the expiry and both variable maps (a map the answer does not carry becomes none). A renewal costs 1 credit, like a login. The server never takes a seat for a renewal: a device whose seat was reset, or that no longer holds one, loses its session with hwid_mismatch at renewal, as a check-in would end it, and only a new Login() takes a free seat again. A definitive answer (revoked, expired, hwid_mismatch, ...) ends the session and is reported. A transient one keeps the session while its lifetime lasts (online check-ins report it as heartbeat_failed; the default mode tries again at the next interval without reporting it) and ends it with session_expired once the lifetime is over.

A session's lifetime is its signed expiry (lowered to a signed licenseExpiresAt) minus its signed timestamp, counted from the moment the answer arrived on two local clocks: a monotonic clock and the wall clock, whichever has advanced more. Setting the clock back does not extend a session, and time the machine spends asleep counts. A login, check-in or renewal answer with no lifetime left is refused with session_expired. IsAuthenticated() applies the rule when called, so it turns false as soon as the lifetime is over, before the next background check renews the session.

Offline license files (.authforge)

For machines that never connect to the internet, the operator mints a signed offline license file in the AuthForge dashboard (License page -> Mint .authforge file) or via POST /v1/licenses/{licenseKey}/offline-files. The file is a standalone Ed25519-signed document; the SDK verifies it with only your app public key and the machine HWID. It never contacts AuthForge and never starts the background thread. Pass an empty appSecret so the air-gapped binary does not contain the App Secret.

Grace period (default) Offline license file
Needs network At Login(), then one check-in per session lifetime while the app runs (none with SetAutoRenew(false)) Never on the end machine
What is verified Signed session from /auth/validate Signed document minted in the cloud
Lifetime Session TTL: 1h to 7d, renewed while the app runs (see Session renewal) Operator-chosen expiry or lifetime (perpetual licenses only)
Revocation Picked up at the next online validate, check-in or renewal Not reachable: the file stays valid until its own expiry
Cost 1 credit per Login(), a tenth of a credit per refresh check-in, 1 credit per renewal 1 credit per mint; verifying is free
authforge::AuthForgeClient client(
    "YOUR_APP_ID",
    "",  // LoginFromFile does not use the App Secret; do not ship it in air-gapped builds
    "YOUR_PUBLIC_KEY",
    authforge::OnlineHeartbeat::Off, 900, authforge::AuthForgeClient::kDefaultApiBaseUrl,
    [](const std::string &reason, const std::exception *exc) {
      std::cerr << reason << (exc ? std::string(": ") + exc->what() : "") << "\n";
    });

// 1. Write an activation request the operator drops into the mint dialog:
std::string request = client.CreateActivationRequest();

// 2. Later, authorize from the minted file (path or armored text). No network.
if (client.LoginFromFile("license.authforge")) {
  const auto info = client.GetOfflineLicense();
  std::cout << "Offline license OK until " << (info->expiresAt ? *info->expiresAt : "forever") << "\n";
}

Since 2.0 (HWID v2) every AuthForge SDK reports the same HWID for the same app id and machine, so the HWID can be collected with any SDK; files bound to a pre-2.0 HWID must be re-issued. After LoginFromFile(), GetSessionKind() returns SessionKind::Offline (SessionKind::Online after Login(), SessionKind::None when logged out).

authforge::VerifyLicenseFile(text, appId, publicKeys, hwid) (free function) and client.VerifyLicenseFile(pathOrText) perform the same checks without touching client state and return a VerifyLicenseFileResult (ok, error, license). Failure codes, in check order: bad_armor, bad_signature, unsupported_version, malformed_payload, wrong_app, expired, hwid_mismatch. LoginFromFile() reports them through onFailure("offline_login_failed", &exc) (with exc.what() = code) and returns false; it never calls std::exit.

File format (version 1): PEM-style armor with informational headers, a base64 JSON payload (v, appId, licenseKey, jti, kid, issuedAt, expiresAt, hwid policy, optional label/variable snapshots) and a detached Ed25519 signature over the UTF-8 bytes of the base64 payload string - the same contract as /auth/validate. See offline_license_vectors.json for conformance vectors and tests/offline_vectors_test.cpp (build with -DAUTHFORGE_BUILD_TESTS=ON, run with ctest).

Self-serve offline activation

A separate mode for apps sold as a one-time purchase: the end user types the license key once, the app makes one online call, and from then on runs from a lifetime .authforge file with no network calls. The operator enables it per app (offlineSelfServe), and it only works for perpetual, seat-limited licenses.

  • Needs the App Secret, unlike air-gapped builds (which still pass "" and use operator-minted files).
  • 2 credits per new machine, charged to the app owner. The same machine activating again (reinstall, deleted file) gets the identical file back for free.
  • A license can produce files for at most maxHwidSlots machines, ever. HWID resets do not free those slots; the vendor can release a machine from the dashboard.
  • A refund, chargeback or revoke cannot reach files already issued. The license is revoked online, but a lifetime file keeps working.
const std::string licensePath = "license.authforge";

authforge::AuthForgeClient client("YOUR_APP_ID", "YOUR_APP_SECRET", "YOUR_PUBLIC_KEY",
                                  authforge::OnlineHeartbeat::Off, 900,
                                  authforge::AuthForgeClient::kDefaultApiBaseUrl,
                                  onFailure);

// 1. Use the file if this machine already has one. No network, no credits.
if (!(std::filesystem::exists(licensePath) && client.LoginFromFile(licensePath))) {
  // 2. No file, or it no longer matches this machine: ask for the key once.
  const std::string key = PromptForKey();
  try {
    client.ActivateOffline(key, licensePath); // verifies, writes the file, starts an offline session
  } catch (const authforge::AuthForgeError &e) {
    if (e.code() == "offline_activation_limit_reached") {
      ShowError("This license is active on its maximum number of machines. Please contact the vendor.");
    } else if (e.code() == "hwid_mismatch") {
      ShowError("No free seat on this license for this machine.");
    } else if (e.isTransient()) {
      ShowError("Could not activate right now (" + e.code() + "). Check your connection and try again.");
    } else {
      ShowError("Activation refused: " + e.code());
    }
    return 1;
  }
}
// Authenticated: GetSessionKind() == SessionKind::Offline, variables available, no background checks.

ActivateOffline(licenseKey, path = "") returns an OfflineActivationResult (file, fileName, jti, replay); replay is true when the server returned this machine's existing file without charging. The SDK sends the same HWID and nonce generator as Login(), uses the same retry policy, and verifies the returned file (signature against your public key(s), app id, this machine's HWID) before writing anything. With a non-empty path the file is written byte-for-byte through a temp file in the same directory and an atomic replace, creating parent directories; with an empty path nothing is written and result.file holds the text.

An empty license key or a missing App Secret throws std::invalid_argument without sending a request. Every other failure throws authforge::AuthForgeError; nothing is written, an existing file at path is left untouched, an existing session is not touched and the client is not authenticated. It never calls onFailure or std::exit.

Code Class Meaning
offline_activation_disabled definitive The app has not enabled self-serve activation
offline_activation_requires_perpetual definitive The license has an expiry; only perpetual licenses can self-serve
offline_activation_requires_seats definitive Unlimited-seat (shared) keys cannot self-serve
offline_activation_limit_reached definitive Every machine slot on the license is used; tell the user to contact the vendor
hwid_mismatch definitive No free seat for this machine
offline_file_rejected definitive The returned file failed local verification; what() carries the reason (offline_file_rejected: bad_signature, hwid_mismatch, wrong_app, ...)
file_write_failed transient Writing path failed (permissions, disk); the client is not authenticated. Retrying is free for the same machine
unexpected_response transient Malformed response (for example a success without a file)
others as in Failure Handling invalid_key, revoked, no_credits, rate_limited, network_error, ...

Migrating from heartbeatMode

Earlier versions took a std::string heartbeatMode ("LOCAL" or "SERVER") as the 4th constructor parameter. That parameter is replaced by authforge::OnlineHeartbeat:

  • "LOCAL" maps to the default (grace period behavior): drop the argument entirely.
  • "SERVER" maps to authforge::OnlineHeartbeat::On.
// Before:
authforge::AuthForgeClient client("APP_ID", "APP_SECRET", "PUBLIC_KEY", "LOCAL");
// After (grace period is the default):
authforge::AuthForgeClient client("APP_ID", "APP_SECRET", "PUBLIC_KEY");

// Before:
authforge::AuthForgeClient client("APP_ID", "APP_SECRET", "PUBLIC_KEY", "SERVER");
// After:
authforge::AuthForgeClient client("APP_ID", "APP_SECRET", "PUBLIC_KEY",
                                  authforge::OnlineHeartbeat::On);

The old string-mode constructors still work and behave exactly as before, but they emit a deprecation warning at compile time.

Failure Handling

If authentication fails, the SDK calls your onFailure callback if one is provided, and GetLastFailure() keeps the last failure either way. Nothing exits the process unless you call SetExitOnFailure(true). Without a callback, a failed Login() returns false and writes nothing; a transient background check failure (network outage, rate_limited, system_error, ...) writes AuthForge: background check failed (<code>); retrying next interval to std::cerr and check-ins continue; a definitive one (a revocation, a session that ran out and could not be renewed, ...) ends the session (IsAuthenticated() turns false, check-ins stop) and writes AuthForge: session ended (<code>). An app written for 2.0.1, which called std::exit(1) here, keeps running after a revocation unless it checks IsAuthenticated(), sets onFailure, or calls SetExitOnFailure(true). A throwing onFailure is ignored (with the opt-in it exits, as in 2.0.1).

ValidateLicense() always returns a ValidateLicenseResult and does not invoke onFailure or exit the process.

Login() and background checks pass an authforge::AuthForgeError as exc, with code(), isTransient() and isFatal(). For server codes exc->what() equals the code. A non-2xx response with a JSON body yields the server's clean code on both login and check-ins (what() is invalid_key, not http_error_401: {...}); only non-JSON error pages become http_error_<status>. authforge::IsTransientErrorCode(code) exposes the same classification. ActivateOffline() and SelfBan() throw the same authforge::AuthForgeError to their caller instead of calling onFailure.

Class Codes Background check (heartbeat_failed)
Definitive revoked, expired, hwid_mismatch, blocked, session_expired, malformed_request, app_disabled, invalid_app, signature_mismatch, and for ActivateOffline(): offline_activation_disabled, offline_activation_requires_perpetual, offline_activation_requires_seats, offline_activation_limit_reached, offline_file_rejected The session is cleared (Logout()) before onFailure runs, so IsAuthenticated() is false; check-ins stop
Transient Everything else: rate_limited, system_error, no_credits, demo_quota_exceeded, app_burn_cap_reached, bad_request, invalid_key, replay_detected, unexpected_response, http_error_<status>, invalid_json_response, response_not_json_object, network_error, timeout, and any unknown code The session is kept, onFailure runs, and check-ins continue at the next interval
  • With renewal off, a transient check-in failure after the session's lifetime has passed is reported as session_expired (definitive), and the default mode ends the session with session_expired at the end of its lifetime. With renewal on, both renew first; session_expired is reported only when the lifetime is over and the renewal did not succeed.
  • On check-ins, hwid_mismatch means this device's HWID is no longer bound to the license (for example after an HWID reset), and blocked means the HWID or IP is blacklisted or not on the app's whitelist.
  • unexpected_response means a check-in failure body that is not {"status":"failed","error":"<code>"} (for example a proxy error in JSON). It is never treated as a verdict; what() keeps the raw status/error.
  • signature_mismatch is reported for a response whose signature does not verify and for a correctly signed validate, renewal or check-in response whose hwid or licenseKey is not this client's (the ones it sent; for a check-in, the session's). In the second case the exception's what() is signature_mismatch: signed response is for a different device or license; ValidateLicenseResult::errorCode is the bare signature_mismatch.
  • Unknown snake_case server codes are passed through as-is instead of becoming unknown_error.

Request retries are automatic inside the internal HTTP layer, and every attempt carries a fresh nonce:

  • rate_limited (or HTTP 429 without an error code): retry after 2s, then 5s (max 3 attempts total)
  • no_credits, demo_quota_exceeded and app_burn_cap_reached also use HTTP 429 but are not retried; the next check-in happens at the next interval
  • no HTTP answer (connection refused or reset, closed before an answer, timeout): retry once after 2s, then fail with network_error or timeout (what() starts with url_error: ). Any answer that arrived is final and never sent again, even when the transfer broke off part way; an answer over 1 MiB is not read (network_error)

To tolerate short outages but shut down on a definitive answer, have the callback signal your main thread and let the main thread save and exit:

std::atomic<bool> licenseLost{false}; // must outlive the client

authforge::AuthForgeClient client(
    "YOUR_APP_ID",
    "YOUR_APP_SECRET",
    "YOUR_PUBLIC_KEY",
    authforge::OnlineHeartbeat::On,
    900,
    authforge::AuthForgeClient::kDefaultApiBaseUrl,
    [&licenseLost](const std::string& reason, const std::exception* exc) {
        if (auto* e = dynamic_cast<const authforge::AuthForgeError*>(exc); e && e->isTransient()) {
            std::cerr << "AuthForge " << reason << " (transient): " << e->code() << std::endl;
            return; // session kept; check-ins continue (Login() still returns false)
        }
        std::cerr << "Auth failed: " << reason << std::endl;
        if (exc) std::cerr << "Details: " << exc->what() << std::endl;
        // This can run on the heartbeat thread: signal the main thread instead of exiting here.
        licenseLost = true;
    }
);

if (!client.Login(licenseKey)) {
    return 1;
}

while (!licenseLost) {
    DoOneUnitOfWork(); // keep units short so the loop notices the signal quickly
}

SaveUserWork();
client.Logout();
return 1;

In a GUI app, post a message to the UI thread instead (for example PostMessage on Windows or QMetaObject::invokeMethod in Qt) and close the main window normally. Calling std::exit(1) inside onFailure is a last resort: it skips the destructors of objects on every thread's stack, so save the user's work first.

Thread safety. Background onFailure calls run on the heartbeat thread with no SDK lock held. Calling Logout(), IsAuthenticated() or Login() from the callback, or destroying the client inside it, is safe. Logout() stops check-ins without blocking; the destructor stops the heartbeat thread and joins it. A check-in or renewal in flight is aborted and its retry delay cut short, so neither waits for the network.

Self-ban (tamper response)

Use SelfBan(...) when anti-tamper checks trigger:

// Post-session (authenticated): revoke + HWID blacklist. The IP is not blocked by default.
client.SelfBan();

// Pre-session: pass license key, SDK automatically disables revokeLicense.
client.SelfBan("AF-XXXX-XXXX-XXXX");

// Also block the caller's IP address:
client.SelfBan("", "", true, true, true);

blacklistIp is false by default, as on the server: an IP address is often shared (an office, a school, a carrier's NAT), so blocking it can lock out other customers. SelfBan() returns true when the server accepts it and throws authforge::AuthForgeError when the server refuses or cannot be reached; it never calls onFailure and never exits.

SelfBan(...) chooses request mode automatically:

  • Uses post-session mode when a session token is available (sessionToken arg or current SDK session).
  • Falls back to pre-session mode with licenseKey + nonce + app secret.
  • In pre-session mode, revoke is always disabled client-side to avoid unsafe key revocations.
  • Not available after LoginFromFile(): offline sessions have no server session, so SelfBan() with no explicit licenseKey / sessionToken throws std::invalid_argument("offline_session") without contacting the server.

How It Works

  1. Activate: Login uses hwidOverride when non-empty; otherwise it derives the HWID from the OS machine id (HWID v2; legacy MAC + CPU + disk serial fingerprint only as a fallback). It then generates a random nonce and sends everything to the AuthForge API. The server validates the license key, binds the HWID, deducts a credit, and returns a signed payload. The SDK verifies the Ed25519 signature and nonce to prevent replay attacks, and checks that the HWID and license key in the signed payload are the ones it sent (a field the payload does not carry is not checked).

  2. Background checks: a background thread runs at the configured interval (Logout() stops it; the destructor stops it without waiting for the network). By default it re-verifies the stored signed session locally and, with renewal on, refreshes the session near its end and renews it once it has run out. With online check-ins enabled, it instead sends a fresh nonce to /auth/heartbeat each interval and verifies the response.

  3. Crypto: /validate, /heartbeat and /renew responses are signed by AuthForge with your app's Ed25519 private key. The SDK verifies every signed payload using your configured publicKey and rejects tampered responses.

  4. SDK identification: every request to the AuthForge API carries the header X-AuthForge-SDK: authforge-cpp/<version>. The version is the AUTHFORGE_SDK_VERSION macro in authforge_sdk.h and matches the CMake project version.

  5. Transport: libcurl over HTTPS only (plain HTTP only to this machine), with a connect timeout of the smaller of requestTimeout and 10 s, no signals (CURLOPT_NOSIGNAL), and answers capped at 1 MiB.

Test Vectors

The shared test_vectors.json file validates cross-language Ed25519 verification behavior. offline_license_vectors.json (generated from a fixed test seed in the Node SDK repo) is the cross-SDK conformance suite for .authforge offline license files: good files plus the bad_signature, wrong key, wrong_app, expired, hwid_mismatch, unsupported_version and bad_armor rejects. tests/heartbeat_test.cpp covers the heartbeat failure contract (classification, retries, session clearing, callback thread safety) against a fake transport. tests/self_serve_activation_test.cpp runs self_serve_activation_vectors.json (the cross-SDK suite for ActivateOffline()) against a fake transport. hwid_vectors.json (generated by authforge-node/generate_hwid_vectors.mjs, copied unmodified into every SDK) is the cross-SDK HWID v2 suite, run by tests/hwid_vectors_test.cpp (plus a live check on macOS). It also runs the legacy fingerprint's command runner and 2.0.1's shell-based one on the same output (tests/legacy_command_helper.cpp writes it) and checks they derive the same value. session_scenario_vectors.json (generated in the Node SDK, copied unmodified into every SDK) holds the cross-SDK session scenarios (login, background checks, lost responses, the clocks, renewal); tests/session_scenarios_test.cpp runs them against a fake server on 127.0.0.1 through the real libcurl transport, with sessions signed by the scenario key. Two tests use no vector file: tests/signed_response_test.cpp signs its own payloads to cover variables across check-ins, the HWID / license key check on validate and check-in responses, the session lifetime, SelfBan() and the http:// rule, and tests/request_header_test.cpp checks, through the real libcurl transport against a server on 127.0.0.1, the X-AuthForge-SDK header, the 1 MiB answer cap and that the destructor does not wait for a background request. Run them all with:

cmake -S . -B build -DAUTHFORGE_BUILD_TESTS=ON
cmake --build build
ctest --test-dir build --output-on-failure

Requirements

  • C++17
  • libsodium
  • OpenSSL
  • libcurl

License

MIT

About

Official C++ SDK for AuthForge — license key authentication with HMAC-verified heartbeats

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages