licensing

package
v0.0.18 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package licensing is an idiomatic Go client for the Keygen licensing API (https://keygen.sh), working both against Keygen CE/EE and any 1:1 compatible implementation.

A Client is created from a Config and is safe for concurrent use. Authenticate either with a license key (the end-user's credential) or an API token:

client, err := licensing.New(licensing.Config{
	Account:    "example-com",
	LicenseKey: licenseKey,
	PublicKey:  accountEd25519Hex,
})
if err != nil {
	log.Fatal(err)
}

Validations return typed sentinel errors, matched with errors.Is:

license, err := client.Validate(ctx, licensing.WithFingerprint(fp))
switch {
case err == nil:
	// licensed
case errors.Is(err, licensing.ErrNotActivated):
	_, err = license.Activate(ctx, fp)
case errors.Is(err, licensing.ErrExpired),
	errors.Is(err, licensing.ErrSuspended):
	// refuse to run
}

With Config.PublicKey set, every API response is verified against the account's signature, and offline artifacts can be verified and decrypted without touching the network:

file, err := license.Checkout(ctx)
...
if err := file.Verify(verifier); err != nil { ... }
dataset, err := file.Decrypt(licenseKey)

A genuine file past its expiry (or issued in the future beyond the clock skew) still decodes: Decode and Decrypt answer the dataset with ErrLicenseFileExpired / ErrMachineFileExpired / ErrClockOutOfSync, so a lapsed lease can be shown and told apart from an invalid one (a bad signature, key or fingerprint answers no dataset):

dataset, err := file.Decrypt(licenseKey, fingerprint)
switch {
case err == nil: // in force
case errors.Is(err, licensing.ErrMachineFileExpired): // lapsed, dataset readable
default: // invalid, dataset nil (unless ErrClockOutOfSync)
}

Heartbeats run in the caller's goroutine, tied to a context:

ctx, stop := context.WithCancel(context.Background())
go func() { _ = machine.Monitor(ctx) }()
defer stop()

Webhooks received from the API can be verified with Verifier.VerifyWebhook.

Index

Constants

View Source
const (
	// SignEd25519 is the default signing algorithm.
	SignEd25519 = algEd25519
	// SignRSAPSSSHA256 signs with RSA-PSS-SHA256.
	SignRSAPSSSHA256 = algRSAPSSSHA256
	// SignRSASHA256 signs with RSA-SHA256.
	SignRSASHA256 = algRSASHA256
	// SignECDSAP256 signs with ECDSA P-256.
	SignECDSAP256 = algECDSAP256
)

Signing algorithms accepted in checkout options, in Keygen's wire form.

View Source
const (
	// DefaultAPIURL is the Keygen cloud API endpoint.
	DefaultAPIURL = "https://api.keygen.sh"
	// DefaultAPIPrefix is the major version prefix of every API path.
	DefaultAPIPrefix = "/v1"
	// DefaultAPIVersion is sent as Keygen-Version on every request.
	DefaultAPIVersion = "1.8"
	// DefaultClockSkew is the maximum tolerated difference between the
	// server's Date/issued timestamps and the local clock. Negative
	// Config.ClockSkew disables the checks.
	DefaultClockSkew = 5 * time.Minute
)

Defaults the client falls back to when Config leaves a field empty.

Variables

View Source
var (
	// ErrTokenInvalid reports an unknown or malformed API token (401).
	ErrTokenInvalid = errors.New("token is invalid")

	// ErrTokenExpired reports an expired API token (401).
	ErrTokenExpired = errors.New("token is expired")

	// ErrTokenNotAllowed reports token authentication the policy forbids (403).
	ErrTokenNotAllowed = errors.New("token authentication is not allowed by policy")

	// ErrLicenseNotAllowed reports license-key authentication the policy
	// forbids (403).
	ErrLicenseNotAllowed = errors.New("license authentication is not allowed by policy")

	// ErrLicenseBanned reports a banned license (403).
	ErrLicenseBanned = errors.New("license is banned")

	// ErrLicenseSuspended reports a suspended license (403).
	ErrLicenseSuspended = errors.New("license is suspended")

	// ErrLicenseExpired reports an expired license that lost access (403).
	ErrLicenseExpiredAuth = errors.New("license is expired")

	// ErrLicenseInvalidKey reports an unknown license key (401).
	ErrLicenseInvalidKey = errors.New("license key is invalid")

	// ErrNotFound reports a 404 for the addressed resource.
	ErrNotFound = errors.New("resource was not found")

	// ErrForbidden reports a 403 the more specific sentinels do not cover.
	ErrForbidden = errors.New("not authorized to perform the request")
)

Credential and transport errors.

View Source
var (
	// ErrLicenseKeyMissing reports a checkout on a license whose key is
	// not known to the client.
	ErrLicenseKeyMissing = errors.New("license key is missing")

	// ErrNotFound reports a validation with code NOT_FOUND: the license
	// does not exist.
	ErrValidationNotFound = errors.New("license does not exist")

	// ErrBanned reports code BANNED: the license owner is banned.
	ErrBanned = errors.New("license owner is banned")

	// ErrSuspended reports code SUSPENDED.
	ErrSuspended = errors.New("license is suspended")

	// ErrExpired reports code EXPIRED.
	ErrExpired = errors.New("license is expired")

	// ErrOverdue reports code OVERDUE: a required check-in is overdue.
	ErrOverdue = errors.New("license is overdue for check in")

	// ErrNotActivated reports codes NO_MACHINE / NO_MACHINES: the license
	// has no activated machine.
	ErrNotActivated = errors.New("license is not activated")

	// ErrTooManyMachines reports code TOO_MANY_MACHINES.
	ErrTooManyMachines = errors.New("license has too many machines")

	// ErrTooManyCores reports code TOO_MANY_CORES.
	ErrTooManyCores = errors.New("license has too many cores")

	// ErrTooManyProcesses reports code TOO_MANY_PROCESSES.
	ErrTooManyProcesses = errors.New("license has too many processes")

	// ErrFingerprintScopeMismatch reports code FINGERPRINT_SCOPE_MISMATCH.
	ErrFingerprintScopeMismatch = errors.New("fingerprint does not match an activated machine")

	// ErrFingerprintScopeRequired reports codes
	// FINGERPRINT_SCOPE_REQUIRED / _EMPTY.
	ErrFingerprintScopeRequired = errors.New("fingerprint scope is required")

	// ErrComponentsScopeMismatch reports code COMPONENTS_SCOPE_MISMATCH.
	ErrComponentsScopeMismatch = errors.New("components do not match activated components")

	// ErrComponentsScopeRequired reports codes
	// COMPONENTS_SCOPE_REQUIRED / _EMPTY.
	ErrComponentsScopeRequired = errors.New("components scope is required")

	// ErrHeartbeatNotStarted reports code HEARTBEAT_NOT_STARTED.
	ErrHeartbeatNotStarted = errors.New("machine heartbeat is required but has not started")

	// ErrHeartbeatDead reports code HEARTBEAT_DEAD, and the API errors
	// MACHINE_HEARTBEAT_DEAD / PROCESS_HEARTBEAT_DEAD on ping.
	ErrHeartbeatDead = errors.New("machine heartbeat is dead")

	// ErrProductScopeMismatch reports code PRODUCT_SCOPE_MISMATCH.
	ErrProductScopeMismatch = errors.New("product scope does not match")

	// ErrPolicyScopeMismatch reports code POLICY_SCOPE_MISMATCH.
	ErrPolicyScopeMismatch = errors.New("policy scope does not match")

	// ErrMachineScopeMismatch reports code MACHINE_SCOPE_MISMATCH.
	ErrMachineScopeMismatch = errors.New("machine scope does not match")

	// ErrUserScopeMismatch reports code USER_SCOPE_MISMATCH.
	ErrUserScopeMismatch = errors.New("user scope does not match")

	// ErrEntitlementsMissing reports codes ENTITLEMENTS_MISSING / _EMPTY.
	ErrEntitlementsMissing = errors.New("license is missing one or more required entitlements")

	// ErrLicenseInvalid reports any validation code without its own
	// sentinel.
	ErrLicenseInvalid = errors.New("license is invalid")
)

Validation outcomes: Validate returns one of these (wrapped in APIError, which carries the full detail) when the validation code is not VALID. The License returned alongside still holds the complete Validation result.

View Source
var (
	// ErrMachineAlreadyActivated reports FINGERPRINT_TAKEN.
	ErrMachineAlreadyActivated = errors.New("machine is already activated")

	// ErrMachineLimitExceeded reports MACHINE_LIMIT_EXCEEDED.
	ErrMachineLimitExceeded = errors.New("machine limit has been exceeded")

	// ErrProcessLimitExceeded reports MACHINE_PROCESS_LIMIT_EXCEEDED.
	ErrProcessLimitExceeded = errors.New("process limit has been exceeded")
)

Activation and process errors.

View Source
var (
	// ErrPublicKeyMissing reports verification attempted without a key.
	ErrPublicKeyMissing = errors.New("public key is missing")

	// ErrPublicKeyInvalid reports an unparsable public key.
	ErrPublicKeyInvalid = errors.New("public key is invalid")

	// ErrSchemeNotSupported reports a key/file scheme the client cannot
	// verify.
	ErrSchemeNotSupported = errors.New("cryptographic scheme is not supported")

	// ErrSignatureMissing reports an absent signature header.
	ErrSignatureMissing = errors.New("signature is missing")

	// ErrSignatureInvalid reports a failed signature verification.
	ErrSignatureInvalid = errors.New("signature is invalid")

	// ErrDigestMissing reports an absent digest header.
	ErrDigestMissing = errors.New("digest is missing")

	// ErrDigestInvalid reports a body digest mismatch.
	ErrDigestInvalid = errors.New("digest is invalid")

	// ErrDateMissing reports an absent Date header.
	ErrDateMissing = errors.New("date is missing")

	// ErrDateInvalid reports an unparsable Date header.
	ErrDateInvalid = errors.New("date is invalid")

	// ErrDateTooOld reports a Date header beyond the clock skew.
	ErrDateTooOld = errors.New("date is too old")

	// ErrClockOutOfSync reports a file issued in the future beyond the
	// clock skew, i.e. a system clock problem or a tampered file.
	ErrClockOutOfSync = errors.New("system clock is out of sync")

	// ErrLicenseKeyNotGenuine reports a license key whose signature does
	// not verify.
	ErrLicenseKeyNotGenuine = errors.New("license key is not genuine")

	// ErrLicenseFileNotGenuine reports a license file whose signature
	// does not verify.
	ErrLicenseFileNotGenuine = errors.New("license file is not genuine")

	// ErrMachineFileNotGenuine reports a machine file whose signature
	// does not verify.
	ErrMachineFileNotGenuine = errors.New("machine file is not genuine")

	// ErrFileNotEncrypted reports Decode on an encrypted file.
	ErrFileNotEncrypted = errors.New("file is encrypted")

	// ErrFileEncrypted reports Decrypt on an unencrypted file.
	ErrFileEncrypted = errors.New("file is not encrypted")

	// ErrFileNotSupported reports a certificate algorithm the client
	// cannot handle.
	ErrFileNotSupported = errors.New("certificate algorithm is not supported")

	// ErrLicenseFileExpired reports an expired license file dataset.
	ErrLicenseFileExpired = errors.New("license file is expired")

	// ErrMachineFileExpired reports an expired machine file dataset.
	ErrMachineFileExpired = errors.New("machine file is expired")

	// ErrCertificateInvalid reports a malformed certificate block.
	ErrCertificateInvalid = errors.New("certificate is invalid")

	// ErrUnbound reports an API operation on a value decoded from an
	// offline file dataset, which has no client attached.
	ErrUnbound = errors.New("value is not bound to a client")
)

Cryptographic errors.

View Source
var ErrConfig = errors.New("invalid config")

ErrConfig reports an invalid Config to New.

View Source
var ErrInvalidIdentifier = errors.New("identifier is invalid")

ErrInvalidIdentifier reports a resource id (UUID) or machine fingerprint that is empty, too long or has characters outside [A-Za-z0-9_:-]. Such a value is refused before any request is made.

View Source
var ErrReservedMetadata = errors.New("metadata key is reserved")

ErrReservedMetadata reports a metadata update touching the keys the installation activation owns ("fingerprint", "publicKey"): changing them would unbind the installation key from the machine.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// Status is the HTTP status code.
	Status int

	// Title is the error title, e.g. "Not found".
	Title string

	// Detail is the human-readable explanation.
	Detail string

	// Code is the Keygen error code, e.g. "NOT_FOUND".
	Code string

	// Source points at the offending request part, e.g. pointer
	// "/data/attributes/fingerprint" or parameter "limit".
	Source string

	// RequestID is the request's UUID from X-Request-Id.
	RequestID string
}

APIError is a structured Keygen error document. All non-2xx responses (except 429, see RateLimitError) come back as *APIError, usually wrapping one of the sentinel errors above so errors.Is works.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the sentinel for well-known codes so errors.Is matches.

type ActivationOption

type ActivationOption func(*ActivationOptions)

ActivationOption configures a machine activation.

func WithActivationComponents

func WithActivationComponents(components ...Component) ActivationOption

WithActivationComponents activates hardware components together with the machine.

func WithMachineCores

func WithMachineCores(cores int) ActivationOption

WithMachineCores overrides the core count (default: NumCPU).

func WithMachineHostname

func WithMachineHostname(hostname string) ActivationOption

WithMachineHostname overrides the hostname (default: os.Hostname).

func WithMachineMetadata

func WithMachineMetadata(metadata map[string]string) ActivationOption

WithMachineMetadata attaches metadata to the machine.

func WithMachineName

func WithMachineName(name string) ActivationOption

WithMachineName names the machine.

func WithMachinePlatform

func WithMachinePlatform(platform string) ActivationOption

WithMachinePlatform overrides the platform (default: os/arch).

type ActivationOptions

type ActivationOptions struct {
	Name       string
	Hostname   string
	Platform   string
	Cores      int
	Metadata   map[string]string
	Components []Component
}

ActivationOptions collect the optional parts of a machine activation.

type CheckoutOption

type CheckoutOption func(*CheckoutOptions)

CheckoutOption configures a checkout.

func CheckoutEncrypt

func CheckoutEncrypt(encrypt bool) CheckoutOption

CheckoutEncrypt toggles payload encryption.

func CheckoutInclude

func CheckoutInclude(include ...string) CheckoutOption

CheckoutInclude embeds the given relationships in the file, e.g. "entitlements" or "license", "license.entitlements".

func CheckoutSign

func CheckoutSign(algorithm string) CheckoutOption

CheckoutSign selects the signing algorithm.

func CheckoutTTL

func CheckoutTTL(ttl time.Duration) CheckoutOption

CheckoutTTL sets the file's time-to-live in whole seconds. The server takes at least one hour: less is an *APIError 400 CHECKOUT_TTL_INVALID.

type CheckoutOptions

type CheckoutOptions struct {
	// Encrypt switches the certificate payload between AES-256-GCM and
	// plain base64. Default: true.
	Encrypt bool

	// Sign is the signing algorithm. Default: ed25519.
	Sign string

	// TTL is the file's lifetime; zero means the server default
	// (one month).
	TTL time.Duration

	// Include lists related resources embedded in the file.
	Include []string
}

CheckoutOptions configure a license or machine file checkout.

type Client

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

Client is a Keygen licensing API client. Construct it with New; it is safe for concurrent use. Every response is verified against the account's public key when Config.PublicKey is set.

func New

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

New validates cfg, resolves defaults, and returns a ready Client. It performs no I/O.

func (*Client) Machine added in v0.0.5

func (c *Client) Machine(ctx context.Context, idOrFingerprint string) (*Machine, error)

Machine fetches a machine by UUID or fingerprint through the client's credentials (admin/product token, not a license key). It calls GET /v1/accounts/{account}/machines/{id} (cloud) or GET /v1/machines/{id} (self-hosted). Keygen allows id or fingerprint in the path.

The identifier is validated and the path segment is escaped with url.PathEscape so metacharacters in the input cannot change the request path.

func (*Client) Me

func (c *Client) Me(ctx context.Context) (*License, error)

Me fetches the current license (GET /v1/me). It requires license-key authentication.

func (*Client) Validate

func (c *Client) Validate(ctx context.Context, options ...ValidationOption) (*License, error)

Validate performs a license validation, optionally scoped to a machine fingerprint and component fingerprints. It fetches the license first, then runs the scoped validation. The returned License carries the full Validation result; when the code is not VALID the error wraps one of the validation sentinels (ErrNotActivated, ErrExpired, ...).

func (*Client) ValidateMachine added in v0.0.5

func (c *Client) ValidateMachine(ctx context.Context, fingerprint string) (*Machine, *License, error)

ValidateMachine looks up a machine by fingerprint, validates its license with the fingerprint scope, and returns both. It works with token-authenticated clients (admin/product tokens), unlike Validate which uses Me (license-key authentication).

type Component

type Component struct {
	// ID is the component UUID.
	ID string `json:"-"`

	// Fingerprint identifies the component.
	Fingerprint string `json:"fingerprint"`

	// Name is the display name.
	Name string `json:"name"`

	// Created/Updated are the resource timestamps.
	Created time.Time `json:"created"`
	Updated time.Time `json:"updated"`

	// Metadata is free-form.
	Metadata map[string]string `json:"metadata"`

	// MachineID comes from the component's relationships.
	MachineID string `json:"-"`
}

Component is a hardware component of a machine.

type Config

type Config struct {
	// APIURL is the API origin, e.g. https://api.keygen.sh (default) or
	// http://localhost:3900 for a self-hosted instance. When it equals
	// the Keygen cloud URL, requests are scoped under
	// /accounts/{Account}; any other origin is used as-is (singleplayer
	// / custom domain form).
	APIURL string

	// APIPrefix prefixes every path. Default "/v1".
	APIPrefix string

	// APIVersion is sent as the Keygen-Version header. Default "1.8".
	APIVersion string

	// Account is the Keygen account id or slug. Required for the Keygen
	// cloud URL; ignored for self-hosted singleplayer endpoints.
	Account string

	// Product scopes license validations to a product id (optional).
	Product string

	// LicenseKey authenticates as the license ("License" scheme).
	LicenseKey string

	// Token authenticates with an API token ("Bearer" scheme). At most
	// one of LicenseKey and Token should be set; LicenseKey wins.
	Token string

	// PublicKey verifies API response signatures, license/machine file
	// signatures, and signed license keys: the account's ed25519 public
	// key as hex, or a PEM-encoded RSA or ECDSA public key. Optional —
	// without it responses and files are trusted as-is.
	PublicKey string

	// UserAgent is appended to the client's default User-Agent.
	UserAgent string

	// HTTPClient performs the requests. Default: a pooled client with
	// sane timeouts.
	HTTPClient *http.Client

	// Logger receives request/response debug lines. Optional.
	Logger *slog.Logger

	// Headers are extra headers sent on every request, e.g. Host or
	// X-Forwarded-Proto for instances behind a proxy. The "Host" key
	// sets the request's Host header (URL and signatures follow).
	Headers map[string]string

	// ClockSkew bounds the tolerated difference between the server's
	// clocks and ours when checking response Date headers and file
	// issued timestamps. Default 5m; negative disables.
	ClockSkew time.Duration
}

Config configures a Client. The zero value plus Account and LicenseKey (or Token) is a valid starting point; everything else falls back to the Keygen cloud defaults.

type Entitlement

type Entitlement struct {
	// ID is the entitlement UUID.
	ID string `json:"-"`

	// Code identifies the entitlement, e.g. "premium-features".
	Code string `json:"code"`

	// Name is the display name.
	Name string `json:"name"`

	// Expiry is the entitlement's expiration, null = perpetual.
	Expiry *time.Time `json:"expiry"`

	// Created/Updated are the resource timestamps.
	Created time.Time `json:"created"`
	Updated time.Time `json:"updated"`

	// Metadata is free-form.
	Metadata Metadata `json:"metadata"`
}

Entitlement is a license's entitlement (a feature flag with an expiration date).

type HeartbeatStatus

type HeartbeatStatus string

HeartbeatStatus is a machine's heartbeat lifecycle state.

const (
	HeartbeatNotStarted  HeartbeatStatus = "NOT_STARTED"
	HeartbeatAlive       HeartbeatStatus = "ALIVE"
	HeartbeatDead        HeartbeatStatus = "DEAD"
	HeartbeatResurrected HeartbeatStatus = "RESURRECTED"
)

Machine heartbeat statuses.

type License

type License struct {

	// ID is the license UUID.
	ID string `json:"-"`

	// Name is the display name.
	Name string `json:"name"`

	// Key is the license key.
	Key string `json:"key"`

	// Expiry is null for perpetual licenses.
	Expiry *time.Time `json:"expiry"`

	// Status is ACTIVE, INACTIVE, EXPIRING, EXPIRED, SUSPENDED, or BANNED.
	Status string `json:"status"`

	// Uses is the current usage counter.
	Uses int `json:"uses"`

	// Suspended reports manual suspension.
	Suspended bool `json:"suspended"`

	// Scheme is the key signing scheme, empty for plain keys.
	Scheme Scheme `json:"scheme"`

	// Strict reports that the policy requires machine tracking.
	Strict bool `json:"strict"`

	// Floating reports multi-seat policies (node-locked when false).
	Floating bool `json:"floating"`

	// Protected reports protection from non-admin mutation.
	Protected bool `json:"protected"`

	// RequireHeartbeat reports that machines must ping.
	RequireHeartbeat bool `json:"requireHeartbeat"`

	// RequireCheckIn reports periodic license check-ins.
	RequireCheckIn bool `json:"requireCheckIn"`

	// MaxMachines/MaxCores/MaxProcesses are the policy limits (null =
	// unlimited).
	MaxMachines  *int `json:"maxMachines"`
	MaxCores     *int `json:"maxCores"`
	MaxProcesses *int `json:"maxProcesses"`

	// Version is the last validated version.
	Version string `json:"version"`

	// LastValidated/LastCheckIn/LastCheckOut are the activity timestamps.
	LastValidated *time.Time `json:"lastValidated"`
	LastCheckIn   *time.Time `json:"lastCheckIn"`
	LastCheckOut  *time.Time `json:"lastCheckOut"`

	// Created/Updated are the resource timestamps.
	Created time.Time `json:"created"`
	Updated time.Time `json:"updated"`

	// Metadata is free-form.
	Metadata Metadata `json:"metadata"`

	// PolicyID/ProductID/OwnerID come from the resource's relationships.
	PolicyID  string `json:"-"`
	ProductID string `json:"-"`
	OwnerID   string `json:"-"`

	// Validation is the result of the last Validate call on this value.
	Validation *ValidationResult `json:"-"`
	// contains filtered or unexported fields
}

License is a Keygen license. A License with a bound client (from Client.Validate, Client.Me, or a decoded dataset bound via Client.Bind) can act: validate, activate machines, check out files.

func (*License) Activate

func (l *License) Activate(
	ctx context.Context,
	fingerprint string,
	options ...ActivationOption,
) (*Machine, error)

Activate activates a machine for the license. The machine's hostname, platform, and core count default to the local system's.

func (*License) Checkout

func (l *License) Checkout(ctx context.Context, options ...CheckoutOption) (*LicenseFile, error)

Checkout checks out an encrypted license file for the license. With Config.PublicKey set the certificate is verified before it is returned. Decrypt the file with the license key.

func (*License) Deactivate

func (l *License) Deactivate(ctx context.Context, machineID string) error

Deactivate deactivates a machine by UUID or fingerprint.

func (*License) Entitlements

func (l *License) Entitlements(ctx context.Context) ([]Entitlement, error)

Entitlements lists up to 100 entitlements of the license.

func (*License) Machine

func (l *License) Machine(ctx context.Context, machineID string) (*Machine, error)

Machine fetches a machine of the license by UUID or fingerprint.

func (*License) Machines

func (l *License) Machines(ctx context.Context) ([]Machine, error)

Machines lists up to 100 machines of the license.

func (*License) Validate

func (l *License) Validate(ctx context.Context, options ...ValidationOption) error

Validate validates the license. See Client.Validate.

func (*License) VerifyKey

func (l *License) VerifyKey() ([]byte, error)

VerifyKey cryptographically verifies the license's signed key offline and returns the embedded dataset (JSON). It requires Config.PublicKey.

type LicenseFile

type LicenseFile struct {
	// ID is the license-file UUID.
	ID string `json:"-"`

	// Certificate is the PEM-like certificate block.
	Certificate string `json:"certificate"`

	// Algorithm is the certificate's encoding+signing algorithm, e.g.
	// aes-256-gcm+ed25519.
	Algorithm string `json:"algorithm"`

	// Includes lists the relationships embedded in the file.
	Includes []string `json:"includes"`

	// Issued/Expiry/TTL describe the file's validity window; Expiry is
	// null and TTL zero for perpetual files.
	Issued time.Time  `json:"issued"`
	Expiry *time.Time `json:"expiry"`
	TTL    int        `json:"ttl"`

	// LicenseID comes from the file's relationships.
	LicenseID string `json:"-"`
	// contains filtered or unexported fields
}

LicenseFile is a checked-out license file.

func ParseLicenseFile

func ParseLicenseFile(certificateBlock string) (*LicenseFile, error)

ParseLicenseFile parses a license file certificate block read from disk.

func (*LicenseFile) Decode

func (f *LicenseFile) Decode() (*LicenseFileDataset, error)

Decode decodes an unencrypted license file's dataset.

A file whose payload decodes but fails the time policy (past its expiry, or issued in the future beyond the clock skew) is answered WITH its dataset and the temporal refusal (ErrLicenseFileExpired or ErrClockOutOfSync), so a caller can still read an expired lease; every other failure (format, decryption, a wrong key or fingerprint) answers no dataset. Decoding does not verify the signature: call Verify first, and treat the dataset as authentic only when it passed.

func (*LicenseFile) Decrypt

func (f *LicenseFile) Decrypt(licenseKey string) (*LicenseFileDataset, error)

Decrypt decrypts and decodes the license file with the license key: the AES key is SHA256(license key). The time policy is Decode's.

func (*LicenseFile) Verify

func (f *LicenseFile) Verify(v Verifier) error

Verify checks the file's signature with the verifier's key.

type LicenseFileDataset

type LicenseFileDataset struct {
	// License is the licensed resource.
	License License `json:"-"`

	// Entitlements are the embedded entitlements.
	Entitlements []Entitlement `json:"-"`

	// Issued/Expiry/TTL describe the file's validity window.
	Issued time.Time  `json:"-"`
	Expiry *time.Time `json:"-"`
	TTL    int        `json:"-"`
}

LicenseFileDataset is the decrypted payload of a license file.

type Machine

type Machine struct {

	// ID is the machine UUID.
	ID string `json:"-"`

	// Name is the display name.
	Name string `json:"name"`

	// Fingerprint is the device fingerprint.
	Fingerprint string `json:"fingerprint"`

	// Hostname/Platform/IP describe the device.
	Hostname string `json:"hostname"`
	Platform string `json:"platform"`
	IP       string `json:"ip"`

	// Cores is the reported core count.
	Cores int `json:"cores"`

	// RequireHeartbeat reports that this machine must ping.
	RequireHeartbeat bool `json:"requireHeartbeat"`

	// HeartbeatStatus is NOT_STARTED, ALIVE, DEAD, or RESURRECTED.
	HeartbeatStatus HeartbeatStatus `json:"heartbeatStatus"`

	// HeartbeatDuration is the ping window in seconds.
	HeartbeatDuration int `json:"heartbeatDuration"`

	// LastHeartbeat/NextHeartbeat are the heartbeat timestamps.
	LastHeartbeat *time.Time `json:"lastHeartbeat"`
	NextHeartbeat *time.Time `json:"nextHeartbeat"`

	// LastCheckOut is the last machine-file checkout.
	LastCheckOut *time.Time `json:"lastCheckOut"`

	// Created/Updated are the resource timestamps.
	Created time.Time `json:"created"`
	Updated time.Time `json:"updated"`

	// Metadata is free-form.
	Metadata Metadata `json:"metadata"`

	// LicenseID comes from the machine's relationships.
	LicenseID string `json:"-"`
	// contains filtered or unexported fields
}

Machine is an activated machine of a license.

func (*Machine) Checkout

func (m *Machine) Checkout(ctx context.Context, options ...CheckoutOption) (*MachineFile, error)

Checkout checks out an encrypted machine file for the machine. Decrypt the file with the license key concatenated with the machine's fingerprint.

func (*Machine) Components

func (m *Machine) Components(ctx context.Context) ([]Component, error)

Components lists up to 100 components of the machine.

func (*Machine) Deactivate

func (m *Machine) Deactivate(ctx context.Context) error

Deactivate deactivates (deletes) the machine.

func (*Machine) Monitor

func (m *Machine) Monitor(ctx context.Context) error

Monitor keeps the machine's heartbeat alive: it pings immediately, then again roughly every heartbeat window (minus a safety margin, with jitter and retries) until ctx is done, at which point it returns nil. It returns the first unrecoverable ping error otherwise.

func (*Machine) Ping

func (m *Machine) Ping(ctx context.Context) error

Ping sends a heartbeat ping and refreshes the machine from the response. A dead machine is resurrected when the policy allows.

func (*Machine) Processes

func (m *Machine) Processes(ctx context.Context) ([]Process, error)

Processes lists up to 100 processes of the machine.

func (*Machine) ReportUsage added in v0.0.5

func (m *Machine) ReportUsage(ctx context.Context, report *usage.Report) (*usage.Acked, error)

ReportUsage sends a usage report for the machine. POST /v1/accounts/{account}/machines/{id}/actions/report-usage Body: {"meta": {"report": <Report>}}. Answer: {"meta": {"ack": {"epoch":..., "seq":..., "hash":"..."}}}.

func (*Machine) Spawn

func (m *Machine) Spawn(ctx context.Context, pid string) (*Process, error)

Spawn creates a process for the machine with the given pid. Use the returned Process's Monitor to keep it alive.

func (*Machine) UpdateMetadata added in v0.0.6

func (m *Machine) UpdateMetadata(ctx context.Context, patch Metadata) error

UpdateMetadata merges patch into the machine's metadata and refreshes the machine from the answer. The server replaces metadata whole, so the machine is read first (GET) and the merged map is sent (PATCH /v1/accounts/{account}/machines/{id}): keys of patch replace their values, a JSON null value removes the key, every other key (fingerprint, publicKey and the caller's own) is kept. Concurrent writers are last-write-wins over the whole map. Keys are camelCase on the wire (the server stores them snake_case and answers camelCase). Changing "fingerprint" or "publicKey" is ErrReservedMetadata.

