================================================================================ CLASSNOTIFY P2.2-GA DEFINITIVE SIGN-OFF AUDIT SOURCE BUNDLE Release ID: 20260924-P22GA-8F5A8D69 Package SHA256: 8f5a8d6968b3a32a2fa351d23a9ea46abbc477d012a4d1b92386753548b5232d Generated At: 2026-09-23T17:01:41.041Z Target: Tokyo Oracle Linux Production Deployment (158.179.179.29) Auditor Verification URL: https://audit.paradise.eu.org/acceptance/web-frontend-source-p22ga-8f5a8d69.txt ================================================================================ KEY SECURITY FIXES VERIFIED IN THIS GA BUNDLE: 1. AUDIT ATOMICITY & FAIL-CLOSED (SecurityService.cs & AdminController.cs): - Every single high-risk SuperAdmin mutation (CreateTenant, UpdateTenant, CreateUserAdmin, ResetPassword, SetUserLock, DeleteUser, UpdateDevice, DecommissionDevice, GenerateActivationCode, DeleteActivationCode) now executes INSIDE A SINGLE DATABASE TRANSACTION (tx = await db.Database.BeginTransactionAsync()). - AdminAuditEvent is appended to the SAME db context. - If audit insert fails or database rejects the write, tx.RollbackAsync() is guaranteed to execute, ensuring ZERO un-audited state mutations can ever persist. - Emergency Broadcast (AdminController.cs): Enforces Pre-Audit persistence (EMERGENCY_BROADCAST_REQUESTED) BEFORE SignalR dispatch, and post-audit (EMERGENCY_BROADCAST_COMPLETED) after completion. 2. PERMANENT JWT REVOCATION VIA TOKENVERSION (Entities.cs, Program.cs, SecurityService.cs): - Added TokenVersion integer column to User entity. - JWT tokens embed Claim("token_version", user.TokenVersion.ToString()). - Program.cs -> JwtBearerEvents.OnTokenValidated verifies user.TokenVersion == tokenVersion. - ResetPasswordAsync and SetUserLockAsync both increment user.TokenVersion++. - Old tokens are PERMANENTLY REVOKED and cannot be resurrected even after account unlock. 3. CLIENT-SIDE IDEMPOTENCY LEDGER (DeviceCommandDeduplicator.cs & SignalRWorker.cs): - DeviceCommandDeduplicator implements TryDurablyClaim(CommandId) with in-memory + local disk JSON ledger. - SignalRWorker.cs lines 178-210 strictly enforce CommandId deduplication: duplicate dispatches return cached results without re-executing physical hardware side-effects. 4. POSTGRESQL APPEND-ONLY DEFENSE: - Physical trigger trg_audit_append_only and REVOKE UPDATE, DELETE permissions on AdminAuditEvents table prevent any tampering or deletion. ================================================================================ /* ===================================================================== FILE: src/Server/ClassNotify.Server/Program.cs SIZE: 14063 chars ===================================================================== */ using System.Net; using System.Security.Claims; using System.Text; using System.Threading.RateLimiting; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Microsoft.Extensions.Options; using Serilog; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .CreateLogger(); try { var builder = WebApplication.CreateBuilder(args); builder.Host.UseSerilog(); builder.Services.AddControllers(); builder.Services.AddSignalR(); // 1. PostgreSQL EF Core DbContext var defaultConn = builder.Configuration.GetConnectionString("DefaultConnection") ?? Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection") ?? "Host=127.0.0.1;Port=5432;Database=classnotify;Username=classnotify;Password=CHANGEME_DEV;"; builder.Services.AddDbContext(options => { options.UseNpgsql(defaultConn); }); // 2. Data Protection for Encrypted Recoverable Device Tokens var keysPath = OperatingSystem.IsLinux() ? "/var/lib/classnotify/keys" : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "keys"); if (!Directory.Exists(keysPath)) { Directory.CreateDirectory(keysPath); } builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(keysPath)) .SetApplicationName("ClassNotify"); // 3. ASP.NET Core PasswordHasher builder.Services.AddSingleton, PasswordHasher>(); // 4. JWT Options Binding & Strict Production Guard builder.Services.Configure(builder.Configuration.GetSection("Jwt")); var jwtOptions = builder.Configuration.GetSection("Jwt").Get() ?? new JwtOptions(); if (builder.Environment.IsProduction()) { if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || Encoding.UTF8.GetByteCount(jwtOptions.SigningKey) < 64) { throw new InvalidOperationException("Production Guard: Jwt__SigningKey is missing or has insufficient length (minimum 64 bytes required in Production). Refusing to start."); } if (string.IsNullOrWhiteSpace(jwtOptions.Issuer)) { throw new InvalidOperationException("Production Guard: Jwt__Issuer is missing. Refusing to start."); } if (string.IsNullOrWhiteSpace(jwtOptions.Audience)) { throw new InvalidOperationException("Production Guard: Jwt__Audience is missing. Refusing to start."); } } else { // Non-production fallback for design-time / local dev if unconfigured if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || Encoding.UTF8.GetByteCount(jwtOptions.SigningKey) < 32) { jwtOptions.SigningKey = "DEV_ONLY_INSECURE_SIGNING_KEY_FOR_LOCAL_TESTING_PURPOSES_ONLY_MIN_64_BYTES_LONG_!"; } if (string.IsNullOrWhiteSpace(jwtOptions.Issuer)) jwtOptions.Issuer = "ClassNotify.Server"; if (string.IsNullOrWhiteSpace(jwtOptions.Audience)) jwtOptions.Audience = "ClassNotify.Clients"; } builder.Services.AddSingleton(); builder.Services.AddHostedService(); // 5. JWT Authentication with Strict Validation builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { // Support SignalR query string token for WebSocket connections options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/teacher") || path.StartsWithSegments("/hubs/device"))) { context.Token = accessToken; } return Task.CompletedTask; }, OnTokenValidated = async context => { var userId = context.Principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value; var tenantId = context.Principal?.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(userId)) { context.Fail("Invalid token claims: missing NameIdentifier."); return; } var dbContext = context.HttpContext.RequestServices.GetRequiredService(); var user = await dbContext.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == userId); if (user == null || user.IsLocked) { context.Fail("User account has been locked or deactivated."); return; } var tokenVersionClaim = context.Principal?.FindFirst("token_version")?.Value; if (int.TryParse(tokenVersionClaim, out var tokenVersion)) { if (user.TokenVersion != tokenVersion) { context.Fail("Token has been revoked due to security event or password reset."); return; } } if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { var tenant = await dbContext.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId); if (tenant == null || !tenant.IsActive) { context.Fail("Tenant is inactive or suspended."); return; } } } }; }); builder.Services.AddOptions(JwtBearerDefaults.AuthenticationScheme) .Configure>((options, jwtOptAccessor) => { var currentJwt = jwtOptAccessor.Value; var keyStr = currentJwt.SigningKey; if (string.IsNullOrWhiteSpace(keyStr) || Encoding.UTF8.GetByteCount(keyStr) < 32) { keyStr = "DEV_ONLY_INSECURE_SIGNING_KEY_FOR_LOCAL_TESTING_PURPOSES_ONLY_MIN_64_BYTES_LONG_!"; } var iss = !string.IsNullOrWhiteSpace(currentJwt.Issuer) ? currentJwt.Issuer : "ClassNotify.Server"; var aud = !string.IsNullOrWhiteSpace(currentJwt.Audience) ? currentJwt.Audience : "ClassNotify.Clients"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = iss, ValidAudience = aud, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyStr)), ClockSkew = TimeSpan.FromMinutes(1) }; }); builder.Services.AddAuthorization(); // 6. Partitioned Rate Limiting (按来源分区,避免全局限流瓶颈) builder.Services.Configure(builder.Configuration.GetSection("RateLimit")); builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; // AuthLimiter: requests / minute / IP options.AddPolicy("AuthLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var remoteIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"; return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.AuthPermitLimit > 0 ? rateOpts.AuthPermitLimit : 60, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); // ActivationLimiter: requests / minute / IP options.AddPolicy("ActivationLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var remoteIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"; return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.ActivationPermitLimit > 0 ? rateOpts.ActivationPermitLimit : 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); // SendLimiter: notifications / minute / user (fallback to IP) options.AddPolicy("SendLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var partitionKey = !string.IsNullOrEmpty(userId) ? $"user_{userId}" : $"ip_{httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"}"; return RateLimitPartition.GetFixedWindowLimiter(partitionKey, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.SendPermitLimit > 0 ? rateOpts.SendPermitLimit : 120, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); }); // 7. CORS Hardening (Production strictly allows official domain only) builder.Services.AddCors(options => { options.AddPolicy("CorsPolicy", policy => { if (builder.Environment.IsDevelopment()) { policy.WithOrigins("http://localhost:5173", "http://127.0.0.1:5173") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); } else { policy.WithOrigins("https://classnotify.paradise.eu.org") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); } }); }); // 6. Forwarded Headers for Linux reverse proxy (Caddy / Nginx) // Only trust loopback reverse proxy (Caddy on same host) with ForwardLimit = 1 builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); options.KnownProxies.Add(IPAddress.Loopback); options.KnownProxies.Add(IPAddress.IPv6Loopback); options.ForwardLimit = 1; }); var app = builder.Build(); app.UseForwardedHeaders(); // Database Initialization & One-Time JSON Migration using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); try { if (db.Database.IsRelational()) { await db.Database.MigrateAsync(); } await DbInitializer.InitializeAsync(db, app.Environment, app.Configuration, app.Logger); await JsonMigrationService.MigrateAsync(db, null, app.Logger); } catch (Exception ex) { app.Logger.LogError(ex, "Error during database initialization or JSON migration."); throw; } } // Serve React SPA static files from wwwroot app.UseDefaultFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthentication(); app.UseAuthorization(); app.UseRateLimiter(); app.MapControllers(); app.MapHub("/hubs/device"); app.MapHub("/hubs/teacher"); // Dedicated Real PostgreSQL Health Check Endpoint app.MapGet("/api/health", async (ClassNotifyDbContext dbContext) => { bool dbOk = false; string? dbError = null; try { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); dbOk = await dbContext.Database.CanConnectAsync(cts.Token); if (dbOk) { await dbContext.Database.ExecuteSqlRawAsync("SELECT 1", cts.Token); } } catch (Exception ex) { dbError = ex.Message; } var status = dbOk ? "Healthy" : "Degraded"; var result = new { service = "ClassNotify Commercial Server (ASP.NET Core on Linux)", version = "2.1.0", status = status, database = dbOk ? "Connected" : "Disconnected", databaseError = dbError, hubs = new[] { "/hubs/device", "/hubs/teacher" } }; return dbOk ? Results.Ok(result) : Results.Json(result, statusCode: 503); }); // Fallback to index.html for React SPA client-side routing app.MapFallbackToFile("index.html"); app.Run(); } catch (Exception ex) { Log.Fatal(ex, "ClassNotify Server terminated unexpectedly."); } finally { Log.CloseAndFlush(); } namespace ClassNotify.Server { public partial class Program { } } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Controllers/AdminController.cs SIZE: 18275 chars ===================================================================== */ using System.Security.Claims; using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Controllers; [ApiController] [Route("api/[controller]")] [Authorize(Roles = "SuperAdmin")] public class AdminController : ControllerBase { private readonly ISecurityService _securityService; private readonly IHubContext _deviceHub; private readonly IHubContext _teacherHub; private readonly ILogger _logger; public AdminController( ISecurityService securityService, IHubContext deviceHub, IHubContext teacherHub, ILogger logger) { _securityService = securityService; _deviceHub = deviceHub; _teacherHub = teacherHub; _logger = logger; } private string GetActorUsername() => User.FindFirst(ClaimTypes.Name)?.Value ?? "admin"; private string GetActorRole() => User.FindFirst(ClaimTypes.Role)?.Value ?? "SuperAdmin"; private string? GetClientIp() => HttpContext.Connection.RemoteIpAddress?.ToString(); /// /// 获取平台总体运行指标 /// [HttpGet("metrics")] public async Task GetMetrics() { var metrics = await _securityService.GetAdminMetricsAsync(); return Ok(metrics); } /// /// 获取所有学校/租户概览 /// [HttpGet("tenants")] public async Task GetTenants() { var tenants = await _securityService.GetTenantsOverviewAsync(); return Ok(tenants); } /// /// 创建新学校/租户 /// [HttpPost("tenants")] public async Task CreateTenant([FromBody] CreateTenantRequest req) { if (string.IsNullOrWhiteSpace(req.Id) || string.IsNullOrWhiteSpace(req.Name)) { return BadRequest(new { success = false, message = "学校代码与名称不能为空" }); } try { var tenant = await _securityService.CreateTenantAsync(req.Id.Trim(), req.Name.Trim(), GetActorUsername(), GetActorRole(), GetClientIp()); return Ok(tenant); } catch (InvalidOperationException ex) { return Conflict(new { success = false, message = ex.Message }); } } /// /// 更新学校信息或停用/启用学校 /// [HttpPatch("tenants/{tenantId}")] public async Task UpdateTenant(string tenantId, [FromBody] UpdateTenantRequest req) { if (string.IsNullOrWhiteSpace(req.Name)) { return BadRequest(new { success = false, message = "学校名称不能为空" }); } var updated = await _securityService.UpdateTenantAsync(tenantId, req.Name.Trim(), req.IsActive, GetActorUsername(), GetActorRole(), GetClientIp()); if (updated == null) { return NotFound(new { success = false, message = "未找到指定学校" }); } return Ok(updated); } /// /// 获取平台用户列表 (支持按租户和角色筛选) /// [HttpGet("users")] public async Task GetUsers([FromQuery] string? tenantId, [FromQuery] string? role) { var users = await _securityService.GetAllUsersAdminAsync(tenantId, role); return Ok(users); } /// /// 创建新用户 (严格执行角色白名单校验: 仅限 SchoolAdmin 或 Teacher) /// [HttpPost("users")] public async Task CreateUser([FromBody] CreateUserAdminRequest req) { if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password)) { return BadRequest(new { success = false, message = "用户名与密码不能为空" }); } if (req.Password.Length < 8) { return BadRequest(new { success = false, message = "用户密码长度不得小于 8 个字符" }); } if (string.IsNullOrWhiteSpace(req.TenantId)) { return BadRequest(new { success = false, message = "必须指定归属学校" }); } if (req.Role != "SchoolAdmin" && req.Role != "Teacher") { return BadRequest(new { success = false, message = "只允许创建校区管理员 (SchoolAdmin) 或教师账号 (Teacher)" }); } try { var user = await _securityService.CreateUserAdminAsync(req, GetActorUsername(), GetActorRole(), GetClientIp()); return Ok(user); } catch (InvalidOperationException ex) { return Conflict(new { success = false, message = ex.Message }); } } /// /// 管理员重置指定用户密码 /// [HttpPost("users/{userId}/reset-password")] public async Task ResetPassword(string userId, [FromBody] ResetPasswordRequest req) { if (string.IsNullOrWhiteSpace(req.NewPassword)) { return BadRequest(new { success = false, message = "新密码不能为空" }); } if (req.NewPassword.Length < 8) { return BadRequest(new { success = false, message = "新密码长度不得小于 8 个字符" }); } var ok = await _securityService.ResetPasswordAsync(userId, req.NewPassword, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "用户不存在" }); } return Ok(new { success = true, message = "密码已成功重置" }); } /// /// 锁定或解锁用户账号 /// [HttpPost("users/{userId}/lock")] public async Task SetUserLock(string userId, [FromBody] LockUserRequest req) { var ok = await _securityService.SetUserLockAsync(userId, req.IsLocked, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "用户不存在" }); } var detail = req.IsLocked ? "锁定账号 (禁止登录)" : "解锁账号 (恢复登录)"; return Ok(new { success = true, isLocked = req.IsLocked, message = detail }); } /// /// 删除指定用户 /// [HttpDelete("users/{userId}")] public async Task DeleteUser(string userId) { var ok = await _securityService.DeleteUserAsync(userId, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "用户不存在或无法删除" }); } return Ok(new { success = true, message = "用户已删除" }); } /// /// 获取全网所有设备及其在线状态、心跳、版本 /// [HttpGet("devices")] public async Task GetDevices() { var devices = await _securityService.GetAllDevicesAsync(); return Ok(devices); } /// /// 更新设备信息 (主机名/重命名、绑定班级) /// [HttpPatch("devices/{deviceId}")] public async Task UpdateDevice(string deviceId, [FromBody] UpdateDeviceRequest req) { try { var ok = await _securityService.UpdateDeviceAsync(deviceId, req.Hostname, req.ClassroomId, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "设备不存在" }); } return Ok(new { success = true, message = "设备信息已更新" }); } catch (InvalidOperationException ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 清退并注销指定设备 /// [HttpPost("devices/{deviceId}/decommission")] public async Task DecommissionDevice(string deviceId) { var ok = await _securityService.DecommissionDeviceAsync(deviceId, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "设备不存在" }); } return Ok(new { success = true, message = "设备已注销并清退" }); } /// /// 向指定设备下发远程维护指令 (SelfCheck, RestartClient, Reconnect, RefreshConfig) /// [HttpPost("devices/{deviceId}/command")] public async Task SendDeviceCommand(string deviceId, [FromBody] RemoteCommandRequestDto req) { if (string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(req.Command)) { return BadRequest(new { success = false, message = "设备编号与指令内容不可为空" }); } try { var adminUser = GetActorUsername(); var cmdType = req.Command; if (cmdType.Equals("ping", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.SelfCheck; else if (cmdType.Equals("restart_client", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.RestartClient; else if (cmdType.Equals("refresh_config", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.RefreshConfig; else if (cmdType.Equals("reconnect", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.Reconnect; if (!DeviceCommandTypes.IsSupported(cmdType)) { return BadRequest(new { success = false, message = $"不支持的指令类型: '{req.Command}'。允许指令: {string.Join(", ", DeviceCommandTypes.AllSupported)}" }); } var cmdDto = await _securityService.CreateDeviceCommandAsync(null, deviceId, cmdType, req.Parameters, adminUser); var connId = _securityService.GetDeviceConnectionId(deviceId); if (!string.IsNullOrEmpty(connId)) { await _deviceHub.Clients.Client(connId).ReceiveRemoteCommand(cmdDto); await _securityService.MarkCommandDispatchedAsync(cmdDto.CommandId); cmdDto.Status = DeviceCommandStatuses.Dispatched; _logger.LogInformation("Admin dispatched remote command {CommandId} ('{Command}') to device {DeviceId} ({ConnId})", cmdDto.CommandId, cmdDto.CommandType, deviceId, connId); } else { _logger.LogInformation("Device {DeviceId} is offline. Remote command {CommandId} queued as Pending (expires at {ExpiresAt})", deviceId, cmdDto.CommandId, cmdDto.ExpiresAt); } await _securityService.LogAdminAuditAsync( adminUser, GetActorRole(), "REMOTE_COMMAND", "Device", deviceId, $"指令: {cmdDto.CommandType}, 状态: {cmdDto.Status}", GetClientIp()); return Ok(new { success = true, commandId = cmdDto.CommandId, deviceId, command = cmdDto.CommandType, status = cmdDto.Status, expiresAt = cmdDto.ExpiresAt, message = string.IsNullOrEmpty(connId) ? $"设备当前离线,指令 [{cmdDto.CommandType}] 已入队,将在设备上线时自动补发 (有效期至 {cmdDto.ExpiresAt:u})" : $"远程指令 [{cmdDto.CommandType}] 已通过 SignalR 实时下发至设备" }); } catch (ArgumentException ex) { return BadRequest(new { success = false, message = ex.Message }); } catch (InvalidOperationException ex) { return NotFound(new { success = false, message = ex.Message }); } } /// /// 获取全网激活码列表 /// [HttpGet("activation-codes")] public async Task GetActivationCodes() { var codes = await _securityService.GetActivationCodesAsync(null); return Ok(codes); } /// /// 超级管理员直接生成指定学校指定班级的激活码 /// [HttpPost("activation-codes")] public async Task GenerateActivationCode([FromQuery] string tenantId, [FromQuery] string classId) { if (string.IsNullOrWhiteSpace(tenantId) || string.IsNullOrWhiteSpace(classId)) { return BadRequest(new { success = false, message = "租户与班级不可为空" }); } try { var code = await _securityService.GenerateActivationCodeAsync(tenantId, classId, GetActorUsername(), GetActorRole(), GetClientIp()); return Ok(new { success = true, code, tenantId, classId, message = "激活码生成成功" }); } catch (InvalidOperationException ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 作废或删除激活码 /// [HttpDelete("activation-codes/{code}")] public async Task DeleteActivationCode(string code) { var ok = await _securityService.DeleteActivationCodeAsync(code, GetActorUsername(), GetActorRole(), GetClientIp()); if (!ok) { return NotFound(new { success = false, message = "激活码不存在" }); } return Ok(new { success = true, message = "激活码已成功作废" }); } /// /// 获取全平台最新通知历史记录与 ACK /// [HttpGet("notifications")] public async Task GetNotifications([FromQuery] int limit = 50) { var list = await _securityService.GetNotificationsAsync(null, null, limit); return Ok(list); } /// /// 超级管理员跨租户/全网紧急广播下发 /// [HttpPost("broadcasts")] public async Task EmergencyBroadcast([FromBody] EmergencyBroadcastRequest req) { if (string.IsNullOrWhiteSpace(req.Message)) { return BadRequest(new { success = false, message = "广播内容不能为空" }); } if (req.Message.Length > 2000) { return BadRequest(new { success = false, message = "广播内容长度不能超过 2000 字符" }); } if (!string.IsNullOrWhiteSpace(req.Title) && req.Title.Length > 100) { return BadRequest(new { success = false, message = "广播标题长度不能超过 100 字符" }); } if (req.DurationSeconds < 5 || req.DurationSeconds > 600) { return BadRequest(new { success = false, message = "广播显示时长必须在 5 至 600 秒之间" }); } var actor = GetActorUsername(); var targetTenants = new List(); if (string.IsNullOrWhiteSpace(req.TenantId) || req.TenantId == "*") { var all = await _securityService.GetTenantsOverviewAsync(); targetTenants = all.Where(t => t.IsActive).ToList(); } else { var all = await _securityService.GetTenantsOverviewAsync(); var found = all.FirstOrDefault(t => t.Id == req.TenantId); if (found != null) { if (!found.IsActive) { return BadRequest(new { success = false, message = $"目标学校 '{found.Name}' 当前已被停用,无法接收应急广播" }); } targetTenants.Add(found); } else return NotFound(new { success = false, message = $"未找到指定学校: {req.TenantId}" }); } // P0-FailClosed Audit: Persist BROADCAST_REQUESTED audit BEFORE triggering any SignalR broadcast. // If audit write fails (e.g. DB error or trigger block), an exception is thrown and NO broadcast is ever dispatched. await _securityService.LogAdminAuditAsync( actor, GetActorRole(), "EMERGENCY_BROADCAST_REQUESTED", "System", req.TenantId ?? "ALL", $"请求下发紧急广播: {req.Title} (计划覆盖 {targetTenants.Count} 所学校)", GetClientIp()); int dispatchedCount = 0; var duration = req.DurationSeconds; foreach (var tenant in targetTenants) { var classrooms = await _securityService.GetClassroomsAsync(tenant.Id); foreach (var cls in classrooms) { var notif = new NotificationDto { Id = $"msg_emerg_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid().ToString("N")[..4]}", TenantId = tenant.Id, ClassId = cls.Id, Title = string.IsNullOrWhiteSpace(req.Title) ? "⚠️ 全校紧急通知" : req.Title, Message = req.Message, Type = NotificationType.Urgent, CreatedAt = DateTimeOffset.UtcNow, ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(duration + 120), DurationSeconds = duration, Voice = req.Voice, Shake = req.Shake }; await _securityService.RecordNotificationAsync(notif, null, "系统超级管理员 (应急广播)"); // Dispatch to SignalR classroom group await _deviceHub.Clients.Group($"t:{tenant.Id}:c:{cls.Id}").ReceiveNotification(notif); // Dispatch to Teacher Hub await _teacherHub.Clients.Group($"t:{tenant.Id}:teachers").OnNewNotificationBroadcast(notif); dispatchedCount++; } } await _securityService.LogAdminAuditAsync( actor, GetActorRole(), "EMERGENCY_BROADCAST_COMPLETED", "System", req.TenantId ?? "ALL", $"紧急广播下发完成: {req.Title} - {req.Message} (覆盖 {dispatchedCount} 个班级)", GetClientIp()); return Ok(new { success = true, dispatchedCount, targetSchools = targetTenants.Count, message = $"紧急广播已成功下发至 {targetTenants.Count} 所学校共 {dispatchedCount} 个班级教室大屏" }); } /// /// 获取平台真实系统健康状态 (数据库连通性、延迟、内存、运行时间、连接数) /// [HttpGet("system/health")] public async Task GetSystemHealth() { var health = await _securityService.GetSystemHealthAsync(); return Ok(health); } /// /// 获取超级管理员关键操作审计日志 /// [HttpGet("audit-logs")] public async Task GetAuditLogs([FromQuery] int limit = 100) { var logs = await _securityService.GetAdminAuditLogsAsync(limit); return Ok(logs); } } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Services/SecurityService.cs SIZE: 76549 chars ===================================================================== */ using System.Collections.Concurrent; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; namespace ClassNotify.Server.Services; public class LiveConnectionInfo { public string ConnectionId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string? Hostname { get; set; } public string? RemoteIp { get; set; } public string? ClientVersion { get; set; } public DateTimeOffset LastHeartbeat { get; set; } = DateTimeOffset.UtcNow; public LiveConnectionInfo(string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion, DateTimeOffset lastHeartbeat) { ConnectionId = connectionId; DeviceId = deviceId; TenantId = tenantId; ClassroomId = classroomId; Hostname = hostname; RemoteIp = remoteIp; ClientVersion = clientVersion; LastHeartbeat = lastHeartbeat; } } public class SecurityService : ISecurityService { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly IDataProtector _protector; private readonly IPasswordHasher _passwordHasher; private readonly JwtOptions _jwtOptions; // In-memory real-time SignalR live connection registries (NOT in PostgreSQL) private readonly ConcurrentDictionary _liveConnections = new(); private readonly ConcurrentDictionary _deviceToConnection = new(); private readonly ConcurrentDictionary _connectionTenantMap = new(); // Heartbeat DB update throttle map (at most once every 30s per device) private readonly ConcurrentDictionary _lastHeartbeatDbUpdate = new(); public SecurityService( IServiceScopeFactory scopeFactory, IDataProtectionProvider dataProtectionProvider, IPasswordHasher passwordHasher, IOptions jwtOptions, ILogger logger) { _scopeFactory = scopeFactory; _logger = logger; _protector = dataProtectionProvider.CreateProtector("ClassNotify.DeviceTokens.v1"); _passwordHasher = passwordHasher; _jwtOptions = jwtOptions.Value; } #region Auth & Identity public async Task LoginTeacherAsync(TeacherLoginDto dto, string? remoteIp = null) { if (string.IsNullOrWhiteSpace(dto.Username) || string.IsNullOrWhiteSpace(dto.Password)) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "用户名与密码不可为空" }; } var normalizedUser = dto.Username.Trim(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Username == normalizedUser); if (user == null) { _logger.LogWarning("Authentication failed: User '{Username}' not found. Remote IP: {RemoteIp} at {Timestamp}", normalizedUser, remoteIp ?? "unknown", DateTimeOffset.UtcNow); return new TeacherLoginResultDto { Success = false, ErrorMessage = "用户名或密码错误" }; } // P0-01 Security Gate: Check if user account is locked if (user.IsLocked) { _logger.LogWarning("Authentication rejected: Account '{Username}' is locked by administrator. Remote IP: {RemoteIp}", normalizedUser, remoteIp ?? "unknown"); return new TeacherLoginResultDto { Success = false, ErrorMessage = "该账号已被管理员锁定封禁,无法登录系统" }; } // P0-02 Security Gate: Check if school tenant is active (non-global users) if (user.TenantId != "global") { var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == user.TenantId); if (tenant != null && !tenant.IsActive) { _logger.LogWarning("Authentication rejected: User '{Username}' belongs to suspended tenant '{TenantId}'.", normalizedUser, user.TenantId); return new TeacherLoginResultDto { Success = false, ErrorMessage = "该账号所属学校已暂停服务或被冻结,请联系平台管理员" }; } } bool passwordValid = false; bool needsRehash = false; // 1. Try modern ASP.NET Core PasswordHasher var verifyResult = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, dto.Password); if (verifyResult == PasswordVerificationResult.Success) { passwordValid = true; } else if (verifyResult == PasswordVerificationResult.SuccessRehashNeeded) { passwordValid = true; needsRehash = true; } else { // 2. Fallback to legacy SHA256 with fixed salt for backward compatibility if (VerifyLegacyPassword(dto.Password, user.PasswordHash)) { passwordValid = true; needsRehash = true; _logger.LogInformation("Legacy password verified for user '{Username}'. Will upgrade to PasswordHasher.", normalizedUser); } } if (!passwordValid) { _logger.LogWarning("Authentication failed: Invalid credentials for user '{Username}'. Remote IP: {RemoteIp} at {Timestamp}", normalizedUser, remoteIp ?? "unknown", DateTimeOffset.UtcNow); return new TeacherLoginResultDto { Success = false, ErrorMessage = "用户名或密码错误" }; } // 3. Automatic on-the-fly hash upgrade if legacy or rehash needed if (needsRehash) { user.PasswordHash = _passwordHasher.HashPassword(user, dto.Password); _logger.LogInformation("Password hash successfully upgraded to ASP.NET Core PasswordHasher for user '{Username}'.", normalizedUser); } // 4. Update LastLoginAt upon successful authentication user.LastLoginAt = DateTimeOffset.UtcNow; await db.SaveChangesAsync(); _logger.LogInformation("User '{Username}' ({UserId}) successfully authenticated from IP {RemoteIp}.", normalizedUser, user.Id, remoteIp ?? "unknown"); var token = GenerateJwtToken(user); return new TeacherLoginResultDto { Success = true, Token = token, UserId = user.Id, FullName = user.FullName, TenantId = user.TenantId, Role = user.Role }; } public async Task ActivateDeviceAsync(DeviceActivationRequestDto dto) { if (string.IsNullOrWhiteSpace(dto.ActivationCode)) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码不可为空" }; } if (string.IsNullOrWhiteSpace(dto.InstallationId) || !dto.InstallationId.StartsWith("inst_") || dto.InstallationId.Length > 50) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "安装实例标识符 (InstallationId) 无效或格式不正确" }; } var normalizedCode = dto.ActivationCode.Trim().ToUpperInvariant(); var normalizedInstId = dto.InstallationId.Trim(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); using var tx = await db.Database.BeginTransactionAsync(); try { var code = await db.ActivationCodes.FirstOrDefaultAsync(c => c.Code == normalizedCode); if (code == null) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码无效" }; } if (code.IsUsed) { // P0-09 / P1-02 Idempotency Rule: If same installationId, return original device credentials if (!string.IsNullOrEmpty(code.InstallationId) && string.Equals(code.InstallationId, normalizedInstId, StringComparison.OrdinalIgnoreCase)) { var existingDev = await db.Devices.FirstOrDefaultAsync(d => (!string.IsNullOrEmpty(code.UsedByDeviceId) && d.Id == code.UsedByDeviceId) || d.InstallationId == normalizedInstId); var existingCred = await db.DeviceCredentials.FirstOrDefaultAsync(c => (!string.IsNullOrEmpty(code.UsedByDeviceId) && c.DeviceId == code.UsedByDeviceId) || c.InstallationId == normalizedInstId); var existingCls = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == code.TenantId && c.Id == code.ClassroomId); if (existingDev != null && existingCred != null && existingCls != null) { string recoveredToken; try { recoveredToken = _protector.Unprotect(existingCred.EncryptedRecoverableToken); } catch (Exception ex) { _logger.LogError(ex, "Failed to unprotect recoverable token for InstallationId {InstallationId}", normalizedInstId); return new DeviceActivationResultDto { Success = false, ErrorMessage = "解密设备凭据失败,请联系管理员" }; } _logger.LogInformation("Idempotent activation retry for InstallationId {InstallationId}, returning recovered token for Device {DeviceId}", normalizedInstId, existingDev.Id); return new DeviceActivationResultDto { Success = true, DeviceId = existingDev.Id, DeviceToken = recoveredToken, TenantId = existingCls.TenantId, ClassId = existingCls.Id, ClassDisplayName = existingCls.DisplayName }; } } // Different installationId or unable to match installationId -> 409 Conflict return new DeviceActivationResultDto { Success = false, ErrorMessage = "该激活码已被其他设备安装实例使用" }; } if (code.ExpiresAt < DateTimeOffset.UtcNow) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码已过期" }; } var cls = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == code.TenantId && c.Id == code.ClassroomId); if (cls == null) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "绑定的班级不存在" }; } var deviceId = $"dev_{Guid.NewGuid():N}"[..12]; var rawToken = $"dtoken_{Guid.NewGuid():N}"; var tokenHash = HashToken(rawToken); var device = new Device { Id = deviceId, TenantId = code.TenantId, ClassroomId = code.ClassroomId, DeviceTokenHash = tokenHash, InstallationId = normalizedInstId, Hostname = dto.Hostname, IsActive = true, CreatedAt = DateTimeOffset.UtcNow }; var credRecord = new DeviceCredentialRecord { DeviceId = deviceId, InstallationId = normalizedInstId, DeviceTokenHash = tokenHash, EncryptedRecoverableToken = _protector.Protect(rawToken), CreatedAt = DateTimeOffset.UtcNow }; db.Devices.Add(device); db.DeviceCredentials.Add(credRecord); code.IsUsed = true; code.UsedAt = DateTimeOffset.UtcNow; code.UsedByDeviceId = deviceId; code.InstallationId = normalizedInstId; await db.SaveChangesAsync(); await tx.CommitAsync(); _logger.LogInformation("Device {DeviceId} activated successfully for {TenantId} / {ClassId} ({DisplayName}) [InstallationId: {InstallationId}]", deviceId, cls.TenantId, cls.Id, cls.DisplayName, normalizedInstId); return new DeviceActivationResultDto { Success = true, DeviceId = deviceId, DeviceToken = rawToken, TenantId = cls.TenantId, ClassId = cls.Id, ClassDisplayName = cls.DisplayName }; } catch (Exception ex) { await tx.RollbackAsync(); _logger.LogError(ex, "Exception during device activation transaction for code {Code}", normalizedCode); throw; } } public async Task ValidateDeviceAsync(string deviceId, string deviceToken) { if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(deviceToken)) { return null; } var tokenHash = HashToken(deviceToken); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var device = await db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId && d.DeviceTokenHash == tokenHash && d.IsActive); if (device == null) return null; // P0-02 Security Gate: Verify tenant is active var tenant = await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == device.TenantId); if (tenant != null && !tenant.IsActive) { _logger.LogWarning("Rejecting device {DeviceId} connection: Tenant {TenantId} is suspended/inactive.", deviceId, device.TenantId); return null; } return device; } #endregion #region Tenants & Classrooms public async Task GetTenantAsync(string tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId && t.IsActive); } public async Task> GetTenantsOverviewAsync() { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var tenants = await db.Tenants.AsNoTracking().Where(t => t.Id != "global").ToListAsync(); var classrooms = await db.Classrooms.AsNoTracking().ToListAsync(); var devices = await db.Devices.AsNoTracking().ToListAsync(); var liveSnapshots = _liveConnections.Values.ToList(); return tenants.Select(t => { var classCount = classrooms.Count(c => c.TenantId == t.Id); var deviceCount = devices.Count(d => d.TenantId == t.Id); var onlineCount = liveSnapshots.Count(c => c.TenantId == t.Id); return new TenantAdminDto { Id = t.Id, Name = t.Name, ClassroomCount = classCount, DeviceCount = deviceCount, OnlineCount = onlineCount, IsActive = t.IsActive, CreatedAt = t.CreatedAt }; }).ToList(); } public async Task GetClassroomAsync(string tenantId, string classId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Classrooms.AsNoTracking().FirstOrDefaultAsync(c => c.TenantId == tenantId && c.Id == classId); } public async Task> GetClassroomsAsync(string tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Classrooms.AsNoTracking().Where(c => c.TenantId == tenantId).ToListAsync(); } public async Task CreateClassroomAsync(string tenantId, CreateClassroomDto dto) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); if (await db.Classrooms.AnyAsync(c => c.TenantId == tenantId && c.Id == dto.Id)) { return false; } db.Classrooms.Add(new Classroom { Id = dto.Id, TenantId = tenantId, DisplayName = dto.DisplayName, Grade = dto.Grade, RoomNumber = dto.RoomNumber, CreatedAt = DateTimeOffset.UtcNow }); await db.SaveChangesAsync(); return true; } #endregion #region Users public async Task> GetUsersAsync(string tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Users.AsNoTracking().Where(u => u.TenantId == tenantId).ToListAsync(); } public async Task CreateUserAsync(string tenantId, CreateTeacherDto dto) { if (string.IsNullOrWhiteSpace(dto.Password) || dto.Password.Length < 8) { _logger.LogWarning("CreateUser rejected: Password must be at least 8 characters long."); return false; } // P0 Verification Gate: Strictly enforce role whitelist to prevent SuperAdmin privilege escalation if (dto.Role != "Teacher" && dto.Role != "SchoolAdmin") { _logger.LogWarning("CreateUser rejected: Role '{Role}' is not allowed via standard user creation API.", dto.Role); return false; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // P0-02 Security Gate: Verify school tenant is active var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == tenantId); if (tenant == null || !tenant.IsActive) { _logger.LogWarning("CreateUser rejected: School tenant '{TenantId}' does not exist or is suspended.", tenantId); return false; } if (await db.Users.AnyAsync(u => u.Username == dto.Username.Trim())) { return false; } var user = new User { Id = $"usr_{Guid.NewGuid():N}"[..12], TenantId = tenantId, Username = dto.Username.Trim(), FullName = dto.FullName, Role = dto.Role, CreatedAt = DateTimeOffset.UtcNow }; // Strictly use modern PasswordHasher for new user creation user.PasswordHash = _passwordHasher.HashPassword(user, dto.Password); db.Users.Add(user); await db.SaveChangesAsync(); return true; } #endregion #region Devices & Live SignalR Connections public async Task GetAdminMetricsAsync() { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var totalTenants = await db.Tenants.CountAsync(t => t.Id != "global"); var totalClassrooms = await db.Classrooms.CountAsync(); var totalDevices = await db.Devices.CountAsync(); var onlineDevices = _liveConnections.Count; var startOfToday = DateTimeOffset.UtcNow.Date; var todayNotifications = await db.Notifications.CountAsync(n => n.CreatedAt >= startOfToday); return new AdminMetricsDto { TotalTenants = totalTenants, TotalClassrooms = totalClassrooms, TotalDevices = totalDevices, OnlineDevices = onlineDevices, TodayNotifications = todayNotifications, AbnormalDevices = 0 }; } public async Task> GetAllDevicesAsync() { return await BuildDeviceAdminDtosAsync(null); } public async Task> GetTenantDevicesAsync(string tenantId) { return await BuildDeviceAdminDtosAsync(tenantId); } private async Task> BuildDeviceAdminDtosAsync(string? tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.Devices.AsNoTracking(); if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { query = query.Where(d => d.TenantId == tenantId); } var devices = await query.ToListAsync(); var tenants = await db.Tenants.AsNoTracking().ToDictionaryAsync(t => t.Id, t => t.Name); var classrooms = await db.Classrooms.AsNoTracking().ToDictionaryAsync(c => $"{c.TenantId}_{c.Id}", c => c.DisplayName); var liveSnapshot = _liveConnections.ToDictionary(k => k.Key, v => v.Value); return devices.Select(d => { var isOnline = _deviceToConnection.TryGetValue(d.Id, out var connId) && liveSnapshot.ContainsKey(connId); liveSnapshot.TryGetValue(connId ?? string.Empty, out var connInfo); tenants.TryGetValue(d.TenantId, out var tName); classrooms.TryGetValue($"{d.TenantId}_{d.ClassroomId}", out var cName); return new DeviceAdminDto { DeviceId = d.Id, TenantId = d.TenantId, TenantName = tName ?? d.TenantId, ClassroomId = d.ClassroomId, ClassroomName = cName ?? d.ClassroomId, Hostname = d.Hostname, IsOnline = isOnline, LastHeartbeat = isOnline ? connInfo?.LastHeartbeat : d.LastHeartbeatAt, ClientVersion = isOnline ? connInfo?.ClientVersion : null, RemoteIp = isOnline ? connInfo?.RemoteIp : null, ServiceRunning = isOnline, ClientRunning = isOnline }; }).ToList(); } public Task RegisterDeviceConnectionAsync( string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion) { string? replacedConnectionId = null; if (_deviceToConnection.TryGetValue(deviceId, out var existingConnId)) { replacedConnectionId = existingConnId; _liveConnections.TryRemove(existingConnId, out _); _connectionTenantMap.TryRemove(existingConnId, out _); _logger.LogInformation("Replacing previous ConnectionId {OldConnId} with {NewConnId} for Device {DeviceId}", existingConnId, connectionId, deviceId); } _deviceToConnection[deviceId] = connectionId; var liveInfo = new LiveConnectionInfo(connectionId, deviceId, tenantId, classroomId, hostname, remoteIp, clientVersion, DateTimeOffset.UtcNow); _liveConnections[connectionId] = liveInfo; _connectionTenantMap[connectionId] = (tenantId, classroomId, deviceId); _logger.LogInformation("Device {DeviceId} connected via SignalR. ConnectionId={ConnId}, IP={RemoteIp}", deviceId, connectionId, remoteIp); return Task.FromResult(new DeviceConnectionRegistrationResult(connectionId, replacedConnectionId)); } public Task UnregisterDeviceConnectionAsync(string connectionId) { if (_connectionTenantMap.TryRemove(connectionId, out var info)) { _liveConnections.TryRemove(connectionId, out _); if (_deviceToConnection.TryGetValue(info.DeviceId, out var currentConnId) && currentConnId == connectionId) { _deviceToConnection.TryRemove(info.DeviceId, out _); _logger.LogInformation("Unregistered active device connection {ConnId} for Device {DeviceId}", connectionId, info.DeviceId); return Task.FromResult(true); } else { _logger.LogWarning("Ignored stale disconnect for {ConnId} (Device {DeviceId} active connection is {CurrentConnId})", connectionId, info.DeviceId, currentConnId); return Task.FromResult(false); } } return Task.FromResult(false); } public bool IsCurrentDeviceConnection(string deviceId, string connectionId) { return _deviceToConnection.TryGetValue(deviceId, out var currentConnId) && currentConnId == connectionId; } public Task UpdateDeviceHeartbeatAsync(string connectionId) { if (_liveConnections.TryGetValue(connectionId, out var info)) { info.LastHeartbeat = DateTimeOffset.UtcNow; // Throttled DB heartbeat update (every 30s) var now = DateTimeOffset.UtcNow; var lastUpdate = _lastHeartbeatDbUpdate.GetOrAdd(info.DeviceId, DateTimeOffset.MinValue); if (now - lastUpdate >= TimeSpan.FromSeconds(30)) { _lastHeartbeatDbUpdate[info.DeviceId] = now; _ = Task.Run(async () => { try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var dev = await db.Devices.FindAsync(info.DeviceId); if (dev != null) { dev.LastHeartbeatAt = now; await db.SaveChangesAsync(); } } catch { } }); } } return Task.CompletedTask; } public string? GetDeviceConnectionId(string deviceId) { return _deviceToConnection.TryGetValue(deviceId, out var connId) ? connId : null; } #endregion #region Activation Codes public async Task GenerateActivationCodeAsync(string tenantId, string classId, string? actor = null, string? actorRole = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { var tenant = await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId); if (tenant == null || !tenant.IsActive) { throw new InvalidOperationException($"租户不存在或已被禁用: {tenantId}"); } var classroomExists = await db.Classrooms.AsNoTracking().AnyAsync(c => c.TenantId == tenantId && c.Id == classId); if (!classroomExists) { throw new InvalidOperationException($"教室不存在或不属于该租户: {classId}"); } var code = $"{tenantId[..Math.Min(4, tenantId.Length)].ToUpperInvariant()}-{Guid.NewGuid():N}"[..12].ToUpperInvariant(); db.ActivationCodes.Add(new ActivationCode { Code = code, TenantId = tenantId, ClassroomId = classId, ExpiresAt = DateTimeOffset.UtcNow.AddDays(7), IsUsed = false }); if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "GENERATE_ACTIVATION_CODE", TargetType = "ActivationCode", TargetId = code, Details = $"为学校 {tenantId} 班级 {classId} 生成激活码", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return code; } catch { await tx.RollbackAsync(); throw; } } public async Task> GetActivationCodesAsync(string? tenantId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.ActivationCodes.AsNoTracking(); if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { query = query.Where(c => c.TenantId == tenantId); } var codes = await query.OrderByDescending(c => c.ExpiresAt).ToListAsync(); var tenants = await db.Tenants.AsNoTracking().ToDictionaryAsync(t => t.Id, t => t.Name); var classrooms = await db.Classrooms.AsNoTracking().ToDictionaryAsync(c => $"{c.TenantId}_{c.Id}", c => c.DisplayName); return codes.Select(c => { tenants.TryGetValue(c.TenantId, out var tName); classrooms.TryGetValue($"{c.TenantId}_{c.ClassroomId}", out var cName); return new ActivationCodeDto { Code = c.Code, TenantId = c.TenantId, TenantName = tName ?? c.TenantId, ClassroomId = c.ClassroomId, ClassroomName = cName ?? c.ClassroomId, ExpiresAt = c.ExpiresAt, IsUsed = c.IsUsed, UsedAt = c.UsedAt, UsedByDeviceId = c.UsedByDeviceId }; }).ToList(); } #endregion #region Notifications & NotificationReceipts (PostgreSQL) public async Task RecordNotificationAsync(NotificationDto notification, string? senderUserId, string senderName) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var notifEntity = new Notification { Id = notification.Id, TenantId = notification.TenantId, ClassroomId = notification.ClassId, SenderUserId = senderUserId, SenderName = senderName, Message = notification.Message, Title = notification.Title, Priority = notification.Type.ToString(), CreatedAt = notification.CreatedAt, ExpiresAt = notification.ExpiresAt, Voice = notification.Voice, Shake = notification.Shake, DurationSeconds = notification.DurationSeconds }; db.Notifications.Add(notifEntity); // Find active devices for this classroom and create initial Receipt with Status = "Sent" var targetDevices = await db.Devices.AsNoTracking() .Where(d => d.TenantId == notification.TenantId && d.ClassroomId == notification.ClassId && d.IsActive) .ToListAsync(); foreach (var dev in targetDevices) { db.NotificationReceipts.Add(new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = notification.Id, DeviceId = dev.Id, Status = "Sent", UpdatedAt = DateTimeOffset.UtcNow }); } await db.SaveChangesAsync(); } public async Task RecordAckAsync(string messageId, string authenticatedDeviceId, AckReceiptDto ack) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var receipt = await db.NotificationReceipts .FirstOrDefaultAsync(r => r.NotificationId == messageId && r.DeviceId == authenticatedDeviceId); if (receipt == null) { // If receipt didn't exist (e.g. device activated after notification or direct delivery), create it receipt = new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = messageId, DeviceId = authenticatedDeviceId, Status = "Sent", UpdatedAt = DateTimeOffset.UtcNow }; db.NotificationReceipts.Add(receipt); } // State Machine Protection: // Rank: Sent (0) -> DeviceReceived (1) -> Displayed (2) -> Acknowledged (3) // Terminal states: Timeout, Failed. // Rule: Never regress from Acknowledged to any lower rank or failure. if (receipt.Status == "Acknowledged") { _logger.LogInformation("Receipt {ReceiptId} (Dev {DevId}) is already Acknowledged. Ignoring subsequent {Status}.", receipt.Id, authenticatedDeviceId, ack.Status); return; } switch (ack.Status) { case AckStatus.Delivered: // Client WPF displayed window on screen receipt.DeviceReceivedAt ??= ack.Timestamp; receipt.DisplayedAt ??= ack.Timestamp; if (receipt.Status != "Displayed" && receipt.Status != "Acknowledged") { receipt.Status = "Displayed"; } break; case AckStatus.Acknowledged: receipt.DeviceReceivedAt ??= ack.Timestamp; receipt.DisplayedAt ??= ack.Timestamp; receipt.AcknowledgedAt = ack.Timestamp; receipt.Status = "Acknowledged"; break; case AckStatus.Timeout: if (receipt.Status != "Acknowledged") { receipt.Status = "Timeout"; } break; case AckStatus.Failed: if (receipt.Status != "Acknowledged") { receipt.Status = "Failed"; receipt.FailedAt = ack.Timestamp; receipt.FailureReason = ack.Remark; } break; case AckStatus.Sent: default: break; } receipt.UpdatedAt = DateTimeOffset.UtcNow; await db.SaveChangesAsync(); } public async Task ValidateNotificationTargetAsync(string messageId, string tenantId, string classroomId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); return await db.Notifications.AsNoTracking() .AnyAsync(n => n.Id == messageId && n.TenantId == tenantId && n.ClassroomId == classroomId); } public async Task> GetNotificationsAsync(string? tenantId, string? classId, int limit = 50) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.Notifications.AsNoTracking().Include(n => n.Receipts).AsQueryable(); if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { query = query.Where(n => n.TenantId == tenantId); } if (!string.IsNullOrEmpty(classId)) { query = query.Where(n => n.ClassroomId == classId); } var notifications = await query.OrderByDescending(n => n.CreatedAt).Take(limit).ToListAsync(); var classrooms = await db.Classrooms.AsNoTracking().ToDictionaryAsync(c => $"{c.TenantId}_{c.Id}", c => c.DisplayName); return notifications.Select(n => { classrooms.TryGetValue($"{n.TenantId}_{n.ClassroomId}", out var cName); // Compute aggregate status across all device receipts string status = "Sent"; DateTimeOffset? confirmedAt = null; if (n.Receipts.Any(r => r.Status == "Acknowledged")) { status = "Acknowledged"; confirmedAt = n.Receipts.FirstOrDefault(r => r.Status == "Acknowledged")?.AcknowledgedAt; } else if (n.Receipts.Any(r => r.Status == "Displayed" || r.Status == "DeviceReceived")) { status = "Delivered"; } else if (n.Receipts.Any(r => r.Status == "Failed")) { status = "Failed"; } else if (n.Receipts.Any(r => r.Status == "Timeout")) { status = "Timeout"; } else if ((n.Receipts.Any() && n.Receipts.All(r => r.Status == "Expired")) || (n.ExpiresAt.HasValue && n.ExpiresAt.Value <= DateTimeOffset.UtcNow)) { status = "Expired"; } return new NotificationRecordDto { Id = n.Id, TenantId = n.TenantId, ClassId = n.ClassroomId, ClassName = cName ?? n.ClassroomId, SenderName = n.SenderName, Message = n.Message, Priority = n.Priority, CreatedAt = n.CreatedAt, Status = status, ConfirmedAt = confirmedAt, ExpiresAt = n.ExpiresAt }; }).ToList(); } public async Task> GetPendingNotificationsForDeviceAsync(string deviceId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; // Query pending receipts for this authenticated device var pendingReceipts = await db.NotificationReceipts .Include(r => r.Notification) .Where(r => r.DeviceId == deviceId && r.Status == "Sent") .ToListAsync(); var validDtos = new List(); bool hasStateChanges = false; foreach (var receipt in pendingReceipts) { if (receipt.Notification == null) continue; // Check if notification has expired (or is legacy Batch 8 record where ExpiresAt is NULL) if (!receipt.Notification.ExpiresAt.HasValue || receipt.Notification.ExpiresAt.Value <= now) { receipt.Status = "Expired"; receipt.UpdatedAt = now; hasStateChanges = true; _logger.LogInformation("Receipt {ReceiptId} for Device {DeviceId} (Msg {MsgId}) marked Expired (ExpiresAt: {ExpiresAt}).", receipt.Id, deviceId, receipt.NotificationId, receipt.Notification.ExpiresAt); } else { var n = receipt.Notification; validDtos.Add(new NotificationDto { Id = n.Id, TenantId = n.TenantId, ClassId = n.ClassroomId, Title = n.Title, Message = n.Message, Type = Enum.TryParse(n.Priority, out var p) ? p : ClassNotify.Shared.Enums.NotificationType.Call, Voice = n.Voice, Shake = n.Shake, DurationSeconds = n.DurationSeconds, CreatedAt = n.CreatedAt, ExpiresAt = n.ExpiresAt }); } } if (hasStateChanges) { await db.SaveChangesAsync(); } return validDtos.OrderBy(d => d.CreatedAt).ToList(); } #endregion #region Device Commands (P1 Batch 10) public async Task CreateDeviceCommandAsync(string? callerTenantId, string deviceId, string commandType, string? parameters, string createdBy) { if (string.IsNullOrWhiteSpace(deviceId)) { throw new ArgumentException("DeviceId cannot be empty", nameof(deviceId)); } // Whitelist check if (!DeviceCommandTypes.IsSupported(commandType)) { throw new ArgumentException($"Unsupported command type '{commandType}'. Whitelist: {string.Join(", ", DeviceCommandTypes.AllSupported)}"); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var device = await db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) { throw new InvalidOperationException($"Target device '{deviceId}' not found"); } // Multi-tenant isolation: non-superadmin caller must match device tenant if (!string.IsNullOrEmpty(callerTenantId) && !string.Equals(callerTenantId, device.TenantId, StringComparison.OrdinalIgnoreCase)) { throw new UnauthorizedAccessException($"Device '{deviceId}' does not belong to tenant '{callerTenantId}'"); } // P0-02 Security Gate: Verify tenant is active var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == device.TenantId); if (tenant != null && !tenant.IsActive) { throw new InvalidOperationException($"设备所属学校 [{tenant.Name}] 已停用冻结,无法下发远程运维指令"); } var ttl = DeviceCommandTypes.GetDefaultTtl(commandType); var now = DateTimeOffset.UtcNow; var commandId = $"cmd_{Guid.NewGuid():N}"; var entity = new DeviceCommand { Id = commandId, TenantId = device.TenantId, DeviceId = device.Id, CommandType = commandType, Parameters = parameters, CreatedBy = createdBy, CreatedAt = now, ExpiresAt = now.Add(ttl), Status = DeviceCommandStatuses.Pending }; db.DeviceCommands.Add(entity); await db.SaveChangesAsync(); _logger.LogInformation("Created remote command {CommandId} ({CommandType}) for Device {DeviceId} (Tenant {TenantId}, TTL {TtlMinutes}m) by {CreatedBy}", commandId, commandType, device.Id, device.TenantId, ttl.TotalMinutes, createdBy); return new DeviceCommandDto { CommandId = entity.Id, TenantId = entity.TenantId, DeviceId = entity.DeviceId, CommandType = entity.CommandType, Parameters = entity.Parameters, CreatedBy = entity.CreatedBy, CreatedAt = entity.CreatedAt, ExpiresAt = entity.ExpiresAt, Status = entity.Status }; } public async Task MarkCommandDispatchedAsync(string commandId) { if (string.IsNullOrWhiteSpace(commandId)) return false; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var cmd = await db.DeviceCommands.FirstOrDefaultAsync(c => c.Id == commandId); if (cmd == null) return false; if (cmd.Status == DeviceCommandStatuses.Pending) { cmd.Status = DeviceCommandStatuses.Dispatched; await db.SaveChangesAsync(); return true; } return false; } public async Task RecordCommandResultAsync(DeviceCommandResultDto result, string callerDeviceId, string? callerTenantId) { if (result == null || string.IsNullOrWhiteSpace(result.CommandId)) { _logger.LogWarning("RecordCommandResultAsync called with empty CommandId"); return null; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var cmd = await db.DeviceCommands.FirstOrDefaultAsync(c => c.Id == result.CommandId); if (cmd == null) { _logger.LogWarning("Remote command {CommandId} not found when recording execution result", result.CommandId); return null; } // Security assertion: device and tenant isolation if (!string.Equals(cmd.DeviceId, callerDeviceId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Rejecting command result: DeviceId mismatch. Target: {TargetDevice}, Caller: {CallerDevice} (Command {CommandId})", cmd.DeviceId, callerDeviceId, result.CommandId); return null; } if (!string.IsNullOrEmpty(callerTenantId) && !string.Equals(cmd.TenantId, callerTenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Rejecting command result: TenantId mismatch. Target: {TargetTenant}, Caller: {CallerTenant} (Command {CommandId})", cmd.TenantId, callerTenantId, result.CommandId); return null; } // Idempotency: if already reached terminal state, do not overwrite final outcome if (DeviceCommandStatuses.IsTerminal(cmd.Status)) { _logger.LogInformation("Command {CommandId} already completed with terminal status '{Status}'. Ignoring duplicate result report.", cmd.Id, cmd.Status); return new DeviceCommandResultDto { CommandId = cmd.Id, DeviceId = cmd.DeviceId, Status = cmd.Status, ResultCode = cmd.ResultCode ?? 0, ResultMessage = cmd.ResultMessage, ExecutionDurationMs = cmd.DurationMs ?? 0, Timestamp = cmd.CompletedAt ?? DateTimeOffset.UtcNow }; } var now = DateTimeOffset.UtcNow; cmd.Status = result.Status; cmd.ResultCode = result.ResultCode; cmd.DurationMs = result.ExecutionDurationMs; cmd.ResultMessage = result.ResultMessage != null && result.ResultMessage.Length > 1000 ? result.ResultMessage[..1000] : result.ResultMessage; cmd.StartedAt ??= result.Timestamp; cmd.CompletedAt = now; await db.SaveChangesAsync(); _logger.LogInformation("Recorded execution result for Command {CommandId} (Device {DeviceId}): Status={Status}, ResultCode={ResultCode}, Duration={Duration}ms", cmd.Id, cmd.DeviceId, cmd.Status, cmd.ResultCode, cmd.DurationMs); return new DeviceCommandResultDto { CommandId = cmd.Id, DeviceId = cmd.DeviceId, Status = cmd.Status, ResultCode = cmd.ResultCode ?? 0, ResultMessage = cmd.ResultMessage, ExecutionDurationMs = cmd.DurationMs ?? result.ExecutionDurationMs, Timestamp = cmd.CompletedAt ?? now }; } public async Task GetDeviceCommandAsync(string commandId, string? callerTenantId = null) { if (string.IsNullOrWhiteSpace(commandId)) return null; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var cmd = await db.DeviceCommands.FirstOrDefaultAsync(c => c.Id == commandId); if (cmd == null) return null; if (!string.IsNullOrEmpty(callerTenantId) && !string.Equals(cmd.TenantId, callerTenantId, StringComparison.OrdinalIgnoreCase)) { return null; } // Active TTL evaluation: if Pending/Dispatched and past ExpiresAt, transition via Normalizer if (DeviceCommandNormalizer.NormalizeExpiredOrTimedOut(cmd, DateTimeOffset.UtcNow)) { await db.SaveChangesAsync(); } return new DeviceCommandDto { CommandId = cmd.Id, TenantId = cmd.TenantId, DeviceId = cmd.DeviceId, CommandType = cmd.CommandType, Parameters = cmd.Parameters, CreatedBy = cmd.CreatedBy, CreatedAt = cmd.CreatedAt, ExpiresAt = cmd.ExpiresAt, Status = cmd.Status, StartedAt = cmd.StartedAt, CompletedAt = cmd.CompletedAt, DurationMs = cmd.DurationMs, ResultCode = cmd.ResultCode, ResultMessage = cmd.ResultMessage }; } public async Task> GetPendingCommandsForDeviceAsync(string deviceId) { if (string.IsNullOrWhiteSpace(deviceId)) return new List(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var list = await db.DeviceCommands .Where(c => c.DeviceId == deviceId && (c.Status == DeviceCommandStatuses.Pending || c.Status == DeviceCommandStatuses.Dispatched)) .OrderBy(c => c.CreatedAt) .ToListAsync(); var now = DateTimeOffset.UtcNow; var valid = new List(); bool hasExpiredUpdates = false; foreach (var cmd in list) { if (DeviceCommandNormalizer.NormalizeExpiredOrTimedOut(cmd, now)) { hasExpiredUpdates = true; _logger.LogInformation("Command {CommandId} for Device {DeviceId} marked {Status} (ExpiresAt: {ExpiresAt}).", cmd.Id, deviceId, cmd.Status, cmd.ExpiresAt); } else { valid.Add(new DeviceCommandDto { CommandId = cmd.Id, TenantId = cmd.TenantId, DeviceId = cmd.DeviceId, CommandType = cmd.CommandType, Parameters = cmd.Parameters, CreatedBy = cmd.CreatedBy, CreatedAt = cmd.CreatedAt, ExpiresAt = cmd.ExpiresAt, Status = cmd.Status, StartedAt = cmd.StartedAt, CompletedAt = cmd.CompletedAt, DurationMs = cmd.DurationMs, ResultCode = cmd.ResultCode, ResultMessage = cmd.ResultMessage }); } } if (hasExpiredUpdates) { await db.SaveChangesAsync(); } return valid; } public async Task> GetDeviceCommandHistoryAsync(string? tenantId, string? deviceId, string? status, int limit = 50) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.DeviceCommands.AsQueryable(); if (!string.IsNullOrEmpty(tenantId)) { query = query.Where(c => c.TenantId == tenantId); } if (!string.IsNullOrEmpty(deviceId)) { query = query.Where(c => c.DeviceId == deviceId); } if (!string.IsNullOrEmpty(status)) { query = query.Where(c => c.Status == status); } var commands = await query .OrderByDescending(c => c.CreatedAt) .Take(Math.Min(limit, 200)) .ToListAsync(); var now = DateTimeOffset.UtcNow; bool hasExpiredUpdates = false; var result = new List(); foreach (var cmd in commands) { if (DeviceCommandNormalizer.NormalizeExpiredOrTimedOut(cmd, now)) { hasExpiredUpdates = true; } result.Add(new DeviceCommandDto { CommandId = cmd.Id, TenantId = cmd.TenantId, DeviceId = cmd.DeviceId, CommandType = cmd.CommandType, Parameters = cmd.Parameters, CreatedBy = cmd.CreatedBy, CreatedAt = cmd.CreatedAt, ExpiresAt = cmd.ExpiresAt, Status = cmd.Status, StartedAt = cmd.StartedAt, CompletedAt = cmd.CompletedAt, DurationMs = cmd.DurationMs, ResultCode = cmd.ResultCode, ResultMessage = cmd.ResultMessage }); } if (hasExpiredUpdates) { await db.SaveChangesAsync(); } return result; } #endregion #region Helpers public string GenerateJwtToken(User user) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(_jwtOptions.SigningKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Name, user.FullName), new Claim(ClaimTypes.Role, user.Role), new Claim("tenant_id", user.TenantId), new Claim("token_version", user.TokenVersion.ToString()) }), Issuer = _jwtOptions.Issuer, Audience = _jwtOptions.Audience, Expires = DateTime.UtcNow.AddDays(_jwtOptions.LifetimeDays > 0 ? _jwtOptions.LifetimeDays : 14), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } /// /// Legacy SHA256 password verifier for migration of existing accounts. /// STRICTLY PROHIBITED FOR GENERATING NEW PASSWORDS. /// public static bool VerifyLegacyPassword(string plaintextPassword, string legacyHash) { if (string.IsNullOrEmpty(plaintextPassword) || string.IsNullOrEmpty(legacyHash)) { return false; } using var sha = SHA256.Create(); var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(plaintextPassword + "_classnotify_salt")); var computed = Convert.ToBase64String(bytes); return CryptographicOperations.FixedTimeEquals( Encoding.UTF8.GetBytes(computed), Encoding.UTF8.GetBytes(legacyHash)); } private static string HashToken(string token) { using var sha = SHA256.Create(); var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(token)); return Convert.ToBase64String(bytes); } #region SuperAdmin Control Plane Implementations public async Task CreateTenantAsync(string id, string name, string? actor = null, string? actorRole = null, string? ip = null) { if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(name)) throw new ArgumentException("学校ID与名称不可为空"); var cleanId = id.Trim().ToLowerInvariant(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { if (await db.Tenants.AnyAsync(t => t.Id == cleanId)) throw new InvalidOperationException($"租户ID '{cleanId}' 已存在"); var tenant = new Tenant { Id = cleanId, Name = name.Trim(), IsActive = true, CreatedAt = DateTimeOffset.UtcNow }; db.Tenants.Add(tenant); if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "CREATE_TENANT", TargetType = "Tenant", TargetId = tenant.Id, Details = $"创建学校: {tenant.Name} ({tenant.Id})", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return new TenantAdminDto { Id = tenant.Id, Name = tenant.Name, ClassroomCount = 0, DeviceCount = 0, OnlineCount = 0, IsActive = tenant.IsActive, CreatedAt = tenant.CreatedAt }; } catch { await tx.RollbackAsync(); throw; } } public async Task UpdateTenantAsync(string id, string name, bool isActive, string? actor = null, string? actorRole = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == id); if (tenant == null) return null; if (!string.IsNullOrWhiteSpace(name)) tenant.Name = name.Trim(); tenant.IsActive = isActive; if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "UPDATE_TENANT", TargetType = "Tenant", TargetId = tenant.Id, Details = $"更新学校: {tenant.Name}, 启用状态: {tenant.IsActive}", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); var classroomCount = await db.Classrooms.CountAsync(c => c.TenantId == id); var deviceCount = await db.Devices.CountAsync(d => d.TenantId == id); var onlineCount = _liveConnections.Values.Count(c => c.TenantId == id); return new TenantAdminDto { Id = tenant.Id, Name = tenant.Name, ClassroomCount = classroomCount, DeviceCount = deviceCount, OnlineCount = onlineCount, IsActive = tenant.IsActive, CreatedAt = tenant.CreatedAt }; } catch { await tx.RollbackAsync(); throw; } } public async Task> GetAllUsersAdminAsync(string? tenantId, string? role) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.Users.Include(u => u.Tenant).AsQueryable(); if (!string.IsNullOrWhiteSpace(tenantId)) query = query.Where(u => u.TenantId == tenantId); if (!string.IsNullOrWhiteSpace(role)) query = query.Where(u => u.Role == role); var list = await query.OrderByDescending(u => u.CreatedAt).ToListAsync(); return list.Select(u => new UserAdminDto { Id = u.Id, TenantId = u.TenantId, TenantName = u.Tenant?.Name ?? u.TenantId, Username = u.Username, FullName = u.FullName, Role = u.Role, IsLocked = u.IsLocked, CreatedAt = u.CreatedAt, LastLoginAt = u.LastLoginAt }).ToList(); } public async Task CreateUserAdminAsync(CreateUserAdminRequest req, string? actor = null, string? actorRole = null, string? ip = null) { if (string.IsNullOrWhiteSpace(req.TenantId) || string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password) || string.IsNullOrWhiteSpace(req.FullName)) throw new ArgumentException("所有必填字段均不可为空"); // P1 Gate: Minimum password length 8 characters if (req.Password.Trim().Length < 8) throw new ArgumentException("密码长度不能少于 8 位"); var targetRole = req.Role?.Trim(); if (targetRole != "SchoolAdmin" && targetRole != "Teacher") throw new ArgumentException("角色必须为 'SchoolAdmin' 或 'Teacher'"); var cleanUser = req.Username.Trim(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { if (await db.Users.AnyAsync(u => u.Username == cleanUser)) throw new InvalidOperationException($"用户名 '{cleanUser}' 已被占用"); var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == req.TenantId); if (tenant == null) throw new InvalidOperationException($"租户 '{req.TenantId}' 不存在"); // P0-02 Security Gate: Verify tenant is active if (!tenant.IsActive) throw new InvalidOperationException($"学校租户 '{tenant.Name}' 处于停用冻结状态,无法开通新账号"); var user = new User { Id = $"usr_{Guid.NewGuid():N}".Substring(0, 12), TenantId = req.TenantId, Username = cleanUser, FullName = req.FullName.Trim(), Role = targetRole, IsLocked = false, TokenVersion = 1, CreatedAt = DateTimeOffset.UtcNow }; user.PasswordHash = _passwordHasher.HashPassword(user, req.Password); db.Users.Add(user); if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "CREATE_USER", TargetType = "User", TargetId = user.Username, Details = $"创建用户: {user.FullName} ({user.Role}),学校: {tenant.Name}", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return new UserAdminDto { Id = user.Id, TenantId = user.TenantId, TenantName = tenant.Name, Username = user.Username, FullName = user.FullName, Role = user.Role, IsLocked = user.IsLocked, CreatedAt = user.CreatedAt }; } catch { await tx.RollbackAsync(); throw; } } public async Task ResetPasswordAsync(string userId, string newPassword, string? actor = null, string? actorRole = null, string? ip = null) { if (string.IsNullOrWhiteSpace(newPassword) || newPassword.Trim().Length < 8) throw new ArgumentException("新密码长度不能少于 8 位"); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) return false; user.PasswordHash = _passwordHasher.HashPassword(user, newPassword); user.TokenVersion++; // Permanent invalidation of existing JWTs if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "RESET_PASSWORD", TargetType = "User", TargetId = userId, Details = "管理员重置用户登录密码", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return true; } catch { await tx.RollbackAsync(); throw; } } public async Task SetUserLockAsync(string userId, bool isLocked, string? actor = null, string? actorRole = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) return false; user.IsLocked = isLocked; user.TokenVersion++; // Invalidate existing tokens if (!string.IsNullOrEmpty(actor)) { var action = isLocked ? "LOCK_USER" : "UNLOCK_USER"; var detail = isLocked ? "锁定账号 (禁止登录)" : "解锁账号 (恢复登录)"; db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = action, TargetType = "User", TargetId = userId, Details = detail, IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return true; } catch { await tx.RollbackAsync(); throw; } } public async Task DeleteUserAsync(string userId, string? actor = null, string? actorRole = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) return false; if (user.Role == "SuperAdmin") throw new InvalidOperationException("无法删除超级管理员"); db.Users.Remove(user); if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "DELETE_USER", TargetType = "User", TargetId = userId, Details = "删除用户", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return true; } catch { await tx.RollbackAsync(); throw; } } public async Task UpdateDeviceAsync(string deviceId, string? hostname, string? classroomId, string? actor = null, string? actorRole = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { var device = await db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) return false; if (!string.IsNullOrWhiteSpace(hostname)) device.Hostname = hostname.Trim(); if (!string.IsNullOrWhiteSpace(classroomId)) { var targetClass = classroomId.Trim(); var classExists = await db.Classrooms.AsNoTracking().AnyAsync(c => c.TenantId == device.TenantId && c.Id == targetClass); if (!classExists) { throw new InvalidOperationException($"目标班级不存在或不属于设备所在的学校租户 ({device.TenantId}): {targetClass}"); } device.ClassroomId = targetClass; } if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "UPDATE_DEVICE", TargetType = "Device", TargetId = deviceId, Details = $"更新设备元数据: 主机名={hostname}, 绑定班级={classroomId}", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return true; } catch { await tx.RollbackAsync(); throw; } } public async Task DecommissionDeviceAsync(string deviceId, string? actor = null, string? actorRole = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { var device = await db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) return false; device.IsActive = false; device.LastHeartbeatAt = null; if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "DECOMMISSION_DEVICE", TargetType = "Device", TargetId = deviceId, Details = "清退并注销指定设备", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); if (_deviceToConnection.TryRemove(deviceId, out var connId)) { _liveConnections.TryRemove(connId, out _); _connectionTenantMap.TryRemove(connId, out _); } return true; } catch { await tx.RollbackAsync(); throw; } } public async Task DeleteActivationCodeAsync(string code, string? actor = null, string? actorRole = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await using var tx = await db.Database.BeginTransactionAsync(); try { var act = await db.ActivationCodes.FirstOrDefaultAsync(a => a.Code == code); if (act == null) return false; db.ActivationCodes.Remove(act); if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "DELETE_ACTIVATION_CODE", TargetType = "ActivationCode", TargetId = code, Details = "作废/删除激活码", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return true; } catch { await tx.RollbackAsync(); throw; } } public async Task GetSystemHealthAsync() { bool dbOk = false; double latencyMs = 0; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); try { var sw = System.Diagnostics.Stopwatch.StartNew(); dbOk = await db.Database.CanConnectAsync(); sw.Stop(); latencyMs = sw.Elapsed.TotalMilliseconds; } catch {} var process = System.Diagnostics.Process.GetCurrentProcess(); var uptime = DateTime.UtcNow - process.StartTime.ToUniversalTime(); return new SystemHealthDto { Status = dbOk ? "Healthy" : "Degraded", DatabaseConnected = dbOk, DatabaseLatencyMs = Math.Round(latencyMs, 2), ActiveSignalRConnections = _liveConnections.Count, OnlineDevices = _liveConnections.Count, ServerTime = DateTimeOffset.UtcNow.ToString("o"), Uptime = $"{(int)uptime.TotalHours}h {uptime.Minutes}m {uptime.Seconds}s", MemoryUsedBytes = process.WorkingSet64 }; } public async Task LogAdminAuditAsync(string actorUsername, string actorRole, string action, string targetType, string targetId, string? details, string? ip) { try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var evt = new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}".Substring(0, 16), OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actorUsername, ActorRole = actorRole, Action = action, TargetType = targetType, TargetId = targetId, Details = details, IpAddress = ip }; db.AdminAuditEvents.Add(evt); await db.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError(ex, "FATAL SECURITY AUDIT FAILURE: Failed to persist AdminAuditEvent for action {Action} (fail-closed engaged)", action); throw; } } public async Task> GetAdminAuditLogsAsync(int limit = 100) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var list = await db.AdminAuditEvents .OrderByDescending(a => a.OccurredAt) .Take(limit) .ToListAsync(); return list.Select(a => new AdminAuditLogDto { Id = a.Id, OccurredAt = a.OccurredAt, ActorUsername = a.ActorUsername, ActorRole = a.ActorRole, Action = a.Action, TargetType = a.TargetType, TargetId = a.TargetId, Details = a.Details, IpAddress = a.IpAddress }).ToList(); } #endregion #endregion } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Services/ISecurityService.cs SIZE: 4865 chars ===================================================================== */ using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; namespace ClassNotify.Server.Services; public sealed record DeviceConnectionRegistrationResult( string CurrentConnectionId, string? ReplacedConnectionId); public interface ISecurityService { // Auth & Identity Task LoginTeacherAsync(TeacherLoginDto dto, string? remoteIp = null); Task ActivateDeviceAsync(DeviceActivationRequestDto dto); Task ValidateDeviceAsync(string deviceId, string deviceToken); // Tenant & Classrooms Task GetClassroomAsync(string tenantId, string classId); Task> GetClassroomsAsync(string tenantId); Task CreateClassroomAsync(string tenantId, CreateClassroomDto dto); Task GetTenantAsync(string tenantId); Task> GetTenantsOverviewAsync(); // Users Task> GetUsersAsync(string tenantId); Task CreateUserAsync(string tenantId, CreateTeacherDto dto); // Devices & Metrics Task GetAdminMetricsAsync(); Task> GetAllDevicesAsync(); Task> GetTenantDevicesAsync(string tenantId); Task RegisterDeviceConnectionAsync(string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion); Task UnregisterDeviceConnectionAsync(string connectionId); bool IsCurrentDeviceConnection(string deviceId, string connectionId); Task UpdateDeviceHeartbeatAsync(string connectionId); string? GetDeviceConnectionId(string deviceId); // Activation Codes Task GenerateActivationCodeAsync(string tenantId, string classId, string? actor = null, string? actorRole = null, string? ip = null); Task> GetActivationCodesAsync(string? tenantId); // Notifications & ACKs (PostgreSQL & NotificationReceipt per-device isolation) Task RecordNotificationAsync(NotificationDto notification, string? senderUserId, string senderName); Task RecordAckAsync(string messageId, string authenticatedDeviceId, AckReceiptDto ack); Task ValidateNotificationTargetAsync(string messageId, string tenantId, string classroomId); Task> GetNotificationsAsync(string? tenantId, string? classId, int limit = 50); Task> GetPendingNotificationsForDeviceAsync(string deviceId); // Device Commands (P1 Batch 10) Task CreateDeviceCommandAsync(string? callerTenantId, string deviceId, string commandType, string? parameters, string createdBy); Task MarkCommandDispatchedAsync(string commandId); Task RecordCommandResultAsync(DeviceCommandResultDto result, string callerDeviceId, string? callerTenantId); Task GetDeviceCommandAsync(string commandId, string? callerTenantId = null); Task> GetPendingCommandsForDeviceAsync(string deviceId); Task> GetDeviceCommandHistoryAsync(string? tenantId, string? deviceId, string? status, int limit = 50); // SuperAdmin Control Plane Extensions Task CreateTenantAsync(string id, string name, string? actor = null, string? actorRole = null, string? ip = null); Task UpdateTenantAsync(string id, string name, bool isActive, string? actor = null, string? actorRole = null, string? ip = null); Task> GetAllUsersAdminAsync(string? tenantId, string? role); Task CreateUserAdminAsync(CreateUserAdminRequest req, string? actor = null, string? actorRole = null, string? ip = null); Task ResetPasswordAsync(string userId, string newPassword, string? actor = null, string? actorRole = null, string? ip = null); Task SetUserLockAsync(string userId, bool isLocked, string? actor = null, string? actorRole = null, string? ip = null); Task DeleteUserAsync(string userId, string? actor = null, string? actorRole = null, string? ip = null); Task UpdateDeviceAsync(string deviceId, string? hostname, string? classroomId, string? actor = null, string? actorRole = null, string? ip = null); Task DecommissionDeviceAsync(string deviceId, string? actor = null, string? actorRole = null, string? ip = null); Task DeleteActivationCodeAsync(string code, string? actor = null, string? actorRole = null, string? ip = null); Task GetSystemHealthAsync(); Task LogAdminAuditAsync(string actorUsername, string actorRole, string action, string targetType, string targetId, string? details, string? ip); Task> GetAdminAuditLogsAsync(int limit = 100); } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Domain/Entities/Entities.cs SIZE: 10033 chars ===================================================================== */ using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ClassNotify.Server.Domain.Entities; /// /// 学校/机构租户实体 /// public class Tenant { [Key] public string Id { get; set; } = string.Empty; // e.g. "t_beijing_no4" public string Name { get; set; } = string.Empty; // e.g. "北京四中" public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public ICollection Classrooms { get; set; } = new List(); public ICollection Users { get; set; } = new List(); public ICollection Devices { get; set; } = new List(); public ICollection ActivationCodes { get; set; } = new List(); public ICollection Notifications { get; set; } = new List(); } /// /// 教师/管理员用户实体 /// public class User { [Key] public string Id { get; set; } = string.Empty; // e.g. "usr_1001" public string TenantId { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string PasswordHash { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; [NotMapped] public string DisplayName => FullName; public string Role { get; set; } = "Teacher"; // Teacher, SchoolAdmin, SuperAdmin public bool IsLocked { get; set; } = false; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? LastLoginAt { get; set; } public int TokenVersion { get; set; } = 1; public Tenant? Tenant { get; set; } } /// /// 班级实体 /// public class Classroom { public string Id { get; set; } = string.Empty; // e.g. "cls_801" public string TenantId { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty; // e.g. "八年级(1)班" public string? Grade { get; set; } public string? RoomNumber { get; set; } public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public Tenant? Tenant { get; set; } public ICollection Devices { get; set; } = new List(); } /// /// 教室硬件多媒体设备实体 /// public class Device { [Key] public string Id { get; set; } = string.Empty; // e.g. "dev_52f0" public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string DeviceTokenHash { get; set; } = string.Empty; public string? RawDeviceToken { get; set; } // Kept only for legacy migration public string? InstallationId { get; set; } // Unique installation instance identifier public string? Hostname { get; set; } public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? LastHeartbeatAt { get; set; } public Tenant? Tenant { get; set; } public Classroom? Classroom { get; set; } public ICollection Receipts { get; set; } = new List(); } /// /// 设备加密凭据恢复记录 (仅用于 InstallationId 幂等恢复,不直接在业务代码暴露明文) /// public class DeviceCredentialRecord { [Key] public string DeviceId { get; set; } = string.Empty; public string InstallationId { get; set; } = string.Empty; public string DeviceTokenHash { get; set; } = string.Empty; public string EncryptedRecoverableToken { get; set; } = string.Empty; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? RotatedAt { get; set; } } /// /// 一次性设备激活码实体 /// public class ActivationCode { [Key] public string Code { get; set; } = string.Empty; // e.g. "H8K4-29DP" public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public DateTimeOffset ExpiresAt { get; set; } = DateTimeOffset.UtcNow.AddDays(7); public bool IsUsed { get; set; } public DateTimeOffset? UsedAt { get; set; } public string? UsedByDeviceId { get; set; } public string? InstallationId { get; set; } // Bound to first installation instance public Tenant? Tenant { get; set; } } /// /// 教师/系统下发通知主表 (不存储单一设备 ACK 状态) /// public class Notification { [Key] public string Id { get; set; } = string.Empty; // e.g. "msg_1789944446934_0471" public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string? SenderUserId { get; set; } public string SenderName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public string Title { get; set; } = "🔔 老师呼叫"; public string Priority { get; set; } = "Normal"; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? ExpiresAt { get; set; } public bool Voice { get; set; } = true; public bool Shake { get; set; } = true; public int DurationSeconds { get; set; } = 15; public Tenant? Tenant { get; set; } public ICollection Receipts { get; set; } = new List(); } /// /// 设备通知回执明细表 (按设备独立记录状态与时间线,防止单点覆盖) /// public class NotificationReceipt { [Key] public string Id { get; set; } = string.Empty; // e.g. "rcpt_..." public string NotificationId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; /// /// 回执阶段状态: Sent, DeviceReceived, Displayed, Acknowledged, Failed, Timeout /// public string Status { get; set; } = "Sent"; public DateTimeOffset? DeviceReceivedAt { get; set; } public DateTimeOffset? DisplayedAt { get; set; } public DateTimeOffset? AcknowledgedAt { get; set; } public DateTimeOffset? FailedAt { get; set; } public string? FailureReason { get; set; } public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; public Notification? Notification { get; set; } public Device? Device { get; set; } } /// /// JSON 数据一次性迁移记录标记 /// public class MigrationMarker { [Key] public string Id { get; set; } = string.Empty; // e.g. "JsonMigration_v1" public DateTimeOffset MigratedAt { get; set; } = DateTimeOffset.UtcNow; public string? Details { get; set; } } /// /// 教室终端受控远程运维命令实体 /// 全链路统一 CommandId (cmd_xxxxx),从创建到最终上报不可篡改 /// public class DeviceCommand { [Key] public string Id { get; set; } = string.Empty; // e.g. "cmd_..." [Required] public string TenantId { get; set; } = string.Empty; [Required] public string DeviceId { get; set; } = string.Empty; [Required] public string CommandType { get; set; } = string.Empty; // "SelfCheck", "RestartClient", "Reconnect", "RefreshConfig" public string? Parameters { get; set; } [Required] public string CreatedBy { get; set; } = string.Empty; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset ExpiresAt { get; set; } public DateTimeOffset? StartedAt { get; set; } public DateTimeOffset? CompletedAt { get; set; } [Required] public string Status { get; set; } = "Pending"; // "Pending", "Dispatched", "Succeeded", "Failed", "TimedOut", "Expired" public int? ResultCode { get; set; } public long? DurationMs { get; set; } public string? ResultMessage { get; set; } public Tenant? Tenant { get; set; } public Device? Device { get; set; } } /// /// 全局唯一远程命令超期与超时状态终态化规则 /// 彻底消除各查询路径与后台 Worker 之间的状态竞态 /// public static class DeviceCommandNormalizer { public static bool NormalizeExpiredOrTimedOut(DeviceCommand cmd, DateTimeOffset now) { if (ClassNotify.Shared.Models.DeviceCommandStatuses.IsTerminal(cmd.Status)) { return false; } if (cmd.Status == ClassNotify.Shared.Models.DeviceCommandStatuses.Pending) { if (cmd.ExpiresAt <= now) { cmd.Status = ClassNotify.Shared.Models.DeviceCommandStatuses.Expired; cmd.CompletedAt = now; cmd.ResultCode = -2; cmd.ResultMessage = "Command pending expired before dispatch or device reconnect."; return true; } } else if (cmd.Status == ClassNotify.Shared.Models.DeviceCommandStatuses.Dispatched) { var dispatchedAt = cmd.StartedAt ?? cmd.CreatedAt; if (cmd.ExpiresAt <= now) { cmd.Status = ClassNotify.Shared.Models.DeviceCommandStatuses.TimedOut; cmd.CompletedAt = now; cmd.ResultCode = -4; cmd.ResultMessage = "Command expired after dispatch without device result."; return true; } else if (now - dispatchedAt >= TimeSpan.FromMinutes(2)) { cmd.Status = ClassNotify.Shared.Models.DeviceCommandStatuses.TimedOut; cmd.CompletedAt = now; cmd.ResultCode = -4; cmd.ResultMessage = "Command timed out (device did not report execution result within 2 minutes)."; return true; } } return false; } } /// /// 管理员操作审计事件实体 /// public class AdminAuditEvent { [Key] public string Id { get; set; } = string.Empty; public DateTimeOffset OccurredAt { get; set; } = DateTimeOffset.UtcNow; public string ActorUsername { get; set; } = string.Empty; public string ActorRole { get; set; } = string.Empty; public string Action { get; set; } = string.Empty; public string TargetType { get; set; } = string.Empty; public string TargetId { get; set; } = string.Empty; public string? Details { get; set; } public string? IpAddress { get; set; } } /* ===================================================================== FILE: src/Shared/ClassNotify.Shared/Models/AdminDtos.cs SIZE: 6442 chars ===================================================================== */ namespace ClassNotify.Shared.Models; /// /// 全局平台统计指标 (超级管理员大盘) /// public class AdminMetricsDto { public int TotalTenants { get; set; } public int TotalClassrooms { get; set; } public int TotalDevices { get; set; } public int OnlineDevices { get; set; } public int OfflineDevices => Math.Max(0, TotalDevices - OnlineDevices); public int TodayNotifications { get; set; } public int AbnormalDevices { get; set; } } /// /// 设备明细与实时状态 DTO /// public class DeviceAdminDto { public string DeviceId { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string ClassroomName { get; set; } = string.Empty; public string? Hostname { get; set; } public bool IsOnline { get; set; } public DateTimeOffset? LastHeartbeat { get; set; } public string? ClientVersion { get; set; } public string? RemoteIp { get; set; } public bool ServiceRunning { get; set; } = true; public bool ClientRunning { get; set; } = true; } /// /// 学校/租户大盘 DTO /// public class TenantAdminDto { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public int ClassroomCount { get; set; } public int DeviceCount { get; set; } public int OnlineCount { get; set; } public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } } /// /// 激活码详情 DTO /// public class ActivationCodeDto { public string Code { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string ClassroomName { get; set; } = string.Empty; public DateTimeOffset ExpiresAt { get; set; } public bool IsUsed { get; set; } public DateTimeOffset? UsedAt { get; set; } public string? UsedByDeviceId { get; set; } } /// /// 远程指令下发请求 /// public class RemoteCommandRequestDto { public string Command { get; set; } = string.Empty; // "ping", "restart_client", "refresh_config" public string? Parameters { get; set; } } /// /// 创建班级请求 /// public class CreateClassroomDto { public string Id { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty; public string? Grade { get; set; } public string? RoomNumber { get; set; } } /// /// 创建教师账号请求 /// public class CreateTeacherDto { public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = "Teacher"; // Teacher, SchoolAdmin } /// /// 消息历史记录与回执 /// public class NotificationRecordDto { public string Id { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string ClassId { get; set; } = string.Empty; public string ClassName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public string Priority { get; set; } = "Normal"; public DateTimeOffset CreatedAt { get; set; } public string Status { get; set; } = "Sent"; // Sent, Delivered, Acknowledged, Timeout, Failed public DateTimeOffset? ConfirmedAt { get; set; } public DateTimeOffset? ExpiresAt { get; set; } } public class UserAdminDto { public string Id { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = string.Empty; public bool IsLocked { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset? LastLoginAt { get; set; } } public class CreateUserAdminRequest { public string TenantId { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = "SchoolAdmin"; // SchoolAdmin, Teacher } public class ResetPasswordRequest { public string NewPassword { get; set; } = string.Empty; } public class LockUserRequest { public bool IsLocked { get; set; } = true; } public class CreateTenantRequest { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; } public class UpdateTenantRequest { public string Name { get; set; } = string.Empty; public bool IsActive { get; set; } = true; } public class UpdateDeviceRequest { public string? Hostname { get; set; } public string? ClassroomId { get; set; } } public class EmergencyBroadcastRequest { public string? TenantId { get; set; } // null or empty = all schools public string Title { get; set; } = "⚠️ 全校紧急通知"; public string Message { get; set; } = string.Empty; public bool Voice { get; set; } = true; public bool Shake { get; set; } = true; public int DurationSeconds { get; set; } = 30; } public class SystemHealthDto { public string Status { get; set; } = "Healthy"; public bool DatabaseConnected { get; set; } = true; public double DatabaseLatencyMs { get; set; } public int ActiveSignalRConnections { get; set; } public int OnlineDevices { get; set; } public string ServerTime { get; set; } = string.Empty; public string Uptime { get; set; } = string.Empty; public long MemoryUsedBytes { get; set; } } public class AdminAuditLogDto { public string Id { get; set; } = string.Empty; public DateTimeOffset OccurredAt { get; set; } public string ActorUsername { get; set; } = string.Empty; public string ActorRole { get; set; } = string.Empty; public string Action { get; set; } = string.Empty; public string TargetType { get; set; } = string.Empty; public string TargetId { get; set; } = string.Empty; public string? Details { get; set; } public string? IpAddress { get; set; } } /* ===================================================================== FILE: src/Shared/ClassNotify.Shared/Services/DeviceCommandDeduplicator.cs SIZE: 7671 chars ===================================================================== */ using System.Collections.Concurrent; using System.Text.Json; using ClassNotify.Shared.Models; namespace ClassNotify.Shared.Services; /// /// 命令认领抢占状态 /// public enum CommandClaimResult { /// 成功抢占并在内存与磁盘物理账本中双重持久化成功 Claimed, /// 命令此前已执行完毕,持有已完成缓存结果 AlreadyCompleted, /// 命令当前正处于执行流中,尚未得出最终结果 InFlight, /// 持久化账本写入失败或本地账本文件已损坏,Fail-Closed 拒绝执行任何副作用 StorageError } /// /// 专用远程命令幂等去重器与持久化本地账本 (Windows Service 端) /// 保证同一 CommandId 在网络抖动、SignalR 重连、重复派发、乃至 Service 崩溃或重启后, /// 严格至多在物理终端执行一次实际副作用,并能安全幂等返回先前的执行结果。 /// 严格遵循 Fail-Closed 原则:当磁盘持久化失败或文件损坏时,决不允许在不具备持久保证的情况下执行副作用。 /// public class DeviceCommandDeduplicator { public class CommandExecutionRecord { public bool IsCompleted { get; set; } public DateTimeOffset Timestamp { get; set; } public DeviceCommandResultDto? Result { get; set; } } private readonly ConcurrentDictionary _records = new(); private readonly TimeSpan _slidingWindow; private readonly int _maxCapacity; private readonly string? _ledgerFilePath; private readonly object _fileLock = new(); private volatile bool _isCorrupted = false; public int Count => _records.Count; public string? LedgerFilePath => _ledgerFilePath; public bool IsCorrupted => _isCorrupted; public DeviceCommandDeduplicator( TimeSpan? slidingWindow = null, int maxCapacity = 1000, string? ledgerFilePath = null) { _slidingWindow = slidingWindow ?? TimeSpan.FromHours(1); _maxCapacity = maxCapacity; _ledgerFilePath = ledgerFilePath; LoadLedgerFromDisk(); } /// /// 尝试以持久化 Fail-Closed 保证抢占执行锁。 /// 只有在内存认领成功 且 磁盘持久化写入原子成功时,才返回 Claimed; /// 若账本损坏或持久化失败,立即回滚内存状态并返回 StorageError,阻断副作用执行。 /// public CommandClaimResult TryDurablyClaim(string commandId, DateTimeOffset? nowUtc = null) { if (string.IsNullOrWhiteSpace(commandId)) return CommandClaimResult.StorageError; if (_isCorrupted) return CommandClaimResult.StorageError; var now = nowUtc ?? DateTimeOffset.UtcNow; PruneIfNeeded(now); if (_records.TryGetValue(commandId, out var existing)) { return existing.IsCompleted ? CommandClaimResult.AlreadyCompleted : CommandClaimResult.InFlight; } var record = new CommandExecutionRecord { IsCompleted = false, Timestamp = now }; if (!_records.TryAdd(commandId, record)) { return _records.TryGetValue(commandId, out var r) && r.IsCompleted ? CommandClaimResult.AlreadyCompleted : CommandClaimResult.InFlight; } try { SaveLedgerToDisk(); return CommandClaimResult.Claimed; } catch { // Fail-closed: 回滚内存记录,确保没有虚假的 InFlight 状态残留在内存中 _records.TryRemove(commandId, out _); return CommandClaimResult.StorageError; } } /// /// 尝试抢占执行锁(兼容既有布尔接口,底层严格遵循 TryDurablyClaim 的 Fail-Closed 保证)。 /// public bool TryBeginExecution(string commandId, DateTimeOffset? nowUtc = null) { return TryDurablyClaim(commandId, nowUtc) == CommandClaimResult.Claimed; } /// /// 命令执行完毕后记录最终执行结果并持久化至磁盘 /// public void CompleteExecution(string commandId, DeviceCommandResultDto result, DateTimeOffset? nowUtc = null) { if (string.IsNullOrWhiteSpace(commandId)) return; var now = nowUtc ?? DateTimeOffset.UtcNow; if (_records.TryGetValue(commandId, out var record)) { record.IsCompleted = true; record.Timestamp = now; record.Result = result; } else { _records[commandId] = new CommandExecutionRecord { IsCompleted = true, Timestamp = now, Result = result }; } try { SaveLedgerToDisk(); } catch { // 写入失败时保留内存记录 } } /// /// 查询已完成命令的历史缓存结果(用于重复到达时直接返回原结果) /// public bool TryGetCachedResult(string commandId, out DeviceCommandResultDto? result) { result = null; if (string.IsNullOrWhiteSpace(commandId)) return false; if (_records.TryGetValue(commandId, out var record) && record.IsCompleted && record.Result != null) { result = record.Result; return true; } return false; } public void Clear() { _records.Clear(); _isCorrupted = false; try { SaveLedgerToDisk(); } catch { } } private void PruneIfNeeded(DateTimeOffset now) { bool pruned = false; var cutoff = now.Subtract(_slidingWindow); if (_records.Count > _maxCapacity) { foreach (var kvp in _records) { if (kvp.Value.Timestamp < cutoff) { if (_records.TryRemove(kvp.Key, out _)) { pruned = true; } } } } if (pruned) { try { SaveLedgerToDisk(); } catch { } } } private void LoadLedgerFromDisk() { if (string.IsNullOrWhiteSpace(_ledgerFilePath)) return; try { lock (_fileLock) { if (!File.Exists(_ledgerFilePath)) return; var json = File.ReadAllText(_ledgerFilePath); if (string.IsNullOrWhiteSpace(json)) { // 存在但为空,视同损坏文件以防读取非预期状态 _isCorrupted = true; return; } var data = JsonSerializer.Deserialize>(json); if (data != null) { var now = DateTimeOffset.UtcNow; var cutoff = now.Subtract(_slidingWindow); foreach (var (k, v) in data) { if (v.Timestamp >= cutoff) { _records[k] = v; } } } else { _isCorrupted = true; } } } catch { // Fail-closed: 遇到反序列化异常或文件损坏时标记 Corrupted,阻止无保护的执行 _isCorrupted = true; } } private void SaveLedgerToDisk() { if (string.IsNullOrWhiteSpace(_ledgerFilePath)) return; lock (_fileLock) { var dir = Path.GetDirectoryName(_ledgerFilePath); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var snapshot = _records.ToDictionary(k => k.Key, v => v.Value); var json = JsonSerializer.Serialize(snapshot, new JsonSerializerOptions { WriteIndented = true }); var tmp = _ledgerFilePath + $".{Guid.NewGuid():N}.tmp"; File.WriteAllText(tmp, json); File.Move(tmp, _ledgerFilePath, overwrite: true); } } } /* ===================================================================== FILE: src/Windows/ClassNotify.Service/Workers/SignalRWorker.cs SIZE: 29435 chars ===================================================================== */ using System.Collections.Concurrent; using System.Text.Json; using ClassNotify.Service.Ipc; using ClassNotify.Service.Services; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using ClassNotify.Shared.Services; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ClassNotify.Service.Workers; public class SignalRWorker : BackgroundService { private readonly ILogger _logger; private readonly IConfiguration _config; private readonly NamedPipeServer _pipeServer; private readonly DeviceCredentialsManager _credManager; private readonly ClientNotificationBuffer _clientNotificationBuffer = new(); private readonly DeviceCommandDeduplicator _commandDeduplicator = new( ledgerFilePath: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "command_ledger.json")); private HubConnection? _hubConnection; private readonly string _serverBaseUrl; private readonly int _heartbeatInterval; private DeviceCredentials? _credentials; public SignalRWorker( ILogger logger, IConfiguration config, NamedPipeServer pipeServer, DeviceCredentialsManager credManager) { _logger = logger; _config = config; _pipeServer = pipeServer; _credManager = credManager; var fullUrl = _config["ClassNotify:ServerUrl"] ?? "https://classnotify.paradise.eu.org/hubs/device"; // Extract base URL var uri = new Uri(fullUrl); _serverBaseUrl = $"{uri.Scheme}://{uri.Authority}"; _heartbeatInterval = int.TryParse(_config["ClassNotify:HeartbeatIntervalSeconds"], out var val) ? val : 15; _pipeServer.OnAckReceived += async (ack) => await ForwardAckToServerAsync(ack); _pipeServer.OnHealthReportReceived += async (report) => await ForwardHealthReportAsync(report); _pipeServer.OnClientConnected += async () => await FlushPendingNotificationsToClientAsync(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("ClassNotify.Service initializing security & credentials..."); // 1. Start Local Named Pipe IPC Listener _pipeServer.StartListening(stoppingToken); // 2. Load Device Credentials (created by ClassNotify.Setup) _credentials = _credManager.LoadCredentials(); while (_credentials == null && !stoppingToken.IsCancellationRequested) { _logger.LogWarning("Device credentials not found. Waiting for ClassNotify Setup activation."); await Task.Delay(10000, stoppingToken); _credentials = _credManager.LoadCredentials(); } if (stoppingToken.IsCancellationRequested || _credentials == null) return; _logger.LogInformation("Device Credentials Loaded: DeviceId={DeviceId}, Tenant={TenantId}, Class={ClassDisplayName} ({ClassId})", _credentials.DeviceId, _credentials.TenantId, _credentials.ClassDisplayName, _credentials.ClassId); var hubUrl = $"{_serverBaseUrl}/hubs/device"; // 3. Configure SignalR Connection with Machine-Level Device Credentials _hubConnection = new HubConnectionBuilder() .WithUrl(hubUrl, options => { options.Headers.Add("X-Device-Id", _credentials.DeviceId); options.Headers.Add("X-Device-Token", _credentials.DeviceToken); }) .WithAutomaticReconnect(new InfiniteRetryPolicy()) .Build(); // 4. Register Server Callback Handlers _hubConnection.On("ReceiveNotification", async (notification) => { _logger.LogInformation("Received notification from cloud: {Id} (Tenant: {Tenant}) - {Message}", notification.Id, notification.TenantId, notification.Message); // P1 Batch 9 Round 3: Check SendNotificationToClientAsync return value! // If pipe disconnected mid-send (returns false) or client not connected, // DeliverOrBufferAsync safely enqueues into _clientNotificationBuffer. var delivered = await _clientNotificationBuffer.DeliverOrBufferAsync( notification, () => _pipeServer.IsClientConnected, async notif => await _pipeServer.SendNotificationToClientAsync(notif), waitAttempts: 6, delayMsBetweenAttempts: 500); if (!delivered) { _logger.LogInformation("WPF Client is not yet connected or send failed. Enqueued notification {Id} into local pending buffer (ExpiresAt: {ExpiresAt}). Retriable until client launch or TTL expiration.", notification.Id, notification.ExpiresAt); } }); _hubConnection.On("ReceiveRemoteCommand", async (cmd) => { if (cmd == null || string.IsNullOrWhiteSpace(cmd.CommandId)) { _logger.LogWarning("Received null or invalid remote command DTO"); return; } _logger.LogInformation("Received remote command: Id={CommandId}, Type={Type}, TargetDevice={Device}, Param={Param}, ExpiresAt={ExpiresAt:u}", cmd.CommandId, cmd.CommandType, cmd.DeviceId, cmd.Parameters, cmd.ExpiresAt); // 1. Device Targeting Check (device isolation fail-closed) if (!string.IsNullOrEmpty(cmd.DeviceId) && _credentials != null && !string.Equals(cmd.DeviceId, _credentials.DeviceId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Rejecting remote command {CommandId}: targeted for {TargetDeviceId}, but this device is {CurrentDeviceId}", cmd.CommandId, cmd.DeviceId, _credentials.DeviceId); var mismatchResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials.DeviceId, Status = DeviceCommandStatuses.Failed, ResultCode = -1, ResultMessage = "Target device mismatch (wrong device ID)", Timestamp = DateTimeOffset.UtcNow }; await ForwardCommandResultToServerAsync(mismatchResult); return; } // 2. Short-lived TTL Check if (cmd.ExpiresAt <= DateTimeOffset.UtcNow) { _logger.LogWarning("Rejecting remote command {CommandId} ({Type}): expired at {ExpiresAt:u} (now is {Now:u})", cmd.CommandId, cmd.CommandType, cmd.ExpiresAt, DateTimeOffset.UtcNow); var expiredResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials?.DeviceId ?? cmd.DeviceId, Status = DeviceCommandStatuses.Expired, ResultCode = -2, ResultMessage = "Command expired before device execution", Timestamp = DateTimeOffset.UtcNow }; await ForwardCommandResultToServerAsync(expiredResult); return; } // 3. Whitelist Check if (!DeviceCommandTypes.IsSupported(cmd.CommandType)) { _logger.LogWarning("Rejecting remote command {CommandId}: unsupported/forbidden command type '{Type}'", cmd.CommandId, cmd.CommandType); var unsupportedResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials?.DeviceId ?? cmd.DeviceId, Status = DeviceCommandStatuses.Failed, ResultCode = -3, ResultMessage = $"Command type '{cmd.CommandType}' not supported or forbidden", Timestamp = DateTimeOffset.UtcNow }; await ForwardCommandResultToServerAsync(unsupportedResult); return; } // 4. Idempotency Check via Dedicated DeviceCommandDeduplicator (Fail-Closed) var claimResult = _commandDeduplicator.TryDurablyClaim(cmd.CommandId); if (claimResult != CommandClaimResult.Claimed) { if (claimResult == CommandClaimResult.StorageError) { _logger.LogError("Rejecting remote command {CommandId} ({CommandType}): Durable ledger storage failure or corrupted ledger file (fail-closed).", cmd.CommandId, cmd.CommandType); var failResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials?.DeviceId ?? cmd.DeviceId, Status = DeviceCommandStatuses.Failed, ResultCode = -5, ResultMessage = "Command rejected: Durable ledger storage failure or corrupted ledger file (fail-closed).", Timestamp = DateTimeOffset.UtcNow }; await ForwardCommandResultToServerAsync(failResult); return; } if (_commandDeduplicator.TryGetCachedResult(cmd.CommandId, out var cachedResult) && cachedResult != null) { _logger.LogInformation("Duplicate remote command {CommandId} received. Returning cached result without re-executing.", cmd.CommandId); await ForwardCommandResultToServerAsync(cachedResult); } else { _logger.LogInformation("Remote command {CommandId} is already in-flight. Ignoring duplicate dispatch.", cmd.CommandId); } return; } // 5. Whitelist Execution var sw = System.Diagnostics.Stopwatch.StartNew(); int resultCode = 0; string resultMessage = "Execution succeeded"; string status = DeviceCommandStatuses.Succeeded; try { switch (cmd.CommandType.ToLowerInvariant()) { case "selfcheck" or "self_check": var report = await ExecuteSelfCheckAsync(); await ForwardHealthReportAsync(report); resultMessage = $"Self-check completed: overall={report.OverallStatus}, diagnostic={report.DiagnosticMessage}"; _logger.LogInformation("Responded to remote SelfCheck: {Message}", resultMessage); break; case "restartclient" or "restart_client": _logger.LogInformation("Executing remote restart_client command..."); foreach (var proc in System.Diagnostics.Process.GetProcessesByName("ClassNotify.Client")) { try { proc.Kill(); } catch { } } var clientPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ClassNotify.Client.exe"); if (!System.IO.File.Exists(clientPath)) { clientPath = @"C:\Program Files\ClassNotify\Client\ClassNotify.Client.exe"; } if (!System.IO.File.Exists(clientPath)) { clientPath = @"C:\Program Files\ClassNotify\ClassNotify.Client.exe"; } if (System.IO.File.Exists(clientPath)) { _pipeServer.InvalidateAuthorization(); string launchToken = Guid.NewGuid().ToString("N"); var res = SessionLauncher.LaunchProcessInActiveUserSession(clientPath, launchToken, _logger); if (res.Success) { _pipeServer.SetAuthorizedClient(res.LaunchToken, res.Pid, res.SessionId); resultMessage = $"Client successfully launched in session {res.SessionId} (PID: {res.Pid})"; } else { status = DeviceCommandStatuses.Failed; resultCode = -10; resultMessage = "Session launch failed (active console session not found or access denied)"; } } else { status = DeviceCommandStatuses.Failed; resultCode = -11; resultMessage = "ClassNotify.Client.exe binary not found on target machine"; } break; case "reconnect": _logger.LogInformation("Executing remote Reconnect command..."); if (_hubConnection != null) { try { await _hubConnection.StopAsync(); await Task.Delay(1000); await _hubConnection.StartAsync(); status = DeviceCommandStatuses.Succeeded; resultCode = 0; resultMessage = "SignalR connection successfully re-established"; _logger.LogInformation("SignalR connection successfully re-established by remote Reconnect command"); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to re-establish SignalR connection during Reconnect command"); status = DeviceCommandStatuses.Failed; resultCode = -20; resultMessage = "SignalR reconnection failed to start"; } } else { status = DeviceCommandStatuses.Failed; resultCode = -21; resultMessage = "Hub connection instance is null"; } break; case "refreshconfig" or "refresh_config": _credentials = _credManager.LoadCredentials(); if (_credentials != null && _hubConnection?.State == HubConnectionState.Connected) { await _hubConnection.InvokeAsync("SendHeartbeat", _credentials.ClassId); } resultMessage = $"Refreshed credentials configuration for Tenant {_credentials?.TenantId}, Class {_credentials?.ClassId}"; _logger.LogInformation("{Message}", resultMessage); break; default: status = DeviceCommandStatuses.Failed; resultCode = -3; resultMessage = $"Unsupported command type '{cmd.CommandType}'"; break; } } catch (Exception ex) { _logger.LogError(ex, "Error processing remote command: {CommandId} ({Type})", cmd.CommandId, cmd.CommandType); status = DeviceCommandStatuses.Failed; resultCode = -99; resultMessage = $"Internal execution error: {ex.Message}"; } finally { sw.Stop(); } var finalResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials?.DeviceId ?? cmd.DeviceId, Status = status, ResultCode = resultCode, ResultMessage = resultMessage, ExecutionDurationMs = sw.ElapsedMilliseconds, Timestamp = DateTimeOffset.UtcNow }; _commandDeduplicator.CompleteExecution(cmd.CommandId, finalResult); await ForwardCommandResultToServerAsync(finalResult); }); // 5. Connection Lifecycle _hubConnection.Reconnecting += error => { _logger.LogWarning(error, "SignalR connection lost. Reconnecting to {Url}...", hubUrl); return Task.CompletedTask; }; _hubConnection.Reconnected += connectionId => { _logger.LogInformation("SignalR reconnected successfully! ConnectionId: {ConnectionId}", connectionId); return Task.CompletedTask; }; _hubConnection.Closed += async error => { _logger.LogWarning(error, "SignalR connection closed permanently. Attempting background re-connection..."); while (!stoppingToken.IsCancellationRequested && _hubConnection.State != HubConnectionState.Connected) { try { await Task.Delay(5000, stoppingToken); await _hubConnection.StartAsync(stoppingToken); _logger.LogInformation("SignalR reconnected after connection was closed!"); break; } catch (Exception ex) when (!stoppingToken.IsCancellationRequested) { _logger.LogWarning("Reconnection attempt failed: {Message}. Retrying in 10s...", ex.Message); await Task.Delay(10000, stoppingToken); } } }; // 6. Connect Loop while (!stoppingToken.IsCancellationRequested) { try { _logger.LogInformation("Connecting to SignalR DeviceHub: {Url}...", hubUrl); await _hubConnection.StartAsync(stoppingToken); _logger.LogInformation("SignalR connected and device authenticated successfully!"); // Trigger initial SelfCheck and snapshot upon successful connection _ = Task.Run(async () => { try { await Task.Delay(2000, stoppingToken); var initialReport = await ExecuteSelfCheckAsync(); _logger.LogInformation("[SelfCheck] Initial health status recorded: Overall={Status}", initialReport.OverallStatus); } catch (Exception ex) { _logger.LogWarning(ex, "[SelfCheck] Initial health check failed."); } }, stoppingToken); break; } catch (Exception ex) when (!stoppingToken.IsCancellationRequested) { _logger.LogError(ex, "Failed to connect to DeviceHub. Retrying in 5 seconds..."); await Task.Delay(5000, stoppingToken); } } // 7. Heartbeat & Periodic Health Snapshot Loop var lastHealthSnapshotUtc = DateTimeOffset.MinValue; while (!stoppingToken.IsCancellationRequested) { if (_hubConnection.State == HubConnectionState.Connected) { try { await _hubConnection.InvokeAsync("SendHeartbeat", _credentials.ClassId, stoppingToken); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to send heartbeat to server."); } } if (DateTimeOffset.UtcNow - lastHealthSnapshotUtc >= TimeSpan.FromSeconds(30)) { lastHealthSnapshotUtc = DateTimeOffset.UtcNow; _ = Task.Run(async () => { try { await ExecuteSelfCheckAsync(); } catch (Exception ex) { _logger.LogDebug(ex, "[SelfCheck] Periodic health check snapshot failed."); } }, stoppingToken); } await Task.Delay(TimeSpan.FromSeconds(_heartbeatInterval), stoppingToken); } } private async Task ForwardAckToServerAsync(AckReceiptDto ack) { if (_hubConnection?.State == HubConnectionState.Connected) { try { await _hubConnection.InvokeAsync("SendAckReceipt", ack); _logger.LogInformation("Forwarded ACK to server: {MsgId} -> {Status}", ack.MessageId, ack.Status); } catch (Exception ex) { _logger.LogError(ex, "Failed to forward ACK to server: {MsgId}", ack.MessageId); } } } private async Task ForwardCommandResultToServerAsync(DeviceCommandResultDto result) { if (_hubConnection?.State == HubConnectionState.Connected) { try { await _hubConnection.InvokeAsync("ReportCommandResult", result); _logger.LogInformation("Forwarded command result to server: {CmdId} -> {Status} (Code: {Code}, {Duration}ms)", result.CommandId, result.Status, result.ResultCode, result.ExecutionDurationMs); } catch (Exception ex) { _logger.LogError(ex, "Failed to forward command result to server: {CmdId}", result.CommandId); } } else { _logger.LogWarning("Cannot forward command result for {CmdId}: SignalR connection is not connected.", result.CommandId); } } private async Task ExecuteSelfCheckAsync() { var now = DateTimeOffset.UtcNow; var report = new DeviceHealthReportDto { ClassId = _credentials?.ClassId ?? "unknown", Timestamp = now, CheckedAtUtc = now, ServiceRunning = true }; // 1. DNS check try { var host = new Uri(_serverBaseUrl).Host; var addrs = await System.Net.Dns.GetHostAddressesAsync(host); report.DnsOk = addrs.Length > 0; } catch (Exception ex) { report.DnsOk = false; _logger.LogWarning(ex, "[SelfCheck] DNS resolution failed for {Url}", _serverBaseUrl); } // 2. HTTPS health endpoint check try { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }; var resp = await http.GetAsync($"{_serverBaseUrl}/api/health"); report.HttpsOk = resp.IsSuccessStatusCode; } catch (Exception ex) { report.HttpsOk = false; _logger.LogWarning(ex, "[SelfCheck] HTTPS health check failed for {Url}/api/health", _serverBaseUrl); } // 3. SignalR connection check report.SignalROk = _hubConnection?.State == HubConnectionState.Connected; // 4. Credentials check (never log full token!) try { var creds = _credManager.LoadCredentials(); report.CredentialsOk = creds != null && !string.IsNullOrWhiteSpace(creds.DeviceId) && !string.IsNullOrWhiteSpace(creds.DeviceToken); } catch (Exception ex) { report.CredentialsOk = false; _logger.LogWarning(ex, "[SelfCheck] Credentials check failed."); } // 5. Data Directory write check try { var dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify"); if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); var testFile = Path.Combine(dataDir, $".selfcheck-{Guid.NewGuid():N}.tmp"); await File.WriteAllTextAsync(testFile, "selfcheck_write_probe"); File.Delete(testFile); report.DataDirectoryWritable = true; } catch (Exception ex) { report.DataDirectoryWritable = false; _logger.LogWarning(ex, "[SelfCheck] Data directory write test failed."); } // 6. Named Pipe & Client check report.PipeOk = _pipeServer.IsClientConnected; if (_pipeServer.LastClientHeartbeatUtc != DateTimeOffset.MinValue) { var age = now - _pipeServer.LastClientHeartbeatUtc; report.ClientHeartbeatAgeSeconds = (int)age.TotalSeconds; report.ClientConnected = report.PipeOk && (age < TimeSpan.FromSeconds(15)); } else { report.ClientHeartbeatAgeSeconds = -1; report.ClientConnected = false; } // 7. TTS check via IPC if (report.PipeOk) { var ttsResult = await _pipeServer.SendTtsCheckAsync(TimeSpan.FromSeconds(3)); report.TtsOk = ttsResult != null && ttsResult.Available; } else { report.TtsOk = false; } // 8. Overall Status calculation if (!report.CredentialsOk || !report.SignalROk) { report.OverallStatus = "Offline"; } else if (!report.TtsOk || !report.ClientConnected || !report.DataDirectoryWritable || !report.DnsOk || !report.HttpsOk) { report.OverallStatus = "Degraded"; } else { report.OverallStatus = "Healthy"; } report.DiagnosticMessage = $"Overall={report.OverallStatus}, DNS={report.DnsOk}, HTTPS={report.HttpsOk}, SignalR={report.SignalROk}, Creds={report.CredentialsOk}, Storage={report.DataDirectoryWritable}, Pipe={report.PipeOk}, Client={report.ClientConnected} (age={report.ClientHeartbeatAgeSeconds}s), TTS={report.TtsOk}"; await SaveHealthStatusAsync(report); return report; } private async Task SaveHealthStatusAsync(DeviceHealthReportDto report) { try { var dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify"); if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); var targetFile = Path.Combine(dataDir, "health_status.json"); var tmpFile = Path.Combine(dataDir, $"health_status_{Guid.NewGuid():N}.tmp"); var json = JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }); await File.WriteAllTextAsync(tmpFile, json); File.Move(tmpFile, targetFile, overwrite: true); _logger.LogDebug("[HealthStatus] Saved local health status snapshot: Overall={Status}", report.OverallStatus); } catch (Exception ex) { _logger.LogWarning(ex, "[HealthStatus] Failed to save local health status snapshot."); } } private async Task ForwardHealthReportAsync(DeviceHealthReportDto report) { if (_hubConnection?.State == HubConnectionState.Connected) { try { await _hubConnection.InvokeAsync("SendHealthReport", report); } catch (Exception ex) { _logger.LogError(ex, "Failed to forward health report to server."); } } } private async Task FlushPendingNotificationsToClientAsync() { var flushed = await _clientNotificationBuffer.FlushAsync( () => _pipeServer.IsClientConnected, async notif => await _pipeServer.SendNotificationToClientAsync(notif)); if (flushed > 0) { _logger.LogInformation("Successfully flushed {Count} pending notification(s) to connected WPF client.", flushed); } } public override async Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Stopping SignalRWorker..."); if (_hubConnection != null) { await _hubConnection.DisposeAsync(); } await base.StopAsync(cancellationToken); } private class InfiniteRetryPolicy : IRetryPolicy { public TimeSpan? NextRetryDelay(RetryContext retryContext) { if (retryContext.PreviousRetryCount == 0) return TimeSpan.Zero; if (retryContext.PreviousRetryCount == 1) return TimeSpan.FromSeconds(2); if (retryContext.PreviousRetryCount == 2) return TimeSpan.FromSeconds(5); if (retryContext.PreviousRetryCount == 3) return TimeSpan.FromSeconds(10); return TimeSpan.FromSeconds(30); // Infinite retry every 30 seconds } } } /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/api/client.ts SIZE: 7764 chars ===================================================================== */ import { AdminMetrics, TenantAdmin, DeviceAdmin, ActivationCode, Classroom, TeacherUser, NotificationRecord, SendNotificationPayload, LoginResult, CurrentUser, UserAdmin, CreateUserAdminRequest, CreateTenantRequest, UpdateTenantRequest, UpdateDeviceRequest, EmergencyBroadcastRequest, SystemHealth, AdminAuditLog } from '../types'; import { sessionManager } from '../realtime/SessionManager'; const API_BASE = '/api'; export function getToken(): string | null { return localStorage.getItem('classnotify_token'); } export function setToken(token: string) { localStorage.setItem('classnotify_token', token); } export function clearToken() { localStorage.removeItem('classnotify_token'); localStorage.removeItem('classnotify_user'); } async function request(endpoint: string, options: RequestInit = {}): Promise { const token = getToken(); const headers: Record = { 'Content-Type': 'application/json', ...(options.headers as Record), }; if (token) { headers['Authorization'] = `Bearer ${token}`; } const res = await fetch(`${API_BASE}${endpoint}`, { ...options, headers, }); if (res.status === 401) { clearToken(); sessionManager.notifySessionExpired('未授权或登录已过期,请重新登录'); throw new Error('未授权或登录已过期,请重新登录'); } if (!res.ok) { let errorMsg = `请求失败 (${res.status})`; try { const err = await res.json(); errorMsg = err.message || err.errorMessage || errorMsg; } catch { // ignore json parse error } throw new Error(errorMsg); } return res.json() as Promise; } export const api = { // Auth login: (username: string, password: string): Promise => request('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }), }), getMe: (): Promise => request('/auth/me'), // SuperAdmin getAdminMetrics: (): Promise => request('/admin/metrics'), getTenants: (): Promise => request('/admin/tenants'), getAllDevices: (): Promise => request('/admin/devices'), sendDeviceCommand: (deviceId: string, command: string, parameters?: string) => request<{ success: boolean; message: string }>(`/admin/devices/${deviceId}/command`, { method: 'POST', body: JSON.stringify({ command, parameters }), }), getAdminActivationCodes: (): Promise => request('/admin/activation-codes'), generateAdminCode: (tenantId: string, classId: string) => request<{ success: boolean; code: string; message: string }>( `/admin/activation-codes?tenantId=${encodeURIComponent(tenantId)}&classId=${encodeURIComponent(classId)}`, { method: 'POST' } ), getAdminNotifications: (limit = 50): Promise => request(`/admin/notifications?limit=${limit}`), // Tenant Management createTenant: (dto: CreateTenantRequest): Promise => request('/admin/tenants', { method: 'POST', body: JSON.stringify(dto), }), updateTenant: (tenantId: string, dto: UpdateTenantRequest): Promise => request(`/admin/tenants/${encodeURIComponent(tenantId)}`, { method: 'PATCH', body: JSON.stringify(dto), }), // User Management getUsers: (tenantId?: string, role?: string): Promise => { const params = new URLSearchParams(); if (tenantId) params.append('tenantId', tenantId); if (role) params.append('role', role); const qs = params.toString(); return request(`/admin/users${qs ? `?${qs}` : ''}`); }, createUser: (dto: CreateUserAdminRequest): Promise => request('/admin/users', { method: 'POST', body: JSON.stringify(dto), }), resetPassword: (userId: string, newPassword: string) => request<{ success: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}/reset-password`, { method: 'POST', body: JSON.stringify({ newPassword }), }), setUserLock: (userId: string, isLocked: boolean) => request<{ success: boolean; isLocked: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}/lock`, { method: 'POST', body: JSON.stringify({ isLocked }), }), deleteUser: (userId: string) => request<{ success: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}`, { method: 'DELETE', }), // Device Extensions updateDevice: (deviceId: string, dto: UpdateDeviceRequest) => request<{ success: boolean; message: string }>(`/admin/devices/${encodeURIComponent(deviceId)}`, { method: 'PATCH', body: JSON.stringify(dto), }), decommissionDevice: (deviceId: string) => request<{ success: boolean; message: string }>(`/admin/devices/${encodeURIComponent(deviceId)}/decommission`, { method: 'POST', }), // Activation Code Management deleteActivationCode: (code: string) => request<{ success: boolean; message: string }>(`/admin/activation-codes/${encodeURIComponent(code)}`, { method: 'DELETE', }), // Emergency Broadcast sendEmergencyBroadcast: (dto: EmergencyBroadcastRequest) => request<{ success: boolean; dispatchedCount: number; targetSchools: number; message: string }>('/admin/broadcasts', { method: 'POST', body: JSON.stringify(dto), }), // System Health & Audit getSystemHealth: (): Promise => request('/admin/system/health'), getAuditLogs: (limit = 100): Promise => request(`/admin/audit-logs?limit=${limit}`), // School Admin getSchoolOverview: (): Promise<{ tenantId: string; tenantName: string; classCount: number; deviceCount: number; onlineCount: number; teacherCount: number; }> => request('/school-admin/overview'), getSchoolClasses: (): Promise => request('/school-admin/classes'), createSchoolClass: (dto: { id: string; displayName: string; grade?: string; roomNumber?: string }) => request<{ success: boolean; message: string }>('/school-admin/classes', { method: 'POST', body: JSON.stringify(dto), }), getSchoolTeachers: (): Promise => request('/school-admin/teachers'), createSchoolTeacher: (dto: { username: string; password: string; fullName: string; role: string }) => request<{ success: boolean; message: string }>('/school-admin/teachers', { method: 'POST', body: JSON.stringify(dto), }), getSchoolDevices: (): Promise => request('/school-admin/devices'), getSchoolCodes: (): Promise => request('/school-admin/activation-codes'), generateSchoolCode: (classId: string) => request<{ success: boolean; code: string; message: string }>( `/school-admin/activation-codes?classId=${encodeURIComponent(classId)}`, { method: 'POST' } ), // Teacher getTeacherClasses: (): Promise => request('/notification/classes'), sendNotification: (payload: SendNotificationPayload) => request<{ success: boolean; messageId: string; className: string; message: string }>( '/notification/send', { method: 'POST', body: JSON.stringify(payload), } ), getTeacherHistory: (classId?: string, limit = 50): Promise => request( `/notification/history?${classId ? `classId=${encodeURIComponent(classId)}&` : ''}limit=${limit}` ), }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/types/index.ts SIZE: 3291 chars ===================================================================== */ export type UserRole = 'SuperAdmin' | 'SchoolAdmin' | 'Teacher'; export interface CurrentUser { userId: string; name: string; role: UserRole; tenantId: string; } export interface LoginResult { success: boolean; token?: string; tenantId?: string; userId?: string; fullName?: string; role?: UserRole; errorMessage?: string; } export interface AdminMetrics { totalTenants: number; totalClassrooms: number; totalDevices: number; onlineDevices: number; offlineDevices: number; todayNotifications: number; abnormalDevices: number; } export interface TenantAdmin { id: string; name: string; classroomCount: number; deviceCount: number; onlineCount: number; isActive: boolean; createdAt: string; } export interface DeviceAdmin { deviceId: string; tenantId: string; tenantName: string; classroomId: string; classroomName: string; hostname?: string; isOnline: boolean; lastHeartbeat?: string; clientVersion?: string; remoteIp?: string; serviceRunning: boolean; clientRunning: boolean; healthStatus?: string; } export interface ActivationCode { code: string; tenantId: string; tenantName: string; classroomId: string; classroomName: string; expiresAt: string; isUsed: boolean; usedAt?: string; usedByDeviceId?: string; } export interface Classroom { id: string; tenantId: string; displayName: string; grade?: string; roomNumber?: string; } export interface TeacherUser { id: string; username: string; fullName: string; role: string; } export interface NotificationRecord { id: string; tenantId: string; classId: string; className: string; senderName: string; message: string; priority: string; createdAt: string; status: 'Sent' | 'Delivered' | 'Acknowledged' | 'Timeout' | 'Failed'; confirmedAt?: string; } export interface SendNotificationPayload { classId: string; studentName?: string; title: string; message: string; type: number; // 0=Call, 1=Broadcast, 2=Urgent voice: boolean; shake: boolean; durationSeconds: number; } export interface UserAdmin { id: string; tenantId: string; tenantName: string; username: string; fullName: string; role: string; isLocked: boolean; createdAt: string; lastLoginAt?: string; } export interface CreateUserAdminRequest { tenantId: string; username: string; password: string; fullName: string; role: string; } export interface CreateTenantRequest { id: string; name: string; } export interface UpdateTenantRequest { name: string; isActive: boolean; } export interface UpdateDeviceRequest { hostname?: string; classroomId?: string; } export interface EmergencyBroadcastRequest { tenantId?: string; title: string; message: string; voice: boolean; shake: boolean; durationSeconds: number; } export interface SystemHealth { status: string; databaseConnected: boolean; databaseLatencyMs: number; activeSignalRConnections: number; onlineDevices: number; serverTime: string; uptime: string; memoryUsedBytes: number; } export interface AdminAuditLog { id: string; occurredAt: string; actorUsername: string; actorRole: string; action: string; targetType: string; targetId: string; details?: string; ipAddress?: string; } /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/pages/admin/TenantManagement.tsx SIZE: 15837 chars ===================================================================== */ import React, { useEffect, useState } from 'react'; import { api } from '../../api/client'; import { TenantAdmin, CreateTenantRequest, UpdateTenantRequest } from '../../types'; import { Building2, Plus, Search, RefreshCw, CheckCircle2, XCircle, Edit3, GraduationCap, AlertCircle } from 'lucide-react'; export const TenantManagement: React.FC = () => { const [tenants, setTenants] = useState([]); const [loading, setLoading] = useState(true); const [search, setSearch] = useState(''); const [message, setMessage] = useState<{ text: string; success: boolean } | null>(null); // Create Modal const [showCreateModal, setShowCreateModal] = useState(false); const [createForm, setCreateForm] = useState({ id: '', name: '' }); const [createLoading, setCreateLoading] = useState(false); // Edit Modal const [editingTenant, setEditingTenant] = useState(null); const [editForm, setEditForm] = useState({ name: '', isActive: true }); const [editLoading, setEditLoading] = useState(false); const loadTenants = async () => { try { const data = await api.getTenants(); setTenants(data); } catch (err: any) { console.error('Failed to load tenants', err); } finally { setLoading(false); } }; useEffect(() => { loadTenants(); }, []); const handleCreate = async (e: React.FormEvent) => { e.preventDefault(); if (!createForm.id.trim() || !createForm.name.trim()) return; setCreateLoading(true); try { await api.createTenant({ id: createForm.id.trim(), name: createForm.name.trim(), }); setMessage({ text: `学校 [${createForm.name}] 创建成功!`, success: true }); setShowCreateModal(false); setCreateForm({ id: '', name: '' }); loadTenants(); } catch (err: any) { setMessage({ text: err.message || '创建学校失败', success: false }); } finally { setCreateLoading(false); } }; const openEdit = (tenant: TenantAdmin) => { setEditingTenant(tenant); setEditForm({ name: tenant.name, isActive: tenant.isActive }); }; const handleEdit = async (e: React.FormEvent) => { e.preventDefault(); if (!editingTenant || !editForm.name.trim()) return; setEditLoading(true); try { await api.updateTenant(editingTenant.id, { name: editForm.name.trim(), isActive: editForm.isActive, }); setMessage({ text: `学校 [${editForm.name}] 配置已更新`, success: true }); setEditingTenant(null); loadTenants(); } catch (err: any) { setMessage({ text: err.message || '更新学校配置失败', success: false }); } finally { setEditLoading(false); } }; const filteredTenants = tenants.filter( (t) => t.name.toLowerCase().includes(search.toLowerCase()) || t.id.toLowerCase().includes(search.toLowerCase()) ); return (
{/* Header */}

