using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Hubs; public class DeviceHub : Hub { private readonly ILogger _logger; private readonly IHubContext _teacherHub; private readonly ISecurityService _securityService; private readonly ISupportBundleDispatchNotifier? _bundleNotifier; // Track active connection -> { TenantId, ClassroomId, DeviceId } private static readonly Dictionary _connectionTenantMap = new(); public DeviceHub( ILogger logger, IHubContext teacherHub, ISecurityService securityService, ISupportBundleDispatchNotifier? bundleNotifier = null) { _logger = logger; _teacherHub = teacherHub; _securityService = securityService; _bundleNotifier = bundleNotifier; } public override async Task OnConnectedAsync() { var httpContext = Context.GetHttpContext(); var deviceId = httpContext?.Request.Headers["X-Device-Id"].FirstOrDefault() ?? httpContext?.Request.Query["device_id"].FirstOrDefault(); var deviceToken = httpContext?.Request.Headers["X-Device-Token"].FirstOrDefault() ?? httpContext?.Request.Query["device_token"].FirstOrDefault(); var clientVersion = httpContext?.Request.Headers["X-Client-Version"].FirstOrDefault() ?? "2.1.0"; var remoteIp = httpContext?.Connection.RemoteIpAddress?.ToString() ?? "127.0.0.1"; if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(deviceToken)) { _logger.LogWarning("Rejecting unauthorized device connection {ConnId}: Missing device credentials.", Context.ConnectionId); Context.Abort(); return; } var device = await _securityService.ValidateDeviceAsync(deviceId, deviceToken); if (device == null) { _logger.LogWarning("Rejecting unauthorized device connection {ConnId}: Invalid device ID or token ({DeviceId}).", Context.ConnectionId, deviceId); Context.Abort(); return; } // Add to Tenant-Isolated Groups var tenantClassGroup = $"t:{device.TenantId}:c:{device.ClassroomId}"; await Groups.AddToGroupAsync(Context.ConnectionId, tenantClassGroup); var tenantDeviceGroup = $"t:{device.TenantId}:d:{device.Id}"; await Groups.AddToGroupAsync(Context.ConnectionId, tenantDeviceGroup); await Groups.AddToGroupAsync(Context.ConnectionId, $"dev_{device.Id}"); lock (_connectionTenantMap) { _connectionTenantMap[Context.ConnectionId] = (device.TenantId, device.ClassroomId, device.Id); } // Register in SecurityService Live Registry (with physical endpoint identity) var regResult = await _securityService.RegisterDeviceConnectionAsync( Context.ConnectionId, device.Id, device.TenantId, device.ClassroomId, device.Hostname, remoteIp, clientVersion, device.InstallationId, device.HardwareComponentsHash); if (!string.IsNullOrEmpty(regResult.ReplacedConnectionId) && regResult.ReplacedConnectionId != Context.ConnectionId) { await Groups.RemoveFromGroupAsync(regResult.ReplacedConnectionId, tenantClassGroup); await Groups.RemoveFromGroupAsync(regResult.ReplacedConnectionId, tenantDeviceGroup); _logger.LogInformation("Removed replaced connection {OldConnId} from class group {Group} and device group {DevGroup}; current connection is {NewConnId}", regResult.ReplacedConnectionId, tenantClassGroup, tenantDeviceGroup, Context.ConnectionId); } _logger.LogInformation("Device {DeviceId} authenticated successfully. Joined groups {ClassGroup} and {DevGroup} at {ConnId}", device.Id, tenantClassGroup, tenantDeviceGroup, Context.ConnectionId); // Notify teachers of THIS tenant var classroom = await _securityService.GetClassroomAsync(device.TenantId, device.ClassroomId); var status = new DeviceStatusDto { DeviceId = device.Id, ClassId = device.ClassroomId, ClassName = classroom?.DisplayName ?? device.ClassroomId, Hostname = device.Hostname ?? "Classroom-PC", State = DeviceOnlineState.Online, LastHeartbeat = DateTimeOffset.UtcNow, AgentVersion = clientVersion }; await _teacherHub.Clients.Group($"t:{device.TenantId}:teachers").OnDeviceStatusChanged(status); await base.OnConnectedAsync(); // P3 License Lifecycle: Push authoritative license status to connecting device DeviceLicenseStatusDto? licStatus = null; try { licStatus = await _securityService.GetDeviceLicenseStatusAsync(device.Id); await Clients.Caller.ReceiveLicenseStatus(licStatus); _logger.LogInformation("Pushed LicenseStatus {Status} (Tier={Tier}, RemainingDays={Days}) to Device {DeviceId}", licStatus.Status, licStatus.Tier, licStatus.RemainingDays, device.Id); } catch (Exception ex) { _logger.LogError(ex, "Error pushing license status to connecting Device {DeviceId}", device.Id); } // P1 Batch 9: Catch-up pending notifications for this reconnected device (Caller unicast only) try { var pendingNotifications = await _securityService.GetPendingNotificationsForDeviceAsync(device.Id); if (pendingNotifications.Count > 0) { _logger.LogInformation("Device {DeviceId} connected with {Count} pending notification(s) to catch up.", device.Id, pendingNotifications.Count); foreach (var pending in pendingNotifications) { // If device license is expired, only dispatch Emergency/Urgent notifications! if (licStatus != null && licStatus.Status == "Expired" && pending.Type != NotificationType.Urgent) { continue; } await Clients.Caller.ReceiveNotification(pending); } } } catch (Exception ex) { _logger.LogError(ex, "Error catching up pending notifications for Device {DeviceId}", device.Id); } // P1 Batch 10: Catch-up pending commands for this reconnected device (Caller unicast only) try { var pendingCommands = await _securityService.GetPendingCommandsForDeviceAsync(device.Id); if (pendingCommands.Count > 0) { _logger.LogInformation("Device {DeviceId} connected with {Count} pending command(s) to catch up.", device.Id, pendingCommands.Count); foreach (var pendingCmd in pendingCommands) { await Clients.Caller.ReceiveRemoteCommand(pendingCmd); await _securityService.MarkCommandDispatchedAsync(pendingCmd.CommandId); } } } catch (Exception ex) { _logger.LogError(ex, "Error catching up pending commands for Device {DeviceId}", device.Id); } // Wake up support bundle dispatch worker if any pending requests exist _bundleNotifier?.Notify(); } public async Task SendAckReceipt(AckReceiptDto ack) { string? tenantId = null; string? classroomId = null; string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { tenantId = info.TenantId; classroomId = info.ClassroomId; deviceId = info.DeviceId; } } if (tenantId == null || classroomId == null || deviceId == null) { _logger.LogWarning("Rejecting ACK from unauthenticated connection {ConnId}", Context.ConnectionId); return; } // Must be current connection for this device (Blocker 1: Fail-closed termination) if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked ACK from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } // P0-11: Enforce device ACK attribution validation. // Force ClassId to match the connection's authenticated classroom (never trust client-supplied ClassId). ack.ClassId = classroomId; // Verify that this notification was actually sent to this tenant and classroom if (!await _securityService.ValidateNotificationTargetAsync(ack.MessageId, tenantId, classroomId)) { _logger.LogWarning("Spoofed or unknown ACK rejected: Message {MsgId} does not match Tenant {TenantId}, Class {ClassId} (Device {DeviceId})", ack.MessageId, tenantId, classroomId, deviceId); return; } _logger.LogInformation("ACK validated from Tenant {TenantId}, Class {ClassId} (Device {DeviceId}): Message {MsgId} -> {Status}", tenantId, classroomId, deviceId, ack.MessageId, ack.Status); // Record ACK in history (NotificationReceipt per device) await _securityService.RecordAckAsync(ack.MessageId, deviceId, ack); // Relay ONLY to teachers belonging to THIS tenant! await _teacherHub.Clients.Group($"t:{tenantId}:teachers").OnAckReceiptReceived(ack); } public async Task ReportCommandResult(DeviceCommandResultDto result) { string? tenantId = null; string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { tenantId = info.TenantId; deviceId = info.DeviceId; } } if (tenantId == null || deviceId == null) { _logger.LogWarning("Rejecting command result from unauthenticated connection {ConnId}", Context.ConnectionId); return; } if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked command result from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } // Security enforcement: force DeviceId from authenticated connection! result.DeviceId = deviceId; var recorded = await _securityService.RecordCommandResultAsync(result, deviceId, tenantId); if (recorded != null) { // Relay to teachers and administrators of THIS tenant! await _teacherHub.Clients.Group($"t:{tenantId}:teachers").OnDeviceCommandStatusChanged(recorded); } } public async Task SendHealthReport(DeviceHealthReportDto report) { string? tenantId = null; string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { tenantId = info.TenantId; deviceId = info.DeviceId; } } if (tenantId == null || deviceId == null) return; if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked health report from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } // Security requirement: Force DeviceId from authenticated connection! report.DeviceId = deviceId; await _teacherHub.Clients.Group($"t:{tenantId}:teachers").OnHealthReportReceived(report); } public async Task SendHeartbeat(string classId) { string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { deviceId = info.DeviceId; } } if (deviceId == null) { _logger.LogWarning("Rejecting heartbeat from unauthenticated connection {ConnId}", Context.ConnectionId); Context.Abort(); return; } if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked heartbeat from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } await _securityService.UpdateDeviceHeartbeatAsync(Context.ConnectionId); _logger.LogDebug("Received heartbeat from Device {DeviceId} ({ConnId})", deviceId, Context.ConnectionId); } public async Task SendHeartbeatWithReport(DeviceHeartbeatDto heartbeat) { string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { deviceId = info.DeviceId; } } if (deviceId == null) { _logger.LogWarning("Rejecting heartbeat report from unauthenticated connection {ConnId}", Context.ConnectionId); Context.Abort(); return; } if (!_securityService.IsCurrentDeviceConnection(deviceId, Context.ConnectionId)) { _logger.LogWarning("Rejecting and aborting stale/revoked heartbeat report from {ConnId} for Device {DeviceId}", Context.ConnectionId, deviceId); Context.Abort(); return; } await _securityService.UpdateDeviceHeartbeatAsync(Context.ConnectionId, heartbeat); _logger.LogDebug("Received structured heartbeat report from Device {DeviceId} ({ConnId}): Svc={ServiceVersion}, Client={ClientVersion}, Corr={CorrId}", deviceId, Context.ConnectionId, heartbeat.ServiceVersion, heartbeat.ClientVersion, heartbeat.CorrelationId); } public override async Task OnDisconnectedAsync(Exception? exception) { string? tenantId = null; string? classId = null; string? deviceId = null; lock (_connectionTenantMap) { if (_connectionTenantMap.TryGetValue(Context.ConnectionId, out var info)) { tenantId = info.TenantId; classId = info.ClassroomId; deviceId = info.DeviceId; _connectionTenantMap.Remove(Context.ConnectionId); } } var isCurrentDisconnected = await _securityService.UnregisterDeviceConnectionAsync(Context.ConnectionId); if (tenantId != null && classId != null && deviceId != null) { if (isCurrentDisconnected) { _logger.LogInformation("Device {DeviceId} disconnected for Tenant {TenantId}, Class {ClassId}", deviceId, tenantId, classId); var status = new DeviceStatusDto { DeviceId = deviceId, ClassId = classId, State = DeviceOnlineState.Offline, LastHeartbeat = DateTimeOffset.UtcNow }; await _teacherHub.Clients.Group($"t:{tenantId}:teachers").OnDeviceStatusChanged(status); } else { _logger.LogInformation("Stale connection {ConnId} disconnected for Device {DeviceId} (Tenant {TenantId}, Class {ClassId}); device is still active on newer connection. Skipping Offline status broadcast.", Context.ConnectionId, deviceId, tenantId, classId); } } await base.OnDisconnectedAsync(exception); } }