liblicense

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package liblicense provides cryptographically signed and encrypted software license generation, issuance, and verification with arbitrary Key-Value (KV) payloads. It is built on top of libcipher (Ed25519 signatures, AES-256-GCM authenticated encryption) and uses standard SSH key pairs (with or without passphrases) as the root of trust / seed.

Index

Constants

View Source
const (
	// DefaultKDFInfo is the HKDF domain separation tag for payload encryption keys.
	DefaultKDFInfo = "contenox/liblicense/payload-encryption/v1"

	// EncryptionKeySize is the default AES-256 key size in bytes.
	EncryptionKeySize = 32
)
View Source
const (
	// TokenPrefix is the prefix for compact license tokens.
	TokenPrefix = "CLIC1"

	// CurrentTokenVersion is the current format version.
	CurrentTokenVersion = 1

	// DefaultAlgorithm is the cryptographic suite name.
	DefaultAlgorithm = "ED25519-AES256GCM"

	// ArmorHeader is the header line for PEM/armored license blocks.
	ArmorHeader = "-----BEGIN CONTENOX LICENSE-----"

	// ArmorFooter is the footer line for PEM/armored license blocks.
	ArmorFooter = "-----END CONTENOX LICENSE-----"
)
View Source
const DefaultInputAllowanceMultiplier = int64(5)

DefaultInputAllowanceMultiplier is the input cap applied when a plan states no multiplier: five times the model's output allowance.

Variables

View Source
var (
	// ErrInvalidToken is returned when a license token string is malformed or unparseable.
	ErrInvalidToken = errors.New("liblicense: invalid license token format")

	// ErrInvalidSignature is returned when a license's signature verification fails.
	ErrInvalidSignature = errors.New("liblicense: invalid license signature")

	// ErrLicenseExpired is returned when a license is past its expiration time.
	ErrLicenseExpired = errors.New("liblicense: license has expired")

	// ErrLicenseNotYetValid is returned when a license's NotBefore timestamp is in the future.
	ErrLicenseNotYetValid = errors.New("liblicense: license is not valid yet")

	// ErrPassphraseRequired is returned when an encrypted SSH private key is provided without a passphrase.
	ErrPassphraseRequired = errors.New("liblicense: ssh private key is encrypted; passphrase required")

	// ErrInvalidPassphrase is returned when an incorrect passphrase is supplied for an encrypted SSH private key.
	ErrInvalidPassphrase = errors.New("liblicense: incorrect passphrase for ssh private key")

	// ErrUnsupportedKeyType is returned when the key is not an Ed25519 key.
	ErrUnsupportedKeyType = errors.New("liblicense: unsupported key type; ed25519 is required")

	// ErrBadPublicKey is returned when a public key is invalid or malformed.
	ErrBadPublicKey = errors.New("liblicense: invalid public key")

	// ErrBadPrivateKey is returned when a private key is invalid or malformed.
	ErrBadPrivateKey = errors.New("liblicense: invalid private key")

	// ErrEmptyClaims is returned when attempting to issue a license with no ID or empty claims.
	ErrEmptyClaims = errors.New("liblicense: claims cannot be empty")

	// ErrDecryptionFailed is returned when the ciphertext cannot be decrypted.
	ErrDecryptionFailed = errors.New("liblicense: failed to decrypt license payload")

	// ErrMissingDecryptionKey is returned when verifying a license without an available decryption key.
	ErrMissingDecryptionKey = errors.New("liblicense: decryption key not provided")

	// ErrNoPinnedAuthorityKey is returned when attempting to use the pinned verifier without a configured authority public key.
	ErrNoPinnedAuthorityKey = errors.New("liblicense: no pinned authority public key configured")

	// ErrNoPinnedPayloadKey is returned when attempting to use the pinned
	// verifier without a configured payload decryption key.
	ErrNoPinnedPayloadKey = errors.New("liblicense: no pinned payload key configured")
)

Package-level error definitions for liblicense.

