Skip to content

About

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

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

43 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AuthForge Go SDK

Official Go SDK for AuthForge. Activate a license online with an Ed25519-verified response, then keep running on the signed session by default (renewed automatically near its end), or opt in to online check-ins so a revocation takes effect within one interval.

Zero external dependencies. Uses only the Go standard library.

How licensing works

  1. Activate (validate) online. Login calls POST /auth/validate. The server checks revocation, expiry, HWID slots, and credits, and returns an Ed25519-signed session with a TTL.
  2. Grace period (the default). After activation, the app keeps running on the signed session. The SDK re-verifies it locally every HeartbeatInterval and keeps it alive (see Session renewal): when about a fifth of the session is left it refreshes it with one check-in, and when it has lapsed it renews it with POST /auth/renew. With DisableAutoRenew: true the SDK makes no request after Login and the session ends with ErrSessionExpired when its TTL runs out. The session TTL is 24h by default; the server clamps requested values to [1h, 7d] (set it with SessionTTL).
  3. Online check-ins (optional). Set OnlineHeartbeat: true to call POST /auth/heartbeat every interval. A revocation, an expiry or a device reset (HWID reset) then takes effect at the next check-in instead of at the end of the session. Check-ins do not detect two copies of the app running under one device ID.

Separately, for machines that can never reach the internet, an operator can mint a signed offline license file (.authforge) in the AuthForge dashboard or Developer API. The SDK verifies it locally with your app public key: see Offline license files.

For apps sold as a one-time purchase, self-serve offline activation lets the end user turn a license key into a lifetime, HWID-bound .authforge file with one online call from the app (ActivateOffline); after that the app runs from the file with no network: see Self-serve offline activation.

Features

Everything in this list ships in authforge.go, crypto.go, hwid.go, offline.go, and offline_activate.go today:

  • License activation via POST /auth/validate, returning a signed LoginResult.
  • Ed25519 signature verification on every /auth/validate, /auth/heartbeat and /auth/renew response; tampered or unsigned responses are rejected.
  • Key rotation: configure PublicKey (single key or comma-separated string) and/or PublicKeys (rotation set). The SDK trusts a signature that matches any configured key, so you can roll the server-side signing key without breaking deployed clients.
  • Nonce anti-replay: a fresh 128-bit nonce is sent on every HTTP attempt, retries included, and the echoed nonce in the signed payload must be the one of the attempt it answers.
  • Response binding: a signed response (/auth/validate, /auth/heartbeat, /auth/renew) is accepted only when the HWID and license key in its payload, when present, are exactly the ones of this client's request or session (including HWIDOverride). A correctly signed response issued for another device or license is rejected with signature_mismatch.
  • HTTPS only: New refuses an http:// APIBaseURL unless its host is 127.0.0.1, ::1 or localhost (local testing).
  • HWID v2: sha256("authforge-hwid-v2|" + appId + "|" + machineId) from the OS machine id (macOS IOPlatformUUID, Linux /etc/machine-id or /var/lib/dbus/machine-id, Windows MachineGuid from the 64-bit registry view), falling back to the legacy fingerprint (hostname + OS + arch + MAC) only when no OS id is readable, with one warning on stderr naming why. HwidSource() reports which (machine-id, legacy or override). Every AuthForge SDK derives the same HWID for the same app and machine; conformance is pinned by hwid_vectors.json. See HWID source and cloned machines.
  • 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; HwidCount / MaxHwidSlots are surfaced on LoginResult. A shared (unlimited-seat) key skips per-device binding.
  • Grace period by default, online check-ins opt-in, session renewal on by default (see Grace period and online check-ins and Session renewal).
  • 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(licenseKey, path) exchanges a key for a lifetime, HWID-bound .authforge file in one online call, verifies it locally, writes it atomically and starts an offline session.
  • Self-ban (SelfBan(...)) for anti-tamper response, both pre-session and post-session.
  • Grace period duration control via SessionTTL, with server-side clamping to [1h, 7d].
  • App variables / license variables for feature flags and tiered licensing.
  • Automatic retries: a rate limit after 2s and 5s, and a request that got no HTTP response at all once after 2s, each attempt with a fresh nonce.
  • SDK identification: every API request carries the header X-AuthForge-SDK: authforge-go/<version>.
  • Returns errors instead of exiting: unlike the Python/Node/C#/C++ SDKs, the Go SDK never calls os.Exit; Login/ValidateLicense return errors and background failures are reported through OnFailure / OnHeartbeatFailure, classified as transient or fatal.

