feat(license): metered licensing — catalogue, entitlements, and enforcement
Server Deploy / deploy (push) Successful in 5m22s

Implements spec 7 tasks 2-10 on top of the six-plan payload from task 1.

Admin: plans re-keyed on (deployment, tier); new catalogue collection holds
every Paddle price ID (one row per priceable component); new entitlements
collection holds desired beside granted. admin/internal/catalogue owns both
folds — entitlement to licence limits, and entitlement to Paddle line items —
so the base allowance is subtracted in exactly one place. licensing.Issue now
snapshots the instance's granted entitlement, never desired. Free is enforced
per account AND deployment. Staff endpoints for plans, catalogue and
entitlements; Free self-hosted can be claimed and renewed on its annual term;
the reaper stays cloud-only.

Server: enforces the monitor cap, audit-log retention (daily sweep, skips
Unlimited and lapsed instances), and gates the OIDC callback. Unset limits are
filled from the seed plan at the single decode site so old blobs never read as
zero.

Frontends: adminsite gains a catalogue price-ID editor, six-plan allowance
screen, and a catalogue-driven PlanConfigurator mounted on the staff instance
page. web shows monitors, audit retention and support level on the licence page.

Docs: CLAUDE.md, spec index and plan 5 preamble updated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-27 09:37:39 +01:00
co-authored by Claude Opus 5
parent 3fc726da9e
commit c4e6ad5485
35 changed files with 2241 additions and 222 deletions
+100 -3
View File
@@ -221,8 +221,13 @@ func createInstance(c *gin.Context) {
// Pre-check the Free rule so we never create an instance we then cannot
// licence. licensing.Issue enforces it too; this is the friendly refusal.
//
// Scoped to cloud because that is what this endpoint creates. It MUST match
// checkFreeLimit's scoping — a pre-check stricter than the issuer refuses
// something that would have worked.
n, err := db.Admin("admin_instances").CountDocuments(ctx, bson.M{
"account_id": s.AccountID,
"deployment": license.DeploymentCloud,
"tier": license.TierFree,
"status": bson.M{"$ne": models.StatusCancelled},
})
@@ -232,7 +237,7 @@ func createInstance(c *gin.Context) {
}
if n > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": "this account already has a Free instance"})
"error": "this account already has a Free cloud instance"})
return
}
@@ -364,10 +369,16 @@ func renewInstance(c *gin.Context) {
return
}
// Free renews on its deployment's only term: monthly for cloud, annual for
// self-hosted. Reading it from TermsFor rather than hardcoding is what stops
// a self-hosted instance being handed a one-month licence.
terms := license.TermsFor(inst.Deployment)
term := terms[len(terms)-1]
lic, err := licensing.Issue(ctx, licensing.IssueInput{
InstanceID: inst.InstanceID,
Tier: license.TierFree,
Term: "monthly",
Term: term,
Reason: models.ReasonRenewal,
IssuedBy: "self-serve",
})
@@ -375,7 +386,9 @@ func renewInstance(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
inject.Deliver(ctx, lic)
// Cloud is injected; self-hosted is delivered to the customer, because their
// database is theirs and we cannot write to it.
deliver(c, inst, lic)
// Clear the notice log so the next term starts the sequence again. Issue has
// already set status back to active.
@@ -414,6 +427,90 @@ var appLoginURL string
// SetAppLoginURL is called from main.
func SetAppLoginURL(v string) { appLoginURL = v }
// claimFree issues a Free licence on a linked self-hosted instance.
//
// The link step creates the row; this gives it a licence. They are separate
// because linking is about identity — proving which install is yours — and
// claiming is about entitlement, and a customer who links an install and then
// changes their mind should not have consumed their one Free allowance.
//
// Free is outside Paddle entirely, so there is no checkout, no subscription and
// nothing to reconcile. licensing.Issue's own checkFreeLimit is the real guard;
// the count here exists to refuse politely before anything is written.
func claimFree(c *gin.Context) {
inst, ok := ownedInstance(c, c.Param("id"))
if !ok {
return
}
ctx := c.Request.Context()
// Cloud Free is claimed at creation by POST /api/instances. Allowing it here
// too would be a second way to reach the same state, with its own bugs.
if inst.Deployment != license.DeploymentSelfHosted {
c.JSON(http.StatusBadRequest, gin.H{
"error": "cloud instances get their Free licence when they are created"})
return
}
if inst.CurrentLicense != "" {
c.JSON(http.StatusConflict, gin.H{
"error": "this instance already has a licence"})
return
}
plan, err := models.GetPlan(ctx, license.DeploymentSelfHosted, license.TierFree)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "no Free plan configured"})
return
}
if !plan.Active {
c.JSON(http.StatusForbidden, gin.H{
"error": "Free self-hosted is not currently offered"})
return
}
// The entitlement is written BEFORE the licence, so Issue snapshots it rather
// than falling back to the plan base. They are the same numbers today, but
// the ordering is what makes that a coincidence rather than a dependency.
if err := models.UpsertEntitlement(ctx, models.Entitlement{
InstanceID: inst.InstanceID,
AccountID: inst.AccountID,
Deployment: license.DeploymentSelfHosted,
Tier: license.TierFree,
Term: "annual",
Desired: models.Config{Servers: plan.BaseLimits.MaxServers, Features: models.Features{}},
Granted: models.Config{Servers: plan.BaseLimits.MaxServers, Features: models.Features{}},
ResolvedLimits: plan.BaseLimits,
}); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
s := auth.Current(c)
lic, err := licensing.Issue(ctx, licensing.IssueInput{
InstanceID: inst.InstanceID,
Tier: license.TierFree,
// Annual, and not a choice. Self-hosted sells annual only because the
// term length is the revocation window for an offline licence.
Term: "annual",
Reason: models.ReasonNew,
IssuedBy: s.Email,
})
if err != nil {
status := http.StatusBadRequest
if errors.Is(err, licensing.ErrFreeLimit) {
status = http.StatusConflict
}
c.JSON(status, gin.H{"error": err.Error()})
return
}
deliver(c, inst, lic)
audit.Write(ctx, models.AuditEntry{
Actor: s.Email, Action: "instance.claimed_free", AccountID: s.AccountID,
Target: inst.InstanceID, Detail: "self-hosted Free, annual", IP: c.ClientIP()})
c.JSON(http.StatusCreated, lic)
}
// deliver sends a freshly issued licence where it needs to go. Cloud instances
// are injected; self-hosted customers are emailed and can download.
//
+187
View File
@@ -0,0 +1,187 @@
package api
import (
"errors"
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/mrhid6/vantage/admin/internal/audit"
"github.com/mrhid6/vantage/admin/internal/auth"
"github.com/mrhid6/vantage/admin/internal/catalogue"
"github.com/mrhid6/vantage/admin/internal/db"
"github.com/mrhid6/vantage/admin/internal/models"
"go.mongodb.org/mongo-driver/v2/bson"
)
// entitlementBody is what a caller may set.
//
// Only Desired is writable. Granted is what a payment confirmed, and letting a
// form set it would let the portal grant itself a licence — which is the one
// thing this whole split exists to prevent. Staff promote Granted explicitly
// through a separate flag, because staff issuing a licence to somebody who has
// not paid is a real operation with a real reason, and it should be one they
// took on purpose and left an audit row for.
type entitlementBody struct {
Tier string `json:"tier"`
Term string `json:"term"`
Servers int `json:"servers"`
Features []string `json:"features"`
// Grant promotes Desired into Granted in the same write. Staff only.
Grant bool `json:"grant"`
}
// getEntitlement serves the customer's own view of one instance's configuration.
func getEntitlement(c *gin.Context) {
inst, ok := ownedInstance(c, c.Param("id"))
if !ok {
return
}
ent, err := models.GetEntitlement(c.Request.Context(), inst.InstanceID)
if errors.Is(err, models.ErrNoEntitlement) {
c.JSON(http.StatusNotFound, gin.H{"error": "no entitlement"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"entitlement": ent, "pending": ent.Pending()})
}
func staffGetEntitlement(c *gin.Context) {
var inst models.Instance
if err := db.Admin("admin_instances").FindOne(c.Request.Context(),
bson.M{"instance_id": c.Param("id")}).Decode(&inst); err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "no such instance"})
return
}
ent, err := models.GetEntitlement(c.Request.Context(), inst.InstanceID)
if errors.Is(err, models.ErrNoEntitlement) {
c.JSON(http.StatusNotFound, gin.H{"error": "no entitlement"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"entitlement": ent, "pending": ent.Pending()})
}
// staffSetEntitlement writes an instance's configuration.
//
// This is the endpoint that makes metering usable before Paddle exists: staff
// configure, then issue. It does NOT issue — recording what an instance is
// allowed and signing a licence for it stay separate, so a bad configuration is
// a row to correct rather than a licence to supersede.
func staffSetEntitlement(c *gin.Context) {
ctx := c.Request.Context()
var body entitlementBody
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid entitlement"})
return
}
var inst models.Instance
if err := db.Admin("admin_instances").FindOne(ctx,
bson.M{"instance_id": c.Param("id")}).Decode(&inst); err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "no such instance"})
return
}
tier := body.Tier
if tier == "" {
tier = inst.Tier
}
plan, err := models.GetPlan(ctx, inst.Deployment, tier)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("no plan for %s/%s", inst.Deployment, tier)})
return
}
if !termSold(inst.Deployment, body.Term) {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("%s does not sell %s", inst.Deployment, body.Term)})
return
}
if body.Servers < plan.BaseLimits.MaxServers &&
plan.BaseLimits.MaxServers != -1 {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("%s includes %d servers; cannot configure fewer",
plan.Name, plan.BaseLimits.MaxServers)})
return
}
desired := models.Config{
Servers: body.Servers,
Features: models.Features(body.Features).OrEmpty(),
}
// Start from whatever is already granted, so writing a desired change never
// silently alters what the instance is currently allowed.
granted := desired
existing, err := models.GetEntitlement(ctx, inst.InstanceID)
switch {
case err == nil:
if !body.Grant {
granted = existing.Granted
}
case errors.Is(err, models.ErrNoEntitlement):
// First write. There is nothing granted to preserve, so desired becomes
// granted — an instance with an entitlement nobody has granted would
// fall back to the plan base at issue time and confuse everyone.
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Only the limits are stored. Features are NOT snapshotted onto the
// entitlement: they live in Granted.Features, and Issue resolves them again
// against the catalogue at signing time. Storing a second copy here would
// give two answers to "which features does this instance have".
limits, _, err := catalogue.Resolve(ctx, plan, granted)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ent := models.Entitlement{
InstanceID: inst.InstanceID,
AccountID: inst.AccountID,
Deployment: inst.Deployment,
Tier: tier,
Term: body.Term,
Desired: desired,
Granted: granted,
ResolvedLimits: limits,
}
// A reduction is a fact about the future, so it carries a date. There is no
// billing period to read yet — plan 5 sets this from the subscription — so
// staff-set reductions are marked as pending without one.
if desired.Servers < granted.Servers {
now := time.Now().UTC()
ent.ScheduledChangeAt = &now
}
if existing != nil {
ent.GrantedAt = existing.GrantedAt
}
if body.Grant {
ent.GrantedAt = time.Now().UTC()
}
if err := models.UpsertEntitlement(ctx, ent); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
audit.Write(ctx, models.AuditEntry{
Actor: auth.Current(c).Email,
Action: "entitlement.updated",
AccountID: inst.AccountID,
Target: inst.InstanceID,
Detail: fmt.Sprintf("tier=%s term=%s desired_servers=%d granted_servers=%d granted=%t",
tier, body.Term, desired.Servers, granted.Servers, body.Grant),
})
c.JSON(http.StatusOK, gin.H{"entitlement": ent, "pending": ent.Pending()})
}
+13 -1
View File
@@ -68,6 +68,10 @@ func Routes(cfg config.Config) http.Handler {
cust.POST("/instances/link", linkInstance)
cust.POST("/instances/:id/relink", relinkInstance)
cust.POST("/instances/:id/renew", renewInstance)
cust.POST("/instances/:id/claim-free",
auth.RequireAccountRole(models.AccountRoleOwner, models.AccountRoleAdmin),
claimFree)
cust.GET("/instances/:id/entitlement", getEntitlement)
cust.GET("/instances/:id/license", getInstanceLicense)
cust.GET("/instances/:id/license/download", downloadInstanceLicense)
cust.GET("/instances/:id/members", listInstanceMembers)
@@ -98,7 +102,15 @@ func Routes(cfg config.Config) http.Handler {
staff.POST("/instances/:id/relink", staffRelink)
staff.GET("/licenses", staffListLicenses)
staff.GET("/plans", staffListPlans)
staff.PUT("/plans/:tier", staffUpdatePlan)
// Plans are keyed on the pair now, so the path is too. A single :tier
// segment could name three rows.
staff.PUT("/plans/:deployment/:tier", staffUpdatePlan)
staff.GET("/catalogue", staffListCatalogue)
staff.PUT("/catalogue", staffUpdateCatalogue)
staff.GET("/instances/:id/entitlement", staffGetEntitlement)
staff.PUT("/instances/:id/entitlement", staffSetEntitlement)
staff.GET("/audit", staffAudit)
staff.GET("/health/injection", staffInjectionHealth)
}
+111 -11
View File
@@ -1,6 +1,7 @@
package api
import (
"fmt"
"net/http"
"strings"
"time"
@@ -393,31 +394,130 @@ func staffListPlans(c *gin.Context) {
c.JSON(http.StatusOK, plans)
}
// staffUpdatePlan changes what a tier grants FROM NOW ON. Existing licences
// snapshotted their plan at issue time and are unaffected — the same rule as
// workflow_runs.steps_snapshot.
// staffUpdatePlan changes what a (deployment, tier) pair grants FROM NOW ON.
// Existing licences snapshotted their plan at issue time and are unaffected —
// the same rule as workflow_runs.steps_snapshot.
//
// It writes no Paddle identifiers: those live in the catalogue, because a
// metered plan is priced by several components.
func staffUpdatePlan(c *gin.Context) {
var body models.Plan
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid plan"})
return
}
deployment, tier := c.Param("deployment"), c.Param("tier")
set := bson.M{
"name": body.Name,
"limits": body.Limits,
"features": body.Features.OrEmpty(),
"paddle_product_id": body.PaddleProductID,
"paddle_price_ids": body.PaddlePriceIDs,
"active": body.Active,
"name": body.Name,
"base_limits": body.BaseLimits,
"base_features": body.BaseFeatures.OrEmpty(),
"support_level": body.SupportLevel,
"active": body.Active,
}
if _, err := db.Admin("plans").UpdateOne(c.Request.Context(),
bson.M{"tier": c.Param("tier")}, bson.M{"$set": set}); err != nil {
res, err := db.Admin("plans").UpdateOne(c.Request.Context(),
bson.M{"deployment": deployment, "tier": tier}, bson.M{"$set": set})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if res.MatchedCount == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "no such plan"})
return
}
audit.Write(c.Request.Context(), models.AuditEntry{
Actor: auth.Current(c).Email,
Action: "plan.updated",
Target: deployment + "/" + tier,
Detail: fmt.Sprintf("servers=%d monitors=%d support=%s active=%t",
body.BaseLimits.MaxServers, body.BaseLimits.MaxMonitors,
body.SupportLevel, body.Active),
})
c.JSON(http.StatusOK, gin.H{"updated": true})
}
func staffListCatalogue(c *gin.Context) {
rows, err := models.AllCatalogue(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, rows)
}
// staffUpdateCatalogue sets the price IDs on one component.
//
// The component is addressed by its natural key rather than by an ObjectID, so
// the staff UI never has to hold a Mongo identifier and a seeded row can be
// updated the moment it exists. Only price IDs are writable: a row's kind, plan
// and key are seeded by SeedCatalogue, and letting a form invent a limit_key
// would let it invent a limit nothing enforces.
func staffUpdateCatalogue(c *gin.Context) {
var body struct {
Kind string `json:"kind"`
Deployment string `json:"deployment"`
Tier string `json:"tier"`
LimitKey string `json:"limit_key"`
FeatureKey string `json:"feature_key"`
PriceIDs map[string]map[string]string `json:"price_ids"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid component"})
return
}
// Refuse a price on a term the deployment does not sell. Storing one would
// mean a resolved self-hosted monthly price later, which the resolver treats
// as a configuration error — better to refuse it at the point somebody
// pastes it, while they are looking at the screen.
for env, byTerm := range body.PriceIDs {
for term, id := range byTerm {
if id == "" {
continue
}
if !termSold(body.Deployment, term) {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("%s does not sell %s (environment %s)",
body.Deployment, term, env)})
return
}
}
}
filter := bson.M{
"kind": body.Kind,
"deployment": body.Deployment,
"tier": body.Tier,
"limit_key": body.LimitKey,
"feature_key": body.FeatureKey,
}
res, err := db.Admin("catalogue").UpdateOne(c.Request.Context(), filter,
bson.M{"$set": bson.M{"price_ids": body.PriceIDs}})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if res.MatchedCount == 0 {
c.JSON(http.StatusNotFound, gin.H{"error": "no such component"})
return
}
audit.Write(c.Request.Context(), models.AuditEntry{
Actor: auth.Current(c).Email,
Action: "catalogue.updated",
Target: body.Deployment + "/" + body.Tier + "/" + body.Kind,
Detail: body.LimitKey + body.FeatureKey,
})
c.JSON(http.StatusOK, gin.H{"updated": true})
}
func termSold(deployment, term string) bool {
for _, t := range license.TermsFor(deployment) {
if t == term {
return true
}
}
return false
}
func staffAudit(c *gin.Context) {
filter := bson.M{}
if v := c.Query("account_id"); v != "" {