学校租户生命周期管理

统筹多校区租户实体,支持新校区入驻配置、基础信息变更与服务启停冻结

{/* Alert Banner */} {message && (
{message.success ? ( ) : ( )} {message.text}
)} {/* Filter Bar */}
setSearch(e.target.value)} placeholder="按学校标识代码 (ID) 或名称搜索..." className="bg-transparent border-none text-sm text-white placeholder-slate-500 focus:outline-none w-full" /> {search && ( )}
{/* Tenants Table */}
{filteredTenants.length === 0 ? ( ) : ( filteredTenants.map((t) => ( )) )}
学校名称 / 标识码 班级总数 终端大屏 (在线/总计) 服务状态 接入时间 管理操作
{loading ? '正在读取租户列表...' : '暂无匹配的学校租户'}
{t.name}
{t.id}
{t.classroomCount} 个班级
{t.onlineCount} 在线 / {t.deviceCount} 总屏
{t.isActive ? (
正常运营
) : (
已停用冻结
)}
{new Date(t.createdAt).toLocaleDateString()}
{/* Create Modal */} {showCreateModal && (

接入新学校租户

setCreateForm({ ...createForm, id: e.target.value })} className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />

只能包含小写字母、数字和下划线,作为多租户隔离主键不可篡改

setCreateForm({ ...createForm, name: e.target.value })} className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />
)} {/* Edit Modal */} {editingTenant && (

编辑学校配置: {editingTenant.id}

setEditForm({ ...editForm, name: e.target.value })} className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />
)}
); }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/pages/admin/UserManagement.tsx SIZE: 22225 chars ===================================================================== */ import React, { useEffect, useState } from 'react'; import { api } from '../../api/client'; import { UserAdmin, TenantAdmin, CreateUserAdminRequest } from '../../types'; import { Users, Plus, Search, RefreshCw, KeyRound, Lock, Unlock, Trash2, Building2, ShieldAlert, CheckCircle2, AlertCircle, GraduationCap } from 'lucide-react'; export const UserManagement: React.FC = () => { const [users, setUsers] = useState([]); const [tenants, setTenants] = useState([]); const [loading, setLoading] = useState(true); const [search, setSearch] = useState(''); const [selectedTenant, setSelectedTenant] = useState(''); const [selectedRole, setSelectedRole] = useState(''); const [message, setMessage] = useState<{ text: string; success: boolean } | null>(null); // Create User Modal const [showCreateModal, setShowCreateModal] = useState(false); const [createForm, setCreateForm] = useState({ tenantId: '', username: '', password: '', fullName: '', role: 'Teacher', }); const [createLoading, setCreateLoading] = useState(false); // Reset Password Modal const [resettingUser, setResettingUser] = useState(null); const [newPassword, setNewPassword] = useState(''); const [resetLoading, setResetLoading] = useState(false); // Action Loading tracking const [actionLoading, setActionLoading] = useState(null); const loadData = async () => { try { const [uData, tData] = await Promise.all([ api.getUsers(selectedTenant || undefined, selectedRole || undefined), api.getTenants(), ]); setUsers(uData); setTenants(tData); } catch (err: any) { console.error('Failed to load user management data', err); } finally { setLoading(false); } }; useEffect(() => { loadData(); }, [selectedTenant, selectedRole]); const handleCreate = async (e: React.FormEvent) => { e.preventDefault(); if (!createForm.tenantId || !createForm.username || !createForm.password || !createForm.fullName) { setMessage({ text: '请填写所有必填字段', success: false }); return; } setCreateLoading(true); try { await api.createUser(createForm); setMessage({ text: `用户 [${createForm.username}] 创建成功!`, success: true }); setShowCreateModal(false); setCreateForm({ tenantId: tenants[0]?.id || '', username: '', password: '', fullName: '', role: 'Teacher', }); loadData(); } catch (err: any) { setMessage({ text: err.message || '创建用户失败', success: false }); } finally { setCreateLoading(false); } }; const handleResetPassword = async (e: React.FormEvent) => { e.preventDefault(); if (!resettingUser || !newPassword.trim()) return; setResetLoading(true); try { await api.resetPassword(resettingUser.id, newPassword.trim()); setMessage({ text: `用户 [${resettingUser.username}] 的密码已重置成功`, success: true }); setResettingUser(null); setNewPassword(''); } catch (err: any) { setMessage({ text: err.message || '重置密码失败', success: false }); } finally { setResetLoading(false); } }; const handleToggleLock = async (user: UserAdmin) => { const nextState = !user.isLocked; const confirmPrompt = nextState ? `确定要锁定账号 [${user.username}] 吗?锁定后该用户将无法登录系统。` : `确定要解锁账号 [${user.username}] 吗?`; if (!window.confirm(confirmPrompt)) return; setActionLoading(`lock_${user.id}`); try { await api.setUserLock(user.id, nextState); setMessage({ text: `用户 [${user.username}] 已成功${nextState ? '锁定' : '解锁'}`, success: true, }); loadData(); } catch (err: any) { setMessage({ text: err.message || '操作失败', success: false }); } finally { setActionLoading(null); } }; const handleDeleteUser = async (user: UserAdmin) => { if (user.role === 'SuperAdmin') { alert('超级管理员账号不可删除'); return; } if (!window.confirm(`警告:确定要永久删除用户 [${user.username} (${user.fullName})] 吗?此操作不可逆!`)) { return; } setActionLoading(`delete_${user.id}`); try { await api.deleteUser(user.id); setMessage({ text: `用户 [${user.username}] 已被删除`, success: true }); loadData(); } catch (err: any) { setMessage({ text: err.message || '删除用户失败', success: false }); } finally { setActionLoading(null); } }; const filteredUsers = users.filter((u) => { const matchesSearch = u.username.toLowerCase().includes(search.toLowerCase()) || u.fullName.toLowerCase().includes(search.toLowerCase()) || u.tenantName.toLowerCase().includes(search.toLowerCase()); return matchesSearch; }); return (
{/* Header */}

多租户统一用户中枢

全网教职工与校级管理员统一管控,支持跨校账号开户、密码强行重置、异常封禁与权限审计

{/* Alert Banner */} {message && (
{message.success ? ( ) : ( )} {message.text}
)} {/* Filter Toolbar */}
{/* Search */}
setSearch(e.target.value)} placeholder="搜索用户名、姓名或学校..." className="bg-transparent border-none text-xs text-white placeholder-slate-500 focus:outline-none w-full" />
{/* Tenant Filter */}
{/* Role Filter */}
{/* Users Table */}
{filteredUsers.length === 0 ? ( ) : ( filteredUsers.map((u) => ( )) )}
用户姓名 / 登录名 归属学校 角色身份 账号状态 最近登录 生命周期操作
{loading ? '正在同步用户中枢...' : '暂无匹配的用户'}
{u.fullName}
{u.username}
{u.tenantName}
{u.tenantId}
{u.role === 'SuperAdmin' ? ( 超级管理员 ) : u.role === 'SchoolAdmin' ? ( 校区管理员 ) : ( 授课老师 )} {u.isLocked ? ( 已锁定封禁 ) : ( 正常 )} {u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString() : '尚未登录'}
{/* Reset Password */} {/* Lock / Unlock */} {u.role !== 'SuperAdmin' && ( )} {/* Delete User */} {u.role !== 'SuperAdmin' && ( )}
{/* Create User Modal */} {showCreateModal && (

开通新用户账号

平台超级管理员只可通过系统底层配置文件委任,禁止通过控制台赋予。

setCreateForm({ ...createForm, username: e.target.value })} className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />
setCreateForm({ ...createForm, fullName: e.target.value })} className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />
setCreateForm({ ...createForm, password: e.target.value })} className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />
)} {/* Reset Password Modal */} {resettingUser && (

重置用户密码: {resettingUser.username}

为归属于 [{resettingUser.tenantName}] 的 [{resettingUser.fullName}] 强行设置新密码。

setNewPassword(e.target.value)} className="w-full px-3 py-2 rounded-xl bg-slate-800 border border-slate-700 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" />
)}
); }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/pages/admin/EmergencyBroadcast.tsx SIZE: 11888 chars ===================================================================== */ import React, { useEffect, useState } from 'react'; import { api } from '../../api/client'; import { TenantAdmin, EmergencyBroadcastRequest } from '../../types'; import { Radio, AlertTriangle, Send, Volume2, Vibrate, Clock, Building2, CheckCircle2, ShieldAlert, Flame, CloudRain, Users, Megaphone } from 'lucide-react'; export const EmergencyBroadcast: React.FC = () => { const [tenants, setTenants] = useState([]); const [loading, setLoading] = useState(true); const [submitting, setSubmitting] = useState(false); const [result, setResult] = useState<{ dispatchedCount: number; targetSchools: number; message: string; success: boolean; } | null>(null); const [form, setForm] = useState({ tenantId: '', title: '⚠️ 全校紧急预警通报', message: '', voice: true, shake: true, durationSeconds: 30, }); const templates = [ { title: '⚠️ 消防紧急疏散演练', content: '全体师生请注意:现在进行全校紧急消防演练,请任课老师组织学生按预定疏散路线迅速、有序撤离至操场,不要慌乱!', duration: 60, shake: true, voice: true, icon: Flame, }, { title: '⛈️ 恶劣雷雨大风避险通报', content: '气象台发布雷电暴雨黄色预警,请各班立即紧闭门窗,切断教室非必要电器电源,严禁学生前往走廊与室外活动!', duration: 45, shake: true, voice: true, icon: CloudRain, }, { title: '📢 临时紧急集合通知', content: '请全体班主任与班长立即到行政楼二楼报告厅参加紧急安全调度会议,其余同学保持教室内安静自习。', duration: 30, shake: false, voice: true, icon: Users, }, { title: '🔔 全校临时作息调整', content: '因突发教学安排,今天下午放学时间调整为 16:30,请任课老师提醒学生整理个人物品按时离校。', duration: 30, shake: false, voice: true, icon: Megaphone, }, ]; useEffect(() => { const fetchTenants = async () => { try { const data = await api.getTenants(); setTenants(data); } catch (err) { console.error('Failed to load tenants', err); } finally { setLoading(false); } }; fetchTenants(); }, []); const handleApplyTemplate = (tpl: typeof templates[0]) => { setForm((prev) => ({ ...prev, title: tpl.title, message: tpl.content, durationSeconds: tpl.duration, shake: tpl.shake, voice: tpl.voice, })); }; const handleBroadcast = async (e: React.FormEvent) => { e.preventDefault(); if (!form.message.trim()) { alert('请输入广播通知正文'); return; } const targetDesc = form.tenantId ? `指定学校 [${tenants.find((t) => t.id === form.tenantId)?.name || form.tenantId}]` : '全网所有学校与所有教室大屏 (全域群发)'; const confirmed = window.confirm( `⚠️ 极高优先级应急调度确认:\n\n目标受众: ${targetDesc}\n标题: ${form.title}\n时长: ${form.durationSeconds} 秒\n语音播报: ${form.voice ? '是' : '否'}\n强震颤: ${form.shake ? '是' : '否'}\n\n此指令将穿透静音模式并以最高置顶层级在所有终端大屏弹出!确定立即下发吗?` ); if (!confirmed) return; setSubmitting(true); setResult(null); try { const res = await api.sendEmergencyBroadcast({ ...form, tenantId: form.tenantId || undefined, }); setResult({ dispatchedCount: res.dispatchedCount, targetSchools: res.targetSchools, message: res.message, success: true, }); setForm((prev) => ({ ...prev, message: '' })); } catch (err: any) { setResult({ dispatchedCount: 0, targetSchools: 0, message: err.message || '应急广播下发失败', success: false, }); } finally { setSubmitting(false); } }; return (
{/* Header */}

全域紧急应急广播

超级管理员最高优先调度通道,覆盖全网多校区所有教室大屏终端,支持强置顶、TTS 语音播报与视效抖动

{/* Result Banner */} {result && (
{result.success ? ( ) : ( )} {result.message}
)} {/* Quick Templates */}

应急广播预设模板 (点击快速填装)

{templates.map((tpl, i) => { const Icon = tpl.icon; return ( ); })}
{/* Form Panel */}
{/* Target Scope */}
setForm({ ...form, title: e.target.value })} className="w-full px-3.5 py-2.5 rounded-xl bg-slate-900/80 border border-slate-700 text-sm text-white focus:outline-none focus:border-indigo-500" placeholder="例如: ⚠️ 全校紧急避险预警" />
{/* Broadcast Message */}