feat(clients): cap how many times a client may auto-renew (#6238)

* feat(clients): cap how many times a client may auto-renew

Auto-renew today runs forever: a prepaid or fixed-term client keeps being
handed new periods until an operator remembers to switch it off. There is no
way to say "renew this three times, then let it lapse".

Add a per-client maximum. Zero keeps today's behaviour, so nothing changes for
anyone who does not set one. When the count is reached the client is simply
left to expire, like any client without auto-renew.

Catching up several missed periods spends one allowance per period. A client
that was away for three cycles must not receive three of them free of the cap,
and the catch-up stops at the last period the cap paid for rather than jumping
to the present.

* fix(clients): persist the auto-renew cap and stop the capped churn

resetMax lived only in the inbound settings JSON and client_traffics, so
every path that rebuilds a client from the clients table wrote it back as
zero. The edit dialog showed 0 for a capped client, and saving an
unrelated comment change lifted the cap; an attach or a traffic reset did
the same with no operator action at all.

Adds reset_max to ClientRecord and threads it through ToRecord, ToClient,
applyClientRecordMerge, the record update map and ClientSlim, so the cap
survives the round trip.

When the cap truncates a catch-up the client is still expired, but the
renewal side effects fired anyway: counters were zeroed for periods it
can never use, and it was enabled and pushed to xray only for
disableInvalidClients to undo both in the same transaction. Those are now
skipped when the new expiry has not reached the present.

Also makes any non-positive resetMax mean unlimited instead of silently
meaning "never renew again", rejects a negative one at the service layer,
surfaces renewals used against allowed in the client info modal so the
operator can see what to raise, adds the field to the bulk-add modal,
translates the labels in all 13 locales, and drops the stray
internal/web/dist/.gitkeep build stub.

* fix(clients): let the renewal cap be changed after creation

ClientService.Update writes the record columns directly only for a client
with no inbounds. The normal path goes through SyncInbound and
applyClientRecordMerge, which this change had not extended, so raising a
cap from 3 to 6 — the natural action when a customer buys another block
of periods — updated the inbound settings JSON while clients.reset_max
kept the old value and the renewal query kept enforcing it.

The existing test did not catch it: it asserted the cap survived an
unrelated edit, and it survived precisely because nothing on that path
ever wrote it. TestClientEditChangesTheRenewalCap raises the cap and then
lifts it entirely; removing the record write turns it red.

* chore: drop the accidentally committed dist build stub

internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
it changes fresh-clone behaviour for everyone: today a bare go build fails
loudly on //go:embed all:dist, which is the documented signal to run the stub
target; with the file present the build succeeds and the panel serves an empty
dist instead.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
This commit is contained in:
n0ctal
2026-08-18 14:53:11 +05:00
committed by GitHub
parent 6a674c7f0c
commit e940f30bb8
29 changed files with 508 additions and 27 deletions
+16
View File
@@ -43,6 +43,15 @@ func validateClientSubID(subID string) error {
return nil
}
// Rejected rather than coerced: a negative cap reads as "unlimited" to a caller
// but selects nothing, so the client would silently stop renewing.
func validateClientResetMax(resetMax int) error {
if resetMax < 0 {
return common.NewError("client resetMax must not be negative, got:", resetMax)
}
return nil
}
func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
if payload == nil {
return false, common.NewError("empty payload")
@@ -57,6 +66,9 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate
if err := validateClientSubID(client.SubID); err != nil {
return false, err
}
if err := validateClientResetMax(client.ResetMax); err != nil {
return false, err
}
if len(payload.InboundIds) == 0 {
return false, common.NewError("at least one inbound is required")
}
@@ -344,6 +356,9 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
if err := validateClientSubID(updated.SubID); err != nil {
return false, err
}
if err := validateClientResetMax(updated.ResetMax); err != nil {
return false, err
}
if updated.SubID == "" {
updated.SubID = existing.SubID
}
@@ -466,6 +481,7 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
"tg_id": merged.TgID,
"comment": merged.Comment,
"reset": merged.Reset,
"reset_max": merged.ResetMax,
}).Error; err != nil {
return needRestart, err
}
+1
View File
@@ -63,6 +63,7 @@ func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecor
}
row.Comment = incoming.Comment
row.Reset = incoming.Reset
row.ResetMax = incoming.ResetMax
if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
row.CreatedAt = incoming.CreatedAt
}
+2
View File
@@ -26,6 +26,7 @@ type ClientSlim struct {
LimitIP int `json:"limitIp"`
LimitHwid int `json:"limitHwid"`
Reset int `json:"reset"`
ResetMax int `json:"resetMax"`
Group string `json:"group,omitempty"`
Comment string `json:"comment,omitempty"`
InboundIds []int `json:"inboundIds"`
@@ -605,6 +606,7 @@ func toClientSlim(c ClientWithAttachments) ClientSlim {
LimitIP: c.LimitIP,
LimitHwid: c.LimitHwid,
Reset: c.Reset,
ResetMax: c.ResetMax,
Group: c.Group,
Comment: c.Comment,
InboundIds: c.InboundIds,
@@ -0,0 +1,287 @@
package service
import (
"encoding/json"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// A prepaid plan must stop itself: once as many renewals have fired as the
// operator allowed, the client expires like any other (#5804).
func TestAutoRenewClients_StopsAtMaxCount(t *testing.T) {
setupBulkDB(t)
svc := &InboundService{}
db := database.GetDB()
past := time.Now().Add(-48 * time.Hour).UnixMilli()
clients := []model.Client{
{Email: "spent@x", ID: "11111111-1111-1111-1111-111111111111", Enable: false, Reset: 30, ResetMax: 2, ExpiryTime: past},
{Email: "left@x", ID: "22222222-2222-2222-2222-222222222222", Enable: false, Reset: 30, ResetMax: 2, ExpiryTime: past},
}
ib := mkInbound(t, 30101, model.VLESS, clientsSettings(t, clients))
if err := svc.clientService.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
rows := []xray.ClientTraffic{
{InboundId: ib.Id, Email: "spent@x", Enable: false, Reset: 30, ResetMax: 2, ResetCount: 2, ExpiryTime: past},
{InboundId: ib.Id, Email: "left@x", Enable: false, Reset: 30, ResetMax: 2, ResetCount: 1, ExpiryTime: past},
}
if err := db.Create(&rows).Error; err != nil {
t.Fatalf("seed client_traffics: %v", err)
}
if _, count, err := svc.autoRenewClients(db, newTrafficMutationBatch()); err != nil {
t.Fatalf("autoRenewClients: %v", err)
} else if count != 1 {
t.Fatalf("renewed count = %d, want 1: only the client with an allowance left", count)
}
var spent xray.ClientTraffic
if err := db.Where("email = ?", "spent@x").First(&spent).Error; err != nil {
t.Fatal(err)
}
if spent.ExpiryTime != past {
t.Fatalf("a client that used its allowance was renewed anyway: expiry %d", spent.ExpiryTime)
}
var left xray.ClientTraffic
if err := db.Where("email = ?", "left@x").First(&left).Error; err != nil {
t.Fatal(err)
}
if left.ExpiryTime <= past {
t.Fatal("a client with an allowance left was not renewed")
}
if left.ResetCount != 2 {
t.Fatalf("reset count = %d after one renewal, want 2", left.ResetCount)
}
}
// Catching up several missed periods spends one allowance per period: a client
// that was away for three cycles must not receive three of them for free.
func TestAutoRenewClients_CatchUpSpendsOneAllowancePerPeriod(t *testing.T) {
setupBulkDB(t)
svc := &InboundService{}
db := database.GetDB()
// Three whole 30-day periods behind.
past := time.Now().Add(-95 * 24 * time.Hour).UnixMilli()
clients := []model.Client{
{Email: "away@x", ID: "33333333-3333-3333-3333-333333333333", Enable: false, Reset: 30, ResetMax: 2, ExpiryTime: past},
}
ib := mkInbound(t, 30102, model.VLESS, clientsSettings(t, clients))
if err := svc.clientService.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
if err := db.Create(&xray.ClientTraffic{
InboundId: ib.Id, Email: "away@x", Enable: false, Reset: 30, ResetMax: 2, ExpiryTime: past,
}).Error; err != nil {
t.Fatalf("seed client_traffics: %v", err)
}
if _, _, err := svc.autoRenewClients(db, newTrafficMutationBatch()); err != nil {
t.Fatalf("autoRenewClients: %v", err)
}
var row xray.ClientTraffic
if err := db.Where("email = ?", "away@x").First(&row).Error; err != nil {
t.Fatal(err)
}
if row.ResetCount != 2 {
t.Fatalf("reset count = %d, want the 2 the cap allowed", row.ResetCount)
}
// Two periods granted, three needed: the client stays expired rather than
// silently receiving the third.
want := past + 2*30*86400000
if row.ExpiryTime != want {
t.Fatalf("expiry = %d, want %d: exactly the periods the cap paid for", row.ExpiryTime, want)
}
if row.ExpiryTime > time.Now().UnixMilli() {
t.Fatal("the capped catch-up handed out a future expiry it had not paid for")
}
}
// No cap set is the existing behaviour: renew for as long as the client keeps
// expiring.
func TestAutoRenewClients_NoCapRenewsAsBefore(t *testing.T) {
setupBulkDB(t)
svc := &InboundService{}
db := database.GetDB()
past := time.Now().Add(-48 * time.Hour).UnixMilli()
clients := []model.Client{
{Email: "forever@x", ID: "44444444-4444-4444-4444-444444444444", Enable: false, Reset: 30, ExpiryTime: past},
}
ib := mkInbound(t, 30103, model.VLESS, clientsSettings(t, clients))
if err := svc.clientService.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
if err := db.Create(&xray.ClientTraffic{
InboundId: ib.Id, Email: "forever@x", Enable: false, Reset: 30, ResetCount: 99, ExpiryTime: past,
}).Error; err != nil {
t.Fatalf("seed client_traffics: %v", err)
}
if _, count, err := svc.autoRenewClients(db, newTrafficMutationBatch()); err != nil {
t.Fatalf("autoRenewClients: %v", err)
} else if count != 1 {
t.Fatalf("renewed count = %d, want 1: a client without a cap keeps renewing", count)
}
}
// The cap has to survive the clients table, not just the settings JSON: an
// ordinary edit rebuilds the client from the record and writes it back (#5804).
func TestClientEditKeepsTheRenewalCap(t *testing.T) {
setupBulkDB(t)
svc := &InboundService{}
db := database.GetDB()
clients := []model.Client{
{Email: "cap@x", ID: "44444444-4444-4444-4444-444444444444", Enable: true, Reset: 30, ResetMax: 3, ExpiryTime: time.Now().Add(24 * time.Hour).UnixMilli()},
}
ib := mkInbound(t, 30104, model.VLESS, clientsSettings(t, clients))
if err := svc.clientService.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
mkTraffic(t, ib.Id, "cap@x", 10, 20, 0, 0, true)
rec, err := svc.clientService.GetRecordByEmail(nil, "cap@x")
if err != nil {
t.Fatalf("GetRecordByEmail: %v", err)
}
if rec.ResetMax != 3 {
t.Fatalf("clients.reset_max = %d, want the 3 the client was created with", rec.ResetMax)
}
// What the edit dialog does: hydrate the record, change something else, save.
edited := rec.ToClient()
edited.Comment = "renamed"
if _, err := svc.clientService.Update(svc, rec.Id, *edited, rec.LimitHwid); err != nil {
t.Fatalf("Update: %v", err)
}
var stored model.Inbound
if err := db.Where("id = ?", ib.Id).First(&stored).Error; err != nil {
t.Fatal(err)
}
var settings struct {
Clients []model.Client `json:"clients"`
}
if err := json.Unmarshal([]byte(stored.Settings), &settings); err != nil {
t.Fatalf("parse inbound settings: %v", err)
}
if len(settings.Clients) != 1 {
t.Fatalf("inbound holds %d clients, want 1", len(settings.Clients))
}
if settings.Clients[0].ResetMax != 3 {
t.Fatalf("inbound settings resetMax = %d after an unrelated edit, want 3: the cap was silently lifted", settings.Clients[0].ResetMax)
}
rec, err = svc.clientService.GetRecordByEmail(nil, "cap@x")
if err != nil {
t.Fatalf("GetRecordByEmail after edit: %v", err)
}
if rec.ResetMax != 3 {
t.Fatalf("clients.reset_max = %d after an unrelated edit, want 3", rec.ResetMax)
}
}
// A cap that runs out mid-catch-up leaves the client expired, so the renewal
// side effects must not fire: disableInvalidClients would undo them at once.
func TestAutoRenewClients_TruncatedCatchUpLeavesTheClientDisabled(t *testing.T) {
setupBulkDB(t)
svc := &InboundService{}
db := database.GetDB()
// Five periods behind with one allowance left: one 30-day step cannot reach
// the present, so the client stays expired.
past := time.Now().Add(-150 * 24 * time.Hour).UnixMilli()
clients := []model.Client{
{Email: "short@x", ID: "55555555-5555-5555-5555-555555555555", Enable: false, Reset: 30, ResetMax: 3, ExpiryTime: past},
}
ib := mkInbound(t, 30105, model.VLESS, clientsSettings(t, clients))
if err := svc.clientService.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
if err := db.Create(&xray.ClientTraffic{
InboundId: ib.Id, Email: "short@x", Enable: false, Reset: 30, ResetMax: 3, ResetCount: 2,
Up: 111, Down: 222, ExpiryTime: past,
}).Error; err != nil {
t.Fatalf("seed client_traffics: %v", err)
}
if _, _, err := svc.autoRenewClients(db, newTrafficMutationBatch()); err != nil {
t.Fatalf("autoRenewClients: %v", err)
}
var row xray.ClientTraffic
if err := db.Where("email = ?", "short@x").First(&row).Error; err != nil {
t.Fatal(err)
}
if row.ExpiryTime >= time.Now().UnixMilli() {
t.Fatalf("expiry %d reached the present: the cap did not truncate the catch-up", row.ExpiryTime)
}
if row.Enable {
t.Fatal("a client still expired after a truncated catch-up was enabled: xray gains a user only to lose it again")
}
if row.Up != 111 || row.Down != 222 {
t.Fatalf("counters zeroed for periods the client can never use: up=%d down=%d", row.Up, row.Down)
}
}
// The cap is useless if it can only be chosen once. The test above passes even
// without the record write, because nothing overwrites the value it checks.
func TestClientEditChangesTheRenewalCap(t *testing.T) {
setupBulkDB(t)
svc := &InboundService{}
clients := []model.Client{
{
Email: "chg@x", ID: "77777777-7777-7777-7777-777777777777", Enable: true, Reset: 30, ResetMax: 3,
ExpiryTime: time.Now().Add(24 * time.Hour).UnixMilli(),
},
}
ib := mkInbound(t, 30106, model.VLESS, clientsSettings(t, clients))
if err := svc.clientService.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
mkTraffic(t, ib.Id, "chg@x", 0, 0, 0, 0, true)
rec, err := svc.clientService.GetRecordByEmail(nil, "chg@x")
if err != nil {
t.Fatalf("GetRecordByEmail: %v", err)
}
// The customer buys another block of periods, which is the whole point of
// the field being editable.
edited := rec.ToClient()
edited.ResetMax = 6
if _, err := svc.clientService.Update(svc, rec.Id, *edited, rec.LimitHwid); err != nil {
t.Fatalf("Update: %v", err)
}
rec, err = svc.clientService.GetRecordByEmail(nil, "chg@x")
if err != nil {
t.Fatalf("GetRecordByEmail after edit: %v", err)
}
if rec.ResetMax != 6 {
t.Fatalf("clients.reset_max = %d after the operator raised the cap to 6", rec.ResetMax)
}
// Lifting the cap entirely has to work too.
edited = rec.ToClient()
edited.ResetMax = 0
if _, err := svc.clientService.Update(svc, rec.Id, *edited, rec.LimitHwid); err != nil {
t.Fatalf("Update to uncapped: %v", err)
}
rec, err = svc.clientService.GetRecordByEmail(nil, "chg@x")
if err != nil {
t.Fatalf("GetRecordByEmail after lifting the cap: %v", err)
}
if rec.ResetMax != 0 {
t.Fatalf("clients.reset_max = %d after the operator lifted the cap", rec.ResetMax)
}
}
+23 -1
View File
@@ -334,6 +334,9 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
// local inbounds. The email-based join through client_inbounds is authoritative.
err = tx.Model(xray.ClientTraffic{}).
Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
// A prepaid plan stops itself: once as many renewals have fired as the
// operator allowed, the client is left to expire like any other.
Where("reset_max <= 0 or reset_count < reset_max").
Where("email IN (?)", tx.Table("client_inbounds ci").
Select("c.email").
Joins("JOIN clients c ON c.id = ci.client_id").
@@ -411,12 +414,29 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
if !ok {
continue
}
// One allowance per period, not per tick: a client away for three
// cycles must not catch up three of them against a prepaid cap.
newExpiryTime := traffic.ExpiryTime
renewals := 0
for newExpiryTime < now {
if traffic.ResetMax > 0 && traffic.ResetCount+renewals >= traffic.ResetMax {
break
}
newExpiryTime += (int64(traffic.Reset) * 86400000)
renewals++
}
if renewals == 0 {
continue
}
c["expiryTime"] = newExpiryTime
traffic.ExpiryTime = newExpiryTime
traffic.ResetCount += renewals
if newExpiryTime <= now {
// Cap ran out mid-catch-up and the client is still expired: enabling it
// for disableInvalidClients to undo adds and removes an xray user for nothing.
clients[client_index] = any(c)
continue
}
traffic.Down = 0
traffic.Up = 0
if !traffic.Enable {
@@ -508,10 +528,11 @@ func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model
ExpiryTime: client.ExpiryTime,
Enable: client.Enable,
Reset: client.Reset,
ResetMax: client.ResetMax,
}
return tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "email"}},
DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset"}),
DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset", "reset_max"}),
}).Create(&clientTraffic).Error
}
@@ -524,6 +545,7 @@ func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *mod
"total": client.TotalGB,
"expiry_time": client.ExpiryTime,
"reset": client.Reset,
"reset_max": client.ResetMax,
})
err := result.Error
return err