Installation

The module is github.com/AuthForgeCC/authforge-go/v3 (Go puts the major version in the module path from v2 on). With a released version tag on GitHub, add it like any other public module:

go get github.com/AuthForgeCC/authforge-go/v3@v3.0.0

Pin a v3.x.y tag you have pushed (for example @v3.0.0). 2.x releases stay available at github.com/AuthForgeCC/authforge-go/v3, and 1.x at the old path github.com/AuthForgeCC/authforge-go. Without an @ suffix, go get resolves @latest once the proxy has indexed the tag.

Local module with replace (forks, air-gapped builds, or hacking on the SDK)

  1. Clone this repository somewhere on your machine (for example next to your application).
  2. In your application's go.mod, require the module path and add a replace to your local checkout:
module example.com/myapp

go 1.21

require github.com/AuthForgeCC/authforge-go/v3 v0.0.0

replace github.com/AuthForgeCC/authforge-go/v3 => ../path/to/authforge-go

Adjust ../path/to/authforge-go to the real path, then run go mod tidy.

Copy source into your project

You can vendor authforge.go, hwid.go, crypto.go, and related files into your tree (for example under internal/authforge/) and adjust import paths if you change the module path. Prefer go get when possible.

Quick start

The quick start below assumes go get (or a replace pointing at a local clone) is configured as in Installation. It activates online once, then keeps running on the signed session, which the SDK refreshes or renews near its end:

package main

import (
	"fmt"
	"os"

	"github.com/AuthForgeCC/authforge-go/v3"
)

func main() {
	licenseLost := make(chan *authforge.Error, 1)
	client, err := authforge.New(authforge.Config{
		AppID:     "YOUR_APP_ID",
		AppSecret: "YOUR_APP_SECRET",
		PublicKey: "YOUR_PUBLIC_KEY",
		OnHeartbeatFailure: func(err *authforge.Error) {
			if err.IsTransient() {
				return // network blip: the SDK checks in again next interval
			}
			select {
			case licenseLost <- err: // signal main instead of exiting on this goroutine
			default:
			}
		},
	})
	if err != nil {
		panic(err)
	}

	result, err := client.Login("XXXX-XXXX-XXXX-XXXX")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Login failed: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Authenticated! Expires: %d\n", result.ExpiresIn)
	lost := <-licenseLost // your app's work runs elsewhere until this fires
	fmt.Fprintf(os.Stderr, "License check failed: %s\n", lost.Code)
	// Save the user's work here, then exit.
	os.Exit(1)
}

To enable online check-ins instead, add OnlineHeartbeat: true (and optionally tune HeartbeatInterval).

Config

