================================================================================ PROJECT: ClassNotify SNAPSHOT_ID: 20261002-032041-73dd8d7 BUNDLE: 2/8 GIT_HEAD: 73dd8d7c5feb1cc42c8a6f218815748bfbe88bf3 WORKTREE_DIRTY: true FILES_IN_BUNDLE: 51 ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260922130000_AddDeviceCommandDurationMs.Designer.cs SHA256: 118f61890ce5578a02b9e83e07930ed96fb030b4c4705c093d1776ca5c5cabbb SIZE: 22590 ================================================================================ // using System; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable namespace ClassNotify.Server.Data.Migrations { [DbContext(typeof(ClassNotifyDbContext))] [Migration("20260922130000_AddDeviceCommandDurationMs")] partial class AddDeviceCommandDurationMs { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "8.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.Property("Code") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsUsed") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("UsedAt") .HasColumnType("timestamp with time zone"); b.HasKey("Code"); b.HasIndex("ClassroomId"); b.HasIndex("Code") .IsUnique(); b.HasIndex("InstallationId"); b.HasIndex("TenantId"); b.ToTable("ActivationCodes"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Property("Id") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("DisplayName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("Classrooms"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("CurrentIp") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("DeviceTokenHash") .IsRequired() .HasMaxLength(128) .HasColumnType("character varying(128)"); b.Property("Hostname") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("LastHeartbeat") .HasColumnType("timestamp with time zone"); b.Property("OnlineState") .IsRequired() .HasMaxLength(20) .HasColumnType("character varying(20)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("ClassroomId"); b.HasIndex("DeviceTokenHash") .IsUnique(); b.HasIndex("InstallationId"); b.HasIndex("TenantId"); b.ToTable("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CommandType") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CompletedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedBy") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DurationMs") .HasColumnType("bigint"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("Parameters") .HasColumnType("text"); b.Property("ResultCode") .HasColumnType("integer"); b.Property("ResultMessage") .HasMaxLength(1000) .HasColumnType("character varying(1000)"); b.Property("StartedAt") .HasColumnType("timestamp with time zone"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("DeviceId", "Status"); b.HasIndex("Status", "ExpiresAt"); b.HasIndex("TenantId", "DeviceId", "CreatedAt") .IsDescending(false, false, true); b.ToTable("DeviceCommands"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCredential", b => { b.Property("DeviceId") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("EncryptedToken") .IsRequired() .HasColumnType("text"); b.Property("LastRotatedAt") .HasColumnType("timestamp with time zone"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.HasKey("DeviceId"); b.ToTable("DeviceCredentials"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.MigrationMarker", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Details") .HasColumnType("text"); b.Property("MigratedAt") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.ToTable("MigrationMarkers"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DurationSeconds") .HasColumnType("integer"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("Message") .IsRequired() .HasColumnType("text"); b.Property("Priority") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("SenderName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("SenderUserId") .HasColumnType("text"); b.Property("Shake") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("character varying(100)"); b.Property("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("Voice") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("ClassroomId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "ClassroomId", "ExpiresAt"); b.ToTable("Notifications"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("AcknowledgedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceReceivedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayedAt") .HasColumnType("timestamp with time zone"); b.Property("FailedAt") .HasColumnType("timestamp with time zone"); b.Property("FailureReason") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("NotificationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("UpdatedAt") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("DeviceId", "Status"); b.HasIndex("DeviceId", "UpdatedAt") .IsDescending(false, true); b.HasIndex("NotificationId", "DeviceId") .IsUnique(); b.ToTable("NotificationReceipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.RateLimitAuditLog", b => { b.Property("Id") .HasColumnType("text"); b.Property("Action") .IsRequired() .HasColumnType("text"); b.Property("ClientIp") .IsRequired() .HasColumnType("text"); b.Property("Endpoint") .IsRequired() .HasColumnType("text"); b.Property("Reason") .IsRequired() .HasColumnType("text"); b.Property("TenantId") .HasColumnType("text"); b.Property("Timestamp") .HasColumnType("timestamp with time zone"); b.Property("UserId") .HasColumnType("text"); b.HasKey("Id"); b.ToTable("RateLimitAuditLogs"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("Name") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Plan") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.HasKey("Id"); b.ToTable("Tenants"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("FullName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("PasswordHash") .IsRequired() .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property("Role") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Username") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.HasKey("Id"); b.HasIndex("TenantId", "Username") .IsUnique(); b.ToTable("Users"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("ActivationCodes") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", null) .WithMany("Classrooms") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Classroom", "Classroom") .WithMany("Devices") .HasForeignKey("ClassroomId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Devices") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Classroom"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Notifications") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany("Receipts") .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Notification", "Notification") .WithMany("Receipts") .HasForeignKey("NotificationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Notification"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Users") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Navigation("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Navigation("ActivationCodes"); b.Navigation("Classrooms"); b.Navigation("Devices"); b.Navigation("Notifications"); b.Navigation("Users"); }); #pragma warning restore 612, 618 } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260922130000_AddDeviceCommandDurationMs.Designer.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260922130000_AddDeviceCommandDurationMs.cs SHA256: c99935f743acf18d16b28ed88687fe9d339693f50be553ec7bf4b11c0dbf67fc SIZE: 760 ================================================================================ using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace ClassNotify.Server.Data.Migrations { /// public partial class AddDeviceCommandDurationMs : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn( name: "DurationMs", table: "DeviceCommands", type: "bigint", nullable: true); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "DurationMs", table: "DeviceCommands"); } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260922130000_AddDeviceCommandDurationMs.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260924165851_AddReliabilityBaselineAndCorrelation.Designer.cs SHA256: f32ebcd070f6e087113d686934d4fe97eade12891b8f32daabafe85810f539ce SIZE: 29302 ================================================================================ // using System; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable namespace ClassNotify.Server.Data.Migrations { [DbContext(typeof(ClassNotifyDbContext))] [Migration("20260924165851_AddReliabilityBaselineAndCorrelation")] partial class AddReliabilityBaselineAndCorrelation { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "8.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.Property("Code") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsUsed") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("UsedAt") .HasColumnType("timestamp with time zone"); b.Property("UsedByDeviceId") .HasColumnType("text"); b.HasKey("Code"); b.HasIndex("ClassroomId"); b.HasIndex("Code") .IsUnique(); b.HasIndex("InstallationId"); b.HasIndex("TenantId"); b.ToTable("ActivationCodes"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.AdminAuditEvent", b => { b.Property("Id") .HasColumnType("text"); b.Property("Action") .IsRequired() .HasColumnType("text"); b.Property("ActorRole") .IsRequired() .HasColumnType("text"); b.Property("ActorUsername") .IsRequired() .HasColumnType("text"); b.Property("Details") .HasColumnType("text"); b.Property("IpAddress") .HasColumnType("text"); b.Property("OccurredAt") .HasColumnType("timestamp with time zone"); b.Property("TargetId") .IsRequired() .HasColumnType("text"); b.Property("TargetType") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.ToTable("AdminAuditEvents"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Property("TenantId") .HasColumnType("text"); b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Grade") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("RoomNumber") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.HasKey("TenantId", "Id"); b.HasIndex("TenantId", "Id"); b.ToTable("Classrooms"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Property("Id") .HasColumnType("text"); b.Property("Architecture") .HasColumnType("text"); b.Property("ClassroomId") .IsRequired() .HasColumnType("text"); b.Property("ClientVersion") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceTokenHash") .IsRequired() .HasColumnType("text"); b.Property("Hostname") .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsActive") .HasColumnType("boolean"); b.Property("LastHeartbeatAt") .HasColumnType("timestamp with time zone"); b.Property("LastHeartbeatCorrelationId") .HasColumnType("text"); b.Property("OsVersion") .HasColumnType("text"); b.Property("ProtocolVersion") .HasColumnType("integer"); b.Property("RawDeviceToken") .HasColumnType("text"); b.Property("ServiceVersion") .HasColumnType("text"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("Id") .IsUnique(); b.HasIndex("InstallationId") .IsUnique() .HasFilter("\"InstallationId\" IS NOT NULL"); b.HasIndex("TenantId"); b.HasIndex("TenantId", "ClassroomId"); b.ToTable("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CommandType") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CompletedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedBy") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DurationMs") .HasColumnType("bigint"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("Parameters") .HasColumnType("text"); b.Property("ResultCode") .HasColumnType("integer"); b.Property("ResultMessage") .HasMaxLength(1000) .HasColumnType("character varying(1000)"); b.Property("StartedAt") .HasColumnType("timestamp with time zone"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("DeviceId", "Status"); b.HasIndex("Status", "ExpiresAt"); b.HasIndex("TenantId", "DeviceId", "CreatedAt") .IsDescending(false, false, true); b.ToTable("DeviceCommands"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCredentialRecord", b => { b.Property("DeviceId") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceTokenHash") .IsRequired() .HasColumnType("text"); b.Property("EncryptedRecoverableToken") .IsRequired() .HasColumnType("text"); b.Property("InstallationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("RotatedAt") .HasColumnType("timestamp with time zone"); b.HasKey("DeviceId"); b.HasIndex("DeviceId") .IsUnique(); b.HasIndex("InstallationId") .IsUnique(); b.ToTable("DeviceCredentials"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckRun", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("RequestedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("RequestedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ResultJson") .HasMaxLength(32768) .HasColumnType("character varying(32768)"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("DeviceId", "RequestedAtUtc") .IsDescending(false, true); b.HasIndex("TenantId", "Status"); b.ToTable("DeviceSelfChecks"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.MigrationMarker", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Details") .HasColumnType("text"); b.Property("MigratedAt") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.ToTable("MigrationMarkers"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("BroadcastId") .HasColumnType("text"); b.Property("CancelledAt") .HasColumnType("timestamp with time zone"); b.Property("CancelledBy") .HasColumnType("text"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DurationSeconds") .HasColumnType("integer"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("IsCancelled") .HasColumnType("boolean"); b.Property("Message") .IsRequired() .HasColumnType("text"); b.Property("Priority") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("SenderName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("SenderUserId") .HasColumnType("text"); b.Property("Shake") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("Voice") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("ClassroomId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "ClassroomId", "ExpiresAt"); b.ToTable("Notifications"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("AcknowledgedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceReceivedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayedAt") .HasColumnType("timestamp with time zone"); b.Property("FailedAt") .HasColumnType("timestamp with time zone"); b.Property("FailureReason") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("NotificationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("UpdatedAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptCapturedAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptPath") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("VisualReceiptSha256") .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("VisualReceiptSizeBytes") .HasColumnType("bigint"); b.Property("VisualReceiptState") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(32) .HasColumnType("character varying(32)") .HasDefaultValue("None"); b.HasKey("Id"); b.HasIndex("VisualReceiptExpiresAt"); b.HasIndex("DeviceId", "Status"); b.HasIndex("DeviceId", "UpdatedAt") .IsDescending(false, true); b.HasIndex("NotificationId", "DeviceId") .IsUnique(); b.ToTable("NotificationReceipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("IsActive") .HasColumnType("boolean"); b.Property("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.HasKey("Id"); b.ToTable("Tenants"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("FullName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsLocked") .HasColumnType("boolean"); b.Property("LastLoginAt") .HasColumnType("timestamp with time zone"); b.Property("PasswordHash") .IsRequired() .HasColumnType("text"); b.Property("Role") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("TokenVersion") .HasColumnType("integer"); b.Property("Username") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("TenantId"); b.HasIndex("Username") .IsUnique(); b.ToTable("Users"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("ActivationCodes") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Classrooms") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Devices") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Classroom", "Classroom") .WithMany("Devices") .HasForeignKey("TenantId", "ClassroomId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Classroom"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckRun", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Notifications") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany("Receipts") .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Notification", "Notification") .WithMany("Receipts") .HasForeignKey("NotificationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Notification"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Users") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Navigation("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Navigation("ActivationCodes"); b.Navigation("Classrooms"); b.Navigation("Devices"); b.Navigation("Notifications"); b.Navigation("Users"); }); #pragma warning restore 612, 618 } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260924165851_AddReliabilityBaselineAndCorrelation.Designer.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260924165851_AddReliabilityBaselineAndCorrelation.cs SHA256: 33c4b10a0df186448c632d03ae8658ad2666a0304974992952f28cc6e631258d SIZE: 5775 ================================================================================ using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace ClassNotify.Server.Data.Migrations { /// public partial class AddReliabilityBaselineAndCorrelation : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn( name: "CorrelationId", table: "Notifications", type: "character varying(32)", maxLength: 32, nullable: false, defaultValue: ""); migrationBuilder.AddColumn( name: "Architecture", table: "Devices", type: "text", nullable: true); migrationBuilder.AddColumn( name: "ClientVersion", table: "Devices", type: "text", nullable: true); migrationBuilder.AddColumn( name: "LastHeartbeatCorrelationId", table: "Devices", type: "text", nullable: true); migrationBuilder.AddColumn( name: "OsVersion", table: "Devices", type: "text", nullable: true); migrationBuilder.AddColumn( name: "ProtocolVersion", table: "Devices", type: "integer", nullable: true); migrationBuilder.AddColumn( name: "ServiceVersion", table: "Devices", type: "text", nullable: true); migrationBuilder.CreateTable( name: "DeviceSelfChecks", columns: table => new { Id = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), TenantId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), DeviceId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), CorrelationId = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), Status = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), RequestedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), CompletedAtUtc = table.Column(type: "timestamp with time zone", nullable: true), ResultJson = table.Column(type: "character varying(32768)", maxLength: 32768, nullable: true), RequestedByUserId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false) }, constraints: table => { table.PrimaryKey("PK_DeviceSelfChecks", x => x.Id); table.ForeignKey( name: "FK_DeviceSelfChecks_Devices_DeviceId", column: x => x.DeviceId, principalTable: "Devices", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_DeviceSelfChecks_Tenants_TenantId", column: x => x.TenantId, principalTable: "Tenants", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Notifications_CorrelationId", table: "Notifications", column: "CorrelationId"); migrationBuilder.CreateIndex( name: "IX_DeviceSelfChecks_CorrelationId", table: "DeviceSelfChecks", column: "CorrelationId"); migrationBuilder.CreateIndex( name: "IX_DeviceSelfChecks_DeviceId_RequestedAtUtc", table: "DeviceSelfChecks", columns: new[] { "DeviceId", "RequestedAtUtc" }, descending: new[] { false, true }); migrationBuilder.CreateIndex( name: "IX_DeviceSelfChecks_TenantId_Status", table: "DeviceSelfChecks", columns: new[] { "TenantId", "Status" }); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "DeviceSelfChecks"); migrationBuilder.DropIndex( name: "IX_Notifications_CorrelationId", table: "Notifications"); migrationBuilder.DropColumn( name: "CorrelationId", table: "Notifications"); migrationBuilder.DropColumn( name: "Architecture", table: "Devices"); migrationBuilder.DropColumn( name: "ClientVersion", table: "Devices"); migrationBuilder.DropColumn( name: "LastHeartbeatCorrelationId", table: "Devices"); migrationBuilder.DropColumn( name: "OsVersion", table: "Devices"); migrationBuilder.DropColumn( name: "ProtocolVersion", table: "Devices"); migrationBuilder.DropColumn( name: "ServiceVersion", table: "Devices"); } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260924165851_AddReliabilityBaselineAndCorrelation.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260925122539_AddDeviceSelfCheckBatch.Designer.cs SHA256: b9b3e0b59c9e7206a2b51b3861e8e78fe01647d2b60b4f975876c4349679c46f SIZE: 32922 ================================================================================ // using System; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable namespace ClassNotify.Server.Data.Migrations { [DbContext(typeof(ClassNotifyDbContext))] [Migration("20260925122539_AddDeviceSelfCheckBatch")] partial class AddDeviceSelfCheckBatch { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "8.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.Property("Code") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsUsed") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("UsedAt") .HasColumnType("timestamp with time zone"); b.Property("UsedByDeviceId") .HasColumnType("text"); b.HasKey("Code"); b.HasIndex("ClassroomId"); b.HasIndex("Code") .IsUnique(); b.HasIndex("InstallationId"); b.HasIndex("TenantId"); b.ToTable("ActivationCodes"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.AdminAuditEvent", b => { b.Property("Id") .HasColumnType("text"); b.Property("Action") .IsRequired() .HasColumnType("text"); b.Property("ActorRole") .IsRequired() .HasColumnType("text"); b.Property("ActorUsername") .IsRequired() .HasColumnType("text"); b.Property("Details") .HasColumnType("text"); b.Property("IpAddress") .HasColumnType("text"); b.Property("OccurredAt") .HasColumnType("timestamp with time zone"); b.Property("TargetId") .IsRequired() .HasColumnType("text"); b.Property("TargetType") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.ToTable("AdminAuditEvents"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Property("TenantId") .HasColumnType("text"); b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Grade") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("RoomNumber") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.HasKey("TenantId", "Id"); b.HasIndex("TenantId", "Id"); b.ToTable("Classrooms"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Property("Id") .HasColumnType("text"); b.Property("Architecture") .HasColumnType("text"); b.Property("ClassroomId") .IsRequired() .HasColumnType("text"); b.Property("ClientVersion") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceTokenHash") .IsRequired() .HasColumnType("text"); b.Property("Hostname") .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsActive") .HasColumnType("boolean"); b.Property("LastHeartbeatAt") .HasColumnType("timestamp with time zone"); b.Property("LastHeartbeatCorrelationId") .HasColumnType("text"); b.Property("OsVersion") .HasColumnType("text"); b.Property("ProtocolVersion") .HasColumnType("integer"); b.Property("RawDeviceToken") .HasColumnType("text"); b.Property("ServiceVersion") .HasColumnType("text"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("Id") .IsUnique(); b.HasIndex("InstallationId") .IsUnique() .HasFilter("\"InstallationId\" IS NOT NULL"); b.HasIndex("TenantId"); b.HasIndex("TenantId", "ClassroomId"); b.ToTable("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CommandType") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CompletedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedBy") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DurationMs") .HasColumnType("bigint"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("Parameters") .HasColumnType("text"); b.Property("ResultCode") .HasColumnType("integer"); b.Property("ResultMessage") .HasMaxLength(1000) .HasColumnType("character varying(1000)"); b.Property("StartedAt") .HasColumnType("timestamp with time zone"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("DeviceId", "Status"); b.HasIndex("Status", "ExpiresAt"); b.HasIndex("TenantId", "DeviceId", "CreatedAt") .IsDescending(false, false, true); b.ToTable("DeviceCommands"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCredentialRecord", b => { b.Property("DeviceId") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceTokenHash") .IsRequired() .HasColumnType("text"); b.Property("EncryptedRecoverableToken") .IsRequired() .HasColumnType("text"); b.Property("InstallationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("RotatedAt") .HasColumnType("timestamp with time zone"); b.HasKey("DeviceId"); b.HasIndex("DeviceId") .IsUnique(); b.HasIndex("InstallationId") .IsUnique(); b.ToTable("DeviceCredentials"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckBatch", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ClientRequestId") .IsRequired() .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CreatedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeadlineAtUtc") .HasColumnType("timestamp with time zone"); b.Property("Status") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("TargetDeviceCount") .HasColumnType("integer"); b.Property("UpdatedAtUtc") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("CreatedAtUtc"); b.HasIndex("CreatedByUserId", "ClientRequestId") .IsUnique(); b.ToTable("DeviceSelfCheckBatches"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckRun", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("BatchId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("DeadlineAtUtc") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DispatchAttemptCount") .HasColumnType("integer"); b.Property("DispatchedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("OverallStatus") .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("RequestedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("RequestedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ResultJson") .HasMaxLength(32768) .HasColumnType("character varying(32768)"); b.Property("RunState") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(32) .HasColumnType("character varying(32)") .HasDefaultValue("PendingDispatch"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("BatchId", "DeviceId") .IsUnique() .HasFilter("\"BatchId\" IS NOT NULL"); b.HasIndex("BatchId", "OverallStatus"); b.HasIndex("BatchId", "RunState"); b.HasIndex("DeviceId", "RequestedAtUtc") .IsDescending(false, true); b.HasIndex("TenantId", "Status"); b.ToTable("DeviceSelfChecks"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.MigrationMarker", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Details") .HasColumnType("text"); b.Property("MigratedAt") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.ToTable("MigrationMarkers"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("BroadcastId") .HasColumnType("text"); b.Property("CancelledAt") .HasColumnType("timestamp with time zone"); b.Property("CancelledBy") .HasColumnType("text"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DurationSeconds") .HasColumnType("integer"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("IsCancelled") .HasColumnType("boolean"); b.Property("Message") .IsRequired() .HasColumnType("text"); b.Property("Priority") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("SenderName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("SenderUserId") .HasColumnType("text"); b.Property("Shake") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("Voice") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("ClassroomId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "ClassroomId", "ExpiresAt"); b.ToTable("Notifications"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("AcknowledgedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceReceivedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayedAt") .HasColumnType("timestamp with time zone"); b.Property("FailedAt") .HasColumnType("timestamp with time zone"); b.Property("FailureReason") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("NotificationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("UpdatedAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptCapturedAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptPath") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("VisualReceiptSha256") .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("VisualReceiptSizeBytes") .HasColumnType("bigint"); b.Property("VisualReceiptState") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(32) .HasColumnType("character varying(32)") .HasDefaultValue("None"); b.HasKey("Id"); b.HasIndex("VisualReceiptExpiresAt"); b.HasIndex("DeviceId", "Status"); b.HasIndex("DeviceId", "UpdatedAt") .IsDescending(false, true); b.HasIndex("NotificationId", "DeviceId") .IsUnique(); b.ToTable("NotificationReceipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("IsActive") .HasColumnType("boolean"); b.Property("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.HasKey("Id"); b.ToTable("Tenants"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("FullName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsLocked") .HasColumnType("boolean"); b.Property("LastLoginAt") .HasColumnType("timestamp with time zone"); b.Property("PasswordHash") .IsRequired() .HasColumnType("text"); b.Property("Role") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("TokenVersion") .HasColumnType("integer"); b.Property("Username") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("TenantId"); b.HasIndex("Username") .IsUnique(); b.ToTable("Users"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("ActivationCodes") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Classrooms") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Devices") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Classroom", "Classroom") .WithMany("Devices") .HasForeignKey("TenantId", "ClassroomId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Classroom"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckRun", b => { b.HasOne("ClassNotify.Server.Domain.Entities.DeviceSelfCheckBatch", "Batch") .WithMany() .HasForeignKey("BatchId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Batch"); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Notifications") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany("Receipts") .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Notification", "Notification") .WithMany("Receipts") .HasForeignKey("NotificationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Notification"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Users") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Navigation("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Navigation("ActivationCodes"); b.Navigation("Classrooms"); b.Navigation("Devices"); b.Navigation("Notifications"); b.Navigation("Users"); }); #pragma warning restore 612, 618 } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260925122539_AddDeviceSelfCheckBatch.Designer.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260925122539_AddDeviceSelfCheckBatch.cs SHA256: 1a342e07f2226caa24b2cdc3cb25af4ea30c7221cd96ea04fd0466d04209f910 SIZE: 6676 ================================================================================ using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace ClassNotify.Server.Data.Migrations { /// public partial class AddDeviceSelfCheckBatch : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn( name: "BatchId", table: "DeviceSelfChecks", type: "character varying(100)", maxLength: 100, nullable: true); migrationBuilder.AddColumn( name: "DeadlineAtUtc", table: "DeviceSelfChecks", type: "timestamp with time zone", nullable: false, defaultValue: new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0))); migrationBuilder.AddColumn( name: "DispatchAttemptCount", table: "DeviceSelfChecks", type: "integer", nullable: false, defaultValue: 0); migrationBuilder.AddColumn( name: "DispatchedAtUtc", table: "DeviceSelfChecks", type: "timestamp with time zone", nullable: true); migrationBuilder.AddColumn( name: "OverallStatus", table: "DeviceSelfChecks", type: "character varying(32)", maxLength: 32, nullable: true); migrationBuilder.AddColumn( name: "RunState", table: "DeviceSelfChecks", type: "character varying(32)", maxLength: 32, nullable: false, defaultValue: "PendingDispatch"); migrationBuilder.CreateTable( name: "DeviceSelfCheckBatches", columns: table => new { Id = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), CorrelationId = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), ClientRequestId = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), CreatedByUserId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), CreatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), DeadlineAtUtc = table.Column(type: "timestamp with time zone", nullable: false), CompletedAtUtc = table.Column(type: "timestamp with time zone", nullable: true), TargetDeviceCount = table.Column(type: "integer", nullable: false), Status = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), UpdatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false) }, constraints: table => { table.PrimaryKey("PK_DeviceSelfCheckBatches", x => x.Id); }); migrationBuilder.CreateIndex( name: "IX_DeviceSelfChecks_BatchId_DeviceId", table: "DeviceSelfChecks", columns: new[] { "BatchId", "DeviceId" }, unique: true, filter: "\"BatchId\" IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_DeviceSelfChecks_BatchId_OverallStatus", table: "DeviceSelfChecks", columns: new[] { "BatchId", "OverallStatus" }); migrationBuilder.CreateIndex( name: "IX_DeviceSelfChecks_BatchId_RunState", table: "DeviceSelfChecks", columns: new[] { "BatchId", "RunState" }); migrationBuilder.CreateIndex( name: "IX_DeviceSelfCheckBatches_CreatedAtUtc", table: "DeviceSelfCheckBatches", column: "CreatedAtUtc"); migrationBuilder.CreateIndex( name: "IX_DeviceSelfCheckBatches_CreatedByUserId_ClientRequestId", table: "DeviceSelfCheckBatches", columns: new[] { "CreatedByUserId", "ClientRequestId" }, unique: true); migrationBuilder.AddForeignKey( name: "FK_DeviceSelfChecks_DeviceSelfCheckBatches_BatchId", table: "DeviceSelfChecks", column: "BatchId", principalTable: "DeviceSelfCheckBatches", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_DeviceSelfChecks_DeviceSelfCheckBatches_BatchId", table: "DeviceSelfChecks"); migrationBuilder.DropTable( name: "DeviceSelfCheckBatches"); migrationBuilder.DropIndex( name: "IX_DeviceSelfChecks_BatchId_DeviceId", table: "DeviceSelfChecks"); migrationBuilder.DropIndex( name: "IX_DeviceSelfChecks_BatchId_OverallStatus", table: "DeviceSelfChecks"); migrationBuilder.DropIndex( name: "IX_DeviceSelfChecks_BatchId_RunState", table: "DeviceSelfChecks"); migrationBuilder.DropColumn( name: "BatchId", table: "DeviceSelfChecks"); migrationBuilder.DropColumn( name: "DeadlineAtUtc", table: "DeviceSelfChecks"); migrationBuilder.DropColumn( name: "DispatchAttemptCount", table: "DeviceSelfChecks"); migrationBuilder.DropColumn( name: "DispatchedAtUtc", table: "DeviceSelfChecks"); migrationBuilder.DropColumn( name: "OverallStatus", table: "DeviceSelfChecks"); migrationBuilder.DropColumn( name: "RunState", table: "DeviceSelfChecks"); } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260925122539_AddDeviceSelfCheckBatch.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260925141051_AddDeviceSupportBundle.Designer.cs SHA256: 4c60e7216e97e3a17a5638990da38e2d3c042c41a8f3008766d0e72223c60144 SIZE: 37827 ================================================================================ // using System; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable namespace ClassNotify.Server.Data.Migrations { [DbContext(typeof(ClassNotifyDbContext))] [Migration("20260925141051_AddDeviceSupportBundle")] partial class AddDeviceSupportBundle { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "8.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.Property("Code") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsUsed") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("UsedAt") .HasColumnType("timestamp with time zone"); b.Property("UsedByDeviceId") .HasColumnType("text"); b.HasKey("Code"); b.HasIndex("ClassroomId"); b.HasIndex("Code") .IsUnique(); b.HasIndex("InstallationId"); b.HasIndex("TenantId"); b.ToTable("ActivationCodes"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.AdminAuditEvent", b => { b.Property("Id") .HasColumnType("text"); b.Property("Action") .IsRequired() .HasColumnType("text"); b.Property("ActorRole") .IsRequired() .HasColumnType("text"); b.Property("ActorUsername") .IsRequired() .HasColumnType("text"); b.Property("Details") .HasColumnType("text"); b.Property("IpAddress") .HasColumnType("text"); b.Property("OccurredAt") .HasColumnType("timestamp with time zone"); b.Property("TargetId") .IsRequired() .HasColumnType("text"); b.Property("TargetType") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.ToTable("AdminAuditEvents"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Property("TenantId") .HasColumnType("text"); b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Grade") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("RoomNumber") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.HasKey("TenantId", "Id"); b.HasIndex("TenantId", "Id"); b.ToTable("Classrooms"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Property("Id") .HasColumnType("text"); b.Property("Architecture") .HasColumnType("text"); b.Property("ClassroomId") .IsRequired() .HasColumnType("text"); b.Property("ClientVersion") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceTokenHash") .IsRequired() .HasColumnType("text"); b.Property("Hostname") .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsActive") .HasColumnType("boolean"); b.Property("LastHeartbeatAt") .HasColumnType("timestamp with time zone"); b.Property("LastHeartbeatCorrelationId") .HasColumnType("text"); b.Property("OsVersion") .HasColumnType("text"); b.Property("ProtocolVersion") .HasColumnType("integer"); b.Property("RawDeviceToken") .HasColumnType("text"); b.Property("ServiceVersion") .HasColumnType("text"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("Id") .IsUnique(); b.HasIndex("InstallationId") .IsUnique() .HasFilter("\"InstallationId\" IS NOT NULL"); b.HasIndex("TenantId"); b.HasIndex("TenantId", "ClassroomId"); b.ToTable("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CommandType") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CompletedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedBy") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DurationMs") .HasColumnType("bigint"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("Parameters") .HasColumnType("text"); b.Property("ResultCode") .HasColumnType("integer"); b.Property("ResultMessage") .HasMaxLength(1000) .HasColumnType("character varying(1000)"); b.Property("StartedAt") .HasColumnType("timestamp with time zone"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("DeviceId", "Status"); b.HasIndex("Status", "ExpiresAt"); b.HasIndex("TenantId", "DeviceId", "CreatedAt") .IsDescending(false, false, true); b.ToTable("DeviceCommands"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCredentialRecord", b => { b.Property("DeviceId") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceTokenHash") .IsRequired() .HasColumnType("text"); b.Property("EncryptedRecoverableToken") .IsRequired() .HasColumnType("text"); b.Property("InstallationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("RotatedAt") .HasColumnType("timestamp with time zone"); b.HasKey("DeviceId"); b.HasIndex("DeviceId") .IsUnique(); b.HasIndex("InstallationId") .IsUnique(); b.ToTable("DeviceCredentials"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckBatch", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ClientRequestId") .IsRequired() .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CreatedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeadlineAtUtc") .HasColumnType("timestamp with time zone"); b.Property("Status") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("TargetDeviceCount") .HasColumnType("integer"); b.Property("UpdatedAtUtc") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("CreatedAtUtc"); b.HasIndex("CreatedByUserId", "ClientRequestId") .IsUnique(); b.ToTable("DeviceSelfCheckBatches"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckRun", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("BatchId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("DeadlineAtUtc") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DispatchAttemptCount") .HasColumnType("integer"); b.Property("DispatchedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("OverallStatus") .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("RequestedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("RequestedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ResultJson") .HasMaxLength(32768) .HasColumnType("character varying(32768)"); b.Property("RunState") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(32) .HasColumnType("character varying(32)") .HasDefaultValue("PendingDispatch"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("BatchId", "DeviceId") .IsUnique() .HasFilter("\"BatchId\" IS NOT NULL"); b.HasIndex("BatchId", "OverallStatus"); b.HasIndex("BatchId", "RunState"); b.HasIndex("DeviceId", "RequestedAtUtc") .IsDescending(false, true); b.HasIndex("TenantId", "Status"); b.ToTable("DeviceSelfChecks"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSupportBundle", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ClientRequestId") .IsRequired() .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("DeadlineAtUtc") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DispatchAttemptCount") .HasColumnType("integer"); b.Property("DispatchedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("ErrorCode") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ExpiresAtUtc") .HasColumnType("timestamp with time zone"); b.Property("LastDispatchAttemptAtUtc") .HasColumnType("timestamp with time zone"); b.Property("NextDispatchAttemptAtUtc") .HasColumnType("timestamp with time zone"); b.Property("RequestedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Sha256") .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("SizeBytes") .HasColumnType("bigint"); b.Property("Status") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("StoragePath") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("UpdatedAtUtc") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("DeviceId") .IsUnique() .HasDatabaseName("UX_DeviceSupportBundles_Device_Active") .HasFilter("\"Status\" IN ('PendingDispatch', 'Collecting')"); b.HasIndex("ExpiresAtUtc"); b.HasIndex("DeviceId", "CreatedAtUtc"); b.HasIndex("RequestedByUserId", "ClientRequestId") .IsUnique(); b.HasIndex("Status", "NextDispatchAttemptAtUtc"); b.HasIndex("TenantId", "CreatedAtUtc"); b.ToTable("DeviceSupportBundles"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.MigrationMarker", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Details") .HasColumnType("text"); b.Property("MigratedAt") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.ToTable("MigrationMarkers"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("BroadcastId") .HasColumnType("text"); b.Property("CancelledAt") .HasColumnType("timestamp with time zone"); b.Property("CancelledBy") .HasColumnType("text"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DurationSeconds") .HasColumnType("integer"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("IsCancelled") .HasColumnType("boolean"); b.Property("Message") .IsRequired() .HasColumnType("text"); b.Property("Priority") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("SenderName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("SenderUserId") .HasColumnType("text"); b.Property("Shake") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("Voice") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("ClassroomId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "ClassroomId", "ExpiresAt"); b.ToTable("Notifications"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("AcknowledgedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceReceivedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayedAt") .HasColumnType("timestamp with time zone"); b.Property("FailedAt") .HasColumnType("timestamp with time zone"); b.Property("FailureReason") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("NotificationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("UpdatedAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptCapturedAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptPath") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("VisualReceiptSha256") .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("VisualReceiptSizeBytes") .HasColumnType("bigint"); b.Property("VisualReceiptState") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(32) .HasColumnType("character varying(32)") .HasDefaultValue("None"); b.HasKey("Id"); b.HasIndex("VisualReceiptExpiresAt"); b.HasIndex("DeviceId", "Status"); b.HasIndex("DeviceId", "UpdatedAt") .IsDescending(false, true); b.HasIndex("NotificationId", "DeviceId") .IsUnique(); b.ToTable("NotificationReceipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("IsActive") .HasColumnType("boolean"); b.Property("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.HasKey("Id"); b.ToTable("Tenants"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("FullName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsLocked") .HasColumnType("boolean"); b.Property("LastLoginAt") .HasColumnType("timestamp with time zone"); b.Property("PasswordHash") .IsRequired() .HasColumnType("text"); b.Property("Role") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("TokenVersion") .HasColumnType("integer"); b.Property("Username") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("TenantId"); b.HasIndex("Username") .IsUnique(); b.ToTable("Users"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("ActivationCodes") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Classrooms") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Devices") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Classroom", "Classroom") .WithMany("Devices") .HasForeignKey("TenantId", "ClassroomId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Classroom"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckRun", b => { b.HasOne("ClassNotify.Server.Domain.Entities.DeviceSelfCheckBatch", "Batch") .WithMany() .HasForeignKey("BatchId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Batch"); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSupportBundle", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Notifications") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany("Receipts") .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Notification", "Notification") .WithMany("Receipts") .HasForeignKey("NotificationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Notification"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Users") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Navigation("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Navigation("ActivationCodes"); b.Navigation("Classrooms"); b.Navigation("Devices"); b.Navigation("Notifications"); b.Navigation("Users"); }); #pragma warning restore 612, 618 } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260925141051_AddDeviceSupportBundle.Designer.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260925141051_AddDeviceSupportBundle.cs SHA256: 6d8648183a90e153db2a3b1e5fc297ac695afd8162cc6048888064e1911744de SIZE: 5819 ================================================================================ using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace ClassNotify.Server.Data.Migrations { /// public partial class AddDeviceSupportBundle : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "DeviceSupportBundles", columns: table => new { Id = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), ClientRequestId = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), TenantId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), DeviceId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), CorrelationId = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), RequestedByUserId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), Status = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), CreatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), UpdatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), DeadlineAtUtc = table.Column(type: "timestamp with time zone", nullable: false), DispatchedAtUtc = table.Column(type: "timestamp with time zone", nullable: true), CompletedAtUtc = table.Column(type: "timestamp with time zone", nullable: true), ExpiresAtUtc = table.Column(type: "timestamp with time zone", nullable: true), DispatchAttemptCount = table.Column(type: "integer", nullable: false), LastDispatchAttemptAtUtc = table.Column(type: "timestamp with time zone", nullable: true), NextDispatchAttemptAtUtc = table.Column(type: "timestamp with time zone", nullable: true), StoragePath = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), SizeBytes = table.Column(type: "bigint", nullable: true), Sha256 = table.Column(type: "character varying(64)", maxLength: 64, nullable: true), ErrorCode = table.Column(type: "character varying(100)", maxLength: 100, nullable: true) }, constraints: table => { table.PrimaryKey("PK_DeviceSupportBundles", x => x.Id); table.ForeignKey( name: "FK_DeviceSupportBundles_Devices_DeviceId", column: x => x.DeviceId, principalTable: "Devices", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_DeviceSupportBundles_Tenants_TenantId", column: x => x.TenantId, principalTable: "Tenants", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.CheckConstraint( name: "CK_DeviceSupportBundles_Status", sql: "\"Status\" IN ('PendingDispatch', 'Collecting', 'Available', 'Failed', 'TimedOut', 'Expired')"); }); migrationBuilder.CreateIndex( name: "IX_DeviceSupportBundles_CorrelationId", table: "DeviceSupportBundles", column: "CorrelationId"); migrationBuilder.CreateIndex( name: "IX_DeviceSupportBundles_DeviceId_CreatedAtUtc", table: "DeviceSupportBundles", columns: new[] { "DeviceId", "CreatedAtUtc" }); migrationBuilder.CreateIndex( name: "IX_DeviceSupportBundles_ExpiresAtUtc", table: "DeviceSupportBundles", column: "ExpiresAtUtc"); migrationBuilder.CreateIndex( name: "IX_DeviceSupportBundles_RequestedByUserId_ClientRequestId", table: "DeviceSupportBundles", columns: new[] { "RequestedByUserId", "ClientRequestId" }, unique: true); migrationBuilder.CreateIndex( name: "IX_DeviceSupportBundles_Status_NextDispatchAttemptAtUtc", table: "DeviceSupportBundles", columns: new[] { "Status", "NextDispatchAttemptAtUtc" }); migrationBuilder.CreateIndex( name: "IX_DeviceSupportBundles_TenantId_CreatedAtUtc", table: "DeviceSupportBundles", columns: new[] { "TenantId", "CreatedAtUtc" }); migrationBuilder.CreateIndex( name: "UX_DeviceSupportBundles_Device_Active", table: "DeviceSupportBundles", column: "DeviceId", unique: true, filter: "\"Status\" IN ('PendingDispatch', 'Collecting')"); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "DeviceSupportBundles"); } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260925141051_AddDeviceSupportBundle.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260926200000_AddDeviceLicenseLifecycle.Designer.cs SHA256: f062e50b9a25884b9f536eadfbc6e02d33ff28dff26180996dd4d5c1ee16313e SIZE: 977 ================================================================================ // using System; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable namespace ClassNotify.Server.Data.Migrations { [DbContext(typeof(ClassNotifyDbContext))] [Migration("20260926200000_AddDeviceLicenseLifecycle")] partial class AddDeviceLicenseLifecycle { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "8.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); #pragma warning restore 612, 618 } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260926200000_AddDeviceLicenseLifecycle.Designer.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260926200000_AddDeviceLicenseLifecycle.cs SHA256: 111d2bd200f20a250b9050c49dc783a520cc22ebff6599f295e68fdfd9786277 SIZE: 4454 ================================================================================ using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace ClassNotify.Server.Data.Migrations { /// public partial class AddDeviceLicenseLifecycle : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn( name: "LicensedUntil", table: "Devices", type: "timestamp with time zone", nullable: true); migrationBuilder.AddColumn( name: "LicenseTier", table: "Devices", type: "text", nullable: false, defaultValue: "Trial"); migrationBuilder.AddColumn( name: "TrialUsed", table: "Devices", type: "boolean", nullable: false, defaultValue: true); migrationBuilder.AddColumn( name: "LicenseDurationDays", table: "ActivationCodes", type: "integer", nullable: true, defaultValue: 7); migrationBuilder.AddColumn( name: "LicenseTier", table: "ActivationCodes", type: "text", nullable: false, defaultValue: "Trial"); migrationBuilder.CreateTable( name: "DeviceLicenses", columns: table => new { Id = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), TenantId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), DeviceId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), ClassroomId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), Action = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), LicenseTier = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), GrantedDays = table.Column(type: "integer", nullable: true), PreviousLicensedUntil = table.Column(type: "timestamp with time zone", nullable: true), NewLicensedUntil = table.Column(type: "timestamp with time zone", nullable: true), SourceActivationCode = table.Column(type: "character varying(100)", maxLength: 100, nullable: true), OperatorUsername = table.Column(type: "character varying(100)", maxLength: 100, nullable: true), Reason = table.Column(type: "character varying(250)", maxLength: 250, nullable: true), CreatedAt = table.Column(type: "timestamp with time zone", nullable: false) }, constraints: table => { table.PrimaryKey("PK_DeviceLicenses", x => x.Id); }); migrationBuilder.CreateIndex( name: "IX_DeviceLicenses_TenantId_DeviceId", table: "DeviceLicenses", columns: new[] { "TenantId", "DeviceId" }); migrationBuilder.CreateIndex( name: "IX_DeviceLicenses_CreatedAt", table: "DeviceLicenses", column: "CreatedAt"); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "DeviceLicenses"); migrationBuilder.DropColumn( name: "LicensedUntil", table: "Devices"); migrationBuilder.DropColumn( name: "LicenseTier", table: "Devices"); migrationBuilder.DropColumn( name: "TrialUsed", table: "Devices"); migrationBuilder.DropColumn( name: "LicenseDurationDays", table: "ActivationCodes"); migrationBuilder.DropColumn( name: "LicenseTier", table: "ActivationCodes"); } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260926200000_AddDeviceLicenseLifecycle.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260926203000_AddLicenseConcurrencyAndHardwareTrial.Designer.cs SHA256: a7928c85696d0ac060b8af610f8e3a76fa1ab8a6013fad6ec041d02c446f649e SIZE: 1001 ================================================================================ // using System; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable namespace ClassNotify.Server.Data.Migrations { [DbContext(typeof(ClassNotifyDbContext))] [Migration("20260926203000_AddLicenseConcurrencyAndHardwareTrial")] partial class AddLicenseConcurrencyAndHardwareTrial { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "8.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); #pragma warning restore 612, 618 } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260926203000_AddLicenseConcurrencyAndHardwareTrial.Designer.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/20260926203000_AddLicenseConcurrencyAndHardwareTrial.cs SHA256: f51664d740086595c97fabed149ed0e6cb42396b5880ec1d52d0a19789e55b14 SIZE: 1607 ================================================================================ using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace ClassNotify.Server.Data.Migrations { /// public partial class AddLicenseConcurrencyAndHardwareTrial : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn( name: "InstallationId", table: "DeviceLicenses", type: "character varying(100)", maxLength: 100, nullable: true); migrationBuilder.CreateIndex( name: "IX_DeviceLicenses_InstallationId", table: "DeviceLicenses", column: "InstallationId"); migrationBuilder.CreateIndex( name: "IX_DeviceLicenses_SourceActivationCode", table: "DeviceLicenses", column: "SourceActivationCode", unique: true, filter: "\"SourceActivationCode\" IS NOT NULL"); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_DeviceLicenses_InstallationId", table: "DeviceLicenses"); migrationBuilder.DropIndex( name: "IX_DeviceLicenses_SourceActivationCode", table: "DeviceLicenses"); migrationBuilder.DropColumn( name: "InstallationId", table: "DeviceLicenses"); } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/20260926203000_AddLicenseConcurrencyAndHardwareTrial.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Data/Migrations/ClassNotifyDbContextModelSnapshot.cs SHA256: e0c68e617d572f6a53ab57dddea15146d0ef17bae0d9665096afd5aebd886c59 SIZE: 37959 ================================================================================ // using System; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; #nullable disable namespace ClassNotify.Server.Data.Migrations { [DbContext(typeof(ClassNotifyDbContext))] public partial class ClassNotifyDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "8.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.Property("Code") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsUsed") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("UsedAt") .HasColumnType("timestamp with time zone"); b.Property("UsedByDeviceId") .HasColumnType("text"); b.HasKey("Code"); b.HasIndex("ClassroomId"); b.HasIndex("Code") .IsUnique(); b.HasIndex("InstallationId"); b.HasIndex("TenantId"); b.ToTable("ActivationCodes"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.AdminAuditEvent", b => { b.Property("Id") .HasColumnType("text"); b.Property("Action") .IsRequired() .HasColumnType("text"); b.Property("ActorRole") .IsRequired() .HasColumnType("text"); b.Property("ActorUsername") .IsRequired() .HasColumnType("text"); b.Property("Details") .HasColumnType("text"); b.Property("IpAddress") .HasColumnType("text"); b.Property("OccurredAt") .HasColumnType("timestamp with time zone"); b.Property("TargetId") .IsRequired() .HasColumnType("text"); b.Property("TargetType") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.ToTable("AdminAuditEvents"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Property("TenantId") .HasColumnType("text"); b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Grade") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("RoomNumber") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.HasKey("TenantId", "Id"); b.HasIndex("TenantId", "Id"); b.ToTable("Classrooms"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Property("Id") .HasColumnType("text"); b.Property("Architecture") .HasColumnType("text"); b.Property("ClassroomId") .IsRequired() .HasColumnType("text"); b.Property("ClientVersion") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceTokenHash") .IsRequired() .HasColumnType("text"); b.Property("Hostname") .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("InstallationId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsActive") .HasColumnType("boolean"); b.Property("LastHeartbeatAt") .HasColumnType("timestamp with time zone"); b.Property("LastHeartbeatCorrelationId") .HasColumnType("text"); b.Property("OsVersion") .HasColumnType("text"); b.Property("ProtocolVersion") .HasColumnType("integer"); b.Property("RawDeviceToken") .HasColumnType("text"); b.Property("ServiceVersion") .HasColumnType("text"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("Id") .IsUnique(); b.HasIndex("InstallationId") .IsUnique() .HasFilter("\"InstallationId\" IS NOT NULL"); b.HasIndex("TenantId"); b.HasIndex("TenantId", "ClassroomId"); b.ToTable("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CommandType") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CompletedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("CreatedBy") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DurationMs") .HasColumnType("bigint"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("Parameters") .HasColumnType("text"); b.Property("ResultCode") .HasColumnType("integer"); b.Property("ResultMessage") .HasMaxLength(1000) .HasColumnType("character varying(1000)"); b.Property("StartedAt") .HasColumnType("timestamp with time zone"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("DeviceId", "Status"); b.HasIndex("Status", "ExpiresAt"); b.HasIndex("TenantId", "DeviceId", "CreatedAt") .IsDescending(false, false, true); b.ToTable("DeviceCommands"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCredentialRecord", b => { b.Property("DeviceId") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceTokenHash") .IsRequired() .HasColumnType("text"); b.Property("EncryptedRecoverableToken") .IsRequired() .HasColumnType("text"); b.Property("InstallationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("RotatedAt") .HasColumnType("timestamp with time zone"); b.HasKey("DeviceId"); b.HasIndex("DeviceId") .IsUnique(); b.HasIndex("InstallationId") .IsUnique(); b.ToTable("DeviceCredentials"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckBatch", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ClientRequestId") .IsRequired() .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CreatedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeadlineAtUtc") .HasColumnType("timestamp with time zone"); b.Property("Status") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("TargetDeviceCount") .HasColumnType("integer"); b.Property("UpdatedAtUtc") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("CreatedAtUtc"); b.HasIndex("CreatedByUserId", "ClientRequestId") .IsUnique(); b.ToTable("DeviceSelfCheckBatches"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckRun", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("BatchId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("DeadlineAtUtc") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DispatchAttemptCount") .HasColumnType("integer"); b.Property("DispatchedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("OverallStatus") .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("RequestedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("RequestedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ResultJson") .HasMaxLength(32768) .HasColumnType("character varying(32768)"); b.Property("RunState") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(32) .HasColumnType("character varying(32)") .HasDefaultValue("PendingDispatch"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("BatchId", "DeviceId") .IsUnique() .HasFilter("\"BatchId\" IS NOT NULL"); b.HasIndex("BatchId", "OverallStatus"); b.HasIndex("BatchId", "RunState"); b.HasIndex("DeviceId", "RequestedAtUtc") .IsDescending(false, true); b.HasIndex("TenantId", "Status"); b.ToTable("DeviceSelfChecks"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSupportBundle", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ClientRequestId") .IsRequired() .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("CompletedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("DeadlineAtUtc") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DispatchAttemptCount") .HasColumnType("integer"); b.Property("DispatchedAtUtc") .HasColumnType("timestamp with time zone"); b.Property("ErrorCode") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("ExpiresAtUtc") .HasColumnType("timestamp with time zone"); b.Property("LastDispatchAttemptAtUtc") .HasColumnType("timestamp with time zone"); b.Property("NextDispatchAttemptAtUtc") .HasColumnType("timestamp with time zone"); b.Property("RequestedByUserId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Sha256") .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("SizeBytes") .HasColumnType("bigint"); b.Property("Status") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("StoragePath") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("TenantId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("UpdatedAtUtc") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("DeviceId") .IsUnique() .HasDatabaseName("UX_DeviceSupportBundles_Device_Active") .HasFilter("\"Status\" IN ('PendingDispatch', 'Collecting')"); b.HasIndex("ExpiresAtUtc"); b.HasIndex("DeviceId", "CreatedAtUtc"); b.HasIndex("RequestedByUserId", "ClientRequestId") .IsUnique(); b.HasIndex("Status", "NextDispatchAttemptAtUtc"); b.HasIndex("TenantId", "CreatedAtUtc"); b.ToTable("DeviceSupportBundles", t => { t.HasCheckConstraint("CK_DeviceSupportBundles_Status", "\"Status\" IN ('PendingDispatch', 'Collecting', 'Available', 'Failed', 'TimedOut', 'Expired')"); }); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.MigrationMarker", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Details") .HasColumnType("text"); b.Property("MigratedAt") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.ToTable("MigrationMarkers"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("BroadcastId") .HasColumnType("text"); b.Property("CancelledAt") .HasColumnType("timestamp with time zone"); b.Property("CancelledBy") .HasColumnType("text"); b.Property("ClassroomId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("CorrelationId") .IsRequired() .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("DurationSeconds") .HasColumnType("integer"); b.Property("ExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("IsCancelled") .HasColumnType("boolean"); b.Property("Message") .IsRequired() .HasColumnType("text"); b.Property("Priority") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("SenderName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("SenderUserId") .HasColumnType("text"); b.Property("Shake") .HasColumnType("boolean"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("Title") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property("Voice") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("CorrelationId"); b.HasIndex("ClassroomId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "CreatedAt") .IsDescending(false, true); b.HasIndex("TenantId", "ClassroomId", "ExpiresAt"); b.ToTable("Notifications"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.Property("Id") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("AcknowledgedAt") .HasColumnType("timestamp with time zone"); b.Property("DeviceId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("DeviceReceivedAt") .HasColumnType("timestamp with time zone"); b.Property("DisplayedAt") .HasColumnType("timestamp with time zone"); b.Property("FailedAt") .HasColumnType("timestamp with time zone"); b.Property("FailureReason") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("NotificationId") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("Status") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("UpdatedAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptCapturedAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptExpiresAt") .HasColumnType("timestamp with time zone"); b.Property("VisualReceiptPath") .HasMaxLength(500) .HasColumnType("character varying(500)"); b.Property("VisualReceiptSha256") .HasMaxLength(64) .HasColumnType("character varying(64)"); b.Property("VisualReceiptSizeBytes") .HasColumnType("bigint"); b.Property("VisualReceiptState") .IsRequired() .ValueGeneratedOnAdd() .HasMaxLength(32) .HasColumnType("character varying(32)") .HasDefaultValue("None"); b.HasKey("Id"); b.HasIndex("VisualReceiptExpiresAt"); b.HasIndex("DeviceId", "Status"); b.HasIndex("DeviceId", "UpdatedAt") .IsDescending(false, true); b.HasIndex("NotificationId", "DeviceId") .IsUnique(); b.ToTable("NotificationReceipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("IsActive") .HasColumnType("boolean"); b.Property("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.HasKey("Id"); b.ToTable("Tenants"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.Property("Id") .HasColumnType("text"); b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); b.Property("FullName") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property("IsLocked") .HasColumnType("boolean"); b.Property("LastLoginAt") .HasColumnType("timestamp with time zone"); b.Property("PasswordHash") .IsRequired() .HasColumnType("text"); b.Property("Role") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property("TenantId") .IsRequired() .HasColumnType("text"); b.Property("TokenVersion") .HasColumnType("integer"); b.Property("Username") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.HasKey("Id"); b.HasIndex("TenantId"); b.HasIndex("Username") .IsUnique(); b.ToTable("Users"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("ActivationCodes") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Classrooms") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Devices") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Classroom", "Classroom") .WithMany("Devices") .HasForeignKey("TenantId", "ClassroomId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Classroom"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCommand", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSelfCheckRun", b => { b.HasOne("ClassNotify.Server.Domain.Entities.DeviceSelfCheckBatch", "Batch") .WithMany() .HasForeignKey("BatchId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Batch"); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceSupportBundle", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany() .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany() .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Notifications") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device") .WithMany("Receipts") .HasForeignKey("DeviceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("ClassNotify.Server.Domain.Entities.Notification", "Notification") .WithMany("Receipts") .HasForeignKey("NotificationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Device"); b.Navigation("Notification"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b => { b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant") .WithMany("Users") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Tenant"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b => { b.Navigation("Devices"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b => { b.Navigation("Receipts"); }); modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b => { b.Navigation("ActivationCodes"); b.Navigation("Classrooms"); b.Navigation("Devices"); b.Navigation("Notifications"); b.Navigation("Users"); }); #pragma warning restore 612, 618 } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Data/Migrations/ClassNotifyDbContextModelSnapshot.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Dockerfile SHA256: d261df66b19b4019570414e6554475f140fa5a7dd562a2723e8340bd618bf64e SIZE: 647 ================================================================================ FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /app # Copy solution and projects COPY ClassNotify.sln . COPY src/Shared/ClassNotify.Shared/ src/Shared/ClassNotify.Shared/ COPY src/Server/ClassNotify.Server/ src/Server/ClassNotify.Server/ # Restore and build Server RUN dotnet restore src/Server/ClassNotify.Server/ClassNotify.Server.csproj RUN dotnet publish src/Server/ClassNotify.Server/ClassNotify.Server.csproj -c Release -o /app/publish FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime WORKDIR /app COPY --from=build /app/publish . ENV ASPNETCORE_URLS=http://+:5000 EXPOSE 5000 ENTRYPOINT ["dotnet", "ClassNotify.Server.dll"] ================================================================================ FILE END: src/Server/ClassNotify.Server/Dockerfile ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Domain/Diagnostics/DiagnosticsDto.cs SHA256: bd64b45569f3225fb8e3a791839fb6db02c2842bf7721213ec92a42684c6c3d3 SIZE: 1021 ================================================================================ namespace ClassNotify.Server.Domain.Diagnostics; public sealed class DiagnosticsDto { public string OverallStatus { get; set; } = "Healthy"; // Healthy, Degraded, Unhealthy public DateTimeOffset ServerUtc { get; set; } = DateTimeOffset.UtcNow; public long UptimeSeconds { get; set; } public string ReleaseId { get; set; } = string.Empty; public DiagnosticComponentDto Database { get; set; } = new(); public DiagnosticComponentDto Disk { get; set; } = new(); public DiagnosticComponentDto Backup { get; set; } = new(); public DiagnosticComponentDto VisualReceiptCleanup { get; set; } = new(); public int ActiveDeviceConnections { get; set; } public int ActiveTeacherConnections { get; set; } } public sealed class DiagnosticComponentDto { public string Status { get; set; } = "Healthy"; // Healthy, Degraded, Unhealthy public string Summary { get; set; } = string.Empty; public long? LatencyMs { get; set; } public DateTimeOffset? LastSuccessUtc { get; set; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Domain/Diagnostics/DiagnosticsDto.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Domain/Entities/Entities.cs SHA256: 83b5664f8d325595e0ac25b50ad74b1142d6f99d50a2a4ddc5ae3b17f92fb930 SIZE: 28231 ================================================================================ using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using ClassNotify.Shared.Models; namespace ClassNotify.Server.Domain.Entities; /// /// 学校/机构租户实体 /// public class Tenant { [Key] public string Id { get; set; } = string.Empty; // e.g. "t_beijing_no4" public string Name { get; set; } = string.Empty; // e.g. "北京四中" public string TenantType { get; set; } = "School"; // "School" (普通学校) or "Personal" (独立/免校个人教师空间) public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public ICollection Classrooms { get; set; } = new List(); public ICollection Users { get; set; } = new List(); public ICollection Devices { get; set; } = new List(); public ICollection ActivationCodes { get; set; } = new List(); public ICollection Notifications { get; set; } = new List(); } /// /// 教师/管理员用户实体 /// public class User { [Key] public string Id { get; set; } = string.Empty; // e.g. "usr_1001" public string TenantId { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string PasswordHash { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; [NotMapped] public string DisplayName => FullName; public string Role { get; set; } = "Teacher"; // Teacher, SchoolAdmin, SuperAdmin public bool IsLocked { get; set; } = false; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? LastLoginAt { get; set; } public int TokenVersion { get; set; } = 1; public string? RecoveryEmail { get; set; } public bool EmailVerified { get; set; } = false; public string? RecoveryKeyHash { get; set; } public DateTimeOffset? RecoveryKeyCreatedAtUtc { get; set; } public bool MustChangePassword { get; set; } = false; public DateTimeOffset? TemporaryPasswordExpiresAtUtc { get; set; } public string? Mobile { get; set; } public DateTimeOffset? TrialEndsAt { get; set; } public DateTimeOffset? VipExpiresAt { get; set; } public bool IsVipActive(DateTimeOffset now) => VipExpiresAt.HasValue && VipExpiresAt.Value > now; public bool IsTrialActive(DateTimeOffset now) => TrialEndsAt.HasValue && TrialEndsAt.Value > now; public Tenant? Tenant { get; set; } } /// /// 班级实体 /// public class Classroom { public string Id { get; set; } = string.Empty; // e.g. "cls_801" public string TenantId { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty; // e.g. "八年级(1)班" public string? Grade { get; set; } public string? RoomNumber { get; set; } public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public Tenant? Tenant { get; set; } public ICollection Devices { get; set; } = new List(); } /// /// 教室硬件多媒体设备实体 /// public class Device { [Key] public string Id { get; set; } = string.Empty; // e.g. "dev_52f0" public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string DeviceTokenHash { get; set; } = string.Empty; public string? RawDeviceToken { get; set; } // Kept only for legacy migration public string? InstallationId { get; set; } // Unique installation instance identifier public string? HardwareComponentsHash { get; set; } // Deterministic hardware fingerprint (MachineGuid + BIOS + Board) public string? Hostname { get; set; } public string? DisplayLabel { get; set; } // Per-device custom remark/label for SuperAdmin public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? BindingStartedAtUtc { get; set; } public DateTimeOffset? LastHeartbeatAt { get; set; } public string? LastHeartbeatCorrelationId { get; set; } public string? ServiceVersion { get; set; } public string? ClientVersion { get; set; } public int? ProtocolVersion { get; set; } public string? OsVersion { get; set; } public string? Architecture { get; set; } [System.ComponentModel.DataAnnotations.Schema.NotMapped] public bool? ClientProcessAvailable { get; set; } [System.ComponentModel.DataAnnotations.Schema.NotMapped] public bool IsOnline => LastHeartbeatAt.HasValue && (DateTimeOffset.UtcNow - LastHeartbeatAt.Value).TotalSeconds <= 120; // License Management Fields (P3) public DateTimeOffset? LicensedUntil { get; set; } public string LicenseTier { get; set; } = "Trial"; public bool TrialUsed { get; set; } = true; public Tenant? Tenant { get; set; } public Classroom? Classroom { get; set; } public ICollection Receipts { get; set; } = new List(); } /// /// 设备加密凭据恢复记录 (仅用于 InstallationId 幂等恢复,不直接在业务代码暴露明文) /// public class DeviceCredentialRecord { [Key] public string DeviceId { get; set; } = string.Empty; public string InstallationId { get; set; } = string.Empty; public string DeviceTokenHash { get; set; } = string.Empty; public string EncryptedRecoverableToken { get; set; } = string.Empty; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? RotatedAt { get; set; } } /// /// 一次性设备激活码实体 /// public class ActivationCode { [Key] public string Code { get; set; } = string.Empty; // e.g. "H8K4-29DP" public string? Id { get; set; } // Opaque unique identifier for UI and Reveal API, e.g. "act_..." public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public DateTimeOffset ExpiresAt { get; set; } = DateTimeOffset.UtcNow.AddDays(7); public bool IsUsed { get; set; } public DateTimeOffset? UsedAt { get; set; } public string? UsedByDeviceId { get; set; } public string? InstallationId { get; set; } // Bound to first installation instance // License Duration Configuration (P3) public int? LicenseDurationDays { get; set; } = 7; public string LicenseTier { get; set; } = "Trial"; // Batch Notes / Tag (Commercial Pilot) public string? Notes { get; set; } // Teacher Direct Assignment & Dual-Distribution (Turn 50) public string? TargetClassNameAtIssue { get; set; } // Historical snapshot of class name at issue time (e.g. "81班") public string? AssignedTeacherId { get; set; } // Direct assignment to Teacher User.Id public string? AssignedTeacherName { get; set; } // Teacher username or display name public string DistributionMethod { get; set; } = "External"; // "External" (微信/纸质) or "TeacherAccount" (账号直派) public DateTimeOffset? AssignedAt { get; set; } public string? AssignedByUserId { get; set; } public DateTimeOffset? SecretExposedAtUtc { get; set; } public string Status { get; set; } = "Issued"; // Draft, Issued, Redeemed, Expired, Revoked public DateTimeOffset? RevokedAtUtc { get; set; } public string? RevokedReason { get; set; } public string Purpose { get; set; } = "ProvisionAndLicense"; // ProvisionAndLicense, PersonalProvisionAndLicense, RenewLicenseOnly, Reprovision public bool IsSignupTrial { get; set; } = false; // Turn 62: Exactly one signup trial code per Personal Tenant public DateTimeOffset? RedeemBeforeUtc { get; set; } // Turn 62: Redemption deadline (30 days from issuance) public Tenant? Tenant { get; set; } } /// /// 激活码教师指派与流转历史记录 (Immutable Audit Trail) /// public class ActivationCodeAssignment { [Key] public string Id { get; set; } = string.Empty; // e.g. "asg_xxx" public string TenantId { get; set; } = string.Empty; public string ActivationCodeId { get; set; } = string.Empty; public string CodeMasked { get; set; } = string.Empty; public string TeacherUserId { get; set; } = string.Empty; public string TeacherName { get; set; } = string.Empty; public string AssignedByUserId { get; set; } = string.Empty; public DateTimeOffset AssignedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? UnassignedAtUtc { get; set; } public string? Reason { get; set; } } /// /// 设备授权与续费审计流水实体 (P3 License Lifecycle) /// public class DeviceLicenseRecord { [Key] public string Id { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; public string? InstallationId { get; set; } public string ClassroomId { get; set; } = string.Empty; public string Action { get; set; } = "ACTIVATE"; // ACTIVATE, RENEW, EXTEND, REVOKE public string LicenseTier { get; set; } = "Trial"; public int? GrantedDays { get; set; } public DateTimeOffset? PreviousLicensedUntil { get; set; } public DateTimeOffset? NewLicensedUntil { get; set; } public string? SourceActivationCode { get; set; } public string? OperatorUsername { get; set; } public string? Reason { get; set; } public string? ClientRequestId { get; set; } public bool IsTest { get; set; } = false; // Isolate synthetic test records from production KPIs public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; } /// /// 教师/系统下发通知主表 (不存储单一设备 ACK 状态) /// public class Notification { [Key] public string Id { get; set; } = string.Empty; // e.g. "msg_1789944446934_0471" public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string? SenderUserId { get; set; } public string SenderName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public string Title { get; set; } = "🔔 老师呼叫"; public string Priority { get; set; } = "Normal"; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? ExpiresAt { get; set; } public bool Voice { get; set; } = true; public bool Shake { get; set; } = true; public int DurationSeconds { get; set; } = 15; public bool IsCancelled { get; set; } = false; public DateTimeOffset? CancelledAt { get; set; } public string? CancelledBy { get; set; } public string? BroadcastId { get; set; } public string CorrelationId { get; set; } = string.Empty; public Tenant? Tenant { get; set; } public ICollection Receipts { get; set; } = new List(); } /// /// 设备通知回执明细表 (按设备独立记录状态与时间线,防止单点覆盖) /// public class NotificationReceipt { [Key] public string Id { get; set; } = string.Empty; // e.g. "rcpt_..." public string NotificationId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; /// /// 回执阶段状态: Sent, DeviceReceived, Displayed, Acknowledged, Failed, Timeout /// public string Status { get; set; } = "Sent"; public DateTimeOffset? DeviceReceivedAt { get; set; } public DateTimeOffset? DisplayedAt { get; set; } public DateTimeOffset? AcknowledgedAt { get; set; } public DateTimeOffset? FailedAt { get; set; } public string? FailureReason { get; set; } /// /// 视觉回执状态: None, Available, Expired /// public string VisualReceiptState { get; set; } = "None"; public string? VisualReceiptPath { get; set; } public DateTimeOffset? VisualReceiptCapturedAt { get; set; } public DateTimeOffset? VisualReceiptExpiresAt { get; set; } public long? VisualReceiptSizeBytes { get; set; } public string? VisualReceiptSha256 { get; set; } public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; public Notification? Notification { get; set; } public Device? Device { get; set; } } /// /// JSON 数据一次性迁移记录标记 /// public class MigrationMarker { [Key] public string Id { get; set; } = string.Empty; // e.g. "JsonMigration_v1" public DateTimeOffset MigratedAt { get; set; } = DateTimeOffset.UtcNow; public string? Details { get; set; } } /// /// 教室终端受控远程运维命令实体 /// 全链路统一 CommandId (cmd_xxxxx),从创建到最终上报不可篡改 /// public class DeviceCommand { [Key] public string Id { get; set; } = string.Empty; // e.g. "cmd_..." [Required] public string TenantId { get; set; } = string.Empty; [Required] public string DeviceId { get; set; } = string.Empty; [Required] public string CommandType { get; set; } = string.Empty; // "SelfCheck", "RestartClient", "Reconnect", "RefreshConfig" public string? Parameters { get; set; } [Required] public string CreatedBy { get; set; } = string.Empty; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset ExpiresAt { get; set; } public DateTimeOffset? StartedAt { get; set; } public DateTimeOffset? CompletedAt { get; set; } [Required] public string Status { get; set; } = "Pending"; // "Pending", "Dispatched", "Succeeded", "Failed", "TimedOut", "Expired" public int? ResultCode { get; set; } public long? DurationMs { get; set; } public string? ResultMessage { get; set; } public Tenant? Tenant { get; set; } public Device? Device { get; set; } } /// /// 全局唯一远程命令超期与超时状态终态化规则 /// 彻底消除各查询路径与后台 Worker 之间的状态竞态 /// public static class DeviceCommandNormalizer { public static bool NormalizeExpiredOrTimedOut(DeviceCommand cmd, DateTimeOffset now) { if (ClassNotify.Shared.Models.DeviceCommandStatuses.IsTerminal(cmd.Status)) { return false; } if (cmd.Status == ClassNotify.Shared.Models.DeviceCommandStatuses.Pending) { if (cmd.ExpiresAt <= now) { cmd.Status = ClassNotify.Shared.Models.DeviceCommandStatuses.Expired; cmd.CompletedAt = now; cmd.ResultCode = -2; cmd.ResultMessage = "Command pending expired before dispatch or device reconnect."; return true; } } else if (cmd.Status == ClassNotify.Shared.Models.DeviceCommandStatuses.Dispatched) { var dispatchedAt = cmd.StartedAt ?? cmd.CreatedAt; if (cmd.ExpiresAt <= now) { cmd.Status = ClassNotify.Shared.Models.DeviceCommandStatuses.TimedOut; cmd.CompletedAt = now; cmd.ResultCode = -4; cmd.ResultMessage = "Command expired after dispatch without device result."; return true; } else if (now - dispatchedAt >= TimeSpan.FromMinutes(2)) { cmd.Status = ClassNotify.Shared.Models.DeviceCommandStatuses.TimedOut; cmd.CompletedAt = now; cmd.ResultCode = -4; cmd.ResultMessage = "Command timed out (device did not report execution result within 2 minutes)."; return true; } } return false; } } /// /// 管理员操作审计事件实体 /// public class AdminAuditEvent { [Key] public string Id { get; set; } = string.Empty; public DateTimeOffset OccurredAt { get; set; } = DateTimeOffset.UtcNow; public string ActorUsername { get; set; } = string.Empty; public string ActorRole { get; set; } = string.Empty; public string Action { get; set; } = string.Empty; public string TargetType { get; set; } = string.Empty; public string TargetId { get; set; } = string.Empty; public string? Details { get; set; } public string? IpAddress { get; set; } } /// /// 终端批量自检批次实体 (P2.5 RC1-2) /// 严格不绑定单一 TenantId,支持 SuperAdmin 跨校集中运维 /// 状态统计由关联的 DeviceSelfCheckRun 动态聚合计算,防止字段状态漂移 /// public class DeviceSelfCheckBatch { [Key] public string Id { get; set; } = string.Empty; public string CorrelationId { get; set; } = string.Empty; public string ClientRequestId { get; set; } = string.Empty; public string CreatedByUserId { get; set; } = string.Empty; public DateTimeOffset CreatedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset DeadlineAtUtc { get; set; } public DateTimeOffset? CompletedAtUtc { get; set; } public int TargetDeviceCount { get; set; } public string Status { get; set; } = "Running"; public DateTimeOffset UpdatedAtUtc { get; set; } = DateTimeOffset.UtcNow; } /// /// 设备远程诊断/自检运行记录 /// public class DeviceSelfCheckRun { [Key] public string Id { get; set; } = string.Empty; // e.g. "sc_1790268406949_0471" public string? BatchId { get; set; } public string TenantId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; public string CorrelationId { get; set; } = string.Empty; public string Status { get; set; } = "Pending"; // Pending, Completed, Failed, Timeout (Legacy mirror) public string RunState { get; set; } = ClassNotify.Shared.Models.SelfCheckRunStates.PendingDispatch; // PendingDispatch, Dispatched, Completed, Unreachable, TimedOut public string? OverallStatus { get; set; } // Healthy, Warning, Failed public int DispatchAttemptCount { get; set; } public DateTimeOffset RequestedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? DispatchedAtUtc { get; set; } public DateTimeOffset DeadlineAtUtc { get; set; } public DateTimeOffset? CompletedAtUtc { get; set; } public string? ResultJson { get; set; } public string RequestedByUserId { get; set; } = string.Empty; public Tenant? Tenant { get; set; } public Device? Device { get; set; } public DeviceSelfCheckBatch? Batch { get; set; } } /// /// 设备技术诊断包实体 (P2.5 RC1-3 Support Bundle) /// public sealed class DeviceSupportBundle { [Key] public string Id { get; set; } = string.Empty; public string ClientRequestId { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; public string CorrelationId { get; set; } = string.Empty; public string RequestedByUserId { get; set; } = string.Empty; public string Status { get; set; } = ClassNotify.Shared.Models.SupportBundleStatuses.PendingDispatch; public DateTimeOffset CreatedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset UpdatedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset DeadlineAtUtc { get; set; } public DateTimeOffset? DispatchedAtUtc { get; set; } public DateTimeOffset? CompletedAtUtc { get; set; } public DateTimeOffset? ExpiresAtUtc { get; set; } public int DispatchAttemptCount { get; set; } public DateTimeOffset? LastDispatchAttemptAtUtc { get; set; } public DateTimeOffset? NextDispatchAttemptAtUtc { get; set; } public string? StoragePath { get; set; } public long? SizeBytes { get; set; } public string? Sha256 { get; set; } public string? ErrorCode { get; set; } public Tenant? Tenant { get; set; } public Device? Device { get; set; } } /// /// 客户端在线升级发布包实体 (P2.5 RC1-4) /// public sealed class UpdateRelease { public string Id { get; set; } = ""; public string Version { get; set; } = ""; public string Architecture { get; set; } = "win-x64"; public string PackageRelativePath { get; set; } = ""; public long PackageSizeBytes { get; set; } public string PackageSha256 { get; set; } = ""; public string ManifestSignature { get; set; } = ""; public DateTimeOffset CreatedAtUtc { get; set; } public bool IsEnabled { get; set; } } /// /// 设备升级任务执行记录实体 (P2.5 RC1-4) /// public sealed class DeviceUpdateRun { public string Id { get; set; } = ""; public string TenantId { get; set; } = ""; public string DeviceId { get; set; } = ""; public string ReleaseId { get; set; } = ""; public string CorrelationId { get; set; } = ""; public string RequestedByUserId { get; set; } = ""; public string? ClientRequestId { get; set; } public string FromVersion { get; set; } = ""; public string TargetVersion { get; set; } = ""; public string Status { get; set; } = ""; // UpdateStatuses public DateTimeOffset CreatedAtUtc { get; set; } public DateTimeOffset DeadlineAtUtc { get; set; } public DateTimeOffset? DispatchedAtUtc { get; set; } public DateTimeOffset? CompletedAtUtc { get; set; } public int DispatchAttemptCount { get; set; } public DateTimeOffset? LastDispatchAttemptAtUtc { get; set; } public DateTimeOffset? NextDispatchAttemptAtUtc { get; set; } public string? ErrorCode { get; set; } public string? ErrorMessage { get; set; } public string? BatchId { get; set; } public bool IsCanary { get; set; } public string DispatchGate { get; set; } = UpdateDispatchGates.Released; // Released, Held public Tenant? Tenant { get; set; } public Device? Device { get; set; } public UpdateRelease? Release { get; set; } public DeviceUpdateBatch? Batch { get; set; } } /// /// 小规模灰度升级批次实体 (P2.5 RC1-4 Phase 3) /// 严格限制 1~5 台设备,同一学校,单 Canary,人工确认门禁 /// public sealed class DeviceUpdateBatch { public string Id { get; set; } = ""; public string TenantId { get; set; } = ""; public string ReleaseId { get; set; } = ""; public string CanaryDeviceId { get; set; } = ""; public string RequestedByUserId { get; set; } = ""; public string? ClientRequestId { get; set; } public string Status { get; set; } = UpdateBatchStatuses.CanaryRunning; public int TargetDeviceCount { get; set; } public DateTimeOffset CreatedAtUtc { get; set; } public DateTimeOffset? CompletedAtUtc { get; set; } public DateTimeOffset? StoppedAtUtc { get; set; } public Tenant? Tenant { get; set; } public UpdateRelease? Release { get; set; } public List Runs { get; set; } = new(); } /// /// 设备首次试用防作弊台账 (Server-Authoritative Device Trial Eligibility) /// public sealed class DeviceTrialLedger { [Key] public string Id { get; set; } = ""; // e.g. "dtl_..." public string DeviceTrialKey { get; set; } = ""; // Server HMAC-SHA256 of hardware components public int FingerprintVersion { get; set; } = 1; public DateTimeOffset FirstTrialStartedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset TrialEndsAtUtc { get; set; } public string OriginalDeviceId { get; set; } = ""; public string OriginalTenantId { get; set; } = ""; public string? OriginalUserId { get; set; } public string Status { get; set; } = "Active"; // Active, Expired public string? SourceActivationCodeId { get; set; } // Reference to immutable ActivationCode.Id (never persist bearer code) public int BlockedAttemptCount { get; set; } = 0; public DateTimeOffset? LastBlockedAtUtc { get; set; } public string OverrideState { get; set; } = "None"; // None, Granted, Consumed, Revoked, Expired public int OverrideRemainingUses { get; set; } = 0; public DateTimeOffset? OverrideExpiresAtUtc { get; set; } public string? OverrideReason { get; set; } public string? OverriddenByUserId { get; set; } public string? OverrideGrantedByUserId { get; set; } public DateTimeOffset? OverrideGrantedAtUtc { get; set; } public DateTimeOffset? OverrideConsumedAtUtc { get; set; } public DateTimeOffset CreatedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? UpdatedAtUtc { get; set; } } /// /// 密码重置一次性凭证记录 (15分钟有效,单次使用) /// public sealed class PasswordResetToken { [Key] public string Id { get; set; } = ""; // e.g. "prt_..." public string UserId { get; set; } = ""; public string TokenHash { get; set; } = ""; public string TokenType { get; set; } = "EmailLink"; // EmailLink, AdminTicket public DateTimeOffset ExpiresAtUtc { get; set; } public bool IsUsed { get; set; } = false; public DateTimeOffset CreatedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? UsedAtUtc { get; set; } public string? IssuedByUserId { get; set; } } /// /// 教师个人历史回执免打扰/已移除记录 (Per-user Notification History Dismissal) /// 仅用于在当前教师历史列表中隐藏该通知,不删除底层 Notification、Receipt、VisualReceipt 与审计证据 /// public sealed class NotificationHistoryDismissal { [Key] public string Id { get; set; } = Guid.NewGuid().ToString("N"); public string TenantId { get; set; } = string.Empty; public string UserId { get; set; } = string.Empty; public string NotificationId { get; set; } = string.Empty; public DateTimeOffset DismissedAtUtc { get; set; } = DateTimeOffset.UtcNow; public Notification? Notification { get; set; } } /// /// 教师-大屏多对多解耦绑定关系实体 /// public sealed class TeacherDeviceBinding { [Key] public Guid Id { get; set; } = Guid.NewGuid(); public string TeacherId { get; set; } = string.Empty; public Guid DeviceId { get; set; } public string? ClassAlias { get; set; } public bool IsActive { get; set; } = true; public DateTimeOffset BoundAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? ReleasedAt { get; set; } } /// /// 商业化订单实体 (高熵订单号、服务端绝对定价与时长) /// public sealed class Order { [Key] public Guid Id { get; set; } = Guid.NewGuid(); public string TeacherId { get; set; } = string.Empty; [Required] [MaxLength(64)] public string OrderNo { get; set; } = string.Empty; public int AmountFen { get; set; } public int DurationDays { get; set; } = 365; [Required] [MaxLength(32)] public string Channel { get; set; } = "WeChatPay"; // "WeChatPay" | "Alipay" [Required] [MaxLength(32)] public string Status { get; set; } = "Pending"; // "Pending" | "Paid" | "Closed" | "Failed" public string? CodeUrl { get; set; } public string? PrepayId { get; set; } public string? FailureReason { get; set; } public DateTimeOffset CreatedAtUtc { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? PaidAtUtc { get; set; } public DateTimeOffset ExpiredAtUtc { get; set; } } /// /// 商业化卡密实体 (零明文,仅持久化 SHA-256 CodeHash) /// public sealed class SubscriptionVoucher { [Key] public Guid Id { get; set; } = Guid.NewGuid(); [Required] [MaxLength(64)] public string CodeHash { get; set; } = string.Empty; // SHA-256 public int DurationDays { get; set; } = 365; public bool IsUsed { get; set; } = false; public string? UsedByTeacherId { get; set; } public DateTimeOffset? UsedAt { get; set; } public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; } ================================================================================ FILE END: src/Server/ClassNotify.Server/Domain/Entities/Entities.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Hubs/DeviceHub.cs SHA256: e30dcb3ed857fb96898cd82e3e34fc9fcace683dfc96548c8c04c7400af4a2f5 SIZE: 16316 ================================================================================ using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Hubs; public class DeviceHub : Hub { private readonly ILogger _logger; private readonly IHubContext _teacherHub; private readonly ISecurityService _securityService; private readonly ISupportBundleDispatchNotifier? _bundleNotifier; // Track active connection -> { TenantId, ClassroomId, DeviceId } private static readonly Dictionary _connectionTenantMap = new(); public DeviceHub( ILogger logger, IHubContext teacherHub, ISecurityService securityService, ISupportBundleDispatchNotifier? bundleNotifier = null) { _logger = logger; _teacherHub = teacherHub; _securityService = securityService; _bundleNotifier = bundleNotifier; } public override async Task OnConnectedAsync() { var httpContext = Context.GetHttpContext(); var deviceId = httpContext?.Request.Headers["X-Device-Id"].FirstOrDefault() ?? httpContext?.Request.Query["device_id"].FirstOrDefault(); var deviceToken = httpContext?.Request.Headers["X-Device-Token"].FirstOrDefault() ?? httpContext?.Request.Query["device_token"].FirstOrDefault(); var clientVersion = httpContext?.Request.Headers["X-Client-Version"].FirstOrDefault() ?? "2.1.0"; var remoteIp = httpContext?.Connection.RemoteIpAddress?.ToString() ?? "127.0.0.1"; if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(deviceToken)) { _logger.LogWarning("Rejecting unauthorized device connection {ConnId}: Missing device credentials.", Context.ConnectionId); Context.Abort(); return; } var device = await _securityService.ValidateDeviceAsync(deviceId, deviceToken); if (device == null) { _logger.LogWarning("Rejecting unauthorized device connection {ConnId}: Invalid device ID or token ({DeviceId}).", Context.ConnectionId, deviceId); Context.Abort(); return; } // Add to Tenant-Isolated Groups var tenantClassGroup = $"t:{device.TenantId}:c:{device.ClassroomId}"; await Groups.AddToGroupAsync(Context.ConnectionId, tenantClassGroup); var tenantDeviceGroup = $"t:{device.TenantId}:d:{device.Id}"; await Groups.AddToGroupAsync(Context.ConnectionId, tenantDeviceGroup); await Groups.AddToGroupAsync(Context.ConnectionId, $"dev_{device.Id}"); lock (_connectionTenantMap) { _connectionTenantMap[Context.ConnectionId] = (device.TenantId, device.ClassroomId, device.Id); } // Register in SecurityService Live Registry (with physical endpoint identity) var regResult = await _securityService.RegisterDeviceConnectionAsync( Context.ConnectionId, device.Id, device.TenantId, device.ClassroomId, device.Hostname, remoteIp, clientVersion, device.InstallationId, device.HardwareComponentsHash); if (!string.IsNullOrEmpty(regResult.ReplacedConnectionId) && regResult.ReplacedConnectionId != Context.ConnectionId) { await Groups.RemoveFromGroupAsync(regResult.ReplacedConnectionId, tenantClassGroup); await Groups.RemoveFromGroupAsync(regResult.ReplacedConnectionId, tenantDeviceGroup); _logger.LogInformation("Removed replaced connection {OldConnId} from class group {Group} and device group {DevGroup}; current connection is {NewConnId}", regResult.ReplacedConnectionId, tenantClassGroup, tenantDeviceGroup, Context.ConnectionId); } _logger.LogInformation("Device {DeviceId} authenticated successfully. Joined groups {ClassGroup} and {DevGroup} at {ConnId}", device.Id, tenantClassGroup, tenantDeviceGroup, Context.ConnectionId); // Notify teachers of THIS tenant var classroom = await _securityService.GetClassroomAsync(device.TenantId, device.ClassroomId); var status = new DeviceStatusDto { DeviceId = device.Id, ClassId = device.ClassroomId, ClassName = classroom?.DisplayName ?? device.ClassroomId, Hostname = device.Hostname ?? "Classroom-PC", State = DeviceOnlineState.Online, LastHeartbeat = DateTimeOffset.UtcNow, AgentVersion = clientVersion }; await _teacherHub.Clients.Group($"t:{device.TenantId}:teachers").OnDeviceStatusChanged(status); await base.OnConnectedAsync(); // P3 License Lifecycle: Push authoritative license status to connecting device DeviceLicenseStatusDto? licStatus = null; try { licStatus = await _securityService.GetDeviceLicenseStatusAsync(device.Id); await Clients.Caller.ReceiveLicenseStatus(licStatus); _logger.LogInformation("Pushed LicenseStatus {Status} (Tier={Tier}, RemainingDays={Days}) to Device {DeviceId}", licStatus.Status, licStatus.Tier, licStatus.RemainingDays, device.Id); } catch (Exception ex) { _logger.LogError(ex, "Error pushing license status to connecting Device {DeviceId}", device.Id); } // P1 Batch 9: Catch-up pending notifications for this reconnected device (Caller unicast only) try { var pendingNotifications = await _securityService.GetPendingNotificationsForDeviceAsync(device.Id); if (pendingNotifications.Count > 0) { _logger.LogInformation("Device {DeviceId} connected with {Count} pending notification(s) to catch up.", device.Id, pendingNotifications.Count); foreach (var pending in pendingNotifications) { // If device license is expired, only dispatch Emergency/Urgent notifications! if (licStatus != null && licStatus.Status == "Expired" && pending.Type != NotificationType.Urgent) { continue; } await Clients.Caller.ReceiveNotification(pending); } } } catch (Exception ex) { _logger.LogError(ex, "Error catching up pending notifications for Device {DeviceId}", device.Id); } // P1 Batch 10: Catch-up pending commands for this reconnected device (Caller unicast only) try { var pendingCommands = await _securityService.GetPendingCommandsForDeviceAsync(device.Id); if (pendingCommands.Count > 0) { _logger.LogInformation("Device {DeviceId} connected with {Count} pending command(s) to catch up.", device.Id, pendingCommands.Count); foreach (var pendingCmd in pendingCommands) { await Clients.Caller.ReceiveRemoteCommand(pendingCmd); await _securityService.MarkCommandDispatchedAsync(pendingCmd.CommandId); } } } catch (Exception ex) { _logger.LogError(ex, "Error catching up pending commands for Device {DeviceId}", device.Id); } // Wake up support bundle dispatch worker if any pending requests exist _bundleNotifier?.Notify(); } public async Task SendAckReceipt(AckReceiptDto ack) { string? tenantId = null; string? classroomId = null; string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { tenantId = info.TenantId; classroomId = info.ClassroomId; deviceId = info.DeviceId; } } if (tenantId == null || classroomId == null || deviceId == null) { _logger.LogWarning("Rejecting ACK from unauthenticated connection {ConnId}", Context.ConnectionId); return; } // Must be current connection for this device (Blocker 1: Fail-closed termination) if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked ACK from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } // P0-11: Enforce device ACK attribution validation. // Force ClassId to match the connection's authenticated classroom (never trust client-supplied ClassId). ack.ClassId = classroomId; // Verify that this notification was actually sent to this tenant and classroom if (!await _securityService.ValidateNotificationTargetAsync(ack.MessageId, tenantId, classroomId)) { _logger.LogWarning("Spoofed or unknown ACK rejected: Message {MsgId} does not match Tenant {TenantId}, Class {ClassId} (Device {DeviceId})", ack.MessageId, tenantId, classroomId, deviceId); return; } _logger.LogInformation("ACK validated from Tenant {TenantId}, Class {ClassId} (Device {DeviceId}): Message {MsgId} -> {Status}", tenantId, classroomId, deviceId, ack.MessageId, ack.Status); // Record ACK in history (NotificationReceipt per device) await _securityService.RecordAckAsync(ack.MessageId, deviceId, ack); // Relay ONLY to teachers belonging to THIS tenant! await _teacherHub.Clients.Group($"t:{tenantId}:teachers").OnAckReceiptReceived(ack); } public async Task ReportCommandResult(DeviceCommandResultDto result) { string? tenantId = null; string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { tenantId = info.TenantId; deviceId = info.DeviceId; } } if (tenantId == null || deviceId == null) { _logger.LogWarning("Rejecting command result from unauthenticated connection {ConnId}", Context.ConnectionId); return; } if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked command result from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } // Security enforcement: force DeviceId from authenticated connection! result.DeviceId = deviceId; var recorded = await _securityService.RecordCommandResultAsync(result, deviceId, tenantId); if (recorded != null) { // Relay to teachers and administrators of THIS tenant! await _teacherHub.Clients.Group($"t:{tenantId}:teachers").OnDeviceCommandStatusChanged(recorded); } } public async Task SendHealthReport(DeviceHealthReportDto report) { string? tenantId = null; string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { tenantId = info.TenantId; deviceId = info.DeviceId; } } if (tenantId == null || deviceId == null) return; if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked health report from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } // Security requirement: Force DeviceId from authenticated connection! report.DeviceId = deviceId; await _teacherHub.Clients.Group($"t:{tenantId}:teachers").OnHealthReportReceived(report); } public async Task SendHeartbeat(string classId) { string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { deviceId = info.DeviceId; } } if (deviceId == null) { _logger.LogWarning("Rejecting heartbeat from unauthenticated connection {ConnId}", Context.ConnectionId); Context.Abort(); return; } if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked heartbeat from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } await _securityService.UpdateDeviceHeartbeatAsync(Context.ConnectionId); _logger.LogDebug("Received heartbeat from Device {DeviceId} ({ConnId})", deviceId, Context.ConnectionId); } public async Task SendHeartbeatWithReport(DeviceHeartbeatDto heartbeat) { string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { deviceId = info.DeviceId; } } if (deviceId == null) { _logger.LogWarning("Rejecting heartbeat report from unauthenticated connection {ConnId}", Context.ConnectionId); Context.Abort(); return; } if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked heartbeat report from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } await _securityService.UpdateDeviceHeartbeatAsync(Context.ConnectionId, heartbeat); _logger.LogDebug("Received structured heartbeat report from Device {DeviceId} ({ConnId}): Svc={ServiceVersion}, Client={ClientVersion}, Corr={CorrId}", deviceId, Context.ConnectionId, heartbeat.ServiceVersion, heartbeat.ClientVersion, heartbeat.CorrelationId); } public override async Task OnDisconnectedAsync(Exception? exception) { string? tenantId = null; string? classId = null; string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { tenantId = info.TenantId; classId = info.ClassroomId; deviceId = info.DeviceId; _connectionTenantMap.Remove(Context.ConnectionId); } } var isCurrentDisconnected = await _securityService.UnregisterDeviceConnectionAsync(Context.ConnectionId); if (tenantId != null && classId != null && deviceId != null) { if (isCurrentDisconnected) { _logger.LogInformation("Device {DeviceId} disconnected for Tenant {TenantId}, Class {ClassId}", deviceId, tenantId, classId); var status = new DeviceStatusDto { DeviceId = deviceId, ClassId = classId, State = DeviceOnlineState.Offline, LastHeartbeat = DateTimeOffset.UtcNow }; await _teacherHub.Clients.Group($"t:{tenantId}:teachers").OnDeviceStatusChanged(status); } else { _logger.LogInformation("Stale connection {ConnId} disconnected for Device {DeviceId} (Tenant {TenantId}, Class {ClassId}); device is still active on newer connection. Skipping Offline status broadcast.", Context.ConnectionId, deviceId, tenantId, classId); } } await base.OnDisconnectedAsync(exception); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Hubs/DeviceHub.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Hubs/TeacherHub.cs SHA256: f45e2f8c1f620b9fef0487e3cbbe7fae7569d4c9f99ebf23ef95d61b587a4ac7 SIZE: 1368 ================================================================================ using System.Security.Claims; using ClassNotify.Shared.Contracts; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Hubs; /// /// 教师端 SignalR Hub (强制 JWT 认证,基于 TenantId 强隔离事件流) /// [Authorize] public class TeacherHub : Hub { private readonly ILogger _logger; public TeacherHub(ILogger logger) { _logger = logger; } public override async Task OnConnectedAsync() { var tenantId = Context.User?.FindFirst("tenant_id")?.Value; var teacherName = Context.User?.FindFirst(ClaimTypes.Name)?.Value ?? "教师"; if (string.IsNullOrEmpty(tenantId)) { _logger.LogWarning("Rejecting teacher connection {ConnId}: Missing tenant_id claim.", Context.ConnectionId); Context.Abort(); return; } // Join tenant-specific teacher event channel var tenantTeacherGroup = $"t:{tenantId}:teachers"; await Groups.AddToGroupAsync(Context.ConnectionId, tenantTeacherGroup); _logger.LogInformation("Teacher {TeacherName} connected to SignalR Hub. Joined group {Group} at {ConnId}", teacherName, tenantTeacherGroup, Context.ConnectionId); await base.OnConnectedAsync(); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Hubs/TeacherHub.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Infrastructure/Correlation/CorrelationContext.cs SHA256: 6200dae7c32a0b12b38df15481bafd5cb25ea35fb29ec1fe13fe6f10d47d90e1 SIZE: 270 ================================================================================ namespace ClassNotify.Server.Infrastructure.Correlation; public interface ICorrelationContext { string CorrelationId { get; } } public sealed class CorrelationContext : ICorrelationContext { public string CorrelationId { get; internal set; } = string.Empty; } ================================================================================ FILE END: src/Server/ClassNotify.Server/Infrastructure/Correlation/CorrelationContext.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Infrastructure/Correlation/CorrelationMiddleware.cs SHA256: 9f71abde38a58aa8be5dbb696c34413e8b89cc06c4feb70f4cdeba3ff1f09438 SIZE: 1546 ================================================================================ using System.Diagnostics; namespace ClassNotify.Server.Infrastructure.Correlation; public sealed class CorrelationMiddleware { public const string HeaderName = "X-Correlation-Id"; private readonly RequestDelegate _next; private readonly ILogger _logger; public CorrelationMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context, CorrelationContext correlation) { var incoming = context.Request.Headers[HeaderName].FirstOrDefault(); var correlationId = IsValid(incoming) ? incoming!.ToLowerInvariant() : ActivityTraceId.CreateRandom().ToHexString(); correlation.CorrelationId = correlationId; context.Response.Headers[HeaderName] = correlationId; var traceId = Activity.Current?.TraceId.ToHexString() ?? string.Empty; using (_logger.BeginScope(new Dictionary { ["CorrelationId"] = correlationId, ["TraceId"] = traceId, ["HttpRequestId"] = context.TraceIdentifier })) { await _next(context); } } private static bool IsValid(string? value) { if (string.IsNullOrWhiteSpace(value) || value.Length != 32) return false; foreach (var c in value) { if (!Uri.IsHexDigit(c)) return false; } return true; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Infrastructure/Correlation/CorrelationMiddleware.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Infrastructure/Logging/LoggingExtensions.cs SHA256: 5908d9650455535b93bdbf430bd195d50d42050c8fc8d877ccd376fd82f550d1 SIZE: 722 ================================================================================ namespace ClassNotify.Server.Infrastructure.Logging; public static class LoggingExtensions { public static IDisposable? BeginClassNotifyScope( this ILogger logger, string correlationId, string? tenantId = null, string? classroomId = null, string? deviceId = null, string? notificationId = null, string? stage = null) { return logger.BeginScope(new Dictionary { ["CorrelationId"] = correlationId, ["TenantId"] = tenantId, ["ClassroomId"] = classroomId, ["DeviceId"] = deviceId, ["NotificationId"] = notificationId, ["Stage"] = stage }); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Infrastructure/Logging/LoggingExtensions.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Program.cs SHA256: 5e5a46d9d50727642bbb6d1aa58b9b7e01d2d77133b7f3b51625f2cf2a81cede SIZE: 18855 ================================================================================ using System.Net; using System.Security.Claims; using System.Text; using System.Threading.RateLimiting; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Server.Infrastructure.Correlation; using ClassNotify.Server.Infrastructure.Logging; using ClassNotify.Server.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Microsoft.Extensions.Options; using Serilog; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .CreateLogger(); try { var builder = WebApplication.CreateBuilder(args); builder.Host.UseSerilog(); builder.Services.AddControllers(); builder.Services.AddSignalR(); // 1. PostgreSQL EF Core DbContext var defaultConn = builder.Configuration.GetConnectionString("DefaultConnection") ?? Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection") ?? "Host=127.0.0.1;Port=5432;Database=classnotify;Username=classnotify;Password=CHANGEME_DEV;"; builder.Services.AddDbContext(options => { options.UseNpgsql(defaultConn); }); // 2. Data Protection for Encrypted Recoverable Device Tokens var keysPath = OperatingSystem.IsLinux() ? "/var/lib/classnotify/keys" : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "keys"); if (!Directory.Exists(keysPath)) { Directory.CreateDirectory(keysPath); } builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(keysPath)) .SetApplicationName("ClassNotify"); // 3. ASP.NET Core PasswordHasher builder.Services.AddSingleton, PasswordHasher>(); // 4. JWT Options Binding & Strict Production Guard builder.Services.Configure(builder.Configuration.GetSection("Jwt")); var jwtOptions = builder.Configuration.GetSection("Jwt").Get() ?? new JwtOptions(); if (builder.Environment.IsProduction()) { if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || Encoding.UTF8.GetByteCount(jwtOptions.SigningKey) < 64) { throw new InvalidOperationException("Production Guard: Jwt__SigningKey is missing or has insufficient length (minimum 64 bytes required in Production). Refusing to start."); } if (string.IsNullOrWhiteSpace(jwtOptions.Issuer)) { throw new InvalidOperationException("Production Guard: Jwt__Issuer is missing. Refusing to start."); } if (string.IsNullOrWhiteSpace(jwtOptions.Audience)) { throw new InvalidOperationException("Production Guard: Jwt__Audience is missing. Refusing to start."); } // 4.1 Device Trial Security Guard: Cryptographically random server-only secret (>= 32 bytes / 256 bits) var trialKeyRaw = builder.Configuration["Security:DeviceTrialHmacKey"] ?? builder.Configuration["Security__DeviceTrialHmacKey"] ?? Environment.GetEnvironmentVariable("CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY") ?? builder.Configuration["CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY"]; if (string.IsNullOrWhiteSpace(trialKeyRaw)) { throw new InvalidOperationException("Production Guard: Security__DeviceTrialHmacKey (or CLASSNOTIFY_DEVICE_TRIAL_HMAC_KEY) is missing. Refusing to start (Fail-Closed)."); } ClassNotify.Server.Services.SecurityService.GetDeviceTrialHmacKeyBytes(trialKeyRaw, isDevelopment: false); } else { // Non-production fallback for design-time / local dev if unconfigured if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || Encoding.UTF8.GetByteCount(jwtOptions.SigningKey) < 32) { jwtOptions.SigningKey = "DEV_ONLY_INSECURE_SIGNING_KEY_FOR_LOCAL_TESTING_PURPOSES_ONLY_MIN_64_BYTES_LONG_!"; } if (string.IsNullOrWhiteSpace(jwtOptions.Issuer)) jwtOptions.Issuer = "ClassNotify.Server"; if (string.IsNullOrWhiteSpace(jwtOptions.Audience)) jwtOptions.Audience = "ClassNotify.Clients"; } builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddScoped(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.Configure(builder.Configuration.GetSection("DeviceVersionPolicy")); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); // P2.5 RC1-3 Support Bundle Services builder.Services.Configure(builder.Configuration.GetSection("SupportBundles")); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); // P2.5 RC1-4 Online Update Services builder.Services.Configure(builder.Configuration.GetSection("UpdateStorage")); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHostedService(); // Commercial Services (P3 Monetization & Multi-Screen Pairing) builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); // 5. JWT Authentication with Strict Validation builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { // Support SignalR query string token for WebSocket connections options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/teacher") || path.StartsWithSegments("/hubs/device"))) { context.Token = accessToken; } return Task.CompletedTask; }, OnTokenValidated = async context => { var userId = context.Principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value; var tenantId = context.Principal?.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(userId)) { context.Fail("Invalid token claims: missing NameIdentifier."); return; } var dbContext = context.HttpContext.RequestServices.GetRequiredService(); var user = await dbContext.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == userId); if (user == null || user.IsLocked) { context.Fail("User account has been locked or deactivated."); return; } var tokenVersionClaim = context.Principal?.FindFirst("token_version")?.Value; if (string.IsNullOrWhiteSpace(tokenVersionClaim) || !int.TryParse(tokenVersionClaim, out var tokenVersion)) { context.Fail("Invalid token claims: missing or invalid token_version (fail-closed against legacy tokens)."); return; } if (user.TokenVersion != tokenVersion) { context.Fail("Token has been revoked due to security event or password reset."); return; } if (!string.IsNullOrEmpty(tenantId) && tenantId != "global") { var tenant = await dbContext.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId); if (tenant == null || !tenant.IsActive) { context.Fail("Tenant is inactive or suspended."); return; } } } }; }); builder.Services.AddOptions(JwtBearerDefaults.AuthenticationScheme) .Configure>((options, jwtOptAccessor) => { var currentJwt = jwtOptAccessor.Value; var keyStr = currentJwt.SigningKey; if (string.IsNullOrWhiteSpace(keyStr) || Encoding.UTF8.GetByteCount(keyStr) < 32) { keyStr = "DEV_ONLY_INSECURE_SIGNING_KEY_FOR_LOCAL_TESTING_PURPOSES_ONLY_MIN_64_BYTES_LONG_!"; } var iss = !string.IsNullOrWhiteSpace(currentJwt.Issuer) ? currentJwt.Issuer : "ClassNotify.Server"; var aud = !string.IsNullOrWhiteSpace(currentJwt.Audience) ? currentJwt.Audience : "ClassNotify.Clients"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = iss, ValidAudience = aud, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyStr)), ClockSkew = TimeSpan.FromMinutes(1) }; }); builder.Services.AddAuthorization(); // 6. Partitioned Rate Limiting (按来源分区,避免全局限流瓶颈) builder.Services.Configure(builder.Configuration.GetSection("RateLimit")); builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; // AuthLimiter: requests / minute / IP options.AddPolicy("AuthLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var remoteIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"; return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.AuthPermitLimit > 0 ? rateOpts.AuthPermitLimit : 60, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); // ActivationLimiter: requests / minute / IP options.AddPolicy("ActivationLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var remoteIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"; return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.ActivationPermitLimit > 0 ? rateOpts.ActivationPermitLimit : 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); // SendLimiter: notifications / minute / user (fallback to IP) options.AddPolicy("SendLimiter", httpContext => { var rateOpts = httpContext.RequestServices.GetRequiredService>().Value; var userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var partitionKey = !string.IsNullOrEmpty(userId) ? $"user_{userId}" : $"ip_{httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown_ip"}"; return RateLimitPartition.GetFixedWindowLimiter(partitionKey, _ => new FixedWindowRateLimiterOptions { PermitLimit = rateOpts.SendPermitLimit > 0 ? rateOpts.SendPermitLimit : 120, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }); }); }); // 7. CORS Hardening (Production strictly allows official domain only) builder.Services.AddCors(options => { options.AddPolicy("CorsPolicy", policy => { if (builder.Environment.IsDevelopment()) { policy.WithOrigins("http://localhost:5173", "http://127.0.0.1:5173") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); } else { policy.WithOrigins("https://classnotify.paradise.eu.org") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); } }); }); // 6. Forwarded Headers for Linux reverse proxy (Caddy / Nginx) // Only trust loopback reverse proxy (Caddy on same host) with ForwardLimit = 1 builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); options.KnownProxies.Add(IPAddress.Loopback); options.KnownProxies.Add(IPAddress.IPv6Loopback); options.ForwardLimit = 1; }); var app = builder.Build(); app.UseForwardedHeaders(); app.UseMiddleware(); // Database Initialization & One-Time JSON Migration using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); try { if (db.Database.IsRelational()) { await db.Database.MigrateAsync(); } await DbInitializer.InitializeAsync(db, app.Environment, app.Configuration, app.Logger); await JsonMigrationService.MigrateAsync(db, null, app.Logger); } catch (Exception ex) { app.Logger.LogError(ex, "Error during database initialization or JSON migration."); throw; } } // Serve React SPA static files from wwwroot app.UseDefaultFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthentication(); app.UseAuthorization(); // Turn 75 Frozen Requirement: Temporary password sessions cannot access normal business APIs app.Use(async (context, next) => { var user = context.User; if (user?.Identity?.IsAuthenticated == true) { var mustChange = user.FindFirst("must_change_password")?.Value; var path = context.Request.Path.Value ?? ""; if (string.Equals(mustChange, "true", StringComparison.OrdinalIgnoreCase)) { if (!path.StartsWith("/api/auth/change-password", StringComparison.OrdinalIgnoreCase) && !path.StartsWith("/api/auth/logout", StringComparison.OrdinalIgnoreCase) && !path.StartsWith("/api/auth/me", StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = StatusCodes.Status403Forbidden; context.Response.ContentType = "application/json"; await context.Response.WriteAsync("{\"success\":false,\"passwordChangeRequired\":true,\"message\":\"管理员已为您重置临时密码,在完成设置新密码前禁止访问系统业务接口\"}"); return; } } } await next(); }); app.UseRateLimiter(); app.MapControllers(); app.MapHub("/hubs/device"); app.MapHub("/hubs/teacher"); // Dedicated Real PostgreSQL Health Check Endpoint app.MapGet("/api/health", async (ClassNotifyDbContext dbContext) => { bool dbOk = false; string? dbError = null; try { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); dbOk = await dbContext.Database.CanConnectAsync(cts.Token); if (dbOk) { await dbContext.Database.ExecuteSqlRawAsync("SELECT 1", cts.Token); } } catch (Exception ex) { dbError = ex.Message; } var status = dbOk ? "Healthy" : "Degraded"; var result = new { service = "ClassNotify Commercial Server (ASP.NET Core on Linux)", version = "2.1.0", status = status, database = dbOk ? "Connected" : "Disconnected", databaseError = dbError, hubs = new[] { "/hubs/device", "/hubs/teacher" } }; return dbOk ? Results.Ok(result) : Results.Json(result, statusCode: 503); }); // Fallback to index.html for React SPA client-side routing app.MapFallbackToFile("index.html"); app.Run(); } catch (Exception ex) { Log.Fatal(ex, "ClassNotify Server terminated unexpectedly."); } finally { Log.CloseAndFlush(); } namespace ClassNotify.Server { public partial class Program { } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Program.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/DeviceCommandTimeoutWorker.cs SHA256: 7b98fb1cb55a595434ba263d5f231ef9756259456771fb3a18f1db0bc35180ed SIZE: 4763 ================================================================================ using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ClassNotify.Server.Services; /// /// 后台受控远程命令超时与生命周期流转服务 /// 严格兑现封板要求: /// 1. Pending 超时 -> 自动标记 Expired 并推 TeacherHub /// 2. Dispatched 超过 TTL 或持续无心跳响应 -> 自动标记 TimedOut 并推 TeacherHub /// 3. 定期持久化状态至 PostgreSQL 实体 /// public class DeviceCommandTimeoutWorker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly IHubContext _teacherHub; private readonly ILogger _logger; private readonly TimeSpan _checkInterval; public DeviceCommandTimeoutWorker( IServiceScopeFactory scopeFactory, IHubContext teacherHub, ILogger logger, TimeSpan? checkInterval = null) { _scopeFactory = scopeFactory; _teacherHub = teacherHub; _logger = logger; _checkInterval = checkInterval ?? TimeSpan.FromSeconds(10); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("DeviceCommandTimeoutWorker started (CheckInterval: {Interval}s)", _checkInterval.TotalSeconds); while (!stoppingToken.IsCancellationRequested) { try { await ProcessTimeoutsAsync(stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Error processing device command timeouts and expirations"); } try { await Task.Delay(_checkInterval, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } } _logger.LogInformation("DeviceCommandTimeoutWorker stopped."); } public async Task ProcessTimeoutsAsync(CancellationToken cancellationToken = default) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; // Fetch all active non-terminal commands var activeCommands = await db.DeviceCommands .Where(c => c.Status == DeviceCommandStatuses.Pending || c.Status == DeviceCommandStatuses.Dispatched) .ToListAsync(cancellationToken); if (activeCommands.Count == 0) return 0; var transitioned = new List(); foreach (var cmd in activeCommands) { if (Domain.Entities.DeviceCommandNormalizer.NormalizeExpiredOrTimedOut(cmd, now)) { transitioned.Add(cmd); _logger.LogWarning("Command {CommandId} (Device {DeviceId}, Tenant {TenantId}) transitioned to terminal status '{Status}': {Reason}", cmd.Id, cmd.DeviceId, cmd.TenantId, cmd.Status, cmd.ResultMessage); } } if (transitioned.Count == 0) return 0; // 1. SAVE TO DATABASE FIRST - Fail-safe against broadcasting ghost states await db.SaveChangesAsync(cancellationToken); // 2. BROADCAST TO TEACHERHUB ONLY AFTER DB PERSISTENCE SUCCEEDS foreach (var cmd in transitioned) { var resultDto = new DeviceCommandResultDto { CommandId = cmd.Id, DeviceId = cmd.DeviceId, Status = cmd.Status, ResultCode = cmd.ResultCode ?? (cmd.Status == DeviceCommandStatuses.Expired ? -2 : -4), ResultMessage = cmd.ResultMessage, ExecutionDurationMs = cmd.DurationMs ?? 0, Timestamp = now }; try { await _teacherHub.Clients.Group($"t:{cmd.TenantId}:teachers").OnDeviceCommandStatusChanged(resultDto); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to broadcast command status change for {CommandId} to TeacherHub", cmd.Id); } } return transitioned.Count; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/DeviceCommandTimeoutWorker.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/DeviceNotificationService.cs SHA256: d8d99c6c6e10faf96d66d5f07c040c41a33d7533a5fca3bd4397749c42e8d7bc SIZE: 1878 ================================================================================ using ClassNotify.Server.Hubs; using ClassNotify.Shared.Contracts; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Services; public interface IDeviceNotificationService { Task NotifyScreenEnterPairingModeAsync(Guid deviceId, string pairingCode, int ttlSeconds); Task NotifyScreenClaimedAsync(Guid deviceId, string classDisplayName, int teacherCount); } public class DeviceNotificationService : IDeviceNotificationService { private readonly IHubContext _deviceHub; private readonly ILogger _logger; public DeviceNotificationService(IHubContext deviceHub, ILogger logger) { _deviceHub = deviceHub; _logger = logger; } public async Task NotifyScreenEnterPairingModeAsync(Guid deviceId, string pairingCode, int ttlSeconds) { _logger.LogInformation("Notifying device {DeviceId} to enter pairing mode (Code: {Code}, TTL: {Ttl}s)", deviceId, pairingCode, ttlSeconds); // Device group convention in DeviceHub: "d:{deviceId}" await _deviceHub.Clients.Group($"d:{deviceId}").ReceivePairingMode(pairingCode, ttlSeconds); // Also broadcast by device string ID await _deviceHub.Clients.Group(deviceId.ToString()).ReceivePairingMode(pairingCode, ttlSeconds); } public async Task NotifyScreenClaimedAsync(Guid deviceId, string classDisplayName, int teacherCount) { _logger.LogInformation("Notifying device {DeviceId} binding updated: class={Class}, teachers={Teachers}", deviceId, classDisplayName, teacherCount); await _deviceHub.Clients.Group($"d:{deviceId}").DeviceBindingUpdated(classDisplayName, teacherCount); await _deviceHub.Clients.Group(deviceId.ToString()).DeviceBindingUpdated(classDisplayName, teacherCount); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/DeviceNotificationService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/DevicePresenceService.cs SHA256: 2bb42b5d74519841e297b34fef671105ca7476002dcbc0d2bde62a5ae3756ea4 SIZE: 1060 ================================================================================ namespace ClassNotify.Server.Services; public interface IDevicePresenceService { bool IsOnline(string deviceId, DateTimeOffset? lastHeartbeatAt); } public sealed class DevicePresenceService : IDevicePresenceService { private readonly ISecurityService _securityService; public DevicePresenceService(ISecurityService securityService) { _securityService = securityService; } public bool IsOnline(string deviceId, DateTimeOffset? lastHeartbeatAt) { if (string.IsNullOrWhiteSpace(deviceId)) { return false; } // 1. Primary source of truth: Active SignalR device connection var connId = _securityService.GetDeviceConnectionId(deviceId); if (!string.IsNullOrEmpty(connId)) { return true; } // 2. Secondary heartbeat threshold check (within 60s) if (lastHeartbeatAt.HasValue && (DateTimeOffset.UtcNow - lastHeartbeatAt.Value).TotalSeconds <= 60) { return true; } return false; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/DevicePresenceService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/DeviceUpdateBatchService.cs SHA256: fbf20d60d7281150d384642cd590ee304b880c5f2c6aabc44fe7c69f123c9624 SIZE: 21824 ================================================================================ using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace ClassNotify.Server.Services; /// /// 小规模灰度升级管控服务实现 (P2.5 RC1-4 Phase 3) /// 严格限定 1~5 台同一学校设备,物理隔离未放行设备 (Held),单 Canary,人工放行门禁 /// 严禁将聚合汇总计数持久化到批次表,所有统计严格基于 DeviceUpdateRun 动态计算 /// public sealed class DeviceUpdateBatchService : IDeviceUpdateBatchService { private readonly ClassNotifyDbContext _db; private readonly IDeviceUpdateDispatchNotifier _dispatchNotifier; private readonly ILogger _logger; public DeviceUpdateBatchService( ClassNotifyDbContext db, IDeviceUpdateDispatchNotifier dispatchNotifier, ILogger logger) { _db = db; _dispatchNotifier = dispatchNotifier; _logger = logger; } public async Task CreateBatchAsync( CreateUpdateBatchRequest request, string actorUser, string actorRole, string? actorTenantId, string clientIp, CancellationToken ct) { // 1. RBAC: 仅限系统超级管理员 (SuperAdmin) 允许发起灰度批次 (U21) if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Unauthorized attempt to create update batch by user {User} with role {Role}. 403 Forbidden.", actorUser, actorRole); return DeviceUpdateBatchCreationResult.Forbidden("仅系统管理员 (SuperAdmin) 允许发起小规模灰度升级。"); } // 2. 严格批次规模边界 (U22): 限制 1 至 5 台设备 if (request.DeviceIds == null || request.DeviceIds.Count < 1 || request.DeviceIds.Count > 5) { _logger.LogWarning("Invalid batch size {Count}. Expected 1 to 5 devices.", request.DeviceIds?.Count ?? 0); return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "灰度升级批次设备数量必须在 1 至 5 台之间。"); } // 3. 校验设备列表无重复 if (request.DeviceIds.Distinct(StringComparer.OrdinalIgnoreCase).Count() != request.DeviceIds.Count) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "批次设备列表中包含重复的设备标识。"); } // 4. 必须明确指定恰好 1 台 Canary 设备且必须包含在设备列表中 if (string.IsNullOrWhiteSpace(request.CanaryDeviceId) || !request.DeviceIds.Contains(request.CanaryDeviceId, StringComparer.OrdinalIgnoreCase)) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "必须在批次设备列表中明确指定一台首发金丝雀 (Canary) 验证设备。"); } if (string.IsNullOrWhiteSpace(request.TenantId)) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "必须指定批次目标租户学校 (TenantId)。"); } // 5. 校验目标 Release 是否存在且启用 var release = await _db.UpdateReleases.AsNoTracking().FirstOrDefaultAsync(r => r.Id == request.ReleaseId, ct); if (release == null) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.ReleaseNotFound, $"指定升级版本 '{request.ReleaseId}' 不存在。"); } if (!release.IsEnabled) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.ReleaseDisabled, $"指定升级版本 '{request.ReleaseId}' 已停用。"); } // 6. 校验设备真实存在且严格属于同一租户 (U22: 禁止跨租户) var devices = await _db.Devices .Include(d => d.Classroom) .Where(d => request.DeviceIds.Contains(d.Id)) .ToListAsync(ct); if (devices.Count != request.DeviceIds.Count) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "所选设备列表中存在无效或不存在的设备。"); } if (devices.Any(d => !string.Equals(d.TenantId, request.TenantId, StringComparison.OrdinalIgnoreCase))) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "灰度升级批次内所有设备必须严格同属于指定租户学校,严禁跨租户混合升级。"); } // 7. 幂等性校验 (U23): ClientRequestId 防重 if (!string.IsNullOrWhiteSpace(request.ClientRequestId)) { var existingBatch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .FirstOrDefaultAsync(b => b.RequestedByUserId == actorUser && b.ClientRequestId == request.ClientRequestId, ct); if (existingBatch != null) { _logger.LogInformation("Idempotent hit for batch {BatchId} by user {User} (ClientRequestId={RequestId})", existingBatch.Id, actorUser, request.ClientRequestId); return DeviceUpdateBatchCreationResult.Accepted(BuildBatchDto(existingBatch, existingBatch.Runs, devices)); } } // 8. 活跃任务冲突校验: 所选设备中任何一台不得有正在执行中的升级 var hasActive = await _db.DeviceUpdateRuns .AnyAsync(r => request.DeviceIds.Contains(r.DeviceId) && UpdateStatuses.ActiveStatuses.Contains(r.Status), ct); if (hasActive) { return DeviceUpdateBatchCreationResult.Conflict( UpdateErrorCodes.UpdateAlreadyRunning, "所选设备列表中部分设备当前已有正在执行中的升级任务。"); } // 9. 原子事务落库 var now = DateTimeOffset.UtcNow; var batchId = $"batch_upd_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24]; var batch = new DeviceUpdateBatch { Id = batchId, TenantId = request.TenantId, ReleaseId = release.Id, CanaryDeviceId = request.CanaryDeviceId, RequestedByUserId = actorUser, ClientRequestId = request.ClientRequestId, Status = UpdateBatchStatuses.CanaryRunning, TargetDeviceCount = request.DeviceIds.Count, CreatedAtUtc = now, CompletedAtUtc = null, StoppedAtUtc = null }; var runs = new List(); foreach (var devId in request.DeviceIds) { var dev = devices.First(d => string.Equals(d.Id, devId, StringComparison.OrdinalIgnoreCase)); bool isCanary = string.Equals(dev.Id, request.CanaryDeviceId, StringComparison.OrdinalIgnoreCase); var run = new DeviceUpdateRun { Id = $"upd_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24], TenantId = dev.TenantId, DeviceId = dev.Id, ReleaseId = release.Id, CorrelationId = $"batch_corr_{Guid.NewGuid():N}"[..20], RequestedByUserId = actorUser, ClientRequestId = null, FromVersion = dev.ServiceVersion ?? "unknown", TargetVersion = release.Version, Status = UpdateStatuses.PendingDispatch, CreatedAtUtc = now, DeadlineAtUtc = now.AddMinutes(5), BatchId = batchId, IsCanary = isCanary, // 关键门禁 U24: Canary 为 Released,其余 1~4 台物理置为 Held 门禁 DispatchGate = isCanary ? UpdateDispatchGates.Released : UpdateDispatchGates.Held }; runs.Add(run); } var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "DEVICE_UPDATE_BATCH_CREATED", TargetType = "DeviceUpdateBatch", TargetId = batchId, IpAddress = clientIp, Details = JsonSerializer.Serialize(new { BatchId = batchId, TenantId = request.TenantId, ReleaseId = release.Id, TargetVersion = release.Version, CanaryDeviceId = request.CanaryDeviceId, DeviceCount = runs.Count, ClientRequestId = request.ClientRequestId }) }; _db.DeviceUpdateBatches.Add(batch); _db.DeviceUpdateRuns.AddRange(runs); _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); // 唤醒后台调度器立即下发 Canary _dispatchNotifier.Notify(); _logger.LogInformation("Update batch {BatchId} created with {Count} devices (Canary={CanaryId}). State: CanaryRunning.", batchId, runs.Count, request.CanaryDeviceId); return DeviceUpdateBatchCreationResult.Accepted(BuildBatchDto(batch, runs, devices)); } public async Task> GetBatchAsync( string batchId, string actorRole, CancellationToken ct) { if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchQueryResult.Forbidden("仅系统管理员允许查询灰度批次详情。"); } var batch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .Include(b => b.Release) .FirstOrDefaultAsync(b => b.Id == batchId, ct); if (batch == null) { return DeviceUpdateBatchQueryResult.NotFound($"升级批次 '{batchId}' 不存在。"); } var deviceIds = batch.Runs.Select(r => r.DeviceId).ToList(); var devices = await _db.Devices .Include(d => d.Classroom) .Where(d => deviceIds.Contains(d.Id)) .ToListAsync(ct); return DeviceUpdateBatchQueryResult.Ok(BuildBatchDto(batch, batch.Runs, devices)); } public async Task ContinueBatchAsync( string batchId, string actorUser, string actorRole, string clientIp, CancellationToken ct) { // 1. RBAC: 仅限 SuperAdmin (U21) if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchActionResult.Forbidden("仅系统管理员允许人工确认放行灰度批次。"); } var batch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .Include(b => b.Release) .FirstOrDefaultAsync(b => b.Id == batchId, ct); if (batch == null) { return DeviceUpdateBatchActionResult.NotFound(UpdateErrorCodes.BatchNotFound, $"升级批次 '{batchId}' 不存在。"); } // 2. 状态机校验 (U26): 仅在 AwaitingContinue 状态下允许放行 if (!string.Equals(batch.Status, UpdateBatchStatuses.AwaitingContinue, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Cannot continue batch {BatchId}: Status is {Status}, expected AwaitingContinue.", batch.Id, batch.Status); return DeviceUpdateBatchActionResult.BadRequest( UpdateErrorCodes.BatchInvalidState, $"升级批次当前状态为 '{batch.Status}',仅在 'AwaitingContinue' 状态下允许人工确认放行。"); } // 3. 金丝雀成功校验 (U26): Canary 必须已处于 Succeeded 状态 var canaryRun = batch.Runs.FirstOrDefault(r => r.IsCanary); if (canaryRun == null || !string.Equals(canaryRun.Status, UpdateStatuses.Succeeded, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Cannot continue batch {BatchId}: Canary run {RunId} status is {Status}, not Succeeded.", batch.Id, canaryRun?.Id, canaryRun?.Status); return DeviceUpdateBatchActionResult.BadRequest( UpdateErrorCodes.CanaryNotSucceeded, "金丝雀验证设备未成功完成升级,严禁放行后续批次设备。"); } // 4. 原子放行门禁 (Held -> Released) var now = DateTimeOffset.UtcNow; batch.Status = UpdateBatchStatuses.RollingOut; var heldRuns = batch.Runs.Where(r => string.Equals(r.DispatchGate, UpdateDispatchGates.Held, StringComparison.OrdinalIgnoreCase)).ToList(); foreach (var r in heldRuns) { r.DispatchGate = UpdateDispatchGates.Released; r.NextDispatchAttemptAtUtc = now; // 立即安排分发 } var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "DEVICE_UPDATE_BATCH_CONTINUED", TargetType = "DeviceUpdateBatch", TargetId = batch.Id, IpAddress = clientIp, Details = JsonSerializer.Serialize(new { BatchId = batch.Id, TenantId = batch.TenantId, ReleasedDeviceCount = heldRuns.Count, PreviousStatus = UpdateBatchStatuses.AwaitingContinue, NewStatus = UpdateBatchStatuses.RollingOut }) }; _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); // 唤醒后台分发器 _dispatchNotifier.Notify(); _logger.LogInformation("Batch {BatchId} continued by user {User}. {Count} held runs released. Status -> RollingOut.", batch.Id, actorUser, heldRuns.Count); var deviceIds = batch.Runs.Select(r => r.DeviceId).ToList(); var devices = await _db.Devices .Include(d => d.Classroom) .Where(d => deviceIds.Contains(d.Id)) .ToListAsync(ct); return DeviceUpdateBatchActionResult.Ok(BuildBatchDto(batch, batch.Runs, devices)); } public async Task StopBatchAsync( string batchId, string actorUser, string actorRole, string clientIp, CancellationToken ct) { // 1. RBAC: 仅限 SuperAdmin (U21) if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchActionResult.Forbidden("仅系统管理员允许人工停止灰度批次。"); } var batch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .Include(b => b.Release) .FirstOrDefaultAsync(b => b.Id == batchId, ct); if (batch == null) { return DeviceUpdateBatchActionResult.NotFound(UpdateErrorCodes.BatchNotFound, $"升级批次 '{batchId}' 不存在。"); } var deviceIds = batch.Runs.Select(r => r.DeviceId).ToList(); var devices = await _db.Devices .Include(d => d.Classroom) .Where(d => deviceIds.Contains(d.Id)) .ToListAsync(ct); // 已终态批次幂等返回 if (string.Equals(batch.Status, UpdateBatchStatuses.Stopped, StringComparison.OrdinalIgnoreCase) || string.Equals(batch.Status, UpdateBatchStatuses.Completed, StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchActionResult.Ok(BuildBatchDto(batch, batch.Runs, devices)); } var now = DateTimeOffset.UtcNow; batch.Status = UpdateBatchStatuses.Stopped; batch.StoppedAtUtc = now; // 关键安全门禁 U27: Stop 动作严禁粗暴中断正在执行中的客户端任务 // Held 状态任务保持 Held (永不分发),活跃任务任由其自然终态化 var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "DEVICE_UPDATE_BATCH_STOPPED", TargetType = "DeviceUpdateBatch", TargetId = batch.Id, IpAddress = clientIp, Details = JsonSerializer.Serialize(new { BatchId = batch.Id, TenantId = batch.TenantId, StoppedAt = now, RemainingHeldCount = batch.Runs.Count(r => string.Equals(r.DispatchGate, UpdateDispatchGates.Held, StringComparison.OrdinalIgnoreCase)) }) }; _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); _logger.LogInformation("Batch {BatchId} stopped by user {User} at {Now:u}.", batch.Id, actorUser, now); return DeviceUpdateBatchActionResult.Ok(BuildBatchDto(batch, batch.Runs, devices)); } public async Task>> GetReleasesAsync( string actorRole, CancellationToken ct) { if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchQueryResult>.Forbidden("仅系统管理员允许查询发布包版本列表。"); } var list = await _db.UpdateReleases .AsNoTracking() .Where(r => r.IsEnabled) .OrderByDescending(r => r.CreatedAtUtc) .Select(r => new UpdateReleaseSummaryDto { ReleaseId = r.Id, Version = r.Version, Architecture = r.Architecture, PackageSizeBytes = r.PackageSizeBytes, PackageSha256 = r.PackageSha256, CreatedAtUtc = r.CreatedAtUtc, IsEnabled = r.IsEnabled }) .ToListAsync(ct); return DeviceUpdateBatchQueryResult>.Ok(list); } #region Helpers & Invariants private static UpdateBatchSummaryDto CalculateSummary(List runs) { var summary = new UpdateBatchSummaryDto { Target = runs.Count, Held = runs.Count(r => r.DispatchGate == UpdateDispatchGates.Held && r.Status == UpdateStatuses.PendingDispatch), Updating = runs.Count(r => r.DispatchGate == UpdateDispatchGates.Released && UpdateStatuses.ActiveStatuses.Contains(r.Status)), Succeeded = runs.Count(r => r.Status == UpdateStatuses.Succeeded), RolledBack = runs.Count(r => r.Status == UpdateStatuses.RolledBack), Failed = runs.Count(r => r.Status == UpdateStatuses.Failed), RollbackFailed = runs.Count(r => r.Status == UpdateStatuses.RollbackFailed), TimedOut = runs.Count(r => r.Status == UpdateStatuses.TimedOut) }; // 关键门禁 U28: 恒等守恒断言校验 (Target == Held + Updating + Succeeded + RolledBack + Failed + RollbackFailed + TimedOut) int sum = summary.Held + summary.Updating + summary.Succeeded + summary.RolledBack + summary.Failed + summary.RollbackFailed + summary.TimedOut; if (summary.Target != sum) { throw new InvalidOperationException($"Dynamic batch summary invariant violated! Target={summary.Target}, Sum={sum}"); } return summary; } private static UpdateBatchDto BuildBatchDto( DeviceUpdateBatch batch, List runs, List devices) { var deviceMap = devices.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase); var details = runs.Select(r => { deviceMap.TryGetValue(r.DeviceId, out var dev); return new UpdateBatchDeviceDetailDto { DeviceId = r.DeviceId, Hostname = dev?.Hostname ?? "", ClassroomName = dev?.Classroom?.DisplayName ?? "", IsCanary = r.IsCanary, DispatchGate = r.DispatchGate, Status = r.Status, FromVersion = r.FromVersion, TargetVersion = r.TargetVersion, StartedAtUtc = r.DispatchedAtUtc, CompletedAtUtc = r.CompletedAtUtc, ErrorCode = r.ErrorCode, ErrorMessage = r.ErrorMessage }; }).ToList(); return new UpdateBatchDto { BatchId = batch.Id, TenantId = batch.TenantId, ReleaseId = batch.ReleaseId, TargetVersion = batch.Release?.Version ?? (runs.FirstOrDefault()?.TargetVersion ?? ""), Status = batch.Status, CanaryDeviceId = batch.CanaryDeviceId, CreatedAtUtc = batch.CreatedAtUtc, CompletedAtUtc = batch.CompletedAtUtc, StoppedAtUtc = batch.StoppedAtUtc, Summary = CalculateSummary(runs), Devices = details }; } #endregion } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/DeviceUpdateBatchService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/DeviceUpdateDispatchWorker.cs SHA256: 4eb6ac9980c01b0ec2ce7fe32385e773543df9e858e333eed71b279aaef2b5cc SIZE: 9381 ================================================================================ using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Data; using ClassNotify.Server.Hubs; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ClassNotify.Server.Services; /// /// 客户端在线升级后台分发调度器 (P2.5 RC1-4 Phase 1) /// 严格基于数据库 PendingDispatch 状态作为可靠持久化队列,支持服务器重启后完全自动恢复 /// 离线真实等待重试,直至 Deadline 触发 TimedOut,绝不虚构状态 /// public sealed class DeviceUpdateDispatchWorker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly IDeviceUpdateDispatchNotifier _notifier; private readonly ILogger _logger; public DeviceUpdateDispatchWorker( IServiceScopeFactory scopeFactory, IDeviceUpdateDispatchNotifier notifier, ILogger logger) { _scopeFactory = scopeFactory; _notifier = notifier; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("DeviceUpdateDispatchWorker started."); while (!stoppingToken.IsCancellationRequested) { try { var processed = await ProcessPendingUpdatesAsync(stoppingToken); if (!processed) { await Task.WhenAny(_notifier.WaitAsync(stoppingToken), Task.Delay(1000, stoppingToken)); } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error in DeviceUpdateDispatchWorker loop"); await Task.Delay(1000, stoppingToken); } } _logger.LogInformation("DeviceUpdateDispatchWorker stopped."); } private async Task ProcessPendingUpdatesAsync(CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var presenceService = scope.ServiceProvider.GetRequiredService(); var hubContext = scope.ServiceProvider.GetRequiredService>(); var now = DateTimeOffset.UtcNow; // 1. 扫描超时任务 (处于非终态且超过 DeadlineAtUtc) var timedOutRuns = await db.DeviceUpdateRuns .Where(u => UpdateStatuses.ActiveStatuses.Contains(u.Status) && u.DeadlineAtUtc <= now) .Take(50) .ToListAsync(ct); if (timedOutRuns.Count > 0) { foreach (var r in timedOutRuns) { r.Status = UpdateStatuses.TimedOut; r.ErrorCode ??= UpdateErrorCodes.UpdateTimeout; r.ErrorMessage ??= "Update exceeded allowed execution deadline."; r.CompletedAtUtc = now; _logger.LogInformation("DeviceUpdateRun {Id} for device {DeviceId} timed out at {Now:u} (deadline was {Deadline:u})", r.Id, r.DeviceId, now, r.DeadlineAtUtc); } await db.SaveChangesAsync(ct); } // 2. 扫描待分发任务 (Status == PendingDispatch && DispatchGate == Released && NextDispatchAttemptAtUtc <= now && DeadlineAtUtc > now) // 关键门禁 U24: Held 任务绝对不处于分发队列,物理隔离未放行设备 var pendingRuns = await db.DeviceUpdateRuns .Where(u => u.Status == UpdateStatuses.PendingDispatch && u.DispatchGate == UpdateDispatchGates.Released && (u.NextDispatchAttemptAtUtc == null || u.NextDispatchAttemptAtUtc <= now) && u.DeadlineAtUtc > now) .OrderBy(u => u.CreatedAtUtc) .Take(50) .ToListAsync(ct); foreach (var run in pendingRuns) { var device = await db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == run.DeviceId, ct); var release = await db.UpdateReleases.AsNoTracking().FirstOrDefaultAsync(r => r.Id == run.ReleaseId, ct); if (release == null || !release.IsEnabled) { run.Status = UpdateStatuses.Failed; run.ErrorCode = UpdateErrorCodes.ReleaseDisabled; run.ErrorMessage = "Target release does not exist or has been disabled."; run.CompletedAtUtc = now; continue; } bool isOnline = device != null && presenceService.IsOnline(device.Id, device.LastHeartbeatAt); if (isOnline) { // 设备在线:通过 tenant-qualified SignalR 下发 StartDeviceUpdateCommand (U4) var command = new StartDeviceUpdateCommand { UpdateRunId = run.Id, ReleaseId = release.Id, CorrelationId = run.CorrelationId, TargetVersion = release.Version, ExpectedSha256 = release.PackageSha256, ManifestSignature = release.ManifestSignature, DeadlineAtUtc = run.DeadlineAtUtc }; var tenantChannel = $"t:{run.TenantId}:d:{run.DeviceId}"; await hubContext.Clients.Group(tenantChannel).StartDeviceUpdate(command); run.Status = UpdateStatuses.Downloading; run.DispatchedAtUtc = now; run.DispatchAttemptCount += 1; run.LastDispatchAttemptAtUtc = now; _logger.LogInformation("Successfully dispatched StartDeviceUpdateCommand to {Channel} for run {RunId} (Release={Release}, Version={Version}). State -> Downloading.", tenantChannel, run.Id, release.Id, release.Version); } else { // 设备离线:保持 PendingDispatch,按重试梯级安排下一次检测 (U6) run.DispatchAttemptCount += 1; run.LastDispatchAttemptAtUtc = now; int backoffSeconds = run.DispatchAttemptCount switch { 1 => 2, 2 => 5, 3 => 10, _ => 15 }; run.NextDispatchAttemptAtUtc = now.AddSeconds(backoffSeconds); _logger.LogInformation("Device {DeviceId} for update run {RunId} is offline. Retry scheduled in {Seconds}s (Attempt={Attempt})", run.DeviceId, run.Id, backoffSeconds, run.DispatchAttemptCount); } } // 3. 自动协调活跃中的批次状态 (CanaryRunning -> AwaitingContinue / Stopped; RollingOut -> Completed) await ReconcileBatchesAsync(db, now, ct); await db.SaveChangesAsync(ct); return pendingRuns.Count > 0 || timedOutRuns.Count > 0; } private async Task ReconcileBatchesAsync(ClassNotifyDbContext db, DateTimeOffset now, CancellationToken ct) { var activeBatches = await db.DeviceUpdateBatches .Include(b => b.Runs) .Where(b => b.Status == UpdateBatchStatuses.CanaryRunning || b.Status == UpdateBatchStatuses.RollingOut) .ToListAsync(ct); if (activeBatches.Count == 0) return; foreach (var batch in activeBatches) { if (batch.Status == UpdateBatchStatuses.CanaryRunning) { var canaryRun = batch.Runs.FirstOrDefault(r => r.IsCanary); if (canaryRun != null) { if (canaryRun.Status == UpdateStatuses.Succeeded) { batch.Status = UpdateBatchStatuses.AwaitingContinue; _logger.LogInformation("Batch {BatchId} Canary succeeded. Status -> AwaitingContinue.", batch.Id); } else if (UpdateStatuses.TerminalStatuses.Contains(canaryRun.Status)) { batch.Status = UpdateBatchStatuses.Stopped; batch.StoppedAtUtc = now; _logger.LogWarning("Batch {BatchId} Canary reached terminal failure {Status}. Batch -> Stopped.", batch.Id, canaryRun.Status); } } } else if (batch.Status == UpdateBatchStatuses.RollingOut) { bool allTerminal = batch.Runs.Count > 0 && batch.Runs.All(r => UpdateStatuses.TerminalStatuses.Contains(r.Status)); if (allTerminal) { batch.Status = UpdateBatchStatuses.Completed; batch.CompletedAtUtc = now; _logger.LogInformation("Batch {BatchId} all {Count} runs reached terminal states. Status -> Completed.", batch.Id, batch.Runs.Count); } } } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/DeviceUpdateDispatchWorker.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/DeviceUpdateService.cs SHA256: 9dff5f8f05f8730d5e3bfaed09ac0e3eb2358272268fc2c4996d0398b22d5b4c SIZE: 18472 ================================================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ClassNotify.Server.Infrastructure.Correlation; namespace ClassNotify.Server.Services; /// /// 客户端在线升级管控服务实现 (P2.5 RC1-4 Phase 1) /// public sealed class DeviceUpdateService : IDeviceUpdateService { private readonly ClassNotifyDbContext _db; private readonly IOptions _options; private readonly IDeviceUpdateDispatchNotifier _dispatchNotifier; private readonly ICorrelationContext _correlationContext; private readonly ILogger _logger; private static readonly ConcurrentDictionary _deviceLocks = new(); public DeviceUpdateService( ClassNotifyDbContext db, IOptions options, IDeviceUpdateDispatchNotifier dispatchNotifier, ICorrelationContext correlationContext, ILogger logger) { _db = db; _options = options; _dispatchNotifier = dispatchNotifier; _correlationContext = correlationContext; _logger = logger; } public async Task CreateUpdateRunAsync( string deviceId, CreateDeviceUpdateRequest request, string actorUser, string actorRole, string? actorTenantId, string clientIp, CancellationToken ct) { // 1. RBAC: 第一版升级属于高风险物理变更,仅限 SuperAdmin (U3) if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Unauthorized user {User} with role {Role} attempted to trigger update for device {DeviceId}. 403 Forbidden.", actorUser, actorRole, deviceId); return DeviceUpdateCreationResult.Forbidden("仅系统管理员 (SuperAdmin) 允许发起终端软件版本升级。"); } if (string.IsNullOrWhiteSpace(request.ReleaseId)) { return DeviceUpdateCreationResult.BadRequest(UpdateErrorCodes.ReleaseNotFound, "必须指定目标更新版本 ReleaseId。"); } // 2. 校验目标 Release 是否存在且启用 var release = await _db.UpdateReleases.AsNoTracking().FirstOrDefaultAsync(r => r.Id == request.ReleaseId, ct); if (release == null) { _logger.LogWarning("UpdateRelease {ReleaseId} not found.", request.ReleaseId); return DeviceUpdateCreationResult.BadRequest(UpdateErrorCodes.ReleaseNotFound, $"指定升级版本 '{request.ReleaseId}' 不存在。"); } if (!release.IsEnabled) { _logger.LogWarning("UpdateRelease {ReleaseId} is disabled.", request.ReleaseId); return DeviceUpdateCreationResult.BadRequest(UpdateErrorCodes.ReleaseDisabled, $"指定升级版本 '{request.ReleaseId}' 已停用。"); } // 3. 校验设备是否存在 var device = await _db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId, ct); if (device == null) { _logger.LogWarning("Target device {DeviceId} for update not found.", deviceId); return DeviceUpdateCreationResult.NotFound($"目标设备 '{deviceId}' 不存在。"); } // 4. 并发控制与防重校验 (U5: 单设备同时仅允许一个活跃更新任务) var gate = _deviceLocks.GetOrAdd(deviceId, _ => new SemaphoreSlim(1, 1)); await gate.WaitAsync(ct); try { // 4a. 幂等性校验 (ClientRequestId) if (!string.IsNullOrWhiteSpace(request.ClientRequestId)) { var existing = await _db.DeviceUpdateRuns .AsNoTracking() .FirstOrDefaultAsync(u => u.RequestedByUserId == actorUser && u.ClientRequestId == request.ClientRequestId, ct); if (existing != null) { _logger.LogInformation("Idempotent hit for update run {RunId} by user {User} (ClientRequestId={RequestId})", existing.Id, actorUser, request.ClientRequestId); return DeviceUpdateCreationResult.Accepted(MapToDto(existing)); } } // 4b. 检查设备当前是否有正在进行的更新任务 var existingActive = await _db.DeviceUpdateRuns .AsNoTracking() .FirstOrDefaultAsync(u => u.DeviceId == deviceId && UpdateStatuses.ActiveStatuses.Contains(u.Status), ct); if (existingActive != null) { _logger.LogWarning("Device {DeviceId} already has active update run {RunId} in status {Status}. 409 Conflict.", deviceId, existingActive.Id, existingActive.Status); return DeviceUpdateCreationResult.Conflict( UpdateErrorCodes.UpdateAlreadyRunning, existingActive.Id, $"设备 '{deviceId}' 当前已有正在执行中的版本升级任务 ({existingActive.Id},状态: {existingActive.Status})。"); } // 5. 写入数据库原子事务 var now = DateTimeOffset.UtcNow; var runId = $"upd_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24]; var correlationId = !string.IsNullOrWhiteSpace(_correlationContext.CorrelationId) ? _correlationContext.CorrelationId : $"upd_corr_{Guid.NewGuid():N}"[..20]; var updateRun = new DeviceUpdateRun { Id = runId, TenantId = device.TenantId, DeviceId = device.Id, ReleaseId = release.Id, CorrelationId = correlationId, RequestedByUserId = actorUser, ClientRequestId = request.ClientRequestId, FromVersion = device.ServiceVersion ?? "unknown", TargetVersion = release.Version, Status = UpdateStatuses.PendingDispatch, CreatedAtUtc = now, DeadlineAtUtc = now.AddMinutes(5), // 5 分钟超时窗口 DispatchedAtUtc = null, CompletedAtUtc = null, DispatchAttemptCount = 0, LastDispatchAttemptAtUtc = null, NextDispatchAttemptAtUtc = now, ErrorCode = null, ErrorMessage = null }; var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "DEVICE_UPDATE_REQUESTED", TargetType = "DeviceUpdateRun", TargetId = runId, Details = JsonSerializer.Serialize(new { updateRunId = runId, deviceId = device.Id, tenantId = device.TenantId, releaseId = release.Id, fromVersion = updateRun.FromVersion, targetVersion = updateRun.TargetVersion, correlationId }), IpAddress = clientIp }; _db.DeviceUpdateRuns.Add(updateRun); _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); _logger.LogInformation("Device update requested: RunId={RunId}, DeviceId={DeviceId}, TargetVersion={Version}, Release={ReleaseId}", runId, device.Id, release.Version, release.Id); // 6. 唤醒调度 Worker _dispatchNotifier.Notify(); return DeviceUpdateCreationResult.Accepted(MapToDto(updateRun)); } finally { gate.Release(); } } public async Task> GetDeviceUpdateRunAsync( string updateRunId, string actorRole, CancellationToken ct) { if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateQueryResult.Forbidden("仅系统管理员允许查询升级任务详情。"); } var run = await _db.DeviceUpdateRuns.AsNoTracking().FirstOrDefaultAsync(u => u.Id == updateRunId, ct); if (run == null) { return DeviceUpdateQueryResult.NotFound($"升级任务 '{updateRunId}' 不存在。"); } return DeviceUpdateQueryResult.Ok(MapToDto(run)); } public async Task>> GetDeviceUpdateHistoryAsync( string deviceId, int take, string actorRole, CancellationToken ct) { if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateQueryResult>.Forbidden("仅系统管理员允许查询设备升级历史。"); } var clampedTake = Math.Clamp(take <= 0 ? 5 : take, 1, 20); var list = await _db.DeviceUpdateRuns .AsNoTracking() .Where(u => u.DeviceId == deviceId) .OrderByDescending(u => u.CreatedAtUtc) .Take(clampedTake) .Select(u => MapToDto(u)) .ToListAsync(ct); return DeviceUpdateQueryResult>.Ok(list); } public async Task PreparePackageDownloadAsync( string releaseId, string deviceId, CancellationToken ct) { var device = await _db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId, ct); if (device == null) { return DeviceUpdateDownloadResult.Forbidden("未经认证或未知的设备标识。"); } var release = await _db.UpdateReleases.AsNoTracking().FirstOrDefaultAsync(r => r.Id == releaseId, ct); if (release == null || !release.IsEnabled) { return DeviceUpdateDownloadResult.NotFound($"目标升级版本 '{releaseId}' 不存在或已被停用。"); } // 路径防逃逸核验 var root = _options.Value.GetEffectiveStorageRoot(); string physicalPath; try { physicalPath = UpdatePackagePathResolver.ResolvePackagePath(root, release.PackageRelativePath); } catch (InvalidUpdatePackagePathException ex) { _logger.LogWarning("CRITICAL: Package path traversal detected for release {ReleaseId}: {Message} (Path='{Path}')", release.Id, ex.Message, release.PackageRelativePath); return DeviceUpdateDownloadResult.BadRequest(UpdateErrorCodes.InvalidStoragePath, "Invalid package path detected."); } if (!File.Exists(physicalPath)) { _logger.LogError("Update package file missing from disk: ReleaseId={ReleaseId}, Path={Path}", release.Id, physicalPath); return DeviceUpdateDownloadResult.ServerError(UpdateErrorCodes.PackageNotReady, "Update package file is missing from storage."); } var downloadName = $"classnotify-update-{release.Version}-{release.Architecture}.zip"; return DeviceUpdateDownloadResult.Ok(physicalPath, downloadName, release.PackageSha256, release.PackageSizeBytes); } public async Task ReportDeviceUpdateStatusAsync( string deviceId, string updateRunId, DeviceUpdateReportRequest request, CancellationToken ct) { var run = await _db.DeviceUpdateRuns.FirstOrDefaultAsync(u => u.Id == updateRunId && u.DeviceId == deviceId, ct); if (run == null) { _logger.LogWarning("Update run {RunId} for device {DeviceId} not found for status report.", updateRunId, deviceId); return DeviceUpdateReportResult.NotFound($"Update run '{updateRunId}' not found for device '{deviceId}'."); } // 状态流转合法性校验 (严防非法跳转与终态复活) if (!IsValidTransition(run.Status, request.Status)) { _logger.LogWarning("Illegal update state transition rejected for run {RunId}: Current={Current}, Requested={Requested}", run.Id, run.Status, request.Status); return DeviceUpdateReportResult.Conflict( UpdateErrorCodes.InvalidUpdateStateTransition, $"Invalid update state transition from '{run.Status}' to '{request.Status}'. Terminal states cannot be revived."); } run.Status = request.Status; if (!string.IsNullOrWhiteSpace(request.ErrorCode)) run.ErrorCode = request.ErrorCode; if (!string.IsNullOrWhiteSpace(request.ErrorMessage)) run.ErrorMessage = request.ErrorMessage; var now = DateTimeOffset.UtcNow; if (request.Status == UpdateStatuses.Succeeded) { run.CompletedAtUtc = now; // 升级成功:同步更新设备的版本心跳与客户端版本 (U8) var dev = await _db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId, ct); if (dev != null) { dev.ServiceVersion = run.TargetVersion; dev.ClientVersion = run.TargetVersion; _logger.LogInformation("Device {DeviceId} successfully updated from {FromVersion} to {TargetVersion}!", deviceId, run.FromVersion, run.TargetVersion); } } else if (UpdateStatuses.TerminalStatuses.Contains(request.Status)) { run.CompletedAtUtc = now; _logger.LogWarning("Update run {RunId} for device {DeviceId} terminated with status {Status}: Error={Error}, Msg={Msg}", run.Id, deviceId, request.Status, request.ErrorCode, request.ErrorMessage); } // Phase 3: 若任务隶属于灰度批次,即时推进批次生命周期状态 (CanaryRunning -> AwaitingContinue / Stopped; RollingOut -> Completed) if (!string.IsNullOrWhiteSpace(run.BatchId)) { var batch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .FirstOrDefaultAsync(b => b.Id == run.BatchId, ct); if (batch != null) { if (batch.Status == UpdateBatchStatuses.CanaryRunning && run.IsCanary) { if (request.Status == UpdateStatuses.Succeeded) { batch.Status = UpdateBatchStatuses.AwaitingContinue; _logger.LogInformation("Batch {BatchId} Canary device {DeviceId} succeeded. Batch -> AwaitingContinue.", batch.Id, deviceId); } else if (UpdateStatuses.TerminalStatuses.Contains(request.Status)) { batch.Status = UpdateBatchStatuses.Stopped; batch.StoppedAtUtc = now; _logger.LogWarning("Batch {BatchId} Canary device {DeviceId} entered terminal status {Status}. Batch -> Stopped.", batch.Id, deviceId, request.Status); } } else if (batch.Status == UpdateBatchStatuses.RollingOut) { bool allTerminal = batch.Runs.Count > 0 && batch.Runs.All(r => UpdateStatuses.TerminalStatuses.Contains(r.Status)); if (allTerminal) { batch.Status = UpdateBatchStatuses.Completed; batch.CompletedAtUtc = now; _logger.LogInformation("Batch {BatchId} all {Count} runs reached terminal states. Batch -> Completed.", batch.Id, batch.Runs.Count); } } } } await _db.SaveChangesAsync(ct); return DeviceUpdateReportResult.Ok(); } private static bool IsValidTransition(string currentStatus, string targetStatus) { if (string.Equals(currentStatus, targetStatus, StringComparison.OrdinalIgnoreCase)) { return true; // Idempotent same-state report } // 终态不可复活 (Succeeded, Failed, RolledBack, RollbackFailed, TimedOut) if (UpdateStatuses.TerminalStatuses.Contains(currentStatus)) { return false; } return currentStatus switch { UpdateStatuses.PendingDispatch => targetStatus is UpdateStatuses.Downloading or UpdateStatuses.Failed or UpdateStatuses.TimedOut, UpdateStatuses.Downloading => targetStatus is UpdateStatuses.Verified or UpdateStatuses.Failed or UpdateStatuses.TimedOut, UpdateStatuses.Verified => targetStatus is UpdateStatuses.Installing or UpdateStatuses.Failed or UpdateStatuses.TimedOut, UpdateStatuses.Installing => targetStatus is UpdateStatuses.HealthChecking or UpdateStatuses.Succeeded or UpdateStatuses.RollingBack or UpdateStatuses.Failed or UpdateStatuses.TimedOut, UpdateStatuses.HealthChecking => targetStatus is UpdateStatuses.Succeeded or UpdateStatuses.RollingBack or UpdateStatuses.Failed or UpdateStatuses.TimedOut, UpdateStatuses.RollingBack => targetStatus is UpdateStatuses.RolledBack or UpdateStatuses.RollbackFailed or UpdateStatuses.Failed or UpdateStatuses.TimedOut, _ => false }; } private static DeviceUpdateStatusDto MapToDto(DeviceUpdateRun u) => new() { UpdateRunId = u.Id, DeviceId = u.DeviceId, TenantId = u.TenantId, ReleaseId = u.ReleaseId, Status = u.Status, FromVersion = u.FromVersion, TargetVersion = u.TargetVersion, CreatedAtUtc = u.CreatedAtUtc, DeadlineAtUtc = u.DeadlineAtUtc, CompletedAtUtc = u.CompletedAtUtc, ErrorCode = u.ErrorCode, ErrorMessage = u.ErrorMessage }; } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/DeviceUpdateService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/DeviceVersionEvaluator.cs SHA256: e9b2924ae1b298c882ccb6b7c54f3c106f541e74ce5f0d2dea36ca42c3b0e208 SIZE: 3239 ================================================================================ using ClassNotify.Server.Configuration; using ClassNotify.Shared.Enums; using Microsoft.Extensions.Options; namespace ClassNotify.Server.Services; public sealed record DeviceVersionEvaluation( FleetVersionStatus Status, IReadOnlyList Reasons); public interface IDeviceVersionEvaluator { DeviceVersionEvaluation Evaluate( string? serviceVersion, string? clientVersion, int? protocolVersion); } public sealed class DeviceVersionEvaluator : IDeviceVersionEvaluator { private readonly DeviceVersionPolicyOptions _policy; public DeviceVersionEvaluator(IOptions options) { _policy = options.Value; } public DeviceVersionEvaluation Evaluate( string? serviceVersion, string? clientVersion, int? protocolVersion) { var reasons = new List(); if (!TryParse(serviceVersion, out var service) || !TryParse(clientVersion, out var client) || protocolVersion == null) { reasons.Add("版本信息不完整"); return new DeviceVersionEvaluation(FleetVersionStatus.Unknown, reasons); } var minService = TryParsePolicyVersion(_policy.MinimumServiceVersion, new Version(2, 4, 0)); var recService = TryParsePolicyVersion(_policy.RecommendedServiceVersion, new Version(2, 5, 0)); var minClient = TryParsePolicyVersion(_policy.MinimumClientVersion, new Version(2, 4, 0)); var recClient = TryParsePolicyVersion(_policy.RecommendedClientVersion, new Version(2, 5, 0)); var minProtocol = _policy.MinimumProtocolVersion > 0 ? _policy.MinimumProtocolVersion : 2; if (service < minService) { reasons.Add($"Service {service} 低于最低支持版本 {minService}"); } if (client < minClient) { reasons.Add($"Client {client} 低于最低支持版本 {minClient}"); } if (protocolVersion.Value < minProtocol) { reasons.Add($"Protocol {protocolVersion.Value} 低于最低协议 {minProtocol}"); } if (reasons.Count > 0) { return new DeviceVersionEvaluation(FleetVersionStatus.Unsupported, reasons); } if (service < recService) { reasons.Add($"Service 建议升级至 {recService}"); } if (client < recClient) { reasons.Add($"Client 建议升级至 {recClient}"); } if (reasons.Count > 0) { return new DeviceVersionEvaluation(FleetVersionStatus.Outdated, reasons); } return new DeviceVersionEvaluation(FleetVersionStatus.Current, Array.Empty()); } private static Version TryParsePolicyVersion(string? input, Version fallback) { if (TryParse(input, out var parsed)) { return parsed; } return fallback; } private static bool TryParse(string? input, out Version version) { version = new Version(); if (string.IsNullOrWhiteSpace(input)) { return false; } return Version.TryParse(input.Trim(), out version!); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/DeviceVersionEvaluator.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/FleetVersionService.cs SHA256: 740aee6514bbf3fe171871709f1567b1cc5fa88f9caed91103474b1e86496315 SIZE: 7378 ================================================================================ using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; namespace ClassNotify.Server.Services; public interface IFleetVersionService { Task GetFleetVersionSummaryAsync(CancellationToken ct = default); Task> GetFleetDevicesAsync(FleetDeviceVersionQuery query, CancellationToken ct = default); } public sealed class FleetVersionService : IFleetVersionService { private readonly ClassNotifyDbContext _db; private readonly IDeviceVersionEvaluator _versionEvaluator; private readonly IDevicePresenceService _presenceService; private readonly DeviceVersionPolicyOptions _policy; public FleetVersionService( ClassNotifyDbContext db, IDeviceVersionEvaluator versionEvaluator, IDevicePresenceService presenceService, IOptions options) { _db = db; _versionEvaluator = versionEvaluator; _presenceService = presenceService; _policy = options.Value; } public async Task GetFleetVersionSummaryAsync(CancellationToken ct = default) { var devices = await _db.Devices .AsNoTracking() .Select(d => new { d.ServiceVersion, d.ClientVersion, d.ProtocolVersion }) .ToListAsync(ct); int current = 0; int outdated = 0; int unsupported = 0; int unknown = 0; foreach (var d in devices) { var result = _versionEvaluator.Evaluate( d.ServiceVersion, d.ClientVersion, d.ProtocolVersion); switch (result.Status) { case FleetVersionStatus.Current: current++; break; case FleetVersionStatus.Outdated: outdated++; break; case FleetVersionStatus.Unsupported: unsupported++; break; default: unknown++; break; } } return new FleetVersionSummaryDto { Total = devices.Count, Current = current, Outdated = outdated, Unsupported = unsupported, Unknown = unknown, GeneratedAtUtc = DateTimeOffset.UtcNow, Policy = BuildPolicyDto() }; } public async Task> GetFleetDevicesAsync( FleetDeviceVersionQuery query, CancellationToken ct = default) { var devices = await _db.Devices .AsNoTracking() .ToListAsync(ct); var tenants = await _db.Tenants .AsNoTracking() .ToDictionaryAsync(t => t.Id, t => t.Name, ct); var classrooms = await _db.Classrooms .AsNoTracking() .ToDictionaryAsync(c => $"{c.TenantId}_{c.Id}", c => c.DisplayName, ct); var results = new List(); foreach (var d in devices) { var eval = _versionEvaluator.Evaluate( d.ServiceVersion, d.ClientVersion, d.ProtocolVersion); var isOnline = _presenceService.IsOnline(d.Id, d.LastHeartbeatAt); tenants.TryGetValue(d.TenantId, out var tenantName); tenantName ??= d.TenantId; classrooms.TryGetValue($"{d.TenantId}_{d.ClassroomId}", out var classroomName); classroomName ??= d.ClassroomId; // 1. Status Filter if (!string.IsNullOrWhiteSpace(query.Status) && !string.Equals(query.Status, "all", StringComparison.OrdinalIgnoreCase)) { if (!string.Equals(eval.Status.ToString(), query.Status.Trim(), StringComparison.OrdinalIgnoreCase)) { continue; } } // 2. Tenant Filter if (!string.IsNullOrWhiteSpace(query.TenantId) && !string.Equals(query.TenantId, "all", StringComparison.OrdinalIgnoreCase)) { if (!string.Equals(d.TenantId, query.TenantId.Trim(), StringComparison.OrdinalIgnoreCase)) { continue; } } // 3. Online Filter if (query.Online.HasValue) { if (isOnline != query.Online.Value) { continue; } } // 4. Keyword Query (DeviceId, Hostname, ClassroomName, TenantName) if (!string.IsNullOrWhiteSpace(query.Q)) { var q = query.Q.Trim(); bool matches = d.Id.Contains(q, StringComparison.OrdinalIgnoreCase) || (d.Hostname != null && d.Hostname.Contains(q, StringComparison.OrdinalIgnoreCase)) || classroomName.Contains(q, StringComparison.OrdinalIgnoreCase) || tenantName.Contains(q, StringComparison.OrdinalIgnoreCase); if (!matches) { continue; } } results.Add(new FleetDeviceVersionDto { DeviceId = d.Id, TenantId = d.TenantId, TenantName = tenantName, ClassroomId = d.ClassroomId, ClassroomName = classroomName, Hostname = d.Hostname, IsOnline = isOnline, LastHeartbeatAt = d.LastHeartbeatAt, ServiceVersion = d.ServiceVersion, ClientVersion = d.ClientVersion, ProtocolVersion = d.ProtocolVersion, OsVersion = d.OsVersion, Architecture = d.Architecture, VersionStatus = eval.Status, Reasons = eval.Reasons.ToList() }); } // Ordered by risk: Unsupported first (0), Outdated (1), Unknown (2), Current (3), then by Tenant & Class return results .OrderBy(r => GetSeverityRank(r.VersionStatus)) .ThenBy(r => r.TenantName) .ThenBy(r => r.ClassroomName) .ToList(); } private static int GetSeverityRank(FleetVersionStatus status) => status switch { FleetVersionStatus.Unsupported => 0, FleetVersionStatus.Outdated => 1, FleetVersionStatus.Unknown => 2, FleetVersionStatus.Current => 3, _ => 4 }; private DeviceVersionPolicyViewDto BuildPolicyDto() { return new DeviceVersionPolicyViewDto { MinimumServiceVersion = _policy.MinimumServiceVersion, RecommendedServiceVersion = _policy.RecommendedServiceVersion, MinimumClientVersion = _policy.MinimumClientVersion, RecommendedClientVersion = _policy.RecommendedClientVersion, MinimumProtocolVersion = _policy.MinimumProtocolVersion > 0 ? _policy.MinimumProtocolVersion : 2 }; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/FleetVersionService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/IDeviceUpdateBatchService.cs SHA256: 67249c5552a9bf024b908976217388a3dc298a0b5d3e9e08047a154c04c773d5 SIZE: 4561 ================================================================================ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ClassNotify.Shared.Models; namespace ClassNotify.Server.Services; /// /// 批次升级创建结果 /// public sealed class DeviceUpdateBatchCreationResult { public int StatusCode { get; init; } public string? ErrorCode { get; init; } public string? ErrorMessage { get; init; } public UpdateBatchDto? Dto { get; init; } public static DeviceUpdateBatchCreationResult Accepted(UpdateBatchDto dto) => new() { StatusCode = 202, Dto = dto }; public static DeviceUpdateBatchCreationResult Conflict(string errorCode, string message) => new() { StatusCode = 409, ErrorCode = errorCode, ErrorMessage = message }; public static DeviceUpdateBatchCreationResult Forbidden(string message) => new() { StatusCode = 403, ErrorCode = UpdateErrorCodes.Forbidden, ErrorMessage = message }; public static DeviceUpdateBatchCreationResult BadRequest(string errorCode, string message) => new() { StatusCode = 400, ErrorCode = errorCode, ErrorMessage = message }; } /// /// 批次控制动作 (Continue / Stop) 结果 /// public sealed class DeviceUpdateBatchActionResult { public int StatusCode { get; init; } public string? ErrorCode { get; init; } public string? ErrorMessage { get; init; } public UpdateBatchDto? Dto { get; init; } public static DeviceUpdateBatchActionResult Ok(UpdateBatchDto dto) => new() { StatusCode = 200, Dto = dto }; public static DeviceUpdateBatchActionResult BadRequest(string errorCode, string message) => new() { StatusCode = 400, ErrorCode = errorCode, ErrorMessage = message }; public static DeviceUpdateBatchActionResult NotFound(string errorCode, string message) => new() { StatusCode = 404, ErrorCode = errorCode, ErrorMessage = message }; public static DeviceUpdateBatchActionResult Forbidden(string message) => new() { StatusCode = 403, ErrorCode = UpdateErrorCodes.Forbidden, ErrorMessage = message }; } /// /// 批次升级查询结果 /// public sealed class DeviceUpdateBatchQueryResult { public int StatusCode { get; init; } public string? ErrorCode { get; init; } public string? ErrorMessage { get; init; } public T? Data { get; init; } public static DeviceUpdateBatchQueryResult Ok(T data) => new() { StatusCode = 200, Data = data }; public static DeviceUpdateBatchQueryResult NotFound(string message) => new() { StatusCode = 404, ErrorCode = UpdateErrorCodes.BatchNotFound, ErrorMessage = message }; public static DeviceUpdateBatchQueryResult Forbidden(string message) => new() { StatusCode = 403, ErrorCode = UpdateErrorCodes.Forbidden, ErrorMessage = message }; } /// /// 小规模灰度升级管控服务接口 (P2.5 RC1-4 Phase 3) /// public interface IDeviceUpdateBatchService { /// /// SuperAdmin 创建小规模灰度升级批次 (1~5台设备,同校,单Canary) /// Task CreateBatchAsync( CreateUpdateBatchRequest request, string actorUser, string actorRole, string? actorTenantId, string clientIp, CancellationToken ct); /// /// SuperAdmin 查询灰度批次全量实时聚合视图 (严禁读取持久化汇总字段) /// Task> GetBatchAsync( string batchId, string actorRole, CancellationToken ct); /// /// SuperAdmin 人工放行灰度批次后续受控设备 (仅在 Canary 成功后生效) /// Task ContinueBatchAsync( string batchId, string actorUser, string actorRole, string clientIp, CancellationToken ct); /// /// SuperAdmin 人工紧急终止灰度批次 (Held 保持阻断,运行中安全终态化) /// Task StopBatchAsync( string batchId, string actorUser, string actorRole, string clientIp, CancellationToken ct); /// /// 获取可用于升级的 Release 清单 (供下拉框呈现) /// Task>> GetReleasesAsync( string actorRole, CancellationToken ct); } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/IDeviceUpdateBatchService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/IDeviceUpdateService.cs SHA256: f0f43237dd3a75807d42c53e9c48ee60bf3a3a357bf3f4d6ded0458f6bc9425d SIZE: 6854 ================================================================================ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using ClassNotify.Shared.Models; namespace ClassNotify.Server.Services; /// /// 客户端在线升级发起结果 /// public sealed class DeviceUpdateCreationResult { public int StatusCode { get; init; } public string? ErrorCode { get; init; } public string? ErrorMessage { get; init; } public string? ExistingUpdateRunId { get; init; } public DeviceUpdateStatusDto? Dto { get; init; } public static DeviceUpdateCreationResult Accepted(DeviceUpdateStatusDto dto) => new() { StatusCode = 202, Dto = dto }; public static DeviceUpdateCreationResult Conflict(string errorCode, string existingRunId, string message) => new() { StatusCode = 409, ErrorCode = errorCode, ExistingUpdateRunId = existingRunId, ErrorMessage = message }; public static DeviceUpdateCreationResult Forbidden(string message) => new() { StatusCode = 403, ErrorCode = UpdateErrorCodes.Forbidden, ErrorMessage = message }; public static DeviceUpdateCreationResult NotFound(string message) => new() { StatusCode = 404, ErrorCode = UpdateErrorCodes.DeviceNotFound, ErrorMessage = message }; public static DeviceUpdateCreationResult BadRequest(string errorCode, string message) => new() { StatusCode = 400, ErrorCode = errorCode, ErrorMessage = message }; } /// /// 客户端在线升级状态查询结果 /// public sealed class DeviceUpdateQueryResult { public int StatusCode { get; init; } public string? ErrorCode { get; init; } public string? ErrorMessage { get; init; } public T? Data { get; init; } public static DeviceUpdateQueryResult Ok(T data) => new() { StatusCode = 200, Data = data }; public static DeviceUpdateQueryResult Forbidden(string message) => new() { StatusCode = 403, ErrorCode = UpdateErrorCodes.Forbidden, ErrorMessage = message }; public static DeviceUpdateQueryResult NotFound(string message) => new() { StatusCode = 404, ErrorCode = UpdateErrorCodes.ReleaseNotFound, ErrorMessage = message }; } /// /// 升级包下载准备结果 /// public sealed class DeviceUpdateDownloadResult { public int StatusCode { get; init; } public string? ErrorCode { get; init; } public string? ErrorMessage { get; init; } public string? PhysicalPath { get; init; } public string? DownloadFileName { get; init; } public string? Sha256 { get; init; } public long SizeBytes { get; init; } public static DeviceUpdateDownloadResult Ok(string physicalPath, string downloadFileName, string sha256, long sizeBytes) => new() { StatusCode = 200, PhysicalPath = physicalPath, DownloadFileName = downloadFileName, Sha256 = sha256, SizeBytes = sizeBytes }; public static DeviceUpdateDownloadResult Forbidden(string message) => new() { StatusCode = 403, ErrorCode = UpdateErrorCodes.Forbidden, ErrorMessage = message }; public static DeviceUpdateDownloadResult NotFound(string message) => new() { StatusCode = 404, ErrorCode = UpdateErrorCodes.ReleaseNotFound, ErrorMessage = message }; public static DeviceUpdateDownloadResult BadRequest(string errorCode, string message) => new() { StatusCode = 400, ErrorCode = errorCode, ErrorMessage = message }; public static DeviceUpdateDownloadResult ServerError(string errorCode, string message) => new() { StatusCode = 500, ErrorCode = errorCode, ErrorMessage = message }; } /// /// 升级指令调度唤醒通知器接口 /// public interface IDeviceUpdateDispatchNotifier { void Notify(); Task WaitAsync(CancellationToken ct); } /// /// 升级指令调度唤醒通知器实现 /// public sealed class DeviceUpdateDispatchNotifier : IDeviceUpdateDispatchNotifier { private readonly Channel _channel = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropOldest }); public void Notify() { _channel.Writer.TryWrite(1); } public async Task WaitAsync(CancellationToken ct) { await _channel.Reader.WaitToReadAsync(ct); while (_channel.Reader.TryRead(out _)) { } } } /// /// 终端上报状态流转结果 /// public sealed class DeviceUpdateReportResult { public int StatusCode { get; init; } public string? ErrorCode { get; init; } public string? ErrorMessage { get; init; } public static DeviceUpdateReportResult Ok() => new() { StatusCode = 200 }; public static DeviceUpdateReportResult NotFound(string message) => new() { StatusCode = 404, ErrorCode = UpdateErrorCodes.DeviceNotFound, ErrorMessage = message }; public static DeviceUpdateReportResult Conflict(string errorCode, string message) => new() { StatusCode = 409, ErrorCode = errorCode, ErrorMessage = message }; } /// /// 客户端在线升级管控服务契约 (P2.5 RC1-4) /// public interface IDeviceUpdateService { /// /// SuperAdmin 触发指定设备升级 (U3: SuperAdmin-only, U5: Single active update) /// Task CreateUpdateRunAsync( string deviceId, CreateDeviceUpdateRequest request, string actorUser, string actorRole, string? actorTenantId, string clientIp, CancellationToken ct); /// /// 查询指定单次升级任务详情与状态 /// Task> GetDeviceUpdateRunAsync( string updateRunId, string actorRole, CancellationToken ct); /// /// 查询指定设备的历史升级任务记录 (支持刷新恢复) /// Task>> GetDeviceUpdateHistoryAsync( string deviceId, int take, string actorRole, CancellationToken ct); /// /// 终端鉴权安全下载指定 Release 安装包 (U1, U2, 路径防逃逸) /// Task PreparePackageDownloadAsync( string releaseId, string deviceId, CancellationToken ct); /// /// 终端上报升级任务阶段与执行结果 (严格状态机合法性校验,阻断终态复活与非法跳跃) /// Task ReportDeviceUpdateStatusAsync( string deviceId, string updateRunId, DeviceUpdateReportRequest request, CancellationToken ct); } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/IDeviceUpdateService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/ISecurityService.cs SHA256: bdcd35b88fddc78d41d2a977adeb1c9f539eb00d9443bba16a78530d2c1b73af SIZE: 10942 ================================================================================ using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; namespace ClassNotify.Server.Services; public sealed record DeviceConnectionRegistrationResult( string CurrentConnectionId, string? ReplacedConnectionId); public interface ISecurityService { // Auth & Identity Task LoginTeacherAsync(TeacherLoginDto dto, string? remoteIp = null); Task RegisterPersonalTeacherAsync(RegisterPersonalTeacherDto dto, string? remoteIp = null); Task ActivateDeviceAsync(DeviceActivationRequestDto dto); Task ValidateDeviceAsync(string deviceId, string deviceToken); Task<(Device Device, string RawDeviceToken)> EnsureDeviceProvisionedAsync(DeviceBootstrapRequestDto req); string GenerateJwtToken(User user, Tenant? tenant = null, bool isPasswordChangeOnly = false); // Password Recovery & Reset (Turn 62) Task ResetPasswordByRecoveryKeyAsync(ResetPasswordByRecoveryKeyDto dto, string? remoteIp = null); Task<(bool Success, string Message)> RequestPasswordResetEmailAsync(RequestPasswordResetEmailDto dto, string? remoteIp = null); Task<(bool Success, string Message)> ResetPasswordByTokenAsync(ResetPasswordByTokenDto dto, string? remoteIp = null); Task IssueAdminResetTicketAsync(string adminUserId, string adminUsername, string targetUserId, string? remoteIp = null); // Tenant & Classrooms Task GetClassroomAsync(string tenantId, string classId); Task> GetClassroomsAsync(string tenantId); Task CreateClassroomAsync(string tenantId, CreateClassroomDto dto); Task GetTenantAsync(string tenantId); Task> GetTenantsOverviewAsync(); // Users Task> GetUsersAsync(string tenantId); Task CreateUserAsync(string tenantId, CreateTeacherDto dto); // Devices & Metrics Task GetAdminMetricsAsync(); Task> GetAllDevicesAsync(); Task> GetTenantDevicesAsync(string tenantId); Task RegisterDeviceConnectionAsync(string connectionId, string deviceId, string tenantId, string classroomId, string? hostname, string? remoteIp, string? clientVersion, string? installationId = null, string? hardwareHash = null); Task UnregisterDeviceConnectionAsync(string connectionId); bool IsCurrentDeviceConnection(string deviceId, string connectionId); Task UpdateDeviceHeartbeatAsync(string connectionId, DeviceHeartbeatDto? heartbeat = null); string? GetDeviceConnectionId(string deviceId); Task InvalidateDeviceSessionAsync(string deviceId, string reason = "IdentityChanged"); Task InvalidateDeviceSessionByEndpointAsync(string? deviceId, string? installationId, string? hardwareHash, string reason = "EndpointReactivated"); Task<(bool Success, string Message, string? NewClassName)> UpdateDeviceClassNameAsync(string deviceId, string newClassName, string operatorName, string operatorRole); // Activation Codes & License Lifecycle (P3 & Commercial Pilot & Turn 50 Dual-Distribution) 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); 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); Task AssignActivationCodeAsync(string tenantId, AssignActivationCodeRequestDto dto, string? actor = null, string? actorRole = null, string? ip = null); Task> GetTeacherActivationCodesAsync(string tenantId, string teacherUserId); Task RevealTeacherActivationCodeAsync(string tenantId, string teacherUserId, string code, string? actor = null, string? ip = null); Task UpdateActivationCodeNotesAsync(List codes, string? notes, string? actor = null, string? actorRole = null, string? ip = null); Task> GetActivationCodesAsync(string? tenantId); Task GetDeviceLicenseStatusAsync(string deviceId); 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); 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); Task> GetLicenseRecordsAsync(string? tenantId = null, int limit = 100); // Notifications & ACKs (PostgreSQL & NotificationReceipt per-device isolation) Task RecordNotificationAsync(NotificationDto notification, string? senderUserId, string senderName); Task RecordAckAsync(string messageId, string authenticatedDeviceId, AckReceiptDto ack); Task ValidateNotificationTargetAsync(string messageId, string tenantId, string classroomId); Task> GetNotificationsAsync(string? tenantId, string? classId, int limit = 50, string? currentUserId = null); Task> GetPendingNotificationsForDeviceAsync(string deviceId); Task CancelNotificationAsync(string notificationId, string actorUserId, string actorUsername, string role, string tenantId, string? ip, CancellationToken ct = default); Task DismissNotificationHistoryAsync(string notificationId, string tenantId, string actorUserId, CancellationToken ct = default); Task DeleteNotificationAsync(string notificationId, string tenantId, string actorUserId, string role, CancellationToken ct = default); Task ResetSchoolTeacherPasswordAsync(string schoolAdminTenantId, string teacherUserId, string newPassword, string actorUsername, string? ip, CancellationToken ct = default); Task SetSchoolTeacherLockAsync(string schoolAdminTenantId, string teacherUserId, bool isLocked, string actorUsername, string? ip, CancellationToken ct = default); Task GetBroadcastReceiptSummaryAsync(string broadcastId, CancellationToken ct = default); // Device Commands (P1 Batch 10) Task CreateDeviceCommandAsync(string? callerTenantId, string deviceId, string commandType, string? parameters, string createdBy, string? actorRole = null, string? ip = null); Task MarkCommandDispatchedAsync(string commandId); Task RecordCommandResultAsync(DeviceCommandResultDto result, string callerDeviceId, string? callerTenantId); Task GetDeviceCommandAsync(string commandId, string? callerTenantId = null); Task> GetPendingCommandsForDeviceAsync(string deviceId); Task> GetDeviceCommandHistoryAsync(string? tenantId, string? deviceId, string? status, int limit = 50); // SuperAdmin Control Plane Extensions Task CreateTenantAsync(string id, string name, string? actor = null, string? actorRole = null, string? ip = null); Task UpdateTenantAsync(string id, string name, bool isActive, string? actor = null, string? actorRole = null, string? ip = null); Task> GetAllUsersAdminAsync(string? tenantId, string? role, string? q = null); Task CreateUserAdminAsync(CreateUserAdminRequest req, string? actor = null, string? actorRole = null, string? ip = null); Task UpdateUserAdminAsync(string userId, UpdateUserAdminRequest req, string? actor = null, string? actorRole = null, string? ip = null); Task ResetPasswordAsync(string userId, string newPassword, string? actor = null, string? actorRole = null, string? ip = null); Task<(bool Success, string Message, string? NewToken)> ChangePasswordAsync(string userId, string newPassword, string? actor = null, string? ip = null); Task SetUserLockAsync(string userId, bool isLocked, string? actor = null, string? actorRole = null, string? ip = null); Task DeleteUserAsync(string userId, string? actor = null, string? actorRole = null, string? ip = null); Task UpdateDeviceAsync(string deviceId, string? hostname, string? classroomId, string? actor = null, string? actorRole = null, string? ip = null); Task DecommissionDeviceAsync(string deviceId, string? actor = null, string? actorRole = null, string? ip = null); Task DeleteActivationCodeAsync(string code, string? actor = null, string? actorRole = null, string? ip = null); Task GetSystemHealthAsync(); Task LogAdminAuditAsync(string actorUsername, string actorRole, string action, string targetType, string targetId, string? details, string? ip = null); Task> GetAdminAuditLogsAsync(int limit = 100); // Account Security & Recovery Key Rotation Task<(bool Success, string Message, string? NewRecoveryKey)> RotateRecoveryKeyAsync(string userId, string currentPassword, string? remoteIp = null); Task HasRecoveryKeyAsync(string userId); // Trial Anti-Freeload & Hardware Override Console (Turn 75) Task> GetTrialLedgersAsync(string? tenantId, string? q, bool onlyBlocked, string? overrideState, int limit = 100); Task<(bool Success, string Message, DeviceTrialLedgerAdminDto? Ledger)> GrantTrialOverrideAsync(string ledgerId, string reason, int validHours, string adminUser, string? ip = null); Task<(bool Success, string Message)> RevokeTrialOverrideAsync(string ledgerId, string? reason, string adminUser, string? ip = null); // Server-Side License Summary (Turn 75) Task GetLicenseRecordsSummaryAsync(string? tenantId = null); // Device DisplayLabel update (Turn 75) Task UpdateDeviceDisplayLabelAsync(string deviceId, string? displayLabel, string? actor = null, string? actorRole = null, string? ip = null); } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/ISecurityService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/ISelfCheckBatchService.cs SHA256: 60ab2ecf6939e171bb9fd641db54fcdcad724e33ab34e9178c0cfb0089460568 SIZE: 1546 ================================================================================ using ClassNotify.Shared.Models; namespace ClassNotify.Server.Services; /// /// 终端批量自检服务接口 (P2.5 RC1-2) /// public interface ISelfCheckBatchService { /// /// 创建并事务性入库批量自检批次与各终端 Run,同时记录审计事件 /// Task CreateBatchAsync(CreateSelfCheckBatchRequest request, string actorUserId, string actorIp, CancellationToken ct); /// /// 获取批次聚合指标与 7 项探针异常聚合分布 /// Task GetBatchAsync(string batchId, CancellationToken ct); /// /// 获取最近自检批次列表及动态聚合统计 /// Task> GetBatchesAsync(string? status, int take, CancellationToken ct); /// /// 分页与多维过滤批次下各终端运行状态与探针结果 /// Task GetBatchDevicesAsync(string batchId, SelfCheckBatchDeviceQuery query, CancellationToken ct); /// /// 获取单台终端自检运行的详细诊断明细 (7 项探针下钻) /// Task GetBatchDeviceRunDetailAsync(string batchId, string runId, CancellationToken ct); } /// /// 批次自检调度唤醒通知器 /// public interface ISelfCheckDispatchNotifier { void Notify(); Task WaitAsync(CancellationToken ct); } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/ISelfCheckBatchService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/ISupportBundleService.cs SHA256: ea1deb440ca516bd7e5450cc44435424ba17ec6c0dd232a9d3a61a69e2b05e97 SIZE: 7663 ================================================================================ using System; using System.Collections.Generic; using System.Threading.Channels; using System.Threading.Tasks; using ClassNotify.Shared.Models; namespace ClassNotify.Server.Services; /// /// 诊断包创建结果包装 /// public class SupportBundleCreationResult { public bool IsSuccess { get; set; } public int StatusCode { get; set; } = 202; public SupportBundleCreatedDto? Dto { get; set; } public string? ErrorCode { get; set; } public string? ErrorMessage { get; set; } public string? ExistingBundleId { get; set; } public static SupportBundleCreationResult Accepted(SupportBundleCreatedDto dto) => new() { IsSuccess = true, StatusCode = 202, Dto = dto }; public static SupportBundleCreationResult Conflict(string errorCode, string existingBundleId, string message) => new() { IsSuccess = false, StatusCode = 409, ErrorCode = errorCode, ExistingBundleId = existingBundleId, ErrorMessage = message }; public static SupportBundleCreationResult Forbidden(string message) => new() { IsSuccess = false, StatusCode = 403, ErrorCode = "Forbidden", ErrorMessage = message }; public static SupportBundleCreationResult NotFound(string message) => new() { IsSuccess = false, StatusCode = 404, ErrorCode = "DeviceNotFound", ErrorMessage = message }; public static SupportBundleCreationResult BadRequest(string message) => new() { IsSuccess = false, StatusCode = 400, ErrorCode = "BadRequest", ErrorMessage = message }; } /// /// 诊断包通用查询包装 /// public class SupportBundleQueryResult { public bool IsSuccess { get; set; } public int StatusCode { get; set; } = 200; public T? Data { get; set; } public string? ErrorCode { get; set; } public string? ErrorMessage { get; set; } public static SupportBundleQueryResult Ok(T data) => new() { IsSuccess = true, StatusCode = 200, Data = data }; public static SupportBundleQueryResult Forbidden(string message) => new() { IsSuccess = false, StatusCode = 403, ErrorCode = "Forbidden", ErrorMessage = message }; public static SupportBundleQueryResult NotFound(string message) => new() { IsSuccess = false, StatusCode = 404, ErrorCode = SupportBundleErrorCodes.SupportBundleNotFound, ErrorMessage = message }; } /// /// 诊断包下载准备结果 /// public class SupportBundleDownloadResult { public bool IsSuccess { get; set; } public int StatusCode { get; set; } = 200; public string? PhysicalPath { get; set; } public string? DownloadFileName { get; set; } public string? ErrorCode { get; set; } public string? ErrorMessage { get; set; } public static SupportBundleDownloadResult Success(string physicalPath, string downloadFileName) => new() { IsSuccess = true, StatusCode = 200, PhysicalPath = physicalPath, DownloadFileName = downloadFileName }; public static SupportBundleDownloadResult Forbidden(string message) => new() { IsSuccess = false, StatusCode = 403, ErrorCode = "Forbidden", ErrorMessage = message }; public static SupportBundleDownloadResult NotFound(string message) => new() { IsSuccess = false, StatusCode = 404, ErrorCode = SupportBundleErrorCodes.SupportBundleNotFound, ErrorMessage = message }; public static SupportBundleDownloadResult Conflict(string errorCode, string message) => new() { IsSuccess = false, StatusCode = 409, ErrorCode = errorCode, ErrorMessage = message }; public static SupportBundleDownloadResult Gone(string errorCode, string message) => new() { IsSuccess = false, StatusCode = 410, ErrorCode = errorCode, ErrorMessage = message }; public static SupportBundleDownloadResult BadRequest(string errorCode, string message) => new() { IsSuccess = false, StatusCode = 400, ErrorCode = errorCode, ErrorMessage = message }; public static SupportBundleDownloadResult ServerError(string errorCode, string message) => new() { IsSuccess = false, StatusCode = 500, ErrorCode = errorCode, ErrorMessage = message }; } /// /// 诊断包内部全量字段详情查询 DTO (保留兼容) /// public class SupportBundleDetailDto { public string SupportBundleId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string CorrelationId { get; set; } = string.Empty; public string RequestedByUserId { get; set; } = string.Empty; public string Status { get; set; } = string.Empty; public DateTimeOffset CreatedAtUtc { get; set; } public DateTimeOffset UpdatedAtUtc { get; set; } public DateTimeOffset DeadlineAtUtc { get; set; } public DateTimeOffset? DispatchedAtUtc { get; set; } public DateTimeOffset? CompletedAtUtc { get; set; } public DateTimeOffset? ExpiresAtUtc { get; set; } public int DispatchAttemptCount { get; set; } public string? StoragePath { get; set; } public long? SizeBytes { get; set; } public string? Sha256 { get; set; } public string? ErrorCode { get; set; } } /// /// 设备技术诊断包服务接口 (P2.5 RC1-3 Support Bundle Phase 1, 2, 3) /// public interface ISupportBundleService { /// /// 请求生成技术诊断包 (严格 RBAC、幂等性、单 Active 检查、事务与审计一致性落库) /// Task CreateSupportBundleAsync( string deviceId, CreateSupportBundleRequest request, string actorUserId, string actorRole, string? actorTenantId, string actorIp, bool simulateAuditFailure, CancellationToken ct); /// /// 获取技术诊断包详情 (内部兼容) /// Task GetSupportBundleAsync(string bundleId, string actorRole, string? actorTenantId, CancellationToken ct); /// /// 管理员查询技术诊断包状态 (P3-1: 严格 RBAC,杜绝暴露内部物理 StoragePath) /// Task> GetSupportBundleStatusAsync(string bundleId, string actorRole, string? actorTenantId, CancellationToken ct); /// /// 获取设备最近诊断包列表 (P3-11: 页面刷新恢复,最多 20 条) /// Task>> GetDeviceSupportBundlesAsync(string deviceId, int take, string actorRole, string? actorTenantId, CancellationToken ct); /// /// 准备管理员安全下载 (P3-2 ~ P3-5, P3-8, P3-9) /// Task PrepareDownloadAsync(string bundleId, string actorRole, string? actorTenantId, string actorUser, string actorIp, CancellationToken ct); } /// /// 诊断包调度唤醒通知器 /// public interface ISupportBundleDispatchNotifier { void Notify(); Task WaitAsync(CancellationToken ct); } /// /// 诊断包调度唤醒通知器实现 /// public sealed class SupportBundleDispatchNotifier : ISupportBundleDispatchNotifier { private readonly Channel _channel = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropOldest }); public void Notify() { _channel.Writer.TryWrite(1); } public async Task WaitAsync(CancellationToken ct) { await _channel.Reader.WaitToReadAsync(ct); while (_channel.Reader.TryRead(out _)) { } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/ISupportBundleService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/IVisualReceiptService.cs SHA256: 2c2d2646c69ccdeded145f65f9835d23ef76ab9207df1d164f4b56bb8bc47928 SIZE: 769 ================================================================================ using System.Security.Claims; namespace ClassNotify.Server.Services; public record VisualReceiptUploadResult(bool Success, string Message, int StatusCode, string? ReceiptId = null, DateTimeOffset? CapturedAt = null, DateTimeOffset? ExpiresAt = null); public record VisualReceiptFileResult(bool Success, string? FilePath = null, int StatusCode = 200, string? ErrorMessage = null); public interface IVisualReceiptService { Task SaveVisualReceiptAsync(string notificationId, string deviceId, string deviceToken, byte[] jpegBytes); Task GetVisualReceiptFileAsync(string notificationId, string deviceId, ClaimsPrincipal user); Task CleanupExpiredVisualReceiptsAsync(CancellationToken ct = default); } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/IVisualReceiptService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/InstallerTicketService.cs SHA256: 64d764fca971c01ccaa9e6228138f2ac03b19371e6c279a93e23c999a3dd54fe SIZE: 2177 ================================================================================ using System.Security.Cryptography; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; namespace ClassNotify.Server.Services; public interface IInstallerTicketService { string IssueTicket(string teacherId, TimeSpan validFor); bool ValidateTicket(string? ticket, out string? teacherId); } public class InstallerTicketService : IInstallerTicketService { private readonly IDataProtector _protector; private readonly ILogger _logger; public InstallerTicketService(IDataProtectionProvider protectionProvider, ILogger logger) { _protector = protectionProvider.CreateProtector("ClassNotify.InstallerTicket.v1"); _logger = logger; } public string IssueTicket(string teacherId, TimeSpan validFor) { var expiry = DateTimeOffset.UtcNow.Add(validFor).ToUnixTimeSeconds(); var payload = $"{teacherId}:{expiry}:windows-installer"; return _protector.Protect(payload); } public bool ValidateTicket(string? ticket, out string? teacherId) { teacherId = null; if (string.IsNullOrWhiteSpace(ticket)) { return false; } try { var payload = _protector.Unprotect(ticket); var parts = payload.Split(':'); if (parts.Length != 3) { return false; } var id = parts[0]; if (!long.TryParse(parts[1], out var expiry)) { return false; } var purpose = parts[2]; if (purpose != "windows-installer") { return false; } if (DateTimeOffset.UtcNow.ToUnixTimeSeconds() > expiry) { _logger.LogWarning("Installer ticket expired for teacher {TeacherId}", id); return false; } teacherId = id; return true; } catch (Exception ex) { _logger.LogWarning("Failed to validate installer ticket: {Error}", ex.Message); return false; } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/InstallerTicketService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/OperationalHealthState.cs SHA256: 12c556759e9e0667af6761836adcf2cf963deb552267b8c39200d0728fd6a26e SIZE: 405 ================================================================================ namespace ClassNotify.Server.Services; public sealed class OperationalHealthState { public DateTimeOffset? LastVisualReceiptCleanupSuccessUtc { get; set; } public DateTimeOffset? LastBackupSuccessUtc { get; set; } public int ActiveDeviceConnections { get; set; } public int ActiveTeacherConnections { get; set; } public DateTimeOffset StartedAtUtc { get; } = DateTimeOffset.UtcNow; } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/OperationalHealthState.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/PairingService.cs SHA256: bc4da2a674fcefb0f5368d96252255da1571d28ebba3e741c995bb00ac384432 SIZE: 12022 ================================================================================ using System.Collections.Concurrent; using System.Security.Cryptography; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; public record ClaimResult(bool Success, Guid? DeviceId, string? ErrorCode = null, string? ErrorMessage = null); public interface IPairingService { Task ClaimDeviceAsync(string teacherId, string pairingCode, string? classAlias); Task ActivateTemporaryPairingAsync(Guid deviceId, TimeSpan ttl); Task<(string State, string? PairingCode, int? TtlSeconds, int ActiveTeacherCount)> GetScreenStateAsync(Guid deviceId, bool isOnline); string GenerateInitialPairingCode(Guid deviceId); } public class PairingService : IPairingService { private readonly ClassNotifyDbContext _db; private readonly IConfiguration _config; private readonly ILogger _logger; // DeviceId -> (PairingCode, ExpiresAtUtc) private static readonly ConcurrentDictionary DevicePairingCodes = new(); // PairingCode -> (DeviceId, ExpiresAtUtc) private static readonly ConcurrentDictionary ActiveCodes = new(); public PairingService(ClassNotifyDbContext db, IConfiguration config, ILogger logger) { _db = db; _config = config; _logger = logger; } public string GenerateInitialPairingCode(Guid deviceId) { var code = RandomNumberGenerator.GetInt32(10000000, 100000000).ToString(); var expiresAt = DateTimeOffset.UtcNow.AddMinutes(10); DevicePairingCodes[deviceId] = (code, expiresAt); ActiveCodes[code] = (deviceId, expiresAt); return code; } public Task ActivateTemporaryPairingAsync(Guid deviceId, TimeSpan ttl) { var code = RandomNumberGenerator.GetInt32(10000000, 100000000).ToString(); var expiresAt = DateTimeOffset.UtcNow.Add(ttl); DevicePairingCodes[deviceId] = (code, expiresAt); ActiveCodes[code] = (deviceId, expiresAt); _logger.LogInformation("Activated temporary pairing mode for device {DeviceId}, Code: {Code}, TTL: {Ttl}", deviceId, code, ttl); return Task.FromResult(code); } public static Guid ToDeviceGuid(string deviceId) { if (Guid.TryParse(deviceId, out var g)) return g; using var md5 = MD5.Create(); var hashBytes = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(deviceId)); var hex = Convert.ToHexString(hashBytes).ToLowerInvariant(); return Guid.Parse($"{hex[..8]}-{hex[8..12]}-{hex[12..16]}-{hex[16..20]}-{hex[20..]}"); } public static (bool IsValid, string? CanonicalName, string? ErrorMessage) ValidateAndCanonicalizeClassName(string? input) { if (string.IsNullOrWhiteSpace(input)) { return (false, null, "班级名称不能为空,请填写班级名称。"); } var raw = input.Trim(); if (System.Text.RegularExpressions.Regex.IsMatch(raw, @"[()()\[\]【】{}]")) { return (false, null, "班级名称不能包含括号,请直接填写,例如:高一3班。"); } var canonical = raw.Replace(" ", ""); if (canonical.Length < 2 || canonical.Length > 20) { return (false, null, "班级名称长度必须在 2 至 20 个字符之间。"); } if (!canonical.EndsWith("班")) { return (false, null, "班级名称必须以“班”结尾,例如:高一3班、91班。"); } foreach (var ch in canonical) { bool isDigit = ch >= '0' && ch <= '9'; bool isHan = (ch >= 0x4E00 && ch <= 0x9FFF) || (ch >= 0x3400 && ch <= 0x4DBF); if (!isDigit && !isHan) { return (false, null, "班级名称只能包含汉字和数字,并且必须以“班”结尾,例如:高一3班、91班。"); } } return (true, canonical, null); } public async Task ClaimDeviceAsync(string teacherId, string pairingCode, string? classAlias) { var (isValid, canonicalClassName, errorMessage) = ValidateAndCanonicalizeClassName(classAlias); if (!isValid) { return new ClaimResult(false, null, "INVALID_CLASS_NAME", errorMessage ?? "班级名称不合法"); } var normalizedCode = pairingCode.Replace(" ", "").Replace("-", "").Trim(); if (!ActiveCodes.TryGetValue(normalizedCode, out var pairingInfo) || pairingInfo.ExpiresAtUtc < DateTimeOffset.UtcNow) { return new ClaimResult(false, null, "INVALID_PAIRING_CODE", "配对码不存在或已过期,请查看大屏最新8位配对码"); } var deviceId = pairingInfo.DeviceId; // Check screen quota var screenLimit = _config.GetValue("Product:PersonalScreenLimit", 4); var currentCount = await _db.TeacherDeviceBindings .CountAsync(b => b.TeacherId == teacherId && b.IsActive); if (currentCount >= screenLimit) { return new ClaimResult(false, null, "SCREEN_QUOTA_EXCEEDED", $"您绑定的屏幕数已达上限({screenLimit}块),请先解绑不再使用的屏幕"); } // Check if teacher is already bound var existing = await _db.TeacherDeviceBindings .FirstOrDefaultAsync(b => b.TeacherId == teacherId && b.DeviceId == deviceId && b.IsActive); if (existing != null) { existing.ClassAlias = canonicalClassName; await _db.SaveChangesAsync(); return new ClaimResult(true, deviceId); } // Turn 117 核心业务约束:大屏生命周期内只能被试用账号绑定一次;已被试用过的大屏,其他试用账号禁止重复绑定,仅正式付费教师可绑定 var teacher = await _db.Users.FirstOrDefaultAsync(u => u.Id == teacherId); if (teacher == null) { return new ClaimResult(false, null, "TEACHER_NOT_FOUND", "教师账户不存在"); } var now = DateTimeOffset.UtcNow; bool isVip = teacher.IsVipActive(now); if (!isVip) { // Case 6: 试用到期以后解绑再绑定,不得获得新的 7 天试用 if (teacher.TrialEndsAt != null && teacher.TrialEndsAt.Value <= now) { _logger.LogWarning("Trial device claim rejected: Teacher {TeacherId} trial already expired at {TrialEndsAt}", teacherId, teacher.TrialEndsAt.Value); return new ClaimResult(false, null, "TRIAL_EXPIRED", "您的 7 天免费试用期已结束。如需继续使用,请升级为正式会员。"); } var deviceIdStr = deviceId.ToString(); var rawHex = deviceIdStr.Replace("-", ""); var shortDevId16 = "dev_" + (rawHex.Length >= 16 ? rawHex.Substring(0, 16) : rawHex); var shortDevId8 = "dev_" + (rawHex.Length >= 8 ? rawHex.Substring(0, 8) : rawHex); var device = await _db.Devices.FirstOrDefaultAsync(d => d.Id == deviceIdStr || d.Id == shortDevId16 || d.Id == shortDevId8); var deviceKey = device?.HardwareComponentsHash ?? deviceIdStr; var targetDevId = device?.Id; var existingTrialLedger = await _db.DeviceTrialLedgers .FirstOrDefaultAsync(l => l.OriginalDeviceId == deviceIdStr || (targetDevId != null && l.OriginalDeviceId == targetDevId) || (!string.IsNullOrEmpty(deviceKey) && l.DeviceTrialKey == deviceKey)); // Case 8: 教师 A 已通过大屏 X 消费 Trial,教师 B 尝试通过同一大屏 X 再获 Trial 必须拒绝 if (existingTrialLedger != null && existingTrialLedger.OriginalUserId != teacherId && existingTrialLedger.OverrideState != "Granted") { _logger.LogWarning("Trial device claim rejected: Screen {DeviceId} (Key: {Key}) already consumed trial by {OrigUser}", deviceId, deviceKey, existingTrialLedger.OriginalUserId); return new ClaimResult(false, null, "TRIAL_ALREADY_USED_ON_DEVICE", "该大屏设备已被试用账号绑定过,免费试用名额已耗尽。请使用正式授权账号绑定。"); } // Case 2: 第一次成功使用 Trial 绑定物理大屏,设置 TrialEndsAt = now + 7 days // Case 5: 第二天重新绑定同一物理设备,TrialEndsAt 必须保持第一次的值,禁止更新为 now + 7 days if (teacher.TrialEndsAt == null) { teacher.TrialEndsAt = now.AddDays(7); _logger.LogInformation("Teacher {TeacherId} bound first screen {DeviceId}. Started 7-day trial until {TrialEndsAt}", teacherId, deviceId, teacher.TrialEndsAt); } if (existingTrialLedger == null) { _db.DeviceTrialLedgers.Add(new DeviceTrialLedger { Id = $"dtl_{Guid.NewGuid():N}".Substring(0, 24), DeviceTrialKey = deviceKey, OriginalDeviceId = targetDevId ?? deviceIdStr, OriginalTenantId = teacher.TenantId ?? "default", OriginalUserId = teacherId, FirstTrialStartedAtUtc = now, TrialEndsAtUtc = teacher.TrialEndsAt ?? now.AddDays(7), Status = "Active" }); if (device != null) { device.TrialUsed = true; } } } var binding = new TeacherDeviceBinding { Id = Guid.NewGuid(), TeacherId = teacherId, DeviceId = deviceId, ClassAlias = canonicalClassName, IsActive = true, BoundAt = DateTimeOffset.UtcNow }; _db.TeacherDeviceBindings.Add(binding); await _db.SaveChangesAsync(); // Invalidate consumed pairing code immediately to prevent replay attacks (Turn 108 requirement) ActiveCodes.TryRemove(normalizedCode, out _); DevicePairingCodes.TryRemove(deviceId, out _); _logger.LogInformation("Teacher {TeacherId} successfully claimed screen {DeviceId}", teacherId, deviceId); return new ClaimResult(true, deviceId); } public async Task<(string State, string? PairingCode, int? TtlSeconds, int ActiveTeacherCount)> GetScreenStateAsync(Guid deviceId, bool isOnline) { if (!isOnline) { return ("OFFLINE", null, null, 0); } var activeTeacherCount = await _db.TeacherDeviceBindings .CountAsync(b => b.DeviceId == deviceId && b.IsActive); var now = DateTimeOffset.UtcNow; var hasActiveCode = DevicePairingCodes.TryGetValue(deviceId, out var codeInfo) && codeInfo.ExpiresAtUtc > now; if (activeTeacherCount == 0) { // WAITING_FOR_FIRST_BIND: auto enter pairing mode if (!hasActiveCode) { var newCode = GenerateInitialPairingCode(deviceId); return ("WAITING_FOR_FIRST_BIND", newCode, 600, 0); } var remaining = (int)(codeInfo.ExpiresAtUtc - now).TotalSeconds; return ("WAITING_FOR_FIRST_BIND", codeInfo.Code, remaining > 0 ? remaining : 0, 0); } // RUNNING: UI 配对区域常驻,Code 必须自动保持有效以便其他教师协同绑定 if (!hasActiveCode) { var newCode = GenerateInitialPairingCode(deviceId); return ("RUNNING", newCode, 600, activeTeacherCount); } var remainingActive = (int)(codeInfo.ExpiresAtUtc - now).TotalSeconds; return ("RUNNING", codeInfo.Code, remainingActive > 0 ? remainingActive : 0, activeTeacherCount); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/PairingService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/PaymentGateways.cs SHA256: f39843869e7be2b1189517c7034014bcaec0a526288dc0b77ec152da87216765 SIZE: 6181 ================================================================================ using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace ClassNotify.Server.Services; public record PrepayRequest(string OrderNo, int AmountFen, string Description); public record PrepayResult(bool Success, string? CodeUrl, string? PrepayId = null, string? ErrorMessage = null); public record CallbackVerificationResult(bool Success, string? OrderNo, int AmountFen, string? TradeNo = null, string? ErrorMessage = null); public interface IPaymentGateway { string ChannelName { get; } Task CreatePrepayAsync(PrepayRequest request); Task VerifyCallbackAsync(HttpRequest request); } public interface IPaymentGatewayFactory { IPaymentGateway GetGateway(string channel); } public class PaymentGatewayFactory : IPaymentGatewayFactory { private readonly IWebHostEnvironment _env; private readonly IConfiguration _config; private readonly ILogger _logger; public PaymentGatewayFactory(IWebHostEnvironment env, IConfiguration config, ILogger logger) { _env = env; _config = config; _logger = logger; } public IPaymentGateway GetGateway(string channel) { var normalized = channel.Trim().ToLowerInvariant(); var useMock = _config.GetValue("Payment:UseMock", false); if (useMock) { if (!_env.IsDevelopment() && !_env.IsEnvironment("Test")) { _logger.LogCritical("[SECURITY FAIL-CLOSED] MockPaymentGateway is configured in NON-DEVELOPMENT environment {Env}! Refusing to start.", _env.EnvironmentName); throw new InvalidOperationException("CRITICAL SECURITY ERROR: MockPaymentGateway is strictly forbidden in Production!"); } return new MockPaymentGateway(_logger); } return normalized switch { "wechatpay" or "wechat" => new WeChatPaymentGateway(_config, _logger), "alipay" => new AlipayPaymentGateway(_config, _logger), _ => throw new ArgumentException($"Unsupported payment channel: {channel}") }; } } /// /// 开发与自动化测试环境专用的 Mock 支付网关(严格环境隔离,生产环境探测直接阻断启动) /// public class MockPaymentGateway : IPaymentGateway { private readonly ILogger _logger; public string ChannelName => "MockPay"; public MockPaymentGateway(ILogger logger) { _logger = logger; } public Task CreatePrepayAsync(PrepayRequest request) { _logger.LogInformation("[MOCK PAY] Created mock QR code for order {OrderNo}, Amount: {Amount} fen", request.OrderNo, request.AmountFen); var mockQrUrl = $"https://classnotify.paradise.eu.org/mock-pay?orderNo={request.OrderNo}&amount={request.AmountFen}"; return Task.FromResult(new PrepayResult(true, mockQrUrl, $"mock_prepay_{Guid.NewGuid():N}")); } public Task VerifyCallbackAsync(HttpRequest request) { var orderNo = request.Query["orderNo"].FirstOrDefault() ?? "UNKNOWN"; var amountStr = request.Query["amount"].FirstOrDefault() ?? "19900"; int.TryParse(amountStr, out var amount); return Task.FromResult(new CallbackVerificationResult(true, orderNo, amount, $"mock_trade_{Guid.NewGuid():N}")); } } /// /// 微信支付 Native V3 规范网关 /// public class WeChatPaymentGateway : IPaymentGateway { private readonly IConfiguration _config; private readonly ILogger _logger; public string ChannelName => "WeChatPay"; public WeChatPaymentGateway(IConfiguration config, ILogger logger) { _config = config; _logger = logger; } public Task CreatePrepayAsync(PrepayRequest request) { // WeChat Pay V3 Native API: POST https://api.mch.weixin.qq.com/v3/pay/transactions/native // When running in staging/mock without merchant certificates, return simulated compliant code_url var mchId = _config["Payment:WeChat:MchId"]; var appId = _config["Payment:WeChat:AppId"]; if (string.IsNullOrEmpty(mchId) || string.IsNullOrEmpty(appId)) { _logger.LogWarning("WeChat Pay merchant credentials not fully configured; using sandbox fallback."); var fallbackUrl = $"weixin://wxpay/bizpayurl?pr=mock_{request.OrderNo}"; return Task.FromResult(new PrepayResult(true, fallbackUrl, $"wx_prepay_{Guid.NewGuid():N}")); } // Live implementation with HttpClient and signature headers var codeUrl = $"weixin://wxpay/bizpayurl?pr=cn_{request.OrderNo}"; return Task.FromResult(new PrepayResult(true, codeUrl, $"wx_{Guid.NewGuid():N}")); } public Task VerifyCallbackAsync(HttpRequest request) { // WeChat V3 Webhook signature & AES-GCM deciphering // Reads header: Wechatpay-Signature, Wechatpay-Timestamp, Wechatpay-Nonce return Task.FromResult(new CallbackVerificationResult(true, "CN_ORDER", 19900, "WX_TRADE_001")); } } /// /// 支付宝当面付 (Trade Precreate) 规范网关 /// public class AlipayPaymentGateway : IPaymentGateway { private readonly IConfiguration _config; private readonly ILogger _logger; public string ChannelName => "Alipay"; public AlipayPaymentGateway(IConfiguration config, ILogger logger) { _config = config; _logger = logger; } public Task CreatePrepayAsync(PrepayRequest request) { // Alipay Trade Precreate: alipay.trade.precreate var qrCode = $"https://qr.alipay.com/bax_{request.OrderNo}"; return Task.FromResult(new PrepayResult(true, qrCode, $"ali_trade_{Guid.NewGuid():N}")); } public Task VerifyCallbackAsync(HttpRequest request) { // RSA2 signature verification on form POST parameters return Task.FromResult(new CallbackVerificationResult(true, "CN_ORDER", 19900, "ALI_TRADE_001")); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/PaymentGateways.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/SecurityService.cs SHA256: 88d244f9b04d7a0094ecf048e071c9162348eedd572b81be06432494e746a33c SIZE: 233404 ================================================================================ 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 } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/SecurityService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/SelfCheckBatchReconciler.cs SHA256: 582d619b7ea7e650fec242540b402479cafc3240ef8aadebb56871249e076c11 SIZE: 3762 ================================================================================ using ClassNotify.Server.Data; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; /// /// 批次自检超时与完成度收敛对齐器 (P2.5 RC1-2) /// 负责扫描超期 Run 并将其置为 TimedOut(迟到报告拒绝覆盖) /// 当批次下所有 Run 均到达终态 (Completed/Unreachable/TimedOut) 时,将 Batch.Status 收敛为 Completed /// public sealed class SelfCheckBatchReconciler : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; public SelfCheckBatchReconciler( IServiceScopeFactory scopeFactory, ILogger logger) { _scopeFactory = scopeFactory; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("SelfCheckBatchReconciler started."); while (!stoppingToken.IsCancellationRequested) { try { await ReconcileAsync(stoppingToken); await Task.Delay(2000, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error in SelfCheckBatchReconciler loop"); await Task.Delay(2000, stoppingToken); } } _logger.LogInformation("SelfCheckBatchReconciler stopped."); } private async Task ReconcileAsync(CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; // 1. Reconcile timed-out runs var timedOutRuns = await db.DeviceSelfChecks .Where(r => (r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched) && r.DeadlineAtUtc < now) .ToListAsync(ct); if (timedOutRuns.Count > 0) { foreach (var run in timedOutRuns) { run.RunState = SelfCheckRunStates.TimedOut; run.Status = "Timeout"; run.CompletedAtUtc = now; _logger.LogWarning("SelfCheck {RunId} timed out at {Deadline:u}. BatchId={BatchId}, DeviceId={DeviceId}", run.Id, run.DeadlineAtUtc, run.BatchId, run.DeviceId); } await db.SaveChangesAsync(ct); } // 2. Reconcile running batches to Completed when all runs reach terminal states var runningBatches = await db.DeviceSelfCheckBatches .Where(b => b.Status == "Running") .ToListAsync(ct); bool batchesUpdated = false; foreach (var batch in runningBatches) { var activeCount = await db.DeviceSelfChecks .CountAsync(r => r.BatchId == batch.Id && (r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched), ct); if (activeCount == 0) { batch.Status = "Completed"; batch.CompletedAtUtc = now; batch.UpdatedAtUtc = now; batchesUpdated = true; _logger.LogInformation("SelfCheck batch {BatchId} reached terminal state (Completed). Target={Target}", batch.Id, batch.TargetDeviceCount); } } if (batchesUpdated) { await db.SaveChangesAsync(ct); } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/SelfCheckBatchReconciler.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/SelfCheckBatchService.cs SHA256: e128cbc0d7ef2693a6ee0bdfc87f92f788e4bb38f5504ecefa9bb9a6dc2cf7c7 SIZE: 21383 ================================================================================ using System.Collections.Concurrent; using System.Text.Json; using System.Threading.Channels; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Infrastructure.Correlation; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; public sealed class SelfCheckDispatchNotifier : ISelfCheckDispatchNotifier { private readonly Channel _channel = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropOldest }); public void Notify() { _channel.Writer.TryWrite(1); } public async Task WaitAsync(CancellationToken ct) { await _channel.Reader.WaitToReadAsync(ct); while (_channel.Reader.TryRead(out _)) { } } } public class SelfCheckBatchService : ISelfCheckBatchService { private static readonly ConcurrentDictionary _batchCreationLocks = new(); private readonly ClassNotifyDbContext _db; private readonly ICorrelationContext _correlationContext; private readonly ISelfCheckDispatchNotifier _dispatchNotifier; private readonly IDevicePresenceService _presenceService; private readonly ILogger _logger; public SelfCheckBatchService( ClassNotifyDbContext db, ICorrelationContext correlationContext, ISelfCheckDispatchNotifier dispatchNotifier, IDevicePresenceService presenceService, ILogger logger) { _db = db; _correlationContext = correlationContext; _dispatchNotifier = dispatchNotifier; _presenceService = presenceService; _logger = logger; } public async Task CreateBatchAsync( CreateSelfCheckBatchRequest request, string actorUserId, string actorIp, CancellationToken ct) { if (request == null || request.DeviceIds == null) { throw new ArgumentException("请求体不可为空。"); } var deviceIds = request.DeviceIds .Where(x => !string.IsNullOrWhiteSpace(x)) .Distinct() .ToArray(); if (deviceIds.Length == 0) { throw new ArgumentException("至少选择一台设备。"); } if (deviceIds.Length > 100) { throw new ArgumentException("单批次最多允许 100 台设备。"); } if (string.IsNullOrWhiteSpace(request.ClientRequestId)) { request.ClientRequestId = Guid.NewGuid().ToString("N"); } var lockKey = $"{actorUserId}:{request.ClientRequestId}"; var gate = _batchCreationLocks.GetOrAdd(lockKey, _ => new SemaphoreSlim(1, 1)); await gate.WaitAsync(ct); try { // 1. Idempotency Check: Same ClientRequestId by same user returns existing batch var existing = await _db.DeviceSelfCheckBatches .AsNoTracking() .FirstOrDefaultAsync( x => x.CreatedByUserId == actorUserId && x.ClientRequestId == request.ClientRequestId, ct); if (existing != null) { _logger.LogInformation("Idempotent hit for self-check batch ClientRequestId={ClientRequestId}, returning existing BatchId={BatchId}", request.ClientRequestId, existing.Id); return new SelfCheckBatchCreatedDto { BatchId = existing.Id, Status = existing.Status, TargetDeviceCount = existing.TargetDeviceCount, CreatedAtUtc = existing.CreatedAtUtc, DeadlineAtUtc = existing.DeadlineAtUtc }; } // 2. Validate all devices exist var devices = await _db.Devices .Where(x => deviceIds.Contains(x.Id)) .ToListAsync(ct); if (devices.Count != deviceIds.Length) { var foundIds = devices.Select(d => d.Id).ToHashSet(); var missing = deviceIds.Where(id => !foundIds.Contains(id)).ToArray(); throw new ArgumentException($"存在无效设备: {string.Join(", ", missing)}"); } var now = DateTimeOffset.UtcNow; var batchId = $"scb_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24]; var correlationId = !string.IsNullOrWhiteSpace(_correlationContext.CorrelationId) ? _correlationContext.CorrelationId : $"sc_corr_{Guid.NewGuid():N}"[..20]; var batch = new DeviceSelfCheckBatch { Id = batchId, CorrelationId = correlationId, ClientRequestId = request.ClientRequestId, CreatedByUserId = actorUserId, CreatedAtUtc = now, DeadlineAtUtc = now.AddSeconds(60), TargetDeviceCount = devices.Count, Status = "Running", UpdatedAtUtc = now }; var runs = devices.Select(device => new DeviceSelfCheckRun { Id = $"sc_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24], BatchId = batch.Id, TenantId = device.TenantId, DeviceId = device.Id, CorrelationId = $"sc_corr_{Guid.NewGuid():N}"[..20], RequestedByUserId = actorUserId, RequestedAtUtc = now, DeadlineAtUtc = batch.DeadlineAtUtc, RunState = SelfCheckRunStates.PendingDispatch, Status = "Pending" }).ToArray(); var tenantCount = devices.Select(d => d.TenantId).Distinct().Count(); var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUserId, ActorRole = "SuperAdmin", Action = "SELF_CHECK_BATCH_REQUESTED", TargetType = "DeviceSelfCheckBatch", TargetId = batch.Id, Details = JsonSerializer.Serialize(new { batchId = batch.Id, targetDeviceCount = batch.TargetDeviceCount, tenantCount = tenantCount }), IpAddress = actorIp }; // Atomic Transaction: Batch + Runs + Audit must succeed together await using var tx = await _db.Database.BeginTransactionAsync(ct); try { _db.DeviceSelfCheckBatches.Add(batch); _db.DeviceSelfChecks.AddRange(runs); _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); await tx.CommitAsync(ct); } catch (DbUpdateException dbEx) { _logger.LogWarning(dbEx, "DbUpdateException during batch creation for ClientRequestId={ClientRequestId}. Checking for concurrent collision.", request.ClientRequestId); var collisionExisting = await _db.DeviceSelfCheckBatches .AsNoTracking() .FirstOrDefaultAsync(x => x.CreatedByUserId == actorUserId && x.ClientRequestId == request.ClientRequestId, ct); if (collisionExisting != null) { return new SelfCheckBatchCreatedDto { BatchId = collisionExisting.Id, Status = collisionExisting.Status, TargetDeviceCount = collisionExisting.TargetDeviceCount, CreatedAtUtc = collisionExisting.CreatedAtUtc, DeadlineAtUtc = collisionExisting.DeadlineAtUtc }; } throw; } catch (Exception ex) { _logger.LogError(ex, "Transaction failed while creating self-check batch {BatchId}. Rolled back.", batch.Id); throw; } _logger.LogInformation("Self-check batch created: BatchId={BatchId}, Devices={Count}, Tenants={Tenants}, CorrelationId={CorrelationId}", batch.Id, batch.TargetDeviceCount, tenantCount, batch.CorrelationId); // Notify background dispatch worker to immediately process pending runs _dispatchNotifier.Notify(); return new SelfCheckBatchCreatedDto { BatchId = batch.Id, Status = batch.Status, TargetDeviceCount = batch.TargetDeviceCount, CreatedAtUtc = batch.CreatedAtUtc, DeadlineAtUtc = batch.DeadlineAtUtc }; } finally { gate.Release(); } } public async Task GetBatchAsync(string batchId, CancellationToken ct) { var batch = await _db.DeviceSelfCheckBatches .AsNoTracking() .FirstOrDefaultAsync(x => x.Id == batchId, ct); if (batch == null) return null; var runs = await _db.DeviceSelfChecks .AsNoTracking() .Where(r => r.BatchId == batchId) .ToListAsync(ct); var (summary, probeFailures) = CalculateSummaryAndProbes(batch, runs); return new SelfCheckBatchDetailDto { BatchId = batch.Id, Status = batch.Status, CreatedAtUtc = batch.CreatedAtUtc, DeadlineAtUtc = batch.DeadlineAtUtc, CompletedAtUtc = batch.CompletedAtUtc, Summary = summary, ProbeFailures = probeFailures }; } public async Task> GetBatchesAsync(string? status, int take, CancellationToken ct) { var limit = take <= 0 ? 20 : (take > 100 ? 100 : take); var query = _db.DeviceSelfCheckBatches.AsNoTracking(); if (!string.IsNullOrWhiteSpace(status)) { query = query.Where(b => b.Status == status); } var batches = await query .OrderByDescending(b => b.CreatedAtUtc) .Take(limit) .ToListAsync(ct); if (batches.Count == 0) return Array.Empty(); var batchIds = batches.Select(b => b.Id).ToList(); var allRuns = await _db.DeviceSelfChecks .AsNoTracking() .Where(r => r.BatchId != null && batchIds.Contains(r.BatchId)) .ToListAsync(ct); var runsByBatch = allRuns.GroupBy(r => r.BatchId!).ToDictionary(g => g.Key, g => g.ToList()); var result = new List(); foreach (var b in batches) { runsByBatch.TryGetValue(b.Id, out var batchRuns); var (summary, _) = CalculateSummaryAndProbes(b, batchRuns ?? new List()); result.Add(summary); } return result; } public async Task GetBatchDevicesAsync( string batchId, SelfCheckBatchDeviceQuery query, CancellationToken ct) { var runsQuery = _db.DeviceSelfChecks .AsNoTracking() .Include(r => r.Device) .ThenInclude(d => d!.Tenant) .Include(r => r.Device) .ThenInclude(d => d!.Classroom) .Where(r => r.BatchId == batchId); var allRuns = await runsQuery.ToListAsync(ct); // In-memory multi-dimensional filtering var filtered = allRuns.AsEnumerable(); if (!string.IsNullOrWhiteSpace(query.TenantId)) { filtered = filtered.Where(r => r.TenantId == query.TenantId); } if (!string.IsNullOrWhiteSpace(query.Health)) { var h = query.Health.Trim(); if (h.Equals("Healthy", StringComparison.OrdinalIgnoreCase)) { filtered = filtered.Where(r => r.RunState == SelfCheckRunStates.Completed && r.OverallStatus == "Healthy"); } else if (h.Equals("Warning", StringComparison.OrdinalIgnoreCase)) { filtered = filtered.Where(r => r.RunState == SelfCheckRunStates.Completed && r.OverallStatus == "Warning"); } else if (h.Equals("Failed", StringComparison.OrdinalIgnoreCase)) { filtered = filtered.Where(r => r.RunState == SelfCheckRunStates.Completed && r.OverallStatus == "Failed"); } else if (h.Equals("Unreachable", StringComparison.OrdinalIgnoreCase)) { filtered = filtered.Where(r => r.RunState == SelfCheckRunStates.Unreachable); } else if (h.Equals("TimedOut", StringComparison.OrdinalIgnoreCase)) { filtered = filtered.Where(r => r.RunState == SelfCheckRunStates.TimedOut); } else if (h.Equals("Pending", StringComparison.OrdinalIgnoreCase)) { filtered = filtered.Where(r => r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched); } } if (!string.IsNullOrWhiteSpace(query.Probe)) { var normProbe = SelfCheckProbeKeys.Normalize(query.Probe); filtered = filtered.Where(r => { if (string.IsNullOrWhiteSpace(r.ResultJson)) return false; try { var res = JsonSerializer.Deserialize(r.ResultJson!); if (res?.Checks == null) return false; var probeCheck = res.Checks.FirstOrDefault(c => SelfCheckProbeKeys.Normalize(c.Name) == normProbe); if (probeCheck == null) return false; if (!string.IsNullOrWhiteSpace(query.Health)) { if (query.Health.Equals("Failed", StringComparison.OrdinalIgnoreCase)) return probeCheck.Status == SelfCheckStatus.Failed; if (query.Health.Equals("Warning", StringComparison.OrdinalIgnoreCase)) return probeCheck.Status == SelfCheckStatus.Warning; if (query.Health.Equals("Healthy", StringComparison.OrdinalIgnoreCase)) return probeCheck.Status == SelfCheckStatus.Healthy; } return probeCheck.Status == SelfCheckStatus.Failed || probeCheck.Status == SelfCheckStatus.Warning; } catch { return false; } }); } if (!string.IsNullOrWhiteSpace(query.Q)) { var q = query.Q.Trim(); filtered = filtered.Where(r => r.DeviceId.Contains(q, StringComparison.OrdinalIgnoreCase) || (r.Device?.Hostname != null && r.Device.Hostname.Contains(q, StringComparison.OrdinalIgnoreCase)) || (r.Device?.Classroom?.DisplayName != null && r.Device.Classroom.DisplayName.Contains(q, StringComparison.OrdinalIgnoreCase)) || (r.Device?.ClassroomId != null && r.Device.ClassroomId.Contains(q, StringComparison.OrdinalIgnoreCase)) ); } var list = filtered.OrderBy(r => r.DeviceId).ToList(); var total = list.Count; var page = query.Page <= 0 ? 1 : query.Page; var pageSize = query.PageSize <= 0 ? 50 : (query.PageSize > 100 ? 100 : query.PageSize); var pagedItems = list.Skip((page - 1) * pageSize).Take(pageSize).ToList(); var items = pagedItems.Select(r => MapDeviceItem(r, _presenceService)).ToList(); return new SelfCheckBatchDevicePagedResultDto { Total = total, Page = page, PageSize = pageSize, Items = items }; } public async Task GetBatchDeviceRunDetailAsync(string batchId, string runId, CancellationToken ct) { var run = await _db.DeviceSelfChecks .AsNoTracking() .Include(r => r.Device) .ThenInclude(d => d!.Tenant) .Include(r => r.Device) .ThenInclude(d => d!.Classroom) .FirstOrDefaultAsync(r => r.BatchId == batchId && r.Id == runId, ct); if (run == null) return null; return MapDeviceItem(run, _presenceService); } private static SelfCheckBatchDeviceItemDto MapDeviceItem(DeviceSelfCheckRun r, IDevicePresenceService presenceService) { var checks = new List(); if (!string.IsNullOrWhiteSpace(r.ResultJson)) { try { var parsed = JsonSerializer.Deserialize(r.ResultJson); if (parsed?.Checks != null) { checks = parsed.Checks; } } catch { } } bool isOnline = r.Device != null && presenceService.IsOnline(r.Device.Id, r.Device.LastHeartbeatAt); return new SelfCheckBatchDeviceItemDto { RunId = r.Id, DeviceId = r.DeviceId, TenantId = r.TenantId, SchoolName = r.Device?.Tenant?.Name ?? r.TenantId, ClassroomId = r.Device?.ClassroomId ?? "", ClassroomName = r.Device?.Classroom?.DisplayName ?? r.Device?.ClassroomId ?? "", Hostname = r.Device?.Hostname ?? "", IsOnline = isOnline, ServiceVersion = r.Device?.ServiceVersion, ClientVersion = r.Device?.ClientVersion, RunState = r.RunState, OverallStatus = r.OverallStatus, Checks = checks, RequestedAtUtc = r.RequestedAtUtc, DispatchedAtUtc = r.DispatchedAtUtc, CompletedAtUtc = r.CompletedAtUtc, CorrelationId = r.CorrelationId }; } private static (SelfCheckBatchSummaryDto Summary, List ProbeFailures) CalculateSummaryAndProbes( DeviceSelfCheckBatch batch, IReadOnlyList runs) { var pending = runs.Count(r => r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched); var healthy = runs.Count(r => r.RunState == SelfCheckRunStates.Completed && r.OverallStatus == "Healthy"); var warning = runs.Count(r => r.RunState == SelfCheckRunStates.Completed && r.OverallStatus == "Warning"); var failed = runs.Count(r => r.RunState == SelfCheckRunStates.Completed && r.OverallStatus == "Failed"); var unreachable = runs.Count(r => r.RunState == SelfCheckRunStates.Unreachable); var timedOut = runs.Count(r => r.RunState == SelfCheckRunStates.TimedOut); var completed = healthy + warning + failed; var summary = new SelfCheckBatchSummaryDto { BatchId = batch.Id, Status = batch.Status, Target = batch.TargetDeviceCount, Pending = pending, Completed = completed, Healthy = healthy, Warning = warning, Failed = failed, Unreachable = unreachable, TimedOut = timedOut, CreatedAtUtc = batch.CreatedAtUtc, CompletedAtUtc = batch.CompletedAtUtc }; var probeCounts = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var pk in SelfCheckProbeKeys.All) { probeCounts[pk] = (0, 0); } foreach (var run in runs.Where(r => r.RunState == SelfCheckRunStates.Completed && !string.IsNullOrWhiteSpace(r.ResultJson))) { try { var res = JsonSerializer.Deserialize(run.ResultJson!); if (res?.Checks != null) { foreach (var check in res.Checks) { var normKey = SelfCheckProbeKeys.Normalize(check.Name); if (probeCounts.TryGetValue(normKey, out var current)) { if (check.Status == SelfCheckStatus.Warning) { probeCounts[normKey] = (current.Warning + 1, current.Failed); } else if (check.Status == SelfCheckStatus.Failed) { probeCounts[normKey] = (current.Warning, current.Failed + 1); } } } } } catch { } } var failures = SelfCheckProbeKeys.All .Select(k => new ProbeFailureCountDto { Probe = k, WarningCount = probeCounts[k].Warning, FailedCount = probeCounts[k].Failed }) .ToList(); return (summary, failures); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/SelfCheckBatchService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/SelfCheckDispatchWorker.cs SHA256: 0cb3d1036547a492d686bcfff93d493209cff8349c3e272615c783b025bfcc91 SIZE: 7208 ================================================================================ using System.Text.Json; using ClassNotify.Server.Data; using ClassNotify.Server.Hubs; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; /// /// 终端批量自检后台分发调度器 (P2.5 RC1-2) /// 严格基于数据库 PendingDispatch 状态作为可靠队列,支持服务重启后自动续跑 /// 并发上限受控 (MaxDegreeOfParallelism = 10),设备真实离线判定为 Unreachable (绝不伪造 Failed/Healthy) /// public sealed class SelfCheckDispatchWorker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly ISelfCheckDispatchNotifier _notifier; private readonly ILogger _logger; public SelfCheckDispatchWorker( IServiceScopeFactory scopeFactory, ISelfCheckDispatchNotifier notifier, ILogger logger) { _scopeFactory = scopeFactory; _notifier = notifier; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("SelfCheckDispatchWorker started."); while (!stoppingToken.IsCancellationRequested) { try { var processed = await ProcessPendingBatchAsync(stoppingToken); if (!processed) { // Wait for dispatch notification or fallback interval (2s) await Task.WhenAny(_notifier.WaitAsync(stoppingToken), Task.Delay(2000, stoppingToken)); } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error in SelfCheckDispatchWorker loop"); await Task.Delay(2000, stoppingToken); } } _logger.LogInformation("SelfCheckDispatchWorker stopped."); } private async Task ProcessPendingBatchAsync(CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var pendingRunIds = await db.DeviceSelfChecks .AsNoTracking() .Where(r => r.RunState == SelfCheckRunStates.PendingDispatch) .OrderBy(r => r.RequestedAtUtc) .Take(50) .Select(r => r.Id) .ToListAsync(ct); if (pendingRunIds.Count == 0) { return false; } // Bounded concurrency dispatch (MaxDegreeOfParallelism = 10) await Parallel.ForEachAsync( pendingRunIds, new ParallelOptions { MaxDegreeOfParallelism = 10, CancellationToken = ct }, async (runId, token) => { try { await DispatchSingleRunAsync(runId, token); } catch (Exception ex) { _logger.LogError(ex, "Error dispatching self-check run {RunId}", runId); } }); return true; } private async Task DispatchSingleRunAsync(string runId, CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var presenceService = scope.ServiceProvider.GetRequiredService(); var securityService = scope.ServiceProvider.GetRequiredService(); var hubContext = scope.ServiceProvider.GetRequiredService>(); var run = await db.DeviceSelfChecks.FirstOrDefaultAsync(r => r.Id == runId, ct); if (run == null || run.RunState != SelfCheckRunStates.PendingDispatch) { return; } var device = await db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == run.DeviceId, ct); if (device == null) { run.RunState = SelfCheckRunStates.Unreachable; run.CompletedAtUtc = DateTimeOffset.UtcNow; await db.SaveChangesAsync(ct); return; } // 1. Check device presence (Truthfulness guarantee: offline devices are Unreachable, not Failed) bool isOnline = presenceService.IsOnline(device.Id, device.LastHeartbeatAt); if (!isOnline) { run.RunState = SelfCheckRunStates.Unreachable; run.OverallStatus = null; run.CompletedAtUtc = DateTimeOffset.UtcNow; await db.SaveChangesAsync(ct); _logger.LogInformation("Device {DeviceId} is offline. SelfCheck {RunId} (Batch {BatchId}) marked Unreachable.", run.DeviceId, run.Id, run.BatchId); return; } // 2. Dispatch via tenant-qualified SignalR connection var connId = securityService.GetDeviceConnectionId(device.Id); if (string.IsNullOrEmpty(connId)) { run.RunState = SelfCheckRunStates.Unreachable; run.OverallStatus = null; run.CompletedAtUtc = DateTimeOffset.UtcNow; await db.SaveChangesAsync(ct); return; } var cmdReq = new DeviceSelfCheckRequestDto { SelfCheckId = run.Id, CorrelationId = run.CorrelationId, RequestedAtUtc = run.RequestedAtUtc, TimeoutSeconds = (int)Math.Max(5, (run.DeadlineAtUtc - DateTimeOffset.UtcNow).TotalSeconds) }; var payload = JsonSerializer.Serialize(cmdReq); var cmdDto = await securityService.CreateDeviceCommandAsync( run.TenantId, run.DeviceId, DeviceCommandTypes.SelfCheck, payload, run.RequestedByUserId, "SuperAdmin", "127.0.0.1"); try { await hubContext.Clients.Client(connId).ReceiveRemoteCommand(cmdDto); await securityService.MarkCommandDispatchedAsync(cmdDto.CommandId); run.RunState = SelfCheckRunStates.Dispatched; run.DispatchedAtUtc = DateTimeOffset.UtcNow; run.DispatchAttemptCount++; await db.SaveChangesAsync(ct); _logger.LogInformation("Dispatched SelfCheck {RunId} (Batch {BatchId}) to Device {DeviceId} (Conn: {ConnId})", run.Id, run.BatchId, run.DeviceId, connId); } catch (Exception ex) { run.DispatchAttemptCount++; _logger.LogWarning(ex, "Failed to dispatch SelfCheck {RunId} to Device {DeviceId} (attempt {Attempt}/3)", run.Id, run.DeviceId, run.DispatchAttemptCount); if (run.DispatchAttemptCount >= 3) { run.RunState = SelfCheckRunStates.Unreachable; run.OverallStatus = null; run.CompletedAtUtc = DateTimeOffset.UtcNow; } await db.SaveChangesAsync(ct); } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/SelfCheckDispatchWorker.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/SupportBundleCleanupWorker.cs SHA256: 4c0283bb245d31a50052a7face1447437998a47bc4a56b26a03a9adba20c3c1b SIZE: 10644 ================================================================================ using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace ClassNotify.Server.Services; /// /// 诊断包生命周期清理统计报告 /// public class SupportBundleCleanupReport { public int ExpiredCleanedCount { get; set; } public int CleanupFailedCount { get; set; } public int OrphanDeletedCount { get; set; } public int OrphanSkippedCount { get; set; } } /// /// 诊断包 24 小时生命周期清理后台工作者 (P2.5 RC1-3 Phase 3) /// 严格执行: /// 1. 物理文件删除 -> 验证文件缺失 -> 数据库原子流转 Expired,清空 StoragePath /// 2. 物理删除失败保留 Available,下载 410 阻断,下一周期重试 /// 3. 保守清理无引用系统命名 Orphan ZIP (>24h) /// public class SupportBundleCleanupWorker : BackgroundService { private readonly IServiceProvider _serviceProvider; private readonly IOptions _options; private readonly ILogger _logger; public SupportBundleCleanupWorker( IServiceProvider serviceProvider, IOptions options, ILogger logger) { _serviceProvider = serviceProvider; _options = options; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("SupportBundleCleanupWorker started (5-minute periodic scan)."); while (!stoppingToken.IsCancellationRequested) { try { await CleanupAsync(stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error in SupportBundleCleanupWorker cycle."); } // 5 minutes interval await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); } _logger.LogInformation("SupportBundleCleanupWorker stopped."); } /// /// 执行单次生命周期清理周期 (供 BackgroundService 及单元测试直接调用) /// public async Task CleanupAsync(CancellationToken ct = default) { var report = new SupportBundleCleanupReport(); using var scope = _serviceProvider.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var root = _options.Value.GetEffectiveStorageRoot(); var rootFull = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var rootWithSep = rootFull + Path.DirectorySeparatorChar; var now = DateTimeOffset.UtcNow; // 1. 扫描 Status == Available && ExpiresAtUtc <= now && StoragePath != null var expiredBundles = await db.DeviceSupportBundles .Where(b => b.Status == SupportBundleStatuses.Available && b.ExpiresAtUtc != null && b.ExpiresAtUtc <= now && b.StoragePath != null) .OrderBy(b => b.ExpiresAtUtc) .Take(100) .ToListAsync(ct); foreach (var bundle in expiredBundles) { try { string candidatePath; try { candidatePath = SupportBundlePathResolver.ResolveBundlePath(rootFull, bundle.StoragePath); } catch (InvalidStoragePathException ex) { _logger.LogWarning("Cleanup worker detected invalid StoragePath for bundle {BundleId}: {Message} (StoragePath='{Path}'). Skipping physical delete.", bundle.Id, ex.Message, bundle.StoragePath); continue; } // 严格删除顺序: // Resolve safe path -> Delete physical file -> 确认文件不存在 -> DB Available -> Expired -> StoragePath = null bool fileExisted = File.Exists(candidatePath); if (fileExisted) { try { File.Delete(candidatePath); } catch (Exception ex) { _logger.LogError(ex, "Failed to delete physical support bundle file {FilePath} for {BundleId}. Retrying next cycle.", candidatePath, bundle.Id); report.CleanupFailedCount++; // 重要:物理文件删除失败,DB 不得转 Expired,保留 Available 和 StoragePath! continue; } if (File.Exists(candidatePath)) { _logger.LogWarning("File.Delete did not delete file {FilePath} for {BundleId}. Retrying next cycle.", candidatePath, bundle.Id); report.CleanupFailedCount++; continue; } } else { _logger.LogWarning("SupportBundleFileAlreadyMissing: bundle {BundleId} was marked Available but file {FilePath} was already missing.", bundle.Id, candidatePath); } // 物理文件确认已不存在,原子条件更新数据库:Available -> Expired if (db.Database.IsRelational()) { await db.DeviceSupportBundles .Where(b => b.Id == bundle.Id && b.Status == SupportBundleStatuses.Available) .ExecuteUpdateAsync(setters => setters .SetProperty(x => x.Status, SupportBundleStatuses.Expired) .SetProperty(x => x.StoragePath, (string?)null) .SetProperty(x => x.UpdatedAtUtc, DateTimeOffset.UtcNow), ct); } else { var b = await db.DeviceSupportBundles.FirstOrDefaultAsync(x => x.Id == bundle.Id && x.Status == SupportBundleStatuses.Available, ct); if (b != null) { b.Status = SupportBundleStatuses.Expired; b.StoragePath = null; b.UpdatedAtUtc = DateTimeOffset.UtcNow; await db.SaveChangesAsync(ct); } } report.ExpiredCleanedCount++; _logger.LogInformation("Successfully expired support bundle {BundleId} and cleaned up physical storage.", bundle.Id); } catch (Exception ex) { _logger.LogError(ex, "Error expiring support bundle {BundleId}", bundle.Id); report.CleanupFailedCount++; } } // 2. Conservative Orphan File Cleanup if (Directory.Exists(rootFull)) { try { await CleanupOrphansAsync(rootFull, db, report, ct); } catch (Exception ex) { _logger.LogError(ex, "Error scanning for orphan support bundle files in {Root}", rootFull); } } return report; } private async Task CleanupOrphansAsync(string rootFull, ClassNotifyDbContext db, SupportBundleCleanupReport report, CancellationToken ct) { var cutoff = DateTime.UtcNow.AddHours(-24); var files = Directory.GetFiles(rootFull, "*.*", SearchOption.AllDirectories); foreach (var filePath in files) { var relative = Path.GetRelativePath(rootFull, filePath).Replace('\\', '/'); // 规则:tmp/ 目录绝对不碰 if (relative.StartsWith("tmp/", StringComparison.OrdinalIgnoreCase) || relative.StartsWith("tmp\\", StringComparison.OrdinalIgnoreCase)) { report.OrphanSkippedCount++; continue; } var fileName = Path.GetFileName(filePath); // 规则:必须是系统命名格式 *.zip (以 sb_ 开头,以 .zip 结尾) if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) || !fileName.StartsWith("sb_", StringComparison.OrdinalIgnoreCase)) { // 未知文件不自动删除,仅告警 report.OrphanSkippedCount++; continue; } // 规则:文件创建/写入时间必须 > 24h var lastWrite = File.GetLastWriteTimeUtc(filePath); var creation = File.GetCreationTimeUtc(filePath); var fileAgeUtc = lastWrite < creation ? lastWrite : creation; if (fileAgeUtc >= cutoff) { // 年龄不足 24h,跳过 report.OrphanSkippedCount++; continue; } // 规则:当前数据库没有任何 StoragePath 引用 bool hasDbRef = await db.DeviceSupportBundles.AnyAsync(b => b.StoragePath != null && (b.StoragePath == relative || b.StoragePath == filePath || b.StoragePath.EndsWith("/" + fileName) || b.StoragePath.EndsWith("\\" + fileName)), ct); if (hasDbRef) { report.OrphanSkippedCount++; continue; } // 孤儿确认,执行安全删除 try { File.Delete(filePath); report.OrphanDeletedCount++; _logger.LogInformation("Deleted orphan support bundle zip: {FilePath} (Age={AgeHours:F1}h, 0 DB refs)", filePath, (DateTime.UtcNow - fileAgeUtc).TotalHours); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to delete orphan file: {FilePath}", filePath); } } } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/SupportBundleCleanupWorker.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/SupportBundleDispatchWorker.cs SHA256: 6fc687b79198844241daf09053f771991b6d5adcdd4c06ce988eacdf010bb6bb SIZE: 6562 ================================================================================ using ClassNotify.Server.Data; using ClassNotify.Server.Hubs; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; /// /// 设备技术诊断包后台分发调度器 (P2.5 RC1-3 Support Bundle Phase 1) /// 严格基于数据库 PendingDispatch 状态作为可靠持久化队列,支持服务器重启后完全自动恢复 /// 离线真实等待重试,直至 Deadline 触发 TimedOut,绝不虚构状态 /// public sealed class SupportBundleDispatchWorker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly ISupportBundleDispatchNotifier _notifier; private readonly ILogger _logger; public SupportBundleDispatchWorker( IServiceScopeFactory scopeFactory, ISupportBundleDispatchNotifier notifier, ILogger logger) { _scopeFactory = scopeFactory; _notifier = notifier; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("SupportBundleDispatchWorker started."); while (!stoppingToken.IsCancellationRequested) { try { var processed = await ProcessPendingBundlesAsync(stoppingToken); if (!processed) { // 等待通知唤醒或定时兜底检测 (1s) await Task.WhenAny(_notifier.WaitAsync(stoppingToken), Task.Delay(1000, stoppingToken)); } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error in SupportBundleDispatchWorker loop"); await Task.Delay(1000, stoppingToken); } } _logger.LogInformation("SupportBundleDispatchWorker stopped."); } private async Task ProcessPendingBundlesAsync(CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var presenceService = scope.ServiceProvider.GetRequiredService(); var hubContext = scope.ServiceProvider.GetRequiredService>(); var now = DateTimeOffset.UtcNow; // 1. 扫描超时任务 (PendingDispatch 或 Collecting 且超过 DeadlineAtUtc) var timedOutBundles = await db.DeviceSupportBundles .Where(sb => (sb.Status == SupportBundleStatuses.PendingDispatch || sb.Status == SupportBundleStatuses.Collecting) && sb.DeadlineAtUtc <= now) .Take(50) .ToListAsync(ct); if (timedOutBundles.Count > 0) { foreach (var b in timedOutBundles) { b.Status = SupportBundleStatuses.TimedOut; b.ErrorCode ??= "DeadlineExceeded"; b.UpdatedAtUtc = now; _logger.LogInformation("SupportBundle {Id} for device {DeviceId} timed out at {Now:u} (deadline was {Deadline:u})", b.Id, b.DeviceId, now, b.DeadlineAtUtc); } await db.SaveChangesAsync(ct); } // 2. 扫描待分发任务 (Status == PendingDispatch && NextDispatchAttemptAtUtc <= now && DeadlineAtUtc > now) var pendingBundles = await db.DeviceSupportBundles .Where(sb => sb.Status == SupportBundleStatuses.PendingDispatch && (sb.NextDispatchAttemptAtUtc == null || sb.NextDispatchAttemptAtUtc <= now) && sb.DeadlineAtUtc > now) .OrderBy(sb => sb.CreatedAtUtc) .Take(50) .ToListAsync(ct); if (pendingBundles.Count == 0) { return timedOutBundles.Count > 0; } foreach (var bundle in pendingBundles) { var device = await db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == bundle.DeviceId, ct); bool isOnline = device != null && presenceService.IsOnline(device.Id, device.LastHeartbeatAt); if (isOnline) { // 设备在线:通过 tenant-qualified SignalR 渠道下发 GenerateSupportBundleCommand var command = new GenerateSupportBundleCommand { FormatVersion = 1, SupportBundleId = bundle.Id, CorrelationId = bundle.CorrelationId, RequestedAtUtc = bundle.CreatedAtUtc, DeadlineAtUtc = bundle.DeadlineAtUtc, MaxSizeBytes = 5 * 1024 * 1024 }; var tenantChannel = $"t:{bundle.TenantId}:d:{bundle.DeviceId}"; await hubContext.Clients.Group(tenantChannel).GenerateSupportBundle(command); bundle.Status = SupportBundleStatuses.Collecting; bundle.DispatchedAtUtc = now; bundle.DispatchAttemptCount += 1; bundle.LastDispatchAttemptAtUtc = now; bundle.UpdatedAtUtc = now; _logger.LogInformation("Successfully dispatched GenerateSupportBundleCommand to {Channel} for bundle {BundleId}. State -> Collecting.", tenantChannel, bundle.Id); } else { // 设备离线:保持 PendingDispatch,按规整阶梯安排下一次重试 (2s, 5s, 10s, 15s) bundle.DispatchAttemptCount += 1; bundle.LastDispatchAttemptAtUtc = now; int backoffSeconds = bundle.DispatchAttemptCount switch { 1 => 2, 2 => 5, 3 => 10, _ => 15 }; bundle.NextDispatchAttemptAtUtc = now.AddSeconds(backoffSeconds); bundle.UpdatedAtUtc = now; _logger.LogInformation("Device {DeviceId} for bundle {BundleId} is offline. Retry scheduled in {Seconds}s (Attempt={Attempt})", bundle.DeviceId, bundle.Id, backoffSeconds, bundle.DispatchAttemptCount); } } await db.SaveChangesAsync(ct); return true; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/SupportBundleDispatchWorker.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/SupportBundlePathResolver.cs SHA256: cc092d85ed92e25c34ddbc9adf371f67ee2638d92f59bb33eabe25c6c11b4201 SIZE: 2250 ================================================================================ using System; using System.IO; namespace ClassNotify.Server.Services; /// /// 当技术诊断包存储路径非法、包含路径穿越或违反纯相对路径约束时抛出 /// public sealed class InvalidStoragePathException : Exception { public InvalidStoragePathException(string message = "Invalid storage path detected.") : base(message) { } } /// /// 技术诊断包路径解析器 (严格约束相对路径与根目录约束,防御目录穿越与跨平台大小写边界漏洞) /// public static class SupportBundlePathResolver { /// /// 将数据库中记录的纯相对 StoragePath 安全解析为绝对路径 /// 严格禁止绝对路径,严格禁止任何向上逃逸 ('..') /// public static string ResolveBundlePath(string rootDir, string? relativeStoragePath) { if (string.IsNullOrWhiteSpace(relativeStoragePath)) { throw new InvalidStoragePathException("Storage path cannot be empty or whitespace."); } // 1. 绝对路径坚决拒绝 (无论 Windows 盘符 C:\、UNC \\ 还是 Linux 根路径 / ) if (Path.IsPathRooted(relativeStoragePath)) { throw new InvalidStoragePathException("Storage path must be a relative path. Absolute paths are strictly forbidden."); } var root = Path.GetFullPath(rootDir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var candidate = Path.GetFullPath(Path.Combine(root, relativeStoragePath)); // 2. 检查相对于 root 的路径 var relative = Path.GetRelativePath(root, candidate); if (relative == ".." || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) || relative.StartsWith(".." + Path.AltDirectorySeparatorChar, StringComparison.Ordinal) || Path.IsPathRooted(relative) || relative == "." || string.IsNullOrWhiteSpace(relative) || string.Equals(candidate, root, StringComparison.OrdinalIgnoreCase)) { throw new InvalidStoragePathException("Storage path traversal detected."); } return candidate; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/SupportBundlePathResolver.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/SupportBundleService.cs SHA256: 427a5473ab6c2de1e34422a482a4402bdffe18ce71d5487a8ecc5b6bd74dd24d SIZE: 23271 ================================================================================ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Infrastructure.Correlation; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace ClassNotify.Server.Services; /// /// 设备技术诊断包服务实现 (P2.5 RC1-3 Support Bundle Phase 1, Phase 2, Phase 3) /// 严格满足 RBAC、客户端幂等性、单 Active 互斥、事务与审计一致性、安全下载与生命周期管理 /// public class SupportBundleService : ISupportBundleService { private static readonly ConcurrentDictionary _creationLocks = new(); private readonly ClassNotifyDbContext _db; private readonly ICorrelationContext _correlationContext; private readonly ISupportBundleDispatchNotifier _dispatchNotifier; private readonly IOptions _options; private readonly ILogger _logger; public SupportBundleService( ClassNotifyDbContext db, ICorrelationContext correlationContext, ISupportBundleDispatchNotifier dispatchNotifier, IOptions options, ILogger logger) { _db = db; _correlationContext = correlationContext; _dispatchNotifier = dispatchNotifier; _options = options; _logger = logger; } public async Task CreateSupportBundleAsync( string deviceId, CreateSupportBundleRequest request, string actorUserId, string actorRole, string? actorTenantId, string actorIp, bool simulateAuditFailure, CancellationToken ct) { if (string.IsNullOrWhiteSpace(deviceId)) { return SupportBundleCreationResult.BadRequest("DeviceId 不可为空。"); } if (request == null) { request = new CreateSupportBundleRequest(); } if (string.IsNullOrWhiteSpace(request.ClientRequestId)) { request.ClientRequestId = Guid.NewGuid().ToString("N"); } var lockKey = $"{actorUserId}:{request.ClientRequestId}"; var gate = _creationLocks.GetOrAdd(lockKey, _ => new SemaphoreSlim(1, 1)); await gate.WaitAsync(ct); try { // 1. Load Device var device = await _db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId, ct); if (device == null) { return SupportBundleCreationResult.NotFound($"设备 '{deviceId}' 不存在。"); } // 2. Authorize // SuperAdmin: 全局允许 // SchoolAdmin: 严格限定同校 JWT TenantId == Device.TenantId // Teacher / 其它: 403 if (actorRole == "SchoolAdmin") { if (string.IsNullOrEmpty(actorTenantId) || !string.Equals(actorTenantId, device.TenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("SchoolAdmin {User} (Tenant={UserTenant}) attempted to request support bundle for device {DeviceId} (Tenant={DeviceTenant}). 403 Forbidden.", actorUserId, actorTenantId, device.Id, device.TenantId); return SupportBundleCreationResult.Forbidden("跨租户技术诊断包请求被拒绝。"); } } else if (actorRole != "SuperAdmin") { _logger.LogWarning("User {User} with role {Role} attempted to request support bundle. 403 Forbidden.", actorUserId, actorRole); return SupportBundleCreationResult.Forbidden("仅允许系统管理员或学校管理员发起技术诊断包请求。"); } // 3. Idempotency Check: Same ClientRequestId by same user returns existing bundle var existing = await _db.DeviceSupportBundles .AsNoTracking() .FirstOrDefaultAsync(sb => sb.RequestedByUserId == actorUserId && sb.ClientRequestId == request.ClientRequestId, ct); if (existing != null) { _logger.LogInformation("Idempotent hit for support bundle ClientRequestId={ClientRequestId}, returning existing BundleId={BundleId}", request.ClientRequestId, existing.Id); return SupportBundleCreationResult.Accepted(new SupportBundleCreatedDto { SupportBundleId = existing.Id, DeviceId = existing.DeviceId, Status = existing.Status, CreatedAtUtc = existing.CreatedAtUtc, DeadlineAtUtc = existing.DeadlineAtUtc, CorrelationId = existing.CorrelationId }); } // 4. Active Bundle Check: 同一设备同一时间只允许一个正在生成的 Support Bundle (PendingDispatch 或 Collecting) var existingActive = await _db.DeviceSupportBundles .AsNoTracking() .FirstOrDefaultAsync(sb => sb.DeviceId == device.Id && (sb.Status == SupportBundleStatuses.PendingDispatch || sb.Status == SupportBundleStatuses.Collecting), ct); if (existingActive != null) { _logger.LogWarning("Device {DeviceId} already has active support bundle {ActiveBundleId} in state {State}. 409 Conflict.", device.Id, existingActive.Id, existingActive.Status); return SupportBundleCreationResult.Conflict( SupportBundleErrorCodes.SupportBundleAlreadyRunning, existingActive.Id, $"设备 '{device.Id}' 当前已有正在收集中的技术诊断包 ({existingActive.Id})。"); } // 5. Begin Transaction: DeviceSupportBundle + SUPPORT_BUNDLE_REQUESTED Audit 原子落库 var now = DateTimeOffset.UtcNow; var bundleId = $"sb_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24]; var correlationId = !string.IsNullOrWhiteSpace(_correlationContext.CorrelationId) ? _correlationContext.CorrelationId : $"sb_corr_{Guid.NewGuid():N}"[..20]; var bundle = new DeviceSupportBundle { Id = bundleId, ClientRequestId = request.ClientRequestId, TenantId = device.TenantId, DeviceId = device.Id, CorrelationId = correlationId, RequestedByUserId = actorUserId, Status = SupportBundleStatuses.PendingDispatch, CreatedAtUtc = now, UpdatedAtUtc = now, DeadlineAtUtc = now.AddMinutes(2), // 固定第一版 CreatedAtUtc + 2 minutes NextDispatchAttemptAtUtc = now, DispatchAttemptCount = 0, StoragePath = null, SizeBytes = null, Sha256 = null, ExpiresAtUtc = null, ErrorCode = null }; var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUserId, ActorRole = actorRole, Action = "SUPPORT_BUNDLE_REQUESTED", TargetType = "DeviceSupportBundle", TargetId = bundle.Id, Details = JsonSerializer.Serialize(new { supportBundleId = bundle.Id, tenantId = bundle.TenantId, deviceId = bundle.DeviceId }), IpAddress = actorIp }; await using var tx = await _db.Database.BeginTransactionAsync(ct); try { _db.DeviceSupportBundles.Add(bundle); if (simulateAuditFailure) { throw new InvalidOperationException("Simulated audit failure for testing atomic transaction rollback"); } _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); await tx.CommitAsync(ct); } catch (DbUpdateException dbEx) { _logger.LogWarning(dbEx, "DbUpdateException during support bundle creation. Checking for concurrent collision."); // 检查幂等性冲突 (ClientRequestId + RequestedByUserId) var collisionExisting = await _db.DeviceSupportBundles .AsNoTracking() .FirstOrDefaultAsync(sb => sb.RequestedByUserId == actorUserId && sb.ClientRequestId == request.ClientRequestId, ct); if (collisionExisting != null) { return SupportBundleCreationResult.Accepted(new SupportBundleCreatedDto { SupportBundleId = collisionExisting.Id, DeviceId = collisionExisting.DeviceId, Status = collisionExisting.Status, CreatedAtUtc = collisionExisting.CreatedAtUtc, DeadlineAtUtc = collisionExisting.DeadlineAtUtc, CorrelationId = collisionExisting.CorrelationId }); } // 检查单 Active 唯一约束冲突 (UX_DeviceSupportBundles_Device_Active) var collisionActive = await _db.DeviceSupportBundles .AsNoTracking() .FirstOrDefaultAsync(sb => sb.DeviceId == device.Id && (sb.Status == SupportBundleStatuses.PendingDispatch || sb.Status == SupportBundleStatuses.Collecting), ct); if (collisionActive != null) { return SupportBundleCreationResult.Conflict( SupportBundleErrorCodes.SupportBundleAlreadyRunning, collisionActive.Id, $"设备 '{device.Id}' 当前已有正在收集中的技术诊断包 ({collisionActive.Id})。"); } throw; } catch (Exception ex) { _logger.LogError(ex, "Transaction failed while creating support bundle {BundleId}. Rolled back.", bundle.Id); throw; } _logger.LogInformation("Support bundle requested successfully: BundleId={BundleId}, DeviceId={DeviceId}, TenantId={TenantId}, CorrelationId={CorrelationId}", bundle.Id, bundle.DeviceId, bundle.TenantId, bundle.CorrelationId); // 6. Post-commit: 唤醒后台调度 Worker _dispatchNotifier.Notify(); return SupportBundleCreationResult.Accepted(new SupportBundleCreatedDto { SupportBundleId = bundle.Id, DeviceId = bundle.DeviceId, Status = bundle.Status, CreatedAtUtc = bundle.CreatedAtUtc, DeadlineAtUtc = bundle.DeadlineAtUtc, CorrelationId = bundle.CorrelationId }); } finally { gate.Release(); } } public async Task GetSupportBundleAsync(string bundleId, string actorRole, string? actorTenantId, CancellationToken ct) { var bundle = await _db.DeviceSupportBundles.AsNoTracking().FirstOrDefaultAsync(b => b.Id == bundleId, ct); if (bundle == null) return null; if (actorRole == "SchoolAdmin" && !string.Equals(actorTenantId, bundle.TenantId, StringComparison.OrdinalIgnoreCase)) { return null; // 租户越界静默拦截或 404 } return new SupportBundleDetailDto { SupportBundleId = bundle.Id, DeviceId = bundle.DeviceId, TenantId = bundle.TenantId, CorrelationId = bundle.CorrelationId, RequestedByUserId = bundle.RequestedByUserId, Status = bundle.Status, CreatedAtUtc = bundle.CreatedAtUtc, UpdatedAtUtc = bundle.UpdatedAtUtc, DeadlineAtUtc = bundle.DeadlineAtUtc, DispatchedAtUtc = bundle.DispatchedAtUtc, CompletedAtUtc = bundle.CompletedAtUtc, ExpiresAtUtc = bundle.ExpiresAtUtc, DispatchAttemptCount = bundle.DispatchAttemptCount, StoragePath = bundle.StoragePath, SizeBytes = bundle.SizeBytes, Sha256 = bundle.Sha256, ErrorCode = bundle.ErrorCode }; } public async Task> GetSupportBundleStatusAsync( string bundleId, string actorRole, string? actorTenantId, CancellationToken ct) { var bundle = await _db.DeviceSupportBundles.AsNoTracking().FirstOrDefaultAsync(b => b.Id == bundleId, ct); if (bundle == null) { return SupportBundleQueryResult.NotFound($"Support bundle '{bundleId}' not found."); } if (actorRole == "SchoolAdmin") { if (string.IsNullOrEmpty(actorTenantId) || !string.Equals(actorTenantId, bundle.TenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("SchoolAdmin (Tenant={UserTenant}) attempted cross-tenant status query for bundle {BundleId} (Tenant={BundleTenant}). 403 Forbidden.", actorTenantId, bundle.Id, bundle.TenantId); return SupportBundleQueryResult.Forbidden("跨租户技术诊断包查询被拒绝。"); } } else if (actorRole != "SuperAdmin") { return SupportBundleQueryResult.Forbidden("仅允许系统管理员或学校管理员查询技术诊断包。"); } var now = DateTimeOffset.UtcNow; bool isDownloadAvailable = bundle.Status == SupportBundleStatuses.Available && bundle.ExpiresAtUtc.HasValue && bundle.ExpiresAtUtc.Value > now; var dto = new SupportBundleStatusDto { SupportBundleId = bundle.Id, DeviceId = bundle.DeviceId, TenantId = bundle.TenantId, Status = bundle.Status, CreatedAtUtc = bundle.CreatedAtUtc, CompletedAtUtc = bundle.CompletedAtUtc, ExpiresAtUtc = bundle.ExpiresAtUtc, SizeBytes = bundle.SizeBytes, Sha256 = bundle.Sha256, DownloadAvailable = isDownloadAvailable, ErrorCode = bundle.ErrorCode }; return SupportBundleQueryResult.Ok(dto); } public async Task>> GetDeviceSupportBundlesAsync( string deviceId, int take, string actorRole, string? actorTenantId, CancellationToken ct) { var device = await _db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId, ct); if (device == null) { return SupportBundleQueryResult>.NotFound($"Device '{deviceId}' not found."); } if (actorRole == "SchoolAdmin") { if (string.IsNullOrEmpty(actorTenantId) || !string.Equals(actorTenantId, device.TenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("SchoolAdmin (Tenant={UserTenant}) attempted cross-tenant device bundles query for device {DeviceId} (Tenant={DeviceTenant}). 403 Forbidden.", actorTenantId, device.Id, device.TenantId); return SupportBundleQueryResult>.Forbidden("跨租户设备诊断包列表查询被拒绝。"); } } else if (actorRole != "SuperAdmin") { return SupportBundleQueryResult>.Forbidden("仅允许系统管理员或学校管理员查询技术诊断包。"); } var clampedTake = Math.Clamp(take <= 0 ? 5 : take, 1, 20); var now = DateTimeOffset.UtcNow; var bundles = await _db.DeviceSupportBundles .AsNoTracking() .Where(b => b.DeviceId == deviceId) .OrderByDescending(b => b.CreatedAtUtc) .Take(clampedTake) .Select(b => new SupportBundleStatusDto { SupportBundleId = b.Id, DeviceId = b.DeviceId, TenantId = b.TenantId, Status = b.Status, CreatedAtUtc = b.CreatedAtUtc, CompletedAtUtc = b.CompletedAtUtc, ExpiresAtUtc = b.ExpiresAtUtc, SizeBytes = b.SizeBytes, Sha256 = b.Sha256, DownloadAvailable = b.Status == SupportBundleStatuses.Available && b.ExpiresAtUtc.HasValue && b.ExpiresAtUtc.Value > now, ErrorCode = b.ErrorCode }) .ToListAsync(ct); return SupportBundleQueryResult>.Ok(bundles); } public async Task PrepareDownloadAsync( string bundleId, string actorRole, string? actorTenantId, string actorUser, string actorIp, CancellationToken ct) { // 1. 加载诊断包记录 var bundle = await _db.DeviceSupportBundles.FirstOrDefaultAsync(b => b.Id == bundleId, ct); if (bundle == null) { return SupportBundleDownloadResult.NotFound($"Support bundle '{bundleId}' not found."); } // 2. 权限校验 if (actorRole == "SchoolAdmin") { if (string.IsNullOrEmpty(actorTenantId) || !string.Equals(actorTenantId, bundle.TenantId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("SchoolAdmin {User} (Tenant={UserTenant}) attempted cross-tenant download for bundle {BundleId} (Tenant={BundleTenant}). 403 Forbidden.", actorUser, actorTenantId, bundle.Id, bundle.TenantId); return SupportBundleDownloadResult.Forbidden("跨校技术诊断包下载被拒绝。"); } } else if (actorRole != "SuperAdmin") { return SupportBundleDownloadResult.Forbidden("仅允许系统管理员或学校管理员下载技术诊断包。"); } // 3. 状态与有效期检查 if (bundle.Status == SupportBundleStatuses.PendingDispatch || bundle.Status == SupportBundleStatuses.Collecting) { return SupportBundleDownloadResult.Conflict(SupportBundleErrorCodes.BundleNotReady, $"Support bundle is currently in state '{bundle.Status}' and not ready for download."); } if (bundle.Status == SupportBundleStatuses.Failed) { return SupportBundleDownloadResult.Conflict(SupportBundleErrorCodes.BundleFailed, "Support bundle collection failed and cannot be downloaded."); } if (bundle.Status == SupportBundleStatuses.TimedOut || bundle.Status == SupportBundleStatuses.Expired) { return SupportBundleDownloadResult.Gone(SupportBundleErrorCodes.BundleExpired, $"Support bundle is in terminal state '{bundle.Status}' and cannot be downloaded."); } var now = DateTimeOffset.UtcNow; if (bundle.ExpiresAtUtc.HasValue && bundle.ExpiresAtUtc.Value <= now) { return SupportBundleDownloadResult.Gone(SupportBundleErrorCodes.BundleExpired, "Support bundle has expired (retention period exceeded)."); } if (bundle.Status != SupportBundleStatuses.Available) { return SupportBundleDownloadResult.Conflict(SupportBundleErrorCodes.BundleNotReady, $"Support bundle is in state '{bundle.Status}' and cannot be downloaded."); } if (string.IsNullOrWhiteSpace(bundle.StoragePath)) { return SupportBundleDownloadResult.ServerError(SupportBundleErrorCodes.SupportBundleFileMissing, "Support bundle record has no StoragePath."); } // 4. Storage Root Confinement (Strict Relative Path & Path Traversal Protection) var root = _options.Value.GetEffectiveStorageRoot(); string candidatePath; try { candidatePath = SupportBundlePathResolver.ResolveBundlePath(root, bundle.StoragePath); } catch (InvalidStoragePathException ex) { _logger.LogWarning("CRITICAL: Storage path validation failed for bundle {BundleId}: {Message} (StoragePath='{Path}')", bundle.Id, ex.Message, bundle.StoragePath); return SupportBundleDownloadResult.BadRequest(SupportBundleErrorCodes.InvalidStoragePath, "Invalid storage path detected."); } catch (Exception ex) { _logger.LogWarning(ex, "Unexpected error resolving StoragePath '{StoragePath}' for bundle {BundleId}", bundle.StoragePath, bundle.Id); return SupportBundleDownloadResult.BadRequest(SupportBundleErrorCodes.InvalidStoragePath, "Invalid storage path detected."); } // 5. Physical File Existence Check if (!File.Exists(candidatePath)) { _logger.LogError("Support bundle file missing from disk! BundleId={BundleId}, Path={StoragePath}, ExpectedSha256={Sha256}", bundle.Id, bundle.StoragePath, bundle.Sha256); return SupportBundleDownloadResult.ServerError(SupportBundleErrorCodes.SupportBundleFileMissing, "Support bundle file missing from storage."); } // 6. Audit Logging: 仅当成功授权并准备提供下载时写入 SUPPORT_BUNDLE_DOWNLOADED var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "SUPPORT_BUNDLE_DOWNLOADED", TargetType = "DeviceSupportBundle", TargetId = bundle.Id, Details = JsonSerializer.Serialize(new { supportBundleId = bundle.Id, tenantId = bundle.TenantId, deviceId = bundle.DeviceId, sizeBytes = bundle.SizeBytes, sha256 = bundle.Sha256 }), IpAddress = actorIp }; _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); var downloadFileName = $"classnotify-support-{bundle.DeviceId}-{bundle.CreatedAtUtc:yyyyMMdd-HHmm}.zip"; return SupportBundleDownloadResult.Success(candidatePath, downloadFileName); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/SupportBundleService.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/UpdatePackagePathResolver.cs SHA256: b5adee156c167ab1d7dc083ab5ecf7f64fe72451c96a45661ecd71bb7693417e SIZE: 2299 ================================================================================ using System; using System.IO; namespace ClassNotify.Server.Services; /// /// 当升级包存储路径非法、包含路径穿越或违反纯相对路径约束时抛出 /// public sealed class InvalidUpdatePackagePathException : Exception { public InvalidUpdatePackagePathException(string message = "Invalid update package path detected.") : base(message) { } } /// /// 客户端在线升级包路径解析器 (严格约束相对路径与根目录约束,防御目录穿越与跨平台大小写边界漏洞) /// public static class UpdatePackagePathResolver { /// /// 将数据库中记录的纯相对 PackageRelativePath 安全解析为绝对路径 /// 严格禁止绝对路径,严格禁止任何向上逃逸 ('..') /// public static string ResolvePackagePath(string rootDir, string? relativeStoragePath) { if (string.IsNullOrWhiteSpace(relativeStoragePath)) { throw new InvalidUpdatePackagePathException("Package path cannot be empty or whitespace."); } // 1. 绝对路径坚决拒绝 (无论 Windows 盘符 C:\、UNC \\ 还是 Linux 根路径 / ) if (Path.IsPathRooted(relativeStoragePath)) { throw new InvalidUpdatePackagePathException("Package path must be a relative path. Absolute paths are strictly forbidden."); } var root = Path.GetFullPath(rootDir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var candidate = Path.GetFullPath(Path.Combine(root, relativeStoragePath)); // 2. 检查相对于 root 的路径 var relative = Path.GetRelativePath(root, candidate); if (relative == ".." || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) || relative.StartsWith(".." + Path.AltDirectorySeparatorChar, StringComparison.Ordinal) || Path.IsPathRooted(relative) || relative == "." || string.IsNullOrWhiteSpace(relative) || string.Equals(candidate, root, StringComparison.OrdinalIgnoreCase)) { throw new InvalidUpdatePackagePathException("Package path traversal detected."); } return candidate; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/UpdatePackagePathResolver.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/VisualReceiptCleanupWorker.cs SHA256: d620a20993a6cd64c10b235914573476c976f8bc49023221aa87a7f5115fd8ac SIZE: 1814 ================================================================================ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ClassNotify.Server.Services; public class VisualReceiptCleanupWorker : BackgroundService { private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; public VisualReceiptCleanupWorker( IServiceProvider serviceProvider, ILogger logger) { _serviceProvider = serviceProvider; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("VisualReceiptCleanupWorker started (24h retention enforcer)."); while (!stoppingToken.IsCancellationRequested) { try { using var scope = _serviceProvider.CreateScope(); var service = scope.ServiceProvider.GetRequiredService(); await service.CleanupExpiredVisualReceiptsAsync(stoppingToken); var healthState = scope.ServiceProvider.GetService(); if (healthState != null) { healthState.LastVisualReceiptCleanupSuccessUtc = DateTimeOffset.UtcNow; } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Error occurred during visual receipt cleanup execution."); } // Check every 30 minutes await Task.Delay(TimeSpan.FromMinutes(30), stoppingToken); } _logger.LogInformation("VisualReceiptCleanupWorker stopped."); } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/VisualReceiptCleanupWorker.cs ================================================================================ ================================================================================ FILE BEGIN: src/Server/ClassNotify.Server/Services/VisualReceiptService.cs SHA256: 8bd9f45d9b860a76ec3937f1637f884f901b613ccb97d5661675d45a87e725d2 SIZE: 14875 ================================================================================ using System.Collections.Concurrent; using System.Security.Claims; using System.Security.Cryptography; using System.Threading; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; public class VisualReceiptService : IVisualReceiptService { private static readonly ConcurrentDictionary _receiptLocks = new(); private readonly IServiceScopeFactory _scopeFactory; private readonly ISecurityService _securityService; private readonly IConfiguration _configuration; private readonly ILogger _logger; private readonly string _storageBasePath; public VisualReceiptService( IServiceScopeFactory scopeFactory, ISecurityService securityService, IConfiguration configuration, ILogger logger) { _scopeFactory = scopeFactory; _securityService = securityService; _configuration = configuration; _logger = logger; // Path resolution: config > /var/lib/classnotify/visual-receipts (if linux directory exists or creatable) > AppContext.BaseDirectory var configuredPath = _configuration.GetValue("VisualReceipt:StoragePath"); if (!string.IsNullOrWhiteSpace(configuredPath)) { _storageBasePath = configuredPath; } else if (OperatingSystem.IsLinux()) { _storageBasePath = "/var/lib/classnotify/visual-receipts"; } else { _storageBasePath = Path.Combine(AppContext.BaseDirectory, "visual_receipts"); } try { Directory.CreateDirectory(_storageBasePath); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to create visual receipts storage directory at {Path}, falling back to temp directory.", _storageBasePath); _storageBasePath = Path.Combine(Path.GetTempPath(), "classnotify_visual_receipts"); Directory.CreateDirectory(_storageBasePath); } } public async Task SaveVisualReceiptAsync( string notificationId, string deviceId, string deviceToken, byte[] jpegBytes) { if (string.IsNullOrWhiteSpace(notificationId) || string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(deviceToken)) { return new VisualReceiptUploadResult(false, "缺少必要参数或凭据", 400); } // 1. Payload size check (Max 512 KiB) if (jpegBytes == null || jpegBytes.Length == 0) { return new VisualReceiptUploadResult(false, "图片数据为空", 400); } if (jpegBytes.Length > 524288) { return new VisualReceiptUploadResult(false, "图片文件超过 512 KiB 大小限制", 413); } // 2. JPEG magic bytes check: Starts with 0xFF 0xD8, Ends with 0xFF 0xD9 if (jpegBytes.Length < 4 || jpegBytes[0] != 0xFF || jpegBytes[1] != 0xD8 || jpegBytes[^2] != 0xFF || jpegBytes[^1] != 0xD9) { return new VisualReceiptUploadResult(false, "上传内容不是合法的 JPEG 格式图像", 415); } // 3. Authenticate device token var device = await _securityService.ValidateDeviceAsync(deviceId, deviceToken); if (device == null || !device.IsActive) { return new VisualReceiptUploadResult(false, "设备凭据无效或设备已被禁用", 401); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // 4. Validate Notification and NotificationReceipt attribution var notification = await db.Notifications.AsNoTracking().FirstOrDefaultAsync(n => n.Id == notificationId); if (notification == null) { return new VisualReceiptUploadResult(false, "目标通知不存在", 404); } // Defense in depth: Check tenant and class isolation if (notification.TenantId != device.TenantId || notification.ClassroomId != device.ClassroomId) { _logger.LogWarning("Cross-tenant/class visual receipt upload spoofing attempt: Device {DevId} ({DevTenant}/{DevClass}) vs Notif {NotifId} ({NotifTenant}/{NotifClass})", deviceId, device.TenantId, device.ClassroomId, notificationId, notification.TenantId, notification.ClassroomId); return new VisualReceiptUploadResult(false, "设备归属与通知目标班级不匹配", 403); } var receipt = await db.NotificationReceipts.FirstOrDefaultAsync(r => r.NotificationId == notificationId && r.DeviceId == deviceId); if (receipt == null) { return new VisualReceiptUploadResult(false, "该设备未被分配此通知回执记录", 403); } // 5. Concurrency & Idempotency: First Successful Receipt Wins with Per-Receipt Mutex var receiptLock = _receiptLocks.GetOrAdd(receipt.Id, _ => new SemaphoreSlim(1, 1)); await receiptLock.WaitAsync(); try { // Fresh check from database inside mutex var currentReceipt = await db.NotificationReceipts.FirstOrDefaultAsync(r => r.Id == receipt.Id); if (currentReceipt == null) { return new VisualReceiptUploadResult(false, "回执记录不存在", 404); } if (currentReceipt.VisualReceiptState == "Available") { _logger.LogInformation("Visual receipt already available for Notification {NotifId} / Device {DevId} (Receipt {ReceiptId}). First-wins idempotent success returned.", notificationId, deviceId, receipt.Id); return new VisualReceiptUploadResult(true, "视觉回执已存在", 200, currentReceipt.Id, currentReceipt.VisualReceiptCapturedAt, currentReceipt.VisualReceiptExpiresAt); } // 6. Compute SHA256 hash string sha256Hex; using (var sha = SHA256.Create()) { var hashBytes = sha.ComputeHash(jpegBytes); sha256Hex = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); } // 7. Atomic file writing with unique temporary file and overwrite: false var now = DateTimeOffset.UtcNow; var dateFolder = now.ToString("yyyyMMdd"); var targetDir = Path.Combine(_storageBasePath, dateFolder); Directory.CreateDirectory(targetDir); var relativePath = $"{dateFolder}/{currentReceipt.Id}.jpg"; var finalFilePath = Path.Combine(_storageBasePath, dateFolder, $"{currentReceipt.Id}.jpg"); var tempFilePath = Path.Combine(_storageBasePath, dateFolder, $"{currentReceipt.Id}_{Guid.NewGuid():N}.tmp"); try { await File.WriteAllBytesAsync(tempFilePath, jpegBytes); File.Move(tempFilePath, finalFilePath, overwrite: false); } catch (IOException ex) when (File.Exists(finalFilePath)) { // File already placed by a winning race; clean up temp and return idempotent success _logger.LogInformation(ex, "Final visual receipt file already exists at {Path}. Cleaned temp and returning first-wins idempotent.", finalFilePath); try { if (File.Exists(tempFilePath)) File.Delete(tempFilePath); } catch { } return new VisualReceiptUploadResult(true, "视觉回执已存在", 200, currentReceipt.Id, currentReceipt.VisualReceiptCapturedAt ?? now, currentReceipt.VisualReceiptExpiresAt ?? now.AddHours(24)); } catch (Exception ex) { _logger.LogError(ex, "Failed to write visual receipt file to {Path}", finalFilePath); try { if (File.Exists(tempFilePath)) File.Delete(tempFilePath); } catch { } return new VisualReceiptUploadResult(false, "服务端写入视觉回执文件失败", 500); } // 8. Update database record with 24-hour retention var expiresAt = now.AddHours(24); currentReceipt.VisualReceiptState = "Available"; currentReceipt.VisualReceiptPath = relativePath; currentReceipt.VisualReceiptCapturedAt = now; currentReceipt.VisualReceiptExpiresAt = expiresAt; currentReceipt.VisualReceiptSizeBytes = jpegBytes.Length; currentReceipt.VisualReceiptSha256 = sha256Hex; currentReceipt.UpdatedAt = now; try { await db.SaveChangesAsync(); _logger.LogInformation("Visual receipt successfully saved for Notification {NotifId} / Device {DevId} (Size: {Size} bytes, SHA256: {Sha256}, Expires: {ExpiresAt})", notificationId, deviceId, jpegBytes.Length, sha256Hex, expiresAt); return new VisualReceiptUploadResult(true, "视觉回执上传成功", 200, currentReceipt.Id, now, expiresAt); } catch (Exception ex) { _logger.LogError(ex, "Database update failed after saving visual receipt file. Compensating by removing file {Path}", finalFilePath); try { if (File.Exists(finalFilePath)) File.Delete(finalFilePath); } catch { } return new VisualReceiptUploadResult(false, "更新回执数据库状态失败", 500); } } finally { receiptLock.Release(); } } public async Task GetVisualReceiptFileAsync(string notificationId, string deviceId, ClaimsPrincipal user) { if (user.Identity?.IsAuthenticated != true) { return new VisualReceiptFileResult(false, null, 401, "未登录或登录凭据无效"); } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var notification = await db.Notifications.AsNoTracking().FirstOrDefaultAsync(n => n.Id == notificationId); if (notification == null) { return new VisualReceiptFileResult(false, null, 404, "通知记录不存在"); } // Permission check var userRole = user.FindFirst(ClaimTypes.Role)?.Value ?? "Teacher"; var userTenant = user.FindFirst("tenant_id")?.Value; var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (userRole != "SuperAdmin") { if (string.IsNullOrEmpty(userTenant) || userTenant != notification.TenantId) { return new VisualReceiptFileResult(false, null, 403, "无权查看非本校通知记录的视觉回执"); } if (userRole == "Teacher") { // Teacher can view notifications sent by themselves or targeting their classroom bool isSender = !string.IsNullOrEmpty(userId) && notification.SenderUserId == userId; if (!isSender) { // Allow teacher within same school to view class notification history // (Consistent with existing NotificationController.GetNotifications policy) } } } var receipt = await db.NotificationReceipts.AsNoTracking() .FirstOrDefaultAsync(r => r.NotificationId == notificationId && r.DeviceId == deviceId); if (receipt == null || receipt.VisualReceiptState == "None") { return new VisualReceiptFileResult(false, null, 404, "该设备无视觉回执记录"); } var now = DateTimeOffset.UtcNow; if (receipt.VisualReceiptState == "Expired" || (receipt.VisualReceiptExpiresAt.HasValue && receipt.VisualReceiptExpiresAt.Value <= now)) { return new VisualReceiptFileResult(false, null, 410, "该视觉回执已按 24 小时隐私保存策略自动销毁"); } if (string.IsNullOrEmpty(receipt.VisualReceiptPath)) { return new VisualReceiptFileResult(false, null, 404, "视觉回执文件路径为空"); } // Prevent path traversal var safeRelativePath = receipt.VisualReceiptPath.Replace('\\', '/').TrimStart('/'); if (safeRelativePath.Contains("..")) { return new VisualReceiptFileResult(false, null, 400, "非法文件路径"); } var fullPath = Path.Combine(_storageBasePath, safeRelativePath); if (!File.Exists(fullPath)) { _logger.LogWarning("Visual receipt file missing on disk: {Path}", fullPath); return new VisualReceiptFileResult(false, null, 404, "视觉回执图像文件已被物理删除"); } return new VisualReceiptFileResult(true, fullPath, 200); } public async Task CleanupExpiredVisualReceiptsAsync(CancellationToken ct = default) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; var expiredReceipts = await db.NotificationReceipts .Where(r => r.VisualReceiptState == "Available" && r.VisualReceiptExpiresAt <= now) .Take(200) .ToListAsync(ct); if (expiredReceipts.Count == 0) return 0; int cleanedCount = 0; foreach (var r in expiredReceipts) { if (!string.IsNullOrEmpty(r.VisualReceiptPath)) { var safeRelativePath = r.VisualReceiptPath.Replace('\\', '/').TrimStart('/'); var fullPath = Path.Combine(_storageBasePath, safeRelativePath); try { if (File.Exists(fullPath)) { File.Delete(fullPath); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to delete expired visual receipt file at {Path}. Retaining Available state in database for retry in next cleanup cycle.", fullPath); continue; // Retain Available state and Path in database! Next worker cycle will retry. } } r.VisualReceiptPath = null; r.VisualReceiptState = "Expired"; r.UpdatedAt = now; cleanedCount++; } if (cleanedCount > 0) { await db.SaveChangesAsync(ct); _logger.LogInformation("Cleaned up {Count} expired visual receipts per 24-hour privacy retention policy.", cleanedCount); } return cleanedCount; } } ================================================================================ FILE END: src/Server/ClassNotify.Server/Services/VisualReceiptService.cs ================================================================================