View Source
var PinnedAuthorityPublicKey string

PinnedAuthorityPublicKey is the official Contenox licensing authority Ed25519 public key. It is empty in the OSS source tree and is injected at compile-time via -ldflags during official release builds.

View Source
var PinnedPayloadKey string

PinnedPayloadKey is the 32-byte payload encryption key every license the relay mints is AES-256-GCM encrypted with. Empty in the OSS source tree and injected at compile-time via -ldflags alongside PinnedAuthorityPublicKey in official release builds: a client that cannot decrypt the license it received at checkin cannot build the model provider its claims describe.

Functions

func ArmorToken

func ArmorToken(token string) string

ArmorToken wraps a compact token in human-readable PEM-like armor lines.

func AudioAllowanceFor

func AudioAllowanceFor(cl *Claims, model string) int64

AudioAllowanceFor reads a model's weekly audio ceiling in mebibytes. Zero means the claim states no audio limit.

func AudioAllowanceKey

func AudioAllowanceKey(model string) string

AudioAllowanceKey is the canonical claim key for a model's weekly ceiling on inline audio, in mebibytes: the wire carries audio as bytes and no duration, so a mebibyte is the largest unit that can be counted exactly.

func CacheDiscountMultiplierFor

func CacheDiscountMultiplierFor(cl *Claims, model string) float64

CacheDiscountMultiplierFor reads a model's prompt cache discount as a fraction. A claim stating none gets the 0.10 default.

func CacheDiscountMultiplierKey

func CacheDiscountMultiplierKey(model string) string

CacheDiscountMultiplierKey is the canonical claim key for a model's prompt cache discount multiplier in basis points (500 = 0.05).

func DearmorToken

func DearmorToken(armored string) (string, error)

DearmorToken extracts the compact token string from an armored block.

func DeriveKey

func DeriveKey(secret []byte, salt []byte, info string) ([]byte, error)

DeriveKey derives a 32-byte symmetric AES-256 key from a seed or secret using HKDF-SHA256.

func EncodeToken

func EncodeToken(h Header, ciphertext []byte, signature []byte) (string, error)

EncodeToken serializes the header, ciphertext, and signature into a compact token string.

func FiveHourAllowanceFor

func FiveHourAllowanceFor(cl *Claims, model string) int64

FiveHourAllowanceFor reads a model's rolling five-hour token limit. Zero means the claim states no burst limit.

func FiveHourAllowanceKey

func FiveHourAllowanceKey(model string) string

FiveHourAllowanceKey is the canonical claim key for a model's rolling five-hour token ceiling.

func GenerateSSHKeyPair

func GenerateSSHKeyPair(comment string, passphrase []byte) (privPEM []byte, pubSSH []byte, err error)

GenerateSSHKeyPair generates a new Ed25519 SSH keypair, returning the private key PEM (optionally encrypted if passphrase is provided) and the OpenSSH public key line.

func ImageAllowanceFor

func ImageAllowanceFor(cl *Claims, model string) int64

ImageAllowanceFor reads a model's weekly image ceiling. Zero means the claim states no image limit.

func ImageAllowanceKey

func ImageAllowanceKey(model string) string

ImageAllowanceKey is the canonical claim key for a model's weekly ceiling on image input, counted in image attachments rather than tokens: an image's token cost is the provider's business, but how many were sent is ours to count.

func InputAllowanceFor

func InputAllowanceFor(cl *Claims, model string) int64

InputAllowanceFor reads a model's weekly input cap. Zero means the claim states no input limit, as a licence minted before the split does not.

func InputAllowanceKey

func InputAllowanceKey(model string) string

InputAllowanceKey is the canonical claim key for a model's weekly input cap.

func LegacyAllowanceFor

func LegacyAllowanceFor(cl *Claims, model string) int64

LegacyAllowanceFor reads the pre-split total allowance under either spelling the issuer has used: "token_allowance:<model>", and the folded form that replaces "/" and "-" with "_".