Field Type Default Description
AppID string required App ID from dashboard
AppSecret string required for online APIs (including ActivateOffline); empty for LoginFromFile only App secret from dashboard. Do not ship it in air-gapped binaries.
PublicKey string required* App Ed25519 public key (base64) from dashboard. Accepts a comma-separated trust list. *Required unless PublicKeys is set.
PublicKeys []string optional Rotation set of trusted Ed25519 public keys. When non-empty, takes precedence over PublicKey; the SDK trusts a signature matching any entry (see Key rotation).
OnlineHeartbeat bool false Enables online check-ins: POST /auth/heartbeat every HeartbeatInterval, so a revocation, an expiry or a device reset takes effect at the next check-in (they do not detect two copies on one device ID). When false, the SDK relies on the grace period.
DisableAutoRenew bool false (renewal on) Turns session renewal off: the default mode then makes no request after Login and the session ends when its TTL runs out, as in 2.0.1, and a check-in answered session_expired ends the session.
HeartbeatMode string "" Deprecated, see Migrating from HeartbeatMode. Empty means the default grace period behavior; "server" maps to OnlineHeartbeat: true; "local" maps to the default.
HeartbeatInterval time.Duration 15 * time.Minute Interval between background checks (online check-ins or local grace period re-verification). Minimum supported interval is 10 * time.Second; pick based on how fast you want revocations to propagate. New prints a warning to stderr when it is at least half the session TTL, since a session could then lapse between two checks.
APIBaseURL string https://auth.authforge.cc API base URL override. New refuses an http:// URL unless its host is 127.0.0.1, ::1 or localhost.
OnFailure func(error string) nil Called when a background check fails (with the error message), unless OnHeartbeatFailure is set
OnHeartbeatFailure func(err *authforge.Error) nil Receives background check failures instead of OnFailure, with err.Code and err.IsTransient() / err.IsFatal(). See Background check failures
RequestTimeout time.Duration 15 * time.Second HTTP timeout per request
SessionTTL time.Duration 0 (server default: 24h) Session lifetime requested on Login and on renewal. Server clamps to [1h, 7d]; out-of-range values are silently clamped. Check-ins refresh the session while preserving the requested TTL.
HWIDOverride string "" Optional custom hardware/subject identifier. When non-empty, the SDK sends this value instead of the generated HWID, and HwidSource() reports override.

Identity-based binding example (Telegram/Discord)

client, err := authforge.New(authforge.Config{
    AppID:           "YOUR_APP_ID",
    AppSecret:       "YOUR_APP_SECRET",
    PublicKey:       "YOUR_PUBLIC_KEY",
    OnlineHeartbeat: true,
    HWIDOverride:    fmt.Sprintf("tg:%d", telegramUserID), // or fmt.Sprintf("discord:%d", discordUserID)
})

Key rotation

To rotate the server-side signing key without a flag-day, configure both the new and previous keys; the SDK accepts a signature matching any entry:

client, err := authforge.New(authforge.Config{
    AppID:      "YOUR_APP_ID",
    AppSecret:  "YOUR_APP_SECRET",
    PublicKeys: []string{"NEW_PUBLIC_KEY", "PREVIOUS_PUBLIC_KEY"},
})

A comma-separated PublicKey ("NEW,PREVIOUS") works too, for env-var convenience.

HWID source and cloned machines

client.HwidSource() says where client.HWID() came from: "machine-id" (the OS machine id, the normal case), "legacy" (no OS machine id was readable, so the pre-2.0 fingerprint is used; New printed AuthForge: could not read the OS machine id (<reason>); using the legacy fingerprint as the HWID to stderr) or "override" (HWIDOverride). The constants authforge.HwidSourceMachineID, HwidSourceLegacy and HwidSourceOverride hold these strings. On Windows the SDK reads MachineGuid through the registry API (64-bit view, also from 32-bit builds); on macOS it asks ioreg once more, waiting up to 5 seconds, before falling back.

Machines cloned from one disk image (VM templates, golden images, containers built with a baked-in /etc/machine-id) share its machine id, and therefore one HWID: AuthForge sees them as one device. Give each clone its own machine id (on Linux clear /etc/machine-id and run systemd-machine-id-setup on first boot; on Windows generalize the image with Sysprep, which resets MachineGuid), or pass a per-instance HWIDOverride.

Grace period and online check-ins

Grace period (the default). After one successful online activation, the app keeps running on the signed session. The SDK re-verifies the stored signed payload locally on every HeartbeatInterval tick. With renewal on (the default), once at most a fifth of the session is left (or two intervals, whichever is longer) it refreshes the session with one POST /auth/heartbeat, and when the session has lapsed (for example the machine slept past its end) it renews it with POST /auth/renew; see Session renewal. A refresh that fails for a transient reason is not reported and the next tick tries again; a definitive answer ends the session. With DisableAutoRenew: true the SDK makes no request after Login and fails with ErrSessionExpired once the session's lifetime is over. The session TTL is 24h by default, server-clamped to [1h, 7d] (set with SessionTTL). This is session continuation, not persistent offline licensing: a mid-session revocation takes effect at the next refresh or renewal (without renewal, at the next online activation).

