feat(clients): support setting HWID limit and MTProto ad-tag in bulk adjust (#6399)

* feat(clients): support setting HWID limit and MTProto ad-tag in bulk adjust

Add HWID device limit and Telegram MTProto sponsor channel (ad-tag)
support to the bulk client adjustment flow in both the panel API
and frontend ClientBulkAdjustModal.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(clients): gate adTag to MTProto inbounds and avoid inbound rewrite for limitHwid

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(clients): stamp updated_at only on the clients a bulk adjust changed

The updated_at write was gated on hasInboundChanges, which accumulates
over the whole inbound instead of describing the client in hand. Once any
client in the settings array changed, every client after it was re-stamped
as well, so whether an untouched client kept its own updated_at depended on
its position in the array. That field feeds node-snapshot conflict
resolution, where a spurious bump lets a stale snapshot value win over the
stored record.

Track the change per client and fold it into the inbound-level flag where
the stamp is written, so the early return still skips a save whose settings
JSON would be unchanged.

Also condenses the BulkAdjust doc comment back to the two-line maximum.

* docs(api): regenerate the bulkAdjust reference for limitHwid and adTag

frontend/public/openapi.json was copied to docs/public/, but pnpm gen:api
was never re-run, so the API reference page's heading, anchor id and search
index still described bulkAdjust without limitHwid or adTag. docs-ci.yml
fires only on docs/**, and that path had been touched, so nothing flagged
the stale MDX.

The externalLinks hunks are the generator rewrapping lines main had left
stale, not a content change.

* fix(i18n): stop enumerating fields in the bulk-adjust empty-form message

bulkAdjustNothing listed the fields the form accepts, so it went stale
every time one was added: only en-US ever gained "flow", leaving the other
twelve locales describing days and traffic alone, and limitHwid and adTag
would have repeated that. Say that one field is required instead of naming
which, so the message cannot drift again.
This commit is contained in:
Rouzbeh†
2026-09-10 17:54:48 +03:30
committed by GitHub
parent 1456658028
commit ed5465d0f2
29 changed files with 626 additions and 121 deletions
+130 -36
View File
@@ -312,11 +312,13 @@ var bulkFlowAllowed = map[string]struct{}{
// for every email in the list. Clients whose corresponding field is
// unlimited (0) are skipped — bulk extend should not accidentally
// limit an unlimited client. addDays and addBytes may be negative.
// flow sets the XTLS flow, limitHwid the max registered devices (0 = unlimited)
// and adTag the MTProto sponsor channel; "none" clears flow or adTag.
//
// Like BulkDelete, the work is grouped by inbound so each inbound's
// settings JSON is parsed and written exactly once regardless of how
// many target emails it contains.
func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64, flow string) (BulkAdjustResult, bool, error) {
func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
result := BulkAdjustResult{}
if len(emails) == 0 {
return result, false, nil
@@ -325,8 +327,18 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
if _, ok := bulkFlowAllowed[flow]; !ok {
flow = "" // ignore unknown directives — "" means "leave flow untouched"
}
adTag = strings.TrimSpace(adTag)
if adTag != "" && adTag != bulkFlowClear && !model.ValidMtprotoAdTag(adTag) {
return result, false, common.NewError("mtproto client ad tag must be 32 hex characters")
}
if limitHwid != nil && *limitHwid < 0 {
zero := 0
limitHwid = &zero
}
adjustFlow := flow != ""
if addDays == 0 && addBytes == 0 && !adjustFlow {
adjustHwid := limitHwid != nil
adjustAdTag := adTag != ""
if addDays == 0 && addBytes == 0 && !adjustFlow && !adjustHwid && !adjustAdTag {
return result, false, common.NewError("no adjustment specified")
}
@@ -419,7 +431,7 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
}
}
}
if entry.applyExpiry || entry.applyTotal || adjustFlow {
if entry.applyExpiry || entry.applyTotal || adjustFlow || adjustHwid || adjustAdTag {
plan[email] = entry
}
}
@@ -434,8 +446,10 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
plannedIds := make([]int, 0, len(plan))
recordIdToEmail := make(map[int]string, len(plan))
for email, entry := range plan {
plannedIds = append(plannedIds, entry.record.Id)
recordIdToEmail[entry.record.Id] = email
if entry.applyExpiry || entry.applyTotal || adjustFlow || adjustAdTag {
plannedIds = append(plannedIds, entry.record.Id)
recordIdToEmail[entry.record.Id] = email
}
}
var mappings []model.ClientInbound
@@ -458,10 +472,12 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
needRestart := false
flowHonored := map[string]bool{}
flowIneligible := map[string]bool{}
adTagHonored := map[string]bool{}
adTagIneligible := map[string]bool{}
execFailed := map[string]bool{}
adjustIds := sortedInboundIds(emailsByInbound)
adjustResults, adjustPanics := fanoutInboundResults(adjustIds, inboundFanoutConcurrency, func(i int) bulkInboundAdjustResult {
return s.bulkAdjustInboundClients(inboundSvc, adjustIds[i], emailsByInbound[adjustIds[i]], plan, flow)
return s.bulkAdjustInboundClients(inboundSvc, adjustIds[i], emailsByInbound[adjustIds[i]], plan, flow, adTag)
})
for i, ibRes := range adjustResults {
if adjustPanics[i] != nil {
@@ -483,6 +499,12 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
for email := range ibRes.flowIneligible {
flowIneligible[email] = true
}
for email := range ibRes.adTagHonored {
adTagHonored[email] = true
}
for email := range ibRes.adTagIneligible {
adTagIneligible[email] = true
}
for email, reason := range ibRes.perEmailSkipped {
execFailed[email] = true
if _, already := skippedReasons[email]; !already {
@@ -511,6 +533,11 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
}
}
wantAdTag := ""
if adjustAdTag && adTag != bulkFlowClear {
wantAdTag = strings.ToLower(adTag)
}
adjusted := map[string]struct{}{}
for email, entry := range plan {
if execFailed[email] {
@@ -531,9 +558,24 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
continue
}
}
// Counted when expiry/total changed, or a flow directive was honored
// for this client (flow lives in the inbound JSON, not ClientTraffic).
if len(updates) > 0 || flowHonored[email] {
if adjustHwid {
if err := s.setClientLimitHwidByEmail(db, email, *limitHwid); err != nil {
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = err.Error()
}
continue
}
}
if adjustAdTag && adTagHonored[email] {
if err := db.Model(&model.ClientRecord{}).Where("email = ?", email).UpdateColumn("ad_tag", wantAdTag).Error; err != nil {
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = err.Error()
}
continue
}
}
// Counted when expiry/total changed, flow was honored, adTag was honored, or limitHwid was adjusted.
if len(updates) > 0 || flowHonored[email] || adTagHonored[email] || adjustHwid {
adjusted[email] = struct{}{}
}
}
@@ -554,6 +596,15 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
}
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "flow not supported on inbound"})
}
for email := range adTagIneligible {
if adTagHonored[email] {
continue
}
if _, already := skippedReasons[email]; already {
continue
}
result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "adTag not supported on inbound"})
}
if len(wasDisabledDepleted) > 0 {
stillDepleted := map[string]struct{}{}
@@ -599,8 +650,10 @@ type bulkInboundAdjustResult struct {
// that an inbound cannot carry must not suppress the expiry/total write for
// the same client (which would diverge the inbound JSON / ClientRecord from
// ClientTraffic). It only feeds the final Skipped report.
flowIneligible map[string]bool
needRestart bool
flowIneligible map[string]bool
adTagHonored map[string]bool
adTagIneligible map[string]bool
needRestart bool
}
// bulkAdjustInboundClients applies expiry/total deltas to multiple clients
@@ -615,8 +668,15 @@ func (s *ClientService) bulkAdjustInboundClients(
emails []string,
plan map[string]*bulkAdjustEntry,
flow string,
adTag string,
) bulkInboundAdjustResult {
res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}, flowHonored: map[string]bool{}, flowIneligible: map[string]bool{}}
res := bulkInboundAdjustResult{
perEmailSkipped: map[string]string{},
flowHonored: map[string]bool{},
flowIneligible: map[string]bool{},
adTagHonored: map[string]bool{},
adTagIneligible: map[string]bool{},
}
defer lockInbound(inboundId).Unlock()
@@ -655,9 +715,16 @@ func (s *ClientService) bulkAdjustInboundClients(
(!oldInbound.DisableFlow &&
inboundCanEnableTlsFlow(string(oldInbound.Protocol), oldInbound.StreamSettings, oldInbound.Settings))
wantAdTag := ""
if adTag != "" && adTag != bulkFlowClear {
wantAdTag = strings.ToLower(adTag)
}
interfaceClients, _ := settings["clients"].([]any)
foundEmails := map[string]bool{}
flowChanged := false
adTagChanged := false
hasInboundChanges := false
nowMs := time.Now().Unix() * 1000
for i, client := range interfaceClients {
c, ok := client.(map[string]any)
@@ -668,12 +735,15 @@ func (s *ClientService) bulkAdjustInboundClients(
if _, want := wantedEmails[targetEmail]; !want || targetEmail == "" {
continue
}
clientChanged := false
entry := plan[targetEmail]
if entry.applyExpiry {
c["expiryTime"] = entry.newExpiry
clientChanged = true
}
if entry.applyTotal {
c["totalGB"] = entry.newTotal
clientChanged = true
}
if flow != "" {
if flowEligible {
@@ -686,13 +756,29 @@ func (s *ClientService) bulkAdjustInboundClients(
flowChanged = true
}
res.flowHonored[targetEmail] = true
clientChanged = true
} else {
// Record separately so this never suppresses the expiry/total
// write for the same client (see flowIneligible doc).
res.flowIneligible[targetEmail] = true
}
}
c["updated_at"] = nowMs
if adTag != "" {
if oldInbound.Protocol == model.MTProto {
if cur, _ := c["adTag"].(string); cur != wantAdTag {
c["adTag"] = wantAdTag
adTagChanged = true
}
res.adTagHonored[targetEmail] = true
clientChanged = true
} else {
res.adTagIneligible[targetEmail] = true
}
}
if clientChanged {
c["updated_at"] = nowMs
hasInboundChanges = true
}
interfaceClients[i] = c
foundEmails[targetEmail] = true
}
@@ -703,7 +789,7 @@ func (s *ClientService) bulkAdjustInboundClients(
}
}
if len(foundEmails) == 0 {
if len(foundEmails) == 0 || !hasInboundChanges {
return res
}
@@ -748,28 +834,36 @@ func (s *ClientService) bulkAdjustInboundClients(
res.perEmailSkipped[email] = txErr.Error()
}
}
} else if oldInbound.NodeID != nil && !flowChanged && len(foundEmails) <= nodeBulkPushThreshold {
rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
if perr != nil {
logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr)
} else if push {
for email := range foundEmails {
entry := plan[email]
updated := *entry.record.ToClient()
if entry.applyExpiry {
updated.ExpiryTime = entry.newExpiry
}
if entry.applyTotal {
updated.TotalGB = entry.newTotal
}
updated.UpdatedAt = nowMs
ctx, cancel := nodePushContext()
err1 := rt.UpdateUser(ctx, oldInbound, email, updated)
cancel()
if err1 != nil {
logger.Warning("Error in updating client on", rt.Name(), ":", err1)
// First failure ends the batch push; the reconcile converges the rest.
break
} else {
if adTagChanged && oldInbound.Protocol == model.MTProto && oldInbound.NodeID == nil {
inboundSvc.applyLocalMtproto(oldInbound.Id)
}
if oldInbound.NodeID != nil && !flowChanged && len(foundEmails) <= nodeBulkPushThreshold {
rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
if perr != nil {
logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr)
} else if push {
for email := range foundEmails {
entry := plan[email]
updated := *entry.record.ToClient()
if entry.applyExpiry {
updated.ExpiryTime = entry.newExpiry
}
if entry.applyTotal {
updated.TotalGB = entry.newTotal
}
if adTag != "" && oldInbound.Protocol == model.MTProto {
updated.AdTag = wantAdTag
}
updated.UpdatedAt = nowMs
ctx, cancel := nodePushContext()
err1 := rt.UpdateUser(ctx, oldInbound, email, updated)
cancel()
if err1 != nil {
logger.Warning("Error in updating client on", rt.Name(), ":", err1)
// First failure ends the batch push; the reconcile converges the rest.
break
}
}
}
}
@@ -77,7 +77,7 @@ func TestBulkAdjustAcrossNodesPushesConcurrently(t *testing.T) {
}
bar.arm()
if _, _, err := (&ClientService{}).BulkAdjust(&InboundService{}, []string{email}, 1, 0, ""); err != nil {
if _, _, err := (&ClientService{}).BulkAdjust(&InboundService{}, []string{email}, 1, 0, "", nil, ""); err != nil {
t.Fatalf("BulkAdjust across %d node inbounds: %v", nodes, err)
}
if got := bar.updateUser.Load(); got == 0 {
+323 -7
View File
@@ -1,6 +1,7 @@
package service
import (
"encoding/json"
"testing"
"time"
@@ -64,7 +65,7 @@ func TestBulkAdjust_FlowSetAndClear(t *testing.T) {
emails := emailsOf(clients)
// Set vision flow.
res, restart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "xtls-rprx-vision-udp443")
res, restart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "xtls-rprx-vision-udp443", nil, "")
if err != nil {
t.Fatalf("BulkAdjust set: %v", err)
}
@@ -81,14 +82,14 @@ func TestBulkAdjust_FlowSetAndClear(t *testing.T) {
}
// Setting the same flow again is a no-op: honored (counted) but no restart.
if _, restart2, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "xtls-rprx-vision-udp443"); err != nil {
if _, restart2, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "xtls-rprx-vision-udp443", nil, ""); err != nil {
t.Fatalf("BulkAdjust idempotent: %v", err)
} else if restart2 {
t.Fatalf("re-setting identical flow should not request a restart")
}
// Clear flow.
cres, crestart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "none")
cres, crestart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "none", nil, "")
if err != nil {
t.Fatalf("BulkAdjust clear: %v", err)
}
@@ -121,7 +122,7 @@ func TestBulkAdjust_FlowIneligibleSkipped(t *testing.T) {
t.Fatalf("seed: %v", err)
}
res, restart, err := svc.BulkAdjust(inboundSvc, []string{"ws1@x"}, 0, 0, "xtls-rprx-vision")
res, restart, err := svc.BulkAdjust(inboundSvc, []string{"ws1@x"}, 0, 0, "xtls-rprx-vision", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -146,11 +147,11 @@ func TestBulkAdjust_NoDirectiveErrors(t *testing.T) {
svc := &ClientService{}
inboundSvc := &InboundService{}
if _, _, err := svc.BulkAdjust(inboundSvc, []string{"any@x"}, 0, 0, ""); err == nil {
if _, _, err := svc.BulkAdjust(inboundSvc, []string{"any@x"}, 0, 0, "", nil, ""); err == nil {
t.Fatalf("expected error when no adjustment is specified")
}
// An unknown flow directive is ignored (treated as ""), so it also errors.
if _, _, err := svc.BulkAdjust(inboundSvc, []string{"any@x"}, 0, 0, "bogus-flow"); err == nil {
if _, _, err := svc.BulkAdjust(inboundSvc, []string{"any@x"}, 0, 0, "bogus-flow", nil, ""); err == nil {
t.Fatalf("unknown flow should be ignored and error like an empty directive")
}
}
@@ -182,7 +183,7 @@ func TestBulkAdjust_DaysApplyDespiteIneligibleFlow(t *testing.T) {
t.Fatalf("seed traffic: %v", err)
}
res, _, err := svc.BulkAdjust(inboundSvc, []string{"mix@x"}, 7, gb, "xtls-rprx-vision")
res, _, err := svc.BulkAdjust(inboundSvc, []string{"mix@x"}, 7, gb, "xtls-rprx-vision", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -217,3 +218,318 @@ func TestBulkAdjust_DaysApplyDespiteIneligibleFlow(t *testing.T) {
t.Fatalf("flow should stay empty on ineligible inbound, got %q", got)
}
}
// TestBulkAdjust_HwidLimit verifies setting and clearing HWID limit in bulk.
func TestBulkAdjust_HwidLimit(t *testing.T) {
setupBulkDB(t)
svc := &ClientService{}
inboundSvc := &InboundService{}
clients := []model.Client{
{Email: "h1@x", ID: "11111111-1111-1111-1111-111111111111", SubID: "sub-h1", Enable: true},
{Email: "h2@x", ID: "22222222-2222-2222-2222-222222222222", SubID: "sub-h2", Enable: true},
}
ib := mkInbound(t, 30301, model.VLESS, clientsSettings(t, clients))
if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("seed: %v", err)
}
emails := emailsOf(clients)
limit2 := 2
res, restart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "", &limit2, "")
if err != nil {
t.Fatalf("BulkAdjust hwid: %v", err)
}
if res.Adjusted != 2 {
t.Fatalf("expected 2 adjusted, got %d", res.Adjusted)
}
if restart {
t.Fatalf("hwid adjustment should not request xray restart")
}
for _, e := range emails {
rec, rErr := svc.GetRecordByEmail(nil, e)
if rErr != nil || rec.LimitHwid != 2 {
t.Fatalf("%s limitHwid = %d (err=%v), want 2", e, rec.LimitHwid, rErr)
}
}
// Reset to 0 (unlimited)
limit0 := 0
res0, _, err0 := svc.BulkAdjust(inboundSvc, emails, 0, 0, "", &limit0, "")
if err0 != nil || res0.Adjusted != 2 {
t.Fatalf("BulkAdjust hwid 0: err=%v, res=%+v", err0, res0)
}
for _, e := range emails {
rec, _ := svc.GetRecordByEmail(nil, e)
if rec.LimitHwid != 0 {
t.Fatalf("%s limitHwid = %d, want 0", e, rec.LimitHwid)
}
}
}
// TestBulkAdjust_MtprotoAdTagSetAndClear verifies ad-tag bulk update and clearing.
func TestBulkAdjust_MtprotoAdTagSetAndClear(t *testing.T) {
setupBulkDB(t)
svc := &ClientService{}
inboundSvc := &InboundService{}
const tag1 = "0123456789abcdef0123456789abcdef"
clients := []model.Client{
{Email: "tg1@x", Secret: "ee00112233445566778899aabbccddeeff6578616d706c652e636f6d", Enable: true},
{Email: "tg2@x", Secret: "ee101112131415161718191a1b1c1d1e1f6578616d706c652e636f6d", Enable: true},
}
ib := &model.Inbound{
Tag: "mtproto-bulk-test",
Enable: true,
Port: 30401,
Protocol: model.MTProto,
Settings: clientsSettings(t, clients),
}
if err := database.GetDB().Create(ib).Error; err != nil {
t.Fatalf("create mtproto inbound: %v", err)
}
if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("seed mtproto: %v", err)
}
emails := emailsOf(clients)
// Set ad-tag
res, restart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "", nil, tag1)
if err != nil {
t.Fatalf("BulkAdjust adTag: %v", err)
}
if res.Adjusted != 2 {
t.Fatalf("expected 2 adjusted, got %d", res.Adjusted)
}
if restart {
t.Fatalf("mtproto adTag update should not request xray restart")
}
for _, e := range emails {
rec, _ := svc.GetRecordByEmail(nil, e)
if rec.AdTag != tag1 {
t.Fatalf("%s adTag = %q, want %q", e, rec.AdTag, tag1)
}
}
// Clear ad-tag with "none"
cres, _, cerr := svc.BulkAdjust(inboundSvc, emails, 0, 0, "", nil, "none")
if cerr != nil || cres.Adjusted != 2 {
t.Fatalf("BulkAdjust clear adTag: err=%v, res=%+v", cerr, cres)
}
for _, e := range emails {
rec, _ := svc.GetRecordByEmail(nil, e)
if rec.AdTag != "" {
t.Fatalf("%s adTag = %q, want empty after clear", e, rec.AdTag)
}
}
// Invalid ad-tag errors
if _, _, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "", nil, "invalid-hex"); err == nil {
t.Fatalf("expected error for invalid hex ad tag")
}
}
// TestBulkAdjust_AdTagIneligibleSkipped verifies that non-MTProto clients are
// refused adTag adjustment, reported as skipped, and their ClientRecord is untouched.
func TestBulkAdjust_AdTagIneligibleSkipped(t *testing.T) {
setupBulkDB(t)
svc := &ClientService{}
inboundSvc := &InboundService{}
clients := []model.Client{
{Email: "vless-notg@x", ID: "55555555-5555-5555-5555-555555555555", SubID: "vless-notg", Enable: true},
}
ib := mkInbound(t, 30501, model.VLESS, clientsSettings(t, clients))
if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("seed: %v", err)
}
const tag1 = "0123456789abcdef0123456789abcdef"
res, restart, err := svc.BulkAdjust(inboundSvc, []string{"vless-notg@x"}, 0, 0, "", nil, tag1)
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
if res.Adjusted != 0 {
t.Fatalf("ineligible protocol should adjust nothing, got %d", res.Adjusted)
}
if restart {
t.Fatalf("no change should not request restart")
}
if len(res.Skipped) != 1 || res.Skipped[0].Email != "vless-notg@x" || res.Skipped[0].Reason != "adTag not supported on inbound" {
t.Fatalf("expected vless-notg@x in skipped with 'adTag not supported on inbound', got %+v", res.Skipped)
}
rec, err := svc.GetRecordByEmail(nil, "vless-notg@x")
if err != nil {
t.Fatalf("GetRecordByEmail: %v", err)
}
if rec.AdTag != "" {
t.Fatalf("adTag on non-MTProto record should stay empty, got %q", rec.AdTag)
}
}
// TestBulkAdjust_DaysApplyDespiteIneligibleAdTag verifies that when a non-MTProto
// client is adjusted with both days and adTag, days are applied but adTag is not
// written to ClientRecord and is reported as skipped.
func TestBulkAdjust_DaysApplyDespiteIneligibleAdTag(t *testing.T) {
setupBulkDB(t)
svc := &ClientService{}
inboundSvc := &InboundService{}
const day = int64(24 * 60 * 60 * 1000)
baseExpiry := time.Now().UnixMilli() + 30*day
clients := []model.Client{
{Email: "vless-days@x", ID: "66666666-6666-6666-6666-666666666666", SubID: "vless-days", Enable: true, ExpiryTime: baseExpiry},
}
ib := mkInbound(t, 30601, model.VLESS, clientsSettings(t, clients))
if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("seed: %v", err)
}
if err := database.GetDB().Create(&xray.ClientTraffic{Email: "vless-days@x", Enable: true, ExpiryTime: baseExpiry}).Error; err != nil {
t.Fatalf("seed traffic: %v", err)
}
const tag1 = "0123456789abcdef0123456789abcdef"
res, _, err := svc.BulkAdjust(inboundSvc, []string{"vless-days@x"}, 7, 0, "", nil, tag1)
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
if res.Adjusted != 1 {
t.Fatalf("days should still be applied: Adjusted=%d skipped=%v", res.Adjusted, res.Skipped)
}
if len(res.Skipped) != 1 || res.Skipped[0].Email != "vless-days@x" || res.Skipped[0].Reason != "adTag not supported on inbound" {
t.Fatalf("expected vless-days@x reported for unhonored adTag, got %v", res.Skipped)
}
rec, err := svc.GetRecordByEmail(nil, "vless-days@x")
if err != nil {
t.Fatalf("record: %v", err)
}
if rec.ExpiryTime != baseExpiry+7*day {
t.Fatalf("expiry time not advanced: got %d, want %d", rec.ExpiryTime, baseExpiry+7*day)
}
if rec.AdTag != "" {
t.Fatalf("adTag should remain empty on ClientRecord for non-MTProto, got %q", rec.AdTag)
}
}
// TestBulkAdjust_MixedMtprotoAndVless_AdTag verifies bulk adjust over a mixed
// MTProto and VLESS selection.
func TestBulkAdjust_MixedMtprotoAndVless_AdTag(t *testing.T) {
setupBulkDB(t)
svc := &ClientService{}
inboundSvc := &InboundService{}
const tag1 = "0123456789abcdef0123456789abcdef"
tgClients := []model.Client{
{Email: "tg-mix@x", Secret: "ee00112233445566778899aabbccddeeff6578616d706c652e636f6d", Enable: true},
}
tgIb := &model.Inbound{
Tag: "mtproto-mix",
Enable: true,
Port: 30701,
Protocol: model.MTProto,
Settings: clientsSettings(t, tgClients),
}
if err := database.GetDB().Create(tgIb).Error; err != nil {
t.Fatalf("create mtproto: %v", err)
}
if err := svc.SyncInbound(nil, tgIb.Id, tgClients); err != nil {
t.Fatalf("sync mtproto: %v", err)
}
vlessClients := []model.Client{
{Email: "vless-mix@x", ID: "77777777-7777-7777-7777-777777777777", SubID: "vless-mix", Enable: true},
}
vlessIb := mkInbound(t, 30702, model.VLESS, clientsSettings(t, vlessClients))
if err := svc.SyncInbound(nil, vlessIb.Id, vlessClients); err != nil {
t.Fatalf("sync vless: %v", err)
}
emails := []string{"tg-mix@x", "vless-mix@x"}
res, restart, err := svc.BulkAdjust(inboundSvc, emails, 0, 0, "", nil, tag1)
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
if res.Adjusted != 1 {
t.Fatalf("expected 1 adjusted (MTProto only), got %d", res.Adjusted)
}
if restart {
t.Fatalf("adTag should not restart xray")
}
if len(res.Skipped) != 1 || res.Skipped[0].Email != "vless-mix@x" || res.Skipped[0].Reason != "adTag not supported on inbound" {
t.Fatalf("expected vless-mix@x in skipped, got %+v", res.Skipped)
}
tgRec, _ := svc.GetRecordByEmail(nil, "tg-mix@x")
if tgRec.AdTag != tag1 {
t.Fatalf("tg-mix@x adTag = %q, want %q", tgRec.AdTag, tag1)
}
vlessRec, _ := svc.GetRecordByEmail(nil, "vless-mix@x")
if vlessRec.AdTag != "" {
t.Fatalf("vless-mix@x adTag = %q, want empty", vlessRec.AdTag)
}
}
// TestBulkAdjust_UnchangedClientKeepsUpdatedAt pins the updated_at stamp to the
// client that actually changed: an untouched client must not be re-stamped only
// because a client earlier in the same inbound's array was adjusted.
func TestBulkAdjust_UnchangedClientKeepsUpdatedAt(t *testing.T) {
setupBulkDB(t)
svc := &ClientService{}
inboundSvc := &InboundService{}
const day = int64(24 * 60 * 60 * 1000)
const seeded = int64(1600000000000)
baseExpiry := time.Now().UnixMilli() + 30*day
// chg@x is listed first and takes the expiry bump; keep@x has unlimited
// expiry on a ws inbound, so the same call changes nothing for it.
clients := []model.Client{
{Email: "chg@x", ID: "88888888-8888-8888-8888-888888888888", SubID: "chg", Enable: true, ExpiryTime: baseExpiry, UpdatedAt: seeded},
{Email: "keep@x", ID: "99999999-9999-9999-9999-999999999999", SubID: "keep", Enable: true, UpdatedAt: seeded},
}
ib := mkInboundStream(t, 30801, model.VLESS, clientsSettings(t, clients), wsStream)
if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("seed: %v", err)
}
if err := database.GetDB().Create(&xray.ClientTraffic{Email: "chg@x", Enable: true, ExpiryTime: baseExpiry}).Error; err != nil {
t.Fatalf("seed traffic: %v", err)
}
// The flow directive is what keeps keep@x in the plan; the ws inbound cannot
// carry it, so the directive is not itself a change for either client.
if _, _, err := svc.BulkAdjust(inboundSvc, emailsOf(clients), 7, 0, "xtls-rprx-vision", nil, ""); err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
stamps := settingsUpdatedAt(t, inboundSvc, ib.Id)
if stamps["chg@x"] <= seeded {
t.Fatalf("adjusted client should be re-stamped, updated_at = %d", stamps["chg@x"])
}
if stamps["keep@x"] != seeded {
t.Fatalf("untouched client updated_at = %d, want %d — a sibling's change must not re-stamp it", stamps["keep@x"], seeded)
}
}
func settingsUpdatedAt(t *testing.T, inboundSvc *InboundService, inboundId int) map[string]int64 {
t.Helper()
ib, err := inboundSvc.GetInbound(inboundId)
if err != nil {
t.Fatalf("GetInbound: %v", err)
}
var parsed struct {
Clients []struct {
Email string `json:"email"`
UpdatedAt int64 `json:"updated_at"`
} `json:"clients"`
}
if err := json.Unmarshal([]byte(ib.Settings), &parsed); err != nil {
t.Fatalf("unmarshal settings: %v", err)
}
out := make(map[string]int64, len(parsed.Clients))
for _, c := range parsed.Clients {
out[c.Email] = c.UpdatedAt
}
return out
}
@@ -96,7 +96,7 @@ func TestBulkAdjust_ReenablesExpiredThenExtended_AllThreeLocations(t *testing.T)
email := "exp@x"
ib := seedLocalDisabledClient(t, svc, 52001, "", email, 0, now-reenableDay, 0, 0)
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 30, 0, "")
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 30, 0, "", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -118,7 +118,7 @@ func TestBulkAdjust_DoesNotReenable_ManuallyDisabledNotDepleted(t *testing.T) {
email := "man@x"
ib := seedLocalDisabledClient(t, svc, 52002, "", email, 0, now+30*reenableDay, 0, 0)
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 30, 0, "")
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 30, 0, "", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -137,7 +137,7 @@ func TestBulkAdjust_StaysDisabled_ExtensionTooSmall(t *testing.T) {
email := "sml@x"
ib := seedLocalDisabledClient(t, svc, 52003, "", email, 0, now-10*reenableDay, 0, 0)
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 5, 0, ""); err != nil {
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 5, 0, "", nil, ""); err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, false)
@@ -151,7 +151,7 @@ func TestBulkAdjust_ReenablesOverQuota_WhenAddBytesClearsQuota(t *testing.T) {
email := "q@x"
ib := seedLocalDisabledClient(t, svc, 52004, "", email, 100, 0, 60, 40)
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 0, 200, "")
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 0, 200, "", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -177,7 +177,7 @@ func TestBulkAdjust_QuotaReductionBelowZeroSkipsInsteadOfUnlimited(t *testing.T)
}
mkTraffic(t, ib.Id, email, 0, 0, 10, 0, true)
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 0, -20, "")
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 0, -20, "", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -202,7 +202,7 @@ func TestBulkAdjust_AppliedFieldReachesTrafficRowDespiteOtherFieldSkip(t *testin
}
mkTraffic(t, ib.Id, email, 0, 0, 100, 0, true)
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 30, 50, ""); err != nil {
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 30, 50, "", nil, ""); err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
if got := trafficOf(t, email).Total; got != 150 {
@@ -219,7 +219,7 @@ func TestBulkAdjust_OverQuota_DaysOnly_StaysDisabled(t *testing.T) {
email := "qd@x"
ib := seedLocalDisabledClient(t, svc, 52005, "", email, 100, now-reenableDay, 60, 40)
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 60, 0, ""); err != nil {
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 60, 0, "", nil, ""); err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, false)
@@ -239,7 +239,7 @@ func TestBulkAdjust_NegativeReduction_DoesNotFlipEnable(t *testing.T) {
}
mkTraffic(t, ib.Id, email, 0, 0, 0, now+5*reenableDay, true)
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, -10, 0, ""); err != nil {
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, -10, 0, "", nil, ""); err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, true)
@@ -254,7 +254,7 @@ func TestBulkAdjust_FlowOnly_NoEnableChange(t *testing.T) {
email := "flow@x"
ib := seedLocalDisabledClient(t, svc, 52007, realityStream, email, 0, now-reenableDay, 0, 0)
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 0, 0, "xtls-rprx-vision-udp443"); err != nil {
if _, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 0, 0, "xtls-rprx-vision-udp443", nil, ""); err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, false)
@@ -271,7 +271,7 @@ func TestBulkAdjust_UnlimitedExpiry_QuotaCleared_Reenables(t *testing.T) {
email := "u@x"
ib := seedLocalDisabledClient(t, svc, 52008, "", email, 100, 0, 100, 0)
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 0, 200, "")
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 0, 200, "", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -314,7 +314,7 @@ func TestBulkAdjust_NodeInbound_ReenablesDBLocations(t *testing.T) {
mkTraffic(t, ib.Id, email, 0, 0, 0, now-reenableDay, false)
forceRecordDisabled(t, svc, email)
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 30, 0, "")
res, _, err := svc.BulkAdjust(inboundSvc, []string{email}, 30, 0, "", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -218,7 +218,7 @@ func TestNodeBulkAdjustDoesNotPushBeforeFailedCommit(t *testing.T) {
}
t.Cleanup(func() { _ = db.Callback().Update().Remove(callbackName) })
result, _, err := (&ClientService{}).BulkAdjust(&InboundService{}, []string{client.Email}, 1, 0, "")
result, _, err := (&ClientService{}).BulkAdjust(&InboundService{}, []string{client.Email}, 1, 0, "", nil, "")
if err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
@@ -347,7 +347,7 @@ func TestBulkOpsPostgresScale(t *testing.T) {
}
t0 := time.Now()
if _, _, err := svc.BulkAdjust(inboundSvc, emailsM, 7, 1<<30, ""); err != nil {
if _, _, err := svc.BulkAdjust(inboundSvc, emailsM, 7, 1<<30, "", nil, ""); err != nil {
t.Fatalf("BulkAdjust: %v", err)
}
adjustDur := time.Since(t0)