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 ClassNotify.Shared.Validation; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using ClassNotify.Server.Hubs; 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? InstallationId { get; set; } public string? PhysicalDeviceKey { get; set; } public string? Hostname { get; set; } public string? RemoteIp { get; set; } public string? ClientVersion { get; set; } public DateTimeOffset LastHeartbeat { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset ConnectedAt { get; set; } = DateTimeOffset.UtcNow; public LiveConnectionInfo(string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion, DateTimeOffset lastHeartbeat, string? installationId = null, string? physicalDeviceKey = null) { ConnectionId = connectionId; DeviceId = deviceId; TenantId = tenantId; ClassroomId = classroomId; Hostname = hostname; RemoteIp = remoteIp; ClientVersion = clientVersion; LastHeartbeat = lastHeartbeat; InstallationId = installationId; PhysicalDeviceKey = physicalDeviceKey; ConnectedAt = DateTimeOffset.UtcNow; } } public class SecurityService : ISecurityService { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly IDataProtector _protector; private readonly IPasswordHasher _passwordHasher; private readonly JwtOptions _jwtOptions; private readonly byte[] _deviceTrialHmacKeyBytes; // In-memory real-time SignalR live connection registries (NOT in PostgreSQL) private readonly ConcurrentDictionary _liveConnections = new(); private readonly ConcurrentDictionary _deviceToConnection = new(); private readonly ConcurrentDictionary _installationToConnection = new(); private readonly ConcurrentDictionary _physicalKeyToConnection = new(); private readonly ConcurrentDictionary _connectionTenantMap = new(); // Heartbeat DB update throttle map (at most once every 30s per device) private readonly ConcurrentDictionary _lastHeartbeatDbUpdate = new(); // Revoked/stale connections tracking for fail-closed authorization enforcement (Turn 73 Blocker 1 & Turn 76) private readonly ConcurrentDictionary _revokedConnections = new(); public SecurityService( IServiceScopeFactory scopeFactory, IDataProtectionProvider dataProtectionProvider, IPasswordHasher passwordHasher, IOptions jwtOptions, IConfiguration configuration, IWebHostEnvironment env, ILogger logger) { _scopeFactory = scopeFactory; _logger = logger; _protector = dataProtectionProvider.CreateProtector("ClassNotify.DeviceTokens.v1"); _passwordHasher = passwordHasher; _jwtOptions = jwtOptions.Value; var rawKey = configuration?["Security:DeviceTrialHmacKey"] ?? configuration?["Security__DeviceTrialHmacKey"] ?? Environment.GetEnvironmentVariable("CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY") ?? configuration?["CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY"]; _deviceTrialHmacKeyBytes = GetDeviceTrialHmacKeyBytes(rawKey, env?.IsDevelopment() ?? true); } #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; user.TokenVersion++; // Enforce Single Sign-On session replacement: supersedes all previous sessions! await db.SaveChangesAsync(); _logger.LogInformation("User '{Username}' ({UserId}) successfully authenticated from IP {RemoteIp}.", normalizedUser, user.Id, remoteIp ?? "unknown"); var userTenant = await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == user.TenantId); if (user.MustChangePassword) { if (user.TemporaryPasswordExpiresAtUtc.HasValue && user.TemporaryPasswordExpiresAtUtc.Value < DateTimeOffset.UtcNow) { _logger.LogWarning("Authentication rejected: Temporary password expired for user '{Username}'.", normalizedUser); return new TeacherLoginResultDto { Success = false, ErrorMessage = "临时密码已过期,请联系管理员重新重置" }; } var changeToken = GenerateJwtToken(user, userTenant, isPasswordChangeOnly: true); return new TeacherLoginResultDto { Success = true, PasswordChangeRequired = true, PasswordChangeToken = changeToken, Token = changeToken, UserId = user.Id, FullName = user.FullName, TenantId = user.TenantId, TenantType = userTenant?.TenantType ?? "School", TenantName = userTenant?.TenantType == "Personal" ? null : userTenant?.Name, Role = "PasswordChangeRequired", ErrorMessage = "管理员已为您重置临时密码,首次登录请先设置您的个人最终密码" }; } var token = GenerateJwtToken(user, userTenant, isPasswordChangeOnly: false); return new TeacherLoginResultDto { Success = true, Token = token, UserId = user.Id, FullName = user.FullName, TenantId = user.TenantId, TenantType = userTenant?.TenantType ?? "School", TenantName = userTenant?.TenantType == "Personal" ? null : userTenant?.Name, Role = user.Role }; } public async Task RegisterPersonalTeacherAsync(RegisterPersonalTeacherDto dto, string? remoteIp = null) { if (dto == null) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "注册参数不可为空" }; } var username = dto.Username?.Trim(); if (string.IsNullOrWhiteSpace(username) || username.Length < 3 || username.Length > 64) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "用户名长度必须在 3 至 64 个字符之间" }; } if (!System.Text.RegularExpressions.Regex.IsMatch(username, @"^[a-zA-Z0-9_\-\.@]+$")) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "用户名仅允许包含字母、数字、下划线、减号、点或@" }; } if (string.IsNullOrWhiteSpace(dto.Password) || dto.Password.Length < 8 || dto.Password.Length > 128) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "密码长度必须在 8 至 128 个字符之间" }; } var fullName = dto.FullName?.Trim(); if (string.IsNullOrWhiteSpace(fullName) || fullName.Length < 2 || fullName.Length > 50) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "请填写教师姓名或称谓 (2 至 50 个字符)" }; } var phone = dto.PhoneNumber?.Trim(); if (!string.IsNullOrWhiteSpace(phone) && phone.Length > 20) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "手机号码长度不能超过 20 位" }; } var recoveryEmail = dto.RecoveryEmail?.Trim(); if (!string.IsNullOrWhiteSpace(recoveryEmail)) { if (recoveryEmail.Length > 128 || !new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(recoveryEmail)) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "备用邮箱格式不正确" }; } } var normalizedUser = username.ToLowerInvariant(); var normalizedName = fullName; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var exists = await db.Users.AnyAsync(u => u.Username.ToLower() == normalizedUser); if (exists) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "该用户名已被使用,请换一个用户名" }; } using var tx = await db.Database.BeginTransactionAsync(); try { bool isSchoolAdmin = string.Equals(dto.AccountType, "SchoolAdmin", StringComparison.OrdinalIgnoreCase); var tenantPrefix = isSchoolAdmin ? "t_s_" : "t_p_"; var tenantType = isSchoolAdmin ? "School" : "Personal"; var userRole = isSchoolAdmin ? "SchoolAdmin" : "TenantOwner"; var tenantId = tenantPrefix + Guid.NewGuid().ToString("N")[..16]; string spaceTitle; if (isSchoolAdmin) { spaceTitle = string.IsNullOrWhiteSpace(dto.SchoolName) ? $"{normalizedName}所管理的学校" : dto.SchoolName.Trim(); } else { spaceTitle = string.IsNullOrWhiteSpace(dto.SpaceName) ? $"{normalizedName}的教学空间" : dto.SpaceName.Trim(); } var newTenant = new Tenant { Id = tenantId, Name = spaceTitle, TenantType = tenantType, IsActive = true, CreatedAt = DateTimeOffset.UtcNow }; db.Tenants.Add(newTenant); var now = DateTimeOffset.UtcNow; var userId = "usr_" + Guid.NewGuid().ToString("N")[..16]; var rawRecoveryKey = GenerateRecoveryKey(); var newUser = new User { Id = userId, TenantId = tenantId, Username = normalizedUser, FullName = normalizedName, Role = userRole, IsLocked = false, TokenVersion = 1, RecoveryEmail = string.IsNullOrWhiteSpace(recoveryEmail) ? null : recoveryEmail.ToLowerInvariant(), EmailVerified = false, RecoveryKeyHash = HashRecoveryKey(rawRecoveryKey), RecoveryKeyCreatedAtUtc = now, CreatedAt = now, LastLoginAt = now, TrialEndsAt = null // 从首次绑定大屏开始计算 7 天试用,未绑定前不提前消耗 }; newUser.PasswordHash = _passwordHasher.HashPassword(newUser, dto.Password); db.Users.Add(newUser); string? activeCodeToReturn = null; string? activeCodeMasked = null; // Handle optional existing activation code binding (兼容学校管理员或已有充值码导入) if (!string.IsNullOrWhiteSpace(dto.ActivationCode)) { var inputCode = dto.ActivationCode.Trim().ToUpperInvariant(); var existingCode = await db.ActivationCodes.FirstOrDefaultAsync(c => c.Code == inputCode); if (existingCode == null) { return new TeacherLoginResultDto { Success = false, ErrorMessage = "所填大屏激活码不存在,请核对后再试" }; } if (existingCode.IsUsed || existingCode.Status == "Redeemed") { return new TeacherLoginResultDto { Success = false, ErrorMessage = "所填大屏激活码已被激活使用,如需重新绑定请在控制台进行认领" }; } existingCode.TenantId = tenantId; existingCode.AssignedTeacherId = userId; existingCode.AssignedTeacherName = normalizedName; existingCode.DistributionMethod = "TeacherAccount"; existingCode.AssignedAt = now; existingCode.AssignedByUserId = "SystemRegistration"; activeCodeToReturn = existingCode.Code; activeCodeMasked = MaskCode(existingCode.Code); db.ActivationCodeAssignments.Add(new ActivationCodeAssignment { Id = "asg_" + Guid.NewGuid().ToString("N")[..16], TenantId = tenantId, ActivationCodeId = existingCode.Id, CodeMasked = activeCodeMasked, TeacherUserId = userId, TeacherName = normalizedName, AssignedByUserId = "SystemRegistration", AssignedAtUtc = now, Reason = "注册时填入并绑定已有激活码" }); } else if (isSchoolAdmin) { // 学校管理员注册时保留赠送首间班级试用激活码 string trialCode; do { trialCode = GenerateCanonicalActivationCode(); } while (await db.ActivationCodes.AnyAsync(c => c.Code == trialCode)); var trialCodeId = "act_" + Guid.NewGuid().ToString("N")[..16]; var trialCodeEntity = new ActivationCode { Id = trialCodeId, Code = trialCode, TenantId = tenantId, ClassroomId = string.Empty, TargetClassNameAtIssue = "待首次激活现场指定", AssignedTeacherId = userId, AssignedTeacherName = normalizedName, DistributionMethod = "TeacherAccount", AssignedAt = now, AssignedByUserId = "SystemRegistration", ExpiresAt = now.AddDays(30), RedeemBeforeUtc = now.AddDays(30), IsUsed = false, Status = "Issued", LicenseDurationDays = 7, LicenseTier = "Trial", Notes = "新注册学校管理员自动赠送首间班级7天试用激活码", Purpose = "PersonalProvisionAndLicense", IsSignupTrial = true }; db.ActivationCodes.Add(trialCodeEntity); activeCodeToReturn = trialCode; activeCodeMasked = MaskCode(trialCode); db.ActivationCodeAssignments.Add(new ActivationCodeAssignment { Id = "asg_" + Guid.NewGuid().ToString("N")[..16], TenantId = tenantId, ActivationCodeId = trialCodeId, CodeMasked = activeCodeMasked, TeacherUserId = userId, TeacherName = normalizedName, AssignedByUserId = "SystemRegistration", AssignedAtUtc = now, Reason = "注册自动发放7天试用激活码" }); } // Turn 112: 个人独立教师全面采用 8 位大屏数字配对码体系,注册阶段停止生成无用字母大屏激活码 await db.SaveChangesAsync(); await tx.CommitAsync(); _logger.LogInformation("Account registered successfully: {Username} ({UserId}), space: {TenantId} ({SpaceName}), IP: {RemoteIp}, Code: {MaskedCode}", normalizedUser, userId, tenantId, spaceTitle, remoteIp ?? "unknown", activeCodeMasked); var token = GenerateJwtToken(newUser, newTenant); return new TeacherLoginResultDto { Success = true, Token = token, UserId = newUser.Id, FullName = newUser.FullName, TenantId = newUser.TenantId, TenantType = tenantType, TenantName = isSchoolAdmin ? spaceTitle : null, Role = newUser.Role, Username = newUser.Username, TrialActivationCodeMasked = activeCodeMasked, TrialActivationCodeId = activeCodeToReturn, RecoveryKey = FormatRecoveryKey(rawRecoveryKey), IsFirstRegistration = true }; } catch (DbUpdateException ex) { await tx.RollbackAsync(); _logger.LogWarning(ex, "Username unique constraint conflict on DB insert for {Username}", normalizedUser); return new TeacherLoginResultDto { Success = false, ErrorMessage = "该用户名已被使用,请换一个用户名" }; } catch (Exception ex) { await tx.RollbackAsync(); _logger.LogError(ex, "Failed to register personal teacher {Username}", normalizedUser); return new TeacherLoginResultDto { Success = false, ErrorMessage = "注册失败,请稍后重试" }; } } 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) 无效或格式不正确" }; } if (!string.IsNullOrWhiteSpace(dto.CustomClassName)) { var (valid, errorMsg) = ClassNameValidator.Validate(dto.CustomClassName); if (!valid) { return new DeviceActivationResultDto { Success = false, ErrorMessage = errorMsg }; } } var rawCode = dto.ActivationCode.Trim().ToUpperInvariant(); var cleanCode = rawCode.Replace("-", "").Replace(" ", ""); var formattedCode = cleanCode.Length == 8 ? $"{cleanCode[..4]}-{cleanCode[4..]}" : rawCode; 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 == rawCode || c.Code == cleanCode || c.Code == formattedCode); if (code == null) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码无效" }; } if (code.Status == "Revoked" || code.RevokedAtUtc.HasValue) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "该激活码已被吊销作废" }; } if (code.IsUsed) { // P0-09 / P1-02 Idempotency Rule: If same installationId OR same physical hardware, return original device credentials bool isSameInstallation = !string.IsNullOrEmpty(code.InstallationId) && string.Equals(code.InstallationId, normalizedInstId, StringComparison.OrdinalIgnoreCase); bool isSamePhysicalHardware = false; if (!isSameInstallation && !string.IsNullOrWhiteSpace(dto.HardwareComponentsHash)) { var hwHash = dto.HardwareComponentsHash.Trim(); if (!string.IsNullOrEmpty(code.UsedByDeviceId)) { isSamePhysicalHardware = await db.Devices.AnyAsync(d => d.Id == code.UsedByDeviceId && d.HardwareComponentsHash == hwHash); } else if (!string.IsNullOrEmpty(code.InstallationId)) { isSamePhysicalHardware = await db.Devices.AnyAsync(d => d.InstallationId == code.InstallationId && d.HardwareComponentsHash == hwHash); } } if (isSameInstallation || isSamePhysicalHardware) { var existingDev = await db.Devices.FirstOrDefaultAsync(d => (!string.IsNullOrEmpty(code.UsedByDeviceId) && d.Id == code.UsedByDeviceId) || d.InstallationId == normalizedInstId || (!string.IsNullOrWhiteSpace(dto.HardwareComponentsHash) && d.HardwareComponentsHash == dto.HardwareComponentsHash.Trim())); var existingCred = await db.DeviceCredentials.FirstOrDefaultAsync(c => (existingDev != null && c.DeviceId == existingDev.Id) || (!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 = "解密设备凭据失败,请联系管理员" }; } // If reinstalled on same physical hardware, update installationId mapping if (isSamePhysicalHardware) { existingDev.InstallationId = normalizedInstId; existingCred.InstallationId = normalizedInstId; code.InstallationId = normalizedInstId; } _logger.LogInformation("Idempotent activation retry for InstallationId {InstallationId} (HardwareMatch={HwMatch}), returning recovered token for Device {DeviceId}", normalizedInstId, isSamePhysicalHardware, existingDev.Id); if (!string.IsNullOrWhiteSpace(dto.CustomClassName)) { existingCls.DisplayName = dto.CustomClassName.Trim(); await db.SaveChangesAsync(); } var existingTenant = await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == existingCls.TenantId); return new DeviceActivationResultDto { Success = true, DeviceId = existingDev.Id, DeviceToken = recoveredToken, TenantId = existingCls.TenantId, TenantType = existingTenant?.TenantType ?? "School", TenantName = existingTenant?.TenantType == "Personal" ? null : existingTenant?.Name, 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 = "激活码已过期" }; } if (code.RedeemBeforeUtc.HasValue && code.RedeemBeforeUtc.Value < DateTimeOffset.UtcNow) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码已超过最晚兑换期限 (RedeemBefore),无法使用" }; } var targetDev = await db.Devices.FirstOrDefaultAsync(d => d.InstallationId == normalizedInstId); if (targetDev == null && !string.IsNullOrWhiteSpace(dto.HardwareComponentsHash)) { var hwHash = dto.HardwareComponentsHash.Trim(); targetDev = await db.Devices.FirstOrDefaultAsync(d => d.HardwareComponentsHash == hwHash); } DateTimeOffset? trialEndsAtUtc = null; DeviceTrialLedger? newTrialLedger = null; if (code.LicenseTier == "Trial" || code.IsSignupTrial) { if (string.IsNullOrWhiteSpace(code.Id)) { code.Id = "act_" + Guid.NewGuid().ToString("N")[..16]; } var hardwareSeed = !string.IsNullOrWhiteSpace(dto.HardwareComponentsHash) ? dto.HardwareComponentsHash.Trim() : normalizedInstId; var fpVersion = dto.FingerprintVersion > 0 ? dto.FingerprintVersion : 1; var serverTrialKey = ComputeDeviceTrialKey(fpVersion, hardwareSeed); var existingTrial = await db.DeviceTrialLedgers.FirstOrDefaultAsync(l => l.DeviceTrialKey == serverTrialKey); var deviceHasUsedTrial = (targetDev != null && targetDev.TrialUsed) || (!string.IsNullOrEmpty(normalizedInstId) && await db.DeviceLicenses.AnyAsync(l => l.InstallationId == normalizedInstId && l.LicenseTier == "Trial")); if (existingTrial != null || deviceHasUsedTrial) { // Check if this is an idempotent re-activation of the SAME activation code that this device already used bool isSameCodeReactivation = (code.IsUsed && code.UsedByDeviceId != null && targetDev != null && code.UsedByDeviceId == targetDev.Id) || (code.IsUsed && existingTrial != null && code.UsedByDeviceId == existingTrial.OriginalDeviceId) || (existingTrial != null && !string.IsNullOrEmpty(existingTrial.SourceActivationCodeId) && existingTrial.SourceActivationCodeId == code.Id); bool hasValidOverride = existingTrial != null && existingTrial.OverrideState == "Granted" && existingTrial.OverrideRemainingUses > 0 && existingTrial.OverrideExpiresAtUtc.HasValue && existingTrial.OverrideExpiresAtUtc.Value > DateTimeOffset.UtcNow; if (hasValidOverride && existingTrial != null) { // Atomically consume override entitlement within this transaction existingTrial.OverrideRemainingUses--; existingTrial.OverrideState = "Consumed"; existingTrial.OverrideConsumedAtUtc = DateTimeOffset.UtcNow; existingTrial.UpdatedAtUtc = DateTimeOffset.UtcNow; existingTrial.Status = "Active"; var trialDays = code.LicenseDurationDays ?? 7; existingTrial.TrialEndsAtUtc = DateTimeOffset.UtcNow.AddDays(trialDays); trialEndsAtUtc = existingTrial.TrialEndsAtUtc; await LogAdminAuditAsync("System", "System", "ADMIN_TRIAL_OVERRIDE_CONSUMED", "DeviceTrialLedger", existingTrial.Id, $"特批试用额度已消费: 机器 (Key={MaskString(serverTrialKey)}) 凭超管特批成功核销试用码 {MaskCode(code.Code)}", null); } else if (!isSameCodeReactivation) { // Increment blocked attempt counter & update timestamp if (existingTrial != null) { existingTrial.BlockedAttemptCount++; existingTrial.LastBlockedAtUtc = DateTimeOffset.UtcNow; existingTrial.UpdatedAtUtc = DateTimeOffset.UtcNow; await db.SaveChangesAsync(); await tx.CommitAsync(); } await LogAdminAuditAsync("System", "System", "TRIAL_REPEAT_BLOCKED", "DeviceTrialLedger", existingTrial?.Id ?? "UNKNOWN", $"拦截重复试用尝试: 机器 Key={MaskString(serverTrialKey)}, 拦截计数={existingTrial?.BlockedAttemptCount ?? 1}", null); _logger.LogWarning("Device trial rejected: physical device (Key: {TrialKey}, InstId: {InstId}) has already consumed a trial ledger. Rejecting new trial voucher {Code}.", MaskString(serverTrialKey), MaskString(normalizedInstId), MaskCode(code.Code)); return new DeviceActivationResultDto { Success = false, ErrorMessage = "该物理设备已使用过免费试用,无法重复使用试用码,请使用正式授权码" }; } else if (existingTrial != null && (existingTrial.Status == "Expired" || existingTrial.TrialEndsAtUtc <= DateTimeOffset.UtcNow)) { _logger.LogWarning("Device trial rejected: physical device (Key: {TrialKey}) trial expired at {TrialEndsAt}. Voucher not consumed.", MaskString(serverTrialKey), existingTrial.TrialEndsAtUtc); return new DeviceActivationResultDto { Success = false, ErrorMessage = "该物理设备的免费试用期已结束,请使用正式授权码" }; } else { trialEndsAtUtc = existingTrial?.TrialEndsAtUtc; } } else { var trialDays = code.LicenseDurationDays ?? 7; trialEndsAtUtc = DateTimeOffset.UtcNow.AddDays(trialDays); newTrialLedger = new DeviceTrialLedger { Id = "dtl_" + Guid.NewGuid().ToString("N")[..16], DeviceTrialKey = serverTrialKey, FingerprintVersion = fpVersion, FirstTrialStartedAtUtc = DateTimeOffset.UtcNow, TrialEndsAtUtc = trialEndsAtUtc.Value, OriginalDeviceId = string.Empty, // Will be set once device is resolved OriginalTenantId = code.TenantId, OriginalUserId = code.AssignedTeacherId, Status = "Active", SourceActivationCodeId = code.Id, CreatedAtUtc = DateTimeOffset.UtcNow }; db.DeviceTrialLedgers.Add(newTrialLedger); } } var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == code.TenantId); if (tenant == null) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "激活码关联的机构/租户不存在,拒绝激活 (Fail-Closed)" }; } Classroom? cls = null; if (!string.IsNullOrWhiteSpace(code.ClassroomId)) { // When ClassroomId is present, existing classroom must resolve within the same tenant. cls = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == code.TenantId && c.Id == code.ClassroomId); if (cls == null) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "绑定的班级不存在或不属于当前机构" }; } if (!string.IsNullOrWhiteSpace(dto.CustomClassName)) { cls.DisplayName = dto.CustomClassName.Trim(); } } else { // ChatGPT Turn 54 Strict Invariant: ONLY explicit PersonalBootstrap voucher allows creating classroom on-the-fly var canBootstrapClassroom = tenant.TenantType == "Personal" && string.IsNullOrWhiteSpace(code.ClassroomId) && (code.Purpose == "PersonalProvisionAndLicense" || code.Purpose == "BootstrapClassroomAndDevice"); if (!canBootstrapClassroom) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "此激活码未绑定班级,且不具备现场建班权限" }; } if (string.IsNullOrWhiteSpace(dto.CustomClassName)) { return new DeviceActivationResultDto { Success = false, ErrorMessage = "首次绑定班级大屏,请输入班级名称 (例如:810班)" }; } var (valid, errorMsg) = ClassNameValidator.Validate(dto.CustomClassName); if (!valid) { return new DeviceActivationResultDto { Success = false, ErrorMessage = errorMsg }; } var newClassId = "cls_" + Guid.NewGuid().ToString("N")[..16]; cls = new Classroom { Id = newClassId, TenantId = code.TenantId, DisplayName = dto.CustomClassName.Trim(), CreatedAt = DateTimeOffset.UtcNow }; db.Classrooms.Add(cls); code.ClassroomId = cls.Id; code.TargetClassNameAtIssue = cls.DisplayName; } var rawToken = $"dtoken_{Guid.NewGuid():N}"; var tokenHash = HashToken(rawToken); DateTimeOffset? licensedUntil; if (code.LicenseTier == "Trial" || code.IsSignupTrial) { licensedUntil = trialEndsAtUtc ?? DateTimeOffset.UtcNow.AddDays(code.LicenseDurationDays ?? 7); } else { licensedUntil = code.LicenseDurationDays.HasValue ? DateTimeOffset.UtcNow.AddDays(code.LicenseDurationDays.Value) : null; } string tier = string.IsNullOrEmpty(code.LicenseTier) ? "Trial" : code.LicenseTier; string deviceId; Device device; if (targetDev != null) { deviceId = targetDev.Id; targetDev.TenantId = code.TenantId; targetDev.ClassroomId = code.ClassroomId; targetDev.DeviceTokenHash = tokenHash; targetDev.InstallationId = normalizedInstId; if (!string.IsNullOrWhiteSpace(dto.HardwareComponentsHash)) { targetDev.HardwareComponentsHash = dto.HardwareComponentsHash.Trim(); } targetDev.Hostname = dto.Hostname; targetDev.IsActive = true; targetDev.LicensedUntil = licensedUntil; targetDev.LicenseTier = tier; targetDev.TrialUsed = targetDev.TrialUsed || (tier == "Trial"); targetDev.BindingStartedAtUtc = DateTimeOffset.UtcNow; // Blocker A: Dedicated rebind epoch boundary; CreatedAt preserved as immutable entity creation time! device = targetDev; } else { deviceId = "dev_" + Guid.NewGuid().ToString("N")[..16]; device = new Device { Id = deviceId, TenantId = code.TenantId, ClassroomId = code.ClassroomId, DeviceTokenHash = tokenHash, InstallationId = normalizedInstId, HardwareComponentsHash = !string.IsNullOrWhiteSpace(dto.HardwareComponentsHash) ? dto.HardwareComponentsHash.Trim() : null, Hostname = dto.Hostname, IsActive = true, LicensedUntil = licensedUntil, LicenseTier = tier, TrialUsed = tier == "Trial", CreatedAt = DateTimeOffset.UtcNow, BindingStartedAtUtc = DateTimeOffset.UtcNow }; db.Devices.Add(device); } if (newTrialLedger != null && string.IsNullOrEmpty(newTrialLedger.OriginalDeviceId)) { newTrialLedger.OriginalDeviceId = deviceId; } var targetCred = await db.DeviceCredentials.FirstOrDefaultAsync(c => c.DeviceId == deviceId || c.InstallationId == normalizedInstId); if (targetCred != null) { targetCred.DeviceId = deviceId; targetCred.InstallationId = normalizedInstId; targetCred.DeviceTokenHash = tokenHash; targetCred.EncryptedRecoverableToken = _protector.Protect(rawToken); targetCred.RotatedAt = DateTimeOffset.UtcNow; } else { var credRecord = new DeviceCredentialRecord { DeviceId = deviceId, InstallationId = normalizedInstId, DeviceTokenHash = tokenHash, EncryptedRecoverableToken = _protector.Protect(rawToken), CreatedAt = DateTimeOffset.UtcNow }; db.DeviceCredentials.Add(credRecord); } var licRecord = new DeviceLicenseRecord { Id = $"lic_{Guid.NewGuid():N}"[..16], TenantId = code.TenantId, DeviceId = deviceId, InstallationId = normalizedInstId, ClassroomId = code.ClassroomId, Action = "ACTIVATE", LicenseTier = tier, GrantedDays = code.LicenseDurationDays, PreviousLicensedUntil = null, NewLicensedUntil = licensedUntil, SourceActivationCode = code.Code, OperatorUsername = "DeviceSelfActivation", Reason = $"初次激活设备,授予 {tier} 授权 ({code.LicenseDurationDays?.ToString() ?? "永久"} 天)", CreatedAt = DateTimeOffset.UtcNow }; db.DeviceLicenses.Add(licRecord); code.IsUsed = true; code.Status = "Redeemed"; 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}, LicensedUntil: {LicensedUntil}, Tier: {Tier}, Code: {MaskedCode}]", deviceId, cls.TenantId, cls.Id, cls.DisplayName, normalizedInstId, licensedUntil, tier, MaskCode(code.Code)); return new DeviceActivationResultDto { Success = true, DeviceId = deviceId, DeviceToken = rawToken, TenantId = cls.TenantId, TenantType = tenant?.TenantType ?? "School", TenantName = tenant?.TenantType == "Personal" ? null : tenant?.Name, ClassId = cls.Id, ClassDisplayName = cls.DisplayName }; } catch (Exception ex) { await tx.RollbackAsync(); _logger.LogError(ex, "Exception during device activation transaction for code {MaskedCode}", MaskCode(rawCode)); 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; } public async Task<(Device Device, string RawDeviceToken)> EnsureDeviceProvisionedAsync(DeviceBootstrapRequestDto req) { var hwHash = (req.HardwareComponentsHash ?? "").Trim(); var instId = (req.InstallationId ?? "").Trim(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); Device? device = null; if (!string.IsNullOrEmpty(hwHash)) { device = await db.Devices.FirstOrDefaultAsync(d => d.HardwareComponentsHash == hwHash); } if (device == null && !string.IsNullOrEmpty(instId)) { device = await db.Devices.FirstOrDefaultAsync(d => d.InstallationId == instId); } string rawToken = ""; if (device == null) { var deviceId = "dev_" + Guid.NewGuid().ToString("N")[..16]; rawToken = $"dtoken_{Guid.NewGuid():N}"; var tokenHash = HashToken(rawToken); device = new Device { Id = deviceId, TenantId = "default", ClassroomId = "unbound", DeviceTokenHash = tokenHash, HardwareComponentsHash = !string.IsNullOrEmpty(hwHash) ? hwHash : null, InstallationId = !string.IsNullOrEmpty(instId) ? instId : $"inst_{Guid.NewGuid():N}"[..24], Hostname = req.Hostname, ClientVersion = req.ClientVersion ?? "2.5.0", IsActive = true, TrialUsed = false, CreatedAt = DateTimeOffset.UtcNow, BindingStartedAtUtc = DateTimeOffset.UtcNow, LicenseTier = "Trial" }; db.Devices.Add(device); var cred = new DeviceCredentialRecord { DeviceId = deviceId, InstallationId = device.InstallationId, DeviceTokenHash = tokenHash, EncryptedRecoverableToken = _protector.Protect(rawToken), CreatedAt = DateTimeOffset.UtcNow }; db.DeviceCredentials.Add(cred); await db.SaveChangesAsync(); _logger.LogInformation("Bootstrapped new unbound device {DeviceId} for hardware hash {HwHash}", deviceId, hwHash); } else { var cred = await db.DeviceCredentials.FirstOrDefaultAsync(c => c.DeviceId == device.Id); if (cred != null) { try { rawToken = _protector.Unprotect(cred.EncryptedRecoverableToken); } catch { rawToken = $"dtoken_{Guid.NewGuid():N}"; cred.EncryptedRecoverableToken = _protector.Protect(rawToken); cred.DeviceTokenHash = HashToken(rawToken); cred.RotatedAt = DateTimeOffset.UtcNow; device.DeviceTokenHash = cred.DeviceTokenHash; } } else { rawToken = $"dtoken_{Guid.NewGuid():N}"; cred = new DeviceCredentialRecord { DeviceId = device.Id, InstallationId = device.InstallationId ?? instId, DeviceTokenHash = HashToken(rawToken), EncryptedRecoverableToken = _protector.Protect(rawToken), CreatedAt = DateTimeOffset.UtcNow }; db.DeviceCredentials.Add(cred); device.DeviceTokenHash = cred.DeviceTokenHash; } if (!string.IsNullOrEmpty(instId) && device.InstallationId != instId) { device.InstallationId = instId; cred.InstallationId = instId; } device.IsActive = true; await db.SaveChangesAsync(); _logger.LogInformation("Recovered existing device credentials for {DeviceId}", device.Id); } return (device, rawToken); } #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, TenantType = t.TenantType ?? "School" }; }).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) { var (valid, errorMsg) = ClassNameValidator.Validate(dto.DisplayName); if (!valid) { _logger.LogWarning("CreateClassroom rejected: Classroom name '{DisplayName}' failed validation: {Error}", dto.DisplayName, errorMsg); return false; } 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.Trim(), TenantId = tenantId, DisplayName = dto.DisplayName.Trim(), Grade = dto.Grade?.Trim(), RoomNumber = dto.RoomNumber?.Trim(), 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().ToString("N")[..16], 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().Where(d => d.IsActive); 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 tenantTypes = await db.Tenants.AsNoTracking().ToDictionaryAsync(t => t.Id, t => t.TenantType ?? "School"); var classrooms = await db.Classrooms.AsNoTracking().ToDictionaryAsync(c => $"{c.TenantId}_{c.Id}", c => c.DisplayName); var policy = scope.ServiceProvider.GetService>()?.Value ?? new ClassNotify.Server.Configuration.DeviceVersionPolicyOptions(); 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); tenantTypes.TryGetValue(d.TenantId, out var tType); classrooms.TryGetValue($"{d.TenantId}_{d.ClassroomId}", out var cName); var serviceVer = d.ServiceVersion; var clientVer = isOnline ? (connInfo?.ClientVersion ?? d.ClientVersion) : d.ClientVersion; var protocolVer = d.ProtocolVersion; var versionStatus = policy.EvaluateVersionStatus(serviceVer, clientVer, protocolVer); var licStatus = CalculateLicenseStatus(d); return new DeviceAdminDto { DeviceId = d.Id, TenantId = d.TenantId, TenantName = tName ?? d.TenantId, TenantType = tType ?? "School", ClassroomId = d.ClassroomId, ClassroomName = cName ?? d.ClassroomId, Hostname = d.Hostname, DisplayLabel = d.DisplayLabel, IsOnline = isOnline, LastHeartbeat = isOnline ? connInfo?.LastHeartbeat : d.LastHeartbeatAt, ClientVersion = clientVer, ServiceVersion = serviceVer, ProtocolVersion = protocolVer, OsVersion = d.OsVersion, Architecture = d.Architecture, VersionStatus = versionStatus, RemoteIp = isOnline ? connInfo?.RemoteIp : null, ServiceRunning = isOnline, ClientRunning = isOnline, LicensedUntil = d.LicensedUntil, LicenseTier = d.LicenseTier ?? "Trial", LicenseStatus = licStatus.Status, RemainingDays = licStatus.RemainingDays, RemainingHours = licStatus.RemainingHours }; }).ToList(); } public string ComputePhysicalDeviceKey(string hardwareFingerprint) { var clean = (hardwareFingerprint ?? "").Trim().ToLowerInvariant(); var payload = $"physical-device:v1:{clean}"; using var hmac = new HMACSHA256(_deviceTrialHmacKeyBytes); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); return Convert.ToHexString(hash); } public Task RegisterDeviceConnectionAsync( string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion, string? installationId = null, string? hardwareHash = null) { string? replacedConnectionId = null; // Physical endpoint key calculation (Domain separation: physical-device:v1:) string? physicalKey = !string.IsNullOrWhiteSpace(hardwareHash) ? ComputePhysicalDeviceKey(hardwareHash) : 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); } // T76-04: Displace any pre-existing connection for the same physical endpoint if (!string.IsNullOrEmpty(installationId) && _installationToConnection.TryGetValue(installationId, out var instOldConn) && instOldConn != connectionId) { _revokedConnections[instOldConn] = true; _liveConnections.TryRemove(instOldConn, out _); _logger.LogInformation("Evicted previous physical session {OldConnId} matching InstallationId {InstId}", instOldConn, installationId); } if (!string.IsNullOrEmpty(physicalKey) && _physicalKeyToConnection.TryGetValue(physicalKey, out var physOldConn) && physOldConn != connectionId) { _revokedConnections[physOldConn] = true; _liveConnections.TryRemove(physOldConn, out _); _logger.LogInformation("Evicted previous physical session {OldConnId} matching PhysicalDeviceKey", physOldConn); } _revokedConnections.TryRemove(connectionId, out _); _deviceToConnection[deviceId] = connectionId; if (!string.IsNullOrEmpty(installationId)) { _installationToConnection[installationId] = connectionId; } if (!string.IsNullOrEmpty(physicalKey)) { _physicalKeyToConnection[physicalKey] = connectionId; } var liveInfo = new LiveConnectionInfo(connectionId, deviceId, tenantId, classroomId, hostname, remoteIp, clientVersion, DateTimeOffset.UtcNow, installationId, physicalKey); _liveConnections[connectionId] = liveInfo; _connectionTenantMap[connectionId] = (tenantId, classroomId, deviceId); _logger.LogInformation("Device {DeviceId} connected via SignalR. ConnectionId={ConnId}, IP={RemoteIp}, InstId={InstId}", deviceId, connectionId, remoteIp, installationId); return Task.FromResult(new DeviceConnectionRegistrationResult(connectionId, replacedConnectionId)); } public Task UnregisterDeviceConnectionAsync(string connectionId) { _revokedConnections.TryRemove(connectionId, out _); if (_connectionTenantMap.TryRemove(connectionId, out var info)) { _liveConnections.TryRemove(connectionId, out var liveInfo); // Blocker 2 / T76-05: Atomic compare-and-remove to avoid deleting newer connection in a race var removed = ((ICollection>)_deviceToConnection) .Remove(new KeyValuePair(info.DeviceId, connectionId)); if (liveInfo?.InstallationId != null) { ((ICollection>)_installationToConnection) .Remove(new KeyValuePair(liveInfo.InstallationId, connectionId)); } if (liveInfo?.PhysicalDeviceKey != null) { ((ICollection>)_physicalKeyToConnection) .Remove(new KeyValuePair(liveInfo.PhysicalDeviceKey, connectionId)); } if (removed) { _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} is mapped to a newer connection)", connectionId, info.DeviceId); return Task.FromResult(false); } } return Task.FromResult(false); } public bool IsCurrentDeviceConnection(string deviceId, string connectionId) { if (_revokedConnections.ContainsKey(connectionId)) { return false; // Blocker 1: Fail-closed for revoked sockets } return _deviceToConnection.TryGetValue(deviceId, out var currentConnId) && currentConnId == connectionId; } public Task UpdateDeviceHeartbeatAsync(string connectionId, DeviceHeartbeatDto? heartbeat = null) { 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; if (heartbeat != null) { if (!string.IsNullOrEmpty(heartbeat.ServiceVersion)) dev.ServiceVersion = heartbeat.ServiceVersion; if (!string.IsNullOrEmpty(heartbeat.ClientVersion)) dev.ClientVersion = heartbeat.ClientVersion; if (heartbeat.ProtocolVersion > 0) dev.ProtocolVersion = heartbeat.ProtocolVersion; if (!string.IsNullOrEmpty(heartbeat.OsVersion)) dev.OsVersion = heartbeat.OsVersion; if (!string.IsNullOrEmpty(heartbeat.Architecture)) dev.Architecture = heartbeat.Architecture; dev.ClientProcessAvailable = heartbeat.ClientProcessAvailable; if (!string.IsNullOrEmpty(heartbeat.CorrelationId)) dev.LastHeartbeatCorrelationId = heartbeat.CorrelationId; } await db.SaveChangesAsync(); } } catch (Exception ex) { _logger.LogError(ex, "Failed to persist heartbeat update for device {DeviceId}", info.DeviceId); } }); } } return Task.CompletedTask; } public string? GetDeviceConnectionId(string deviceId) { return _deviceToConnection.TryGetValue(deviceId, out var connId) ? connId : null; } public Task InvalidateDeviceSessionAsync(string deviceId, string reason = "IdentityChanged") { return InvalidateDeviceSessionByEndpointAsync(deviceId, null, null, reason); } public async Task InvalidateDeviceSessionByEndpointAsync( string? deviceId, string? installationId, string? hardwareHash, string reason = "EndpointReactivated") { var targetConnIds = new HashSet(); if (!string.IsNullOrEmpty(deviceId) && _deviceToConnection.TryGetValue(deviceId, out var c1)) { targetConnIds.Add(c1); } if (!string.IsNullOrEmpty(installationId) && _installationToConnection.TryGetValue(installationId, out var c2)) { targetConnIds.Add(c2); } string? physKey = !string.IsNullOrWhiteSpace(hardwareHash) ? ComputePhysicalDeviceKey(hardwareHash) : null; if (!string.IsNullOrEmpty(physKey) && _physicalKeyToConnection.TryGetValue(physKey, out var c3)) { targetConnIds.Add(c3); } // Sweep _liveConnections for any matching installationId, physKey or deviceId foreach (var kvp in _liveConnections) { var live = kvp.Value; if ((!string.IsNullOrEmpty(deviceId) && live.DeviceId == deviceId) || (!string.IsNullOrEmpty(installationId) && live.InstallationId == installationId) || (!string.IsNullOrEmpty(physKey) && live.PhysicalDeviceKey == physKey)) { targetConnIds.Add(kvp.Key); } } if (targetConnIds.Count == 0) { _logger.LogInformation("No active SignalR sessions found to invalidate for Device {DeviceId}, Inst {InstId}, PhysKey {PhysKey} (Reason: {Reason})", deviceId, installationId, physKey, reason); return; } using var scope = _scopeFactory.CreateScope(); var hubContext = scope.ServiceProvider.GetService>(); foreach (var connId in targetConnIds) { _revokedConnections[connId] = true; _liveConnections.TryRemove(connId, out var info); _connectionTenantMap.TryRemove(connId, out _); if (info != null) { ((ICollection>)_deviceToConnection) .Remove(new KeyValuePair(info.DeviceId, connId)); if (info.InstallationId != null) ((ICollection>)_installationToConnection) .Remove(new KeyValuePair(info.InstallationId, connId)); if (info.PhysicalDeviceKey != null) ((ICollection>)_physicalKeyToConnection) .Remove(new KeyValuePair(info.PhysicalDeviceKey, connId)); } _logger.LogInformation("Invalidated SignalR session {ConnId} for Device {DeviceId}, Inst {InstId} (Reason: {Reason})", connId, info?.DeviceId ?? deviceId, info?.InstallationId ?? installationId, reason); if (hubContext != null) { try { if (info != null) { await hubContext.Groups.RemoveFromGroupAsync(connId, $"t:{info.TenantId}:c:{info.ClassroomId}"); await hubContext.Groups.RemoveFromGroupAsync(connId, $"t:{info.TenantId}:d:{info.DeviceId}"); } if (!string.IsNullOrEmpty(deviceId)) { await hubContext.Groups.RemoveFromGroupAsync(connId, $"dev_{deviceId}"); } await hubContext.Clients.Client(connId).DeviceSessionInvalidated(reason); } catch (Exception ex) { _logger.LogWarning(ex, "Error notifying invalidated session {ConnId}", connId); } } } } public async Task<(bool Success, string Message, string? NewClassName)> UpdateDeviceClassNameAsync( string deviceId, string newClassName, string operatorName, string operatorRole) { if (string.IsNullOrWhiteSpace(deviceId)) { return (false, "设备标识不可为空", null); } var (valid, errorMsg) = ClassNameValidator.Validate(newClassName); if (!valid) { return (false, errorMsg!, null); } var cleanName = newClassName.Trim(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var device = await db.Devices .Include(d => d.Classroom) .FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) { return (false, "设备不存在", null); } if (device.Classroom == null) { return (false, "该设备尚未绑定任何班级", null); } var oldName = device.Classroom.DisplayName; device.Classroom.DisplayName = cleanName; // Record audit event var audit = new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = operatorName ?? "System", ActorRole = operatorRole ?? "Unknown", Action = "CLASS_NAME_UPDATED", TargetType = "Classroom", TargetId = device.ClassroomId, Details = $"更新班级名称: 原名称='{oldName}', 新名称='{cleanName}', 关联设备={device.Id}" }; db.AdminAuditEvents.Add(audit); await db.SaveChangesAsync(); _logger.LogInformation("Classroom {ClassroomId} display name updated from '{Old}' to '{New}' by {Operator} ({Role})", device.ClassroomId, oldName, cleanName, operatorName, operatorRole); return (true, "班级名称更新成功", cleanName); } #endregion #region Activation Codes & License Lifecycle (P3) /// /// 生成标准纯 8 位大写激活码(V2 规范,如 7KM4X9QR)。 /// 采用严格 32 字符无歧义字符集(排除 0, O, I, L),无横杠,无空格,无业务前缀,40 bit 密码学安全随机。 /// public const string ActivationCodeAlphabet = "123456789ABCDEFGHJKMNPQRSTUVWXYZ"; public static string GenerateCanonicalActivationCode() { Span chars = stackalloc char[8]; for (int i = 0; i < chars.Length; i++) { chars[i] = ActivationCodeAlphabet[System.Security.Cryptography.RandomNumberGenerator.GetInt32(ActivationCodeAlphabet.Length)]; } return new string(chars); } public static byte[] GetDeviceTrialHmacKeyBytes(string? rawKey, bool isDevelopment = false) { if (string.IsNullOrWhiteSpace(rawKey)) { if (isDevelopment) { return Encoding.UTF8.GetBytes("ClassNotify.DevTrialKey.32BytesSecret!!"); } throw new InvalidOperationException("Fatal Security Error: Security__DeviceTrialHmacKey (or CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY) is missing. Refusing to start (Fail-Closed)."); } rawKey = rawKey.Trim(); try { var b64Bytes = Convert.FromBase64String(rawKey); if (b64Bytes.Length >= 32) return b64Bytes; } catch { } try { var hexBytes = Convert.FromHexString(rawKey); if (hexBytes.Length >= 32) return hexBytes; } catch { } var utf8Bytes = Encoding.UTF8.GetBytes(rawKey); if (utf8Bytes.Length >= 32) return utf8Bytes; throw new InvalidOperationException("Fatal Security Error: Security__DeviceTrialHmacKey has insufficient entropy (< 32 bytes / 256 bits). Refusing to start (Fail-Closed)."); } public string ComputeDeviceTrialKey(int version, string hardwareSeed) { var v = version > 0 ? version : 1; var cleanSeed = hardwareSeed.Trim().ToLowerInvariant(); var payload = $"{v}:{cleanSeed}"; using var hmac = new HMACSHA256(_deviceTrialHmacKeyBytes); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); return Convert.ToHexString(hash); } public string ComputeDeviceTrialKey(string hardwareSeed) => ComputeDeviceTrialKey(1, hardwareSeed); public static string GenerateRecoveryKey() { const string alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // 32 chars, unambiguous Span chars = stackalloc char[16]; for (int i = 0; i < chars.Length; i++) { chars[i] = alphabet[RandomNumberGenerator.GetInt32(alphabet.Length)]; } return new string(chars); } public static string FormatRecoveryKey(string rawKey) { var clean = rawKey.Replace("-", "").Trim().ToUpperInvariant(); if (clean.Length == 16) { return $"{clean[..4]}-{clean[4..8]}-{clean[8..12]}-{clean[12..]}"; } return clean; } public static string HashRecoveryKey(string rawKey) { var clean = rawKey.Replace("-", "").Trim().ToUpperInvariant(); using var sha = SHA256.Create(); var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(clean)); return Convert.ToHexString(hash); } public static string HashString(string input) { using var sha = SHA256.Create(); var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(input.Trim())); return Convert.ToHexString(hash); } public static string MaskString(string? input) { if (string.IsNullOrWhiteSpace(input)) return "****"; if (input.Length <= 4) return "****"; return "****" + input[^4..]; } public async Task GenerateActivationCodeAsync( string tenantId, string classId, int? durationDays = 7, string tier = "Trial", string? notes = null, string? actor = null, string? actorRole = null, string? ip = null, string distributionMethod = "External", string? assignedTeacherId = null, string? assignedTeacherName = null, string? targetClassName = null, string? purpose = null) { var list = await GenerateActivationCodesAsync(tenantId, classId, 1, durationDays, tier, notes, actor, actorRole, ip, distributionMethod, assignedTeacherId, assignedTeacherName, targetClassName, purpose); return list.FirstOrDefault() ?? string.Empty; } public async Task> GenerateActivationCodesAsync( string tenantId, string classId, int count, int? durationDays = 7, string tier = "Trial", string? notes = null, string? actor = null, string? actorRole = null, string? ip = null, string distributionMethod = "External", string? assignedTeacherId = null, string? assignedTeacherName = null, string? targetClassName = null, string? purpose = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); count = Math.Clamp(count, 1, 100); await using var tx = await db.Database.BeginTransactionAsync(); try { if (!string.Equals(tier, "Perpetual", StringComparison.OrdinalIgnoreCase)) { if (!durationDays.HasValue || durationDays.Value < 1 || durationDays.Value > 3650) { throw new ArgumentOutOfRangeException(nameof(durationDays), "授权天数必须在 1 至 3650 天之间"); } } else { durationDays = null; } var tenant = await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId); if (tenant == null || !tenant.IsActive) { throw new InvalidOperationException($"租户不存在或已被禁用: {tenantId}"); } // ChatGPT Turn 54 Blocker 2 Fix: Fail-closed explicit purpose checking. // Never infer elevated purpose from missing classId. var cleanPurpose = !string.IsNullOrWhiteSpace(purpose) ? purpose.Trim() : "ProvisionAndLicense"; bool isPersonalBootstrap = false; if (cleanPurpose == "PersonalProvisionAndLicense" || cleanPurpose == "BootstrapClassroomAndDevice") { if (tenant.TenantType != "Personal") { throw new InvalidOperationException("非教师账号(Personal Tenant)禁止生成 PersonalProvisionAndLicense 类型的激活码"); } isPersonalBootstrap = true; } else { // For all other purposes (ProvisionAndLicense, etc.), ClassroomId is strictly required! if (string.IsNullOrWhiteSpace(classId)) { throw new ArgumentException("开通绑定设备或重新绑定用途必须指定班级"); } } Classroom? classroom = null; if (!string.IsNullOrWhiteSpace(classId)) { classroom = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == tenantId && c.Id == classId); if (classroom == null) { throw new KeyNotFoundException($"班级不存在或不属于该学校: {classId}"); } } string? finalTeacherId = string.IsNullOrWhiteSpace(assignedTeacherId) ? null : assignedTeacherId.Trim(); string? finalTeacherName = string.IsNullOrWhiteSpace(assignedTeacherName) ? null : assignedTeacherName.Trim(); if (!string.IsNullOrEmpty(finalTeacherId)) { var teacher = await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.TenantId == tenantId && u.Id == finalTeacherId && (u.Role == "Teacher" || u.Role == "TenantOwner") && !u.IsLocked); if (teacher == null) { throw new ArgumentException($"未找到有效的教师账号或该账号无权限: {finalTeacherId}"); } finalTeacherName = teacher.FullName; distributionMethod = "TeacherAccount"; } var generatedCodes = new List(count); var targetClassSnapshot = classroom?.DisplayName ?? (isPersonalBootstrap ? "待首次激活现场指定" : null); for (int i = 0; i < count; i++) { string code; do { code = GenerateCanonicalActivationCode(); } while (await db.ActivationCodes.AnyAsync(c => c.Code == code)); generatedCodes.Add(code); var codeId = "act_" + Guid.NewGuid().ToString("N")[..16]; db.ActivationCodes.Add(new ActivationCode { Id = codeId, Code = code, TenantId = tenantId, ClassroomId = classroom?.Id ?? string.Empty, TargetClassNameAtIssue = targetClassSnapshot, AssignedTeacherId = finalTeacherId, AssignedTeacherName = finalTeacherName, DistributionMethod = string.IsNullOrEmpty(distributionMethod) ? "External" : distributionMethod, AssignedAt = !string.IsNullOrEmpty(finalTeacherId) ? DateTimeOffset.UtcNow : null, AssignedByUserId = actor, ExpiresAt = DateTimeOffset.UtcNow.AddDays(30), IsUsed = false, Status = "Issued", LicenseDurationDays = durationDays, LicenseTier = string.IsNullOrEmpty(tier) ? "Trial" : tier, Notes = string.IsNullOrWhiteSpace(notes) ? null : notes.Trim(), Purpose = cleanPurpose }); if (!string.IsNullOrEmpty(finalTeacherId)) { db.ActivationCodeAssignments.Add(new ActivationCodeAssignment { Id = "asg_" + Guid.NewGuid().ToString("N")[..16], TenantId = tenantId, ActivationCodeId = codeId, CodeMasked = MaskCode(code), TeacherUserId = finalTeacherId, TeacherName = finalTeacherName ?? finalTeacherId, AssignedByUserId = actor ?? "system", AssignedAtUtc = DateTimeOffset.UtcNow, Reason = "InitialIssuance" }); } } if (!string.IsNullOrEmpty(actor)) { var details = count > 1 ? $"为学校 {tenantId} 班级 {classId} ({targetClassSnapshot}) 批量生成 {count} 个激活码 (分发模式: {distributionMethod}, 教师: {finalTeacherName ?? "微信/线下发放"}, 授权时长: {durationDays?.ToString() ?? "永久"}天, 类别: {tier}, 备注: {notes ?? "无"})" : $"为学校 {tenantId} 班级 {classId} ({targetClassSnapshot}) 生成激活码 (分发模式: {distributionMethod}, 教师: {finalTeacherName ?? "微信/线下发放"}, 授权时长: {durationDays?.ToString() ?? "永久"}天, 类别: {tier}, 备注: {notes ?? "无"})"; db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = count > 1 ? "BATCH_GENERATE_ACTIVATION_CODES" : "GENERATE_ACTIVATION_CODE", TargetType = "ActivationCode", TargetId = count == 1 ? generatedCodes[0] : $"{count}_codes", Details = details, IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return generatedCodes; } catch { await tx.RollbackAsync(); throw; } } public async Task AssignActivationCodeAsync(string tenantId, AssignActivationCodeRequestDto dto, string? actor = null, string? actorRole = null, string? ip = null) { if (dto == null || string.IsNullOrWhiteSpace(dto.Code)) return false; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); using var tx = await db.Database.BeginTransactionAsync(); try { var rawCode = dto.Code.Trim().ToUpperInvariant(); var cleanCode = rawCode.Replace("-", "").Replace(" ", ""); var formattedCode = cleanCode.Length == 8 ? $"{cleanCode[..4]}-{cleanCode[4..]}" : rawCode; var codeEntity = await db.ActivationCodes.FirstOrDefaultAsync(c => c.TenantId == tenantId && (c.Code == rawCode || c.Code == cleanCode || c.Code == formattedCode)); if (codeEntity == null) { throw new KeyNotFoundException($"未找到属于该学校的激活码: {dto.Code}"); } if (codeEntity.Status == "Revoked" || codeEntity.RevokedAtUtc.HasValue) { throw new InvalidOperationException("该激活码已被吊销作废,不可重新指派"); } if (codeEntity.IsUsed || codeEntity.Status == "Redeemed") { throw new InvalidOperationException("该激活码已被设备激活使用,不可重新指派"); } // 1. Assign or change Teacher (Enforce Role == Teacher) User? targetTeacher = null; if (!string.IsNullOrWhiteSpace(dto.TeacherId)) { targetTeacher = await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.TenantId == tenantId && u.Id == dto.TeacherId.Trim() && u.Role == "Teacher" && !u.IsLocked); if (targetTeacher == null) { throw new ArgumentException($"未找到有效的本校教师账号或该账号无教师权限: {dto.TeacherId}"); } } // Exposed voucher reassign protection (Turn 51 & 52 GPT Audit): // If the voucher secret was already revealed by previous teacher, revoke old code and issue new code for new teacher if (codeEntity.SecretExposedAtUtc.HasValue && targetTeacher != null && !string.Equals(codeEntity.AssignedTeacherId, targetTeacher.Id, StringComparison.OrdinalIgnoreCase)) { var oldTeacherName = codeEntity.AssignedTeacherName ?? codeEntity.AssignedTeacherId ?? "原教师"; codeEntity.Status = "Revoked"; codeEntity.RevokedAtUtc = DateTimeOffset.UtcNow; codeEntity.RevokedReason = "ReassignedAfterSecretExposure"; codeEntity.IsUsed = false; // Revoke is NOT Redeem! codeEntity.Notes = (codeEntity.Notes ?? "") + $" [安全改派自动吊销: 原指派给 {oldTeacherName}]"; // Close out active assignment record for old voucher var oldCodeKey = codeEntity.Id ?? codeEntity.Code; var prevAssignment = await db.ActivationCodeAssignments .Where(a => a.ActivationCodeId == oldCodeKey && a.UnassignedAtUtc == null) .OrderByDescending(a => a.AssignedAtUtc) .FirstOrDefaultAsync(); if (prevAssignment != null) { prevAssignment.UnassignedAtUtc = DateTimeOffset.UtcNow; prevAssignment.Reason = "ReassignedAfterSecretExposure"; } var targetClassIdForNew = !string.IsNullOrWhiteSpace(dto.ClassroomId) ? dto.ClassroomId.Trim() : codeEntity.ClassroomId; var targetClassroomForNew = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == tenantId && c.Id == targetClassIdForNew); if (targetClassroomForNew == null) { throw new ArgumentException($"指定班级不存在或不属于当前学校: {targetClassIdForNew}"); } string newCode; do { newCode = GenerateCanonicalActivationCode(); } while (await db.ActivationCodes.AnyAsync(c => c.Code == newCode)); var newCodeId = "act_" + Guid.NewGuid().ToString("N")[..16]; var freshCodeEntity = new ActivationCode { Id = newCodeId, Code = newCode, TenantId = tenantId, ClassroomId = targetClassroomForNew.Id, TargetClassNameAtIssue = targetClassroomForNew.DisplayName, AssignedTeacherId = targetTeacher.Id, AssignedTeacherName = targetTeacher.FullName, DistributionMethod = "TeacherAccount", AssignedAt = DateTimeOffset.UtcNow, AssignedByUserId = actor, ExpiresAt = DateTimeOffset.UtcNow.AddDays(30), IsUsed = false, Status = "Issued", LicenseDurationDays = codeEntity.LicenseDurationDays, LicenseTier = codeEntity.LicenseTier, Notes = dto.Notes ?? codeEntity.Notes }; db.ActivationCodes.Add(freshCodeEntity); db.ActivationCodeAssignments.Add(new ActivationCodeAssignment { Id = "asg_" + Guid.NewGuid().ToString("N")[..16], TenantId = tenantId, ActivationCodeId = newCodeId, CodeMasked = MaskCode(newCode), TeacherUserId = targetTeacher.Id, TeacherName = targetTeacher.FullName, AssignedByUserId = actor ?? "system", AssignedAtUtc = DateTimeOffset.UtcNow, Reason = "FreshVoucherAfterSecretExposure" }); if (!string.IsNullOrEmpty(actor)) { var maskedOld = MaskCode(codeEntity.Code); var maskedNew = MaskCode(newCode); db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SchoolAdmin", Action = "REASSIGN_EXPOSED_ACTIVATION_CODE", TargetType = "ActivationCode", TargetId = codeEntity.Id ?? codeEntity.Code, Details = $"原激活码 {maskedOld} 已被前任教师查看,系统安全吊销并在同一事务中为教师 {targetTeacher.FullName} 重新签发新激活码 {maskedNew} (绑定班级: {targetClassroomForNew.DisplayName})", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return true; } if (targetTeacher != null) { codeEntity.AssignedTeacherId = targetTeacher.Id; codeEntity.AssignedTeacherName = targetTeacher.FullName; codeEntity.DistributionMethod = "TeacherAccount"; codeEntity.AssignedAt = DateTimeOffset.UtcNow; codeEntity.AssignedByUserId = actor; db.ActivationCodeAssignments.Add(new ActivationCodeAssignment { Id = "asg_" + Guid.NewGuid().ToString("N")[..16], TenantId = tenantId, ActivationCodeId = codeEntity.Id ?? codeEntity.Code, CodeMasked = MaskCode(codeEntity.Code), TeacherUserId = targetTeacher.Id, TeacherName = targetTeacher.FullName, AssignedByUserId = actor ?? "system", AssignedAtUtc = DateTimeOffset.UtcNow, Reason = "DirectReassignment" }); } else if (dto.TeacherId != null && string.IsNullOrWhiteSpace(dto.TeacherId)) { // Explicitly clear assignment back to External codeEntity.AssignedTeacherId = null; codeEntity.AssignedTeacherName = null; codeEntity.DistributionMethod = "External"; } // 2. Assign or change Classroom (Fail-closed: must exist in tenant) if (!string.IsNullOrWhiteSpace(dto.ClassroomId)) { var classroom = await db.Classrooms.FirstOrDefaultAsync(c => c.TenantId == tenantId && c.Id == dto.ClassroomId.Trim()); if (classroom == null) { throw new ArgumentException($"指定班级不存在或不属于当前学校: {dto.ClassroomId}"); } codeEntity.ClassroomId = classroom.Id; codeEntity.TargetClassNameAtIssue = classroom.DisplayName; } // 3. Update Notes if (dto.Notes != null) { codeEntity.Notes = string.IsNullOrWhiteSpace(dto.Notes) ? null : dto.Notes.Trim(); } if (!string.IsNullOrEmpty(actor)) { var maskedCode = MaskCode(codeEntity.Code); db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SchoolAdmin", Action = "ASSIGN_ACTIVATION_CODE", TargetType = "ActivationCode", TargetId = codeEntity.Id ?? codeEntity.Code, Details = $"指派激活码 {maskedCode} 至老师: {codeEntity.AssignedTeacherName ?? "线下直接给"}, 绑定班级: {codeEntity.TargetClassNameAtIssue ?? codeEntity.ClassroomId}, 说明: {codeEntity.Notes ?? "无"}", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return true; } catch { await tx.RollbackAsync(); throw; } } public async Task> GetTeacherActivationCodesAsync(string tenantId, string teacherUserId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var codes = await db.ActivationCodes.AsNoTracking() .Where(c => c.TenantId == tenantId && c.AssignedTeacherId == teacherUserId) .OrderByDescending(c => c.AssignedAt ?? c.ExpiresAt) .ToListAsync(); var classrooms = await db.Classrooms.AsNoTracking() .Where(c => c.TenantId == tenantId) .ToDictionaryAsync(c => c.Id, c => c.DisplayName); var tenant = await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId); var tName = tenant?.Name ?? tenantId; // Turn 81: Load devices for redeemed codes to calculate live authoritative expiration var deviceIds = codes .Where(c => !string.IsNullOrEmpty(c.UsedByDeviceId)) .Select(c => c.UsedByDeviceId!) .Distinct() .ToList(); var devices = await db.Devices.AsNoTracking() .Where(d => d.TenantId == tenantId && deviceIds.Contains(d.Id)) .ToDictionaryAsync(d => d.Id); var serverNowUtc = DateTimeOffset.UtcNow; return codes.Select(c => { classrooms.TryGetValue(c.ClassroomId, out var cName); var finalClassName = c.TargetClassNameAtIssue ?? cName ?? c.ClassroomId; DateTimeOffset? licensedUntil = null; int? remainingDays = null; int? remainingHours = null; string? licenseStatus = null; if (!string.IsNullOrEmpty(c.UsedByDeviceId) && devices.TryGetValue(c.UsedByDeviceId, out var device)) { var licenseDto = CalculateLicenseStatus(device); licensedUntil = licenseDto.LicensedUntilUtc; remainingDays = licenseDto.RemainingDays; remainingHours = licenseDto.RemainingHours; licenseStatus = licenseDto.Status; } return new ActivationCodeDto { Id = c.Id ?? ("act_" + c.Code), Code = c.Code, // Turn 81: Full unmasked plaintext for authorized teacher per PO & Brain approval MaskedCode = c.Code, TenantId = c.TenantId, TenantName = tName, ClassroomId = c.ClassroomId, ClassroomName = finalClassName, TargetClassName = finalClassName, ExpiresAt = c.ExpiresAt, IsUsed = c.IsUsed || c.Status == "Redeemed", Status = c.Status, RevokedAtUtc = c.RevokedAtUtc, RevokedReason = c.RevokedReason, UsedAt = c.UsedAt, UsedByDeviceId = c.UsedByDeviceId, LicenseDurationDays = c.LicenseDurationDays, LicenseTier = c.LicenseTier ?? "Trial", Notes = c.Notes, AssignedTeacherId = c.AssignedTeacherId, AssignedTeacherName = c.AssignedTeacherName, DistributionMethod = string.IsNullOrEmpty(c.DistributionMethod) ? "TeacherAccount" : c.DistributionMethod, AssignedAt = c.AssignedAt, AssignedByUserId = c.AssignedByUserId, SecretExposedAtUtc = c.SecretExposedAtUtc, // Turn 81 Live Authoritative Fields LicensedUntil = licensedUntil, RemainingDays = remainingDays, RemainingHours = remainingHours, LicenseStatus = licenseStatus, ServerNow = serverNowUtc, TimeZone = "Asia/Shanghai" }; }).ToList(); } public async Task RevealTeacherActivationCodeAsync(string tenantId, string teacherUserId, string codeId, string? actor = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var cleanId = codeId.Trim(); // Strict Invariant (Turn 52 GPT Verdict): ONLY opaque ActivationCode.Id allowed. Raw voucher or masked suffix strictly rejected! var codeEntity = await db.ActivationCodes.FirstOrDefaultAsync(c => c.TenantId == tenantId && c.AssignedTeacherId == teacherUserId && c.Id == cleanId); if (codeEntity == null) { throw new KeyNotFoundException("未找到属于当前教师的待激活凭证 (必须使用有效的凭证标识符)"); } if (codeEntity.Status == "Revoked" || codeEntity.RevokedAtUtc.HasValue) { throw new InvalidOperationException("该激活码已被吊销作废,无法查看明文"); } if (codeEntity.IsUsed || codeEntity.Status == "Redeemed") { throw new InvalidOperationException("该激活码已被大屏激活使用,无法再次查看明文"); } if (codeEntity.ExpiresAt < DateTimeOffset.UtcNow) { throw new InvalidOperationException("该激活码已过期"); } codeEntity.SecretExposedAtUtc = DateTimeOffset.UtcNow; if (!string.IsNullOrEmpty(actor)) { var masked = MaskCode(codeEntity.Code); db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = "Teacher", Action = "ACTIVATION_CODE_REVEALED", TargetType = "ActivationCode", TargetId = codeEntity.Id ?? masked, Details = $"教师 {actor} 查看激活码明文 (班级: {codeEntity.TargetClassNameAtIssue ?? codeEntity.ClassroomId})", IpAddress = ip }); } await db.SaveChangesAsync(); return codeEntity.Code; } public static string MaskCode(string? code) { if (string.IsNullOrWhiteSpace(code)) return "****"; var clean = code.Trim(); if (clean.Length <= 4) return "****"; if (clean.Length == 9 && clean[4] == '-') { return $"{clean[..4]}-****"; } if (clean.Length == 8) { return $"{clean[..4]}-****"; } var prefix = clean[..Math.Min(4, clean.Length)]; var suffix = clean[^Math.Min(4, clean.Length)..]; return $"{prefix}-****-{suffix}"; } public async Task UpdateActivationCodeNotesAsync( List codes, string? notes, string? actor = null, string? actorRole = null, string? ip = null) { if (codes == null || codes.Count == 0) return false; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var normalized = codes.Select(c => c.Trim().ToUpperInvariant()).Distinct().ToList(); var entities = await db.ActivationCodes.Where(a => normalized.Contains(a.Code)).ToListAsync(); if (entities.Count == 0) return false; var trimmedNotes = string.IsNullOrWhiteSpace(notes) ? null : notes.Trim(); foreach (var entity in entities) { entity.Notes = trimmedNotes; } if (!string.IsNullOrEmpty(actor)) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor, ActorRole = actorRole ?? "SuperAdmin", Action = "BATCH_TAG_ACTIVATION_CODES", TargetType = "ActivationCode", TargetId = $"{entities.Count}_codes", Details = $"批量更新 {entities.Count} 个激活码备注为: {notes ?? "清空"}", IpAddress = ip }); } await db.SaveChangesAsync(); return true; } 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); var finalClassName = c.TargetClassNameAtIssue ?? cName ?? c.ClassroomId; return new ActivationCodeDto { Id = c.Id ?? ("act_" + c.Code), Code = c.Code, MaskedCode = MaskCode(c.Code), TenantId = c.TenantId, TenantName = tName ?? c.TenantId, ClassroomId = c.ClassroomId, ClassroomName = finalClassName, TargetClassName = finalClassName, ExpiresAt = c.ExpiresAt, IsUsed = c.IsUsed, UsedAt = c.UsedAt, UsedByDeviceId = c.UsedByDeviceId, LicenseDurationDays = c.LicenseDurationDays, LicenseTier = c.LicenseTier ?? "Trial", Notes = c.Notes, AssignedTeacherId = c.AssignedTeacherId, AssignedTeacherName = c.AssignedTeacherName, DistributionMethod = string.IsNullOrEmpty(c.DistributionMethod) ? "External" : c.DistributionMethod, AssignedAt = c.AssignedAt, AssignedByUserId = c.AssignedByUserId }; }).ToList(); } public async Task GetDeviceLicenseStatusAsync(string deviceId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var device = await db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId); if (device == null) { return new DeviceLicenseStatusDto { Status = "Expired", Tier = "Unknown", CanReceiveNormalNotifications = false, CanReceiveEmergencyNotifications = true, Message = "设备未注册" }; } return CalculateLicenseStatus(device); } public static DeviceLicenseStatusDto CalculateLicenseStatus(Device device) { var now = DateTimeOffset.UtcNow; TimeZoneInfo tz; try { tz = TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai"); } catch { try { tz = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"); } catch { tz = TimeZoneInfo.CreateCustomTimeZone("CST", TimeSpan.FromHours(8), "CST", "CST"); } } var nowLocal = TimeZoneInfo.ConvertTime(now, tz); var reminderKey = nowLocal.ToString("yyyy-MM-dd"); DeviceLicenseStatusDto dto; if (!device.LicensedUntil.HasValue) { dto = new DeviceLicenseStatusDto { Status = "Perpetual", Tier = string.IsNullOrEmpty(device.LicenseTier) ? "Perpetual" : device.LicenseTier, LicensedUntilUtc = null, RemainingDays = null, RemainingHours = null, IsPerpetual = true, CanReceiveNormalNotifications = true, CanReceiveEmergencyNotifications = true, Message = "永久商业授权", ServerNowUtc = now, ReminderDateKey = reminderKey, IssuedAtUtc = now, OfflineGraceUntilUtc = now.AddDays(30) }; } else { var until = device.LicensedUntil.Value; var untilLocal = TimeZoneInfo.ConvertTime(until, tz); if (now > until) { dto = new DeviceLicenseStatusDto { Status = "Expired", Tier = device.LicenseTier, LicensedUntilUtc = until, RemainingDays = 0, RemainingHours = 0, IsPerpetual = false, CanReceiveNormalNotifications = false, CanReceiveEmergencyNotifications = true, Message = $"授权已于 {untilLocal:yyyy-MM-dd HH:mm} 到期,普通通知已暂停", ServerNowUtc = now, ReminderDateKey = reminderKey, IssuedAtUtc = now, OfflineGraceUntilUtc = null }; } else { var calendarDays = (untilLocal.Date - nowLocal.Date).Days; var totalHours = (until - now).TotalHours; var remainingHours = (int)Math.Max(1, Math.Ceiling(totalHours)); // GPT Invariant: Offline Grace is temporary disaster recovery, never extending actual license. // Trial: ~24 hours; Standard/Academic: ~7 days; capped at device.LicensedUntil var graceHours = device.LicenseTier == "Trial" ? 24 : 7 * 24; var maxGrace = now.AddHours(graceHours); var offlineGraceUntil = (until < maxGrace) ? until : maxGrace; if (calendarDays <= 0) { // Expiring today (less than 24 calendar hours remaining) dto = new DeviceLicenseStatusDto { Status = "ExpiringSoon", Tier = device.LicenseTier, LicensedUntilUtc = until, RemainingDays = 0, RemainingHours = remainingHours, IsPerpetual = false, CanReceiveNormalNotifications = true, CanReceiveEmergencyNotifications = true, Message = $"授权今日到期,剩余 {remainingHours} 小时 ({untilLocal:HH:mm})", ServerNowUtc = now, ReminderDateKey = reminderKey, IssuedAtUtc = now, OfflineGraceUntilUtc = offlineGraceUntil }; } else if (calendarDays <= 7) { dto = new DeviceLicenseStatusDto { Status = "ExpiringSoon", Tier = device.LicenseTier, LicensedUntilUtc = until, RemainingDays = calendarDays, RemainingHours = remainingHours, IsPerpetual = false, CanReceiveNormalNotifications = true, CanReceiveEmergencyNotifications = true, Message = $"授权即将到期,剩余 {calendarDays} 天 ({untilLocal:yyyy-MM-dd})", ServerNowUtc = now, ReminderDateKey = reminderKey, IssuedAtUtc = now, OfflineGraceUntilUtc = offlineGraceUntil }; } else { dto = new DeviceLicenseStatusDto { Status = "Valid", Tier = device.LicenseTier, LicensedUntilUtc = until, RemainingDays = calendarDays, RemainingHours = remainingHours, IsPerpetual = false, CanReceiveNormalNotifications = true, CanReceiveEmergencyNotifications = true, Message = "授权正常", ServerNowUtc = now, ReminderDateKey = reminderKey, IssuedAtUtc = now, OfflineGraceUntilUtc = offlineGraceUntil }; } } } dto.DeviceId = device.Id; dto.LeaseSignature = ComputeLeaseSignature(dto); return dto; } public static string ComputeLeaseSignature(DeviceLicenseStatusDto dto, string? secretKey = null) { var key = secretKey ?? $"{dto.DeviceId}_ClassNotify_Offline_Lease_2026"; var payload = $"{dto.DeviceId}|{dto.Status}|{dto.Tier}|{dto.LicensedUntilUtc?.ToUnixTimeSeconds()}|{dto.IssuedAtUtc.ToUnixTimeSeconds()}|{dto.OfflineGraceUntilUtc?.ToUnixTimeSeconds()}"; using var hmac = new System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(key)); var hash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payload)); return Convert.ToBase64String(hash); } public async Task<(bool Success, string Message, DeviceLicenseStatusDto? Status)> RenewDeviceLicenseAsync( string deviceId, string? activationCode, int? extendDays = null, string? tier = null, string? operatorUser = null, string? reason = null, DateTimeOffset? validThroughDate = 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, "设备未找到", null); } int? daysToAdd = extendDays; string newTier = tier ?? device.LicenseTier; string? usedCode = null; if (!string.IsNullOrWhiteSpace(activationCode)) { var rawCode = activationCode.Trim().ToUpperInvariant(); var cleanCode = rawCode.Replace("-", "").Replace(" ", ""); var formattedCode = cleanCode.Length == 8 ? $"{cleanCode[..4]}-{cleanCode[4..]}" : rawCode; var code = await db.ActivationCodes.FirstOrDefaultAsync(c => c.Code == rawCode || c.Code == cleanCode || c.Code == formattedCode); if (code == null) { return (false, "激活码不存在", null); } if (code.IsUsed) { return (false, "该激活码已被使用", null); } if (code.ExpiresAt < DateTimeOffset.UtcNow) { return (false, "激活码已过期", null); } if (code.TenantId != device.TenantId && code.TenantId != "global" && !string.IsNullOrEmpty(code.TenantId)) { return (false, "激活码与设备学校不匹配", null); } if (code.TenantId == "global" || string.IsNullOrEmpty(code.TenantId)) { code.TenantId = device.TenantId; } // Anti-freeload rule from GPT: Trial cannot be used multiple times on same device or same physical hardware! var hasUsedTrial = device.TrialUsed || (!string.IsNullOrEmpty(device.InstallationId) && await db.DeviceLicenses.AnyAsync(l => l.InstallationId == device.InstallationId && l.LicenseTier == "Trial")); if (code.LicenseTier == "Trial") { var hardwareSeed = !string.IsNullOrWhiteSpace(device.HardwareComponentsHash) ? device.HardwareComponentsHash.Trim() : (device.InstallationId ?? device.Id); var serverTrialKey = ComputeDeviceTrialKey(hardwareSeed); var existingTrial = await db.DeviceTrialLedgers.FirstOrDefaultAsync(l => l.DeviceTrialKey == serverTrialKey); if (hasUsedTrial || existingTrial != null) { bool hasValidOverride = existingTrial != null && existingTrial.OverrideState == "Granted" && existingTrial.OverrideRemainingUses > 0 && existingTrial.OverrideExpiresAtUtc.HasValue && existingTrial.OverrideExpiresAtUtc.Value > DateTimeOffset.UtcNow; if (hasValidOverride && existingTrial != null) { existingTrial.OverrideRemainingUses--; existingTrial.OverrideState = "Consumed"; existingTrial.OverrideConsumedAtUtc = DateTimeOffset.UtcNow; existingTrial.UpdatedAtUtc = DateTimeOffset.UtcNow; existingTrial.Status = "Active"; var trialDays = code.LicenseDurationDays ?? 7; existingTrial.TrialEndsAtUtc = DateTimeOffset.UtcNow.AddDays(trialDays); await LogAdminAuditAsync(operatorUser ?? "System", "SuperAdmin", "ADMIN_TRIAL_OVERRIDE_CONSUMED", "DeviceTrialLedger", existingTrial.Id, $"特批试用额度已消费: 机器 {device.Id} 续期使用特批试用码 {MaskCode(code.Code)}"); } else { if (existingTrial != null) { existingTrial.BlockedAttemptCount++; existingTrial.LastBlockedAtUtc = DateTimeOffset.UtcNow; existingTrial.UpdatedAtUtc = DateTimeOffset.UtcNow; await db.SaveChangesAsync(); } await LogAdminAuditAsync(operatorUser ?? "System", "SuperAdmin", "TRIAL_REPEAT_BLOCKED", "DeviceTrialLedger", existingTrial?.Id ?? "UNKNOWN", $"拦截续期重复试用尝试: 设备 {device.Id}, 拦截计数={existingTrial?.BlockedAttemptCount ?? 1}"); return (false, "该物理设备已使用过免费试用,无法重复使用试用码,请使用正式授权码", null); } } } daysToAdd = code.LicenseDurationDays; newTier = string.IsNullOrEmpty(code.LicenseTier) ? "AcademicYear" : code.LicenseTier; usedCode = code.Code; code.IsUsed = true; code.UsedAt = DateTimeOffset.UtcNow; code.UsedByDeviceId = device.Id; } var oldExpiry = device.LicensedUntil; DateTimeOffset? newExpiry; if (string.Equals(newTier, "Perpetual", StringComparison.OrdinalIgnoreCase)) { newExpiry = null; newTier = "Perpetual"; daysToAdd = null; } else if (validThroughDate.HasValue) { if (oldExpiry.HasValue && validThroughDate.Value <= oldExpiry.Value && oldExpiry.Value > DateTimeOffset.UtcNow) { return (false, "指定截止日期不得早于或等于当前有效到期日", null); } newExpiry = validThroughDate.Value; daysToAdd = (int)Math.Max(1, (validThroughDate.Value - DateTimeOffset.UtcNow).TotalDays); } else if (daysToAdd.HasValue) { // Formula approved by GPT: base = max(UtcNow, CurrentLicensedUntil); newExpiry = base + Duration var baseTime = (oldExpiry.HasValue && oldExpiry.Value > DateTimeOffset.UtcNow) ? oldExpiry.Value : DateTimeOffset.UtcNow; newExpiry = baseTime.AddDays(daysToAdd.Value); } else { newExpiry = null; // Perpetual } device.LicensedUntil = newExpiry; device.LicenseTier = newTier; if (newTier == "Trial") { device.TrialUsed = true; } var licRecord = new DeviceLicenseRecord { Id = $"lic_{Guid.NewGuid():N}"[..16], TenantId = device.TenantId, DeviceId = device.Id, InstallationId = device.InstallationId, ClassroomId = device.ClassroomId, Action = string.IsNullOrEmpty(usedCode) ? "ADMIN_EXTEND" : "RENEW", LicenseTier = newTier, GrantedDays = daysToAdd, PreviousLicensedUntil = oldExpiry, NewLicensedUntil = newExpiry, SourceActivationCode = usedCode, OperatorUsername = operatorUser ?? "System", Reason = reason ?? (string.IsNullOrEmpty(usedCode) ? "管理员后台续费/延期" : "大屏输入激活码续期"), CreatedAt = DateTimeOffset.UtcNow }; db.DeviceLicenses.Add(licRecord); await db.SaveChangesAsync(); await tx.CommitAsync(); var statusDto = CalculateLicenseStatus(device); _logger.LogInformation("License renewed successfully for Device {DeviceId}: Tier={Tier}, NewExpiry={NewExpiry}, SourceCode={MaskedSourceCode}", deviceId, newTier, newExpiry, MaskCode(usedCode)); return (true, "续费成功", statusDto); } catch (DbUpdateException dbEx) { await tx.RollbackAsync(); _logger.LogWarning(dbEx, "Concurrent renewal collision or unique constraint violation on device {DeviceId}", deviceId); return (false, "该激活码已被使用或并发核销冲突", null); } catch (Exception ex) { await tx.RollbackAsync(); _logger.LogError(ex, "Failed to renew license for device {DeviceId}", deviceId); return (false, "续期处理异常: " + ex.Message, null); } } public async Task<(bool Success, string Message, List<(string DeviceId, DeviceLicenseStatusDto Status)> RenewedDevices)> BatchRenewDevicesLicenseAsync( List deviceIds, int? extendDays = null, string? tier = null, string? operatorUser = null, string? reason = null, DateTimeOffset? validThroughDate = null, string? clientRequestId = null, string? licenseKind = null, string? validThroughLocalDate = null, string? tenantId = null) { var resultList = new List<(string DeviceId, DeviceLicenseStatusDto Status)>(); if (deviceIds == null || deviceIds.Count == 0) { return (false, "未指定任何需要续期的设备", resultList); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // 1. Idempotency Check (ClientRequestId) if (!string.IsNullOrWhiteSpace(clientRequestId)) { var existingRecords = await db.DeviceLicenses.AsNoTracking() .Where(l => l.ClientRequestId == clientRequestId) .ToListAsync(); if (existingRecords.Count > 0) { _logger.LogInformation("Batch license renewal idempotent hit for ClientRequestId={ClientRequestId}", clientRequestId); var existingDeviceIds = existingRecords.Select(r => r.DeviceId).Distinct().ToList(); var cachedDevices = await db.Devices.AsNoTracking().Where(d => existingDeviceIds.Contains(d.Id)).ToListAsync(); foreach (var d in cachedDevices) { resultList.Add((d.Id, CalculateLicenseStatus(d))); } return (true, $"该批量续费请求已处理(幂等去重,共 {resultList.Count} 台设备)", resultList); } } // 2. Local Calendar Day Interpretation for validThroughLocalDate (anti-timezone-leak) if (!string.IsNullOrWhiteSpace(validThroughLocalDate) && DateOnly.TryParse(validThroughLocalDate, out var parsedLocalDate)) { var localEndOfDay = parsedLocalDate.ToDateTime(new TimeOnly(23, 59, 59, 999), DateTimeKind.Unspecified); TimeZoneInfo tz; try { tz = TimeZoneInfo.FindSystemTimeZoneById(OperatingSystem.IsWindows() ? "China Standard Time" : "Asia/Shanghai"); } catch { tz = TimeZoneInfo.Local; } var utcEndOfDay = TimeZoneInfo.ConvertTimeToUtc(localEndOfDay, tz); validThroughDate = new DateTimeOffset(utcEndOfDay, TimeSpan.Zero); } bool isExplicitPerpetual = string.Equals(licenseKind, "Perpetual", StringComparison.OrdinalIgnoreCase) || string.Equals(tier, "Perpetual", StringComparison.OrdinalIgnoreCase); await using var tx = await db.Database.BeginTransactionAsync(); try { var query = db.Devices.Where(d => deviceIds.Contains(d.Id)); if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { query = query.Where(d => d.TenantId == tenantId); } var devices = await query.ToListAsync(); if (devices.Count == 0) { return (false, "未找到指定的设备或设备不属于当前学校", resultList); } foreach (var device in devices) { string newTier = isExplicitPerpetual ? "Perpetual" : (tier ?? device.LicenseTier); var oldExpiry = device.LicensedUntil; DateTimeOffset? newExpiry; int? daysToAdd = extendDays; if (isExplicitPerpetual) { newExpiry = null; newTier = "Perpetual"; daysToAdd = null; } else if (validThroughDate.HasValue) { newExpiry = validThroughDate.Value; daysToAdd = (int)Math.Max(1, (validThroughDate.Value - DateTimeOffset.UtcNow).TotalDays); } else if (daysToAdd.HasValue) { var baseTime = (oldExpiry.HasValue && oldExpiry.Value > DateTimeOffset.UtcNow) ? oldExpiry.Value : DateTimeOffset.UtcNow; newExpiry = baseTime.AddDays(daysToAdd.Value); } else { newExpiry = null; } device.LicensedUntil = newExpiry; device.LicenseTier = newTier; var licRecord = new DeviceLicenseRecord { Id = $"lic_{Guid.NewGuid():N}"[..16], TenantId = device.TenantId, DeviceId = device.Id, InstallationId = device.InstallationId, ClassroomId = device.ClassroomId, Action = "BATCH_ADMIN_EXTEND", LicenseTier = newTier, GrantedDays = daysToAdd, PreviousLicensedUntil = oldExpiry, NewLicensedUntil = newExpiry, OperatorUsername = operatorUser ?? "System", Reason = reason ?? $"管理员后台批量续费 ({daysToAdd?.ToString() ?? "永久"}天)", ClientRequestId = clientRequestId, CreatedAt = DateTimeOffset.UtcNow }; db.DeviceLicenses.Add(licRecord); var statusDto = CalculateLicenseStatus(device); resultList.Add((device.Id, statusDto)); } await db.SaveChangesAsync(); await tx.CommitAsync(); _logger.LogInformation("Batch license renewal succeeded for {Count} devices by {Operator} (RequestId={RequestId})", resultList.Count, operatorUser, clientRequestId); return (true, $"成功为 {resultList.Count} 台设备完成授权续期", resultList); } catch (Exception ex) { await tx.RollbackAsync(); _logger.LogError(ex, "Failed to batch renew licenses"); return (false, $"批量续费失败: {ex.Message}", resultList); } } public async Task> GetLicenseRecordsAsync(string? tenantId = null, int limit = 100) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.DeviceLicenses.AsNoTracking().AsQueryable(); if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { query = query.Where(l => l.TenantId == tenantId); } return await query.OrderByDescending(l => l.CreatedAt).Take(limit).ToListAsync(); } #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, BroadcastId = notification.BroadcastId, 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, CorrelationId = notification.CorrelationId }; 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 notif = await db.Notifications.AsNoTracking().FirstOrDefaultAsync(n => n.Id == messageId); if (notif != null && !string.IsNullOrEmpty(notif.CorrelationId)) { if (!string.IsNullOrEmpty(ack.CorrelationId) && ack.CorrelationId != notif.CorrelationId) { _logger.LogWarning("ACK correlation mismatch for Msg {MsgId}: client provided {ClientCorrId}, canonical is {CanonicalCorrId}", messageId, ack.CorrelationId, notif.CorrelationId); } ack.CorrelationId = notif.CorrelationId; } 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, Cancelled. // Rule: Never resurrect a Cancelled receipt, and never regress from Acknowledged to any lower rank or failure. if (receipt.Status == "Cancelled" || receipt.Status == "Acknowledged") { _logger.LogInformation("Receipt {ReceiptId} (Dev {DevId}) is terminal {Status}. Ignoring subsequent {NewStatus}.", receipt.Id, authenticatedDeviceId, receipt.Status, 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: // Brain Turn 81 CAS Guard: // Only allow transition to Failed if not already Acknowledged, Displayed, or Cancelled. // Prevent race condition where late/secondary failure overwrites successful Displayed state. if (receipt.Status != "Acknowledged" && receipt.Status != "Displayed" && receipt.Status != "Cancelled") { receipt.Status = "Failed"; receipt.FailedAt = ack.Timestamp; receipt.FailureReason = !string.IsNullOrEmpty(ack.FailureReason) ? ack.FailureReason : (!string.IsNullOrEmpty(ack.Remark) ? 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, string? currentUserId = null) { 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); } // Server-side exclusion of dismissed notifications for this user (Per-user history dismissal) if (!string.IsNullOrEmpty(currentUserId)) { var dismissedIdsQuery = db.NotificationHistoryDismissals.AsNoTracking() .Where(d => d.UserId == currentUserId) .Select(d => d.NotificationId); query = query.Where(n => !dismissedIdsQuery.Contains(n.Id)); } 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.IsCancelled) { status = "Cancelled"; } else 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, IsCancelled = n.IsCancelled, CancelledAt = n.CancelledAt, CancelledBy = n.CancelledBy, ConfirmedAt = confirmedAt, ExpiresAt = n.ExpiresAt, Receipts = n.Receipts.Select(r => new NotificationReceiptViewDto { DeviceId = r.DeviceId, Status = r.Status, DisplayedAt = r.DisplayedAt, VisualReceiptState = r.VisualReceiptState, VisualReceiptCapturedAt = r.VisualReceiptCapturedAt, VisualReceiptExpiresAt = r.VisualReceiptExpiresAt }).ToList() }; }).ToList(); } public async Task> GetPendingNotificationsForDeviceAsync(string deviceId) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; var validDtos = new List(); // Query current device to ensure strict tenant and classroom scope (ARCH & GPT Turn 73) var currentDevice = await db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId); if (currentDevice == null) return validDtos; // Query pending receipts for this authenticated device (excluding cancelled notifications) var pendingReceipts = await db.NotificationReceipts .Include(r => r.Notification) .Where(r => r.DeviceId == deviceId && r.Status == "Sent" && r.Notification != null && !r.Notification.IsCancelled) .ToListAsync(); bool hasStateChanges = false; foreach (var receipt in pendingReceipts) { if (receipt.Notification == null) continue; // Strict Scope Guard (Turn 73): Reject & invalidate receipts that belong to a different Tenant or Classroom if (receipt.Notification.TenantId != currentDevice.TenantId || receipt.Notification.ClassroomId != currentDevice.ClassroomId) { receipt.Status = "Invalidated"; receipt.UpdatedAt = now; hasStateChanges = true; _logger.LogWarning("Receipt {ReceiptId} for Device {DeviceId} marked Invalidated: Notification belongs to Tenant {OldTenant}/Class {OldClass}, but Device is now in {CurTenant}/{CurClass}.", receipt.Id, deviceId, receipt.Notification.TenantId, receipt.Notification.ClassroomId, currentDevice.TenantId, currentDevice.ClassroomId); continue; } // Blocker A: Dedicated Binding Epoch Boundary Guard (Turn 73 Round 2): // Strictly reject & invalidate receipts created prior to current device binding epoch var bindingEpoch = currentDevice.BindingStartedAtUtc ?? currentDevice.CreatedAt; if (receipt.Notification.CreatedAt < bindingEpoch) { receipt.Status = "Invalidated"; receipt.UpdatedAt = now; hasStateChanges = true; _logger.LogWarning("Receipt {ReceiptId} for Device {DeviceId} marked Invalidated: Notification CreatedAt ({NotifCreatedAt}) is prior to device binding epoch ({BindingEpoch}).", receipt.Id, deviceId, receipt.Notification.CreatedAt, bindingEpoch); continue; } if (receipt.Notification.IsCancelled) { receipt.Status = "Cancelled"; receipt.UpdatedAt = now; hasStateChanges = true; 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(); } public async Task CancelNotificationAsync( string notificationId, string actorUserId, string actorUsername, string role, string tenantId, string? ip, CancellationToken ct = default) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var snapshot = await db.Notifications .AsNoTracking() .Where(n => n.Id == notificationId) .Select(n => new { n.Id, n.TenantId, n.ClassroomId, n.SenderUserId, n.SenderName, n.Message, n.IsCancelled, n.CancelledAt, n.CancelledBy }) .SingleOrDefaultAsync(ct); if (snapshot == null) throw new KeyNotFoundException("通知记录不存在。"); // ---------- Authorization (Enforced at Service Layer) ---------- switch (role) { case "SuperAdmin": break; case "SchoolAdmin": case "TenantOwner": if (snapshot.TenantId != tenantId) throw new UnauthorizedAccessException("无权撤回其他学校/空间的通知。"); break; case "Teacher": if (snapshot.TenantId != tenantId) throw new UnauthorizedAccessException("无权撤回其他学校的通知。"); // Check ownership: Strict SenderUserId matching (never rely on mutable display name) if (!string.IsNullOrEmpty(snapshot.SenderUserId) && snapshot.SenderUserId != actorUserId) throw new UnauthorizedAccessException("教师只能撤回自己发送的通知。"); break; default: throw new UnauthorizedAccessException("当前角色无通知撤回权限。"); } if (snapshot.IsCancelled) { return new CancelNotificationResult( snapshot.Id, snapshot.TenantId, snapshot.ClassroomId, true, snapshot.CancelledAt, snapshot.CancelledBy); } var now = DateTimeOffset.UtcNow; await using var tx = await db.Database.BeginTransactionAsync(ct); try { // 原子 first-writer-wins var affected = await db.Notifications .Where(n => n.Id == notificationId && !n.IsCancelled) .ExecuteUpdateAsync(setters => setters .SetProperty(n => n.IsCancelled, true) .SetProperty(n => n.CancelledAt, now) .SetProperty(n => n.CancelledBy, actorUsername), ct); if (affected == 0) { var current = await db.Notifications.AsNoTracking() .SingleAsync(n => n.Id == notificationId, ct); await tx.RollbackAsync(ct); return new CancelNotificationResult( current.Id, current.TenantId, current.ClassroomId, true, current.CancelledAt, current.CancelledBy); } // 只终止尚未 Displayed / Acknowledged 的 Receipt await db.NotificationReceipts .Where(r => r.NotificationId == notificationId && (r.Status == "Sent" || r.Status == "DeviceReceived")) .ExecuteUpdateAsync(setters => setters .SetProperty(r => r.Status, "Cancelled") .SetProperty(r => r.UpdatedAt, now), ct); db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = now, ActorUsername = actorUsername, ActorRole = role, Action = "NOTIFICATION_CANCELLED", TargetType = "Notification", TargetId = notificationId, Details = $"提前关闭通知,Tenant={snapshot.TenantId}, Classroom={snapshot.ClassroomId}: {snapshot.Message}", IpAddress = ip }); await db.SaveChangesAsync(ct); await tx.CommitAsync(ct); return new CancelNotificationResult( notificationId, snapshot.TenantId, snapshot.ClassroomId, false, now, actorUsername); } catch { await tx.RollbackAsync(ct); throw; } } public async Task DismissNotificationHistoryAsync(string notificationId, string tenantId, string actorUserId, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(notificationId) || string.IsNullOrWhiteSpace(actorUserId)) return false; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // Verify the notification exists and belongs to the caller's tenant var notification = await db.Notifications.AsNoTracking() .FirstOrDefaultAsync(n => n.Id == notificationId, ct); if (notification == null || notification.TenantId != tenantId) { return false; } // Idempotent upsert: check if already dismissed by this user var existing = await db.NotificationHistoryDismissals .FirstOrDefaultAsync(d => d.UserId == actorUserId && d.NotificationId == notificationId, ct); if (existing != null) { // Already dismissed -> idempotent 200 success! return true; } var dismissal = new NotificationHistoryDismissal { Id = Guid.NewGuid().ToString("N"), TenantId = tenantId, UserId = actorUserId, NotificationId = notificationId, DismissedAtUtc = DateTimeOffset.UtcNow }; db.NotificationHistoryDismissals.Add(dismissal); await db.SaveChangesAsync(ct); _logger.LogInformation("Notification {NotificationId} history dismissed by user {ActorUserId} in tenant {TenantId}. All business/receipt/visual data preserved.", notificationId, actorUserId, tenantId); return true; } public async Task DeleteNotificationAsync(string notificationId, string tenantId, string actorUserId, string role, CancellationToken ct = default) { // Backward-compatibility: forwards to non-destructive per-user dismissal return await DismissNotificationHistoryAsync(notificationId, tenantId, actorUserId, ct); } #endregion #region Device Commands (P1 Batch 10) public async Task CreateDeviceCommandAsync(string? callerTenantId, string deviceId, string commandType, string? parameters, string createdBy, string? actorRole = null, string? ip = null) { 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(); await using var tx = await db.Database.BeginTransactionAsync(); try { 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); // Pre-Audit in the EXACT SAME database transaction: // Ensures DeviceCommand cannot persist without immutable REMOTE_COMMAND_REQUESTED audit db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = now, ActorUsername = createdBy, ActorRole = actorRole ?? "SuperAdmin", Action = "REMOTE_COMMAND_REQUESTED", TargetType = "Device", TargetId = device.Id, Details = $"创建远程控制指令: {commandType} (CommandId: {commandId}, 参数: {parameters ?? "none"})", IpAddress = ip }); await db.SaveChangesAsync(); await tx.CommitAsync(); _logger.LogInformation("Created remote command {CommandId} ({CommandType}) with atomic Pre-Audit for Device {DeviceId} (Tenant {TenantId}) by {CreatedBy}", commandId, commandType, device.Id, device.TenantId, 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 }; } catch { await tx.RollbackAsync(); throw; } } 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, Tenant? tenant = null, bool isPasswordChangeOnly = false) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(_jwtOptions.SigningKey); var tenantType = tenant?.TenantType ?? (user.TenantId.StartsWith("t_p_") || user.TenantId.StartsWith("t_indep_") ? "Personal" : "School"); var claims = new List { new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Name, user.FullName), new Claim(ClaimTypes.Role, isPasswordChangeOnly ? "PasswordChangeRequired" : user.Role), new Claim("tenant_id", user.TenantId), new Claim("tenant_type", tenantType), new Claim("token_version", user.TokenVersion.ToString()) }; if (isPasswordChangeOnly) { claims.Add(new Claim("must_change_password", "true")); claims.Add(new Claim("purpose", "password_change")); } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Issuer = _jwtOptions.Issuer, Audience = _jwtOptions.Audience, Expires = isPasswordChangeOnly ? DateTime.UtcNow.AddMinutes(15) : 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, string? q = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.Users.Include(u => u.Tenant).AsQueryable(); if (!string.IsNullOrWhiteSpace(tenantId) && tenantId != "all") query = query.Where(u => u.TenantId == tenantId); if (!string.IsNullOrWhiteSpace(role) && role != "all") query = query.Where(u => u.Role == role); if (!string.IsNullOrWhiteSpace(q)) { var term = q.Trim().ToLower(); query = query.Where(u => u.Username.ToLower().Contains(term) || u.FullName.ToLower().Contains(term) || u.Id.ToLower().Contains(term) || (u.RecoveryEmail != null && u.RecoveryEmail.ToLower().Contains(term)) || (u.Tenant != null && u.Tenant.Name.ToLower().Contains(term)) || u.TenantId.ToLower().Contains(term)); } 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, TenantType = u.Tenant?.TenantType ?? "School", Username = u.Username, FullName = u.FullName, Role = u.Role, IsLocked = u.IsLocked, CreatedAt = u.CreatedAt, LastLoginAt = u.LastLoginAt, RecoveryEmail = u.RecoveryEmail }).ToList(); } public async Task UpdateUserAdminAsync(string userId, UpdateUserAdminRequest req, string? actor = null, string? actorRole = null, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.Include(u => u.Tenant).FirstOrDefaultAsync(u => u.Id == userId); if (user == null) return null; var changed = false; var oldRole = user.Role; var oldName = user.FullName; var oldTenant = user.TenantId; if (!string.IsNullOrWhiteSpace(req.FullName) && req.FullName.Trim() != user.FullName) { user.FullName = req.FullName.Trim(); changed = true; } if (!string.IsNullOrWhiteSpace(req.Role) && req.Role.Trim() != user.Role) { var validRoles = new[] { "Teacher", "SchoolAdmin", "SuperAdmin", "TenantOwner" }; if (!validRoles.Contains(req.Role.Trim())) { throw new ArgumentException($"不支持的角色类型: {req.Role}"); } user.Role = req.Role.Trim(); changed = true; } if (!string.IsNullOrWhiteSpace(req.TenantId) && req.TenantId.Trim() != user.TenantId) { var tenantExists = await db.Tenants.AnyAsync(t => t.Id == req.TenantId.Trim()); if (!tenantExists) { throw new ArgumentException($"指定的校区/租户空间不存在: {req.TenantId}"); } user.TenantId = req.TenantId.Trim(); changed = true; } if (req.RecoveryEmail != null && req.RecoveryEmail.Trim() != user.RecoveryEmail) { user.RecoveryEmail = string.IsNullOrWhiteSpace(req.RecoveryEmail) ? null : req.RecoveryEmail.Trim(); changed = true; } if (changed) { db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor ?? "SuperAdmin", ActorRole = actorRole ?? "SuperAdmin", Action = "UPDATE_USER", TargetType = "User", TargetId = user.Id, Details = $"更新用户信息: 姓名 '{oldName}'->'{user.FullName}', 角色 '{oldRole}'->'{user.Role}', 归属 '{oldTenant}'->'{user.TenantId}'", IpAddress = ip }); await db.SaveChangesAsync(); } return new UserAdminDto { Id = user.Id, TenantId = user.TenantId, TenantName = user.Tenant?.Name ?? user.TenantId, TenantType = user.Tenant?.TenantType ?? "School", Username = user.Username, FullName = user.FullName, Role = user.Role, IsLocked = user.IsLocked, CreatedAt = user.CreatedAt, LastLoginAt = user.LastLoginAt, RecoveryEmail = user.RecoveryEmail }; } 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.MustChangePassword = true; user.TemporaryPasswordExpiresAtUtc = DateTimeOffset.UtcNow.AddHours(24); 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_BY_ADMIN", TargetType = "User", TargetId = userId, Details = $"管理员重置用户临时密码,已强制开启首次登录修改密码要求 (MustChangePassword=true, TokenVersion={user.TokenVersion})", IpAddress = ip }); } await db.SaveChangesAsync(); await tx.CommitAsync(); return true; } catch { await tx.RollbackAsync(); throw; } } public async Task<(bool Success, string Message, string? NewToken)> ChangePasswordAsync(string userId, string newPassword, string? actor = null, string? ip = null) { if (string.IsNullOrWhiteSpace(newPassword) || newPassword.Trim().Length < 8) { return (false, "新密码长度不能少于 8 位", null); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null || user.IsLocked) return (false, "用户不存在或已被锁定", null); user.PasswordHash = _passwordHasher.HashPassword(user, newPassword); user.MustChangePassword = false; user.TemporaryPasswordExpiresAtUtc = null; user.TokenVersion++; // Switch session boundary: invalidates the change-password token! db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor ?? user.Username, ActorRole = user.Role, Action = "USER_SET_FINAL_PASSWORD", TargetType = "User", TargetId = user.Id, IpAddress = ip, Details = $"用户自行设置最终密码完成,临时凭据已销毁,会话已切换 (TokenVersion={user.TokenVersion})" }); await db.SaveChangesAsync(); var tenant = await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == user.TenantId); var finalToken = GenerateJwtToken(user, tenant, isPasswordChangeOnly: false); return (true, "密码修改成功,已切换至正常会话", finalToken); } 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 ResetSchoolTeacherPasswordAsync(string schoolAdminTenantId, string teacherUserId, string newPassword, string actorUsername, string? ip, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(newPassword) || newPassword.Trim().Length < 8) throw new ArgumentException("新密码长度不得少于 8 位"); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var targetUser = await db.Users .FirstOrDefaultAsync(u => u.Id == teacherUserId, ct); if (targetUser == null) throw new KeyNotFoundException("账号不存在。"); if (targetUser.Role == "SuperAdmin") throw new UnauthorizedAccessException("无权修改超级管理员密码。"); if (targetUser.TenantId != schoolAdminTenantId) throw new UnauthorizedAccessException("无权修改其他学校账号密码。"); if (targetUser.Role != "Teacher") throw new UnauthorizedAccessException("学校管理员无权修改非教师角色账号密码。"); await using var tx = await db.Database.BeginTransactionAsync(ct); try { targetUser.PasswordHash = _passwordHasher.HashPassword(targetUser, newPassword); targetUser.TokenVersion += 1; // 吊销旧 Token db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actorUsername, ActorRole = "SchoolAdmin", Action = "SCHOOLADMIN_RESET_TEACHER_PASSWORD", TargetType = "User", TargetId = teacherUserId, Details = $"重置教师密码: {targetUser.Username}", IpAddress = ip }); await db.SaveChangesAsync(ct); await tx.CommitAsync(ct); return true; } catch { await tx.RollbackAsync(ct); throw; } } public async Task SetSchoolTeacherLockAsync(string schoolAdminTenantId, string teacherUserId, bool isLocked, string actorUsername, string? ip, CancellationToken ct = default) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var targetUser = await db.Users .FirstOrDefaultAsync(u => u.Id == teacherUserId, ct); if (targetUser == null) throw new KeyNotFoundException("账号不存在。"); if (targetUser.Role == "SuperAdmin") throw new UnauthorizedAccessException("无权锁定超级管理员账号。"); if (targetUser.TenantId != schoolAdminTenantId) throw new UnauthorizedAccessException("无权操作其他学校账号。"); if (targetUser.Role != "Teacher") throw new UnauthorizedAccessException("学校管理员无权启停非教师角色账号。"); if (targetUser.IsLocked == isLocked) return false; await using var tx = await db.Database.BeginTransactionAsync(ct); try { targetUser.IsLocked = isLocked; targetUser.TokenVersion += 1; var action = isLocked ? "SCHOOLADMIN_LOCK_TEACHER" : "SCHOOLADMIN_UNLOCK_TEACHER"; var details = isLocked ? $"停用教师账号: {targetUser.Username}" : $"恢复教师账号: {targetUser.Username}"; db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actorUsername, ActorRole = "SchoolAdmin", Action = action, TargetType = "User", TargetId = teacherUserId, Details = details, IpAddress = ip }); await db.SaveChangesAsync(ct); await tx.CommitAsync(ct); return true; } catch { await tx.RollbackAsync(ct); throw; } } public async Task GetBroadcastReceiptSummaryAsync(string broadcastId, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(broadcastId)) return null; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var notifications = await db.Notifications .AsNoTracking() .Include(n => n.Receipts) .Where(n => n.BroadcastId == broadcastId) .ToListAsync(ct); if (notifications.Count == 0) return null; var receipts = notifications .SelectMany(n => n.Receipts) .ToList(); return new BroadcastReceiptSummaryDto { BroadcastId = broadcastId, TargetSchools = notifications.Select(n => n.TenantId).Distinct().Count(), TargetClassrooms = notifications.Count, TargetDevices = receipts.Count, Displayed = receipts.Count(r => NotificationReceiptStatuses.IsDisplayed(r.Status)), Pending = receipts.Count(r => NotificationReceiptStatuses.IsPending(r.Status)), Cancelled = receipts.Count(r => r.Status == NotificationReceiptStatuses.Cancelled), Failed = receipts.Count(r => NotificationReceiptStatuses.IsFailed(r.Status)), CreatedAt = notifications.Min(n => n.CreatedAt) }; } 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("无法删除超级管理员账号"); // Check if user is sole owner / sole admin of their tenant if (!string.IsNullOrEmpty(user.TenantId)) { var tenant = await db.Tenants.FirstOrDefaultAsync(t => t.Id == user.TenantId); if (tenant != null) { if (tenant.TenantType == "Personal" && (user.Role == "TenantOwner" || user.Role == "Teacher")) { var otherUsers = await db.Users.CountAsync(u => u.TenantId == user.TenantId && u.Id != user.Id); if (otherUsers == 0) { throw new InvalidOperationException("该用户为个人空间的唯一所有者,直接删除将导致孤儿空间。请先在租户管理中解散该空间或转移所有权"); } } else if (tenant.TenantType == "School" && user.Role == "SchoolAdmin") { var otherSchoolAdmins = await db.Users.CountAsync(u => u.TenantId == user.TenantId && u.Role == "SchoolAdmin" && u.Id != user.Id); if (otherSchoolAdmins == 0) { throw new InvalidOperationException("该用户为学校空间的唯一校区管理员,直接删除将导致该校失管。请先指定其他校区管理员后再执行删除"); } } } } // Invalidate session immediately user.TokenVersion++; // Revoke any pending ResetTickets var pendingTokens = await db.PasswordResetTokens.Where(t => t.UserId == user.Id && !t.IsUsed).ToListAsync(); foreach (var pt in pendingTokens) { pt.IsUsed = true; } // Snapshot target info for immutable audit var targetTenant = await db.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == user.TenantId); var snapshotDetails = $"物理注销删除用户快照: UID={user.Id}, Username={user.Username}, FullName={user.FullName}, Role={user.Role}, TenantId={user.TenantId}, TenantName={targetTenant?.Name ?? "N/A"}"; 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 = snapshotDetails, 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 rawCode = code.Trim().ToUpperInvariant(); var cleanCode = rawCode.Replace("-", "").Replace(" ", ""); var formattedCode = cleanCode.Length == 8 ? $"{cleanCode[..4]}-{cleanCode[4..]}" : rawCode; var act = await db.ActivationCodes.FirstOrDefaultAsync(a => a.Code == rawCode || a.Code == cleanCode || a.Code == formattedCode); 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 = null) { 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(); } #region Password Recovery & Reset (Turn 62) public async Task ResetPasswordByRecoveryKeyAsync(ResetPasswordByRecoveryKeyDto dto, string? remoteIp = null) { if (dto == null || string.IsNullOrWhiteSpace(dto.UsernameOrEmail) || string.IsNullOrWhiteSpace(dto.RecoveryKey) || string.IsNullOrWhiteSpace(dto.NewPassword)) { return new ResetPasswordByRecoveryKeyResultDto { Success = false, Message = "用户名/邮箱、恢复密钥与新密码均不可为空" }; } if (dto.NewPassword.Length < 8 || dto.NewPassword.Length > 128) { return new ResetPasswordByRecoveryKeyResultDto { Success = false, Message = "新密码长度必须在 8 至 128 个字符之间" }; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var target = dto.UsernameOrEmail.Trim().ToLowerInvariant(); var user = await db.Users.FirstOrDefaultAsync(u => u.Username.ToLower() == target || (u.RecoveryEmail != null && u.RecoveryEmail.ToLower() == target)); if (user == null || string.IsNullOrWhiteSpace(user.RecoveryKeyHash)) { _logger.LogWarning("Recovery key reset failed: User '{Target}' not found or has no recovery key. Remote IP: {RemoteIp}", target, remoteIp ?? "unknown"); return new ResetPasswordByRecoveryKeyResultDto { Success = false, Message = "账号或恢复密钥错误" }; } if (user.IsLocked) { return new ResetPasswordByRecoveryKeyResultDto { Success = false, Message = "该账号已被管理员锁定,无法重置密码" }; } var inputHash = HashRecoveryKey(dto.RecoveryKey); var expectedBytes = Encoding.UTF8.GetBytes(user.RecoveryKeyHash); var actualBytes = Encoding.UTF8.GetBytes(inputHash); if (expectedBytes.Length != actualBytes.Length || !CryptographicOperations.FixedTimeEquals(expectedBytes, actualBytes)) { _logger.LogWarning("Recovery key reset failed: Invalid key hash for user {Username}. Remote IP: {RemoteIp}", user.Username, remoteIp ?? "unknown"); return new ResetPasswordByRecoveryKeyResultDto { Success = false, Message = "账号或恢复密钥错误" }; } // Rotate recovery key (One-time use) var freshRecoveryKey = GenerateRecoveryKey(); user.PasswordHash = _passwordHasher.HashPassword(user, dto.NewPassword); user.RecoveryKeyHash = HashRecoveryKey(freshRecoveryKey); user.RecoveryKeyCreatedAtUtc = DateTimeOffset.UtcNow; user.TokenVersion++; // Invalidate all existing JWT sessions db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = user.Username, ActorRole = user.Role, Action = "RESET_PASSWORD_BY_RECOVERY_KEY", TargetType = "User", TargetId = user.Id, Details = "通过安全恢复密钥自救重置密码并轮换新密钥", IpAddress = remoteIp }); await db.SaveChangesAsync(); _logger.LogInformation("Password successfully reset via recovery key for user {Username} ({UserId}). Old key rotated.", user.Username, user.Id); return new ResetPasswordByRecoveryKeyResultDto { Success = true, Message = "密码已成功重置!原有恢复密钥已作废,系统已为您生成全新的安全恢复密钥,请务必妥善保存。", NewRecoveryKey = FormatRecoveryKey(freshRecoveryKey) }; } public async Task<(bool Success, string Message)> RequestPasswordResetEmailAsync(RequestPasswordResetEmailDto dto, string? remoteIp = null) { if (dto == null || string.IsNullOrWhiteSpace(dto.Email)) { return (false, "邮箱地址不可为空"); } var targetEmail = dto.Email.Trim().ToLowerInvariant(); using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.RecoveryEmail != null && u.RecoveryEmail.ToLower() == targetEmail); // Fail-safe generic response against user enumeration const string genericResponse = "如果该邮箱在系统中已绑定账号,我们已发送重置密码链接(15分钟内有效),请注意查收邮件。"; if (user == null || user.IsLocked) { _logger.LogInformation("Password reset email requested for unknown or locked email: {Email}", targetEmail); return (true, genericResponse); } var rawToken = Guid.NewGuid().ToString("N") + Guid.NewGuid().ToString("N"); var tokenHash = HashString(rawToken); var resetToken = new PasswordResetToken { Id = "prt_" + Guid.NewGuid().ToString("N")[..16], UserId = user.Id, TokenHash = tokenHash, TokenType = "EmailLink", ExpiresAtUtc = DateTimeOffset.UtcNow.AddMinutes(15), IsUsed = false, CreatedAtUtc = DateTimeOffset.UtcNow }; db.PasswordResetTokens.Add(resetToken); await db.SaveChangesAsync(); // Zero-secret logging: Only log expiration and metadata, NEVER log raw secret tokens _logger.LogInformation("Password reset token generated for user {Username} ({UserId}), token expires at {Expires}.", user.Username, user.Id, resetToken.ExpiresAtUtc); return (true, genericResponse); } public async Task<(bool Success, string Message)> ResetPasswordByTokenAsync(ResetPasswordByTokenDto dto, string? remoteIp = null) { if (dto == null || string.IsNullOrWhiteSpace(dto.Token) || string.IsNullOrWhiteSpace(dto.NewPassword)) { return (false, "重置凭证与新密码不可为空"); } if (dto.NewPassword.Length < 8 || dto.NewPassword.Length > 128) { return (false, "新密码长度必须在 8 至 128 个字符之间"); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var tokenHash = HashString(dto.Token.Trim()); var resetToken = await db.PasswordResetTokens.FirstOrDefaultAsync(t => t.TokenHash == tokenHash); if (resetToken == null || resetToken.IsUsed || resetToken.ExpiresAtUtc <= DateTimeOffset.UtcNow) { return (false, "重置链接或工单无效或已过期,请重新申请"); } var user = await db.Users.FirstOrDefaultAsync(u => u.Id == resetToken.UserId); if (user == null || user.IsLocked) { return (false, "关联的用户账号不存在或已被停用"); } user.PasswordHash = _passwordHasher.HashPassword(user, dto.NewPassword); user.TokenVersion++; resetToken.IsUsed = true; resetToken.UsedAtUtc = DateTimeOffset.UtcNow; db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = user.Username, ActorRole = user.Role, Action = "RESET_PASSWORD_BY_TOKEN", TargetType = "User", TargetId = user.Id, Details = $"通过凭据重置密码 (类型: {resetToken.TokenType})", IpAddress = remoteIp }); await db.SaveChangesAsync(); _logger.LogInformation("Password successfully reset via token (Type: {Type}) for user {Username} ({UserId})", resetToken.TokenType, user.Username, user.Id); return (true, "密码已成功重置,请使用新密码重新登录"); } public async Task IssueAdminResetTicketAsync(string adminUserId, string adminUsername, string targetUserId, string? remoteIp = null) { if (string.IsNullOrWhiteSpace(targetUserId)) { return new ResetTicketResultDto { Success = false, ErrorMessage = "目标用户标识不可为空" }; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Id == targetUserId); if (user == null) { return new ResetTicketResultDto { Success = false, ErrorMessage = "未找到目标用户" }; } var rawTicket = "rst_" + Guid.NewGuid().ToString("N"); var tokenHash = HashString(rawTicket); var expires = DateTimeOffset.UtcNow.AddHours(24); var resetToken = new PasswordResetToken { Id = "prt_" + Guid.NewGuid().ToString("N")[..16], UserId = user.Id, TokenHash = tokenHash, TokenType = "AdminTicket", ExpiresAtUtc = expires, IsUsed = false, IssuedByUserId = adminUserId, CreatedAtUtc = DateTimeOffset.UtcNow }; db.PasswordResetTokens.Add(resetToken); db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = adminUsername, ActorRole = "Admin", Action = "ISSUE_ADMIN_RESET_TICKET", TargetType = "User", TargetId = user.Id, Details = $"管理员签发一次性重置工单 (有效至 {expires:yyyy-MM-dd HH:mm:ss} UTC)", IpAddress = remoteIp }); await db.SaveChangesAsync(); _logger.LogInformation("Admin {AdminUsername} issued reset ticket for user {TargetUsername} ({TargetUserId}), valid until {Expires}", adminUsername, user.Username, user.Id, expires); return new ResetTicketResultDto { Success = true, Ticket = rawTicket, ResetUrl = $"/reset-password?ticket={rawTicket}", ExpiresAtUtc = expires }; } public async Task HasRecoveryKeyAsync(string userId) { if (string.IsNullOrWhiteSpace(userId)) return false; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); return user != null && !string.IsNullOrWhiteSpace(user.RecoveryKeyHash); } public async Task<(bool Success, string Message, string? NewRecoveryKey)> RotateRecoveryKeyAsync(string userId, string currentPassword, string? remoteIp = null) { if (string.IsNullOrWhiteSpace(userId)) { return (false, "用户标识不可为空", null); } if (string.IsNullOrWhiteSpace(currentPassword)) { return (false, "请输入当前密码以验证身份", null); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userId); if (user == null) { return (false, "用户账号不存在", null); } if (user.IsLocked) { return (false, "账号已被锁定,无法操作", null); } var verifyResult = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, currentPassword); if (verifyResult == PasswordVerificationResult.Failed) { _logger.LogWarning("Recovery key rotation failed: Invalid password for user {Username}. Remote IP: {RemoteIp}", user.Username, remoteIp ?? "unknown"); return (false, "当前密码错误,身份验证失败", null); } // Generate fresh CSPRNG recovery key and hash it var freshRecoveryKey = GenerateRecoveryKey(); user.RecoveryKeyHash = HashRecoveryKey(freshRecoveryKey); user.RecoveryKeyCreatedAtUtc = DateTimeOffset.UtcNow; db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = user.Username, ActorRole = user.Role, Action = "ROTATE_RECOVERY_KEY", TargetType = "User", TargetId = user.Id, Details = "用户在控制台自主轮换安全恢复密钥,原有恢复密钥立即失效作废", IpAddress = remoteIp }); await db.SaveChangesAsync(); _logger.LogInformation("Security recovery key successfully rotated for user {Username} ({UserId}). Old key invalidated.", user.Username, user.Id); return (true, "安全恢复密钥已重新生成,旧密钥已彻底作废!请妥善保存新密钥。", FormatRecoveryKey(freshRecoveryKey)); } #region Turn 75: Trial Anti-Freeload & Hardware Override Console private static string MaskFingerprint(string? key) { if (string.IsNullOrWhiteSpace(key)) return "••••"; var k = key.Trim(); if (k.Length <= 8) return "••••" + k[^Math.Min(4, k.Length)..]; return $"{k[..4]}••••{k[^4..]}"; } public async Task> GetTrialLedgersAsync( string? tenantId, string? q, bool onlyBlocked, string? overrideState, int limit = 100) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.DeviceTrialLedgers.AsNoTracking().AsQueryable(); if (!string.IsNullOrWhiteSpace(tenantId) && tenantId != "all") { query = query.Where(l => l.OriginalTenantId == tenantId); } if (onlyBlocked) { query = query.Where(l => l.BlockedAttemptCount > 0); } var now = DateTimeOffset.UtcNow; if (!string.IsNullOrWhiteSpace(overrideState) && overrideState != "All") { if (overrideState.Equals("Expired", StringComparison.OrdinalIgnoreCase)) { query = query.Where(l => l.OverrideState == "Granted" && l.OverrideExpiresAtUtc != null && l.OverrideExpiresAtUtc.Value < now); } else if (overrideState.Equals("Granted", StringComparison.OrdinalIgnoreCase)) { query = query.Where(l => l.OverrideState == "Granted" && (l.OverrideExpiresAtUtc == null || l.OverrideExpiresAtUtc.Value >= now)); } else { query = query.Where(l => l.OverrideState == overrideState); } } var ledgers = await query.OrderByDescending(l => l.FirstTrialStartedAtUtc) .Take(Math.Clamp(limit, 1, 500)) .ToListAsync(); var deviceIds = ledgers.Select(l => l.OriginalDeviceId).Where(id => !string.IsNullOrEmpty(id)).Distinct().ToList(); var devices = await db.Devices.AsNoTracking().Where(d => deviceIds.Contains(d.Id)).ToDictionaryAsync(d => d.Id); var tenantIds = ledgers.Select(l => l.OriginalTenantId).Where(id => !string.IsNullOrEmpty(id)).Distinct().ToList(); var tenants = await db.Tenants.AsNoTracking().Where(t => tenantIds.Contains(t.Id)).ToDictionaryAsync(t => t.Id); var classIds = devices.Values.Select(d => d.ClassroomId).Where(cid => !string.IsNullOrEmpty(cid)).Distinct().ToList(); var classrooms = await db.Classrooms.AsNoTracking().Where(c => classIds.Contains(c.Id)).ToListAsync(); var classLookup = classrooms.GroupBy(c => c.Id).ToDictionary(g => g.Key, g => g.First()); var result = new List(); foreach (var l in ledgers) { devices.TryGetValue(l.OriginalDeviceId, out var dev); tenants.TryGetValue(l.OriginalTenantId, out var ten); Classroom? cls = null; if (dev != null && !string.IsNullOrEmpty(dev.ClassroomId)) { classLookup.TryGetValue(dev.ClassroomId, out cls); } // Real-time evaluation of expired state var effOverrideState = l.OverrideState; if (effOverrideState == "Granted" && l.OverrideExpiresAtUtc.HasValue && l.OverrideExpiresAtUtc.Value < now) { effOverrideState = "Expired"; } var dto = new DeviceTrialLedgerAdminDto { Id = l.Id, MaskedFingerprint = MaskFingerprint(l.DeviceTrialKey), FingerprintVersion = l.FingerprintVersion, OriginalDeviceId = l.OriginalDeviceId, Hostname = dev?.Hostname, OriginalTenantId = l.OriginalTenantId, TenantName = ten?.Name, TenantType = ten?.TenantType ?? "School", ClassroomId = dev?.ClassroomId, ClassroomName = cls?.DisplayName ?? dev?.ClassroomId, FirstTrialStartedAtUtc = l.FirstTrialStartedAtUtc, TrialEndsAtUtc = l.TrialEndsAtUtc, Status = l.Status, BlockedAttemptCount = l.BlockedAttemptCount, LastBlockedAtUtc = l.LastBlockedAtUtc, OverrideState = effOverrideState, OverrideRemainingUses = l.OverrideRemainingUses, OverrideExpiresAtUtc = l.OverrideExpiresAtUtc, OverrideReason = l.OverrideReason, OverrideGrantedByUserId = l.OverrideGrantedByUserId, OverrideGrantedAtUtc = l.OverrideGrantedAtUtc, OverrideConsumedAtUtc = l.OverrideConsumedAtUtc, SourceActivationCodeId = l.SourceActivationCodeId, CreatedAtUtc = l.CreatedAtUtc, UpdatedAtUtc = l.UpdatedAtUtc }; // Query filter (DeviceId, Hostname, ClassroomName, TenantName, SourceActivationCodeId) // Never match raw voucher code if (!string.IsNullOrWhiteSpace(q)) { var queryTerm = q.Trim(); var matched = (dto.OriginalDeviceId?.Contains(queryTerm, StringComparison.OrdinalIgnoreCase) == true) || (dto.Hostname?.Contains(queryTerm, StringComparison.OrdinalIgnoreCase) == true) || (dto.ClassroomName?.Contains(queryTerm, StringComparison.OrdinalIgnoreCase) == true) || (dto.TenantName?.Contains(queryTerm, StringComparison.OrdinalIgnoreCase) == true) || (dto.SourceActivationCodeId?.Contains(queryTerm, StringComparison.OrdinalIgnoreCase) == true); if (!matched) continue; } result.Add(dto); } return result; } public async Task<(bool Success, string Message, DeviceTrialLedgerAdminDto? Ledger)> GrantTrialOverrideAsync( string ledgerId, string reason, int validHours, string adminUser, string? ip = null) { if (string.IsNullOrWhiteSpace(reason)) { return (false, "特批原因不能为空,必须详细记录特批缘由以供安全审计", null); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var ledger = await db.DeviceTrialLedgers.FirstOrDefaultAsync(l => l.Id == ledgerId); if (ledger == null) { return (false, "未找到指定的试用台账记录", null); } var hours = validHours > 0 ? validHours : 72; var expiresAt = DateTimeOffset.UtcNow.AddHours(hours); // Prevent duplicate active override: cannot grant new override while an unexpired, unconsumed one is active if (ledger.OverrideState == "Granted" && ledger.OverrideRemainingUses > 0 && ledger.OverrideExpiresAtUtc.HasValue && ledger.OverrideExpiresAtUtc.Value > DateTimeOffset.UtcNow) { return (false, "当前台账已存在有效特批放行额度,在过期或核销前严禁重复签发", null); } ledger.OverrideState = "Granted"; ledger.OverrideRemainingUses = 1; ledger.OverrideExpiresAtUtc = expiresAt; ledger.OverrideReason = reason.Trim(); ledger.OverrideGrantedByUserId = adminUser; ledger.OverrideGrantedAtUtc = DateTimeOffset.UtcNow; ledger.OverrideConsumedAtUtc = null; ledger.UpdatedAtUtc = DateTimeOffset.UtcNow; db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = adminUser, ActorRole = "SuperAdmin", Action = "ADMIN_TRIAL_OVERRIDE_GRANTED", TargetType = "DeviceTrialLedger", TargetId = ledger.Id, Details = $"超管人工特批一次性试用放行。有效时间: {hours}小时 (至 {expiresAt:yyyy-MM-dd HH:mm:ss} UTC)。特批原因: {reason.Trim()}", IpAddress = ip }); await db.SaveChangesAsync(); _logger.LogInformation("Trial override granted for ledger {LedgerId} by {AdminUser}. Valid for {Hours}h. Reason: {Reason}", ledger.Id, adminUser, hours, reason.Trim()); var dto = new DeviceTrialLedgerAdminDto { Id = ledger.Id, MaskedFingerprint = MaskFingerprint(ledger.DeviceTrialKey), FingerprintVersion = ledger.FingerprintVersion, OriginalDeviceId = ledger.OriginalDeviceId, OriginalTenantId = ledger.OriginalTenantId, FirstTrialStartedAtUtc = ledger.FirstTrialStartedAtUtc, TrialEndsAtUtc = ledger.TrialEndsAtUtc, Status = ledger.Status, BlockedAttemptCount = ledger.BlockedAttemptCount, LastBlockedAtUtc = ledger.LastBlockedAtUtc, OverrideState = ledger.OverrideState, OverrideRemainingUses = ledger.OverrideRemainingUses, OverrideExpiresAtUtc = ledger.OverrideExpiresAtUtc, OverrideReason = ledger.OverrideReason, OverrideGrantedByUserId = ledger.OverrideGrantedByUserId, OverrideGrantedAtUtc = ledger.OverrideGrantedAtUtc, SourceActivationCodeId = ledger.SourceActivationCodeId, CreatedAtUtc = ledger.CreatedAtUtc, UpdatedAtUtc = ledger.UpdatedAtUtc }; return (true, $"特批放行成功!该设备已获得 1 次试用激活特权,请在 {hours} 小时内完成试用兑换。", dto); } public async Task<(bool Success, string Message)> RevokeTrialOverrideAsync( string ledgerId, string? reason, string adminUser, string? ip = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var ledger = await db.DeviceTrialLedgers.FirstOrDefaultAsync(l => l.Id == ledgerId); if (ledger == null) { return (false, "未找到指定的试用台账记录"); } if (ledger.OverrideState == "Consumed") { return (false, "该特批权益已被设备在激活过程中消费生效,无法撤销已消费的试用"); } ledger.OverrideState = "Revoked"; ledger.OverrideRemainingUses = 0; ledger.OverrideReason = string.IsNullOrWhiteSpace(reason) ? $"{ledger.OverrideReason} [已由 {adminUser} 撤销]" : $"{ledger.OverrideReason} [已撤销: {reason.Trim()}]"; ledger.UpdatedAtUtc = DateTimeOffset.UtcNow; db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = adminUser, ActorRole = "SuperAdmin", Action = "ADMIN_TRIAL_OVERRIDE_REVOKED", TargetType = "DeviceTrialLedger", TargetId = ledger.Id, Details = $"超管撤销人工特批试用放行资格。撤销理由: {reason?.Trim() ?? "无"}", IpAddress = ip }); await db.SaveChangesAsync(); _logger.LogInformation("Trial override revoked for ledger {LedgerId} by {AdminUser}. Reason: {Reason}", ledger.Id, adminUser, reason); return (true, "已成功撤销该设备的试用特批放行资格"); } public async Task GetLicenseRecordsSummaryAsync(string? tenantId = null) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var query = db.DeviceLicenses.AsNoTracking().AsQueryable(); if (!string.IsNullOrWhiteSpace(tenantId) && tenantId != "all") { query = query.Where(r => r.TenantId == tenantId); } // T75-02 & T75-03: Exclude test records and invalid/negative granted days from production KPIs var validRecords = await query .Where(r => !r.IsTest && r.GrantedDays.HasValue && r.GrantedDays.Value > 0) .Select(r => new { r.Action, r.LicenseTier, GrantedDays = r.GrantedDays!.Value }) .ToListAsync(); var totalGrantedDays = validRecords.Sum(r => r.GrantedDays); var activationCount = validRecords.Count(r => r.Action == "ACTIVATE"); var renewalCount = validRecords.Count(r => r.Action == "RENEW"); var perpetualCount = validRecords.Count(r => r.LicenseTier == "Perpetual" || r.GrantedDays >= 36500); var adjustmentCount = validRecords.Count(r => r.Action == "MANUAL_GRANT" || r.Action == "EXTEND"); return new LicenseRecordsSummaryDto { TotalGrantedDays = totalGrantedDays, ActivationCount = activationCount, RenewalCount = renewalCount, PerpetualCount = perpetualCount, AdjustmentCount = adjustmentCount, TotalRecords = validRecords.Count }; } public async Task UpdateDeviceDisplayLabelAsync( string deviceId, string? displayLabel, string? actor = null, string? actorRole = null, string? ip = null) { if (string.IsNullOrWhiteSpace(deviceId)) return false; using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var dev = await db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId); if (dev == null) return false; var oldLabel = dev.DisplayLabel; var cleanLabel = string.IsNullOrWhiteSpace(displayLabel) ? null : displayLabel.Trim(); if (cleanLabel != null && cleanLabel.Length > 100) { cleanLabel = cleanLabel[..100]; } dev.DisplayLabel = cleanLabel; db.AdminAuditEvents.Add(new AdminAuditEvent { Id = $"aud_{Guid.NewGuid():N}"[..16], OccurredAt = DateTimeOffset.UtcNow, ActorUsername = actor ?? "SuperAdmin", ActorRole = actorRole ?? "SuperAdmin", Action = "UPDATE_DEVICE_DISPLAY_LABEL", TargetType = "Device", TargetId = dev.Id, Details = $"修改大屏设备备注: '{oldLabel}' -> '{cleanLabel}'", IpAddress = ip }); await db.SaveChangesAsync(); return true; } #endregion #endregion #endregion #endregion }