From 2541080c91dba5cb8f1b9f9b54aead30a3d3cfa5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:19:07 +0100 Subject: [PATCH 001/130] chore(deps): bump github.com/go-playground/validator/v10 (#7074) Bumps [github.com/go-playground/validator/v10](https://github.com/go-playground/validator) from 10.30.5 to 10.30.6. - [Release notes](https://github.com/go-playground/validator/releases) - [Commits](https://github.com/go-playground/validator/compare/v10.30.5...v10.30.6) --- updated-dependencies: - dependency-name: github.com/go-playground/validator/v10 dependency-version: 10.30.6 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index e447fee5c..ac44b4280 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/gin-contrib/sessions v1.1.3 github.com/gin-gonic/gin v1.12.0 github.com/go-ldap/ldap/v3 v3.4.15 - github.com/go-playground/validator/v10 v10.30.5 + github.com/go-playground/validator/v10 v10.30.6 github.com/goccy/go-json v0.12.0 github.com/goccy/go-yaml v1.19.2 github.com/google/uuid v1.6.0 diff --git a/go.sum b/go.sum index 5a3c43b35..483711405 100644 --- a/go.sum +++ b/go.sum @@ -51,8 +51,8 @@ github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9 github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= -github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4= -github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ= +github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo= +github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4= github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI= github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= From cd176faf4e1a1df4c45d5ccddac73edd2cb1f602 Mon Sep 17 00:00:00 2001 From: Benjamin Mitchell Date: Thu, 5 Nov 2026 09:02:39 -0800 Subject: [PATCH 002/130] fix(clients): reject dot names and recover legacy clients (#7062) Reject reserved dot-segment client names and recover legacy records through query aliases. Preserve token scopes and path identity precedence, and update the generated API reference. --- .../content/docs/en/reference/api/clients.mdx | 65 +++++- docs/public/openapi.json | 163 ++++++++++++- frontend/public/openapi.json | 163 ++++++++++++- frontend/src/api/client-management.ts | 5 + frontend/src/hooks/useClients.ts | 10 +- frontend/src/pages/api-docs/endpoints.ts | 51 ++++- frontend/src/schemas/client.ts | 1 + .../test/client-dot-name-recovery.test.tsx | 120 ++++++++++ frontend/src/test/client-name.test.ts | 22 ++ internal/web/controller/api.go | 2 + internal/web/controller/client.go | 31 ++- .../web/controller/client_dot_name_test.go | 216 ++++++++++++++++++ internal/web/controller/client_lookup_test.go | 40 ++++ internal/web/service/client_crud.go | 3 + .../service/client_email_validation_test.go | 6 + internal/web/translation/ar-EG.json | 1 + internal/web/translation/en-US.json | 1 + internal/web/translation/es-ES.json | 1 + internal/web/translation/fa-IR.json | 1 + internal/web/translation/id-ID.json | 1 + internal/web/translation/ja-JP.json | 1 + internal/web/translation/pt-BR.json | 1 + internal/web/translation/ru-RU.json | 1 + internal/web/translation/sk-SK.json | 1 + internal/web/translation/tr-TR.json | 1 + internal/web/translation/uk-UA.json | 1 + internal/web/translation/vi-VN.json | 1 + internal/web/translation/zh-CN.json | 1 + internal/web/translation/zh-TW.json | 1 + 29 files changed, 895 insertions(+), 17 deletions(-) create mode 100644 frontend/src/api/client-management.ts create mode 100644 frontend/src/test/client-dot-name-recovery.test.tsx create mode 100644 frontend/src/test/client-name.test.ts create mode 100644 internal/web/controller/client_dot_name_test.go diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index ab790f938..bf70abb01 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -28,6 +28,10 @@ _openapi: title: Fetch one client by email, including the inbound IDs and external config IDs it is attached to. url: '#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to' + - depth: 2 + title: Fetch one client by email, including the inbound IDs and external config + IDs it is attached to. + url: '#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to-1' - depth: 2 title: Fetch clients by subscription ID. url: '#fetch-clients-by-subscription-id' @@ -48,10 +52,19 @@ _openapi: inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch). url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch' + - depth: 2 + title: Update an existing client by email. Changes propagate to every attached + inbound. Body is the JSON client payload — supply the full set of fields + you want to keep (the server replaces the row, it does not patch). + url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch-1' - depth: 2 title: Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed. url: '#delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed' + - depth: 2 + title: Delete a client by email. Removes it from every attached inbound and + drops its traffic record unless keepTraffic=1 is passed. + url: '#delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1' - depth: 2 title: Attach an existing client to one or more additional inbounds. Body is JSON. @@ -324,6 +337,9 @@ _openapi: - content: Fetch one client by email, including the inbound IDs and external config IDs it is attached to. id: fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to + - content: Fetch one client by email, including the inbound IDs and external + config IDs it is attached to. + id: fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to-1 - content: Fetch clients by subscription ID. id: fetch-clients-by-subscription-id - content: Fetch clients by Telegram user ID. Returns an array since multiple @@ -340,9 +356,17 @@ _openapi: fields you want to keep (the server replaces the row, it does not patch). id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch + - content: Update an existing client by email. Changes propagate to every attached + inbound. Body is the JSON client payload — supply the full set of + fields you want to keep (the server replaces the row, it does not + patch). + id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch-1 - content: Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed. id: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed + - content: Delete a client by email. Removes it from every attached inbound and + drops its traffic record unless keepTraffic=1 is passed. + id: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1 - content: Attach an existing client to one or more additional inbounds. Body is JSON. id: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json @@ -564,6 +588,9 @@ _openapi: tunnel) contribute nothing.' id: return-every-url-for-one-client-across-all-attached-inbounds-one-per-advertised-endpoint-the-managed-hosts-of-the-inbound-else-its-streamsettingsexternalproxy-entries-else-its-own-address-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-mtproto-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing contents: + - content: Query-parameter alias for the path endpoint. Use email=. or email=.. to + manage legacy reserved names without URL dot-segment normalization. + heading: fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to-1 - content: Matches the exact subscription ID and orders results by client ID. Returns an array of the same payloads as GET /clients/get/:email, since multiple clients can share a subscription ID. Includes disabled, @@ -572,11 +599,14 @@ _openapi: email lookup. Requires an admin token or a panel login session. heading: fetch-clients-by-subscription-id - content: >- - Fields the server fills in when they are omitted — a valid value sent - by the caller is never overwritten. Re-adding an email that already - exists, with its stored `subId`, reuses the stored `id`, `password`, - `auth` and `secret` instead of minting new ones, so the identity stays - in sync across its inbounds. + Client email must not be exactly `.` or `..`. Existing reserved-name + clients can be read, renamed to a valid name, or deleted using the + query-parameter /get, /update and /del aliases. Fields the server + fills in when they are omitted — a valid value sent by the caller is + never overwritten. Re-adding an email that already exists, with its + stored `subId`, reuses the stored `id`, `password`, `auth` and + `secret` instead of minting new ones, so the identity stays in sync + across its inbounds. - **VLESS / VMess** — `id`, a fresh UUID @@ -650,6 +680,17 @@ _openapi: without an `inbound :` prefix and leaves the inbound edits in place.' heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch + - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + to manage legacy reserved names without URL dot-segment normalization. + The inbounds are applied concurrently and independently: one that + fails no longer stops the others. Every inbound error names the + inbound it came from (`inbound 7: `), and several failures + are reported together, one per line. So a `success:false` response can + still have applied the edit to the remaining inbounds. The client + record is written after the inbounds, so a failure there is reported + without an `inbound :` prefix and leaves the inbound edits in + place.' + heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch-1 - content: 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures @@ -660,6 +701,18 @@ _openapi: inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.' heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed + - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + to manage legacy reserved names without URL dot-segment normalization. + The inbounds are applied concurrently and independently: one that + fails no longer stops the others. Every inbound error names the + inbound it came from (`inbound 7: `), and several failures + are reported together, one per line. So a `success:false` response can + still have removed the client from the remaining inbounds; the client + record is kept in that case, so re-running the call retries exactly + the leftovers. The record and traffic rows are dropped after the + inbounds, so a failure there is reported without an `inbound :` + prefix and leaves the client already removed from every inbound.' + heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1 - content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
@@ -685,7 +738,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index c999960f5..557c7a764 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -8722,6 +8722,48 @@ } } }, + "/panel/api/clients/get": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Fetch one client by email, including the inbound IDs and external config IDs it is attached to.", + "operationId": "get_panel_api_clients_get", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email (unique identifier).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + } + } + } + } + } + } + }, "/panel/api/clients/get/subId/{subId}": { "get": { "tags": [ @@ -8845,7 +8887,7 @@ ], "summary": "Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.", "operationId": "post_panel_api_clients_add", - "description": "Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", + "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", "requestBody": { "required": true, "content": { @@ -9070,6 +9112,70 @@ } } }, + "/panel/api/clients/update": { + "post": { + "tags": [ + "Clients" + ], + "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).", + "operationId": "post_panel_api_clients_update", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Current client email (unique identifier).", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + }, + "example": { + "email": "alice@example.com", + "totalGB": 107374182400, + "expiryTime": 1767225600000, + "limitHwid": 2, + "tgId": 123456789, + "enable": true + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "msg": "Client updated" + } + } + } + } + } + } + }, "/panel/api/clients/del/{email}": { "post": { "tags": [ @@ -9125,6 +9231,61 @@ } } }, + "/panel/api/clients/del": { + "post": { + "tags": [ + "Clients" + ], + "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", + "operationId": "post_panel_api_clients_del", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email (unique identifier).", + "schema": { + "type": "string" + } + }, + { + "name": "keepTraffic", + "in": "query", + "required": true, + "description": "Pass 1 to retain the xray_client_traffic row after deletion.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "msg": "Client deleted" + } + } + } + } + } + } + }, "/panel/api/clients/{email}/attach": { "post": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index c999960f5..557c7a764 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -8722,6 +8722,48 @@ } } }, + "/panel/api/clients/get": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Fetch one client by email, including the inbound IDs and external config IDs it is attached to.", + "operationId": "get_panel_api_clients_get", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email (unique identifier).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + } + } + } + } + } + } + }, "/panel/api/clients/get/subId/{subId}": { "get": { "tags": [ @@ -8845,7 +8887,7 @@ ], "summary": "Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.", "operationId": "post_panel_api_clients_add", - "description": "Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", + "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", "requestBody": { "required": true, "content": { @@ -9070,6 +9112,70 @@ } } }, + "/panel/api/clients/update": { + "post": { + "tags": [ + "Clients" + ], + "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).", + "operationId": "post_panel_api_clients_update", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Current client email (unique identifier).", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + }, + "example": { + "email": "alice@example.com", + "totalGB": 107374182400, + "expiryTime": 1767225600000, + "limitHwid": 2, + "tgId": 123456789, + "enable": true + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "msg": "Client updated" + } + } + } + } + } + } + }, "/panel/api/clients/del/{email}": { "post": { "tags": [ @@ -9125,6 +9231,61 @@ } } }, + "/panel/api/clients/del": { + "post": { + "tags": [ + "Clients" + ], + "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", + "operationId": "post_panel_api_clients_del", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email (unique identifier).", + "schema": { + "type": "string" + } + }, + { + "name": "keepTraffic", + "in": "query", + "required": true, + "description": "Pass 1 to retain the xray_client_traffic row after deletion.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "msg": "Client deleted" + } + } + } + } + } + } + }, "/panel/api/clients/{email}/attach": { "post": { "tags": [ diff --git a/frontend/src/api/client-management.ts b/frontend/src/api/client-management.ts new file mode 100644 index 000000000..0ba8f6b63 --- /dev/null +++ b/frontend/src/api/client-management.ts @@ -0,0 +1,5 @@ +export function clientManagementPath(action: 'get' | 'update' | 'del', email: string): string { + const base = `/panel/api/clients/${action}`; + const encoded = encodeURIComponent(email); + return email === '.' || email === '..' ? `${base}?email=${encoded}` : `${base}/${encoded}`; +} diff --git a/frontend/src/hooks/useClients.ts b/frontend/src/hooks/useClients.ts index 199a47a2e..7020762ec 100644 --- a/frontend/src/hooks/useClients.ts +++ b/frontend/src/hooks/useClients.ts @@ -4,6 +4,7 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tansta import { HttpUtil, Msg } from '@/utils'; import { parseMsg } from '@/utils/zodValidate'; import { keys } from '@/api/queryKeys'; +import { clientManagementPath } from '@/api/client-management'; import { markLocalInvalidate } from '@/api/invalidationTracker'; import { ClientHydrateSchema, @@ -343,7 +344,7 @@ export function useClients(options: UseClientsOptions = {}) { const hydrate = useCallback(async (email: string): Promise => { if (!email) return null; - const msg = await HttpUtil.get(`/panel/api/clients/get/${encodeURIComponent(email)}`); + const msg = await HttpUtil.get(clientManagementPath('get', email)); if (!msg?.success || !msg.obj) return null; const validated = parseMsg(msg, ClientHydrateSchema, 'clients/get'); return validated.obj; @@ -375,7 +376,7 @@ export function useClients(options: UseClientsOptions = {}) { const updateMut = useMutation({ mutationFn: ({ email, client }: { email: string; client: unknown }) => - HttpUtil.post(`/panel/api/clients/update/${encodeURIComponent(email)}`, client, JSON_HEADERS), + HttpUtil.post(clientManagementPath('update', email), client, JSON_HEADERS), onSuccess: (msg) => { if (msg?.success) invalidateAll(); }, @@ -383,9 +384,8 @@ export function useClients(options: UseClientsOptions = {}) { const removeMut = useMutation({ mutationFn: ({ email, keepTraffic }: { email: string; keepTraffic?: boolean }) => { - const url = keepTraffic - ? `/panel/api/clients/del/${encodeURIComponent(email)}?keepTraffic=1` - : `/panel/api/clients/del/${encodeURIComponent(email)}`; + let url = clientManagementPath('del', email); + if (keepTraffic) url += `${url.includes('?') ? '&' : '?'}keepTraffic=1`; return HttpUtil.post(url); }, onSuccess: (msg) => { diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 3f5b44bfa..c968b440e 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1149,6 +1149,19 @@ export const sections: readonly Section[] = [ response: '{\n "success": true,\n "obj": {\n "client": { "id": 1, "email": "alice@example.com", ... },\n "inboundIds": [3, 5],\n "externalLinks": [\n { "id": 11, "kind": "link", "value": "vless://...", "remark": "DE", "enable": true, "expiryTime": 0 },\n { "id": 12, "kind": "subscription", "value": "https://provider.example/sub/abc", "remark": "Provider", "enable": false, "expiryTime": 1767225600000, "namePrefix": "[zjh] ", "lastFetchAt": 1767220000000, "lastFetchError": "" }\n ]\n }\n}', }, + { + method: 'GET', + path: '/panel/api/clients/get', + summary: + 'Fetch one client by email, including the inbound IDs and external config IDs it is attached to.', + description: + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization.', + params: [ + { name: 'email', in: 'query', type: 'string', desc: 'Client email (unique identifier).' }, + ], + response: + '{\n "success": true,\n "obj": {\n "client": { "id": 1, "email": "alice@example.com", ... },\n "inboundIds": [3, 5],\n "externalLinks": [\n { "id": 11, "kind": "link", "value": "vless://...", "remark": "DE", "enable": true, "expiryTime": 0 },\n { "id": 12, "kind": "subscription", "value": "https://provider.example/sub/abc", "remark": "Provider", "enable": false, "expiryTime": 1767225600000, "namePrefix": "[zjh] ", "lastFetchAt": 1767220000000, "lastFetchError": "" }\n ]\n }\n}', + }, { method: 'GET', path: '/panel/api/clients/get/subId/:subId', @@ -1195,7 +1208,7 @@ export const sections: readonly Section[] = [ summary: 'Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.', description: - 'Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.', + 'Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.', params: [ { name: 'client', @@ -1277,6 +1290,24 @@ export const sections: readonly Section[] = [ body: '{\n "email": "alice@example.com",\n "totalGB": 107374182400,\n "expiryTime": 1767225600000,\n "limitHwid": 2,\n "tgId": 123456789,\n "enable": true\n}', response: '{\n "success": true,\n "msg": "Client updated"\n}', }, + { + method: 'POST', + path: '/panel/api/clients/update', + summary: + 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).', + description: + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + params: [ + { + name: 'email', + in: 'query', + type: 'string', + desc: 'Current client email (unique identifier).', + }, + ], + body: '{\n "email": "alice@example.com",\n "totalGB": 107374182400,\n "expiryTime": 1767225600000,\n "limitHwid": 2,\n "tgId": 123456789,\n "enable": true\n}', + response: '{\n "success": true,\n "msg": "Client updated"\n}', + }, { method: 'POST', path: '/panel/api/clients/del/:email', @@ -1295,6 +1326,24 @@ export const sections: readonly Section[] = [ ], response: '{\n "success": true,\n "msg": "Client deleted"\n}', }, + { + method: 'POST', + path: '/panel/api/clients/del', + summary: + 'Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.', + description: + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.', + params: [ + { name: 'email', in: 'query', type: 'string', desc: 'Client email (unique identifier).' }, + { + name: 'keepTraffic', + in: 'query', + type: 'integer', + desc: 'Pass 1 to retain the xray_client_traffic row after deletion.', + }, + ], + response: '{\n "success": true,\n "msg": "Client deleted"\n}', + }, { method: 'POST', path: '/panel/api/clients/:email/attach', diff --git a/frontend/src/schemas/client.ts b/frontend/src/schemas/client.ts index 2f7894a3a..9ff2a45b7 100644 --- a/frontend/src/schemas/client.ts +++ b/frontend/src/schemas/client.ts @@ -319,6 +319,7 @@ export const ClientFormSchema = z.object({ .string() .trim() .min(1, 'pages.clients.email') + .refine((v) => v !== '.' && v !== '..', 'pages.clients.emailReservedName') .refine((v) => !hasForbiddenClientChars(v), 'pages.clients.emailInvalidChars'), subId: z.string().refine((v) => !hasForbiddenClientChars(v), 'pages.clients.subIdInvalidChars'), uuid: z.string(), diff --git a/frontend/src/test/client-dot-name-recovery.test.tsx b/frontend/src/test/client-dot-name-recovery.test.tsx new file mode 100644 index 000000000..9e3190bd4 --- /dev/null +++ b/frontend/src/test/client-dot-name-recovery.test.tsx @@ -0,0 +1,120 @@ +import type { ReactNode } from 'react'; +import { act, renderHook } from '@testing-library/react'; +import { QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { setupHttp } from '@/api/http-init'; +import { useClients } from '@/hooks/useClients'; +import { makeTestQueryClient } from '@/test/test-utils'; +import { HttpUtil } from '@/utils'; + +const ORIGIN = 'https://example.invalid'; +const BASE = '/audit/panel/api/clients/'; + +describe('legacy dot-name client recovery', () => { + const requests: { url: URL; method: string; body: unknown }[] = []; + + beforeAll(() => { + vi.mocked(HttpUtil.get).mockRestore(); + vi.mocked(HttpUtil.post).mockRestore(); + }); + + beforeEach(() => { + requests.length = 0; + window.X_UI_BASE_PATH = `${ORIGIN}/audit/`; + setupHttp(); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string, init?: RequestInit) => { + const url = new URL(input); + const method = init?.method ?? 'GET'; + if (!url.pathname.startsWith(BASE)) { + const obj = url.pathname.endsWith('/csrf-token') ? 'audit-csrf' : {}; + return Response.json({ success: true, obj }); + } + if (url.pathname.endsWith('/options') || url.pathname.endsWith('/onlines')) { + return Response.json({ success: true, obj: [] }); + } + const body = init?.body ? JSON.parse(String(init.body)) : null; + requests.push({ url, method, body }); + const [action, segment] = url.pathname.slice(BASE.length).split('/'); + const email = + url.searchParams.get('email') ?? (segment ? decodeURIComponent(segment) : null); + if (action === 'get' && email) { + return Response.json({ + success: true, + obj: { client: { email, uuid: 'kept-uuid' }, inboundIds: [7] }, + }); + } + if (['update', 'del'].includes(action) && email) { + return Response.json({ success: true }); + } + return Response.json({ success: false, msg: 'Missing client identity' }, { status: 404 }); + }), + ); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + delete window.X_UI_BASE_PATH; + setupHttp(); + }); + + function wrapper({ children }: { children: ReactNode }) { + return {children}; + } + + it.each(['.', '..'])('loads the full record and renames a legacy %j client', async (email) => { + const { result } = renderHook(() => useClients({ list: false }), { wrapper }); + await act(async () => { + const full = await result.current.hydrate(email); + expect(full?.client.uuid).toBe('kept-uuid'); + expect(full?.inboundIds).toEqual([7]); + const msg = await result.current.update(email, { + email: 'restored-client', + id: full?.client.uuid, + }); + expect(msg.success).toBe(true); + }); + const update = requests.find((r) => r.url.pathname === `${BASE}update`); + expect(update?.url.searchParams.get('email')).toBe(email); + expect(update?.body).toEqual({ email: 'restored-client', id: 'kept-uuid' }); + }); + + it.each(['.', '..'])( + 'individually deletes legacy %j while preserving keepTraffic', + async (email) => { + const { result } = renderHook(() => useClients({ list: false }), { wrapper }); + await act(async () => { + const msg = await result.current.remove(email, true); + expect(msg.success).toBe(true); + }); + const request = requests.find((r) => r.url.pathname === `${BASE}del`); + expect(request?.method).toBe('POST'); + expect(request?.url.searchParams.get('email')).toBe(email); + expect(request?.url.searchParams.get('keepTraffic')).toBe('1'); + }, + ); + + it.each(['...', '.alice', 'alice.', 'alice.example', 'alice..example'])( + 'keeps the existing path endpoints for %s', + async (email) => { + const { result } = renderHook(() => useClients({ list: false }), { wrapper }); + await act(async () => { + expect((await result.current.hydrate(email))?.client.email).toBe(email); + expect((await result.current.update(email, { email })).success).toBe(true); + expect((await result.current.remove(email, true)).success).toBe(true); + }); + for (const action of ['get', 'update', 'del']) { + const request = requests.find((r) => r.url.pathname === `${BASE}${action}/${email}`); + expect(request).toBeDefined(); + expect(request?.url.searchParams.has('email')).toBe(false); + } + expect( + requests + .find((r) => r.url.pathname === `${BASE}del/${email}`) + ?.url.searchParams.get('keepTraffic'), + ).toBe('1'); + }, + ); +}); diff --git a/frontend/src/test/client-name.test.ts b/frontend/src/test/client-name.test.ts new file mode 100644 index 000000000..52cce93a1 --- /dev/null +++ b/frontend/src/test/client-name.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; + +import { ClientCreateFormSchema, ClientFormSchema } from '@/schemas/client'; + +describe('client name validation', () => { + it.each(['.', '..', ' . ', ' .. '])('rejects the reserved name %j on create and edit', (name) => { + for (const schema of [ClientCreateFormSchema, ClientFormSchema]) { + const result = schema.shape.email.safeParse(name); + expect(result.success).toBe(false); + if (!result.success) { + expect(result.error.issues[0].message).toBe('pages.clients.emailReservedName'); + } + } + }); + + it.each(['...', '.alice', 'alice.', 'alice.example', 'alice..example', 'alice@example.com'])( + 'preserves ordinary dotted names: %s', + (name) => { + expect(ClientFormSchema.shape.email.parse(name)).toBe(name); + }, + ); +}); diff --git a/internal/web/controller/api.go b/internal/web/controller/api.go index 4c9038f16..d046ed23c 100644 --- a/internal/web/controller/api.go +++ b/internal/web/controller/api.go @@ -105,8 +105,10 @@ var nodeSyncScopeAllow = map[string]map[string]struct{}{ "/inbounds/:id/subSortIndex": {http.MethodPost: {}}, "/clients/add": {http.MethodPost: {}}, "/clients/del/:email": {http.MethodPost: {}}, + "/clients/del": {http.MethodPost: {}}, "/clients/:email/detach": {http.MethodPost: {}}, "/clients/update/:email": {http.MethodPost: {}}, + "/clients/update": {http.MethodPost: {}}, "/server/restartXrayService": {http.MethodPost: {}}, "/server/getWebCertFiles": {http.MethodGet: {}}, "/server/descendants": {http.MethodGet: {}}, diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 2c7c5e3ef..97c924410 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -53,6 +53,7 @@ func NewClientController(g *gin.RouterGroup) *ClientController { func (a *ClientController) initRouter(g *gin.RouterGroup) { g.GET("/list", a.list) g.GET("/list/paged", a.listPaged) + g.GET("/get", a.get) g.GET("/get/:email", a.get) g.GET("/get/subId/:subId", a.getBySubId) g.GET("/get/tgId/:tgId", a.getByTgId) @@ -63,7 +64,9 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) { g.POST("/add", a.create) g.POST("/renewalPreview", a.renewalPreview) + g.POST("/update", a.update) g.POST("/update/:email", a.update) + g.POST("/del", a.delete) g.POST("/del/:email", a.delete) g.POST("/:email/attach", a.attach) g.POST("/:email/detach", a.detach) @@ -159,8 +162,24 @@ func (a *ClientController) buildClientPayload(rec *model.ClientRecord) (gin.H, e }, nil } -func (a *ClientController) get(c *gin.Context) { +// Query aliases keep legacy dot-segment names addressable without changing path clients. +func clientEmailParam(c *gin.Context) (string, bool) { email := c.Param("email") + if email == "" { + email = c.Query("email") + } + if email == "" { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client email is required")) + return "", false + } + return email, true +} + +func (a *ClientController) get(c *gin.Context) { + email, ok := clientEmailParam(c) + if !ok { + return + } rec, err := a.clientService.GetRecordByEmail(nil, email) if err != nil { jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err) @@ -244,7 +263,10 @@ func (a *ClientController) create(c *gin.Context) { } func (a *ClientController) update(c *gin.Context) { - email := c.Param("email") + email, ok := clientEmailParam(c) + if !ok { + return + } var req struct { model.Client LimitHwid int `json:"limitHwid"` @@ -273,7 +295,10 @@ func (a *ClientController) update(c *gin.Context) { } func (a *ClientController) delete(c *gin.Context) { - email := c.Param("email") + email, ok := clientEmailParam(c) + if !ok { + return + } keepTraffic := c.Query("keepTraffic") == "1" needRestart, err := a.clientService.DeleteByEmail(&a.inboundService, email, keepTraffic) // Flagged before the error check: a partly-applied delete already removed diff --git a/internal/web/controller/client_dot_name_test.go b/internal/web/controller/client_dot_name_test.go new file mode 100644 index 000000000..272b73a85 --- /dev/null +++ b/internal/web/controller/client_dot_name_test.go @@ -0,0 +1,216 @@ +package controller + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/gin-gonic/gin" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/entity" + "github.com/mhsanaei/3x-ui/v3/internal/web/locale" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func seedLegacyDotClient(t *testing.T, email string) (*gin.Engine, model.ClientRecord, model.Inbound) { + t.Helper() + dir := t.TempDir() + t.Setenv("XUI_DB_FOLDER", dir) + dbtest.InitDB(t, filepath.Join(dir, "x-ui.db")) + db := database.GetDB() + rec := model.ClientRecord{Email: email, UUID: "11111111-2222-3333-4444-555555555555", SubID: "legacy-dot-sub", Enable: true} + if err := db.Create(&rec).Error; err != nil { + t.Fatal(err) + } + settings, err := json.Marshal(map[string]any{ + "clients": []model.Client{*rec.ToClient()}, + "decryption": "none", + }) + if err != nil { + t.Fatal(err) + } + ib := model.Inbound{Tag: "legacy-dot", Port: 443, Protocol: model.VLESS, Settings: string(settings), StreamSettings: `{"network":"tcp","security":"none"}`} + if err := db.Create(&ib).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: ib.Id}).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&xray.ClientTraffic{Email: email, InboundId: ib.Id, Up: 111, Down: 222, Enable: true}).Error; err != nil { + t.Fatal(err) + } + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set("I18n", func(_ locale.I18nType, key string, _ ...string) string { return key }) + c.Next() + }) + NewClientController(router.Group("/base/panel/api/clients")) + return router, rec, ib +} + +func dotClientRequest(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder { + t.Helper() + payload, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(method, "/base/panel/api/clients/"+path, bytes.NewReader(payload)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + return w +} + +func assertDotClientSuccess(t *testing.T, w *httptest.ResponseRecorder) { + t.Helper() + var msg entity.Msg + if err := json.Unmarshal(w.Body.Bytes(), &msg); err != nil { + t.Fatal(err) + } + if w.Code != http.StatusOK || !msg.Success { + t.Fatalf("status/body = %d/%s", w.Code, w.Body.String()) + } +} + +func TestClientQueryAliasRecoversLegacyDotName(t *testing.T) { + for _, email := range []string{".", ".."} { + t.Run(email, func(t *testing.T) { + router, rec, ib := seedLegacyDotClient(t, email) + query := "?email=" + url.QueryEscape(email) + w := dotClientRequest(t, router, http.MethodGet, "get"+query, nil) + assertDotClientSuccess(t, w) + var full struct { + Obj struct { + Client model.ClientRecord `json:"client"` + InboundIDs []int `json:"inboundIds"` + UsedTraffic int64 `json:"usedTraffic"` + } `json:"obj"` + } + if err := json.Unmarshal(w.Body.Bytes(), &full); err != nil { + t.Fatal(err) + } + if full.Obj.Client.Email != email || full.Obj.Client.UUID != rec.UUID || len(full.Obj.InboundIDs) != 1 || full.Obj.InboundIDs[0] != ib.Id || full.Obj.UsedTraffic != 333 { + t.Fatalf("unexpected legacy payload: %s", w.Body.String()) + } + updated := rec.ToClient() + updated.Email = "restored-client" + w = dotClientRequest(t, router, http.MethodPost, "update"+query, updated) + assertDotClientSuccess(t, w) + db := database.GetDB() + var after model.ClientRecord + if err := db.First(&after, rec.Id).Error; err != nil { + t.Fatal(err) + } + if after.Email != updated.Email || after.UUID != rec.UUID || after.SubID != rec.SubID { + t.Fatalf("rename changed identity: %+v", after) + } + if err := db.First(&ib, ib.Id).Error; err != nil { + t.Fatal(err) + } + var settings struct { + Clients []model.Client `json:"clients"` + } + if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil { + t.Fatal(err) + } + if len(settings.Clients) != 1 || settings.Clients[0].Email != updated.Email || settings.Clients[0].ID != rec.UUID { + t.Fatalf("rename lost inbound credentials: %s", ib.Settings) + } + var traffic xray.ClientTraffic + if err := db.Where("email = ?", updated.Email).First(&traffic).Error; err != nil { + t.Fatal(err) + } + if traffic.Up != 111 || traffic.Down != 222 { + t.Fatalf("rename lost usage: %+v", traffic) + } + }) + } +} + +func TestClientQueryAliasDeletesLegacyDotName(t *testing.T) { + for _, email := range []string{".", ".."} { + for _, keep := range []bool{false, true} { + t.Run(email+"/keep="+strconv.FormatBool(keep), func(t *testing.T) { + router, rec, ib := seedLegacyDotClient(t, email) + path := "del?email=" + url.QueryEscape(email) + if keep { + path += "&keepTraffic=1" + } + w := dotClientRequest(t, router, http.MethodPost, path, nil) + assertDotClientSuccess(t, w) + db := database.GetDB() + var count int64 + if err := db.Model(&model.ClientRecord{}).Where("id = ?", rec.Id).Count(&count).Error; err != nil || count != 0 { + t.Fatalf("client remains: count=%d err=%v", count, err) + } + if err := db.Model(&model.ClientInbound{}).Where("client_id = ?", rec.Id).Count(&count).Error; err != nil || count != 0 { + t.Fatalf("attachment remains: count=%d err=%v", count, err) + } + if err := db.First(&ib, ib.Id).Error; err != nil { + t.Fatal(err) + } + var settings struct { + Clients []model.Client `json:"clients"` + } + if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil || len(settings.Clients) != 0 { + t.Fatalf("inbound client remains: %s err=%v", ib.Settings, err) + } + if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", email).Count(&count).Error; err != nil { + t.Fatal(err) + } + var want int64 + if keep { + want = 1 + } + if count != want { + t.Fatalf("retained traffic count=%d keep=%v", count, keep) + } + }) + } + } +} + +func TestClientQueryAliasRequiresEmail(t *testing.T) { + router, _, _ := seedLegacyDotClient(t, ".") + for _, route := range []struct { + method, path string + }{ + {http.MethodGet, "get"}, {http.MethodPost, "update"}, {http.MethodPost, "del"}, + } { + w := dotClientRequest(t, router, route.method, route.path, map[string]any{"email": "must-not-be-used-as-target"}) + var msg entity.Msg + if err := json.Unmarshal(w.Body.Bytes(), &msg); err != nil { + t.Fatal(err) + } + if msg.Success || !strings.Contains(msg.Msg, "client email is required") { + t.Fatalf("missing query accepted: %s", w.Body.String()) + } + } +} + +func TestClientPathEmailTakesPrecedenceOverQuery(t *testing.T) { + router, legacy, _ := seedLegacyDotClient(t, ".") + normal := model.ClientRecord{Email: "audit-client", UUID: "normal-uuid", SubID: "normal-sub", Enable: true} + db := database.GetDB() + if err := db.Create(&normal).Error; err != nil { + t.Fatal(err) + } + w := dotClientRequest(t, router, http.MethodPost, "del/audit-client?email=.", nil) + assertDotClientSuccess(t, w) + var count int64 + if err := db.Model(&model.ClientRecord{}).Where("id = ?", normal.Id).Count(&count).Error; err != nil || count != 0 { + t.Fatalf("path client remains: count=%d err=%v", count, err) + } + if err := db.Model(&model.ClientRecord{}).Where("id = ?", legacy.Id).Count(&count).Error; err != nil || count != 1 { + t.Fatalf("query overrode the path identity: count=%d err=%v", count, err) + } +} diff --git a/internal/web/controller/client_lookup_test.go b/internal/web/controller/client_lookup_test.go index 1e7cd892c..815049d3d 100644 --- a/internal/web/controller/client_lookup_test.go +++ b/internal/web/controller/client_lookup_test.go @@ -152,3 +152,43 @@ func TestClientGetBySubIDRequiresAdmin(t *testing.T) { }) } } + +func TestClientQueryAliasTokenScopes(t *testing.T) { + router, api := newAPIAuthTestEngine(t) + NewClientController(router.Group("/base/panel/api/clients", api.checkAPIAuth, api.enforceTokenScope)) + for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeMonitor, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin} { + if err := database.GetDB().Create(&model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Enabled: true, Scope: scope}).Error; err != nil { + t.Fatal(err) + } + } + for _, route := range []struct { + method string + path string + }{ + {http.MethodGet, "get"}, + {http.MethodPost, "update"}, + {http.MethodPost, "del"}, + } { + for _, scope := range []string{"", model.ApiScopeAdmin, model.ApiScopeMonitor, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin} { + t.Run(route.path+"/scope="+scope, func(t *testing.T) { + req := httptest.NewRequest(route.method, "/base/panel/api/clients/"+route.path+"?email=missing", strings.NewReader(`{"email":"restored-client"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Requested-With", "XMLHttpRequest") + if scope != "" { + req.Header.Set("Authorization", "Bearer "+scope) + } + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + want := http.StatusOK + if scope == "" { + want = http.StatusUnauthorized + } else if scope == model.ApiScopeMonitor || (route.method == http.MethodGet && scope != model.ApiScopeAdmin) { + want = http.StatusForbidden + } + if w.Code != want { + t.Fatalf("status = %d, want %d, body = %s", w.Code, want, w.Body.String()) + } + }) + } + } +} diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 392fa563a..7f1687fba 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -37,6 +37,9 @@ func hasForbiddenClientChar(s string) bool { } func validateClientEmail(email string) error { + if email == "." || email == ".." { + return common.NewError("client email must not be '.' or '..'") + } if hasForbiddenClientChar(email) { return common.NewError("client email contains an invalid character:", email) } diff --git a/internal/web/service/client_email_validation_test.go b/internal/web/service/client_email_validation_test.go index 4e01b2079..2f849d37a 100644 --- a/internal/web/service/client_email_validation_test.go +++ b/internal/web/service/client_email_validation_test.go @@ -7,6 +7,10 @@ func TestValidateClientEmail(t *testing.T) { "alice", "alice@example.com", "user-123_test.name", + "...", + ".alice", + "alice.", + "alice..example", "имя", } for _, email := range valid { @@ -16,6 +20,8 @@ func TestValidateClientEmail(t *testing.T) { } invalid := []string{ + ".", + "..", "i6dui/", "a/b", "client with spaces", diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index fb570a464..194eca6fc 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -876,6 +876,7 @@ "subIdDesc": "يُستخدم أيضًا كرمز دعوة لهذا العميل في بوت تيليجرام: من يرسله إلى البوت يُربط بهذا العميل. اجعله طويلًا وعشوائيًا — فالمعرّف القصير أو السهل التخمين قد يستولي عليه شخص آخر.", "online": "متصل", "email": "البريد", + "emailReservedName": "لا يمكن أن يكون اسم العميل «.» أو «..» فقط", "emailInvalidChars": "لا يمكن أن يحتوي البريد الإلكتروني على مسافات أو '/' أو '\\' أو أحرف تحكم", "subIdInvalidChars": "لا يمكن أن يحتوي معرّف الاشتراك على مسافات أو '/' أو '\\' أو أحرف تحكم", "group": "المجموعة", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index a11d6d4a0..ed3c13da0 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -876,6 +876,7 @@ "subIdDesc": "Also works as this client's Telegram bot invite code: whoever sends it to the bot is linked to this client. Keep it long and random — a short or guessable ID can be claimed by someone else.", "online": "Online", "email": "Email", + "emailReservedName": "Client name cannot be exactly \".\" or \"..\"", "emailInvalidChars": "Email cannot contain spaces, '/', '\\', or control characters", "subIdInvalidChars": "Subscription ID cannot contain spaces, '/', '\\', or control characters", "group": "Group", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 3bb0f0ce2..4515a5e97 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -876,6 +876,7 @@ "subIdDesc": "También sirve como código de invitación de este cliente en el bot de Telegram: quien lo envíe al bot queda vinculado a este cliente. Mantenlo largo y aleatorio: un ID corto o fácil de adivinar puede ser reclamado por otra persona.", "online": "En línea", "email": "Email", + "emailReservedName": "El nombre del cliente no puede ser exactamente \".\" o \"..\"", "emailInvalidChars": "El correo no puede contener espacios, '/', '\\' ni caracteres de control", "subIdInvalidChars": "El ID de suscripción no puede contener espacios, '/', '\\' ni caracteres de control", "group": "Grupo", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 957fb8c2e..16c5a1cc2 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -876,6 +876,7 @@ "subIdDesc": "این شناسه، کد دعوت این کاربر در ربات تلگرام هم هست: هر کسی آن را به ربات بفرستد به این کاربر متصل می‌شود. آن را طولانی و تصادفی نگه دارید؛ شناسهٔ کوتاه یا قابل حدس ممکن است توسط شخص دیگری تصاحب شود.", "online": "آنلاین", "email": "ایمیل", + "emailReservedName": "نام کاربر نمی‌تواند فقط «.» یا «..» باشد", "emailInvalidChars": "ایمیل نمی‌تواند شامل فاصله، '/'، '\\' یا کاراکترهای کنترلی باشد", "subIdInvalidChars": "شناسه‌ی اشتراک نمی‌تواند شامل فاصله، '/'، '\\' یا کاراکترهای کنترلی باشد", "group": "گروه", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index e14b66968..9afc4339b 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -876,6 +876,7 @@ "subIdDesc": "Juga berfungsi sebagai kode undangan bot Telegram untuk klien ini: siapa pun yang mengirimkannya ke bot akan ditautkan ke klien ini. Buat panjang dan acak — ID yang pendek atau mudah ditebak bisa diklaim orang lain.", "online": "Online", "email": "Email", + "emailReservedName": "Nama klien tidak boleh hanya \".\" atau \"..\"", "emailInvalidChars": "Email tidak boleh mengandung spasi, '/', '\\', atau karakter kontrol", "subIdInvalidChars": "ID langganan tidak boleh mengandung spasi, '/', '\\', atau karakter kontrol", "group": "Grup", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index f238906b5..9472664b0 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -876,6 +876,7 @@ "subIdDesc": "このクライアントの Telegram ボット招待コードとしても使われます。ボットに送信した人がこのクライアントに紐付けられます。長くランダムな値にしてください。短い、または推測しやすい ID は他人に取得されるおそれがあります。", "online": "オンライン", "email": "メール", + "emailReservedName": "クライアント名を「.」または「..」だけにすることはできません", "emailInvalidChars": "メールアドレスにスペース、'/'、'\\'、または制御文字を含めることはできません", "subIdInvalidChars": "サブスクリプションIDにスペース、'/'、'\\'、または制御文字を含めることはできません", "group": "グループ", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index b014a82e7..3df23658d 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -876,6 +876,7 @@ "subIdDesc": "Também funciona como código de convite deste cliente no bot do Telegram: quem enviá-lo ao bot fica vinculado a este cliente. Mantenha-o longo e aleatório — um ID curto ou fácil de adivinhar pode ser reivindicado por outra pessoa.", "online": "Online", "email": "Email", + "emailReservedName": "O nome do cliente não pode ser exatamente \".\" ou \"..\"", "emailInvalidChars": "O e-mail não pode conter espaços, '/', '\\' ou caracteres de controle", "subIdInvalidChars": "O ID de assinatura não pode conter espaços, '/', '\\' ou caracteres de controle", "group": "Grupo", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 86adf35cd..2fc6a751c 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -876,6 +876,7 @@ "subIdDesc": "Также служит кодом приглашения этого клиента в Telegram-боте: тот, кто отправит его боту, будет привязан к этому клиенту. Используйте длинное случайное значение — короткий или легко угадываемый ID может присвоить кто-то другой.", "online": "В сети", "email": "Email", + "emailReservedName": "Имя клиента не может состоять только из «.» или «..»", "emailInvalidChars": "Email не может содержать пробелы, '/', '\\' или управляющие символы", "subIdInvalidChars": "ID подписки не может содержать пробелы, '/', '\\' или управляющие символы", "group": "Группа", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index c21a2c7ca..bd49a3bb1 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -876,6 +876,7 @@ "subIdDesc": "Slúži aj ako pozývací kód klienta do Telegram bota. Kto ho pošle botovi, priradí sa k tomuto klientovi. Použite dlhé náhodné ID. Krátke alebo odhadnuteľné ID si môže privlastniť niekto iný.", "online": "Online", "email": "Názov klienta", + "emailReservedName": "Názov klienta nesmie byť presne \".\" ani \"..\"", "emailInvalidChars": "Názov klienta nesmie obsahovať medzery, '/', '\\' ani riadiace znaky", "subIdInvalidChars": "ID odberu nesmie obsahovať medzery, '/', '\\' ani riadiace znaky", "group": "Skupina", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 99c1183be..593e4932c 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -876,6 +876,7 @@ "subIdDesc": "Bu istemcinin Telegram botu davet kodu olarak da kullanılır: bunu bota gönderen kişi bu istemciye bağlanır. Uzun ve rastgele tutun — kısa veya tahmin edilebilir bir kimlik başkası tarafından sahiplenilebilir.", "online": "Çevrimiçi", "email": "E-posta", + "emailReservedName": "İstemci adı yalnızca \".\" veya \"..\" olamaz", "emailInvalidChars": "E-posta boşluk, '/', '\\' veya kontrol karakterleri içeremez", "subIdInvalidChars": "Abonelik kimliği boşluk, '/', '\\' veya kontrol karakterleri içeremez", "group": "Grup", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 690efd610..506df1d42 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -876,6 +876,7 @@ "subIdDesc": "Також слугує кодом запрошення цього клієнта в Telegram-боті: той, хто надішле його боту, буде прив'язаний до цього клієнта. Використовуйте довге випадкове значення — короткий або легко вгадуваний ID може привласнити хтось інший.", "online": "У мережі", "email": "Email", + "emailReservedName": "Ім’я клієнта не може складатися лише з «.» або «..»", "emailInvalidChars": "Email не може містити пробіли, '/', '\\' або керуючі символи", "subIdInvalidChars": "ID підписки не може містити пробіли, '/', '\\' або керуючі символи", "group": "Група", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 54bf57deb..1723feeec 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -876,6 +876,7 @@ "subIdDesc": "Cũng được dùng làm mã mời bot Telegram của client này: ai gửi mã này cho bot sẽ được liên kết với client. Hãy để mã dài và ngẫu nhiên — ID ngắn hoặc dễ đoán có thể bị người khác chiếm.", "online": "Trực tuyến", "email": "Email", + "emailReservedName": "Tên máy khách không được chỉ là \".\" hoặc \"..\"", "emailInvalidChars": "Email không được chứa khoảng trắng, '/', '\\' hoặc ký tự điều khiển", "subIdInvalidChars": "ID đăng ký không được chứa khoảng trắng, '/', '\\' hoặc ký tự điều khiển", "group": "Nhóm", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index ef97d0351..5e98edf8c 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -876,6 +876,7 @@ "subIdDesc": "同时用作该客户端的 Telegram 机器人邀请码:任何人将其发送给机器人即会绑定到此客户端。请保持足够长且随机——过短或易猜的 ID 可能被他人抢先绑定。", "online": "在线", "email": "邮箱", + "emailReservedName": "客户端名称不能仅为“.”或“..”", "emailInvalidChars": "邮箱不能包含空格、'/'、'\\' 或控制字符", "subIdInvalidChars": "订阅 ID 不能包含空格、'/'、'\\' 或控制字符", "group": "分组", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 2a49cc8cb..1d522f9cf 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -876,6 +876,7 @@ "subIdDesc": "同時作為此用戶端的 Telegram 機器人邀請碼:任何人將其傳送給機器人即會綁定到此用戶端。請保持足夠長且隨機——過短或容易猜到的 ID 可能被他人搶先綁定。", "online": "上線", "email": "電子郵件", + "emailReservedName": "用戶端名稱不能僅為「.」或「..」", "emailInvalidChars": "電子郵件不能包含空格、'/'、'\\' 或控制字元", "subIdInvalidChars": "訂閱 ID 不能包含空格、'/'、'\\' 或控制字元", "group": "群組", From e4935be8617688126ad5478143b6d58a528676b6 Mon Sep 17 00:00:00 2001 From: Aleksey Fedorov <320380254+Dv2Corn@users.noreply.github.com> Date: Fri, 6 Nov 2026 03:06:16 +1000 Subject: [PATCH 003/130] fix(api): preserve omitted client fields in partial updates (#7042) Keep omitted client fields and per-inbound flows unchanged while honoring explicit clears. Support the query aliases used to recover legacy dot-name clients and regenerate the API reference. Add an HTTP regression covering partial updates through those aliases. --- .../content/docs/en/reference/api/clients.mdx | 70 ++++---- .../content/docs/fa/reference/api/clients.mdx | 15 +- .../content/docs/ru/reference/api/clients.mdx | 15 +- .../content/docs/zh/reference/api/clients.mdx | 12 +- docs/public/openapi.json | 8 +- frontend/public/openapi.json | 8 +- frontend/src/pages/api-docs/endpoints.ts | 8 +- .../src/pages/clients/ClientFormModal.tsx | 6 +- .../src/test/client-form-reverse.test.tsx | 64 +++++++ internal/web/controller/client.go | 9 +- .../controller/client_partial_update_test.go | 74 ++++++++ internal/web/service/client_crud.go | 17 ++ internal/web/service/client_partial_update.go | 130 ++++++++++++++ .../web/service/client_partial_update_test.go | 160 ++++++++++++++++++ 14 files changed, 525 insertions(+), 71 deletions(-) create mode 100644 frontend/src/test/client-form-reverse.test.tsx create mode 100644 internal/web/controller/client_partial_update_test.go create mode 100644 internal/web/service/client_partial_update.go create mode 100644 internal/web/service/client_partial_update_test.go diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index bf70abb01..0d8399316 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -48,15 +48,17 @@ _openapi: title: Preview client auto-renewal dates without saving or resetting anything. url: '#preview-client-auto-renewal-dates-without-saving-or-resetting-anything' - depth: 2 - title: Update an existing client by email. Changes propagate to every attached - inbound. Body is the JSON client payload — supply the full set of fields - you want to keep (the server replaces the row, it does not patch). - url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch' + title: 'Update an existing client by email. Changes propagate to every attached + inbound. Body is the JSON client payload: omitted fields keep their + current values, and an explicit zero, empty or null value clears a + field, except as noted below.' + url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below' - depth: 2 - title: Update an existing client by email. Changes propagate to every attached - inbound. Body is the JSON client payload — supply the full set of fields - you want to keep (the server replaces the row, it does not patch). - url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch-1' + title: 'Update an existing client by email. Changes propagate to every attached + inbound. Body is the JSON client payload: omitted fields keep their + current values, and an explicit zero, empty or null value clears a + field, except as noted below.' + url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1' - depth: 2 title: Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed. @@ -351,16 +353,16 @@ _openapi: id: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields - content: Preview client auto-renewal dates without saving or resetting anything. id: preview-client-auto-renewal-dates-without-saving-or-resetting-anything - - content: Update an existing client by email. Changes propagate to every attached - inbound. Body is the JSON client payload — supply the full set of - fields you want to keep (the server replaces the row, it does not - patch). - id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch - - content: Update an existing client by email. Changes propagate to every attached - inbound. Body is the JSON client payload — supply the full set of - fields you want to keep (the server replaces the row, it does not - patch). - id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch-1 + - content: 'Update an existing client by email. Changes propagate to every + attached inbound. Body is the JSON client payload: omitted fields keep + their current values, and an explicit zero, empty or null value clears + a field, except as noted below.' + id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below + - content: 'Update an existing client by email. Changes propagate to every + attached inbound. Body is the JSON client payload: omitted fields keep + their current values, and an explicit zero, empty or null value clears + a field, except as noted below.' + id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1 - content: Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed. id: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed @@ -671,17 +673,10 @@ _openapi: preview is informational and does not reserve an allowance or guarantee node availability. heading: preview-client-auto-renewal-dates-without-saving-or-resetting-anything - - content: 'The inbounds are applied concurrently and independently: one that - fails no longer stops the others. Every inbound error names the - inbound it came from (`inbound 7: `), and several failures - are reported together, one per line. So a `success:false` response can - still have applied the edit to the remaining inbounds. The client - record is written after the inbounds, so a failure there is reported - without an `inbound :` prefix and leaves the inbound edits in - place.' - heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch - - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. - to manage legacy reserved names without URL dot-segment normalization. + - content: 'An omitted `flow` leaves every attached inbound on its own flow. Send + `"reverse": null` to remove the reverse tag. Credentials (`id`, + `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG + `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures @@ -690,7 +685,22 @@ _openapi: record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.' - heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch-1 + heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below + - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + to manage legacy reserved names without URL dot-segment normalization. + An omitted `flow` leaves every attached inbound on its own flow. Send + `"reverse": null` to remove the reverse tag. Credentials (`id`, + `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG + `allowedIPs` are never cleared: an empty value keeps the stored one. + The inbounds are applied concurrently and independently: one that + fails no longer stops the others. Every inbound error names the + inbound it came from (`inbound 7: `), and several failures + are reported together, one per line. So a `success:false` response can + still have applied the edit to the remaining inbounds. The client + record is written after the inbounds, so a failure there is reported + without an `inbound :` prefix and leaves the inbound edits in + place.' + heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1 - content: 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures diff --git a/docs/content/docs/fa/reference/api/clients.mdx b/docs/content/docs/fa/reference/api/clients.mdx index 8c3e73c83..ef08359ca 100644 --- a/docs/content/docs/fa/reference/api/clients.mdx +++ b/docs/content/docs/fa/reference/api/clients.mdx @@ -44,10 +44,11 @@ _openapi: - depth: 2 title: >- Update an existing client by email. Changes propagate to every attached - inbound. Body is the JSON client payload — supply the full set of fields - you want to keep (the server replaces the row, it does not patch). + inbound. Body is the JSON client payload: omitted fields keep their + current values, and an explicit zero, empty or null value clears a + field, except as noted below. url: >- - #update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch + #update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - depth: 2 title: >- Delete a client by email. Removes it from every attached inbound and @@ -358,11 +359,11 @@ _openapi: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields - content: >- Update an existing client by email. Changes propagate to every - attached inbound. Body is the JSON client payload — supply the full - set of fields you want to keep (the server replaces the row, it does - not patch). + attached inbound. Body is the JSON client payload: omitted fields keep + their current values, and an explicit zero, empty or null value clears + a field, except as noted below. id: >- - update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch + update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - content: >- Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed. diff --git a/docs/content/docs/ru/reference/api/clients.mdx b/docs/content/docs/ru/reference/api/clients.mdx index b8cd10682..7d8dd6ff9 100644 --- a/docs/content/docs/ru/reference/api/clients.mdx +++ b/docs/content/docs/ru/reference/api/clients.mdx @@ -44,10 +44,11 @@ _openapi: - depth: 2 title: >- Update an existing client by email. Changes propagate to every attached - inbound. Body is the JSON client payload — supply the full set of fields - you want to keep (the server replaces the row, it does not patch). + inbound. Body is the JSON client payload: omitted fields keep their + current values, and an explicit zero, empty or null value clears a + field, except as noted below. url: >- - #update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch + #update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - depth: 2 title: >- Delete a client by email. Removes it from every attached inbound and @@ -358,11 +359,11 @@ _openapi: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields - content: >- Update an existing client by email. Changes propagate to every - attached inbound. Body is the JSON client payload — supply the full - set of fields you want to keep (the server replaces the row, it does - not patch). + attached inbound. Body is the JSON client payload: omitted fields keep + their current values, and an explicit zero, empty or null value clears + a field, except as noted below. id: >- - update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch + update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - content: >- Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed. diff --git a/docs/content/docs/zh/reference/api/clients.mdx b/docs/content/docs/zh/reference/api/clients.mdx index 52da456f9..bfbb1b6ad 100644 --- a/docs/content/docs/zh/reference/api/clients.mdx +++ b/docs/content/docs/zh/reference/api/clients.mdx @@ -35,10 +35,10 @@ _openapi: #create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields - depth: 2 title: >- - 按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷—— - 请提供你希望保留的完整字段集(服务端会替换整条记录,而非局部更新)。 + 按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷: + 省略的字段保留当前值,显式的零值、空值或 null 会清除该字段(例外见下文)。 url: >- - #update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch + #update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - depth: 2 title: >- 按 email 删除客户端。将其从每个挂载的入站中移除,并删除其流量记录,除非传入 @@ -292,10 +292,10 @@ _openapi: id: >- create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields - content: >- - 按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷—— - 请提供你希望保留的完整字段集(服务端会替换整条记录,而非局部更新)。 + 按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷: + 省略的字段保留当前值,显式的零值、空值或 null 会清除该字段(例外见下文)。 id: >- - update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch + update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - content: >- 按 email 删除客户端。将其从每个挂载的入站中移除,并删除其流量记录,除非传入 keepTraffic=1。 diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 557c7a764..20cd85b2c 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -9053,9 +9053,9 @@ "tags": [ "Clients" ], - "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).", + "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update_email", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", "parameters": [ { "name": "email", @@ -9117,9 +9117,9 @@ "tags": [ "Clients" ], - "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).", + "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", "parameters": [ { "name": "email", diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 557c7a764..20cd85b2c 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -9053,9 +9053,9 @@ "tags": [ "Clients" ], - "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).", + "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update_email", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", "parameters": [ { "name": "email", @@ -9117,9 +9117,9 @@ "tags": [ "Clients" ], - "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).", + "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", "parameters": [ { "name": "email", diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index c968b440e..8ecb6fa30 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1276,9 +1276,9 @@ export const sections: readonly Section[] = [ method: 'POST', path: '/panel/api/clients/update/:email', summary: - 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).', + 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.', description: - 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + 'An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', params: [ { name: 'email', @@ -1294,9 +1294,9 @@ export const sections: readonly Section[] = [ method: 'POST', path: '/panel/api/clients/update', summary: - 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload — supply the full set of fields you want to keep (the server replaces the row, it does not patch).', + 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.', description: - 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', params: [ { name: 'email', diff --git a/frontend/src/pages/clients/ClientFormModal.tsx b/frontend/src/pages/clients/ClientFormModal.tsx index e079ca354..e6e24e3e2 100644 --- a/frontend/src/pages/clients/ClientFormModal.tsx +++ b/frontend/src/pages/clients/ClientFormModal.tsx @@ -798,10 +798,10 @@ export default function ClientFormModal({ comment: values.comment, enable: !!values.enable, }; + // Sent even when empty, so clearing the tag never rests on how the server + // reads an omitted key. const reverseTagValue = showReverseTag ? (values.reverseTag || '').trim() : ''; - if (reverseTagValue) { - clientPayload.reverse = { tag: reverseTagValue }; - } + clientPayload.reverse = reverseTagValue ? { tag: reverseTagValue } : null; if (showWireguard || showAmneziawg) { // AmneziaWG peers are wire-identical to WireGuard peers (same diff --git a/frontend/src/test/client-form-reverse.test.tsx b/frontend/src/test/client-form-reverse.test.tsx new file mode 100644 index 000000000..f22b1ee82 --- /dev/null +++ b/frontend/src/test/client-form-reverse.test.tsx @@ -0,0 +1,64 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, fireEvent, waitFor, screen } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; + +import { ThemeProvider } from '@/hooks/useTheme'; +import ClientFormModal from '@/pages/clients/ClientFormModal'; +import type { ClientRecord, InboundOption } from '@/hooks/useClients'; + +const VLESS_INBOUND = { + id: 7, + port: 10443, + protocol: 'vless', + tag: 'in-10443-tcp', + enable: true, +} as unknown as InboundOption; + +const CLIENT = { + email: 'reverse-user', + uuid: '11111111-1111-1111-1111-111111111111', + subId: 'subid-reverse', + enable: true, + reverse: { tag: 'back' }, +} as unknown as ClientRecord; + +async function saveEdited(edit?: (input: HTMLInputElement) => void) { + const save = vi.fn().mockResolvedValue({ success: true }); + render( + + + {}} + /> + + , + ); + const input = (await screen.findByPlaceholderText('Optional reverse tag')) as HTMLInputElement; + await waitFor(() => expect(input.value).toBe('back')); + edit?.(input); + fireEvent.click(await screen.findByRole('button', { name: /save/i })); + await waitFor(() => expect(save).toHaveBeenCalled()); + return save.mock.calls[0][0] as Record; +} + +// A cleared tag goes out as an explicit null rather than a missing key, which a +// partial update would read as "keep the stored tag". +describe('ClientFormModal — reverse tag', () => { + it('sends an explicit null when the operator clears the tag', async () => { + const payload = await saveEdited((input) => fireEvent.change(input, { target: { value: '' } })); + expect(payload).toHaveProperty('reverse', null); + }); + + it('round-trips an unchanged tag', async () => { + const payload = await saveEdited(); + expect(payload.reverse).toEqual({ tag: 'back' }); + }); +}); diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 97c924410..41c990971 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -267,16 +267,13 @@ func (a *ClientController) update(c *gin.Context) { if !ok { return } - var req struct { - model.Client - LimitHwid int `json:"limitHwid"` - } - if err := c.ShouldBindJSON(&req); err != nil { + body, err := c.GetRawData() + if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } inboundFilter := parseInboundIdsQuery(c.Query("inboundIds")) - needRestart, err := a.clientService.UpdateByEmail(&a.inboundService, email, req.Client, req.LimitHwid, inboundFilter...) + needRestart, err := a.clientService.UpdateByEmailJSON(&a.inboundService, email, body, inboundFilter...) // Flagged before the error check: a partly-applied edit leaves the change // committed on the inbounds that succeeded, and those still need the restart. if needRestart { diff --git a/internal/web/controller/client_partial_update_test.go b/internal/web/controller/client_partial_update_test.go new file mode 100644 index 000000000..017236118 --- /dev/null +++ b/internal/web/controller/client_partial_update_test.go @@ -0,0 +1,74 @@ +package controller + +import ( + "path/filepath" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +// A handler that binds the body straight into model.Client turns every omitted +// field into its zero: this expiry-only body would disable the client. +func TestUpdateHandlerKeepsFieldsTheBodyOmits(t *testing.T) { + const email = "partial-body@example.com" + dbDir := t.TempDir() + t.Setenv("XUI_DB_FOLDER", dbDir) + dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db")) + db := database.GetDB() + ib := &model.Inbound{ + UserId: 1, Enable: true, Port: 43350, Tag: "in-partial-body", + Protocol: model.VLESS, Settings: `{"clients": []}`, + StreamSettings: `{"network":"tcp","security":"none"}`, + } + if err := db.Create(ib).Error; err != nil { + t.Fatalf("create inbound: %v", err) + } + if _, err := (&service.ClientService{}).Create(&service.InboundService{}, &service.ClientCreatePayload{ + Client: model.Client{ + Email: email, ID: "11111111-2222-3333-4444-555555555555", Enable: true, + LimitIP: 2, TotalGB: 10 << 30, TgID: 42, Comment: "phone", + }, + InboundIds: []int{ib.Id}, + }); err != nil { + t.Fatalf("seed client: %v", err) + } + + a := &ClientController{} + c, w := postCtx(t, email, map[string]any{"email": email, "expiryTime": 1893456000000}) + a.update(c) + + var rec model.ClientRecord + if err := db.Where("email = ?", email).First(&rec).Error; err != nil { + t.Fatalf("reload client: %v (response %s)", err, w.Body.String()) + } + if rec.ExpiryTime != 1893456000000 { + t.Fatalf("expiry not applied: %d (response %s)", rec.ExpiryTime, w.Body.String()) + } + if !rec.Enable || rec.LimitIP != 2 || rec.TotalGB != 10<<30 || rec.TgID != 42 || rec.Comment != "phone" { + t.Fatalf("handler reset fields the body omitted: %+v", rec) + } +} + +func TestClientQueryAliasPartialUpdateKeepsOmittedFields(t *testing.T) { + for _, email := range []string{".", ".."} { + t.Run(email, func(t *testing.T) { + router, rec, _ := seedLegacyDotClient(t, email) + db := database.GetDB() + if err := db.Model(&model.ClientRecord{}).Where("id = ?", rec.Id).Updates(map[string]any{"limit_ip": 2, "total_gb": int64(10 << 30), "comment": "retained"}).Error; err != nil { + t.Fatal(err) + } + w := dotClientRequest(t, router, "POST", "update?email="+email, map[string]any{"email": "recovered-partial", "expiryTime": int64(1893456000000)}) + assertDotClientSuccess(t, w) + var after model.ClientRecord + if err := db.First(&after, rec.Id).Error; err != nil { + t.Fatal(err) + } + if after.Email != "recovered-partial" || after.ExpiryTime != 1893456000000 || !after.Enable || after.UUID != rec.UUID || after.SubID != rec.SubID || after.LimitIP != 2 || after.TotalGB != 10<<30 || after.Comment != "retained" { + t.Fatalf("query alias partial update lost client state: %+v", after) + } + }) + } +} diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 7f1687fba..30a8cc640 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -675,6 +675,12 @@ func applyShadowsocksClientMethod(clients []any, settings map[string]any) { } func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, limitHwid int, inboundFilter ...int) (bool, error) { + return s.update(inboundSvc, id, updated, limitHwid, false, inboundFilter) +} + +// keepInboundFlows: the caller sent no flow, so every inbound keeps its own and an +// unlinked record keeps its stored one. +func (s *ClientService) update(inboundSvc *InboundService, id int, updated model.Client, limitHwid int, keepInboundFlows bool, inboundFilter []int) (bool, error) { existing, err := s.GetByID(id) if err != nil { return false, err @@ -800,6 +806,14 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model } } + var inboundFlows map[int]string + if keepInboundFlows { + updated.Flow = existing.Flow + if inboundFlows, err = inboundFlowOverrides(id); err != nil { + return false, err + } + } + tunnelCount, tcErr := tunnelInboundCount(inboundIds) if tcErr != nil { return false, tcErr @@ -828,6 +842,9 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model return false, err } clientForInbound := updated + if keepInboundFlows { + clientForInbound.Flow = inboundFlows[ibId] + } if ips, ok := updated.AllowedIPsByInbound[ibId]; ok { clientForInbound.AllowedIPs = ips } else if tunnelCount > 1 && (inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG) { diff --git a/internal/web/service/client_partial_update.go b/internal/web/service/client_partial_update.go new file mode 100644 index 000000000..6ddbdd7d9 --- /dev/null +++ b/internal/web/service/client_partial_update.go @@ -0,0 +1,130 @@ +package service + +import ( + "encoding/json" + "strings" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/util/common" +) + +// UpdateByEmailJSON applies a POST /clients/update body: an omitted key keeps the +// stored value and an explicit zero, empty or null value clears it. +func (s *ClientService) UpdateByEmailJSON(inboundSvc *InboundService, email string, body []byte, inboundFilter ...int) (bool, error) { + var req clientPayloadWithHwid + if err := json.Unmarshal(body, &req); err != nil { + return false, err + } + if email == "" { + return false, common.NewError("client email is required") + } + rec, err := s.GetRecordByEmail(nil, email) + if err != nil { + return false, err + } + keys := clientPayloadKeys(body) + fillAbsentClientFields(rec, &req.Client, &req.LimitHwid, keys) + return s.update(inboundSvc, rec.Id, req.Client, req.LimitHwid, !keys.has("flow"), inboundFilter) +} + +// payloadKeys is a struct so tools/openapigen, which exports every named +// non-struct type of this package, leaves it out of the generated frontend types. +type payloadKeys struct{ names []string } + +func clientPayloadKeys(body []byte) payloadKeys { + var raw map[string]json.RawMessage + if err := json.Unmarshal(body, &raw); err != nil { + return payloadKeys{} + } + keys := payloadKeys{names: make([]string, 0, len(raw))} + for k := range raw { + keys.names = append(keys.names, k) + } + return keys +} + +// has matches keys the way encoding/json binds them to fields: case-insensitively, +// so a body sending "limitIP" counts as carrying limitIp. +func (k payloadKeys) has(name string) bool { + for _, key := range k.names { + if strings.EqualFold(key, name) { + return true + } + } + return false +} + +// fillAbsentClientFields leaves flow to update, which keeps it per inbound. +func fillAbsentClientFields(rec *model.ClientRecord, updated *model.Client, limitHwid *int, keys payloadKeys) { + stored := rec.ToClient() + if !keys.has("email") { + updated.Email = stored.Email + } + if !keys.has("security") { + updated.Security = stored.Security + } + if !keys.has("limitIp") { + updated.LimitIP = stored.LimitIP + } + if !keys.has("totalGB") { + updated.TotalGB = stored.TotalGB + } + if !keys.has("expiryTime") { + updated.ExpiryTime = stored.ExpiryTime + } + if !keys.has("enable") { + updated.Enable = stored.Enable + } + if !keys.has("tgId") { + updated.TgID = stored.TgID + } + if !keys.has("group") { + updated.Group = stored.Group + } + if !keys.has("comment") { + updated.Comment = stored.Comment + } + if !keys.has("reset") { + updated.Reset = stored.Reset + } + if !keys.has("resetDay") { + updated.ResetDay = stored.ResetDay + } + if !keys.has("resetWeekday") { + updated.ResetWeekday = stored.ResetWeekday + } + if !keys.has("resetMax") { + updated.ResetMax = stored.ResetMax + } + if !keys.has("trafficReset") { + updated.TrafficReset = stored.TrafficReset + } + if !keys.has("trafficResetDay") { + updated.TrafficResetDay = stored.TrafficResetDay + } + if !keys.has("adTag") { + updated.AdTag = stored.AdTag + } + if !keys.has("reverse") { + updated.Reverse = stored.Reverse + } + if !keys.has("limitHwid") { + *limitHwid = rec.LimitHwid + } +} + +// inboundFlowOverrides returns each linked inbound's flow_override: the reliable +// per-inbound flow, unlike clients.flow (see EffectiveFlow). +func inboundFlowOverrides(recordId int) (map[int]string, error) { + var links []model.ClientInbound + if err := database.GetDB().Select("inbound_id", "flow_override"). + Where("client_id = ?", recordId).Find(&links).Error; err != nil { + return nil, err + } + flows := make(map[int]string, len(links)) + for _, link := range links { + flows[link.InboundId] = link.FlowOverride + } + return flows, nil +} diff --git a/internal/web/service/client_partial_update_test.go b/internal/web/service/client_partial_update_test.go new file mode 100644 index 000000000..0f50489e3 --- /dev/null +++ b/internal/web/service/client_partial_update_test.go @@ -0,0 +1,160 @@ +package service + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +const partialTestPSK = "Pm4Hn0f8i8b6v3gJ0vZQ3yHq4mUe7qkq0m3o2l9sY9c=" + +func updateByEmailJSON(t *testing.T, svc *ClientService, email, body string) { + t.Helper() + if _, err := svc.UpdateByEmailJSON(&InboundService{}, email, []byte(body)); err != nil { + t.Fatalf("UpdateByEmailJSON(%s): %v", body, err) + } +} + +func inboundClientByEmail(t *testing.T, inboundId int, email string) model.Client { + t.Helper() + inboundSvc := &InboundService{} + ib, err := inboundSvc.GetInbound(inboundId) + if err != nil { + t.Fatalf("GetInbound(%d): %v", inboundId, err) + } + clients, err := inboundSvc.GetClients(ib) + if err != nil { + t.Fatalf("GetClients(%d): %v", inboundId, err) + } + for _, c := range clients { + if c.Email == email { + return c + } + } + t.Fatalf("inbound %d has no client %q", inboundId, email) + return model.Client{} +} + +// A body carrying only email and expiryTime used to disable the client and zero its +// limits, Telegram id, comment, group, renewal settings and limitHwid. +func TestUpdateByEmailJSONKeepsOmittedFields(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + ib := mkInbound(t, 52111, model.AmneziaWG, `{"server":{"privateKey":"server","publicKey":"server-pub","subnetIp":"10.8.1.0","subnetCidr":24},"clients":[]}`) + + seed := model.Client{ + Email: "full@awg", Enable: true, + PrivateKey: "client-private", PublicKey: "client-public", + PreSharedKey: partialTestPSK, + AllowedIPs: []string{"10.8.1.8/32"}, + LimitIP: 3, TotalGB: 50 << 30, ExpiryTime: 1700000000000, + TgID: 123456, Comment: "laptop", Group: "family", + Reset: 30, ResetMax: 4, + } + seed.AllowedIPsByInbound = map[int][]string{ib.Id: seed.AllowedIPs} + if _, err := svc.CreateOne(&InboundService{}, ib.Id, seed); err != nil { + t.Fatalf("seed client: %v", err) + } + if err := database.GetDB().Model(&model.ClientRecord{}).Where("email = ?", seed.Email). + UpdateColumn("limit_hwid", 2).Error; err != nil { + t.Fatal(err) + } + + updateByEmailJSON(t, svc, seed.Email, `{"email": "full@awg", "expiryTime": 1893456000000}`) + + rec := lookupClientRecord(t, seed.Email) + if !rec.Enable { + t.Fatal("partial update disabled the client") + } + if rec.ExpiryTime != 1893456000000 { + t.Fatalf("expiry not applied: %d", rec.ExpiryTime) + } + if rec.LimitIP != 3 || rec.TotalGB != 50<<30 || rec.TgID != 123456 || rec.Comment != "laptop" || + rec.Group != "family" || rec.Reset != 30 || rec.ResetMax != 4 || rec.LimitHwid != 2 { + t.Fatalf("partial update reset omitted fields: %+v", rec) + } + peer := inboundClientByEmail(t, ib.Id, seed.Email) + if !peer.Enable || peer.PreSharedKey != partialTestPSK || peer.PrivateKey != seed.PrivateKey { + t.Fatalf("inbound peer lost its state: %+v", peer) + } + + updateByEmailJSON(t, svc, seed.Email, `{"enable": false, "comment": "", "totalGB": 0}`) + rec = lookupClientRecord(t, seed.Email) + if rec.Enable || rec.Comment != "" || rec.TotalGB != 0 { + t.Fatalf("explicit zeros were not applied: %+v", rec) + } + if rec.ExpiryTime != 1893456000000 || rec.LimitIP != 3 || rec.Group != "family" || rec.LimitHwid != 2 { + t.Fatalf("second partial update reset omitted fields: %+v", rec) + } +} + +// encoding/json binds "limitIP" to limitIp; a case-sensitive presence check then +// overwrote the decoded zero with the stored value. +func TestUpdateByEmailJSONMatchesKeysCaseInsensitively(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + ib := mkInbound(t, 52112, model.VLESS, `{"clients":[]}`) + seed := model.Client{ + Email: "case@vless", ID: "0d1b6f8e-3c2a-4f61-9a43-5b7f0c2e9d11", Enable: true, + LimitIP: 3, TgID: 123456, ExpiryTime: 1700000000000, + } + if _, err := svc.CreateOne(&InboundService{}, ib.Id, seed); err != nil { + t.Fatalf("seed client: %v", err) + } + + updateByEmailJSON(t, svc, seed.Email, `{"limitIP": 0, "tgID": 0, "expirytime": 1893456000000}`) + + rec := lookupClientRecord(t, seed.Email) + if rec.LimitIP != 0 || rec.TgID != 0 || rec.ExpiryTime != 1893456000000 { + t.Fatalf("differently-cased keys were not applied: limitIp=%d tgId=%d expiry=%d", rec.LimitIP, rec.TgID, rec.ExpiryTime) + } + if !rec.Enable { + t.Fatal("partial update disabled the client") + } +} + +// clients.flow is unreliable for a multi-inbound client (#4792): an omitted flow +// must keep each inbound's own flow instead of copying that column everywhere. +func TestUpdateByEmailJSONOmittedFlowKeepsEachInboundsFlow(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + const vision = "xtls-rprx-vision" + reality := mkInboundStream(t, 52113, model.VLESS, `{"clients":[]}`, realityStream) + ws := mkInboundStream(t, 52114, model.VLESS, `{"clients":[]}`, wsStream) + seed := model.Client{ + Email: "flow@vless", ID: "6a0f2c1e-8b4d-4e7a-9c35-1d2e3f4a5b6c", Enable: true, Flow: vision, + Reverse: &model.ClientReverse{Tag: "back"}, + } + if _, err := svc.Create(&InboundService{}, &ClientCreatePayload{Client: seed, InboundIds: []int{reality.Id, ws.Id}}); err != nil { + t.Fatalf("seed client: %v", err) + } + if rec := lookupClientRecord(t, seed.Email); rec.Reverse == "" { + t.Fatal("seed did not store the reverse tag") + } + if err := database.GetDB().Model(&model.ClientRecord{}).Where("email = ?", seed.Email). + UpdateColumn("flow", "").Error; err != nil { + t.Fatalf("zero clients.flow: %v", err) + } + + updateByEmailJSON(t, svc, seed.Email, `{"expiryTime": 1893456000000}`) + + if got := inboundClientByEmail(t, reality.Id, seed.Email); got.Flow != vision || got.ExpiryTime != 1893456000000 { + t.Fatalf("Reality inbound: flow=%q expiry=%d, want %q and the new expiry", got.Flow, got.ExpiryTime, vision) + } + if got := inboundClientByEmail(t, ws.Id, seed.Email); got.Flow != "" { + t.Fatalf("WS inbound gained flow %q", got.Flow) + } + if rec := lookupClientRecord(t, seed.Email); rec.Reverse == "" { + t.Fatal("an omitted reverse must keep the tag") + } + updateByEmailJSON(t, svc, seed.Email, `{"reverse": null}`) + if rec := lookupClientRecord(t, seed.Email); rec.Reverse != "" { + t.Fatalf("an explicit null reverse must clear the tag: %q", rec.Reverse) + } + + updateByEmailJSON(t, svc, seed.Email, `{"flow": ""}`) + if got := inboundClientByEmail(t, reality.Id, seed.Email); got.Flow != "" { + t.Fatalf("an explicit empty flow must clear Vision, got %q", got.Flow) + } +} From dbb6212988f86e32580d31789ec285ac86786096 Mon Sep 17 00:00:00 2001 From: Mahdi Fallahnejhad <60172658+Zaltapar@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:37:52 +0330 Subject: [PATCH 004/130] fix(clients): restore depleted clients on renewal and prioritize operator writes (#6987) Restore usable clients when renewed, avoid duplicate reset updates, and prioritize operator writes in the serialized traffic writer. Preserve manual disables and keep every inbound consistent after traffic resets. --- internal/web/service/client_crud.go | 15 + internal/web/service/client_inbound_apply.go | 29 +- .../web/service/client_renewal_reenable.go | 60 ++++ internal/web/service/client_traffic.go | 25 +- .../client_traffic_reset_order_test.go | 2 +- .../service/client_update_reenable_test.go | 284 ++++++++++++++++++ internal/web/service/inbound_disable.go | 42 +++ internal/web/service/inbound_node.go | 4 +- internal/web/service/inbound_traffic.go | 111 ++++--- .../web/service/inbound_traffic_global.go | 2 +- internal/web/service/traffic_writer.go | 93 ++++-- internal/web/service/traffic_writer_test.go | 106 ++++++- internal/web/service/tuic_traffic_receipt.go | 3 +- 13 files changed, 684 insertions(+), 92 deletions(-) create mode 100644 internal/web/service/client_renewal_reenable.go create mode 100644 internal/web/service/client_update_reenable_test.go diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 30a8cc640..1f2d1a761 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -782,6 +782,12 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model updated.Secret = existing.Secret } + // A client the quota loop switched off comes back on when this update + // restores a usable window, as BulkAdjust already does on a renewal (#5619). + if !updated.Enable && s.renewalReenables(existing.Email, updated.TotalGB, updated.ExpiryTime) { + updated.Enable = true + } + if updated.Email != existing.Email { var collisionCount int64 if err := database.GetDB().Model(&model.ClientRecord{}). @@ -936,6 +942,15 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model }).Error; err != nil { return needRestart, err } + // No inbound left, so UpdateClientStat never runs; re-assert the + // enforcement row's off switch here or a re-enabled client stays off. + if merged.Enable { + if err := database.GetDB().Model(xray.ClientTraffic{}). + Where("email = ?", existing.Email). + UpdateColumn("enable", true).Error; err != nil { + return needRestart, err + } + } } reverseStr := "" diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index c9df9de98..f0c9c1882 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -1537,9 +1537,31 @@ func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, cl }) } +// renewalReenableFor projects the post-renewal limits for a single-field +// renewal (nil side keeps the stored limit; no row means no quota state). +func (s *ClientService) renewalReenableFor(email string, setExpiry *int64, setTotal *int64) bool { + total, expiry, ok := storedTrafficLimits(email) + if !ok { + return false + } + if setExpiry != nil { + expiry = *setExpiry + } + if setTotal != nil { + total = *setTotal + } + return s.renewalReenables(email, total, expiry) +} + func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) { + reenable := s.renewalReenableFor(clientEmail, &expiry_time, nil) return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) { c["expiryTime"] = expiry_time + if reenable { + // A renewed client that the quota loop had switched off comes back + // with the renewal instead of waiting for a manual enable (#5619). + c["enable"] = true + } }) } @@ -1547,7 +1569,12 @@ func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundServic if totalGB < 0 { return false, common.NewError("totalGB must be >= 0") } + newTotal := int64(totalGB) * 1024 * 1024 * 1024 + reenable := s.renewalReenableFor(clientEmail, nil, &newTotal) return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) { - c["totalGB"] = totalGB * 1024 * 1024 * 1024 + c["totalGB"] = newTotal + if reenable { + c["enable"] = true + } }) } diff --git a/internal/web/service/client_renewal_reenable.go b/internal/web/service/client_renewal_reenable.go new file mode 100644 index 000000000..edd9a9deb --- /dev/null +++ b/internal/web/service/client_renewal_reenable.go @@ -0,0 +1,60 @@ +package service + +import ( + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +// renewalReenables reports whether the quota loop switched the client off and +// this renewal (newTotal/newExpiry, usage unchanged) clears the depletion (#5619). +func (s *ClientService) renewalReenables(email string, newTotal, newExpiry int64) bool { + db := database.GetDB() + var traffic xray.ClientTraffic + if err := db.Where("email = ?", email).First(&traffic).Error; err != nil { + return false // no enforcement row: the quota loop never switched this client off + } + if traffic.Enable { + return false + } + + cond, condArgs := depletedCond(db) + var wasDepleted int64 + if err := db.Model(xray.ClientTraffic{}). + Where(cond+" AND email = ?", append(append([]any{}, condArgs...), email)...). + Count(&wasDepleted).Error; err != nil || wasDepleted == 0 { + return false // off for another reason than depletion: the operator's off stands + } + + // Project the post-renewal row: total/expiry move, up/down and a fresh + // cross-panel push can still deplete it. + now := time.Now().UnixMilli() + used := traffic.Up + traffic.Down + if newTotal > 0 && used >= newTotal { + return false // still over quota + } + if newExpiry > 0 && newExpiry <= now { + return false // still expired + } + if newTotal > 0 { + var globalDepleted int64 + if err := db.Model(&model.ClientGlobalTraffic{}). + Where("email = ? AND updated_at >= ? AND up + down >= ?", email, globalTrafficFreshSince(time.Now()), newTotal). + Count(&globalDepleted).Error; err == nil && globalDepleted > 0 { + return false // a master's pushed usage still depletes the fresh quota + } + } + return true +} + +// storedTrafficLimits reads a client's enforcement row; ok is false when the +// client has no row, in which case no quota state can be projected for it. +func storedTrafficLimits(email string) (total, expiry int64, ok bool) { + var row xray.ClientTraffic + if err := database.GetDB().Where("email = ?", email).First(&row).Error; err != nil { + return 0, 0, false + } + return row.Total, row.ExpiryTime, true +} diff --git a/internal/web/service/client_traffic.go b/internal/web/service/client_traffic.go index 73d663d2e..025c83c39 100644 --- a/internal/web/service/client_traffic.go +++ b/internal/web/service/client_traffic.go @@ -50,17 +50,22 @@ func (s *ClientService) ResetTrafficByEmail(inboundSvc *InboundService, email st needRestart = nr } - // Enable only a client the quota switched off, once the counters are zero: a - // hand-disabled one stays off, and a still-depleted one would be switched off again. + // Restore quota-disabled clients after zeroing; preserve an operator + // disable, including when no inbound remains. if !rec.Enable && len(quotaDisabled) > 0 { - updated := rec.ToClient() - updated.Enable = true - nr, uErr := s.Update(inboundSvc, rec.Id, *updated, rec.LimitHwid) - if uErr != nil { - logger.Warning("Failed to auto-enable client during traffic reset:", uErr) - } - if nr { - needRestart = true + // Inbound resets already restored hosted clients. Only an unhosted + // record still needs the full update. + fresh, fErr := s.GetRecordByEmail(nil, email) + if fErr == nil && !fresh.Enable { + updated := fresh.ToClient() + updated.Enable = true + nr, uErr := s.Update(inboundSvc, fresh.Id, *updated, fresh.LimitHwid) + if uErr != nil { + logger.Warning("Failed to auto-enable client during traffic reset:", uErr) + } + if nr { + needRestart = true + } } } return needRestart, nil diff --git a/internal/web/service/client_traffic_reset_order_test.go b/internal/web/service/client_traffic_reset_order_test.go index 152c0738e..f69ba75ea 100644 --- a/internal/web/service/client_traffic_reset_order_test.go +++ b/internal/web/service/client_traffic_reset_order_test.go @@ -67,7 +67,7 @@ func requireResetSurvivesTick(t *testing.T, reset func() error) { tickDone <- err }() deadline := time.Now().Add(5 * time.Second) - for len(twQueue) < 2 && time.Now().Before(deadline) { + for trafficWriterQueueLen() < 2 && time.Now().Before(deadline) { time.Sleep(time.Millisecond) } close(release) diff --git a/internal/web/service/client_update_reenable_test.go b/internal/web/service/client_update_reenable_test.go new file mode 100644 index 000000000..28dfa5c24 --- /dev/null +++ b/internal/web/service/client_update_reenable_test.go @@ -0,0 +1,284 @@ +package service + +import ( + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +// renewalReenableDay keeps the seeds one day past (or before) their boundary. +const renewalReenableDay = int64(24 * 60 * 60 * 1000) + +// seedRenewableDepletedClient seeds a local inbound whose client the quota loop +// switched off: record off, inbound JSON off, and the traffic row off and depleted. +func seedRenewableDepletedClient(t *testing.T, svc *ClientService, port int, email string, total, expiry, up, down int64) *model.Inbound { + t.Helper() + ib := seedLocalDisabledClient(t, svc, port, "", email, total, expiry, up, down) + if got := trafficOf(t, email); got.Enable { + t.Fatalf("seed %s: want an off traffic row, got %+v", email, got) + } + return ib +} + +func TestUpdate_ReenablesDepletedClient_WhenExpiryExtended(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + now := time.Now().UnixMilli() + email := "renew-exp@x" + ib := seedRenewableDepletedClient(t, svc, 53101, email, 0, now-2*renewalReenableDay, 0, 0) + + rec, err := svc.GetRecordByEmail(nil, email) + if err != nil { + t.Fatalf("GetRecordByEmail: %v", err) + } + updated := rec.ToClient() + updated.ExpiryTime = now + 30*renewalReenableDay + // The editor round-trips the switch as the stored off state; the renewal + // must turn it back on by itself. + if _, err := svc.Update(inboundSvc, rec.Id, *updated, 0); err != nil { + t.Fatalf("Update: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, true) + if got := trafficOf(t, email).ExpiryTime; got != now+30*renewalReenableDay { + t.Fatalf("%s: expiry = %d, want %d", email, got, now+30*renewalReenableDay) + } +} + +func TestUpdate_ReenablesDepletedClient_WhenTotalRaised(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + email := "renew-total@x" + ib := seedRenewableDepletedClient(t, svc, 53102, email, 100, 0, 60, 40) + + rec, err := svc.GetRecordByEmail(nil, email) + if err != nil { + t.Fatalf("GetRecordByEmail: %v", err) + } + updated := rec.ToClient() + updated.TotalGB = 300 + if _, err := svc.Update(inboundSvc, rec.Id, *updated, 0); err != nil { + t.Fatalf("Update: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, true) + if got := trafficOf(t, email).Total; got != 300 { + t.Fatalf("%s: total = %d, want 300", email, got) + } +} + +func TestUpdate_KeepsDisabled_StillExpiredAfterUpdate(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + now := time.Now().UnixMilli() + email := "renew-sml@x" + ib := seedRenewableDepletedClient(t, svc, 53103, email, 0, now-10*renewalReenableDay, 0, 0) + + rec, err := svc.GetRecordByEmail(nil, email) + if err != nil { + t.Fatalf("GetRecordByEmail: %v", err) + } + updated := rec.ToClient() + updated.ExpiryTime = now - 5*renewalReenableDay // an extension that still lands in the past + if _, err := svc.Update(inboundSvc, rec.Id, *updated, 0); err != nil { + t.Fatalf("Update: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, false) +} + +func TestUpdate_KeepsDisabled_StillOverQuotaAfterUpdate(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + email := "renew-quota@x" + ib := seedRenewableDepletedClient(t, svc, 53104, email, 100, 0, 60, 40) + + rec, err := svc.GetRecordByEmail(nil, email) + if err != nil { + t.Fatalf("GetRecordByEmail: %v", err) + } + updated := rec.ToClient() + updated.TotalGB = 80 // still below the 100 bytes of usage + if _, err := svc.Update(inboundSvc, rec.Id, *updated, 0); err != nil { + t.Fatalf("Update: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, false) +} + +func TestUpdate_KeepsDisabled_ManuallyDisabledNotDepleted(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + now := time.Now().UnixMilli() + email := "renew-manual@x" + ib := seedRenewableDepletedClient(t, svc, 53105, email, 0, now+30*renewalReenableDay, 0, 0) + + rec, err := svc.GetRecordByEmail(nil, email) + if err != nil { + t.Fatalf("GetRecordByEmail: %v", err) + } + updated := rec.ToClient() + updated.ExpiryTime = now + 60*renewalReenableDay + if _, err := svc.Update(inboundSvc, rec.Id, *updated, 0); err != nil { + t.Fatalf("Update: %v", err) + } + // The quota loop never switched this client off — it reads under quota — + // so a manual switch-off survives a renewal. + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, false) +} + +func TestUpdate_ReenablesDepletedClient_SkipsStillDepletedGlobalUsage(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + now := time.Now().UnixMilli() + email := "renew-global@x" + ib := seedRenewableDepletedClient(t, svc, 53106, email, 100, now+30*renewalReenableDay, 0, 0) + // A fresh master push depletes the local limits even though up/down read 0. + global := model.ClientGlobalTraffic{MasterGuid: "master-a", Email: email, Up: 90, Down: 60} + if err := database.GetDB().Create(&global).Error; err != nil { + t.Fatalf("seed global traffic: %v", err) + } + + rec, err := svc.GetRecordByEmail(nil, email) + if err != nil { + t.Fatalf("GetRecordByEmail: %v", err) + } + updated := rec.ToClient() + updated.TotalGB = 100 + if _, err := svc.Update(inboundSvc, rec.Id, *updated, 0); err != nil { + t.Fatalf("Update: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, false) + + // Raising the quota above the pushed usage re-enables it. + updated.TotalGB = 1000 + if _, err := svc.Update(inboundSvc, rec.Id, *updated, 0); err != nil { + t.Fatalf("Update: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, true) +} + +func TestUpdate_ReenablesDepletedClient_WithoutInbound(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + now := time.Now().UnixMilli() + email := "renew-noib@x" + rec := &model.ClientRecord{ + Email: email, + UUID: "44444444-4444-4444-4444-444444444444", + SubID: email, + } + if err := database.GetDB().Create(rec).Error; err != nil { + t.Fatalf("create record: %v", err) + } + forceRecordDisabled(t, svc, email) + if err := database.GetDB().Create(&xray.ClientTraffic{ + Email: email, Enable: false, ExpiryTime: now - 2*renewalReenableDay, + }).Error; err != nil { + t.Fatalf("seed client_traffics: %v", err) + } + + updated := rec.ToClient() + updated.ExpiryTime = now + 30*renewalReenableDay + if _, err := svc.Update(inboundSvc, rec.Id, *updated, 0); err != nil { + t.Fatalf("Update: %v", err) + } + if got := recordEnableOf(t, svc, email); !got { + t.Fatalf("%s: client_records.enable = false, want true", email) + } + if got := trafficOf(t, email).Enable; !got { + t.Fatalf("%s: client_traffics.enable = false, want true (no-inbound re-enable gap)", email) + } +} + +func TestResetClientExpiryTimeByEmail_ReenablesDepletedClient(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + now := time.Now().UnixMilli() + email := "renew-setter@x" + ib := seedRenewableDepletedClient(t, svc, 53107, email, 0, now-2*renewalReenableDay, 0, 0) + + if _, err := svc.ResetClientExpiryTimeByEmail(inboundSvc, email, now+30*renewalReenableDay); err != nil { + t.Fatalf("ResetClientExpiryTimeByEmail: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, true) +} + +func TestResetClientExpiryTimeByEmail_KeepsDisabled_ManuallyDisabledNotDepleted(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + now := time.Now().UnixMilli() + email := "renew-setter-off@x" + ib := seedRenewableDepletedClient(t, svc, 53108, email, 0, now+30*renewalReenableDay, 0, 0) + + if _, err := svc.ResetClientExpiryTimeByEmail(inboundSvc, email, now+60*renewalReenableDay); err != nil { + t.Fatalf("ResetClientExpiryTimeByEmail: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, false) +} + +func TestResetClientTrafficLimitByEmail_ReenablesDepletedClient(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + email := "renew-setter-total@x" + ib := seedRenewableDepletedClient(t, svc, 53109, email, 100, 0, 60, 40) + + if _, err := svc.ResetClientTrafficLimitByEmail(inboundSvc, email, 1); err != nil { + t.Fatalf("ResetClientTrafficLimitByEmail: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ib.Id, email, true) + if got := trafficOf(t, email).Total; got != 1<<30 { + t.Fatalf("%s: total = %d, want %d", email, got, 1<<30) + } +} + +// A client living on several inbounds must come back on every one of them, +// not only the inbound whose reset ran first. +func TestResetTrafficByEmail_ReenablesEveryInboundOfTheClient(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + inboundSvc := &InboundService{} + + email := "renew-multi@x" + c := model.Client{ + Email: email, ID: "11111111-1111-1111-1111-111111111111", SubID: email, + Enable: false, TotalGB: 1000, + } + ibA := mkInbound(t, 53201, model.VLESS, clientsSettings(t, []model.Client{c})) + ibB := mkInbound(t, 53202, model.VLESS, clientsSettings(t, []model.Client{c})) + for _, ib := range []*model.Inbound{ibA, ibB} { + if err := svc.SyncInbound(nil, ib.Id, []model.Client{c}); err != nil { + t.Fatalf("SyncInbound %d: %v", ib.Id, err) + } + } + mkTraffic(t, ibA.Id, email, 600, 500, 1000, 0, false) + forceRecordDisabled(t, svc, email) + + if _, err := svc.ResetTrafficByEmail(inboundSvc, email); err != nil { + t.Fatalf("ResetTrafficByEmail: %v", err) + } + assertEnableEverywhere(t, svc, inboundSvc, ibA.Id, email, true) + assertEnableEverywhere(t, svc, inboundSvc, ibB.Id, email, true) + if got := trafficOf(t, email); !got.Enable || got.Up+got.Down != 0 { + t.Fatalf("%s: traffic row enable=%v used=%d, want enabled at 0", email, got.Enable, got.Up+got.Down) + } +} diff --git a/internal/web/service/inbound_disable.go b/internal/web/service/inbound_disable.go index 597b8853b..32ad298dd 100644 --- a/internal/web/service/inbound_disable.go +++ b/internal/web/service/inbound_disable.go @@ -275,6 +275,48 @@ func (s *InboundService) markClientsDisabledInSettings(tx *gorm.DB, inboundID in return &snapshot, &ib, nil } +// markClientEnabledInSettings is the re-enable twin of +// markClientsDisabledInSettings: flip one email's stored entry back on. +func (s *InboundService) markClientEnabledInSettings(tx *gorm.DB, inboundID int, email string) error { + var ib model.Inbound + if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).First(&ib).Error; err != nil { + return err + } + settings := map[string]any{} + if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil { + return err + } + clients, _ := settings["clients"].([]any) + now := time.Now().Unix() * 1000 + mutated := false + for i := range clients { + entry, ok := clients[i].(map[string]any) + if !ok { + continue + } + if e, _ := entry["email"].(string); e != email { + continue + } + if cur, _ := entry["enable"].(bool); cur { + continue + } + entry["enable"] = true + entry["updated_at"] = now + clients[i] = entry + mutated = true + } + if !mutated { + return nil + } + settings["clients"] = clients + bs, err := json.MarshalIndent(settings, "", " ") + if err != nil { + return err + } + return tx.Model(&model.Inbound{}).Where("id = ?", inboundID). + Update("settings", string(bs)).Error +} + // trafficDisabledEmails reports which emails have a switched-off stats row. The // table is email-keyed and its inbound_id goes stale, so never filter on it. func trafficDisabledEmails(db *gorm.DB, emails []string) (map[string]struct{}, error) { diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index f14ce8987..0cf2ad2f4 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -390,7 +390,9 @@ func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime. // config push just landed, whose snapshot may still predate it (#6228). func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { var structuralChange bool - err := submitTrafficWrite(func() error { + // Node merges take the background lane: a per-client mutation the operator + // is waiting on must not queue behind the next batch of 5s snapshots. + err := submitTrafficWriteBackground(func() error { var inner error structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty, justPushed) return inner diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index 3669ca3d4..7de298b98 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -28,7 +28,9 @@ func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraff var disabledNodeIDs []int var remotePlans []trafficInboundUpdatePlan var renewed []string - err = submitTrafficWrite(func() error { + // The periodic poll takes the background lane: an operator's save or reset + // queued while a poll runs must not sit behind the next merge batch. + err = submitTrafficWriteBackground(func() error { var inner error needRestart, clientsDisabled, disabledNodeIDs, remotePlans, renewed, inner = s.addTrafficLocked(inboundTraffics, clientTraffics) return inner @@ -720,55 +722,61 @@ func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (b needRestart := false var reenablePlan *trafficLocalApplyPlan var reenableNodeID *int + // This inbound's stored entry read off and this reset flips it back on, + // in the same transaction as the zeroing. + flipStoredEntry := false traffic, err := s.GetClientTrafficByEmail(clientEmail) if err != nil { return false, nil, err } - // A reset lifts the quota gate only: a client switched off by hand stays off. keepOff, err := handDisabledEmails(database.GetDB(), []string{clientEmail}) if err != nil { return false, nil, err } handDisabled := len(keepOff) > 0 - - if !traffic.Enable && !handDisabled { - inbound, err := s.GetInbound(id) - if err != nil { - return false, nil, err + inbound, err := s.GetInbound(id) + if err != nil { + return false, nil, err + } + clients, err := s.GetClients(inbound) + if err != nil { + return false, nil, err + } + // Check each stored entry: the first reset already enables the shared + // row. A row-only check would leave sibling inbounds disabled. + entry := (*model.Client)(nil) + for i := range clients { + if clients[i].Email == clientEmail { + entry = &clients[i] + break } - clients, err := s.GetClients(inbound) - if err != nil { - return false, nil, err - } - for _, client := range clients { - if client.Email == clientEmail && client.Enable { - cipher := "" - if string(inbound.Protocol) == "shadowsocks" { - var oldSettings map[string]any - err = json.Unmarshal([]byte(inbound.Settings), &oldSettings) - if err != nil { - return false, nil, err - } - cipher, _ = oldSettings["method"].(string) - } - clientMap := map[string]any{ - "email": client.Email, - "id": client.ID, - "auth": client.Auth, - "security": client.Security, - "flow": client.Flow, - "password": client.Password, - "cipher": cipher, - "reverse": client.Reverse, - } - if inbound.NodeID != nil { - reenableNodeID = inbound.NodeID - } else { - reenablePlan = &trafficLocalApplyPlan{action: trafficAddUser, inbound: *inbound, client: clientMap} - } - break + } + if entry != nil && !handDisabled && (!entry.Enable || !traffic.Enable) { + flipStoredEntry = true + cipher := "" + if string(inbound.Protocol) == "shadowsocks" { + var oldSettings map[string]any + err = json.Unmarshal([]byte(inbound.Settings), &oldSettings) + if err != nil { + return false, nil, err } + cipher, _ = oldSettings["method"].(string) + } + clientMap := map[string]any{ + "email": entry.Email, + "id": entry.ID, + "auth": entry.Auth, + "security": entry.Security, + "flow": entry.Flow, + "password": entry.Password, + "cipher": cipher, + "reverse": entry.Reverse, + } + if inbound.NodeID != nil { + reenableNodeID = inbound.NodeID + } else { + reenablePlan = &trafficLocalApplyPlan{action: trafficAddUser, inbound: *inbound, client: clientMap} } } @@ -778,10 +786,6 @@ func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (b db := database.GetDB() now := time.Now().UnixMilli() - inbound, err := s.GetInbound(id) - if err != nil { - return false, nil, err - } if err := db.Transaction(func(tx *gorm.DB) error { if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil { return err @@ -803,16 +807,32 @@ func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (b Update("last_traffic_reset_time", now).Error; err != nil { return err } + if flipStoredEntry { + // Restore quota-disabled entries with the counters; an operator + // disable has already been excluded. + if err := s.markClientEnabledInSettings(tx, id, clientEmail); err != nil { + return err + } + if err := tx.Model(&model.ClientRecord{}).Where("email = ?", clientEmail). + Updates(map[string]any{"enable": true, "updated_at": now}).Error; err != nil { + return err + } + } if reenableNodeID != nil { return (&NodeService{}).MarkNodeDirtyTx(tx, *reenableNodeID) } - if inbound != nil && inbound.NodeID != nil { + if inbound.NodeID != nil { return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID) } return nil }); err != nil { return false, nil, err } + if flipStoredEntry { + // The entry left the subscription in its disabled state; a just + // re-enabled client must not keep missing from it. + InvalidateSubData() + } if reenablePlan != nil { rt, err := s.runtimeFor(&reenablePlan.inbound) @@ -826,10 +846,7 @@ func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (b } } - if inbound != nil { - return needRestart, inbound.NodeID, nil - } - return needRestart, nil, nil + return needRestart, inbound.NodeID, nil } // ResetAllTraffics zeroes every inbound's counters and brings back the inbounds a traffic diff --git a/internal/web/service/inbound_traffic_global.go b/internal/web/service/inbound_traffic_global.go index 43eea2022..55fd08ffd 100644 --- a/internal/web/service/inbound_traffic_global.go +++ b/internal/web/service/inbound_traffic_global.go @@ -37,7 +37,7 @@ func (s *InboundService) AcceptGlobalTraffic(masterGuid string, traffics []*xray return nil } - return submitTrafficWrite(func() error { + return submitTrafficWriteBackground(func() error { db := database.GetDB() known := make([]string, 0, len(emails)) for _, batch := range chunkStrings(emails, sqlInChunk) { diff --git a/internal/web/service/traffic_writer.go b/internal/web/service/traffic_writer.go index e8c43d7a4..b65c9eea5 100644 --- a/internal/web/service/traffic_writer.go +++ b/internal/web/service/traffic_writer.go @@ -26,11 +26,12 @@ type trafficWriteRequest struct { type serializedTxContextKey struct{} var ( - twMu sync.Mutex - twQueue chan *trafficWriteRequest - twCtx context.Context - twCancel context.CancelFunc - twDone chan struct{} + twMu sync.Mutex + twAdminQueue chan *trafficWriteRequest + twBgQueue chan *trafficWriteRequest + twCtx context.Context + twCancel context.CancelFunc + twDone chan struct{} ) // StartTrafficWriter spins up the serial writer goroutine. Safe to call again @@ -53,16 +54,18 @@ func StartTrafficWriter() { } } - queue := make(chan *trafficWriteRequest, trafficWriterQueueSize) + adminQueue := make(chan *trafficWriteRequest, trafficWriterQueueSize) + bgQueue := make(chan *trafficWriteRequest, trafficWriterQueueSize) ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) - twQueue = queue + twAdminQueue = adminQueue + twBgQueue = bgQueue twCtx = ctx twCancel = cancel twDone = done - go runTrafficWriter(ctx, queue, done) + go runTrafficWriter(ctx, adminQueue, bgQueue, done) } // StopTrafficWriter cancels the writer context and waits for the goroutine to @@ -89,31 +92,68 @@ func StopTrafficWriter() { } func clearTrafficWriterState() { - twQueue = nil + twAdminQueue = nil + twBgQueue = nil twCtx = nil twCancel = nil twDone = nil } -func runTrafficWriter(ctx context.Context, queue chan *trafficWriteRequest, done chan struct{}) { +// trafficWriterQueueLen is the test's view of both lanes' pending requests. +func trafficWriterQueueLen() int { + twMu.Lock() + defer twMu.Unlock() + return len(twAdminQueue) + len(twBgQueue) +} + +// One goroutine serves both lanes (no two writes side by side — the Postgres +// deadlock guard c5d31de4e; the admin lane is preferred over the 5s poll and node merges, #6035). +func runTrafficWriter(ctx context.Context, adminQueue, bgQueue chan *trafficWriteRequest, done chan struct{}) { defer close(done) for { select { - case req := <-queue: + case req := <-adminQueue: req.done <- safeApply(req.apply) case <-ctx.Done(): - for { - select { - case req := <-queue: - req.done <- safeApply(req.apply) - default: - return - } + drainTrafficWriter(adminQueue, bgQueue) + return + default: + select { + case req := <-adminQueue: + req.done <- safeApply(req.apply) + case req := <-bgQueue: + req.done <- safeApply(req.apply) + case <-ctx.Done(): + drainTrafficWriter(adminQueue, bgQueue) + return } } } } +// drainTrafficWriter finishes every request already queued on shutdown, as the +// single-queue writer used to: both lanes drain until empty, so no write is dropped. +func drainTrafficWriter(adminQueue, bgQueue chan *trafficWriteRequest) { + for { + drained := false + select { + case req := <-adminQueue: + req.done <- safeApply(req.apply) + drained = true + default: + } + select { + case req := <-bgQueue: + req.done <- safeApply(req.apply) + drained = true + default: + } + if !drained { + return + } + } +} + // runSerializedTx runs fn inside one DB transaction on the shared serial // traffic-writer goroutine, so it can never execute concurrently with the // @every 5s traffic poll (AddTraffic). Both touch the hot client_traffics and @@ -167,13 +207,28 @@ func safeApply(fn func() error) (err error) { return fn() } +// submitTrafficWrite runs fn on the serial writer's admin lane, ahead of any +// queued periodic work (the traffic poll, the node sync merges). func submitTrafficWrite(fn func() error) error { + return submitTrafficWriteLane(fn, false) +} + +// submitTrafficWriteBackground runs fn on the periodic lane (the 5s traffic poll +// and node snapshot merges), served only when no admin-lane write is queued. +func submitTrafficWriteBackground(fn func() error) error { + return submitTrafficWriteLane(fn, true) +} + +func submitTrafficWriteLane(fn func() error, background bool) error { req := &trafficWriteRequest{apply: fn, done: make(chan error, 1)} twMu.Lock() - queue := twQueue + queue := twAdminQueue ctx := twCtx done := twDone + if background { + queue = twBgQueue + } if queue == nil || ctx == nil || done == nil { twMu.Unlock() return safeApply(fn) diff --git a/internal/web/service/traffic_writer_test.go b/internal/web/service/traffic_writer_test.go index 42520fbbe..8623cf4b1 100644 --- a/internal/web/service/traffic_writer_test.go +++ b/internal/web/service/traffic_writer_test.go @@ -161,13 +161,7 @@ func waitTrafficWriterQueued(t *testing.T) { deadline := time.Now().Add(time.Second) for time.Now().Before(deadline) { - twMu.Lock() - queued := 0 - if twQueue != nil { - queued = len(twQueue) - } - twMu.Unlock() - if queued > 0 { + if trafficWriterQueueLen() > 0 { return } time.Sleep(10 * time.Millisecond) @@ -217,10 +211,7 @@ func parkSerializedWriter(t *testing.T) (release func()) { func waitForQueuedWrite() bool { deadline := time.Now().Add(time.Second) for time.Now().Before(deadline) { - twMu.Lock() - queued := len(twQueue) > 0 - twMu.Unlock() - if queued { + if trafficWriterQueueLen() > 0 { return true } time.Sleep(10 * time.Millisecond) @@ -228,6 +219,99 @@ func waitForQueuedWrite() bool { return false } +// A write the operator is waiting on must not queue behind the periodic work +// that keeps arriving every 5s (#6035): with both lanes filled, admin runs first. +func TestTrafficWriterAdminLanePreemptsBackgroundQueue(t *testing.T) { + resetTrafficWriterForTest(t) + + StartTrafficWriter() + parkStarted := make(chan struct{}) + releasePark := make(chan struct{}) + go func() { + _ = submitTrafficWrite(func() error { + close(parkStarted) + <-releasePark + return nil + }) + }() + waitTrafficWriterSignal(t, parkStarted, "parking write did not start") + + order := make(chan string, 2) + bgDone := make(chan error, 1) + go func() { + bgDone <- submitTrafficWriteBackground(func() error { + order <- "background" + return nil + }) + }() + adminDone := make(chan error, 1) + go func() { + adminDone <- submitTrafficWrite(func() error { + order <- "admin" + return nil + }) + }() + deadline := time.Now().Add(time.Second) + for trafficWriterQueueLen() < 2 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if trafficWriterQueueLen() < 2 { + t.Fatal("both writes did not reach the queues") + } + + close(releasePark) + if got := <-order; got != "admin" { + t.Fatalf("first write served after the parked one = %q, want admin: the lane the operator waits on", got) + } + if got := <-order; got != "background" { + t.Fatalf("second write served = %q, want background", got) + } + if err := <-adminDone; err != nil { + t.Fatalf("admin write: %v", err) + } + if err := <-bgDone; err != nil { + t.Fatalf("background write: %v", err) + } +} + +// A stop must drain every queued write on both lanes, not one per lane: a +// submitter blocked behind two queued writes must not read "stopped". +func TestTrafficWriterStopDrainsEveryQueuedWrite(t *testing.T) { + resetTrafficWriterForTest(t) + + StartTrafficWriter() + parkStarted := make(chan struct{}) + releasePark := make(chan struct{}) + go func() { + _ = submitTrafficWrite(func() error { + close(parkStarted) + <-releasePark + return nil + }) + }() + waitTrafficWriterSignal(t, parkStarted, "parking write did not start") + + results := make(chan error, 3) + go func() { results <- submitTrafficWrite(func() error { return nil }) }() + go func() { results <- submitTrafficWrite(func() error { return nil }) }() + go func() { results <- submitTrafficWriteBackground(func() error { return nil }) }() + deadline := time.Now().Add(time.Second) + for trafficWriterQueueLen() < 3 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if trafficWriterQueueLen() < 3 { + t.Fatal("queued writes did not all reach the lanes") + } + + close(releasePark) + StopTrafficWriter() + for range 3 { + if err := waitTrafficWriterErr(t, results); err != nil { + t.Fatalf("a queued write was dropped on stop: %v", err) + } + } +} + func waitWriterResult(t *testing.T, done <-chan error) error { t.Helper() select { diff --git a/internal/web/service/tuic_traffic_receipt.go b/internal/web/service/tuic_traffic_receipt.go index 117df3785..35b925cac 100644 --- a/internal/web/service/tuic_traffic_receipt.go +++ b/internal/web/service/tuic_traffic_receipt.go @@ -17,7 +17,8 @@ func (s *InboundService) AddTuicTrafficBatch(id string, traffic []*xray.ClientTr if id == "" { return errors.New("TUIC traffic batch has no ID") } - return submitTrafficWrite(func() error { + // The receipt journal is periodic accounting, not an operator action. + return submitTrafficWriteBackground(func() error { return database.GetDB().Transaction(func(tx *gorm.DB) error { result := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&model.TuicTrafficReceipt{ID: id}) if result.Error != nil { From f4030c889c2ea3f6aab492774b7b9d70eb311ad0 Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 5 Nov 2026 20:38:49 +0330 Subject: [PATCH 005/130] fix(frontend): make inbound forms accessible to screen readers (#7025) Expose selectable options and selected values, associate validation guidance with controls, and contain keyboard focus in inbound dialogs. Preserve create and edit serialization and add Chromium keyboard and accessibility checks. --- .github/workflows/ci.yml | 9 + frontend/README.md | 27 +++ frontend/src/components/form/NativeSelect.css | 14 ++ .../components/form/NativeSelect.stories.tsx | 67 ++++++++ frontend/src/components/form/NativeSelect.tsx | 70 ++++++++ .../components/form/rhf/FormField.stories.tsx | 3 + .../src/components/form/rhf/FormField.tsx | 21 ++- .../forms/transport/CustomSockoptList.tsx | 3 +- .../xray/forms/transport/FinalMaskForm.tsx | 17 +- .../lib/xray/forms/transport/XDriveForm.tsx | 3 +- .../form/InboundFormModal.stories.tsx | 121 ++++++++++++++ .../pages/inbounds/form/InboundFormModal.tsx | 60 ++++++- .../inbounds/form/protocols/hysteria.tsx | 5 +- .../pages/inbounds/form/protocols/mixed.tsx | 5 +- .../inbounds/form/protocols/shadowsocks.tsx | 9 +- .../pages/inbounds/form/protocols/tuic.tsx | 7 +- .../pages/inbounds/form/protocols/tunnel.tsx | 5 +- .../pages/inbounds/form/protocols/vless.tsx | 5 +- .../pages/inbounds/form/security/reality.tsx | 5 +- .../src/pages/inbounds/form/security/tls.tsx | 11 +- .../pages/inbounds/form/transport/sockopt.tsx | 5 +- .../pages/inbounds/form/transport/xhttp.tsx | 17 +- .../test/inbound-form-accessibility.test.tsx | 133 +++++++++++++++ frontend/src/test/inbound-form-modal.test.tsx | 84 ++++------ frontend/src/test/native-select.test.tsx | 99 +++++++++++ .../src/test/outbound-form-modal.test.tsx | 7 + frontend/src/test/rhf-form-field.test.tsx | 5 + frontend/src/test/test-utils.tsx | 13 ++ frontend/tools/check-inbound-keyboard.mjs | 155 ++++++++++++++++++ 29 files changed, 875 insertions(+), 110 deletions(-) create mode 100644 frontend/src/components/form/NativeSelect.css create mode 100644 frontend/src/components/form/NativeSelect.stories.tsx create mode 100644 frontend/src/components/form/NativeSelect.tsx create mode 100644 frontend/src/pages/inbounds/form/InboundFormModal.stories.tsx create mode 100644 frontend/src/test/inbound-form-accessibility.test.tsx create mode 100644 frontend/src/test/native-select.test.tsx create mode 100644 frontend/tools/check-inbound-keyboard.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d82bb8cb..e17f1eb25 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -365,6 +365,15 @@ jobs: - name: Build Storybook run: npm run build-storybook working-directory: frontend + - name: Inbound keyboard and accessibility tree + working-directory: frontend + run: | + set -euo pipefail + ./node_modules/.bin/vite preview --outDir storybook-static --host 127.0.0.1 --port 6006 > /tmp/inbound-preview.log 2>&1 & + preview_pid=$! + trap 'kill "$preview_pid" 2>/dev/null || true' EXIT + curl --retry 30 --retry-connrefused --retry-delay 1 --retry-max-time 45 -fsS http://127.0.0.1:6006/iframe.html > /dev/null + node tools/check-inbound-keyboard.mjs http://127.0.0.1:6006 - name: Audit run: npm run audit working-directory: frontend diff --git a/frontend/README.md b/frontend/README.md index 77e32aee6..5ed72ea67 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -47,6 +47,33 @@ production-style links work without round-tripping through Go. CI runs `typecheck`, `lint`, `format:check`, `test`, `build`, and `build-storybook` on every PR (see `../.github/workflows/ci.yml`). +### Inbound accessibility verification + +`npm test` includes the real inbound form and native-select regression fixtures. +After `npm run build-storybook`, serve the built stories with +`npx vite preview --outDir storybook-static --host 127.0.0.1 --port 6006` and, in +another terminal, run `node tools/check-inbound-keyboard.mjs`. CI runs this check +too. It uses real Chromium Tab/Arrow/Enter input, checks native selected values +in the accessibility tree, captures create/edit requests, and verifies focus +containment and return. Its HTTP boundary is stubbed; backend configuration +generation and server validation are unchanged. + +Mobile viewport emulation and accessibility-tree checks do not prove TalkBack +or NVDA compatibility. On actual Android TalkBack/Chrome and Windows NVDA: + +1. Open Add Inbound, explore Protocol, open the native picker, choose Shadowsocks + and confirm the control announces its selected value. Cancel another picker + and confirm the value and focus stay unchanged. +2. Visit Protocol, select an encryption method, then Stream; choose RAW, + WebSocket, gRPC and XHTTP and verify the dependent fields and their labels. +3. Check Security's None/TLS/REALITY radios; try certificate/uTLS selections and + the ALPN multi-select, searchable node/fallback fields, clearing and custom tags. +4. Trigger a custom-share-address validation error from another tab. Confirm + the form reveals/focuses the field and reads its hint/error. Correct it and save. +5. Edit the inbound, confirm Protocol remains disabled, save a transport change, + and close/reopen with keyboard and touch exploration. Focus must return to + the opener and Tab/Shift+Tab must stay inside the open dialog. + ### One-off: scan for deprecated APIs Run this command to sweep the codebase for usages of APIs marked diff --git a/frontend/src/components/form/NativeSelect.css b/frontend/src/components/form/NativeSelect.css new file mode 100644 index 000000000..7d1d00b48 --- /dev/null +++ b/frontend/src/components/form/NativeSelect.css @@ -0,0 +1,14 @@ +.native-select { + padding-inline: 11px; + font-family: inherit; + cursor: pointer; +} + +.native-select:focus-visible { + outline: 2px solid currentColor; + outline-offset: 2px; +} + +.native-select:disabled { + cursor: not-allowed; +} diff --git a/frontend/src/components/form/NativeSelect.stories.tsx b/frontend/src/components/form/NativeSelect.stories.tsx new file mode 100644 index 000000000..cfe0eca95 --- /dev/null +++ b/frontend/src/components/form/NativeSelect.stories.tsx @@ -0,0 +1,67 @@ +import { useState } from 'react'; +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, within } from 'storybook/test'; + +import { NativeSelect } from './NativeSelect'; + +const meta = { + title: 'Form/NativeSelect', + component: NativeSelect, + tags: ['autodocs'], + parameters: { + docs: { + description: { + component: + 'Native single selection for short, fixed lists. Labels, values, keyboard interaction and the mobile picker belong to the browser. Index keys keep number and string values distinct in onChange; searchable, clearable and multi-select fields continue using Ant Design.', + }, + }, + }, + argTypes: { + options: { + description: 'Ordered labels, typed string/number values and optional disabled choices.', + }, + value: { + description: 'Controlled form value. Saved values absent from the list remain visible.', + }, + onChange: { + description: 'Receives the original typed option value for RHF or Ant Design Form.', + }, + placeholder: { description: 'Shown until the form has a value.' }, + disabled: { + description: 'Uses native disabled behavior and preserves the controlled form value.', + }, + size: { + description: 'Ant Design token size, without turning the control into a multi-row listbox.', + }, + }, + args: { + 'aria-label': 'Protocol', + options: [ + { value: 'vless', label: 'VLESS' }, + { value: 'shadowsocks', label: 'Shadowsocks' }, + { value: 'tuic', label: 'TUIC', disabled: true }, + ], + }, +} satisfies Meta; +export default meta; +type Story = StoryObj; + +export const SingleSelection: Story = { + render: function Render(args) { + const [value, setValue] = useState('vless'); + return ; + }, + play: async ({ canvas, userEvent }) => { + const select = canvas.getByRole('combobox', { name: 'Protocol' }); + await expect(select).toHaveDisplayValue('VLESS'); + await userEvent.selectOptions( + select, + within(select).getByRole('option', { name: 'Shadowsocks' }), + ); + await expect(select).toHaveDisplayValue('Shadowsocks'); + await expect(within(select).getByRole('option', { name: 'Shadowsocks' })).toHaveProperty( + 'selected', + true, + ); + }, +}; diff --git a/frontend/src/components/form/NativeSelect.tsx b/frontend/src/components/form/NativeSelect.tsx new file mode 100644 index 000000000..52307a299 --- /dev/null +++ b/frontend/src/components/form/NativeSelect.tsx @@ -0,0 +1,70 @@ +import type { ComponentPropsWithRef } from 'react'; +import { theme } from 'antd'; + +import './NativeSelect.css'; + +export interface NativeSelectProps extends Omit< + ComponentPropsWithRef<'select'>, + 'value' | 'defaultValue' | 'onChange' | 'multiple' | 'children' | 'size' +> { + value?: Value | null; + onChange?: (value: Value) => void; + options: readonly { value: Value; label: string | number; disabled?: boolean }[]; + placeholder?: string; + size?: 'small' | 'middle' | 'large'; +} + +export function NativeSelect({ + value, + options, + onChange, + placeholder, + disabled, + className, + style, + size, + ...props +}: NativeSelectProps) { + const { token } = theme.useToken(); + const selected = options.findIndex((option) => Object.is(option.value, value)); + const hasUnlistedValue = selected < 0 && value != null; + return ( + + ); +} diff --git a/frontend/src/components/form/rhf/FormField.stories.tsx b/frontend/src/components/form/rhf/FormField.stories.tsx index 37541574b..5bf09ca2c 100644 --- a/frontend/src/components/form/rhf/FormField.stories.tsx +++ b/frontend/src/components/form/rhf/FormField.stories.tsx @@ -221,6 +221,9 @@ export const ValidationErrors: Story = { play: async ({ canvas, userEvent }) => { const remarkError = await canvas.findByText('Remark is required'); await waitFor(() => expect(remarkError).toBeVisible()); + await expect(canvas.getByRole('textbox', { name: 'Remark' })).toHaveAccessibleDescription( + 'Remark is required', + ); await waitFor(() => expect(canvas.getByText('Port must be between 1 and 65535')).toBeVisible()); await userEvent.type(canvas.getByPlaceholderText('vless-reality-443'), 'vless-reality-443'); await userEvent.click(canvas.getByRole('button', { name: 'Validate' })); diff --git a/frontend/src/components/form/rhf/FormField.tsx b/frontend/src/components/form/rhf/FormField.tsx index aeca5064c..db04469a9 100644 --- a/frontend/src/components/form/rhf/FormField.tsx +++ b/frontend/src/components/form/rhf/FormField.tsx @@ -1,5 +1,5 @@ import { cloneElement, useId } from 'react'; -import type { CSSProperties, ReactElement, ReactNode } from 'react'; +import type { AriaAttributes, CSSProperties, ReactElement, ReactNode } from 'react'; import { Controller } from 'react-hook-form'; import type { Control, ControllerProps, FieldValues, Path } from 'react-hook-form'; import { Form } from 'antd'; @@ -50,12 +50,10 @@ export function FormField({ const dottedName = toDotted(name) as Path; const generatedId = useId(); const hintId = useId(); - const childOwnProps = (children as ReactElement<{ id?: string; 'aria-describedby'?: string }>) - .props; + const errorId = `${generatedId}-error`; + const extraId = `${generatedId}-extra`; + const childOwnProps = (children as ReactElement<{ id?: string } & AriaAttributes>).props; const fieldId = childOwnProps.id ?? generatedId; - const describedBy = tooltip - ? [childOwnProps['aria-describedby'], hintId].filter(Boolean).join(' ') - : undefined; return ( ({ const help = fieldState.error?.message ? t(fieldState.error.message, { defaultValue: fieldState.error.message }) : undefined; + const describedBy = + [childOwnProps['aria-describedby'], tooltip && hintId, extra && extraId, help && errorId] + .filter(Boolean) + .join(' ') || undefined; const childProps: Record = { id: fieldId, + 'aria-describedby': describedBy, + 'aria-invalid': fieldState.invalid || childOwnProps['aria-invalid'], [valueProp]: displayValue, onChange: (...args: unknown[]) => { const raw = normalizeAntdOnChange(args, valueProp); @@ -79,16 +83,15 @@ export function FormField({ onBlur: field.onBlur, ref: field.ref, }; - if (describedBy) childProps['aria-describedby'] = describedBy; return ( {extra} : extra} required={required} validateStatus={fieldState.error ? 'error' : undefined} - help={help} + help={help ? {help} : undefined} noStyle={noStyle} className={className} style={style} diff --git a/frontend/src/lib/xray/forms/transport/CustomSockoptList.tsx b/frontend/src/lib/xray/forms/transport/CustomSockoptList.tsx index baa8af201..76d3e6cbe 100644 --- a/frontend/src/lib/xray/forms/transport/CustomSockoptList.tsx +++ b/frontend/src/lib/xray/forms/transport/CustomSockoptList.tsx @@ -1,3 +1,4 @@ +import { NativeSelect } from '@/components/form/NativeSelect'; import { Button, Divider, Form, Input, Select } from 'antd'; import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'; import { useTranslation } from 'react-i18next'; @@ -68,7 +69,7 @@ export default function CustomSockoptList({ - diff --git a/frontend/src/lib/xray/forms/transport/FinalMaskForm.tsx b/frontend/src/lib/xray/forms/transport/FinalMaskForm.tsx index 269fd604d..ca1d7e75d 100644 --- a/frontend/src/lib/xray/forms/transport/FinalMaskForm.tsx +++ b/frontend/src/lib/xray/forms/transport/FinalMaskForm.tsx @@ -1,3 +1,4 @@ +import { NativeSelect } from '@/components/form/NativeSelect'; import { useEffect, useId, useRef, useState } from 'react'; import { AutoComplete, @@ -407,7 +408,7 @@ function TcpMasksList({ } /> {allowPresets && ( - form.setFieldValue([...absolutePath, 'settings'], defaultTcpMaskSettings(v)) } @@ -1123,7 +1124,7 @@ function UdpMaskItem({ - - - - + - ({ value: r, label: t(`pages.inbounds.periodicTrafficReset.${r}`), @@ -958,7 +994,7 @@ export default function InboundFormModal({ <> {hasSelectableTransport && ( - - ({ value: m, label: m }))} /> + ({ value: m, label: m }))} + /> {isSSWith2022 && ( @@ -48,7 +51,7 @@ export default function ShadowsocksFields({ isSSWith2022 }: ShadowsocksFieldsPro )} - - - setAuthKind(v)} diff --git a/frontend/src/pages/inbounds/form/security/reality.tsx b/frontend/src/pages/inbounds/form/security/reality.tsx index 0b5649138..2bd4848ac 100644 --- a/frontend/src/pages/inbounds/form/security/reality.tsx +++ b/frontend/src/pages/inbounds/form/security/reality.tsx @@ -1,3 +1,4 @@ +import { NativeSelect } from '@/components/form/NativeSelect'; import { useState, useId } from 'react'; import { useFormContext, useWatch } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; @@ -112,7 +113,9 @@ export default function RealityForm({ name={['streamSettings', 'realitySettings', 'settings', 'fingerprint']} label="uTLS" > - ({ value: u, label: u }))} /> @@ -212,7 +213,7 @@ function EchSockoptSection() { name={['streamSettings', 'tlsSettings', 'echSockopt', 'domainStrategy']} label={t('pages.xray.wireguard.domainStrategy')} > - ({ value: v, label: v }))} /> - ({ value: fp, label: fp })), diff --git a/frontend/src/pages/inbounds/form/transport/sockopt.tsx b/frontend/src/pages/inbounds/form/transport/sockopt.tsx index b9f2a84dd..8863d3f84 100644 --- a/frontend/src/pages/inbounds/form/transport/sockopt.tsx +++ b/frontend/src/pages/inbounds/form/transport/sockopt.tsx @@ -1,3 +1,4 @@ +import { NativeSelect } from '@/components/form/NativeSelect'; import { useId } from 'react'; import { useTranslation } from 'react-i18next'; import { Alert, Form, InputNumber, Segmented, Select, Switch } from 'antd'; @@ -207,13 +208,13 @@ export default function SockoptForm({ name={['streamSettings', 'sockopt', 'tcpcongestion']} label={t('pages.inbounds.form.tcpCongestion')} > - - - - - patch('inboundIds', v as number[])} options={inboundOptions} - placeholder={t('inbounds')} + placeholder={t('pages.clients.attachedInbounds')} allowClear showSearch={{ optionFilterProp: 'label' }} listHeight={220} diff --git a/frontend/src/pages/inbounds/form/protocols/tuic.tsx b/frontend/src/pages/inbounds/form/protocols/tuic.tsx index 7f82bdfa1..c3cab905c 100644 --- a/frontend/src/pages/inbounds/form/protocols/tuic.tsx +++ b/frontend/src/pages/inbounds/form/protocols/tuic.tsx @@ -69,7 +69,7 @@ export default function TuicFields() { if (obj.webKeyFile) { setValue('settings.server.private_key', obj.webKeyFile); } - messageApi.success(t('pages.inbounds.setSuccess')); + messageApi.success(t('success')); } catch { messageApi.error(t('somethingWentWrong')); } finally { diff --git a/frontend/src/pages/settings/SecurityTab.tsx b/frontend/src/pages/settings/SecurityTab.tsx index d8b448f70..87e4a5f1a 100644 --- a/frontend/src/pages/settings/SecurityTab.tsx +++ b/frontend/src/pages/settings/SecurityTab.tsx @@ -169,7 +169,7 @@ export default function SecurityTab({ allSetting, updateSetting, saveSetting }: if (!token) return; const ok = await ClipboardManager.copyText(token); if (ok) messageApi.success(t('copySuccess')); - else messageApi.error(t('copyFail') ?? 'Copy failed'); + else messageApi.error(t('copyFail')); } function openCreateModal() { diff --git a/frontend/src/pages/xray/overrides/WarpModal.tsx b/frontend/src/pages/xray/overrides/WarpModal.tsx index 7fc2dc5bf..fb24f0f1e 100644 --- a/frontend/src/pages/xray/overrides/WarpModal.tsx +++ b/frontend/src/pages/xray/overrides/WarpModal.tsx @@ -291,7 +291,7 @@ export default function WarpModal({ interval: methods.getValues('updateInterval'), }); if (msg?.success) { - messageApi.success(t('pages.setting.toasts.saveSuccess', 'Settings saved successfully')); + messageApi.success(t('pages.settings.toasts.modifySettings')); } } finally { setLoading(false); diff --git a/frontend/src/test/i18n-dead-keys.test.ts b/frontend/src/test/i18n-dead-keys.test.ts index 002849c57..9cead2504 100644 --- a/frontend/src/test/i18n-dead-keys.test.ts +++ b/frontend/src/test/i18n-dead-keys.test.ts @@ -82,14 +82,15 @@ describe('i18n keys', () => { ); }); - it('no literal t() key resolves to an object', () => { - const objectKeys = Array.from( - blob.matchAll(/\bt\(\s*(['"`])([\w.-]+)\1\s*[,)]/g), - (m) => m[2], - ).filter((key) => enKeys.some((leaf) => leaf.startsWith(`${key}.`))); + it('every literal t() key is an en-US string', () => { + const leaves = new Set(enKeys); + const literalKeys = new Set( + Array.from(blob.matchAll(/\bt\(\s*(['"`])([\w.-]+)\1\s*[,)]/g), (m) => m[2]), + ); + const unresolved = [...literalKeys].filter((key) => !leaves.has(key)); expect( - objectKeys, - `t() keys naming a group, rendered as "key '…' returned an object instead of string.":\n ${objectKeys.join('\n ')}`, + unresolved, + `t() keys that are not an en-US string (a missing key renders raw, a group renders "key '…' returned an object instead of string."):\n ${unresolved.join('\n ')}`, ).toEqual([]); }); diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 194eca6fc..80f302f51 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -40,6 +40,7 @@ "indefinite": "غير محدد", "unlimited": "غير محدود", "none": "لا شيء", + "empty": "فارغ", "qrCode": "كود QR", "info": "معلومات أكتر", "edit": "تحرير", @@ -47,6 +48,7 @@ "reset": "إعادة تعيين", "noData": "لا توجد بيانات.", "copySuccess": "اتنسخ بنجاح", + "copyFail": "فشل النسخ", "sure": "متأكد؟", "encryption": "تشفير", "transmission": "نقل", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index ed3c13da0..feb00c580 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -40,6 +40,7 @@ "indefinite": "Indefinite", "unlimited": "Unlimited", "none": "None", + "empty": "Empty", "qrCode": "QR Code", "info": "More Information", "edit": "Edit", @@ -47,6 +48,7 @@ "reset": "Reset", "noData": "Nothing here yet", "copySuccess": "Copied successfully", + "copyFail": "Copy failed", "sure": "Sure", "encryption": "Encryption", "transmission": "Transmission", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 4515a5e97..445ce1826 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -40,6 +40,7 @@ "indefinite": "Indefinido", "unlimited": "Ilimitado", "none": "Ninguno", + "empty": "Vacío", "qrCode": "Código QR", "info": "Más Información", "edit": "Editar", @@ -47,6 +48,7 @@ "reset": "Restablecer", "noData": "Sin datos", "copySuccess": "Copiado exitosamente", + "copyFail": "Error al copiar", "sure": "Seguro", "encryption": "Encriptación", "transmission": "Transmisión", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 16c5a1cc2..8b747b942 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -40,6 +40,7 @@ "indefinite": "نامحدود", "unlimited": "نامحدود", "none": "هیچ", + "empty": "خالی", "qrCode": "QRکد", "info": "اطلاعات بیشتر", "edit": "ویرایش", @@ -47,6 +48,7 @@ "reset": "بازنشانی", "noData": "داده‌ای وجود ندارد.", "copySuccess": "باموفقیت کپی‌شد", + "copyFail": "کپی ناموفق بود", "sure": "مطمئن", "encryption": "رمزگذاری", "transmission": "راه‌اتصال", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 9afc4339b..5ecee70c1 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -40,6 +40,7 @@ "indefinite": "Tak Terbatas", "unlimited": "Tanpa Batas", "none": "Tidak ada", + "empty": "Kosong", "qrCode": "Kode QR", "info": "Informasi Lebih Lanjut", "edit": "Edit", @@ -47,6 +48,7 @@ "reset": "Reset", "noData": "Tidak ada data.", "copySuccess": "Berhasil Disalin", + "copyFail": "Gagal Menyalin", "sure": "Yakin", "encryption": "Enkripsi", "transmission": "Transmisi", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 9472664b0..52bd3c9b2 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -40,6 +40,7 @@ "indefinite": "無期限", "unlimited": "無制限", "none": "なし", + "empty": "空欄", "qrCode": "QRコード", "info": "詳細情報", "edit": "編集", @@ -47,6 +48,7 @@ "reset": "リセット", "noData": "データなし。", "copySuccess": "コピー成功", + "copyFail": "コピー失敗", "sure": "確定", "encryption": "暗号化", "transmission": "伝送", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 3df23658d..11e238b90 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -40,6 +40,7 @@ "indefinite": "Indeterminado", "unlimited": "Ilimitado", "none": "Nenhum", + "empty": "Vazio", "qrCode": "Código QR", "info": "Mais Informações", "edit": "Editar", @@ -47,6 +48,7 @@ "reset": "Redefinir", "noData": "Sem dados.", "copySuccess": "Copiado com Sucesso", + "copyFail": "Falha ao Copiar", "sure": "Certo", "encryption": "Criptografia", "transmission": "Transmissão", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 2fc6a751c..5e4bbce3d 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -40,6 +40,7 @@ "indefinite": "Бесконечно", "unlimited": "Безлимит", "none": "Нет", + "empty": "Пусто", "qrCode": "QR-код", "info": "Информация", "edit": "Изменить", @@ -47,6 +48,7 @@ "reset": "Сброс", "noData": "Нет данных.", "copySuccess": "Скопировано", + "copyFail": "Не удалось скопировать", "sure": "Да", "encryption": "Шифрование", "transmission": "Транспорт", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index bd49a3bb1..edb961b00 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -40,6 +40,7 @@ "indefinite": "Bez časového obmedzenia", "unlimited": "Bez obmedzenia", "none": "Žiadne", + "empty": "Prázdne", "qrCode": "QR kód", "info": "Ďalšie informácie", "edit": "Upraviť", @@ -47,6 +48,7 @@ "reset": "Vynulovať", "noData": "Zatiaľ tu nič nie je", "copySuccess": "Úspešne skopírované", + "copyFail": "Kopírovanie zlyhalo", "sure": "Áno", "encryption": "Šifrovanie", "transmission": "Prenos", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 593e4932c..3bc0cc4d7 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -40,6 +40,7 @@ "indefinite": "Belirsiz", "unlimited": "Sınırsız", "none": "Yok", + "empty": "Boş", "qrCode": "QR Kod", "info": "Daha Fazla Bilgi", "edit": "Düzenle", @@ -47,6 +48,7 @@ "reset": "Sıfırla", "noData": "Veri yok.", "copySuccess": "Başarıyla kopyalandı", + "copyFail": "Kopyalama başarısız", "sure": "Emin misiniz?", "encryption": "Şifreleme", "transmission": "İletim", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 506df1d42..af803fd74 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -40,6 +40,7 @@ "indefinite": "Безстроково", "unlimited": "Безлімітний", "none": "Немає", + "empty": "Порожньо", "qrCode": "QR-Код", "info": "Більше інформації", "edit": "Змінити", @@ -47,6 +48,7 @@ "reset": "Скидання", "noData": "Немає даних.", "copySuccess": "Скопійовано успішно", + "copyFail": "Не вдалося скопіювати", "sure": "Звичайно", "encryption": "Шифрування", "transmission": "Протокол передачи", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 1723feeec..68a702ad1 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -40,6 +40,7 @@ "indefinite": "Không xác định", "unlimited": "Không giới hạn", "none": "Không", + "empty": "Trống", "qrCode": "Mã QR", "info": "Thông tin thêm", "edit": "Sửa", @@ -47,6 +48,7 @@ "reset": "Đặt lại", "noData": "Không có dữ liệu.", "copySuccess": "Đã sao chép thành công", + "copyFail": "Sao chép thất bại", "sure": "Chắc chắn", "encryption": "Mã hóa", "transmission": "Truyền tải", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 5e98edf8c..b59f15ffa 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -40,6 +40,7 @@ "indefinite": "无限期", "unlimited": "无限制", "none": "无", + "empty": "空", "qrCode": "二维码", "info": "更多信息", "edit": "编辑", @@ -47,6 +48,7 @@ "reset": "重置", "noData": "无数据。", "copySuccess": "复制成功", + "copyFail": "复制失败", "sure": "确定", "encryption": "加密", "transmission": "传输", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 1d522f9cf..02251ac98 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -40,6 +40,7 @@ "indefinite": "無限期", "unlimited": "無限制", "none": "無", + "empty": "空", "qrCode": "二維碼", "info": "更多資訊", "edit": "編輯", @@ -47,6 +48,7 @@ "reset": "重置", "noData": "無數據。", "copySuccess": "複製成功", + "copyFail": "複製失敗", "sure": "確定", "encryption": "加密", "transmission": "傳輸", From 510bee2f30130e0859667316d844eeebfab08315 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Fri, 6 Nov 2026 18:47:13 +0100 Subject: [PATCH 007/130] fix(traffic): serialize inline traffic writes with the writer submitTrafficWrite falls back to running fn inline when the serial writer is not running (before StartTrafficWriter, during the shutdown drain, in CLI paths and tests). That path took no lock, so an inline write could run beside the draining writer or another inline write, breaking the single-writer invariant that guards the Postgres deadlock. One visible effect: ResetTrafficByEmail fans out one reset per inbound. Run side by side, the second reset read the record still disabled but the traffic already zeroed, judged the client operator-disabled and saved enable=false over the first reset's restore (TestResetTrafficByEmail_ReenablesEveryInboundOfTheClient failed ~25%). safeApply now holds a package mutex, so every write path is serialized. --- internal/web/service/traffic_writer.go | 5 +++ internal/web/service/traffic_writer_test.go | 49 +++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/internal/web/service/traffic_writer.go b/internal/web/service/traffic_writer.go index b65c9eea5..a40b17484 100644 --- a/internal/web/service/traffic_writer.go +++ b/internal/web/service/traffic_writer.go @@ -32,6 +32,7 @@ var ( twCtx context.Context twCancel context.CancelFunc twDone chan struct{} + twApplyMu sync.Mutex ) // StartTrafficWriter spins up the serial writer goroutine. Safe to call again @@ -197,7 +198,11 @@ func isSerializedTx(tx *gorm.DB) bool { return serializedTxOf(tx) != nil } +// safeApply holds twApplyMu so an inline fallback (no writer, or shutdown drain) +// never runs beside another write: overlapping resets switched a client back off. func safeApply(fn func() error) (err error) { + twApplyMu.Lock() + defer twApplyMu.Unlock() defer func() { if r := recover(); r != nil { err = fmt.Errorf("traffic writer panic: %v", r) diff --git a/internal/web/service/traffic_writer_test.go b/internal/web/service/traffic_writer_test.go index 8623cf4b1..35189cd28 100644 --- a/internal/web/service/traffic_writer_test.go +++ b/internal/web/service/traffic_writer_test.go @@ -63,6 +63,55 @@ func TestTrafficWriterSubmitAfterStopRunsInline(t *testing.T) { } } +// The inline fallback ran beside other writes, so two resets of one client +// raced and the second one switched the client back off. +func TestTrafficWriterInlineFallbackNeverOverlapsAnotherWrite(t *testing.T) { + for _, tt := range []struct { + name string + setup func(t *testing.T, first func()) + }{ + {"writer never started", func(t *testing.T, first func()) { + go func() { _ = submitTrafficWrite(func() error { first(); return nil }) }() + }}, + {"submitted while shutdown drains", func(t *testing.T, first func()) { + StartTrafficWriter() + go func() { _ = submitTrafficWrite(func() error { first(); return nil }) }() + twMu.Lock() + ctx := twCtx + twMu.Unlock() + go StopTrafficWriter() + <-ctx.Done() + }}, + } { + t.Run(tt.name, func(t *testing.T) { + resetTrafficWriterForTest(t) + entered, secondStarted := make(chan struct{}), make(chan struct{}) + var inFirst, overlapped atomic.Bool + tt.setup(t, func() { + inFirst.Store(true) + close(entered) + select { + case <-secondStarted: + case <-time.After(300 * time.Millisecond): + } + inFirst.Store(false) + }) + <-entered + err := submitTrafficWrite(func() error { + overlapped.Store(inFirst.Load()) + close(secondStarted) + return nil + }) + if err != nil { + t.Fatalf("second submitTrafficWrite: %v", err) + } + if overlapped.Load() { + t.Fatal("inline write ran while another write was still applying") + } + }) + } +} + func TestTrafficWriterStopDrainsQueuedWrite(t *testing.T) { resetTrafficWriterForTest(t) From e535df03745c5ad003ae48e812024eb5fdc2124d Mon Sep 17 00:00:00 2001 From: Sanaei Date: Fri, 6 Nov 2026 18:47:14 +0100 Subject: [PATCH 008/130] fix(test): pin Havana repeated-midnight cases to a past transition tzdata 2026f cancelled Cuba's November 2026 DST fallback, so on hosts with current tzdata (macOS) 2026-11-01 has no repeated midnight: TestNextWeeklyRenewal_RepeatedMidnight failed and the subscription calendar cases passed without exercising the repeated midnight. Move both to 2020-11-01, a Sunday fallback on the 1st that every tzdata version agrees on. The weekly case still catches a 168-hour advance. --- internal/sub/calendar_expire_test.go | 5 +++-- internal/web/service/calendar_weekly_renew_test.go | 8 +++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/internal/sub/calendar_expire_test.go b/internal/sub/calendar_expire_test.go index 281dd7383..2d611e54a 100644 --- a/internal/sub/calendar_expire_test.go +++ b/internal/sub/calendar_expire_test.go @@ -37,8 +37,9 @@ func TestSubscriptionCalendarExpireInclusive(t *testing.T) { {"Taipei midnight", "true", "Asia/Taipei", "2030-10-01T00:00:00+08:00", 1, 1, true}, {"New York daylight time", "true", "America/New_York", "2030-10-01T00:00:00-04:00", 1, 1, true}, {"New York standard time", "true", "America/New_York", "2030-02-01T00:00:00-05:00", 1, 1, true}, - {"Havana first midnight", "true", "America/Havana", "2026-11-01T00:00:00-04:00", 1, 1, true}, - {"Havana repeated midnight", "true", "America/Havana", "2026-11-01T00:00:00-05:00", 1, 1, false}, + // Past fallback on purpose: tzdata 2026f cancelled Cuba's 2026 one. + {"Havana first midnight", "true", "America/Havana", "2020-11-01T00:00:00-04:00", 1, 1, true}, + {"Havana repeated midnight", "true", "America/Havana", "2020-11-01T00:00:00-05:00", 1, 1, false}, {"UTC midnight is not Taipei midnight", "true", "Asia/Taipei", "2030-10-01T00:00:00Z", 1, 1, false}, {"midday unchanged", "true", "UTC", "2030-10-01T12:00:00Z", 1, 1, false}, {"other midnight unchanged", "true", "UTC", "2030-10-02T00:00:00Z", 1, 1, false}, diff --git a/internal/web/service/calendar_weekly_renew_test.go b/internal/web/service/calendar_weekly_renew_test.go index c42a92b7f..eb6ce35a2 100644 --- a/internal/web/service/calendar_weekly_renew_test.go +++ b/internal/web/service/calendar_weekly_renew_test.go @@ -10,10 +10,12 @@ func TestNextWeeklyRenewal_RepeatedMidnight(t *testing.T) { if err != nil { t.Fatal(err) } + // A past transition: tzdata 2026f cancelled Cuba's November 2026 fallback, + // so a future one makes the result depend on the host's tzdata version. for _, tt := range []struct{ expiry, want string }{ - {"2026-10-25T00:00:00-04:00", "2026-11-01T00:00:00-04:00"}, - {"2026-11-01T00:00:00-04:00", "2026-11-08T00:00:00-05:00"}, - {"2026-11-01T00:00:00-05:00", "2026-11-08T00:00:00-05:00"}, + {"2020-10-25T00:00:00-04:00", "2020-11-01T00:00:00-04:00"}, + {"2020-11-01T00:00:00-04:00", "2020-11-08T00:00:00-05:00"}, + {"2020-11-01T00:00:00-05:00", "2020-11-08T00:00:00-05:00"}, } { from, err := time.Parse(time.RFC3339, tt.expiry) if err != nil { From 192dc93c164fb212a54c315bca49b268d827c4dd Mon Sep 17 00:00:00 2001 From: Sanaei Date: Thu, 12 Nov 2026 19:10:18 +0100 Subject: [PATCH 009/130] feat(xray): update xray-core to v26.11.9 Bump xtls/xray-core to 676eaf66f8f0 (v26.11.9) and the three binary pins (DockerInit.sh, release.yml Linux + Windows) in lockstep, so the vendored config loader and the child binary validate the same config. The same go.mod also moves the go directive to 1.27.4 and golang.org/x/crypto to v0.58.1-0.20261009181718-2f1f834330b2; the core pulls in refraction-networking/utls 20261108164504, xtls/reality 20261108101329 and klauspost/cpuid v2.4.2. XDRIVE now caps concurrency at 256 instead of 64 (#7340), so the schema comment quoting the cap follows. --- .github/workflows/release.yml | 4 ++-- DockerInit.sh | 2 +- .../src/schemas/protocols/stream/xdrive.ts | 2 +- go.mod | 13 +++++----- go.sum | 24 ++++++++----------- 5 files changed, 20 insertions(+), 25 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0c24efecf..82e130e75 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -115,7 +115,7 @@ jobs: cd x-ui/bin # Download dependencies - Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.10.31/" + Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.11.9/" if [ "${{ matrix.platform }}" == "amd64" ]; then fetch ${Xray_URL}Xray-linux-64.zip unzip Xray-linux-64.zip @@ -283,7 +283,7 @@ jobs: cd x-ui\bin # Download Xray for Windows - $Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.10.31/" + $Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.11.9/" Invoke-WebRequest @retry -Uri "${Xray_URL}Xray-windows-64.zip" -OutFile "Xray-windows-64.zip" Expand-Archive -Path "Xray-windows-64.zip" -DestinationPath . Remove-Item "Xray-windows-64.zip" diff --git a/DockerInit.sh b/DockerInit.sh index e4e4ea879..52b363eef 100755 --- a/DockerInit.sh +++ b/DockerInit.sh @@ -52,7 +52,7 @@ if [ -z "$MTG_MULTI_VER" ]; then fi mkdir -p build/bin cd build/bin -curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.10.31/Xray-linux-${XRAY_ZIP}.zip" +curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.11.9/Xray-linux-${XRAY_ZIP}.zip" unzip "Xray-linux-${XRAY_ZIP}.zip" rm -f "Xray-linux-${XRAY_ZIP}.zip" geoip.dat geosite.dat mv xray "${XRAY_BIN}" diff --git a/frontend/src/schemas/protocols/stream/xdrive.ts b/frontend/src/schemas/protocols/stream/xdrive.ts index c82e61bc9..4c496c088 100644 --- a/frontend/src/schemas/protocols/stream/xdrive.ts +++ b/frontend/src/schemas/protocols/stream/xdrive.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; // Both XDRIVE ends carry the same service, folder and secrets; an absent tuning knob takes -// the core's default (segmentBytes and concurrency are capped there at 16 MiB / 64). +// the core's default (segmentBytes and concurrency are capped there at 16 MiB / 256). export const XDriveServiceSchema = z.enum(['google-drive', 'local', 'template', 's3']); export type XDriveService = z.infer; diff --git a/go.mod b/go.mod index ac44b4280..604688e2d 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/mhsanaei/3x-ui/v3 -go 1.27.3 +go 1.27.4 require ( github.com/amnezia-vpn/amneziawg-go/v3 v3.1.20260828 @@ -22,15 +22,15 @@ require ( github.com/nicksnyder/go-i18n/v2 v2.7.0 github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 github.com/quic-go/quic-go v0.64.1 - github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af + github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b github.com/robfig/cron/v3 v3.0.1 github.com/shirou/gopsutil/v4 v4.26.10 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e github.com/valyala/fasthttp v1.77.0 github.com/xlzd/gotp v0.1.0 - github.com/xtls/xray-core v1.260327.1-0.20261031132019-a4a3dff5b20c + github.com/xtls/xray-core v1.260327.1-0.20261109052709-676eaf66f8f0 go.uber.org/atomic v1.12.0 - golang.org/x/crypto v0.58.0 + golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2 golang.org/x/net v0.62.0 golang.org/x/sync v0.24.0 golang.org/x/sys v0.49.0 @@ -47,7 +47,6 @@ require ( require ( github.com/Azure/go-ntlmssp v0.1.1 // indirect - github.com/andybalholm/brotli v1.2.7 // indirect github.com/bytedance/gopkg v0.1.4 // indirect github.com/bytedance/sonic v1.15.5 // indirect github.com/bytedance/sonic/loader v0.5.3 // indirect @@ -73,7 +72,7 @@ require ( github.com/jinzhu/now v1.1.5 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/juju/ratelimit v1.0.2 // indirect - github.com/klauspost/cpuid/v2 v2.4.1 // indirect + github.com/klauspost/cpuid/v2 v2.4.2 // indirect github.com/koron/go-ssdp v0.9.1 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/libp2p/go-nat v1.0.1-0.20250821073202-01afc089f138 // indirect @@ -103,7 +102,7 @@ require ( github.com/vishvananda/netlink v1.3.1 // indirect github.com/vishvananda/netns v0.0.5 // indirect github.com/wlynxg/anet v0.0.5 // indirect - github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8 // indirect + github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b // indirect github.com/yuin/gopher-lua v1.1.2 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect go.mongodb.org/mongo-driver/v2 v2.9.2 // indirect diff --git a/go.sum b/go.sum index 483711405..c9a22a8fc 100644 --- a/go.sum +++ b/go.sum @@ -6,8 +6,6 @@ github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktp github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4= github.com/amnezia-vpn/amneziawg-go/v3 v3.1.20260828 h1:D8d8gGvwXcTxUIsE4z6F6vjy4/VZddu95vMNtOygh1c= github.com/amnezia-vpn/amneziawg-go/v3 v3.1.20260828/go.mod h1:YoPc6qcOZqD7TXZ1xpedD8Sx3aSKsxN05ZqEFmXDNHk= -github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A= -github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e h1:5mgtR5gwIgBKMiGI1QdXldZZ+SNor06Nbu1wCBulQBg= github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e/go.mod h1:x7qxEvX6MCVtDuBKHj3E+88+BtrbEMuAL5qGUKItjW8= github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM= @@ -118,8 +116,8 @@ github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI= github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk= github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= -github.com/klauspost/cpuid/v2 v2.4.1 h1:I9KxadAkvo+QjtcEE2f2tyfEvmIla/T0m+14PrZNl0U= -github.com/klauspost/cpuid/v2 v2.4.1/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ= +github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/koron/go-ssdp v0.9.1 h1:zvxbAAuJftJIZ8Jh8mda+LI7V92hYZf/sKprmOxpxwA= github.com/koron/go-ssdp v0.9.1/go.mod h1:C43c047jWkDaeg9YuZlSh/QGqOieuWV6dbhWi/jcaLk= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -178,8 +176,8 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.64.1 h1:BCNTP+6x6++OPKrGST2FR3f1tycx8O3QOA3QQv09g70= github.com/quic-go/quic-go v0.64.1/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w= -github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af h1:er2acxbi3N1nvEq6HXHUAR1nTWEJmQfqiGR8EVT9rfs= -github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM= +github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b h1:Mi/DuaTxHeNIQ9g1ylZicAqa6Cb9wkHRiNtQH9uZ7Ts= +github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b/go.mod h1:rc/ctWeKlh9LSk5k90KlSPcwF7P6D31mn/9GI2NAfBI= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc= @@ -222,12 +220,10 @@ github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= github.com/xlzd/gotp v0.1.0 h1:37blvlKCh38s+fkem+fFh7sMnceltoIEBYTVXyoa5Po= github.com/xlzd/gotp v0.1.0/go.mod h1:ndLJ3JKzi3xLmUProq4LLxCuECL93dG9WASNLpHz8qg= -github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8 h1:RjLnVvlzK4q6zWaSBPNRGsrgx2fbJDeUWffjw574uzs= -github.com/xtls/reality v0.0.0-20261014101318-83f621788ca8/go.mod h1:ptlSkJ8k/7IDauNH0SA96JPOo+nYGLTv2Y3UMpwvAsY= -github.com/xtls/xray-core v1.260327.1-0.20261031132019-a4a3dff5b20c h1:XijTasBJ2fImHZo1GoAgSfHuDqloQGYHEADLy9CgrJ8= -github.com/xtls/xray-core v1.260327.1-0.20261031132019-a4a3dff5b20c/go.mod h1:/Umx7vpU+A78gOOuKl6ESU6eQJ5EBRhwr5cl7+9/drw= -github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= -github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b h1:fAn11r21QiUY2oAGwENWb5ummjhWwMcs2WzkbjDMh+k= +github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b/go.mod h1:ptlSkJ8k/7IDauNH0SA96JPOo+nYGLTv2Y3UMpwvAsY= +github.com/xtls/xray-core v1.260327.1-0.20261109052709-676eaf66f8f0 h1:p2uoadP+ulClbJ9dn+QioF2SfBqRly6VoKJosHqwcRo= +github.com/xtls/xray-core v1.260327.1-0.20261109052709-676eaf66f8f0/go.mod h1:qOpfp0I7DlfhmEHyiv0OV+6jbalzb41EFGegv0UfzBE= github.com/yuin/gopher-lua v0.0.0-20190206043414-8bfc7677f583/go.mod h1:gqRgreBUhTSL0GeU64rtZ3Uq3wtjOa/TB2YfrtkCbVQ= github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA= github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8= @@ -245,8 +241,8 @@ go4.org/netipx v0.0.0-20260823151212-3075585bcbeb h1:XBM4hvfwGAttkkiTIFfeigdfcL1 go4.org/netipx v0.0.0-20260823151212-3075585bcbeb/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y= golang.org/x/arch v0.32.0 h1:NjGf8/xGf5JgAJ4dw4NtME5R1L7xatagqAg95T3LgII= golang.org/x/arch v0.32.0/go.mod h1:KcJSod3cqT2dKcjBxqTyGfbumNikqU9p5tHJinPJnuY= -golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= -golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2 h1:zGDaB+/Mus2mScKvZ23k+W9NAUbP56sNM9SptgvWI5A= +golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/crypto/x509roots/fallback v0.0.0-20261030153154-30a33513ff6d h1:5NBkmd8MXirajj6AAEpi4HFVJnVkBNPTL1ggYAKqaws= golang.org/x/crypto/x509roots/fallback v0.0.0-20261030153154-30a33513ff6d/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E= golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A= From a748f799c709fd878858cb46e1ede4ba8155909a Mon Sep 17 00:00:00 2001 From: Sanaei Date: Thu, 12 Nov 2026 19:10:18 +0100 Subject: [PATCH 010/130] fix(xray): adopt freedom finalRules delay and logLevel xray-core 26.11.9 (#7329) renamed a final rule's blockDelay to delay, added logLevel, and now refuses either on a rule whose action is not block. A stored template with a blockDelay on an allow rule therefore stops the core at startup after the upgrade. A one-time seeder strips delay, blockDelay and logLevel from non-block rules of the template's freedom outbounds and moves blockDelay to delay on block rules. The outbound form reads both spellings (blockDelay wins, as in the core), writes delay, gains a log level control on block rules and emits neither key on an allow rule. --- .../src/lib/xray/outbound-form-adapter.ts | 16 ++- .../xray/outbounds/protocols/freedom.tsx | 34 ++++-- frontend/src/schemas/forms/outbound-form.ts | 8 +- .../src/schemas/protocols/outbound/freedom.ts | 3 + .../src/test/outbound-form-adapter.test.ts | 29 ++++- internal/database/db.go | 89 +++++++++++++++- ...freedom_final_rule_delay_migration_test.go | 100 ++++++++++++++++++ 7 files changed, 263 insertions(+), 16 deletions(-) create mode 100644 internal/database/freedom_final_rule_delay_migration_test.go diff --git a/frontend/src/lib/xray/outbound-form-adapter.ts b/frontend/src/lib/xray/outbound-form-adapter.ts index 41fdd1374..340fdb476 100644 --- a/frontend/src/lib/xray/outbound-form-adapter.ts +++ b/frontend/src/lib/xray/outbound-form-adapter.ts @@ -354,14 +354,23 @@ function freedomFromWire( network, port: asString(rr.port), ip: asArray(rr.ip).map((x) => asString(x)), - blockDelay: asString(rr.blockDelay), + // The deprecated blockDelay wins over delay, as it does in xray-core 26.11.9. + delay: asString(rr.blockDelay) || asString(rr.delay), + logLevel: asString(rr.logLevel), }; }); // Legacy ipsBlocked → finalRule(block) backfill if (finalRules.length === 0) { const ipsBlocked = asArray(raw.ipsBlocked).map((x) => asString(x)); if (ipsBlocked.length > 0) { - finalRules.push({ action: 'block', network: '', port: '', ip: ipsBlocked, blockDelay: '' }); + finalRules.push({ + action: 'block', + network: '', + port: '', + ip: ipsBlocked, + delay: '', + logLevel: '', + }); } } // Wire fragment is either missing or a populated object. Mirror the @@ -828,7 +837,8 @@ function freedomToWire(s: FreedomOutboundFormSettings) { network: r.network || undefined, port: r.port || undefined, ip: r.ip.length > 0 ? r.ip : undefined, - blockDelay: r.action === 'block' && r.blockDelay ? r.blockDelay : undefined, + delay: r.action === 'block' && r.delay ? r.delay : undefined, + logLevel: r.action === 'block' && r.logLevel ? r.logLevel : undefined, })) : undefined, }; diff --git a/frontend/src/pages/xray/outbounds/protocols/freedom.tsx b/frontend/src/pages/xray/outbounds/protocols/freedom.tsx index 5e4a7b253..d2d43da6b 100644 --- a/frontend/src/pages/xray/outbounds/protocols/freedom.tsx +++ b/frontend/src/pages/xray/outbounds/protocols/freedom.tsx @@ -6,6 +6,7 @@ import { useFieldArray, useFormContext, useWatch } from 'react-hook-form'; import { selectTagRender } from '@/components/form'; import { FormField } from '@/components/form/rhf'; +import { LOG_LEVELS } from '@/pages/xray/basics/constants'; import { activateOnKey } from '@/utils/a11y'; import { OutboundDomainStrategies } from '@/schemas/primitives'; @@ -220,7 +221,14 @@ export default function FreedomFields() { icon={} aria-label={t('add')} onClick={() => - appendFinalRule({ action: 'allow', network: '', port: '', ip: [], blockDelay: '' }) + appendFinalRule({ + action: 'allow', + network: '', + port: '', + ip: [], + delay: '', + logLevel: '', + }) } /> @@ -281,12 +289,24 @@ export default function FreedomFields() { /> {finalRulesValues[index]?.action === 'block' && ( - - - + <> + + + + + ({ value: s, label: s }))} onChange={(v) => mutate((tt) => { - if (tt.log) tt.log.loglevel = v; + if (!tt.log) return; + // The core reads either spelling, so keeping both would let the stale one win. + delete tt.log.loglevel; + tt.log.logLevel = v; }) } /> diff --git a/frontend/src/test/basics-log-level.test.tsx b/frontend/src/test/basics-log-level.test.tsx new file mode 100644 index 000000000..358d177e4 --- /dev/null +++ b/frontend/src/test/basics-log-level.test.tsx @@ -0,0 +1,34 @@ +import { describe, it, expect, vi } from 'vitest'; +import { fireEvent, screen } from '@testing-library/react'; + +import BasicsTab from '@/pages/xray/basics/BasicsTab'; +import type { XraySettingsValue } from '@/hooks/useXraySetting'; + +import { renderWithProviders } from './test-utils'; + +// xray-core 26.11.9 (#7329) spells the key log.logLevel and still reads loglevel. +describe('BasicsTab log level spelling', () => { + it('shows a template written as logLevel and saves one key, not both spellings', () => { + const setTemplateSettings = vi.fn(); + renderWithProviders( + , + ); + fireEvent.click(screen.getByRole('tab', { name: /Log/ })); + const combobox = screen.getByRole('combobox', { name: 'Log Level' }); + expect(combobox.closest('.ant-select')?.textContent).toContain('debug'); + + fireEvent.mouseDown(combobox); + fireEvent.click(screen.getByTitle('error')); + const update = setTemplateSettings.mock.calls.at(-1)?.[0] as ( + prev: XraySettingsValue, + ) => XraySettingsValue; + const legacy = { log: { loglevel: 'warning' } } as unknown as XraySettingsValue; + expect(update(legacy).log).toEqual({ logLevel: 'error' }); + }); +}); From 1d5a14bb62cbdda0c5c489603da0f3bfad86242b Mon Sep 17 00:00:00 2001 From: Sanaei Date: Thu, 12 Nov 2026 19:18:21 +0100 Subject: [PATCH 013/130] chore(deps): update go dependencies Move the modules that are not pinned by xray-core: quic-go v0.65.0, fasthttp v1.78.0, go-sqlite3 v1.14.53, klauspost/compress v1.20.4, gin-contrib gzip v1.2.10 / sessions v1.1.4 / sse v1.2.1, x/crypto v0.59.0 (back on a tagged release), x/sync v0.25.0, x/sys v0.50.0, x/text v0.44.0, x/arch v0.33.0, mongo-driver v2.10.0, purego, goupnp, go-ssdp, pion/transport, go-internal and genproto. Held back: pgx v5.13.0, x/exp and x509roots/fallback are less than a day old; apernet/quic-go, gvisor and xtls/reality move only with xray-core. --- go.mod | 38 ++++++++++++++--------------- go.sum | 76 +++++++++++++++++++++++++++++----------------------------- 2 files changed, 57 insertions(+), 57 deletions(-) diff --git a/go.mod b/go.mod index 604688e2d..4ba6a7bb9 100644 --- a/go.mod +++ b/go.mod @@ -5,8 +5,8 @@ go 1.27.4 require ( github.com/amnezia-vpn/amneziawg-go/v3 v3.1.20260828 github.com/apernet/quic-go v0.61.1-0.20260806010916-184d081eef3e - github.com/gin-contrib/gzip v1.2.9 - github.com/gin-contrib/sessions v1.1.3 + github.com/gin-contrib/gzip v1.2.10 + github.com/gin-contrib/sessions v1.1.4 github.com/gin-gonic/gin v1.12.0 github.com/go-ldap/ldap/v3 v3.4.15 github.com/go-playground/validator/v10 v10.30.6 @@ -16,25 +16,25 @@ require ( github.com/gorilla/websocket v1.5.3 github.com/jackc/pgx/v5 v5.12.0 github.com/joho/godotenv v1.5.1 - github.com/klauspost/compress v1.20.3 - github.com/mattn/go-sqlite3 v1.14.52 + github.com/klauspost/compress v1.20.4 + github.com/mattn/go-sqlite3 v1.14.53 github.com/mymmrac/telego v1.12.1 github.com/nicksnyder/go-i18n/v2 v2.7.0 github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 - github.com/quic-go/quic-go v0.64.1 + github.com/quic-go/quic-go v0.65.0 github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b github.com/robfig/cron/v3 v3.0.1 github.com/shirou/gopsutil/v4 v4.26.10 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e - github.com/valyala/fasthttp v1.77.0 + github.com/valyala/fasthttp v1.78.0 github.com/xlzd/gotp v0.1.0 github.com/xtls/xray-core v1.260327.1-0.20261109052709-676eaf66f8f0 go.uber.org/atomic v1.12.0 - golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2 + golang.org/x/crypto v0.59.0 golang.org/x/net v0.62.0 - golang.org/x/sync v0.24.0 - golang.org/x/sys v0.49.0 - golang.org/x/text v0.43.0 + golang.org/x/sync v0.25.0 + golang.org/x/sys v0.50.0 + golang.org/x/text v0.44.0 google.golang.org/grpc v1.86.0-dev google.golang.org/protobuf v1.36.12 gopkg.in/natefinch/lumberjack.v2 v2.2.1 @@ -51,9 +51,9 @@ require ( github.com/bytedance/sonic v1.15.5 // indirect github.com/bytedance/sonic/loader v0.5.3 // indirect github.com/cloudwego/base64x v0.1.7 // indirect - github.com/ebitengine/purego v0.11.2 // indirect + github.com/ebitengine/purego v0.11.3 // indirect github.com/gabriel-vasile/mimetype v1.4.16 // indirect - github.com/gin-contrib/sse v1.2.0 // indirect + github.com/gin-contrib/sse v1.2.1 // indirect github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-playground/locales v0.14.2 // indirect @@ -63,7 +63,7 @@ require ( github.com/gorilla/securecookie v1.1.2 // indirect github.com/gorilla/sessions v1.4.0 // indirect github.com/grbit/go-json v0.11.0 // indirect - github.com/huin/goupnp v1.3.0 // indirect + github.com/huin/goupnp v1.3.1 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect @@ -73,7 +73,7 @@ require ( github.com/json-iterator/go v1.1.12 // indirect github.com/juju/ratelimit v1.0.2 // indirect github.com/klauspost/cpuid/v2 v2.4.2 // indirect - github.com/koron/go-ssdp v0.9.1 // indirect + github.com/koron/go-ssdp v0.9.2 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/libp2p/go-nat v1.0.1-0.20250821073202-01afc089f138 // indirect github.com/libp2p/go-netroute v0.4.0 // indirect @@ -88,11 +88,11 @@ require ( github.com/pion/logging v0.2.4 // indirect github.com/pion/stun/v3 v3.1.7 // indirect github.com/pion/transport/v4 v4.1.3 // indirect - github.com/pion/transport/v5 v5.1.4 // indirect + github.com/pion/transport/v5 v5.1.5 // indirect github.com/pires/go-proxyproto v0.16.0 // indirect github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect github.com/quic-go/qpack v0.6.0 // indirect - github.com/rogpeppe/go-internal v1.15.0 // indirect + github.com/rogpeppe/go-internal v1.16.0 // indirect github.com/tklauser/go-sysconf v0.4.0 // indirect github.com/tklauser/numcpus v0.12.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect @@ -105,16 +105,16 @@ require ( github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b // indirect github.com/yuin/gopher-lua v1.1.2 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect - go.mongodb.org/mongo-driver/v2 v2.9.2 // indirect + go.mongodb.org/mongo-driver/v2 v2.10.0 // indirect go4.org/netipx v0.0.0-20260823151212-3075585bcbeb // indirect - golang.org/x/arch v0.32.0 // indirect + golang.org/x/arch v0.33.0 // indirect golang.org/x/crypto/x509roots/fallback v0.0.0-20261030153154-30a33513ff6d // indirect golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e // indirect golang.org/x/time v0.16.0 // indirect golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect golang.zx2c4.com/wireguard v0.0.0-20261024220952-b3bc704ef0ee // indirect golang.zx2c4.com/wireguard/windows v1.1.1 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect layeh.com/gopher-luar v1.0.11 // indirect lukechampine.com/blake3 v1.4.1 // indirect ) diff --git a/go.sum b/go.sum index c9a22a8fc..5551954d7 100644 --- a/go.sum +++ b/go.sum @@ -22,18 +22,18 @@ github.com/cloudwego/base64x v0.1.7/go.mod h1:Cu1PV9zfrSf7ET2tIbWbbEy7jO7HHJ13q4 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU= -github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg= +github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I= -github.com/gin-contrib/gzip v1.2.9 h1:MPyIubgLF/o5A4ni90weaQV0Oji7JTQto7QBVqWtmmY= -github.com/gin-contrib/gzip v1.2.9/go.mod h1:vLBq0o7y73JpE7m1pngAK/BPaVB7EU56R2gQP1yCgbo= -github.com/gin-contrib/sessions v1.1.3 h1:jTd6RietfxB/0brE36W6Q7XTl9die/gwD5orFZQZfh0= -github.com/gin-contrib/sessions v1.1.3/go.mod h1:4As481wI7g3rsRf6RnQYc0pS/IqBjp8vpz1Y4wudHek= -github.com/gin-contrib/sse v1.2.0 h1:AeYPE9hukQvAU1y7+eNvTC67PuBLK4BOduG08yv7L28= -github.com/gin-contrib/sse v1.2.0/go.mod h1:9ivB3pROCxcwnwHvAoYaHLwNQMGmzCjgriA04TuNIAc= +github.com/gin-contrib/gzip v1.2.10 h1:wHeVRAuhY5/CNXEo0gdto+Ajo5FEfKIX9GH15bkzxGs= +github.com/gin-contrib/gzip v1.2.10/go.mod h1:jDsAa3ADH+IKTOwF4HMtvw+mfXlKOaPjcSMOjykcOQ0= +github.com/gin-contrib/sessions v1.1.4 h1:Sa7J/IezGn+u5BuKfvCwDPhk9wbYjaoqj1h4txFOV5c= +github.com/gin-contrib/sessions v1.1.4/go.mod h1:ookhiYRLoBKVyGLB//uxOUUEm/5BW8K9c+9XElJ+Ffg= +github.com/gin-contrib/sse v1.2.1 h1:VAN6YEQlc6DbKmGYzSHZ72JWk5fp4gZaDwie4+bXx7s= +github.com/gin-contrib/sse v1.2.1/go.mod h1:9ivB3pROCxcwnwHvAoYaHLwNQMGmzCjgriA04TuNIAc= github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ= @@ -80,8 +80,8 @@ github.com/grbit/go-json v0.11.0 h1:bAbyMdYrYl/OjYsSqLH99N2DyQ291mHy726Mx+sYrnc= github.com/grbit/go-json v0.11.0/go.mod h1:IYpHsdybQ386+6g3VE6AXQ3uTGa5mquBme5/ZWmtzek= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc= -github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= +github.com/huin/goupnp v1.3.1 h1:n8259zVoE4BU7dBCQEUlwZK1h0Z3pxZ58ov0xbJuIQU= +github.com/huin/goupnp v1.3.1/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -114,12 +114,12 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI= github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk= -github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= -github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ= github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= -github.com/koron/go-ssdp v0.9.1 h1:zvxbAAuJftJIZ8Jh8mda+LI7V92hYZf/sKprmOxpxwA= -github.com/koron/go-ssdp v0.9.1/go.mod h1:C43c047jWkDaeg9YuZlSh/QGqOieuWV6dbhWi/jcaLk= +github.com/koron/go-ssdp v0.9.2 h1:s7YOSyV2Sch54U4+JGtiT+qgyUUKqbHbelgAV5PBCu0= +github.com/koron/go-ssdp v0.9.2/go.mod h1:AfRmwB0yUX/pCcB5dI7Z3947zo+sC3lXmqQOW8VO/TA= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -134,8 +134,8 @@ github.com/lufia/plan9stats v0.0.0-20261101121723-be84dd9509a0 h1:bGmNmV0W+HWMJy github.com/lufia/plan9stats v0.0.0-20261101121723-be84dd9509a0/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= -github.com/mattn/go-sqlite3 v1.14.52 h1:wVbm2Qnf4OXkqhBTSPuCRZDRnxfbVrrmiCEroVdog8U= -github.com/mattn/go-sqlite3 v1.14.52/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w= +github.com/mattn/go-sqlite3 v1.14.53 h1:mnTM0owzUMrKuLo+0w51NUiB0ir2Fo7kFXlPt/l3BGs= +github.com/mattn/go-sqlite3 v1.14.53/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w= github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -163,8 +163,8 @@ github.com/pion/stun/v3 v3.1.7 h1:uRXMTlGLf89WgItGNyZ6aR5jMTX0NBbybXADpQCzn+E= github.com/pion/stun/v3 v3.1.7/go.mod h1:Nq77RW4aRrSNrltf2ksUJLjxWeipj4lnlgdsYIxC8g8= github.com/pion/transport/v4 v4.1.3 h1:Qf6b/NJRn8J0yJK/Ac/qq9oY6XcKiWiLf9Kxsi0x05o= github.com/pion/transport/v4 v4.1.3/go.mod h1:Oxo5oODQvjFF7NkHBBz3f4fZXLB7x03uLVuzfYeA5pE= -github.com/pion/transport/v5 v5.1.4 h1:j0E5QIPyv28YnWxa8yE9AyDmrxVnwhZ109c7Dpt48K4= -github.com/pion/transport/v5 v5.1.4/go.mod h1:Qxw6fCEjFWQkRDZOhS4Vf+neJBcihauvA3uyEa1J1F0= +github.com/pion/transport/v5 v5.1.5 h1:73fa352Y9dq85kCd9rzyBV7wd/qhAiBIuTtwzWO3WS0= +github.com/pion/transport/v5 v5.1.5/go.mod h1:Qxw6fCEjFWQkRDZOhS4Vf+neJBcihauvA3uyEa1J1F0= github.com/pires/go-proxyproto v0.16.0 h1:9KYT/fM3wpjT8bdMEj/7FBcoiUG1KyzEjRYnPu+vz7A= github.com/pires/go-proxyproto v0.16.0/go.mod h1:n7yhg8yIfNl3KgYDCwBzmeUHNpKTVnUhcWpc7rV4RW4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -174,14 +174,14 @@ github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4 github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= -github.com/quic-go/quic-go v0.64.1 h1:BCNTP+6x6++OPKrGST2FR3f1tycx8O3QOA3QQv09g70= -github.com/quic-go/quic-go v0.64.1/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w= +github.com/quic-go/quic-go v0.65.0 h1:BJQSjdTvLPLmWtaCupUphRbgxgpZhdO/GMpr9Eoe3B4= +github.com/quic-go/quic-go v0.65.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w= github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b h1:Mi/DuaTxHeNIQ9g1ylZicAqa6Cb9wkHRiNtQH9uZ7Ts= github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b/go.mod h1:rc/ctWeKlh9LSk5k90KlSPcwF7P6D31mn/9GI2NAfBI= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= -github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc= -github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= +github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= +github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= github.com/shirou/gopsutil/v4 v4.26.10 h1:MJN6euesJx53MVEjscYeyRSRcrdIcy3sz5k9nosjldg= github.com/shirou/gopsutil/v4 v4.26.10/go.mod h1:XpkIrcUMQhwte/dGxu57KtnMMFsbKelI7PP23zweKBk= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= @@ -208,8 +208,8 @@ github.com/ugorji/go/codec v1.3.2 h1:zkEASHHyEClGeURfgNT9PJZVfAbs9oEX9QXggwWNJbc github.com/ugorji/go/codec v1.3.2/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.77.0 h1:6mxBJdHabRmU4Cmw79Uqhgvjzsp6pjOaQk2t8COflzo= -github.com/valyala/fasthttp v1.77.0/go.mod h1:m8oTPC8riDDky07invpl+Gz3RixnAN5BbwyUuVB5H2o= +github.com/valyala/fasthttp v1.78.0 h1:tKfLdx7cD8HZOTP1wc2OpbQMbgO1HP12J0y/XMdyW6Q= +github.com/valyala/fasthttp v1.78.0/go.mod h1:8NXUY/ZXyjqEWN5cbfIdAAv+ES+5yfcl2EGNo872KzQ= github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4= github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE= github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0= @@ -229,8 +229,8 @@ github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= -go.mongodb.org/mongo-driver/v2 v2.9.2 h1:OCAdjI37pC/SVxucz/9CM8zD4jCdegtsY5QcKzYFCgE= -go.mongodb.org/mongo-driver/v2 v2.9.2/go.mod h1:SHKN0IWkKmEVGHLjXnni6s4wPKX4v86FTgOeJJFuXcA= +go.mongodb.org/mongo-driver/v2 v2.10.0 h1:BYJLuVSu3/xDvToG+VQyoTPS+jxq9tuQDf+1nAlFKSE= +go.mongodb.org/mongo-driver/v2 v2.10.0/go.mod h1:PxPyIAlsI1jkYZvUNfTr++ggyBP+RSaxHYctt6TcZc4= go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= @@ -239,10 +239,10 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go4.org/netipx v0.0.0-20260823151212-3075585bcbeb h1:XBM4hvfwGAttkkiTIFfeigdfcL1xIfdKXqFdgiHGtDs= go4.org/netipx v0.0.0-20260823151212-3075585bcbeb/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y= -golang.org/x/arch v0.32.0 h1:NjGf8/xGf5JgAJ4dw4NtME5R1L7xatagqAg95T3LgII= -golang.org/x/arch v0.32.0/go.mod h1:KcJSod3cqT2dKcjBxqTyGfbumNikqU9p5tHJinPJnuY= -golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2 h1:zGDaB+/Mus2mScKvZ23k+W9NAUbP56sNM9SptgvWI5A= -golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/arch v0.33.0 h1:Xhs4e8nHj/CU/eFFMok2wQG3amA8430Sjdobboa4NrM= +golang.org/x/arch v0.33.0/go.mod h1:yelN722/RE0EdL5KBgAqvVqP++p/dn8sL4UaLD8n8As= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/crypto/x509roots/fallback v0.0.0-20261030153154-30a33513ff6d h1:5NBkmd8MXirajj6AAEpi4HFVJnVkBNPTL1ggYAKqaws= golang.org/x/crypto/x509roots/fallback v0.0.0-20261030153154-30a33513ff6d/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E= golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A= @@ -250,18 +250,18 @@ golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/Ye golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= -golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= -golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= -golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= @@ -274,8 +274,8 @@ golang.zx2c4.com/wireguard/windows v1.1.1 h1:8/H97U1v1PNDNcBsMZgU3KFuND9MQdTsU2N golang.zx2c4.com/wireguard/windows v1.1.1/go.mod h1:+fbT3FFdX4zzYDLwJh5+HPEcNN/3HyNdzhNSVsQM+zs= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e h1:w3fy/G8OrJHYexn+u5y7hFyc8YRRIr7DCevtIOwAcGY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c h1:XXChExL+Tm7Ubp0x0VXUEncPLHrkXIgoVWqnxmKNbAA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.86.0-dev h1:FLq7hcApuJeJ70J9+k0FvmXsNCwS8B2/MeAfYdy3GHY= google.golang.org/grpc v1.86.0-dev/go.mod h1:Ovl0ECo4xx5r4kn/6d4BPSNB7OIFuu6EAjOzjtVAKaM= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= From 0abbe1a4af06c41e483aa9830529492c66d93a18 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Thu, 12 Nov 2026 19:26:56 +0100 Subject: [PATCH 014/130] chore(deps): update frontend dependencies Majors: i18next 26 -> 27.1.1 with react-i18next 17 -> 18.0.1, and jsdom 30 -> 31. The vitest group moves together to 5.1.0 (vitest, coverage-v8, browser-playwright and the addon-vitest override). Also antd 6.7.0, storybook 10.6.7, vite 8.3.8, @vitejs/plugin-react 6.3.0, react-query 5.107.1, react-hook-form 7.92.0, msw 3.0.5, playwright 1.65.0, otpauth 9.6.0 and oxfmt 0.78.0. i18next 27 dropped interpolation.nestingPrefixEscaped, the option that kept "$t(...)" nesting from ever matching, and an empty nestingPrefix falls back to "$t(". The prefix is now a NUL character, which no translation or node-reported text contains; node-list-untrusted-i18n.test.tsx goes red without it. Held back: oxlint stays at 1.90.0, because 1.91 and later flag six fetch-in-effect loaders with react(set-state-in-effect) and those need a data-loading rewrite of their own. @hookform/resolvers 7.0.6 and oxlint-tsgolint 7.0.2007 are less than a day old, so 7.0.5 and 7.0.2006 are locked; the lockfile was resolved with a one-day cutoff. --- frontend/package-lock.json | 2282 ++++++++++++++++++------------------ frontend/package.json | 52 +- frontend/src/i18n/react.ts | 7 +- 3 files changed, 1152 insertions(+), 1189 deletions(-) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f315d85e8..6a37d6a79 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -11,50 +11,50 @@ "@ant-design/icons": "^6.3.4", "@codemirror/lang-json": "^6.0.2", "@codemirror/theme-one-dark": "^6.1.3", - "@hookform/resolvers": "^7.0.1", + "@hookform/resolvers": "^7.0.5", "@noble/hashes": "^2.4.0", - "@tanstack/react-query": "^5.105.1", - "@tanstack/react-query-devtools": "^5.105.1", - "antd": "^6.6.8", + "@tanstack/react-query": "^5.107.1", + "@tanstack/react-query-devtools": "^5.107.1", + "antd": "^6.7.0", "codemirror": "^6.0.2", "dayjs": "^1.11.23", - "i18next": "^26.6.0", - "otpauth": "^9.5.2", + "i18next": "^27.1.1", + "otpauth": "^9.6.0", "persian-calendar-suite": "^1.5.6", "react": "^19.3.1", "react-dom": "^19.3.1", - "react-hook-form": "^7.91.0", - "react-i18next": "^17.1.10", + "react-hook-form": "^7.92.0", + "react-i18next": "^18.0.1", "react-router": "^8.5.1", "swagger-ui-react": "^5.34.1", "uplot": "^1.6.32", "zod": "^4.6.7" }, "devDependencies": { - "@storybook/addon-a11y": "^10.6.5", - "@storybook/addon-docs": "^10.6.5", - "@storybook/addon-vitest": "^10.6.5", - "@storybook/react-vite": "^10.6.5", + "@storybook/addon-a11y": "^10.6.7", + "@storybook/addon-docs": "^10.6.7", + "@storybook/addon-vitest": "^10.6.7", + "@storybook/react-vite": "^10.6.7", "@testing-library/dom": "^10.4.2", "@testing-library/react": "^16.3.3", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "@types/swagger-ui-react": "^5.18.0", - "@vitejs/plugin-react": "^6.1.2", - "@vitest/browser-playwright": "5.0.5", - "@vitest/coverage-v8": "^5.0.5", + "@vitejs/plugin-react": "^6.3.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/coverage-v8": "^5.1.0", "husky": "^9.1.7", - "jsdom": "^30.1.3", + "jsdom": "^31.0.0", "lint-staged": "^17.6.0", - "msw": "^3.0.3", - "oxfmt": "0.75.0", + "msw": "^3.0.5", + "oxfmt": "0.78.0", "oxlint": "1.90.0", - "oxlint-tsgolint": "^7.0.2005", - "playwright": "^1.64.1", - "storybook": "^10.6.5", + "oxlint-tsgolint": "^7.0.2006", + "playwright": "^1.65.0", + "storybook": "^10.6.7", "typescript": "7.0.2", - "vite": "8.3.5", - "vitest": "^5.0.5" + "vite": "8.3.8", + "vitest": "^5.1.0" }, "engines": { "node": ">=26.0.0", @@ -161,39 +161,6 @@ "react-dom": "^0.14.0 || ^15.0.1 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, - "node_modules/@asamuzakjp/css-color": { - "version": "7.1.9", - "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.9.tgz", - "integrity": "sha512-vZ6JQVq8Ivgz6b/IBlAf90wZviXdluY13cQOPO+nJHbmXwGrPl2GcpqUY7a55/8ZVdfONXpCFMpRijOBCHNlcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@csstools/css-calc": "^3.4.3", - "@csstools/css-color-parser": "^4.2.6", - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2", - "lru-cache": "^11.5.3" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, - "node_modules/@asamuzakjp/dom-selector": { - "version": "10.0.5", - "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-10.0.5.tgz", - "integrity": "sha512-EgmJ7oEaGQECTn3H3wmnQpEy4hKY66VvM7VQndwPIQob3p877BgbyOUE3EX0LgXQCciF2H8KMdR+RznqjMNOLw==", - "dev": true, - "license": "MIT", - "dependencies": { - "bidi-js": "^1.1.0", - "css-tree": "^3.2.1", - "is-potential-custom-element-name": "^1.0.1", - "lru-cache": "^11.5.3" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", @@ -220,21 +187,21 @@ } }, "node_modules/@babel/core": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", - "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", "dev": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helpers": "^7.29.7", - "@babel/parser": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", @@ -251,13 +218,13 @@ } }, "node_modules/@babel/generator": { - "version": "7.29.12", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.12.tgz", - "integrity": "sha512-2W76mhjrpQFO1lK5e8IvGYB2D0YZ7S2R1Z2BjO2ZUYuW+amcpK/z60U6ZZmzskwoa7sJ6XohP/Wg8H5KxXI/IA==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.13.tgz", + "integrity": "sha512-T5FRo+RzVHvGjWOuF1Ljc44b+NXAOazodHkGUHp4I3zCkQ4/sNVJm56h1S278LMR0bY5xBhztGziSbli8zObIw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^7.29.12", + "@babel/parser": "^7.29.13", "@babel/types": "^7.29.11", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", @@ -268,9 +235,9 @@ } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", - "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", "dev": true, "license": "MIT", "dependencies": { @@ -319,15 +286,15 @@ } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", - "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.13.tgz", + "integrity": "sha512-/U96wOz+SCoZ7Da/8kjDGltcNY280JPQcRNPK0Hk3PTbdpaiBDQImtC6JsbVwb1HGMr3usZQU2WsWVjhYNmRzw==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", - "@babel/traverse": "^7.29.7" + "@babel/traverse": "^7.29.13" }, "engines": { "node": ">=6.9.0" @@ -337,9 +304,9 @@ } }, "node_modules/@babel/helper-string-parser": { - "version": "7.29.11", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.11.tgz", - "integrity": "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.13.tgz", + "integrity": "sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ==", "dev": true, "license": "MIT", "engines": { @@ -367,23 +334,23 @@ } }, "node_modules/@babel/helpers": { - "version": "7.29.10", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.10.tgz", - "integrity": "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.13.tgz", + "integrity": "sha512-laoRpD/kO/iA4CDlgJbixHekg7oPvWALK0PQyK3Ob2I2njZRvVAD77RfWCIImtqWCq6KijoBoZK7bp/HlTWASQ==", "dev": true, "license": "MIT", "dependencies": { "@babel/template": "^7.29.7", - "@babel/types": "^7.29.8" + "@babel/types": "^7.29.11" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.29.12", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.12.tgz", - "integrity": "sha512-WJ7JBp/Q4+z/ImydtI7jS6NVco5++632ExBemSX+Ysb+G1lCwQ5BVo3SY+jGGOcZXI4ZccbZSUSJLNBW6eEpJg==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.13.tgz", + "integrity": "sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ==", "dev": true, "license": "MIT", "dependencies": { @@ -397,18 +364,18 @@ } }, "node_modules/@babel/runtime": { - "version": "7.29.10", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", - "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.13.tgz", + "integrity": "sha512-v+oN26xP4YIlQsbQ/CbTH1WG5m/l/DjKKZNy/Kp3f/AFvbgt7Em/D0FeMM3O2hX0YzeN2M16W8lOpyhIkfCBcQ==", "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/runtime-corejs3": { - "version": "7.29.10", - "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.29.10.tgz", - "integrity": "sha512-R4FKrg4Vy0hB7PfAxf9LOorEPd5/36SCIXPXAvjlQaQmPvtrjwoDXV15jsSm2ecsqBW1Iewwb7mEnG83xIEApg==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.29.13.tgz", + "integrity": "sha512-vz2jdupHNmzH+i7E6u6Np8dKWMwp+P9R8lbjXerbD4YcaHa+Jc2rmSR8MhMfXpHZYcwZ28Wq0LsbcLf50TglIw==", "license": "MIT", "dependencies": { "core-js-pure": "^3.48.0" @@ -433,16 +400,16 @@ } }, "node_modules/@babel/traverse": { - "version": "7.29.12", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.12.tgz", - "integrity": "sha512-MscXe/NAZcOkYEsRajHZFt3ynsb22PUi6CTrp5U7+RYycR9By84mn9mFN54YgfITiqK4hFx3Ju3tZSyzfpS5ew==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.13.tgz", + "integrity": "sha512-0ve0xMlFA73dgY1oyJRY6RoW+/bncdcOQqg6jjYcVfXBK90OdLXjm9R6lmRetdZVrPjXkKIoMVBqYFPjcAlZ4Q==", "dev": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.12", + "@babel/generator": "^7.29.13", "@babel/helper-globals": "^7.29.7", - "@babel/parser": "^7.29.12", + "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", "@babel/types": "^7.29.11", "debug": "^4.3.1" @@ -482,19 +449,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@bramus/specificity": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", - "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", - "dev": true, - "license": "MIT", - "dependencies": { - "css-tree": "^3.2.1" - }, - "bin": { - "specificity": "bin/cli.js" - } - }, "node_modules/@codemirror/autocomplete": { "version": "6.20.4", "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz", @@ -617,146 +571,6 @@ "solid-js": "^1.8" } }, - "node_modules/@csstools/color-helpers": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", - "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT-0", - "engines": { - "node": ">=20.19.0" - } - }, - "node_modules/@csstools/css-calc": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", - "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-color-parser": { - "version": "4.2.7", - "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.7.tgz", - "integrity": "sha512-zgm9yjQz5iJB4VL8RyVwd71TWB8Q89FSxt/NzXoWqPSkEBOVtn9L6vAPtSc9hpKfB0Awo/AL2VKFHjYetBLFHQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "dependencies": { - "@csstools/color-helpers": "^6.1.2", - "@csstools/css-calc": "^3.4.3" - }, - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-parser-algorithms": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", - "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-syntax-patches-for-csstree": { - "version": "1.1.16", - "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.16.tgz", - "integrity": "sha512-LsDbJPP/B8cPasUJyTA5S99F7C4G93ngW8hUluXz8CFeOaaRnBPtBiIlvgcPYU0HmHNz8CXg+1vwFrIB4F6Dgw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT-0", - "peerDependencies": { - "css-tree": "^3.2.1" - }, - "peerDependenciesMeta": { - "css-tree": { - "optional": true - } - } - }, - "node_modules/@csstools/css-tokenizer": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", - "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - } - }, "node_modules/@emnapi/core": { "version": "1.9.2", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz", @@ -1289,9 +1103,9 @@ "license": "MIT" }, "node_modules/@hookform/resolvers": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-7.0.1.tgz", - "integrity": "sha512-F3aM0dDWsRGmFjnnXjogaGLwP7gY2HA6/c5qp4v4Im/UV7pTNkX+WAjcOlM1V0PE0zoMzuPqCyaYtMzUhoFToA==", + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-7.0.5.tgz", + "integrity": "sha512-E7ca3tpIJxHPGhFOfXLlCCZh7up6EcnUTbgTt0SRUENXagq8DJnob9rK+VqsNCsfUuO6mMU5NYNm6BaL18flgQ==", "license": "MIT", "dependencies": { "@standard-schema/utils": "^0.3.0" @@ -1301,7 +1115,7 @@ "@vinejs/vine": "^2.0.0 || ^3.0.0 || ^4.0.0", "ajv": "^8.12.0", "ajv-errors": "^3.0.0", - "ajv-formats": "^2.1.1", + "ajv-formats": "^2.1.1 || ^3.0.0", "arktype": "^2.0.0", "ata-validator": "^1.23.0", "class-transformer": ">=0.4.0", @@ -1395,27 +1209,27 @@ } }, "node_modules/@inquirer/ansi": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.10.tgz", - "integrity": "sha512-dwrc+1aqVZpHNkNDswXGtn1typ+Pxpo5FHZRyBw1le7onEJUkPUkYOY1FIFC1LvFMYUqqLuWBwElhAmencL7MQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.1.0.tgz", + "integrity": "sha512-63GU5AD9KhNbWM0jlhHoMJTEFck2upFOPxHlnCKf3xYTV3rjTUUQfodihmTnfYQzMLS29oy8lK/gA1eJgu4bhA==", "dev": true, "license": "MIT", "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/@inquirer/confirm": { - "version": "6.3.5", - "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.3.5.tgz", - "integrity": "sha512-BJ59BOyURiZiAxdr9AuRu38/k+rV+DcTIM2fUF/c/BXrab6H8zMZTTOl3LgkSJH96Xob2vOJxDiBkHiz32Xx2w==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.4.0.tgz", + "integrity": "sha512-+DCZxrOF01Q/1SzTQkgycAQPS/Jf+Yol0h1P/MVmopukTsxGOu1h/LKqf30y0eHKFZYYrgUMVhGDhEbPmSPi9A==", "dev": true, "license": "MIT", "dependencies": { - "@inquirer/core": "^12.0.6", - "@inquirer/type": "4.2.1" + "@inquirer/core": "^12.1.0", + "@inquirer/type": "4.3.0" }, "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "peerDependencies": { "@types/node": ">=18" @@ -1427,22 +1241,22 @@ } }, "node_modules/@inquirer/core": { - "version": "12.0.6", - "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.0.6.tgz", - "integrity": "sha512-5yxn2LsJ8Tu4ei2a+yNkmFRhM/cb+JMEsEs/AW6CCOnBnpMy4IjYiPMFyHtYq8weOmlTyqqCx40y0DsD7OsEPw==", + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.1.0.tgz", + "integrity": "sha512-6H7usRWw4Gdjgpaem10CA5MfZ/xoYPGyInriR1Xubqjv+SVo8LIJ1erpFxW5JgCza6VZVZiKLTko7RtUU3AQMg==", "dev": true, "license": "MIT", "dependencies": { - "@inquirer/ansi": "^2.0.10", - "@inquirer/figures": "^2.0.10", - "@inquirer/type": "4.2.1", + "@inquirer/ansi": "^2.1.0", + "@inquirer/figures": "^2.1.0", + "@inquirer/type": "4.3.0", "cli-width": "^4.1.0", "fast-wrap-ansi": "^0.2.0", - "mute-stream": "^3.0.0", + "mute-stream": "^4.0.0", "signal-exit": "^4.1.0" }, "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "peerDependencies": { "@types/node": ">=18" @@ -1454,23 +1268,23 @@ } }, "node_modules/@inquirer/figures": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.10.tgz", - "integrity": "sha512-51elrUJV3jZpvD0ygz8+U10Kc6+Lzqln+/tYmnbhy6jo5oXpE6hMCcv+OTBC0enwJXsb3JIuT3VtEinRNCSK2A==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.1.0.tgz", + "integrity": "sha512-CR9u2PME23jxy2SOyTb117efwAAPm98Zr+LoWI+PiQ55D6U8Yeu/HyFTxwytKhPa6oxAGzdsm2Kg7oLS6B9z8w==", "dev": true, "license": "MIT", "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/@inquirer/type": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", - "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.3.0.tgz", + "integrity": "sha512-/IA8q2nyjgyl0NGSjqiRXB8gh3We7Pzx9C0c+6Zoolu905jFc79anerrUG7+n65+qs310DRK43yi2WDI8nY59A==", "dev": true, "license": "MIT", "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "peerDependencies": { "@types/node": ">=18" @@ -1491,9 +1305,9 @@ } }, "node_modules/@isaacs/nonrecursive-glob-match": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.0.3.tgz", - "integrity": "sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", "license": "BlueOak-1.0.0" }, "node_modules/@joshwooding/vite-plugin-react-docgen-typescript": { @@ -1669,9 +1483,9 @@ "license": "MIT" }, "node_modules/@mswjs/interceptors": { - "version": "0.45.11", - "resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.45.11.tgz", - "integrity": "sha512-+ISPERIRIHhSVnFQRGCP9jDJXxn0/z2+pWWbXUym6JUfpUCRW2Pvro4P9RBKGYUKTKAULszKurKMTQIsaJUIgQ==", + "version": "0.45.12", + "resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.45.12.tgz", + "integrity": "sha512-LLttQ/SSmseGFD/sNiHv9q34hd4gmPLN9uQdIIsU/V/o2AgTJm3dWoKHA4KTj0BzAans6CoEmpHYmp80yp69VA==", "dev": true, "license": "MIT", "dependencies": { @@ -1687,9 +1501,9 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", - "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", + "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", "dev": true, "license": "MIT", "optional": true, @@ -1704,8 +1518,8 @@ "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", - "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" } }, "node_modules/@noble/hashes": { @@ -2436,9 +2250,9 @@ ] }, "node_modules/@oxfmt/binding-android-arm-eabi": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.75.0.tgz", - "integrity": "sha512-zHJ7LcTN46/5mtoLxsUu14pdF9ixFwDURtmxZ0CeNwqom5qB5NRVqU6o2GRZ7QPdNBW8G6j9UTJzQ+EDevMH0w==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.78.0.tgz", + "integrity": "sha512-1x9NPGQG5WMOOT8spRP4hPbeqwB/P9ayxFo4EUDSle6mLmtYRqE6suXgHr93/S2nnszy77LlIa8klkKdWtHbMw==", "cpu": [ "arm" ], @@ -2453,9 +2267,9 @@ } }, "node_modules/@oxfmt/binding-android-arm64": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.75.0.tgz", - "integrity": "sha512-IdxsKZJvHZUvI7q6kLmzXdEFpFiBEDQw/WJtSp1QlzNXBw1JlLN3tY50WwWd4doPnq86XW4P+7BsQwu6meCW+w==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.78.0.tgz", + "integrity": "sha512-1muYaW9SiPEq8NIPGX0B20oUwCx6HWiCsZem/2jU7UsOzoXLT4YxWq6ybdhwKSKl0PyAfvyMyPF7FsI1To7AdA==", "cpu": [ "arm64" ], @@ -2470,9 +2284,9 @@ } }, "node_modules/@oxfmt/binding-darwin-arm64": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.75.0.tgz", - "integrity": "sha512-vyiqZilO5jal/nXZ0143NyKcP6TkzjaQdVEWU/kwgyWqugAgIRgAbrnO3MOF+e6LkQu3CrtrkPoc3mrsZZY6cA==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.78.0.tgz", + "integrity": "sha512-jl4KJdo8HrVpLmcSYS/7oDXPH8Hzd6VrzgUFRAbY0j6cSRjcDkUnpuAStuNLoqvMtZEi7Rdy68BBriCgWJcy2g==", "cpu": [ "arm64" ], @@ -2487,9 +2301,9 @@ } }, "node_modules/@oxfmt/binding-darwin-x64": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.75.0.tgz", - "integrity": "sha512-oua7eVqVe769mDam6ORcavygxTzG3ovo5QRQ1kJCPaEbnWXPYhtAiYDj8pajVmFjO7j8Elf3gInnWpTX0LLYtg==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.78.0.tgz", + "integrity": "sha512-RwOhQgAQi1qV3TeuTfrgGkCWEL3eDFIql/lo4rt2xpGHqyolKa+W5cFbb+M9IvwMwQbplii5Gbv1ZQQPTJlNug==", "cpu": [ "x64" ], @@ -2504,9 +2318,9 @@ } }, "node_modules/@oxfmt/binding-freebsd-x64": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.75.0.tgz", - "integrity": "sha512-NWkbezhg7mx2Ep94g/TysR3c1bsISsU4lQ6t5xI4841PAk0Kqcn1+UEe+BoFH2/UK2YegPXq+OF+0bUcSvUalA==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.78.0.tgz", + "integrity": "sha512-MAXydj01mLjMUlnmo7sYVm+7kdBdU9Nwaux2Q1f9oLNqt3CCdego1oMoZ30qDyZQGQXfVJZEU1yRV7mSzwKDVA==", "cpu": [ "x64" ], @@ -2521,9 +2335,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.75.0.tgz", - "integrity": "sha512-CAHX87kJplTq2E0OWP7opG8gEVlHc7CeLEi4nMJOyx3psuqBKf84HZ3UIkX2guWEJ5UljU2zJF0o46XylywVVA==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.78.0.tgz", + "integrity": "sha512-rz6FVZRiWsq3O2YQgCoqZRwaQQaPQ70NBks4+KINjjPJOjBTd8g/iq6ynS97ode+qKGlhXtpc/xCl8LHzfOjyQ==", "cpu": [ "arm" ], @@ -2538,9 +2352,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm-musleabihf": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.75.0.tgz", - "integrity": "sha512-jmxYOiQzx2fp+OwQb7717K1zI8AMKEykw04sfr95/mU8SIL/oKgQq8nXH42sEznEquBL2RU7nLY36eBnYFT+vg==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.78.0.tgz", + "integrity": "sha512-lIK0XJi4JP1FnhuLjR/JWhQHGghZc+ghFNnbZTQC8kxsmrkW3ex8CeF7fp0FT+rEP0Nm6voCYkasL8poVWA9sQ==", "cpu": [ "arm" ], @@ -2555,9 +2369,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-gnu": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.75.0.tgz", - "integrity": "sha512-eimaiAhx08dbOg12Fj3PYhymXY8vRbaiJB505vDXMy6ohne3Y1qTS0e5KEwFMq3LmDjEO+16BX38c/oXFI/SAQ==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.78.0.tgz", + "integrity": "sha512-o2LJIHfW3ZADOjDVk5c7MM1M8CiAG43GTc4mlJAK23fOHgru4CvnqWedCoCXpIsKokoRdEa7XdQywPGZv1BAiA==", "cpu": [ "arm64" ], @@ -2575,9 +2389,9 @@ } }, "node_modules/@oxfmt/binding-linux-arm64-musl": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.75.0.tgz", - "integrity": "sha512-bjSONIG1ba2xugr9oHQau0E6oPFYOMjPaa5hK/wpVC/Q1pcgf2BZMKwbuA8/cWzhWX5QV/UdPzD+rw1kQHpikQ==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.78.0.tgz", + "integrity": "sha512-G+lUaQk94Vo+4byyd8X2+pPXtd7wObpdbvBC8xyozZD0ROSVBI3XpNNR6HECkJq4Q51AwLuJG81f4x+4eqvSrw==", "cpu": [ "arm64" ], @@ -2595,9 +2409,9 @@ } }, "node_modules/@oxfmt/binding-linux-ppc64-gnu": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.75.0.tgz", - "integrity": "sha512-wDksWQXC/KZucISyqlhBtvpW+pyHh8z0Cjm6Qxiv22XlllM2Bx5gJGDnPYjV+H0lL+o1iqLlEli8jmBuRCLcjw==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.78.0.tgz", + "integrity": "sha512-r76PAZf9/ZgF/iDRaIf8nLsr4x6ZHe/j2QLmWUjoQ46Sa11qMO68a5u5iux3y8vLzqYTS/xtKO9PjjMfyk5png==", "cpu": [ "ppc64" ], @@ -2615,9 +2429,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-gnu": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.75.0.tgz", - "integrity": "sha512-5JkNwViqaVuk4I+9+zgVrEYiHOAPXFxgDgP6iDnpdOBjm7XAHAOjSvolHZZAokWPx7CGOw8tKteXmn4WPIInaQ==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.78.0.tgz", + "integrity": "sha512-SQiXTt/c4aVoRXkJvhf4Y/sA1XYe3XjSMDbdX5PiAssBuHERoGtncQXz0KKWkXPejWTKlAL4mZSQZdHOCiw7TA==", "cpu": [ "riscv64" ], @@ -2635,9 +2449,9 @@ } }, "node_modules/@oxfmt/binding-linux-riscv64-musl": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.75.0.tgz", - "integrity": "sha512-1EVqRIE0eZLB08j3ZCVN47Ors7LCXGmOI+3xJYgyoFUKUerD3Glxb+Q1Bp3lK8NeT5R3ZdS9uhX/wobNBYZ6jw==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.78.0.tgz", + "integrity": "sha512-VNB3wFUx/rAqwVNW+uyXxb+c0HUrmcS51UPkFMDWJY95c6Tck6u6HOyVLsqiYoC8kh2mGlwanYmjb/R2McvN0A==", "cpu": [ "riscv64" ], @@ -2655,9 +2469,9 @@ } }, "node_modules/@oxfmt/binding-linux-s390x-gnu": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.75.0.tgz", - "integrity": "sha512-UJWRVNT6Yuw4ssLv2BwaBUWU1GWtByE+EnoHu8I+P1t8Kn+WozYU5WYOqb5aj8gbXJJ8gGZt+w40Hi/7L6iVLw==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.78.0.tgz", + "integrity": "sha512-1nbI0Y7SXwx2f4mJmKt58MaDdjAcoaYM90pBMGdcZCsTW2taFW1/MUi3uQGRPAN2n+3PldCdO9m+D6x+gU/heg==", "cpu": [ "s390x" ], @@ -2675,9 +2489,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-gnu": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.75.0.tgz", - "integrity": "sha512-FHdvHhyz8ChBctBUvVGti49kSEwANd1PZQwlXUEoF9Ed4plxXxk/wWc0mfZmrze2lRgmME7ytDmVIOixYauQhg==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.78.0.tgz", + "integrity": "sha512-I2z2ISPjrl3CSRF5fmQkNnoh46UVU1GjM1V0+COJyNZcj0SDNM4DrPP2/gXCX38YJ1P2BL6sF2VdsJ+pEYEbJQ==", "cpu": [ "x64" ], @@ -2695,9 +2509,9 @@ } }, "node_modules/@oxfmt/binding-linux-x64-musl": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.75.0.tgz", - "integrity": "sha512-6MjtsF96s9mSBV0GEwUe4pOFPP2Mz7ahcHPAit0DSKL5fM6oMM7RG1zvYxwB7+SBkIxsWBRhhxuqmy7pibNwsA==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.78.0.tgz", + "integrity": "sha512-YHt5nKKFxT4SruI57FHnEhGRSDuoFqNoAM3moYCClg70mjjS39gBBbdzaZv+N0otdzvQVuHTPu3jFu5tpqC3XQ==", "cpu": [ "x64" ], @@ -2715,9 +2529,9 @@ } }, "node_modules/@oxfmt/binding-openharmony-arm64": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.75.0.tgz", - "integrity": "sha512-1D6T6aL1Pj+U5GLxqwV1fKjUJ5+FFm+bn7UrqNDMveZmWs0jo/3vc+dzzuV/jF/FdVo12gowODk3SnAO2YOwLg==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.78.0.tgz", + "integrity": "sha512-WH21lBMU+LYzF7aMeozTZlyc44oa2F+I5OtQ7RwuidCDoAxgTyN1s34rx0PBYrio56+2G88U9VOnYJsyV7VMHQ==", "cpu": [ "arm64" ], @@ -2732,9 +2546,9 @@ } }, "node_modules/@oxfmt/binding-win32-arm64-msvc": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.75.0.tgz", - "integrity": "sha512-RX2eUmy7J/nM8+tnM3nzR8t1eqkwj1q8Kgo7beA+4DVgKYYHHyrEa3qEmthxw7Z+HqpCCEOWuoqa+jelo9/w2Q==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.78.0.tgz", + "integrity": "sha512-uNQqHJrtHIiSl8pMbhDktmGpA1hqwldWNO8kbNpNFhVt+BYk4C3Ge8nlJgkRtGjtMam0+542G5UQJJG6lLePbg==", "cpu": [ "arm64" ], @@ -2749,9 +2563,9 @@ } }, "node_modules/@oxfmt/binding-win32-ia32-msvc": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.75.0.tgz", - "integrity": "sha512-UpKta0iSZmPLII0dYXYdbzdBTsGREUbSHLqgLdtKcqBvs40qjmUz+cgUcaU1smPx13DfbEG4XqnaSn5MoFN0og==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.78.0.tgz", + "integrity": "sha512-W6omURRT39EHBPH4Z8sUPIOzWVjMbhCCCWcfT0sa6aeC+vOXNyBAJmpQRh5//KfPDX96jJlNith9i4N65wxB+Q==", "cpu": [ "ia32" ], @@ -2766,9 +2580,9 @@ } }, "node_modules/@oxfmt/binding-win32-x64-msvc": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.75.0.tgz", - "integrity": "sha512-pjiLiCk0QMCWxs0n5XiNU85YLAKA+wJxPjxlDVygmr4bP4glcfTU2nOpso5nR4Rdi2Pxv5YwakD4UE+eh7M0BQ==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.78.0.tgz", + "integrity": "sha512-r9rWKeDVc7lIrj0Us9kP08W7FudYAoWyEdO40qnKk20bHiTbW/z2v4LoIxxUENQyFfApbeV2Gl9XsEgY/tY1dA==", "cpu": [ "x64" ], @@ -2783,9 +2597,9 @@ } }, "node_modules/@oxlint-tsgolint/darwin-arm64": { - "version": "7.0.2005", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/darwin-arm64/-/darwin-arm64-7.0.2005.tgz", - "integrity": "sha512-VqDZxcZVjlonNLuuvraVNgDQt+1ndwa4yJo8OqsK4HYh/61ba9IlMStCVfi/aaIqRoDhNbAKC8gdcTrXqnb+Ug==", + "version": "7.0.2006", + "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/darwin-arm64/-/darwin-arm64-7.0.2006.tgz", + "integrity": "sha512-uc0MEHXZUDW23Zmo5X28eSNeSnP17jKnh9GiehpVZqhfy99ks8spyXT5Llar3tjDN7ppnQN0Qd9FK6WNkdD+fQ==", "cpu": [ "arm64" ], @@ -2797,9 +2611,9 @@ ] }, "node_modules/@oxlint-tsgolint/darwin-x64": { - "version": "7.0.2005", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/darwin-x64/-/darwin-x64-7.0.2005.tgz", - "integrity": "sha512-4kUfLRNYoVpv0Tm3jPYrvxyfOc/LmdvFC3pKZ4tL6K7lA7K/VS81SAtmxRzbYXYSyb3SBWhwsuX+df4neqzxxA==", + "version": "7.0.2006", + "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/darwin-x64/-/darwin-x64-7.0.2006.tgz", + "integrity": "sha512-+x1/pa3S3VMC9cif8XKTOCQUuqRT+wu1Ix+FK5svXa2xbXCuE7+4S0SfmuSnK/mk9AI5+xBxZFhILxmCPUZ1hA==", "cpu": [ "x64" ], @@ -2811,9 +2625,9 @@ ] }, "node_modules/@oxlint-tsgolint/linux-arm64": { - "version": "7.0.2005", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/linux-arm64/-/linux-arm64-7.0.2005.tgz", - "integrity": "sha512-rhUNcPsBlKvhXtrbhbBUidtRBRdJ8fbEHN9H5Q5N59gby18ruGuDA7KUxl7oRnUzp797uykYQhkBDm+0KpfK/Q==", + "version": "7.0.2006", + "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/linux-arm64/-/linux-arm64-7.0.2006.tgz", + "integrity": "sha512-90v7HX8m54kHXn5DpjNEN18Fb7xwJMREe/wji3USyAf9pTMv7a3qZ3cPoLViIcIzxPLmkcYZIs1j1H3Z2gbVLA==", "cpu": [ "arm64" ], @@ -2825,9 +2639,9 @@ ] }, "node_modules/@oxlint-tsgolint/linux-x64": { - "version": "7.0.2005", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/linux-x64/-/linux-x64-7.0.2005.tgz", - "integrity": "sha512-tKs9yinDQZOHygM0e8EJnjTU3mzJtdfkOZP6Udu82iLMePUSHOhTJ9zzU/mSd1hQxURI4LTRRiFhfzC+PzwdNA==", + "version": "7.0.2006", + "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/linux-x64/-/linux-x64-7.0.2006.tgz", + "integrity": "sha512-/k0wsEqHiA5dWBJYuld3Vecv6bIhKCasxpho/aFkvh870Qox33MuTkKUGWIVm/njAxw7W4pu1a/Xfa3jwuKuPQ==", "cpu": [ "x64" ], @@ -2839,9 +2653,9 @@ ] }, "node_modules/@oxlint-tsgolint/win32-arm64": { - "version": "7.0.2005", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/win32-arm64/-/win32-arm64-7.0.2005.tgz", - "integrity": "sha512-VYPnu1gjfbSv+ROhuyNfMs382D4zQU2ZRc8Uc3nuEZo1k2kf+1KfTrg4hrlWh73h9GI+dUWyo+DYCQzUBlPwcQ==", + "version": "7.0.2006", + "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/win32-arm64/-/win32-arm64-7.0.2006.tgz", + "integrity": "sha512-CQT5sqcLZLNZSWLzUUEjQmp74UX8h1agp3ZJ8pfRktHbx6gfBa8a7CjrnRrZ9VXlwnXVkpw7m5KBO6y+S5MQRA==", "cpu": [ "arm64" ], @@ -2853,9 +2667,9 @@ ] }, "node_modules/@oxlint-tsgolint/win32-x64": { - "version": "7.0.2005", - "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/win32-x64/-/win32-x64-7.0.2005.tgz", - "integrity": "sha512-ekU89cTGy9fpQzuvxIsFHrnoP8XoFjGIRgPEW6eqgY2NYjGy9pwpjF79o04WXRMJFKRrcaVqkZXUUBdLsqpQDw==", + "version": "7.0.2006", + "resolved": "https://registry.npmjs.org/@oxlint-tsgolint/win32-x64/-/win32-x64-7.0.2006.tgz", + "integrity": "sha512-VZsGowXcp3vQNkjoGeVCOTf4aGrRpRk6bBJWhefnJVPr6z+dX+LKqqHfwaqnFvg66Q2iJpXqklRW38YO21ee+Q==", "cpu": [ "x64" ], @@ -3233,14 +3047,14 @@ } }, "node_modules/@rc-component/cascader": { - "version": "1.22.0", - "resolved": "https://registry.npmjs.org/@rc-component/cascader/-/cascader-1.22.0.tgz", - "integrity": "sha512-SffrA57aS9oub3VuI7ajPhJTPtaNxngSvtRhD40Rd8dwJ5vfWPSrVanWgeepdWFGBt7EHftIK5RUU0u3rCTwWw==", + "version": "1.26.0", + "resolved": "https://registry.npmjs.org/@rc-component/cascader/-/cascader-1.26.0.tgz", + "integrity": "sha512-x8n7/LKzdOcuo0+rzmLlMI7mwo2bkOzXS0BST8/X0XyD7NVBdC3xbXvL3/ZH6wsLAWBQAmkmJVrK3DKeDgqDMQ==", "license": "MIT", "dependencies": { - "@rc-component/select": "~1.10.0", - "@rc-component/tree": "~1.4.0", - "@rc-component/util": "^1.11.1", + "@rc-component/select": "~1.12.0", + "@rc-component/tree": "~1.5.3", + "@rc-component/util": "^1.14.0", "clsx": "^2.1.1" }, "peerDependencies": { @@ -3263,14 +3077,14 @@ } }, "node_modules/@rc-component/collapse": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@rc-component/collapse/-/collapse-1.2.0.tgz", - "integrity": "sha512-ZRYSKSS39qsFx93p26bde7JUZJshsUBEQRlRXPuJYlAiNX0vyYlF5TsAm8JZN3LcF8XvKikdzPbgAtXSbkLUkw==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@rc-component/collapse/-/collapse-1.3.0.tgz", + "integrity": "sha512-1pFv7V080Y2ba+MlW6R5arBbxz4EipC7YZmbyHT9ecfWtb1FPCBz9aOKKuX5cBBqdpM+jGDSNORuW4OM/QWIcg==", "license": "MIT", "dependencies": { - "@babel/runtime": "^7.10.1", + "@babel/runtime": "^8.0.0", "@rc-component/motion": "^1.1.4", - "@rc-component/util": "^1.3.0", + "@rc-component/util": "^1.13.0", "clsx": "^2.1.1" }, "peerDependencies": { @@ -3278,6 +3092,12 @@ "react-dom": ">=18.0.0" } }, + "node_modules/@rc-component/collapse/node_modules/@babel/runtime": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-8.1.0.tgz", + "integrity": "sha512-MQye/pU7gzXerMzlhScFNH1u4Je6rR8cqJWSgAfD+rIwbbtwG8tVDegoI7sWfcXkfVRW09G7vk2vjxGIuKFfwg==", + "license": "MIT" + }, "node_modules/@rc-component/color-picker": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/@rc-component/color-picker/-/color-picker-3.1.1.tgz", @@ -3339,9 +3159,9 @@ } }, "node_modules/@rc-component/dropdown": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rc-component/dropdown/-/dropdown-1.0.3.tgz", - "integrity": "sha512-YTST/N6kpqpDz3IMuM/PSSZnrDpSOA6dgHv12gPA90ZTSLv2CoqkZ0+9NtwTY6BeO7dstPblSic2QJg7dSFy/g==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@rc-component/dropdown/-/dropdown-2.0.1.tgz", + "integrity": "sha512-ZZncN8mWNbC5U+YAUQUNXT/R5gOF7HxplEnK979CGjVVLvfp/ULb8IqE8sLU8bKVk7oWqv8cAt4DL0iGoGvNrA==", "license": "MIT", "dependencies": { "@rc-component/trigger": "^3.0.0", @@ -3388,13 +3208,13 @@ } }, "node_modules/@rc-component/input": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@rc-component/input/-/input-1.3.1.tgz", - "integrity": "sha512-iFvTUT9W+JC/MSin2aGAk8NqsVlTzcExNC9DZariON1IWirju9NoNeEk47an4Q8iHazkoVI/y1LnDi88+CPcig==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@rc-component/input/-/input-1.4.1.tgz", + "integrity": "sha512-NZF402PNixm56G6793DSz0zgDLtUf1eFR6XMI0cBbsRr71odJ295B/aJD2p0hliYJnm6X5pYxEMLcatRCpTjUQ==", "license": "MIT", "dependencies": { "@rc-component/resize-observer": "^1.1.1", - "@rc-component/util": "^1.11.1", + "@rc-component/util": "^1.14.0", "clsx": "^2.1.1" }, "peerDependencies": { @@ -3403,13 +3223,13 @@ } }, "node_modules/@rc-component/input-number": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/@rc-component/input-number/-/input-number-1.6.2.tgz", - "integrity": "sha512-Gjcq7meZlCOiWN1t1xCC+7/s85humHVokTBI7PJgTfoyw5OWF74y3e6P8PHX104g9+b54jsodFIzyaj6p8LI9w==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@rc-component/input-number/-/input-number-1.8.0.tgz", + "integrity": "sha512-6hyI17JGZ/P3LXEqDZ3fRmcdNVTAS6aBbZ/cvKu0xCz3v3IF5t8OxCddjy/oSCSBcu+iLh878BbHEgeqKBHQ3A==", "license": "MIT", "dependencies": { - "@rc-component/mini-decimal": "^1.0.1", - "@rc-component/util": "^1.4.0", + "@rc-component/mini-decimal": "^1.1.1", + "@rc-component/util": "^1.14.0", "clsx": "^2.1.1" }, "peerDependencies": { @@ -3418,9 +3238,9 @@ } }, "node_modules/@rc-component/listy": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@rc-component/listy/-/listy-1.2.3.tgz", - "integrity": "sha512-IXiMjV5s0rczLBlfh7G5nB4M3365mrEeedjwKtf5I+Ns3PqRUsebR2h5u8CeFarsVfLUPC2I5p0h09TNoOWyvQ==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@rc-component/listy/-/listy-1.4.0.tgz", + "integrity": "sha512-enNtH2D3nU00qqP+YFxG3V3rnaXpN6HecFUIc/Q5SjxFmg8Ab20os1odn90Bam5y+ZIiOh52HUqvu4HwZv8pkQ==", "license": "MIT", "dependencies": { "@rc-component/motion": "^1.1.4", @@ -3436,15 +3256,15 @@ } }, "node_modules/@rc-component/mentions": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/@rc-component/mentions/-/mentions-1.12.0.tgz", - "integrity": "sha512-v5MBx8zDcqCT+uybJgKpcx3Fgrvj0m3u+A/15RlSBaMx12lLoJZTTYggC3pbYYfohcKujWWUyBz6O6Gp2vGiNA==", + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@rc-component/mentions/-/mentions-1.14.1.tgz", + "integrity": "sha512-Ra4462KKaiAkwRklJpYZPznWssCf0LjFKIhHaxuha1rwdrTY1UBeYSzfqj7ux7S2/AqjR9k60U5PijFToNma/Q==", "license": "MIT", "dependencies": { - "@rc-component/input": "~1.3.1", - "@rc-component/menu": "~1.5.0", + "@rc-component/input": "~1.4.1", + "@rc-component/menu": "~1.6.0", "@rc-component/trigger": "^3.0.0", - "@rc-component/util": "^1.11.1", + "@rc-component/util": "^1.14.0", "clsx": "^2.1.1" }, "peerDependencies": { @@ -3453,15 +3273,15 @@ } }, "node_modules/@rc-component/menu": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@rc-component/menu/-/menu-1.5.0.tgz", - "integrity": "sha512-RjvzPsZkwVEg3xu+/jDDqDeUCBJAnWylONFlGeQgg5enlNAnlpybqhaMGE/UPEIvr6hL90PGhjFBguJqj0Qb2Q==", + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/@rc-component/menu/-/menu-1.6.2.tgz", + "integrity": "sha512-S4vR5PEhfDjV8Wi3bMQCGhM15MuQjtTTkLrUj/nVAaGrmD0/kcBZ6V3z0f5+QMIj01sF95dRohBKNh0gy/AoXQ==", "license": "MIT", "dependencies": { "@rc-component/motion": "^1.1.4", "@rc-component/overflow": "^1.0.0", "@rc-component/trigger": "^3.0.0", - "@rc-component/util": "^1.11.1", + "@rc-component/util": "^1.13.0", "clsx": "^2.1.1" }, "peerDependencies": { @@ -3546,12 +3366,12 @@ } }, "node_modules/@rc-component/pagination": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@rc-component/pagination/-/pagination-1.4.0.tgz", - "integrity": "sha512-CW1g7P9V8u+e8JQdUsl2RWg+GCsoee0mtJjZUCCxn/vb3jzOwDKm6hAdwddHCVBfWJ58eGUBZz3IvnU8rRktjw==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@rc-component/pagination/-/pagination-1.7.0.tgz", + "integrity": "sha512-bG3H6gNTABAX9wIRjonxld2SU8C4wvpq/8Xgg30oQWsunRTtUeIlM7J+9UvJAC0CXgG9ZFpoiQ+vbyOuXCcveA==", "license": "MIT", "dependencies": { - "@rc-component/util": "^1.11.1", + "@rc-component/util": "^1.13.0", "clsx": "^2.1.1" }, "peerDependencies": { @@ -3560,15 +3380,15 @@ } }, "node_modules/@rc-component/picker": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@rc-component/picker/-/picker-1.12.2.tgz", - "integrity": "sha512-ZB1A+tzTQkgtR4flPrAMvxIAOelIIOOOsp22fU2Nad6PbZcJacnyGJUJqUH7ZS9mwxeUwurf1pLMKXrVsK1tlA==", + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/@rc-component/picker/-/picker-1.17.0.tgz", + "integrity": "sha512-r+fJajCeT2gIVzuOSX+M2jjMglCYLa2b7ESZbD1IYrhOBhnHN3H0rSrbcThi/XRumlz1qWMncnC1WHQTzPolSg==", "license": "MIT", "dependencies": { "@rc-component/overflow": "^1.0.0", "@rc-component/resize-observer": "^1.0.0", "@rc-component/trigger": "^3.6.15", - "@rc-component/util": "^1.13.0", + "@rc-component/util": "^1.14.0", "clsx": "^2.1.1" }, "engines": { @@ -3615,9 +3435,9 @@ } }, "node_modules/@rc-component/progress": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rc-component/progress/-/progress-1.0.3.tgz", - "integrity": "sha512-Q1nPLIvKr95el/q76yaBh5nv1hqCsWaHQb8U7vXEDMefEhHgM7n3CPoN+o4LHnTyANQHmMFgoS/naAT4Bhxuaw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rc-component/progress/-/progress-1.1.0.tgz", + "integrity": "sha512-4IjvlwckYBxp6kauIkjSGNNXKIpuU5PoBnAIME4fYoQABBt0HAzyM0Sz0EEnaJiifRu3wTOwE5GFy4hzJthBxA==", "license": "MIT", "dependencies": { "@rc-component/util": "^1.11.1", @@ -3691,20 +3511,20 @@ } }, "node_modules/@rc-component/segmented/node_modules/@babel/runtime": { - "version": "8.0.10", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-8.0.10.tgz", - "integrity": "sha512-0QyWQOIhl2onOgg96BuOYV+oCgLINVDPC8RkVPCiQhLILVqpefDUmcY+aAsW6vp7fcuTZL6SXXlFrSDCTFIu1w==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-8.1.0.tgz", + "integrity": "sha512-MQye/pU7gzXerMzlhScFNH1u4Je6rR8cqJWSgAfD+rIwbbtwG8tVDegoI7sWfcXkfVRW09G7vk2vjxGIuKFfwg==", "license": "MIT" }, "node_modules/@rc-component/select": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@rc-component/select/-/select-1.10.1.tgz", - "integrity": "sha512-H+yQsl+qED9NilQ3g6zdpsMwUgwVjrcMTkNHAWRVU/MoNCYgTbDgU+MIMgZDK+rVdd2JUfI/MkysMcZZ0cyQKw==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@rc-component/select/-/select-1.12.0.tgz", + "integrity": "sha512-S3YCqh6GnXL47MkA7Jb1SQdiinfUeygBkCpWhWFVH3nrOzObOiNobkX8HPHomjhpiVRDa/9ESszhPnfyuubFFw==", "license": "MIT", "dependencies": { "@rc-component/overflow": "^1.0.0", "@rc-component/trigger": "^3.0.0", - "@rc-component/util": "^1.11.1", + "@rc-component/util": "^1.14.0", "@rc-component/virtual-list": "^1.2.0", "clsx": "^2.1.1" }, @@ -3717,12 +3537,12 @@ } }, "node_modules/@rc-component/slider": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@rc-component/slider/-/slider-1.1.1.tgz", - "integrity": "sha512-LSzgWGYDgeCDgR4r1XlU29gbYws6HpLnvJd/uMhLeW/vQgxldeR+Wb4uzHDCHiYEbr1bnEHWdjkPxjJRHxuiig==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rc-component/slider/-/slider-1.2.1.tgz", + "integrity": "sha512-viYU/3Vy8dXfTOAB/5rNkNHIsHJQ7DwK+sdQ5L76qDHhL8RtLfwsR7pYTUFfmKUgSAhSzEQolmfuDeIx3/fBJQ==", "license": "MIT", "dependencies": { - "@rc-component/util": "^1.3.0", + "@rc-component/util": "^1.13.0", "clsx": "^2.1.1" }, "engines": { @@ -3765,9 +3585,9 @@ } }, "node_modules/@rc-component/table": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@rc-component/table/-/table-1.11.1.tgz", - "integrity": "sha512-OWdS6DMmeWb7bJBGqPxYZpQbzBlBiXZUu2sqo6Ii7Sjs9GeK1IsrXrWk26SL2c6KEseabswdxrRj7WUm9LdECw==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@rc-component/table/-/table-1.12.0.tgz", + "integrity": "sha512-uyrnUDucOKR7BeXRtw3v2CM/LkuXjbvFhM1+HFdUc11Vkfc4aEXgHjPXvi6jKK8NuS3Yt4wMgBuLVIRTPJoqwQ==", "license": "MIT", "dependencies": { "@rc-component/context": "^2.0.1", @@ -3785,16 +3605,16 @@ } }, "node_modules/@rc-component/tabs": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/@rc-component/tabs/-/tabs-1.13.0.tgz", - "integrity": "sha512-3FXr+9ZII8tFLWuDWrgjRaxZd2mazkKJAGRFEfVmp4r1qnBglOlxQ78l54Td1aj6/iFaaEReKSAF2HToztU5uw==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@rc-component/tabs/-/tabs-2.0.0.tgz", + "integrity": "sha512-gpknpprmgyPXdDJ4TJ2NIVNbHc+S43bb4G1iAESq5DYCQwT6zGURWE/1uGtCoyQBZ+ySk2Tx+fekpbw9GafvoQ==", "license": "MIT", "dependencies": { - "@rc-component/dropdown": "~1.0.0", - "@rc-component/menu": "~1.5.0", + "@rc-component/dropdown": "~2.0.0", + "@rc-component/menu": "~1.6.0", "@rc-component/motion": "^1.1.3", "@rc-component/resize-observer": "^1.0.0", - "@rc-component/util": "^1.11.1", + "@rc-component/util": "^1.13.0", "clsx": "^2.1.1" }, "engines": { @@ -3840,13 +3660,13 @@ } }, "node_modules/@rc-component/tree": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@rc-component/tree/-/tree-1.4.0.tgz", - "integrity": "sha512-dGsJGDJQedA0BqqVgj3F8BvHXTSZijyhTXdbAdkcx8lynzZkty/CV3Z3LOm/fxz+BCfl3dfGiAQpb7Q5XNvl0Q==", + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/@rc-component/tree/-/tree-1.5.3.tgz", + "integrity": "sha512-Uk4AFu3FQg+WfeFa+KtfQtuQmgV6Wc+ZQdeJeOpsJyu65bcGAp43PiHlx9xhW06BS+OUyzUc0pvwM9PqFZvB+Q==", "license": "MIT", "dependencies": { "@rc-component/motion": "^1.0.0", - "@rc-component/util": "^1.11.1", + "@rc-component/util": "^1.13.0", "@rc-component/virtual-list": "^1.2.0", "clsx": "^2.1.1" }, @@ -3859,14 +3679,14 @@ } }, "node_modules/@rc-component/tree-select": { - "version": "1.16.1", - "resolved": "https://registry.npmjs.org/@rc-component/tree-select/-/tree-select-1.16.1.tgz", - "integrity": "sha512-a1Oi6EJhqAhdOxxupdJi6fP0RPHMKn5TcfkX2+llaQ4lF4nwfH7b6SCHcnsybaa2s+pk1yZYwVyeOYkDnEBRdg==", + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/@rc-component/tree-select/-/tree-select-1.19.0.tgz", + "integrity": "sha512-LlZTsnShZkSJpOJ7XuLmhSNUqyaYl1OUbdRzdgaqcyZyYydOyWb8GC0wxHMeyL3qau3kNg/r3fo6gqASHQ2uog==", "license": "MIT", "dependencies": { - "@rc-component/select": "~1.10.0", - "@rc-component/tree": "~1.4.0", - "@rc-component/util": "^1.11.1", + "@rc-component/select": "~1.12.0", + "@rc-component/tree": "~1.5.3", + "@rc-component/util": "^1.14.0", "clsx": "^2.1.1" }, "peerDependencies": { @@ -3909,9 +3729,9 @@ } }, "node_modules/@rc-component/util": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/@rc-component/util/-/util-1.14.0.tgz", - "integrity": "sha512-qFpkGBCiyN3NNAU+FOnZdcdz7A/rXCg3JdQk+bujUKAExZgRqzf2yy1f4YN63Lwctic5FcK9rgjQ6aWbykqwEw==", + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@rc-component/util/-/util-1.14.1.tgz", + "integrity": "sha512-pyCKpJ+L2EcNspFpKBG10C1dyMv0w9FzcM+gM3FK4h6/NtMZzdimr5iYDR8ptfp4wJj9lnYHg3OTvLVE1EuTbQ==", "license": "MIT", "dependencies": { "is-mobile": "^5.0.0", @@ -3942,9 +3762,9 @@ } }, "node_modules/@rc-component/virtual-list/node_modules/@babel/runtime": { - "version": "8.0.10", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-8.0.10.tgz", - "integrity": "sha512-0QyWQOIhl2onOgg96BuOYV+oCgLINVDPC8RkVPCiQhLILVqpefDUmcY+aAsW6vp7fcuTZL6SXXlFrSDCTFIu1w==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-8.1.0.tgz", + "integrity": "sha512-MQye/pU7gzXerMzlhScFNH1u4Je6rR8cqJWSgAfD+rIwbbtwG8tVDegoI7sWfcXkfVRW09G7vk2vjxGIuKFfwg==", "license": "MIT" }, "node_modules/@remix-run/route-pattern": { @@ -3954,9 +3774,9 @@ "license": "MIT" }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.16.tgz", - "integrity": "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", "cpu": [ "arm" ], @@ -3971,9 +3791,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.16.tgz", - "integrity": "sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", "cpu": [ "arm64" ], @@ -3988,9 +3808,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.16.tgz", - "integrity": "sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", "cpu": [ "arm64" ], @@ -4005,9 +3825,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.16.tgz", - "integrity": "sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", "cpu": [ "x64" ], @@ -4022,9 +3842,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.16.tgz", - "integrity": "sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", "cpu": [ "x64" ], @@ -4039,9 +3859,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.16.tgz", - "integrity": "sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", "cpu": [ "arm" ], @@ -4056,9 +3876,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.16.tgz", - "integrity": "sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", "cpu": [ "arm64" ], @@ -4076,9 +3896,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.16.tgz", - "integrity": "sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", "cpu": [ "arm64" ], @@ -4096,9 +3916,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.16.tgz", - "integrity": "sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", "cpu": [ "ppc64" ], @@ -4116,9 +3936,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.16.tgz", - "integrity": "sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", "cpu": [ "s390x" ], @@ -4136,9 +3956,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.16.tgz", - "integrity": "sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", "cpu": [ "x64" ], @@ -4156,9 +3976,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.16.tgz", - "integrity": "sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", "cpu": [ "x64" ], @@ -4176,9 +3996,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.16.tgz", - "integrity": "sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", "cpu": [ "arm64" ], @@ -4192,10 +4012,85 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.16.tgz", - "integrity": "sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", "cpu": [ "arm64" ], @@ -4210,9 +4105,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.16.tgz", - "integrity": "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", "cpu": [ "x64" ], @@ -4227,9 +4122,9 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.0.tgz", + "integrity": "sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==", "dev": true, "license": "MIT" }, @@ -4423,9 +4318,9 @@ "license": "MIT" }, "node_modules/@storybook/addon-a11y": { - "version": "10.6.5", - "resolved": "https://registry.npmjs.org/@storybook/addon-a11y/-/addon-a11y-10.6.5.tgz", - "integrity": "sha512-7dEH3OHKdE+0zakqEy50KtfhPORIm1xnhWeehyROO1Ct7Rx9s7cYcx6edUZvh0tCuX5VhDnDmkvQV+dbrPDmCA==", + "version": "10.6.7", + "resolved": "https://registry.npmjs.org/@storybook/addon-a11y/-/addon-a11y-10.6.7.tgz", + "integrity": "sha512-ARd+bjfOYoICe00+svRgFsCVqV7RbN+wgi8yfRhk31kESR7NnTMBGiZD8vWv/r3xqul/Ddr1uR6mUK4lpH7sqw==", "dev": true, "license": "MIT", "dependencies": { @@ -4437,19 +4332,19 @@ "url": "https://opencollective.com/storybook" }, "peerDependencies": { - "storybook": "^10.6.5" + "storybook": "^10.6.7" } }, "node_modules/@storybook/addon-docs": { - "version": "10.6.5", - "resolved": "https://registry.npmjs.org/@storybook/addon-docs/-/addon-docs-10.6.5.tgz", - "integrity": "sha512-Kt0pGLA+nwdu2g80p8jbdoiiKXxwQbhrY6uzMzq/0G1lytxpJUzrOQAM+GDcEbqyvpKr0u5d1q05/LPem/uooQ==", + "version": "10.6.7", + "resolved": "https://registry.npmjs.org/@storybook/addon-docs/-/addon-docs-10.6.7.tgz", + "integrity": "sha512-R0SxB+sv99/V1H51JFh5CjiN5Ufpuh8Bho7iT8hhl1NMGLk76BBqq9l63XgCp4d+1k9mXz7BVu7zFLWdf+j/Rg==", "dev": true, "license": "MIT", "dependencies": { "@mdx-js/react": "^3.0.0", "@storybook/icons": "^2.0.2", - "@storybook/react-dom-shim": "10.6.5", + "@storybook/react-dom-shim": "10.6.7", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "ts-dedent": "^2.0.0", @@ -4461,7 +4356,7 @@ }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", - "storybook": "^10.6.5" + "storybook": "^10.6.7" }, "peerDependenciesMeta": { "@types/react": { @@ -4470,9 +4365,9 @@ } }, "node_modules/@storybook/addon-vitest": { - "version": "10.6.5", - "resolved": "https://registry.npmjs.org/@storybook/addon-vitest/-/addon-vitest-10.6.5.tgz", - "integrity": "sha512-0N0E7TQgmdrPNCPqNiVdTWOEQ1Nes+YsUphYX/abzlp6ReOyYBoQJw6mZ0b7BN5ACgdXQsr9Tth161t72k+51Q==", + "version": "10.6.7", + "resolved": "https://registry.npmjs.org/@storybook/addon-vitest/-/addon-vitest-10.6.7.tgz", + "integrity": "sha512-8Pc71Al635pMfYK9mBfzBd87ta1yD7tgyn0IGPtK6HGdRM0IBrMzVW716Z0i4dfedMPma5z77sIzlr+7z4gBMA==", "dev": true, "license": "MIT", "dependencies": { @@ -4486,7 +4381,7 @@ "peerDependencies": { "@vitest/browser": "^4.0.0 || ^5.0.0", "@vitest/browser-playwright": "^4.0.0 || ^5.0.0", - "storybook": "^10.6.5", + "storybook": "^10.6.7", "vitest": "^4.0.0 || ^5.0.0" }, "peerDependenciesMeta": { @@ -4502,9 +4397,9 @@ } }, "node_modules/@storybook/builder-vite": { - "version": "10.6.5", - "resolved": "https://registry.npmjs.org/@storybook/builder-vite/-/builder-vite-10.6.5.tgz", - "integrity": "sha512-udrGjg3yt38pz4FxplypXxw1creIGS7N6QS8xfvTFM8MQNtPyojT/gZdd4fhX0dFrQx5MMuJEYJA5gUBiPsLtg==", + "version": "10.6.7", + "resolved": "https://registry.npmjs.org/@storybook/builder-vite/-/builder-vite-10.6.7.tgz", + "integrity": "sha512-6DI3XP4He/nMMK4vGLl9tkneygr5bJvYx5EwNZMzw15tCosvGuWRREBvWqTHjZdoRa8HJpqosoFm60splBoAew==", "dev": true, "license": "MIT", "dependencies": { @@ -4515,7 +4410,7 @@ "url": "https://opencollective.com/storybook" }, "peerDependencies": { - "storybook": "^10.6.5", + "storybook": "^10.6.7", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, @@ -4537,14 +4432,14 @@ } }, "node_modules/@storybook/react": { - "version": "10.6.5", - "resolved": "https://registry.npmjs.org/@storybook/react/-/react-10.6.5.tgz", - "integrity": "sha512-vvRjRe/O8NRiQbGyA7Ne6h2jbD6GjwNZFkMdHl+0kZH8Z/S9ZWWmKmjCySvH/OmgighdCOQ98tcfND7m65WQBg==", + "version": "10.6.7", + "resolved": "https://registry.npmjs.org/@storybook/react/-/react-10.6.7.tgz", + "integrity": "sha512-PzQG9vNKRMjk81W1zli6mrsjUkp+05GzEmdpxxpmSvf5I2KrhUjO+FBN0s4wdJTrJRDZwjZzXcR0TkvkBxAB4g==", "dev": true, "license": "MIT", "dependencies": { "@storybook/global": "^5.0.0", - "@storybook/react-dom-shim": "10.6.5", + "@storybook/react-dom-shim": "10.6.7", "react-docgen": "^8.0.2", "react-docgen-typescript": "^2.2.2" }, @@ -4557,7 +4452,7 @@ "@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", - "storybook": "^10.6.5", + "storybook": "^10.6.7", "typescript": ">= 4.9.x" }, "peerDependenciesMeta": { @@ -4573,9 +4468,9 @@ } }, "node_modules/@storybook/react-dom-shim": { - "version": "10.6.5", - "resolved": "https://registry.npmjs.org/@storybook/react-dom-shim/-/react-dom-shim-10.6.5.tgz", - "integrity": "sha512-Qbbkp+5Otg32w8Ddav6rH6MGPiYVfEzrgn0HqbqlqS8kY+DRXo+NYXJwZTVSDSwrYPrfH+Ok2tV4uE8Zo0c3cg==", + "version": "10.6.7", + "resolved": "https://registry.npmjs.org/@storybook/react-dom-shim/-/react-dom-shim-10.6.7.tgz", + "integrity": "sha512-h5VsEhWyLI4BsqcFwK/nOwvy5t8Hu3Tt7msUn4smHM0NbqtMlyZmA3LH58Q2plRy41T6lg0BLVjz5S/9s8cTZA==", "dev": true, "license": "MIT", "funding": { @@ -4587,7 +4482,7 @@ "@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", - "storybook": "^10.6.5" + "storybook": "^10.6.7" }, "peerDependenciesMeta": { "@types/react": { @@ -4599,16 +4494,16 @@ } }, "node_modules/@storybook/react-vite": { - "version": "10.6.5", - "resolved": "https://registry.npmjs.org/@storybook/react-vite/-/react-vite-10.6.5.tgz", - "integrity": "sha512-RsRF1drYtCku7+PMdRnuFt3EdG8Rn8I5G8ne0cBjn24xSn5Pbo9W+y9IoyD2llAeaeCpzEEdASY12wpKd3aCQA==", + "version": "10.6.7", + "resolved": "https://registry.npmjs.org/@storybook/react-vite/-/react-vite-10.6.7.tgz", + "integrity": "sha512-7mpJApW6zy4riLPq7o0he80eQy1GofdqEPWWpCHQDMVuOJAvmuuX656hY5flboZwWC18g/6yWbxrRQx5uf7pDQ==", "dev": true, "license": "MIT", "dependencies": { "@joshwooding/vite-plugin-react-docgen-typescript": "^0.7.0", "@rollup/pluginutils": "^5.0.2", - "@storybook/builder-vite": "10.6.5", - "@storybook/react": "10.6.5", + "@storybook/builder-vite": "10.6.7", + "@storybook/react": "10.6.7", "empathic": "^2.0.0", "magic-string": "^1.1.0", "react-docgen": "^8.0.2", @@ -4622,7 +4517,7 @@ "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", - "storybook": "^10.6.5", + "storybook": "^10.6.7", "typescript": ">= 4.9.x", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, @@ -4633,13 +4528,13 @@ } }, "node_modules/@swagger-api/apidom-ast": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ast/-/apidom-ast-1.13.3.tgz", - "integrity": "sha512-5722GHs+iLl4F5EbyReh+d0XEmG6t4F1BRTPEjHBrmfboBICi7u1cwwZ2wsCskQl0TehEl3RX1ZJWPmpkzjQFw==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ast/-/apidom-ast-1.14.0.tgz", + "integrity": "sha512-yzKA1z63/YL/bT50axexISPwQpQC7Vtl+OBVGMktz9lQgKpQTudKEp/k4c3D61jOS5YWKtu2UzcB65l/AY+0mQ==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-error": "^1.13.3", + "@swagger-api/apidom-error": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4647,14 +4542,14 @@ } }, "node_modules/@swagger-api/apidom-core": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-core/-/apidom-core-1.13.3.tgz", - "integrity": "sha512-Sgd8pWucD2vs055koRTrRG1zH+pj9VXdyLtjKKC/iML6eAFgd0lmLccK2aFNGt2/36olIzNODeRMTPRnufZgCA==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-core/-/apidom-core-1.14.0.tgz", + "integrity": "sha512-4BCnyq7P7ZJZawZpIt0tw/OGgiTYsfZ5nCq+9az0hHQWyQ/C7nbYzjeCoY+gMGlO33S/CIlzkJL7nL7xv4rijA==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-ast": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", + "@swagger-api/apidom-ast": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", "@types/ramda": "~0.30.0", "minim": "~0.23.8", "ramda": "~0.30.0", @@ -4664,35 +4559,35 @@ } }, "node_modules/@swagger-api/apidom-error": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-error/-/apidom-error-1.13.3.tgz", - "integrity": "sha512-5erobaeuRu5rAwcL/ljE3jGuX/ILENq3zLU8rZCV0/rvlc5vuGGhyowt8UmI79L7y+vifYFs6d+kcfn/di0T6A==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-error/-/apidom-error-1.14.0.tgz", + "integrity": "sha512-LiuN9xv+qM1w+zrYXTg94uZSKtzMQp64fiKxU8CZW/psfyj+/5RUt3bn+tHzoVuaN8XPLyvCafCchZ8MKTcvEA==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.20.7" } }, "node_modules/@swagger-api/apidom-json-pointer": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-json-pointer/-/apidom-json-pointer-1.13.3.tgz", - "integrity": "sha512-eQaMH3HnR5eElsBQc5IueDsZoK76uCnW78JZDP2uLDTq3Lqx0hzUyFnZUSwY/XrLmfcLWtJiSABezEU/DcfJBg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-json-pointer/-/apidom-json-pointer-1.14.0.tgz", + "integrity": "sha512-lxBGROkikKtqe8WyXSczRSttwKp79jqNiJ2KK6OsuWxe+3ehic2dzvC+xKXgIiSkGjYRV3saSa2OcwvcqSWOuQ==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", "@swaggerexpert/json-pointer": "^2.10.1" } }, "node_modules/@swagger-api/apidom-ns-a2a-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-a2a-1/-/apidom-ns-a2a-1-1.13.3.tgz", - "integrity": "sha512-TZEmV3E2Hji9dDm7e1wAckMnqFGdxnFSrbDtwKbubSfYgshSMqx0Vc3mQu/IsigqSmZZLWgmOI9iq737SqraZQ==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-a2a-1/-/apidom-ns-a2a-1-1.14.0.tgz", + "integrity": "sha512-Dz/z444nTMr2n4cGHhf7fuBdX6dI+rsS65651NLmD52oFENRkklMgWcfwZqBWp8u87oLsCf8ZS0vqiaU6myLfQ==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4700,16 +4595,16 @@ } }, "node_modules/@swagger-api/apidom-ns-api-design-systems": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-api-design-systems/-/apidom-ns-api-design-systems-1.13.3.tgz", - "integrity": "sha512-00aflYATDo1RbkLNvAq/lS3aEZHfCKFwBZbSSvoLAXsIguzKYCCIjm5F+4fWLIiToL7junHvnUuS9PHTMre7bQ==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-api-design-systems/-/apidom-ns-api-design-systems-1.14.0.tgz", + "integrity": "sha512-p9GfaYZvNGMVuSy89IGeeyod+RFfKma+znrv1N4Id/QLBe0VLisnmqf/wKNWCpK8FE0uZqxvuFRUMj2eOuGnfQ==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-1": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-1": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4717,15 +4612,15 @@ } }, "node_modules/@swagger-api/apidom-ns-arazzo-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-arazzo-1/-/apidom-ns-arazzo-1-1.13.3.tgz", - "integrity": "sha512-42apSY7ttFRHIX7JDCH494IGwd6AhS7Owj4ftdfzhZUj1ZQU8YcXzunmlwig4tw1RyOR3hBzH51h0uvWO6M2+w==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-arazzo-1/-/apidom-ns-arazzo-1-1.14.0.tgz", + "integrity": "sha512-UIjdwgBCkOJYXxjmCulnvRjocJW0uhg2OXUS7FzKMXf0O3EeK3ChUoyOYgfSsQ8x6oF7uWbpSy4geSezCikj1Q==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-2020-12": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-2020-12": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4733,15 +4628,15 @@ } }, "node_modules/@swagger-api/apidom-ns-asyncapi-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-asyncapi-2/-/apidom-ns-asyncapi-2-1.13.3.tgz", - "integrity": "sha512-TrUYjBi8obSkt30/rqmDS9mNepoPbJCF1zrnMVKx2EmYMqq3S35ZRC+PJSqCDCZ7VlVm8oE4/jtRm1LCmCPFvg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-asyncapi-2/-/apidom-ns-asyncapi-2-1.14.0.tgz", + "integrity": "sha512-MTJZk9Dpg9maey3eHg7D4t1Hl8i0pK8PrqXhmMGNiyKGMLSVmZeIZMC89fJVUZFn6zEcYAGE9dq0oAR4V17n5Q==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-draft-7": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-draft-7": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4749,15 +4644,15 @@ } }, "node_modules/@swagger-api/apidom-ns-asyncapi-3": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-asyncapi-3/-/apidom-ns-asyncapi-3-1.13.3.tgz", - "integrity": "sha512-uN8dK3zUS0rR2uWgeH7X2AGVzsupBjJqz3jebkneTdPm9r8xmJuKhPboXiafrveqv0V9BGFUcMSn9S9FPyD1Cg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-asyncapi-3/-/apidom-ns-asyncapi-3-1.14.0.tgz", + "integrity": "sha512-oxRxbEaZ019N2hYQh7TQT5JyyWFaenwx0nCE8wGUCYVeXAnH5BH8SCOxJgi51++N1Ro+mFtP6+D26GyFLl1asA==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-asyncapi-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-asyncapi-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4765,15 +4660,15 @@ } }, "node_modules/@swagger-api/apidom-ns-json-schema-2019-09": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-2019-09/-/apidom-ns-json-schema-2019-09-1.13.3.tgz", - "integrity": "sha512-W0P/yN5ZDxjEFb2W+f7NK1XokhBxXvfhWVSPoze7K+bF4ekcB2qkfxAdsI38FWvlxQGL6TQETxQna9Lp1d7blw==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-2019-09/-/apidom-ns-json-schema-2019-09-1.14.0.tgz", + "integrity": "sha512-jHE49ethyReHw0krjIx+pi0gEESNCCjVxuEp1ZvdVun7a+KIBJwp9koHVxO+GPlXBeg/accV2WK0ASGiwXffQA==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-draft-7": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-draft-7": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4781,15 +4676,15 @@ } }, "node_modules/@swagger-api/apidom-ns-json-schema-2020-12": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-2020-12/-/apidom-ns-json-schema-2020-12-1.13.3.tgz", - "integrity": "sha512-fF5Wqvmb2vvx0o0Tr5Vcz+Q6gedVi7oGeKJWaSBA7WJ0awUz+PCIW3OPiKhcxdVW2/Zrxd5kMELDCmarnHS65Q==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-2020-12/-/apidom-ns-json-schema-2020-12-1.14.0.tgz", + "integrity": "sha512-HGBVG+JlAQbHmLunjDlmNw80NUN6DVyy4p+VMs9JZH2oACSKaOxNmHhertk0Szg0xdNXVEJiVvOKkjeLI+iADw==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-2019-09": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-2019-09": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4797,14 +4692,14 @@ } }, "node_modules/@swagger-api/apidom-ns-json-schema-draft-4": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-4/-/apidom-ns-json-schema-draft-4-1.13.3.tgz", - "integrity": "sha512-8jh6dhDKskIPP/76aIMlNpCHf5oHHyMuAe4FL2nw3fat3GOq/l0ea0a/6E1tjUJLokAaES0sWTkxYgNRWMBrBg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-4/-/apidom-ns-json-schema-draft-4-1.14.0.tgz", + "integrity": "sha512-Un0xLcfALPM9NWavUPL5LCU2kEYjhnkhqTxQolbXqE/BbQzBdiSFTlXys56L4tz6UyH8v1LjE2Af63UCY4kKmQ==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-ast": "^1.13.3", - "@swagger-api/apidom-core": "^1.13.3", + "@swagger-api/apidom-ast": "^1.14.0", + "@swagger-api/apidom-core": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4812,15 +4707,15 @@ } }, "node_modules/@swagger-api/apidom-ns-json-schema-draft-6": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-6/-/apidom-ns-json-schema-draft-6-1.13.3.tgz", - "integrity": "sha512-axUur9XmKCi42WSGceBXKwnqPTMMVF+0Etaksazo5j7ydWLEM0J1EyeeE7uZlpaoIA1/ev2m09j2v1LNOc6NYg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-6/-/apidom-ns-json-schema-draft-6-1.14.0.tgz", + "integrity": "sha512-lVLknAwGZEyjWbFCQg8ZUVQetN8I5hGmcGb3bnURxglXpneFGsf6vFg1ptBRF4W6PO3okeOAyKvE93gZB4F5Jg==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-draft-4": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-draft-4": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4828,15 +4723,15 @@ } }, "node_modules/@swagger-api/apidom-ns-json-schema-draft-7": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-7/-/apidom-ns-json-schema-draft-7-1.13.3.tgz", - "integrity": "sha512-AyIMoer1bFhn3ULeEe6EMQDcD4b4JiTWQMvS/qDUoQqY6fCLPu6er/6cxcjcgTgf8L86aG6PhPxucnYDWr0DFQ==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-7/-/apidom-ns-json-schema-draft-7-1.14.0.tgz", + "integrity": "sha512-XECPBJyJRj6QKvNGwWumagSRIQhu0WGpYlnLNxyXPTFbDt52GBdz1k5qA4F+cJIBtOMKqZH+TSsMiRKjHs0PxA==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-draft-6": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-draft-6": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4844,16 +4739,16 @@ } }, "node_modules/@swagger-api/apidom-ns-openapi-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-2/-/apidom-ns-openapi-2-1.13.3.tgz", - "integrity": "sha512-ndrNoyETfWPOvoqNIQ19yoYGVhXlrLCK2xanTn+IGJ4hg/9vK2Le4Qmiv1O/E90hODs5JPx1WuZBRQikKOLW8Q==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-2/-/apidom-ns-openapi-2-1.14.0.tgz", + "integrity": "sha512-ithVOQNsgUbA4o4Gsyv5IXvXGk2EVFSzRb79L+fUNb2kBn2NThyG3IBLaHVkdLxzD5AtNiqw7canD1+osJLgZg==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-draft-4": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-draft-4": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4861,15 +4756,15 @@ } }, "node_modules/@swagger-api/apidom-ns-openapi-3-0": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-0/-/apidom-ns-openapi-3-0-1.13.3.tgz", - "integrity": "sha512-emLzxkwOb/RCenwZ6DRukuTAWwwqcM6a76gpHL8rq9Ax8AEbmKB0Ex25tqc/HWXRRTOioylSuotluUvHcRqXEQ==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-0/-/apidom-ns-openapi-3-0-1.14.0.tgz", + "integrity": "sha512-sWd0ck8wG6dJZRhUEXENZWJwU4zdT8mPeGyNaaCwN0T7ShATg3RXL3eMJuRqP1liQmZuf+A5Ho/IxmS98ZgWYw==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-draft-4": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-draft-4": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4877,17 +4772,17 @@ } }, "node_modules/@swagger-api/apidom-ns-openapi-3-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-1/-/apidom-ns-openapi-3-1-1.13.3.tgz", - "integrity": "sha512-Oh1lonFFB1sEATek6e18efUMNG+ttXWrRHrblJtVMx7cUelP1BTvBt4ykrvlnXw4EoG8bIHwLtD6yVgCX1mcpw==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-1/-/apidom-ns-openapi-3-1-1.14.0.tgz", + "integrity": "sha512-HCTmFPzQumKTrcs+4eaTMfhWgkx6dJ30Zh/VOkZOtVgQDUzezKKUm1+NIdFZEIaQ0ZmRGvdXZ+RZnF6v1U6hUQ==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-ast": "^1.13.3", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-json-pointer": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-2020-12": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-0": "^1.13.3", + "@swagger-api/apidom-ast": "^1.14.0", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-json-pointer": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-2020-12": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-0": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4895,18 +4790,18 @@ } }, "node_modules/@swagger-api/apidom-ns-openapi-3-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-2/-/apidom-ns-openapi-3-2-1.13.3.tgz", - "integrity": "sha512-1wUZvT2E71WorxQDy9zxrq2GJud7wUO6r/oDPTldnRiagAe/KXyLyRbucxeaLqh417wCg2ySGyClZVUT5QwE9g==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-2/-/apidom-ns-openapi-3-2-1.14.0.tgz", + "integrity": "sha512-tFBqwD4t3ChezZ6oM7gNEbTFpNsb5xxg7ozhfgc34xdak1/MIQkRNLH/GgvpztG81pERIqrQLGcbWm5iH8wqFg==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-ast": "^1.13.3", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-json-pointer": "^1.13.3", - "@swagger-api/apidom-ns-json-schema-2020-12": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-0": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-1": "^1.13.3", + "@swagger-api/apidom-ast": "^1.14.0", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-json-pointer": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-2020-12": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-0": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-1": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -4914,176 +4809,176 @@ } }, "node_modules/@swagger-api/apidom-parser-adapter-a2a-json-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-a2a-json-1/-/apidom-parser-adapter-a2a-json-1-1.13.3.tgz", - "integrity": "sha512-v1GCfvk/goJBlroHSW5gVHWI0OgHG3HfsfHR6XlWwronJaaTq/Adz7yE/rNyjC+Wfmi7VVhuNoWvOUuWjbWr3w==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-a2a-json-1/-/apidom-parser-adapter-a2a-json-1-1.14.0.tgz", + "integrity": "sha512-161dG8D7BP7ejwNKLRweemGw4cpJjVMixXos/67PCnr2Hg+MV+vEhh0VtBJoSf2NMNnfhO9g1wKAnj2pDCYWNA==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-a2a-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-a2a-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-a2a-yaml-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-a2a-yaml-1/-/apidom-parser-adapter-a2a-yaml-1-1.13.3.tgz", - "integrity": "sha512-WMDimop6PdvAoNKymE5sm4xclvEfFFQhASKjY48t9E7gYg0qterZKspNBVDw0Zd6OP/Lg4NxmdafPlkhD5JTQA==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-a2a-yaml-1/-/apidom-parser-adapter-a2a-yaml-1-1.14.0.tgz", + "integrity": "sha512-osK6KbCLUS12fMtjIQ/GZ8SbVZVoe0t9Lhb9IO4WSQz75R2YUdU/iB8Jx93SciiHjCQ/1iRI+EBfUZkmyzbeIw==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-a2a-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-a2a-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-api-design-systems-json": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-api-design-systems-json/-/apidom-parser-adapter-api-design-systems-json-1.13.3.tgz", - "integrity": "sha512-eaoQxXaMBBqYlNxYDbmzNyYCfn73TiqVuTQxfDNENtQmX36w3c/T7fBwOjfL41GqzzJF6pzVvu3jFHOFgse0Ww==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-api-design-systems-json/-/apidom-parser-adapter-api-design-systems-json-1.14.0.tgz", + "integrity": "sha512-Ga4ibi3XL4QPVKInUID5mbsX6wfDZ0awHHtLPktxkEauZdh/O/VAnvL7s559wJcFltNaHAQkHq0c2WPVkwxjZw==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-api-design-systems": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-api-design-systems": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-api-design-systems-yaml": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-api-design-systems-yaml/-/apidom-parser-adapter-api-design-systems-yaml-1.13.3.tgz", - "integrity": "sha512-Ne6oCXVaanpN1h4ThuOhiF4HDUN3lZmSfpkJt5qJrsMYNGIVqIIEjrqhVs3MDK+gSa+oQszHnbZSkePz+6dsJQ==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-api-design-systems-yaml/-/apidom-parser-adapter-api-design-systems-yaml-1.14.0.tgz", + "integrity": "sha512-6FWu5PsI/0YJts0GCF3+0EcBHteoV1oVVaKhf9cT2ZehG3fXHtgmz3lviG+CtdolIQ5+k4NNPvWXmECzZo96fg==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-api-design-systems": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-api-design-systems": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-arazzo-json-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-arazzo-json-1/-/apidom-parser-adapter-arazzo-json-1-1.13.3.tgz", - "integrity": "sha512-UTV8YHKZInMCyXDBQq4rmgW+dK9rQ7tjRFjr4lzXWMZuBPcd0+ot4Wh0azn7NC8vXqa1qBX6a+pqX9hUVLRXQA==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-arazzo-json-1/-/apidom-parser-adapter-arazzo-json-1-1.14.0.tgz", + "integrity": "sha512-CBSyZX+g3A7x9WPzve97gRNibgVXobPgEYaRBMkfEun51rsygI33yMOpmEBi7xu3FV7h8SQiB268krhCjfKaYw==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-arazzo-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-arazzo-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-arazzo-yaml-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-arazzo-yaml-1/-/apidom-parser-adapter-arazzo-yaml-1-1.13.3.tgz", - "integrity": "sha512-s0eT30Yy0izzZIRSJfQedwI0nOFMLs5E5wRzAUje8DI2qdSlFjA1AFtDtylMq9TQPn9y6AG2ysPy/TecfigdbQ==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-arazzo-yaml-1/-/apidom-parser-adapter-arazzo-yaml-1-1.14.0.tgz", + "integrity": "sha512-zDjsCgVDcFS/+YWZgSD3vJK4rzOZCg+HvcNEsCV9lO7FfN/jXykWFlFTkWDfSrSEoltRbWAzV5hd/etEvpjbjQ==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-arazzo-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-arazzo-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-asyncapi-json-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-json-2/-/apidom-parser-adapter-asyncapi-json-2-1.13.3.tgz", - "integrity": "sha512-u7OXUI17VK+SX6j8whSBNPnMl85fvexFyu1lbrdpNIJP3gojUgvSZN6g9w0pII7VYBfsYDkDLKQemYVQtK4jEA==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-json-2/-/apidom-parser-adapter-asyncapi-json-2-1.14.0.tgz", + "integrity": "sha512-DwQpgYw8s9cLbxUtrP8psFzqoR52Bn1+r7a2khLxTebUgfUYLn8orffvq/xppx3lf2Rnvqgey7wPy0eI5WUoag==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-asyncapi-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-asyncapi-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-asyncapi-json-3": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-json-3/-/apidom-parser-adapter-asyncapi-json-3-1.13.3.tgz", - "integrity": "sha512-Z65quIJg7z74wGJH/JuAbGM92FsWxmHKrZQl7/0yMAzI56mATUTgDWNXbm51JypRzSA393MKpFzy0dinU0eN+A==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-json-3/-/apidom-parser-adapter-asyncapi-json-3-1.14.0.tgz", + "integrity": "sha512-V4BA10W8x0z/ZRpcRGjVdjKAxLC9eByrGDJjMYRQrEBOKGnUSkIE/xg3N7adp+SHSFem76H4Ez8+e4op67RQsw==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-asyncapi-3": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-asyncapi-3": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-asyncapi-yaml-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-yaml-2/-/apidom-parser-adapter-asyncapi-yaml-2-1.13.3.tgz", - "integrity": "sha512-18m7ubllmlEp1xUL2idh7u5QgJbQVkLVYtQvIalvVHC8Lr6I4kbG4LiZXjxGx1SBg+BpPV1jjlQ+bG+Iz4Vh7w==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-yaml-2/-/apidom-parser-adapter-asyncapi-yaml-2-1.14.0.tgz", + "integrity": "sha512-w5+0L5sZKbmjcx06Y1me6nK8v+q9n013hL19DzmU0EhVn9rWrqWg891irWwkOqmfJmCcuz8NVBIwqNMxDJy5Fg==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-asyncapi-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-asyncapi-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-asyncapi-yaml-3": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-yaml-3/-/apidom-parser-adapter-asyncapi-yaml-3-1.13.3.tgz", - "integrity": "sha512-iuLrgNFv1mujaHkeO1xTRvrP28RMtwT3D6zq8RmqHrdlXEYd9RFTsecuBBax6ZyB4WRU3r/bbTPhy2UfhM0vaw==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-yaml-3/-/apidom-parser-adapter-asyncapi-yaml-3-1.14.0.tgz", + "integrity": "sha512-TQpWTTJNg0eSxv8xpTJGOwMlftuHY/YeVpBphA9Ssk22K8ImmB/pZQGhE5oUJ7M7mbgXvlJOtkbuBFDQ7ji3Eg==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-asyncapi-3": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-asyncapi-3": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-json": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-json/-/apidom-parser-adapter-json-1.13.3.tgz", - "integrity": "sha512-1TbxPuoh+ZSoGo0bcGnAeOFANU8GPTYVt1jsDnVIhNQL/DU/27hCuKse5xiystKNt6qiGyAQ1wEKqtaBedojzg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-json/-/apidom-parser-adapter-json-1.14.0.tgz", + "integrity": "sha512-6dUeLKjA/h62ost0ZMXAUBdfFvSRINuDh1U+9VVHkERq9ZsOmetLon+7T9UGkJPIi2R0r/Qr49LjuMGtnAE5JA==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-ast": "^1.13.3", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", + "@swagger-api/apidom-ast": "^1.14.0", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0", @@ -5092,145 +4987,177 @@ "web-tree-sitter": "=0.24.5" } }, - "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-2/-/apidom-parser-adapter-openapi-json-2-1.13.3.tgz", - "integrity": "sha512-gwc2lBGvmMlHXPKU5a8isCbGvo1CDg84uEjp3A/zT3SSYXaEBKOqrqLFvSVoPAtVo3tpTTwtSoxodESxdl1YLw==", + "node_modules/@swagger-api/apidom-parser-adapter-json-schema-json-2020-12": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-json-schema-json-2020-12/-/apidom-parser-adapter-json-schema-json-2020-12-1.14.0.tgz", + "integrity": "sha512-PYB86bWah0dYBVnsFk7yi9E6clRLn45VaBWSE418c2kCI8q7Bpm+URSnR0LUYLHV573BMY7UKpi7/W8fP23f6A==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-openapi-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-2020-12": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", + "@types/ramda": "~0.30.0", + "ramda": "~0.30.0", + "ramda-adjunct": "^5.0.0" + } + }, + "node_modules/@swagger-api/apidom-parser-adapter-json-schema-yaml-2020-12": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-json-schema-yaml-2020-12/-/apidom-parser-adapter-json-schema-yaml-2020-12-1.14.0.tgz", + "integrity": "sha512-S869/DexEyiZsybmNvNJW5q/+JMP2PkufKCBjwpxqWCcFFGaJenwjaIvTJX1tfKrpc/cuBlviaKeyNA+cCaWBA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@babel/runtime-corejs3": "^7.26.10", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-2020-12": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", + "@types/ramda": "~0.30.0", + "ramda": "~0.30.0", + "ramda-adjunct": "^5.0.0" + } + }, + "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-2": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-2/-/apidom-parser-adapter-openapi-json-2-1.14.0.tgz", + "integrity": "sha512-50dRHYztd1DxZTrKjjoBxvWskRAqn9OdP5JtfO3UkARxG0tNsQrNzcYFuO39OZnBxpE3h+1WChmHNL+c3jvTNw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@babel/runtime-corejs3": "^7.26.10", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-openapi-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-3-0": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-0/-/apidom-parser-adapter-openapi-json-3-0-1.13.3.tgz", - "integrity": "sha512-VrW34GMn8PerjUBCNDHJpulSEAH8BsUAV09jPw4PhVsIFSombRbEflLDH8cpmLYS4l2ywNVgn6YiZKy92jnJ6Q==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-0/-/apidom-parser-adapter-openapi-json-3-0-1.14.0.tgz", + "integrity": "sha512-Q96xoMKQ+tg1/bVD2XmRgFU1HW/T+gb8MtR+UDkpRMEyylPi2ODJE8sfoL/oKlo2RuzHSi0giJ2RnFVkZLZFTg==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-0": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-0": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-3-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-1/-/apidom-parser-adapter-openapi-json-3-1-1.13.3.tgz", - "integrity": "sha512-h06hVkFgpRiyWes2kRBKvquAVozIjAXBmEV7xowyo1hRyE+45VFPjey/pdaV6YWiSCekLZ2kRYh4U4b+U+oL0w==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-1/-/apidom-parser-adapter-openapi-json-3-1-1.14.0.tgz", + "integrity": "sha512-sXzDeTnY/VHH5Fd0gxS9JiOISU/U/YEWwdL+wYXXJPjDr0dddhTSad7+QMxP1BkqBJEIuS87Jmfv5qOAFV79Mw==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-3-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-2/-/apidom-parser-adapter-openapi-json-3-2-1.13.3.tgz", - "integrity": "sha512-QsVjugqHqwM4VvN2DIIHpHt+5clvliHOBAj/WBYeiCBTBBI6m1/2hlG2Vu7jyMEpA88ML1WLK8JOHf2+fOwN1A==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-2/-/apidom-parser-adapter-openapi-json-3-2-1.14.0.tgz", + "integrity": "sha512-vgcy8rsMwxcsS8xtJ0qJwy93zrHZ85YooHtc8ny2zCAKEv7QlKjXYdX1bDUskdxOV3Xh8ZaS5XPBqvL4DFS8/g==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-openapi-yaml-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-2/-/apidom-parser-adapter-openapi-yaml-2-1.13.3.tgz", - "integrity": "sha512-lWTxEXmISAE5qN3H0sKLZyNdlBTM3LwyeRbkuGSLbzT8SyIAL37chiuYaBNRfdA1Y8x9xbIdimCWZpACet4Glw==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-2/-/apidom-parser-adapter-openapi-yaml-2-1.14.0.tgz", + "integrity": "sha512-oQS4SEjBfoEp0MMs2m6+4YIh+tqgs/PklSW9vdIhMbc4tbluM7Ro8tJXeIh3aS5lSyeN7ReJg9aJhzDooeWoAg==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-openapi-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-openapi-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-openapi-yaml-3-0": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-0/-/apidom-parser-adapter-openapi-yaml-3-0-1.13.3.tgz", - "integrity": "sha512-EDmWNX7OFaHQl8YIRNdH06aehJZr3qt+1p2Qzrc2vn0adnmw9lQX3FvBUI44A5w3R/Q2z0iMtOXIo3baqr7MZQ==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-0/-/apidom-parser-adapter-openapi-yaml-3-0-1.14.0.tgz", + "integrity": "sha512-WCyBR8Ca1ge8XT54nDvHnoYbGCOpOOb6VOLlzrMOy/ikF7JKR+A9IuqRkqPEuhUjjxr5Dc1Edv4NlivFykEdqA==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-0": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-0": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-openapi-yaml-3-1": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-1/-/apidom-parser-adapter-openapi-yaml-3-1-1.13.3.tgz", - "integrity": "sha512-0Qi+dK+6F6cgu0GTm1Y/tCSbhN6zZI9iULjLPNsQYLZEKvUzo56FFcGVIOaYveG7qguXKC9YQ9bZcS1ZqhgS1Q==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-1/-/apidom-parser-adapter-openapi-yaml-3-1-1.14.0.tgz", + "integrity": "sha512-m1CwUYTgK0zvs0AndrdzKuL5FNfez6lag9nEsKfumoJJ1T/kev7Yo3jmPC++lLGsnJGbagIAkZ2nIBC5BuVKvQ==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-openapi-yaml-3-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-2/-/apidom-parser-adapter-openapi-yaml-3-2-1.13.3.tgz", - "integrity": "sha512-dL3vJ8kFSvh9mmlHM1Cl8hNFJWHQ8CpypkfN7QTuMHIVJruvOwJ2VWhNXM8GTH07ytFg8cFto0UAGYgG2E/raw==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-2/-/apidom-parser-adapter-openapi-yaml-3-2-1.14.0.tgz", + "integrity": "sha512-4G6gEAp742YgXUocebXTDitiDkVvK30ceZFLvCmKaeuw1VsQJ/yNWGzTxkB25F0qbgdFGzceGJlX9eJx/svlGg==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", "ramda-adjunct": "^5.0.0" } }, "node_modules/@swagger-api/apidom-parser-adapter-yaml-1-2": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-yaml-1-2/-/apidom-parser-adapter-yaml-1-2-1.13.3.tgz", - "integrity": "sha512-6jNhcCGnEE35dCG1NGEEddUb26kFU8VzuBoCJpOeCOJcKcsVehSpS2igD9bOVepoWMORRRE7CQkcCjoKMk95Xg==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-yaml-1-2/-/apidom-parser-adapter-yaml-1-2-1.14.0.tgz", + "integrity": "sha512-ckzyyfgJUH+rEajzlrFaCwqc/K19KIIN1V9/zaVugDdxe1LLbtk11RQQa6AetkpeQdYVPzTMHIpKGluGyhZ1Bg==", "license": "Apache-2.0", "optional": true, "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-ast": "^1.13.3", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", + "@swagger-api/apidom-ast": "^1.14.0", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", "@tree-sitter-grammars/tree-sitter-yaml": "=0.7.1", "@types/ramda": "~0.30.0", "ramda": "~0.30.0", @@ -5272,14 +5199,14 @@ } }, "node_modules/@swagger-api/apidom-reference": { - "version": "1.13.3", - "resolved": "https://registry.npmjs.org/@swagger-api/apidom-reference/-/apidom-reference-1.13.3.tgz", - "integrity": "sha512-mOJ7ANqcrxhzGHPybNuzAV8Ytm7gCGRj+S4xOkNmg7cerPmMgUxTwhDPF3FDQ/wUfQL+jjdYef2IydwdOxab+A==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@swagger-api/apidom-reference/-/apidom-reference-1.14.0.tgz", + "integrity": "sha512-LCp15dZ61tEEMYsZY65qbRTx0KEqwO8j2qNowV3rADQa91x3QKPo8V1mcGAh+DUGun3m3hjh72c5rLsJCb6zSg==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.26.10", - "@swagger-api/apidom-core": "^1.13.3", - "@swagger-api/apidom-error": "^1.13.3", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", "@types/ramda": "~0.30.0", "axios": "^1.20.0", "minimatch": "^10.2.6", @@ -5287,34 +5214,37 @@ "ramda-adjunct": "^5.0.0" }, "optionalDependencies": { - "@swagger-api/apidom-json-pointer": "^1.13.3", - "@swagger-api/apidom-ns-a2a-1": "^1.13.3", - "@swagger-api/apidom-ns-arazzo-1": "^1.13.3", - "@swagger-api/apidom-ns-asyncapi-2": "^1.13.3", - "@swagger-api/apidom-ns-openapi-2": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-0": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-1": "^1.13.3", - "@swagger-api/apidom-ns-openapi-3-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-a2a-json-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-a2a-yaml-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-api-design-systems-json": "^1.13.3", - "@swagger-api/apidom-parser-adapter-api-design-systems-yaml": "^1.13.3", - "@swagger-api/apidom-parser-adapter-arazzo-json-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-arazzo-yaml-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-asyncapi-json-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-asyncapi-json-3": "^1.13.3", - "@swagger-api/apidom-parser-adapter-asyncapi-yaml-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-asyncapi-yaml-3": "^1.13.3", - "@swagger-api/apidom-parser-adapter-json": "^1.13.3", - "@swagger-api/apidom-parser-adapter-openapi-json-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-openapi-json-3-0": "^1.13.3", - "@swagger-api/apidom-parser-adapter-openapi-json-3-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-openapi-json-3-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-openapi-yaml-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-openapi-yaml-3-0": "^1.13.3", - "@swagger-api/apidom-parser-adapter-openapi-yaml-3-1": "^1.13.3", - "@swagger-api/apidom-parser-adapter-openapi-yaml-3-2": "^1.13.3", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.13.3" + "@swagger-api/apidom-json-pointer": "^1.14.0", + "@swagger-api/apidom-ns-a2a-1": "^1.14.0", + "@swagger-api/apidom-ns-arazzo-1": "^1.14.0", + "@swagger-api/apidom-ns-asyncapi-2": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-2020-12": "^1.14.0", + "@swagger-api/apidom-ns-openapi-2": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-0": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-1": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-a2a-json-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-a2a-yaml-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-api-design-systems-json": "^1.14.0", + "@swagger-api/apidom-parser-adapter-api-design-systems-yaml": "^1.14.0", + "@swagger-api/apidom-parser-adapter-arazzo-json-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-arazzo-yaml-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-asyncapi-json-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-asyncapi-json-3": "^1.14.0", + "@swagger-api/apidom-parser-adapter-asyncapi-yaml-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-asyncapi-yaml-3": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json-schema-json-2020-12": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json-schema-yaml-2020-12": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-json-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-json-3-0": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-json-3-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-json-3-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-yaml-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-yaml-3-0": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-yaml-3-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-yaml-3-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0" } }, "node_modules/@swaggerexpert/cookie": { @@ -5342,13 +5272,10 @@ } }, "node_modules/@swc/helpers": { - "version": "0.5.23", - "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", - "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.8.0" - } + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz", + "integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==", + "license": "Apache-2.0" }, "node_modules/@tanstack/match-sorter-utils": { "version": "9.2.6", @@ -5367,9 +5294,9 @@ } }, "node_modules/@tanstack/query-core": { - "version": "5.105.1", - "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.105.1.tgz", - "integrity": "sha512-B/rNlZoZ54w1dlddiUt9oEe1SLM+37c00SKLJEg9YH+7as3Y54P81o9Fh+2ujZ36tXPnQJ5oVe7AcyEWkyFhPg==", + "version": "5.107.1", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.107.1.tgz", + "integrity": "sha512-PSyAik11oQBEVOiVy5hjZWHmoUqOXqK1WYy4v55mcxozEfKaQgpUMsgnXhWjuESzSht8JfzqMS1m6M/9CpNgvg==", "license": "MIT", "funding": { "type": "github", @@ -5377,9 +5304,9 @@ } }, "node_modules/@tanstack/query-devtools": { - "version": "5.105.1", - "resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.105.1.tgz", - "integrity": "sha512-3iHdlC/S1e1W+7bemP5WN/feZapc0WW6XHXtmfY3AmWVlA20tEK4WxVXcKhh7IngjPGHlY6eXi1MVkrHuaxDzQ==", + "version": "5.107.1", + "resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.107.1.tgz", + "integrity": "sha512-cZvgIPNvsh57mM3yTTwuL2GUMmMp5XR+3k5r2UJDyStmPYCqSwZf8z7OulgA4X8vISziAG5PoykbQ1q+2zemdA==", "license": "MIT", "dependencies": { "@kobalte/core": "^0.13.14", @@ -5387,7 +5314,8 @@ "@solid-primitives/resize-observer": "^2.2.0", "@solid-primitives/storage": "^1.3.11", "@tanstack/match-sorter-utils": "^9.1.2", - "@tanstack/query-core": "5.105.1", + "@tanstack/query-core": "5.107.1", + "@tanstack/solid-virtual": "^3.13.52", "clsx": "^2.1.1", "goober": "^2.1.19", "solid-js": "^1.9.15", @@ -5400,12 +5328,12 @@ } }, "node_modules/@tanstack/react-query": { - "version": "5.105.1", - "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.105.1.tgz", - "integrity": "sha512-qcu+/+PtBOjW8qU4/0l47QVmNG7hPOWsCLzP0bTRhE1X7HYa757C4732wXTUH0QhCjTV1yedX8onsCiEwlNYrA==", + "version": "5.107.1", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.107.1.tgz", + "integrity": "sha512-udCOOLp3ZAheUrIHLCe+ZZge6nr2ZUrGMSWcCuXsjY1Bf2JeeE09oxst97PILiCY6N8xo/7bIo3Hvz13zh06FA==", "license": "MIT", "dependencies": { - "@tanstack/query-core": "5.105.1" + "@tanstack/query-core": "5.107.1" }, "funding": { "type": "github", @@ -5422,19 +5350,19 @@ } }, "node_modules/@tanstack/react-query-devtools": { - "version": "5.105.1", - "resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.105.1.tgz", - "integrity": "sha512-VJwunCp9fPbGGkbXlKn4T8w20sNdlFZoMqTjOdzqdhfk0Ujthln4LSN7xkVLCTAq0OGaV/0srQ/5esNpaktRvw==", + "version": "5.107.1", + "resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.107.1.tgz", + "integrity": "sha512-A3q9X3iOxtlz1jU/ou7t9CFvNHT84rTMofS1YEkFcBalvwotZ/RJKPDsX1NsQVl10J8XwN0OYMSfdjgIElt0sg==", "license": "MIT", "dependencies": { - "@tanstack/query-devtools": "5.105.1" + "@tanstack/query-devtools": "5.107.1" }, "funding": { "type": "github", "url": "https://github.com/sponsors/tannerlinsley" }, "peerDependencies": { - "@tanstack/react-query": "^5.105.1", + "@tanstack/react-query": "^5.107.1", "@types/react": "^18 || ^19", "react": "^18 || ^19" }, @@ -5461,7 +5389,7 @@ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, - "node_modules/@tanstack/virtual-core": { + "node_modules/@tanstack/react-virtual/node_modules/@tanstack/virtual-core": { "version": "3.17.8", "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.17.8.tgz", "integrity": "sha512-BfEvehNpOT75r5Ksc5xW6NZuXujTfb7nlSEyVu4XHG3gdxNg1KqXruWbDewXOUaUYIo4oRbSfkjIajz4MAT8tA==", @@ -5471,6 +5399,32 @@ "url": "https://github.com/sponsors/tannerlinsley" } }, + "node_modules/@tanstack/solid-virtual": { + "version": "3.13.53", + "resolved": "https://registry.npmjs.org/@tanstack/solid-virtual/-/solid-virtual-3.13.53.tgz", + "integrity": "sha512-LUdGSmkTkwtpUea4w7bJp6N6ErnNkWT5iXpvn0mI9ijjtVrOa0JkSX8ZhQfNZxbhm4cnlGYbz/U1SQn/LqSNlw==", + "license": "MIT", + "dependencies": { + "@tanstack/virtual-core": "3.19.11" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "solid-js": "^1.3.0" + } + }, + "node_modules/@tanstack/virtual-core": { + "version": "3.19.11", + "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.19.11.tgz", + "integrity": "sha512-/5iHb0RHBvj8Di59FDs4ESNm45jls33aZAi4zccVXZjc/6ZvwQP6nzEYeT6weXjTf9E6/vrp2JhYWRyO+ZP13A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, "node_modules/@testing-library/dom": { "version": "10.4.2", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", @@ -5547,9 +5501,9 @@ } }, "node_modules/@testing-library/user-event": { - "version": "14.6.8", - "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.8.tgz", - "integrity": "sha512-vgSSqnANMnkcYR/vUNDbwS7aM3OErRLNUG8vCVVlj4oc6cKffUrccX7UAS5AmJQQNZTSibi9z5GvvRZ0aYgUCQ==", + "version": "14.6.9", + "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.9.tgz", + "integrity": "sha512-/8boTjZHNXFi8JGUI2Ev05cq0Szh0OX35Bamkq6CK1ne+l1Xm8BKE3+nGgsnFgaYk0MX67Vh59cZDsNz5lJJEg==", "dev": true, "license": "MIT", "engines": { @@ -6100,9 +6054,9 @@ } }, "node_modules/@vitejs/plugin-react": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", - "integrity": "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz", + "integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==", "dev": true, "license": "MIT", "dependencies": { @@ -6112,9 +6066,9 @@ "node": "^20.19.0 || >=22.12.0" }, "peerDependencies": { - "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", "babel-plugin-react-compiler": "^1.0.0", - "oxc-transform-react": "^0.152.0", + "oxc-transform-react": ">=0.152.0 <0.157.0", "vite": "^8.0.0" }, "peerDependenciesMeta": { @@ -6130,16 +6084,16 @@ } }, "node_modules/@vitest/browser": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/browser/-/browser-5.0.5.tgz", - "integrity": "sha512-IDMoZX/iZ8rkilw7weaSgN8tJ7iZ9hUv0wYoKXyiyjWjWFwLSWAY707DcVTgxTYOudWC1E3HA9LYn7kVa9a7uQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/browser/-/browser-5.1.0.tgz", + "integrity": "sha512-2sjGVAC/Rs8Jwv+xxBgklNG2g1LGyNgcFMBw71AcfBstLz25UGv1+fVvvZ+z8IfSuNg3nipERijnFtoEIdRDEA==", "dev": true, "license": "MIT", "dependencies": { "@blazediff/core": "1.10.0", - "@vitest/mocker": "5.0.5", - "@vitest/ui": "5.0.5", - "@vitest/utils": "5.0.5", + "@vitest/mocker": "5.1.0", + "@vitest/ui": "5.1.0", + "@vitest/utils": "5.1.0", "magic-string": "^1.4.3", "pngjs": "^7.0.0", "sirv": "^3.0.2", @@ -6150,18 +6104,18 @@ "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "vitest": "5.0.5" + "vitest": "5.1.0" } }, "node_modules/@vitest/browser-playwright": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/browser-playwright/-/browser-playwright-5.0.5.tgz", - "integrity": "sha512-lcdThFUUcMV9mGGV1SUiZXPxfjgW4CssA7o3STxzh8WK0tT2r526kc12tZIBRZfoLMwkhxjLmMXkWXONzdsDQw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/browser-playwright/-/browser-playwright-5.1.0.tgz", + "integrity": "sha512-3PbVvX/KNeUEzUeTTXw5bQDyfJS+WqU/UJ8RNWIojHb0mE6d/IBjuLmt+i7OpJ00tjNWv0O6XBm5ler/tEf3eg==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/browser": "5.0.5", - "@vitest/mocker": "5.0.5", + "@vitest/browser": "5.1.0", + "@vitest/mocker": "5.1.0", "tinyrainbow": "^3.2.0" }, "funding": { @@ -6169,7 +6123,7 @@ }, "peerDependencies": { "playwright": "*", - "vitest": "5.0.5" + "vitest": "5.1.0" }, "peerDependenciesMeta": { "playwright": { @@ -6178,15 +6132,15 @@ } }, "node_modules/@vitest/coverage-v8": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.0.5.tgz", - "integrity": "sha512-4KpkGdIrSqBihx/JyP/e+S+IKB98etg1XDQiLAxksLfcShnwi1VReGeOT9NI43hLHbknosKp/1CCLn9Zgcs8mg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.1.0.tgz", + "integrity": "sha512-OY9aShBQG5KOIw2zCo9fDoCHI9RHliNHJ//nM7m6jGg41Hyke9JOGWmeMlK74xYErsxMoK8mIB3gAeEyFVA7LA==", "dev": true, "license": "MIT", "dependencies": { "@bcoe/v8-coverage": "^1.0.2", - "@vitest/istanbul-lib-coverage": "^1.0.2", - "@vitest/istanbul-lib-report": "^1.0.2", + "@vitest/istanbul-lib-coverage": "^2.1.0", + "@vitest/istanbul-lib-report": "^2.1.0", "ast-v8-to-istanbul": "^1.0.7", "magicast": "^0.5.5", "obug": "^3.0.0", @@ -6197,8 +6151,8 @@ "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "@vitest/browser": "5.0.5", - "vitest": "5.0.5" + "@vitest/browser": "5.1.0", + "vitest": "5.1.0" }, "peerDependenciesMeta": { "@vitest/browser": { @@ -6275,9 +6229,9 @@ } }, "node_modules/@vitest/istanbul-lib-coverage": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-1.0.2.tgz", - "integrity": "sha512-9J/JMwOf9AoJhAywhrn7ScKTL38hsWQP/qPG60OtaAFcQ5OXPwKsxZFlbnuCKmZ61m8/lGgHYnFpdyQZUvG/iA==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-2.1.0.tgz", + "integrity": "sha512-WOjuS+xcjSIy7ruYBQ+9BUcV7XZQ0FyVcbWbWxW9TRx/kLGx5SQaeFRIFDJxjNplb6YsT7SpKo2zuXXUo91OIQ==", "dev": true, "license": "MIT", "engines": { @@ -6285,27 +6239,27 @@ } }, "node_modules/@vitest/istanbul-lib-report": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-1.0.2.tgz", - "integrity": "sha512-gUsfXZJbzPamoIY5TvHFiMMoXESBrUMo+xqaj+rYrWI69+EnvRlYBlP96ZnHPY4vX8kyUpgAnFUCg5wZG/HkDQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-2.1.0.tgz", + "integrity": "sha512-+ZFta25nWtGCOBG9/IET8w1RO5Oawsd6H8Uf6AJ9EA/StFuKVtKAEJEJ6uRt84OH+T4YkI0ASmIHAhRA+0KVxw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/istanbul-lib-coverage": "1.0.2" + "@vitest/istanbul-lib-coverage": "2.1.0" }, "engines": { "node": ">=22" } }, "node_modules/@vitest/mocker": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", - "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", "dev": true, "license": "MIT", "dependencies": { "@jridgewell/trace-mapping": "0.3.31", - "@vitest/spy": "5.0.5", + "@vitest/spy": "5.1.0", "estree-walker": "^3.0.3", "magic-string": "^1.4.3" }, @@ -6336,9 +6290,9 @@ } }, "node_modules/@vitest/pretty-format": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-5.0.5.tgz", - "integrity": "sha512-24sSdIlMA9DVPXnYiB9siwU0bTd887Y9jX3+vabztCSsvHwo7ipvJ/a2L3Rljw8+2rK1f5fCj3h5U9I/Jsqgbw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-5.1.0.tgz", + "integrity": "sha512-IRx5mc30CrFzyMNni6SZKQ1r53kv049Mcvvk0WbWcD6PUz/bFjG4zYv0KosQAeonPpGp5WxqYBMqdSOfJfvVWw==", "dev": true, "license": "MIT", "dependencies": { @@ -6349,9 +6303,9 @@ } }, "node_modules/@vitest/spy": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", - "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", "dev": true, "license": "MIT", "funding": { @@ -6359,13 +6313,13 @@ } }, "node_modules/@vitest/ui": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/ui/-/ui-5.0.5.tgz", - "integrity": "sha512-dCoGUOdgmCaSB2g+WQ/spPCBkytAWdNUkFSXY4z+eYp2d8JEOY8v0uDRaJTG9qf/kTlTVZ4CuYMYMz/f1HS/qQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/ui/-/ui-5.1.0.tgz", + "integrity": "sha512-00S3x4NRmqIBUiTVWF9/xLaA9EP9KeKv0+1sBO7e2Y4luBISlW+2ttnhlk/zjbTqEvVhJWCCo7MXzu6zNbefqQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "5.0.5", + "@vitest/utils": "5.1.0", "fflate": "^0.8.3", "flatted": "^3.4.4", "pathe": "^2.0.3", @@ -6376,17 +6330,17 @@ "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "vitest": "5.0.5" + "vitest": "5.1.0" } }, "node_modules/@vitest/utils": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-5.0.5.tgz", - "integrity": "sha512-/rBu7gzLDQI/SC79Tn98b5DwOgaHU/Gt4I9OVeP3YofzNaYtbImRCOJQmT1S6vOJg9gEIlWC+r3QxKkjuSa1nQ==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-5.1.0.tgz", + "integrity": "sha512-V+qgCwkvVw+s1t1S5TaoBHsLi5Sz/YmohCMoOu0mZ8ZQst2bKhRYARAQucWpVg8D0mv0x5MHcWXY5QdOsoiGBQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "5.0.5", + "@vitest/pretty-format": "5.1.0", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.2.0" }, @@ -6450,9 +6404,9 @@ } }, "node_modules/antd": { - "version": "6.6.8", - "resolved": "https://registry.npmjs.org/antd/-/antd-6.6.8.tgz", - "integrity": "sha512-e+hDj/0myqbLBn8UGS0dYhPROAENruNscWe4gzyTnwx7yTip7D72wJUNxtsTplPXwRM1Mo4tXNSgaSb3UmV3RQ==", + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/antd/-/antd-6.7.0.tgz", + "integrity": "sha512-QwFK+butqX4HA3xG2zWN9OOQVLdlV4S3WC5BETtDEXGypBlSZy0LPFFwQIGJl10UtGAQi3p6Z4WiDVf7nr4FcA==", "license": "MIT", "dependencies": { "@ant-design/colors": "^8.0.1", @@ -6462,40 +6416,40 @@ "@ant-design/icons": "^6.3.4", "@ant-design/react-slick": "~2.0.0", "@babel/runtime": "^7.29.2", - "@rc-component/cascader": "~1.22.0", + "@rc-component/cascader": "~1.26.0", "@rc-component/checkbox": "~2.0.0", - "@rc-component/collapse": "~1.2.0", + "@rc-component/collapse": "~1.3.0", "@rc-component/color-picker": "~3.1.1", "@rc-component/dialog": "~1.10.0", "@rc-component/drawer": "~1.4.2", - "@rc-component/dropdown": "~1.0.3", + "@rc-component/dropdown": "~2.0.1", "@rc-component/form": "~1.8.6", "@rc-component/image": "~1.10.0", - "@rc-component/input": "~1.3.1", - "@rc-component/input-number": "~1.6.2", - "@rc-component/listy": "~1.2.3", - "@rc-component/mentions": "~1.12.0", - "@rc-component/menu": "~1.5.0", + "@rc-component/input": "~1.4.1", + "@rc-component/input-number": "~1.8.0", + "@rc-component/listy": "~1.4.0", + "@rc-component/mentions": "~1.14.1", + "@rc-component/menu": "~1.6.1", "@rc-component/motion": "^1.3.3", "@rc-component/mutate-observer": "^2.0.1", "@rc-component/notification": "~2.1.1", - "@rc-component/pagination": "~1.4.0", - "@rc-component/picker": "~1.12.2", - "@rc-component/progress": "~1.0.3", + "@rc-component/pagination": "~1.7.0", + "@rc-component/picker": "~1.17.0", + "@rc-component/progress": "~1.1.0", "@rc-component/qrcode": "~2.0.0", "@rc-component/rate": "~1.0.1", "@rc-component/resize-observer": "^1.1.2", "@rc-component/segmented": "~1.4.0", - "@rc-component/select": "~1.10.1", - "@rc-component/slider": "~1.1.1", + "@rc-component/select": "~1.12.0", + "@rc-component/slider": "~1.2.1", "@rc-component/steps": "~1.2.3", "@rc-component/switch": "~1.0.3", - "@rc-component/table": "~1.11.1", - "@rc-component/tabs": "~1.13.0", + "@rc-component/table": "~1.12.0", + "@rc-component/tabs": "~2.0.0", "@rc-component/tooltip": "~1.5.2", "@rc-component/tour": "~2.4.0", - "@rc-component/tree": "~1.4.0", - "@rc-component/tree-select": "~1.16.1", + "@rc-component/tree": "~1.5.3", + "@rc-component/tree-select": "~1.19.0", "@rc-component/trigger": "^3.10.1", "@rc-component/upload": "~1.1.1", "@rc-component/util": "^1.14.0", @@ -6559,9 +6513,9 @@ } }, "node_modules/ast-v8-to-istanbul": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.7.tgz", - "integrity": "sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.8.tgz", + "integrity": "sha512-lPdpagk13ANXV+HClJEpCZM7kUsl5XcvgqKzZhaj6Ve1ZFICcY2sGhAN1n1vT0tML6EclT7bfVgTxqL57Gkpow==", "dev": true, "license": "MIT", "dependencies": { @@ -6628,12 +6582,12 @@ } }, "node_modules/axios": { - "version": "1.21.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.21.0.tgz", - "integrity": "sha512-YCzXMB53Q9PZBsh7yN7wtapit4WepwcHS2fP8QhGsBxSz5YtgYobV7GGlWlAJi+RxfU77GQTQi2DSLUma42EYA==", + "version": "1.21.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.21.1.tgz", + "integrity": "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==", "license": "MIT", "dependencies": { - "follow-redirects": "^1.16.0", + "follow-redirects": "^1.16.2", "form-data": "^4.0.6", "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" @@ -6669,9 +6623,9 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.11.34", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz", - "integrity": "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA==", + "version": "2.11.35", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.35.tgz", + "integrity": "sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -6681,20 +6635,37 @@ "node": ">=6.0.0" } }, - "node_modules/bidi-js": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", - "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", "dev": true, "license": "MIT", "dependencies": { - "require-from-string": "^2.0.2" + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, "node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" @@ -6825,9 +6796,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001820", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001820.tgz", - "integrity": "sha512-gfWD6MxqVCqAOwmODfZf7DchWvlrA+SRdNX7ceLfg3xRqe5ssjjpF7EgslC/0tiLiNTajdaNN/q8c/5u/7Gz8w==", + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", "dev": true, "funding": [ { @@ -6998,10 +6969,13 @@ } }, "node_modules/compute-scroll-into-view": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.1.1.tgz", - "integrity": "sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==", - "license": "MIT" + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.2.0.tgz", + "integrity": "sha512-XoIY5SQr8LvsgdyucinWuP34RJ4mjTjJMLUoP7rRD/HyxxVMfjtjL7biNiuPFz1QoduEV54p/XMVdjiHzNSMgg==", + "license": "MIT", + "engines": { + "node": ">=26" + } }, "node_modules/convert-source-map": { "version": "2.0.0", @@ -7011,9 +6985,9 @@ "license": "MIT" }, "node_modules/cookie": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.1.tgz", - "integrity": "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.2.tgz", + "integrity": "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==", "dev": true, "license": "MIT", "engines": { @@ -7071,20 +7045,6 @@ "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", "license": "MIT" }, - "node_modules/css-tree": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", - "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", - "dev": true, - "license": "MIT", - "dependencies": { - "mdn-data": "2.27.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" - } - }, "node_modules/css.escape": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", @@ -7324,9 +7284,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.472", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.472.tgz", - "integrity": "sha512-s4+nfT29b0FKpVKoaIxl2pWsoNcn7A/nMPSrxayw4T3BsmPeV2lF9Y06BsAQeMGhCTQ4nYJ5XST7jkqe4ZEqFw==", + "version": "1.5.481", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.481.tgz", + "integrity": "sha512-dNUsbAP6E2S1dHIYEuN3cQ0dViThjMtpVRheGdvv5HgHFtzLi4Cu4Mbzms85YggP3Eh2VVZTl5+XxEN8ofCbmQ==", "dev": true, "license": "ISC" }, @@ -7348,9 +7308,9 @@ } }, "node_modules/entities": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", - "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", "dev": true, "license": "BSD-2-Clause", "engines": { @@ -7584,9 +7544,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.2.tgz", - "integrity": "sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==", + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", "funding": [ { "type": "individual", @@ -7737,13 +7697,13 @@ } }, "node_modules/glob": { - "version": "14.0.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.3.tgz", - "integrity": "sha512-A1vjIwC3qpdCso45Iw127gnp7sPhqgY8lUQhDrArIs+GbmfaaVPFuoyy7WyLT9EPZCRZ7j7aLdwUhQmHWesEow==", + "version": "14.0.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.4.tgz", + "integrity": "sha512-mMiwNKoJZ4HAIRVJxotO6LsNRReA30gQwP9E2/p94tfLv+jygCNpKDjhhSL6OLY6LE371EZm5EAf7RpYuUqlsw==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "minimatch": "^11.0.2", + "minimatch": "^11.0.5", "minipass": "^7.1.3", "path-scurry": "^3.0.0" }, @@ -7934,9 +7894,9 @@ } }, "node_modules/i18next": { - "version": "26.6.0", - "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.6.0.tgz", - "integrity": "sha512-jpb1n5386s9mbBLNF6tSNIVhbBUUNiNeDyjWte+uxHP/Wr+CEy7WBM8q29TkfQ46VbwKeJFYdQJK3pSUhLp4CQ==", + "version": "27.1.1", + "resolved": "https://registry.npmjs.org/i18next/-/i18next-27.1.1.tgz", + "integrity": "sha512-Qq3aJizS3RXQ30crhx9BKQLrHoa6GKpgrOJjVZ9vgj3EBxAddrmVfDNUrAMxSUimw5Jc+ld4SSZUAzf1q4nGyQ==", "funding": [ { "type": "individual", @@ -7952,6 +7912,9 @@ } ], "license": "MIT", + "engines": { + "node": ">=22" + }, "peerDependencies": { "typescript": "^5 || ^6 || ^7" }, @@ -7982,9 +7945,9 @@ "license": "BSD-3-Clause" }, "node_modules/immutable": { - "version": "5.1.9", - "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.9.tgz", - "integrity": "sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==", + "version": "5.1.10", + "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.10.tgz", + "integrity": "sha512-Uu72qZXUtm+n98uML3Xr6pVFHl4xnmeCuAsrm0VqFlQim/Ib6NrPSJLpx6CrZ/G6DnoGaCUgtx8gY+o+ovxnCw==", "license": "MIT" }, "node_modules/indent-string": { @@ -8049,9 +8012,9 @@ } }, "node_modules/is-core-module": { - "version": "2.17.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", - "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.18.0.tgz", + "integrity": "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==", "dev": true, "license": "MIT", "dependencies": { @@ -8211,41 +8174,39 @@ } }, "node_modules/jsdom": { - "version": "30.1.3", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.3.tgz", - "integrity": "sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==", + "version": "31.0.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.0.tgz", + "integrity": "sha512-xAkhD9z1eyFC5+QUi9K24CaZJgdCQ2GOGLW1GdVDoQvkp/AxEH9TQ0pAplPOlIiV92hfcgnFOADZypbjgbBT6Q==", "dev": true, "license": "MIT", "dependencies": { - "@asamuzakjp/css-color": "^7.1.3", - "@asamuzakjp/dom-selector": "^10.0.3", - "@bramus/specificity": "^2.4.2", - "@csstools/css-syntax-patches-for-csstree": "^1.1.15", "@exodus/bytes": "^1.16.0", - "css-tree": "^3.2.1", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", "data-urls": "^8.0.0", "decimal.js": "^10.6.0", "html-encoding-sniffer": "^7.0.0", "is-potential-custom-element-name": "^1.0.1", "lru-cache": "^11.5.3", - "parse5": "^8.0.1", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", "saxes": "^6.0.0", "tough-cookie": "^6.0.2", - "undici": "^8.12.1", + "undici": "^8.12.3", "w3c-xmlserializer": "^6.0.0", "webidl-conversions": "^8.0.1", "whatwg-mimetype": "^5.0.0", - "whatwg-url": "^17.2.0", + "whatwg-url": "^17.3.0", "xml-name-validator": "^5.0.0" }, "engines": { "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "peerDependencies": { - "canvas": "^3.2.3" + "@napi-rs/canvas": "^1.0.13" }, "peerDependenciesMeta": { - "canvas": { + "@napi-rs/canvas": { "optional": true } } @@ -8685,13 +8646,6 @@ "node": ">= 0.4" } }, - "node_modules/mdn-data": { - "version": "2.27.1", - "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", - "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", - "dev": true, - "license": "CC0-1.0" - }, "node_modules/mime-db": { "version": "1.52.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", @@ -8736,16 +8690,16 @@ } }, "node_modules/minimatch": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.3.tgz", - "integrity": "sha512-iny/40PEGkNJQ5/Pv6z3nm6FbRAby32GeZRjCUJk2WnNDbgPSTcdI+DDvLqsgBdD4cD5sMtMheqPPnehCCa8Nw==", + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.0.3", + "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -8788,15 +8742,15 @@ "license": "MIT" }, "node_modules/msw": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/msw/-/msw-3.0.3.tgz", - "integrity": "sha512-hsXUCt2gK12q1IUBY9VmMun+yC60eEpVzegAFN5aGZbXhrGqtgPARVWn2ew4mezYvk1G8yhFha9myGSyRyRGWg==", + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/msw/-/msw-3.0.5.tgz", + "integrity": "sha512-RkzyWIaG+T2jYf9KOUrNOZuXl4sCpz35m13nVlt1ACFQhl/WjHU9zKMwlrR/6NatgKjL5U84UmVXOz9/+mvGsw==", "dev": true, "license": "MIT", "dependencies": { "@inquirer/confirm": "^6.0.11", "@msw/url": "^0.1.2", - "@mswjs/interceptors": "^0.45.6", + "@mswjs/interceptors": "^0.45.11", "cookie": "^2.0.1", "headers-polyfill": "^5.0.1", "is-node-process": "^1.2.0", @@ -8834,13 +8788,13 @@ } }, "node_modules/mute-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", - "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-4.0.0.tgz", + "integrity": "sha512-gSrprq0fJ3EiOErzjdIZrjysVVmJ4uu1QWfCDss5LypA5OXvrMje5Ym5z6V6RLyJ2eF87lasX7t6a0AnFvZblg==", "dev": true, "license": "ISC", "engines": { - "node": "^20.17.0 || >=22.9.0" + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" } }, "node_modules/nanoid": { @@ -8875,6 +8829,7 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/node-abort-controller/-/node-abort-controller-3.1.1.tgz", "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==", + "deprecated": "This package is no longer needed on supported Node.js versions. Node.js 16+ includes AbortController and AbortSignal as built-in globals. All Node.js versions requiring this polyfill are end-of-life. Use the built-in globals instead.", "license": "MIT" }, "node_modules/node-addon-api": { @@ -8976,9 +8931,9 @@ } }, "node_modules/otpauth": { - "version": "9.5.2", - "resolved": "https://registry.npmjs.org/otpauth/-/otpauth-9.5.2.tgz", - "integrity": "sha512-GQ5emWR/x1tcExT62IBT0UfO95wZzJZyxYOJOGVeQF47SYEN9vmh0vISvDZaNMuFJRG+IaWCKtfm+t9Bfoal6w==", + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/otpauth/-/otpauth-9.6.0.tgz", + "integrity": "sha512-qQXHTxcXohDhQjF1ZEbUVEpTIssFL2rd+2kHfw/McIVCbTLD6qAsbTCQxpXRLyeyUw6Ipjpykw4dWZL/zfIVqA==", "license": "MIT", "dependencies": { "@noble/hashes": "2.4.0" @@ -9064,9 +9019,9 @@ } }, "node_modules/oxfmt": { - "version": "0.75.0", - "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.75.0.tgz", - "integrity": "sha512-/ZKvY5asfsVi9hdkOmRIumqOPu6kxlTgiJSZf54uq29kKew+Gu1FFAnEkGePyvLVW+MAYu41D6XggnzoElQzPw==", + "version": "0.78.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.78.0.tgz", + "integrity": "sha512-uagX+70mKqh/YqxB6ON/lkxVPH6E1Z7pfP2x6XVRPPyiDCZtX6o1xIEeXAIXJ/2wA5ViX4RFuW+IAQn85yJdWg==", "dev": true, "license": "MIT", "dependencies": { @@ -9082,25 +9037,25 @@ "url": "https://github.com/sponsors/oxc-project" }, "optionalDependencies": { - "@oxfmt/binding-android-arm-eabi": "0.75.0", - "@oxfmt/binding-android-arm64": "0.75.0", - "@oxfmt/binding-darwin-arm64": "0.75.0", - "@oxfmt/binding-darwin-x64": "0.75.0", - "@oxfmt/binding-freebsd-x64": "0.75.0", - "@oxfmt/binding-linux-arm-gnueabihf": "0.75.0", - "@oxfmt/binding-linux-arm-musleabihf": "0.75.0", - "@oxfmt/binding-linux-arm64-gnu": "0.75.0", - "@oxfmt/binding-linux-arm64-musl": "0.75.0", - "@oxfmt/binding-linux-ppc64-gnu": "0.75.0", - "@oxfmt/binding-linux-riscv64-gnu": "0.75.0", - "@oxfmt/binding-linux-riscv64-musl": "0.75.0", - "@oxfmt/binding-linux-s390x-gnu": "0.75.0", - "@oxfmt/binding-linux-x64-gnu": "0.75.0", - "@oxfmt/binding-linux-x64-musl": "0.75.0", - "@oxfmt/binding-openharmony-arm64": "0.75.0", - "@oxfmt/binding-win32-arm64-msvc": "0.75.0", - "@oxfmt/binding-win32-ia32-msvc": "0.75.0", - "@oxfmt/binding-win32-x64-msvc": "0.75.0" + "@oxfmt/binding-android-arm-eabi": "0.78.0", + "@oxfmt/binding-android-arm64": "0.78.0", + "@oxfmt/binding-darwin-arm64": "0.78.0", + "@oxfmt/binding-darwin-x64": "0.78.0", + "@oxfmt/binding-freebsd-x64": "0.78.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.78.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.78.0", + "@oxfmt/binding-linux-arm64-gnu": "0.78.0", + "@oxfmt/binding-linux-arm64-musl": "0.78.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.78.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.78.0", + "@oxfmt/binding-linux-riscv64-musl": "0.78.0", + "@oxfmt/binding-linux-s390x-gnu": "0.78.0", + "@oxfmt/binding-linux-x64-gnu": "0.78.0", + "@oxfmt/binding-linux-x64-musl": "0.78.0", + "@oxfmt/binding-openharmony-arm64": "0.78.0", + "@oxfmt/binding-win32-arm64-msvc": "0.78.0", + "@oxfmt/binding-win32-ia32-msvc": "0.78.0", + "@oxfmt/binding-win32-x64-msvc": "0.78.0" }, "peerDependencies": { "@astrojs/compiler-rs": "^0.5.0", @@ -9169,21 +9124,21 @@ } }, "node_modules/oxlint-tsgolint": { - "version": "7.0.2005", - "resolved": "https://registry.npmjs.org/oxlint-tsgolint/-/oxlint-tsgolint-7.0.2005.tgz", - "integrity": "sha512-6ccPGu4u4J9bwYPHXBFPee3RZrX3BboRdU7k14zRDDB1lvN3O7J/vPRFdaEfa1+CWx4xnQQOp4ctoaF66oO0uw==", + "version": "7.0.2006", + "resolved": "https://registry.npmjs.org/oxlint-tsgolint/-/oxlint-tsgolint-7.0.2006.tgz", + "integrity": "sha512-5B3UtH71kycPHUC1kFEIffivEAs49SUmkJuHZOZnTY0NPj4legp0bcsCQucuLVNCoJzDucS68P2C4WIhP+LypQ==", "dev": true, "license": "MIT", "bin": { "tsgolint": "bin/tsgolint.js" }, "optionalDependencies": { - "@oxlint-tsgolint/darwin-arm64": "7.0.2005", - "@oxlint-tsgolint/darwin-x64": "7.0.2005", - "@oxlint-tsgolint/linux-arm64": "7.0.2005", - "@oxlint-tsgolint/linux-x64": "7.0.2005", - "@oxlint-tsgolint/win32-arm64": "7.0.2005", - "@oxlint-tsgolint/win32-x64": "7.0.2005" + "@oxlint-tsgolint/darwin-arm64": "7.0.2006", + "@oxlint-tsgolint/darwin-x64": "7.0.2006", + "@oxlint-tsgolint/linux-arm64": "7.0.2006", + "@oxlint-tsgolint/linux-x64": "7.0.2006", + "@oxlint-tsgolint/win32-arm64": "7.0.2006", + "@oxlint-tsgolint/win32-x64": "7.0.2006" } }, "node_modules/parse-entities": { @@ -9212,13 +9167,26 @@ "license": "MIT" }, "node_modules/parse5": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", - "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", "dev": true, "license": "MIT", "dependencies": { - "entities": "^8.0.0" + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz", + "integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.1.1" }, "funding": { "url": "https://github.com/inikulin/parse5?sponsor=1" @@ -9295,13 +9263,13 @@ } }, "node_modules/playwright": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", - "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz", + "integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.64.1" + "playwright-core": "1.65.0" }, "bin": { "playwright": "cli.js" @@ -9311,9 +9279,9 @@ } }, "node_modules/playwright-core": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", - "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", + "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==", "dev": true, "license": "Apache-2.0", "bin": { @@ -9582,9 +9550,9 @@ } }, "node_modules/react-hook-form": { - "version": "7.91.0", - "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.91.0.tgz", - "integrity": "sha512-5BEBUnCBwa28AFXYTYmOaB/+CSpJ/+CWVASHEvIGUzFdHyUiPHeRhG7r5hOZ8nZi0yP7pbHdFNXO/p31EKTJFQ==", + "version": "7.92.0", + "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.92.0.tgz", + "integrity": "sha512-O5ILyY5fYHN7N13Pfxpe55KboyNFsJdM03BHpshQkClJd8raugiAUGY7VjifITrfhVxyx81ko25azXCoayhf1w==", "license": "MIT", "engines": { "node": ">=18.0.0" @@ -9604,25 +9572,24 @@ } }, "node_modules/react-i18next": { - "version": "17.1.10", - "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.1.10.tgz", - "integrity": "sha512-XuUuA/rxukE4hXuR//PN308DuSQkWqKNNWBUj0dDTR087l3+6WLid3NC/w55ALrXA/dtWb7lychJ4rQLR3DCDg==", + "version": "18.0.1", + "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-18.0.1.tgz", + "integrity": "sha512-kPWXI0E/lrPj3+/umcKNzYZVnWmEedLiamMzDIHfbs+5ANf6yzvlZsjKou8f7kaGkfMMDLIZBejV+4aSN1CyBw==", "license": "MIT", "dependencies": { - "@babel/runtime": "^7.29.7", - "html-parse-stringify": "^4.0.1", - "use-sync-external-store": "^1.6.0" + "html-parse-stringify": "^4.0.1" + }, + "engines": { + "node": ">=22" }, "peerDependencies": { - "i18next": ">= 26.2.0", - "react": ">= 16.8.0", + "@types/react": "*", + "i18next": ">= 27.0.1", + "react": ">= 18.0.0", "typescript": "^5 || ^6 || ^7" }, "peerDependenciesMeta": { - "react-dom": { - "optional": true - }, - "react-native": { + "@types/react": { "optional": true }, "typescript": { @@ -9838,16 +9805,6 @@ "node": ">=0.10" } }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", @@ -9861,14 +9818,14 @@ "license": "MIT" }, "node_modules/resolve": { - "version": "1.22.13", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz", - "integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==", + "version": "1.22.14", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz", + "integrity": "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "is-core-module": "^2.17.0", + "is-core-module": "^2.18.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, @@ -9899,9 +9856,9 @@ "license": "MIT" }, "node_modules/rolldown": { - "version": "1.2.16", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.16.tgz", - "integrity": "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "dev": true, "license": "MIT", "dependencies": { @@ -9915,21 +9872,22 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.16", - "@rolldown/binding-android-arm64": "1.2.16", - "@rolldown/binding-darwin-arm64": "1.2.16", - "@rolldown/binding-darwin-x64": "1.2.16", - "@rolldown/binding-freebsd-x64": "1.2.16", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", - "@rolldown/binding-linux-arm64-gnu": "1.2.16", - "@rolldown/binding-linux-arm64-musl": "1.2.16", - "@rolldown/binding-linux-ppc64-gnu": "1.2.16", - "@rolldown/binding-linux-s390x-gnu": "1.2.16", - "@rolldown/binding-linux-x64-gnu": "1.2.16", - "@rolldown/binding-linux-x64-musl": "1.2.16", - "@rolldown/binding-openharmony-arm64": "1.2.16", - "@rolldown/binding-win32-arm64-msvc": "1.2.16", - "@rolldown/binding-win32-x64-msvc": "1.2.16" + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, "node_modules/rolldown/node_modules/@oxc-project/types": { @@ -9995,18 +9953,21 @@ "license": "MIT" }, "node_modules/scroll-into-view-if-needed": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.1.0.tgz", - "integrity": "sha512-49oNpRjWRvnU8NyGVmUaYG4jtTkNonFZI86MmGRDqBphEK2EXT9gdEUoQPZhuBM8yWHxCWbobltqYO5M4XrUvQ==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.2.0.tgz", + "integrity": "sha512-mnlrulRcw9gQR/HI0SlT56kmyCS/Z1tH/By43m8v8kHBjD8XecscweRcjKAk3kt4WLeyJQaSSQ8efy5f+r/dqA==", "license": "MIT", "dependencies": { "compute-scroll-into-view": "^3.0.2" + }, + "engines": { + "node": ">=26" } }, "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "dev": true, "license": "ISC", "bin": { @@ -10041,24 +10002,24 @@ } }, "node_modules/seroval": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.7.6.tgz", - "integrity": "sha512-oKNe6A8I3lSA5J0xg9xsrWCWDpET6CFhCMVuIsCmqrjNpBXzQXDAAQI5UfuC4Ner4DIR+VAtSw7TC0AmRMqFFQ==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.8.1.tgz", + "integrity": "sha512-7z9x1flFYfZBz+LfDkXNfm5UIhZJ/97ASaV8Q1wctoVkeqVfv+tLPsWebeMXBNw6XprvwxDE5wC5Ylqmr+iSrA==", "license": "MIT", "engines": { "node": ">=20" } }, "node_modules/seroval-plugins": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.7.6.tgz", - "integrity": "sha512-/TPCAd6q5stAZnugD2fsvNKtM2UpgwrS8/fO1cXTgPC0EqCsGB+UfkEEsToFCfg35CDTMlWkppfr/zWnLJGpBA==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.8.0.tgz", + "integrity": "sha512-96vBb12rDvPPwdKUgWw1op3fGq8AVBFOr0IllbnM72yR5J9WWXF18cQ4g1XfDO7HCyh2dt70P3XdtyRayP8FWg==", "license": "MIT", "engines": { "node": ">=20" }, "peerDependencies": { - "seroval": "^1.0" + "seroval": "^1.8.0" } }, "node_modules/set-cookie-parser": { @@ -10144,9 +10105,9 @@ } }, "node_modules/solid-js": { - "version": "1.9.18", - "resolved": "https://registry.npmjs.org/solid-js/-/solid-js-1.9.18.tgz", - "integrity": "sha512-CHGO5YFk6Y9m/1YSxVtKnXfrW7JD3Tmof8HmR4z6TmCPsS8efo8LnzIR8CQh3cUvffqYm6DWyBFfk8dQw1CNQQ==", + "version": "1.9.19", + "resolved": "https://registry.npmjs.org/solid-js/-/solid-js-1.9.19.tgz", + "integrity": "sha512-NIrV/6o1FtmrA9iuAAYvnQJZaHrGcaH3LKSVj4kCiZfwqjCtJNDgIgR9XcqYl6KR/Lb3oRx1HrlyswPWR8SRvw==", "license": "MIT", "dependencies": { "csstype": "^3.1.0", @@ -10233,9 +10194,9 @@ "license": "MIT" }, "node_modules/storybook": { - "version": "10.6.5", - "resolved": "https://registry.npmjs.org/storybook/-/storybook-10.6.5.tgz", - "integrity": "sha512-qurC38Nx4PDF9YIq6GO95dpUx8a3B9AZwlcHBo4cOI9At09ifjQRsqcwcdOf2YX0cpVhFKmHkI20SWCrxqYQrg==", + "version": "10.6.7", + "resolved": "https://registry.npmjs.org/storybook/-/storybook-10.6.7.tgz", + "integrity": "sha512-/1h87XqC+8tZ5PQ/GVWOg78tCQuEAshYWwok5niBcnHEKzZy6Ls06uuT5/rhQ3iUB0y8iexEVHmUe3jaaxNguw==", "dev": true, "license": "MIT", "dependencies": { @@ -10295,9 +10256,9 @@ } }, "node_modules/storybook/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -10357,9 +10318,9 @@ } }, "node_modules/strip-ansi/node_modules/ansi-regex": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.5.0.tgz", - "integrity": "sha512-zhvbbbdt1kbw7EJ9OQoxmQcuaNR9P5kTj7e/YdmOSU10aHWbycofJxA6jKfoEy3vlLdctOF9ZHaxLtmSm998wQ==", + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", + "integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==", "dev": true, "license": "MIT", "engines": { @@ -10430,19 +10391,20 @@ } }, "node_modules/swagger-client": { - "version": "3.38.4", - "resolved": "https://registry.npmjs.org/swagger-client/-/swagger-client-3.38.4.tgz", - "integrity": "sha512-uY92350FG2Nc54rZ9hClmRMXa7hKyEGL08iERCAXLAODS0d3RjTrttVyV/T0pM0HknCc2S1gi2whyZcGMx4FSQ==", + "version": "3.39.0", + "resolved": "https://registry.npmjs.org/swagger-client/-/swagger-client-3.39.0.tgz", + "integrity": "sha512-EDpBphskzOCzczUrucX3/FVb7k5gch1GSzB+MTBcdGY3Zew2XKs0ryPPw1J2l1hioojwwKUZXtEg31axbnQvpQ==", "license": "Apache-2.0", "dependencies": { "@babel/runtime-corejs3": "^7.22.15", "@scarf/scarf": "=1.4.0", - "@swagger-api/apidom-core": "^1.12.1", - "@swagger-api/apidom-error": "^1.12.1", - "@swagger-api/apidom-json-pointer": "^1.12.1", - "@swagger-api/apidom-ns-openapi-3-1": "^1.12.1", - "@swagger-api/apidom-ns-openapi-3-2": "^1.12.1", - "@swagger-api/apidom-reference": "^1.12.1", + "@swagger-api/apidom-core": "^1.14.0", + "@swagger-api/apidom-error": "^1.14.0", + "@swagger-api/apidom-json-pointer": "^1.14.0", + "@swagger-api/apidom-ns-json-schema-2020-12": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-1": "^1.14.0", + "@swagger-api/apidom-ns-openapi-3-2": "^1.14.0", + "@swagger-api/apidom-reference": "^1.14.0", "@swaggerexpert/cookie": "^2.0.2", "deepmerge": "~4.3.0", "fast-json-patch": "^3.0.0-1", @@ -10458,27 +10420,29 @@ "node": ">=22" }, "optionalDependencies": { - "@swagger-api/apidom-ns-asyncapi-2": "^1.12.1", - "@swagger-api/apidom-ns-asyncapi-3": "^1.12.1", - "@swagger-api/apidom-ns-openapi-2": "^1.12.1", - "@swagger-api/apidom-parser-adapter-api-design-systems-json": "^1.12.1", - "@swagger-api/apidom-parser-adapter-api-design-systems-yaml": "^1.12.1", - "@swagger-api/apidom-parser-adapter-arazzo-json-1": "^1.12.1", - "@swagger-api/apidom-parser-adapter-arazzo-yaml-1": "^1.12.1", - "@swagger-api/apidom-parser-adapter-asyncapi-json-2": "^1.12.1", - "@swagger-api/apidom-parser-adapter-asyncapi-json-3": "^1.12.1", - "@swagger-api/apidom-parser-adapter-asyncapi-yaml-2": "^1.12.1", - "@swagger-api/apidom-parser-adapter-asyncapi-yaml-3": "^1.12.1", - "@swagger-api/apidom-parser-adapter-json": "^1.12.1", - "@swagger-api/apidom-parser-adapter-openapi-json-2": "^1.12.1", - "@swagger-api/apidom-parser-adapter-openapi-json-3-0": "^1.12.1", - "@swagger-api/apidom-parser-adapter-openapi-json-3-1": "^1.12.1", - "@swagger-api/apidom-parser-adapter-openapi-json-3-2": "^1.12.1", - "@swagger-api/apidom-parser-adapter-openapi-yaml-2": "^1.12.1", - "@swagger-api/apidom-parser-adapter-openapi-yaml-3-0": "^1.12.1", - "@swagger-api/apidom-parser-adapter-openapi-yaml-3-1": "^1.12.1", - "@swagger-api/apidom-parser-adapter-openapi-yaml-3-2": "^1.12.1", - "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.12.1" + "@swagger-api/apidom-ns-asyncapi-2": "^1.14.0", + "@swagger-api/apidom-ns-asyncapi-3": "^1.14.0", + "@swagger-api/apidom-ns-openapi-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-api-design-systems-json": "^1.14.0", + "@swagger-api/apidom-parser-adapter-api-design-systems-yaml": "^1.14.0", + "@swagger-api/apidom-parser-adapter-arazzo-json-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-arazzo-yaml-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-asyncapi-json-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-asyncapi-json-3": "^1.14.0", + "@swagger-api/apidom-parser-adapter-asyncapi-yaml-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-asyncapi-yaml-3": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json-schema-json-2020-12": "^1.14.0", + "@swagger-api/apidom-parser-adapter-json-schema-yaml-2020-12": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-json-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-json-3-0": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-json-3-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-json-3-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-yaml-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-yaml-3-0": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-yaml-3-1": "^1.14.0", + "@swagger-api/apidom-parser-adapter-openapi-yaml-3-2": "^1.14.0", + "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.14.0" } }, "node_modules/swagger-ui-react": { @@ -10557,9 +10521,9 @@ "license": "MIT" }, "node_modules/tinybench": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", - "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", "dev": true, "license": "MIT", "engines": { @@ -10624,22 +10588,22 @@ } }, "node_modules/tldts": { - "version": "7.4.19", - "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", - "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", + "version": "7.4.22", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.22.tgz", + "integrity": "sha512-TmLwkCZ1GFMxGkKfg2ooQhPF8rDMuuXvJHSxFiOU1fofh27L6NaO5T9KSlQXCJX2eoSt14I8F4saSMILOmXmaQ==", "dev": true, "license": "MIT", "dependencies": { - "tldts-core": "^7.4.19" + "tldts-core": "^7.4.22" }, "bin": { "tldts": "bin/cli.js" } }, "node_modules/tldts-core": { - "version": "7.4.20", - "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.20.tgz", - "integrity": "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==", + "version": "7.4.22", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.22.tgz", + "integrity": "sha512-NRyhrlvJcTwvoRibE0dEZvp6C5RwV4RxpsX1zbkI1k7Fk2pzIhmQ+MvswJEd5KKl3VRFRMDTipXse/ejh/ld/w==", "dev": true, "license": "MIT" }, @@ -10674,9 +10638,9 @@ } }, "node_modules/tough-cookie": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", - "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", + "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -10849,9 +10813,9 @@ } }, "node_modules/undici": { - "version": "8.12.3", - "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz", - "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", + "version": "8.12.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz", + "integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==", "dev": true, "license": "MIT", "engines": { @@ -10954,16 +10918,16 @@ } }, "node_modules/vite": { - "version": "8.3.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", - "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", "dev": true, "license": "MIT", "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", - "postcss": "^8.5.30", - "rolldown": "~1.2.14", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", "tinyglobby": "^0.2.17" }, "bin": { @@ -11032,14 +10996,14 @@ } }, "node_modules/vitest": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", - "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", "dev": true, "license": "MIT", "dependencies": { "@types/chai": "^5.2.2", - "@vitest/mocker": "5.0.5", + "@vitest/mocker": "5.1.0", "chai": "^6.3.0", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", @@ -11065,12 +11029,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "5.0.5", - "@vitest/browser-preview": "5.0.5", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", - "@vitest/coverage-istanbul": "5.0.5", - "@vitest/coverage-v8": "5.0.5", - "@vitest/ui": "5.0.5", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" @@ -11276,9 +11240,9 @@ } }, "node_modules/ws": { - "version": "8.22.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", - "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", "dev": true, "license": "MIT", "engines": { diff --git a/frontend/package.json b/frontend/package.json index a9a192c42..b0404a585 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -38,50 +38,50 @@ "@ant-design/icons": "^6.3.4", "@codemirror/lang-json": "^6.0.2", "@codemirror/theme-one-dark": "^6.1.3", - "@hookform/resolvers": "^7.0.1", + "@hookform/resolvers": "^7.0.5", "@noble/hashes": "^2.4.0", - "@tanstack/react-query": "^5.105.1", - "@tanstack/react-query-devtools": "^5.105.1", - "antd": "^6.6.8", + "@tanstack/react-query": "^5.107.1", + "@tanstack/react-query-devtools": "^5.107.1", + "antd": "^6.7.0", "codemirror": "^6.0.2", "dayjs": "^1.11.23", - "i18next": "^26.6.0", - "otpauth": "^9.5.2", + "i18next": "^27.1.1", + "otpauth": "^9.6.0", "persian-calendar-suite": "^1.5.6", "react": "^19.3.1", "react-dom": "^19.3.1", - "react-hook-form": "^7.91.0", - "react-i18next": "^17.1.10", + "react-hook-form": "^7.92.0", + "react-i18next": "^18.0.1", "react-router": "^8.5.1", "swagger-ui-react": "^5.34.1", "uplot": "^1.6.32", "zod": "^4.6.7" }, "devDependencies": { - "@storybook/addon-a11y": "^10.6.5", - "@storybook/addon-docs": "^10.6.5", - "@storybook/addon-vitest": "^10.6.5", - "@storybook/react-vite": "^10.6.5", + "@storybook/addon-a11y": "^10.6.7", + "@storybook/addon-docs": "^10.6.7", + "@storybook/addon-vitest": "^10.6.7", + "@storybook/react-vite": "^10.6.7", "@testing-library/dom": "^10.4.2", "@testing-library/react": "^16.3.3", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "@types/swagger-ui-react": "^5.18.0", - "@vitejs/plugin-react": "^6.1.2", - "@vitest/browser-playwright": "5.0.5", - "@vitest/coverage-v8": "^5.0.5", + "@vitejs/plugin-react": "^6.3.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/coverage-v8": "^5.1.0", "husky": "^9.1.7", - "jsdom": "^30.1.3", + "jsdom": "^31.0.0", "lint-staged": "^17.6.0", - "msw": "^3.0.3", - "oxfmt": "0.75.0", + "msw": "^3.0.5", + "oxfmt": "0.78.0", "oxlint": "1.90.0", - "oxlint-tsgolint": "^7.0.2005", - "playwright": "^1.64.1", - "storybook": "^10.6.5", + "oxlint-tsgolint": "^7.0.2006", + "playwright": "^1.65.0", + "storybook": "^10.6.7", "typescript": "7.0.2", - "vite": "8.3.5", - "vitest": "^5.0.5" + "vite": "8.3.8", + "vitest": "^5.1.0" }, "overrides": { "dompurify": "^3.4.17", @@ -104,9 +104,9 @@ "valibot": "^1.1.0" }, "@storybook/addon-vitest": { - "vitest": "5.0.5", - "@vitest/browser-playwright": "5.0.5", - "@vitest/browser": "5.0.5" + "vitest": "5.1.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser": "5.1.0" }, "remarkable": { "argparse": "^2.0.1" diff --git a/frontend/src/i18n/react.ts b/frontend/src/i18n/react.ts index 7ca9d78d0..bec4dd670 100644 --- a/frontend/src/i18n/react.ts +++ b/frontend/src/i18n/react.ts @@ -9,14 +9,13 @@ import enUS from '../../../internal/web/translation/en-US.json'; const FALLBACK = 'en-US'; -// No locale uses $t(...) nesting, and its regex backtracks exponentially on an unclosed -// "$t(" in untrusted text (node-reported names, remarks); no off switch, so never match. +// No locale uses $t(...) nesting, and untrusted text (node-reported names, remarks) must not +// reach it; i18next 27 has no off switch, so the prefix is a NUL that no text contains. export const INTERPOLATION: InterpolationOptions = { escapeValue: false, prefix: '{', suffix: '}', - nestingPrefix: '', - nestingPrefixEscaped: '(?!)', + nestingPrefix: '\u0000', }; const lazyModules = import.meta.glob([ From 35921b95a2175bebfeb6f8f6951f89879d8d2348 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Thu, 12 Nov 2026 19:26:57 +0100 Subject: [PATCH 015/130] fix(xray): show the Google Drive defaults in the XDRIVE tuning fields xray-core 26.11.9 (#7340, #7352) gives the Google Drive backend its own defaults for the knobs a config leaves empty: flushIntervalMs 10, maxPollIntervalMs 200 and concurrency 64. The other services keep 20, 500 and 8. The tuning placeholders stand for "what the core uses when this is empty", so they now follow the selected service, and the transports page in all four doc languages names the Google Drive values. --- docs/content/docs/en/config/transports.mdx | 2 +- docs/content/docs/fa/config/transports.mdx | 2 +- docs/content/docs/ru/config/transports.mdx | 2 +- docs/content/docs/zh/config/transports.mdx | 2 +- .../src/lib/xray/forms/transport/XDriveForm.tsx | 17 +++++++++++++++-- 5 files changed, 19 insertions(+), 6 deletions(-) diff --git a/docs/content/docs/en/config/transports.mdx b/docs/content/docs/en/config/transports.mdx index 59c5bc08f..d9c7450c2 100644 --- a/docs/content/docs/en/config/transports.mdx +++ b/docs/content/docs/en/config/transports.mdx @@ -137,7 +137,7 @@ enabled. The panel offers XDRIVE only for VLESS, refuses to save an inbound with | `secrets` | — | Google Drive: ClientID, ClientSecret, RefreshToken — exactly three, in that order. Template: values read as `{secret0}`, `{secret1}`, …. S3: AccessKeyID, SecretAccessKey and an optional SessionToken. | | `template` | — | Template service only: the storage API's `auth`, `put`, `get`, `list` and `delete` operations. | | `s3` | — | S3 service only: `endpoint` (an http(s) URL), `region`, `bucket` and `pathStyle` (default `true`; `false` puts the bucket in the host name). `remoteFolder` is the object prefix. | -| tuning | core defaults | `segmentBytes` (512 KiB), `flushIntervalMs` (20), `pollIntervalMs`/`maxPollIntervalMs` (50/500), `eagerWindowMs` (2000), `holeTimeoutMs` (30000), `sessionTtlSeconds` (300), `concurrency` (8). | +| tuning | core defaults | `segmentBytes` (512 KiB), `flushIntervalMs` (20), `pollIntervalMs`/`maxPollIntervalMs` (50/500), `eagerWindowMs` (2000), `holeTimeoutMs` (30000), `sessionTtlSeconds` (300), `concurrency` (8). Google Drive defaults to `flushIntervalMs` 10, `maxPollIntervalMs` 200 and `concurrency` 64 (xray-core 26.11.9). | The optional **Front address/port** (the stream-level `address`/`port`) is a domain front the storage API is dialed through; TLS still names the API host. XDRIVE has diff --git a/docs/content/docs/fa/config/transports.mdx b/docs/content/docs/fa/config/transports.mdx index 9066c9604..058d6311b 100644 --- a/docs/content/docs/fa/config/transports.mdx +++ b/docs/content/docs/fa/config/transports.mdx @@ -138,7 +138,7 @@ inbound به مقدار `decryption` نیاز دارد و outbound به `encrypt | `secrets` | — | Google Drive: دقیقاً سه مقدار ClientID، ClientSecret و RefreshToken به همین ترتیب. Template: مقادیری که با `{secret0}`، `{secret1}`، … خوانده می‌شوند. S3: ‏AccessKeyID، SecretAccessKey و در صورت نیاز SessionToken. | | `template` | — | فقط برای سرویس template: عملیات `auth`، `put`، `get`، `list` و `delete` در API ذخیره‌ساز. | | `s3` | — | فقط برای سرویس s3: `endpoint` (یک URL از نوع http(s))، `region`، `bucket` و `pathStyle` (پیش‌فرض `true`؛ با `false` نام باکت در نام میزبان می‌آید). `remoteFolder` پیشوند اشیاء است. | -| تنظیمات دقیق | پیش‌فرض هسته | `segmentBytes` (512 KiB)، `flushIntervalMs` (20)، `pollIntervalMs`/`maxPollIntervalMs` (50/500)، `eagerWindowMs` (2000)، `holeTimeoutMs` (30000)، `sessionTtlSeconds` (300)، `concurrency` (8). | +| تنظیمات دقیق | پیش‌فرض هسته | `segmentBytes` (512 KiB)، `flushIntervalMs` (20)، `pollIntervalMs`/`maxPollIntervalMs` (50/500)، `eagerWindowMs` (2000)، `holeTimeoutMs` (30000)، `sessionTtlSeconds` (300)، `concurrency` (8). پیش‌فرض Google Drive: ‏`flushIntervalMs` برابر 10، `maxPollIntervalMs` برابر 200 و `concurrency` برابر 64 (xray-core 26.11.9). | **آدرس/پورت Front** اختیاری (کلیدهای `address`/`port` در سطح stream) یک domain front است که API ذخیره‌ساز از طریق آن وصل می‌شود؛ نام TLS همچنان میزبان API است. XDRIVE لایهٔ diff --git a/docs/content/docs/ru/config/transports.mdx b/docs/content/docs/ru/config/transports.mdx index 04b13642d..f70901269 100644 --- a/docs/content/docs/ru/config/transports.mdx +++ b/docs/content/docs/ru/config/transports.mdx @@ -140,7 +140,7 @@ Mux. Панель предлагает XDRIVE только для VLESS, не с | `secrets` | — | Google Drive: ровно три значения — ClientID, ClientSecret, RefreshToken, в этом порядке. Template: значения, доступные как `{secret0}`, `{secret1}`, …. S3: AccessKeyID, SecretAccessKey и при необходимости SessionToken. | | `template` | — | Только для template: операции `auth`, `put`, `get`, `list` и `delete` API хранилища. | | `s3` | — | Только для s3: `endpoint` (URL http(s)), `region`, `bucket` и `pathStyle` (по умолчанию `true`; `false` переносит бакет в имя хоста). `remoteFolder` — префикс объектов. | -| тонкая настройка | значения ядра | `segmentBytes` (512 KiB), `flushIntervalMs` (20), `pollIntervalMs`/`maxPollIntervalMs` (50/500), `eagerWindowMs` (2000), `holeTimeoutMs` (30000), `sessionTtlSeconds` (300), `concurrency` (8). | +| тонкая настройка | значения ядра | `segmentBytes` (512 KiB), `flushIntervalMs` (20), `pollIntervalMs`/`maxPollIntervalMs` (50/500), `eagerWindowMs` (2000), `holeTimeoutMs` (30000), `sessionTtlSeconds` (300), `concurrency` (8). Для Google Drive по умолчанию `flushIntervalMs` 10, `maxPollIntervalMs` 200 и `concurrency` 64 (xray-core 26.11.9). | Необязательные **адрес/порт фронтинга** (`address`/`port` на уровне stream) — домен-фронт, через который идёт подключение к API хранилища; в TLS по-прежнему указывается хост API. diff --git a/docs/content/docs/zh/config/transports.mdx b/docs/content/docs/zh/config/transports.mdx index b9634185a..f40641254 100644 --- a/docs/content/docs/zh/config/transports.mdx +++ b/docs/content/docs/zh/config/transports.mdx @@ -129,7 +129,7 @@ XDRIVE 把数据流作为文件存放在双方都能访问的文件夹中:服 | `secrets` | — | Google Drive:恰好三项,依次为 ClientID、ClientSecret、RefreshToken。Template:以 `{secret0}`、`{secret1}`… 引用的值。S3:AccessKeyID、SecretAccessKey,以及可选的 SessionToken。 | | `template` | — | 仅用于 template 服务:存储 API 的 `auth`、`put`、`get`、`list` 和 `delete` 操作。 | | `s3` | — | 仅用于 s3 服务:`endpoint`(http(s) URL)、`region`、`bucket` 和 `pathStyle`(默认 `true`;为 `false` 时存储桶名放在主机名中)。`remoteFolder` 为对象前缀。 | -| 调优参数 | 内核默认值 | `segmentBytes`(512 KiB)、`flushIntervalMs`(20)、`pollIntervalMs`/`maxPollIntervalMs`(50/500)、`eagerWindowMs`(2000)、`holeTimeoutMs`(30000)、`sessionTtlSeconds`(300)、`concurrency`(8)。 | +| 调优参数 | 内核默认值 | `segmentBytes`(512 KiB)、`flushIntervalMs`(20)、`pollIntervalMs`/`maxPollIntervalMs`(50/500)、`eagerWindowMs`(2000)、`holeTimeoutMs`(30000)、`sessionTtlSeconds`(300)、`concurrency`(8)。Google Drive 的默认值为 `flushIntervalMs` 10、`maxPollIntervalMs` 200、`concurrency` 64(xray-core 26.11.9)。 | 可选的**前置地址/端口**(stream 级的 `address`/`port`)是连接存储 API 时使用的域前置;TLS 中仍使用 API 主机名。 XDRIVE 没有自己的 TLS/REALITY 层——其流量就是存储 API 自身的 HTTPS。在出站上,**TLS** diff --git a/frontend/src/lib/xray/forms/transport/XDriveForm.tsx b/frontend/src/lib/xray/forms/transport/XDriveForm.tsx index ac18c30e2..7712360f3 100644 --- a/frontend/src/lib/xray/forms/transport/XDriveForm.tsx +++ b/frontend/src/lib/xray/forms/transport/XDriveForm.tsx @@ -30,6 +30,13 @@ const TUNING_FIELDS = [ ['concurrency', 'concurrency', 8], ] as const; +// xray-core 26.11.9 (#7340, #7352) gives the Google Drive backend its own defaults. +const GOOGLE_DRIVE_TUNING_DEFAULTS: Partial> = { + flushIntervalMs: 10, + maxPollIntervalMs: 200, + concurrency: 64, +}; + const GOOGLE_DRIVE_SECRETS = ['clientId', 'clientSecret', 'refreshToken'] as const; const S3_SECRETS = [ ['accessKeyId', true], @@ -192,9 +199,15 @@ export default function XDriveForm() { )} - {TUNING_FIELDS.map(([key, label, placeholder]) => ( + {TUNING_FIELDS.map(([key, label, coreDefault]) => ( - + ))} From 8cccc1c9bf051a871d8b758f4061f181e476e526 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Thu, 12 Nov 2026 19:26:57 +0100 Subject: [PATCH 016/130] feat(xray): explain what mux concurrency means on xray-core 26.11.9 xray-core 26.11.9 (bb335c6) raises any mux concurrency from 0 to 128 to 128, where 0 used to mean 8 and every other value was used as written. The panel's default of 8 and anything a user types up to 128 therefore no longer changes the result on a current core, while an older client core still honours it. The concurrency field of the outbound mux form, the host mux override and the JSON subscription mux settings now carries that as a hint in all 14 locales. The emitted value is unchanged. --- frontend/src/pages/settings/SubscriptionFormatsTab.tsx | 1 + frontend/src/pages/xray/outbounds/transport/mux.tsx | 1 + internal/web/translation/ar-EG.json | 1 + internal/web/translation/en-US.json | 1 + internal/web/translation/es-ES.json | 1 + internal/web/translation/fa-IR.json | 1 + internal/web/translation/id-ID.json | 1 + internal/web/translation/ja-JP.json | 1 + internal/web/translation/pt-BR.json | 1 + internal/web/translation/ru-RU.json | 1 + internal/web/translation/sk-SK.json | 1 + internal/web/translation/tr-TR.json | 1 + internal/web/translation/uk-UA.json | 1 + internal/web/translation/vi-VN.json | 1 + internal/web/translation/zh-CN.json | 1 + internal/web/translation/zh-TW.json | 1 + 16 files changed, 16 insertions(+) diff --git a/frontend/src/pages/settings/SubscriptionFormatsTab.tsx b/frontend/src/pages/settings/SubscriptionFormatsTab.tsx index 056b14789..b3884bf9d 100644 --- a/frontend/src/pages/settings/SubscriptionFormatsTab.tsx +++ b/frontend/src/pages/settings/SubscriptionFormatsTab.tsx @@ -361,6 +361,7 @@ export default function SubscriptionFormatsTab({ diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 20f87bc26..e152133e2 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -1439,6 +1439,7 @@ "applyTo": "تطبيق على", "addNoise": "+ ضوضاء", "concurrency": "التزامن", + "concurrencyHint": "عدد الـstreams في كل اتصال. xray-core 26.11.9 والأحدث بيرفع أي قيمة من 0 لـ128 إلى 128؛ النسخ الأقدم بتستخدم الرقم زي ما هو (0 يعني 8). القيمة ‎-1‏ بتقفل الـmux على TCP.", "xudpConcurrency": "تزامن xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 711e767f1..05599684a 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -1564,6 +1564,7 @@ "applyTo": "Apply to", "addNoise": "+ Noise", "concurrency": "Concurrency", + "concurrencyHint": "Streams per connection. xray-core 26.11.9 and newer raise any value from 0 to 128 to 128; older cores use the number as written (0 means 8). -1 turns TCP mux off.", "xudpConcurrency": "xudp concurrency", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 303e09f4b..8ea61b93b 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -1439,6 +1439,7 @@ "applyTo": "Aplicar a", "addNoise": "+ Ruido", "concurrency": "Concurrencia", + "concurrencyHint": "Flujos por conexión. xray-core 26.11.9 y posteriores elevan a 128 cualquier valor entre 0 y 128; los núcleos anteriores usan el número tal cual (0 significa 8). -1 desactiva el mux TCP.", "xudpConcurrency": "Concurrencia xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 6f99bce5d..7ab61bd43 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -1443,6 +1443,7 @@ "applyTo": "اعمال بر", "addNoise": "+ نویز", "concurrency": "هم‌زمانی", + "concurrencyHint": "تعداد استریم در هر اتصال. xray-core 26.11.9 و جدیدتر هر مقدار بین ۰ تا ۱۲۸ را به ۱۲۸ می‌رساند؛ هسته‌های قدیمی‌تر همان عدد را به کار می‌برند (۰ یعنی ۸). مقدار ‎-1‏ ماکس TCP را خاموش می‌کند.", "xudpConcurrency": "هم‌زمانی xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 2a2a03407..d08644082 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -1439,6 +1439,7 @@ "applyTo": "Terapkan ke", "addNoise": "+ Noise", "concurrency": "Konkurensi", + "concurrencyHint": "Jumlah stream per koneksi. xray-core 26.11.9 dan yang lebih baru menaikkan nilai 0 sampai 128 menjadi 128; core yang lebih lama memakai angka apa adanya (0 berarti 8). -1 mematikan mux TCP.", "xudpConcurrency": "Konkurensi xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index bdef5c00f..f1f84a9a2 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -1439,6 +1439,7 @@ "applyTo": "適用先", "addNoise": "+ ノイズ", "concurrency": "並行数", + "concurrencyHint": "1 接続あたりのストリーム数。xray-core 26.11.9 以降は 0〜128 の値をすべて 128 に引き上げます。それより古いコアは指定した数値をそのまま使います(0 は 8)。-1 で TCP mux を無効にします。", "xudpConcurrency": "xudp 並行数", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index eccd461d1..8e4a29bc1 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -1439,6 +1439,7 @@ "applyTo": "Aplicar a", "addNoise": "+ Ruído", "concurrency": "Concorrência", + "concurrencyHint": "Fluxos por conexão. O xray-core 26.11.9 e posteriores elevam para 128 qualquer valor de 0 a 128; núcleos mais antigos usam o número como está (0 significa 8). -1 desativa o mux TCP.", "xudpConcurrency": "Concorrência xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 59920df0b..fae67a37a 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -1439,6 +1439,7 @@ "applyTo": "Применить к", "addNoise": "+ Шум", "concurrency": "Параллелизм", + "concurrencyHint": "Число потоков на соединение. xray-core 26.11.9 и новее поднимает любое значение от 0 до 128 до 128; более старые ядра используют число как есть (0 означает 8). -1 отключает TCP-mux.", "xudpConcurrency": "Параллелизм xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index f2f42cdca..0b5a38bfe 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -1564,6 +1564,7 @@ "applyTo": "Použiť na", "addNoise": "+ Šum", "concurrency": "Počet súbežných prenosov", + "concurrencyHint": "Počet streamov na jedno spojenie. xray-core 26.11.9 a novšie zvýšia každú hodnotu od 0 do 128 na 128; staršie jadrá použijú číslo tak, ako je zadané (0 znamená 8). -1 vypne TCP mux.", "xudpConcurrency": "Súbežné prenosy xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 9f7154927..0909deae6 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -1439,6 +1439,7 @@ "applyTo": "Şuna Uygula", "addNoise": "+ Gürültü", "concurrency": "Eşzamanlılık", + "concurrencyHint": "Bağlantı başına akış sayısı. xray-core 26.11.9 ve sonrası 0 ile 128 arasındaki her değeri 128'e yükseltir; daha eski çekirdekler sayıyı yazıldığı gibi kullanır (0, 8 demektir). -1 TCP mux'u kapatır.", "xudpConcurrency": "xudp eşzamanlılık", "xudpUdp443": "UDP 443" }, diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index b74c40b06..acac29f67 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -1439,6 +1439,7 @@ "applyTo": "Застосувати до", "addNoise": "+ Шум", "concurrency": "Паралельність", + "concurrencyHint": "Кількість потоків на з'єднання. xray-core 26.11.9 і новіші піднімають будь-яке значення від 0 до 128 до 128; старіші ядра використовують число як є (0 означає 8). -1 вимикає TCP-mux.", "xudpConcurrency": "Паралельність xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index d43b7a156..0e2a172bf 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -1439,6 +1439,7 @@ "applyTo": "Áp dụng cho", "addNoise": "+ Nhiễu", "concurrency": "Đồng thời", + "concurrencyHint": "Số luồng trên mỗi kết nối. xray-core 26.11.9 trở lên nâng mọi giá trị từ 0 đến 128 thành 128; các core cũ hơn dùng đúng con số đã nhập (0 nghĩa là 8). -1 tắt mux TCP.", "xudpConcurrency": "Đồng thời xudp", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 503743ee9..3fd3cae64 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -1439,6 +1439,7 @@ "applyTo": "应用于", "addNoise": "+ 噪声", "concurrency": "并发", + "concurrencyHint": "每个连接承载的流数量。xray-core 26.11.9 及更新版本会把 0 到 128 之间的值一律提高到 128;更早的核心按填写的数值使用(0 表示 8)。-1 关闭 TCP mux。", "xudpConcurrency": "xudp 并发", "xudpUdp443": "xudp UDP 443" }, diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 5e6bed66d..deda19386 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -1439,6 +1439,7 @@ "applyTo": "套用至", "addNoise": "+ 雜訊", "concurrency": "並發", + "concurrencyHint": "每個連線承載的串流數量。xray-core 26.11.9 及更新版本會把 0 到 128 之間的值一律提高到 128;更早的核心依填寫的數值使用(0 表示 8)。-1 關閉 TCP mux。", "xudpConcurrency": "xudp 並發", "xudpUdp443": "xudp UDP 443" }, From efe768521d45c5a26d284b6c75a512b2e257efac Mon Sep 17 00:00:00 2001 From: Aleksey Fedorov <320380254+Dv2Corn@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:35:08 +1000 Subject: [PATCH 017/130] fix(memory): derive the Go soft limit from the panel's own cgroup (#7102) The automatic soft limit read only /sys/fs/cgroup/memory.max, the root of the cgroup namespace. A systemd MemoryMax on x-ui.service lives below that root, so it was never seen: on a bare host the root has no memory.max and no soft limit was set at all, and inside an LXC/Incus container the limit came from the container (2 GiB -> "1843 MiB") while systemd killed the panel at 650M. Either way GC never tightened before the OOM kill. Walk from the process's own cgroup (/proc/self/cgroup) up to the visible root and take the tightest memory.max (cgroup v2) or memory.limit_in_bytes (v1). Docker with a private cgroup namespace sees the same root limit as before. --- internal/util/sys/memlimit.go | 59 +++++++++++++------ internal/util/sys/memlimit_test.go | 91 ++++++++++++++++++++++++++++++ 2 files changed, 134 insertions(+), 16 deletions(-) create mode 100644 internal/util/sys/memlimit_test.go diff --git a/internal/util/sys/memlimit.go b/internal/util/sys/memlimit.go index ca6836308..b3a7467ee 100644 --- a/internal/util/sys/memlimit.go +++ b/internal/util/sys/memlimit.go @@ -3,7 +3,9 @@ package sys import ( "fmt" "os" + "path/filepath" "runtime/debug" + "slices" "strconv" "strings" ) @@ -89,26 +91,51 @@ func MemoryReleaseIntervalMinutes() int { return defaultReleaseMinutes } -// cgroupMemoryLimit reads the container memory limit from cgroup v2 then v1. -// A "max" value or the v1 unlimited sentinel (~8 EiB) means no limit at this -// level, so it reports not-found and the caller falls back to the Go default. The -// files are absent off Linux, which also yields not-found. +// cgroupMemoryLimit returns the tightest memory limit between this process's own +// cgroup and the cgroup root it can see: a systemd MemoryMax sits below that root. func cgroupMemoryLimit() (int64, bool) { - const unlimited = int64(1) << 62 + self, _ := os.ReadFile("/proc/self/cgroup") + return cgroupMemoryLimitAt(string(self), "/sys/fs/cgroup") +} - if b, err := os.ReadFile("/sys/fs/cgroup/memory.max"); err == nil { - if s := strings.TrimSpace(string(b)); s != "" && s != "max" { - if v, err := strconv.ParseInt(s, 10, 64); err == nil && v > 0 && v < unlimited { - return v, true +func cgroupMemoryLimitAt(selfCgroup, root string) (int64, bool) { + if limit, ok := tightestLimit(root, ownCgroupPath(selfCgroup, "0", ""), "memory.max"); ok { + return limit, true + } + return tightestLimit(filepath.Join(root, "memory"), ownCgroupPath(selfCgroup, "", "memory"), "memory.limit_in_bytes") +} + +// ownCgroupPath picks the /proc/self/cgroup line of the v2 hierarchy (id "0") or the +// v1 hierarchy carrying controller; "/" when there is no such line. +func ownCgroupPath(selfCgroup, id, controller string) string { + for line := range strings.Lines(selfCgroup) { + fields := strings.SplitN(strings.TrimSpace(line), ":", 3) + if len(fields) != 3 { + continue + } + if (id != "" && fields[0] == id && fields[1] == "") || + (controller != "" && slices.Contains(strings.Split(fields[1], ","), controller)) { + return fields[2] + } + } + return "/" +} + +// tightestLimit walks from root/rel up to root. "max" and the v1 unlimited +// sentinel (~8 EiB) do not parse as a limit; files are absent off Linux. +func tightestLimit(root, rel, name string) (int64, bool) { + const unlimited = int64(1) << 62 + var limit int64 + for dir := filepath.Join(root, filepath.Clean("/"+rel)); ; dir = filepath.Dir(dir) { + if b, err := os.ReadFile(filepath.Join(dir, name)); err == nil { + v, err := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64) + if err == nil && v > 0 && v < unlimited && (limit == 0 || v < limit) { + limit = v } } - } - - if b, err := os.ReadFile("/sys/fs/cgroup/memory/memory.limit_in_bytes"); err == nil { - if v, err := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64); err == nil && v > 0 && v < unlimited { - return v, true + if len(dir) <= len(root) { + break } } - - return 0, false + return limit, limit > 0 } diff --git a/internal/util/sys/memlimit_test.go b/internal/util/sys/memlimit_test.go new file mode 100644 index 000000000..32e37e92c --- /dev/null +++ b/internal/util/sys/memlimit_test.go @@ -0,0 +1,91 @@ +package sys + +import ( + "os" + "path/filepath" + "testing" +) + +func TestCgroupMemoryLimitAt(t *testing.T) { + const service = "/system.slice/x-ui.service" + tests := []struct { + name string + selfCgroup string + files map[string]string + want int64 + wantOK bool + }{ + { + name: "systemd MemoryMax inside a container limit", + selfCgroup: "0::" + service + "\n", + files: map[string]string{ + "root/memory.max": "2147483648\n", + "root/system.slice/memory.max": "max\n", + "root" + service + "/memory.max": "681574400\n", + }, + want: 681574400, wantOK: true, + }, + { + name: "systemd MemoryMax on a bare host, root has no memory.max", + selfCgroup: "0::" + service + "\n", + files: map[string]string{ + "root/system.slice/memory.max": "max\n", + "root" + service + "/memory.max": "681574400\n", + }, + want: 681574400, wantOK: true, + }, + { + name: "container limit tighter than the service limit", + selfCgroup: "0::" + service + "\n", + files: map[string]string{ + "root/memory.max": "536870912\n", + "root" + service + "/memory.max": "681574400\n", + }, + want: 536870912, wantOK: true, + }, + { + name: "no limit at any level", + selfCgroup: "0::" + service + "\n", + files: map[string]string{ + "root/memory.max": "max\n", + "root" + service + "/memory.max": "max\n", + }, + }, + { + name: "cgroup v1 limit on the service, unlimited sentinel at the root", + selfCgroup: "12:cpu,cpuacct:" + service + "\n7:memory:" + service + "\n", + files: map[string]string{ + "root/memory/memory.limit_in_bytes": "9223372036854771712\n", + "root/memory" + service + "/memory.limit_in_bytes": "681574400\n", + }, + want: 681574400, wantOK: true, + }, + { + name: "cgroup outside the namespace never reads above the root", + selfCgroup: "0::/../../elsewhere\n", + files: map[string]string{ + "memory.max": "1048576\n", + "root/memory.max": "2147483648\n", + }, + want: 2147483648, wantOK: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + for name, body := range tt.files { + path := filepath.Join(dir, name) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + got, ok := cgroupMemoryLimitAt(tt.selfCgroup, filepath.Join(dir, "root")) + if got != tt.want || ok != tt.wantOK { + t.Fatalf("cgroupMemoryLimitAt() = %d, %v; want %d, %v", got, ok, tt.want, tt.wantOK) + } + }) + } +} From 7da8fd23beecadc789a71b512a82ff94ee60c596 Mon Sep 17 00:00:00 2001 From: Benjamin Mitchell <352241654+BenjaminMitchell-D0FB@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:36:22 -0800 Subject: [PATCH 018/130] fix(groups): preserve group traffic totals on global client reset (#7094) Adjust group baselines before clearing client counters so group usage survives a global reset. --- .../web/service/client_group_reset_test.go | 34 +++++++++++++++++++ internal/web/service/client_groups.go | 12 +++++++ internal/web/service/client_traffic.go | 3 ++ 3 files changed, 49 insertions(+) diff --git a/internal/web/service/client_group_reset_test.go b/internal/web/service/client_group_reset_test.go index 5ba06026a..d06b98a68 100644 --- a/internal/web/service/client_group_reset_test.go +++ b/internal/web/service/client_group_reset_test.go @@ -174,6 +174,40 @@ func TestGroupTotalsSurviveBulkClientReset(t *testing.T) { } } +func TestGroupTotalsSurviveGlobalClientReset(t *testing.T) { + initTrafficTestDB(t) + svc := &ClientService{} + + seedGroupedClient(t, "alice", "reset", 100, 200) + seedGroupedClient(t, "bob", "unreset", 40, 60) + if err := svc.ResetGroupTraffic("reset"); err != nil { + t.Fatalf("ResetGroupTraffic: %v", err) + } + + if _, err := svc.ResetAllTraffics(); err != nil { + t.Fatalf("ResetAllTraffics: %v", err) + } + if g := groupByName(t, svc, "unreset"); g.Up != 40 || g.Down != 60 || g.TrafficUsed != 100 { + t.Fatalf("global reset changed accumulated group usage: got %+v, want up=40 down=60 used=100", g) + } + + var traffic xray.ClientTraffic + if err := database.GetDB().Where("email = ?", "alice").First(&traffic).Error; err != nil { + t.Fatalf("load alice traffic: %v", err) + } + if traffic.Up != 0 || traffic.Down != 0 { + t.Fatalf("client traffic not reset: up=%d down=%d", traffic.Up, traffic.Down) + } + + if err := database.GetDB().Model(&traffic). + Updates(map[string]any{"up": 10, "down": 20}).Error; err != nil { + t.Fatalf("record new alice traffic: %v", err) + } + if g := groupByName(t, svc, "reset"); g.Up != 10 || g.Down != 20 || g.TrafficUsed != 30 { + t.Fatalf("global reset hid new group usage: got %+v, want up=10 down=20 used=30", g) + } +} + func TestGroupTotalsSurviveClientDelete(t *testing.T) { initTrafficTestDB(t) csvc := &ClientService{} diff --git a/internal/web/service/client_groups.go b/internal/web/service/client_groups.go index 504b4559a..6db1c448a 100644 --- a/internal/web/service/client_groups.go +++ b/internal/web/service/client_groups.go @@ -67,6 +67,14 @@ func adjustGroupBaselinesForRemovedTraffic(tx *gorm.DB, emails []string) error { return shiftGroupBaselines(tx, emails, -1) } +func adjustAllGroupBaselinesForRemovedTraffic(tx *gorm.DB) error { + totals, err := sumGroupTraffic(tx, "c.group_name <> ''") + if err != nil { + return err + } + return applyGroupBaselineShift(tx, totals, -1) +} + // adjustGroupBaselinesForRestoredTraffic shifts group baselines up by counters an // import restored, so usage from before the import never enters a group total. func adjustGroupBaselinesForRestoredTraffic(tx *gorm.DB, emails []string) error { @@ -92,6 +100,10 @@ func shiftGroupBaselines(tx *gorm.DB, emails []string, sign int64) error { } } } + return applyGroupBaselineShift(tx, totals, sign) +} + +func applyGroupBaselineShift(tx *gorm.DB, totals map[string]*groupCounters, sign int64) error { for name, d := range totals { if d.up == 0 && d.down == 0 { continue diff --git a/internal/web/service/client_traffic.go b/internal/web/service/client_traffic.go index 025c83c39..3ea5b8aad 100644 --- a/internal/web/service/client_traffic.go +++ b/internal/web/service/client_traffic.go @@ -252,6 +252,9 @@ func (s *ClientService) ResetAllTraffics() (bool, error) { if qErr != nil { return qErr } + if err := adjustAllGroupBaselinesForRemovedTraffic(tx); err != nil { + return err + } if affected, qErr = zeroClientTraffics(tx, nil, keepOff); qErr != nil { return qErr } From 8438981ef124a8bf2151327fc09807422f02940d Mon Sep 17 00:00:00 2001 From: PluS98 <104105009+Plus98ir@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:01:07 +0300 Subject: [PATCH 019/130] fix(hosts): let the Host form clear its SNI (#7095) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removing the last SNI tag in Hosts → Edit Host and saving did nothing: the submit fell back to the hidden legacy `sni` field, so the old name was sent again and the backend rebuilt the pool from it. It came back on the next edit and stayed in every share link built from that host. The tag list is the only SNI input, so the primary SNI is now the first tag or empty. The dynamic ECH helper read the same stale field and follows the list too. Hosts saved with only the legacy field still load, because the form seeds the tag list from it. --- frontend/src/pages/hosts/HostFormModal.tsx | 6 +-- frontend/src/test/host-form-sni.test.tsx | 47 ++++++++++++++++++++++ 2 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 frontend/src/test/host-form-sni.test.tsx diff --git a/frontend/src/pages/hosts/HostFormModal.tsx b/frontend/src/pages/hosts/HostFormModal.tsx index 9089d711c..8c6b37b40 100644 --- a/frontend/src/pages/hosts/HostFormModal.tsx +++ b/frontend/src/pages/hosts/HostFormModal.tsx @@ -121,8 +121,7 @@ export default function HostFormModal({ watchedSnis && watchedSnis.filter((s) => typeof s === 'string' && s.trim() !== '').length > 1, ); - const watchedSingleSni = useWatch({ control: methods.control, name: 'sni' }) ?? ''; - const hostSni = (watchedSnis && watchedSnis.length > 0 ? watchedSnis[0] : '') || watchedSingleSni; + const hostSni = watchedSnis?.[0] ?? ''; const hostEchConfig = useWatch({ control: methods.control, name: 'echConfigList' }) ?? ''; const showTls = security === 'tls' || security === 'reality' || security === 'same'; const showTlsExtras = security === 'tls' || security === 'same'; @@ -208,11 +207,10 @@ export default function HostFormModal({ const { enable, ...rest } = values; const isDisabled = !enable; const cleanedSnis = (rest.snis || []).map((s) => s.trim()).filter(Boolean); - const primarySni = cleanedSnis.length > 0 ? cleanedSnis[0] : rest.sni || ''; const payload: BulkAddHostValues = { ...rest, hosts: (rest.hosts || []).filter((h) => h && h.trim() !== ''), - sni: primarySni, + sni: cleanedSnis[0] ?? '', snis: cleanedSnis, sniSharedRandom: cleanedSnis.length > 1 && Boolean(rest.sniSharedRandom), isDisabled, diff --git a/frontend/src/test/host-form-sni.test.tsx b/frontend/src/test/host-form-sni.test.tsx new file mode 100644 index 000000000..5e9420013 --- /dev/null +++ b/frontend/src/test/host-form-sni.test.tsx @@ -0,0 +1,47 @@ +import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { HostRecord } from '@/api/queries/useHostsQuery'; +import HostFormModal from '@/pages/hosts/HostFormModal'; +import { HttpUtil, Msg } from '@/utils'; +import { renderWithProviders } from './test-utils'; + +const host = { + groupId: 'g1', + remark: 'DE WS', + inboundIds: [1], + hosts: ['cdn.example.com'], + security: 'same', + sni: 'dash.example.com', + snis: ['dash.example.com'], +} as HostRecord; + +describe('Host form SNI', () => { + beforeEach(() => { + vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', [])); + }); + + it('saves an empty SNI after the last SNI tag is removed', async () => { + const save = vi.fn().mockResolvedValue({ success: true }); + renderWithProviders( + {}} + />, + ); + const tag = await screen.findByTitle('dash.example.com'); + const remove = tag.querySelector('.ant-select-selection-item-remove'); + if (!remove) throw new Error('missing SNI tag remove button'); + fireEvent.click(remove); + await waitFor(() => expect(screen.queryByTitle('dash.example.com')).toBeNull()); + + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(save).toHaveBeenCalledTimes(1)); + expect(save.mock.calls[0][0]).toMatchObject({ sni: '', snis: [] }); + }); +}); From 7367ff75cd5ca8aa2ae12c363d3705e5b22584be Mon Sep 17 00:00:00 2001 From: Aleksey Fedorov <320380254+Dv2Corn@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:13:13 +1000 Subject: [PATCH 020/130] fix(2fa): accept display forms of the TOTP secret and never panic on a bad one (#7113) gotp decodes the stored secret with strict base32 and panics when that fails, so a 2FA secret saved through the settings API in lower case, grouped by spaces, or not base32 at all turned every login and every attempt to turn 2FA off into an HTTP 500. An empty secret had the opposite problem: the login check accepted the code of an empty HMAC key, which anyone can compute. VerifyWithSkew now normalizes the secret and verifies nothing for an empty or non-base32 one, so secrets already stored in a display form work again. Turning 2FA on through the settings update stores the normalized secret and refuses one no authenticator could match. --- internal/util/totp/totp.go | 20 ++++++++- internal/util/totp/totp_test.go | 27 ++++++++++++ internal/web/service/panel/user_test.go | 36 ++++++++++++++++ internal/web/service/setting.go | 6 +++ internal/web/service/setting_security_test.go | 42 ++++++++++++++++++- 5 files changed, 128 insertions(+), 3 deletions(-) diff --git a/internal/util/totp/totp.go b/internal/util/totp/totp.go index 4a25dc42e..96aa09096 100644 --- a/internal/util/totp/totp.go +++ b/internal/util/totp/totp.go @@ -1,6 +1,8 @@ package totp import ( + "encoding/base32" + "strings" "time" "github.com/xlzd/gotp" @@ -10,9 +12,25 @@ import ( // Standard TOTP clock-drift tolerance, see MHSanaei/3x-ui#6535. const SkewWindows = 1 +// NormalizeSecret turns a base32 key as authenticator apps show it (lower case, +// grouped by spaces, padded) into the bare upper-case form gotp decodes. +func NormalizeSecret(secret string) string { + return strings.TrimRight(strings.ToUpper(strings.Join(strings.Fields(secret), "")), "=") +} + +// ValidSecret reports whether secret is a non-empty base32 key once normalized. +func ValidSecret(secret string) bool { + key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(NormalizeSecret(secret)) + return err == nil && len(key) > 0 +} + // VerifyWithSkew accepts the code for the current step plus/minus SkewWindows. +// An empty or non-base32 secret verifies nothing (gotp panics on the latter). func VerifyWithSkew(secret, code string, now time.Time) bool { - totp := gotp.NewDefaultTOTP(secret) + if !ValidSecret(secret) { + return false + } + totp := gotp.NewDefaultTOTP(NormalizeSecret(secret)) for i := -SkewWindows; i <= SkewWindows; i++ { if totp.AtTime(now.Add(time.Duration(i*30)*time.Second)) == code { return true diff --git a/internal/util/totp/totp_test.go b/internal/util/totp/totp_test.go index 1036af6f2..6161e7c56 100644 --- a/internal/util/totp/totp_test.go +++ b/internal/util/totp/totp_test.go @@ -32,3 +32,30 @@ func TestVerifyWithSkew(t *testing.T) { t.Fatal("wrong code should not verify") } } + +func TestVerifyWithSkewSecretForms(t *testing.T) { + const canonical = "JBSWY3DPEHPK3PXP" + now := time.Unix((time.Now().Unix()/30)*30+15, 0).UTC() + code := gotp.NewDefaultTOTP(canonical).AtTime(now) + + cases := []struct { + name string + secret string + want bool + }{ + {"canonical", canonical, true}, + {"lower case", "jbswy3dpehpk3pxp", true}, + {"grouped and padded", " jbsw y3dp ehpk 3pxp== ", true}, + {"empty", "", false}, + {"blank", " ", false}, + {"not base32", "totp-secret", false}, + {"base32 digits out of range", "JBSWY3DPEHPK3PX1", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := VerifyWithSkew(c.secret, code, now); got != c.want { + t.Fatalf("VerifyWithSkew(%q) = %v, want %v", c.secret, got, c.want) + } + }) + } +} diff --git a/internal/web/service/panel/user_test.go b/internal/web/service/panel/user_test.go index 70e26f5b3..7171e53e9 100644 --- a/internal/web/service/panel/user_test.go +++ b/internal/web/service/panel/user_test.go @@ -4,6 +4,9 @@ import ( "path/filepath" "strings" "testing" + "time" + + "github.com/xlzd/gotp" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" @@ -74,3 +77,36 @@ func TestUserSettersRefuseNamesTheLoginRouteRefuses(t *testing.T) { t.Fatalf("stored username = %q (%v), want it unchanged", stored.Username, err) } } + +// A stored 2FA secret in a form gotp cannot decode made every login panic (HTTP 500). +func TestCheckUserTwoFactorSecretForms(t *testing.T) { + cases := []struct { + name, stored, codeSecret string + want bool + }{ + {"canonical", "JBSWY3DPEHPK3PXP", "JBSWY3DPEHPK3PXP", true}, + {"lower case", "jbswy3dpehpk3pxp", "JBSWY3DPEHPK3PXP", true}, + {"not base32", "totp-secret", "JBSWY3DPEHPK3PXP", false}, + {"empty secret", "", "", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db")) + svc := &UserService{} + if err := svc.UpdateFirstUser("admin", "s3cret-Pass"); err != nil { + t.Fatalf("UpdateFirstUser: %v", err) + } + if err := svc.settingService.SetTwoFactorEnable(true); err != nil { + t.Fatal(err) + } + if err := svc.settingService.SetTwoFactorToken(tc.stored); err != nil { + t.Fatal(err) + } + code := gotp.NewDefaultTOTP(tc.codeSecret).AtTime(time.Now()) + user, err := svc.CheckUser("admin", "s3cret-Pass", code) + if got := err == nil && user != nil; got != tc.want { + t.Fatalf("CheckUser with stored secret %q: ok = %v (%v), want %v", tc.stored, got, err, tc.want) + } + }) + } +} diff --git a/internal/web/service/setting.go b/internal/web/service/setting.go index b7a9df205..14643202e 100644 --- a/internal/web/service/setting.go +++ b/internal/web/service/setting.go @@ -1683,6 +1683,12 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears if err := s.preserveRedactedSecrets(allSetting, clears); err != nil { return err } + if allSetting.TwoFactorEnable { + if !totp.ValidSecret(allSetting.TwoFactorToken) { + return errors.New("two-factor secret must be a non-empty base32 key") + } + allSetting.TwoFactorToken = totp.NormalizeSecret(allSetting.TwoFactorToken) + } if err := validateSettingsURLs(allSetting); err != nil { return err } diff --git a/internal/web/service/setting_security_test.go b/internal/web/service/setting_security_test.go index 1b0777303..2d06dae5d 100644 --- a/internal/web/service/setting_security_test.go +++ b/internal/web/service/setting_security_test.go @@ -102,7 +102,7 @@ func TestUpdateAllSettingPreservesRedactedSecrets(t *testing.T) { if err := s.saveSetting("twoFactorEnable", "true"); err != nil { t.Fatal(err) } - if err := s.saveSetting("twoFactorToken", "totp-secret"); err != nil { + if err := s.saveSetting("twoFactorToken", "JBSWY3DPEHPK3PXP"); err != nil { t.Fatal(err) } if err := s.saveSetting("smtpPassword", "smtp-secret"); err != nil { @@ -126,7 +126,7 @@ func TestUpdateAllSettingPreservesRedactedSecrets(t *testing.T) { if got, _ := s.GetLdapPassword(); got != "ldap-secret" { t.Fatalf("ldap password = %q, want preserved secret", got) } - if got, _ := s.GetTwoFactorToken(); got != "totp-secret" { + if got, _ := s.GetTwoFactorToken(); got != "JBSWY3DPEHPK3PXP" { t.Fatalf("2fa token = %q, want preserved secret", got) } if got, _ := s.GetSmtpPassword(); got != "smtp-secret" { @@ -137,6 +137,44 @@ func TestUpdateAllSettingPreservesRedactedSecrets(t *testing.T) { } } +// Turning 2FA on stores the secret in the form the TOTP decoder takes, and refuses +// one that no authenticator code could ever match. +func TestUpdateAllSettingTwoFactorSecret(t *testing.T) { + cases := []struct { + name, stored, submitted, want string + wantErr bool + }{ + {name: "canonical", submitted: "JBSWY3DPEHPK3PXP", want: "JBSWY3DPEHPK3PXP"}, + {name: "lower case and grouped", submitted: "jbsw y3dp ehpk 3pxp", want: "JBSWY3DPEHPK3PXP"}, + {name: "redacted keeps stored", stored: "ORIGINALSECRET234567", submitted: "", want: "ORIGINALSECRET234567"}, + {name: "not base32", stored: "ORIGINALSECRET234567", submitted: "totp-secret", want: "ORIGINALSECRET234567", wantErr: true}, + {name: "nothing stored", submitted: "", want: "", wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + setupSettingTestDB(t) + s := &SettingService{} + if err := s.SetTwoFactorToken(tc.stored); err != nil { + t.Fatal(err) + } + view, err := s.GetAllSettingView() + if err != nil { + t.Fatal(err) + } + settings := &view.AllSetting + settings.TwoFactorEnable = true + settings.TwoFactorToken = tc.submitted + err = s.UpdateAllSetting(settings, SecretClears{}) + if (err != nil) != tc.wantErr { + t.Fatalf("UpdateAllSetting error = %v, wantErr %v", err, tc.wantErr) + } + if got, _ := s.GetTwoFactorToken(); got != tc.want { + t.Fatalf("stored 2FA secret = %q, want %q", got, tc.want) + } + }) + } +} + func TestUpdateAllSettingClearsFlaggedSecrets(t *testing.T) { setupSettingTestDB(t) s := &SettingService{} From 243b5c9da78884066fa8d50bbace36803dd46baa Mon Sep 17 00:00:00 2001 From: Jay Hemnani <193022578+jayhemnani9910@users.noreply.github.com> Date: Fri, 13 Nov 2026 04:54:13 +0530 Subject: [PATCH 021/130] fix(sub): send the serverDescription tail only to clients that read it (#7108) A Host Description is appended to every raw-subscription node name as a base64 `?serverDescription=` tail. Only Happ and INCY read it; v2rayN, v2rayNG, OpenClash and the rest show it as part of the node name, and the only way out was clearing the Description (#7105). The raw subscription body now carries the tail only when the requesting User-Agent is Happ or INCY, for the endpoint links and the Hysteria2 loop alike. Copied links, QR codes and the panel's link export keep it, since the server cannot tell which client they end up in. Closes #7105 --- internal/sub/controller.go | 1 + internal/sub/controller_test.go | 26 +++++++++++++++++++ internal/sub/endpoint.go | 2 +- .../sub/hysteria_server_description_test.go | 3 +++ internal/sub/service.go | 7 ++++- 5 files changed, 37 insertions(+), 2 deletions(-) diff --git a/internal/sub/controller.go b/internal/sub/controller.go index e2de1f750..56d85d2b8 100644 --- a/internal/sub/controller.go +++ b/internal/sub/controller.go @@ -502,6 +502,7 @@ func (a *SUBController) subs(c *gin.Context) { scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c) subReq := a.subService.ForRequest(host) subReq.subscriptionBody = true + subReq.omitServerDescription = !IsHappClient(userAgent) && !IsIncyClient(userAgent) subs, _, _, traffic, err := subReq.getSubs(subId) if err != nil || subs == nil { writeSubError(c, err) diff --git a/internal/sub/controller_test.go b/internal/sub/controller_test.go index fb119c8a9..c07acc016 100644 --- a/internal/sub/controller_test.go +++ b/internal/sub/controller_test.go @@ -803,6 +803,32 @@ func TestLegacyClashEndpointNormalizesShadowsocksCipher(t *testing.T) { } } +// #7105: only Happ and INCY read the tail; other clients show it in the node name. +func TestRawSubServerDescriptionByClient(t *testing.T) { + seedSubDB(t) + seedSubInbound(t, "s1", "vl", 4492, 1, `{"network":"tcp","security":"none","externalProxy":[{"forceTls":"same","dest":"a.example.com","port":443,"remark":"A","serverDescription":"Berlin"}]}`) + gin.SetMode(gin.TestMode) + + cases := map[string]bool{"Happ/3.1": true, "INCY/1.0.0/ios": true, "v2rayN/7.10": false} + for userAgent, wantTail := range cases { + t.Run(userAgent, func(t *testing.T) { + router := gin.New() + NewSUBController(router.Group("/"), WithSUBEncryption(false)) + req := httptest.NewRequest(http.MethodGet, "http://sub.example.com/sub/s1", nil) + req.Header.Set("User-Agent", userAgent) + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + body := resp.Body.String() + if resp.Code != http.StatusOK || !strings.Contains(body, "vless") { + t.Fatalf("status=%d, body=%s", resp.Code, body) + } + if got := strings.Contains(body, "?serverDescription=QmVybGlu"); got != wantTail { + t.Fatalf("tail present = %v, want %v; body=%s", got, wantTail, body) + } + }) + } +} + func TestIncyRoutingIsolatedFromHappHeaders(t *testing.T) { seedSubDB(t) seedSubInbound(t, "s1", "vl", 4492, 1, `{"network":"tcp","security":"none"}`) diff --git a/internal/sub/endpoint.go b/internal/sub/endpoint.go index 5d8c9d34d..0db4dd5fb 100644 --- a/internal/sub/endpoint.go +++ b/internal/sub/endpoint.go @@ -136,7 +136,7 @@ func (s *SubService) buildEndpointLinks( applyEndpointFinalMask(e, nextParams) applyEndpointAllowInsecure(e, nextParams, securityToApply) remark := makeRemark(e) - if e.ServerDescription != "" { + if e.ServerDescription != "" && !s.omitServerDescription { remark = appendHappServerDescription(remark, e.ServerDescription) } links = append(links, buildLinkWithParamsAndSecurity( diff --git a/internal/sub/hysteria_server_description_test.go b/internal/sub/hysteria_server_description_test.go index 2dd7c440e..9f750a2c5 100644 --- a/internal/sub/hysteria_server_description_test.go +++ b/internal/sub/hysteria_server_description_test.go @@ -52,6 +52,9 @@ func TestGenHysteriaLinkAppendsHostServerDescription(t *testing.T) { if !strings.HasSuffix(got, "?serverDescription=V2ktRmk=") { t.Fatalf("host serverDescription missing from fragment.\n got: %s\nwant suffix: ?serverDescription=V2ktRmk=", got) } + if got := (&SubService{omitServerDescription: true}).genHysteriaLink(in, "user"); strings.Contains(got, "serverDescription") { + t.Fatalf("tail not omitted: %s", got) + } }) } } diff --git a/internal/sub/service.go b/internal/sub/service.go index 49c53cef4..4287f28d2 100644 --- a/internal/sub/service.go +++ b/internal/sub/service.go @@ -46,6 +46,9 @@ type SubService struct { // other context — the sub info page, the panel's link/QR displays — renders // the name-only template, like Remnawave. subscriptionBody bool + // omitServerDescription drops the ?serverDescription= tail, which only Happ + // and INCY read; other clients show it in the node name (#7105). + omitServerDescription bool // usageShown emits info once per subscription identity, including twins. // PrepareForRequest resets this per-request state. usageShown map[string]bool @@ -1744,7 +1747,9 @@ func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) strin // VLESS/Trojan/SS get the host's description through buildEndpointLinks; // this loop renders the fragment itself, so add it here too (#6738). remark := s.endpointRemark(inbound, email, ep, "quic") - remark = appendHappServerDescription(remark, externalProxyToEndpoint(ep).ServerDescription) + if !s.omitServerDescription { + remark = appendHappServerDescription(remark, externalProxyToEndpoint(ep).ServerDescription) + } links = append(links, buildLinkWithParams(link, epParams, remark)) } return strings.Join(links, "\n") From 3a28d130a7424715230e905f0db3bff86302cf35 Mon Sep 17 00:00:00 2001 From: PluS98 <104105009+Plus98ir@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:42:16 +0300 Subject: [PATCH 022/130] fix(tgbot): keep backup files in the chat and the menu below them (#7092) Every bot notice carries a Hide button, which deletes the message it sits on. On a backup that message is the file itself: one tap, with no confirmation, could remove the admin's only copy of the database. Backup files (the .db and config.json, from the backup button, the scheduled job and the panel's backup-to-Telegram endpoint) are now sent without a keyboard; other notices, including the ban log file, keep Hide. The backup button also left the menu above the files it sent, out of view at the bottom of the chat. It now sends the Maintenance menu again below them and removes the old one. A scheduled backup leaves the menu where it is. --- .../web/service/tgbot/backup_delivery_test.go | 135 ++++++++++++++++++ internal/web/service/tgbot/notices.go | 13 +- internal/web/service/tgbot/notices_test.go | 2 +- internal/web/service/tgbot/screen_view.go | 4 +- internal/web/service/tgbot/screen_views.go | 4 +- internal/web/service/tgbot/screens_test.go | 19 ++- internal/web/service/tgbot/tgbot_report.go | 4 +- internal/web/service/tgbot/tgbot_router.go | 2 + 8 files changed, 168 insertions(+), 15 deletions(-) create mode 100644 internal/web/service/tgbot/backup_delivery_test.go diff --git a/internal/web/service/tgbot/backup_delivery_test.go b/internal/web/service/tgbot/backup_delivery_test.go new file mode 100644 index 000000000..a09223140 --- /dev/null +++ b/internal/web/service/tgbot/backup_delivery_test.go @@ -0,0 +1,135 @@ +package tgbot + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/mymmrac/telego" +) + +const testXrayConfig = `{"log":{}}` + +// backupFixture gives GetDb and the config read real files in a throwaway folder. +func backupFixture(t *testing.T) (*Tgbot, func() []apiCall) { + t.Helper() + _, calls := newScreenTgbot(t, false) + t.Setenv("XUI_DB_FOLDER", t.TempDir()) + binFolder := t.TempDir() + t.Setenv("XUI_BIN_FOLDER", binFolder) + if err := os.WriteFile(filepath.Join(binFolder, "config.json"), []byte(testXrayConfig), 0o600); err != nil { + t.Fatal(err) + } + tb := initReportDB(t) + setTestAdmins(t, 1) + tb.resolveScreenArt() + return tb, calls +} + +func documentsOf(calls []apiCall) []apiCall { + var documents []apiCall + for _, call := range calls { + if call.Method == "sendDocument" { + documents = append(documents, call) + } + } + return documents +} + +// A Hide button on a backup deleted the admin's only copy of the database with +// one tap, so neither delivery path may offer a way to delete the files. +func TestBackupFilesCarryNoHideButton(t *testing.T) { + for _, tc := range []struct { + name string + deliver func(tb *Tgbot) + }{ + {"backup button", func(tb *Tgbot) { + tb.answerCallback(&telego.CallbackQuery{ + ID: "q1", From: telego.User{ID: 1}, Data: cbBackup, + Message: &telego.Message{MessageID: 50, Chat: telego.Chat{ID: 1, Type: "private"}}, + }, true) + }}, + {"scheduled backup", func(tb *Tgbot) { tb.SendBackupToAdmins() }}, + } { + t.Run(tc.name, func(t *testing.T) { + tb, calls := backupFixture(t) + tc.deliver(tb) + + documents := documentsOf(calls()) + if len(documents) != 2 { + t.Fatalf("documents = %d, want the database and config.json (calls: %v)", len(documents), methods(calls())) + } + dbName, _ := documents[0].Payload["filename"].(string) + if !strings.HasSuffix(dbName, ".db") || documents[1].Payload["filename"] != "config.json" { + t.Errorf("files = %q, %v; want a .db then config.json", dbName, documents[1].Payload["filename"]) + } + for _, document := range documents { + if markup, ok := document.Payload["reply_markup"]; ok { + t.Errorf("%v carries a keyboard that can delete it: %v", document.Payload["filename"], markup) + } + } + }) + } +} + +// The files used to land under the menu and bury it, so the bot looked dead to +// an admin who stayed at the bottom of the chat. +func TestBackupButtonMovesTheMenuBelowTheFiles(t *testing.T) { + tb, calls := backupFixture(t) + const chatID int64 = 1 + tb.screenCategory(chatID, "maintenance") + menu, ok := tb.screens().get(chatID) + if !ok { + t.Fatal("menu not tracked") + } + before := len(calls()) + + tb.answerCallback(&telego.CallbackQuery{ + ID: "q1", From: telego.User{ID: 1}, Data: cbBackup, + Message: &telego.Message{MessageID: menu.msgID, Chat: telego.Chat{ID: chatID, Type: "private"}}, + }, true) + + got := calls()[before:] + want := []string{"answerCallbackQuery", "sendDocument", "sendDocument", "sendPhoto", "deleteMessage"} + if !reflect.DeepEqual(methods(got), want) { + t.Fatalf("calls = %v, want %v", methods(got), want) + } + if deleted := got[4].Payload["message_id"]; deleted != float64(menu.msgID) { + t.Errorf("deleted message %v, want the old menu %d", deleted, menu.msgID) + } + current, ok := tb.screens().get(chatID) + if !ok || current.msgID == menu.msgID || !hasButton(current.rows, cbBackup) { + t.Errorf("tracked screen = %+v, want a new maintenance menu", current) + } +} + +// A scheduled backup arrives unprompted: it must not move a menu the admin may +// be using at that moment. +func TestScheduledBackupLeavesTheMenuInPlace(t *testing.T) { + tb, calls := backupFixture(t) + tb.screenCategory(1, "maintenance") + menu, _ := tb.screens().get(1) + before := len(calls()) + + tb.SendBackupToAdmins() + + if got := methods(calls()[before:]); !reflect.DeepEqual(got, []string{"sendDocument", "sendDocument"}) { + t.Errorf("calls = %v, want only the two files", got) + } + if current, _ := tb.screens().get(1); current.msgID != menu.msgID { + t.Errorf("tracked menu moved from %d to %d", menu.msgID, current.msgID) + } +} + +func hasButton(rows [][]telego.InlineKeyboardButton, data string) bool { + for _, row := range rows { + for _, button := range row { + if button.CallbackData == data { + return true + } + } + } + return false +} diff --git a/internal/web/service/tgbot/notices.go b/internal/web/service/tgbot/notices.go index d290f291b..01e59018b 100644 --- a/internal/web/service/tgbot/notices.go +++ b/internal/web/service/tgbot/notices.go @@ -129,9 +129,9 @@ func (t *Tgbot) dropNoticeFor(chatID int64, msgID int) { } } -// sendDocumentWithCaption uploads a file with its summary as caption: a document -// cannot hold a screen, so one message does the work of two. -func (t *Tgbot) sendDocumentWithCaption(chatID int64, data []byte, name, caption string) bool { +// sendBackupFile uploads a file with its summary as caption. It has no hide button: +// that button deletes the message, and this may be the admin's only copy. +func (t *Tgbot) sendBackupFile(chatID int64, data []byte, name, caption string) bool { if liveBot() == nil || data == nil { return false } @@ -139,10 +139,9 @@ func (t *Tgbot) sendDocumentWithCaption(chatID int64, data []byte, name, caption defer cancel() _, err := liveBot().SendDocument(ctx, &telego.SendDocumentParams{ ChatID: tu.ID(chatID), MessageThreadID: adminTopic(chatID), - Document: tu.FileFromBytes(data, name), - Caption: caption, - ParseMode: "HTML", - ReplyMarkup: t.hideButton(), + Document: tu.FileFromBytes(data, name), + Caption: caption, + ParseMode: "HTML", }) if err != nil { logger.Warning("Failed to upload a file with a caption:", err) diff --git a/internal/web/service/tgbot/notices_test.go b/internal/web/service/tgbot/notices_test.go index 1ba5faa05..ab1420048 100644 --- a/internal/web/service/tgbot/notices_test.go +++ b/internal/web/service/tgbot/notices_test.go @@ -96,7 +96,7 @@ func TestBackupArrivesAsOneMessageWithACaption(t *testing.T) { notices.reset() tb := initReportDB(t) - tb.sendDocumentWithCaption(1, []byte("db-bytes"), "x-ui.db", "host\nbackup time") + tb.sendBackupFile(1, []byte("db-bytes"), "x-ui.db", "host\nbackup time") got := calls() sends := 0 diff --git a/internal/web/service/tgbot/screen_view.go b/internal/web/service/tgbot/screen_view.go index e147743ed..3f0d0f4de 100644 --- a/internal/web/service/tgbot/screen_view.go +++ b/internal/web/service/tgbot/screen_view.go @@ -89,11 +89,11 @@ func (t *Tgbot) categoryRows(category string) [][]telego.InlineKeyboardButton { // screenCategory draws one menu subject. The hint line names the subject, so a // user who arrived through a notification can see where they are. -func (t *Tgbot) screenCategory(chatID int64, category string) { +func (t *Tgbot) screenCategory(chatID int64, category string, delivery ...screenDelivery) { body := t.I18nBot("tgbot.messages.category_" + category) rows := [][]telego.InlineKeyboardButton{} rows = append(rows, t.categoryRows(category)...) - t.renderScreen(chatID, t.newScreen("main", body, rows...)) + t.renderScreen(chatID, t.newScreen("main", body, rows...), delivery...) } // btn is where a localized label becomes a callback button; btn2 is btn with a diff --git a/internal/web/service/tgbot/screen_views.go b/internal/web/service/tgbot/screen_views.go index 4deeaf295..73e3f4fc0 100644 --- a/internal/web/service/tgbot/screen_views.go +++ b/internal/web/service/tgbot/screen_views.go @@ -266,11 +266,11 @@ func (t *Tgbot) sendBackupScreen(chatID int64) { // carries the backup and what it is for. body := summary + "\n\n" + t.depleteReport() caption := trimCaption(body, botCaptionLimit) - if t.sendDocumentWithCaption(chatID, dbData, t.serverService.BackupFilename(""), caption) { + if t.sendBackupFile(chatID, dbData, t.serverService.BackupFilename(""), caption) { // The generated config travels with the DB on both backup paths: an // operator restoring from the file would otherwise lose it silently. if config, err := os.ReadFile(xray.GetConfigPath()); err == nil { - t.sendDocumentWithCaption(chatID, config, "config.json", "") + t.sendBackupFile(chatID, config, "config.json", "") } if rest := strings.TrimSpace(strings.TrimPrefix(body, caption)); rest != "" { // Rare: the summary outgrew a caption. The file already landed. diff --git a/internal/web/service/tgbot/screens_test.go b/internal/web/service/tgbot/screens_test.go index 8775554ed..8212cdf6b 100644 --- a/internal/web/service/tgbot/screens_test.go +++ b/internal/web/service/tgbot/screens_test.go @@ -60,7 +60,8 @@ func recordingServer(t *testing.T, failEdit bool, overrides ...map[string]any) ( if strings.HasPrefix(string(body), "{") { // JSON payload: keep it as decoded. } else { - payload = map[string]any{} + r.Body = io.NopCloser(bytes.NewReader(body)) + payload = multipartPayload(r) } mu.Lock() calls = append(calls, apiCall{Method: method, Payload: payload}) @@ -139,6 +140,22 @@ func recordingServer(t *testing.T, failEdit bool, overrides ...map[string]any) ( } } +// multipartPayload exposes an upload's form fields as a payload; the uploaded +// document's file name is under "filename". +func multipartPayload(r *http.Request) map[string]any { + payload := map[string]any{} + if r.ParseMultipartForm(1<<22) != nil { + return payload + } + for name, values := range r.MultipartForm.Value { + payload[name] = values[0] + } + if files := r.MultipartForm.File["document"]; len(files) > 0 { + payload["filename"] = files[0].Filename + } + return payload +} + // newScreenTgbot points the package bot at a recording server and clears the // process-wide screen state the previous test may have left behind. func newScreenTgbot(t *testing.T, failEdit bool) (*Tgbot, func() []apiCall) { diff --git a/internal/web/service/tgbot/tgbot_report.go b/internal/web/service/tgbot/tgbot_report.go index 1b377896e..a37239efc 100644 --- a/internal/web/service/tgbot/tgbot_report.go +++ b/internal/web/service/tgbot/tgbot_report.go @@ -123,10 +123,10 @@ func (t *Tgbot) SendBackupToAdmins() { if dbData == nil { t.sendNotice(adminId, t.I18nBot("tgbot.messages.backupFailed")) } else { - t.sendDocumentWithCaption(adminId, dbData, dbFilename, t.backupSummary()) + t.sendBackupFile(adminId, dbData, dbFilename, t.backupSummary()) time.Sleep(500 * time.Millisecond) if configErr == nil { - t.sendDocumentWithCaption(adminId, config, "config.json", "") + t.sendBackupFile(adminId, config, "config.json", "") } } // Add delay between sends to avoid Telegram rate limits diff --git a/internal/web/service/tgbot/tgbot_router.go b/internal/web/service/tgbot/tgbot_router.go index 2fe033e84..1c65523cd 100644 --- a/internal/web/service/tgbot/tgbot_router.go +++ b/internal/web/service/tgbot/tgbot_router.go @@ -1000,6 +1000,8 @@ func (t *Tgbot) answerCallback(callbackQuery *telego.CallbackQuery, isAdmin bool case "bkp", "get_backup": t.answerSilent(callbackQuery.ID) t.sendBackupScreen(chatId) + // The files landed under the menu; bring it back below them so it stays in view. + t.screenCategory(chatId, "maintenance", screenSendNew) case "ban", "get_banlogs": t.answerSilent(callbackQuery.ID) t.screenBanLogs(chatId) From 21aa66262911a3a8e0492c263a81a00d406078f5 Mon Sep 17 00:00:00 2001 From: Nikan Zeyaei <72458440+NikanZeyaei@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:24:30 +0330 Subject: [PATCH 023/130] docs(nodes): note that updating an mTLS node needs a node-admin token (#6957) A master that reaches a node over mTLS with no bearer token is treated as node-sync, which cannot call /server/updatePanel, so "Update panel" on such a node fails with HTTP 403. That is intended, but the multi-node guide said the API token is "not needed in mTLS mode" (#6953). The guide (en/fa/ru/zh) and the node form's mTLS hint (all 14 locales) now say that updating the node from the master still needs a token with the node-admin scope. No logic changes. The CI workflow's path filter does not cover internal/web/translation or docs, so only Docs CI ran on this head; the locale-dependent tests were run locally. --- docs/content/docs/en/operations/multi-node.mdx | 10 +++++++++- docs/content/docs/fa/operations/multi-node.mdx | 10 +++++++++- docs/content/docs/ru/operations/multi-node.mdx | 11 ++++++++++- docs/content/docs/zh/operations/multi-node.mdx | 6 +++++- internal/web/translation/ar-EG.json | 2 +- internal/web/translation/en-US.json | 2 +- internal/web/translation/es-ES.json | 2 +- internal/web/translation/fa-IR.json | 2 +- internal/web/translation/id-ID.json | 2 +- internal/web/translation/ja-JP.json | 2 +- internal/web/translation/pt-BR.json | 2 +- internal/web/translation/ru-RU.json | 2 +- internal/web/translation/sk-SK.json | 2 +- internal/web/translation/tr-TR.json | 2 +- internal/web/translation/uk-UA.json | 2 +- internal/web/translation/vi-VN.json | 2 +- internal/web/translation/zh-CN.json | 2 +- internal/web/translation/zh-TW.json | 2 +- 18 files changed, 47 insertions(+), 18 deletions(-) diff --git a/docs/content/docs/en/operations/multi-node.mdx b/docs/content/docs/en/operations/multi-node.mdx index f2ae13e38..abcffac62 100644 --- a/docs/content/docs/en/operations/multi-node.mdx +++ b/docs/content/docs/en/operations/multi-node.mdx @@ -23,7 +23,7 @@ Provide the node's connection details: | **Scheme** | `https` (default) or `http`. | | **Address / Port**| The node panel's host and port. | | **Base path** | The node's web base path. | -| **API token** | A Bearer token created on the node (not needed in mTLS mode). | +| **API token** | A Bearer token created on the node. Optional in mTLS mode, except for **Update panel** (needs `node-admin`). | | **TLS verify** | `verify` (default), `skip`, `pin` (pin a cert SHA-256), or `mtls`. | | **Inbound sync** | `all` inbounds, or `selected` by tag. | | **Outbound tag** | Optionally reach the node **through** a named outbound (egress bridge).| @@ -64,6 +64,14 @@ next restart. Set the node's TLS verify mode to `mtls`. The master now presents a client certificate instead of an API token. + + + A node reached over mTLS without a token only has the `node-sync` scope, which + cannot run **Update panel** (the node answers HTTP 403, "this API token is not + permitted to access this endpoint"). To update such a node from the master, + create an API token with the `node-admin` scope on the node and paste it into + the master's **API token** field for that node. Keep TLS verify on `mtls`. + diff --git a/docs/content/docs/fa/operations/multi-node.mdx b/docs/content/docs/fa/operations/multi-node.mdx index 63aa1078d..f84696186 100644 --- a/docs/content/docs/fa/operations/multi-node.mdx +++ b/docs/content/docs/fa/operations/multi-node.mdx @@ -20,7 +20,7 @@ icon: Boxes | **Scheme** | `https` (پیش‌فرض) یا `http`. | | **Address / Port**| میزبان و پورت پنل نود. | | **Base path** | مسیر پایهٔ وب نود. | -| **API token** | یک توکن Bearer که روی نود ساخته می‌شود (در حالت mTLS لازم نیست). | +| **API token** | یک توکن Bearer که روی نود ساخته می‌شود (در حالت mTLS اختیاری است، به‌جز **به‌روزرسانی پنل** که به توکن `node-admin` نیاز دارد). | | **TLS verify** | `verify` (پیش‌فرض)، `skip`، `pin` (پین‌کردن SHA-256 گواهی) یا `mtls`. | | **Inbound sync** | همهٔ inboundها (`all`) یا انتخاب‌شده (`selected`) بر اساس تگ. | | **Outbound tag** | به‌اختیار از طریق یک outbound نام‌دار به نود برسید (پل خروجی). | @@ -59,6 +59,14 @@ icon: Boxes حالت TLS verify نود را روی `mtls` تنظیم کنید. اکنون مستر به‌جای یک توکن API یک گواهی کلاینت ارائه می‌دهد. + + + نودی که بدون توکن و از طریق mTLS متصل شده فقط دامنهٔ `node-sync` را دارد و نمی‌تواند + **به‌روزرسانی پنل** را اجرا کند (نود پاسخ HTTP 403 با پیام + «this API token is not permitted to access this endpoint» می‌دهد). برای به‌روزرسانی + چنین نودی از مستر، روی نود یک توکن API با دامنهٔ `node-admin` بسازید و آن را در + فیلد **API token** همان نود در مستر وارد کنید. حالت TLS verify را روی `mtls` نگه دارید. + diff --git a/docs/content/docs/ru/operations/multi-node.mdx b/docs/content/docs/ru/operations/multi-node.mdx index 6c3cb4ccd..6580839f0 100644 --- a/docs/content/docs/ru/operations/multi-node.mdx +++ b/docs/content/docs/ru/operations/multi-node.mdx @@ -24,7 +24,7 @@ API этого узла. Главная панель опрашивает каж | **Схема** | `https` (по умолчанию) или `http`. | | **Адрес / Порт** | Хост и порт панели узла. | | **Базовый путь** | Веб-базовый путь узла. | -| **API-токен** | Bearer-токен, созданный на узле (не нужен в режиме mTLS). | +| **API-токен** | Bearer-токен, созданный на узле (в режиме mTLS необязателен, кроме **Обновления панели** — нужен `node-admin`). | | **Проверка TLS** | `verify` (по умолчанию), `skip`, `pin` (закрепить SHA-256 сертификата) или `mtls`. | | **Синхронизация inbound** | `all` (все) inbound-соединения или `selected` (выбранные) по тегу. | | **Тег исходящего**| При необходимости обращаться к узлу **через** именованное исходящее соединение (мост исходящего трафика). | @@ -67,6 +67,15 @@ API этого узла. Главная панель опрашивает каж Задайте на узле режим проверки TLS `mtls`. Теперь главная панель предъявляет клиентский сертификат вместо API-токена. + + + Узел, подключённый по mTLS без токена, имеет только область `node-sync`, которая + не позволяет выполнить **Обновление панели** (узел отвечает HTTP 403, + «this API token is not permitted to access this endpoint»). Чтобы обновить такой + узел с главной панели, создайте на узле API-токен с областью `node-admin` и + вставьте его в поле **API-токен** этого узла на главной панели. Режим проверки + TLS оставьте `mtls`. + diff --git a/docs/content/docs/zh/operations/multi-node.mdx b/docs/content/docs/zh/operations/multi-node.mdx index 2f7101ee2..66233a8f3 100644 --- a/docs/content/docs/zh/operations/multi-node.mdx +++ b/docs/content/docs/zh/operations/multi-node.mdx @@ -20,7 +20,7 @@ icon: Boxes | **Scheme** | `https`(默认)或 `http`。 | | **Address / Port**| 节点面板的主机和端口。 | | **Base path** | 节点的 Web 基础路径。 | -| **API token** | 在节点上创建的 Bearer 令牌(mTLS 模式下不需要)。 | +| **API token** | 在节点上创建的 Bearer 令牌(mTLS 模式下可选,但**更新面板**需要 `node-admin` 令牌)。 | | **TLS verify** | `verify`(默认)、`skip`、`pin`(固定证书 SHA-256)或 `mtls`。 | | **Inbound sync** | `all` 入站,或按标签 `selected`。 | | **Outbound tag** | 可选地**通过**指定的出站到达节点(出口桥接)。 | @@ -53,6 +53,10 @@ icon: Boxes ### 将节点切换到 mTLS 将节点的 TLS 验证模式设置为 `mtls`。现在主控将出示客户端证书而非 API 令牌。 + + + 通过 mTLS 连接且未提供令牌的节点只具有 `node-sync` 权限范围,无法执行**更新面板**(节点返回 HTTP 403,“this API token is not permitted to access this endpoint”)。要从主控更新此类节点,请在节点上创建具有 `node-admin` 权限范围的 API 令牌,并将其填入主控中该节点的 **API token** 字段。TLS 验证模式保持为 `mtls`。 + diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index e152133e2..08b8cbe64 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -1194,7 +1194,7 @@ "tlsPin": "تثبيت الشهادة (SHA-256)", "tlsSkip": "تخطّي التحقق", "tlsMtls": "TLS متبادل (شهادة العميل)", - "mtlsFormHint": "يصادق هذا النود اللوحة باستخدام شهادة عميل. انسخ CA الخاص بهذه اللوحة من قسم mTLS النود إلى النود، واضبط CA الموثوق به، ثم أعد تشغيله.", + "mtlsFormHint": "يصادق هذا النود اللوحة باستخدام شهادة عميل. انسخ CA الخاص بهذه اللوحة من قسم mTLS النود إلى النود، واضبط CA الموثوق به، ثم أعد تشغيله. لا يزال تحديث لوحة هذا النود من هنا يتطلب رمز API بنطاق node-admin.", "mtls": { "title": "mTLS النود", "intro": "يضيف TLS المتبادل عامل شهادة العميل فوق رمز API في الاتصالات بين النودات. وهو اختياري: اتركه فارغًا للاكتفاء بالمصادقة عبر الرمز.", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 05599684a..57a915a52 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -1315,7 +1315,7 @@ "tlsPin": "Pin certificate (SHA-256)", "tlsSkip": "Skip verification", "tlsMtls": "Mutual TLS (client certificate)", - "mtlsFormHint": "This node authenticates the panel with a client certificate. Copy this panel's CA from the Node mTLS section onto the node, set its Trusted parent CA, then restart it.", + "mtlsFormHint": "This node authenticates the panel with a client certificate. Copy this panel's CA from the Node mTLS section onto the node, set its Trusted parent CA, then restart it. Updating this node's panel from here still needs an API token with the node-admin scope.", "mtls": { "title": "Node mTLS", "intro": "Mutual TLS adds a client-certificate factor on top of the API token for node-to-node calls. It is opt-in: leave it empty to keep token-only auth.", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 8ea61b93b..c780eda85 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -1194,7 +1194,7 @@ "tlsPin": "Fijar certificado (SHA-256)", "tlsSkip": "Omitir verificación", "tlsMtls": "TLS mutuo (certificado de cliente)", - "mtlsFormHint": "Este nodo autentica al panel con un certificado de cliente. Copia el CA de este panel desde la sección mTLS del nodo al nodo, configura su CA de confianza y luego reinícialo.", + "mtlsFormHint": "Este nodo autentica al panel con un certificado de cliente. Copia el CA de este panel desde la sección mTLS del nodo al nodo, configura su CA de confianza y luego reinícialo. Actualizar el panel de este nodo desde aquí sigue requiriendo un token de API con el alcance node-admin.", "mtls": { "title": "mTLS del nodo", "intro": "TLS mutuo añade un factor de certificado de cliente además del token de API para las llamadas entre nodos. Es opcional: déjalo vacío para mantener solo la autenticación por token.", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 7ab61bd43..5922171e0 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -1194,7 +1194,7 @@ "tlsPin": "Pin گواهی (SHA-256)", "tlsSkip": "رد کردن اعتبارسنجی", "tlsMtls": "TLS متقابل (گواهی کلاینت)", - "mtlsFormHint": "این نود با یک گواهی کلاینت، پنل را احراز هویت می‌کند. CA این پنل را از بخش mTLS نود به نود کپی کنید، CA مورد اعتماد آن را تنظیم کنید و سپس آن را راه‌اندازی مجدد کنید.", + "mtlsFormHint": "این نود با یک گواهی کلاینت، پنل را احراز هویت می‌کند. CA این پنل را از بخش mTLS نود به نود کپی کنید، CA مورد اعتماد آن را تنظیم کنید و سپس آن را راه‌اندازی مجدد کنید. به‌روزرسانی پنل این نود از اینجا همچنان به یک توکن API با دامنهٔ node-admin نیاز دارد.", "mtls": { "title": "mTLS نود", "intro": "TLS متقابل علاوه بر توکن API، یک عامل گواهی کلاینت برای ارتباط بین نودها اضافه می‌کند. اختیاری است: برای استفاده فقط از احراز هویت با توکن، آن را خالی بگذارید.", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index d08644082..6102b7450 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -1194,7 +1194,7 @@ "tlsPin": "Pin sertifikat (SHA-256)", "tlsSkip": "Lewati verifikasi", "tlsMtls": "TLS mutual (sertifikat klien)", - "mtlsFormHint": "Node ini mengautentikasi panel dengan sertifikat klien. Salin CA panel ini dari bagian mTLS Node ke node, atur CA tepercayanya, lalu mulai ulang.", + "mtlsFormHint": "Node ini mengautentikasi panel dengan sertifikat klien. Salin CA panel ini dari bagian mTLS Node ke node, atur CA tepercayanya, lalu mulai ulang. Memperbarui panel node ini dari sini tetap memerlukan token API dengan cakupan node-admin.", "mtls": { "title": "mTLS Node", "intro": "TLS mutual menambahkan faktor sertifikat klien di atas token API untuk panggilan antar-node. Bersifat opsional: biarkan kosong untuk tetap menggunakan autentikasi token saja.", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index f1f84a9a2..61ca87665 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -1194,7 +1194,7 @@ "tlsPin": "証明書をピン留め(SHA-256)", "tlsSkip": "検証をスキップ", "tlsMtls": "相互 TLS(クライアント証明書)", - "mtlsFormHint": "このノードはクライアント証明書でパネルを認証します。「ノード mTLS」セクションからこのパネルの CA をノードにコピーし、信頼する CA を設定してから再起動してください。", + "mtlsFormHint": "このノードはクライアント証明書でパネルを認証します。「ノード mTLS」セクションからこのパネルの CA をノードにコピーし、信頼する CA を設定してから再起動してください。 ここからこのノードのパネルを更新するには、node-admin スコープの API トークンが引き続き必要です。", "mtls": { "title": "ノード mTLS", "intro": "相互 TLS は、ノード間通信で API トークンに加えてクライアント証明書による認証を追加します。任意です。空のままにするとトークンのみの認証になります。", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 8e4a29bc1..5172553e4 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -1194,7 +1194,7 @@ "tlsPin": "Fixar certificado (SHA-256)", "tlsSkip": "Ignorar verificação", "tlsMtls": "TLS mútuo (certificado de cliente)", - "mtlsFormHint": "Este nó autentica o painel com um certificado de cliente. Copie o CA deste painel na seção mTLS do nó para o nó, defina o CA confiável dele e reinicie-o.", + "mtlsFormHint": "Este nó autentica o painel com um certificado de cliente. Copie o CA deste painel na seção mTLS do nó para o nó, defina o CA confiável dele e reinicie-o. Atualizar o painel deste nó a partir daqui ainda exige um token de API com o escopo node-admin.", "mtls": { "title": "mTLS do nó", "intro": "O TLS mútuo adiciona um fator de certificado de cliente além do token de API nas chamadas entre nós. É opcional: deixe vazio para manter apenas a autenticação por token.", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index fae67a37a..350e8399a 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -1194,7 +1194,7 @@ "tlsPin": "Закрепить сертификат (SHA-256)", "tlsSkip": "Пропустить проверку", "tlsMtls": "Взаимный TLS (клиентский сертификат)", - "mtlsFormHint": "Этот узел аутентифицирует панель с помощью клиентского сертификата. Скопируйте CA этой панели из раздела «mTLS узла» на узел, задайте его доверенный CA и перезапустите узел.", + "mtlsFormHint": "Этот узел аутентифицирует панель с помощью клиентского сертификата. Скопируйте CA этой панели из раздела «mTLS узла» на узел, задайте его доверенный CA и перезапустите узел. Для обновления панели этого узла отсюда по-прежнему нужен API-токен с областью node-admin.", "mtls": { "title": "mTLS узла", "intro": "Взаимный TLS добавляет фактор клиентского сертификата поверх API-токена для вызовов между узлами. Это необязательно: оставьте пустым, чтобы использовать только аутентификацию по токену.", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 0b5a38bfe..07eaa676d 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -1315,7 +1315,7 @@ "tlsPin": "Pevný odtlačok certifikátu (SHA-256)", "tlsSkip": "Vynechať overenie", "tlsMtls": "Vzájomné TLS (klientsky certifikát)", - "mtlsFormHint": "Tento server overuje panel klientskym certifikátom. Skopírujte certifikačnú autoritu tohto panelu z časti mTLS serverov na vzdialený server, nastavte jeho dôveryhodnú nadradenú autoritu a potom ho reštartujte.", + "mtlsFormHint": "Tento server overuje panel klientskym certifikátom. Skopírujte certifikačnú autoritu tohto panelu z časti mTLS serverov na vzdialený server, nastavte jeho dôveryhodnú nadradenú autoritu a potom ho reštartujte. Aktualizácia panelu tohto servera odtiaľto stále vyžaduje API token s rozsahom node-admin.", "mtls": { "title": "mTLS serverov", "intro": "Vzájomné TLS pridáva k tokenu API aj overenie klientskym certifikátom pri komunikácii medzi servermi. Je voliteľné. Prázdne nastavenie ponechá overenie iba tokenom.", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 0909deae6..df2d995b9 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -1194,7 +1194,7 @@ "tlsPin": "Sertifikayı Sabitle (SHA-256)", "tlsSkip": "Doğrulamayı Atla", "tlsMtls": "Karşılıklı TLS (istemci sertifikası)", - "mtlsFormHint": "Bu düğüm, paneli bir istemci sertifikasıyla doğrular. Düğüm mTLS bölümünden bu panelin CA’sını düğüme kopyalayın, güvenilen CA’sını ayarlayın ve ardından düğümü yeniden başlatın.", + "mtlsFormHint": "Bu düğüm, paneli bir istemci sertifikasıyla doğrular. Düğüm mTLS bölümünden bu panelin CA’sını düğüme kopyalayın, güvenilen CA’sını ayarlayın ve ardından düğümü yeniden başlatın. Bu düğümün panelini buradan güncellemek için yine de node-admin kapsamlı bir API belirteci gerekir.", "mtls": { "title": "Düğüm mTLS", "intro": "Karşılıklı TLS, düğümler arası çağrılarda API belirtecinin yanına bir istemci sertifikası faktörü ekler. İsteğe bağlıdır: yalnızca belirteçle kimlik doğrulamayı sürdürmek için boş bırakın.", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index acac29f67..23dbefe4c 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -1194,7 +1194,7 @@ "tlsPin": "Закріпити сертифікат (SHA-256)", "tlsSkip": "Пропустити перевірку", "tlsMtls": "Взаємний TLS (клієнтський сертифікат)", - "mtlsFormHint": "Цей вузол автентифікує панель за допомогою клієнтського сертифіката. Скопіюйте CA цієї панелі з розділу «mTLS вузла» на вузол, задайте його довірений CA та перезапустіть вузол.", + "mtlsFormHint": "Цей вузол автентифікує панель за допомогою клієнтського сертифіката. Скопіюйте CA цієї панелі з розділу «mTLS вузла» на вузол, задайте його довірений CA та перезапустіть вузол. Для оновлення панелі цього вузла звідси все одно потрібен API-токен з областю node-admin.", "mtls": { "title": "mTLS вузла", "intro": "Взаємний TLS додає фактор клієнтського сертифіката поверх API-токена для викликів між вузлами. Це необов’язково: залиште порожнім, щоб використовувати лише автентифікацію за токеном.", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 0e2a172bf..8693d7bf4 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -1194,7 +1194,7 @@ "tlsPin": "Ghim chứng chỉ (SHA-256)", "tlsSkip": "Bỏ qua xác minh", "tlsMtls": "TLS song phương (chứng chỉ máy khách)", - "mtlsFormHint": "Nút này xác thực bảng điều khiển bằng chứng chỉ máy khách. Sao chép CA của bảng điều khiển này từ mục mTLS nút sang nút, đặt CA tin cậy của nó, rồi khởi động lại.", + "mtlsFormHint": "Nút này xác thực bảng điều khiển bằng chứng chỉ máy khách. Sao chép CA của bảng điều khiển này từ mục mTLS nút sang nút, đặt CA tin cậy của nó, rồi khởi động lại. Cập nhật bảng điều khiển của nút này từ đây vẫn cần token API có phạm vi node-admin.", "mtls": { "title": "mTLS nút", "intro": "TLS song phương bổ sung yếu tố chứng chỉ máy khách bên cạnh token API cho các lệnh gọi giữa các nút. Đây là tùy chọn: để trống để chỉ dùng xác thực bằng token.", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 3fd3cae64..56eedc32a 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -1194,7 +1194,7 @@ "tlsPin": "固定证书(SHA-256)", "tlsSkip": "跳过校验", "tlsMtls": "双向 TLS(客户端证书)", - "mtlsFormHint": "此节点使用客户端证书对面板进行认证。请从“节点 mTLS”区域复制本面板的 CA 到该节点,设置其受信任的 CA,然后重启该节点。", + "mtlsFormHint": "此节点使用客户端证书对面板进行认证。请从“节点 mTLS”区域复制本面板的 CA 到该节点,设置其受信任的 CA,然后重启该节点。 从这里更新此节点的面板仍需要具有 node-admin 权限范围的 API 令牌。", "mtls": { "title": "节点 mTLS", "intro": "双向 TLS 在节点间调用的 API 令牌之上增加客户端证书认证。此为可选项:留空则仅使用令牌认证。", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index deda19386..d3aff24d5 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -1194,7 +1194,7 @@ "tlsPin": "釘選憑證(SHA-256)", "tlsSkip": "略過驗證", "tlsMtls": "雙向 TLS(用戶端憑證)", - "mtlsFormHint": "此節點使用用戶端憑證對面板進行驗證。請從「節點 mTLS」區域複製本面板的 CA 到該節點,設定其受信任的 CA,然後重新啟動該節點。", + "mtlsFormHint": "此節點使用用戶端憑證對面板進行驗證。請從「節點 mTLS」區域複製本面板的 CA 到該節點,設定其受信任的 CA,然後重新啟動該節點。 從這裡更新此節點的面板仍需要具有 node-admin 權限範圍的 API 權杖。", "mtls": { "title": "節點 mTLS", "intro": "雙向 TLS 在節點間呼叫的 API 權杖之上增加用戶端憑證驗證。此為選用項目:留空則僅使用權杖驗證。", From 166d5633cc3f95a45bb99cf59ebff8706b6ce153 Mon Sep 17 00:00:00 2001 From: Nikan Zeyaei <72458440+NikanZeyaei@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:33:01 +0330 Subject: [PATCH 024/130] feat(frontend): confirm before stopping Xray and offer Start when it is stopped (#7104) Stop sat next to Restart on the dashboard and fired on the first click. A mis-click cut every proxy connection, and when the panel itself is reached through that proxy the only way back was SSH (#7103). Stop now opens a confirmation with Cancel focused. When Xray is stopped the first button reads Start instead of Restart and Stop is disabled; in the crashed state Stop stays enabled, because setting the manual-stop flag is what halts the crash-recovery restart loop. Closes #7103 --- .../src/pages/index/OverviewActionBar.tsx | 56 ++++++++---- .../src/test/overview-stop-confirm.test.tsx | 89 +++++++++++++++++++ internal/web/translation/ar-EG.json | 5 ++ internal/web/translation/en-US.json | 5 ++ internal/web/translation/es-ES.json | 5 ++ internal/web/translation/fa-IR.json | 5 ++ internal/web/translation/id-ID.json | 5 ++ internal/web/translation/ja-JP.json | 5 ++ internal/web/translation/pt-BR.json | 5 ++ internal/web/translation/ru-RU.json | 5 ++ internal/web/translation/sk-SK.json | 5 ++ internal/web/translation/tr-TR.json | 5 ++ internal/web/translation/uk-UA.json | 5 ++ internal/web/translation/vi-VN.json | 5 ++ internal/web/translation/zh-CN.json | 5 ++ internal/web/translation/zh-TW.json | 5 ++ 16 files changed, 198 insertions(+), 17 deletions(-) create mode 100644 frontend/src/test/overview-stop-confirm.test.tsx diff --git a/frontend/src/pages/index/OverviewActionBar.tsx b/frontend/src/pages/index/OverviewActionBar.tsx index 900ce1ead..9a5dbab7f 100644 --- a/frontend/src/pages/index/OverviewActionBar.tsx +++ b/frontend/src/pages/index/OverviewActionBar.tsx @@ -1,7 +1,7 @@ import { Fragment } from 'react'; import type { ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; -import { Button, Tag, Tooltip } from 'antd'; +import { Button, Modal, Tag, Tooltip } from 'antd'; import { ApiOutlined, ArrowUpOutlined, @@ -11,6 +11,7 @@ import { CloudServerOutlined, ControlOutlined, FileTextOutlined, + PlayCircleOutlined, PoweroffOutlined, ReloadOutlined, } from '@ant-design/icons'; @@ -26,7 +27,7 @@ interface OverviewActionBarProps { panelVersion: string; latestVersion: string; updateAvailable: boolean; - onStopXray: () => void; + onStopXray: () => void | Promise; onRestartXray: () => void; onOpenLogs: () => void; onOpenXrayLogs: () => void; @@ -45,6 +46,9 @@ interface BarAction { text: string; onClick: () => void; primary?: boolean; + danger?: boolean; + disabled?: boolean; + hint?: string; } const XRAY_STATE_KEYS: Record = { @@ -73,16 +77,18 @@ export default function OverviewActionBar({ onOpenVersionSwitch, }: OverviewActionBarProps) { const { t } = useTranslation(); + const [modal, modalContextHolder] = Modal.useModal(); const stateText = t(XRAY_STATE_KEYS[status.xray.state] ?? 'pages.index.xrayStatusUnknown'); const hasVersion = !!status.xray.version && status.xray.version !== 'Unknown'; const size = isMobile ? ('small' as const) : ('middle' as const); + const isStopped = status.xray.state === 'stop'; const actionGroups: BarAction[][] = [ [ { key: 'restart', - icon: , - text: t('pages.index.restartXray'), + icon: isStopped ? : , + text: t(isStopped ? 'pages.index.startXray' : 'pages.index.restartXray'), onClick: onRestartXray, primary: true, }, @@ -90,7 +96,19 @@ export default function OverviewActionBar({ key: 'stop', icon: , text: t('pages.index.stopXray'), - onClick: onStopXray, + danger: true, + disabled: isStopped, + hint: isStopped ? t('pages.index.stopXrayDisabledHint') : undefined, + onClick: () => + modal.confirm({ + title: t('pages.index.stopXrayConfirmTitle'), + content: t('pages.index.stopXrayConfirmContent'), + okText: t('pages.index.stopXrayConfirmOk'), + okType: 'danger', + cancelText: t('cancel'), + focusable: { autoFocusButton: 'cancel' }, + onOk: onStopXray, + }), }, ], [ @@ -165,6 +183,7 @@ export default function OverviewActionBar({ return (
+ {modalContextHolder} {status.xray.errorMsg ? ( {status.xray.errorMsg}}> {statePill} @@ -204,18 +223,21 @@ export default function OverviewActionBar({ {groupIndex > 0 && } {group.map((action) => ( - + + + ))} ))} diff --git a/frontend/src/test/overview-stop-confirm.test.tsx b/frontend/src/test/overview-stop-confirm.test.tsx new file mode 100644 index 000000000..105a8f6c3 --- /dev/null +++ b/frontend/src/test/overview-stop-confirm.test.tsx @@ -0,0 +1,89 @@ +import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +import { Status } from '@/models/status'; +import OverviewActionBar from '@/pages/index/OverviewActionBar'; + +import { renderWithProviders } from './test-utils'; + +const noop = () => {}; + +function renderBar( + state: string, + { + onStopXray = noop, + onRestartXray = noop, + }: { onStopXray?: () => void; onRestartXray?: () => void } = {}, +) { + const status = new Status(); + status.xray.state = state; + renderWithProviders( + , + ); +} + +// Stop used to fire on the first click, so a mis-click killed every proxy connection (#7103). +describe('OverviewActionBar stop confirmation', () => { + it('does not stop Xray until the dialog is confirmed', async () => { + const onStopXray = vi.fn(); + renderBar('running', { onStopXray }); + + fireEvent.click(screen.getByRole('button', { name: 'Stop' })); + expect(await screen.findAllByText('Stop Xray?')).not.toHaveLength(0); + expect(onStopXray).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(onStopXray).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: 'Stop' })); + await waitFor(() => + expect(screen.getAllByRole('button', { name: 'Stop Xray' })).not.toHaveLength(0), + ); + fireEvent.click(screen.getAllByRole('button', { name: 'Stop Xray' }).at(-1)!); + await waitFor(() => expect(onStopXray).toHaveBeenCalledOnce()); + }); +}); + +// Stop on a stopped core only errors and sets the manual-stop flag. In the crash +// state Stop is the one dashboard control that halts the restart loop. +describe('OverviewActionBar start / disabled stop', () => { + it('offers Start and disables Stop when the core is stopped', () => { + const onRestartXray = vi.fn(); + renderBar('stop', { onRestartXray }); + + expect(screen.queryByRole('button', { name: 'Restart' })).toBeNull(); + expect((screen.getByRole('button', { name: 'Stop' }) as HTMLButtonElement).disabled).toBe(true); + fireEvent.click(screen.getByRole('button', { name: 'Start' })); + expect(onRestartXray).toHaveBeenCalledOnce(); + }); + + it('keeps Restart and leaves Stop usable when the core errored', async () => { + const onStopXray = vi.fn(); + renderBar('error', { onStopXray }); + + expect(screen.getByRole('button', { name: 'Restart' })).toBeTruthy(); + const stop = screen.getByRole('button', { name: 'Stop' }) as HTMLButtonElement; + expect(stop.disabled).toBe(false); + fireEvent.click(stop); + fireEvent.click(await screen.findByRole('button', { name: 'Stop Xray' })); + await waitFor(() => expect(onStopXray).toHaveBeenCalledOnce()); + }); +}); diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 08b8cbe64..a3eb4e3e3 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "إيقاف", "restartXray": "إعادة تشغيل", + "startXray": "تشغيل", + "stopXrayDisabledHint": "Xray غير قيد التشغيل", + "stopXrayConfirmTitle": "إيقاف Xray؟", + "stopXrayConfirmContent": "سيؤدي إيقاف Xray إلى قطع جميع اتصالات البروكسي فورًا. هل تريد المتابعة؟", + "stopXrayConfirmOk": "إيقاف Xray", "xraySwitch": "النسخة", "xrayUpdates": "تحديثات Xray", "xraySwitchClickDesk": "اختار بحذر، النسخ القديمة ممكن ما تتوافقش مع الإعدادات الحالية.", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 57a915a52..4b7d4cc1d 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Stop", "restartXray": "Restart", + "startXray": "Start", + "stopXrayDisabledHint": "Xray is not running", + "stopXrayConfirmTitle": "Stop Xray?", + "stopXrayConfirmContent": "Stopping Xray will immediately interrupt all proxy connections. Are you sure you want to continue?", + "stopXrayConfirmOk": "Stop Xray", "xraySwitch": "Version", "xrayUpdates": "Xray Updates", "xraySwitchClickDesk": "Choose carefully, as older versions may not be compatible with current configurations.", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index c780eda85..8cc810704 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Detener", "restartXray": "Reiniciar", + "startXray": "Iniciar", + "stopXrayDisabledHint": "Xray no se está ejecutando", + "stopXrayConfirmTitle": "¿Detener Xray?", + "stopXrayConfirmContent": "Detener Xray interrumpirá de inmediato todas las conexiones proxy. ¿Seguro que quieres continuar?", + "stopXrayConfirmOk": "Detener Xray", "xraySwitch": "Versión", "xrayUpdates": "Actualizaciones de Xray", "xraySwitchClickDesk": "Elige sabiamente, ya que las versiones anteriores pueden no ser compatibles con las configuraciones actuales.", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 5922171e0..71e3e8c89 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "توقف", "restartXray": "راه‌اندازی مجدد", + "startXray": "شروع", + "stopXrayDisabledHint": "Xray در حال اجرا نیست", + "stopXrayConfirmTitle": "Xray متوقف شود؟", + "stopXrayConfirmContent": "توقف Xray بلافاصله همه اتصالات پراکسی را قطع می‌کند. آیا مطمئن هستید؟", + "stopXrayConfirmOk": "توقف Xray", "xraySwitch": "‌نسخه", "xrayUpdates": "به‌روزرسانی‌های Xray", "xraySwitchClickDesk": "لطفا بادقت انتخاب کنید. درصورت انتخاب نسخه قدیمی‌تر، امکان ناهماهنگی با پیکربندی فعلی وجود دارد", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 6102b7450..e21038caa 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Hentikan", "restartXray": "Mulai ulang", + "startXray": "Mulai", + "stopXrayDisabledHint": "Xray tidak berjalan", + "stopXrayConfirmTitle": "Hentikan Xray?", + "stopXrayConfirmContent": "Menghentikan Xray akan langsung memutus semua koneksi proxy. Yakin ingin melanjutkan?", + "stopXrayConfirmOk": "Hentikan Xray", "xraySwitch": "Versi", "xrayUpdates": "Pembaruan Xray", "xraySwitchClickDesk": "Pilih dengan hati-hati, karena versi yang lebih lama mungkin tidak kompatibel dengan konfigurasi saat ini.", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 61ca87665..a3209c94e 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "停止", "restartXray": "再起動", + "startXray": "開始", + "stopXrayDisabledHint": "Xray は実行されていません", + "stopXrayConfirmTitle": "Xray を停止しますか?", + "stopXrayConfirmContent": "Xray を停止すると、すべてのプロキシ接続が直ちに切断されます。続行しますか?", + "stopXrayConfirmOk": "Xray を停止", "xraySwitch": "バージョン", "xrayUpdates": "Xrayの更新", "xraySwitchClickDesk": "慎重に選択してください。古いバージョンは現在の設定と互換性がない可能性があります。", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 5172553e4..05e4aee69 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Parar", "restartXray": "Reiniciar", + "startXray": "Iniciar", + "stopXrayDisabledHint": "O Xray não está em execução", + "stopXrayConfirmTitle": "Parar o Xray?", + "stopXrayConfirmContent": "Parar o Xray interromperá imediatamente todas as conexões de proxy. Tem certeza de que deseja continuar?", + "stopXrayConfirmOk": "Parar o Xray", "xraySwitch": "Versão", "xrayUpdates": "Atualizações do Xray", "xraySwitchClickDesk": "Escolha com cuidado, pois versões mais antigas podem não ser compatíveis com as configurações atuais.", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 350e8399a..2b228875b 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Стоп", "restartXray": "Перезапуск", + "startXray": "Запуск", + "stopXrayDisabledHint": "Xray не запущен", + "stopXrayConfirmTitle": "Остановить Xray?", + "stopXrayConfirmContent": "Остановка Xray немедленно разорвёт все прокси-соединения. Продолжить?", + "stopXrayConfirmOk": "Остановить Xray", "xraySwitch": "Выбор версии", "xrayUpdates": "Обновления Xray", "xraySwitchClickDesk": "Важно: старые версии могут не поддерживать текущие настройки", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 07eaa676d..c936760b8 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Zastaviť", "restartXray": "Reštartovať", + "startXray": "Spustiť", + "stopXrayDisabledHint": "Xray nebeží", + "stopXrayConfirmTitle": "Zastaviť Xray?", + "stopXrayConfirmContent": "Zastavenie Xray okamžite preruší všetky proxy spojenia. Naozaj chcete pokračovať?", + "stopXrayConfirmOk": "Zastaviť Xray", "xraySwitch": "Verzia", "xrayUpdates": "Aktualizácie Xray", "xraySwitchClickDesk": "Verziu vyberajte opatrne. Staršie verzie nemusia podporovať aktuálnu konfiguráciu.", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index df2d995b9..92c82be09 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Durdur", "restartXray": "Yeniden Başlat", + "startXray": "Başlat", + "stopXrayDisabledHint": "Xray çalışmıyor", + "stopXrayConfirmTitle": "Xray durdurulsun mu?", + "stopXrayConfirmContent": "Xray'i durdurmak tüm proxy bağlantılarını anında keser. Devam etmek istediğinizden emin misiniz?", + "stopXrayConfirmOk": "Xray'i durdur", "xraySwitch": "Sürüm", "xrayUpdates": "Xray Güncellemeleri", "xraySwitchClickDesk": "Dikkatli seçin, eski sürümler mevcut yapılandırmalarla uyumlu olmayabilir.", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 23dbefe4c..407785a7f 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Стоп", "restartXray": "Перезапуск", + "startXray": "Запуск", + "stopXrayDisabledHint": "Xray не запущено", + "stopXrayConfirmTitle": "Зупинити Xray?", + "stopXrayConfirmContent": "Зупинка Xray негайно розірве всі проксі-з'єднання. Продовжити?", + "stopXrayConfirmOk": "Зупинити Xray", "xraySwitch": "Версія", "xrayUpdates": "Оновлення Xray", "xraySwitchClickDesk": "Вибирайте уважно, оскільки старіші версії можуть бути несумісними з поточними конфігураціями.", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 8693d7bf4..6dfb88600 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "Dừng", "restartXray": "Khởi động lại", + "startXray": "Khởi động", + "stopXrayDisabledHint": "Xray không chạy", + "stopXrayConfirmTitle": "Dừng Xray?", + "stopXrayConfirmContent": "Dừng Xray sẽ ngắt ngay lập tức mọi kết nối proxy. Bạn có chắc muốn tiếp tục?", + "stopXrayConfirmOk": "Dừng Xray", "xraySwitch": "Phiên bản", "xrayUpdates": "Cập nhật Xray", "xraySwitchClickDesk": "Hãy lựa chọn thận trọng, vì các phiên bản cũ có thể không tương thích với các cấu hình hiện tại.", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 56eedc32a..268d6eb62 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "停止", "restartXray": "重启", + "startXray": "启动", + "stopXrayDisabledHint": "Xray 未运行", + "stopXrayConfirmTitle": "停止 Xray?", + "stopXrayConfirmContent": "停止 Xray 将立即中断所有代理连接。确定要继续吗?", + "stopXrayConfirmOk": "停止 Xray", "xraySwitch": "版本", "xrayUpdates": "Xray 更新", "xraySwitchClickDesk": "请谨慎选择,因为较旧版本可能与当前配置不兼容", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index d3aff24d5..03945751d 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -151,6 +151,11 @@ "xrayStatus": "Xray", "stopXray": "停止", "restartXray": "重新啟動", + "startXray": "啟動", + "stopXrayDisabledHint": "Xray 未執行", + "stopXrayConfirmTitle": "停止 Xray?", + "stopXrayConfirmContent": "停止 Xray 將立即中斷所有代理連線。確定要繼續嗎?", + "stopXrayConfirmOk": "停止 Xray", "xraySwitch": "版本", "xrayUpdates": "Xray 更新", "xraySwitchClickDesk": "請謹慎選擇,因為較舊版本可能與當前配置不相容", From 51f7ba47f78d6c48d637dceb9b1bb7febe474cbe Mon Sep 17 00:00:00 2001 From: "Cheng Ho Ming, Eric" Date: Sat, 14 Nov 2026 00:25:38 +0800 Subject: [PATCH 025/130] feat(xray): drag to reorder DNS servers (#6959) Xray queries DNS servers in list order, but the DNS table offered only Edit and Delete, so changing a server's priority meant deleting and re-adding servers. Each row now has a grab handle that reorders by drag and drop, using the same pointer hook and drop markers as the Routing rules table, and the row menu gains Move up and Move down. Every path only reorders dns.servers; a server's own fields are left as they are. --- frontend/src/pages/xray/dns/DnsTab.tsx | 64 ++++++++++++++--- frontend/src/pages/xray/dns/useDnsColumns.tsx | 43 +++++++++++- frontend/src/test/dns-tab.test.tsx | 68 ++++++++++++++++++- 3 files changed, 161 insertions(+), 14 deletions(-) diff --git a/frontend/src/pages/xray/dns/DnsTab.tsx b/frontend/src/pages/xray/dns/DnsTab.tsx index b52193936..003fbfdf3 100644 --- a/frontend/src/pages/xray/dns/DnsTab.tsx +++ b/frontend/src/pages/xray/dns/DnsTab.tsx @@ -27,6 +27,7 @@ import { selectTagRender } from '@/components/form'; import { onNumber } from '@/utils/onNumber'; import { SettingListItem } from '@/components/ui'; import { useMediaQuery } from '@/hooks/useMediaQuery'; +import { usePointerRowReorder } from '@/hooks/usePointerRowReorder'; import { catTabLabel } from '@/pages/settings/catTabLabel'; import DnsServerModal from './DnsServerModal'; import type { DnsServerValue } from './DnsServerModal'; @@ -52,6 +53,7 @@ export default function DnsTab({ templateSettings, setTemplateSettings }: DnsTab const [editingServer, setEditingServer] = useState(null); const [editingIndex, setEditingIndex] = useState(null); const [presetsModalOpen, setPresetsModalOpen] = useState(false); + const serversContainerRef = useRef(null); const dns = (templateSettings?.dns as DnsConfig | undefined) ?? null; const dnsEnabled = !!dns; @@ -166,8 +168,33 @@ export default function DnsTab({ templateSettings, setTemplateSettings }: DnsTab }, [mutate], ); + const moveServer = useCallback( + (from: number, to: number) => { + mutate((tt) => { + const servers = (tt.dns as DnsConfig | undefined)?.servers; + if (!servers) return; + const [moved] = servers.splice(from, 1); + servers.splice(to, 0, moved); + }); + }, + [mutate], + ); - const dnsColumns = useDnsServerColumns({ openEditServer, deleteServer }); + const { drag, onPointerDown: onHandlePointerDown } = usePointerRowReorder({ + containerRef: serversContainerRef, + getRowKey: (row) => Number(row.dataset.rowKey), + onDrop: ({ from, to }) => moveServer(from, to), + }); + const draggedIndex = drag?.from ?? null; + const dropTargetIndex = drag?.to ?? null; + + const dnsColumns = useDnsServerColumns({ + rowsLength: dnsServers.length, + onHandlePointerDown, + openEditServer, + moveServer, + deleteServer, + }); function openAddServer() { setEditingServer(null); @@ -475,14 +502,21 @@ export default function DnsTab({ templateSettings, setTemplateSettings }: DnsTab {t('pages.xray.dns.clearAll')} - r.key} - pagination={false} - size="small" - bordered - /> +
+
r.key} + rowClassName={(_r, i) => { + if (i === draggedIndex) return 'row-dragging'; + if (i !== dropTargetIndex || draggedIndex == null) return ''; + return i > draggedIndex ? 'drop-after' : 'drop-before'; + }} + pagination={false} + size="small" + bordered + /> + ), }); @@ -517,7 +551,17 @@ export default function DnsTab({ templateSettings, setTemplateSettings }: DnsTab return out; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [t, isMobile, dnsEnabled, dns, hostsList, dnsServers, fakeDnsList]); + }, [ + t, + isMobile, + dnsEnabled, + dns, + hostsList, + dnsServers, + fakeDnsList, + draggedIndex, + dropTargetIndex, + ]); return ( <> diff --git a/frontend/src/pages/xray/dns/useDnsColumns.tsx b/frontend/src/pages/xray/dns/useDnsColumns.tsx index 70f12f25b..1c7ec608a 100644 --- a/frontend/src/pages/xray/dns/useDnsColumns.tsx +++ b/frontend/src/pages/xray/dns/useDnsColumns.tsx @@ -1,7 +1,14 @@ import { useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import { Button, Dropdown, Input, InputNumber, Space } from 'antd'; -import { MoreOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'; +import { + MoreOutlined, + EditOutlined, + DeleteOutlined, + ArrowUpOutlined, + ArrowDownOutlined, + HolderOutlined, +} from '@ant-design/icons'; import type { ColumnsType } from 'antd/es/table'; import { onNumber } from '@/utils/onNumber'; @@ -13,10 +20,16 @@ export type DnsServerRow = { key: number; server: DnsServerValue }; export type FakednsTableRow = { key: number; ipPool: string; poolSize: number }; export function useDnsServerColumns({ + rowsLength, + onHandlePointerDown, openEditServer, + moveServer, deleteServer, }: { + rowsLength: number; + onHandlePointerDown: (idx: number, ev: React.PointerEvent) => void; openEditServer: (idx: number) => void; + moveServer: (from: number, to: number) => void; deleteServer: (idx: number) => void; }): ColumnsType { const { t } = useTranslation(); @@ -29,6 +42,12 @@ export function useDnsServerColumns({ width: 60, render: (_v, _record, index) => ( +
r} + pagination={false} + dataSource={spares} + locale={{ emptyText: t('pages.inbounds.realityWatch.noSpares') }} + columns={[ + { title: t('pages.inbounds.form.target'), render: (_, r: string) => r }, + { + title: t('pages.inbounds.realityWatch.realTest'), + width: 190, + render: (_, r: string) => { + const res = tests[r]; + return res ? ( + + {res.feasible + ? `${t('pages.inbounds.realityWatch.testOk')}${res.latencyMs > 0 ? ` · ${res.latencyMs} ms` : ''}` + : t('pages.inbounds.realityWatch.testFailed')} + + ) : ( + + ); + }, + }, + { + width: 96, + render: (_, r: string) => ( + + {!isDraft && ( + + + {!isDraft && ( + + )} + + + + {!!status?.events?.length && ( + + + {[...status.events].reverse().map((ev) => ( + + {dayjs.unix(ev.at).format('MM-DD HH:mm')} ·{' '} + {ev.to + ? t('pages.inbounds.realityWatch.eventSwitched', { from: ev.from, to: ev.to }) + : t('pages.inbounds.realityWatch.eventNoSpare', { from: ev.from })} + + ))} + + + )} + setScannerOpen(false)} + scanRealityCandidates={scanRealityCandidates} + onPick={(r) => { + setSpares((prev) => addSpare(prev, r.target, currentTarget)); + setDirty(true); + }} + /> + + ); +} diff --git a/frontend/src/pages/inbounds/form/security/reality.tsx b/frontend/src/pages/inbounds/form/security/reality.tsx index 2bd4848ac..e388dcf6e 100644 --- a/frontend/src/pages/inbounds/form/security/reality.tsx +++ b/frontend/src/pages/inbounds/form/security/reality.tsx @@ -26,7 +26,9 @@ import { validateRealityMaxClientVer, validateRealityTarget, } from '@/lib/xray/stream-wire-normalize'; -import type { RealityScanResult } from '@/generated/types'; +import type { RealityScanResult, RealityWatchEntry } from '@/generated/types'; +import type { MessageInstance } from 'antd/es/message/interface'; +import RealityWatchSection from './RealityWatchSection'; import RealityTargetScannerModal, { MLDSA65_MIN_CERT_CHAIN_BYTES, } from './RealityTargetScannerModal'; @@ -44,6 +46,11 @@ interface RealityFormProps { clearRealityKeypair: () => void; genMldsa65: () => void; clearMldsa65: () => void; + inboundId?: number | null; + onNode?: boolean; + messageApi?: MessageInstance; + onWatchDraftChange?: (entry: RealityWatchEntry) => void; + onWatchSwitched?: (target: string, serverNames: string[]) => void; } export default function RealityForm({ @@ -59,6 +66,11 @@ export default function RealityForm({ clearRealityKeypair, genMldsa65, clearMldsa65, + inboundId = null, + onNode = false, + messageApi, + onWatchDraftChange, + onWatchSwitched, }: RealityFormProps) { const { t } = useTranslation(); const uid = useId(); @@ -387,6 +399,14 @@ export default function RealityForm({ }, ]} /> + setScannerOpen(false)} diff --git a/frontend/src/pages/inbounds/form/security/realityWatch.ts b/frontend/src/pages/inbounds/form/security/realityWatch.ts new file mode 100644 index 000000000..de7bb5e30 --- /dev/null +++ b/frontend/src/pages/inbounds/form/security/realityWatch.ts @@ -0,0 +1,15 @@ +// Same limit and shape as the server (internal/web/service/reality_watch.go). +export const REALITY_WATCH_MAX_SPARES = 10; + +export function normalizeSpare(target: string): string { + const t = target.trim().toLowerCase(); + return /:\d+$/.test(t) ? t : `${t}:443`; +} + +export function addSpare(spares: string[], target: string, current: string): string[] { + const t = normalizeSpare(target); + if (!t || t === ':443' || spares.includes(t) || (current && t === normalizeSpare(current))) + return spares; + if (spares.length >= REALITY_WATCH_MAX_SPARES) return spares; + return [...spares, t]; +} diff --git a/frontend/src/test/__snapshots__/inbound-form-blocks.test.tsx.snap b/frontend/src/test/__snapshots__/inbound-form-blocks.test.tsx.snap index 2afe583ca..c132370be 100644 --- a/frontend/src/test/__snapshots__/inbound-form-blocks.test.tsx.snap +++ b/frontend/src/test/__snapshots__/inbound-form-blocks.test.tsx.snap @@ -17,6 +17,8 @@ exports[`inbound security forms > RealityForm field structure is stable 1`] = ` "mldsa65 Seed", "mldsa65 Verify", "Master Key Log", + "Replace automatically", + "Spare targets", ] `; diff --git a/frontend/src/test/inbound-form-modal.test.tsx b/frontend/src/test/inbound-form-modal.test.tsx index 938e02200..ff1314bc0 100644 --- a/frontend/src/test/inbound-form-modal.test.tsx +++ b/frontend/src/test/inbound-form-modal.test.tsx @@ -22,7 +22,7 @@ vi.mock('antd', async (importOriginal) => { ...actual, message: { ...actual.message, - useMessage: () => [{ error: messageError }, null], + useMessage: () => [{ error: messageError, success: vi.fn() }, null], }, }; }); @@ -539,6 +539,60 @@ describe('InboundFormModal', () => { // Clients and enable change through their own endpoints; the server keeps the // stored ones, so the edit form must neither send nor validate its stale copy. + // The editor saves the whole form, so a form left on the old target undid the switch. + it('saves the target a REALITY watch switch moved to, not the one it opened with', async () => { + const post = vi.mocked(HttpUtil.post); + const get = vi.mocked(HttpUtil.get); + const realPost = post.getMockImplementation(); + const realGet = get.getMockImplementation(); + onTestFinished(() => { + post.mockImplementation(realPost!); + get.mockImplementation(realGet!); + }); + const status = (target: string, serverNames: string[], spares: string[]) => ({ + success: true, + msg: '', + obj: { + inboundId: 42, + target, + serverNames, + spares, + auto: false, + checkedAt: 0, + ok: false, + fails: 0, + reason: '', + latencyMs: 0, + events: [], + }, + }); + get.mockImplementation(async (url: string) => + url.startsWith('/panel/api/realityWatch/status/') + ? status('example.com:443', ['example.com'], ['spare.example:443']) + : realGet!(url), + ); + post.mockImplementation(async (url: string) => + url.startsWith('/panel/api/realityWatch/switch/') + ? status('spare.example:443', ['spare.example'], ['example.com:443']) + : { success: true, msg: '', obj: {} }, + ); + post.mockClear(); + await renderCloneLikeEdit(cloneLikeVlessInbound('example.com:443')); + + fireEvent.click(screen.getByRole('tab', { name: 'Security' })); + fireEvent.click(await screen.findByRole('button', { name: 'Switch to this now' })); + expect(await screen.findByDisplayValue('spare.example:443')).toBeTruthy(); + fireEvent.click(primaryButton()); + + await waitFor(() => + expect(post.mock.calls.some(([url]) => String(url).includes('/inbounds/update/'))).toBe(true), + ); + const update = post.mock.calls.find(([url]) => String(url).includes('/inbounds/update/'))!; + const stream = JSON.parse((update[1] as { streamSettings: string }).streamSettings); + expect(stream.realitySettings.target).toBe('spare.example:443'); + expect(stream.realitySettings.serverNames).toEqual(['spare.example']); + }, 20_000); + it('edit save neither sends nor validates the clients it loaded', async () => { const post = vi.mocked(HttpUtil.post); post.mockClear(); diff --git a/frontend/src/test/reality-watch-draft.test.tsx b/frontend/src/test/reality-watch-draft.test.tsx new file mode 100644 index 000000000..653e8c4ae --- /dev/null +++ b/frontend/src/test/reality-watch-draft.test.tsx @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest'; +import { Form } from 'antd'; +import { fireEvent } from '@testing-library/react'; +import { FormProvider, useForm } from 'react-hook-form'; + +import RealityWatchSection from '@/pages/inbounds/form/security/RealityWatchSection'; +import type { RealityWatchEntry } from '@/generated/types'; +import { renderWithProviders } from './test-utils'; + +function Harness({ onDraftChange }: { onDraftChange: (d: RealityWatchEntry) => void }) { + const methods = useForm({ + defaultValues: { streamSettings: { realitySettings: { target: 'a.example.com:443' } } }, + }); + return ( + +
+ []} + onDraftChange={onDraftChange} + /> + +
+ ); +} + +// A new inbound used to show only "save first", so spares meant a create-then-edit round trip. +describe('REALITY watch on a new inbound', () => { + it('lets the admin set the auto switch and hands it to the form to save with the inbound', () => { + const drafts: RealityWatchEntry[] = []; + const { getByRole, getByText } = renderWithProviders( + drafts.push(d)} />, + ); + expect(getByText('Find spares')).toBeTruthy(); + fireEvent.click(getByRole('switch')); + expect(drafts.at(-1)).toEqual({ auto: true, spares: [] }); + }); +}); diff --git a/frontend/src/test/reality-watch-spares.test.ts b/frontend/src/test/reality-watch-spares.test.ts new file mode 100644 index 000000000..927eb6d0e --- /dev/null +++ b/frontend/src/test/reality-watch-spares.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; + +import { addSpare } from '@/pages/inbounds/form/security/realityWatch'; + +// The server keys spares as lower-case host:port and drops the current target; adding the +// same site twice from the scanner must not create a second entry that the server collapses. +describe('addSpare', () => { + it('normalizes to host:port and skips repeats and the current target', () => { + let spares: string[] = []; + spares = addSpare(spares, 'WWW.Example.com', 'cur.example.com:443'); + spares = addSpare(spares, 'www.example.com:443', 'cur.example.com:443'); + spares = addSpare(spares, 'other.example.com:8443', 'cur.example.com:443'); + spares = addSpare(spares, 'cur.example.com', 'cur.example.com:443'); + expect(spares).toEqual(['www.example.com:443', 'other.example.com:8443']); + }); + + it('keeps at most 10, like the server', () => { + let spares: string[] = []; + for (let i = 0; i < 12; i++) spares = addSpare(spares, `s${i}.example.com`, ''); + expect(spares).toHaveLength(10); + expect(spares[9]).toBe('s9.example.com:443'); + }); +}); diff --git a/internal/web/controller/api.go b/internal/web/controller/api.go index ab6e9533b..a3b0edcbc 100644 --- a/internal/web/controller/api.go +++ b/internal/web/controller/api.go @@ -248,6 +248,9 @@ func (a *APIController) initRouter(g *gin.RouterGroup, router http.Handler) { // Subscription balancers — client-side balancers for the JSON sub output NewSubBalancerController(api) + // REALITY watch — spare targets and automatic replacement per REALITY inbound + NewRealityWatchController(api.Group("/realityWatch")) + // Extra routes api.POST("/backuptotgbot", a.BackuptoTgbot) api.POST(mcp.Path, a.requireMCPEnabled, gin.WrapH(mcp.NewHandler(router))) diff --git a/internal/web/controller/reality_watch.go b/internal/web/controller/reality_watch.go new file mode 100644 index 000000000..352188967 --- /dev/null +++ b/internal/web/controller/reality_watch.go @@ -0,0 +1,93 @@ +package controller + +import ( + "strconv" + + "github.com/mhsanaei/3x-ui/v3/internal/web/service" + + "github.com/gin-gonic/gin" +) + +// RealityWatchController sets the spare targets of REALITY inbounds and switches them. +type RealityWatchController struct { + realityWatchService service.RealityWatchService +} + +func NewRealityWatchController(g *gin.RouterGroup) *RealityWatchController { + a := &RealityWatchController{} + g.GET("/list", a.list) + g.GET("/status/:id", a.status) + g.POST("/save/:id", a.save) + g.POST("/switch/:id", a.switchTarget) + g.POST("/test", a.test) + return a +} + +type realityWatchTargetRequest struct { + Target string `json:"target"` +} + +func (a *RealityWatchController) list(c *gin.Context) { + jsonObj(c, a.realityWatchService.List(), nil) +} + +func (a *RealityWatchController) status(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.failed"), err) + return + } + jsonObj(c, a.realityWatchService.Status(id), nil) +} + +func (a *RealityWatchController) save(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.failed"), err) + return + } + var entry service.RealityWatchEntry + if err := c.ShouldBindJSON(&entry); err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.failed"), err) + return + } + if err := a.realityWatchService.SaveConfig(id, entry); err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.failed"), err) + return + } + jsonObj(c, a.realityWatchService.Status(id), nil) +} + +// switchTarget answers with the status so the editor gets the saved target and SNIs in one step; +// a form left on the old ones would put them back on its next Save. +func (a *RealityWatchController) switchTarget(c *gin.Context) { + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.switchFailed"), err) + return + } + var req realityWatchTargetRequest + if err := c.ShouldBindJSON(&req); err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.switchFailed"), err) + return + } + if _, err := a.realityWatchService.SwitchTo(c.Request.Context(), id, req.Target); err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.switchFailed"), err) + return + } + jsonObj(c, a.realityWatchService.Status(id), nil) +} + +func (a *RealityWatchController) test(c *gin.Context) { + var req realityWatchTargetRequest + if err := c.ShouldBindJSON(&req); err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.failed"), err) + return + } + res, err := a.realityWatchService.TestTarget(c.Request.Context(), req.Target) + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.realityWatch.toasts.failed"), err) + return + } + jsonObj(c, res, nil) +} diff --git a/internal/web/job/reality_watch_job.go b/internal/web/job/reality_watch_job.go new file mode 100644 index 000000000..43900d8f2 --- /dev/null +++ b/internal/web/job/reality_watch_job.go @@ -0,0 +1,20 @@ +package job + +import ( + "context" + + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +// RealityWatchJob checks the target of every watched REALITY inbound and replaces a dead one. +type RealityWatchJob struct { + realityWatchService service.RealityWatchService +} + +func NewRealityWatchJob() *RealityWatchJob { + return &RealityWatchJob{} +} + +func (j *RealityWatchJob) Run() { + j.realityWatchService.Tick(context.Background()) +} diff --git a/internal/web/service/host.go b/internal/web/service/host.go index 4343e9387..4eed6fa44 100644 --- a/internal/web/service/host.go +++ b/internal/web/service/host.go @@ -409,6 +409,39 @@ func (s *HostService) UpdateHostGroup(groupId string, req *entity.HostGroup) ([] return desired, nil } +// MoveInboundSni follows a REALITY inbound to a new SNI: a Host's own SNI overrides serverNames in +// links. Only this inbound's rows change, because a shared group's other inbounds keep their target. +func (s *HostService) MoveInboundSni(inboundId int, oldNames []string, newSni string) error { + move := func(sni string) string { + if slices.Contains(oldNames, sni) { + return newSni + } + return sni + } + return database.GetDB().Transaction(func(tx *gorm.DB) error { + var rows []*model.Host + if err := tx.Where("inbound_id = ? AND security IN ?", inboundId, []string{"", "same", "reality"}).Find(&rows).Error; err != nil { + return err + } + for _, h := range rows { + sni := move(h.Sni) + pool := make([]string, 0, len(h.Snis)) + for _, name := range h.Snis { + pool = append(pool, move(name)) + } + pool = cleanSnis(pool) + if sni == h.Sni && slices.Equal(pool, h.Snis) { + continue + } + h.Sni, h.Snis = sni, pool + if err := tx.Save(h).Error; err != nil { + return err + } + } + return nil + }) +} + func (s *HostService) DeleteHostGroup(groupId string) error { return database.GetDB().Transaction(func(tx *gorm.DB) error { _, err := database.DeleteHosts(tx, "group_id = ?", groupId) diff --git a/internal/web/service/reality_watch.go b/internal/web/service/reality_watch.go new file mode 100644 index 000000000..5ebf74697 --- /dev/null +++ b/internal/web/service/reality_watch.go @@ -0,0 +1,523 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "net" + "strconv" + "strings" + "sync" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/logger" +) + +// The REALITY watch checks a target from this server and, after realityWatchFailLimit failures +// in a row, moves the inbound to the first spare that passes both checks. + +const ( + realityWatchSetting = "realityWatch" + realityWatchFailLimit = 3 + realityWatchMaxSpares = 10 + realityWatchMaxEvents = 20 +) + +var ( + errRealityWatchBadSpare = errors.New("reality watch: invalid spare target") + errRealityWatchNotReality = errors.New("reality watch: not a REALITY inbound") + errRealityWatchTargetFails = errors.New("reality watch: target fails the check") + errRealityWatchNoSpare = errors.New("reality watch: no spare target works") + errRealityWatchChanged = errors.New("reality watch: the target changed during the check") + errRealityWatchOnNode = errors.New("reality watch: this server cannot test a node inbound's target") + + realityWatchProbe = func(s *ServerService, target, sni string, xver int) *RealityScanResult { + res, err := s.ScanRealityTarget(target, sni, xver, false) + if err != nil { + return &RealityScanResult{Target: target, Reason: err.Error()} + } + return res + } + realityWatchRealTest = xrayRealityRealTest +) + +// RealityWatchEntry is what the admin sets per inbound: spare targets (host:port) in order +// of preference, and whether a dead target is replaced without asking. +type RealityWatchEntry struct { + Auto bool `json:"auto" example:"true"` + Spares []string `json:"spares" example:"[\"www.example.com:443\"]"` +} + +// RealityWatchEvent is one switch (To set) or a failed attempt to find a working spare. +type RealityWatchEvent struct { + At int64 `json:"at" example:"1793000000"` + From string `json:"from" example:"old.example.com:443"` + To string `json:"to" example:"www.example.com:443"` + Reason string `json:"reason" example:"TLS handshake failed: EOF"` +} + +type RealityWatchStatus struct { + InboundId int `json:"inboundId" example:"3"` + Target string `json:"target" example:"old.example.com:443"` + ServerNames []string `json:"serverNames" example:"[\"old.example.com\"]"` + Auto bool `json:"auto" example:"true"` + Spares []string `json:"spares" example:"[\"www.example.com:443\"]"` + CheckedAt int64 `json:"checkedAt" example:"1793000000"` + Ok bool `json:"ok" example:"true"` + Fails int `json:"fails" example:"0"` + Reason string `json:"reason" example:""` + LatencyMs int `json:"latencyMs" example:"180"` + Events []RealityWatchEvent `json:"events"` +} + +type realityWatchState struct { + checkedAt time.Time + ok bool + fails int + reason string + latencyMs int + events []RealityWatchEvent +} + +// realityWatchMu guards config, state and the final save, never a network check: those take +// minutes when targets time out and the API must answer meanwhile. +var ( + realityWatchMu sync.Mutex + realityWatchStates = map[int]*realityWatchState{} + realityWatchTickMu sync.Mutex +) + +func resetRealityWatchState() { + realityWatchMu.Lock() + defer realityWatchMu.Unlock() + realityWatchStates = map[int]*realityWatchState{} +} + +type RealityWatchService struct { + inboundService InboundService + hostService HostService + settingService SettingService + serverService ServerService + xrayService XrayService +} + +type realitySettingsView struct { + Target string `json:"target"` + Dest string `json:"dest"` + ServerNames []string `json:"serverNames"` + Xver int `json:"xver"` +} + +// realityOf reads an inbound's REALITY target (older configs call it dest) and SNIs. +func realityOf(ib *model.Inbound) (realitySettingsView, bool) { + var stream struct { + Security string `json:"security"` + RealitySettings realitySettingsView `json:"realitySettings"` + } + if json.Unmarshal([]byte(ib.StreamSettings), &stream) != nil || stream.Security != "reality" { + return realitySettingsView{}, false + } + rs := stream.RealitySettings + if rs.Target == "" { + rs.Target = rs.Dest + } + return rs, rs.Target != "" +} + +// normalizeRealityTarget is host:port in lower case, :443 when no port is given. +func normalizeRealityTarget(raw string) (string, error) { + raw = strings.ToLower(strings.TrimSpace(raw)) + host, port, err := splitRealityTarget(raw) + if err != nil || strings.ContainsAny(raw, " \"'`;") { + return "", errRealityWatchBadSpare + } + return net.JoinHostPort(host, strconv.Itoa(port)), nil +} + +func (s *RealityWatchService) loadConfig() map[int]RealityWatchEntry { + out := map[int]RealityWatchEntry{} + raw, err := s.settingService.getString(realityWatchSetting) + if err != nil || raw == "" { + return out + } + var byKey map[string]RealityWatchEntry + if json.Unmarshal([]byte(raw), &byKey) != nil { + return out + } + for k, v := range byKey { + if id, err := strconv.Atoi(k); err == nil { + out[id] = v + } + } + return out +} + +func (s *RealityWatchService) storeConfig(cfg map[int]RealityWatchEntry) error { + byKey := make(map[string]RealityWatchEntry, len(cfg)) + for id, v := range cfg { + byKey[strconv.Itoa(id)] = v + } + b, err := json.Marshal(byKey) + if err != nil { + return err + } + return s.settingService.setString(realityWatchSetting, string(b)) +} + +// SaveConfig sets an inbound's spares and auto switch; the current target is never a spare. +func (s *RealityWatchService) SaveConfig(inboundId int, entry RealityWatchEntry) error { + ib, err := s.inboundService.GetInbound(inboundId) + if err != nil { + return err + } + rs, ok := realityOf(ib) + if !ok { + return errRealityWatchNotReality + } + current, _ := normalizeRealityTarget(rs.Target) + spares := []string{} + for _, raw := range entry.Spares { + target, err := normalizeRealityTarget(raw) + if err != nil { + return err + } + if target != current && !containsString(spares, target) && len(spares) < realityWatchMaxSpares { + spares = append(spares, target) + } + } + realityWatchMu.Lock() + defer realityWatchMu.Unlock() + cfg := s.loadConfig() + cfg[inboundId] = RealityWatchEntry{Auto: entry.Auto, Spares: spares} + return s.storeConfig(cfg) +} + +func containsString(list []string, v string) bool { + for _, x := range list { + if x == v { + return true + } + } + return false +} + +func (s *RealityWatchService) Status(inboundId int) RealityWatchStatus { + realityWatchMu.Lock() + defer realityWatchMu.Unlock() + return s.statusLocked(inboundId, s.loadConfig()[inboundId]) +} + +func (s *RealityWatchService) statusLocked(inboundId int, entry RealityWatchEntry) RealityWatchStatus { + st := RealityWatchStatus{ + InboundId: inboundId, Auto: entry.Auto, Spares: entry.Spares, + ServerNames: []string{}, Events: []RealityWatchEvent{}, + } + if st.Spares == nil { + st.Spares = []string{} + } + if ib, err := s.inboundService.GetInbound(inboundId); err == nil { + if rs, ok := realityOf(ib); ok { + st.Target = rs.Target + if rs.ServerNames != nil { + st.ServerNames = rs.ServerNames + } + } + } + if state := realityWatchStates[inboundId]; state != nil { + st.Ok, st.Fails, st.Reason, st.LatencyMs = state.ok, state.fails, state.reason, state.latencyMs + if !state.checkedAt.IsZero() { + st.CheckedAt = state.checkedAt.Unix() + } + st.Events = append(st.Events, state.events...) + } + return st +} + +// List is the status of every watched inbound. +func (s *RealityWatchService) List() []RealityWatchStatus { + realityWatchMu.Lock() + defer realityWatchMu.Unlock() + out := []RealityWatchStatus{} + for id, entry := range s.loadConfig() { + out = append(out, s.statusLocked(id, entry)) + } + return out +} + +// Tick checks every watched inbound's target once (the cron job calls it). A cycle still running +// when the next one fires keeps going alone, so one outage is not counted twice. +func (s *RealityWatchService) Tick(ctx context.Context) { + if !realityWatchTickMu.TryLock() { + return + } + defer realityWatchTickMu.Unlock() + realityWatchMu.Lock() + cfg := s.loadConfig() + realityWatchMu.Unlock() + for id := range cfg { + s.checkInbound(ctx, id) + } +} + +// checkInbound skips node inbounds: their REALITY server runs on the node, so this server's +// view says nothing about it. +func (s *RealityWatchService) checkInbound(ctx context.Context, id int) { + ib, err := s.inboundService.GetInbound(id) + if err != nil || !ib.Enable || ib.NodeID != nil { + return + } + rs, ok := realityOf(ib) + if !ok || localRealityTarget(rs.Target) { + return + } + res := realityWatchProbe(&s.serverService, rs.Target, firstString(rs.ServerNames), rs.Xver) + // a domain that resolves into a private network: the SSRF guard blocked it, nothing failed + if res.PrivateTarget { + return + } + alive := realityTargetAlive(ctx, rs, res) + + realityWatchMu.Lock() + entry := s.loadConfig()[id] + state := realityWatchStates[id] + if state == nil { + state = &realityWatchState{} + realityWatchStates[id] = state + } + state.checkedAt, state.ok, state.reason, state.latencyMs = time.Now(), alive, res.Reason, res.LatencyMs + if alive { + state.fails = 0 + state.reason = "" + realityWatchMu.Unlock() + return + } + state.fails++ + due := entry.Auto && state.fails >= realityWatchFailLimit + realityWatchMu.Unlock() + if !due { + return + } + + _, err = s.switchInbound(ctx, id, rs, entry.Spares, res.Reason) + switch { + case err == nil: + case errors.Is(err, errRealityWatchChanged): + logger.Infof("reality watch: inbound %d changed during the check, not switching it", id) + default: + realityWatchMu.Lock() + defer realityWatchMu.Unlock() + // one "nothing works" line per outage, not one per check + if n := len(state.events); n == 0 || state.events[n-1].To != "" { + s.recordLocked(id, RealityWatchEvent{At: time.Now().Unix(), From: rs.Target, Reason: res.Reason}) + } + logger.Warningf("reality watch: inbound %d target %s fails (%s) and no spare works", id, rs.Target, res.Reason) + } +} + +// realityTargetAlive decides whether a target failed. The scanner's bar (h2, SNI on the cert) is +// for choosing a target; one that misses it can still carry REALITY, so the real test decides. +func realityTargetAlive(ctx context.Context, rs realitySettingsView, res *RealityScanResult) bool { + if res.Feasible { + return true + } + if !res.TLS13 { + return false + } + target, err := normalizeRealityTarget(rs.Target) + if err != nil { + return false + } + sni := firstString(rs.ServerNames) + if sni == "" { + sni, _, _ = net.SplitHostPort(target) + } + if err := realityWatchRealTest(ctx, target, sni); err != nil { + logger.Infof("reality watch: %s fails a real REALITY connection: %v", target, err) + return false + } + return true +} + +// localRealityTarget is a target on this machine or the LAN: a bare port, a unix socket, or +// a private / loopback address. The admin fronts REALITY with it on purpose; never replace it. +func localRealityTarget(target string) bool { + t := strings.TrimSpace(target) + if t == "" || strings.HasPrefix(t, "/") || strings.HasPrefix(t, "@") { + return true + } + if _, err := strconv.Atoi(t); err == nil { + return true + } + host := t + if h, _, err := net.SplitHostPort(t); err == nil { + host = h + } + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(strings.Trim(host, "[]")) + return ip != nil && (ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified()) +} + +func firstString(list []string) string { + if len(list) == 0 { + return "" + } + return list[0] +} + +// SwitchTo moves an inbound to target now (the admin's button), after the same checks. A node +// inbound is refused: both checks run here and say nothing about the node's network. +func (s *RealityWatchService) SwitchTo(ctx context.Context, inboundId int, target string) (*RealityWatchEvent, error) { + target, err := normalizeRealityTarget(target) + if err != nil { + return nil, err + } + ib, err := s.inboundService.GetInbound(inboundId) + if err != nil { + return nil, err + } + if ib.NodeID != nil { + return nil, errRealityWatchOnNode + } + rs, ok := realityOf(ib) + if !ok { + return nil, errRealityWatchNotReality + } + ev, err := s.switchInbound(ctx, inboundId, rs, []string{target}, "") + if errors.Is(err, errRealityWatchNoSpare) { + return nil, errRealityWatchTargetFails + } + return ev, err +} + +// TestTarget runs the server check and the real REALITY connection on one target. +func (s *RealityWatchService) TestTarget(ctx context.Context, target string) (*RealityScanResult, error) { + target, err := normalizeRealityTarget(target) + if err != nil { + return nil, err + } + host, _, _ := net.SplitHostPort(target) + res := realityWatchProbe(&s.serverService, target, host, 0) + if res.Feasible { + if err := realityWatchRealTest(ctx, target, host); err != nil { + res.Feasible, res.Reason = false, "REALITY test failed: "+err.Error() + } + } + return res, nil +} + +// switchInbound tries candidates in order; the first that passes the server check and a real +// REALITY connection becomes the target, with its host as the only SNI. +func (s *RealityWatchService) switchInbound(ctx context.Context, inboundId int, rs realitySettingsView, + candidates []string, reason string, +) (*RealityWatchEvent, error) { + for _, cand := range candidates { + if cand == rs.Target { + continue + } + host, _, err := net.SplitHostPort(cand) + if err != nil { + continue + } + if res := realityWatchProbe(&s.serverService, cand, host, rs.Xver); !res.Feasible { + continue + } + if err := realityWatchRealTest(ctx, cand, host); err != nil { + logger.Infof("reality watch: %s passes the TLS check but not a real REALITY connection: %v", cand, err) + continue + } + return s.commitSwitch(inboundId, rs.Target, cand, host, reason) + } + return nil, errRealityWatchNoSpare +} + +// commitSwitch saves a fresh copy of the inbound, since the checks took long enough for an admin +// to save an edit. A target changed meanwhile means the admin already chose; nothing is switched. +func (s *RealityWatchService) commitSwitch(inboundId int, from, to, sni, reason string) (*RealityWatchEvent, error) { + realityWatchMu.Lock() + defer realityWatchMu.Unlock() + ib, err := s.inboundService.GetInbound(inboundId) + if err != nil { + return nil, err + } + rs, ok := realityOf(ib) + if !ok { + return nil, errRealityWatchNotReality + } + if rs.Target != from { + return nil, errRealityWatchChanged + } + if err := s.applyTarget(ib, to, sni); err != nil { + return nil, err + } + // The inbound has moved, so a host failure must not lose the spares and history below. + if err := s.hostService.MoveInboundSni(inboundId, rs.ServerNames, sni); err != nil { + logger.Warningf("reality watch: inbound %d switched but its hosts keep the old SNI: %v", inboundId, err) + } + InvalidateSubData() + + cfg := s.loadConfig() + entry := cfg[inboundId] + spares := []string{} + for _, sp := range entry.Spares { + if sp != to { + spares = append(spares, sp) + } + } + if old, err := normalizeRealityTarget(from); err == nil && !containsString(spares, old) { + spares = append(spares, old) + } + entry.Spares = spares + cfg[inboundId] = entry + if err := s.storeConfig(cfg); err != nil { + return nil, err + } + ev := RealityWatchEvent{At: time.Now().Unix(), From: from, To: to, Reason: reason} + s.recordLocked(inboundId, ev) + realityWatchStates[inboundId].fails = 0 + logger.Warningf("reality watch: inbound %d switched from %s to %s", inboundId, from, to) + return &ev, nil +} + +func (s *RealityWatchService) recordLocked(inboundId int, ev RealityWatchEvent) { + state := realityWatchStates[inboundId] + if state == nil { + state = &realityWatchState{} + realityWatchStates[inboundId] = state + } + state.events = append(state.events, ev) + if len(state.events) > realityWatchMaxEvents { + state.events = state.events[len(state.events)-realityWatchMaxEvents:] + } +} + +// applyTarget rewrites only target and serverNames, keeping every other REALITY setting, and +// saves through UpdateInbound so the change reaches Xray the same way an admin's edit does. +func (s *RealityWatchService) applyTarget(ib *model.Inbound, target, sni string) error { + var stream map[string]any + if err := json.Unmarshal([]byte(ib.StreamSettings), &stream); err != nil { + return err + } + rs, ok := stream["realitySettings"].(map[string]any) + if !ok { + return errRealityWatchNotReality + } + delete(rs, "dest") + rs["target"] = target + rs["serverNames"] = []string{sni} + b, err := json.Marshal(stream) + if err != nil { + return err + } + ib.StreamSettings = string(b) + _, needRestart, err := s.inboundService.UpdateInbound(ib) + if err != nil { + return err + } + if needRestart { + s.xrayService.SetToNeedRestart() + } + return nil +} diff --git a/internal/web/service/reality_watch_test.go b/internal/web/service/reality_watch_test.go new file mode 100644 index 000000000..fdd451eeb --- /dev/null +++ b/internal/web/service/reality_watch_test.go @@ -0,0 +1,498 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +// stubRealityWatch makes probe answer from feasible (target -> ok) and the real test from +// works; both record what they were asked so a test can tell what was tried. +func stubRealityWatch(t *testing.T, feasible, works map[string]bool) *[]string { + t.Helper() + var tried []string + prevProbe, prevReal := realityWatchProbe, realityWatchRealTest + realityWatchProbe = func(_ *ServerService, target, _ string, _ int) *RealityScanResult { + if feasible[target] { + return &RealityScanResult{Target: target, Feasible: true} + } + return &RealityScanResult{Target: target, Reason: "TLS handshake failed: EOF"} + } + realityWatchRealTest = func(_ context.Context, target, _ string) error { + tried = append(tried, target) + if works[target] { + return nil + } + return errors.New("no reply through REALITY") + } + resetRealityWatchState() + t.Cleanup(func() { + realityWatchProbe, realityWatchRealTest = prevProbe, prevReal + resetRealityWatchState() + }) + return &tried +} + +func realityInbound(t *testing.T, port int, target, sni string) *model.Inbound { + t.Helper() + stream := `{"network":"tcp","security":"reality","realitySettings":{"show":false,"xver":0,"target":"` + + target + `","serverNames":["` + sni + `"],"privateKey":"k","shortIds":["ab"]}}` + return mkInboundStream(t, port, model.VLESS, `{"clients":[],"decryption":"none"}`, stream) +} + +func realityTargetOf(t *testing.T, id int) (string, []string) { + t.Helper() + ib, err := (&InboundService{}).GetInbound(id) + if err != nil { + t.Fatal(err) + } + var stream struct { + RealitySettings struct { + Target string `json:"target"` + ServerNames []string `json:"serverNames"` + PrivateKey string `json:"privateKey"` + } `json:"realitySettings"` + } + if err := json.Unmarshal([]byte(ib.StreamSettings), &stream); err != nil { + t.Fatal(err) + } + if stream.RealitySettings.PrivateKey != "k" { + t.Fatalf("switch lost the other REALITY settings: %s", ib.StreamSettings) + } + return stream.RealitySettings.Target, stream.RealitySettings.ServerNames +} + +// A single failure is often a blip, and a switch moves every client to a new SNI, so only the +// third failed check in a row switches, and only to a spare that passed both checks. +func TestRealityWatchSwitchesAfterThreeFailedChecks(t *testing.T) { + setupBulkDB(t) + tried := stubRealityWatch(t, + map[string]bool{"b.example:443": true, "c.example:443": true}, + map[string]bool{"b.example:443": false, "c.example:443": true}) + ib := realityInbound(t, 4431, "a.example:443", "a.example") + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Auto: true, Spares: []string{"b.example", "c.example:443"}}); err != nil { + t.Fatalf("SaveConfig: %v", err) + } + + for check := 1; check <= 2; check++ { + s.Tick(context.Background()) + if target, _ := realityTargetOf(t, ib.Id); target != "a.example:443" { + t.Fatalf("after %d failed checks target = %s, want it kept", check, target) + } + } + s.Tick(context.Background()) + target, names := realityTargetOf(t, ib.Id) + if target != "c.example:443" || !reflect.DeepEqual(names, []string{"c.example"}) { + t.Fatalf("after the third failed check target = %s %v, want c.example:443 [c.example]", target, names) + } + if !reflect.DeepEqual(*tried, []string{"b.example:443", "c.example:443"}) { + t.Errorf("real-tested %v, want b (failed) then c", *tried) + } + st := s.Status(ib.Id) + if !reflect.DeepEqual(st.Spares, []string{"b.example:443", "a.example:443"}) { + t.Errorf("spares after the switch = %v, want b kept and the old target last", st.Spares) + } + if len(st.Events) != 1 || st.Events[0].From != "a.example:443" || st.Events[0].To != "c.example:443" { + t.Errorf("events = %+v, want one switch a -> c", st.Events) + } +} + +// With no spare that works the inbound must stay as it is: a switch would only trade a +// broken target for another broken one. The outage is logged once, not every check. +func TestRealityWatchKeepsTheTargetWhenNoSpareWorks(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, map[string]bool{"b.example:443": true}, nil) + ib := realityInbound(t, 4432, "a.example:443", "a.example") + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Auto: true, Spares: []string{"b.example:443"}}); err != nil { + t.Fatal(err) + } + for range 5 { + s.Tick(context.Background()) + } + if target, _ := realityTargetOf(t, ib.Id); target != "a.example:443" { + t.Fatalf("target = %s, want a.example:443 kept", target) + } + st := s.Status(ib.Id) + if st.Fails != 5 || len(st.Events) != 1 || st.Events[0].To != "" { + t.Fatalf("fails %d, events %+v; want 5 fails and one 'no spare works' event", st.Fails, st.Events) + } +} + +// A good check in between starts the count again; auto off and node inbounds never switch. +func TestRealityWatchOnlySwitchesSustainedFailuresItOwns(t *testing.T) { + setupBulkDB(t) + feasible := map[string]bool{"b.example:443": true} + stubRealityWatch(t, feasible, map[string]bool{"b.example:443": true}) + ib := realityInbound(t, 4433, "a.example:443", "a.example") + manual := realityInbound(t, 4434, "a.example:443", "a.example") + node := realityInbound(t, 4435, "a.example:443", "a.example") + nodeID := 7 + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", node.Id).Update("node_id", nodeID).Error; err != nil { + t.Fatal(err) + } + s := &RealityWatchService{} + for id, auto := range map[int]bool{ib.Id: true, manual.Id: false, node.Id: true} { + if err := s.SaveConfig(id, RealityWatchEntry{Auto: auto, Spares: []string{"b.example:443"}}); err != nil { + t.Fatal(err) + } + } + + s.Tick(context.Background()) + s.Tick(context.Background()) + feasible["a.example:443"] = true + s.Tick(context.Background()) + delete(feasible, "a.example:443") + s.Tick(context.Background()) + s.Tick(context.Background()) + if target, _ := realityTargetOf(t, ib.Id); target != "a.example:443" { + t.Fatalf("2 fails, ok, 2 fails switched to %s; the good check must reset the count", target) + } + s.Tick(context.Background()) + for _, tc := range []struct { + name string + id int + want string + }{{"auto", ib.Id, "b.example:443"}, {"auto off", manual.Id, "a.example:443"}, {"node inbound", node.Id, "a.example:443"}} { + if target, _ := realityTargetOf(t, tc.id); target != tc.want { + t.Errorf("%s: target = %s, want %s", tc.name, target, tc.want) + } + } + if st := s.Status(manual.Id); st.Fails != 3 { + t.Errorf("auto off still shows the checks: fails = %d, want 3 since the good one", st.Fails) + } + if st := s.Status(node.Id); st.Fails != 0 || st.CheckedAt != 0 { + t.Errorf("node inbound was checked from this server (fails %d); its REALITY runs on the node", st.Fails) + } +} + +// The admin's switch button goes through the same real test: a spare that fails it is refused. +func TestRealityWatchManualSwitchNeedsTheRealTest(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, map[string]bool{"b.example:443": true, "c.example:443": true}, + map[string]bool{"c.example:443": true}) + ib := realityInbound(t, 4436, "a.example:443", "a.example") + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Spares: []string{"b.example:443", "c.example:443"}}); err != nil { + t.Fatal(err) + } + if _, err := s.SwitchTo(context.Background(), ib.Id, "b.example:443"); !errors.Is(err, errRealityWatchTargetFails) { + t.Fatalf("switch to a spare failing the real test: err = %v, want errRealityWatchTargetFails", err) + } + if target, _ := realityTargetOf(t, ib.Id); target != "a.example:443" { + t.Fatalf("refused switch still changed the target to %s", target) + } + if ev, err := s.SwitchTo(context.Background(), ib.Id, "c.example:443"); err != nil || ev.To != "c.example:443" { + t.Fatalf("switch to c: %+v, %v", ev, err) + } + if target, _ := realityTargetOf(t, ib.Id); target != "c.example:443" { + t.Fatalf("target = %s, want c.example:443", target) + } + // the editor fills its form from this, or its Save would put the old target back + if st := s.Status(ib.Id); st.Target != "c.example:443" || !reflect.DeepEqual(st.ServerNames, []string{"c.example"}) { + t.Errorf("status after the switch: target %s names %v", st.Target, st.ServerNames) + } +} + +func TestRealityWatchSaveConfigNormalizesSpares(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, nil, nil) + ib := realityInbound(t, 4437, "a.example:443", "a.example") + s := &RealityWatchService{} + err := s.SaveConfig(ib.Id, RealityWatchEntry{Spares: []string{" B.example ", "b.example:443", "c.example:8443", "a.example:443"}}) + if err != nil { + t.Fatal(err) + } + if got := s.Status(ib.Id).Spares; !reflect.DeepEqual(got, []string{"b.example:443", "c.example:8443"}) { + t.Errorf("spares = %v, want lower-cased, :443 added, repeats and the current target dropped", got) + } + for _, bad := range []string{"not a host", "a.example:99999", `x"; rm`} { + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Spares: []string{bad}}); !errors.Is(err, errRealityWatchBadSpare) { + t.Errorf("spare %q: err = %v, want errRealityWatchBadSpare", bad, err) + } + } + plain := mkInboundStream(t, 4438, model.VLESS, `{"clients":[]}`, `{"network":"tcp","security":"tls"}`) + if err := s.SaveConfig(plain.Id, RealityWatchEntry{Auto: true}); !errors.Is(err, errRealityWatchNotReality) { + t.Errorf("watch on a TLS inbound: err = %v, want errRealityWatchNotReality", err) + } +} + +// A target on this machine or the LAN (a local web server fronting REALITY, a bare port, a +// unix socket) is blocked by the probe's SSRF guard; that is not a failure to act on. +func TestRealityWatchLeavesLocalTargetsAlone(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, map[string]bool{"b.example:443": true}, map[string]bool{"b.example:443": true}) + prev := realityWatchProbe + realityWatchProbe = func(s *ServerService, target, sni string, xver int) *RealityScanResult { + if target == "local.example:443" { + return &RealityScanResult{Target: target, PrivateTarget: true, Reason: "connection failed: private address blocked"} + } + return prev(s, target, sni, xver) + } + s := &RealityWatchService{} + var ids []int + for i, target := range []string{"127.0.0.1:8443", "8443", "/run/web.sock", "local.example:443"} { + ib := realityInbound(t, 4440+i, target, "a.example") + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Auto: true, Spares: []string{"b.example:443"}}); err != nil { + t.Fatalf("SaveConfig(%s): %v", target, err) + } + ids = append(ids, ib.Id) + } + for range 4 { + s.Tick(context.Background()) + } + for _, id := range ids { + target, _ := realityTargetOf(t, id) + if target == "b.example:443" || s.Status(id).Fails != 0 { + t.Errorf("local target %s: switched or counted as failing (fails %d)", target, s.Status(id).Fails) + } + } +} + +// duringRealTest runs edit while the spare's real test is in flight, the slow part of a switch. +func duringRealTest(t *testing.T, edit func()) { + t.Helper() + prev := realityWatchRealTest + realityWatchRealTest = func(ctx context.Context, target, sni string) error { + edit() + return prev(ctx, target, sni) + } + t.Cleanup(func() { realityWatchRealTest = prev }) +} + +// A switch used to save the copy read before its checks, wiping what the admin saved meanwhile. +func TestRealityWatchSwitchKeepsAnEditSavedDuringTheCheck(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, map[string]bool{"b.example:443": true}, map[string]bool{"b.example:443": true}) + ib := realityInbound(t, 4441, "a.example:443", "a.example") + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Spares: []string{"b.example:443"}}); err != nil { + t.Fatal(err) + } + duringRealTest(t, func() { + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("remark", "edited").Error; err != nil { + t.Error(err) + } + }) + if _, err := s.SwitchTo(context.Background(), ib.Id, "b.example:443"); err != nil { + t.Fatalf("SwitchTo: %v", err) + } + got, err := (&InboundService{}).GetInbound(ib.Id) + if err != nil { + t.Fatal(err) + } + if got.Remark != "edited" { + t.Errorf("remark = %q, the switch overwrote the admin's edit", got.Remark) + } + if target, _ := realityTargetOf(t, ib.Id); target != "b.example:443" { + t.Errorf("target = %s, want b.example:443", target) + } +} + +// An admin who fixes the target by hand mid-check has decided; the watcher must not override it. +func TestRealityWatchDoesNotSwitchATargetTheAdminJustChanged(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, map[string]bool{"b.example:443": true}, map[string]bool{"b.example:443": true}) + ib := realityInbound(t, 4442, "a.example:443", "a.example") + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Auto: true, Spares: []string{"b.example:443"}}); err != nil { + t.Fatal(err) + } + s.Tick(context.Background()) + s.Tick(context.Background()) + duringRealTest(t, func() { + cur, err := (&InboundService{}).GetInbound(ib.Id) + if err != nil { + t.Error(err) + return + } + stream := strings.ReplaceAll(cur.StreamSettings, "a.example", "admin.example") + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("stream_settings", stream).Error; err != nil { + t.Error(err) + } + }) + s.Tick(context.Background()) + if target, _ := realityTargetOf(t, ib.Id); target != "admin.example:443" { + t.Errorf("target = %s, the watcher replaced the admin's choice", target) + } + st := s.Status(ib.Id) + if !reflect.DeepEqual(st.Spares, []string{"b.example:443"}) { + t.Errorf("spares = %v, want them untouched", st.Spares) + } + if len(st.Events) != 0 { + t.Errorf("events = %+v, want none: nothing switched and a spare did pass", st.Events) + } +} + +// Checks take up to 10 s per probe and 25 s per real test; the watch API must answer meanwhile. +func TestRealityWatchApiAnswersDuringACheck(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, nil, nil) + ib := realityInbound(t, 4443, "a.example:443", "a.example") + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Spares: []string{"b.example:443"}}); err != nil { + t.Fatal(err) + } + prev := realityWatchProbe + t.Cleanup(func() { realityWatchProbe = prev }) + realityWatchProbe = func(sv *ServerService, target, sni string, xver int) *RealityScanResult { + answered := make(chan struct{}) + go func() { + s.Status(ib.Id) + close(answered) + }() + select { + case <-answered: + case <-time.After(3 * time.Second): + t.Error("Status blocked behind a running check") + } + return prev(sv, target, sni, xver) + } + s.Tick(context.Background()) +} + +// With the lock no longer held across checks, a slow cycle must not double-count failures. +func TestRealityWatchTicksDoNotOverlap(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, nil, nil) + ib := realityInbound(t, 4444, "a.example:443", "a.example") + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Spares: []string{"b.example:443"}}); err != nil { + t.Fatal(err) + } + prev := realityWatchProbe + t.Cleanup(func() { realityWatchProbe = prev }) + calls := 0 + realityWatchProbe = func(sv *ServerService, target, sni string, xver int) *RealityScanResult { + calls++ + if calls == 1 { + nested := make(chan struct{}) + go func() { + s.Tick(context.Background()) + close(nested) + }() + select { + case <-nested: + case <-time.After(3 * time.Second): + t.Error("the overlapping tick waited instead of returning at once") + } + } + return prev(sv, target, sni, xver) + } + s.Tick(context.Background()) + if calls != 1 { + t.Errorf("target probed %d times, want the overlapping tick to do nothing", calls) + } + if st := s.Status(ib.Id); st.Fails != 1 { + t.Errorf("fails = %d, want 1", st.Fails) + } +} + +// Missing the scanner's bar (no h2, SNI not on the cert) does not mean REALITY is broken: only +// a target with no TLS 1.3, or one failing the real connection, counts as a failed check. +func TestRealityWatchRealTestJudgesATargetTheScannerDislikes(t *testing.T) { + for _, tc := range []struct { + name string + worksNow bool + tls13 bool + wantFails int + wantOk bool + }{ + {"works through REALITY", true, true, 0, true}, + {"fails through REALITY", false, true, 1, false}, + {"no TLS 1.3", true, false, 1, false}, + } { + t.Run(tc.name, func(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, nil, map[string]bool{"a.example:443": tc.worksNow}) + prev := realityWatchProbe + t.Cleanup(func() { realityWatchProbe = prev }) + realityWatchProbe = func(_ *ServerService, target, _ string, _ int) *RealityScanResult { + return &RealityScanResult{Target: target, TLS13: tc.tls13, Reason: "server does not negotiate HTTP/2 (h2)"} + } + ib := realityInbound(t, 4445, "a.example:443", "a.example") + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Spares: []string{"b.example:443"}}); err != nil { + t.Fatal(err) + } + s.Tick(context.Background()) + st := s.Status(ib.Id) + if st.Fails != tc.wantFails || st.Ok != tc.wantOk { + t.Errorf("fails = %d ok = %v, want %d %v", st.Fails, st.Ok, tc.wantFails, tc.wantOk) + } + }) + } +} + +// A Host's own SNI overrides serverNames in links, so a stale one keeps clients cut off after +// a switch. Only rows of this inbound that use REALITY and pin one of its old names may change. +func TestRealityWatchSwitchMovesHostSnis(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, map[string]bool{"b.example:443": true}, map[string]bool{"b.example:443": true}) + ib := realityInbound(t, 4446, "a.example:443", "a.example") + other := realityInbound(t, 4447, "a.example:443", "a.example") + rows := []*model.Host{ + {InboundId: ib.Id, Remark: "pinned", Security: "same", Sni: "a.example"}, + {InboundId: ib.Id, Remark: "pool", Security: "reality", Sni: "a.example", Snis: []string{"a.example", "custom.example"}}, + {InboundId: ib.Id, Remark: "custom", Security: "same", Sni: "custom.example"}, + {InboundId: ib.Id, Remark: "tls", Security: "tls", Sni: "a.example"}, + {InboundId: other.Id, Remark: "other", Security: "same", Sni: "a.example"}, + } + if err := database.GetDB().Create(&rows).Error; err != nil { + t.Fatal(err) + } + s := &RealityWatchService{} + if err := s.SaveConfig(ib.Id, RealityWatchEntry{Spares: []string{"b.example:443"}}); err != nil { + t.Fatal(err) + } + if _, err := s.SwitchTo(context.Background(), ib.Id, "b.example:443"); err != nil { + t.Fatalf("SwitchTo: %v", err) + } + want := map[string]struct { + sni string + snis []string + }{ + "pinned": {sni: "b.example"}, + "pool": {sni: "b.example", snis: []string{"b.example", "custom.example"}}, + "custom": {sni: "custom.example"}, + "tls": {sni: "a.example"}, + "other": {sni: "a.example"}, + } + var got []model.Host + if err := database.GetDB().Find(&got).Error; err != nil { + t.Fatal(err) + } + for _, h := range got { + w := want[h.Remark] + if h.Sni != w.sni || !slices.Equal(h.Snis, w.snis) { + t.Errorf("host %s: sni %q snis %v, want %q %v", h.Remark, h.Sni, h.Snis, w.sni, w.snis) + } + } +} + +// The UI disables the button for node inbounds because this server's tests say nothing about +// the node's network; the API must hold the same line. +func TestRealityWatchManualSwitchRefusesANodeInbound(t *testing.T) { + setupBulkDB(t) + stubRealityWatch(t, map[string]bool{"b.example:443": true}, map[string]bool{"b.example:443": true}) + ib := realityInbound(t, 4448, "a.example:443", "a.example") + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("node_id", 7).Error; err != nil { + t.Fatal(err) + } + s := &RealityWatchService{} + if _, err := s.SwitchTo(context.Background(), ib.Id, "b.example:443"); !errors.Is(err, errRealityWatchOnNode) { + t.Fatalf("err = %v, want errRealityWatchOnNode", err) + } + if target, _ := realityTargetOf(t, ib.Id); target != "a.example:443" { + t.Errorf("target = %s, want it kept", target) + } +} diff --git a/internal/web/service/reality_watch_xray.go b/internal/web/service/reality_watch_xray.go new file mode 100644 index 000000000..4342186e0 --- /dev/null +++ b/internal/web/service/reality_watch_xray.go @@ -0,0 +1,134 @@ +package service + +import ( + "context" + "crypto/ecdh" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "strconv" + "time" + + "github.com/google/uuid" + + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +const realityRealTestTimeout = 25 * time.Second + +var realityRealTestBinary = xray.GetBinaryPath + +// xrayRealityRealTest fetches https://sni/ through a throwaway REALITY server and client on +// loopback: some sites pass TLS 1.3 + h2 but break REALITY's handshake, cutting every client. +func xrayRealityRealTest(ctx context.Context, target, sni string) error { + bin := realityRealTestBinary() + if _, err := os.Stat(bin); err != nil { + return fmt.Errorf("xray binary: %w", err) + } + priv, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + return err + } + privKey := base64.RawURLEncoding.EncodeToString(priv.Bytes()) + pubKey := base64.RawURLEncoding.EncodeToString(priv.PublicKey().Bytes()) + id := uuid.NewString() + serverPort, err := realityTestPort(ctx) + if err != nil { + return err + } + socksPort, err := realityTestPort(ctx) + if err != nil { + return err + } + dir, err := os.MkdirTemp("", "xui-reality-test-") + if err != nil { + return err + } + defer os.RemoveAll(dir) + + server := map[string]any{ + "log": map[string]any{"loglevel": "none"}, + "inbounds": []any{map[string]any{ + "listen": "127.0.0.1", "port": serverPort, "protocol": "vless", + "settings": map[string]any{"clients": []any{map[string]any{"id": id}}, "decryption": "none"}, + "streamSettings": map[string]any{"network": "tcp", "security": "reality", "realitySettings": map[string]any{ + "target": target, "serverNames": []string{sni}, "privateKey": privKey, "shortIds": []string{"a1"}, + }}, + }}, + "outbounds": []any{map[string]any{"protocol": "freedom"}}, + } + client := map[string]any{ + "log": map[string]any{"loglevel": "none"}, + "inbounds": []any{map[string]any{"listen": "127.0.0.1", "port": socksPort, "protocol": "socks", "settings": map[string]any{"udp": false}}}, + "outbounds": []any{map[string]any{ + "protocol": "vless", + "settings": map[string]any{"vnext": []any{map[string]any{ + "address": "127.0.0.1", "port": serverPort, + "users": []any{map[string]any{"id": id, "encryption": "none"}}, + }}}, + "streamSettings": map[string]any{"network": "tcp", "security": "reality", "realitySettings": map[string]any{ + "serverName": sni, "fingerprint": "chrome", "publicKey": pubKey, "shortId": "a1", + }}, + }}, + } + + ctx, cancel := context.WithTimeout(ctx, realityRealTestTimeout) + defer cancel() + for name, cfg := range map[string]any{"server.json": server, "client.json": client} { + b, _ := json.Marshal(cfg) + path := filepath.Join(dir, name) + if err := os.WriteFile(path, b, 0o600); err != nil { + return err + } + cmd := exec.CommandContext(ctx, bin, "run", "-c", path) + if err := cmd.Start(); err != nil { + return err + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + } + socks := "127.0.0.1:" + strconv.Itoa(socksPort) + for !portOpen(ctx, socks) { + select { + case <-ctx.Done(): + return errors.New("throwaway xray did not start") + case <-time.After(200 * time.Millisecond): + } + } + httpClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(&url.URL{Scheme: "socks5", Host: socks})}} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+net.JoinHostPort(sni, "443")+"/", nil) + if err != nil { + return err + } + resp, err := httpClient.Do(req) + if err != nil { + return fmt.Errorf("no reply through REALITY: %w", err) + } + resp.Body.Close() + return nil +} + +func realityTestPort(ctx context.Context) (int, error) { + l, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0") + if err != nil { + return 0, err + } + defer l.Close() + return l.Addr().(*net.TCPAddr).Port, nil +} + +func portOpen(ctx context.Context, addr string) bool { + c, err := (&net.Dialer{Timeout: 200 * time.Millisecond}).DialContext(ctx, "tcp", addr) + if err != nil { + return false + } + c.Close() + return true +} diff --git a/internal/web/service/reality_watch_xray_e2e_test.go b/internal/web/service/reality_watch_xray_e2e_test.go new file mode 100644 index 000000000..03c000820 --- /dev/null +++ b/internal/web/service/reality_watch_xray_e2e_test.go @@ -0,0 +1,32 @@ +package service + +import ( + "context" + "os" + "testing" +) + +// The real test is the gate before every switch: it must pass on a site REALITY works with +// and fail when the target is unreachable. Needs an xray binary and internet: +// +// XRAY_E2E_BINARY=/usr/local/x-ui/bin/xray-linux-amd64 go test ./internal/web/service -run TestRealityRealTestAgainstRealXray +func TestRealityRealTestAgainstRealXray(t *testing.T) { + bin := os.Getenv("XRAY_E2E_BINARY") + if bin == "" { + t.Skip("XRAY_E2E_BINARY not set") + } + prev := realityRealTestBinary + realityRealTestBinary = func() string { return bin } + t.Cleanup(func() { realityRealTestBinary = prev }) + + target := os.Getenv("REALITY_E2E_TARGET") + if target == "" { + target = "www.speedtest.net" + } + if err := xrayRealityRealTest(context.Background(), target+":443", target); err != nil { + t.Fatalf("REALITY through %s: %v; want a reply", target, err) + } + if err := xrayRealityRealTest(context.Background(), "127.0.0.1:1", target); err == nil { + t.Fatal("REALITY with an unreachable target passed; want an error") + } +} diff --git a/internal/web/service/setting.go b/internal/web/service/setting.go index 940513a14..c18e3f967 100644 --- a/internal/web/service/setting.go +++ b/internal/web/service/setting.go @@ -82,6 +82,7 @@ var defaultValueMap = map[string]string{ "publicIpv6Override": "", "trustedProxyCIDRs": DefaultTrustedProxyCIDRs, "realityScanCandidates": DefaultRealityScanCandidatesCSV, + "realityWatch": "{}", "ipLimitAllowlist": "", "pageSize": "25", "expireDiff": "0", diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 0fa42a54f..8ea65faad 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -810,7 +810,37 @@ "peerNumberConfig": "تكوين Peer {n}" }, "sniffingDestOverride": "تجاوز الوجهة", - "advancedTitle": "الإعدادات المتقدمة" + "advancedTitle": "الإعدادات المتقدمة", + "realityWatch": { + "title": "إبقاء REALITY يعمل", + "savedWithInbound": "تُحفظ مع الوارد نفسه.", + "hint": "يفحص هذا الخادم الهدف كل 10 دقائق. بعد {limit} فحوص فاشلة متتالية، ينتقل الوارد إلى أول هدف احتياطي يجتاز الفحص نفسه واتصال REALITY حقيقيًا عبر Xray مؤقت. يتغير الهدف وSNI فقط؛ يحصل العملاء على SNI الجديد مع تحديث الاشتراك التالي.", + "onNode": "يعمل هذا الوارد على عقدة، لذا لا يمكن لهذا الخادم فحص هدفه أو تبديله.", + "status": "الحالة", + "notChecked": "لم يُفحص بعد", + "failing": "معطّل ({fails} من {limit})", + "working": "يعمل", + "auto": "استبدال تلقائي", + "spares": "أهداف احتياطية", + "noSpares": "لا توجد أهداف احتياطية: أضف بعضها عبر «بحث عن احتياطي»", + "realTest": "اختبار حقيقي", + "testOk": "يعمل", + "testFailed": "لا يعمل", + "test": "اختبار", + "testAll": "اختبار الكل", + "switchNow": "التبديل إليه الآن", + "findSpares": "بحث عن احتياطي", + "save": "حفظ الاحتياطيات", + "history": "السجل", + "eventSwitched": "{from} ← {to}", + "eventNoSpare": "تعطّل {from} ولم يعمل أي احتياطي", + "toasts": { + "saved": "تم حفظ الاحتياطيات", + "failed": "تعذّر حفظ الاحتياطيات", + "switchFailed": "تعذّر التبديل: فشل الهدف في الفحص أو في اختبار REALITY الحقيقي", + "switched": "تم التبديل إلى {target}" + } + } }, "clients": { "tabBasics": "أساسي", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 5587810ed..d8b5a369d 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -810,7 +810,37 @@ "peerNumber": "Peer {n}", "peerNumberConfig": "Peer {n} config" }, - "sniffingDestOverride": "Destination override" + "sniffingDestOverride": "Destination override", + "realityWatch": { + "title": "Keep REALITY working", + "savedWithInbound": "They are saved together with the inbound.", + "hint": "Every 10 minutes this server checks the target. After {limit} failed checks in a row, the inbound moves to the first spare that passes the same check and a real REALITY connection through a temporary Xray. Only the target and SNI change; clients get the new SNI with their next subscription update.", + "onNode": "This inbound runs on a node, so this server cannot check or switch its target.", + "status": "Status", + "notChecked": "not checked yet", + "failing": "failing ({fails} of {limit})", + "working": "working", + "auto": "Replace automatically", + "spares": "Spare targets", + "noSpares": "No spares yet: add some with Find spares", + "realTest": "Real test", + "testOk": "works", + "testFailed": "fails", + "test": "Test", + "testAll": "Test all", + "switchNow": "Switch to this now", + "findSpares": "Find spares", + "save": "Save spares", + "history": "History", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} failed and no spare worked", + "toasts": { + "saved": "Spares saved", + "failed": "Could not save the spares", + "switchFailed": "Could not switch: the target failed the check or the real REALITY test", + "switched": "Switched to {target}" + } + } }, "clients": { "tabBasics": "Basics", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index acd69923a..b8c116ce3 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Config Peer {n}" }, "sniffingDestOverride": "Anulación de destino", - "advancedTitle": "Configuración avanzada" + "advancedTitle": "Configuración avanzada", + "realityWatch": { + "title": "Mantener REALITY funcionando", + "savedWithInbound": "Se guardan junto con la entrada.", + "hint": "Cada 10 minutos este servidor comprueba el destino. Tras {limit} comprobaciones fallidas seguidas, el inbound pasa a la primera reserva que supere la misma comprobación y una conexión REALITY real a través de un Xray temporal. Solo cambian el destino y el SNI; los clientes reciben el nuevo SNI con la próxima actualización de la suscripción.", + "onNode": "Este inbound se ejecuta en un nodo, así que este servidor no puede comprobar ni cambiar su destino.", + "status": "Estado", + "notChecked": "aún sin comprobar", + "failing": "fallando ({fails} de {limit})", + "working": "funciona", + "auto": "Reemplazar automáticamente", + "spares": "Destinos de reserva", + "noSpares": "Aún no hay reservas: añade algunas con Buscar reservas", + "realTest": "Prueba real", + "testOk": "funciona", + "testFailed": "falla", + "test": "Probar", + "testAll": "Probar todos", + "switchNow": "Cambiar a este ahora", + "findSpares": "Buscar reservas", + "save": "Guardar reservas", + "history": "Historial", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} falló y ninguna reserva funcionó", + "toasts": { + "saved": "Reservas guardadas", + "failed": "No se pudieron guardar las reservas", + "switchFailed": "No se pudo cambiar: el destino no superó la comprobación o la prueba REALITY real", + "switched": "Cambiado a {target}" + } + } }, "clients": { "tabBasics": "Básico", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index a738c443d..20fa9fc25 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -810,7 +810,37 @@ "peerNumberConfig": "پیکربندی Peer {n}" }, "sniffingDestOverride": "بازنویسی مقصد", - "advancedTitle": "تنظیمات پیشرفته" + "advancedTitle": "تنظیمات پیشرفته", + "realityWatch": { + "title": "زنده نگه داشتن REALITY", + "savedWithInbound": "این‌ها همراه با خود اینباند ذخیره می‌شوند.", + "hint": "این سرور هر ۱۰ دقیقه تارگت را بررسی می‌کند. بعد از {limit} بررسی ناموفق پشت سر هم، اینباند به اولین یدکی می‌رود که همان بررسی و یک اتصال واقعی REALITY از طریق یک Xray موقت را رد کند. فقط تارگت و SNI عوض می‌شوند؛ کلاینت‌ها SNI جدید را با به‌روزرسانی بعدی ساب‌اسکریپشن می‌گیرند.", + "onNode": "این اینباند روی یک نود اجرا می‌شود، پس این سرور نمی‌تواند هدف آن را بررسی یا تعویض کند.", + "status": "وضعیت", + "notChecked": "هنوز بررسی نشده", + "failing": "خراب ({fails} از {limit})", + "working": "کار می‌کند", + "auto": "جایگزینی خودکار", + "spares": "تارگت‌های یدک", + "noSpares": "هنوز یدکی نیست: با «پیدا کردن یدک» اضافه کنید", + "realTest": "تست واقعی", + "testOk": "کار می‌کند", + "testFailed": "کار نمی‌کند", + "test": "تست", + "testAll": "تست همه", + "switchNow": "همین الان جایگزین شود", + "findSpares": "پیدا کردن یدک", + "save": "ذخیرهٔ یدک‌ها", + "history": "تاریخچه", + "eventSwitched": "{from} ← {to}", + "eventNoSpare": "{from} خراب شد و هیچ یدکی کار نکرد", + "toasts": { + "saved": "یدک‌ها ذخیره شدند", + "failed": "ذخیرهٔ یدک‌ها ممکن نشد", + "switchFailed": "تعویض ممکن نشد: تارگت بررسی یا تست واقعی REALITY را رد نکرد", + "switched": "به {target} تعویض شد" + } + } }, "clients": { "tabBasics": "پایه", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 7c256051d..e09f5e044 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Konfig Peer {n}" }, "sniffingDestOverride": "Penggantian tujuan", - "advancedTitle": "Pengaturan Lanjutan" + "advancedTitle": "Pengaturan Lanjutan", + "realityWatch": { + "title": "Jaga REALITY tetap jalan", + "savedWithInbound": "Semua ini disimpan bersama inbound.", + "hint": "Setiap 10 menit server ini memeriksa target. Setelah {limit} pemeriksaan gagal berturut-turut, inbound pindah ke cadangan pertama yang lolos pemeriksaan yang sama dan koneksi REALITY sungguhan melalui Xray sementara. Hanya target dan SNI yang berubah; klien mendapat SNI baru pada pembaruan langganan berikutnya.", + "onNode": "Inbound ini berjalan di node, jadi server ini tidak dapat memeriksa atau mengganti targetnya.", + "status": "Status", + "notChecked": "belum diperiksa", + "failing": "gagal ({fails} dari {limit})", + "working": "berjalan", + "auto": "Ganti otomatis", + "spares": "Target cadangan", + "noSpares": "Belum ada cadangan: tambahkan dengan Cari cadangan", + "realTest": "Tes nyata", + "testOk": "berhasil", + "testFailed": "gagal", + "test": "Tes", + "testAll": "Tes semua", + "switchNow": "Ganti ke ini sekarang", + "findSpares": "Cari cadangan", + "save": "Simpan cadangan", + "history": "Riwayat", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} gagal dan tidak ada cadangan yang berhasil", + "toasts": { + "saved": "Cadangan disimpan", + "failed": "Tidak bisa menyimpan cadangan", + "switchFailed": "Tidak bisa mengganti: target gagal pemeriksaan atau tes REALITY nyata", + "switched": "Diganti ke {target}" + } + } }, "clients": { "tabBasics": "Dasar", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 99b6bdf87..6ca2ec60d 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Peer {n} 設定" }, "sniffingDestOverride": "宛先のオーバーライド", - "advancedTitle": "詳細設定" + "advancedTitle": "詳細設定", + "realityWatch": { + "title": "REALITY を維持", + "savedWithInbound": "インバウンドと一緒に保存されます。", + "hint": "このサーバーは10分ごとにターゲットを確認します。{limit}回連続で失敗すると、同じ確認と一時的な Xray を使った実際の REALITY 接続に合格した最初の予備に切り替えます。変わるのはターゲットと SNI だけで、クライアントは次のサブスクリプション更新で新しい SNI を受け取ります。", + "onNode": "このインバウンドはノードで動いているため、このサーバーではターゲットの確認も切り替えもできません。", + "status": "状態", + "notChecked": "未確認", + "failing": "失敗中({fails} / {limit})", + "working": "正常", + "auto": "自動で置き換える", + "spares": "予備ターゲット", + "noSpares": "予備がありません。「予備を探す」で追加してください", + "realTest": "実接続テスト", + "testOk": "成功", + "testFailed": "失敗", + "test": "テスト", + "testAll": "すべてテスト", + "switchNow": "今すぐこれに切り替え", + "findSpares": "予備を探す", + "save": "予備を保存", + "history": "履歴", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} が失敗し、使える予備がありませんでした", + "toasts": { + "saved": "予備を保存しました", + "failed": "予備を保存できませんでした", + "switchFailed": "切り替えできません:ターゲットが確認または実際の REALITY テストに失敗しました", + "switched": "{target} に切り替えました" + } + } }, "clients": { "tabBasics": "基本", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index d7456e2ba..82f0e3ab3 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Config Peer {n}" }, "sniffingDestOverride": "Substituição de destino", - "advancedTitle": "Configurações avançadas" + "advancedTitle": "Configurações avançadas", + "realityWatch": { + "title": "Manter o REALITY funcionando", + "savedWithInbound": "Eles são salvos junto com a entrada.", + "hint": "A cada 10 minutos este servidor verifica o destino. Após {limit} verificações seguidas com falha, o inbound passa para a primeira reserva que passar na mesma verificação e numa conexão REALITY real por um Xray temporário. Só o destino e o SNI mudam; os clientes recebem o novo SNI na próxima atualização da assinatura.", + "onNode": "Este inbound roda em um nó, então este servidor não pode verificar nem trocar o destino dele.", + "status": "Status", + "notChecked": "ainda não verificado", + "failing": "falhando ({fails} de {limit})", + "working": "funcionando", + "auto": "Substituir automaticamente", + "spares": "Destinos reserva", + "noSpares": "Nenhuma reserva ainda: adicione com Buscar reservas", + "realTest": "Teste real", + "testOk": "funciona", + "testFailed": "falha", + "test": "Testar", + "testAll": "Testar todos", + "switchNow": "Trocar para este agora", + "findSpares": "Buscar reservas", + "save": "Salvar reservas", + "history": "Histórico", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} falhou e nenhuma reserva funcionou", + "toasts": { + "saved": "Reservas salvas", + "failed": "Não foi possível salvar as reservas", + "switchFailed": "Não foi possível trocar: o destino falhou na verificação ou no teste REALITY real", + "switched": "Trocado para {target}" + } + } }, "clients": { "tabBasics": "Básico", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 74979702c..32fc4e533 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -810,7 +810,37 @@ "peerNumber": "Peer {n}", "peerNumberConfig": "Конфиг Peer {n}" }, - "sniffingDestOverride": "Переопределение назначения" + "sniffingDestOverride": "Переопределение назначения", + "realityWatch": { + "title": "Поддерживать REALITY в работе", + "savedWithInbound": "Они сохраняются вместе с инбаундом.", + "hint": "Каждые 10 минут этот сервер проверяет цель. После {limit} неудачных проверок подряд инбаунд переходит на первую запасную цель, прошедшую ту же проверку и реальное подключение REALITY через временный Xray. Меняются только цель и SNI; клиенты получат новый SNI при следующем обновлении подписки.", + "onNode": "Этот инбаунд работает на ноде, поэтому этот сервер не может проверить или переключить его цель.", + "status": "Статус", + "notChecked": "ещё не проверено", + "failing": "сбой ({fails} из {limit})", + "working": "работает", + "auto": "Заменять автоматически", + "spares": "Запасные цели", + "noSpares": "Запасных пока нет: добавьте через «Найти запасные»", + "realTest": "Реальный тест", + "testOk": "работает", + "testFailed": "не работает", + "test": "Тест", + "testAll": "Проверить все", + "switchNow": "Переключить сейчас", + "findSpares": "Найти запасные", + "save": "Сохранить запасные", + "history": "История", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} перестал работать, и ни одна запасная не подошла", + "toasts": { + "saved": "Запасные сохранены", + "failed": "Не удалось сохранить запасные", + "switchFailed": "Не удалось переключить: цель не прошла проверку или реальный тест REALITY", + "switched": "Переключено на {target}" + } + } }, "clients": { "tabBasics": "Основные", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 503a79b8b..3a555e699 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -810,7 +810,37 @@ "peerNumber": "Peer {n}", "peerNumberConfig": "Konfigurácia peeru {n}" }, - "sniffingDestOverride": "Prepísať cieľ" + "sniffingDestOverride": "Prepísať cieľ", + "realityWatch": { + "title": "Udržať REALITY v chode", + "savedWithInbound": "Uložia sa spolu s inboundom.", + "hint": "Tento server každých 10 minút kontroluje cieľ. Po {limit} neúspešných kontrolách za sebou sa inbound presunie na prvý záložný cieľ, ktorý prejde rovnakou kontrolou a skutočným spojením REALITY cez dočasný Xray. Mení sa len cieľ a SNI; klienti dostanú nové SNI pri ďalšej aktualizácii odberu.", + "onNode": "Tento inbound beží na uzle, preto tento server nemôže skontrolovať ani prepnúť jeho cieľ.", + "status": "Stav", + "notChecked": "zatiaľ nekontrolované", + "failing": "zlyháva ({fails} z {limit})", + "working": "funguje", + "auto": "Nahradiť automaticky", + "spares": "Záložné ciele", + "noSpares": "Zatiaľ žiadne záložné: pridajte cez Nájsť záložné", + "realTest": "Skutočný test", + "testOk": "funguje", + "testFailed": "zlyhal", + "test": "Test", + "testAll": "Otestovať všetky", + "switchNow": "Prepnúť naň teraz", + "findSpares": "Nájsť záložné", + "save": "Uložiť záložné", + "history": "História", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} zlyhal a žiadny záložný nefungoval", + "toasts": { + "saved": "Záložné uložené", + "failed": "Záložné sa nepodarilo uložiť", + "switchFailed": "Prepnutie zlyhalo: cieľ neprešiel kontrolou alebo skutočným testom REALITY", + "switched": "Prepnuté na {target}" + } + } }, "clients": { "tabBasics": "Základné údaje", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index b076b4a48..0310abbf6 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Peer {n} Yapılandırması" }, "sniffingDestOverride": "Hedef geçersiz kılma", - "advancedTitle": "Gelişmiş Ayarlar" + "advancedTitle": "Gelişmiş Ayarlar", + "realityWatch": { + "title": "REALITY'yi çalışır tut", + "savedWithInbound": "Bunlar inbound ile birlikte kaydedilir.", + "hint": "Bu sunucu hedefi her 10 dakikada bir denetler. Art arda {limit} başarısız denetimden sonra inbound, aynı denetimi ve geçici bir Xray üzerinden gerçek bir REALITY bağlantısını geçen ilk yedeğe geçer. Yalnızca hedef ve SNI değişir; istemciler yeni SNI'yı bir sonraki abonelik güncellemesinde alır.", + "onNode": "Bu inbound bir düğümde çalışıyor, bu yüzden bu sunucu hedefini denetleyemez veya değiştiremez.", + "status": "Durum", + "notChecked": "henüz denetlenmedi", + "failing": "başarısız ({fails}/{limit})", + "working": "çalışıyor", + "auto": "Otomatik değiştir", + "spares": "Yedek hedefler", + "noSpares": "Henüz yedek yok: Yedek bul ile ekleyin", + "realTest": "Gerçek test", + "testOk": "çalışıyor", + "testFailed": "çalışmıyor", + "test": "Test et", + "testAll": "Hepsini test et", + "switchNow": "Şimdi buna geç", + "findSpares": "Yedek bul", + "save": "Yedekleri kaydet", + "history": "Geçmiş", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} çalışmadı ve hiçbir yedek çalışmadı", + "toasts": { + "saved": "Yedekler kaydedildi", + "failed": "Yedekler kaydedilemedi", + "switchFailed": "Geçilemedi: hedef denetimi veya gerçek REALITY testini geçemedi", + "switched": "{target} hedefine geçildi" + } + } }, "clients": { "tabBasics": "Temel", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 8bd3b8932..6fe06bc19 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Конфіг Peer {n}" }, "sniffingDestOverride": "Перевизначення призначення", - "advancedTitle": "Додаткові налаштування" + "advancedTitle": "Додаткові налаштування", + "realityWatch": { + "title": "Підтримувати REALITY у роботі", + "savedWithInbound": "Вони зберігаються разом з інбаундом.", + "hint": "Кожні 10 хвилин цей сервер перевіряє ціль. Після {limit} невдалих перевірок поспіль інбаунд переходить на першу запасну ціль, що пройшла ту саму перевірку та справжнє підключення REALITY через тимчасовий Xray. Змінюються лише ціль і SNI; клієнти отримають новий SNI під час наступного оновлення підписки.", + "onNode": "Цей інбаунд працює на ноді, тому цей сервер не може перевірити чи перемкнути його ціль.", + "status": "Стан", + "notChecked": "ще не перевірено", + "failing": "збій ({fails} з {limit})", + "working": "працює", + "auto": "Замінювати автоматично", + "spares": "Запасні цілі", + "noSpares": "Запасних поки немає: додайте через «Знайти запасні»", + "realTest": "Справжній тест", + "testOk": "працює", + "testFailed": "не працює", + "test": "Тест", + "testAll": "Перевірити всі", + "switchNow": "Перемкнути зараз", + "findSpares": "Знайти запасні", + "save": "Зберегти запасні", + "history": "Історія", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} перестав працювати, і жодна запасна не підійшла", + "toasts": { + "saved": "Запасні збережено", + "failed": "Не вдалося зберегти запасні", + "switchFailed": "Не вдалося перемкнути: ціль не пройшла перевірку або справжній тест REALITY", + "switched": "Перемкнено на {target}" + } + } }, "clients": { "tabBasics": "Основні", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index ad27f7f5b..14f155494 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Cấu hình Peer {n}" }, "sniffingDestOverride": "Ghi đè đích", - "advancedTitle": "Cài đặt nâng cao" + "advancedTitle": "Cài đặt nâng cao", + "realityWatch": { + "title": "Giữ REALITY hoạt động", + "savedWithInbound": "Chúng được lưu cùng với inbound.", + "hint": "Cứ 10 phút máy chủ này kiểm tra mục tiêu. Sau {limit} lần kiểm tra thất bại liên tiếp, inbound chuyển sang mục tiêu dự phòng đầu tiên vượt qua cùng phép kiểm tra và một kết nối REALITY thật qua một Xray tạm thời. Chỉ mục tiêu và SNI thay đổi; client nhận SNI mới ở lần cập nhật gói đăng ký kế tiếp.", + "onNode": "Inbound này chạy trên một node nên máy chủ này không thể kiểm tra hoặc chuyển mục tiêu của nó.", + "status": "Trạng thái", + "notChecked": "chưa kiểm tra", + "failing": "lỗi ({fails}/{limit})", + "working": "hoạt động", + "auto": "Tự động thay thế", + "spares": "Mục tiêu dự phòng", + "noSpares": "Chưa có dự phòng: thêm bằng Tìm dự phòng", + "realTest": "Kiểm tra thật", + "testOk": "hoạt động", + "testFailed": "lỗi", + "test": "Kiểm tra", + "testAll": "Kiểm tra tất cả", + "switchNow": "Chuyển sang ngay", + "findSpares": "Tìm dự phòng", + "save": "Lưu dự phòng", + "history": "Lịch sử", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} lỗi và không dự phòng nào hoạt động", + "toasts": { + "saved": "Đã lưu dự phòng", + "failed": "Không lưu được dự phòng", + "switchFailed": "Không chuyển được: mục tiêu không qua phép kiểm tra hoặc kiểm tra REALITY thật", + "switched": "Đã chuyển sang {target}" + } + } }, "clients": { "tabBasics": "Cơ bản", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 782ddfb6b..6fd231da0 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Peer {n} 配置" }, "sniffingDestOverride": "目标覆盖", - "advancedTitle": "高级设置" + "advancedTitle": "高级设置", + "realityWatch": { + "title": "保持 REALITY 可用", + "savedWithInbound": "它们会随入站一起保存。", + "hint": "本服务器每 10 分钟检查一次目标。连续 {limit} 次检查失败后,入站会切换到第一个通过同样检查并经临时 Xray 完成真实 REALITY 连接的备用目标。只改变目标和 SNI;客户端会在下次更新订阅时获得新的 SNI。", + "onNode": "此入站运行在节点上,本服务器无法检查或切换其目标。", + "status": "状态", + "notChecked": "尚未检查", + "failing": "失败({fails}/{limit})", + "working": "正常", + "auto": "自动替换", + "spares": "备用目标", + "noSpares": "还没有备用目标:用“查找备用”添加", + "realTest": "真实测试", + "testOk": "可用", + "testFailed": "不可用", + "test": "测试", + "testAll": "全部测试", + "switchNow": "立即切换到此", + "findSpares": "查找备用", + "save": "保存备用", + "history": "历史", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} 失效,且没有可用的备用目标", + "toasts": { + "saved": "备用目标已保存", + "failed": "无法保存备用目标", + "switchFailed": "无法切换:目标未通过检查或真实 REALITY 测试", + "switched": "已切换到 {target}" + } + } }, "clients": { "tabBasics": "基本", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 1c122b12d..c5026572b 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -810,7 +810,37 @@ "peerNumberConfig": "Peer {n} 設定" }, "sniffingDestOverride": "目標覆寫", - "advancedTitle": "進階設定" + "advancedTitle": "進階設定", + "realityWatch": { + "title": "保持 REALITY 可用", + "savedWithInbound": "它們會隨入站一起儲存。", + "hint": "本伺服器每 10 分鐘檢查一次目標。連續 {limit} 次檢查失敗後,入站會切換到第一個通過同樣檢查並經臨時 Xray 完成真實 REALITY 連線的備用目標。只改變目標與 SNI;用戶端會在下次更新訂閱時取得新的 SNI。", + "onNode": "此入站執行在節點上,本伺服器無法檢查或切換其目標。", + "status": "狀態", + "notChecked": "尚未檢查", + "failing": "失敗({fails}/{limit})", + "working": "正常", + "auto": "自動替換", + "spares": "備用目標", + "noSpares": "還沒有備用目標:用「尋找備用」新增", + "realTest": "真實測試", + "testOk": "可用", + "testFailed": "不可用", + "test": "測試", + "testAll": "全部測試", + "switchNow": "立即切換到此", + "findSpares": "尋找備用", + "save": "儲存備用", + "history": "歷史", + "eventSwitched": "{from} → {to}", + "eventNoSpare": "{from} 失效,且沒有可用的備用目標", + "toasts": { + "saved": "備用目標已儲存", + "failed": "無法儲存備用目標", + "switchFailed": "無法切換:目標未通過檢查或真實 REALITY 測試", + "switched": "已切換到 {target}" + } + } }, "clients": { "tabBasics": "基本", diff --git a/internal/web/web.go b/internal/web/web.go index b3299d3b9..9b5bafb07 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -310,6 +310,7 @@ func (s *Server) initRouter() (*gin.Engine, error) { // counters. const ( cadenceXrayRunning = "@every 1s" + cadenceRealityWatch = "@every 10m" cadenceXrayRestart = "@every 30s" cadenceXrayTraffic = "@every 5s" cadenceMtproto = "@every 10s" @@ -387,6 +388,7 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) { _, _ = s.cron.AddJob("@daily", job.NewClearLogsJob()) _, _ = s.cron.AddJob(cadenceXrayLogPrune, job.NewPruneXrayLogsJob()) _, _ = s.cron.AddJob("@hourly", job.NewWarpIpJob()) + _, _ = s.cron.AddJob(cadenceRealityWatch, job.NewRealityWatchJob()) // Inbound traffic reset jobs // Run every hour diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index eed5d1861..c34562288 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -119,6 +119,9 @@ func run(root, outDir string) error { "NodeView", "ProbeResultUI", "RealityScanResult", + "RealityWatchEntry", + "RealityWatchEvent", + "RealityWatchStatus", "GeodataTokenIssue", "AmneziaWGLogs", "PeerActivity", From 05e8f172685e82d50c46c67ffd04183fa10c813e Mon Sep 17 00:00:00 2001 From: Mr Cortex <106546449+themrcortex@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:04:29 +0330 Subject: [PATCH 081/130] feat(dashboard): choose the time range of the overview charts (#7139) Every overview chart gets the same range selector: 2m, 5m, 30m, 1h, 6h and 12h. The 2m default is the live trend the page already drew, one point per status poll, so nothing changes until a longer range is picked. A longer range is read from the server's stored rollups through the new GET /panel/api/server/overviewHistory/:bucket, which returns all eight overview series in one response, and is refreshed once per point, at most once a minute. A metric the host cannot report stays empty in a ranged window instead of drawing zeros, a range change clears the chart rather than showing the old range under the new label, and avg/peak labels keep their number order in RTL locales. --- docs/content/docs/en/operations/meta.json | 1 + .../docs/en/operations/system-monitoring.mdx | 47 +++++++ docs/content/docs/en/reference/api/server.mdx | 37 ++++-- docs/content/docs/fa/operations/meta.json | 1 + .../docs/fa/operations/system-monitoring.mdx | 47 +++++++ docs/public/openapi.json | 57 +++++++-- frontend/public/openapi.json | 57 +++++++-- frontend/src/pages/api-docs/endpoints.ts | 30 +++-- frontend/src/pages/index/ConnectionsCard.tsx | 11 +- frontend/src/pages/index/IndexPage.css | 29 ++++- frontend/src/pages/index/IndexPage.tsx | 65 ++++++++-- .../src/pages/index/OverviewRangeSelect.tsx | 34 +++++ frontend/src/pages/index/ThroughputCard.tsx | 11 +- frontend/src/pages/index/VitalTile.tsx | 19 ++- .../src/pages/index/useOverviewHistory.ts | 105 +++++++++++++++- .../src/test/network-traffic-status.test.tsx | 2 + .../src/test/overview-range-select.test.tsx | 17 +++ .../src/test/overview-ranged-history.test.tsx | 116 ++++++++++++++++++ frontend/src/test/vital-tile-label.test.tsx | 33 +++++ internal/web/controller/api.go | 1 + internal/web/controller/server.go | 9 ++ internal/web/service/server.go | 13 ++ .../service/server_overview_history_test.go | 33 +++++ 23 files changed, 720 insertions(+), 55 deletions(-) create mode 100644 docs/content/docs/en/operations/system-monitoring.mdx create mode 100644 docs/content/docs/fa/operations/system-monitoring.mdx create mode 100644 frontend/src/pages/index/OverviewRangeSelect.tsx create mode 100644 frontend/src/test/overview-range-select.test.tsx create mode 100644 frontend/src/test/overview-ranged-history.test.tsx create mode 100644 internal/web/service/server_overview_history_test.go diff --git a/docs/content/docs/en/operations/meta.json b/docs/content/docs/en/operations/meta.json index c3b7c348a..230047510 100644 --- a/docs/content/docs/en/operations/meta.json +++ b/docs/content/docs/en/operations/meta.json @@ -3,6 +3,7 @@ "icon": "ServerCog", "pages": [ "reverse-proxy", + "system-monitoring", "multi-node", "outbounds-routing", "backup-restore", diff --git a/docs/content/docs/en/operations/system-monitoring.mdx b/docs/content/docs/en/operations/system-monitoring.mdx new file mode 100644 index 000000000..d80b2791f --- /dev/null +++ b/docs/content/docs/en/operations/system-monitoring.mdx @@ -0,0 +1,47 @@ +--- +title: System monitoring +description: Read the overview charts, choose a time window, and understand how 3x-ui stores system history. +icon: ChartNoAxesCombined +--- + +The overview page combines a current server snapshot with short time-series charts. It shows CPU, memory, swap, storage, network throughput, and open TCP/UDP connections. Open **System history** for additional metrics such as packets, disk I/O, load averages, and Xray online clients. + +## Choose a chart window + +Each overview chart has the same time-range selector in its upper-right corner. The default is **2m**. The choices are **2m**, **5m**, **30m**, **1h**, **6h**, and **12h**. Changing any selector changes the window on every overview chart. + +The number of chart points stays capped at 60. Short windows use finer samples; longer windows use averages. At **2m** the charts are live: every status poll, once every 2 seconds, adds a point. A longer window is read from the server's stored history and refreshed once per point, at most once a minute. + +The **System history** dialog has per-metric tabs and longer windows: **2m**, **1h**, **3h**, **6h**, **12h**, **24h**, **2d**, and **7d**. It refreshes only the active metric, and slows its polling as the selected window grows. + +## Metrics and scope + +The overview charts show: + +- CPU use, memory use, swap use, and disk use as percentages. +- Network upload and download throughput in bytes per second. +- Current TCP and UDP connection counts. + +System history adds packet rates, disk read/write rates, Xray online clients, and the 1, 5, and 15 minute load averages. CPU and swap follow the panel's resource scope when it runs inside a container; unavailable scoped metrics are left empty instead of being filled with host values. + +Chart summaries show the average and peak inside the selected window. For Persian labels, the text and numeric value are isolated separately so right-to-left text direction does not reorder the number or percent sign. + +## Collection and retention + +The panel samples server status every **2 seconds**. Each metric is written into three fixed-size rollup tiers: + +| Resolution | Retained window | Use | +| --- | --- | --- | +| 2 seconds | 1 hour | Recent charts | +| 1 minute | 48 hours | Medium windows | +| 10 minutes | 7 days | Long history | + +Samples are averaged as they move through each tier. A series retains about 5,700 points (roughly 90 KiB before serialization), regardless of uptime. The overview endpoint returns up to 60 points per metric in one response, avoiding a request for each individual chart. + +System history is saved to `system_metrics.gob` in the panel's database directory once a minute and again during shutdown. It is restored at startup. A new installation begins collecting history when the panel starts; it cannot reconstruct metrics from before collection was enabled. + +## API + +For a window longer than **2m** the overview requests `GET /panel/api/server/overviewHistory/{bucket}`. `bucket` is the number of seconds one point covers: `5`, `30`, `60`, `360` and `720` give the 5 minute through 12 hour windows. The response contains up to 60 `{ "t": unixSeconds, "v": value }` points for each overview metric. + +The system history dialog requests `GET /panel/api/server/history/{metric}/{bucket}` for the active metric. It uses the same `{t, v}` point format and supports the longer bucket values documented in the [Server API reference](/docs/reference/api/server). diff --git a/docs/content/docs/en/reference/api/server.mdx b/docs/content/docs/en/reference/api/server.mdx index 0ac548f28..9738ba947 100644 --- a/docs/content/docs/en/reference/api/server.mdx +++ b/docs/content/docs/en/reference/api/server.mdx @@ -33,18 +33,24 @@ _openapi: data with a uniform {t, v} shape.' url: '#legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape' - depth: 2 - title: Aggregated time-series for one metric. Returns an array of {t, v} samples - covering the last ~6 hours. - url: '#aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours' + title: Aggregated time-series for one system metric. Returns up to 60 {t, v} + samples; supported bucket sizes cover windows from 2 minutes up to 7 + days. + url: '#aggregated-time-series-for-one-system-metric-returns-up-to-60-t-v-samples-supported-bucket-sizes-cover-windows-from-2-minutes-up-to-7-days' + - depth: 2 + title: 'Aggregated history for all overview charts in one response: up to 60 {t, + v} samples for each of cpu, mem, swap, diskUsage, netUp, netDown, + tcpCount and udpCount.' + url: '#aggregated-history-for-all-overview-charts-in-one-response-up-to-60-t-v-samples-for-each-of-cpu-mem-swap-diskusage-netup-netdown-tcpcount-and-udpcount' - depth: 2 title: Xray runtime metrics state — whether the xray config has a `metrics` block, which expvar keys are flowing, and the current snapshot values for each. Returns an empty state when metrics are not configured. url: '#xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured' - depth: 2 - title: Time-series history for one Xray runtime metric over the last ~6 hours. - Same {t, v} shape as /history/:metric/:bucket. - url: '#time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket' + title: Aggregated history for one Xray runtime metric. Returns up to 60 {t, v} + samples for bucket windows up to 7 days. + url: '#aggregated-history-for-one-xray-runtime-metric-returns-up-to-60-t-v-samples-for-bucket-windows-up-to-7-days' - depth: 2 title: Latest snapshot from the Xray observatory — per-outbound latency, health status, and last-probe time. Only populated when the Xray config has an @@ -207,16 +213,21 @@ _openapi: - content: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead — same data with a uniform {t, v} shape.' id: legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape - - content: Aggregated time-series for one metric. Returns an array of {t, v} - samples covering the last ~6 hours. - id: aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours + - content: Aggregated time-series for one system metric. Returns up to 60 {t, v} + samples; supported bucket sizes cover windows from 2 minutes up to 7 + days. + id: aggregated-time-series-for-one-system-metric-returns-up-to-60-t-v-samples-supported-bucket-sizes-cover-windows-from-2-minutes-up-to-7-days + - content: 'Aggregated history for all overview charts in one response: up to 60 + {t, v} samples for each of cpu, mem, swap, diskUsage, netUp, netDown, + tcpCount and udpCount.' + id: aggregated-history-for-all-overview-charts-in-one-response-up-to-60-t-v-samples-for-each-of-cpu-mem-swap-diskusage-netup-netdown-tcpcount-and-udpcount - content: Xray runtime metrics state — whether the xray config has a `metrics` block, which expvar keys are flowing, and the current snapshot values for each. Returns an empty state when metrics are not configured. id: xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured - - content: Time-series history for one Xray runtime metric over the last ~6 hours. - Same {t, v} shape as /history/:metric/:bucket. - id: time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket + - content: Aggregated history for one Xray runtime metric. Returns up to 60 {t, v} + samples for bucket windows up to 7 days. + id: aggregated-history-for-one-xray-runtime-metric-returns-up-to-60-t-v-samples-for-bucket-windows-up-to-7-days - content: Latest snapshot from the Xray observatory — per-outbound latency, health status, and last-probe time. Only populated when the Xray config has an observatory configured. @@ -334,7 +345,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/content/docs/fa/operations/meta.json b/docs/content/docs/fa/operations/meta.json index 000badb34..e1becfb6b 100644 --- a/docs/content/docs/fa/operations/meta.json +++ b/docs/content/docs/fa/operations/meta.json @@ -3,6 +3,7 @@ "icon": "ServerCog", "pages": [ "reverse-proxy", + "system-monitoring", "multi-node", "outbounds-routing", "backup-restore", diff --git a/docs/content/docs/fa/operations/system-monitoring.mdx b/docs/content/docs/fa/operations/system-monitoring.mdx new file mode 100644 index 000000000..2082e9c59 --- /dev/null +++ b/docs/content/docs/fa/operations/system-monitoring.mdx @@ -0,0 +1,47 @@ +--- +title: پایش سیستم +description: نمودارهای نمای کلی، انتخاب بازهٔ زمانی و نحوهٔ نگهداری تاریخچهٔ سیستم در 3x-ui. +icon: ChartNoAxesCombined +--- + +صفحهٔ نمای کلی، وضعیت فعلی سرور را همراه نمودارهای زمانی نشان می‌دهد: پردازنده، حافظه، سوآپ، فضای ذخیره‌سازی، نرخ ترافیک شبکه و اتصال‌های TCP/UDP. برای شاخص‌های بیشتر مثل نرخ بسته‌ها، ورودی/خروجی دیسک، میانگین بار سیستم و کلاینت‌های آنلاین Xray، پنجرهٔ **تاریخچهٔ سیستم** را باز کنید. + +## انتخاب بازهٔ نمودار + +هر نمودار نمای کلی یک سلکت بازهٔ زمانی در گوشهٔ بالای سمت راست دارد. مقدار پیش‌فرض **2m** است. گزینه‌ها **2m**، **5m**، **30m**، **1h**، **6h** و **12h** هستند. تغییر بازه در هر نمودار، بازهٔ همهٔ نمودارهای نمای کلی را تغییر می‌دهد. + +تعداد نقطه‌های نمودار حداکثر ۶۰ نقطه است. بازه‌های کوتاه‌تر از نمونه‌های دقیق‌تر و بازه‌های بلندتر از میانگین نمونه‌ها استفاده می‌کنند. در بازهٔ **2m** نمودارها زنده‌اند: هر بار دریافت وضعیت، یعنی هر ۲ ثانیه، یک نقطه اضافه می‌کند. بازه‌های بلندتر از تاریخچهٔ ذخیره‌شده در سرور خوانده می‌شوند و به‌ازای هر نقطه یک بار، و حداکثر دقیقه‌ای یک بار، به‌روزرسانی می‌شوند. + +پنجرهٔ **تاریخچهٔ سیستم** برای هر شاخص زبانه‌ای جدا دارد و بازه‌های بلندتر **2m**، **1h**، **3h**، **6h**، **12h**، **24h**، **2d** و **7d** را ارائه می‌کند. فقط شاخص فعال به‌روزرسانی می‌شود و با بزرگ‌تر شدن بازه، فاصلهٔ دریافت اطلاعات بیشتر می‌شود. + +## شاخص‌ها و محدودهٔ منابع + +نمودارهای نمای کلی این موارد را نشان می‌دهند: + +- مصرف پردازنده، حافظه، سوآپ و دیسک به‌صورت درصد. +- نرخ ارسال و دریافت شبکه به بایت بر ثانیه. +- تعداد فعلی اتصال‌های TCP و UDP. + +تاریخچهٔ سیستم نرخ بسته‌ها، نرخ خواندن/نوشتن دیسک، کلاینت‌های آنلاین Xray و میانگین بار ۱، ۵ و ۱۵ دقیقه را هم دارد. وقتی پنل داخل کانتینر اجرا می‌شود، مصرف پردازنده و سوآپ از محدودهٔ منابع همان کانتینر گرفته می‌شوند. اگر این شاخص‌ها در دسترس نباشند، نمودار خالی می‌ماند و از دادهٔ میزبان به‌جای آن‌ها استفاده نمی‌شود. + +خلاصهٔ هر نمودار، میانگین و بیشینهٔ مقدار را در بازهٔ انتخاب‌شده نشان می‌دهد. برچسب و مقدار عددی فارسی جدا از هم نمایش داده می‌شوند تا جهت راست‌به‌چپ، ترتیب رقم‌ها و علامت درصد را جابه‌جا نکند. + +## جمع‌آوری و نگهداری داده + +پنل هر **۲ ثانیه** یک نمونه از وضعیت سرور می‌گیرد. هر شاخص در سه سطح تجمیع با اندازهٔ ثابت نگهداری می‌شود: + +| دقت داده | مدت نگهداری | کاربرد | +| --- | --- | --- | +| ۲ ثانیه | ۱ ساعت | نمودارهای نزدیک به زمان حال | +| ۱ دقیقه | ۴۸ ساعت | بازه‌های میان‌مدت | +| ۱۰ دقیقه | ۷ روز | تاریخچهٔ بلندمدت | + +هنگام انتقال داده به سطح بعدی، نمونه‌ها با هم میانگین‌گیری می‌شوند. هر شاخص حدود ۵٬۷۰۰ نقطه (نزدیک به ۹۰ کیلوبایت پیش از سریال‌سازی) نگه می‌دارد؛ بنابراین مصرف حافظه با زمان کارکرد سرور رشد نامحدود ندارد. یک درخواست، حداکثر ۶۰ نقطه از همهٔ شاخص‌های نمای کلی را می‌گیرد تا برای هر نمودار درخواست جداگانه ارسال نشود. + +تاریخچهٔ سیستم هر دقیقه در فایل `system_metrics.gob` کنار داده‌های پایگاه‌دادهٔ پنل ذخیره می‌شود و هنگام خاموش شدن پنل نیز ذخیرهٔ نهایی انجام می‌شود. داده‌ها هنگام راه‌اندازی بعدی بازیابی می‌شوند. نصب تازه از زمان شروع پنل داده جمع می‌کند و نمی‌تواند شاخص‌های پیش از فعال شدن این جمع‌آوری را بازسازی کند. + +## API + +نمای کلی برای بازه‌های بلندتر از **2m** از `GET /panel/api/server/overviewHistory/{bucket}` استفاده می‌کند. مقدار `bucket` تعداد ثانیه‌هایی است که هر نقطه پوشش می‌دهد: مقادیر `5`، `30`، `60`، `360` و `720` بازه‌های ۵ دقیقه تا ۱۲ ساعت را می‌دهند. پاسخ برای هر شاخص نمای کلی حداکثر ۶۰ نقطه با قالب `{ "t": unixSeconds, "v": value }` دارد. + +پنجرهٔ تاریخچهٔ سیستم برای شاخص فعال، `GET /panel/api/server/history/{metric}/{bucket}` را فراخوانی می‌کند. قالب هر نقطه همان `{t, v}` است؛ مقدارهای بزرگ‌تر `bucket` در [مرجع API سرور](/docs/reference/api/server) آمده‌اند. diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 733b1e2b4..d65258604 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -7255,7 +7255,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } @@ -7289,14 +7289,14 @@ "tags": [ "Server" ], - "summary": "Aggregated time-series for one metric. Returns an array of {t, v} samples covering the last ~6 hours.", + "summary": "Aggregated time-series for one system metric. Returns up to 60 {t, v} samples; supported bucket sizes cover windows from 2 minutes up to 7 days.", "operationId": "get_panel_api_server_history_metric_bucket", "parameters": [ { "name": "metric", "in": "path", "required": true, - "description": "cpu | mem | netUp | netDown | online | load1 | load5 | load15.", + "description": "cpu | mem | swap | netUp | netDown | pktUp | pktDown | diskRead | diskWrite | diskUsage | tcpCount | udpCount | online | load1 | load5 | load15.", "schema": { "type": "string" } @@ -7305,7 +7305,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } @@ -7347,6 +7347,47 @@ } } }, + "/panel/api/server/overviewHistory/{bucket}": { + "get": { + "tags": [ + "Server" + ], + "summary": "Aggregated history for all overview charts in one response: up to 60 {t, v} samples for each of cpu, mem, swap, diskUsage, netUp, netDown, tcpCount and udpCount.", + "operationId": "get_panel_api_server_overviewHistory_bucket", + "parameters": [ + { + "name": "bucket", + "in": "path", + "required": true, + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + } + } + } + } + } + } + }, "/panel/api/server/xrayMetricsState": { "get": { "tags": [ @@ -7382,7 +7423,7 @@ "tags": [ "Server" ], - "summary": "Time-series history for one Xray runtime metric over the last ~6 hours. Same {t, v} shape as /history/:metric/:bucket.", + "summary": "Aggregated history for one Xray runtime metric. Returns up to 60 {t, v} samples for bucket windows up to 7 days.", "operationId": "get_panel_api_server_xrayMetricsHistory_metric_bucket", "parameters": [ { @@ -7398,7 +7439,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } @@ -7478,7 +7519,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } @@ -13669,7 +13710,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 733b1e2b4..d65258604 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -7255,7 +7255,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } @@ -7289,14 +7289,14 @@ "tags": [ "Server" ], - "summary": "Aggregated time-series for one metric. Returns an array of {t, v} samples covering the last ~6 hours.", + "summary": "Aggregated time-series for one system metric. Returns up to 60 {t, v} samples; supported bucket sizes cover windows from 2 minutes up to 7 days.", "operationId": "get_panel_api_server_history_metric_bucket", "parameters": [ { "name": "metric", "in": "path", "required": true, - "description": "cpu | mem | netUp | netDown | online | load1 | load5 | load15.", + "description": "cpu | mem | swap | netUp | netDown | pktUp | pktDown | diskRead | diskWrite | diskUsage | tcpCount | udpCount | online | load1 | load5 | load15.", "schema": { "type": "string" } @@ -7305,7 +7305,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } @@ -7347,6 +7347,47 @@ } } }, + "/panel/api/server/overviewHistory/{bucket}": { + "get": { + "tags": [ + "Server" + ], + "summary": "Aggregated history for all overview charts in one response: up to 60 {t, v} samples for each of cpu, mem, swap, diskUsage, netUp, netDown, tcpCount and udpCount.", + "operationId": "get_panel_api_server_overviewHistory_bucket", + "parameters": [ + { + "name": "bucket", + "in": "path", + "required": true, + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + } + } + } + } + } + } + }, "/panel/api/server/xrayMetricsState": { "get": { "tags": [ @@ -7382,7 +7423,7 @@ "tags": [ "Server" ], - "summary": "Time-series history for one Xray runtime metric over the last ~6 hours. Same {t, v} shape as /history/:metric/:bucket.", + "summary": "Aggregated history for one Xray runtime metric. Returns up to 60 {t, v} samples for bucket windows up to 7 days.", "operationId": "get_panel_api_server_xrayMetricsHistory_metric_bucket", "parameters": [ { @@ -7398,7 +7439,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } @@ -7478,7 +7519,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } @@ -13669,7 +13710,7 @@ "name": "bucket", "in": "path", "required": true, - "description": "Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.", + "description": "Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.", "schema": { "type": "integer" } diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 9b0f943b3..e23b82b13 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -482,7 +482,7 @@ export const sections: readonly Section[] = [ name: 'bucket', in: 'path', type: 'number', - desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.', + desc: 'Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.', }, ], }, @@ -490,24 +490,38 @@ export const sections: readonly Section[] = [ method: 'GET', path: '/panel/api/server/history/:metric/:bucket', summary: - 'Aggregated time-series for one metric. Returns an array of {t, v} samples covering the last ~6 hours.', + 'Aggregated time-series for one system metric. Returns up to 60 {t, v} samples; supported bucket sizes cover windows from 2 minutes up to 7 days.', params: [ { name: 'metric', in: 'path', type: 'string', - desc: 'cpu | mem | netUp | netDown | online | load1 | load5 | load15.', + desc: 'cpu | mem | swap | netUp | netDown | pktUp | pktDown | diskRead | diskWrite | diskUsage | tcpCount | udpCount | online | load1 | load5 | load15.', }, { name: 'bucket', in: 'path', type: 'number', - desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.', + desc: 'Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.', }, ], response: '{\n "success": true,\n "obj": [\n { "t": 1700000000, "v": 12.5 },\n { "t": 1700000002, "v": 13.1 }\n ]\n}', }, + { + method: 'GET', + path: '/panel/api/server/overviewHistory/:bucket', + summary: + 'Aggregated history for all overview charts in one response: up to 60 {t, v} samples for each of cpu, mem, swap, diskUsage, netUp, netDown, tcpCount and udpCount.', + params: [ + { + name: 'bucket', + in: 'path', + type: 'number', + desc: 'Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.', + }, + ], + }, { method: 'GET', path: '/panel/api/server/xrayMetricsState', @@ -518,7 +532,7 @@ export const sections: readonly Section[] = [ method: 'GET', path: '/panel/api/server/xrayMetricsHistory/:metric/:bucket', summary: - 'Time-series history for one Xray runtime metric over the last ~6 hours. Same {t, v} shape as /history/:metric/:bucket.', + 'Aggregated history for one Xray runtime metric. Returns up to 60 {t, v} samples for bucket windows up to 7 days.', params: [ { name: 'metric', @@ -530,7 +544,7 @@ export const sections: readonly Section[] = [ name: 'bucket', in: 'path', type: 'number', - desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.', + desc: 'Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.', }, ], }, @@ -556,7 +570,7 @@ export const sections: readonly Section[] = [ name: 'bucket', in: 'path', type: 'number', - desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.', + desc: 'Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.', }, ], }, @@ -2040,7 +2054,7 @@ export const sections: readonly Section[] = [ name: 'bucket', in: 'path', type: 'number', - desc: 'Bucket size in seconds. Allowed: 2, 30, 60, 120, 180, 300.', + desc: 'Bucket size in seconds. Allowed: 2, 5, 30, 60, 180, 360, 720, 1440, 2880, 10080.', }, ], }, diff --git a/frontend/src/pages/index/ConnectionsCard.tsx b/frontend/src/pages/index/ConnectionsCard.tsx index a127fb2f6..128e9b4ab 100644 --- a/frontend/src/pages/index/ConnectionsCard.tsx +++ b/frontend/src/pages/index/ConnectionsCard.tsx @@ -4,6 +4,8 @@ import { Card, theme } from 'antd'; import { Sparkline } from '@/components/viz'; import type { Status } from '@/models/status'; +import OverviewRangeSelect from './OverviewRangeSelect'; +import type { OverviewRange } from './OverviewRangeSelect'; interface ConnectionsCardProps { status: Status; @@ -11,6 +13,8 @@ interface ConnectionsCardProps { udp: number[]; labels: string[]; isMobile: boolean; + range: OverviewRange; + onRangeChange: (range: OverviewRange) => void; } export default function ConnectionsCard({ @@ -19,6 +23,8 @@ export default function ConnectionsCard({ udp, labels, isMobile, + range, + onRangeChange, }: ConnectionsCardProps) { const { t } = useTranslation(); const { token } = theme.useToken(); @@ -34,7 +40,7 @@ export default function ConnectionsCard({ ); return ( - +
{t('pages.index.connectionCount')}
@@ -43,6 +49,9 @@ export default function ConnectionsCard({
+
+ +
diff --git a/frontend/src/pages/index/IndexPage.css b/frontend/src/pages/index/IndexPage.css index 8eb56ebcc..22f689698 100644 --- a/frontend/src/pages/index/IndexPage.css +++ b/frontend/src/pages/index/IndexPage.css @@ -213,14 +213,19 @@ } .ov-tile { + position: relative; overflow: hidden; } +.ov-wide-card { + position: relative; +} + .ov-tile-head { display: flex; align-items: center; gap: 8px; - padding: 14px var(--ov-pad) 0; + padding: 14px calc(var(--ov-pad) + 82px + 12px) 0 var(--ov-pad); color: var(--ov-accent); } @@ -267,10 +272,30 @@ color: var(--ov-faint); } +.ov-tile-foot > span { + display: inline-flex; + align-items: baseline; + gap: 4px; + white-space: nowrap; + unicode-bidi: plaintext; +} + .ov-tile-chart { margin-top: 6px; } +.ov-range-toolbar { + position: absolute; + z-index: 1; + top: 14px; + right: var(--ov-pad); + display: flex; +} + +.ov-range-select { + width: 82px; +} + /* — throughput + connections — */ .ov-mid { @@ -290,7 +315,7 @@ align-items: flex-start; flex-wrap: wrap; gap: 16px; - padding: var(--ov-pad) var(--ov-pad) 0; + padding: var(--ov-pad) calc(var(--ov-pad) + 82px + 12px) 0 var(--ov-pad); } .ov-wide-head-stack { diff --git a/frontend/src/pages/index/IndexPage.tsx b/frontend/src/pages/index/IndexPage.tsx index 01cee6f64..63fda3f39 100644 --- a/frontend/src/pages/index/IndexPage.tsx +++ b/frontend/src/pages/index/IndexPage.tsx @@ -30,6 +30,7 @@ import ThroughputCard from './ThroughputCard'; import ConnectionsCard from './ConnectionsCard'; import SystemStrip from './SystemStrip'; import { mean, peak, useOverviewHistory } from './useOverviewHistory'; +import type { OverviewRange } from './OverviewRangeSelect'; import type { PanelUpdateInfo } from './PanelUpdateModal'; const JsonEditor = lazy(() => import('@/components/form/JsonEditor')); const PanelUpdateModal = lazy(() => import('./PanelUpdateModal')); @@ -42,6 +43,15 @@ const AmneziaWGLogModal = lazy(() => import('./AmneziaWGLogModal')); const VersionModal = lazy(() => import('./VersionModal')); import './IndexPage.css'; +function metricFoot(label: string, value: string) { + return ( + <> + {label} + {value} + + ); +} + export default function IndexPage() { const { t } = useTranslation(); const { isDark, isUltra, antdThemeConfig } = useTheme(); @@ -76,7 +86,8 @@ export default function IndexPage() { const [loading, setLoading] = useState(false); const [loadingTip, setLoadingTip] = useState(t('loading')); - const history = useOverviewHistory(status, fetched && !fetchError); + const [historyRange, setHistoryRange] = useState(2); + const history = useOverviewHistory(status, fetched && !fetchError, historyRange); useEffect(() => { HttpUtil.post<{ accessLogEnable?: boolean; devChannelEnable?: boolean }>( @@ -238,10 +249,18 @@ export default function IndexPage() { ? `${status.logicalPro} vCPU` : `${CPUFormatter.cpuCoreFormat(status.cpuCores)} / ${status.logicalPro}T · ${CPUFormatter.cpuSpeedFormat(status.cpuSpeedMhz)}` } - footLeft={`${t('pages.index.avg')} ${mean(history.series.cpu).toFixed(0)}%`} - footRight={`${t('pages.index.peak')} ${peak(history.series.cpu).toFixed(0)}%`} + footLeft={metricFoot( + t('pages.index.avg'), + `${mean(history.series.cpu).toFixed(0)}%`, + )} + footRight={metricFoot( + t('pages.index.peak'), + `${peak(history.series.cpu).toFixed(0)}%`, + )} data={history.series.cpu} isMobile={isMobile} + range={historyRange} + onRangeChange={setHistoryRange} /> } @@ -249,10 +268,18 @@ export default function IndexPage() { percent={status.mem.percent} statusColor={status.mem.color} detail={`${SizeFormatter.sizeFormat(status.mem.current)} / ${SizeFormatter.sizeFormat(status.mem.total)}`} - footLeft={`${t('pages.index.avg')} ${mean(history.series.mem).toFixed(0)}%`} - footRight={`${t('pages.index.peak')} ${peak(history.series.mem).toFixed(0)}%`} + footLeft={metricFoot( + t('pages.index.avg'), + `${mean(history.series.mem).toFixed(0)}%`, + )} + footRight={metricFoot( + t('pages.index.peak'), + `${peak(history.series.mem).toFixed(0)}%`, + )} data={history.series.mem} isMobile={isMobile} + range={historyRange} + onRangeChange={setHistoryRange} /> } @@ -261,10 +288,18 @@ export default function IndexPage() { percent={status.swap.percent} statusColor={status.swap.color} detail={`${SizeFormatter.sizeFormat(status.swap.current)} / ${SizeFormatter.sizeFormat(status.swap.total)}`} - footLeft={`${t('pages.index.avg')} ${mean(history.series.swap).toFixed(1)}%`} - footRight={`${t('pages.index.peak')} ${peak(history.series.swap).toFixed(0)}%`} + footLeft={metricFoot( + t('pages.index.avg'), + `${mean(history.series.swap).toFixed(1)}%`, + )} + footRight={metricFoot( + t('pages.index.peak'), + `${peak(history.series.swap).toFixed(0)}%`, + )} data={history.series.swap} isMobile={isMobile} + range={historyRange} + onRangeChange={setHistoryRange} /> } @@ -272,10 +307,18 @@ export default function IndexPage() { percent={status.disk.percent} statusColor={status.disk.color} detail={`${SizeFormatter.sizeFormat(status.disk.current)} / ${SizeFormatter.sizeFormat(totalDisk)}`} - footLeft={`${t('pages.index.free')} ${SizeFormatter.sizeFormat(freeDisk)}`} - footRight={`${t('pages.index.avg')} ${mean(history.series.diskUsage).toFixed(1)}%`} + footLeft={metricFoot( + t('pages.index.free'), + SizeFormatter.sizeFormat(freeDisk), + )} + footRight={metricFoot( + t('pages.index.avg'), + `${mean(history.series.diskUsage).toFixed(1)}%`, + )} data={history.series.diskUsage} isMobile={isMobile} + range={historyRange} + onRangeChange={setHistoryRange} />
@@ -286,6 +329,8 @@ export default function IndexPage() { down={history.series.netDown} labels={history.labels} isMobile={isMobile} + range={historyRange} + onRangeChange={setHistoryRange} />
diff --git a/frontend/src/pages/index/OverviewRangeSelect.tsx b/frontend/src/pages/index/OverviewRangeSelect.tsx new file mode 100644 index 000000000..a9878cee2 --- /dev/null +++ b/frontend/src/pages/index/OverviewRangeSelect.tsx @@ -0,0 +1,34 @@ +import { Select } from 'antd'; +import { useTranslation } from 'react-i18next'; + +export const OVERVIEW_RANGES = [2, 5, 30, 60, 360, 720] as const; +export type OverviewRange = (typeof OVERVIEW_RANGES)[number]; + +interface OverviewRangeSelectProps { + value: OverviewRange; + onChange: (value: OverviewRange) => void; +} + +const OPTIONS = [ + { value: 2, label: '2m' }, + { value: 5, label: '5m' }, + { value: 30, label: '30m' }, + { value: 60, label: '1h' }, + { value: 360, label: '6h' }, + { value: 720, label: '12h' }, +]; + +export default function OverviewRangeSelect({ value, onChange }: OverviewRangeSelectProps) { + const { t } = useTranslation(); + + return ( +
+ + + + + + + + + + + +
{t('pages.clients.upload')} + {SizeFormatter.sizeFormat(history!.lifetimeUp)} + {t('pages.clients.download')} + {SizeFormatter.sizeFormat(history!.lifetimeDown)} +
+ {t('pages.clients.currentCycle')}: ↑{' '} + {SizeFormatter.sizeFormat(history!.currentUp)} / ↓{' '} + {SizeFormatter.sizeFormat(history!.currentDown)} +
+ + {history!.nodes.length > 0 && ( +
+ + {t('pages.clients.usageByNode')} + + + + )} + {history!.windows.length > 0 && ( +
+ + {t('pages.clients.pastCycles')} + +
+
+ + + )} + {history!.changes.length > 0 && ( +
+ + {t('pages.clients.changes')} + +
+
+ + + )} + + )} + + ); +} diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index e080c5c11..f4a55ffc1 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -524,12 +524,27 @@ export const EXAMPLES: Record = { } ] }, + "ClientChangeLog": { + "at": 1735689600000, + "email": "user1@example.com", + "field": "dataLimit", + "id": 14825, + "newValue": "21474836480", + "oldValue": "10737418240", + "source": "panel" + }, "ClientInbound": { "clientId": 0, "createdAt": 0, "flowOverride": "", "inboundId": 0 }, + "ClientNodeUsage": { + "down": 2097152, + "nodeId": 7, + "nodeName": "de-fra-1", + "up": 1048576 + }, "ClientPageResponse": { "filtered": 47, "groups": [ @@ -696,6 +711,50 @@ export const EXAMPLES: Record = { "up": 1048576, "uuid": "e18c9a96-71bf-48d4-933f-8b9a46d4290c" }, + "ClientTrafficWindow": { + "at": 1735689600000, + "down": 2097152, + "email": "user1@example.com", + "id": 14825, + "reason": "reset", + "up": 1048576 + }, + "ClientUsageHistory": { + "changes": [ + { + "at": 1735689600000, + "email": "user1@example.com", + "field": "dataLimit", + "id": 14825, + "newValue": "21474836480", + "oldValue": "10737418240", + "source": "panel" + } + ], + "currentDown": 2097152, + "currentUp": 1048576, + "email": "user1@example.com", + "lifetimeDown": 21474836480, + "lifetimeUp": 10737418240, + "nodes": [ + { + "down": 2097152, + "nodeId": 7, + "nodeName": "de-fra-1", + "up": 1048576 + } + ], + "windows": [ + { + "at": 1735689600000, + "down": 2097152, + "email": "user1@example.com", + "id": 14825, + "reason": "reset", + "up": 1048576 + } + ] + }, "ClientsSummary": { "active": 1850, "deactive": [ diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 8fb853833..5e9320253 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -2161,6 +2161,52 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientChangeLog": { + "description": "ClientChangeLog records one metadata change to a client: one row per\nchanged field, newest read first in the client's usage history.", + "properties": { + "at": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "field": { + "example": "dataLimit", + "type": "string" + }, + "id": { + "example": 14825, + "format": "int64", + "type": "integer" + }, + "newValue": { + "example": "21474836480", + "type": "string" + }, + "oldValue": { + "example": "10737418240", + "type": "string" + }, + "source": { + "description": "panel | tgbot | auto-renew", + "example": "panel", + "type": "string" + } + }, + "required": [ + "at", + "email", + "field", + "id", + "newValue", + "oldValue", + "source" + ], + "type": "object" + }, "ClientInbound": { "properties": { "clientId": { @@ -2185,6 +2231,36 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientNodeUsage": { + "description": "ClientNodeUsage is one node's counters for a client since its last reset.", + "properties": { + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "nodeId": { + "example": 7, + "type": "integer" + }, + "nodeName": { + "example": "de-fra-1", + "type": "string" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "nodeId", + "nodeName", + "up" + ], + "type": "object" + }, "ClientPageResponse": { "description": "ClientPageResponse is the shape returned by ListPaged. `Total` is the\nrow count in the DB; `Filtered` is the count after Search/Filter/Protocol\nwere applied, before pagination. The page contains at most PageSize items.\nSummary is computed across the full DB row set so dashboard counters\non the clients page stay stable as the user paginates/filters.", "properties": { @@ -2715,6 +2791,107 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientTrafficWindow": { + "description": "ClientTrafficWindow is one closed traffic window of a client: usage zeroed at a\nreset or an auto-renewal; lifetime = SUM(rows) + live counters.", + "properties": { + "at": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "id": { + "example": 14825, + "format": "int64", + "type": "integer" + }, + "reason": { + "description": "reset | renew | earlier", + "example": "reset", + "type": "string" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "at", + "down", + "email", + "id", + "reason", + "up" + ], + "type": "object" + }, + "ClientUsageHistory": { + "description": "ClientUsageHistory is what the client editor's history button shows.", + "properties": { + "changes": { + "items": { + "$ref": "#/components/schemas/ClientChangeLog" + }, + "type": "array" + }, + "currentDown": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "currentUp": { + "example": 1048576, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "lifetimeDown": { + "example": 21474836480, + "format": "int64", + "type": "integer" + }, + "lifetimeUp": { + "example": 10737418240, + "format": "int64", + "type": "integer" + }, + "nodes": { + "items": { + "$ref": "#/components/schemas/ClientNodeUsage" + }, + "type": "array" + }, + "windows": { + "items": { + "$ref": "#/components/schemas/ClientTrafficWindow" + }, + "type": "array" + } + }, + "required": [ + "changes", + "currentDown", + "currentUp", + "email", + "lifetimeDown", + "lifetimeUp", + "nodes", + "windows" + ], + "type": "object" + }, "ClientsSummary": { "description": "ClientsSummary collects per-bucket counts plus the matching email lists so\nthe clients page can render the dashboard stat cards and their hover\npopovers without shipping the full client array. The counters are exact;\nthe lists stop at clientSummaryEmailCap entries and only back the popovers.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 4174060b1..3d851811d 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -507,6 +507,16 @@ export interface Client { wireguardDevices?: WireguardDevice[]; } +export interface ClientChangeLog { + at: number; + email: string; + field: string; + id: number; + newValue: string; + oldValue: string; + source: string; +} + export interface ClientInbound { clientId: number; createdAt: number; @@ -514,6 +524,13 @@ export interface ClientInbound { inboundId: number; } +export interface ClientNodeUsage { + down: number; + nodeId: number; + nodeName: string; + up: number; +} + export interface ClientPageResponse { filtered: number; groups: string[]; @@ -628,6 +645,26 @@ export interface ClientTraffic { uuid: string; } +export interface ClientTrafficWindow { + at: number; + down: number; + email: string; + id: number; + reason: string; + up: number; +} + +export interface ClientUsageHistory { + changes: ClientChangeLog[]; + currentDown: number; + currentUp: number; + email: string; + lifetimeDown: number; + lifetimeUp: number; + nodes: ClientNodeUsage[]; + windows: ClientTrafficWindow[]; +} + export interface ClientsSummary { active: number; deactive: string[]; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index c2ffd90aa..02164dac4 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -527,6 +527,17 @@ export const ClientSchema = z.object({ }); export type Client = z.infer; +export const ClientChangeLogSchema = z.object({ + at: z.number().int(), + email: z.string(), + field: z.string(), + id: z.number().int(), + newValue: z.string(), + oldValue: z.string(), + source: z.string(), +}); +export type ClientChangeLog = z.infer; + export const ClientInboundSchema = z.object({ clientId: z.number().int(), createdAt: z.number().int(), @@ -535,6 +546,14 @@ export const ClientInboundSchema = z.object({ }); export type ClientInbound = z.infer; +export const ClientNodeUsageSchema = z.object({ + down: z.number().int(), + nodeId: z.number().int(), + nodeName: z.string(), + up: z.number().int(), +}); +export type ClientNodeUsage = z.infer; + export const ClientPageResponseSchema = z.object({ filtered: z.number().int(), groups: z.array(z.string()), @@ -656,6 +675,28 @@ export const ClientTrafficSchema = z.object({ }); export type ClientTraffic = z.infer; +export const ClientTrafficWindowSchema = z.object({ + at: z.number().int(), + down: z.number().int(), + email: z.string(), + id: z.number().int(), + reason: z.string(), + up: z.number().int(), +}); +export type ClientTrafficWindow = z.infer; + +export const ClientUsageHistorySchema = z.object({ + changes: z.array(z.lazy(() => ClientChangeLogSchema)), + currentDown: z.number().int(), + currentUp: z.number().int(), + email: z.string(), + lifetimeDown: z.number().int(), + lifetimeUp: z.number().int(), + nodes: z.array(z.lazy(() => ClientNodeUsageSchema)), + windows: z.array(z.lazy(() => ClientTrafficWindowSchema)), +}); +export type ClientUsageHistory = z.infer; + export const ClientsSummarySchema = z.object({ active: z.number().int(), deactive: z.array(z.string()), diff --git a/frontend/src/lib/clients/usage-history.ts b/frontend/src/lib/clients/usage-history.ts new file mode 100644 index 000000000..51be9cfe6 --- /dev/null +++ b/frontend/src/lib/clients/usage-history.ts @@ -0,0 +1,80 @@ +export interface ClientTrafficWindowInfo { + id: number; + email: string; + at: number; + up: number; + down: number; + reason: string; +} + +export interface ClientNodeUsageInfo { + nodeId: number; + nodeName: string; + up: number; + down: number; +} + +export interface ClientChangeInfo { + id: number; + email: string; + at: number; + field: string; + oldValue: string; + newValue: string; + source: string; +} + +export interface ClientUsageHistoryInfo { + email: string; + lifetimeUp: number; + lifetimeDown: number; + currentUp: number; + currentDown: number; + windows: ClientTrafficWindowInfo[]; + nodes: ClientNodeUsageInfo[]; + changes: ClientChangeInfo[]; +} + +const num = (value: unknown, fallback = 0): number => + typeof value === 'number' && Number.isFinite(value) ? value : fallback; + +// The backend omits empty collections; the modal always wants real arrays. +export function normalizeClientUsageHistory(raw: unknown): ClientUsageHistoryInfo { + const obj = (raw ?? {}) as Record; + const rows = (value: unknown): Array> => + Array.isArray(value) + ? value.filter( + (entry): entry is Record => !!entry && typeof entry === 'object', + ) + : []; + return { + email: typeof obj.email === 'string' ? obj.email : '', + lifetimeUp: num(obj.lifetimeUp), + lifetimeDown: num(obj.lifetimeDown), + currentUp: num(obj.currentUp), + currentDown: num(obj.currentDown), + windows: rows(obj.windows).map((w) => ({ + id: num(w.id), + email: String(w.email ?? ''), + at: num(w.at), + up: num(w.up), + down: num(w.down), + reason: String(w.reason ?? ''), + })), + nodes: rows(obj.nodes).map((n) => ({ + nodeId: num(n.nodeId), + nodeName: String(n.nodeName ?? ''), + up: num(n.up), + down: num(n.down), + })), + changes: rows(obj.changes).map((c) => ({ + id: num(c.id), + email: String(c.email ?? ''), + at: num(c.at), + field: String(c.field ?? ''), + oldValue: String(c.oldValue ?? ''), + newValue: String(c.newValue ?? ''), + source: String(c.source ?? ''), + })), + }; +} diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index e23b82b13..b725f84f1 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1870,6 +1870,21 @@ export const sections: readonly Section[] = [ ], responseSchema: 'ClientTraffic', }, + { + method: 'GET', + path: '/panel/api/clients/usageHistory/:email', + summary: + "Usage and change history for one client, behind the edit modal's history button. lifetimeUp/lifetimeDown are every archived window plus the client's live counters; currentUp/currentDown are the still-open window. windows lists the closed cycles, newest first (reason: reset | renew | earlier): one is archived whenever a traffic reset or an auto-renewal zeroes the client's counters, the newest 100 are kept and older ones are folded into a single earlier row, so the lifetime total does not change. nodes is the per-node upload/download accumulated since the last reset. changes is the metadata change log, newest first, capped at the newest 200 rows: one row per changed field (subId, expiry, dataLimit, enable, limitIp, limitHwid, adTag, group, renewalPlan) and a name row for a rename; source is panel | tgbot | auto-renew. A renamed client keeps its history under the new email. The history belongs to the client: once the client is deleted, its history is removed within five minutes. Requires an admin token or a panel login session.", + params: [ + { + name: 'email', + in: 'path', + type: 'string', + desc: 'Client email (unique across the panel).', + }, + ], + responseSchema: 'ClientUsageHistory', + }, { method: 'GET', path: '/panel/api/clients/subLinks/:subId', diff --git a/frontend/src/pages/clients/ClientFormModal.tsx b/frontend/src/pages/clients/ClientFormModal.tsx index 24916789c..e66963c95 100644 --- a/frontend/src/pages/clients/ClientFormModal.tsx +++ b/frontend/src/pages/clients/ClientFormModal.tsx @@ -19,7 +19,7 @@ import { Typography, message, } from 'antd'; -import { EyeOutlined, ReloadOutlined, RetweetOutlined } from '@ant-design/icons'; +import { EyeOutlined, HistoryOutlined, ReloadOutlined, RetweetOutlined } from '@ant-design/icons'; import dayjs from 'dayjs'; import type { Dayjs } from 'dayjs'; import { FormProvider, useForm, useWatch, type FieldPath } from 'react-hook-form'; @@ -36,6 +36,7 @@ import { useRawHostsQuery } from '@/api/queries/useRawHostsQuery'; import { DateTimePicker, SelectAllClearButtons, selectTagRender } from '@/components/form'; import { FormField, rhfZodValidate } from '@/components/form/rhf'; import ClientHwidListModal from '@/components/clients/ClientHwidList'; +import ClientUsageHistoryModal from '@/components/clients/ClientUsageHistoryModal'; import { TLS_FLOW_CONTROL, TRAFFIC_RESETS } from '@/schemas/primitives'; import { OptionalAmneziaWGKeepAliveInputSchema, @@ -293,6 +294,7 @@ export default function ClientFormModal({ setHwidBlocked, } = useClientHwids(client?.email); const [hwidsModalOpen, setHwidsModalOpen] = useState(false); + const [usageHistoryOpen, setUsageHistoryOpen] = useState(false); const { datepicker } = useDatepicker(); const hwidDateLabel = (ts: number) => !ts || ts <= 0 ? '-' : IntlUtil.formatDate(ts, datepicker); @@ -908,6 +910,14 @@ export default function ClientFormModal({ )} + {isEdit && client?.email && ( + + )}
{links.map((link, idx) => { const parts = parseLinkParts(link); - const rowTitle = parts?.remark || `Link ${idx + 1}`; + const rowTitle = parts?.remark || linkRemarks[idx] || `Link ${idx + 1}`; const isWireguardLink = link.startsWith('wireguard://') || link.startsWith('wg://'); const wireguardConfig = isWireguardLink ? wireguardConfigFromLink(link, rowTitle) : ''; const amneziawgConfig = link.startsWith('vpn://') ? amneziawgConfigFromLink(link) : ''; diff --git a/frontend/src/pages/sub/SubPage.tsx b/frontend/src/pages/sub/SubPage.tsx index d001c37cb..4470db414 100644 --- a/frontend/src/pages/sub/SubPage.tsx +++ b/frontend/src/pages/sub/SubPage.tsx @@ -34,6 +34,7 @@ const updateHours = Number(subData.subUpdates || 0); const announce = subData.announce || ''; const links: string[] = Array.isArray(subData.links) ? subData.links : []; const linkEmails: string[] = Array.isArray(subData.emails) ? subData.emails : []; +const linkRemarks: string[] = Array.isArray(subData.linkRemarks) ? subData.linkRemarks : []; const totalByte = Number(subData.totalByte || 0); const usedByte = Number(subData.usedByte || 0) || @@ -124,7 +125,7 @@ export default function SubPage() { {links.length} ), - children: , + children: , }); } return items; diff --git a/frontend/src/test/sub-links-tab.test.tsx b/frontend/src/test/sub-links-tab.test.tsx index dcf7a80b2..acb91fe23 100644 --- a/frontend/src/test/sub-links-tab.test.tsx +++ b/frontend/src/test/sub-links-tab.test.tsx @@ -2,6 +2,7 @@ import { fireEvent, render, within } from '@testing-library/react'; import { QRCode } from 'antd'; import { describe, expect, it, vi } from 'vitest'; +import SubConfigsTab from '@/pages/sub/SubConfigsTab'; import SubLinksTab from '@/pages/sub/SubLinksTab'; import { renderWithProviders } from './test-utils'; @@ -79,3 +80,21 @@ describe('SubLinksTab inline QR card', () => { expect(card.querySelector('.ant-segmented')).toBeNull(); }); }); + +describe('SubConfigsTab row titles (#7198)', () => { + it('names a remark-less tg://proxy row from linkRemarks at its own index', () => { + const links = [ + 'vless://11111111-1111-4111-8111-111111111111@h.example.com:443?type=tcp#DE-alice', + 'tg://proxy?server=203.0.113.7&port=8443&secret=ee00', + 'tg://proxy?server=203.0.113.8&port=8443&secret=ee11', + ]; + const view = renderWithProviders( + , + ); + + const titles = [...view.container.querySelectorAll('.sub-row-title')].map( + (el) => el.textContent, + ); + expect(titles).toEqual(['DE-alice', 'mt-sub-user', 'Link 3']); + }); +}); diff --git a/internal/sub/controller.go b/internal/sub/controller.go index 098ae568d..ef155e99f 100644 --- a/internal/sub/controller.go +++ b/internal/sub/controller.go @@ -450,6 +450,7 @@ func (a *SUBController) maybeServeSubInfo(c *gin.Context) bool { } info := a.subPageContext(page) delete(info, "links") + delete(info, "linkRemarks") delete(info, "subFormat") info["emails"] = dedupeEmails(page.Emails) c.JSON(http.StatusOK, info) @@ -462,6 +463,7 @@ func (a *SUBController) buildSubPageData(c *gin.Context) (PageData, bool) { subReq := a.subService.ForRequest(host) subReq.wireguardDevice = c.Query("wgDevice") subReq.subscriptionBody = false + subReq.linkRemarks = map[string]string{} subs, emails, lastOnline, traffic, err := subReq.getSubs(subId) if err != nil || subs == nil { writeSubError(c, err) @@ -746,6 +748,7 @@ func (a *SUBController) subPageContext(page PageData) map[string]any { "subUpdates": updateHours, "links": page.Result, "emails": page.Emails, + "linkRemarks": page.LinkRemarks, "datepicker": datepicker, "announce": page.SubAnnounce, } diff --git a/internal/sub/info_endpoint_test.go b/internal/sub/info_endpoint_test.go index ddb2f583e..78494410b 100644 --- a/internal/sub/info_endpoint_test.go +++ b/internal/sub/info_endpoint_test.go @@ -175,3 +175,68 @@ func TestSubPageDataNamesTheFormatOfTheVisitedRoute(t *testing.T) { }) } } + +// tg://proxy links carry no #remark, so the page data must name the MTProto row +// at the link's own index and leave self-named links empty (#7198). +func TestSubPage_MtprotoRowCarriesInboundRemark(t *testing.T) { + gin.SetMode(gin.TestMode) + initSubDB(t) + seedInfoEndpointSub(t, "mt-page", "user") + db := database.GetDB() + inbound := &model.Inbound{ + Listen: "203.0.113.7", Port: 8443, Protocol: model.MTProto, Enable: true, + Tag: "mt-page", Remark: "mt-sub", + Settings: `{"fakeTlsDomain":"www.cloudflare.com","clients":[{"email":"user","enable":true,"subId":"mt-page","secret":"` + mtprotoTestSecret + `"}]}`, + } + if err := db.Create(inbound).Error; err != nil { + t.Fatalf("create inbound: %v", err) + } + var client model.ClientRecord + if err := db.Where("email = ?", "user").First(&client).Error; err != nil { + t.Fatalf("load client: %v", err) + } + if err := db.Model(&client).Update("secret", mtprotoTestSecret).Error; err != nil { + t.Fatalf("set secret: %v", err) + } + if err := db.Create(&model.ClientInbound{ClientId: client.Id, InboundId: inbound.Id}).Error; err != nil { + t.Fatalf("attach client: %v", err) + } + oldDistFS := distFS + distFS = testDistFS + t.Cleanup(func() { distFS = oldDistFS }) + + router := gin.New() + NewSUBController(router.Group("/")) + req := httptest.NewRequest(http.MethodGet, "/sub/mt-page", nil) + req.Host = "sub.example.com" + req.Header.Set("Accept", "text/html") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + _, rest, found := strings.Cut(w.Body.String(), "window.__SUB_PAGE_DATA__=") + raw, _, closed := strings.Cut(rest, ";") + if w.Code != http.StatusOK || !found || !closed { + t.Fatalf("status = %d, page data not found; body=%s", w.Code, w.Body.String()) + } + var page struct { + Links []string `json:"links"` + LinkRemarks []string `json:"linkRemarks"` + } + if err := json.Unmarshal([]byte(raw), &page); err != nil { + t.Fatalf("page data is not valid JSON: %v; data=%s", err, raw) + } + want := make([]string, len(page.Links)) + mtproto := 0 + for i, link := range page.Links { + if strings.HasPrefix(link, "tg://proxy") { + want[i] = "mt-sub-user" + mtproto++ + } + } + if mtproto != 1 || len(page.Links) != 2 { + t.Fatalf("links = %q, want one tg://proxy link and one external link", page.Links) + } + if len(page.LinkRemarks) != len(want) || page.LinkRemarks[0] != want[0] || page.LinkRemarks[1] != want[1] { + t.Fatalf("linkRemarks = %q, want %q for links %q", page.LinkRemarks, want, page.Links) + } +} diff --git a/internal/sub/service.go b/internal/sub/service.go index a931379b3..d1a7079c7 100644 --- a/internal/sub/service.go +++ b/internal/sub/service.go @@ -103,6 +103,9 @@ type SubService struct { // settingsByInbound: one decode per request, not one per link of a subId. tuicByInbound map[int]*tuicLinkInstance amneziaWGServerByInbound map[int]*amneziawg.ServerSettings + // linkRemarks maps a remark-less link (mtproto) to its remark; only the sub page + // sets it, so the Configs tab can name the row. + linkRemarks map[string]string } // tuicLinkInstance indexes a decoded TUIC inbound's clients by email @@ -1313,11 +1316,15 @@ func (s *SubService) genMtprotoLink(inbound *model.Inbound, email string) string endpoints := s.advertisedEndpoints(inbound) links := make([]string, 0, len(endpoints)) for _, endpoint := range endpoints { - links = append(links, buildLinkWithParams("tg://proxy", map[string]string{ + link := buildLinkWithParams("tg://proxy", map[string]string{ "server": endpoint.Address, "port": fmt.Sprintf("%d", endpoint.Port), "secret": resolved.Secret, - }, "")) + }, "") + if s.linkRemarks != nil { + s.linkRemarks[link] = s.endpointRemark(inbound, email, endpoint.ep, "") + } + links = append(links, link) } return strings.Join(links, "\n") } @@ -3400,6 +3407,7 @@ type PageData struct { SubAnnounce string Result []string Emails []string + LinkRemarks []string } // ResolveRequest extracts scheme, host, and header information from an HTTP request. @@ -3548,6 +3556,7 @@ func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray pageLinks := make([]string, 0, len(subs)) pageEmails := make([]string, 0, len(subs)) + pageRemarks := make([]string, 0, len(subs)) for i, sub := range subs { email := "" if i < len(emails) { @@ -3556,6 +3565,7 @@ func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray for _, link := range splitLinkLines(sub) { pageLinks = append(pageLinks, link) pageEmails = append(pageEmails, email) + pageRemarks = append(pageRemarks, s.linkRemarks[link]) } } @@ -3583,6 +3593,7 @@ func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray SubSupportUrl: subSupportUrl, Result: pageLinks, Emails: pageEmails, + LinkRemarks: pageRemarks, } } From efb6c6d5796c427cb547fecc4f2a607c36ae7009 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 25 Nov 2026 15:23:19 +0330 Subject: [PATCH 089/130] perf(traffic): skip unchanged client lifecycle writes (#7204) A full inbound save ran the lifecycle UPDATE on client_traffics for every client of the inbound, even when quota, expiry, renewal settings and the enable flag already matched. On PostgreSQL each of those is a new row version and WAL, on every stream-settings edit of a large inbound. Guard the same UPDATE with a NULL-safe IS DISTINCT FROM over the eight columns it assigns, so the database writes only a row that actually differs and still repairs one that drifted. The PostgreSQL CI job runs the lifecycle suite, including a row-lock check on a second connection. Closes #7202 --- .github/workflows/ci.yml | 9 + internal/web/service/bulk_clients_test.go | 2 +- .../client_traffic_lifecycle_bench_test.go | 196 +++++++++++++ .../service/client_traffic_lifecycle_test.go | 267 ++++++++++++++++++ internal/web/service/inbound_traffic.go | 11 +- 5 files changed, 480 insertions(+), 5 deletions(-) create mode 100644 internal/web/service/client_traffic_lifecycle_bench_test.go create mode 100644 internal/web/service/client_traffic_lifecycle_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 08731d130..a80719556 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,15 @@ jobs: exit 1 fi + - name: PostgreSQL client traffic lifecycle edits + run: | + set -o pipefail + go test ./internal/web/service -run '^TestClientTrafficLifecyclePostgres$' -count=1 -v | tee /tmp/postgres-client-traffic-lifecycle.log + if ! grep -q -- '^--- PASS: TestClientTrafficLifecyclePostgres ' /tmp/postgres-client-traffic-lifecycle.log; then + echo "expected the PostgreSQL client traffic lifecycle suite to pass" >&2 + exit 1 + fi + - name: PostgreSQL batched stats identities run: | set -o pipefail diff --git a/internal/web/service/bulk_clients_test.go b/internal/web/service/bulk_clients_test.go index 34fba1942..085ec95f4 100644 --- a/internal/web/service/bulk_clients_test.go +++ b/internal/web/service/bulk_clients_test.go @@ -11,7 +11,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database/model" ) -func setupBulkDB(t *testing.T) { +func setupBulkDB(t testing.TB) { t.Helper() dbDir := t.TempDir() t.Setenv("XUI_DB_FOLDER", dbDir) diff --git a/internal/web/service/client_traffic_lifecycle_bench_test.go b/internal/web/service/client_traffic_lifecycle_bench_test.go new file mode 100644 index 000000000..b33c3d7fd --- /dev/null +++ b/internal/web/service/client_traffic_lifecycle_bench_test.go @@ -0,0 +1,196 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "os" + "strings" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" +) + +type lifecycleBenchMetrics struct { + statements int64 + updates int64 + rows int64 + txTime time.Duration +} + +type lifecycleBenchPool struct { + *sql.DB + metrics *lifecycleBenchMetrics +} + +func (p *lifecycleBenchPool) GetDBConn() (*sql.DB, error) { return p.DB, nil } + +func (p *lifecycleBenchPool) BeginTx(ctx context.Context, opts *sql.TxOptions) (gorm.ConnPool, error) { + if p.metrics == nil { + return p.DB.BeginTx(ctx, opts) + } + start := time.Now() + tx, err := p.DB.BeginTx(ctx, opts) + if err != nil { + return nil, err + } + return &lifecycleBenchTx{Tx: tx, start: start, metrics: p.metrics}, nil +} + +func (p *lifecycleBenchPool) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + if p.metrics != nil { + p.metrics.statements++ + } + return p.DB.QueryContext(ctx, query, args...) +} + +func (p *lifecycleBenchPool) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + if p.metrics != nil { + p.metrics.statements++ + } + return p.DB.QueryRowContext(ctx, query, args...) +} + +func (p *lifecycleBenchPool) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { + if p.metrics != nil { + p.metrics.statements++ + } + return p.DB.ExecContext(ctx, query, args...) +} + +type lifecycleBenchTx struct { + *sql.Tx + start time.Time + metrics *lifecycleBenchMetrics +} + +func (t *lifecycleBenchTx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + t.metrics.statements++ + return t.Tx.QueryContext(ctx, query, args...) +} + +func (t *lifecycleBenchTx) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + t.metrics.statements++ + return t.Tx.QueryRowContext(ctx, query, args...) +} + +func (t *lifecycleBenchTx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { + t.metrics.statements++ + result, err := t.Tx.ExecContext(ctx, query, args...) + if err == nil && strings.HasPrefix(query, `UPDATE "client_traffics" SET "email"=`) { + n, err := result.RowsAffected() + if err != nil { + return result, err + } + t.metrics.updates++ + t.metrics.rows += n + } + return result, err +} + +func (t *lifecycleBenchTx) Commit() error { + err := t.Tx.Commit() + t.metrics.txTime += time.Since(t.start) + return err +} + +func BenchmarkInboundTrafficLifecycleEdit(b *testing.B) { + if os.Getenv("XUI_DB_TYPE") != "postgres" || os.Getenv("XUI_DB_DSN") == "" { + b.Skip("requires a dedicated disposable PostgreSQL server for WAL measurement") + } + for _, size := range []int{1000, 10000, 20000} { + b.Run(fmt.Sprint(size), func(b *testing.B) { + cleanup, err := testpg.IsolatePackage("inbound_lifecycle_bench") + if err != nil { + b.Fatal(err) + } + b.Cleanup(cleanup) + setupBulkDB(b) + db := database.GetDB() + sqlDB, err := db.DB() + if err != nil { + b.Fatal(err) + } + clients := make([]model.Client, size) + for i := range clients { + clients[i] = model.Client{ + Email: fmt.Sprintf("fixture-%05d@x", i), ID: fmt.Sprintf("00000000-0000-4000-8000-%012d", i+1), + Enable: true, TotalGB: 1 << 30, + } + } + svc := &InboundService{} + inbound := seedTrafficLifecycleInbound(b, svc, clients) + pool := &lifecycleBenchPool{DB: sqlDB} + original := db.Statement.ConnPool + db.Statement.ConnPool = pool + defer func() { db.Statement.ConnPool = original }() + for _, percent := range []int{0, 10, 100} { + b.Run(fmt.Sprintf("changed-%d", percent), func(b *testing.B) { + benchmarkTrafficLifecycleEdits(b, svc, inbound, pool, size, size*percent/100) + }) + } + }) + } +} + +func benchmarkTrafficLifecycleEdits(b *testing.B, svc *InboundService, inbound *model.Inbound, pool *lifecycleBenchPool, size, changed int) { + b.Helper() + prepare := func() { + b.Helper() + if err := database.GetDB().Exec("UPDATE client_traffics SET total = 0 WHERE id IN (SELECT id FROM client_traffics ORDER BY id LIMIT ?)", changed).Error; err != nil { + b.Fatal(err) + } + } + edit := func(remark string) { + b.Helper() + form := *inbound + form.Remark = remark + if _, _, err := svc.UpdateInbound(&form); err != nil { + b.Fatal(err) + } + } + // Warm the exact code path and then restore drift before each timed edit. + prepare() + edit("warm-up") + var totals lifecycleBenchMetrics + var walBytes int64 + iteration := 0 + b.ReportAllocs() + for b.Loop() { + b.StopTimer() + prepare() + var lsn string + if err := pool.DB.QueryRowContext(b.Context(), "SELECT pg_current_wal_insert_lsn()::text").Scan(&lsn); err != nil { + b.Fatal(err) + } + iteration++ + remark := fmt.Sprintf("edit-%d", iteration) + var metrics lifecycleBenchMetrics + pool.metrics = &metrics + b.StartTimer() + edit(remark) + b.StopTimer() + pool.metrics = nil + if metrics.txTime <= 0 || metrics.updates != int64(size) || (metrics.rows != int64(changed) && metrics.rows != int64(size)) { + b.Fatalf("inbound edit at %d/%d changed rows: %+v", changed, size, metrics) + } + var wal int64 + if err := pool.DB.QueryRowContext(b.Context(), "SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(), $1::pg_lsn)::bigint", lsn).Scan(&wal); err != nil { + b.Fatal(err) + } + walBytes += wal + totals.statements += metrics.statements + totals.rows += metrics.rows + totals.txTime += metrics.txTime + b.StartTimer() + } + b.ReportMetric(float64(totals.statements)/float64(b.N), "sql/op") + b.ReportMetric(float64(totals.rows)/float64(b.N), "traffic-rows/op") + b.ReportMetric(float64(walBytes)/float64(b.N), "wal-B/op") + b.ReportMetric(float64(totals.txTime.Microseconds())/float64(b.N), "tx-us/op") +} diff --git a/internal/web/service/client_traffic_lifecycle_test.go b/internal/web/service/client_traffic_lifecycle_test.go new file mode 100644 index 000000000..f1509de16 --- /dev/null +++ b/internal/web/service/client_traffic_lifecycle_test.go @@ -0,0 +1,267 @@ +package service + +import ( + "errors" + "os" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/mattn/go-sqlite3" + "gorm.io/gorm" + "gorm.io/gorm/clause" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestClientTrafficLifecyclePostgres(t *testing.T) { + if os.Getenv("XUI_DB_TYPE") != "postgres" || os.Getenv("XUI_DB_DSN") == "" { + t.Skip("requires a disposable PostgreSQL database") + } + for _, test := range []struct { + name string + run func(*testing.T) + }{ + {"inbound save", TestInboundEditWritesOnlyDriftedTraffic}, + {"fields and errors", TestUpdateClientStatPreservesLifecycleAndCounters}, + {"row locks", checkUpdateClientStatRowLocks}, + {"one connection", TestUpdateClientTrafficsStaysOnOneConnection}, + {"rename onto existing stats", TestUpdateInboundClientRenameOntoExistingStatStaysOnOneConnection}, + {"master lifecycle", TestInboundUpdateFromMasterAppliesClientLifecycle}, + {"sibling lifecycle", TestNodeInboundPushDisablingASharedClientRemovesItFromEveryHandler}, + {"detached lifecycle", TestUpdate_NoInbound_SyncsEnforcementRow}, + {"reattachment", TestAddClientStat_MultiInboundReattachStaysIdempotent}, + } { + t.Run(test.name, func(t *testing.T) { + cleanup, err := testpg.IsolatePackage("client_traffic_lifecycle") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + test.run(t) + }) + } +} + +func execLifecycleTestSQL(t testing.TB, queries ...string) { + t.Helper() + for _, query := range queries { + if err := database.GetDB().Exec(query).Error; err != nil { + t.Fatal(err) + } + } +} + +func auditLifecycleWrites(t *testing.T) func() int64 { + t.Helper() + execLifecycleTestSQL(t, "CREATE TABLE lifecycle_write_audit (email text)") + db := database.GetDB() + if db.Name() == "postgres" { + execLifecycleTestSQL(t, `CREATE FUNCTION audit_lifecycle_write() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN INSERT INTO lifecycle_write_audit VALUES (NEW.email); RETURN NEW; END; + $$`, `CREATE TRIGGER audit_lifecycle_write AFTER UPDATE ON client_traffics + FOR EACH ROW EXECUTE FUNCTION audit_lifecycle_write()`) + } else { + execLifecycleTestSQL(t, `CREATE TRIGGER audit_lifecycle_write AFTER UPDATE ON client_traffics + BEGIN INSERT INTO lifecycle_write_audit VALUES (NEW.email); END`) + } + return func() int64 { + t.Helper() + var count int64 + if err := db.Table("lifecycle_write_audit").Count(&count).Error; err != nil { + t.Fatal(err) + } + return count + } +} + +func seedTrafficLifecycleInbound(t testing.TB, svc *InboundService, clients []model.Client) *model.Inbound { + t.Helper() + inbound, _, err := svc.AddInbound(&model.Inbound{ + UserId: 1, Tag: "lifecycle-edit", Remark: "before", Port: 43021, + Enable: true, Protocol: model.VLESS, Settings: clientsSettings(t, clients), + StreamSettings: `{"network":"tcp","security":"none"}`, + }) + if err != nil { + t.Fatal(err) + } + return inbound +} + +func TestInboundEditWritesOnlyDriftedTraffic(t *testing.T) { + setupBulkDB(t) + svc := &InboundService{} + ib := seedTrafficLifecycleInbound(t, svc, []model.Client{ + {Email: "stable@x", ID: "00000000-0000-4000-8000-000000000001", Enable: true, TotalGB: 1 << 30}, + {Email: "drifted@x", ID: "00000000-0000-4000-8000-000000000002", Enable: true, TotalGB: 2 << 30}, + }) + stable := readClientTraffic(t, "stable@x") + execLifecycleTestSQL(t, "UPDATE client_traffics SET total = 0, up = 73, down = 19, last_online = 100, reset_count = 2 WHERE email = 'drifted@x'") + drifted := readClientTraffic(t, "drifted@x") + drifted.Total = 2 << 30 + count := auditLifecycleWrites(t) + form := *ib + form.Remark = "edited" + if _, _, err := svc.UpdateInbound(&form); err != nil { + t.Fatal(err) + } + if got := count(); got != 1 { + t.Fatalf("row trigger fired %d times, want only the drift repair", got) + } + if got := readClientTraffic(t, stable.Email); got != stable { + t.Fatalf("identical row changed: %+v, want %+v", got, stable) + } + if got := readClientTraffic(t, drifted.Email); got != drifted { + t.Fatalf("drift repair = %+v, want %+v", got, drifted) + } + form.Remark = "edited again" + if _, _, err := svc.UpdateInbound(&form); err != nil { + t.Fatal(err) + } + if got := count(); got != 1 { + t.Fatalf("second edit fired additional row triggers: got %d total", got) + } + saved, err := svc.GetInbound(ib.Id) + if err != nil || saved.Remark != "edited again" { + t.Fatalf("inbound edit did not persist: %v, %v", saved, err) + } +} + +func TestUpdateClientStatPreservesLifecycleAndCounters(t *testing.T) { + setupBulkDB(t) + db := database.GetDB() + svc := &InboundService{} + count := auditLifecycleWrites(t) + for _, tc := range []struct { + name string + set func(*xray.ClientTraffic, *model.Client) + }{ + {"case-only rename", func(row *xray.ClientTraffic, c *model.Client) { c.Email = strings.ToUpper(row.Email) }}, + {"disable", func(_ *xray.ClientTraffic, c *model.Client) { c.Enable = false }}, + {"enable", func(row *xray.ClientTraffic, c *model.Client) { row.Enable, c.Enable = false, true }}, + {"clear total", func(_ *xray.ClientTraffic, c *model.Client) { c.TotalGB = 0 }}, + {"delayed expiry", func(_ *xray.ClientTraffic, c *model.Client) { c.ExpiryTime = -86400000 }}, + {"interval", func(_ *xray.ClientTraffic, c *model.Client) { c.Reset = 30 }}, + {"billing day", func(_ *xray.ClientTraffic, c *model.Client) { c.ResetDay = 15 }}, + {"weekly day", func(_ *xray.ClientTraffic, c *model.Client) { c.ResetWeekday = 7 }}, + {"max renewals", func(_ *xray.ClientTraffic, c *model.Client) { c.ResetMax = 4 }}, + {"repair nulls", func(_ *xray.ClientTraffic, _ *model.Client) {}}, + } { + t.Run(tc.name, func(t *testing.T) { + row := xray.ClientTraffic{ + Email: tc.name + "@x", Enable: true, Total: 1 << 30, + Up: 3, Down: 5, LastOnline: 7, LastSubFetch: 9, ResetCount: 11, InboundId: 13, + } + client := model.Client{Email: row.Email, Enable: row.Enable, TotalGB: row.Total} + tc.set(&row, &client) + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + if tc.name == "repair nulls" { + if err := db.Model(&row).Updates(map[string]any{ + "enable": nil, "total": nil, "expiry_time": nil, "reset": nil, + "reset_day": nil, "reset_weekday": nil, "reset_max": nil, + }).Error; err != nil { + t.Fatal(err) + } + } + before := count() + if err := db.Transaction(func(tx *gorm.DB) error { return svc.UpdateClientStat(tx, row.Email, &client) }); err != nil { + t.Fatal(err) + } + row.Email, row.Enable, row.Total, row.ExpiryTime = client.Email, client.Enable, client.TotalGB, client.ExpiryTime + row.Reset, row.ResetDay, row.ResetWeekday, row.ResetMax = client.Reset, client.ResetDay, client.ResetWeekday, client.ResetMax + if got := readClientTraffic(t, client.Email); got != row || count() != before+1 { + t.Fatalf("updated row = %+v, want %+v and exactly one write", got, row) + } + if tc.name == "repair nulls" { + var nulls int64 + if err := db.Model(xray.ClientTraffic{}).Where("id = ?", row.Id). + Where("(enable IS NULL OR total IS NULL OR expiry_time IS NULL OR reset IS NULL OR reset_day IS NULL OR reset_weekday IS NULL OR reset_max IS NULL)"). + Count(&nulls).Error; err != nil || nulls != 0 { + t.Fatalf("NULL repair = %d rows remain, error=%v", nulls, err) + } + } + }) + } + before := count() + if err := svc.UpdateClientStat(db, "missing@x", &model.Client{Email: "missing@x"}); err != nil || count() != before { + t.Fatalf("missing row: error=%v, writes=%d", err, count()-before) + } + invalid := xray.ClientTraffic{Email: "invalid@x", ResetWeekday: 8} + if err := db.Create(&invalid).Error; err != nil { + t.Fatal(err) + } + if err := svc.UpdateClientStat(db, invalid.Email, &model.Client{Email: invalid.Email, ResetWeekday: 8}); err == nil || + err.Error() != "client resetWeekday must be between 0 and 7, got: 8\n" || count() != before { + t.Fatalf("equal invalid row: error=%v, writes=%d", err, count()-before) + } + if err := svc.UpdateClientStat(db, "disable@x", &model.Client{Email: "enable@x"}); !lifecycleUniqueViolation(err) { + t.Fatalf("rename onto existing email: expected unique constraint error, got %v", err) + } + if got := readClientTraffic(t, "disable@x"); got.Total != 1<<30 || count() != before { + t.Fatalf("failed rename changed source: %+v", got) + } +} + +func lifecycleUniqueViolation(err error) bool { + var pgErr *pgconn.PgError + var sqliteErr sqlite3.Error + return errors.As(err, &pgErr) && pgErr.Code == "23505" || + errors.As(err, &sqliteErr) && sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique +} + +func checkUpdateClientStatRowLocks(t *testing.T) { + t.Helper() + setupBulkDB(t) + db := database.GetDB() + svc := &InboundService{} + for _, test := range []struct { + name string + total int64 + wantLocked bool + }{ + {"identical", 1000, false}, + {"changed", 2000, true}, + } { + t.Run(test.name, func(t *testing.T) { + row := xray.ClientTraffic{Email: test.name + "@x", Enable: true, Total: 1000} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + tx := db.Begin() + if tx.Error != nil { + t.Fatal(tx.Error) + } + defer func() { _ = tx.Rollback().Error }() + client := model.Client{Email: row.Email, Enable: true, TotalGB: test.total} + if err := svc.UpdateClientStat(tx, row.Email, &client); err != nil { + t.Fatal(err) + } + + // Probe on another connection while the UPDATE transaction is still open. + err := db.Transaction(func(other *gorm.DB) error { + var locked xray.ClientTraffic + return other.Clauses(clause.Locking{Strength: "UPDATE", Options: "NOWAIT"}). + Where("id = ?", row.Id).Take(&locked).Error + }) + if test.wantLocked { + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || pgErr.Code != "55P03" { + t.Fatalf("changed update should hold a row lock (SQLSTATE 55P03), got %v", err) + } + } else if err != nil { + t.Fatalf("identical update should leave the row available, got %v", err) + } + if err := tx.Commit().Error; err != nil { + t.Fatal(err) + } + if got := readClientTraffic(t, row.Email).Total; got != test.total { + t.Fatalf("committed total = %d, want %d", got, test.total) + } + }) + } +} diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index bd3bba31a..e03458a31 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -662,8 +662,13 @@ func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *mod if err := validateClientRenewal(*client); err != nil { return err } - result := tx.Model(xray.ClientTraffic{}). + // Compare the persisted row atomically so an unchanged inbound can still repair drift. + return tx.Model(xray.ClientTraffic{}). Where("email = ?", email). + Where(`(email, enable, expiry_time, reset, reset_day, reset_max, reset_weekday, total) + IS DISTINCT FROM (?, ?, ?, ?, ?, ?, ?, ?)`, + client.Email, client.Enable, client.ExpiryTime, client.Reset, client.ResetDay, + client.ResetMax, client.ResetWeekday, client.TotalGB). Updates(map[string]any{ "enable": client.Enable, "email": client.Email, @@ -673,9 +678,7 @@ func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *mod "reset_day": client.ResetDay, "reset_weekday": client.ResetWeekday, "reset_max": client.ResetMax, - }) - err := result.Error - return err + }).Error } func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error { From 40132196980664bd7adbd78dc1cac5e00df23c29 Mon Sep 17 00:00:00 2001 From: Aleksey Fedorov <320380254+Dv2Corn@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:08:34 +1000 Subject: [PATCH 090/130] fix(settings): wait for the panel to answer before reloading after a restart (#7205) After Restart Panel, and after a database import, the page slept a fixed 5 seconds and reloaded. When the panel took longer to come back, the reload reached a reverse proxy with nothing listening upstream and the browser showed its 502/504 page. Keep the 5 second delay, then poll the address the page is about to open every 2 seconds until it answers below 500, and give up after 90 seconds so the page never hangs. A new port or protocol is probed with no-cors; an https page whose target is http would be blocked as mixed content, so it probes its own origin, which is the proxy that answers 502 while the panel is down. Closes #7190 --- frontend/src/pages/index/BackupModal.tsx | 2 +- frontend/src/pages/settings/SettingsPage.tsx | 5 +- frontend/src/test/wait-for-panel.test.ts | 78 ++++++++++++++++++++ frontend/src/utils/index.ts | 29 ++++++++ 4 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 frontend/src/test/wait-for-panel.test.ts diff --git a/frontend/src/pages/index/BackupModal.tsx b/frontend/src/pages/index/BackupModal.tsx index 473d30592..fbc09ed04 100644 --- a/frontend/src/pages/index/BackupModal.tsx +++ b/frontend/src/pages/index/BackupModal.tsx @@ -61,7 +61,7 @@ export default function BackupModal({ // importDB schedules the panel restart server-side; wait it out, then reload. onBusy({ busy: true, tip: `${t('pages.settings.restartPanel')}…` }); - await PromiseUtil.sleep(5000); + await PromiseUtil.waitForPanel(window.location.href); window.location.reload(); }); fileInput.click(); diff --git a/frontend/src/pages/settings/SettingsPage.tsx b/frontend/src/pages/settings/SettingsPage.tsx index 7f42169c0..c666bafd1 100644 --- a/frontend/src/pages/settings/SettingsPage.tsx +++ b/frontend/src/pages/settings/SettingsPage.tsx @@ -150,8 +150,9 @@ export default function SettingsPage() { try { const msg = (await HttpUtil.post('/panel/api/setting/restartPanel')) as ApiMsg; if (!msg?.success) return; - await PromiseUtil.sleep(5000); - window.location.replace(rebuildUrlAfterRestart()); + const target = rebuildUrlAfterRestart(); + await PromiseUtil.waitForPanel(target); + window.location.replace(target); } finally { setSpinning(false); } diff --git a/frontend/src/test/wait-for-panel.test.ts b/frontend/src/test/wait-for-panel.test.ts new file mode 100644 index 000000000..c16101226 --- /dev/null +++ b/frontend/src/test/wait-for-panel.test.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { PromiseUtil } from '@/utils'; + +const fast = { delay: 0, interval: 1, timeout: 200 }; + +function answer(status: number, type: ResponseType = 'basic'): Response { + return { status, type } as Response; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('PromiseUtil.waitForPanel (#7190)', () => { + it('keeps polling through refused connections and proxy 502s until the panel answers', async () => { + vi.stubGlobal('window', { + location: { href: 'https://panel.test/panel/settings', origin: 'https://panel.test' }, + }); + const fetchMock = vi + .fn() + .mockRejectedValueOnce(new TypeError('Failed to fetch')) + .mockResolvedValueOnce(answer(502)) + .mockResolvedValueOnce(answer(200)); + vi.stubGlobal('fetch', fetchMock); + + await expect(PromiseUtil.waitForPanel('https://panel.test/panel/settings', fast)).resolves.toBe( + true, + ); + expect(fetchMock).toHaveBeenCalledTimes(3); + expect(fetchMock.mock.calls[0][1]).toMatchObject({ mode: 'same-origin', cache: 'no-store' }); + }); + + it('gives up after the timeout so the caller still navigates', async () => { + vi.stubGlobal('window', { + location: { href: 'https://panel.test/', origin: 'https://panel.test' }, + }); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(answer(502))); + + await expect( + PromiseUtil.waitForPanel('https://panel.test/', { ...fast, timeout: 20 }), + ).resolves.toBe(false); + }); + + it('probes a new port or protocol with no-cors and accepts the opaque answer', async () => { + vi.stubGlobal('window', { + location: { + href: 'http://203.0.113.5:2053/panel/settings', + origin: 'http://203.0.113.5:2053', + }, + }); + const fetchMock = vi.fn().mockResolvedValue(answer(0, 'opaque')); + vi.stubGlobal('fetch', fetchMock); + + await expect( + PromiseUtil.waitForPanel('https://203.0.113.5:8443/panel/settings', fast), + ).resolves.toBe(true); + expect(fetchMock.mock.calls[0][1]).toMatchObject({ mode: 'no-cors' }); + }); + + it('probes the current origin when an https page would open an http target (mixed content)', async () => { + vi.stubGlobal('window', { + location: { + href: 'https://panel.test/panel/settings', + origin: 'https://panel.test', + protocol: 'https:', + }, + }); + const fetchMock = vi.fn().mockResolvedValue(answer(200)); + vi.stubGlobal('fetch', fetchMock); + + await expect(PromiseUtil.waitForPanel('http://panel.test/panel/settings', fast)).resolves.toBe( + true, + ); + expect(String(fetchMock.mock.calls[0][0])).toBe('https://panel.test/panel/settings'); + expect(fetchMock.mock.calls[0][1]).toMatchObject({ mode: 'same-origin' }); + }); +}); diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts index e3f781620..84320e704 100644 --- a/frontend/src/utils/index.ts +++ b/frontend/src/utils/index.ts @@ -180,6 +180,35 @@ export class PromiseUtil { setTimeout(resolve, timeout); }); } + + // After the restart delay, polls the target until it answers below 500; false on timeout. + // https page -> http target is blocked as mixed content: probe this origin, the proxy's. + static async waitForPanel( + url: string, + { delay = 5000, interval = 2000, timeout = 90_000 } = {}, + ): Promise { + await PromiseUtil.sleep(delay); + const target = new URL(url, window.location.href); + const mixed = window.location.protocol === 'https:' && target.protocol === 'http:'; + const probe = mixed ? new URL(window.location.href) : target; + const sameOrigin = probe.origin === window.location.origin; + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + try { + const res = await fetch(probe, { + cache: 'no-store', + redirect: 'manual', + mode: sameOrigin ? 'same-origin' : 'no-cors', + signal: AbortSignal.timeout(Math.max(interval, 1000)), + }); + if (res.type === 'opaque' || res.type === 'opaqueredirect' || res.status < 500) return true; + } catch { + /* not listening yet */ + } + await PromiseUtil.sleep(interval); + } + return false; + } } export interface RandomSeqOptions { From e95d17a7dbece52c3dbfb9515d23c3e4b935135e Mon Sep 17 00:00:00 2001 From: Nethmina Yasas <63988674+NethminaYasas@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:51:43 +0530 Subject: [PATCH 091/130] feat(groups): assign host rules from client groups (#7064) Host rules could only be given to clients one by one, so giving a set of customers their own endpoints meant editing every client. A client group can now carry host rules, chosen when the group is created, from its edit dialog or from a quick-assign action on the Groups page. A subscription resolves a client's hosts in this order: the client's own host rules, then the host rules of its group, then the inbound's default pool. A group whose bound rules are all disabled or excluded from the requested format renders nothing for that inbound instead of falling back to the default pool. Binding a rule to a group narrows what its members get; other clients still see that rule in the default pool. Group names are now matched case-insensitively. On upgrade, labels that differ only in case (VIP and vip) are merged into one group, the first by name order. Adds POST /panel/api/clients/groups/:name/hosts and an optional hostGroupIds on group create and rename. --- .github/workflows/ci.yml | 6 +- .../content/docs/en/reference/api/clients.mdx | 73 +-- .../content/docs/fa/reference/api/clients.mdx | 12 +- .../content/docs/ru/reference/api/clients.mdx | 12 +- .../content/docs/zh/reference/api/clients.mdx | 12 +- docs/public/openapi.json | 90 +++- frontend/public/openapi.json | 90 +++- frontend/src/pages/api-docs/endpoints.ts | 21 +- .../src/pages/groups/GroupHostRulesModal.tsx | 63 +++ frontend/src/pages/groups/GroupsPage.tsx | 182 ++++++-- frontend/src/pages/groups/HostGroupSelect.tsx | 38 ++ frontend/src/schemas/client.ts | 5 + internal/database/client_groups.go | 91 ++++ internal/database/client_groups_test.go | 123 +++++ internal/database/db.go | 8 + internal/database/migrate_data.go | 1 + internal/database/model/model.go | 9 + internal/sub/clash_service.go | 4 +- internal/sub/host_group_test.go | 431 ++++++++++++++++++ internal/sub/host_order.go | 6 +- internal/sub/host_scope.go | 179 ++++++++ internal/sub/host_sub.go | 11 +- internal/sub/json_service.go | 4 +- internal/sub/links.go | 2 +- internal/sub/service.go | 16 +- internal/web/controller/group.go | 42 +- internal/web/service/client_crud.go | 7 + .../service/client_group_host_binding_test.go | 431 ++++++++++++++++++ internal/web/service/client_groups.go | 367 ++++++++++----- internal/web/service/client_link.go | 18 + internal/web/service/host.go | 10 +- internal/web/service/inbound.go | 3 + internal/web/translation/ar-EG.json | 10 +- internal/web/translation/en-US.json | 10 +- internal/web/translation/es-ES.json | 10 +- internal/web/translation/fa-IR.json | 10 +- internal/web/translation/id-ID.json | 10 +- internal/web/translation/ja-JP.json | 10 +- internal/web/translation/pt-BR.json | 10 +- internal/web/translation/ru-RU.json | 10 +- internal/web/translation/sk-SK.json | 10 +- internal/web/translation/tr-TR.json | 10 +- internal/web/translation/uk-UA.json | 10 +- internal/web/translation/vi-VN.json | 10 +- internal/web/translation/zh-CN.json | 10 +- internal/web/translation/zh-TW.json | 10 +- 46 files changed, 2222 insertions(+), 285 deletions(-) create mode 100644 frontend/src/pages/groups/GroupHostRulesModal.tsx create mode 100644 frontend/src/pages/groups/HostGroupSelect.tsx create mode 100644 internal/database/client_groups.go create mode 100644 internal/database/client_groups_test.go create mode 100644 internal/sub/host_group_test.go create mode 100644 internal/sub/host_scope.go create mode 100644 internal/web/service/client_group_host_binding_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a80719556..381156ef7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -156,12 +156,12 @@ jobs: - name: PostgreSQL schema and migration tests run: | set -o pipefail - go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres|TestClientWeeklyRenewMigration_Postgres|TestMigrate_LegacyBooleanVerifyPeerCertByNameIsBlanked_Postgres|TestClientKeepAlivePostgresMigrationPreservesLegacyScalars|TestPostgresModelSettled_TracksSchemaPresence)$' -count=1 -v | tee /tmp/postgres-schema.log + go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres|TestClientWeeklyRenewMigration_Postgres|TestMigrate_LegacyBooleanVerifyPeerCertByNameIsBlanked_Postgres|TestClientKeepAlivePostgresMigrationPreservesLegacyScalars|TestPostgresModelSettled_TracksSchemaPresence|TestEnsureClientGroupRows_Postgres)$' -count=1 -v | tee /tmp/postgres-schema.log # All must pass. Counting, not SKIP-matching: renaming a test would # otherwise leave this step green while testing nothing. passed=$(grep -c -- '^--- PASS' /tmp/postgres-schema.log || true) - if [ "$passed" -lt 6 ]; then - echo "expected at least 6 passing PostgreSQL schema tests, got $passed" >&2 + if [ "$passed" -lt 7 ]; then + echo "expected at least 7 passing PostgreSQL schema tests, got $passed" >&2 exit 1 fi diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 4194b8a0b..eae5f2d48 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -228,27 +228,36 @@ _openapi: clients. url: '#zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-its-quota-had-disabled-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-a-client-disabled-by-hand-stays-disabled-returns-the-count-of-successfully-reset-clients' - depth: 2 - title: List all client groups with their member counts. Merges persisted groups - (rows in client_groups, including empty placeholders) with the distinct - group_name values currently set on clients. Sorted alphabetically - (case-insensitive). - url: '#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive' + title: List all client groups with their member counts and the host groups bound + to each. Merges persisted groups (rows in client_groups, including empty + placeholders) with the distinct group_name values currently set on + clients. Sorted alphabetically (case-insensitive). + url: '#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive' + - depth: 2 + title: Replace the host groups attached to a client group. Clients in this group + receive the bound host groups instead of the inbound default host pool; + other clients are unaffected. An empty array clears the bindings. + Returns the saved host group IDs. + url: '#replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids' - depth: 2 title: Return just the email list of clients that currently belong to the given group. Useful for fanning a single bulk action over an entire group without round-tripping the full client list. url: '#return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list' - depth: 2 - title: Create a new empty (placeholder) group. The group becomes selectable in - client forms and the filter drawer even before any client is added to - it. Errors if a group with the same name already exists. - url: '#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists' + title: Create a new group, optionally with host rules bound to it. The group + becomes selectable in client forms and the filter drawer even before any + client is added to it. Host group IDs are validated before the group is + created. Errors if a group with the same name already exists. + url: '#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists' - depth: 2 - title: Rename a group. The new name is applied to the client_groups row AND - propagated to every matching client (both clients.group_name and the - client entry inside every owning inbound's settings JSON) in a single - transaction. Returns the number of clients whose label was updated. - url: '#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated' + title: Rename a group and optionally replace its host rules in one transaction. + The new name is applied to the client_groups row AND propagated to every + matching client (both clients.group_name and the client entry inside + every owning inbound's settings JSON). Omit hostGroupIds to leave the + bindings unchanged; send an empty array to clear them. Returns the + number of clients whose label was updated. + url: '#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated' - depth: 2 title: Remove a group. Deletes the client_groups row and clears the group label from every matching client (both clients.group_name and the inbound @@ -562,24 +571,32 @@ _openapi: disabled by hand stays disabled. Returns the count of successfully reset clients. id: zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-its-quota-had-disabled-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-a-client-disabled-by-hand-stays-disabled-returns-the-count-of-successfully-reset-clients - - content: List all client groups with their member counts. Merges persisted - groups (rows in client_groups, including empty placeholders) with the - distinct group_name values currently set on clients. Sorted - alphabetically (case-insensitive). - id: list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive + - content: List all client groups with their member counts and the host groups + bound to each. Merges persisted groups (rows in client_groups, + including empty placeholders) with the distinct group_name values + currently set on clients. Sorted alphabetically (case-insensitive). + id: list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive + - content: Replace the host groups attached to a client group. Clients in this + group receive the bound host groups instead of the inbound default + host pool; other clients are unaffected. An empty array clears the + bindings. Returns the saved host group IDs. + id: replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids - content: Return just the email list of clients that currently belong to the given group. Useful for fanning a single bulk action over an entire group without round-tripping the full client list. id: return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list - - content: Create a new empty (placeholder) group. The group becomes selectable in - client forms and the filter drawer even before any client is added to - it. Errors if a group with the same name already exists. - id: create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists - - content: Rename a group. The new name is applied to the client_groups row AND + - content: Create a new group, optionally with host rules bound to it. The group + becomes selectable in client forms and the filter drawer even before + any client is added to it. Host group IDs are validated before the + group is created. Errors if a group with the same name already exists. + id: create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists + - content: Rename a group and optionally replace its host rules in one + transaction. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the - client entry inside every owning inbound's settings JSON) in a single - transaction. Returns the number of clients whose label was updated. - id: rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated + client entry inside every owning inbound's settings JSON). Omit + hostGroupIds to leave the bindings unchanged; send an empty array to + clear them. Returns the number of clients whose label was updated. + id: rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated - content: Remove a group. Deletes the client_groups row and clears the group label from every matching client (both clients.group_name and the inbound settings JSON). The clients themselves are NOT deleted — use @@ -866,7 +883,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/content/docs/fa/reference/api/clients.mdx b/docs/content/docs/fa/reference/api/clients.mdx index ef08359ca..0d8523ff1 100644 --- a/docs/content/docs/fa/reference/api/clients.mdx +++ b/docs/content/docs/fa/reference/api/clients.mdx @@ -216,7 +216,7 @@ _openapi: group_name values currently set on clients. Sorted alphabetically (case-insensitive). url: >- - #list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive + #list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive - depth: 2 title: >- Return just the email list of clients that currently belong to the given @@ -230,7 +230,7 @@ _openapi: client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists. url: >- - #create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists + #create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists - depth: 2 title: >- Rename a group. The new name is applied to the client_groups row AND @@ -238,7 +238,7 @@ _openapi: client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated. url: >- - #rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated + #rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated - depth: 2 title: >- Remove a group. Deletes the client_groups row and clears the group label @@ -514,7 +514,7 @@ _openapi: distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive). id: >- - list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive + list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive - content: >- Return just the email list of clients that currently belong to the given group. Useful for fanning a single bulk action over an entire @@ -526,14 +526,14 @@ _openapi: in client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists. id: >- - create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists + create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists - content: >- Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated. id: >- - rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated + rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated - content: >- Remove a group. Deletes the client_groups row and clears the group label from every matching client (both clients.group_name and the diff --git a/docs/content/docs/ru/reference/api/clients.mdx b/docs/content/docs/ru/reference/api/clients.mdx index 7d8dd6ff9..e6bbf9bcf 100644 --- a/docs/content/docs/ru/reference/api/clients.mdx +++ b/docs/content/docs/ru/reference/api/clients.mdx @@ -216,7 +216,7 @@ _openapi: group_name values currently set on clients. Sorted alphabetically (case-insensitive). url: >- - #list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive + #list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive - depth: 2 title: >- Return just the email list of clients that currently belong to the given @@ -230,7 +230,7 @@ _openapi: client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists. url: >- - #create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists + #create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists - depth: 2 title: >- Rename a group. The new name is applied to the client_groups row AND @@ -238,7 +238,7 @@ _openapi: client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated. url: >- - #rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated + #rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated - depth: 2 title: >- Remove a group. Deletes the client_groups row and clears the group label @@ -514,7 +514,7 @@ _openapi: distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive). id: >- - list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive + list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive - content: >- Return just the email list of clients that currently belong to the given group. Useful for fanning a single bulk action over an entire @@ -526,14 +526,14 @@ _openapi: in client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists. id: >- - create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists + create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists - content: >- Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated. id: >- - rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated + rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated - content: >- Remove a group. Deletes the client_groups row and clears the group label from every matching client (both clients.group_name and the diff --git a/docs/content/docs/zh/reference/api/clients.mdx b/docs/content/docs/zh/reference/api/clients.mdx index bfbb1b6ad..aa9eda9c2 100644 --- a/docs/content/docs/zh/reference/api/clients.mdx +++ b/docs/content/docs/zh/reference/api/clients.mdx @@ -175,7 +175,7 @@ _openapi: 列出所有客户端分组及其成员数量。将持久化分组(client_groups 中的记录,包括空占位符) 与当前在客户端上设置的去重后的 group_name 值合并。按字母顺序排序(不区分大小写)。 url: >- - #list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive + #list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive - depth: 2 title: >- 仅返回当前属于指定分组的客户端 email 列表。适用于将单个批量操作扇出到整个分组,而无需 @@ -187,14 +187,14 @@ _openapi: 创建一个新的空(占位)分组。即使尚未向其添加任何客户端,该分组也会在客户端表单和筛选 抽屉中变为可选。若已存在同名分组,则报错。 url: >- - #create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists + #create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists - depth: 2 title: >- 重命名分组。新名称会应用到 client_groups 记录,并在单个事务中传播到每个匹配的客户端 (包括 clients.group_name 以及每个所属入站的 settings JSON 内的客户端条目)。返回 标签被更新的客户端数量。 url: >- - #rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated + #rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated - depth: 2 title: >- 移除分组。删除 client_groups 记录,并从每个匹配的客户端清除分组标签(包括 @@ -412,7 +412,7 @@ _openapi: 列出所有客户端分组及其成员数量。将持久化分组(client_groups 中的记录,包括空占位符) 与当前在客户端上设置的去重后的 group_name 值合并。按字母顺序排序(不区分大小写)。 id: >- - list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive + list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive - content: >- 仅返回当前属于指定分组的客户端 email 列表。适用于将单个批量操作扇出到整个分组,而无需 往返获取完整的客户端列表。 @@ -422,13 +422,13 @@ _openapi: 创建一个新的空(占位)分组。即使尚未向其添加任何客户端,该分组也会在客户端表单和筛选 抽屉中变为可选。若已存在同名分组,则报错。 id: >- - create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists + create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists - content: >- 重命名分组。新名称会应用到 client_groups 记录,并在单个事务中传播到每个匹配的客户端 (包括 clients.group_name 以及每个所属入站的 settings JSON 内的客户端条目)。返回 标签被更新的客户端数量。 id: >- - rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated + rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated - content: >- 移除分组。删除 client_groups 记录,并从每个匹配的客户端清除分组标签(包括 clients.group_name 以及入站 settings JSON)。客户端本身不会被删除——如需删除请先按 diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 4781420a0..9d86bced4 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -11801,7 +11801,7 @@ "tags": [ "Clients" ], - "summary": "List all client groups with their member counts. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).", + "summary": "List all client groups with their member counts and the host groups bound to each. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).", "operationId": "get_panel_api_clients_groups", "responses": { "200": { @@ -11824,12 +11824,18 @@ "success": true, "obj": [ { + "id": 1, "name": "customer-a", - "clientCount": 5 + "clientCount": 5, + "hostGroupIds": [ + "cdn-front" + ] }, { + "id": 2, "name": "internal", - "clientCount": 0 + "clientCount": 0, + "hostGroupIds": [] } ] } @@ -11839,6 +11845,70 @@ } } }, + "/panel/api/clients/groups/{name}/hosts": { + "post": { + "tags": [ + "Clients" + ], + "summary": "Replace the host groups attached to a client group. Clients in this group receive the bound host groups instead of the inbound default host pool; other clients are unaffected. An empty array clears the bindings. Returns the saved host group IDs.", + "operationId": "post_panel_api_clients_groups_name_hosts", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "description": "Group name (URL-encoded).", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + }, + "example": { + "hostGroupIds": [ + "cdn-front" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "hostGroupIds": [ + "cdn-front" + ] + } + } + } + } + } + } + } + }, "/panel/api/clients/groups/{name}/emails": { "get": { "tags": [ @@ -11893,7 +11963,7 @@ "tags": [ "Clients" ], - "summary": "Create a new empty (placeholder) group. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists.", + "summary": "Create a new group, optionally with host rules bound to it. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Host group IDs are validated before the group is created. Errors if a group with the same name already exists.", "operationId": "post_panel_api_clients_groups_create", "requestBody": { "required": true, @@ -11903,7 +11973,10 @@ "type": "object" }, "example": { - "name": "customer-a" + "name": "customer-a", + "hostGroupIds": [ + "cdn-front" + ] } } } @@ -11942,7 +12015,7 @@ "tags": [ "Clients" ], - "summary": "Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated.", + "summary": "Rename a group and optionally replace its host rules in one transaction. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON). Omit hostGroupIds to leave the bindings unchanged; send an empty array to clear them. Returns the number of clients whose label was updated.", "operationId": "post_panel_api_clients_groups_rename", "requestBody": { "required": true, @@ -11953,7 +12026,10 @@ }, "example": { "oldName": "customer-a", - "newName": "tier-1" + "newName": "tier-1", + "hostGroupIds": [ + "cdn-front" + ] } } } diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 4781420a0..9d86bced4 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -11801,7 +11801,7 @@ "tags": [ "Clients" ], - "summary": "List all client groups with their member counts. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).", + "summary": "List all client groups with their member counts and the host groups bound to each. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).", "operationId": "get_panel_api_clients_groups", "responses": { "200": { @@ -11824,12 +11824,18 @@ "success": true, "obj": [ { + "id": 1, "name": "customer-a", - "clientCount": 5 + "clientCount": 5, + "hostGroupIds": [ + "cdn-front" + ] }, { + "id": 2, "name": "internal", - "clientCount": 0 + "clientCount": 0, + "hostGroupIds": [] } ] } @@ -11839,6 +11845,70 @@ } } }, + "/panel/api/clients/groups/{name}/hosts": { + "post": { + "tags": [ + "Clients" + ], + "summary": "Replace the host groups attached to a client group. Clients in this group receive the bound host groups instead of the inbound default host pool; other clients are unaffected. An empty array clears the bindings. Returns the saved host group IDs.", + "operationId": "post_panel_api_clients_groups_name_hosts", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "description": "Group name (URL-encoded).", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + }, + "example": { + "hostGroupIds": [ + "cdn-front" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "hostGroupIds": [ + "cdn-front" + ] + } + } + } + } + } + } + } + }, "/panel/api/clients/groups/{name}/emails": { "get": { "tags": [ @@ -11893,7 +11963,7 @@ "tags": [ "Clients" ], - "summary": "Create a new empty (placeholder) group. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists.", + "summary": "Create a new group, optionally with host rules bound to it. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Host group IDs are validated before the group is created. Errors if a group with the same name already exists.", "operationId": "post_panel_api_clients_groups_create", "requestBody": { "required": true, @@ -11903,7 +11973,10 @@ "type": "object" }, "example": { - "name": "customer-a" + "name": "customer-a", + "hostGroupIds": [ + "cdn-front" + ] } } } @@ -11942,7 +12015,7 @@ "tags": [ "Clients" ], - "summary": "Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated.", + "summary": "Rename a group and optionally replace its host rules in one transaction. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON). Omit hostGroupIds to leave the bindings unchanged; send an empty array to clear them. Returns the number of clients whose label was updated.", "operationId": "post_panel_api_clients_groups_rename", "requestBody": { "required": true, @@ -11953,7 +12026,10 @@ }, "example": { "oldName": "customer-a", - "newName": "tier-1" + "newName": "tier-1", + "hostGroupIds": [ + "cdn-front" + ] } } } diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index b725f84f1..a54db2dc7 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1702,9 +1702,18 @@ export const sections: readonly Section[] = [ method: 'GET', path: '/panel/api/clients/groups', summary: - 'List all client groups with their member counts. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).', + 'List all client groups with their member counts and the host groups bound to each. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).', response: - '{\n "success": true,\n "obj": [\n { "name": "customer-a", "clientCount": 5 },\n { "name": "internal", "clientCount": 0 }\n ]\n}', + '{\n "success": true,\n "obj": [\n { "id": 1, "name": "customer-a", "clientCount": 5, "hostGroupIds": ["cdn-front"] },\n { "id": 2, "name": "internal", "clientCount": 0, "hostGroupIds": [] }\n ]\n}', + }, + { + method: 'POST', + path: '/panel/api/clients/groups/:name/hosts', + summary: + 'Replace the host groups attached to a client group. Clients in this group receive the bound host groups instead of the inbound default host pool; other clients are unaffected. An empty array clears the bindings. Returns the saved host group IDs.', + params: [{ name: 'name', in: 'path', type: 'string', desc: 'Group name (URL-encoded).' }], + body: '{\n "hostGroupIds": ["cdn-front"]\n}', + response: '{\n "success": true,\n "obj": {\n "hostGroupIds": ["cdn-front"]\n }\n}', }, { method: 'GET', @@ -1718,16 +1727,16 @@ export const sections: readonly Section[] = [ method: 'POST', path: '/panel/api/clients/groups/create', summary: - 'Create a new empty (placeholder) group. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists.', - body: '{\n "name": "customer-a"\n}', + 'Create a new group, optionally with host rules bound to it. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Host group IDs are validated before the group is created. Errors if a group with the same name already exists.', + body: '{\n "name": "customer-a",\n "hostGroupIds": ["cdn-front"]\n}', response: '{\n "success": true,\n "obj": {\n "name": "customer-a"\n }\n}', }, { method: 'POST', path: '/panel/api/clients/groups/rename', summary: - "Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated.", - body: '{\n "oldName": "customer-a",\n "newName": "tier-1"\n}', + "Rename a group and optionally replace its host rules in one transaction. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON). Omit hostGroupIds to leave the bindings unchanged; send an empty array to clear them. Returns the number of clients whose label was updated.", + body: '{\n "oldName": "customer-a",\n "newName": "tier-1",\n "hostGroupIds": ["cdn-front"]\n}', response: '{\n "success": true,\n "obj": {\n "affected": 5\n }\n}', }, { diff --git a/frontend/src/pages/groups/GroupHostRulesModal.tsx b/frontend/src/pages/groups/GroupHostRulesModal.tsx new file mode 100644 index 000000000..fe7331559 --- /dev/null +++ b/frontend/src/pages/groups/GroupHostRulesModal.tsx @@ -0,0 +1,63 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Modal, Typography } from 'antd'; + +import type { GroupSummary } from '@/schemas/client'; +import HostGroupSelect from './HostGroupSelect'; + +interface GroupHostRulesModalProps { + open: boolean; + group: GroupSummary | null; + onOpenChange: (open: boolean) => void; + save: (name: string, hostGroupIds: string[]) => Promise; +} + +export default function GroupHostRulesModal({ + open, + group, + onOpenChange, + save, +}: GroupHostRulesModalProps) { + const { t } = useTranslation(); + const [loadingSave, setLoadingSave] = useState(false); + const openGroupKey = open ? (group?.name ?? null) : null; + const [syncedGroupKey, setSyncedGroupKey] = useState(openGroupKey); + const [value, setValue] = useState(group?.hostGroupIds ?? []); + + // Reset during render so the first open frame already shows the saved set. + if (openGroupKey !== syncedGroupKey) { + setSyncedGroupKey(openGroupKey); + if (open) { + setValue(group?.hostGroupIds ?? []); + setLoadingSave(false); + } + } + + async function onOk() { + if (!group || loadingSave) return; + setLoadingSave(true); + try { + if (await save(group.name, value)) onOpenChange(false); + } finally { + setLoadingSave(false); + } + } + + return ( + onOpenChange(false)} + destroyOnHidden + > + + {t('pages.groups.hostRulesHint')} + + + + ); +} diff --git a/frontend/src/pages/groups/GroupsPage.tsx b/frontend/src/pages/groups/GroupsPage.tsx index ba49175ab..407785f70 100644 --- a/frontend/src/pages/groups/GroupsPage.tsx +++ b/frontend/src/pages/groups/GroupsPage.tsx @@ -29,6 +29,7 @@ import { EditOutlined, LinkOutlined, MoreOutlined, + PartitionOutlined, PieChartOutlined, PlusOutlined, RetweetOutlined, @@ -56,6 +57,7 @@ import { type GroupSummary, } from '@/schemas/client'; import { parseMsg } from '@/utils/zodValidate'; +import HostGroupSelect from './HostGroupSelect'; const ClientRecordListSchema = z .array(ClientRecordSchema) @@ -66,9 +68,16 @@ const SubLinksModal = lazy(() => import('../clients/SubLinksModal')); const ClientBulkAdjustModal = lazy(() => import('../clients/ClientBulkAdjustModal')); const GroupAddClientsModal = lazy(() => import('./GroupAddClientsModal')); const GroupRemoveClientsModal = lazy(() => import('./GroupRemoveClientsModal')); +const GroupHostRulesModal = lazy(() => import('./GroupHostRulesModal')); const JSON_HEADERS = { headers: { 'Content-Type': 'application/json' } } as const; +function sameIds(a: string[], b: string[]): boolean { + if (a.length !== b.length) return false; + const ids = new Set(a); + return b.every((id) => ids.has(id)); +} + async function fetchGroups(): Promise { const msg = await HttpUtil.get('/panel/api/clients/groups', undefined, { silent: true }); if (!msg?.success) throw new Error(msg?.msg || 'Failed to load groups'); @@ -117,15 +126,15 @@ export default function GroupsPage() { }, [queryClient]); const createMut = useMutation({ - mutationFn: (body: { name: string }) => + mutationFn: (body: { name: string; hostGroupIds: string[] }) => HttpUtil.post('/panel/api/clients/groups/create', body, JSON_HEADERS), onSuccess: (msg) => { if (msg?.success) invalidate(); }, }); - const renameMut = useMutation({ - mutationFn: (body: { oldName: string; newName: string }) => + const editMut = useMutation({ + mutationFn: (body: { oldName: string; newName: string; hostGroupIds: string[] }) => HttpUtil.post('/panel/api/clients/groups/rename', body, JSON_HEADERS), onSuccess: (msg) => { if (msg?.success) invalidate(); @@ -148,14 +157,30 @@ export default function GroupsPage() { }, }); + const groupHostsMut = useMutation({ + mutationFn: (body: { name: string; hostGroupIds: string[] }) => + HttpUtil.post( + `/panel/api/clients/groups/${encodeURIComponent(body.name)}/hosts`, + { hostGroupIds: body.hostGroupIds }, + JSON_HEADERS, + ), + onSuccess: (msg) => { + if (msg?.success) invalidate(); + }, + }); + const [createOpen, setCreateOpen] = useState(false); const [createName, setCreateName] = useState(''); + const [createHostGroupIds, setCreateHostGroupIds] = useState([]); - const [renameOpen, setRenameOpen] = useState(false); - const [renameTarget, setRenameTarget] = useState(null); - const [renameValue, setRenameValue] = useState(''); + const [editOpen, setEditOpen] = useState(false); + const [editTarget, setEditTarget] = useState(null); + const [editName, setEditName] = useState(''); + const [editHostGroupIds, setEditHostGroupIds] = useState([]); const [subLinksOpen, setSubLinksOpen] = useState(false); + const [hostRulesOpen, setHostRulesOpen] = useState(false); + const [hostRulesGroup, setHostRulesGroup] = useState(null); const [adjustOpen, setAdjustOpen] = useState(false); const [addClientsOpen, setAddClientsOpen] = useState(false); const [removeClientsOpen, setRemoveClientsOpen] = useState(false); @@ -189,6 +214,7 @@ export default function GroupsPage() { function openCreate() { setCreateName(''); + setCreateHostGroupIds([]); setCreateOpen(true); } @@ -199,39 +225,50 @@ export default function GroupsPage() { messageApi.error(t('pages.groups.renameCollision', { name })); return; } - const msg = await createMut.mutateAsync({ name }); + const msg = await createMut.mutateAsync({ name, hostGroupIds: createHostGroupIds }); if (msg?.success) { messageApi.success(t('pages.groups.createSuccess', { name })); setCreateOpen(false); } } - function openRename(g: GroupSummary) { - setRenameTarget(g); - setRenameValue(g.name); - setRenameOpen(true); + function openEdit(g: GroupSummary) { + setEditTarget(g); + setEditName(g.name); + setEditHostGroupIds(g.hostGroupIds ?? []); + setEditOpen(true); } - async function confirmRename() { - if (!renameTarget) return; - const next = renameValue.trim(); - if (!next || next === renameTarget.name) { - setRenameOpen(false); - return; - } + async function confirmEdit() { + if (!editTarget) return; + const next = editName.trim(); + if (!next) return; + const nameChanged = next !== editTarget.name; if ( - groups.some( - (g) => g.name.toLowerCase() === next.toLowerCase() && g.name !== renameTarget.name, - ) + nameChanged && + groups.some((g) => g.name !== editTarget.name && g.name.toLowerCase() === next.toLowerCase()) ) { messageApi.error(t('pages.groups.renameCollision', { name: next })); return; } - const msg = await renameMut.mutateAsync({ oldName: renameTarget.name, newName: next }); + const previousHostGroupIds = editTarget.hostGroupIds ?? []; + if (!nameChanged && sameIds(previousHostGroupIds, editHostGroupIds)) { + setEditOpen(false); + return; + } + const msg = await editMut.mutateAsync({ + oldName: editTarget.name, + newName: next, + hostGroupIds: editHostGroupIds, + }); if (msg?.success) { const affected = (msg.obj as { affected?: number } | undefined)?.affected ?? 0; - messageApi.success(t('pages.groups.renameSuccess', { count: affected })); - setRenameOpen(false); + if (nameChanged) { + messageApi.success(t('pages.groups.renameSuccess', { count: affected })); + } else { + messageApi.success(t('pages.groups.hostRulesSaved', { name: next })); + } + setEditOpen(false); } } @@ -287,6 +324,21 @@ export default function GroupsPage() { setAddClientsOpen(true); } + function openHostRulesFor(g: GroupSummary) { + setHostRulesGroup(g); + setHostRulesOpen(true); + } + + async function saveHostRules(name: string, hostGroupIds: string[]): Promise { + const msg = await groupHostsMut.mutateAsync({ name, hostGroupIds }); + if (msg?.success) { + messageApi.success(t('pages.groups.hostRulesSaved', { name })); + return true; + } + messageApi.error(msg?.msg || t('somethingWentWrong')); + return false; + } + function openRemoveClientsFor(g: GroupSummary) { if (!g.clientCount) { messageApi.info(t('pages.groups.emptyForAction')); @@ -380,10 +432,16 @@ export default function GroupsPage() { onClick: () => openAddClientsFor(row), }, { - key: 'rename', + key: 'hostRules', + icon: , + label: t('pages.groups.hostRules'), + onClick: () => openHostRulesFor(row), + }, + { + key: 'edit', icon: , - label: t('pages.groups.rename'), - onClick: () => openRename(row), + label: t('pages.groups.editGroup'), + onClick: () => openEdit(row), }, { type: 'divider' }, { @@ -416,7 +474,7 @@ export default function GroupsPage() { { title: t('pages.clients.actions'), key: 'actions', - width: 90, + width: 130, render: (_v, row) => ( @@ -428,14 +486,24 @@ export default function GroupsPage() { icon={} /> - + + ), + }, { title: t('pages.groups.upload'), dataIndex: 'up', @@ -623,33 +708,48 @@ export default function GroupsPage() { autoFocus /> + + + setRenameOpen(false)} - onOk={confirmRename} + confirmLoading={editMut.isPending} + onCancel={() => setEditOpen(false)} + onOk={confirmEdit} destroyOnHidden >
- + setRenameValue(e.target.value)} - onPressEnter={confirmRename} + id={`${uid}-edit-name`} + value={editName} + onChange={(e) => setEditName(e.target.value)} + onPressEnter={confirmEdit} placeholder={t('pages.clients.groupPlaceholder')} autoFocus /> + + +
+ + + + void; + ariaLabel?: string; +} + +// Shared host-rule picker for the group create, edit, and quick-assign dialogs. +export default function HostGroupSelect({ value, onChange, ariaLabel }: HostGroupSelectProps) { + const { t } = useTranslation(); + const { hosts, loading } = useHostsQuery(); + // /hosts/list returns one grouped entry per groupId, so option values are unique. + const options = hosts.map((host) => ({ + value: host.groupId, + label: host.remark || host.groupId, + })); + + return ( + + ) : ( + + ))} + + { + setLoading(true); + setPage(1); + setSearch(e.target.value); + }} + /> + {!sourceId && ( + ({ value })) ?? []} + filterOption={(input, option) => + option?.value.toLowerCase().includes(input.toLowerCase()) ?? false + } + onChange={(value) => { + setLoading(true); + setPage(1); + setGroup(value); + }} + /> + )} + + + + + + + {t('pages.inbounds.attachClientsSelectedCount', { + selected, + total: frozen?.eligible ?? rows?.eligible ?? 0, + })} + + + {loadError && } + {!sourceId && !loading && !search && !group && rows?.total === 0 && ( + + )} +
+ + size="small" + rowKey="id" + columns={columns} + loading={loading} + dataSource={rows?.items ?? []} + virtual + scroll={{ x: 620, y: 280 }} + pagination={{ + current: page, + total: rows?.total ?? 0, + pageSize: PAGE_SIZE, + showSizeChanger: false, + onChange: (next) => { + if (page !== next) { + setLoading(true); + setPage(next); + } + }, + }} + rowSelection={{ + selectedRowKeys: (rows?.items ?? []) + .filter( + (row) => + !row.alreadyAttached && + (frozen + ? inFrozenScope(frozen, row) && !choices.has(row.id) + : choices.has(row.id)), + ) + .map((row) => row.id), + onChange: selectRows, + getCheckboxProps: (row) => ({ + disabled: + !!busy || + loading || + !targets.length || + row.alreadyAttached || + (!!frozen && !inFrozenScope(frozen, row)), + 'aria-label': row.email, + }), + }} + /> +
+ {exclusions.length > 0 && ( + + {t('pages.inbounds.attachExcludedClients')} + + {exclusions.map(([id, email]) => ( + + ))} + + + {lastExclusionPage > 1 && ( + + )} + + )} +
+ + ); +} diff --git a/frontend/src/pages/inbounds/clients/AttachClientsModal.tsx b/frontend/src/pages/inbounds/clients/AttachClientsModal.tsx index 4894dff0f..16bbe7fbf 100644 --- a/frontend/src/pages/inbounds/clients/AttachClientsModal.tsx +++ b/frontend/src/pages/inbounds/clients/AttachClientsModal.tsx @@ -1,13 +1,5 @@ -import { useMemo, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Alert, Input, Modal, Select, Space, Table, Tag, Typography, message } from 'antd'; -import type { ColumnsType } from 'antd/es/table'; - -import { selectTagRender } from '@/components/form'; -import { HttpUtil } from '@/utils'; -import { formatInboundLabel } from '@/lib/inbounds/label'; -import { coerceInboundJsonField, type DBInbound } from '@/models/dbinbound'; -import { isInboundMultiUser } from '../list'; +import type { DBInbound } from '@/models/dbinbound'; +import AttachClientPickerModal from './AttachClientPickerModal'; interface AttachClientsModalProps { open: boolean; @@ -17,32 +9,6 @@ interface AttachClientsModalProps { onAttached?: () => void; } -interface BulkAttachResult { - attached?: string[]; - skipped?: string[]; - errors?: string[]; -} - -interface ClientRow { - email: string; - comment: string; - enable: boolean; -} - -function readClientRows(settings: unknown): ClientRow[] { - const parsed = coerceInboundJsonField(settings) as { - clients?: Array<{ email?: string; comment?: string; enable?: boolean }>; - }; - const clients = Array.isArray(parsed?.clients) ? parsed.clients : []; - return clients - .map((c) => ({ - email: (c?.email || '').trim(), - comment: (c?.comment || '').trim(), - enable: c?.enable !== false, - })) - .filter((r) => r.email); -} - export default function AttachClientsModal({ open, source, @@ -50,174 +16,14 @@ export default function AttachClientsModal({ onClose, onAttached, }: AttachClientsModalProps) { - const { t } = useTranslation(); - const [messageApi, messageContextHolder] = message.useMessage(); - const [targetIds, setTargetIds] = useState([]); - const [saving, setSaving] = useState(false); - const [clientRows, setClientRows] = useState([]); - const [selectedEmails, setSelectedEmails] = useState([]); - const [search, setSearch] = useState(''); - - // React resets this during render rather than in an effect so the modal's - // first open frame already shows cleared fields. - const openSource = open ? source : null; - const [syncedSource, setSyncedSource] = useState(null); - if (openSource !== syncedSource) { - setSyncedSource(openSource); - if (openSource) { - const rows = readClientRows(openSource.settings); - setClientRows(rows); - setSelectedEmails(rows.map((r) => r.email)); - setTargetIds([]); - setSearch(''); - } - } - - const targetOptions = useMemo(() => { - if (!source) return []; - return (dbInbounds || []) - .filter((ib) => ib.id !== source.id && isInboundMultiUser(ib)) - .map((ib) => ({ value: ib.id, label: formatInboundLabel(ib.tag, ib.remark) })); - }, [dbInbounds, source]); - - const filteredRows = useMemo(() => { - const q = search.trim().toLowerCase(); - if (!q) return clientRows; - return clientRows.filter( - (r) => r.email.toLowerCase().includes(q) || r.comment.toLowerCase().includes(q), - ); - }, [clientRows, search]); - - const columns: ColumnsType = useMemo( - () => [ - { - title: t('pages.inbounds.email'), - dataIndex: 'email', - key: 'email', - ellipsis: true, - }, - { - title: t('comment'), - dataIndex: 'comment', - key: 'comment', - ellipsis: true, - }, - { - title: t('enable'), - dataIndex: 'enable', - key: 'enable', - width: 90, - render: (enabled: boolean) => - enabled ? ( - {t('enable')} - ) : ( - {t('pages.inbounds.attachClientsStatusDisabled')} - ), - }, - ], - [t], - ); - - async function submit() { - if (!source || targetIds.length === 0 || selectedEmails.length === 0) return; - setSaving(true); - try { - const msg = await HttpUtil.post( - '/panel/api/clients/bulkAttach', - { emails: selectedEmails, inboundIds: targetIds }, - { headers: { 'Content-Type': 'application/json' } }, - ); - if (!msg?.success) { - messageApi.error(msg?.msg || t('somethingWentWrong')); - return; - } - const result = (msg.obj || {}) as BulkAttachResult; - const attached = result.attached?.length ?? 0; - const skipped = result.skipped?.length ?? 0; - const errors = result.errors?.length ?? 0; - if (errors > 0) { - messageApi.warning( - t('pages.inbounds.attachClientsResultMixed', { attached, skipped, errors }), - ); - } else { - messageApi.success(t('pages.inbounds.attachClientsResult', { attached, skipped })); - } - onAttached?.(); - onClose(); - } finally { - setSaving(false); - } - } - + if (!open || !source) return null; return ( - - {messageContextHolder} - - {t('pages.inbounds.attachClientsDesc', { count: clientRows.length })} - - - - {t('pages.inbounds.attachClientsSelectLabel')} - - setSearch(e.target.value)} - placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} - style={{ maxWidth: 320 }} - /> - - {t('pages.inbounds.attachClientsSelectedCount', { - selected: selectedEmails.length, - total: clientRows.length, - })} - - - - size="small" - rowKey="email" - columns={columns} - dataSource={filteredRows} - pagination={false} - scroll={{ y: 280 }} - rowSelection={{ - selectedRowKeys: selectedEmails, - onChange: (keys) => setSelectedEmails(keys as string[]), - preserveSelectedRowKeys: true, - }} - /> - - - {targetOptions.length === 0 ? ( - - ) : ( - setGroupFilter(v)} - options={groupOptions} - placeholder={t('pages.clients.group')} - style={{ minWidth: 160 }} - showSearch={{ optionFilterProp: 'label' }} - /> - )} - - - {t('pages.inbounds.attachClientsSelectedCount', { - selected: selectedEmails.length, - total: attachableCount, - })} - - - - size="small" - rowKey="email" - columns={columns} - dataSource={filteredRows} - pagination={false} - scroll={{ y: 280 }} - rowSelection={{ - selectedRowKeys: selectedEmails, - onChange: (keys) => setSelectedEmails(keys as string[]), - getCheckboxProps: (row) => ({ disabled: row.alreadyAttached }), - preserveSelectedRowKeys: true, - }} - /> - - - )} - + ); } diff --git a/frontend/src/test/attach-clients-modal.test.tsx b/frontend/src/test/attach-clients-modal.test.tsx index c7aa18b12..f2a5cd8ef 100644 --- a/frontend/src/test/attach-clients-modal.test.tsx +++ b/frontend/src/test/attach-clients-modal.test.tsx @@ -1,43 +1,225 @@ -import { describe, expect, it } from 'vitest'; -import { screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; import AttachClientsModal from '@/pages/inbounds/clients/AttachClientsModal'; +import AttachExistingClientsModal from '@/pages/inbounds/clients/AttachExistingClientsModal'; import { DBInbound } from '@/models/dbinbound'; +import { HttpUtil } from '@/utils'; import { renderWithProviders } from './test-utils'; -function sourceInbound() { +function inbound(id: number) { return new DBInbound({ - id: 7, + id, port: 443, listen: '', protocol: 'vless', remark: 'edge', enable: true, - settings: JSON.stringify({ - clients: [ - { id: 'uuid-1', email: 'alice@test' }, - { id: 'uuid-2', email: 'bob@test' }, - ], - decryption: 'none', - }), - streamSettings: JSON.stringify({ network: 'tcp', security: 'none' }), + settings: '{"clients":[{"email":"not-from-api"}]}', + streamSettings: '', sniffing: '', }); } -describe('AttachClientsModal', () => { - it('lists the source clients, selected, when first mounted already open', async () => { +function candidate(id: number, email: string, alreadyAttached = false, inScope = true) { + return { + id, + email, + alreadyAttached, + inScope, + enable: true, + group: 'fixture', + comment: '', + }; +} + +const alice = candidate(1, 'alice@test'); +const bob = candidate(119, 'bob@test'); +const attached = candidate(2, 'attached@test', true); +const page = { + items: [alice, attached], + eligible: 9999, + total: 10000, + groups: ['fixture'], +}; +const url = '/panel/api/clients/attachCandidates'; + +afterEach(() => vi.restoreAllMocks()); + +describe('inbound client attachment picker', () => { + it('loads source membership from the paged API without decoding inbound settings', async () => { + const get = vi.spyOn(HttpUtil, 'get').mockResolvedValue({ success: true, obj: page } as never); renderWithProviders( - {}} />, + {}} />, + ); + expect(await screen.findByText('alice@test')).toBeTruthy(); + expect(screen.queryByText('not-from-api')).toBeNull(); + expect(get).toHaveBeenCalledWith( + url, + expect.objectContaining({ sourceId: 7, page: 1 }), + expect.anything(), + ); + }); + + it('submits a compact frozen selection with exclusions retained across searches', async () => { + const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (path, raw) => { + if (path.endsWith('/job-123')) + return { + success: true, + obj: { + running: false, + result: { attached: 9997, skipped: 0, errors: 0 }, + }, + } as never; + const p = raw as { freeze?: boolean; search?: string }; + return { + success: true, + obj: p.freeze + ? { ...page, items: [], scopeToken: 'frozen-token', maxId: 10000 } + : p.search + ? { ...page, items: [bob], total: 1 } + : page, + } as never; + }); + const post = vi.spyOn(HttpUtil, 'post').mockResolvedValue({ + success: true, + obj: { jobId: 'job-123' }, + } as never); + const close = vi.fn(); + renderWithProviders(); + await screen.findByText('alice@test'); + const aliceBox = screen.getByRole('checkbox', { + name: 'alice@test', + }) as HTMLInputElement; + expect(aliceBox.checked).toBe(false); + expect( + ( + screen.getByRole('checkbox', { + name: 'attached@test', + }) as HTMLInputElement + ).disabled, + ).toBe(true); + fireEvent.click(screen.getByRole('button', { name: /select all eligible clients/i })); + await waitFor(() => expect(aliceBox.checked).toBe(true)); + fireEvent.click(aliceBox); + fireEvent.change(screen.getByRole('searchbox', { name: /search/i }), { + target: { value: 'bob' }, + }); + await screen.findByText('bob@test'); + fireEvent.click(screen.getByRole('checkbox', { name: 'bob@test' })); + expect(screen.getByRole('button', { name: /restore alice@test/i })).toBeTruthy(); + expect(get).toHaveBeenCalledWith( + url, + expect.objectContaining({ inboundIds: '8', freeze: true }), + expect.anything(), ); - expect(await screen.findByText('alice@test')).toBeTruthy(); - expect(screen.getByText('bob@test')).toBeTruthy(); + const submit = screen.getByRole('button', { name: /^attach clients to/i }); + fireEvent.click(submit); + fireEvent.click(submit); + await waitFor(() => expect(close).toHaveBeenCalledOnce()); + expect(post).toHaveBeenCalledExactlyOnceWith( + '/panel/api/clients/bulkAttach', + { + inboundIds: [8], + selection: { + mode: 'allMatching', + sourceId: 0, + scopeToken: 'frozen-token', + excludedClientIds: [1, 119], + search: '', + group: '', + }, + }, + expect.anything(), + ); + }); + it('freezes Select All to the active search and keeps other rows out of the selection', async () => { + const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (path, raw) => { + if (path.endsWith('/job-9')) + return { + success: true, + obj: { + running: false, + result: { attached: 1, skipped: 0, errors: 0 }, + }, + } as never; + const p = raw as { + freeze?: boolean; + search?: string; + scopeSearch?: string; + }; + if (p.freeze) + return { + success: true, + obj: { + ...page, + items: [], + eligible: 1, + scopeToken: 'bob-token', + maxId: 10000, + }, + } as never; + if (p.search) + return { + success: true, + obj: { ...page, items: [bob], total: 1 }, + } as never; + const outside = candidate(1, 'alice@test', false, p.scopeSearch !== 'bob'); + return { + success: true, + obj: { ...page, items: [outside, bob] }, + } as never; + }); + const post = vi.spyOn(HttpUtil, 'post').mockResolvedValue({ + success: true, + obj: { jobId: 'job-9' }, + } as never); + const close = vi.fn(); + renderWithProviders(); + await screen.findByText('alice@test'); + const searchBox = screen.getByRole('searchbox', { name: /search/i }); + fireEvent.change(searchBox, { target: { value: 'bob' } }); + await waitFor(() => expect(screen.queryByText('alice@test')).toBeNull()); + fireEvent.click(screen.getByRole('button', { name: /select all eligible clients/i })); + await waitFor(() => + expect((screen.getByRole('checkbox', { name: 'bob@test' }) as HTMLInputElement).checked).toBe( + true, + ), + ); + expect(get).toHaveBeenCalledWith( + url, + expect.objectContaining({ inboundIds: '8', freeze: true, search: 'bob' }), + expect.anything(), + ); - const boxes = screen.getAllByRole('checkbox') as HTMLInputElement[]; - const rowBoxes = boxes.slice(1); - expect(rowBoxes).toHaveLength(2); - expect(rowBoxes.every((b) => b.checked)).toBe(true); + fireEvent.change(searchBox, { target: { value: '' } }); + const aliceBox = (await screen.findByRole('checkbox', { + name: 'alice@test', + })) as HTMLInputElement; + expect(aliceBox.checked).toBe(false); + expect(aliceBox.disabled).toBe(true); + expect((screen.getByRole('checkbox', { name: 'bob@test' }) as HTMLInputElement).checked).toBe( + true, + ); + + fireEvent.click(screen.getByRole('button', { name: /^attach clients to/i })); + await waitFor(() => expect(close).toHaveBeenCalledOnce()); + expect(post).toHaveBeenCalledExactlyOnceWith( + '/panel/api/clients/bulkAttach', + { + inboundIds: [8], + selection: { + mode: 'allMatching', + sourceId: 0, + scopeToken: 'bob-token', + excludedClientIds: [], + search: 'bob', + group: '', + }, + }, + expect.anything(), + ); }); }); diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index c1393c6db..9380e28df 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -3,6 +3,7 @@ package controller import ( "encoding/json" "errors" + "fmt" "net/http" "strconv" "strings" @@ -53,6 +54,7 @@ func NewClientController(g *gin.RouterGroup) *ClientController { func (a *ClientController) initRouter(g *gin.RouterGroup) { g.GET("/list", a.list) g.GET("/list/paged", a.listPaged) + g.GET("/attachCandidates", a.attachCandidates) g.GET("/get", a.get) g.GET("/get/:email", a.get) g.GET("/get/subId/:subId", a.getBySubId) @@ -88,6 +90,7 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) { g.POST("/bulkDel", a.bulkDelete) g.POST("/bulkCreate", a.bulkCreate) g.POST("/bulkAttach", a.bulkAttach) + g.GET("/bulkAttach/:id", a.attachStatus) g.POST("/bulkDetach", a.bulkDetach) g.POST("/bulkResetTraffic", a.bulkResetTraffic) g.POST("/resetTraffic/:email", a.resetTrafficByEmail) @@ -138,6 +141,20 @@ func (a *ClientController) listPaged(c *gin.Context) { jsonObj(c, resp, nil) } +func (a *ClientController) attachCandidates(c *gin.Context) { + var params service.AttachCandidateParams + if err := c.ShouldBindQuery(¶ms); err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err) + return + } + result, err := a.clientService.ListAttachCandidates(c.Request.Context(), params) + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err) + return + } + jsonObj(c, result, nil) +} + func (a *ClientController) buildClientPayload(rec *model.ClientRecord) (gin.H, error) { inboundIds, err := a.clientService.GetInboundIdsForRecord(rec.Id) if err != nil { @@ -426,8 +443,9 @@ type bulkDeleteRequest struct { } type bulkAttachRequest struct { - Emails []string `json:"emails"` - InboundIds []int `json:"inboundIds"` + Emails []string `json:"emails"` + InboundIds []int `json:"inboundIds"` + Selection *service.AttachSelection `json:"selection,omitempty"` } func (a *ClientController) bulkAttach(c *gin.Context) { @@ -436,6 +454,14 @@ func (a *ClientController) bulkAttach(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if req.Selection != nil { + if len(req.Emails) > 0 { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), fmt.Errorf("use either emails or an attachment selection")) + return + } + a.beginBulkAttach(c, req.InboundIds, *req.Selection) + return + } result, needRestart, err := a.clientService.BulkAttach(&a.inboundService, req.Emails, req.InboundIds) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) diff --git a/internal/web/controller/client_attach_jobs.go b/internal/web/controller/client_attach_jobs.go new file mode 100644 index 000000000..6df6ec03a --- /dev/null +++ b/internal/web/controller/client_attach_jobs.go @@ -0,0 +1,118 @@ +package controller + +import ( + "context" + "errors" + "sync" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "github.com/mhsanaei/3x-ui/v3/internal/util/common" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +// Attachment jobs belong to the same administrator-only API as bulkAttach. +// Keep a bounded in-memory history of results and run one picker job at a time. +type attachJobStore struct { + mu sync.Mutex + running bool + jobs map[string]AttachJobStatus +} + +type AttachJobStatus struct { + Running bool `json:"running" example:"false"` + Result *service.AttachSelectionResult `json:"result,omitempty"` + Error string `json:"error,omitempty"` + ended time.Time +} + +var attachJobs attachJobStore + +func (s *attachJobStore) start(run func() (*service.AttachSelectionResult, error)) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.running { + return "", errors.New("another client attachment is running") + } + if s.jobs == nil { + s.jobs = make(map[string]AttachJobStatus) + } + cutoff := time.Now().Add(-15 * time.Minute) + var oldestID string + var oldest time.Time + for id, status := range s.jobs { + if status.ended.Before(cutoff) { + delete(s.jobs, id) + continue + } + if oldestID == "" || status.ended.Before(oldest) { + oldestID, oldest = id, status.ended + } + } + if len(s.jobs) >= 32 { + delete(s.jobs, oldestID) + } + id := uuid.NewString() + s.jobs[id] = AttachJobStatus{Running: true} + s.running = true + common.GoRecover("client-attachment", func() { + status := AttachJobStatus{Error: "client attachment interrupted"} + defer func() { + s.mu.Lock() + defer s.mu.Unlock() + status.ended = time.Now() + s.jobs[id] = status + s.running = false + }() + result, err := run() + if err != nil { + status.Error = err.Error() + return + } + status.Error = "" + status.Result = result + }) + return id, nil +} + +func (s *attachJobStore) get(id string) (AttachJobStatus, bool) { + s.mu.Lock() + defer s.mu.Unlock() + status, ok := s.jobs[id] + if !status.Running && time.Since(status.ended) > 15*time.Minute { + delete(s.jobs, id) + return AttachJobStatus{}, false + } + return status, ok +} + +func (a *ClientController) beginBulkAttach(c *gin.Context, targets []int, selection service.AttachSelection) { + id, err := attachJobs.start(func() (*service.AttachSelectionResult, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + result, restart, err := a.clientService.BulkAttachSelection(ctx, &a.inboundService, targets, selection) + if restart { + a.xrayService.SetToNeedRestart() + } + if err == nil { + notifyClientsChanged() + } + return result, err + }) + if err != nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + return + } + jsonObj(c, gin.H{"jobId": id}, nil) +} + +func (a *ClientController) attachStatus(c *gin.Context) { + status, ok := attachJobs.get(c.Param("id")) + if !ok { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client attachment status unavailable")) + return + } + jsonObj(c, status, nil) +} diff --git a/internal/web/controller/client_attach_jobs_test.go b/internal/web/controller/client_attach_jobs_test.go new file mode 100644 index 000000000..4e6cea6ad --- /dev/null +++ b/internal/web/controller/client_attach_jobs_test.go @@ -0,0 +1,51 @@ +package controller + +import ( + "errors" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +func TestAttachJobStorePublishesStatusAndPreventsOverlap(t *testing.T) { + var store attachJobStore + block := make(chan struct{}) + id, err := store.start(func() (*service.AttachSelectionResult, error) { + <-block + return &service.AttachSelectionResult{Attached: 9997, Skipped: 1, Errors: 2}, nil + }) + if err != nil { + t.Fatal(err) + } + if status, ok := store.get(id); !ok || !status.Running { + t.Fatalf("accepted job status = %#v, found=%t", status, ok) + } + if _, err := store.start(nil); err == nil { + t.Fatal("overlapping job was accepted") + } + close(block) + + wait := func(id string) AttachJobStatus { + t.Helper() + for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); { + if status, ok := store.get(id); ok && !status.Running { + return status + } + time.Sleep(time.Millisecond) + } + t.Fatal("job did not finish") + return AttachJobStatus{} + } + result := wait(id).Result + if result == nil || result.Attached != 9997 || result.Skipped != 1 || result.Errors != 2 { + t.Fatalf("partial result lost: %#v", result) + } + id, err = store.start(func() (*service.AttachSelectionResult, error) { return nil, errors.New("stale selection") }) + if err != nil { + t.Fatal(err) + } + if status := wait(id); status.Result != nil || status.Error != "stale selection" { + t.Fatalf("failed result lost: %#v", status) + } +} diff --git a/internal/web/service/client_attach_selection.go b/internal/web/service/client_attach_selection.go new file mode 100644 index 000000000..a02179f11 --- /dev/null +++ b/internal/web/service/client_attach_selection.go @@ -0,0 +1,319 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "fmt" + "hash" + "slices" + "strconv" + "strings" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +const attachCandidatePageSize = 100 + +type AttachCandidateParams struct { + SourceID int `form:"sourceId"` + Targets string `form:"inboundIds"` + Page int `form:"page"` + Search string `form:"search"` + Group string `form:"group"` + Freeze bool `form:"freeze"` + // The filter a frozen selection was taken under, which marks rows inScope. + ScopeSearch string `form:"scopeSearch"` + ScopeGroup string `form:"scopeGroup"` +} + +type AttachCandidate struct { + ID int `json:"id" gorm:"column:id" example:"1"` + Email string `json:"email" example:"alice@example.test"` + Group string `json:"group" example:"staff"` + Comment string `json:"comment" example:"Example client"` + Enable bool `json:"enable" example:"true"` + AlreadyAttached bool `json:"alreadyAttached" example:"false"` + InScope bool `json:"inScope" example:"true"` +} + +type AttachCandidatePage struct { + Items []AttachCandidate `json:"items"` + Total int64 `json:"total" example:"120"` + Eligible int64 `json:"eligible" example:"118"` + Groups []string `json:"groups" example:"[\"staff\"]"` + ScopeToken string `json:"scopeToken,omitempty"` + MaxID int `json:"maxId,omitempty"` +} + +type AttachSelection struct { + Mode string `json:"mode"` + SourceID int `json:"sourceId"` + ClientIDs []int `json:"clientIds"` + ExcludedClientIDs []int `json:"excludedClientIds"` + ScopeToken string `json:"scopeToken"` + Search string `json:"search"` + Group string `json:"group"` +} + +type AttachSelectionResult struct { + Attached int `json:"attached" example:"9997"` + Skipped int `json:"skipped" example:"0"` + Errors int `json:"errors" example:"0"` +} + +func attachScope(db *gorm.DB, sourceID int, ids []int) ([]int, error) { + if len(ids) > 100 || sourceID < 0 || (sourceID == 0 && len(ids) == 0) { + return nil, fmt.Errorf("invalid client attachment scope") + } + targets := uniqueInts(ids) + slices.Sort(targets) + inbounds := slices.Clone(targets) + if sourceID > 0 { + if slices.Contains(targets, sourceID) { + return nil, fmt.Errorf("source inbound cannot be a target") + } + inbounds = append(inbounds, sourceID) + } + var rows []model.Inbound + if err := db.Select("id", "protocol").Where("id IN ?", inbounds).Find(&rows).Error; err != nil { + return nil, err + } + if len(rows) != len(inbounds) { + return nil, fmt.Errorf("an inbound in the attachment scope no longer exists") + } + for _, row := range rows { + switch row.Protocol { + case model.VMESS, model.VLESS, model.Trojan, model.Shadowsocks, model.Hysteria, + model.MTProto, model.WireGuard, model.AmneziaWG, model.TUIC, model.MASQUE: + default: + return nil, fmt.Errorf("inbound %d does not support attaching clients", row.Id) + } + } + return targets, nil +} + +func attachCandidates(db *gorm.DB, sourceID int) *gorm.DB { + q := db.Table("clients AS c").Where("c.email <> ''") + if sourceID > 0 { + q = q.Where("EXISTS (SELECT 1 FROM client_inbounds AS src WHERE src.client_id = c.id AND src.inbound_id = ?)", sourceID) + } + return q +} + +const attachedToTargetsSQL = "(SELECT COUNT(*) FROM client_inbounds AS dst WHERE dst.client_id = c.id AND dst.inbound_id IN ?) = ?" + +func eligibleAttachCandidates(q *gorm.DB, targets []int) *gorm.DB { + if len(targets) > 0 { + return q.Where("NOT ("+attachedToTargetsSQL+")", targets, len(targets)) + } + return q +} + +// attachFilter is the search and group predicate of a candidate page or a frozen scope. +func attachFilter(sourceID int, search, group string) (string, []any) { + var clauses []string + var args []any + if sourceID == 0 && group != "" { + clauses = append(clauses, "c.group_name = ?") + args = append(args, group) + } + if search = strings.TrimSpace(search); search != "" { + col := "c.group_name" + if sourceID > 0 { + col = "c.comment" + } + const like = " LIKE ? ESCAPE '\\'" + predicates := []string{"LOWER(c.email)" + like, "LOWER(" + col + ")" + like} + pattern := "%" + escapeLikeLiteral(strings.ToLower(search)) + "%" + args = append(args, pattern, pattern) + for _, variant := range caseVariants(search) { + pattern := "%" + escapeLikeLiteral(variant) + "%" + predicates = append(predicates, "c.email"+like, col+like) + args = append(args, pattern, pattern) + } + clauses = append(clauses, "("+strings.Join(predicates, " OR ")+")") + } + return strings.Join(clauses, " AND "), args +} + +func filteredAttachCandidates(q *gorm.DB, sourceID int, search, group string) *gorm.DB { + if filter, args := attachFilter(sourceID, search, group); filter != "" { + return q.Where(filter, args...) + } + return q +} + +func writeAttachID(h hash.Hash, id int) { + var buf [8]byte + binary.BigEndian.PutUint64(buf[:], uint64(id)) + _, _ = h.Write(buf[:]) +} + +func attachScopeHash(sourceID int, targets []int) hash.Hash { + h := sha256.New() + writeAttachID(h, sourceID) + writeAttachID(h, len(targets)) + for _, id := range targets { + writeAttachID(h, id) + } + return h +} + +func (s *ClientService) ListAttachCandidates(ctx context.Context, p AttachCandidateParams) (*AttachCandidatePage, error) { + if p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 256 || len(p.Group) > 256 || + len(p.ScopeSearch) > 256 || len(p.ScopeGroup) > 256 { + return nil, fmt.Errorf("invalid client attachment page") + } + db := database.GetDB().WithContext(ctx) + var ids []int + if p.Targets != "" { + for part := range strings.SplitSeq(p.Targets, ",") { + id, err := strconv.Atoi(part) + if err != nil || id < 1 || len(ids) >= 100 { + return nil, fmt.Errorf("invalid attachment target ID") + } + ids = append(ids, id) + } + } + targets, err := attachScope(db, p.SourceID, ids) + if err != nil { + return nil, err + } + resp := &AttachCandidatePage{Items: []AttachCandidate{}, Groups: []string{}} + eligible := eligibleAttachCandidates(attachCandidates(db, p.SourceID), targets) + if p.Freeze { + if len(targets) == 0 { + return nil, fmt.Errorf("select attachment targets first") + } + h := attachScopeHash(p.SourceID, targets) + rows, err := filteredAttachCandidates(eligible, p.SourceID, p.Search, p.Group).Select("c.id").Order("c.id").Rows() + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var id int + if err := rows.Scan(&id); err != nil { + return nil, err + } + writeAttachID(h, id) + resp.Eligible++ + resp.MaxID = id + } + if err := rows.Err(); err != nil { + return nil, err + } + writeAttachID(h, resp.MaxID) + resp.ScopeToken = strconv.Itoa(resp.MaxID) + "." + hex.EncodeToString(h.Sum(nil)) + return resp, nil + } + if err := eligible.Count(&resp.Eligible).Error; err != nil { + return nil, err + } + + if p.SourceID == 0 { + if err := attachCandidates(db, 0).Where("c.group_name <> ''"). + Distinct("c.group_name").Order("c.group_name").Limit(100).Pluck("c.group_name", &resp.Groups).Error; err != nil { + return nil, err + } + } + filtered := filteredAttachCandidates(attachCandidates(db, p.SourceID), p.SourceID, p.Search, p.Group) + if err := filtered.Count(&resp.Total).Error; err != nil { + return nil, err + } + columns, args := "c.id, c.email, c.group_name AS \"group\", c.comment, c.enable, ", []any{} + if len(targets) == 0 { + columns += "false AS already_attached, " + } else { + columns += attachedToTargetsSQL + " AS already_attached, " + args = append(args, targets, len(targets)) + } + if scope, scopeArgs := attachFilter(p.SourceID, p.ScopeSearch, p.ScopeGroup); scope == "" { + columns += "true AS in_scope" + } else { + columns += "(" + scope + ") AS in_scope" + args = append(args, scopeArgs...) + } + filtered = filtered.Select(columns, args...) + err = filtered.Order("c.id").Offset(max(0, p.Page-1) * attachCandidatePageSize). + Limit(attachCandidatePageSize).Scan(&resp.Items).Error + return resp, err +} + +func (s *ClientService) BulkAttachSelection(ctx context.Context, inboundSvc *InboundService, targets []int, selection AttachSelection) (*AttachSelectionResult, bool, error) { + db := database.GetDB().WithContext(ctx) + targets, err := attachScope(db, selection.SourceID, targets) + if err != nil { + return nil, false, err + } + if len(targets) == 0 { + return nil, false, fmt.Errorf("select attachment targets first") + } + stale := fmt.Errorf("client attachment selection changed; clear the selection and select clients again") + q := eligibleAttachCandidates(attachCandidates(db, selection.SourceID), targets) + var records []*model.ClientRecord + switch selection.Mode { + case "explicit": + if len(selection.ClientIDs) == 0 || len(selection.ClientIDs) > 50_000 || selection.ScopeToken != "" || + len(selection.ExcludedClientIDs) > 0 || selection.Search != "" || selection.Group != "" { + return nil, false, fmt.Errorf("invalid explicit client attachment selection") + } + ids := uniqueInts(selection.ClientIDs) + for _, chunk := range chunkInts(ids, 400) { + var part []*model.ClientRecord + if err := q.Session(&gorm.Session{}).Where("c.id IN ?", chunk).Find(&part).Error; err != nil { + return nil, false, err + } + if len(part) != len(chunk) { + return nil, false, stale + } + records = append(records, part...) + } + case "allMatching": + cutoff, digest, ok := strings.Cut(selection.ScopeToken, ".") + maxID, parseErr := strconv.Atoi(cutoff) + if !ok || parseErr != nil || maxID < 0 || len(digest) != sha256.Size*2 || len(selection.ClientIDs) > 0 || + len(selection.ExcludedClientIDs) > 50_000 || len(selection.Search) > 256 || len(selection.Group) > 256 { + return nil, false, fmt.Errorf("invalid all-clients attachment selection") + } + excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs)) + for _, id := range selection.ExcludedClientIDs { + excluded[id] = struct{}{} + } + h := attachScopeHash(selection.SourceID, targets) + // Find runs the model's read hooks. The cutoff excludes newer clients. + var eligibleRecords []*model.ClientRecord + q = filteredAttachCandidates(q, selection.SourceID, selection.Search, selection.Group) + if err := q.Where("c.id <= ?", maxID).Order("c.id").Find(&eligibleRecords).Error; err != nil { + return nil, false, err + } + records = eligibleRecords[:0] + for _, record := range eligibleRecords { + writeAttachID(h, record.Id) + if _, skip := excluded[record.Id]; skip { + delete(excluded, record.Id) + continue + } + records = append(records, record) + } + writeAttachID(h, maxID) + if len(excluded) > 0 || hex.EncodeToString(h.Sum(nil)) != digest { + return nil, false, stale + } + default: + return nil, false, fmt.Errorf("invalid client attachment selection mode") + } + if err := ctx.Err(); err != nil { + return nil, false, err + } + result, restart, err := s.bulkAttachRecords(inboundSvc, records, targets, &BulkAttachResult{}) + if err != nil { + return nil, restart, err + } + return &AttachSelectionResult{Attached: len(result.Attached), Skipped: len(result.Skipped), Errors: len(result.Errors)}, restart, nil +} diff --git a/internal/web/service/client_attach_selection_test.go b/internal/web/service/client_attach_selection_test.go new file mode 100644 index 000000000..eb2ecd84a --- /dev/null +++ b/internal/web/service/client_attach_selection_test.go @@ -0,0 +1,278 @@ +package service + +import ( + "context" + "fmt" + "slices" + "strconv" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestAttachCandidatesSelection(t *testing.T) { + setupBulkDB(t) + testAttachCandidatesSelection(t) +} + +func TestAttachCandidatesSelectionPostgres(t *testing.T) { + durablePostgresDB(t) + testAttachCandidatesSelection(t) +} + +func testAttachCandidatesSelection(t *testing.T) { + t.Helper() + db := database.GetDB() + ctx := context.Background() + svc := &ClientService{} + suffix := time.Now().UnixNano() + source := durableTestInbound(nil, fmt.Sprintf("attach-source-%d", suffix), 42541) + target := durableTestInbound(nil, fmt.Sprintf("attach-target-%d", suffix), 42542) + if err := db.Create(source).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(target).Error; err != nil { + t.Fatal(err) + } + email := func(i int) string { return fmt.Sprintf("candidate-%d-%04d@x", suffix, i) } + clients := make([]model.Client, 121) + for i := range clients { + clients[i] = model.Client{ + Email: email(i), SubID: fmt.Sprintf("test%d", i), Enable: i != 2, Group: "fixture", + ID: fmt.Sprintf("11111111-1111-4111-8111-%012d", i), + } + } + clients[119].Comment = "Журнал match_% only" + keepAlive := model.KeepAliveValue("19") + clients[3].KeepAlive = &keepAlive + if err := svc.SyncInbound(nil, source.Id, clients); err != nil { + t.Fatal(err) + } + if err := svc.SyncInbound(nil, target.Id, clients[:1]); err != nil { + t.Fatal(err) + } + p := AttachCandidateParams{SourceID: source.Id, Targets: strconv.Itoa(target.Id)} + first, err := svc.ListAttachCandidates(ctx, p) + if err != nil || len(first.Items) != 100 || first.Total != 121 || first.Eligible != 120 || !first.Items[0].AlreadyAttached || first.Items[2].Enable { + t.Fatalf("candidate first page = %+v, err=%v", first, err) + } + p.Page = 2 + second, err := svc.ListAttachCandidates(ctx, p) + if err != nil || len(second.Items) != 21 { + t.Fatalf("second page size = %v, err=%v", second, err) + } + search, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{SourceID: source.Id, Targets: p.Targets, Search: "журнал MATCH_%"}) + if err != nil || len(search.Items) != 1 || search.Items[0].Email != email(119) { + t.Fatalf("literal source search = %+v, err=%v", search, err) + } + group, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{Targets: p.Targets, Group: "fixture", Search: fmt.Sprintf("candidate-%d", suffix)}) + if err != nil || group.Total != 121 || !slices.Contains(group.Groups, "fixture") { + t.Fatalf("group search = %+v, err=%v", group, err) + } + + p.Freeze = true + scope, err := svc.ListAttachCandidates(ctx, p) + if err != nil || scope.Eligible != 120 || len(scope.Items) != 0 || scope.ScopeToken == "" { + t.Fatalf("freeze = %+v, err=%v", scope, err) + } + inboundSvc := &InboundService{} + request := AttachSelection{ + Mode: "allMatching", SourceID: source.Id, ScopeToken: scope.ScopeToken, + ExcludedClientIDs: []int{first.Items[1].ID, second.Items[0].ID}, + } + extra := model.Client{Email: email(121), Enable: true} + if err := svc.ApplyInboundClientDelta(nil, source.Id, []model.Client{extra}, nil); err != nil { + t.Fatal(err) + } + if err := svc.ApplyInboundClientDelta(nil, source.Id, nil, []string{clients[2].Email}); err != nil { + t.Fatal(err) + } + if _, _, err := svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, request); err == nil { + t.Fatal("a client that leaves the frozen scope should invalidate the selection") + } + var linked int64 + if err := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", target.Id).Count(&linked).Error; err != nil || linked != 1 { + t.Fatalf("stale selection mutated target: links=%d err=%v", linked, err) + } + if err := svc.ApplyInboundClientDelta(nil, source.Id, clients[2:3], nil); err != nil { + t.Fatal(err) + } + result, _, err := svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, request) + if err != nil || result.Attached != 118 || result.Skipped != 0 || result.Errors != 0 { + t.Fatalf("scoped attach = %+v, err=%v", result, err) + } + got, err := svc.ListForInbound(nil, target.Id) + if err != nil || len(got) != 119 { + t.Fatalf("target has %d clients, err=%v", len(got), err) + } + for _, row := range got { + if row.Email == first.Items[1].Email || row.Email == second.Items[0].Email || row.Email == extra.Email || + (row.Email == email(2) && row.Enable) { + t.Fatalf("invalid attachment %+v", row) + } + } + reloaded, err := inboundSvc.GetInbound(target.Id) + if err != nil { + t.Fatal(err) + } + configured, err := inboundSvc.GetClients(reloaded) + if err != nil { + t.Fatal(err) + } + i := slices.IndexFunc(configured, func(c model.Client) bool { return c.Email == email(3) }) + if i < 0 || configured[i].KeepAlive == nil || *configured[i].KeepAlive != keepAlive { + t.Fatal("bulk attachment discarded the stored client keepalive") + } + explicit := AttachSelection{Mode: "explicit", SourceID: source.Id, ClientIDs: []int{first.Items[1].ID}} + result, _, err = svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, explicit) + if err != nil || result.Attached != 1 { + t.Fatalf("explicit attachment = %+v, err=%v", result, err) + } +} + +func TestFrozenAttachSelectionFollowsFilter(t *testing.T) { + setupBulkDB(t) + testFrozenAttachSelectionFollowsFilter(t) +} + +func TestFrozenAttachSelectionFollowsFilterPostgres(t *testing.T) { + durablePostgresDB(t) + testFrozenAttachSelectionFollowsFilter(t) +} + +func testFrozenAttachSelectionFollowsFilter(t *testing.T) { + t.Helper() + db := database.GetDB() + ctx := context.Background() + svc := &ClientService{} + suffix := time.Now().UnixNano() + source := durableTestInbound(nil, fmt.Sprintf("filter-source-%d", suffix), 42544) + target := durableTestInbound(nil, fmt.Sprintf("filter-target-%d", suffix), 42545) + if err := db.Create(source).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(target).Error; err != nil { + t.Fatal(err) + } + staff := fmt.Sprintf("staff-%d", suffix) + email := func(i int) string { return fmt.Sprintf("filter-%d-%d@x", suffix, i) } + clients := make([]model.Client, 6) + for i := range clients { + clients[i] = model.Client{ + Email: email(i), SubID: fmt.Sprintf("filter%d", i), Enable: true, Group: staff, + ID: fmt.Sprintf("22222222-2222-4222-8222-%012d", i), + } + } + clients[1].Group, clients[3].Group = "guests", "" + if err := svc.SyncInbound(nil, source.Id, clients); err != nil { + t.Fatal(err) + } + targets := strconv.Itoa(target.Id) + search := fmt.Sprintf("FILTER-%d", suffix) + scope, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{Targets: targets, Group: staff, Search: search, Freeze: true}) + if err != nil || scope.Eligible != 4 { + t.Fatalf("frozen group scope = %+v, err=%v, want the 4 staff clients", scope, err) + } + page, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{Targets: targets, Search: search, ScopeGroup: staff, ScopeSearch: search}) + if err != nil || len(page.Items) != 6 { + t.Fatalf("unfiltered page under a frozen scope = %+v, err=%v", page, err) + } + for i, row := range page.Items { + if row.InScope != (i != 1 && i != 3) { + t.Fatalf("row %d %s inScope = %t", i, row.Email, row.InScope) + } + } + inboundSvc := &InboundService{} + request := AttachSelection{Mode: "allMatching", ScopeToken: scope.ScopeToken, ExcludedClientIDs: []int{page.Items[0].ID}} + if _, _, err := svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, request); err == nil { + t.Fatal("a frozen token was accepted without the filter it was taken under") + } + request.Group, request.Search = staff, search + result, _, err := svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, request) + if err != nil || result.Attached != 3 || result.Errors != 0 { + t.Fatalf("filtered attach = %+v, err=%v", result, err) + } + got, err := svc.ListForInbound(nil, target.Id) + if err != nil { + t.Fatal(err) + } + var emails []string + for _, row := range got { + emails = append(emails, row.Email) + } + slices.Sort(emails) + if want := []string{email(2), email(4), email(5)}; !slices.Equal(emails, want) { + t.Fatalf("target clients = %v, want %v", emails, want) + } +} + +func BenchmarkAttachCandidateScale(b *testing.B) { + for _, count := range []int{1000, 10000, 50000} { + b.Run(fmt.Sprint(count), func(b *testing.B) { + setupScaleDB(b) + ds := seedScaleDataset(b, count, 1) + db := database.GetDB() + target := durableTestInbound(nil, "attach-scale", 42543) + if err := db.Create(target).Error; err != nil { + b.Fatal(err) + } + svc := &ClientService{} + for _, mode := range []string{"page", "search", "freeze"} { + b.Run(mode, func(b *testing.B) { + p := AttachCandidateParams{SourceID: ds.inboundIds[0], Targets: strconv.Itoa(target.Id), Freeze: mode == "freeze"} + if mode == "search" { + p.Search = ds.emails[count/2] + } + b.ReportAllocs() + for b.Loop() { + result, err := svc.ListAttachCandidates(context.Background(), p) + if err != nil || len(result.Items) > attachCandidatePageSize || result.Eligible != int64(count) { + b.Fatalf("bounded candidate page or eligibility count failed: %v", err) + } + } + }) + } + }) + } +} + +func TestAttachTenThousandClientsScale(t *testing.T) { + setupScaleDB(t) + ds := seedScaleDataset(t, 10_000, 1) + db := database.GetDB() + target := durableTestInbound(nil, "attach-ten-thousand", 42543) + if err := db.Create(target).Error; err != nil { + t.Fatal(err) + } + ctx := context.Background() + svc := &ClientService{} + scope, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{ + SourceID: ds.inboundIds[0], Targets: strconv.Itoa(target.Id), Freeze: true, + }) + if err != nil { + t.Fatal(err) + } + var excluded []int + excludedEmails := []string{ds.emails[0], ds.emails[5000], ds.emails[9999]} + if err := db.Model(&model.ClientRecord{}).Where("email IN ?", excludedEmails).Pluck("id", &excluded).Error; err != nil { + t.Fatal(err) + } + start := time.Now() + result, _, err := svc.BulkAttachSelection(ctx, &InboundService{}, []int{target.Id}, AttachSelection{ + Mode: "allMatching", SourceID: ds.inboundIds[0], ScopeToken: scope.ScopeToken, ExcludedClientIDs: excluded, + }) + if err != nil || result.Attached != 9997 || result.Skipped != 0 || result.Errors != 0 { + t.Fatalf("large attachment = %+v, err=%v", result, err) + } + t.Logf("attached 9997 of 10000 clients in %v", time.Since(start)) + var links, unexpected int64 + query := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", target.Id) + if err := query.Count(&links).Error; err != nil || links != 9997 { + t.Fatalf("target links = %d, err=%v", links, err) + } + if err := query.Where("client_id IN ?", excluded).Count(&unexpected).Error; err != nil || unexpected != 0 { + t.Fatalf("target has %d excluded clients, err=%v", unexpected, err) + } +} diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index 674d92542..b996d31a6 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -36,12 +36,6 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, return result, false, nil } - recordErr := func(format string, args ...any) { - msg := fmt.Sprintf(format, args...) - result.Errors = append(result.Errors, msg) - logger.Warningf("[BulkAttach] %s", msg) - } - records := make([]*model.ClientRecord, 0, len(emails)) seenEmail := make(map[string]struct{}, len(emails)) for _, email := range emails { @@ -55,12 +49,22 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, seenEmail[key] = struct{}{} rec, err := s.GetRecordByEmail(nil, email) if err != nil { - recordErr("%s: %v", email, err) + logAttachError(result, "%s: %v", email, err) continue } records = append(records, rec) } + return s.bulkAttachRecords(inboundSvc, records, inboundIds, result) +} + +func logAttachError(result *BulkAttachResult, format string, args ...any) { + msg := fmt.Sprintf(format, args...) + result.Errors = append(result.Errors, msg) + logger.Warningf("[BulkAttach] %s", msg) +} + +func (s *ClientService) bulkAttachRecords(inboundSvc *InboundService, records []*model.ClientRecord, inboundIds []int, result *BulkAttachResult) (*BulkAttachResult, bool, error) { // Same rule as Attach (#4834): clients.flow is unreliable when a non-flow // inbound synced last, so seed from EffectiveFlow before clientWithInboundFlow. emailsForFlow := make([]string, 0, len(records)) @@ -89,7 +93,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, seenInbound[ibId] = struct{}{} inbound, err := inboundSvc.GetInbound(ibId) if err != nil { - recordErr("inbound %d: %v", ibId, err) + logAttachError(result, "inbound %d: %v", ibId, err) continue } if inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG { @@ -97,7 +101,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, } existingClients, err := inboundSvc.GetClients(inbound) if err != nil { - recordErr("inbound %d: %v", ibId, err) + logAttachError(result, "inbound %d: %v", ibId, err) continue } have := make(map[string]struct{}, len(existingClients)) @@ -120,7 +124,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, } client.UpdatedAt = time.Now().UnixMilli() if err := s.fillProtocolDefaults(&client, inbound); err != nil { - recordErr("%s -> inbound %d: %v", rec.Email, ibId, err) + logAttachError(result, "%s -> inbound %d: %v", rec.Email, ibId, err) continue } clientsToAdd = append(clientsToAdd, clientWithInboundFlow(client, inbound)) @@ -132,7 +136,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, payload, err := json.Marshal(map[string][]model.Client{"clients": clientsToAdd}) if err != nil { - recordErr("inbound %d: %v", ibId, err) + logAttachError(result, "inbound %d: %v", ibId, err) continue } attachIds = append(attachIds, ibId) @@ -153,7 +157,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, err = attachPanics[i] } if err != nil { - recordErr("inbound %d: %v", attachIds[i], err) + logAttachError(result, "inbound %d: %v", attachIds[i], err) continue } if out.needRestart { diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 9cd51ef38..281f1232c 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "العملاء للإرفاق", "attachClientsSearchPlaceholder": "ابحث بالبريد أو التعليق", "attachClientsStatusDisabled": "معطل", + "attachSelectPage": "تحديد عملاء هذه الصفحة", + "attachSelectAllEligible": "تحديد جميع العملاء المؤهلين", + "attachClearSelection": "مسح التحديد", + "attachExcludedClients": "العملاء المستبعدون", + "attachRestoreClient": "إعادة تحديد {email}", + "attachClearExclusions": "مسح الاستبعادات", "attachClientsSelectedCount": "{selected} من {total} محدد", "attachExistingClients": "إرفاق العملاء الحاليين…", "attachExistingTitle": "إرفاق العملاء الحاليين بـ «{remark}»", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 0f0c9b635..2d7a17e7f 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Clients to attach", "attachClientsSearchPlaceholder": "Search email or comment", "attachClientsStatusDisabled": "Disabled", + "attachSelectPage": "Select this page", + "attachSelectAllEligible": "Select all eligible clients", + "attachClearSelection": "Clear selection", + "attachExcludedClients": "Excluded clients", + "attachRestoreClient": "Restore {email}", + "attachClearExclusions": "Clear exclusions", "attachClientsSelectedCount": "{selected} of {total} selected", "attachExistingClients": "Attach Existing Clients…", "attachExistingTitle": "Attach existing clients to \"{remark}\"", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 9c35c6660..1acfab2f4 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Clientes para asociar", "attachClientsSearchPlaceholder": "Buscar email o comentario", "attachClientsStatusDisabled": "Deshabilitado", + "attachSelectPage": "Seleccionar esta página", + "attachSelectAllEligible": "Seleccionar todos los clientes elegibles", + "attachClearSelection": "Borrar selección", + "attachExcludedClients": "Clientes excluidos", + "attachRestoreClient": "Restaurar {email}", + "attachClearExclusions": "Borrar exclusiones", "attachClientsSelectedCount": "{selected} de {total} seleccionado(s)", "attachExistingClients": "Asociar clientes existentes…", "attachExistingTitle": "Asociar clientes existentes a «{remark}»", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index b883d8847..d5d7a05b6 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "کاربران برای الصاق", "attachClientsSearchPlaceholder": "جستجوی ایمیل یا توضیح", "attachClientsStatusDisabled": "غیرفعال", + "attachSelectPage": "انتخاب این صفحه", + "attachSelectAllEligible": "انتخاب همهٔ کلاینت‌های واجد شرایط", + "attachClearSelection": "پاک کردن انتخاب", + "attachExcludedClients": "کلاینت‌های مستثنا", + "attachRestoreClient": "بازگرداندن {email}", + "attachClearExclusions": "پاک کردن موارد مستثنا", "attachClientsSelectedCount": "{selected} از {total} انتخاب‌شده", "attachExistingClients": "الصاق کاربران موجود…", "attachExistingTitle": "الصاق کاربران موجود به «{remark}»", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 70da620f3..8334f2339 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Klien untuk dilampirkan", "attachClientsSearchPlaceholder": "Cari email atau komentar", "attachClientsStatusDisabled": "Dinonaktifkan", + "attachSelectPage": "Pilih halaman ini", + "attachSelectAllEligible": "Pilih semua klien yang memenuhi syarat", + "attachClearSelection": "Hapus pilihan", + "attachExcludedClients": "Klien yang dikecualikan", + "attachRestoreClient": "Sertakan kembali {email}", + "attachClearExclusions": "Hapus pengecualian", "attachClientsSelectedCount": "{selected} dari {total} dipilih", "attachExistingClients": "Lampirkan klien yang ada…", "attachExistingTitle": "Lampirkan klien yang ada ke «{remark}»", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index bfe2e9543..fec842129 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "アタッチするクライアント", "attachClientsSearchPlaceholder": "メールまたはコメントを検索", "attachClientsStatusDisabled": "無効", + "attachSelectPage": "このページを選択", + "attachSelectAllEligible": "対象のクライアントをすべて選択", + "attachClearSelection": "選択を解除", + "attachExcludedClients": "除外したクライアント", + "attachRestoreClient": "{email} を選択に戻す", + "attachClearExclusions": "除外を解除", "attachClientsSelectedCount": "{total} 中 {selected} 選択中", "attachExistingClients": "既存のクライアントをアタッチ…", "attachExistingTitle": "「{remark}」に既存のクライアントをアタッチ", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index d0967122d..15a75e592 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Clientes para associar", "attachClientsSearchPlaceholder": "Buscar email ou comentário", "attachClientsStatusDisabled": "Desabilitado", + "attachSelectPage": "Selecionar esta página", + "attachSelectAllEligible": "Selecionar todos os clientes elegíveis", + "attachClearSelection": "Limpar seleção", + "attachExcludedClients": "Clientes excluídos", + "attachRestoreClient": "Restaurar {email}", + "attachClearExclusions": "Limpar exclusões", "attachClientsSelectedCount": "{selected} de {total} selecionado(s)", "attachExistingClients": "Associar clientes existentes…", "attachExistingTitle": "Associar clientes existentes a «{remark}»", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index a9af6b490..e5d3845e1 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Клиенты для привязки", "attachClientsSearchPlaceholder": "Поиск email или комментария", "attachClientsStatusDisabled": "Отключено", + "attachSelectPage": "Выбрать эту страницу", + "attachSelectAllEligible": "Выбрать всех доступных клиентов", + "attachClearSelection": "Очистить выбор", + "attachExcludedClients": "Исключённые клиенты", + "attachRestoreClient": "Вернуть {email}", + "attachClearExclusions": "Очистить исключения", "attachClientsSelectedCount": "{selected} из {total} выбрано", "attachExistingClients": "Привязать существующих клиентов…", "attachExistingTitle": "Привязать существующих клиентов к «{remark}»", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 9d1887047..f6112e144 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Klienti na priradenie", "attachClientsSearchPlaceholder": "Hľadať podľa názvu klienta alebo poznámky", "attachClientsStatusDisabled": "Vypnutý", + "attachSelectPage": "Vybrať túto stránku", + "attachSelectAllEligible": "Vybrať všetkých oprávnených klientov", + "attachClearSelection": "Zrušiť výber", + "attachExcludedClients": "Vylúčení klienti", + "attachRestoreClient": "Obnoviť {email}", + "attachClearExclusions": "Vymazať výnimky", "attachClientsSelectedCount": "Vybrané: {selected} z {total}", "attachExistingClients": "Priradiť existujúcich klientov…", "attachExistingTitle": "Priradiť existujúcich klientov k vstupu „{remark}“", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 4c8e86f5a..cb7d5dbf3 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Bağlanacak Kullanıcılar", "attachClientsSearchPlaceholder": "E-posta veya yorum ara", "attachClientsStatusDisabled": "Devre Dışı", + "attachSelectPage": "Bu sayfayı seç", + "attachSelectAllEligible": "Uygun tüm istemcileri seç", + "attachClearSelection": "Seçimi temizle", + "attachExcludedClients": "Hariç tutulan istemciler", + "attachRestoreClient": "{email} istemcisini geri ekle", + "attachClearExclusions": "Hariç tutulanları temizle", "attachClientsSelectedCount": "{total} içinden {selected} seçildi", "attachExistingClients": "Mevcut Kullanıcıları Bağla…", "attachExistingTitle": "«{remark}» gelen bağlantıya mevcut kullanıcıları bağla", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 5733ee7ed..2481590c0 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Клієнти для прив'язки", "attachClientsSearchPlaceholder": "Пошук email або коментаря", "attachClientsStatusDisabled": "Вимкнено", + "attachSelectPage": "Вибрати цю сторінку", + "attachSelectAllEligible": "Вибрати всіх доступних клієнтів", + "attachClearSelection": "Очистити вибір", + "attachExcludedClients": "Виключені клієнти", + "attachRestoreClient": "Повернути {email}", + "attachClearExclusions": "Очистити виключення", "attachClientsSelectedCount": "Обрано {selected} з {total}", "attachExistingClients": "Прив'язати наявних клієнтів…", "attachExistingTitle": "Прив'язати наявних клієнтів до «{remark}»", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index cab6edff2..f61ab407a 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "Client để gắn", "attachClientsSearchPlaceholder": "Tìm email hoặc ghi chú", "attachClientsStatusDisabled": "Đã tắt", + "attachSelectPage": "Chọn trang này", + "attachSelectAllEligible": "Chọn tất cả máy khách đủ điều kiện", + "attachClearSelection": "Xóa lựa chọn", + "attachExcludedClients": "Máy khách bị loại trừ", + "attachRestoreClient": "Khôi phục {email}", + "attachClearExclusions": "Xóa mục loại trừ", "attachClientsSelectedCount": "Đã chọn {selected}/{total}", "attachExistingClients": "Gắn client hiện có…", "attachExistingTitle": "Gắn client hiện có vào «{remark}»", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 21cb49bcb..b48352f0e 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "要附加的客户端", "attachClientsSearchPlaceholder": "搜索邮箱或备注", "attachClientsStatusDisabled": "已禁用", + "attachSelectPage": "选择此页", + "attachSelectAllEligible": "选择所有符合条件的客户端", + "attachClearSelection": "清除选择", + "attachExcludedClients": "已排除的客户端", + "attachRestoreClient": "恢复选择 {email}", + "attachClearExclusions": "清除排除项", "attachClientsSelectedCount": "已选 {selected}/{total}", "attachExistingClients": "附加现有客户端…", "attachExistingTitle": "将现有客户端附加到 “{remark}”", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index b3bdd60ef..1e51565dd 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -363,6 +363,12 @@ "attachClientsSelectLabel": "要附加的客戶端", "attachClientsSearchPlaceholder": "搜尋電子郵件或備註", "attachClientsStatusDisabled": "已停用", + "attachSelectPage": "選擇此頁", + "attachSelectAllEligible": "選擇所有符合條件的用戶端", + "attachClearSelection": "清除選擇", + "attachExcludedClients": "已排除的用戶端", + "attachRestoreClient": "恢復選擇 {email}", + "attachClearExclusions": "清除排除項", "attachClientsSelectedCount": "已選 {selected}/{total}", "attachExistingClients": "附加現有客戶端…", "attachExistingTitle": "將現有客戶端附加到「{remark}」", diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index 971437c7b..7ebfaf9db 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -108,6 +108,9 @@ func run(root, outDir string) error { "ClientRenewalPreviewRequest", "ClientRenewalPreview", "ClientPageResponse", + "AttachCandidate", + "AttachCandidatePage", + "AttachSelectionResult", "BulkAdjustResult", "BulkAdjustReport", "BulkExternalLinksResult", @@ -142,7 +145,7 @@ func run(root, outDir string) error { }, { Path: resolveRel(root, "internal/web/controller"), - StructAllow: setOf("TgBotCapabilities"), + StructAllow: setOf("TgBotCapabilities", "AttachJobStatus"), }, { Path: resolveRel(root, "internal/amneziawg"), From 428dfe7709e731692d4de02ce3a52ea28f87d0c6 Mon Sep 17 00:00:00 2001 From: Hamed Date: Sat, 28 Nov 2026 18:13:26 +0330 Subject: [PATCH 113/130] fix(iplimit): persist Fail2ban enforcement consent (#7239) Removing IP Limit from the x-ui menu saved nothing, so the next update, reinstall or panel self-update installed Fail2ban again and re-enabled the host-wide 3x-ipl jail. The choice is now written to the panel's env file and every later install and update reads it first. A fresh native install asks before enabling enforcement (Enter declines) and an unattended one enables it only with XUI_ENABLE_FAIL2BAN=true; a stored choice wins over the process environment. Hosts that already have the jail configured and nothing stored are left as they are. The menu restarts the panel so it runs with the same value, and OpenRC exports it to the service. Removal and reload touch only the managed jail, and the package is uninstalled only when 3x-ipl is the sole jail, so a distro-enabled sshd jail keeps Fail2ban installed. The journal backend override for Debian 12+ and Ubuntu 22.04+ now targets the stock sshd jail and leaves operator backend and log settings alone. Fixes #7222 --- docs/content/docs/en/operations/security.mdx | 6 +- docs/content/docs/fa/operations/security.mdx | 2 +- docs/content/docs/ru/operations/security.mdx | 6 +- docs/content/docs/zh/operations/security.mdx | 5 +- install.sh | 96 ++---- internal/database/db.go | 5 + internal/database/fail2ban_state_test.go | 14 +- scripts_base_path_test.go | 12 +- scripts_fail2ban_test.go | 211 +++++++++++++ update.sh | 38 +-- x-ui.rc | 5 +- x-ui.sh | 315 ++++++++++++------- 12 files changed, 500 insertions(+), 215 deletions(-) create mode 100644 scripts_fail2ban_test.go diff --git a/docs/content/docs/en/operations/security.mdx b/docs/content/docs/en/operations/security.mdx index 4c294b582..3cc468913 100644 --- a/docs/content/docs/en/operations/security.mdx +++ b/docs/content/docs/en/operations/security.mdx @@ -21,8 +21,10 @@ See [First login](/docs/guide/first-login) for the full checklist. Set an **IP limit** per client (see [Clients](/docs/config/clients)) to cap the number of simultaneous source IPs. Enforcement is handled by **Fail2ban**, which -3x-ui installs and configures for you (enabled by default on script installs, and -on Docker via `XUI_ENABLE_FAIL2BAN=true`). +3x-ui installs and configures when you opt in. On a fresh native install, +answer **Yes** to enable enforcement, or set `XUI_ENABLE_FAIL2BAN=true` for +unattended and Docker installs. The native installer remembers your choice across +updates and reinstalls. Source IP tracking continues independently of enforcement. Manage it from the `x-ui` menu (**22 — IP Limit Management**): install/configure, change the ban duration (default **30 minutes**), ban/unban an IP, view ban logs, diff --git a/docs/content/docs/fa/operations/security.mdx b/docs/content/docs/fa/operations/security.mdx index 06e7b4ba3..e8572dbd6 100644 --- a/docs/content/docs/fa/operations/security.mdx +++ b/docs/content/docs/fa/operations/security.mdx @@ -17,7 +17,7 @@ icon: ShieldCheck ## Fail2ban و محدودیت‌های IP -برای هر کلاینت یک **محدودیت IP** تنظیم کنید (به [کلاینت‌ها](/docs/config/clients) مراجعه کنید) تا تعداد IPهای مبدأ همزمان محدود شود. اعمال این محدودیت توسط **Fail2ban** انجام می‌شود که 3x-ui آن را برای شما نصب و پیکربندی می‌کند (در نصب‌های اسکریپتی به‌طور پیش‌فرض فعال است و در Docker از طریق `XUI_ENABLE_FAIL2BAN=true`). +برای هر کلاینت یک **محدودیت IP** تنظیم کنید (به [کلاینت‌ها](/docs/config/clients) مراجعه کنید) تا تعداد IPهای مبدأ همزمان محدود شود. اعمال این محدودیت توسط **Fail2ban** انجام می‌شود که 3x-ui پس از موافقت شما آن را نصب و پیکربندی می‌کند. در نصب تازه با اسکریپت، برای فعال‌کردن اعمال محدودیت **Yes** را انتخاب کنید. در نصب خودکار و Docker، `XUI_ENABLE_FAIL2BAN=true` را تنظیم کنید. انتخاب شما در به‌روزرسانی و نصب مجدد حفظ می‌شود. ردیابی IP مبدأ مستقل از اعمال محدودیت ادامه دارد. آن را از منوی `x-ui` مدیریت کنید (**۲۲ — IP Limit Management**): نصب/پیکربندی، تغییر مدت مسدودسازی (پیش‌فرض **۳۰ دقیقه**)، مسدودسازی/رفع مسدودی یک IP، مشاهده لاگ‌های مسدودسازی و بررسی وضعیت. در پشت صحنه: diff --git a/docs/content/docs/ru/operations/security.mdx b/docs/content/docs/ru/operations/security.mdx index d9acbe8e6..1bd53c627 100644 --- a/docs/content/docs/ru/operations/security.mdx +++ b/docs/content/docs/ru/operations/security.mdx @@ -21,8 +21,10 @@ icon: ShieldCheck Задайте **ограничение IP** для каждого клиента (см. [Клиенты](/docs/config/clients)), чтобы ограничить число одновременных исходных IP. Применением правил занимается **Fail2ban**, который -3x-ui устанавливает и настраивает за вас (включён по умолчанию при установке через скрипт, а -в Docker — через `XUI_ENABLE_FAIL2BAN=true`). +3x-ui устанавливает и настраивает по вашему согласию. При новой установке через +скрипт ответьте **Да**, чтобы включить применение ограничений. Для автоматической +установки и Docker задайте `XUI_ENABLE_FAIL2BAN=true`. Скрипт сохраняет выбор при +обновлении и переустановке. Отслеживание исходных IP работает независимо. Управляйте им из меню `x-ui` (**22 — IP Limit Management**): установка/настройка, изменение длительности блокировки (по умолчанию **30 минут**), блокировка/разблокировка IP, просмотр журналов блокировок diff --git a/docs/content/docs/zh/operations/security.mdx b/docs/content/docs/zh/operations/security.mdx index b62d0fe2a..21856a43f 100644 --- a/docs/content/docs/zh/operations/security.mdx +++ b/docs/content/docs/zh/operations/security.mdx @@ -19,8 +19,9 @@ icon: ShieldCheck ## Fail2ban 与 IP 限制 为每个客户端设置一个 **IP 限制**(参见[客户端](/docs/config/clients)),以限制同时使用的源 -IP 数量。限制的执行由 **Fail2ban** 负责,3x-ui 会为你安装并配置好它(脚本安装时默认启用, -Docker 安装时通过 `XUI_ENABLE_FAIL2BAN=true` 启用)。 +IP 数量。由 **Fail2ban** 执行限制,3x-ui 会在你同意后安装并配置它。首次通过脚本安装时, +选择 **Yes** 以启用限制。对于无人值守和 Docker 安装,请设置 `XUI_ENABLE_FAIL2BAN=true`。 +脚本会在更新和重新安装时保留你的选择。源 IP 跟踪独立运行。 可从 `x-ui` 菜单(**22 — IP Limit Management**)进行管理:安装/配置、修改封锁时长 (默认 **30 分钟**)、封锁/解封某个 IP、查看封锁日志,以及检查状态。其底层机制如下: diff --git a/install.sh b/install.sh index 4d7c50e88..e8008aa4d 100644 --- a/install.sh +++ b/install.sh @@ -1228,17 +1228,7 @@ config_after_install() { fi if [[ "$db_choice" == "2" ]]; then local xui_env_file - case "${release}" in - ubuntu | debian | armbian) - xui_env_file="/etc/default/x-ui" - ;; - arch | manjaro | parch | alpine) - xui_env_file="/etc/conf.d/x-ui" - ;; - *) - xui_env_file="/etc/sysconfig/x-ui" - ;; - esac + xui_env_file=$(xui_env_file_path) local xui_dsn="" local pg_mode="" @@ -1487,35 +1477,33 @@ EOF ${xui_folder}/x-ui migrate } -# setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature -# by invoking the freshly installed x-ui CLI. IP Limit is load-bearing on -# fail2ban (without it the panel disables the limitIp field and zeroes existing -# limits), so a fresh install should make it work out of the box, just like the -# Docker image already does. Non-fatal by design: a fail2ban failure must never -# abort the panel install. +xui_env_file_path() { + case "$release" in + ubuntu | debian | armbian) printf '/etc/default/x-ui\n' ;; + arch | manjaro | parch | alpine) printf '/etc/conf.d/x-ui\n' ;; + *) printf '/etc/sysconfig/x-ui\n' ;; + esac +} + +load_xui_env() { + local envfile="${1:-}" + [[ -n "$envfile" ]] || envfile=$(xui_env_file_path) + if [[ -r "$envfile" ]]; then + set -a + # shellcheck disable=SC1090 + source "$envfile" + set +a + fi +} + +# Delegate only to releases that can honor and persist the administrator's choice. setup_fail2ban() { - if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then - echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}" + if [[ ! -x /usr/bin/x-ui ]] || ! grep -Fq 'setup_fail2ban_for_lifecycle()' /usr/bin/x-ui; then + echo -e "${yellow}This release does not support the persistent IP Limit setup policy. Skipping automatic setup.${plain}" return 0 fi - - if [[ ! -x /usr/bin/x-ui ]]; then - echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}" - return 0 - fi - - # Scripts older than v3.4.0 have no setup-fail2ban and exit 0 from the - # usage banner, which would read as success here. - if ! grep -q '"setup-fail2ban")' /usr/bin/x-ui; then - echo -e "${yellow}This x-ui.sh predates 'x-ui setup-fail2ban'; skipping Fail2ban auto-setup.${plain}" - return 0 - fi - - echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}" - if /usr/bin/x-ui setup-fail2ban; then - echo -e "${green}Fail2ban setup complete.${plain}" - else - echo -e "${yellow}Fail2ban setup did not finish; IP Limit stays disabled until you run 'x-ui' and open the IP Limit menu. Continuing.${plain}" + if ! /usr/bin/x-ui setup-fail2ban "${1:-install}"; then + echo -e "${yellow}Fail2ban setup did not finish. Use the IP Limit menu to check its configuration.${plain}" fi return 0 } @@ -1587,25 +1575,7 @@ _xui_service_write_paths_dropin() { local db_folder log_folder bin_folder main_folder local path line="" whitespace_paths="" seen_paths="" escaped_path - if [[ -z "$env_file" ]]; then - case "${release}" in - ubuntu | debian | armbian) - env_file="/etc/default/x-ui" - ;; - arch | manjaro | parch | alpine) - env_file="/etc/conf.d/x-ui" - ;; - *) - env_file="/etc/sysconfig/x-ui" - ;; - esac - fi - if [[ -r "$env_file" ]]; then - set -a - # shellcheck disable=SC1090 - source "$env_file" - set +a - fi + load_xui_env "$env_file" # XUI_* wins over the script's own default: the unit hands that same env # file to the panel through EnvironmentFile=, so these are the folders it @@ -1784,6 +1754,11 @@ require_repo_files() { install_x-ui() { cd ${xui_folder%/x-ui}/ + local fail2ban_mode=install + if [[ -x "${xui_folder}/x-ui" ]]; then + fail2ban_mode=update + fi + load_xui_env # Download resources if [ $# == 0 ]; then @@ -1986,6 +1961,7 @@ install_x-ui() { chmod +x /usr/bin/x-ui mkdir -p /var/log/x-ui config_after_install + setup_fail2ban "$fail2ban_mode" # Etckeeper compatibility if [ -d "/etc/.git" ]; then @@ -2023,7 +1999,7 @@ install_x-ui() { fi chmod +x /etc/init.d/x-ui rc-update add x-ui - rc-service x-ui start + rc-service x-ui restart else # Install systemd service file service_installed=false @@ -2092,17 +2068,13 @@ install_x-ui() { chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1 systemctl daemon-reload systemctl enable x-ui - systemctl start x-ui + systemctl restart x-ui else echo -e "${red}Failed to install x-ui.service file${plain}" exit 1 fi fi - # IP Limit relies on fail2ban; install + configure it now so the feature - # works out of the box (no-op when XUI_ENABLE_FAIL2BAN=false). Never fatal. - setup_fail2ban - echo -e "${green}x-ui ${tag_version}${plain} installation finished, it is running now..." echo -e "" echo -e "┌───────────────────────────────────────────────────────┐ diff --git a/internal/database/db.go b/internal/database/db.go index 969520e78..b6f2d512e 100644 --- a/internal/database/db.go +++ b/internal/database/db.go @@ -1851,6 +1851,11 @@ func resetIpLimitsWithoutFail2ban() error { return nil } + // An explicit enforcement choice can change independently of client limits. + if _, configured := os.LookupEnv("XUI_ENABLE_FAIL2BAN"); configured { + return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error + } + state, probeErr := fail2banEnforcementState() if state == fail2banEnforcing { return db.Create(&model.HistoryOfSeeders{SeederName: "ResetIpLimitNoFail2ban"}).Error diff --git a/internal/database/fail2ban_state_test.go b/internal/database/fail2ban_state_test.go index 509c0ac37..05a3c4e7f 100644 --- a/internal/database/fail2ban_state_test.go +++ b/internal/database/fail2ban_state_test.go @@ -54,6 +54,16 @@ func TestFail2banEnforcementStateSeparatesAbsentFromUnrunnable(t *testing.T) { } func TestResetIpLimitsKeepsConfiguredLimitsWhenProbeFails(t *testing.T) { + testResetIpLimitsKeepsConfiguredLimits(t, 0) +} + +func TestResetIpLimitsKeepsConfiguredLimitsWhenOptedOut(t *testing.T) { + t.Setenv("XUI_ENABLE_FAIL2BAN", "false") + testResetIpLimitsKeepsConfiguredLimits(t, 1) +} + +func testResetIpLimitsKeepsConfiguredLimits(t *testing.T, wantHistory int64) { + t.Helper() if runtime.GOOS == "windows" { t.Skip("fail2ban shell fixtures are Unix-only") } @@ -103,7 +113,7 @@ func TestResetIpLimitsKeepsConfiguredLimitsWhenProbeFails(t *testing.T) { if err := db.Model(&model.HistoryOfSeeders{}).Where("seeder_name = ?", "ResetIpLimitNoFail2ban").Count(&count).Error; err != nil { t.Fatalf("count seeder history: %v", err) } - if count != 0 { - t.Fatalf("seeder history rows = %d, want 0", count) + if count != wantHistory { + t.Fatalf("seeder history rows = %d, want %d", count, wantHistory) } } diff --git a/scripts_base_path_test.go b/scripts_base_path_test.go index a5d6df4d2..0fba126c7 100644 --- a/scripts_base_path_test.go +++ b/scripts_base_path_test.go @@ -129,6 +129,7 @@ chmod() { :; } [() { if [[ "${2:-}" == /etc/* ]]; then return 1; fi; builtin [ "$@"; } _install_xui_service_unit() { printf 'unit\n' >> "$TEST_SETTINGS_DIR/lifecycle"; } setup_fail2ban() { printf 'fail2ban\n' >> "$TEST_SETTINGS_DIR/lifecycle"; } +fail2ban_mode=install ` driver += scriptFunction(t, script, "gen_random_string") + scriptFunction(t, script, function) if script == "install.sh" { @@ -142,7 +143,11 @@ setup_fail2ban() { printf 'fail2ban\n' >> "$TEST_SETTINGS_DIR/lifecycle"; } parent = "install_x-ui" } body := scriptFunction(t, script, parent) - start := strings.Index(body, "\n "+function) + startCall := function + if script == "update.sh" { + startCall = "setup_fail2ban" + } + start := strings.Index(body, "\n "+startCall) if start < 0 { t.Fatalf("%s: missing configuration call in %s", script, parent) } @@ -269,10 +274,9 @@ func TestScriptConfigReadFailureKeepsServiceSetup(t *testing.T) { if err != nil || !strings.Contains(out, "Unable to read webBasePath") { t.Errorf("service setup should continue after the settings warning: %v\n%s", err, out) } - wantLifecycle, wantServices := "fail2ban\n", "" + wantLifecycle, wantServices := "fail2ban\nunit\n", "daemon-reload\nenable x-ui\nstart x-ui\n" if script == "install.sh" { - wantLifecycle = "unit\nfail2ban\n" - wantServices = "daemon-reload\nenable x-ui\nstart x-ui\n" + wantServices = "daemon-reload\nenable x-ui\nrestart x-ui\n" } for name, want := range map[string]string{ "path": "/a/", "username": "admin", "password": "admin", "writes": "", diff --git a/scripts_fail2ban_test.go b/scripts_fail2ban_test.go new file mode 100644 index 000000000..d99bde7af --- /dev/null +++ b/scripts_fail2ban_test.go @@ -0,0 +1,211 @@ +package main + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestNativeFail2banLifecycle(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("requires a POSIX shell") + } + bash, err := exec.LookPath("bash") + if err != nil { + t.Skip("requires bash") + } + for _, tc := range []struct { + name, initial, command, wantChoice string + setup, installed, jail, ssh bool + }{ + {name: "Enter declines", command: "export NONINTERACTIVE=0; printf '\\n' | setup_install", wantChoice: "false"}, + {name: "Yes enables", command: "export NONINTERACTIVE=0; printf 'y\\n' | setup_install", wantChoice: "true", setup: true, installed: true, jail: true}, + {name: "unattended unset", command: "setup_install", wantChoice: "false"}, + {name: "unattended false", command: "XUI_ENABLE_FAIL2BAN=false setup_install", wantChoice: "false"}, + {name: "unattended true", command: "XUI_ENABLE_FAIL2BAN=true setup_install", wantChoice: "true", setup: true, installed: true, jail: true}, + {name: "retry configured jail without replacing its ban duration", initial: "legacy", command: "rm \"$TEST_DIR/managed-running\"; XUI_ENABLE_FAIL2BAN=true setup_update; test -e \"$TEST_DIR/managed-running\"", wantChoice: "true", installed: true, jail: true}, + {name: "legacy active keeps configuration", initial: "legacy", command: "setup_update", installed: true, jail: true}, + {name: "update without managed jail", initial: "ssh", command: "setup_update", wantChoice: "false", installed: true, ssh: true}, + {name: "remove and reinstall", initial: "legacy ssh", command: "printf '1\\n' | remove_iplimit; XUI_ENABLE_FAIL2BAN=true setup_update; setup_install", wantChoice: "false", installed: true, ssh: true}, + {name: "remove package and update", initial: "legacy", command: "printf '2\\n' | remove_iplimit; setup_update", wantChoice: "false"}, + {name: "package removal protects ssh", initial: "legacy ssh", command: "printf '2\\n' | remove_iplimit; setup_update", wantChoice: "false", installed: true, ssh: true}, + {name: "explicit menu re-enable", initial: "legacy", command: "printf '1\\n' | remove_iplimit; install_iplimit; setup_update", wantChoice: "true", setup: true, installed: true, jail: true}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + driver := setupFail2banScriptFixture(t, dir) + for _, line := range strings.Fields(tc.initial) { + switch line { + case "legacy": + writeFail2banFixture(t, dir, "fail2ban/jail.d/3x-ipl.conf", "[3x-ipl]\nenabled = true\nbantime = 47m\n") + writeFail2banFixture(t, dir, "installed", "") + writeFail2banFixture(t, dir, "managed-running", "") + case "ssh": + writeFail2banFixture(t, dir, "fail2ban/jail.d/sshd.local", "[sshd]\nenabled = true\n") + writeFail2banFixture(t, dir, "installed", "") + writeFail2banFixture(t, dir, "ssh-running", "") + } + } + writeFail2banFixture(t, dir, "env", "XUI_DB_TYPE=postgres\nOTHER_KEY='value with spaces'\n") + cmd := exec.CommandContext(t.Context(), bash, "-c", driver+"\n"+tc.command) + for _, e := range os.Environ() { + if !strings.HasPrefix(e, "XUI_") && !strings.HasPrefix(e, "NONINTERACTIVE=") && !strings.HasPrefix(e, "TEST_DIR=") { + cmd.Env = append(cmd.Env, e) + } + } + cmd.Env = append(cmd.Env, "TEST_DIR="+dir) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("shell flow: %v\n%s", err, out) + } + wantEnv := "XUI_DB_TYPE=postgres\nOTHER_KEY='value with spaces'\n" + if tc.wantChoice != "" { + wantEnv += "XUI_ENABLE_FAIL2BAN=" + tc.wantChoice + "\n" + } + if env := readScriptState(t, dir, "env"); env != wantEnv { + t.Errorf("preference file = %q, want stored %s and untouched options", env, tc.wantChoice) + } + for path, present := range map[string]bool{"setup": tc.setup, "installed": tc.installed, "fail2ban/jail.d/3x-ipl.conf": tc.jail, "ssh-running": tc.ssh} { + _, err := os.Stat(filepath.Join(dir, path)) + if (err == nil) != present { + t.Errorf("%s present = %t, want %t (stat %v)", path, err == nil, present, err) + } + } + if tc.ssh && readScriptState(t, dir, "fail2ban/jail.d/sshd.local") != "[sshd]\nenabled = true\n" { + t.Errorf("independent SSH jail configuration changed") + } + if tc.jail && !tc.setup && !strings.Contains(readScriptState(t, dir, "fail2ban/jail.d/3x-ipl.conf"), "bantime = 47m") { + t.Error("update rewrote the existing jail's ban duration") + } + }) + } +} + +func writeFail2banFixture(t *testing.T, dir, path, contents string) { + t.Helper() + target := filepath.Join(dir, filepath.FromSlash(path)) + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(target, []byte(contents), 0o700); err != nil { + t.Fatal(err) + } +} + +func setupFail2banScriptFixture(t *testing.T, dir string) string { + t.Helper() + driver := `red= green= yellow= plain= release=debian +xui_env_file_path() { printf '%s\n' "$TEST_DIR/env"; } +LOGE() { printf '%s\n' "$*"; } +before_show_menu() { :; } +check_status() { return 1; } +systemctl() { + if [[ $1 == stop ]]; then rm -f "$TEST_DIR/ssh-running" "$TEST_DIR/managed-running"; fi +} +apt-get() { rm -f "$TEST_DIR/installed"; } +command() { + if [[ $* == '-v fail2ban-client' ]]; then [[ -f "$TEST_DIR/installed" ]]; else builtin command "$@"; fi +} +fail2ban-client() { + case "$*" in + 'status 3x-ipl') [[ -f "$TEST_DIR/managed-running" ]] ;; + 'stop 3x-ipl') rm -f "$TEST_DIR/managed-running" ;; + status) + local jails= + [[ ! -f "$TEST_DIR/managed-running" ]] || jails=3x-ipl + [[ ! -f "$TEST_DIR/ssh-running" ]] || jails="${jails:+$jails, }sshd" + printf 'Status\n- Jail list:\t%s\n' "$jails" ;; + -d) + [[ ! -f "$TEST_DIR/fail2ban/jail.d/3x-ipl.conf" ]] || echo "['add', '3x-ipl', 'auto']" + [[ ! -f "$TEST_DIR/fail2ban/jail.d/sshd.local" ]] || echo "['add', 'sshd', 'auto']" ;; + *) return 1 ;; + esac +} +start_iplimit_jail() { touch "$TEST_DIR/managed-running"; } +setup_fail2ban_iplimit() { + mkdir -p "$TEST_DIR/fail2ban/jail.d" + printf '[3x-ipl]\nenabled=true\nbantime=30m\n' > "$TEST_DIR/fail2ban/jail.d/3x-ipl.conf" + touch "$TEST_DIR/setup" "$TEST_DIR/installed" "$TEST_DIR/managed-running" +} +` + source, err := os.ReadFile("x-ui.sh") + if err != nil { + t.Fatal(err) + } + for _, name := range []string{ + "confirm", "read_fail2ban_preference", "persist_fail2ban_preference", + "iplimit_jail_configured", "setup_fail2ban_for_lifecycle", "apply_iplimit_preference", + "iplimit_remove_conflicts", "iplimit_can_uninstall", "remove_iplimit_jail", + "install_iplimit", "remove_iplimit", + } { + if strings.Contains(string(source), "\n"+name+"() {\n") { + driver += strings.ReplaceAll(scriptFunction(t, "x-ui.sh", name), "/etc/fail2ban", filepath.Join(dir, "fail2ban")) + } + } + cli := "#!/bin/bash\n" + driver + "\ncase \"$1\" in\n\"setup-fail2ban\")\n" + if strings.Contains(driver, "\nsetup_fail2ban_for_lifecycle() {\n") { + cli += "setup_fail2ban_for_lifecycle \"${2:-update}\";;\n" + } else { + cli += "setup_fail2ban_iplimit;;\n" + } + writeFail2banFixture(t, dir, "x-ui", cli+"esac\n") + for script, name := range map[string]string{"install.sh": "setup_install", "update.sh": "setup_update"} { + wrapper := scriptFunction(t, script, "setup_fail2ban") + wrapper = strings.Replace(wrapper, "setup_fail2ban() {", name+"() {", 1) + wrapper = strings.ReplaceAll(wrapper, "/usr/bin/x-ui", filepath.Join(dir, "x-ui")) + driver += wrapper + } + driver += "\nexport NONINTERACTIVE=1\n" + return driver +} + +func TestNativeFail2banStockSSHBackend(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("requires a POSIX shell") + } + bash, err := exec.LookPath("bash") + if err != nil { + t.Skip("requires bash") + } + const stock = "[DEFAULT]\nbackend = auto\n\n[sshd]\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\n" + const ownJail = "[monitor]\nbackend = polling\nlogpath = /var/log/monitor.log\n" + const override = "fail2ban/jail.d/3x-ipl-backend.conf" + for _, tc := range []struct { + name, release, version, customFile, customContents, want string + }{ + {name: "Debian 12 journal only", release: "debian", version: "12", want: "[sshd]\nbackend = systemd\n"}, + {name: "Ubuntu 22.04 journal only", release: "ubuntu", version: "2204", want: "[sshd]\nbackend = systemd\n"}, + {name: "file logs available", release: "debian", version: "12", customFile: "auth.log"}, + {name: "operator SSH configuration", release: "ubuntu", version: "2404", customFile: "fail2ban/jail.d/sshd.local", customContents: "[sshd]\nbackend = polling\n"}, + {name: "operator default backend", release: "debian", version: "12", customFile: "fail2ban/jail.local", customContents: "[DEFAULT]\nbackend = polling\n"}, + {name: "legacy persisted override", release: "debian", version: "12", customFile: override, customContents: "[DEFAULT]\nbackend = systemd\n", want: "[DEFAULT]\nbackend = systemd\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + writeFail2banFixture(t, dir, "fail2ban/jail.conf", stock) + writeFail2banFixture(t, dir, "fail2ban/jail.d/monitor.local", ownJail) + if tc.customFile != "" { + writeFail2banFixture(t, dir, tc.customFile, tc.customContents) + } + script := scriptFunction(t, "x-ui.sh", "configure_default_sshd_backend") + script += "\napt-get() { :; }\nrelease=\"$1\" os_version=\"$2\"\nconfigure_default_sshd_backend \"$3/fail2ban\" \"$3/auth.log\"" + out, err := exec.CommandContext(t.Context(), bash, "-c", script, "test", tc.release, tc.version, dir).CombinedOutput() + if err != nil { + t.Fatalf("configure default backend: %v, %s", err, out) + } + got, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(override))) + if tc.want == "" && !os.IsNotExist(err) { + t.Fatalf("unexpected override, err=%v: %s", err, got) + } + if tc.want != "" && (err != nil || string(got) != tc.want) { + t.Fatalf("override = %q, want %q, err=%v", got, tc.want, err) + } + if readScriptState(t, dir, "fail2ban/jail.conf") != stock || readScriptState(t, dir, "fail2ban/jail.d/monitor.local") != ownJail { + t.Fatal("stock config or independent jail was rewritten") + } + }) + } +} diff --git a/update.sh b/update.sh index ae1781cbb..7d7e3a1ff 100755 --- a/update.sh +++ b/update.sh @@ -253,36 +253,14 @@ config_after_update() { fi } -# setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature -# by invoking the freshly downloaded x-ui CLI. IP Limit is load-bearing on -# fail2ban (without it the panel disables the limitIp field and zeroes existing -# limits), so updating an older install should make it work without a manual -# trip through the IP Limit menu. Non-fatal: a fail2ban failure must never abort -# the update. XUI_ENABLE_FAIL2BAN is honored (load_xui_env exports it from the -# persisted env file, so a deliberate opt-out survives updates). +# Delegate only to releases that can honor and persist the administrator's choice. setup_fail2ban() { - if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then - echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}" + if [[ ! -x /usr/bin/x-ui ]] || ! grep -Fq 'setup_fail2ban_for_lifecycle()' /usr/bin/x-ui; then + echo -e "${yellow}This release does not support the persistent IP Limit setup policy. Skipping automatic setup.${plain}" return 0 fi - - if [[ ! -x /usr/bin/x-ui ]]; then - echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}" - return 0 - fi - - # Scripts older than v3.4.0 have no setup-fail2ban and exit 0 from the - # usage banner, which would read as success here. - if ! grep -q '"setup-fail2ban")' /usr/bin/x-ui; then - echo -e "${yellow}This x-ui.sh predates 'x-ui setup-fail2ban'; skipping Fail2ban auto-setup.${plain}" - return 0 - fi - - echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}" - if /usr/bin/x-ui setup-fail2ban; then - echo -e "${green}Fail2ban setup complete.${plain}" - else - echo -e "${yellow}Fail2ban setup did not finish; IP Limit stays disabled until you run 'x-ui' and open the IP Limit menu. Continuing.${plain}" + if ! /usr/bin/x-ui setup-fail2ban update; then + echo -e "${yellow}Fail2ban setup did not finish. Use the IP Limit menu to check its configuration.${plain}" fi return 0 } @@ -706,6 +684,7 @@ update_x-ui() { # config_after_update's CLI calls never run them on the same database at once (#6728). echo -e "${green}Migrating database...${plain}" "${xui_folder}/x-ui" migrate + setup_fail2ban if [[ $release == "alpine" ]]; then echo -e "${green}Installing startup unit x-ui.rc...${plain}" @@ -784,11 +763,6 @@ update_x-ui() { config_after_update - # IP Limit relies on fail2ban; install + configure it now so the feature - # works out of the box on update too (no-op when XUI_ENABLE_FAIL2BAN=false). - # Never fatal. - setup_fail2ban - echo -e "${green}x-ui ${tag_version}${plain} updating finished, it is running now..." echo -e "" echo -e "┌───────────────────────────────────────────────────────┐ diff --git a/x-ui.rc b/x-ui.rc index 55f6246be..b1ae7626f 100644 --- a/x-ui.rc +++ b/x-ui.rc @@ -9,10 +9,13 @@ depend() { need net } start_pre(){ + if [ "${XUI_ENABLE_FAIL2BAN+x}" ]; then + export XUI_ENABLE_FAIL2BAN + fi cd /usr/local/x-ui } reload() { ebegin "Reloading ${RC_SVCNAME}" kill -USR1 $(cat $pidfile) eend $? -} \ No newline at end of file +} diff --git a/x-ui.sh b/x-ui.sh index 5f44a144d..d47d53a9b 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -2277,7 +2277,8 @@ iplimit_main() { show_menu ;; 1) - confirm "Proceed with installation of Fail2ban & IP Limit?" "y" + echo "IP Limit bans apply host-wide and can interrupt other clients behind a shared relay." + confirm "Enable IP Limit and restart the running panel to apply the choice?" "n" if [[ $? == 0 ]]; then install_iplimit else @@ -2285,14 +2286,15 @@ iplimit_main() { fi ;; 2) + local preference + if ! preference=$(read_fail2ban_preference) || [[ "$preference" == "false" ]] || ! iplimit_jail_configured; then + LOGE "Enable IP Limit before changing its ban duration." + iplimit_main + return + fi read -rp "Please enter new Ban Duration in Minutes [default 30]: " NUM if [[ $NUM =~ ^[0-9]+$ ]]; then - create_iplimit_jails ${NUM} - if [[ $release == "alpine" ]]; then - rc-service fail2ban restart - else - systemctl restart fail2ban - fi + create_iplimit_jails "$NUM" && fail2ban-client reload 3x-ipl else echo -e "${red}${NUM} is not a number! Please, try again.${plain}" fi @@ -2363,15 +2365,80 @@ iplimit_main() { esac } -setup_fail2ban_iplimit() { - # Honor the same toggle the panel uses (isFail2BanEnabled): enabled when the - # var is unset or exactly "true"; any other explicit value means the operator - # opted out, so do nothing rather than install a fail2ban the panel ignores. - if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then - echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban setup.${plain}\n" +read_fail2ban_preference() { + ( + local envfile + envfile=$(xui_env_file_path) + if [[ -e "$envfile" ]]; then + # shellcheck disable=SC1090 + source "$envfile" || return 1 + fi + if [[ ${XUI_ENABLE_FAIL2BAN+x} ]]; then + if [[ "$XUI_ENABLE_FAIL2BAN" == "true" ]]; then + printf 'true\n' + else + printf 'false\n' + fi + fi + ) +} + +persist_fail2ban_preference() { + local choice="$1" envfile temp + envfile=$(xui_env_file_path) + if [[ -L "$envfile" ]]; then + envfile=$(readlink -f -- "$envfile") || return 1 + fi + mkdir -p -- "${envfile%/*}" || return 1 + temp=$(mktemp "${envfile}.XXXXXX") || return 1 + if [[ -e "$envfile" ]] && ! { + cp -p -- "$envfile" "$temp" && + awk '!/^[[:space:]]*(export[[:space:]]+)?XUI_ENABLE_FAIL2BAN=/' "$envfile" > "$temp" + }; then + rm -f -- "$temp" + return 1 + fi + if ! printf 'XUI_ENABLE_FAIL2BAN=%s\n' "$choice" >> "$temp" || ! mv -f -- "$temp" "$envfile"; then + rm -f -- "$temp" + return 1 + fi +} + +iplimit_jail_configured() { + [[ -f /etc/fail2ban/jail.d/3x-ipl.conf ]] || + grep -Eq '^[[:space:]]*\[3x-ipl\]' /etc/fail2ban/jail.conf /etc/fail2ban/jail.local 2>/dev/null || + fail2ban-client status 3x-ipl > /dev/null 2>&1 +} + +setup_fail2ban_for_lifecycle() { + local mode="$1" choice + choice=$(read_fail2ban_preference) || return 1 + if [[ -z "$choice" ]] && iplimit_jail_configured; then + # Preserve legacy jails, including later overrides to their enabled state. return 0 fi + if [[ -z "$choice" ]]; then + choice=false + if [[ "$mode" == "install" && "${NONINTERACTIVE:-1}" == "0" ]]; then + echo "IP Limit bans apply host-wide and can interrupt other clients behind a shared relay." + if confirm "Install Fail2ban and enable IP Limit?" "n"; then + choice=true + fi + fi + fi + persist_fail2ban_preference "$choice" || return 1 + if [[ "$choice" == "false" ]]; then + echo "IP Limit enforcement is opted out." + return 0 + fi + if command -v fail2ban-client > /dev/null 2>&1 && iplimit_jail_configured; then + fail2ban-client status 3x-ipl > /dev/null 2>&1 || start_iplimit_jail + return + fi + XUI_ENABLE_FAIL2BAN=true setup_fail2ban_iplimit +} +setup_fail2ban_iplimit() { if ! command -v fail2ban-client &> /dev/null; then echo -e "${green}Fail2ban is not installed. Installing now...!${plain}\n" @@ -2390,6 +2457,9 @@ setup_fail2ban_iplimit() { apt-get install python3-pip -y python3 -m pip install pyasynchat --break-system-packages fi + if [[ "$os_version" -ge 2200 ]]; then + apt-get install -y python3-systemd + fi apt-get install fail2ban nftables -y ;; debian) @@ -2453,107 +2523,142 @@ setup_fail2ban_iplimit() { echo -e "${green}Configuring IP Limit...${plain}\n" # make sure there's no conflict for jail files - iplimit_remove_conflicts + iplimit_remove_conflicts || return 1 # Check if log file exists if ! test -f "${iplimit_banned_log_path}"; then - touch ${iplimit_banned_log_path} + touch "$iplimit_banned_log_path" || return 1 fi # Check if service log file exists so fail2ban won't return error if ! test -f "${iplimit_log_path}"; then - touch ${iplimit_log_path} + touch "$iplimit_log_path" || return 1 fi # Create the iplimit jail files # we didn't pass the bantime here to use the default value - create_iplimit_jails + create_iplimit_jails || return 1 - # Launching fail2ban - if [[ $release == "alpine" ]]; then - if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then - rc-service fail2ban start - else - rc-service fail2ban restart - fi - rc-update add fail2ban - else - if ! systemctl is-active --quiet fail2ban; then - systemctl start fail2ban - else - systemctl restart fail2ban - fi - systemctl enable fail2ban - fi + start_iplimit_jail || return 1 echo -e "${green}IP Limit installed and configured successfully!${plain}\n" return 0 } -# install_iplimit is the interactive (menu) entry point: it runs the shared -# setup and then returns to the menu. The non-interactive installer path uses -# setup_fail2ban_iplimit directly via `x-ui setup-fail2ban`. +configure_default_sshd_backend() { + local config_dir="$1" auth_log="$2" jail_file + local override="$config_dir/jail.d/3x-ipl-backend.conf" + [[ ( "$release" == "debian" && ${os_version:-0} -ge 12 ) || ( "$release" == "ubuntu" && ${os_version:-0} -ge 2200 ) ]] || return 0 + [[ ! -e "$auth_log" && ! -e "$override" && ! -L "$override" && ! -e "$config_dir/paths-overrides.local" ]] || return 0 + + # Repair the distro's stock SSH jail for journal-only hosts. + awk ' + /^[[:space:]]*\[/ { section = $0 } + section ~ /\[DEFAULT\]/ && /^[[:space:]]*backend[[:space:]]*=[[:space:]]*auto[[:space:]]*$/ { stock_backend = 1 } + section ~ /\[sshd\]/ && /^[[:space:]]*backend[[:space:]]*=[[:space:]]*%[(]sshd_backend[)]s[[:space:]]*$/ { stock_ssh = 1 } + section ~ /\[sshd\]/ && /^[[:space:]]*logpath[[:space:]]*=[[:space:]]*%[(]sshd_log[)]s[[:space:]]*$/ { stock_log = 1 } + END { exit !(stock_backend && stock_ssh && stock_log) } + ' "$config_dir/jail.conf" 2>/dev/null || return 0 + + for jail_file in "$config_dir/jail.local" "$config_dir/jail.d/"*.conf "$config_dir/jail.d/"*.local; do + [[ -f "$jail_file" ]] || continue + if awk ' + /^[[:space:]]*\[/ { section = $0 } + section ~ /\[(DEFAULT|sshd)\]/ && /^[[:space:]]*(backend|logpath)[[:space:]]*=/ { custom = 1 } + END { exit !custom } + ' "$jail_file"; then + return 0 + fi + done + + if ! /usr/bin/python3 -c 'from systemd import journal' > /dev/null 2>&1; then + apt-get install -y python3-systemd || return 1 + fi + printf '[sshd]\nbackend = systemd\n' > "$override" +} + +start_iplimit_jail() { + if fail2ban-client ping > /dev/null 2>&1; then + fail2ban-client reload --if-exists 3x-ipl || return 1 + else + configure_default_sshd_backend /etc/fail2ban /var/log/auth.log || return 1 + if [[ $release == "alpine" ]]; then + rc-service fail2ban start && rc-update add fail2ban || return 1 + else + systemctl start fail2ban && systemctl enable fail2ban || return 1 + fi + fi + fail2ban-client status 3x-ipl > /dev/null 2>&1 +} + +apply_iplimit_preference() { + local choice="$1" + persist_fail2ban_preference "$choice" || { + LOGE "Could not save the IP Limit preference." + return 1 + } + export XUI_ENABLE_FAIL2BAN="$choice" +} + install_iplimit() { - setup_fail2ban_iplimit + if apply_iplimit_preference true && setup_fail2ban_iplimit; then + if check_status; then restart 0; fi + else + LOGE "IP Limit setup did not finish." + fi before_show_menu } +iplimit_can_uninstall() { + local status dump jails + status=$(LC_ALL=C fail2ban-client status 2>/dev/null) || return 1 + jails=$(sed -nE 's/^.*Jail list:[[:space:]]*//p' <<< "$status") + [[ "$jails" == "3x-ipl" ]] || return 1 + dump=$(LC_ALL=C fail2ban-client -d 2>/dev/null) || return 1 + jails=$(grep -E "^\[['\"]add['\"]," <<< "$dump") + # Require a known dump containing only the managed jail before removing the package. + [[ "$jails" == "['add', '3x-ipl', "* && "$jails" != *$'\n'* ]] +} + +remove_iplimit_jail() { + if fail2ban-client status 3x-ipl > /dev/null 2>&1; then + fail2ban-client stop 3x-ipl || return 1 + fi + iplimit_remove_conflicts || return 1 + rm -f -- /etc/fail2ban/filter.d/3x-ipl.conf /etc/fail2ban/action.d/3x-ipl.conf /etc/fail2ban/jail.d/3x-ipl.conf +} + remove_iplimit() { echo -e "${green}\t1.${plain} Only remove IP Limit configurations" echo -e "${green}\t2.${plain} Uninstall Fail2ban and IP Limit" echo -e "${green}\t0.${plain} Back to Main Menu" - read -rp "Choose an option: " num + local num uninstall_package=false + read -rp "Choose an option (a running panel will restart to apply the change): " num case "$num" in - 1) - rm -f /etc/fail2ban/filter.d/3x-ipl.conf - rm -f /etc/fail2ban/action.d/3x-ipl.conf - rm -f /etc/fail2ban/jail.d/3x-ipl.conf - if [[ $release == "alpine" ]]; then - rc-service fail2ban restart - else - systemctl restart fail2ban + 1 | 2) + if [[ "$num" == "2" ]] && iplimit_can_uninstall; then + uninstall_package=true fi - echo -e "${green}IP Limit removed successfully!${plain}\n" - before_show_menu - ;; - 2) - rm -rf /etc/fail2ban - if [[ $release == "alpine" ]]; then - rc-service fail2ban stop - else - systemctl stop fail2ban + if ! apply_iplimit_preference false || ! remove_iplimit_jail; then + LOGE "IP Limit removal did not finish." + return 1 fi - case "${release}" in - ubuntu | debian | armbian) - apt-get remove -y fail2ban - apt-get purge -y fail2ban -y - apt-get autoremove -y - ;; - fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol) - dnf remove fail2ban -y - dnf autoremove -y - ;; - centos) - if [[ "${VERSION_ID}" =~ ^7 ]]; then - yum remove fail2ban -y - yum autoremove -y - else - dnf remove fail2ban -y - dnf autoremove -y - fi - ;; - arch | manjaro | parch) - pacman -Rns --noconfirm fail2ban - ;; - alpine) - apk del fail2ban - ;; - *) - echo -e "${red}Unsupported operating system. Please uninstall Fail2ban manually.${plain}\n" - exit 1 - ;; - esac - echo -e "${green}Fail2ban and IP Limit removed successfully!${plain}\n" + if [[ "$uninstall_package" == "true" ]]; then + case "${release}" in + ubuntu | debian | armbian) apt-get remove -y fail2ban ;; + fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol) dnf remove -y fail2ban ;; + centos) + if [[ "${VERSION_ID}" =~ ^7 ]]; then yum remove -y fail2ban; else dnf remove -y fail2ban; fi + ;; + arch | manjaro | parch) pacman -R --noconfirm fail2ban ;; + alpine) apk del fail2ban ;; + *) false ;; + esac || LOGE "Could not uninstall Fail2ban." + elif [[ "$num" == "2" ]]; then + echo "Keeping Fail2ban because other jails are present or its configuration could not be verified." + fi + if check_status; then restart 0; fi + echo -e "${green}IP Limit removed. Future updates will respect this choice.${plain}\n" before_show_menu ;; 0) @@ -2608,20 +2713,7 @@ create_iplimit_jails() { # Use default bantime if not passed => 30 minutes local bantime="${1:-30}" - # Uncomment 'allowipv6 = auto' in fail2ban.conf - sed -i 's/#allowipv6 = auto/allowipv6 = auto/g' /etc/fail2ban/fail2ban.conf - - # Debian 12+ / Ubuntu 22.04+ log sshd to the journal only; a jail.d override - # survives package upgrades. Only the stock 'backend = auto' is overridden. - if [[ ( "${release}" == "debian" && ${os_version} -ge 12 ) || ( "${release}" == "ubuntu" && ${os_version} -ge 2200 ) ]] && - sed -n '0,/action =/p' /etc/fail2ban/jail.conf | grep -q '^backend = auto'; then - cat << EOF > /etc/fail2ban/jail.d/3x-ipl-backend.conf -[DEFAULT] -backend = systemd -EOF - fi - - cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf + cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf || return 1 [3x-ipl] enabled=true backend=auto @@ -2633,7 +2725,7 @@ findtime=32 bantime=${bantime}m EOF - cat << EOF > /etc/fail2ban/filter.d/3x-ipl.conf + cat << EOF > /etc/fail2ban/filter.d/3x-ipl.conf || return 1 [Definition] datepattern = ^%%Y/%%m/%%d %%H:%%M:%%S failregex = \[LIMIT_IP\]\s*Email\s*=\s*.+\s*\|\|\s*Disconnecting OLD IP\s*=\s*\s*\|\|\s*Timestamp\s*=\s*\d+ @@ -2652,7 +2744,7 @@ EOF local exempt_ports="${ssh_ports}" [[ -n "${panel_port}" ]] && exempt_ports="${exempt_ports},${panel_port}" - cat << EOF > /etc/fail2ban/action.d/3x-ipl.conf + cat << EOF > /etc/fail2ban/action.d/3x-ipl.conf || return 1 [INCLUDES] before = iptables-allports.conf @@ -2690,11 +2782,20 @@ iplimit_remove_conflicts() { /etc/fail2ban/jail.local ) + local file temp for file in "${jail_files[@]}"; do - # Check for [3x-ipl] config in jail file then remove it - if test -f "${file}" && grep -qw '3x-ipl' ${file}; then - sed -i "/\[3x-ipl\]/,/^$/d" ${file} - echo -e "${yellow}Removing conflicts of [3x-ipl] in jail (${file})!${plain}\n" + [[ -f "$file" ]] && grep -Eq '^[[:space:]]*\[3x-ipl\]' "$file" || continue + if [[ -L "$file" ]]; then + file=$(readlink -f -- "$file") || return 1 + fi + temp=$(mktemp "${file}.XXXXXX") || return 1 + if ! { + cp -p -- "$file" "$temp" && + awk '/^[[:space:]]*\[/ { managed = ($0 ~ /^[[:space:]]*\[3x-ipl\]/) } !managed' "$file" > "$temp" && + mv -f -- "$temp" "$file" + }; then + rm -f -- "$temp" + return 1 fi done } @@ -3761,7 +3862,7 @@ if [[ $# -gt 0 ]]; then check_install 0 && show_banlog 0 ;; "setup-fail2ban") - setup_fail2ban_iplimit + setup_fail2ban_for_lifecycle "${2:-update}" ;; "update") check_install 0 && update 0 From 2db45393cf6d41b9b336eb2f6b862b97b161db01 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 11:02:51 +0330 Subject: [PATCH 114/130] fix(iplimit): install the iptables tools the ban action needs The 3x-ipl Fail2ban action bans with iptables and ip6tables, but the setup installed only fail2ban and nftables. Debian 12/13 and Ubuntu 22.04/24.04 do not pull iptables in with fail2ban, so on a host without it every ban logged "iptables: not found", showed up in the jail's banned list and applied no rule, while the setup reported success. A configured 3x-ipl jail now always has its ban tools. Writing the action installs them when they are missing, and so does an update over a jail an earlier release set up, whether the choice is stored or not. A jail that is already running is restarted after the install so bans it recorded without a rule get one. When the tools cannot be installed the setup fails with the reason instead of writing a jail that enforces nothing. The lifecycle fixture now models the tools as present, so its cases no longer depend on the host running the tests. --- scripts_fail2ban_test.go | 100 ++++++++++++++++++++++++++++++++++++++- x-ui.sh | 33 ++++++++++++- 2 files changed, 130 insertions(+), 3 deletions(-) diff --git a/scripts_fail2ban_test.go b/scripts_fail2ban_test.go index d99bde7af..ca7088848 100644 --- a/scripts_fail2ban_test.go +++ b/scripts_fail2ban_test.go @@ -107,7 +107,11 @@ systemctl() { } apt-get() { rm -f "$TEST_DIR/installed"; } command() { - if [[ $* == '-v fail2ban-client' ]]; then [[ -f "$TEST_DIR/installed" ]]; else builtin command "$@"; fi + case "$*" in + '-v fail2ban-client') [[ -f "$TEST_DIR/installed" ]] ;; + '-v iptables' | '-v ip6tables') [[ -f "$TEST_DIR/$2" ]] ;; + *) builtin command "$@" ;; + esac } fail2ban-client() { case "$*" in @@ -139,7 +143,7 @@ setup_fail2ban_iplimit() { "confirm", "read_fail2ban_preference", "persist_fail2ban_preference", "iplimit_jail_configured", "setup_fail2ban_for_lifecycle", "apply_iplimit_preference", "iplimit_remove_conflicts", "iplimit_can_uninstall", "remove_iplimit_jail", - "install_iplimit", "remove_iplimit", + "install_iplimit", "remove_iplimit", "iplimit_ban_tools_present", "ensure_iplimit_ban_tools", } { if strings.Contains(string(source), "\n"+name+"() {\n") { driver += strings.ReplaceAll(scriptFunction(t, "x-ui.sh", name), "/etc/fail2ban", filepath.Join(dir, "fail2ban")) @@ -159,9 +163,101 @@ setup_fail2ban_iplimit() { driver += wrapper } driver += "\nexport NONINTERACTIVE=1\n" + writeFail2banFixture(t, dir, "iptables", "") + writeFail2banFixture(t, dir, "ip6tables", "") return driver } +func TestIPLimitBanToolsAreEnsured(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("requires a POSIX shell") + } + bash, err := exec.LookPath("bash") + if err != nil { + t.Skip("requires bash") + } + const legacyJail = "[3x-ipl]\nenabled = true\nbantime = 47m\n" + const install = "update\ninstall -y iptables\n" + for _, tc := range []struct { + name, command, env, wantPackages, wantRestarts string + present, unavailable, jail, wantFailure bool + }{ + {name: "writing the action installs the missing tools", command: "create_iplimit_jails", wantPackages: install}, + {name: "present tools need no package and no restart", command: "create_iplimit_jails", present: true, jail: true}, + {name: "an update repairs a running legacy jail", command: "setup_fail2ban_for_lifecycle update", jail: true, wantPackages: install, wantRestarts: "restart 3x-ipl\n"}, + {name: "an update repairs a stored opt-in", command: "setup_fail2ban_for_lifecycle update", env: "XUI_ENABLE_FAIL2BAN=true\n", jail: true, wantPackages: install, wantRestarts: "restart 3x-ipl\n"}, + {name: "tools that cannot be installed fail the setup", command: "create_iplimit_jails", unavailable: true, wantPackages: install, wantFailure: true}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + driver := setupFail2banScriptFixture(t, dir) + ` +iplimit_log_path="$TEST_DIR/3xipl.log" iplimit_banned_log_path="$TEST_DIR/3xipl-banned.log" xui_folder="$TEST_DIR/app" +apt-get() { + printf '%s\n' "$*" >> "$TEST_DIR/packages" + if [[ $* == *iptables* && ! -f "$TEST_DIR/unavailable" ]]; then touch "$TEST_DIR/iptables" "$TEST_DIR/ip6tables"; fi +} +fail2ban-client() { + case "$*" in + 'status 3x-ipl') [[ -f "$TEST_DIR/managed-running" ]] ;; + 'restart 3x-ipl') printf '%s\n' "$*" >> "$TEST_DIR/restarts" ;; + *) return 1 ;; + esac +} +` + strings.ReplaceAll(scriptFunction(t, "x-ui.sh", "create_iplimit_jails"), "/etc/fail2ban", filepath.Join(dir, "fail2ban")) + for _, sub := range []string{"jail.d", "filter.d", "action.d"} { + if err := os.MkdirAll(filepath.Join(dir, "fail2ban", sub), 0o755); err != nil { + t.Fatal(err) + } + } + if !tc.present { + for _, tool := range []string{"iptables", "ip6tables"} { + if err := os.Remove(filepath.Join(dir, tool)); err != nil { + t.Fatal(err) + } + } + } + if tc.unavailable { + writeFail2banFixture(t, dir, "unavailable", "") + } + if tc.jail { + writeFail2banFixture(t, dir, "fail2ban/jail.d/3x-ipl.conf", legacyJail) + writeFail2banFixture(t, dir, "installed", "") + writeFail2banFixture(t, dir, "managed-running", "") + } + writeFail2banFixture(t, dir, "env", tc.env) + writeFail2banFixture(t, dir, "packages", "") + writeFail2banFixture(t, dir, "restarts", "") + cmd := exec.CommandContext(t.Context(), bash, "-c", driver+"\n"+tc.command) + for _, e := range os.Environ() { + if !strings.HasPrefix(e, "XUI_") && !strings.HasPrefix(e, "TEST_DIR=") { + cmd.Env = append(cmd.Env, e) + } + } + cmd.Env = append(cmd.Env, "TEST_DIR="+dir) + out, err := cmd.CombinedOutput() + if (err != nil) != tc.wantFailure { + t.Fatalf("shell flow error = %v, want failure %t\n%s", err, tc.wantFailure, out) + } + for _, tool := range []string{"iptables", "ip6tables"} { + _, statErr := os.Stat(filepath.Join(dir, tool)) + if (statErr == nil) == tc.wantFailure { + t.Errorf("%s present = %t after the flow, want %t", tool, statErr == nil, !tc.wantFailure) + } + } + if got := readScriptState(t, dir, "packages"); got != tc.wantPackages { + t.Errorf("package manager calls = %q, want %q", got, tc.wantPackages) + } + if got := readScriptState(t, dir, "restarts"); got != tc.wantRestarts { + t.Errorf("jail restarts = %q, want %q", got, tc.wantRestarts) + } + _, actionErr := os.Stat(filepath.Join(dir, "fail2ban", "action.d", "3x-ipl.conf")) + if tc.wantFailure && (actionErr == nil || !strings.Contains(string(out), "iptables and ip6tables")) { + t.Errorf("setup without ban tools wrote the action (stat %v) or hid the reason: %s", actionErr, out) + } + }) + } +} + func TestNativeFail2banStockSSHBackend(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("requires a POSIX shell") diff --git a/x-ui.sh b/x-ui.sh index d47d53a9b..2eeee3a38 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -2415,7 +2415,8 @@ setup_fail2ban_for_lifecycle() { choice=$(read_fail2ban_preference) || return 1 if [[ -z "$choice" ]] && iplimit_jail_configured; then # Preserve legacy jails, including later overrides to their enabled state. - return 0 + ensure_iplimit_ban_tools + return fi if [[ -z "$choice" ]]; then choice=false @@ -2432,6 +2433,7 @@ setup_fail2ban_for_lifecycle() { return 0 fi if command -v fail2ban-client > /dev/null 2>&1 && iplimit_jail_configured; then + ensure_iplimit_ban_tools || return 1 fail2ban-client status 3x-ipl > /dev/null 2>&1 || start_iplimit_jail return fi @@ -2709,10 +2711,39 @@ show_banlog() { fail2ban-client status 3x-ipl || echo -e "${yellow}Unable to get jail status${plain}" } +iplimit_ban_tools_present() { + command -v iptables > /dev/null 2>&1 && command -v ip6tables > /dev/null 2>&1 +} + +# The 3x-ipl action bans with iptables and ip6tables, which Debian and Ubuntu do not +# install with fail2ban; without them a ban is listed by fail2ban and never applied. +ensure_iplimit_ban_tools() { + iplimit_ban_tools_present && return 0 + case "${release}" in + ubuntu | debian | armbian) apt-get update && apt-get install -y iptables ;; + fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol) dnf -y install iptables ;; + centos) + if [[ "${VERSION_ID}" =~ ^7 ]]; then yum -y install iptables; else dnf -y install iptables; fi + ;; + arch | manjaro | parch) pacman -Sy --noconfirm iptables ;; + alpine) apk add iptables ;; + esac + if ! iplimit_ban_tools_present; then + LOGE "IP Limit bans need iptables and ip6tables, which could not be installed." + return 1 + fi + # Bans recorded while the tools were missing get their rules when the jail restarts. + if fail2ban-client status 3x-ipl > /dev/null 2>&1; then + fail2ban-client restart 3x-ipl > /dev/null || return 1 + fi +} + create_iplimit_jails() { # Use default bantime if not passed => 30 minutes local bantime="${1:-30}" + ensure_iplimit_ban_tools || return 1 + cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf || return 1 [3x-ipl] enabled=true From 408fd682f520d294293d77a36034022c146760cb Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 11:31:20 +0330 Subject: [PATCH 115/130] fix(node): count a restarted node counter once while its client is frozen While a client's lifecycle was frozen (node config_dirty, a push that just landed, a reset the node still owes, or a client the node only reports usage for), a node counter that fell below the stored baseline left that baseline untouched. The other field's growth was still added to the client, and because the baseline never moved the same amount was added again on every sync tick: an idle client gained gigabytes per minute and was cut off. A client whose counters stayed below the old baseline had the opposite problem, and none of its usage was counted. The baseline was held back on purpose (#6228): the dip is the evidence that the node renewed the client, and it had to survive until an unfrozen tick could judge it. The baseline was doing two jobs. It now always follows the node, so a delta is added once, and the unjudged dip is kept in a new node_client_traffics.dipped_while_frozen column that the first unfrozen tick consumes. A renewal seen while frozen is now also adopted when the client's usage has since outgrown the pre-renewal baseline; before, that evidence was lost. Usage already over-counted cannot be recovered and needs a manual reset. A baseline that is stuck at upgrade time adds its delta one last time on the first sync and is correct from then on. --- internal/database/db.go | 11 +++ .../database/model/node_client_traffic.go | 3 + .../node_client_traffic_dip_migration_test.go | 52 +++++++++++ internal/web/service/inbound_node.go | 46 +++++---- internal/web/service/node_frozen_dip_test.go | 93 +++++++++++++++++++ 5 files changed, 188 insertions(+), 17 deletions(-) create mode 100644 internal/database/node_client_traffic_dip_migration_test.go create mode 100644 internal/web/service/node_frozen_dip_test.go diff --git a/internal/database/db.go b/internal/database/db.go index b6f2d512e..64659eae1 100644 --- a/internal/database/db.go +++ b/internal/database/db.go @@ -126,6 +126,14 @@ func migrateInboundPreserveClientTrafficColumn(tx *gorm.DB) error { return migrator.AddColumn(&model.Inbound{}, "PreserveClientTraffic") } +func migrateNodeClientTrafficDippedWhileFrozenColumn(tx *gorm.DB) error { + migrator := tx.Migrator() + if !migrator.HasTable(&model.NodeClientTraffic{}) || migrator.HasColumn(&model.NodeClientTraffic{}, "dipped_while_frozen") { + return nil + } + return migrator.AddColumn(&model.NodeClientTraffic{}, "DippedWhileFrozen") +} + func migrateClientKeepAliveRangeColumn() error { migrator := db.Migrator() if !migrator.HasTable(&model.ClientRecord{}) || migrator.HasColumn(&model.ClientRecord{}, "wg_keep_alive_range") { @@ -150,6 +158,9 @@ func initModels() error { if err := migrateInboundPreserveClientTrafficColumn(db); err != nil { return err } + if err := migrateNodeClientTrafficDippedWhileFrozenColumn(db); err != nil { + return err + } models := allModels() for _, mdl := range models { if IsPostgres() && postgresModelSettled(mdl) { diff --git a/internal/database/model/node_client_traffic.go b/internal/database/model/node_client_traffic.go index 08a0952fb..ec9f83245 100644 --- a/internal/database/model/node_client_traffic.go +++ b/internal/database/model/node_client_traffic.go @@ -6,4 +6,7 @@ type NodeClientTraffic struct { Email string `json:"email" gorm:"uniqueIndex:idx_node_email,priority:2;not null"` Up int64 `json:"up"` Down int64 `json:"down"` + // The node counter fell below this baseline while the client's lifecycle was + // frozen: renewal evidence the merge has not judged yet (#6228). + DippedWhileFrozen bool `json:"dippedWhileFrozen" gorm:"not null;default:false"` } diff --git a/internal/database/node_client_traffic_dip_migration_test.go b/internal/database/node_client_traffic_dip_migration_test.go new file mode 100644 index 000000000..fb88b3802 --- /dev/null +++ b/internal/database/node_client_traffic_dip_migration_test.go @@ -0,0 +1,52 @@ +package database + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestMigrateNodeClientTrafficDippedWhileFrozenColumn(t *testing.T) { + initMigrateDB(t) + tx := GetDB().Begin() + if tx.Error != nil { + t.Fatal(tx.Error) + } + t.Cleanup(func() { tx.Rollback() }) + + // Recreate the previous schema in this transaction on SQLite or PostgreSQL. + if err := tx.Exec("ALTER TABLE node_client_traffics DROP COLUMN dipped_while_frozen").Error; err != nil { + t.Fatal(err) + } + const email = "legacy-baseline@x" + if err := tx.Exec("INSERT INTO node_client_traffics (node_id, email, up, down) VALUES (7, ?, 30, 50)", email).Error; err != nil { + t.Fatal(err) + } + if err := migrateNodeClientTrafficDippedWhileFrozenColumn(tx); err != nil { + t.Fatal(err) + } + var stored model.NodeClientTraffic + if err := tx.Where("email = ?", email).First(&stored).Error; err != nil { + t.Fatal(err) + } + if stored.NodeId != 7 || stored.Up != 30 || stored.Down != 50 || stored.DippedWhileFrozen { + t.Fatalf("legacy baseline after migration: node=%d up=%d down=%d dipped=%t, want 7/30/50/false", + stored.NodeId, stored.Up, stored.Down, stored.DippedWhileFrozen) + } + var nulls int64 + if err := tx.Raw("SELECT COUNT(*) FROM node_client_traffics WHERE dipped_while_frozen IS NULL").Scan(&nulls).Error; err != nil { + t.Fatal(err) + } + if nulls != 0 { + t.Fatalf("migration left %d NULL dipped_while_frozen cell(s), want 0", nulls) + } + if err := tx.Model(&stored).Update("dipped_while_frozen", true).Error; err != nil { + t.Fatal(err) + } + if err := migrateNodeClientTrafficDippedWhileFrozenColumn(tx); err != nil { + t.Fatalf("repeat migration: %v", err) + } + if err := tx.First(&stored, stored.Id).Error; err != nil || !stored.DippedWhileFrozen { + t.Fatalf("repeat migration lost the pending dip: dipped=%t, err=%v", stored.DippedWhileFrozen, err) + } +} diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index c3861ec86..6630462cb 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -247,11 +247,13 @@ type nodeTrafficCounter struct { Down int64 } -func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error { +func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, counter nodeTrafficCounter, dippedWhileFrozen bool) error { return tx.Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}}, - DoUpdates: clause.AssignmentColumns([]string{"up", "down"}), - }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error + DoUpdates: clause.AssignmentColumns([]string{"up", "down", "dipped_while_frozen"}), + }).Create(&model.NodeClientTraffic{ + NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dippedWhileFrozen, + }).Error } // mergeNodeClientTraffic folds one node-reported client into its central row. @@ -354,8 +356,8 @@ func applyMasterClientLifecycle(c *model.Client, master *xray.ClientTraffic, cs } // nodeClientRenewed reports a node-side auto-renew: an absolute deadline moved -// forward, evidenced by a renewal-count bump or a drop below the stored baseline. -func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, canon, base nodeTrafficCounter) bool { +// forward, evidenced by a renewal-count bump or a counter that fell below its baseline. +func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, counterDipped bool) bool { if (cs.Reset <= 0 && cs.ResetDay <= 0 && cs.ResetWeekday <= 0) || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 { return false } @@ -367,7 +369,7 @@ func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, cano if cs.ResetCount > existing.ResetCount { return true } - return canon.Up < base.Up || canon.Down < base.Down + return counterDipped } // liftActivatedClientRecordExpiries copies a node-activated deadline from @@ -639,6 +641,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } nodeBaselines := make(map[string]nodeTrafficCounter) + dippedWhileFrozen := make(map[string]bool) var baselineRows []model.NodeClientTraffic if err := db.Model(&model.NodeClientTraffic{}). Where("node_id = ?", nodeID). @@ -647,6 +650,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } for i := range baselineRows { nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down} + if baselineRows[i].DippedWhileFrozen { + dippedWhileFrozen[baselineRows[i].Email] = true + } } var defaultUserId int @@ -1125,6 +1131,8 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi deltaDown = 0 } } + // A dip seen while frozen stays owed until an unfrozen tick judges it. + counterDipped := dippedWhileFrozen[cs.Email] || (seen && (canon.Up < base.Up || canon.Down < base.Down)) if _, rowExists := statByEmail[cs.Email]; !rowExists { if dirty { @@ -1166,10 +1174,11 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi centralCSByEmail[cs.Email] = row statByEmail[cs.Email] = row structuralChange = true - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil { + if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, false); err != nil { return false, err } - nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down} + nodeBaselines[cs.Email] = canon + delete(dippedWhileFrozen, cs.Email) continue } @@ -1186,7 +1195,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } - renewed := !clientFrozen && seen && existing != nil && nodeClientRenewed(existing, cs, canon, base) + renewed := !clientFrozen && seen && existing != nil && nodeClientRenewed(existing, cs, counterDipped) if renewed { // Reject when the node's own settings still carry the old absolute: // lagging ClientStats after a master shorten mimic a renew (#6228). @@ -1253,18 +1262,21 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi *row = next } } - // A dip plus a lagging longer expiry mimics nodeClientRenewed and would - // undo a master shorten once the freeze lifts (#6228). - if clientFrozen && seen && (canon.Up < base.Up || canon.Down < base.Down) { + // The baseline always follows the node so a delta is added once; a frozen + // tick cannot judge a renewal, so its dip is carried on the row instead. + stillOwed := clientFrozen && counterDipped + if seen && base == canon && stillOwed == dippedWhileFrozen[cs.Email] { continue } - if seen && base == canon { - continue - } - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil { + if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, stillOwed); err != nil { return false, err } - nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down} + nodeBaselines[cs.Email] = canon + if stillOwed { + dippedWhileFrozen[cs.Email] = true + } else { + delete(dippedWhileFrozen, cs.Email) + } } for k, existing := range centralCS { diff --git a/internal/web/service/node_frozen_dip_test.go b/internal/web/service/node_frozen_dip_test.go new file mode 100644 index 000000000..107933b1e --- /dev/null +++ b/internal/web/service/node_frozen_dip_test.go @@ -0,0 +1,93 @@ +package service + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func syncDirtyNode(t *testing.T, svc *InboundService, nodeID int, tag, settings string, stats ...xray.ClientTraffic) { + t.Helper() + snap := &runtime.TrafficSnapshot{ + Inbounds: []*model.Inbound{{Tag: tag, Settings: settings, ClientStats: stats}}, + } + if _, err := svc.setRemoteTrafficLocked(nodeID, snap, true, false); err != nil { + t.Fatalf("dirty setRemoteTrafficLocked node %d: %v", nodeID, err) + } +} + +// A node counter that restarted below the baseline while the node is dirty must +// add the other field's growth once, not again on every tick. +func TestNodeFrozenDip_IdleClientCountedOnce(t *testing.T) { + db := initTrafficTestDB(t) + svc := &InboundService{} + + const email = "idle@x" + seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true}) + createNodeInboundWithClient(t, db, 1, "n1-in", 41001, email) + settings := `{"clients":[{"email":"idle@x","enable":true}]}` + for range 2 { + syncNodeWithSettings(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: email, Up: 2000, Down: 3000, Enable: true}) + } + before := readTraffic(t, db, email) + + for range 3 { + syncDirtyNode(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: email, Up: 100, Down: 18000, Enable: true}) + } + + assertUpDown(t, readTraffic(t, db, email), before.Up, before.Down+15000, "after three dirty ticks of an idle client") +} + +// Usage a client makes below the pre-restart baseline while the node is dirty +// must still be counted. +func TestNodeFrozenDip_UsageBelowOldBaselineCounted(t *testing.T) { + db := initTrafficTestDB(t) + svc := &InboundService{} + + const email = "active@x" + seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true}) + createNodeInboundWithClient(t, db, 1, "n1-in", 41001, email) + settings := `{"clients":[{"email":"active@x","enable":true}]}` + for range 2 { + syncNodeWithSettings(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: email, Up: 5000, Down: 5000, Enable: true}) + } + before := readTraffic(t, db, email) + + for _, used := range []int64{100, 1000, 4000} { + syncDirtyNode(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: email, Up: used, Down: used, Enable: true}) + } + + assertUpDown(t, readTraffic(t, db, email), before.Up+3900, before.Down+3900, "after the restarted counter grew to 4000") +} + +// A node-side renewal seen while dirty must still be adopted on the first clean +// tick, even after the client's usage outgrew the pre-renewal baseline. +func TestNodeFrozenDip_RenewalSurvivesUsagePastOldBaseline(t *testing.T) { + db := initTrafficTestDB(t) + createNodeInbound(t, db, 1, "n1-in", 41001) + svc := &InboundService{} + + const email = "renew-then-use" + syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{ + Email: email, Up: 100, Down: 100, ExpiryTime: earlyAbs, Enable: true, Reset: 30, + }) + if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email). + Updates(map[string]any{"expiry_time": earlyAbs, "enable": true, "up": int64(100), "down": int64(100)}).Error; err != nil { + t.Fatalf("seed master: %v", err) + } + + renewed := xray.ClientTraffic{Email: email, Up: 10, Down: 10, ExpiryTime: lateAbs, Enable: true, Reset: 30} + syncDirtyNode(t, svc, 1, "n1-in", "", renewed) + renewed.Up, renewed.Down = 500, 500 + syncDirtyNode(t, svc, 1, "n1-in", "", renewed) + if got := readTraffic(t, db, email).ExpiryTime; got != earlyAbs { + t.Fatalf("renewal while dirty raised expiry: got %d want %d", got, earlyAbs) + } + + syncNode(t, svc, 1, "n1-in", renewed) + if got := readTraffic(t, db, email).ExpiryTime; got != lateAbs { + t.Fatalf("renewal after the dirty flag cleared did not apply: got %d want %d", got, lateAbs) + } +} From 6d9a23feb51c77b23b0ff7f5a0bc33c8f87b5986 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 11:31:20 +0330 Subject: [PATCH 116/130] style(tests): clear the editor diagnostics in the service tests The config scale benchmark used the b.N loop that gopls flags for modernization; it now uses b.Loop, which also makes its ResetTimer and StopTimer calls redundant. assertInboundClientGroup and seedUsageHistoryClient each took a parameter they never read, so the parameters and the arguments passed for them are gone. --- .../service/client_group_host_binding_test.go | 8 +++--- .../web/service/client_usage_history_test.go | 25 +++++++++---------- .../web/service/xray_config_scale_test.go | 4 +-- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/internal/web/service/client_group_host_binding_test.go b/internal/web/service/client_group_host_binding_test.go index 6a913c60d..c398659ab 100644 --- a/internal/web/service/client_group_host_binding_test.go +++ b/internal/web/service/client_group_host_binding_test.go @@ -387,20 +387,20 @@ func TestClientGroup_RenameAndDeleteFollowCanonicalizedJSONCase(t *testing.T) { if rec.Group != "VIP" { t.Fatalf("client group = %q, want canonical VIP", rec.Group) } - assertInboundClientGroup(t, db, ib.Id, "case@x", "vip") + assertInboundClientGroup(t, db, ib.Id, "vip") if _, err := svc.UpdateGroup("VIP", "Gold", nil); err != nil { t.Fatalf("UpdateGroup: %v", err) } - assertInboundClientGroup(t, db, ib.Id, "case@x", "Gold") + assertInboundClientGroup(t, db, ib.Id, "Gold") if _, err := svc.DeleteGroup("Gold"); err != nil { t.Fatalf("DeleteGroup: %v", err) } - assertInboundClientGroup(t, db, ib.Id, "case@x", "") + assertInboundClientGroup(t, db, ib.Id, "") } -func assertInboundClientGroup(t *testing.T, db *gorm.DB, inboundID int, email, want string) { +func assertInboundClientGroup(t *testing.T, db *gorm.DB, inboundID int, want string) { t.Helper() var settings string if err := db.Model(&model.Inbound{}).Where("id = ?", inboundID).Pluck("settings", &settings).Error; err != nil { diff --git a/internal/web/service/client_usage_history_test.go b/internal/web/service/client_usage_history_test.go index 28272c577..445a3fb80 100644 --- a/internal/web/service/client_usage_history_test.go +++ b/internal/web/service/client_usage_history_test.go @@ -12,7 +12,7 @@ import ( // seedUsageHistoryClient seeds a local VLESS inbound hosting one client and a // live traffic row with the given counters. -func seedUsageHistoryClient(t *testing.T, inboundSvc *InboundService, email, uid string, up, down int64) *model.Inbound { +func seedUsageHistoryClient(t *testing.T, email, uid string, up, down int64) *model.Inbound { t.Helper() setupBulkDB(t) svc := &ClientService{} @@ -90,7 +90,7 @@ func TestEveryResetPathArchivesTheWindowItCloses(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { inbounds, clients := &InboundService{}, &ClientService{} - ib := seedUsageHistoryClient(t, inbounds, email, "44444444-1111-4111-8111-111111111111", 100, 200) + ib := seedUsageHistoryClient(t, email, "44444444-1111-4111-8111-111111111111", 100, 200) if err := tc.reset(inbounds, clients, ib); err != nil { t.Fatal(err) } @@ -115,7 +115,7 @@ func TestEveryResetPathArchivesTheWindowItCloses(t *testing.T) { func TestWindowsPastTheCapFoldWithoutChangingLifetime(t *testing.T) { const email = "capped@example.test" inbounds, clients := &InboundService{}, &ClientService{} - ib := seedUsageHistoryClient(t, inbounds, email, "12121212-1111-4111-8111-111111111111", 100, 200) + ib := seedUsageHistoryClient(t, email, "12121212-1111-4111-8111-111111111111", 100, 200) db := database.GetDB() seeded := make([]model.ClientTrafficWindow, 0, clientTrafficWindowKeep) for i := range clientTrafficWindowKeep { @@ -169,7 +169,7 @@ func TestWindowsPastTheCapFoldWithoutChangingLifetime(t *testing.T) { func TestLifetimeCountsTheOpenWindow(t *testing.T) { const email = "open-win@example.test" inbounds, clients := &InboundService{}, &ClientService{} - ib := seedUsageHistoryClient(t, inbounds, email, "17171717-1111-4111-8111-111111111111", 100, 200) + ib := seedUsageHistoryClient(t, email, "17171717-1111-4111-8111-111111111111", 100, 200) if _, err := inbounds.ResetClientTraffic(ib.Id, email); err != nil { t.Fatal(err) } @@ -191,7 +191,7 @@ func TestLifetimeCountsTheOpenWindow(t *testing.T) { func TestChangeLogKeepsTheNewestRowsPerClient(t *testing.T) { const email, other = "chatty@example.test", "quiet@example.test" inbounds, clients := &InboundService{}, &ClientService{} - seedUsageHistoryClient(t, inbounds, email, "13131313-1111-4111-8111-111111111111", 0, 0) + seedUsageHistoryClient(t, email, "13131313-1111-4111-8111-111111111111", 0, 0) db := database.GetDB() seeded := make([]model.ClientChangeLog, 0, clientChangeLogKeep+1) for i := range clientChangeLogKeep { @@ -226,7 +226,7 @@ func TestChangeLogKeepsTheNewestRowsPerClient(t *testing.T) { func TestBotAndBulkEditsAreLoggedWithTheirSource(t *testing.T) { const email = "edited@example.test" inbounds, clients := &InboundService{}, &ClientService{} - seedUsageHistoryClient(t, inbounds, email, "14141414-1111-4111-8111-111111111111", 0, 0) + seedUsageHistoryClient(t, email, "14141414-1111-4111-8111-111111111111", 0, 0) // The bulk add skips an unlimited client, so the bot sets a limit first. if _, err := clients.ResetClientTrafficLimitByEmail(inbounds, email, 1); err != nil { @@ -254,7 +254,7 @@ func TestBotAndBulkEditsAreLoggedWithTheirSource(t *testing.T) { func TestHistoryOfADeletedClientIsReaped(t *testing.T) { const gone, kept = "gone@example.test", "kept@example.test" inbounds, clients := &InboundService{}, &ClientService{} - seedUsageHistoryClient(t, inbounds, gone, "15151515-1111-4111-8111-111111111111", 0, 0) + seedUsageHistoryClient(t, gone, "15151515-1111-4111-8111-111111111111", 0, 0) stays := model.Client{Email: kept, ID: "16161616-1111-4111-8111-111111111111", SubID: kept, Enable: true} ib := mkInbound(t, 54506, model.VLESS, clientsSettings(t, []model.Client{stays})) if err := clients.SyncInbound(nil, ib.Id, []model.Client{stays}); err != nil { @@ -323,7 +323,7 @@ func TestReapSparesAnEmailClaimedAfterItWasListed(t *testing.T) { // Bulk reset archives only the rows that actually carried usage. func TestBulkResetArchivesUsedWindowsOnly(t *testing.T) { inboundSvc := &InboundService{} - seedUsageHistoryClient(t, inboundSvc, "bulk-used@example.test", "55555555-2222-4222-8222-222222222222", 10, 5) + seedUsageHistoryClient(t, "bulk-used@example.test", "55555555-2222-4222-8222-222222222222", 10, 5) svc := &ClientService{} // A second zero-usage client on its own inbound. @@ -404,7 +404,7 @@ func TestAutoRenewArchivesRenewWindowAndLogsExpiry(t *testing.T) { // no-op save logs nothing. func TestUpdateLogsChangedFieldsOnly(t *testing.T) { inboundSvc := &InboundService{} - seedUsageHistoryClient(t, inboundSvc, "upd-log@example.test", "99999999-6666-4666-8666-666666666666", 0, 0) + seedUsageHistoryClient(t, "upd-log@example.test", "99999999-6666-4666-8666-666666666666", 0, 0) svc := &ClientService{} rec, err := svc.GetRecordByEmail(nil, "upd-log@example.test") @@ -448,7 +448,7 @@ func TestUpdateLogsChangedFieldsOnly(t *testing.T) { // Bulk enable/disable logs an "enable" row only for the clients that flipped. func TestBulkSetEnableLogsOnlyFlippedClients(t *testing.T) { inboundSvc := &InboundService{} - seedUsageHistoryClient(t, inboundSvc, "bulk-en-a@example.test", "aaaaaaaa-7777-4777-8777-777777777777", 0, 0) + seedUsageHistoryClient(t, "bulk-en-a@example.test", "aaaaaaaa-7777-4777-8777-777777777777", 0, 0) svc := &ClientService{} clientB := model.Client{Email: "bulk-en-b@example.test", ID: "bbbbbbbb-8888-4888-8888-888888888888", SubID: "bulk-en-b@example.test", Enable: true} ib2 := mkInbound(t, 54505, model.VLESS, clientsSettings(t, []model.Client{clientB})) @@ -479,7 +479,7 @@ func TestBulkSetEnableLogsOnlyFlippedClients(t *testing.T) { func TestRenameMigratesClientHistory(t *testing.T) { const oldEmail, newEmail = "old-name@example.test", "new-name@example.test" inboundSvc := &InboundService{} - ib := seedUsageHistoryClient(t, inboundSvc, oldEmail, "cccccccc-9999-4999-8999-999999999999", 7, 9) + ib := seedUsageHistoryClient(t, oldEmail, "cccccccc-9999-4999-8999-999999999999", 7, 9) svc := &ClientService{} same := model.Client{Email: oldEmail, ID: "cccccccc-9999-4999-8999-999999999999", SubID: oldEmail, Enable: true} second := mkInbound(t, 54507, model.VLESS, clientsSettings(t, []model.Client{same})) @@ -555,8 +555,7 @@ func TestRenameOfAnUnattachedClientMigratesItsHistory(t *testing.T) { // GetUsageHistory must report the node's own accumulated up/down, separated. func TestGetUsageHistoryReportsNodeUsage(t *testing.T) { - inboundSvc := &InboundService{} - seedUsageHistoryClient(t, inboundSvc, "node-usage@example.test", "eeeeeeee-bbbb-4bbb-8bbb-bbbbbbbbbbbb", 0, 0) + seedUsageHistoryClient(t, "node-usage@example.test", "eeeeeeee-bbbb-4bbb-8bbb-bbbbbbbbbbbb", 0, 0) db := database.GetDB() node := &model.Node{ diff --git a/internal/web/service/xray_config_scale_test.go b/internal/web/service/xray_config_scale_test.go index e0d8c0107..9535b9891 100644 --- a/internal/web/service/xray_config_scale_test.go +++ b/internal/web/service/xray_config_scale_test.go @@ -33,13 +33,11 @@ func BenchmarkGetXrayConfigDisabledClients(b *testing.B) { } svc := &XrayService{} b.ReportAllocs() - b.ResetTimer() - for range b.N { + for b.Loop() { if _, err := svc.GetXrayConfig(); err != nil { b.Fatal(err) } } - b.StopTimer() const marker = "disabled-client benchmark log boundary" logger.Info(marker) if _, err := svc.GetXrayConfig(); err != nil { From 3e1fc3c24fc035634ae024b6fb4b92427cbbdc7d Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 12:05:06 +0330 Subject: [PATCH 117/130] fix(mtproto): stop relaying strangers to the fronting CDN, count fronted traffic An MTProto inbound must not relay a stranger's connection to a public host picked by an SNI the panel never configured, and every byte it moves must show up in the inbound's traffic. mtg relays whatever it cannot serve as a proxy to the fronting target, byte for byte, and the target answers by the SNI of that connection. With the default FakeTLS domain on a CDN, anybody could reach any site of that CDN through the inbound ("clean IP"). mtg dials the target itself, past the Xray bridge and outside every secret, so neither the clients nor the inbound showed that traffic. - The generated config sets [domain-fronting] require-sni-match (mtg-multi 1.17.0) unless the fronting IP is a loopback, private or link-local address, i.e. the operator's own web server. mtg then relays only a ClientHello naming the FakeTLS domain and closes the rest. An older mtg ignores the key. - The /stats "fronting" counters are scraped per process and added to the inbound's total, for routed inbounds too. TestRenderConfig pinned the old rule (a bare config has no [domain-fronting] section) and now expects the section without a host. --- internal/mtproto/manager.go | 101 +++++++++++++------ internal/mtproto/manager_fronting_test.go | 117 ++++++++++++++++++++++ internal/mtproto/manager_mutation_test.go | 3 +- internal/mtproto/manager_test.go | 6 +- internal/web/job/mtproto_job.go | 37 ++++--- internal/web/job/mtproto_job_test.go | 48 +++++++++ 6 files changed, 263 insertions(+), 49 deletions(-) create mode 100644 internal/mtproto/manager_fronting_test.go create mode 100644 internal/web/job/mtproto_job_test.go diff --git a/internal/mtproto/manager.go b/internal/mtproto/manager.go index fdd19127d..b37d3c4ff 100644 --- a/internal/mtproto/manager.go +++ b/internal/mtproto/manager.go @@ -10,6 +10,7 @@ import ( "maps" "net" "net/http" + "net/netip" "net/url" "os" "slices" @@ -129,11 +130,24 @@ type Traffic struct { Down int64 } +// FrontedTraffic is what an mtg process relayed to its fronting target since the +// previous scrape. No client owns these bytes; only the inbound does. +type FrontedTraffic struct { + Tag string + Up int64 + Down int64 +} + type clientCounters struct { up int64 down int64 } +// since returns the growth over prev; a counter that went backwards counts as none. +func (c clientCounters) since(prev clientCounters) (up, down int64) { + return max(c.up-prev.up, 0), max(c.down-prev.down, 0) +} + type managed struct { proc *Process tag string @@ -142,6 +156,7 @@ type managed struct { apiPort int apiToken string last map[string]clientCounters + fronted clientCounters } // Manager owns the set of running mtg processes keyed by inbound id. @@ -411,16 +426,16 @@ func (m *Manager) StopAll() { } } -// CollectTraffic scrapes each running mtg /stats endpoint and returns the -// per-client byte deltas since the previous scrape, plus the emails of clients -// with at least one live connection. -func (m *Manager) CollectTraffic() ([]Traffic, []string) { +// CollectTraffic scrapes each running mtg /stats endpoint for the byte deltas since the +// previous scrape, per client and per inbound's fronted connections, and the online emails. +func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { type snap struct { id int apiPort int apiToken string tag string last map[string]clientCounters + fronted clientCounters } m.mu.Lock() snaps := make([]snap, 0, len(m.procs)) @@ -430,22 +445,22 @@ func (m *Manager) CollectTraffic() ([]Traffic, []string) { } lastCopy := make(map[string]clientCounters, len(cur.last)) maps.Copy(lastCopy, cur.last) - snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy}) + snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy, fronted: cur.fronted}) } m.mu.Unlock() var out []Traffic + var fronted []FrontedTraffic var online []string for _, s := range snaps { - users, ok := scrapeStats(s.apiPort, s.apiToken) + stats, ok := scrapeStats(s.apiPort, s.apiToken) if !ok { continue } - newLast := make(map[string]clientCounters, len(users)) - for email, u := range users { - up := u.BytesIn - down := u.BytesOut - newLast[email] = clientCounters{up: up, down: down} + newLast := make(map[string]clientCounters, len(stats.Users)) + for email, u := range stats.Users { + now := u.counters() + newLast[email] = now if u.Connections > 0 { online = append(online, email) } @@ -453,26 +468,24 @@ func (m *Manager) CollectTraffic() ([]Traffic, []string) { if !had { continue } - du := up - prev.up - dd := down - prev.down - if du < 0 { - du = 0 - } - if dd < 0 { - dd = 0 - } - if du > 0 || dd > 0 { + if du, dd := now.since(prev); du > 0 || dd > 0 { out = append(out, Traffic{Tag: s.tag, Email: email, Up: du, Down: dd}) } } + // mtg counts fronted bytes from zero at start, the same point this baseline begins. + frontedNow := stats.Fronting.counters() + if du, dd := frontedNow.since(s.fronted); du > 0 || dd > 0 { + fronted = append(fronted, FrontedTraffic{Tag: s.tag, Up: du, Down: dd}) + } m.mu.Lock() if cur, ok := m.procs[s.id]; ok { cur.last = newLast + cur.fronted = frontedNow } m.mu.Unlock() } - return out, online + return out, fronted, online } func (m *Manager) HasRunning() bool { @@ -563,7 +576,8 @@ func renderConfig(inst Instance, apiPort int, apiToken string) string { if inst.PublicIPv6 != "" { fmt.Fprintf(&b, "public-ipv6 = %q\n", inst.PublicIPv6) } - if inst.FrontingIP != "" || inst.FrontingPort > 0 || inst.FrontingProxyProtocol { + requireSNIMatch := !frontsIntoOwnNetwork(inst.FrontingIP) + if inst.FrontingIP != "" || inst.FrontingPort > 0 || inst.FrontingProxyProtocol || requireSNIMatch { b.WriteString("\n[domain-fronting]\n") if inst.FrontingIP != "" { fmt.Fprintf(&b, "host = %q\n", inst.FrontingIP) @@ -574,6 +588,9 @@ func renderConfig(inst Instance, apiPort int, apiToken string) string { if inst.FrontingProxyProtocol { b.WriteString("proxy-protocol = true\n") } + if requireSNIMatch { + b.WriteString("require-sni-match = true\n") + } } // When the inbound opts into Xray routing, mtg reaches Telegram through the // loopback SOCKS bridge the panel injects into the running Xray config. mtg @@ -620,6 +637,16 @@ func renderConfig(inst Instance, apiPort int, apiToken string) string { return b.String() } +// frontsIntoOwnNetwork reports whether the fronting target is the operator's own server. +// Any other target answers by the stranger's SNI: a CDN there makes the inbound an open relay. +func frontsIntoOwnNetwork(host string) bool { + addr, err := netip.ParseAddr(host) + if err != nil { + return false + } + return addr.IsLoopback() || addr.IsPrivate() || addr.IsLinkLocalUnicast() +} + func writeConfig(path string, inst Instance, apiPort int, apiToken string) error { if err := os.MkdirAll(configDir(), 0o750); err != nil { return err @@ -636,6 +663,17 @@ type statsUser struct { BytesOut int64 `json:"bytes_out"` } +func (u statsUser) counters() clientCounters { + return clientCounters{up: u.BytesIn, down: u.BytesOut} +} + +// statsSnapshot is the part of mtg-multi's /stats the panel reads. Fronting counts the +// connections relayed to the fronting target; a binary older than 1.17.0 omits it. +type statsSnapshot struct { + Users map[string]statsUser `json:"users"` + Fronting statsUser `json:"fronting"` +} + type secretPutEntry struct { Secret string `json:"secret"` AdTag string `json:"ad_tag,omitempty"` @@ -718,26 +756,23 @@ func applySecrets(port int, token string, inst Instance) bool { return resp.StatusCode == http.StatusOK } -// scrapeStats reads the mtg-multi /stats JSON API and returns the per-user -// cumulative counters. Best-effort: an unreachable endpoint or unparseable body -// yields ok=false. -func scrapeStats(port int, token string) (map[string]statsUser, bool) { +// scrapeStats reads the mtg-multi /stats JSON API. Best-effort: an unreachable +// endpoint or unparseable body yields ok=false. +func scrapeStats(port int, token string) (statsSnapshot, bool) { client := http.Client{Timeout: 3 * time.Second} req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/stats", port), nil) if err != nil { - return nil, false + return statsSnapshot{}, false } authorize(req, token) resp, err := client.Do(req) if err != nil { - return nil, false + return statsSnapshot{}, false } defer resp.Body.Close() - var parsed struct { - Users map[string]statsUser `json:"users"` - } + var parsed statsSnapshot if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { - return nil, false + return statsSnapshot{}, false } - return parsed.Users, true + return parsed, true } diff --git a/internal/mtproto/manager_fronting_test.go b/internal/mtproto/manager_fronting_test.go new file mode 100644 index 000000000..df9b06c61 --- /dev/null +++ b/internal/mtproto/manager_fronting_test.go @@ -0,0 +1,117 @@ +package mtproto + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" +) + +// mtg relays an unauthenticated connection to the fronting target by the SNI the +// stranger sent, so a public target turns the inbound into an open relay (CDN "clean IP"). +func TestRenderConfigRequiresSNIMatchForPublicFronting(t *testing.T) { + cases := []struct { + name string + frontingIP string + want bool + }{ + {"FakeTLS domain resolved over DNS", "", true}, + {"public address", "104.16.132.229", true}, + {"hostname", "cdn.example.com", true}, + {"loopback web server", "127.0.0.1", false}, + {"IPv6 loopback web server", "::1", false}, + {"web server on the private network", "10.0.0.5", false}, + {"web server on a unique-local network", "fd00::5", false}, + {"web server on the link", "169.254.10.1", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := renderConfig(Instance{ + Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}}, + Listen: "0.0.0.0", Port: 2087, + FrontingIP: tc.frontingIP, + }, 5000, "") + got := strings.Contains(cfg, "\n[domain-fronting]\n") && strings.Contains(cfg, "\nrequire-sni-match = true\n") + if got != tc.want { + t.Fatalf("require-sni-match emitted = %v, want %v:\n%s", got, tc.want, cfg) + } + if strings.Index(cfg, "require-sni-match") > strings.Index(cfg, "[secrets]") { + t.Fatalf("require-sni-match must stay inside [domain-fronting], before [secrets]:\n%s", cfg) + } + }) + } +} + +// Fronted bytes belong to no secret, so they never showed in the per-user map: +// an inbound relaying gigabytes to its fronting domain reported no traffic. +func TestCollectTrafficReportsFrontedBytes(t *testing.T) { + pidFile := installFakeMtg(t) + mgr := &Manager{procs: map[int]*managed{}, swept: true} + if err := mgr.Ensure(mtgInst(1, SecretEntry{Name: "alice", Secret: "ee01"})); err != nil { + t.Fatalf("ensure: %v", err) + } + waitSpawnCount(t, pidFile, 1) + t.Cleanup(mgr.StopAll) + + scrapes := []string{ + `"fronting":{"connections":3,"bytes_in":100,"bytes_out":1000,"rejected":0}`, + `"fronting":{"connections":3,"bytes_in":150,"bytes_out":1600,"rejected":7}`, + `"fronting":{"connections":0,"bytes_in":150,"bytes_out":1600,"rejected":9}`, + } + var scrape atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + body := scrapes[min(int(scrape.Add(1))-1, len(scrapes)-1)] + _, _ = io.WriteString(w, fmt.Sprintf(`{%s,"users":{"alice":{"connections":0,"bytes_in":10,"bytes_out":20}}}`, body)) + })) + defer srv.Close() + mgr.procs[1].apiPort = serverPort(t, srv) + + wants := [][]FrontedTraffic{ + {{Tag: "inbound-1", Up: 100, Down: 1000}}, + {{Tag: "inbound-1", Up: 50, Down: 600}}, + nil, + } + for i, want := range wants { + clients, fronted, _ := mgr.CollectTraffic() + if len(clients) != 0 { + t.Fatalf("scrape %d: fronted bytes must not be attributed to a client: %+v", i+1, clients) + } + if !reflect.DeepEqual(fronted, want) { + t.Fatalf("scrape %d: fronted = %+v, want %+v", i+1, fronted, want) + } + } +} + +func TestCollectTrafficWithoutFrontingCounters(t *testing.T) { + pidFile := installFakeMtg(t) + mgr := &Manager{procs: map[int]*managed{}, swept: true} + if err := mgr.Ensure(mtgInst(1, SecretEntry{Name: "alice", Secret: "ee01"})); err != nil { + t.Fatalf("ensure: %v", err) + } + waitSpawnCount(t, pidFile, 1) + t.Cleanup(mgr.StopAll) + + var scrape atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + n := int64(scrape.Add(1)) + _, _ = io.WriteString(w, fmt.Sprintf(`{"users":{"alice":{"connections":1,"bytes_in":%d,"bytes_out":%d}}}`, 10*n, 20*n)) + })) + defer srv.Close() + mgr.procs[1].apiPort = serverPort(t, srv) + + mgr.CollectTraffic() + clients, fronted, online := mgr.CollectTraffic() + if want := []Traffic{{Tag: "inbound-1", Email: "alice", Up: 10, Down: 20}}; !reflect.DeepEqual(clients, want) { + t.Fatalf("clients = %+v, want %+v", clients, want) + } + if len(fronted) != 0 { + t.Fatalf("an mtg without fronting counters must report no fronted traffic: %+v", fronted) + } + if !reflect.DeepEqual(online, []string{"alice"}) { + t.Fatalf("online = %+v, want [alice]", online) + } +} diff --git a/internal/mtproto/manager_mutation_test.go b/internal/mtproto/manager_mutation_test.go index 914f205dd..d726db800 100644 --- a/internal/mtproto/manager_mutation_test.go +++ b/internal/mtproto/manager_mutation_test.go @@ -41,10 +41,11 @@ func TestScrapeStats(t *testing.T) { })) defer srv.Close() - users, ok := scrapeStats(serverPort(t, srv), "sesame") + stats, ok := scrapeStats(serverPort(t, srv), "sesame") if !ok { t.Fatal("scrapeStats should succeed against a valid /stats endpoint") } + users := stats.Users if len(users) != 2 { t.Fatalf("expected 2 users, got %d: %+v", len(users), users) } diff --git a/internal/mtproto/manager_test.go b/internal/mtproto/manager_test.go index 412975aac..3ce15539b 100644 --- a/internal/mtproto/manager_test.go +++ b/internal/mtproto/manager_test.go @@ -123,13 +123,13 @@ func TestInstanceFromInboundLeavesOutWhatMtgCannotParse(t *testing.T) { } func TestRenderConfig(t *testing.T) { - // A bare instance emits only the required keys, api-bind-to, and the - // [secrets] section, with no optional keys and no [domain-fronting]. + // A bare instance emits only the required keys, api-bind-to, the SNI gate of + // [domain-fronting] and the [secrets] section, with no optional keys. bare := renderConfig(Instance{ Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}}, Listen: "0.0.0.0", Port: 8443, }, 5000, "") - for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]", "[defense.pending-handshakes]", "[secret-ad-tags]", "api-token"} { + for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "host =", "proxy-protocol =", "[stats.prometheus]", "[throttle]", "[defense.pending-handshakes]", "[secret-ad-tags]", "api-token"} { if strings.Contains(bare, unwanted) { t.Fatalf("bare config should not contain %q:\n%s", unwanted, bare) } diff --git a/internal/web/job/mtproto_job.go b/internal/web/job/mtproto_job.go index 21ebfaec4..82a474f07 100644 --- a/internal/web/job/mtproto_job.go +++ b/internal/web/job/mtproto_job.go @@ -41,11 +41,27 @@ func (j *MtprotoJob) Run() { mgr := mtproto.GetManager() mgr.Reconcile(desired) - deltas, onlineEmails := mgr.CollectTraffic() + deltas, fronted, onlineEmails := mgr.CollectTraffic() + traffics, clientTraffics := rollUpMtprotoTraffic(deltas, fronted, routedTags) - // A routed inbound's total is already metered through the Xray bridge by - // xray_traffic_job, so only non-routed inbounds are rolled up here; per-client - // deltas are always kept, since the bridge cannot tell mtproto users apart. + if len(traffics) > 0 || len(clientTraffics) > 0 { + if _, _, err := j.inboundService.AddTraffic(traffics, clientTraffics); err != nil { + logger.Warning("mtproto job: add traffic failed:", err) + } + } + + j.inboundService.RefreshLocalOnlineClients(onlineEmails, activeTags) +} + +// rollUpMtprotoTraffic turns scraped mtg deltas into inbound and client traffic. +// Fronted bytes join every inbound's total: mtg dials the fronting target itself, past Xray. +func rollUpMtprotoTraffic( + deltas []mtproto.Traffic, + fronted []mtproto.FrontedTraffic, + routedTags map[string]bool, +) ([]*xray.Traffic, []*xray.ClientTraffic) { + // xray_traffic_job already meters a routed inbound's client bytes through the bridge; + // per-client deltas are always kept, since the bridge cannot tell mtproto users apart. clientTraffics := make([]*xray.ClientTraffic, 0, len(deltas)) inboundUp := make(map[string]int64) inboundDown := make(map[string]int64) @@ -60,6 +76,10 @@ func (j *MtprotoJob) Run() { inboundDown[d.Tag] += d.Down } } + for _, f := range fronted { + inboundUp[f.Tag] += f.Up + inboundDown[f.Tag] += f.Down + } traffics := make([]*xray.Traffic, 0, len(inboundUp)) for tag, up := range inboundUp { @@ -70,12 +90,5 @@ func (j *MtprotoJob) Run() { Down: inboundDown[tag], }) } - - if len(traffics) > 0 || len(clientTraffics) > 0 { - if _, _, err := j.inboundService.AddTraffic(traffics, clientTraffics); err != nil { - logger.Warning("mtproto job: add traffic failed:", err) - } - } - - j.inboundService.RefreshLocalOnlineClients(onlineEmails, activeTags) + return traffics, clientTraffics } diff --git a/internal/web/job/mtproto_job_test.go b/internal/web/job/mtproto_job_test.go new file mode 100644 index 000000000..f1dc72833 --- /dev/null +++ b/internal/web/job/mtproto_job_test.go @@ -0,0 +1,48 @@ +package job + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/mtproto" +) + +// Fronted bytes leave through mtg's own dialer, never through the Xray bridge, +// so a routed inbound has to count them here or nothing counts them at all. +func TestRollUpMtprotoTraffic(t *testing.T) { + routed := map[string]bool{"routed": true} + clients := []mtproto.Traffic{ + {Tag: "direct", Email: "alice", Up: 1, Down: 2}, + {Tag: "direct", Email: "bob", Up: 10, Down: 20}, + {Tag: "routed", Email: "carol", Up: 100, Down: 200}, + } + fronted := []mtproto.FrontedTraffic{ + {Tag: "direct", Up: 1000, Down: 2000}, + {Tag: "routed", Up: 10000, Down: 20000}, + } + + inbounds, clientTraffics := rollUpMtprotoTraffic(clients, fronted, routed) + + got := map[string][2]int64{} + for _, tr := range inbounds { + if !tr.IsInbound { + t.Fatalf("traffic for %q must be inbound traffic", tr.Tag) + } + got[tr.Tag] = [2]int64{tr.Up, tr.Down} + } + want := map[string][2]int64{ + "direct": {1011, 2022}, + "routed": {10000, 20000}, + } + if len(got) != len(want) || got["direct"] != want["direct"] || got["routed"] != want["routed"] { + t.Fatalf("inbound totals = %v, want %v", got, want) + } + + if len(clientTraffics) != 3 { + t.Fatalf("every client delta must be kept, fronted bytes belong to no client: %+v", clientTraffics) + } + for i, c := range clients { + if ct := clientTraffics[i]; ct.Email != c.Email || ct.Up != c.Up || ct.Down != c.Down { + t.Fatalf("client traffic %d = %+v, want %+v", i, ct, c) + } + } +} From 22fe0c4cd99e0a408506f4656d12d0a153270fc5 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 12:13:19 +0330 Subject: [PATCH 118/130] feat(mtproto): record client IPs and enforce the IP limit for MTProto clients Every client the panel serves has its connected addresses recorded and its IP limit applied, whichever process carries it. MTProto clients are served by mtg, never by Xray, so the core's online list could not see them: their IP log stayed empty and a configured limitIp never fired, although the form offers both for every protocol. mtg-multi 1.17.0 reports users..active_ips in /stats. The manager keeps them from each scrape together with the time an address was first seen connected, so the scan can keep the newest addresses and ban the oldest, and the IP scan merges them the way it already merges kernel-mode AmneziaWG peers. A failed scrape drops the addresses instead of leaving them live, and loopback addresses (a relay in front of mtg) are skipped as the core skips them. Enforcement is the existing fail2ban path. The temporary credential drop is Xray-only, so on Windows, where it is the only mechanism, an MTProto limit is recorded but not enforced. --- internal/mtproto/manager.go | 61 +++++++++++++++- internal/mtproto/manager_client_ips_test.go | 73 +++++++++++++++++++ internal/web/job/check_client_ip_job.go | 51 ++++++++----- .../check_client_ip_job_integration_test.go | 34 +++++++++ 4 files changed, 197 insertions(+), 22 deletions(-) create mode 100644 internal/mtproto/manager_client_ips_test.go diff --git a/internal/mtproto/manager.go b/internal/mtproto/manager.go index b37d3c4ff..e04efd48b 100644 --- a/internal/mtproto/manager.go +++ b/internal/mtproto/manager.go @@ -157,6 +157,8 @@ type managed struct { apiToken string last map[string]clientCounters fronted clientCounters + // ips is replaced whole on every scrape and never edited, so readers may share it. + ips map[string]map[string]int64 } // Manager owns the set of running mtg processes keyed by inbound id. @@ -436,6 +438,7 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { tag string last map[string]clientCounters fronted clientCounters + ips map[string]map[string]int64 } m.mu.Lock() snaps := make([]snap, 0, len(m.procs)) @@ -445,16 +448,23 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { } lastCopy := make(map[string]clientCounters, len(cur.last)) maps.Copy(lastCopy, cur.last) - snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy, fronted: cur.fronted}) + snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy, fronted: cur.fronted, ips: cur.ips}) } m.mu.Unlock() var out []Traffic var fronted []FrontedTraffic var online []string + now := time.Now().Unix() for _, s := range snaps { stats, ok := scrapeStats(s.apiPort, s.apiToken) if !ok { + // Nothing is known about who is connected now: stale addresses must not stay live. + m.mu.Lock() + if cur, ok := m.procs[s.id]; ok { + cur.ips = nil + } + m.mu.Unlock() continue } newLast := make(map[string]clientCounters, len(stats.Users)) @@ -482,12 +492,54 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { if cur, ok := m.procs[s.id]; ok { cur.last = newLast cur.fronted = frontedNow + cur.ips = activeIPsSince(s.ips, stats.Users, now) } m.mu.Unlock() } return out, fronted, online } +// ClientIPs returns the addresses mtg reported connected at the last scrape, +// as email -> address -> Unix time the address was first seen connected. +func (m *Manager) ClientIPs() map[string]map[string]int64 { + m.mu.Lock() + defer m.mu.Unlock() + out := map[string]map[string]int64{} + for _, cur := range m.procs { + for email, ips := range cur.ips { + if _, ok := out[email]; !ok { + out[email] = make(map[string]int64, len(ips)) + } + for ip, since := range ips { + out[email][ip] = max(out[email][ip], since) + } + } + } + return out +} + +// activeIPsSince carries each address's first sighting over from prev while mtg still +// lists it. A loopback address is a relay in front of mtg, not a client, as in the core. +func activeIPsSince(prev map[string]map[string]int64, users map[string]statsUser, now int64) map[string]map[string]int64 { + out := make(map[string]map[string]int64, len(users)) + for email, u := range users { + for _, ip := range u.ActiveIPs { + if addr, err := netip.ParseAddr(ip); err == nil && addr.IsLoopback() { + continue + } + since, known := prev[email][ip] + if !known { + since = now + } + if _, ok := out[email]; !ok { + out[email] = make(map[string]int64, len(u.ActiveIPs)) + } + out[email][ip] = since + } + } + return out +} + func (m *Manager) HasRunning() bool { m.mu.Lock() defer m.mu.Unlock() @@ -658,9 +710,10 @@ func writeConfig(path string, inst Instance, apiPort int, apiToken string) error // the client sent to the proxy (upload) and bytes_out is what the proxy returned // (download). type statsUser struct { - Connections int64 `json:"connections"` - BytesIn int64 `json:"bytes_in"` - BytesOut int64 `json:"bytes_out"` + Connections int64 `json:"connections"` + BytesIn int64 `json:"bytes_in"` + BytesOut int64 `json:"bytes_out"` + ActiveIPs []string `json:"active_ips"` } func (u statsUser) counters() clientCounters { diff --git a/internal/mtproto/manager_client_ips_test.go b/internal/mtproto/manager_client_ips_test.go new file mode 100644 index 000000000..c790f6922 --- /dev/null +++ b/internal/mtproto/manager_client_ips_test.go @@ -0,0 +1,73 @@ +package mtproto + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "testing" + "time" +) + +// The IP limit keeps a client's newest addresses and bans the oldest, so an address +// must keep the time it connected for as long as mtg reports it. +func TestActiveIPsSince(t *testing.T) { + prev := map[string]map[string]int64{ + "alice": {"203.0.113.7": 100, "203.0.113.8": 110}, + } + users := map[string]statsUser{ + "alice": {ActiveIPs: []string{"203.0.113.7", "198.51.100.4", "127.0.0.1", "::1"}}, + "bob": {ActiveIPs: []string{"2001:db8::1"}}, + "carol": {}, + } + + got := activeIPsSince(prev, users, 200) + + want := map[string]map[string]int64{ + "alice": {"203.0.113.7": 100, "198.51.100.4": 200}, + "bob": {"2001:db8::1": 200}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("activeIPsSince = %v, want %v", got, want) + } +} + +// MTProto clients never reach Xray, so its online list cannot see them: without +// mtg's own addresses their IP log stays empty and their IP limit never fires. +func TestClientIPsFollowTheLastScrape(t *testing.T) { + pidFile := installFakeMtg(t) + mgr := &Manager{procs: map[int]*managed{}, swept: true} + if err := mgr.Ensure(mtgInst(1, SecretEntry{Name: "alice", Secret: "ee01"})); err != nil { + t.Fatalf("ensure: %v", err) + } + waitSpawnCount(t, pidFile, 1) + t.Cleanup(mgr.StopAll) + + if got := mgr.ClientIPs(); len(got) != 0 { + t.Fatalf("no address is known before the first scrape, got %v", got) + } + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, `{"users":{"alice":{"connections":2,"bytes_in":1,"bytes_out":2,"active_ips":["203.0.113.7"]}}}`) + })) + mgr.procs[1].apiPort = serverPort(t, srv) + + before := time.Now().Unix() + mgr.CollectTraffic() + after := time.Now().Unix() + + got := mgr.ClientIPs() + seen, ok := got["alice"]["203.0.113.7"] + if len(got) != 1 || len(got["alice"]) != 1 || !ok || seen < before || seen > after { + t.Fatalf("ClientIPs = %v, want alice at 203.0.113.7 seen in [%d, %d]", got, before, after) + } + + // A scrape that fails says nothing about who is connected: the addresses of the + // previous one must not stay "live", or a client that left keeps counting. + srv.Close() + mgr.CollectTraffic() + if got := mgr.ClientIPs(); len(got) != 0 { + t.Fatalf("a failed scrape must drop the known addresses, got %v", fmt.Sprint(got)) + } +} diff --git a/internal/web/job/check_client_ip_job.go b/internal/web/job/check_client_ip_job.go index 9774c63c1..03670186c 100644 --- a/internal/web/job/check_client_ip_job.go +++ b/internal/web/job/check_client_ip_job.go @@ -17,6 +17,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/logger" + "github.com/mhsanaei/3x-ui/v3/internal/mtproto" "github.com/mhsanaei/3x-ui/v3/internal/web/service" "github.com/mhsanaei/3x-ui/v3/internal/xray" @@ -39,6 +40,7 @@ type onlineUsersSource interface { type CheckClientIpJob struct { bannedSeen map[string]int64 onlineUsers onlineUsersSource + mtprotoIPs func() map[string]map[string]int64 allowlist ipLimitAllowlist lastIpPrune int64 } @@ -52,31 +54,26 @@ const ipPruneIntervalSeconds = int64(5 * 60) // NewCheckClientIpJob creates a new client IP monitoring job instance. func NewCheckClientIpJob() *CheckClientIpJob { - return &CheckClientIpJob{onlineUsers: &service.XrayService{}} + return &CheckClientIpJob{ + onlineUsers: &service.XrayService{}, + mtprotoIPs: mtproto.GetManager().ClientIPs, + } } func (j *CheckClientIpJob) Run() { j.pruneStaleIpRows() observed, apiMode := j.collectFromOnlineAPI() - // Kernel-mode AmneziaWG peers never reach Xray, so its online users cannot - // see them; their connect locations come from the kernel interface instead. - kernelIPs := amneziawgkern.GetCollector().ClientIPs() - if len(kernelIPs) > 0 { - if observed == nil { - observed = make(map[string]map[string]int64, len(kernelIPs)) - } - for email, ips := range kernelIPs { - if _, ok := observed[email]; !ok { - observed[email] = make(map[string]int64, len(ips)) - } - for ip, ts := range ips { - if prev, seen := observed[email][ip]; !seen || ts > prev { - observed[email][ip] = ts - } - } + // Kernel-mode AmneziaWG peers and MTProto clients never reach Xray, so its online + // users cannot see them; the kernel interface and the mtg sidecars report their own. + sidecarSeen := false + for _, ips := range []map[string]map[string]int64{amneziawgkern.GetCollector().ClientIPs(), j.mtprotoIPs()} { + if len(ips) == 0 { + continue } + sidecarSeen = true + observed = mergeObservedIPs(observed, ips) } - if !apiMode && len(kernelIPs) == 0 { + if !apiMode && !sidecarSeen { // xray is down or predates the online-stats API. There is no access-log // fallback anymore, so there is nothing to do this run. logger.Debug("[LimitIP] online-stats API unavailable this run; skipping") @@ -101,6 +98,24 @@ func (j *CheckClientIpJob) Run() { j.processObserved(observed, enforce, true) } +// mergeObservedIPs folds src (email -> ip -> last-seen) into dst, newest sighting winning. +func mergeObservedIPs(dst, src map[string]map[string]int64) map[string]map[string]int64 { + if dst == nil { + dst = make(map[string]map[string]int64, len(src)) + } + for email, ips := range src { + if _, ok := dst[email]; !ok { + dst[email] = make(map[string]int64, len(ips)) + } + for ip, ts := range ips { + if prev, seen := dst[email][ip]; !seen || ts > prev { + dst[email][ip] = ts + } + } + } + return dst +} + // resolveEnforce decides whether limits can actually be enforced this run: a // disabled fail2ban gates every platform, a missing binary the ones needing it. func (j *CheckClientIpJob) resolveEnforce(f2bEnabled, hasLimit, f2bInstalled, needsBinary bool) bool { diff --git a/internal/web/job/check_client_ip_job_integration_test.go b/internal/web/job/check_client_ip_job_integration_test.go index 68171c2d9..28a2b2ade 100644 --- a/internal/web/job/check_client_ip_job_integration_test.go +++ b/internal/web/job/check_client_ip_job_integration_test.go @@ -5,6 +5,7 @@ import ( "log" "os" "path/filepath" + "strings" "sync" "testing" "time" @@ -555,3 +556,36 @@ func TestUpdateInboundClientIps_AllowlistedIpIsNeitherCountedNorBanned(t *testin } } } + +// An MTProto client is served by mtg, not Xray: its addresses come from the sidecar +// and must be recorded and limited even while the online-stats API has nothing. +func TestRun_EnforcesIpLimitOnMtprotoClients(t *testing.T) { + setupIntegrationDB(t) + t.Setenv("XUI_ENABLE_FAIL2BAN", "true") + fakeFail2BanClient(t) + + const email = "mtproto-user" + seedLinkedInboundWithClient(t, "inbound-mtproto", email, 1) + + now := time.Now().Unix() + j := NewCheckClientIpJob() + j.mtprotoIPs = func() map[string]map[string]int64 { + return map[string]map[string]int64{email: {"203.0.113.30": now - 600, "203.0.113.31": now - 5}} + } + // The first scan only records; enforcement needs the stored row. + j.Run() + j.Run() + + got := ipSet(readClientIps(t, email)) + if _, kept := got["203.0.113.31"]; !kept || len(got) != 1 { + t.Fatalf("only the newest address stays recorded as live, got %v", got) + } + body, err := os.ReadFile(readIpLimitLogPath()) + if err != nil { + t.Fatalf("read 3xipl.log: %v", err) + } + want := "[LIMIT_IP] Email = " + email + " || Disconnecting OLD IP = 203.0.113.30 || Timestamp = " + if !strings.Contains(string(body), want) || strings.Contains(string(body), "203.0.113.31") { + t.Fatalf("the oldest address alone must be queued for a ban, 3xipl.log:\n%s", body) + } +} From 32615e1d7643d7a5b3981354dcd2ad96bedf69f5 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 13:21:29 +0330 Subject: [PATCH 119/130] fix(mtproto): stop claiming mtg auto-detects the public IP for ad-tags The Public IPv4/IPv6 hint told operators to leave the field blank so mtg would detect the address itself. mtg-multi has no such detection for the middle proxy: with the field empty it feeds its socket's local address into the middle-proxy key schedule, which only matches what Telegram sees when the public IP sits on the server's own interface. Behind NAT or a Docker bridge the handshake is refused, so every connection of an ad-tagged client spends 5-7 seconds on the middle proxy before falling back to a direct connection, and the sponsored channel never appears. Measured against real Telegram with a tagged and three untagged clients; the untagged ones were unaffected. The hint in all 14 locales now says when blank is correct and when the address must be entered. The two code comments repeating the claim are corrected with it. --- frontend/src/schemas/protocols/inbound/mtproto.ts | 4 ++-- internal/mtproto/manager.go | 5 ++--- internal/web/translation/ar-EG.json | 2 +- internal/web/translation/en-US.json | 2 +- internal/web/translation/es-ES.json | 2 +- internal/web/translation/fa-IR.json | 2 +- internal/web/translation/id-ID.json | 2 +- internal/web/translation/ja-JP.json | 2 +- internal/web/translation/pt-BR.json | 2 +- internal/web/translation/ru-RU.json | 2 +- internal/web/translation/sk-SK.json | 2 +- internal/web/translation/tr-TR.json | 2 +- internal/web/translation/uk-UA.json | 2 +- internal/web/translation/vi-VN.json | 2 +- internal/web/translation/zh-CN.json | 2 +- internal/web/translation/zh-TW.json | 2 +- 16 files changed, 18 insertions(+), 19 deletions(-) diff --git a/frontend/src/schemas/protocols/inbound/mtproto.ts b/frontend/src/schemas/protocols/inbound/mtproto.ts index dd4d8182e..02e7eac1e 100644 --- a/frontend/src/schemas/protocols/inbound/mtproto.ts +++ b/frontend/src/schemas/protocols/inbound/mtproto.ts @@ -62,8 +62,8 @@ export const MtprotoInboundSettingsSchema = z.object({ routeThroughXray: z.boolean().optional(), outboundTag: z.string().optional(), routeXrayPort: z.number().int().min(0).max(65535).optional(), - // publicIpv4/publicIpv6 pin this server's reachable address the Telegram - // middle proxy needs when clients carry ad-tags; blank = mtg auto-detects. + // publicIpv4/publicIpv6: the address Telegram's middle proxy sees for ad-tagged + // clients; blank = mtg uses its socket's local address, wrong behind NAT. publicIpv4: z.string().optional(), publicIpv6: z.string().optional(), }); diff --git a/internal/mtproto/manager.go b/internal/mtproto/manager.go index e04efd48b..79005991e 100644 --- a/internal/mtproto/manager.go +++ b/internal/mtproto/manager.go @@ -63,9 +63,8 @@ type Instance struct { // client IP (mtg-multi >= 1.16.0); zero leaves the limit off. PendingHandshakesMaxPerIP int - // PublicIPv4/PublicIPv6 pin the proxy's reachable address the Telegram - // middle proxy needs when clients carry advertising tags; they are omitted - // when empty so mtg auto-detects, and a change forces a restart. + // PublicIPv4/PublicIPv6 are the address Telegram's middle proxy sees for ad-tagged clients. + // Empty leaves mtg on its socket's local address, wrong behind NAT; a change forces a restart. PublicIPv4 string PublicIPv6 string diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 281f1232c..8793eaa33 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -533,7 +533,7 @@ "mtgAdTagInvalid": "يجب أن تتكوّن العلامة الإعلانية من 32 حرفًا ست عشريًا بالضبط.", "mtgPublicIpv4": "عنوان IPv4 العام", "mtgPublicIpv6": "عنوان IPv6 العام", - "mtgPublicIpHint": "العنوان العام لهذا الخادم الذي يمكن الوصول إليه، ويُستخدم بواسطة البروكسي الوسيط للعلامة الإعلانية. اتركه فارغًا ليكتشفه mtg تلقائيًا.", + "mtgPublicIpHint": "العنوان العام لهذا الخادم، ويُستخدم بواسطة البروكسي الوسيط للعلامة الإعلانية. إذا تُرك فارغًا، يستخدم mtg عنوان واجهة الشبكة في الخادم، وهذا صحيح فقط إذا كان عنوان IP العام معيّنًا عليها. خلف NAT أو Docker أدخله هنا؛ وإلا سيتصل العملاء أصحاب العلامة الإعلانية ببطء ولن تظهر القناة المموّلة.", "visionTestseed": "Vision testseed", "version": "الإصدار", "udpIdleTimeout": "UDP idle timeout (ثانية)", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 2d7a17e7f..49ab6c892 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -535,7 +535,7 @@ "mtgAdTagInvalid": "Ad-tag must be exactly 32 hexadecimal characters.", "mtgPublicIpv4": "Public IPv4", "mtgPublicIpv6": "Public IPv6", - "mtgPublicIpHint": "This server's reachable public address, used by the ad-tag middle proxy. Leave blank to let mtg auto-detect it.", + "mtgPublicIpHint": "This server's public address, used by the ad-tag middle proxy. When left blank, mtg uses the address on the server's network interface, which is only correct if the public IP is assigned to it. Behind NAT or Docker, enter it here; otherwise ad-tagged clients connect slowly and the sponsored channel is not shown.", "visionTestseed": "Vision testseed", "version": "Version", "udpIdleTimeout": "UDP idle timeout (s)", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 1acfab2f4..aeb4bc385 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -533,7 +533,7 @@ "mtgAdTagInvalid": "El ad-tag debe tener exactamente 32 caracteres hexadecimales.", "mtgPublicIpv4": "IPv4 pública", "mtgPublicIpv6": "IPv6 pública", - "mtgPublicIpHint": "La dirección pública accesible de este servidor, usada por el proxy intermedio del ad-tag. Déjalo en blanco para que mtg la detecte automáticamente.", + "mtgPublicIpHint": "La dirección pública de este servidor, usada por el proxy intermedio del ad-tag. Si se deja en blanco, mtg usa la dirección de la interfaz de red del servidor, lo cual solo es correcto si la IP pública está asignada a ella. Detrás de NAT o Docker, indícala aquí; de lo contrario, los clientes con ad-tag se conectan lentamente y el canal patrocinado no se muestra.", "visionTestseed": "Vision testseed", "version": "Versión", "udpIdleTimeout": "UDP idle timeout (s)", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index d5d7a05b6..51d3effe5 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -533,7 +533,7 @@ "mtgAdTagInvalid": "برچسب تبلیغاتی باید دقیقاً ۳۲ کاراکتر هگزادسیمال باشد.", "mtgPublicIpv4": "IPv4 عمومی", "mtgPublicIpv6": "IPv6 عمومی", - "mtgPublicIpHint": "نشانی عمومی و در‌دسترس این سرور که پروکسی میانی برچسب تبلیغاتی از آن استفاده می‌کند. برای تشخیص خودکار توسط mtg، خالی بگذارید.", + "mtgPublicIpHint": "نشانی عمومی این سرور که پروکسی میانی برچسب تبلیغاتی از آن استفاده می‌کند. اگر خالی بماند، mtg نشانی کارت شبکهٔ سرور را به کار می‌برد که فقط وقتی درست است که IP عمومی روی همان کارت شبکه تنظیم شده باشد. پشت NAT یا Docker آن را اینجا وارد کنید؛ وگرنه کلاینت‌های دارای برچسب تبلیغاتی کند وصل می‌شوند و کانال حامی نمایش داده نمی‌شود.", "visionTestseed": "Vision testseed", "version": "نسخه", "udpIdleTimeout": "UDP idle timeout (s)", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 8334f2339..479bce2dc 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -533,7 +533,7 @@ "mtgAdTagInvalid": "Ad-tag harus tepat 32 karakter heksadesimal.", "mtgPublicIpv4": "IPv4 Publik", "mtgPublicIpv6": "IPv6 Publik", - "mtgPublicIpHint": "Alamat publik server ini yang dapat dijangkau, digunakan oleh proxy perantara ad-tag. Biarkan kosong agar mtg mendeteksinya secara otomatis.", + "mtgPublicIpHint": "Alamat publik server ini, digunakan oleh proxy perantara ad-tag. Jika dibiarkan kosong, mtg memakai alamat pada antarmuka jaringan server, yang hanya benar jika IP publik terpasang di antarmuka tersebut. Di belakang NAT atau Docker, isi di sini; jika tidak, klien dengan ad-tag terhubung lambat dan kanal bersponsor tidak ditampilkan.", "visionTestseed": "Vision testseed", "version": "Versi", "udpIdleTimeout": "UDP idle timeout (d)", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index fec842129..26a98d514 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -584,7 +584,7 @@ "mtgAdTagInvalid": "広告タグは正確に 32 文字の 16 進数である必要があります。", "mtgPublicIpv4": "パブリック IPv4", "mtgPublicIpv6": "パブリック IPv6", - "mtgPublicIpHint": "広告タグの中間プロキシが使用する、このサーバーの到達可能なパブリックアドレス。空欄にすると mtg が自動検出します。", + "mtgPublicIpHint": "広告タグの中間プロキシが使用する、このサーバーのパブリックアドレス。空欄の場合、mtg はサーバーのネットワークインターフェースのアドレスを使用しますが、これが正しいのはパブリック IP がそのインターフェースに割り当てられている場合のみです。NAT や Docker の背後ではここに入力してください。入力しないと、広告タグ付きクライアントの接続が遅くなり、スポンサーチャンネルは表示されません。", "visionTestseed": "Vision testseed", "version": "バージョン", "udpIdleTimeout": "UDP idle timeout (秒)", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 15a75e592..b9eeed22b 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -584,7 +584,7 @@ "mtgAdTagInvalid": "A ad-tag deve ter exatamente 32 caracteres hexadecimais.", "mtgPublicIpv4": "IPv4 público", "mtgPublicIpv6": "IPv6 público", - "mtgPublicIpHint": "O endereço público acessível deste servidor, usado pelo proxy intermediário da ad-tag. Deixe em branco para o mtg detectá-lo automaticamente.", + "mtgPublicIpHint": "O endereço público deste servidor, usado pelo proxy intermediário da ad-tag. Se ficar em branco, o mtg usa o endereço da interface de rede do servidor, o que só está correto se o IP público estiver atribuído a ela. Atrás de NAT ou Docker, informe-o aqui; caso contrário, os clientes com ad-tag conectam lentamente e o canal patrocinado não é exibido.", "visionTestseed": "Vision testseed", "version": "Versão", "udpIdleTimeout": "UDP idle timeout (s)", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index e5d3845e1..59b97274c 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -586,7 +586,7 @@ "mtgAdTagInvalid": "Рекламный тег должен содержать ровно 32 шестнадцатеричных символа.", "mtgPublicIpv4": "Публичный IPv4", "mtgPublicIpv6": "Публичный IPv6", - "mtgPublicIpHint": "Доступный публичный адрес этого сервера, используемый промежуточным прокси рекламного тега. Оставьте пустым, чтобы mtg определил его автоматически.", + "mtgPublicIpHint": "Публичный адрес этого сервера, используемый промежуточным прокси рекламного тега. Если оставить пустым, mtg использует адрес сетевого интерфейса сервера, что верно, только когда публичный IP назначен на этот интерфейс. За NAT или в Docker укажите его здесь, иначе клиенты с рекламным тегом подключаются медленно, а спонсорский канал не показывается.", "visionTestseed": "Vision testseed", "version": "Версия", "udpIdleTimeout": "UDP idle timeout (с)", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index f6112e144..a400e4e45 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -535,7 +535,7 @@ "mtgAdTagInvalid": "Reklamná značka musí mať presne 32 hexadecimálnych znakov.", "mtgPublicIpv4": "Verejná IPv4", "mtgPublicIpv6": "Verejná IPv6", - "mtgPublicIpHint": "Dostupná verejná adresa tohto servera pre sprostredkujúci reklamný proxy. Prázdne pole umožní mtg zistiť adresu automaticky.", + "mtgPublicIpHint": "Verejná adresa tohto servera pre sprostredkujúci reklamný proxy. Ak pole zostane prázdne, mtg použije adresu sieťového rozhrania servera, čo je správne iba vtedy, keď je verejná IP priradená priamo k nemu. Za NAT alebo v Dockeri ju zadajte sem, inak sa klienti s reklamnou značkou pripájajú pomaly a sponzorovaný kanál sa nezobrazí.", "visionTestseed": "Testovacia hodnota Vision (testseed)", "version": "Verzia", "udpIdleTimeout": "Časový limit nečinnosti UDP (s)", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index cb7d5dbf3..147d35004 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -533,7 +533,7 @@ "mtgAdTagInvalid": "Reklam etiketi tam olarak 32 onaltılık karakter olmalıdır.", "mtgPublicIpv4": "Genel IPv4", "mtgPublicIpv6": "Genel IPv6", - "mtgPublicIpHint": "Bu sunucunun erişilebilir genel adresi; reklam etiketi ara proxy'si tarafından kullanılır. mtg'nin otomatik algılaması için boş bırakın.", + "mtgPublicIpHint": "Bu sunucunun genel adresi; reklam etiketi ara proxy'si tarafından kullanılır. Boş bırakılırsa mtg, sunucunun ağ arayüzündeki adresi kullanır; bu yalnızca genel IP o arayüze atanmışsa doğrudur. NAT veya Docker arkasında adresi buraya girin; aksi halde reklam etiketli istemciler yavaş bağlanır ve sponsorlu kanal gösterilmez.", "visionTestseed": "Vision Testseed", "version": "Sürüm", "udpIdleTimeout": "UDP Idle Timeout (s)", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 2481590c0..4af33898f 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -533,7 +533,7 @@ "mtgAdTagInvalid": "Рекламний тег має містити рівно 32 шістнадцяткові символи.", "mtgPublicIpv4": "Публічний IPv4", "mtgPublicIpv6": "Публічний IPv6", - "mtgPublicIpHint": "Доступна публічна адреса цього сервера, яку використовує проміжний проксі рекламного тега. Залиште порожнім, щоб mtg визначив її автоматично.", + "mtgPublicIpHint": "Публічна адреса цього сервера, яку використовує проміжний проксі рекламного тега. Якщо залишити порожнім, mtg використовує адресу мережевого інтерфейсу сервера, що правильно лише тоді, коли публічну IP призначено на цей інтерфейс. За NAT або в Docker вкажіть її тут, інакше клієнти з рекламним тегом підключаються повільно, а спонсорський канал не показується.", "visionTestseed": "Vision testseed", "version": "Версія", "udpIdleTimeout": "UDP idle timeout (с)", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index f61ab407a..2790b96eb 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -584,7 +584,7 @@ "mtgAdTagInvalid": "Ad-tag phải có đúng 32 ký tự thập lục phân.", "mtgPublicIpv4": "IPv4 công khai", "mtgPublicIpv6": "IPv6 công khai", - "mtgPublicIpHint": "Địa chỉ công khai có thể truy cập của máy chủ này, được proxy trung gian ad-tag sử dụng. Để trống để mtg tự phát hiện.", + "mtgPublicIpHint": "Địa chỉ công khai của máy chủ này, được proxy trung gian ad-tag sử dụng. Nếu để trống, mtg dùng địa chỉ trên giao diện mạng của máy chủ, điều này chỉ đúng khi IP công khai được gán trực tiếp cho giao diện đó. Khi nằm sau NAT hoặc Docker, hãy nhập địa chỉ tại đây; nếu không, các client có ad-tag sẽ kết nối chậm và kênh tài trợ không hiển thị.", "visionTestseed": "Vision testseed", "version": "Phiên bản", "udpIdleTimeout": "UDP idle timeout (s)", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index b48352f0e..1d1720dec 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -583,7 +583,7 @@ "mtgAdTagInvalid": "广告标签必须为 32 位十六进制字符。", "mtgPublicIpv4": "公网 IPv4", "mtgPublicIpv6": "公网 IPv6", - "mtgPublicIpHint": "本服务器可访问的公网地址,供广告标签的中间代理使用。留空则由 mtg 自动检测。", + "mtgPublicIpHint": "本服务器的公网地址,供广告标签的中间代理使用。留空时 mtg 使用服务器网卡上的地址,只有公网 IP 直接配置在网卡上时才正确。位于 NAT 或 Docker 之后时请在此填写,否则带广告标签的客户端连接缓慢,且不会显示赞助频道。", "visionTestseed": "Vision testseed", "version": "版本", "udpIdleTimeout": "UDP 空闲超时 (s)", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 1e51565dd..3ff06dfc3 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -533,7 +533,7 @@ "mtgAdTagInvalid": "廣告標籤必須為 32 位十六進位字元。", "mtgPublicIpv4": "公網 IPv4", "mtgPublicIpv6": "公網 IPv6", - "mtgPublicIpHint": "本伺服器可存取的公網位址,供廣告標籤的中間代理使用。留空則由 mtg 自動偵測。", + "mtgPublicIpHint": "本伺服器的公網位址,供廣告標籤的中間代理使用。留空時 mtg 會使用伺服器網路介面上的位址,只有公網 IP 直接設定在該介面上時才正確。位於 NAT 或 Docker 之後時請在此填寫,否則帶有廣告標籤的用戶端連線緩慢,且不會顯示贊助頻道。", "visionTestseed": "Vision testseed", "version": "版本", "udpIdleTimeout": "UDP 閒置逾時 (s)", From c23e1cb23152db34e4596e5ac16e96614221dea5 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 13:47:59 +0330 Subject: [PATCH 120/130] feat(nodes): show how many clients are online on the node itself Since a69f2dee a node's online report is cut to the clients linked to its inbounds on this panel, so a node that also serves inbounds the panel does not import (inboundSyncMode=selected, or inbounds created on the node) shows only part of its load, and an operator cannot tell a busy node from an idle one. The panel now counts the distinct clients in the node's own entry of that report before the cut and keeps the number only: the emails of clients it does not manage are still dropped, so they cannot mark another client online or reach the IP limit. The count needs no new node endpoint, so nodes on older builds report it too, and it is dropped together with the node's online clients when the node is no longer synced. The Nodes page shows it as "synced / total" in the online tag when the node reports more than the synced count. Transitive sub-nodes carry no total: the panel takes no counts from an intermediate node. --- docs/public/openapi.json | 15 ++ frontend/public/openapi.json | 15 ++ frontend/src/generated/examples.ts | 2 + frontend/src/generated/schemas.ts | 11 ++ frontend/src/generated/types.ts | 2 + frontend/src/generated/zod.ts | 2 + frontend/src/pages/nodes/NodeList.tsx | 48 ++++-- frontend/src/schemas/node.ts | 2 + .../src/test/node-list-online-total.test.tsx | 80 ++++++++++ internal/database/model/model.go | 14 +- internal/web/service/inbound_node.go | 27 ++++ internal/web/service/node.go | 5 + internal/web/service/node_contract.go | 2 + .../web/service/node_online_total_test.go | 139 ++++++++++++++++++ internal/web/service/node_tree.go | 3 + internal/web/translation/ar-EG.json | 1 + internal/web/translation/en-US.json | 1 + internal/web/translation/es-ES.json | 1 + internal/web/translation/fa-IR.json | 1 + internal/web/translation/id-ID.json | 1 + internal/web/translation/ja-JP.json | 1 + internal/web/translation/pt-BR.json | 1 + internal/web/translation/ru-RU.json | 1 + internal/web/translation/sk-SK.json | 1 + internal/web/translation/tr-TR.json | 1 + internal/web/translation/uk-UA.json | 1 + internal/web/translation/vi-VN.json | 1 + internal/web/translation/zh-CN.json | 1 + internal/web/translation/zh-TW.json | 1 + internal/xray/process.go | 37 ++++- 30 files changed, 395 insertions(+), 23 deletions(-) create mode 100644 frontend/src/test/node-list-online-total.test.tsx create mode 100644 internal/web/service/node_online_total_test.go diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 483eae866..8ee92524e 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -4434,6 +4434,11 @@ "example": 3, "type": "integer" }, + "onlineTotalCount": { + "description": "OnlineTotalCount also counts clients on inbounds this panel does not sync.", + "example": 7, + "type": "integer" + }, "outboundTag": { "type": "string" }, @@ -4537,6 +4542,7 @@ "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -4759,6 +4765,10 @@ "example": 5, "type": "integer" }, + "onlineTotalCount": { + "example": 9, + "type": "integer" + }, "outboundTag": { "example": "direct", "type": "string" @@ -4852,6 +4862,7 @@ "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -13563,6 +13574,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -13767,6 +13779,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -13920,6 +13933,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -19719,6 +19733,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 483eae866..8ee92524e 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -4434,6 +4434,11 @@ "example": 3, "type": "integer" }, + "onlineTotalCount": { + "description": "OnlineTotalCount also counts clients on inbounds this panel does not sync.", + "example": 7, + "type": "integer" + }, "outboundTag": { "type": "string" }, @@ -4537,6 +4542,7 @@ "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -4759,6 +4765,10 @@ "example": 5, "type": "integer" }, + "onlineTotalCount": { + "example": 9, + "type": "integer" + }, "outboundTag": { "example": "direct", "type": "string" @@ -4852,6 +4862,7 @@ "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -13563,6 +13574,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -13767,6 +13779,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -13920,6 +13933,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -19719,6 +19733,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index ce21c190d..1c7b6c620 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1158,6 +1158,7 @@ export const EXAMPLES: Record = { "netDown": 2097152, "netUp": 1048576, "onlineCount": 3, + "onlineTotalCount": 7, "outboundTag": "", "panelVersion": "v3.x.x", "parentGuid": "", @@ -1226,6 +1227,7 @@ export const EXAMPLES: Record = { "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 19fb6bf0b..bd97abbdc 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -4408,6 +4408,11 @@ export const SCHEMAS: Record = { "example": 3, "type": "integer" }, + "onlineTotalCount": { + "description": "OnlineTotalCount also counts clients on inbounds this panel does not sync.", + "example": 7, + "type": "integer" + }, "outboundTag": { "type": "string" }, @@ -4511,6 +4516,7 @@ export const SCHEMAS: Record = { "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -4733,6 +4739,10 @@ export const SCHEMAS: Record = { "example": 5, "type": "integer" }, + "onlineTotalCount": { + "example": 9, + "type": "integer" + }, "outboundTag": { "example": "direct", "type": "string" @@ -4826,6 +4836,7 @@ export const SCHEMAS: Record = { "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index e49e8ae56..5b406d8d8 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1011,6 +1011,7 @@ export interface Node { netDown: number; netUp: number; onlineCount: number; + onlineTotalCount: number; outboundTag: string; panelVersion: string; parentGuid?: string; @@ -1075,6 +1076,7 @@ export interface NodeView { netDown: number; netUp: number; onlineCount: number; + onlineTotalCount: number; outboundTag: string; panelVersion: string; parentGuid?: string; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 38c619155..3611c3061 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1074,6 +1074,7 @@ export const NodeSchema = z.object({ netDown: z.number().int(), netUp: z.number().int(), onlineCount: z.number().int(), + onlineTotalCount: z.number().int(), outboundTag: z.string(), panelVersion: z.string(), parentGuid: z.string().optional(), @@ -1140,6 +1141,7 @@ export const NodeViewSchema = z.object({ netDown: z.number().int(), netUp: z.number().int(), onlineCount: z.number().int(), + onlineTotalCount: z.number().int(), outboundTag: z.string(), panelVersion: z.string(), parentGuid: z.string().optional(), diff --git a/frontend/src/pages/nodes/NodeList.tsx b/frontend/src/pages/nodes/NodeList.tsx index 17185f869..b85606bec 100644 --- a/frontend/src/pages/nodes/NodeList.tsx +++ b/frontend/src/pages/nodes/NodeList.tsx @@ -53,6 +53,15 @@ function isUpdateEligible(n: NodeRecord): boolean { return !!n.enable && n.status === 'online'; } +// A node also serves clients on inbounds this panel does not sync; when it reports +// more online than the synced count, both show as "synced / total". +function onlineCounts(n: NodeRecord): { label: string; synced: number; total: number } | null { + const synced = n.onlineCount || 0; + const total = Math.max(n.onlineTotalCount || 0, synced); + if (!total) return null; + return { label: total > synced ? `${synced} / ${total}` : String(synced), synced, total }; +} + interface NodeRow extends NodeRecord { url: string; key: string | number; @@ -177,6 +186,27 @@ function useRelativeTime() { ); } +function OnlineTag({ node, compact }: { node: NodeRecord; compact?: boolean }) { + const { t } = useTranslation(); + const counts = onlineCounts(node); + if (!counts) return null; + const tag = compact ? ( + + {counts.label} + + ) : ( + + {counts.label} {t('online')} + + ); + if (counts.total > counts.synced) { + const title = t('pages.nodes.onlineOnNode', { synced: counts.synced, total: counts.total }); + return {tag}; + } + // The compact tag is a bare number, so it still needs to say what it counts. + return compact ? {tag} : tag; +} + export default function NodeList({ nodes, loading = false, @@ -530,17 +560,7 @@ export default function NodeList({ ) : null} - {record.onlineCount ? ( - - - {record.onlineCount} - - - ) : null} + ), }, @@ -887,11 +907,7 @@ export default function NodeList({ {statsNode.depletedCount} {t('depleted')} ) : null} - {statsNode.onlineCount ? ( - - {statsNode.onlineCount} {t('online')} - - ) : null} +
{t('pages.nodes.lastHeartbeat')} diff --git a/frontend/src/schemas/node.ts b/frontend/src/schemas/node.ts index 10efb8242..dc64dd00f 100644 --- a/frontend/src/schemas/node.ts +++ b/frontend/src/schemas/node.ts @@ -23,6 +23,8 @@ export const NodeRecordSchema = z inboundCount: z.number().optional(), clientCount: z.number().optional(), onlineCount: z.number().optional(), + // Clients online on the node itself, including inbounds this panel does not sync. + onlineTotalCount: z.number().optional(), activeCount: z.number().optional(), disabledCount: z.number().optional(), depletedCount: z.number().optional(), diff --git a/frontend/src/test/node-list-online-total.test.tsx b/frontend/src/test/node-list-online-total.test.tsx new file mode 100644 index 000000000..d6bbc9eea --- /dev/null +++ b/frontend/src/test/node-list-online-total.test.tsx @@ -0,0 +1,80 @@ +import { screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it } from 'vitest'; + +import NodeList from '@/pages/nodes/NodeList'; +import type { NodeRecord } from '@/schemas/node'; + +import { renderWithProviders } from './test-utils'; + +const noop = () => {}; + +function renderNode( + counts: Pick, + isMobile = false, +) { + const node: NodeRecord = { + id: 1, + name: 'edge', + guid: 'e1', + enable: true, + status: 'online', + clientCount: 40, + ...counts, + }; + renderWithProviders( + , + ); +} + +// The online badge counts only clients of inbounds imported into this panel, so a node busy on +// its other inbounds looked idle; the node's own total must show beside that count. +describe('NodeList online total', () => { + it('shows synced / total and explains both numbers on hover', async () => { + renderNode({ onlineCount: 3, onlineTotalCount: 12 }); + + await userEvent.hover(screen.getByText('3 / 12')); + + expect((await screen.findByRole('tooltip')).textContent).toBe( + '3 online on inbounds imported into this panel, 12 online on the node in total', + ); + }); + + it('shows the total when no synced client is online', () => { + renderNode({ onlineCount: 0, onlineTotalCount: 5 }); + + expect(screen.getByText('0 / 5')).toBeTruthy(); + }); + + it.each<[string, Pick]>([ + ['the total equals the synced count', { onlineCount: 7, onlineTotalCount: 7 }], + ['the panel reports no total', { onlineCount: 7 }], + ])('keeps the single number when %s', (_name, counts) => { + renderNode(counts); + + expect(screen.getByText('7')).toBeTruthy(); + expect(screen.queryByText(/\d \/ \d/)).toBeNull(); + }); + + it('shows synced / total in the mobile stats dialog', async () => { + renderNode({ onlineCount: 3, onlineTotalCount: 12 }, true); + + await userEvent.click(screen.getByRole('button', { name: 'More Information' })); + + expect(within(await screen.findByRole('dialog')).getByText('3 / 12 Online')).toBeTruthy(); + }); +}); diff --git a/internal/database/model/model.go b/internal/database/model/model.go index ebc39449b..9e733e5e0 100644 --- a/internal/database/model/model.go +++ b/internal/database/model/model.go @@ -941,12 +941,14 @@ type Node struct { DownNotified bool `json:"-" gorm:"column:down_notified;default:false"` - InboundCount int `json:"inboundCount" gorm:"-" example:"5"` - ClientCount int `json:"clientCount" gorm:"-" example:"27"` - OnlineCount int `json:"onlineCount" gorm:"-" example:"3"` - ActiveCount int `json:"activeCount" gorm:"-" example:"23"` - DisabledCount int `json:"disabledCount" gorm:"-" example:"3"` - DepletedCount int `json:"depletedCount" gorm:"-" example:"1"` + InboundCount int `json:"inboundCount" gorm:"-" example:"5"` + ClientCount int `json:"clientCount" gorm:"-" example:"27"` + OnlineCount int `json:"onlineCount" gorm:"-" example:"3"` + // OnlineTotalCount also counts clients on inbounds this panel does not sync. + OnlineTotalCount int `json:"onlineTotalCount" gorm:"-" example:"7"` + ActiveCount int `json:"activeCount" gorm:"-" example:"23"` + DisabledCount int `json:"disabledCount" gorm:"-" example:"3"` + DepletedCount int `json:"depletedCount" gorm:"-" example:"1"` // ParentGuid + Transitive are set only when a node is surfaced as part of a // node tree (#4983): direct nodes carry the master panel's own GUID, a diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 6630462cb..16757f266 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -1558,6 +1558,8 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + ownOnlineTotal := reportedOwnOnlineTotal(snap, nodeRow.Guid) + // The online report outlives this merge, so it is cut first to the node's own clients. if len(snap.OnlineTree) > 0 || len(snap.OnlineEmails) > 0 { attached, err := nodeAttachedEmails(db, nodeID) @@ -1584,6 +1586,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } process.SetNodeOnlineTree(nodeID, filterGuidTreeKeys(tree, hostedGuids)) + process.SetNodeOnlineTotal(nodeID, ownOnlineTotal) activeTree := normalizeActiveInboundTreeTags(snap.ActiveInboundTree, tagToCentral) if guidShared && len(activeTree) > 0 { @@ -1698,6 +1701,16 @@ func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) } } +// GetNodeOnlineTotals returns, per direct node id, how many clients that node reported +// online on its own core, including those on inbounds this panel does not sync. +func (s *InboundService) GetNodeOnlineTotals() map[int]int { + process := currentXrayProcess() + if process == nil { + return map[int]int{} + } + return process.GetNodeOnlineTotals() +} + func (s *InboundService) ClearNodeOnlineClients(nodeID int) { if process := currentXrayProcess(); process != nil { process.ClearNodeOnlineClients(nodeID) @@ -1769,6 +1782,20 @@ func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]st return remapped } +// reportedOwnOnlineTotal counts the clients a node reports online on its own core, synced +// here or not. An old build's flat list is all it sends, so its sub-nodes' clients count too. +func reportedOwnOnlineTotal(snap *runtime.TrafficSnapshot, nodeGuid string) int { + emails := snap.OnlineEmails + if len(snap.OnlineTree) > 0 { + emails = snap.OnlineTree[nodeGuid] + } + distinct := make(map[string]struct{}, len(emails)) + for _, email := range emails { + distinct[email] = struct{}{} + } + return len(distinct) +} + // keepAttachedOnlineEmails cuts a node's online report to the clients linked to its inbounds, // once each per GUID, into fresh slices so the reported ones are not pinned. func keepAttachedOnlineEmails(snap *runtime.TrafficSnapshot, attached map[string]struct{}) { diff --git a/internal/web/service/node.go b/internal/web/service/node.go index d9f1a9845..3365f62e1 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -163,6 +163,11 @@ func (s *NodeService) populateClientCounts(db *gorm.DB, nodes []*model.Node) { } func (s *NodeService) enrichDashboardStats(db *gorm.DB, nodes []*model.Node) { + // Set before the early returns: a node with nothing synced still has clients online. + onlineTotals := (&InboundService{}).GetNodeOnlineTotals() + for _, n := range nodes { + n.OnlineTotalCount = onlineTotals[n.Id] + } type inboundRow struct { Id int NodeID int `gorm:"column:node_id"` diff --git a/internal/web/service/node_contract.go b/internal/web/service/node_contract.go index 782808c9b..d1e136189 100644 --- a/internal/web/service/node_contract.go +++ b/internal/web/service/node_contract.go @@ -45,6 +45,7 @@ type NodeView struct { InboundCount int `json:"inboundCount" example:"3"` ClientCount int `json:"clientCount" example:"25"` OnlineCount int `json:"onlineCount" example:"5"` + OnlineTotalCount int `json:"onlineTotalCount" example:"9"` ActiveCount int `json:"activeCount" example:"20"` DisabledCount int `json:"disabledCount" example:"2"` DepletedCount int `json:"depletedCount" example:"1"` @@ -94,6 +95,7 @@ func toNodeView(n *model.Node) *NodeView { InboundCount: n.InboundCount, ClientCount: n.ClientCount, OnlineCount: n.OnlineCount, + OnlineTotalCount: n.OnlineTotalCount, ActiveCount: n.ActiveCount, DisabledCount: n.DisabledCount, DepletedCount: n.DepletedCount, diff --git a/internal/web/service/node_online_total_test.go b/internal/web/service/node_online_total_test.go new file mode 100644 index 000000000..fbbdcec4a --- /dev/null +++ b/internal/web/service/node_online_total_test.go @@ -0,0 +1,139 @@ +package service + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +// The node list counts only the clients this panel syncs as online; clients on the +// node's unsynced inbounds must still reach it as a number, never as emails. +func TestNodeTreeCountsEveryClientOnlineOnTheNode(t *testing.T) { + db := initTrafficTestDB(t) + useOnlineTestProcess(t) + svc := &InboundService{} + seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true, Guid: "node-guid"}) + createNodeInboundWithClient(t, db, 1, "keep", 41411, "kept@x") + settings := `{"clients":[{"email":"kept@x","enable":true}]}` + sync := func(t *testing.T, report func(*runtime.TrafficSnapshot)) { + t.Helper() + snap := snapshotWithClients(t, "keep", settings, xray.ClientTraffic{Email: "kept@x", Enable: true}) + report(snap) + if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil { + t.Fatalf("sync: %v", err) + } + } + sync(t, func(*runtime.TrafficSnapshot) {}) + + steps := []struct { + name string + report func(*runtime.TrafficSnapshot) + subNode bool + wantSynced int + wantTotal int + }{ + { + name: "own GUID entry counted once per client, other GUIDs left out", + report: func(snap *runtime.TrafficSnapshot) { + snap.OnlineTree = map[string][]string{ + "node-guid": {"kept@x", "local-a@x", "local-a@x", "local-b@x"}, + "someone-else": {"s1@x", "s2@x", "s3@x", "s4@x", "s5@x"}, + } + }, + wantSynced: 1, + wantTotal: 3, + }, + { + name: "survives the per-GUID recount a sub-node triggers", + report: func(snap *runtime.TrafficSnapshot) { + snap.OnlineTree = map[string][]string{"node-guid": {"kept@x", "local-a@x"}} + }, + subNode: true, + wantSynced: 1, + wantTotal: 2, + }, + { + name: "flat list of a node without the per-GUID endpoint", + report: func(snap *runtime.TrafficSnapshot) { + snap.OnlineEmails = []string{"local-a@x", "local-b@x", "local-c@x", "kept@x"} + }, + wantSynced: 1, + wantTotal: 4, + }, + { + name: "an empty report replaces the previous total", + report: func(*runtime.TrafficSnapshot) {}, + }, + } + for _, step := range steps { + t.Run(step.name, func(t *testing.T) { + if step.subNode { + nodeDescendantsMu.Lock() + nodeDescendantsCache[1] = []model.NodeSummary{{Guid: "sub-guid", ParentGuid: "node-guid", Name: "sub"}} + nodeDescendantsMu.Unlock() + t.Cleanup(func() { + nodeDescendantsMu.Lock() + nodeDescendantsCache = map[int][]model.NodeSummary{} + nodeDescendantsMu.Unlock() + }) + } + sync(t, step.report) + + tree, err := (&NodeService{}).GetNodeTree() + if err != nil { + t.Fatalf("GetNodeTree: %v", err) + } + for _, n := range tree { + if n.Id != 1 { + if n.OnlineTotalCount != 0 { + t.Errorf("sub-node %q total online = %d, want 0: nothing reports it", n.Guid, n.OnlineTotalCount) + } + continue + } + if n.OnlineCount != step.wantSynced || n.OnlineTotalCount != step.wantTotal { + t.Errorf("online = %d synced / %d total, want %d / %d", n.OnlineCount, n.OnlineTotalCount, step.wantSynced, step.wantTotal) + } + } + if step.subNode && len(tree) != 2 { + t.Fatalf("tree has %d nodes, want the node and its sub-node", len(tree)) + } + }) + } +} + +// A node the sync no longer reaches keeps no online clients, so it keeps no total either. +func TestNodeOnlineTotalIsDroppedWithTheNodesOnlineClients(t *testing.T) { + tests := []struct { + name string + drop func(svc *InboundService) + }{ + {"failed probe", func(svc *InboundService) { svc.ClearNodeOnlineClients(1) }}, + {"node disabled", func(svc *InboundService) { + svc.RetainSyncedNodeOnlineClients([]*model.Node{{Id: 1, Enable: false, Status: "online"}}) + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db := initTrafficTestDB(t) + useOnlineTestProcess(t) + svc := &InboundService{} + seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true, Guid: "node-guid"}) + // No synced client is online, so only the total holds the node's entry. + snap := &runtime.TrafficSnapshot{OnlineTree: map[string][]string{"node-guid": {"local-a@x", "local-b@x"}}} + if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil { + t.Fatalf("sync: %v", err) + } + if got := svc.GetNodeOnlineTotals()[1]; got != 2 { + t.Fatalf("total online before the drop = %d, want 2", got) + } + + tt.drop(svc) + + if got := svc.GetNodeOnlineTotals(); len(got) != 0 { + t.Errorf("total online after the drop = %v, want none", got) + } + }) + } +} diff --git a/internal/web/service/node_tree.go b/internal/web/service/node_tree.go index 11f2a39aa..393cad1b4 100644 --- a/internal/web/service/node_tree.go +++ b/internal/web/service/node_tree.go @@ -260,10 +260,13 @@ func (s *NodeService) recountByGuid(nodes []*model.Node, selfGuid string) { } onlineByGuid := s.onlineEmailsByGuid() + onlineTotals := (&InboundService{}).GetNodeOnlineTotals() for _, n := range nodes { guid := effectiveNodeGuid(n, ambiguous) n.InboundCount = inboundCountByGuid[guid] n.OnlineCount = len(onlineByGuid[guid]) + // Keyed by node id, so a transitive sub-node (id 0) never has one. + n.OnlineTotalCount = onlineTotals[n.Id] n.DepletedCount = depletedByGuid[guid] n.DisabledCount = disabledByGuid[guid] n.ActiveCount = activeByGuid[guid] diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 8793eaa33..d7729f1c3 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -1222,6 +1222,7 @@ "onlineNodes": "متصل", "offlineNodes": "غير متصل", "avgLatency": "متوسط الكمون", + "onlineOnNode": "{synced} متصل على الاتصالات الواردة المستوردة إلى هذه اللوحة، و{total} متصل على العقدة إجمالاً", "name": "الاسم", "namePlaceholder": "مثال: de-frankfurt-1", "addressPlaceholder": "panel.example.com أو 1.2.3.4", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 49ab6c892..a092f1c62 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -1343,6 +1343,7 @@ "onlineNodes": "Online", "offlineNodes": "Offline", "avgLatency": "Avg Latency", + "onlineOnNode": "{synced} online on inbounds imported into this panel, {total} online on the node in total", "name": "Name", "namePlaceholder": "e.g. de-frankfurt-1", "addressPlaceholder": "panel.example.com or 1.2.3.4", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index aeb4bc385..fc8562787 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -1222,6 +1222,7 @@ "onlineNodes": "En línea", "offlineNodes": "Sin conexión", "avgLatency": "Latencia media", + "onlineOnNode": "{synced} en línea en los inbounds importados a este panel, {total} en línea en total en el nodo", "name": "Nombre", "namePlaceholder": "p. ej. de-frankfurt-1", "addressPlaceholder": "panel.example.com o 1.2.3.4", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 51d3effe5..4ea72f867 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -1222,6 +1222,7 @@ "onlineNodes": "آنلاین", "offlineNodes": "آفلاین", "avgLatency": "میانگین تاخیر", + "onlineOnNode": "{synced} آنلاین روی اینباندهای واردشده به این پنل، {total} آنلاین در کل نود", "name": "نام", "namePlaceholder": "مثلاً de-frankfurt-1", "addressPlaceholder": "panel.example.com یا 1.2.3.4", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 479bce2dc..a825d4c33 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -1222,6 +1222,7 @@ "onlineNodes": "Online", "offlineNodes": "Offline", "avgLatency": "Latensi Rata-rata", + "onlineOnNode": "{synced} online pada inbound yang diimpor ke panel ini, total {total} online di node", "name": "Nama", "namePlaceholder": "mis. de-frankfurt-1", "addressPlaceholder": "panel.example.com atau 1.2.3.4", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 26a98d514..2338bbc1c 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -1222,6 +1222,7 @@ "onlineNodes": "オンライン", "offlineNodes": "オフライン", "avgLatency": "平均レイテンシ", + "onlineOnNode": "このパネルにインポートしたインバウンドでオンライン: {synced}、ノード全体でオンライン: {total}", "name": "名前", "namePlaceholder": "例: de-frankfurt-1", "addressPlaceholder": "panel.example.com または 1.2.3.4", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index b9eeed22b..5fd957531 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -1222,6 +1222,7 @@ "onlineNodes": "Online", "offlineNodes": "Offline", "avgLatency": "Latência média", + "onlineOnNode": "{synced} online nos inbounds importados para este painel, {total} online no nó no total", "name": "Nome", "namePlaceholder": "ex.: de-frankfurt-1", "addressPlaceholder": "panel.example.com ou 1.2.3.4", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 59b97274c..49a3f2a43 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -1222,6 +1222,7 @@ "onlineNodes": "В сети", "offlineNodes": "Не в сети", "avgLatency": "Средняя задержка", + "onlineOnNode": "В сети на инбаундах, импортированных в эту панель: {synced}; всего в сети на узле: {total}", "name": "Имя", "namePlaceholder": "напр. de-frankfurt-1", "addressPlaceholder": "panel.example.com или 1.2.3.4", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index a400e4e45..7562dd9f8 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -1343,6 +1343,7 @@ "onlineNodes": "Online", "offlineNodes": "Offline", "avgLatency": "Priemerná odozva", + "onlineOnNode": "{synced} online na vstupoch importovaných do tohto panela, celkovo {total} online na uzle", "name": "Názov", "namePlaceholder": "napr. de-frankfurt-1", "addressPlaceholder": "panel.example.com alebo 1.2.3.4", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 147d35004..cde7b4f35 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -1222,6 +1222,7 @@ "onlineNodes": "Çevrimiçi", "offlineNodes": "Çevrimdışı", "avgLatency": "Ortalama Gecikme", + "onlineOnNode": "Bu panele içe aktarılan inbound'larda {synced} çevrimiçi, düğümde toplam {total} çevrimiçi", "name": "Ad", "namePlaceholder": "ör. de-frankfurt-1", "addressPlaceholder": "panel.example.com veya 1.2.3.4", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 4af33898f..da0390bf0 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -1222,6 +1222,7 @@ "onlineNodes": "У мережі", "offlineNodes": "Не в мережі", "avgLatency": "Середня затримка", + "onlineOnNode": "У мережі на інбаундах, імпортованих у цю панель: {synced}; усього в мережі на вузлі: {total}", "name": "Назва", "namePlaceholder": "напр. de-frankfurt-1", "addressPlaceholder": "panel.example.com або 1.2.3.4", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 2790b96eb..03aea4d6d 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -1222,6 +1222,7 @@ "onlineNodes": "Trực tuyến", "offlineNodes": "Ngoại tuyến", "avgLatency": "Độ trễ trung bình", + "onlineOnNode": "{synced} trực tuyến trên các inbound đã nhập vào bảng điều khiển này, tổng cộng {total} trực tuyến trên nút", "name": "Tên", "namePlaceholder": "vd: de-frankfurt-1", "addressPlaceholder": "panel.example.com hoặc 1.2.3.4", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 1d1720dec..3d49fe829 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -1222,6 +1222,7 @@ "onlineNodes": "在线", "offlineNodes": "离线", "avgLatency": "平均延迟", + "onlineOnNode": "导入此面板的入站上有 {synced} 个在线,该节点上共有 {total} 个在线", "name": "名称", "namePlaceholder": "例如:de-frankfurt-1", "addressPlaceholder": "panel.example.com 或 1.2.3.4", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 3ff06dfc3..05fb344f4 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -1222,6 +1222,7 @@ "onlineNodes": "上線", "offlineNodes": "離線", "avgLatency": "平均延遲", + "onlineOnNode": "匯入此面板的入站上有 {synced} 個上線,該節點上共有 {total} 個上線", "name": "名稱", "namePlaceholder": "例如:de-frankfurt-1", "addressPlaceholder": "panel.example.com 或 1.2.3.4", diff --git a/internal/xray/process.go b/internal/xray/process.go index fd3792183..6fe89d505 100644 --- a/internal/xray/process.go +++ b/internal/xray/process.go @@ -182,7 +182,10 @@ type process struct { // traffic within its own grace window. The inbounds page combines this with // nodeOnlineTrees so a multi-inbound client is not shown on an idle inbound. nodeActiveInboundTrees map[int]map[string][]string - onlineMu sync.RWMutex + // nodeOnlineTotals is, per direct node id, how many clients that node reported online + // on its own core: a number only, since most are not this panel's clients. + nodeOnlineTotals map[int]int + onlineMu sync.RWMutex // onlineAPISupport caches whether the running core implements the // online-stats RPCs (GetUsersStats). A new process is created on every @@ -583,6 +586,32 @@ func (p *Process) SetNodeActiveInboundTree(nodeID int, tree map[string][]string) p.nodeActiveInboundTrees[nodeID] = tree } +// SetNodeOnlineTotal records how many clients a direct node reported online on its own +// core, replacing the previous tick's number. +func (p *Process) SetNodeOnlineTotal(nodeID, total int) { + p.onlineMu.Lock() + defer p.onlineMu.Unlock() + if total <= 0 { + delete(p.nodeOnlineTotals, nodeID) + return + } + if p.nodeOnlineTotals == nil { + p.nodeOnlineTotals = map[int]int{} + } + p.nodeOnlineTotals[nodeID] = total +} + +// GetNodeOnlineTotals returns a copy of the per-node totals SetNodeOnlineTotal recorded. +func (p *Process) GetNodeOnlineTotals() map[int]int { + p.onlineMu.RLock() + defer p.onlineMu.RUnlock() + out := make(map[int]int, len(p.nodeOnlineTotals)) + for nodeID, total := range p.nodeOnlineTotals { + out[nodeID] = total + } + return out +} + // ClearNodeOnlineClients drops a direct node's whole subtree contribution. // Called when a probe fails so a downed node — and everything behind it — doesn't // keep its clients listed as "online" until the next successful probe. @@ -591,6 +620,7 @@ func (p *Process) ClearNodeOnlineClients(nodeID int) { defer p.onlineMu.Unlock() delete(p.nodeOnlineTrees, nodeID) delete(p.nodeActiveInboundTrees, nodeID) + delete(p.nodeOnlineTotals, nodeID) } // RetainNodeOnlineClients drops the subtree of every direct node keep rejects: nodes @@ -608,6 +638,11 @@ func (p *Process) RetainNodeOnlineClients(keep func(nodeID int) bool) { delete(p.nodeActiveInboundTrees, nodeID) } } + for nodeID := range p.nodeOnlineTotals { + if !keep(nodeID) { + delete(p.nodeOnlineTotals, nodeID) + } + } } // GetUptime returns the uptime of the Xray process in seconds. From af917bc0af4e12430a494b59a8938288af935d3b Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 15:00:25 +0330 Subject: [PATCH 121/130] fix(clients): keep the client form footer inside a phone screen The "Usage & change history" button made the edit form's footer four labelled buttons in one row that cannot wrap. On a phone that row is wider than the modal, so the modal grew past the screen and Cancel and Save ended up outside it. Below 768px the two extra actions, Reset Traffic and the history button, now show only their icon and keep their name as an aria-label, so the row fits again. The row may also wrap, as a guard for a locale whose Cancel and Save labels are unusually long. Wider screens are unchanged. Layout is out of reach of the jsdom tests. Measured in headless Chromium at 360px on a running panel: before, three of the four buttons lay outside the viewport; after, all four sit on one row inside it in en-US, fa-IR and ru-RU, and at 1280px the labels are still shown. --- .../src/pages/clients/ClientFormModal.css | 26 +++++++++++++++++++ .../src/pages/clients/ClientFormModal.tsx | 8 ++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/frontend/src/pages/clients/ClientFormModal.css b/frontend/src/pages/clients/ClientFormModal.css index 3e5803424..52c695eed 100644 --- a/frontend/src/pages/clients/ClientFormModal.css +++ b/frontend/src/pages/clients/ClientFormModal.css @@ -3,3 +3,29 @@ .client-form-modal .ant-tabs-content > .ant-form-item:last-child { margin-bottom: 0; } + +/* Four labelled buttons are wider than a phone and would widen the modal past the + screen, so below the md breakpoint the two extra actions keep only their icon. */ +.client-form-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.client-form-footer-actions { + display: flex; + gap: 8px; + margin-inline-start: auto; +} + +@media (max-width: 767px) { + .client-form-footer-extra.ant-btn { + padding-inline: 0; + width: 32px; + } + + .client-form-footer-extra.ant-btn > span:not(.ant-btn-icon) { + display: none; + } +} diff --git a/frontend/src/pages/clients/ClientFormModal.tsx b/frontend/src/pages/clients/ClientFormModal.tsx index e66963c95..a55c11173 100644 --- a/frontend/src/pages/clients/ClientFormModal.tsx +++ b/frontend/src/pages/clients/ClientFormModal.tsx @@ -890,7 +890,7 @@ export default function ClientFormModal({ onCancel={close} afterClose={() => setActiveTab('basic')} footer={ -
+
{isEdit && resetTraffic && ( @@ -912,13 +914,15 @@ export default function ClientFormModal({ )} {isEdit && client?.email && ( )} -
+