func MonthlyBudgetUSDFor

func MonthlyBudgetUSDFor(cl *Claims, model string) float64

MonthlyBudgetUSDFor reads a model's monthly spend ceiling in USD. Zero means the claim states no budget.

func MonthlyBudgetUSDKey

func MonthlyBudgetUSDKey(model string) string

MonthlyBudgetUSDKey is the canonical claim key for a model's monthly spend ceiling, in microdollars.

func OutputAllowanceFor

func OutputAllowanceFor(cl *Claims, model string) int64

OutputAllowanceFor reads a model's weekly output allowance. A licence minted before output and input were split carries only the legacy total allowance, which is honoured as the output allowance for as long as such a token is live. Zero means the claim states no output limit for the model.

func OutputAllowanceKey

func OutputAllowanceKey(model string) string

OutputAllowanceKey is the canonical claim key for a model's weekly output allowance.

func ParseAuthorityPublicKey

func ParseAuthorityPublicKey(s string) (libcipher.SigningPublicKey, error)

ParseAuthorityPublicKey parses an authority public key from OpenSSH wire format, PEM block, or base64 raw bytes.

func ParseSSHPrivateKey

func ParseSSHPrivateKey(pemBytes []byte, passphrase []byte) (libcipher.SigningPrivateKey, error)

ParseSSHPrivateKey parses an OpenSSH or PEM-encoded private key, decrypting with passphrase if provided. Returns an Ed25519 private key compatible with libcipher.

func ParseSSHPublicKey

func ParseSSHPublicKey(pubKeyBytes []byte) (libcipher.SigningPublicKey, error)

ParseSSHPublicKey parses an OpenSSH authorized_keys line or PEM/base64 public key. Returns an Ed25519 public key compatible with libcipher.

func QuickIssue

func QuickIssue(privPEM []byte, passphrase []byte, claims Claims) (string, error)

QuickIssue issues an encrypted and signed license token from an SSH private key PEM.

func SigningMessage

func SigningMessage(headerB64, cipherB64 string) []byte

SigningMessage constructs the canonical byte slice to be signed for given header and ciphertext base64 strings.

func ThinkingDiscountMultiplierFor

func ThinkingDiscountMultiplierFor(cl *Claims, model string) float64

ThinkingDiscountMultiplierFor reads the allowance share of a thinking token. An absent or invalid claim charges the whole token.

func ThinkingDiscountMultiplierKey

func ThinkingDiscountMultiplierKey(model string) string

ThinkingDiscountMultiplierKey is the canonical claim key for the share of a model's thinking tokens that consumes its output and burst allowances.

Types

type Claims

type Claims struct {
	// ID is the unique identifier for this license.
	ID string `json:"id"`

	// Issuer identifies who issued the license.
	Issuer string `json:"iss,omitempty"`

	// Subject identifies the licensee / user / customer / tenant.
	Subject string `json:"sub,omitempty"`

	// IssuedAt is the UTC timestamp when the license was created.
	IssuedAt time.Time `json:"iat"`

	// NotBefore is the optional UTC timestamp before which the license is not active.
	NotBefore *time.Time `json:"nbf,omitempty"`

	// ExpiresAt is the optional UTC timestamp after which the license is expired.
	ExpiresAt *time.Time `json:"exp,omitempty"`

	// KV holds arbitrary key-value pairs (e.g., "tokens": "500000", "tier": "enterprise").
	KV map[string]string `json:"kv,omitempty"`
}

Claims represents the full payload of a license, combining standard metadata with an arbitrary key-value mapping (KV) for feature flags, token quotas, tier, etc.

func NewClaims

func NewClaims(id, issuer, subject string) Claims

NewClaims initializes a Claims instance with a generated ID and IssuedAt set to current time.

func QuickVerify

func QuickVerify(privPEM []byte, passphrase []byte, token string) (*Claims, error)

QuickVerify verifies and decrypts a license token using an SSH private key (which contains the full seed).

func QuickVerifyAt

func QuickVerifyAt(pubKeyBytes []byte, payloadKey []byte, token string, at time.Time) (*Claims, error)

QuickVerifyAt verifies the token at an explicit timestamp.

func QuickVerifyPinned

func QuickVerifyPinned(payloadKey []byte, token string) (*Claims, error)

QuickVerifyPinned verifies and decrypts a token using the build-time PinnedAuthorityPublicKey.

func QuickVerifyPinnedAt

func QuickVerifyPinnedAt(payloadKey []byte, token string, at time.Time) (*Claims, error)

QuickVerifyPinnedAt verifies a token using the build-time PinnedAuthorityPublicKey at an explicit timestamp.

func QuickVerifyWithPublicKey

func QuickVerifyWithPublicKey(pubKeyBytes []byte, payloadKey []byte, token string) (*Claims, error)

QuickVerifyWithPublicKey verifies the signature using an SSH public key and decrypts with the payload key.

func VerifyPinnedToken

func VerifyPinnedToken(token string) (*Claims, error)

VerifyPinnedToken verifies and decrypts a token with both build-time pinned values: PinnedAuthorityPublicKey for the signature and PinnedPayloadKey for the payload. This is the client entry point the contenox model provider uses to turn a checked-in license into a configured provider.

func (*Claims) Get

func (c *Claims) Get(key string) (string, bool)

Get returns the value associated with key, and whether the key was present.

func (*Claims) GetBool

func (c *Claims) GetBool(key string, defaultVal bool) bool

GetBool returns the boolean value for key, or defaultVal if absent or unparseable.

func (*Claims) GetInt

func (c *Claims) GetInt(key string, defaultVal int) int

GetInt returns the integer value for key, or defaultVal if absent or unparseable.

func (*Claims) GetInt64

func (c *Claims) GetInt64(key string, defaultVal int64) int64

GetInt64 returns the int64 value for key, or defaultVal if absent or unparseable.

func (*Claims) GetString

func (c *Claims) GetString(key, defaultVal string) string

GetString returns the value associated with key, or defaultVal if absent.

func (*Claims) HasFeature

func (c *Claims) HasFeature(feature string) bool

HasFeature returns true if feature is enabled, checking both: 1. A comma/space-separated list of features in the "features" or "capabilities" key 2. A specific boolean key matching the feature name (e.g., "feature:ee_ai_tools" or "ee_ai_tools")

func (*Claims) Set

func (c *Claims) Set(key, val string)

Set stores a string key-value pair.

func (*Claims) SetBool

func (c *Claims) SetBool(key string, val bool)

SetBool stores a boolean value under key.

func (*Claims) SetInt

func (c *Claims) SetInt(key string, val int)

SetInt stores an integer value under key.

func (*Claims) SetInt64

func (c *Claims) SetInt64(key string, val int64)

SetInt64 stores an int64 value under key.

func (*Claims) ValidateTimestamps

func (c *Claims) ValidateTimestamps(now time.Time) error

ValidateTimestamps checks whether the license is currently valid at time `now`.

type Header struct {
	Version   int    `json:"v"`
	Algorithm string `json:"alg"`
	KeyID     string `json:"kid,omitempty"`
	LicenseID string `json:"id,omitempty"`
	ExpiresAt *int64 `json:"exp,omitempty"`
}

Header holds the unencrypted metadata stored in the envelope.

func DecodeToken

func DecodeToken(rawToken string) (*Header, []byte, []byte, []byte, error)

DecodeToken parses a compact or armored token string into its constituent parts: Header, Ciphertext, Signature, and the signing message bytes.

type Issuer

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

Issuer creates, encrypts, and signs license tokens using an SSH/Ed25519 private key.

func NewIssuer

func NewIssuer(privKey libcipher.SigningPrivateKey, opts ...IssuerOption) (*Issuer, error)

NewIssuer creates a new Issuer using an Ed25519 signing private key.

func NewIssuerFromSSHPrivateKey

func NewIssuerFromSSHPrivateKey(pemBytes []byte, passphrase []byte, opts ...IssuerOption) (*Issuer, error)

NewIssuerFromSSHPrivateKey creates an Issuer by parsing an SSH private key (with optional passphrase).

func (*Issuer) Issue

func (iss *Issuer) Issue(claims Claims) (string, error)

Issue generates, encrypts, and signs a license token in compact format.

func (*Issuer) IssueArmored

func (iss *Issuer) IssueArmored(claims Claims) (string, error)

IssueArmored generates, encrypts, signs, and formats a license token as an armored text block.

func (*Issuer) PublicKey

func (iss *Issuer) PublicKey() libcipher.SigningPublicKey

PublicKey returns the issuer's public key.

type IssuerOption

type IssuerOption func(*Issuer)

IssuerOption allows customizing the Issuer.

func WithIssuerKDFInfo

func WithIssuerKDFInfo(info string) IssuerOption

WithIssuerKDFInfo customizes the HKDF info string used to derive the encryption key.

func WithIssuerKeyID

func WithIssuerKeyID(keyID string) IssuerOption

WithIssuerKeyID sets a key ID (kid) in the token header.

func WithPayloadEncryptionKey

func WithPayloadEncryptionKey(key []byte) IssuerOption

WithPayloadEncryptionKey sets an explicit 32-byte symmetric encryption key for the payload.

type Verifier

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

Verifier validates signatures and decrypts license payloads using an SSH/Ed25519 public or private key.

func NewPinnedVerifier

func NewPinnedVerifier(opts ...VerifierOption) (*Verifier, error)

NewPinnedVerifier constructs a Verifier configured with the build-time PinnedAuthorityPublicKey.

func NewVerifier

func NewVerifier(pubKey libcipher.SigningPublicKey, opts ...VerifierOption) (*Verifier, error)

NewVerifier creates a Verifier with an Ed25519 public key.

func NewVerifierFromSSHPrivateKey

func NewVerifierFromSSHPrivateKey(pemBytes []byte, passphrase []byte, opts ...VerifierOption) (*Verifier, error)

NewVerifierFromSSHPrivateKey creates a Verifier using an SSH private key (which contains both the public key and allows automatic decryption key derivation).

func NewVerifierFromSSHPublicKey

func NewVerifierFromSSHPublicKey(pubKeyBytes []byte, opts ...VerifierOption) (*Verifier, error)

NewVerifierFromSSHPublicKey creates a Verifier by parsing an OpenSSH or PEM public key.

func (*Verifier) InspectHeader

func (v *Verifier) InspectHeader(token string) (*Header, error)

InspectHeader parses and returns the unencrypted token header without verifying or decrypting.

func (*Verifier) Verify

func (v *Verifier) Verify(token string) (*Claims, error)

Verify validates the signature, decrypts the payload, and validates timestamps at the current time.

func (*Verifier) VerifyAt

func (v *Verifier) VerifyAt(token string, now time.Time) (*Claims, error)

VerifyAt validates the signature, decrypts the payload, and validates timestamps against the given time `now`.

type VerifierOption

type VerifierOption func(*Verifier)

VerifierOption allows customizing the Verifier.

func WithExpectedIssuer

func WithExpectedIssuer(expectedIssuer string) VerifierOption

WithExpectedIssuer validates that the verified claims match the expected issuer string.

func WithExpectedSubject

func WithExpectedSubject(expectedSubject string) VerifierOption

WithExpectedSubject validates that the verified claims match the expected subject string.

func WithPayloadDecryptionKey

func WithPayloadDecryptionKey(key []byte) VerifierOption

WithPayloadDecryptionKey sets the explicit 32-byte symmetric decryption key for the payload.

func WithVerifierKDFInfo

func WithVerifierKDFInfo(info string) VerifierOption

WithVerifierKDFInfo customizes the HKDF info string used when deriving the decryption key.

Jump to

Keyboard shortcuts

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