func (*Machine) Usage added in v0.0.5

func (m *Machine) Usage(ctx context.Context, afterSeq uint64, limit int) (*usage.Response, error)

Usage fetches usage events for the machine. GET /v1/accounts/{account}/machines/{id}/usage?after=<seq>&limit=<n>.

type MachineFile

type MachineFile struct {
	// ID is the machine-file UUID.
	ID string `json:"-"`

	// Certificate is the PEM-like certificate block.
	Certificate string `json:"certificate"`

	// Algorithm is the certificate's encoding+signing algorithm.
	Algorithm string `json:"algorithm"`

	// Includes lists the relationships embedded in the file.
	Includes []string `json:"includes"`

	// Issued/Expiry/TTL describe the file's validity window.
	Issued time.Time  `json:"issued"`
	Expiry *time.Time `json:"expiry"`
	TTL    int        `json:"ttl"`

	// MachineID/LicenseID come from the file's relationships.
	MachineID string `json:"-"`
	LicenseID string `json:"-"`
	// contains filtered or unexported fields
}

MachineFile is a checked-out machine file.

func ParseMachineFile

func ParseMachineFile(certificateBlock string) (*MachineFile, error)

ParseMachineFile parses a machine file certificate block read from disk.

func (*MachineFile) Decode

func (f *MachineFile) Decode() (*MachineFileDataset, error)

