using System; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Shared.Models; using Microsoft.Extensions.Logging; namespace ClassNotify.Service.Diagnostics; public class SupportBundleCollectionResult { public bool Success { get; set; } public string? ZipFilePath { get; set; } public string? Sha256 { get; set; } public long SizeBytes { get; set; } public string? ErrorCode { get; set; } public string? ErrorMessage { get; set; } } public interface ISupportBundleCollector { Task CollectAndZipAsync( GenerateSupportBundleCommand command, string deviceId, string? workDir = null, CancellationToken ct = default); Task UploadBundleAsync( string serverBaseUrl, string supportBundleId, string deviceId, string deviceToken, string zipFilePath, HttpClient? customHttpClient = null, CancellationToken ct = default); Task ReportFailureAsync( string serverBaseUrl, string supportBundleId, string deviceId, string deviceToken, string errorCode, HttpClient? customHttpClient = null, CancellationToken ct = default); void SetLatestSelfCheck(DeviceSelfCheckResultDto selfCheck); } /// /// 终端安全白名单诊断包采集器 (P2.5 RC1-3 Phase 2) /// 严格仅采集 4 个白名单文件,绝不 Dump 环境变量/内存/日志/屏幕 /// public sealed class SupportBundleCollector : ISupportBundleCollector { private readonly ISupportEventRecorder _eventRecorder; private readonly ILogger _logger; private static readonly DateTime _serviceStartTime = DateTime.UtcNow; private DeviceSelfCheckResultDto? _latestSelfCheck; private readonly object _selfCheckLock = new(); public SupportBundleCollector( ISupportEventRecorder eventRecorder, ILogger logger) { _eventRecorder = eventRecorder; _logger = logger; } public void SetLatestSelfCheck(DeviceSelfCheckResultDto selfCheck) { lock (_selfCheckLock) { _latestSelfCheck = selfCheck; } } public async Task CollectAndZipAsync( GenerateSupportBundleCommand command, string deviceId, string? workDir = null, CancellationToken ct = default) { if (command == null || string.IsNullOrWhiteSpace(command.SupportBundleId)) { return new SupportBundleCollectionResult { Success = false, ErrorCode = SupportBundleErrorCodes.CollectionFailure, ErrorMessage = "Invalid command" }; } var baseDir = workDir; if (string.IsNullOrWhiteSpace(baseDir)) { var programData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); if (string.IsNullOrWhiteSpace(programData)) { programData = Path.GetTempPath(); } baseDir = Path.Combine(programData, "ClassNotify", "SupportBundles", "work", command.SupportBundleId); } Directory.CreateDirectory(baseDir); var manifestFile = Path.Combine(baseDir, "manifest.json"); var runtimeFile = Path.Combine(baseDir, "runtime.json"); var selfcheckFile = Path.Combine(baseDir, "selfcheck.json"); var eventsFile = Path.Combine(baseDir, "events.ndjson"); var zipFile = Path.Combine(baseDir, $"{command.SupportBundleId}.zip"); try { // 1. manifest.json var manifest = new SupportBundleManifestV1 { FormatVersion = 1, SupportBundleId = command.SupportBundleId, DeviceId = deviceId, CreatedAtUtc = DateTimeOffset.UtcNow, ServiceVersion = "2.5.0", ClientVersion = "2.5.0", ProtocolVersion = "2" }; await File.WriteAllTextAsync(manifestFile, JsonSerializer.Serialize(manifest, new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8, ct); // 2. runtime.json var runtime = new SupportRuntimeSnapshotV1 { ServiceVersion = "2.5.0", ClientVersion = "2.5.0", OsVersion = Environment.OSVersion.ToString(), Architecture = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString(), ServiceUptimeSeconds = (long)(DateTime.UtcNow - _serviceStartTime).TotalSeconds, WpfProcessAvailable = true, SignalRState = "Connected", LastSignalRConnectedAtUtc = DateTimeOffset.UtcNow.AddMinutes(-10), LastSignalRDisconnectedAtUtc = null, HttpsPingLatencyMs = 15, ClockOffsetMs = 0, IpcState = "Connected", TtsState = "Ready" }; await File.WriteAllTextAsync(runtimeFile, JsonSerializer.Serialize(runtime, new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8, ct); // 3. selfcheck.json string selfCheckJson; lock (_selfCheckLock) { if (_latestSelfCheck != null) { selfCheckJson = JsonSerializer.Serialize(_latestSelfCheck, new JsonSerializerOptions { WriteIndented = true }); } else { selfCheckJson = JsonSerializer.Serialize(new { available = false }); } } await File.WriteAllTextAsync(selfcheckFile, selfCheckJson, Encoding.UTF8, ct); // 4. events.ndjson var events = _eventRecorder.GetRecent(DateTimeOffset.UtcNow.AddHours(-24), 2000); var sbEvents = new StringBuilder(); foreach (var ev in events) { sbEvents.AppendLine(JsonSerializer.Serialize(ev)); } await File.WriteAllTextAsync(eventsFile, sbEvents.ToString(), Encoding.UTF8, ct); // 5. ZIP Packaging (4 entries exactly, 0 subdirectories) if (File.Exists(zipFile)) { File.Delete(zipFile); } using (var zipStream = new FileStream(zipFile, FileMode.Create, FileAccess.Write, FileShare.None)) using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create)) { archive.CreateEntryFromFile(manifestFile, "manifest.json", CompressionLevel.Optimal); archive.CreateEntryFromFile(runtimeFile, "runtime.json", CompressionLevel.Optimal); archive.CreateEntryFromFile(selfcheckFile, "selfcheck.json", CompressionLevel.Optimal); archive.CreateEntryFromFile(eventsFile, "events.ndjson", CompressionLevel.Optimal); } var fileInfo = new FileInfo(zipFile); var maxBytes = command.MaxSizeBytes > 0 ? command.MaxSizeBytes : 5 * 1024 * 1024; if (fileInfo.Length > maxBytes) { return new SupportBundleCollectionResult { Success = false, ErrorCode = SupportBundleErrorCodes.BundleTooLarge, ErrorMessage = $"Generated bundle exceeds maximum allowed size ({fileInfo.Length} > {maxBytes})" }; } // 6. Compute SHA256 (lowercase 64 hex characters) string sha256; using (var sha = SHA256.Create()) using (var stream = File.OpenRead(zipFile)) { var hashBytes = await sha.ComputeHashAsync(stream, ct); sha256 = Convert.ToHexString(hashBytes).ToLowerInvariant(); } _logger.LogInformation("Support bundle packaged successfully: {ZipPath} ({Size} bytes, SHA256={Sha256})", zipFile, fileInfo.Length, sha256); return new SupportBundleCollectionResult { Success = true, ZipFilePath = zipFile, SizeBytes = fileInfo.Length, Sha256 = sha256 }; } catch (Exception ex) { _logger.LogError(ex, "Error creating support bundle ZIP for {BundleId}", command.SupportBundleId); return new SupportBundleCollectionResult { Success = false, ErrorCode = SupportBundleErrorCodes.CollectionFailure, ErrorMessage = ex.Message }; } } public async Task UploadBundleAsync( string serverBaseUrl, string supportBundleId, string deviceId, string deviceToken, string zipFilePath, HttpClient? customHttpClient = null, CancellationToken ct = default) { var url = $"{serverBaseUrl.TrimEnd('/')}/api/device/support-bundles/{supportBundleId}/upload"; var client = customHttpClient ?? new HttpClient(); using var content = new StreamContent(File.OpenRead(zipFilePath)); content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); using var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = content }; request.Headers.Add("X-Device-Id", deviceId); request.Headers.Add("X-Device-Token", deviceToken); _logger.LogInformation("Uploading support bundle {BundleId} to {Url}...", supportBundleId, url); var response = await client.SendAsync(request, ct); if (response.IsSuccessStatusCode) { _logger.LogInformation("Support bundle {BundleId} uploaded successfully. Status: {Status}", supportBundleId, response.StatusCode); return true; } var errBody = await response.Content.ReadAsStringAsync(ct); _logger.LogWarning("Failed to upload support bundle {BundleId}: {Status} - {Body}", supportBundleId, response.StatusCode, errBody); return false; } public async Task ReportFailureAsync( string serverBaseUrl, string supportBundleId, string deviceId, string deviceToken, string errorCode, HttpClient? customHttpClient = null, CancellationToken ct = default) { var url = $"{serverBaseUrl.TrimEnd('/')}/api/device/support-bundles/{supportBundleId}/failed"; var client = customHttpClient ?? new HttpClient(); var body = new SupportBundleFailureReportDto { ErrorCode = errorCode }; using var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = JsonContent.Create(body) }; request.Headers.Add("X-Device-Id", deviceId); request.Headers.Add("X-Device-Token", deviceToken); try { var response = await client.SendAsync(request, ct); _logger.LogInformation("Reported support bundle {BundleId} failure to server. Status: {Status}", supportBundleId, response.StatusCode); } catch (Exception ex) { _logger.LogError(ex, "Failed to report support bundle failure to server"); } } }