Refactor client update handling to support nullable parameters for name and expiration
CI / Backend (build + test) (push) Successful in 1m18s
CI / Frontend (lint + typecheck + build) (push) Successful in 59s

- Updated the `UpdateClientAsync` method in `IXuiPanelGateway` to accept nullable parameters for `name` and `expiresAt`, allowing for more flexible client management without unintended modifications.
- Adjusted the `BlockUserCommandHandler`, `UnblockUserCommandHandler`, and other related command handlers to utilize the new nullable parameters, ensuring that client names remain unchanged during block/unblock operations and that expiration dates are managed correctly.
- Enhanced the billing and configuration handling to reflect the new logic for managing client states based on expiration rather than enabling/disabling, improving reliability in client status management.
- Updated tests to cover the new behavior and ensure proper functionality across the application.
This commit is contained in:
Leonid Pershin
2026-07-19 18:58:36 +03:00
parent 5ff5224935
commit 979eddf72e
20 changed files with 282 additions and 29 deletions
@@ -42,13 +42,17 @@ public sealed class BlockUserCommandHandler(
if (inbound is not null && node is not null)
{
// name: null — не трогаем текущее имя клиента в панели, это не переименование.
// expiresAt: null — блокировка админом отдельная ось от биллинга (см.
// IXuiPanelGateway.UpdateClientAsync), срок оплаты не трогаем.
var updateResult = await gateway.UpdateClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
config.Protocol,
config.Label ?? config.ClientEmail,
name: null,
enable: false,
expiresAt: null,
cancellationToken
);
@@ -47,13 +47,17 @@ public sealed class UnblockUserCommandHandler(
if (inbound is not null && node is not null)
{
// name: null — не трогаем текущее имя клиента в панели, это не переименование.
// expiresAt: null — блокировка админом отдельная ось от биллинга (см.
// IXuiPanelGateway.UpdateClientAsync), срок оплаты не трогаем.
var updateResult = await gateway.UpdateClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
config.Protocol,
config.Label ?? config.ClientEmail,
name: null,
enable: true,
expiresAt: null,
cancellationToken
);
@@ -47,13 +47,18 @@ internal static class BillingConfigResumer
if (inbound is not null && node is not null)
{
// Возвращаем через expiryTime = новый newPaidUntil, а не enable:true — тот же
// механизм приостановки, что и у BillingService (см. IXuiPanelGateway.UpdateClientAsync):
// переписываем просроченную дату на настоящую, панель/Xray сами перестают считать
// клиента истёкшим. name: null — не переименовываем клиента.
var updateResult = await gateway.UpdateClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
config.Protocol,
config.Label ?? config.ClientEmail,
enable: true,
name: null,
enable: null,
expiresAt: newPaidUntil,
cancellationToken
);
@@ -36,6 +36,8 @@ public interface IXuiPanelGateway
/// Возвращает ClientExternalId, присвоенный панелью (UUID для VLESS/VMess, пароль для Trojan/Shadowsocks).
/// <paramref name="limitIp"/> — лимит одновременных IP клиента (квота роли, см. AppRole.MaxIpLimit);
/// -1 (RoleQuota.Unlimited) означает без лимита — гейтвей сам переводит его в нативное значение 3x-ui.
/// <paramref name="expiresAt"/> — дата, до которой клиент активен в самой панели (billing-роли —
/// AppUser.BillingPaidUntil на момент создания); <c>null</c> — без ограничения по сроку.
/// </summary>
Task<Result<string>> AddClientAsync(
Node node,
@@ -44,6 +46,7 @@ public interface IXuiPanelGateway
string clientEmail,
string clientName,
int limitIp,
DateTimeOffset? expiresAt,
CancellationToken cancellationToken
);
@@ -55,13 +58,35 @@ public interface IXuiPanelGateway
CancellationToken cancellationToken
);
/// <summary>
/// Все параметры, кроме обязательных идентификаторов, — "не трогать, если null" (см. ThreeXui.Net
/// UpdateClientRequest: "All fields optional — null means leave as is").
/// <para>
/// <paramref name="name"/> — НЕ отдельная косметическая метка: у клиента 3x-ui нет своего поля
/// remark/comment, поэтому ThreeXui.Net пишет её в то же поле <c>settings.clients[].email</c>,
/// которое AddClientAsync изначально заполняет стабильным ClientEmail. Передавайте <c>null</c>
/// для любого вызова, не являющегося намеренным переименованием — иначе затрёте панельный
/// identity-идентификатор клиента (и сломаете сопоставление по email в GetClientTrafficAsync).
/// Единственный легитимный вызывающий с непустым name — EditVpnConfigCommandHandler.
/// </para>
/// <para>
/// <paramref name="expiresAt"/> — используется для приостановки/возврата за неуплату
/// (BillingService/BillingConfigResumer): дата в прошлом делает клиента просроченным для самой
/// панели/Xray независимо от <paramref name="enable"/> (по факту тестирования — переключение
/// enable ненадёжно останавливает уже установленные соединения, а expiryTime — надёжно), дата в
/// будущем (новый AppUser.BillingPaidUntil) снимает приостановку. Блокировка/разблокировка
/// админом (BlockUserCommandHandler/UnblockUserCommandHandler) — отдельная ось, передаёт
/// <c>expiresAt: null</c> и управляет только <paramref name="enable"/>.
/// </para>
/// </summary>
Task<Result> UpdateClientAsync(
Node node,
string inboundRemoteId,
string clientExternalId,
VpnProtocol protocol,
string name,
bool enable,
string? name,
bool? enable,
DateTimeOffset? expiresAt,
CancellationToken cancellationToken
);
@@ -73,6 +73,8 @@ public sealed class CreateVpnConfigCommandHandler(
config.ClientEmail,
config.Label ?? config.ClientEmail,
profile.MaxIpLimit,
// BillingRequired-проверка выше гарантирует, что при BillingEnabled PaidUntil уже в будущем.
expiresAt: profile.BillingEnabled ? profile.BillingPaidUntil : null,
cancellationToken
);
@@ -42,13 +42,17 @@ public sealed class EditVpnConfigCommandHandler(
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
if (node is not null)
{
// enable/expiresAt: null — переименование не должно снимать приостановку/блокировку
// клиента (раньше здесь стояло enable:true и молча реактивировало погашенный за
// неуплату/блокировку конфиг просто оттого, что пользователь его переименовал).
var updateResult = await gateway.UpdateClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
config.Protocol,
command.Label,
enable: true,
enable: null,
expiresAt: null,
cancellationToken
);
@@ -56,6 +56,9 @@ public sealed class RotateVpnConfigCommandHandler(
newClientEmail,
config.Label ?? newClientEmail,
profile.MaxIpLimit,
// Переносим уже действующий срок (billing paidUntil) на нового клиента — ротация не должна
// ни продлевать, ни сбрасывать оплаченный период.
expiresAt: config.ExpiresAt,
cancellationToken
);
@@ -139,13 +139,18 @@ public sealed class BillingService(
if (inbound is not null && node is not null)
{
// Приостанавливаем через expiryTime в прошлом, а не enable:false — переключение enable
// ненадёжно останавливает уже установленные соединения на стороне Xray/панели (см.
// IXuiPanelGateway.UpdateClientAsync), просроченный expiryTime — надёжно и независимо
// от enable. name: null — не переименовываем клиента.
var updateResult = await gateway.UpdateClientAsync(
node,
inbound.RemoteInboundId,
config.ClientExternalId,
config.Protocol,
config.Label ?? config.ClientEmail,
enable: false,
name: null,
enable: null,
expiresAt: DateTimeOffset.UtcNow.AddDays(-1),
cancellationToken
);
@@ -92,6 +92,7 @@ internal sealed class XuiPanelGateway(
string clientEmail,
string clientName,
int limitIp,
DateTimeOffset? expiresAt,
CancellationToken cancellationToken
)
{
@@ -105,7 +106,7 @@ internal sealed class XuiPanelGateway(
clientEmail,
ToRemoteProtocol(protocol),
limitIp == RoleQuota.Unlimited ? 0 : limitIp,
null
expiresAt
);
var result = await client.AddClientAsync(inboundRemoteId, request, cancellationToken);
return Result.Success(result.ExternalClientId);
@@ -150,16 +151,17 @@ internal sealed class XuiPanelGateway(
string inboundRemoteId,
string clientExternalId,
VpnProtocol protocol,
string name,
bool enable,
string? name,
bool? enable,
DateTimeOffset? expiresAt,
CancellationToken cancellationToken
)
{
try
{
var client = GetClient(node);
// deviceLimit: null — не трогаем то, что уже стоит на клиенте в панели (см. AddClientAsync).
var request = new UpdateClientRequest(null, null, enable, name);
// limitIp: null — не трогаем то, что уже стоит на клиенте в панели (см. AddClientAsync).
var request = new UpdateClientRequest(null, expiresAt, enable, name);
await client.UpdateClientAsync(
inboundRemoteId,
clientExternalId,