using System.Collections.Concurrent; using System.IO.Compression; using System.Net.Http.Json; using System.Text.Json; using ClassNotify.Service.Diagnostics; using ClassNotify.Service.Ipc; using ClassNotify.Service.Services; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using ClassNotify.Shared.Security; 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 readonly ISupportBundleCollector _bundleCollector; private readonly ISupportEventRecorder _eventRecorder; private readonly IHostApplicationLifetime? _hostLifetime; private readonly SemaphoreSlim _updateLock = new(1, 1); private readonly System.Threading.Channels.Channel _supportBundleChannel = System.Threading.Channels.Channel.CreateBounded(new System.Threading.Channels.BoundedChannelOptions(10) { FullMode = System.Threading.Channels.BoundedChannelFullMode.DropOldest }); private readonly ConcurrentDictionary _activeBundleOperations = new(); private HubConnection? _hubConnection; private readonly SemaphoreSlim _connectionGate = new(1, 1); private readonly ConcurrentDictionary _processedNotificationIds = new(); private CancellationTokenSource? _stoppingCts; private FileSystemWatcher? _credentialsWatcher; private readonly object _credentialsDebounceLock = new(); private CancellationTokenSource? _credentialsDebounceCts; private readonly string _serverBaseUrl; private readonly int _heartbeatInterval; private DeviceCredentials? _credentials; private DeviceLicenseStatusDto? _currentLicenseStatus; private readonly ClockTrustEvaluator _clockTrustEvaluator; // Connection Supervisor & Realtime Truth State (T76-01 ~ T76-06, T76-09) private DateTimeOffset _lastSuccessfulHeartbeatUtc = DateTimeOffset.MinValue; private bool _isRealtimeReady = false; private string _realtimeChannelState = "Disconnected"; private string _channelDetail = "等待服务启动..."; private bool _isServerReachable = false; // Turn 115 Dual-State Lifecycle & Pairing Session private int _boundTeacherCount = 0; private long _stateRevision = 1; private PairingSessionDto? _activePairingSession; private readonly object _pairingLock = new(); public SignalRWorker( ILogger logger, IConfiguration config, NamedPipeServer pipeServer, DeviceCredentialsManager credManager, ClockTrustEvaluator? clockTrustEvaluator = null, ISupportBundleCollector? bundleCollector = null, ISupportEventRecorder? eventRecorder = null, IHostApplicationLifetime? hostLifetime = null) { _logger = logger; _config = config; _pipeServer = pipeServer; _credManager = credManager; _clockTrustEvaluator = clockTrustEvaluator ?? new ClockTrustEvaluator(new LoggerFactory().CreateLogger()); _eventRecorder = eventRecorder ?? new ClassNotify.Service.Diagnostics.SupportEventRecorder(); _bundleCollector = bundleCollector ?? new ClassNotify.Service.Diagnostics.SupportBundleCollector(_eventRecorder, new LoggerFactory().CreateLogger()); _hostLifetime = hostLifetime; 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(); if (_currentLicenseStatus == null) { LoadLicenseLease(); } if (_currentLicenseStatus != null) { await _pipeServer.SendLicenseStatusToClientAsync(_currentLicenseStatus); } }; _pipeServer.OnRenewRequested += async (code) => await ExecuteLicenseRenewalAsync(code); _pipeServer.OnActivateRequested += async (dto) => await ExecuteLicenseActivationAsync(dto); _pipeServer.OnUpdateClassNameRequested += async (dto) => await ExecuteUpdateClassNameAsync(dto); _pipeServer.OnRequestPairingMode += async () => await ExecuteRequestPairingModeAsync(); _pipeServer.OnRequestPairingSession += async (purpose) => await ExecuteRequestPairingSessionAsync(purpose); _pipeServer.OnGetClientStateRequested += async () => await Task.FromResult(BuildClientStateSnapshot()); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); _logger.LogInformation("ClassNotify.Service initializing security & credentials..."); // Start Background Support Bundle Processing Loop (P2.5 RC1-3 Phase 2) _ = ProcessSupportBundleQueueAsync(stoppingToken); // 1. Start Local Named Pipe IPC Listener _pipeServer.StartListening(stoppingToken); // 2. Load Device Credentials (created by ClassNotify.Setup or auto-bootstrapped) _credentials = _credManager.LoadCredentials(); if (_credentials == null) { _logger.LogInformation("No local credentials found. Attempting automatic device bootstrap from server..."); try { var bootRes = await BootstrapDeviceFromServerAsync(stoppingToken); if (bootRes.Success) { _logger.LogInformation("Automatic device bootstrap succeeded on startup."); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to bootstrap device on startup, will retry in background."); } } while (_credentials == null && !stoppingToken.IsCancellationRequested) { _logger.LogWarning("Device credentials not found. Waiting for server bootstrap or manual activation..."); try { await Task.Delay(5000, stoppingToken); var bootRes = await BootstrapDeviceFromServerAsync(stoppingToken); if (bootRes.Success) break; } catch (OperationCanceledException) { break; } catch (Exception ex) { _logger.LogDebug(ex, "Bootstrap retry failed: {Message}", ex.Message); } _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); // P3 License Lifecycle: Load cached license lease from disk immediately LoadLicenseLease(); // Turn 73 Hardening: Monitor local credentials file changes to proactively trigger SignalR rebind try { var credsDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify"); if (Directory.Exists(credsDir)) { _credentialsWatcher = new FileSystemWatcher(credsDir, "device_credentials.json") { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size, EnableRaisingEvents = true }; void TriggerCredentialsRebind(object sender, FileSystemEventArgs e) { lock (_credentialsDebounceLock) { _credentialsDebounceCts?.Cancel(); _credentialsDebounceCts = new CancellationTokenSource(); var token = _credentialsDebounceCts.Token; _ = Task.Run(async () => { try { await Task.Delay(1000, token); if (!token.IsCancellationRequested) { _logger.LogInformation("[SignalR] Detected local device_credentials.json update. Invoking supervised rebind..."); await EnsureConnectedAsync("LocalCredentialsFileUpdated", token); } } catch (OperationCanceledException) { } catch (Exception ex) { _logger.LogError(ex, "[SignalR] Error during file-watcher triggered reconnect"); } }); } } _credentialsWatcher.Changed += TriggerCredentialsRebind; _credentialsWatcher.Created += TriggerCredentialsRebind; _credentialsWatcher.Renamed += (s, e) => TriggerCredentialsRebind(s, e); } } catch (Exception ex) { _logger.LogWarning(ex, "[SignalR] Failed to initialize FileSystemWatcher for credentials file"); } // 6. Supervised Connection Initialization (T76-01 / T76-02) await EnsureConnectedAsync("InitialServiceStart", stoppingToken); // 7. Heartbeat & Periodic Health Snapshot Loop var lastHealthSnapshotUtc = DateTimeOffset.MinValue; while (!stoppingToken.IsCancellationRequested) { var now = DateTimeOffset.UtcNow; if (_hubConnection != null && _hubConnection.State == HubConnectionState.Connected) { // T76-06: Heartbeat silence watchdog: if no successful heartbeat for > 45s, force reconnect! if (_lastSuccessfulHeartbeatUtc != DateTimeOffset.MinValue && (now - _lastSuccessfulHeartbeatUtc > TimeSpan.FromSeconds(45))) { _logger.LogWarning("[Watchdog] No successful heartbeat ACK for {Seconds}s (>45s). Forcing supervised reconnect...", (int)(now - _lastSuccessfulHeartbeatUtc).TotalSeconds); _isRealtimeReady = false; _realtimeChannelState = "Reconnecting"; _channelDetail = "心跳应答超时,自愈监督器介入重连..."; UpdateIpcClientSnapshot(); await EnsureConnectedAsync("HeartbeatTimeoutWatchdog", stoppingToken); } else { try { var heartbeatDto = new DeviceHeartbeatDto { ServiceVersion = typeof(SignalRWorker).Assembly.GetName().Version?.ToString(3) ?? "2.5.0", ClientVersion = "2.5.0", ProtocolVersion = 1, OsVersion = Environment.OSVersion.VersionString, Architecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), ClientProcessAvailable = _pipeServer.IsClientConnected, CorrelationId = $"hb_{Guid.NewGuid():N}"[..16] }; await _hubConnection.InvokeAsync("SendHeartbeatWithReport", heartbeatDto, stoppingToken); _lastSuccessfulHeartbeatUtc = DateTimeOffset.UtcNow; _isRealtimeReady = true; _realtimeChannelState = "Connected"; _channelDetail = $"实时通道畅通 · 最近心跳: {DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(8)):HH:mm:ss}"; } catch (Exception ex) { _logger.LogWarning(ex, "Failed to send structured heartbeat report, falling back to legacy heartbeat."); try { await _hubConnection.InvokeAsync("SendHeartbeat", _credentials?.ClassId ?? "", stoppingToken); _lastSuccessfulHeartbeatUtc = DateTimeOffset.UtcNow; _isRealtimeReady = true; _realtimeChannelState = "Connected"; _channelDetail = $"实时通道畅通 · 最近心跳: {DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(8)):HH:mm:ss}"; } catch (Exception hbEx) { _logger.LogWarning(hbEx, "[Watchdog] Both structured and legacy heartbeat failed. Triggering EnsureConnectedAsync..."); _isRealtimeReady = false; _realtimeChannelState = "Reconnecting"; _channelDetail = "发送心跳失败,自愈监督器介入重连..."; UpdateIpcClientSnapshot(); await EnsureConnectedAsync("HeartbeatSendFailed", stoppingToken); } } } } else { // T76-01: Disconnected state watchdog - self-heal immediately! _isRealtimeReady = false; _realtimeChannelState = "Disconnected"; _channelDetail = "与云端未连接,自愈监督器持续重试中..."; _logger.LogInformation("[Watchdog] Connection state is {State}. Invoking EnsureConnectedAsync...", _hubConnection?.State.ToString() ?? "Null"); UpdateIpcClientSnapshot(); await EnsureConnectedAsync("DisconnectedWatchdog", stoppingToken); } UpdateIpcClientSnapshot(); 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); } // P3 Anti-Time-Tamper & Monotonic Clock Trust Evaluation if (_currentLicenseStatus != null) { var (isUntrusted, untrustedReason) = _clockTrustEvaluator.Evaluate(_currentLicenseStatus); if (isUntrusted && _currentLicenseStatus.Status != "TimeUntrusted") { _logger.LogWarning("Switching device license status to TimeUntrusted: {Reason}", untrustedReason); _currentLicenseStatus.Status = "TimeUntrusted"; _currentLicenseStatus.CanReceiveNormalNotifications = false; _currentLicenseStatus.CanReceiveEmergencyNotifications = true; // Safety invariant L5 _currentLicenseStatus.Message = "系统时间异常,授权状态暂时无法可信验证。请开启 Windows「自动设置时间」并完成联网校时。"; await _pipeServer.SendLicenseStatusToClientAsync(_currentLicenseStatus); } } await Task.Delay(TimeSpan.FromSeconds(_heartbeatInterval), stoppingToken); } } private async Task ForwardAckToServerAsync(AckReceiptDto ack) { if (ack != null && !string.IsNullOrWhiteSpace(ack.MessageId)) { _processedNotificationIds.TryAdd(ack.MessageId, DateTimeOffset.UtcNow); } 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 ExecuteComprehensiveSelfCheckAsync(DeviceSelfCheckRequestDto? req = null) { var startedAt = DateTimeOffset.UtcNow; var selfCheckId = req?.SelfCheckId ?? $"sc_{startedAt.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24]; var correlationId = req?.CorrelationId ?? $"sc_corr_{Guid.NewGuid():N}"[..20]; var deviceId = _credentials?.DeviceId ?? "unknown"; var checks = new List(); // 1. Service daemon check checks.Add(new SelfCheckItemDto { Name = "Service", Status = SelfCheckStatus.Healthy, Code = "SERVICE_RUNNING", Summary = "Windows Service daemon running normally", LatencyMs = 0 }); // 2. SignalR connection check var signalrOk = _hubConnection?.State == HubConnectionState.Connected; checks.Add(new SelfCheckItemDto { Name = "SignalR", Status = signalrOk ? SelfCheckStatus.Healthy : SelfCheckStatus.Failed, Code = signalrOk ? "SIGNALR_CONNECTED" : "SIGNALR_DISCONNECTED", Summary = $"SignalR state: {_hubConnection?.State}", LatencyMs = null }); // 3 & 4. HTTPS and Clock Offset check SelfCheckItemDto httpsCheck; SelfCheckItemDto clockCheck; try { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(req?.TimeoutSeconds > 0 ? req.TimeoutSeconds : 5) }; if (_credentials != null) { http.DefaultRequestHeaders.Add("X-Device-Id", _credentials.DeviceId); http.DefaultRequestHeaders.Add("X-Device-Token", _credentials.DeviceToken); } var pingSw = System.Diagnostics.Stopwatch.StartNew(); var resp = await http.GetAsync($"{_serverBaseUrl}/api/device/ping"); pingSw.Stop(); var latency = pingSw.ElapsedMilliseconds; if (resp.IsSuccessStatusCode) { var content = await resp.Content.ReadAsStringAsync(); DateTimeOffset? serverUtc = null; try { using var doc = System.Text.Json.JsonDocument.Parse(content); if (doc.RootElement.TryGetProperty("serverUtc", out var prop) && prop.TryGetDateTimeOffset(out var sUtc)) { serverUtc = sUtc; } } catch { } httpsCheck = new SelfCheckItemDto { Name = "HTTPS", Status = latency < 1000 ? SelfCheckStatus.Healthy : (latency < 3000 ? SelfCheckStatus.Warning : SelfCheckStatus.Failed), Code = "HTTPS_OK", Summary = $"HTTPS ping latency: {latency}ms", LatencyMs = latency }; if (serverUtc.HasValue) { var offsetMs = Math.Abs((DateTimeOffset.UtcNow - serverUtc.Value).TotalMilliseconds); var clockStatus = offsetMs < 3000 ? SelfCheckStatus.Healthy : (offsetMs < 10000 ? SelfCheckStatus.Warning : SelfCheckStatus.Failed); var clockCode = offsetMs < 3000 ? "CLOCK_SYNCHRONIZED" : (offsetMs < 10000 ? "CLOCK_SKEW_DETECTED" : "CLOCK_DRIFT_CRITICAL"); clockCheck = new SelfCheckItemDto { Name = "Clock", Status = clockStatus, Code = clockCode, Summary = $"Clock offset: {offsetMs:F0}ms", LatencyMs = (long)offsetMs }; } else { clockCheck = new SelfCheckItemDto { Name = "Clock", Status = SelfCheckStatus.Warning, Code = "CLOCK_UNKNOWN", Summary = "Server did not provide serverUtc timestamp", LatencyMs = null }; } } else { httpsCheck = new SelfCheckItemDto { Name = "HTTPS", Status = SelfCheckStatus.Failed, Code = "HTTPS_HTTP_ERROR", Summary = $"HTTPS ping returned {(int)resp.StatusCode} {resp.StatusCode}", LatencyMs = latency }; clockCheck = new SelfCheckItemDto { Name = "Clock", Status = SelfCheckStatus.Skipped, Code = "CLOCK_SKIPPED", Summary = "Clock check skipped due to HTTPS failure", LatencyMs = null }; } } catch (Exception ex) { httpsCheck = new SelfCheckItemDto { Name = "HTTPS", Status = SelfCheckStatus.Failed, Code = "HTTPS_EXCEPTION", Summary = $"HTTPS ping error: {ex.Message}", LatencyMs = null }; clockCheck = new SelfCheckItemDto { Name = "Clock", Status = SelfCheckStatus.Skipped, Code = "CLOCK_SKIPPED", Summary = "Clock check skipped due to HTTPS exception", LatencyMs = null }; } checks.Add(httpsCheck); checks.Add(clockCheck); // 5. IPC (Named Pipe) check bool pipeConnected = _pipeServer.IsClientConnected; checks.Add(new SelfCheckItemDto { Name = "IPC", Status = pipeConnected ? SelfCheckStatus.Healthy : SelfCheckStatus.Warning, Code = pipeConnected ? "PIPE_CONNECTED" : "PIPE_DISCONNECTED", Summary = pipeConnected ? "Named Pipe connected" : "Named Pipe client not connected", LatencyMs = null }); // 6. WPF client process check var wpfProcs = System.Diagnostics.Process.GetProcessesByName("ClassNotify.Client"); bool wpfRunning = wpfProcs.Length > 0; SelfCheckStatus wpfStatus; string wpfCode; string wpfSummary; if (wpfRunning && pipeConnected) { wpfStatus = SelfCheckStatus.Healthy; wpfCode = "CLIENT_ACTIVE"; wpfSummary = "WPF client UI active and responsive"; } else if (wpfRunning && !pipeConnected) { wpfStatus = SelfCheckStatus.Warning; wpfCode = "CLIENT_UNRESPONSIVE"; wpfSummary = "WPF process running but IPC not connected"; } else { wpfStatus = SelfCheckStatus.Failed; wpfCode = "CLIENT_STOPPED"; wpfSummary = "WPF client process not running"; } checks.Add(new SelfCheckItemDto { Name = "WPF", Status = wpfStatus, Code = wpfCode, Summary = wpfSummary, LatencyMs = null }); // 7. TTS synthesis engine check SelfCheckItemDto ttsCheck; try { if (pipeConnected) { var tts = await _pipeServer.SendTtsCheckAsync(TimeSpan.FromSeconds(3)); bool ok = tts != null && tts.Available; ttsCheck = new SelfCheckItemDto { Name = "TTS", Status = ok ? SelfCheckStatus.Healthy : SelfCheckStatus.Warning, Code = ok ? "TTS_READY" : "TTS_UNAVAILABLE", Summary = ok ? $"TTS engine ready ({tts?.VoiceCount ?? 0} voices)" : "TTS engine not available on WPF client", LatencyMs = null }; } else { ttsCheck = new SelfCheckItemDto { Name = "TTS", Status = SelfCheckStatus.Warning, Code = "TTS_PIPE_OFFLINE", Summary = "WPF client not connected via IPC to probe TTS synthesizer", LatencyMs = null }; } } catch (Exception ex) { ttsCheck = new SelfCheckItemDto { Name = "TTS", Status = SelfCheckStatus.Warning, Code = "TTS_ERROR", Summary = $"TTS check error: {ex.Message}", LatencyMs = null }; } checks.Add(ttsCheck); // Calculate Overall Status SelfCheckStatus overall = SelfCheckStatus.Healthy; if (checks.Any(c => c.Status == SelfCheckStatus.Failed)) { overall = SelfCheckStatus.Failed; } else if (checks.Any(c => c.Status == SelfCheckStatus.Warning)) { overall = SelfCheckStatus.Warning; } var result = new DeviceSelfCheckResultDto { SelfCheckId = selfCheckId, CorrelationId = correlationId, DeviceId = deviceId, StartedAtUtc = startedAt, CompletedAtUtc = DateTimeOffset.UtcNow, OverallStatus = overall, Checks = checks }; // Post result back to server if (_credentials != null && !string.IsNullOrEmpty(_serverBaseUrl)) { _ = Task.Run(async () => { try { using var postClient = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; using var postReq = new HttpRequestMessage(HttpMethod.Post, $"{_serverBaseUrl}/api/device/self-check/{selfCheckId}/result"); postReq.Headers.Add("X-Device-Id", _credentials.DeviceId); postReq.Headers.Add("X-Device-Token", _credentials.DeviceToken); postReq.Content = new StringContent(JsonSerializer.Serialize(result), System.Text.Encoding.UTF8, "application/json"); var postResp = await postClient.SendAsync(postReq); _logger.LogInformation("Posted self-check result {SelfCheckId} to server: HTTP {Status}", selfCheckId, postResp.StatusCode); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to post self-check result {SelfCheckId} to server", selfCheckId); } }); } return result; } 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 => { var success = await _pipeServer.SendNotificationToClientAsync(notif); if (success && !string.IsNullOrWhiteSpace(notif.Id)) { _processedNotificationIds.TryAdd(notif.Id, DateTimeOffset.UtcNow); } return success; }); if (flushed > 0) { _logger.LogInformation("Successfully flushed {Count} pending notification(s) to connected WPF client.", flushed); } } private async Task ProcessSupportBundleQueueAsync(CancellationToken stoppingToken) { _logger.LogInformation("Support bundle background queue processor started."); try { await foreach (var cmd in _supportBundleChannel.Reader.ReadAllAsync(stoppingToken)) { if (stoppingToken.IsCancellationRequested) break; await ExecuteSupportBundleWorkflowAsync(cmd, stoppingToken); } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { // Normal shutdown } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception in SupportBundle queue processor loop."); } } private async Task ExecuteSupportBundleWorkflowAsync(GenerateSupportBundleCommand cmd, CancellationToken ct) { if (cmd == null || string.IsNullOrWhiteSpace(cmd.SupportBundleId)) return; // Check deadline if (cmd.DeadlineAtUtc <= DateTimeOffset.UtcNow) { _logger.LogWarning("Rejecting support bundle command {BundleId}: command already expired (Deadline: {Deadline:u})", cmd.SupportBundleId, cmd.DeadlineAtUtc); return; } // De-duplicate active runs on client if (!_activeBundleOperations.TryAdd(cmd.SupportBundleId, 0)) { _logger.LogWarning("Support bundle {BundleId} is already being generated/uploaded. Skipping duplicate request.", cmd.SupportBundleId); return; } string? zipFilePath = null; try { if (_credentials == null) { _logger.LogWarning("Cannot execute support bundle {BundleId}: device credentials not yet loaded.", cmd.SupportBundleId); return; } _logger.LogInformation("Starting collection and zip for support bundle {BundleId}...", cmd.SupportBundleId); var collectResult = await _bundleCollector.CollectAndZipAsync(cmd, _credentials.DeviceId, ct: ct); if (!collectResult.Success || string.IsNullOrEmpty(collectResult.ZipFilePath)) { _logger.LogWarning("Support bundle {BundleId} collection failed: {Error}", cmd.SupportBundleId, collectResult.ErrorMessage); await _bundleCollector.ReportFailureAsync(_serverBaseUrl, cmd.SupportBundleId, _credentials.DeviceId, _credentials.DeviceToken, collectResult.ErrorCode ?? SupportBundleErrorCodes.CollectionFailure, ct: ct); return; } zipFilePath = collectResult.ZipFilePath; // Upload to server _logger.LogInformation("Uploading support bundle {BundleId} ({Size} bytes) to server...", cmd.SupportBundleId, collectResult.SizeBytes); var uploaded = await _bundleCollector.UploadBundleAsync(_serverBaseUrl, cmd.SupportBundleId, _credentials.DeviceId, _credentials.DeviceToken, zipFilePath, ct: ct); if (!uploaded) { _logger.LogWarning("Support bundle {BundleId} upload failed.", cmd.SupportBundleId); } } catch (Exception ex) { _logger.LogError(ex, "Unexpected error executing support bundle {BundleId}", cmd.SupportBundleId); if (_credentials != null) { try { await _bundleCollector.ReportFailureAsync(_serverBaseUrl, cmd.SupportBundleId, _credentials.DeviceId, _credentials.DeviceToken, SupportBundleErrorCodes.CollectionFailure, ct: ct); } catch { } } } finally { _activeBundleOperations.TryRemove(cmd.SupportBundleId, out _); if (!string.IsNullOrEmpty(zipFilePath)) { try { if (System.IO.File.Exists(zipFilePath)) { System.IO.File.Delete(zipFilePath); } var dir = Path.GetDirectoryName(zipFilePath); if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir)) { Directory.Delete(dir, true); } } catch { } } } } public override async Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Stopping SignalRWorker..."); if (_hubConnection != null) { await _hubConnection.DisposeAsync(); } await base.StopAsync(cancellationToken); } private async Task HandleDeviceUpdateAsync(StartDeviceUpdateCommand cmd) { if (cmd == null || string.IsNullOrWhiteSpace(cmd.UpdateRunId)) { _logger.LogWarning("Received null or empty StartDeviceUpdateCommand."); return; } if (!await _updateLock.WaitAsync(0)) { _logger.LogWarning("Rejecting StartDeviceUpdateCommand {RunId}: another update is already in progress.", cmd.UpdateRunId); return; } try { _logger.LogInformation("Processing StartDeviceUpdateCommand: RunId={RunId}, ReleaseId={ReleaseId}, Version={Version}, Sha256={Sha256}, Deadline={Deadline:u}", cmd.UpdateRunId, cmd.ReleaseId, cmd.TargetVersion, cmd.ExpectedSha256, cmd.DeadlineAtUtc); if (_credentials == null) { _logger.LogWarning("Cannot execute update {RunId}: credentials not available.", cmd.UpdateRunId); return; } if (cmd.DeadlineAtUtc <= DateTimeOffset.UtcNow) { _logger.LogWarning("Rejecting update {RunId}: command already expired at {Deadline:u}", cmd.UpdateRunId, cmd.DeadlineAtUtc); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.TimedOut, UpdateErrorCodes.UpdateTimeout, "Update command expired before execution."); return; } // 1. Report Downloading await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Downloading); var programData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var updaterDir = Path.Combine(programData, "ClassNotify", "Updater"); var stagingDir = Path.Combine(updaterDir, "staging"); var backupsDir = Path.Combine(updaterDir, "backups", cmd.UpdateRunId); Directory.CreateDirectory(stagingDir); var stagingZip = Path.Combine(stagingDir, $"{cmd.UpdateRunId}.zip"); // 2. Download package var downloadUrl = $"{_serverBaseUrl}/api/device/update-releases/{cmd.ReleaseId}/package"; _logger.LogInformation("Downloading update package from {Url} to {StagingZip}...", downloadUrl, stagingZip); using (var http = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }) { http.DefaultRequestHeaders.Add("X-Device-Id", _credentials.DeviceId); http.DefaultRequestHeaders.Add("X-Device-Token", _credentials.DeviceToken); using var resp = await http.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead); if (!resp.IsSuccessStatusCode) { var errorBody = await resp.Content.ReadAsStringAsync(); _logger.LogError("Download failed for update {RunId}: HTTP {Code} {Body}", cmd.UpdateRunId, resp.StatusCode, errorBody); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Failed, UpdateErrorCodes.PackageNotReady, $"Download failed: HTTP {resp.StatusCode}"); return; } using var fs = new FileStream(stagingZip, FileMode.Create, FileAccess.Write, FileShare.None); await resp.Content.CopyToAsync(fs); } _logger.LogInformation("Download completed for update {RunId}. Size: {Size} bytes. Starting verification...", cmd.UpdateRunId, new FileInfo(stagingZip).Length); // 3. Verify SHA256 string actualSha256; using (var sha = System.Security.Cryptography.SHA256.Create()) using (var fs = File.OpenRead(stagingZip)) { var hashBytes = await sha.ComputeHashAsync(fs); actualSha256 = Convert.ToHexString(hashBytes).ToLowerInvariant(); } if (!string.Equals(actualSha256, cmd.ExpectedSha256, StringComparison.OrdinalIgnoreCase)) { _logger.LogError("SHA256 hash mismatch for update {RunId}: expected {Expected}, got {Actual}", cmd.UpdateRunId, cmd.ExpectedSha256, actualSha256); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Failed, UpdateErrorCodes.InvalidSha256, $"Package SHA256 mismatch: expected {cmd.ExpectedSha256}, got {actualSha256}"); try { File.Delete(stagingZip); } catch { } return; } // 4. Verify ECDSA signature var publicKey = _config["ClassNotify:UpdatePublicKey"] ?? UpdatePackageSigner.DefaultTestPublicKeyBase64; bool signatureValid = UpdatePackageSigner.VerifyHashHex(cmd.ExpectedSha256, cmd.ManifestSignature, publicKey); if (!signatureValid) { _logger.LogError("Digital signature verification failed for update {RunId}", cmd.UpdateRunId); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Failed, UpdateErrorCodes.InvalidSignature, "Digital signature verification failed."); try { File.Delete(stagingZip); } catch { } return; } // 5. Inspect package manifest & architecture try { using var archive = ZipFile.OpenRead(stagingZip); var manifestEntry = archive.GetEntry("manifest.json"); if (manifestEntry == null) { _logger.LogError("manifest.json not found in update package {RunId}", cmd.UpdateRunId); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Failed, UpdateErrorCodes.ManifestInvalid, "manifest.json missing in package."); try { File.Delete(stagingZip); } catch { } return; } using var stream = manifestEntry.Open(); var manifest = await JsonSerializer.DeserializeAsync(stream); if (manifest == null || manifest.FormatVersion != 1) { _logger.LogError("Invalid manifest format in package {RunId}", cmd.UpdateRunId); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Failed, UpdateErrorCodes.ManifestInvalid, "Invalid manifest format."); try { File.Delete(stagingZip); } catch { } return; } var currentArch = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture switch { System.Runtime.InteropServices.Architecture.X64 => "win-x64", System.Runtime.InteropServices.Architecture.Arm64 => "win-arm64", System.Runtime.InteropServices.Architecture.X86 => "win-x86", _ => "win-x64" }; if (!string.Equals(manifest.Architecture, "any", StringComparison.OrdinalIgnoreCase) && !string.Equals(manifest.Architecture, currentArch, StringComparison.OrdinalIgnoreCase)) { _logger.LogError("Package architecture mismatch in update {RunId}: expected {CurrentArch}, got {PkgArch}", cmd.UpdateRunId, currentArch, manifest.Architecture); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Failed, UpdateErrorCodes.ArchitectureMismatch, $"Package architecture '{manifest.Architecture}' is incompatible with host '{currentArch}'."); try { File.Delete(stagingZip); } catch { } return; } } catch (Exception ex) { _logger.LogError(ex, "Failed to read zip archive for update {RunId}", cmd.UpdateRunId); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Failed, UpdateErrorCodes.InvalidPackageZip, $"Corrupted zip archive: {ex.Message}"); try { File.Delete(stagingZip); } catch { } return; } // 6. Report Verified await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Verified); // 7. Report Installing and launch standalone UpdateAgent await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Installing); var agentDir = Path.Combine(programData, "ClassNotify", "Updater"); Directory.CreateDirectory(agentDir); var agentPath = Path.Combine(agentDir, "ClassNotify.UpdateAgent.exe"); if (!File.Exists(agentPath)) { var localAgent = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ClassNotify.UpdateAgent.exe"); if (File.Exists(localAgent)) { File.Copy(localAgent, agentPath, true); } } if (File.Exists(agentPath)) { var targetDir = AppDomain.CurrentDomain.BaseDirectory; var psi = new System.Diagnostics.ProcessStartInfo { FileName = agentPath, Arguments = $"--run-id \"{cmd.UpdateRunId}\" --target-dir \"{targetDir}\" --staging-zip \"{stagingZip}\" --backup-dir \"{backupsDir}\" --wait-pid {Environment.ProcessId} --service-name \"ClassNotifyService\" --server-url \"{_serverBaseUrl}\" --device-id \"{_credentials.DeviceId}\" --target-version \"{cmd.TargetVersion}\"", UseShellExecute = false, CreateNoWindow = true }; _logger.LogInformation("Launching standalone UpdateAgent: {Path} {Args}", agentPath, psi.Arguments); System.Diagnostics.Process.Start(psi); _logger.LogInformation("ClassNotify.UpdateAgent launched successfully. Stopping main service daemon to release file locks..."); _hostLifetime?.StopApplication(); } else { _logger.LogWarning("UpdateAgent binary not found at {AgentPath}. Running in simulated/direct mode.", agentPath); } } catch (Exception ex) { _logger.LogError(ex, "Unexpected error executing update {RunId}", cmd.UpdateRunId); await ReportUpdateStatusAsync(cmd.UpdateRunId, UpdateStatuses.Failed, "UpdateExecutionError", ex.Message); } finally { _updateLock.Release(); } } private async Task ReportUpdateStatusAsync(string runId, string status, string? errorCode = null, string? errorMessage = null) { if (_credentials == null || string.IsNullOrWhiteSpace(_serverBaseUrl)) return; try { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; http.DefaultRequestHeaders.Add("X-Device-Id", _credentials.DeviceId); http.DefaultRequestHeaders.Add("X-Device-Token", _credentials.DeviceToken); var req = new DeviceUpdateReportRequest { Status = status, ErrorCode = errorCode, ErrorMessage = errorMessage }; var endpoint = $"{_serverBaseUrl}/api/device/update-runs/{runId}/status"; var resp = await http.PostAsJsonAsync(endpoint, req); _logger.LogInformation("[UpdateStatus] Reported status {Status} for run {RunId} (HTTP {Code})", status, runId, (int)resp.StatusCode); } catch (Exception ex) { _logger.LogWarning(ex, "[UpdateStatus] Failed to report status {Status} for run {RunId}", status, runId); } } private async Task<(bool Success, string Message)> ExecuteLicenseRenewalAsync(string code) { if (_credentials == null) { return (false, "设备未完成初次激活,无法续期"); } try { using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; client.DefaultRequestHeaders.Add("X-Device-Id", _credentials.DeviceId); client.DefaultRequestHeaders.Add("X-Device-Token", _credentials.DeviceToken); var url = $"{_serverBaseUrl}/api/device/license/renew"; var reqObj = new { activationCode = code, reason = "Screen self-renew" }; var response = await client.PostAsJsonAsync(url, reqObj); var resStr = await response.Content.ReadAsStringAsync(); using var doc = JsonDocument.Parse(resStr); if (response.IsSuccessStatusCode) { // P3 Recovery Invariant: Immediately recover server authoritative state upon successful renewal await RecoverLicenseFromServerAsync(); var msg = doc.RootElement.TryGetProperty("message", out var msgElem) ? msgElem.GetString() : "续费成功!"; return (true, msg ?? "续费成功!"); } else { var errMsg = doc.RootElement.TryGetProperty("message", out var errElem) ? errElem.GetString() : "续费失败"; return (false, errMsg ?? "续费失败"); } } catch (Exception ex) { _logger.LogError(ex, "Exception calling renew license API"); return (false, "网络异常,无法连接到授权服务器: " + ex.Message); } } private string GetOrCreateInstallationId() { try { var dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify"); Directory.CreateDirectory(dataDir); var statePath = Path.Combine(dataDir, "installer_state.json"); if (File.Exists(statePath)) { var json = File.ReadAllText(statePath); using var doc = JsonDocument.Parse(json); if (doc.RootElement.TryGetProperty("installationId", out var elem) || doc.RootElement.TryGetProperty("InstallationId", out elem)) { var id = elem.GetString(); if (!string.IsNullOrWhiteSpace(id) && id.StartsWith("inst_") && id.Length <= 50) { return id; } } } var newId = $"inst_{Guid.NewGuid():D}"; var newJson = JsonSerializer.Serialize(new { InstallationId = newId, ActivationCompleted = false }, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllText(statePath, newJson); return newId; } catch { return $"inst_{Guid.NewGuid():D}"; } } private async Task<(bool Success, string Message, string? ClassName, string? ExpireDate)> ExecuteLicenseActivationAsync(DeviceActivationRequestDto req) { try { using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; var url = $"{_serverBaseUrl}/api/device/activate"; var maskedCode = string.IsNullOrWhiteSpace(req.ActivationCode) ? "****" : (req.ActivationCode.Length > 4 ? "****" + req.ActivationCode[^4..] : "****"); _logger.LogInformation("[Activation] Service executing activation: code='{MaskedCode}', customClassName='{Class}', url='{Url}'", maskedCode, req.CustomClassName, url); var reqObj = new { activationCode = req.ActivationCode.Trim().ToUpperInvariant(), installationId = GetOrCreateInstallationId(), hostname = Environment.MachineName, clientVersion = "2.1.0", customClassName = req.CustomClassName, hardwareComponentsHash = HardwareFingerprintProvider.GetHardwareComponentsHash(), fingerprintVersion = 1 }; var response = await client.PostAsJsonAsync(url, reqObj); var resStr = await response.Content.ReadAsStringAsync(); _logger.LogInformation("[Activation] Server HTTP {Status}: {Body}", (int)response.StatusCode, resStr); if (string.IsNullOrWhiteSpace(resStr)) { return (false, $"服务器返回空响应 (HTTP {(int)response.StatusCode})", null, null); } using var doc = JsonDocument.Parse(resStr); if (response.IsSuccessStatusCode) { var deviceId = doc.RootElement.TryGetProperty("deviceId", out var dIdElem) ? dIdElem.GetString() : null; var deviceToken = doc.RootElement.TryGetProperty("deviceToken", out var dTokElem) ? dTokElem.GetString() : null; var tenantId = doc.RootElement.TryGetProperty("tenantId", out var tElem) ? tElem.GetString() : "default"; var classId = doc.RootElement.TryGetProperty("classId", out var cElem) ? cElem.GetString() : null; var classDisplayName = doc.RootElement.TryGetProperty("classDisplayName", out var cdElem) ? cdElem.GetString() : (req.CustomClassName ?? "教学班级"); if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(deviceToken)) { return (false, "服务器返回的设备认证凭据无效", null, null); } var newCreds = new DeviceCredentials { DeviceId = deviceId, DeviceToken = deviceToken, TenantId = tenantId ?? "default", ClassId = classId ?? string.Empty, ClassDisplayName = classDisplayName ?? "教学班级", ActivatedAt = DateTimeOffset.UtcNow }; _credManager.SaveCredentials(newCreds); _credentials = newCreds; _logger.LogInformation("[Activation] Successfully activated and saved credentials for {Class}", classDisplayName); // GPT Turn 76 Protocol: Supervised immediate rebind with fresh credentials into the new tenant/classroom! _ = Task.Run(async () => await EnsureConnectedAsync("ActivationCredentialRotation", _stoppingCts?.Token ?? CancellationToken.None)); try { await RecoverLicenseFromServerAsync(); } catch { } var expireDateStr = _currentLicenseStatus?.LicensedUntilUtc?.ToOffset(TimeSpan.FromHours(8)).ToString("yyyy年M月d日") ?? "长期有效"; return (true, "激活成功", classDisplayName, expireDateStr); } else { var errMsg = doc.RootElement.TryGetProperty("errorMessage", out var errElem) ? errElem.GetString() : null; if (string.IsNullOrEmpty(errMsg)) { errMsg = doc.RootElement.TryGetProperty("message", out var mElem) ? mElem.GetString() : "激活失败,请核对激活码"; } return (false, errMsg ?? "激活失败", null, null); } } catch (HttpRequestException ex) { _logger.LogWarning(ex, "Activation network error"); return (false, "无法连接到云端服务器,请检查网络连接", null, null); } catch (Exception ex) { _logger.LogError(ex, "Activation exception"); return (false, $"激活失败: {ex.Message}", null, null); } } private async Task<(bool Success, string Message)> ExecuteUpdateClassNameAsync(UpdateClassNameRequestDto req) { if (_credentials == null || string.IsNullOrEmpty(_credentials.DeviceId) || string.IsNullOrEmpty(_credentials.DeviceToken)) { return (false, "设备尚未激活,无法修改班级名称"); } try { using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; client.DefaultRequestHeaders.Add("X-Device-Id", _credentials.DeviceId); client.DefaultRequestHeaders.Add("X-Device-Token", _credentials.DeviceToken); var url = $"{_serverBaseUrl}/api/device/class-name"; var response = await client.PutAsJsonAsync(url, new { className = req.ClassName }); var resStr = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { _credentials.ClassDisplayName = req.ClassName; _credManager.SaveCredentials(_credentials); _logger.LogInformation("[ClassName] Successfully updated class display name to '{Name}'", req.ClassName); await _pipeServer.NotifyClassDisplayNameChangedAsync(req.ClassName); return (true, "班级名称已成功更新并同步到后台"); } else { try { using var doc = JsonDocument.Parse(resStr); string? msg = doc.RootElement.TryGetProperty("message", out var m) ? m.GetString() : null; return (false, msg ?? "更新班级名称失败"); } catch { return (false, "更新班级名称失败"); } } } catch (Exception ex) { _logger.LogError(ex, "Error updating class name via server API"); return (false, $"网络请求异常: {ex.Message}"); } } private async Task<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)> BootstrapDeviceFromServerAsync(CancellationToken cancellationToken = default) { try { using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; var url = $"{_serverBaseUrl}/api/device/bootstrap"; var reqObj = new DeviceBootstrapRequestDto { HardwareComponentsHash = HardwareFingerprintProvider.GetHardwareComponentsHash(), InstallationId = GetOrCreateInstallationId(), Hostname = Environment.MachineName, ClientVersion = "2.1.0" }; var response = await client.PostAsJsonAsync(url, reqObj, cancellationToken); _isServerReachable = response.IsSuccessStatusCode; var resStr = await response.Content.ReadAsStringAsync(cancellationToken); if (response.IsSuccessStatusCode) { using var doc = JsonDocument.Parse(resStr); var deviceId = doc.RootElement.TryGetProperty("deviceId", out var dId) ? dId.GetString() : null; var deviceToken = doc.RootElement.TryGetProperty("deviceToken", out var dTok) ? dTok.GetString() : null; var tenantId = doc.RootElement.TryGetProperty("tenantId", out var tId) ? tId.GetString() : "default"; var isBound = doc.RootElement.TryGetProperty("isBound", out var ib) && ib.GetBoolean(); var pairingCode = doc.RootElement.TryGetProperty("pairingCode", out var pc) ? pc.GetString() : null; var ttl = doc.RootElement.TryGetProperty("ttlSeconds", out var ttlElem) ? ttlElem.GetInt32() : 600; var classDisplayName = doc.RootElement.TryGetProperty("classDisplayName", out var cd) ? cd.GetString() : "待绑定大屏"; if (!string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(deviceToken)) { var newCreds = new DeviceCredentials { DeviceId = deviceId, DeviceToken = deviceToken, TenantId = tenantId ?? "default", ClassId = isBound ? (classDisplayName ?? "教学班级") : "待绑定大屏", ClassDisplayName = isBound ? (classDisplayName ?? "教学班级") : "待绑定大屏", ActivatedAt = DateTimeOffset.UtcNow }; _credManager.SaveCredentials(newCreds); _credentials = newCreds; _logger.LogInformation("[Bootstrap] Successfully bootstrapped device {DeviceId} (IsBound={IsBound}, PairingCode={Code})", deviceId, isBound, pairingCode); if (isBound) { _ = Task.Run(async () => await EnsureConnectedAsync("BootstrapRebind", _stoppingCts?.Token ?? CancellationToken.None)); } UpdateIpcClientSnapshot(); return (true, pairingCode, ttl, null); } } return (false, null, 0, "引导接口返回数据格式异常"); } catch (Exception ex) { _isServerReachable = false; _logger.LogWarning("[Bootstrap] Failed to bootstrap from server: {Message}", ex.Message); return (false, null, 0, $"网络连接异常: {ex.Message}"); } } private async Task<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)> ExecuteRequestPairingModeAsync() { if (_credentials == null || string.IsNullOrEmpty(_credentials.DeviceId) || string.IsNullOrEmpty(_credentials.DeviceToken)) { var bootRes = await BootstrapDeviceFromServerAsync(); if (bootRes.Success && !string.IsNullOrEmpty(bootRes.PairingCode)) { return bootRes; } if (_credentials == null || string.IsNullOrEmpty(_credentials.DeviceId) || string.IsNullOrEmpty(_credentials.DeviceToken)) { return (false, null, 0, bootRes.ErrorMessage ?? "设备未能获取到云端凭据,请检查网络连接"); } } try { using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; client.DefaultRequestHeaders.Add("X-Device-Id", _credentials.DeviceId); client.DefaultRequestHeaders.Add("X-Device-Token", _credentials.DeviceToken); var url = $"{_serverBaseUrl}/api/device/request-pairing"; var response = await client.PostAsync(url, null); _isServerReachable = response.IsSuccessStatusCode; var resStr = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { using var doc = JsonDocument.Parse(resStr); string? code = doc.RootElement.TryGetProperty("pairingCode", out var c) ? c.GetString() : null; int ttl = doc.RootElement.TryGetProperty("ttlSeconds", out var t) ? t.GetInt32() : 600; _logger.LogInformation("[Pairing] Successfully requested pairing code {Code} for Device {DeviceId}", code, _credentials.DeviceId); return (true, code, ttl, null); } else { if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized || response.StatusCode == System.Net.HttpStatusCode.NotFound) { _logger.LogWarning("[Pairing] Received {StatusCode} requesting pairing code, attempting re-bootstrap...", response.StatusCode); var reBoot = await BootstrapDeviceFromServerAsync(); if (reBoot.Success && !string.IsNullOrEmpty(reBoot.PairingCode)) { return reBoot; } } try { using var doc = JsonDocument.Parse(resStr); string? msg = doc.RootElement.TryGetProperty("message", out var m) ? m.GetString() : null; return (false, null, 0, msg ?? $"获取配对码失败 ({(int)response.StatusCode})"); } catch { return (false, null, 0, $"获取配对码失败 ({(int)response.StatusCode})"); } } } catch (Exception ex) { _isServerReachable = false; _logger.LogError(ex, "Error requesting pairing code via server API"); return (false, null, 0, $"网络请求异常: {ex.Message}"); } } private async Task ExecuteRequestPairingSessionAsync(PairingPurpose purpose) { lock (_pairingLock) { if (_activePairingSession != null && _activePairingSession.Purpose == purpose && _activePairingSession.ExpiresAt > DateTimeOffset.UtcNow.AddSeconds(15) && !string.IsNullOrEmpty(_activePairingSession.Code)) { _logger.LogInformation("[Pairing] Reusing unexpired pairing session {Code} (Expires: {Exp})", _activePairingSession.Code, _activePairingSession.ExpiresAt); return _activePairingSession; } } var (success, code, ttl, err) = await ExecuteRequestPairingModeAsync(); lock (_pairingLock) { if (success && !string.IsNullOrEmpty(code)) { var session = new PairingSessionDto { Code = code, ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(ttl > 0 ? ttl : 600), Purpose = purpose, State = PairingSessionState.Active }; _activePairingSession = session; return session; } else { return new PairingSessionDto { Code = string.Empty, ExpiresAt = DateTimeOffset.UtcNow, Purpose = purpose, State = PairingSessionState.Failed, ErrorMessage = err ?? "获取配对码失败,请确认网络连接" }; } } } private ClientStateSnapshotDto BuildClientStateSnapshot() { if (_credentials == null) { return new ClientStateSnapshotDto { BindingState = DeviceBindingState.Unbound, ProvisioningState = "Unactivated", LicenseStatus = "Unactivated", ClassId = null, ClassDisplayName = null, ClassroomId = null, ClassroomDisplayName = null, RemainingDays = 0, CanRenew = false, CanReceiveNormalNotifications = false, CloudConnected = _isServerReachable, RealtimeChannelState = _isServerReachable ? "Ready" : "Disconnected", ChannelDetail = _isServerReachable ? "大屏已连接云端,等待绑定到工作台" : "正在尝试连接云端服务器...", BoundTeacherCount = 0, StateRevision = _stateRevision }; } bool isUnbound = string.IsNullOrWhiteSpace(_credentials.ClassId) || string.IsNullOrWhiteSpace(_credentials.DeviceId) || _credentials.ClassId == "待绑定大屏" || _credentials.ClassDisplayName == "待绑定大屏"; // T76-09: Truthful real-time state calculation (Never reports online when channel is dead or not READY) var isConnected = isUnbound ? (_isServerReachable || (_isRealtimeReady && _hubConnection?.State == HubConnectionState.Connected)) : (_isRealtimeReady && _hubConnection?.State == HubConnectionState.Connected); var isExpired = _currentLicenseStatus?.Status == "Expired" || (_currentLicenseStatus?.LicensedUntilUtc.HasValue == true && DateTimeOffset.UtcNow > _currentLicenseStatus.LicensedUntilUtc.Value); var effectiveLicenseStatus = isExpired ? "Expired" : (_currentLicenseStatus?.Status ?? "Valid"); var canReceiveNormal = !isExpired && (_currentLicenseStatus?.CanReceiveNormalNotifications ?? true); return new ClientStateSnapshotDto { BindingState = isUnbound ? DeviceBindingState.Unbound : DeviceBindingState.Bound, ProvisioningState = isUnbound ? "Unactivated" : "Activated", LicenseStatus = effectiveLicenseStatus, DeviceId = _credentials.DeviceId, TenantId = _credentials.TenantId, ClassId = isUnbound ? null : _credentials.ClassId, ClassDisplayName = isUnbound ? null : _credentials.ClassDisplayName, ClassroomId = isUnbound ? null : _credentials.ClassId, ClassroomDisplayName = isUnbound ? null : _credentials.ClassDisplayName, RemainingDays = isExpired ? 0 : (_currentLicenseStatus?.RemainingDays ?? 0), RemainingHours = isExpired ? 0 : (_currentLicenseStatus?.RemainingHours ?? 0), LicensedUntilUtc = _currentLicenseStatus?.LicensedUntilUtc, CanRenew = true, CanReceiveNormalNotifications = canReceiveNormal, CloudConnected = isConnected, RealtimeChannelState = isUnbound ? (_isServerReachable ? "Ready" : "Disconnected") : _realtimeChannelState, LastSuccessfulHeartbeatUtc = _lastSuccessfulHeartbeatUtc != DateTimeOffset.MinValue ? _lastSuccessfulHeartbeatUtc : null, ChannelDetail = isUnbound ? (_isServerReachable ? "大屏已连接云端,等待绑定到工作台" : "正在尝试连接云端服务器...") : _channelDetail, BoundTeacherCount = isUnbound ? 0 : Math.Max(1, _boundTeacherCount), StateRevision = _stateRevision }; } private void UpdateIpcClientSnapshot() { try { if (_currentLicenseStatus != null && _pipeServer.IsClientConnected) { _ = _pipeServer.SendLicenseStatusToClientAsync(_currentLicenseStatus); } } catch { } } private readonly string _licenseLeaseFilePath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "license_lease.json"); private void SaveLicenseLease(DeviceLicenseStatusDto lic) { try { var dir = Path.GetDirectoryName(_licenseLeaseFilePath); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); _clockTrustEvaluator.RecordServerTime(lic.ServerNowUtc); var json = JsonSerializer.Serialize(lic, new JsonSerializerOptions { WriteIndented = true }); var tmp = _licenseLeaseFilePath + ".tmp"; File.WriteAllText(tmp, json); File.Move(tmp, _licenseLeaseFilePath, overwrite: true); _logger.LogInformation("Saved offline license lease to {Path}", _licenseLeaseFilePath); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to save license lease file"); } } private void LoadLicenseLease() { try { if (File.Exists(_licenseLeaseFilePath)) { var json = File.ReadAllText(_licenseLeaseFilePath); var lic = JsonSerializer.Deserialize(json); if (lic != null) { _currentLicenseStatus = lic; // P3 Anti-Time-Tamper & Monotonic Clock Trust Evaluation var (isUntrusted, untrustedReason) = _clockTrustEvaluator.Evaluate(_currentLicenseStatus); if (isUntrusted) { _currentLicenseStatus.Status = "TimeUntrusted"; _currentLicenseStatus.CanReceiveNormalNotifications = false; _currentLicenseStatus.CanReceiveEmergencyNotifications = true; // Safety invariant L5 _currentLicenseStatus.Message = "系统时间异常,授权状态暂时无法可信验证。请开启 Windows「自动设置时间」并完成联网校时。"; } else { // Evaluate local offline grace / restriction if currently not connected to server var now = DateTimeOffset.UtcNow; if (lic.LicensedUntilUtc.HasValue && now > lic.LicensedUntilUtc.Value) { _currentLicenseStatus.Status = "Expired"; _currentLicenseStatus.CanReceiveNormalNotifications = false; _currentLicenseStatus.Message = $"授权已于 {lic.LicensedUntilUtc.Value:yyyy-MM-dd} 到期"; } else if (lic.OfflineGraceUntilUtc.HasValue && now > lic.OfflineGraceUntilUtc.Value) { _currentLicenseStatus.Status = "OfflineRestricted"; _currentLicenseStatus.CanReceiveNormalNotifications = false; _currentLicenseStatus.Message = "设备已超过离线容灾宽限期,请连接校园网刷新授权"; } else if (_hubConnection?.State != HubConnectionState.Connected) { _currentLicenseStatus.Status = "OfflineGrace"; _currentLicenseStatus.CanReceiveNormalNotifications = true; _currentLicenseStatus.Message = "离线容灾运行中"; } } _logger.LogInformation("Loaded cached license lease from disk: Status={Status}, OfflineGraceUntil={Grace:u}", _currentLicenseStatus.Status, _currentLicenseStatus.OfflineGraceUntilUtc); } } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to load cached license lease file"); } } public async Task RecoverLicenseFromServerAsync() { if (_credentials == null) return; try { using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; client.DefaultRequestHeaders.Add("X-Device-Id", _credentials.DeviceId); client.DefaultRequestHeaders.Add("X-Device-Token", _credentials.DeviceToken); var url = $"{_serverBaseUrl}/api/device/license"; var response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var lic = await response.Content.ReadFromJsonAsync(); if (lic != null) { _logger.LogInformation("GET /api/device/license recovered authoritative state: Status={Status}, Days={Days}, GraceUntil={Grace:u}", lic.Status, lic.RemainingDays, lic.OfflineGraceUntilUtc); _currentLicenseStatus = lic; SaveLicenseLease(lic); await _pipeServer.SendLicenseStatusToClientAsync(lic); } } else { _logger.LogWarning("GET /api/device/license returned HTTP {StatusCode}", response.StatusCode); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to recover license status via GET /api/device/license, using local lease"); } } private HubConnection CreateAndConfigureHubConnection(DeviceCredentials creds, string hubUrl) { var connection = new HubConnectionBuilder() .WithUrl(hubUrl, options => { options.Headers.Add("X-Device-Id", creds.DeviceId); options.Headers.Add("X-Device-Token", creds.DeviceToken); }) .WithAutomaticReconnect(new InfiniteRetryPolicy()) .Build(); // 4. Register Server Callback Handlers connection.On("ReceiveNotification", async (notification) => { if (notification == null || string.IsNullOrWhiteSpace(notification.Id)) return; // Turn 73 Blocker 4: Check if already completed/processed to avoid duplicate popups if (_processedNotificationIds.ContainsKey(notification.Id)) { _logger.LogInformation("Ignored already processed notification {Id} from cloud.", notification.Id); return; } // P79 Layer 2 LocalLicenseGuard: Authoritative local lease assertion if (notification.Type != ClassNotify.Shared.Enums.NotificationType.Urgent) { if (_currentLicenseStatus != null) { bool isExp = _currentLicenseStatus.Status == "Expired" || (_currentLicenseStatus.LicensedUntilUtc.HasValue && DateTimeOffset.UtcNow > _currentLicenseStatus.LicensedUntilUtc.Value); if (isExp || !_currentLicenseStatus.CanReceiveNormalNotifications) { _logger.LogWarning("[LocalLicenseGuard] Suppressed normal notification {Id} on expired device (Status={Status}, LicensedUntil={Until:u}).", notification.Id, _currentLicenseStatus.Status, _currentLicenseStatus.LicensedUntilUtc); return; } } } _logger.LogInformation("Received notification from cloud: {Id} (Tenant: {Tenant}) - {Message}", notification.Id, notification.TenantId, notification.Message); // DeliverOrBufferAsync safely delivers to WPF or enqueues into _clientNotificationBuffer. var delivered = await _clientNotificationBuffer.DeliverOrBufferAsync( notification, () => _pipeServer.IsClientConnected, async notif => await _pipeServer.SendNotificationToClientAsync(notif), waitAttempts: 6, delayMsBetweenAttempts: 500); if (delivered) { // Blocker 4 Hardening: Only commit to processed dedupe set AFTER successful live delivery to WPF! _processedNotificationIds.TryAdd(notification.Id, DateTimeOffset.UtcNow); _logger.LogInformation("Notification {Id} successfully delivered to client; recorded in deduplication set.", notification.Id); } else { // If buffered (or send failed), do NOT mark as processed so that catch-up or retry can redeliver if needed! _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); } }); connection.On("CancelNotification", async (notificationId) => { if (string.IsNullOrWhiteSpace(notificationId)) return; _logger.LogInformation("Received CancelNotification for notification {Id}. Forwarding CloseNotification to Client...", notificationId); _clientNotificationBuffer.Remove(notificationId); await _pipeServer.SendCloseNotificationAsync(notificationId); }); // P3 License Lifecycle: Realtime Authoritative Status from Server connection.On("ReceiveLicenseStatus", async (licStatus) => { if (licStatus == null) return; _logger.LogInformation("Received ReceiveLicenseStatus: Status={Status}, Tier={Tier}, RemainingDays={Days}, LicensedUntil={Until:u}", licStatus.Status, licStatus.Tier, licStatus.RemainingDays, licStatus.LicensedUntilUtc); _currentLicenseStatus = licStatus; SaveLicenseLease(licStatus); await _pipeServer.SendLicenseStatusToClientAsync(licStatus); }); connection.On("ClassDisplayNameChanged", async (newClassName) => { _logger.LogInformation("[SignalR] Received ClassDisplayNameChanged push: {Name}", newClassName); if (!string.IsNullOrEmpty(newClassName)) { if (_credentials != null) { _credentials.ClassDisplayName = newClassName; _credManager.SaveCredentials(_credentials); } await _pipeServer.NotifyClassDisplayNameChangedAsync(newClassName); } }); // Dual-Brain Commercialization: Receive Temporary Pairing Mode Activation connection.On("ReceivePairingMode", async (pairingCode, ttlSeconds) => { _logger.LogInformation("[SignalR] Received ReceivePairingMode push: Code={Code}, TTL={TTL}s", pairingCode, ttlSeconds); await _pipeServer.SendPairingModeToClientAsync(pairingCode, ttlSeconds); }); // Turn 115: Server notifies device that teacher binding has updated connection.On("DeviceBindingUpdated", async (newClassName, teacherCount) => { _logger.LogInformation("[SignalR] Received DeviceBindingUpdated push: Name={Name}, Teachers={Teachers}", newClassName, teacherCount); if (!string.IsNullOrEmpty(newClassName)) { if (_credentials != null) { _credentials.ClassDisplayName = newClassName; if (string.IsNullOrEmpty(_credentials.ClassId) || _credentials.ClassId == "待绑定大屏") { _credentials.ClassId = newClassName; } _credManager.SaveCredentials(_credentials); } _boundTeacherCount = teacherCount; _stateRevision++; UpdateIpcClientSnapshot(); await _pipeServer.NotifyClassDisplayNameChangedAsync(newClassName); } }); // GPT Turn 73: Server notifies client that the session has been invalidated (rebind / tenant move) connection.On("DeviceSessionInvalidated", (reason) => { _logger.LogWarning("[SignalR] Server notified DeviceSessionInvalidated (Reason: {Reason}). Triggering fresh rebuild...", reason); _ = Task.Run(async () => { // Wait briefly for local credential writer to flush new token if activation was triggered externally for (int i = 0; i < 15; i++) { var diskCreds = _credManager.LoadCredentials(); if (diskCreds != null && diskCreds.DeviceToken != _credentials?.DeviceToken) { break; } await Task.Delay(200); } await EnsureConnectedAsync($"ServerSessionInvalidated:{reason}", _stoppingCts?.Token ?? CancellationToken.None); }); }); // P2.5 RC1-3 Phase 2: Decoupled Collection & Upload Queue connection.On("GenerateSupportBundle", (cmd) => { if (cmd == null || string.IsNullOrWhiteSpace(cmd.SupportBundleId)) { _logger.LogWarning("Received null or invalid GenerateSupportBundle command"); return; } _logger.LogInformation( "Received GenerateSupportBundle command: SupportBundleId={SupportBundleId}, CorrelationId={CorrelationId}, RequestedAt={RequestedAt:u}, DeadlineAt={DeadlineAt:u}, MaxSizeBytes={MaxSizeBytes}. Enqueueing for background processing...", cmd.SupportBundleId, cmd.CorrelationId, cmd.RequestedAtUtc, cmd.DeadlineAtUtc, cmd.MaxSizeBytes); _supportBundleChannel.Writer.TryWrite(cmd); }); // P2.5 RC1-4 Phase 1: Software Update & Rollback Command connection.On("StartDeviceUpdate", async (cmd) => { await HandleDeviceUpdateAsync(cmd); }); connection.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": DeviceSelfCheckRequestDto? scReq = null; if (!string.IsNullOrWhiteSpace(cmd.Parameters)) { try { scReq = JsonSerializer.Deserialize(cmd.Parameters); } catch { } } var scResult = await ExecuteComprehensiveSelfCheckAsync(scReq); _bundleCollector.SetLatestSelfCheck(scResult); var legacyReport = await ExecuteSelfCheckAsync(); await ForwardHealthReportAsync(legacyReport); resultMessage = $"Self-check completed: overall={scResult.OverallStatus}, checks={scResult.Checks.Count}"; status = scResult.OverallStatus == SelfCheckStatus.Failed ? DeviceCommandStatuses.Failed : DeviceCommandStatuses.Succeeded; resultCode = scResult.OverallStatus == SelfCheckStatus.Failed ? 1 : 0; _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 // 5. Connection Lifecycle (Supervised by ConnectionSupervisor) connection.Reconnecting += error => { _logger.LogWarning(error, "SignalR connection lost. Reconnecting to {Url}...", hubUrl); _isRealtimeReady = false; _realtimeChannelState = "Reconnecting"; _channelDetail = "网络波动,SignalR 正在尝试恢复..."; UpdateIpcClientSnapshot(); return Task.CompletedTask; }; connection.Reconnected += async connectionId => { _logger.LogInformation("SignalR reconnected successfully! ConnectionId: {ConnectionId}", connectionId); try { await RecoverLicenseFromServerAsync(); var hbDto = new DeviceHeartbeatDto { ServiceVersion = typeof(SignalRWorker).Assembly.GetName().Version?.ToString(3) ?? "2.5.0", ClientVersion = "2.5.0", ProtocolVersion = 1, OsVersion = Environment.OSVersion.VersionString, Architecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), ClientProcessAvailable = _pipeServer.IsClientConnected, CorrelationId = $"reconn_{Guid.NewGuid():N}"[..16] }; await connection.InvokeAsync("SendHeartbeatWithReport", hbDto, _stoppingCts?.Token ?? CancellationToken.None); _lastSuccessfulHeartbeatUtc = DateTimeOffset.UtcNow; _isRealtimeReady = true; _realtimeChannelState = "Connected"; _channelDetail = $"实时通道恢复畅通 · 最近心跳: {DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(8)):HH:mm:ss}"; UpdateIpcClientSnapshot(); } catch (Exception ex) { _logger.LogWarning(ex, "[SignalR] Error completing reconnected handshake; triggering supervisor..."); _isRealtimeReady = false; _ = EnsureConnectedAsync("ReconnectedHandshakeFailed", _stoppingCts?.Token ?? CancellationToken.None); } }; connection.Closed += async error => { _logger.LogWarning(error, "SignalR connection closed. Triggering ConnectionSupervisor..."); _isRealtimeReady = false; _realtimeChannelState = "Disconnected"; _channelDetail = "连接已关闭,自愈监督器正在重连..."; UpdateIpcClientSnapshot(); // T76-01 / T76-03: Single reconnection supervisor owner (no multiple conflicting tasks!) _ = EnsureConnectedAsync("ConnectionClosed", _stoppingCts?.Token ?? CancellationToken.None); await Task.CompletedTask; }; return connection; } public async Task EnsureConnectedAsync(string reason, CancellationToken ct) { // T76-03: Try acquiring gate immediately; if another task is already performing reconnect/supervision, return to avoid stampede if (!await _connectionGate.WaitAsync(0, ct)) { _logger.LogDebug("[Supervisor] Connection gate busy; another connection supervisor cycle is already active (Reason: {Reason})", reason); return; } try { // If healthy and not a forced rebind, nothing to do bool isForced = reason == "ForceRebuild" || reason == "LocalCredentialsFileUpdated" || reason == "ClosedLoopCredentialMismatch" || reason == "ServerSessionInvalidated" || reason == "InitialServiceStart"; if (!isForced && IsCurrentConnectionHealthy()) { return; } await RebuildAndConnectWithSupervisionAsync(reason, ct); } finally { _connectionGate.Release(); } } private bool IsCurrentConnectionHealthy() { if (!_isRealtimeReady || _hubConnection == null || _hubConnection.State != HubConnectionState.Connected) { return false; } if (_lastSuccessfulHeartbeatUtc != DateTimeOffset.MinValue && (DateTimeOffset.UtcNow - _lastSuccessfulHeartbeatUtc > TimeSpan.FromSeconds(45))) { return false; // Silence watchdog exceeded } return true; } private async Task RebuildAndConnectWithSupervisionAsync(string reason, CancellationToken ct) { _logger.LogInformation("[Supervisor] Beginning supervised connection rebuild (Reason: {Reason})...", reason); _isRealtimeReady = false; _realtimeChannelState = reason == "LocalCredentialsFileUpdated" || reason == "ServerSessionInvalidated" ? "UpdatingBinding" : "Reconnecting"; _channelDetail = reason == "LocalCredentialsFileUpdated" ? "正在更新班级绑定凭据..." : "正在重新连接云端服务器..."; UpdateIpcClientSnapshot(); // 1. Tear down previous connection cleanly if (_hubConnection != null) { try { await _hubConnection.StopAsync(CancellationToken.None); await _hubConnection.DisposeAsync(); } catch (Exception ex) { _logger.LogDebug(ex, "[Supervisor] Error disposing previous connection during rebuild"); } _hubConnection = null; } // 2. Reload latest credentials from disk or auto-bootstrap var freshCreds = _credManager.LoadCredentials(); if (freshCreds == null || string.IsNullOrEmpty(freshCreds.DeviceId) || string.IsNullOrEmpty(freshCreds.DeviceToken)) { _logger.LogInformation("[Supervisor] Credentials not found on disk. Attempting auto-bootstrap from server..."); var bootRes = await BootstrapDeviceFromServerAsync(ct); if (bootRes.Success) { freshCreds = _credManager.LoadCredentials(); } } if (freshCreds == null || string.IsNullOrEmpty(freshCreds.DeviceId) || string.IsNullOrEmpty(freshCreds.DeviceToken)) { _logger.LogWarning("[Supervisor] Cannot connect: Credentials not found on disk and bootstrap unsuccessful."); _realtimeChannelState = "Disconnected"; _channelDetail = "等待获取大屏凭据..."; UpdateIpcClientSnapshot(); return; } _credentials = freshCreds; // 3. Connect Loop with exponential backoff & jitter (T76-02: initial/repeated failure retry) int attempt = 0; var backoffs = new[] { 1, 2, 5, 10, 20, 30 }; var hubUrl = $"{_serverBaseUrl}/hubs/device"; while (!ct.IsCancellationRequested) { attempt++; try { _logger.LogInformation("[Supervisor] Establishing HubConnection attempt #{Attempt} to {Url}...", attempt, hubUrl); _hubConnection = CreateAndConfigureHubConnection(_credentials, hubUrl); await _hubConnection.StartAsync(ct); // 4. Strict READY protocol (GPT Brain section VIII): // Step A: Recover authoritative license status await RecoverLicenseFromServerAsync(); // Step B: Send initial heartbeat ACK with health metrics var hbDto = new DeviceHeartbeatDto { ServiceVersion = typeof(SignalRWorker).Assembly.GetName().Version?.ToString(3) ?? "2.5.0", ClientVersion = "2.5.0", ProtocolVersion = 1, OsVersion = Environment.OSVersion.VersionString, Architecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), ClientProcessAvailable = _pipeServer.IsClientConnected, CorrelationId = $"ready_{Guid.NewGuid():N}"[..16] }; await _hubConnection.InvokeAsync("SendHeartbeatWithReport", hbDto, ct); _lastSuccessfulHeartbeatUtc = DateTimeOffset.UtcNow; _isRealtimeReady = true; _realtimeChannelState = "Connected"; _channelDetail = $"实时通道畅通 · 最近心跳: {DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(8)):HH:mm:ss}"; _logger.LogInformation("[Supervisor] SignalR session established and fully authenticated (READY) on attempt #{Attempt} for Device={DeviceId}!", attempt, _credentials.DeviceId); UpdateIpcClientSnapshot(); break; } catch (Exception ex) when (!ct.IsCancellationRequested) { _isRealtimeReady = false; _realtimeChannelState = "Reconnecting"; int delaySec = backoffs[Math.Min(attempt - 1, backoffs.Length - 1)]; int jitterMs = Random.Shared.Next(100, 500); _channelDetail = $"连接重试中 ({attempt}次重试,{delaySec}秒后继续)..."; _logger.LogWarning(ex, "[Supervisor] Connection attempt #{Attempt} failed: {Message}. Retrying in {Sec}s...", attempt, ex.Message, delaySec); UpdateIpcClientSnapshot(); await Task.Delay(TimeSpan.FromSeconds(delaySec) + TimeSpan.FromMilliseconds(jitterMs), ct); } } } 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 } } }