using System.IO; using System.IO.Compression; using System.Net; using System.Net.Http; using System.Reflection; using System.Security.Cryptography; using System.Text.Json; using XFEToolBox.Client.Profiles.CrossVersionProfiles; using XFEToolBox.Client.Utilities.Server; using XFEToolBox.Core.Models.Users; using XFEToolBox.Core.Tools; namespace QuickTools.Validation; internal static partial class Program { private static readonly JsonSerializerOptions ReleaseJson = new(JsonSerializerDefaults.Web) { WriteIndented = true }; private static async Task ReleaseOperations(string[] args) { // Never log tokens, authenticated request bodies, or profile contents. try { if (args.Contains("--launch-package")) { string path = Path.GetFullPath(args[Array.IndexOf(args, "--launch-package") + 1]); var manifest = ReadPackageManifest(path); string hash = Convert.ToHexString(SHA256.HashData(await File.ReadAllBytesAsync(path))); var service = typeof(XFEToolBox.Client.Utilities.QuickToolsBridge).Assembly.GetType("XFEToolBox.Client.Utilities.ToolProjectRunService", true)!; var task = (Task)service.GetMethod("BuildPackageAndRunAsync")!.Invoke(null, [path, manifest.Id, manifest.Version, hash, false, CancellationToken.None, null])!; await task; object result = task.GetType().GetProperty("Result")!.GetValue(task)!; Console.WriteLine(JsonSerializer.Serialize(result, ReleaseJson)); return (bool)result.GetType().GetProperty("Success")!.GetValue(result)! ? 0 : 1; } var catalog = await ClientSession.Requester.Request("catalogTools"); Ensure(catalog.StatusCode == HttpStatusCode.OK && catalog.Result is not null, "Catalog unavailable: " + catalog.StatusCode); var targets = QuickToolIds(); Console.WriteLine(JsonSerializer.Serialize(new { categories = catalog.Result!.Select(t => t.Category).Distinct().Order().ToArray(), tools = catalog.Result!.Where(t => targets.Contains(t.Id)).Select(t => new { t.Id, t.Name, t.LatestVersion, t.Category }) }, ReleaseJson)); ClientSession.Requester.Session = SystemProfile.LoginSession; var user = await ClientSession.Requester.Request("currentUser"); Ensure(user.StatusCode == HttpStatusCode.OK && user.Result is not null, "Existing login unavailable: " + user.StatusCode); Console.WriteLine("Existing account verified; administrator=" + user.Result!.IsAdministrator); var managed = await ClientSession.Requester.Request("adminTools"); Ensure(managed.StatusCode == HttpStatusCode.OK && managed.Result is not null, "Cannot inspect existing versions: " + managed.StatusCode); Console.WriteLine(JsonSerializer.Serialize(managed.Result!.Where(t => targets.Contains(t.Manifest.Id)).Select(t => new { t.Manifest.Id, t.Manifest.Version, t.Package.Published, t.Package.Sha256 }), ReleaseJson)); if (!args.Contains("--publish-verified")) return 0; Ensure(user.Result.IsAdministrator, "Publishing requires the logged-in administrator account."); string directory = Path.GetFullPath(args[Array.IndexOf(args, "--publish-verified") + 1]); // Explicit per-package UI evidence is required in addition to the automated regression report. using var gate = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(directory, "verification.json"))); Ensure(gate.RootElement.GetProperty("automatedFailures").GetInt32() == 0, "Automated tests must pass before publication."); var checks = gate.RootElement.GetProperty("tools").EnumerateArray().ToDictionary(t => t.GetProperty("id").GetString()!); var packages = targets.Select(id => Directory.GetFiles(Path.Combine(directory, "Packages"), id + "-*.xfetool").Single()).ToArray(); foreach (var path in packages) { var manifest = ReadPackageManifest(path); string hash = Convert.ToHexString(SHA256.HashData(await File.ReadAllBytesAsync(path))); Ensure(checks.TryGetValue(manifest.Id, out var check) && check.GetProperty("opened").GetBoolean() && check.GetProperty("functional").GetBoolean() && check.GetProperty("sha256").GetString()!.Equals(hash, StringComparison.OrdinalIgnoreCase), "Missing exact-package verification: " + manifest.Id); Ensure(catalog.Result!.Any(t => t.Category == manifest.Category), "Category does not exist: " + manifest.Category); var existing = managed.Result!.SingleOrDefault(t => t.Manifest.Id == manifest.Id && t.Manifest.Version == manifest.Version); Ensure(existing is null || (existing.Package.Published && existing.Package.Sha256.Equals(hash, StringComparison.OrdinalIgnoreCase)), "Version collision: " + manifest.Id); } var published = new List(); using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(2), BaseAddress = new Uri(ClientSession.ApiAddress.TrimEnd('/') + "/") }; foreach (var path in packages) { var manifest = ReadPackageManifest(path); byte[] bytes = await File.ReadAllBytesAsync(path); string hash = Convert.ToHexString(SHA256.HashData(bytes)); if (!managed.Result!.Any(t => t.Manifest.Id == manifest.Id && t.Manifest.Version == manifest.Version)) { var upload = await ClientSession.Requester.Request("adminUploadTool", Convert.ToBase64String(bytes), true, false); Ensure(upload.StatusCode is HttpStatusCode.OK or HttpStatusCode.Created && upload.Result is not null, "Publish failed: " + manifest.Id + " / " + upload.StatusCode + " / " + upload.Message); } var details = await ClientSession.Requester.Request("catalogToolDetails", manifest.Id); Ensure(details.StatusCode == HttpStatusCode.OK && details.Result is not null, "Public details unavailable"); Equal(manifest.Version, details.Result!.Manifest.Version); Equal(manifest.Category, details.Result.Manifest.Category); var version = details.Result.Versions.Single(v => v.Version == manifest.Version); Ensure(version.Published && version.Sha256.Equals(hash, StringComparison.OrdinalIgnoreCase), "Online hash/publication mismatch"); var url = new Uri(new Uri(ClientSession.ApiAddress.TrimEnd('/') + "/"), version.DownloadUrl); Ensure(url.Scheme == "https" && url.Host == new Uri(ClientSession.ApiAddress).Host, "Unexpected download origin"); using var download = new MemoryStream(); await new ToolCatalogClient(http).DownloadPackageAsync(version, download); var downloaded = download.ToArray(); Equal(hash, Convert.ToHexString(SHA256.HashData(downloaded))); string downloadPath = Path.Combine(directory, "online", Path.GetFileName(path)); Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)!); await File.WriteAllBytesAsync(downloadPath, downloaded); var fresh = await ClientSession.Requester.Request("catalogTools"); var item = fresh.Result!.Single(t => t.Id == manifest.Id); Equal(manifest.Version, item.LatestVersion); Equal(manifest.Category, item.Category); using var zip = ZipFile.OpenRead(path); using var icon = new MemoryStream(); using (var stream = zip.GetEntry(manifest.Icon!)!.Open()) await stream.CopyToAsync(icon); Ensure(item.IconDataUrl is not null && Convert.FromBase64String(item.IconDataUrl[(item.IconDataUrl.IndexOf(',') + 1)..]).SequenceEqual(icon.ToArray()), "Online icon differs"); published.Add(new { manifest.Id, manifest.Name, manifest.Version, manifest.Category, sha256 = hash, published = true, downloadedHashVerified = true, iconVerified = true }); await File.WriteAllTextAsync(Path.Combine(directory, "publication.json"), JsonSerializer.Serialize(published, ReleaseJson)); Console.WriteLine("PUBLISHED AND VERIFIED " + manifest.Id + " " + manifest.Version); } return 0; } catch (Exception ex) { Console.Error.WriteLine(ex.Message); return 1; } } private static string[] QuickToolIds() => XFEToolBox.QuickTools.QuickToolCatalog.All.Select(t => "xfestudio." + t.Id).ToArray(); private static ToolPackageManifest ReadPackageManifest(string path) { using var zip = ZipFile.OpenRead(path); using var entry = zip.GetEntry("manifest.json")!.Open(); return JsonSerializer.Deserialize(entry, ReleaseJson)!; } }