licencly

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

licencly-go

Verify Licencly licenses and check for entitled updates, from Go.

go get github.com/licencly/licencly-go

The idea

The signed license file is the answer; the network is an optimisation. The client reads its 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.

Quickstart

Copy the product UUID and public key from your Licencly dashboard and embed them at build time. Fetching keys at runtime would defeat the whole scheme.

package main

import (
	"context"
	"fmt"

	"github.com/licencly/licencly-go"
)

// From Products → your product → Signing key.
var publicKeys = licencly.MustParseKeys(map[string]string{
	"9f2c1a44-…": "MWvD7YE6HjI/DQ0kYGJFNG4kXlx4hP6ck1Vr4j77fzk=",
})

func main() {
	client, err := licencly.New(licencly.Config{
		ProductUUID: "fec65576-…",
		PublicKeys:  publicKeys,
		Fingerprint: machineID(), // yours; see below
	})
	if err != nil {
		panic(err)
	}

	decision, err := client.Validate(context.Background(), userEnteredKey)
	if err != nil && !licencly.IsNetwork(err) {
		fmt.Println("licensing error:", err)
		return
	}

	switch decision.Outcome {
	case licencly.OutcomeValid:
		// Run.
	case licencly.OutcomeNotActive:
		fmt.Println("This license has been suspended or revoked.")
	case licencly.OutcomeExpired:
		fmt.Println("This license expired. Renew to continue.")
	case licencly.OutcomeWrongMachine:
		fmt.Println("This license is in use on another machine.")
	case licencly.OutcomeStale:
		fmt.Println("Please connect to the internet to re-check your license.")
	case licencly.OutcomeInvalid:
		fmt.Println("This license file could not be verified.")
	}
}

Validate makes no network call at all while the cached file is still fresh.

Offline

When Behaviour
Before rev Cache only, no network
Between rev and rev + grace Keeps working, refreshes in the background. NeedsRevalidation is true
After rev + grace OutcomeStale

A network failure inside the grace window is not an error your users should see. Check licencly.IsNetwork(err) and stay quiet.

Updates

res, err := client.CheckForUpdate(ctx, key, licencly.UpdateQuery{
	CurrentVersion: "1.2.0",
	Platform:       runtime.GOOS,
	Arch:           runtime.GOARCH,
})

switch {
case res.Available():
	path, err := client.DownloadArtifact(ctx, key, res.Release, "/tmp/updates", artifactKey)

case res.RenewalWouldUnlock():
	// Not an error: a newer version exists and this license is not entitled
	// to it. res.Latest names what renewing would unlock.
	fmt.Printf("Version %s is available with an active maintenance plan.\n", res.Latest.Version)
}

Checking for updates never consumes a seat.

Verifying downloads

artifactKey is your own Ed25519 public key, compiled into your application, not fetched from Licencly. Licencly stores and serves the signature but cannot produce one, so a compromise of Licencly cannot push code to your users. DownloadArtifact verifies the digest and that signature before the file is moved into place; passing nil reduces it to corruption detection.

Generate the keypair with the sign tool in the server repo, and keep the private half off Licencly entirely.

Machine fingerprints

The SDK does not compute one, because a good fingerprint is specific to what you ship. It must stay stable across restarts, app updates and reboots, and survive minor hardware change. VMs, containers and cloned disks all defeat naive approaches. Budget more thought than it looks like it needs.

If you leave Fingerprint empty, machine binding is disabled and a license file copied to another machine will still verify.

Clock tampering

Expiry is checked against a clock the user controls; rolling it back extends an expired license offline. This is unavoidable for anything that must work without a network, and it is true of every offline licensing scheme.

The SDK records the furthest-forward time it has seen and rejects a jump backwards of more than 24 hours. That is a speed bump, not a fix.

Errors worth telling apart

Check Meaning
licencly.IsNetwork(err) Could not reach the server. Retryable, and silent inside grace
licencly.IsTampering(err) Signature or format failure. Never retry
*APIError.SeatLimitReached() No free activations
*APIError.NotFound() Unknown product or key
*APIError.RateLimited() Carries RetryAfter

Conformance

go test ./... runs testdata/vectors.json, the same suite every Licencly SDK runs. If this SDK ever disagrees with the Python, TypeScript or .NET ones, that test fails first.

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

View Source
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
)
View Source
const (
	StatusActive    = "active"
	StatusSuspended = "suspended"
	StatusRevoked   = "revoked"
	StatusExpired   = "expired"
)

License statuses carried in the file.

View Source
const Version = "1.0.1"

Version of this SDK, sent in the user agent so a vendor's traffic is identifiable when they ask for support.

Variables

View Source
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")
)
View Source
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")
)
View Source
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

func DefaultCachePath(productSlug string) (string, error)

DefaultCachePath returns an OS-appropriate per-user location.

func IsNetwork

func IsNetwork(err error) bool

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

func IsTampering(err error) bool

IsTampering reports whether the license file failed verification. Never retry these: retrying obscures an attack and fixes nothing.

func MachineID

func MachineID(salt string) (string, error)

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
}

func MustParseKeys

func MustParseKeys(keys map[string]string) map[string]ed25519.PublicKey

MustParseKeys turns base64 public keys into the map Config wants. It panics on malformed input, which is correct for keys compiled into a binary: a bad key is a build error, not a runtime condition.

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) Error

func (e *APIError) Error() string

func (*APIError) NotFound

func (e *APIError) NotFound() bool

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 (e *APIError) RateLimited() bool

func (*APIError) SeatLimitReached

func (e *APIError) SeatLimitReached() bool

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

func Decode(token string) (Claims, error)

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

func Verify(token string, pub ed25519.PublicKey) (Claims, error)

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

func VerifyWithKeys(token string, keys map[string]ed25519.PublicKey) (Claims, error)

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

func (c Claims) Check(now time.Time, fingerprint string) error

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

func (c Claims) ExpiresAtTime() time.Time

ExpiresAtTime returns the expiry, or the zero time for a perpetual license.

func (Claims) MaintenanceActive

func (c Claims) MaintenanceActive(now time.Time) bool

MaintenanceActive reports entitlement to releases published now. A perpetual license with lapsed maintenance keeps running but stops receiving updates.

func (Claims) NeedsRevalidation

func (c Claims) NeedsRevalidation(now time.Time) bool

NeedsRevalidation reports whether the file is past its check-in time but still inside the grace window: the period where the app keeps running and refreshes in the background.

type Client

type Client struct {
	// contains filtered or unexported fields
}

func New

func New(cfg Config) (*Client, error)

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

func (c *Client) ClearCache() error

ClearCache removes the stored license. Exposed so support can say "run this".

func (*Client) Deactivate

func (c *Client) Deactivate(ctx context.Context, licenseKey string) error

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

func (c *Client) Validate(ctx context.Context, licenseKey string) (Decision, error)

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

func (d Decision) MaintenanceActive(now time.Time) bool

MaintenanceActive reports entitlement to new releases.

func (Decision) OK

func (d Decision) OK() bool

OK is the single check an application should gate on.

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.

func (*FileCache) Clear

func (c *FileCache) Clear() error

func (*FileCache) Load

func (c *FileCache) Load() (string, time.Time, error)

func (*FileCache) Save

func (c *FileCache) Save(file string, highestSeen time.Time) error

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

func (*MemoryCache) Load

func (c *MemoryCache) Load() (string, time.Time, error)

func (*MemoryCache) Save

func (c *MemoryCache) Save(file string, highestSeen time.Time) 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 UpdateQuery struct {
	CurrentVersion string
	Channel        string
	Platform       string
	Arch           string
}

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL