Enhance Docker setup and user notification features
CI / Backend (build + test) (push) Failing after 1m35s
CI / Frontend (lint + typecheck + build) (push) Successful in 35s

- Updated docker-compose.yml to include environment variables and health checks for the app service.
- Modified Dockerfile to install curl for health checks and adjusted the build process for backend services.
- Improved user notification handling in activation, blocking, and config revocation commands by integrating Telegram notifications.
- Added new test cases to validate the updated command handlers and Telegram notifier functionality.
- Enhanced documentation to reflect the new Telegram bot features and user management improvements.
This commit is contained in:
Leonid Pershin
2026-07-02 01:16:53 +03:00
parent 7b6fe9ad78
commit ed07221ca5
15 changed files with 404 additions and 34 deletions
@@ -262,7 +262,7 @@ public sealed class PnvBotUpdateHandler(
{
const string text = "Привет! Это бот PnvPanel.\n\n"
+ "/configs — мои конфиги\n"
+ "/login — войти на сайт без пароля\n"
+ "Вход без пароля запускается кнопкой «Войти через Telegram» на сайте — бот пришлёт запрос на подтверждение.\n"
+ "/unlink — отвязать Telegram\n"
+ "/help — эта справка";
await botClient.SendMessage(chatId, text, cancellationToken: cancellationToken);
@@ -9,7 +9,8 @@ using PnvPanel.Domain.Activation;
namespace PnvPanel.Application.Admin.Activation;
public sealed class ApproveActivationCommandHandler(
IAppDbContext dbContext, IIdentityService identityService, IRealtimeNotifier notifier, ICurrentUser currentUser)
IAppDbContext dbContext, IIdentityService identityService, IRealtimeNotifier notifier,
ITelegramNotifier telegramNotifier, ICurrentUser currentUser)
: ICommandHandler<ApproveActivationCommand, Result>
{
public async Task<Result> Handle(ApproveActivationCommand command, CancellationToken cancellationToken)
@@ -33,6 +34,7 @@ public sealed class ApproveActivationCommandHandler(
return activateResult;
await notifier.NotifyUserActivatedAsync(request.UserId, cancellationToken);
await telegramNotifier.NotifyUserAsync(request.UserId, "✅ Ваш аккаунт активирован администратором.", cancellationToken);
return Result.Success();
}
}
@@ -10,7 +10,7 @@ namespace PnvPanel.Application.Admin.Users;
/// <summary>Блокировка гасит все активные конфиги в 3x-ui (см. architecture.md).</summary>
public sealed class BlockUserCommandHandler(
IAppDbContext dbContext, IIdentityService identityService, IXuiPanelGateway gateway,
IRealtimeNotifier notifier, ICurrentUser currentUser)
IRealtimeNotifier notifier, ITelegramNotifier telegramNotifier, ICurrentUser currentUser)
: ICommandHandler<BlockUserCommand, Result>
{
public async Task<Result> Handle(BlockUserCommand command, CancellationToken cancellationToken)
@@ -44,6 +44,8 @@ public sealed class BlockUserCommandHandler(
dbContext.AuditLogs.Add(AuditLog.Create(
currentUser.UserId, "UserBlocked", "User", command.UserId.ToString(), metadata: null, AuditSource.Web));
await telegramNotifier.NotifyUserAsync(command.UserId, "⛔ Ваш аккаунт заблокирован администратором.", cancellationToken);
return Result.Success();
}
}
@@ -9,7 +9,8 @@ using PnvPanel.Domain.Configs;
namespace PnvPanel.Application.Admin.Users;
public sealed class ForceRevokeConfigCommandHandler(
IAppDbContext dbContext, IXuiPanelGateway gateway, IRealtimeNotifier notifier, ICurrentUser currentUser)
IAppDbContext dbContext, IXuiPanelGateway gateway, IRealtimeNotifier notifier,
ITelegramNotifier telegramNotifier, ICurrentUser currentUser)
: ICommandHandler<ForceRevokeConfigCommand, Result>
{
public async Task<Result> Handle(ForceRevokeConfigCommand command, CancellationToken cancellationToken)
@@ -35,6 +36,9 @@ public sealed class ForceRevokeConfigCommandHandler(
dbContext.AuditLogs.Add(AuditLog.Create(
currentUser.UserId, "ConfigForceRevoked", "VpnConfig", config.Id.ToString(), metadata: null, AuditSource.Web));
await telegramNotifier.NotifyUserAsync(
config.UserId, $"⚠️ Администратор отозвал ваш конфиг «{config.Label ?? config.ClientEmail}».", cancellationToken);
return Result.Success();
}
}
@@ -14,6 +14,7 @@ public class ApproveActivationCommandHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
[Fact]
@@ -28,7 +29,7 @@ public class ApproveActivationCommandHandlerTests
_currentUser.UserId.Returns(adminId);
_identityService.ActivateUserAsync(request.UserId, adminId, Arg.Any<CancellationToken>()).Returns(Result.Success());
var handler = new ApproveActivationCommandHandler(dbContext, _identityService, _notifier, _currentUser);
var handler = new ApproveActivationCommandHandler(dbContext, _identityService, _notifier, _telegramNotifier, _currentUser);
var result = await handler.Handle(new ApproveActivationCommand(request.Id), CancellationToken.None);
@@ -43,7 +44,7 @@ public class ApproveActivationCommandHandlerTests
using var dbContext = InMemoryDbContextFactory.Create();
_currentUser.UserId.Returns(Guid.NewGuid());
var handler = new ApproveActivationCommandHandler(dbContext, _identityService, _notifier, _currentUser);
var handler = new ApproveActivationCommandHandler(dbContext, _identityService, _notifier, _telegramNotifier, _currentUser);
var result = await handler.Handle(new ApproveActivationCommand(Guid.NewGuid()), CancellationToken.None);
@@ -62,7 +63,7 @@ public class ApproveActivationCommandHandlerTests
_currentUser.UserId.Returns(Guid.NewGuid());
var handler = new ApproveActivationCommandHandler(dbContext, _identityService, _notifier, _currentUser);
var handler = new ApproveActivationCommandHandler(dbContext, _identityService, _notifier, _telegramNotifier, _currentUser);
var result = await handler.Handle(new ApproveActivationCommand(request.Id), CancellationToken.None);
@@ -83,7 +84,7 @@ public class ApproveActivationCommandHandlerTests
var failure = Error.NotFound("User.NotFound", "Пользователь не найден.");
_identityService.ActivateUserAsync(request.UserId, adminId, Arg.Any<CancellationToken>()).Returns(Result.Failure(failure));
var handler = new ApproveActivationCommandHandler(dbContext, _identityService, _notifier, _currentUser);
var handler = new ApproveActivationCommandHandler(dbContext, _identityService, _notifier, _telegramNotifier, _currentUser);
var result = await handler.Handle(new ApproveActivationCommand(request.Id), CancellationToken.None);
@@ -15,6 +15,7 @@ public class BlockUserCommandHandlerTests
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
[Fact]
@@ -25,7 +26,7 @@ public class BlockUserCommandHandlerTests
var failure = UserErrors.NotFound;
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Failure(failure));
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
@@ -55,7 +56,7 @@ public class BlockUserCommandHandlerTests
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_currentUser.UserId.Returns(adminId);
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
@@ -81,7 +82,7 @@ public class BlockUserCommandHandlerTests
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_currentUser.UserId.Returns(Guid.NewGuid());
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
@@ -0,0 +1,76 @@
using System.Net;
using PnvPanel.IntegrationTests.TestSupport;
using Xunit;
using static PnvPanel.IntegrationTests.TestSupport.AuthTestHelper;
namespace PnvPanel.IntegrationTests.Activation;
[Collection(IntegrationTestCollection.Name)]
public class ActivationFlowTests(PnvPanelWebApplicationFactory factory)
{
private sealed record ActivationRequestResponse(Guid Id, string? Comment, DateTimeOffset CreatedAt);
[Fact]
public async Task RequestThenAdminApprove_ActivatesUser()
{
using var userClient = factory.CreateClient();
var userName = $"dave_{Guid.NewGuid():N}"[..20];
var (userId, userToken) = await RegisterAndLoginAsync(userClient, userName, "P@ssw0rd123");
userClient.UseBearerToken(userToken);
var requestResponse = await userClient.PostJsonAsync("/api/activation/request", new { comment = "Please activate me" });
Assert.Equal(HttpStatusCode.OK, requestResponse.StatusCode);
var request = await requestResponse.ReadAsAsync<ActivationRequestResponse>();
Assert.NotNull(request);
using var adminClient = factory.CreateClient();
var adminToken = await LoginAsAdminAsync(adminClient);
adminClient.UseBearerToken(adminToken);
var approveResponse = await adminClient.PostAsync($"/api/admin/activation-requests/{request!.Id}/approve", content: null);
Assert.Equal(HttpStatusCode.NoContent, approveResponse.StatusCode);
var meResponse = await userClient.GetAsync("/api/auth/me");
var me = await meResponse.ReadAsAsync<CurrentUserResponse>();
Assert.True(me!.IsActivated);
Assert.Equal(userId, me.Id);
}
[Fact]
public async Task RequestThenAdminReject_KeepsUserNotActivated()
{
using var userClient = factory.CreateClient();
var userName = $"erin_{Guid.NewGuid():N}"[..20];
var (_, userToken) = await RegisterAndLoginAsync(userClient, userName, "P@ssw0rd123");
userClient.UseBearerToken(userToken);
var requestResponse = await userClient.PostJsonAsync("/api/activation/request", new { comment = (string?)null });
var request = await requestResponse.ReadAsAsync<ActivationRequestResponse>();
using var adminClient = factory.CreateClient();
var adminToken = await LoginAsAdminAsync(adminClient);
adminClient.UseBearerToken(adminToken);
var rejectResponse = await adminClient.PostJsonAsync($"/api/admin/activation-requests/{request!.Id}/reject", new { reason = "not enough info" });
Assert.Equal(HttpStatusCode.NoContent, rejectResponse.StatusCode);
var meResponse = await userClient.GetAsync("/api/auth/me");
var me = await meResponse.ReadAsAsync<CurrentUserResponse>();
Assert.False(me!.IsActivated);
}
[Fact]
public async Task Request_WhenAlreadyPending_ReturnsConflict()
{
using var userClient = factory.CreateClient();
var userName = $"frank_{Guid.NewGuid():N}"[..20];
var (_, userToken) = await RegisterAndLoginAsync(userClient, userName, "P@ssw0rd123");
userClient.UseBearerToken(userToken);
var first = await userClient.PostJsonAsync("/api/activation/request", new { comment = (string?)null });
Assert.Equal(HttpStatusCode.OK, first.StatusCode);
var second = await userClient.PostJsonAsync("/api/activation/request", new { comment = (string?)null });
Assert.Equal(HttpStatusCode.Conflict, second.StatusCode);
}
}
@@ -0,0 +1,82 @@
using System.Net;
using PnvPanel.IntegrationTests.TestSupport;
using Xunit;
using static PnvPanel.IntegrationTests.TestSupport.AuthTestHelper;
namespace PnvPanel.IntegrationTests.Admin;
[Collection(IntegrationTestCollection.Name)]
public class NodeInboundCrudTests(PnvPanelWebApplicationFactory factory)
{
private sealed record NodeResponse(Guid Id, string Name, string BaseAddress, string Username, string? Location, int Status, bool IsEnabled);
private sealed record InboundResponse(
Guid Id, Guid NodeId, string RemoteInboundId, int Protocol, string Remark, int Port,
bool IsPublished, string? DisplayName, int? MaxClients, IReadOnlyList<Guid> AllowedRoleIds);
private sealed record SyncNodeResponse(int InboundsSynced, int Status);
[Fact]
public async Task RegisterSyncListPublish_FullNodeInboundLifecycle_Succeeds()
{
using var adminClient = factory.CreateClient();
var adminToken = await LoginAsAdminAsync(adminClient);
adminClient.UseBearerToken(adminToken);
var registerResponse = await adminClient.PostJsonAsync("/api/admin/nodes", new
{
name = $"Node-{Guid.NewGuid():N}"[..20],
baseAddress = "https://node.example.com:2053",
username = "admin",
password = "node-panel-password",
location = "Germany",
});
Assert.Equal(HttpStatusCode.OK, registerResponse.StatusCode);
var node = await registerResponse.ReadAsAsync<NodeResponse>();
Assert.NotNull(node);
var listNodesResponse = await adminClient.GetAsync("/api/admin/nodes");
Assert.Equal(HttpStatusCode.OK, listNodesResponse.StatusCode);
var nodes = await listNodesResponse.ReadAsAsync<List<NodeResponse>>();
Assert.Contains(nodes!, n => n.Id == node!.Id);
var syncResponse = await adminClient.PostAsync($"/api/admin/nodes/{node!.Id}/sync", content: null);
Assert.Equal(HttpStatusCode.OK, syncResponse.StatusCode);
var sync = await syncResponse.ReadAsAsync<SyncNodeResponse>();
Assert.Equal(1, sync!.InboundsSynced);
var listInboundsResponse = await adminClient.GetAsync($"/api/admin/inbounds?nodeId={node.Id}");
Assert.Equal(HttpStatusCode.OK, listInboundsResponse.StatusCode);
var inbounds = await listInboundsResponse.ReadAsAsync<List<InboundResponse>>();
var inbound = Assert.Single(inbounds!);
Assert.False(inbound.IsPublished);
var publishResponse = await adminClient.SendPutJsonAsync($"/api/admin/inbounds/{inbound.Id}/publish", new
{
isPublished = true,
displayName = "Germany (VLESS)",
allowedRoleIds = Array.Empty<Guid>(),
maxClients = (int?)null,
});
Assert.Equal(HttpStatusCode.OK, publishResponse.StatusCode);
var published = await publishResponse.ReadAsAsync<InboundResponse>();
Assert.True(published!.IsPublished);
Assert.Equal("Germany (VLESS)", published.DisplayName);
}
[Fact]
public async Task RegisterNode_AsNonAdmin_ReturnsForbidden()
{
using var userClient = factory.CreateClient();
var userName = $"greg_{Guid.NewGuid():N}"[..20];
var (_, userToken) = await RegisterAndLoginAsync(userClient, userName, "P@ssw0rd123");
userClient.UseBearerToken(userToken);
var response = await userClient.PostJsonAsync("/api/admin/nodes", new
{
name = "Node", baseAddress = "https://node.example.com", username = "admin", password = "pw", location = (string?)null,
});
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
}
@@ -0,0 +1,104 @@
using System.Net;
using PnvPanel.IntegrationTests.TestSupport;
using Xunit;
using static PnvPanel.IntegrationTests.TestSupport.AuthTestHelper;
namespace PnvPanel.IntegrationTests.Configs;
[Collection(IntegrationTestCollection.Name)]
public class ConfigQuotaTests(PnvPanelWebApplicationFactory factory)
{
private const int Quota = 2;
private const int ConcurrentAttempts = 6;
private sealed record RoleResponse(Guid Id, string Name, int MaxConfigs, bool IsSystem);
private sealed record NodeResponse(Guid Id, string Name);
private sealed record SyncNodeResponse(int InboundsSynced, int Status);
private sealed record InboundResponse(Guid Id, Guid NodeId, string RemoteInboundId, int Protocol, string Remark, int Port, bool IsPublished);
private sealed record ActivationRequestResponse(Guid Id, string? Comment, DateTimeOffset CreatedAt);
/// <summary>
/// Доказывает, что pg_advisory_xact_lock в CreateVpnConfigCommandHandler реально защищает
/// от гонки: при параллельных запросах ровно Quota проходят, остальные — 409 QuotaExceeded.
/// Это поведение невозможно проверить unit-тестами на InMemory-провайдере (см. Application.Tests).
/// </summary>
[Fact]
public async Task ConcurrentConfigCreation_AllowsExactlyQuotaSuccesses()
{
using var adminClient = factory.CreateClient();
var adminToken = await LoginAsAdminAsync(adminClient);
adminClient.UseBearerToken(adminToken);
var rolesResponse = await adminClient.GetAsync("/api/admin/roles");
Assert.Equal(HttpStatusCode.OK, rolesResponse.StatusCode);
var roles = await rolesResponse.ReadAsAsync<List<RoleResponse>>();
var userRole = roles!.Single(r => r.Name == "user");
var updateRoleResponse = await adminClient.SendPutJsonAsync($"/api/admin/roles/{userRole.Id}", new { maxConfigs = Quota });
Assert.Equal(HttpStatusCode.OK, updateRoleResponse.StatusCode);
var registerNodeResponse = await adminClient.PostJsonAsync("/api/admin/nodes", new
{
name = $"QuotaNode-{Guid.NewGuid():N}"[..24],
baseAddress = "https://quota-node.example.com",
username = "admin",
password = "node-panel-password",
location = (string?)null,
});
var node = await registerNodeResponse.ReadAsAsync<NodeResponse>();
var syncResponse = await adminClient.PostAsync($"/api/admin/nodes/{node!.Id}/sync", content: null);
var sync = await syncResponse.ReadAsAsync<SyncNodeResponse>();
Assert.Equal(1, sync!.InboundsSynced);
var inboundsResponse = await adminClient.GetAsync($"/api/admin/inbounds?nodeId={node.Id}");
var inbound = (await inboundsResponse.ReadAsAsync<List<InboundResponse>>())!.Single();
var publishResponse = await adminClient.SendPutJsonAsync($"/api/admin/inbounds/{inbound.Id}/publish", new
{
isPublished = true,
displayName = "Quota inbound",
allowedRoleIds = new[] { userRole.Id },
maxClients = (int?)null,
});
Assert.Equal(HttpStatusCode.OK, publishResponse.StatusCode);
using var userClient = factory.CreateClient();
var userName = $"quota_{Guid.NewGuid():N}"[..20];
var (_, userToken) = await RegisterAndLoginAsync(userClient, userName, "P@ssw0rd123");
userClient.UseBearerToken(userToken);
var activationRequestResponse = await userClient.PostJsonAsync("/api/activation/request", new { comment = (string?)null });
var activationRequest = await activationRequestResponse.ReadAsAsync<ActivationRequestResponse>();
var approveResponse = await adminClient.PostAsync($"/api/admin/activation-requests/{activationRequest!.Id}/approve", content: null);
Assert.Equal(HttpStatusCode.NoContent, approveResponse.StatusCode);
var tasks = Enumerable.Range(0, ConcurrentAttempts).Select(async i =>
{
using var attemptClient = factory.CreateClient();
attemptClient.UseBearerToken(userToken);
return await attemptClient.PostJsonAsync("/api/configs", new
{
inboundId = inbound.Id,
label = $"device-{i}",
deviceLimit = (int?)null,
});
});
var responses = await Task.WhenAll(tasks);
var succeeded = responses.Count(r => r.StatusCode == HttpStatusCode.OK);
var quotaExceeded = responses.Count(r => r.StatusCode == HttpStatusCode.Conflict);
Assert.Equal(Quota, succeeded);
Assert.Equal(ConcurrentAttempts - Quota, quotaExceeded);
var myConfigsResponse = await userClient.GetAsync("/api/configs");
var myConfigs = await myConfigsResponse.ReadAsAsync<List<object>>();
Assert.Equal(Quota, myConfigs!.Count);
}
}
@@ -16,4 +16,7 @@ public static class HttpClientJsonExtensions
public static Task<HttpResponseMessage> PostJsonAsync(this HttpClient client, string url, object body)
=> client.PostAsJsonAsync(url, body, JsonOptions);
public static Task<HttpResponseMessage> SendPutJsonAsync(this HttpClient client, string url, object body)
=> client.PutAsJsonAsync(url, body, JsonOptions);
}