Decode decodes an unencrypted machine file's dataset.

A file whose payload decodes but fails the time policy (past its expiry, or issued in the future beyond the clock skew) is answered WITH its dataset and the temporal refusal (ErrMachineFileExpired or ErrClockOutOfSync), so a caller can still read an expired lease; every other failure (format, decryption, a wrong key or fingerprint) answers no dataset. Decoding does not verify the signature: call Verify first, and treat the dataset as authentic only when it passed.

func (*MachineFile) Decrypt

func (f *MachineFile) Decrypt(licenseKey, fingerprint string) (*MachineFileDataset, error)

Decrypt decrypts and decodes the machine file: the AES key is SHA256(license key + fingerprint). The time policy is Decode's.

func (*MachineFile) Verify

func (f *MachineFile) Verify(v Verifier) error

Verify checks the file's signature with the verifier's key.

type MachineFileDataset

type MachineFileDataset struct {
	// Machine is the machine resource.
	Machine Machine `json:"-"`

	// License is the licensed resource.
	License License `json:"-"`

	// Entitlements/Components are the embedded relationships.
	Entitlements []Entitlement `json:"-"`
	Components   []Component   `json:"-"`

	// Issued/Expiry/TTL describe the file's validity window.
	Issued time.Time  `json:"-"`
	Expiry *time.Time `json:"-"`
	TTL    int        `json:"-"`
}

