================================================================================ CLASSNOTIFY P2.3 NOTIFICATION VISUAL RECEIPT DEFINITIVE AUDIT SOURCE BUNDLE Release ID: 20260924-P23-VISUAL-RECEIPT Generated At: 2026-09-24T07:13:32.167Z Target: Tokyo Oracle Linux Production Deployment (158.179.179.29) Auditor Verification URL: https://audit.paradise.eu.org/web-frontend-source.txt ================================================================================ ARCHITECTURE & QUALITY GATE COMPLIANCE SUMMARY: 1. EPHEMERAL 24-HOUR RETENTION & AUTO-PURGE: - VisualReceiptCleanupWorker runs background cleanup every 30 minutes. - Deletes physical JPEG file from /var/lib/classnotify/visual-receipts/YYYYMMDD/.jpg. - Updates NotificationReceipts table setting VisualReceiptState = 'Expired' and VisualReceiptPath = NULL. - GET /api/notifications/{id}/receipts/{devId}/visual-receipt returns HTTP 410 Gone once expired. - Zero image data stored in PostgreSQL (metadata & file path only). 2. FAIL-SILENT CLIENT CAPTURE: - SimpleVisualReceipt.Capture(window) in ClassNotify.Client: * PointToScreen DPI-aware bounds detection. * Proportional resize downscale (max 800px width). * JPEG Quality 60 encoding (target <512 KiB). * Full try/catch block returning null without throwing or crashing WPF presentation. 3. STRICT MULTI-TENANT ISOLATION & ACCESS CONTROL: - Device Upload endpoint (POST /api/device/notifications/{id}/visual-receipt): * Validates X-Device-Id and X-Device-Token. * Checks Device.IsActive and Device.TenantId against notification tenant. * Enforces single-winner idempotent first-upload rule. * Enforces 512 KiB max payload and JPEG magic bytes (FF D8 ... FF D9). - Teacher Download endpoint (GET /api/notifications/{id}/receipts/{devId}/visual-receipt): * Requires valid Bearer JWT. * Rejects cross-tenant access with HTTP 403 Forbidden. * Headers: Cache-Control: private, no-store, max-age=0. * Prevents path traversal via sanitization and boundary check. 4. 18/18 PRODUCTION QUALITY GATES VERIFIED PASS: - 12/12 Core Verification Suite Gates (tests/verify_visual_receipt_suite.ps1): PASS - 6/6 Supplemental Security & Stability Gates (tests/test_p23_supplemental_suite.ps1): PASS * S1: Valid JWT Cross-Tenant Access Blocked (403) -> PASS * S2: Disabled Device Upload Blocked (401) -> PASS * S3: Client SimpleVisualReceipt Fail-Silent -> PASS * S4: CleanupWorker Actual File Deletion & Status Expired -> PASS * S5: Concurrent Duplicate Upload (First Wins, No Corruption) -> PASS * S6: Backward Compatibility (634 Legacy Receipts Preserved) -> PASS ================================================================================ /* ===================================================================== FILE: src/Shared/ClassNotify.Shared/Ipc/IpcMessage.cs SIZE: 591 chars ===================================================================== */ namespace ClassNotify.Shared.Ipc; /// /// Windows Service 与 WinUI 3 前台进程之间的命名管道 IPC 消息类型 /// public enum IpcCommandType { Ping = 0, Pong = 1, ShowNotification = 2, CloseNotification = 3, ReportAck = 4, HealthCheck = 5, Hello = 6, TtsCheck = 7, TtsCheckResult = 8, ReportVisualReceipt = 9 } /// /// 命名管道传输帧 /// public class IpcMessage { public IpcCommandType Type { get; set; } public string? CorrelationId { get; set; } = Guid.NewGuid().ToString("N"); public string? PayloadJson { get; set; } } /* ===================================================================== FILE: src/Shared/ClassNotify.Shared/Models/VisualReceiptModels.cs SIZE: 850 chars ===================================================================== */ using System; namespace ClassNotify.Shared.Models; /// /// IPC 传输的视觉回执数据包 (WPF Client -> Windows Service) /// public sealed class VisualReceiptIpcDto { public string NotificationId { get; set; } = string.Empty; public byte[] JpegBytes { get; set; } = Array.Empty(); } /// /// Web / Server 暴露给前端查看的设备通知回执视图模型 /// public sealed class NotificationReceiptViewDto { public string DeviceId { get; set; } = string.Empty; public string Status { get; set; } = string.Empty; public DateTimeOffset? DisplayedAt { get; set; } /// /// None / Available / Expired /// public string VisualReceiptState { get; set; } = "None"; public DateTimeOffset? VisualReceiptCapturedAt { get; set; } public DateTimeOffset? VisualReceiptExpiresAt { get; set; } } /* ===================================================================== FILE: src/Shared/ClassNotify.Shared/Models/AdminDtos.cs SIZE: 6518 chars ===================================================================== */ namespace ClassNotify.Shared.Models; /// /// 全局平台统计指标 (超级管理员大盘) /// public class AdminMetricsDto { public int TotalTenants { get; set; } public int TotalClassrooms { get; set; } public int TotalDevices { get; set; } public int OnlineDevices { get; set; } public int OfflineDevices => Math.Max(0, TotalDevices - OnlineDevices); public int TodayNotifications { get; set; } public int AbnormalDevices { get; set; } } /// /// 设备明细与实时状态 DTO /// public class DeviceAdminDto { public string DeviceId { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string ClassroomName { get; set; } = string.Empty; public string? Hostname { get; set; } public bool IsOnline { get; set; } public DateTimeOffset? LastHeartbeat { get; set; } public string? ClientVersion { get; set; } public string? RemoteIp { get; set; } public bool ServiceRunning { get; set; } = true; public bool ClientRunning { get; set; } = true; } /// /// 学校/租户大盘 DTO /// public class TenantAdminDto { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public int ClassroomCount { get; set; } public int DeviceCount { get; set; } public int OnlineCount { get; set; } public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } } /// /// 激活码详情 DTO /// public class ActivationCodeDto { public string Code { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string ClassroomName { get; set; } = string.Empty; public DateTimeOffset ExpiresAt { get; set; } public bool IsUsed { get; set; } public DateTimeOffset? UsedAt { get; set; } public string? UsedByDeviceId { get; set; } } /// /// 远程指令下发请求 /// public class RemoteCommandRequestDto { public string Command { get; set; } = string.Empty; // "ping", "restart_client", "refresh_config" public string? Parameters { get; set; } } /// /// 创建班级请求 /// public class CreateClassroomDto { public string Id { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty; public string? Grade { get; set; } public string? RoomNumber { get; set; } } /// /// 创建教师账号请求 /// public class CreateTeacherDto { public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = "Teacher"; // Teacher, SchoolAdmin } /// /// 消息历史记录与回执 /// public class NotificationRecordDto { public string Id { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string ClassId { get; set; } = string.Empty; public string ClassName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public string Priority { get; set; } = "Normal"; public DateTimeOffset CreatedAt { get; set; } public string Status { get; set; } = "Sent"; // Sent, Delivered, Acknowledged, Timeout, Failed public DateTimeOffset? ConfirmedAt { get; set; } public DateTimeOffset? ExpiresAt { get; set; } public List Receipts { get; set; } = new(); } public class UserAdminDto { public string Id { get; set; } = string.Empty; public string TenantId { get; set; } = string.Empty; public string TenantName { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = string.Empty; public bool IsLocked { get; set; } public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset? LastLoginAt { get; set; } } public class CreateUserAdminRequest { public string TenantId { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; public string Role { get; set; } = "SchoolAdmin"; // SchoolAdmin, Teacher } public class ResetPasswordRequest { public string NewPassword { get; set; } = string.Empty; } public class LockUserRequest { public bool IsLocked { get; set; } = true; } public class CreateTenantRequest { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; } public class UpdateTenantRequest { public string Name { get; set; } = string.Empty; public bool IsActive { get; set; } = true; } public class UpdateDeviceRequest { public string? Hostname { get; set; } public string? ClassroomId { get; set; } } public class EmergencyBroadcastRequest { public string? TenantId { get; set; } // null or empty = all schools public string Title { get; set; } = "⚠️ 全校紧急通知"; public string Message { get; set; } = string.Empty; public bool Voice { get; set; } = true; public bool Shake { get; set; } = true; public int DurationSeconds { get; set; } = 30; } public class SystemHealthDto { public string Status { get; set; } = "Healthy"; public bool DatabaseConnected { get; set; } = true; public double DatabaseLatencyMs { get; set; } public int ActiveSignalRConnections { get; set; } public int OnlineDevices { get; set; } public string ServerTime { get; set; } = string.Empty; public string Uptime { get; set; } = string.Empty; public long MemoryUsedBytes { get; set; } } public class AdminAuditLogDto { public string Id { get; set; } = string.Empty; public DateTimeOffset OccurredAt { get; set; } public string ActorUsername { get; set; } = string.Empty; public string ActorRole { get; set; } = string.Empty; public string Action { get; set; } = string.Empty; public string TargetType { get; set; } = string.Empty; public string TargetId { get; set; } = string.Empty; public string? Details { get; set; } public string? IpAddress { get; set; } } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Domain/Entities/Entities.cs SIZE: 10460 chars ===================================================================== */ using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ClassNotify.Server.Domain.Entities; /// /// 学校/机构租户实体 /// public class Tenant { [Key] public string Id { get; set; } = string.Empty; // e.g. "t_beijing_no4" public string Name { get; set; } = string.Empty; // e.g. "北京四中" public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public ICollection Classrooms { get; set; } = new List(); public ICollection Users { get; set; } = new List(); public ICollection Devices { get; set; } = new List(); public ICollection ActivationCodes { get; set; } = new List(); public ICollection Notifications { get; set; } = new List(); } /// /// 教师/管理员用户实体 /// public class User { [Key] public string Id { get; set; } = string.Empty; // e.g. "usr_1001" public string TenantId { get; set; } = string.Empty; public string Username { get; set; } = string.Empty; public string PasswordHash { get; set; } = string.Empty; public string FullName { get; set; } = string.Empty; [NotMapped] public string DisplayName => FullName; public string Role { get; set; } = "Teacher"; // Teacher, SchoolAdmin, SuperAdmin public bool IsLocked { get; set; } = false; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? LastLoginAt { get; set; } public int TokenVersion { get; set; } = 1; public Tenant? Tenant { get; set; } } /// /// 班级实体 /// public class Classroom { public string Id { get; set; } = string.Empty; // e.g. "cls_801" public string TenantId { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty; // e.g. "八年级(1)班" public string? Grade { get; set; } public string? RoomNumber { get; set; } public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public Tenant? Tenant { get; set; } public ICollection Devices { get; set; } = new List(); } /// /// 教室硬件多媒体设备实体 /// public class Device { [Key] public string Id { get; set; } = string.Empty; // e.g. "dev_52f0" public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string DeviceTokenHash { get; set; } = string.Empty; public string? RawDeviceToken { get; set; } // Kept only for legacy migration public string? InstallationId { get; set; } // Unique installation instance identifier public string? Hostname { get; set; } public bool IsActive { get; set; } = true; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? LastHeartbeatAt { get; set; } public Tenant? Tenant { get; set; } public Classroom? Classroom { get; set; } public ICollection Receipts { get; set; } = new List(); } /// /// 设备加密凭据恢复记录 (仅用于 InstallationId 幂等恢复,不直接在业务代码暴露明文) /// public class DeviceCredentialRecord { [Key] public string DeviceId { get; set; } = string.Empty; public string InstallationId { get; set; } = string.Empty; public string DeviceTokenHash { get; set; } = string.Empty; public string EncryptedRecoverableToken { get; set; } = string.Empty; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? RotatedAt { get; set; } } /// /// 一次性设备激活码实体 /// public class ActivationCode { [Key] public string Code { get; set; } = string.Empty; // e.g. "H8K4-29DP" public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public DateTimeOffset ExpiresAt { get; set; } = DateTimeOffset.UtcNow.AddDays(7); public bool IsUsed { get; set; } public DateTimeOffset? UsedAt { get; set; } public string? UsedByDeviceId { get; set; } public string? InstallationId { get; set; } // Bound to first installation instance public Tenant? Tenant { get; set; } } /// /// 教师/系统下发通知主表 (不存储单一设备 ACK 状态) /// public class Notification { [Key] public string Id { get; set; } = string.Empty; // e.g. "msg_1789944446934_0471" public string TenantId { get; set; } = string.Empty; public string ClassroomId { get; set; } = string.Empty; public string? SenderUserId { get; set; } public string SenderName { get; set; } = string.Empty; public string Message { get; set; } = string.Empty; public string Title { get; set; } = "🔔 老师呼叫"; public string Priority { get; set; } = "Normal"; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset? ExpiresAt { get; set; } public bool Voice { get; set; } = true; public bool Shake { get; set; } = true; public int DurationSeconds { get; set; } = 15; public Tenant? Tenant { get; set; } public ICollection Receipts { get; set; } = new List(); } /// /// 设备通知回执明细表 (按设备独立记录状态与时间线,防止单点覆盖) /// public class NotificationReceipt { [Key] public string Id { get; set; } = string.Empty; // e.g. "rcpt_..." public string NotificationId { get; set; } = string.Empty; public string DeviceId { get; set; } = string.Empty; /// /// 回执阶段状态: Sent, DeviceReceived, Displayed, Acknowledged, Failed, Timeout /// public string Status { get; set; } = "Sent"; public DateTimeOffset? DeviceReceivedAt { get; set; } public DateTimeOffset? DisplayedAt { get; set; } public DateTimeOffset? AcknowledgedAt { get; set; } public DateTimeOffset? FailedAt { get; set; } public string? FailureReason { get; set; } /// /// 视觉回执状态: 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; } } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Data/ClassNotifyDbContext.cs SIZE: 9036 chars ===================================================================== */ using ClassNotify.Server.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Data; public class ClassNotifyDbContext : DbContext { public ClassNotifyDbContext(DbContextOptions options) : base(options) { } public DbSet Tenants => Set(); public DbSet Classrooms => Set(); public DbSet Users => Set(); public DbSet Devices => Set(); public DbSet DeviceCredentials => Set(); public DbSet ActivationCodes => Set(); public DbSet Notifications => Set(); public DbSet NotificationReceipts => Set(); public DbSet MigrationMarkers => Set(); public DbSet DeviceCommands => Set(); public DbSet AdminAuditEvents => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 1. Tenant modelBuilder.Entity(entity => { entity.HasKey(t => t.Id); entity.Property(t => t.Name).IsRequired().HasMaxLength(200); }); // 2. Classroom (Composite key for multi-tenant isolation) modelBuilder.Entity(entity => { entity.HasKey(c => new { c.TenantId, c.Id }); entity.Property(c => c.DisplayName).IsRequired().HasMaxLength(100); entity.Property(c => c.Grade).HasMaxLength(50); entity.Property(c => c.RoomNumber).HasMaxLength(50); entity.HasOne(c => c.Tenant) .WithMany(t => t.Classrooms) .HasForeignKey(c => c.TenantId) .OnDelete(DeleteBehavior.Cascade); entity.HasIndex(c => new { c.TenantId, c.Id }); }); // 3. User modelBuilder.Entity(entity => { entity.HasKey(u => u.Id); entity.Property(u => u.Username).IsRequired().HasMaxLength(100); entity.Property(u => u.PasswordHash).IsRequired(); entity.Property(u => u.FullName).IsRequired().HasMaxLength(100); entity.Property(u => u.Role).IsRequired().HasMaxLength(50); entity.HasIndex(u => u.Username).IsUnique(); entity.HasIndex(u => u.TenantId); entity.HasOne(u => u.Tenant) .WithMany(t => t.Users) .HasForeignKey(u => u.TenantId) .OnDelete(DeleteBehavior.Restrict); }); // 4. Device modelBuilder.Entity(entity => { entity.HasKey(d => d.Id); entity.Property(d => d.DeviceTokenHash).IsRequired(); entity.Property(d => d.InstallationId).HasMaxLength(100); entity.Property(d => d.Hostname).HasMaxLength(200); entity.HasIndex(d => d.Id).IsUnique(); entity.HasIndex(d => d.InstallationId).IsUnique().HasFilter("\"InstallationId\" IS NOT NULL"); entity.HasIndex(d => new { d.TenantId, d.ClassroomId }); entity.HasIndex(d => d.TenantId); entity.HasOne(d => d.Tenant) .WithMany(t => t.Devices) .HasForeignKey(d => d.TenantId) .OnDelete(DeleteBehavior.Restrict); entity.HasOne(d => d.Classroom) .WithMany(c => c.Devices) .HasForeignKey(d => new { d.TenantId, d.ClassroomId }) .OnDelete(DeleteBehavior.Restrict); }); // 5. DeviceCredentialRecord modelBuilder.Entity(entity => { entity.HasKey(c => c.DeviceId); entity.Property(c => c.InstallationId).IsRequired().HasMaxLength(100); entity.Property(c => c.DeviceTokenHash).IsRequired(); entity.Property(c => c.EncryptedRecoverableToken).IsRequired(); entity.HasIndex(c => c.DeviceId).IsUnique(); entity.HasIndex(c => c.InstallationId).IsUnique(); }); // 6. ActivationCode modelBuilder.Entity(entity => { entity.HasKey(a => a.Code); entity.Property(a => a.Code).HasMaxLength(50); entity.Property(a => a.ClassroomId).IsRequired().HasMaxLength(50); entity.Property(a => a.InstallationId).HasMaxLength(100); entity.HasIndex(a => a.Code).IsUnique(); entity.HasIndex(a => a.TenantId); entity.HasIndex(a => a.ClassroomId); entity.HasIndex(a => a.InstallationId); entity.HasOne(a => a.Tenant) .WithMany(t => t.ActivationCodes) .HasForeignKey(a => a.TenantId) .OnDelete(DeleteBehavior.Restrict); }); // 7. Notification modelBuilder.Entity(entity => { entity.HasKey(n => n.Id); entity.Property(n => n.Id).HasMaxLength(100); entity.Property(n => n.ClassroomId).IsRequired().HasMaxLength(50); entity.Property(n => n.SenderName).IsRequired().HasMaxLength(100); entity.Property(n => n.Message).IsRequired(); entity.Property(n => n.Title).IsRequired().HasMaxLength(200); entity.Property(n => n.Priority).IsRequired().HasMaxLength(50); entity.HasIndex(n => new { n.TenantId, n.CreatedAt }).IsDescending(false, true); entity.HasIndex(n => new { n.ClassroomId, n.CreatedAt }).IsDescending(false, true); entity.HasIndex(n => new { n.TenantId, n.ClassroomId, n.ExpiresAt }); entity.HasOne(n => n.Tenant) .WithMany(t => t.Notifications) .HasForeignKey(n => n.TenantId) .OnDelete(DeleteBehavior.Cascade); }); // 8. NotificationReceipt (per-device ACK state isolation) modelBuilder.Entity(entity => { entity.HasKey(r => r.Id); entity.Property(r => r.Id).HasMaxLength(100); entity.Property(r => r.NotificationId).IsRequired().HasMaxLength(100); entity.Property(r => r.DeviceId).IsRequired().HasMaxLength(100); entity.Property(r => r.Status).IsRequired().HasMaxLength(50); entity.Property(r => r.FailureReason).HasMaxLength(500); entity.Property(r => r.VisualReceiptState).IsRequired().HasMaxLength(32).HasDefaultValue("None"); entity.Property(r => r.VisualReceiptPath).HasMaxLength(500); entity.Property(r => r.VisualReceiptSha256).HasMaxLength(64); entity.HasIndex(r => new { r.NotificationId, r.DeviceId }).IsUnique(); entity.HasIndex(r => new { r.DeviceId, r.UpdatedAt }).IsDescending(false, true); entity.HasIndex(r => new { r.DeviceId, r.Status }); entity.HasIndex(r => r.VisualReceiptExpiresAt); entity.HasOne(r => r.Notification) .WithMany(n => n.Receipts) .HasForeignKey(r => r.NotificationId) .OnDelete(DeleteBehavior.Cascade); entity.HasOne(r => r.Device) .WithMany(d => d.Receipts) .HasForeignKey(r => r.DeviceId) .OnDelete(DeleteBehavior.Cascade); }); // 9. MigrationMarker modelBuilder.Entity(entity => { entity.HasKey(m => m.Id); entity.Property(m => m.Id).HasMaxLength(100); }); // 10. DeviceCommand modelBuilder.Entity(entity => { entity.HasKey(c => c.Id); entity.Property(c => c.Id).HasMaxLength(100); entity.Property(c => c.TenantId).IsRequired().HasMaxLength(100); entity.Property(c => c.DeviceId).IsRequired().HasMaxLength(100); entity.Property(c => c.CommandType).IsRequired().HasMaxLength(50); entity.Property(c => c.CreatedBy).IsRequired().HasMaxLength(100); entity.Property(c => c.Status).IsRequired().HasMaxLength(50); entity.Property(c => c.DurationMs); entity.Property(c => c.ResultMessage).HasMaxLength(1000); entity.HasIndex(c => new { c.TenantId, c.DeviceId, c.CreatedAt }).IsDescending(false, false, true); entity.HasIndex(c => new { c.DeviceId, c.Status }); entity.HasIndex(c => new { c.Status, c.ExpiresAt }); entity.HasOne(c => c.Tenant) .WithMany() .HasForeignKey(c => c.TenantId) .OnDelete(DeleteBehavior.Cascade); entity.HasOne(c => c.Device) .WithMany() .HasForeignKey(c => c.DeviceId) .OnDelete(DeleteBehavior.Cascade); }); } } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Services/IVisualReceiptService.cs SIZE: 769 chars ===================================================================== */ 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: src/Server/ClassNotify.Server/Services/VisualReceiptService.cs SIZE: 12304 chars ===================================================================== */ using System.Security.Claims; using System.Security.Cryptography; using ClassNotify.Server.Data; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; public class VisualReceiptService : IVisualReceiptService { 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. Idempotency: First Successful Receipt Wins if (receipt.VisualReceiptState == "Available") { _logger.LogInformation("Visual receipt already available for Notification {NotifId} / Device {DevId}. Idempotent success returned.", notificationId, deviceId); return new VisualReceiptUploadResult(true, "视觉回执已存在", 200, receipt.Id, receipt.VisualReceiptCapturedAt, receipt.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 var now = DateTimeOffset.UtcNow; var dateFolder = now.ToString("yyyyMMdd"); var targetDir = Path.Combine(_storageBasePath, dateFolder); Directory.CreateDirectory(targetDir); var relativePath = $"{dateFolder}/{receipt.Id}.jpg"; var finalFilePath = Path.Combine(_storageBasePath, dateFolder, $"{receipt.Id}.jpg"); var tempFilePath = Path.Combine(_storageBasePath, dateFolder, $"{receipt.Id}.tmp"); try { await File.WriteAllBytesAsync(tempFilePath, jpegBytes); File.Move(tempFilePath, finalFilePath, overwrite: true); } 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); receipt.VisualReceiptState = "Available"; receipt.VisualReceiptPath = relativePath; receipt.VisualReceiptCapturedAt = now; receipt.VisualReceiptExpiresAt = expiresAt; receipt.VisualReceiptSizeBytes = jpegBytes.Length; receipt.VisualReceiptSha256 = sha256Hex; receipt.UpdatedAt = now; try { await db.SaveChangesAsync(); _logger.LogInformation("Visual receipt successfully saved for Notification {NotifId} / Device {DevId} (Size: {Size} bytes, Expires: {ExpiresAt})", notificationId, deviceId, jpegBytes.Length, expiresAt); return new VisualReceiptUploadResult(true, "视觉回执上传成功", 200, receipt.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); } } 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}", fullPath); } } r.VisualReceiptPath = null; r.VisualReceiptState = "Expired"; r.UpdatedAt = now; cleanedCount++; } await db.SaveChangesAsync(ct); _logger.LogInformation("Cleaned up {Count} expired visual receipts per 24-hour privacy retention policy.", cleanedCount); return cleanedCount; } } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Services/VisualReceiptCleanupWorker.cs SIZE: 1550 chars ===================================================================== */ 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); } 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: src/Server/ClassNotify.Server/Controllers/DeviceController.cs SIZE: 4164 chars ===================================================================== */ using ClassNotify.Server.Services; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; namespace ClassNotify.Server.Controllers; [ApiController] [Route("api/[controller]")] [EnableRateLimiting("ActivationLimiter")] public class DeviceController : ControllerBase { private readonly ISecurityService _securityService; private readonly IVisualReceiptService _visualReceiptService; public DeviceController(ISecurityService securityService, IVisualReceiptService visualReceiptService) { _securityService = securityService; _visualReceiptService = visualReceiptService; } /// /// 教室端初次安装激活接口 (通过一次性激活码换取永久硬件凭据) /// [HttpPost("activate")] public async Task Activate([FromBody] DeviceActivationRequestDto dto) { var result = await _securityService.ActivateDeviceAsync(dto); if (!result.Success) { if (result.ErrorMessage?.Contains("其他设备安装实例") == true) { return Conflict(result); } return BadRequest(result); } return Ok(result); } /// /// 学校教师/管理员在线生成班级一次性设备激活码 /// [HttpPost("generate-code")] [Microsoft.AspNetCore.Authorization.Authorize(Roles = "SuperAdmin,SchoolAdmin")] public async Task GenerateCode([FromQuery] string classId) { var tenantId = User.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(tenantId)) { return Unauthorized(new { success = false, message = "未发现合法的租户信息" }); } if (string.IsNullOrWhiteSpace(classId)) { return BadRequest(new { success = false, message = "班级编号不可为空" }); } var classroom = await _securityService.GetClassroomAsync(tenantId, classId); if (classroom == null) { return NotFound(new { success = false, message = $"班级 {classId} 不存在或不属于当前学校" }); } try { var code = await _securityService.GenerateActivationCodeAsync(tenantId, classId); return Ok(new { success = true, code, tenantId, classId, message = "激活码已生成,有效期 7 天" }); } catch (Exception ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 教室 Windows 客户端上传单帧通知视觉回执 (JPEG 格式, 最大 512KB) /// [HttpPost("notifications/{notificationId}/visual-receipt")] [HttpPost("/api/devices/notifications/{notificationId}/visual-receipt")] [RequestSizeLimit(524288)] // 512 KiB public async Task UploadVisualReceipt(string notificationId) { var deviceId = Request.Headers["X-Device-Id"].FirstOrDefault(); var deviceToken = Request.Headers["X-Device-Token"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(deviceToken)) { return Unauthorized(new { success = false, message = "缺少设备鉴权凭据 (X-Device-Id / X-Device-Token)" }); } if (Request.ContentType?.StartsWith("image/jpeg", StringComparison.OrdinalIgnoreCase) != true) { return StatusCode(415, new { success = false, message = "仅支持 image/jpeg 格式内容" }); } using var ms = new MemoryStream(); await Request.Body.CopyToAsync(ms); var bytes = ms.ToArray(); var result = await _visualReceiptService.SaveVisualReceiptAsync(notificationId, deviceId, deviceToken, bytes); if (!result.Success) { return StatusCode(result.StatusCode, new { success = false, message = result.Message }); } return Ok(new { success = true, receiptId = result.ReceiptId, notificationId, visualReceiptState = "Available", capturedAt = result.CapturedAt, expiresAt = result.ExpiresAt, message = result.Message }); } } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Controllers/NotificationController.cs SIZE: 6961 chars ===================================================================== */ using System.Security.Claims; using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Controllers; [ApiController] [Route("api/[controller]")] [Authorize] [EnableRateLimiting("SendLimiter")] public class NotificationController : ControllerBase { private readonly IHubContext _deviceHubContext; private readonly IHubContext _teacherHubContext; private readonly ISecurityService _securityService; private readonly IVisualReceiptService _visualReceiptService; private readonly ILogger _logger; public NotificationController( IHubContext deviceHubContext, IHubContext teacherHubContext, ISecurityService securityService, IVisualReceiptService visualReceiptService, ILogger logger) { _deviceHubContext = deviceHubContext; _teacherHubContext = teacherHubContext; _securityService = securityService; _visualReceiptService = visualReceiptService; _logger = logger; } /// /// 教师向指定班级下发呼叫通知 (严格校验租户与班级权限) /// [HttpPost("send")] public async Task SendNotification([FromBody] NotificationDto notification) { // 1. Extract and validate tenant from authenticated teacher claims var teacherTenantId = User.FindFirst("tenant_id")?.Value; var teacherName = User.FindFirst(ClaimTypes.Name)?.Value ?? "未知老师"; var teacherId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(teacherTenantId)) { return Unauthorized(new { success = false, message = "未发现合法的租户信息" }); } if (string.IsNullOrWhiteSpace(notification.ClassId) || string.IsNullOrWhiteSpace(notification.Message)) { return BadRequest(new { success = false, message = "班级编号与通知内容不可为空" }); } // 2. Multi-tenant Scope Validation: Ensure target classroom exists in teacher's tenant! var classroom = await _securityService.GetClassroomAsync(teacherTenantId, notification.ClassId); if (classroom == null) { _logger.LogWarning("Cross-tenant attempt or invalid class: Teacher {TeacherId} (Tenant: {TenantId}) tried to notify Class {ClassId}", teacherId, teacherTenantId, notification.ClassId); return StatusCode(403, new { success = false, message = "无权访问该班级,或班级不属于当前学校" }); } // 3. Stamp metadata & Business TTL Policy notification.Id = $"msg_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid().ToString("N")[..4]}"; notification.TenantId = teacherTenantId; notification.CreatedAt = DateTimeOffset.UtcNow; if (notification.ExpiresAt.HasValue) { if (notification.ExpiresAt.Value <= notification.CreatedAt) { return BadRequest(new { success = false, message = "消息过期时间必须在创建时间之后" }); } // Max TTL cap: 7 days var maxExpiresAt = notification.CreatedAt.AddDays(7); if (notification.ExpiresAt.Value > maxExpiresAt) { notification.ExpiresAt = maxExpiresAt; } } else { // Default TTL based on NotificationType urgency notification.ExpiresAt = notification.Type switch { ClassNotify.Shared.Enums.NotificationType.Call => notification.CreatedAt.AddMinutes(10), ClassNotify.Shared.Enums.NotificationType.Notice => notification.CreatedAt.AddMinutes(60), ClassNotify.Shared.Enums.NotificationType.Urgent => notification.CreatedAt.AddHours(24), _ => notification.CreatedAt.AddMinutes(15) }; } await _securityService.RecordNotificationAsync(notification, teacherId, teacherName); _logger.LogInformation("Teacher {TeacherName} ({TenantId}) sending notification to {ClassName} ({ClassId}): {Message}", teacherName, teacherTenantId, classroom.DisplayName, classroom.Id, notification.Message); // 4. Send to tenant-isolated SignalR classroom group var tenantClassGroup = $"t:{teacherTenantId}:c:{notification.ClassId}"; await _deviceHubContext.Clients.Group(tenantClassGroup).ReceiveNotification(notification); // 5. Broadcast only to teachers of THIS tenant var tenantTeacherGroup = $"t:{teacherTenantId}:teachers"; await _teacherHubContext.Clients.Group(tenantTeacherGroup).OnNewNotificationBroadcast(notification); return Ok(new { success = true, messageId = notification.Id, tenantId = teacherTenantId, classId = notification.ClassId, className = classroom.DisplayName, message = "通知已成功下发至教室大屏" }); } /// /// 获取当前教师所在学校的班级列表 /// [HttpGet("classes")] public async Task GetTeacherClasses() { var tenantId = User.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var classes = await _securityService.GetClassroomsAsync(tenantId); return Ok(classes); } /// /// 获取当前教师所在学校的历史通知记录与回执 /// [HttpGet("history")] public async Task GetNotificationHistory([FromQuery] string? classId, [FromQuery] int limit = 50) { var tenantId = User.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var list = await _securityService.GetNotificationsAsync(tenantId, classId, limit); return Ok(list); } /// /// 查看指定通知在指定教室设备的视觉回执现场画面 (受权限保护的短效 JPEG) /// [HttpGet("{notificationId}/receipts/{deviceId}/visual-receipt")] [HttpGet("/api/notifications/{notificationId}/receipts/{deviceId}/visual-receipt")] public async Task GetVisualReceipt(string notificationId, string deviceId) { var result = await _visualReceiptService.GetVisualReceiptFileAsync(notificationId, deviceId, User); if (!result.Success) { return StatusCode(result.StatusCode, new { success = false, message = result.ErrorMessage }); } Response.Headers["Cache-Control"] = "private, no-store, max-age=0"; Response.Headers["Pragma"] = "no-cache"; Response.Headers["X-Content-Type-Options"] = "nosniff"; return PhysicalFile(result.FilePath!, "image/jpeg"); } } /* ===================================================================== FILE: src/Server/ClassNotify.Server/Program.cs SIZE: 14398 chars ===================================================================== */ using System.Net; using System.Security.Claims; using System.Text; using System.Threading.RateLimiting; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Microsoft.Extensions.Options; using Serilog; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.Console() .CreateLogger(); try { var builder = WebApplication.CreateBuilder(args); builder.Host.UseSerilog(); builder.Services.AddControllers(); builder.Services.AddSignalR(); // 1. PostgreSQL EF Core DbContext var defaultConn = builder.Configuration.GetConnectionString("DefaultConnection") ?? Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection") ?? "Host=127.0.0.1;Port=5432;Database=classnotify;Username=classnotify;Password=CHANGEME_DEV;"; builder.Services.AddDbContext(options => { options.UseNpgsql(defaultConn); }); // 2. Data Protection for Encrypted Recoverable Device Tokens var keysPath = OperatingSystem.IsLinux() ? "/var/lib/classnotify/keys" : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "keys"); if (!Directory.Exists(keysPath)) { Directory.CreateDirectory(keysPath); } builder.Services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(keysPath)) .SetApplicationName("ClassNotify"); // 3. ASP.NET Core PasswordHasher builder.Services.AddSingleton, PasswordHasher>(); // 4. JWT Options Binding & Strict Production Guard builder.Services.Configure(builder.Configuration.GetSection("Jwt")); var jwtOptions = builder.Configuration.GetSection("Jwt").Get() ?? new JwtOptions(); if (builder.Environment.IsProduction()) { if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || Encoding.UTF8.GetByteCount(jwtOptions.SigningKey) < 64) { throw new InvalidOperationException("Production Guard: Jwt__SigningKey is missing or has insufficient length (minimum 64 bytes required in Production). Refusing to start."); } if (string.IsNullOrWhiteSpace(jwtOptions.Issuer)) { throw new InvalidOperationException("Production Guard: Jwt__Issuer is missing. Refusing to start."); } if (string.IsNullOrWhiteSpace(jwtOptions.Audience)) { throw new InvalidOperationException("Production Guard: Jwt__Audience is missing. Refusing to start."); } } else { // Non-production fallback for design-time / local dev if unconfigured if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || Encoding.UTF8.GetByteCount(jwtOptions.SigningKey) < 32) { jwtOptions.SigningKey = "DEV_ONLY_INSECURE_SIGNING_KEY_FOR_LOCAL_TESTING_PURPOSES_ONLY_MIN_64_BYTES_LONG_!"; } if (string.IsNullOrWhiteSpace(jwtOptions.Issuer)) jwtOptions.Issuer = "ClassNotify.Server"; if (string.IsNullOrWhiteSpace(jwtOptions.Audience)) jwtOptions.Audience = "ClassNotify.Clients"; } builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); // 5. JWT Authentication with Strict Validation builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { // Support SignalR query string token for WebSocket connections options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/teacher") || path.StartsWithSegments("/hubs/device"))) { context.Token = accessToken; } return Task.CompletedTask; }, OnTokenValidated = async context => { var userId = context.Principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value; var tenantId = context.Principal?.FindFirst("tenant_id")?.Value; if (string.IsNullOrEmpty(userId)) { context.Fail("Invalid token claims: missing NameIdentifier."); return; } var dbContext = context.HttpContext.RequestServices.GetRequiredService(); var user = await dbContext.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == userId); if (user == null || user.IsLocked) { context.Fail("User account has been locked or deactivated."); return; } var tokenVersionClaim = context.Principal?.FindFirst("token_version")?.Value; if (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(); // Database Initialization & One-Time JSON Migration using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); try { if (db.Database.IsRelational()) { await db.Database.MigrateAsync(); } await DbInitializer.InitializeAsync(db, app.Environment, app.Configuration, app.Logger); await JsonMigrationService.MigrateAsync(db, null, app.Logger); } catch (Exception ex) { app.Logger.LogError(ex, "Error during database initialization or JSON migration."); throw; } } // Serve React SPA static files from wwwroot app.UseDefaultFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthentication(); app.UseAuthorization(); app.UseRateLimiter(); app.MapControllers(); app.MapHub("/hubs/device"); app.MapHub("/hubs/teacher"); // Dedicated Real PostgreSQL Health Check Endpoint app.MapGet("/api/health", async (ClassNotifyDbContext dbContext) => { bool dbOk = false; string? dbError = null; try { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); dbOk = await dbContext.Database.CanConnectAsync(cts.Token); if (dbOk) { await dbContext.Database.ExecuteSqlRawAsync("SELECT 1", cts.Token); } } catch (Exception ex) { dbError = ex.Message; } var status = dbOk ? "Healthy" : "Degraded"; var result = new { service = "ClassNotify Commercial Server (ASP.NET Core on Linux)", version = "2.1.0", status = status, database = dbOk ? "Connected" : "Disconnected", databaseError = dbError, hubs = new[] { "/hubs/device", "/hubs/teacher" } }; return dbOk ? Results.Ok(result) : Results.Json(result, statusCode: 503); }); // Fallback to index.html for React SPA client-side routing app.MapFallbackToFile("index.html"); app.Run(); } catch (Exception ex) { Log.Fatal(ex, "ClassNotify Server terminated unexpectedly."); } finally { Log.CloseAndFlush(); } namespace ClassNotify.Server { public partial class Program { } } /* ===================================================================== FILE: src/Windows/ClassNotify.Client/Services/SimpleVisualReceipt.cs SIZE: 4106 chars ===================================================================== */ using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Windows; namespace ClassNotify.Client.Services { public static class SimpleVisualReceipt { public static byte[]? Capture(Window window) { try { if (window == null || !window.IsLoaded || window.ActualWidth <= 0 || window.ActualHeight <= 0) { return null; } // 1. Get physical screen bounds using PointToScreen (DPI-aware) System.Windows.Point topLeft = window.PointToScreen(new System.Windows.Point(0, 0)); System.Windows.Point bottomRight = window.PointToScreen(new System.Windows.Point(window.ActualWidth, window.ActualHeight)); int x = (int)Math.Round(topLeft.X); int y = (int)Math.Round(topLeft.Y); int width = (int)Math.Round(bottomRight.X - topLeft.X); int height = (int)Math.Round(bottomRight.Y - topLeft.Y); if (width <= 0 || height <= 0) { return null; } // 2. Capture the window area from screen using var sourceBmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); using (var g = Graphics.FromImage(sourceBmp)) { g.CopyFromScreen(x, y, 0, 0, new System.Drawing.Size(width, height), CopyPixelOperation.SourceCopy); } // 3. Proportional resize if wider than 800px Bitmap finalBmp = sourceBmp; bool isResized = false; if (width > 800) { int targetWidth = 800; int targetHeight = (int)Math.Max(1, Math.Round((double)height * 800 / width)); var resizedBmp = new Bitmap(targetWidth, targetHeight, PixelFormat.Format24bppRgb); using (var g = Graphics.FromImage(resizedBmp)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(sourceBmp, 0, 0, targetWidth, targetHeight); } finalBmp = resizedBmp; isResized = true; } try { // 4. Encode as JPEG with Quality = 60 var jpegEncoder = ImageCodecInfo.GetImageEncoders() .FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid); if (jpegEncoder == null) return null; var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 60L); using var ms = new MemoryStream(); finalBmp.Save(ms, jpegEncoder, encoderParameters); byte[] bytes = ms.ToArray(); // Verify size within 512 KiB and valid JPEG magic if (bytes.Length > 512 * 1024) { return null; } if (bytes.Length >= 4 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[bytes.Length - 2] == 0xFF && bytes[bytes.Length - 1] == 0xD9) { return bytes; } return null; } finally { if (isResized) { finalBmp.Dispose(); } } } catch { // Fail silent: visual receipt must never throw or disrupt client return null; } } } } /* ===================================================================== FILE: src/Windows/ClassNotify.Client/Services/IpcClient.cs SIZE: 12844 chars ===================================================================== */ using System.Collections.Concurrent; using System.IO; using System.IO.Pipes; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Ipc; using ClassNotify.Shared.Models; using ClassNotify.Shared.Services; namespace ClassNotify.Client.Services { public class IpcClient { private readonly string _pipeName; private readonly Dispatcher _dispatcher; private NamedPipeClientStream? _pipeStream; private StreamWriter? _writer; private MainWindow? _currentWindow; private static readonly ClientNotificationDeduplicator _deduplicator = new(); private readonly object _pipeLock = new(); private readonly string? _ipcToken; public IpcClient(Dispatcher dispatcher, string pipeName = "ClassNotify_Ipc_Pipe", string? ipcToken = null) { _dispatcher = dispatcher; _pipeName = pipeName; _ipcToken = ipcToken ?? Environment.GetEnvironmentVariable("CLASSNOTIFY_IPC_TOKEN"); } public void Start(CancellationToken cancellationToken) { Task.Run(async () => { while (!cancellationToken.IsCancellationRequested) { try { _pipeStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); await _pipeStream.ConnectAsync(5000, cancellationToken); _writer = new StreamWriter(_pipeStream, Encoding.UTF8) { AutoFlush = true }; var reader = new StreamReader(_pipeStream, Encoding.UTF8); // Send Hello handshake immediately upon connection (Protocol Version 2 with Launch Token) var helloJson = JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = _ipcToken ?? string.Empty }); await _writer.WriteLineAsync(helloJson); await _writer.FlushAsync(); while (_pipeStream.IsConnected && !cancellationToken.IsCancellationRequested) { var line = await reader.ReadLineAsync(cancellationToken); if (string.IsNullOrEmpty(line)) break; ProcessIpcMessage(line); } } catch (OperationCanceledException) { break; } catch { await Task.Delay(3000, cancellationToken); } finally { lock (_pipeLock) { _writer?.Dispose(); _writer = null; _pipeStream?.Dispose(); _pipeStream = null; } } } }, cancellationToken); } private void Log(string msg) { try { var logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "logs"); Directory.CreateDirectory(logDir); var logFile = Path.Combine(logDir, "client.log"); File.AppendAllText(logFile, $"[{DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss.fff}] [IpcClient] {msg}\r\n"); } catch { } } private void ProcessIpcMessage(string json) { try { var msg = JsonSerializer.Deserialize(json); if (msg == null) return; Log($"Received IPC command: type={msg.Type}"); if (msg.Type == IpcCommandType.Ping) { SendPong(); return; } if (msg.Type == IpcCommandType.TtsCheck) { CheckTtsAndReply(); return; } if (msg.Type == IpcCommandType.ShowNotification && !string.IsNullOrEmpty(msg.PayloadJson)) { var notification = JsonSerializer.Deserialize(msg.PayloadJson); if (notification != null) { // P1 Batch 9: Client-side idempotent duplicate suppression for at-least-once delivery if (!_deduplicator.TryProcess(notification.Id)) { Log($"[Idempotent] Notification {notification.Id} already processed. Suppressing duplicate window & TTS."); SendAck(notification.Id, notification.ClassId, AckStatus.Delivered); return; } _dispatcher.Invoke(() => { _currentWindow?.Close(); _currentWindow = new MainWindow(notification, (status) => { SendAck(notification.Id, notification.ClassId, status); }); _currentWindow.Show(); _currentWindow.Activate(); // P0-05 Fix: Report Delivered ONLY after the window is actually displayed on screen SendAck(notification.Id, notification.ClassId, AckStatus.Delivered); // P2.3: Capture visual receipt after short delay to allow UI to render var win = _currentWindow; var notifId = notification.Id; Task.Run(async () => { try { await Task.Delay(400); byte[]? jpeg = null; await _dispatcher.InvokeAsync(() => { if (win != null && win.IsLoaded) { jpeg = SimpleVisualReceipt.Capture(win); } }); if (jpeg != null && jpeg.Length > 0) { await ReportVisualReceiptAsync(notifId, jpeg); } } catch (Exception ex) { Log($"[VisualReceipt] Failed to capture/send visual receipt: {ex.Message}"); } }); }); } } } catch (Exception ex) { Log($"Error in ProcessIpcMessage: {ex}"); } } private void CheckTtsAndReply() { try { Log("Checking TTS engine availability..."); using var synth = new System.Speech.Synthesis.SpeechSynthesizer(); var voices = synth.GetInstalledVoices(); int voiceCount = voices.Count; bool available = voiceCount > 0; Log($"TTS check completed: available={available}, voiceCount={voiceCount}"); var resultDto = new TtsCheckResultDto { Available = available, VoiceCount = voiceCount }; var replyMsg = new IpcMessage { Type = IpcCommandType.TtsCheckResult, PayloadJson = JsonSerializer.Serialize(resultDto) }; lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { _writer.WriteLine(JsonSerializer.Serialize(replyMsg)); _writer.Flush(); Log("Sent TtsCheckResult to Service."); } else { Log($"Failed to send TtsCheckResult: writer={_writer != null}, stream={_pipeStream != null}, connected={_pipeStream?.IsConnected}"); } } } catch (Exception ex) { Log($"Exception in CheckTtsAndReply: {ex}"); var resultDto = new TtsCheckResultDto { Available = false, VoiceCount = 0 }; var replyMsg = new IpcMessage { Type = IpcCommandType.TtsCheckResult, PayloadJson = JsonSerializer.Serialize(resultDto) }; lock (_pipeLock) { _writer?.WriteLine(JsonSerializer.Serialize(replyMsg)); _writer?.Flush(); } } } private void SendPong() { try { lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { var pongMsg = new IpcMessage { Type = IpcCommandType.Pong, PayloadJson = DateTimeOffset.UtcNow.ToString("O") }; _writer.WriteLine(JsonSerializer.Serialize(pongMsg)); } } } catch { } } private void SendAck(string msgId, string classId, AckStatus status) { try { lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { var ack = new AckReceiptDto { MessageId = msgId, ClassId = classId, Status = status, Timestamp = DateTimeOffset.UtcNow }; var ipcMsg = new IpcMessage { Type = IpcCommandType.ReportAck, PayloadJson = JsonSerializer.Serialize(ack) }; _writer.WriteLine(JsonSerializer.Serialize(ipcMsg)); } } } catch { } } public async Task ReportVisualReceiptAsync(string notificationId, byte[] jpegBytes) { try { if (string.IsNullOrWhiteSpace(notificationId) || jpegBytes == null || jpegBytes.Length == 0) return; if (jpegBytes.Length > 512 * 1024) { Log($"[VisualReceipt] Payload exceeds 512 KiB ({jpegBytes.Length} bytes). Discarding."); return; } var dto = new VisualReceiptIpcDto { NotificationId = notificationId, JpegBytes = jpegBytes }; var ipcMsg = new IpcMessage { Type = IpcCommandType.ReportVisualReceipt, PayloadJson = JsonSerializer.Serialize(dto) }; lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { _writer.WriteLine(JsonSerializer.Serialize(ipcMsg)); _writer.Flush(); Log($"[VisualReceipt] Sent visual receipt to Service for notification {notificationId} ({jpegBytes.Length} bytes)"); } } await Task.CompletedTask; } catch (Exception ex) { Log($"[VisualReceipt] Error sending visual receipt: {ex.Message}"); } } } } /* ===================================================================== FILE: src/Windows/ClassNotify.Service/Ipc/NamedPipeServer.cs SIZE: 22274 chars ===================================================================== */ using System.Diagnostics; using System.IO.Pipes; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Text.Json; using ClassNotify.Shared.Ipc; using ClassNotify.Shared.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ClassNotify.Service.Ipc; public class NamedPipeServer { private readonly ILogger _logger; private readonly string _pipeName; private NamedPipeServerStream? _pipeStream; private StreamWriter? _writer; private readonly SemaphoreSlim _writeLock = new(1, 1); private readonly object _stateLock = new(); private volatile bool _isAuthenticated = false; private TaskCompletionSource? _ttsCheckTcs; private readonly SemaphoreSlim _ttsCheckLock = new(1, 1); private readonly object _authLock = new(); private string? _authorizedToken; private int? _authorizedPid; private uint? _authorizedSessionId; public bool HasAuthorizedClient { get { lock (_authLock) { return !string.IsNullOrEmpty(_authorizedToken) && _authorizedPid.HasValue; } } } public void SetAuthorizedClient(string token, int pid, uint sessionId) { lock (_authLock) { _authorizedToken = token; _authorizedPid = pid; _authorizedSessionId = sessionId; _logger.LogInformation("[NamedPipeServer] Registered authorized client: PID={Pid}, SessionId={SessionId}.", pid, sessionId); } } public void InvalidateAuthorization() { lock (_authLock) { _authorizedToken = null; _authorizedPid = null; _authorizedSessionId = null; _isAuthenticated = false; _logger.LogInformation("[NamedPipeServer] Client authorization invalidated."); } } public event Action? OnAckReceived; public event Action? OnHealthReportReceived; public event Action? OnVisualReceiptReceived; public event Action? OnClientConnected; public string ExpectedProcessName { get; set; } = "ClassNotify.Client"; public bool IsClientConnected => _pipeStream != null && _pipeStream.IsConnected && _isAuthenticated; public DateTimeOffset LastClientHeartbeatUtc { get; private set; } = DateTimeOffset.MinValue; [DllImport("kernel32.dll", SetLastError = true)] private static extern uint WTSGetActiveConsoleSessionId(); [DllImport("wtsapi32.dll", SetLastError = true)] private static extern bool WTSQueryUserToken(uint sessionId, out IntPtr phToken); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out uint ClientProcessId); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetNamedPipeClientSessionId(IntPtr Pipe, out uint ClientSessionId); public NamedPipeServer(IConfiguration configuration, ILogger logger) { _logger = logger; _pipeName = configuration["ClassNotify:PipeName"] ?? "ClassNotify_Ipc_Pipe"; } public void StartListening(CancellationToken stoppingToken) { Task.Run(async () => { while (!stoppingToken.IsCancellationRequested) { try { // Step 0: Ensure an active interactive user session exists before creating the pipe var activeUser = TryGetActiveUserIdentity(); if (activeUser == null) { _logger.LogInformation("No active interactive user; delaying pipe creation."); await Task.Delay(3000, stoppingToken); continue; } _logger.LogInformation("Creating NamedPipeServerStream: {PipeName} for Active User SID: {Sid} (Session {SessionId})", _pipeName, activeUser.Value.Sid.Value, activeUser.Value.SessionId); var pipeSecurity = CreateHardenedPipeSecurity(activeUser.Value.Sid); _pipeStream = NamedPipeServerStreamAcl.Create( _pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, inBufferSize: 4096, outBufferSize: 4096, pipeSecurity); _logger.LogInformation("Waiting for WinUI 3 client connection on named pipe (timeout 5s)..."); using (var connectCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken)) { connectCts.CancelAfter(TimeSpan.FromSeconds(5)); try { await _pipeStream.WaitForConnectionAsync(connectCts.Token); } catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) { // 5s elapsed without client connection. Check if active user changed or logged off var currentActive = TryGetActiveUserIdentity(); if (currentActive == null || currentActive.Value.SessionId != activeUser.Value.SessionId || !currentActive.Value.Sid.Equals(activeUser.Value.Sid)) { _logger.LogInformation("[NamedPipeServer] Active user session changed (old: Session {OldSess}, new: {NewUser}). Recreating pipe with new ACL.", activeUser.Value.SessionId, currentActive.HasValue ? $"Session {currentActive.Value.SessionId} ({currentActive.Value.Sid})" : "None"); } _pipeStream.Dispose(); _pipeStream = null; continue; } } _isAuthenticated = false; _writer = new StreamWriter(_pipeStream, Encoding.UTF8) { AutoFlush = true }; var reader = new StreamReader(_pipeStream, Encoding.UTF8); // Step 1: Enforce Hello Handshake as the very first message var handshakeLine = await reader.ReadLineAsync(stoppingToken); if (string.IsNullOrEmpty(handshakeLine)) { _logger.LogWarning("[NamedPipeServer] Client disconnected without sending handshake."); continue; } if (!ValidateHandshake(handshakeLine, _pipeStream.SafePipeHandle.DangerousGetHandle())) { _logger.LogWarning("[NamedPipeServer] Invalid or unauthorized handshake received. Disconnecting client."); continue; } _isAuthenticated = true; _logger.LogInformation("[NamedPipeServer] client reconnected and authenticated via handshake"); LastClientHeartbeatUtc = DateTimeOffset.UtcNow; OnClientConnected?.Invoke(); // Step 2: Main message loop while (_pipeStream.IsConnected && !stoppingToken.IsCancellationRequested) { var line = await reader.ReadLineAsync(stoppingToken); if (string.IsNullOrEmpty(line)) break; HandleClientMessage(line); } } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogError(ex, "Named Pipe server encountered an error. Recreating pipe..."); await Task.Delay(2000, stoppingToken); } finally { await _writeLock.WaitAsync(CancellationToken.None); try { _isAuthenticated = false; _writer?.Dispose(); _writer = null; _pipeStream?.Dispose(); _pipeStream = null; } finally { _writeLock.Release(); } } } }, stoppingToken); } private PipeSecurity CreateHardenedPipeSecurity(SecurityIdentifier userSid) { var pipeSecurity = new PipeSecurity(); // 1. LocalSystem: FullControl pipeSecurity.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); // 2. Administrators: FullControl pipeSecurity.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), PipeAccessRights.FullControl, AccessControlType.Allow)); // 3. Active Interactive User: ReadWrite (strictly restrict to current active session user) pipeSecurity.AddAccessRule(new PipeAccessRule( userSid, PipeAccessRights.ReadWrite, AccessControlType.Allow)); _logger.LogInformation("[NamedPipeServer] Pipe ACL configured for Active User SID: {Sid}", userSid.Value); return pipeSecurity; } private (uint SessionId, SecurityIdentifier Sid)? TryGetActiveUserIdentity() { uint activeSessionId = WTSGetActiveConsoleSessionId(); if (activeSessionId != 0xFFFFFFFF && WTSQueryUserToken(activeSessionId, out IntPtr token)) { try { using var identity = new WindowsIdentity(token); if (identity.User != null) { return (activeSessionId, identity.User); } } finally { CloseHandle(token); } } for (uint s = 1; s <= 32; s++) { if (WTSQueryUserToken(s, out IntPtr userToken)) { try { using var identity = new WindowsIdentity(userToken); if (identity.User != null) { return (s, identity.User); } } finally { CloseHandle(userToken); } } } try { var currentUser = WindowsIdentity.GetCurrent().User; if (currentUser != null) { uint currentSession = (uint)Process.GetCurrentProcess().SessionId; return (currentSession, currentUser); } } catch { } return null; } private bool ValidateHandshake(string line, IntPtr pipeHandle) { try { // 1. Query Win32 client PID if (!GetNamedPipeClientProcessId(pipeHandle, out uint clientPid) || clientPid == 0) { _logger.LogWarning("[NamedPipeServer] SECURITY: Failed to obtain client PID from named pipe handle."); return false; } // 2. Query Win32 client Session ID if (!GetNamedPipeClientSessionId(pipeHandle, out uint clientSessionId)) { _logger.LogWarning("[NamedPipeServer] SECURITY: Failed to obtain client Session ID from named pipe handle."); return false; } // 3. Verify process name string procName = string.Empty; try { using var proc = Process.GetProcessById((int)clientPid); procName = proc.ProcessName; } catch (Exception ex) { _logger.LogWarning(ex, "[NamedPipeServer] SECURITY: Unable to inspect client process PID={Pid}.", clientPid); return false; } if (!procName.Equals(ExpectedProcessName, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("[NamedPipeServer] SECURITY: Connecting process '{Name}' (PID={Pid}) is not {Expected}.", procName, clientPid, ExpectedProcessName); return false; } // 4. Validate handshake JSON payload using var doc = JsonDocument.Parse(line); var root = doc.RootElement; if (!root.TryGetProperty("type", out var typeElem) || typeElem.GetString() != "hello" || !root.TryGetProperty("client", out var clientElem) || clientElem.GetString() != "ClassNotify.Client") { _logger.LogWarning("[NamedPipeServer] SECURITY: Invalid handshake payload structure from PID={Pid}.", clientPid); return false; } if (!root.TryGetProperty("protocolVersion", out var verElem) || verElem.GetInt32() < 2) { _logger.LogWarning("[NamedPipeServer] SECURITY: Rejected handshake with protocolVersion < 2 from PID={Pid}.", clientPid); return false; } if (!root.TryGetProperty("token", out var tokenElem) || string.IsNullOrEmpty(tokenElem.GetString())) { _logger.LogWarning("[NamedPipeServer] SECURITY: Missing launch token from PID={Pid}.", clientPid); return false; } string clientToken = tokenElem.GetString()!; // 5. Verify token, PID, and Session against registered authorization lock (_authLock) { if (string.IsNullOrEmpty(_authorizedToken)) { _logger.LogWarning("[NamedPipeServer] SECURITY: No active launch authorization registered on service. Rejecting PID={Pid}.", clientPid); return false; } if (!string.Equals(_authorizedToken, clientToken, StringComparison.Ordinal)) { _logger.LogWarning("[NamedPipeServer] SECURITY: Launch token mismatch from PID={Pid}.", clientPid); return false; } if (_authorizedPid.HasValue && _authorizedPid.Value > 0 && _authorizedPid.Value != (int)clientPid) { _logger.LogWarning("[NamedPipeServer] SECURITY: Connecting PID={ActualPid} does not match expected PID={ExpectedPid}.", clientPid, _authorizedPid.Value); return false; } if (_authorizedSessionId.HasValue && _authorizedSessionId.Value != clientSessionId) { _logger.LogWarning("[NamedPipeServer] SECURITY: Connecting SessionId={ActualSession} does not match expected SessionId={ExpectedSession}.", clientSessionId, _authorizedSessionId.Value); return false; } } _logger.LogInformation("[NamedPipeServer] Client verified successfully: PID={Pid}, Session={SessionId}.", clientPid, clientSessionId); return true; } catch (Exception ex) { _logger.LogWarning(ex, "[NamedPipeServer] SECURITY: Handshake validation exception."); return false; } } private async Task SendMessageInternalAsync(IpcMessage message, CancellationToken cancellationToken = default) { if (!_isAuthenticated) { _logger.LogWarning("Cannot send message over Named Pipe: Client is not authenticated via handshake."); return false; } await _writeLock.WaitAsync(cancellationToken); try { if (_writer == null || _pipeStream == null || !_pipeStream.IsConnected) { _logger.LogWarning("Cannot send message: Named Pipe is disconnected."); return false; } var json = JsonSerializer.Serialize(message); await _writer.WriteLineAsync(json); await _writer.FlushAsync(); return true; } catch (IOException ioEx) { _logger.LogWarning(ioEx, "IOException while writing to Named Pipe. Client likely disconnected."); return false; } catch (ObjectDisposedException odEx) { _logger.LogWarning(odEx, "ObjectDisposedException while writing to Named Pipe."); return false; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error writing to Named Pipe."); return false; } finally { _writeLock.Release(); } } public async Task SendNotificationToClientAsync(NotificationDto notification) { var ipcMsg = new IpcMessage { Type = IpcCommandType.ShowNotification, PayloadJson = JsonSerializer.Serialize(notification) }; bool sent = await SendMessageInternalAsync(ipcMsg); if (sent) { _logger.LogInformation("Relayed notification {NotificationId} to WinUI 3 client via Named Pipe.", notification.Id); } return sent; } public async Task SendPingAsync() { var pingMsg = new IpcMessage { Type = IpcCommandType.Ping, PayloadJson = DateTimeOffset.UtcNow.ToString("O") }; return await SendMessageInternalAsync(pingMsg); } public async Task SendTtsCheckAsync(TimeSpan timeout) { if (!await _ttsCheckLock.WaitAsync(timeout)) { _logger.LogWarning("[NamedPipeServer] Concurrent TtsCheck request timed out waiting for lock."); return null; } try { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _ttsCheckTcs = tcs; var msg = new IpcMessage { Type = IpcCommandType.TtsCheck, PayloadJson = "{}" }; bool sent = await SendMessageInternalAsync(msg); if (!sent) { _ttsCheckTcs = null; return null; } using var cts = new CancellationTokenSource(timeout); cts.Token.Register(() => tcs.TrySetCanceled()); try { return await tcs.Task; } catch { return null; } finally { _ttsCheckTcs = null; } } finally { _ttsCheckLock.Release(); } } private void HandleClientMessage(string json) { if (!_isAuthenticated) { _logger.LogWarning("[NamedPipeServer] Ignoring message received before handshake completion."); return; } try { var msg = JsonSerializer.Deserialize(json); if (msg == null) return; // Any message from client indicates active IPC connection LastClientHeartbeatUtc = DateTimeOffset.UtcNow; switch (msg.Type) { case IpcCommandType.Pong: _logger.LogDebug("Received Pong heartbeat from client."); break; case IpcCommandType.ReportAck: if (!string.IsNullOrEmpty(msg.PayloadJson)) { var ack = JsonSerializer.Deserialize(msg.PayloadJson); if (ack != null) OnAckReceived?.Invoke(ack); } break; case IpcCommandType.HealthCheck: if (!string.IsNullOrEmpty(msg.PayloadJson)) { var report = JsonSerializer.Deserialize(msg.PayloadJson); if (report != null) OnHealthReportReceived?.Invoke(report); } break; case IpcCommandType.TtsCheckResult: _logger.LogInformation("[NamedPipeServer] Received TtsCheckResult from client: {Payload}", msg.PayloadJson); if (!string.IsNullOrEmpty(msg.PayloadJson)) { var result = JsonSerializer.Deserialize(msg.PayloadJson); if (result != null) { _ttsCheckTcs?.TrySetResult(result); } } break; case IpcCommandType.ReportVisualReceipt: if (!string.IsNullOrEmpty(msg.PayloadJson)) { var visualReceipt = JsonSerializer.Deserialize(msg.PayloadJson); if (visualReceipt != null) { OnVisualReceiptReceived?.Invoke(visualReceipt); } } break; } } catch (Exception ex) { _logger.LogError(ex, "Error processing IPC message from client: {Json}", json); } } } /* ===================================================================== FILE: src/Windows/ClassNotify.Service/Workers/SignalRWorker.cs SIZE: 32768 chars ===================================================================== */ using System.Collections.Concurrent; using System.Text.Json; using ClassNotify.Service.Ipc; using ClassNotify.Service.Services; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using ClassNotify.Shared.Services; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ClassNotify.Service.Workers; public class SignalRWorker : BackgroundService { private readonly ILogger _logger; private readonly IConfiguration _config; private readonly NamedPipeServer _pipeServer; private readonly DeviceCredentialsManager _credManager; private readonly ClientNotificationBuffer _clientNotificationBuffer = new(); private readonly DeviceCommandDeduplicator _commandDeduplicator = new( ledgerFilePath: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "command_ledger.json")); private HubConnection? _hubConnection; private readonly string _serverBaseUrl; private readonly int _heartbeatInterval; private DeviceCredentials? _credentials; public SignalRWorker( ILogger logger, IConfiguration config, NamedPipeServer pipeServer, DeviceCredentialsManager credManager) { _logger = logger; _config = config; _pipeServer = pipeServer; _credManager = credManager; var fullUrl = _config["ClassNotify:ServerUrl"] ?? "https://classnotify.paradise.eu.org/hubs/device"; // Extract base URL var uri = new Uri(fullUrl); _serverBaseUrl = $"{uri.Scheme}://{uri.Authority}"; _heartbeatInterval = int.TryParse(_config["ClassNotify:HeartbeatIntervalSeconds"], out var val) ? val : 15; _pipeServer.OnAckReceived += async (ack) => await ForwardAckToServerAsync(ack); _pipeServer.OnHealthReportReceived += async (report) => await ForwardHealthReportAsync(report); _pipeServer.OnVisualReceiptReceived += async (receipt) => await UploadVisualReceiptAsync(receipt); _pipeServer.OnClientConnected += async () => await FlushPendingNotificationsToClientAsync(); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("ClassNotify.Service initializing security & credentials..."); // 1. Start Local Named Pipe IPC Listener _pipeServer.StartListening(stoppingToken); // 2. Load Device Credentials (created by ClassNotify.Setup) _credentials = _credManager.LoadCredentials(); while (_credentials == null && !stoppingToken.IsCancellationRequested) { _logger.LogWarning("Device credentials not found. Waiting for ClassNotify Setup activation."); await Task.Delay(10000, stoppingToken); _credentials = _credManager.LoadCredentials(); } if (stoppingToken.IsCancellationRequested || _credentials == null) return; _logger.LogInformation("Device Credentials Loaded: DeviceId={DeviceId}, Tenant={TenantId}, Class={ClassDisplayName} ({ClassId})", _credentials.DeviceId, _credentials.TenantId, _credentials.ClassDisplayName, _credentials.ClassId); var hubUrl = $"{_serverBaseUrl}/hubs/device"; // 3. Configure SignalR Connection with Machine-Level Device Credentials _hubConnection = new HubConnectionBuilder() .WithUrl(hubUrl, options => { options.Headers.Add("X-Device-Id", _credentials.DeviceId); options.Headers.Add("X-Device-Token", _credentials.DeviceToken); }) .WithAutomaticReconnect(new InfiniteRetryPolicy()) .Build(); // 4. Register Server Callback Handlers _hubConnection.On("ReceiveNotification", async (notification) => { _logger.LogInformation("Received notification from cloud: {Id} (Tenant: {Tenant}) - {Message}", notification.Id, notification.TenantId, notification.Message); // P1 Batch 9 Round 3: Check SendNotificationToClientAsync return value! // If pipe disconnected mid-send (returns false) or client not connected, // DeliverOrBufferAsync safely enqueues into _clientNotificationBuffer. var delivered = await _clientNotificationBuffer.DeliverOrBufferAsync( notification, () => _pipeServer.IsClientConnected, async notif => await _pipeServer.SendNotificationToClientAsync(notif), waitAttempts: 6, delayMsBetweenAttempts: 500); if (!delivered) { _logger.LogInformation("WPF Client is not yet connected or send failed. Enqueued notification {Id} into local pending buffer (ExpiresAt: {ExpiresAt}). Retriable until client launch or TTL expiration.", notification.Id, notification.ExpiresAt); } }); _hubConnection.On("ReceiveRemoteCommand", async (cmd) => { if (cmd == null || string.IsNullOrWhiteSpace(cmd.CommandId)) { _logger.LogWarning("Received null or invalid remote command DTO"); return; } _logger.LogInformation("Received remote command: Id={CommandId}, Type={Type}, TargetDevice={Device}, Param={Param}, ExpiresAt={ExpiresAt:u}", cmd.CommandId, cmd.CommandType, cmd.DeviceId, cmd.Parameters, cmd.ExpiresAt); // 1. Device Targeting Check (device isolation fail-closed) if (!string.IsNullOrEmpty(cmd.DeviceId) && _credentials != null && !string.Equals(cmd.DeviceId, _credentials.DeviceId, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Rejecting remote command {CommandId}: targeted for {TargetDeviceId}, but this device is {CurrentDeviceId}", cmd.CommandId, cmd.DeviceId, _credentials.DeviceId); var mismatchResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials.DeviceId, Status = DeviceCommandStatuses.Failed, ResultCode = -1, ResultMessage = "Target device mismatch (wrong device ID)", Timestamp = DateTimeOffset.UtcNow }; await ForwardCommandResultToServerAsync(mismatchResult); return; } // 2. Short-lived TTL Check if (cmd.ExpiresAt <= DateTimeOffset.UtcNow) { _logger.LogWarning("Rejecting remote command {CommandId} ({Type}): expired at {ExpiresAt:u} (now is {Now:u})", cmd.CommandId, cmd.CommandType, cmd.ExpiresAt, DateTimeOffset.UtcNow); var expiredResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials?.DeviceId ?? cmd.DeviceId, Status = DeviceCommandStatuses.Expired, ResultCode = -2, ResultMessage = "Command expired before device execution", Timestamp = DateTimeOffset.UtcNow }; await ForwardCommandResultToServerAsync(expiredResult); return; } // 3. Whitelist Check if (!DeviceCommandTypes.IsSupported(cmd.CommandType)) { _logger.LogWarning("Rejecting remote command {CommandId}: unsupported/forbidden command type '{Type}'", cmd.CommandId, cmd.CommandType); var unsupportedResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials?.DeviceId ?? cmd.DeviceId, Status = DeviceCommandStatuses.Failed, ResultCode = -3, ResultMessage = $"Command type '{cmd.CommandType}' not supported or forbidden", Timestamp = DateTimeOffset.UtcNow }; await ForwardCommandResultToServerAsync(unsupportedResult); return; } // 4. Idempotency Check via Dedicated DeviceCommandDeduplicator (Fail-Closed) var claimResult = _commandDeduplicator.TryDurablyClaim(cmd.CommandId); if (claimResult != CommandClaimResult.Claimed) { if (claimResult == CommandClaimResult.StorageError) { _logger.LogError("Rejecting remote command {CommandId} ({CommandType}): Durable ledger storage failure or corrupted ledger file (fail-closed).", cmd.CommandId, cmd.CommandType); var failResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials?.DeviceId ?? cmd.DeviceId, Status = DeviceCommandStatuses.Failed, ResultCode = -5, ResultMessage = "Command rejected: Durable ledger storage failure or corrupted ledger file (fail-closed).", Timestamp = DateTimeOffset.UtcNow }; await ForwardCommandResultToServerAsync(failResult); return; } if (_commandDeduplicator.TryGetCachedResult(cmd.CommandId, out var cachedResult) && cachedResult != null) { _logger.LogInformation("Duplicate remote command {CommandId} received. Returning cached result without re-executing.", cmd.CommandId); await ForwardCommandResultToServerAsync(cachedResult); } else { _logger.LogInformation("Remote command {CommandId} is already in-flight. Ignoring duplicate dispatch.", cmd.CommandId); } return; } // 5. Whitelist Execution var sw = System.Diagnostics.Stopwatch.StartNew(); int resultCode = 0; string resultMessage = "Execution succeeded"; string status = DeviceCommandStatuses.Succeeded; try { switch (cmd.CommandType.ToLowerInvariant()) { case "selfcheck" or "self_check": var report = await ExecuteSelfCheckAsync(); await ForwardHealthReportAsync(report); resultMessage = $"Self-check completed: overall={report.OverallStatus}, diagnostic={report.DiagnosticMessage}"; _logger.LogInformation("Responded to remote SelfCheck: {Message}", resultMessage); break; case "restartclient" or "restart_client": _logger.LogInformation("Executing remote restart_client command..."); foreach (var proc in System.Diagnostics.Process.GetProcessesByName("ClassNotify.Client")) { try { proc.Kill(); } catch { } } var clientPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ClassNotify.Client.exe"); if (!System.IO.File.Exists(clientPath)) { clientPath = @"C:\Program Files\ClassNotify\Client\ClassNotify.Client.exe"; } if (!System.IO.File.Exists(clientPath)) { clientPath = @"C:\Program Files\ClassNotify\ClassNotify.Client.exe"; } if (System.IO.File.Exists(clientPath)) { _pipeServer.InvalidateAuthorization(); string launchToken = Guid.NewGuid().ToString("N"); var res = SessionLauncher.LaunchProcessInActiveUserSession(clientPath, launchToken, _logger); if (res.Success) { _pipeServer.SetAuthorizedClient(res.LaunchToken, res.Pid, res.SessionId); resultMessage = $"Client successfully launched in session {res.SessionId} (PID: {res.Pid})"; } else { status = DeviceCommandStatuses.Failed; resultCode = -10; resultMessage = "Session launch failed (active console session not found or access denied)"; } } else { status = DeviceCommandStatuses.Failed; resultCode = -11; resultMessage = "ClassNotify.Client.exe binary not found on target machine"; } break; case "reconnect": _logger.LogInformation("Executing remote Reconnect command..."); if (_hubConnection != null) { try { await _hubConnection.StopAsync(); await Task.Delay(1000); await _hubConnection.StartAsync(); status = DeviceCommandStatuses.Succeeded; resultCode = 0; resultMessage = "SignalR connection successfully re-established"; _logger.LogInformation("SignalR connection successfully re-established by remote Reconnect command"); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to re-establish SignalR connection during Reconnect command"); status = DeviceCommandStatuses.Failed; resultCode = -20; resultMessage = "SignalR reconnection failed to start"; } } else { status = DeviceCommandStatuses.Failed; resultCode = -21; resultMessage = "Hub connection instance is null"; } break; case "refreshconfig" or "refresh_config": _credentials = _credManager.LoadCredentials(); if (_credentials != null && _hubConnection?.State == HubConnectionState.Connected) { await _hubConnection.InvokeAsync("SendHeartbeat", _credentials.ClassId); } resultMessage = $"Refreshed credentials configuration for Tenant {_credentials?.TenantId}, Class {_credentials?.ClassId}"; _logger.LogInformation("{Message}", resultMessage); break; default: status = DeviceCommandStatuses.Failed; resultCode = -3; resultMessage = $"Unsupported command type '{cmd.CommandType}'"; break; } } catch (Exception ex) { _logger.LogError(ex, "Error processing remote command: {CommandId} ({Type})", cmd.CommandId, cmd.CommandType); status = DeviceCommandStatuses.Failed; resultCode = -99; resultMessage = $"Internal execution error: {ex.Message}"; } finally { sw.Stop(); } var finalResult = new DeviceCommandResultDto { CommandId = cmd.CommandId, DeviceId = _credentials?.DeviceId ?? cmd.DeviceId, Status = status, ResultCode = resultCode, ResultMessage = resultMessage, ExecutionDurationMs = sw.ElapsedMilliseconds, Timestamp = DateTimeOffset.UtcNow }; _commandDeduplicator.CompleteExecution(cmd.CommandId, finalResult); await ForwardCommandResultToServerAsync(finalResult); }); // 5. Connection Lifecycle _hubConnection.Reconnecting += error => { _logger.LogWarning(error, "SignalR connection lost. Reconnecting to {Url}...", hubUrl); return Task.CompletedTask; }; _hubConnection.Reconnected += connectionId => { _logger.LogInformation("SignalR reconnected successfully! ConnectionId: {ConnectionId}", connectionId); return Task.CompletedTask; }; _hubConnection.Closed += async error => { _logger.LogWarning(error, "SignalR connection closed permanently. Attempting background re-connection..."); while (!stoppingToken.IsCancellationRequested && _hubConnection.State != HubConnectionState.Connected) { try { await Task.Delay(5000, stoppingToken); await _hubConnection.StartAsync(stoppingToken); _logger.LogInformation("SignalR reconnected after connection was closed!"); break; } catch (Exception ex) when (!stoppingToken.IsCancellationRequested) { _logger.LogWarning("Reconnection attempt failed: {Message}. Retrying in 10s...", ex.Message); await Task.Delay(10000, stoppingToken); } } }; // 6. Connect Loop while (!stoppingToken.IsCancellationRequested) { try { _logger.LogInformation("Connecting to SignalR DeviceHub: {Url}...", hubUrl); await _hubConnection.StartAsync(stoppingToken); _logger.LogInformation("SignalR connected and device authenticated successfully!"); // Trigger initial SelfCheck and snapshot upon successful connection _ = Task.Run(async () => { try { await Task.Delay(2000, stoppingToken); var initialReport = await ExecuteSelfCheckAsync(); _logger.LogInformation("[SelfCheck] Initial health status recorded: Overall={Status}", initialReport.OverallStatus); } catch (Exception ex) { _logger.LogWarning(ex, "[SelfCheck] Initial health check failed."); } }, stoppingToken); break; } catch (Exception ex) when (!stoppingToken.IsCancellationRequested) { _logger.LogError(ex, "Failed to connect to DeviceHub. Retrying in 5 seconds..."); await Task.Delay(5000, stoppingToken); } } // 7. Heartbeat & Periodic Health Snapshot Loop var lastHealthSnapshotUtc = DateTimeOffset.MinValue; while (!stoppingToken.IsCancellationRequested) { if (_hubConnection.State == HubConnectionState.Connected) { try { await _hubConnection.InvokeAsync("SendHeartbeat", _credentials.ClassId, stoppingToken); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to send heartbeat to server."); } } if (DateTimeOffset.UtcNow - lastHealthSnapshotUtc >= TimeSpan.FromSeconds(30)) { lastHealthSnapshotUtc = DateTimeOffset.UtcNow; _ = Task.Run(async () => { try { await ExecuteSelfCheckAsync(); } catch (Exception ex) { _logger.LogDebug(ex, "[SelfCheck] Periodic health check snapshot failed."); } }, stoppingToken); } await Task.Delay(TimeSpan.FromSeconds(_heartbeatInterval), stoppingToken); } } private async Task ForwardAckToServerAsync(AckReceiptDto ack) { if (_hubConnection?.State == HubConnectionState.Connected) { try { await _hubConnection.InvokeAsync("SendAckReceipt", ack); _logger.LogInformation("Forwarded ACK to server: {MsgId} -> {Status}", ack.MessageId, ack.Status); } catch (Exception ex) { _logger.LogError(ex, "Failed to forward ACK to server: {MsgId}", ack.MessageId); } } } private async Task ForwardCommandResultToServerAsync(DeviceCommandResultDto result) { if (_hubConnection?.State == HubConnectionState.Connected) { try { await _hubConnection.InvokeAsync("ReportCommandResult", result); _logger.LogInformation("Forwarded command result to server: {CmdId} -> {Status} (Code: {Code}, {Duration}ms)", result.CommandId, result.Status, result.ResultCode, result.ExecutionDurationMs); } catch (Exception ex) { _logger.LogError(ex, "Failed to forward command result to server: {CmdId}", result.CommandId); } } else { _logger.LogWarning("Cannot forward command result for {CmdId}: SignalR connection is not connected.", result.CommandId); } } private async Task UploadVisualReceiptAsync(VisualReceiptIpcDto receipt) { if (_credentials == null || string.IsNullOrWhiteSpace(_credentials.DeviceId) || string.IsNullOrWhiteSpace(_credentials.DeviceToken)) { _logger.LogWarning("[VisualReceipt] Cannot upload receipt: Device credentials missing."); return; } if (receipt == null || string.IsNullOrWhiteSpace(receipt.NotificationId) || receipt.JpegBytes == null || receipt.JpegBytes.Length == 0) { _logger.LogWarning("[VisualReceipt] Invalid receipt payload (missing ID or empty bytes)."); return; } if (receipt.JpegBytes.Length > 512 * 1024) { _logger.LogWarning("[VisualReceipt] Payload exceeds 512 KiB ({Length} bytes). Discarding.", receipt.JpegBytes.Length); return; } var uploadUrl = $"{_serverBaseUrl}/api/device/notifications/{Uri.EscapeDataString(receipt.NotificationId)}/visual-receipt"; for (int attempt = 1; attempt <= 2; attempt++) { try { using var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; using var content = new ByteArrayContent(receipt.JpegBytes); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); using var request = new HttpRequestMessage(HttpMethod.Post, uploadUrl); request.Headers.Add("X-Device-Id", _credentials.DeviceId); request.Headers.Add("X-Device-Token", _credentials.DeviceToken); request.Content = content; var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { _logger.LogInformation("[VisualReceipt] Successfully uploaded visual receipt for notification {NotificationId} ({Bytes} bytes)", receipt.NotificationId, receipt.JpegBytes.Length); return; } var respText = await response.Content.ReadAsStringAsync(); _logger.LogWarning("[VisualReceipt] Upload attempt {Attempt} failed with status {StatusCode}: {Error}", attempt, response.StatusCode, respText); if (response.StatusCode == System.Net.HttpStatusCode.BadRequest || response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.Forbidden || response.StatusCode == System.Net.HttpStatusCode.NotFound || (int)response.StatusCode == 413 || (int)response.StatusCode == 415) { break; } } catch (Exception ex) { _logger.LogWarning(ex, "[VisualReceipt] Upload attempt {Attempt} encountered exception for notification {NotificationId}", attempt, receipt.NotificationId); } if (attempt < 2) { await Task.Delay(2000); } } } private async Task ExecuteSelfCheckAsync() { var now = DateTimeOffset.UtcNow; var report = new DeviceHealthReportDto { ClassId = _credentials?.ClassId ?? "unknown", Timestamp = now, CheckedAtUtc = now, ServiceRunning = true }; // 1. DNS check try { var host = new Uri(_serverBaseUrl).Host; var addrs = await System.Net.Dns.GetHostAddressesAsync(host); report.DnsOk = addrs.Length > 0; } catch (Exception ex) { report.DnsOk = false; _logger.LogWarning(ex, "[SelfCheck] DNS resolution failed for {Url}", _serverBaseUrl); } // 2. HTTPS health endpoint check try { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }; var resp = await http.GetAsync($"{_serverBaseUrl}/api/health"); report.HttpsOk = resp.IsSuccessStatusCode; } catch (Exception ex) { report.HttpsOk = false; _logger.LogWarning(ex, "[SelfCheck] HTTPS health check failed for {Url}/api/health", _serverBaseUrl); } // 3. SignalR connection check report.SignalROk = _hubConnection?.State == HubConnectionState.Connected; // 4. Credentials check (never log full token!) try { var creds = _credManager.LoadCredentials(); report.CredentialsOk = creds != null && !string.IsNullOrWhiteSpace(creds.DeviceId) && !string.IsNullOrWhiteSpace(creds.DeviceToken); } catch (Exception ex) { report.CredentialsOk = false; _logger.LogWarning(ex, "[SelfCheck] Credentials check failed."); } // 5. Data Directory write check try { var dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify"); if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); var testFile = Path.Combine(dataDir, $".selfcheck-{Guid.NewGuid():N}.tmp"); await File.WriteAllTextAsync(testFile, "selfcheck_write_probe"); File.Delete(testFile); report.DataDirectoryWritable = true; } catch (Exception ex) { report.DataDirectoryWritable = false; _logger.LogWarning(ex, "[SelfCheck] Data directory write test failed."); } // 6. Named Pipe & Client check report.PipeOk = _pipeServer.IsClientConnected; if (_pipeServer.LastClientHeartbeatUtc != DateTimeOffset.MinValue) { var age = now - _pipeServer.LastClientHeartbeatUtc; report.ClientHeartbeatAgeSeconds = (int)age.TotalSeconds; report.ClientConnected = report.PipeOk && (age < TimeSpan.FromSeconds(15)); } else { report.ClientHeartbeatAgeSeconds = -1; report.ClientConnected = false; } // 7. TTS check via IPC if (report.PipeOk) { var ttsResult = await _pipeServer.SendTtsCheckAsync(TimeSpan.FromSeconds(3)); report.TtsOk = ttsResult != null && ttsResult.Available; } else { report.TtsOk = false; } // 8. Overall Status calculation if (!report.CredentialsOk || !report.SignalROk) { report.OverallStatus = "Offline"; } else if (!report.TtsOk || !report.ClientConnected || !report.DataDirectoryWritable || !report.DnsOk || !report.HttpsOk) { report.OverallStatus = "Degraded"; } else { report.OverallStatus = "Healthy"; } report.DiagnosticMessage = $"Overall={report.OverallStatus}, DNS={report.DnsOk}, HTTPS={report.HttpsOk}, SignalR={report.SignalROk}, Creds={report.CredentialsOk}, Storage={report.DataDirectoryWritable}, Pipe={report.PipeOk}, Client={report.ClientConnected} (age={report.ClientHeartbeatAgeSeconds}s), TTS={report.TtsOk}"; await SaveHealthStatusAsync(report); return report; } private async Task SaveHealthStatusAsync(DeviceHealthReportDto report) { try { var dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify"); if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); var targetFile = Path.Combine(dataDir, "health_status.json"); var tmpFile = Path.Combine(dataDir, $"health_status_{Guid.NewGuid():N}.tmp"); var json = JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }); await File.WriteAllTextAsync(tmpFile, json); File.Move(tmpFile, targetFile, overwrite: true); _logger.LogDebug("[HealthStatus] Saved local health status snapshot: Overall={Status}", report.OverallStatus); } catch (Exception ex) { _logger.LogWarning(ex, "[HealthStatus] Failed to save local health status snapshot."); } } private async Task ForwardHealthReportAsync(DeviceHealthReportDto report) { if (_hubConnection?.State == HubConnectionState.Connected) { try { await _hubConnection.InvokeAsync("SendHealthReport", report); } catch (Exception ex) { _logger.LogError(ex, "Failed to forward health report to server."); } } } private async Task FlushPendingNotificationsToClientAsync() { var flushed = await _clientNotificationBuffer.FlushAsync( () => _pipeServer.IsClientConnected, async notif => await _pipeServer.SendNotificationToClientAsync(notif)); if (flushed > 0) { _logger.LogInformation("Successfully flushed {Count} pending notification(s) to connected WPF client.", flushed); } } public override async Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Stopping SignalRWorker..."); if (_hubConnection != null) { await _hubConnection.DisposeAsync(); } await base.StopAsync(cancellationToken); } private class InfiniteRetryPolicy : IRetryPolicy { public TimeSpan? NextRetryDelay(RetryContext retryContext) { if (retryContext.PreviousRetryCount == 0) return TimeSpan.Zero; if (retryContext.PreviousRetryCount == 1) return TimeSpan.FromSeconds(2); if (retryContext.PreviousRetryCount == 2) return TimeSpan.FromSeconds(5); if (retryContext.PreviousRetryCount == 3) return TimeSpan.FromSeconds(10); return TimeSpan.FromSeconds(30); // Infinite retry every 30 seconds } } } /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/types/index.ts SIZE: 3566 chars ===================================================================== */ export type UserRole = 'SuperAdmin' | 'SchoolAdmin' | 'Teacher'; export interface CurrentUser { userId: string; name: string; role: UserRole; tenantId: string; } export interface LoginResult { success: boolean; token?: string; tenantId?: string; userId?: string; fullName?: string; role?: UserRole; errorMessage?: string; } export interface AdminMetrics { totalTenants: number; totalClassrooms: number; totalDevices: number; onlineDevices: number; offlineDevices: number; todayNotifications: number; abnormalDevices: number; } export interface TenantAdmin { id: string; name: string; classroomCount: number; deviceCount: number; onlineCount: number; isActive: boolean; createdAt: string; } export interface DeviceAdmin { deviceId: string; tenantId: string; tenantName: string; classroomId: string; classroomName: string; hostname?: string; isOnline: boolean; lastHeartbeat?: string; clientVersion?: string; remoteIp?: string; serviceRunning: boolean; clientRunning: boolean; healthStatus?: string; } export interface ActivationCode { code: string; tenantId: string; tenantName: string; classroomId: string; classroomName: string; expiresAt: string; isUsed: boolean; usedAt?: string; usedByDeviceId?: string; } export interface Classroom { id: string; tenantId: string; displayName: string; grade?: string; roomNumber?: string; } export interface TeacherUser { id: string; username: string; fullName: string; role: string; } export interface NotificationReceiptView { deviceId: string; status: string; displayedAt?: string; visualReceiptState: 'None' | 'Available' | 'Expired'; visualReceiptCapturedAt?: string; visualReceiptExpiresAt?: string; } export interface NotificationRecord { id: string; tenantId: string; classId: string; className: string; senderName: string; message: string; priority: string; createdAt: string; status: 'Sent' | 'Delivered' | 'Acknowledged' | 'Timeout' | 'Failed'; confirmedAt?: string; receipts?: NotificationReceiptView[]; } export interface SendNotificationPayload { classId: string; studentName?: string; title: string; message: string; type: number; // 0=Call, 1=Broadcast, 2=Urgent voice: boolean; shake: boolean; durationSeconds: number; } export interface UserAdmin { id: string; tenantId: string; tenantName: string; username: string; fullName: string; role: string; isLocked: boolean; createdAt: string; lastLoginAt?: string; } export interface CreateUserAdminRequest { tenantId: string; username: string; password: string; fullName: string; role: string; } export interface CreateTenantRequest { id: string; name: string; } export interface UpdateTenantRequest { name: string; isActive: boolean; } export interface UpdateDeviceRequest { hostname?: string; classroomId?: string; } export interface EmergencyBroadcastRequest { tenantId?: string; title: string; message: string; voice: boolean; shake: boolean; durationSeconds: number; } export interface SystemHealth { status: string; databaseConnected: boolean; databaseLatencyMs: number; activeSignalRConnections: number; onlineDevices: number; serverTime: string; uptime: string; memoryUsedBytes: number; } export interface AdminAuditLog { id: string; occurredAt: string; actorUsername: string; actorRole: string; action: string; targetType: string; targetId: string; details?: string; ipAddress?: string; } /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/api/client.ts SIZE: 8521 chars ===================================================================== */ import { AdminMetrics, TenantAdmin, DeviceAdmin, ActivationCode, Classroom, TeacherUser, NotificationRecord, SendNotificationPayload, LoginResult, CurrentUser, UserAdmin, CreateUserAdminRequest, CreateTenantRequest, UpdateTenantRequest, UpdateDeviceRequest, EmergencyBroadcastRequest, SystemHealth, AdminAuditLog } from '../types'; import { sessionManager } from '../realtime/SessionManager'; const API_BASE = '/api'; export function getToken(): string | null { return localStorage.getItem('classnotify_token'); } export function setToken(token: string) { localStorage.setItem('classnotify_token', token); } export function clearToken() { localStorage.removeItem('classnotify_token'); localStorage.removeItem('classnotify_user'); } async function request(endpoint: string, options: RequestInit = {}): Promise { const token = getToken(); const headers: Record = { 'Content-Type': 'application/json', ...(options.headers as Record), }; if (token) { headers['Authorization'] = `Bearer ${token}`; } const res = await fetch(`${API_BASE}${endpoint}`, { ...options, headers, }); if (res.status === 401) { clearToken(); sessionManager.notifySessionExpired('未授权或登录已过期,请重新登录'); throw new Error('未授权或登录已过期,请重新登录'); } if (!res.ok) { let errorMsg = `请求失败 (${res.status})`; try { const err = await res.json(); errorMsg = err.message || err.errorMessage || errorMsg; } catch { // ignore json parse error } throw new Error(errorMsg); } return res.json() as Promise; } export const api = { // Auth login: (username: string, password: string): Promise => request('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }), }), getMe: (): Promise => request('/auth/me'), // SuperAdmin getAdminMetrics: (): Promise => request('/admin/metrics'), getTenants: (): Promise => request('/admin/tenants'), getAllDevices: (): Promise => request('/admin/devices'), sendDeviceCommand: (deviceId: string, command: string, parameters?: string) => request<{ success: boolean; message: string }>(`/admin/devices/${deviceId}/command`, { method: 'POST', body: JSON.stringify({ command, parameters }), }), getAdminActivationCodes: (): Promise => request('/admin/activation-codes'), getAdminClasses: (tenantId: string): Promise => request(`/admin/classes?tenantId=${encodeURIComponent(tenantId)}`), generateAdminCode: (tenantId: string, classId: string) => request<{ success: boolean; code: string; message: string }>( `/admin/activation-codes?tenantId=${encodeURIComponent(tenantId)}&classId=${encodeURIComponent(classId)}`, { method: 'POST' } ), getAdminNotifications: (limit = 50): Promise => request(`/admin/notifications?limit=${limit}`), // Tenant Management createTenant: (dto: CreateTenantRequest): Promise => request('/admin/tenants', { method: 'POST', body: JSON.stringify(dto), }), updateTenant: (tenantId: string, dto: UpdateTenantRequest): Promise => request(`/admin/tenants/${encodeURIComponent(tenantId)}`, { method: 'PATCH', body: JSON.stringify(dto), }), // User Management getUsers: (tenantId?: string, role?: string): Promise => { const params = new URLSearchParams(); if (tenantId) params.append('tenantId', tenantId); if (role) params.append('role', role); const qs = params.toString(); return request(`/admin/users${qs ? `?${qs}` : ''}`); }, createUser: (dto: CreateUserAdminRequest): Promise => request('/admin/users', { method: 'POST', body: JSON.stringify(dto), }), resetPassword: (userId: string, newPassword: string) => request<{ success: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}/reset-password`, { method: 'POST', body: JSON.stringify({ newPassword }), }), setUserLock: (userId: string, isLocked: boolean) => request<{ success: boolean; isLocked: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}/lock`, { method: 'POST', body: JSON.stringify({ isLocked }), }), deleteUser: (userId: string) => request<{ success: boolean; message: string }>(`/admin/users/${encodeURIComponent(userId)}`, { method: 'DELETE', }), // Device Extensions updateDevice: (deviceId: string, dto: UpdateDeviceRequest) => request<{ success: boolean; message: string }>(`/admin/devices/${encodeURIComponent(deviceId)}`, { method: 'PATCH', body: JSON.stringify(dto), }), decommissionDevice: (deviceId: string) => request<{ success: boolean; message: string }>(`/admin/devices/${encodeURIComponent(deviceId)}/decommission`, { method: 'POST', }), // Activation Code Management deleteActivationCode: (code: string) => request<{ success: boolean; message: string }>(`/admin/activation-codes/${encodeURIComponent(code)}`, { method: 'DELETE', }), // Emergency Broadcast sendEmergencyBroadcast: (dto: EmergencyBroadcastRequest) => request<{ success: boolean; dispatchedCount: number; targetSchools: number; message: string }>('/admin/broadcasts', { method: 'POST', body: JSON.stringify(dto), }), // System Health & Audit getSystemHealth: (): Promise => request('/admin/system/health'), getAuditLogs: (limit = 100): Promise => request(`/admin/audit-logs?limit=${limit}`), // School Admin getSchoolOverview: (): Promise<{ tenantId: string; tenantName: string; classCount: number; deviceCount: number; onlineCount: number; teacherCount: number; }> => request('/school-admin/overview'), getSchoolClasses: (): Promise => request('/school-admin/classes'), createSchoolClass: (dto: { id: string; displayName: string; grade?: string; roomNumber?: string }) => request<{ success: boolean; message: string }>('/school-admin/classes', { method: 'POST', body: JSON.stringify(dto), }), getSchoolTeachers: (): Promise => request('/school-admin/teachers'), createSchoolTeacher: (dto: { username: string; password: string; fullName: string; role: string }) => request<{ success: boolean; message: string }>('/school-admin/teachers', { method: 'POST', body: JSON.stringify(dto), }), getSchoolDevices: (): Promise => request('/school-admin/devices'), getSchoolCodes: (): Promise => request('/school-admin/activation-codes'), generateSchoolCode: (classId: string) => request<{ success: boolean; code: string; message: string }>( `/school-admin/activation-codes?classId=${encodeURIComponent(classId)}`, { method: 'POST' } ), // Teacher getTeacherClasses: (): Promise => request('/notification/classes'), sendNotification: (payload: SendNotificationPayload) => request<{ success: boolean; messageId: string; className: string; message: string }>( '/notification/send', { method: 'POST', body: JSON.stringify(payload), } ), getTeacherHistory: (classId?: string, limit = 50): Promise => request( `/notification/history?${classId ? `classId=${encodeURIComponent(classId)}&` : ''}limit=${limit}` ), getVisualReceiptBlob: async (notificationId: string, deviceId: string): Promise => { const token = getToken(); const res = await fetch(`${API_BASE}/notifications/${encodeURIComponent(notificationId)}/receipts/${encodeURIComponent(deviceId)}/visual-receipt`, { headers: token ? { Authorization: `Bearer ${token}` } : {}, }); if (res.status === 410) { throw new Error('视觉回执已按24小时保存策略自动销毁'); } if (res.status === 404) { throw new Error('未找到该通知的视觉回执'); } if (!res.ok) { throw new Error(`获取视觉回执失败 (${res.status})`); } return res.blob(); }, }; /* ===================================================================== FILE: src/Web/ClassNotify.Web/src/pages/teacher/TeacherConsole.tsx SIZE: 27156 chars ===================================================================== */ import React, { useEffect, useState } from 'react'; import { api } from '../../api/client'; import { Classroom, NotificationRecord } from '../../types'; import { teacherRealtime } from '../../realtime/TeacherRealtime'; import { RealtimeStatusBadge } from '../../components/RealtimeStatusBadge'; import { Bell, Send, Volume2, Sparkles, CheckCircle2, Clock, AlertTriangle, User, Radio, Check, Loader2, RefreshCw, AlertCircle, Eye, ZoomIn, ZoomOut, X, ShieldCheck } from 'lucide-react'; function parseAckStatus(raw: number | string): 'Sent' | 'Delivered' | 'Acknowledged' | 'Timeout' | 'Failed' { if (typeof raw === 'string') { switch (raw.toLowerCase()) { case 'acknowledged': case 'confirmed': return 'Acknowledged'; case 'delivered': return 'Delivered'; case 'sent': return 'Sent'; case 'timeout': return 'Timeout'; case 'failed': return 'Failed'; default: return 'Sent'; } } switch (raw) { case 2: return 'Acknowledged'; case 1: return 'Delivered'; case 0: return 'Sent'; case 3: return 'Timeout'; case 4: return 'Failed'; default: return 'Sent'; } } export const TeacherConsole: React.FC = () => { const [classes, setClasses] = useState([]); const [selectedClassId, setSelectedClassId] = useState(''); const [studentName, setStudentName] = useState(''); const [message, setMessage] = useState(''); const [voice, setVoice] = useState(true); const [shake, setShake] = useState(true); const [isUrgent, setIsUrgent] = useState(false); const [duration, setDuration] = useState(15); const [sending, setSending] = useState(false); const [history, setHistory] = useState([]); const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(null); // Visual Receipt Modal State const [visualModalData, setVisualModalData] = useState<{ notificationId: string; deviceId: string; className: string; capturedAt?: string; } | null>(null); const [visualImageUrl, setVisualImageUrl] = useState(null); const [visualLoading, setVisualLoading] = useState(false); const [visualError, setVisualError] = useState(null); const [zoomLevel, setZoomLevel] = useState(1); const openVisualReceiptModal = async (notifId: string, deviceId: string, className: string, capturedAt?: string) => { setVisualModalData({ notificationId: notifId, deviceId, className, capturedAt }); setVisualLoading(true); setVisualError(null); setVisualImageUrl(null); setZoomLevel(1); try { const blob = await api.getVisualReceiptBlob(notifId, deviceId); const url = URL.createObjectURL(blob); setVisualImageUrl(url); } catch (err: any) { setVisualError(err?.message || '获取视觉核验图像失败'); } finally { setVisualLoading(false); } }; const closeVisualReceiptModal = () => { if (visualImageUrl) { URL.revokeObjectURL(visualImageUrl); } setVisualImageUrl(null); setVisualModalData(null); setVisualError(null); setZoomLevel(1); }; const classesRef = React.useRef(classes); useEffect(() => { classesRef.current = classes; }, [classes]); // Presets const presets = [ '请带各科作业本到办公室', '马上到操场集合整队', '课代表请到教研室领试卷', '午休时间请教室内保持安静', '请班长负责维护自习纪律', '放学后值日生留下来打扫卫生', ]; const loadClassesAndHistory = async () => { setLoading(true); setLoadError(null); try { const cls = await api.getTeacherClasses(); setClasses(cls); if (cls.length > 0 && !selectedClassId) { setSelectedClassId(cls[0].id); } const hist = await api.getTeacherHistory(undefined, 20); setHistory( hist.map((item) => ({ ...item, status: parseAckStatus(item.status), })) ); } catch (err: any) { setLoadError(err?.message || '加载班级或历史记录失败'); } finally { setLoading(false); } }; useEffect(() => { loadClassesAndHistory(); }, []); useEffect(() => { // Live ACK updates via SignalR event (No 4-second polling!) const unsubscribeAck = teacherRealtime.onAckReceiptReceived((receipt) => { setHistory((prev) => prev.map((item) => { if (item.id === receipt.messageId) { const mappedStatus = parseAckStatus(receipt.status); return { ...item, status: mappedStatus, confirmedAt: receipt.timestamp || item.confirmedAt || new Date().toISOString(), }; } return item; }) ); }); // Realtime SignalR listener for new notification broadcasts const unsubscribeBroadcast = teacherRealtime.onNewNotificationBroadcast((n) => { setHistory((prev) => { if (prev.some((item) => item.id === n.id)) { return prev; } const targetClass = classesRef.current.find((c) => c.id === n.classId); const newItem: NotificationRecord = { id: n.id, tenantId: n.tenantId, classId: n.classId, className: targetClass?.displayName || n.classId, senderName: '教师', message: n.message, priority: n.type === 2 ? 'Urgent' : 'Normal', createdAt: n.createdAt, status: 'Sent', }; return [newItem, ...prev]; }); }); return () => { unsubscribeAck(); unsubscribeBroadcast(); }; }, []); const handleSend = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedClassId || !message.trim()) return; setSending(true); try { const targetClass = classes.find((c) => c.id === selectedClassId); const title = studentName.trim() ? `🔔 老师呼叫: ${studentName.trim()}` : `📢 ${targetClass?.displayName || '班级'}通知`; const res = await api.sendNotification({ classId: selectedClassId, studentName: studentName.trim() || undefined, title, message: message.trim(), type: isUrgent ? 2 : 0, // 2=Urgent, 0=Call voice, shake, durationSeconds: duration, }); const sentMsg = message.trim(); setMessage(''); setStudentName(''); // Optimistically insert to history by messageId without full history refetch if (res?.messageId) { setHistory((prev) => { if (prev.some((item) => item.id === res.messageId)) return prev; const newRecord: NotificationRecord = { id: res.messageId, tenantId: '', classId: selectedClassId, className: targetClass?.displayName || selectedClassId, senderName: '教师', message: sentMsg, priority: isUrgent ? 'Urgent' : 'Normal', createdAt: new Date().toISOString(), status: 'Sent', }; return [newRecord, ...prev]; }); } } catch (err: any) { alert(err.message || '呼叫发送失败'); } finally { setSending(false); } }; return (

教师呼叫工作台

向指定教室大屏下发即时点呼与通知,支持语音朗读(TTS)与学生回执确认

{/* Error state */} {loadError && (
{loadError}
)}
{/* Left Form: 7 cols */}
{/* Target Class Selector */}
{classes.length === 0 ? (
未查询到可用班级,请联系学校管理员添加班级
) : (
{classes.map((cls) => { const isSelected = selectedClassId === cls.id; return ( ); })}
)}
{/* Optional Student Name */}
setStudentName(e.target.value)} placeholder="如:张三、李四(支持单人或多人)" className="w-full px-3.5 py-2.5 rounded-xl bg-slate-950 border border-slate-700/80 text-white text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all placeholder:text-slate-600" />
{/* Content / Message */}