feat(sub): add read-only HWID device-slot status endpoint (#6380)

* feat(sub): add read-only HWID device-slot status endpoint

Closes #6357

A client with an HWID limit had no way to tell a subscriber how many device
slots were left: /{subPath}/{subId} only exposes the gate as a boolean through
X-Hwid-* headers on a 404, and ?format=info carries no limitHwid or registered
count. Every "why can't I connect on my new phone" case therefore had to be
answered by the operator by hand.

GET /{subPath}/{subId}/hwid-status now returns the aggregate counters:

  {"active":true,"limit":2,"registered":1,"remaining":1,"full":false}

- SELECT-only. It never registers an hwid, never touches last_seen and never
  calls the enforcement path, so asking about a slot cannot spend one.
- Counters only: no hwid value or hash, no email, no device metadata, no IP,
  no User-Agent, and none of the X-Hwid-* gate headers.
- The subscription id is already the bearer secret for /{subPath}/{subId}, so
  no admin token and no new auth mechanism.
- Unknown and disabled subscriptions both answer a bare 404, with identical
  status, headers and body, so the route cannot be used to probe which
  subscription ids exist.
- No HWID limit configured returns {"active":false,"limit":0,...}.
- No schema change and no migration.

Scoped to enabled clients exactly like effectiveHwidLimitForSubID, so the
reported limit is always the limit the gate enforces on a shared sub_id, and
remaining clamps at zero when the effective limit drops below the number of
registered devices. A separate route leaves /{subPath}/{subId}, ?format=info
and the JSON/Clash routes byte-for-byte unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(sub): document hwid-status as the bare object it returns

The OpenAPI operation for GET /{subPath}/{subId}/hwid-status inherited the
{success,msg,obj} panel envelope from build-openapi.mjs's default 200
response, while the handler writes the HwidSlotStatus struct bare. A client
generated from the spec would read `obj` and never find the counters, and
the description prose contradicted the schema with a hand-written example.

HwidSlotStatus now sits in openapigen's StructAllow with example: tags, the
entry references the generated schema through a `responses` block, and
build-openapi.mjs attaches the generated example to any `responses` entry
that $refs a generated schema, so no example is hand-written. The HEAD
variant the controller registers is documented like its siblings, and the
summary follows the "path prefix is configured by subPath" wording now that
fresh panels randomise the prefix.

Regenerated frontend/public/openapi.json, docs/public/openapi.json and the
subscription-server MDX. openapi-runtime-contracts.test.ts pins the bare
schema, the generated example and the HEAD operation.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
Namso9
2026-09-11 16:29:35 +06:30
committed by GitHub
parent 8f162994ef
commit 89ee1242bd
15 changed files with 637 additions and 3 deletions
+14
View File
@@ -311,6 +311,8 @@ func (a *SUBController) initRouter(g *gin.RouterGroup) {
gLink := g.Group(a.subPath)
gLink.GET(":subid", a.subs)
gLink.HEAD(":subid", a.subs)
gLink.GET(":subid/hwid-status", a.hwidStatus)
gLink.HEAD(":subid/hwid-status", a.hwidStatus)
if a.jsonEnabled {
gJson := g.Group(a.subJsonPath)
gJson.GET(":subid", a.subJsons)
@@ -707,6 +709,18 @@ func applyHwidHeaders(c *gin.Context, result service.HwidGateResult) {
}
}
// hwidStatus serves read-only device-slot counters for a subscription. It
// deliberately skips enforceHwid: asking about slots must not consume one.
func (a *SUBController) hwidStatus(c *gin.Context) {
status, found, err := a.clientService.HwidSlotStatusForSubID(c.Param("subid"))
if err != nil || !found {
writeSubError(c, err)
return
}
setNoCacheHeaders(c)
c.JSON(http.StatusOK, status)
}
// 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) {
+112
View File
@@ -1,10 +1,12 @@
package sub
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"testing"
"github.com/gin-gonic/gin"
@@ -144,3 +146,113 @@ func TestSubscriptionHwidGateSkipsHtmlInfoPage(t *testing.T) {
t.Fatalf("HTML sub page should not be HWID-gated: %#v", rec.Header())
}
}
// Decoding into a map rather than the service struct keeps the exact field set
// asserted, so an extra field leaking into the response fails the test.
func assertHwidStatus(t *testing.T, rec *httptest.ResponseRecorder, active bool, limit, registered, remaining int, full bool) {
t.Helper()
if rec.Code != http.StatusOK {
t.Fatalf("hwid-status status = %d, body=%q", rec.Code, rec.Body.String())
}
var got map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("decode hwid-status body %q: %v", rec.Body.String(), err)
}
want := map[string]any{
"active": active,
"limit": float64(limit),
"registered": float64(registered),
"remaining": float64(remaining),
"full": full,
}
if len(got) != len(want) {
t.Fatalf("hwid-status fields = %#v, want exactly %#v", got, want)
}
for key, value := range want {
if got[key] != value {
t.Fatalf("hwid-status[%q] = %#v, want %#v (body %#v)", key, got[key], value, got)
}
}
}
func TestSubscriptionHwidStatusCountsRegisteredDevices(t *testing.T) {
router, subID := initHwidSubRouter(t, 2)
statusPath := "/sub/" + subID + "/hwid-status"
assertHwidStatus(t, requestSub(t, router, http.MethodGet, statusPath, "", ""), true, 2, 0, 2, false)
for i, hwid := range []string{"device-one", "device-two"} {
if rec := requestSub(t, router, http.MethodGet, "/sub/"+subID, hwid, ""); rec.Code != http.StatusOK {
t.Fatalf("register %s = %d, want 200", hwid, rec.Code)
}
registered := i + 1
rec := requestSub(t, router, http.MethodGet, statusPath, "", "")
assertHwidStatus(t, rec, true, 2, registered, 2-registered, registered == 2)
}
if rec := requestSub(t, router, http.MethodHead, statusPath, "", ""); rec.Code != http.StatusOK {
t.Fatalf("HEAD hwid-status = %d, want 200", rec.Code)
}
}
// The endpoint must stay SELECT-only: asking about slots while carrying an
// X-HWID header must not spend the slot the caller is asking about.
func TestSubscriptionHwidStatusDoesNotRegisterDevice(t *testing.T) {
router, subID := initHwidSubRouter(t, 1)
rec := requestSub(t, router, http.MethodGet, "/sub/"+subID+"/hwid-status", "device-probe", "")
assertHwidStatus(t, rec, true, 1, 0, 1, false)
for _, header := range []string{"X-Hwid-Active", "X-Hwid-Limit", "X-Hwid-Not-Supported", "X-Hwid-Max-Devices-Reached"} {
if value := rec.Header().Get(header); value != "" {
t.Fatalf("hwid-status leaked gate header %s = %q", header, value)
}
}
var count int64
if err := database.GetDB().Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&count).Error; err != nil {
t.Fatalf("count hwids: %v", err)
}
if count != 0 {
t.Fatalf("client_hwids rows after status probe = %d, want 0", count)
}
if rec := requestSub(t, router, http.MethodGet, "/sub/"+subID, "device-probe", ""); rec.Code != http.StatusOK {
t.Fatalf("subscription fetch after probe = %d, want 200", rec.Code)
}
}
func TestSubscriptionHwidStatusWithoutLimit(t *testing.T) {
router, subID := initHwidSubRouter(t, 0)
assertHwidStatus(t, requestSub(t, router, http.MethodGet, "/sub/"+subID+"/hwid-status", "", ""), false, 0, 0, 0, false)
}
// An unknown and a disabled subscription must be indistinguishable, so a
// caller cannot probe which subscription ids exist.
func TestSubscriptionHwidStatusHidesUnknownVersusDisabled(t *testing.T) {
router, subID := initHwidSubRouter(t, 1)
unknown := requestSub(t, router, http.MethodGet, "/sub/does-not-exist/hwid-status", "", "")
if unknown.Code != http.StatusNotFound {
t.Fatalf("unknown subId status = %d, want 404", unknown.Code)
}
if err := database.GetDB().Model(&model.ClientRecord{}).
Where("sub_id = ?", subID).
UpdateColumn("enable", false).Error; err != nil {
t.Fatalf("disable client: %v", err)
}
disabled := requestSub(t, router, http.MethodGet, "/sub/"+subID+"/hwid-status", "", "")
if disabled.Code != unknown.Code {
t.Fatalf("disabled status = %d, unknown status = %d, want identical", disabled.Code, unknown.Code)
}
if disabled.Body.String() != unknown.Body.String() {
t.Fatalf("disabled body = %q, unknown body = %q, want identical", disabled.Body.String(), unknown.Body.String())
}
if !reflect.DeepEqual(disabled.Header(), unknown.Header()) {
t.Fatalf("disabled headers = %#v, unknown headers = %#v, want identical", disabled.Header(), unknown.Header())
}
if disabled.Body.Len() != 0 {
t.Fatalf("404 body = %q, want empty", disabled.Body.String())
}
}
+49
View File
@@ -31,6 +31,16 @@ type HwidGateResult struct {
Registered int
}
// HwidSlotStatus is the aggregate device-slot view exposed to subscribers:
// counters only, no hwid value or hash, no email, no device metadata.
type HwidSlotStatus struct {
Active bool `json:"active" example:"true"`
Limit int `json:"limit" example:"2"`
Registered int `json:"registered" example:"1"`
Remaining int `json:"remaining" example:"1"`
Full bool `json:"full" example:"false"`
}
const minHwidLength = 6
type ClientHwidInfo struct {
@@ -156,6 +166,45 @@ func (s *ClientService) EnforceHwidForSubID(subID string, req HwidRequest) (Hwid
return res, err
}
// HwidSlotStatusForSubID is SELECT-only: it must never write client_hwids or
// last_seen. Enabled-clients scope mirrors the gate, so limit == limit enforced.
func (s *ClientService) HwidSlotStatusForSubID(subID string) (status HwidSlotStatus, found bool, err error) {
subID = strings.TrimSpace(subID)
if subID == "" {
return status, false, nil
}
db := database.GetDB()
var enabled int64
if err := db.Model(&model.ClientRecord{}).
Where("sub_id = ? AND enable = ?", subID, true).
Count(&enabled).Error; err != nil {
return status, false, err
}
if enabled == 0 {
return status, false, nil
}
limit, err := effectiveHwidLimitForSubID(db, subID)
if err != nil {
return status, false, err
}
if limit <= 0 {
return status, true, nil
}
var registered int64
if err := db.Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&registered).Error; err != nil {
return status, false, err
}
status.Active = true
status.Limit = limit
status.Registered = int(registered)
status.Remaining = max(limit-status.Registered, 0)
status.Full = status.Registered >= limit
return status, true, nil
}
func (s *ClientService) ListClientHwids(email string) ([]ClientHwidInfo, error) {
rec, err := s.GetRecordByEmail(nil, email)
if err != nil {
+58
View File
@@ -217,3 +217,61 @@ func TestClientHwidGateSharedSubIdUsesMaxLimit(t *testing.T) {
t.Fatalf("missing HWID should be denied: %+v", res)
}
}
func TestClientHwidSlotStatus(t *testing.T) {
initClientHwidTestDB(t)
svc := &ClientService{}
db := database.GetDB()
rec := seedHwidClient(t, 1)
status, found, err := svc.HwidSlotStatusForSubID("no-such-sub")
if err != nil || found || status != (HwidSlotStatus{}) {
t.Fatalf("unknown subId = (%+v, %v, %v), want zero status and found=false", status, found, err)
}
status, found, err = svc.HwidSlotStatusForSubID(" " + rec.SubID + " ")
if err != nil || !found {
t.Fatalf("padded subId = (%+v, %v, %v), want found=true", status, found, err)
}
if want := (HwidSlotStatus{Active: true, Limit: 1, Remaining: 1}); status != want {
t.Fatalf("empty slots = %+v, want %+v", status, want)
}
// A shared sub_id takes the highest limit, matching the enforcement gate.
if err := db.Create(&model.ClientRecord{Email: "second@example.com", SubID: rec.SubID, UUID: "22222222-2222-4333-8444-555555555555", Enable: true, LimitHwid: 3}).Error; err != nil {
t.Fatalf("seed second client: %v", err)
}
for _, hwid := range []string{"device-one", "device-two", "device-three"} {
if _, err := svc.EnforceHwidForSubID(rec.SubID, HwidRequest{Hwid: hwid}); err != nil {
t.Fatalf("register %s: %v", hwid, err)
}
}
status, found, err = svc.HwidSlotStatusForSubID(rec.SubID)
if err != nil || !found {
t.Fatalf("shared subId = (%+v, %v, %v), want found=true", status, found, err)
}
if want := (HwidSlotStatus{Active: true, Limit: 3, Registered: 3, Full: true}); status != want {
t.Fatalf("full slots = %+v, want %+v", status, want)
}
// Deleting the highest-limit client drops the effective limit below the
// registered count, and remaining must clamp at zero instead of going negative.
if err := db.Where("email = ?", "second@example.com").Delete(&model.ClientRecord{}).Error; err != nil {
t.Fatalf("delete second client: %v", err)
}
status, _, err = svc.HwidSlotStatusForSubID(rec.SubID)
if err != nil {
t.Fatalf("lowered limit: %v", err)
}
if want := (HwidSlotStatus{Active: true, Limit: 1, Registered: 3, Remaining: 0, Full: true}); status != want {
t.Fatalf("over-limit slots = %+v, want %+v", status, want)
}
if err := db.Model(&model.ClientRecord{}).Where("sub_id = ?", rec.SubID).UpdateColumn("enable", false).Error; err != nil {
t.Fatalf("disable clients: %v", err)
}
status, found, err = svc.HwidSlotStatusForSubID(rec.SubID)
if err != nil || found || status != (HwidSlotStatus{}) {
t.Fatalf("disabled subId = (%+v, %v, %v), want zero status and found=false", status, found, err)
}
}