MachineFileDataset is the decrypted payload of a machine file.

type Metadata

type Metadata map[string]json.RawMessage

Metadata is a resource's free-form metadata. Values are raw JSON so nested structures survive a round trip; use String for the common scalar case.

func (Metadata) String

func (m Metadata) String(key string) (string, bool)

String returns a metadata value as a string, reporting whether the value exists and is a string.

type Process

type Process struct {

	// ID is the process UUID.
	ID string `json:"-"`

	// Pid is the caller-supplied process identifier.
	Pid string `json:"pid"`

	// Status is ALIVE or DEAD (RESURRECTED in a resurrecting ping's
	// response).
	Status ProcessStatus `json:"status"`

	// Interval is the required ping interval in seconds.
	Interval int `json:"interval"`

	// LastHeartbeat/NextHeartbeat are the heartbeat timestamps.
	LastHeartbeat *time.Time `json:"lastHeartbeat"`
	NextHeartbeat *time.Time `json:"nextHeartbeat"`

	// Created/Updated are the resource timestamps.
	Created time.Time `json:"created"`
	Updated time.Time `json:"updated"`

	// Metadata is free-form.
	Metadata Metadata `json:"metadata"`

	// MachineID comes from the process's relationships.
	MachineID string `json:"-"`
	// contains filtered or unexported fields
}

Process is a process of a machine, kept alive by heartbeat pings.

func (*Process) Kill

func (p *Process) Kill(ctx context.Context) error

Kill deletes the process.

func (*Process) Monitor

func (p *Process) Monitor(ctx context.Context) error

Monitor keeps the process's heartbeat alive, like Machine.Monitor but at the process's own interval.

func (*Process) Ping

func (p *Process) Ping(ctx context.Context) error

Ping sends a heartbeat ping and refreshes the process from the response.

type ProcessStatus

type ProcessStatus string

ProcessStatus is a process's heartbeat lifecycle state.

const (
	ProcessAlive       ProcessStatus = "ALIVE"
	ProcessDead        ProcessStatus = "DEAD"
	ProcessResurrected ProcessStatus = "RESURRECTED"
)

Process statuses.

type RateLimitError

type RateLimitError struct {
	// Window is the active throttle window, e.g. "1m".
	Window string

	// Count is the requests made in the window.
	Count int

	// Limit is the requests allowed in the window.
	Limit int

	// Remaining is the requests left in the window.
	Remaining int

	// Reset is when the window ends.
	Reset time.Time

	// RetryAfter is the seconds until the window ends.
	RetryAfter int
}

RateLimitError is a 429 response. It carries the throttling state from the X-RateLimit-* and Retry-After headers.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type Scheme

type Scheme string

Scheme is a license key signing scheme.

const (
	// SchemeEd25519 signs keys with the account's ed25519 key.
	SchemeEd25519 Scheme = "ED25519_SIGN"
	// SchemeECDSAP256 signs keys with the account's ECDSA P-256 key.
	SchemeECDSAP256 Scheme = "ECDSA_P256_SIGN"
	// SchemeRSAPKCS1 signs keys with RSA PKCS#1 v1.5 over the raw seed
	// (v1 format, no key/ prefix).
	SchemeRSAPKCS1 Scheme = "RSA_2048_PKCS1_SIGN"
	// SchemeRSAPKCS1V2 signs keys with RSA PKCS#1 v1.5 over key/<seed>.
	SchemeRSAPKCS1V2 Scheme = "RSA_2048_PKCS1_SIGN_V2"
	// SchemeRSAPSS signs keys with RSA-PSS over the raw seed (v1 format).
	SchemeRSAPSS Scheme = "RSA_2048_PKCS1_PSS_SIGN"
	// SchemeRSAPSSV2 signs keys with RSA-PSS over key/<seed>.
	SchemeRSAPSSV2 Scheme = "RSA_2048_PKCS1_PSS_SIGN_V2"
)

The license key schemes the client can verify.

type SkewGuard

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

SkewGuard decides whether a timestamp is close enough to now. The zero value accepts everything.

func SkewGuardFor

func SkewGuardFor(skew time.Duration) SkewGuard

newSkewGuard builds a guard tolerating skew; non-positive skew disables the check.

func (SkewGuard) Within

func (g SkewGuard) Within(t time.Time) bool

Within reports whether t is not older than skew (future dates always pass, matching Keygen clients).

type ValidationCode

type ValidationCode string

ValidationCode is a license validation code.

const (
	CodeValid                    ValidationCode = "VALID"
	CodeNotFound                 ValidationCode = "NOT_FOUND"
	CodeBanned                   ValidationCode = "BANNED"
	CodeSuspended                ValidationCode = "SUSPENDED"
	CodeExpired                  ValidationCode = "EXPIRED"
	CodeOverdue                  ValidationCode = "OVERDUE"
	CodeNoMachine                ValidationCode = "NO_MACHINE"
	CodeNoMachines               ValidationCode = "NO_MACHINES"
	CodeTooManyMachines          ValidationCode = "TOO_MANY_MACHINES"
	CodeTooManyCores             ValidationCode = "TOO_MANY_CORES"
	CodeTooManyProcesses         ValidationCode = "TOO_MANY_PROCESSES"
	CodeFingerprintScopeMismatch ValidationCode = "FINGERPRINT_SCOPE_MISMATCH"
	CodeFingerprintScopeRequired ValidationCode = "FINGERPRINT_SCOPE_REQUIRED"
	CodeFingerprintScopeEmpty    ValidationCode = "FINGERPRINT_SCOPE_EMPTY"
	CodeComponentsScopeMismatch  ValidationCode = "COMPONENTS_SCOPE_MISMATCH"
	CodeComponentsScopeRequired  ValidationCode = "COMPONENTS_SCOPE_REQUIRED"
	CodeComponentsScopeEmpty     ValidationCode = "COMPONENTS_SCOPE_EMPTY"
	CodeHeartbeatNotStarted      ValidationCode = "HEARTBEAT_NOT_STARTED"
	CodeHeartbeatDead            ValidationCode = "HEARTBEAT_DEAD"
	CodeProductScopeMismatch     ValidationCode = "PRODUCT_SCOPE_MISMATCH"
	CodeProductScopeRequired     ValidationCode = "PRODUCT_SCOPE_REQUIRED"
	CodePolicyScopeMismatch      ValidationCode = "POLICY_SCOPE_MISMATCH"
	CodePolicyScopeRequired      ValidationCode = "POLICY_SCOPE_REQUIRED"
	CodeMachineScopeMismatch     ValidationCode = "MACHINE_SCOPE_MISMATCH"
	CodeMachineScopeRequired     ValidationCode = "MACHINE_SCOPE_REQUIRED"
	CodeUserScopeMismatch        ValidationCode = "USER_SCOPE_MISMATCH"
	CodeUserScopeRequired        ValidationCode = "USER_SCOPE_REQUIRED"
	CodeEntitlementsMissing      ValidationCode = "ENTITLEMENTS_MISSING"
	CodeEntitlementsEmpty        ValidationCode = "ENTITLEMENTS_SCOPE_EMPTY"
)

