1
0

client_hwid.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package service
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "errors"
  6. "strings"
  7. "time"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  11. "gorm.io/gorm"
  12. "gorm.io/gorm/clause"
  13. )
  14. type HwidRequest struct {
  15. Hwid string
  16. UserAgent string
  17. DeviceOS string
  18. OsVersion string
  19. DeviceModel string
  20. }
  21. type HwidGateResult struct {
  22. Allowed bool
  23. Active bool
  24. NotSupported bool
  25. MaxDevicesReached bool
  26. LimitReached bool
  27. Limit int
  28. Registered int
  29. }
  30. // HwidSlotStatus is the aggregate device-slot view exposed to subscribers:
  31. // counters only, no hwid value or hash, no email, no device metadata.
  32. type HwidSlotStatus struct {
  33. Active bool `json:"active" example:"true"`
  34. Limit int `json:"limit" example:"2"`
  35. Registered int `json:"registered" example:"1"`
  36. Remaining int `json:"remaining" example:"1"`
  37. Full bool `json:"full" example:"false"`
  38. }
  39. const (
  40. minHwidLength = 6
  41. hwidFingerprintLength = 12
  42. )
  43. var errClientHwidWriteNotSerialized = errors.New("client HWID write requires the serialized transaction")
  44. type ClientHwidInfo struct {
  45. Id int `json:"id"`
  46. FirstSeen int64 `json:"firstSeen"`
  47. LastSeen int64 `json:"lastSeen"`
  48. UserAgent string `json:"userAgent"`
  49. DeviceOS string `json:"deviceOs"`
  50. OsVersion string `json:"osVersion"`
  51. DeviceModel string `json:"deviceModel"`
  52. Fingerprint string `json:"fingerprint"`
  53. }
  54. func hashHwid(raw string) string {
  55. sum := sha256.Sum256([]byte(raw))
  56. return hex.EncodeToString(sum[:])
  57. }
  58. func shortHwidFingerprint(hash string) string {
  59. if len(hash) <= hwidFingerprintLength {
  60. return hash
  61. }
  62. return hash[:hwidFingerprintLength]
  63. }
  64. func trimHwidMeta(s string) string {
  65. s = strings.TrimSpace(s)
  66. r := []rune(s)
  67. if len(r) > 512 {
  68. return string(r[:512])
  69. }
  70. return s
  71. }
  72. func normalizeHwidRequest(req HwidRequest) HwidRequest {
  73. return HwidRequest{
  74. Hwid: strings.TrimSpace(req.Hwid),
  75. UserAgent: trimHwidMeta(req.UserAgent),
  76. DeviceOS: trimHwidMeta(req.DeviceOS),
  77. OsVersion: trimHwidMeta(req.OsVersion),
  78. DeviceModel: trimHwidMeta(req.DeviceModel),
  79. }
  80. }
  81. func effectiveHwidLimitForSubID(tx *gorm.DB, subID string) (int, error) {
  82. var limit int
  83. err := tx.Model(&model.ClientRecord{}).
  84. Where("sub_id = ? AND enable = ?", subID, true).
  85. Select("COALESCE(MAX(limit_hwid), 0)").
  86. Scan(&limit).Error
  87. return limit, err
  88. }
  89. func (s *ClientService) EnforceHwidForSubID(subID string, req HwidRequest) (HwidGateResult, error) {
  90. var res HwidGateResult
  91. subID = strings.TrimSpace(subID)
  92. if subID == "" {
  93. res.Allowed = true
  94. return res, nil
  95. }
  96. db := database.GetDB()
  97. limit, err := effectiveHwidLimitForSubID(db, subID)
  98. if err != nil {
  99. return res, err
  100. }
  101. req = normalizeHwidRequest(req)
  102. if limit <= 0 {
  103. res.Allowed = true
  104. if len(req.Hwid) >= minHwidLength {
  105. trackUnlimitedHwid(db, subID, req)
  106. }
  107. return res, nil
  108. }
  109. res.Active = true
  110. res.Limit = limit
  111. if len(req.Hwid) < minHwidLength {
  112. res.NotSupported = true
  113. return res, nil
  114. }
  115. hwidHash := hashHwid(req.Hwid)
  116. err = db.Transaction(func(tx *gorm.DB) error {
  117. limit, err := effectiveHwidLimitForSubID(tx, subID)
  118. if err != nil {
  119. return err
  120. }
  121. if limit <= 0 {
  122. res = HwidGateResult{Allowed: true}
  123. return nil
  124. }
  125. res.Active = true
  126. res.Limit = limit
  127. now := time.Now().UnixMilli()
  128. var existing model.ClientHwid
  129. err = tx.Where("sub_id = ? AND hwid_hash = ?", subID, hwidHash).First(&existing).Error
  130. if err == nil {
  131. if err := tx.Model(&model.ClientHwid{}).Where("id = ?", existing.Id).Updates(map[string]any{
  132. "last_seen": now, "user_agent": req.UserAgent, "device_os": req.DeviceOS, "os_version": req.OsVersion, "device_model": req.DeviceModel,
  133. }).Error; err != nil {
  134. return err
  135. }
  136. var count int64
  137. if err := tx.Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&count).Error; err != nil {
  138. return err
  139. }
  140. res.Allowed = true
  141. res.Registered = int(count)
  142. res.LimitReached = count >= int64(limit)
  143. return nil
  144. }
  145. if !errors.Is(err, gorm.ErrRecordNotFound) {
  146. return err
  147. }
  148. var count int64
  149. if err := tx.Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&count).Error; err != nil {
  150. return err
  151. }
  152. res.Registered = int(count)
  153. if count >= int64(limit) {
  154. res.MaxDevicesReached = true
  155. res.LimitReached = true
  156. return nil
  157. }
  158. if err := tx.Create(&model.ClientHwid{SubID: subID, HwidHash: hwidHash, FirstSeen: now, LastSeen: now, UserAgent: req.UserAgent, DeviceOS: req.DeviceOS, OsVersion: req.OsVersion, DeviceModel: req.DeviceModel}).Error; err != nil {
  159. return err
  160. }
  161. res.Allowed = true
  162. res.Registered = int(count) + 1
  163. res.LimitReached = res.Registered >= limit
  164. return nil
  165. })
  166. return res, err
  167. }
  168. // trackUnlimitedHwid lists devices of a sub with no HWID limit in the panel. It is
  169. // best-effort: a failed write must not deny a subscription nothing restricts.
  170. func trackUnlimitedHwid(db *gorm.DB, subID string, req HwidRequest) {
  171. now := time.Now().UnixMilli()
  172. err := db.Clauses(clause.OnConflict{
  173. Columns: []clause.Column{{Name: "sub_id"}, {Name: "hwid_hash"}},
  174. DoUpdates: clause.AssignmentColumns([]string{"last_seen", "user_agent", "device_os", "os_version", "device_model"}),
  175. }).Create(&model.ClientHwid{SubID: subID, HwidHash: hashHwid(req.Hwid), FirstSeen: now, LastSeen: now, UserAgent: req.UserAgent, DeviceOS: req.DeviceOS, OsVersion: req.OsVersion, DeviceModel: req.DeviceModel}).Error
  176. if err != nil {
  177. logger.Warning("track HWID for unlimited subscription failed:", err)
  178. }
  179. }
  180. // HwidSlotStatusForSubID is SELECT-only: it must never write client_hwids or
  181. // last_seen. Enabled-clients scope mirrors the gate, so limit == limit enforced.
  182. func (s *ClientService) HwidSlotStatusForSubID(subID string) (status HwidSlotStatus, found bool, err error) {
  183. subID = strings.TrimSpace(subID)
  184. if subID == "" {
  185. return status, false, nil
  186. }
  187. db := database.GetDB()
  188. var enabled int64
  189. if err := db.Model(&model.ClientRecord{}).
  190. Where("sub_id = ? AND enable = ?", subID, true).
  191. Count(&enabled).Error; err != nil {
  192. return status, false, err
  193. }
  194. if enabled == 0 {
  195. return status, false, nil
  196. }
  197. limit, err := effectiveHwidLimitForSubID(db, subID)
  198. if err != nil {
  199. return status, false, err
  200. }
  201. if limit <= 0 {
  202. return status, true, nil
  203. }
  204. var registered int64
  205. if err := db.Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&registered).Error; err != nil {
  206. return status, false, err
  207. }
  208. status.Active = true
  209. status.Limit = limit
  210. status.Registered = int(registered)
  211. status.Remaining = max(limit-status.Registered, 0)
  212. status.Full = status.Registered >= limit
  213. return status, true, nil
  214. }
  215. func (s *ClientService) ListClientHwids(email string) ([]ClientHwidInfo, error) {
  216. rec, err := s.GetRecordByEmail(nil, email)
  217. if err != nil {
  218. return nil, err
  219. }
  220. subID := strings.TrimSpace(rec.SubID)
  221. if subID == "" {
  222. return nil, nil
  223. }
  224. var rows []model.ClientHwid
  225. if err := database.GetDB().
  226. Where("sub_id = ?", subID).
  227. Order("last_seen DESC").
  228. Order("id DESC").
  229. Find(&rows).Error; err != nil {
  230. return nil, err
  231. }
  232. out := make([]ClientHwidInfo, 0, len(rows))
  233. for _, r := range rows {
  234. out = append(out, ClientHwidInfo{
  235. Id: r.Id,
  236. FirstSeen: r.FirstSeen,
  237. LastSeen: r.LastSeen,
  238. UserAgent: r.UserAgent,
  239. DeviceOS: r.DeviceOS,
  240. OsVersion: r.OsVersion,
  241. DeviceModel: r.DeviceModel,
  242. Fingerprint: shortHwidFingerprint(r.HwidHash),
  243. })
  244. }
  245. return out, nil
  246. }
  247. func (s *ClientService) ClearClientHwids(email string) error {
  248. rec, err := s.GetRecordByEmail(nil, email)
  249. if err != nil {
  250. return err
  251. }
  252. subID := strings.TrimSpace(rec.SubID)
  253. if subID == "" {
  254. return nil
  255. }
  256. return database.GetDB().Where("sub_id = ?", subID).Delete(&model.ClientHwid{}).Error
  257. }
  258. // DeleteClientHwid removes one device, scoped to the client's sub_id: ids
  259. // are a global auto-increment, so an id outside this subscription won't match.
  260. func (s *ClientService) DeleteClientHwid(email string, id int) error {
  261. rec, err := s.GetRecordByEmail(nil, email)
  262. if err != nil {
  263. return err
  264. }
  265. subID := strings.TrimSpace(rec.SubID)
  266. if subID == "" {
  267. return errors.New("client has no subscription id")
  268. }
  269. res := database.GetDB().Where("sub_id = ? AND id = ?", subID, id).Delete(&model.ClientHwid{})
  270. if res.Error != nil {
  271. return res.Error
  272. }
  273. if res.RowsAffected == 0 {
  274. return errors.New("device not found")
  275. }
  276. return nil
  277. }
  278. // Serialize the limit write and trim with SyncInbound and client deletion.
  279. func (s *ClientService) setClientLimitHwidByEmail(email string, limit int) error {
  280. return runSerializedTx(func(tx *gorm.DB) error {
  281. return s.setClientLimitHwidByEmailTx(tx, email, limit)
  282. })
  283. }
  284. func (s *ClientService) setClientLimitHwidByEmailTx(tx *gorm.DB, email string, limit int) error {
  285. if !isSerializedTx(tx) {
  286. return errClientHwidWriteNotSerialized
  287. }
  288. if limit < 0 {
  289. limit = 0
  290. }
  291. var rec model.ClientRecord
  292. if err := tx.Where("email = ?", email).First(&rec).Error; err != nil {
  293. return err
  294. }
  295. if err := tx.Model(&model.ClientRecord{}).Where("id = ?", rec.Id).UpdateColumn("limit_hwid", limit).Error; err != nil {
  296. return err
  297. }
  298. subID := strings.TrimSpace(rec.SubID)
  299. if subID == "" {
  300. return nil
  301. }
  302. effective, err := effectiveHwidLimitForSubID(tx, subID)
  303. if err != nil {
  304. return err
  305. }
  306. return trimClientHwidsForSubID(tx, subID, effective)
  307. }
  308. func trimClientHwidsForSubID(tx *gorm.DB, subID string, limit int) error {
  309. subID = strings.TrimSpace(subID)
  310. if subID == "" || limit <= 0 {
  311. return nil
  312. }
  313. var keep []int
  314. if err := tx.Model(&model.ClientHwid{}).
  315. Where("sub_id = ?", subID).
  316. Order("last_seen DESC").
  317. Order("id DESC").
  318. Limit(limit).
  319. Pluck("id", &keep).Error; err != nil {
  320. return err
  321. }
  322. if len(keep) == 0 {
  323. return tx.Where("sub_id = ?", subID).Delete(&model.ClientHwid{}).Error
  324. }
  325. return tx.Where("sub_id = ? AND id NOT IN ?", subID, keep).Delete(&model.ClientHwid{}).Error
  326. }
  327. func clearClientHwidsBySubIDTx(tx *gorm.DB, subIDs ...string) error {
  328. if !isSerializedTx(tx) {
  329. return errClientHwidWriteNotSerialized
  330. }
  331. clean := make([]string, 0, len(subIDs))
  332. seen := map[string]struct{}{}
  333. for _, subID := range subIDs {
  334. subID = strings.TrimSpace(subID)
  335. if subID == "" {
  336. continue
  337. }
  338. if _, ok := seen[subID]; ok {
  339. continue
  340. }
  341. seen[subID] = struct{}{}
  342. clean = append(clean, subID)
  343. }
  344. for _, batch := range chunkStrings(clean, sqlInChunk) {
  345. if err := tx.Where("sub_id IN ?", batch).Delete(&model.ClientHwid{}).Error; err != nil {
  346. return err
  347. }
  348. }
  349. return nil
  350. }