Documentation
¶
Overview ¶
Package domain holds the pure rules of the licensing model: entities, enums, sentinels, key schemes and the expiry/status/heartbeat math. No infrastructure.
Metadata limits: the reference's JsonValidator rules shared by every resource that carries metadata.
Index ¶
- Constants
- Variables
- func AuthenticationStrategies() []string
- func CheckInIntervals() []string
- func CompareLegacyKey(storedDigest, raw string) bool
- func ComponentUniquenessStrategies() []string
- func ExpirationBases() []string
- func ExpirationStrategies() []string
- func HeartbeatBases() []string
- func HeartbeatCullStrategies() []string
- func HeartbeatResurrectionStrategies() []string
- func IsWebhookEvent(event string) bool
- func LicenseNotifications(license License, state LicenseNotificationState, now time.Time) []string
- func MachineLeasingStrategies() []string
- func MachineUniquenessStrategies() []string
- func MatchingStrategies() []string
- func MetadataViolation(m map[string]any) string
- func OverageStrategies() []string
- func Overridden[T int32 | int64](override *T) bool
- func PolicyCryptoSchemes() []string
- func ProcessLeasingStrategies() []string
- func ProductDistributionStrategies() []string
- func PublicAddress(address net.IP, allowed []*net.IPNet) bool
- func RenewalBases() []string
- func SameJSON(a, b any) bool
- func TransferStrategies() []string
- type Account
- type Brand
- type Entitlement
- type Group
- type GroupOwner
- type HeartbeatPolicy
- func (h HeartbeatPolicy) AlwaysResurrectDead() bool
- func (h HeartbeatPolicy) DeactivateDead() bool
- func (h HeartbeatPolicy) DurationOrDefault() time.Duration
- func (h HeartbeatPolicy) DurationSeconds() int32
- func (h HeartbeatPolicy) FromCreation() bool
- func (h HeartbeatPolicy) LazarusTTL() time.Duration
- func (h HeartbeatPolicy) ResurrectDead() bool
- type Key
- type License
- func (l License) Active(t time.Time) bool
- func (l License) Banned() bool
- func (l License) CheckInOverdue(now time.Time) bool
- func (l License) Expired(now time.Time) bool
- func (l License) Expiring(now time.Time) bool
- func (l License) MaxCores() *int32
- func (l License) MaxDisk() *int64
- func (l License) MaxMachines() *int32
- func (l License) MaxMemory() *int64
- func (l License) MaxProcesses() *int32
- func (l License) MaxUsers() *int32
- func (l License) MaxUses() *int32
- func (l License) NextCheckIn() *time.Time
- func (l License) ProtectedFlag() bool
- func (l License) Status(now time.Time) string
- func (l License) UsersCount() int32
- type LicenseAuth
- type LicenseEntitlement
- type LicenseNotificationState
- type LicenseUser
- type LicenseValidationEvent
- type Machine
- func (m Machine) Alive() bool
- func (m Machine) InAliveScope() bool
- func (m Machine) MaxProcesses() *int32
- func (m Machine) NextHeartbeatAt() *time.Time
- func (m Machine) NotStarted() bool
- func (m Machine) RequiresHeartbeat() bool
- func (m Machine) ResurrectionPeriodPassed(now time.Time) bool
- func (m Machine) Status(now time.Time) string
- type MachineComponent
- type MachineProcess
- type NetResolver
- type PasswordReset
- type Policy
- func (p Policy) ComponentUniqueness() string
- func (p Policy) HeartbeatOf() HeartbeatPolicy
- func (p Policy) MachineLeasePerUser() bool
- func (p Policy) MachineUniqueness() string
- func (p Policy) ProcessLeasing() string
- func (p Policy) RequiresCheckIn() bool
- func (p Policy) WithinOverage(next, limit float64) bool
- type PolicyEntitlement
- type Product
- type Resolver
- type Role
- type SecondFactor
- type Token
- type URLViolation
- type User
- type Violation
- type WebhookEndpoint
- type WebhookEvent
- type WebhookEventStatus
Constants ¶
const ( AuthStrategyToken = "TOKEN" AuthStrategyLicense = "LICENSE" AuthStrategySession = "SESSION" AuthStrategyMixed = "MIXED" AuthStrategyNone = "NONE" )
The policy's authentication strategies (Policy#authentication_strategy).
const ( LicenseStatusActive = "ACTIVE" LicenseStatusInactive = "INACTIVE" LicenseStatusExpiring = "EXPIRING" LicenseStatusExpired = "EXPIRED" LicenseStatusSuspended = "SUSPENDED" LicenseStatusBanned = "BANNED" )
The license statuses, in resolution order.
const ( HeartbeatTTLSeconds int32 = 600 HeartbeatDriftSeconds int32 = 30 )
Heartbeat defaults (Machine::HEARTBEAT_TTL and HEARTBEAT_DRIFT).
const ( MachineNotStarted = "NOT_STARTED" MachineAlive = "ALIVE" MachineDead = "DEAD" HeartbeatResurrected = "RESURRECTED" )
Heartbeat statuses of machines and processes.
const ( MetadataMaxBytes = 16 * 1024 MetadataMaxDepth = 4 MetadataMaxKeys = 64 )
The metadata limits.
const ( DistributionLicensed = "LICENSED" DistributionOpen = "OPEN" DistributionClosed = "CLOSED" )
The product's distribution strategies (Product#distribution_strategy). LICENSED is the default and the null equivalent on the wire.
const ( SecondFactorIssuer = "Keygen" SecondFactorImage = "https://keygen.sh/images/logomark.png" )
The TOTP provisioning constants of the reference's SecondFactor model.
const ( SignatureEd25519 = "ed25519" SignatureRSAPSS = "rsa-pss-sha256" SignatureRSAPKCS1v5 = "rsa-sha256" SignatureECDSAP256 = "ecdsa-p256" )
The endpoint's signing algorithms (webhook_endpoints.signature_algorithm).
const AccountStatusSubscribed = "SUBSCRIBED"
Status of a CE singleplayer account on the wire: Keygen CE reports the account as subscribed (the billing state an installation has without billing).
const DefaultBrandName = "Licenses"
DefaultBrandName names an installation that configures no brand.
const (
ExpirationRevokeAccess = "REVOKE_ACCESS"
)
The policy's expiration strategies that revoke access on expiry.
const MaxWebhookURLLength = 4 * 1024
MaxWebhookURLLength is the URL column's 4 KB bound.
Variables ¶
var ErrNotFound = errors.New("domain: not found")
ErrNotFound is the shared not-found sentinel of the storage ports: one sentinel across the scenarios and repositories, because a repository method serves several scenario ports and must speak the not-found every consumer checks.
var ReservedEntitlementCodes = []string{
reservedActions, reservedAction,
}
ReservedEntitlementCodes: the two route-segment-colliding aliases.
var ReservedKeys = []string{reservedActions, reservedAction} //nolint:gochecknoglobals // transcribed reference data
ReservedKeys: the two route-segment-colliding key values.
var ReservedProductCodes = []string{
reservedActions, reservedAction,
}
ReservedProductCodes: the two route-segment-colliding aliases.
var SignatureAlgorithms = []string{ SignatureEd25519, SignatureRSAPSS, SignatureRSAPKCS1v5, SignatureECDSAP256, }
SignatureAlgorithms is the closed set the endpoint accepts.
var WebhookEvents = []string{
"component.created", "component.updated", "component.deleted",
"entitlement.created", "entitlement.updated", "entitlement.deleted",
"group.created", "group.updated", "group.deleted",
"group.owners.attached", "group.owners.detached",
"key.created", "key.updated", "key.deleted",
"license.created", "license.updated", "license.deleted",
"license.suspended", "license.revoked", "license.reinstated", "license.renewed",
"license.expired", "license.expiring-soon",
"license.checked-in", "license.checked-out",
"license.check-in-required-soon", "license.check-in-overdue",
"license.validated", "license.validation.succeeded", "license.validation.failed",
"license.group.updated", "license.owner.updated", "license.policy.updated",
"license.user.updated", "license.users.attached", "license.users.detached",
"license.entitlements.attached", "license.entitlements.detached",
"license.usage.incremented", "license.usage.decremented", "license.usage.reset",
"machine.created", "machine.updated", "machine.deleted", "machine.checked-out",
"machine.heartbeat.ping", "machine.heartbeat.pong", "machine.heartbeat.dead",
"machine.heartbeat.reset", "machine.heartbeat.resurrected",
"machine.group.updated", "machine.owner.updated", "machine.proofs.generated",
"policy.created", "policy.updated", "policy.deleted",
"policy.entitlements.attached", "policy.entitlements.detached", "policy.pool.popped",
"process.created", "process.deleted",
"process.heartbeat.ping", "process.heartbeat.pong", "process.heartbeat.dead",
"product.created", "product.updated", "product.deleted",
"second-factor.created", "second-factor.deleted",
"second-factor.enabled", "second-factor.disabled",
"token.generated", "token.regenerated", "token.revoked",
"user.created", "user.updated", "user.deleted",
"user.banned", "user.unbanned", "user.password-reset", "user.group.updated",
}
WebhookEvents is the in-scope webhook event universe: the reference's seeded event_types minus the out-of-scope families (releases, artifacts, packages, engines, environments, accounts/billing). Subscriptions are validated against it (an out-of-scope family name is SUBSCRIPTIONS_NOT_ALLOWED here, though the full reference accepts it — it never emits those events).
Functions ¶
func AuthenticationStrategies ¶
func AuthenticationStrategies() []string
func CheckInIntervals ¶
func CheckInIntervals() []string
func CompareLegacyKey ¶
CompareLegacyKey checks a raw legacy-encrypted key against the stored bcrypt digest (BCrypt(SHA256hex(raw))).
func ComponentUniquenessStrategies ¶
func ComponentUniquenessStrategies() []string
func ExpirationBases ¶
func ExpirationBases() []string
func ExpirationStrategies ¶
func ExpirationStrategies() []string
func HeartbeatBases ¶
func HeartbeatBases() []string
func HeartbeatCullStrategies ¶
func HeartbeatCullStrategies() []string
func HeartbeatResurrectionStrategies ¶
func HeartbeatResurrectionStrategies() []string
func IsWebhookEvent ¶
IsWebhookEvent answers whether the name is a subscribable event.
func LicenseNotifications ¶
func LicenseNotifications(license License, state LicenseNotificationState, now time.Time) []string
LicenseNotifications is the event selection of the reference's expiration and overdue-check-in workers. Expired/overdue notices stop after twelve hours; advance warnings cover the next three days. Throttles are per kind.
func MachineLeasingStrategies ¶
func MachineLeasingStrategies() []string
func MachineUniquenessStrategies ¶
func MachineUniquenessStrategies() []string
Strategy enum sets, transcribed from Policy's SCOPES/constants.
func MatchingStrategies ¶
func MatchingStrategies() []string
func MetadataViolation ¶
MetadataViolation returns the first model-level metadata violation in the reference's wire order: bytesize, depth, then keys. The reference renders only the first error for a given attribute and validation code.
func OverageStrategies ¶
func OverageStrategies() []string
func Overridden ¶ added in v0.0.5
Overridden answers the reference's `<limit>_override?`: an override is in effect only when set and non-zero (Rails' query method on an integer column is false for 0, so a zero override reads the policy's).
func PolicyCryptoSchemes ¶
func PolicyCryptoSchemes() []string
Policy crypto schemes (Policy::CRYPTO_SCHEMES).
func ProcessLeasingStrategies ¶
func ProcessLeasingStrategies() []string
func ProductDistributionStrategies ¶
func ProductDistributionStrategies() []string
ProductDistributionStrategies is the allowed set.
func PublicAddress ¶
PublicAddress answers whether the IP is a routable public address under the reference's blacklist (loopback, private, link-local, mapped/compat and the reserved ranges are all refused) — or inside one of the allowed private ranges.
func RenewalBases ¶
func RenewalBases() []string
func SameJSON ¶ added in v0.0.18
SameJSON reports whether two values encode to the same JSON: the declared catalog's equality, under which a nil and an empty list or a number decoded from the configuration and from a row compare equal only when they mean the same.
func TransferStrategies ¶
func TransferStrategies() []string
Types ¶
type Account ¶
type Account struct {
ID uuid.UUID
Name string
Slug string
APIVersion string
Protected bool
Keys crypto.AccountKeys
CreatedAt time.Time
UpdatedAt time.Time
}
Account is the single account of the installation. It exists implicitly: the row is created at startup from configuration when missing.
type Brand ¶
type Brand struct {
Name string `json:"name,omitempty"`
Tagline string `json:"tagline,omitempty"`
LogoURL string `json:"logoUrl,omitempty"` //nolint:tagliatelle // frontend configuration is camelCase
FaviconURL string `json:"faviconUrl,omitempty"` //nolint:tagliatelle // frontend configuration is camelCase
AccentColor string `json:"accentColor,omitempty"` //nolint:tagliatelle // frontend configuration is camelCase
SupportEmail string `json:"supportEmail,omitempty"` //nolint:tagliatelle // frontend configuration is camelCase
SupportURL string `json:"supportUrl,omitempty"` //nolint:tagliatelle // frontend configuration is camelCase
TermsURL string `json:"termsUrl,omitempty"` //nolint:tagliatelle // frontend configuration is camelCase
PrivacyURL string `json:"privacyUrl,omitempty"` //nolint:tagliatelle // frontend configuration is camelCase
}
Brand is the vendor identity the installation shows its customers: the portal's header, colors and footer links, and the data every message template receives. It is immutable after NewBrand.
type Entitlement ¶
type Entitlement struct {
ID uuid.UUID
AccountID uuid.UUID
Name string
Code string
Metadata map[string]any
CreatedAt, UpdatedAt time.Time
}
Entitlement is an account-wide feature policies and licenses attach.
type Group ¶
type Group struct {
ID uuid.UUID
AccountID uuid.UUID
Name string
// MaxUsers/MaxLicenses/MaxMachines are nil without a limit.
MaxUsers *int
MaxLicenses *int
MaxMachines *int
Metadata map[string]any
CreatedAt time.Time
UpdatedAt time.Time
}
Group groups users, licenses and machines under shared limits.
type GroupOwner ¶
type GroupOwner struct {
ID uuid.UUID
AccountID uuid.UUID
GroupID uuid.UUID
UserID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
}
GroupOwner is the group↔user ownership join resource.
type HeartbeatPolicy ¶ added in v0.0.5
type HeartbeatPolicy struct {
Require bool
Duration *int32
Basis string
Resurrect string
CullOnDeath string
}
HeartbeatPolicy is the heartbeat part of a policy.
func (HeartbeatPolicy) AlwaysResurrectDead ¶ added in v0.0.5
func (h HeartbeatPolicy) AlwaysResurrectDead() bool
AlwaysResurrectDead answers always_resurrect_dead?.
func (HeartbeatPolicy) DeactivateDead ¶ added in v0.0.5
func (h HeartbeatPolicy) DeactivateDead() bool
DeactivateDead answers deactivate_dead?: an unset strategy culls.
func (HeartbeatPolicy) DurationOrDefault ¶ added in v0.0.5
func (h HeartbeatPolicy) DurationOrDefault() time.Duration
DurationOrDefault is the policy's heartbeat duration, else the TTL.
func (HeartbeatPolicy) DurationSeconds ¶ added in v0.0.5
func (h HeartbeatPolicy) DurationSeconds() int32
DurationSeconds is DurationOrDefault in whole seconds.
func (HeartbeatPolicy) FromCreation ¶ added in v0.0.5
func (h HeartbeatPolicy) FromCreation() bool
FromCreation answers heartbeat_from_creation?: the clock starts at activation instead of at the first ping.
func (HeartbeatPolicy) LazarusTTL ¶ added in v0.0.5
func (h HeartbeatPolicy) LazarusTTL() time.Duration
LazarusTTL is the window after death within which a ping revives.
func (HeartbeatPolicy) ResurrectDead ¶ added in v0.0.5
func (h HeartbeatPolicy) ResurrectDead() bool
ResurrectDead answers resurrect_dead?: an unset strategy never revives.
type Key ¶
type Key struct {
ID uuid.UUID
AccountID uuid.UUID
PolicyID uuid.UUID
// ProductID is the key's policy's product (rendered in the key
// document's product relationship).
ProductID uuid.UUID
Key string
CreatedAt, UpdatedAt time.Time
}
Key is a member of a pooled policy's key pool.
type License ¶
type License struct {
ID uuid.UUID
AccountID uuid.UUID
ProductID uuid.UUID
PolicyID uuid.UUID
// OwnerID is the owner user (user_id); Valid false when unowned.
OwnerID uuid.NullUUID
GroupID uuid.NullUUID
Name *string
// Key is the stored key: the plaintext for every scheme but
// LEGACY_ENCRYPT (which stores a bcrypt digest and renders the raw
// key only in the create response, via RawKey).
Key string
// RawKey carries the one-time plaintext of a legacy-encrypted key
// (the create response renders it; later reads omit key entirely).
RawKey *string
// Expiry is nil for perpetual licenses.
Expiry *time.Time
Uses int32
Suspended bool
// Protected is the license override; nil inherits the policy.
Protected *bool
Metadata map[string]any
// The per-license limit overrides (nil inherits the policy).
MaxMachinesOverride *int32
MaxProcessesOverride *int32
MaxUsersOverride *int32
MaxCoresOverride *int32
MaxMemoryOverride *int64
MaxDiskOverride *int64
MaxUsesOverride *int32
// Denormalized counters, kept by the app like the reference's
// counter caches.
MachinesCount int32
MachinesCoreCount int32
MachinesMemoryCount int64
MachinesDiskCount int64
LicenseUsersCount int32
LastValidatedAt *time.Time
LastValidatedChecksum *string
LastValidatedVersion *string
LastCheckInAt *time.Time
LastCheckOutAt *time.Time
CreatedAt, UpdatedAt time.Time
// Policy is the owning policy row (loaded with the license).
Policy Policy
// OwnerBanned: the owner's ban state (license.banned?).
OwnerBanned bool
// OwnerEmail of the owner (feeds the generated seed keys and the
// user-scope check); nil when unowned.
OwnerEmail *string
}
License is a license: its row plus the policy it delegates to (the reference delegates scheme/strict/floating/limits/check-in straight to the policy, so the scenario loads it together with the row).
func (License) CheckInOverdue ¶
CheckInOverdue answers check_in_overdue?.
func (License) MaxMachines ¶
MaxMachines answers the effective machine limit (override else policy).
func (License) MaxProcesses ¶
MaxProcesses answers the effective process limit.
func (License) NextCheckIn ¶
NextCheckIn answers next_check_in_at (nil unless check-in applies and has happened once).
func (License) ProtectedFlag ¶
ProtectedFlag answers protected?: the override when set, else the policy's.
func (License) Status ¶
Status resolves the wire status (BANNED → SUSPENDED → EXPIRED → EXPIRING → INACTIVE → ACTIVE).
func (License) UsersCount ¶
UsersCount answers the users count (licensees plus the owner).
type LicenseAuth ¶
type LicenseAuth struct {
ID uuid.UUID
AccountID uuid.UUID
Key string
Suspended bool
// GroupID is the license's group, when it has one (Valid false
// otherwise).
GroupID uuid.NullUUID
// Expiry is nil when the license never expires.
Expiry *time.Time
// OwnerBanned: the owning user is banned (license.banned?).
OwnerBanned bool
// PolicyAuthenticationStrategy may be empty (legacy nil → TOKEN).
PolicyAuthenticationStrategy string
// PolicyExpirationStrategy may be empty.
PolicyExpirationStrategy string
}
LicenseAuth is the slice of a license needed to authenticate by key: the license row plus the owner-ban and policy-strategy answers.
func (LicenseAuth) Expired ¶
func (l LicenseAuth) Expired(now time.Time) bool
Expired reports whether the license's expiry lies in the past.
func (LicenseAuth) RevokesAccess ¶ added in v0.0.14
func (l LicenseAuth) RevokesAccess() bool
RevokesAccess mirrors Policy#revoke_access? (REVOKE_ACCESS): an expired license no longer authenticates. RESTRICT_ACCESS (the default) still does, and check-out answers it a file with the license expired inside.
func (LicenseAuth) SupportsLicenseAuth ¶
func (l LicenseAuth) SupportsLicenseAuth() bool
SupportsLicenseAuth mirrors Policy#supports_license_auth?.
func (LicenseAuth) SupportsTokenAuth ¶
func (l LicenseAuth) SupportsTokenAuth() bool
SupportsTokenAuth mirrors Policy#supports_token_auth?.
type LicenseEntitlement ¶
type LicenseEntitlement struct {
ID uuid.UUID
AccountID uuid.UUID
LicenseID uuid.UUID
EntitlementID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
}
LicenseEntitlement is the license↔entitlement join resource.
type LicenseNotificationState ¶
type LicenseNotificationState struct {
Expiration *time.Time
ExpiringSoon *time.Time
CheckInOverdue *time.Time
CheckInSoon *time.Time
}
LicenseNotificationState persists the reference's per-event daily throttle.
type LicenseUser ¶
type LicenseUser struct {
ID uuid.UUID
AccountID uuid.UUID
LicenseID uuid.UUID
UserID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
}
LicenseUser is the license↔licensee join resource.
type LicenseValidationEvent ¶
type LicenseValidationEvent struct {
License License
Valid bool
Detail string
Code string
Time time.Time
Nonce *int64
Scope map[string]any
}
LicenseValidationEvent carries the license and the validation metadata included in the reference's webhook document.
type Machine ¶
type Machine struct {
ID uuid.UUID
AccountID uuid.UUID
LicenseID uuid.UUID
PolicyID uuid.UUID
OwnerID uuid.NullUUID
GroupID uuid.NullUUID
Name *string
Fingerprint string
IP *string
Hostname *string
Platform *string
Cores *int32
Memory *int64
Disk *int64
// MaxProcessesOverride is the machine's own process limit (else
// the license's maxProcesses).
MaxProcessesOverride *int32
Metadata map[string]any
LastHeartbeatAt *time.Time
LastCheckOutAt *time.Time
LastDeathEventSentAt *time.Time
CreatedAt, UpdatedAt time.Time
// The facts joined for authorization: the product the machine's
// policy belongs to, the license's owner and its resolved protected
// flag.
ProductID uuid.UUID
LicenseOwnerID uuid.NullUUID
LicenseProtected bool
// LicenseMaxProcesses is the license's process limit (its override
// else the policy's).
LicenseMaxProcesses *int32
// Heartbeat is the policy's heartbeat rule set.
Heartbeat HeartbeatPolicy
// HeartbeatStatus is Status at load time, or RESURRECTED right after
// a resurrection (the reference's transient status override).
HeartbeatStatus string
}
Machine is a licensed device.
func (Machine) InAliveScope ¶ added in v0.0.5
InAliveScope answers the reference's Machine.alive SQL scope (what license validation counts): every machine not dead — not yet started ones included, unlike the alive? predicate.
func (Machine) MaxProcesses ¶
MaxProcesses answers the machine's effective process limit (the override else the license's).
func (Machine) NextHeartbeatAt ¶ added in v0.0.5
NextHeartbeatAt is when the next ping is due; nil before the first.
func (Machine) NotStarted ¶
NotStarted answers heartbeat_not_started?.
func (Machine) RequiresHeartbeat ¶ added in v0.0.5
RequiresHeartbeat answers requires_heartbeat?: the policy demands it or the machine has pinged once.
func (Machine) ResurrectionPeriodPassed ¶ added in v0.0.5
ResurrectionPeriodPassed answers resurrection_period_passed?.
type MachineComponent ¶ added in v0.0.5
type MachineComponent struct {
ID uuid.UUID
AccountID uuid.UUID
MachineID uuid.UUID
Name string
Fingerprint string
Metadata map[string]any
CreatedAt time.Time
UpdatedAt time.Time
// ProductID and LicenseID are its machine's (joined).
ProductID uuid.UUID
LicenseID uuid.UUID
}
MachineComponent is a named hardware fingerprint of a machine.
type MachineProcess ¶ added in v0.0.5
type MachineProcess struct {
ID uuid.UUID
AccountID uuid.UUID
MachineID uuid.UUID
PID string
Metadata map[string]any
LastHeartbeatAt time.Time
LastDeathEventSentAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
// Heartbeat is its machine policy's heartbeat rule set.
Heartbeat HeartbeatPolicy
// HeartbeatStatus is Status at load time, or RESURRECTED right after
// a resurrection.
HeartbeatStatus string
// ProductID and LicenseID are its machine's (joined).
ProductID uuid.UUID
LicenseID uuid.UUID
}
MachineProcess is a running process on a machine, with a heartbeat.
func (MachineProcess) NextHeartbeatAt ¶ added in v0.0.5
func (p MachineProcess) NextHeartbeatAt() time.Time
NextHeartbeatAt is when the next ping is due (the machine's interval).
func (MachineProcess) ResurrectionPeriodPassed ¶ added in v0.0.5
func (p MachineProcess) ResurrectionPeriodPassed(now time.Time) bool
ResurrectionPeriodPassed answers resurrection_period_passed?.
type NetResolver ¶
type NetResolver struct{}
NetResolver resolves through the host's resolver (the default DNS path); tests inject deterministic answers instead.
func (NetResolver) LookupHost ¶
func (NetResolver) LookupHost(host string) ([]string, error)
LookupHost implements Resolver.
type PasswordReset ¶
type PasswordReset struct {
User User
Token string
// Deliver only gates email; the webhook and event are always recorded.
Deliver *bool
}
PasswordReset is the password-reset event's user and one-time plaintext claim. The claim belongs only to webhook document metadata, never user attributes.
type Policy ¶
type Policy struct {
ID uuid.UUID
AccountID uuid.UUID
ProductID uuid.UUID
Name string
Duration *int32
Strict bool
Floating bool
UsePool bool
MaxMachines *int32
MaxProcesses *int32
MaxUsers *int32
MaxCores *int32
MaxMemory *int64
MaxDisk *int64
MaxUses *int32
MachineUniquenessStrategy string
MachineMatchingStrategy string
ComponentUniquenessStrategy string
ComponentMatchingStrategy string
ExpirationStrategy string
ExpirationBasis string
RenewalBasis string
TransferStrategy string
AuthenticationStrategy string
MachineLeasingStrategy string
ProcessLeasingStrategy string
OverageStrategy string
Scheme string
Encrypted bool
// Protected is nil until created (it then inherits the account's
// protected flag); PATCH may set it explicitly.
Protected *bool
RequireProductScope bool
RequirePolicyScope bool
RequireMachineScope bool
RequireFingerprintScope bool
RequireComponentsScope bool
RequireUserScope bool
RequireChecksumScope bool
RequireVersionScope bool
RequireCheckIn bool
CheckInInterval string
CheckInIntervalCount *int32
HeartbeatDuration *int32
HeartbeatCullStrategy string
HeartbeatResurrectionStrategy string
HeartbeatBasis string
RequireHeartbeat bool
Metadata map[string]any
CreatedAt, UpdatedAt time.Time
}
Policy is a product's licensing rule set. Every strategy column is a nullable enum; the zero-value strings mean null on the wire.
func PolicyCreateDefaults ¶
func PolicyCreateDefaults() Policy
The policy create defaults (v1.7): every nil strategy defaults, and a node-locked policy with no explicit maxMachines gets exactly one.
func (Policy) ComponentUniqueness ¶ added in v0.0.5
ComponentUniqueness is the effective component uniqueness strategy (an unset one is per machine).
func (Policy) HeartbeatOf ¶ added in v0.0.5
func (p Policy) HeartbeatOf() HeartbeatPolicy
HeartbeatOf is the heartbeat rule set of the policy.
func (Policy) MachineLeasePerUser ¶ added in v0.0.5
MachineLeasePerUser answers machine_lease_per_user?: limits count per machine owner instead of per license.
func (Policy) MachineUniqueness ¶ added in v0.0.5
MachineUniqueness is the effective machine uniqueness strategy (an unset one is per license).
func (Policy) ProcessLeasing ¶ added in v0.0.5
ProcessLeasing is the policy's process leasing strategy: PER_MACHINE (the default), PER_LICENSE or PER_USER.
func (Policy) RequiresCheckIn ¶
RequiresCheckIn answers requires_check_in? (the policy's flag).
func (Policy) WithinOverage ¶ added in v0.0.5
WithinOverage answers whether next, past limit, is still allowed by the policy's overage strategy (ALWAYS_ALLOW_OVERAGE, or within the 1.25x, 1.5x or 2x allowance).
type PolicyEntitlement ¶
type PolicyEntitlement struct {
ID uuid.UUID
AccountID uuid.UUID
PolicyID uuid.UUID
EntitlementID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
}
PolicyEntitlement is one policy_entitlements join row: the resource the attach route answers.
type Product ¶
type Product struct {
ID uuid.UUID
AccountID uuid.UUID
Name string
Code string // empty is null
DistributionStrategy string // LICENSED when unset
URL string
Platforms []string // nil is null
Metadata map[string]any
CreatedAt, UpdatedAt time.Time
}
Product is an account's product: the top of the licensing tree.
type Resolver ¶
Resolver answers the addresses a host resolves to (DNS). An interface so tests can supply deterministic answers.
type Role ¶
type Role string
Role of a bearer. The zero value is the plain user role.
const ( RoleUser Role = "user" RoleAdmin Role = "admin" RoleDeveloper Role = "developer" RoleReadOnly Role = "read_only" RoleSalesAgent Role = "sales_agent" RoleSupportRole Role = "support_agent" RoleProduct Role = "product" RoleLicense Role = "license" )
The CE roles. Stored underscored like Keygen's internal names; the wire format renders them dasherized (see Wire).
type SecondFactor ¶
type SecondFactor struct {
ID uuid.UUID
AccountID uuid.UUID
UserID uuid.UUID
// Secret is the base32 TOTP secret.
Secret string
Enabled bool
// LastVerifiedAt blocks OTP replays (the matched timestamp is
// persisted after every successful verification).
LastVerifiedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
SecondFactor is a user's TOTP second factor. At most one exists per user (unique index), exactly like the reference.
func (SecondFactor) URI ¶
func (s SecondFactor) URI(email string) string
URI is the provisioning URI, rendered only while the factor is disabled (the secret is not exposed once enabled).
type Token ¶
type Token struct {
ID uuid.UUID
AccountID uuid.UUID
Digest string
BearerID uuid.UUID
// BearerType is the polymorphic bearer: "User", "Product" or
// "License", stored like Keygen's bearer_type column.
BearerType string
BearerRole Role
Kind string
Name *string
// Expiry is nil for tokens that never expire.
Expiry *time.Time
Permissions []string
// Activation-token counters (bearer_type License); zero otherwise.
MaxActivations *int
Activations int
MaxDeactivations *int
Deactivations int
CreatedAt time.Time
UpdatedAt time.Time
}
Token is an authentication token. Only the digest is persisted; the raw secret exists once, in the creation response.
type URLViolation ¶
URLViolation is one rule the endpoint URL broke. The validator accumulates them in the reference's order (protocol, host, address).
func ValidateURL ¶
func ValidateURL( raw string, protocols []string, resolver Resolver, allowed []*net.IPNet, ) []URLViolation
ValidateURL is the reference's shared URL validator (the endpoint and the product both use it, with different protocol sets): the protocol allowlist, a dotted public-suffix-style host that is not blacklisted, and DNS resolution where every address is public (or explicitly allowed — the self-hosted escape hatch for internal receivers). Violations accumulate in the validator's order.
func ValidateWebhookURL ¶
func ValidateWebhookURL(raw string, resolver Resolver, allowed []*net.IPNet) []URLViolation
ValidateWebhookURL applies the reference's URL validator to a webhook endpoint URL: https only.
type User ¶
type User struct {
ID uuid.UUID
AccountID uuid.UUID
FirstName string
LastName string
Email string
// PasswordDigest is the bcrypt hash; empty for passwordless users.
PasswordDigest string
Role Role
// Permissions overrides the role's default set when non-empty (an EE
// feature; kept for wire fidelity of the storage shape).
Permissions map[string]struct{}
GroupID uuid.NullUUID
Metadata map[string]any
// PasswordResetToken is the HMAC digest of the outstanding
// password-reset token (plaintext only in the webhook/email).
PasswordResetToken string
PasswordResetSentAt *time.Time
// BannedAt is set when the user is banned; nil otherwise.
BannedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
User is an account's user: a license owner or an admin bearer.
func (User) Authenticates ¶
Authenticates reports whether the password matches the digest (bcrypt, like the reference's has_secure_password).
func (User) FullName ¶
FullName is nil on the wire unless both names are present, like the Keygen serializer.
func (User) HasPassword ¶
HasPassword reports whether the user may authenticate with a password.
type Violation ¶
type Violation struct {
Code string
Detail string
// Attr is the wire attribute name (camelCase); Rel the wire
// relationship name when the violation points at a relationship.
Attr string
Rel string
}
Violation is one model-validation failure: the error code the wire renders, its verbatim detail, and the attribute or relationship it points at. The scenarios translate violations into the 422 document.
type WebhookEndpoint ¶
type WebhookEndpoint struct {
ID uuid.UUID
AccountID uuid.UUID
ProductID uuid.NullUUID
URL string
Subscriptions []string
// SignatureAlgorithm is never empty (ed25519 by default).
SignatureAlgorithm string
APIVersion string
CreatedAt time.Time
UpdatedAt time.Time
}
WebhookEndpoint is a registered HTTPS receiver of webhook events, optionally scoped to one product (it then receives only the events that product may read).
func (WebhookEndpoint) Subscribed ¶
func (e WebhookEndpoint) Subscribed(event string) bool
Subscribed answers whether the endpoint receives the event ("*" or the exact name — disabled endpoints hold an empty list).
type WebhookEvent ¶
type WebhookEvent struct {
ID uuid.UUID
AccountID uuid.UUID
EndpointID uuid.NullUUID
Endpoint string
Event string
Payload string
APIVersion string
IdempotencyToken string
Status WebhookEventStatus
Attempts int
LastResponseCode *int
LastResponseBody *string
CreatedAt time.Time
UpdatedAt time.Time
}
WebhookEvent is the Keygen API resource describing a delivery and its outcome. The delivery reference is enqueued atomically alongside this resource.
type WebhookEventStatus ¶
type WebhookEventStatus string
WebhookEventStatus is the delivery lifecycle of a webhook event.
const ( EventDelivering WebhookEventStatus = "DELIVERING" EventDelivered WebhookEventStatus = "DELIVERED" EventFailing WebhookEventStatus = "FAILING" EventFailed WebhookEventStatus = "FAILED" )
The statuses (webhook_events.status).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package crypto holds the key generation and signing helpers: account keys, license-key schemes, license/machine files, response signatures and token secrets/digests.
|
Package crypto holds the key generation and signing helpers: account keys, license-key schemes, license/machine files, response signatures and token secrets/digests. |
|
Package jsonapi holds the wire-format transforms every handler shares: the metadata key casing (camelCase on the wire, snake_case stored) and the timestamp rendering.
|
Package jsonapi holds the wire-format transforms every handler shares: the metadata key casing (camelCase on the wire, snake_case stored) and the timestamp rendering. |