Documentation
¶
Overview ¶
Package keygrant is KeyGrant licensing for Go apps: command-line tools, desktop apps and self-hosted servers. A licence is a signed lease (an EdDSA JWT) verified offline against the product's public keys, so licensing fails in favour of the paying customer: an outage, no network or a slow answer never takes a licence away while the device holds a lease that is still valid.
//go:embed keygrant-keys.json
var publicKeys string
lic, err := keygrant.New("autowind", "https://api.keygrant.dev", publicKeys, keygrant.WithMajor(2))
if err != nil {
log.Fatal(err) // a configuration error
}
defer lic.Close(context.Background())
switch st := lic.Status(ctx); st.State {
case keygrant.Licensed, keygrant.Trial:
// run
case keygrant.Unknown:
// the state could not be read just now: keep running, ask again shortly
case keygrant.Expired:
// st.Reason says why: offline (the lease ran out with KeyGrant out of
// reach: ask the customer to connect) or trial (the trial has ended)
default:
// unlicensed, or a key that does not license this build: ask for a key
err := lic.Activate(ctx, key)
if errors.Is(err, keygrant.ErrLimit) {
// every seat is taken
}
}
Every error a License call answers is a *Error (but for Require's *MissingEntitlementError), matched with errors.Is against its sentinel, whose Unwrap reaches the cause (the network's or the storage's); a context that ends first is its own error. The License's calls run one at a time (see License). The rules every KeyGrant SDK shares are at https://keygrant.dev/docs/sdks/behavior.
Example ¶
package main
import (
"context"
"fmt"
"log"
keygrant "github.com/keygrantdev/keygrant-go"
)
// publicKeys is the product's key set, as its Signing key tab copies it. An app
// embeds it: //go:embed keygrant-keys.json.
var publicKeys string
func main() {
lic, err := keygrant.New("autowind", "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())
ctx := context.Background()
switch st := lic.Status(ctx); st.State {
case keygrant.Licensed, keygrant.Trial:
// run
case keygrant.Unknown:
// the state could not be read just now: keep running, ask again shortly
case keygrant.Expired:
// st.Reason is ReasonOffline (ask the customer to connect) or ReasonTrial
default:
fmt.Println("enter your licence key")
}
}
Output:
Index ¶
- Constants
- Variables
- func DefaultStoragePath(product string) string
- func Grants(entitlements map[string]Entitlement, code string) bool
- type ActivateOption
- type Code
- type ConfigError
- type DeviceKind
- type Entitlement
- type EntitlementKind
- type Error
- type FileStorage
- type Fingerprinter
- type HTTPDoer
- type Identity
- type ImportedLicenseFile
- type KeyModel
- type KeyState
- type License
- func (l *License) Activate(ctx context.Context, key string, opts ...ActivateOption) error
- func (l *License) Close(ctx context.Context) error
- func (l *License) ConfirmPickUp(ctx context.Context, email, code string) ([]PickedKey, error)
- func (l *License) Deactivate(ctx context.Context) (released bool, err error)
- func (l *License) Has(ctx context.Context, code string) bool
- func (l *License) ImportLicenseFile(ctx context.Context, content []byte, opts ...ActivateOption) (ImportedLicenseFile, error)
- func (l *License) PickUp(ctx context.Context, email string) error
- func (l *License) Refresh(ctx context.Context) Status
- func (l *License) RemoveLicenseFile(ctx context.Context) error
- func (l *License) Require(ctx context.Context, code string) error
- func (l *License) RestoreByEmail(ctx context.Context, email, code string) error
- func (l *License) StartTrial(ctx context.Context) Status
- func (l *License) Status(ctx context.Context) Status
- func (l *License) UpgradeURL(ctx context.Context, paymentLink string) (link string, ok bool, err error)
- func (l *License) Use(ctx context.Context, meter string, n int64) (UseResult, error)
- type LicenseFileKind
- type LicensedTo
- type MeterStatus
- type MissingEntitlementError
- type Option
- func WithClock(now func() time.Time) Option
- func WithDeviceHold(hold bool) Option
- func WithDeviceName(name string) Option
- func WithFingerprinter(f Fingerprinter) Option
- func WithHTTPClient(client HTTPDoer) Option
- func WithHTTPTimeout(d time.Duration) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMajor(major int) Option
- func WithRevokedLicenseFiles(ids ...string) Option
- func WithStash(s Stash) Option
- func WithStorage(s Storage) Option
- func WithStoragePath(path string) Option
- type PickedKey
- type PickedSale
- type PickedVersions
- type Reason
- type RegistryStash
- type Source
- type Stash
- type State
- type Status
- type Storage
- type Updater
- type UseResult
Examples ¶
Constants ¶
const ( // LicenseFileExtension is the extension of both kinds of licence file: one // file association, one filter in an open dialog or a drop handler. LicenseFileExtension = ".kglicense" // LicenseFileMediaType is the media type a licence file is mailed as. LicenseFileMediaType = "application/vnd.keygrant.license" // MaxLicenseFileBytes is the most a licence file's content may hold. MaxLicenseFileBytes = 16384 )
What a licence file is.
const DefaultHTTPTimeout = 15 * time.Second
DefaultHTTPTimeout is how long a request may take before it is abandoned, unless WithHTTPTimeout says otherwise.
const MaxMeterUses = 1_000_000_000
MaxMeterUses is the most uses one Use may spend.
const Version = "1.0.0"
Version is this SDK's version, as its VERSION file and release tag name it.
Variables ¶
var ( ErrInvalidKey = &Error{Code: CodeInvalidKey} ErrLimit = &Error{Code: CodeLimit} ErrRevoked = &Error{Code: CodeRevoked} ErrUpgrade = &Error{Code: CodeUpgrade} ErrOutdated = &Error{Code: CodeOutdated} ErrNetwork = &Error{Code: CodeNetwork} ErrInvalidLease = &Error{Code: CodeInvalidLease} ErrUserEmailRequired = &Error{Code: CodeUserEmailRequired} ErrUserEmailMismatch = &Error{Code: CodeUserEmailMismatch} ErrUserCodeRequired = &Error{Code: CodeUserCodeRequired} ErrUserCodeInvalid = &Error{Code: CodeUserCodeInvalid} ErrTooManyCodes = &Error{Code: CodeTooManyCodes} ErrTooManyAttempts = &Error{Code: CodeTooManyAttempts} ErrTryAgain = &Error{Code: CodeTryAgain} ErrMalformed = &Error{Code: CodeMalformed} ErrNotALicenseFile = &Error{Code: CodeNotALicenseFile} ErrBadSignature = &Error{Code: CodeBadSignature} ErrUnknownKey = &Error{Code: CodeUnknownKey} ErrWrongProduct = &Error{Code: CodeWrongProduct} ErrRevokedFile = &Error{Code: CodeRevokedFile} ErrInvalidEmail = &Error{Code: CodeInvalidEmail} ErrWrongCode = &Error{Code: CodeWrongCode} ErrCodeExpired = &Error{Code: CodeCodeExpired} ErrPickupDisabled = &Error{Code: CodePickupDisabled} ErrNoKey = &Error{Code: CodeNoKey} ErrInvalidAmount = &Error{Code: CodeInvalidAmount} ErrNoMeter = &Error{Code: CodeNoMeter} ErrUsedUp = &Error{Code: CodeUsedUp} ErrOfflineLimit = &Error{Code: CodeOfflineLimit} ErrNotLicensed = &Error{Code: CodeNotLicensed} ErrStorage = &Error{Code: CodeStorage} ErrDevice = &Error{Code: CodeDevice} // ErrBusy is a call that must not run while an earlier call on the same // License has not finished (an adapter stuck on storage, or on a network // that never answers): Deactivate, ImportLicenseFile and RemoveLicenseFile // answer it. Activate and RestoreByEmail answer ErrNetwork there, as every // KeyGrant SDK does, with ErrBusy as its cause, so the error matches both. // Try again. ErrBusy = &Error{Code: CodeBusy} ErrInvalidURL = &Error{Code: CodeInvalidURL} )
The sentinels, one for each Code.
Functions ¶
func DefaultStoragePath ¶
DefaultStoragePath is where the default storage keeps a product's state on this machine: %LOCALAPPDATA%\KeyGrant\<product>.json on Windows, ~/Library/Application Support/KeyGrant/<product>.json on macOS, and $XDG_CONFIG_HOME/keygrant/<product>.json (or ~/.config/keygrant) elsewhere.
Types ¶
type ActivateOption ¶
type ActivateOption func(*activateOptions)
ActivateOption is what a person typed for a user-locked key.
func WithCode ¶
func WithCode(code string) ActivateOption
WithCode is the six-digit code mailed to that address, for a key that mails one. It is never stored.
func WithEmail ¶
func WithEmail(email string) ActivateOption
WithEmail is the address the key was sold to, for a user-locked key. It is never stored.
type Code ¶
type Code string
Code is the word an error names, as the KeyGrant API and every KeyGrant SDK write it.
const ( // CodeInvalidKey is a key that is not one: empty, too long, or unknown to // the product. CodeInvalidKey Code = "invalid-key" // CodeLimit is a key with every device seat taken. CodeLimit Code = "limit" // CodeRevoked is a key revoked, refunded or expired. CodeRevoked Code = "revoked" // CodeUpgrade is a build newer than the key covers: buy an upgrade. CodeUpgrade Code = "upgrade" // CodeOutdated is a build older than the key's lowest version: update the app. CodeOutdated Code = "outdated" // CodeNetwork is no usable answer: no network, a timeout, an outage, or an // answer the SDK does not recognise. Try again. CodeNetwork Code = "network" // CodeInvalidLease is a lease the server answered that does not verify here // (a build whose public keys do not match the product's). CodeInvalidLease Code = "invalid-lease" // CodeUserEmailRequired is a user-locked key asking for the address it was // sold to: Activate again WithEmail. CodeUserEmailRequired Code = "user-email-required" // CodeUserEmailMismatch is not the key's address. CodeUserEmailMismatch Code = "user-email-mismatch" // CodeUserCodeRequired is a code just mailed to the address: Activate again // WithEmail and WithCode. CodeUserCodeRequired Code = "user-code-required" // CodeUserCodeInvalid is a code that is wrong, expired, used, or not six // digits. CodeUserCodeInvalid Code = "user-code-invalid" // CodeTooManyCodes is three codes mailed for the key this hour. CodeTooManyCodes Code = "too-many-codes" // CodeTooManyAttempts is too many wrong addresses or codes this hour. CodeTooManyAttempts Code = "too-many-attempts" // CodeTryAgain is a code that could not be mailed just now: nothing was // activated. CodeTryAgain Code = "try-again" )
The codes Activate answers (sdk-contract.md sections 3 and 11).
const ( // CodeMalformed is content that holds no licence file token. CodeMalformed Code = "malformed" // CodeNotALicenseFile is a token that is not a licence file (a lease, say). CodeNotALicenseFile Code = "not-a-license-file" // CodeBadSignature is a file the key it names did not sign. CodeBadSignature Code = "bad-signature" // CodeUnknownKey is a file signed by a key this build does not carry. CodeUnknownKey Code = "unknown-key" // CodeWrongProduct is another product's file. CodeWrongProduct Code = "wrong-product" // CodeRevokedFile is a file this build refuses (WithRevokedLicenseFiles). CodeRevokedFile Code = "revoked-file" )
The codes ImportLicenseFile answers besides Activate's (sdk-contract.md 10.6), with CodeUpgrade and CodeOutdated for an offline file outside this build's versions.
const ( // CodeInvalidAmount is an n outside 1 to MaxMeterUses: nothing was asked. CodeInvalidAmount Code = "invalid-amount" // CodeNoMeter is a meter the key does not have. CodeNoMeter Code = "no-meter" // CodeUsedUp is fewer uses left than asked (UseResult.Left says how many). CodeUsedUp Code = "used-up" // CodeOfflineLimit is no answer, and the spend past this device's offline // allowance for the meter or past what it knows is left: ask the customer // to connect. CodeOfflineLimit Code = "offline-limit" // CodeNotLicensed is no key's lease that licenses this build here. CodeNotLicensed Code = "not-licensed" // CodeDevice is a key whose seat is another device's. CodeDevice Code = "device" )
The codes Use answers besides the verdicts (CodeRevoked, CodeUpgrade, CodeOutdated, CodeDevice) (sdk-contract.md 12.9).
const ( // CodeInvalidEmail is an address that is blank, too long, or one the // server could not take. CodeInvalidEmail Code = "invalid-email" // CodeWrongCode is a code that is not the address's live code (or not six // digits). Ask again. CodeWrongCode Code = "wrong-code" // CodeCodeExpired is no live code for the address: PickUp again. CodeCodeExpired Code = "code-expired" // CodePickupDisabled is a product whose Key pickup is off. CodePickupDisabled Code = "pickup-disabled" // CodeNoKey is an address with no live key of the product. CodeNoKey Code = "no-key" )
The codes key pickup answers besides Activate's (sdk-contract.md 13.2 and 13.4), with CodeTooManyAttempts, CodeTryAgain and CodeNetwork.
const ( // CodeStorage is a state that could not be read or saved just now (the // Error's Err says why): try again shortly. CodeStorage Code = "storage" // CodeBusy is a call that could not run in turn: an earlier call on the // same License has not finished (ErrBusy). CodeBusy Code = "busy" )
The codes of the stored state and of the calls' order, which most calls may answer.
const CodeInvalidURL Code = "invalid-url"
CodeInvalidURL is a payment link UpgradeURL was given that is not an absolute URL.
type ConfigError ¶
type ConfigError struct {
Reason string
}
ConfigError is a configuration New cannot make a License from.
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
type DeviceKind ¶
type DeviceKind string
DeviceKind is what a device's fingerprint hashes.
const ( DeviceMachine DeviceKind = "machine" DeviceHostname DeviceKind = "hostname" )
The kinds of fingerprint. Only a seat keyed by a DeviceMachine fingerprint is held to its device.
type Entitlement ¶
type Entitlement struct {
Kind EntitlementKind
Flag bool
Number float64
Text string
}
Entitlement is one entitlement a lease grants: a flag, a number (a double, as JSON reads it) or a text. Only the field its Kind names is set.
type EntitlementKind ¶
type EntitlementKind int
EntitlementKind is what an entitlement's value is.
const ( // EntitlementFlag is a JSON boolean. EntitlementFlag EntitlementKind = 1 // EntitlementNumber is a JSON number, read as a double. EntitlementNumber EntitlementKind = 2 // EntitlementText is a JSON string. EntitlementText EntitlementKind = 3 )
The kinds of entitlement.
type Error ¶
type Error struct {
Code Code
// RetryAfter is how long to wait before asking again, when the server said
// (too-many-attempts and try-again on a pickup); zero otherwise.
RetryAfter time.Duration
// Err is the cause, when there is one: behind CodeNetwork the request's
// failure (a DNS, TLS or proxy error, an answer the SDK does not
// recognise, or no answer within the HTTP timeout), behind CodeStorage the
// storage's error (fs.ErrPermission and the like), and behind an Activate
// or RestoreByEmail that could not run in turn, ErrBusy. Unwrap returns it,
// so errors.Is and errors.As reach it too. Nil otherwise.
Err error
}
Error is an answer the SDK gives as an error, named by its Code. Compare with errors.Is against the sentinels (errors.Is(err, keygrant.ErrLimit)), or take it with errors.As for its Code, its RetryAfter and its cause.
type FileStorage ¶
type FileStorage struct {
// contains filtered or unexported fields
}
FileStorage is the default storage: a JSON file written atomically (a temp file beside it, flushed, renamed over it), saved with a revision so two processes never lose each other's save, and read so that only a missing file is no state.
func NewFileStorage ¶
func NewFileStorage(path string) *FileStorage
NewFileStorage is the default storage at path.
func (*FileStorage) Read ¶
func (s *FileStorage) Read(readOnly bool) ([]byte, error)
Read is the stored JSON object, or nil for none.
func (*FileStorage) Update ¶
func (s *FileStorage) Update(merge func(current []byte) ([]byte, error)) error
Update saves merge of the state as stored, merged again onto a state another process saved meanwhile.
func (*FileStorage) Write ¶
func (s *FileStorage) Write(data []byte) error
Write puts a whole state in place.
type Fingerprinter ¶
Fingerprinter says who this device is. The default (DefaultFingerprinter) reads the operating system's machine id, with the host name's fingerprint beside it. An error, or no answer before ctx ends, is "cannot tell this time".
func DefaultFingerprinter ¶
func DefaultFingerprinter() Fingerprinter
DefaultFingerprinter is the default Fingerprinter: the machine id (Windows' MachineGuid, macOS' IOPlatformUUID, Linux's /etc/machine-id), hashed, with the host name's fingerprint as an alternate; the host name's when the machine has no id to read. A wrapper around it should call it to keep its kind and its alternate.
type HTTPDoer ¶
HTTPDoer sends a request: an *http.Client is one. The SDK bounds every request itself, whatever the client's own timeout.
type Identity ¶
type Identity struct {
// Fingerprint is the device's fingerprint; "" when it cannot be told this
// time (it is read again next call, never stood in for).
Fingerprint string
// Kind is what Fingerprint hashes; "" when not known, and then no seat is
// ever held to the device.
Kind DeviceKind
// Alternates are other fingerprints this device answers to (the host name's).
Alternates []string
}
Identity is who this device is, as a Fingerprinter answers.
type ImportedLicenseFile ¶
type ImportedLicenseFile struct {
Kind LicenseFileKind
LicensedTo LicensedTo
}
ImportedLicenseFile is what ImportLicenseFile took.
type KeyModel ¶
type KeyModel string
KeyModel is the type of licence model a picked key was sold under.
type License ¶
type License struct {
// contains filtered or unexported fields
}
License is KeyGrant licensing for one product on this device. It verifies signed leases offline and asks the server only to activate, to renew a lease nearing its end or past it, to tell it of a newer major, or to report a running trial's launch, so an outage never locks out a paying customer while the lease is live.
A License is safe for use by many goroutines. Its calls run one at a time, but for Has, Require and UpgradeURL, which only read. Create one per process, and Close it before the process ends.
func New ¶
New is a License for product, asking apiBaseURL (https://api.keygrant.dev), and verifying leases against publicKeys: the product's key set as its Signing key tab copies it or GET /v1/products/<product>/pubkey answers it ({"keys":[...]}), a JSON list of JWKs, one JWK, or one key's x alone. Embed it at build time (//go:embed). Create one License per process. The error is a *ConfigError: for a product that is not a slug, a base that is not an absolute http(s) URL, a key set that cannot be used, a relative storage path, or an adapter that is a nil of its type.
func (*License) Activate ¶
Activate activates a licence key on this device. A user-locked key asks a NEW device who it is: ErrUserEmailRequired, then (with WithEmail) ErrUserCodeRequired when it mails a code, then (WithEmail and WithCode) the activation. The error is an *Error (errors.Is against ErrLimit and the others; ErrStorage, with the storage's error as its cause, when the state could not be read or the activation saved; ErrNetwork, with ErrBusy as its cause, behind a call that has not finished), or the context's own error when ctx ends first.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"io/fs"
"log"
"time"
keygrant "github.com/keygrantdev/keygrant-go"
)
// publicKeys is the product's key set, as its Signing key tab copies it. An app
// embeds it: //go:embed keygrant-keys.json.
var publicKeys string
func main() {
lic, err := keygrant.New("autowind", "https://api.keygrant.dev", publicKeys)
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err = lic.Activate(ctx, "AUTO-ABCD-EFGH-JKLM-NPQR")
var kgErr *keygrant.Error
switch {
case err == nil:
fmt.Println("activated")
case errors.Is(err, keygrant.ErrLimit):
fmt.Println("every seat of this key is taken: deactivate another device")
case errors.Is(err, keygrant.ErrUserEmailRequired):
fmt.Println("enter the address the key was sold to") // then Activate WithEmail
case errors.Is(err, keygrant.ErrNetwork):
// no usable answer: errors.As gives why, for the log
if errors.As(err, &kgErr) && kgErr.Err != nil {
log.Printf("activation got no answer: %v", kgErr.Err)
}
fmt.Println("KeyGrant could not be reached: try again")
case errors.Is(err, keygrant.ErrStorage):
// the state could not be saved: the storage's own error is reached too
if errors.Is(err, fs.ErrPermission) {
fmt.Println("the licence folder cannot be written")
}
case errors.Is(err, context.DeadlineExceeded):
fmt.Println("timed out")
default:
fmt.Println(err)
}
}
Output:
func (*License) Close ¶
Close waits for the work the License left running in the background (a trial's launch report, at most about 8 seconds) until ctx ends, and starts no more of it: a later launch report is not made. A short-lived program defers it; one that skips it loses a report, never a licence.
func (*License) ConfirmPickUp ¶
ConfirmPickUp confirms the code mailed to the address and answers the address's live keys of the product, each Held when this device holds a seat on it. It writes nothing and runs beside any call; the keys are kept in memory for ten minutes, so the same address and code answer from them. The error is an *Error (ErrInvalidEmail or ErrWrongCode before anything is sent; ErrWrongCode, ErrCodeExpired, ErrPickupDisabled, ErrTooManyAttempts, ErrTryAgain, ErrNetwork), or the context's own when ctx ends first.
func (*License) Deactivate ¶
Deactivate releases this device's seat and drops the local licence, saying whether the seat is now free (released): false when KeyGrant could not be asked or did not confirm it, so the app does not tell the customer a seat is free that the server may still hold. The local licence is dropped either way, unless ctx ended before KeyGrant answered: then nothing changes and the error is the context's. Otherwise the error is ErrBusy (behind a call that has not finished) or ErrStorage when the state could not be read or saved (the key is then kept: try again).
func (*License) Has ¶
Has is whether the licence this device holds grants the entitlement code, offline, from what is stored, with no ask and no write: a licence that does not license this build, and none at all, grant nothing; a running trial grants what its trial lease does. It runs beside any call, and asks nothing, but it reads the state file and verifies the lease, and may read the machine id: on a disk that keeps failing it can take about a second, and the machine id up to two more, which ctx cuts short (a device that cannot be told is not judged by its device, here as everywhere). Call it where that wait is harmless, or keep its answer: it changes only with a call that writes.
func (*License) ImportLicenseFile ¶
func (l *License) ImportLicenseFile(ctx context.Context, content []byte, opts ...ActivateOption) (ImportedLicenseFile, error)
ImportLicenseFile takes a licence file the customer was sent (.kglicense): its content, as a drop handler or an open dialog reads it, never its path. It is verified offline against the build's key set, for this product and, for an offline file, this build's major, and refused when WithRevokedLicenseFiles lists it: ErrMalformed, ErrNotALicenseFile, ErrBadSignature, ErrUnknownKey, ErrWrongProduct, ErrRevokedFile, ErrUpgrade or ErrOutdated, nothing stored. An OFFLINE file is then stored, and licenses the app with no network, ever (Status gives Source SourceFile). A KEY file's key is activated online exactly as Activate(ctx, key, opts...) would, and its errors are Activate's. ErrBusy behind a call that has not finished; ErrStorage when an offline file cannot be saved.
func (*License) PickUp ¶
PickUp asks KeyGrant to mail a code to the address the key was sold to. It says nothing of whether the address holds a key: the server answers every address alike. It writes nothing and runs beside any call. The error is an *Error (ErrInvalidEmail before anything is sent; ErrPickupDisabled, ErrTooManyAttempts or ErrTryAgain with a RetryAfter, ErrNetwork), or the context's own when ctx ends first.
func (*License) Refresh ¶
Refresh is Status forced online, whatever the waits say: call it when the customer says they have paid.
func (*License) RemoveLicenseFile ¶
RemoveLicenseFile drops the stored offline licence file, if there is one; a key this device holds keeps working. ErrBusy behind a call that has not finished; ErrStorage when that cannot be saved.
func (*License) RestoreByEmail ¶
RestoreByEmail confirms the code and activates the key that fits this build (the one this device holds a seat on, else one with a free seat, else the first), with the address and, for a code-locked key, the code the pickup handed back. The address, the code and the keys are never stored. It runs in turn as Activate does. The error is ConfirmPickUp's, then ErrNoKey, ErrUpgrade or ErrOutdated when no key fits, then Activate's.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"log"
keygrant "github.com/keygrantdev/keygrant-go"
)
// publicKeys is the product's key set, as its Signing key tab copies it. An app
// embeds it: //go:embed keygrant-keys.json.
var publicKeys string
func main() {
lic, err := keygrant.New("autowind", "https://api.keygrant.dev", publicKeys)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
if err := lic.PickUp(ctx, "jo@example.com"); err != nil {
log.Fatal(err)
}
// The customer reads the six-digit code from their mail.
if err := lic.RestoreByEmail(ctx, "jo@example.com", "123456"); errors.Is(err, keygrant.ErrWrongCode) {
fmt.Println("that code is not the one we sent")
}
}
Output:
func (*License) StartTrial ¶
StartTrial begins (or re-syncs) this device's trial and answers its status. As Status, it never fails: Unknown when the state cannot be read, and the server's trial when it cannot be saved.
func (*License) Status ¶
Status is the licence's status: offline first, asking the server only when it should (a lease near its end or past it, a newer major on an open lease, a refusal to heal, a trial to heal). It never fails: a state that cannot be read is Unknown/storage; when ctx ends while an earlier call holds the License, the answer is from what is stored (Stalled).
func (*License) UpgradeURL ¶
func (l *License) UpgradeURL(ctx context.Context, paymentLink string) (link string, ok bool, err error)
UpgradeURL is paymentLink with this device's ACTIVATION id as client_reference_id (never the key), so a checkout for an upgrade finds the key the customer holds; ok is false when the device holds no activated licence. The error is ErrInvalidURL for a link that is not an absolute URL, ErrStorage when the stored state cannot be read (which may take about a second on a disk that keeps failing), or the context's when ctx has ended. It runs beside any call, and writes nothing.
func (*License) Use ¶
Use spends n (1 to MaxMeterUses) uses of the key's meter, before the work they count; do the work only when the error is nil. Online it is exact: the server takes n only while the meter has room for all of it (ErrUsedUp, with Left, otherwise). With no answer (no network, a timeout, a 5xx or 429) it spends from this device's offline allowance for the meter, never past what the device last heard is left (ErrOfflineLimit), and reports the spend with its next request. It needs a key's lease that licenses this build here (ErrNotLicensed otherwise, asking nothing): a trial and an offline licence file have no meters. ErrOfflineLimit after an ask that got no answer has why as its cause. The error is also ErrInvalidAmount, ErrNoMeter, ErrStorage, or a verdict (ErrRevoked, ErrUpgrade, ErrOutdated, ErrDevice), and the context's own when ctx ends before the request is sent (nothing is spent then). Two calls are two spends.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"log"
keygrant "github.com/keygrantdev/keygrant-go"
)
// publicKeys is the product's key set, as its Signing key tab copies it. An app
// embeds it: //go:embed keygrant-keys.json.
var publicKeys string
func main() {
lic, err := keygrant.New("autowind", "https://api.keygrant.dev", publicKeys)
if err != nil {
log.Fatal(err)
}
res, err := lic.Use(context.Background(), "exports", 1)
switch {
case err == nil:
fmt.Println("export; uses left:", res.Left)
case errors.Is(err, keygrant.ErrUsedUp):
fmt.Println("no exports left:", res.Left)
case errors.Is(err, keygrant.ErrOfflineLimit):
fmt.Println("connect to the internet to export more")
default:
fmt.Println(err)
}
}
Output:
type LicenseFileKind ¶
type LicenseFileKind string
LicenseFileKind is which of the two kinds a licence file is.
const ( // KeyFile carries a licence key, activated online as a typed key is. KeyFile LicenseFileKind = "key" // OfflineFile licenses the app offline for good, bound to no device. OfflineFile LicenseFileKind = "offline" )
The kinds.
type LicensedTo ¶
type LicensedTo struct {
Name, Email string
}
LicensedTo is who a licence file is licensed to: its name, its address, or both ("" for one it does not name).
type MeterStatus ¶
MeterStatus is one meter as this device knows it: what is left (net of the spends it has not reported, never below 0), the uses the key holds, the allowance this device may spend with no answer, the spends not yet reported, and whether the meter comes back each billing period.
type MissingEntitlementError ¶
type MissingEntitlementError struct {
// Entitlement is the code that was asked for.
Entitlement string
}
MissingEntitlementError is what Require answers when the licence does not grant an entitlement.
func (*MissingEntitlementError) Error ¶
func (e *MissingEntitlementError) Error() string
type Option ¶
type Option func(*config)
Option configures a License.
func WithDeviceHold ¶
WithDeviceHold is whether a licence is held to the device it was activated on (default true). False for pooled, non-persistent machines (VDI), where every session may be another machine: no lease is then judged by its device.
func WithDeviceName ¶
WithDeviceName is the device name reported to the server on activation (cut to 120 UTF-16 units).
func WithFingerprinter ¶
func WithFingerprinter(f Fingerprinter) Option
WithFingerprinter replaces the default fingerprinter. It must honour the context it is given: one that does not is abandoned at its bound, but its goroutine runs on until it returns.
func WithHTTPClient ¶
WithHTTPClient replaces the HTTP client (an *http.Client of its own, honouring HTTPS_PROXY and NO_PROXY). It must honour each request's context: one that does not is abandoned at the SDK's bound, but its goroutine runs on until it returns.
func WithHTTPTimeout ¶
WithHTTPTimeout is how long a request may take before it is abandoned (default DefaultHTTPTimeout), for every call that names no shorter bound.
func WithLogger ¶
WithLogger logs what the SDK works around without failing a call: a state that could not be read or saved, a device that could not be identified, a request that got no answer (at debug level: an offline customer makes many), and a panic recovered from an adapter (at error level, with its stack). Never a licence key, an address, a code or a fingerprint. Default: no log.
Example ¶
package main
import (
"context"
"log"
"log/slog"
"os"
keygrant "github.com/keygrantdev/keygrant-go"
)
// publicKeys is the product's key set, as its Signing key tab copies it. An app
// embeds it: //go:embed keygrant-keys.json.
var publicKeys string
func main() {
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))
lic, err := keygrant.New("autowind", "https://api.keygrant.dev", publicKeys, keygrant.WithLogger(logger))
if err != nil {
log.Fatal(err)
}
_ = lic.Status(context.Background())
}
Output:
func WithMajor ¶
WithMajor is the app's major version (default 1). Read as the server reads a version: a 0.x build (0) runs as major 1.
func WithRevokedLicenseFiles ¶
WithRevokedLicenseFiles are the ids of licence files this build refuses.
func WithStash ¶
WithStash replaces the default trial stash (the registry on Windows, none elsewhere); nil is none. Its calls must return promptly: they run in the call that starts a trial.
func WithStoragePath ¶
WithStoragePath keeps the default storage's file at path instead of DefaultStoragePath. The path must be absolute: a relative one would move with the working directory, and with it the licence.
type PickedKey ¶
type PickedKey struct {
Key string
Model KeyModel // the licence model's type, "" when the server sent none
ModelName string // its name, "" when none
State KeyState
// Entitlements is what the key grants, nil when nothing.
Entitlements map[string]Entitlement
// ExpiresAt is when the key ends; the zero time for one that does not.
ExpiresAt time.Time
// Versions are the majors the key covers; nil for a key sold without a
// version and not yet bound, which covers any build.
Versions *PickedVersions
DeviceLimit int64
ActiveDevices int64
// Held is whether this device already holds a seat on the key.
Held bool
// Sale is the sale the key is one of, when the server said.
Sale *PickedSale
// ActivationCode is the code a code-locked key activates with: pass it to
// Activate WithCode. "" for any other key.
ActivationCode string
}
PickedKey is one of the address's live keys a pickup handed back. Show it by ModelName and let the customer pick; never show the key itself.
type PickedSale ¶
PickedSale is the sale a picked key is one of: its id, the key's place in it and its size.
type PickedVersions ¶
PickedVersions are the majors a picked key covers: from MinMajor up to MaxMajor (nil: no highest), and every major while UpgradeUntil (the zero time: none) is ahead.
type Reason ¶
type Reason string
Reason is why a Status is what it is.
const ( // ReasonRevoked: the key was revoked, refunded or expired, or this device released. ReasonRevoked Reason = "revoked" // ReasonUpgrade: the build is newer than the key covers (buy an upgrade). ReasonUpgrade Reason = "upgrade" // ReasonOutdated: the build is older than the key's lowest version (update the app). ReasonOutdated Reason = "outdated" // ReasonOffline: the lease ran out with the server out of reach. ReasonOffline Reason = "offline" // ReasonTampered: the lease is not this licence's. ReasonTampered Reason = "tampered" // ReasonUnknownKey: the lease is signed by a key this build does not carry. ReasonUnknownKey Reason = "unknown-key" // ReasonDevice: the licence was activated on another device. ReasonDevice Reason = "device" // ReasonTrial: the trial has ended. ReasonTrial Reason = "trial" // ReasonStorage: the stored state could not be read just now. ReasonStorage Reason = "storage" // ReasonRevokedFile: the stored licence file is one this build refuses // (WithRevokedLicenseFiles). ReasonRevokedFile Reason = "revoked-file" )
The reasons.
type RegistryStash ¶
type RegistryStash struct {
// contains filtered or unexported fields
}
RegistryStash keeps a trial's start in HKCU\Software\KeyGrant\<product>, value TrialStart, a REG_QWORD of milliseconds since the epoch: the one format every KeyGrant SDK reads and writes (sdk-contract.md 5.4), so a trial one SDK stashed is seen by another for the same product.
func NewRegistryStash ¶
func NewRegistryStash(product string) *RegistryStash
NewRegistryStash is the registry stash for a product.
func (*RegistryStash) ReadTrialStart ¶
func (r *RegistryStash) ReadTrialStart() (time.Time, error)
ReadTrialStart is the start kept: a REG_QWORD, or a REG_SZ of decimal digits and nothing else (its terminating NULs dropped); anything else (another type, 0, 2^53 or more) is none.
func (*RegistryStash) WriteTrialStart ¶
func (r *RegistryStash) WriteTrialStart(start time.Time) error
WriteTrialStart keeps the start as a REG_QWORD; a start that is no evidence is not written.
type Source ¶
type Source string
Source is where a status comes from, when it is not a key or a trial.
const SourceFile Source = "file"
SourceFile: the stored offline licence file.
type Stash ¶
type Stash interface {
// ReadTrialStart is the trial start kept, or the zero time for none.
ReadTrialStart() (time.Time, error)
WriteTrialStart(start time.Time) error
}
Stash keeps a trial's start where it outlives the app being removed, so a reinstall does not start a new trial (the Windows registry, by default on Windows). A failure costs nothing: a read that fails is no evidence, and a write that fails is ignored.
type State ¶
type State string
State is what a Status says of the licence.
const ( // Licensed: a key's lease (or an offline licence file) licenses this build. Licensed State = "licensed" // Trial: a trial runs on this device. Trial State = "trial" // Expired: the lease or the trial has run out (Reason says which). Expired State = "expired" // Invalid: what the device holds does not license this build (Reason says why). Invalid State = "invalid" // Unlicensed: no key and no trial. Unlicensed State = "unlicensed" // Unknown: the stored state could not be read just now (Reason storage): // nothing is known either way, so keep running and ask again shortly. Unknown State = "unknown" )
The states.
type Status ¶
type Status struct {
State State
Reason Reason // "" when there is none
// Key is the licence key this device holds, when it holds one.
Key string
// TrialEndsAt is when the running trial ends; the zero time otherwise.
TrialEndsAt time.Time
// TrialDaysLeft is the trial's days left, counted up (0 on its last day's end).
TrialDaysLeft int
// Test is true for a test licence: refuse one in a release build if you like.
Test bool
// Stalled is true when an earlier call on this License has not finished, so
// this answer comes from what is stored, with no ask and no write.
Stalled bool
// Entitlements is what the licence grants beyond the base product, by code;
// nil when it grants none, and on every status but licensed and trial.
Entitlements map[string]Entitlement
// Source is SourceFile when the stored offline licence file gives this
// status; "" otherwise.
Source Source
// LicensedTo is who that file is licensed to, on a licensed status from it
// and on an invalid one for revoked-file, upgrade or outdated; nil otherwise.
LicensedTo *LicensedTo
// Meters are the key's meters, by code, on a licensed status from a key's
// lease; nil when it has none, and on every other status.
Meters map[string]MeterStatus
}
Status is what the SDK says of the licence on this device.
type Storage ¶
type Storage interface {
// Read is the stored JSON object, or nil for none. readOnly (a call behind
// one that has not finished) reads and writes nothing else.
Read(readOnly bool) ([]byte, error)
// Write puts a whole state in place.
Write(data []byte) error
}
Storage keeps the licence's state: one JSON object. The default (NewFileStorage at DefaultStoragePath) writes atomically and merges a save again onto a state another process saved meanwhile; a Storage of your own replaces it.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
b64
Package b64 is base64url as every KeyGrant token is written (RFC 4648 section 5, no padding), read only in its canonical form.
|
Package b64 is base64url as every KeyGrant token is written (RFC 4648 section 5, no padding), read only in its canonical form. |
|
device
Package device is who the device is: the fingerprints the SDK sends, the claims a lease names a device by, and the default fingerprinter's reading of the machine id (the reference's adapters.ts, device.ts, machine-id.ts).
|
Package device is who the device is: the fingerprints the SDK sends, the claims a lease names a device by, and the default fingerprinter's reading of the machine id (the reference's adapters.ts, device.ts, machine-id.ts). |
|
jsonx
Package jsonx reads JSON as the reference SDK's JSON.parse does, into values a caller reads by exact member name: objects as map[string]any, arrays as []any, strings, booleans, nil, and numbers kept as their text (json.Number), so a whole number written 4.0, a number past 2^53 and one past a double's range are each seen for what they are.
|
Package jsonx reads JSON as the reference SDK's JSON.parse does, into values a caller reads by exact member name: objects as map[string]any, arrays as []any, strings, booleans, nil, and numbers kept as their text (json.Number), so a whole number written 4.0, a number past 2^53 and one past a double's range are each seen for what they are. |
|
jstext
Package jstext does to text what the reference SDK's JavaScript does to it, so a key, an address or a name is read the same in every KeyGrant SDK: String.prototype.trim, String.prototype.toUpperCase, lengths counted in UTF-16 units, and TextDecoder's reading of UTF-8.
|
Package jstext does to text what the reference SDK's JavaScript does to it, so a key, an address or a name is read the same in every KeyGrant SDK: String.prototype.trim, String.prototype.toUpperCase, lengths counted in UTF-16 units, and TextDecoder's reading of UTF-8. |
|
lease
Package lease verifies a KeyGrant lease offline: a compact JWS, EdDSA over Ed25519, against the build's key set (the reference's shared crypto.ts verifyLease), and reads its claims as the reference reads them.
|
Package lease verifies a KeyGrant lease offline: a compact JWS, EdDSA over Ed25519, against the build's key set (the reference's shared crypto.ts verifyLease), and reads its claims as the reference reads them. |
|
licensefile
Package licensefile reads and judges a licence file (sdk-contract.md section 10; the reference's shared license-file.ts, license-file-text.ts and the reference's license-file.ts): the container, the token verified offline against the build's key set, the judgement for this app and the status a stored one gives.
|
Package licensefile reads and judges a licence file (sdk-contract.md section 10; the reference's shared license-file.ts, license-file-text.ts and the reference's license-file.ts): the container, the token verified offline against the build's key set, the judgement for this app and the status a stored one gives. |
|
meters
Package meters is metered uses' logic (sdk-contract.md section 12; the reference's meters.ts and journal.ts): what use() was asked, the figures, a status's meters, spending offline, when a spend asks, the reports a request carries and the confirmations an answer brings, what a use answer does, and the journal of unsynced spends.
|
Package meters is metered uses' logic (sdk-contract.md section 12; the reference's meters.ts and journal.ts): what use() was asked, the figures, a status's meters, spending offline, when a spend asks, the reports a request carries and the confirmations an answer brings, what a use answer does, and the journal of unsynced spends. |
|
offline
Package offline is what the SDK decides from what the device holds, without asking the server (the reference's offline.ts): whether a lease licenses this build, what a trial shows, which refusal still stands, and when to ask again.
|
Package offline is what the SDK decides from what the device holds, without asking the server (the reference's offline.ts): whether a lease licenses this build, what a trial shows, which refusal still stands, and when to ask again. |
|
pickup
Package pickup is key pickup's logic (sdk-contract.md section 13; the reference's pickup.ts): what a person typed prepared to send, a refusal's word, a confirm's keys read leniently, and the key a restore activates.
|
Package pickup is key pickup's logic (sdk-contract.md section 13; the reference's pickup.ts): what a person typed prepared to send, a refusal's word, a confirm's keys read leniently, and the key a restore activates. |
|
state
Package state is what the SDK keeps on disk (sdk-contract.md 5.5): the stored state, a JSON object every KeyGrant SDK reads and writes the same way, how a save lands on it (merge.go), and the clock guard (clock.go).
|
Package state is what the SDK keeps on disk (sdk-contract.md 5.5): the stored state, a JSON object every KeyGrant SDK reads and writes the same way, how a save lands on it (merge.go), and the clock guard (clock.go). |
|
store
Package store is the SDK's default state file (the reference's storage.ts, storage-fs.ts; sdk-contract.md section 6): where it lives, and how it is read and written so that neither a crash nor a busy disk ever costs a customer their licence.
|
Package store is the SDK's default state file (the reference's storage.ts, storage-fs.ts; sdk-contract.md section 6): where it lives, and how it is read and written so that neither a crash nor a busy disk ever costs a customer their licence. |
|
wire
Package wire is what the SDK sends and reads on the wire (the reference's wire.ts): the server's error words, the bounds the endpoints hold strings to, and the shapes of their answers.
|
Package wire is what the SDK sends and reads on the wire (the reference's wire.ts): the server's error words, the bounds the endpoints hold strings to, and the shapes of their answers. |