Go

The reference for the github.com/keygrantdev/keygrant-go module 1.0.0, the KeyGrant SDK for Go: command-line tools, desktop apps and self-hosted servers. The rules every SDK shares are in How every SDK behaves.

  • Go 1.26 or later.
  • Runs on Windows, macOS and Linux, with no cgo.
  • Depends on the standard library, which verifies leases (crypto/ed25519) and makes the requests, and golang.org/x/sys.
  • Proxy: the default client copies net/http's default transport, so it uses the proxy that one does: HTTPS_PROXY or HTTP_PROXY, by the request's scheme, except for the hosts in NO_PROXY.

Release notes

Add it

Terminal
go get github.com/keygrantdev/keygrant-go

Import it as keygrant. Copy the product's key set from the dashboard (Copy key set) into a file beside your code and embed it, so the build verifies leases with no network:

Go
//go:embed keygrant-keys.jsonvar publicKeys string

Use it

Go
lic, err := keygrant.New("my-product", "https://api.keygrant.dev", publicKeys, keygrant.WithMajor(2))if err != nil {    log.Fatal(err) // a *keygrant.ConfigError: the configuration, never the network}defer lic.Close(context.Background())
switch st := lic.Status(ctx); st.State {case keygrant.Licensed, keygrant.Trial: // runcase keygrant.Unknown: // the stored license could not be read just now: keep running, ask again shortlydefault: if err := lic.Activate(ctx, key); err != nil { showError(err) // errors.Is(err, keygrant.ErrLimit), ... }}
  • Every call that may wait takes a context.Context. It can only cut a call shorter: the SDK bounds every request itself, whatever the context says.
  • License is safe for use by many goroutines; create one per process. Calls on it run one at a time, except Has, Require, UpgradeURL, PickUp and ConfirmPickUp, which only read and run beside any call, and Close.
  • One at a time means a call waits for the one before it to finish, but not past that call's grace: the request timeout and 15 seconds more, from when it started (30 seconds by default). Behind a call still stuck after that (an adapter or a network that never answers), Deactivate, ImportLicenseFile and RemoveLicenseFile answer ErrBusy, Activate and RestoreByEmail answer ErrNetwork with ErrBusy as its cause, Status, Refresh and StartTrial answer from storage with Stalled true, and Use still spends but saves nothing: it keeps a spend made offline, or one that got no answer, in memory for the next call that can save it, and the figures of a spend KeyGrant answered are not kept at all.
  • A Use that spends makes its request and saves the license before it returns (except behind a stuck call, as above), so a server spending uses for many requests at once spends them one after another. Keep a Status answer rather than asking for one per request.

New and its options

New(product, apiBaseURL, publicKeys, opts...)

The three required settings, then the options below. publicKeys is the product's key set as a string: the {"keys": [...]} that /pubkey answers and the dashboard's Copy key set copies.

  • A JSON list of JWKs, one JWK, or its bare x also work.
  • A lease is verified by the key it names, or, naming none, by each key in turn.
  • It returns a *ConfigError for a product that is not a product ID (letters, digits, -, ., _ and ~, at most 64, and not . or ..); a base URL that is not an absolute http or https URL, or carries credentials, a query or a fragment, or ends in //; a key set it cannot use; an HTTP timeout that is not positive; a revoked license file id that is not UTF-8; a relative storage path, or no folder for the license on this machine when neither WithStoragePath nor WithStorage is given; or an adapter that is a nil of its type, such as a nil *http.Client.
WithMajor(int)

This build's major version. 0 is read as 1, as KeyGrant reads a 0.x version, so a 0.x build can set 0 or 1.

Default 1

WithDeviceName(name)

What the license's device list calls this machine, cut to 120 UTF-16 units.

WithDeviceHold(bool)

false turns device hold off, so no license is held to its device. See Device management.

Default true

WithHTTPTimeout(time.Duration)

How long one request may take. It must be positive.

Default 15 seconds (DefaultHTTPTimeout)

WithRevokedLicenseFiles(ids...)

The ids of the license files this build refuses, matched exactly: how an app update stops an offline license file that leaked. See License files.

  • A stored file listed here reads as Invalid with reason ReasonRevokedFile, and importing one is refused.

Default none

WithStoragePath(path)

Keeps the default storage's file at path, which must be absolute, instead of the folder every SDK shares (Storage).

WithStorage(Storage)

Your own storage in place of the default (Storage).

WithStash(Stash)

The trial stash (Keeping a trial through a reinstall). nil is none.

Default the registry on Windows, none elsewhere

WithFingerprinter(Fingerprinter)

Who this device is, in place of the default (How a device is identified).

WithHTTPClient(HTTPDoer)

The HTTP client, such as an *http.Client of your own. The SDK bounds every request itself, whatever the client's own timeout.

WithClock(func() time.Time)

The device clock.

Default time.Now

WithLogger(*slog.Logger)

Logs what the SDK works around without failing a call (Logging).

Default no log

Calls

Activate(ctx, key, opts...)

Returns nil once this device holds a verified lease, or an error (Errors). opts are WithEmail and WithCode, for a key only its buyer can activate (below).

Status(ctx)

Returns a Status (below), offline first. It never fails: a license that cannot be read is Unknown with reason ReasonStorage. Refresh(ctx) is the same call forced online, and StartTrial(ctx) begins this device's trial; both return a Status too.

Deactivate(ctx)

Returns (released bool, err error). released is true only when KeyGrant confirmed the seat is free, or the device held no seat of its own.

Has(ctx, code)

Returns whether the license grants the entitlement code, offline from the stored lease. See Check an entitlement.

  • keygrant.Grants(st.Entitlements, code) answers the same of a status already in hand.
Require(ctx, code)

Returns a *MissingEntitlementError, whose Entitlement is the code, when the license does not grant it.

ImportLicenseFile(ctx, content, opts...)

Returns (ImportedLicenseFile, error) (below). content is a []byte.

RemoveLicenseFile(ctx)

Returns an error.

Use(ctx, meter, n)

Returns (UseResult, error): a nil error is a spend (Metered uses).

PickUp(ctx, email)

Asks KeyGrant to email a six-digit code to the address, for key pickup; a code goes only to an address that holds a live key of the product, and the answer is the same either way. Returns an error.

ConfirmPickUp(ctx, email, code)

Returns the address's keys, ([]PickedKey, error). They are kept in memory for 10 minutes, so the same address and code answer again without a new code (What is kept).

RestoreByEmail(ctx, email, code)

Confirms the code and activates the key that fits this build. Returns an error.

UpgradeURL(ctx, link)

Returns (link string, ok bool, err error): ok is false when no key and activation are stored, without reading the link. See Sell an upgrade.

Close(ctx)

Waits for the work the License left running in the background, a trial's launch report, until ctx ends, and starts no more of it: after Close, no launch report is made. Returns ctx.Err() when ctx ends first, else nil (Short-lived programs).

Errors

Match an error with errors.Is against its sentinel, and take it with errors.As for its code and its cause. The words are the activation errors, the pickup errors and those of the sections below.

Go
err := lic.Activate(ctx, key)var kgErr *keygrant.Errorswitch {case err == nil:    // activatedcase errors.Is(err, keygrant.ErrLimit):    // every seat of the key is takencase errors.Is(err, keygrant.ErrNetwork):    // no usable answer: try again. The cause is for your log.    if errors.As(err, &kgErr) && kgErr.Err != nil {        log.Printf("activation got no answer: %v", kgErr.Err)    }case errors.Is(err, keygrant.ErrStorage):    // the license could not be read or saved; errors.Is(err, fs.ErrPermission) works toocase errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):    // your own context ended first}
*keygrant.Error

Every error a License call returns, but for your context's own and Require's. Its Code is the word every KeyGrant SDK shares, such as limit, and a sentinel for each code makes errors.Is work: ErrInvalidKey, ErrLimit, ErrRevoked, ErrUpgrade, ErrOutdated, ErrInvalidLease, ErrNetwork and the rest.

  • Err, the cause, which Unwrap returns: behind ErrNetwork the HTTP client's error (DNS, TLS, a proxy), a net.Error whose Timeout() is true when no answer came within the request timeout, the HTTP status of an answer the SDK does not take, or, for an activation that could not identify this device in time, an error that says so (nothing was sent); behind ErrStorage the storage's own error, so errors.Is(err, fs.ErrPermission) works too.
  • RetryAfter, a time.Duration, on a pickup's ErrTooManyAttempts and ErrTryAgain when KeyGrant said how long to wait.
ErrStorage

Its word is storage. The stored license could not be read or saved. Try again shortly.

ErrBusy

Its word is busy. From Deactivate, ImportLicenseFile and RemoveLicenseFile, while an earlier call on this License has run past its grace and has still not finished (Use it). Activate and RestoreByEmail answer ErrNetwork there, as every SDK does, with ErrBusy as its cause, so the error matches both. Try again.

ErrInvalidURL

Its word is invalid-url. From UpgradeURL, when an activation is stored: the link is not an absolute URL.

Your context's error

When ctx ends before the call is answered, the call returns ctx.Err() itself, never wrapped, and saves nothing; but a Use whose request was already sent (Metered uses). Status, Refresh and StartTrial never fail: a context that ends while the call waits its turn gets the answer from storage, with Stalled true.

*MissingEntitlementError

From Require.

*ConfigError

From New, with its Reason.

Status

State, Reason

The states and reasons, as constants: Licensed, Trial, Expired, Invalid, Unlicensed, Unknown, and ReasonRevoked through ReasonRevokedFile. Reason is "" when there is none.

Key

The license key; on a status from a license file, the key the file records, when the file could be read (Licensed, or Invalid for ReasonRevokedFile, ReasonUpgrade or ReasonOutdated).

TrialDaysLeft, TrialEndsAt

On a running trial: the days left, rounded up, and when it ends, a time.Time. Zero on any other status.

Test

true for a test license.

Entitlements

A map[string]Entitlement, nil when the lease grants nothing and on every status but Licensed and Trial. An Entitlement's Kind is EntitlementFlag, EntitlementNumber or EntitlementText, and only the field it names (Flag, Number or Text) is set.

Meters

A map[string]MeterStatus, nil on every status but a Licensed one from a key's lease that names meters (below).

Stalled

true when an earlier call has not finished, so the status was read from storage.

Source, LicensedTo

On a status from a license file (below): SourceFile, and who it is licensed to. "" and nil on every status not from a license file.

Keep the app running on Licensed, Trial and Unknown, and ask for a key only on the others: Unknown means the stored license could not be read just now (States and reasons).

Keys only their buyer can activate

When a key is locked to its buyer (Who can activate), pass what the customer typed to Activate as keygrant.WithEmail(email) and keygrant.WithCode(code), each optional. The steps and rules are in How every SDK behaves.

Go
err := lic.Activate(ctx, key, keygrant.WithEmail(email), keygrant.WithCode(code))switch {case errors.Is(err, keygrant.ErrUserEmailRequired), errors.Is(err, keygrant.ErrUserEmailMismatch):    // ask for the address, then activate again with itcase errors.Is(err, keygrant.ErrUserCodeRequired):    // a code was just mailed to the address: ask for itcase errors.Is(err, keygrant.ErrUserCodeInvalid):    // wrong, expired or used: ask again, or activate WithEmail alone for a new codecase errors.Is(err, keygrant.ErrTooManyCodes), errors.Is(err, keygrant.ErrTooManyAttempts):    // waitcase errors.Is(err, keygrant.ErrTryAgain):    // the code could not be mailed: offer to try again}
  • Activate(ctx, key) with neither answers a locked key ErrUserEmailRequired.
  • ImportLicenseFile(ctx, content, opts...) passes them on to a key file's key.
  • Neither the email nor the code is stored.
ErrUserEmailRequired

Its word is user-email-required. The key is locked to its buyer and this device is new: ask for the email the key was sold to and call Activate again WithEmail.

ErrUserEmailMismatch

Its word is user-email-mismatch. That is not the email the key was sold to (or it is longer than 254 UTF-16 units, and no request is made). KeyGrant never says what the right one is.

ErrUserCodeRequired

Its word is user-code-required. The email was right and KeyGrant has just emailed a code to it: ask for the code and call Activate again WithEmail and WithCode.

ErrUserCodeInvalid

Its word is user-code-invalid. The code is wrong, expired (it lasts 10 minutes) or already used, or is not six digits (no request is made). Ask again, or activate with the email alone for a new code.

ErrTooManyCodes

Its word is too-many-codes. Three codes have been emailed for this key this hour. Use the last one, or wait.

ErrTooManyAttempts

Its word is too-many-attempts. Too many wrong emails or codes for this key this hour. Try again later.

ErrTryAgain

Its word is try-again. The code could not be emailed just now, and nothing was activated. Try again; it is nobody's mistake.

Restoring a license without the key

For a build that may not take a typed key: PickUp(ctx, email) emails the customer a six-digit code, and RestoreByEmail(ctx, email, code) activates the key that fits this build. How a pickup works is in How every SDK behaves.

Go
// 1. Email a code to the address the key was sold to (the answer is the same either way).if err := lic.PickUp(ctx, email); err != nil {    showError(err)}
// 2. The customer types the code: restore.err := lic.RestoreByEmail(ctx, email, code)var kgErr *keygrant.Errorswitch {case err == nil: // licensed: read Statuscase errors.Is(err, keygrant.ErrWrongCode): // ask againcase errors.Is(err, keygrant.ErrCodeExpired): // lic.PickUp(ctx, email) for a new codecase errors.Is(err, keygrant.ErrTooManyAttempts), errors.Is(err, keygrant.ErrTryAgain): if errors.As(err, &kgErr) && kgErr.RetryAfter > 0 { // wait kgErr.RetryAfter }case errors.Is(err, keygrant.ErrNoKey): // no key under that addresscase errors.Is(err, keygrant.ErrUpgrade), errors.Is(err, keygrant.ErrOutdated): // the address has keys, none for this builddefault: showError(err) // an activation error, such as ErrLimit}
  • To let the customer choose, call ConfirmPickUp, show each PickedKey by its ModelName, and activate the one chosen with Activate, WithEmail, and WithCode of its ActivationCode when it has one.
  • The errors are the pickup errors: ErrInvalidEmail, ErrWrongCode, ErrCodeExpired, ErrTooManyAttempts, ErrPickupDisabled, ErrTryAgain, ErrNetwork; and, from RestoreByEmail, ErrNoKey, ErrUpgrade or ErrOutdated (the address has keys, none for this build), and the activation errors, such as ErrLimit. The requests are on the endpoints page.

A PickedKey has:

Key

The key, to activate. Never show it.

Model, ModelName

The license model's type, a KeyModel (ModelPerpetual, ModelSubscription, ModelTrial or ModelTimed), and its name, to show.

State

A KeyState: KeyActive or KeyTrial.

Entitlements, ExpiresAt

What the key grants, and when it ends (the zero time for a key that does not).

Versions

The majors it covers, nil for a key sold without a version and not yet bound.

DeviceLimit, ActiveDevices, Held

Its seats, those taken, and whether this device already holds one.

Sale

The sale of several keys it is one of, when KeyGrant said.

ActivationCode

For a key locked with a code: pass it to Activate WithCode, with the email. "" for any other key.

License files

A customer can be sent a .kglicense file: a key file, which activates its key, or an offline license file, which licenses the app with no network. How each behaves is in How every SDK behaves, and what each costs under Delivered as in License models. These are not the file the SDK stores its own state in (Storage).

Warning

Keep every key that signed a file in the key set you give New. A build without it reads such a file as Invalid with reason ReasonUnknownKey.

  • LicenseFileExtension is .kglicense, for an open dialog's filter or a drop handler's test.
  • LicenseFileMediaType is application/vnd.keygrant.license, and MaxLicenseFileBytes is 16,384, the most a file may be.
  • ImportLicenseFile takes the file's content, never its path: read the file and hand over its bytes.
  • List the ids of leaked files in WithRevokedLicenseFiles (Blocking a leaked file).
Go
f, err := os.Open(path) // from an open dialog filtered to keygrant.LicenseFileExtensionif err != nil {    return}defer f.Close()// Never more than a license file can be: a larger one is refused unread.content, err := io.ReadAll(io.LimitReader(f, keygrant.MaxLicenseFileBytes+1))if err != nil {    return}imported, err := lic.ImportLicenseFile(ctx, content)switch {case err == nil:    fmt.Println("Licensed to", imported.LicensedTo.Name) // imported.Kind: keygrant.KeyFile or keygrant.OfflineFilecase errors.Is(err, keygrant.ErrUnknownKey):    // signed by a key this build does not carry: update the appdefault:    showError(err) // ErrMalformed, ErrBadSignature, ErrWrongProduct, ...; for a key file, what Activate answers}

What ImportLicenseFile answers

It verifies the file offline (Importing a file). It returns an ImportedLicenseFile, whose Kind is KeyFile or OfflineFile and LicensedTo who the file names, or an error: for a key file whose key did not activate, what Activate answers; ErrBusy while an earlier call has not finished; ErrStorage when an offline file cannot be saved; or one of the refusals below, with nothing stored.

ErrMalformed

Its word is malformed. Not a license file's text, or its token or claims are broken, or it is more than MaxLicenseFileBytes.

ErrNotALicenseFile

Its word is not-a-license-file. A token that is not a license file (a lease, say).

ErrBadSignature

Its word is bad-signature. Not signed by the key it names.

ErrUnknownKey

Its word is unknown-key. Signed by a key this build does not carry (the key set given to New): a newer one, after the product rotated its key, which an update of the app carries. A key file's notes print its key, which can be typed meanwhile.

ErrWrongProduct

Its word is wrong-product. Another product's file.

ErrRevokedFile

Its word is revoked-file. The file's id is listed in WithRevokedLicenseFiles.

ErrUpgrade

Its word is upgrade. An offline file that does not cover this build: this build is newer than the file covers.

ErrOutdated

Its word is outdated. An offline file that does not cover this build: this build is older than the file covers.

RemoveLicenseFile(ctx) drops the stored offline file, if there is one, and a key this device holds keeps working. It returns ErrBusy when an earlier call has not finished and ErrStorage when the change cannot be saved.

The status of a stored file

A stored offline file answers every Status with Licensed, Source SourceFile, the Key, LicensedTo and the file's entitlements, and never asks KeyGrant, Refresh included.

  • Show "Licensed to Ada Lovelace" from LicensedTo.Name.
  • A status from a file has no seat to deactivate: offer RemoveLicenseFile instead. Deactivate leaves the file alone.
  • Besides ReasonRevokedFile, a status from a file can be Invalid with reason ReasonUpgrade, ReasonOutdated, ReasonTampered or ReasonUnknownKey. What each means, and which wins when the device also holds a key, is in The status of a stored file.

Metered uses

A license model can count uses of what it sells (Metered uses). The app spends them with Use(ctx, meter, n) before the work they count, and does the work only when the error is nil.

Go
res, err := lic.Use(ctx, "exports", 1) // Use(ctx, "exports", 40) spends forty at once, whole or noneswitch {case err == nil:    runExport() // res.Left: what is left now, net of this device's unsynced spendscase errors.Is(err, keygrant.ErrUsedUp):    offerMoreExports(res.Left) // when res.HasLeftcase errors.Is(err, keygrant.ErrOfflineLimit):    askToConnect()default:    showMeterProblem(err) // ErrNoMeter, ErrNotLicensed, ErrRevoked, ErrDevice, ...}
// Offline, from the lease: keygrant.MeterStatus{Left: 950, Total: 1000, Offline: 100, Unsynced: 0, Resets: false}exports := lic.Status(ctx).Meters["exports"]fmt.Println(exports.Left, "exports left")
  • The outcome is an error value beside the UseResult, as io.Reader returns a count and an error together: Left is set wherever there is a figure, an error included.
  • n is an int64. Outside 1 to MaxMeterUses it is ErrInvalidAmount, and a meter code that is not 1 to 32 UTF-16 units is ErrNoMeter, both without asking.
  • A request waits at most 5 seconds for KeyGrant, less when WithHTTPTimeout is shorter.
  • Your context: ended before the request is sent, Use returns its error and spends nothing. Ended once the request is out, KeyGrant may have taken the spend, so it is answered as any spend with no answer is (With no answer), and reported with the next request.
  • Deactivate sends the unsynced spends with the release.
  • How a spend works online and offline, and why a meter never takes the license away, is in How every SDK behaves.
Left, HasLeft

What the meter has left after the spend, net of this device's unsynced spends. HasLeft is false where there is no figure to say, as for a refusal that names none.

Offline

True when the device spent from its offline allowance, to be reported with its next request.

When Use does not spend

ErrUsedUp

Its word is used-up. The meter has fewer uses left than asked. Left says how many are left, when KeyGrant gave a number (HasLeft), so the app can offer fewer. It is KeyGrant's own word, not a guess.

ErrOfflineLimit

Its word is offline-limit. KeyGrant could not be reached, and the spend is past this device's offline allowance for the meter or past what it last heard is left. Left says what the device may still spend. Ask the customer to connect. When the spend asked KeyGrant and got no answer, the error's cause says why.

ErrNoMeter

Its word is no-meter. The key has no meter with that code, or the code is empty or longer than 32 UTF-16 units.

ErrNotLicensed

Its word is not-licensed. No key's lease licenses this build on this device, so nothing was asked. A device trial and an offline license file have no meters.

ErrRevoked, ErrUpgrade, ErrOutdated, ErrDevice

KeyGrant's verdict on the key, this build or this device, as Status says it. Their words are revoked, upgrade, outdated and device.

ErrStorage

Its word is storage. The stored license could not be read just now. Try again shortly.

ErrInvalidAmount

Its word is invalid-amount. n is not from 1 to MaxMeterUses (1,000,000,000). This is a bug in the app: nothing was asked.

Status.Meters

A map by meter code, on a Licensed status from a key's lease that names meters, and nil on every other status. Each MeterStatus has:

Left

What is left, net of this device's unsynced spends.

Total

The uses the key holds, for good or for this billing period.

Offline

This device's offline allowance.

Unsynced

Uses this device spent that KeyGrant has not heard of yet.

Resets

true for a meter that comes back each billing period.

Buying from the trial

Go
// The Buy button, while the app holds no key.openInBrowser("https://buy.stripe.com/your-payment-link")
// The customer types the key from the delivery email:if err := lic.Activate(ctx, key); err == nil { showThanks()}

The checkout creates the key and delivers it, and the customer types it into the app. See Buying from the trial.

When Status answers Trial, the trial reports its launch to KeyGrant at most once a day, in the background, so the call never waits for it. The app need not call StartTrial on each launch for Analytics to count the trial as come back (Device trials).

Short-lived programs

A command-line tool runs for a moment and exits. Status answers offline from the stored lease, and asks KeyGrant only when something is due, such as a lease near its end. That request waits at most 5 seconds while the lease still licenses this build, and at most the request timeout (15 seconds by default) otherwise. Defer Close, which waits for a trial's launch report still on its way: a program that skips it loses a launch report, never a license. os.Exit skips deferred calls, so exit after the function that deferred it has returned:

Go
func main() {    if err := run(); err != nil {        fmt.Fprintln(os.Stderr, err)        os.Exit(1) // after run has returned, so its deferred Close has run    }}
func run() error { lic, err := keygrant.New("my-tool", "https://api.keygrant.dev", publicKeys) if err != nil { return err } // Waits for a trial's launch report still on its way: about 8 seconds at most. defer lic.Close(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() switch lic.Status(ctx).State { case keygrant.Licensed, keygrant.Trial, keygrant.Unknown: return doWork() default: return errors.New("my-tool is not licensed: run my-tool activate <key>") }}

In containers and CI

A Docker container's host name is, by default, its container ID. A Linux container with no machine ID to read (neither /etc/machine-id nor /var/lib/dbus/machine-id, or one on a file system held in memory, or one written since the machine booted) is identified by that host name, so each new container is a new device and takes a new seat. An image that carries a machine ID file older than the machine's boot (by more than 5 seconds) gives every container made from it the same ID, so they share one seat. Use one of:

  • an offline license file (above), which is bound to no device;
  • WithDeviceHold(false), for pooled machines where any session may be another machine (Device hold);
  • WithFingerprinter, with an identity of your own, such as an ID you keep on a volume (How a device is identified).

Logging

WithLogger takes an *slog.Logger and logs what the SDK works around without failing a call: a license it could not read or save, bytes your own storage returned that are not a license, and a device it could not identify (warn); a request that got no answer (debug: an offline customer makes many); and a panic recovered from your storage, fingerprinter or HTTP client (error, with its stack). It never logs a license key, an email, a code or a fingerprint.

Go
lic, err := keygrant.New("my-product", "https://api.keygrant.dev", publicKeys,    keygrant.WithLogger(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))))

How a device is identified

DefaultFingerprinter() hashes the operating system's machine ID: MachineGuid under HKLM\SOFTWARE\Microsoft\Cryptography on Windows, IOPlatformUUID on macOS, and on Linux /etc/machine-id, else /var/lib/dbus/machine-id. It adds the host name's fingerprint beside it, and uses the host name's alone when the machine has no ID to read (no file, no permission, a failed ioreg, no registry value). A read that times out, or fails in an unexpected way, gives no fingerprint for that call: the device cannot be told, and the ID is read again next time. See Device management.

  • On Linux, an ID on a file system held in memory (tmpfs or ramfs), or one written since the machine booted, counts as no ID.
  • WithFingerprinter takes your own. Its Identify(ctx) answers an Identity: the Fingerprint, its Kind (DeviceMachine or DeviceHostname; only a seat keyed by a machine ID is held to its device), and Alternates. An error, or no answer before ctx ends, means the device cannot be told this time.

Storage

The default storage is the folder every SDK shares, in the same format (Where the license is stored), so it reads a license another SDK stored. DefaultStoragePath(product) says where it is on this machine.

  • A save checks that no other process saved since it read, and renames its file in, under a lock on <product>.json.lock beside it, so processes of one tool do not lose each other's save. A lock held past about a second, or a platform with no file lock, leaves the check alone: a lock never fails a save.
  • WithStoragePath(path) moves the file; the path must be absolute.
  • WithStorage takes your own Storage: Read(readOnly) returns the stored JSON object (nil for none), and Write(data) puts a whole one in place. One that also has Update(merge) (Updater) saves through it. Bytes that are not a JSON object, or none at all, read as no license, as the default storage reads a damaged file.

Adapters of your own

  • New refuses a storage, stash, fingerprinter or HTTP client that is a nil of its type, such as a nil *http.Client.
  • A panic in one is recovered and counted as its failure (no answer, a device that cannot be told, a storage error, no trial evidence), so it never ends the process from one of the SDK's goroutines.
  • A fingerprinter and an HTTP client must honour the context they are given. One that does not is abandoned at the SDK's bound, but its goroutine runs on until it returns.

Keeping a trial through a reinstall

On Windows the default stash, RegistryStash, keeps the trial's start date under HKCU\Software\KeyGrant\<product>, in the format every SDK reads, so reinstalling the app does not start a new trial. Elsewhere there is none. WithStash(nil) turns it off, and WithStash takes your own. RegistryStash builds on every platform, and keeps nothing off Windows.