Documentation
¶
Overview ¶
Package licencly verifies Licencly licenses and checks for entitled updates.
The design in one sentence: the signed license file is the answer, and the network is an optimisation. Validate reads the cache, refreshes when due, and keeps working through an outage until the grace period is spent, so Licencly being unreachable never stops software you have already sold.
client, err := licencly.New(licencly.Config{
ProductUUID: "…",
PublicKeys: licencly.MustParseKeys(map[string]string{"<kid>": "<base64>"}),
})
decision, err := client.Validate(ctx, licenseKey)
if !decision.OK() {
// decision.Outcome says why
}
Index ¶
- Constants
- Variables
- func DefaultCachePath(productSlug string) (string, error)
- func IsNetwork(err error) bool
- func IsTampering(err error) bool
- func MachineID(salt string) (string, error)
- func MustParseKeys(keys map[string]string) map[string]ed25519.PublicKey
- type APIError
- type Cache
- type Claims
- type Client
- func (c *Client) CheckForUpdate(ctx context.Context, licenseKey string, q UpdateQuery) (UpdateResult, error)
- func (c *Client) ClearCache() error
- func (c *Client) Deactivate(ctx context.Context, licenseKey string) error
- func (c *Client) DownloadArtifact(ctx context.Context, licenseKey string, release *Release, destDir string, ...) (string, error)
- func (c *Client) Validate(ctx context.Context, licenseKey string) (Decision, error)
- type Config
- type Decision
- type FileCache
- type MemoryCache
- type NetworkError
- type Outcome
- type Release
- type UpdateOutcome
- type UpdateQuery
- type UpdateResult
Constants ¶
const ( // Prefix is the format version, and is part of the signed bytes, so a // future format cannot be relabelled as this one. Prefix = "lcl1" // FormatVersion is the license file schema version, distinct from the SDK's // own Version. FormatVersion = 1 )
const ( StatusActive = "active" StatusSuspended = "suspended" StatusRevoked = "revoked" StatusExpired = "expired" )
License statuses carried in the file.
const Version = "1.0.0"
Version of this SDK, sent in the user agent so a vendor's traffic is identifiable when they ask for support.
Variables ¶
var ( ErrMalformed = errors.New("licencly: license file is malformed") ErrUnknownVersion = errors.New("licencly: unsupported license file version") ErrBadSignature = errors.New("licencly: signature does not verify") ErrUnknownKey = errors.New("licencly: license was signed by a key this build does not trust") ErrNotActive = errors.New("licencly: license is not active") ErrExpired = errors.New("licencly: license has expired") ErrWrongMachine = errors.New("licencly: license was issued to a different machine") ErrStale = errors.New("licencly: license is past its offline grace period") )
var ( ErrChecksumMismatch = errors.New("licencly: downloaded artifact does not match its checksum") ErrArtifactSignature = errors.New("licencly: artifact signature does not verify against your artifact key") ErrArtifactUnsigned = errors.New("licencly: artifact carries no signature") )
var ErrNoMachineID = errors.New("licencly: no stable machine identifier found")
ErrNoMachineID is returned when no stable identifier could be read. It is rare, and it means machine binding is not available on that host rather than that anything is wrong: handle it by validating without a fingerprint.
Functions ¶
func DefaultCachePath ¶
DefaultCachePath returns an OS-appropriate per-user location.
func IsNetwork ¶
IsNetwork reports whether the failure was reaching the server rather than anything about the license. Inside the grace period this should be handled silently.
func IsTampering ¶
IsTampering reports whether the license file failed verification. Never retry these: retrying obscures an attack and fixes nothing.
func MachineID ¶
MachineID returns a stable, hashed identifier for the machine it runs on, suitable for Config.Fingerprint. It reads, in order:
- Linux: /etc/machine-id, then /var/lib/dbus/machine-id
- macOS: IOPlatformUUID
- Windows: HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid
- anywhere: the MAC address of the first physical network interface
The operating system's identifier is preferred over a MAC deliberately. A MAC changes with a dock or a USB adapter, Wi-Fi MACs are randomised per network, and a machine running Docker or a VPN has several. The OS identifier survives all of that and a hardware upgrade, and does not survive being copied to another machine, which is the line a seat limit wants.
The result is hashed with salt, so no hardware identifier leaves the machine and the same computer looks different to every vendor. Pass your product UUID: it is stable and already public.
fp, err := licencly.MachineID(productUUID)
if err != nil {
fp = "" // no machine binding on this host
}
Types ¶
type APIError ¶
type APIError struct {
Status int
Code string
Message string
// RetryAfter is set on a 429.
RetryAfter time.Duration
}
APIError is a structured refusal from the server.
func (*APIError) NotFound ¶
NotFound reports an unknown product, an unknown key, or a malformed one. The server deliberately does not distinguish them: that would let anyone probe which keys are real.
func (*APIError) RateLimited ¶
func (*APIError) SeatLimitReached ¶
SeatLimitReached reports that the license is in use on the maximum number of machines. Distinguished from NotFound because the holder has proved they own a real key and needs to be told to free a seat.
type Cache ¶
type Cache interface {
Load() (file string, highestSeen time.Time, err error)
Save(file string, highestSeen time.Time) error
Clear() error
}
Cache stores the last good license file between runs. Without it, every launch needs the network and the offline guarantee is worthless.
type Claims ¶
type Claims struct {
Version int `json:"v"`
KeyID string `json:"kid"`
LicenseUUID string `json:"lic"`
Key string `json:"key"`
ProductUUID string `json:"prd"`
CustomerRef string `json:"sub"`
Status string `json:"st"`
Seats int `json:"seats"`
Used int `json:"used"`
Fingerprint string `json:"fp"`
IssuedAt int64 `json:"iat"`
ExpiresAt int64 `json:"exp"`
MaintenanceExpiresAt int64 `json:"mnt"`
RevalidateAfter int64 `json:"rev"`
GraceSeconds int64 `json:"grace"`
Metadata map[string]any `json:"meta,omitempty"`
}
Claims is the verified content of a license file.
func Decode ¶
Decode parses the payload WITHOUT verifying the signature.
Its only legitimate use is reading KeyID to choose a public key. Every claim is attacker-controlled until Verify has succeeded.
func Verify ¶
Verify checks the signature. It does not evaluate expiry, status or machine binding: call Claims.Check for that, so a caller can tell "forged" apart from "expired".
func VerifyWithKeys ¶
VerifyWithKeys selects the public key by the file's key id.
An unknown id is refused rather than retried against every key held: a client that tries them all accepts a file signed by a rotated-out key an attacker recovered.
func (Claims) Check ¶
Check evaluates verified claims against the local clock and machine.
fingerprint may be empty when the platform cannot produce one, in which case the machine binding is skipped, but a file issued to a specific machine will then be accepted anywhere, so pass one whenever you can.
func (Claims) ExpiresAtTime ¶
ExpiresAtTime returns the expiry, or the zero time for a perpetual license.
func (Claims) MaintenanceActive ¶
MaintenanceActive reports entitlement to releases published now. A perpetual license with lapsed maintenance keeps running but stops receiving updates.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func (*Client) CheckForUpdate ¶
func (c *Client) CheckForUpdate(ctx context.Context, licenseKey string, q UpdateQuery) (UpdateResult, error)
CheckForUpdate asks which release this license is entitled to.
Never consumes a seat: a background updater polling weekly must not exhaust a customer's activations.
func (*Client) ClearCache ¶
ClearCache removes the stored license. Exposed so support can say "run this".
func (*Client) Deactivate ¶
Deactivate frees this machine's seat.
func (*Client) DownloadArtifact ¶
func (c *Client) DownloadArtifact( ctx context.Context, licenseKey string, release *Release, destDir string, artifactKey ed25519.PublicKey, ) (string, error)
DownloadArtifact fetches a release and verifies it before returning a path.
artifactKey is YOUR Ed25519 public key, compiled into this application and not fetched from Licencly. That is what makes the guarantee real: Licencly stores and serves the signature but cannot produce one, so a compromise of Licencly cannot push code to your users.
Passing a nil key skips signature verification and only checks the digest. Do that only if you have not set up artifact signing; it reduces the check to corruption detection.
artifactKey comes last to match the Node, Python and .NET SDKs, where it is the optional argument and so has to. Four SDKs that disagree on argument order is a trap for anyone porting an integration between them.
func (*Client) Validate ¶
Validate decides whether this machine may run.
It refreshes from the server when the cached file is due, and falls back to the cache whenever the server cannot be reached, so a Licencly outage does not stop software that has already been sold. It never blocks on the network while a usable cached file exists.
The cache is keyed on the product, so it can hold a license other than the one being validated. A cached file is only reused when its key claim matches the key asked about and its fingerprint matches this machine; otherwise the server is asked, because answering with a different customer's license would be worse than failing.
type Config ¶
type Config struct {
// ProductUUID identifies your product. From the dashboard.
ProductUUID string
// PublicKeys maps a signing key id to its public key. Embed these in your
// application at build time: fetching them at runtime would defeat the
// entire scheme.
//
// Include retired keys as well as the active one: a license signed before
// a rotation still verifies against the key it was signed with.
PublicKeys map[string]ed25519.PublicKey
// Fingerprint identifies this machine. Empty disables machine binding,
// which makes the file usable anywhere it is copied.
Fingerprint string
// Cache persists the last good file. Defaults to a per-user file.
Cache Cache
BaseURL string
HTTPClient *http.Client
Timeout time.Duration
// DownloadTimeout bounds an artifact download, which is a different order
// of magnitude from an API call. Defaults to 30 minutes. Pass a context
// with a deadline for finer control.
DownloadTimeout time.Duration
Retries int
// Hostname, Platform and AppVersion are reported on activation so a vendor
// can recognise machines in their dashboard. Optional.
Hostname string
Platform string
AppVersion string
// Now overrides the clock, for tests.
Now func() time.Time
}
type Decision ¶
type Decision struct {
Outcome Outcome
// Claims is populated whenever the signature verified, even if the license
// is expired or revoked, so an app can say *which* license expired.
Claims Claims
// NeedsRevalidation is true inside the grace window: keep running, refresh
// in the background.
NeedsRevalidation bool
// FromCache reports that no network call was made or that one failed and
// the cached file was used.
FromCache bool
// Err carries the underlying cause for anything other than valid.
Err error
}
Decision is what an application acts on.
func (Decision) MaintenanceActive ¶
MaintenanceActive reports entitlement to new releases.
type FileCache ¶
type FileCache struct {
Path string
}
FileCache stores the file in the user's data directory.
Per-user and writable without privileges on purpose: an application that needs admin rights to cache a license will not have them when it matters.
type MemoryCache ¶
type MemoryCache struct {
// contains filtered or unexported fields
}
MemoryCache holds the file for the process lifetime only. Useful in tests and in short-lived jobs where writing to disk is unwelcome.
func (*MemoryCache) Clear ¶
func (c *MemoryCache) Clear() error
type NetworkError ¶
type NetworkError struct{ Err error }
NetworkError means Licencly could not be reached. Retryable, and inside the grace window it is not something the user should be shown.
func (*NetworkError) Error ¶
func (e *NetworkError) Error() string
func (*NetworkError) Unwrap ¶
func (e *NetworkError) Unwrap() error
type Outcome ¶
type Outcome string
Outcome is the result of evaluating a license. The set is fixed and shared by every Licencly SDK.
const ( // OutcomeValid means verified and inside its window. Run. OutcomeValid Outcome = "valid" // OutcomeInvalid means the signature or format failed. This is tampering, // not a network problem: refuse, and do not retry. OutcomeInvalid Outcome = "invalid" // OutcomeNotActive means suspended, revoked or expired by status. OutcomeNotActive Outcome = "not_active" // OutcomeExpired means past its expiry date. OutcomeExpired Outcome = "expired" // OutcomeWrongMachine means the file was issued to a different machine. OutcomeWrongMachine Outcome = "wrong_machine" // OutcomeStale means the offline grace period is spent and the server // could not be reached. OutcomeStale Outcome = "stale" )
type Release ¶
type Release struct {
UUID string `json:"uuid"`
Version string `json:"version"`
Channel string `json:"channel"`
Platform string `json:"platform"`
Arch string `json:"arch"`
Notes string `json:"notes"`
MinUpgradeFrom string `json:"min_upgrade_from"`
ArtifactSize int64 `json:"artifact_size"`
ArtifactSHA256 string `json:"artifact_sha256"`
ArtifactFilename string `json:"artifact_filename"`
Signed bool `json:"signed"`
}
type UpdateOutcome ¶
type UpdateOutcome string
UpdateOutcome mirrors the server's vocabulary exactly, so a vendor reading their logs sees the same word the API returned.
const ( UpdateAvailable UpdateOutcome = "update_available" UpToDate UpdateOutcome = "up_to_date" // MaintenanceLapsed is NOT an error. A newer release exists and this // license is not entitled to it; Latest names what a renewal would unlock. MaintenanceLapsed UpdateOutcome = "maintenance_lapsed" // UpgradeBlocked means an entitled release exists but needs an // intermediate version this client has not reached. UpgradeBlocked UpdateOutcome = "upgrade_blocked" NotEntitled UpdateOutcome = "not_entitled" )
type UpdateQuery ¶
type UpdateResult ¶
type UpdateResult struct {
Outcome UpdateOutcome
// Release is the one to install, when Outcome is UpdateAvailable.
Release *Release
// Latest is what a renewal would unlock, when held back.
Latest *Release
DownloadURL string
}
func (UpdateResult) Available ¶
func (r UpdateResult) Available() bool
Available is the single check for "should I offer an update".
func (UpdateResult) RenewalWouldUnlock ¶
func (r UpdateResult) RenewalWouldUnlock() bool
RenewalWouldUnlock reports that a newer release exists but this license cannot have it: a prompt, not a failure.