[GH-ISSUE #6334] feat(hwid): auto-remove inactive HWID devices (TTL) #4301

Open
opened 2026-10-31 20:38:40 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @acidmsg on GitHub (Aug 26, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6334

Problem

limit_hwid blocks new devices once the limit is reached. When a user loses or replaces a device (phone, OS reinstall), the old HWID permanently occupies a slot — it can only be freed manually via API/UI.

Proposal

Add a TTL for HWID records:

  1. Panel setting: hwidInactiveDays (default 0 = disabled)
  2. Background job: periodically delete client_hwids where last_seen < now - N days
  3. Or: auto-cleanup on subscription request, if the limit is reached and there are records older than N days

Implementation

DELETE FROM client_hwids WHERE last_seen < strftime('%s','now','-N days')*1000;
  • last_seen already updates on every subscription request — active devices are unaffected
  • Table has no foreign keys — deletion is safe

Why

  • Limit slots free up automatically when users change devices
  • client_hwids doesn't grow indefinitely
Originally created by @acidmsg on GitHub (Aug 26, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6334 ### Problem `limit_hwid` blocks new devices once the limit is reached. When a user loses or replaces a device (phone, OS reinstall), the old HWID **permanently** occupies a slot — it can only be freed manually via API/UI. ### Proposal Add a TTL for HWID records: 1. **Panel setting:** `hwidInactiveDays` (default 0 = disabled) 2. **Background job:** periodically delete `client_hwids` where `last_seen < now - N days` 3. Or: auto-cleanup on subscription request, if the limit is reached and there are records older than N days ### Implementation ```sql DELETE FROM client_hwids WHERE last_seen < strftime('%s','now','-N days')*1000; ``` - `last_seen` already updates on every subscription request — active devices are unaffected - Table has no foreign keys — deletion is safe ### Why - Limit slots free up automatically when users change devices - `client_hwids` doesn't grow indefinitely
Author
Owner

@github-actions[bot] commented on GitHub (Aug 26, 2026):

This is a valid feature request — nothing like it exists today, and your reading of the gate is correct: a registered HWID keeps its slot until someone removes it by hand. Two details in the proposal need correcting before it gets implemented, though.

What the code does now

The gate is EnforceHwidForSubID in internal/web/service/client_hwid.go, called from the subscription server (internal/sub/controller.go:622, enforceHwid, which reads the X-HWID header). A known device refreshes its timestamp on every subscription fetch (internal/web/service/client_hwid.go:121-123):

if err := tx.Model(&model.ClientHwid{}).Where("id = ?", existing.Id).Updates(map[string]any{
    "last_seen": now, "user_agent": req.UserAgent, ...

and an unknown device is refused once the slot count is reached (internal/web/service/client_hwid.go:143-147):

if count >= int64(limit) {
    res.MaxDevicesReached = true
    res.LimitReached = true
    return nil
}

There is no expiry anywhere: no hwid* key in defaultValueMap (internal/web/service/setting.go:44), no HWID job in internal/web/job/, and no such entry in the cron table (docs/architecture.md:363-388). Freeing a slot is manual only, through ClearClientHwids / DeleteClientHwid (internal/web/service/client_hwid.go:191, :205), exposed at internal/web/controller/client.go:79-81:

POST   /panel/api/clients/hwids/:email        # list
DELETE /panel/api/clients/hwids/:email        # clear all
DELETE /panel/api/clients/hwids/:email/:id    # remove one device

The per-device form landed in 1250fbb7 (#6245 / PR #6265, 2026-08-21) and ships in v3.7.0; the UI for it is frontend/src/components/clients/ClientHwidList.tsx.

Correction 1 — client_hwids does not grow indefinitely. Rows per sub_id are already capped: inserts stop at the effective limit (the block quoted above), lowering limit_hwid trims the excess by last_seen DESC (trimClientHwidsForSubID, internal/web/service/client_hwid.go:249-267, called at :246), and deleting a client drops its rows (clearClientHwidsBySubIDTx, :269, call sites client_crud.go:710, client_bulk.go:833, client_portable.go:210). So the case for a TTL rests entirely on your first argument — a dead device holding a live slot — which is real; unbounded table growth is not.

Correction 2 — the SQL is SQLite-only. The panel also runs on PostgreSQL (XUI_DB_TYPE / XUI_DB_DSN), where strftime does not exist, so the cutoff has to be computed in Go and applied through GORM. The existing precedent is the client-IP staleness sweep added in 103b0dfe: cutoff := time.Now().Unix() - clientIpStaleAfterSeconds (internal/web/service/inbound_client_ips.go:244), driven from internal/web/job/check_client_ip_job.go. Note the unit differs — client_hwids.last_seen is milliseconds (now := time.Now().UnixMilli(), internal/web/service/client_hwid.go:117), while the IP tables store seconds.

One design caveat worth stating in the request. last_seen records when the device last fetched the subscription, not when it last used the tunnel. A client configured to update its subscription rarely or only manually would be evicted while still in active use, and would then re-register only if a slot happens to be free at its next fetch. That argues for your default 0 = disabled, and it also makes your option 3 (prune expired rows inside the existing transaction, only when the limit is actually reached) the least surprising of the three, and the smallest change — it needs no new cron job, just a cutoff check where the count is taken.

If a panel-wide setting is added instead, it also carries the setting chain: a key in defaultValueMap (internal/web/service/setting.go:44), the settings API/UI, and one new key in all 13 locale files under internal/web/translation/.

Related, not duplicates: #6245 (per-device removal, implemented) and #6234 (bulk editing of the HWID limit, still open). I have labelled this enhancement; the decision on whether to take it is the maintainer's.

Verdict: Feature request

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5423586709 --> @github-actions[bot] commented on GitHub (Aug 26, 2026): This is a valid feature request — nothing like it exists today, and your reading of the gate is correct: a registered HWID keeps its slot until someone removes it by hand. Two details in the proposal need correcting before it gets implemented, though. **What the code does now** The gate is `EnforceHwidForSubID` in `internal/web/service/client_hwid.go`, called from the subscription server (`internal/sub/controller.go:622`, `enforceHwid`, which reads the `X-HWID` header). A known device refreshes its timestamp on every subscription fetch (`internal/web/service/client_hwid.go:121-123`): ```go if err := tx.Model(&model.ClientHwid{}).Where("id = ?", existing.Id).Updates(map[string]any{ "last_seen": now, "user_agent": req.UserAgent, ... ``` and an unknown device is refused once the slot count is reached (`internal/web/service/client_hwid.go:143-147`): ```go if count >= int64(limit) { res.MaxDevicesReached = true res.LimitReached = true return nil } ``` There is no expiry anywhere: no `hwid*` key in `defaultValueMap` (`internal/web/service/setting.go:44`), no HWID job in `internal/web/job/`, and no such entry in the cron table (`docs/architecture.md:363-388`). Freeing a slot is manual only, through `ClearClientHwids` / `DeleteClientHwid` (`internal/web/service/client_hwid.go:191`, `:205`), exposed at `internal/web/controller/client.go:79-81`: ``` POST /panel/api/clients/hwids/:email # list DELETE /panel/api/clients/hwids/:email # clear all DELETE /panel/api/clients/hwids/:email/:id # remove one device ``` The per-device form landed in 1250fbb7 (#6245 / PR #6265, 2026-08-21) and ships in v3.7.0; the UI for it is `frontend/src/components/clients/ClientHwidList.tsx`. **Correction 1 — `client_hwids` does not grow indefinitely.** Rows per `sub_id` are already capped: inserts stop at the effective limit (the block quoted above), lowering `limit_hwid` trims the excess by `last_seen DESC` (`trimClientHwidsForSubID`, `internal/web/service/client_hwid.go:249-267`, called at `:246`), and deleting a client drops its rows (`clearClientHwidsBySubIDTx`, `:269`, call sites `client_crud.go:710`, `client_bulk.go:833`, `client_portable.go:210`). So the case for a TTL rests entirely on your first argument — a dead device holding a live slot — which is real; unbounded table growth is not. **Correction 2 — the SQL is SQLite-only.** The panel also runs on PostgreSQL (`XUI_DB_TYPE` / `XUI_DB_DSN`), where `strftime` does not exist, so the cutoff has to be computed in Go and applied through GORM. The existing precedent is the client-IP staleness sweep added in 103b0dfe: `cutoff := time.Now().Unix() - clientIpStaleAfterSeconds` (`internal/web/service/inbound_client_ips.go:244`), driven from `internal/web/job/check_client_ip_job.go`. Note the unit differs — `client_hwids.last_seen` is milliseconds (`now := time.Now().UnixMilli()`, `internal/web/service/client_hwid.go:117`), while the IP tables store seconds. **One design caveat worth stating in the request.** `last_seen` records when the device last *fetched the subscription*, not when it last used the tunnel. A client configured to update its subscription rarely or only manually would be evicted while still in active use, and would then re-register only if a slot happens to be free at its next fetch. That argues for your `default 0 = disabled`, and it also makes your option 3 (prune expired rows inside the existing transaction, only when the limit is actually reached) the least surprising of the three, and the smallest change — it needs no new cron job, just a cutoff check where the count is taken. If a panel-wide setting is added instead, it also carries the setting chain: a key in `defaultValueMap` (`internal/web/service/setting.go:44`), the settings API/UI, and one new key in all 13 locale files under `internal/web/translation/`. Related, not duplicates: #6245 (per-device removal, implemented) and #6234 (bulk editing of the HWID limit, still open). I have labelled this `enhancement`; the decision on whether to take it is the maintainer's. Verdict: Feature request *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@acidmsg commented on GitHub (Aug 31, 2026):

Thank you for the detailed analysis — especially the correction that client_hwids rows are already capped, and the note that last_seen tracks subscription fetches rather than actual tunnel usage. Both are accurate and match what we see in practice.

Follow-up on your "least surprising" option 3 (prune inside the existing transaction when the limit is reached):

We'd like to explore making it even more user-friendly for non-technical end users. Instead of just pruning expired rows by a TTL, what do you think of FIFO eviction on limit-reached:

When a new HWID arrives and count >= limit, instead of returning MaxDevicesReached = true (refusing the device), delete the row with the oldest last_seen for that sub_id and register the new device in the same transaction.

Rationale:

  • The most common real-world scenario is a lost/replaced device (phone lost, OS reinstall). The user simply connects with the new device and the stale slot frees itself — zero user action, zero admin action.
  • last_seen is refreshed on every subscription fetch, so an actively-used device is never evicted — eviction targets the device that hasn't fetched in the longest time.
  • It's the same code path you suggested (option 3): a cutoff check where the count is taken (internal/web/service/client_hwid.go:143-147), just replacing the refusal with delete-oldest + insert.
  • It also naturally bounds table growth without any cron job.

The obvious trade-off: a leaked subscription could displace the least-active device. In practice for small panels this seems acceptable — the evicted device was the one not being used, and its owner re-connects with the new device, evicting the intruder in turn (FIFO is self-healing under symmetric use).

One design question: should this be the default behavior, or gated behind a setting (e.g. hwidFifoEvict: true/false, default false to preserve current strict behavior)?

Would be curious about your take before we adjust the proposal.

<!-- gh-comment-id:5478632151 --> @acidmsg commented on GitHub (Aug 31, 2026): Thank you for the detailed analysis — especially the correction that `client_hwids` rows are already capped, and the note that `last_seen` tracks subscription fetches rather than actual tunnel usage. Both are accurate and match what we see in practice. **Follow-up on your "least surprising" option 3 (prune inside the existing transaction when the limit is reached):** We'd like to explore making it even more user-friendly for non-technical end users. Instead of just pruning expired rows by a TTL, what do you think of **FIFO eviction on limit-reached**: When a new HWID arrives and `count >= limit`, instead of returning `MaxDevicesReached = true` (refusing the device), delete the row with the **oldest `last_seen`** for that `sub_id` and register the new device in the same transaction. Rationale: - The most common real-world scenario is a lost/replaced device (phone lost, OS reinstall). The user simply connects with the new device and the stale slot frees itself — zero user action, zero admin action. - `last_seen` is refreshed on every subscription fetch, so an actively-used device is never evicted — eviction targets the device that hasn't fetched in the longest time. - It's the same code path you suggested (option 3): a cutoff check where the count is taken (`internal/web/service/client_hwid.go:143-147`), just replacing the refusal with delete-oldest + insert. - It also naturally bounds table growth without any cron job. The obvious trade-off: a leaked subscription could displace the least-active device. In practice for small panels this seems acceptable — the evicted device was the one not being used, and its owner re-connects with the new device, evicting the intruder in turn (FIFO is self-healing under symmetric use). One design question: should this be the **default behavior**, or gated behind a setting (e.g. `hwidFifoEvict: true/false`, default false to preserve current strict behavior)? Would be curious about your take before we adjust the proposal.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#4301
No description provided.