Online check-ins (OnlineHeartbeat: true). The SDK sends POST /auth/heartbeat on every interval. A revocation, an expiry or a device reset (HWID reset) takes effect at the very next check-in, and each successful check-in refreshes the session. Check-ins do not detect two copies of the app running under one device ID. A definitive rejection (revoked, hwid_mismatch, blocked, ...) clears the stored session immediately; every other failure (network, rate_limited, system_error, no_credits, unknown codes, ...) is transient and keeps it until its lifetime runs out. With renewal on, a check-in answered session_expired renews the session, and so does a transient failure once the lifetime is over. See Background check failures.

Session renewal

Renewal is on by default (DisableAutoRenew turns it off). POST /auth/renew sends what Login sends (app id and secret, license key, HWID, a fresh nonce, ttlSeconds when SessionTTL is set; not the old session token, which may have expired) and its response is checked as a Login response is. Success replaces the session token, its lifetime and both variable maps (a renewal without variables leaves none) and calls no callback. Renewal never takes a free seat: a device whose seat was reset or given to another device gets hwid_mismatch and loses its session. A definitive answer (revoked, expired, hwid_mismatch, ...) ends the session and is reported. A transient one keeps the session while its lifetime lasts (reported for online check-ins, silent in the default mode, and the next tick tries again) and ends it with session_expired after. A server without the route answers 404, which is transient.

Price. A renewal costs 1 credit, like a Login. The default mode's refresh is a check-in, priced as one (10 check-ins = 1 credit). On the default 24h TTL and interval, an app that runs for days makes about one refresh check-in per day, and renews only when a session lapsed (for example after a sleep past its end) or the server answered the refresh with session_expired.

