feat(sub): add per-client subscription HWID limits (#5802)

* feat(sub): add per-client subscription HWID limits

* fix(sub): address HWID review on shared subId and bulk create

* fix(sub): store HWID devices by sub_id and drop anchor client workaround

* fix(sub): restore UA auto-detect and HTML page routing in subs()

The cherry-pick of the HWID gate onto main's refactored SUBController
had dropped main's UA-based format auto-detection and sub-page handling
from subs(). Restore those branches, slotting enforceHwid after the
HTML page and before format detection so the gate only applies to
machine-readable subscription bodies.

Also adapt tests to main's options-struct constructor and to the
ClientService.Update signature extended with limitHwid.

* fix(frontend): drop axios from HttpUtil.delete

The bulk-delete rework's committed version still referenced axios,
which this file no longer imports, breaking typecheck in CI. Use the
httpRequest wrapper like the other verbs.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
Rouzbeh†
2026-08-15 18:20:20 +03:30
committed by GitHub
parent 1793a9b8b4
commit 694ad6deae
45 changed files with 1212 additions and 50 deletions
+45
View File
@@ -72,6 +72,7 @@ type SUBController struct {
subService *SubService
subJsonService *SubJsonService
subClashService *SubClashService
clientService service.ClientService
settingService service.SettingService
subTemplateMu sync.RWMutex
@@ -384,6 +385,9 @@ func (a *SUBController) subs(c *gin.Context) {
logSubscriptionRoute(userAgent, "html")
return
}
if !a.enforceHwid(c) {
return
}
if shouldAutoServeClash(a.subClashAutoDetect, a.clashEnabled, false, userAgent, a.clashUserAgent) && a.serveClashBody(c, false) {
a.recordSubscriptionFetch(c)
logSubscriptionRoute(userAgent, "clash")
@@ -605,6 +609,41 @@ func (a *SUBController) subPageContext(page PageData) map[string]any {
}
}
func (a *SUBController) enforceHwid(c *gin.Context) bool {
result, err := a.clientService.EnforceHwidForSubID(c.Param("subid"), service.HwidRequest{
Hwid: c.GetHeader("X-HWID"),
UserAgent: c.GetHeader("User-Agent"),
DeviceOS: c.GetHeader("X-Device-OS"),
OsVersion: c.GetHeader("X-Ver-OS"),
DeviceModel: c.GetHeader("X-Device-Model"),
})
if err != nil {
writeSubError(c, err)
return false
}
applyHwidHeaders(c, result)
if !result.Allowed {
c.Status(http.StatusNotFound)
return false
}
return true
}
func applyHwidHeaders(c *gin.Context, result service.HwidGateResult) {
if result.Active {
c.Header("X-Hwid-Active", "true")
}
if result.NotSupported {
c.Header("X-Hwid-Not-Supported", "true")
}
if result.LimitReached {
c.Header("X-Hwid-Limit", "true")
}
if result.MaxDevicesReached {
c.Header("X-Hwid-Max-Devices-Reached", "true")
}
}
// setNoCacheHeaders marks a subscription page response as non-cacheable so VPN
// clients and browsers always fetch fresh traffic/expiry data.
func setNoCacheHeaders(c *gin.Context) {
@@ -668,6 +707,9 @@ func (a *SUBController) subJsons(c *gin.Context) {
if a.maybeServeSubPage(c) {
return
}
if !a.enforceHwid(c) {
return
}
a.serveJson(c, a.jsonAlwaysArray, "text/plain; charset=utf-8")
}
@@ -713,6 +755,9 @@ func (a *SUBController) subClashs(c *gin.Context) {
if a.maybeServeSubPage(c) {
return
}
if !a.enforceHwid(c) {
return
}
if !a.serveClashBody(c, false) {
writeSubError(c, nil)
}
+134
View File
@@ -0,0 +1,134 @@
package sub
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func initHwidSubRouter(t *testing.T, limit int) (*gin.Engine, string) {
t.Helper()
tmp := t.TempDir()
t.Chdir(tmp)
if err := os.MkdirAll("internal/web/dist", 0o755); err != nil {
t.Fatalf("mkdir dist: %v", err)
}
if err := os.WriteFile("internal/web/dist/subpage.html", []byte("<html><head></head><body></body></html>"), 0o644); err != nil {
t.Fatalf("write subpage: %v", err)
}
t.Setenv("XUI_DB_FOLDER", tmp)
if err := database.InitDB(filepath.Join(tmp, "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = database.CloseDB() })
const subID = "sub-hwid-route"
const email = "route@example.com"
const uuid = "11111111-2222-4333-8444-555555555555"
db := database.GetDB()
ib := &model.Inbound{
UserId: 1,
Tag: "hwid-sub",
Enable: true,
Port: 443,
Protocol: model.VLESS,
Settings: `{"clients":[]}`,
StreamSettings: `{"network":"tcp","security":"none"}`,
}
if err := db.Create(ib).Error; err != nil {
t.Fatalf("seed inbound: %v", err)
}
client := &model.ClientRecord{Email: email, SubID: subID, UUID: uuid, Enable: true, LimitHwid: limit}
if err := db.Create(client).Error; err != nil {
t.Fatalf("seed client: %v", err)
}
if err := db.Create(&model.ClientInbound{ClientId: client.Id, InboundId: ib.Id}).Error; err != nil {
t.Fatalf("seed client inbound: %v", err)
}
gin.SetMode(gin.TestMode)
router := gin.New()
NewSUBController(
router.Group("/"),
WithSUBPath("/sub/"),
WithSUBJsonPath("/json/"),
WithSUBClashPath("/clash/"),
WithSUBClashAutoDetect(true),
WithSUBJsonAutoDetect(true),
WithSUBJsonEnabled(true),
WithSUBClashEnabled(true),
)
return router, subID
}
func requestSub(t *testing.T, router *gin.Engine, method string, path string, hwid string, accept string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, nil)
req.Host = "sub.example.com"
if hwid != "" {
req.Header.Set("X-HWID", hwid)
}
if accept != "" {
req.Header.Set("Accept", accept)
}
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
return rec
}
func TestSubscriptionHwidGateAcrossBodyRoutes(t *testing.T) {
router, subID := initHwidSubRouter(t, 1)
for _, path := range []string{"/sub/" + subID, "/json/" + subID, "/clash/" + subID} {
rec := requestSub(t, router, http.MethodGet, path, "", "")
if rec.Code != http.StatusNotFound {
t.Fatalf("%s missing HWID status = %d, want 404", path, rec.Code)
}
if rec.Header().Get("X-Hwid-Active") != "true" || rec.Header().Get("X-Hwid-Not-Supported") != "true" {
t.Fatalf("%s missing HWID headers = %#v", path, rec.Header())
}
}
rec := requestSub(t, router, http.MethodHead, "/sub/"+subID, "", "")
if rec.Code != http.StatusNotFound || rec.Header().Get("X-Hwid-Not-Supported") != "true" {
t.Fatalf("HEAD missing HWID = %d %#v", rec.Code, rec.Header())
}
for _, path := range []string{"/sub/" + subID, "/json/" + subID, "/clash/" + subID} {
rec = requestSub(t, router, http.MethodGet, path, "device-one", "")
if rec.Code != http.StatusOK {
t.Fatalf("%s registered HWID status = %d, body=%q", path, rec.Code, rec.Body.String())
}
if rec.Header().Get("X-Hwid-Active") != "true" {
t.Fatalf("%s allowed response missing active HWID header", path)
}
}
rec = requestSub(t, router, http.MethodGet, "/json/"+subID, "device-two", "")
if rec.Code != http.StatusNotFound {
t.Fatalf("new HWID after limit status = %d, want 404", rec.Code)
}
if rec.Header().Get("X-Hwid-Max-Devices-Reached") != "true" || rec.Header().Get("X-Hwid-Limit") != "true" {
t.Fatalf("limit headers missing: %#v", rec.Header())
}
}
func TestSubscriptionHwidGateSkipsHtmlInfoPage(t *testing.T) {
router, subID := initHwidSubRouter(t, 1)
rec := requestSub(t, router, http.MethodGet, "/sub/"+subID, "", "text/html")
if rec.Code != http.StatusOK {
t.Fatalf("HTML sub page status = %d, want 200, body=%q", rec.Code, rec.Body.String())
}
if rec.Header().Get("X-Hwid-Not-Supported") != "" {
t.Fatalf("HTML sub page should not be HWID-gated: %#v", rec.Header())
}
}