Validation codes. Codes without a dedicated sentinel error map to ErrLicenseInvalid.

type ValidationOption

type ValidationOption func(*ValidationOptions)

ValidationOption configures a license validation scope.

func WithComponents

func WithComponents(fingerprints ...string) ValidationOption

WithComponents scopes the validation to component fingerprints; it requires WithFingerprint.

func WithFingerprint

func WithFingerprint(fingerprint string) ValidationOption

WithFingerprint scopes the validation to a machine fingerprint.

type ValidationOptions

type ValidationOptions struct {
	Fingerprint string
	Components  []string
}

ValidationOptions is the validation scope under construction.

type ValidationResult

type ValidationResult struct {
	// Code is the machine-readable outcome.
	Code ValidationCode `json:"code"`

	// Detail is the human-readable outcome.
	Detail string `json:"detail"`

	// Valid is the server's verdict; it can be true alongside a
	// soft-fail code (e.g. EXPIRED under MAINTAIN_ACCESS).
	Valid bool `json:"valid"`

	// TS is when the server processed the validation.
	TS time.Time `json:"ts"`

	// Scope echoes the validated scope when one was sent.
	Scope *validateScope `json:"scope,omitempty"`
}

ValidationResult is the meta object of a validation response.

func (*ValidationResult) Err

func (r *ValidationResult) Err() error

Err returns the sentinel error for the result's code, or nil for VALID.

type Verifier

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

Verifier verifies Keygen signatures: API responses, webhooks, license and machine files, and cryptographically signed license keys. It is immutable after construction; the zero value refuses everything with ErrPublicKeyMissing.

func NewVerifier

func NewVerifier(publicKey string) (Verifier, error)

NewVerifier parses a public key: a 64-character hex ed25519 key (the form Keygen accounts expose), or a PEM-encoded RSA or ECDSA public key.

func (Verifier) VerifyLicenseKey

func (v Verifier) VerifyLicenseKey(scheme Scheme, key string) ([]byte, error)

VerifyLicenseKey verifies a cryptographically signed license key and returns its embedded dataset (the JSON the key was signed over). Supported schemes: ED25519_SIGN, ECDSA_P256_SIGN, and the RSA RSA_2048_PKCS1[PSS]_SIGN[_V2] variants.

func (Verifier) VerifyResponse

func (v Verifier) VerifyResponse(request *http.Request, header http.Header, body []byte, skew SkewGuard) error

VerifyResponse checks the Keygen-Signature headers of an API response against its body. It verifies the Digest header against the body, the Date header against skew, and the signature over the HTTP signing string "(request-target) host date digest". request is the request the response answers (its method, URI, and Host header define the signed request-target).

func (Verifier) VerifyWebhook

func (v Verifier) VerifyWebhook(request *http.Request, skew SkewGuard) error

VerifyWebhook checks the Keygen-Signature headers of an incoming webhook request. The event must be considered untrusted when it returns an error. The request body is replaced with an equivalent reader after inspection.

Directories

Path Synopsis
Package installation manages license-bound installation keys and
Package installation manages license-bound installation keys and
internal
jsonapi
Package jsonapi is the licensing client's private JSON:API transport: the document envelope, request encoding, and response decoding into the client's typed structs.
Package jsonapi is the licensing client's private JSON:API transport: the document envelope, request encoding, and response decoding into the client's typed structs.
Package lictest runs a real backplane-lic server inside a test's process, for integration tests of what uses the licensing API: the server's own HTTP handler on a loopback port, over a PostgreSQL the caller provides (migrated on start), in an account of its own, so tests share one database and run in parallel.
Package lictest runs a real backplane-lic server inside a test's process, for integration tests of what uses the licensing API: the server's own HTTP handler on a loopback port, over a PostgreSQL the caller provides (migrated on start), in an account of its own, so tests share one database and run in parallel.
Package request signs and verifies HTTP requests with RFC 9421 HTTP Message Signatures (Ed25519).
Package request signs and verifies HTTP requests with RFC 9421 HTTP Message Signatures (Ed25519).
Package usage implements a signed hash chain for usage journals.
Package usage implements a signed hash chain for usage journals.

Jump to

Keyboard shortcuts

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