Clocks. A session lasts the lifetime the server signed (from its signed timestamp to expiresIn, or to licenseExpiresAt when the license ends first), counted from when the response arrived on whichever of two clocks moved further: the wall clock, which keeps counting while the machine sleeps, and the monotonic clock, which setting the system clock back cannot move. Setting the clock back does not stretch a session, a sleep counts, and a local clock that is wrong by a constant amount changes nothing. A response with no time left fails Login with session_expired. IsAuthenticated() is judged when called: it turns false once the lifetime is over (or an offline file's expiresAt has passed) without ending the session or calling a callback; the next background check renews a lapsed session or reports session_expired.

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 online check-ins. Leave AppSecret empty so the air-gapped binary does not contain the App Secret.

Grace period (default) Offline license file
Needs network Once, at Login 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 Operator-chosen expiry or lifetime (perpetual licenses only)
Revocation Picked up at the next check-in, refresh or renewal Not reachable: the file stays valid until its own expiry
Cost 1 credit per Login or renewal; a refresh is a check-in (1/10 credit) 1 credit per mint; verifying is free
client, err := authforge.New(authforge.Config{
	AppID:     "YOUR_APP_ID",
	PublicKey: "YOUR_PUBLIC_KEY",
	OnFailure: func(msg string) { log.Println("authforge:", msg) },
})
if err != nil {
	log.Fatal(err)
}

// 1. Write an activation request the operator drops into the mint dialog:
request := client.CreateActivationRequest(authforge.ActivationRequestOptions{})

// 2. Later, authorize from the minted file (path or armored text). No network.
lic, err := client.LoginFromFile("license.authforge")
if err != nil {
	switch {
	case errors.Is(err, authforge.ErrOfflineExpired):
		log.Fatal("offline license expired - ask the operator for a new file")
	case errors.Is(err, authforge.ErrOfflineHwidMismatch):
		log.Fatal("this file is bound to a different machine")
	default:
		log.Fatal(err)
	}
}
fmt.Println("Offline license OK; expires:", lic.ExpiresAt) // nil pointer = lifetime
fmt.Println(client.LicenseVariables())

HWIDs are identical across AuthForge SDKs for the same app id and machine (HWID v2), so an HWID collected with any SDK can bind a file loaded by this one. After LoginFromFile, GetSessionKind() returns SessionKindOffline (SessionKindOnline after Login, SessionKindNone when logged out).

authforge.VerifyLicenseFile(text, opts) (package function) and client.VerifyLicenseFile(pathOrText) perform the same checks without touching client state. Errors are sentinels for errors.Is, in check order: ErrOfflineBadArmor, ErrOfflineBadSignature, ErrOfflineUnsupportedVersion, ErrOfflineMalformedPayload, ErrOfflineWrongApp, ErrOfflineExpired, ErrOfflineHwidMismatch; authforge.OfflineErrorCode(err) maps them to the cross-SDK codes. LoginFromFile also reports offline_login_failed: <code> through OnFailure.

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. HWID derivation is covered by the shared hwid_vectors.json.

Self-serve offline activation

For apps sold as a one-time purchase that should run offline after a single online step. The end user enters their license key once. ActivateOffline(licenseKey, path) calls POST /auth/offline/activate with the same HWID and nonce handling as Login; the server checks the key, binds a seat and returns a lifetime .authforge file bound to this machine. The SDK verifies the file with your public key(s), app id and the local HWID before writing anything, writes it to path atomically (temp file + rename, parent directories created), and starts an offline session exactly as LoginFromFile does (SessionKindOffline, variables and OfflineLicense() populated, no background checks). Every later launch runs from the file with no network and no credits.

This is a separate mode from air-gapped offline files:

  • It needs the App Secret, because activation is an online call. Air-gapped builds that only call LoginFromFile still ship without it.
  • The app owner must turn on self-serve activation for the app (dashboard app settings, or offlineSelfServe on PUT /v1/apps/{appId}). The license must be perpetual (no expiry) and seat-limited (not a shared key).
  • Billing: each new machine costs the app owner 2 credits, once. The same machine re-activating (reinstall, deleted file) gets the identical file back for free. A refused activation costs nothing.
  • A license can produce files for at most maxHwidSlots distinct machines, ever. HWID resets do not free these machine slots; only the vendor can release one.
  • A refund, chargeback or revoke disables the license online but cannot reach files already issued. A lifetime file keeps working.
const licensePath = "license.authforge" // for example under os.UserConfigDir()

client, err := authforge.New(authforge.Config{
	AppID:     "YOUR_APP_ID",
	AppSecret: "YOUR_APP_SECRET", // required for ActivateOffline
	PublicKey: "YOUR_PUBLIC_KEY",
})
if err != nil {
	log.Fatal(err)
}

// Every launch: run from the file when it is there and valid for this machine.
if _, err := client.LoginFromFile(licensePath); err != nil {
	// No file yet, or it fails (for example ErrOfflineHwidMismatch after a hardware change).
	key := promptForLicenseKey() // your UI
	if err := client.ActivateOffline(key, licensePath); err != nil {
		switch {
		case errors.Is(err, authforge.ErrOfflineActivationLimitReached):
			showError("This license is already activated on all the machines it allows. Please contact the vendor.")
		case errors.Is(err, authforge.ErrHwidMismatch):
			showError("This license has no free seat for this machine.")
		case errors.Is(err, authforge.ErrInvalidKey), errors.Is(err, authforge.ErrRevoked), errors.Is(err, authforge.ErrExpired):
			showError("That license key is not valid.")
		case authforge.IsTransient(err):
			showError("Activation is unavailable right now (" + authforge.ErrorCode(err) + "). Please try again later.")
		default:
			showError("Activation failed (" + authforge.ErrorCode(err) + ").")
		}
		return
	}
}
// Authenticated offline: client.GetSessionKind() == authforge.SessionKindOffline
fmt.Println(client.LicenseVariables())

Errors are *authforge.Error values. The activation-specific codes are all fatal (IsFatal()):

Code Sentinel (errors.Is) Meaning
offline_activation_disabled ErrOfflineActivationDisabled The app owner has not enabled self-serve activation
offline_activation_requires_perpetual ErrOfflineActivationRequiresPerpetual The license has an expiry; only perpetual licenses can self-serve
offline_activation_requires_seats ErrOfflineActivationRequiresSeats Shared (unlimited-seat) keys cannot self-serve
offline_activation_limit_reached ErrOfflineActivationLimitReached Every machine slot on the license is used; tell the user to contact the vendor
hwid_mismatch ErrHwidMismatch No free seat for this machine
offline_file_rejected ErrOfflineFileRejected The returned file failed local verification; the verifier's reason (bad_signature, wrong_app, hwid_mismatch, ...) is in the message and in authforge.OfflineErrorCode(err). Check PublicKey / AppID

Every other code (invalid_key, revoked, no_credits, rate_limited, system_error, ...) keeps its usual meaning and classification. A success response without a file is unexpected_response (transient); a local write failure is file_write_failed (transient; retrying is free because the same machine gets the same file back). rate_limited and network failures are retried as for Login.

On any failure nothing is written, an existing file at path is left untouched, the client is not authenticated, OnFailure is not called and the process is never exited. Pass path as "" to authenticate without saving the file. LoginFromFile echoes its failures to OnFailure as offline_login_failed: <code>, so if your OnFailure ends the app, leave it unset in this mode (offline sessions have no background checks).

Migrating from HeartbeatMode

Config.HeartbeatMode is deprecated but still works:

  • HeartbeatMode: "local" maps to the default grace period behavior. Remove the field.
  • HeartbeatMode: "server" maps to online check-ins. Replace it with OnlineHeartbeat: true.
  • An empty HeartbeatMode is now valid and means the default grace period behavior.
  • Any other value still returns an error from New.
  • If both fields are set, either one enables online check-ins: HeartbeatMode: "server" is not overridden by OnlineHeartbeat: false.
// Before:
authforge.Config{ /* ... */ HeartbeatMode: "server"}
// After:
authforge.Config{ /* ... */ OnlineHeartbeat: true}

// Before:
authforge.Config{ /* ... */ HeartbeatMode: "local"}
// After (grace period is the default):
authforge.Config{ /* ... */ }

Billing

  • 1 Login or ValidateLicense call = 1 credit (one /auth/validate debit each).
  • 10 online check-ins on the same license = 1 credit (debited every 10th successful check-in). The default mode's refresh near the end of a session is a check-in.
  • 1 renewal (POST /auth/renew) = 1 credit, only when a session lapsed or the server answered a check-in with session_expired. With DisableAutoRenew, the default mode costs nothing after activation.
  • 1 new offline activation (ActivateOffline) = 2 credits, charged to the app owner once per machine. Re-activating the same machine is free, and so are LoginFromFile / VerifyLicenseFile.

This means a session-style app running for 6 hours at a 15-minute check-in interval burns ~1 validation + ~24 check-ins = ~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 (they always land on the next check-in).

Methods

Method Returns Description
Login(licenseKey string) (*LoginResult, error) Activates the key online and stores the signed session (sessionToken, expiresIn, appVariables, licenseVariables)
ValidateLicense(licenseKey string) (*LoginResult, error) Same /auth/validate + signatures as Login; does not persist session or start background checks; does not invoke OnFailure for validate or network errors
SelfBan(...) (map[string]interface{}, error) Requests /auth/selfban to blacklist HWID/IP and optionally revoke (session-authenticated only). Pass false for blacklistIP unless you mean to block everyone behind that IP
LoginFromFile(pathOrText string) (*OfflineLicense, error) Authorizes from an offline .authforge file with no network; never starts background checks; errors are ErrOffline* sentinels and are echoed to OnFailure as offline_login_failed: <code>
VerifyLicenseFile(pathOrText string) (*OfflineLicense, error) Verifies a .authforge file with this client's app id / keys / HWID without changing state
ActivateOffline(licenseKey, path string) error Self-serve offline activation: one online call returns a lifetime HWID-bound .authforge file, verified locally, written atomically to path (skipped when ""), then an offline session as with LoginFromFile. Requires AppSecret
OfflineLicense() *OfflineLicense The offline file in use (JTI, ExpiresAt, HwidPolicy, …) or nil
GetSessionKind() SessionKind SessionKindOnline, SessionKindOffline, or SessionKindNone when logged out
HWID() string The HWID this client sends (or HWIDOverride); customers share it to receive a bound file
HwidSource() string Where the HWID came from: "machine-id", "legacy" or "override" (see HWID source and cloned machines)
CreateActivationRequest(opts ActivationRequestOptions) 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 an online session's signed lifetime lasts, or an offline file has not expired. Judged when called; never ends the session or calls a callback
GetSessionData() / SessionData() map[string]interface{} Full decoded payload map
GetAppVariables() / AppVariables() map[string]interface{} App-scoped variables map
GetLicenseVariables() / LicenseVariables() map[string]interface{} License-scoped variables map

Error handling

The SDK returns errors instead of panicking. Common failure cases are exposed as sentinel errors:

if err != nil {
	switch {
	case errors.Is(err, authforge.ErrInvalidApp):
		// app credentials are invalid
	case errors.Is(err, authforge.ErrInvalidKey):
		// license key is invalid
	case errors.Is(err, authforge.ErrExpired):
		// license expired
	case errors.Is(err, authforge.ErrRevoked):
		// license revoked
	case errors.Is(err, authforge.ErrHwidMismatch):
		// HWID slots full (Login) or HWID no longer bound (check-in)
	case errors.Is(err, authforge.ErrNoCredits):
		// account has no credits
	case errors.Is(err, authforge.ErrAppBurnCapReached):
		// app credit burn cap reached
	case errors.Is(err, authforge.ErrBlocked):
		// blocked by security rules
	case errors.Is(err, authforge.ErrRateLimited):
		// request was rate limited
	case errors.Is(err, authforge.ErrReplayDetected):
		// nonce replay detected
	case errors.Is(err, authforge.ErrAppDisabled):
		// app disabled
	case errors.Is(err, authforge.ErrSessionExpired):
		// session expired (grace period ended)
	case errors.Is(err, authforge.ErrRevokeRequiresSession):
		// attempted pre-session revoke
	case errors.Is(err, authforge.ErrBadRequest):
		// bad_request or malformed_request
	case errors.Is(err, authforge.ErrServerError):
		// system_error or server_error
	case errors.Is(err, authforge.ErrSignatureMismatch):
		// response signature invalid, or signed for a different device or license
	default:
		// transport or unknown error
	}
}

ValidateLicense returns the same error types as Login but does not call OnFailure for failed validate or network errors (background checks still use OnFailure on failure).

Server and transport failures are *authforge.Error values: authforge.ErrorCode(err) returns the machine-readable code (invalid_key, hwid_mismatch, network_error, http_error_502, ...) and authforge.IsTransient(err) its classification. errors.Is against the sentinels above keeps working. Server codes this SDK version doesn't know yet are passed through unchanged.

Internal request retries are automatic:

  • rate_limited, or HTTP 429 without an error code: retry after 2s, then 5s (max 3 attempts total). no_credits, app_burn_cap_reached and demo_quota_exceeded share HTTP 429 but are not retried; a background check reports them as transient and tries again at the next interval.
  • no HTTP response at all (connection refused or reset, closed before answering, timeout): sent once more after 2s. Any HTTP response is the answer and is not sent again, apart from the rate limit above.
  • every attempt carries a fresh nonce, and the response is checked against the nonce of the attempt it answers

Background check failures

Each failed background check produces an *authforge.Error:

  • Code: the server's error code (revoked, expired, hwid_mismatch, blocked, session_expired, rate_limited, no_credits, system_error, malformed_request, ...), or an SDK code: network_error, timeout, http_error_<status> (non-JSON error body), invalid_json_response, unexpected_response, signature_mismatch, nonce_mismatch, ...
  • IsTransient() / IsFatal(): the classification.

A failed check-in counts as an AuthForge verdict only when the body is a JSON object with "status": "failed" and a non-empty string error. Any other failure body (for example {"error":"revoked"} without a status, or {"status":"failed"} without an error) is reported as unexpected_response, and the message keeps the raw status / error values.

Kind Codes What the SDK does
Fatal revoked, expired, hwid_mismatch (the HWID is no longer bound to the license, for example after an HWID reset), blocked (HWID/IP blacklisted or not whitelisted), session_expired (the session's lifetime is over and it could not be renewed; with renewal on, a check-in answered session_expired renews instead), malformed_request, app_disabled, invalid_app, signature_mismatch (including a response signed for another device or license) Clears the stored session (as Logout() does) and stops background checks before the callback runs, so the grace period cannot keep the app running on it and IsAuthenticated() is false. The callback may call Login again.
Transient Everything else: network_error, timeout, rate_limited, system_error, server_error, no_credits, demo_quota_exceeded, app_burn_cap_reached, bad_request, invalid_key, every http_error_<status>, invalid_json_response, unexpected_response, and codes this SDK version doesn't know yet Keeps the session and checks in again on the next HeartbeatInterval. Once the session's lifetime is over, a transient failure renews the session (with renewal on); when that fails too, or with renewal off, it is reported as a fatal session_expired instead.

The error reaches OnHeartbeatFailure when it is set, otherwise OnFailure as err.Error() (the same message as earlier releases, for example authforge: license revoked: revoked). A heartbeat network failure is reported once, not as a separate network_error string first. Without a callback, a transient failure prints AuthForge: background check failed (<code>); retrying next interval to stderr and checks in again next interval; a fatal one clears the session and stops background checks without output (the SDK never exits the process, so check IsAuthenticated() or set a callback).

Callbacks run on the background check goroutine with no SDK lock held, so calling Logout(), IsAuthenticated() or any other client method from them is safe; Logout() there stops further checks. A check-in or renewal still in flight when Logout() or Login runs never writes its result back to the client.

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

licenseLost := make(chan *authforge.Error, 1)

client, err := authforge.New(authforge.Config{
	AppID:           "YOUR_APP_ID",
	AppSecret:       "YOUR_APP_SECRET",
	PublicKey:       "YOUR_PUBLIC_KEY",
	OnlineHeartbeat: true,
	SessionTTL:      time.Hour, // retry window for transient check-in failures
	OnHeartbeatFailure: func(err *authforge.Error) {
		if err.IsTransient() {
			// Connectivity problem or AuthForge overloaded: keep running. The SDK
			// retries every HeartbeatInterval; once the session's lifetime is over
			// it tries to renew it, and reports session_expired (fatal) only when
			// that fails too.
			log.Printf("AuthForge check-in failed (%s), retrying", err.Code)
			return
		}
		log.Printf("License check failed: %s", err.Code) // session already cleared
		select {
		case licenseLost <- err: // runs on the background goroutine: signal, don't exit here
		default:
		}
	},
})

// ... Login, then run your app's work on other goroutines ...

select {
case <-licenseLost:
	saveUserWork()
	client.Logout()
	os.Exit(1)
case <-appDone:
}

You can also pass a context.Context built with context.WithCancelCause and cancel it from the callback. Calling os.Exit(1) inside the callback is a last resort: deferred functions do not run, so save the user's work first.

Self-ban (tamper response)

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

// Post-session (authenticated): revoke the license and block this device.
_, err = client.SelfBan("", "", true, true, false)

// Pre-session: pass the license key; the SDK always sends revokeLicense=false here.
_, err = client.SelfBan("AF-XXXX-XXXX-XXXX", "", false, true, false)

// Arguments: licenseKey, sessionToken, revokeLicense, blacklistHwid, blacklistIP.

Pass false for blacklistIP unless you mean it: an IP address is often shared (an office, a school, a mobile carrier's NAT), and blocking it locks out everyone behind it. The SDK always sends the value you pass; the server, too, blocks the IP only when a request asks for it.

SelfBan(...) selects mode automatically:

  • Uses post-session mode when a session token is available (sessionToken argument 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 returns ErrOfflineSession without contacting the server.

License

MIT

About

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

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages