keygen

package module
v1.0.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2021 License: MIT Imports: 16 Imported by: 0

README

Keygen Go SDK

Package keygen allows Go programs to license and remotely update themselves with the keygen.sh service.

License activation example

import "github.com/keygen-sh/sdk"

keygen.Account = os.Getenv("KEYGEN_ACCOUNT")
keygen.Product = os.Getenv("KEYGEN_PRODUCT")
keygen.Token = os.Getenv("KEYGEN_TOKEN")

func activate() error {
  fingerprint := uuid.New().String()

  // Validate the license for the current fingerprint
  license, err := keygen.Validate(fingerprint)
  switch {
  case err == ErrLicenseNotActivated:
    // Activate the current fingerprint
    machine, err := license.Activate(fingerprint)
    switch {
    case err != ErrMachineLimitExceeded:
      fmt.Println("Machine limit has been exceeded!")

      return err
    case err != nil:
      fmt.Println("Machine activaiton failed!")

      return err
    }
  }
  case err == ErrLicenseInvalid:
    fmt.Println("License is not valid!")

    return err
  case err == ErrLicenseExpired:
    fmt.Println("License is expired!")

    return err
  case err != nil:
    fmt.Println("License is invalid!")

    return err
}

Automatic upgrade example

import "github.com/keygen-sh/sdk"

keygen.Account = os.Getenv("KEYGEN_ACCOUNT")
keygen.Product = os.Getenv("KEYGEN_PRODUCT")
keygen.Token = os.Getenv("KEYGEN_TOKEN")

func upgrade() error {
  // Check for upgrade
  release, err := keygen.Upgrade("1.0.0")
  switch {
  case err == ErrUpgradeNotAvailable:
     fmt.Println("No upgrade available, already at the latest version!")

     return nil
  case err != nil:
    fmt.Println("Upgrade check failed!")

    return err
  }

  // Download the upgrade and apply it
  err = release.Apply()
  if err != nil {
      return err
  }
}

Documentation

Index

Constants

View Source
const (
	APIURL     = "https://api.keygen.sh"
	APIVersion = "v1"
)
View Source
const (
	// Filetype is the release filetype used when checking for upgrades.
	Filetype = "binary"
)
View Source
const (
	// Platform is the release platform used when checking for upgrades
	// and when activating machines.
	Platform = runtime.GOOS + "_" + runtime.GOARCH
)
View Source
const (
	SchemeCodeEd25519 = "ED25519_SIGN"
)

Variables

View Source
var (
	ErrLicenseTokenInvalid     = errors.New("authentication token is invalid")
	ErrMachineAlreadyActivated = errors.New("machine is already activated")
	ErrMachineLimitExceeded    = errors.New("machine limit has been exceeded")
	ErrMachineDead             = errors.New("machine does not exist")
	ErrNotFound                = errors.New("resource does not exist")
)
View Source
var (
	// Account is the Keygen account ID used globally in the binding.
	Account string

	// Product is the Keygen product ID used globally in the binding.
	Product string

	// Token is the Keygen API token used globally in the binding.
	Token string

	// PublicKey is the Keygen public key used for verifying license keys
	// and API response signatures.
	PublicKey string

	// Channel is the release channel used when checking for upgrades.
	Channel = "stable"
)
View Source
var (
	ErrLicenseNotActivated    = errors.New("license is not activated")
	ErrLicenseExpired         = errors.New("license is expired")
	ErrLicenseSuspended       = errors.New("license is suspended")
	ErrLicenseTooManyMachines = errors.New("license has too many machines")
	ErrLicenseTooManyCores    = errors.New("license has too many cores")
	ErrLicenseNotSigned       = errors.New("license is not signed")
	ErrLicenseInvalid         = errors.New("license is invalid")
	ErrFingerprintMissing     = errors.New("fingerprint scope is missing")
	ErrProductMissing         = errors.New("product scope is missing")
)
View Source
var (
	ErrLicenseSchemeNotSupported = errors.New("license scheme is not supported")
	ErrLicenseSchemeMissing      = errors.New("license scheme is missing")
	ErrLicenseKeyMissing         = errors.New("license key is missing")
	ErrLicenseNotGenuine         = errors.New("license key is not genuine")
	ErrPublicKeyMissing          = errors.New("public key is missing")
	ErrPublicKeyInvalid          = errors.New("public key is invalid")
)
View Source
var (
	ErrReleaseLocationMissing = errors.New("release has no download URL")
)
View Source
var (
	ErrUpgradeNotAvailable = errors.New("no upgrades available (already up-to-date)")
)

Functions

func Genuine

func Genuine(licenseKey string, signingScheme string) ([]byte, error)

Genuine checks if a license key is genuine by cryptographically verifying the key using your PublicKey. If the key is genuine, the decoded dataset from the key will be returned. An error will be returned if the key is not genuine or otherwise invalid, e.g. ErrLicenseNotGenuine.

Types

type Artifact

type Artifact struct {
	ID        string    `json:"-"`
	Type      string    `json:"-"`
	Key       string    `json:"key"`
	Created   time.Time `json:"created"`
	Updated   time.Time `json:"updated"`
	ReleaseId string    `json:"-"`
}

Artifact represents an Keygen artifact object.

func (*Artifact) SetData

func (a *Artifact) SetData(to func(target interface{}) error) error

func (*Artifact) SetID

func (a *Artifact) SetID(id string) error

Implement jsonapi.UnmarshalData interface

func (*Artifact) SetRelationships

func (a *Artifact) SetRelationships(relationships map[string]interface{}) error

func (*Artifact) SetType

func (a *Artifact) SetType(t string) error

type Client

type Client struct {
	Account string
	Token   string
}

func (*Client) Delete

func (c *Client) Delete(path string, params interface{}, model interface{}) (*Response, error)

func (*Client) Get

func (c *Client) Get(path string, params interface{}, model interface{}) (*Response, error)

func (*Client) Patch

func (c *Client) Patch(path string, params interface{}, model interface{}) (*Response, error)

func (*Client) Post

func (c *Client) Post(path string, params interface{}, model interface{}) (*Response, error)

func (*Client) Put

func (c *Client) Put(path string, params interface{}, model interface{}) (*Response, error)

type Entitlement

type Entitlement struct {
	ID       string                 `json:"-"`
	Type     string                 `json:"-"`
	Code     string                 `json:"code"`
	Created  time.Time              `json:"created"`
	Updated  time.Time              `json:"updated"`
	Metadata map[string]interface{} `json:"metadata"`
}

Entitlement represents an Keygen entitlement object.

func (*Entitlement) SetData

func (e *Entitlement) SetData(to func(target interface{}) error) error

func (*Entitlement) SetID

func (e *Entitlement) SetID(id string) error

Implement jsonapi.UnmarshalData interface

func (*Entitlement) SetType

func (e *Entitlement) SetType(t string) error

type Entitlements

type Entitlements []Entitlement

Entitlements represents an array of entitlement objects.

func (*Entitlements) SetData

func (e *Entitlements) SetData(to func(target interface{}) error) error

Implement jsonapi.UnmarshalData interface

type ErrorCode

type ErrorCode string
const (
	ErrorCodeTokenInvalid         ErrorCode = "TOKEN_INVALID"
	ErrorCodeFingerprintTaken     ErrorCode = "FINGERPRINT_TAKEN"
	ErrorCodeMachineLimitExceeded ErrorCode = "MACHINE_LIMIT_EXCEEDED"
	ErrorCodeMachineDead          ErrorCode = "MACHINE_DEAD"
	ErrorCodeNotFound             ErrorCode = "NOT_FOUND"
)

type License

type License struct {
	ID            string                 `json:"-"`
	Type          string                 `json:"-"`
	Name          string                 `json:"name"`
	Key           string                 `json:"key"`
	Expiry        *time.Time             `json:"expiry"`
	Scheme        string                 `json:"scheme"`
	LastValidated *time.Time             `json:"lastValidated"`
	Created       time.Time              `json:"created"`
	Updated       time.Time              `json:"updated"`
	Metadata      map[string]interface{} `json:"metadata"`
	PolicyId      string                 `json:"-"`
}

License represents an Keygen license object.

func Validate

func Validate(fingerprints ...string) (*License, error)

Validate performs a license validation using the current Token, scoped to any provided fingerprints. It returns a License, and an error if the license is invalid, e.g. ErrLicenseNotActivated or ErrLicenseExpired.

func (*License) Activate

func (l *License) Activate(fingerprint string) (*Machine, error)

Activate performs a machine activation for the license, identified by the provided fingerprint. If the activation is successful, the new machine will be returned. An error will be returned if the activation fails, e.g. ErrMachineLimitExceeded or ErrMachineAlreadyActivated.

func (*License) Deactivate

func (l *License) Deactivate(id string) error

Deactivate performs a machine deactivation, identified by the provided ID. The ID can be the machine's UUID or the machine's fingerprint. An error will be returned if the machine deactivation fails.

func (*License) Entitlements

func (l *License) Entitlements() (Entitlements, error)

Machines lists up to 100 entitlements for the license.

func (*License) Genuine

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

Genuine checks if the license's key is genuine by cryptographically verifying the key using your PublicKey. If the license is genuine, the decoded dataset from the key will be returned. An error will be returned if the license is not genuine, or if the key is not signed, e.g. ErrLicenseNotGenuine or ErrLicenseNotSigned.

func (*License) Machines

func (l *License) Machines() (Machines, error)

Machines lists up to 100 machines for the license.

func (*License) SetData

func (l *License) SetData(to func(target interface{}) error) error

func (*License) SetID

func (l *License) SetID(id string) error

Implement jsonapi.UnmarshalData interface

func (*License) SetRelationships

func (l *License) SetRelationships(relationships map[string]interface{}) error

func (*License) SetType

func (l *License) SetType(t string) error

func (*License) Validate

func (l *License) Validate(fingerprints ...string) error

Validate performs a license validation, scoped to any provided fingerprints. It returns an error if the license is invalid, e.g. ErrLicenseNotActivated, ErrLicenseExpired or ErrLicenseTooManyMachines.

type Machine

type Machine struct {
	ID                string                 `json:"-"`
	Type              string                 `json:"-"`
	Name              string                 `json:"name"`
	Fingerprint       string                 `json:"fingerprint"`
	Hostname          string                 `json:"hostname"`
	Platform          string                 `json:"platform"`
	Cores             int                    `json:"cores"`
	HeartbeatStatus   string                 `json:"heartbeatStatus"`
	HeartbeatDuration int                    `json:"heartbeatDuration"`
	Created           time.Time              `json:"created"`
	Updated           time.Time              `json:"updated"`
	Metadata          map[string]interface{} `json:"metadata"`
	LicenseID         string                 `json:"-"`
}

Machine represents an Keygen machine object.

func (*Machine) Deactivate

func (m *Machine) Deactivate() error

Deactivate performs a machine deactivation for the current Machine. An error will be returned if the machine deactivation fails.

func (Machine) GetData

func (m Machine) GetData() interface{}

func (Machine) GetID

func (m Machine) GetID() string

Implement jsonapi.MarshalData interface

func (Machine) GetType

func (m Machine) GetType() string

func (*Machine) Monitor

func (m *Machine) Monitor() chan error

Monitor performs, on a loop, a machine hearbeat ping for the current Machine. An error channel will be returned, where any ping errors will be emitted. Pings are sent according to the machine's required heartbeat window.

func (*Machine) SetData

func (m *Machine) SetData(to func(target interface{}) error) error

func (*Machine) SetID

func (m *Machine) SetID(id string) error

Implement jsonapi.UnmarshalData interface

func (*Machine) SetType

func (m *Machine) SetType(t string) error

type Machines

type Machines []Machine

Machines represents an array of machine objects.

func (*Machines) SetData

func (m *Machines) SetData(to func(target interface{}) error) error

Implement jsonapi.UnmarshalData interface

type Release

type Release struct {
	ID       string                 `json:"-"`
	Type     string                 `json:"-"`
	Version  string                 `json:"version"`
	Filename string                 `json:"filename"`
	Filetype string                 `json:"filetype"`
	Filesize string                 `json:"filesize"`
	Platform string                 `json:"platform"`
	Channel  string                 `json:"channel"`
	Created  time.Time              `json:"created"`
	Updated  time.Time              `json:"updated"`
	Metadata map[string]interface{} `json:"metadata"`
	Location string                 `json:"-"`
}

Release represents an Keygen release object.

func Upgrade

func Upgrade(currentVersion string) (*Release, error)

func (*Release) Install

func (r *Release) Install() error

Install performs an update of the current executable to the new Release.

func (*Release) SetData

func (r *Release) SetData(to func(target interface{}) error) error

func (*Release) SetID

func (r *Release) SetID(id string) error

Implement jsonapi.UnmarshalData interface

func (*Release) SetType

func (r *Release) SetType(t string) error

type Response

type Response struct {
	Headers  http.Header
	Document *jsonapi.Document
	Body     []byte
	Status   int
}

type ValidationCode

type ValidationCode string
const (
	ValidationCodeValid                    ValidationCode = "VALID"
	ValidationCodeNotFound                 ValidationCode = "NOT_FOUND"
	ValidationCodeSuspended                ValidationCode = "SUSPENDED"
	ValidationCodeExpired                  ValidationCode = "EXPIRED"
	ValidationCodeOverdue                  ValidationCode = "OVERDUE"
	ValidationCodeNoMachine                ValidationCode = "NO_MACHINE"
	ValidationCodeNoMachines               ValidationCode = "NO_MACHINES"
	ValidationCodeTooManyMachines          ValidationCode = "TOO_MANY_MACHINES"
	ValidationCodeTooManyCores             ValidationCode = "TOO_MANY_CORES"
	ValidationCodeFingerprintScopeRequired ValidationCode = "FINGERPRINT_SCOPE_REQUIRED"
	ValidationCodeFingerprintScopeMismatch ValidationCode = "FINGERPRINT_SCOPE_MISMATCH"
	ValidationCodeFingerprintScopeEmpty    ValidationCode = "FINGERPRINT_SCOPE_EMPTY"
	ValidationCodeProductScopeRequired     ValidationCode = "PRODUCT_SCOPE_REQUIRED"
	ValidationCodeProductScopeEmpty        ValidationCode = "PRODUCT_SCOPE_MISMATCH"
	ValidationCodePolicyScopeRequired      ValidationCode = "POLICY_SCOPE_REQUIRED"
	ValidationCodePolicyScopeMismatch      ValidationCode = "POLICY_SCOPE_MISMATCH"
	ValidationCodeMachineScopeRequired     ValidationCode = "MACHINE_SCOPE_REQUIRED"
	ValidationCodeMachineScopeMismatch     ValidationCode = "MACHINE_SCOPE_MISMATCH"
	ValidationCodeEntitlementsMissing      ValidationCode = "ENTITLEMENTS_MISSING"
	ValidationCodeEntitlementsEmpty        ValidationCode = "ENTITLEMENTS_SCOPE_EMPTY"
)

Jump to

Keyboard shortcuts

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